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