Open History to see the last commit
1import * as Dialog from "../../components/ui/Dialog";
2import {
3 AuthTerminalReadScope,
4 AuthTerminalOperateScope,
5 DEFAULT_TERMINAL_ID,
6 EnvironmentId,
7 ThreadId,
8 sessionGrantsScope,
9} from "@t3tools/contracts";
10import { type KnownTerminalSession } from "@t3tools/client-runtime/state/terminal";
11import { SymbolView } from "../../components/ui/AppSymbol";
12import { AppBar } from "../../components/ui/AppBar";
13import { useNativeColumnLayoutMetrics } from "../../native/native-layout-metrics";
14import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
15import { useAtomMount } from "@effect/atom-react";
16import { useMemo, useRef, useState, useSyncExternalStore } from "react";
17import { Platform, Pressable, View } from "react-native";
18import { useSafeAreaInsets } from "react-native-safe-area-context";
19import { AppText as Text } from "../../components/ui/AppText";
20import { TerminalContextSheet } from "./TerminalContextSheet";
21import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule";
22import * as Clipboard from "expo-clipboard";
23import * as Option from "effect/Option";
24import * as Schema from "effect/Schema";
25import { AsyncResult } from "effect/reactivity";
26import {
27 KeyboardController,
28 KeyboardEvents,
29 KeyboardStickyView,
30 useKeyboardState,
31} from "react-native-keyboard-controller";
32
33import {
34 ComposerToolbarButton,
35 ComposerToolbarRow,
36 ComposerToolbarScroller,
37} from "../../components/ComposerToolbar";
38import { EmptyState } from "../../components/ui/EmptyState";
39import { GlassSurface } from "../../components/ui/GlassSurface";
40import { LoadingScreen } from "../../components/LoadingScreen";
41import { ScreenContent } from "../../components/ui/ScreenContent";
42import { Button } from "../../components/ui/Button";
43import { IconButton } from "../../components/ui/IconButton";
44import { environmentCatalog } from "../../connection/catalog";
45import { useEnvironmentPresentation } from "../../state/presentation";
46import { terminalEnvironment } from "../../state/terminal";
47import { environmentSession, readEnvironmentScope } from "../../state/session";
48import { useEnvironmentQuery } from "../../state/query";
49import { appAtomRegistry } from "../../state/atom-registry";
50import { useAtomCommand } from "../../state/use-atom-command";
51import { uuidv4 } from "../../lib/uuid";
52import { useServerConfigs } from "../../state/entities";
53import { useConnectionsReady } from "../../state/workspace";
54import {
55 MAX_TERMINAL_FONT_SIZE,
56 MIN_TERMINAL_FONT_SIZE,
57 TERMINAL_FONT_SIZE_STEP,
58 stepTerminalFontSize,
59} from "../../lib/appearancePreferences";
60import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
61import {
62 useAttachedTerminalSession,
63 useKnownTerminalSessions,
64} from "../../state/use-terminal-session";
65import { useThreadSelection } from "../../state/use-thread-selection";
66import { useSelectedThreadProjection } from "../../state/use-thread-detail";
67import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
68import { TerminalSurface, type TerminalSurfaceHandle } from "./NativeTerminalSurface";
69import { getMobileTerminalTheme } from "./terminalTheme";
70import { terminalDebugLog } from "./terminalDebugLog";
71import { useTerminalExitNavigation } from "./useTerminalExitNavigation";
72import {
73 useInitialTerminalLaunchLocation,
74 takePendingTerminalLaunch,
75 type PendingTerminalLaunch,
76} from "./terminalLaunchContext";
77import {
78 basename,
79 buildTerminalMenuSessions,
80 getTerminalStatusLabel,
81 nextOpenTerminalId,
82 previousLiveTerminalId,
83 resolveTerminalSessionLabel,
84 type TerminalMenuSession,
85} from "./terminalMenu";
86import {
87 hostPlatformFromOs,
88 resolveModifiedTerminalInput,
89 type HostPlatform,
90 type PendingModifier,
91} from "./terminalInput";
92import { createTerminalPasteSession } from "./terminalPaste";
93import { cacheTerminalGridSize, getCachedTerminalGridSize } from "./terminalUiState";
94
95function TerminalHeader(props: {
96 readonly subtitle: string;
97 readonly isEnvironmentReady: boolean;
98 readonly canOperateTerminal: boolean;
99 readonly fontSize: number;
100 readonly terminalId: string;
101 readonly sessions: ReadonlyArray<TerminalMenuSession>;
102 readonly status: Parameters<typeof getTerminalStatusLabel>[0];
103 readonly workspaceRoot: string;
104 readonly onCloseTerminal: () => void;
105 readonly onDecreaseFontSize: () => void;
106 readonly onIncreaseFontSize: () => void;
107 readonly onOpenNewTerminal: () => void;
108 readonly onSelectTerminal: (terminalId: string) => void;
109}) {
110 return (
111 <AppBar
112 title="Terminal"
113 subtitle={props.subtitle}
114 onBack={props.onCloseTerminal}
115 backInSplitView={{
116 accessibilityLabel: "Back to chat",
117 icon: "chevron.left",
118 }}
119 menus={
120 props.isEnvironmentReady
121 ? [
122 {
123 title: "Terminal options",
124 icon: "terminal",
125 status: getTerminalStatusLabel(props.status),
126 items: [
127 {
128 id: "text-size",
129 title: "Text size",
130 icon: "textformat.size",
131 inline: true,
132 items: [
133 {
134 id: "font-decrease",
135 title: `A- ${Math.max(MIN_TERMINAL_FONT_SIZE, props.fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
136 disabled: props.fontSize <= MIN_TERMINAL_FONT_SIZE,
137 onPress: props.onDecreaseFontSize,
138 },
139 {
140 id: "font-increase",
141 title: `A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, props.fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
142 disabled: props.fontSize >= MAX_TERMINAL_FONT_SIZE,
143 onPress: props.onIncreaseFontSize,
144 },
145 ],
146 },
147 ...props.sessions.map((session) => ({
148 id: `terminal-session:${session.terminalId}`,
149 title: session.displayLabel,
150 icon: "terminal",
151 subtitle: [
152 getTerminalStatusLabel({
153 status: session.status,
154 hasRunningSubprocess: session.hasRunningSubprocess,
155 }),
156 basename(session.cwd),
157 ]
158 .filter(Boolean)
159 .join(" · "),
160 selected: session.terminalId === props.terminalId,
161 onPress: () => props.onSelectTerminal(session.terminalId),
162 })),
163 {
164 id: "terminal-new",
165 disabled: !props.canOperateTerminal,
166 title: "Open new terminal",
167 icon: "plus",
168 subtitle: `Start another shell in ${basename(props.workspaceRoot) ?? "this workspace"}`,
169 onPress: props.onOpenNewTerminal,
170 },
171 ],
172 },
173 ]
174 : undefined
175 }
176 />
177 );
178}
179
180const DEFAULT_TERMINAL_COLS = 80;
181const DEFAULT_TERMINAL_ROWS = 24;
182const TERMINAL_ACCESSORY_HEIGHT = 52;
183const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
184
185class TerminalClipboardReadError extends Schema.TaggedError<TerminalClipboardReadError>()(
186 "TerminalClipboardReadError",
187 { terminalId: Schema.String, cause: Schema.Defect() },
188) {
189 override get message(): string {
190 return `Failed to read the clipboard for a paste into terminal ${this.terminalId}.`;
191 }
192}
193
194type TerminalToolbarAction =
195 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
196 | { readonly kind: "clear"; readonly key: string; readonly label: string }
197 | { readonly kind: "paste"; readonly key: string; readonly label: string }
198 | {
199 readonly kind: "modifier";
200 readonly key: string;
201 readonly label: string;
202 readonly modifier: PendingModifier;
203 };
204
205function firstRouteParam(value: string | string[] | undefined): string | null {
206 const first = Array.isArray(value) ? value[0] : value;
207 return first === undefined || first.trim().length === 0 ? null : first;
208}
209
210function inferHostPlatform(environmentLabel: string | null): HostPlatform {
211 const value = environmentLabel?.toLowerCase() ?? "";
212 if (
213 value.includes("mac") ||
214 value.includes("macbook") ||
215 value.includes("mac mini") ||
216 value.includes("imac") ||
217 value.includes("darwin")
218 ) {
219 return "mac";
220 }
221 if (value.includes("windows") || value.includes("win")) {
222 return "windows";
223 }
224 if (value.includes("linux") || value.includes("ubuntu") || value.includes("debian")) {
225 return "linux";
226 }
227
228 return "unknown";
229}
230
231function pickRunningTerminalSessionForBootstrap(
232 sessions: ReadonlyArray<KnownTerminalSession>,
233): KnownTerminalSession | null {
234 const running = sessions.filter(
235 (session) => session.state.status === "running" || session.state.status === "starting",
236 );
237 if (running.length === 0) {
238 return null;
239 }
240 return (
241 running.find((session) => session.target.terminalId === DEFAULT_TERMINAL_ID) ??
242 running[0] ??
243 null
244 );
245}
246
247type ThreadTerminalRouteScreenProps = StaticScreenProps<{
248 readonly environmentId: string;
249 readonly threadId: string;
250 readonly terminalId?: string;
251}>;
252
253type ThreadSelection = ReturnType<typeof useThreadSelection>;
254
255function useTerminalAccess(environmentId: EnvironmentId | null) {
256 const session = useEnvironmentQuery(
257 environmentId === null ? null : environmentSession.sessionStateAtom(environmentId),
258 );
259 const isAuthenticated = session.error === null && session.data?.authenticated === true;
260 return {
261 session,
262 isAuthenticated,
263 canOperate:
264 isAuthenticated &&
265 session.data !== null &&
266 sessionGrantsScope(session.data, AuthTerminalOperateScope),
267 canRead:
268 isAuthenticated &&
269 session.data !== null &&
270 sessionGrantsScope(session.data, AuthTerminalReadScope),
271 };
272}
273
274export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps) {
275 const connectionsReady = useConnectionsReady();
276 const params = props.route.params;
277 const selection = useThreadSelection();
278 const { selectedThread } = selection;
279 const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
280 const routeEnvironmentId = routeEnvironmentIdRaw
281 ? EnvironmentId.make(routeEnvironmentIdRaw)
282 : null;
283 const access = useTerminalAccess(routeEnvironmentId);
284 const knownSessions = useKnownTerminalSessions({
285 environmentId: selectedThread?.environmentId ?? null,
286 threadId: selectedThread?.id ?? null,
287 });
288 const requestedTerminalId = firstRouteParam(params.terminalId);
289 // A route without a terminal shows the thread's running one. The choice is
290 // made once, from the first session list that has one, so the terminal shown
291 // does not change under the user as sessions come and go.
292 const [bootstrapTerminalId, setBootstrapTerminalId] = useState<string | null>(null);
293 const runningSession = knownSessions.sessions
294 ? (pickRunningTerminalSessionForBootstrap(knownSessions.sessions) ??
295 (access.canOperate ? null : (knownSessions.sessions[0] ?? null)))
296 : null;
297 if (
298 requestedTerminalId === null &&
299 bootstrapTerminalId === null &&
300 runningSession !== null &&
301 runningSession.target.terminalId !== DEFAULT_TERMINAL_ID
302 ) {
303 setBootstrapTerminalId(runningSession.target.terminalId);
304 }
305 const explicitTerminalId = requestedTerminalId ?? bootstrapTerminalId;
306 const terminalId = explicitTerminalId ?? DEFAULT_TERMINAL_ID;
307
308 if (!selectedThread) {
309 if (!connectionsReady) {
310 return <LoadingScreen message="Opening terminal…" />;
311 }
312
313 return (
314 <View className="flex-1 bg-screen">
315 <EmptyState
316 title="Thread unavailable"
317 detail="This terminal route needs an active thread and workspace."
318 />
319 </View>
320 );
321 }
322
323 return (
324 <ThreadTerminal
325 key={`${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`}
326 params={params}
327 routeEnvironmentId={routeEnvironmentId}
328 selection={selection}
329 thread={selectedThread}
330 terminalId={terminalId}
331 hasExplicitTerminalId={explicitTerminalId !== null}
332 access={access}
333 knownSessions={knownSessions}
334 />
335 );
336}
337
338function readLiveTerminalSessions(
339 environmentId: EnvironmentId,
340 threadId: ThreadId,
341): ReadonlyArray<TerminalMenuSession> {
342 if (!readEnvironmentScope(environmentId, AuthTerminalReadScope)) return [];
343 const result = appAtomRegistry.get(terminalEnvironment.metadata({ environmentId, input: null }));
344 const summaries = Option.getOrElse(AsyncResult.value(result), () => []);
345 return summaries
346 .filter((summary) => summary.threadId === threadId)
347 .map((summary) => ({
348 terminalId: summary.terminalId,
349 cwd: summary.cwd,
350 status: summary.status,
351 hasRunningSubprocess: summary.hasRunningSubprocess,
352 displayLabel: resolveTerminalSessionLabel(summary.terminalId, summary),
353 updatedAt: summary.updatedAt,
354 }));
355}
356
357// `useKeyboardState` only flips on willShow and didHide; the accessory must
358// leave as soon as the keyboard starts hiding, so it follows the will-events.
359let keyboardShowing = KeyboardController.isVisible();
360function subscribeKeyboardShowing(onChange: () => void) {
361 keyboardShowing = KeyboardController.isVisible();
362 const willShow = KeyboardEvents.addListener("keyboardWillShow", () => {
363 keyboardShowing = true;
364 onChange();
365 });
366 const willHide = KeyboardEvents.addListener("keyboardWillHide", () => {
367 keyboardShowing = false;
368 onChange();
369 });
370 return () => {
371 willShow.remove();
372 willHide.remove();
373 };
374}
375const getKeyboardShowing = () => keyboardShowing;
376
377function ThreadTerminal(props: {
378 readonly params: ThreadTerminalRouteScreenProps["route"]["params"];
379 readonly routeEnvironmentId: EnvironmentId | null;
380 readonly selection: ThreadSelection;
381 readonly thread: NonNullable<ThreadSelection["selectedThread"]>;
382 readonly terminalId: string;
383 readonly hasExplicitTerminalId: boolean;
384 readonly access: ReturnType<typeof useTerminalAccess>;
385 readonly knownSessions: ReturnType<typeof useKnownTerminalSessions>;
386}) {
387 const { params, routeEnvironmentId, thread: selectedThread, terminalId } = props;
388 const { selectedThreadProject, selectedEnvironmentConnection } = props.selection;
389 const {
390 session: terminalSession,
391 isAuthenticated,
392 canOperate: canOperateTerminal,
393 canRead: canReadTerminal,
394 } = props.access;
395 const {
396 sessions: knownSessions,
397 isPending: sessionsPending,
398 error: sessionsError,
399 } = props.knownSessions;
400 const insets = useSafeAreaInsets();
401 const nativeColumnMetrics = useNativeColumnLayoutMetrics();
402 const navigation = useNavigation();
403 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
404 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
405 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
406 const selectedThreadDetail = useSelectedThreadProjection();
407 const selectedThreadDetailWorktreePath =
408 selectedThreadDetail?.projection.thread.worktreePath ?? null;
409 const routeThreadIdRaw = firstRouteParam(params.threadId);
410 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
411 const environment = useEnvironmentPresentation(routeEnvironmentId);
412 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
413 // Any new positive value triggers capture, even on remount. Pass one only while pending and keep increasing it.
414 const captureSequenceRef = useRef(0);
415 const [captureRequest, setCaptureRequest] = useState(0);
416 const [capturedOutput, setCapturedOutput] = useState<string | null>(null);
417 const requestCapture = () => {
418 captureSequenceRef.current += 1;
419 setCaptureRequest(captureSequenceRef.current);
420 };
421 const {
422 isReady: hasResolvedFontPreference,
423 appearance,
424 themeAppearance: appearanceScheme,
425 themeId,
426 setTerminalFontSize,
427 themeVariables,
428 } = useAppearancePreferences();
429 const fontSize = appearance.terminalFontSize;
430 const terminalKey = `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`;
431 const activeKnownSession = useMemo(
432 () => knownSessions?.find((session) => session.target.terminalId === terminalId) ?? null,
433 [knownSessions, terminalId],
434 );
435 const hasTerminalTarget = props.hasExplicitTerminalId || activeKnownSession !== null;
436 const [pendingLaunch] = useState<PendingTerminalLaunch | null>(() =>
437 takePendingTerminalLaunch({
438 environmentId: selectedThread.environmentId,
439 threadId: selectedThread.id,
440 terminalId,
441 }),
442 );
443 const [initialAttachGridSize] = useState(
444 () =>
445 (routeEnvironmentId && routeThreadId
446 ? getCachedTerminalGridSize({
447 environmentId: routeEnvironmentId,
448 threadId: routeThreadId,
449 terminalId,
450 })
451 : null) ?? { cols: DEFAULT_TERMINAL_COLS, rows: DEFAULT_TERMINAL_ROWS },
452 );
453 const [pasteSession] = useState(createTerminalPasteSession);
454 const exitNavigation = useTerminalExitNavigation({
455 environmentId: String(selectedThread.environmentId),
456 threadId: String(selectedThread.id),
457 readFallbackTerminalId: () =>
458 previousLiveTerminalId({
459 sessions: readLiveTerminalSessions(selectedThread.environmentId, selectedThread.id),
460 exitedTerminalId: terminalId,
461 }),
462 });
463 const [terminalSessionDriver] = useState(() =>
464 terminalEnvironment.createSession({
465 target: {
466 environmentId: selectedThread.environmentId,
467 threadId: selectedThread.id,
468 terminalId,
469 },
470 gridSize: initialAttachGridSize,
471 initialInput: pendingLaunch?.initialInput,
472 canOperate: () =>
473 readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope),
474 onExit: exitNavigation.exited,
475 onLiveChange: (live) => {
476 if (live) exitNavigation.restarted();
477 pasteSession.reset(live);
478 },
479 debugLog: terminalDebugLog,
480 }),
481 );
482 const surfaceRef = useRef<TerminalSurfaceHandle>(null);
483 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
484 const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);
485 const launchLocation = useInitialTerminalLaunchLocation({
486 targetKey: terminalKey,
487 pendingLaunch,
488 isAuthenticated,
489 canRead: canReadTerminal,
490 canOperate: canOperateTerminal,
491 hasLoadedSessions: knownSessions !== null,
492 location: selectedThreadProject?.workspaceRoot
493 ? {
494 terminalLocation: activeKnownSession?.state.summary ?? null,
495 activeSessionLocation: activeKnownSession?.state.summary ?? null,
496 workspaceRoot: selectedThreadProject.workspaceRoot,
497 threadShellWorktreePath: selectedThread.worktreePath ?? null,
498 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
499 }
500 : null,
501 });
502 const terminalAttachInput = useMemo(
503 () =>
504 launchLocation !== null && hasResolvedFontPreference && isEnvironmentReady
505 ? {
506 threadId: selectedThread.id,
507 terminalId,
508 cwd: launchLocation.cwd,
509 worktreePath: launchLocation.worktreePath,
510 cols: initialAttachGridSize.cols,
511 rows: initialAttachGridSize.rows,
512 ...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
513 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
514 }
515 : null,
516 [
517 hasResolvedFontPreference,
518 initialAttachGridSize,
519 isEnvironmentReady,
520 launchLocation,
521 pendingLaunch,
522 selectedThread.id,
523 terminalId,
524 ],
525 );
526 const observingTerminal = !canOperateTerminal && canReadTerminal && hasTerminalTarget;
527 const streamingOutput = supportsNativeTerminalOutput();
528 const terminal = useAttachedTerminalSession({
529 materializeBuffer: !streamingOutput,
530 environmentId: selectedThread.environmentId,
531 terminal: canOperateTerminal
532 ? terminalAttachInput
533 : observingTerminal
534 ? { threadId: selectedThread.id, terminalId }
535 : null,
536 });
537 useAtomMount(
538 terminalSessionDriver.driver(
539 canOperateTerminal
540 ? terminalAttachInput === null
541 ? null
542 : { kind: "attached", input: terminalAttachInput }
543 : observingTerminal
544 ? { kind: "observing" }
545 : null,
546 ),
547 );
548 const isRunning = terminal.status === "running" || terminal.status === "starting";
549
550 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
551 const serverConfigs = useServerConfigs();
552 const hostOs =
553 routeEnvironmentId === null
554 ? null
555 : (serverConfigs.get(routeEnvironmentId)?.environment.platform.os ?? null);
556 const hostPlatform = useMemo(
557 () =>
558 hostPlatformFromOs(hostOs) ??
559 inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
560 [hostOs, selectedEnvironmentConnection?.environmentLabel],
561 );
562
563 const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);
564 const headerSubtitle = selectedThreadProject?.title ?? "";
565 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
566 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
567 hostPlatform === "mac"
568 ? [
569 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
570 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
571 ]
572 : [
573 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
574 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
575 ];
576
577 return [
578 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
579 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
580 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
581 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
582 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
583 ...modifierActions,
584 { kind: "send", key: "tab", label: "tab", data: "\t" },
585 { kind: "paste", key: "paste", label: "paste" },
586 { kind: "clear", key: "clear", label: "clear" },
587 { kind: "send", key: "tilde", label: "~", data: "~" },
588 { kind: "send", key: "pipe", label: "|", data: "|" },
589 { kind: "send", key: "slash", label: "/", data: "/" },
590 { kind: "send", key: "dash", label: "-", data: "-" },
591 ];
592 }, [hostPlatform]);
593 const keyboardState = useKeyboardState((state) => ({
594 height: state.height,
595 isVisible: state.isVisible,
596 }));
597 const keyboardShowing = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing);
598 // The accessory follows the keyboard, except that the dismiss and show
599 // buttons flip it ahead of the keyboard animation.
600 const [accessory, setAccessory] = useState({ keyboardShowing, dismissed: false });
601 if (accessory.keyboardShowing !== keyboardShowing) {
602 setAccessory({ keyboardShowing, dismissed: !keyboardShowing });
603 }
604 const isAccessoryDismissed = accessory.dismissed;
605 const isAccessoryVisible = canOperateTerminal && keyboardState.isVisible && !isAccessoryDismissed;
606 // Android's terminal owns an EditText; turning off autoFocus also clears its native focus.
607 const terminalAutoFocus =
608 Platform.OS === "android"
609 ? !isAccessoryDismissed &&
610 (!SHOWCASE_ENABLED || keyboardFocusRequest > 0 || keyboardState.isVisible)
611 : !SHOWCASE_ENABLED;
612 const terminalBottomInset =
613 (keyboardState.isVisible ? keyboardState.height : 0) +
614 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
615
616 const terminalMenuSessions = useMemo<ReadonlyArray<TerminalMenuSession>>(
617 () =>
618 buildTerminalMenuSessions({
619 knownSessions: knownSessions ?? [],
620 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
621 currentSession: {
622 terminalId,
623 cwd: cwd ?? null,
624 status: terminal.status,
625 hasRunningSubprocess: terminal.hasRunningSubprocess,
626 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
627 updatedAt: terminal.updatedAt,
628 },
629 }),
630 [
631 cwd,
632 knownSessions,
633 selectedThreadProject?.workspaceRoot,
634 terminal.hasRunningSubprocess,
635 terminal.summary,
636 terminal.status,
637 terminal.updatedAt,
638 terminalId,
639 ],
640 );
641
642 const writeInput = async (data: string): Promise<boolean> => {
643 if (
644 !isRunning ||
645 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
646 ) {
647 return false;
648 }
649
650 const result = await writeTerminal({
651 environmentId: selectedThread.environmentId,
652 input: {
653 threadId: selectedThread.id,
654 terminalId,
655 data,
656 },
657 });
658 return result._tag === "Success";
659 };
660
661 const pasteFromClipboard = async () => {
662 await pasteSession.paste({
663 readText: Clipboard.getStringAsync,
664 write: writeInput,
665 onReadError: (cause) => {
666 console.error(new TerminalClipboardReadError({ terminalId, cause }));
667 },
668 });
669 };
670
671 const writeModifiedInput = (data: string) => {
672 if (pendingModifier === null) {
673 void writeInput(data);
674 return;
675 }
676
677 setPendingModifier(null);
678 const resolved = resolveModifiedTerminalInput({
679 data,
680 modifier: pendingModifier,
681 hostPlatform,
682 });
683 if (resolved.kind === "paste") {
684 void pasteFromClipboard();
685 return;
686 }
687 void writeInput(resolved.data);
688 };
689
690 const handleInput = (data: string) => {
691 if (data.length === 0) {
692 return;
693 }
694
695 writeModifiedInput(data);
696 };
697
698 const handleResize = (size: { readonly cols: number; readonly rows: number }) => {
699 terminalDebugLog("native:onResize", {
700 cols: size.cols,
701 rows: size.rows,
702 terminalKey,
703 });
704 if (routeEnvironmentId && routeThreadId) {
705 cacheTerminalGridSize(
706 {
707 environmentId: routeEnvironmentId,
708 threadId: routeThreadId,
709 terminalId,
710 },
711 size,
712 );
713 }
714 terminalSessionDriver.reportGridSize(size);
715 };
716
717 const handleSelectTerminal = (nextTerminalId: string) => {
718 if (nextTerminalId === terminalId) {
719 return;
720 }
721
722 navigation.dispatch(
723 StackActions.replace("ThreadTerminal", {
724 environmentId: String(selectedThread.environmentId),
725 threadId: String(selectedThread.id),
726 terminalId: nextTerminalId,
727 }),
728 );
729 };
730
731 const handleCloseTerminal = () => {
732 if (navigation.canGoBack()) {
733 navigation.goBack();
734 return;
735 }
736 navigation.dispatch(
737 StackActions.replace("Thread", {
738 environmentId: params.environmentId,
739 threadId: params.threadId,
740 }),
741 );
742 };
743
744 const handleOpenNewTerminal = () => {
745 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
746 return;
747 }
748
749 navigation.dispatch(
750 StackActions.replace("ThreadTerminal", {
751 environmentId: String(selectedThread.environmentId),
752 threadId: String(selectedThread.id),
753 terminalId: nextOpenTerminalId({
754 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
755 activeRouteTerminalId: terminalId,
756 ...(knownSessions === null ||
757 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
758 ? { uniqueSuffix: uuidv4() }
759 : {}),
760 }),
761 }),
762 );
763 };
764
765 const handleDecreaseFontSize = () => {
766 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
767 };
768
769 const handleIncreaseFontSize = () => {
770 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
771 };
772
773 const handleClearTerminal = () => {
774 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
775 return;
776 }
777
778 setPendingModifier(null);
779 void clearTerminal({
780 environmentId: selectedThread.environmentId,
781 input: {
782 threadId: selectedThread.id,
783 terminalId,
784 },
785 });
786 };
787
788 const handleToolbarActionPress = (action: TerminalToolbarAction) => {
789 if (action.kind === "modifier") {
790 setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
791 return;
792 }
793
794 if (action.kind === "clear") {
795 handleClearTerminal();
796 return;
797 }
798
799 if (action.kind === "paste") {
800 setPendingModifier(null);
801 void pasteFromClipboard();
802 return;
803 }
804
805 writeModifiedInput(action.data);
806 };
807
808 const handleDismissKeyboard = () => {
809 setAccessory((current) => ({ ...current, dismissed: true }));
810 void KeyboardController.dismiss();
811 };
812
813 const handleShowKeyboard = () => {
814 if (!canOperateTerminal) return;
815 setAccessory((current) => ({ ...current, dismissed: false }));
816 setKeyboardFocusRequest((current) => current + 1);
817 surfaceRef.current?.focusKeyboard();
818 };
819 const handleRetryEnvironment = () => {
820 if (routeEnvironmentId !== null) {
821 void retryEnvironment(routeEnvironmentId);
822 }
823 };
824
825 if (!selectedThreadProject?.workspaceRoot) {
826 return (
827 <View className="flex-1 bg-screen">
828 <EmptyState
829 title="Terminal unavailable"
830 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
831 />
832 </View>
833 );
834 }
835
836 if (!environment.isReady && environment.presentation === null) {
837 return <LoadingScreen message="Opening terminal…" />;
838 }
839
840 return (
841 <>
842 {capturedOutput !== null ? (
843 <TerminalContextSheet
844 text={capturedOutput}
845 environmentId={selectedThread.environmentId}
846 threadId={selectedThread.id}
847 terminalId={terminalId}
848 terminalLabel={resolveTerminalSessionLabel(terminalId, terminal.summary)}
849 onClose={() => setCapturedOutput(null)}
850 onAttach={() => {
851 setCapturedOutput(null);
852 if (navigation.canGoBack()) navigation.goBack();
853 }}
854 />
855 ) : null}
856 <TerminalHeader
857 canOperateTerminal={canOperateTerminal}
858 subtitle={headerSubtitle}
859 isEnvironmentReady={isEnvironmentReady}
860 fontSize={fontSize}
861 terminalId={terminalId}
862 sessions={terminalMenuSessions}
863 status={{
864 status: terminal.status,
865 hasRunningSubprocess: terminal.hasRunningSubprocess,
866 }}
867 workspaceRoot={selectedThreadProject.workspaceRoot}
868 onCloseTerminal={handleCloseTerminal}
869 onDecreaseFontSize={handleDecreaseFontSize}
870 onIncreaseFontSize={handleIncreaseFontSize}
871 onOpenNewTerminal={handleOpenNewTerminal}
872 onSelectTerminal={handleSelectTerminal}
873 />
874
875 <ScreenContent>
876 <View
877 className="flex-1"
878 style={{
879 backgroundColor:
880 Platform.OS === "android"
881 ? themeVariables["--color-card-alt"]
882 : terminalTheme.background,
883 // Measured top reservation is zero when UIKit already inset the body or moved the bar.
884 paddingTop:
885 Platform.OS === "ios" ? (nativeColumnMetrics?.safeArea.top ?? insets.top) : 0,
886 paddingBottom:
887 Platform.OS === "android" && !keyboardState.isVisible ? insets.bottom : 0,
888 }}
889 >
890 {!isEnvironmentReady ? (
891 <EnvironmentConnectionNotice
892 environmentLabel={
893 environment.presentation?.entry.target.label ??
894 selectedEnvironmentConnection?.environmentLabel ??
895 "Environment"
896 }
897 connection={
898 environment.presentation?.connection ?? {
899 phase: "available",
900 error: null,
901 traceId: null,
902 }
903 }
904 resourceName="terminal"
905 onRetry={handleRetryEnvironment}
906 />
907 ) : terminalSession.data === null && terminalSession.error === null ? (
908 <EmptyState
909 title="Checking terminal access"
910 detail="Waiting for this connection's permissions."
911 />
912 ) : !canReadTerminal && !canOperateTerminal ? (
913 <EmptyState
914 title={
915 terminalSession.error
916 ? "Could not check terminal access"
917 : "Terminal access unavailable"
918 }
919 detail={
920 terminalSession.error ??
921 "This connection does not have permission to view terminals."
922 }
923 />
924 ) : canOperateTerminal && launchLocation === null ? (
925 sessionsError !== null ? (
926 <EmptyState title="Could not load terminals" detail={sessionsError} />
927 ) : (
928 <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
929 )
930 ) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (
931 <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
932 ) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (
933 <EmptyState title="Could not load terminals" detail={sessionsError} />
934 ) : !canOperateTerminal && !hasTerminalTarget ? (
935 <EmptyState
936 title="No terminal sessions"
937 detail="Existing terminals will appear here when another client opens one."
938 />
939 ) : !canOperateTerminal && terminal.error !== null ? (
940 <EmptyState title="Terminal unavailable" detail={terminal.error} />
941 ) : (
942 <>
943 <View
944 style={{
945 flex: 1,
946 paddingBottom: terminalBottomInset,
947 }}
948 >
949 <View
950 pointerEvents="none"
951 style={{
952 position: "absolute",
953 inset: 0,
954 backgroundColor: terminalTheme.background,
955 }}
956 />
957 <TerminalSurface
958 ref={surfaceRef}
959 autoFocus={canOperateTerminal && terminalAutoFocus}
960 readOnly={!canOperateTerminal}
961 buffer={terminal.version === 0 ? null : terminal.buffer}
962 output={terminal.version === 0 ? null : terminal.output}
963 fontSize={fontSize}
964 isRunning={isRunning}
965 keyboardFocusRequest={keyboardFocusRequest}
966 captureRequest={captureRequest}
967 onCapture={(text) => {
968 setCaptureRequest(0);
969 if (text.trim()) setCapturedOutput(text);
970 else
971 Dialog.alert("No terminal output", "There is no visible output to attach.");
972 }}
973 onInput={handleInput}
974 onResize={handleResize}
975 style={{ flex: 1 }}
976 terminalKey={terminalKey}
977 theme={terminalTheme}
978 />
979 </View>
980
981 {Platform.OS === "android" && !keyboardState.isVisible ? (
982 <View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">
983 {hasNativeTerminalSurface() ? (
984 <Button label="Attach output" tone="text" onPress={requestCapture} />
985 ) : null}
986 <View className="flex-1" />
987 <IconButton
988 accessibilityLabel="Show keyboard"
989 disabled={!canOperateTerminal}
990 icon="keyboard"
991 onPress={handleShowKeyboard}
992 />
993 </View>
994 ) : Platform.OS !== "android" && hasNativeTerminalSurface() ? (
995 <Pressable
996 accessibilityRole="button"
997 onPress={() => {
998 KeyboardController.dismiss();
999 requestCapture();
1000 }}
1001 className="px-4 py-2"
1002 >
1003 <Text style={{ color: terminalTheme.foreground }}>Attach visible output</Text>
1004 </Pressable>
1005 ) : null}
1006 {isAccessoryVisible ? (
1007 <KeyboardStickyView
1008 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
1009 offset={{ closed: 0, opened: 0 }}
1010 >
1011 <View
1012 className="border-t"
1013 style={{
1014 backgroundColor: terminalTheme.background,
1015 borderTopColor: terminalTheme.border,
1016 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1017 }}
1018 >
1019 <ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
1020 <ComposerToolbarScroller
1021 contentPaddingRight={2}
1022 fadeOpaque={terminalTheme.background}
1023 fadeTransparent={`${terminalTheme.background}00`}
1024 >
1025 {terminalToolbarActions.map((action) => {
1026 const active =
1027 action.kind === "modifier" && pendingModifier === action.modifier;
1028
1029 return (
1030 <ComposerToolbarButton
1031 key={action.key}
1032 active={active}
1033 label={action.label}
1034 maxWidth={120}
1035 minWidth={action.label.length > 1 ? 56 : 44}
1036 onPress={() => handleToolbarActionPress(action)}
1037 showChevron={false}
1038 textTransform={
1039 action.kind === "modifier" || action.kind === "clear"
1040 ? "uppercase"
1041 : "none"
1042 }
1043 />
1044 );
1045 })}
1046 </ComposerToolbarScroller>
1047 <ComposerToolbarButton
1048 accessibilityLabel="Dismiss keyboard"
1049 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1050 onPress={handleDismissKeyboard}
1051 showChevron={false}
1052 />
1053 </ComposerToolbarRow>
1054 </View>
1055 </KeyboardStickyView>
1056 ) : canOperateTerminal && !keyboardState.isVisible && Platform.OS !== "android" ? (
1057 <Pressable
1058 accessibilityLabel="Show keyboard"
1059 accessibilityRole="button"
1060 onPress={handleShowKeyboard}
1061 style={({ pressed }) => ({
1062 bottom: 16,
1063 borderRadius: 28,
1064 opacity: pressed ? 0.72 : 1,
1065 position: "absolute",
1066 right: 16,
1067 })}
1068 >
1069 <GlassSurface
1070 chrome="none"
1071 fallbackColor={terminalTheme.background}
1072 glassEffectStyle="regular"
1073 tintColor="transparent"
1074 style={{
1075 alignItems: "center",
1076 borderRadius: 24,
1077 height: 48,
1078 justifyContent: "center",
1079 width: 48,
1080 }}
1081 pointerEvents="none"
1082 >
1083 <SymbolView
1084 name={{ ios: "keyboard", android: "keyboard" }}
1085 size={20}
1086 tintColor={terminalTheme.foreground}
1087 type="monochrome"
1088 />
1089 </GlassSurface>
1090 </Pressable>
1091 ) : null}
1092 </>
1093 )}
1094 </View>
1095 </ScreenContent>
1096 </>
1097 );
1098}