@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.
@@ -77,3 +77,77 @@ describe("GET /get-messages endpoint", () => {
77
77
  expect(res.status).toBe(404);
78
78
  });
79
79
  });
80
+
81
+ describe("onRequest override patterns", () => {
82
+ it("/get-messages works when user overrides onRequest and calls super", async () => {
83
+ const room = crypto.randomUUID();
84
+
85
+ const { ws } = await connectChatWS(`/agents/agent-with-super-call/${room}`);
86
+ await new Promise((r) => setTimeout(r, 50));
87
+
88
+ const agentStub = await getAgentByName(env.AgentWithSuperCall, room);
89
+ const messages: ChatMessage[] = [
90
+ { id: "test-1", role: "user", parts: [{ type: "text", text: "Hello" }] }
91
+ ];
92
+ await agentStub.persistMessages(messages);
93
+ ws.close(1000);
94
+
95
+ const req = new Request(
96
+ `http://example.com/agents/agent-with-super-call/${room}/get-messages`
97
+ );
98
+ const res = await worker.fetch(req, env, createExecutionContext());
99
+
100
+ expect(res.status).toBe(200);
101
+ const returned = (await res.json()) as ChatMessage[];
102
+ expect(returned.length).toBe(1);
103
+ expect(returned[0].id).toBe("test-1");
104
+ });
105
+
106
+ it("/get-messages works when user overrides onRequest WITHOUT calling super", async () => {
107
+ const room = crypto.randomUUID();
108
+
109
+ const { ws } = await connectChatWS(
110
+ `/agents/agent-without-super-call/${room}`
111
+ );
112
+ await new Promise((r) => setTimeout(r, 50));
113
+
114
+ const agentStub = await getAgentByName(env.AgentWithoutSuperCall, room);
115
+ const messages: ChatMessage[] = [
116
+ {
117
+ id: "test-no-super-1",
118
+ role: "user",
119
+ parts: [{ type: "text", text: "Hello" }]
120
+ }
121
+ ];
122
+ await agentStub.persistMessages(messages);
123
+ ws.close(1000);
124
+
125
+ const req = new Request(
126
+ `http://example.com/agents/agent-without-super-call/${room}/get-messages`
127
+ );
128
+ const res = await worker.fetch(req, env, createExecutionContext());
129
+
130
+ expect(res.status).toBe(200);
131
+ const returned = (await res.json()) as ChatMessage[];
132
+ expect(returned.length).toBe(1);
133
+ expect(returned[0].id).toBe("test-no-super-1");
134
+ });
135
+
136
+ it("non-get-messages routes still delegate to user onRequest override", async () => {
137
+ const room = crypto.randomUUID();
138
+
139
+ const { ws } = await connectChatWS(
140
+ `/agents/agent-without-super-call/${room}`
141
+ );
142
+ await new Promise((r) => setTimeout(r, 50));
143
+ ws.close(1000);
144
+
145
+ const req = new Request(
146
+ `http://example.com/agents/agent-without-super-call/${room}/other-route`
147
+ );
148
+ const res = await worker.fetch(req, env, createExecutionContext());
149
+
150
+ expect(res.status).toBe(200);
151
+ expect(await res.text()).toBe("custom only");
152
+ });
153
+ });
@@ -103,4 +103,241 @@ describe("Merge Incoming With Server State", () => {
103
103
 
104
104
  ws.close(1000);
105
105
  });
