Open History to see the last commit
1import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
3import type { MenuAction } from "@react-native-menu/menu";
4import { SymbolView } from "../../components/AppSymbol";
5import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
6import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8import { Platform, Pressable, View, useColorScheme } from "react-native";
9import {
10 KeyboardController,
11 KeyboardEvents,
12 KeyboardStickyView,
13 useKeyboardState,
14} from "react-native-keyboard-controller";
15
16import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader";
17import {
18 ComposerToolbarButton,
19 ComposerToolbarRow,
20 ComposerToolbarScroller,
21} from "../../components/ComposerToolbarTrigger";
22import { ControlPillMenu } from "../../components/ControlPill";
23import { EmptyState } from "../../components/EmptyState";
24import { GlassSurface } from "../../components/GlassSurface";
25import { LoadingScreen } from "../../components/LoadingScreen";
26import { environmentCatalog } from "../../connection/catalog";
27import { useEnvironmentPresentation } from "../../state/presentation";
28import { terminalEnvironment } from "../../state/terminal";
29import { useAtomCommand } from "../../state/use-atom-command";
30import { useWorkspaceState } from "../../state/workspace";
31import {
32 MAX_TERMINAL_FONT_SIZE,
33 MIN_TERMINAL_FONT_SIZE,
34 TERMINAL_FONT_SIZE_STEP,
35 stepTerminalFontSize,
36} from "../../lib/appearancePreferences";
37import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
38import {
39 useAttachedTerminalSession,
40 useKnownTerminalSessions,
41} from "../../state/use-terminal-session";
42import { useThreadSelection } from "../../state/use-thread-selection";
43import { useSelectedThreadDetail } from "../../state/use-thread-detail";
44import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
45import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
46import { TerminalSurface } from "./NativeTerminalSurface";
47import { getPierreTerminalTheme } from "./terminalTheme";
48import { terminalDebugLog } from "./terminalDebugLog";
49import {
50 getTerminalBufferReplayKey,
51 getTerminalSurfaceReplayBuffer,
52 TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
53} from "./terminalBufferReplay";
54import {
55 resolveTerminalOpenLocation,
56 takePendingTerminalLaunch,
57 type PendingTerminalLaunch,
58} from "./terminalLaunchContext";
59import {
60 basename,
61 buildTerminalMenuSessions,
62 getTerminalStatusLabel,
63 nextOpenTerminalId,
64 previousLiveTerminalId,
65 resolveTerminalSessionLabel,
66 type TerminalMenuSession,
67} from "./terminalMenu";
68import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";
69
70const DEFAULT_TERMINAL_COLS = 80;
71const DEFAULT_TERMINAL_ROWS = 24;
72const TERMINAL_ACCESSORY_HEIGHT = 52;
73
74type PendingModifier = "ctrl" | "meta";
75type HostPlatform = "mac" | "linux" | "windows" | "unknown";
76
77type TerminalToolbarAction =
78 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
79 | { readonly kind: "clear"; readonly key: string; readonly label: string }
80 | {
81 readonly kind: "modifier";
82 readonly key: string;
83 readonly label: string;
84 readonly modifier: PendingModifier;
85 };
86
87function firstRouteParam(value: string | string[] | undefined): string | null {
88 if (Array.isArray(value)) {
89 return value[0] ?? null;
90 }
91
92 return value ?? null;
93}
94
95function inferHostPlatform(environmentLabel: string | null): HostPlatform {
96 const value = environmentLabel?.toLowerCase() ?? "";
97 if (
98 value.includes("mac") ||
99 value.includes("macbook") ||
100 value.includes("mac mini") ||
101 value.includes("imac") ||
102 value.includes("darwin")
103 ) {
104 return "mac";
105 }
106 if (value.includes("windows") || value.includes("win")) {
107 return "windows";
108 }
109 if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) {
110 return "linux";
111 }
112
113 return "unknown";
114}
115
116function applyCtrlModifier(input: string): string {
117 const firstCharacter = input[0];
118 if (!firstCharacter) {
119 return input;
120 }
121
122 const lowerCharacter = firstCharacter.toLowerCase();
123 if (lowerCharacter >= "a" && lowerCharacter <= "z") {
124 return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);
125 }
126
127 if (firstCharacter === "@") return "\u0000";
128 if (firstCharacter === "[") return "\u001b";
129 if (firstCharacter === "\\") return "\u001c";
130 if (firstCharacter === "]") return "\u001d";
131 if (firstCharacter === "^") return "\u001e";
132 if (firstCharacter === "_") return "\u001f";
133 if (firstCharacter === "?") return "\u007f";
134
135 return input;
136}
137
138function pickRunningTerminalSessionForBootstrap(
139 sessions: ReadonlyArray<KnownTerminalSession>,
140): KnownTerminalSession | null {
141 const running = sessions.filter(
142 (session) => session.state.status === "running" || session.state.status === "starting",
143 );
144 if (running.length === 0) {
145 return null;
146 }
147 return (
148 running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ??
149 running[0] ??
150 null
151 );
152}
153
154type ThreadTerminalRouteScreenProps = StaticScreenProps<{
155 readonly environmentId: string;
156 readonly threadId: string;
157 readonly terminalId?: string;
158}>;
159
160export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) {
161 const navigation = useNavigation();
162 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
163 const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
164 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
165 const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close");
166 const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
167 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
168 const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
169 const { state: workspaceState } = useWorkspaceState();
170 const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
171 const params = props.route.params;
172 const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
173 useThreadSelection();
174 const selectedThreadDetail = useSelectedThreadDetail();
175 const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
176 const routeThreadIdRaw = firstRouteParam(params.threadId);
177 const routeEnvironmentId = routeEnvironmentIdRaw
178 ? EnvironmentId.make(routeEnvironmentIdRaw)
179 : null;
180 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
181 const environment = useEnvironmentPresentation(routeEnvironmentId);
182 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
183 const requestedTerminalId = firstRouteParam(params.terminalId);
184 const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
185 const {
186 isReady: hasResolvedFontPreference,
187 appearance,
188 setTerminalFontSize,
189 } = useAppearancePreferences();
190 const fontSize = appearance.terminalFontSize;
191 const cachedRouteGridSize =
192 routeEnvironmentId && routeThreadId
193 ? getCachedTerminalGridSize({
194 environmentId: routeEnvironmentId,
195 threadId: routeThreadId,
196 terminalId,
197 })
198 : null;
199 const knownSessions = useKnownTerminalSessions({
200 environmentId: selectedThread?.environmentId ?? null,
201 threadId: selectedThread?.id ?? null,
202 });
203 const runningSession = useMemo(
204 () => pickRunningTerminalSessionForBootstrap(knownSessions),
205 [knownSessions],
206 );
207 const activeKnownSession = useMemo(
208 () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
209 [knownSessions, terminalId],
210 );
211 const launchTarget = useMemo(
212 () =>
213 selectedThread
214 ? {
215 environmentId: selectedThread.environmentId,
216 threadId: selectedThread.id,
217 terminalId,
218 }
219 : null,
220 [selectedThread, terminalId],
221 );
222 const launchTargetKey = launchTarget
223 ? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`
224 : null;
225 const [pendingLaunchEntry, setPendingLaunchEntry] = useState<{
226 readonly key: string | null;
227 readonly launch: PendingTerminalLaunch | null;
228 }>(() => ({
229 key: launchTargetKey,
230 launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
231 }));
232 const pendingLaunch =
233 pendingLaunchEntry.key === launchTargetKey ? pendingLaunchEntry.launch : null;
234 const hasResolvedPendingLaunch = pendingLaunchEntry.key === launchTargetKey;
235 const [initialAttachGridEntry, setInitialAttachGridEntry] = useState(() => ({
236 key: launchTargetKey,
237 size: cachedRouteGridSize ?? {
238 cols: DEFAULT_TERMINAL_COLS,
239 rows: DEFAULT_TERMINAL_ROWS,
240 },
241 }));
242 const initialAttachGridSize =
243 initialAttachGridEntry.key === launchTargetKey ? initialAttachGridEntry.size : null;
244 const [lastGridSize, setLastGridSize] = useState(
245 cachedRouteGridSize ?? {
246 cols: DEFAULT_TERMINAL_COLS,
247 rows: DEFAULT_TERMINAL_ROWS,
248 },
249 );
250 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
251 const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
252 const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
253 const firstNonEmptyBufferLoggedRef = useRef(false);
254 const lastBufferReplayKeyRef = useRef<string | null>(null);
255 const sentInitialInputKeyRef = useRef<string | null>(null);
256 const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
257 /** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */
258 const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);
259 const [pendingModifierState, setPendingModifierState] = useState<{
260 readonly terminalId: string;
261 readonly value: PendingModifier | null;
262 }>({
263 terminalId,
264 value: null,
265 });
266 const shouldRedirectToRunningTerminal =
267 requestedTerminalId === null &&
268 runningSession !== null &&
269 runningSession.target.terminalId !== terminalId;
270 const launchLocationCandidate = useMemo(() => {
271 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
272 return null;
273 }
274 if (pendingLaunch) {
275 return {
276 cwd: pendingLaunch.cwd,
277 worktreePath: pendingLaunch.worktreePath,
278 };
279 }
280 return resolveTerminalOpenLocation({
281 terminalLocation: activeKnownSession?.state.summary ?? null,
282 activeSessionLocation: activeKnownSession?.state.summary ?? null,
283 workspaceRoot: selectedThreadProject.workspaceRoot,
284 threadShellWorktreePath: selectedThread.worktreePath ?? null,
285 threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
286 });
287 }, [
288 activeKnownSession?.state.summary,
289 pendingLaunch,
290 selectedThread,
291 selectedThreadDetail?.worktreePath,
292 selectedThreadProject?.workspaceRoot,
293 ]);
294 const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
295 key: launchTargetKey,
296 location: launchLocationCandidate,
297 }));
298 const launchLocation =
299 initialLaunchLocationEntry.key === launchTargetKey ? initialLaunchLocationEntry.location : null;
300 const terminalAttachInput = useMemo(
301 () =>
302 selectedThread !== null &&
303 launchLocation !== null &&
304 hasResolvedPendingLaunch &&
305 initialAttachGridSize !== null &&
306 hasResolvedFontPreference &&
307 hasMeasuredSurface &&
308 isEnvironmentReady &&
309 !shouldRedirectToRunningTerminal
310 ? {
311 threadId: selectedThread.id,
312 terminalId,
313 cwd: launchLocation.cwd,
314 worktreePath: launchLocation.worktreePath,
315 cols: initialAttachGridSize.cols,
316 rows: initialAttachGridSize.rows,
317 ...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
318 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
319 }
320 : null,
321 [
322 hasMeasuredSurface,
323 hasResolvedFontPreference,
324 hasResolvedPendingLaunch,
325 initialAttachGridSize,
326 isEnvironmentReady,
327 launchLocation,
328 pendingLaunch,
329 selectedThread,
330 shouldRedirectToRunningTerminal,
331 terminalId,
332 ],
333 );
334 const terminal = useAttachedTerminalSession({
335 environmentId: selectedThread?.environmentId ?? null,
336 terminal: terminalAttachInput,
337 });
338 const terminalKey = selectedThread
339 ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
340 : terminalId;
341 const bufferReplayKey = useMemo(
342 () => getTerminalBufferReplayKey({ terminalKey, fontSize }),
343 [fontSize, terminalKey],
344 );
345 if (lastBufferReplayKeyRef.current === null) {
346 lastBufferReplayKeyRef.current = bufferReplayKey;
347 }
348 const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
349 buffer: terminal.buffer,
350 replayKey: bufferReplayKey,
351 readyReplayKey: readyBufferReplayKey,
352 });
353 const isRunning = terminal.status === "running" || terminal.status === "starting";
354
355 // When the process ends while this screen is attached (e.g. typing `exit`),
356 // close the session and leave the screen, mirroring the web drawer's
357 // onSessionExited flow. Only react to a running -> exited transition
358 // observed on this screen so already-exited sessions can still be opened
359 // (they restart on attach).
360 const runningTerminalKeyRef = useRef<string | null>(null);
361 const reopenedStaleTerminalKeyRef = useRef<string | null>(null);
362 const pendingExitNavigationRef = useRef<string | null>(null);
363
364 // Attach subscriptions are cached with an idle TTL, so revisiting a
365 // terminal whose session ended while unobserved reuses the stale stream
366 // without a new attach RPC — the server never respawns anything. Detect
367 // that (dead status with processed events, never seen running here) and
368 // issue an explicit open; its snapshot flows into the live subscription.
369 useEffect(() => {
370 if (isRunning) {
371 reopenedStaleTerminalKeyRef.current = null;
372 return;
373 }
374 if (
375 terminalAttachInput === null ||
376 !selectedThread ||
377 (terminal.status !== "closed" && terminal.status !== "exited") ||
378 terminal.version === 0 ||
379 runningTerminalKeyRef.current === terminalKey ||
380 reopenedStaleTerminalKeyRef.current === terminalKey
381 ) {
382 return;
383 }
384 reopenedStaleTerminalKeyRef.current = terminalKey;
385 void openTerminal({
386 environmentId: selectedThread.environmentId,
387 input: {
388 threadId: selectedThread.id,
389 terminalId,
390 cwd: terminalAttachInput.cwd,
391 worktreePath: terminalAttachInput.worktreePath,
392 cols: terminalAttachInput.cols,
393 rows: terminalAttachInput.rows,
394 ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}),
395 },
396 }).then((result) => {
397 // Release the guard on failure so a later render can retry the respawn.
398 if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) {
399 reopenedStaleTerminalKeyRef.current = null;
400 }
401 });
402 }, [
403 isRunning,
404 openTerminal,
405 selectedThread,
406 terminal.status,
407 terminal.version,
408 terminalAttachInput,
409 terminalId,
410 terminalKey,
411 ]);
412
413 useEffect(() => {
414 terminalDebugLog("surface:props", {
415 terminalKey,
416 atomBufferLen: terminal.buffer.length,
417 surfaceBufferLen: terminalSurfaceBuffer.length,
418 replayKey: bufferReplayKey,
419 readyReplayKey: readyBufferReplayKey,
420 status: terminal.status,
421 version: terminal.version,
422 });
423 }, [
424 bufferReplayKey,
425 readyBufferReplayKey,
426 terminal.buffer.length,
427 terminal.status,
428 terminal.version,
429 terminalKey,
430 terminalSurfaceBuffer.length,
431 ]);
432
433 useEffect(() => {
434 terminalDebugLog("session:status", {
435 terminalKey,
436 status: terminal.status,
437 error: terminal.error,
438 summary: terminal.summary?.cwd ?? null,
439 bufferLen: terminal.buffer.length,
440 version: terminal.version,
441 });
442 }, [
443 terminal.buffer.length,
444 terminal.error,
445 terminal.status,
446 terminal.summary?.cwd,
447 terminal.version,
448 terminalKey,
449 ]);
450
451 useEffect(() => {
452 if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {
453 return;
454 }
455 firstNonEmptyBufferLoggedRef.current = true;
456 terminalDebugLog("session:first-nonempty-buffer", {
457 terminalKey,
458 length: terminal.buffer.length,
459 preview: terminal.buffer.slice(0, 160),
460 });
461 }, [terminal.buffer, terminal.buffer.length, terminalKey]);
462 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
463 const hostPlatform = useMemo(
464 () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
465 [selectedEnvironmentConnection?.environmentLabel],
466 );
467
468 const terminalTheme = getPierreTerminalTheme(appearanceScheme);
469 const usesNativeHeaderGlass = Platform.OS === "ios";
470 const pendingModifier =
471 pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
472 const headerSubtitle = selectedThreadProject?.title ?? "";
473 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
474 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
475 hostPlatform === "mac"
476 ? [
477 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
478 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
479 ]
480 : [
481 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
482 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
483 ];
484
485 return [
486 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
487 ...modifierActions,
488 { kind: "send", key: "tab", label: "tab", data: "\t" },
489 { kind: "clear", key: "clear", label: "clear" },
490 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
491 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
492 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
493 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
494 { kind: "send", key: "tilde", label: "~", data: "~" },
495 { kind: "send", key: "pipe", label: "|", data: "|" },
496 { kind: "send", key: "slash", label: "/", data: "/" },
497 { kind: "send", key: "dash", label: "-", data: "-" },
498 ];
499 }, [hostPlatform]);
500 const keyboardState = useKeyboardState((state) => ({
501 height: state.height,
502 isVisible: state.isVisible,
503 }));
504 const isAccessoryVisible = keyboardState.isVisible && !isAccessoryDismissed;
505 const terminalBottomInset =
506 (keyboardState.isVisible ? keyboardState.height : 0) +
507 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
508
509 useEffect(() => {
510 const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {
511 setIsAccessoryDismissed(false);
512 });
513 const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {
514 setIsAccessoryDismissed(true);
515 });
516
517 return () => {
518 keyboardWillShow.remove();
519 keyboardWillHide.remove();
520 };
521 }, []);
522
523 const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
524 () =>
525 buildTerminalMenuSessions({
526 knownSessions,
527 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
528 currentSession: {
529 terminalId,
530 cwd: cwd ?? null,
531 status: terminal.status,
532 hasRunningSubprocess: terminal.hasRunningSubprocess,
533 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
534 updatedAt: terminal.updatedAt,
535 },
536 }),
537 [
538 cwd,
539 knownSessions,
540 selectedThreadProject?.workspaceRoot,
541 terminal.hasRunningSubprocess,
542 terminal.summary,
543 terminal.status,
544 terminal.updatedAt,
545 terminalId,
546 ],
547 );
548
549 useEffect(() => {
550 if (pendingLaunchEntry.key === launchTargetKey) {
551 return;
552 }
553 setPendingLaunchEntry({
554 key: launchTargetKey,
555 launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
556 });
557 }, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);
558
559 useEffect(() => {
560 if (initialAttachGridEntry.key === launchTargetKey) {
561 return;
562 }
563 setInitialAttachGridEntry({
564 key: launchTargetKey,
565 size: cachedRouteGridSize ?? {
566 cols: DEFAULT_TERMINAL_COLS,
567 rows: DEFAULT_TERMINAL_ROWS,
568 },
569 });
570 }, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
571
572 useEffect(() => {
573 if (
574 initialLaunchLocationEntry.key === launchTargetKey &&
575 initialLaunchLocationEntry.location !== null
576 ) {
577 return;
578 }
579 if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {
580 return;
581 }
582 setInitialLaunchLocationEntry({
583 key: launchTargetKey,
584 location: launchLocationCandidate,
585 });
586 }, [
587 initialLaunchLocationEntry.key,
588 initialLaunchLocationEntry.location,
589 launchLocationCandidate,
590 launchTargetKey,
591 ]);
592
593 useEffect(() => {
594 if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
595 return;
596 }
597 navigation.dispatch(
598 StackActions.replace("ThreadTerminal", {
599 environmentId: String(selectedThread.environmentId),
600 threadId: String(selectedThread.id),
601 terminalId: runningSession.target.terminalId,
602 }),
603 );
604 }, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
605
606 useEffect(() => {
607 const initialInput = pendingLaunch?.initialInput;
608 if (
609 !initialInput ||
610 !selectedThread ||
611 terminal.version === 0 ||
612 sentInitialInputKeyRef.current === launchTargetKey
613 ) {
614 return;
615 }
616 sentInitialInputKeyRef.current = launchTargetKey;
617 void writeTerminal({
618 environmentId: selectedThread.environmentId,
619 input: {
620 threadId: selectedThread.id,
621 terminalId,
622 data: initialInput,
623 },
624 });
625 }, [
626 launchTargetKey,
627 pendingLaunch?.initialInput,
628 selectedThread,
629 terminal.version,
630 terminalId,
631 writeTerminal,
632 ]);
633
634 useEffect(() => {
635 firstNonEmptyBufferLoggedRef.current = false;
636 sentInitialInputKeyRef.current = null;
637 }, [terminalKey]);
638
639 const clearBufferReplayTimer = useCallback(() => {
640 if (bufferReplayTimerRef.current !== null) {
641 clearTimeout(bufferReplayTimerRef.current);
642 bufferReplayTimerRef.current = null;
643 }
644 }, []);
645
646 const scheduleBufferReplayReady = useCallback(() => {
647 clearBufferReplayTimer();
648 const replayKey = bufferReplayKey;
649 terminalDebugLog("replay:schedule-ready", {
650 replayKey,
651 delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
652 });
653 bufferReplayTimerRef.current = setTimeout(() => {
654 bufferReplayTimerRef.current = null;
655 setReadyBufferReplayKey(replayKey);
656 terminalDebugLog("replay:ready", { replayKey });
657 }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
658 }, [bufferReplayKey, clearBufferReplayTimer]);
659
660 useEffect(() => {
661 if (lastBufferReplayKeyRef.current === bufferReplayKey) {
662 return;
663 }
664
665 lastBufferReplayKeyRef.current = bufferReplayKey;
666 clearBufferReplayTimer();
667 setReadyBufferReplayKey(null);
668 }, [bufferReplayKey, clearBufferReplayTimer]);
669
670 useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
671
672 useEffect(() => {
673 if (!routeEnvironmentId || !routeThreadId) {
674 setLastGridSize({
675 cols: DEFAULT_TERMINAL_COLS,
676 rows: DEFAULT_TERMINAL_ROWS,
677 });
678 return;
679 }
680
681 setLastGridSize(
682 getCachedTerminalGridSize({
683 environmentId: routeEnvironmentId,
684 threadId: routeThreadId,
685 terminalId,
686 }) ?? {
687 cols: DEFAULT_TERMINAL_COLS,
688 rows: DEFAULT_TERMINAL_ROWS,
689 },
690 );
691 setHasMeasuredSurface(true);
692 }, [routeEnvironmentId, routeThreadId, terminalId]);
693
694 const writeInput = useCallback(
695 (data: string) => {
696 if (!selectedThread || !isRunning) {
697 return;
698 }
699
700 void writeTerminal({
701 environmentId: selectedThread.environmentId,
702 input: {
703 threadId: selectedThread.id,
704 terminalId,
705 data,
706 },
707 });
708 },
709 [isRunning, selectedThread, terminalId, writeTerminal],
710 );
711
712 const handleInput = useCallback(
713 (data: string) => {
714 if (data.length === 0) {
715 return;
716 }
717
718 if (pendingModifier === "ctrl") {
719 setPendingModifierState({ terminalId, value: null });
720 writeInput(applyCtrlModifier(data));
721 } else if (pendingModifier === "meta") {
722 setPendingModifierState({ terminalId, value: null });
723 writeInput(`\u001b${data}`);
724 } else {
725 writeInput(data);
726 }
727 },
728 [pendingModifier, terminalId, writeInput],
729 );
730
731 const handleResize = useCallback(
732 (size: { readonly cols: number; readonly rows: number }) => {
733 terminalDebugLog("native:onResize", {
734 cols: size.cols,
735 rows: size.rows,
736 terminalKey,
737 });
738 setHasMeasuredSurface(true);
739 if (readyBufferReplayKey !== bufferReplayKey) {
740 scheduleBufferReplayReady();
741 }
742 if (routeEnvironmentId && routeThreadId) {
743 cacheTerminalGridSize(
744 {
745 environmentId: routeEnvironmentId,
746 threadId: routeThreadId,
747 terminalId,
748 },
749 size,
750 );
751 }
752 if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
753 return;
754 }
755
756 setLastGridSize(size);
757 if (!selectedThread || !isRunning) {
758 return;
759 }
760
761 void resizeTerminal({
762 environmentId: selectedThread.environmentId,
763 input: {
764 threadId: selectedThread.id,
765 terminalId,
766 cols: size.cols,
767 rows: size.rows,
768 },
769 });
770 },
771 [
772 isRunning,
773 lastGridSize.cols,
774 lastGridSize.rows,
775 bufferReplayKey,
776 readyBufferReplayKey,
777 routeEnvironmentId,
778 routeThreadId,
779 resizeTerminal,
780 scheduleBufferReplayReady,
781 selectedThread,
782 terminalId,
783 terminalKey,
784 ],
785 );
786
787 const handleSelectTerminal = useCallback(
788 (nextTerminalId: string) => {
789 if (!selectedThread || nextTerminalId === terminalId) {
790 return;
791 }
792
793 navigation.dispatch(
794 StackActions.replace("ThreadTerminal", {
795 environmentId: String(selectedThread.environmentId),
796 threadId: String(selectedThread.id),
797 terminalId: nextTerminalId,
798 }),
799 );
800 },
801 [navigation, selectedThread, terminalId],
802 );
803
804 const navigateAwayAfterExit = useCallback(() => {
805 // With other shells still live, fall through to the previous one instead
806 // of dropping the user back on the thread.
807 const fallbackTerminalId = previousLiveTerminalId({
808 sessions: terminalMenuSessions,
809 exitedTerminalId: terminalId,
810 });
811 if (fallbackTerminalId !== null && selectedThread) {
812 navigation.dispatch(
813 StackActions.replace("ThreadTerminal", {
814 environmentId: String(selectedThread.environmentId),
815 threadId: String(selectedThread.id),
816 terminalId: fallbackTerminalId,
817 }),
818 );
819 return;
820 }
821 if (navigation.canGoBack()) {
822 navigation.goBack();
823 return;
824 }
825 // Deep-linked/root mounts have nothing to pop; land on the thread
826 // instead of stranding the user on a dead terminal.
827 if (selectedThread) {
828 navigation.dispatch(
829 StackActions.replace("Thread", {
830 environmentId: String(selectedThread.environmentId),
831 threadId: String(selectedThread.id),
832 }),
833 );
834 }
835 }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
836
837 useEffect(() => {
838 // Detached (hidden surface or environment drop): forget the running
839 // marker so a reattach takes the stale-reopen path instead of misreading
840 // the dead snapshot as an exit observed on this screen. A pending exit
841 // navigation stays armed — it only clears once the session runs again —
842 // so refocusing a dead screen still leaves it.
843 if (terminalAttachInput === null) {
844 runningTerminalKeyRef.current = null;
845 return;
846 }
847 if (isRunning) {
848 runningTerminalKeyRef.current = terminalKey;
849 // The session came back (e.g. respawned elsewhere) before the user
850 // returned; a stale pending exit must not eject a live terminal.
851 pendingExitNavigationRef.current = null;
852 return;
853 }
854 // The web drawer treats both exited and closed as session end.
855 const sessionEnded = terminal.status === "exited" || terminal.status === "closed";
856 if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) {
857 return;
858 }
859 runningTerminalKeyRef.current = null;
860 // Mark this key handled so the stale-attach effect doesn't respawn the
861 // session the user just ended.
862 reopenedStaleTerminalKeyRef.current = terminalKey;
863 if (selectedThread) {
864 void closeTerminal({
865 environmentId: selectedThread.environmentId,
866 input: {
867 threadId: selectedThread.id,
868 terminalId,
869 },
870 });
871 }
872 if (navigation.isFocused()) {
873 navigateAwayAfterExit();
874 return;
875 }
876 // An unfocused screen can't navigate; leave when the user returns so
877 // they never land on the dead session.
878 pendingExitNavigationRef.current = terminalKey;
879 }, [
880 closeTerminal,
881 isRunning,
882 navigateAwayAfterExit,
883 navigation,
884 selectedThread,
885 terminal.status,
886 terminalAttachInput,
887 terminalId,
888 terminalKey,
889 ]);
890
891 useEffect(
892 () =>
893 navigation.addListener("focus", () => {
894 if (pendingExitNavigationRef.current !== terminalKey) {
895 return;
896 }
897 pendingExitNavigationRef.current = null;
898 navigateAwayAfterExit();
899 }),
900 [navigateAwayAfterExit, navigation, terminalKey],
901 );
902
903 const handleOpenNewTerminal = useCallback(() => {
904 if (!selectedThread) {
905 return;
906 }
907
908 navigation.dispatch(
909 StackActions.replace("ThreadTerminal", {
910 environmentId: String(selectedThread.environmentId),
911 threadId: String(selectedThread.id),
912 terminalId: nextOpenTerminalId({
913 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
914 activeRouteTerminalId: terminalId,
915 }),
916 }),
917 );
918 }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
919
920 const handleDecreaseFontSize = useCallback(() => {
921 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
922 }, [fontSize, setTerminalFontSize]);
923
924 const handleIncreaseFontSize = useCallback(() => {
925 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
926 }, [fontSize, setTerminalFontSize]);
927
928 // Android mirror of the iOS NativeHeaderToolbar terminal menu below: text
929 // size, session switching, and "Open new terminal", rendered through the
930 // token-styled anchored menu (the native header items are iOS-only).
931 const androidTerminalMenuActions = useMemo<MenuAction[]>(
932 () => [
933 {
934 id: "text-size",
935 title: "Text size",
936 subactions: [
937 {
938 id: "font-decrease",
939 title: `A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
940 attributes: fontSize <= MIN_TERMINAL_FONT_SIZE ? { disabled: true } : undefined,
941 },
942 {
943 id: "font-increase",
944 title: `A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
945 attributes: fontSize >= MAX_TERMINAL_FONT_SIZE ? { disabled: true } : undefined,
946 },
947 ],
948 },
949 ...terminalMenuSessions.map(
950 (session): MenuAction => ({
951 id: `terminal-session:${session.terminalId}`,
952 title: session.displayLabel,
953 subtitle: [getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
954 .filter(Boolean)
955 .join(" · "),
956 state: session.terminalId === terminalId ? ("on" as const) : undefined,
957 }),
958 ),
959 {
960 id: "terminal-new",
961 title: "Open new terminal",
962 image: "plus",
963 subtitle: `Start another shell in ${basename(selectedThreadProject?.workspaceRoot ?? null) ?? "this workspace"}`,
964 },
965 ],
966 [fontSize, selectedThreadProject?.workspaceRoot, terminalId, terminalMenuSessions],
967 );
968
969 const handleAndroidTerminalMenuAction = useCallback(
970 (event: { nativeEvent: { event: string } }) => {
971 const id = event.nativeEvent.event;
972 if (id === "font-decrease") {
973 handleDecreaseFontSize();
974 return;
975 }
976 if (id === "font-increase") {
977 handleIncreaseFontSize();
978 return;
979 }
980 if (id === "terminal-new") {
981 handleOpenNewTerminal();
982 return;
983 }
984 if (id.startsWith("terminal-session:")) {
985 handleSelectTerminal(id.slice("terminal-session:".length));
986 }
987 },
988 [handleDecreaseFontSize, handleIncreaseFontSize, handleOpenNewTerminal, handleSelectTerminal],
989 );
990
991 const handleClearTerminal = useCallback(() => {
992 if (!selectedThread) {
993 return;
994 }
995
996 setPendingModifierState({ terminalId, value: null });
997 void clearTerminal({
998 environmentId: selectedThread.environmentId,
999 input: {
1000 threadId: selectedThread.id,
1001 terminalId,
1002 },
1003 });
1004 }, [clearTerminal, selectedThread, terminalId]);
1005
1006 const handleToolbarActionPress = useCallback(
1007 (action: TerminalToolbarAction) => {
1008 if (action.kind === "modifier") {
1009 setPendingModifierState((current) => ({
1010 terminalId,
1011 value:
1012 (current.terminalId === terminalId ? current.value : null) === action.modifier
1013 ? null
1014 : action.modifier,
1015 }));
1016 return;
1017 }
1018
1019 if (action.kind === "clear") {
1020 handleClearTerminal();
1021 return;
1022 }
1023
1024 setPendingModifierState({ terminalId, value: null });
1025 if (pendingModifier === "ctrl") {
1026 writeInput(applyCtrlModifier(action.data));
1027 } else if (pendingModifier === "meta") {
1028 writeInput(`\u001b${action.data}`);
1029 } else {
1030 writeInput(action.data);
1031 }
1032 },
1033 [handleClearTerminal, pendingModifier, terminalId, writeInput],
1034 );
1035
1036 const handleDismissKeyboard = useCallback(() => {
1037 setIsAccessoryDismissed(true);
1038 void KeyboardController.dismiss();
1039 }, []);
1040
1041 const handleShowKeyboard = useCallback(() => {
1042 setKeyboardFocusRequest((current) => current + 1);
1043 }, []);
1044 const handleRetryEnvironment = useCallback(() => {
1045 if (routeEnvironmentId !== null) {
1046 void retryEnvironment(routeEnvironmentId);
1047 }
1048 }, [retryEnvironment, routeEnvironmentId]);
1049
1050 if (!selectedThread) {
1051 if (workspaceState.isLoadingConnections) {
1052 return <LoadingScreen message="Opening terminal…" />;
1053 }
1054
1055 return (
1056 <View className="flex-1 bg-screen">
1057 <EmptyState
1058 title="Thread unavailable"
1059 detail="This terminal route needs an active thread and workspace."
1060 />
1061 </View>
1062 );
1063 }
1064
1065 if (!selectedThreadProject?.workspaceRoot) {
1066 return (
1067 <View className="flex-1 bg-screen">
1068 <EmptyState
1069 title="Terminal unavailable"
1070 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
1071 />
1072 </View>
1073 );
1074 }
1075
1076 if (!environment.isReady && environment.presentation === null) {
1077 return <LoadingScreen message="Opening terminal…" />;
1078 }
1079
1080 return (
1081 <>
1082 <NativeStackScreenOptions
1083 options={{
1084 // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS — the pty
1085 // scrolls internally, nothing for glass to sample). Default title/subtitle
1086 // styling, like every other page.
1087 // Android draws its own in-flow header (AndroidScreenHeader below);
1088 // the native stack header stays iOS-only.
1089 headerShown: Platform.OS !== "android",
1090 title: "Terminal",
1091 unstable_headerSubtitle:
1092 usesNativeHeaderGlass && headerSubtitle.length > 0 ? headerSubtitle : undefined,
1093 }}
1094 />
1095
1096 {Platform.OS === "android" ? (
1097 <AndroidScreenHeader
1098 title="Terminal"
1099 subtitle={headerSubtitle}
1100 onBack={navigation.canGoBack() ? () => navigation.goBack() : undefined}
1101 trailing={
1102 <>
1103 {layout.usesSplitView ? (
1104 <AndroidHeaderIconButton
1105 accessibilityLabel={
1106 panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"
1107 }
1108 icon={
1109 panes.primarySidebarVisible
1110 ? "arrow.up.left.and.arrow.down.right"
1111 : "sidebar.left"
1112 }
1113 onPress={togglePrimarySidebar}
1114 />
1115 ) : null}
1116 {isEnvironmentReady ? (
1117 <ControlPillMenu
1118 actions={androidTerminalMenuActions}
1119 isAnchoredToRight
1120 title={getTerminalStatusLabel({
1121 status: terminal.status,
1122 hasRunningSubprocess: terminal.hasRunningSubprocess,
1123 })}
1124 onPressAction={handleAndroidTerminalMenuAction}
1125 >
1126 <AndroidHeaderIconButton accessibilityLabel="Terminal options" icon="terminal" />
1127 </ControlPillMenu>
1128 ) : null}
1129 </>
1130 }
1131 />
1132 ) : null}
1133
1134 {layout.usesSplitView ? (
1135 <NativeHeaderToolbar placement="left">
1136 <NativeHeaderToolbar.Button
1137 accessibilityLabel={panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"}
1138 icon={
1139 panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
1140 }
1141 onPress={togglePrimarySidebar}
1142 separateBackground
1143 />
1144 </NativeHeaderToolbar>
1145 ) : null}
1146
1147 {isEnvironmentReady ? (
1148 <NativeHeaderToolbar placement="right">
1149 <NativeHeaderToolbar.Menu icon="terminal" title="Terminal options" separateBackground>
1150 <NativeHeaderToolbar.Label>
1151 {getTerminalStatusLabel({
1152 status: terminal.status,
1153 hasRunningSubprocess: terminal.hasRunningSubprocess,
1154 })}
1155 </NativeHeaderToolbar.Label>
1156 <NativeHeaderToolbar.Menu icon="textformat.size" inline title="Text size">
1157 <NativeHeaderToolbar.Label>Text size</NativeHeaderToolbar.Label>
1158 <NativeHeaderToolbar.MenuAction
1159 disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
1160 discoverabilityLabel="Decrease terminal text size"
1161 onPress={handleDecreaseFontSize}
1162 >
1163 <NativeHeaderToolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
1164 </NativeHeaderToolbar.MenuAction>
1165 <NativeHeaderToolbar.MenuAction
1166 disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
1167 discoverabilityLabel="Increase terminal text size"
1168 onPress={handleIncreaseFontSize}
1169 >
1170 <NativeHeaderToolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
1171 </NativeHeaderToolbar.MenuAction>
1172 </NativeHeaderToolbar.Menu>
1173 {terminalMenuSessions.map((session) => (
1174 <NativeHeaderToolbar.MenuAction
1175 key={session.terminalId}
1176 icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
1177 onPress={() => handleSelectTerminal(session.terminalId)}
1178 subtitle={[
1179 getTerminalStatusLabel({ status: session.status }),
1180 basename(session.cwd),
1181 ]
1182 .filter(Boolean)
1183 .join(" · ")}
1184 >
1185 <NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
1186 </NativeHeaderToolbar.MenuAction>
1187 ))}
1188 <NativeHeaderToolbar.MenuAction
1189 icon="plus"
1190 onPress={handleOpenNewTerminal}
1191 subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
1192 >
1193 <NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
1194 </NativeHeaderToolbar.MenuAction>
1195 </NativeHeaderToolbar.Menu>
1196 </NativeHeaderToolbar>
1197 ) : null}
1198
1199 <View className="flex-1" style={{ backgroundColor: terminalTheme.background }}>
1200 {!isEnvironmentReady ? (
1201 <EnvironmentConnectionNotice
1202 environmentLabel={
1203 environment.presentation?.entry.target.label ??
1204 selectedEnvironmentConnection?.environmentLabel ??
1205 "Environment"
1206 }
1207 connection={
1208 environment.presentation?.connection ?? {
1209 phase: "available",
1210 error: null,
1211 traceId: null,
1212 }
1213 }
1214 resourceName="terminal"
1215 onRetry={handleRetryEnvironment}
1216 />
1217 ) : (
1218 <>
1219 <View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
1220 <TerminalSurface
1221 buffer={terminalSurfaceBuffer}
1222 fontSize={fontSize}
1223 isRunning={isRunning}
1224 keyboardFocusRequest={keyboardFocusRequest}
1225 onInput={handleInput}
1226 onResize={handleResize}
1227 style={{ flex: 1 }}
1228 terminalKey={terminalKey}
1229 />
1230 </View>
1231
1232 {isAccessoryVisible ? (
1233 <KeyboardStickyView
1234 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1235 offset={{ closed: 0, opened: 0 }}
1236 >
1237 <View
1238 className="border-t"
1239 style={{
1240 backgroundColor: terminalTheme.background,
1241 borderTopColor: terminalTheme.border,
1242 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1243 }}
1244 >
1245 <ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
1246 <ComposerToolbarScroller
1247 contentPaddingRight={2}
1248 fadeOpaque={terminalTheme.background}
1249 fadeTransparent={`${terminalTheme.background}00`}
1250 >
1251 {terminalToolbarActions.map((action) => {
1252 const active =
1253 action.kind === "modifier" && pendingModifier === action.modifier;
1254
1255 return (
1256 <ComposerToolbarButton
1257 key={action.key}
1258 active={active}
1259 label={action.label}
1260 maxWidth={120}
1261 minWidth={action.label.length > 1 ? 56 : 44}
1262 onPress={() => handleToolbarActionPress(action)}
1263 showChevron={false}
1264 textTransform={
1265 action.kind === "modifier" || action.kind === "clear"
1266 ? "uppercase"
1267 : "none"
1268 }
1269 />
1270 );
1271 })}
1272 </ComposerToolbarScroller>
1273 <ComposerToolbarButton
1274 accessibilityLabel="Dismiss keyboard"
1275 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1276 onPress={handleDismissKeyboard}
1277 showChevron={false}
1278 />
1279 </ComposerToolbarRow>
1280 </View>
1281 </KeyboardStickyView>
1282 ) : !keyboardState.isVisible ? (
1283 <Pressable
1284 accessibilityLabel="Show keyboard"
1285 accessibilityRole="button"
1286 onPress={handleShowKeyboard}
1287 style={({ pressed }) => ({
1288 bottom: 16,
1289 borderRadius: 28,
1290 opacity: pressed ? 0.72 : 1,
1291 position: "absolute",
1292 right: 16,
1293 })}
1294 >
1295 <GlassSurface
1296 chrome="none"
1297 glassEffectStyle="regular"
1298 tintColor="transparent"
1299 style={{
1300 alignItems: "center",
1301 borderRadius: 24,
1302 height: 48,
1303 justifyContent: "center",
1304 width: 48,
1305 }}
1306 pointerEvents="none"
1307 >
1308 <SymbolView
1309 name={{ ios: "keyboard", android: "keyboard" }}
1310 size={20}
1311 tintColor={terminalTheme.foreground}
1312 type="monochrome"
1313 />
1314 </GlassSurface>
1315 </Pressable>
1316 ) : null}
1317 </>
1318 )}
1319 </View>
1320 </>
1321 );
1322}