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

ShellStream.test.ts

631 lines19.8 KB

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