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

useWorktreeSetup.ts

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