Open History to see the last commit
1import {
2 EventId,
3 MessageId,
4 ThreadId,
5 RunId,
6 TurnItemId,
7 type OrchestrationV2ThreadStreamItem,
8} from "@t3tools/contracts";
9import { it } from "@effect/vitest";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Stream from "effect/Stream";
13import * as TestClock from "effect/testing/TestClock";
14import { describe, expect } from "vite-plus/test";
15import {
16 coalesceLiveToolUpdatedEvents,
17 coalesceThreadLiveStream,
18 makeThreadLiveEventCoalescer,
19} from "./ThreadLiveEventCoalescer.ts";
20
21type ThreadEvent = Extract<OrchestrationV2ThreadStreamItem, { readonly kind: "event" }>;
22const threadId = ThreadId.make("thread-coalescer-test");
23const runId = RunId.make("run-coalescer-test");
24const now = DateTime.makeUnsafe("2026-01-01T00:00:01.000Z");
25const encodeEvent = JSON.stringify;
26
27function makeToolActivity(
28 sequence: number,
29 options: {
30 readonly kind?: "tool.updated" | "tool.completed";
31 readonly toolCallId?: string;
32 readonly turnId?: RunId;
33 } = {},
34): ThreadEvent {
35 const itemRunId = options.turnId ?? runId;
36 const status = options.kind === "tool.completed" ? "completed" : "running";
37 return {
38 kind: "event",
39 sequence,
40 event: {
41 id: EventId.make(`event-${sequence}`),
42 type: "turn-item.updated",
43 threadId,
44 runId: itemRunId,
45 occurredAt: now,
46 payload: {
47 id: TurnItemId.make(options.toolCallId ?? "call-edit"),
48 type: "command_execution",
49 threadId,
50 runId: itemRunId,
51 nodeId: null,
52 providerThreadId: null,
53 providerTurnId: null,
54 nativeItemRef: null,
55 parentItemId: null,
56 ordinal: 0,
57 status,
58 title: "Editing app.ts",
59 startedAt: now,
60 completedAt: status === "completed" ? now : null,
61 updatedAt: now,
62 input: "echo app.ts",
63 output: `output-${sequence}`,
64 },
65 },
66 };
67}
68
69function makeMessage(sequence: number, text = "Still working"): ThreadEvent {
70 return {
71 kind: "event",
72 sequence,
73 event: {
74 id: EventId.make(`event-${sequence}`),
75 type: "message.updated",
76 threadId,
77 runId,
78 occurredAt: now,
79 payload: {
80 id: MessageId.make(`message-${sequence}`),
81 threadId,
82 runId,
83 nodeId: null,
84 createdBy: "agent",
85 creationSource: "provider",
86 role: "assistant",
87 text,
88 attachments: [],
89 streaming: false,
90 createdAt: now,
91 updatedAt: now,
92 },
93 },
94 };
95}
96
97describe("ThreadLiveEventCoalescer", () => {
98 it("coalesces only calls with a stable toolCallId", () => {
99 const events = [
100 makeToolActivity(1, { toolCallId: "call-a" }),
101 makeToolActivity(2, { toolCallId: "call-b" }),
102 makeToolActivity(3, { toolCallId: "call-a" }),
103 ];
104
105 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3]);
106 });
107
108 it("does not coalesce stable tool calls across turns", () => {
109 const events = [
110 makeToolActivity(1, { turnId: RunId.make("turn-old") }),
111 makeToolActivity(2, { turnId: RunId.make("turn-new") }),
112 ];
113
114 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([1, 2]);
115 });
116
117 it("flushes a stable update run before a completion boundary", () => {
118 const events = [
119 makeToolActivity(1),
120 makeToolActivity(2),
121 makeToolActivity(3, { kind: "tool.completed" }),
122 makeToolActivity(4),
123 ];
124
125 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3, 4]);
126 });
127
128 it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
129 Effect.scoped(
130 Effect.gen(function* () {
131 const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "50 millis" });
132 yield* Effect.scoped(coalescer.offer(makeToolActivity(1)));
133 yield* TestClock.adjust("50 millis");
134 const items = yield* coalescer.stream.pipe(Stream.take(1), Stream.runCollect);
135 expect(items.map((item) => (item.kind === "event" ? item.sequence : item.kind))).toEqual([
136 1,
137 ]);
138 }),
139 ),
140 );
141
142 it.effect("keeps an unacknowledged batch charged and clears later events on overflow", () =>
143 Effect.scoped(
144 Effect.gen(function* () {
145 const coalescer = yield* makeThreadLiveEventCoalescer({ maxItems: 3 });
146 const first = makeMessage(1, "é".repeat(1_024));
147 yield* coalescer.offer(first);
148
149 yield* Effect.scoped(
150 Effect.gen(function* () {
151 const pull = yield* Stream.toPull(coalescer.stream);
152 const batch = yield* pull;
153 expect(batch.map((item) => (item.kind === "event" ? item.sequence : null))).toEqual([
154 1,
155 ]);
156 yield* coalescer.offer(makeMessage(2));
157 yield* coalescer.offer(makeToolActivity(3));
158 expect((yield* coalescer.usage).retainedItems).toBe(3);
159
160 const overflow = yield* coalescer
161 .offer(makeToolActivity(4, { kind: "tool.completed" }))
162 .pipe(Effect.result);
163 expect(overflow._tag).toBe("Failure");
164 yield* coalescer.closed;
165 expect(yield* coalescer.usage).toEqual({
166 retainedItems: 1,
167 retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
168 });
169 }),
170 );
171 expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
172 }),
173 ),
174 );
175});
176
177it.effect("flushes the last update before a finite source ends", () =>
178 Effect.gen(function* () {
179 const result = yield* Stream.make(makeToolActivity(1), makeToolActivity(2)).pipe(
180 coalesceThreadLiveStream,
181 Stream.runCollect,
182 );
183 expect(result.map((item) => (item.kind === "event" ? item.sequence : null))).toEqual([2]);
184 }),
185);
186
187it.effect("propagates an upstream failure instead of leaving the subscriber waiting", () =>
188 Effect.gen(function* () {
189 const result = yield* Stream.fail("source stopped").pipe(
190 coalesceThreadLiveStream,
191 Stream.runCollect,
192 Effect.result,
193 );
194 expect(result._tag).toBe("Failure");
195 if (result._tag === "Failure") expect(result.failure).toBe("source stopped");
196 }),
197);