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

ThreadTerminalRouteScreen.tsx

1,405 lines47.8 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 { useSelectedThreadDetail } 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 = useSelectedThreadDetail();
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: selectedThreadDetail?.worktreePath ?? null,
285 });
286 }, [
287 activeKnownSession?.state.summary,
288 pendingLaunch,
289 selectedThread,
290 selectedThreadDetail?.worktreePath,
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 handleCloseTerminal = useCallback(() => {
854 if (navigation.canGoBack()) {
855 navigation.goBack();
856 return;
857 }
858 navigation.dispatch(
859 StackActions.replace("Thread", {
860 environmentId: params.environmentId,
861 threadId: params.threadId,
862 }),
863 );
864 }, [navigation, params.environmentId, params.threadId]);
865​
866 const navigateAwayAfterExit = useCallback(() => {
867 // With other shells still live, fall through to the previous one instead
868 // of dropping the user back on the thread.
869 const fallbackTerminalId = previousLiveTerminalId({
870 sessions: terminalMenuSessions,
871 exitedTerminalId: terminalId,
872 });
873 if (fallbackTerminalId !== null && selectedThread) {
874 navigation.dispatch(
875 StackActions.replace("ThreadTerminal", {
876 environmentId: String(selectedThread.environmentId),
877 threadId: String(selectedThread.id),
878 terminalId: fallbackTerminalId,
879 }),
880 );
881 return;
882 }
883 if (navigation.canGoBack()) {
884 navigation.goBack();
885 return;
886 }
887 // Deep-linked/root mounts have nothing to pop; land on the thread
888 // instead of stranding the user on a dead terminal.
889 if (selectedThread) {
890 navigation.dispatch(
891 StackActions.replace("Thread", {
892 environmentId: String(selectedThread.environmentId),
893 threadId: String(selectedThread.id),
894 }),
895 );
896 }
897 }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
898​
899 useEffect(() => {
900 // Detached (hidden surface or environment drop): forget the running
901 // marker so a reattach takes the stale-reopen path instead of misreading
902 // the dead snapshot as an exit observed on this screen. A pending exit
903 // navigation stays armed — it only clears once the session runs again —
904 // so refocusing a dead screen still leaves it.
905 if (terminalAttachInput === null) {
906 runningTerminalKeyRef.current = null;
907 return;
908 }
909 if (isRunning) {
910 runningTerminalKeyRef.current = terminalKey;
911 // The session came back (e.g. respawned elsewhere) before the user
912 // returned; a stale pending exit must not eject a live terminal.
913 pendingExitNavigationRef.current = null;
914 return;
915 }
916 // The web drawer treats both exited and closed as session end.
917 const sessionEnded = terminal.status === "exited" || terminal.status === "closed";
918 if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) {
919 return;
920 }
921 runningTerminalKeyRef.current = null;
922 // Mark this key handled so the stale-attach effect doesn't respawn the
923 // session the user just ended.
924 reopenedStaleTerminalKeyRef.current = terminalKey;
925 if (selectedThread) {
926 void closeTerminal({
927 environmentId: selectedThread.environmentId,
928 input: {
929 threadId: selectedThread.id,
930 terminalId,
931 },
932 });
933 }
934 if (navigation.isFocused()) {
935 navigateAwayAfterExit();
936 return;
937 }
938 // An unfocused screen can't navigate; leave when the user returns so
939 // they never land on the dead session.
940 pendingExitNavigationRef.current = terminalKey;
941 }, [
942 closeTerminal,
943 isRunning,
944 navigateAwayAfterExit,
945 navigation,
946 selectedThread,
947 terminal.status,
948 terminalAttachInput,
949 terminalId,
950 terminalKey,
951 ]);
952​
953 useEffect(
954 () =>
955 navigation.addListener("focus", () => {
956 if (pendingExitNavigationRef.current !== terminalKey) {
957 return;
958 }
959 pendingExitNavigationRef.current = null;
960 navigateAwayAfterExit();
961 }),
962 [navigateAwayAfterExit, navigation, terminalKey],
963 );
964​
965 const handleOpenNewTerminal = useCallback(() => {
966 if (!selectedThread) {
967 return;
968 }
969​
970 navigation.dispatch(
971 StackActions.replace("ThreadTerminal", {
972 environmentId: String(selectedThread.environmentId),
973 threadId: String(selectedThread.id),
974 terminalId: nextOpenTerminalId({
975 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
976 activeRouteTerminalId: terminalId,
977 }),
978 }),
979 );
980 }, [navigation, selectedThread, terminalId, terminalMenuSessions]);
981​
982 const handleDecreaseFontSize = useCallback(() => {
983 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
984 }, [fontSize, setTerminalFontSize]);
985​
986 const handleIncreaseFontSize = useCallback(() => {
987 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
988 }, [fontSize, setTerminalFontSize]);
989​
990 // Android mirror of the iOS NativeHeaderToolbar terminal menu below: text
991 // size, session switching, and "Open new terminal", rendered through the
992 // token-styled anchored menu (the native header items are iOS-only).
993 const androidTerminalMenuActions = useMemo<MenuAction[]>(
994 () => [
995 {
996 id: "text-size",
997 title: "Text size",
998 subactions: [
999 {
1000 id: "font-decrease",
1001 title: `A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
1002 attributes: fontSize <= MIN_TERMINAL_FONT_SIZE ? { disabled: true } : undefined,
1003 },
1005 id: "font-increase",
1006 title: `A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
1007 attributes: fontSize >= MAX_TERMINAL_FONT_SIZE ? { disabled: true } : undefined,
1008 },
1009 ],
1010 },
1011 ...terminalMenuSessions.map((session): MenuAction => ({
1012 id: `terminal-session:${session.terminalId}`,
1013 title: session.displayLabel,
1014 subtitle: [getTerminalStatusLabel({ status: session.status }), basename(session.cwd)]
1015 .filter(Boolean)
1016 .join(" · "),
1017 state: session.terminalId === terminalId ? ("on" as const) : undefined,
1018 })),
1020 id: "terminal-new",
1021 title: "Open new terminal",
1022 image: "plus",
1023 subtitle: `Start another shell in ${basename(selectedThreadProject?.workspaceRoot ?? null) ?? "this workspace"}`,
1024 },
1025 ],
1026 [fontSize, selectedThreadProject?.workspaceRoot, terminalId, terminalMenuSessions],
1027 );
1028​
1029 const handleAndroidTerminalMenuAction = useCallback(
1030 (event: { nativeEvent: { event: string } }) => {
1031 const id = event.nativeEvent.event;
1032 if (id === "font-decrease") {
1033 handleDecreaseFontSize();
1034 return;
1036 if (id === "font-increase") {
1037 handleIncreaseFontSize();
1038 return;
1040 if (id === "terminal-new") {
1041 handleOpenNewTerminal();
1042 return;
1044 if (id.startsWith("terminal-session:")) {
1045 handleSelectTerminal(id.slice("terminal-session:".length));
1047 },
1048 [handleDecreaseFontSize, handleIncreaseFontSize, handleOpenNewTerminal, handleSelectTerminal],
1049 );
1050​
1051 const handleClearTerminal = useCallback(() => {
1052 if (!selectedThread) {
1053 return;
1055​
1056 setPendingModifierState({ terminalId, value: null });
1057 void clearTerminal({
1058 environmentId: selectedThread.environmentId,
1059 input: {
1060 threadId: selectedThread.id,
1061 terminalId,
1062 },
1063 });
1064 }, [clearTerminal, selectedThread, terminalId]);
1065​
1066 const handleToolbarActionPress = useCallback(
1067 (action: TerminalToolbarAction) => {
1068 if (action.kind === "modifier") {
1069 setPendingModifierState((current) => ({
1070 terminalId,
1071 value:
1072 (current.terminalId === terminalId ? current.value : null) === action.modifier
1073 ? null
1074 : action.modifier,
1075 }));
1076 return;
1078​
1079 if (action.kind === "clear") {
1080 handleClearTerminal();
1081 return;
1083​
1084 if (action.kind === "paste") {
1085 setPendingModifierState({ terminalId, value: null });
1086 void pasteFromClipboard();
1087 return;
1089​
1090 writeModifiedInput(action.data);
1091 },
1092 [handleClearTerminal, pasteFromClipboard, terminalId, writeModifiedInput],
1093 );
1094​
1095 const handleDismissKeyboard = useCallback(() => {
1096 setIsAccessoryDismissed(true);
1097 void KeyboardController.dismiss();
1098 }, []);
1099​
1100 const handleShowKeyboard = useCallback(() => {
1101 setKeyboardFocusRequest((current) => current + 1);
1102 }, []);
1103 const handleRetryEnvironment = useCallback(() => {
1104 if (routeEnvironmentId !== null) {
1105 void retryEnvironment(routeEnvironmentId);
1107 }, [retryEnvironment, routeEnvironmentId]);
1108​
1109 if (!selectedThread) {
1110 if (workspaceState.isLoadingConnections) {
1111 return <LoadingScreen message="Opening terminal…" />;
1113​
1114 return (
1115 <View className="flex-1 bg-screen">
1116 <EmptyState
1117 title="Thread unavailable"
1118 detail="This terminal route needs an active thread and workspace."
1119 />
1120 </View>
1121 );
1123​
1124 if (!selectedThreadProject?.workspaceRoot) {
1125 return (
1126 <View className="flex-1 bg-screen">
1127 <EmptyState
1128 title="Terminal unavailable"
1129 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
1130 />
1131 </View>
1132 );
1134​
1135 if (!environment.isReady && environment.presentation === null) {
1136 return <LoadingScreen message="Opening terminal…" />;
1138​
1139 return (
1140 <>
1141 <NativeStackScreenOptions
1142 options={{
1143 // Static header config lives in Stack.tsx (SOLID_HEADER_OPTIONS — the pty
1144 // scrolls internally, nothing for glass to sample). Default title/subtitle
1145 // styling, like every other page.
1146 // Android draws its own in-flow header (AndroidScreenHeader below);
1147 // the native stack header stays iOS-only.
1148 headerShown: Platform.OS !== "android",
1149 title: "Terminal",
1150 unstable_headerSubtitle:
1151 usesNativeHeaderGlass && headerSubtitle.length > 0 ? headerSubtitle : undefined,
1152 }}
1153 />
1154​
1155 {Platform.OS === "android" ? (
1156 <AndroidScreenHeader
1157 title="Terminal"
1158 subtitle={headerSubtitle}
1159 onBack={handleCloseTerminal}
1160 trailing={
1161 <>
1162 {layout.usesSplitView ? (
1163 <AndroidHeaderIconButton
1164 accessibilityLabel={
1165 panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"
1167 icon={
1168 panes.primarySidebarVisible
1169 ? "arrow.up.left.and.arrow.down.right"
1170 : "sidebar.left"
1172 onPress={togglePrimarySidebar}
1173 />
1174 ) : null}
1175 {isEnvironmentReady ? (
1176 <ControlPillMenu
1177 actions={androidTerminalMenuActions}
1178 isAnchoredToRight
1179 title={getTerminalStatusLabel({
1180 status: terminal.status,
1181 hasRunningSubprocess: terminal.hasRunningSubprocess,
1182 })}
1183 onPressAction={handleAndroidTerminalMenuAction}
1185 <AndroidHeaderIconButton accessibilityLabel="Terminal options" icon="terminal" />
1186 </ControlPillMenu>
1187 ) : null}
1188 </>
1190 />
1191 ) : null}
1192​
1193 {layout.usesSplitView ? (
1194 <NativeHeaderToolbar placement="left">
1195 <NativeHeaderToolbar.Button
1196 accessibilityLabel="Close terminal"
1197 icon="xmark"
1198 onPress={handleCloseTerminal}
1199 separateBackground
1200 />
1201 <NativeHeaderToolbar.Button
1202 accessibilityLabel={panes.primarySidebarVisible ? "Maximize terminal" : "Show threads"}
1203 icon={
1204 panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
1206 onPress={togglePrimarySidebar}
1207 separateBackground
1208 />
1209 </NativeHeaderToolbar>
1210 ) : null}
1211​
1212 {isEnvironmentReady ? (
1213 <NativeHeaderToolbar placement="right">
1214 <NativeHeaderToolbar.Menu icon="terminal" title="Terminal options" separateBackground>
1215 <NativeHeaderToolbar.Label>
1216 {getTerminalStatusLabel({
1217 status: terminal.status,
1218 hasRunningSubprocess: terminal.hasRunningSubprocess,
1219 })}
1220 </NativeHeaderToolbar.Label>
1221 <NativeHeaderToolbar.Menu icon="textformat.size" inline title="Text size">
1222 <NativeHeaderToolbar.Label>Text size</NativeHeaderToolbar.Label>
1223 <NativeHeaderToolbar.MenuAction
1224 disabled={fontSize <= MIN_TERMINAL_FONT_SIZE}
1225 discoverabilityLabel="Decrease terminal text size"
1226 onPress={handleDecreaseFontSize}
1228 <NativeHeaderToolbar.Label>{`A- ${Math.max(MIN_TERMINAL_FONT_SIZE, fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
1229 </NativeHeaderToolbar.MenuAction>
1230 <NativeHeaderToolbar.MenuAction
1231 disabled={fontSize >= MAX_TERMINAL_FONT_SIZE}
1232 discoverabilityLabel="Increase terminal text size"
1233 onPress={handleIncreaseFontSize}
1235 <NativeHeaderToolbar.Label>{`A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`}</NativeHeaderToolbar.Label>
1236 </NativeHeaderToolbar.MenuAction>
1237 </NativeHeaderToolbar.Menu>
1238 {terminalMenuSessions.map((session) => (
1239 <NativeHeaderToolbar.MenuAction
1240 key={session.terminalId}
1241 icon={session.terminalId === terminalId ? "checkmark" : "terminal"}
1242 onPress={() => handleSelectTerminal(session.terminalId)}
1243 subtitle={[
1244 getTerminalStatusLabel({ status: session.status }),
1245 basename(session.cwd),
1247 .filter(Boolean)
1248 .join(" · ")}
1250 <NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
1251 </NativeHeaderToolbar.MenuAction>
1252 ))}
1253 <NativeHeaderToolbar.MenuAction
1254 icon="plus"
1255 onPress={handleOpenNewTerminal}
1256 subtitle={`Start another shell in ${basename(selectedThreadProject.workspaceRoot) ?? "this workspace"}`}
1258 <NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
1259 </NativeHeaderToolbar.MenuAction>
1260 </NativeHeaderToolbar.Menu>
1261 </NativeHeaderToolbar>
1262 ) : null}
1263​
1264 <View className="flex-1" style={{ backgroundColor: terminalTheme.background }}>
1265 {!isEnvironmentReady ? (
1266 <EnvironmentConnectionNotice
1267 environmentLabel={
1268 environment.presentation?.entry.target.label ??
1269 selectedEnvironmentConnection?.environmentLabel ??
1270 "Environment"
1272 connection={
1273 environment.presentation?.connection ?? {
1274 phase: "available",
1275 error: null,
1276 traceId: null,
1279 resourceName="terminal"
1280 onRetry={handleRetryEnvironment}
1281 />
1282 ) : (
1283 <>
1284 <BlurTargetView
1285 ref={terminalBlurTarget}
1286 style={{
1287 flex: 1,
1288 paddingBottom: terminalBottomInset,
1289 }}
1291 <View
1292 pointerEvents="none"
1293 style={{
1294 position: "absolute",
1295 inset: 0,
1296 backgroundColor: terminalTheme.background,
1297 }}
1298 />
1299 <TerminalSurface
1300 autoFocus={!SHOWCASE_ENABLED}
1301 buffer={terminalSurfaceBuffer}
1302 fontSize={fontSize}
1303 isRunning={isRunning}
1304 keyboardFocusRequest={keyboardFocusRequest}
1305 onInput={handleInput}
1306 onResize={handleResize}
1307 style={{ flex: 1 }}
1308 terminalKey={terminalKey}
1309 theme={terminalTheme}
1310 />
1311 </BlurTargetView>
1312​
1313 {isAccessoryVisible ? (
1314 <KeyboardStickyView
1315 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1316 offset={{ closed: 0, opened: 0 }}
1318 <View
1319 className="border-t"
1320 style={{
1321 backgroundColor: terminalTheme.background,
1322 borderTopColor: terminalTheme.border,
1323 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1324 }}
1326 <ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
1327 <ComposerToolbarScroller
1328 contentPaddingRight={2}
1329 fadeOpaque={terminalTheme.background}
1330 fadeTransparent={`${terminalTheme.background}00`}
1332 {terminalToolbarActions.map((action) => {
1333 const active =
1334 action.kind === "modifier" && pendingModifier === action.modifier;
1335​
1336 return (
1337 <ComposerToolbarButton
1338 key={action.key}
1339 active={active}
1340 label={action.label}
1341 maxWidth={120}
1342 minWidth={action.label.length > 1 ? 56 : 44}
1343 onPress={() => handleToolbarActionPress(action)}
1344 showChevron={false}
1345 textTransform={
1346 action.kind === "modifier" || action.kind === "clear"
1347 ? "uppercase"
1348 : "none"
1350 />
1351 );
1352 })}
1353 </ComposerToolbarScroller>
1354 <ComposerToolbarButton
1355 accessibilityLabel="Dismiss keyboard"
1356 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1357 onPress={handleDismissKeyboard}
1358 showChevron={false}
1359 />
1360 </ComposerToolbarRow>
1361 </View>
1362 </KeyboardStickyView>
1363 ) : !keyboardState.isVisible ? (
1364 <Pressable
1365 accessibilityLabel="Show keyboard"
1366 accessibilityRole="button"
1367 onPress={handleShowKeyboard}
1368 style={({ pressed }) => ({
1369 bottom: 16,
1370 borderRadius: 28,
1371 opacity: pressed ? 0.72 : 1,
1372 position: "absolute",
1373 right: 16,
1374 })}
1376 <GlassSurface
1377 chrome="none"
1378 blurTarget={terminalBlurTarget}
1379 fallbackColor={terminalTheme.background}
1380 glassEffectStyle="regular"
1381 tintColor="transparent"
1382 style={{
1383 alignItems: "center",
1384 borderRadius: 24,
1385 height: 48,
1386 justifyContent: "center",
1387 width: 48,
1388 }}
1389 pointerEvents="none"
1391 <SymbolView
1392 name={{ ios: "keyboard", android: "keyboard" }}
1393 size={20}
1394 tintColor={terminalTheme.foreground}
1395 type="monochrome"
1396 />
1397 </GlassSurface>
1398 </Pressable>
1399 ) : null}
1400 </>
1401 )}
1402 </View>
1403 </>
1404 );