@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.
- package/dist/experimental/forever.d.ts +4 -13
- package/dist/experimental/forever.js +1 -46
- package/dist/experimental/forever.js.map +1 -1
- package/dist/index.d.ts +59 -4
- package/dist/index.js +170 -28
- package/dist/index.js.map +1 -1
- package/dist/{message-builder-Bwc_Umye.js → message-builder-uSvexDl2.js} +17 -4
- package/dist/message-builder-uSvexDl2.js.map +1 -0
- package/dist/react.js +96 -10
- package/dist/react.js.map +1 -1
- package/dist/{resumable-stream-DqXxQVjf.d.ts → resumable-stream-DTLAk9XC.d.ts} +25 -2
- package/dist/types.d.ts +2 -1
- package/dist/types.js.map +1 -1
- package/package.json +7 -3
- package/CHANGELOG.md +0 -251
- package/dist/message-builder-Bwc_Umye.js.map +0 -1
- package/e2e/chat.spec.ts +0 -1703
- package/e2e/client-tools.spec.ts +0 -504
- package/e2e/llm.spec.ts +0 -637
- package/e2e/playwright.config.ts +0 -27
- package/e2e/worker.ts +0 -174
- package/e2e/wrangler.jsonc +0 -23
- package/scripts/build.ts +0 -32
- package/src/ai-chat-v5-migration.ts +0 -403
- package/src/experimental/forever.ts +0 -66
- package/src/index.ts +0 -2269
- package/src/message-builder.ts +0 -384
- package/src/react-tests/setup.ts +0 -3
- package/src/react-tests/use-agent-chat.test.tsx +0 -1435
- package/src/react-tests/vitest.config.ts +0 -20
- package/src/react.tsx +0 -1447
- package/src/resumable-stream.ts +0 -441
- package/src/tests/cancel-request.test.ts +0 -280
- package/src/tests/chat-context.test.ts +0 -85
- package/src/tests/chat-persistence.test.ts +0 -426
- package/src/tests/clear-history.test.ts +0 -132
- package/src/tests/client-tool-duplicate-message.test.ts +0 -1957
- package/src/tests/client-tools-broadcast.test.ts +0 -138
- package/src/tests/client-tools-continuation.test.ts +0 -314
- package/src/tests/client-tools-reconnect.test.ts +0 -143
- package/src/tests/cloudflare-test.d.ts +0 -5
- package/src/tests/custom-body-continuation.test.ts +0 -309
- package/src/tests/custom-body.test.ts +0 -186
- package/src/tests/destroy.test.ts +0 -57
- package/src/tests/get-messages-endpoint.test.ts +0 -153
- package/src/tests/max-persisted-messages.test.ts +0 -201
- package/src/tests/merge-server-state.test.ts +0 -343
- package/src/tests/message-builder.test.ts +0 -808
- package/src/tests/migration.test.ts +0 -282
- package/src/tests/non-sse-response.test.ts +0 -186
- package/src/tests/onfinish-cleanup.test.ts +0 -362
- package/src/tests/plaintext-response.test.ts +0 -87
- package/src/tests/request-id.test.ts +0 -312
- package/src/tests/resumable-streaming.test.ts +0 -758
- package/src/tests/row-size-guard.test.ts +0 -374
- package/src/tests/sanitize-messages.test.ts +0 -325
- package/src/tests/test-utils.ts +0 -39
- package/src/tests/tsconfig.json +0 -10
- package/src/tests/validate-messages.test.ts +0 -269
- package/src/tests/vitest.config.ts +0 -30
- package/src/tests/worker.ts +0 -456
- package/src/tests/wrangler.jsonc +0 -50
- package/src/tests/ws-transport-abort.test.ts +0 -198
- package/src/types.ts +0 -152
- package/src/ws-chat-transport.ts +0 -227
- package/tsconfig.json +0 -4
- package/vitest.config.ts +0 -7
|
@@ -1,85 +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("AIChatAgent Connection Context - Issue #711", () => {
|
|
9
|
-
it("getCurrentAgent() should return connection in onChatMessage and nested async functions (tool execute)", async () => {
|
|
10
|
-
const room = crypto.randomUUID();
|
|
11
|
-
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
12
|
-
|
|
13
|
-
// Get the agent stub to access captured context
|
|
14
|
-
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
15
|
-
|
|
16
|
-
// Clear any previous captured context
|
|
17
|
-
await agentStub.clearCapturedContext();
|
|
18
|
-
|
|
19
|
-
let resolvePromise: (value: boolean) => void;
|
|
20
|
-
const donePromise = new Promise<boolean>((res) => {
|
|
21
|
-
resolvePromise = res;
|
|
22
|
-
});
|
|
23
|
-
|
|
24
|
-
const timeout = setTimeout(() => resolvePromise(false), 2000);
|
|
25
|
-
|
|
26
|
-
ws.addEventListener("message", (e: MessageEvent) => {
|
|
27
|
-
const data = JSON.parse(e.data as string);
|
|
28
|
-
if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
|
|
29
|
-
clearTimeout(timeout);
|
|
30
|
-
resolvePromise(true);
|
|
31
|
-
}
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
const userMessage: ChatMessage = {
|
|
35
|
-
id: "msg1",
|
|
36
|
-
role: "user",
|
|
37
|
-
parts: [{ type: "text", text: "Hello" }]
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
// Send a chat message which will trigger onChatMessage
|
|
41
|
-
ws.send(
|
|
42
|
-
JSON.stringify({
|
|
43
|
-
type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
|
|
44
|
-
id: "req1",
|
|
45
|
-
init: {
|
|
46
|
-
method: "POST",
|
|
47
|
-
body: JSON.stringify({ messages: [userMessage] })
|
|
48
|
-
}
|
|
49
|
-
})
|
|
50
|
-
);
|
|
51
|
-
|
|
52
|
-
const done = await donePromise;
|
|
53
|
-
expect(done).toBe(true);
|
|
54
|
-
|
|
55
|
-
// Wait a bit to ensure context is captured
|
|
56
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
57
|
-
|
|
58
|
-
// Check the captured context from onChatMessage
|
|
59
|
-
const capturedContext = await agentStub.getCapturedContext();
|
|
60
|
-
|
|
61
|
-
expect(capturedContext).not.toBeNull();
|
|
62
|
-
// The agent should be available
|
|
63
|
-
expect(capturedContext?.hasAgent).toBe(true);
|
|
64
|
-
// The connection should be available - this is the bug being tested
|
|
65
|
-
// Before the fix, this would be false
|
|
66
|
-
expect(capturedContext?.hasConnection).toBe(true);
|
|
67
|
-
// The connection ID should be defined
|
|
68
|
-
expect(capturedContext?.connectionId).toBeDefined();
|
|
69
|
-
|
|
70
|
-
// Check the nested context
|
|
71
|
-
// Tools called from onChatMessage couldn't access connection context
|
|
72
|
-
const nestedContext = await agentStub.getNestedContext();
|
|
73
|
-
|
|
74
|
-
expect(nestedContext).not.toBeNull();
|
|
75
|
-
// The agent should be available in nested async functions
|
|
76
|
-
expect(nestedContext?.hasAgent).toBe(true);
|
|
77
|
-
// The connection should ALSO be available in nested async functions (tool execute)
|
|
78
|
-
// Before the fix, this would be false
|
|
79
|
-
expect(nestedContext?.hasConnection).toBe(true);
|
|
80
|
-
// The connection ID should match between onChatMessage and nested function
|
|
81
|
-
expect(nestedContext?.connectionId).toBe(capturedContext?.connectionId);
|
|
82
|
-
|
|
83
|
-
ws.close(1000);
|
|
84
|
-
});
|
|
85
|
-
});
|
|
@@ -1,426 +0,0 @@
|
|
|
1
|
-
import { createExecutionContext, env } from "cloudflare:test";
|
|
2
|
-
import { describe, it, expect } from "vitest";
|
|
3
|
-
import worker from "./worker";
|
|
4
|
-
import { MessageType } from "../types";
|
|
5
|
-
import type { UIMessage as ChatMessage } from "ai";
|
|
6
|
-
import { connectChatWS } from "./test-utils";
|
|
7
|
-
import { getAgentByName } from "agents";
|
|
8
|
-
|
|
9
|
-
// Type helper for tool call parts - extracts ToolUIPart from ChatMessage parts
|
|
10
|
-
type TestToolCallPart = Extract<
|
|
11
|
-
ChatMessage["parts"][number],
|
|
12
|
-
{ type: `tool-${string}` }
|
|
13
|
-
>;
|
|
14
|
-
|
|
15
|
-
describe("Chat Agent Persistence", () => {
|
|
16
|
-
it("persists new messages incrementally without deleting existing ones", async () => {
|
|
17
|
-
const room = crypto.randomUUID();
|
|
18
|
-
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
19
|
-
|
|
20
|
-
const messages: unknown[] = [];
|
|
21
|
-
let resolvePromise: (value: boolean) => void;
|
|
22
|
-
const donePromise = new Promise<boolean>((res) => {
|
|
23
|
-
resolvePromise = res;
|
|
24
|
-
});
|
|
25
|
-
|
|
26
|
-
const timeout = setTimeout(() => resolvePromise(false), 2000);
|
|
27
|
-
|
|
28
|
-
ws.addEventListener("message", (e: MessageEvent) => {
|
|
29
|
-
const data = JSON.parse(e.data as string);
|
|
30
|
-
messages.push(data);
|
|
31
|
-
|
|
32
|
-
if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
|
|
33
|
-
clearTimeout(timeout);
|
|
34
|
-
resolvePromise(true);
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
const firstMessage: ChatMessage = {
|
|
39
|
-
id: "msg1",
|
|
40
|
-
role: "user",
|
|
41
|
-
parts: [{ type: "text", text: "Hello" }]
|
|
42
|
-
};
|
|
43
|
-
|
|
44
|
-
ws.send(
|
|
45
|
-
JSON.stringify({
|
|
46
|
-
type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
|
|
47
|
-
id: "req1",
|
|
48
|
-
init: {
|
|
49
|
-
method: "POST",
|
|
50
|
-
body: JSON.stringify({ messages: [firstMessage] })
|
|
51
|
-
}
|
|
52
|
-
})
|
|
53
|
-
);
|
|
54
|
-
|
|
55
|
-
const firstDone = await donePromise;
|
|
56
|
-
expect(firstDone).toBe(true);
|
|
57
|
-
|
|
58
|
-
const secondMessage: ChatMessage = {
|
|
59
|
-
id: "msg2",
|
|
60
|
-
role: "user",
|
|
61
|
-
parts: [{ type: "text", text: "How are you?" }]
|
|
62
|
-
};
|
|
63
|
-
|
|
64
|
-
const secondPromise = new Promise<boolean>((res) => {
|
|
65
|
-
resolvePromise = res;
|
|
66
|
-
});
|
|
67
|
-
const timeout2 = setTimeout(() => resolvePromise(false), 2000);
|
|
68
|
-
|
|
69
|
-
ws.addEventListener("message", (e: MessageEvent) => {
|
|
70
|
-
const data = JSON.parse(e.data as string);
|
|
71
|
-
if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
|
|
72
|
-
clearTimeout(timeout2);
|
|
73
|
-
resolvePromise(true);
|
|
74
|
-
}
|
|
75
|
-
});
|
|
76
|
-
|
|
77
|
-
ws.send(
|
|
78
|
-
JSON.stringify({
|
|
79
|
-
type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
|
|
80
|
-
id: "req2",
|
|
81
|
-
init: {
|
|
82
|
-
method: "POST",
|
|
83
|
-
body: JSON.stringify({ messages: [firstMessage, secondMessage] })
|
|
84
|
-
}
|
|
85
|
-
})
|
|
86
|
-
);
|
|
87
|
-
|
|
88
|
-
const secondDone = await secondPromise;
|
|
89
|
-
expect(secondDone).toBe(true);
|
|
90
|
-
|
|
91
|
-
ws.close(1000);
|
|
92
|
-
|
|
93
|
-
const getMessagesReq = new Request(
|
|
94
|
-
`http://example.com/agents/test-chat-agent/${room}/get-messages`
|
|
95
|
-
);
|
|
96
|
-
const getMessagesRes = await worker.fetch(
|
|
97
|
-
getMessagesReq,
|
|
98
|
-
env,
|
|
99
|
-
createExecutionContext()
|
|
100
|
-
);
|
|
101
|
-
expect(getMessagesRes.status).toBe(200);
|
|
102
|
-
|
|
103
|
-
const persistedMessages = (await getMessagesRes.json()) as ChatMessage[];
|
|
104
|
-
expect(persistedMessages.length).toBeGreaterThanOrEqual(4); // 2 user + 2 assistant
|
|
105
|
-
|
|
106
|
-
const userMessages = persistedMessages.filter((m) => m.role === "user");
|
|
107
|
-
expect(userMessages.length).toBe(2);
|
|
108
|
-
expect(userMessages.some((m) => m.id === "msg1")).toBe(true);
|
|
109
|
-
expect(userMessages.some((m) => m.id === "msg2")).toBe(true);
|
|
110
|
-
|
|
111
|
-
const assistantMessages = persistedMessages.filter(
|
|
112
|
-
(m) => m.role === "assistant"
|
|
113
|
-
);
|
|
114
|
-
expect(assistantMessages.length).toBeGreaterThanOrEqual(2);
|
|
115
|
-
|
|
116
|
-
// check that assistant messages have content
|
|
117
|
-
assistantMessages.forEach((msg) => {
|
|
118
|
-
expect(msg.parts).toBeDefined();
|
|
119
|
-
expect(msg.parts.length).toBeGreaterThan(0);
|
|
120
|
-
});
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
it("handles messages incrementally", async () => {
|
|
124
|
-
const room = crypto.randomUUID();
|
|
125
|
-
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
126
|
-
|
|
127
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
128
|
-
|
|
129
|
-
const initialMessages: ChatMessage[] = [
|
|
130
|
-
{ id: "init1", role: "user", parts: [{ type: "text", text: "First" }] },
|
|
131
|
-
{
|
|
132
|
-
id: "init2",
|
|
133
|
-
role: "assistant",
|
|
134
|
-
parts: [{ type: "text", text: "Response" }]
|
|
135
|
-
}
|
|
136
|
-
];
|
|
137
|
-
|
|
138
|
-
ws.send(
|
|
139
|
-
JSON.stringify({
|
|
140
|
-
type: MessageType.CF_AGENT_CHAT_MESSAGES,
|
|
141
|
-
messages: initialMessages
|
|
142
|
-
})
|
|
143
|
-
);
|
|
144
|
-
|
|
145
|
-
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
146
|
-
|
|
147
|
-
const replacementMessages: ChatMessage[] = [
|
|
148
|
-
{
|
|
149
|
-
id: "new1",
|
|
150
|
-
role: "user",
|
|
151
|
-
parts: [{ type: "text", text: "New conversation" }]
|
|
152
|
-
}
|
|
153
|
-
];
|
|
154
|
-
|
|
155
|
-
ws.send(
|
|
156
|
-
JSON.stringify({
|
|
157
|
-
type: MessageType.CF_AGENT_CHAT_MESSAGES,
|
|
158
|
-
messages: replacementMessages
|
|
159
|
-
})
|
|
160
|
-
);
|
|
161
|
-
|
|
162
|
-
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
163
|
-
|
|
164
|
-
ws.close(1000);
|
|
165
|
-
|
|
166
|
-
const getMessagesReq = new Request(
|
|
167
|
-
`http://example.com/agents/test-chat-agent/${room}/get-messages`
|
|
168
|
-
);
|
|
169
|
-
const getMessagesRes = await worker.fetch(
|
|
170
|
-
getMessagesReq,
|
|
171
|
-
env,
|
|
172
|
-
createExecutionContext()
|
|
173
|
-
);
|
|
174
|
-
expect(getMessagesRes.status).toBe(200);
|
|
175
|
-
|
|
176
|
-
const persistedMessages = (await getMessagesRes.json()) as ChatMessage[];
|
|
177
|
-
expect(persistedMessages.length).toBe(3); // init1, init2, new1
|
|
178
|
-
|
|
179
|
-
const messageIds = persistedMessages.map((m) => m.id);
|
|
180
|
-
expect(messageIds).toContain("init1");
|
|
181
|
-
expect(messageIds).toContain("init2");
|
|
182
|
-
expect(messageIds).toContain("new1");
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
it("persists tool calls and updates them with tool outputs", async () => {
|
|
186
|
-
const room = crypto.randomUUID();
|
|
187
|
-
|
|
188
|
-
const ctx = createExecutionContext();
|
|
189
|
-
const req = new Request(
|
|
190
|
-
`http://example.com/agents/test-chat-agent/${room}`,
|
|
191
|
-
{
|
|
192
|
-
headers: { Upgrade: "websocket" }
|
|
193
|
-
}
|
|
194
|
-
);
|
|
195
|
-
const res = await worker.fetch(req, env, ctx);
|
|
196
|
-
expect(res.status).toBe(101);
|
|
197
|
-
const ws = res.webSocket as WebSocket;
|
|
198
|
-
ws.accept();
|
|
199
|
-
|
|
200
|
-
await ctx.waitUntil(Promise.resolve());
|
|
201
|
-
|
|
202
|
-
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
203
|
-
|
|
204
|
-
await agentStub.testPersistToolCall("msg-tool-1", "getLocalTime");
|
|
205
|
-
|
|
206
|
-
const messagesAfterCall =
|
|
207
|
-
(await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
208
|
-
expect(messagesAfterCall.length).toBe(1);
|
|
209
|
-
expect(messagesAfterCall[0].id).toBe("msg-tool-1");
|
|
210
|
-
const toolPart1 = messagesAfterCall[0].parts[0] as {
|
|
211
|
-
type: string;
|
|
212
|
-
state: string;
|
|
213
|
-
toolCallId: string;
|
|
214
|
-
input: unknown;
|
|
215
|
-
};
|
|
216
|
-
expect(toolPart1.type).toBe("tool-getLocalTime");
|
|
217
|
-
expect(toolPart1.state).toBe("input-available");
|
|
218
|
-
expect(toolPart1.input).toEqual({ location: "London" });
|
|
219
|
-
|
|
220
|
-
await agentStub.testPersistToolResult("msg-tool-1", "getLocalTime", "10am");
|
|
221
|
-
|
|
222
|
-
const messagesAfterOutput =
|
|
223
|
-
(await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
224
|
-
|
|
225
|
-
// Should still be only 1 message
|
|
226
|
-
expect(messagesAfterOutput.length).toBe(1);
|
|
227
|
-
expect(messagesAfterOutput[0].id).toBe("msg-tool-1");
|
|
228
|
-
|
|
229
|
-
const toolPart2 = messagesAfterOutput[0].parts[0] as {
|
|
230
|
-
type: string;
|
|
231
|
-
state: string;
|
|
232
|
-
toolCallId: string;
|
|
233
|
-
input: unknown;
|
|
234
|
-
output: unknown;
|
|
235
|
-
};
|
|
236
|
-
expect(toolPart2.type).toBe("tool-getLocalTime");
|
|
237
|
-
expect(toolPart2.state).toBe("output-available");
|
|
238
|
-
expect(toolPart2.output).toBe("10am");
|
|
239
|
-
expect(toolPart2.input).toEqual({ location: "London" });
|
|
240
|
-
|
|
241
|
-
ws.close(1000);
|
|
242
|
-
});
|
|
243
|
-
|
|
244
|
-
it("persists multiple messages with tool calls and outputs correctly", async () => {
|
|
245
|
-
const room = crypto.randomUUID();
|
|
246
|
-
const ctx = createExecutionContext();
|
|
247
|
-
const req = new Request(
|
|
248
|
-
`http://example.com/agents/test-chat-agent/${room}`,
|
|
249
|
-
{
|
|
250
|
-
headers: { Upgrade: "websocket" }
|
|
251
|
-
}
|
|
252
|
-
);
|
|
253
|
-
const res = await worker.fetch(req, env, ctx);
|
|
254
|
-
expect(res.status).toBe(101);
|
|
255
|
-
const ws = res.webSocket as WebSocket;
|
|
256
|
-
ws.accept();
|
|
257
|
-
|
|
258
|
-
await ctx.waitUntil(Promise.resolve());
|
|
259
|
-
|
|
260
|
-
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
261
|
-
|
|
262
|
-
const userMessage: ChatMessage = {
|
|
263
|
-
id: "user-1",
|
|
264
|
-
role: "user",
|
|
265
|
-
parts: [{ type: "text", text: "What time is it in London?" }]
|
|
266
|
-
};
|
|
267
|
-
|
|
268
|
-
const toolCallPart: TestToolCallPart = {
|
|
269
|
-
type: "tool-getLocalTime",
|
|
270
|
-
toolCallId: "call_456",
|
|
271
|
-
state: "input-available",
|
|
272
|
-
input: { location: "London" }
|
|
273
|
-
};
|
|
274
|
-
|
|
275
|
-
const assistantToolCall: ChatMessage = {
|
|
276
|
-
id: "assistant-1",
|
|
277
|
-
role: "assistant",
|
|
278
|
-
parts: [toolCallPart] as ChatMessage["parts"]
|
|
279
|
-
};
|
|
280
|
-
|
|
281
|
-
await agentStub.persistMessages([userMessage, assistantToolCall]);
|
|
282
|
-
|
|
283
|
-
const messagesAfterToolCall =
|
|
284
|
-
(await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
285
|
-
expect(messagesAfterToolCall.length).toBe(2);
|
|
286
|
-
expect(messagesAfterToolCall.find((m) => m.id === "user-1")).toBeDefined();
|
|
287
|
-
expect(
|
|
288
|
-
messagesAfterToolCall.find((m) => m.id === "assistant-1")
|
|
289
|
-
).toBeDefined();
|
|
290
|
-
|
|
291
|
-
const toolResultPart: TestToolCallPart = {
|
|
292
|
-
type: "tool-getLocalTime",
|
|
293
|
-
toolCallId: "call_456",
|
|
294
|
-
state: "output-available",
|
|
295
|
-
input: { location: "London" },
|
|
296
|
-
output: "3:00 PM"
|
|
297
|
-
};
|
|
298
|
-
|
|
299
|
-
const assistantToolOutput: ChatMessage = {
|
|
300
|
-
id: "assistant-1",
|
|
301
|
-
role: "assistant",
|
|
302
|
-
parts: [toolResultPart] as ChatMessage["parts"]
|
|
303
|
-
};
|
|
304
|
-
|
|
305
|
-
const assistantResponse: ChatMessage = {
|
|
306
|
-
id: "assistant-2",
|
|
307
|
-
role: "assistant",
|
|
308
|
-
parts: [{ type: "text", text: "It is 3:00 PM in London." }]
|
|
309
|
-
};
|
|
310
|
-
|
|
311
|
-
await agentStub.persistMessages([
|
|
312
|
-
userMessage,
|
|
313
|
-
assistantToolOutput,
|
|
314
|
-
assistantResponse
|
|
315
|
-
]);
|
|
316
|
-
|
|
317
|
-
const persistedMessages =
|
|
318
|
-
(await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
319
|
-
|
|
320
|
-
// Should have 3 messages: user-1, assistant-1 (with tool output), assistant-2
|
|
321
|
-
expect(persistedMessages.length).toBe(3);
|
|
322
|
-
|
|
323
|
-
const userMsg = persistedMessages.find((m) => m.id === "user-1");
|
|
324
|
-
expect(userMsg).toBeDefined();
|
|
325
|
-
expect(userMsg?.role).toBe("user");
|
|
326
|
-
|
|
327
|
-
// Verify assistant message with tool output (should be updated, not duplicated)
|
|
328
|
-
const assistantWithTool = persistedMessages.find(
|
|
329
|
-
(m) => m.id === "assistant-1"
|
|
330
|
-
);
|
|
331
|
-
expect(assistantWithTool).toBeDefined();
|
|
332
|
-
const toolPart = assistantWithTool?.parts[0] as {
|
|
333
|
-
type: string;
|
|
334
|
-
state: string;
|
|
335
|
-
toolCallId: string;
|
|
336
|
-
input: unknown;
|
|
337
|
-
output: unknown;
|
|
338
|
-
};
|
|
339
|
-
expect(toolPart.type).toBe("tool-getLocalTime");
|
|
340
|
-
expect(toolPart.state).toBe("output-available");
|
|
341
|
-
expect(toolPart.output).toBe("3:00 PM");
|
|
342
|
-
|
|
343
|
-
const finalResponse = persistedMessages.find((m) => m.id === "assistant-2");
|
|
344
|
-
expect(finalResponse).toBeDefined();
|
|
345
|
-
expect(finalResponse?.parts[0].type).toBe("text");
|
|
346
|
-
|
|
347
|
-
ws.close(1000);
|
|
348
|
-
});
|
|
349
|
-
|
|
350
|
-
it("maintains chronological order when tool outputs arrive after the final response", async () => {
|
|
351
|
-
const room = crypto.randomUUID();
|
|
352
|
-
const ctx = createExecutionContext();
|
|
353
|
-
const req = new Request(
|
|
354
|
-
`http://example.com/agents/test-chat-agent/${room}`,
|
|
355
|
-
{
|
|
356
|
-
headers: { Upgrade: "websocket" }
|
|
357
|
-
}
|
|
358
|
-
);
|
|
359
|
-
const res = await worker.fetch(req, env, ctx);
|
|
360
|
-
expect(res.status).toBe(101);
|
|
361
|
-
const ws = res.webSocket as WebSocket;
|
|
362
|
-
ws.accept();
|
|
363
|
-
|
|
364
|
-
await ctx.waitUntil(Promise.resolve());
|
|
365
|
-
|
|
366
|
-
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
367
|
-
|
|
368
|
-
const userMessage: ChatMessage = {
|
|
369
|
-
id: "user-1",
|
|
370
|
-
role: "user",
|
|
371
|
-
parts: [{ type: "text", text: "What time is it?" }]
|
|
372
|
-
};
|
|
373
|
-
|
|
374
|
-
const toolCallPart: TestToolCallPart = {
|
|
375
|
-
type: "tool-getLocalTime",
|
|
376
|
-
toolCallId: "call_123",
|
|
377
|
-
state: "input-available",
|
|
378
|
-
input: { location: "London" }
|
|
379
|
-
};
|
|
380
|
-
|
|
381
|
-
const assistantToolCall: ChatMessage = {
|
|
382
|
-
id: "assistant-1",
|
|
383
|
-
role: "assistant",
|
|
384
|
-
parts: [toolCallPart] as ChatMessage["parts"]
|
|
385
|
-
};
|
|
386
|
-
|
|
387
|
-
const assistantResponse: ChatMessage = {
|
|
388
|
-
id: "assistant-2",
|
|
389
|
-
role: "assistant",
|
|
390
|
-
parts: [{ type: "text", text: "Let me check." }]
|
|
391
|
-
};
|
|
392
|
-
|
|
393
|
-
await agentStub.persistMessages([
|
|
394
|
-
userMessage,
|
|
395
|
-
assistantToolCall,
|
|
396
|
-
assistantResponse
|
|
397
|
-
]);
|
|
398
|
-
|
|
399
|
-
const toolResultPart: TestToolCallPart = {
|
|
400
|
-
type: "tool-getLocalTime",
|
|
401
|
-
toolCallId: "call_123",
|
|
402
|
-
state: "output-available",
|
|
403
|
-
input: { location: "London" },
|
|
404
|
-
output: "3:00 PM"
|
|
405
|
-
};
|
|
406
|
-
|
|
407
|
-
const assistantToolResult: ChatMessage = {
|
|
408
|
-
id: "assistant-1",
|
|
409
|
-
role: "assistant",
|
|
410
|
-
parts: [toolResultPart] as ChatMessage["parts"]
|
|
411
|
-
};
|
|
412
|
-
|
|
413
|
-
await agentStub.persistMessages([assistantToolResult]);
|
|
414
|
-
|
|
415
|
-
const persistedMessages =
|
|
416
|
-
(await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
417
|
-
|
|
418
|
-
expect(persistedMessages.map((m) => m.id)).toEqual([
|
|
419
|
-
"user-1",
|
|
420
|
-
"assistant-1",
|
|
421
|
-
"assistant-2"
|
|
422
|
-
]);
|
|
423
|
-
|
|
424
|
-
ws.close(1000);
|
|
425
|
-
});
|
|
426
|
-
});
|
|
@@ -1,132 +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("Clear History", () => {
|
|
9
|
-
it("clears all messages, stream data, and broadcasts to other connections", async () => {
|
|
10
|
-
const room = crypto.randomUUID();
|
|
11
|
-
const { ws: ws1 } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
12
|
-
const { ws: ws2 } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
13
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
14
|
-
|
|
15
|
-
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
16
|
-
|
|
17
|
-
// Persist some messages
|
|
18
|
-
const messages: ChatMessage[] = [
|
|
19
|
-
{
|
|
20
|
-
id: "clear-1",
|
|
21
|
-
role: "user",
|
|
22
|
-
parts: [{ type: "text", text: "Hello" }]
|
|
23
|
-
},
|
|
24
|
-
{
|
|
25
|
-
id: "clear-2",
|
|
26
|
-
role: "assistant",
|
|
27
|
-
parts: [{ type: "text", text: "Hi" }]
|
|
28
|
-
}
|
|
29
|
-
];
|
|
30
|
-
await agentStub.persistMessages(messages);
|
|
31
|
-
|
|
32
|
-
// Also create some stream data
|
|
33
|
-
const streamId = await agentStub.testStartStream("req-clear-test");
|
|
34
|
-
await agentStub.testStoreStreamChunk(
|
|
35
|
-
streamId,
|
|
36
|
-
'{"type":"text","text":"stream-data"}'
|
|
37
|
-
);
|
|
38
|
-
await agentStub.testFlushChunkBuffer();
|
|
39
|
-
|
|
40
|
-
// Verify data exists before clear
|
|
41
|
-
const beforeMessages = await agentStub.getPersistedMessages();
|
|
42
|
-
expect((beforeMessages as ChatMessage[]).length).toBe(2);
|
|
43
|
-
const beforeChunks = await agentStub.getStreamChunks(streamId);
|
|
44
|
-
expect(beforeChunks.length).toBe(1);
|
|
45
|
-
|
|
46
|
-
// Listen for clear broadcast on ws2
|
|
47
|
-
let ws2ReceivedClear = false;
|
|
48
|
-
ws2.addEventListener("message", (e: MessageEvent) => {
|
|
49
|
-
const data = JSON.parse(e.data as string);
|
|
50
|
-
if (data.type === MessageType.CF_AGENT_CHAT_CLEAR) {
|
|
51
|
-
ws2ReceivedClear = true;
|
|
52
|
-
}
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
// Clear via ws1
|
|
56
|
-
ws1.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
|
|
57
|
-
|
|
58
|
-
await new Promise((r) => setTimeout(r, 100));
|
|
59
|
-
|
|
60
|
-
// Messages should be cleared
|
|
61
|
-
const afterMessages = await agentStub.getPersistedMessages();
|
|
62
|
-
expect((afterMessages as ChatMessage[]).length).toBe(0);
|
|
63
|
-
|
|
64
|
-
// Stream data should be cleared
|
|
65
|
-
const afterChunks = await agentStub.getStreamChunks(streamId);
|
|
66
|
-
expect(afterChunks.length).toBe(0);
|
|
67
|
-
const afterMeta = await agentStub.getStreamMetadata(streamId);
|
|
68
|
-
expect(afterMeta).toBeNull();
|
|
69
|
-
|
|
70
|
-
// Active stream state should be cleared
|
|
71
|
-
expect(await agentStub.getActiveStreamId()).toBeNull();
|
|
72
|
-
expect(await agentStub.getActiveRequestId()).toBeNull();
|
|
73
|
-
|
|
74
|
-
// ws2 should have received the clear broadcast
|
|
75
|
-
expect(ws2ReceivedClear).toBe(true);
|
|
76
|
-
|
|
77
|
-
ws1.close();
|
|
78
|
-
ws2.close(1000);
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
it("resets abort controllers when clearing history", async () => {
|
|
82
|
-
const room = crypto.randomUUID();
|
|
83
|
-
const { ws } = await connectChatWS(`/agents/test-chat-agent/${room}`);
|
|
84
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
85
|
-
|
|
86
|
-
// Start a request
|
|
87
|
-
const userMessage: ChatMessage = {
|
|
88
|
-
id: "msg-abort-1",
|
|
89
|
-
role: "user",
|
|
90
|
-
parts: [{ type: "text", text: "Hello" }]
|
|
91
|
-
};
|
|
92
|
-
|
|
93
|
-
let resolvePromise: (value: boolean) => void;
|
|
94
|
-
const donePromise = new Promise<boolean>((res) => {
|
|
95
|
-
resolvePromise = res;
|
|
96
|
-
});
|
|
97
|
-
const timeout = setTimeout(() => resolvePromise(false), 2000);
|
|
98
|
-
|
|
99
|
-
ws.addEventListener("message", (e: MessageEvent) => {
|
|
100
|
-
const data = JSON.parse(e.data as string);
|
|
101
|
-
if (data.type === MessageType.CF_AGENT_USE_CHAT_RESPONSE && data.done) {
|
|
102
|
-
clearTimeout(timeout);
|
|
103
|
-
resolvePromise(true);
|
|
104
|
-
}
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
ws.send(
|
|
108
|
-
JSON.stringify({
|
|
109
|
-
type: MessageType.CF_AGENT_USE_CHAT_REQUEST,
|
|
110
|
-
id: "req-abort-1",
|
|
111
|
-
init: {
|
|
112
|
-
method: "POST",
|
|
113
|
-
body: JSON.stringify({ messages: [userMessage] })
|
|
114
|
-
}
|
|
115
|
-
})
|
|
116
|
-
);
|
|
117
|
-
|
|
118
|
-
await donePromise;
|
|
119
|
-
|
|
120
|
-
// Clear should not throw even with prior requests
|
|
121
|
-
ws.send(JSON.stringify({ type: MessageType.CF_AGENT_CHAT_CLEAR }));
|
|
122
|
-
|
|
123
|
-
await new Promise((r) => setTimeout(r, 100));
|
|
124
|
-
|
|
125
|
-
// Agent should be in clean state
|
|
126
|
-
const agentStub = await getAgentByName(env.TestChatAgent, room);
|
|
127
|
-
const afterMessages = await agentStub.getPersistedMessages();
|
|
128
|
-
expect((afterMessages as ChatMessage[]).length).toBe(0);
|
|
129
|
-
|
|
130
|
-
ws.close(1000);
|
|
131
|
-
});
|
|
132
|
-
});
|