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