@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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