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

ThreadRouteScreen.tsx

1,109 lines42.0 KB

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