@cloudflare/ai-chat 0.0.7 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +126 -74
  10. package/dist/index.js +753 -632
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +248 -259
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +12 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +850 -1132
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +396 -462
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +314 -0
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +186 -0
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +85 -23
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
@@ -0,0 +1,282 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ autoTransformMessage,
4
+ autoTransformMessages,
5
+ isUIMessage,
6
+ needsMigration,
7
+ analyzeCorruption,
8
+ migrateToUIMessage,
9
+ migrateMessagesToUIFormat
10
+ } from "../ai-chat-v5-migration";
11
+ import type { UIMessage } from "ai";
12
+
13
+ describe("AI SDK v5 Migration", () => {
14
+ describe("isUIMessage", () => {
15
+ it("returns true for messages with parts array", () => {
16
+ expect(
17
+ isUIMessage({
18
+ id: "1",
19
+ role: "user",
20
+ parts: [{ type: "text", text: "hi" }]
21
+ })
22
+ ).toBe(true);
23
+ });
24
+
25
+ it("returns false for legacy messages with string content", () => {
26
+ expect(isUIMessage({ id: "1", role: "user", content: "hello" })).toBe(
27
+ false
28
+ );
29
+ });
30
+
31
+ it("returns false for null/undefined", () => {
32
+ expect(isUIMessage(null)).toBe(false);
33
+ expect(isUIMessage(undefined)).toBe(false);
34
+ });
35
+
36
+ it("returns false for non-object types", () => {
37
+ expect(isUIMessage("string")).toBe(false);
38
+ expect(isUIMessage(42)).toBe(false);
39
+ });
40
+ });
41
+
42
+ describe("autoTransformMessage", () => {
43
+ it("passes through UIMessages unchanged", () => {
44
+ const msg: UIMessage = {
45
+ id: "1",
46
+ role: "user",
47
+ parts: [{ type: "text", text: "hello" }]
48
+ };
49
+ expect(autoTransformMessage(msg)).toBe(msg);
50
+ });
51
+
52
+ it("transforms legacy string content to text part", () => {
53
+ const result = autoTransformMessage({
54
+ id: "legacy-1",
55
+ role: "user",
56
+ content: "Hello world"
57
+ });
58
+ expect(result.id).toBe("legacy-1");
59
+ expect(result.role).toBe("user");
60
+ expect(result.parts.length).toBe(1);
61
+ expect(result.parts[0].type).toBe("text");
62
+ expect((result.parts[0] as { text: string }).text).toBe("Hello world");
63
+ });
64
+
65
+ it("transforms legacy tool invocations", () => {
66
+ const result = autoTransformMessage({
67
+ id: "tool-1",
68
+ role: "assistant",
69
+ content: "",
70
+ toolInvocations: [
71
+ {
72
+ toolCallId: "call_1",
73
+ toolName: "getWeather",
74
+ args: { city: "London" },
75
+ state: "result",
76
+ result: "Sunny"
77
+ }
78
+ ]
79
+ });
80
+
81
+ expect(result.parts.length).toBe(1);
82
+ const toolPart = result.parts[0] as {
83
+ type: string;
84
+ toolCallId: string;
85
+ state: string;
86
+ input: Record<string, unknown>;
87
+ output: unknown;
88
+ };
89
+ expect(toolPart.type).toBe("tool-getWeather");
90
+ expect(toolPart.toolCallId).toBe("call_1");
91
+ expect(toolPart.state).toBe("output-available");
92
+ expect(toolPart.input).toEqual({ city: "London" });
93
+ expect(toolPart.output).toBe("Sunny");
94
+ });
95
+
96
+ it("maps tool invocation states correctly", () => {
97
+ const states = {
98
+ "partial-call": "input-streaming",
99
+ call: "input-available",
100
+ result: "output-available",
101
+ error: "output-error"
102
+ };
103
+
104
+ for (const [v4State, v5State] of Object.entries(states)) {
105
+ const result = autoTransformMessage({
106
+ role: "assistant",
107
+ content: "",
108
+ toolInvocations: [
109
+ {
110
+ toolCallId: `call_${v4State}`,
111
+ toolName: "test",
112
+ args: {},
113
+ state: v4State as "partial-call" | "call" | "result" | "error"
114
+ }
115
+ ]
116
+ });
117
+
118
+ const toolPart = result.parts[0] as { state: string };
119
+ expect(toolPart.state).toBe(v5State);
120
+ }
121
+ });
122
+
123
+ it("handles corrupt array content format", () => {
124
+ const result = autoTransformMessage({
125
+ id: "corrupt-1",
126
+ role: "user",
127
+ content: [{ type: "text", text: "Hello from array" }]
128
+ } as unknown as { id: string; role: string; content: unknown });
129
+
130
+ expect(result.parts.length).toBe(1);
131
+ expect((result.parts[0] as { text: string }).text).toBe(
132
+ "Hello from array"
133
+ );
134
+ });
135
+
136
+ it("transforms reasoning field to reasoning part", () => {
137
+ const result = autoTransformMessage({
138
+ id: "reasoning-1",
139
+ role: "assistant",
140
+ content: "Final answer",
141
+ reasoning: "Let me think about this..."
142
+ });
143
+
144
+ // When reasoning exists, the content fallback (`!parts.length`) doesn't trigger.
145
+ // Only the reasoning part is created. The `content` field is only used
146
+ // as fallback when there are no other parts.
147
+ expect(result.parts.length).toBe(1);
148
+ expect(result.parts[0].type).toBe("reasoning");
149
+ expect((result.parts[0] as { text: string }).text).toBe(
150
+ "Let me think about this..."
151
+ );
152
+ });
153
+
154
+ it("transforms file parts from legacy format (without parts array)", () => {
155
+ // Note: if the message has a `parts` array, isUIMessage() returns true
156
+ // and the message passes through unchanged. File transformation only
157
+ // applies to messages that have `parts` but are NOT UIMessages.
158
+ // In practice, legacy messages with file `parts` also have `content`
159
+ // as a string, and crucially `parts` contains objects with `data`
160
+ // (not the UIMessage part shape). However, isUIMessage only checks
161
+ // Array.isArray(parts), so it still matches.
162
+ //
163
+ // To test the actual data→url transformation, we construct a message
164
+ // that won't match isUIMessage (no `parts` key at the top level, but
165
+ // file data embedded differently). In practice this path is hit when
166
+ // messages come from v4 storage with toolInvocations + file data.
167
+ const result = autoTransformMessage({
168
+ id: "file-1",
169
+ role: "assistant",
170
+ content: "",
171
+ toolInvocations: [
172
+ {
173
+ toolCallId: "call_file",
174
+ toolName: "generateImage",
175
+ args: {},
176
+ state: "result",
177
+ result: "image.png"
178
+ }
179
+ ]
180
+ });
181
+
182
+ // Should have tool part with result
183
+ const toolPart = result.parts[0] as {
184
+ type: string;
185
+ state: string;
186
+ output: unknown;
187
+ };
188
+ expect(toolPart.type).toBe("tool-generateImage");
189
+ expect(toolPart.state).toBe("output-available");
190
+ expect(toolPart.output).toBe("image.png");
191
+ });
192
+
193
+ it("uses 'data' role mapped to 'system'", () => {
194
+ const result = autoTransformMessage({
195
+ id: "data-1",
196
+ role: "data",
197
+ content: "System instruction"
198
+ });
199
+ expect(result.role).toBe("system");
200
+ });
201
+
202
+ it("generates fallback id when none provided", () => {
203
+ const result = autoTransformMessage(
204
+ {
205
+ role: "user",
206
+ content: "no id"
207
+ },
208
+ 5
209
+ );
210
+ expect(result.id).toBe("msg-5");
211
+ });
212
+ });
213
+
214
+ describe("autoTransformMessages", () => {
215
+ it("transforms array of mixed-format messages", () => {
216
+ const input = [
217
+ { id: "1", role: "user", content: "Hello" },
218
+ {
219
+ id: "2",
220
+ role: "assistant",
221
+ parts: [{ type: "text", text: "Hi!" }]
222
+ }
223
+ ];
224
+
225
+ const result = autoTransformMessages(input);
226
+ expect(result.length).toBe(2);
227
+ expect(result[0].parts[0].type).toBe("text");
228
+ expect(result[1].parts[0].type).toBe("text");
229
+ });
230
+
231
+ it("handles empty array", () => {
232
+ expect(autoTransformMessages([])).toEqual([]);
233
+ });
234
+ });
235
+
236
+ describe("deprecated functions", () => {
237
+ it("migrateToUIMessage works but is deprecated", () => {
238
+ const result = migrateToUIMessage({
239
+ id: "dep-1",
240
+ role: "user",
241
+ content: "test"
242
+ });
243
+ expect(result.parts[0].type).toBe("text");
244
+ });
245
+
246
+ it("migrateMessagesToUIFormat works but is deprecated", () => {
247
+ const result = migrateMessagesToUIFormat([
248
+ { id: "dep-2", role: "user", content: "test" }
249
+ ]);
250
+ expect(result.length).toBe(1);
251
+ });
252
+
253
+ it("needsMigration works but is deprecated", () => {
254
+ expect(
255
+ needsMigration([{ id: "1", role: "user", content: "old format" }])
256
+ ).toBe(true);
257
+ expect(
258
+ needsMigration([
259
+ { id: "1", role: "user", parts: [{ type: "text", text: "new" }] }
260
+ ])
261
+ ).toBe(false);
262
+ });
263
+
264
+ it("analyzeCorruption reports stats correctly", () => {
265
+ const stats = analyzeCorruption([
266
+ { id: "1", role: "user", parts: [{ type: "text", text: "clean" }] },
267
+ { id: "2", role: "user", content: "legacy string" },
268
+ {
269
+ id: "3",
270
+ role: "user",
271
+ content: [{ type: "text", text: "corrupt array" }]
272
+ }
273
+ ]);
274
+
275
+ expect(stats.total).toBe(3);
276
+ expect(stats.clean).toBe(1);
277
+ expect(stats.legacyString).toBe(1);
278
+ expect(stats.corruptArray).toBe(1);
279
+ expect(stats.unknown).toBe(0);
280
+ });
281
+ });
282
+ });
@@ -106,7 +106,7 @@ describe("Non-SSE Response Handling - PR #761", () => {
106
106
  const doneMessage = chatResponses.find((m) => m.done === true);
107
107
  expect(doneMessage).toBeDefined();
108
108
 
109
- ws.close();
109
+ ws.close(1000);
110
110
  });
