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

ThreadTerminalRouteScreen.tsx

1,368 lines46.8 KB

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