Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import type {
3 ApplicationStoredEvent,
4 OrchestrationV2ShellSnapshot,
5 OrchestrationV2ShellStreamItem,
6 OrchestrationV2StoredEvent,
7 OrchestrationV2ThreadShell,
8} from "@t3tools/contracts";
9import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
10import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient";
11import type * as Cause from "effect/Cause";
12import * as DateTime from "effect/DateTime";
13import * as Deferred from "effect/Deferred";
14import * as Duration from "effect/Duration";
15import * as Effect from "effect/Effect";
16import * as Option from "effect/Option";
17import * as PubSub from "effect/PubSub";
18import * as Queue from "effect/Queue";
19import * as SqlClient from "effect/sql/SqlClient";
20import * as Stream from "effect/Stream";
21import * as TestClock from "effect/testing/TestClock";
22
23import {
24 archivedShellStreamItemFromThreadShell,
25 buildActiveShellSnapshot,
26 bufferShellLiveStream,
27 coalesceShellApplicationEvents,
28 coalesceStoredThreadEvents,
29 composeShellStreamWithEnrichment,
30 dedupeShellEnrichment,
31 loadShellSnapshotParts,
32 shellStreamItemFromEnrichmentRefresh,
33 shellStreamItemFromThreadShell,
34 shellStreamItemsFromInitialSnapshot,
35 shellStreamItemsFromResumeSnapshot,
36 skipUnchangedThreadShells,
37} from "./ShellStream.ts";
38
39function project(sequence: number, id: string): ApplicationStoredEvent {
40 return {
41 sequence,
42 aggregateKind: "project",
43 aggregateId: id,
44 } as ApplicationStoredEvent;
45}
46
47function thread(sequence: number, id: string): ApplicationStoredEvent {
48 return {
49 sequence,
50 event: { threadId: id },
51 } as ApplicationStoredEvent;
52}
53
54const emptyShellSnapshot = {
55 schemaVersion: 1,
56 snapshotSequence: 0,
57 projects: [],
58 threads: [],
59 archivedThreads: [],
60} as OrchestrationV2ShellSnapshot;
61
62it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () =>
63 Effect.scoped(
64 Effect.gen(function* () {
65 const input = yield* Queue.unbounded<
66 Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>,
67 Cause.Done
68 >();
69 const drained = yield* Deferred.make<void>();
70 const shell = shellFixture({ id: ThreadId.make("same"), title: "Before" });
71 const project = {
72 id: ProjectId.make("same"),
73 title: "Before",
74 workspaceRoot: "/workspace/same",
75 repositoryIdentity: null,
76 defaultModelSelection: null,
77 scripts: [],
78 createdAt: "2026-09-01T00:00:00Z",
79 updatedAt: "2026-09-01T00:00:00Z",
80 };
81 const initial = {
82 kind: "thread.updated" as const,
83 sequence: 1,
84 location: "active" as const,
85 thread: shell,
86 };
87 const updates = [
88 { kind: "project.updated", sequence: 2, project },
89 { ...initial, sequence: 3 },
90 { ...initial, sequence: 4, location: "archive" },
91 { ...initial, sequence: 5, thread: { ...shell, id: ThreadId.make("other") } },
92 {
93 kind: "project.updated",
94 sequence: 6,
95 project: { ...project, id: ProjectId.make("other") },
96 },
97 { kind: "project.removed", sequence: 7, projectId: project.id },
98 { kind: "thread.removed", sequence: 8, location: "active", threadId: shell.id },
99 { kind: "project.updated", sequence: 9, project: { ...project, title: "Recreated" } },
100 { ...initial, sequence: 10, thread: { ...shell, title: "Recreated" } },
101 { kind: "thread.removed", sequence: 11, location: "archive", threadId: shell.id },
102 ] satisfies Array<Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>>;
103 const pull = yield* Stream.toPull(
104 bufferShellLiveStream(
105 Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(drained, undefined))),
106 { maxItems: 6, maxSerializedBytes: 1_500 },
107 ),
108 );
109 yield* Queue.offer(input, initial);
110 expect(yield* pull).toEqual([initial]);
111 yield* Queue.offerAll(input, updates);
112 yield* Queue.end(input);
113 // Finish producing the burst while the first batch is still awaiting its ACK.
114 yield* Deferred.await(drained);
115 expect(yield* pull).toEqual([updates[3], updates[4], updates[7], updates[8], updates[9]]);
116 }),
117 ),
118);
119
120describe("buildActiveShellSnapshot", () => {
121 it("never duplicates archived rows into the regular shell", () => {
122 const active = shellFixture({ archivedAt: null });
123 const archived = shellFixture({
124 id: ThreadId.make("thread-archived"),
125 archivedAt: "2026-07-30T00:00:00.000Z" as never,
126 });
127
128 expect(
129 buildActiveShellSnapshot({
130 projects: [],
131 threads: {
132 schemaVersion: 1,
133 snapshotSequence: 4,
134 threads: [active],
135 archivedThreads: [archived],
136 },
137 snapshotSequence: 7,
138 }),
139 ).toEqual({
140 schemaVersion: 1,
141 snapshotSequence: 7,
142 projects: [],
143 threads: [active],
144 archivedThreads: [],
145 });
146 });
147});
148
149describe("coalesceShellApplicationEvents", () => {
150 it("keeps the newest event per aggregate and preserves sequence order", () => {
151 expect(
152 coalesceShellApplicationEvents([
153 thread(2, "thread-a"),
154 project(3, "project-a"),
155 thread(4, "thread-b"),
156 thread(5, "thread-a"),
157 project(6, "project-a"),
158 ]).map((event) => event.sequence),
159 ).toEqual([4, 5, 6]);
160 });
161});
162
163function storedThreadEvent(
164 sequence: number,
165 threadId: string,
166 event: Record<string, unknown> = {},
167): OrchestrationV2StoredEvent {
168 return { sequence, event: { threadId, ...event } } as OrchestrationV2StoredEvent;
169}
170
171describe("loadShellSnapshotParts", () => {
172 it.effect("decodes the threads after the read transaction releases the connection", () =>
173 Effect.gen(function* () {
174 const sql = yield* SqlClient.SqlClient;
175 const steps: Array<string> = [];
176 const step = <A>(name: string, value: A) =>
177 Effect.serviceOption(sql.transactionService).pipe(
178 Effect.map((transaction) => {
179 steps.push(`${name}:${Option.isSome(transaction) ? "in" : "out of"} transaction`);
180 return value;
181 }),
182 );
183 const thread = shellFixture({});
184
185 const snapshot = yield* loadShellSnapshotParts({
186 sql,
187 readThreads: step(
188 "read threads",
189 step("decode threads", {
190 schemaVersion: 1,
191 snapshotSequence: 3,
192 threads: [thread],
193 archivedThreads: [],
194 }),
195 ),
196 listProjects: step("list projects", []),
197 latestSequence: step("latest sequence", 7),
198 });
199
200 expect(steps).toEqual([
201 "read threads:in transaction",
202 "list projects:in transaction",
203 "latest sequence:in transaction",
204 "decode threads:out of transaction",
205 ]);
206 expect(snapshot.snapshotSequence).toBe(7);
207 expect(snapshot.threads.threads).toEqual([thread]);
208 }).pipe(Effect.provide(NodeSqliteClient.layer({ filename: ":memory:" }))),
209 );
210});
211
212function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): OrchestrationV2ThreadShell {
213 return { id: "thread-a", archivedAt: null, ...overrides } as OrchestrationV2ThreadShell;
214}
215
216describe("coalesceStoredThreadEvents", () => {
217 it("keeps the newest stored event per thread and preserves sequence order", () => {
218 expect(
219 coalesceStoredThreadEvents([
220 storedThreadEvent(2, "thread-a"),
221 storedThreadEvent(3, "thread-b"),
222 storedThreadEvent(5, "thread-a"),
223 ]).map((stored) => stored.sequence),
224 ).toEqual([3, 5]);
225 });
226});
227
228describe("shellStreamItemFromThreadShell", () => {
229 it("emits an active thread update when the shell is not archived", () => {
230 const shell = shellFixture({ archivedAt: null });
231 expect(
232 shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
233 ).toEqual({
234 kind: "thread.updated",
235 sequence: 4,
236 location: "active",
237 thread: shell,
238 });
239 });
240
241 it("removes archived threads from the active-only shell", () => {
242 const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never });
243 expect(
244 shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
245 ).toEqual({
246 kind: "thread.removed",
247 sequence: 4,
248 location: "active",
249 threadId: "thread-a",
250 });
251 });
252
253 it("emits an active-shell removal when an archived thread is deleted", () => {
254 expect(
255 shellStreamItemFromThreadShell({
256 stored: storedThreadEvent(6, "thread-a", {
257 type: "thread.deleted",
258 payload: { archivedAt: "2026-07-30T00:00:00.000Z" },
259 }),
260 shell: null,
261 }),
262 ).toEqual({
263 kind: "thread.removed",
264 sequence: 6,
265 location: "active",
266 threadId: "thread-a",
267 });
268 });
269
270 it("emits a removal from the active list for other missing shells", () => {
271 expect(
272 shellStreamItemFromThreadShell({
273 stored: storedThreadEvent(6, "thread-a", {
274 type: "thread.deleted",
275 payload: { archivedAt: null },
276 }),
277 shell: null,
278 }),
279 ).toEqual({
280 kind: "thread.removed",
281 sequence: 6,
282 location: "active",
283 threadId: "thread-a",
284 });
285 });
286});
287
288describe("archivedShellStreamItemFromThreadShell", () => {
289 it("emits an update for an archived shell", () => {
290 const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never });
291 expect(
292 archivedShellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
293 ).toEqual({ kind: "thread.updated", sequence: 4, thread: shell });
294 });
295
296 it("ignores active threads that never touched the archive", () => {
297 expect(
298 archivedShellStreamItemFromThreadShell({
299 stored: storedThreadEvent(4, "thread-a", { type: "thread.settled" }),
300 shell: shellFixture({ archivedAt: null }),
301 }),
302 ).toBeNull();
303 });
304
305 it("emits a removal when a thread leaves the archive", () => {
306 expect(
307 archivedShellStreamItemFromThreadShell({
308 stored: storedThreadEvent(4, "thread-a", { type: "thread.unarchived" }),
309 shell: shellFixture({ archivedAt: null }),
310 }),
311 ).toEqual({ kind: "thread.removed", sequence: 4, threadId: "thread-a" });
312 });
313
314 it("emits a removal when an archived thread is deleted", () => {
315 expect(
316 archivedShellStreamItemFromThreadShell({
317 stored: storedThreadEvent(4, "thread-a", {
318 type: "thread.deleted",
319 payload: { archivedAt: "2026-07-30T00:00:00.000Z" },
320 }),
321 shell: null,
322 }),
323 ).toEqual({ kind: "thread.removed", sequence: 4, threadId: "thread-a" });
324 });
325});
326
327describe("shellStreamItemFromEnrichmentRefresh", () => {
328 it("batches nearby completion roots onto one snapshot item", () => {
329 expect(
330 shellStreamItemFromEnrichmentRefresh({
331 snapshot: emptyShellSnapshot,
332 changes: [
333 { workspaceRoot: "/workspace/a" },
334 { workspaceRoot: "/workspace/b" },
335 { workspaceRoot: "/workspace/a" },
336 ],
337 }),
338 ).toEqual({
339 kind: "snapshot",
340 snapshot: emptyShellSnapshot,
341 resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/b"],
342 });
343 });
344});
345
346describe("shellStreamItemsFromInitialSnapshot", () => {
347 it("keeps thread rows out of the metadata-only enrichment frame", () => {
348 const snapshot = {
349 ...emptyShellSnapshot,
350 projects: [
351 { id: "project-a", workspaceRoot: "/workspace/a" },
352 { id: "project-b", workspaceRoot: "/workspace/b" },
353 ],
354 threads: [shellFixture({})],
355 archivedThreads: [shellFixture({ id: ThreadId.make("thread-archived"), archivedAt: null })],
356 } as unknown as OrchestrationV2ShellSnapshot;
357
358 const items = shellStreamItemsFromInitialSnapshot({
359 snapshot,
360 resolvedRepositoryIdentityRoots: ["/workspace/a"],
361 });
362
363 expect(items[0]).toEqual({ kind: "snapshot", snapshot });
364 expect(items[1]).toMatchObject({
365 kind: "snapshot",
366 snapshot: {
367 projects: [{ id: "project-a", workspaceRoot: "/workspace/a" }],
368 threads: [],
369 archivedThreads: [],
370 },
371 resolvedRepositoryIdentityRoots: ["/workspace/a"],
372 });
373 expect(JSON.stringify(items[1]).length).toBeLessThan(JSON.stringify(items[0]).length);
374 });
375
376 it("emits unmarked authoritative then same-sequence marked enrichment when roots resolved", () => {
377 const snapshot = {
378 ...emptyShellSnapshot,
379 snapshotSequence: 7,
380 } as OrchestrationV2ShellSnapshot;
381
382 expect(
383 shellStreamItemsFromInitialSnapshot({
384 snapshot,
385 resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/a"],
386 }),
387 ).toEqual([
388 { kind: "snapshot", snapshot },
389 {
390 kind: "snapshot",
391 snapshot,
392 resolvedRepositoryIdentityRoots: ["/workspace/a"],
393 },
394 ]);
395 });
396
397 it("emits only the unmarked authoritative snapshot when no roots resolved", () => {
398 expect(
399 shellStreamItemsFromInitialSnapshot({
400 snapshot: emptyShellSnapshot,
401 resolvedRepositoryIdentityRoots: [],
402 }),
403 ).toEqual([{ kind: "snapshot", snapshot: emptyShellSnapshot }]);
404 });
405});
406
407describe("shellStreamItemsFromResumeSnapshot", () => {
408 it("never repeats the authoritative shell snapshot", () => {
409 expect(
410 shellStreamItemsFromResumeSnapshot({
411 snapshot: {
412 ...emptyShellSnapshot,
413 threads: [shellFixture({})],
414 },
415 resolvedRepositoryIdentityRoots: [],
416 }),
417 ).toEqual([]);
418 });
419});
420
421describe("composeShellStreamWithEnrichment", () => {
422 it.effect("preserves pending repository resolutions while an enrichment ACK is withheld", () =>
423 Effect.scoped(
424 Effect.gen(function* () {
425 // Match ProjectEnrichmentService's sliding notifications and the WS batching path.
426 const changes = yield* Effect.acquireRelease(
427 PubSub.sliding<{ readonly workspaceRoot: string }>(256),
428 PubSub.shutdown,
429 );
430 const subscription = yield* PubSub.subscribe(changes);
431 const pull = yield* Stream.toPull(
432 composeShellStreamWithEnrichment({
433 initial: Stream.empty,
434 tail: Stream.empty,
435 enrichment: Stream.fromSubscription(subscription).pipe(
436 Stream.groupedWithin(64, Duration.millis(25)),
437 Stream.map((changes) =>
438 shellStreamItemFromEnrichmentRefresh({
439 snapshot: emptyShellSnapshot,
440 changes,
441 }),
442 ),
443 ),
444 }),
445 );
446
447 const firstRoots = Array.from({ length: 64 }, (_, index) => `/workspace/first-${index}`);
448 yield* PubSub.publishAll(
449 changes,
450 firstRoots.map((workspaceRoot) => ({ workspaceRoot })),
451 );
452 expect(yield* pull).toMatchObject([{ resolvedRepositoryIdentityRoots: firstRoots }]);
453
454 // The next completion can be batched before the client acknowledges the first.
455 yield* PubSub.publish(changes, { workspaceRoot: "/workspace/pending" });
456 yield* Effect.yieldNow;
457 yield* TestClock.adjust(Duration.millis(25));
458 const laterRoots = Array.from({ length: 256 }, (_, index) => `/workspace/later-${index}`);
459 yield* PubSub.publishAll(
460 changes,
461 laterRoots.map((workspaceRoot) => ({ workspaceRoot })),
462 );
463
464 const resumed = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
465 Stream.takeUntil(
466 (item) =>
467 item.resolvedRepositoryIdentityRoots?.includes("/workspace/later-255") ?? false,
468 ),
469 Stream.runCollect,
470 );
471 expect(resumed.flatMap((item) => item.resolvedRepositoryIdentityRoots ?? [])).toEqual([
472 "/workspace/pending",
473 ...laterRoots,
474 ]);
475 }),
476 ),
477 );
478
479 it.effect("keeps a merged shell batch charged while the client withholds its ACK", () =>
480 Effect.scoped(
481 Effect.gen(function* () {
482 const update = yield* Deferred.make<void>();
483 const closed = yield* Deferred.make<void>();
484 const initial = {
485 kind: "thread.removed" as const,
486 sequence: 1,
487 location: "active" as const,
488 threadId: ThreadId.make("thread-a"),
489 };
490 const pull = yield* Stream.toPull(
491 composeShellStreamWithEnrichment({
492 initial: Stream.empty,
493 tail: bufferShellLiveStream(
494 Stream.concat(
495 Stream.succeed(initial),
496 Stream.fromEffect(Deferred.await(update)).pipe(
497 Stream.map(() => ({ ...initial, sequence: 2 })),
498 ),
499 ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
500 { maxItems: 1 },
501 ),
502 enrichment: Stream.empty,
503 }),
504 );
505 expect(yield* pull).toEqual([initial]);
506 // Let the merge producer run while the client still withholds its ACK.
507 yield* Effect.yieldNow;
508 yield* Deferred.succeed(update, undefined);
509 yield* Deferred.await(closed);
510 const result = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
511 Stream.runDrain,
512 Effect.result,
513 );
514 expect(result._tag).toBe("Failure");
515 if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
516 }),
517 ),
518 );
519
520 it.effect(
521 "emits every initial item before enrichment even when enrichment is already ready",
522 () =>
523 Effect.gen(function* () {
524 const initialSnapshot = {
525 ...emptyShellSnapshot,
526 snapshotSequence: 5,
527 } as OrchestrationV2ShellSnapshot;
528 const enrichmentSnapshot = {
529 ...emptyShellSnapshot,
530 snapshotSequence: 10,
531 } as OrchestrationV2ShellSnapshot;
532
533 const initialItems = shellStreamItemsFromInitialSnapshot({
534 snapshot: initialSnapshot,
535 resolvedRepositoryIdentityRoots: ["/workspace/a"],
536 });
537 const enrichment = Stream.make(
538 shellStreamItemFromEnrichmentRefresh({
539 snapshot: enrichmentSnapshot,
540 changes: [{ workspaceRoot: "/workspace/b" }],
541 }),
542 );
543 const tail = Stream.make(
544 { kind: "synchronized" as const },
545 {
546 kind: "project.removed" as const,
547 sequence: 6,
548 projectId: "project-a",
549 },
550 );
551
552 const items = Array.from(
553 yield* composeShellStreamWithEnrichment({
554 initial: Stream.fromIterable(initialItems),
555 tail,
556 enrichment,
557 }).pipe(Stream.runCollect),
558 );
559
560 expect(items.slice(0, initialItems.length)).toEqual(initialItems);
561
562 const enrichmentIndex = items.findIndex(
563 (item) =>
564 item.kind === "snapshot" &&
565 "resolvedRepositoryIdentityRoots" in item &&
566 item.resolvedRepositoryIdentityRoots?.includes("/workspace/b"),
567 );
568 expect(enrichmentIndex).toBeGreaterThanOrEqual(initialItems.length);
569
570 for (let index = 0; index < initialItems.length; index++) {
571 expect(items[index]).toEqual(initialItems[index]);
572 }
573 }),
574 );
575
576 it.effect("still interleaves enrichment with the post-prefix tail after initials drain", () =>
577 Effect.gen(function* () {
578 const items = Array.from(
579 yield* composeShellStreamWithEnrichment({
580 initial: Stream.make("initial-unmarked", "initial-marked"),
581 tail: Stream.make("tail-a", "tail-b"),
582 enrichment: Stream.make("enrichment"),
583 }).pipe(Stream.runCollect),
584 );
585
586 expect(items.slice(0, 2)).toEqual(["initial-unmarked", "initial-marked"]);
587 expect(items).toContain("enrichment");
588 expect(items).toContain("tail-a");
589 expect(items).toContain("tail-b");
590 expect(items.indexOf("enrichment")).toBeGreaterThanOrEqual(2);
591 }),
592 );
593});
594
595describe("dedupeShellEnrichment", () => {
596 const project = {
597 id: ProjectId.make("project-a"),
598 title: "A project",
599 workspaceRoot: "/workspace/a",
600 repositoryIdentity: null,
601 defaultModelSelection: null,
602 scripts: [],
603 createdAt: "2026-09-01T00:00:00Z",
604 updatedAt: "2026-09-01T00:00:00Z",
605 };
606 const initial = {
607 kind: "snapshot" as const,
608 snapshot: { ...emptyShellSnapshot, projects: [project] },
609 };
610 const marked = { ...initial, resolvedRepositoryIdentityRoots: [project.workspaceRoot] };
611
612 it.effect(
613 "keeps initial/resume resolution and real changes but drops sequence-only repeats",
614 () =>
615 Effect.gen(function* () {
616 const repeated = {
617 ...marked,
618 snapshot: { ...marked.snapshot, snapshotSequence: 10, projects: [{ ...project }] },
619 };
620 const progressed = {
621 ...repeated,
622 resolvedRepositoryIdentityRoots: [project.workspaceRoot, "/workspace/b"],
623 };
624 const changed = {
625 ...progressed,
626 snapshot: { ...progressed.snapshot, projects: [{ ...project, title: "Renamed" }] },
627 };
628 const items = yield* Stream.make(
629 initial,
630 marked,
631 repeated,
632 progressed,
633 changed,
634 changed,
635 ).pipe(dedupeShellEnrichment, Stream.runCollect);
636 expect(items).toEqual([initial, marked, progressed, changed]);
637 const resumed = Stream.make(marked, repeated).pipe(dedupeShellEnrichment);
638 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
639 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
640 }),
641 );
642
643 it.effect("keeps authoritative snapshots and invalidates metadata after project deltas", () =>
644 Effect.gen(function* () {
645 const removed = { kind: "project.removed" as const, projectId: project.id, sequence: 2 };
646 const updated = { kind: "project.updated" as const, project, sequence: 3 };
647 const withThreads = {
648 ...marked,
649 snapshot: { ...marked.snapshot, threads: [shellFixture({})] },
650 };
651 const values = [
652 initial,
653 initial,
654 marked,
655 removed,
656 marked,
657 updated,
658 marked,
659 withThreads,
660 withThreads,
661 ];
662 expect(
663 yield* Stream.fromIterable(values).pipe(dedupeShellEnrichment, Stream.runCollect),
664 ).toEqual(values);
665 }),
666 );
667
668 it.effect(
669 "deduplicates across thread deltas without dropping those deltas or identity clears",
670 () =>
671 Effect.gen(function* () {
672 const delta = {
673 kind: "thread.removed" as const,
674 threadId: ThreadId.make("thread-a"),
675 location: "active" as const,
676 sequence: 2,
677 };
678 const resolved = {
679 ...marked,
680 snapshot: {
681 ...marked.snapshot,
682 projects: [
683 {
684 ...project,
685 repositoryIdentity: {
686 canonicalKey: "github.com/test/repo",
687 locator: {
688 source: "git-remote" as const,
689 remoteName: "origin",
690 remoteUrl: "https://github.com/test/repo.git",
691 },
692 },
693 },
694 ],
695 },
696 };
697 expect(
698 yield* Stream.make(marked, delta, marked, resolved, marked).pipe(
699 dedupeShellEnrichment,
700 Stream.runCollect,
701 ),
702 ).toEqual([marked, delta, resolved, marked]);
703 }),
704 );
705});
706
707describe("skipUnchangedThreadShells", () => {
708 const at = (ms: number) => DateTime.makeUnsafe(Date.parse("2026-10-01T00:00:00.000Z") + ms);
709 const shell = (
710 id: string,
711 overrides: Partial<OrchestrationV2ThreadShell> = {},
712 ): OrchestrationV2ThreadShell => ({
713 id: ThreadId.make(id),
714 projectId: ProjectId.make("project-a"),
715 title: "Thread",
716 providerInstanceId: ProviderInstanceId.make("codex"),
717 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
718 runtimeMode: "full-access",
719 interactionMode: "default",
720 worktreePath: null,
721 activeProviderThreadId: null,
722 lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
723 forkedFrom: null,
724 createdBy: "user",
725 creationSource: "web",
726 activeRunId: null,
727 latestVisibleMessage: null,
728 hasActionableProposedPlan: false,
729 itemCount: 1,
730 visibleItemCount: 1,
731 branch: null,
732 status: "running",
733 pendingRuntimeRequest: null,
734 pendingBackgroundTasks: [],
735 latestRunId: null,
736 latestUserMessageAt: null,
737 createdAt: at(0),
738 updatedAt: at(0),
739 archivedAt: null,
740 settledOverride: null,
741 settledAt: null,
742 deletedAt: null,
743 ...overrides,
744 });
745 type Step =
746 | { readonly advanceMs: number }
747 | Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" | "synchronized" }>;
748 const updated = (sequence: number, thread: OrchestrationV2ThreadShell): Step => ({
749 kind: "thread.updated",
750 sequence,
751 location: "active",
752 thread,
753 });
754 const run = (steps: ReadonlyArray<Step>) =>
755 Stream.fromIterable(steps).pipe(
756 Stream.mapEffect((step) =>
757 "advanceMs" in step
758 ? TestClock.adjust(Duration.millis(step.advanceMs)).pipe(Effect.as(null))
759 : Effect.succeed(step),
760 ),
761 Stream.filter((item) => item !== null),
762 skipUnchangedThreadShells,
763 Stream.runCollect,
764 Effect.map((items) => Array.from(items, (item) => ("sequence" in item ? item.sequence : -1))),
765 );
766
767 it.effect("drops shells that only moved updatedAt, and resends them after a while", () =>
768 Effect.gen(function* () {
769 const sent = yield* run([
770 updated(1, shell("a")),
771 updated(2, shell("a", { updatedAt: at(100) })),
772 updated(3, shell("a", { updatedAt: at(200), itemCount: 2, visibleItemCount: 2 })),
773 updated(4, shell("a", { updatedAt: at(300), itemCount: 2, visibleItemCount: 2 })),
774 updated(5, shell("b")),
775 { advanceMs: 5_000 },
776 updated(6, shell("a", { updatedAt: at(5_300), itemCount: 2, visibleItemCount: 2 })),
777 ]);
778 expect(sent).toEqual([1, 3, 5, 6]);
779 }),
780 );
781
782 it.effect("sends the next update after a removal", () =>
783 Effect.gen(function* () {
784 const sent = yield* run([
785 updated(1, shell("a")),
786 { kind: "thread.removed", sequence: 2, location: "active", threadId: ThreadId.make("a") },
787 updated(3, shell("a")),
788 ]);
789 expect(sent).toEqual([1, 2, 3]);
790 }),
791 );
792});