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

ShellStream.test.ts

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