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

ThreadTerminalRouteScreen.tsx

1,055 lines35.4 KB

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