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