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

WorktreeSetupTracker.ts

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