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