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

ThreadTerminalRouteScreen.tsx

1,162 lines42.9 KB

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