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

ThreadTerminalRouteScreen.tsx

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