Open History to see the last commit
1import type {
2 EnvironmentId,
3 OrchestrationV2ThreadProjection,
4 RunId,
5 ScopedThreadRef,
6 ThreadId,
7 WorktreeSetupSnapshot,
8} from "@t3tools/contracts";
9import { workspacePreparationRetryRunIds } from "@t3tools/client-runtime/state/turn-item-presentation";
10import { useState } from "react";
11import { useStableCallback } from "../../hooks/useStableCallback";
12import { useEnvironmentQuery } from "../../state/query";
13import { threadEnvironment } from "../../state/threads";
14import { useAtomCommand } from "../../state/use-atom-command";
15import { vcsEnvironment } from "../../state/vcs";
16import { useTerminalUiStateStore } from "../../terminalUiStateStore";
17import type { Thread } from "../../types";
18import { resolveVisibleWorktreeSetup, resolveWorktreeSetupProgress } from "../ChatView.logic";
19import { worktreeSetupAgentStarted } from "./MessagesTimeline.logic";
20
21/** Runs with a workspace preparation retry in flight, across ChatView instances. */
22const retryingWorkspacePreparationRunIds = new Set<RunId>();
23
24/**
25 * Progress of the worktree a send is preparing for this route: the live setup
26 * snapshot, whether it holds the composer, and the actions on its card.
27 */
28export function useWorktreeSetup(input: {
29 readonly routeThreadRef: ScopedThreadRef;
30 // The draft id for a draft route, else the route's thread key. A bootstrap
31 // rotates the thread id, so setup started from a draft stays keyed by it.
32 readonly ownerKey: string;
33 readonly activeThread:
34 | { readonly id: ThreadId; readonly worktreePath: string | null }
35 | undefined;
36 readonly threadRef: ScopedThreadRef | null;
37 readonly serverProjection: OrchestrationV2ThreadProjection | null;
38 readonly activityRun: Thread["latestRun"] | null;
39 readonly localPreparing: boolean;
40 // A send that the server queues behind the setup run is not held here.
41 readonly sendQueuesBehindSetup: boolean;
42 readonly followUpSent: boolean;
43}) {
44 const {
45 routeThreadRef,
46 ownerKey,
47 activeThread,
48 threadRef,
49 serverProjection,
50 activityRun,
51 localPreparing,
52 sendQueuesBehindSetup,
53 followUpSent,
54 } = input;
55 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
56 reportFailure: false,
57 });
58 const retryWorkspacePreparation = useAtomCommand(threadEnvironment.retryWorkspacePreparation);
59 const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);
60 // The thread a send is setting up, recorded by begin() before the server knows it.
61 const [startedSetup, setStartedSetup] = useState<{
62 readonly environmentId: EnvironmentId;
63 readonly threadId: ThreadId;
64 readonly ownerKey: string;
65 } | null>(null);
66 // Last live snapshot from the setup stream. The server drops a finished
67 // snapshot after a grace period and emits null; holding it here bridges the
68 // gap until the settled activity arrives on the thread projection.
69 const [heldSnapshot, setHeldSnapshot] = useState<WorktreeSetupSnapshot | null>(null);
70 const started = startedSetup !== null && startedSetup.ownerKey === ownerKey;
71 // Keep the sending environment during local draft setup; revisiting a
72 // canonical thread subscribes by its durable identity.
73 const target = started ? startedSetup : routeThreadRef;
74 const runPreparing = activityRun?.status === "preparing";
75 const snapshotQuery = useEnvironmentQuery(
76 started ||
77 (activeThread?.id === routeThreadRef.threadId &&
78 (localPreparing || runPreparing || activeThread.worktreePath !== null))
79 ? vcsEnvironment.worktreeSetup({
80 environmentId: target.environmentId,
81 input: { threadId: target.threadId },
82 })
83 : null,
84 );
85 const latestSnapshot = snapshotQuery.data;
86 // A newer snapshot replaces the held one; a late older one for the same
87 // thread does not. Switching routes drops it.
88 const [heldFor, setHeldFor] = useState<{
89 readonly routeThreadRef: ScopedThreadRef;
90 readonly latestSnapshot: WorktreeSetupSnapshot | null | undefined;
91 }>({ routeThreadRef, latestSnapshot: null });
92 if (heldFor.routeThreadRef !== routeThreadRef || heldFor.latestSnapshot !== latestSnapshot) {
93 const routeChanged = heldFor.routeThreadRef !== routeThreadRef;
94 setHeldFor({ routeThreadRef, latestSnapshot });
95 if (routeChanged) {
96 setHeldSnapshot(null);
97 } else if (latestSnapshot) {
98 setHeldSnapshot((current) =>
99 current?.threadId === latestSnapshot.threadId && current.sequence > latestSnapshot.sequence
100 ? current
101 : latestSnapshot,
102 );
103 }
104 }
105 const { snapshot: liveSnapshot, isPreparingWorktree } = resolveWorktreeSetupProgress({
106 threadId: target.threadId,
107 localPreparing,
108 runStatus: activityRun?.status,
109 latest: latestSnapshot,
110 held: heldSnapshot,
111 });
112 const worktreeSetup = resolveVisibleWorktreeSetup({
113 live: liveSnapshot,
114 recorded: null,
115 turnStarted: activityRun?.startedAt != null,
116 followUpSent,
117 });
118 // Sends wait for the agent handoff, not for the setup script: an async
119 // script keeps the snapshot running while the agent already works, and a
120 // follow-up must not be held behind a slow install. Before the first
121 // snapshot arrives the starting session stands in for it. Once the server
122 // has the thread, a send queues behind the setup run instead.
123 const blocksSend =
124 !sendQueuesBehindSetup &&
125 (worktreeSetup !== null
126 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
127 : isPreparingWorktree);
128
129 // Keyed by content so the timeline context only changes when a retry appears or clears.
130 const retryableRunIdsKey = [
131 ...workspacePreparationRetryRunIds(
132 serverProjection?.runs ?? [],
133 serverProjection?.turnItems ?? [],
134 ),
135 ].join("\n");
136 const [retryableRunIds, setRetryableRunIds] = useState({
137 key: retryableRunIdsKey,
138 ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
139 });
140 if (retryableRunIds.key !== retryableRunIdsKey) {
141 setRetryableRunIds({
142 key: retryableRunIdsKey,
143 ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
144 });
145 }
146
147 /** Records the thread a send is about to set up; null when the send needs none. */
148 const begin = useStableCallback(
149 (thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null) =>
150 setStartedSetup(thread === null ? null : { ...thread, ownerKey }),
151 );
152 /** Cancels a running setup. Resolves true once the server cancelled it. */
153 const cancel = useStableCallback(async () => {
154 if (!worktreeSetup || worktreeSetup.phase !== "running") return false;
155 const result = await cancelWorktreeSetup({
156 environmentId: target.environmentId,
157 input: { threadId: worktreeSetup.threadId },
158 });
159 return result._tag === "Success" && result.value.cancelled;
160 });
161 const retryPreparation = useStableCallback((runId: RunId) => {
162 // One retry per failed run: a second click lands after the run is preparing again.
163 if (!threadRef || retryingWorkspacePreparationRunIds.has(runId)) return;
164 retryingWorkspacePreparationRunIds.add(runId);
165 void retryWorkspacePreparation({
166 environmentId: threadRef.environmentId,
167 input: { threadId: threadRef.threadId, runId },
168 }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));
169 });
170 // The setup terminal belongs to the thread that was set up. A failed
171 // bootstrap deletes that thread and closes its terminals, so only offer the
172 // terminal while the setup thread is still the active one.
173 const setupThreadRef =
174 worktreeSetup && threadRef && worktreeSetup.threadId === threadRef.threadId ? threadRef : null;
175 const openSetupTerminal = setupThreadRef
176 ? (terminalId: string) => {
177 storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });
178 }
179 : null;
180
181 return {
182 worktreeSetup,
183 isPreparingWorktree,
184 blocksSend,
185 retryableRunIds: retryableRunIds.ids,
186 begin,
187 cancel,
188 retryPreparation,
189 openSetupTerminal,
190 };
191}