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

ThreadRouteScreen.tsx

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