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 { SymbolView } from "expo-symbols";
4import { Stack, useLocalSearchParams, useRouter } from "expo-router";
5import { useCallback, useEffect, useMemo, useRef, useState } from "react";
6import { Pressable, Text as RNText, View, useColorScheme } from "react-native";
7import {
8 KeyboardController,
9 KeyboardEvents,
10 KeyboardStickyView,
11 useKeyboardState,
12} from "react-native-keyboard-controller";
13
14import {
15 ComposerToolbarButton,
16 ComposerToolbarRow,
17 ComposerToolbarScroller,
18} from "../../components/ComposerToolbarTrigger";
19import { EmptyState } from "../../components/EmptyState";
20import { GlassSurface } from "../../components/GlassSurface";
21import { LoadingScreen } from "../../components/LoadingScreen";
22import { environmentCatalog } from "../../connection/catalog";
23import { useEnvironmentPresentation } from "../../state/presentation";
24import { terminalEnvironment } from "../../state/terminal";
25import { useAtomCommand } from "../../state/use-atom-command";
26import { useWorkspaceState } from "../../state/workspace";
27import { buildThreadTerminalNavigation } from "../../lib/routes";
28import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
29import {
30 useAttachedTerminalSession,
31 useKnownTerminalSessions,
32} from "../../state/use-terminal-session";
33import { useThreadSelection } from "../../state/use-thread-selection";
34import { useSelectedThreadDetail } from "../../state/use-thread-detail";
35import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
36import { TerminalSurface } from "./NativeTerminalSurface";
37import { getPierreTerminalTheme } from "./terminalTheme";
38import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
39import { terminalDebugLog } from "./terminalDebugLog";
40import {
41 getTerminalBufferReplayKey,
42 getTerminalSurfaceReplayBuffer,
43 TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
44} from "./terminalBufferReplay";
45import {
46 resolveTerminalOpenLocation,
47 takePendingTerminalLaunch,
48 type PendingTerminalLaunch,
49} from "./terminalLaunchContext";
50import {
51 basename,
52 buildTerminalMenuSessions,
53 getTerminalStatusLabel,
54 nextOpenTerminalId,
55 resolveTerminalSessionLabel,
56 type TerminalMenuSession,
57} from "./terminalMenu";
58import {
59 DEFAULT_TERMINAL_FONT_SIZE,
60 MAX_TERMINAL_FONT_SIZE,
61 MIN_TERMINAL_FONT_SIZE,
62 TERMINAL_FONT_SIZE_STEP,
63 normalizeTerminalFontSize,
64} from "./terminalPreferences";
65import {
66 cacheTerminalFontSize,
67 cacheTerminalGridSize,
68 getCachedTerminalFontSize,
69 getCachedTerminalGridSize,
70} from "./terminalUiState";
71
72const DEFAULT_TERMINAL_COLS = 80;
73const DEFAULT_TERMINAL_ROWS = 24;
74const TERMINAL_ACCESSORY_HEIGHT = 52;
75
76type PendingModifier = "ctrl" | "meta";
77type HostPlatform = "mac" | "linux" | "windows" | "unknown";
78
79type TerminalToolbarAction =
80 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
81 | { readonly kind: "clear"; readonly key: string; readonly label: string }
82 | {
83 readonly kind: "modifier";
84 readonly key: string;
85 readonly label: string;
86 readonly modifier: PendingModifier;
87 };
88
89function firstRouteParam(value: string | string[] | undefined): string | null {
90 if (Array.isArray(value)) {
91 return value[0] ?? null;
92 }
93
94 return value ?? null;
95}
96
97function inferHostPlatform(environmentLabel: string | null): HostPlatform {
98 const value = environmentLabel?.toLowerCase() ?? "";
99 if (
100 value.includes("mac") ||
101 value.includes("macbook") ||
102 value.includes("mac mini") ||
103 value.includes("imac") ||
104 value.includes("darwin")
105 ) {
106 return "mac";
107 }
108 if (value.includes("windows") || value.includes("win")) {
109 return "windows";
110 }
111 if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) {
112 return "linux";
113 }
114
115 return "unknown";
116}
117
118function applyCtrlModifier(input: string): string {
119 const firstCharacter = input[0];
120 if (!firstCharacter) {
121 return input;
122 }
123
124 const lowerCharacter = firstCharacter.toLowerCase();
125 if (lowerCharacter >= "a" && lowerCharacter <= "z") {
126 return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);
127 }
128
129 if (firstCharacter === "@") return "\u0000";
130 if (firstCharacter === "[") return "\u001b";
131 if (firstCharacter === "\\") return "\u001c";
132 if (firstCharacter === "]") return "\u001d";
133 if (firstCharacter === "^") return "\u001e";
134 if (firstCharacter === "_") return "\u001f";
135 if (firstCharacter === "?") return "\u007f";
136
137 return input;
138}
139
140function pickRunningTerminalSessionForBootstrap(
141 sessions: ReadonlyArray<KnownTerminalSession>,
142): KnownTerminalSession | null {
143 const running = sessions.filter(
144 (session) => session.state.status === "running" || session.state.status === "starting",
145 );
146 if (running.length === 0) {
147 return null;
148 }
149 return (
150 running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ??
151 running[0] ??
152 null
153 );
154}
155
156export function ThreadTerminalRouteScreen() {
157 const router = useRouter();
158 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
159 const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
160 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
161 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
162 const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
163 const { state: workspaceState } = useWorkspaceState();
164 const params = useLocalSearchParams<{
165 environmentId?: string | string[];
166 threadId?: string | string[];
167 terminalId?: string | string[];
168 }>();
169 const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
170 useThreadSelection();
171 const selectedThreadDetail = useSelectedThreadDetail();
172 const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
173 const routeThreadIdRaw = firstRouteParam(params.threadId);
174 const routeEnvironmentId = routeEnvironmentIdRaw
175 ? EnvironmentId.make(routeEnvironmentIdRaw)
176 : null;
177 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
178 const environment = useEnvironmentPresentation(routeEnvironmentId);
179 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
180 const requestedTerminalId = firstRouteParam(params.terminalId);
181 const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
182 const cachedFontSize = getCachedTerminalFontSize();
183 const cachedRouteGridSize =
184 routeEnvironmentId && routeThreadId
185 ? getCachedTerminalGridSize({
186 environmentId: routeEnvironmentId,
187 threadId: routeThreadId,
188 terminalId,
189 })
190 : null;
191 const knownSessions = useKnownTerminalSessions({
192 environmentId: selectedThread?.environmentId ?? null,
193 threadId: selectedThread?.id ?? null,
194 });
195 const runningSession = useMemo(
196 () => pickRunningTerminalSessionForBootstrap(knownSessions),
197 [knownSessions],
198 );
199 const activeKnownSession = useMemo(
200 () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
201 [knownSessions, terminalId],
202 );
203 const launchTarget = useMemo(
204 () =>
205 selectedThread
206 ? {
207 environmentId: selectedThread.environmentId,
208 threadId: selectedThread.id,
209 terminalId,
210 }
211 : null,
212 [selectedThread, terminalId],
213 );
214 const launchTargetKey = launchTarget
215 ? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`
216 : null;
217 const [pendingLaunchEntry, setPendingLaunchEntry] = useState<{
218 readonly key: string | null;
219 readonly launch: PendingTerminalLaunch | null;
220 }>(() => ({
221 key: launchTargetKey,
222 launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
223 }));
224 const pendingLaunch =
225 pendingLaunchEntry.key === launchTargetKey ? pendingLaunchEntry.launch : null;
226 const hasResolvedPendingLaunch = pendingLaunchEntry.key === launchTargetKey;
227 const [initialAttachGridEntry, setInitialAttachGridEntry] = useState(() => ({
228 key: launchTargetKey,
229 size: cachedRouteGridSize ?? {
230 cols: DEFAULT_TERMINAL_COLS,
231 rows: DEFAULT_TERMINAL_ROWS,
232 },
233 }));
234 const initialAttachGridSize =
235 initialAttachGridEntry.key === launchTargetKey ? initialAttachGridEntry.size : null;
236 const [lastGridSize, setLastGridSize] = useState(
237 cachedRouteGridSize ?? {
238 cols: DEFAULT_TERMINAL_COLS,
239 rows: DEFAULT_TERMINAL_ROWS,
240 },
241 );
242 const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
243 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
244 const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
245 const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
246 const firstNonEmptyBufferLoggedRef = useRef(false);
247 const lastBufferReplayKeyRef = useRef<string | null>(null);
248 const sentInitialInputKeyRef = useRef<string | null>(null);
249 const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
250 const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState(
251 cachedFontSize !== null,
252 );
253 /** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */
254 const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);
255 const [pendingModifierState, setPendingModifierState] = useState<{
256 readonly terminalId: string;
257 readonly value: PendingModifier | null;
258 }>({
259 terminalId,
260 value: null,
261 });
262 const shouldRedirectToRunningTerminal =
263 requestedTerminalId === null &&
264 runningSession !== null &&
265 runningSession.target.terminalId !== terminalId;
266 const launchLocationCandidate = useMemo(() => {
267 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
268 return null;
269 }
270 if (pendingLaunch) {
271 return {
272 cwd: pendingLaunch.cwd,
273 worktreePath: pendingLaunch.worktreePath,
274 };
275 }
276 return resolveTerminalOpenLocation({
277 terminalLocation: activeKnownSession?.state.summary ?? null,
278 activeSessionLocation: activeKnownSession?.state.summary ?? null,
279 workspaceRoot: selectedThreadProject.workspaceRoot,
280 threadShellWorktreePath: selectedThread.worktreePath ?? null,
281 threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
282 });
283 }, [
284 activeKnownSession?.state.summary,
285 pendingLaunch,
286 selectedThread,
287 selectedThreadDetail?.worktreePath,
288 selectedThreadProject?.workspaceRoot,
289 ]);
290 const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
291 key: launchTargetKey,
292 location: launchLocationCandidate,
293 }));
294 const launchLocation =
295 initialLaunchLocationEntry.key === launchTargetKey ? initialLaunchLocationEntry.location : null;
296 const terminalAttachInput = useMemo(
297 () =>
298 selectedThread !== null &&
299 launchLocation !== null &&
300 hasResolvedPendingLaunch &&
301 initialAttachGridSize !== null &&
302 hasResolvedFontPreference &&
303 hasMeasuredSurface &&
304 isEnvironmentReady &&
305 !shouldRedirectToRunningTerminal
306 ? {
307 threadId: selectedThread.id,
308 terminalId,
309 cwd: launchLocation.cwd,
310 worktreePath: launchLocation.worktreePath,
311 cols: initialAttachGridSize.cols,
312 rows: initialAttachGridSize.rows,
313 ...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
314 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
315 }
316 : null,
317 [
318 hasMeasuredSurface,
319 hasResolvedFontPreference,
320 hasResolvedPendingLaunch,
321 initialAttachGridSize,
322 isEnvironmentReady,
323 launchLocation,
324 pendingLaunch,
325 selectedThread,
326 shouldRedirectToRunningTerminal,
327 terminalId,
328 ],
329 );
330 const terminal = useAttachedTerminalSession({
331 environmentId: selectedThread?.environmentId ?? null,
332 terminal: terminalAttachInput,
333 });
334 const terminalKey = selectedThread
335 ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
336 : terminalId;
337 const bufferReplayKey = useMemo(
338 () => getTerminalBufferReplayKey({ terminalKey, fontSize }),
339 [fontSize, terminalKey],
340 );
341 if (lastBufferReplayKeyRef.current === null) {
342 lastBufferReplayKeyRef.current = bufferReplayKey;
343 }
344 const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
345 buffer: terminal.buffer,
346 replayKey: bufferReplayKey,
347 readyReplayKey: readyBufferReplayKey,
348 });
349 const isRunning = terminal.status === "running" || terminal.status === "starting";
350
351 useEffect(() => {
352 terminalDebugLog("surface:props", {
353 terminalKey,
354 atomBufferLen: terminal.buffer.length,
355 surfaceBufferLen: terminalSurfaceBuffer.length,
356 replayKey: bufferReplayKey,
357 readyReplayKey: readyBufferReplayKey,
358 status: terminal.status,
359 version: terminal.version,
360 });
361 }, [
362 bufferReplayKey,
363 readyBufferReplayKey,
364 terminal.buffer.length,
365 terminal.status,
366 terminal.version,
367 terminalKey,
368 terminalSurfaceBuffer.length,
369 ]);
370
371 useEffect(() => {
372 terminalDebugLog("session:status", {
373 terminalKey,
374 status: terminal.status,
375 error: terminal.error,
376 summary: terminal.summary?.cwd ?? null,
377 bufferLen: terminal.buffer.length,
378 version: terminal.version,
379 });
380 }, [
381 terminal.buffer.length,
382 terminal.error,
383 terminal.status,
384 terminal.summary?.cwd,
385 terminal.version,
386 terminalKey,
387 ]);
388
389 useEffect(() => {
390 if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {
391 return;
392 }
393 firstNonEmptyBufferLoggedRef.current = true;
394 terminalDebugLog("session:first-nonempty-buffer", {
395 terminalKey,
396 length: terminal.buffer.length,
397 preview: terminal.buffer.slice(0, 160),
398 });
399 }, [terminal.buffer, terminal.buffer.length, terminalKey]);
400 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
401 const hostPlatform = useMemo(
402 () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
403 [selectedEnvironmentConnection?.environmentLabel],
404 );
405
406 const terminalTheme = getPierreTerminalTheme(appearanceScheme);
407 const pendingModifier =
408 pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
409 const headerTitle = useMemo(() => {
410 const topLineParts = [
411 selectedEnvironmentConnection?.environmentLabel ?? null,
412 selectedThreadProject?.title ?? null,
413 ].filter((value): value is string => Boolean(value));
414
415 return {
416 topLine: topLineParts.join(" \u00b7 "),
417 bottomLine: cwd ?? selectedThreadProject?.workspaceRoot ?? "",
418 };
419 }, [
420 cwd,
421 selectedEnvironmentConnection?.environmentLabel,
422 selectedThreadProject?.title,
423 selectedThreadProject?.workspaceRoot,
424 ]);
425 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
426 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
427 hostPlatform === "mac"
428 ? [
429 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
430 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
431 ]
432 : [
433 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
434 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
435 ];
436
437 return [
438 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
439 ...modifierActions,
440 { kind: "send", key: "tab", label: "tab", data: "\t" },
441 { kind: "clear", key: "clear", label: "clear" },
442 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
443 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
444 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
445 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
446 { kind: "send", key: "tilde", label: "~", data: "~" },
447 { kind: "send", key: "pipe", label: "|", data: "|" },
448 { kind: "send", key: "slash", label: "/", data: "/" },
449 { kind: "send", key: "dash", label: "-", data: "-" },
450 ];
451 }, [hostPlatform]);
452 const keyboardState = useKeyboardState((state) => ({
453 height: state.height,
454 isVisible: state.isVisible,
455 }));
456 const isAccessoryVisible = keyboardState.isVisible && !isAccessoryDismissed;
457 const terminalBottomInset =
458 (keyboardState.isVisible ? keyboardState.height : 0) +
459 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
460
461 useEffect(() => {
462 const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {
463 setIsAccessoryDismissed(false);
464 });
465 const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {
466 setIsAccessoryDismissed(true);
467 });
468
469 return () => {
470 keyboardWillShow.remove();
471 keyboardWillHide.remove();
472 };
473 }, []);
474
475 const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
476 () =>
477 buildTerminalMenuSessions({
478 knownSessions,
479 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
480 currentSession: {
481 terminalId,
482 cwd: cwd ?? null,
483 status: terminal.status,
484 hasRunningSubprocess: terminal.hasRunningSubprocess,
485 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
486 updatedAt: terminal.updatedAt,
487 },
488 }),
489 [
490 cwd,
491 knownSessions,
492 selectedThreadProject?.workspaceRoot,
493 terminal.hasRunningSubprocess,
494 terminal.summary,
495 terminal.status,
496 terminal.updatedAt,
497 terminalId,
498 ],
499 );
500
501 useEffect(() => {
502 if (pendingLaunchEntry.key === launchTargetKey) {
503 return;
504 }
505 setPendingLaunchEntry({
506 key: launchTargetKey,
507 launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
508 });
509 }, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);
510
511 useEffect(() => {
512 if (initialAttachGridEntry.key === launchTargetKey) {
513 return;
514 }
515 setInitialAttachGridEntry({
516 key: launchTargetKey,
517 size: cachedRouteGridSize ?? {
518 cols: DEFAULT_TERMINAL_COLS,
519 rows: DEFAULT_TERMINAL_ROWS,
520 },
521 });
522 }, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
523
524 useEffect(() => {
525 if (
526 initialLaunchLocationEntry.key === launchTargetKey &&
527 initialLaunchLocationEntry.location !== null
528 ) {
529 return;
530 }
531 if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {
532 return;
533 }
534 setInitialLaunchLocationEntry({
535 key: launchTargetKey,
536 location: launchLocationCandidate,
537 });
538 }, [
539 initialLaunchLocationEntry.key,
540 initialLaunchLocationEntry.location,
541 launchLocationCandidate,
542 launchTargetKey,
543 ]);
544
545 useEffect(() => {
546 if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
547 return;
548 }
549 router.replace(buildThreadTerminalNavigation(selectedThread, runningSession.target.terminalId));
550 }, [router, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
551
552 useEffect(() => {
553 const initialInput = pendingLaunch?.initialInput;
554 if (
555 !initialInput ||
556 !selectedThread ||
557 terminal.version === 0 ||
558 sentInitialInputKeyRef.current === launchTargetKey
559 ) {
560 return;
561 }
562 sentInitialInputKeyRef.current = launchTargetKey;
563 void writeTerminal({
564 environmentId: selectedThread.environmentId,
565 input: {
566 threadId: selectedThread.id,
567 terminalId,
568 data: initialInput,
569 },
570 });
571 }, [
572 launchTargetKey,
573 pendingLaunch?.initialInput,
574 selectedThread,
575 terminal.version,
576 terminalId,
577 writeTerminal,
578 ]);
579
580 useEffect(() => {
581 firstNonEmptyBufferLoggedRef.current = false;
582 sentInitialInputKeyRef.current = null;
583 }, [terminalKey]);
584
585 const clearBufferReplayTimer = useCallback(() => {
586 if (bufferReplayTimerRef.current !== null) {
587 clearTimeout(bufferReplayTimerRef.current);
588 bufferReplayTimerRef.current = null;
589 }
590 }, []);
591
592 const scheduleBufferReplayReady = useCallback(() => {
593 clearBufferReplayTimer();
594 const replayKey = bufferReplayKey;
595 terminalDebugLog("replay:schedule-ready", {
596 replayKey,
597 delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
598 });
599 bufferReplayTimerRef.current = setTimeout(() => {
600 bufferReplayTimerRef.current = null;
601 setReadyBufferReplayKey(replayKey);
602 terminalDebugLog("replay:ready", { replayKey });
603 }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
604 }, [bufferReplayKey, clearBufferReplayTimer]);
605
606 useEffect(() => {
607 if (lastBufferReplayKeyRef.current === bufferReplayKey) {
608 return;
609 }
610
611 lastBufferReplayKeyRef.current = bufferReplayKey;
612 clearBufferReplayTimer();
613 setReadyBufferReplayKey(null);
614 }, [bufferReplayKey, clearBufferReplayTimer]);
615
616 useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
617
618 useEffect(() => {
619 if (!routeEnvironmentId || !routeThreadId) {
620 setLastGridSize({
621 cols: DEFAULT_TERMINAL_COLS,
622 rows: DEFAULT_TERMINAL_ROWS,
623 });
624 return;
625 }
626
627 setLastGridSize(
628 getCachedTerminalGridSize({
629 environmentId: routeEnvironmentId,
630 threadId: routeThreadId,
631 terminalId,
632 }) ?? {
633 cols: DEFAULT_TERMINAL_COLS,
634 rows: DEFAULT_TERMINAL_ROWS,
635 },
636 );
637 setHasMeasuredSurface(true);
638 }, [routeEnvironmentId, routeThreadId, terminalId]);
639
640 useEffect(() => {
641 let cancelled = false;
642
643 void loadPreferences()
644 .then((preferences) => {
645 if (cancelled) {
646 return;
647 }
648
649 setFontSize(cacheTerminalFontSize(preferences.terminalFontSize));
650 setHasResolvedFontPreference(true);
651 })
652 .catch(() => {
653 if (cancelled) {
654 return;
655 }
656
657 setHasResolvedFontPreference(true);
658 });
659
660 return () => {
661 cancelled = true;
662 };
663 }, []);
664
665 useEffect(() => {
666 if (!hasResolvedFontPreference) {
667 return;
668 }
669
670 cacheTerminalFontSize(fontSize);
671 void savePreferencesPatch({
672 terminalFontSize: normalizeTerminalFontSize(fontSize),
673 });
674 }, [fontSize, hasResolvedFontPreference]);
675
676 const writeInput = useCallback(
677 (data: string) => {
678 if (!selectedThread || !isRunning) {
679 return;
680 }
681
682 void writeTerminal({
683 environmentId: selectedThread.environmentId,
684 input: {
685 threadId: selectedThread.id,
686 terminalId,
687 data,
688 },
689 });
690 },
691 [isRunning, selectedThread, terminalId, writeTerminal],
692 );
693
694 const handleInput = useCallback(
695 (data: string) => {
696 if (data.length === 0) {
697 return;
698 }
699
700 if (pendingModifier === "ctrl") {
701 setPendingModifierState({ terminalId, value: null });
702 writeInput(applyCtrlModifier(data));
703 } else if (pendingModifier === "meta") {
704 setPendingModifierState({ terminalId, value: null });
705 writeInput(`\u001b${data}`);
706 } else {
707 writeInput(data);
708 }
709 },
710 [pendingModifier, terminalId, writeInput],
711 );
712
713 const handleResize = useCallback(
714 (size: { readonly cols: number; readonly rows: number }) => {
715 terminalDebugLog("native:onResize", {
716 cols: size.cols,
717 rows: size.rows,
718 terminalKey,
719 });
720 setHasMeasuredSurface(true);
721 if (readyBufferReplayKey !== bufferReplayKey) {
722 scheduleBufferReplayReady();
723 }
724 if (routeEnvironmentId && routeThreadId) {
725 cacheTerminalGridSize(
726 {
727 environmentId: routeEnvironmentId,
728 threadId: routeThreadId,
729 terminalId,
730 },
731 size,
732 );
733 }
734 if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
735 return;
736 }
737
738 setLastGridSize(size);
739 if (!selectedThread || !isRunning) {
740 return;
741 }
742
743 void resizeTerminal({
744 environmentId: selectedThread.environmentId,
745 input: {
746 threadId: selectedThread.id,
747 terminalId,
748 cols: size.cols,
749 rows: size.rows,
750 },
751 });
752 },
753 [
754 isRunning,
755 lastGridSize.cols,
756 lastGridSize.rows,
757 bufferReplayKey,
758 readyBufferReplayKey,
759 routeEnvironmentId,
760 routeThreadId,
761 resizeTerminal,
762 scheduleBufferReplayReady,
763 selectedThread,
764 terminalId,
765 terminalKey,
766 ],
767 );
768
769 const handleSelectTerminal = useCallback(
770 (nextTerminalId: string) => {
771 if (!selectedThread || nextTerminalId === terminalId) {
772 return;
773 }
774
775 router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
776 },
777 [router, selectedThread, terminalId],
778 );
779
780 const handleOpenNewTerminal = useCallback(() => {
781 if (!selectedThread) {
782 return;
783 }
784
785 router.replace(
786 buildThreadTerminalNavigation(
787 selectedThread,
788 nextOpenTerminalId({
789 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
790 activeRouteTerminalId: terminalId,
791 }),
792 ),
793 );
794 }, [router, selectedThread, terminalId, terminalMenuSessions]);
795
796 const adjustFontSize = useCallback((delta: number) => {
797 setTimeout(() => {
798 setFontSize((current) => cacheTerminalFontSize(current + delta));
799 }, 0);
800 }, []);
801
802 const handleDecreaseFontSize = useCallback(() => {
803 adjustFontSize(-TERMINAL_FONT_SIZE_STEP);
804 }, [adjustFontSize]);
805
806 const handleIncreaseFontSize = useCallback(() => {
807 adjustFontSize(TERMINAL_FONT_SIZE_STEP);
808 }, [adjustFontSize]);
809
810 const handleClearTerminal = useCallback(() => {
811 if (!selectedThread) {
812 return;
813 }
814
815 setPendingModifierState({ terminalId, value: null });
816 void clearTerminal({
817 environmentId: selectedThread.environmentId,
818 input: {
819 threadId: selectedThread.id,
820 terminalId,
821 },
822 });
823 }, [clearTerminal, selectedThread, terminalId]);
824
825 const handleToolbarActionPress = useCallback(
826 (action: TerminalToolbarAction) => {
827 if (action.kind === "modifier") {
828 setPendingModifierState((current) => ({
829 terminalId,
830 value:
831 (current.terminalId === terminalId ? current.value : null) === action.modifier
832 ? null
833 : action.modifier,
834 }));
835 return;
836 }
837
838 if (action.kind === "clear") {
839 handleClearTerminal();
840 return;
841 }
842
843 setPendingModifierState({ terminalId, value: null });
844 if (pendingModifier === "ctrl") {
845 writeInput(applyCtrlModifier(action.data));
846 } else if (pendingModifier === "meta") {
847 writeInput(`\u001b${action.data}`);
848 } else {
849 writeInput(action.data);
850 }
851 },
852 [handleClearTerminal, pendingModifier, terminalId, writeInput],
853 );
854
855 const handleDismissKeyboard = useCallback(() => {
856 setIsAccessoryDismissed(true);
857 void KeyboardController.dismiss();
858 }, []);
859
860 const handleShowKeyboard = useCallback(() => {
861 setKeyboardFocusRequest((current) => current + 1);
862 }, []);
863 const handleRetryEnvironment = useCallback(() => {
864 if (routeEnvironmentId !== null) {
865 void retryEnvironment(routeEnvironmentId);
866 }
867 }, [retryEnvironment, routeEnvironmentId]);
868
869 if (!selectedThread) {
870 if (workspaceState.isLoadingConnections) {
871 return <LoadingScreen message="Opening terminal…" />;
872 }
873
874 return (
875 <View className="flex-1 bg-screen">
876 <EmptyState
877 title="Thread unavailable"
878 detail="This terminal route needs an active thread and workspace."
879 />
880 </View>
881 );
882 }
883
884 if (!selectedThreadProject?.workspaceRoot) {
885 return (
886 <View className="flex-1 bg-screen">
887 <EmptyState
888 title="Terminal unavailable"
889 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
890 />
891 </View>
892 );
893 }
894
895 if (!environment.isReady && environment.presentation === null) {
896 return <LoadingScreen message="Opening terminal…" />;
897 }
898
899 return (
900 <>
901 <Stack.Screen
902 options={{
903 headerShown: true,
904 headerBackButtonDisplayMode: "minimal",
905 headerBackTitle: "",
906 headerShadowVisible: false,
907 headerStyle: { backgroundColor: terminalTheme.background },
908 headerTintColor: terminalTheme.foreground,
909 headerTitleAlign: "center",
910 title: "",
911 headerTitle: () => (
912 <View
913 style={{
914 alignItems: "center",
915 gap: 1,
916 maxWidth: 240,
917 }}
918 >
919 <RNText
920 numberOfLines={1}
921 style={{
922 color: terminalTheme.foreground,
923 fontFamily: "DMSans_700Bold",
924 fontSize: MOBILE_TYPOGRAPHY.footnote.fontSize,
925 lineHeight: 16,
926 }}
927 >
928 {headerTitle.topLine}
929 </RNText>
930 <RNText
931 ellipsizeMode="middle"
932 numberOfLines={1}
933 style={{
934 color: terminalTheme.mutedForeground,
935 fontFamily: "Menlo",
936 fontSize: MOBILE_TYPOGRAPHY.caption.fontSize,
937 lineHeight: 14,
938 }}
939 >
940 {headerTitle.bottomLine}
941 </RNText>
942 </View>
943 ),
944 }}
945 />
946
947 {isEnvironmentReady ? (
948 <Stack.Toolbar placement="right">
949 <Stack.Toolbar.Menu icon="terminal" title="Terminal options" separateBackground>
950 <Stack.Toolbar.Label>
951 {getTerminalStatusLabel({
952 status: terminal.status,
953 hasRunningSubprocess: terminal.hasRunningSubprocess,
954 })}
955 </Stack.Toolbar.Label>
956 <Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
957 <Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
958 <Stack.Toolbar.MenuAction
959 disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
960 discoverabilityLabel="Decrease terminal text size"
961 onPress={handleDecreaseFontSize}
962 >
963 <Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
964 </Stack.Toolbar.MenuAction>
965 <Stack.Toolbar.MenuAction
966 disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
967 discoverabilityLabel="Increase terminal text size"
968 onPress={handleIncreaseFontSize}
969 >
970 <Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
971 </Stack.Toolbar.MenuAction>
972 </Stack.Toolbar.Menu>
973 {terminalMenuSessions.map((session) => (
974 <Stack.Toolbar.MenuAction
975 key={session.terminalId}
976 icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
977 onPress={() => handleSelectTerminal(session.terminalId)}
978 subtitle={[
979 getTerminalStatusLabel({ status: session.status }),
980 basename(session.cwd),
981 ]
982 .filter(Boolean)
983 .join(" · ")}
984 >
985 <Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
986 </Stack.Toolbar.MenuAction>
987 ))}
988 <Stack.Toolbar.MenuAction
989 icon="plus"
990 onPress={handleOpenNewTerminal}
991 subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
992 >
993 <Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
994 </Stack.Toolbar.MenuAction>
995 </Stack.Toolbar.Menu>
996 </Stack.Toolbar>
997 ) : null}
998
999 <View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
1000 {!isEnvironmentReady ? (
1001 <EnvironmentConnectionNotice
1002 environmentLabel={
1003 environment.presentation?.entry.target.label ??
1004 selectedEnvironmentConnection?.environmentLabel ??
1005 "Environment"
1006 }
1007 connection={
1008 environment.presentation?.connection ?? {
1009 phase: "available",
1010 error: null,
1011 traceId: null,
1012 }
1013 }
1014 resourceName="terminal"
1015 onRetry={handleRetryEnvironment}
1016 />
1017 ) : (
1018 <>
1019 <View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
1020 <TerminalSurface
1021 buffer={terminalSurfaceBuffer}
1022 fontSize={fontSize}
1023 isRunning={isRunning}
1024 keyboardFocusRequest={keyboardFocusRequest}
1025 onInput={handleInput}
1026 onResize={handleResize}
1027 style={{ flex: 1 }}
1028 terminalKey={terminalKey}
1029 />
1030 </View>
1031
1032 {isAccessoryVisible ? (
1033 <KeyboardStickyView
1034 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1035 offset={{ closed: 0, opened: 0 }}
1036 >
1037 <View
1038 style={{
1039 backgroundColor: terminalTheme.background,
1040 borderTopColor: terminalTheme.border,
1041 borderTopWidth: 1,
1042 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1043 }}
1044 >
1045 <ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
1046 <ComposerToolbarScroller
1047 contentPaddingRight={2}
1048 fadeOpaque={terminalTheme.background}
1049 fadeTransparent={`${terminalTheme.background}00`}
1050 >
1051 {terminalToolbarActions.map((action) => {
1052 const active =
1053 action.kind === "modifier" && pendingModifier === action.modifier;
1054
1055 return (
1056 <ComposerToolbarButton
1057 key={action.key}
1058 active={active}
1059 label={action.label}
1060 maxWidth={120}
1061 minWidth={action.label.length > 1 ? 56 : 44}
1062 onPress={() => handleToolbarActionPress(action)}
1063 showChevron={false}
1064 textTransform={
1065 action.kind === "modifier" || action.kind === "clear"
1066 ? "uppercase"
1067 : "none"
1068 }
1069 />
1070 );
1071 })}
1072 </ComposerToolbarScroller>
1073 <ComposerToolbarButton
1074 accessibilityLabel="Dismiss keyboard"
1075 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1076 onPress={handleDismissKeyboard}
1077 showChevron={false}
1078 />
1079 </ComposerToolbarRow>
1080 </View>
1081 </KeyboardStickyView>
1082 ) : !keyboardState.isVisible ? (
1083 <Pressable
1084 accessibilityLabel="Show keyboard"
1085 accessibilityRole="button"
1086 onPress={handleShowKeyboard}
1087 style={({ pressed }) => ({
1088 bottom: 16,
1089 borderRadius: 28,
1090 opacity: pressed ? 0.72 : 1,
1091 position: "absolute",
1092 right: 16,
1093 })}
1094 >
1095 <GlassSurface
1096 chrome="none"
1097 glassEffectStyle="regular"
1098 tintColor="transparent"
1099 style={{
1100 alignItems: "center",
1101 borderRadius: 24,
1102 height: 48,
1103 justifyContent: "center",
1104 width: 48,
1105 }}
1106 pointerEvents="none"
1107 >
1108 <SymbolView
1109 name={{ ios: "keyboard", android: "keyboard" }}
1110 size={20}
1111 tintColor={terminalTheme.foreground}
1112 type="monochrome"
1113 />
1114 </GlassSurface>
1115 </Pressable>
1116 ) : null}
1117 </>
1118 )}
1119 </View>
1120 </>
1121 );
1122}