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

ShellStream.test.ts

466 lines16.1 KB

1import { describe, expect, it } from "@effect/vitest";
2import type {
3 OrchestrationV2ShellSnapshot,
4 OrchestrationV2ShellStreamItem,
5 OrchestrationV2ThreadShell,
6} from "@t3tools/contracts";
7import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
8import type * as Cause from "effect/Cause";
9import * as DateTime from "effect/DateTime";
10import * as Deferred from "effect/Deferred";
11import * as Duration from "effect/Duration";
12import * as Effect from "effect/Effect";
13import * as PubSub from "effect/PubSub";
14import * as Queue from "effect/Queue";
15import * as Stream from "effect/Stream";
16import * as TestClock from "effect/testing/TestClock";
17​
18import {
19 bufferShellLiveStream,
20 composeShellStreamWithEnrichment,
21 dedupeShellEnrichment,
22 shellStreamItemFromEnrichmentRefresh,
23 shellStreamItemsFromInitialSnapshot,
24 skipUnchangedThreadShells,
25} from "./ShellStream.ts";
26​
27const emptyShellSnapshot = {
28 schemaVersion: 1,
29 snapshotSequence: 0,
30 projects: [],
31 threads: [],
32 archivedThreads: [],
33} as OrchestrationV2ShellSnapshot;
34​
35it.effect("coalesces a slow shell subscriber by identity and location in sequence order", () =>
36 Effect.scoped(
37 Effect.gen(function* () {
38 const input = yield* Queue.unbounded<
39 Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>,
40 Cause.Done
41 >();
42 const drained = yield* Deferred.make<void>();
43 const shell = shellFixture({ id: ThreadId.make("same"), title: "Before" });
44 const project = {
45 id: ProjectId.make("same"),
46 title: "Before",
47 workspaceRoot: "/workspace/same",
48 repositoryIdentity: null,
49 defaultModelSelection: null,
50 scripts: [],
51 createdAt: "2026-09-01T00:00:00Z",
52 updatedAt: "2026-09-01T00:00:00Z",
53 };
54 const initial = {
55 kind: "thread.updated" as const,
56 sequence: 1,
57 location: "active" as const,
58 thread: shell,
59 };
60 const updates = [
61 { kind: "project.updated", sequence: 2, project },
62 { ...initial, sequence: 3 },
63 { ...initial, sequence: 4, location: "archive" },
64 { ...initial, sequence: 5, thread: { ...shell, id: ThreadId.make("other") } },
65 {
66 kind: "project.updated",
67 sequence: 6,
68 project: { ...project, id: ProjectId.make("other") },
69 },
70 { kind: "project.removed", sequence: 7, projectId: project.id },
71 { kind: "thread.removed", sequence: 8, location: "active", threadId: shell.id },
72 { kind: "project.updated", sequence: 9, project: { ...project, title: "Recreated" } },
73 { ...initial, sequence: 10, thread: { ...shell, title: "Recreated" } },
74 { kind: "thread.removed", sequence: 11, location: "archive", threadId: shell.id },
75 ] satisfies Array<Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>>;
76 const pull = yield* Stream.toPull(
77 bufferShellLiveStream(
78 Stream.fromQueue(input).pipe(Stream.ensuring(Deferred.succeed(drained, undefined))),
79 { maxItems: 6, maxSerializedBytes: 1_500 },
80 ),
81 );
82 yield* Queue.offer(input, initial);
83 expect(yield* pull).toEqual([initial]);
84 yield* Queue.offerAll(input, updates);
85 yield* Queue.end(input);
86 // Finish producing the burst while the first batch is still awaiting its ACK.
87 yield* Deferred.await(drained);
88 expect(yield* pull).toEqual([updates[3], updates[4], updates[7], updates[8], updates[9]]);
89 }),
90 ),
91);
92​
93function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): OrchestrationV2ThreadShell {
94 return { id: "thread-a", archivedAt: null, ...overrides } as OrchestrationV2ThreadShell;
96​
97describe("shellStreamItemsFromInitialSnapshot", () => {
98 it("keeps thread rows out of the metadata-only enrichment frame", () => {
99 const snapshot = {
100 ...emptyShellSnapshot,
101 projects: [
102 { id: "project-a", workspaceRoot: "/workspace/a" },
103 { id: "project-b", workspaceRoot: "/workspace/b" },
104 ],
105 threads: [shellFixture({})],
106 archivedThreads: [shellFixture({ id: ThreadId.make("thread-archived"), archivedAt: null })],
107 } as unknown as OrchestrationV2ShellSnapshot;
108​
109 const items = shellStreamItemsFromInitialSnapshot({
110 snapshot,
111 resolvedRepositoryIdentityRoots: ["/workspace/a"],
112 });
113​
114 expect(items[0]).toEqual({ kind: "snapshot", snapshot });
115 expect(items[1]).toMatchObject({
116 kind: "snapshot",
117 snapshot: {
118 projects: [{ id: "project-a", workspaceRoot: "/workspace/a" }],
119 threads: [],
120 archivedThreads: [],
121 },
122 resolvedRepositoryIdentityRoots: ["/workspace/a"],
123 });
124 expect(JSON.stringify(items[1]).length).toBeLessThan(JSON.stringify(items[0]).length);
125 });
126});
127​
128describe("composeShellStreamWithEnrichment", () => {
129 it.effect("preserves pending repository resolutions while an enrichment ACK is withheld", () =>
130 Effect.scoped(
131 Effect.gen(function* () {
132 // Match ProjectEnrichmentService's sliding notifications and the WS batching path.
133 const changes = yield* Effect.acquireRelease(
134 PubSub.sliding<{ readonly workspaceRoot: string }>(256),
135 PubSub.shutdown,
136 );
137 const subscription = yield* PubSub.subscribe(changes);
138 const pull = yield* Stream.toPull(
139 composeShellStreamWithEnrichment({
140 initial: Stream.empty,
141 tail: Stream.empty,
142 enrichment: Stream.fromSubscription(subscription).pipe(
143 Stream.groupedWithin(64, Duration.millis(25)),
144 Stream.map((changes) =>
145 shellStreamItemFromEnrichmentRefresh({
146 snapshot: emptyShellSnapshot,
147 changes,
148 }),
149 ),
150 ),
151 }),
152 );
153​
154 const firstRoots = Array.from({ length: 64 }, (_, index) => `/workspace/first-${index}`);
155 yield* PubSub.publishAll(
156 changes,
157 firstRoots.map((workspaceRoot) => ({ workspaceRoot })),
158 );
159 expect(yield* pull).toMatchObject([{ resolvedRepositoryIdentityRoots: firstRoots }]);
160​
161 // The next completion can be batched before the client acknowledges the first.
162 yield* PubSub.publish(changes, { workspaceRoot: "/workspace/pending" });
163 yield* Effect.yieldNow;
164 yield* TestClock.adjust(Duration.millis(25));
165 const laterRoots = Array.from({ length: 256 }, (_, index) => `/workspace/later-${index}`);
166 yield* PubSub.publishAll(
167 changes,
168 laterRoots.map((workspaceRoot) => ({ workspaceRoot })),
169 );
170​
171 const resumed = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
172 Stream.takeUntil(
173 (item) =>
174 item.resolvedRepositoryIdentityRoots?.includes("/workspace/later-255") ?? false,
175 ),
176 Stream.runCollect,
177 );
178 expect(resumed.flatMap((item) => item.resolvedRepositoryIdentityRoots ?? [])).toEqual([
179 "/workspace/pending",
180 ...laterRoots,
181 ]);
182 }),
183 ),
184 );
185​
186 it.effect("keeps a merged shell batch charged while the client withholds its ACK", () =>
187 Effect.scoped(
188 Effect.gen(function* () {
189 const update = yield* Deferred.make<void>();
190 const closed = yield* Deferred.make<void>();
191 const initial = {
192 kind: "thread.removed" as const,
193 sequence: 1,
194 location: "active" as const,
195 threadId: ThreadId.make("thread-a"),
196 };
197 const pull = yield* Stream.toPull(
198 composeShellStreamWithEnrichment({
199 initial: Stream.empty,
200 tail: bufferShellLiveStream(
201 Stream.concat(
202 Stream.succeed(initial),
203 Stream.fromEffect(Deferred.await(update)).pipe(
204 Stream.map(() => ({ ...initial, sequence: 2 })),
205 ),
206 ).pipe(Stream.ensuring(Deferred.succeed(closed, undefined))),
207 { maxItems: 1 },
208 ),
209 enrichment: Stream.empty,
210 }),
211 );
212 expect(yield* pull).toEqual([initial]);
213 // Let the merge producer run while the client still withholds its ACK.
214 yield* Effect.yieldNow;
215 yield* Deferred.succeed(update, undefined);
216 yield* Deferred.await(closed);
217 const result = yield* Stream.fromPull(Effect.succeed(pull)).pipe(
218 Stream.runDrain,
219 Effect.result,
220 );
221 expect(result._tag).toBe("Failure");
222 if (result._tag === "Failure") expect(result.failure._tag).toBe("LiveStreamBufferError");
223 }),
224 ),
225 );
226​
227 it.effect(
228 "emits every initial item before enrichment even when enrichment is already ready",
229 () =>
230 Effect.gen(function* () {
231 const initialSnapshot = {
232 ...emptyShellSnapshot,
233 snapshotSequence: 5,
234 } as OrchestrationV2ShellSnapshot;
235 const enrichmentSnapshot = {
236 ...emptyShellSnapshot,
237 snapshotSequence: 10,
238 } as OrchestrationV2ShellSnapshot;
239​
240 const initialItems = shellStreamItemsFromInitialSnapshot({
241 snapshot: initialSnapshot,
242 resolvedRepositoryIdentityRoots: ["/workspace/a"],
243 });
244 const enrichment = Stream.make(
245 shellStreamItemFromEnrichmentRefresh({
246 snapshot: enrichmentSnapshot,
247 changes: [{ workspaceRoot: "/workspace/b" }],
248 }),
249 );
250 const tail = Stream.make(
251 { kind: "synchronized" as const },
252 {
253 kind: "project.removed" as const,
254 sequence: 6,
255 projectId: "project-a",
256 },
257 );
258​
259 const items = Array.from(
260 yield* composeShellStreamWithEnrichment({
261 initial: Stream.fromIterable(initialItems),
262 tail,
263 enrichment,
264 }).pipe(Stream.runCollect),
265 );
266​
267 expect(items.slice(0, initialItems.length)).toEqual(initialItems);
268​
269 const enrichmentIndex = items.findIndex(
270 (item) =>
271 item.kind === "snapshot" &&
272 "resolvedRepositoryIdentityRoots" in item &&
273 item.resolvedRepositoryIdentityRoots?.includes("/workspace/b"),
274 );
275 expect(enrichmentIndex).toBeGreaterThanOrEqual(initialItems.length);
276​
277 for (let index = 0; index < initialItems.length; index++) {
278 expect(items[index]).toEqual(initialItems[index]);
279 }
280 }),
281 );
282});
283​
284describe("dedupeShellEnrichment", () => {
285 const project = {
286 id: ProjectId.make("project-a"),
287 title: "A project",
288 workspaceRoot: "/workspace/a",
289 repositoryIdentity: null,
290 defaultModelSelection: null,
291 scripts: [],
292 createdAt: "2026-09-01T00:00:00Z",
293 updatedAt: "2026-09-01T00:00:00Z",
294 };
295 const initial = {
296 kind: "snapshot" as const,
297 snapshot: { ...emptyShellSnapshot, projects: [project] },
298 };
299 const marked = { ...initial, resolvedRepositoryIdentityRoots: [project.workspaceRoot] };
300​
301 it.effect(
302 "keeps initial/resume resolution and real changes but drops sequence-only repeats",
303 () =>
304 Effect.gen(function* () {
305 const repeated = {
306 ...marked,
307 snapshot: { ...marked.snapshot, snapshotSequence: 10, projects: [{ ...project }] },
308 };
309 const progressed = {
310 ...repeated,
311 resolvedRepositoryIdentityRoots: [project.workspaceRoot, "/workspace/b"],
312 };
313 const changed = {
314 ...progressed,
315 snapshot: { ...progressed.snapshot, projects: [{ ...project, title: "Renamed" }] },
316 };
317 const items = yield* Stream.make(
318 initial,
319 marked,
320 repeated,
321 progressed,
322 changed,
323 changed,
324 ).pipe(dedupeShellEnrichment, Stream.runCollect);
325 expect(items).toEqual([initial, marked, progressed, changed]);
326 const resumed = Stream.make(marked, repeated).pipe(dedupeShellEnrichment);
327 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
328 expect(yield* Stream.runCollect(resumed)).toEqual([marked]);
329 }),
330 );
331​
332 it.effect("keeps authoritative snapshots and invalidates metadata after project deltas", () =>
333 Effect.gen(function* () {
334 const removed = { kind: "project.removed" as const, projectId: project.id, sequence: 2 };
335 const updated = { kind: "project.updated" as const, project, sequence: 3 };
336 const withThreads = {
337 ...marked,
338 snapshot: { ...marked.snapshot, threads: [shellFixture({})] },
339 };
340 const values = [
341 initial,
342 initial,
343 marked,
344 removed,
345 marked,
346 updated,
347 marked,
348 withThreads,
349 withThreads,
350 ];
351 expect(
352 yield* Stream.fromIterable(values).pipe(dedupeShellEnrichment, Stream.runCollect),
353 ).toEqual(values);
354 }),
355 );
356​
357 it.effect(
358 "deduplicates across thread deltas without dropping those deltas or identity clears",
359 () =>
360 Effect.gen(function* () {
361 const delta = {
362 kind: "thread.removed" as const,
363 threadId: ThreadId.make("thread-a"),
364 location: "active" as const,
365 sequence: 2,
366 };
367 const resolved = {
368 ...marked,
369 snapshot: {
370 ...marked.snapshot,
371 projects: [
372 {
373 ...project,
374 repositoryIdentity: {
375 canonicalKey: "github.com/test/repo",
376 locator: {
377 source: "git-remote" as const,
378 remoteName: "origin",
379 remoteUrl: "https://github.com/test/repo.git",
380 },
381 },
382 },
383 ],
384 },
385 };
386 expect(
387 yield* Stream.make(marked, delta, marked, resolved, marked).pipe(
388 dedupeShellEnrichment,
389 Stream.runCollect,
390 ),
391 ).toEqual([marked, delta, resolved, marked]);
392 }),
393 );
394});
395​
396describe("skipUnchangedThreadShells", () => {
397 const at = (ms: number) => DateTime.makeUnsafe(Date.parse("2026-10-01T00:00:00.000Z") + ms);
398 const shell = (
399 id: string,
400 overrides: Partial<OrchestrationV2ThreadShell> = {},
401 ): OrchestrationV2ThreadShell => ({
402 id: ThreadId.make(id),
403 projectId: ProjectId.make("project-a"),
404 title: "Thread",
405 providerInstanceId: ProviderInstanceId.make("codex"),
406 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
407 runtimeMode: "full-access",
408 interactionMode: "default",
409 worktreePath: null,
410 activeProviderThreadId: null,
411 lineage: { rootThreadId: ThreadId.make(id), parentThreadId: null, relationshipToParent: null },
412 forkedFrom: null,
413 createdBy: "user",
414 creationSource: "web",
415 activeRunId: null,
416 latestVisibleMessage: null,
417 hasActionableProposedPlan: false,
418 itemCount: 1,
419 visibleItemCount: 1,
420 branch: null,
421 status: "running",
422 pendingRuntimeRequest: null,
423 pendingBackgroundTasks: [],
424 latestRunId: null,
425 latestUserMessageAt: null,
426 createdAt: at(0),
427 updatedAt: at(0),
428 archivedAt: null,
429 settledOverride: null,
430 settledAt: null,
431 deletedAt: null,
432 ...overrides,
433 });
434 type Step =
435 | { readonly advanceMs: number }
436 | Exclude<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" | "synchronized" }>;
437 const updated = (sequence: number, thread: OrchestrationV2ThreadShell): Step => ({
438 kind: "thread.updated",
439 sequence,
440 location: "active",
441 thread,
442 });
443 const run = (steps: ReadonlyArray<Step>) =>
444 Stream.fromIterable(steps).pipe(
445 Stream.mapEffect((step) =>
446 "advanceMs" in step
447 ? TestClock.adjust(Duration.millis(step.advanceMs)).pipe(Effect.as(null))
448 : Effect.succeed(step),
449 ),
450 Stream.filter((item) => item !== null),
451 skipUnchangedThreadShells,
452 Stream.runCollect,
453 Effect.map((items) => Array.from(items, (item) => ("sequence" in item ? item.sequence : -1))),
454 );
455​
456 it.effect("sends the next update after a removal", () =>
457 Effect.gen(function* () {
458 const sent = yield* run([
459 updated(1, shell("a")),
460 { kind: "thread.removed", sequence: 2, location: "active", threadId: ThreadId.make("a") },
461 updated(3, shell("a")),
462 ]);
463 expect(sent).toEqual([1, 2, 3]);
464 }),
465 );
466});