106
+
107
+ it("reuses server assistant IDs for plain text messages to avoid duplicates", async () => {
108
+ const room = crypto.randomUUID();
109
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
110
+ await new Promise((r) => setTimeout(r, 50));
111
+
112
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
113
+
114
+ await agentStub.persistMessages([
115
+ {
116
+ id: "user-1",
117
+ role: "user",
118
+ parts: [{ type: "text", text: "Hello" }]
119
+ },
120
+ {
121
+ id: "assistant_server_1",
122
+ role: "assistant",
123
+ parts: [{ type: "text", text: "Hi there!" }]
124
+ }
125
+ ]);
126
+
127
+ await agentStub.persistMessages([
128
+ {
129
+ id: "user-1",
130
+ role: "user",
131
+ parts: [{ type: "text", text: "Hello" }]
132
+ },
133
+ {
134
+ id: "assistant_client_1",
135
+ role: "assistant",
136
+ parts: [{ type: "text", text: "Hi there!" }]
137
+ },
138
+ {
139
+ id: "user-2",
140
+ role: "user",
141
+ parts: [{ type: "text", text: "How are you?" }]
142
+ }
143
+ ]);
144
+
145
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
146
+ expect(persisted.length).toBe(3);
147
+
148
+ const assistantMessages = persisted.filter((m) => m.role === "assistant");
149
+ expect(assistantMessages.length).toBe(1);
150
+ expect(assistantMessages[0].id).toBe("assistant_server_1");
151
+ expect((assistantMessages[0].parts[0] as { text: string }).text).toBe(
152
+ "Hi there!"
153
+ );
154
+
155
+ ws.close(1000);
156
+ });
157
+
158
+ it("matches repeated assistant text messages in order", async () => {
159
+ const room = crypto.randomUUID();
160
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
161
+ await new Promise((r) => setTimeout(r, 50));
162
+
163
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
164
+
165
+ await agentStub.persistMessages([
166
+ {
167
+ id: "user-server-1",
168
+ role: "user",
169
+ parts: [{ type: "text", text: "Say hi" }]
170
+ },
171
+ {
172
+ id: "assistant_server_1",
173
+ role: "assistant",
174
+ parts: [{ type: "text", text: "Hi there!" }]
175
+ },
176
+ {
177
+ id: "user-server-2",
178
+ role: "user",
179
+ parts: [{ type: "text", text: "Say hi again" }]
180
+ },
181
+ {
182
+ id: "assistant_server_2",
183
+ role: "assistant",
184
+ parts: [{ type: "text", text: "Hi there!" }]
185
+ }
186
+ ]);
187
+
188
+ await agentStub.persistMessages([
189
+ {
190
+ id: "user-server-1",
191
+ role: "user",
192
+ parts: [{ type: "text", text: "Say hi" }]
193
+ },
194
+ {
195
+ id: "assistant_client_1",
196
+ role: "assistant",
197
+ parts: [{ type: "text", text: "Hi there!" }]
198
+ },
199
+ {
200
+ id: "user-server-2",
201
+ role: "user",
202
+ parts: [{ type: "text", text: "Say hi again" }]
203
+ },
204
+ {
205
+ id: "assistant_client_2",
206
+ role: "assistant",
207
+ parts: [{ type: "text", text: "Hi there!" }]
208
+ }
209
+ ]);
210
+
211
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
212
+
213
+ const assistantMessages = persisted.filter((m) => m.role === "assistant");
214
+ expect(assistantMessages.length).toBe(2);
215
+ expect(assistantMessages[0].id).toBe("assistant_server_1");
216
+ expect(assistantMessages[1].id).toBe("assistant_server_2");
217
+
218
+ ws.close(1000);
219
+ });
220
+
221
+ it("does not reconcile when assistant content differs at the same position", async () => {
222
+ const room = crypto.randomUUID();
223
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
224
+ await new Promise((r) => setTimeout(r, 50));
225
+
226
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
227
+
228
+ await agentStub.persistMessages([
229
+ {
230
+ id: "user-1",
231
+ role: "user",
232
+ parts: [{ type: "text", text: "Hello" }]
233
+ },
234
+ {
235
+ id: "assistant_server_1",
236
+ role: "assistant",
237
+ parts: [{ type: "text", text: "Hi there!" }]
238
+ }
239
+ ]);
240
+
241
+ await agentStub.persistMessages([
242
+ {
243
+ id: "user-1",
244
+ role: "user",
245
+ parts: [{ type: "text", text: "Hello" }]
246
+ },
247
+ {
248
+ id: "assistant_client_1",
249
+ role: "assistant",
250
+ parts: [{ type: "text", text: "Completely different response" }]
251
+ }
252
+ ]);
253
+
254
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
255
+
256
+ const assistantMessages = persisted.filter((m) => m.role === "assistant");
257
+ expect(assistantMessages.length).toBe(2);
258
+ expect(assistantMessages.map((m) => m.id)).toContain("assistant_server_1");
259
+ expect(assistantMessages.map((m) => m.id)).toContain("assistant_client_1");
260
+
261
+ ws.close(1000);
262
+ });
263
+
264
+ it("skips tool-bearing assistant messages during reconciliation without breaking cursor", async () => {
265
+ const room = crypto.randomUUID();
266
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
267
+ await new Promise((r) => setTimeout(r, 50));
268
+
269
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
270
+
271
+ const toolPart: TestToolCallPart = {
272
+ type: "tool-getWeather",
273
+ toolCallId: "call_mixed_1",
274
+ state: "output-available",
275
+ input: { city: "London" },
276
+ output: "Rainy, 12°C"
277
+ };
278
+
279
+ await agentStub.persistMessages([
280
+ {
281
+ id: "user-1",
282
+ role: "user",
283
+ parts: [{ type: "text", text: "What is the weather?" }]
284
+ },
285
+ {
286
+ id: "assistant_server_tool",
287
+ role: "assistant",
288
+ parts: [toolPart] as ChatMessage["parts"]
289
+ },
290
+ {
291
+ id: "user-2",
292
+ role: "user",
293
+ parts: [{ type: "text", text: "Thanks" }]
294
+ },
295
+ {
296
+ id: "assistant_server_text",
297
+ role: "assistant",
298
+ parts: [{ type: "text", text: "You're welcome!" }]
299
+ }
300
+ ]);
301
+
302
+ await agentStub.persistMessages([
303
+ {
304
+ id: "user-1",
305
+ role: "user",
306
+ parts: [{ type: "text", text: "What is the weather?" }]
307
+ },
308
+ {
309
+ id: "assistant_server_tool",
310
+ role: "assistant",
311
+ parts: [toolPart] as ChatMessage["parts"]
312
+ },
313
+ {
314
+ id: "user-2",
315
+ role: "user",
316
+ parts: [{ type: "text", text: "Thanks" }]
317
+ },
318
+ {
319
+ id: "assistant_client_text",
320
+ role: "assistant",
321
+ parts: [{ type: "text", text: "You're welcome!" }]
322
+ }
323
+ ]);
324
+
325
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
326
+
327
+ expect(persisted.length).toBe(4);
328
+
329
+ const toolMsg = persisted.find((m) => m.id === "assistant_server_tool");
330
+ expect(toolMsg).toBeDefined();
331
+
332
+ const textAssistants = persisted.filter(
333
+ (m) => m.role === "assistant" && m.id !== "assistant_server_tool"
334
+ );
335
+ expect(textAssistants.length).toBe(1);
336
+ expect(textAssistants[0].id).toBe("assistant_server_text");
337
+ expect((textAssistants[0].parts[0] as { text: string }).text).toBe(
338
+ "You're welcome!"
339
+ );
340
+
341
+ ws.close(1000);
342
+ });
106
343
  });
