@cloudflare/ai-chat 0.0.8 → 0.1.1

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 (60) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +225 -459
  3. package/dist/ai-chat-v5-migration.d.ts +9 -9
  4. package/dist/ai-chat-v5-migration.js +25 -4
  5. package/dist/ai-chat-v5-migration.js.map +1 -1
  6. package/dist/experimental/forever.d.ts +29 -0
  7. package/dist/experimental/forever.js +55 -0
  8. package/dist/experimental/forever.js.map +1 -0
  9. package/dist/index.d.ts +114 -76
  10. package/dist/index.js +745 -629
  11. package/dist/index.js.map +1 -1
  12. package/dist/message-builder-Bwc_Umye.js +231 -0
  13. package/dist/message-builder-Bwc_Umye.js.map +1 -0
  14. package/dist/react.d.ts +27 -9
  15. package/dist/react.js +244 -258
  16. package/dist/react.js.map +1 -1
  17. package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
  18. package/dist/types.d.ts +16 -4
  19. package/dist/types.js +2 -0
  20. package/dist/types.js.map +1 -1
  21. package/e2e/chat.spec.ts +1703 -0
  22. package/e2e/client-tools.spec.ts +504 -0
  23. package/e2e/llm.spec.ts +637 -0
  24. package/e2e/playwright.config.ts +24 -0
  25. package/e2e/worker.ts +176 -0
  26. package/e2e/wrangler.jsonc +23 -0
  27. package/package.json +13 -5
  28. package/scripts/build.ts +2 -1
  29. package/src/ai-chat-v5-migration.ts +32 -5
  30. package/src/experimental/forever.ts +66 -0
  31. package/src/index.ts +831 -1137
  32. package/src/message-builder.ts +384 -0
  33. package/src/react-tests/use-agent-chat.test.tsx +738 -2
  34. package/src/react.tsx +385 -461
  35. package/src/resumable-stream.ts +441 -0
  36. package/src/tests/chat-context.test.ts +1 -1
  37. package/src/tests/chat-persistence.test.ts +5 -5
  38. package/src/tests/clear-history.test.ts +132 -0
  39. package/src/tests/client-tool-duplicate-message.test.ts +457 -14
  40. package/src/tests/client-tools-broadcast.test.ts +2 -2
  41. package/src/tests/client-tools-continuation.test.ts +3 -3
  42. package/src/tests/client-tools-reconnect.test.ts +143 -0
  43. package/src/tests/custom-body-continuation.test.ts +309 -0
  44. package/src/tests/custom-body.test.ts +3 -3
  45. package/src/tests/destroy.test.ts +57 -0
  46. package/src/tests/get-messages-endpoint.test.ts +79 -0
  47. package/src/tests/max-persisted-messages.test.ts +201 -0
  48. package/src/tests/merge-server-state.test.ts +106 -0
  49. package/src/tests/message-builder.test.ts +808 -0
  50. package/src/tests/migration.test.ts +282 -0
  51. package/src/tests/non-sse-response.test.ts +2 -2
  52. package/src/tests/onfinish-cleanup.test.ts +362 -0
  53. package/src/tests/plaintext-response.test.ts +87 -0
  54. package/src/tests/resumable-streaming.test.ts +220 -14
  55. package/src/tests/row-size-guard.test.ts +374 -0
  56. package/src/tests/sanitize-messages.test.ts +215 -0
  57. package/src/tests/validate-messages.test.ts +269 -0
  58. package/src/tests/worker.ts +59 -24
  59. package/src/types.ts +17 -1
  60. package/src/ws-chat-transport.ts +203 -0
