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

ThreadTerminalRouteScreen.tsx

1,077 lines39.8 KB

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