Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import type {
3 ApplicationStoredEvent,
4 OrchestrationV2ShellSnapshot,
5 OrchestrationV2ShellStreamItem,
6 OrchestrationV2ThreadShell,
7} from "@t3tools/contracts";
8import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
9import type * as Cause from "effect/Cause";
10import * as DateTime from "effect/DateTime";
11import * as Deferred from "effect/Deferred";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as PubSub from "effect/PubSub";
15import * as Queue from "effect/Queue";
16import * as Stream from "effect/Stream";
17import * as TestClock from "effect/testing/TestClock";
18
19import {
20 bufferShellLiveStream,
21 composeShellStreamWithEnrichment,
22 dedupeShellEnrichment,
23 shellStreamItemFromEnrichmentRefresh,
24 shellStreamItemsFromInitialSnapshot,
25 shouldPublishShellApplicationEvent,
26 skipUnchangedThreadShells,
27} from "./ShellStream.ts";
28
29const emptyShellSnapshot = {
30 schemaVersion: 1,
31 snapshotSequence: 0,
32 projects: [],
33 threads: [],
34 archivedThreads: [],
35} as OrchestrationV2ShellSnapshot;
36
37describe("subagent shell events", () => {
38 const stored = (threadId: string, type: string) =>
39 ({ event: { threadId, type } }) as ApplicationStoredEvent;
40
41 it("keeps regular threads and subagent state changes while omitting subagent transcript updates", () => {
42 const subagents = new Set(["child"]);
43 expect(
44 shouldPublishShellApplicationEvent(stored("parent", "turn-item.updated"), subagents),
45 ).toBe(true);
46 expect(
47 shouldPublishShellApplicationEvent(stored("child", "turn-item.updated"), subagents),
48 ).toBe(false);
49 expect(shouldPublishShellApplicationEvent(stored("child", "node.updated"), subagents)).toBe(
50 false,
51 );
52 expect(
53 shouldPublishShellApplicationEvent(stored("child", "runtime-request.updated"), subagents),
54 ).toBe(true);
55 expect(shouldPublishShellApplicationEvent(stored("child", "run.updated"), subagents)).toBe(
56 true,
57 );
58 });
59
60 it("tracks subagents created after the subscription starts", () => {
61 const subagents = new Set<string>();
62 const created = {
63 event: {
64 threadId: "new-child",
65 type: "thread.created",
66 payload: { lineage: { relationshipToParent: "subagent" } },
67 },
68 } as ApplicationStoredEvent;
69 expect(shouldPublishShellApplicationEvent(created, subagents)).toBe(true);
70 expect(
71 shouldPublishShellApplicationEvent(stored("new-child", "message.updated"), subagents),
72 ).toBe(false);
73 expect(
74 shouldPublishShellApplicationEvent(stored("new-child", "thread.deleted"), subagents),
75 ).toBe(true);
76 expect(subagents.has("new-child")).toBe(true);
77 });
78});
79
80it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () =>
81 Effect.scoped(
82 Effect.gen(function* () {
83 const input = yield* Queue.unbounded<
84 Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>,
85 Cause.Done
86 >();
87 const drained = yield* Deferred.make<void>();
88 const shell = shellFixture({ id: ThreadId.make("same"), title: "Before" });
89 const project = {
90 id: ProjectId.make("same"),
91 title: "Before",
92 workspaceRoot: "/workspace/same",
93 repositoryIdentity: null,
94 defaultModelSelection: null,
95 scripts: [],
96 createdAt: "2026-09-01T00:00:00Z",
97 updatedAt: "2026-09-01T00:00:00Z",
98 };
99 const initial = {
100 kind: "thread.updated" as const,
101 sequence: 1,
102 location: "active" as const,
103 thread: shell,
104 };
105 const updates = [
106 { kind: "project.updated", sequence: 2, project },
107 { ...initial, sequence: 3 },
108 { ...initial, sequence: 4, location: "archive" },
109 { ...initial, sequence: 5, thread: { ...shell, id: ThreadId.make("other") } },
110 {
111 kind: "project.updated",
112 sequence: 6,
113 project: { ...project, id: ProjectId.make("other") },
114 },
115 { kind: "project.removed", sequence: 7, projectId: project.id },
116 { kind: "thread.removed", sequence: 8, location: "active", threadId: shell.id },
117 { kind: "project.updated", sequence: 9, project: { ...project, title: "Recreated" } },
118 { ...initial, sequence: 10, thread: { ...shell, title: "Recreated" } },
119 { kind: "thread.removed", sequence: 11, location: "archive", threadId: shell.id },
120 ] satisfies Array<Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>>;
121 const pull = yield* Stream.toPull(
122 bufferShellLiveStream(
123 Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(drained, undefined))),
124 { maxItems: 6, maxSerializedBytes: 1_500 },
125 ),
126 );
127 yield* Queue.offer(input, initial);
128 expect(yield* pull).toEqual([initial]);
129 yield* Queue.offerAll(input, updates);
130 yield* Queue.end(input);
131 // Finish producing the burst while the first batch is still awaiting its ACK.
132 yield* Deferred.await(drained);
133 expect(yield* pull).toEqual([updates[3], updates[4], updates[7], updates[8], updates[9]]);
134 }),
135 ),
136);
137
138function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): OrchestrationV2ThreadShell {
139 return { id: "thread-a", archivedAt: null, ...overrides } as OrchestrationV2ThreadShell;
140}
141
142describe("shellStreamItemsFromInitialSnapshot", () => {
143 it("keeps thread rows out of the metadata-only enrichment frame", () => {
144 const snapshot = {
145 ...emptyShellSnapshot,
146 projects: [
147 { id: "project-a", workspaceRoot: "/workspace/a" },
148 { id: "project-b", workspaceRoot: "/workspace/b" },
149 ],
150 threads: [shellFixture({})],
151 archivedThreads: [shellFixture({ id: ThreadId.make("thread-archived"), archivedAt: null })],
152 } as unknown as OrchestrationV2ShellSnapshot;
153
154 const items = shellStreamItemsFromInitialSnapshot({
155 snapshot,
156 resolvedRepositoryIdentityRoots: ["/workspace/a"],
157 });
158
159 expect(items[0]).toEqual({ kind: "snapshot", snapshot });
160 expect(items[1]).toMatchObject({
161 kind: "snapshot",
162 snapshot: {
163 projects: [{ id: "project-a", workspaceRoot: "/workspace/a" }],
164 threads: [],
165 archivedThreads: [],
166 },
167 resolvedRepositoryIdentityRoots: ["/workspace/a"],
168 });
169 expect(JSON.stringify(items[1]).length).toBeLessThan(JSON.stringify(items[0]).length);
170 });
171});
172
173describe("composeShellStreamWithEnrichment", () => {
174 it.effect("preserves pending repository resolutions while an enrichment ACK is withheld", () =>
175 Effect.scoped(
176 Effect.gen(function* () {
177 // Match ProjectEnrichmentService's sliding notifications and the WS batching path.
178 const changes = yield* Effect.acquireRelease(
179 PubSub.sliding<{ readonly workspaceRoot: string }>(256),
180 PubSub.shutdown,
181 );
182 const subscription = yield* PubSub.subscribe(changes);
183 const pull = yield* Stream.toPull(
184 composeShellStreamWithEnrichment({
185 initial: Stream.empty,
186 tail: Stream.empty,
187 enrichment: Stream.fromSubscription(subscription).pipe(
188 Stream.groupedWithin(64, Duration.millis(25)),
189 Stream.map((changes) =>
190 shellStreamItemFromEnrichmentRefresh({
191 snapshot: emptyShellSnapshot,
192 changes,
193 }),
194 ),
195 ),
196 }),
197 );
198
199 const firstRoots = Array.from({ length: 64 }, (_, index) => `/workspace/first-${index}`);
200 yield* PubSub.publishAll(
201 changes,
202 firstRoots.map((workspaceRoot) => ({ workspaceRoot })),
203 );
204 expect(yield* pull).toMatchObject([{ resolvedRepositoryIdentityRoots: firstRoots }]);
205
206 // The next completion can be batched before the client acknowledges the first.
207 yield* PubSub.publish(changes, { workspaceRoot: "/workspace/pending" });
208 yield* Effect.yieldNow;
209 yield* TestClock.adjust(Duration.millis(25));
210 const laterRoots = Array.from({ length: 256 }, (_, index) => `/workspace/later-${index}`);
211 yield* PubSub.publishAll(
212 changes,
213 laterRoots.map((workspaceRoot) => ({ workspaceRoot })),
214 );
215
216 const resumed = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
217 Stream.takeUntil(
218 (item) =>
219 item.resolvedRepositoryIdentityRoots?.includes("/workspace/later-255") ?? false,
220 ),
221 Stream.runCollect,
222 );
223 expect(resumed.flatMap((item) => item.resolvedRepositoryIdentityRoots ?? [])).toEqual([
224 "/workspace/pending",
225 ...laterRoots,
226 ]);
227 }),
228 ),
229 );
230
231 it.effect("keeps a merged shell batch charged while the client withholds its ACK", () =>
232 Effect.scoped(
233 Effect.gen(function* () {
234 const update = yield* Deferred.make<void>();
235 const closed = yield* Deferred.make<void>();
236 const initial = {
237 kind: "thread.removed" as const,
238 sequence: 1,
239 location: "active" as const,
240 threadId: ThreadId.make("thread-a"),
241 };
242 const pull = yield* Stream.toPull(
243 composeShellStreamWithEnrichment({
244 initial: Stream.empty,
245 tail: bufferShellLiveStream(
246 Stream.concat(
247 Stream.succeed(initial),
248 Stream.fromEffect(Deferred.await(update)).pipe(
249 Stream.map(() => ({ ...initial, sequence: 2 })),
250 ),
251 ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
252 { maxItems: 1 },
253 ),
254 enrichment: Stream.empty,
255 }),
256 );
257 expect(yield* pull).toEqual([initial]);
258 // Let the merge producer run while the client still withholds its ACK.
259 yield* Effect.yieldNow;
260 yield* Deferred.succeed(update, undefined);
261 yield* Deferred.await(closed);
262 const result = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
263 Stream.runDrain,
264 Effect.result,
265 );
266 expect(result._tag).toBe("Failure");
267 if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
268 }),
269 ),
270 );
271
272 it.effect(
273 "emits every initial item before enrichment even when enrichment is already ready",
274 () =>
275 Effect.gen(function* () {
276 const initialSnapshot = {
277 ...emptyShellSnapshot,
278 snapshotSequence: 5,
279 } as OrchestrationV2ShellSnapshot;
280 const enrichmentSnapshot = {
281 ...emptyShellSnapshot,
282 snapshotSequence: 10,
283 } as OrchestrationV2ShellSnapshot;
284
285 const initialItems = shellStreamItemsFromInitialSnapshot({
286 snapshot: initialSnapshot,
287 resolvedRepositoryIdentityRoots: ["/workspace/a"],
288 });
289 const enrichment = Stream.make(
290 shellStreamItemFromEnrichmentRefresh({
291 snapshot: enrichmentSnapshot,
292 changes: [{ workspaceRoot: "/workspace/b" }],
293 }),
294 );
295 const tail = Stream.make(
296 { kind: "synchronized" as const },
297 {
298 kind: "project.removed" as const,
299 sequence: 6,
300 projectId: "project-a",
301 },
302 );
303
304 const items = Array.from(
305 yield* composeShellStreamWithEnrichment({
306 initial: Stream.fromIterable(initialItems),
307 tail,
308 enrichment,
309 }).pipe(Stream.runCollect),
310 );
311
312 expect(items.slice(0, initialItems.length)).toEqual(initialItems);
313
314 const enrichmentIndex = items.findIndex(
315 (item) =>
316 item.kind === "snapshot" &&
317 "resolvedRepositoryIdentityRoots" in item &&
318 item.resolvedRepositoryIdentityRoots?.includes("/workspace/b"),
319 );
320 expect(enrichmentIndex).toBeGreaterThanOrEqual(initialItems.length);
321
322 for (let index = 0; index < initialItems.length; index++) {
323 expect(items[index]).toEqual(initialItems[index]);
324 }
325 }),
326 );
327});
328
329describe("dedupeShellEnrichment", () => {
330 const project = {
331 id: ProjectId.make("project-a"),
332 title: "A project",
333 workspaceRoot: "/workspace/a",
334 repositoryIdentity: null,
335 defaultModelSelection: null,
336 scripts: [],
337 createdAt: "2026-09-01T00:00:00Z",
338 updatedAt: "2026-09-01T00:00:00Z",
339 };
340 const initial = {
341 kind: "snapshot" as const,
342 snapshot: { ...emptyShellSnapshot, projects: [project] },
343 };
344 const marked = { ...initial, resolvedRepositoryIdentityRoots: [project.workspaceRoot] };
345
346 it.effect(
347 "keeps initial/resume resolution and real changes but drops sequence-only repeats",
348 () =>
349 Effect.gen(function* () {
350 const repeated = {
351 ...marked,
352 snapshot: { ...marked.snapshot, snapshotSequence: 10, projects: [{ ...project }] },
353 };
354 const progressed = {
355 ...repeated,
356 resolvedRepositoryIdentityRoots: [project.workspaceRoot, "/workspace/b"],
357 };
358 const changed = {
359 ...progressed,
360 snapshot: { ...progressed.snapshot, projects: [{ ...project, title: "Renamed" }] },
361 };
362 const items = yield* Stream.make(
363 initial,
364 marked,
365 repeated,
366 progressed,
367 changed,
368 changed,
369 ).pipe(dedupeShellEnrichment, Stream.runCollect);
370 expect(items).toEqual([initial, marked, progressed, changed]);
371 const resumed = Stream.make(marked, repeated).pipe(dedupeShellEnrichment);
372 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
373 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
374 }),
375 );
376
377 it.effect("keeps authoritative snapshots and invalidates metadata after project deltas", () =>
378 Effect.gen(function* () {
379 const removed = { kind: "project.removed" as const, projectId: project.id, sequence: 2 };
380 const updated = { kind: "project.updated" as const, project, sequence: 3 };
381 const withThreads = {
382 ...marked,
383 snapshot: { ...marked.snapshot, threads: [shellFixture({})] },
384 };
385 const values = [
386 initial,
387 initial,
388 marked,
389 removed,
390 marked,
391 updated,
392 marked,
393 withThreads,
394 withThreads,
395 ];
396 expect(
397 yield* Stream.fromIterable(values).pipe(dedupeShellEnrichment, Stream.runCollect),
398 ).toEqual(values);
399 }),
400 );
401
402 it.effect(
403 "deduplicates across thread deltas without dropping those deltas or identity clears",
404 () =>
405 Effect.gen(function* () {
406 const delta = {
407 kind: "thread.removed" as const,
408 threadId: ThreadId.make("thread-a"),
409 location: "active" as const,
410 sequence: 2,
411 };
412 const resolved = {
413 ...marked,
414 snapshot: {
415 ...marked.snapshot,
416 projects: [
417 {
418 ...project,
419 repositoryIdentity: {
420 canonicalKey: "github.com/test/repo",
421 locator: {
422 source: "git-remote" as const,
423 remoteName: "origin",
424 remoteUrl: "https://github.com/test/repo.git",
425 },
426 },
427 },
428 ],
429 },
430 };
431 expect(
432 yield* Stream.make(marked, delta, marked, resolved, marked).pipe(
433 dedupeShellEnrichment,
434 Stream.runCollect,
435 ),
436 ).toEqual([marked, delta, resolved, marked]);
437 }),
438 );
439});
440
441describe("skipUnchangedThreadShells", () => {
442 const at = (ms: number) => DateTime.makeUnsafe(Date.parse("2026-10-01T00:00:00.000Z") + ms);
443 const shell = (
444 id: string,
445 overrides: Partial<OrchestrationV2ThreadShell> = {},
446 ): OrchestrationV2ThreadShell => ({
447 id: ThreadId.make(id),
448 projectId: ProjectId.make("project-a"),
449 title: "Thread",
450 providerInstanceId: ProviderInstanceId.make("codex"),
451 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
452 runtimeMode: "full-access",
453 interactionMode: "default",
454 worktreePath: null,
455 activeProviderThreadId: null,
456 lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
457 forkedFrom: null,
458 createdBy: "user",
459 creationSource: "web",
460 activeRunId: null,
461 latestVisibleMessage: null,
462 hasActionableProposedPlan: false,
463 itemCount: 1,
464 visibleItemCount: 1,
465 branch: null,
466 status: "running",
467 pendingRuntimeRequest: null,
468 pendingBackgroundTasks: [],
469 latestRunId: null,
470 latestUserMessageAt: null,
471 createdAt: at(0),
472 updatedAt: at(0),
473 archivedAt: null,
474 settledOverride: null,
475 settledAt: null,
476 deletedAt: null,
477 ...overrides,
478 });
479 type Step =
480 | { readonly advanceMs: number }
481 | Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" | "synchronized" }>;
482 const updated = (sequence: number, thread: OrchestrationV2ThreadShell): Step => ({
483 kind: "thread.updated",
484 sequence,
485 location: "active",
486 thread,
487 });
488 const run = (steps: ReadonlyArray<Step>) =>
489 Stream.fromIterable(steps).pipe(
490 Stream.mapEffect((step) =>
491 "advanceMs" in step
492 ? TestClock.adjust(Duration.millis(step.advanceMs)).pipe(Effect.as(null))
493 : Effect.succeed(step),
494 ),
495 Stream.filter((item) => item !== null),
496 skipUnchangedThreadShells,
497 Stream.runCollect,
498 Effect.map((items) => Array.from(items, (item) => ("sequence" in item ? item.sequence : -1))),
499 );
500
501 it.effect("sends the next update after a removal", () =>
502 Effect.gen(function* () {
503 const sent = yield* run([
504 updated(1, shell("a")),
505 { kind: "thread.removed", sequence: 2, location: "active", threadId: ThreadId.make("a") },
506 updated(3, shell("a")),
507 ]);
508 expect(sent).toEqual([1, 2, 3]);
509 }),
510 );
511});