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

ThreadRouteScreen.tsx

1,159 lines43.8 KB

1import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
2import { buildProjectThreadStartTurnInput } from "../../lib/projectThreadStartTurn";
3import { useWorktreeSetup } from "./use-worktree-setup";
4import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
5import { ScreenHeader } from "../../components/ScreenHeader";
6import { ScreenHeaderButton } from "../../components/ScreenHeaderButton";
7import type { ScreenHeaderAction } from "../../components/ScreenHeader.types";
8import { useThreadHeaderOptions } from "./useThreadHeaderOptions";
9import {
10 StackActions,
11 useFocusEffect,
12 useNavigation,
13 type StaticScreenProps,
14} from "@react-navigation/native";
15import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
16import * as Option from "effect/Option";
17import {
18 AuthOrchestrationOperateScope,
19 AuthTerminalOperateScope,
20 AuthTerminalReadScope,
21 DEFAULT_SERVER_SETTINGS,
22 EnvironmentId,
23 ThreadId,
24 type ProjectScript,
25} from "@t3tools/contracts";
26import {
27 projectScriptCwd,
28 projectScriptRuntimeEnv,
29 resolveProjectScripts,
30} from "@t3tools/shared/projectScripts";
31import { Alert, Platform, ScrollView, View } from "react-native";
32import { useSafeAreaInsets } from "react-native-safe-area-context";
33import { useConnectionsReady } from "../../state/workspace";
34import { useEnvironmentShellReadiness } from "../../state/shell";
35import { restoredNewTaskDraftKey } from "../../state/new-task-draft-key";
36import { clearPendingThreadCreationOutcome } from "../../state/pending-thread-creation";
37import { recoverFailedThreadDraft } from "../../state/recover-failed-thread-draft";
38import { useEnvironmentQuery } from "../../state/query";
39import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vcs-action-state";
40import { vcsEnvironment } from "../../state/vcs";
41import { EmptyState } from "../../components/EmptyState";
42import { LoadingScreen } from "../../components/LoadingScreen";
43import { scopedThreadKey } from "../../lib/scopedEntities";
44import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
45import { connectionTone } from "../connection/connectionTone";
46import {
47 useRemoteConnections,
48 useRemoteConnectionStatus,
49 useRemoteEnvironmentRuntime,
50} from "../../state/use-remote-environment-registry";
51import { useKnownTerminalSessions } from "../../state/use-terminal-session";
52import { uuidv4 } from "../../lib/uuid";
53import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
54import { useSelectedThreadDetailState } from "../../state/use-thread-detail";
55import { useThreadSelection } from "../../state/use-thread-selection";
56import { GitActionProgressOverlay } from "./GitActionProgressOverlay";
57import {
58 buildTerminalMenuSessions,
59 nextOpenTerminalId,
60 resolveProjectScriptTerminalId,
61} from "../terminal/terminalMenu";
62import {
63 resolvePreferredThreadWorktreePath,
64 stagePendingTerminalLaunch,
65} from "../terminal/terminalLaunchContext";
66import { terminalDebugLog } from "../terminal/terminalDebugLog";
67import { ThreadDetailScreen, type ThreadDetailScreenProps } from "./ThreadDetailScreen";
68import { GitOverviewSheet } from "./git/GitOverviewSheet";
69import { useAtomCommand } from "../../state/use-atom-command";
70import { useSelectedThreadGitActions } from "../../state/use-selected-thread-git-actions";
71import { useSelectedThreadGitState } from "../../state/use-selected-thread-git-state";
72import { useSelectedThreadRequests } from "../../state/use-selected-thread-requests";
73import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
74import { useThreadComposerState } from "../../state/use-thread-composer-state";
75import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";
76import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";
77import { threadEnvironment } from "../../state/threads";
78import { projectThreadContentPresentation } from "./threadContentPresentation";
79import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";
80import {
81 useAdaptiveWorkspaceLayout,
82 useAdaptiveWorkspacePaneRole,
83 useRegisterWorkspaceInspector,
84} from "../layout/AdaptiveWorkspaceLayout";
85import { ThreadFileNavigatorPane } from "../files/thread-file-navigator-pane";
86import {
87 ThreadInspectorContentStack,
88 type ThreadInspectorMode,
89} from "./thread-inspector-content-stack";
90import { threadRouteIsHydrating } from "./thread-route-hydration";
91​
92function ThreadHeader(
93 props: Parameters<typeof useThreadHeaderOptions>[0] & {
94 readonly hasThreadCwd: boolean;
95 readonly hasWorkspaceRoot: boolean;
96 readonly fileInspectorSupported: boolean;
97 readonly inspectorMode: ThreadInspectorMode | null;
98 readonly onToggleInspector: () => void;
99 readonly onOpenGitInspector: () => void;
100 readonly onOpenFilesInspector: () => void;
101 },
102) {
103 const navigation = useNavigation();
104 const { layout, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
105 const { onOpenTerminal, onMergeBack } = props.gitControls;
106 const native = useThreadHeaderOptions(props);
107 const androidHeaderActions = useMemo<ReadonlyArray<ScreenHeaderAction>>(() => {
108 const actions: ScreenHeaderAction[] = [];
109 if (props.onReturnToThread) {
110 actions.push({
111 accessibilityLabel: "Return to chat",
112 icon: "chevron.left",
113 onPress: props.onReturnToThread,
114 });
115 }
116 if (props.hasThreadCwd) {
117 const filesVisible = props.inspectorMode === "files" && panes.auxiliaryPaneVisible;
118 actions.push({
119 accessibilityLabel: filesVisible ? "Close files" : "Open files",
120 selected: filesVisible,
121 icon: "folder",
122 onPress: filesVisible ? toggleAuxiliaryPane : props.onOpenFilesInspector,
123 });
124 }
125 if (props.hasWorkspaceRoot && props.gitControls.canOpenTerminal) {
126 actions.push({
127 accessibilityLabel: "Open terminal",
128 icon: "terminal",
129 onPress: () => onOpenTerminal(null),
130 });
131 }
132 actions.push({
133 accessibilityLabel: "Open git controls",
134 icon: "point.topleft.down.curvedto.point.bottomright.up",
135 onPress: props.onOpenGitInspector,
136 });
137 if (onMergeBack) {
138 actions.push({
139 accessibilityLabel: "Merge back to source",
140 icon: "arrow.triangle.merge",
141 onPress: onMergeBack,
142 });
143 }
144 return actions;
145 }, [
146 props.inspectorMode,
147 panes.auxiliaryPaneVisible,
148 props.onOpenFilesInspector,
149 onOpenTerminal,
150 onMergeBack,
151 props.onOpenGitInspector,
152 toggleAuxiliaryPane,
153 props.onReturnToThread,
154 props.hasThreadCwd,
155 props.hasWorkspaceRoot,
156 props.gitControls.canOpenTerminal,
157 ]);
158​
159 return (
160 <>
161 <ScreenHeader
162 title={props.title}
163 subtitle={props.subtitle}
164 sidebar={native.sidebar}
165 options={native.options}
166 optionsVersion={props.gitControls.projectScripts}
167 trailing={
168 props.fileInspectorSupported && props.hasThreadCwd ? (
169 <ScreenHeaderButton
170 accessibilityLabel={
171 props.inspectorMode !== null && panes.auxiliaryPaneVisible
172 ? "Hide inspector"
173 : "Show inspector"
174 }
175 icon="sidebar.right"
176 selected={props.inspectorMode !== null && panes.auxiliaryPaneVisible}
177 onPress={props.onToggleInspector}
178 />
179 ) : null
180 }
181 onBack={
182 layout.usesSplitView
183 ? undefined
184 : () => {
185 // A deep link or cold start has no previous route; Home is the way out.
186 // Read the history at press time: it changes without re-rendering this screen.
187 if (navigation.canGoBack()) navigation.goBack();
188 else navigation.dispatch(StackActions.replace("Home"));
189 }
190 }
191 actions={androidHeaderActions}
192 hideBottomBorder
193 />
194 {native.fallback}
195 </>
196 );
198​
199interface ThreadInspectorSelection {
200 readonly routeThreadIdentity: string | null;
201 readonly mode: ThreadInspectorMode;
203​
204function InspectorPaneRoleActivation() {
205 useAdaptiveWorkspacePaneRole("inspector");
206 return null;
208​
209// A blank param (a hand-typed deep link) is treated as missing, since branded
210// IDs reject whitespace-only values.
211function firstRouteParam(value: string | string[] | undefined): string | null {
212 const first = Array.isArray(value) ? value[0] : value;
213 return first === undefined || first.trim().length === 0 ? null : first;
215​
216function OpeningThreadLoadingScreen() {
217 return <LoadingScreen message="Opening thread…" messagePlacement="above-spinner" />;
219​
220type ThreadRouteScreenRouteProps = StaticScreenProps<{
221 readonly environmentId: string;
222 readonly threadId: string;
223}>;
224​
225interface ThreadRouteScreenProps extends ThreadRouteScreenRouteProps {
226 readonly onReturnToThread?: () => void;
227 readonly renderInspector?: (headerInset: number) => ReactNode;
229​
230/** Shows recovery only after the target route has reached a terminal unavailable state. */
231function ThreadUnavailableScreen(props: {
232 readonly actionLabel: string;
233 readonly onAction: () => void;
234}) {
235 return (
236 <ScrollView
237 contentInsetAdjustmentBehavior="automatic"
238 contentContainerStyle={{
239 flexGrow: 1,
240 justifyContent: "center",
241 paddingHorizontal: 24,
242 paddingVertical: 32,
243 }}
244 className="bg-screen flex-1"
245 >
246 <EmptyState
247 title="Thread unavailable"
248 detail="This thread is not available in the current mobile snapshot."
249 actionLabel={props.actionLabel}
250 onAction={props.onAction}
251 />
252 </ScrollView>
253 );
255​
256export function ThreadRouteScreen(props: ThreadRouteScreenProps) {
257 const connectionsReady = useConnectionsReady();
258 const { connectionState } = useRemoteConnectionStatus();
259 const { selectedThread } = useThreadSelection();
260 const params = props.route.params;
261 const environmentIdRaw = firstRouteParam(params.environmentId);
262 const threadIdRaw = firstRouteParam(params.threadId);
263 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
264 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
265 const routeEnvironmentShellState = useEnvironmentShellReadiness(environmentId);
266 const { onReconnectEnvironment } = useRemoteConnections();
267 const navigation = useNavigation();
268 const routeConnectionState =
269 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
270 const routeThreadKey =
271 environmentId !== null && threadIdRaw !== null
272 ? scopedThreadKey(environmentId, ThreadId.make(threadIdRaw))
273 : null;
274 const selectedThreadKey =
275 selectedThread === null
276 ? null
277 : scopedThreadKey(selectedThread.environmentId, selectedThread.id);
278 const selectedThreadDetailState = useSelectedThreadDetailState();
279​
280 if (environmentId === null || threadIdRaw === null) {
281 return <OpeningThreadLoadingScreen />;
282 }
283​
284 // Render the full thread chrome (header, feed, composer) as soon as the
285 // thread SHELL is known — no blocking on message detail. The feed shows a
286 // loading placeholder while messages fetch, the floating pill above the
287 // composer reports loading/syncing, and the composer's connection pill
288 // reports connecting/reconnecting status.
289 if (selectedThread !== null && selectedThreadKey === routeThreadKey) {
290 return <ThreadRouteContent {...props} selectedThreadDetailState={selectedThreadDetailState} />;
291 }
292​
293 const stillHydrating = threadRouteIsHydrating({
294 isLoadingConnections: !connectionsReady,
295 connectionState: routeConnectionState,
296 shellStatus: routeEnvironmentShellState.status,
297 shellHasError: routeEnvironmentShellState.hasError,
298 detailStatus: selectedThreadDetailState.status,
299 detailHasError: Option.isSome(selectedThreadDetailState.error),
300 });
301​
302 if (stillHydrating) {
303 return <OpeningThreadLoadingScreen />;
304 }
305​
306 return (
307 <ThreadUnavailableScreen
308 actionLabel={
309 routeEnvironmentRuntime === null ? "Manage environments" : "Reconnect environment"
310 }
311 onAction={() => {
312 if (routeEnvironmentRuntime !== null) {
313 onReconnectEnvironment(environmentId);
314 return;
315 }
316 navigation.navigate("SettingsSheet", {
317 screen: "SettingsContent",
318 params: { screen: "SettingsEnvironments" },
319 });
320 }}
321 />
322 );
324​
325function ThreadRouteContent(
326 props: ThreadRouteScreenProps & {
327 readonly selectedThreadDetailState: ReturnType<typeof useSelectedThreadDetailState>;
328 },
329) {
330 const { themeVariables } = useAppearancePreferences();
331 const headerColor = themeVariables["--color-header"];
332 const { fileInspector, layout, panes, showAuxiliaryPane, toggleAuxiliaryPane } =
333 useAdaptiveWorkspaceLayout();
334 const { connectionState } = useRemoteConnectionStatus();
335 const { onReconnectEnvironment } = useRemoteConnections();
336 const {
337 selectedThread,
338 selectedThreadCreation,
339 selectedThreadProject,
340 selectedEnvironmentConnection,
341 } = useThreadSelection();
342 const canOperateThread = useEnvironmentScope(
343 selectedThread?.environmentId ?? null,
344 AuthOrchestrationOperateScope,
345 );
346 const canReadTerminal = useEnvironmentScope(
347 selectedThread?.environmentId ?? null,
348 AuthTerminalReadScope,
349 );
350 const canOperateTerminal = useEnvironmentScope(
351 selectedThread?.environmentId ?? null,
352 AuthTerminalOperateScope,
353 );
354 const selectedThreadDetailState = props.selectedThreadDetailState;
355 const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
356 const { selectedThreadCwd } = useSelectedThreadWorktree();
357 const composer = useThreadComposerState();
358 const gitState = useSelectedThreadGitState();
359 const gitActions = useSelectedThreadGitActions();
360 const requests = useSelectedThreadRequests();
361 const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
362 const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
363 label: "load earlier thread history",
364 reportFailure: false,
365 });
366 const historyControls = useMemo(() => {
367 const history = selectedThreadDetailState.history;
368 if (!selectedThread) {
369 return undefined;
370 }
371 if (!history.hasMoreHistory && history.error === null) {
372 return undefined;
373 }
374 return {
375 hasMoreHistory: history.hasMoreHistory,
376 loading: history.loading,
377 error: history.error,
378 onLoadEarlier: () => {
379 void loadEarlierHistory({
380 environmentId: selectedThread.environmentId,
381 input: { threadId: selectedThread.id },
382 });
383 },
384 };
385 }, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
386 const navigation = useNavigation();
387 const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
388 const mergeBackTargetThreadId = resolveMergeBackTargetThreadId(selectedThreadDetail);
389 const mergeBackRun =
390 selectedThreadDetail === null ? null : resolveLatestMergeBackRun(selectedThreadDetail);
391 const mergeBackBusyRef = useRef(false);
392 const handleMergeBack = useCallback(async () => {
393 if (
394 mergeBackBusyRef.current ||
395 !selectedThread ||
396 mergeBackTargetThreadId === null ||
397 mergeBackRun === null
398 ) {
399 return;
400 }
401 mergeBackBusyRef.current = true;
402 try {
403 const result = await mergeBack({
404 environmentId: selectedThread.environmentId,
405 input: {
406 sourceThreadId: selectedThread.id,
407 targetThreadId: mergeBackTargetThreadId,
408 runId: mergeBackRun.id,
409 creationSource: "mobile",
410 },
411 });
412 if (result._tag !== "Success") return;
413 navigation.navigate("Thread", {
414 environmentId: selectedThread.environmentId,
415 threadId: mergeBackTargetThreadId,
416 });
417 } finally {
418 mergeBackBusyRef.current = false;
419 }
420 }, [mergeBack, mergeBackRun, mergeBackTargetThreadId, navigation, selectedThread]);
421 const params = props.route.params;
422 const environmentIdRaw = firstRouteParam(params.environmentId);
423 const environmentId = environmentIdRaw ? EnvironmentId.make(environmentIdRaw) : null;
424 const threadId = firstRouteParam(params.threadId);
425 const routeThreadIdentity =
426 environmentIdRaw !== null && threadId !== null ? `${environmentIdRaw}:${threadId}` : null;
427 const [inspectorSelection, setInspectorSelection] = useState<ThreadInspectorSelection | null>(
428 () => (props.renderInspector ? { routeThreadIdentity, mode: "route" } : null),
429 );
430 const inspectorMode = (() => {
431 if (inspectorSelection?.routeThreadIdentity === routeThreadIdentity) {
432 if (inspectorSelection.mode === "files" && selectedThreadCwd === null) {
433 return null;
434 }
435 return inspectorSelection.mode;
436 }
437 return null;
438 })();
439 useEffect(() => {
440 if (
441 fileInspector.supported &&
442 selectedThreadCwd === null &&
443 inspectorMode === null &&
444 panes.auxiliaryPaneVisible
445 ) {
446 toggleAuxiliaryPane();
447 }
448 }, [
449 fileInspector.supported,
450 inspectorMode,
451 panes.auxiliaryPaneVisible,
452 selectedThreadCwd,
453 toggleAuxiliaryPane,
454 ]);
455​
456 useEffect(() => {
457 setInspectorSelection((current) => {
458 if (props.renderInspector === undefined) {
459 if (current === null || current.mode === "route") {
460 return null;
461 }
462 return { ...current, routeThreadIdentity };
463 }
464​
465 if (current === null || current.mode === "route") {
466 return { routeThreadIdentity, mode: "route" };
467 }
468​
469 return { ...current, routeThreadIdentity };
470 });
471 }, [props.renderInspector, routeThreadIdentity]);
472​
473 useFocusEffect(
474 useCallback(() => {
475 return () => {
476 if (props.renderInspector === undefined) {
477 // Inspectors are contextual to this chat destination. Clear the
478 // hidden chat copy after a native push so returning from Files,
479 // Review, or Terminal cannot reserve an empty trailing pane.
480 setInspectorSelection(null);
481 }
482 };
483 }, [props.renderInspector]),
484 );
485 const routeEnvironmentRuntime = useRemoteEnvironmentRuntime(environmentId);
486 const routeConnectionState =
487 routeEnvironmentRuntime?.connectionState ?? (environmentId ? "available" : connectionState);
488 const routeConnectionError = routeEnvironmentRuntime?.connectionError ?? null;
489 const selectedThreadWithDraftSettings = useMemo(
490 () =>
491 selectedThread
492 ? {
493 ...selectedThread,
494 modelSelection: composer.modelSelection ?? selectedThread.modelSelection,
495 runtimeMode: composer.runtimeMode ?? selectedThread.runtimeMode,
496 interactionMode: composer.interactionMode ?? selectedThread.interactionMode,
497 }
498 : null,
499 [composer.interactionMode, composer.modelSelection, composer.runtimeMode, selectedThread],
500 );
501​
502 /* ─── Native header theming ──────────────────────────────────────── */
503 const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
504 const headerSubtitle = [
505 selectedThreadProject?.title ?? null,
506 selectedEnvironmentConnection?.environmentLabel ?? null,
507 ]
508 .filter(Boolean)
509 .join(" · ");
510 /* ─── Git status for native header trigger ───────────────────────── */
511 const gitStatus = useEnvironmentQuery(
512 selectedThread !== null && selectedThreadCwd !== null
513 ? vcsEnvironment.status({
514 environmentId: selectedThread.environmentId,
515 input: { cwd: selectedThreadCwd },
516 })
517 : null,
518 );
519 const { sessions: knownTerminalSessions } = useKnownTerminalSessions({
520 environmentId: selectedThread?.environmentId ?? null,
521 threadId: selectedThread?.id ?? null,
522 });
523 const terminalMenuSessions = useMemo(
524 () =>
525 buildTerminalMenuSessions({
526 knownSessions: knownTerminalSessions ?? [],
527 workspaceRoot: selectedThreadProject?.workspaceRoot ?? null,
528 }),
529 [knownTerminalSessions, selectedThreadProject?.workspaceRoot],
530 );
531 const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
532 const handleReconnectEnvironment = useCallback(() => {
533 if (!environmentId) {
534 return;
535 }
536 onReconnectEnvironment(environmentId);
537 }, [environmentId, onReconnectEnvironment]);
538​
539 /* ─── Git action progress (for overlay banner) ──────────────────── */
540 const gitActionProgressTarget = useMemo(
541 () => ({
542 environmentId: selectedThread?.environmentId ?? null,
543 cwd: selectedThreadCwd,
544 }),
545 [selectedThread?.environmentId, selectedThreadCwd],
546 );
547 const gitActionProgress = useGitActionProgress(gitActionProgressTarget);
548​
549 const handleOpenGitInspector = useCallback(() => {
550 if (!fileInspector.supported) {
551 if (selectedThread === null) {
552 return;
553 }
554 navigation.navigate("GitOverview", {
555 environmentId: String(selectedThread.environmentId),
556 threadId: String(selectedThread.id),
557 });
558 return;
559 }
560 setInspectorSelection({ routeThreadIdentity, mode: "git" });
561 showAuxiliaryPane("inspector");
562 }, [fileInspector.supported, navigation, routeThreadIdentity, selectedThread, showAuxiliaryPane]);
563 const handleOpenFilesInspector = useCallback(() => {
564 if (selectedThread === null || selectedThreadCwd === null) {
565 return;
566 }
567 if (!fileInspector.supported) {
568 navigation.navigate("ThreadFiles", {
569 environmentId: String(selectedThread.environmentId),
570 threadId: String(selectedThread.id),
571 });
572 return;
573 }
574 setInspectorSelection({
575 routeThreadIdentity,
576 mode: props.renderInspector === undefined ? "files" : "route",
577 });
578 showAuxiliaryPane("inspector");
579 }, [
580 fileInspector.supported,
581 navigation,
582 props.renderInspector,
583 routeThreadIdentity,
584 selectedThread,
585 selectedThreadCwd,
586 showAuxiliaryPane,
587 ]);
588 const inspectorToggleActionRef = useRef({
589 inspectorMode,
590 openFilesInspector: handleOpenFilesInspector,
591 toggleAuxiliaryPane,
592 });
593 inspectorToggleActionRef.current = {
594 inspectorMode,
595 openFilesInspector: handleOpenFilesInspector,
596 toggleAuxiliaryPane,
597 };
598 const handleToggleInspector = useCallback(() => {
599 const action = inspectorToggleActionRef.current;
600 if (action.inspectorMode === null) {
601 action.openFilesInspector();
602 return;
603 }
604 action.toggleAuxiliaryPane();
605 }, []);
606 const handleSelectInspectorFile = useCallback(
607 (path: string) => {
608 if (selectedThread === null) {
609 return;
610 }
611 const params = {
612 environmentId: String(selectedThread.environmentId),
613 threadId: String(selectedThread.id),
614 path: path.split("/").filter((segment) => segment.length > 0),
615 };
616 if (fileInspector.supported) {
617 navigation.navigate("ThreadFile", params);
618 return;
619 }
620 navigation.navigate("ThreadFile", params);
621 },
622 [fileInspector.supported, navigation, selectedThread],
623 );
624 // The workspace inspector column spans the full window height. On iOS the
625 // panes bring their own nested native headers (which underlap the status
626 // bar); elsewhere the pane content pads itself below the top inset.
627 const safeAreaInsets = useSafeAreaInsets();
628 const inspectorHeaderInset = Platform.OS === "ios" ? 0 : safeAreaInsets.top;
629 const GitInspector = useCallback(
630 () => (
631 <GitOverviewSheet
632 headerInset={inspectorHeaderInset}
633 presentation="inspector"
634 route={{ params: props.route.params }}
635 />
636 ),
637 [inspectorHeaderInset, props.route.params],
638 );
639 const FilesInspector = useCallback(
640 () =>
641 selectedThread !== null && selectedThreadCwd !== null ? (
642 <ThreadFileNavigatorPane
643 cwd={selectedThreadCwd}
644 environmentId={selectedThread.environmentId}
645 headerInset={inspectorHeaderInset}
646 projectName={selectedThreadProject?.title ?? "Files"}
647 selectedPath={null}
648 onSelectFile={handleSelectInspectorFile}
649 />
650 ) : null,
651 [
652 handleSelectInspectorFile,
653 inspectorHeaderInset,
654 selectedThread,
655 selectedThreadCwd,
656 selectedThreadProject?.title,
657 ],
658 );
659 const RouteInspector = useCallback(
660 () => props.renderInspector?.(inspectorHeaderInset),
661 [inspectorHeaderInset, props.renderInspector],
662 );
663 const renderInspectorStack = useCallback(
664 () =>
665 inspectorMode === null ? null : (
666 <ThreadInspectorContentStack
667 Files={FilesInspector}
668 Git={GitInspector}
669 mode={inspectorMode}
670 resetKeys={[routeThreadIdentity, selectedThreadCwd]}
671 Route={props.renderInspector ? RouteInspector : undefined}
672 />
673 ),
674 [
675 FilesInspector,
676 GitInspector,
677 RouteInspector,
678 inspectorMode,
679 props.renderInspector,
680 routeThreadIdentity,
681 selectedThreadCwd,
682 ],
683 );
684 const activeInspectorRenderer = inspectorMode === null ? undefined : renderInspectorStack;
685 // Hand the inspector to the workspace so it renders beside the navigator,
686 // outside this screen's native header — the terminal/git/files toolbar
687 // stays anchored to the chat pane instead of floating above the inspector.
688 useRegisterWorkspaceInspector(activeInspectorRenderer);
689​
690 const handleOpenConnectionEditor = useCallback(() => {
691 void navigation.navigate("Connections");
692 }, [navigation]);
693 const handleStopThread = useCallback(() => {
694 if (
695 !selectedThread ||
696 !readEnvironmentScope(selectedThread.environmentId, AuthOrchestrationOperateScope) ||
697 composer.interruptibleRunId === null
698 ) {
699 return;
700 }
701 return interruptThreadTurn({
702 environmentId: selectedThread.environmentId,
703 input: {
704 threadId: selectedThread.id,
705 runId: composer.interruptibleRunId,
706 },
707 });
708 }, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
709​
710 const handleOpenTerminal = useCallback(
711 (nextTerminalId?: string | null) => {
712 terminalDebugLog("terminal-menu:open-existing", {
713 terminalId: nextTerminalId ?? null,
714 hasThread: Boolean(selectedThread),
715 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
716 });
717​
718 if (
719 !selectedThread ||
720 !selectedThreadProject?.workspaceRoot ||
721 (!readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope) &&
722 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope))
723 ) {
724 return;
725 }
726​
727 void navigation.navigate("ThreadTerminal", {
728 environmentId: String(selectedThread.environmentId),
729 threadId: String(selectedThread.id),
730 ...(nextTerminalId ? { terminalId: nextTerminalId } : {}),
731 });
732 },
733 [navigation, selectedThread, selectedThreadProject?.workspaceRoot],
734 );
735​
736 const handleOpenNewTerminal = useCallback(() => {
737 terminalDebugLog("terminal-menu:open-new", {
738 hasThread: Boolean(selectedThread),
739 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
740 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
741 });
742​
743 if (
744 !selectedThread ||
745 !selectedThreadProject?.workspaceRoot ||
746 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
747 ) {
748 return;
749 }
750​
751 const nextId = nextOpenTerminalId({
752 listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
753 ...(knownTerminalSessions === null ||
754 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
755 ? { uniqueSuffix: uuidv4() }
756 : {}),
757 });
758 void navigation.navigate("ThreadTerminal", {
759 environmentId: String(selectedThread.environmentId),
760 threadId: String(selectedThread.id),
761 terminalId: nextId,
762 });
763 }, [
764 knownTerminalSessions,
765 navigation,
766 selectedThread,
767 selectedThreadProject?.workspaceRoot,
768 terminalMenuSessions,
769 ]);
770​
771 const handleRunProjectScript = useCallback(
772 async (script: ProjectScript) => {
773 terminalDebugLog("project-script:press", {
774 scriptId: script.id,
775 command: script.command,
776 hasThread: Boolean(selectedThread),
777 hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
778 });
779​
780 if (
781 !selectedThread ||
782 !selectedThreadProject?.workspaceRoot ||
783 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalOperateScope)
784 ) {
785 terminalDebugLog("project-script:abort", {
786 scriptId: script.id,
787 reason: "no-thread-workspace-or-terminal-access",
788 });
789 return;
790 }
791​
792 const targetTerminalId = resolveProjectScriptTerminalId({
793 existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
794 ...(knownTerminalSessions === null ||
795 !readEnvironmentScope(selectedThread.environmentId, AuthTerminalReadScope)
796 ? { uniqueSuffix: uuidv4() }
797 : {}),
798 hasRunningTerminal: terminalMenuSessions.some(
799 (session) => session.status === "running" || session.status === "starting",
800 ),
801 });
802 const preferredWorktreePath = resolvePreferredThreadWorktreePath({
803 threadShellWorktreePath: selectedThread.worktreePath ?? null,
804 threadDetailWorktreePath: selectedThreadDetailWorktreePath,
805 });
806 const cwd = projectScriptCwd({
807 project: { cwd: selectedThreadProject.workspaceRoot },
808 worktreePath: preferredWorktreePath,
809 });
810 const env = projectScriptRuntimeEnv({
811 project: { cwd: selectedThreadProject.workspaceRoot },
812 worktreePath: preferredWorktreePath,
813 });
814 stagePendingTerminalLaunch({
815 target: {
816 environmentId: selectedThread.environmentId,
817 threadId: selectedThread.id,
818 terminalId: targetTerminalId,
819 },
820 launch: {
821 cwd,
822 worktreePath: preferredWorktreePath,
823 env,
824 initialInput: `${script.command}\r`,
825 },
826 });
827 terminalDebugLog("project-script:staged", {
828 scriptId: script.id,
829 terminalId: targetTerminalId,
830 cwd,
831 worktreePath: preferredWorktreePath,
832 });
833​
834 void navigation.navigate("ThreadTerminal", {
835 environmentId: String(selectedThread.environmentId),
836 threadId: String(selectedThread.id),
837 terminalId: targetTerminalId,
838 });
839 },
840 [
841 navigation,
842 selectedThread,
843 selectedThreadDetailWorktreePath,
844 selectedThreadProject,
845 terminalMenuSessions,
846 knownTerminalSessions,
847 ],
848 );
849 const threadGitControlProps = {
850 environmentId: environmentIdRaw ?? "",
851 threadId: threadId ?? "",
852 auxiliaryPaneControl:
853 !layout.usesSplitView && fileInspector.supported && selectedThreadCwd !== null
854 ? {
855 accessibilityLabel: "Toggle inspector",
856 onPress: handleToggleInspector,
857 }
858 : undefined,
859 onOpenFilesInspector:
860 fileInspector.supported && selectedThreadCwd !== null ? handleOpenFilesInspector : undefined,
861 onOpenGitInspector: fileInspector.supported ? handleOpenGitInspector : undefined,
862 onMergeBack:
863 mergeBackTargetThreadId !== null && mergeBackRun !== null
864 ? () => void handleMergeBack()
865 : undefined,
866 currentBranch: selectedThread?.branch ?? null,
867 gitStatus: gitStatus.data,
868 gitOperationLabel: gitState.gitOperationLabel,
869 canOpenTerminal:
870 Boolean(selectedThreadProject?.workspaceRoot) && (canReadTerminal || canOperateTerminal),
871 canOperateTerminal,
872 canOpenFiles: Boolean(selectedThreadProject?.workspaceRoot),
873 projectScripts: selectedThreadProject
874 ? resolveProjectScripts(
875 routeEnvironmentRuntime?.serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS,
876 selectedThreadProject,
877 )
878 : [],
879 terminalSessions: terminalMenuSessions,
880 showDirectFileControl: layout.usesSplitView,
881 onOpenTerminal: handleOpenTerminal,
882 onOpenNewTerminal: handleOpenNewTerminal,
883 onRunProjectScript: handleRunProjectScript,
884 onPull: gitActions.onPullSelectedThreadBranch,
885 onRunAction: gitActions.onRunSelectedThreadGitAction,
886 };
887 const handleEditFailedCreation = useCallback(async () => {
888 const creation = selectedThreadCreation?.message;
889 if (!creation?.creation || routeThreadIdentity === null) {
890 return;
891 }
892 // The drain restored the prompt and attachments into the recovery draft
893 // the rejected creation owns. Open that draft by id: without it the sheet
894 // mints a fresh empty one and the restored content is unreachable.
895 try {
896 await recoverFailedThreadDraft(creation);
897 } catch (error) {
898 Alert.alert(
899 "Could not restore draft",
900 error instanceof Error ? error.message : String(error),
901 );
902 return;
903 }
904 clearPendingThreadCreationOutcome(routeThreadIdentity);
905 navigation.dispatch(
906 StackActions.replace("NewTaskSheet", {
907 screen: "NewTaskDraft",
908 params: {
909 draftId: restoredNewTaskDraftKey(creation.messageId),
910 environmentId: String(creation.environmentId),
911 projectId: String(creation.creation.projectId),
912 ...(selectedThreadProject ? { title: selectedThreadProject.title } : {}),
913 },
914 }),
915 );
916 }, [navigation, routeThreadIdentity, selectedThreadCreation, selectedThreadProject]);
917 const setupTurnStartedAt = composer.selectedThreadActivityRun?.startedAt ?? null;
918 const { snapshot: worktreeSetupSnapshot, visible: worktreeSetup } = useWorktreeSetup({
919 environmentId: selectedThread?.environmentId ?? null,
920 threadId: selectedThread?.id ?? null,
921 preparing:
922 composer.selectedThreadActivityRun?.status === "preparing" ||
923 selectedThread?.runtime?.status === "preparing" ||
924 selectedThread?.worktreePath != null ||
925 (selectedThreadCreation?.message.creation?.workspaceMode === "worktree" &&
926 selectedThreadCreation.outcome == null),
927 turnStarted: setupTurnStartedAt !== null,
928 followUpSent:
929 composer.selectedThreadFeed.filter(
930 (entry) => entry.type === "message" && entry.message.role === "user",
931 ).length +
932 composer.selectedThreadQueueCount >
933 1,
934 });
935 const awaitingBootstrapTurn =
936 worktreeSetup !== null
937 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
938 : (selectedThreadDetail?.runs.some((run) => run.status === "preparing") ?? false);
939 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup);
940 const handleCancelWorktreeSetup = useCallback(() => {
941 if (!selectedThread) return;
942 void cancelWorktreeSetup({
943 environmentId: selectedThread.environmentId,
944 input: { threadId: selectedThread.id },
945 });
946 }, [cancelWorktreeSetup, selectedThread]);
947 const startLocalThread = useAtomCommand(threadEnvironment.startTurn, "work locally");
948 const localResendBusy = useRef(false);
949 const setupMessage = selectedThreadDetail?.messages.find((message) => message.role === "user");
950 const handleWorkLocally = useCallback(async () => {
951 if (!selectedThread || !selectedThreadProject || !setupMessage || localResendBusy.current)
952 return;
953 localResendBusy.current = true;
954 try {
955 const result = await cancelWorktreeSetup({
956 environmentId: selectedThread.environmentId,
957 input: { threadId: selectedThread.id },
958 });
959 if (result._tag !== "Success" || !result.value.cancelled) return;
960 // V2 accepts the launch before setup runs, so cancellation never rejects
961 // the original outbox delivery. Reuse the server-owned prompt and uploads.
962 const metadata = makeTurnCommandMetadata();
963 const launched = await startLocalThread({
964 environmentId: selectedThread.environmentId,
965 input: buildProjectThreadStartTurnInput({
966 ...metadata,
967 projectId: selectedThread.projectId,
968 projectCwd: selectedThreadProject.workspaceRoot,
969 text: setupMessage.text,
970 ...(setupMessage.context ? { context: setupMessage.context } : {}),
971 uploadedAttachments: setupMessage.attachments,
972 modelSelection: selectedThread.modelSelection,
973 runtimeMode: selectedThread.runtimeMode,
974 interactionMode: selectedThread.interactionMode,
975 workspaceMode: "local",
976 branch: null,
977 worktreePath: null,
978 startFromOrigin: false,
979 worktreeBranchName: "",
980 }),
981 });
982 if (launched._tag !== "Success") return;
983 navigation.dispatch(
984 StackActions.replace("Thread", {
985 environmentId: String(selectedThread.environmentId),
986 threadId: metadata.threadId,
987 }),
988 );
989 } finally {
990 localResendBusy.current = false;
991 }
992 }, [
993 cancelWorktreeSetup,
994 navigation,
995 selectedThread,
996 selectedThreadProject,
997 setupMessage,
998 startLocalThread,
999 ]);
1000 const creationState = ((): ThreadDetailScreenProps["creationState"] => {
1001 if (selectedThreadCreation === null) {
1002 return awaitingBootstrapTurn ? { kind: "preparing", preparingWorktree: true } : null;
1004 if (selectedThreadCreation.outcome?.kind === "failed") {
1005 return {
1006 kind: "failed",
1007 reason: selectedThreadCreation.outcome.reason,
1008 onEditTask: handleEditFailedCreation,
1009 };
1011 return {
1012 kind: "preparing",
1013 preparingWorktree: selectedThreadCreation.message.creation?.workspaceMode === "worktree",
1014 };
1015 })();
1016 if (!environmentId || !threadId) {
1017 return <OpeningThreadLoadingScreen />;
1019​
1020 if (!selectedThread) {
1021 return <OpeningThreadLoadingScreen />;
1023​
1024 // A queued creation renders as ready content: its prompt is the whole
1025 // conversation until the server creates the thread. The subscription's
1026 // not-found error for that window is expected, not a load failure.
1027 const contentPresentation =
1028 creationState !== null
1029 ? { kind: "ready" as const }
1030 : projectThreadContentPresentation({
1031 hasDetail: selectedThreadDetail !== null,
1032 detailError: Option.getOrNull(selectedThreadDetailState.error),
1033 detailDeleted: selectedThreadDetailState.status === "deleted",
1034 connectionState: routeConnectionState,
1035 });
1036 const serverConfig = routeEnvironmentRuntime?.serverConfig ?? null;
1037 const renderThreadRouteBody = () => (
1038 <>
1039 <GitActionProgressOverlay progress={gitActionProgress} onDismiss={dismissGitActionResult} />
1040​
1041 <View className="flex-1 bg-screen android:overflow-hidden android:rounded-t-[28px] android:bg-thread-canvas">
1042 <ThreadDetailScreen
1043 canOperateThread={canOperateThread}
1044 selectedThread={selectedThreadWithDraftSettings ?? selectedThread}
1045 contentPresentation={contentPresentation}
1046 screenTone={connectionTone(routeConnectionState)}
1047 connectionError={routeConnectionError}
1048 environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
1049 feedbackSubmissions={composer.feedbackSubmissions}
1050 onDismissFeedback={composer.dismissFeedback}
1051 selectedThreadFeed={composer.selectedThreadFeed}
1052 activityRun={composer.selectedThreadActivityRun}
1053 activeWorkStartedAt={
1054 creationState?.kind === "preparing" ||
1055 (worktreeSetup !== null && setupTurnStartedAt === null)
1056 ? null
1057 : composer.activeWorkStartedAt
1059 isCompacting={composer.isCompacting}
1060 runlessWorkActive={composer.runlessWorkActive}
1061 providerSubagentStatus={composer.providerSubagentStatus}
1062 creationState={creationState}
1063 setupWorkingStartedAt={
1064 composer.activeWorkStartedAt !== null &&
1065 worktreeSetupSnapshot !== null &&
1066 composer.selectedThreadFeed.filter(
1067 (entry) => entry.type === "message" && entry.message.role === "user",
1068 ).length <= 1
1069 ? composer.activeWorkStartedAt
1070 : null
1072 worktreeSetup={
1073 worktreeSetup
1074 ? {
1075 snapshot: worktreeSetup,
1076 turnStartedAt: setupTurnStartedAt,
1077 working: composer.activeWorkStartedAt !== null,
1078 turnStarted: setupTurnStartedAt !== null,
1079 onCancel: handleCancelWorktreeSetup,
1080 onWorkLocally: setupMessage && selectedThreadProject ? handleWorkLocally : null,
1082 : null
1084 activePendingApproval={requests.activePendingApproval}
1085 respondingApprovalId={requests.respondingApprovalId}
1086 activePendingUserInput={requests.activePendingUserInput}
1087 activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
1088 activePendingUserInputAnswers={requests.activePendingUserInputAnswers}
1089 respondingUserInputId={requests.respondingUserInputId}
1090 draftMessage={composer.draftMessage}
1091 draftAttachments={composer.draftAttachments}
1092 connectionStateLabel={routeConnectionState}
1093 threadSyncStatus={selectedThreadDetailState.status}
1094 historyControls={historyControls}
1095 activeThreadBusy={composer.activeThreadBusy}
1096 canStopThread={awaitingBootstrapTurn || composer.interruptibleRunId !== null}
1097 queuedRunEdit={composer.queuedRunEdit}
1098 composerDraftKey={composer.composerDraftKey}
1099 followUpBehavior={composer.followUpBehavior}
1100 canSteerActiveTurn={composer.canSteerActiveTurn}
1101 isSavingQueuedEdit={composer.isSavingQueuedEdit}
1102 onCancelQueuedRunEdit={composer.cancelQueuedRunEdit}
1103 onRemoveQueuedEditAttachment={composer.onRemoveQueuedEditAttachment}
1104 environmentId={selectedThread.environmentId}
1105 projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
1106 threadCwd={selectedThreadCwd}
1107 selectedThreadQueueCount={composer.selectedThreadQueueCount}
1108 queuedMessages={composer.selectedThreadQueuedMessages}
1109 dispatchingMessageId={composer.dispatchingQueuedMessageId}
1110 layoutVariant={layout.variant}
1111 usesAutomaticContentInsets={usesNativeHeaderGlass}
1112 onOpenConnectionEditor={handleOpenConnectionEditor}
1113 onChangeDraftMessage={composer.onChangeDraftMessage}
1114 onPickDraftMedia={composer.onPickDraftMedia}
1115 onPickDraftFiles={composer.onPickDraftFiles}
1116 onNativePasteImages={composer.onNativePasteImages}
1117 onNativePasteText={composer.onNativePasteText}
1118 onRemoveDraftImage={composer.onRemoveDraftImage}
1119 serverConfig={serverConfig}
1120 onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
1121 onSendMessage={composer.onSendMessage}
1122 onReconnectEnvironment={handleReconnectEnvironment}
1123 canSwitchThreadProvider={composer.canSwitchThreadProvider}
1124 onUpdateThreadModelSelection={composer.onUpdateModelSelection}
1125 onUpdateThreadRuntimeMode={composer.onUpdateRuntimeMode}
1126 onUpdateThreadInteractionMode={composer.onUpdateInteractionMode}
1127 onRespondToApproval={requests.onRespondToApproval}
1128 onSelectUserInputOption={requests.onSelectUserInputOption}
1129 onChangeUserInputCustomAnswer={requests.onChangeUserInputCustomAnswer}
1130 onSubmitUserInput={requests.onSubmitUserInput}
1131 onDismissUserInput={requests.onDismissUserInput}
1132 />
1133 </View>
1134 </>
1135 );
1136​
1137 return (
1138 <>
1139 {activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
1140 <ThreadHeader
1141 title={selectedThread.title}
1142 subtitle={headerSubtitle}
1143 headerColor={headerColor}
1144 usesNativeHeaderGlass={usesNativeHeaderGlass}
1145 gitControls={threadGitControlProps}
1146 hasThreadCwd={selectedThreadCwd !== null}
1147 hasWorkspaceRoot={Boolean(selectedThreadProject?.workspaceRoot)}
1148 fileInspectorSupported={fileInspector.supported}
1149 inspectorMode={inspectorMode}
1150 onToggleInspector={handleToggleInspector}
1151 onOpenGitInspector={handleOpenGitInspector}
1152 onOpenFilesInspector={handleOpenFilesInspector}
1153 onReturnToThread={props.onReturnToThread}
1154 />
1155​
1156 {renderThreadRouteBody()}
1157 </>
1158 );