@@ -0,0 +1,143 @@
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("Client tools after reconnect", () => {
9
+ it("should use client tools from CF_AGENT_TOOL_RESULT for continuation", async () => {
10
+ const room = crypto.randomUUID();
11
+
12
+ // Step 1: Set up a conversation with a pending tool call (simulates state before refresh)
13
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
14
+
15
+ const userMessage: ChatMessage = {
16
+ id: "msg1",
17
+ role: "user",
18
+ parts: [{ type: "text", text: "Change the background" }]
19
+ };
20
+
21
+ const toolCallId = "call_reconnect_test";
22
+ const assistantMessage: ChatMessage = {
23
+ id: "assistant-1",
24
+ role: "assistant",
25
+ parts: [
26
+ {
27
+ type: "tool-changeBackgroundColor",
28
+ toolCallId,
29
+ state: "input-available",
30
+ input: { color: "blue" }
31
+ }
32
+ ] as ChatMessage["parts"]
33
+ };
34
+
35
+ // Persist messages directly (simulates state loaded from SQLite after DO restart)
36
+ await agentStub.persistMessages([userMessage, assistantMessage]);
37
+
38
+ // Step 2: Connect (simulates reconnect after refresh)
39
+ // Note: We intentionally do NOT send a CF_AGENT_USE_CHAT_REQUEST first,
40
+ // so _lastClientTools is never set — this simulates DO restart.
41
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
42
+
43
+ // Wait for connection to be established
44
+ await new Promise((resolve) => setTimeout(resolve, 200));
45
+
46
+ // Clear any captured context from connection setup
47
+ await agentStub.clearCapturedContext();
48
+
49
+ // Step 3: Send tool result WITH clientTools (simulates client approval after reconnect)
50
+ const clientTools = [
51
+ {
52
+ name: "changeBackgroundColor",
53
+ description: "Changes the background color",
54
+ parameters: {
55
+ type: "object",
56
+ properties: { color: { type: "string" } }
57
+ }
58
+ },
59
+ {
60
+ name: "changeTextColor",
61
+ description: "Changes the text color",
62
+ parameters: {
63
+ type: "object",
64
+ properties: { color: { type: "string" } }
65
+ }
66
+ }
67
+ ];
68
+
69
+ ws.send(
70
+ JSON.stringify({
71
+ type: MessageType.CF_AGENT_TOOL_RESULT,
72
+ toolCallId,
73
+ toolName: "changeBackgroundColor",
74
+ output: { success: true },
75
+ autoContinue: true,
76
+ clientTools
77
+ })
78
+ );
79
+
80
+ // Wait for tool result to be applied + 500ms stream wait + continuation
81
+ await new Promise((resolve) => setTimeout(resolve, 1500));
82
+
83
+ // Step 4: Verify continuation received client tools
84
+ const capturedClientTools = await agentStub.getCapturedClientTools();
85
+ expect(capturedClientTools).toBeDefined();
86
+ expect(capturedClientTools).toHaveLength(2);
87
+ expect(capturedClientTools![0].name).toBe("changeBackgroundColor");
88
+ expect(capturedClientTools![1].name).toBe("changeTextColor");
89
+
90
+ ws.close(1000);
91
+ });
92
+
93
+ it("should work without clientTools in CF_AGENT_TOOL_RESULT (backwards compat)", async () => {
94
+ const room = crypto.randomUUID();
95
+
96
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
97
+
98
+ // Persist a conversation with a pending tool call
99
+ await agentStub.persistMessages([
100
+ {
101
+ id: "msg1",
102
+ role: "user",
103
+ parts: [{ type: "text", text: "Do something" }]
104
+ },
105
+ {
106
+ id: "assistant-1",
107
+ role: "assistant",
108
+ parts: [
109
+ {
110
+ type: "tool-testTool",
111
+ toolCallId: "call_compat_test",
112
+ state: "input-available",
113
+ input: {}
114
+ }
115
+ ] as ChatMessage["parts"]
116
+ }
117
+ ]);
118
+
119
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
120
+ await new Promise((resolve) => setTimeout(resolve, 200));
121
+ await agentStub.clearCapturedContext();
122
+
123
+ // Send tool result WITHOUT clientTools (old client behavior)
124
+ ws.send(
125
+ JSON.stringify({
126
+ type: MessageType.CF_AGENT_TOOL_RESULT,
127
+ toolCallId: "call_compat_test",
128
+ toolName: "testTool",
129
+ output: { success: true },
130
+ autoContinue: true
131
+ // No clientTools field
132
+ })
133
+ );
134
+
135
+ await new Promise((resolve) => setTimeout(resolve, 1500));
136
+
137
+ // Continuation should still fire, just without client tools
138
+ const capturedClientTools = await agentStub.getCapturedClientTools();
139
+ expect(capturedClientTools).toBeUndefined();
140
+
141
+ ws.close(1000);
142
+ });
143
+ });
@@ -0,0 +1,309 @@
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
+ });
@@ -66,7 +66,7 @@ describe("Custom body forwarding to onChatMessage", () => {
66
66
  customField: "custom-value"
67
67
  });
68
68
 
69
- ws.close();
69
+ ws.close(1000);
70
70
  });
71
71
 
72
72
  it("should not include messages or clientTools in body", async () => {
@@ -126,7 +126,7 @@ describe("Custom body forwarding to onChatMessage", () => {
126
126
  expect(capturedBody).not.toHaveProperty("messages");
127
127
  expect(capturedBody).not.toHaveProperty("clientTools");
128
128
 
129
- ws.close();
129
+ ws.close(1000);
130
130
  });
131
131
 
132
132
  it("should set body to undefined when no custom fields are present", async () => {
@@ -181,6 +181,6 @@ describe("Custom body forwarding to onChatMessage", () => {
181
181
  // When there are no custom fields, body should be undefined
182
182
  expect(capturedBody).toBeUndefined();
183
183
 
184
- ws.close();
184
+ ws.close(1000);
185
185
  });
186
186
  });
@@ -0,0 +1,57 @@
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
+ });
@@ -0,0 +1,79 @@
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
+ });