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

useWorktreeSetup.ts

177 lines6.8 KB

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