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

ShellStream.test.ts

576 lines19.8 KB

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