@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
@@ -1,758 +0,0 @@
1
- import { env } from "cloudflare:test";
2
- import { describe, it, expect } from "vitest";
3
- import { MessageType, type OutgoingMessage } from "../types";
4
- import { connectChatWS, isUseChatResponseMessage } from "./test-utils";
5
- import { getAgentByName } from "agents";
6
-
7
- function isStreamResumingMessage(
8
- m: unknown
9
- ): m is Extract<
10
- OutgoingMessage,
11
- { type: MessageType.CF_AGENT_STREAM_RESUMING }
12
- > {
13
- return (
14
- typeof m === "object" &&
15
- m !== null &&
16
- "type" in m &&
17
- m.type === MessageType.CF_AGENT_STREAM_RESUMING
18
- );
19
- }
20
-
21
- function collectMessages(ws: WebSocket): unknown[] {
22
- const messages: unknown[] = [];
23
- ws.addEventListener("message", (e: MessageEvent) => {
24
- try {
25
- messages.push(JSON.parse(e.data as string));
26
- } catch {
27
- messages.push(e.data);
28
- }
29
- });
30
- return messages;
31
- }
32
-
33
- describe("Resumable Streaming", () => {
34
- describe("Stream lifecycle", () => {
35
- it("stores stream metadata when starting a stream", async () => {
36
- const room = crypto.randomUUID();
37
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
38
-
39
- await new Promise((r) => setTimeout(r, 50));
40
-
41
- const agentStub = await getAgentByName(env.TestChatAgent, room);
42
-
43
- const streamId = await agentStub.testStartStream("req-123");
44
- expect(streamId).toBeDefined();
45
- expect(typeof streamId).toBe("string");
46
-
47
- const metadata = await agentStub.getStreamMetadata(streamId);
48
- expect(metadata).toBeDefined();
49
- expect(metadata?.status).toBe("streaming");
50
- expect(metadata?.request_id).toBe("req-123");
51
-
52
- ws.close(1000);
53
- });
54
-
55
- it("stores stream chunks in batches", async () => {
56
- const room = crypto.randomUUID();
57
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
58
-
59
- await new Promise((r) => setTimeout(r, 50));
60
-
61
- const agentStub = await getAgentByName(env.TestChatAgent, room);
62
-
63
- const streamId = await agentStub.testStartStream("req-456");
64
-
65
- // Store several chunks
66
- await agentStub.testStoreStreamChunk(
67
- streamId,
68
- '{"type":"text","text":"Hello"}'
69
- );
70
- await agentStub.testStoreStreamChunk(
71
- streamId,
72
- '{"type":"text","text":" world"}'
73
- );
74
- await agentStub.testStoreStreamChunk(
75
- streamId,
76
- '{"type":"text","text":"!"}'
77
- );
78
-
79
- // Flush the buffer
80
- await agentStub.testFlushChunkBuffer();
81
-
82
- const chunks = await agentStub.getStreamChunks(streamId);
83
- expect(chunks.length).toBe(3);
84
- expect(chunks[0].chunk_index).toBe(0);
85
- expect(chunks[1].chunk_index).toBe(1);
86
- expect(chunks[2].chunk_index).toBe(2);
87
- expect(chunks[0].body).toBe('{"type":"text","text":"Hello"}');
88
-
89
- ws.close(1000);
90
- });
91
-
92
- it("marks stream as completed and clears active state", async () => {
93
- const room = crypto.randomUUID();
94
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
95
-
96
- await new Promise((r) => setTimeout(r, 50));
97
-
98
- const agentStub = await getAgentByName(env.TestChatAgent, room);
99
-
100
- const streamId = await agentStub.testStartStream("req-789");
101
-
102
- // Verify active state
103
- expect(await agentStub.getActiveStreamId()).toBe(streamId);
104
- expect(await agentStub.getActiveRequestId()).toBe("req-789");
105
-
106
- // Complete the stream
107
- await agentStub.testCompleteStream(streamId);
108
-
109
- // Verify cleared state
110
- expect(await agentStub.getActiveStreamId()).toBeNull();
111
- expect(await agentStub.getActiveRequestId()).toBeNull();
112
-
113
- const metadata = await agentStub.getStreamMetadata(streamId);
114
- expect(metadata?.status).toBe("completed");
115
-
116
- ws.close(1000);
117
- });
118
-
119
- it("marks stream as error on failure", async () => {
120
- const room = crypto.randomUUID();
121
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
122
-
123
- await new Promise((r) => setTimeout(r, 50));
124
-
125
- const agentStub = await getAgentByName(env.TestChatAgent, room);
126
-
127
- const streamId = await agentStub.testStartStream("req-error");
128
-
129
- // Mark as error
130
- await agentStub.testMarkStreamError(streamId);
131
-
132
- // Verify cleared state
133
- expect(await agentStub.getActiveStreamId()).toBeNull();
134
-
135
- const metadata = await agentStub.getStreamMetadata(streamId);
136
- expect(metadata?.status).toBe("error");
137
-
138
- ws.close(1000);
139
- });
140
- });
141
-
142
- describe("Stream resumption", () => {
143
- it("notifies new connections about active streams", async () => {
144
- const room = crypto.randomUUID();
145
-
146
- // First connection - start a stream
147
- const { ws: ws1 } = await connectChatWS(
148
- `/agents/test-chat-agent/${room}`
149
- );
150
- await new Promise((r) => setTimeout(r, 50));
151
-
152
- const agentStub = await getAgentByName(env.TestChatAgent, room);
153
- const streamId = await agentStub.testStartStream("req-resume");
154
- await agentStub.testStoreStreamChunk(
155
- streamId,
156
- '{"type":"text","text":"Hello"}'
157
- );
158
- await agentStub.testFlushChunkBuffer();
159
-
160
- ws1.close();
161
- await new Promise((r) => setTimeout(r, 50));
162
-
163
- // Second connection - should receive resume notification
164
- const { ws: ws2 } = await connectChatWS(
165
- `/agents/test-chat-agent/${room}`
166
- );
167
- const messages2 = collectMessages(ws2);
168
-
169
- await new Promise((r) => setTimeout(r, 100));
170
-
171
- const resumeMsg = messages2.find(isStreamResumingMessage);
172
- expect(resumeMsg).toBeDefined();
173
- expect(resumeMsg?.id).toBe("req-resume");
174
-
175
- ws2.close(1000);
176
- });
177
-
178
- it("sends stream chunks after client ACK", async () => {
179
- const room = crypto.randomUUID();
180
-
181
- // Setup - create a stream with chunks
182
- const { ws: ws1 } = await connectChatWS(
183
- `/agents/test-chat-agent/${room}`
184
- );
185
- await new Promise((r) => setTimeout(r, 50));
186
-
187
- const agentStub = await getAgentByName(env.TestChatAgent, room);
188
- const streamId = await agentStub.testStartStream("req-ack");
189
- await agentStub.testStoreStreamChunk(
190
- streamId,
191
- '{"type":"text","text":"chunk1"}'
192
- );
193
- await agentStub.testStoreStreamChunk(
194
- streamId,
195
- '{"type":"text","text":"chunk2"}'
196
- );
197
- await agentStub.testFlushChunkBuffer();
198
-
199
- ws1.close();
200
- await new Promise((r) => setTimeout(r, 50));
201
-
202
- // New connection
203
- const { ws: ws2 } = await connectChatWS(
204
- `/agents/test-chat-agent/${room}`
205
- );
206
- const messages2 = collectMessages(ws2);
207
-
208
- await new Promise((r) => setTimeout(r, 100));
209
-
210
- // Send ACK
211
- ws2.send(
212
- JSON.stringify({
213
- type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
214
- id: "req-ack"
215
- })
216
- );
217
-
218
- await new Promise((r) => setTimeout(r, 100));
219
-
220
- // Should receive the chunks
221
- const chunkMsgs = messages2.filter(isUseChatResponseMessage);
222
- expect(chunkMsgs.length).toBeGreaterThanOrEqual(2);
223
- expect(chunkMsgs[0].body).toBe('{"type":"text","text":"chunk1"}');
224
- expect(chunkMsgs[1].body).toBe('{"type":"text","text":"chunk2"}');
225
-
226
- ws2.close(1000);
227
- });
228
-
229
- it("does not deliver live chunks before ACK to resuming connections", async () => {
230
- const room = crypto.randomUUID();
231
-
232
- // First connection - start a stream
233
- const { ws: ws1 } = await connectChatWS(
234
- `/agents/test-chat-agent/${room}`
235
- );
236
- const messages1 = collectMessages(ws1);
237
- await new Promise((r) => setTimeout(r, 50));
238
-
239
- const agentStub = await getAgentByName(env.TestChatAgent, room);
240
- const streamId = await agentStub.testStartStream("req-live");
241
-
242
- // Second connection - will be notified to resume
243
- const { ws: ws2 } = await connectChatWS(
244
- `/agents/test-chat-agent/${room}`
245
- );
246
- const messages2 = collectMessages(ws2);
247
-
248
- await new Promise((r) => setTimeout(r, 100));
249
-
250
- // Broadcast a live chunk while ws2 is pending resume (no ACK yet)
251
- await agentStub.testBroadcastLiveChunk(
252
- "req-live",
253
- streamId,
254
- '{"type":"text-delta","id":"0","delta":"A"}'
255
- );
256
-
257
- await new Promise((r) => setTimeout(r, 100));
258
-
259
- // ws2 should NOT receive live chunks before ACK
260
- const preAckChunks = messages2.filter(isUseChatResponseMessage);
261
- expect(preAckChunks.length).toBe(0);
262
-
263
- // ws1 should receive the live chunk
264
- const ws1Chunks = messages1.filter(isUseChatResponseMessage);
265
- expect(ws1Chunks.length).toBe(1);
266
- expect(ws1Chunks[0].body).toBe(
267
- '{"type":"text-delta","id":"0","delta":"A"}'
268
- );
269
-
270
- // Send ACK to resume
271
- ws2.send(
272
- JSON.stringify({
273
- type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
274
- id: "req-live"
275
- })
276
- );
277
-
278
- await new Promise((r) => setTimeout(r, 100));
279
-
280
- // After ACK, ws2 should receive the replayed chunk
281
- const postAckChunks = messages2.filter(isUseChatResponseMessage);
282
- expect(postAckChunks.length).toBeGreaterThanOrEqual(1);
283
- expect(postAckChunks[0].body).toBe(
284
- '{"type":"text-delta","id":"0","delta":"A"}'
285
- );
286
-
287
- // Live chunks after ACK should be delivered
288
- await agentStub.testBroadcastLiveChunk(
289
- "req-live",
290
- streamId,
291
- '{"type":"text-delta","id":"0","delta":"B"}'
292
- );
293
-
294
- await new Promise((r) => setTimeout(r, 100));
295
-
296
- const finalChunks = messages2.filter(isUseChatResponseMessage);
297
- expect(finalChunks.some((m) => m.body?.includes('"delta":"B"'))).toBe(
298
- true
299
- );
300
-
301
- ws1.close();
302
- ws2.close(1000);
303
- });
304
-
305
- it("ignores ACK with wrong request ID", async () => {
306
- const room = crypto.randomUUID();
307
-
308
- // Setup
309
- const { ws: ws1 } = await connectChatWS(
310
- `/agents/test-chat-agent/${room}`
311
- );
312
- await new Promise((r) => setTimeout(r, 50));
313
-
314
- const agentStub = await getAgentByName(env.TestChatAgent, room);
315
- const streamId = await agentStub.testStartStream("req-correct");
316
- await agentStub.testStoreStreamChunk(
317
- streamId,
318
- '{"type":"text","text":"secret"}'
319
- );
320
- await agentStub.testFlushChunkBuffer();
321
-
322
- ws1.close();
323
- await new Promise((r) => setTimeout(r, 50));
324
-
325
- // New connection
326
- const { ws: ws2 } = await connectChatWS(
327
- `/agents/test-chat-agent/${room}`
328
- );
329
- const messages2 = collectMessages(ws2);
330
-
331
- await new Promise((r) => setTimeout(r, 100));
332
-
333
- // Send ACK with wrong ID
334
- ws2.send(
335
- JSON.stringify({
336
- type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
337
- id: "req-wrong-id"
338
- })
339
- );
340
-
341
- await new Promise((r) => setTimeout(r, 100));
342
-
343
- // Should NOT receive chunks (only state/mcp messages)
344
- const chunkMsgs = messages2.filter(isUseChatResponseMessage);
345
- expect(chunkMsgs.length).toBe(0);
346
-
347
- ws2.close(1000);
348
- });
349
- });
350
-
351
- describe("Stale stream handling", () => {
352
- it("deletes stale streams on restore (older than 5 minutes)", async () => {
353
- const room = crypto.randomUUID();
354
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
355
-
356
- await new Promise((r) => setTimeout(r, 50));
357
-
358
- const agentStub = await getAgentByName(env.TestChatAgent, room);
359
-
360
- // Insert a stale stream (6 minutes old)
361
- const staleStreamId = "stale-stream-123";
362
- await agentStub.testInsertStaleStream(
363
- staleStreamId,
364
- "req-stale",
365
- 6 * 60 * 1000
366
- );
367
-
368
- // Verify it exists
369
- const beforeRestore = await agentStub.getStreamMetadata(staleStreamId);
370
- expect(beforeRestore).toBeDefined();
371
-
372
- // Trigger restore
373
- await agentStub.testRestoreActiveStream();
374
-
375
- // Should be deleted
376
- const afterRestore = await agentStub.getStreamMetadata(staleStreamId);
377
- expect(afterRestore).toBeNull();
378
-
379
- // Active stream should NOT be set
380
- expect(await agentStub.getActiveStreamId()).toBeNull();
381
-
382
- ws.close(1000);
383
- });
384
-
385
- it("restores fresh streams (under 5 minutes old)", async () => {
386
- const room = crypto.randomUUID();
387
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
388
-
389
- await new Promise((r) => setTimeout(r, 50));
390
-
391
- const agentStub = await getAgentByName(env.TestChatAgent, room);
392
-
393
- // Insert a fresh stream (1 minute old)
394
- const freshStreamId = "fresh-stream-456";
395
- await agentStub.testInsertStaleStream(
396
- freshStreamId,
397
- "req-fresh",
398
- 1 * 60 * 1000
399
- );
400
-
401
- // Clear any active state first
402
- const currentActive = await agentStub.getActiveStreamId();
403
- if (currentActive) {
404
- await agentStub.testCompleteStream(currentActive);
405
- }
406
-
407
- // Trigger restore
408
- await agentStub.testRestoreActiveStream();
409
-
410
- // Should be restored
411
- expect(await agentStub.getActiveStreamId()).toBe(freshStreamId);
412
- expect(await agentStub.getActiveRequestId()).toBe("req-fresh");
413
-
414
- ws.close(1000);
415
- });
416
- });
417
-
418
- describe("Clear history", () => {
419
- it("clears stream data when chat history is cleared", async () => {
420
- const room = crypto.randomUUID();
421
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
422
-
423
- await new Promise((r) => setTimeout(r, 50));
424
-
425
- const agentStub = await getAgentByName(env.TestChatAgent, room);
426
-
427
- // Create a stream with chunks
428
- const streamId = await agentStub.testStartStream("req-clear");
429
- await agentStub.testStoreStreamChunk(
430
- streamId,
431
- '{"type":"text","text":"data"}'
432
- );
433
- await agentStub.testFlushChunkBuffer();
434
-
435
- // Verify data exists
436
- const chunksBefore = await agentStub.getStreamChunks(streamId);
437
- expect(chunksBefore.length).toBe(1);
438
-
439
- // Clear history via WebSocket message
440
- ws.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
441
-
442
- await new Promise((r) => setTimeout(r, 100));
443
-
444
- // Stream data should be cleared
445
- const chunksAfter = await agentStub.getStreamChunks(streamId);
446
- expect(chunksAfter.length).toBe(0);
447
-
448
- const metadataAfter = await agentStub.getStreamMetadata(streamId);
449
- expect(metadataAfter).toBeNull();
450
-
451
- // Active state should be cleared
452
- expect(await agentStub.getActiveStreamId()).toBeNull();
453
-
454
- ws.close(1000);
455
- });
456
- });
457
-
458
- describe("Chunk buffer", () => {
459
- it("flushes chunks before starting a new stream", async () => {
460
- const room = crypto.randomUUID();
461
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
462
-
463
- await new Promise((r) => setTimeout(r, 50));
464
-
465
- const agentStub = await getAgentByName(env.TestChatAgent, room);
466
-
467
- // Start first stream and add chunks without explicit flush
468
- const stream1 = await agentStub.testStartStream("req-1");
469
- await agentStub.testStoreStreamChunk(
470
- stream1,
471
- '{"type":"text","text":"s1c1"}'
472
- );
473
- await agentStub.testStoreStreamChunk(
474
- stream1,
475
- '{"type":"text","text":"s1c2"}'
476
- );
477
-
478
- // Start second stream - should flush first stream's chunks
479
- const stream2 = await agentStub.testStartStream("req-2");
480
-
481
- // First stream's chunks should be persisted
482
- const chunks1 = await agentStub.getStreamChunks(stream1);
483
- expect(chunks1.length).toBe(2);
484
-
485
- // Second stream is active
486
- expect(await agentStub.getActiveStreamId()).toBe(stream2);
487
-
488
- ws.close(1000);
489
- });
490
-
491
- it("flushes on complete", async () => {
492
- const room = crypto.randomUUID();
493
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
494
-
495
- await new Promise((r) => setTimeout(r, 50));
496
-
497
- const agentStub = await getAgentByName(env.TestChatAgent, room);
498
-
499
- const streamId = await agentStub.testStartStream("req-flush");
500
- await agentStub.testStoreStreamChunk(
501
- streamId,
502
- '{"type":"text","text":"final"}'
503
- );
504
-
505
- // Complete - should flush
506
- await agentStub.testCompleteStream(streamId);
507
-
508
- const chunks = await agentStub.getStreamChunks(streamId);
509
- expect(chunks.length).toBe(1);
510
- expect(chunks[0].body).toBe('{"type":"text","text":"final"}');
511
-
512
- ws.close(1000);
513
- });
514
- });
515
-
516
- describe("Completed stream handling", () => {
517
- it("sends done signal for completed streams on resume", async () => {
518
- const room = crypto.randomUUID();
519
-
520
- // Setup - create and complete a stream
521
- const { ws: ws1 } = await connectChatWS(
522
- `/agents/test-chat-agent/${room}`
523
- );
524
- await new Promise((r) => setTimeout(r, 50));
525
-
526
- const agentStub = await getAgentByName(env.TestChatAgent, room);
527
- const streamId = await agentStub.testStartStream("req-done");
528
- await agentStub.testStoreStreamChunk(
529
- streamId,
530
- '{"type":"text","text":"done"}'
531
- );
532
- await agentStub.testCompleteStream(streamId);
533
-
534
- ws1.close();
535
- await new Promise((r) => setTimeout(r, 50));
536
-
537
- // New connection - no resume notification since stream is completed
538
- const { ws: ws2 } = await connectChatWS(
539
- `/agents/test-chat-agent/${room}`
540
- );
541
- const messages2 = collectMessages(ws2);
542
-
543
- await new Promise((r) => setTimeout(r, 100));
544
-
545
- // Should NOT get resume notification for completed stream
546
- const resumeMsg = messages2.find(isStreamResumingMessage);
547
- expect(resumeMsg).toBeUndefined();
548
-
549
- ws2.close(1000);
550
- });
551
- });
552
-
553
- describe("Client-initiated resume (issue #896)", () => {
554
- it("CF_AGENT_STREAM_RESUME_REQUEST triggers resume notification", async () => {
555
- const room = crypto.randomUUID();
556
-
557
- // First connection: start a stream
558
- const { ws: ws1 } = await connectChatWS(
559
- `/agents/test-chat-agent/${room}`
560
- );
561
- await new Promise((r) => setTimeout(r, 50));
562
-
563
- const agentStub = await getAgentByName(env.TestChatAgent, room);
564
- const streamId = await agentStub.testStartStream("req-client-resume");
565
- await agentStub.testStoreStreamChunk(
566
- streamId,
567
- '{"type":"text-start","id":"t1"}'
568
- );
569
- await agentStub.testStoreStreamChunk(
570
- streamId,
571
- '{"type":"text-delta","id":"t1","delta":"hello"}'
572
- );
573
- await agentStub.testFlushChunkBuffer();
574
-
575
- ws1.close();
576
- await new Promise((r) => setTimeout(r, 50));
577
-
578
- // Second connection: send CF_AGENT_STREAM_RESUME_REQUEST
579
- const { ws: ws2 } = await connectChatWS(
580
- `/agents/test-chat-agent/${room}`
581
- );
582
- const messages2 = collectMessages(ws2);
583
-
584
- // Wait briefly for any onConnect push (which we'll also get)
585
- await new Promise((r) => setTimeout(r, 50));
586
-
587
- // Send the client-initiated resume request
588
- ws2.send(
589
- JSON.stringify({
590
- type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST
591
- })
592
- );
593
-
594
- await new Promise((r) => setTimeout(r, 100));
595
-
596
- // Should have received CF_AGENT_STREAM_RESUMING (from request, not just onConnect)
597
- const resumeMsgs = messages2.filter(isStreamResumingMessage);
598
- // May get 2 (one from onConnect, one from request) or 1 if timing collapses them
599
- expect(resumeMsgs.length).toBeGreaterThanOrEqual(1);
600
-
601
- ws2.close(1000);
602
- });
603
-
604
- it("CF_AGENT_STREAM_RESUME_REQUEST with no active stream is a no-op", async () => {
605
- const room = crypto.randomUUID();
606
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
607
- const messages = collectMessages(ws);
608
-
609
- await new Promise((r) => setTimeout(r, 50));
610
-
611
- // Send resume request when there's no active stream
612
- ws.send(
613
- JSON.stringify({
614
- type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST
615
- })
616
- );
617
-
618
- await new Promise((r) => setTimeout(r, 100));
619
-
620
- // Should NOT get CF_AGENT_STREAM_RESUMING
621
- const resumeMsg = messages.find(isStreamResumingMessage);
622
- expect(resumeMsg).toBeUndefined();
623
-
624
- ws.close(1000);
625
- });
626
-
627
- it("replayed chunks have replay=true flag", async () => {
628
- const room = crypto.randomUUID();
629
-
630
- const { ws: ws1 } = await connectChatWS(
631
- `/agents/test-chat-agent/${room}`
632
- );
633
- await new Promise((r) => setTimeout(r, 50));
634
-
635
- const agentStub = await getAgentByName(env.TestChatAgent, room);
636
- // Start a stream and add chunks but do NOT complete it
637
- // (stream must be active for resume to work)
638
- const streamId = await agentStub.testStartStream("req-replay-flag");
639
- await agentStub.testStoreStreamChunk(
640
- streamId,
641
- '{"type":"text-start","id":"t1"}'
642
- );
643
- await agentStub.testStoreStreamChunk(
644
- streamId,
645
- '{"type":"text-delta","id":"t1","delta":"test"}'
646
- );
647
- await agentStub.testFlushChunkBuffer();
648
-
649
- ws1.close();
650
- await new Promise((r) => setTimeout(r, 50));
651
-
652
- // Reconnect — active stream triggers resume
653
- const { ws: ws2 } = await connectChatWS(
654
- `/agents/test-chat-agent/${room}`
655
- );
656
- const messages2 = collectMessages(ws2);
657
-
658
- await new Promise((r) => setTimeout(r, 50));
659
-
660
- // Send resume request
661
- ws2.send(
662
- JSON.stringify({
663
- type: MessageType.CF_AGENT_STREAM_RESUME_REQUEST
664
- })
665
- );
666
-
667
- await new Promise((r) => setTimeout(r, 50));
668
-
669
- // ACK the resuming notification
670
- const resumeMsg = messages2.find(isStreamResumingMessage);
671
- expect(resumeMsg).toBeDefined();
672
-
673
- ws2.send(
674
- JSON.stringify({
675
- type: MessageType.CF_AGENT_STREAM_RESUME_ACK,
676
- id: (resumeMsg as { id: string }).id
677
- })
678
- );
679
-
680
- await new Promise((r) => setTimeout(r, 200));
681
-
682
- // All CF_AGENT_USE_CHAT_RESPONSE messages should have replay=true
683
- const responseMessages = messages2.filter(isUseChatResponseMessage);
684
- expect(responseMessages.length).toBeGreaterThan(0);
685
-
686
- for (const msg of responseMessages) {
687
- expect((msg as { replay?: boolean }).replay).toBe(true);
688
- }
689
-
690
- ws2.close(1000);
691
- });
692
- });
693
-
694
- describe("clearAll clears chunk buffer", () => {
695
- it("buffered chunks are not flushed to SQLite after clearAll", async () => {
696
- const room = crypto.randomUUID();
697
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
698
- await new Promise((r) => setTimeout(r, 50));
699
-
700
- const agentStub = await getAgentByName(env.TestChatAgent, room);
701
-
702
- // Start a stream and buffer some chunks (do NOT flush)
703
- const streamId = await agentStub.testStartStream("req-buffer-clear");
704
- await agentStub.testStoreStreamChunk(streamId, "chunk-1");
705
- await agentStub.testStoreStreamChunk(streamId, "chunk-2");
706
-
707
- // Chunks should be in buffer but not yet in SQLite (buffer size < 10)
708
- let chunks = await agentStub.getStreamChunks(streamId);
709
- expect(chunks.length).toBe(0); // Still in memory buffer
710
-
711
- // Clear all — should discard the buffer
712
- ws.send(JSON.stringify({ type: "cf_agent_chat_clear" }));
713
- await new Promise((r) => setTimeout(r, 100));
714
-
715
- // Flush should be a no-op since buffer was cleared
716
- await agentStub.testFlushChunkBuffer();
717
- chunks = await agentStub.getStreamChunks(streamId);
718
- expect(chunks.length).toBe(0);
719
-
720
- // Wait before close to let the agent settle
721
- await new Promise((r) => setTimeout(r, 50));
722
- ws.close(1000);
723
- });
724
- });
725
-
726
- describe("errored stream cleanup", () => {
727
- it("errored streams are cleaned up alongside completed streams", async () => {
728
- const room = crypto.randomUUID();
729
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
730
- await new Promise((r) => setTimeout(r, 50));
731
-
732
- const agentStub = await getAgentByName(env.TestChatAgent, room);
733
-
734
- // Insert an old errored stream (25 hours old, past the 24h cleanup threshold)
735
- await agentStub.testInsertOldErroredStream(
736
- "old-errored",
737
- "req-errored",
738
- 25 * 60 * 60 * 1000
739
- );
740
-
741
- // Verify the errored stream exists
742
- const metadata = await agentStub.getStreamMetadata("old-errored");
743
- expect(metadata?.status).toBe("error");
744
-
745
- // Trigger cleanup by completing a dummy stream
746
- // (cleanup runs periodically inside completeStream)
747
- await agentStub.testTriggerStreamCleanup();
748
-
749
- // The old errored stream should be cleaned up
750
- const afterMetadata = await agentStub.getStreamMetadata("old-errored");
751
- expect(afterMetadata).toBeNull();
752
-
753
- // Wait before close to let the agent settle
754
- await new Promise((r) => setTimeout(r, 50));
755
- ws.close(1000);
756
- });
757
- });
758
- });