@cloudflare/ai-chat 0.1.4 → 0.1.6

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 (66) 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 +170 -28
  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 +125 -31
  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 -244
  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/types.ts +0 -152
  64. package/src/ws-chat-transport.ts +0 -203
  65. package/tsconfig.json +0 -4
  66. package/vitest.config.ts +0 -7
@@ -1,441 +0,0 @@
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
- }
@@ -1,280 +0,0 @@
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, isUseChatResponseMessage } from "./test-utils";
6
- import { getAgentByName } from "agents";
7
-
8
- /**
9
- * Helper: connect to the SlowStreamAgent
10
- */
11
- function connectSlowStream(room: string) {
12
- return connectChatWS(`/agents/slow-stream-agent/${room}`);
13
- }
14
-
15
- /**
16
- * Helper: send a chat request with custom body fields
17
- */
18
- function sendChatRequest(
19
- ws: WebSocket,
20
- requestId: string,
21
- messages: ChatMessage[],
22
- extraBody?: Record<string, unknown>
23
- ) {
24
- ws.send(
25
- JSON.stringify({
26
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
27
- id: requestId,
28
- init: {
29
- method: "POST",
30
- body: JSON.stringify({ messages, ...extraBody })
31
- }
32
- })
33
- );
34
- }
35
-
36
- /**
37
- * Helper: send a cancel request
38
- */
39
- function sendCancel(ws: WebSocket, requestId: string) {
40
- ws.send(
41
- JSON.stringify({
42
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL,
43
- id: requestId
44
- })
45
- );
46
- }
47
-
48
- /**
49
- * Helper: collect messages from a WebSocket until a done message arrives or timeout
50
- */
51
- function collectMessages(
52
- ws: WebSocket,
53
- timeoutMs = 5000
54
- ): Promise<{ messages: unknown[]; timedOut: boolean }> {
55
- const messages: unknown[] = [];
56
- let resolve: (value: { messages: unknown[]; timedOut: boolean }) => void;
57
- const promise = new Promise<{ messages: unknown[]; timedOut: boolean }>(
58
- (r) => {
59
- resolve = r;
60
- }
61
- );
62
-
63
- const timeout = setTimeout(() => {
64
- ws.removeEventListener("message", handler);
65
- resolve({ messages, timedOut: true });
66
- }, timeoutMs);
67
-
68
- function handler(e: MessageEvent) {
69
- const data = JSON.parse(e.data as string);
70
- messages.push(data);
71
- if (isUseChatResponseMessage(data) && data.done) {
72
- clearTimeout(timeout);
73
- ws.removeEventListener("message", handler);
74
- resolve({ messages, timedOut: false });
75
- }
76
- }
77
-
78
- ws.addEventListener("message", handler);
79
- return promise;
80
- }
81
-
82
- const userMessage: ChatMessage = {
83
- id: "msg1",
84
- role: "user",
85
- parts: [{ type: "text", text: "Hello" }]
86
- };
87
-
88
- describe("Cancel request", () => {
89
- it("cancel during plaintext streaming sends done and stops chunks", async () => {
90
- const room = crypto.randomUUID();
91
- const { ws } = await connectSlowStream(room);
92
- await new Promise((r) => setTimeout(r, 50));
93
-
94
- const requestId = "req-cancel-plain";
95
-
96
- // Start collecting messages
97
- const collecting = collectMessages(ws);
98
-
99
- // Send a slow plaintext streaming request (20 chunks × 50ms = ~1s total)
100
- sendChatRequest(ws, requestId, [userMessage], {
101
- format: "plaintext",
102
- chunkCount: 20,
103
- chunkDelayMs: 50
104
- });
105
-
106
- // Wait for a couple of chunks to arrive, then cancel
107
- await new Promise((r) => setTimeout(r, 200));
108
- sendCancel(ws, requestId);
109
-
110
- const { messages, timedOut } = await collecting;
111
- expect(timedOut).toBe(false);
112
-
113
- // Should have received a done message
114
- const chatResponses = messages.filter(isUseChatResponseMessage);
115
- const doneMsg = chatResponses.find((m) => m.done === true);
116
- expect(doneMsg).toBeDefined();
117
-
118
- // Should NOT have received all 20 chunks worth of text-delta events
119
- // (we cancelled after ~200ms, which is ~4 chunks at 50ms each)
120
- const textDeltas = chatResponses.filter((m) => {
121
- if (!m.body || typeof m.body !== "string" || m.body.length === 0)
122
- return false;
123
- try {
124
- const parsed = JSON.parse(m.body);
125
- return parsed.type === "text-delta";
126
- } catch {
127
- return false;
128
- }
129
- });
130
- expect(textDeltas.length).toBeLessThan(20);
131
-
132
- ws.close(1000);
133
- });
134
-
135
- it("cancel during SSE streaming sends done and stops chunks", async () => {
136
- const room = crypto.randomUUID();
137
- const { ws } = await connectSlowStream(room);
138
- await new Promise((r) => setTimeout(r, 50));
139
-
140
- const requestId = "req-cancel-sse";
141
-
142
- const collecting = collectMessages(ws);
143
-
144
- sendChatRequest(ws, requestId, [userMessage], {
145
- format: "sse",
146
- chunkCount: 20,
147
- chunkDelayMs: 50
148
- });
149
-
150
- // Wait for some chunks then cancel
151
- await new Promise((r) => setTimeout(r, 200));
152
- sendCancel(ws, requestId);
153
-
154
- const { messages, timedOut } = await collecting;
155
- expect(timedOut).toBe(false);
156
-
157
- // Should have received a done message
158
- const chatResponses = messages.filter(isUseChatResponseMessage);
159
- const doneMsg = chatResponses.find((m) => m.done === true);
160
- expect(doneMsg).toBeDefined();
161
-
162
- // Should have fewer chunks than a full stream
163
- const dataChunks = chatResponses.filter(
164
- (m) => m.body && typeof m.body === "string" && m.body.length > 0
165
- );
166
- expect(dataChunks.length).toBeLessThan(20);
167
-
168
- ws.close(1000);
169
- });
170
-
171
- it("abort controller is cleaned up after cancel", async () => {
172
- const room = crypto.randomUUID();
173
- const { ws } = await connectSlowStream(room);
174
- await new Promise((r) => setTimeout(r, 50));
175
-
176
- const agentStub = await getAgentByName(env.SlowStreamAgent, room);
177
-
178
- const requestId = "req-cancel-cleanup";
179
- const collecting = collectMessages(ws);
180
-
181
- sendChatRequest(ws, requestId, [userMessage], {
182
- format: "plaintext",
183
- chunkCount: 20,
184
- chunkDelayMs: 50
185
- });
186
-
187
- await new Promise((r) => setTimeout(r, 200));
188
- sendCancel(ws, requestId);
189
-
190
- await collecting;
191
-
192
- // Allow cleanup to complete
193
- await new Promise((r) => setTimeout(r, 200));
194
-
195
- const count = await agentStub.getAbortControllerCount();
196
- expect(count).toBe(0);
197
-
198
- ws.close(1000);
199
- });
200
-
201
- it("cancel with abortSignal wired to stream stops faster", async () => {
202
- const room = crypto.randomUUID();
203
- const { ws } = await connectSlowStream(room);
204
- await new Promise((r) => setTimeout(r, 50));
205
-
206
- const requestId = "req-cancel-with-signal";
207
- const collecting = collectMessages(ws);
208
-
209
- sendChatRequest(ws, requestId, [userMessage], {
210
- format: "plaintext",
211
- useAbortSignal: true,
212
- chunkCount: 20,
213
- chunkDelayMs: 50
214
- });
215
-
216
- await new Promise((r) => setTimeout(r, 200));
217
- sendCancel(ws, requestId);
218
-
219
- const { messages, timedOut } = await collecting;
220
- expect(timedOut).toBe(false);
221
-
222
- // Should have received done
223
- const chatResponses = messages.filter(isUseChatResponseMessage);
224
- const doneMsg = chatResponses.find((m) => m.done === true);
225
- expect(doneMsg).toBeDefined();
226
-
227
- // Abort controller should be cleaned up
228
- await new Promise((r) => setTimeout(r, 200));
229
- const agentStub = await getAgentByName(env.SlowStreamAgent, room);
230
- const count = await agentStub.getAbortControllerCount();
231
- expect(count).toBe(0);
232
-
233
- ws.close(1000);
234
- });
235
-
236
- it("completing a full stream without cancel produces no abort-related issues", async () => {
237
- const room = crypto.randomUUID();
238
- const { ws } = await connectSlowStream(room);
239
- await new Promise((r) => setTimeout(r, 50));
240
-
241
- const requestId = "req-no-cancel";
242
- const collecting = collectMessages(ws);
243
-
244
- // Send a fast request that completes naturally
245
- sendChatRequest(ws, requestId, [userMessage], {
246
- format: "plaintext",
247
- chunkCount: 3,
248
- chunkDelayMs: 10
249
- });
250
-
251
- const { messages, timedOut } = await collecting;
252
- expect(timedOut).toBe(false);
253
-
254
- // Should have received all chunks + done
255
- const chatResponses = messages.filter(isUseChatResponseMessage);
256
- const doneMsg = chatResponses.find((m) => m.done === true);
257
- expect(doneMsg).toBeDefined();
258
-
259
- // Should have all 3 text-delta events
260
- const textDeltas = chatResponses.filter((m) => {
261
- if (!m.body || typeof m.body !== "string" || m.body.length === 0)
262
- return false;
263
- try {
264
- const parsed = JSON.parse(m.body);
265
- return parsed.type === "text-delta";
266
- } catch {
267
- return false;
268
- }
269
- });
270
- expect(textDeltas.length).toBe(3);
271
-
272
- // Abort controller should be cleaned up
273
- await new Promise((r) => setTimeout(r, 100));
274
- const agentStub = await getAgentByName(env.SlowStreamAgent, room);
275
- const count = await agentStub.getAbortControllerCount();
276
- expect(count).toBe(0);
277
-
278
- ws.close(1000);
279
- });
280
- });