@cloudflare/ai-chat 0.1.3 → 0.1.5

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.
@@ -133,6 +133,116 @@ describe("Message Sanitization", () => {
133
133
  ws.close(1000);
134
134
  });
135
135
 
136
+ it("preserves Anthropic redacted_thinking blocks with empty text", async () => {
137
+ const room = crypto.randomUUID();
138
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
139
+ await new Promise((r) => setTimeout(r, 50));
140
+
141
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
142
+
143
+ const messageWithRedactedThinking: ChatMessage = {
144
+ id: "msg-sanitize-redacted",
145
+ role: "assistant",
146
+ parts: [
147
+ {
148
+ type: "reasoning",
149
+ text: "",
150
+ state: "done",
151
+ providerMetadata: {
152
+ anthropic: {
153
+ redactedData: "base64-encrypted-data"
154
+ }
155
+ }
156
+ },
157
+ { type: "reasoning", text: "", state: "done" },
158
+ { type: "text", text: "Here is my answer" },
159
+ {
160
+ type: "reasoning",
161
+ text: "Visible thinking",
162
+ state: "done"
163
+ }
164
+ ] as ChatMessage["parts"]
165
+ };
166
+
167
+ await agentStub.persistMessages([messageWithRedactedThinking]);
168
+
169
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
170
+ expect(persisted.length).toBe(1);
171
+
172
+ // The Anthropic redacted_thinking part (empty text + providerMetadata.anthropic) should be preserved
173
+ // The plain empty reasoning part should be filtered out
174
+ // The non-empty reasoning part should be preserved
175
+ const reasoningParts = persisted[0].parts.filter(
176
+ (p) => p.type === "reasoning"
177
+ );
178
+ expect(reasoningParts.length).toBe(2);
179
+
180
+ const redactedPart = reasoningParts[0] as {
181
+ text: string;
182
+ providerMetadata?: Record<string, unknown>;
183
+ };
184
+ expect(redactedPart.text).toBe("");
185
+ expect(redactedPart.providerMetadata?.anthropic).toEqual({
186
+ redactedData: "base64-encrypted-data"
187
+ });
188
+
189
+ expect((reasoningParts[1] as { text: string }).text).toBe(
190
+ "Visible thinking"
191
+ );
192
+
193
+ // Text part should be preserved
194
+ const textParts = persisted[0].parts.filter((p) => p.type === "text");
195
+ expect(textParts.length).toBe(1);
196
+
197
+ ws.close(1000);
198
+ });
199
+
200
+ it("removes empty OpenAI reasoning placeholders after stripping metadata", async () => {
201
+ const room = crypto.randomUUID();
202
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
203
+ await new Promise((r) => setTimeout(r, 50));
204
+
205
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
206
+
207
+ // OpenAI returns empty reasoning parts with only ephemeral metadata.
208
+ // After stripping OpenAI fields, these should be filtered out entirely.
209
+ const messageWithOpenAIReasoning: ChatMessage = {
210
+ id: "msg-sanitize-openai-reasoning",
211
+ role: "assistant",
212
+ parts: [
213
+ {
214
+ type: "reasoning",
215
+ text: "",
216
+ state: "done",
217
+ providerMetadata: {
218
+ openai: {
219
+ itemId: "item_reasoning_1",
220
+ reasoningEncryptedContent: "encrypted-blob"
221
+ }
222
+ }
223
+ },
224
+ { type: "text", text: "Final answer" }
225
+ ] as ChatMessage["parts"]
226
+ };
227
+
228
+ await agentStub.persistMessages([messageWithOpenAIReasoning]);
229
+
230
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
231
+ expect(persisted.length).toBe(1);
232
+
233
+ // The empty reasoning part should be gone (OpenAI metadata stripped, then empty part filtered)
234
+ const reasoningParts = persisted[0].parts.filter(
235
+ (p) => p.type === "reasoning"
236
+ );
237
+ expect(reasoningParts.length).toBe(0);
238
+
239
+ // Text part should be preserved
240
+ const textParts = persisted[0].parts.filter((p) => p.type === "text");
241
+ expect(textParts.length).toBe(1);
242
+
243
+ ws.close(1000);
244
+ });
245
+
136
246
  it("strips callProviderMetadata from tool parts", async () => {
137
247
  const room = crypto.randomUUID();
138
248
  const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
@@ -3,6 +3,7 @@ import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
3
3
  export default defineWorkersConfig({
4
4
  test: {
5
5
  name: "workers",
6
+ include: ["**/*.test.ts"],
6
7
  deps: {
7
8
  optimizer: {
8
9
  ssr: {
@@ -16,6 +16,9 @@ type TestToolCallPart = Extract<
16
16
 
17
17
  export type Env = {
18
18
  TestChatAgent: DurableObjectNamespace<TestChatAgent>;
19
+ AgentWithSuperCall: DurableObjectNamespace<AgentWithSuperCall>;
20
+ AgentWithoutSuperCall: DurableObjectNamespace<AgentWithoutSuperCall>;
21
+ SlowStreamAgent: DurableObjectNamespace<SlowStreamAgent>;
19
22
  };
20
23
 
21
24
  export class TestChatAgent extends AIChatAgent<Env> {
@@ -36,14 +39,17 @@ export class TestChatAgent extends AIChatAgent<Env> {
36
39
  private _capturedBody: Record<string, unknown> | undefined = undefined;
37
40
  // Store captured clientTools from onChatMessage options for testing
38
41
  private _capturedClientTools: ClientToolSchema[] | undefined = undefined;
42
+ // Store captured requestId from onChatMessage options for testing
43
+ private _capturedRequestId: string | undefined = undefined;
39
44
 
40
45
  async onChatMessage(
41
46
  _onFinish: StreamTextOnFinishCallback<ToolSet>,
42
47
  options?: OnChatMessageOptions
43
48
  ) {
44
- // Capture the body and clientTools from options for testing
49
+ // Capture the body, clientTools, and requestId from options for testing
45
50
  this._capturedBody = options?.body;
46
51
  this._capturedClientTools = options?.clientTools;
52
+ this._capturedRequestId = options?.requestId;
47
53
 
48
54
  // Capture getCurrentAgent() context for testing
49
55
  const { agent, connection } = getCurrentAgent();
@@ -98,6 +104,7 @@ export class TestChatAgent extends AIChatAgent<Env> {
98
104
  this._nestedContext = null;
99
105
  this._capturedBody = undefined;
100
106
  this._capturedClientTools = undefined;
107
+ this._capturedRequestId = undefined;
101
108
  }
102
109
 
103
110
  getCapturedBody(): Record<string, unknown> | undefined {
@@ -108,6 +115,10 @@ export class TestChatAgent extends AIChatAgent<Env> {
108
115
  return this._capturedClientTools;
109
116
  }
110
117
 
118
+ getCapturedRequestId(): string | undefined {
119
+ return this._capturedRequestId;
120
+ }
121
+
111
122
  getPersistedMessages(): ChatMessage[] {
112
123
  const rawMessages = (
113
124
  this.sql`select * from cf_ai_chat_agent_messages order by created_at` ||
@@ -320,6 +331,107 @@ export class TestChatAgent extends AIChatAgent<Env> {
320
331
  }
321
332
  }
322
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
+
323
435
  export default {
324
436
  async fetch(request: Request, env: Env, _ctx: ExecutionContext) {
325
437
  const url = new URL(request.url);
@@ -13,6 +13,18 @@
13
13
  {
14
14
  "class_name": "TestChatAgent",
15
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"
16
28
  }
17
29
  ]
18
30
  },
@@ -21,6 +33,18 @@
21
33
  {
22
34
  "new_sqlite_classes": ["TestChatAgent"],
23
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"
24
48
  }
25
49
  ]
26
50
  }
@@ -0,0 +1,198 @@
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
+ });
package/src/types.ts CHANGED
@@ -127,6 +127,10 @@ export type IncomingMessage<ChatMessage extends UIMessage = UIMessage> =
127
127
  toolName: string;
128
128
  /** The output from the tool execution */
129
129
  output: unknown;
130
+ /** Override the tool part state (e.g. "output-error" for custom denial) */
131
+ state?: "output-available" | "output-error";
132
+ /** Error message when state is "output-error" */
133
+ errorText?: string;
130
134
  /** Whether server should auto-continue the conversation after applying result */
131
135
  autoContinue?: boolean;
132
136
  /** Client tool schemas for continuation (client is source of truth) */
@@ -107,25 +107,53 @@ export class WebSocketChatTransport<
107
107
  // Track this request so the onAgentMessage handler skips it
108
108
  this.activeRequestIds?.add(requestId);
109
109
 
110
- // Handle abort from the caller (only if the stream has not already completed)
111
- options.abortSignal?.addEventListener("abort", () => {
112
- if (completed) return;
113
- this.agent.send(
114
- JSON.stringify({
115
- id: requestId,
116
- type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
117
- })
118
- );
119
- this.activeRequestIds?.delete(requestId);
120
- abortController.abort();
121
- });
122
-
123
110
  // Create a ReadableStream<UIMessageChunk> that emits parsed chunks
124
111
  // as they arrive over the WebSocket
125
112
  const agent = this.agent;
126
113
  const activeIds = this.activeRequestIds;
114
+
115
+ // Single cleanup helper — every terminal path (done, error, abort)
116
+ // goes through here exactly once.
117
+ const finish = (action: () => void) => {
118
+ if (completed) return;
119
+ completed = true;
120
+ try {
121
+ action();
122
+ } catch {
123
+ // Stream may already be closed
124
+ }
125
+ activeIds?.delete(requestId);
126
+ abortController.abort();
127
+ };
128
+
129
+ const abortError = new Error("Aborted");
130
+ abortError.name = "AbortError";
131
+
132
+ // Abort handler: send cancel to server, then terminate the stream.
133
+ // Used by both the caller's abortSignal and stream.cancel().
134
+ const onAbort = () => {
135
+ if (completed) return;
136
+ try {
137
+ agent.send(
138
+ JSON.stringify({
139
+ id: requestId,
140
+ type: MessageType.CF_AGENT_CHAT_REQUEST_CANCEL
141
+ })
142
+ );
143
+ } catch {
144
+ // Ignore failures (e.g. agent already disconnected)
145
+ }
146
+ finish(() => streamController.error(abortError));
147
+ };
148
+
149
+ // streamController is assigned synchronously by start(), so it is
150
+ // always available by the time onAbort or onMessage can fire.
151
+ let streamController!: ReadableStreamDefaultController<UIMessageChunk>;
152
+
127
153
  const stream = new ReadableStream<UIMessageChunk>({
128
154
  start(controller) {
155
+ streamController = controller;
156
+
129
157
  const onMessage = (event: MessageEvent) => {
130
158
  try {
131
159
  const data = JSON.parse(
@@ -136,10 +164,7 @@ export class WebSocketChatTransport<
136
164
  if (data.id !== requestId) return;
137
165
 
138
166
  if (data.error) {
139
- completed = true;
140
- controller.error(new Error(data.body));
141
- activeIds?.delete(requestId);
142
- abortController.abort();
167
+ finish(() => controller.error(new Error(data.body)));
143
168
  return;
144
169
  }
145
170
 
@@ -154,14 +179,7 @@ export class WebSocketChatTransport<
154
179
  }
155
180
 
156
181
  if (data.done) {
157
- completed = true;
158
- try {
159
- controller.close();
160
- } catch {
161
- // Stream may already be closed
162
- }
163
- activeIds?.delete(requestId);
164
- abortController.abort();
182
+ finish(() => controller.close());
165
183
  }
166
184
  } catch {
167
185
  // Ignore non-JSON messages
@@ -173,10 +191,16 @@ export class WebSocketChatTransport<
173
191
  });
174
192
  },
175
193
  cancel() {
176
- abortController.abort();
194
+ onAbort();
177
195
  }
178
196
  });
179
197
 
198
+ // Handle abort from the caller
199
+ if (options.abortSignal) {
200
+ options.abortSignal.addEventListener("abort", onAbort, { once: true });
201
+ if (options.abortSignal.aborted) onAbort();
202
+ }
203
+
180
204
  // Send the request over WebSocket
181
205
  agent.send(
182
206
  JSON.stringify({