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 DateTime from "effect/DateTime";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15
16import {
17 archivedShellStreamItemFromThreadShell,
18 buildActiveShellSnapshot,
19 coalesceShellApplicationEvents,
20 coalesceStoredThreadEvents,
21 composeShellStreamWithEnrichment,
22 dedupeShellEnrichment,
23 shellStreamItemFromEnrichmentRefresh,
24 shellStreamItemFromThreadShell,
25 shellStreamItemsFromInitialSnapshot,
26 shellStreamItemsFromResumeSnapshot,
27 skipUnchangedThreadShells,
28} from "./ShellStream.ts";
29
30function project(sequence: number, id: string): ApplicationStoredEvent {
31 return {
32 sequence,
33 aggregateKind: "project",
34 aggregateId: id,
35 } as ApplicationStoredEvent;
36}
37
38function thread(sequence: number, id: string): ApplicationStoredEvent {
39 return {
40 sequence,
41 event: { threadId: id },
42 } as ApplicationStoredEvent;
43}
44
45const emptyShellSnapshot = {
46 schemaVersion: 1,
47 snapshotSequence: 0,
48 projects: [],
49 threads: [],
50 archivedThreads: [],
51} as OrchestrationV2ShellSnapshot;
52
53describe("buildActiveShellSnapshot", () => {
54 it("never duplicates archived rows into the regular shell", () => {
55 const active = shellFixture({ archivedAt: null });
56 const archived = shellFixture({
57 id: ThreadId.make("thread-archived"),
58 archivedAt: "2026-07-30T00:00:00.000Z" as never,
59 });
60
61 expect(
62 buildActiveShellSnapshot({
63 projects: [],
64 threads: {
65 schemaVersion: 1,
66 snapshotSequence: 4,
67 threads: [active],
68 archivedThreads: [archived],
69 },
70 snapshotSequence: 7,
71 }),
72 ).toEqual({
73 schemaVersion: 1,
74 snapshotSequence: 7,
75 projects: [],
76 threads: [active],
77 archivedThreads: [],
78 });
79 });
80});
81
82describe("coalesceShellApplicationEvents", () => {
83 it("keeps the newest event per aggregate and preserves sequence order", () => {
84 expect(
85 coalesceShellApplicationEvents([
86 thread(2, "thread-a"),
87 project(3, "project-a"),
88 thread(4, "thread-b"),
89 thread(5, "thread-a"),
90 project(6, "project-a"),
91 ]).map((event) => event.sequence),
92 ).toEqual([4, 5, 6]);
93 });
94});
95
96function storedThreadEvent(
97 sequence: number,
98 threadId: string,
99 event: Record<string, unknown> = {},
100): OrchestrationV2StoredEvent {
101 return { sequence, event: { threadId, ...event } } as OrchestrationV2StoredEvent;
102}
103
104function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): OrchestrationV2ThreadShell {
105 return { id: "thread-a", archivedAt: null, ...overrides } as OrchestrationV2ThreadShell;
106}
107
108describe("coalesceStoredThreadEvents", () => {
109 it("keeps the newest stored event per thread and preserves sequence order", () => {
110 expect(
111 coalesceStoredThreadEvents([
112 storedThreadEvent(2, "thread-a"),
113 storedThreadEvent(3, "thread-b"),
114 storedThreadEvent(5, "thread-a"),
115 ]).map((stored) => stored.sequence),
116 ).toEqual([3, 5]);
117 });
118});
119
120describe("shellStreamItemFromThreadShell", () => {
121 it("emits an active thread update when the shell is not archived", () => {
122 const shell = shellFixture({ archivedAt: null });
123 expect(
124 shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
125 ).toEqual({
126 kind: "thread.updated",
127 sequence: 4,
128 location: "active",
129 thread: shell,
130 });
131 });
132
133 it("removes archived threads from the active-only shell", () => {
134 const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never });
135 expect(
136 shellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
137 ).toEqual({
138 kind: "thread.removed",
139 sequence: 4,
140 location: "active",
141 threadId: "thread-a",
142 });
143 });
144
145 it("emits an active-shell removal when an archived thread is deleted", () => {
146 expect(
147 shellStreamItemFromThreadShell({
148 stored: storedThreadEvent(6, "thread-a", {
149 type: "thread.deleted",
150 payload: { archivedAt: "2026-07-30T00:00:00.000Z" },
151 }),
152 shell: null,
153 }),
154 ).toEqual({
155 kind: "thread.removed",
156 sequence: 6,
157 location: "active",
158 threadId: "thread-a",
159 });
160 });
161
162 it("emits a removal from the active list for other missing shells", () => {
163 expect(
164 shellStreamItemFromThreadShell({
165 stored: storedThreadEvent(6, "thread-a", {
166 type: "thread.deleted",
167 payload: { archivedAt: null },
168 }),
169 shell: null,
170 }),
171 ).toEqual({
172 kind: "thread.removed",
173 sequence: 6,
174 location: "active",
175 threadId: "thread-a",
176 });
177 });
178});
179
180describe("archivedShellStreamItemFromThreadShell", () => {
181 it("emits an update for an archived shell", () => {
182 const shell = shellFixture({ archivedAt: "2026-07-30T00:00:00.000Z" as never });
183 expect(
184 archivedShellStreamItemFromThreadShell({ stored: storedThreadEvent(4, "thread-a"), shell }),
185 ).toEqual({ kind: "thread.updated", sequence: 4, thread: shell });
186 });
187
188 it("ignores active threads that never touched the archive", () => {
189 expect(
190 archivedShellStreamItemFromThreadShell({
191 stored: storedThreadEvent(4, "thread-a", { type: "thread.settled" }),
192 shell: shellFixture({ archivedAt: null }),
193 }),
194 ).toBeNull();
195 });
196
197 it("emits a removal when a thread leaves the archive", () => {
198 expect(
199 archivedShellStreamItemFromThreadShell({
200 stored: storedThreadEvent(4, "thread-a", { type: "thread.unarchived" }),
201 shell: shellFixture({ archivedAt: null }),
202 }),
203 ).toEqual({ kind: "thread.removed", sequence: 4, threadId: "thread-a" });
204 });
205
206 it("emits a removal when an archived thread is deleted", () => {
207 expect(
208 archivedShellStreamItemFromThreadShell({
209 stored: storedThreadEvent(4, "thread-a", {
210 type: "thread.deleted",
211 payload: { archivedAt: "2026-07-30T00:00:00.000Z" },
212 }),
213 shell: null,
214 }),
215 ).toEqual({ kind: "thread.removed", sequence: 4, threadId: "thread-a" });
216 });
217});
218
219describe("shellStreamItemFromEnrichmentRefresh", () => {
220 it("batches nearby completion roots onto one snapshot item", () => {
221 expect(
222 shellStreamItemFromEnrichmentRefresh({
223 snapshot: emptyShellSnapshot,
224 changes: [
225 { workspaceRoot: "/workspace/a" },
226 { workspaceRoot: "/workspace/b" },
227 { workspaceRoot: "/workspace/a" },
228 ],
229 }),
230 ).toEqual({
231 kind: "snapshot",
232 snapshot: emptyShellSnapshot,
233 resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/b"],
234 });
235 });
236});
237
238describe("shellStreamItemsFromInitialSnapshot", () => {
239 it("keeps thread rows out of the metadata-only enrichment frame", () => {
240 const snapshot = {
241 ...emptyShellSnapshot,
242 projects: [
243 { id: "project-a", workspaceRoot: "/workspace/a" },
244 { id: "project-b", workspaceRoot: "/workspace/b" },
245 ],
246 threads: [shellFixture({})],
247 archivedThreads: [shellFixture({ id: ThreadId.make("thread-archived"), archivedAt: null })],
248 } as unknown as OrchestrationV2ShellSnapshot;
249
250 const items = shellStreamItemsFromInitialSnapshot({
251 snapshot,
252 resolvedRepositoryIdentityRoots: ["/workspace/a"],
253 });
254
255 expect(items[0]).toEqual({ kind: "snapshot", snapshot });
256 expect(items[1]).toMatchObject({
257 kind: "snapshot",
258 snapshot: {
259 projects: [{ id: "project-a", workspaceRoot: "/workspace/a" }],
260 threads: [],
261 archivedThreads: [],
262 },
263 resolvedRepositoryIdentityRoots: ["/workspace/a"],
264 });
265 expect(JSON.stringify(items[1]).length).toBeLessThan(JSON.stringify(items[0]).length);
266 });
267
268 it("emits unmarked authoritative then same-sequence marked enrichment when roots resolved", () => {
269 const snapshot = {
270 ...emptyShellSnapshot,
271 snapshotSequence: 7,
272 } as OrchestrationV2ShellSnapshot;
273
274 expect(
275 shellStreamItemsFromInitialSnapshot({
276 snapshot,
277 resolvedRepositoryIdentityRoots: ["/workspace/a", "/workspace/a"],
278 }),
279 ).toEqual([
280 { kind: "snapshot", snapshot },
281 {
282 kind: "snapshot",
283 snapshot,
284 resolvedRepositoryIdentityRoots: ["/workspace/a"],
285 },
286 ]);
287 });
288
289 it("emits only the unmarked authoritative snapshot when no roots resolved", () => {
290 expect(
291 shellStreamItemsFromInitialSnapshot({
292 snapshot: emptyShellSnapshot,
293 resolvedRepositoryIdentityRoots: [],
294 }),
295 ).toEqual([{ kind: "snapshot", snapshot: emptyShellSnapshot }]);
296 });
297});
298
299describe("shellStreamItemsFromResumeSnapshot", () => {
300 it("never repeats the authoritative shell snapshot", () => {
301 expect(
302 shellStreamItemsFromResumeSnapshot({
303 snapshot: {
304 ...emptyShellSnapshot,
305 threads: [shellFixture({})],
306 },
307 resolvedRepositoryIdentityRoots: [],
308 }),
309 ).toEqual([]);
310 });
311});
312
313describe("composeShellStreamWithEnrichment", () => {
314 it.effect(
315 "emits every initial item before enrichment even when enrichment is already ready",
316 () =>
317 Effect.gen(function* () {
318 const initialSnapshot = {
319 ...emptyShellSnapshot,
320 snapshotSequence: 5,
321 } as OrchestrationV2ShellSnapshot;
322 const enrichmentSnapshot = {
323 ...emptyShellSnapshot,
324 snapshotSequence: 10,
325 } as OrchestrationV2ShellSnapshot;
326
327 const initialItems = shellStreamItemsFromInitialSnapshot({
328 snapshot: initialSnapshot,
329 resolvedRepositoryIdentityRoots: ["/workspace/a"],
330 });
331 // Enrichment stream is fully ready before the composed stream is pulled.
332 const enrichment = Stream.make(
333 shellStreamItemFromEnrichmentRefresh({
334 snapshot: enrichmentSnapshot,
335 changes: [{ workspaceRoot: "/workspace/b" }],
336 }),
337 );
338 const tail = Stream.make(
339 { kind: "synchronized" as const },
340 {
341 kind: "project.removed" as const,
342 sequence: 6,
343 projectId: "project-a",
344 },
345 );
346
347 const items = Array.from(
348 yield* composeShellStreamWithEnrichment({
349 initial: Stream.fromIterable(initialItems),
350 tail,
351 enrichment,
352 }).pipe(Stream.runCollect),
353 );
354
355 expect(items.slice(0, initialItems.length)).toEqual(initialItems);
356
357 const enrichmentIndex = items.findIndex(
358 (item) =>
359 item.kind === "snapshot" &&
360 "resolvedRepositoryIdentityRoots" in item &&
361 item.resolvedRepositoryIdentityRoots?.includes("/workspace/b"),
362 );
363 expect(enrichmentIndex).toBeGreaterThanOrEqual(initialItems.length);
364
365 for (let index = 0; index < initialItems.length; index++) {
366 expect(items[index]).toEqual(initialItems[index]);
367 }
368 }),
369 );
370
371 it.effect("still interleaves enrichment with the post-prefix tail after initials drain", () =>
372 Effect.gen(function* () {
373 const items = Array.from(
374 yield* composeShellStreamWithEnrichment({
375 initial: Stream.make("initial-unmarked", "initial-marked"),
376 tail: Stream.make("tail-a", "tail-b"),
377 enrichment: Stream.make("enrichment"),
378 }).pipe(Stream.runCollect),
379 );
380
381 expect(items.slice(0, 2)).toEqual(["initial-unmarked", "initial-marked"]);
382 expect(items).toContain("enrichment");
383 expect(items).toContain("tail-a");
384 expect(items).toContain("tail-b");
385 expect(items.indexOf("enrichment")).toBeGreaterThanOrEqual(2);
386 }),
387 );
388});
389
390describe("dedupeShellEnrichment", () => {
391 const project = {
392 id: ProjectId.make("project-a"),
393 title: "A project",
394 workspaceRoot: "/workspace/a",
395 repositoryIdentity: null,
396 defaultModelSelection: null,
397 scripts: [],
398 createdAt: "2026-09-01T00:00:00Z",
399 updatedAt: "2026-09-01T00:00:00Z",
400 };
401 const initial = {
402 kind: "snapshot" as const,
403 snapshot: { ...emptyShellSnapshot, projects: [project] },
404 };
405 const marked = { ...initial, resolvedRepositoryIdentityRoots: [project.workspaceRoot] };
406
407 it.effect(
408 "keeps initial/resume resolution and real changes but drops sequence-only repeats",
409 () =>
410 Effect.gen(function* () {
411 const repeated = {
412 ...marked,
413 snapshot: { ...marked.snapshot, snapshotSequence: 10, projects: [{ ...project }] },
414 };
415 const progressed = {
416 ...repeated,
417 resolvedRepositoryIdentityRoots: [project.workspaceRoot, "/workspace/b"],
418 };
419 const changed = {
420 ...progressed,
421 snapshot: { ...progressed.snapshot, projects: [{ ...project, title: "Renamed" }] },
422 };
423 const items = yield* Stream.make(
424 initial,
425 marked,
426 repeated,
427 progressed,
428 changed,
429 changed,
430 ).pipe(dedupeShellEnrichment, Stream.runCollect);
431 expect(items).toEqual([initial, marked, progressed, changed]);
432 const resumed = Stream.make(marked, repeated).pipe(dedupeShellEnrichment);
433 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
434 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
435 }),
436 );
437
438 it.effect("keeps authoritative snapshots and invalidates metadata after project deltas", () =>
439 Effect.gen(function* () {
440 const removed = { kind: "project.removed" as const, projectId: project.id, sequence: 2 };
441 const updated = { kind: "project.updated" as const, project, sequence: 3 };
442 const withThreads = {
443 ...marked,
444 snapshot: { ...marked.snapshot, threads: [shellFixture({})] },
445 };
446 const values = [
447 initial,
448 initial,
449 marked,
450 removed,
451 marked,
452 updated,
453 marked,
454 withThreads,
455 withThreads,
456 ];
457 expect(
458 yield* Stream.fromIterable(values).pipe(dedupeShellEnrichment, Stream.runCollect),
459 ).toEqual(values);
460 }),
461 );
462
463 it.effect(
464 "deduplicates across thread deltas without dropping those deltas or identity clears",
465 () =>
466 Effect.gen(function* () {
467 const delta = {
468 kind: "thread.removed" as const,
469 threadId: ThreadId.make("thread-a"),
470 location: "active" as const,
471 sequence: 2,
472 };
473 const resolved = {
474 ...marked,
475 snapshot: {
476 ...marked.snapshot,
477 projects: [
478 {
479 ...project,
480 repositoryIdentity: {
481 canonicalKey: "github.com/test/repo",
482 locator: {
483 source: "git-remote" as const,
484 remoteName: "origin",
485 remoteUrl: "https://github.com/test/repo.git",
486 },
487 },
488 },
489 ],
490 },
491 };
492 expect(
493 yield* Stream.make(marked, delta, marked, resolved, marked).pipe(
494 dedupeShellEnrichment,
495 Stream.runCollect,
496 ),
497 ).toEqual([marked, delta, resolved, marked]);
498 }),
499 );
500});
501
502describe("skipUnchangedThreadShells", () => {
503 const at = (ms: number) => DateTime.makeUnsafe(Date.parse("2026-10-01T00:00:00.000Z") + ms);
504 const shell = (
505 id: string,
506 overrides: Partial<OrchestrationV2ThreadShell> = {},
507 ): OrchestrationV2ThreadShell => ({
508 id: ThreadId.make(id),
509 projectId: ProjectId.make("project-a"),
510 title: "Thread",
511 providerInstanceId: ProviderInstanceId.make("codex"),
512 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
513 runtimeMode: "full-access",
514 interactionMode: "default",
515 worktreePath: null,
516 activeProviderThreadId: null,
517 lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
518 forkedFrom: null,
519 createdBy: "user",
520 creationSource: "web",
521 activeRunId: null,
522 latestVisibleMessage: null,
523 hasActionableProposedPlan: false,
524 itemCount: 1,
525 visibleItemCount: 1,
526 branch: null,
527 status: "running",
528 pendingRuntimeRequest: null,
529 pendingBackgroundTasks: [],
530 latestRunId: null,
531 latestUserMessageAt: null,
532 createdAt: at(0),
533 updatedAt: at(0),
534 archivedAt: null,
535 settledOverride: null,
536 settledAt: null,
537 deletedAt: null,
538 ...overrides,
539 });
540 type Step =
541 | { readonly advanceMs: number }
542 | Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" | "synchronized" }>;
543 const updated = (sequence: number, thread: OrchestrationV2ThreadShell): Step => ({
544 kind: "thread.updated",
545 sequence,
546 location: "active",
547 thread,
548 });
549 const run = (steps: ReadonlyArray<Step>) =>
550 Stream.fromIterable(steps).pipe(
551 Stream.mapEffect((step) =>
552 "advanceMs" in step
553 ? TestClock.adjust(Duration.millis(step.advanceMs)).pipe(Effect.as(null))
554 : Effect.succeed(step),
555 ),
556 Stream.filter((item) => item !== null),
557 skipUnchangedThreadShells,
558 Stream.runCollect,
559 Effect.map((items) => Array.from(items, (item) => ("sequence" in item ? item.sequence : -1))),
560 );
561
562 it.effect("drops shells that only moved updatedAt, and resends them after a while", () =>
563 Effect.gen(function* () {
564 const sent = yield* run([
565 updated(1, shell("a")),
566 updated(2, shell("a", { updatedAt: at(100) })),
567 updated(3, shell("a", { updatedAt: at(200), itemCount: 2, visibleItemCount: 2 })),
568 updated(4, shell("a", { updatedAt: at(300), itemCount: 2, visibleItemCount: 2 })),
569 updated(5, shell("b")),
570 // The resend window is 5 s.
571 { advanceMs: 5_000 },
572 updated(6, shell("a", { updatedAt: at(5_300), itemCount: 2, visibleItemCount: 2 })),
573 ]);
574 expect(sent).toEqual([1, 3, 5, 6]);
575 }),
576 );
577
578 it.effect("sends the next update after a removal", () =>
579 Effect.gen(function* () {
580 const sent = yield* run([
581 updated(1, shell("a")),
582 { kind: "thread.removed", sequence: 2, location: "active", threadId: ThreadId.make("a") },
583 updated(3, shell("a")),
584 ]);
585 expect(sent).toEqual([1, 2, 3]);
586 }),
587 );
588});