@devries-cameron20 / t3code Mirror · read-only / commits / 5786e12981
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 17:00 UTC

refactor(mobile): terminal lifecycle runs in a session store, not screen effects (#25071)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 25, 2026 at 18:13 UTC 5786e12981f82adbe9d1f18fd5a490496817b5f9
14 files changed +1145 -1016
apps/mobile/src/features/terminal/NativeTerminalSurface.tsx
+26 -12
@@ -1,5 +1,13 @@
1 import type { TerminalOutputState } from "@t3tools/client-runtime/state/terminal";
2 -import { memo, useCallback, useEffect, useRef, useState } from "react";
2 +import {
3 + memo,
4 + useCallback,
5 + useEffect,
6 + useImperativeHandle,
7 + useRef,
8 + useState,
9 + type Ref,
10 +} from "react";
11 import {
12 Pressable,
13 ScrollView,
@@ -38,7 +46,13 @@ interface TerminalResizeEvent {
46 readonly rows: number;
47 }
48
49 +export interface TerminalSurfaceHandle {
50 + /** The text fallback focuses its input; the native view follows `keyboardFocusRequest`. */
51 + readonly focusKeyboard: () => void;
52 +}
53 +
54 interface TerminalSurfaceProps extends ViewProps {
55 + readonly ref?: Ref<TerminalSurfaceHandle>;
56 readonly terminalKey: string;
57 readonly buffer: string | null;
58 readonly output: TerminalOutputState | null;
@@ -71,9 +85,10 @@ function estimateGridSize(input: {
85 };
86 }
87
74 -const FallbackTerminalSurface = memo(function FallbackTerminalSurface(
75 - props: ReadyTerminalSurfaceProps,
76 -) {
88 +const FallbackTerminalSurface = memo(function FallbackTerminalSurface({
89 + ref,
90 + ...props
91 +}: ReadyTerminalSurfaceProps) {
92 const fontSize = props.fontSize ?? MOBILE_TYPOGRAPHY.label.fontSize;
93 const inputRef = useRef<TextInputInstance>(null);
94 const { themeAppearance, themeId } = useAppearancePreferences();
@@ -89,15 +104,14 @@ const FallbackTerminalSurface = memo(function FallbackTerminalSurface(
104 props.onResize(estimateGridSize({ width, height, fontSize }));
105 };
106
92 - useEffect(() => {
93 - if (!props.readOnly && (props.keyboardFocusRequest ?? 0) > 0) {
107 + useImperativeHandle(ref, () => ({
108 + focusKeyboard: () => {
109 + if (props.readOnly) return;
110 + // Blur first so a focused input still raises the keyboard; focus lands after the blur commits.
111 inputRef.current?.blur();
95 - const focusFrame = requestAnimationFrame(() => inputRef.current?.focus());
96 - return () => cancelAnimationFrame(focusFrame);
97 - }
98 -
99 - return undefined;
100 - }, [props.keyboardFocusRequest, props.readOnly]);
112 + requestAnimationFrame(() => inputRef.current?.focus());
113 + },
114 + }));
115
116 return (
117 <View
apps/mobile/src/features/terminal/ThreadTerminalRouteScreen.tsx
+337 -625
@@ -12,14 +12,17 @@ import { SymbolView } from "../../components/ui/AppSymbol";
12 import { AppBar } from "../../components/ui/AppBar";
13 import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
14 import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
15 -import { useCallback, useEffect, useMemo, useRef, useState } from "react";
15 +import { useAtomMount } from "@effect/atom-react";
16 +import { useMemo, useRef, useState, useSyncExternalStore } from "react";
17 import { Platform, Pressable, View } from "react-native";
18 import { useSafeAreaInsets } from "react-native-safe-area-context";
19 import { AppText as Text } from "../../components/ui/AppText";
20 import { TerminalContextSheet } from "./TerminalContextSheet";
21 import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule";
22 import * as Clipboard from "expo-clipboard";
23 +import * as Option from "effect/Option";
24 import * as Schema from "effect/Schema";
25 +import { AsyncResult } from "effect/reactivity";
26 import {
27 KeyboardController,
28 KeyboardEvents,
@@ -43,6 +46,7 @@ import { useEnvironmentPresentation } from "../../state/presentation";
46 import { terminalEnvironment } from "../../state/terminal";
47 import { environmentSession, readEnvironmentScope } from "../../state/session";
48 import { useEnvironmentQuery } from "../../state/query";
49 +import { appAtomRegistry } from "../../state/atom-registry";
50 import { useAtomCommand } from "../../state/use-atom-command";
51 import { uuidv4 } from "../../lib/uuid";
52 import { useServerConfigs } from "../../state/entities";
@@ -61,14 +65,10 @@ import {
65 import { useThreadSelection } from "../../state/use-thread-selection";
66 import { useSelectedThreadProjection } from "../../state/use-thread-detail";
67 import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
64 -import { TerminalSurface } from "./NativeTerminalSurface";
68 +import { TerminalSurface, type TerminalSurfaceHandle } from "./NativeTerminalSurface";
69 import { getMobileTerminalTheme } from "./terminalTheme";
70 import { terminalDebugLog } from "./terminalDebugLog";
67 -import {
68 - getTerminalBufferReplayKey,
69 - getTerminalSurfaceReplayBuffer,
70 - TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
71 -} from "./terminalBufferReplay";
71 +import { useTerminalExitNavigation } from "./useTerminalExitNavigation";
72 import {
73 useInitialTerminalLaunchLocation,
74 takePendingTerminalLaunch,
@@ -91,8 +91,6 @@ import {
91 } from "./terminalInput";
92 import { createTerminalPasteSession } from "./terminalPaste";
93 import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";
94 -import { useTerminalGridSync } from "./useTerminalGridSync";
95 -import { useTerminalLifecycle } from "./useTerminalLifecycle";
94
95 function TerminalHeader(props: {
96 readonly subtitle: string;
@@ -252,46 +250,166 @@ type ThreadTerminalRouteScreenProps = StaticScreenProps<{
250 readonly terminalId?: string;
251 }>;
252
253 +type ThreadSelection = ReturnType<typeof useThreadSelection>;
254 +
255 +function useTerminalAccess(environmentId: EnvironmentId | null) {
256 + const session = useEnvironmentQuery(
257 + environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
258 + );
259 + const isAuthenticated = session.error === null && session.data?.authenticated === true;
260 + return {
261 + session,
262 + isAuthenticated,
263 + canOperate:
264 + isAuthenticated &&
265 + session.data !== null &&
266 + sessionGrantsScope(session.data, AuthTerminalOperateScope),
267 + canRead:
268 + isAuthenticated &&
269 + session.data !== null &&
270 + sessionGrantsScope(session.data, AuthTerminalReadScope),
271 + };
272 +}
273 +
274 export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) {
275 + const connectionsReady = useConnectionsReady();
276 + const params = props.route.params;
277 + const selection = useThreadSelection();
278 + const { selectedThread } = selection;
279 + const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
280 + const routeEnvironmentId = routeEnvironmentIdRaw
281 + ? EnvironmentId.make(routeEnvironmentIdRaw)
282 + : null;
283 + const access = useTerminalAccess(routeEnvironmentId);
284 + const knownSessions = useKnownTerminalSessions({
285 + environmentId: selectedThread?.environmentId ?? null,
286 + threadId: selectedThread?.id ?? null,
287 + });
288 + const requestedTerminalId = firstRouteParam(params.terminalId);
289 + // A route without a terminal shows the thread's running one. The choice is
290 + // made once, from the first session list that has one, so the terminal shown
291 + // does not change under the user as sessions come and go.
292 + const [bootstrapTerminalId, setBootstrapTerminalId] = useState<string | null>(null);
293 + const runningSession = knownSessions.sessions
294 + ? (pickRunningTerminalSessionForBootstrap(knownSessions.sessions) ??
295 + (access.canOperate ? null : (knownSessions.sessions[0] ?? null)))
296 + : null;
297 + if (
298 + requestedTerminalId === null &&
299 + bootstrapTerminalId === null &&
300 + runningSession !== null &&
301 + runningSession.target.terminalId !== DEFAULT_TERMINAL_ID
302 + ) {
303 + setBootstrapTerminalId(runningSession.target.terminalId);
304 + }
305 + const explicitTerminalId = requestedTerminalId ?? bootstrapTerminalId;
306 + const terminalId = explicitTerminalId ?? DEFAULT_TERMINAL_ID;
307 +
308 + if (!selectedThread) {
309 + if (!connectionsReady) {
310 + return <LoadingScreen message="Opening terminal…" />;
311 + }
312 +
313 + return (
314 + <View className="flex-1 bg-screen">
315 + <EmptyState
316 + title="Thread unavailable"
317 + detail="This terminal route needs an active thread and workspace."
318 + />
319 + </View>
320 + );
321 + }
322 +
323 + return (
324 + <ThreadTerminal
325 + key={`${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`}
326 + params={params}
327 + routeEnvironmentId={routeEnvironmentId}
328 + selection={selection}
329 + thread={selectedThread}
330 + terminalId={terminalId}
331 + hasExplicitTerminalId={explicitTerminalId !== null}
332 + access={access}
333 + knownSessions={knownSessions}
334 + />
335 + );
336 +}
337 +
338 +function readLiveTerminalSessions(
339 + environmentId: EnvironmentId,
340 + threadId: ThreadId,
341 +): ReadonlyArray<TerminalMenuSession> {
342 + if (!readEnvironmentScope(environmentId, AuthTerminalReadScope)) return [];
343 + const result = appAtomRegistry.get(terminalEnvironment.metadata({ environmentId, input: null }));
344 + const summaries = Option.getOrElse(AsyncResult.value(result), () => []);
345 + return summaries
346 + .filter((summary) => summary.threadId === threadId)
347 + .map((summary) => ({
348 + terminalId: summary.terminalId,
349 + cwd: summary.cwd,
350 + status: summary.status,
351 + hasRunningSubprocess: summary.hasRunningSubprocess,
352 + displayLabel: resolveTerminalSessionLabel(summary.terminalId, summary),
353 + updatedAt: summary.updatedAt,
354 + }));
355 +}
356 +
357 +// `useKeyboardState` only flips on willShow and didHide; the accessory must
358 +// leave as soon as the keyboard starts hiding, so it follows the will-events.
359 +let keyboardShowing = KeyboardController.isVisible();
360 +function subscribeKeyboardShowing(onChange: () => void) {
361 + keyboardShowing = KeyboardController.isVisible();
362 + const willShow = KeyboardEvents.addListener("keyboardWillShow", () => {
363 + keyboardShowing = true;
364 + onChange();
365 + });
366 + const willHide = KeyboardEvents.addListener("keyboardWillHide", () => {
367 + keyboardShowing = false;
368 + onChange();
369 + });
370 + return () => {
371 + willShow.remove();
372 + willHide.remove();
373 + };
374 +}
375 +const getKeyboardShowing = () => keyboardShowing;
376 +
377 +function ThreadTerminal(props: {
378 + readonly params: ThreadTerminalRouteScreenProps["route"]["params"];
379 + readonly routeEnvironmentId: EnvironmentId | null;
380 + readonly selection: ThreadSelection;
381 + readonly thread: NonNullable<ThreadSelection["selectedThread"]>;
382 + readonly terminalId: string;
383 + readonly hasExplicitTerminalId: boolean;
384 + readonly access: ReturnType<typeof useTerminalAccess>;
385 + readonly knownSessions: ReturnType<typeof useKnownTerminalSessions>;
386 +}) {
387 + const { params, routeEnvironmentId, thread: selectedThread, terminalId } = props;
388 + const { selectedThreadProject, selectedEnvironmentConnection } = props.selection;
389 + const {
390 + session: terminalSession,
391 + isAuthenticated,
392 + canOperate: canOperateTerminal,
393 + canRead: canReadTerminal,
394 + } = props.access;
395 + const {
396 + sessions: knownSessions,
397 + isPending: sessionsPending,
398 + error: sessionsError,
399 + } = props.knownSessions;
400 const insets = useSafeAreaInsets();
401 const nativeColumnMetrics = useNativeColumnLayoutMetrics();
402 const navigation = useNavigation();
403 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
260 - const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
404 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
262 - const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close");
263 - const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
405 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
265 - const connectionsReady = useConnectionsReady();
266 - const params = props.route.params;
267 - const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
268 - useThreadSelection();
406 const selectedThreadDetail = useSelectedThreadProjection();
407 const selectedThreadDetailWorktreePath =
408 selectedThreadDetail?.projection.thread.worktreePath ?? null;
272 - const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
409 const routeThreadIdRaw = firstRouteParam(params.threadId);
274 - const routeEnvironmentId = routeEnvironmentIdRaw
275 - ? EnvironmentId.make(routeEnvironmentIdRaw)
276 - : null;
410 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
278 - const terminalSession = useEnvironmentQuery(
279 - routeEnvironmentId === null ? null : environmentSession.sessionStateAtom(routeEnvironmentId),
280 - );
281 - const isAuthenticated =
282 - terminalSession.error === null && terminalSession.data?.authenticated === true;
283 - const canOperateTerminal =
284 - isAuthenticated &&
285 - terminalSession.data !== null &&
286 - sessionGrantsScope(terminalSession.data, AuthTerminalOperateScope);
287 - const canReadTerminal =
288 - isAuthenticated &&
289 - terminalSession.data !== null &&
290 - sessionGrantsScope(terminalSession.data, AuthTerminalReadScope);
411 const environment = useEnvironmentPresentation(routeEnvironmentId);
412 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
293 - const requestedTerminalId = firstRouteParam(params.terminalId);
294 - const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
413 // Any new positive value triggers capture, even on remount. Pass one only while pending and keep increasing it.
414 const captureSequenceRef = useRef(0);
415 const [captureRequest, setCaptureRequest] = useState(0);
@@ -309,120 +427,81 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
427 themeVariables,
428 } = useAppearancePreferences();
429 const fontSize = appearance.terminalFontSize;
312 - const cachedRouteGridSize =
313 - routeEnvironmentId && routeThreadId
314 - ? getCachedTerminalGridSize({
315 - environmentId: routeEnvironmentId,
316 - threadId: routeThreadId,
317 - terminalId,
318 - })
319 - : null;
320 - const {
321 - sessions: knownSessions,
322 - isPending: sessionsPending,
323 - error: sessionsError,
324 - } = useKnownTerminalSessions({
325 - environmentId: selectedThread?.environmentId ?? null,
326 - threadId: selectedThread?.id ?? null,
327 - });
328 - const runningSession = useMemo(
329 - () =>
330 - pickRunningTerminalSessionForBootstrap(knownSessions ?? []) ??
331 - (canOperateTerminal ? null : (knownSessions?.[0] ?? null)),
332 - [canOperateTerminal, knownSessions],
333 - );
430 + const terminalKey = `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`;
431 const activeKnownSession = useMemo(
432 () => knownSessions?.find((session) => session.target.terminalId === terminalId) ?? null,
433 [knownSessions, terminalId],
434 );
338 - const hasTerminalTarget = requestedTerminalId !== null || activeKnownSession !== null;
339 - const launchTarget = useMemo(
435 + const hasTerminalTarget = props.hasExplicitTerminalId || activeKnownSession !== null;
436 + const [pendingLaunch] = useState<PendingTerminalLaunch | null>(() =>
437 + takePendingTerminalLaunch({
438 + environmentId: selectedThread.environmentId,
439 + threadId: selectedThread.id,
440 + terminalId,
441 + }),
442 + );
443 + const [initialAttachGridSize] = useState(
444 () =>
341 - selectedThread
342 - ? {
343 - environmentId: selectedThread.environmentId,
344 - threadId: selectedThread.id,
445 + (routeEnvironmentId && routeThreadId
446 + ? getCachedTerminalGridSize({
447 + environmentId: routeEnvironmentId,
448 + threadId: routeThreadId,
449 terminalId,
346 - }
347 - : null,
348 - [selectedThread, terminalId],
450 + })
451 + : null) ?? { cols: DEFAULT_TERMINAL_COLS, rows: DEFAULT_TERMINAL_ROWS },
452 );
350 - const launchTargetKey = launchTarget
351 - ? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`
352 - : null;
353 - const [pendingLaunchEntry, setPendingLaunchEntry] = useState<{
354 - readonly key: string | null;
355 - readonly launch: PendingTerminalLaunch | null;
356 - }>(() => ({
357 - key: launchTargetKey,
358 - launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
359 - }));
360 - const pendingLaunch =
361 - pendingLaunchEntry.key === launchTargetKey ? pendingLaunchEntry.launch : null;
362 - const hasResolvedPendingLaunch = pendingLaunchEntry.key === launchTargetKey;
363 - const [initialAttachGridEntry, setInitialAttachGridEntry] = useState(() => ({
364 - key: launchTargetKey,
365 - size: cachedRouteGridSize ?? {
366 - cols: DEFAULT_TERMINAL_COLS,
367 - rows: DEFAULT_TERMINAL_ROWS,
368 - },
369 - }));
370 - const initialAttachGridSize =
371 - initialAttachGridEntry.key === launchTargetKey ? initialAttachGridEntry.size : null;
372 - const [lastGridSize, setLastGridSize] = useState(
373 - cachedRouteGridSize ?? {
374 - cols: DEFAULT_TERMINAL_COLS,
375 - rows: DEFAULT_TERMINAL_ROWS,
376 - },
453 + const [pasteSession] = useState(createTerminalPasteSession);
454 + const exitNavigation = useTerminalExitNavigation({
455 + environmentId: String(selectedThread.environmentId),
456 + threadId: String(selectedThread.id),
457 + readFallbackTerminalId: () =>
458 + previousLiveTerminalId({
459 + sessions: readLiveTerminalSessions(selectedThread.environmentId, selectedThread.id),
460 + exitedTerminalId: terminalId,
461 + }),
462 + });
463 + const [terminalSessionDriver] = useState(() =>
464 + terminalEnvironment.createSession({
465 + target: {
466 + environmentId: selectedThread.environmentId,
467 + threadId: selectedThread.id,
468 + terminalId,
469 + },
470 + gridSize: initialAttachGridSize,
471 + initialInput: pendingLaunch?.initialInput,
472 + canOperate: () =>
473 + readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope),
474 + onExit: exitNavigation.exited,
475 + onLiveChange: (live) => {
476 + if (live) exitNavigation.restarted();
477 + pasteSession.reset(live);
478 + },
479 + debugLog: terminalDebugLog,
480 + }),
481 );
482 + const surfaceRef = useRef<TerminalSurfaceHandle>(null);
483 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
379 - const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
380 - const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
381 - const firstNonEmptyBufferLoggedRef = useRef(false);
382 - const lastBufferReplayKeyRef = useRef<string | null>(null);
383 - const sentInitialInputKeyRef = useRef<string | null>(null);
384 - const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
385 - const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);
386 - const [pendingModifierState, setPendingModifierState] = useState<{
387 - readonly terminalId: string;
388 - readonly value: PendingModifier | null;
389 - }>({
390 - terminalId,
391 - value: null,
392 - });
393 - const shouldRedirectToRunningTerminal =
394 - requestedTerminalId === null &&
395 - runningSession !== null &&
396 - runningSession.target.terminalId !== terminalId;
484 + const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);
485 const launchLocation = useInitialTerminalLaunchLocation({
398 - targetKey: launchTargetKey,
486 + targetKey: terminalKey,
487 pendingLaunch,
400 - hasResolvedPendingLaunch,
488 isAuthenticated,
489 canRead: canReadTerminal,
490 canOperate: canOperateTerminal,
491 hasLoadedSessions: knownSessions !== null,
405 - location:
406 - selectedThread && selectedThreadProject?.workspaceRoot
407 - ? {
408 - terminalLocation: activeKnownSession?.state.summary ?? null,
409 - activeSessionLocation: activeKnownSession?.state.summary ?? null,
410 - workspaceRoot: selectedThreadProject.workspaceRoot,
411 - threadShellWorktreePath: selectedThread.worktreePath ?? null,
412 - threadDetailWorktreePath: selectedThreadDetailWorktreePath,
413 - }
414 - : null,
492 + location: selectedThreadProject?.workspaceRoot
493 + ? {
494 + terminalLocation: activeKnownSession?.state.summary ?? null,
495 + activeSessionLocation: activeKnownSession?.state.summary ?? null,
496 + workspaceRoot: selectedThreadProject.workspaceRoot,
497 + threadShellWorktreePath: selectedThread.worktreePath ?? null,
498 + threadDetailWorktreePath: selectedThreadDetailWorktreePath,
499 + }
500 + : null,
501 });
502 const terminalAttachInput = useMemo(
503 () =>
418 - selectedThread !== null &&
419 - launchLocation !== null &&
420 - hasResolvedPendingLaunch &&
421 - initialAttachGridSize !== null &&
422 - hasResolvedFontPreference &&
423 - hasMeasuredSurface &&
424 - isEnvironmentReady &&
425 - !shouldRedirectToRunningTerminal
504 + launchLocation !== null && hasResolvedFontPreference && isEnvironmentReady
505 ? {
506 threadId: selectedThread.id,
507 terminalId,
@@ -435,107 +514,39 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
514 }
515 : null,
516 [
438 - hasMeasuredSurface,
517 hasResolvedFontPreference,
440 - hasResolvedPendingLaunch,
518 initialAttachGridSize,
519 isEnvironmentReady,
520 launchLocation,
521 pendingLaunch,
445 - selectedThread,
446 - shouldRedirectToRunningTerminal,
522 + selectedThread.id,
523 terminalId,
524 ],
525 );
450 - const observingTerminal =
451 - !canOperateTerminal && canReadTerminal && selectedThread !== null && hasTerminalTarget;
526 + const observingTerminal = !canOperateTerminal && canReadTerminal && hasTerminalTarget;
527 const streamingOutput = supportsNativeTerminalOutput();
528 const terminal = useAttachedTerminalSession({
529 materializeBuffer: !streamingOutput,
455 - environmentId: selectedThread?.environmentId ?? null,
530 + environmentId: selectedThread.environmentId,
531 terminal: canOperateTerminal
532 ? terminalAttachInput
533 : observingTerminal
534 ? { threadId: selectedThread.id, terminalId }
535 : null,
536 });
462 - const terminalKey = selectedThread
463 - ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
464 - : terminalId;
465 - useTerminalGridSync({
466 - environmentId: selectedThread?.environmentId ?? null,
467 - threadId: selectedThread?.id ?? null,
468 - terminalId,
469 - canOperate: canOperateTerminal,
470 - terminal,
471 - size: lastGridSize,
472 - resize: resizeTerminal,
473 - });
474 - const bufferReplayKey = useMemo(
475 - () => getTerminalBufferReplayKey({ terminalKey, fontSize }),
476 - [fontSize, terminalKey],
537 + useAtomMount(
538 + terminalSessionDriver.driver(
539 + canOperateTerminal
540 + ? terminalAttachInput === null
541 + ? null
542 + : { kind: "attached", input: terminalAttachInput }
543 + : observingTerminal
544 + ? { kind: "observing" }
545 + : null,
546 + ),
547 );
478 - if (lastBufferReplayKeyRef.current === null) {
479 - lastBufferReplayKeyRef.current = bufferReplayKey;
480 - }
481 - const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
482 - buffer: terminal.buffer,
483 - replayKey: bufferReplayKey,
484 - readyReplayKey: readyBufferReplayKey,
485 - });
548 const isRunning = terminal.status === "running" || terminal.status === "starting";
549
488 - const pendingExitNavigationRef = useRef<string | null>(null);
489 -
490 - useEffect(() => {
491 - terminalDebugLog("surface:props", {
492 - terminalKey,
493 - atomBufferLen: terminal.buffer.length,
494 - surfaceBufferLen: terminalSurfaceBuffer.length,
495 - replayKey: bufferReplayKey,
496 - readyReplayKey: readyBufferReplayKey,
497 - status: terminal.status,
498 - version: terminal.version,
499 - });
500 - }, [
501 - bufferReplayKey,
502 - readyBufferReplayKey,
503 - terminal.buffer.length,
504 - terminal.status,
505 - terminal.version,
506 - terminalKey,
507 - terminalSurfaceBuffer.length,
508 - ]);
509 -
510 - useEffect(() => {
511 - terminalDebugLog("session:status", {
512 - terminalKey,
513 - status: terminal.status,
514 - error: terminal.error,
515 - summary: terminal.summary?.cwd ?? null,
516 - bufferLen: terminal.buffer.length,
517 - version: terminal.version,
518 - });
519 - }, [
520 - terminal.buffer.length,
521 - terminal.error,
522 - terminal.status,
523 - terminal.summary?.cwd,
524 - terminal.version,
525 - terminalKey,
526 - ]);
527 -
528 - useEffect(() => {
529 - if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {
530 - return;
531 - }
532 - firstNonEmptyBufferLoggedRef.current = true;
533 - terminalDebugLog("session:first-nonempty-buffer", {
534 - terminalKey,
535 - length: terminal.buffer.length,
536 - preview: terminal.buffer.slice(0, 160),
537 - });
538 - }, [terminal.buffer, terminal.buffer.length, terminalKey]);
550 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
551 const serverConfigs = useServerConfigs();
552 const hostOs =
@@ -550,8 +561,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
561 );
562
563 const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);
553 - const pendingModifier =
554 - pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
564 const headerSubtitle = selectedThreadProject?.title ?? "";
565 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
566 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
@@ -585,6 +594,14 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
594 height: state.height,
595 isVisible: state.isVisible,
596 }));
597 + const keyboardShowing = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing);
598 + // The accessory follows the keyboard, except that the dismiss and show
599 + // buttons flip it ahead of the keyboard animation.
600 + const [accessory, setAccessory] = useState({ keyboardShowing, dismissed: false });
601 + if (accessory.keyboardShowing !== keyboardShowing) {
602 + setAccessory({ keyboardShowing, dismissed: !keyboardShowing });
603 + }
604 + const isAccessoryDismissed = accessory.dismissed;
605 const isAccessoryVisible = canOperateTerminal && keyboardState.isVisible && !isAccessoryDismissed;
606 // Android's terminal owns an EditText; turning off autoFocus also clears its native focus.
607 const terminalAutoFocus =
@@ -596,20 +613,6 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
613 (keyboardState.isVisible ? keyboardState.height : 0) +
614 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
615
599 - useEffect(() => {
600 - const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {
601 - setIsAccessoryDismissed(false);
602 - });
603 - const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {
604 - setIsAccessoryDismissed(true);
605 - });
606 -
607 - return () => {
608 - keyboardWillShow.remove();
609 - keyboardWillHide.remove();
610 - };
611 - }, []);
612 -
616 const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
617 () =>
618 buildTerminalMenuSessions({
@@ -636,170 +639,26 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
639 ],
640 );
641
639 - useEffect(() => {
640 - if (pendingLaunchEntry.key === launchTargetKey) {
641 - return;
642 - }
643 - setPendingLaunchEntry({
644 - key: launchTargetKey,
645 - launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
646 - });
647 - }, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);
648 -
649 - useEffect(() => {
650 - if (initialAttachGridEntry.key === launchTargetKey) {
651 - return;
652 - }
653 - setInitialAttachGridEntry({
654 - key: launchTargetKey,
655 - size: cachedRouteGridSize ?? {
656 - cols: DEFAULT_TERMINAL_COLS,
657 - rows: DEFAULT_TERMINAL_ROWS,
658 - },
659 - });
660 - }, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
661 -
662 - useEffect(() => {
663 - if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
664 - return;
665 - }
666 - navigation.dispatch(
667 - StackActions.replace("ThreadTerminal", {
668 - environmentId: String(selectedThread.environmentId),
669 - threadId: String(selectedThread.id),
670 - terminalId: runningSession.target.terminalId,
671 - }),
672 - );
673 - }, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
674 -
675 - useEffect(() => {
676 - const initialInput = pendingLaunch?.initialInput;
642 + const writeInput = async (data: string): Promise<boolean> => {
643 if (
678 - !canOperateTerminal ||
679 - !initialInput ||
680 - !selectedThread ||
681 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope) ||
682 - terminal.version === 0 ||
683 - sentInitialInputKeyRef.current === launchTargetKey
644 + !isRunning ||
645 + !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
646 ) {
685 - return;
647 + return false;
648 }
687 - sentInitialInputKeyRef.current = launchTargetKey;
688 - void writeTerminal({
649 +
650 + const result = await writeTerminal({
651 environmentId: selectedThread.environmentId,
652 input: {
653 threadId: selectedThread.id,
654 terminalId,
693 - data: initialInput,
655 + data,
656 },
657 });
696 - }, [
697 - launchTargetKey,
698 - pendingLaunch?.initialInput,
699 - selectedThread,
700 - terminal.version,
701 - terminalId,
702 - writeTerminal,
703 - canOperateTerminal,
704 - ]);
705 -
706 - useEffect(() => {
707 - firstNonEmptyBufferLoggedRef.current = false;
708 - sentInitialInputKeyRef.current = null;
709 - }, [terminalKey]);
710 -
711 - const clearBufferReplayTimer = useCallback(() => {
712 - if (bufferReplayTimerRef.current !== null) {
713 - clearTimeout(bufferReplayTimerRef.current);
714 - bufferReplayTimerRef.current = null;
715 - }
716 - }, []);
717 -
718 - const scheduleBufferReplayReady = useCallback(() => {
719 - clearBufferReplayTimer();
720 - const replayKey = bufferReplayKey;
721 - terminalDebugLog("replay:schedule-ready", {
722 - replayKey,
723 - delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
724 - });
725 - bufferReplayTimerRef.current = setTimeout(() => {
726 - bufferReplayTimerRef.current = null;
727 - setReadyBufferReplayKey(replayKey);
728 - terminalDebugLog("replay:ready", { replayKey });
729 - }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
730 - }, [bufferReplayKey, clearBufferReplayTimer]);
731 -
732 - useEffect(() => {
733 - if (lastBufferReplayKeyRef.current === bufferReplayKey) {
734 - return;
735 - }
736 -
737 - lastBufferReplayKeyRef.current = bufferReplayKey;
738 - clearBufferReplayTimer();
739 - setReadyBufferReplayKey(null);
740 - }, [bufferReplayKey, clearBufferReplayTimer]);
741 -
742 - useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
743 -
744 - useEffect(() => {
745 - if (!routeEnvironmentId || !routeThreadId) {
746 - setLastGridSize({
747 - cols: DEFAULT_TERMINAL_COLS,
748 - rows: DEFAULT_TERMINAL_ROWS,
749 - });
750 - return;
751 - }
752 -
753 - setLastGridSize(
754 - getCachedTerminalGridSize({
755 - environmentId: routeEnvironmentId,
756 - threadId: routeThreadId,
757 - terminalId,
758 - }) ?? {
759 - cols: DEFAULT_TERMINAL_COLS,
760 - rows: DEFAULT_TERMINAL_ROWS,
761 - },
762 - );
763 - setHasMeasuredSurface(true);
764 - }, [routeEnvironmentId, routeThreadId, terminalId]);
765 -
766 - const writeInput = useCallback(
767 - async (data: string): Promise<boolean> => {
768 - if (
769 - !selectedThread ||
770 - !isRunning ||
771 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
772 - ) {
773 - return false;
774 - }
775 -
776 - const result = await writeTerminal({
777 - environmentId: selectedThread.environmentId,
778 - input: {
779 - threadId: selectedThread.id,
780 - terminalId,
781 - data,
782 - },
783 - });
784 - return result._tag === "Success";
785 - },
786 - [isRunning, selectedThread, terminalId, writeTerminal],
787 - );
788 -
789 - const pasteSessionRef = useRef<ReturnType<typeof createTerminalPasteSession> | null>(null);
790 - if (pasteSessionRef.current === null) {
791 - pasteSessionRef.current = createTerminalPasteSession();
792 - }
793 - const pasteSession = pasteSessionRef.current;
794 -
795 - useEffect(() => {
796 - pasteSession.reset(canOperateTerminal && isRunning);
797 - return () => {
798 - pasteSession.reset(false);
799 - };
800 - }, [canOperateTerminal, isRunning, pasteSession, terminal.lifecycleVersion, terminalKey]);
658 + return result._tag === "Success";
659 + };
660
802 - const pasteFromClipboard = useCallback(async () => {
661 + const pasteFromClipboard = async () => {
662 await pasteSession.paste({
663 readText: Clipboard.getStringAsync,
664 write: writeInput,
@@ -807,205 +666,83 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
666 console.error(new TerminalClipboardReadError({ terminalId, cause }));
667 },
668 });
810 - }, [pasteSession, terminalId, writeInput]);
811 -
812 - const writeModifiedInput = useCallback(
813 - (data: string) => {
814 - if (pendingModifier === null) {
815 - void writeInput(data);
816 - return;
817 - }
669 + };
670
819 - setPendingModifierState({ terminalId, value: null });
820 - const resolved = resolveModifiedTerminalInput({
821 - data,
822 - modifier: pendingModifier,
823 - hostPlatform,
824 - });
825 - if (resolved.kind === "paste") {
826 - void pasteFromClipboard();
827 - return;
828 - }
829 - void writeInput(resolved.data);
830 - },
831 - [hostPlatform, pasteFromClipboard, pendingModifier, terminalId, writeInput],
832 - );
671 + const writeModifiedInput = (data: string) => {
672 + if (pendingModifier === null) {
673 + void writeInput(data);
674 + return;
675 + }
676
834 - const handleInput = useCallback(
835 - (data: string) => {
836 - if (data.length === 0) {
837 - return;
838 - }
677 + setPendingModifier(null);
678 + const resolved = resolveModifiedTerminalInput({
679 + data,
680 + modifier: pendingModifier,
681 + hostPlatform,
682 + });
683 + if (resolved.kind === "paste") {
684 + void pasteFromClipboard();
685 + return;
686 + }
687 + void writeInput(resolved.data);
688 + };
689
840 - writeModifiedInput(data);
841 - },
842 - [writeModifiedInput],
843 - );
690 + const handleInput = (data: string) => {
691 + if (data.length === 0) {
692 + return;
693 + }
694
845 - const handleResize = useCallback(
846 - (size: { readonly cols: number; readonly rows: number }) => {
847 - terminalDebugLog("native:onResize", {
848 - cols: size.cols,
849 - rows: size.rows,
850 - terminalKey,
851 - });
852 - setHasMeasuredSurface(true);
853 - if (readyBufferReplayKey !== bufferReplayKey) {
854 - scheduleBufferReplayReady();
855 - }
856 - if (routeEnvironmentId && routeThreadId) {
857 - cacheTerminalGridSize(
858 - {
859 - environmentId: routeEnvironmentId,
860 - threadId: routeThreadId,
861 - terminalId,
862 - },
863 - size,
864 - );
865 - }
866 - if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
867 - return;
868 - }
695 + writeModifiedInput(data);
696 + };
697
870 - setLastGridSize(size);
871 - },
872 - [
873 - lastGridSize.cols,
874 - lastGridSize.rows,
875 - bufferReplayKey,
876 - readyBufferReplayKey,
877 - routeEnvironmentId,
878 - routeThreadId,
879 - scheduleBufferReplayReady,
880 - terminalId,
698 + const handleResize = (size: { readonly cols: number; readonly rows: number }) => {
699 + terminalDebugLog("native:onResize", {
700 + cols: size.cols,
701 + rows: size.rows,
702 terminalKey,
882 - ],
883 - );
884 -
885 - const handleSelectTerminal = useCallback(
886 - (nextTerminalId: string) => {
887 - if (!selectedThread || nextTerminalId === terminalId) {
888 - return;
889 - }
890 -
891 - navigation.dispatch(
892 - StackActions.replace("ThreadTerminal", {
893 - environmentId: String(selectedThread.environmentId),
894 - threadId: String(selectedThread.id),
895 - terminalId: nextTerminalId,
896 - }),
703 + });
704 + if (routeEnvironmentId && routeThreadId) {
705 + cacheTerminalGridSize(
706 + {
707 + environmentId: routeEnvironmentId,
708 + threadId: routeThreadId,
709 + terminalId,
710 + },
711 + size,
712 );
898 - },
899 - [navigation, selectedThread, terminalId],
900 - );
713 + }
714 + terminalSessionDriver.reportGridSize(size);
715 + };
716
902 - const handleCloseTerminal = useCallback(() => {
903 - if (navigation.canGoBack()) {
904 - navigation.goBack();
717 + const handleSelectTerminal = (nextTerminalId: string) => {
718 + if (nextTerminalId === terminalId) {
719 return;
720 }
721 +
722 navigation.dispatch(
908 - StackActions.replace("Thread", {
909 - environmentId: params.environmentId,
910 - threadId: params.threadId,
723 + StackActions.replace("ThreadTerminal", {
724 + environmentId: String(selectedThread.environmentId),
725 + threadId: String(selectedThread.id),
726 + terminalId: nextTerminalId,
727 }),
728 );
913 - }, [navigation, params.environmentId, params.threadId]);
729 + };
730
915 - const navigateAwayAfterExit = useCallback(() => {
916 - const fallbackTerminalId = previousLiveTerminalId({
917 - sessions: terminalMenuSessions,
918 - exitedTerminalId: terminalId,
919 - });
920 - if (fallbackTerminalId !== null && selectedThread) {
921 - navigation.dispatch(
922 - StackActions.replace("ThreadTerminal", {
923 - environmentId: String(selectedThread.environmentId),
924 - threadId: String(selectedThread.id),
925 - terminalId: fallbackTerminalId,
926 - }),
927 - );
928 - return;
929 - }
731 + const handleCloseTerminal = () => {
732 if (navigation.canGoBack()) {
733 navigation.goBack();
734 return;
735 }
934 - if (selectedThread) {
935 - navigation.dispatch(
936 - StackActions.replace("Thread", {
937 - environmentId: String(selectedThread.environmentId),
938 - threadId: String(selectedThread.id),
939 - }),
940 - );
941 - }
942 - }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
943 -
944 - useTerminalLifecycle({
945 - terminalKey,
946 - canOperate: canOperateTerminal,
947 - observing: observingTerminal,
948 - attached: terminalAttachInput !== null && selectedThread !== null,
949 - terminal,
950 - reopen: async () => {
951 - if (
952 - terminalAttachInput === null ||
953 - selectedThread === null ||
954 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
955 - )
956 - return false;
957 - const result = await openTerminal({
958 - environmentId: selectedThread.environmentId,
959 - input: {
960 - threadId: selectedThread.id,
961 - terminalId,
962 - cwd: terminalAttachInput.cwd,
963 - worktreePath: terminalAttachInput.worktreePath,
964 - cols: terminalAttachInput.cols,
965 - rows: terminalAttachInput.rows,
966 - ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}),
967 - },
968 - });
969 - return result._tag === "Success";
970 - },
971 - onRunning: () => {
972 - pendingExitNavigationRef.current = null;
973 - },
974 - onExit: () => {
975 - if (
976 - selectedThread === null ||
977 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
978 - )
979 - return;
980 - void closeTerminal({
981 - environmentId: selectedThread.environmentId,
982 - input: { threadId: selectedThread.id, terminalId },
983 - });
984 - if (navigation.isFocused()) {
985 - navigateAwayAfterExit();
986 - return;
987 - }
988 - pendingExitNavigationRef.current = terminalKey;
989 - },
990 - });
991 -
992 - useEffect(
993 - () =>
994 - navigation.addListener("focus", () => {
995 - if (pendingExitNavigationRef.current !== terminalKey) {
996 - return;
997 - }
998 - pendingExitNavigationRef.current = null;
999 - navigateAwayAfterExit();
736 + navigation.dispatch(
737 + StackActions.replace("Thread", {
738 + environmentId: params.environmentId,
739 + threadId: params.threadId,
740 }),
1001 - [navigateAwayAfterExit, navigation, terminalKey],
1002 - );
741 + );
742 + };
743
1004 - const handleOpenNewTerminal = useCallback(() => {
1005 - if (
1006 - !selectedThread ||
1007 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
1008 - ) {
744 + const handleOpenNewTerminal = () => {
745 + if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
746 return;
747 }
748
@@ -1023,25 +760,22 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
760 }),
761 }),
762 );
1026 - }, [knownSessions, navigation, selectedThread, terminalId, terminalMenuSessions]);
763 + };
764
1028 - const handleDecreaseFontSize = useCallback(() => {
765 + const handleDecreaseFontSize = () => {
766 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
1030 - }, [fontSize, setTerminalFontSize]);
767 + };
768
1032 - const handleIncreaseFontSize = useCallback(() => {
769 + const handleIncreaseFontSize = () => {
770 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
1034 - }, [fontSize, setTerminalFontSize]);
771 + };
772
1036 - const handleClearTerminal = useCallback(() => {
1037 - if (
1038 - !selectedThread ||
1039 - !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
1040 - ) {
773 + const handleClearTerminal = () => {
774 + if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
775 return;
776 }
777
1044 - setPendingModifierState({ terminalId, value: null });
778 + setPendingModifier(null);
779 void clearTerminal({
780 environmentId: selectedThread.environmentId,
781 input: {
@@ -1049,67 +783,44 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
783 terminalId,
784 },
785 });
1052 - }, [clearTerminal, selectedThread, terminalId]);
786 + };
787
1054 - const handleToolbarActionPress = useCallback(
1055 - (action: TerminalToolbarAction) => {
1056 - if (action.kind === "modifier") {
1057 - setPendingModifierState((current) => ({
1058 - terminalId,
1059 - value:
1060 - (current.terminalId === terminalId ? current.value : null) === action.modifier
1061 - ? null
1062 - : action.modifier,
1063 - }));
1064 - return;
1065 - }
788 + const handleToolbarActionPress = (action: TerminalToolbarAction) => {
789 + if (action.kind === "modifier") {
790 + setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
791 + return;
792 + }
793
1067 - if (action.kind === "clear") {
1068 - handleClearTerminal();
1069 - return;
1070 - }
794 + if (action.kind === "clear") {
795 + handleClearTerminal();
796 + return;
797 + }
798
1072 - if (action.kind === "paste") {
1073 - setPendingModifierState({ terminalId, value: null });
1074 - void pasteFromClipboard();
1075 - return;
1076 - }
799 + if (action.kind === "paste") {
800 + setPendingModifier(null);
801 + void pasteFromClipboard();
802 + return;
803 + }
804
1078 - writeModifiedInput(action.data);
1079 - },
1080 - [handleClearTerminal, pasteFromClipboard, terminalId, writeModifiedInput],
1081 - );
805 + writeModifiedInput(action.data);
806 + };
807
1083 - const handleDismissKeyboard = useCallback(() => {
1084 - setIsAccessoryDismissed(true);
808 + const handleDismissKeyboard = () => {
809 + setAccessory((current) => ({ ...current, dismissed: true }));
810 void KeyboardController.dismiss();
1086 - }, []);
811 + };
812
1088 - const handleShowKeyboard = useCallback(() => {
813 + const handleShowKeyboard = () => {
814 if (!canOperateTerminal) return;
1090 - setIsAccessoryDismissed(false);
815 + setAccessory((current) => ({ ...current, dismissed: false }));
816 setKeyboardFocusRequest((current) => current + 1);
1092 - }, [canOperateTerminal]);
1093 - const handleRetryEnvironment = useCallback(() => {
817 + surfaceRef.current?.focusKeyboard();
818 + };
819 + const handleRetryEnvironment = () => {
820 if (routeEnvironmentId !== null) {
821 void retryEnvironment(routeEnvironmentId);
822 }
1097 - }, [retryEnvironment, routeEnvironmentId]);
1098 -
1099 - if (!selectedThread) {
1100 - if (!connectionsReady) {
1101 - return <LoadingScreen message="Opening terminal…" />;
1102 - }
1103 -
1104 - return (
1105 - <View className="flex-1 bg-screen">
1106 - <EmptyState
1107 - title="Thread unavailable"
1108 - detail="This terminal route needs an active thread and workspace."
1109 - />
1110 - </View>
1111 - );
1112 - }
823 + };
824
825 if (!selectedThreadProject?.workspaceRoot) {
826 return (
@@ -1128,7 +839,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
839
840 return (
841 <>
1131 - {capturedOutput !== null && selectedThread ? (
842 + {capturedOutput !== null ? (
843 <TerminalContextSheet
844 text={capturedOutput}
845 environmentId={selectedThread.environmentId}
@@ -1244,9 +955,10 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
955 }}
956 />
957 <TerminalSurface
958 + ref={surfaceRef}
959 autoFocus={canOperateTerminal && terminalAutoFocus}
960 readOnly={!canOperateTerminal}
1249 - buffer={terminal.version === 0 ? null : terminalSurfaceBuffer}
961 + buffer={terminal.version === 0 ? null : terminal.buffer}
962 output={terminal.version === 0 ? null : terminal.output}
963 fontSize={fontSize}
964 isRunning={isRunning}
@@ -1268,7 +980,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
980
981 {Platform.OS === "android" && !keyboardState.isVisible ? (
982 <View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">
1271 - {selectedThread && hasNativeTerminalSurface() ? (
983 + {hasNativeTerminalSurface() ? (
984 <Button label="Attach output" tone="text" onPress={requestCapture} />
985 ) : null}
986 <View className="flex-1" />
@@ -1279,7 +991,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
991 onPress={handleShowKeyboard}
992 />
993 </View>
1282 - ) : Platform.OS !== "android" && selectedThread && hasNativeTerminalSurface() ? (
994 + ) : Platform.OS !== "android" && hasNativeTerminalSurface() ? (
995 <Pressable
996 accessibilityRole="button"
997 onPress={() => {
apps/mobile/src/features/terminal/terminalBufferReplay.ts deleted
-27
@@ -1,27 +0,0 @@
1 -import { terminalDebugLog } from "./terminalDebugLog";
2 -
3 -export const TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS = 180;
4 -
5 -export function getTerminalBufferReplayKey(input: {
6 - readonly terminalKey: string;
7 - readonly fontSize: number;
8 -}): string {
9 - return `${input.terminalKey}:${input.fontSize}`;
10 -}
11 -
12 -export function getTerminalSurfaceReplayBuffer(input: {
13 - readonly buffer: string;
14 - readonly replayKey: string;
15 - readonly readyReplayKey: string | null;
16 -}): string {
17 - if (input.readyReplayKey !== null && input.readyReplayKey !== input.replayKey) {
18 - terminalDebugLog("replay:stale-key-hiding-buffer", {
19 - replayKey: input.replayKey,
20 - readyReplayKey: input.readyReplayKey,
21 - bufferLen: input.buffer.length,
22 - });
23 - return "";
24 - }
25 -
26 - return input.buffer;
27 -}
apps/mobile/src/features/terminal/terminalLaunchContext.ts
+8 -15
@@ -1,5 +1,5 @@
1 import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 -import { useEffect, useState } from "react";
2 +import { useState } from "react";
3
4 interface TerminalLocationLike {
5 readonly cwd: string;
@@ -82,10 +82,10 @@ export function resolveTerminalOpenLocation(input: {
82 };
83 }
84
85 +/** The first location resolved for a terminal target stays fixed for that target. */
86 export function useInitialTerminalLaunchLocation(input: {
86 - readonly targetKey: string | null;
87 + readonly targetKey: string;
88 readonly pendingLaunch: PendingTerminalLaunch | null;
88 - readonly hasResolvedPendingLaunch: boolean;
89 readonly isAuthenticated: boolean;
90 readonly canRead: boolean;
91 readonly canOperate: boolean;
@@ -93,12 +93,7 @@ export function useInitialTerminalLaunchLocation(input: {
93 readonly location: Parameters<typeof resolveTerminalOpenLocation>[0] | null;
94 }) {
95 let candidate: TerminalLocationLike | null = null;
96 - if (
97 - input.location !== null &&
98 - input.hasResolvedPendingLaunch &&
99 - input.isAuthenticated &&
100 - (input.canRead || input.canOperate)
101 - ) {
96 + if (input.location !== null && input.isAuthenticated && (input.canRead || input.canOperate)) {
97 if (input.pendingLaunch !== null) {
98 candidate = {
99 cwd: input.pendingLaunch.cwd,
@@ -110,11 +105,9 @@ export function useInitialTerminalLaunchLocation(input: {
105 }
106 }
107 const [entry, setEntry] = useState(() => ({ key: input.targetKey, location: candidate }));
113 - useEffect(() => {
114 - if (entry.key === input.targetKey && (entry.location !== null || candidate === null)) {
115 - return;
116 - }
108 + if (entry.key !== input.targetKey || (entry.location === null && candidate !== null)) {
109 setEntry({ key: input.targetKey, location: candidate });
118 - }, [candidate, entry.key, entry.location, input.targetKey]);
119 - return entry.key === input.targetKey ? entry.location : null;
110 + return candidate;
111 + }
112 + return entry.location;
113 }
apps/mobile/src/features/terminal/useTerminalExitNavigation.test.tsx new
+133
@@ -0,0 +1,133 @@
1 +import * as NodeModule from "node:module";
2 +import { act, useLayoutEffect } from "react";
3 +import { createRoot } from "react-dom/client";
4 +import { expect, it, vi } from "vite-plus/test";
5 +
6 +const harness = vi.hoisted(() => ({ navigation: undefined as unknown }));
7 +
8 +vi.mock("@react-navigation/native", async () => {
9 + const { createRequire } = await import("node:module");
10 + const requireNavigation = createRequire(
11 + createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
12 + );
13 + return {
14 + StackActions: requireNavigation("@react-navigation/routers").StackActions,
15 + useNavigation: () => harness.navigation,
16 + };
17 +});
18 +
19 +import { useTerminalExitNavigation } from "./useTerminalExitNavigation";
20 +
21 +const requireNavigation = NodeModule.createRequire(
22 + NodeModule.createRequire(import.meta.url).resolve("@react-navigation/native/package.json"),
23 +);
24 +const { StackRouter, StackActions, CommonActions } = requireNavigation(
25 + "@react-navigation/routers",
26 +) as {
27 + StackRouter: typeof import("@react-navigation/native").StackRouter;
28 + StackActions: typeof import("@react-navigation/native").StackActions;
29 + CommonActions: typeof import("@react-navigation/native").CommonActions;
30 +};
31 +
32 +type Action = Parameters<ReturnType<typeof StackRouter>["getStateForAction"]>[1];
33 +
34 +function setup(fallbackTerminalId: string | null) {
35 + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
36 + const router = StackRouter({});
37 + const options = {
38 + routeNames: ["Thread", "ThreadTerminal", "ThreadFiles"],
39 + routeParamList: {},
40 + routeGetIdList: {},
41 + };
42 + let state = router.getInitialState(options);
43 + const apply = (action: Action) => {
44 + const next = router.getStateForAction(state, action, options);
45 + if (!next) throw new Error(`Rejected ${action.type}`);
46 + state = router.getRehydratedState(next, options);
47 + };
48 + const thread = { environmentId: "environment", threadId: "thread" };
49 + apply(StackActions.replace("Thread", thread));
50 + apply(StackActions.push("ThreadTerminal", { ...thread, terminalId: "second" }));
51 + const terminalKey = state.routes.at(-1)!.key;
52 + const focusListeners = new Set<() => void>();
53 + // A screen's navigation object stamps its route as the source but leaves the
54 + // target unset, as React Navigation's screen navigation does.
55 + const dispatch = (action: Action) => apply({ source: terminalKey, ...action } as Action);
56 + harness.navigation = {
57 + dispatch,
58 + goBack: () => dispatch(CommonActions.goBack()),
59 + canGoBack: () => state.routes.length > 1,
60 + isFocused: () => state.routes.at(-1)?.key === terminalKey,
61 + addListener: (_event: "focus", listener: () => void) => {
62 + focusListeners.add(listener);
63 + return () => focusListeners.delete(listener);
64 + },
65 + };
66 + let exitNavigation!: ReturnType<typeof useTerminalExitNavigation>;
67 + function Probe() {
68 + const value = useTerminalExitNavigation({
69 + ...thread,
70 + readFallbackTerminalId: () => fallbackTerminalId,
71 + });
72 + useLayoutEffect(() => {
73 + exitNavigation = value;
74 + });
75 + return null;
76 + }
77 + const root = createRoot(document.createElement("div"));
78 + act(() => root.render(<Probe />));
79 + return {
80 + exitNavigation,
81 + routes: () => state.routes.map((route) => [route.name, route.params]),
82 + openFiles: () => apply(StackActions.push("ThreadFiles", thread)),
83 + returnToTerminal: () => {
84 + apply(StackActions.pop());
85 + for (const listener of focusListeners) listener();
86 + },
87 + [Symbol.dispose]: () => act(() => root.unmount()),
88 + };
89 +}
90 +
91 +const thread = { environmentId: "environment", threadId: "thread" };
92 +
93 +it("leaves the screen on top alone when a terminal behind it exits, then goes back on return", () => {
94 + using screen = setup(null);
95 + screen.openFiles();
96 +
97 + screen.exitNavigation.exited();
98 + expect(screen.routes()).toEqual([
99 + ["Thread", thread],
100 + ["ThreadTerminal", { ...thread, terminalId: "second" }],
101 + ["ThreadFiles", thread],
102 + ]);
103 +
104 + screen.returnToTerminal();
105 + expect(screen.routes()).toEqual([["Thread", thread]]);
106 +});
107 +
108 +it("does not replace the screen on top with the fallback terminal", () => {
109 + using screen = setup("first");
110 + screen.openFiles();
111 +
112 + screen.exitNavigation.exited();
113 + expect(screen.routes().at(-1)).toEqual(["ThreadFiles", thread]);
114 +
115 + screen.returnToTerminal();
116 + expect(screen.routes()).toEqual([
117 + ["Thread", thread],
118 + ["ThreadTerminal", { ...thread, terminalId: "first" }],
119 + ]);
120 +});
121 +
122 +it("stays on a terminal that restarted before the user returned", () => {
123 + using screen = setup(null);
124 + screen.openFiles();
125 +
126 + screen.exitNavigation.exited();
127 + screen.exitNavigation.restarted();
128 + screen.returnToTerminal();
129 + expect(screen.routes()).toEqual([
130 + ["Thread", thread],
131 + ["ThreadTerminal", { ...thread, terminalId: "second" }],
132 + ]);
133 +});
apps/mobile/src/features/terminal/useTerminalExitNavigation.ts new
+66
@@ -0,0 +1,66 @@
1 +import { StackActions, useNavigation } from "@react-navigation/native";
2 +import { useEffect, useEffectEvent, useRef } from "react";
3 +
4 +/**
5 + * Leaves a terminal screen whose shell exited: to another live terminal of the
6 + * thread, else back. Screen navigation acts on the top route of the stack, so
7 + * a shell that exits while another screen is on top waits until its own screen
8 + * is focused again.
9 + */
10 +export function useTerminalExitNavigation(target: {
11 + readonly environmentId: string;
12 + readonly threadId: string;
13 + readonly readFallbackTerminalId: () => string | null;
14 +}) {
15 + const navigation = useNavigation();
16 + const pendingRef = useRef(false);
17 +
18 + const navigateAway = useEffectEvent(() => {
19 + const fallbackTerminalId = target.readFallbackTerminalId();
20 + if (fallbackTerminalId !== null) {
21 + navigation.dispatch(
22 + StackActions.replace("ThreadTerminal", {
23 + environmentId: target.environmentId,
24 + threadId: target.threadId,
25 + terminalId: fallbackTerminalId,
26 + }),
27 + );
28 + return;
29 + }
30 + if (navigation.canGoBack()) {
31 + navigation.goBack();
32 + return;
33 + }
34 + navigation.dispatch(
35 + StackActions.replace("Thread", {
36 + environmentId: target.environmentId,
37 + threadId: target.threadId,
38 + }),
39 + );
40 + });
41 +
42 + // 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
43 + useEffect(
44 + () =>
45 + navigation.addListener("focus", () => {
46 + if (!pendingRef.current) return;
47 + pendingRef.current = false;
48 + navigateAway();
49 + }),
50 + [navigation],
51 + );
52 +
53 + return {
54 + exited: () => {
55 + if (navigation.isFocused()) {
56 + navigateAway();
57 + return;
58 + }
59 + pendingRef.current = true;
60 + },
61 + /** A shell that runs again before the screen regains focus keeps the screen. */
62 + restarted: () => {
63 + pendingRef.current = false;
64 + },
65 + };
66 +}
apps/mobile/src/features/terminal/useTerminalGridSync.test.ts deleted
-107
@@ -1,107 +0,0 @@
1 -import * as NodeModule from "node:module";
2 -import { EMPTY_TERMINAL_BUFFER_STATE } from "@t3tools/client-runtime/state/terminal";
3 -import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4 -import { act, createElement, type ReactNode } from "react";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 -
7 -import { useTerminalGridSync } from "./useTerminalGridSync";
8 -
9 -const access = vi.hoisted(() => ({ environments: new Set<string>() }));
10 -vi.mock("../../state/session", () => ({
11 - readEnvironmentScope: (environmentId: string, scope: string) =>
12 - scope === "terminal:operate" && access.environments.has(environmentId),
13 -}));
14 -
15 -// Mobile already depends on ReactDOM but does not install its browser type declarations.
16 -const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {
17 - createRoot(container: Element): {
18 - render(children: ReactNode): void;
19 - unmount(): void;
20 - };
21 -};
22 -
23 -type Input = Parameters<typeof useTerminalGridSync>[0];
24 -let root: ReturnType<typeof createRoot>;
25 -const resize = vi.fn<Input["resize"]>();
26 -
27 -function GridProbe(input: Input) {
28 - useTerminalGridSync(input);
29 - return null;
30 -}
31 -
32 -function session({
33 - generation = 1,
34 - version = 1,
35 - status = "running",
36 -}: {
37 - readonly generation?: number;
38 - readonly version?: number;
39 - readonly status?: Input["terminal"]["status"];
40 -} = {}): Input["terminal"] {
41 - return { output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation }, version, status };
42 -}
43 -
44 -function input(): Input {
45 - return {
46 - environmentId: EnvironmentId.make("environment"),
47 - threadId: ThreadId.make("thread"),
48 - terminalId: "term-1",
49 - canOperate: true,
50 - terminal: session(),
51 - size: { cols: 80, rows: 24 },
52 - resize,
53 - };
54 -}
55 -
56 -function render(value: Input) {
57 - return act(() => root.render(createElement(GridProbe, value)));
58 -}
59 -
60 -beforeEach(() => {
61 - resize.mockClear();
62 - access.environments.clear();
63 - access.environments.add("environment");
64 - // The probe renders no DOM, but ReactDOM needs an event target to run real effects.
65 - const document = {
66 - nodeType: 9,
67 - addEventListener() {},
68 - removeEventListener() {},
69 - };
70 - const container = {
71 - nodeType: 1,
72 - tagName: "DIV",
73 - namespaceURI: "http://www.w3.org/1999/xhtml",
74 - ownerDocument: document,
75 - addEventListener() {},
76 - removeEventListener() {},
77 - };
78 - vi.stubGlobal("document", document);
79 - vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
80 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
81 - root = createRoot(container as unknown as HTMLElement);
82 -});
83 -
84 -afterEach(async () => {
85 - await act(() => root.unmount());
86 - vi.unstubAllGlobals();
87 -});
88 -
89 -it("replays an unchanged grid after reconnecting with a new attachment generation", async () => {
90 - const current = { ...input(), size: { cols: 120, rows: 40 } };
91 - await render(current);
92 - expect(resize).toHaveBeenCalledOnce();
93 -
94 - await render({ ...current, terminal: session({ generation: 2, version: 0 }) });
95 - expect(resize).toHaveBeenCalledOnce();
96 -
97 - await render({ ...current, terminal: session({ generation: 2 }) });
98 - expect(resize).toHaveBeenCalledTimes(2);
99 - expect(resize).toHaveBeenLastCalledWith({
100 - environmentId: "environment",
101 - input: { threadId: "thread", terminalId: "term-1", cols: 120, rows: 40 },
102 - });
103 -
104 - // React may observe the next snapshot without rendering the empty seed first.
105 - await render({ ...current, terminal: session({ generation: 3 }) });
106 - expect(resize).toHaveBeenCalledTimes(3);
107 -});
apps/mobile/src/features/terminal/useTerminalGridSync.ts deleted
-51
@@ -1,51 +0,0 @@
1 -import type { TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
2 -import {
3 - AuthTerminalOperateScope,
4 - type EnvironmentId,
5 - type TerminalResizeInput,
6 - type ThreadId,
7 -} from "@t3tools/contracts";
8 -import { useEffect } from "react";
9 -
10 -import type { TerminalGridSize } from "./terminalUiState";
11 -import { readEnvironmentScope } from "../../state/session";
12 -
13 -export function useTerminalGridSync({
14 - environmentId,
15 - threadId,
16 - terminalId,
17 - canOperate,
18 - terminal,
19 - size,
20 - resize,
21 -}: {
22 - readonly environmentId: EnvironmentId | null;
23 - readonly threadId: ThreadId | null;
24 - readonly terminalId: string;
25 - readonly canOperate: boolean;
26 - readonly terminal: Pick<TerminalSessionState, "output" | "status" | "version">;
27 - readonly size: TerminalGridSize;
28 - readonly resize: (target: {
29 - readonly environmentId: EnvironmentId;
30 - readonly input: TerminalResizeInput;
31 - }) => void;
32 -}): void {
33 - const generation =
34 - canOperate && terminal.version > 0 && terminal.status === "running"
35 - ? terminal.output.generation
36 - : null;
37 -
38 - useEffect(() => {
39 - if (
40 - generation === null ||
41 - environmentId === null ||
42 - threadId === null ||
43 - !readEnvironmentScope(environmentId, AuthTerminalOperateScope)
44 - )
45 - return;
46 - resize({
47 - environmentId,
48 - input: { threadId, terminalId, cols: size.cols, rows: size.rows },
49 - });
50 - }, [environmentId, generation, resize, size.cols, size.rows, terminalId, threadId]);
51 -}
apps/mobile/src/features/terminal/useTerminalLifecycle.test.ts deleted
-99
@@ -1,99 +0,0 @@
1 -import * as NodeModule from "node:module";
2 -import { act, createElement, type ReactNode } from "react";
3 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4 -
5 -import { useTerminalLifecycle } from "./useTerminalLifecycle";
6 -
7 -const { createRoot } = NodeModule.createRequire(import.meta.url)("react-dom/client") as {
8 - createRoot(container: Element): {
9 - render(children: ReactNode): void;
10 - unmount(): void;
11 - };
12 -};
13 -
14 -type Input = Parameters<typeof useTerminalLifecycle>[0];
15 -let root: ReturnType<typeof createRoot>;
16 -const reopen = vi.fn<Input["reopen"]>();
17 -const onRunning = vi.fn<Input["onRunning"]>();
18 -const onExit = vi.fn<Input["onExit"]>();
19 -
20 -function LifecycleProbe(input: Input) {
21 - useTerminalLifecycle(input);
22 - return null;
23 -}
24 -
25 -function input(changes: Partial<Input> = {}): Input {
26 - return {
27 - terminalKey: "environment:thread:term-1",
28 - canOperate: true,
29 - observing: false,
30 - attached: true,
31 - terminal: { status: "running", version: 1 },
32 - reopen,
33 - onRunning,
34 - onExit,
35 - ...changes,
36 - };
37 -}
38 -
39 -function render(value: Input) {
40 - return act(() => root.render(createElement(LifecycleProbe, value)));
41 -}
42 -
43 -beforeEach(() => {
44 - reopen.mockReset().mockResolvedValue(true);
45 - onRunning.mockClear();
46 - onExit.mockClear();
47 - const document = {
48 - nodeType: 9,
49 - addEventListener() {},
50 - removeEventListener() {},
51 - };
52 - const container = {
53 - nodeType: 1,
54 - tagName: "DIV",
55 - namespaceURI: "http://www.w3.org/1999/xhtml",
56 - ownerDocument: document,
57 - addEventListener() {},
58 - removeEventListener() {},
59 - };
60 - vi.stubGlobal("document", document);
61 - vi.stubGlobal("window", { document, HTMLIFrameElement: EventTarget });
62 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
63 - root = createRoot(container as unknown as HTMLElement);
64 -});
65 -
66 -afterEach(async () => {
67 - await act(() => root.unmount());
68 - vi.unstubAllGlobals();
69 -});
70 -
71 -it("does not respawn a terminal that exited after operate was revoked", async () => {
72 - await render(input());
73 - await render(input({ canOperate: false }));
74 - await render(input({ canOperate: false, terminal: { status: "exited", version: 2 } }));
75 - await render(input({ terminal: { status: "exited", version: 1 } }));
76 - expect(reopen).not.toHaveBeenCalled();
77 - expect(onExit).not.toHaveBeenCalled();
78 -});
79 -
80 -it("reopens an ended terminal on an explicit new route visit", async () => {
81 - await render(input({ canOperate: false, terminal: { status: "exited", version: 1 } }));
82 - await render(input({ terminalKey: "environment:thread:term-2" }));
83 - await render(input({ terminal: { status: "exited", version: 1 } }));
84 - expect(reopen).toHaveBeenCalledOnce();
85 -
86 - await render(input({ terminal: { status: "exited", version: 2 } }));
87 - expect(reopen).toHaveBeenCalledOnce();
88 - await render(input({ terminal: { status: "running", version: 3 } }));
89 - await render(input({ terminal: { status: "exited", version: 4 } }));
90 - expect(onExit).toHaveBeenCalledOnce();
91 -});
92 -
93 -it("keeps a detached terminal from being mistaken for a live exit", async () => {
94 - await render(input());
95 - await render(input({ attached: false, terminal: { status: "closed", version: 0 } }));
96 - await render(input({ terminal: { status: "exited", version: 1 } }));
97 - expect(onExit).not.toHaveBeenCalled();
98 - expect(reopen).toHaveBeenCalledOnce();
99 -});
apps/mobile/src/features/terminal/useTerminalLifecycle.ts deleted
-76
@@ -1,76 +0,0 @@
1 -import type { TerminalSessionState } from "@t3tools/client-runtime/state/terminal";
2 -import { useEffect, useEffectEvent, useRef } from "react";
3 -
4 -export function useTerminalLifecycle({
5 - terminalKey,
6 - canOperate,
7 - observing,
8 - attached,
9 - terminal,
10 - reopen,
11 - onRunning,
12 - onExit,
13 -}: {
14 - readonly terminalKey: string;
15 - readonly canOperate: boolean;
16 - readonly observing: boolean;
17 - readonly attached: boolean;
18 - readonly terminal: Pick<TerminalSessionState, "status" | "version">;
19 - readonly reopen: () => Promise<boolean>;
20 - readonly onRunning: () => void;
21 - readonly onExit: () => void;
22 -}) {
23 - const lifecycle = useRef({
24 - key: terminalKey,
25 - wasRunning: false,
26 - observed: false,
27 - reopened: false,
28 - });
29 - const reopenTerminal = useEffectEvent(reopen);
30 - const handleRunning = useEffectEvent(onRunning);
31 - const handleExit = useEffectEvent(onExit);
32 -
33 - useEffect(() => {
34 - if (lifecycle.current.key !== terminalKey) {
35 - lifecycle.current = {
36 - key: terminalKey,
37 - wasRunning: false,
38 - observed: false,
39 - reopened: false,
40 - };
41 - }
42 - const current = lifecycle.current;
43 - if (!canOperate) {
44 - if (observing || terminal.version > 0 || current.wasRunning) current.observed = true;
45 - current.wasRunning = false;
46 - return;
47 - }
48 - if (!attached) {
49 - current.wasRunning = false;
50 - return;
51 - }
52 - if (terminal.version === 0) return;
53 -
54 - if (terminal.status === "running" || terminal.status === "starting") {
55 - current.wasRunning = true;
56 - current.reopened = false;
57 - handleRunning();
58 - return;
59 - }
60 - if (terminal.status !== "closed" && terminal.status !== "exited") return;
61 -
62 - if (current.wasRunning) {
63 - current.wasRunning = false;
64 - current.reopened = true;
65 - handleExit();
66 - return;
67 - }
68 - // An explicit visit can reopen a cached ended session. Granting a viewer
69 - // operate permission must leave the history they were reading intact.
70 - if (current.observed || current.reopened) return;
71 - current.reopened = true;
72 - void reopenTerminal().then((succeeded) => {
73 - if (!succeeded && lifecycle.current === current) current.reopened = false;
74 - });
75 - }, [attached, canOperate, observing, terminal.status, terminal.version, terminalKey]);
76 -}
apps/mobile/src/reactCompilerCoverage.test.ts
-1
@@ -19,7 +19,6 @@ const KNOWN_BAILOUTS: Record<string, string> = {
19 "src/components/ui/Menu.tsx": "ref read during render",
20 "src/features/diffs/nativeReviewDiffSurface.ts": "ref read during render",
21 "src/features/home/thread-swipe-actions.tsx": "ref read during render",
22 - "src/features/terminal/ThreadTerminalRouteScreen.tsx": "ref read during render",
22 "src/features/threads/PendingUserInputCard.tsx": "mutates a frozen value",
23 "src/features/threads/ThreadArrangementSheet.tsx": "ref read during render",
24 "src/features/voice-input/VoiceInputProvider.tsx": "ref read during render",
apps/mobile/vite.config.ts
+1
@@ -16,6 +16,7 @@ const reactTests = [
16 "src/native/useRetryingImageSource.test.tsx",
17 "src/state/queries.debounce.test.tsx",
18 "src/state/use-selected-thread-git-actions.test.tsx",
19 + "src/features/terminal/useTerminalExitNavigation.test.tsx",
20 ];
21
22 export default defineConfig({
packages/client-runtime/src/state/terminal.test.ts new
+247
@@ -0,0 +1,247 @@
1 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
3 +import { expect, it } from "vite-plus/test";
4 +
5 +import {
6 + createTerminalSession,
7 + INITIAL_TERMINAL_LIFECYCLE,
8 + transitionTerminalLifecycle,
9 + type TerminalLifecycleEvent,
10 + type TerminalSessionMode,
11 +} from "./terminal.ts";
12 +import { EMPTY_TERMINAL_BUFFER_STATE, type TerminalBufferState } from "./terminalSession.ts";
13 +
14 +function run(events: ReadonlyArray<TerminalLifecycleEvent>) {
15 + let state = INITIAL_TERMINAL_LIFECYCLE;
16 + const commands: Array<string> = [];
17 + for (const event of events) {
18 + const step = transitionTerminalLifecycle(state, event);
19 + state = step.state;
20 + if (step.command !== null) commands.push(step.command);
21 + }
22 + return commands;
23 +}
24 +
25 +const status = (value: TerminalBufferState["status"], version = 1): TerminalLifecycleEvent => ({
26 + type: "status",
27 + status: value,
28 + version,
29 +});
30 +
31 +it("does not respawn a terminal that exited after operate was revoked", () => {
32 + expect(
33 + run([status("running"), { type: "detached", canOperate: false }, status("exited")]),
34 + ).toEqual([]);
35 +});
36 +
37 +it("reopens an ended terminal on an explicit visit, once until it runs again", () => {
38 + expect(run([status("exited"), status("exited", 2)])).toEqual(["reopen"]);
39 + expect(run([status("exited"), status("running", 3), status("exited", 4)])).toEqual([
40 + "reopen",
41 + "exit",
42 + ]);
43 + expect(run([status("exited"), { type: "reopen-failed" }, status("exited", 2)])).toEqual([
44 + "reopen",
45 + "reopen",
46 + ]);
47 +});
48 +
49 +it("keeps a detached terminal from being mistaken for a live exit", () => {
50 + expect(
51 + run([status("running"), { type: "detached", canOperate: true }, status("exited")]),
52 + ).toEqual(["reopen"]);
53 +});
54 +
55 +it("leaves the history a viewer was reading when operate is granted", () => {
56 + expect(run([{ type: "observed" }, status("exited")])).toEqual([]);
57 +});
58 +
59 +const environmentId = EnvironmentId.make("environment");
60 +const threadId = ThreadId.make("thread");
61 +
62 +function setup(options: { readonly initialInput?: string } = {}) {
63 + // Tests flush the registry's scheduled work to control when driver finalizers run.
64 + const scheduled: Array<() => void> = [];
65 + const registry = AtomRegistry.make({
66 + scheduleTask: (task) => {
67 + scheduled.push(task);
68 + return () => {};
69 + },
70 + });
71 + const flush = () => {
72 + for (const task of scheduled.splice(0)) task();
73 + };
74 + const attachment = Atom.make<AsyncResult.AsyncResult<TerminalBufferState, unknown>>(
75 + AsyncResult.initial(true),
76 + );
77 + const observation = Atom.make<AsyncResult.AsyncResult<TerminalBufferState, unknown>>(
78 + AsyncResult.initial(true),
79 + );
80 + const access = { canOperate: true };
81 + const calls: Array<{ readonly command: string; readonly input: unknown }> = [];
82 + const command = (name: string) => ({
83 + label: name,
84 + run: async (_registry: AtomRegistry.AtomRegistry, value: { readonly input: unknown }) => {
85 + calls.push({ command: name, input: value.input });
86 + return AsyncResult.success(undefined);
87 + },
88 + });
89 + const exits: Array<true> = [];
90 + const live: Array<boolean> = [];
91 + const session = createTerminalSession(
92 + {
93 + attach: () => attachment,
94 + observe: () => observation,
95 + open: command("open"),
96 + resize: command("resize"),
97 + write: command("write"),
98 + close: command("close"),
99 + },
100 + {
101 + target: { environmentId, threadId, terminalId: "term-1" },
102 + gridSize: { cols: 120, rows: 40 },
103 + initialInput: options.initialInput,
104 + canOperate: () => access.canOperate,
105 + onExit: () => exits.push(true),
106 + onLiveChange: (value) => live.push(value),
107 + },
108 + );
109 + const attached: TerminalSessionMode = {
110 + kind: "attached",
111 + input: { threadId, terminalId: "term-1", cwd: "/repo", cols: 80, rows: 24 },
112 + };
113 + const snapshot = (state: Partial<TerminalBufferState> & { readonly generation?: number }) => {
114 + const { generation = 1, ...rest } = state;
115 + return AsyncResult.success({
116 + ...EMPTY_TERMINAL_BUFFER_STATE,
117 + output: { ...EMPTY_TERMINAL_BUFFER_STATE.output, generation },
118 + ...rest,
119 + });
120 + };
121 + const emit = (state: Partial<TerminalBufferState> & { readonly generation?: number }) =>
122 + registry.set(attachment, snapshot(state));
123 + // A new attach subscription starts from an empty seed.
124 + const detach = () => registry.set(attachment, AsyncResult.initial(true));
125 + const observe = (state: Partial<TerminalBufferState>) =>
126 + registry.set(observation, snapshot(state));
127 + const mount = (mode: TerminalSessionMode) => registry.mount(session.driver(mode));
128 + const of = (name: string) => calls.filter((call) => call.command === name).map((c) => c.input);
129 + return { session, attached, access, flush, detach, emit, observe, mount, calls, of, exits, live };
130 +}
131 +
132 +it("replays the measured grid on every new attachment generation", () => {
133 + const { session, attached, emit, mount, of } = setup();
134 + mount(attached);
135 + emit({ status: "running", version: 1 });
136 + expect(of("resize")).toEqual([{ threadId, terminalId: "term-1", cols: 120, rows: 40 }]);
137 +
138 + session.reportGridSize({ cols: 100, rows: 30 });
139 + expect(of("resize")).toHaveLength(2);
140 + session.reportGridSize({ cols: 100, rows: 30 });
141 + expect(of("resize")).toHaveLength(2);
142 +
143 + // A reconnect seeds an empty state first, then the new generation's snapshot.
144 + emit({ status: "running", version: 0, generation: 2 });
145 + expect(of("resize")).toHaveLength(2);
146 + emit({ status: "running", version: 1, generation: 2 });
147 + expect(of("resize")).toHaveLength(3);
148 + emit({ status: "running", version: 2, generation: 3 });
149 + expect(of("resize")).toEqual([
150 + { threadId, terminalId: "term-1", cols: 120, rows: 40 },
151 + { threadId, terminalId: "term-1", cols: 100, rows: 30 },
152 + { threadId, terminalId: "term-1", cols: 100, rows: 30 },
153 + { threadId, terminalId: "term-1", cols: 100, rows: 30 },
154 + ]);
155 +});
156 +
157 +it("writes the launch's initial input once the first snapshot lands", () => {
158 + const { attached, emit, mount, calls, of } = setup({ initialInput: "pnpm dev\r" });
159 + mount(attached);
160 + expect(of("write")).toEqual([]);
161 + emit({ status: "running", version: 1 });
162 + emit({ status: "running", version: 2 });
163 + expect(of("write")).toEqual([{ threadId, terminalId: "term-1", data: "pnpm dev\r" }]);
164 + // The shell gets the measured grid before the launched command runs.
165 + expect(calls.map((call) => call.command)).toEqual(["resize", "write"]);
166 +});
167 +
168 +it("closes and reports a shell that exits while attached", () => {
169 + const { attached, emit, mount, of, exits, live } = setup();
170 + mount(attached);
171 + emit({ status: "running", version: 1, lifecycleVersion: 0 });
172 + emit({ status: "exited", version: 2 });
173 + expect(of("close")).toEqual([{ threadId, terminalId: "term-1" }]);
174 + expect(of("open")).toEqual([]);
175 + expect(exits).toHaveLength(1);
176 + expect(live).toEqual([true, false]);
177 +});
178 +
179 +it("does not reopen an ended shell after a viewer is granted operate", () => {
180 + const { attached, flush, access, emit, observe, mount, of } = setup();
181 + access.canOperate = false;
182 + const unmountViewer = mount({ kind: "observing" });
183 + observe({ status: "exited", version: 1 });
184 + access.canOperate = true;
185 + unmountViewer();
186 + flush();
187 + mount(attached);
188 + emit({ status: "exited", version: 1 });
189 + expect(of("open")).toEqual([]);
190 +});
191 +
192 +it("does not reopen on grant when the viewer had no snapshot yet", () => {
193 + const { attached, flush, access, emit, mount, of } = setup();
194 + access.canOperate = false;
195 + const unmountViewer = mount({ kind: "observing" });
196 + access.canOperate = true;
197 + unmountViewer();
198 + flush();
199 + mount(attached);
200 + emit({ status: "exited", version: 1 });
201 + expect(of("open")).toEqual([]);
202 +});
203 +
204 +it("leaves a shell that exited after operate was revoked mid-run", () => {
205 + const { attached, flush, access, detach, emit, mount, of, exits } = setup();
206 + const unmountAttached = mount(attached);
207 + emit({ status: "running", version: 1 });
208 + access.canOperate = false;
209 + unmountAttached();
210 + flush();
211 + detach();
212 + access.canOperate = true;
213 + mount(attached);
214 + emit({ status: "exited", version: 2 });
215 + expect(of("open")).toEqual([]);
216 + expect(of("close")).toEqual([]);
217 + expect(exits).toEqual([]);
218 +});
219 +
220 +it("reopens instead of closing a shell that ended while detached", () => {
221 + const { attached, flush, detach, emit, mount, of, exits } = setup();
222 + const unmountAttached = mount(attached);
223 + emit({ status: "running", version: 1 });
224 + unmountAttached();
225 + flush();
226 + detach();
227 + mount(attached);
228 + emit({ status: "exited", version: 2 });
229 + expect(of("close")).toEqual([]);
230 + expect(exits).toEqual([]);
231 + expect(of("open")).toHaveLength(1);
232 +});
233 +
234 +it("keeps a replaced attachment's late release from resetting the new one", () => {
235 + const { attached, flush, emit, mount, of, exits } = setup();
236 + const unmountFirst = mount(attached);
237 + emit({ status: "running", version: 1 });
238 + mount({
239 + kind: "attached",
240 + input: { threadId, terminalId: "term-1", cwd: "/repo/worktree", cols: 80, rows: 24 },
241 + });
242 + unmountFirst();
243 + flush();
244 + emit({ status: "exited", version: 2 });
245 + expect(of("close")).toHaveLength(1);
246 + expect(exits).toHaveLength(1);
247 +});
packages/client-runtime/src/state/terminal.ts
+327 -3
@@ -1,21 +1,37 @@
1 -import { type TerminalSummary, WS_METHODS } from "@t3tools/contracts";
1 +import {
2 + type EnvironmentId,
3 + type TerminalAttachInput,
4 + type TerminalCloseInput,
5 + type TerminalOpenInput,
6 + type TerminalResizeInput,
7 + type TerminalSummary,
8 + type TerminalWriteInput,
9 + type ThreadId,
10 + WS_METHODS,
11 +} from "@t3tools/contracts";
12 import * as Effect from "effect/Effect";
13 +import * as Option from "effect/Option";
14 import * as Stream from "effect/Stream";
4 -import { Atom } from "effect/reactivity";
15 +import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
16
17 import {
18 + type AtomCommand,
19 createAtomCommandScheduler,
20 createEnvironmentRpcCommand,
21 createEnvironmentRpcSubscriptionAtomFamily,
22 createEnvironmentSubscriptionAtomFamily,
23 + runAtomCommand,
24 } from "./runtime.ts";
25 import type { EnvironmentRegistry } from "../connection/registry.ts";
26 import { subscribe, subscribeDynamic, type EnvironmentRpcInput } from "../rpc/client.ts";
27 import {
28 applyTerminalAttachStreamEvent,
29 applyTerminalMetadataStreamEvent,
30 + EMPTY_TERMINAL_BUFFER_STATE,
31 nextTerminalAttachSeedState,
32 + type TerminalBufferState,
33 } from "./terminalSession.ts";
34 +import { terminalOutputText } from "./terminalOutput.ts";
35
36 export function createTerminalEnvironmentAtoms<R, E>(
37 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, E>,
@@ -37,7 +53,7 @@ export function createTerminalEnvironmentAtoms<R, E>(
53 readonly input: { readonly threadId: string; readonly terminalId?: string | undefined };
54 }) => JSON.stringify([environmentId, input.threadId, input.terminalId ?? null]);
55 const lifecycleConcurrency = { mode: "serial" as const, key: terminalThreadKey };
40 - return {
56 + const atoms = {
57 observe: createEnvironmentSubscriptionAtomFamily(runtime, {
58 label: "environment-data:terminal:observe",
59 subscribe: (input: EnvironmentRpcInput<typeof WS_METHODS.terminalObserve>) =>
@@ -112,6 +128,314 @@ export function createTerminalEnvironmentAtoms<R, E>(
128 concurrency: lifecycleConcurrency,
129 }),
130 };
131 + return {
132 + ...atoms,
133 + createSession: (options: TerminalSessionOptions) => createTerminalSession(atoms, options),
134 + };
135 +}
136 +
137 +export interface TerminalLifecycleState {
138 + readonly wasRunning: boolean;
139 + /** The user has seen this terminal without operate permission. */
140 + readonly observed: boolean;
141 + readonly reopened: boolean;
142 +}
143 +
144 +export const INITIAL_TERMINAL_LIFECYCLE: TerminalLifecycleState = {
145 + wasRunning: false,
146 + observed: false,
147 + reopened: false,
148 +};
149 +
150 +export type TerminalLifecycleEvent =
151 + /** A viewer without operate permission is following this terminal. */
152 + | { readonly type: "observed" }
153 + | { readonly type: "detached"; readonly canOperate: boolean }
154 + | {
155 + readonly type: "status";
156 + readonly status: TerminalBufferState["status"];
157 + readonly version: number;
158 + }
159 + | { readonly type: "reopen-failed" };
160 +
161 +export type TerminalLifecycleCommand = "exit" | "reopen" | null;
162 +
163 +export function transitionTerminalLifecycle(
164 + state: TerminalLifecycleState,
165 + event: TerminalLifecycleEvent,
166 +): { readonly state: TerminalLifecycleState; readonly command: TerminalLifecycleCommand } {
167 + switch (event.type) {
168 + case "observed":
169 + return { state: { ...state, observed: true }, command: null };
170 + case "detached":
171 + return {
172 + state: {
173 + ...state,
174 + // Losing operate while the shell runs leaves the viewer reading its history.
175 + observed: state.observed || (!event.canOperate && state.wasRunning),
176 + wasRunning: false,
177 + },
178 + command: null,
179 + };
180 + case "reopen-failed":
181 + return { state: { ...state, reopened: false }, command: null };
182 + case "status": {
183 + if (event.version === 0) return { state, command: null };
184 + if (event.status === "running" || event.status === "starting") {
185 + return { state: { ...state, wasRunning: true, reopened: false }, command: null };
186 + }
187 + if (event.status !== "closed" && event.status !== "exited") return { state, command: null };
188 + if (state.wasRunning) {
189 + return { state: { ...state, wasRunning: false, reopened: true }, command: "exit" };
190 + }
191 + // An explicit visit can reopen a cached ended session. Granting a viewer
192 + // operate permission must leave the history they were reading intact.
193 + if (state.observed || state.reopened) return { state, command: null };
194 + return { state: { ...state, reopened: true }, command: "reopen" };
195 + }
196 + }
197 +}
198 +
199 +export interface TerminalGridSize {
200 + readonly cols: number;
201 + readonly rows: number;
202 +}
203 +
204 +export type TerminalSessionMode =
205 + | { readonly kind: "observing" }
206 + | { readonly kind: "attached"; readonly input: TerminalAttachInput };
207 +
208 +type EnvironmentCommand<Input> = AtomCommand<
209 + { readonly environmentId: EnvironmentId; readonly input: Input },
210 + unknown,
211 + unknown
212 +>;
213 +
214 +export interface TerminalSessionAtoms {
215 + readonly attach: (target: {
216 + readonly environmentId: EnvironmentId;
217 + readonly input: TerminalAttachInput;
218 + }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;
219 + readonly observe: (target: {
220 + readonly environmentId: EnvironmentId;
221 + readonly input: { readonly threadId: ThreadId; readonly terminalId: string };
222 + }) => Atom.Atom<AsyncResult.AsyncResult<TerminalBufferState, unknown>>;
223 + readonly open: EnvironmentCommand<TerminalOpenInput>;
224 + readonly resize: EnvironmentCommand<TerminalResizeInput>;
225 + readonly write: EnvironmentCommand<TerminalWriteInput>;
226 + readonly close: EnvironmentCommand<TerminalCloseInput>;
227 +}
228 +
229 +export interface TerminalSessionOptions {
230 + readonly target: {
231 + readonly environmentId: EnvironmentId;
232 + readonly threadId: ThreadId;
233 + readonly terminalId: string;
234 + };
235 + readonly gridSize: TerminalGridSize;
236 + /** Written once, as soon as the first attachment snapshot lands. */
237 + readonly initialInput?: string | undefined;
238 + /** Read right before every command, so revoking operate stops them at once. */
239 + readonly canOperate: () => boolean;
240 + /** The shell ended while attached; the store has already closed it. */
241 + readonly onExit: () => void;
242 + /** Fires when the shell starts or stops accepting input, and on every restart. */
243 + readonly onLiveChange?: (live: boolean) => void;
244 + readonly debugLog?: (message: string, data: Record<string, unknown>) => void;
245 +}
246 +
247 +export interface TerminalSession {
248 + /**
249 + * Mount while the session follows a terminal: attached to operate it, or
250 + * observing it read-only. `null` follows nothing.
251 + */
252 + readonly driver: (mode: TerminalSessionMode | null) => Atom.Atom<void>;
253 + /** The surface measured a new grid; the shell is resized while it runs. */
254 + readonly reportGridSize: (size: TerminalGridSize) => void;
255 +}
256 +
257 +/**
258 + * Owns one shown terminal's lifecycle: it reopens an ended shell on an explicit
259 + * visit, closes and reports a shell that exits while attached, replays the
260 + * measured grid whenever the server starts a new output generation, and writes
261 + * the launch's initial input once.
262 + */
263 +export function createTerminalSession(
264 + atoms: TerminalSessionAtoms,
265 + options: TerminalSessionOptions,
266 +): TerminalSession {
267 + const { environmentId, threadId, terminalId } = options.target;
268 + let lifecycle = INITIAL_TERMINAL_LIFECYCLE;
269 + let gridSize = options.gridSize;
270 + let generation: number | null = null;
271 + let liveLifecycleVersion: number | null = null;
272 + let initialInputPending = Boolean(options.initialInput);
273 + let lastStatus: TerminalBufferState["status"] | null = null;
274 + let loggedFirstOutput = false;
275 + let resizeRegistry: AtomRegistry.AtomRegistry | null = null;
276 + // Driver atoms are released on a scheduled task, so an attachment replaced by
277 + // another one must not reset state the newer attachment already set.
278 + let currentAttachment: object | null = null;
279 +
280 + const sendResize = () => {
281 + if (generation === null || resizeRegistry === null || !options.canOperate()) return;
282 + void runAtomCommand(resizeRegistry, atoms.resize, {
283 + environmentId,
284 + input: { threadId, terminalId, cols: gridSize.cols, rows: gridSize.rows },
285 + });
286 + };
287 +
288 + const setLive = (next: number | null) => {
289 + if (next === liveLifecycleVersion) return;
290 + liveLifecycleVersion = next;
291 + options.onLiveChange?.(next !== null);
292 + };
293 +
294 + const apply = (
295 + event: TerminalLifecycleEvent,
296 + registry: AtomRegistry.AtomRegistry,
297 + input: TerminalAttachInput | null,
298 + ) => {
299 + const step = transitionTerminalLifecycle(lifecycle, event);
300 + lifecycle = step.state;
301 + if (step.command === "exit") {
302 + if (!options.canOperate()) return;
303 + void runAtomCommand(registry, atoms.close, {
304 + environmentId,
305 + input: { threadId, terminalId },
306 + });
307 + options.onExit();
308 + return;
309 + }
310 + if (step.command !== "reopen") return;
311 + const reopen = async () => {
312 + if (input?.cwd === undefined || !options.canOperate()) return false;
313 + const result = await runAtomCommand(registry, atoms.open, {
314 + environmentId,
315 + input: {
316 + threadId,
317 + terminalId,
318 + cwd: input.cwd,
319 + worktreePath: input.worktreePath,
320 + cols: input.cols,
321 + rows: input.rows,
322 + ...(input.env ? { env: input.env } : {}),
323 + },
324 + });
325 + return result._tag === "Success";
326 + };
327 + void reopen().then((succeeded) => {
328 + if (!succeeded)
329 + lifecycle = transitionTerminalLifecycle(lifecycle, { type: "reopen-failed" }).state;
330 + });
331 + };
332 +
333 + const onAttachment = (
334 + registry: AtomRegistry.AtomRegistry,
335 + input: TerminalAttachInput,
336 + result: AsyncResult.AsyncResult<TerminalBufferState, unknown>,
337 + ) => {
338 + resizeRegistry = registry;
339 + const buffer = Option.getOrElse(AsyncResult.value(result), () => EMPTY_TERMINAL_BUFFER_STATE);
340 + const status = result._tag === "Failure" ? "error" : buffer.status;
341 + if (status !== lastStatus) {
342 + lastStatus = status;
343 + options.debugLog?.("session:status", {
344 + terminalId,
345 + status,
346 + error: buffer.error,
347 + version: buffer.version,
348 + });
349 + }
350 + if (!loggedFirstOutput && options.debugLog) {
351 + const text = terminalOutputText(buffer.output);
352 + if (text.length > 0) {
353 + loggedFirstOutput = true;
354 + options.debugLog("session:first-nonempty-buffer", {
355 + terminalId,
356 + length: text.length,
357 + preview: text.slice(0, 160),
358 + });
359 + }
360 + }
361 +
362 + setLive(status === "running" || status === "starting" ? buffer.lifecycleVersion : null);
363 +
364 + // Resize before the initial input so a launched command starts at the measured grid.
365 + const nextGeneration =
366 + buffer.version > 0 && status === "running" ? buffer.output.generation : null;
367 + if (nextGeneration !== generation) {
368 + generation = nextGeneration;
369 + sendResize();
370 + }
371 +
372 + if (initialInputPending && buffer.version > 0 && options.initialInput && options.canOperate()) {
373 + initialInputPending = false;
374 + void runAtomCommand(registry, atoms.write, {
375 + environmentId,
376 + input: { threadId, terminalId, data: options.initialInput },
377 + });
378 + }
379 +
380 + apply({ type: "status", status, version: buffer.version }, registry, input);
381 + };
382 +
383 + const idle = Atom.make<void>(undefined);
384 + const modes = new Map<string, TerminalSessionMode>();
385 + const drivers = Atom.family((key: string) => {
386 + const mode = modes.get(key)!;
387 + return Atom.make((get) => {
388 + const registry = get.registry;
389 + // `subscribe`, not `get`: a rebuild would resubscribe on every output chunk.
390 + if (mode.kind === "observing") {
391 + // Viewing read-only counts as observed before the first snapshot lands, so
392 + // a grant that arrives early still leaves the ended shell's history alone.
393 + get.subscribe(
394 + atoms.observe({ environmentId, input: { threadId, terminalId } }),
395 + () => {
396 + if (options.canOperate()) return;
397 + lifecycle = transitionTerminalLifecycle(lifecycle, { type: "observed" }).state;
398 + },
399 + { immediate: true },
400 + );
401 + return;
402 + }
403 + const attachment = {};
404 + currentAttachment = attachment;
405 + get.addFinalizer(() => {
406 + if (currentAttachment !== attachment) return;
407 + currentAttachment = null;
408 + generation = null;
409 + lastStatus = null;
410 + setLive(null);
411 + lifecycle = transitionTerminalLifecycle(lifecycle, {
412 + type: "detached",
413 + canOperate: options.canOperate(),
414 + }).state;
415 + });
416 + get.subscribe(
417 + atoms.attach({ environmentId, input: mode.input }),
418 + (result) => onAttachment(registry, mode.input, result),
419 + { immediate: true },
420 + );
421 + }).pipe(
422 + Atom.withLabel(`terminal-session:${environmentId}:${threadId}:${terminalId}:${mode.kind}`),
423 + );
424 + });
425 +
426 + return {
427 + driver: (mode) => {
428 + if (mode === null) return idle;
429 + const key = JSON.stringify(mode);
430 + if (!modes.has(key)) modes.set(key, mode);
431 + return drivers(key);
432 + },
433 + reportGridSize: (size) => {
434 + if (size.cols === gridSize.cols && size.rows === gridSize.rows) return;
435 + gridSize = size;
436 + sendResize();
437 + },
438 + };
439 }
440
441 export * from "./terminalSession.ts";