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

ThreadTerminalRouteScreen.tsx

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