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

ThreadTerminalRouteScreen.tsx

1,083 lines39.4 KB

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 Schema from "effect/Schema";
24import { AsyncResult } from "effect/reactivity";
25import {
26 KeyboardController,
27 KeyboardEvents,
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";
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 );
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 }
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;
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";
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 );
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 };
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 );
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 }));
354​
355// `useKeyboardState` only flips on willShow and didHide; the accessory must
356// leave as soon as the keyboard starts hiding, so it follows the will-events.
357let keyboardShowing = KeyboardController.isVisible();
358function subscribeKeyboardShowing(onChange: () => void) {
359 keyboardShowing = KeyboardController.isVisible();
360 const willShow = KeyboardEvents.addListener("keyboardWillShow", () => {
361 keyboardShowing = true;
362 onChange();
363 });
364 const willHide = KeyboardEvents.addListener("keyboardWillHide", () => {
365 keyboardShowing = false;
366 onChange();
367 });
368 return () => {
369 willShow.remove();
370 willHide.remove();
371 };
373const getKeyboardShowing = () => keyboardShowing;
374​
375function ThreadTerminal(props: {
376 readonly params: ThreadTerminalRouteScreenProps["route"]["params"];
377 readonly routeEnvironmentId: EnvironmentId | null;
378 readonly selection: ThreadSelection;
379 readonly thread: NonNullable<ThreadSelection["selectedThread"]>;
380 readonly terminalId: string;
381 readonly hasExplicitTerminalId: boolean;
382 readonly access: ReturnType<typeof useTerminalAccess>;
383 readonly knownSessions: ReturnType<typeof useKnownTerminalSessions>;
384}) {
385 const { params, routeEnvironmentId, thread: selectedThread, terminalId } = props;
386 const { selectedThreadProject, selectedEnvironmentConnection } = props.selection;
387 const {
388 session: terminalSession,
389 isAuthenticated,
390 canOperate: canOperateTerminal,
391 canRead: canReadTerminal,
392 } = props.access;
393 const {
394 sessions: knownSessions,
395 isPending: sessionsPending,
396 error: sessionsError,
397 } = props.knownSessions;
398 const insets = useSafeAreaInsets();
399 const nativeColumnMetrics = useNativeColumnLayoutMetrics();
400 const navigation = useNavigation();
401 const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");
402 const clearTerminal = useAtomCommand(terminalEnvironment.clear, "terminal clear");
403 const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, "environment retry");
404 const selectedThreadDetail = useSelectedThreadProjection();
405 const selectedThreadDetailWorktreePath =
406 selectedThreadDetail?.projection.thread.worktreePath ?? null;
407 const routeThreadIdRaw = firstRouteParam(params.threadId);
408 const routeThreadId = routeThreadIdRaw ? ThreadId.make(routeThreadIdRaw) : null;
409 const environment = useEnvironmentPresentation(routeEnvironmentId);
410 const isEnvironmentReady = environment.presentation?.connection.phase === "connected";
411 // Any new positive value triggers capture, even on remount. Pass one only while pending and keep increasing it.
412 const captureSequenceRef = useRef(0);
413 const [captureRequest, setCaptureRequest] = useState(0);
414 const [capturedOutput, setCapturedOutput] = useState<string | null>(null);
415 const requestCapture = () => {
416 captureSequenceRef.current += 1;
417 setCaptureRequest(captureSequenceRef.current);
418 };
419 const {
420 isReady: hasResolvedFontPreference,
421 appearance,
422 themeAppearance: appearanceScheme,
423 themeId,
424 setTerminalFontSize,
425 themeVariables,
426 } = useAppearancePreferences();
427 const fontSize = appearance.terminalFontSize;
428 const terminalKey = `${selectedThread.environmentId}:${selectedThread.id}:${terminalId}`;
429 const activeKnownSession =
430 knownSessions?.find((session) => session.target.terminalId === terminalId) ?? null;
431 const hasTerminalTarget = props.hasExplicitTerminalId || activeKnownSession !== null;
432 const [pendingLaunch] = useState<PendingTerminalLaunch | null>(() =>
433 takePendingTerminalLaunch({
434 environmentId: selectedThread.environmentId,
435 threadId: selectedThread.id,
436 terminalId,
437 }),
438 );
439 const [initialAttachGridSize] = useState(
440 () =>
441 (routeEnvironmentId && routeThreadId
442 ? getCachedTerminalGridSize({
443 environmentId: routeEnvironmentId,
444 threadId: routeThreadId,
445 terminalId,
446 })
447 : null) ?? { cols: DEFAULT_TERMINAL_COLS, rows: DEFAULT_TERMINAL_ROWS },
448 );
449 const [pasteSession] = useState(createTerminalPasteSession);
450 const exitNavigation = useTerminalExitNavigation({
451 environmentId: String(selectedThread.environmentId),
452 threadId: String(selectedThread.id),
453 readFallbackTerminalId: () =>
454 previousLiveTerminalId({
455 sessions: readLiveTerminalSessions(selectedThread.environmentId, selectedThread.id),
456 exitedTerminalId: terminalId,
457 }),
458 });
459 const [terminalSessionDriver] = useState(() =>
460 terminalEnvironment.createSession({
461 target: {
462 environmentId: selectedThread.environmentId,
463 threadId: selectedThread.id,
464 terminalId,
465 },
466 gridSize: initialAttachGridSize,
467 initialInput: pendingLaunch?.initialInput,
468 canOperate: () =>
469 readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope),
470 onExit: exitNavigation.exited,
471 onLiveChange: (live) => {
472 if (live) exitNavigation.restarted();
473 pasteSession.reset(live);
474 },
475 }),
476 );
477 const surfaceRef = useRef<TerminalSurfaceHandle>(null);
478 const [keyboardFocusRequest, setKeyboardFocusRequest] = useState(0);
479 const [pendingModifier, setPendingModifier] = useState<PendingModifier | null>(null);
480 const launchLocation = useInitialTerminalLaunchLocation({
481 targetKey: terminalKey,
482 pendingLaunch,
483 isAuthenticated,
484 canRead: canReadTerminal,
485 canOperate: canOperateTerminal,
486 hasLoadedSessions: knownSessions !== null,
487 location: selectedThreadProject?.workspaceRoot
488 ? {
489 terminalLocation: activeKnownSession?.state.summary ?? null,
490 activeSessionLocation: activeKnownSession?.state.summary ?? null,
491 workspaceRoot: selectedThreadProject.workspaceRoot,
492 threadShellWorktreePath: selectedThread.worktreePath ?? null,
493 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
494 }
495 : null,
496 });
497 const terminalAttachInput = useMemo(
498 () =>
499 launchLocation !== null && hasResolvedFontPreference && isEnvironmentReady
500 ? {
501 threadId: selectedThread.id,
502 terminalId,
503 cwd: launchLocation.cwd,
504 worktreePath: launchLocation.worktreePath,
505 cols: initialAttachGridSize.cols,
506 rows: initialAttachGridSize.rows,
507 ...(pendingLaunch?.env ? { env: pendingLaunch.env } : {}),
508 ...(pendingLaunch ? { restartIfNotRunning: true } : {}),
509 }
510 : null,
511 [
512 hasResolvedFontPreference,
513 initialAttachGridSize,
514 isEnvironmentReady,
515 launchLocation,
516 pendingLaunch,
517 selectedThread.id,
518 terminalId,
519 ],
520 );
521 const observingTerminal = !canOperateTerminal && canReadTerminal && hasTerminalTarget;
522 const streamingOutput = supportsNativeTerminalOutput();
523 const terminal = useAttachedTerminalSession({
524 materializeBuffer: !streamingOutput,
525 environmentId: selectedThread.environmentId,
526 terminal: canOperateTerminal
527 ? terminalAttachInput
528 : observingTerminal
529 ? { threadId: selectedThread.id, terminalId }
530 : null,
531 });
532 useAtomMount(
533 terminalSessionDriver.driver(
534 canOperateTerminal
535 ? terminalAttachInput === null
536 ? null
537 : { kind: "attached", input: terminalAttachInput }
538 : observingTerminal
539 ? { kind: "observing" }
540 : null,
541 ),
542 );
543 const isRunning = terminal.status === "running" || terminal.status === "starting";
544​
545 const cwd = terminal.summary?.cwd ?? selectedThreadProject?.workspaceRoot ?? null;
546 const serverConfigs = useServerConfigs();
547 const hostOs =
548 routeEnvironmentId === null
549 ? null
550 : (serverConfigs.get(routeEnvironmentId)?.environment.platform.os ?? null);
551 const hostPlatform = useMemo(
552 () =>
553 hostPlatformFromOs(hostOs) ??
554 inferHostPlatform(selectedEnvironmentConnection?.environmentLabel ?? null),
555 [hostOs, selectedEnvironmentConnection?.environmentLabel],
556 );
557​
558 const terminalTheme = getMobileTerminalTheme(themeId, appearanceScheme);
559 const headerSubtitle = selectedThreadProject?.title ?? "";
560 const terminalToolbarActions = useMemo<ReadonlyArray<TerminalToolbarAction>>(() => {
561 const modifierActions: ReadonlyArray<TerminalToolbarAction> =
562 hostPlatform === "mac"
563 ? [
564 { kind: "modifier", key: "cmd", label: "cmd", modifier: "meta" },
565 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
566 ]
567 : [
568 { kind: "modifier", key: "ctrl", label: "ctrl", modifier: "ctrl" },
569 { kind: "modifier", key: "alt", label: "alt", modifier: "meta" },
570 ];
571​
572 return [
573 { kind: "send", key: "up", label: "↑", data: "\u001b[A" },
574 { kind: "send", key: "down", label: "↓", data: "\u001b[B" },
575 { kind: "send", key: "left", label: "←", data: "\u001b[D" },
576 { kind: "send", key: "right", label: "→", data: "\u001b[C" },
577 { kind: "send", key: "esc", label: "esc", data: "\u001b" },
578 ...modifierActions,
579 { kind: "send", key: "tab", label: "tab", data: "\t" },
580 { kind: "paste", key: "paste", label: "paste" },
581 { kind: "clear", key: "clear", label: "clear" },
582 { kind: "send", key: "tilde", label: "~", data: "~" },
583 { kind: "send", key: "pipe", label: "|", data: "|" },
584 { kind: "send", key: "slash", label: "/", data: "/" },
585 { kind: "send", key: "dash", label: "-", data: "-" },
586 ];
587 }, [hostPlatform]);
588 const keyboardState = useKeyboardState((state) => ({
589 height: state.height,
590 isVisible: state.isVisible,
591 }));
592 const keyboardShowing = useSyncExternalStore(subscribeKeyboardShowing, getKeyboardShowing);
593 // The accessory follows the keyboard, except that the dismiss and show
594 // buttons flip it ahead of the keyboard animation.
595 const [accessory, setAccessory] = useState({ keyboardShowing, dismissed: false });
596 if (accessory.keyboardShowing !== keyboardShowing) {
597 setAccessory({ keyboardShowing, dismissed: !keyboardShowing });
598 }
599 const isAccessoryDismissed = accessory.dismissed;
600 const isAccessoryVisible = canOperateTerminal && keyboardState.isVisible && !isAccessoryDismissed;
601 // Android's terminal owns an EditText; turning off autoFocus also clears its native focus.
602 const terminalAutoFocus =
603 Platform.OS === "android"
604 ? !isAccessoryDismissed &&
605 (!SHOWCASE_ENABLED || keyboardFocusRequest > 0 || keyboardState.isVisible)
606 : !SHOWCASE_ENABLED;
607 const terminalBottomInset =
608 (keyboardState.isVisible ? keyboardState.height : 0) +
609 (isAccessoryVisible ? TERMINAL_ACCESSORY_HEIGHT : 0);
610​
611 const terminalMenuSessions: ReadonlyArray<TerminalMenuSession> = buildTerminalMenuSessions({
612 knownSessions: knownSessions ?? [],
613 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
614 currentSession: {
615 terminalId,
616 cwd: cwd ?? null,
617 status: terminal.status,
618 hasRunningSubprocess: terminal.hasRunningSubprocess,
619 displayLabel: resolveTerminalSessionLabel(terminalId, terminal.summary),
620 updatedAt: terminal.updatedAt,
621 },
622 });
623​
624 const writeInput = async (data: string): Promise<boolean> => {
625 if (
626 !isRunning ||
627 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
628 ) {
629 return false;
630 }
631​
632 const result = await writeTerminal({
633 environmentId: selectedThread.environmentId,
634 input: {
635 threadId: selectedThread.id,
636 terminalId,
637 data,
638 },
639 });
640 return result._tag === "Success";
641 };
642​
643 const pasteFromClipboard = async () => {
644 await pasteSession.paste({
645 readText: Clipboard.getStringAsync,
646 write: writeInput,
647 onReadError: (cause) => {
648 console.error(new TerminalClipboardReadError({ terminalId, cause }));
649 },
650 });
651 };
652​
653 const writeModifiedInput = (data: string) => {
654 if (pendingModifier === null) {
655 void writeInput(data);
656 return;
657 }
658​
659 setPendingModifier(null);
660 const resolved = resolveModifiedTerminalInput({
661 data,
662 modifier: pendingModifier,
663 hostPlatform,
664 });
665 if (resolved.kind === "paste") {
666 void pasteFromClipboard();
667 return;
668 }
669 void writeInput(resolved.data);
670 };
671​
672 const handleInput = (data: string) => {
673 if (data.length === 0) {
674 return;
675 }
676​
677 writeModifiedInput(data);
678 };
679​
680 const handleResize = (size: { readonly cols: number; readonly rows: number }) => {
681 if (routeEnvironmentId && routeThreadId) {
682 cacheTerminalGridSize(
683 {
684 environmentId: routeEnvironmentId,
685 threadId: routeThreadId,
686 terminalId,
687 },
688 size,
689 );
690 }
691 terminalSessionDriver.reportGridSize(size);
692 };
693​
694 const handleSelectTerminal = (nextTerminalId: string) => {
695 if (nextTerminalId === terminalId) {
696 return;
697 }
698​
699 navigation.dispatch(
700 StackActions.replace("ThreadTerminal", {
701 environmentId: String(selectedThread.environmentId),
702 threadId: String(selectedThread.id),
703 terminalId: nextTerminalId,
704 }),
705 );
706 };
707​
708 const handleCloseTerminal = () => {
709 if (navigation.canGoBack()) {
710 navigation.goBack();
711 return;
712 }
713 navigation.dispatch(
714 StackActions.replace("Thread", {
715 environmentId: params.environmentId,
716 threadId: params.threadId,
717 }),
718 );
719 };
720​
721 const handleOpenNewTerminal = () => {
722 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
723 return;
724 }
725​
726 navigation.dispatch(
727 StackActions.replace("ThreadTerminal", {
728 environmentId: String(selectedThread.environmentId),
729 threadId: String(selectedThread.id),
730 terminalId: nextOpenTerminalId({
731 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
732 activeRouteTerminalId: terminalId,
733 ...(knownSessions === null ||
734 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
735 ? { uniqueSuffix: uuidv4() }
736 : {}),
737 }),
738 }),
739 );
740 };
741​
742 const handleDecreaseFontSize = () => {
743 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
744 };
745​
746 const handleIncreaseFontSize = () => {
747 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
748 };
749​
750 const handleClearTerminal = () => {
751 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
752 return;
753 }
754​
755 setPendingModifier(null);
756 void clearTerminal({
757 environmentId: selectedThread.environmentId,
758 input: {
759 threadId: selectedThread.id,
760 terminalId,
761 },
762 });
763 };
764​
765 const handleToolbarActionPress = (action: TerminalToolbarAction) => {
766 if (action.kind === "modifier") {
767 setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
768 return;
769 }
770​
771 if (action.kind === "clear") {
772 handleClearTerminal();
773 return;
774 }
775​
776 if (action.kind === "paste") {
777 setPendingModifier(null);
778 void pasteFromClipboard();
779 return;
780 }
781​
782 writeModifiedInput(action.data);
783 };
784​
785 const handleDismissKeyboard = () => {
786 setAccessory((current) => ({ ...current, dismissed: true }));
787 void KeyboardController.dismiss();
788 };
789​
790 const handleShowKeyboard = () => {
791 if (!canOperateTerminal) return;
792 setAccessory((current) => ({ ...current, dismissed: false }));
793 setKeyboardFocusRequest((current) => current + 1);
794 surfaceRef.current?.focusKeyboard();
795 };
796 const handleRetryEnvironment = () => {
797 if (routeEnvironmentId !== null) {
798 void retryEnvironment(routeEnvironmentId);
799 }
800 };
801​
802 if (!selectedThreadProject?.workspaceRoot) {
803 return (
804 <View className="flex-1 bg-screen">
805 <EmptyState
806 title="Terminal unavailable"
807 detail="This thread does not have a workspace root yet, so there is nowhere to open a shell."
808 />
809 </View>
810 );
811 }
812​
813 if (!environment.isReady && environment.presentation === null) {
814 return <LoadingScreen message="Opening terminal…" />;
815 }
816​
817 return (
818 <>
819 {capturedOutput !== null ? (
820 <TerminalContextSheet
821 text={capturedOutput}
822 environmentId={selectedThread.environmentId}
823 threadId={selectedThread.id}
824 terminalId={terminalId}
825 terminalLabel={resolveTerminalSessionLabel(terminalId, terminal.summary)}
826 onClose={() => setCapturedOutput(null)}
827 onAttach={() => {
828 setCapturedOutput(null);
829 if (navigation.canGoBack()) navigation.goBack();
830 }}
831 />
832 ) : null}
833 <TerminalHeader
834 canOperateTerminal={canOperateTerminal}
835 subtitle={headerSubtitle}
836 isEnvironmentReady={isEnvironmentReady}
837 fontSize={fontSize}
838 terminalId={terminalId}
839 sessions={terminalMenuSessions}
840 status={{
841 status: terminal.status,
842 hasRunningSubprocess: terminal.hasRunningSubprocess,
843 }}
844 workspaceRoot={selectedThreadProject.workspaceRoot}
845 onCloseTerminal={handleCloseTerminal}
846 onDecreaseFontSize={handleDecreaseFontSize}
847 onIncreaseFontSize={handleIncreaseFontSize}
848 onOpenNewTerminal={handleOpenNewTerminal}
849 onSelectTerminal={handleSelectTerminal}
850 />
851​
852 <ScreenContent>
853 <View
854 className="flex-1"
855 style={{
856 backgroundColor:
857 Platform.OS === "android"
858 ? themeVariables["--color-card-alt"]
859 : terminalTheme.background,
860 // Measured top reservation is zero when UIKit already inset the body or moved the bar.
861 paddingTop:
862 Platform.OS === "ios" ? (nativeColumnMetrics?.safeArea.top ?? insets.top) : 0,
863 paddingBottom:
864 Platform.OS === "android" && !keyboardState.isVisible ? insets.bottom : 0,
865 }}
866 >
867 {!isEnvironmentReady ? (
868 <EnvironmentConnectionNotice
869 environmentLabel={
870 environment.presentation?.entry.target.label ??
871 selectedEnvironmentConnection?.environmentLabel ??
872 "Environment"
873 }
874 connection={
875 environment.presentation?.connection ?? {
876 phase: "available",
877 error: null,
878 traceId: null,
879 }
880 }
881 resourceName="terminal"
882 onRetry={handleRetryEnvironment}
883 />
884 ) : terminalSession.data === null && terminalSession.error === null ? (
885 <EmptyState
886 title="Checking terminal access"
887 detail="Waiting for this connection's permissions."
888 />
889 ) : !canReadTerminal && !canOperateTerminal ? (
890 <EmptyState
891 title={
892 terminalSession.error
893 ? "Could not check terminal access"
894 : "Terminal access unavailable"
895 }
896 detail={
897 terminalSession.error ??
898 "This connection does not have permission to view terminals."
899 }
900 />
901 ) : canOperateTerminal && launchLocation === null ? (
902 sessionsError !== null ? (
903 <EmptyState title="Could not load terminals" detail={sessionsError} />
904 ) : (
905 <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
906 )
907 ) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (
908 <EmptyState title="Loading terminals" detail="Reading existing terminal sessions." />
909 ) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (
910 <EmptyState title="Could not load terminals" detail={sessionsError} />
911 ) : !canOperateTerminal && !hasTerminalTarget ? (
912 <EmptyState
913 title="No terminal sessions"
914 detail="Existing terminals will appear here when another client opens one."
915 />
916 ) : !canOperateTerminal && terminal.error !== null ? (
917 <EmptyState title="Terminal unavailable" detail={terminal.error} />
918 ) : (
919 <>
920 <View
921 style={{
922 flex: 1,
923 paddingBottom: terminalBottomInset,
924 }}
925 >
926 <View
927 pointerEvents="none"
928 style={{
929 position: "absolute",
930 inset: 0,
931 backgroundColor: terminalTheme.background,
932 }}
933 />
934 <TerminalSurface
935 ref={surfaceRef}
936 autoFocus={canOperateTerminal && terminalAutoFocus}
937 readOnly={!canOperateTerminal}
938 buffer={terminal.version === 0 ? null : terminal.buffer}
939 output={terminal.version === 0 ? null : terminal.output}
940 fontSize={fontSize}
941 grid={terminal.grid}
942 isRunning={isRunning}
943 keyboardFocusRequest={keyboardFocusRequest}
944 captureRequest={captureRequest}
945 onCapture={(text) => {
946 setCaptureRequest(0);
947 if (text.trim()) setCapturedOutput(text);
948 else
949 Dialog.alert("No terminal output", "There is no visible output to attach.");
950 }}
951 onInput={handleInput}
952 onResize={handleResize}
953 style={{ flex: 1 }}
954 terminalKey={terminalKey}
955 theme={terminalTheme}
956 />
957 </View>
958​
959 {Platform.OS === "android" && !keyboardState.isVisible ? (
960 <View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">
961 {hasNativeTerminalSurface() ? (
962 <Button label="Attach output" tone="text" onPress={requestCapture} />
963 ) : null}
964 <View className="flex-1" />
965 <IconButton
966 accessibilityLabel="Show keyboard"
967 disabled={!canOperateTerminal}
968 icon="keyboard"
969 onPress={handleShowKeyboard}
970 />
971 </View>
972 ) : Platform.OS !== "android" && hasNativeTerminalSurface() ? (
973 <Pressable
974 accessibilityRole="button"
975 onPress={() => {
976 KeyboardController.dismiss();
977 requestCapture();
978 }}
979 className="px-4 pt-2"
980 style={{
981 paddingBottom:
982 8 +
983 (keyboardState.isVisible
984 ? 0
985 : (nativeColumnMetrics?.safeArea.bottom ?? insets.bottom)),
986 }}
987 >
988 <Text style={{ color: terminalTheme.foreground }}>Attach visible output</Text>
989 </Pressable>
990 ) : null}
991 {isAccessoryVisible ? (
992 <KeyboardStickyView
993 style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
994 offset={{ closed: 0, opened: 0 }}
995 >
996 <View
997 className="border-t"
998 style={{
999 backgroundColor: terminalTheme.background,
1000 borderTopColor: terminalTheme.border,
1001 minHeight: TERMINAL_ACCESSORY_HEIGHT,
1002 }}
1004 <ComposerToolbarRow paddingBottom={4} paddingHorizontal={8} paddingTop={4}>
1005 <ComposerToolbarScroller
1006 contentPaddingRight={2}
1007 fadeOpaque={terminalTheme.background}
1008 fadeTransparent={`${terminalTheme.background}00`}
1010 {terminalToolbarActions.map((action) => {
1011 const active =
1012 action.kind === "modifier" && pendingModifier === action.modifier;
1013​
1014 return (
1015 <ComposerToolbarButton
1016 key={action.key}
1017 active={active}
1018 label={action.label}
1019 maxWidth={120}
1020 minWidth={action.label.length > 1 ? 56 : 44}
1021 onPress={() => handleToolbarActionPress(action)}
1022 showChevron={false}
1023 textTransform={
1024 action.kind === "modifier" || action.kind === "clear"
1025 ? "uppercase"
1026 : "none"
1028 />
1029 );
1030 })}
1031 </ComposerToolbarScroller>
1032 <ComposerToolbarButton
1033 accessibilityLabel="Dismiss keyboard"
1034 icon={{ ios: "keyboard.chevron.compact.down", android: "keyboard_hide" }}
1035 onPress={handleDismissKeyboard}
1036 showChevron={false}
1037 />
1038 </ComposerToolbarRow>
1039 </View>
1040 </KeyboardStickyView>
1041 ) : canOperateTerminal && !keyboardState.isVisible && Platform.OS !== "android" ? (
1042 <Pressable
1043 accessibilityLabel="Show keyboard"
1044 accessibilityRole="button"
1045 onPress={handleShowKeyboard}
1046 style={({ pressed }) => ({
1047 bottom: 16,
1048 borderRadius: 28,
1049 opacity: pressed ? 0.72 : 1,
1050 position: "absolute",
1051 right: 16,
1052 })}
1054 <GlassSurface
1055 chrome="none"
1056 fallbackColor={terminalTheme.background}
1057 glassEffectStyle="regular"
1058 tintColor="transparent"
1059 style={{
1060 alignItems: "center",
1061 borderRadius: 24,
1062 height: 48,
1063 justifyContent: "center",
1064 width: 48,
1065 }}
1066 pointerEvents="none"
1068 <SymbolView
1069 name={{ ios: "keyboard", android: "keyboard" }}
1070 size={20}
1071 tintColor={terminalTheme.foreground}
1072 type="monochrome"
1073 />
1074 </GlassSurface>
1075 </Pressable>
1076 ) : null}
1077 </>
1078 )}
1079 </View>
1080 </ScreenContent>
1081 </>
1082 );