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

ThreadRouteScreen.tsx

1,111 lines42.3 KB

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