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

ThreadTerminalRouteScreen.tsx

1,411 lines48.6 KB

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