@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,309 +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 } from "./test-utils";
6
- import { getAgentByName } from "agents";
7
-
8
- describe("Custom body forwarding during tool continuation", () => {
9
- it("should forward stored body to onChatMessage during auto-continuation", async () => {
10
- const room = crypto.randomUUID();
11
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
12
-
13
- const agentStub = await getAgentByName(env.TestChatAgent, room);
14
- await agentStub.clearCapturedContext();
15
-
16
- // Step 1: Send initial chat request WITH custom body fields to store them
17
- let resolvePromise: (value: boolean) => void;
18
- let donePromise = new Promise<boolean>((res) => {
19
- resolvePromise = res;
20
- });
21
-
22
- let timeout = setTimeout(() => resolvePromise(false), 2000);
23
-
24
- ws.addEventListener("message", function handler(e: MessageEvent) {
25
- const data = JSON.parse(e.data as string);
26
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
27
- clearTimeout(timeout);
28
- resolvePromise(true);
29
- ws.removeEventListener("message", handler);
30
- }
31
- });
32
-
33
- const userMessage: ChatMessage = {
34
- id: "msg1",
35
- role: "user",
36
- parts: [{ type: "text", text: "Hello" }]
37
- };
38
-
39
- ws.send(
40
- JSON.stringify({
41
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
42
- id: "req1",
43
- init: {
44
- method: "POST",
45
- body: JSON.stringify({
46
- messages: [userMessage],
47
- model: "gpt-4",
48
- temperature: 0.7,
49
- customField: "custom-value"
50
- })
51
- }
52
- })
53
- );
54
-
55
- let done = await donePromise;
56
- expect(done).toBe(true);
57
-
58
- // Verify initial request received body
59
- await new Promise((resolve) => setTimeout(resolve, 100));
60
- const initialBody = await agentStub.getCapturedBody();
61
- expect(initialBody).toEqual({
62
- model: "gpt-4",
63
- temperature: 0.7,
64
- customField: "custom-value"
65
- });
66
-
67
- // Step 2: Persist a tool call in input-available state
68
- const toolCallId = "call_body_continuation_test";
69
- await agentStub.persistMessages([
70
- userMessage,
71
- {
72
- id: "assistant-1",
73
- role: "assistant",
74
- parts: [
75
- {
76
- type: "tool-changeBackgroundColor",
77
- toolCallId,
78
- state: "input-available",
79
- input: { color: "green" }
80
- }
81
- ] as ChatMessage["parts"]
82
- }
83
- ]);
84
-
85
- // Step 3: Clear captured state before continuation
86
- await agentStub.clearCapturedContext();
87
-
88
- // Step 4: Send tool result with autoContinue to trigger continuation
89
- ws.send(
90
- JSON.stringify({
91
- type: "cf_agent_tool_result",
92
- toolCallId,
93
- toolName: "changeBackgroundColor",
94
- output: { success: true },
95
- autoContinue: true
96
- })
97
- );
98
-
99
- // Wait for continuation (500ms stream wait + processing)
100
- await new Promise((resolve) => setTimeout(resolve, 1000));
101
-
102
- // Step 5: Verify continuation received the same body
103
- const continuationBody = await agentStub.getCapturedBody();
104
- expect(continuationBody).toBeDefined();
105
- expect(continuationBody).toEqual({
106
- model: "gpt-4",
107
- temperature: 0.7,
108
- customField: "custom-value"
109
- });
110
-
111
- ws.close(1000);
112
- });
113
-
114
- it("should clear stored body when chat is cleared", async () => {
115
- const room = crypto.randomUUID();
116
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
117
-
118
- const agentStub = await getAgentByName(env.TestChatAgent, room);
119
-
120
- // Send initial request with custom body to store it
121
- let resolvePromise: (value: boolean) => void;
122
- const donePromise = new Promise<boolean>((res) => {
123
- resolvePromise = res;
124
- });
125
-
126
- const timeout = setTimeout(() => resolvePromise(false), 2000);
127
-
128
- ws.addEventListener("message", function handler(e: MessageEvent) {
129
- const data = JSON.parse(e.data as string);
130
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
131
- clearTimeout(timeout);
132
- resolvePromise(true);
133
- ws.removeEventListener("message", handler);
134
- }
135
- });
136
-
137
- ws.send(
138
- JSON.stringify({
139
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
140
- id: "req1",
141
- init: {
142
- method: "POST",
143
- body: JSON.stringify({
144
- messages: [
145
- {
146
- id: "msg1",
147
- role: "user",
148
- parts: [{ type: "text", text: "Hi" }]
149
- }
150
- ],
151
- model: "gpt-4",
152
- temperature: 0.5
153
- })
154
- }
155
- })
156
- );
157
-
158
- const done = await donePromise;
159
- expect(done).toBe(true);
160
-
161
- // Clear chat
162
- ws.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
163
- await new Promise((resolve) => setTimeout(resolve, 200));
164
-
165
- // Persist a tool call and trigger continuation
166
- await agentStub.persistMessages([
167
- {
168
- id: "user-1",
169
- role: "user",
170
- parts: [{ type: "text", text: "Execute tool" }]
171
- },
172
- {
173
- id: "assistant-1",
174
- role: "assistant",
175
- parts: [
176
- {
177
- type: "tool-testTool",
178
- toolCallId: "call_after_clear",
179
- state: "input-available",
180
- input: {}
181
- }
182
- ] as ChatMessage["parts"]
183
- }
184
- ]);
185
-
186
- await agentStub.clearCapturedContext();
187
-
188
- ws.send(
189
- JSON.stringify({
190
- type: "cf_agent_tool_result",
191
- toolCallId: "call_after_clear",
192
- toolName: "testTool",
193
- output: { success: true },
194
- autoContinue: true
195
- })
196
- );
197
-
198
- await new Promise((resolve) => setTimeout(resolve, 1000));
199
-
200
- // Body should be undefined after chat clear
201
- const continuationBody = await agentStub.getCapturedBody();
202
- expect(continuationBody).toBeUndefined();
203
-
204
- ws.close(1000);
205
- });
206
-
207
- it("should update stored body when new request has different body fields", async () => {
208
- const room = crypto.randomUUID();
209
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
210
-
211
- const agentStub = await getAgentByName(env.TestChatAgent, room);
212
-
213
- // Send first request WITH body
214
- let resolvePromise: (value: boolean) => void;
215
- let donePromise = new Promise<boolean>((res) => {
216
- resolvePromise = res;
217
- });
218
- let timeout = setTimeout(() => resolvePromise(false), 2000);
219
-
220
- const handler1 = (e: MessageEvent) => {
221
- const data = JSON.parse(e.data as string);
222
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
223
- clearTimeout(timeout);
224
- resolvePromise(true);
225
- }
226
- };
227
- ws.addEventListener("message", handler1);
228
-
229
- ws.send(
230
- JSON.stringify({
231
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
232
- id: "req1",
233
- init: {
234
- method: "POST",
235
- body: JSON.stringify({
236
- messages: [
237
- {
238
- id: "msg1",
239
- role: "user",
240
- parts: [{ type: "text", text: "Hi" }]
241
- }
242
- ],
243
- model: "gpt-4",
244
- temperature: 0.7
245
- })
246
- }
247
- })
248
- );
249
-
250
- let done = await donePromise;
251
- expect(done).toBe(true);
252
- ws.removeEventListener("message", handler1);
253
-
254
- await new Promise((resolve) => setTimeout(resolve, 100));
255
- let capturedBody = await agentStub.getCapturedBody();
256
- expect(capturedBody).toEqual({ model: "gpt-4", temperature: 0.7 });
257
-
258
- // Send second request with DIFFERENT body
259
- donePromise = new Promise<boolean>((res) => {
260
- resolvePromise = res;
261
- });
262
- timeout = setTimeout(() => resolvePromise(false), 2000);
263
-
264
- const handler2 = (e: MessageEvent) => {
265
- const data = JSON.parse(e.data as string);
266
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
267
- clearTimeout(timeout);
268
- resolvePromise(true);
269
- }
270
- };
271
- ws.addEventListener("message", handler2);
272
-
273
- ws.send(
274
- JSON.stringify({
275
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
276
- id: "req2",
277
- init: {
278
- method: "POST",
279
- body: JSON.stringify({
280
- messages: [
281
- {
282
- id: "msg1",
283
- role: "user",
284
- parts: [{ type: "text", text: "Hi" }]
285
- },
286
- {
287
- id: "msg2",
288
- role: "user",
289
- parts: [{ type: "text", text: "Again" }]
290
- }
291
- ],
292
- model: "claude-3",
293
- maxTokens: 1000
294
- })
295
- }
296
- })
297
- );
298
-
299
- done = await donePromise;
300
- expect(done).toBe(true);
301
- ws.removeEventListener("message", handler2);
302
-
303
- await new Promise((resolve) => setTimeout(resolve, 100));
304
- capturedBody = await agentStub.getCapturedBody();
305
- expect(capturedBody).toEqual({ model: "claude-3", maxTokens: 1000 });
306
-
307
- ws.close(1000);
308
- });
309
- });
@@ -1,186 +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 } from "./test-utils";
6
- import { getAgentByName } from "agents";
7
-
8
- describe("Custom body forwarding to onChatMessage", () => {
9
- it("should forward custom body fields from the request to onChatMessage options", async () => {
10
- const room = crypto.randomUUID();
11
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
12
-
13
- const agentStub = await getAgentByName(env.TestChatAgent, room);
14
- await agentStub.clearCapturedContext();
15
-
16
- let resolvePromise: (value: boolean) => void;
17
- const donePromise = new Promise<boolean>((res) => {
18
- resolvePromise = res;
19
- });
20
-
21
- const timeout = setTimeout(() => resolvePromise(false), 2000);
22
-
23
- ws.addEventListener("message", (e: MessageEvent) => {
24
- const data = JSON.parse(e.data as string);
25
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
26
- clearTimeout(timeout);
27
- resolvePromise(true);
28
- }
29
- });
30
-
31
- const userMessage: ChatMessage = {
32
- id: "msg1",
33
- role: "user",
34
- parts: [{ type: "text", text: "Hello" }]
35
- };
36
-
37
- // Send a chat message with custom body fields
38
- ws.send(
39
- JSON.stringify({
40
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
41
- id: "req1",
42
- init: {
43
- method: "POST",
44
- body: JSON.stringify({
45
- messages: [userMessage],
46
- model: "gpt-4",
47
- temperature: 0.7,
48
- customField: "custom-value"
49
- })
50
- }
51
- })
52
- );
53
-
54
- const done = await donePromise;
55
- expect(done).toBe(true);
56
-
57
- // Wait a bit for the handler to complete
58
- await new Promise((resolve) => setTimeout(resolve, 100));
59
-
60
- const capturedBody = await agentStub.getCapturedBody();
61
-
62
- expect(capturedBody).toBeDefined();
63
- expect(capturedBody).toEqual({
64
- model: "gpt-4",
65
- temperature: 0.7,
66
- customField: "custom-value"
67
- });
68
-
69
- ws.close(1000);
70
- });
71
-
72
- it("should not include messages or clientTools in body", async () => {
73
- const room = crypto.randomUUID();
74
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
75
-
76
- const agentStub = await getAgentByName(env.TestChatAgent, room);
77
- await agentStub.clearCapturedContext();
78
-
79
- let resolvePromise: (value: boolean) => void;
80
- const donePromise = new Promise<boolean>((res) => {
81
- resolvePromise = res;
82
- });
83
-
84
- const timeout = setTimeout(() => resolvePromise(false), 2000);
85
-
86
- ws.addEventListener("message", (e: MessageEvent) => {
87
- const data = JSON.parse(e.data as string);
88
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
89
- clearTimeout(timeout);
90
- resolvePromise(true);
91
- }
92
- });
93
-
94
- const userMessage: ChatMessage = {
95
- id: "msg1",
96
- role: "user",
97
- parts: [{ type: "text", text: "Hello" }]
98
- };
99
-
100
- // Send a message with clientTools and custom fields
101
- ws.send(
102
- JSON.stringify({
103
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
104
- id: "req2",
105
- init: {
106
- method: "POST",
107
- body: JSON.stringify({
108
- messages: [userMessage],
109
- clientTools: [{ name: "testTool", description: "A test tool" }],
110
- extraData: "should-be-in-body"
111
- })
112
- }
113
- })
114
- );
115
-
116
- const done = await donePromise;
117
- expect(done).toBe(true);
118
-
119
- await new Promise((resolve) => setTimeout(resolve, 100));
120
-
121
- const capturedBody = await agentStub.getCapturedBody();
122
-
123
- expect(capturedBody).toBeDefined();
124
- // Should only contain extraData, not messages or clientTools
125
- expect(capturedBody).toEqual({ extraData: "should-be-in-body" });
126
- expect(capturedBody).not.toHaveProperty("messages");
127
- expect(capturedBody).not.toHaveProperty("clientTools");
128
-
129
- ws.close(1000);
130
- });
131
-
132
- it("should set body to undefined when no custom fields are present", async () => {
133
- const room = crypto.randomUUID();
134
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
135
-
136
- const agentStub = await getAgentByName(env.TestChatAgent, room);
137
- await agentStub.clearCapturedContext();
138
-
139
- let resolvePromise: (value: boolean) => void;
140
- const donePromise = new Promise<boolean>((res) => {
141
- resolvePromise = res;
142
- });
143
-
144
- const timeout = setTimeout(() => resolvePromise(false), 2000);
145
-
146
- ws.addEventListener("message", (e: MessageEvent) => {
147
- const data = JSON.parse(e.data as string);
148
- if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
149
- clearTimeout(timeout);
150
- resolvePromise(true);
151
- }
152
- });
153
-
154
- const userMessage: ChatMessage = {
155
- id: "msg1",
156
- role: "user",
157
- parts: [{ type: "text", text: "Hello" }]
158
- };
159
-
160
- // Send a message with only messages (no custom fields)
161
- ws.send(
162
- JSON.stringify({
163
- type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
164
- id: "req3",
165
- init: {
166
- method: "POST",
167
- body: JSON.stringify({
168
- messages: [userMessage]
169
- })
170
- }
171
- })
172
- );
173
-
174
- const done = await donePromise;
175
- expect(done).toBe(true);
176
-
177
- await new Promise((resolve) => setTimeout(resolve, 100));
178
-
179
- const capturedBody = await agentStub.getCapturedBody();
180
-
181
- // When there are no custom fields, body should be undefined
182
- expect(capturedBody).toBeUndefined();
183
-
184
- ws.close(1000);
185
- });
186
- });
@@ -1,57 +0,0 @@
1
- import { env } from "cloudflare:test";
2
- import { describe, it, expect } from "vitest";
3
- import { connectChatWS } from "./test-utils";
4
- import { getAgentByName } from "agents";
5
-
6
- describe("AIChatAgent destroy()", () => {
7
- it("clears active stream state on destroy", async () => {
8
- const room = crypto.randomUUID();
9
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
10
- await new Promise((r) => setTimeout(r, 50));
11
-
12
- const agentStub = await getAgentByName(env.TestChatAgent, room);
13
-
14
- // Start a stream to create active state
15
- const streamId = await agentStub.testStartStream("req-destroy-1");
16
- await agentStub.testStoreStreamChunk(
17
- streamId,
18
- '{"type":"text","text":"test"}'
19
- );
20
- await agentStub.testFlushChunkBuffer();
21
-
22
- // Verify state exists before destroy
23
- expect(await agentStub.getActiveStreamId()).toBe(streamId);
24
- const chunks = await agentStub.getStreamChunks(streamId);
25
- expect(chunks.length).toBe(1);
26
-
27
- ws.close(1000);
28
- });
29
-
30
- it("flushes pending chunk buffer on destroy", async () => {
31
- const room = crypto.randomUUID();
32
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
33
- await new Promise((r) => setTimeout(r, 50));
34
-
35
- const agentStub = await getAgentByName(env.TestChatAgent, room);
36
-
37
- // Start a stream and add chunks without flushing
38
- const streamId = await agentStub.testStartStream("req-destroy-2");
39
- await agentStub.testStoreStreamChunk(
40
- streamId,
41
- '{"type":"text","text":"chunk1"}'
42
- );
43
- await agentStub.testStoreStreamChunk(
44
- streamId,
45
- '{"type":"text","text":"chunk2"}'
46
- );
47
-
48
- // These are still in the buffer (not flushed yet since < 10 chunks)
49
- // Flush manually to verify they're stored
50
- await agentStub.testFlushChunkBuffer();
51
-
52
- const chunks = await agentStub.getStreamChunks(streamId);
53
- expect(chunks.length).toBe(2);
54
-
55
- ws.close(1000);
56
- });
57
- });
@@ -1,153 +0,0 @@
1
- import { createExecutionContext, env } from "cloudflare:test";
2
- import { describe, it, expect } from "vitest";
3
- import worker from "./worker";
4
- import type { UIMessage as ChatMessage } from "ai";
5
- import { connectChatWS } from "./test-utils";
6
- import { getAgentByName } from "agents";
7
-
8
- describe("GET /get-messages endpoint", () => {
9
- it("returns empty array for a new agent with no messages", async () => {
10
- const room = crypto.randomUUID();
11
-
12
- // First, establish a WebSocket to create the DO instance
13
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
14
- await new Promise((r) => setTimeout(r, 50));
15
- ws.close(1000);
16
-
17
- const req = new Request(
18
- `http://example.com/agents/test-chat-agent/${room}/get-messages`
19
- );
20
- const res = await worker.fetch(req, env, createExecutionContext());
21
-
22
- expect(res.status).toBe(200);
23
- const messages = (await res.json()) as ChatMessage[];
24
- expect(messages).toEqual([]);
25
- });
26
-
27
- it("returns persisted messages in chronological order", async () => {
28
- const room = crypto.randomUUID();
29
- const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
30
- await new Promise((r) => setTimeout(r, 50));
31
-
32
- const agentStub = await getAgentByName(env.TestChatAgent, room);
33
-
34
- const messages: ChatMessage[] = [
35
- {
36
- id: "msg-get-1",
37
- role: "user",
38
- parts: [{ type: "text", text: "First" }]
39
- },
40
- {
41
- id: "msg-get-2",
42
- role: "assistant",
43
- parts: [{ type: "text", text: "Second" }]
44
- },
45
- {
46
- id: "msg-get-3",
47
- role: "user",
48
- parts: [{ type: "text", text: "Third" }]
49
- }
50
- ];
51
-
52
- await agentStub.persistMessages(messages);
53
- ws.close(1000);
54
-
55
- const req = new Request(
56
- `http://example.com/agents/test-chat-agent/${room}/get-messages`
57
- );
58
- const res = await worker.fetch(req, env, createExecutionContext());
59
-
60
- expect(res.status).toBe(200);
61
- const returned = (await res.json()) as ChatMessage[];
62
- expect(returned.length).toBe(3);
63
- expect(returned.map((m) => m.id)).toEqual([
64
- "msg-get-1",
65
- "msg-get-2",
66
- "msg-get-3"
67
- ]);
68
- });
69
-
70
- it("returns 404 for non-existent routes", async () => {
71
- const req = new Request(
72
- "http://example.com/agents/test-chat-agent/foo/bar"
73
- );
74
- const res = await worker.fetch(req, env, createExecutionContext());
75
-
76
- // The worker returns 404 for unknown routes
77
- expect(res.status).toBe(404);
78
- });
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
- });