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