@cloudflare/ai-chat 0.0.8 → 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 +89 -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 +114 -76
  10. package/dist/index.js +745 -629
  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 +244 -258
  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 +831 -1137
  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 +385 -461
  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 +3 -3
  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 +3 -3
  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 +59 -24
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
@@ -0,0 +1,441 @@
1
+ /**
2
+ * ResumableStream: Standalone class for buffering, persisting, and replaying
3
+ * stream chunks in SQLite. Extracted from AIChatAgent to separate concerns.
4
+ *
5
+ * Handles:
6
+ * - Chunk buffering (batched writes to SQLite for performance)
7
+ * - Stream lifecycle (start, complete, error)
8
+ * - Chunk replay for reconnecting clients
9
+ * - Stale stream cleanup
10
+ * - Active stream restoration after agent restart
11
+ */
12
+
13
+ import { nanoid } from "nanoid";
14
+ import type { Connection } from "agents";
15
+ import { MessageType } from "./types";
16
+
17
+ /** Number of chunks to buffer before flushing to SQLite */
18
+ const CHUNK_BUFFER_SIZE = 10;
19
+ /** Maximum buffer size to prevent memory issues on rapid reconnections */
20
+ const CHUNK_BUFFER_MAX_SIZE = 100;
21
+ /** Maximum age for a "streaming" stream before considering it stale (ms) - 5 minutes */
22
+ const STREAM_STALE_THRESHOLD_MS = 5 * 60 * 1000;
23
+ /** Default cleanup interval for old streams (ms) - every 10 minutes */
24
+ const CLEANUP_INTERVAL_MS = 10 * 60 * 1000;
25
+ /** Default age threshold for cleaning up completed streams (ms) - 24 hours */
26
+ const CLEANUP_AGE_THRESHOLD_MS = 24 * 60 * 60 * 1000;
27
+ /** Shared encoder for UTF-8 byte length measurement */
28
+ const textEncoder = new TextEncoder();
29
+
30
+ /**
31
+ * Stored stream chunk for resumable streaming
32
+ */
33
+ type StreamChunk = {
34
+ id: string;
35
+ stream_id: string;
36
+ body: string;
37
+ chunk_index: number;
38
+ created_at: number;
39
+ };
40
+
41
+ /**
42
+ * Stream metadata for tracking active streams
43
+ */
44
+ type StreamMetadata = {
45
+ id: string;
46
+ request_id: string;
47
+ status: "streaming" | "completed" | "error";
48
+ created_at: number;
49
+ completed_at: number | null;
50
+ };
51
+
52
+ /**
53
+ * Minimal SQL interface matching Agent's this.sql tagged template.
54
+ * Allows ResumableStream to work with the Agent's SQLite without
55
+ * depending on the full Agent class.
56
+ */
57
+ export type SqlTaggedTemplate = {
58
+ <T = Record<string, unknown>>(
59
+ strings: TemplateStringsArray,
60
+ ...values: (string | number | boolean | null)[]
61
+ ): T[];
62
+ };
63
+
64
+ export class ResumableStream {
65
+ private _activeStreamId: string | null = null;
66
+ private _activeRequestId: string | null = null;
67
+ private _streamChunkIndex = 0;
68
+
69
+ private _chunkBuffer: Array<{
70
+ id: string;
71
+ streamId: string;
72
+ body: string;
73
+ index: number;
74
+ }> = [];
75
+ private _isFlushingChunks = false;
76
+ private _lastCleanupTime = 0;
77
+
78
+ constructor(private sql: SqlTaggedTemplate) {
79
+ // Create tables for stream chunks and metadata
80
+ this.sql`create table if not exists cf_ai_chat_stream_chunks (
81
+ id text primary key,
82
+ stream_id text not null,
83
+ body text not null,
84
+ chunk_index integer not null,
85
+ created_at integer not null
86
+ )`;
87
+
88
+ this.sql`create table if not exists cf_ai_chat_stream_metadata (
89
+ id text primary key,
90
+ request_id text not null,
91
+ status text not null,
92
+ created_at integer not null,
93
+ completed_at integer
94
+ )`;
95
+
96
+ this.sql`create index if not exists idx_stream_chunks_stream_id
97
+ on cf_ai_chat_stream_chunks(stream_id, chunk_index)`;
98
+
99
+ // Restore any active stream from a previous session
100
+ this.restore();
101
+ }
102
+
103
+ // ── State accessors ────────────────────────────────────────────────
104
+
105
+ get activeStreamId(): string | null {
106
+ return this._activeStreamId;
107
+ }
108
+
109
+ get activeRequestId(): string | null {
110
+ return this._activeRequestId;
111
+ }
112
+
113
+ hasActiveStream(): boolean {
114
+ return this._activeStreamId !== null;
115
+ }
116
+
117
+ // ── Stream lifecycle ───────────────────────────────────────────────
118
+
119
+ /**
120
+ * Start tracking a new stream for resumable streaming.
121
+ * Creates metadata entry in SQLite and sets up tracking state.
122
+ * @param requestId - The unique ID of the chat request
123
+ * @returns The generated stream ID
124
+ */
125
+ start(requestId: string): string {
126
+ // Flush any pending chunks from previous streams to prevent mixing
127
+ this.flushBuffer();
128
+
129
+ const streamId = nanoid();
130
+ this._activeStreamId = streamId;
131
+ this._activeRequestId = requestId;
132
+ this._streamChunkIndex = 0;
133
+
134
+ this.sql`
135
+ insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
136
+ values (${streamId}, ${requestId}, 'streaming', ${Date.now()})
137
+ `;
138
+
139
+ return streamId;
140
+ }
141
+
142
+ /**
143
+ * Mark a stream as completed and flush any pending chunks.
144
+ * @param streamId - The stream to mark as completed
145
+ */
146
+ complete(streamId: string) {
147
+ this.flushBuffer();
148
+
149
+ this.sql`
150
+ update cf_ai_chat_stream_metadata
151
+ set status = 'completed', completed_at = ${Date.now()}
152
+ where id = ${streamId}
153
+ `;
154
+ this._activeStreamId = null;
155
+ this._activeRequestId = null;
156
+ this._streamChunkIndex = 0;
157
+
158
+ // Periodically clean up old streams
159
+ this._maybeCleanupOldStreams();
160
+ }
161
+
162
+ /**
163
+ * Mark a stream as errored and clean up state.
164
+ * @param streamId - The stream to mark as errored
165
+ */
166
+ markError(streamId: string) {
167
+ this.flushBuffer();
168
+
169
+ this.sql`
170
+ update cf_ai_chat_stream_metadata
171
+ set status = 'error', completed_at = ${Date.now()}
172
+ where id = ${streamId}
173
+ `;
174
+ this._activeStreamId = null;
175
+ this._activeRequestId = null;
176
+ this._streamChunkIndex = 0;
177
+ }
178
+
179
+ // ── Chunk storage ──────────────────────────────────────────────────
180
+
181
+ /** Maximum chunk body size before skipping storage (bytes). Prevents SQLite row limit crash. */
182
+ private static CHUNK_MAX_BYTES = 1_800_000;
183
+
184
+ /**
185
+ * Buffer a stream chunk for batch write to SQLite.
186
+ * Chunks exceeding the row size limit are skipped to prevent crashes.
187
+ * The chunk is still broadcast to live clients (caller handles that),
188
+ * but will be missing from replay on reconnection.
189
+ * @param streamId - The stream this chunk belongs to
190
+ * @param body - The serialized chunk body
191
+ */
192
+ storeChunk(streamId: string, body: string) {
193
+ // Guard against chunks that would exceed SQLite row limit.
194
+ // The chunk is still broadcast to live clients; only replay storage is skipped.
195
+ const bodyBytes = textEncoder.encode(body).byteLength;
196
+ if (bodyBytes > ResumableStream.CHUNK_MAX_BYTES) {
197
+ console.warn(
198
+ `[ResumableStream] Skipping oversized chunk (${bodyBytes} bytes) ` +
199
+ `to prevent SQLite row limit crash. Live clients still receive it.`
200
+ );
201
+ return;
202
+ }
203
+
204
+ // Force flush if buffer is at max to prevent memory issues
205
+ if (this._chunkBuffer.length >= CHUNK_BUFFER_MAX_SIZE) {
206
+ this.flushBuffer();
207
+ }
208
+
209
+ this._chunkBuffer.push({
210
+ id: nanoid(),
211
+ streamId,
212
+ body,
213
+ index: this._streamChunkIndex
214
+ });
215
+ this._streamChunkIndex++;
216
+
217
+ // Flush when buffer reaches threshold
218
+ if (this._chunkBuffer.length >= CHUNK_BUFFER_SIZE) {
219
+ this.flushBuffer();
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Flush buffered chunks to SQLite in a single batch.
225
+ * Uses a lock to prevent concurrent flush operations.
226
+ */
227
+ flushBuffer() {
228
+ if (this._isFlushingChunks || this._chunkBuffer.length === 0) {
229
+ return;
230
+ }
231
+
232
+ this._isFlushingChunks = true;
233
+ try {
234
+ const chunks = this._chunkBuffer;
235
+ this._chunkBuffer = [];
236
+
237
+ const now = Date.now();
238
+ for (const chunk of chunks) {
239
+ this.sql`
240
+ insert into cf_ai_chat_stream_chunks (id, stream_id, body, chunk_index, created_at)
241
+ values (${chunk.id}, ${chunk.streamId}, ${chunk.body}, ${chunk.index}, ${now})
242
+ `;
243
+ }
244
+ } finally {
245
+ this._isFlushingChunks = false;
246
+ }
247
+ }
248
+
249
+ // ── Chunk replay ───────────────────────────────────────────────────
250
+
251
+ /**
252
+ * Send stored stream chunks to a connection for replay.
253
+ * Chunks are marked with replay: true so the client can batch-apply them.
254
+ * @param connection - The WebSocket connection
255
+ * @param requestId - The original request ID
256
+ */
257
+ replayChunks(connection: Connection, requestId: string) {
258
+ const streamId = this._activeStreamId;
259
+ if (!streamId) return;
260
+
261
+ this.flushBuffer();
262
+
263
+ const chunks = this.sql<StreamChunk>`
264
+ select * from cf_ai_chat_stream_chunks
265
+ where stream_id = ${streamId}
266
+ order by chunk_index asc
267
+ `;
268
+
269
+ for (const chunk of chunks || []) {
270
+ connection.send(
271
+ JSON.stringify({
272
+ body: chunk.body,
273
+ done: false,
274
+ id: requestId,
275
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
276
+ replay: true
277
+ })
278
+ );
279
+ }
280
+
281
+ // If the stream completed between our check above and now, send done.
282
+ // In practice this cannot happen (DO is single-threaded and replay is
283
+ // synchronous), but we guard defensively in case the flow changes.
284
+ if (this._activeStreamId !== streamId) {
285
+ connection.send(
286
+ JSON.stringify({
287
+ body: "",
288
+ done: true,
289
+ id: requestId,
290
+ type: MessageType.CF_AGENT_USE_CHAT_RESPONSE,
291
+ replay: true
292
+ })
293
+ );
294
+ }
295
+ }
296
+
297
+ // ── Restore / cleanup ──────────────────────────────────────────────
298
+
299
+ /**
300
+ * Restore active stream state if the agent was restarted during streaming.
301
+ * Validates stream freshness to avoid sending stale resume notifications.
302
+ */
303
+ restore() {
304
+ const activeStreams = this.sql<StreamMetadata>`
305
+ select * from cf_ai_chat_stream_metadata
306
+ where status = 'streaming'
307
+ order by created_at desc
308
+ limit 1
309
+ `;
310
+
311
+ if (activeStreams && activeStreams.length > 0) {
312
+ const stream = activeStreams[0];
313
+ const streamAge = Date.now() - stream.created_at;
314
+
315
+ // Check if stream is stale; delete to free storage
316
+ if (streamAge > STREAM_STALE_THRESHOLD_MS) {
317
+ this
318
+ .sql`delete from cf_ai_chat_stream_chunks where stream_id = ${stream.id}`;
319
+ this
320
+ .sql`delete from cf_ai_chat_stream_metadata where id = ${stream.id}`;
321
+ console.warn(
322
+ `[ResumableStream] Deleted stale stream ${stream.id} (age: ${Math.round(streamAge / 1000)}s)`
323
+ );
324
+ return;
325
+ }
326
+
327
+ this._activeStreamId = stream.id;
328
+ this._activeRequestId = stream.request_id;
329
+
330
+ // Get the last chunk index
331
+ const lastChunk = this.sql<{ max_index: number }>`
332
+ select max(chunk_index) as max_index
333
+ from cf_ai_chat_stream_chunks
334
+ where stream_id = ${this._activeStreamId}
335
+ `;
336
+ this._streamChunkIndex =
337
+ lastChunk && lastChunk[0]?.max_index != null
338
+ ? lastChunk[0].max_index + 1
339
+ : 0;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Clear all stream data (called on chat history clear).
345
+ */
346
+ clearAll() {
347
+ this._chunkBuffer = [];
348
+ this.sql`delete from cf_ai_chat_stream_chunks`;
349
+ this.sql`delete from cf_ai_chat_stream_metadata`;
350
+ this._activeStreamId = null;
351
+ this._activeRequestId = null;
352
+ this._streamChunkIndex = 0;
353
+ }
354
+
355
+ /**
356
+ * Drop all stream tables (called on destroy).
357
+ */
358
+ destroy() {
359
+ this.flushBuffer();
360
+ this.sql`drop table if exists cf_ai_chat_stream_chunks`;
361
+ this.sql`drop table if exists cf_ai_chat_stream_metadata`;
362
+ this._activeStreamId = null;
363
+ this._activeRequestId = null;
364
+ }
365
+
366
+ // ── Internal ───────────────────────────────────────────────────────
367
+
368
+ private _maybeCleanupOldStreams() {
369
+ const now = Date.now();
370
+ if (now - this._lastCleanupTime < CLEANUP_INTERVAL_MS) {
371
+ return;
372
+ }
373
+ this._lastCleanupTime = now;
374
+
375
+ const cutoff = now - CLEANUP_AGE_THRESHOLD_MS;
376
+ this.sql`
377
+ delete from cf_ai_chat_stream_chunks
378
+ where stream_id in (
379
+ select id from cf_ai_chat_stream_metadata
380
+ where status in ('completed', 'error') and completed_at < ${cutoff}
381
+ )
382
+ `;
383
+ this.sql`
384
+ delete from cf_ai_chat_stream_metadata
385
+ where status in ('completed', 'error') and completed_at < ${cutoff}
386
+ `;
387
+ }
388
+
389
+ // ── Test helpers (matching old AIChatAgent test API) ────────────────
390
+
391
+ /** @internal For testing only */
392
+ getStreamChunks(
393
+ streamId: string
394
+ ): Array<{ body: string; chunk_index: number }> {
395
+ return (
396
+ this.sql<{ body: string; chunk_index: number }>`
397
+ select body, chunk_index from cf_ai_chat_stream_chunks
398
+ where stream_id = ${streamId}
399
+ order by chunk_index asc
400
+ ` || []
401
+ );
402
+ }
403
+
404
+ /** @internal For testing only */
405
+ getStreamMetadata(
406
+ streamId: string
407
+ ): { status: string; request_id: string } | null {
408
+ const result = this.sql<{ status: string; request_id: string }>`
409
+ select status, request_id from cf_ai_chat_stream_metadata
410
+ where id = ${streamId}
411
+ `;
412
+ return result && result.length > 0 ? result[0] : null;
413
+ }
414
+
415
+ /** @internal For testing only */
416
+ getAllStreamMetadata(): Array<{
417
+ id: string;
418
+ status: string;
419
+ request_id: string;
420
+ created_at: number;
421
+ }> {
422
+ return (
423
+ this.sql<{
424
+ id: string;
425
+ status: string;
426
+ request_id: string;
427
+ created_at: number;
428
+ }>`select id, status, request_id, created_at from cf_ai_chat_stream_metadata` ||
429
+ []
430
+ );
431
+ }
432
+
433
+ /** @internal For testing only */
434
+ insertStaleStream(streamId: string, requestId: string, ageMs: number): void {
435
+ const createdAt = Date.now() - ageMs;
436
+ this.sql`
437
+ insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
438
+ values (${streamId}, ${requestId}, 'streaming', ${createdAt})
439
+ `;
440
+ }
441
+ }
@@ -80,6 +80,6 @@ describe("AIChatAgent Connection Context - Issue #711", () => {
80
80
  // The connection ID should match between onChatMessage and nested function
81
81
  expect(nestedContext?.connectionId).toBe(capturedContext?.connectionId);
82
82
 
83
- ws.close();
83
+ ws.close(1000);
84
84
  });
85
85
  });
@@ -88,7 +88,7 @@ describe("Chat Agent Persistence", () => {
88
88
  const secondDone = await secondPromise;
89
89
  expect(secondDone).toBe(true);
90
90
 
91
- ws.close();
91
+ ws.close(1000);
92
92
 
93
93
  const getMessagesReq = new Request(
94
94
  `http://example.com/agents/test-chat-agent/${room}/get-messages`
@@ -161,7 +161,7 @@ describe("Chat Agent Persistence", () => {
161
161
 
162
162
  await new Promise((resolve) => setTimeout(resolve, 100));
163
163
 
164
- ws.close();
164
+ ws.close(1000);
165
165
 
166
166
  const getMessagesReq = new Request(
167
167
  `http://example.com/agents/test-chat-agent/${room}/get-messages`
@@ -238,7 +238,7 @@ describe("Chat Agent Persistence", () => {
238
238
  expect(toolPart2.output).toBe("10am");
239
239
  expect(toolPart2.input).toEqual({ location: "London" });
240
240
 
241
- ws.close();
241
+ ws.close(1000);
242
242
  });
243
243
 
244
244
  it("persists multiple messages with tool calls and outputs correctly", async () => {
@@ -344,7 +344,7 @@ describe("Chat Agent Persistence", () => {
344
344
  expect(finalResponse).toBeDefined();
345
345
  expect(finalResponse?.parts[0].type).toBe("text");
346
346
 
347
- ws.close();
347
+ ws.close(1000);
348
348
  });
349
349
 
350
350
  it("maintains chronological order when tool outputs arrive after the final response", async () => {
@@ -421,6 +421,6 @@ describe("Chat Agent Persistence", () => {
421
421
  "assistant-2"
422
422
  ]);
423
423
 
424
- ws.close();
424
+ ws.close(1000);
425
425
  });
426
426
  });
@@ -0,0 +1,132 @@
1
+ import { env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import { MessageType } from "../types";
4
+ import type { UIMessage as ChatMessage } from "ai";
5
+ import { connectChatWS } from "./test-utils";
6
+ import { getAgentByName } from "agents";
7
+
8
+ describe("Clear History", () => {
9
+ it("clears all messages, stream data, and broadcasts to other connections", async () => {
10
+ const room = crypto.randomUUID();
11
+ const { ws: ws1 } = await connectChatWS(`/agents/test-chat-agent/${room}`);
12
+ const { ws: ws2 } = await connectChatWS(`/agents/test-chat-agent/${room}`);
13
+ await new Promise((r) => setTimeout(r, 50));
14
+
15
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
16
+
17
+ // Persist some messages
18
+ const messages: ChatMessage[] = [
19
+ {
20
+ id: "clear-1",
21
+ role: "user",
22
+ parts: [{ type: "text", text: "Hello" }]
23
+ },
24
+ {
25
+ id: "clear-2",
26
+ role: "assistant",
27
+ parts: [{ type: "text", text: "Hi" }]
28
+ }
29
+ ];
30
+ await agentStub.persistMessages(messages);
31
+
32
+ // Also create some stream data
33
+ const streamId = await agentStub.testStartStream("req-clear-test");
34
+ await agentStub.testStoreStreamChunk(
35
+ streamId,
36
+ '{"type":"text","text":"stream-data"}'
37
+ );
38
+ await agentStub.testFlushChunkBuffer();
39
+
40
+ // Verify data exists before clear
41
+ const beforeMessages = await agentStub.getPersistedMessages();
42
+ expect((beforeMessages as ChatMessage[]).length).toBe(2);
43
+ const beforeChunks = await agentStub.getStreamChunks(streamId);
44
+ expect(beforeChunks.length).toBe(1);
45
+
46
+ // Listen for clear broadcast on ws2
47
+ let ws2ReceivedClear = false;
48
+ ws2.addEventListener("message", (e: MessageEvent) => {
49
+ const data = JSON.parse(e.data as string);
50
+ if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
51
+ ws2ReceivedClear = true;
52
+ }
53
+ });
54
+
55
+ // Clear via ws1
56
+ ws1.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
57
+
58
+ await new Promise((r) => setTimeout(r, 100));
59
+
60
+ // Messages should be cleared
61
+ const afterMessages = await agentStub.getPersistedMessages();
62
+ expect((afterMessages as ChatMessage[]).length).toBe(0);
63
+
64
+ // Stream data should be cleared
65
+ const afterChunks = await agentStub.getStreamChunks(streamId);
66
+ expect(afterChunks.length).toBe(0);
67
+ const afterMeta = await agentStub.getStreamMetadata(streamId);
68
+ expect(afterMeta).toBeNull();
69
+
70
+ // Active stream state should be cleared
71
+ expect(await agentStub.getActiveStreamId()).toBeNull();
72
+ expect(await agentStub.getActiveRequestId()).toBeNull();
73
+
74
+ // ws2 should have received the clear broadcast
75
+ expect(ws2ReceivedClear).toBe(true);
76
+
77
+ ws1.close();
78
+ ws2.close(1000);
79
+ });
80
+
81
+ it("resets abort controllers when clearing history", async () => {
82
+ const room = crypto.randomUUID();
83
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
84
+ await new Promise((r) => setTimeout(r, 50));
85
+
86
+ // Start a request
87
+ const userMessage: ChatMessage = {
88
+ id: "msg-abort-1",
89
+ role: "user",
90
+ parts: [{ type: "text", text: "Hello" }]
91
+ };
92
+
93
+ let resolvePromise: (value: boolean) => void;
94
+ const donePromise = new Promise<boolean>((res) => {
95
+ resolvePromise = res;
96
+ });
97
+ const timeout = setTimeout(() => resolvePromise(false), 2000);
98
+
99
+ ws.addEventListener("message", (e: MessageEvent) => {
100
+ const data = JSON.parse(e.data as string);
101
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
102
+ clearTimeout(timeout);
103
+ resolvePromise(true);
104
+ }
105
+ });
106
+
107
+ ws.send(
108
+ JSON.stringify({
109
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
110
+ id: "req-abort-1",
111
+ init: {
112
+ method: "POST",
113
+ body: JSON.stringify({ messages: [userMessage] })
114
+ }
115
+ })
116
+ );
117
+
118
+ await donePromise;
119
+
120
+ // Clear should not throw even with prior requests
121
+ ws.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
122
+
123
+ await new Promise((r) => setTimeout(r, 100));
124
+
125
+ // Agent should be in clean state
126
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
127
+ const afterMessages = await agentStub.getPersistedMessages();
128
+ expect((afterMessages as ChatMessage[]).length).toBe(0);
129
+
130
+ ws.close(1000);
131
+ });
132
+ });