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 { useContentTopInset } from "../../components/ui/useBarInset";
15import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
16import { useAtomMount } from "@effect/atom-react";
17import { useMemo, useRef, useState, useSyncExternalStore } from "react";
18import { Platform, Pressable, View } from "react-native";
19import { useSafeAreaInsets } from "react-native-safe-area-context";
20import { AppText as Text } from "../../components/ui/AppText";
21import { TerminalContextSheet } from "./TerminalContextSheet";
22import { hasNativeTerminalSurface, supportsNativeTerminalOutput } from "./nativeTerminalModule";
23import * as Clipboard from "expo-clipboard";
24import * as Schema from "effect/Schema";
25import { AsyncResult } from "effect/reactivity";
26import {
27 KeyboardController,
28 KeyboardStickyView,
29 useKeyboardState,
30} from "react-native-keyboard-controller";
31
32import {
33 ComposerToolbarButton,
34 ComposerToolbarRow,
35 ComposerToolbarScroller,
36} from "../../components/ComposerToolbar";
37import { EmptyState } from "../../components/ui/EmptyState";
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";
92import { getKeyboardShowEpoch, subscribeKeyboardShowing } from "./terminalKeyboardShowing";
93
94function TerminalHeader(props: {
95 readonly subtitle: string;
96 readonly isEnvironmentReady: boolean;
97 readonly canOperateTerminal: boolean;
98 readonly fontSize: number;
99 readonly terminalId: string;
100 readonly sessions: ReadonlyArray<TerminalMenuSession>;
101 readonly status: Parameters<typeof getTerminalStatusLabel>[0];
102 readonly workspaceRoot: string;
103 readonly onCloseTerminal: () => void;
104 readonly onDecreaseFontSize: () => void;
105 readonly onIncreaseFontSize: () => void;
106 readonly onOpenNewTerminal: () => void;
107 readonly onSelectTerminal: (terminalId: string) => void;
108}) {
109 return (
110 <AppBar
111 title="Terminal"
112 subtitle={props.subtitle}
113 onBack={props.onCloseTerminal}
114 backInSplitView={{
115 accessibilityLabel: "Back to chat",
116 icon: "chevron.left",
117 }}
118 menus={
119 props.isEnvironmentReady
120 ? [
121 {
122 title: "Terminal options",
123 icon: "terminal",
124 status: getTerminalStatusLabel(props.status),
125 items: [
126 {
127 id: "text-size",
128 title: "Text size",
129 icon: "textformat.size",
130 inline: true,
131 items: [
132 {
133 id: "font-decrease",
134 title: `A- ${Math.max(MIN_TERMINAL_FONT_SIZE, props.fontSize - TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
135 disabled: props.fontSize <= MIN_TERMINAL_FONT_SIZE,
136 onPress: props.onDecreaseFontSize,
137 },
138 {
139 id: "font-increase",
140 title: `A+ ${Math.min(MAX_TERMINAL_FONT_SIZE, props.fontSize + TERMINAL_FONT_SIZE_STEP).toFixed(1)} pt`,
141 disabled: props.fontSize >= MAX_TERMINAL_FONT_SIZE,
142 onPress: props.onIncreaseFontSize,
143 },
144 ],
145 },
146 ...props.sessions.map((session) => ({
147 id: `terminal-session:${session.terminalId}`,
148 title: session.displayLabel,
149 icon: "terminal",
150 subtitle: [
151 getTerminalStatusLabel({
152 status: session.status,
153 hasRunningSubprocess: session.hasRunningSubprocess,
154 }),
155 basename(session.cwd),
156 ]
157 .filter(Boolean)
158 .join(" · "),
159 selected: session.terminalId === props.terminalId,
160 onPress: () => props.onSelectTerminal(session.terminalId),
161 })),
162 {
163 id: "terminal-new",
164 disabled: !props.canOperateTerminal,
165 title: "Open new terminal",
166 icon: "plus",
167 subtitle: `Start another shell in ${basename(props.workspaceRoot) ?? "this workspace"}`,
168 onPress: props.onOpenNewTerminal,
169 },
170 ],
171 },
172 ]
173 : undefined
174 }
175 />
176 );
177}
178
179const DEFAULT_TERMINAL_COLS = 80;
180const DEFAULT_TERMINAL_ROWS = 24;
181const TERMINAL_ACCESSORY_HEIGHT = 52;
182const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
183
184class TerminalClipboardReadError extends Schema.TaggedError<TerminalClipboardReadError>()(
185 "TerminalClipboardReadError",
186 { terminalId: Schema.String, cause: Schema.Defect() },
187) {
188 override get message(): string {
189 return `Failed to read the clipboard for a paste into terminal ${this.terminalId}.`;
190 }
191}
192
193type TerminalToolbarAction =
194 | { readonly kind: "send"; readonly key: string; readonly label: string; readonly data: string }
195 | { readonly kind: "clear"; 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 contentTopInset = useContentTopInset();
381 const navigation = useNavigation();
382 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
383 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
384 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
385 const selectedThreadDetail = useSelectedThreadProjection();
386 const selectedThreadDetailWorktreePath =
387 selectedThreadDetail?.projection.thread.worktreePath ?? null;
388 const routeThreadIdRaw = firstRouteParam(params.threadId);
389 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
390 const environment = useEnvironmentPresentation(routeEnvironmentId);
391 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
392 // Any new positive value triggers capture, even on remount. Pass one only while pending and keep increasing it.
393 const captureSequenceRef = useRef(0);
394 const [captureRequest, setCaptureRequest] = useState(0);
395 const [capturedOutput, setCapturedOutput] = useState<string | null>(null);
396 const requestCapture = () => {
397 captureSequenceRef.current += 1;
398 setCaptureRequest(captureSequenceRef.current);
399 };
400 const {
401 isReady: hasResolvedFontPreference,
402 appearance,
403 themeAppearance: appearanceScheme,
404 themeId,
405 setTerminalFontSize,
406 themeVariables,
407 } = useAppearancePreferences();
408 const fontSize = appearance.terminalFontSize;
409 const terminalKey = `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`;
410 const activeKnownSession =
411 knownSessions?.find((session) => session.target.terminalId === terminalId) ?? null;
412 const hasTerminalTarget = props.hasExplicitTerminalId || activeKnownSession !== null;
413 const [pendingLaunch] = useState<PendingTerminalLaunch | null>(() =>
414 takePendingTerminalLaunch({
415 environmentId: selectedThread.environmentId,
416 threadId: selectedThread.id,
417 terminalId,
418 }),
419 );
420 const [initialAttachGridSize] = useState(
421 () =>
422 (routeEnvironmentId && routeThreadId
423 ? getCachedTerminalGridSize({
424 environmentId: routeEnvironmentId,
425 threadId: routeThreadId,
426 terminalId,
427 })
428 : null) ?? { cols: DEFAULT_TERMINAL_COLS, rows: DEFAULT_TERMINAL_ROWS },
429 );
430 const [pasteSession] = useState(createTerminalPasteSession);
431 const exitNavigation = useTerminalExitNavigation({
432 environmentId: String(selectedThread.environmentId),
433 threadId: String(selectedThread.id),
434 readFallbackTerminalId: () =>
435 previousLiveTerminalId({
436 sessions: readLiveTerminalSessions(selectedThread.environmentId, selectedThread.id),
437 exitedTerminalId: terminalId,
438 }),
439 });
440 const [terminalSessionDriver] = useState(() =>
441 terminalEnvironment.createSession({
442 target: {
443 environmentId: selectedThread.environmentId,
444 threadId: selectedThread.id,
445 terminalId,
446 },
447 gridSize: initialAttachGridSize,
448 initialInput: pendingLaunch?.initialInput,
449 canOperate: () =>
450 readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope),
451 onExit: exitNavigation.exited,
452 onLiveChange: (live) => {
453 if (live) exitNavigation.restarted();
454 pasteSession.reset(live);
455 },
456 }),
457 );
458 const surfaceRef = useRef<TerminalSurfaceHandle>(null);
459 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
460 const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);
461 const launchLocation = useInitialTerminalLaunchLocation({
462 targetKey: terminalKey,
463 pendingLaunch,
464 isAuthenticated,
465 canRead: canReadTerminal,
466 canOperate: canOperateTerminal,
467 hasLoadedSessions: knownSessions !== null,
468 location: selectedThreadProject?.workspaceRoot
469 ? {
470 terminalLocation: activeKnownSession?.state.summary ?? null,
471 activeSessionLocation: activeKnownSession?.state.summary ?? null,
472 workspaceRoot: selectedThreadProject.workspaceRoot,
473 threadShellWorktreePath: selectedThread.worktreePath ?? null,
474 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
475 }
476 : null,
477 });
478 const terminalAttachInput = useMemo(
479 () =>
480 launchLocation !== null && hasResolvedFontPreference && isEnvironmentReady
481 ? {
482 threadId: selectedThread.id,
483 terminalId,
484 cwd: launchLocation.cwd,
485 worktreePath: launchLocation.worktreePath,
486 cols: initialAttachGridSize.cols,
487 rows: initialAttachGridSize.rows,
488 ...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
489 ...(pendingLaunch ? { stopOnSettle: pendingLaunch.stopOnSettle ?? false } : {}),
490 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
491 }
492 : null,
493 [
494 hasResolvedFontPreference,
495 initialAttachGridSize,
496 isEnvironmentReady,
497 launchLocation,
498 pendingLaunch,
499 selectedThread.id,
500 terminalId,
501 ],
502 );
503 const observingTerminal = !canOperateTerminal && canReadTerminal && hasTerminalTarget;
504 const streamingOutput = supportsNativeTerminalOutput();
505 const terminal = useAttachedTerminalSession({
506 materializeBuffer: !streamingOutput,
507 environmentId: selectedThread.environmentId,
508 terminal: canOperateTerminal
509 ? terminalAttachInput
510 : observingTerminal
511 ? { threadId: selectedThread.id, terminalId }
512 : null,
513 });
514 useAtomMount(
515 terminalSessionDriver.driver(
516 canOperateTerminal
517 ? terminalAttachInput === null
518 ? null
519 : { kind: "attached", input: terminalAttachInput }
520 : observingTerminal
521 ? { kind: "observing" }
522 : null,
523 ),
524 );
525 const isRunning = terminal.status === "running" || terminal.status === "starting";
526
527 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
528 const serverConfigs = useServerConfigs();
529 const hostOs =
530 routeEnvironmentId === null
531 ? null
532 : (serverConfigs.get(routeEnvironmentId)?.environment.platform.os ?? null);
533 const hostPlatform = useMemo(
534 () =>
535 hostPlatformFromOs(hostOs) ??
536 inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
537 [hostOs, selectedEnvironmentConnection?.environmentLabel],
538 );
539
540 const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);
541 const headerSubtitle = selectedThreadProject?.title ?? "";
542 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
543 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
544 hostPlatform === "mac"
545 ? [
546 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
547 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
548 ]
549 : [
550 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
551 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
552 ];
553
554 return [
555 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
556 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
557 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
558 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
559 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
560 ...modifierActions,
561 { kind: "send", key: "tab", label: "tab", data: "\t" },
562 { kind: "clear", key: "clear", label: "clear" },
563 { kind: "send", key: "tilde", label: "~", data: "~" },
564 { kind: "send", key: "pipe", label: "|", data: "|" },
565 { kind: "send", key: "slash", label: "/", data: "/" },
566 { kind: "send", key: "dash", label: "-", data: "-" },
567 ];
568 }, [hostPlatform]);
569 const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
570 const keyboardHeight = useKeyboardState((state) => state.height);
571 const keyboardShowEpoch = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowEpoch);
572 // The accessory follows the keyboard, except that the dismiss and show
573 // buttons flip it ahead of the keyboard animation.
574 const [accessory, setAccessory] = useState({ keyboardShowEpoch, dismissed: false });
575 if (accessory.keyboardShowEpoch !== keyboardShowEpoch) {
576 setAccessory({ keyboardShowEpoch, dismissed: keyboardShowEpoch === 0 });
577 }
578 const isAccessoryDismissed = accessory.dismissed;
579 const isAccessoryVisible = canOperateTerminal && isKeyboardVisible && !isAccessoryDismissed;
580 // Android's terminal owns an EditText; turning off autoFocus also clears its native focus.
581 const terminalAutoFocus =
582 Platform.OS === "android"
583 ? !isAccessoryDismissed &&
584 (!SHOWCASE_ENABLED || keyboardFocusRequest > 0 || isKeyboardVisible)
585 : !SHOWCASE_ENABLED;
586 const terminalBottomInset =
587 (isKeyboardVisible ? keyboardHeight : 0) + (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
588
589 const terminalMenuSessions: ReadonlyArray<TerminalMenuSession> = buildTerminalMenuSessions({
590 knownSessions: knownSessions ?? [],
591 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
592 currentSession: {
593 terminalId,
594 cwd: cwd ?? null,
595 status: terminal.status,
596 hasRunningSubprocess: terminal.hasRunningSubprocess,
597 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
598 updatedAt: terminal.updatedAt,
599 },
600 });
601
602 const writeInput = async (data: string): Promise<boolean> => {
603 if (
604 !isRunning ||
605 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
606 ) {
607 return false;
608 }
609
610 const result = await writeTerminal({
611 environmentId: selectedThread.environmentId,
612 input: {
613 threadId: selectedThread.id,
614 terminalId,
615 data,
616 },
617 });
618 return result._tag === "Success";
619 };
620
621 const pasteText = async (readText: () => Promise<string>) => {
622 await pasteSession.paste({
623 readText,
624 write: writeInput,
625 onReadError: (cause) => {
626 console.error(new TerminalClipboardReadError({ terminalId, cause }));
627 },
628 });
629 };
630
631 const writeModifiedInput = (data: string) => {
632 if (pendingModifier === null) {
633 void writeInput(data);
634 return;
635 }
636
637 setPendingModifier(null);
638 const resolved = resolveModifiedTerminalInput({
639 data,
640 modifier: pendingModifier,
641 hostPlatform,
642 });
643 if (resolved.kind === "paste") {
644 void pasteText(Clipboard.getStringAsync);
645 return;
646 }
647 void writeInput(resolved.data);
648 };
649
650 const handleInput = (data: string) => {
651 if (data.length === 0) {
652 return;
653 }
654
655 writeModifiedInput(data);
656 };
657
658 const handleResize = (size: { readonly cols: number; readonly rows: number }) => {
659 if (routeEnvironmentId && routeThreadId) {
660 cacheTerminalGridSize(
661 {
662 environmentId: routeEnvironmentId,
663 threadId: routeThreadId,
664 terminalId,
665 },
666 size,
667 );
668 }
669 terminalSessionDriver.reportGridSize(size);
670 };
671
672 const handleSelectTerminal = (nextTerminalId: string) => {
673 if (nextTerminalId === terminalId) {
674 return;
675 }
676
677 navigation.dispatch(
678 StackActions.replace("ThreadTerminal", {
679 environmentId: String(selectedThread.environmentId),
680 threadId: String(selectedThread.id),
681 terminalId: nextTerminalId,
682 }),
683 );
684 };
685
686 const handleCloseTerminal = () => {
687 if (navigation.canGoBack()) {
688 navigation.goBack();
689 return;
690 }
691 navigation.dispatch(
692 StackActions.replace("Thread", {
693 environmentId: params.environmentId,
694 threadId: params.threadId,
695 }),
696 );
697 };
698
699 const handleOpenNewTerminal = () => {
700 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
701 return;
702 }
703
704 navigation.dispatch(
705 StackActions.replace("ThreadTerminal", {
706 environmentId: String(selectedThread.environmentId),
707 threadId: String(selectedThread.id),
708 terminalId: nextOpenTerminalId({
709 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
710 activeRouteTerminalId: terminalId,
711 ...(knownSessions === null ||
712 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
713 ? { uniqueSuffix: uuidv4() }
714 : {}),
715 }),
716 }),
717 );
718 };
719
720 const handleDecreaseFontSize = () => {
721 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
722 };
723
724 const handleIncreaseFontSize = () => {
725 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
726 };
727
728 const handleClearTerminal = () => {
729 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
730 return;
731 }
732
733 setPendingModifier(null);
734 void clearTerminal({
735 environmentId: selectedThread.environmentId,
736 input: {
737 threadId: selectedThread.id,
738 terminalId,
739 },
740 });
741 };
742
743 const handleToolbarActionPress = (action: TerminalToolbarAction) => {
744 if (action.kind === "modifier") {
745 setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
746 return;
747 }
748
749 // Toolbar input bypasses the native field, so a syllable it holds must not be recomposed.
750 surfaceRef.current?.resetInput();
751
752 if (action.kind === "clear") {
753 handleClearTerminal();
754 return;
755 }
756
757 writeModifiedInput(action.data);
758 };
759
760 const handlePaste = (readText: () => Promise<string>) => {
761 // Pasted text bypasses the native field, so a syllable it holds must not be recomposed.
762 surfaceRef.current?.resetInput();
763 setPendingModifier(null);
764 void pasteText(readText);
765 };
766
767 const handleDismissKeyboard = () => {
768 setAccessory((current) => ({ ...current, dismissed: true }));
769 void KeyboardController.dismiss();
770 };
771
772 const handleShowKeyboard = () => {
773 if (!canOperateTerminal) return;
774 setAccessory((current) => ({ ...current, dismissed: false }));
775 setKeyboardFocusRequest((current) => current + 1);
776 surfaceRef.current?.focusKeyboard();
777 };
778 const handleRetryEnvironment = () => {
779 if (routeEnvironmentId !== null) {
780 void retryEnvironment(routeEnvironmentId);
781 }
782 };
783
784 if (!selectedThreadProject?.workspaceRoot) {
785 return (
786 <View className="flex-1 bg-screen">
787 <EmptyState
788 title="Terminal unavailable"
789 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
790 />
791 </View>
792 );
793 }
794
795 if (!environment.isReady && environment.presentation === null) {
796 return <LoadingScreen message="Opening terminal…" />;
797 }
798
799 return (
800 <>
801 {capturedOutput !== null ? (
802 <TerminalContextSheet
803 text={capturedOutput}
804 environmentId={selectedThread.environmentId}
805 threadId={selectedThread.id}
806 terminalId={terminalId}
807 terminalLabel={resolveTerminalSessionLabel(terminalId, terminal.summary)}
808 onClose={() => setCapturedOutput(null)}
809 onAttach={() => {
810 setCapturedOutput(null);
811 if (navigation.canGoBack()) navigation.goBack();
812 }}
813 />
814 ) : null}
815 <TerminalHeader
816 canOperateTerminal={canOperateTerminal}
817 subtitle={headerSubtitle}
818 isEnvironmentReady={isEnvironmentReady}
819 fontSize={fontSize}
820 terminalId={terminalId}
821 sessions={terminalMenuSessions}
822 status={{
823 status: terminal.status,
824 hasRunningSubprocess: terminal.hasRunningSubprocess,
825 }}
826 workspaceRoot={selectedThreadProject.workspaceRoot}
827 onCloseTerminal={handleCloseTerminal}
828 onDecreaseFontSize={handleDecreaseFontSize}
829 onIncreaseFontSize={handleIncreaseFontSize}
830 onOpenNewTerminal={handleOpenNewTerminal}
831 onSelectTerminal={handleSelectTerminal}
832 />
833
834 <ScreenContent>
835 <View
836 className="flex-1"
837 style={{
838 backgroundColor:
839 Platform.OS === "android"
840 ? themeVariables["--color-card-alt"]
841 : terminalTheme.background,
842 // Measured top reservation is zero when UIKit already inset the body or moved the bar.
843 paddingTop: contentTopInset,
844 paddingBottom: Platform.OS === "android" && !isKeyboardVisible ? insets.bottom : 0,
845 }}
846 >
847 {!isEnvironmentReady ? (
848 <EnvironmentConnectionNotice
849 environmentLabel={
850 environment.presentation?.entry.target.label ??
851 selectedEnvironmentConnection?.environmentLabel ??
852 "Environment"
853 }
854 connection={
855 environment.presentation?.connection ?? {
856 phase: "available",
857 error: null,
858 traceId: null,
859 }
860 }
861 resourceName="terminal"
862 onRetry={handleRetryEnvironment}
863 />
864 ) : terminalSession.data === null && terminalSession.error === null ? (
865 <EmptyState
866 title="Checking terminal access"
867 detail="Waiting for this connection's permissions."
868 />
869 ) : !canReadTerminal && !canOperateTerminal ? (
870 <EmptyState
871 title={
872 terminalSession.error
873 ? "Could not check terminal access"
874 : "Terminal access unavailable"
875 }
876 detail={
877 terminalSession.error ??
878 "This connection does not have permission to view terminals."
879 }
880 />
881 ) : canOperateTerminal && launchLocation === null ? (
882 sessionsError !== null ? (
883 <EmptyState title="Could not load terminals" detail={sessionsError} />
884 ) : (
885 <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
886 )
887 ) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (
888 <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
889 ) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (
890 <EmptyState title="Could not load terminals" detail={sessionsError} />
891 ) : !canOperateTerminal && !hasTerminalTarget ? (
892 <EmptyState
893 title="No terminal sessions"
894 detail="Existing terminals will appear here when another client opens one."
895 />
896 ) : !canOperateTerminal && terminal.error !== null ? (
897 <EmptyState title="Terminal unavailable" detail={terminal.error} />
898 ) : (
899 <>
900 <View
901 style={{
902 flex: 1,
903 paddingBottom: terminalBottomInset,
904 }}
905 >
906 <View
907 pointerEvents="none"
908 style={{
909 position: "absolute",
910 inset: 0,
911 backgroundColor: terminalTheme.background,
912 }}
913 />
914 <TerminalSurface
915 ref={surfaceRef}
916 autoFocus={canOperateTerminal && terminalAutoFocus}
917 readOnly={!canOperateTerminal}
918 buffer={terminal.version === 0 ? null : terminal.buffer}
919 output={terminal.version === 0 ? null : terminal.output}
920 fontSize={fontSize}
921 grid={terminal.grid}
922 isRunning={isRunning}
923 keyboardFocusRequest={keyboardFocusRequest}
924 captureRequest={captureRequest}
925 onCapture={(text) => {
926 setCaptureRequest(0);
927 if (text.trim()) setCapturedOutput(text);
928 else
929 Dialog.alert("No terminal output", "There is no visible output to attach.");
930 }}
931 onInput={handleInput}
932 onPaste={(text) => handlePaste(async () => text)}
933 onResize={handleResize}
934 style={{ flex: 1 }}
935 terminalKey={terminalKey}
936 theme={terminalTheme}
937 />
938 </View>
939
940 {Platform.OS === "android" && !isKeyboardVisible ? (
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 (isKeyboardVisible
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="Paste"
1015 icon={{ ios: "doc.on.clipboard", android: "content_paste" }}
1016 onPress={() => handlePaste(Clipboard.getStringAsync)}
1017 showChevron={false}
1018 />
1019 <ComposerToolbarButton
1020 accessibilityLabel="Dismiss keyboard"
1021 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1022 onPress={handleDismissKeyboard}
1023 showChevron={false}
1024 />
1025 </ComposerToolbarRow>
1026 </View>
1027 </KeyboardStickyView>
1028 ) : canOperateTerminal && !isKeyboardVisible && Platform.OS !== "android" ? (
1029 <Pressable
1030 accessibilityLabel="Show keyboard"
1031 accessibilityRole="button"
1032 onPress={handleShowKeyboard}
1033 style={({ pressed }) => ({
1034 bottom: 16,
1035 borderRadius: 28,
1036 opacity: pressed ? 0.72 : 1,
1037 position: "absolute",
1038 right: 16,
1039 })}
1040 >
1041 <GlassSurface
1042 chrome="none"
1043 fallbackColor={terminalTheme.background}
1044 glassEffectStyle="regular"
1045 tintColor="transparent"
1046 style={{
1047 alignItems: "center",
1048 borderRadius: 24,
1049 height: 48,
1050 justifyContent: "center",
1051 width: 48,
1052 }}
1053 pointerEvents="none"
1054 >
1055 <SymbolView
1056 name={{ ios: "keyboard", android: "keyboard" }}
1057 size={20}
1058 tintColor={terminalTheme.foreground}
1059 type="monochrome"
1060 />
1061 </GlassSurface>
1062 </Pressable>
1063 ) : null}
1064 </>
1065 )}
1066 </View>
1067 </ScreenContent>
1068 </>
1069 );
1070}