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

WorktreeSetupTracker.ts

361 lines12.5 KB

1import type {
2 ThreadId,
3 WorktreeSetupSnapshot,
4 WorktreeSetupStage,
5 WorktreeSetupStageId,
6 WorktreeSetupStageStatus,
7} from "@t3tools/contracts";
8import {
9 WORKTREE_SETUP_DETAIL_MAX_LENGTH,
10 WORKTREE_SETUP_ERROR_MAX_LENGTH,
11 WORKTREE_SETUP_STAGE_ORDER,
12 WORKTREE_SETUP_TAIL_LINE_MAX_LENGTH,
13} from "@t3tools/contracts";
14import { splitsSurrogatePair } from "@t3tools/shared/assistantCitations";
15import * as Context from "effect/Context";
16import * as DateTime from "effect/DateTime";
17import * as Effect from "effect/Effect";
18import * as Fiber from "effect/Fiber";
19import * as Layer from "effect/Layer";
20import * as PubSub from "effect/PubSub";
21import * as Queue from "effect/Queue";
22import * as Ref from "effect/Ref";
23import * as Stream from "effect/Stream";
24​
25export class WorktreeSetupTracker extends Context.Service<
26 WorktreeSetupTracker,
27 {
28 readonly begin: (input: {
29 readonly threadId: ThreadId;
30 readonly branch: string | null;
31 readonly baseRef: string | null;
32 readonly stages: ReadonlyArray<WorktreeSetupStageId>;
33 readonly fiber: Fiber.Fiber<unknown, unknown> | null;
34 }) => Effect.Effect<void>;
35 readonly update: (
36 threadId: ThreadId,
37 mutate: (snapshot: WorktreeSetupSnapshot) => WorktreeSetupSnapshot,
38 ) => Effect.Effect<void>;
39 readonly stage: (
40 threadId: ThreadId,
41 stageId: WorktreeSetupStageId,
42 patch: Partial<Omit<WorktreeSetupStage, "id">>,
43 ) => Effect.Effect<void>;
44 readonly stageStatus: (
45 threadId: ThreadId,
46 stageId: WorktreeSetupStageId,
47 status: WorktreeSetupStageStatus,
48 detail?: string | null,
49 ) => Effect.Effect<void>;
50 readonly appendTail: (
51 threadId: ThreadId,
52 stageId: WorktreeSetupStageId,
53 line: string,
54 ) => Effect.Effect<void>;
55 readonly finish: (
56 threadId: ThreadId,
57 phase: "done" | "failed" | "cancelled",
58 error?: string | null,
59 ) => Effect.Effect<WorktreeSetupSnapshot | null>;
60 /** Call just before dispatch so late cancellation cannot roll back a started agent's thread. */
61 readonly markUncancellable: (threadId: ThreadId) => Effect.Effect<void>;
62 readonly cancel: (threadId: ThreadId) => Effect.Effect<boolean>;
63 /** Holds a newly allocated workspace through blocking preparation and any rollback. */
64 readonly holdWorkspace: (threadId: ThreadId) => Effect.Effect<Effect.Effect<void>>;
65 readonly workspaceIsHeld: (threadId: ThreadId) => Effect.Effect<boolean>;
66 readonly get: (threadId: ThreadId) => Effect.Effect<WorktreeSetupSnapshot | null>;
67 readonly stream: (threadId: ThreadId) => Stream.Stream<WorktreeSetupSnapshot | null>;
68 }
69>()("t3/project/WorktreeSetupTracker") {}
70​
71const TAIL_LINE_LIMIT = 4;
72​
73function clampText(text: string, maxLength: number): string {
74 if (text.length <= maxLength) return text;
75 const end = splitsSurrogatePair(text, maxLength - 1) ? maxLength - 2 : maxLength - 1;
76 return `${text.slice(0, end)}\u2026`;
78​
79const clampDetail = (detail: string | null): string | null =>
80 detail === null ? null : clampText(detail, WORKTREE_SETUP_DETAIL_MAX_LENGTH);
81const FINISHED_RETENTION = "30 seconds";
82​
83const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
84​
85interface TrackedSetup {
86 readonly snapshot: WorktreeSetupSnapshot;
87 readonly fiber: Fiber.Fiber<unknown, unknown> | null;
89​
90function emptyStage(id: WorktreeSetupStageId): WorktreeSetupStage {
91 return {
92 id,
93 status: "pending",
94 startedAt: null,
95 endedAt: null,
96 percent: null,
97 detail: null,
98 tail: [],
99 };
101​
102export const make = Effect.gen(function* () {
103 const setups = yield* Ref.make(new Map<ThreadId, TrackedSetup>());
104 const workspaceHolds = new Map<ThreadId, number>();
105 const changes = yield* PubSub.unbounded<{
106 readonly threadId: ThreadId;
107 readonly snapshot: WorktreeSetupSnapshot | null;
108 }>();
109 const retentionFibers = new Map<ThreadId, Fiber.Fiber<void, never>>();
110 // Keep sequences increasing across setups so existing subscribers accept the next setup's first snapshot.
111 const lastSequenceByThread = new Map<ThreadId, number>();
112​
113 const publish = (threadId: ThreadId, snapshot: WorktreeSetupSnapshot | null) =>
114 PubSub.publish(changes, { threadId, snapshot }).pipe(Effect.asVoid);
115​
116 const modify = (
117 threadId: ThreadId,
118 mutate: (tracked: TrackedSetup) => TrackedSetup,
119 ): Effect.Effect<WorktreeSetupSnapshot | null> =>
120 Ref.modify(setups, (current) => {
121 const existing = current.get(threadId);
122 if (!existing) return [null, current] as const;
123 const nextTracked = mutate(existing);
124 const nextSnapshot = {
125 ...nextTracked.snapshot,
126 sequence: existing.snapshot.sequence + 1,
127 };
128 lastSequenceByThread.set(threadId, nextSnapshot.sequence);
129 const next = new Map(current);
130 next.set(threadId, { ...nextTracked, snapshot: nextSnapshot });
131 return [nextSnapshot, next] as const;
132 }).pipe(Effect.tap((snapshot) => (snapshot ? publish(threadId, snapshot) : Effect.void)));
133​
134 const clearRetention = (threadId: ThreadId) => {
135 const fiber = retentionFibers.get(threadId);
136 retentionFibers.delete(threadId);
137 return fiber ? Fiber.interrupt(fiber).pipe(Effect.ignore) : Effect.void;
138 };
139​
140 const remove = (threadId: ThreadId) =>
141 Ref.update(setups, (current) => {
142 if (!current.has(threadId)) return current;
143 const next = new Map(current);
144 next.delete(threadId);
145 return next;
146 }).pipe(
147 Effect.andThen(publish(threadId, null)),
148 // After retention, subscribers see null and accept any sequence; the counter can reset.
149 Effect.tap(() => Effect.sync(() => lastSequenceByThread.delete(threadId))),
150 );
151​
152 const begin: WorktreeSetupTracker["Service"]["begin"] = Effect.fn("WorktreeSetupTracker.begin")(
153 function* (input) {
154 yield* clearRetention(input.threadId);
155 const startedAt = yield* nowIso;
156 const ordered = WORKTREE_SETUP_STAGE_ORDER.filter((id) => input.stages.includes(id));
157 const snapshot: WorktreeSetupSnapshot = {
158 threadId: input.threadId,
159 phase: "running",
160 startedAt,
161 endedAt: null,
162 branch: input.branch,
163 baseRef: input.baseRef,
164 worktreePath: null,
165 setupScript: null,
166 stages: ordered.map(emptyStage),
167 error: null,
168 sequence: (lastSequenceByThread.get(input.threadId) ?? -1) + 1,
169 };
170 lastSequenceByThread.set(input.threadId, snapshot.sequence);
171 yield* Ref.update(setups, (current) => {
172 const next = new Map(current);
173 next.set(input.threadId, { snapshot, fiber: input.fiber });
174 return next;
175 });
176 yield* publish(input.threadId, snapshot);
177 },
178 );
179​
180 const update: WorktreeSetupTracker["Service"]["update"] = (threadId, mutate) =>
181 modify(threadId, (tracked) => ({ ...tracked, snapshot: mutate(tracked.snapshot) })).pipe(
182 Effect.asVoid,
183 );
184​
185 const stage: WorktreeSetupTracker["Service"]["stage"] = (threadId, stageId, patch) =>
186 update(threadId, (snapshot) => ({
187 ...snapshot,
188 stages: snapshot.stages.map((entry) =>
189 entry.id === stageId
190 ? {
191 ...entry,
192 ...patch,
193 ...(patch.detail === undefined ? {} : { detail: clampDetail(patch.detail ?? null) }),
194 }
195 : entry,
196 ),
197 }));
198​
199 const stageStatus: WorktreeSetupTracker["Service"]["stageStatus"] = (
200 threadId,
201 stageId,
202 status,
203 detail,
204 ) =>
205 nowIso.pipe(
206 Effect.flatMap((at) =>
207 update(threadId, (snapshot) => ({
208 ...snapshot,
209 stages: snapshot.stages.map((entry) => {
210 if (entry.id !== stageId) return entry;
211 const startedAt = entry.startedAt ?? (status === "pending" ? null : at);
212 const endedAt =
213 status === "running" || status === "pending" ? null : (entry.endedAt ?? at);
214 return {
215 ...entry,
216 status,
217 startedAt,
218 endedAt,
219 ...(detail === undefined ? {} : { detail: clampDetail(detail ?? null) }),
220 };
221 }),
222 })),
223 ),
224 );
225​
226 const appendTail: WorktreeSetupTracker["Service"]["appendTail"] = (threadId, stageId, line) =>
227 update(threadId, (snapshot) => ({
228 ...snapshot,
229 stages: snapshot.stages.map((entry) =>
230 entry.id === stageId
231 ? {
232 ...entry,
233 tail: [...entry.tail, clampText(line, WORKTREE_SETUP_TAIL_LINE_MAX_LENGTH)].slice(
234 -TAIL_LINE_LIMIT,
235 ),
236 }
237 : entry,
238 ),
239 }));
240​
241 const finish: WorktreeSetupTracker["Service"]["finish"] = Effect.fn(
242 "WorktreeSetupTracker.finish",
243 )(function* (threadId, phase, error) {
244 const endedAt = yield* nowIso;
245 const snapshot = yield* modify(threadId, (tracked) => ({
246 fiber: null,
247 snapshot: {
248 ...tracked.snapshot,
249 phase,
250 endedAt,
251 error:
252 error === undefined || error === null
253 ? null
254 : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH),
255 stages: tracked.snapshot.stages.map((entry) =>
256 entry.status === "running"
257 ? {
258 ...entry,
259 status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",
260 endedAt,
261 }
262 : entry,
263 ),
264 },
265 }));
266 if (!snapshot) return null;
267 yield* clearRetention(threadId);
268 const fiber = yield* remove(threadId).pipe(
269 Effect.delay(FINISHED_RETENTION),
270 Effect.ensuring(
271 Effect.sync(() => {
272 if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);
273 }),
274 ),
275 Effect.forkDetach,
276 );
277 retentionFibers.set(threadId, fiber);
278 return snapshot;
279 });
280​
281 const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) =>
282 Ref.update(setups, (current) => {
283 const existing = current.get(threadId);
284 if (!existing || existing.fiber === null) return current;
285 const next = new Map(current);
286 next.set(threadId, { ...existing, fiber: null });
287 return next;
288 });
289​
290 const cancel: WorktreeSetupTracker["Service"]["cancel"] = Effect.fn(
291 "WorktreeSetupTracker.cancel",
292 )(function* (threadId) {
293 const current = yield* Ref.get(setups);
294 const tracked = current.get(threadId);
295 if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {
296 return false;
297 }
298 yield* Fiber.interrupt(tracked.fiber);
299 return true;
300 });
301​
302 const get: WorktreeSetupTracker["Service"]["get"] = (threadId) =>
303 Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null));
304​
305 const holdWorkspace = (threadId: ThreadId) =>
306 Effect.sync(() => {
307 workspaceHolds.set(threadId, (workspaceHolds.get(threadId) ?? 0) + 1);
308 let released = false;
309 return Effect.sync(() => {
310 if (released) return;
311 released = true;
312 const count = workspaceHolds.get(threadId) ?? 1;
313 if (count === 1) workspaceHolds.delete(threadId);
314 else workspaceHolds.set(threadId, count - 1);
315 });
316 });
317​
318 const workspaceIsHeld = (threadId: ThreadId) => Effect.sync(() => workspaceHolds.has(threadId));
319​
320 // One-slot sliding mailboxes bound slow WebSockets to the newest setup snapshot.
321 const stream: WorktreeSetupTracker["Service"]["stream"] = (threadId) =>
322 Stream.callback<WorktreeSetupSnapshot | null>(
323 (mailbox) =>
324 Effect.gen(function* () {
325 const subscription = yield* PubSub.subscribe(changes);
326 const initial = yield* get(threadId);
327 // The initial snapshot already includes queued changes; drop them to avoid stale replay.
328 let lastSequence = initial?.sequence ?? -1;
329 Queue.offerUnsafe(mailbox, initial);
330 yield* Stream.fromSubscription(subscription).pipe(
331 Stream.runForEach((change) =>
332 Effect.sync(() => {
333 if (change.threadId !== threadId) return;
334 if (change.snapshot !== null && change.snapshot.sequence <= lastSequence) return;
335 lastSequence = change.snapshot?.sequence ?? -1;
336 Queue.offerUnsafe(mailbox, change.snapshot);
337 }),
338 ),
339 Effect.forkScoped,
340 );
341 }),
342 { bufferSize: 1, strategy: "sliding" },
343 );
344​
345 return WorktreeSetupTracker.of({
346 begin,
347 update,
348 stage,
349 stageStatus,
350 appendTail,
351 finish,
352 markUncancellable,
353 cancel,
354 holdWorkspace,
355 workspaceIsHeld,
356 get,
357 stream,
358 });
359});
360​
361export const layer = Layer.effect(WorktreeSetupTracker, make);