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

ThreadTerminalRouteScreen.tsx

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