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