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

WorktreeSetupTracker.ts

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