@cloudflare/ai-chat 0.1.5 → 0.1.7

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 (67) hide show
  1. package/dist/experimental/forever.d.ts +4 -13
  2. package/dist/experimental/forever.js +1 -46
  3. package/dist/experimental/forever.js.map +1 -1
  4. package/dist/index.d.ts +59 -4
  5. package/dist/index.js +150 -36
  6. package/dist/index.js.map +1 -1
  7. package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
  8. package/dist/message-builder-uSvexDl2.js.map +1 -0
  9. package/dist/react.js +96 -10
  10. package/dist/react.js.map +1 -1
  11. package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
  12. package/dist/types.d.ts +2 -1
  13. package/dist/types.js.map +1 -1
  14. package/package.json +7 -3
  15. package/CHANGELOG.md +0 -251
  16. package/dist/message-builder-Bwc_Umye.js.map +0 -1
  17. package/e2e/chat.spec.ts +0 -1703
  18. package/e2e/client-tools.spec.ts +0 -504
  19. package/e2e/llm.spec.ts +0 -637
  20. package/e2e/playwright.config.ts +0 -27
  21. package/e2e/worker.ts +0 -174
  22. package/e2e/wrangler.jsonc +0 -23
  23. package/scripts/build.ts +0 -32
  24. package/src/ai-chat-v5-migration.ts +0 -403
  25. package/src/experimental/forever.ts +0 -66
  26. package/src/index.ts +0 -2269
  27. package/src/message-builder.ts +0 -384
  28. package/src/react-tests/setup.ts +0 -3
  29. package/src/react-tests/use-agent-chat.test.tsx +0 -1435
  30. package/src/react-tests/vitest.config.ts +0 -20
  31. package/src/react.tsx +0 -1447
  32. package/src/resumable-stream.ts +0 -441
  33. package/src/tests/cancel-request.test.ts +0 -280
  34. package/src/tests/chat-context.test.ts +0 -85
  35. package/src/tests/chat-persistence.test.ts +0 -426
  36. package/src/tests/clear-history.test.ts +0 -132
  37. package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
  38. package/src/tests/client-tools-broadcast.test.ts +0 -138
  39. package/src/tests/client-tools-continuation.test.ts +0 -314
  40. package/src/tests/client-tools-reconnect.test.ts +0 -143
  41. package/src/tests/cloudflare-test.d.ts +0 -5
  42. package/src/tests/custom-body-continuation.test.ts +0 -309
  43. package/src/tests/custom-body.test.ts +0 -186
  44. package/src/tests/destroy.test.ts +0 -57
  45. package/src/tests/get-messages-endpoint.test.ts +0 -153
  46. package/src/tests/max-persisted-messages.test.ts +0 -201
  47. package/src/tests/merge-server-state.test.ts +0 -343
  48. package/src/tests/message-builder.test.ts +0 -808
  49. package/src/tests/migration.test.ts +0 -282
  50. package/src/tests/non-sse-response.test.ts +0 -186
  51. package/src/tests/onfinish-cleanup.test.ts +0 -362
  52. package/src/tests/plaintext-response.test.ts +0 -87
  53. package/src/tests/request-id.test.ts +0 -312
  54. package/src/tests/resumable-streaming.test.ts +0 -758
  55. package/src/tests/row-size-guard.test.ts +0 -374
  56. package/src/tests/sanitize-messages.test.ts +0 -325
  57. package/src/tests/test-utils.ts +0 -39
  58. package/src/tests/tsconfig.json +0 -10
  59. package/src/tests/validate-messages.test.ts +0 -269
  60. package/src/tests/vitest.config.ts +0 -30
  61. package/src/tests/worker.ts +0 -456
  62. package/src/tests/wrangler.jsonc +0 -50
  63. package/src/tests/ws-transport-abort.test.ts +0 -198
  64. package/src/types.ts +0 -152
  65. package/src/ws-chat-transport.ts +0 -227
  66. package/tsconfig.json +0 -4
  67. package/vitest.config.ts +0 -7
