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 * as Context from "effect/Context";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Fiber from "effect/Fiber";
18import * as Layer from "effect/Layer";
19import * as PubSub from "effect/PubSub";
20import * as Queue from "effect/Queue";
21import * as Ref from "effect/Ref";
22import * as Stream from "effect/Stream";
23
24/**
25 * Tracks the live stages of a bootstrap worktree setup per thread so clients
26 * can render a progress card while the first turn is still being prepared.
27 *
28 * State is memory only. It exists from the first `begin` until the turn starts
29 * or the setup fails, plus a short grace window so a client that subscribes
30 * late still sees the final state. Nothing here is persisted or event-sourced:
31 * the durable record of a setup is the thread's worktree path and the setup
32 * script activities, both of which already exist.
33 */
34export class WorktreeSetupTracker extends Context.Service<
35 WorktreeSetupTracker,
36 {
37 /** Creates a fresh running snapshot for the thread, replacing any prior one. */
38 readonly begin: (input: {
39 readonly threadId: ThreadId;
40 readonly branch: string | null;
41 readonly baseRef: string | null;
42 readonly stages: ReadonlyArray<WorktreeSetupStageId>;
43 /** Interrupting this fiber cancels the bootstrap. */
44 readonly fiber: Fiber.Fiber<unknown, unknown> | null;
45 }) => Effect.Effect<void>;
46 readonly update: (
47 threadId: ThreadId,
48 mutate: (snapshot: WorktreeSetupSnapshot) => WorktreeSetupSnapshot,
49 ) => Effect.Effect<void>;
50 readonly stage: (
51 threadId: ThreadId,
52 stageId: WorktreeSetupStageId,
53 patch: Partial<Omit<WorktreeSetupStage, "id">>,
54 ) => Effect.Effect<void>;
55 readonly stageStatus: (
56 threadId: ThreadId,
57 stageId: WorktreeSetupStageId,
58 status: WorktreeSetupStageStatus,
59 detail?: string | null,
60 ) => Effect.Effect<void>;
61 readonly appendTail: (
62 threadId: ThreadId,
63 stageId: WorktreeSetupStageId,
64 line: string,
65 ) => Effect.Effect<void>;
66 readonly finish: (
67 threadId: ThreadId,
68 phase: "done" | "failed" | "cancelled",
69 error?: string | null,
70 ) => Effect.Effect<void>;
71 /**
72 * Drops the cancel handle. Called right before the turn is dispatched so a
73 * late cancel cannot roll back a thread whose agent has already started.
74 */
75 readonly markUncancellable: (threadId: ThreadId) => Effect.Effect<void>;
76 /**
77 * Interrupts the running bootstrap and waits for it to unwind, so the
78 * caller's dispatch has already failed and rolled back when this returns.
79 * Returns false when nothing is running or the setup is past cancellation.
80 */
81 readonly cancel: (threadId: ThreadId) => Effect.Effect<boolean>;
82 readonly get: (threadId: ThreadId) => Effect.Effect<WorktreeSetupSnapshot | null>;
83 /** Emits the current snapshot (or null) first, then every change until unsubscribed. */
84 readonly stream: (threadId: ThreadId) => Stream.Stream<WorktreeSetupSnapshot | null>;
85 }
86>()("t3/project/WorktreeSetupTracker") {}
87
88const TAIL_LINE_LIMIT = 4;
89
90/** Keeps free text inside the contract limit, ending in an ellipsis when cut. */
91function clampText(text: string, maxLength: number): string {
92 return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1)}\u2026`;
93}
94
95const clampDetail = (detail: string | null): string | null =>
96 detail === null ? null : clampText(detail, WORKTREE_SETUP_DETAIL_MAX_LENGTH);
97/** Finished snapshots stay visible this long so a late subscriber sees the outcome. */
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;
105}
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 };
117}
118
119export const make = Effect.gen(function* () {
120 const setups = yield* Ref.make(new Map<ThreadId, TrackedSetup>());
121 const changes = yield* PubSub.unbounded<{
122 readonly threadId: ThreadId;
123 readonly snapshot: WorktreeSetupSnapshot | null;
124 }>();
125 const retentionFibers = new Map<ThreadId, Fiber.Fiber<void, never>>();
126 // Sequences keep increasing across setups of the same thread so a stream
127 // opened during a previous setup still accepts the next one's first snapshot.
128 const lastSequenceByThread = new Map<ThreadId, number>();
129
130 const publish = (threadId: ThreadId, snapshot: WorktreeSetupSnapshot | null) =>
131 PubSub.publish(changes, { threadId, snapshot }).pipe(Effect.asVoid);
132
133 const modify = (
134 threadId: ThreadId,
135 mutate: (tracked: TrackedSetup) => TrackedSetup,
136 ): Effect.Effect<WorktreeSetupSnapshot | null> =>
137 Ref.modify(setups, (current) => {
138 const existing = current.get(threadId);
139 if (!existing) return [null, current] as const;
140 const nextTracked = mutate(existing);
141 const nextSnapshot = {
142 ...nextTracked.snapshot,
143 sequence: existing.snapshot.sequence + 1,
144 };
145 lastSequenceByThread.set(threadId, nextSnapshot.sequence);
146 const next = new Map(current);
147 next.set(threadId, { ...nextTracked, snapshot: nextSnapshot });
148 return [nextSnapshot, next] as const;
149 }).pipe(Effect.tap((snapshot) => (snapshot ? publish(threadId, snapshot) : Effect.void)));
150
151 const clearRetention = (threadId: ThreadId) => {
152 const fiber = retentionFibers.get(threadId);
153 retentionFibers.delete(threadId);
154 return fiber ? Fiber.interrupt(fiber).pipe(Effect.ignore) : Effect.void;
155 };
156
157 const remove = (threadId: ThreadId) =>
158 Ref.update(setups, (current) => {
159 if (!current.has(threadId)) return current;
160 const next = new Map(current);
161 next.delete(threadId);
162 return next;
163 }).pipe(
164 Effect.andThen(publish(threadId, null)),
165 // A subscriber that outlives retention sees `null` here and accepts any
166 // sequence after it, so the counter can start over for this thread.
167 Effect.tap(() => Effect.sync(() => lastSequenceByThread.delete(threadId))),
168 );
169
170 const begin: WorktreeSetupTracker["Service"]["begin"] = (input) =>
171 Effect.gen(function* () {
172 yield* clearRetention(input.threadId);
173 const startedAt = yield* nowIso;
174 const ordered = WORKTREE_SETUP_STAGE_ORDER.filter((id) => input.stages.includes(id));
175 const snapshot: WorktreeSetupSnapshot = {
176 threadId: input.threadId,
177 phase: "running",
178 startedAt,
179 endedAt: null,
180 branch: input.branch,
181 baseRef: input.baseRef,
182 worktreePath: null,
183 setupScript: null,
184 stages: ordered.map(emptyStage),
185 error: null,
186 sequence: (lastSequenceByThread.get(input.threadId) ?? -1) + 1,
187 };
188 lastSequenceByThread.set(input.threadId, snapshot.sequence);
189 yield* Ref.update(setups, (current) => {
190 const next = new Map(current);
191 next.set(input.threadId, { snapshot, fiber: input.fiber });
192 return next;
193 });
194 yield* publish(input.threadId, snapshot);
195 });
196
197 const update: WorktreeSetupTracker["Service"]["update"] = (threadId, mutate) =>
198 modify(threadId, (tracked) => ({ ...tracked, snapshot: mutate(tracked.snapshot) })).pipe(
199 Effect.asVoid,
200 );
201
202 const stage: WorktreeSetupTracker["Service"]["stage"] = (threadId, stageId, patch) =>
203 update(threadId, (snapshot) => ({
204 ...snapshot,
205 stages: snapshot.stages.map((entry) =>
206 entry.id === stageId
207 ? {
208 ...entry,
209 ...patch,
210 ...(patch.detail === undefined ? {} : { detail: clampDetail(patch.detail ?? null) }),
211 }
212 : entry,
213 ),
214 }));
215
216 const stageStatus: WorktreeSetupTracker["Service"]["stageStatus"] = (
217 threadId,
218 stageId,
219 status,
220 detail,
221 ) =>
222 nowIso.pipe(
223 Effect.flatMap((at) =>
224 update(threadId, (snapshot) => ({
225 ...snapshot,
226 stages: snapshot.stages.map((entry) => {
227 if (entry.id !== stageId) return entry;
228 const startedAt = entry.startedAt ?? (status === "pending" ? null : at);
229 const endedAt =
230 status === "running" || status === "pending" ? null : (entry.endedAt ?? at);
231 return {
232 ...entry,
233 status,
234 startedAt,
235 endedAt,
236 ...(detail === undefined ? {} : { detail: clampDetail(detail ?? null) }),
237 };
238 }),
239 })),
240 ),
241 );
242
243 const appendTail: WorktreeSetupTracker["Service"]["appendTail"] = (threadId, stageId, line) =>
244 update(threadId, (snapshot) => ({
245 ...snapshot,
246 stages: snapshot.stages.map((entry) =>
247 entry.id === stageId
248 ? {
249 ...entry,
250 tail: [...entry.tail, clampText(line, WORKTREE_SETUP_TAIL_LINE_MAX_LENGTH)].slice(
251 -TAIL_LINE_LIMIT,
252 ),
253 }
254 : entry,
255 ),
256 }));
257
258 const finish: WorktreeSetupTracker["Service"]["finish"] = (threadId, phase, error) =>
259 Effect.gen(function* () {
260 const endedAt = yield* nowIso;
261 const snapshot = yield* modify(threadId, (tracked) => ({
262 fiber: null,
263 snapshot: {
264 ...tracked.snapshot,
265 phase,
266 endedAt,
267 error:
268 error === undefined || error === null
269 ? null
270 : clampText(error, WORKTREE_SETUP_ERROR_MAX_LENGTH),
271 stages: tracked.snapshot.stages.map((entry) =>
272 entry.status === "running"
273 ? {
274 ...entry,
275 status: phase === "done" ? "done" : phase === "cancelled" ? "skipped" : "failed",
276 endedAt,
277 }
278 : entry,
279 ),
280 },
281 }));
282 if (!snapshot) return;
283 yield* clearRetention(threadId);
284 const fiber = yield* remove(threadId).pipe(
285 Effect.delay(FINISHED_RETENTION),
286 Effect.ensuring(
287 Effect.sync(() => {
288 // Only drop our own entry: a newer setup may have replaced it.
289 if (retentionFibers.get(threadId) === fiber) retentionFibers.delete(threadId);
290 }),
291 ),
292 Effect.forkDetach,
293 );
294 retentionFibers.set(threadId, fiber);
295 });
296
297 const markUncancellable: WorktreeSetupTracker["Service"]["markUncancellable"] = (threadId) =>
298 Ref.update(setups, (current) => {
299 const existing = current.get(threadId);
300 if (!existing || existing.fiber === null) return current;
301 const next = new Map(current);
302 next.set(threadId, { ...existing, fiber: null });
303 return next;
304 });
305
306 const cancel: WorktreeSetupTracker["Service"]["cancel"] = (threadId) =>
307 Effect.gen(function* () {
308 const current = yield* Ref.get(setups);
309 const tracked = current.get(threadId);
310 if (!tracked || tracked.snapshot.phase !== "running" || !tracked.fiber) {
311 return false;
312 }
313 yield* Fiber.interrupt(tracked.fiber);
314 return true;
315 });
316
317 const get: WorktreeSetupTracker["Service"]["get"] = (threadId) =>
318 Ref.get(setups).pipe(Effect.map((current) => current.get(threadId)?.snapshot ?? null));
319
320 /**
321 * Each subscriber gets a one-slot sliding mailbox: a slow WebSocket only
322 * ever holds the newest snapshot, so a chatty setup script cannot grow the
323 * server heap. Snapshots are whole states, so skipping intermediates is safe.
324 */
325 const stream: WorktreeSetupTracker["Service"]["stream"] = (threadId) =>
326 Stream.callback<WorktreeSetupSnapshot | null>(
327 (mailbox) =>
328 Effect.gen(function* () {
329 const subscription = yield* PubSub.subscribe(changes);
330 const initial = yield* get(threadId);
331 // Changes published between subscribing and reading `initial` are
332 // already folded into it. Drop them so the client never steps back.
333 let lastSequence = initial?.sequence ?? -1;
334 Queue.offerUnsafe(mailbox, initial);
335 yield* Stream.fromSubscription(subscription).pipe(
336 Stream.runForEach((change) =>
337 Effect.sync(() => {
338 if (change.threadId !== threadId) return;
339 if (change.snapshot !== null && change.snapshot.sequence <= lastSequence) return;
340 lastSequence = change.snapshot?.sequence ?? -1;
341 Queue.offerUnsafe(mailbox, change.snapshot);
342 }),
343 ),
344 Effect.forkScoped,
345 );
346 }),
347 { bufferSize: 1, strategy: "sliding" },
348 );
349
350 return WorktreeSetupTracker.of({
351 begin,
352 update,
353 stage,
354 stageStatus,
355 appendTail,
356 finish,
357 markUncancellable,
358 cancel,
359 get,
360 stream,
361 });
362});
363
364export const layer = Layer.effect(WorktreeSetupTracker, make);