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

ThreadTerminalRouteScreen.tsx

1,388 lines47.4 KB

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