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

ThreadRouteScreen.tsx

1,108 lines42.0 KB

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