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

ThreadTerminalRouteScreen.tsx

1,412 lines48.5 KB

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