@@ -0,0 +1,312 @@
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: send a chat request and wait for the done response.
10
+ * Returns the request ID that was sent.
11
+ */
12
+ async function sendChatAndWaitForDone(
13
+ ws: WebSocket,
14
+ requestId: string,
15
+ messages: ChatMessage[],
16
+ extraBody?: Record<string, unknown>
17
+ ): Promise<void> {
18
+ let resolvePromise: (value: boolean) => void;
19
+ const donePromise = new Promise<boolean>((res) => {
20
+ resolvePromise = res;
21
+ });
22
+
23
+ const timeout = setTimeout(() => resolvePromise(false), 2000);
24
+
25
+ const handler = (e: MessageEvent) => {
26
+ const data = JSON.parse(e.data as string);
27
+ if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
28
+ clearTimeout(timeout);
29
+ resolvePromise(true);
30
+ }
31
+ };
32
+ ws.addEventListener("message", handler);
33
+
34
+ ws.send(
35
+ JSON.stringify({
36
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
37
+ id: requestId,
38
+ init: {
39
+ method: "POST",
40
+ body: JSON.stringify({ messages, ...extraBody })
41
+ }
42
+ })
43
+ );
44
+
45
+ const done = await donePromise;
46
+ ws.removeEventListener("message", handler);
47
+ expect(done).toBe(true);
48
+
49
+ // Allow handler to finish
50
+ await new Promise((resolve) => setTimeout(resolve, 100));
51
+ }
52
+
53
+ describe("requestId in OnChatMessageOptions", () => {
54
+ it("should pass the client-sent request ID on initial chat messages", async () => {
55
+ const room = crypto.randomUUID();
56
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
57
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
58
+ await agentStub.clearCapturedContext();
59
+
60
+ const userMessage: ChatMessage = {
61
+ id: "msg1",
62
+ role: "user",
63
+ parts: [{ type: "text", text: "Hello" }]
64
+ };
65
+
66
+ await sendChatAndWaitForDone(ws, "my-request-123", [userMessage]);
67
+
68
+ const capturedId = await agentStub.getCapturedRequestId();
69
+ expect(capturedId).toBe("my-request-123");
70
+
71
+ ws.close(1000);
72
+ });
73
+
74
+ it("should pass a server-generated requestId on tool result continuation", async () => {
75
+ const room = crypto.randomUUID();
76
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
77
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
78
+
79
+ const userMessage: ChatMessage = {
80
+ id: "msg1",
81
+ role: "user",
82
+ parts: [{ type: "text", text: "Hello" }]
83
+ };
84
+
85
+ // Step 1: Send initial request so context is established
86
+ await sendChatAndWaitForDone(ws, "initial-req", [userMessage]);
87
+
88
+ // Step 2: Persist a tool call in input-available state
89
+ const toolCallId = "call_reqid_test";
90
+ await agentStub.persistMessages([
91
+ userMessage,
92
+ {
93
+ id: "assistant-1",
94
+ role: "assistant",
95
+ parts: [
96
+ {
97
+ type: "tool-testTool",
98
+ toolCallId,
99
+ state: "input-available",
100
+ input: {}
101
+ }
102
+ ] as ChatMessage["parts"]
103
+ }
104
+ ]);
105
+
106
+ // Step 3: Clear captured state before continuation
107
+ await agentStub.clearCapturedContext();
108
+
109
+ // Step 4: Send tool result with autoContinue
110
+ ws.send(
111
+ JSON.stringify({
112
+ type: "cf_agent_tool_result",
113
+ toolCallId,
114
+ toolName: "testTool",
115
+ output: { success: true },
116
+ autoContinue: true
117
+ })
118
+ );
119
+
120
+ // Wait for continuation (500ms stream wait + processing)
121
+ await new Promise((resolve) => setTimeout(resolve, 1500));
122
+
123
+ // Step 5: Verify a requestId was passed (server-generated, so just check it exists)
124
+ const capturedId = await agentStub.getCapturedRequestId();
125
+ expect(capturedId).toBeDefined();
126
+ expect(typeof capturedId).toBe("string");
127
+ expect(capturedId!.length).toBeGreaterThan(0);
128
+ // Should NOT be the initial request ID — it's a new continuation ID
129
+ expect(capturedId).not.toBe("initial-req");
130
+
131
+ ws.close(1000);
132
+ });
133
+
134
+ it("should pass a server-generated requestId on tool approval continuation", async () => {
135
+ const room = crypto.randomUUID();
136
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
137
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
138
+
139
+ const userMessage: ChatMessage = {
140
+ id: "msg1",
141
+ role: "user",
142
+ parts: [{ type: "text", text: "Hello" }]
143
+ };
144
+
145
+ // Step 1: Send initial request
146
+ await sendChatAndWaitForDone(ws, "initial-req", [userMessage]);
147
+
148
+ // Step 2: Persist a tool call in approval-required state
149
+ const toolCallId = "call_approval_test";
150
+ await agentStub.persistMessages([
151
+ userMessage,
152
+ {
153
+ id: "assistant-1",
154
+ role: "assistant",
155
+ parts: [
156
+ {
157
+ type: "tool-testTool",
158
+ toolCallId,
159
+ state: "input-available",
160
+ input: {}
161
+ }
162
+ ] as ChatMessage["parts"]
163
+ }
164
+ ]);
165
+
166
+ // Step 3: Clear captured state
167
+ await agentStub.clearCapturedContext();
168
+
169
+ // Step 4: Send approval with autoContinue
170
+ ws.send(
171
+ JSON.stringify({
172
+ type: "cf_agent_tool_approval",
173
+ toolCallId,
174
+ approved: true,
175
+ autoContinue: true
176
+ })
177
+ );
178
+
179
+ // Wait for continuation
180
+ await new Promise((resolve) => setTimeout(resolve, 1500));
181
+
182
+ // Step 5: Verify requestId was passed
183
+ const capturedId = await agentStub.getCapturedRequestId();
184
+ expect(capturedId).toBeDefined();
185
+ expect(typeof capturedId).toBe("string");
186
+ expect(capturedId!.length).toBeGreaterThan(0);
187
+ expect(capturedId).not.toBe("initial-req");
188
+
189
+ ws.close(1000);
190
+ });
191
+
192
+ it("should tag response messages with requestId so the client can match them", async () => {
193
+ const room = crypto.randomUUID();
194
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
195
+
196
+ const receivedMessages: Array<{ id: string; done: boolean }> = [];
197
+
198
+ ws.addEventListener("message", (e: MessageEvent) => {
199
+ const data = JSON.parse(e.data as string);
200
+ if (isUseChatResponseMessage(data)) {
201
+ receivedMessages.push({ id: data.id, done: !!data.done });
202
+ }
203
+ });
204
+
205
+ const userMessage: ChatMessage = {
206
+ id: "msg1",
207
+ role: "user",
208
+ parts: [{ type: "text", text: "Hello" }]
209
+ };
210
+
211
+ ws.send(
212
+ JSON.stringify({
213
+ type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
214
+ id: "tagged-req-42",
215
+ init: {
216
+ method: "POST",
217
+ body: JSON.stringify({ messages: [userMessage] })
218
+ }
219
+ })
220
+ );
221
+
222
+ // Wait for the done message
223
+ await new Promise<void>((resolve) => {
224
+ const interval = setInterval(() => {
225
+ if (receivedMessages.some((m) => m.done)) {
226
+ clearInterval(interval);
227
+ resolve();
228
+ }
229
+ }, 50);
230
+ setTimeout(() => {
231
+ clearInterval(interval);
232
+ resolve();
233
+ }, 2000);
234
+ });
235
+
236
+ // ALL response messages should be tagged with the same request ID
237
+ expect(receivedMessages.length).toBeGreaterThan(0);
238
+ for (const msg of receivedMessages) {
239
+ expect(msg.id).toBe("tagged-req-42");
240
+ }
241
+
242
+ ws.close(1000);
243
+ });
244
+
245
+ it("should allow handlers to send error responses using requestId (pre-stream failure use case)", async () => {
246
+ // This is the primary use case from the PR:
247
+ // An onChatMessage handler validates the request body BEFORE starting a stream.
248
+ // If validation fails, it needs the requestId to send a properly-tagged error
249
+ // message that the client transport will accept (it filters by data.id === requestId).
250
+ //
251
+ // We test this by verifying that requestId is available and matches the
252
+ // wire-protocol ID, so a handler *could* send:
253
+ // connection.send(JSON.stringify({
254
+ // type: "cf_agent_use_chat_response",
255
+ // id: options.requestId,
256
+ // body: "validation error",
257
+ // done: true,
258
+ // error: true
259
+ // }));
260
+
261
+ const room = crypto.randomUUID();
262
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
263
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
264
+ await agentStub.clearCapturedContext();
265
+
266
+ const userMessage: ChatMessage = {
267
+ id: "msg1",
268
+ role: "user",
269
+ parts: [{ type: "text", text: "Hello" }]
270
+ };
271
+
272
+ const clientRequestId = "client-error-test-id";
273
+ await sendChatAndWaitForDone(ws, clientRequestId, [userMessage]);
274
+
275
+ // Verify the requestId received in onChatMessage matches exactly
276
+ // what the client sent as data.id — this is the contract that lets
277
+ // handlers send tagged error responses
278
+ const capturedId = await agentStub.getCapturedRequestId();
279
+ expect(capturedId).toBe(clientRequestId);
280
+
281
+ ws.close(1000);
282
+ });
283
+
284
+ it("should pass requestId with different values across sequential requests", async () => {
285
+ const room = crypto.randomUUID();
286
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
287
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
288
+
289
+ const userMessage: ChatMessage = {
290
+ id: "msg1",
291
+ role: "user",
292
+ parts: [{ type: "text", text: "Hello" }]
293
+ };
294
+
295
+ // First request
296
+ await agentStub.clearCapturedContext();
297
+ await sendChatAndWaitForDone(ws, "req-alpha", [userMessage]);
298
+ const firstId = await agentStub.getCapturedRequestId();
299
+ expect(firstId).toBe("req-alpha");
300
+
301
+ // Second request with different ID
302
+ await agentStub.clearCapturedContext();
303
+ await sendChatAndWaitForDone(ws, "req-beta", [userMessage]);
304
+ const secondId = await agentStub.getCapturedRequestId();
305
+ expect(secondId).toBe("req-beta");
306
+
307
+ // They should be different
308
+ expect(firstId).not.toBe(secondId);
309
+
310
+ ws.close(1000);
311
+ });
312
+ });