111
111
 
112
112
  it("should use consistent id across text-start, text-delta, and text-end events", async () => {
@@ -181,6 +181,6 @@ describe("Non-SSE Response Handling - PR #761", () => {
181
181
  expect(event.id).toBe(requestId);
182
182
  }
183
183
 
184
- ws.close();
184
+ ws.close(1000);
185
185
  });
186
186
  });
@@ -0,0 +1,362 @@
1
+ import { env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import { MessageType } from "../types";
4
+ import { connectChatWS } from "./test-utils";
5
+ import { getAgentByName } from "agents";
6
+
7
+ describe("onFinish cleanup (framework-managed)", () => {
8
+ it("cleans up abort controller after stream completes even without user passing onFinish", async () => {
9
+ const room = crypto.randomUUID();
10
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
11
+
12
+ let resolvePromise: (value: boolean) => void;
13
+ const donePromise = new Promise<boolean>((res) => {
14
+ resolvePromise = res;
15
+ });
16
+ const timeout = setTimeout(() => resolvePromise(false), 3000);
17
+
18
+ ws.addEventListener("message", (e: MessageEvent) => {
19
+ const data = JSON.parse(e.data as string);
20
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
21
+ clearTimeout(timeout);
22
+ resolvePromise(true);
23
+ }
24
+ });
25
+
26
+ // Send first request
27
+ ws.send(
28
+ JSON.stringify({
29
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
30
+ id: "req-cleanup-1",
31
+ init: {
32
+ method: "POST",
33
+ body: JSON.stringify({
34
+ messages: [
35
+ {
36
+ id: "msg-cleanup-1",
37
+ role: "user",
38
+ parts: [{ type: "text", text: "Hello" }]
39
+ }
40
+ ]
41
+ })
42
+ }
43
+ })
44
+ );
45
+
46
+ const done = await donePromise;
47
+ expect(done).toBe(true);
48
+
49
+ // Send a second request to prove the agent is still healthy
50
+ // (no leaked abort controllers causing issues)
51
+ let resolveSecond: (value: boolean) => void;
52
+ const secondDone = new Promise<boolean>((res) => {
53
+ resolveSecond = res;
54
+ });
55
+ const timeout2 = setTimeout(() => resolveSecond(false), 3000);
56
+
57
+ ws.addEventListener("message", (e: MessageEvent) => {
58
+ const data = JSON.parse(e.data as string);
59
+ if (
60
+ data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&
61
+ data.done &&
62
+ data.id === "req-cleanup-2"
63
+ ) {
64
+ clearTimeout(timeout2);
65
+ resolveSecond(true);
66
+ }
67
+ });
68
+
69
+ ws.send(
70
+ JSON.stringify({
71
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
72
+ id: "req-cleanup-2",
73
+ init: {
74
+ method: "POST",
75
+ body: JSON.stringify({
76
+ messages: [
77
+ {
78
+ id: "msg-cleanup-1",
79
+ role: "user",
80
+ parts: [{ type: "text", text: "Hello" }]
81
+ },
82
+ {
83
+ id: "msg-cleanup-2",
84
+ role: "user",
85
+ parts: [{ type: "text", text: "Second message" }]
86
+ }
87
+ ]
88
+ })
89
+ }
90
+ })
91
+ );
92
+
93
+ const second = await secondDone;
94
+ expect(second).toBe(true);
95
+
96
+ ws.close(1000);
97
+ });
98
+
99
+ it("cancellation still works after cleanup is moved to _reply", async () => {
100
+ const room = crypto.randomUUID();
101
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
102
+ await new Promise((r) => setTimeout(r, 50));
103
+
104
+ // Send a request and immediately cancel it
105
+ ws.send(
106
+ JSON.stringify({
107
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
108
+ id: "req-cancel-test",
109
+ init: {
110
+ method: "POST",
111
+ body: JSON.stringify({
112
+ messages: [
113
+ {
114
+ id: "cancel-1",
115
+ role: "user",
116
+ parts: [{ type: "text", text: "Cancel me" }]
117
+ }
118
+ ]
119
+ })
120
+ }
121
+ })
122
+ );
123
+
124
+ ws.send(
125
+ JSON.stringify({
126
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL,
127
+ id: "req-cancel-test"
128
+ })
129
+ );
130
+
131
+ // Wait a moment for processing
132
+ await new Promise((r) => setTimeout(r, 500));
133
+
134
+ // Agent should still be alive -- send another request
135
+ let resolvePromise: (value: boolean) => void;
136
+ const donePromise = new Promise<boolean>((res) => {
137
+ resolvePromise = res;
138
+ });
139
+ const timeout = setTimeout(() => resolvePromise(false), 3000);
140
+
141
+ ws.addEventListener("message", (e: MessageEvent) => {
142
+ const data = JSON.parse(e.data as string);
143
+ if (
144
+ data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&
145
+ data.done &&
146
+ data.id === "req-after-cancel"
147
+ ) {
148
+ clearTimeout(timeout);
149
+ resolvePromise(true);
150
+ }
151
+ });
152
+
153
+ ws.send(
154
+ JSON.stringify({
155
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
156
+ id: "req-after-cancel",
157
+ init: {
158
+ method: "POST",
159
+ body: JSON.stringify({
160
+ messages: [
161
+ {
162
+ id: "after-cancel-1",
163
+ role: "user",
164
+ parts: [{ type: "text", text: "Still alive?" }]
165
+ }
166
+ ]
167
+ })
168
+ }
169
+ })
170
+ );
171
+
172
+ const done = await donePromise;
173
+ expect(done).toBe(true);
174
+
175
+ ws.close(1000);
176
+ });
177
+
178
+ it("multiple concurrent requests each get cleaned up", async () => {
179
+ const room = crypto.randomUUID();
180
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
181
+
182
+ const received: string[] = [];
183
+ ws.addEventListener("message", (e: MessageEvent) => {
184
+ try {
185
+ const data = JSON.parse(e.data as string);
186
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
187
+ received.push(data.id);
188
+ }
189
+ } catch {
190
+ // ignore
191
+ }
192
+ });
193
+
194
+ // Send two requests simultaneously
195
+ ws.send(
196
+ JSON.stringify({
197
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
198
+ id: "req-concurrent-1",
199
+ init: {
200
+ method: "POST",
201
+ body: JSON.stringify({
202
+ messages: [
203
+ {
204
+ id: "conc-1",
205
+ role: "user",
206
+ parts: [{ type: "text", text: "First" }]
207
+ }
208
+ ]
209
+ })
210
+ }
211
+ })
212
+ );
213
+
214
+ ws.send(
215
+ JSON.stringify({
216
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
217
+ id: "req-concurrent-2",
218
+ init: {
219
+ method: "POST",
220
+ body: JSON.stringify({
221
+ messages: [
222
+ {
223
+ id: "conc-1",
224
+ role: "user",
225
+ parts: [{ type: "text", text: "First" }]
226
+ },
227
+ {
228
+ id: "conc-2",
229
+ role: "user",
230
+ parts: [{ type: "text", text: "Second" }]
231
+ }
232
+ ]
233
+ })
234
+ }
235
+ })
236
+ );
237
+
238
+ // Wait for both to complete
239
+ await new Promise((r) => setTimeout(r, 2000));
240
+
241
+ // Both requests should have completed
242
+ expect(received).toContain("req-concurrent-1");
243
+ expect(received).toContain("req-concurrent-2");
244
+
245
+ ws.close(1000);
246
+ });
247
+
248
+ it("abort controllers are cleaned up after stream completion (count returns to 0)", async () => {
249
+ const room = crypto.randomUUID();
250
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
251
+
252
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
253
+
254
+ // Initially no abort controllers
255
+ expect(await agentStub.getAbortControllerCount()).toBe(0);
256
+
257
+ let resolvePromise: (value: boolean) => void;
258
+ const donePromise = new Promise<boolean>((res) => {
259
+ resolvePromise = res;
260
+ });
261
+ const timeout = setTimeout(() => resolvePromise(false), 3000);
262
+
263
+ ws.addEventListener("message", (e: MessageEvent) => {
264
+ const data = JSON.parse(e.data as string);
265
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
266
+ clearTimeout(timeout);
267
+ resolvePromise(true);
268
+ }
269
+ });
270
+
271
+ // Send a request
272
+ ws.send(
273
+ JSON.stringify({
274
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
275
+ id: "req-ac-check",
276
+ init: {
277
+ method: "POST",
278
+ body: JSON.stringify({
279
+ messages: [
280
+ {
281
+ id: "ac-1",
282
+ role: "user",
283
+ parts: [{ type: "text", text: "Hello" }]
284
+ }
285
+ ]
286
+ })
287
+ }
288
+ })
289
+ );
290
+
291
+ const done = await donePromise;
292
+ expect(done).toBe(true);
293
+
294
+ // Give _reply a moment to finish its cleanup after the stream completes
295
+ await new Promise((r) => setTimeout(r, 100));
296
+
297
+ // Abort controller should have been cleaned up by _reply
298
+ // even though our test worker's onChatMessage does NOT pass onFinish to streamText
299
+ expect(await agentStub.getAbortControllerCount()).toBe(0);
300
+
301
+ ws.close(1000);
302
+ });
303
+
304
+ it("abort controllers are cleaned up after multiple sequential requests", async () => {
305
+ const room = crypto.randomUUID();
306
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
307
+
308
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
309
+
310
+ // Send 3 sequential requests
311
+ for (let i = 0; i < 3; i++) {
312
+ let resolvePromise: (value: boolean) => void;
313
+ const donePromise = new Promise<boolean>((res) => {
314
+ resolvePromise = res;
315
+ });
316
+ const timeout = setTimeout(() => resolvePromise(false), 3000);
317
+
318
+ const listener = (e: MessageEvent) => {
319
+ const data = JSON.parse(e.data as string);
320
+ if (
321
+ data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE &&
322
+ data.done &&
323
+ data.id === `req-seq-${i}`
324
+ ) {
325
+ clearTimeout(timeout);
326
+ resolvePromise(true);
327
+ }
328
+ };
329
+ ws.addEventListener("message", listener);
330
+
331
+ ws.send(
332
+ JSON.stringify({
333
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
334
+ id: `req-seq-${i}`,
335
+ init: {
336
+ method: "POST",
337
+ body: JSON.stringify({
338
+ messages: [
339
+ {
340
+ id: `seq-${i}`,
341
+ role: "user",
342
+ parts: [{ type: "text", text: `Message ${i}` }]
343
+ }
344
+ ]
345
+ })
346
+ }
347
+ })
348
+ );
349
+
350
+ await donePromise;
351
+ ws.removeEventListener("message", listener);
352
+ }
353
+
354
+ // Wait for cleanup
355
+ await new Promise((r) => setTimeout(r, 100));
356
+
357
+ // All 3 abort controllers should be cleaned up
358
+ expect(await agentStub.getAbortControllerCount()).toBe(0);
359
+
360
+ ws.close(1000);
361
+ });
362
+ });