package/e2e/chat.spec.ts DELETED
@@ -1,1703 +0,0 @@
1
- import { test, expect } from "@playwright/test";
2
-
3
- // ── Helpers ──────────────────────────────────────────────────────────
4
-
5
- /** Message type constants (mirrors src/types.ts MessageType enum values) */
6
- const MessageType = {
7
- CF_AGENT_CHAT_MESSAGES: "cf_agent_chat_messages",
8
- CF_AGENT_USE_CHAT_REQUEST: "cf_agent_use_chat_request",
9
- CF_AGENT_USE_CHAT_RESPONSE: "cf_agent_use_chat_response",
10
- CF_AGENT_CHAT_CLEAR: "cf_agent_chat_clear",
11
- CF_AGENT_STREAM_RESUMING: "cf_agent_stream_resuming",
12
- CF_AGENT_STREAM_RESUME_ACK: "cf_agent_stream_resume_ack"
13
- } as const;
14
-
15
- type WSMessage = {
16
- type: string;
17
- [key: string]: unknown;
18
- };
19
-
20
- /**
21
- * Opens a real WebSocket to the agent inside the browser page context.
22
- * Returns helpers to send messages and collect responses.
23
- */
24
- function wsHelpers(baseURL: string) {
25
- const agentPath = (room: string) =>
26
- `${baseURL.replace("http", "ws")}/agents/chat-agent/${room}`;
27
-
28
- return { agentPath };
29
- }
30
-
31
- /**
32
- * Connects a WebSocket inside page.evaluate and returns collected messages.
33
- * We run everything inside the browser because Playwright's native WS
34
- * support is for intercepting, not initiating raw connections.
35
- */
36
- async function connectAndRun(
37
- page: import("@playwright/test").Page,
38
- wsUrl: string,
39
- actions: string // JS function body that receives (ws, resolve, reject, MessageType)
40
- ): Promise<WSMessage[]> {
41
- return page.evaluate(
42
- ({ url, actions, MT }) => {
43
- return new Promise<WSMessage[]>((resolve, reject) => {
44
- const ws = new WebSocket(url);
45
- const received: WSMessage[] = [];
46
-
47
- ws.onmessage = (e) => {
48
- try {
49
- received.push(JSON.parse(e.data as string));
50
- } catch {
51
- // ignore non-JSON
52
- }
53
- };
54
-
55
- ws.onerror = () => reject(new Error("WebSocket error"));
56
-
57
- ws.onopen = () => {
58
- try {
59
- // Execute the caller-provided action script
60
- const fn = new Function(
61
- "ws",
62
- "resolve",
63
- "reject",
64
- "received",
65
- "MT",
66
- actions
67
- );
68
- fn(ws, resolve, reject, received, MT);
69
- } catch (err) {
70
- reject(err);
71
- }
72
- };
73
- });
74
- },
75
- { url: wsUrl, actions, MT: MessageType }
76
- );
77
- }
78
-
79
- // ── Tests ────────────────────────────────────────────────────────────
80
-
81
- test.describe("AIChatAgent e2e", () => {
82
- test.beforeEach(async ({ page }) => {
83
- // Navigate to a blank page so we have a browser context for WebSockets
84
- await page.goto("about:blank");
85
- });
86
-
87
- test("chat message round-trip: send request, receive streamed response", async ({
88
- page,
89
- baseURL
90
- }) => {
91
- const { agentPath } = wsHelpers(baseURL!);
92
- const room = crypto.randomUUID();
93
-
94
- const messages = await connectAndRun(
95
- page,
96
- agentPath(room),
97
- `
98
- const userMsg = {
99
- id: "user-1",
100
- role: "user",
101
- parts: [{ type: "text", text: "Hello" }]
102
- };
103
-
104
- ws.send(JSON.stringify({
105
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
106
- id: "req-1",
107
- init: {
108
- method: "POST",
109
- body: JSON.stringify({ messages: [userMsg] })
110
- }
111
- }));
112
-
113
- // Wait for the done signal
114
- const check = setInterval(() => {
115
- const doneMsg = received.find(
116
- m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done === true
117
- );
118
- if (doneMsg) {
119
- clearInterval(check);
120
- ws.close();
121
- resolve(received);
122
- }
123
- }, 50);
124
-
125
- // Timeout safety
126
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
127
- `
128
- );
129
-
130
- // Note: The sender is excluded from CF_AGENT_CHAT_MESSAGES broadcasts
131
- // (by design — only other connections receive it). So we only check
132
- // for the stream response here. Multi-connection sync is tested separately.
133
-
134
- // Should have received stream response chunks
135
- const streamResponses = messages.filter(
136
- (m) => m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE
137
- );
138
- expect(streamResponses.length).toBeGreaterThanOrEqual(2); // at least one chunk + done
139
-
140
- // Should have text-start, text-delta, text-end events
141
- const nonDoneResponses = streamResponses.filter(
142
- (m) => !m.done && typeof m.body === "string" && (m.body as string).trim()
143
- );
144
- const bodies = nonDoneResponses.map((m) => JSON.parse(m.body as string));
145
- const types = bodies.map((b: { type: string }) => b.type);
146
- expect(types).toContain("text-start");
147
- expect(types).toContain("text-delta");
148
- expect(types).toContain("text-end");
149
-
150
- // The text-delta should contain the response text
151
- const deltas = bodies.filter(
152
- (b: { type: string }) => b.type === "text-delta"
153
- );
154
- const fullText = deltas.map((d: { delta: string }) => d.delta).join("");
155
- expect(fullText).toBe("Hello from e2e agent!");
156
-
157
- // The final message should be done=true
158
- const lastMsg = streamResponses[streamResponses.length - 1];
159
- expect(lastMsg.done).toBe(true);
160
- });
161
-
162
- test("message persistence: messages survive reconnection", async ({
163
- page,
164
- baseURL
165
- }) => {
166
- const { agentPath } = wsHelpers(baseURL!);
167
- const room = crypto.randomUUID();
168
-
169
- // First connection: send a message
170
- await connectAndRun(
171
- page,
172
- agentPath(room),
173
- `
174
- const userMsg = {
175
- id: "persist-1",
176
- role: "user",
177
- parts: [{ type: "text", text: "Remember me" }]
178
- };
179
-
180
- ws.send(JSON.stringify({
181
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
182
- id: "req-persist",
183
- init: {
184
- method: "POST",
185
- body: JSON.stringify({ messages: [userMsg] })
186
- }
187
- }));
188
-
189
- const check = setInterval(() => {
190
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
191
- clearInterval(check);
192
- ws.close();
193
- resolve(received);
194
- }
195
- }, 50);
196
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
197
- `
198
- );
199
-
200
- // Verify via HTTP GET /get-messages
201
- const res = await page.request.get(
202
- `${baseURL}/agents/chat-agent/${room}/get-messages`
203
- );
204
- expect(res.ok()).toBe(true);
205
-
206
- const persisted = await res.json();
207
- expect(Array.isArray(persisted)).toBe(true);
208
- expect(persisted.length).toBeGreaterThanOrEqual(2); // user + assistant
209
-
210
- // User message should be persisted
211
- const userMsg = persisted.find((m: { id: string }) => m.id === "persist-1");
212
- expect(userMsg).toBeTruthy();
213
- expect(userMsg.role).toBe("user");
214
-
215
- // Assistant response should be persisted
216
- const assistantMsgs = persisted.filter(
217
- (m: { role: string }) => m.role === "assistant"
218
- );
219
- expect(assistantMsgs.length).toBeGreaterThanOrEqual(1);
220
- });
221
-
222
- test("clear history: clears all messages and notifies other connections", async ({
223
- page,
224
- baseURL
225
- }) => {
226
- const { agentPath } = wsHelpers(baseURL!);
227
- const room = crypto.randomUUID();
228
- const wsUrl = agentPath(room);
229
-
230
- // Send a message first
231
- await connectAndRun(
232
- page,
233
- wsUrl,
234
- `
235
- ws.send(JSON.stringify({
236
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
237
- id: "req-clear",
238
- init: {
239
- method: "POST",
240
- body: JSON.stringify({
241
- messages: [{
242
- id: "clear-msg-1",
243
- role: "user",
244
- parts: [{ type: "text", text: "About to be cleared" }]
245
- }]
246
- })
247
- }
248
- }));
249
-
250
- const check = setInterval(() => {
251
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
252
- clearInterval(check);
253
- ws.close();
254
- resolve(received);
255
- }
256
- }, 50);
257
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
258
- `
259
- );
260
-
261
- // Verify messages exist
262
- const before = await page.request.get(
263
- `${baseURL}/agents/chat-agent/${room}/get-messages`
264
- );
265
- const beforeData = await before.json();
266
- expect(beforeData.length).toBeGreaterThanOrEqual(1);
267
-
268
- // Send clear from a new connection
269
- await connectAndRun(
270
- page,
271
- wsUrl,
272
- `
273
- ws.send(JSON.stringify({ type: MT.CF_AGENT_CHAT_CLEAR }));
274
- // Wait a bit for the clear to process
275
- setTimeout(() => { ws.close(); resolve(received); }, 500);
276
- `
277
- );
278
-
279
- // Verify messages are cleared
280
- const after = await page.request.get(
281
- `${baseURL}/agents/chat-agent/${room}/get-messages`
282
- );
283
- const afterData = await after.json();
284
- expect(afterData.length).toBe(0);
285
- });
286
-
287
- test("multi-connection sync: second connection receives broadcast", async ({
288
- page,
289
- baseURL
290
- }) => {
291
- const { agentPath } = wsHelpers(baseURL!);
292
- const room = crypto.randomUUID();
293
- const wsUrl = agentPath(room);
294
-
295
- // Open two WebSocket connections and send from the first.
296
- // The second should receive the CF_AGENT_CHAT_MESSAGES broadcast
297
- // AND the streamed response.
298
- const result = await page.evaluate(
299
- ({ url, MT }) => {
300
- return new Promise<{
301
- ws1Messages: Array<{ type: string; [k: string]: unknown }>;
302
- ws2Messages: Array<{ type: string; [k: string]: unknown }>;
303
- }>((resolve) => {
304
- const ws1Messages: Array<{ type: string; [k: string]: unknown }> = [];
305
- const ws2Messages: Array<{ type: string; [k: string]: unknown }> = [];
306
-
307
- const ws1 = new WebSocket(url);
308
- const ws2 = new WebSocket(url);
309
-
310
- let ws1Open = false;
311
- let ws2Open = false;
312
-
313
- function maybeSend() {
314
- if (!ws1Open || !ws2Open) return;
315
-
316
- // Give connections a moment to fully register
317
- setTimeout(() => {
318
- ws1.send(
319
- JSON.stringify({
320
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
321
- id: "req-sync",
322
- init: {
323
- method: "POST",
324
- body: JSON.stringify({
325
- messages: [
326
- {
327
- id: "sync-1",
328
- role: "user",
329
- parts: [{ type: "text", text: "Sync test" }]
330
- }
331
- ]
332
- })
333
- }
334
- })
335
- );
336
- }, 100);
337
- }
338
-
339
- ws1.onopen = () => {
340
- ws1Open = true;
341
- maybeSend();
342
- };
343
- ws2.onopen = () => {
344
- ws2Open = true;
345
- maybeSend();
346
- };
347
-
348
- ws1.onmessage = (e) => {
349
- try {
350
- ws1Messages.push(JSON.parse(e.data));
351
- } catch {}
352
- };
353
- ws2.onmessage = (e) => {
354
- try {
355
- ws2Messages.push(JSON.parse(e.data));
356
- } catch {}
357
- };
358
-
359
- // Wait for stream to complete on ws1
360
- const check = setInterval(() => {
361
- const done = ws1Messages.find(
362
- (m) => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done === true
363
- );
364
- if (done) {
365
- clearInterval(check);
366
- // Give ws2 a moment to receive broadcasts
367
- setTimeout(() => {
368
- ws1.close();
369
- ws2.close();
370
- resolve({ ws1Messages, ws2Messages });
371
- }, 200);
372
- }
373
- }, 50);
374
-
375
- setTimeout(() => {
376
- clearInterval(check);
377
- ws1.close();
378
- ws2.close();
379
- resolve({ ws1Messages, ws2Messages });
380
- }, 8000);
381
- });
382
- },
383
- { url: wsUrl, MT: MessageType }
384
- );
385
-
386
- // ws2 should have received the chat messages broadcast
387
- const ws2ChatMsgs = result.ws2Messages.filter(
388
- (m) => m.type === MessageType.CF_AGENT_CHAT_MESSAGES
389
- );
390
- expect(ws2ChatMsgs.length).toBeGreaterThanOrEqual(1);
391
-
392
- // ws2 should have received the stream response (it's broadcast to all)
393
- const ws2StreamResponses = result.ws2Messages.filter(
394
- (m) => m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE
395
- );
396
- expect(ws2StreamResponses.length).toBeGreaterThanOrEqual(1);
397
- });
398
-
399
- test("separate rooms are isolated", async ({ page, baseURL }) => {
400
- const { agentPath } = wsHelpers(baseURL!);
401
- const roomA = crypto.randomUUID();
402
- const roomB = crypto.randomUUID();
403
-
404
- // Send a message to room A
405
- await connectAndRun(
406
- page,
407
- agentPath(roomA),
408
- `
409
- ws.send(JSON.stringify({
410
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
411
- id: "req-iso-a",
412
- init: {
413
- method: "POST",
414
- body: JSON.stringify({
415
- messages: [{
416
- id: "iso-a",
417
- role: "user",
418
- parts: [{ type: "text", text: "Room A" }]
419
- }]
420
- })
421
- }
422
- }));
423
- const check = setInterval(() => {
424
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
425
- clearInterval(check);
426
- ws.close();
427
- resolve(received);
428
- }
429
- }, 50);
430
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
431
- `
432
- );
433
-
434
- // Room A should have messages
435
- const resA = await page.request.get(
436
- `${baseURL}/agents/chat-agent/${roomA}/get-messages`
437
- );
438
- const dataA = await resA.json();
439
- expect(dataA.length).toBeGreaterThanOrEqual(2);
440
-
441
- // Room B should be empty
442
- const resB = await page.request.get(
443
- `${baseURL}/agents/chat-agent/${roomB}/get-messages`
444
- );
445
- const dataB = await resB.json();
446
- expect(dataB.length).toBe(0);
447
- });
448
-
449
- test("multiple messages accumulate in conversation", async ({
450
- page,
451
- baseURL
452
- }) => {
453
- const { agentPath } = wsHelpers(baseURL!);
454
- const room = crypto.randomUUID();
455
- const wsUrl = agentPath(room);
456
-
457
- // Send first message
458
- await connectAndRun(
459
- page,
460
- wsUrl,
461
- `
462
- ws.send(JSON.stringify({
463
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
464
- id: "req-multi-1",
465
- init: {
466
- method: "POST",
467
- body: JSON.stringify({
468
- messages: [{
469
- id: "multi-1",
470
- role: "user",
471
- parts: [{ type: "text", text: "First" }]
472
- }]
473
- })
474
- }
475
- }));
476
- const check = setInterval(() => {
477
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
478
- clearInterval(check);
479
- ws.close();
480
- resolve(received);
481
- }
482
- }, 50);
483
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
484
- `
485
- );
486
-
487
- // Send second message (include first message in the array, as the client would)
488
- await connectAndRun(
489
- page,
490
- wsUrl,
491
- `
492
- ws.send(JSON.stringify({
493
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
494
- id: "req-multi-2",
495
- init: {
496
- method: "POST",
497
- body: JSON.stringify({
498
- messages: [
499
- { id: "multi-1", role: "user", parts: [{ type: "text", text: "First" }] },
500
- { id: "multi-2", role: "user", parts: [{ type: "text", text: "Second" }] }
501
- ]
502
- })
503
- }
504
- }));
505
- const check = setInterval(() => {
506
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
507
- clearInterval(check);
508
- ws.close();
509
- resolve(received);
510
- }
511
- }, 50);
512
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
513
- `
514
- );
515
-
516
- // Verify all messages persisted
517
- const res = await page.request.get(
518
- `${baseURL}/agents/chat-agent/${room}/get-messages`
519
- );
520
- const data = await res.json();
521
-
522
- // Should have: multi-1 (user), assistant-1, multi-2 (user), assistant-2
523
- const userMsgs = data.filter((m: { role: string }) => m.role === "user");
524
- const assistantMsgs = data.filter(
525
- (m: { role: string }) => m.role === "assistant"
526
- );
527
- expect(userMsgs.length).toBe(2);
528
- expect(assistantMsgs.length).toBe(2);
529
- });
530
-
531
- test("request cancellation", async ({ page, baseURL }) => {
532
- const { agentPath } = wsHelpers(baseURL!);
533
- const room = crypto.randomUUID();
534
-
535
- // Send a request and immediately cancel it
536
- const messages = await connectAndRun(
537
- page,
538
- agentPath(room),
539
- `
540
- ws.send(JSON.stringify({
541
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
542
- id: "req-cancel",
543
- init: {
544
- method: "POST",
545
- body: JSON.stringify({
546
- messages: [{
547
- id: "cancel-1",
548
- role: "user",
549
- parts: [{ type: "text", text: "Cancel me" }]
550
- }]
551
- })
552
- }
553
- }));
554
-
555
- // Cancel immediately
556
- ws.send(JSON.stringify({
557
- type: "cf_agent_chat_request_cancel",
558
- id: "req-cancel"
559
- }));
560
-
561
- // Wait a bit then close
562
- setTimeout(() => { ws.close(); resolve(received); }, 1000);
563
- `
564
- );
565
-
566
- // The test passes if no errors are thrown — cancellation is graceful
567
- // We might or might not get a response depending on timing
568
- expect(messages).toBeDefined();
569
- });
570
- });
571
-
572
- // ── Stream Resumption ──────────────────────────────────────────────
573
-
574
- test.describe("Stream resumption e2e", () => {
575
- test.beforeEach(async ({ page }) => {
576
- await page.goto("about:blank");
577
- });
578
-
579
- test("resume mid-stream: reconnecting client receives CF_AGENT_STREAM_RESUMING", async ({
580
- page,
581
- baseURL
582
- }) => {
583
- const room = crypto.randomUUID();
584
- const slowUrl = `${baseURL!.replace("http", "ws")}/agents/slow-agent/${room}`;
585
-
586
- // Connect, send a message to start a slow stream, then disconnect mid-stream
587
- await page.evaluate(
588
- ({ url, MT }) => {
589
- return new Promise<void>((resolve) => {
590
- const ws = new WebSocket(url);
591
- ws.onopen = () => {
592
- ws.send(
593
- JSON.stringify({
594
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
595
- id: "req-slow",
596
- init: {
597
- method: "POST",
598
- body: JSON.stringify({
599
- messages: [
600
- {
601
- id: "slow-1",
602
- role: "user",
603
- parts: [{ type: "text", text: "Go slow" }]
604
- }
605
- ]
606
- })
607
- }
608
- })
609
- );
610
- // Disconnect after 600ms (mid-stream — SlowAgent sends chunks every 400ms)
611
- setTimeout(() => {
612
- ws.close();
613
- resolve();
614
- }, 600);
615
- };
616
- });
617
- },
618
- { url: slowUrl, MT: MessageType }
619
- );
620
-
621
- // Wait a beat for the server to register the disconnect
622
- await new Promise((r) => setTimeout(r, 200));
623
-
624
- // Reconnect — should receive CF_AGENT_STREAM_RESUMING
625
- const resumeResult = await page.evaluate(
626
- ({ url, MT }) => {
627
- return new Promise<{
628
- messages: Array<{ type: string; [k: string]: unknown }>;
629
- gotResuming: boolean;
630
- gotResumeChunks: boolean;
631
- }>((resolve) => {
632
- const ws = new WebSocket(url);
633
- const messages: Array<{ type: string; [k: string]: unknown }> = [];
634
- let gotResuming = false;
635
- let gotResumeChunks = false;
636
-
637
- ws.onmessage = (e) => {
638
- try {
639
- const data = JSON.parse(e.data);
640
- messages.push(data);
641
-
642
- if (data.type === MT.CF_AGENT_STREAM_RESUMING) {
643
- gotResuming = true;
644
- // Send ACK
645
- ws.send(
646
- JSON.stringify({
647
- type: MT.CF_AGENT_STREAM_RESUME_ACK,
648
- id: data.id
649
- })
650
- );
651
- }
652
-
653
- if (
654
- data.type === MT.CF_AGENT_USE_CHAT_RESPONSE &&
655
- !data.done &&
656
- data.body
657
- ) {
658
- gotResumeChunks = true;
659
- }
660
-
661
- if (data.type === MT.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
662
- setTimeout(() => {
663
- ws.close();
664
- resolve({ messages, gotResuming, gotResumeChunks });
665
- }, 200);
666
- }
667
- } catch {
668
- // ignore
669
- }
670
- };
671
-
672
- setTimeout(() => {
673
- ws.close();
674
- resolve({ messages, gotResuming, gotResumeChunks });
675
- }, 10000);
676
- });
677
- },
678
- { url: slowUrl, MT: MessageType }
679
- );
680
-
681
- // Should have received the resuming notification
682
- expect(resumeResult.gotResuming).toBe(true);
683
- // Should have received replayed chunks after ACK
684
- expect(resumeResult.gotResumeChunks).toBe(true);
685
- });
686
-
687
- test("no resume after completion: reconnecting gets no CF_AGENT_STREAM_RESUMING", async ({
688
- page,
689
- baseURL
690
- }) => {
691
- const { agentPath } = wsHelpers(baseURL!);
692
- const room = crypto.randomUUID();
693
-
694
- // Send a message and wait for completion
695
- await connectAndRun(
696
- page,
697
- agentPath(room),
698
- `
699
- ws.send(JSON.stringify({
700
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
701
- id: "req-done-first",
702
- init: {
703
- method: "POST",
704
- body: JSON.stringify({
705
- messages: [{
706
- id: "done-1",
707
- role: "user",
708
- parts: [{ type: "text", text: "Quick" }]
709
- }]
710
- })
711
- }
712
- }));
713
- const check = setInterval(() => {
714
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
715
- clearInterval(check);
716
- ws.close();
717
- resolve(received);
718
- }
719
- }, 50);
720
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
721
- `
722
- );
723
-
724
- // Reconnect — should NOT get CF_AGENT_STREAM_RESUMING
725
- const reconnectMsgs = await connectAndRun(
726
- page,
727
- agentPath(room),
728
- `
729
- // Wait and see what messages arrive
730
- setTimeout(() => { ws.close(); resolve(received); }, 1000);
731
- `
732
- );
733
-
734
- const resumeMsg = reconnectMsgs.find(
735
- (m) => m.type === MessageType.CF_AGENT_STREAM_RESUMING
736
- );
737
- expect(resumeMsg).toBeUndefined();
738
- });
739
-
740
- test("client-initiated resume: CF_AGENT_STREAM_RESUME_REQUEST triggers resume after handler is ready", async ({
741
- page,
742
- baseURL
743
- }) => {
744
- const room = crypto.randomUUID();
745
- const slowUrl = `${baseURL!.replace("http", "ws")}/agents/slow-agent/${room}`;
746
-
747
- // Start a slow stream and disconnect mid-stream
748
- await page.evaluate(
749
- ({ url, MT }) => {
750
- return new Promise<void>((resolve) => {
751
- const ws = new WebSocket(url);
752
- ws.onopen = () => {
753
- ws.send(
754
- JSON.stringify({
755
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
756
- id: "req-client-resume",
757
- init: {
758
- method: "POST",
759
- body: JSON.stringify({
760
- messages: [
761
- {
762
- id: "cr-1",
763
- role: "user",
764
- parts: [{ type: "text", text: "Go slow" }]
765
- }
766
- ]
767
- })
768
- }
769
- })
770
- );
771
- setTimeout(() => {
772
- ws.close();
773
- resolve();
774
- }, 600);
775
- };
776
- });
777
- },
778
- { url: slowUrl, MT: MessageType }
779
- );
780
-
781
- await new Promise((r) => setTimeout(r, 200));
782
-
783
- // Reconnect and explicitly send CF_AGENT_STREAM_RESUME_REQUEST
784
- // (simulating what the client does after useEffect registers the handler)
785
- const result = await page.evaluate(
786
- ({ url, MT }) => {
787
- return new Promise<{
788
- gotResuming: boolean;
789
- gotChunks: boolean;
790
- replayFlags: boolean[];
791
- }>((resolve) => {
792
- const ws = new WebSocket(url);
793
- let gotResuming = false;
794
- let gotChunks = false;
795
- const replayFlags: boolean[] = [];
796
-
797
- ws.onmessage = (e) => {
798
- try {
799
- const data = JSON.parse(e.data);
800
-
801
- if (data.type === MT.CF_AGENT_STREAM_RESUMING) {
802
- gotResuming = true;
803
- ws.send(
804
- JSON.stringify({
805
- type: MT.CF_AGENT_STREAM_RESUME_ACK,
806
- id: data.id
807
- })
808
- );
809
- }
810
-
811
- if (data.type === "cf_agent_use_chat_response") {
812
- if (!data.done && data.body) {
813
- gotChunks = true;
814
- replayFlags.push(data.replay === true);
815
- }
816
- if (data.done) {
817
- replayFlags.push(data.replay === true);
818
- setTimeout(() => {
819
- ws.close();
820
- resolve({ gotResuming, gotChunks, replayFlags });
821
- }, 200);
822
- }
823
- }
824
- } catch {
825
- // ignore
826
- }
827
- };
828
-
829
- ws.onopen = () => {
830
- // Send resume request after handler is ready
831
- // (this is what useAgentChat does in its useEffect)
832
- ws.send(
833
- JSON.stringify({
834
- type: "cf_agent_stream_resume_request"
835
- })
836
- );
837
- };
838
-
839
- setTimeout(() => {
840
- ws.close();
841
- resolve({ gotResuming, gotChunks, replayFlags });
842
- }, 10000);
843
- });
844
- },
845
- { url: slowUrl, MT: MessageType }
846
- );
847
-
848
- // Should have received resume notification via the request
849
- expect(result.gotResuming).toBe(true);
850
- // Should have received chunks (mix of replayed from DB + live from ongoing stream)
851
- expect(result.gotChunks).toBe(true);
852
- // At least some chunks should have replay=true (the ones replayed from DB)
853
- expect(result.replayFlags.length).toBeGreaterThan(0);
854
- expect(result.replayFlags.some((f) => f === true)).toBe(true);
855
- });
856
-
857
- test("replayed chunks have replay=true flag", async ({ page, baseURL }) => {
858
- const room = crypto.randomUUID();
859
- const slowUrl = `${baseURL!.replace("http", "ws")}/agents/slow-agent/${room}`;
860
-
861
- // Start stream, disconnect mid-stream, reconnect
862
- await page.evaluate(
863
- ({ url, MT }) => {
864
- return new Promise<void>((resolve) => {
865
- const ws = new WebSocket(url);
866
- ws.onopen = () => {
867
- ws.send(
868
- JSON.stringify({
869
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
870
- id: "req-replay-flag",
871
- init: {
872
- method: "POST",
873
- body: JSON.stringify({
874
- messages: [
875
- {
876
- id: "rf-1",
877
- role: "user",
878
- parts: [{ type: "text", text: "Go slow" }]
879
- }
880
- ]
881
- })
882
- }
883
- })
884
- );
885
- setTimeout(() => {
886
- ws.close();
887
- resolve();
888
- }, 600);
889
- };
890
- });
891
- },
892
- { url: slowUrl, MT: MessageType }
893
- );
894
-
895
- await new Promise((r) => setTimeout(r, 200));
896
-
897
- // Reconnect and check replay flags
898
- const result = await page.evaluate(
899
- ({ url, MT }) => {
900
- return new Promise<{
901
- chunks: Array<{
902
- body?: string;
903
- done: boolean;
904
- replay?: boolean;
905
- }>;
906
- }>((resolve) => {
907
- const ws = new WebSocket(url);
908
- const chunks: Array<{
909
- body?: string;
910
- done: boolean;
911
- replay?: boolean;
912
- }> = [];
913
-
914
- ws.onmessage = (e) => {
915
- try {
916
- const data = JSON.parse(e.data);
917
-
918
- if (data.type === MT.CF_AGENT_STREAM_RESUMING) {
919
- ws.send(
920
- JSON.stringify({
921
- type: MT.CF_AGENT_STREAM_RESUME_ACK,
922
- id: data.id
923
- })
924
- );
925
- }
926
-
927
- if (data.type === "cf_agent_use_chat_response") {
928
- chunks.push({
929
- body: data.body,
930
- done: data.done,
931
- replay: data.replay
932
- });
933
- if (data.done) {
934
- setTimeout(() => {
935
- ws.close();
936
- resolve({ chunks });
937
- }, 200);
938
- }
939
- }
940
- } catch {
941
- // ignore
942
- }
943
- };
944
-
945
- setTimeout(() => {
946
- ws.close();
947
- resolve({ chunks });
948
- }, 10000);
949
- });
950
- },
951
- { url: slowUrl, MT: MessageType }
952
- );
953
-
954
- // Should have received chunks
955
- expect(result.chunks.length).toBeGreaterThan(0);
956
-
957
- // Replayed chunks (from DB) have replay=true,
958
- // live chunks (from ongoing stream) don't.
959
- // At least some should be replayed.
960
- const replayedChunks = result.chunks.filter((c) => c.replay === true);
961
- expect(replayedChunks.length).toBeGreaterThan(0);
962
- });
963
- });
964
-
965
- // ── Custom Body ────────────────────────────────────────────────────
966
-
967
- test.describe("Custom body forwarding e2e", () => {
968
- test.beforeEach(async ({ page }) => {
969
- await page.goto("about:blank");
970
- });
971
-
972
- test("custom fields in request body are forwarded to onChatMessage", async ({
973
- page,
974
- baseURL
975
- }) => {
976
- const { agentPath } = wsHelpers(baseURL!);
977
- const room = crypto.randomUUID();
978
-
979
- // Send a request with custom body fields
980
- await connectAndRun(
981
- page,
982
- agentPath(room),
983
- `
984
- ws.send(JSON.stringify({
985
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
986
- id: "req-custom-body",
987
- init: {
988
- method: "POST",
989
- body: JSON.stringify({
990
- messages: [{
991
- id: "cb-1",
992
- role: "user",
993
- parts: [{ type: "text", text: "With custom body" }]
994
- }],
995
- customField: "test-value",
996
- nestedData: { key: 123 }
997
- })
998
- }
999
- }));
1000
- const check = setInterval(() => {
1001
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1002
- clearInterval(check);
1003
- ws.close();
1004
- resolve(received);
1005
- }
1006
- }, 50);
1007
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1008
- `
1009
- );
1010
-
1011
- // If the agent didn't crash and responded, the custom body was received.
1012
- // The ChatAgent doesn't use options.body, but the fact that it responded
1013
- // means the parsing didn't fail — custom fields are silently passed through.
1014
- const res = await page.request.get(
1015
- `${baseURL}/agents/chat-agent/${room}/get-messages`
1016
- );
1017
- const data = await res.json();
1018
- expect(data.length).toBeGreaterThanOrEqual(2);
1019
- });
1020
- });
1021
-
1022
- // ── Error Handling ─────────────────────────────────────────────────
1023
-
1024
- test.describe("Error handling e2e", () => {
1025
- test.beforeEach(async ({ page }) => {
1026
- await page.goto("about:blank");
1027
- });
1028
-
1029
- test("malformed JSON on WebSocket does not crash connection", async ({
1030
- page,
1031
- baseURL
1032
- }) => {
1033
- const { agentPath } = wsHelpers(baseURL!);
1034
- const room = crypto.randomUUID();
1035
-
1036
- const messages = await connectAndRun(
1037
- page,
1038
- agentPath(room),
1039
- `
1040
- // Send garbage text
1041
- ws.send("this is not json at all!!!");
1042
- ws.send("{broken json");
1043
- ws.send("");
1044
-
1045
- // Then send a valid request
1046
- ws.send(JSON.stringify({
1047
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1048
- id: "req-after-garbage",
1049
- init: {
1050
- method: "POST",
1051
- body: JSON.stringify({
1052
- messages: [{
1053
- id: "garbage-1",
1054
- role: "user",
1055
- parts: [{ type: "text", text: "Still works?" }]
1056
- }]
1057
- })
1058
- }
1059
- }));
1060
-
1061
- const check = setInterval(() => {
1062
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1063
- clearInterval(check);
1064
- ws.close();
1065
- resolve(received);
1066
- }
1067
- }, 50);
1068
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1069
- `
1070
- );
1071
-
1072
- // Should have received a valid response despite the garbage
1073
- const doneMsg = messages.find(
1074
- (m) => m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && m.done
1075
- );
1076
- expect(doneMsg).toBeTruthy();
1077
- });
1078
-
1079
- test("invalid message type does not crash connection", async ({
1080
- page,
1081
- baseURL
1082
- }) => {
1083
- const { agentPath } = wsHelpers(baseURL!);
1084
- const room = crypto.randomUUID();
1085
-
1086
- const messages = await connectAndRun(
1087
- page,
1088
- agentPath(room),
1089
- `
1090
- // Send valid JSON with unknown type
1091
- ws.send(JSON.stringify({ type: "totally_invalid_type", data: "whatever" }));
1092
- ws.send(JSON.stringify({ type: "another_fake", id: "fake-id" }));
1093
-
1094
- // Then send a valid request
1095
- ws.send(JSON.stringify({
1096
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1097
- id: "req-after-invalid",
1098
- init: {
1099
- method: "POST",
1100
- body: JSON.stringify({
1101
- messages: [{
1102
- id: "invalid-type-1",
1103
- role: "user",
1104
- parts: [{ type: "text", text: "Still alive?" }]
1105
- }]
1106
- })
1107
- }
1108
- }));
1109
-
1110
- const check = setInterval(() => {
1111
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1112
- clearInterval(check);
1113
- ws.close();
1114
- resolve(received);
1115
- }
1116
- }, 50);
1117
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1118
- `
1119
- );
1120
-
1121
- const doneMsg = messages.find(
1122
- (m) => m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && m.done
1123
- );
1124
- expect(doneMsg).toBeTruthy();
1125
- });
1126
-
1127
- test("LLM API error returns error response to client", async ({
1128
- page,
1129
- baseURL
1130
- }) => {
1131
- const room = crypto.randomUUID();
1132
- const badKeyUrl = `${baseURL!.replace("http", "ws")}/agents/bad-key-agent/${room}`;
1133
-
1134
- const messages = await page.evaluate(
1135
- ({ url, MT }) => {
1136
- return new Promise<Array<{ type: string; [k: string]: unknown }>>(
1137
- (resolve) => {
1138
- const ws = new WebSocket(url);
1139
- const received: Array<{ type: string; [k: string]: unknown }> = [];
1140
-
1141
- ws.onmessage = (e) => {
1142
- try {
1143
- received.push(JSON.parse(e.data));
1144
- } catch {
1145
- // ignore
1146
- }
1147
- };
1148
-
1149
- ws.onopen = () => {
1150
- ws.send(
1151
- JSON.stringify({
1152
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1153
- id: "req-bad-key",
1154
- init: {
1155
- method: "POST",
1156
- body: JSON.stringify({
1157
- messages: [
1158
- {
1159
- id: "bad-key-1",
1160
- role: "user",
1161
- parts: [{ type: "text", text: "This should fail" }]
1162
- }
1163
- ]
1164
- })
1165
- }
1166
- })
1167
- );
1168
- };
1169
-
1170
- // Wait for error or done
1171
- const check = setInterval(() => {
1172
- const errorOrDone = received.find(
1173
- (m) =>
1174
- m.type === MT.CF_AGENT_USE_CHAT_RESPONSE &&
1175
- (m.done || m.error)
1176
- );
1177
- if (errorOrDone) {
1178
- clearInterval(check);
1179
- setTimeout(() => {
1180
- ws.close();
1181
- resolve(received);
1182
- }, 200);
1183
- }
1184
- }, 100);
1185
-
1186
- setTimeout(() => {
1187
- clearInterval(check);
1188
- ws.close();
1189
- resolve(received);
1190
- }, 15000);
1191
- }
1192
- );
1193
- },
1194
- { url: badKeyUrl, MT: MessageType }
1195
- );
1196
-
1197
- // Should have received an error response
1198
- const errorMsg = messages.find(
1199
- (m) =>
1200
- m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && m.error === true
1201
- );
1202
- expect(errorMsg).toBeTruthy();
1203
- });
1204
- });
1205
-
1206
- // ── Concurrency ────────────────────────────────────────────────────
1207
-
1208
- test.describe("Concurrency e2e", () => {
1209
- test.beforeEach(async ({ page }) => {
1210
- await page.goto("about:blank");
1211
- });
1212
-
1213
- test("concurrent requests: two requests complete without interference", async ({
1214
- page,
1215
- baseURL
1216
- }) => {
1217
- const { agentPath } = wsHelpers(baseURL!);
1218
- const room = crypto.randomUUID();
1219
-
1220
- const result = await page.evaluate(
1221
- ({ url, MT }) => {
1222
- return new Promise<{
1223
- req1Done: boolean;
1224
- req2Done: boolean;
1225
- messages: Array<{ type: string; [k: string]: unknown }>;
1226
- }>((resolve) => {
1227
- const ws = new WebSocket(url);
1228
- const messages: Array<{ type: string; [k: string]: unknown }> = [];
1229
- let req1Done = false;
1230
- let req2Done = false;
1231
-
1232
- ws.onmessage = (e) => {
1233
- try {
1234
- const data = JSON.parse(e.data);
1235
- messages.push(data);
1236
-
1237
- if (data.type === MT.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
1238
- if (data.id === "req-conc-1") req1Done = true;
1239
- if (data.id === "req-conc-2") req2Done = true;
1240
- if (req1Done && req2Done) {
1241
- setTimeout(() => {
1242
- ws.close();
1243
- resolve({ req1Done, req2Done, messages });
1244
- }, 200);
1245
- }
1246
- }
1247
- } catch {
1248
- // ignore
1249
- }
1250
- };
1251
-
1252
- ws.onopen = () => {
1253
- // Send two requests simultaneously
1254
- ws.send(
1255
- JSON.stringify({
1256
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1257
- id: "req-conc-1",
1258
- init: {
1259
- method: "POST",
1260
- body: JSON.stringify({
1261
- messages: [
1262
- {
1263
- id: "conc-1",
1264
- role: "user",
1265
- parts: [{ type: "text", text: "First concurrent" }]
1266
- }
1267
- ]
1268
- })
1269
- }
1270
- })
1271
- );
1272
- ws.send(
1273
- JSON.stringify({
1274
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1275
- id: "req-conc-2",
1276
- init: {
1277
- method: "POST",
1278
- body: JSON.stringify({
1279
- messages: [
1280
- {
1281
- id: "conc-1",
1282
- role: "user",
1283
- parts: [{ type: "text", text: "First concurrent" }]
1284
- },
1285
- {
1286
- id: "conc-2",
1287
- role: "user",
1288
- parts: [{ type: "text", text: "Second concurrent" }]
1289
- }
1290
- ]
1291
- })
1292
- }
1293
- })
1294
- );
1295
- };
1296
-
1297
- setTimeout(() => {
1298
- ws.close();
1299
- resolve({ req1Done, req2Done, messages });
1300
- }, 10000);
1301
- });
1302
- },
1303
- { url: agentPath(room), MT: MessageType }
1304
- );
1305
-
1306
- expect(result.req1Done).toBe(true);
1307
- expect(result.req2Done).toBe(true);
1308
- });
1309
- });
1310
-
1311
- // ── Large Messages ─────────────────────────────────────────────────
1312
-
1313
- test.describe("Large messages e2e", () => {
1314
- test.beforeEach(async ({ page }) => {
1315
- await page.goto("about:blank");
1316
- });
1317
-
1318
- test("large message persistence: 10KB message persists correctly", async ({
1319
- page,
1320
- baseURL
1321
- }) => {
1322
- const { agentPath } = wsHelpers(baseURL!);
1323
- const room = crypto.randomUUID();
1324
-
1325
- // Generate a 10KB string
1326
- const largeText = "A".repeat(10 * 1024);
1327
-
1328
- await connectAndRun(
1329
- page,
1330
- agentPath(room),
1331
- `
1332
- ws.send(JSON.stringify({
1333
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1334
- id: "req-large",
1335
- init: {
1336
- method: "POST",
1337
- body: JSON.stringify({
1338
- messages: [{
1339
- id: "large-1",
1340
- role: "user",
1341
- parts: [{ type: "text", text: "${largeText}" }]
1342
- }]
1343
- })
1344
- }
1345
- }));
1346
- const check = setInterval(() => {
1347
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1348
- clearInterval(check);
1349
- ws.close();
1350
- resolve(received);
1351
- }
1352
- }, 50);
1353
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1354
- `
1355
- );
1356
-
1357
- // Verify persistence
1358
- const res = await page.request.get(
1359
- `${baseURL}/agents/chat-agent/${room}/get-messages`
1360
- );
1361
- const data = await res.json();
1362
-
1363
- const userMsg = data.find((m: { id: string }) => m.id === "large-1");
1364
- expect(userMsg).toBeTruthy();
1365
- const textPart = userMsg.parts.find(
1366
- (p: { type: string }) => p.type === "text"
1367
- );
1368
- expect(textPart.text.length).toBe(10 * 1024);
1369
- });
1370
- });
1371
-
1372
- // ── Malformed Input ────────────────────────────────────────────────
1373
-
1374
- test.describe("Malformed input e2e", () => {
1375
- test.beforeEach(async ({ page }) => {
1376
- await page.goto("about:blank");
1377
- });
1378
-
1379
- test("empty messages array: agent handles gracefully", async ({
1380
- page,
1381
- baseURL
1382
- }) => {
1383
- const { agentPath } = wsHelpers(baseURL!);
1384
- const room = crypto.randomUUID();
1385
-
1386
- const messages = await connectAndRun(
1387
- page,
1388
- agentPath(room),
1389
- `
1390
- ws.send(JSON.stringify({
1391
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1392
- id: "req-empty",
1393
- init: {
1394
- method: "POST",
1395
- body: JSON.stringify({ messages: [] })
1396
- }
1397
- }));
1398
-
1399
- // Wait for a response or timeout
1400
- const check = setInterval(() => {
1401
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1402
- clearInterval(check);
1403
- ws.close();
1404
- resolve(received);
1405
- }
1406
- }, 50);
1407
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 3000);
1408
- `
1409
- );
1410
-
1411
- // Agent should handle empty messages without crashing
1412
- // It may send a response or just not crash — either is fine
1413
- expect(messages).toBeDefined();
1414
- });
1415
-
1416
- test("missing body in init: agent handles gracefully", async ({
1417
- page,
1418
- baseURL
1419
- }) => {
1420
- const { agentPath } = wsHelpers(baseURL!);
1421
- const room = crypto.randomUUID();
1422
-
1423
- const messages = await connectAndRun(
1424
- page,
1425
- agentPath(room),
1426
- `
1427
- ws.send(JSON.stringify({
1428
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1429
- id: "req-no-body",
1430
- init: {
1431
- method: "POST"
1432
- }
1433
- }));
1434
-
1435
- // Give the agent a moment to process (and not crash)
1436
- setTimeout(() => {
1437
- // Then send a valid request to prove the connection is still alive
1438
- ws.send(JSON.stringify({
1439
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1440
- id: "req-valid-after",
1441
- init: {
1442
- method: "POST",
1443
- body: JSON.stringify({
1444
- messages: [{
1445
- id: "after-no-body",
1446
- role: "user",
1447
- parts: [{ type: "text", text: "Recovery" }]
1448
- }]
1449
- })
1450
- }
1451
- }));
1452
- }, 500);
1453
-
1454
- const check = setInterval(() => {
1455
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1456
- clearInterval(check);
1457
- ws.close();
1458
- resolve(received);
1459
- }
1460
- }, 50);
1461
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1462
- `
1463
- );
1464
-
1465
- // Connection should still be alive — the valid request should have completed
1466
- expect(messages).toBeDefined();
1467
- });
1468
- });
1469
-
1470
- // ── Large Output ───────────────────────────────────────────────────
1471
-
1472
- test.describe("Large tool output e2e", () => {
1473
- test.beforeEach(async ({ page }) => {
1474
- await page.goto("about:blank");
1475
- });
1476
-
1477
- test("large message persists without crash", async ({ page, baseURL }) => {
1478
- const { agentPath } = wsHelpers(baseURL!);
1479
- const room = crypto.randomUUID();
1480
-
1481
- // Send a message with a 100KB body to test persistence of large data
1482
- const largeText = "A".repeat(100_000);
1483
-
1484
- await connectAndRun(
1485
- page,
1486
- agentPath(room),
1487
- `
1488
- ws.send(JSON.stringify({
1489
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1490
- id: "req-large-output",
1491
- init: {
1492
- method: "POST",
1493
- body: JSON.stringify({
1494
- messages: [{
1495
- id: "large-output-1",
1496
- role: "user",
1497
- parts: [{ type: "text", text: "${largeText}" }]
1498
- }]
1499
- })
1500
- }
1501
- }));
1502
- const check = setInterval(() => {
1503
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1504
- clearInterval(check);
1505
- ws.close();
1506
- resolve(received);
1507
- }
1508
- }, 50);
1509
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1510
- `
1511
- );
1512
-
1513
- // Verify the message persisted and is retrievable
1514
- const res = await page.request.get(
1515
- `${baseURL}/agents/chat-agent/${room}/get-messages`
1516
- );
1517
- expect(res.ok()).toBe(true);
1518
- const data = await res.json();
1519
- expect(data.length).toBeGreaterThanOrEqual(2); // user + assistant
1520
-
1521
- // The user message should have the large text
1522
- const userMsg = data.find((m: { id: string }) => m.id === "large-output-1");
1523
- expect(userMsg).toBeTruthy();
1524
- });
1525
-
1526
- test("3MB message: does not crash, degrades gracefully with compaction", async ({
1527
- page,
1528
- baseURL
1529
- }) => {
1530
- const { agentPath } = wsHelpers(baseURL!);
1531
- const room = crypto.randomUUID();
1532
-
1533
- // First, send a normal message to establish the conversation
1534
- await connectAndRun(
1535
- page,
1536
- agentPath(room),
1537
- `
1538
- ws.send(JSON.stringify({
1539
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1540
- id: "req-3mb-setup",
1541
- init: {
1542
- method: "POST",
1543
- body: JSON.stringify({
1544
- messages: [{
1545
- id: "3mb-user-1",
1546
- role: "user",
1547
- parts: [{ type: "text", text: "Hello" }]
1548
- }]
1549
- })
1550
- }
1551
- }));
1552
- const check = setInterval(() => {
1553
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1554
- clearInterval(check);
1555
- ws.close();
1556
- resolve(received);
1557
- }
1558
- }, 50);
1559
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1560
- `
1561
- );
1562
-
1563
- // Now send a message set that includes a 3MB assistant message
1564
- // (simulating what would happen if a tool returned a huge result)
1565
- // We send it via CF_AGENT_CHAT_MESSAGES which goes through persistMessages
1566
- const threeMBText = "X".repeat(3_000_000);
1567
-
1568
- await connectAndRun(
1569
- page,
1570
- agentPath(room),
1571
- `
1572
- // Send the 3MB message via CF_AGENT_CHAT_MESSAGES (setMessages path)
1573
- ws.send(JSON.stringify({
1574
- type: "cf_agent_chat_messages",
1575
- messages: [
1576
- {
1577
- id: "3mb-user-1",
1578
- role: "user",
1579
- parts: [{ type: "text", text: "Hello" }]
1580
- },
1581
- {
1582
- id: "3mb-assistant-huge",
1583
- role: "assistant",
1584
- parts: [
1585
- { type: "text", text: "Here are the results:" },
1586
- {
1587
- type: "tool-bigQuery",
1588
- toolCallId: "call_3mb",
1589
- state: "output-available",
1590
- input: { query: "SELECT * FROM everything" },
1591
- output: "${threeMBText}"
1592
- }
1593
- ]
1594
- }
1595
- ]
1596
- }));
1597
-
1598
- // Give it time to persist
1599
- setTimeout(() => { ws.close(); resolve(received); }, 1000);
1600
- `
1601
- );
1602
-
1603
- // Verify the agent didn't crash -- messages are retrievable
1604
- const res = await page.request.get(
1605
- `${baseURL}/agents/chat-agent/${room}/get-messages`
1606
- );
1607
- expect(res.ok()).toBe(true);
1608
- const data = await res.json();
1609
-
1610
- // Should have messages (didn't crash)
1611
- expect(data.length).toBeGreaterThanOrEqual(2);
1612
-
1613
- // Find the huge assistant message
1614
- const hugeMsg = data.find(
1615
- (m: { id: string }) => m.id === "3mb-assistant-huge"
1616
- );
1617
- expect(hugeMsg).toBeTruthy();
1618
-
1619
- // The tool output should be compacted (not the original 3MB)
1620
- const toolPart = hugeMsg.parts.find(
1621
- (p: { toolCallId?: string }) => p.toolCallId === "call_3mb"
1622
- );
1623
- expect(toolPart).toBeTruthy();
1624
- const output = toolPart.output as string;
1625
-
1626
- // Should contain the compaction notice
1627
- expect(output).toContain("too large to persist");
1628
- expect(output).toContain("suggest re-running the tool");
1629
- expect(output).toContain("Preview:");
1630
-
1631
- // Should be much smaller than 3MB
1632
- expect(output.length).toBeLessThan(10_000);
1633
-
1634
- // The text part should be preserved (it was small)
1635
- const textPart = hugeMsg.parts.find(
1636
- (p: { type: string }) => p.type === "text"
1637
- );
1638
- expect(textPart).toBeTruthy();
1639
- expect(textPart.text).toBe("Here are the results:");
1640
-
1641
- // Metadata should indicate compaction happened
1642
- if (hugeMsg.metadata) {
1643
- expect(hugeMsg.metadata.compactedToolOutputs).toContain("call_3mb");
1644
- }
1645
-
1646
- // The conversation should still work -- send another message
1647
- const followUp = await connectAndRun(
1648
- page,
1649
- agentPath(room),
1650
- `
1651
- ws.send(JSON.stringify({
1652
- type: MT.CF_AGENT_USE_CHAT_REQUEST,
1653
- id: "req-3mb-followup",
1654
- init: {
1655
- method: "POST",
1656
- body: JSON.stringify({
1657
- messages: [
1658
- {
1659
- id: "3mb-user-1",
1660
- role: "user",
1661
- parts: [{ type: "text", text: "Hello" }]
1662
- },
1663
- {
1664
- id: "3mb-assistant-huge",
1665
- role: "assistant",
1666
- parts: [
1667
- { type: "text", text: "Here are the results:" },
1668
- {
1669
- type: "tool-bigQuery",
1670
- toolCallId: "call_3mb",
1671
- state: "output-available",
1672
- input: { query: "SELECT * FROM everything" },
1673
- output: "compacted"
1674
- }
1675
- ]
1676
- },
1677
- {
1678
- id: "3mb-user-2",
1679
- role: "user",
1680
- parts: [{ type: "text", text: "Thanks, what next?" }]
1681
- }
1682
- ]
1683
- })
1684
- }
1685
- }));
1686
- const check = setInterval(() => {
1687
- if (received.find(m => m.type === MT.CF_AGENT_USE_CHAT_RESPONSE && m.done)) {
1688
- clearInterval(check);
1689
- ws.close();
1690
- resolve(received);
1691
- }
1692
- }, 50);
1693
- setTimeout(() => { clearInterval(check); ws.close(); resolve(received); }, 5000);
1694
- `
1695
- );
1696
-
1697
- // Follow-up should succeed (agent still alive)
1698
- const doneMsg = followUp.find(
1699
- (m) => m.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && m.done
1700
- );
1701
- expect(doneMsg).toBeTruthy();
1702
- });
1703
- });