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