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

ThreadTerminalRouteScreen.tsx

1,164 lines43.1 KB

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