@cloudflare/ai-chat 0.1.5 → 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 (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 +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 +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,456 +0,0 @@
1
- import { AIChatAgent, type OnChatMessageOptions } from "../";
2
- import type {
3
- UIMessage as ChatMessage,
4
- StreamTextOnFinishCallback,
5
- ToolSet
6
- } from "ai";
7
- import { getCurrentAgent, routeAgentRequest } from "agents";
8
- import { MessageType, type OutgoingMessage } from "../types";
9
- import type { ClientToolSchema } from "../";
10
-
11
- // Type helper for tool call parts - extracts from ChatMessage parts
12
- type TestToolCallPart = Extract<
13
- ChatMessage["parts"][number],
14
- { type: `tool-${string}` }
15
- >;
16
-
17
- export type Env = {
18
- TestChatAgent: DurableObjectNamespace<TestChatAgent>;
19
- AgentWithSuperCall: DurableObjectNamespace<AgentWithSuperCall>;
20
- AgentWithoutSuperCall: DurableObjectNamespace<AgentWithoutSuperCall>;
21
- SlowStreamAgent: DurableObjectNamespace<SlowStreamAgent>;
22
- };
23
-
24
- export class TestChatAgent extends AIChatAgent<Env> {
25
- observability = undefined;
26
- // Store captured context for testing
27
- private _capturedContext: {
28
- hasAgent: boolean;
29
- hasConnection: boolean;
30
- connectionId: string | undefined;
31
- } | null = null;
32
- // Store context captured from nested async function (simulates tool execute)
33
- private _nestedContext: {
34
- hasAgent: boolean;
35
- hasConnection: boolean;
36
- connectionId: string | undefined;
37
- } | null = null;
38
- // Store captured body from onChatMessage options for testing
39
- private _capturedBody: Record<string, unknown> | undefined = undefined;
40
- // Store captured clientTools from onChatMessage options for testing
41
- private _capturedClientTools: ClientToolSchema[] | undefined = undefined;
42
- // Store captured requestId from onChatMessage options for testing
43
- private _capturedRequestId: string | undefined = undefined;
44
-
45
- async onChatMessage(
46
- _onFinish: StreamTextOnFinishCallback<ToolSet>,
47
- options?: OnChatMessageOptions
48
- ) {
49
- // Capture the body, clientTools, and requestId from options for testing
50
- this._capturedBody = options?.body;
51
- this._capturedClientTools = options?.clientTools;
52
- this._capturedRequestId = options?.requestId;
53
-
54
- // Capture getCurrentAgent() context for testing
55
- const { agent, connection } = getCurrentAgent();
56
- this._capturedContext = {
57
- hasAgent: agent !== undefined,
58
- hasConnection: connection !== undefined,
59
- connectionId: connection?.id
60
- };
61
-
62
- // Simulate what happens inside a tool's execute function:
63
- // It's a nested async function called from within onChatMessage
64
- await this._simulateToolExecute();
65
-
66
- // Simple echo response for testing
67
- return new Response("Hello from chat agent!", {
68
- headers: { "Content-Type": "text/plain" }
69
- });
70
- }
71
-
72
- // This simulates an AI SDK tool's execute function being called
73
- private async _simulateToolExecute(): Promise<void> {
74
- // Add a small delay to ensure we're in a new microtask (like real tool execution)
75
- await Promise.resolve();
76
-
77
- // Capture context inside the "tool execute" function
78
- const { agent, connection } = getCurrentAgent();
79
- this._nestedContext = {
80
- hasAgent: agent !== undefined,
81
- hasConnection: connection !== undefined,
82
- connectionId: connection?.id
83
- };
84
- }
85
-
86
- getCapturedContext(): {
87
- hasAgent: boolean;
88
- hasConnection: boolean;
89
- connectionId: string | undefined;
90
- } | null {
91
- return this._capturedContext;
92
- }
93
-
94
- getNestedContext(): {
95
- hasAgent: boolean;
96
- hasConnection: boolean;
97
- connectionId: string | undefined;
98
- } | null {
99
- return this._nestedContext;
100
- }
101
-
102
- clearCapturedContext(): void {
103
- this._capturedContext = null;
104
- this._nestedContext = null;
105
- this._capturedBody = undefined;
106
- this._capturedClientTools = undefined;
107
- this._capturedRequestId = undefined;
108
- }
109
-
110
- getCapturedBody(): Record<string, unknown> | undefined {
111
- return this._capturedBody;
112
- }
113
-
114
- getCapturedClientTools(): ClientToolSchema[] | undefined {
115
- return this._capturedClientTools;
116
- }
117
-
118
- getCapturedRequestId(): string | undefined {
119
- return this._capturedRequestId;
120
- }
121
-
122
- getPersistedMessages(): ChatMessage[] {
123
- const rawMessages = (
124
- this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
125
- []
126
- ).map((row) => {
127
- return JSON.parse(row.message as string);
128
- });
129
- return rawMessages;
130
- }
131
-
132
- async testPersistToolCall(messageId: string, toolName: string) {
133
- const toolCallPart: TestToolCallPart = {
134
- type: `tool-${toolName}`,
135
- toolCallId: `call_${messageId}`,
136
- state: "input-available",
137
- input: { location: "London" }
138
- };
139
-
140
- const messageWithToolCall: ChatMessage = {
141
- id: messageId,
142
- role: "assistant",
143
- parts: [toolCallPart] as ChatMessage["parts"]
144
- };
145
- await this.persistMessages([messageWithToolCall]);
146
- return messageWithToolCall;
147
- }
148
-
149
- async testPersistToolResult(
150
- messageId: string,
151
- toolName: string,
152
- output: string
153
- ) {
154
- const toolResultPart: TestToolCallPart = {
155
- type: `tool-${toolName}`,
156
- toolCallId: `call_${messageId}`,
157
- state: "output-available",
158
- input: { location: "London" },
159
- output
160
- };
161
-
162
- const messageWithToolOutput: ChatMessage = {
163
- id: messageId,
164
- role: "assistant",
165
- parts: [toolResultPart] as ChatMessage["parts"]
166
- };
167
- await this.persistMessages([messageWithToolOutput]);
168
- return messageWithToolOutput;
169
- }
170
-
171
- // Resumable streaming test helpers
172
-
173
- testStartStream(requestId: string): string {
174
- return this._startStream(requestId);
175
- }
176
-
177
- testStoreStreamChunk(streamId: string, body: string): void {
178
- this._storeStreamChunk(streamId, body);
179
- }
180
-
181
- testBroadcastLiveChunk(
182
- requestId: string,
183
- streamId: string,
184
- body: string
185
- ): void {
186
- this._storeStreamChunk(streamId, body);
187
- const message: OutgoingMessage = {
188
- body,
189
- done: false,
190
- id: requestId,
191
- type: MessageType.CF_AGENT_USE_CHAT_RESPONSE
192
- };
193
- (
194
- this as unknown as {
195
- _broadcastChatMessage: (
196
- msg: OutgoingMessage,
197
- exclude?: string[]
198
- ) => void;
199
- }
200
- )._broadcastChatMessage(message);
201
- }
202
-
203
- testFlushChunkBuffer(): void {
204
- this._flushChunkBuffer();
205
- }
206
-
207
- testCompleteStream(streamId: string): void {
208
- this._completeStream(streamId);
209
- }
210
-
211
- testMarkStreamError(streamId: string): void {
212
- this._markStreamError(streamId);
213
- }
214
-
215
- getActiveStreamId(): string | null {
216
- return this._activeStreamId;
217
- }
218
-
219
- getActiveRequestId(): string | null {
220
- return this._activeRequestId;
221
- }
222
-
223
- getStreamChunks(
224
- streamId: string
225
- ): Array<{ body: string; chunk_index: number }> {
226
- return (
227
- this.sql<{ body: string; chunk_index: number }>`
228
- select body, chunk_index from cf_ai_chat_stream_chunks
229
- where stream_id = ${streamId}
230
- order by chunk_index asc
231
- ` || []
232
- );
233
- }
234
-
235
- getStreamMetadata(
236
- streamId: string
237
- ): { status: string; request_id: string } | null {
238
- const result = this.sql<{ status: string; request_id: string }>`
239
- select status, request_id from cf_ai_chat_stream_metadata
240
- where id = ${streamId}
241
- `;
242
- return result && result.length > 0 ? result[0] : null;
243
- }
244
-
245
- getAllStreamMetadata(): Array<{
246
- id: string;
247
- status: string;
248
- request_id: string;
249
- created_at: number;
250
- }> {
251
- return (
252
- this.sql<{
253
- id: string;
254
- status: string;
255
- request_id: string;
256
- created_at: number;
257
- }>`select id, status, request_id, created_at from cf_ai_chat_stream_metadata` ||
258
- []
259
- );
260
- }
261
-
262
- testInsertStaleStream(
263
- streamId: string,
264
- requestId: string,
265
- ageMs: number
266
- ): void {
267
- const createdAt = Date.now() - ageMs;
268
- this.sql`
269
- insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at)
270
- values (${streamId}, ${requestId}, 'streaming', ${createdAt})
271
- `;
272
- }
273
-
274
- testInsertOldErroredStream(
275
- streamId: string,
276
- requestId: string,
277
- ageMs: number
278
- ): void {
279
- const createdAt = Date.now() - ageMs;
280
- const completedAt = createdAt + 1000;
281
- this.sql`
282
- insert into cf_ai_chat_stream_metadata (id, request_id, status, created_at, completed_at)
283
- values (${streamId}, ${requestId}, 'error', ${createdAt}, ${completedAt})
284
- `;
285
- }
286
-
287
- testRestoreActiveStream(): void {
288
- this._restoreActiveStream();
289
- }
290
-
291
- testTriggerStreamCleanup(): void {
292
- // Force the cleanup interval to 0 so the next completeStream triggers it
293
- // We do this by starting and immediately completing a dummy stream
294
- const dummyId = this._startStream("cleanup-trigger");
295
- this._completeStream(dummyId);
296
- }
297
-
298
- /**
299
- * Insert a raw JSON string as a message directly into SQLite.
300
- * Used to test validation of malformed/corrupt messages.
301
- */
302
- insertRawMessage(rowId: string, rawJson: string): void {
303
- this.sql`
304
- insert into cf_ai_chat_agent_messages (id, message)
305
- values (${rowId}, ${rawJson})
306
- `;
307
- }
308
-
309
- setMaxPersistedMessages(max: number | null): void {
310
- this.maxPersistedMessages = max ?? undefined;
311
- }
312
-
313
- getMessageCount(): number {
314
- const result = this.sql<{ cnt: number }>`
315
- select count(*) as cnt from cf_ai_chat_agent_messages
316
- `;
317
- return result?.[0]?.cnt ?? 0;
318
- }
319
-
320
- /**
321
- * Returns the number of active abort controllers.
322
- * Used to verify that cleanup happens after stream completion.
323
- * If controllers leak, this count grows with each request.
324
- */
325
- getAbortControllerCount(): number {
326
- return (
327
- this as unknown as {
328
- _chatMessageAbortControllers: Map<string, unknown>;
329
- }
330
- )._chatMessageAbortControllers.size;
331
- }
332
- }
333
-
334
- /**
335
- * Test agent that streams chunks slowly, useful for testing cancel/abort.
336
- *
337
- * Control via request body fields:
338
- * - `format`: "sse" | "plaintext" (default: "plaintext")
339
- * - `useAbortSignal`: boolean — whether to connect abortSignal to the stream
340
- * - `chunkCount`: number of chunks to emit (default: 20)
341
- * - `chunkDelayMs`: delay between chunks in ms (default: 50)
342
- */
343
- export class SlowStreamAgent extends AIChatAgent<Env> {
344
- observability = undefined;
345
-
346
- async onChatMessage(
347
- _onFinish: StreamTextOnFinishCallback<ToolSet>,
348
- options?: OnChatMessageOptions
349
- ) {
350
- const body = options?.body as
351
- | {
352
- format?: string;
353
- useAbortSignal?: boolean;
354
- chunkCount?: number;
355
- chunkDelayMs?: number;
356
- }
357
- | undefined;
358
- const format = body?.format ?? "plaintext";
359
- const useAbortSignal = body?.useAbortSignal ?? false;
360
- const chunkCount = body?.chunkCount ?? 20;
361
- const chunkDelayMs = body?.chunkDelayMs ?? 50;
362
- const abortSignal = useAbortSignal ? options?.abortSignal : undefined;
363
-
364
- const encoder = new TextEncoder();
365
- const stream = new ReadableStream({
366
- async pull(controller) {
367
- for (let i = 0; i < chunkCount; i++) {
368
- if (abortSignal?.aborted) {
369
- controller.close();
370
- return;
371
- }
372
- await new Promise((r) => setTimeout(r, chunkDelayMs));
373
- if (abortSignal?.aborted) {
374
- controller.close();
375
- return;
376
- }
377
- if (format === "sse") {
378
- const chunk = JSON.stringify({
379
- type: "text-delta",
380
- textDelta: `chunk-${i} `
381
- });
382
- controller.enqueue(encoder.encode(`data: ${chunk}\n\n`));
383
- } else {
384
- controller.enqueue(encoder.encode(`chunk-${i} `));
385
- }
386
- }
387
- if (format === "sse") {
388
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
389
- }
390
- controller.close();
391
- }
392
- });
393
-
394
- const contentType = format === "sse" ? "text/event-stream" : "text/plain";
395
- return new Response(stream, {
396
- headers: { "Content-Type": contentType }
397
- });
398
- }
399
-
400
- getAbortControllerCount(): number {
401
- return (
402
- this as unknown as {
403
- _chatMessageAbortControllers: Map<string, unknown>;
404
- }
405
- )._chatMessageAbortControllers.size;
406
- }
407
- }
408
-
409
- // Test agent that overrides onRequest and calls super.onRequest()
410
- export class AgentWithSuperCall extends AIChatAgent<Env> {
411
- async onRequest(request: Request): Promise<Response> {
412
- const url = new URL(request.url);
413
- if (url.pathname.endsWith("/custom-route")) {
414
- return new Response("custom route");
415
- }
416
- return super.onRequest(request);
417
- }
418
-
419
- async onChatMessage() {
420
- return new Response("chat response");
421
- }
422
- }
423
-
424
- // Test agent that overrides onRequest WITHOUT calling super.onRequest()
425
- export class AgentWithoutSuperCall extends AIChatAgent<Env> {
426
- async onRequest(_request: Request): Promise<Response> {
427
- return new Response("custom only");
428
- }
429
-
430
- async onChatMessage() {
431
- return new Response("chat response");
432
- }
433
- }
434
-
435
- export default {
436
- async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
437
- const url = new URL(request.url);
438
-
439
- if (url.pathname === "/500") {
440
- return new Response("Internal Server Error", { status: 500 });
441
- }
442
-
443
- return (
444
- (await routeAgentRequest(request, env)) ||
445
- new Response("Not found", { status: 404 })
446
- );
447
- },
448
-
449
- async email(
450
- _message: ForwardableEmailMessage,
451
- _env: Env,
452
- _ctx: ExecutionContext
453
- ) {
454
- // Bring this in when we write tests for the complete email handler flow
455
- }
456
- };
@@ -1,50 +0,0 @@
1
- {
2
- "compatibility_date": "2026-01-28",
3
- "compatibility_flags": [
4
- "nodejs_compat",
5
- // adding these flags since the vitest runner needs them
6
- "enable_nodejs_tty_module",
7
- "enable_nodejs_fs_module",
8
- "enable_nodejs_http_modules",
9
- "enable_nodejs_perf_hooks_module"
10
- ],
11
- "durable_objects": {
12
- "bindings": [
13
- {
14
- "class_name": "TestChatAgent",
15
- "name": "TestChatAgent"
16
- },
17
- {
18
- "class_name": "AgentWithSuperCall",
19
- "name": "AgentWithSuperCall"
20
- },
21
- {
22
- "class_name": "AgentWithoutSuperCall",
23
- "name": "AgentWithoutSuperCall"
24
- },
25
- {
26
- "class_name": "SlowStreamAgent",
27
- "name": "SlowStreamAgent"
28
- }
29
- ]
30
- },
31
- "main": "worker.ts",
32
- "migrations": [
33
- {
34
- "new_sqlite_classes": ["TestChatAgent"],
35
- "tag": "v1"
36
- },
37
- {
38
- "new_sqlite_classes": ["AgentWithSuperCall"],
39
- "tag": "v2"
40
- },
41
- {
42
- "new_sqlite_classes": ["AgentWithoutSuperCall"],
43
- "tag": "v3"
44
- },
45
- {
46
- "new_sqlite_classes": ["SlowStreamAgent"],
47
- "tag": "v4"
48
- }
49
- ]
50
- }
@@ -1,198 +0,0 @@
1
- import { describe, it, expect } from "vitest";
2
- import type { UIMessage as ChatMessage, UIMessageChunk } from "ai";
3
- import { connectChatWS } from "./test-utils";
4
- import { WebSocketChatTransport } from "../ws-chat-transport";
5
-
6
- function connectSlowStream(room: string) {
7
- return connectChatWS(`/agents/slow-stream-agent/${room}`);
8
- }
9
-
10
- function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
11
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
12
- const timeoutPromise = new Promise<never>((_, reject) => {
13
- timeoutId = setTimeout(() => reject(new Error("Timed out")), timeoutMs);
14
- });
15
-
16
- return Promise.race([promise, timeoutPromise]).finally(() => {
17
- if (timeoutId) clearTimeout(timeoutId);
18
- }) as Promise<T>;
19
- }
20
-
21
- async function readUntilDoneOrAbort(
22
- reader: ReadableStreamDefaultReader<unknown>,
23
- timeoutMs: number
24
- ) {
25
- const deadline = Date.now() + timeoutMs;
26
-
27
- while (true) {
28
- const remaining = deadline - Date.now();
29
- if (remaining <= 0) throw new Error("Timed out waiting for stream to end");
30
-
31
- try {
32
- const result = await withTimeout(reader.read(), remaining);
33
- if (result.done) return;
34
- } catch (err) {
35
- if (err && typeof err === "object" && "name" in err) {
36
- if ((err as { name: unknown }).name === "AbortError") return;
37
- }
38
- throw err;
39
- }
40
- }
41
- }
42
-
43
- async function collectChunks(
44
- stream: ReadableStream<UIMessageChunk>,
45
- timeoutMs: number
46
- ): Promise<UIMessageChunk[]> {
47
- const reader = stream.getReader();
48
- const chunks: UIMessageChunk[] = [];
49
- const deadline = Date.now() + timeoutMs;
50
-
51
- while (true) {
52
- const remaining = deadline - Date.now();
53
- if (remaining <= 0) throw new Error("Timed out collecting chunks");
54
-
55
- const result = await withTimeout(reader.read(), remaining);
56
- if (result.done) break;
57
- chunks.push(result.value);
58
- }
59
- return chunks;
60
- }
61
-
62
- const userMessage: ChatMessage = {
63
- id: "msg1",
64
- role: "user",
65
- parts: [{ type: "text", text: "Hello" }]
66
- };
67
-
68
- describe("WebSocketChatTransport abort", () => {
69
- it("terminates the stream when abortSignal fires mid-stream", async () => {
70
- const room = crypto.randomUUID();
71
- const { ws } = await connectSlowStream(room);
72
- await new Promise((r) => setTimeout(r, 50));
73
-
74
- try {
75
- const transport = new WebSocketChatTransport<ChatMessage>({
76
- agent: ws
77
- });
78
- const abortController = new AbortController();
79
-
80
- const stream = await transport.sendMessages({
81
- chatId: "chat",
82
- messages: [userMessage],
83
- abortSignal: abortController.signal,
84
- trigger: "submit-message",
85
- body: {
86
- format: "plaintext",
87
- chunkCount: 20,
88
- chunkDelayMs: 50
89
- }
90
- });
91
-
92
- const reader = stream.getReader();
93
-
94
- // Abort mid-stream. Without proper stream termination, this would hang.
95
- setTimeout(() => abortController.abort(), 200);
96
-
97
- await expect(readUntilDoneOrAbort(reader, 5000)).resolves.toBeUndefined();
98
- } finally {
99
- ws.close(1000);
100
- }
101
- });
102
-
103
- it("terminates immediately when abortSignal is already aborted", async () => {
104
- const room = crypto.randomUUID();
105
- const { ws } = await connectSlowStream(room);
106
- await new Promise((r) => setTimeout(r, 50));
107
-
108
- try {
109
- const transport = new WebSocketChatTransport<ChatMessage>({
110
- agent: ws
111
- });
112
-
113
- const abortController = new AbortController();
114
- abortController.abort();
115
-
116
- const stream = await transport.sendMessages({
117
- chatId: "chat",
118
- messages: [userMessage],
119
- abortSignal: abortController.signal,
120
- trigger: "submit-message",
121
- body: {
122
- format: "plaintext",
123
- chunkCount: 20,
124
- chunkDelayMs: 50
125
- }
126
- });
127
-
128
- const reader = stream.getReader();
129
-
130
- // Should terminate immediately — no waiting for chunks
131
- await expect(readUntilDoneOrAbort(reader, 1000)).resolves.toBeUndefined();
132
- } finally {
133
- ws.close(1000);
134
- }
135
- });
136
-
137
- it("stream.cancel() sends cancel to server and terminates", async () => {
138
- const room = crypto.randomUUID();
139
- const { ws } = await connectSlowStream(room);
140
- await new Promise((r) => setTimeout(r, 50));
141
-
142
- try {
143
- const transport = new WebSocketChatTransport<ChatMessage>({
144
- agent: ws
145
- });
146
-
147
- const stream = await transport.sendMessages({
148
- chatId: "chat",
149
- messages: [userMessage],
150
- abortSignal: undefined,
151
- trigger: "submit-message",
152
- body: {
153
- format: "plaintext",
154
- chunkCount: 20,
155
- chunkDelayMs: 50
156
- }
157
- });
158
-
159
- // Let a few chunks arrive
160
- await new Promise((r) => setTimeout(r, 200));
161
-
162
- // cancel() should not hang — it sends CF_AGENT_CHAT_REQUEST_CANCEL
163
- // and terminates the stream
164
- await expect(withTimeout(stream.cancel(), 2000)).resolves.toBeUndefined();
165
- } finally {
166
- ws.close(1000);
167
- }
168
- });
169
-
170
- it("completes normally when stream finishes without abort", async () => {
171
- const room = crypto.randomUUID();
172
- const { ws } = await connectSlowStream(room);
173
- await new Promise((r) => setTimeout(r, 50));
174
-
175
- try {
176
- const transport = new WebSocketChatTransport<ChatMessage>({
177
- agent: ws
178
- });
179
-
180
- const stream = await transport.sendMessages({
181
- chatId: "chat",
182
- messages: [userMessage],
183
- abortSignal: undefined,
184
- trigger: "submit-message",
185
- body: {
186
- format: "plaintext",
187
- chunkCount: 3,
188
- chunkDelayMs: 10
189
- }
190
- });
191
-
192
- const chunks = await collectChunks(stream, 5000);
193
- expect(chunks.length).toBeGreaterThanOrEqual(3);
194
- } finally {
195
- ws.close(1000);
196
- }
197
- });
198
- });