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