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

ThreadTerminalRouteScreen.tsx

1,064 lines39.1 KB

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