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