@cloudflare/ai-chat 0.0.8 → 0.1.0

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 +89 -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 +12 -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,201 @@
1
+ import { env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import type { UIMessage as ChatMessage } from "ai";
4
+ import { connectChatWS } from "./test-utils";
5
+ import { getAgentByName } from "agents";
6
+
7
+ describe("maxPersistedMessages", () => {
8
+ it("does not limit messages when maxPersistedMessages is undefined", async () => {
9
+ const room = crypto.randomUUID();
10
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
11
+ await new Promise((r) => setTimeout(r, 50));
12
+
13
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
14
+
15
+ // Default: no limit
16
+ const messages: ChatMessage[] = Array.from({ length: 20 }, (_, i) => ({
17
+ id: `msg-nolimit-${i}`,
18
+ role: "user" as const,
19
+ parts: [{ type: "text" as const, text: `Message ${i}` }]
20
+ }));
21
+
22
+ await agentStub.persistMessages(messages);
23
+
24
+ const count = await agentStub.getMessageCount();
25
+ expect(count).toBe(20);
26
+
27
+ ws.close(1000);
28
+ });
29
+
30
+ it("deletes oldest messages when count exceeds limit", 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
+ // Set limit to 5
38
+ await agentStub.setMaxPersistedMessages(5);
39
+
40
+ // Persist 10 messages
41
+ const messages: ChatMessage[] = Array.from({ length: 10 }, (_, i) => ({
42
+ id: `msg-limit-${i}`,
43
+ role: "user" as const,
44
+ parts: [{ type: "text" as const, text: `Message ${i}` }]
45
+ }));
46
+
47
+ await agentStub.persistMessages(messages);
48
+
49
+ // Should have exactly 5 messages
50
+ const count = await agentStub.getMessageCount();
51
+ expect(count).toBe(5);
52
+
53
+ // The kept messages should be the most recent 5
54
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
55
+ expect(persisted.length).toBe(5);
56
+ expect(persisted[0].id).toBe("msg-limit-5");
57
+ expect(persisted[4].id).toBe("msg-limit-9");
58
+
59
+ ws.close(1000);
60
+ });
61
+
62
+ it("keeps all messages when count is under the limit", async () => {
63
+ const room = crypto.randomUUID();
64
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
65
+ await new Promise((r) => setTimeout(r, 50));
66
+
67
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
68
+
69
+ await agentStub.setMaxPersistedMessages(100);
70
+
71
+ const messages: ChatMessage[] = Array.from({ length: 5 }, (_, i) => ({
72
+ id: `msg-under-${i}`,
73
+ role: "user" as const,
74
+ parts: [{ type: "text" as const, text: `Message ${i}` }]
75
+ }));
76
+
77
+ await agentStub.persistMessages(messages);
78
+
79
+ const count = await agentStub.getMessageCount();
80
+ expect(count).toBe(5);
81
+
82
+ ws.close(1000);
83
+ });
84
+
85
+ it("enforces limit across multiple persist calls", async () => {
86
+ const room = crypto.randomUUID();
87
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
88
+ await new Promise((r) => setTimeout(r, 50));
89
+
90
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
91
+
92
+ await agentStub.setMaxPersistedMessages(4);
93
+
94
+ // First batch: 3 messages
95
+ await agentStub.persistMessages([
96
+ {
97
+ id: "batch1-1",
98
+ role: "user",
99
+ parts: [{ type: "text", text: "First" }]
100
+ },
101
+ {
102
+ id: "batch1-2",
103
+ role: "assistant",
104
+ parts: [{ type: "text", text: "Response 1" }]
105
+ },
106
+ {
107
+ id: "batch1-3",
108
+ role: "user",
109
+ parts: [{ type: "text", text: "Second" }]
110
+ }
111
+ ]);
112
+
113
+ expect(await agentStub.getMessageCount()).toBe(3);
114
+
115
+ // Second batch: adds 3 more (total would be 6, limit is 4)
116
+ await agentStub.persistMessages([
117
+ {
118
+ id: "batch1-1",
119
+ role: "user",
120
+ parts: [{ type: "text", text: "First" }]
121
+ },
122
+ {
123
+ id: "batch1-2",
124
+ role: "assistant",
125
+ parts: [{ type: "text", text: "Response 1" }]
126
+ },
127
+ {
128
+ id: "batch1-3",
129
+ role: "user",
130
+ parts: [{ type: "text", text: "Second" }]
131
+ },
132
+ {
133
+ id: "batch2-1",
134
+ role: "assistant",
135
+ parts: [{ type: "text", text: "Response 2" }]
136
+ },
137
+ {
138
+ id: "batch2-2",
139
+ role: "user",
140
+ parts: [{ type: "text", text: "Third" }]
141
+ },
142
+ {
143
+ id: "batch2-3",
144
+ role: "assistant",
145
+ parts: [{ type: "text", text: "Response 3" }]
146
+ }
147
+ ]);
148
+
149
+ // Should be capped at 4
150
+ expect(await agentStub.getMessageCount()).toBe(4);
151
+
152
+ // The kept messages should be the most recent 4
153
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
154
+ expect(persisted.map((m) => m.id)).toEqual([
155
+ "batch1-3",
156
+ "batch2-1",
157
+ "batch2-2",
158
+ "batch2-3"
159
+ ]);
160
+
161
+ ws.close(1000);
162
+ });
163
+
164
+ it("can be disabled by setting to null", async () => {
165
+ const room = crypto.randomUUID();
166
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
167
+ await new Promise((r) => setTimeout(r, 50));
168
+
169
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
170
+
171
+ // Enable limit
172
+ await agentStub.setMaxPersistedMessages(3);
173
+
174
+ await agentStub.persistMessages(
175
+ Array.from({ length: 5 }, (_, i) => ({
176
+ id: `disable-${i}`,
177
+ role: "user" as const,
178
+ parts: [{ type: "text" as const, text: `Msg ${i}` }]
179
+ }))
180
+ );
181
+ expect(await agentStub.getMessageCount()).toBe(3);
182
+
183
+ // Disable limit
184
+ await agentStub.setMaxPersistedMessages(null);
185
+
186
+ // Add more messages -- should keep all now
187
+ await agentStub.persistMessages(
188
+ Array.from({ length: 8 }, (_, i) => ({
189
+ id: `disable-after-${i}`,
190
+ role: "user" as const,
191
+ parts: [{ type: "text" as const, text: `Msg after ${i}` }]
192
+ }))
193
+ );
194
+
195
+ // All 8 new + 3 remaining from before (but IDs overlap detection may differ)
196
+ // The key assertion: count is more than 3 (limit was removed)
197
+ expect(await agentStub.getMessageCount()).toBeGreaterThan(3);
198
+
199
+ ws.close(1000);
200
+ });
201
+ });
@@ -0,0 +1,106 @@
1
+ import { env } from "cloudflare:test";
2
+ import { describe, it, expect } from "vitest";
3
+ import type { UIMessage as ChatMessage } from "ai";
4
+ import { connectChatWS } from "./test-utils";
5
+ import { getAgentByName } from "agents";
6
+
7
+ // Type helper for tool call parts
8
+ type TestToolCallPart = Extract<
9
+ ChatMessage["parts"][number],
10
+ { type: `tool-${string}` }
11
+ >;
12
+
13
+ describe("Merge Incoming With Server State", () => {
14
+ it("preserves server-side tool outputs when client sends messages without them", async () => {
15
+ const room = crypto.randomUUID();
16
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
17
+ await new Promise((r) => setTimeout(r, 50));
18
+
19
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
20
+
21
+ // Step 1: Persist a message with tool output on the server
22
+ const toolResultPart: TestToolCallPart = {
23
+ type: "tool-getWeather",
24
+ toolCallId: "call_merge_1",
25
+ state: "output-available",
26
+ input: { city: "London" },
27
+ output: "Rainy, 12°C"
28
+ };
29
+
30
+ const serverMessage: ChatMessage = {
31
+ id: "assistant-merge-1",
32
+ role: "assistant",
33
+ parts: [toolResultPart] as ChatMessage["parts"]
34
+ };
35
+
36
+ await agentStub.persistMessages([serverMessage]);
37
+
38
+ // Step 2: Client sends the same message but without the tool output
39
+ // (client only knows about input-available state)
40
+ const clientMessage: ChatMessage = {
41
+ id: "assistant-merge-1",
42
+ role: "assistant",
43
+ parts: [
44
+ {
45
+ type: "tool-getWeather",
46
+ toolCallId: "call_merge_1",
47
+ state: "input-available",
48
+ input: { city: "London" }
49
+ } as unknown as ChatMessage["parts"][number]
50
+ ]
51
+ };
52
+
53
+ // Send via CF_AGENT_CHAT_MESSAGES (which triggers persistMessages with merge)
54
+ const newUserMsg: ChatMessage = {
55
+ id: "user-merge-1",
56
+ role: "user",
57
+ parts: [{ type: "text", text: "Follow up question" }]
58
+ };
59
+
60
+ await agentStub.persistMessages([clientMessage, newUserMsg]);
61
+
62
+ // Step 3: Verify the tool output is preserved
63
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
64
+
65
+ const assistantMsg = persisted.find((m) => m.id === "assistant-merge-1");
66
+ expect(assistantMsg).toBeDefined();
67
+
68
+ const toolPart = assistantMsg!.parts[0] as {
69
+ state: string;
70
+ output?: unknown;
71
+ };
72
+ expect(toolPart.state).toBe("output-available");
73
+ expect(toolPart.output).toBe("Rainy, 12°C");
74
+
75
+ ws.close(1000);
76
+ });
77
+
78
+ it("passes through messages unchanged when server has no tool outputs", async () => {
79
+ const room = crypto.randomUUID();
80
+ const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
81
+ await new Promise((r) => setTimeout(r, 50));
82
+
83
+ const agentStub = await getAgentByName(env.TestChatAgent, room);
84
+
85
+ const userMessage: ChatMessage = {
86
+ id: "user-no-merge",
87
+ role: "user",
88
+ parts: [{ type: "text", text: "Hello" }]
89
+ };
90
+
91
+ const assistantMessage: ChatMessage = {
92
+ id: "assistant-no-merge",
93
+ role: "assistant",
94
+ parts: [{ type: "text", text: "Hi there!" }]
95
+ };
96
+
97
+ await agentStub.persistMessages([userMessage, assistantMessage]);
98
+
99
+ const persisted = (await agentStub.getPersistedMessages()) as ChatMessage[];
100
+ expect(persisted.length).toBe(2);
101
+ expect(persisted[0].id).toBe("user-no-merge");
102
+ expect(persisted[1].id).toBe("assistant-no-merge");
103
+
104
+ ws.close(1000);
105
+ });
106
+ });