Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadTerminalRouteScreen.tsx

1,334 lines42.7 KB

1import {
2 DEFAULT_TERMINAL_ID,
3 EnvironmentId,
4 type TerminalAttachStreamEvent,
5 ThreadId,
6} from "@t3tools/contracts";
7import type { KnownTerminalSession } from "@t3tools/client-runtime";
8import { SymbolView } from "expo-symbols";
9import { Stack, useLocalSearchParams, useRouter } from "expo-router";
10import { useCallback, useEffect, useMemo, useRef, useState } from "react";
11import {
12 Pressable,
13 ScrollView,
14 Text as RNText,
15 View,
16 useColorScheme,
17 type LayoutChangeEvent,
18 type NativeScrollEvent,
19 type NativeSyntheticEvent,
20} from "react-native";
21import {
22 KeyboardController,
23 KeyboardEvents,
24 KeyboardStickyView,
25 useKeyboardState,
26} from "react-native-keyboard-controller";
27​
28import { EmptyState } from "../../components/EmptyState";
29import { GlassSurface } from "../../components/GlassSurface";
30import { LoadingScreen } from "../../components/LoadingScreen";
31import { buildThreadTerminalNavigation } from "../../lib/routes";
32import { getEnvironmentClient } from "../../state/environment-session-registry";
33import { useRemoteEnvironmentState } from "../../state/use-remote-environment-registry";
34import {
35 attachTerminalSession,
36 useKnownTerminalSessions,
37 useTerminalSession,
38 useTerminalSessionTarget,
39} from "../../state/use-terminal-session";
40import { useThreadSelection } from "../../state/use-thread-selection";
41import { useSelectedThreadDetail } from "../../state/use-thread-detail";
42import { TerminalSurface } from "./NativeTerminalSurface";
43import { getPierreTerminalTheme } from "./terminalTheme";
44import { loadPreferences, savePreferencesPatch } from "../../lib/storage";
45import { terminalDebugLog } from "./terminalDebugLog";
46import {
47 getTerminalBufferReplayKey,
48 getTerminalSurfaceReplayBuffer,
49 TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
50} from "./terminalBufferReplay";
51import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
52import {
53 resolveTerminalOpenLocation,
54 stagePendingTerminalLaunch,
55 takePendingTerminalLaunch,
56} from "./terminalLaunchContext";
57import {
58 basename,
59 buildTerminalMenuSessions,
60 getTerminalStatusLabel,
61 nextOpenTerminalId,
62 resolveTerminalSessionLabel,
63 type TerminalMenuSession,
64} from "./terminalMenu";
65import {
66 DEFAULT_TERMINAL_FONT_SIZE,
67 MAX_TERMINAL_FONT_SIZE,
68 MIN_TERMINAL_FONT_SIZE,
69 TERMINAL_FONT_SIZE_STEP,
70 normalizeTerminalFontSize,
71} from "./terminalPreferences";
72import {
73 cacheTerminalFontSize,
74 cacheTerminalGridSize,
75 getCachedTerminalFontSize,
76 getCachedTerminalGridSize,
77} from "./terminalUiState";
78​
79const DEFAULT_TERMINAL_COLS = 80;
80const DEFAULT_TERMINAL_ROWS = 24;
81const TERMINAL_ACCESSORY_HEIGHT = 52;
82const TERMINAL_ACCESSORY_FADE_WIDTH = 18;
83​
84type PendingModifier = "ctrl" | "meta";
85type HostPlatform = "mac" | "linux" | "windows" | "unknown";
86​
87type TerminalToolbarAction =
88 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
89 | { readonly kind: "clear"; readonly key: string; readonly label: string }
90 | {
91 readonly kind: "modifier";
92 readonly key: string;
93 readonly label: string;
94 readonly modifier: PendingModifier;
95 };
96​
97function getTerminalStatusTone(input: {
98 readonly status: TerminalMenuSession["status"];
99 readonly hasRunningSubprocess?: boolean;
100}): {
101 readonly tintColor: string;
102 readonly textColor: string;
103} {
104 if (input.status === "running") {
105 if (input.hasRunningSubprocess) {
106 return {
107 tintColor: "#fbbf24",
108 textColor: "#a3a3a3",
109 };
110 }
111​
112 return {
113 tintColor: "#34d399",
114 textColor: "#a3a3a3",
115 };
116 }
117​
118 if (input.status === "starting") {
119 return {
120 tintColor: "#f59e0b",
121 textColor: "#a3a3a3",
122 };
123 }
124​
125 if (input.status === "error") {
126 return {
127 tintColor: "#ef4444",
128 textColor: "#fca5a5",
129 };
130 }
131​
132 return {
133 tintColor: "#ef4444",
134 textColor: "#a3a3a3",
135 };
137​
138function firstRouteParam(value: string | string[] | undefined): string | null {
139 if (Array.isArray(value)) {
140 return value[0] ?? null;
141 }
142​
143 return value ?? null;
145​
146function inferHostPlatform(environmentLabel: string | null): HostPlatform {
147 const value = environmentLabel?.toLowerCase() ?? "";
148 if (
149 value.includes("mac") ||
150 value.includes("macbook") ||
151 value.includes("mac mini") ||
152 value.includes("imac") ||
153 value.includes("darwin")
154 ) {
155 return "mac";
156 }
157 if (value.includes("windows") || value.includes("win")) {
158 return "windows";
159 }
160 if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) {
161 return "linux";
162 }
163​
164 return "unknown";
166​
167function applyCtrlModifier(input: string): string {
168 const firstCharacter = input[0];
169 if (!firstCharacter) {
170 return input;
171 }
172​
173 const lowerCharacter = firstCharacter.toLowerCase();
174 if (lowerCharacter >= "a" && lowerCharacter <= "z") {
175 return String.fromCharCode(lowerCharacter.charCodeAt(0) - 96);
176 }
177​
178 if (firstCharacter === "@") return "\u0000";
179 if (firstCharacter === "[") return "\u001b";
180 if (firstCharacter === "\\") return "\u001c";
181 if (firstCharacter === "]") return "\u001d";
182 if (firstCharacter === "^") return "\u001e";
183 if (firstCharacter === "_") return "\u001f";
184 if (firstCharacter === "?") return "\u007f";
185​
186 return input;
188​
189function withAlpha(hexColor: string, alpha: string): string {
190 return /^#[0-9a-f]{6}$/i.test(hexColor) ? `${hexColor}${alpha}` : hexColor;
192​
193function pickRunningTerminalSessionForBootstrap(
194 sessions: ReadonlyArray<KnownTerminalSession>,
195): KnownTerminalSession | null {
196 const running = sessions.filter(
197 (session) => session.state.status === "running" || session.state.status === "starting",
198 );
199 if (running.length === 0) {
200 return null;
201 }
202 return (
203 running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ??
204 running[0] ??
205 null
206 );
208​
209export function ThreadTerminalRouteScreen() {
210 const router = useRouter();
211 const appearanceScheme = useColorScheme() === "light" ? "light" : "dark";
212 const { isLoadingSavedConnection } = useRemoteEnvironmentState();
213 const params = useLocalSearchParams<{
214 environmentId?: string | string[];
215 threadId?: string | string[];
216 terminalId?: string | string[];
217 }>();
218 const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
219 useThreadSelection();
220 const selectedThreadDetail = useSelectedThreadDetail();
221 const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
222 const routeThreadIdRaw = firstRouteParam(params.threadId);
223 const routeEnvironmentId = routeEnvironmentIdRaw
224 ? EnvironmentId.make(routeEnvironmentIdRaw)
225 : null;
226 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
227 const requestedTerminalId = firstRouteParam(params.terminalId);
228 const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
229 const cachedFontSize = getCachedTerminalFontSize();
230 const cachedRouteGridSize =
231 routeEnvironmentId && routeThreadId
232 ? getCachedTerminalGridSize({
233 environmentId: routeEnvironmentId,
234 threadId: routeThreadId,
235 terminalId,
236 })
237 : null;
238 const knownSessions = useKnownTerminalSessions({
239 environmentId: selectedThread?.environmentId ?? null,
240 threadId: selectedThread?.id ?? null,
241 });
242 const [lastGridSize, setLastGridSize] = useState(
243 cachedRouteGridSize ?? {
244 cols: DEFAULT_TERMINAL_COLS,
245 rows: DEFAULT_TERMINAL_ROWS,
246 },
247 );
248 const [fontSize, setFontSize] = useState(cachedFontSize ?? DEFAULT_TERMINAL_FONT_SIZE);
249 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
250 const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
251 const toolbarScrollGeometryRef = useRef({
252 contentWidth: 0,
253 offsetX: 0,
254 viewportWidth: 0,
255 });
256 const [toolbarScrollEdges, setToolbarScrollEdges] = useState({
257 showLeftFade: false,
258 showRightFade: false,
259 });
260 const hasOpenedRef = useRef(false);
261 const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
262 const attachStreamLogCountRef = useRef(0);
263 const firstNonEmptyBufferLoggedRef = useRef(false);
264 const lastBufferReplayKeyRef = useRef<string | null>(null);
265 const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
266 const [hasResolvedFontPreference, setHasResolvedFontPreference] = useState(
267 cachedFontSize !== null,
268 );
269 /** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */
270 const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);
271 const [pendingModifierState, setPendingModifierState] = useState<{
272 readonly terminalId: string;
273 readonly value: PendingModifier | null;
274 }>({
275 terminalId,
276 value: null,
277 });
278 const target = useTerminalSessionTarget({
279 environmentId: selectedThread?.environmentId ?? null,
280 threadId: selectedThread?.id ?? null,
281 terminalId,
282 });
283 const terminal = useTerminalSession(target);
284 const terminalKey = selectedThread
285 ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
286 : terminalId;
287 const bufferReplayKey = useMemo(
288 () => getTerminalBufferReplayKey({ terminalKey, fontSize }),
289 [fontSize, terminalKey],
290 );
291 if (lastBufferReplayKeyRef.current === null) {
292 lastBufferReplayKeyRef.current = bufferReplayKey;
293 }
294 const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
295 buffer: terminal.buffer,
296 replayKey: bufferReplayKey,
297 readyReplayKey: readyBufferReplayKey,
298 });
299 const isRunning = terminal.status === "running" || terminal.status === "starting";
300​
301 useEffect(() => {
302 terminalDebugLog("surface:props", {
303 terminalKey,
304 atomBufferLen: terminal.buffer.length,
305 surfaceBufferLen: terminalSurfaceBuffer.length,
306 replayKey: bufferReplayKey,
307 readyReplayKey: readyBufferReplayKey,
308 status: terminal.status,
309 version: terminal.version,
310 });
311 }, [
312 bufferReplayKey,
313 readyBufferReplayKey,
314 terminal.buffer.length,
315 terminal.status,
316 terminal.version,
317 terminalKey,
318 terminalSurfaceBuffer.length,
319 ]);
320​
321 useEffect(() => {
322 terminalDebugLog("session:status", {
323 terminalKey,
324 status: terminal.status,
325 error: terminal.error,
326 summary: terminal.summary?.cwd ?? null,
327 bufferLen: terminal.buffer.length,
328 version: terminal.version,
329 });
330 }, [
331 terminal.buffer.length,
332 terminal.error,
333 terminal.status,
334 terminal.summary?.cwd,
335 terminal.version,
336 terminalKey,
337 ]);
338​
339 useEffect(() => {
340 if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {
341 return;
342 }
343 firstNonEmptyBufferLoggedRef.current = true;
344 terminalDebugLog("session:first-nonempty-buffer", {
345 terminalKey,
346 length: terminal.buffer.length,
347 preview: terminal.buffer.slice(0, 160),
348 });
349 }, [terminal.buffer, terminal.buffer.length, terminalKey]);
350 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
351 const hostPlatform = useMemo(
352 () => inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
353 [selectedEnvironmentConnection?.environmentLabel],
354 );
355 const runningSession = useMemo(
356 () => pickRunningTerminalSessionForBootstrap(knownSessions),
357 [knownSessions],
358 );
359 const activeKnownSession = useMemo(
360 () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
361 [knownSessions, terminalId],
362 );
363​
364 const terminalAttachLaunchHintsRef = useRef({
365 terminalSummary: terminal.summary,
366 activeKnownSummary: activeKnownSession?.state.summary ?? null,
367 });
368 terminalAttachLaunchHintsRef.current = {
369 terminalSummary: terminal.summary,
370 activeKnownSummary: activeKnownSession?.state.summary ?? null,
371 };
372​
373 const terminalStatusTone = useMemo(
374 () =>
375 getTerminalStatusTone({
376 status: terminal.status,
377 hasRunningSubprocess: terminal.hasRunningSubprocess,
378 }),
379 [terminal.hasRunningSubprocess, terminal.status],
380 );
381 const terminalTheme = getPierreTerminalTheme(appearanceScheme);
382 const pendingModifier =
383 pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
384 const headerTitle = useMemo(() => {
385 const topLineParts = [
386 selectedEnvironmentConnection?.environmentLabel ?? null,
387 selectedThreadProject?.title ?? null,
388 ].filter((value): value is string => Boolean(value));
389​
390 return {
391 topLine: topLineParts.join(" \u00b7 "),
392 bottomLine: cwd ?? selectedThreadProject?.workspaceRoot ?? "",
393 };
394 }, [
395 cwd,
396 selectedEnvironmentConnection?.environmentLabel,
397 selectedThreadProject?.title,
398 selectedThreadProject?.workspaceRoot,
399 ]);
400 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
401 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
402 hostPlatform === "mac"
403 ? [
404 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
405 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
406 ]
407 : [
408 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
409 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
410 ];
411​
412 return [
413 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
414 ...modifierActions,
415 { kind: "send", key: "tab", label: "tab", data: "\t" },
416 { kind: "clear", key: "clear", label: "clear" },
417 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
418 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
419 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
420 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
421 { kind: "send", key: "tilde", label: "~", data: "~" },
422 { kind: "send", key: "pipe", label: "|", data: "|" },
423 { kind: "send", key: "slash", label: "/", data: "/" },
424 { kind: "send", key: "dash", label: "-", data: "-" },
425 ];
426 }, [hostPlatform]);
427 const keyboardState = useKeyboardState((state) => ({
428 height: state.height,
429 isVisible: state.isVisible,
430 }));
431 const isAccessoryVisible = keyboardState.isVisible && !isAccessoryDismissed;
432 const terminalBottomInset =
433 (keyboardState.isVisible ? keyboardState.height : 0) +
434 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
435​
436 useEffect(() => {
437 const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {
438 setIsAccessoryDismissed(false);
439 });
440 const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {
441 setIsAccessoryDismissed(true);
442 });
443​
444 return () => {
445 keyboardWillShow.remove();
446 keyboardWillHide.remove();
447 };
448 }, []);
449​
450 const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
451 () =>
452 buildTerminalMenuSessions({
453 knownSessions,
454 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
455 currentSession: {
456 terminalId,
457 cwd: cwd ?? null,
458 status: terminal.status,
459 hasRunningSubprocess: terminal.hasRunningSubprocess,
460 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
461 updatedAt: terminal.updatedAt,
462 },
463 }),
464 [
465 cwd,
466 knownSessions,
467 selectedThreadProject?.workspaceRoot,
468 terminal.hasRunningSubprocess,
469 terminal.summary,
470 terminal.status,
471 terminal.updatedAt,
472 terminalId,
473 ],
474 );
475​
476 const logAttachStreamEvent = useCallback((event: TerminalAttachStreamEvent) => {
477 const n = ++attachStreamLogCountRef.current;
478 if (event.type === "output" && n > 32 && n % 64 !== 0) {
479 return;
480 }
481 if (event.type === "snapshot") {
482 terminalDebugLog("attach:stream", {
483 n,
484 type: event.type,
485 status: event.snapshot.status,
486 historyLen: event.snapshot.history.length,
487 cwd: event.snapshot.cwd,
488 });
489 return;
490 }
491 if (event.type === "output") {
492 terminalDebugLog("attach:stream", { n, type: event.type, dataLen: event.data.length });
493 return;
494 }
495 terminalDebugLog("attach:stream", { n, type: event.type });
496 }, []);
497​
498 const attachTerminal = useCallback(() => {
499 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
500 terminalDebugLog("attach:abort", { reason: "no-thread-or-workspace" });
501 return null;
502 }
503​
504 const client = getEnvironmentClient(selectedThread.environmentId);
505 if (!client) {
506 terminalDebugLog("attach:abort", {
507 reason: "no-environment-client",
508 environmentId: selectedThread.environmentId,
509 });
510 return null;
511 }
512​
513 const pendingLaunchTarget = {
514 environmentId: selectedThread.environmentId,
515 threadId: selectedThread.id,
516 terminalId,
517 };
518 const pendingLaunch = takePendingTerminalLaunch(pendingLaunchTarget);
519 let initialInputSent = false;
520​
521 try {
522 const launchLocation = pendingLaunch
523 ? {
524 cwd: pendingLaunch.cwd,
525 worktreePath: pendingLaunch.worktreePath,
526 }
527 : resolveTerminalOpenLocation({
528 terminalLocation: terminalAttachLaunchHintsRef.current.terminalSummary,
529 activeSessionLocation: terminalAttachLaunchHintsRef.current.activeKnownSummary,
530 workspaceRoot: selectedThreadProject.workspaceRoot,
531 threadShellWorktreePath: selectedThread.worktreePath ?? null,
532 threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
533 });
534​
535 terminalDebugLog("attach:start", {
536 terminalId,
537 threadId: selectedThread.id,
538 cols: lastGridSize.cols,
539 rows: lastGridSize.rows,
540 cwd: launchLocation.cwd,
541 worktreePath: launchLocation.worktreePath,
542 });
543​
544 return attachTerminalSession({
545 environmentId: selectedThread.environmentId,
546 client,
547 terminal: {
548 threadId: selectedThread.id,
549 terminalId,
550 cwd: launchLocation.cwd,
551 worktreePath: launchLocation.worktreePath,
552 cols: lastGridSize.cols,
553 rows: lastGridSize.rows,
554 env: pendingLaunch?.env,
555 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
556 },
557 onEvent: logAttachStreamEvent,
558 onSnapshot: () => {
559 if (!pendingLaunch?.initialInput || initialInputSent) {
560 return;
561 }
562​
563 initialInputSent = true;
564 void client.terminal.write({
565 threadId: selectedThread.id,
566 terminalId,
567 data: pendingLaunch.initialInput,
568 });
569 },
570 });
571 } catch (error) {
572 terminalDebugLog("attach:error", {
573 message: error instanceof Error ? error.message : String(error),
574 });
575 if (pendingLaunch) {
576 stagePendingTerminalLaunch({
577 target: pendingLaunchTarget,
578 launch: pendingLaunch,
579 });
580 }
581​
582 throw error;
583 }
584 }, [
585 lastGridSize.cols,
586 lastGridSize.rows,
587 logAttachStreamEvent,
588 selectedThreadDetail?.worktreePath,
589 selectedThread,
590 selectedThreadProject?.workspaceRoot,
591 terminalId,
592 ]);
593​
594 const attachTerminalRef = useRef(attachTerminal);
595 attachTerminalRef.current = attachTerminal;
596 const selectedThreadRef = useRef(selectedThread);
597 selectedThreadRef.current = selectedThread;
598 const selectedThreadProjectBootstrapRef = useRef(selectedThreadProject);
599 selectedThreadProjectBootstrapRef.current = selectedThreadProject;
600 const runningSessionRef = useRef(runningSession);
601 runningSessionRef.current = runningSession;
602 const terminalBootstrapRef = useRef({
603 status: terminal.status,
604 bufferLen: terminal.buffer.length,
605 });
606 terminalBootstrapRef.current = {
607 status: terminal.status,
608 bufferLen: terminal.buffer.length,
609 };
610​
611 useEffect(() => {
612 hasOpenedRef.current = false;
613 attachStreamLogCountRef.current = 0;
614 firstNonEmptyBufferLoggedRef.current = false;
615 }, [terminalKey]);
616​
617 const clearBufferReplayTimer = useCallback(() => {
618 if (bufferReplayTimerRef.current !== null) {
619 clearTimeout(bufferReplayTimerRef.current);
620 bufferReplayTimerRef.current = null;
621 }
622 }, []);
623​
624 const scheduleBufferReplayReady = useCallback(() => {
625 clearBufferReplayTimer();
626 const replayKey = bufferReplayKey;
627 terminalDebugLog("replay:schedule-ready", {
628 replayKey,
629 delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
630 });
631 bufferReplayTimerRef.current = setTimeout(() => {
632 bufferReplayTimerRef.current = null;
633 setReadyBufferReplayKey(replayKey);
634 terminalDebugLog("replay:ready", { replayKey });
635 }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
636 }, [bufferReplayKey, clearBufferReplayTimer]);
637​
638 useEffect(() => {
639 if (lastBufferReplayKeyRef.current === bufferReplayKey) {
640 return;
641 }
642​
643 lastBufferReplayKeyRef.current = bufferReplayKey;
644 clearBufferReplayTimer();
645 setReadyBufferReplayKey(null);
646 }, [bufferReplayKey, clearBufferReplayTimer]);
647​
648 useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
649​
650 useEffect(() => {
651 if (!routeEnvironmentId || !routeThreadId) {
652 setLastGridSize({
653 cols: DEFAULT_TERMINAL_COLS,
654 rows: DEFAULT_TERMINAL_ROWS,
655 });
656 return;
657 }
658​
659 setLastGridSize(
660 getCachedTerminalGridSize({
661 environmentId: routeEnvironmentId,
662 threadId: routeThreadId,
663 terminalId,
664 }) ?? {
665 cols: DEFAULT_TERMINAL_COLS,
666 rows: DEFAULT_TERMINAL_ROWS,
667 },
668 );
669 setHasMeasuredSurface(true);
670 }, [routeEnvironmentId, routeThreadId, terminalId]);
671​
672 useEffect(() => {
673 let cancelled = false;
674​
675 void loadPreferences()
676 .then((preferences) => {
677 if (cancelled) {
678 return;
679 }
680​
681 setFontSize(cacheTerminalFontSize(preferences.terminalFontSize));
682 setHasResolvedFontPreference(true);
683 })
684 .catch(() => {
685 if (cancelled) {
686 return;
687 }
688​
689 setHasResolvedFontPreference(true);
690 });
691​
692 return () => {
693 cancelled = true;
694 };
695 }, []);
696​
697 useEffect(() => {
698 if (!hasResolvedFontPreference) {
699 return;
700 }
701​
702 cacheTerminalFontSize(fontSize);
703 void savePreferencesPatch({
704 terminalFontSize: normalizeTerminalFontSize(fontSize),
705 });
706 }, [fontSize, hasResolvedFontPreference]);
707​
708 // Subscribes `terminal.attach` once per route+terminal until thread/env/attach args change.
709 // Use refs for `attachTerminal` / `selectedThread` / `runningSession`: their identities change when
710 // unrelated store updates (e.g. terminal buffer) re-render the parent, which was firing cleanup
711 // → detach immediately after the first snapshot.
712 useEffect(() => {
713 if (!hasResolvedFontPreference || !hasMeasuredSurface) {
714 return;
715 }
716​
717 const thread = selectedThreadRef.current;
718 const project = selectedThreadProjectBootstrapRef.current;
719 const running = runningSessionRef.current;
720 const termSnap = terminalBootstrapRef.current;
721​
722 const bootstrapAction = resolveTerminalRouteBootstrap({
723 hasThread: thread !== null,
724 hasWorkspaceRoot: Boolean(project?.workspaceRoot),
725 hasOpened: hasOpenedRef.current,
726 requestedTerminalId,
727 currentTerminalId: terminalId,
728 runningTerminalId: running?.target.terminalId ?? null,
729 currentTerminalStatus: termSnap.status,
730 // Metadata summary (cwd/status) is not scrollback. Only `terminal.attach` fills `buffer`;
731 // treating summary as "hydrated" skipped attach while status was running → empty surface.
732 hasCurrentTerminalHydration: termSnap.bufferLen > 0,
733 });
734 if (bootstrapAction.kind !== "idle") {
735 terminalDebugLog("bootstrap:action", {
736 kind: bootstrapAction.kind,
737 hasOpenedBefore: hasOpenedRef.current,
738 hasHydration: termSnap.bufferLen > 0,
739 terminalStatus: termSnap.status,
740 bufLen: termSnap.bufferLen,
741 });
742 }
743 if (bootstrapAction.kind === "idle" || !thread) {
744 return;
745 }
746​
747 if (bootstrapAction.kind === "redirect") {
748 router.replace(buildThreadTerminalNavigation(thread, bootstrapAction.terminalId));
749 return;
750 }
751​
752 hasOpenedRef.current = true;
753 try {
754 const detach = attachTerminalRef.current();
755 terminalDebugLog("bootstrap:subscribe", { hasDetach: Boolean(detach) });
756 if (!detach) {
757 hasOpenedRef.current = false;
758 return;
759 }
760 return () => {
761 detach();
762 hasOpenedRef.current = false;
763 terminalDebugLog("bootstrap:unsubscribe");
764 };
765 } catch (error) {
766 hasOpenedRef.current = false;
767 terminalDebugLog("bootstrap:attach-threw", {
768 message: error instanceof Error ? error.message : String(error),
769 });
770 return;
771 }
772 }, [
773 hasMeasuredSurface,
774 hasResolvedFontPreference,
775 requestedTerminalId,
776 router,
777 selectedThread?.environmentId,
778 selectedThread?.id,
779 selectedThreadProject?.workspaceRoot,
780 terminalId,
781 ]);
782​
783 const writeInput = useCallback(
784 (data: string) => {
785 if (!selectedThread || !isRunning) {
786 return;
787 }
788​
789 const client = getEnvironmentClient(selectedThread.environmentId);
790 if (!client) {
791 return;
792 }
793​
794 void client.terminal.write({
795 threadId: selectedThread.id,
796 terminalId,
797 data,
798 });
799 },
800 [isRunning, selectedThread, terminalId],
801 );
802​
803 const handleInput = useCallback(
804 (data: string) => {
805 if (data.length === 0) {
806 return;
807 }
808​
809 if (pendingModifier === "ctrl") {
810 setPendingModifierState({ terminalId, value: null });
811 writeInput(applyCtrlModifier(data));
812 } else if (pendingModifier === "meta") {
813 setPendingModifierState({ terminalId, value: null });
814 writeInput(`\u001b${data}`);
815 } else {
816 writeInput(data);
817 }
818 },
819 [pendingModifier, terminalId, writeInput],
820 );
821​
822 const handleResize = useCallback(
823 (size: { readonly cols: number; readonly rows: number }) => {
824 terminalDebugLog("native:onResize", {
825 cols: size.cols,
826 rows: size.rows,
827 terminalKey,
828 });
829 setHasMeasuredSurface(true);
830 if (readyBufferReplayKey !== bufferReplayKey) {
831 scheduleBufferReplayReady();
832 }
833 if (routeEnvironmentId && routeThreadId) {
834 cacheTerminalGridSize(
835 {
836 environmentId: routeEnvironmentId,
837 threadId: routeThreadId,
838 terminalId,
839 },
840 size,
841 );
842 }
843 if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
844 return;
845 }
846​
847 setLastGridSize(size);
848 if (!selectedThread || !isRunning) {
849 return;
850 }
851​
852 const client = getEnvironmentClient(selectedThread.environmentId);
853 if (!client) {
854 return;
855 }
856​
857 void client.terminal.resize({
858 threadId: selectedThread.id,
859 terminalId,
860 cols: size.cols,
861 rows: size.rows,
862 });
863 },
864 [
865 isRunning,
866 lastGridSize.cols,
867 lastGridSize.rows,
868 bufferReplayKey,
869 readyBufferReplayKey,
870 routeEnvironmentId,
871 routeThreadId,
872 scheduleBufferReplayReady,
873 selectedThread,
874 terminalId,
875 terminalKey,
876 ],
877 );
878​
879 const handleSelectTerminal = useCallback(
880 (nextTerminalId: string) => {
881 if (!selectedThread || nextTerminalId === terminalId) {
882 return;
883 }
884​
885 router.replace(buildThreadTerminalNavigation(selectedThread, nextTerminalId));
886 },
887 [router, selectedThread, terminalId],
888 );
889​
890 const handleOpenNewTerminal = useCallback(() => {
891 if (!selectedThread) {
892 return;
893 }
894​
895 router.replace(
896 buildThreadTerminalNavigation(
897 selectedThread,
898 nextOpenTerminalId({
899 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
900 activeRouteTerminalId: terminalId,
901 }),
902 ),
903 );
904 }, [router, selectedThread, terminalId, terminalMenuSessions]);
905​
906 const adjustFontSize = useCallback((delta: number) => {
907 setTimeout(() => {
908 setFontSize((current) => cacheTerminalFontSize(current + delta));
909 }, 0);
910 }, []);
911​
912 const handleDecreaseFontSize = useCallback(() => {
913 adjustFontSize(-TERMINAL_FONT_SIZE_STEP);
914 }, [adjustFontSize]);
915​
916 const handleIncreaseFontSize = useCallback(() => {
917 adjustFontSize(TERMINAL_FONT_SIZE_STEP);
918 }, [adjustFontSize]);
919​
920 const handleClearTerminal = useCallback(() => {
921 if (!selectedThread) {
922 return;
923 }
924​
925 const client = getEnvironmentClient(selectedThread.environmentId);
926 if (!client) {
927 return;
928 }
929​
930 setPendingModifierState({ terminalId, value: null });
931 void client.terminal.clear({
932 threadId: selectedThread.id,
933 terminalId,
934 });
935 }, [selectedThread, terminalId]);
936​
937 const handleToolbarActionPress = useCallback(
938 (action: TerminalToolbarAction) => {
939 if (action.kind === "modifier") {
940 setPendingModifierState((current) => ({
941 terminalId,
942 value:
943 (current.terminalId === terminalId ? current.value : null) === action.modifier
944 ? null
945 : action.modifier,
946 }));
947 return;
948 }
949​
950 if (action.kind === "clear") {
951 handleClearTerminal();
952 return;
953 }
954​
955 setPendingModifierState({ terminalId, value: null });
956 if (pendingModifier === "ctrl") {
957 writeInput(applyCtrlModifier(action.data));
958 } else if (pendingModifier === "meta") {
959 writeInput(`\u001b${action.data}`);
960 } else {
961 writeInput(action.data);
962 }
963 },
964 [handleClearTerminal, pendingModifier, terminalId, writeInput],
965 );
966​
967 const updateToolbarScrollEdges = useCallback(
968 (patch: Partial<(typeof toolbarScrollGeometryRef)["current"]>) => {
969 const nextGeometry = { ...toolbarScrollGeometryRef.current, ...patch };
970 toolbarScrollGeometryRef.current = nextGeometry;
971 const nextEdges = {
972 showLeftFade: nextGeometry.offsetX > 1,
973 showRightFade:
974 nextGeometry.offsetX + nextGeometry.viewportWidth < nextGeometry.contentWidth - 1,
975 };
976​
977 setToolbarScrollEdges((current) =>
978 current.showLeftFade === nextEdges.showLeftFade &&
979 current.showRightFade === nextEdges.showRightFade
980 ? current
981 : nextEdges,
982 );
983 },
984 [],
985 );
986​
987 const handleToolbarLayout = useCallback(
988 (event: LayoutChangeEvent) => {
989 updateToolbarScrollEdges({ viewportWidth: event.nativeEvent.layout.width });
990 },
991 [updateToolbarScrollEdges],
992 );
993​
994 const handleToolbarContentSizeChange = useCallback(
995 (contentWidth: number) => {
996 updateToolbarScrollEdges({ contentWidth });
997 },
998 [updateToolbarScrollEdges],
999 );
1000​
1001 const handleToolbarScroll = useCallback(
1002 (event: NativeSyntheticEvent<NativeScrollEvent>) => {
1003 updateToolbarScrollEdges({ offsetX: event.nativeEvent.contentOffset.x });
1004 },
1005 [updateToolbarScrollEdges],
1006 );
1007​
1008 const handleDismissKeyboard = useCallback(() => {
1009 setIsAccessoryDismissed(true);
1010 void KeyboardController.dismiss();
1011 }, []);
1012​
1013 const handleShowKeyboard = useCallback(() => {
1014 setKeyboardFocusRequest((current) => current + 1);
1015 }, []);
1016​
1017 if (!selectedThread) {
1018 if (isLoadingSavedConnection) {
1019 return <LoadingScreen message="Opening terminal…" />;
1021​
1022 return (
1023 <View className="flex-1 bg-screen">
1024 <EmptyState
1025 title="Thread unavailable"
1026 detail="This terminal route needs an active thread and workspace."
1027 />
1028 </View>
1029 );
1031​
1032 if (!selectedThreadProject?.workspaceRoot) {
1033 return (
1034 <View className="flex-1 bg-screen">
1035 <EmptyState
1036 title="Terminal unavailable"
1037 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
1038 />
1039 </View>
1040 );
1042​
1043 return (
1044 <>
1045 <Stack.Screen
1046 options={{
1047 headerShown: true,
1048 headerBackButtonDisplayMode: "minimal",
1049 headerBackTitle: "",
1050 headerShadowVisible: false,
1051 headerStyle: { backgroundColor: terminalTheme.background },
1052 headerTintColor: terminalTheme.foreground,
1053 headerTitleAlign: "center",
1054 title: "",
1055 headerTitle: () => (
1056 <View
1057 style={{
1058 alignItems: "center",
1059 gap: 1,
1060 maxWidth: 240,
1061 }}
1063 <RNText
1064 numberOfLines={1}
1065 style={{
1066 color: terminalTheme.foreground,
1067 fontFamily: "DMSans_700Bold",
1068 fontSize: 13,
1069 lineHeight: 16,
1070 }}
1072 {headerTitle.topLine}
1073 </RNText>
1074 <RNText
1075 ellipsizeMode="middle"
1076 numberOfLines={1}
1077 style={{
1078 color: terminalTheme.mutedForeground,
1079 fontFamily: "Menlo",
1080 fontSize: 11,
1081 lineHeight: 14,
1082 }}
1084 {headerTitle.bottomLine}
1085 </RNText>
1086 </View>
1087 ),
1088 }}
1089 />
1090​
1091 <Stack.Toolbar placement="right">
1092 <Stack.Toolbar.Menu
1093 icon="circle.fill"
1094 style={{
1095 color: terminalStatusTone.textColor,
1096 fontFamily: "DMSans_700Bold",
1097 fontSize: 12,
1098 fontWeight: "700",
1099 }}
1100 tintColor={terminalStatusTone.tintColor}
1101 title="Terminal options"
1103 <Stack.Toolbar.Label>
1104 {getTerminalStatusLabel({
1105 status: terminal.status,
1106 hasRunningSubprocess: terminal.hasRunningSubprocess,
1107 })}
1108 </Stack.Toolbar.Label>
1109 <Stack.Toolbar.Menu icon="textformat.size" inline title="Text size">
1110 <Stack.Toolbar.Label>Text size</Stack.Toolbar.Label>
1111 <Stack.Toolbar.MenuAction
1112 disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
1113 discoverabilityLabel="Decrease terminal text size"
1114 onPress={handleDecreaseFontSize}
1116 <Stack.Toolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
1117 </Stack.Toolbar.MenuAction>
1118 <Stack.Toolbar.MenuAction
1119 disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
1120 discoverabilityLabel="Increase terminal text size"
1121 onPress={handleIncreaseFontSize}
1123 <Stack.Toolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</Stack.Toolbar.Label>
1124 </Stack.Toolbar.MenuAction>
1125 </Stack.Toolbar.Menu>
1126 {terminalMenuSessions.map((session) => (
1127 <Stack.Toolbar.MenuAction
1128 key={session.terminalId}
1129 icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
1130 onPress={() => handleSelectTerminal(session.terminalId)}
1131 subtitle={[getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
1132 .filter(Boolean)
1133 .join(" · ")}
1135 <Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
1136 </Stack.Toolbar.MenuAction>
1137 ))}
1138 <Stack.Toolbar.MenuAction
1139 icon="plus"
1140 onPress={handleOpenNewTerminal}
1141 subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
1143 <Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
1144 </Stack.Toolbar.MenuAction>
1145 </Stack.Toolbar.Menu>
1146 </Stack.Toolbar>
1147​
1148 <View style={{ flex: 1, backgroundColor: terminalTheme.background }}>
1149 <View style={{ flex: 1, paddingBottom: terminalBottomInset }}>
1150 <TerminalSurface
1151 buffer={terminalSurfaceBuffer}
1152 fontSize={fontSize}
1153 isRunning={isRunning}
1154 keyboardFocusRequest={keyboardFocusRequest}
1155 onInput={handleInput}
1156 onResize={handleResize}
1157 style={{ flex: 1 }}
1158 terminalKey={terminalKey}
1159 />
1160 </View>
1161​
1162 {isAccessoryVisible ? (
1163 <KeyboardStickyView
1164 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1165 offset={{ closed: 0, opened: 0 }}
1167 <View
1168 style={{
1169 backgroundColor: terminalTheme.background,
1170 borderTopColor: terminalTheme.border,
1171 borderTopWidth: 1,
1172 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1173 paddingBottom: 4,
1174 paddingHorizontal: 8,
1175 paddingTop: 4,
1176 }}
1178 <View style={{ alignItems: "center", flexDirection: "row", gap: 6 }}>
1179 <View style={{ flex: 1, position: "relative" }}>
1180 <ScrollView
1181 horizontal
1182 contentContainerStyle={{ alignItems: "center", gap: 6, paddingRight: 2 }}
1183 onContentSizeChange={handleToolbarContentSizeChange}
1184 onLayout={handleToolbarLayout}
1185 onScroll={handleToolbarScroll}
1186 scrollEventThrottle={16}
1187 showsHorizontalScrollIndicator={false}
1189 {terminalToolbarActions.map((action) => {
1190 const active =
1191 action.kind === "modifier" && pendingModifier === action.modifier;
1192​
1193 return (
1194 <Pressable
1195 key={action.key}
1196 onPress={() => handleToolbarActionPress(action)}
1197 style={({ pressed }) => ({
1198 alignItems: "center",
1199 backgroundColor: active
1200 ? withAlpha(
1201 terminalTheme.palette[10] ?? terminalTheme.foreground,
1202 "2e",
1204 : pressed
1205 ? withAlpha(terminalTheme.foreground, "1f")
1206 : withAlpha(terminalTheme.foreground, "12"),
1207 borderColor: active
1208 ? withAlpha(
1209 terminalTheme.palette[10] ?? terminalTheme.foreground,
1210 "52",
1212 : terminalTheme.border,
1213 borderRadius: 12,
1214 borderWidth: 1,
1215 justifyContent: "center",
1216 minWidth: action.label.length > 1 ? 46 : 38,
1217 paddingHorizontal: 11,
1218 paddingVertical: 8,
1219 })}
1221 <RNText
1222 style={{
1223 color: active
1224 ? (terminalTheme.palette[10] ?? terminalTheme.foreground)
1225 : terminalTheme.foreground,
1226 fontFamily: "DMSans_700Bold",
1227 fontSize: 12,
1228 fontWeight: "700",
1229 textTransform:
1230 action.kind === "modifier" || action.kind === "clear"
1231 ? "uppercase"
1232 : "none",
1233 }}
1235 {action.label}
1236 </RNText>
1237 </Pressable>
1238 );
1239 })}
1240 </ScrollView>
1241 {toolbarScrollEdges.showLeftFade ? (
1242 <View
1243 pointerEvents="none"
1244 style={{
1245 bottom: 0,
1246 experimental_backgroundImage: `linear-gradient(to right, ${terminalTheme.background} 0%, ${withAlpha(terminalTheme.background, "00")} 100%)`,
1247 left: 0,
1248 position: "absolute",
1249 top: 0,
1250 width: TERMINAL_ACCESSORY_FADE_WIDTH,
1251 }}
1252 />
1253 ) : null}
1254 {toolbarScrollEdges.showRightFade ? (
1255 <View
1256 pointerEvents="none"
1257 style={{
1258 bottom: 0,
1259 experimental_backgroundImage: `linear-gradient(to right, ${withAlpha(terminalTheme.background, "00")} 0%, ${terminalTheme.background} 100%)`,
1260 position: "absolute",
1261 right: 0,
1262 top: 0,
1263 width: TERMINAL_ACCESSORY_FADE_WIDTH,
1264 }}
1265 />
1266 ) : null}
1267 </View>
1268 <Pressable
1269 accessibilityLabel="Dismiss keyboard"
1270 accessibilityRole="button"
1271 onPress={handleDismissKeyboard}
1272 style={({ pressed }) => ({
1273 alignItems: "center",
1274 backgroundColor: pressed
1275 ? withAlpha(terminalTheme.foreground, "1f")
1276 : withAlpha(terminalTheme.foreground, "12"),
1277 borderColor: terminalTheme.border,
1278 borderRadius: 12,
1279 borderWidth: 1,
1280 justifyContent: "center",
1281 minWidth: 38,
1282 paddingHorizontal: 11,
1283 paddingVertical: 8,
1284 })}
1286 <SymbolView
1287 name={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1288 size={14}
1289 tintColor={terminalTheme.foreground}
1290 type="monochrome"
1291 />
1292 </Pressable>
1293 </View>
1294 </View>
1295 </KeyboardStickyView>
1296 ) : !keyboardState.isVisible ? (
1297 <Pressable
1298 accessibilityLabel="Show keyboard"
1299 accessibilityRole="button"
1300 onPress={handleShowKeyboard}
1301 style={({ pressed }) => ({
1302 bottom: 16,
1303 borderRadius: 28,
1304 opacity: pressed ? 0.72 : 1,
1305 position: "absolute",
1306 right: 16,
1307 })}
1309 <GlassSurface
1310 chrome="none"
1311 glassEffectStyle="regular"
1312 tintColor="transparent"
1313 style={{
1314 alignItems: "center",
1315 borderRadius: 24,
1316 height: 48,
1317 justifyContent: "center",
1318 width: 48,
1319 }}
1320 pointerEvents="none"
1322 <SymbolView
1323 name={{ ios: "keyboard", android: "keyboard" }}
1324 size={20}
1325 tintColor={terminalTheme.foreground}
1326 type="monochrome"
1327 />
1328 </GlassSurface>
1329 </Pressable>
1330 ) : null}
1331 </View>
1332 </>
1333 );