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

ThreadTerminalRouteScreen.tsx

1,441 lines49.4 KB

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