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

ShellStream.test.ts

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