Open History to see the last commit
1import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2import type {
3 EnvironmentId,
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 { focusTerminal } from "../../lib/terminalFocus";
19import { resolveVisibleWorktreeSetup, resolveWorktreeSetupProgress } from "../ChatView.logic";
20import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
21
22// Share in-flight preparation retries across ChatView instances.
23const retryingWorkspacePreparationRunIds = new Set<RunId>();
24
25export function useWorktreeSetup(input: {
26 readonly routeThreadRef: ScopedThreadRef;
27 // Use the draft id until promotion: bootstrap rotates the thread id.
28 readonly ownerKey: string;
29 readonly activeThread:
30 | { readonly id: ThreadId; readonly worktreePath: string | null }
31 | undefined;
32 readonly threadRef: ScopedThreadRef | null;
33 readonly serverProjection: ThreadStructure | null;
34 readonly activityRun: Thread["latestRun"] | null;
35 readonly localPreparing: boolean;
36 readonly sendQueuesBehindSetup: boolean;
37 readonly followUpSent: boolean;
38}) {
39 const {
40 routeThreadRef,
41 ownerKey,
42 activeThread,
43 threadRef,
44 serverProjection,
45 activityRun,
46 localPreparing,
47 sendQueuesBehindSetup,
48 followUpSent,
49 } = input;
50 const cancelWorktreeSetup = useAtomCommand(vcsEnvironment.cancelWorktreeSetup, {
51 reportFailure: false,
52 });
53 const retryWorkspacePreparation = useAtomCommand(threadEnvironment.retryWorkspacePreparation);
54 const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);
55 const [startedSetup, setStartedSetup] = useState<{
56 readonly environmentId: EnvironmentId;
57 readonly threadId: ThreadId;
58 readonly ownerKey: string;
59 } | null>(null);
60 // Retain the dropped snapshot until settled activity reaches the projection.
61 const [heldSnapshot, setHeldSnapshot] = useState<WorktreeSetupSnapshot | null>(null);
62 const started = startedSetup !== null && startedSetup.ownerKey === ownerKey;
63 const target = started ? startedSetup : routeThreadRef;
64 const runPreparing = activityRun?.status === "preparing";
65 // Stop settles the run before checkout cleanup publishes the final setup snapshot.
66 const snapshotQuery = useEnvironmentQuery(
67 started ||
68 (heldSnapshot?.threadId === target.threadId && heldSnapshot.phase === "running") ||
69 (activeThread?.id === routeThreadRef.threadId &&
70 (localPreparing || runPreparing || activeThread.worktreePath !== null))
71 ? vcsEnvironment.worktreeSetup({
72 environmentId: target.environmentId,
73 input: { threadId: target.threadId },
74 })
75 : null,
76 );
77 const latestSnapshot = snapshotQuery.data;
78 const [heldFor, setHeldFor] = useState<{
79 readonly routeThreadRef: ScopedThreadRef;
80 readonly latestSnapshot: WorktreeSetupSnapshot | null | undefined;
81 }>({ routeThreadRef, latestSnapshot: null });
82 if (heldFor.routeThreadRef !== routeThreadRef || heldFor.latestSnapshot !== latestSnapshot) {
83 const routeChanged = heldFor.routeThreadRef !== routeThreadRef;
84 setHeldFor({ routeThreadRef, latestSnapshot });
85 if (routeChanged) {
86 setHeldSnapshot(null);
87 } else if (latestSnapshot) {
88 setHeldSnapshot((current) =>
89 current?.threadId === latestSnapshot.threadId && current.sequence > latestSnapshot.sequence
90 ? current
91 : latestSnapshot,
92 );
93 }
94 }
95 const { snapshot: liveSnapshot, isPreparingWorktree } = resolveWorktreeSetupProgress({
96 threadId: target.threadId,
97 localPreparing,
98 runStatus: activityRun?.status,
99 latest: latestSnapshot,
100 held: heldSnapshot,
101 });
102 const worktreeSetup = resolveVisibleWorktreeSetup({
103 live: liveSnapshot,
104 recorded: null,
105 runs: serverProjection?.runs ?? [],
106 followUpSent,
107 });
108 // After agent handoff, sends queue behind setup without awaiting its scripts.
109 const blocksSend =
110 !sendQueuesBehindSetup &&
111 (worktreeSetup !== null
112 ? worktreeSetup.phase === "running" && !worktreeSetupAgentStarted(worktreeSetup)
113 : isPreparingWorktree);
114
115 const retryableRunIdsKey = [
116 ...workspacePreparationRetryRunIds(
117 serverProjection?.runs ?? [],
118 serverProjection?.turnItems ?? [],
119 ),
120 ].join("\n");
121 const [retryableRunIds, setRetryableRunIds] = useState({
122 key: retryableRunIdsKey,
123 ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
124 });
125 if (retryableRunIds.key !== retryableRunIdsKey) {
126 setRetryableRunIds({
127 key: retryableRunIdsKey,
128 ids: new Set(retryableRunIdsKey === "" ? [] : (retryableRunIdsKey.split("\n") as RunId[])),
129 });
130 }
131
132 const begin = useStableCallback(
133 (thread: { readonly environmentId: EnvironmentId; readonly threadId: ThreadId } | null) =>
134 setStartedSetup(thread === null ? null : { ...thread, ownerKey }),
135 );
136 const cancel = useStableCallback(async () => {
137 if (!worktreeSetup || worktreeSetup.phase !== "running") return false;
138 const result = await cancelWorktreeSetup({
139 environmentId: target.environmentId,
140 input: { threadId: worktreeSetup.threadId },
141 });
142 return result._tag === "Success" && result.value.cancelled;
143 });
144 const retryPreparation = useStableCallback((runId: RunId) => {
145 if (!threadRef || retryingWorkspacePreparationRunIds.has(runId)) return;
146 retryingWorkspacePreparationRunIds.add(runId);
147 void retryWorkspacePreparation({
148 environmentId: threadRef.environmentId,
149 input: { threadId: threadRef.threadId, runId },
150 }).finally(() => retryingWorkspacePreparationRunIds.delete(runId));
151 });
152 // Failed bootstrap deletes threads and terminals; expose terminals only for active threads.
153 const setupThreadRef =
154 worktreeSetup && threadRef && worktreeSetup.threadId === threadRef.threadId ? threadRef : null;
155 const openSetupTerminal = setupThreadRef
156 ? (terminalId: string) => {
157 storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });
158 focusTerminal(setupThreadRef, terminalId);
159 }
160 : null;
161
162 return {
163 worktreeSetup,
164 isPreparingWorktree,
165 blocksSend,
166 retryableRunIds: retryableRunIds.ids,
167 begin,
168 cancel,
169 retryPreparation,
170 openSetupTerminal,
171 };
172}