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