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

ThreadTerminalRouteScreen.tsx

1,164 lines43.0 KB

1import * as Dialog from "../../components/ui/Dialog";
2import { m } from "../../i18n/messages";
3import {
4 AuthTerminalReadScope,
5 AuthTerminalOperateScope,
6 chunkTerminalWrite,
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 (data: string): Promise<boolean> => {
653 if (
654 !isRunning ||
655 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
656 ) {
657 return false;
658 }
659​
660 // Android's IME delivers a system paste as one input, which can exceed one write.
661 const isSameShell = pasteSession.liveness();
662 for (const chunk of chunkTerminalWrite(data)) {
663 if (!isSameShell()) return false;
664 const result = await writeTerminal({
665 environmentId: selectedThread.environmentId,
666 input: {
667 threadId: selectedThread.id,
668 terminalId,
669 data: chunk,
670 },
671 });
672 if (result._tag !== "Success") return false;
673 }
674 return true;
675 };
676​
677 const pasteText = async (readText: () => Promise<string>) => {
678 await pasteSession.paste({
679 readText,
680 write: writeInput,
681 onReadError: (cause) => {
682 console.error(new TerminalClipboardReadError({ terminalId, cause }));
683 },
684 });
685 };
686​
687 const writeModifiedInput = (data: string) => {
688 if (pendingModifier === null) {
689 void writeInput(data);
690 return;
691 }
692​
693 setPendingModifier(null);
694 const resolved = resolveModifiedTerminalInput({
695 data,
696 modifier: pendingModifier,
697 hostPlatform,
698 });
699 if (resolved.kind === "paste") {
700 void pasteText(Clipboard.getStringAsync);
701 return;
702 }
703 void writeInput(resolved.data);
704 };
705​
706 const handleInput = (data: string) => {
707 if (data.length === 0) {
708 return;
709 }
710​
711 writeModifiedInput(data);
712 };
713​
714 const handleResize = (size: { readonly cols: number; readonly rows: number }) => {
715 if (routeEnvironmentId && routeThreadId) {
716 cacheTerminalGridSize(
717 {
718 environmentId: routeEnvironmentId,
719 threadId: routeThreadId,
720 terminalId,
721 },
722 size,
723 );
724 }
725 terminalSessionDriver.reportGridSize(size);
726 };
727​
728 const handleSelectTerminal = (nextTerminalId: string) => {
729 if (nextTerminalId === terminalId) {
730 return;
731 }
732​
733 navigation.dispatch(
734 StackActions.replace("ThreadTerminal", {
735 environmentId: String(selectedThread.environmentId),
736 threadId: String(selectedThread.id),
737 terminalId: nextTerminalId,
738 }),
739 );
740 };
741​
742 const handleBack = () => {
743 if (navigation.canGoBack()) {
744 navigation.goBack();
745 return;
746 }
747 navigation.dispatch(
748 StackActions.replace("Thread", {
749 environmentId: params.environmentId,
750 threadId: params.threadId,
751 }),
752 );
753 };
754​
755 const handleCloseTerminal = () => {
756 Dialog.confirm({
757 title: gt('Close terminal "{label}"?', {
758 label: resolveTerminalSessionLabel(terminalId, terminal.summary),
759 }),
760 message: gt("This stops the running process and clears its history."),
761 confirmText: gt("Confirm"),
762 destructive: true,
763 onConfirm: async () => {
764 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) return;
765 const result = await closeTerminal({
766 environmentId: selectedThread.environmentId,
767 input: { threadId: selectedThread.id, terminalId, deleteHistory: true },
768 });
769 if (AsyncResult.isSuccess(result)) exitNavigation.exited();
770 else Dialog.alert(gt("Couldn't close terminal"), gt("Check the connection and try again."));
771 },
772 });
773 };
774​
775 const handleOpenNewTerminal = () => {
776 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
777 return;
778 }
779​
780 navigation.dispatch(
781 StackActions.replace("ThreadTerminal", {
782 environmentId: String(selectedThread.environmentId),
783 threadId: String(selectedThread.id),
784 terminalId: nextOpenTerminalId({
785 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
786 activeRouteTerminalId: terminalId,
787 ...(knownSessions === null ||
788 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
789 ? { uniqueSuffix: uuidv4() }
790 : {}),
791 }),
792 }),
793 );
794 };
795​
796 const handleDecreaseFontSize = () => {
797 setTerminalFontSize(stepTerminalFontSize(fontSize, -1));
798 };
799​
800 const handleIncreaseFontSize = () => {
801 setTerminalFontSize(stepTerminalFontSize(fontSize, 1));
802 };
803​
804 const handleClearTerminal = () => {
805 if (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)) {
806 return;
807 }
808​
809 setPendingModifier(null);
810 void clearTerminal({
811 environmentId: selectedThread.environmentId,
812 input: {
813 threadId: selectedThread.id,
814 terminalId,
815 },
816 });
817 };
818​
819 const handleToolbarActionPress = (action: TerminalToolbarAction) => {
820 if (action.kind === "modifier") {
821 setPendingModifier((current) => (current === action.modifier ? null : action.modifier));
822 return;
823 }
824​
825 // Toolbar input bypasses the native field, so a syllable it holds must not be recomposed.
826 surfaceRef.current?.resetInput();
827​
828 if (action.kind === "clear") {
829 handleClearTerminal();
830 return;
831 }
832​
833 writeModifiedInput(action.data);
834 };
835​
836 const handlePaste = (readText: () => Promise<string>) => {
837 // Pasted text bypasses the native field, so a syllable it holds must not be recomposed.
838 surfaceRef.current?.resetInput();
839 setPendingModifier(null);
840 void pasteText(readText);
841 };
842​
843 const handleDismissKeyboard = () => {
844 setAccessory((current) => ({ ...current, dismissed: true }));
845 void KeyboardController.dismiss();
846 };
847​
848 const handleShowKeyboard = () => {
849 if (!canOperateTerminal) return;
850 setAccessory((current) => ({ ...current, dismissed: false }));
851 setKeyboardFocusRequest((current) => current + 1);
852 surfaceRef.current?.focusKeyboard();
853 };
854 const handleRetryEnvironment = () => {
855 if (routeEnvironmentId !== null) {
856 void retryEnvironment(routeEnvironmentId);
857 }
858 };
859​
860 if (!selectedThreadProject?.workspaceRoot) {
861 return (
862 <View className="flex-1 bg-screen">
863 <EmptyState
864 title={gt("Terminal unavailable")}
865 detail={gt(
866 "This thread does not have a workspace root yet, so there is nowhere to open a shell.",
867 )}
868 />
869 </View>
870 );
871 }
872​
873 if (!environment.isReady && environment.presentation === null) {
874 return <LoadingScreen message={gt("Opening terminal…")} />;
875 }
876​
877 return (
878 <>
879 {capturedOutput !== null ? (
880 <TerminalContextSheet
881 text={capturedOutput}
882 environmentId={selectedThread.environmentId}
883 threadId={selectedThread.id}
884 terminalId={terminalId}
885 terminalLabel={resolveTerminalSessionLabel(terminalId, terminal.summary, messages)}
886 onClose={() => setCapturedOutput(null)}
887 onAttach={() => {
888 setCapturedOutput(null);
889 if (navigation.canGoBack()) navigation.goBack();
890 }}
891 />
892 ) : null}
893 <TerminalHeader
894 canOperateTerminal={canOperateTerminal}
895 subtitle={headerSubtitle}
896 isEnvironmentReady={isEnvironmentReady}
897 fontSize={fontSize}
898 terminalId={terminalId}
899 sessions={terminalMenuSessions}
900 status={{
901 status: terminal.status,
902 hasRunningSubprocess: terminal.hasRunningSubprocess,
903 }}
904 workspaceRoot={selectedThreadProject.workspaceRoot}
905 onBack={handleBack}
906 onCloseTerminal={handleCloseTerminal}
907 onDecreaseFontSize={handleDecreaseFontSize}
908 onIncreaseFontSize={handleIncreaseFontSize}
909 onOpenNewTerminal={handleOpenNewTerminal}
910 onSelectTerminal={handleSelectTerminal}
911 />
912​
913 <ScreenContent>
914 <View
915 className="flex-1"
916 style={{
917 backgroundColor:
918 Platform.OS === "android"
919 ? themeVariables["--color-card-alt"]
920 : terminalTheme.background,
921 // Measured top reservation is zero when UIKit already inset the body or moved the bar.
922 paddingTop: contentTopInset,
923 paddingBottom: Platform.OS === "android" && !isKeyboardVisible ? insets.bottom : 0,
924 }}
925 >
926 {!isEnvironmentReady ? (
927 <EnvironmentConnectionNotice
928 environmentLabel={
929 environment.presentation?.entry.target.label ??
930 selectedEnvironmentConnection?.environmentLabel ??
931 gt("Environment", { $context: "fallback environment name" })
932 }
933 connection={
934 environment.presentation?.connection ?? {
935 phase: "available",
936 error: null,
937 traceId: null,
938 }
939 }
940 resource="terminal"
941 onRetry={handleRetryEnvironment}
942 />
943 ) : terminalSession.data === null && terminalSession.error === null ? (
944 <EmptyState
945 title={gt("Checking terminal access")}
946 detail={gt("Waiting for this connection's permissions.")}
947 />
948 ) : !canReadTerminal && !canOperateTerminal ? (
949 <EmptyState
950 title={
951 terminalSession.error
952 ? gt("Could not check terminal access")
953 : gt("Terminal access unavailable")
954 }
955 detail={
956 terminalSession.error ??
957 gt("This connection does not have permission to view terminals.")
958 }
959 />
960 ) : canOperateTerminal && launchLocation === null ? (
961 sessionsError !== null ? (
962 <EmptyState title={gt("Could not load terminals")} detail={sessionsError} />
963 ) : (
964 <EmptyState
965 title={gt("Loading terminals")}
966 detail={gt("Reading existing terminal sessions.")}
967 />
968 )
969 ) : !canOperateTerminal && !hasTerminalTarget && sessionsPending ? (
970 <EmptyState
971 title={gt("Loading terminals")}
972 detail={gt("Reading existing terminal sessions.")}
973 />
974 ) : !canOperateTerminal && !hasTerminalTarget && sessionsError !== null ? (
975 <EmptyState title={gt("Could not load terminals")} detail={sessionsError} />
976 ) : !canOperateTerminal && !hasTerminalTarget ? (
977 <EmptyState
978 title={gt("No terminal sessions")}
979 detail={gt("Existing terminals will appear here when another client opens one.")}
980 />
981 ) : terminal.error !== null && (!canOperateTerminal || terminal.status === "error") ? (
982 <EmptyState title={gt("Terminal unavailable")} detail={terminal.error} />
983 ) : (
984 <>
985 <View
986 style={{
987 flex: 1,
988 paddingBottom: terminalBottomInset,
989 }}
990 >
991 <View
992 pointerEvents="none"
993 style={{
994 position: "absolute",
995 inset: 0,
996 backgroundColor: terminalTheme.background,
997 }}
998 />
999 <TerminalSurface
1000 ref={surfaceRef}
1001 autoFocus={canOperateTerminal && terminalAutoFocus}
1002 readOnly={!canOperateTerminal}
1003 buffer={terminal.version === 0 ? null : terminal.buffer}
1004 output={terminal.version === 0 ? null : terminal.output}
1005 fontSize={fontSize}
1006 grid={terminal.grid}
1007 isRunning={isRunning}
1008 keyboardFocusRequest={keyboardFocusRequest}
1009 captureRequest={captureRequest}
1010 onCapture={(text) => {
1011 setCaptureRequest(0);
1012 if (text.trim()) setCapturedOutput(text);
1013 else
1014 Dialog.alert(
1015 m(msg("No terminal output")),
1016 m(msg("There is no visible output to attach.")),
1017 );
1018 }}
1019 onInput={handleInput}
1020 onPaste={(text) => handlePaste(async () => text)}
1021 onResize={handleResize}
1022 style={{ flex: 1 }}
1023 terminalKey={terminalKey}
1024 theme={terminalTheme}
1025 />
1026 </View>
1027​
1028 {Platform.OS === "android" && !isKeyboardVisible ? (
1029 <View className="min-h-14 flex-row items-center gap-2 bg-card-alt px-2">
1030 {hasNativeTerminalSurface() ? (
1031 <Button label={gt("Attach output")} tone="text" onPress={requestCapture} />
1032 ) : null}
1033 <View className="flex-1" />
1034 <IconButton
1035 accessibilityLabel={gt("Show keyboard")}
1036 disabled={!canOperateTerminal}
1037 icon="keyboard"
1038 onPress={handleShowKeyboard}
1039 />
1040 </View>
1041 ) : Platform.OS !== "android" && hasNativeTerminalSurface() ? (
1042 <Pressable
1043 accessibilityRole="button"
1044 onPress={() => {
1045 KeyboardController.dismiss();
1046 requestCapture();
1047 }}
1048 className="min-h-[44px] justify-center px-4 pt-2"
1049 style={{
1050 paddingBottom:
1051 8 +
1052 (isKeyboardVisible
1053 ? 0
1054 : (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("Paste", { $context: "verb" })}
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 );