TypeScript
refactor(mobile): terminal lifecycle runs in a session store, not screen effects (#25071)
Julius Marminge5786e12981f8
diff --git a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsxindex bfd89bfb683..601d415ccfc 100644--- a/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx+++ b/apps/mobile/src/features/terminal/NativeTerminalSurface.tsx@@ -1,5 +1,13 @@import type { TerminalOutputState } from "@t3tools/client-runtime/state/terminal";-import { memo, useCallback, useEffect, useRef, useState } from "react";+import {+ memo,+ useCallback,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+ type Ref,+} from "react";import {Pressable,ScrollView,@@ -38,7 +46,13 @@ interface TerminalResizeEvent {readonly rows: number;}+export interface TerminalSurfaceHandle {+ /** The text fallback focuses its input; the native view follows `keyboardFocusRequest`. */+ readonly focusKeyboard: () => void;+}+interface TerminalSurfaceProps extends ViewProps {+ readonly ref?: Ref<TerminalSurfaceHandle>;readonly terminalKey: string;readonly buffer: string | null;readonly output: TerminalOutputState | null;@@ -71,9 +85,10 @@ function estimateGridSize(input: {};}-const FallbackTerminalSurface = memo(function FallbackTerminalSurface(- props: ReadyTerminalSurfaceProps,-) {+const FallbackTerminalSurface = memo(function FallbackTerminalSurface({+ ref,+ ...props+}: ReadyTerminalSurfaceProps) {const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;const inputRef = useRef<TextInputInstance>(null);const { themeAppearance, themeId } = useAppearancePreferences();@@ -89,15 +104,14 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(props.onResize(estimateGridSize({ width, height, fontSize }));};- useEffect(() => {- if (!props.readOnly && (props.keyboardFocusRequest ?? 0) > 0) {+ useImperativeHandle(ref, () => ({+ focusKeyboard: () => {+ if (props.readOnly) return;+ // Blur first so a focused input still raises the keyboard; focus lands after the blur commits.inputRef.current?.blur();- const focusFrame = requestAnimationFrame(() => inputRef.current?.focus());- return () => cancelAnimationFrame(focusFrame);- }-- return undefined;- }, [props.keyboardFocusRequest, props.readOnly]);+ requestAnimationFrame(() => inputRef.current?.focus());+ },+ }));return (<Viewdiff --git a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsxindex bffcb221772..de0c090f939 100644--- a/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx+++ b/apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx@@ -12,14 +12,17 @@ import { SymbolView } from "../../components/ui/AppSymbol";import { AppBar } from "../../components/ui/AppBar";import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { useAtomMount } from "@effect/atom-react";+import { useMemo, useRef, useState, useSyncExternalStore } from "react";import { Platform, Pressable, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";import { AppText as Text } from "../../components/ui/AppText";import { TerminalContextSheet } from "./TerminalContextSheet";import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule";import * as Clipboard from "expo-clipboard";+import * as Option from "effect/Option";import * as Schema from "effect/Schema";+import { AsyncResult } from "effect/reactivity";import {KeyboardController,KeyboardEvents,@@ -43,6 +46,7 @@ import { useEnvironmentPresentation } from "../../state/presentation";import { terminalEnvironment } from "../../state/terminal";import { environmentSession, readEnvironmentScope } from "../../state/session";import { useEnvironmentQuery } from "../../state/query";+import { appAtomRegistry } from "../../state/atom-registry";import { useAtomCommand } from "../../state/use-atom-command";import { uuidv4 } from "../../lib/uuid";import { useServerConfigs } from "../../state/entities";@@ -61,14 +65,10 @@ import {import { useThreadSelection } from "../../state/use-thread-selection";import { useSelectedThreadProjection } from "../../state/use-thread-detail";import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";-import { TerminalSurface } from "./NativeTerminalSurface";+import { TerminalSurface, type TerminalSurfaceHandle } from "./NativeTerminalSurface";import { getMobileTerminalTheme } from "./terminalTheme";import { terminalDebugLog } from "./terminalDebugLog";-import {- getTerminalBufferReplayKey,- getTerminalSurfaceReplayBuffer,- TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,-} from "./terminalBufferReplay";+import { useTerminalExitNavigation } from "./useTerminalExitNavigation";import {useInitialTerminalLaunchLocation,takePendingTerminalLaunch,@@ -91,8 +91,6 @@ import {} from "./terminalInput";import { createTerminalPasteSession } from "./terminalPaste";import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";-import { useTerminalGridSync } from "./useTerminalGridSync";-import { useTerminalLifecycle } from "./useTerminalLifecycle";function TerminalHeader(props: {readonly subtitle: string;@@ -252,46 +250,166 @@ type ThreadTerminalRouteScreenProps = StaticScreenProps<{readonly terminalId?: string;}>;+type ThreadSelection = ReturnType<typeof useThreadSelection>;++function useTerminalAccess(environmentId: EnvironmentId | null) {+ const session = useEnvironmentQuery(+ environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),+ );+ const isAuthenticated = session.error === null && session.data?.authenticated === true;+ return {+ session,+ isAuthenticated,+ canOperate:+ isAuthenticated &&+ session.data !== null &&+ sessionGrantsScope(session.data, AuthTerminalOperateScope),+ canRead:+ isAuthenticated &&+ session.data !== null &&+ sessionGrantsScope(session.data, AuthTerminalReadScope),+ };+}+export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) {+ const connectionsReady = useConnectionsReady();+ const params = props.route.params;+ const selection = useThreadSelection();+ const { selectedThread } = selection;+ const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);+ const routeEnvironmentId = routeEnvironmentIdRaw+ ? EnvironmentId.make(routeEnvironmentIdRaw)+ : null;+ const access = useTerminalAccess(routeEnvironmentId);+ const knownSessions = useKnownTerminalSessions({+ environmentId: selectedThread?.environmentId ?? null,+ threadId: selectedThread?.id ?? null,+ });+ const requestedTerminalId = firstRouteParam(params.terminalId);+ // A route without a terminal shows the thread's running one. The choice is+ // made once, from the first session list that has one, so the terminal shown+ // does not change under the user as sessions come and go.+ const [bootstrapTerminalId, setBootstrapTerminalId] = useState<string | null>(null);+ const runningSession = knownSessions.sessions+ ? (pickRunningTerminalSessionForBootstrap(knownSessions.sessions) ??+ (access.canOperate ? null : (knownSessions.sessions[0] ?? null)))+ : null;+ if (+ requestedTerminalId === null &&+ bootstrapTerminalId === null &&+ runningSession !== null &&+ runningSession.target.terminalId !== DEFAULT_TERMINAL_ID+ ) {+ setBootstrapTerminalId(runningSession.target.terminalId);+ }+ const explicitTerminalId = requestedTerminalId ?? bootstrapTerminalId;+ const terminalId = explicitTerminalId ?? DEFAULT_TERMINAL_ID;++ if (!selectedThread) {+ if (!connectionsReady) {+ return <LoadingScreen message="Opening terminal…" />;+ }++ return (+ <View className="flex-1 bg-screen">+ <EmptyState+ title="Thread unavailable"+ detail="This terminal route needs an active thread and workspace."+ />+ </View>+ );+ }++ return (+ <ThreadTerminal+ key={`${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`}+ params={params}+ routeEnvironmentId={routeEnvironmentId}+ selection={selection}+ thread={selectedThread}+ terminalId={terminalId}+ hasExplicitTerminalId={explicitTerminalId !== null}+ access={access}+ knownSessions={knownSessions}+ />+ );+}++function readLiveTerminalSessions(+ environmentId: EnvironmentId,+ threadId: ThreadId,+): ReadonlyArray<TerminalMenuSession> {+ if (!readEnvironmentScope(environmentId, AuthTerminalReadScope)) return [];+ const result = appAtomRegistry.get(terminalEnvironment.metadata({ environmentId, input: null }));+ const summaries = Option.getOrElse(AsyncResult.value(result), () => []);+ return summaries+ .filter((summary) => summary.threadId === threadId)+ .map((summary) => ({+ terminalId: summary.terminalId,+ cwd: summary.cwd,+ status: summary.status,+ hasRunningSubprocess: summary.hasRunningSubprocess,+ displayLabel: resolveTerminalSessionLabel(summary.terminalId, summary),+ updatedAt: summary.updatedAt,+ }));+}++// `useKeyboardState` only flips on willShow and didHide; the accessory must+// leave as soon as the keyboard starts hiding, so it follows the will-events.+let keyboardShowing = KeyboardController.isVisible();+function subscribeKeyboardShowing(onChange: () => void) {+ keyboardShowing = KeyboardController.isVisible();+ const willShow = KeyboardEvents.addListener("keyboardWillShow", () => {+ keyboardShowing = true;+ onChange();+ });+ const willHide = KeyboardEvents.addListener("keyboardWillHide", () => {+ keyboardShowing = false;+ onChange();+ });+ return () => {+ willShow.remove();+ willHide.remove();+ };+}+const getKeyboardShowing = () => keyboardShowing;++function ThreadTerminal(props: {+ readonly params: ThreadTerminalRouteScreenProps["route"]["params"];+ readonly routeEnvironmentId: EnvironmentId | null;+ readonly selection: ThreadSelection;+ readonly thread: NonNullable<ThreadSelection["selectedThread"]>;+ readonly terminalId: string;+ readonly hasExplicitTerminalId: boolean;+ readonly access: ReturnType<typeof useTerminalAccess>;+ readonly knownSessions: ReturnType<typeof useKnownTerminalSessions>;+}) {+ const { params, routeEnvironmentId, thread: selectedThread, terminalId } = props;+ const { selectedThreadProject, selectedEnvironmentConnection } = props.selection;+ const {+ session: terminalSession,+ isAuthenticated,+ canOperate: canOperateTerminal,+ canRead: canReadTerminal,+ } = props.access;+ const {+ sessions: knownSessions,+ isPending: sessionsPending,+ error: sessionsError,+ } = props.knownSessions;const insets = useSafeAreaInsets();const nativeColumnMetrics = useNativeColumnLayoutMetrics();const navigation = useNavigation();const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");- const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");- const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close");- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");- const connectionsReady = useConnectionsReady();- const params = props.route.params;- const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =- useThreadSelection();const selectedThreadDetail = useSelectedThreadProjection();const selectedThreadDetailWorktreePath =selectedThreadDetail?.projection.thread.worktreePath ?? null;- const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);const routeThreadIdRaw = firstRouteParam(params.threadId);- const routeEnvironmentId = routeEnvironmentIdRaw- ? EnvironmentId.make(routeEnvironmentIdRaw)- : null;const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;- const terminalSession = useEnvironmentQuery(- routeEnvironmentId === null ? null : environmentSession.sessionStateAtom(routeEnvironmentId),- );- const isAuthenticated =- terminalSession.error === null && terminalSession.data?.authenticated === true;- const canOperateTerminal =- isAuthenticated &&- terminalSession.data !== null &&- sessionGrantsScope(terminalSession.data, AuthTerminalOperateScope);- const canReadTerminal =- isAuthenticated &&- terminalSession.data !== null &&- sessionGrantsScope(terminalSession.data, AuthTerminalReadScope);const environment = useEnvironmentPresentation(routeEnvironmentId);const isEnvironmentReady = environment.presentation?.connection.phase === "connected";- const requestedTerminalId = firstRouteParam(params.terminalId);- const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;// Any new positive value triggers capture, even on remount. Pass one only while pending and keep increasing it.const captureSequenceRef = useRef(0);const [captureRequest, setCaptureRequest] = useState(0);@@ -309,120 +427,81 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)themeVariables,} = useAppearancePreferences();const fontSize = appearance.terminalFontSize;- const cachedRouteGridSize =- routeEnvironmentId && routeThreadId- ? getCachedTerminalGridSize({- environmentId: routeEnvironmentId,- threadId: routeThreadId,- terminalId,- })- : null;- const {- sessions: knownSessions,- isPending: sessionsPending,- error: sessionsError,- } = useKnownTerminalSessions({- environmentId: selectedThread?.environmentId ?? null,- threadId: selectedThread?.id ?? null,- });- const runningSession = useMemo(- () =>- pickRunningTerminalSessionForBootstrap(knownSessions ?? []) ??- (canOperateTerminal ? null : (knownSessions?.[0] ?? null)),- [canOperateTerminal, knownSessions],- );+ const terminalKey = `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`;const activeKnownSession = useMemo(() => knownSessions?.find((session) => session.target.terminalId === terminalId) ?? null,[knownSessions, terminalId],);- const hasTerminalTarget = requestedTerminalId !== null || activeKnownSession !== null;- const launchTarget = useMemo(+ const hasTerminalTarget = props.hasExplicitTerminalId || activeKnownSession !== null;+ const [pendingLaunch] = useState<PendingTerminalLaunch | null>(() =>+ takePendingTerminalLaunch({+ environmentId: selectedThread.environmentId,+ threadId: selectedThread.id,+ terminalId,+ }),+ );+ const [initialAttachGridSize] = useState(() =>- selectedThread- ? {- environmentId: selectedThread.environmentId,- threadId: selectedThread.id,+ (routeEnvironmentId && routeThreadId+ ? getCachedTerminalGridSize({+ environmentId: routeEnvironmentId,+ threadId: routeThreadId,terminalId,- }- : null,- [selectedThread, terminalId],+ })+ : null) ?? { cols: DEFAULT_TERMINAL_COLS, rows: DEFAULT_TERMINAL_ROWS },);- const launchTargetKey = launchTarget- ? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`- : null;- const [pendingLaunchEntry, setPendingLaunchEntry] = useState<{- readonly key: string | null;- readonly launch: PendingTerminalLaunch | null;- }>(() => ({- key: launchTargetKey,- launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),- }));- const pendingLaunch =- pendingLaunchEntry.key === launchTargetKey ? pendingLaunchEntry.launch : null;- const hasResolvedPendingLaunch = pendingLaunchEntry.key === launchTargetKey;- const [initialAttachGridEntry, setInitialAttachGridEntry] = useState(() => ({- key: launchTargetKey,- size: cachedRouteGridSize ?? {- cols: DEFAULT_TERMINAL_COLS,- rows: DEFAULT_TERMINAL_ROWS,- },- }));- const initialAttachGridSize =- initialAttachGridEntry.key === launchTargetKey ? initialAttachGridEntry.size : null;- const [lastGridSize, setLastGridSize] = useState(- cachedRouteGridSize ?? {- cols: DEFAULT_TERMINAL_COLS,- rows: DEFAULT_TERMINAL_ROWS,- },+ const [pasteSession] = useState(createTerminalPasteSession);+ const exitNavigation = useTerminalExitNavigation({+ environmentId: String(selectedThread.environmentId),+ threadId: String(selectedThread.id),+ readFallbackTerminalId: () =>+ previousLiveTerminalId({+ sessions: readLiveTerminalSessions(selectedThread.environmentId, selectedThread.id),+ exitedTerminalId: terminalId,+ }),+ });+ const [terminalSessionDriver] = useState(() =>+ terminalEnvironment.createSession({+ target: {+ environmentId: selectedThread.environmentId,+ threadId: selectedThread.id,+ terminalId,+ },+ gridSize: initialAttachGridSize,+ initialInput: pendingLaunch?.initialInput,+ canOperate: () =>+ readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope),+ onExit: exitNavigation.exited,+ onLiveChange: (live) => {+ if (live) exitNavigation.restarted();+ pasteSession.reset(live);+ },+ debugLog: terminalDebugLog,+ }),);+ const surfaceRef = useRef<TerminalSurfaceHandle>(null);const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);- const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);- const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);- const firstNonEmptyBufferLoggedRef = useRef(false);- const lastBufferReplayKeyRef = useRef<string | null>(null);- const sentInitialInputKeyRef = useRef<string | null>(null);- const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);- const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);- const [pendingModifierState, setPendingModifierState] = useState<{- readonly terminalId: string;- readonly value: PendingModifier | null;- }>({- terminalId,- value: null,- });- const shouldRedirectToRunningTerminal =- requestedTerminalId === null &&- runningSession !== null &&- runningSession.target.terminalId !== terminalId;+ const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);const launchLocation = useInitialTerminalLaunchLocation({- targetKey: launchTargetKey,+ targetKey: terminalKey,pendingLaunch,- hasResolvedPendingLaunch,isAuthenticated,canRead: canReadTerminal,canOperate: canOperateTerminal,hasLoadedSessions: knownSessions !== null,- location:- selectedThread && selectedThreadProject?.workspaceRoot- ? {- terminalLocation: activeKnownSession?.state.summary ?? null,- activeSessionLocation: activeKnownSession?.state.summary ?? null,- workspaceRoot: selectedThreadProject.workspaceRoot,- threadShellWorktreePath: selectedThread.worktreePath ?? null,- threadDetailWorktreePath: selectedThreadDetailWorktreePath,- }- : null,+ location: selectedThreadProject?.workspaceRoot+ ? {+ terminalLocation: activeKnownSession?.state.summary ?? null,+ activeSessionLocation: activeKnownSession?.state.summary ?? null,+ workspaceRoot: selectedThreadProject.workspaceRoot,+ threadShellWorktreePath: selectedThread.worktreePath ?? null,+ threadDetailWorktreePath: selectedThreadDetailWorktreePath,+ }+ : null,});const terminalAttachInput = useMemo(() =>- selectedThread !== null &&- launchLocation !== null &&- hasResolvedPendingLaunch &&- initialAttachGridSize !== null &&- hasResolvedFontPreference &&- hasMeasuredSurface &&- isEnvironmentReady &&- !shouldRedirectToRunningTerminal+ launchLocation !== null && hasResolvedFontPreference && isEnvironmentReady? {threadId: selectedThread.id,terminalId,@@ -435,107 +514,39 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)}: null,[- hasMeasuredSurface,hasResolvedFontPreference,- hasResolvedPendingLaunch,initialAttachGridSize,isEnvironmentReady,launchLocation,pendingLaunch,- selectedThread,- shouldRedirectToRunningTerminal,+ selectedThread.id,terminalId,],);- const observingTerminal =- !canOperateTerminal && canReadTerminal && selectedThread !== null && hasTerminalTarget;+ const observingTerminal = !canOperateTerminal && canReadTerminal && hasTerminalTarget;const streamingOutput = supportsNativeTerminalOutput();const terminal = useAttachedTerminalSession({materializeBuffer: !streamingOutput,- environmentId: selectedThread?.environmentId ?? null,+ environmentId: selectedThread.environmentId,terminal: canOperateTerminal? terminalAttachInput: observingTerminal? { threadId: selectedThread.id, terminalId }: null,});- const terminalKey = selectedThread- ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`- : terminalId;- useTerminalGridSync({- environmentId: selectedThread?.environmentId ?? null,- threadId: selectedThread?.id ?? null,- terminalId,- canOperate: canOperateTerminal,- terminal,- size: lastGridSize,- resize: resizeTerminal,- });- const bufferReplayKey = useMemo(- () => getTerminalBufferReplayKey({ terminalKey, fontSize }),- [fontSize, terminalKey],+ useAtomMount(+ terminalSessionDriver.driver(+ canOperateTerminal+ ? terminalAttachInput === null+ ? null+ : { kind: "attached", input: terminalAttachInput }+ : observingTerminal+ ? { kind: "observing" }+ : null,+ ),);- if (lastBufferReplayKeyRef.current === null) {- lastBufferReplayKeyRef.current = bufferReplayKey;- }- const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({- buffer: terminal.buffer,- replayKey: bufferReplayKey,- readyReplayKey: readyBufferReplayKey,- });const isRunning = terminal.status === "running" || terminal.status === "starting";- const pendingExitNavigationRef = useRef<string | null>(null);-- useEffect(() => {- terminalDebugLog("surface:props", {- terminalKey,- atomBufferLen: terminal.buffer.length,- surfaceBufferLen: terminalSurfaceBuffer.length,- replayKey: bufferReplayKey,- readyReplayKey: readyBufferReplayKey,- status: terminal.status,- version: terminal.version,- });- }, [- bufferReplayKey,- readyBufferReplayKey,- terminal.buffer.length,- terminal.status,- terminal.version,- terminalKey,- terminalSurfaceBuffer.length,- ]);-- useEffect(() => {- terminalDebugLog("session:status", {- terminalKey,- status: terminal.status,- error: terminal.error,- summary: terminal.summary?.cwd ?? null,- bufferLen: terminal.buffer.length,- version: terminal.version,- });- }, [- terminal.buffer.length,- terminal.error,- terminal.status,- terminal.summary?.cwd,- terminal.version,- terminalKey,- ]);-- useEffect(() => {- if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {- return;- }- firstNonEmptyBufferLoggedRef.current = true;- terminalDebugLog("session:first-nonempty-buffer", {- terminalKey,- length: terminal.buffer.length,- preview: terminal.buffer.slice(0, 160),- });- }, [terminal.buffer, terminal.buffer.length, terminalKey]);const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;const serverConfigs = useServerConfigs();const hostOs =@@ -550,8 +561,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps));const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);- const pendingModifier =- pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;const headerSubtitle = selectedThreadProject?.title ?? "";const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {const modifierActions: ReadonlyArray<TerminalToolbarAction> =@@ -585,6 +594,14 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)height: state.height,isVisible: state.isVisible,}));+ const keyboardShowing = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing);+ // The accessory follows the keyboard, except that the dismiss and show+ // buttons flip it ahead of the keyboard animation.+ const [accessory, setAccessory] = useState({ keyboardShowing, dismissed: false });+ if (accessory.keyboardShowing !== keyboardShowing) {+ setAccessory({ keyboardShowing, dismissed: !keyboardShowing });+ }+ const isAccessoryDismissed = accessory.dismissed;const isAccessoryVisible = canOperateTerminal && keyboardState.isVisible && !isAccessoryDismissed;// Android's terminal owns an EditText; turning off autoFocus also clears its native focus.const terminalAutoFocus =@@ -596,20 +613,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)(keyboardState.isVisible ? keyboardState.height : 0) +(isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);- useEffect(() => {- const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {- setIsAccessoryDismissed(false);- });- const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {- setIsAccessoryDismissed(true);- });-- return () => {- keyboardWillShow.remove();- keyboardWillHide.remove();- };- }, []);-const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(() =>buildTerminalMenuSessions({@@ -636,170 +639,26 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)],);- useEffect(() => {- if (pendingLaunchEntry.key === launchTargetKey) {- return;- }- setPendingLaunchEntry({- key: launchTargetKey,- launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),- });- }, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);-- useEffect(() => {- if (initialAttachGridEntry.key === launchTargetKey) {- return;- }- setInitialAttachGridEntry({- key: launchTargetKey,- size: cachedRouteGridSize ?? {- cols: DEFAULT_TERMINAL_COLS,- rows: DEFAULT_TERMINAL_ROWS,- },- });- }, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);-- useEffect(() => {- if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {- return;- }- navigation.dispatch(- StackActions.replace("ThreadTerminal", {- environmentId: String(selectedThread.environmentId),- threadId: String(selectedThread.id),- terminalId: runningSession.target.terminalId,- }),- );- }, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]);-- useEffect(() => {- const initialInput = pendingLaunch?.initialInput;+ const writeInput = async (data: string): Promise<boolean> => {if (- !canOperateTerminal ||- !initialInput ||- !selectedThread ||- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope) ||- terminal.version === 0 ||- sentInitialInputKeyRef.current === launchTargetKey+ !isRunning ||+ !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {- return;+ return false;}- sentInitialInputKeyRef.current = launchTargetKey;- void writeTerminal({++ const result = await writeTerminal({environmentId: selectedThread.environmentId,input: {threadId: selectedThread.id,terminalId,- data: initialInput,+ data,},});- }, [- launchTargetKey,- pendingLaunch?.initialInput,- selectedThread,- terminal.version,- terminalId,- writeTerminal,- canOperateTerminal,- ]);-- useEffect(() => {- firstNonEmptyBufferLoggedRef.current = false;- sentInitialInputKeyRef.current = null;- }, [terminalKey]);-- const clearBufferReplayTimer = useCallback(() => {- if (bufferReplayTimerRef.current !== null) {- clearTimeout(bufferReplayTimerRef.current);- bufferReplayTimerRef.current = null;- }- }, []);-- const scheduleBufferReplayReady = useCallback(() => {- clearBufferReplayTimer();- const replayKey = bufferReplayKey;- terminalDebugLog("replay:schedule-ready", {- replayKey,- delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,- });- bufferReplayTimerRef.current = setTimeout(() => {- bufferReplayTimerRef.current = null;- setReadyBufferReplayKey(replayKey);- terminalDebugLog("replay:ready", { replayKey });- }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);- }, [bufferReplayKey, clearBufferReplayTimer]);-- useEffect(() => {- if (lastBufferReplayKeyRef.current === bufferReplayKey) {- return;- }-- lastBufferReplayKeyRef.current = bufferReplayKey;- clearBufferReplayTimer();- setReadyBufferReplayKey(null);- }, [bufferReplayKey, clearBufferReplayTimer]);-- useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);-- useEffect(() => {- if (!routeEnvironmentId || !routeThreadId) {- setLastGridSize({- cols: DEFAULT_TERMINAL_COLS,- rows: DEFAULT_TERMINAL_ROWS,- });- return;- }-- setLastGridSize(- getCachedTerminalGridSize({- environmentId: routeEnvironmentId,- threadId: routeThreadId,- terminalId,- }) ?? {- cols: DEFAULT_TERMINAL_COLS,- rows: DEFAULT_TERMINAL_ROWS,- },- );- setHasMeasuredSurface(true);- }, [routeEnvironmentId, routeThreadId, terminalId]);-- const writeInput = useCallback(- async (data: string): Promise<boolean> => {- if (- !selectedThread ||- !isRunning ||- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)- ) {- return false;- }-- const result = await writeTerminal({- environmentId: selectedThread.environmentId,- input: {- threadId: selectedThread.id,- terminalId,- data,- },- });- return result._tag === "Success";- },- [isRunning, selectedThread, terminalId, writeTerminal],- );-- const pasteSessionRef = useRef<ReturnType<typeof createTerminalPasteSession> | null>(null);- if (pasteSessionRef.current === null) {- pasteSessionRef.current = createTerminalPasteSession();- }- const pasteSession = pasteSessionRef.current;-- useEffect(() => {- pasteSession.reset(canOperateTerminal && isRunning);- return () => {- pasteSession.reset(false);- };- }, [canOperateTerminal, isRunning, pasteSession, terminal.lifecycleVersion, terminalKey]);+ return result._tag === "Success";+ };- const pasteFromClipboard = useCallback(async () => {+ const pasteFromClipboard = async () => {await pasteSession.paste({readText: Clipboard.getStringAsync,write: writeInput,@@ -807,205 +666,83 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)console.error(new TerminalClipboardReadError({ terminalId, cause }));},});- }, [pasteSession, terminalId, writeInput]);-- const writeModifiedInput = useCallback(- (data: string) => {- if (pendingModifier === null) {- void writeInput(data);- return;- }+ };- setPendingModifierState({ terminalId, value: null });- const resolved = resolveModifiedTerminalInput({- data,- modifier: pendingModifier,- hostPlatform,- });- if (resolved.kind === "paste") {- void pasteFromClipboard();- return;- }- void writeInput(resolved.data);- },- [hostPlatform, pasteFromClipboard, pendingModifier, terminalId, writeInput],- );+ const writeModifiedInput = (data: string) => {+ if (pendingModifier === null) {+ void writeInput(data);+ return;+ }- const handleInput = useCallback(- (data: string) => {- if (data.length === 0) {- return;- }+ setPendingModifier(null);+ const resolved = resolveModifiedTerminalInput({+ data,+ modifier: pendingModifier,+ hostPlatform,+ });+ if (resolved.kind === "paste") {+ void pasteFromClipboard();+ return;+ }+ void writeInput(resolved.data);+ };- writeModifiedInput(data);- },- [writeModifiedInput],- );+ const handleInput = (data: string) => {+ if (data.length === 0) {+ return;+ }- const handleResize = useCallback(- (size: { readonly cols: number; readonly rows: number }) => {- terminalDebugLog("native:onResize", {- cols: size.cols,- rows: size.rows,- terminalKey,- });- setHasMeasuredSurface(true);- if (readyBufferReplayKey !== bufferReplayKey) {- scheduleBufferReplayReady();- }- if (routeEnvironmentId && routeThreadId) {- cacheTerminalGridSize(- {- environmentId: routeEnvironmentId,- threadId: routeThreadId,- terminalId,- },- size,- );- }- if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {- return;- }+ writeModifiedInput(data);+ };- setLastGridSize(size);- },- [- lastGridSize.cols,- lastGridSize.rows,- bufferReplayKey,- readyBufferReplayKey,- routeEnvironmentId,- routeThreadId,- scheduleBufferReplayReady,- terminalId,+ const handleResize = (size: { readonly cols: number; readonly rows: number }) => {+ terminalDebugLog("native:onResize", {+ cols: size.cols,+ rows: size.rows,terminalKey,- ],- );-- const handleSelectTerminal = useCallback(- (nextTerminalId: string) => {- if (!selectedThread || nextTerminalId === terminalId) {- return;- }-- navigation.dispatch(- StackActions.replace("ThreadTerminal", {- environmentId: String(selectedThread.environmentId),- threadId: String(selectedThread.id),- terminalId: nextTerminalId,- }),+ });+ if (routeEnvironmentId && routeThreadId) {+ cacheTerminalGridSize(+ {+ environmentId: routeEnvironmentId,+ threadId: routeThreadId,+ terminalId,+ },+ size,);- },- [navigation, selectedThread, terminalId],- );+ }+ terminalSessionDriver.reportGridSize(size);+ };- const handleCloseTerminal = useCallback(() => {- if (navigation.canGoBack()) {- navigation.goBack();+ const handleSelectTerminal = (nextTerminalId: string) => {+ if (nextTerminalId === terminalId) {return;}+navigation.dispatch(- StackActions.replace("Thread", {- environmentId: params.environmentId,- threadId: params.threadId,+ StackActions.replace("ThreadTerminal", {+ environmentId: String(selectedThread.environmentId),+ threadId: String(selectedThread.id),+ terminalId: nextTerminalId,}),);- }, [navigation, params.environmentId, params.threadId]);+ };- const navigateAwayAfterExit = useCallback(() => {- const fallbackTerminalId = previousLiveTerminalId({- sessions: terminalMenuSessions,- exitedTerminalId: terminalId,- });- if (fallbackTerminalId !== null && selectedThread) {- navigation.dispatch(- StackActions.replace("ThreadTerminal", {- environmentId: String(selectedThread.environmentId),- threadId: String(selectedThread.id),- terminalId: fallbackTerminalId,- }),- );- return;- }+ const handleCloseTerminal = () => {if (navigation.canGoBack()) {navigation.goBack();return;}- if (selectedThread) {- navigation.dispatch(- StackActions.replace("Thread", {- environmentId: String(selectedThread.environmentId),- threadId: String(selectedThread.id),- }),- );- }- }, [navigation, selectedThread, terminalId, terminalMenuSessions]);-- useTerminalLifecycle({- terminalKey,- canOperate: canOperateTerminal,- observing: observingTerminal,- attached: terminalAttachInput !== null && selectedThread !== null,- terminal,- reopen: async () => {- if (- terminalAttachInput === null ||- selectedThread === null ||- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)- )- return false;- const result = await openTerminal({- environmentId: selectedThread.environmentId,- input: {- threadId: selectedThread.id,- terminalId,- cwd: terminalAttachInput.cwd,- worktreePath: terminalAttachInput.worktreePath,- cols: terminalAttachInput.cols,- rows: terminalAttachInput.rows,- ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}),- },- });- return result._tag === "Success";- },- onRunning: () => {- pendingExitNavigationRef.current = null;- },- onExit: () => {- if (- selectedThread === null ||- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)- )- return;- void closeTerminal({- environmentId: selectedThread.environmentId,- input: { threadId: selectedThread.id, terminalId },- });- if (navigation.isFocused()) {- navigateAwayAfterExit();- return;- }- pendingExitNavigationRef.current = terminalKey;- },- });-- useEffect(- () =>- navigation.addListener("focus", () => {- if (pendingExitNavigationRef.current !== terminalKey) {- return;- }- pendingExitNavigationRef.current = null;- navigateAwayAfterExit();+ navigation.dispatch(+ StackActions.replace("Thread", {+ environmentId: params.environmentId,+ threadId: params.threadId,}),- [navigateAwayAfterExit, navigation, terminalKey],- );+ );+ };- const handleOpenNewTerminal = useCallback(() => {- if (- !selectedThread ||- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)- ) {+ const handleOpenNewTerminal = () => {+ if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {return;}@@ -1023,25 +760,22 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)}),}),);- }, [knownSessions, navigation, selectedThread, terminalId, terminalMenuSessions]);+ };- const handleDecreaseFontSize = useCallback(() => {+ const handleDecreaseFontSize = () => {setTerminalFontSize(stepTerminalFontSize(fontSize, -1));- }, [fontSize, setTerminalFontSize]);+ };- const handleIncreaseFontSize = useCallback(() => {+ const handleIncreaseFontSize = () => {setTerminalFontSize(stepTerminalFontSize(fontSize, 1));- }, [fontSize, setTerminalFontSize]);+ };- const handleClearTerminal = useCallback(() => {- if (- !selectedThread ||- !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)- ) {+ const handleClearTerminal = () => {+ if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {return;}- setPendingModifierState({ terminalId, value: null });+ setPendingModifier(null);void clearTerminal({environmentId: selectedThread.environmentId,input: {@@ -1049,67 +783,44 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)terminalId,},});- }, [clearTerminal, selectedThread, terminalId]);+ };- const handleToolbarActionPress = useCallback(- (action: TerminalToolbarAction) => {- if (action.kind === "modifier") {- setPendingModifierState((current) => ({- terminalId,- value:- (current.terminalId === terminalId ? current.value : null) === action.modifier- ? null- : action.modifier,- }));- return;- }+ const handleToolbarActionPress = (action: TerminalToolbarAction) => {+ if (action.kind === "modifier") {+ setPendingModifier((current) => (current === action.modifier ? null : action.modifier));+ return;+ }- if (action.kind === "clear") {- handleClearTerminal();- return;- }+ if (action.kind === "clear") {+ handleClearTerminal();+ return;+ }- if (action.kind === "paste") {- setPendingModifierState({ terminalId, value: null });- void pasteFromClipboard();- return;- }+ if (action.kind === "paste") {+ setPendingModifier(null);+ void pasteFromClipboard();+ return;+ }- writeModifiedInput(action.data);- },- [handleClearTerminal, pasteFromClipboard, terminalId, writeModifiedInput],- );+ writeModifiedInput(action.data);+ };- const handleDismissKeyboard = useCallback(() => {- setIsAccessoryDismissed(true);+ const handleDismissKeyboard = () => {+ setAccessory((current) => ({ ...current, dismissed: true }));void KeyboardController.dismiss();- }, []);+ };- const handleShowKeyboard = useCallback(() => {+ const handleShowKeyboard = () => {if (!canOperateTerminal) return;- setIsAccessoryDismissed(false);+ setAccessory((current) => ({ ...current, dismissed: false }));setKeyboardFocusRequest((current) => current + 1);- }, [canOperateTerminal]);- const handleRetryEnvironment = useCallback(() => {+ surfaceRef.current?.focusKeyboard();+ };+ const handleRetryEnvironment = () => {if (routeEnvironmentId !== null) {void retryEnvironment(routeEnvironmentId);}- }, [retryEnvironment, routeEnvironmentId]);-- if (!selectedThread) {- if (!connectionsReady) {- return <LoadingScreen message="Opening terminal…" />;- }-- return (- <View className="flex-1 bg-screen">- <EmptyState- title="Thread unavailable"- detail="This terminal route needs an active thread and workspace."- />- </View>- );- }+ };if (!selectedThreadProject?.workspaceRoot) {return (@@ -1128,7 +839,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)return (<>- {capturedOutput !== null && selectedThread ? (+ {capturedOutput !== null ? (<TerminalContextSheettext={capturedOutput}environmentId={selectedThread.environmentId}@@ -1244,9 +955,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)}}/><TerminalSurface+ ref={surfaceRef}autoFocus={canOperateTerminal && terminalAutoFocus}readOnly={!canOperateTerminal}- buffer={terminal.version === 0 ? null : terminalSurfaceBuffer}+ buffer={terminal.version === 0 ? null : terminal.buffer}output={terminal.version === 0 ? null : terminal.output}fontSize={fontSize}isRunning={isRunning}@@ -1268,7 +980,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps){Platform.OS === "android" && !keyboardState.isVisible ? (<View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">- {selectedThread && hasNativeTerminalSurface() ? (+ {hasNativeTerminalSurface() ? (<Button label="Attach output" tone="text" onPress={requestCapture} />) : null}<View className="flex-1" />@@ -1279,7 +991,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)onPress={handleShowKeyboard}/></View>- ) : Platform.OS !== "android" && selectedThread && hasNativeTerminalSurface() ? (+ ) : Platform.OS !== "android" && hasNativeTerminalSurface() ? (<PressableaccessibilityRole="button"onPress={() => {diff --git a/apps/mobile/src/features/terminal/terminalBufferReplay.ts b/apps/mobile/src/features/terminal/terminalBufferReplay.tsdeleted file mode 100644index 966f3be1ff7..00000000000--- a/apps/mobile/src/features/terminal/terminalBufferReplay.ts+++ /dev/null@@ -1,27 +0,0 @@-import { terminalDebugLog } from "./terminalDebugLog";--export const TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS = 180;--export function getTerminalBufferReplayKey(input: {- readonly terminalKey: string;- readonly fontSize: number;-}): string {- return `${input.terminalKey}:${input.fontSize}`;-}--export function getTerminalSurfaceReplayBuffer(input: {- readonly buffer: string;- readonly replayKey: string;- readonly readyReplayKey: string | null;-}): string {- if (input.readyReplayKey !== null && input.readyReplayKey !== input.replayKey) {- terminalDebugLog("replay:stale-key-hiding-buffer", {- replayKey: input.replayKey,- readyReplayKey: input.readyReplayKey,- bufferLen: input.buffer.length,- });- return "";- }-- return input.buffer;-}diff --git a/apps/mobile/src/features/terminal/terminalLaunchContext.ts b/apps/mobile/src/features/terminal/terminalLaunchContext.tsindex 51966003646..1ee18cd2006 100644--- a/apps/mobile/src/features/terminal/terminalLaunchContext.ts+++ b/apps/mobile/src/features/terminal/terminalLaunchContext.ts@@ -1,5 +1,5 @@import type { EnvironmentId, ThreadId } from "@t3tools/contracts";-import { useEffect, useState } from "react";+import { useState } from "react";interface TerminalLocationLike {readonly cwd: string;@@ -82,10 +82,10 @@ export function resolveTerminalOpenLocation(input: {};}+/** The first location resolved for a terminal target stays fixed for that target. */export function useInitialTerminalLaunchLocation(input: {- readonly targetKey: string | null;+ readonly targetKey: string;readonly pendingLaunch: PendingTerminalLaunch | null;- readonly hasResolvedPendingLaunch: boolean;readonly isAuthenticated: boolean;readonly canRead: boolean;readonly canOperate: boolean;@@ -93,12 +93,7 @@ export function useInitialTerminalLaunchLocation(input: {readonly location: Parameters<typeof resolveTerminalOpenLocation>[0] | null;}) {let candidate: TerminalLocationLike | null = null;- if (- input.location !== null &&- input.hasResolvedPendingLaunch &&- input.isAuthenticated &&- (input.canRead || input.canOperate)- ) {+ if (input.location !== null && input.isAuthenticated && (input.canRead || input.canOperate)) {if (input.pendingLaunch !== null) {candidate = {cwd: input.pendingLaunch.cwd,@@ -110,11 +105,9 @@ export function useInitialTerminalLaunchLocation(input: {}}const [entry, setEntry] = useState(() => ({ key: input.targetKey, location: candidate }));- useEffect(() => {- if (entry.key === input.targetKey && (entry.location !== null || candidate === null)) {- return;- }+ if (entry.key !== input.targetKey || (entry.location === null && candidate !== null)) {setEntry({ key: input.targetKey, location: candidate });- }, [candidate, entry.key, entry.location, input.targetKey]);- return entry.key === input.targetKey ? entry.location : null;+ return candidate;+ }+ return entry.location;}diff --git a/apps/mobile/src/features/terminal/useTerminalExitNavigation.test.tsx b/apps/mobile/src/features/terminal/useTerminalExitNavigation.test.tsxnew file mode 100644index 00000000000..06a5363dc55--- /dev/null+++ b/apps/mobile/src/features/terminal/useTerminalExitNavigation.test.tsx@@ -0,0 +1,133 @@+import * as NodeModule from "node:module";+import { act, useLayoutEffect } from "react";+import { createRoot } from "react-dom/client";+import { expect, it, vi } from "vite-plus/test";++const harness = vi.hoisted(() => ({ navigation: undefined as unknown }));++vi.mock("@react-navigation/native", async () => {+ const { createRequire } = await import("node:module");+ const requireNavigation = createRequire(+ createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),+ );+ return {+ StackActions: requireNavigation("@react-navigation/routers").StackActions,+ useNavigation: () => harness.navigation,+ };+});++import { useTerminalExitNavigation } from "./useTerminalExitNavigation";++const requireNavigation = NodeModule.createRequire(+ NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),+);+const { StackRouter, StackActions, CommonActions } = requireNavigation(+ "@react-navigation/routers",+) as {+ StackRouter: typeof import("@react-navigation/native").StackRouter;+ StackActions: typeof import("@react-navigation/native").StackActions;+ CommonActions: typeof import("@react-navigation/native").CommonActions;+};++type Action = Parameters<ReturnType<typeof StackRouter>["getStateForAction"]>[1];++function setup(fallbackTerminalId: string | null) {+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+ const router = StackRouter({});+ const options = {+ routeNames: ["Thread", "ThreadTerminal", "ThreadFiles"],+ routeParamList: {},+ routeGetIdList: {},+ };+ let state = router.getInitialState(options);+ const apply = (action: Action) => {+ const next = router.getStateForAction(state, action, options);+ if (!next) throw new Error(`Rejected ${action.type}`);+ state = router.getRehydratedState(next, options);+ };+ const thread = { environmentId: "environment", threadId: "thread" };+ apply(StackActions.replace("Thread", thread));+ apply(StackActions.push("ThreadTerminal", { ...thread, terminalId: "second" }));+ const terminalKey = state.routes.at(-1)!.key;+ const focusListeners = new Set<() => void>();+ // A screen's navigation object stamps its route as the source but leaves the+ // target unset, as React Navigation's screen navigation does.+ const dispatch = (action: Action) => apply({ source: terminalKey, ...action } as Action);+ harness.navigation = {+ dispatch,+ goBack: () => dispatch(CommonActions.goBack()),+ canGoBack: () => state.routes.length > 1,+ isFocused: () => state.routes.at(-1)?.key === terminalKey,+ addListener: (_event: "focus", listener: () => void) => {+ focusListeners.add(listener);+ return () => focusListeners.delete(listener);+ },+ };+ let exitNavigation!: ReturnType<typeof useTerminalExitNavigation>;+ function Probe() {+ const value = useTerminalExitNavigation({+ ...thread,+ readFallbackTerminalId: () => fallbackTerminalId,+ });+ useLayoutEffect(() => {+ exitNavigation = value;+ });+ return null;+ }+ const root = createRoot(document.createElement("div"));+ act(() => root.render(<Probe />));+ return {+ exitNavigation,+ routes: () => state.routes.map((route) => [route.name, route.params]),+ openFiles: () => apply(StackActions.push("ThreadFiles", thread)),+ returnToTerminal: () => {+ apply(StackActions.pop());+ for (const listener of focusListeners) listener();+ },+ [Symbol.dispose]: () => act(() => root.unmount()),+ };+}++const thread = { environmentId: "environment", threadId: "thread" };++it("leaves the screen on top alone when a terminal behind it exits, then goes back on return", () => {+ using screen = setup(null);+ screen.openFiles();++ screen.exitNavigation.exited();+ expect(screen.routes()).toEqual([+ ["Thread", thread],+ ["ThreadTerminal", { ...thread, terminalId: "second" }],+ ["ThreadFiles", thread],+ ]);++ screen.returnToTerminal();+ expect(screen.routes()).toEqual([["Thread", thread]]);+});++it("does not replace the screen on top with the fallback terminal", () => {+ using screen = setup("first");+ screen.openFiles();++ screen.exitNavigation.exited();+ expect(screen.routes().at(-1)).toEqual(["ThreadFiles", thread]);++ screen.returnToTerminal();+ expect(screen.routes()).toEqual([+ ["Thread", thread],+ ["ThreadTerminal", { ...thread, terminalId: "first" }],+ ]);+});++it("stays on a terminal that restarted before the user returned", () => {+ using screen = setup(null);+ screen.openFiles();++ screen.exitNavigation.exited();+ screen.exitNavigation.restarted();+ screen.returnToTerminal();+ expect(screen.routes()).toEqual([+ ["Thread", thread],+ ["ThreadTerminal", { ...thread, terminalId: "second" }],+ ]);+});diff --git a/apps/mobile/src/features/terminal/useTerminalExitNavigation.ts b/apps/mobile/src/features/terminal/useTerminalExitNavigation.tsnew file mode 100644index 00000000000..a2aa873b296--- /dev/null+++ b/apps/mobile/src/features/terminal/useTerminalExitNavigation.ts@@ -0,0 +1,66 @@+import { StackActions, useNavigation } from "@react-navigation/native";+import { useEffect, useEffectEvent, useRef } from "react";++/**+ * Leaves a terminal screen whose shell exited: to another live terminal of the+ * thread, else back. Screen navigation acts on the top route of the stack, so+ * a shell that exits while another screen is on top waits until its own screen+ * is focused again.+ */+export function useTerminalExitNavigation(target: {+ readonly environmentId: string;+ readonly threadId: string;+ readonly readFallbackTerminalId: () => string | null;+}) {+ const navigation = useNavigation();+ const pendingRef = useRef(false);++ const navigateAway = useEffectEvent(() => {+ const fallbackTerminalId = target.readFallbackTerminalId();+ if (fallbackTerminalId !== null) {+ navigation.dispatch(+ StackActions.replace("ThreadTerminal", {+ environmentId: target.environmentId,+ threadId: target.threadId,+ terminalId: fallbackTerminalId,+ }),+ );+ return;+ }+ if (navigation.canGoBack()) {+ navigation.goBack();+ return;+ }+ navigation.dispatch(+ StackActions.replace("Thread", {+ environmentId: target.environmentId,+ threadId: target.threadId,+ }),+ );+ });++ // oxlint-disable-next-line t3code/react-effect-budget -- focus subscription for the screen's lifetime; an exit behind another screen navigates when the user returns+ useEffect(+ () =>+ navigation.addListener("focus", () => {+ if (!pendingRef.current) return;+ pendingRef.current = false;+ navigateAway();+ }),+ [navigation],+ );++ return {+ exited: () => {+ if (navigation.isFocused()) {+ navigateAway();+ return;+ }+ pendingRef.current = true;+ },+ /** A shell that runs again before the screen regains focus keeps the screen. */+ restarted: () => {+ pendingRef.current = false;+ },+ };+}diff --git a/apps/mobile/src/features/terminal/useTerminalGridSync.test.ts b/apps/mobile/src/features/terminal/useTerminalGridSync.test.tsdeleted file mode 100644index 8eeeb442571..00000000000--- a/apps/mobile/src/features/terminal/useTerminalGridSync.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import * as NodeModule from "node:module";-import { EMPTY_TERMINAL_BUFFER_STATE } from "@t3tools/client-runtime/state/terminal";-import { EnvironmentId, ThreadId } from "@t3tools/contracts";-import { act, createElement, type ReactNode } from "react";-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";--import { useTerminalGridSync } from "./useTerminalGridSync";--const access = vi.hoisted(() => ({ environments: new Set<string>() }));-vi.mock("../../state/session", () => ({- readEnvironmentScope: (environmentId: string, scope: string) =>- scope === "terminal:operate" && access.environments.has(environmentId),-}));--// Mobile already depends on ReactDOM but does not install its browser type declarations.-const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {- createRoot(container: Element): {- render(children: ReactNode): void;- unmount(): void;- };-};--type Input = Parameters<typeof useTerminalGridSync>[0];-let root: ReturnType<typeof createRoot>;-const resize = vi.fn<Input["resize"]>();--function GridProbe(input: Input) {- useTerminalGridSync(input);- return null;-}--function session({- generation = 1,- version = 1,- status = "running",-}: {- readonly generation?: number;- readonly version?: number;- readonly status?: Input["terminal"]["status"];-} = {}): Input["terminal"] {- return { output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation }, version, status };-}--function input(): Input {- return {- environmentId: EnvironmentId.make("environment"),- threadId: ThreadId.make("thread"),- terminalId: "term-1",- canOperate: true,- terminal: session(),- size: { cols: 80, rows: 24 },- resize,- };-}--function render(value: Input) {- return act(() => root.render(createElement(GridProbe, value)));-}--beforeEach(() => {- resize.mockClear();- access.environments.clear();- access.environments.add("environment");- // The probe renders no DOM, but ReactDOM needs an event target to run real effects.- const document = {- nodeType: 9,- addEventListener() {},- removeEventListener() {},- };- const container = {- nodeType: 1,- tagName: "DIV",- namespaceURI: "http://www.w3.org/1999/xhtml",- ownerDocument: document,- addEventListener() {},- removeEventListener() {},- };- vi.stubGlobal("document", document);- vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- root = createRoot(container as unknown as HTMLElement);-});--afterEach(async () => {- await act(() => root.unmount());- vi.unstubAllGlobals();-});--it("replays an unchanged grid after reconnecting with a new attachment generation", async () => {- const current = { ...input(), size: { cols: 120, rows: 40 } };- await render(current);- expect(resize).toHaveBeenCalledOnce();-- await render({ ...current, terminal: session({ generation: 2, version: 0 }) });- expect(resize).toHaveBeenCalledOnce();-- await render({ ...current, terminal: session({ generation: 2 }) });- expect(resize).toHaveBeenCalledTimes(2);- expect(resize).toHaveBeenLastCalledWith({- environmentId: "environment",- input: { threadId: "thread", terminalId: "term-1", cols: 120, rows: 40 },- });-- // React may observe the next snapshot without rendering the empty seed first.- await render({ ...current, terminal: session({ generation: 3 }) });- expect(resize).toHaveBeenCalledTimes(3);-});diff --git a/apps/mobile/src/features/terminal/useTerminalGridSync.ts b/apps/mobile/src/features/terminal/useTerminalGridSync.tsdeleted file mode 100644index 6bdcc1f05ef..00000000000--- a/apps/mobile/src/features/terminal/useTerminalGridSync.ts+++ /dev/null@@ -1,51 +0,0 @@-import type { TerminalSessionState } from "@t3tools/client-runtime/state/terminal";-import {- AuthTerminalOperateScope,- type EnvironmentId,- type TerminalResizeInput,- type ThreadId,-} from "@t3tools/contracts";-import { useEffect } from "react";--import type { TerminalGridSize } from "./terminalUiState";-import { readEnvironmentScope } from "../../state/session";--export function useTerminalGridSync({- environmentId,- threadId,- terminalId,- canOperate,- terminal,- size,- resize,-}: {- readonly environmentId: EnvironmentId | null;- readonly threadId: ThreadId | null;- readonly terminalId: string;- readonly canOperate: boolean;- readonly terminal: Pick<TerminalSessionState, "output" | "status" | "version">;- readonly size: TerminalGridSize;- readonly resize: (target: {- readonly environmentId: EnvironmentId;- readonly input: TerminalResizeInput;- }) => void;-}): void {- const generation =- canOperate && terminal.version > 0 && terminal.status === "running"- ? terminal.output.generation- : null;-- useEffect(() => {- if (- generation === null ||- environmentId === null ||- threadId === null ||- !readEnvironmentScope(environmentId, AuthTerminalOperateScope)- )- return;- resize({- environmentId,- input: { threadId, terminalId, cols: size.cols, rows: size.rows },- });- }, [environmentId, generation, resize, size.cols, size.rows, terminalId, threadId]);-}diff --git a/apps/mobile/src/features/terminal/useTerminalLifecycle.test.ts b/apps/mobile/src/features/terminal/useTerminalLifecycle.test.tsdeleted file mode 100644index 6f565384bb6..00000000000--- a/apps/mobile/src/features/terminal/useTerminalLifecycle.test.ts+++ /dev/null@@ -1,99 +0,0 @@-import * as NodeModule from "node:module";-import { act, createElement, type ReactNode } from "react";-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";--import { useTerminalLifecycle } from "./useTerminalLifecycle";--const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {- createRoot(container: Element): {- render(children: ReactNode): void;- unmount(): void;- };-};--type Input = Parameters<typeof useTerminalLifecycle>[0];-let root: ReturnType<typeof createRoot>;-const reopen = vi.fn<Input["reopen"]>();-const onRunning = vi.fn<Input["onRunning"]>();-const onExit = vi.fn<Input["onExit"]>();--function LifecycleProbe(input: Input) {- useTerminalLifecycle(input);- return null;-}--function input(changes: Partial<Input> = {}): Input {- return {- terminalKey: "environment:thread:term-1",- canOperate: true,- observing: false,- attached: true,- terminal: { status: "running", version: 1 },- reopen,- onRunning,- onExit,- ...changes,- };-}--function render(value: Input) {- return act(() => root.render(createElement(LifecycleProbe, value)));-}--beforeEach(() => {- reopen.mockReset().mockResolvedValue(true);- onRunning.mockClear();- onExit.mockClear();- const document = {- nodeType: 9,- addEventListener() {},- removeEventListener() {},- };- const container = {- nodeType: 1,- tagName: "DIV",- namespaceURI: "http://www.w3.org/1999/xhtml",- ownerDocument: document,- addEventListener() {},- removeEventListener() {},- };- vi.stubGlobal("document", document);- vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);- root = createRoot(container as unknown as HTMLElement);-});--afterEach(async () => {- await act(() => root.unmount());- vi.unstubAllGlobals();-});--it("does not respawn a terminal that exited after operate was revoked", async () => {- await render(input());- await render(input({ canOperate: false }));- await render(input({ canOperate: false, terminal: { status: "exited", version: 2 } }));- await render(input({ terminal: { status: "exited", version: 1 } }));- expect(reopen).not.toHaveBeenCalled();- expect(onExit).not.toHaveBeenCalled();-});--it("reopens an ended terminal on an explicit new route visit", async () => {- await render(input({ canOperate: false, terminal: { status: "exited", version: 1 } }));- await render(input({ terminalKey: "environment:thread:term-2" }));- await render(input({ terminal: { status: "exited", version: 1 } }));- expect(reopen).toHaveBeenCalledOnce();-- await render(input({ terminal: { status: "exited", version: 2 } }));- expect(reopen).toHaveBeenCalledOnce();- await render(input({ terminal: { status: "running", version: 3 } }));- await render(input({ terminal: { status: "exited", version: 4 } }));- expect(onExit).toHaveBeenCalledOnce();-});--it("keeps a detached terminal from being mistaken for a live exit", async () => {- await render(input());- await render(input({ attached: false, terminal: { status: "closed", version: 0 } }));- await render(input({ terminal: { status: "exited", version: 1 } }));- expect(onExit).not.toHaveBeenCalled();- expect(reopen).toHaveBeenCalledOnce();-});diff --git a/apps/mobile/src/features/terminal/useTerminalLifecycle.ts b/apps/mobile/src/features/terminal/useTerminalLifecycle.tsdeleted file mode 100644index c77c941045b..00000000000--- a/apps/mobile/src/features/terminal/useTerminalLifecycle.ts+++ /dev/null@@ -1,76 +0,0 @@-import type { TerminalSessionState } from "@t3tools/client-runtime/state/terminal";-import { useEffect, useEffectEvent, useRef } from "react";--export function useTerminalLifecycle({- terminalKey,- canOperate,- observing,- attached,- terminal,- reopen,- onRunning,- onExit,-}: {- readonly terminalKey: string;- readonly canOperate: boolean;- readonly observing: boolean;- readonly attached: boolean;- readonly terminal: Pick<TerminalSessionState, "status" | "version">;- readonly reopen: () => Promise<boolean>;- readonly onRunning: () => void;- readonly onExit: () => void;-}) {- const lifecycle = useRef({- key: terminalKey,- wasRunning: false,- observed: false,- reopened: false,- });- const reopenTerminal = useEffectEvent(reopen);- const handleRunning = useEffectEvent(onRunning);- const handleExit = useEffectEvent(onExit);-- useEffect(() => {- if (lifecycle.current.key !== terminalKey) {- lifecycle.current = {- key: terminalKey,- wasRunning: false,- observed: false,- reopened: false,- };- }- const current = lifecycle.current;- if (!canOperate) {- if (observing || terminal.version > 0 || current.wasRunning) current.observed = true;- current.wasRunning = false;- return;- }- if (!attached) {- current.wasRunning = false;- return;- }- if (terminal.version === 0) return;-- if (terminal.status === "running" || terminal.status === "starting") {- current.wasRunning = true;- current.reopened = false;- handleRunning();- return;- }- if (terminal.status !== "closed" && terminal.status !== "exited") return;-- if (current.wasRunning) {- current.wasRunning = false;- current.reopened = true;- handleExit();- return;- }- // An explicit visit can reopen a cached ended session. Granting a viewer- // operate permission must leave the history they were reading intact.- if (current.observed || current.reopened) return;- current.reopened = true;- void reopenTerminal().then((succeeded) => {- if (!succeeded && lifecycle.current === current) current.reopened = false;- });- }, [attached, canOperate, observing, terminal.status, terminal.version, terminalKey]);-}diff --git a/apps/mobile/src/reactCompilerCoverage.test.ts b/apps/mobile/src/reactCompilerCoverage.test.tsindex ffaf7063006..e5f86349d0c 100644--- a/apps/mobile/src/reactCompilerCoverage.test.ts+++ b/apps/mobile/src/reactCompilerCoverage.test.ts@@ -19,7 +19,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {"src/components/ui/Menu.tsx": "ref read during render","src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render","src/features/home/thread-swipe-actions.tsx": "ref read during render",- "src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render","src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value","src/features/threads/ThreadArrangementSheet.tsx": "ref read during render","src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",diff --git a/apps/mobile/vite.config.ts b/apps/mobile/vite.config.tsindex e3f79ba02c3..77fffb6cb61 100644--- a/apps/mobile/vite.config.ts+++ b/apps/mobile/vite.config.ts@@ -16,6 +16,7 @@ const reactTests = ["src/native/useRetryingImageSource.test.tsx","src/state/queries.debounce.test.tsx","src/state/use-selected-thread-git-actions.test.tsx",+ "src/features/terminal/useTerminalExitNavigation.test.tsx",];export default defineConfig({diff --git a/packages/client-runtime/src/state/terminal.test.ts b/packages/client-runtime/src/state/terminal.test.tsnew file mode 100644index 00000000000..139a1b4c58e--- /dev/null+++ b/packages/client-runtime/src/state/terminal.test.ts@@ -0,0 +1,247 @@+import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";+import { expect, it } from "vite-plus/test";++import {+ createTerminalSession,+ INITIAL_TERMINAL_LIFECYCLE,+ transitionTerminalLifecycle,+ type TerminalLifecycleEvent,+ type TerminalSessionMode,+} from "./terminal.ts";+import { EMPTY_TERMINAL_BUFFER_STATE, type TerminalBufferState } from "./terminalSession.ts";++function run(events: ReadonlyArray<TerminalLifecycleEvent>) {+ let state = INITIAL_TERMINAL_LIFECYCLE;+ const commands: Array<string> = [];+ for (const event of events) {+ const step = transitionTerminalLifecycle(state, event);+ state = step.state;+ if (step.command !== null) commands.push(step.command);+ }+ return commands;+}++const status = (value: TerminalBufferState["status"], version = 1): TerminalLifecycleEvent => ({+ type: "status",+ status: value,+ version,+});++it("does not respawn a terminal that exited after operate was revoked", () => {+ expect(+ run([status("running"), { type: "detached", canOperate: false }, status("exited")]),+ ).toEqual([]);+});++it("reopens an ended terminal on an explicit visit, once until it runs again", () => {+ expect(run([status("exited"), status("exited", 2)])).toEqual(["reopen"]);+ expect(run([status("exited"), status("running", 3), status("exited", 4)])).toEqual([+ "reopen",+ "exit",+ ]);+ expect(run([status("exited"), { type: "reopen-failed" }, status("exited", 2)])).toEqual([+ "reopen",+ "reopen",+ ]);+});++it("keeps a detached terminal from being mistaken for a live exit", () => {+ expect(+ run([status("running"), { type: "detached", canOperate: true }, status("exited")]),+ ).toEqual(["reopen"]);+});++it("leaves the history a viewer was reading when operate is granted", () => {+ expect(run([{ type: "observed" }, status("exited")])).toEqual([]);+});++const environmentId = EnvironmentId.make("environment");+const threadId = ThreadId.make("thread");++function setup(options: { readonly initialInput?: string } = {}) {+ // Tests flush the registry's scheduled work to control when driver finalizers run.+ const scheduled: Array<() => void> = [];+ const registry = AtomRegistry.make({+ scheduleTask: (task) => {+ scheduled.push(task);+ return () => {};+ },+ });+ const flush = () => {+ for (const task of scheduled.splice(0)) task();+ };+ const attachment = Atom.make<AsyncResult.AsyncResult<TerminalBufferState, unknown>>(+ AsyncResult.initial(true),+ );+ const observation = Atom.make<AsyncResult.AsyncResult<TerminalBufferState, unknown>>(+ AsyncResult.initial(true),+ );+ const access = { canOperate: true };+ const calls: Array<{ readonly command: string; readonly input: unknown }> = [];+ const command = (name: string) => ({+ label: name,+ run: async (_registry: AtomRegistry.AtomRegistry, value: { readonly input: unknown }) => {+ calls.push({ command: name, input: value.input });+ return AsyncResult.success(undefined);+ },+ });+ const exits: Array<true> = [];+ const live: Array<boolean> = [];+ const session = createTerminalSession(+ {+ attach: () => attachment,+ observe: () => observation,+ open: command("open"),+ resize: command("resize"),+ write: command("write"),+ close: command("close"),+ },+ {+ target: { environmentId, threadId, terminalId: "term-1" },+ gridSize: { cols: 120, rows: 40 },+ initialInput: options.initialInput,+ canOperate: () => access.canOperate,+ onExit: () => exits.push(true),+ onLiveChange: (value) => live.push(value),+ },+ );+ const attached: TerminalSessionMode = {+ kind: "attached",+ input: { threadId, terminalId: "term-1", cwd: "/repo", cols: 80, rows: 24 },+ };+ const snapshot = (state: Partial<TerminalBufferState> & { readonly generation?: number }) => {+ const { generation = 1, ...rest } = state;+ return AsyncResult.success({+ ...EMPTY_TERMINAL_BUFFER_STATE,+ output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation },+ ...rest,+ });+ };+ const emit = (state: Partial<TerminalBufferState> & { readonly generation?: number }) =>+ registry.set(attachment, snapshot(state));+ // A new attach subscription starts from an empty seed.+ const detach = () => registry.set(attachment, AsyncResult.initial(true));+ const observe = (state: Partial<TerminalBufferState>) =>+ registry.set(observation, snapshot(state));+ const mount = (mode: TerminalSessionMode) => registry.mount(session.driver(mode));+ const of = (name: string) => calls.filter((call) => call.command === name).map((c) => c.input);+ return { session, attached, access, flush, detach, emit, observe, mount, calls, of, exits, live };+}++it("replays the measured grid on every new attachment generation", () => {+ const { session, attached, emit, mount, of } = setup();+ mount(attached);+ emit({ status: "running", version: 1 });+ expect(of("resize")).toEqual([{ threadId, terminalId: "term-1", cols: 120, rows: 40 }]);++ session.reportGridSize({ cols: 100, rows: 30 });+ expect(of("resize")).toHaveLength(2);+ session.reportGridSize({ cols: 100, rows: 30 });+ expect(of("resize")).toHaveLength(2);++ // A reconnect seeds an empty state first, then the new generation's snapshot.+ emit({ status: "running", version: 0, generation: 2 });+ expect(of("resize")).toHaveLength(2);+ emit({ status: "running", version: 1, generation: 2 });+ expect(of("resize")).toHaveLength(3);+ emit({ status: "running", version: 2, generation: 3 });+ expect(of("resize")).toEqual([+ { threadId, terminalId: "term-1", cols: 120, rows: 40 },+ { threadId, terminalId: "term-1", cols: 100, rows: 30 },+ { threadId, terminalId: "term-1", cols: 100, rows: 30 },+ { threadId, terminalId: "term-1", cols: 100, rows: 30 },+ ]);+});++it("writes the launch's initial input once the first snapshot lands", () => {+ const { attached, emit, mount, calls, of } = setup({ initialInput: "pnpm dev\r" });+ mount(attached);+ expect(of("write")).toEqual([]);+ emit({ status: "running", version: 1 });+ emit({ status: "running", version: 2 });+ expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "pnpm dev\r" }]);+ // The shell gets the measured grid before the launched command runs.+ expect(calls.map((call) => call.command)).toEqual(["resize", "write"]);+});++it("closes and reports a shell that exits while attached", () => {+ const { attached, emit, mount, of, exits, live } = setup();+ mount(attached);+ emit({ status: "running", version: 1, lifecycleVersion: 0 });+ emit({ status: "exited", version: 2 });+ expect(of("close")).toEqual([{ threadId, terminalId: "term-1" }]);+ expect(of("open")).toEqual([]);+ expect(exits).toHaveLength(1);+ expect(live).toEqual([true, false]);+});++it("does not reopen an ended shell after a viewer is granted operate", () => {+ const { attached, flush, access, emit, observe, mount, of } = setup();+ access.canOperate = false;+ const unmountViewer = mount({ kind: "observing" });+ observe({ status: "exited", version: 1 });+ access.canOperate = true;+ unmountViewer();+ flush();+ mount(attached);+ emit({ status: "exited", version: 1 });+ expect(of("open")).toEqual([]);+});++it("does not reopen on grant when the viewer had no snapshot yet", () => {+ const { attached, flush, access, emit, mount, of } = setup();+ access.canOperate = false;+ const unmountViewer = mount({ kind: "observing" });+ access.canOperate = true;+ unmountViewer();+ flush();+ mount(attached);+ emit({ status: "exited", version: 1 });+ expect(of("open")).toEqual([]);+});++it("leaves a shell that exited after operate was revoked mid-run", () => {+ const { attached, flush, access, detach, emit, mount, of, exits } = setup();+ const unmountAttached = mount(attached);+ emit({ status: "running", version: 1 });+ access.canOperate = false;+ unmountAttached();+ flush();+ detach();+ access.canOperate = true;+ mount(attached);+ emit({ status: "exited", version: 2 });+ expect(of("open")).toEqual([]);+ expect(of("close")).toEqual([]);+ expect(exits).toEqual([]);+});++it("reopens instead of closing a shell that ended while detached", () => {+ const { attached, flush, detach, emit, mount, of, exits } = setup();+ const unmountAttached = mount(attached);+ emit({ status: "running", version: 1 });+ unmountAttached();+ flush();+ detach();+ mount(attached);+ emit({ status: "exited", version: 2 });+ expect(of("close")).toEqual([]);+ expect(exits).toEqual([]);+ expect(of("open")).toHaveLength(1);+});++it("keeps a replaced attachment's late release from resetting the new one", () => {+ const { attached, flush, emit, mount, of, exits } = setup();+ const unmountFirst = mount(attached);+ emit({ status: "running", version: 1 });+ mount({+ kind: "attached",+ input: { threadId, terminalId: "term-1", cwd: "/repo/worktree", cols: 80, rows: 24 },+ });+ unmountFirst();+ flush();+ emit({ status: "exited", version: 2 });+ expect(of("close")).toHaveLength(1);+ expect(exits).toHaveLength(1);+});diff --git a/packages/client-runtime/src/state/terminal.ts b/packages/client-runtime/src/state/terminal.tsindex 8c0a1113e15..c7592c93f31 100644--- a/packages/client-runtime/src/state/terminal.ts+++ b/packages/client-runtime/src/state/terminal.ts@@ -1,21 +1,37 @@-import { type TerminalSummary, WS_METHODS } from "@t3tools/contracts";+import {+ type EnvironmentId,+ type TerminalAttachInput,+ type TerminalCloseInput,+ type TerminalOpenInput,+ type TerminalResizeInput,+ type TerminalSummary,+ type TerminalWriteInput,+ type ThreadId,+ WS_METHODS,+} from "@t3tools/contracts";import * as Effect from "effect/Effect";+import * as Option from "effect/Option";import * as Stream from "effect/Stream";-import { Atom } from "effect/reactivity";+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";import {+ type AtomCommand,createAtomCommandScheduler,createEnvironmentRpcCommand,createEnvironmentRpcSubscriptionAtomFamily,createEnvironmentSubscriptionAtomFamily,+ runAtomCommand,} from "./runtime.ts";import type { EnvironmentRegistry } from "../connection/registry.ts";import { subscribe, subscribeDynamic, type EnvironmentRpcInput } from "../rpc/client.ts";import {applyTerminalAttachStreamEvent,applyTerminalMetadataStreamEvent,+ EMPTY_TERMINAL_BUFFER_STATE,nextTerminalAttachSeedState,+ type TerminalBufferState,} from "./terminalSession.ts";+import { terminalOutputText } from "./terminalOutput.ts";export function createTerminalEnvironmentAtoms<R, E>(runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,@@ -37,7 +53,7 @@ export function createTerminalEnvironmentAtoms<R, E>(readonly input: { readonly threadId: string; readonly terminalId?: string | undefined };}) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]);const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey };- return {+ const atoms = {observe: createEnvironmentSubscriptionAtomFamily(runtime, {label: "environment-data:terminal:observe",subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalObserve>) =>@@ -112,6 +128,314 @@ export function createTerminalEnvironmentAtoms<R, E>(concurrency: lifecycleConcurrency,}),};+ return {+ ...atoms,+ createSession: (options: TerminalSessionOptions) => createTerminalSession(atoms, options),+ };+}++export interface TerminalLifecycleState {+ readonly wasRunning: boolean;+ /** The user has seen this terminal without operate permission. */+ readonly observed: boolean;+ readonly reopened: boolean;+}++export const INITIAL_TERMINAL_LIFECYCLE: TerminalLifecycleState = {+ wasRunning: false,+ observed: false,+ reopened: false,+};++export type TerminalLifecycleEvent =+ /** A viewer without operate permission is following this terminal. */+ | { readonly type: "observed" }+ | { readonly type: "detached"; readonly canOperate: boolean }+ | {+ readonly type: "status";+ readonly status: TerminalBufferState["status"];+ readonly version: number;+ }+ | { readonly type: "reopen-failed" };++export type TerminalLifecycleCommand = "exit" | "reopen" | null;++export function transitionTerminalLifecycle(+ state: TerminalLifecycleState,+ event: TerminalLifecycleEvent,+): { readonly state: TerminalLifecycleState; readonly command: TerminalLifecycleCommand } {+ switch (event.type) {+ case "observed":+ return { state: { ...state, observed: true }, command: null };+ case "detached":+ return {+ state: {+ ...state,+ // Losing operate while the shell runs leaves the viewer reading its history.+ observed: state.observed || (!event.canOperate && state.wasRunning),+ wasRunning: false,+ },+ command: null,+ };+ case "reopen-failed":+ return { state: { ...state, reopened: false }, command: null };+ case "status": {+ if (event.version === 0) return { state, command: null };+ if (event.status === "running" || event.status === "starting") {+ return { state: { ...state, wasRunning: true, reopened: false }, command: null };+ }+ if (event.status !== "closed" && event.status !== "exited") return { state, command: null };+ if (state.wasRunning) {+ return { state: { ...state, wasRunning: false, reopened: true }, command: "exit" };+ }+ // An explicit visit can reopen a cached ended session. Granting a viewer+ // operate permission must leave the history they were reading intact.+ if (state.observed || state.reopened) return { state, command: null };+ return { state: { ...state, reopened: true }, command: "reopen" };+ }+ }+}++export interface TerminalGridSize {+ readonly cols: number;+ readonly rows: number;+}++export type TerminalSessionMode =+ | { readonly kind: "observing" }+ | { readonly kind: "attached"; readonly input: TerminalAttachInput };++type EnvironmentCommand<Input> = AtomCommand<+ { readonly environmentId: EnvironmentId; readonly input: Input },+ unknown,+ unknown+>;++export interface TerminalSessionAtoms {+ readonly attach: (target: {+ readonly environmentId: EnvironmentId;+ readonly input: TerminalAttachInput;+ }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;+ readonly observe: (target: {+ readonly environmentId: EnvironmentId;+ readonly input: { readonly threadId: ThreadId; readonly terminalId: string };+ }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;+ readonly open: EnvironmentCommand<TerminalOpenInput>;+ readonly resize: EnvironmentCommand<TerminalResizeInput>;+ readonly write: EnvironmentCommand<TerminalWriteInput>;+ readonly close: EnvironmentCommand<TerminalCloseInput>;+}++export interface TerminalSessionOptions {+ readonly target: {+ readonly environmentId: EnvironmentId;+ readonly threadId: ThreadId;+ readonly terminalId: string;+ };+ readonly gridSize: TerminalGridSize;+ /** Written once, as soon as the first attachment snapshot lands. */+ readonly initialInput?: string | undefined;+ /** Read right before every command, so revoking operate stops them at once. */+ readonly canOperate: () => boolean;+ /** The shell ended while attached; the store has already closed it. */+ readonly onExit: () => void;+ /** Fires when the shell starts or stops accepting input, and on every restart. */+ readonly onLiveChange?: (live: boolean) => void;+ readonly debugLog?: (message: string, data: Record<string, unknown>) => void;+}++export interface TerminalSession {+ /**+ * Mount while the session follows a terminal: attached to operate it, or+ * observing it read-only. `null` follows nothing.+ */+ readonly driver: (mode: TerminalSessionMode | null) => Atom.Atom<void>;+ /** The surface measured a new grid; the shell is resized while it runs. */+ readonly reportGridSize: (size: TerminalGridSize) => void;+}++/**+ * Owns one shown terminal's lifecycle: it reopens an ended shell on an explicit+ * visit, closes and reports a shell that exits while attached, replays the+ * measured grid whenever the server starts a new output generation, and writes+ * the launch's initial input once.+ */+export function createTerminalSession(+ atoms: TerminalSessionAtoms,+ options: TerminalSessionOptions,+): TerminalSession {+ const { environmentId, threadId, terminalId } = options.target;+ let lifecycle = INITIAL_TERMINAL_LIFECYCLE;+ let gridSize = options.gridSize;+ let generation: number | null = null;+ let liveLifecycleVersion: number | null = null;+ let initialInputPending = Boolean(options.initialInput);+ let lastStatus: TerminalBufferState["status"] | null = null;+ let loggedFirstOutput = false;+ let resizeRegistry: AtomRegistry.AtomRegistry | null = null;+ // Driver atoms are released on a scheduled task, so an attachment replaced by+ // another one must not reset state the newer attachment already set.+ let currentAttachment: object | null = null;++ const sendResize = () => {+ if (generation === null || resizeRegistry === null || !options.canOperate()) return;+ void runAtomCommand(resizeRegistry, atoms.resize, {+ environmentId,+ input: { threadId, terminalId, cols: gridSize.cols, rows: gridSize.rows },+ });+ };++ const setLive = (next: number | null) => {+ if (next === liveLifecycleVersion) return;+ liveLifecycleVersion = next;+ options.onLiveChange?.(next !== null);+ };++ const apply = (+ event: TerminalLifecycleEvent,+ registry: AtomRegistry.AtomRegistry,+ input: TerminalAttachInput | null,+ ) => {+ const step = transitionTerminalLifecycle(lifecycle, event);+ lifecycle = step.state;+ if (step.command === "exit") {+ if (!options.canOperate()) return;+ void runAtomCommand(registry, atoms.close, {+ environmentId,+ input: { threadId, terminalId },+ });+ options.onExit();+ return;+ }+ if (step.command !== "reopen") return;+ const reopen = async () => {+ if (input?.cwd === undefined || !options.canOperate()) return false;+ const result = await runAtomCommand(registry, atoms.open, {+ environmentId,+ input: {+ threadId,+ terminalId,+ cwd: input.cwd,+ worktreePath: input.worktreePath,+ cols: input.cols,+ rows: input.rows,+ ...(input.env ? { env: input.env } : {}),+ },+ });+ return result._tag === "Success";+ };+ void reopen().then((succeeded) => {+ if (!succeeded)+ lifecycle = transitionTerminalLifecycle(lifecycle, { type: "reopen-failed" }).state;+ });+ };++ const onAttachment = (+ registry: AtomRegistry.AtomRegistry,+ input: TerminalAttachInput,+ result: AsyncResult.AsyncResult<TerminalBufferState, unknown>,+ ) => {+ resizeRegistry = registry;+ const buffer = Option.getOrElse(AsyncResult.value(result), () => EMPTY_TERMINAL_BUFFER_STATE);+ const status = result._tag === "Failure" ? "error" : buffer.status;+ if (status !== lastStatus) {+ lastStatus = status;+ options.debugLog?.("session:status", {+ terminalId,+ status,+ error: buffer.error,+ version: buffer.version,+ });+ }+ if (!loggedFirstOutput && options.debugLog) {+ const text = terminalOutputText(buffer.output);+ if (text.length > 0) {+ loggedFirstOutput = true;+ options.debugLog("session:first-nonempty-buffer", {+ terminalId,+ length: text.length,+ preview: text.slice(0, 160),+ });+ }+ }++ setLive(status === "running" || status === "starting" ? buffer.lifecycleVersion : null);++ // Resize before the initial input so a launched command starts at the measured grid.+ const nextGeneration =+ buffer.version > 0 && status === "running" ? buffer.output.generation : null;+ if (nextGeneration !== generation) {+ generation = nextGeneration;+ sendResize();+ }++ if (initialInputPending && buffer.version > 0 && options.initialInput && options.canOperate()) {+ initialInputPending = false;+ void runAtomCommand(registry, atoms.write, {+ environmentId,+ input: { threadId, terminalId, data: options.initialInput },+ });+ }++ apply({ type: "status", status, version: buffer.version }, registry, input);+ };++ const idle = Atom.make<void>(undefined);+ const modes = new Map<string, TerminalSessionMode>();+ const drivers = Atom.family((key: string) => {+ const mode = modes.get(key)!;+ return Atom.make((get) => {+ const registry = get.registry;+ // `subscribe`, not `get`: a rebuild would resubscribe on every output chunk.+ if (mode.kind === "observing") {+ // Viewing read-only counts as observed before the first snapshot lands, so+ // a grant that arrives early still leaves the ended shell's history alone.+ get.subscribe(+ atoms.observe({ environmentId, input: { threadId, terminalId } }),+ () => {+ if (options.canOperate()) return;+ lifecycle = transitionTerminalLifecycle(lifecycle, { type: "observed" }).state;+ },+ { immediate: true },+ );+ return;+ }+ const attachment = {};+ currentAttachment = attachment;+ get.addFinalizer(() => {+ if (currentAttachment !== attachment) return;+ currentAttachment = null;+ generation = null;+ lastStatus = null;+ setLive(null);+ lifecycle = transitionTerminalLifecycle(lifecycle, {+ type: "detached",+ canOperate: options.canOperate(),+ }).state;+ });+ get.subscribe(+ atoms.attach({ environmentId, input: mode.input }),+ (result) => onAttachment(registry, mode.input, result),+ { immediate: true },+ );+ }).pipe(+ Atom.withLabel(`terminal-session:${environmentId}:${threadId}:${terminalId}:${mode.kind}`),+ );+ });++ return {+ driver: (mode) => {+ if (mode === null) return idle;+ const key = JSON.stringify(mode);+ if (!modes.has(key)) modes.set(key, mode);+ return drivers(key);+ },+ reportGridSize: (size) => {+ if (size.cols === gridSize.cols && size.rows === gridSize.rows) return;+ gridSize = size;+ sendResize();+ },+ };}export * from "./terminalSession.ts";