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