Open History to see the last commit
1import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
2import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
3import type { MenuAction } from "@react-native-menu/menu";
4import { SymbolView } from "../../components/AppSymbol";
5import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
6import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
7import { useCallback, useEffect, useMemo, useRef, useState } from "react";
8import { Platform, Pressable, View } from "react-native";
9import * as Clipboard from "expo-clipboard";
10import * as Schema from "effect/Schema";
11import {
12 KeyboardController,
13 KeyboardEvents,
14 KeyboardStickyView,
15 useKeyboardState,
16} from "react-native-keyboard-controller";
17
18import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader";
19import {
20 ComposerToolbarButton,
21 ComposerToolbarRow,
22 ComposerToolbarScroller,
23} from "../../components/ComposerToolbar";
24import { ControlPillMenu } from "../../components/ControlPill";
25import { EmptyState } from "../../components/EmptyState";
26import { GlassSurface } from "../../components/GlassSurface";
27import { LoadingScreen } from "../../components/LoadingScreen";
28import { environmentCatalog } from "../../connection/catalog";
29import { useEnvironmentPresentation } from "../../state/presentation";
30import { terminalEnvironment } from "../../state/terminal";
31import { useAtomCommand } from "../../state/use-atom-command";
32import { useServerConfigs } from "../../state/entities";
33import { useWorkspaceState } from "../../state/workspace";
34import {
35 MAX_TERMINAL_FONT_SIZE,
36 MIN_TERMINAL_FONT_SIZE,
37 TERMINAL_FONT_SIZE_STEP,
38 stepTerminalFontSize,
39} from "../../lib/appearancePreferences";
40import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
41import {
42 useAttachedTerminalSession,
43 useKnownTerminalSessions,
44} from "../../state/use-terminal-session";
45import { useThreadSelection } from "../../state/use-thread-selection";
46import { useSelectedThreadProjection } from "../../state/use-thread-detail";
47import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
48import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
49import { TerminalSurface } from "./NativeTerminalSurface";
50import { getMobileTerminalTheme } from "./terminalTheme";
51import { terminalDebugLog } from "./terminalDebugLog";
52import {
53 getTerminalBufferReplayKey,
54 getTerminalSurfaceReplayBuffer,
55 TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
56} from "./terminalBufferReplay";
57import {
58 resolveTerminalOpenLocation,
59 takePendingTerminalLaunch,
60 type PendingTerminalLaunch,
61} from "./terminalLaunchContext";
62import {
63 basename,
64 buildTerminalMenuSessions,
65 getTerminalStatusLabel,
66 nextOpenTerminalId,
67 previousLiveTerminalId,
68 resolveTerminalSessionLabel,
69 type TerminalMenuSession,
70} from "./terminalMenu";
71import {
72 hostPlatformFromOs,
73 resolveModifiedTerminalInput,
74 type HostPlatform,
75 type PendingModifier,
76} from "./terminalInput";
77import { createTerminalPasteSession } from "./terminalPaste";
78import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";
79
80const DEFAULT_TERMINAL_COLS = 80;
81const DEFAULT_TERMINAL_ROWS = 24;
82const TERMINAL_ACCESSORY_HEIGHT = 52;
83const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
84
85class TerminalClipboardReadError extends Schema.TaggedErrorClass<TerminalClipboardReadError>()(
86 "TerminalClipboardReadError",
87 { terminalId: Schema.String, cause: Schema.Defect() },
88) {
89 override get message(): string {
90 return `Failed to read the clipboard for a paste into terminal ${this.terminalId}.`;
91 }
92}
93
94type TerminalToolbarAction =
95 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
96 | { readonly kind: "clear"; readonly key: string; readonly label: string }
97 | { readonly kind: "paste"; readonly key: string; readonly label: string }
98 | {
99 readonly kind: "modifier";
100 readonly key: string;
101 readonly label: string;
102 readonly modifier: PendingModifier;
103 };
104
105function firstRouteParam(value: string | string[] | undefined): string | null {
106 if (Array.isArray(value)) {
107 return value[0] ?? null;
108 }
109
110 return value ?? null;
111}
112
113function inferHostPlatform(environmentLabel: string | null): HostPlatform {
114 const value = environmentLabel?.toLowerCase() ?? "";
115 if (
116 value.includes("mac") ||
117 value.includes("macbook") ||
118 value.includes("mac mini") ||
119 value.includes("imac") ||
120 value.includes("darwin")
121 ) {
122 return "mac";
123 }
124 if (value.includes("windows") || value.includes("win")) {
125 return "windows";
126 }
127 if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) {
128 return "linux";
129 }
130
131 return "unknown";
132}
133
134function pickRunningTerminalSessionForBootstrap(
135 sessions: ReadonlyArray<KnownTerminalSession>,
136): KnownTerminalSession | null {
137 const running = sessions.filter(
138 (session) => session.state.status === "running" || session.state.status === "starting",
139 );
140 if (running.length === 0) {
141 return null;
142 }
143 return (
144 running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ??
145 running[0] ??
146 null
147 );
148}
149
150type ThreadTerminalRouteScreenProps = StaticScreenProps<{
151 readonly environmentId: string;
152 readonly threadId: string;
153 readonly terminalId?: string;
154}>;
155
156export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) {
157 const navigation = useNavigation();
158 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
159 const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");
160 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
161 const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close");
162 const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");
163 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
164 const { state: workspaceState } = useWorkspaceState();
165 const { layout, panes, togglePrimarySidebar } = useAdaptiveWorkspaceLayout();
166 const params = props.route.params;
167 const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
168 useThreadSelection();
169 const selectedThreadDetail = useSelectedThreadProjection();
170 const selectedThreadDetailWorktreePath =
171 selectedThreadDetail?.projection.thread.worktreePath ?? null;
172 const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
173 const routeThreadIdRaw = firstRouteParam(params.threadId);
174 const routeEnvironmentId = routeEnvironmentIdRaw
175 ? EnvironmentId.make(routeEnvironmentIdRaw)
176 : null;
177 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
178 const environment = useEnvironmentPresentation(routeEnvironmentId);
179 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
180 const requestedTerminalId = firstRouteParam(params.terminalId);
181 const terminalId = requestedTerminalId ?? DEFAULT_TERMINAL_ID;
182 const {
183 isReady: hasResolvedFontPreference,
184 appearance,
185 themeAppearance: appearanceScheme,
186 themeId,
187 setTerminalFontSize,
188 } = useAppearancePreferences();
189 const fontSize = appearance.terminalFontSize;
190 const cachedRouteGridSize =
191 routeEnvironmentId && routeThreadId
192 ? getCachedTerminalGridSize({
193 environmentId: routeEnvironmentId,
194 threadId: routeThreadId,
195 terminalId,
196 })
197 : null;
198 const knownSessions = useKnownTerminalSessions({
199 environmentId: selectedThread?.environmentId ?? null,
200 threadId: selectedThread?.id ?? null,
201 });
202 const runningSession = useMemo(
203 () => pickRunningTerminalSessionForBootstrap(knownSessions),
204 [knownSessions],
205 );
206 const activeKnownSession = useMemo(
207 () => knownSessions.find((session) => session.target.terminalId === terminalId) ?? null,
208 [knownSessions, terminalId],
209 );
210 const launchTarget = useMemo(
211 () =>
212 selectedThread
213 ? {
214 environmentId: selectedThread.environmentId,
215 threadId: selectedThread.id,
216 terminalId,
217 }
218 : null,
219 [selectedThread, terminalId],
220 );
221 const launchTargetKey = launchTarget
222 ? `${launchTarget.environmentId}:${launchTarget.threadId}:${launchTarget.terminalId}`
223 : null;
224 const [pendingLaunchEntry, setPendingLaunchEntry] = useState<{
225 readonly key: string | null;
226 readonly launch: PendingTerminalLaunch | null;
227 }>(() => ({
228 key: launchTargetKey,
229 launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
230 }));
231 const pendingLaunch =
232 pendingLaunchEntry.key === launchTargetKey ? pendingLaunchEntry.launch : null;
233 const hasResolvedPendingLaunch = pendingLaunchEntry.key === launchTargetKey;
234 const [initialAttachGridEntry, setInitialAttachGridEntry] = useState(() => ({
235 key: launchTargetKey,
236 size: cachedRouteGridSize ?? {
237 cols: DEFAULT_TERMINAL_COLS,
238 rows: DEFAULT_TERMINAL_ROWS,
239 },
240 }));
241 const initialAttachGridSize =
242 initialAttachGridEntry.key === launchTargetKey ? initialAttachGridEntry.size : null;
243 const [lastGridSize, setLastGridSize] = useState(
244 cachedRouteGridSize ?? {
245 cols: DEFAULT_TERMINAL_COLS,
246 rows: DEFAULT_TERMINAL_ROWS,
247 },
248 );
249 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
250 const [isAccessoryDismissed, setIsAccessoryDismissed] = useState(false);
251 const bufferReplayTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
252 const firstNonEmptyBufferLoggedRef = useRef(false);
253 const lastBufferReplayKeyRef = useRef<string | null>(null);
254 const sentInitialInputKeyRef = useRef<string | null>(null);
255 const [readyBufferReplayKey, setReadyBufferReplayKey] = useState<string | null>(null);
256 /** Default grid is always valid for attach; onResize refines cols/rows. Requiring a cached size blocked bootstrap for new terminal routes. */
257 const [hasMeasuredSurface, setHasMeasuredSurface] = useState(true);
258 const [pendingModifierState, setPendingModifierState] = useState<{
259 readonly terminalId: string;
260 readonly value: PendingModifier | null;
261 }>({
262 terminalId,
263 value: null,
264 });
265 const shouldRedirectToRunningTerminal =
266 requestedTerminalId === null &&
267 runningSession !== null &&
268 runningSession.target.terminalId !== terminalId;
269 const launchLocationCandidate = useMemo(() => {
270 if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
271 return null;
272 }
273 if (pendingLaunch) {
274 return {
275 cwd: pendingLaunch.cwd,
276 worktreePath: pendingLaunch.worktreePath,
277 };
278 }
279 return resolveTerminalOpenLocation({
280 terminalLocation: activeKnownSession?.state.summary ?? null,
281 activeSessionLocation: activeKnownSession?.state.summary ?? null,
282 workspaceRoot: selectedThreadProject.workspaceRoot,
283 threadShellWorktreePath: selectedThread.worktreePath ?? null,
284 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
285 });
286 }, [
287 activeKnownSession?.state.summary,
288 pendingLaunch,
289 selectedThread,
290 selectedThreadDetailWorktreePath,
291 selectedThreadProject?.workspaceRoot,
292 ]);
293 const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
294 key: launchTargetKey,
295 location: launchLocationCandidate,
296 }));
297 const launchLocation =
298 initialLaunchLocationEntry.key === launchTargetKey ? initialLaunchLocationEntry.location : null;
299 const terminalAttachInput = useMemo(
300 () =>
301 selectedThread !== null &&
302 launchLocation !== null &&
303 hasResolvedPendingLaunch &&
304 initialAttachGridSize !== null &&
305 hasResolvedFontPreference &&
306 hasMeasuredSurface &&
307 isEnvironmentReady &&
308 !shouldRedirectToRunningTerminal
309 ? {
310 threadId: selectedThread.id,
311 terminalId,
312 cwd: launchLocation.cwd,
313 worktreePath: launchLocation.worktreePath,
314 cols: initialAttachGridSize.cols,
315 rows: initialAttachGridSize.rows,
316 ...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
317 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
318 }
319 : null,
320 [
321 hasMeasuredSurface,
322 hasResolvedFontPreference,
323 hasResolvedPendingLaunch,
324 initialAttachGridSize,
325 isEnvironmentReady,
326 launchLocation,
327 pendingLaunch,
328 selectedThread,
329 shouldRedirectToRunningTerminal,
330 terminalId,
331 ],
332 );
333 const terminal = useAttachedTerminalSession({
334 environmentId: selectedThread?.environmentId ?? null,
335 terminal: terminalAttachInput,
336 });
337 const terminalKey = selectedThread
338 ? `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`
339 : terminalId;
340 const bufferReplayKey = useMemo(
341 () => getTerminalBufferReplayKey({ terminalKey, fontSize }),
342 [fontSize, terminalKey],
343 );
344 if (lastBufferReplayKeyRef.current === null) {
345 lastBufferReplayKeyRef.current = bufferReplayKey;
346 }
347 const terminalSurfaceBuffer = getTerminalSurfaceReplayBuffer({
348 buffer: terminal.buffer,
349 replayKey: bufferReplayKey,
350 readyReplayKey: readyBufferReplayKey,
351 });
352 const isRunning = terminal.status === "running" || terminal.status === "starting";
353
354 // When the process ends while this screen is attached (e.g. typing `exit`),
355 // close the session and leave the screen, mirroring the web drawer's
356 // onSessionExited flow. Only react to a running -> exited transition
357 // observed on this screen so already-exited sessions can still be opened
358 // (they restart on attach).
359 const runningTerminalKeyRef = useRef<string | null>(null);
360 const reopenedStaleTerminalKeyRef = useRef<string | null>(null);
361 const pendingExitNavigationRef = useRef<string | null>(null);
362
363 // Attach subscriptions are cached with an idle TTL, so revisiting a
364 // terminal whose session ended while unobserved reuses the stale stream
365 // without a new attach RPC — the server never respawns anything. Detect
366 // that (dead status with processed events, never seen running here) and
367 // issue an explicit open; its snapshot flows into the live subscription.
368 useEffect(() => {
369 if (isRunning) {
370 reopenedStaleTerminalKeyRef.current = null;
371 return;
372 }
373 if (
374 terminalAttachInput === null ||
375 !selectedThread ||
376 (terminal.status !== "closed" && terminal.status !== "exited") ||
377 terminal.version === 0 ||
378 runningTerminalKeyRef.current === terminalKey ||
379 reopenedStaleTerminalKeyRef.current === terminalKey
380 ) {
381 return;
382 }
383 reopenedStaleTerminalKeyRef.current = terminalKey;
384 void openTerminal({
385 environmentId: selectedThread.environmentId,
386 input: {
387 threadId: selectedThread.id,
388 terminalId,
389 cwd: terminalAttachInput.cwd,
390 worktreePath: terminalAttachInput.worktreePath,
391 cols: terminalAttachInput.cols,
392 rows: terminalAttachInput.rows,
393 ...(terminalAttachInput.env ? { env: terminalAttachInput.env } : {}),
394 },
395 }).then((result) => {
396 // Release the guard on failure so a later render can retry the respawn.
397 if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) {
398 reopenedStaleTerminalKeyRef.current = null;
399 }
400 });
401 }, [
402 isRunning,
403 openTerminal,
404 selectedThread,
405 terminal.status,
406 terminal.version,
407 terminalAttachInput,
408 terminalId,
409 terminalKey,
410 ]);
411
412 useEffect(() => {
413 terminalDebugLog("surface:props", {
414 terminalKey,
415 atomBufferLen: terminal.buffer.length,
416 surfaceBufferLen: terminalSurfaceBuffer.length,
417 replayKey: bufferReplayKey,
418 readyReplayKey: readyBufferReplayKey,
419 status: terminal.status,
420 version: terminal.version,
421 });
422 }, [
423 bufferReplayKey,
424 readyBufferReplayKey,
425 terminal.buffer.length,
426 terminal.status,
427 terminal.version,
428 terminalKey,
429 terminalSurfaceBuffer.length,
430 ]);
431
432 useEffect(() => {
433 terminalDebugLog("session:status", {
434 terminalKey,
435 status: terminal.status,
436 error: terminal.error,
437 summary: terminal.summary?.cwd ?? null,
438 bufferLen: terminal.buffer.length,
439 version: terminal.version,
440 });
441 }, [
442 terminal.buffer.length,
443 terminal.error,
444 terminal.status,
445 terminal.summary?.cwd,
446 terminal.version,
447 terminalKey,
448 ]);
449
450 useEffect(() => {
451 if (terminal.buffer.length === 0 || firstNonEmptyBufferLoggedRef.current) {
452 return;
453 }
454 firstNonEmptyBufferLoggedRef.current = true;
455 terminalDebugLog("session:first-nonempty-buffer", {
456 terminalKey,
457 length: terminal.buffer.length,
458 preview: terminal.buffer.slice(0, 160),
459 });
460 }, [terminal.buffer, terminal.buffer.length, terminalKey]);
461 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
462 const serverConfigs = useServerConfigs();
463 const hostOs =
464 routeEnvironmentId === null
465 ? null
466 : (serverConfigs.get(routeEnvironmentId)?.environment.platform.os ?? null);
467 // The descriptor is authoritative; the label is only a hint until it arrives.
468 const hostPlatform = useMemo(
469 () =>
470 hostPlatformFromOs(hostOs) ??
471 inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
472 [hostOs, selectedEnvironmentConnection?.environmentLabel],
473 );
474
475 const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);
476 const usesNativeHeaderGlass = Platform.OS === "ios";
477 const pendingModifier =
478 pendingModifierState.terminalId === terminalId ? pendingModifierState.value : null;
479 const headerSubtitle = selectedThreadProject?.title ?? "";
480 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
481 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
482 hostPlatform === "mac"
483 ? [
484 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
485 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
486 ]
487 : [
488 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
489 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
490 ];
491
492 return [
493 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
494 ...modifierActions,
495 { kind: "send", key: "tab", label: "tab", data: "\t" },
496 { kind: "paste", key: "paste", label: "paste" },
497 { kind: "clear", key: "clear", label: "clear" },
498 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
499 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
500 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
501 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
502 { kind: "send", key: "tilde", label: "~", data: "~" },
503 { kind: "send", key: "pipe", label: "|", data: "|" },
504 { kind: "send", key: "slash", label: "/", data: "/" },
505 { kind: "send", key: "dash", label: "-", data: "-" },
506 ];
507 }, [hostPlatform]);
508 const keyboardState = useKeyboardState((state) => ({
509 height: state.height,
510 isVisible: state.isVisible,
511 }));
512 const isAccessoryVisible = keyboardState.isVisible && !isAccessoryDismissed;
513 const terminalBottomInset =
514 (keyboardState.isVisible ? keyboardState.height : 0) +
515 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
516
517 useEffect(() => {
518 const keyboardWillShow = KeyboardEvents.addListener("keyboardWillShow", () => {
519 setIsAccessoryDismissed(false);
520 });
521 const keyboardWillHide = KeyboardEvents.addListener("keyboardWillHide", () => {
522 setIsAccessoryDismissed(true);
523 });
524
525 return () => {
526 keyboardWillShow.remove();
527 keyboardWillHide.remove();
528 };
529 }, []);
530
531 const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
532 () =>
533 buildTerminalMenuSessions({
534 knownSessions,
535 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
536 currentSession: {
537 terminalId,
538 cwd: cwd ?? null,
539 status: terminal.status,
540 hasRunningSubprocess: terminal.hasRunningSubprocess,
541 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
542 updatedAt: terminal.updatedAt,
543 },
544 }),
545 [
546 cwd,
547 knownSessions,
548 selectedThreadProject?.workspaceRoot,
549 terminal.hasRunningSubprocess,
550 terminal.summary,
551 terminal.status,
552 terminal.updatedAt,
553 terminalId,
554 ],
555 );
556
557 useEffect(() => {
558 if (pendingLaunchEntry.key === launchTargetKey) {
559 return;
560 }
561 setPendingLaunchEntry({
562 key: launchTargetKey,
563 launch: launchTarget === null ? null : takePendingTerminalLaunch(launchTarget),
564 });
565 }, [launchTarget, launchTargetKey, pendingLaunchEntry.key]);
566
567 useEffect(() => {
568 if (initialAttachGridEntry.key === launchTargetKey) {
569 return;
570 }
571 setInitialAttachGridEntry({
572 key: launchTargetKey,
573 size: cachedRouteGridSize ?? {
574 cols: DEFAULT_TERMINAL_COLS,
575 rows: DEFAULT_TERMINAL_ROWS,
576 },
577 });
578 }, [cachedRouteGridSize, initialAttachGridEntry.key, launchTargetKey]);
579
580 useEffect(() => {
581 if (
582 initialLaunchLocationEntry.key === launchTargetKey &&
583 initialLaunchLocationEntry.location !== null
584 ) {
585 return;
586 }
587 if (initialLaunchLocationEntry.key === launchTargetKey && launchLocationCandidate === null) {
588 return;
589 }
590 setInitialLaunchLocationEntry({
591 key: launchTargetKey,
592 location: launchLocationCandidate,
593 });
594 }, [
595 initialLaunchLocationEntry.key,
596 initialLaunchLocationEntry.location,
597 launchLocationCandidate,
598 launchTargetKey,
599 ]);
600
601 useEffect(() => {
602 if (!shouldRedirectToRunningTerminal || !selectedThread || !runningSession) {
603 return;
604 }
605 navigation.dispatch(
606 StackActions.replace("ThreadTerminal", {
607 environmentId: String(selectedThread.environmentId),
608 threadId: String(selectedThread.id),
609 terminalId: runningSession.target.terminalId,
610 }),
611 );
612 }, [navigation, runningSession, selectedThread, shouldRedirectToRunningTerminal]);
613
614 useEffect(() => {
615 const initialInput = pendingLaunch?.initialInput;
616 if (
617 !initialInput ||
618 !selectedThread ||
619 terminal.version === 0 ||
620 sentInitialInputKeyRef.current === launchTargetKey
621 ) {
622 return;
623 }
624 sentInitialInputKeyRef.current = launchTargetKey;
625 void writeTerminal({
626 environmentId: selectedThread.environmentId,
627 input: {
628 threadId: selectedThread.id,
629 terminalId,
630 data: initialInput,
631 },
632 });
633 }, [
634 launchTargetKey,
635 pendingLaunch?.initialInput,
636 selectedThread,
637 terminal.version,
638 terminalId,
639 writeTerminal,
640 ]);
641
642 useEffect(() => {
643 firstNonEmptyBufferLoggedRef.current = false;
644 sentInitialInputKeyRef.current = null;
645 }, [terminalKey]);
646
647 const clearBufferReplayTimer = useCallback(() => {
648 if (bufferReplayTimerRef.current !== null) {
649 clearTimeout(bufferReplayTimerRef.current);
650 bufferReplayTimerRef.current = null;
651 }
652 }, []);
653
654 const scheduleBufferReplayReady = useCallback(() => {
655 clearBufferReplayTimer();
656 const replayKey = bufferReplayKey;
657 terminalDebugLog("replay:schedule-ready", {
658 replayKey,
659 delayMs: TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS,
660 });
661 bufferReplayTimerRef.current = setTimeout(() => {
662 bufferReplayTimerRef.current = null;
663 setReadyBufferReplayKey(replayKey);
664 terminalDebugLog("replay:ready", { replayKey });
665 }, TERMINAL_BUFFER_REPLAY_STABILITY_DELAY_MS);
666 }, [bufferReplayKey, clearBufferReplayTimer]);
667
668 useEffect(() => {
669 if (lastBufferReplayKeyRef.current === bufferReplayKey) {
670 return;
671 }
672
673 lastBufferReplayKeyRef.current = bufferReplayKey;
674 clearBufferReplayTimer();
675 setReadyBufferReplayKey(null);
676 }, [bufferReplayKey, clearBufferReplayTimer]);
677
678 useEffect(() => clearBufferReplayTimer, [clearBufferReplayTimer]);
679
680 useEffect(() => {
681 if (!routeEnvironmentId || !routeThreadId) {
682 setLastGridSize({
683 cols: DEFAULT_TERMINAL_COLS,
684 rows: DEFAULT_TERMINAL_ROWS,
685 });
686 return;
687 }
688
689 setLastGridSize(
690 getCachedTerminalGridSize({
691 environmentId: routeEnvironmentId,
692 threadId: routeThreadId,
693 terminalId,
694 }) ?? {
695 cols: DEFAULT_TERMINAL_COLS,
696 rows: DEFAULT_TERMINAL_ROWS,
697 },
698 );
699 setHasMeasuredSurface(true);
700 }, [routeEnvironmentId, routeThreadId, terminalId]);
701
702 /** Resolves true once the pty accepted the write, false if it was skipped or rejected. */
703 const writeInput = useCallback(
704 async (data: string): Promise<boolean> => {
705 if (!selectedThread || !isRunning) {
706 return false;
707 }
708
709 const result = await writeTerminal({
710 environmentId: selectedThread.environmentId,
711 input: {
712 threadId: selectedThread.id,
713 terminalId,
714 data,
715 },
716 });
717 return result._tag === "Success";
718 },
719 [isRunning, selectedThread, terminalId, writeTerminal],
720 );
721
722 const pasteSessionRef = useRef<ReturnType<typeof createTerminalPasteSession> | null>(null);
723 if (pasteSessionRef.current === null) {
724 pasteSessionRef.current = createTerminalPasteSession();
725 }
726 const pasteSession = pasteSessionRef.current;
727
728 // Drop delayed clipboard reads whenever the route or attached pty changes.
729 useEffect(() => {
730 pasteSession.reset(isRunning);
731 return () => {
732 pasteSession.reset(false);
733 };
734 }, [isRunning, pasteSession, terminal.lifecycleVersion, terminalKey]);
735
736 const pasteFromClipboard = useCallback(async () => {
737 await pasteSession.paste({
738 readText: Clipboard.getStringAsync,
739 write: writeInput,
740 onReadError: (cause) => {
741 console.error(new TerminalClipboardReadError({ terminalId, cause }));
742 },
743 });
744 }, [pasteSession, terminalId, writeInput]);
745
746 /** Sends a key through the armed toolbar modifier, if any, and disarms it. */
747 const writeModifiedInput = useCallback(
748 (data: string) => {
749 if (pendingModifier === null) {
750 void writeInput(data);
751 return;
752 }
753
754 setPendingModifierState({ terminalId, value: null });
755 const resolved = resolveModifiedTerminalInput({
756 data,
757 modifier: pendingModifier,
758 hostPlatform,
759 });
760 if (resolved.kind === "paste") {
761 void pasteFromClipboard();
762 return;
763 }
764 void writeInput(resolved.data);
765 },
766 [hostPlatform, pasteFromClipboard, pendingModifier, terminalId, writeInput],
767 );
768
769 const handleInput = useCallback(
770 (data: string) => {
771 if (data.length === 0) {
772 return;
773 }
774
775 writeModifiedInput(data);
776 },
777 [writeModifiedInput],
778 );
779
780 const handleResize = useCallback(
781 (size: { readonly cols: number; readonly rows: number }) => {
782 terminalDebugLog("native:onResize", {
783 cols: size.cols,
784 rows: size.rows,
785 terminalKey,
786 });
787 setHasMeasuredSurface(true);
788 if (readyBufferReplayKey !== bufferReplayKey) {
789 scheduleBufferReplayReady();
790 }
791 if (routeEnvironmentId && routeThreadId) {
792 cacheTerminalGridSize(
793 {
794 environmentId: routeEnvironmentId,
795 threadId: routeThreadId,
796 terminalId,
797 },
798 size,
799 );
800 }
801 if (size.cols === lastGridSize.cols && size.rows === lastGridSize.rows) {
802 return;
803 }
804
805 setLastGridSize(size);
806 if (!selectedThread || !isRunning) {
807 return;
808 }
809
810 void resizeTerminal({
811 environmentId: selectedThread.environmentId,
812 input: {
813 threadId: selectedThread.id,
814 terminalId,
815 cols: size.cols,
816 rows: size.rows,
817 },
818 });
819 },
820 [
821 isRunning,
822 lastGridSize.cols,
823 lastGridSize.rows,
824 bufferReplayKey,
825 readyBufferReplayKey,
826 routeEnvironmentId,
827 routeThreadId,
828 resizeTerminal,
829 scheduleBufferReplayReady,
830 selectedThread,
831 terminalId,
832 terminalKey,
833 ],
834 );
835
836 const handleSelectTerminal = useCallback(
837 (nextTerminalId: string) => {
838 if (!selectedThread || nextTerminalId === terminalId) {
839 return;
840 }
841
842 navigation.dispatch(
843 StackActions.replace("ThreadTerminal", {
844 environmentId: String(selectedThread.environmentId),
845 threadId: String(selectedThread.id),
846 terminalId: nextTerminalId,
847 }),
848 );
849 },
850 [navigation, selectedThread, terminalId],
851 );
852
853 const navigateAwayAfterExit = useCallback(() => {
854 // With other shells still live, fall through to the previous one instead
855 // of dropping the user back on the thread.
856 const fallbackTerminalId = previousLiveTerminalId({
857 sessions: terminalMenuSessions,
858 exitedTerminalId: terminalId,
859 });
860 if (fallbackTerminalId !== null && selectedThread) {
861 navigation.dispatch(
862 StackActions.replace("ThreadTerminal", {
863 environmentId: String(selectedThread.environmentId),
864 threadId: String(selectedThread.id),
865 terminalId: fallbackTerminalId,
866 }),
867 );
868 return;
869 }
870 if (navigation.canGoBack()) {
871 navigation.goBack();
872 return;
873 }
874 // Deep-linked/root mounts have nothing to pop; land on the thread
875 // instead of stranding the user on a dead terminal.
876 if (selectedThread) {
877 navigation.dispatch(
878 StackActions.replace("Thread", {
879 environmentId: String(selectedThread.environmentId),
880 threadId: String(selectedThread.id),
881 }),
882 );
883 }
884 }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
885
886 useEffect(() => {
887 // Detached (hidden surface or environment drop): forget the running
888 // marker so a reattach takes the stale-reopen path instead of misreading
889 // the dead snapshot as an exit observed on this screen. A pending exit
890 // navigation stays armed — it only clears once the session runs again —
891 // so refocusing a dead screen still leaves it.
892 if (terminalAttachInput === null) {
893 runningTerminalKeyRef.current = null;
894 return;
895 }
896 if (isRunning) {
897 runningTerminalKeyRef.current = terminalKey;
898 // The session came back (e.g. respawned elsewhere) before the user
899 // returned; a stale pending exit must not eject a live terminal.
900 pendingExitNavigationRef.current = null;
901 return;
902 }
903 // The web drawer treats both exited and closed as session end.
904 const sessionEnded = terminal.status === "exited" || terminal.status === "closed";
905 if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) {
906 return;
907 }
908 runningTerminalKeyRef.current = null;
909 // Mark this key handled so the stale-attach effect doesn't respawn the
910 // session the user just ended.
911 reopenedStaleTerminalKeyRef.current = terminalKey;
912 if (selectedThread) {
913 void closeTerminal({
914 environmentId: selectedThread.environmentId,
915 input: {
916 threadId: selectedThread.id,
917 terminalId,
918 },
919 });
920 }
921 if (navigation.isFocused()) {
922 navigateAwayAfterExit();
923 return;
924 }
925 // An unfocused screen can't navigate; leave when the user returns so
926 // they never land on the dead session.
927 pendingExitNavigationRef.current = terminalKey;
928 }, [
929 closeTerminal,
930 isRunning,
931 navigateAwayAfterExit,
932 navigation,
933 selectedThread,
934 terminal.status,
935 terminalAttachInput,
936 terminalId,
937 terminalKey,
938 ]);
939
940 useEffect(
941 () =>
942 navigation.addListener("focus", () => {
943 if (pendingExitNavigationRef.current !== terminalKey) {
944 return;
945 }
946 pendingExitNavigationRef.current = null;
947 navigateAwayAfterExit();
948 }),
949 [navigateAwayAfterExit, navigation, terminalKey],
950 );
951
952 const handleOpenNewTerminal = useCallback(() => {
953 if (!selectedThread) {
954 return;
955 }
956
957 navigation.dispatch(
958 StackActions.replace("ThreadTerminal", {
959 environmentId: String(selectedThread.environmentId),
960 threadId: String(selectedThread.id),
961 terminalId: nextOpenTerminalId({
962 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
963 activeRouteTerminalId: terminalId,
964 }),
965 }),
966 );
967 }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
968
969 const handleDecreaseFontSize = useCallback(() => {
970 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
971 }, [fontSize, setTerminalFontSize]);
972
973 const handleIncreaseFontSize = useCallback(() => {
974 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
975 }, [fontSize, setTerminalFontSize]);
976
977 // Android mirror of the iOS NativeHeaderToolbar terminal menu below: text
978 // size, session switching, and "Open new terminal", rendered through the
979 // token-styled anchored menu (the native header items are iOS-only).
980 const androidTerminalMenuActions = useMemo<MenuAction[]>(
981 () => [
982 {
983 id: "text-size",
984 title: "Text size",
985 subactions: [
986 {
987 id: "font-decrease",
988 title: `A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
989 attributes: fontSize <= MIN_TERMINAL_FONT_SIZE ? { disabled: true } : undefined,
990 },
991 {
992 id: "font-increase",
993 title: `A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
994 attributes: fontSize >= MAX_TERMINAL_FONT_SIZE ? { disabled: true } : undefined,
995 },
996 ],
997 },
998 ...terminalMenuSessions.map((session): MenuAction => ({
999 id: `terminal-session:${session.terminalId}`,
1000 title: session.displayLabel,
1001 subtitle: [getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
1002 .filter(Boolean)
1003 .join(" · "),
1004 state: session.terminalId === terminalId ? ("on" as const) : undefined,
1005 })),
1006 {
1007 id: "terminal-new",
1008 title: "Open new terminal",
1009 image: "plus",
1010 subtitle: `Start another shell in ${basename(selectedThreadProject?.workspaceRoot ?? null) ?? "this workspace"}`,
1011 },
1012 ],
1013 [fontSize, selectedThreadProject?.workspaceRoot, terminalId, terminalMenuSessions],
1014 );
1015
1016 const handleAndroidTerminalMenuAction = useCallback(
1017 (event: { nativeEvent: { event: string } }) => {
1018 const id = event.nativeEvent.event;
1019 if (id === "font-decrease") {
1020 handleDecreaseFontSize();
1021 return;
1022 }
1023 if (id === "font-increase") {
1024 handleIncreaseFontSize();
1025 return;
1026 }
1027 if (id === "terminal-new") {
1028 handleOpenNewTerminal();
1029 return;
1030 }
1031 if (id.startsWith("terminal-session:")) {
1032 handleSelectTerminal(id.slice("terminal-session:".length));
1033 }
1034 },
1035 [handleDecreaseFontSize, handleIncreaseFontSize, handleOpenNewTerminal, handleSelectTerminal],
1036 );
1037
1038 const handleClearTerminal = useCallback(() => {
1039 if (!selectedThread) {
1040 return;
1041 }
1042
1043 setPendingModifierState({ terminalId, value: null });
1044 void clearTerminal({
1045 environmentId: selectedThread.environmentId,
1046 input: {
1047 threadId: selectedThread.id,
1048 terminalId,
1049 },
1050 });
1051 }, [clearTerminal, selectedThread, terminalId]);
1052
1053 const handleToolbarActionPress = useCallback(
1054 (action: TerminalToolbarAction) => {
1055 if (action.kind === "modifier") {
1056 setPendingModifierState((current) => ({
1057 terminalId,
1058 value:
1059 (current.terminalId === terminalId ? current.value : null) === action.modifier
1060 ? null
1061 : action.modifier,
1062 }));
1063 return;
1064 }
1065
1066 if (action.kind === "clear") {
1067 handleClearTerminal();
1068 return;
1069 }
1070
1071 if (action.kind === "paste") {
1072 setPendingModifierState({ terminalId, value: null });
1073 void pasteFromClipboard();
1074 return;
1075 }
1076
1077 writeModifiedInput(action.data);
1078 },
1079 [handleClearTerminal, pasteFromClipboard, terminalId, writeModifiedInput],
1080 );
1081
1082 const handleDismissKeyboard = useCallback(() => {
1083 setIsAccessoryDismissed(true);
1084 void KeyboardController.dismiss();
1085 }, []);
1086
1087 const handleShowKeyboard = useCallback(() => {
1088 setKeyboardFocusRequest((current) => current + 1);
1089 }, []);
1090 const handleRetryEnvironment = useCallback(() => {
1091 if (routeEnvironmentId !== null) {
1092 void retryEnvironment(routeEnvironmentId);
1093 }
1094 }, [retryEnvironment, routeEnvironmentId]);
1095
1096 if (!selectedThread) {
1097 if (workspaceState.isLoadingConnections) {
1098 return <LoadingScreen message="Opening terminal…" />;
1099 }
1100
1101 return (
1102 <View className="flex-1 bg-screen">
1103 <EmptyState
1104 title="Thread unavailable"
1105 detail="This terminal route needs an active thread and workspace."
1106 />
1107 </View>
1108 );
1109 }
1110
1111 if (!selectedThreadProject?.workspaceRoot) {
1112 return (
1113 <View className="flex-1 bg-screen">
1114 <EmptyState
1115 title="Terminal unavailable"
1116 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
1117 />
1118 </View>
1119 );
1120 }
1121
1122 if (!environment.isReady && environment.presentation === null) {
1123 return <LoadingScreen message="Opening terminal…" />;
1124 }
1125
1126 return (
1127 <>
1128 <NativeStackScreenOptions
1129 options={{
1130 // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS — the pty
1131 // scrolls internally, nothing for glass to sample). Default title/subtitle
1132 // styling, like every other page.
1133 // Android draws its own in-flow header (AndroidScreenHeader below);
1134 // the native stack header stays iOS-only.
1135 headerShown: Platform.OS !== "android",
1136 title: "Terminal",
1137 unstable_headerSubtitle:
1138 usesNativeHeaderGlass && headerSubtitle.length > 0 ? headerSubtitle : undefined,
1139 }}
1140 />
1141
1142 {Platform.OS === "android" ? (
1143 <AndroidScreenHeader
1144 title="Terminal"
1145 subtitle={headerSubtitle}
1146 onBack={navigation.canGoBack() ? () => navigation.goBack() : undefined}
1147 trailing={
1148 <>
1149 {layout.usesSplitView ? (
1150 <AndroidHeaderIconButton
1151 accessibilityLabel={
1152 panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"
1153 }
1154 icon={
1155 panes.primarySidebarVisible
1156 ? "arrow.up.left.and.arrow.down.right"
1157 : "sidebar.left"
1158 }
1159 onPress={togglePrimarySidebar}
1160 />
1161 ) : null}
1162 {isEnvironmentReady ? (
1163 <ControlPillMenu
1164 actions={androidTerminalMenuActions}
1165 isAnchoredToRight
1166 title={getTerminalStatusLabel({
1167 status: terminal.status,
1168 hasRunningSubprocess: terminal.hasRunningSubprocess,
1169 })}
1170 onPressAction={handleAndroidTerminalMenuAction}
1171 >
1172 <AndroidHeaderIconButton accessibilityLabel="Terminal options" icon="terminal" />
1173 </ControlPillMenu>
1174 ) : null}
1175 </>
1176 }
1177 />
1178 ) : null}
1179
1180 {layout.usesSplitView ? (
1181 <NativeHeaderToolbar placement="left">
1182 <NativeHeaderToolbar.Button
1183 accessibilityLabel={panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"}
1184 icon={
1185 panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
1186 }
1187 onPress={togglePrimarySidebar}
1188 separateBackground
1189 />
1190 </NativeHeaderToolbar>
1191 ) : null}
1192
1193 {isEnvironmentReady ? (
1194 <NativeHeaderToolbar placement="right">
1195 <NativeHeaderToolbar.Menu icon="terminal" title="Terminal options" separateBackground>
1196 <NativeHeaderToolbar.Label>
1197 {getTerminalStatusLabel({
1198 status: terminal.status,
1199 hasRunningSubprocess: terminal.hasRunningSubprocess,
1200 })}
1201 </NativeHeaderToolbar.Label>
1202 <NativeHeaderToolbar.Menu icon="textformat.size" inline title="Text size">
1203 <NativeHeaderToolbar.Label>Text size</NativeHeaderToolbar.Label>
1204 <NativeHeaderToolbar.MenuAction
1205 disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
1206 discoverabilityLabel="Decrease terminal text size"
1207 onPress={handleDecreaseFontSize}
1208 >
1209 <NativeHeaderToolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
1210 </NativeHeaderToolbar.MenuAction>
1211 <NativeHeaderToolbar.MenuAction
1212 disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
1213 discoverabilityLabel="Increase terminal text size"
1214 onPress={handleIncreaseFontSize}
1215 >
1216 <NativeHeaderToolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
1217 </NativeHeaderToolbar.MenuAction>
1218 </NativeHeaderToolbar.Menu>
1219 {terminalMenuSessions.map((session) => (
1220 <NativeHeaderToolbar.MenuAction
1221 key={session.terminalId}
1222 icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
1223 onPress={() => handleSelectTerminal(session.terminalId)}
1224 subtitle={[
1225 getTerminalStatusLabel({ status: session.status }),
1226 basename(session.cwd),
1227 ]
1228 .filter(Boolean)
1229 .join(" · ")}
1230 >
1231 <NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
1232 </NativeHeaderToolbar.MenuAction>
1233 ))}
1234 <NativeHeaderToolbar.MenuAction
1235 icon="plus"
1236 onPress={handleOpenNewTerminal}
1237 subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
1238 >
1239 <NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
1240 </NativeHeaderToolbar.MenuAction>
1241 </NativeHeaderToolbar.Menu>
1242 </NativeHeaderToolbar>
1243 ) : null}
1244
1245 <View className="flex-1" style={{ backgroundColor: terminalTheme.background }}>
1246 {!isEnvironmentReady ? (
1247 <EnvironmentConnectionNotice
1248 environmentLabel={
1249 environment.presentation?.entry.target.label ??
1250 selectedEnvironmentConnection?.environmentLabel ??
1251 "Environment"
1252 }
1253 connection={
1254 environment.presentation?.connection ?? {
1255 phase: "available",
1256 error: null,
1257 traceId: null,
1258 }
1259 }
1260 resourceName="terminal"
1261 onRetry={handleRetryEnvironment}
1262 />
1263 ) : (
1264 <>
1265 <View className="flex-1" style={{ paddingBottom: terminalBottomInset }}>
1266 <TerminalSurface
1267 autoFocus={!SHOWCASE_ENABLED}
1268 buffer={terminalSurfaceBuffer}
1269 fontSize={fontSize}
1270 isRunning={isRunning}
1271 keyboardFocusRequest={keyboardFocusRequest}
1272 onInput={handleInput}
1273 onResize={handleResize}
1274 style={{ flex: 1 }}
1275 terminalKey={terminalKey}
1276 theme={terminalTheme}
1277 />
1278 </View>
1279
1280 {isAccessoryVisible ? (
1281 <KeyboardStickyView
1282 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1283 offset={{ closed: 0, opened: 0 }}
1284 >
1285 <View
1286 className="border-t"
1287 style={{
1288 backgroundColor: terminalTheme.background,
1289 borderTopColor: terminalTheme.border,
1290 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1291 }}
1292 >
1293 <ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
1294 <ComposerToolbarScroller
1295 contentPaddingRight={2}
1296 fadeOpaque={terminalTheme.background}
1297 fadeTransparent={`${terminalTheme.background}00`}
1298 >
1299 {terminalToolbarActions.map((action) => {
1300 const active =
1301 action.kind === "modifier" && pendingModifier === action.modifier;
1302
1303 return (
1304 <ComposerToolbarButton
1305 key={action.key}
1306 active={active}
1307 label={action.label}
1308 maxWidth={120}
1309 minWidth={action.label.length > 1 ? 56 : 44}
1310 onPress={() => handleToolbarActionPress(action)}
1311 showChevron={false}
1312 textTransform={
1313 action.kind === "modifier" || action.kind === "clear"
1314 ? "uppercase"
1315 : "none"
1316 }
1317 />
1318 );
1319 })}
1320 </ComposerToolbarScroller>
1321 <ComposerToolbarButton
1322 accessibilityLabel="Dismiss keyboard"
1323 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1324 onPress={handleDismissKeyboard}
1325 showChevron={false}
1326 />
1327 </ComposerToolbarRow>
1328 </View>
1329 </KeyboardStickyView>
1330 ) : !keyboardState.isVisible ? (
1331 <Pressable
1332 accessibilityLabel="Show keyboard"
1333 accessibilityRole="button"
1334 onPress={handleShowKeyboard}
1335 style={({ pressed }) => ({
1336 bottom: 16,
1337 borderRadius: 28,
1338 opacity: pressed ? 0.72 : 1,
1339 position: "absolute",
1340 right: 16,
1341 })}
1342 >
1343 <GlassSurface
1344 chrome="none"
1345 glassEffectStyle="regular"
1346 tintColor="transparent"
1347 style={{
1348 alignItems: "center",
1349 borderRadius: 24,
1350 height: 48,
1351 justifyContent: "center",
1352 width: 48,
1353 }}
1354 pointerEvents="none"
1355 >
1356 <SymbolView
1357 name={{ ios: "keyboard", android: "keyboard" }}
1358 size={20}
1359 tintColor={terminalTheme.foreground}
1360 type="monochrome"
1361 />
1362 </GlassSurface>
1363 </Pressable>
1364 ) : null}
1365 </>
1366 )}
1367 </View>
1368 </>
1369 );
1370}