Open History to see the last commit
1import {
2 EventId,
3 MessageId,
4 ThreadId,
5 TurnId,
6 OrchestrationEvent,
7 type OrchestrationThreadActivity,
8} from "@t3tools/contracts";
9import { it } from "@effect/vitest";
10import * as Clock from "effect/Clock";
11import * as Effect from "effect/Effect";
12import * as Schema from "effect/Schema";
13import * as Stream from "effect/Stream";
14import * as TestClock from "effect/testing/TestClock";
15import { describe, expect } from "vite-plus/test";
16
17import {
18 coalesceLiveToolUpdatedEvents,
19 makeThreadLiveEventCoalescer,
20} from "./ThreadLiveEventCoalescer.ts";
21
22const threadId = ThreadId.make("thread-coalescer-test");
23const turnId = TurnId.make("turn-coalescer-test");
24const encodeEvent = Schema.encodeSync(Schema.fromJsonString(OrchestrationEvent));
25
26function makeToolActivity(
27 sequence: number,
28 options: {
29 readonly kind?: "tool.updated" | "tool.completed";
30 readonly toolCallId?: string;
31 readonly turnId?: TurnId;
32 } = {},
33): OrchestrationEvent {
34 const {
35 kind = "tool.updated",
36 toolCallId = "call-edit",
37 turnId: activityTurnId = turnId,
38 } = options;
39 const activity: OrchestrationThreadActivity = {
40 id: EventId.make(`activity-${sequence}`),
41 tone: "tool",
42 kind,
43 summary: "Editing app.ts",
44 payload: {
45 itemType: "file_change",
46 title: "Editing app.ts",
47 data: toolCallId ? { toolCallId } : {},
48 },
49 turnId: activityTurnId,
50 createdAt: "2026-01-01T00:00:01.000Z",
51 };
52 return {
53 sequence,
54 eventId: EventId.make(`event-${sequence}`),
55 aggregateKind: "thread",
56 aggregateId: threadId,
57 occurredAt: "2026-01-01T00:00:01.000Z",
58 commandId: null,
59 causationEventId: null,
60 correlationId: null,
61 metadata: {},
62 type: "thread.activity-appended",
63 payload: { threadId, activity },
64 };
65}
66
67function makeMessage(sequence: number, text = "Still working"): OrchestrationEvent {
68 return {
69 sequence,
70 eventId: EventId.make(`event-${sequence}`),
71 aggregateKind: "thread",
72 aggregateId: threadId,
73 occurredAt: "2026-01-01T00:00:02.000Z",
74 commandId: null,
75 causationEventId: null,
76 correlationId: null,
77 metadata: {},
78 type: "thread.message-sent",
79 payload: {
80 threadId,
81 messageId: MessageId.make(`message-${sequence}`),
82 role: "assistant",
83 text,
84 turnId,
85 streaming: false,
86 createdAt: "2026-01-01T00:00:02.000Z",
87 updatedAt: "2026-01-01T00:00:02.000Z",
88 },
89 };
90}
91
92describe("ThreadLiveEventCoalescer", () => {
93 it("coalesces only calls with a stable toolCallId", () => {
94 const events = [
95 makeToolActivity(1, { toolCallId: "call-a" }),
96 makeToolActivity(2, { toolCallId: "call-b" }),
97 makeToolActivity(3, { toolCallId: "call-a" }),
98 ];
99
100 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3]);
101 });
102
103 it("preserves parallel same-label calls without a stable toolCallId", () => {
104 const events = [
105 makeToolActivity(1, { toolCallId: "" }),
106 makeToolActivity(2, { toolCallId: "" }),
107 makeToolActivity(3, { kind: "tool.completed", toolCallId: "" }),
108 ];
109
110 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([1, 2, 3]);
111 });
112
113 it("does not coalesce stable tool calls across turns", () => {
114 const events = [
115 makeToolActivity(1, { turnId: TurnId.make("turn-old") }),
116 makeToolActivity(2, { turnId: TurnId.make("turn-new") }),
117 ];
118
119 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([1, 2]);
120 });
121
122 it("flushes a stable update run before a completion boundary", () => {
123 const events = [
124 makeToolActivity(1),
125 makeToolActivity(2),
126 makeToolActivity(3, { kind: "tool.completed" }),
127 makeToolActivity(4),
128 ];
129
130 expect(coalesceLiveToolUpdatedEvents(events).map((event) => event.sequence)).toEqual([2, 3, 4]);
131 });
132
133 it.effect("flushes pending tool updates as soon as an unrelated event arrives", () =>
134 Effect.scoped(
135 Effect.gen(function* () {
136 const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "500 millis" });
137 const startedAt = yield* Clock.currentTimeMillis;
138 yield* Effect.forEach(
139 Array.from({ length: 10 }, (_, index) => index + 2),
140 (sequence) => coalescer.offer({ kind: "event", event: makeToolActivity(sequence) }),
141 { discard: true },
142 );
143 yield* coalescer.offer({ kind: "event", event: makeMessage(12) });
144
145 expect(yield* Clock.currentTimeMillis).toBe(startedAt);
146 expect(
147 (yield* coalescer.stream.pipe(Stream.take(2), Stream.runCollect)).map((item) =>
148 item.kind === "event" ? item.event.sequence : item.kind,
149 ),
150 ).toEqual([11, 12]);
151 }),
152 ).pipe(Effect.provide(TestClock.layer())),
153 );
154
155 it.effect("flushes pending tool updates as soon as a synchronization marker arrives", () =>
156 Effect.scoped(
157 Effect.gen(function* () {
158 const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "500 millis" });
159 const startedAt = yield* Clock.currentTimeMillis;
160 yield* coalescer.offer({ kind: "event", event: makeToolActivity(2) });
161 yield* coalescer.offer({ kind: "event", event: makeToolActivity(3) });
162 yield* coalescer.offer({ kind: "synchronized" });
163
164 expect(yield* Clock.currentTimeMillis).toBe(startedAt);
165 expect(
166 (yield* coalescer.stream.pipe(Stream.take(2), Stream.runCollect)).map((item) =>
167 item.kind === "event" ? item.event.sequence : item.kind,
168 ),
169 ).toEqual([3, "synchronized"]);
170 }),
171 ).pipe(Effect.provide(TestClock.layer())),
172 );
173
174 it.effect("fails and clears pending updates when their serialized payload fills the budget", () =>
175 Effect.scoped(
176 Effect.gen(function* () {
177 const first = makeToolActivity(1);
178 const coalescer = yield* makeThreadLiveEventCoalescer({
179 coalesceWindow: "500 millis",
180 maxSerializedBytes: Buffer.byteLength(encodeEvent(first)),
181 });
182 yield* coalescer.offer({ kind: "event", event: first });
183 expect(yield* coalescer.usage).toEqual({
184 retainedItems: 1,
185 retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
186 });
187
188 const overflow = yield* coalescer
189 .offer({ kind: "event", event: makeToolActivity(2) })
190 .pipe(Effect.result);
191 expect(overflow._tag).toBe("Failure");
192 yield* coalescer.closed;
193 expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
194 const marker = yield* coalescer.offer({ kind: "synchronized" }).pipe(Effect.result);
195 expect(marker._tag).toBe("Failure");
196 const delivered = yield* coalescer.stream.pipe(Stream.runCollect, Effect.result);
197 expect(delivered._tag).toBe("Failure");
198 }),
199 ),
200 );
201
202 it.effect("keeps the flush timer alive when an offer's shorter scope closes", () =>
203 Effect.scoped(
204 Effect.gen(function* () {
205 const coalescer = yield* makeThreadLiveEventCoalescer({ coalesceWindow: "50 millis" });
206 yield* Effect.scoped(coalescer.offer({ kind: "event", event: makeToolActivity(1) }));
207 yield* TestClock.adjust("50 millis");
208 const items = yield* coalescer.stream.pipe(Stream.take(1), Stream.runCollect);
209 expect(
210 items.map((item) => (item.kind === "event" ? item.event.sequence : item.kind)),
211 ).toEqual([1]);
212 }),
213 ),
214 );
215
216 it.effect("keeps an unacknowledged batch charged and clears later events on overflow", () =>
217 Effect.scoped(
218 Effect.gen(function* () {
219 const coalescer = yield* makeThreadLiveEventCoalescer({ maxItems: 3 });
220 const first = makeMessage(1, "é".repeat(1_024));
221 yield* coalescer.offer({ kind: "event", event: first });
222
223 yield* Effect.scoped(
224 Effect.gen(function* () {
225 const pull = yield* Stream.toPull(coalescer.stream);
226 const batch = yield* pull;
227 expect(
228 batch.map((item) => (item.kind === "event" ? item.event.sequence : null)),
229 ).toEqual([1]);
230 yield* coalescer.offer({ kind: "event", event: makeMessage(2) });
231 yield* coalescer.offer({ kind: "event", event: makeToolActivity(3) });
232 expect((yield* coalescer.usage).retainedItems).toBe(3);
233
234 const overflow = yield* coalescer
235 .offer({ kind: "event", event: makeToolActivity(4, { kind: "tool.completed" }) })
236 .pipe(Effect.result);
237 expect(overflow._tag).toBe("Failure");
238 // Do not pull or acknowledge the batch. Cleanup must still finish.
239 yield* coalescer.closed;
240 expect(yield* coalescer.usage).toEqual({
241 retainedItems: 1,
242 retainedSerializedBytes: Buffer.byteLength(encodeEvent(first)),
243 });
244 }),
245 );
246 expect(yield* coalescer.usage).toEqual({ retainedItems: 0, retainedSerializedBytes: 0 });
247 }),
248 ),
249 );
250});