@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.
- package/CHANGELOG.md +97 -0
- package/README.md +225 -459
- package/dist/ai-chat-v5-migration.d.ts +9 -9
- package/dist/ai-chat-v5-migration.js +25 -4
- package/dist/ai-chat-v5-migration.js.map +1 -1
- package/dist/experimental/forever.d.ts +29 -0
- package/dist/experimental/forever.js +55 -0
- package/dist/experimental/forever.js.map +1 -0
- package/dist/index.d.ts +114 -76
- package/dist/index.js +745 -629
- package/dist/index.js.map +1 -1
- package/dist/message-builder-Bwc_Umye.js +231 -0
- package/dist/message-builder-Bwc_Umye.js.map +1 -0
- package/dist/react.d.ts +27 -9
- package/dist/react.js +244 -258
- package/dist/react.js.map +1 -1
- package/dist/resumable-stream-DqXxQVjf.d.ts +103 -0
- package/dist/types.d.ts +16 -4
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -1
- package/e2e/chat.spec.ts +1703 -0
- package/e2e/client-tools.spec.ts +504 -0
- package/e2e/llm.spec.ts +637 -0
- package/e2e/playwright.config.ts +24 -0
- package/e2e/worker.ts +176 -0
- package/e2e/wrangler.jsonc +23 -0
- package/package.json +13 -5
- package/scripts/build.ts +2 -1
- package/src/ai-chat-v5-migration.ts +32 -5
- package/src/experimental/forever.ts +66 -0
- package/src/index.ts +831 -1137
- package/src/message-builder.ts +384 -0
- package/src/react-tests/use-agent-chat.test.tsx +738 -2
- package/src/react.tsx +385 -461
- package/src/resumable-stream.ts +441 -0
- package/src/tests/chat-context.test.ts +1 -1
- package/src/tests/chat-persistence.test.ts +5 -5
- package/src/tests/clear-history.test.ts +132 -0
- package/src/tests/client-tool-duplicate-message.test.ts +457 -14
- package/src/tests/client-tools-broadcast.test.ts +2 -2
- package/src/tests/client-tools-continuation.test.ts +3 -3
- package/src/tests/client-tools-reconnect.test.ts +143 -0
- package/src/tests/custom-body-continuation.test.ts +309 -0
- package/src/tests/custom-body.test.ts +3 -3
- package/src/tests/destroy.test.ts +57 -0
- package/src/tests/get-messages-endpoint.test.ts +79 -0
- package/src/tests/max-persisted-messages.test.ts +201 -0
- package/src/tests/merge-server-state.test.ts +106 -0
- package/src/tests/message-builder.test.ts +808 -0
- package/src/tests/migration.test.ts +282 -0
- package/src/tests/non-sse-response.test.ts +2 -2
- package/src/tests/onfinish-cleanup.test.ts +362 -0
- package/src/tests/plaintext-response.test.ts +87 -0
- package/src/tests/resumable-streaming.test.ts +220 -14
- package/src/tests/row-size-guard.test.ts +374 -0
- package/src/tests/sanitize-messages.test.ts +215 -0
- package/src/tests/validate-messages.test.ts +269 -0
- package/src/tests/worker.ts +59 -24
- package/src/types.ts +17 -1
- package/src/ws-chat-transport.ts +203 -0
|
@@ -3,6 +3,11 @@ import { getAgentByName } from "agents";
|
|
|
3
3
|
import { describe, it, expect } from "vitest";
|
|
4
4
|
import worker from "./worker";
|
|
5
5
|
import type { UIMessage as ChatMessage } from "ai";
|
|
6
|
+
import {
|
|
7
|
+
applyChunkToParts,
|
|
8
|
+
type MessageParts,
|
|
9
|
+
type StreamChunkData
|
|
10
|
+
} from "../message-builder";
|
|
6
11
|
|
|
7
12
|
describe("Client-side tool duplicate message prevention", () => {
|
|
8
13
|
it("merges tool output into existing message by toolCallId", async () => {
|
|
@@ -76,7 +81,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
76
81
|
expect(toolPart.state).toBe("output-available");
|
|
77
82
|
expect(toolPart.output).toBe("result");
|
|
78
83
|
|
|
79
|
-
ws.close();
|
|
84
|
+
ws.close(1000);
|
|
80
85
|
});
|
|
81
86
|
|
|
82
87
|
it("CF_AGENT_TOOL_RESULT applies tool result without auto-continuation by default", async () => {
|
|
@@ -149,7 +154,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
149
154
|
// No continuation parts (only the original tool part)
|
|
150
155
|
expect(assistantMsg.parts.length).toBe(1);
|
|
151
156
|
|
|
152
|
-
ws.close();
|
|
157
|
+
ws.close(1000);
|
|
153
158
|
});
|
|
154
159
|
|
|
155
160
|
it("CF_AGENT_TOOL_RESULT auto-continues and merges when autoContinue is true", async () => {
|
|
@@ -224,7 +229,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
224
229
|
// Continuation parts should be appended (TestChatAgent returns text response)
|
|
225
230
|
expect(assistantMsg.parts.length).toBeGreaterThan(1);
|
|
226
231
|
|
|
227
|
-
ws.close();
|
|
232
|
+
ws.close(1000);
|
|
228
233
|
});
|
|
229
234
|
|
|
230
235
|
it("strips OpenAI itemIds from persisted messages to prevent duplicate errors", async () => {
|
|
@@ -284,7 +289,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
284
289
|
expect(textPart.text).toBe("Hello! How can I help?");
|
|
285
290
|
expect(textPart.providerMetadata?.openai?.itemId).toBeUndefined();
|
|
286
291
|
|
|
287
|
-
ws.close();
|
|
292
|
+
ws.close(1000);
|
|
288
293
|
});
|
|
289
294
|
|
|
290
295
|
it("strips OpenAI itemIds from tool parts with callProviderMetadata", async () => {
|
|
@@ -347,7 +352,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
347
352
|
expect(toolPart.toolCallId).toBe(toolCallId);
|
|
348
353
|
expect(toolPart.callProviderMetadata?.openai?.itemId).toBeUndefined();
|
|
349
354
|
|
|
350
|
-
ws.close();
|
|
355
|
+
ws.close(1000);
|
|
351
356
|
});
|
|
352
357
|
|
|
353
358
|
it("preserves other providerMetadata when stripping itemId", async () => {
|
|
@@ -418,7 +423,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
418
423
|
"also_keep_me"
|
|
419
424
|
);
|
|
420
425
|
|
|
421
|
-
ws.close();
|
|
426
|
+
ws.close(1000);
|
|
422
427
|
});
|
|
423
428
|
|
|
424
429
|
it("filters out empty reasoning parts to prevent AI SDK warnings", async () => {
|
|
@@ -472,7 +477,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
472
477
|
expect(assistantMessage!.parts.length).toBe(1);
|
|
473
478
|
expect(assistantMessage!.parts[0].type).toBe("text");
|
|
474
479
|
|
|
475
|
-
ws.close();
|
|
480
|
+
ws.close(1000);
|
|
476
481
|
});
|
|
477
482
|
|
|
478
483
|
it("preserves non-empty reasoning parts", async () => {
|
|
@@ -539,7 +544,7 @@ describe("Client-side tool duplicate message prevention", () => {
|
|
|
539
544
|
// itemId should still be stripped
|
|
540
545
|
expect(reasoningPart.providerMetadata?.openai?.itemId).toBeUndefined();
|
|
541
546
|
|
|
542
|
-
ws.close();
|
|
547
|
+
ws.close(1000);
|
|
543
548
|
});
|
|
544
549
|
});
|
|
545
550
|
|
|
@@ -610,7 +615,7 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
|
|
|
610
615
|
expect(toolPart.state).toBe("approval-responded");
|
|
611
616
|
expect(toolPart.approval).toEqual({ approved: true });
|
|
612
617
|
|
|
613
|
-
ws.close();
|
|
618
|
+
ws.close(1000);
|
|
614
619
|
});
|
|
615
620
|
|
|
616
621
|
it("CF_AGENT_TOOL_APPROVAL handles rejection (approved: false)", async () => {
|
|
@@ -673,7 +678,7 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
|
|
|
673
678
|
expect(toolPart.state).toBe("approval-responded");
|
|
674
679
|
expect(toolPart.approval).toEqual({ approved: false });
|
|
675
680
|
|
|
676
|
-
ws.close();
|
|
681
|
+
ws.close(1000);
|
|
677
682
|
});
|
|
678
683
|
|
|
679
684
|
it("CF_AGENT_TOOL_APPROVAL updates tool in approval-requested state", async () => {
|
|
@@ -735,9 +740,10 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
|
|
|
735
740
|
approval?: { approved: boolean };
|
|
736
741
|
};
|
|
737
742
|
expect(toolPart.state).toBe("approval-responded");
|
|
738
|
-
|
|
743
|
+
// approval.id is preserved from the approval-requested state
|
|
744
|
+
expect(toolPart.approval).toEqual({ id: "approval-123", approved: true });
|
|
739
745
|
|
|
740
|
-
ws.close();
|
|
746
|
+
ws.close(1000);
|
|
741
747
|
});
|
|
742
748
|
|
|
743
749
|
it("CF_AGENT_TOOL_APPROVAL with non-existent toolCallId logs warning", async () => {
|
|
@@ -787,7 +793,7 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
|
|
|
787
793
|
const assistantMsg = messages.find((m) => m.role === "assistant");
|
|
788
794
|
expect(assistantMsg?.parts[0]).toEqual({ type: "text", text: "Hi there!" });
|
|
789
795
|
|
|
790
|
-
ws.close();
|
|
796
|
+
ws.close(1000);
|
|
791
797
|
});
|
|
792
798
|
|
|
793
799
|
it("CF_AGENT_TOOL_APPROVAL does not update tool already in output-available state", async () => {
|
|
@@ -852,6 +858,443 @@ describe("Tool approval (needsApproval) duplicate message prevention", () => {
|
|
|
852
858
|
expect(toolPart.state).toBe("output-available");
|
|
853
859
|
expect(toolPart.output).toEqual({ result: "done" });
|
|
854
860
|
|
|
855
|
-
ws.close();
|
|
861
|
+
ws.close(1000);
|
|
862
|
+
});
|
|
863
|
+
});
|
|
864
|
+
|
|
865
|
+
describe("Tool approval auto-continuation (needsApproval)", () => {
|
|
866
|
+
it("CF_AGENT_TOOL_APPROVAL without autoContinue does NOT trigger continuation", async () => {
|
|
867
|
+
const room = crypto.randomUUID();
|
|
868
|
+
const ctx = createExecutionContext();
|
|
869
|
+
const req = new Request(
|
|
870
|
+
`http://example.com/agents/test-chat-agent/${room}`,
|
|
871
|
+
{ headers: { Upgrade: "websocket" } }
|
|
872
|
+
);
|
|
873
|
+
const res = await worker.fetch(req, env, ctx);
|
|
874
|
+
expect(res.status).toBe(101);
|
|
875
|
+
const ws = res.webSocket as WebSocket;
|
|
876
|
+
ws.accept();
|
|
877
|
+
await ctx.waitUntil(Promise.resolve());
|
|
878
|
+
|
|
879
|
+
const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
|
|
880
|
+
const toolCallId = "call_no_auto_continue";
|
|
881
|
+
|
|
882
|
+
// Persist assistant message with tool in input-available state
|
|
883
|
+
await agentStub.persistMessages([
|
|
884
|
+
{
|
|
885
|
+
id: "user-1",
|
|
886
|
+
role: "user",
|
|
887
|
+
parts: [{ type: "text", text: "Execute tool" }]
|
|
888
|
+
},
|
|
889
|
+
{
|
|
890
|
+
id: "assistant-1",
|
|
891
|
+
role: "assistant",
|
|
892
|
+
parts: [
|
|
893
|
+
{
|
|
894
|
+
type: "tool-testTool",
|
|
895
|
+
toolCallId,
|
|
896
|
+
state: "input-available",
|
|
897
|
+
input: { param: "value" }
|
|
898
|
+
}
|
|
899
|
+
] as ChatMessage["parts"]
|
|
900
|
+
}
|
|
901
|
+
]);
|
|
902
|
+
|
|
903
|
+
// Send approval WITHOUT autoContinue
|
|
904
|
+
ws.send(
|
|
905
|
+
JSON.stringify({
|
|
906
|
+
type: "cf_agent_tool_approval",
|
|
907
|
+
toolCallId,
|
|
908
|
+
approved: true
|
|
909
|
+
// no autoContinue
|
|
910
|
+
})
|
|
911
|
+
);
|
|
912
|
+
|
|
913
|
+
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
914
|
+
|
|
915
|
+
const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
916
|
+
const assistantMessages = messages.filter((m) => m.role === "assistant");
|
|
917
|
+
|
|
918
|
+
// Should have exactly 1 assistant message (no continuation)
|
|
919
|
+
expect(assistantMessages.length).toBe(1);
|
|
920
|
+
|
|
921
|
+
const assistantMsg = assistantMessages[0];
|
|
922
|
+
expect(assistantMsg.id).toBe("assistant-1");
|
|
923
|
+
|
|
924
|
+
// Tool state should be approval-responded but no continuation parts
|
|
925
|
+
const toolPart = assistantMsg.parts[0] as {
|
|
926
|
+
state: string;
|
|
927
|
+
approval?: { approved: boolean };
|
|
928
|
+
};
|
|
929
|
+
expect(toolPart.state).toBe("approval-responded");
|
|
930
|
+
expect(toolPart.approval).toEqual({ approved: true });
|
|
931
|
+
expect(assistantMsg.parts.length).toBe(1);
|
|
932
|
+
|
|
933
|
+
ws.close(1000);
|
|
934
|
+
});
|
|
935
|
+
|
|
936
|
+
it("CF_AGENT_TOOL_APPROVAL with autoContinue triggers continuation", async () => {
|
|
937
|
+
const room = crypto.randomUUID();
|
|
938
|
+
const ctx = createExecutionContext();
|
|
939
|
+
const req = new Request(
|
|
940
|
+
`http://example.com/agents/test-chat-agent/${room}`,
|
|
941
|
+
{ headers: { Upgrade: "websocket" } }
|
|
942
|
+
);
|
|
943
|
+
const res = await worker.fetch(req, env, ctx);
|
|
944
|
+
expect(res.status).toBe(101);
|
|
945
|
+
const ws = res.webSocket as WebSocket;
|
|
946
|
+
ws.accept();
|
|
947
|
+
await ctx.waitUntil(Promise.resolve());
|
|
948
|
+
|
|
949
|
+
const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
|
|
950
|
+
const toolCallId = "call_auto_continue_approval";
|
|
951
|
+
|
|
952
|
+
// Persist assistant message with tool in input-available state
|
|
953
|
+
await agentStub.persistMessages([
|
|
954
|
+
{
|
|
955
|
+
id: "user-1",
|
|
956
|
+
role: "user",
|
|
957
|
+
parts: [{ type: "text", text: "Execute tool" }]
|
|
958
|
+
},
|
|
959
|
+
{
|
|
960
|
+
id: "assistant-1",
|
|
961
|
+
role: "assistant",
|
|
962
|
+
parts: [
|
|
963
|
+
{
|
|
964
|
+
type: "tool-testTool",
|
|
965
|
+
toolCallId,
|
|
966
|
+
state: "input-available",
|
|
967
|
+
input: { param: "value" }
|
|
968
|
+
}
|
|
969
|
+
] as ChatMessage["parts"]
|
|
970
|
+
}
|
|
971
|
+
]);
|
|
972
|
+
|
|
973
|
+
// Send approval WITH autoContinue: true
|
|
974
|
+
ws.send(
|
|
975
|
+
JSON.stringify({
|
|
976
|
+
type: "cf_agent_tool_approval",
|
|
977
|
+
toolCallId,
|
|
978
|
+
approved: true,
|
|
979
|
+
autoContinue: true
|
|
980
|
+
})
|
|
981
|
+
);
|
|
982
|
+
|
|
983
|
+
// Wait for approval + continuation (500ms wait + stream)
|
|
984
|
+
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
985
|
+
|
|
986
|
+
const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
987
|
+
const assistantMessages = messages.filter((m) => m.role === "assistant");
|
|
988
|
+
|
|
989
|
+
// Should still have 1 assistant message (continuation merged into it)
|
|
990
|
+
expect(assistantMessages.length).toBe(1);
|
|
991
|
+
|
|
992
|
+
const assistantMsg = assistantMessages[0];
|
|
993
|
+
expect(assistantMsg.id).toBe("assistant-1");
|
|
994
|
+
|
|
995
|
+
// First part should be the approved tool
|
|
996
|
+
const toolPart = assistantMsg.parts[0] as {
|
|
997
|
+
state: string;
|
|
998
|
+
approval?: { approved: boolean };
|
|
999
|
+
};
|
|
1000
|
+
expect(toolPart.state).toBe("approval-responded");
|
|
1001
|
+
expect(toolPart.approval).toEqual({ approved: true });
|
|
1002
|
+
|
|
1003
|
+
// Continuation parts should be appended (TestChatAgent returns text response)
|
|
1004
|
+
expect(assistantMsg.parts.length).toBeGreaterThan(1);
|
|
1005
|
+
|
|
1006
|
+
ws.close(1000);
|
|
1007
|
+
});
|
|
1008
|
+
|
|
1009
|
+
it("CF_AGENT_TOOL_APPROVAL with approved: false and autoContinue does NOT continue", async () => {
|
|
1010
|
+
const room = crypto.randomUUID();
|
|
1011
|
+
const ctx = createExecutionContext();
|
|
1012
|
+
const req = new Request(
|
|
1013
|
+
`http://example.com/agents/test-chat-agent/${room}`,
|
|
1014
|
+
{ headers: { Upgrade: "websocket" } }
|
|
1015
|
+
);
|
|
1016
|
+
const res = await worker.fetch(req, env, ctx);
|
|
1017
|
+
expect(res.status).toBe(101);
|
|
1018
|
+
const ws = res.webSocket as WebSocket;
|
|
1019
|
+
ws.accept();
|
|
1020
|
+
await ctx.waitUntil(Promise.resolve());
|
|
1021
|
+
|
|
1022
|
+
const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
|
|
1023
|
+
const toolCallId = "call_rejected_no_continue";
|
|
1024
|
+
|
|
1025
|
+
// Persist assistant message with tool in input-available state
|
|
1026
|
+
await agentStub.persistMessages([
|
|
1027
|
+
{
|
|
1028
|
+
id: "user-1",
|
|
1029
|
+
role: "user",
|
|
1030
|
+
parts: [{ type: "text", text: "Execute tool" }]
|
|
1031
|
+
},
|
|
1032
|
+
{
|
|
1033
|
+
id: "assistant-1",
|
|
1034
|
+
role: "assistant",
|
|
1035
|
+
parts: [
|
|
1036
|
+
{
|
|
1037
|
+
type: "tool-testTool",
|
|
1038
|
+
toolCallId,
|
|
1039
|
+
state: "input-available",
|
|
1040
|
+
input: { param: "value" }
|
|
1041
|
+
}
|
|
1042
|
+
] as ChatMessage["parts"]
|
|
1043
|
+
}
|
|
1044
|
+
]);
|
|
1045
|
+
|
|
1046
|
+
// Send rejection with autoContinue: true — should NOT continue
|
|
1047
|
+
ws.send(
|
|
1048
|
+
JSON.stringify({
|
|
1049
|
+
type: "cf_agent_tool_approval",
|
|
1050
|
+
toolCallId,
|
|
1051
|
+
approved: false,
|
|
1052
|
+
autoContinue: true
|
|
1053
|
+
})
|
|
1054
|
+
);
|
|
1055
|
+
|
|
1056
|
+
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
1057
|
+
|
|
1058
|
+
const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
1059
|
+
const assistantMessages = messages.filter((m) => m.role === "assistant");
|
|
1060
|
+
|
|
1061
|
+
// Should have 1 assistant message, no continuation
|
|
1062
|
+
expect(assistantMessages.length).toBe(1);
|
|
1063
|
+
|
|
1064
|
+
const assistantMsg = assistantMessages[0];
|
|
1065
|
+
const toolPart = assistantMsg.parts[0] as {
|
|
1066
|
+
state: string;
|
|
1067
|
+
approval?: { approved: boolean };
|
|
1068
|
+
};
|
|
1069
|
+
expect(toolPart.state).toBe("approval-responded");
|
|
1070
|
+
expect(toolPart.approval).toEqual({ approved: false });
|
|
1071
|
+
|
|
1072
|
+
// No continuation parts
|
|
1073
|
+
expect(assistantMsg.parts.length).toBe(1);
|
|
1074
|
+
|
|
1075
|
+
ws.close(1000);
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
it("CF_AGENT_TOOL_APPROVAL with autoContinue on approval-requested state triggers continuation", async () => {
|
|
1079
|
+
const room = crypto.randomUUID();
|
|
1080
|
+
const ctx = createExecutionContext();
|
|
1081
|
+
const req = new Request(
|
|
1082
|
+
`http://example.com/agents/test-chat-agent/${room}`,
|
|
1083
|
+
{ headers: { Upgrade: "websocket" } }
|
|
1084
|
+
);
|
|
1085
|
+
const res = await worker.fetch(req, env, ctx);
|
|
1086
|
+
expect(res.status).toBe(101);
|
|
1087
|
+
const ws = res.webSocket as WebSocket;
|
|
1088
|
+
ws.accept();
|
|
1089
|
+
await ctx.waitUntil(Promise.resolve());
|
|
1090
|
+
|
|
1091
|
+
const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
|
|
1092
|
+
const toolCallId = "call_approval_requested_continue";
|
|
1093
|
+
|
|
1094
|
+
// Persist assistant message with tool in approval-requested state
|
|
1095
|
+
await agentStub.persistMessages([
|
|
1096
|
+
{
|
|
1097
|
+
id: "user-1",
|
|
1098
|
+
role: "user",
|
|
1099
|
+
parts: [{ type: "text", text: "Execute tool" }]
|
|
1100
|
+
},
|
|
1101
|
+
{
|
|
1102
|
+
id: "assistant-1",
|
|
1103
|
+
role: "assistant",
|
|
1104
|
+
parts: [
|
|
1105
|
+
{
|
|
1106
|
+
type: "tool-testTool",
|
|
1107
|
+
toolCallId,
|
|
1108
|
+
state: "approval-requested",
|
|
1109
|
+
input: { param: "value" },
|
|
1110
|
+
approval: { id: "approval-456" }
|
|
1111
|
+
}
|
|
1112
|
+
] as ChatMessage["parts"]
|
|
1113
|
+
}
|
|
1114
|
+
]);
|
|
1115
|
+
|
|
1116
|
+
// Send approval with autoContinue
|
|
1117
|
+
ws.send(
|
|
1118
|
+
JSON.stringify({
|
|
1119
|
+
type: "cf_agent_tool_approval",
|
|
1120
|
+
toolCallId,
|
|
1121
|
+
approved: true,
|
|
1122
|
+
autoContinue: true
|
|
1123
|
+
})
|
|
1124
|
+
);
|
|
1125
|
+
|
|
1126
|
+
await new Promise((resolve) => setTimeout(resolve, 800));
|
|
1127
|
+
|
|
1128
|
+
const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
1129
|
+
const assistantMessages = messages.filter((m) => m.role === "assistant");
|
|
1130
|
+
|
|
1131
|
+
expect(assistantMessages.length).toBe(1);
|
|
1132
|
+
|
|
1133
|
+
const assistantMsg = assistantMessages[0];
|
|
1134
|
+
|
|
1135
|
+
// Tool part should be updated
|
|
1136
|
+
const toolPart = assistantMsg.parts[0] as {
|
|
1137
|
+
state: string;
|
|
1138
|
+
approval?: { approved: boolean };
|
|
1139
|
+
};
|
|
1140
|
+
expect(toolPart.state).toBe("approval-responded");
|
|
1141
|
+
expect(toolPart.approval).toEqual({ id: "approval-456", approved: true });
|
|
1142
|
+
|
|
1143
|
+
// Continuation should have appended parts
|
|
1144
|
+
expect(assistantMsg.parts.length).toBeGreaterThan(1);
|
|
1145
|
+
|
|
1146
|
+
ws.close(1000);
|
|
1147
|
+
});
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
describe("applyChunkToParts: tool-approval-request", () => {
|
|
1151
|
+
it("transitions tool part from input-available to approval-requested", () => {
|
|
1152
|
+
const parts: MessageParts = [
|
|
1153
|
+
{
|
|
1154
|
+
type: "tool-calculate",
|
|
1155
|
+
toolCallId: "call_123",
|
|
1156
|
+
toolName: "calculate",
|
|
1157
|
+
state: "input-available",
|
|
1158
|
+
input: { a: 5000, b: 3, operator: "*" }
|
|
1159
|
+
} as MessageParts[number]
|
|
1160
|
+
];
|
|
1161
|
+
|
|
1162
|
+
const handled = applyChunkToParts(parts, {
|
|
1163
|
+
type: "tool-approval-request",
|
|
1164
|
+
approvalId: "approval-abc",
|
|
1165
|
+
toolCallId: "call_123"
|
|
1166
|
+
} as StreamChunkData);
|
|
1167
|
+
|
|
1168
|
+
expect(handled).toBe(true);
|
|
1169
|
+
const part = parts[0] as Record<string, unknown>;
|
|
1170
|
+
expect(part.state).toBe("approval-requested");
|
|
1171
|
+
expect(part.approval).toEqual({ id: "approval-abc" });
|
|
1172
|
+
// Input should be preserved
|
|
1173
|
+
expect(part.input).toEqual({ a: 5000, b: 3, operator: "*" });
|
|
1174
|
+
});
|
|
1175
|
+
|
|
1176
|
+
it("does nothing if tool part not found", () => {
|
|
1177
|
+
const parts: MessageParts = [];
|
|
1178
|
+
|
|
1179
|
+
const handled = applyChunkToParts(parts, {
|
|
1180
|
+
type: "tool-approval-request",
|
|
1181
|
+
approvalId: "approval-abc",
|
|
1182
|
+
toolCallId: "call_nonexistent"
|
|
1183
|
+
} as StreamChunkData);
|
|
1184
|
+
|
|
1185
|
+
expect(handled).toBe(true);
|
|
1186
|
+
expect(parts.length).toBe(0);
|
|
1187
|
+
});
|
|
1188
|
+
});
|
|
1189
|
+
|
|
1190
|
+
describe("applyChunkToParts: tool-output-denied", () => {
|
|
1191
|
+
it("transitions tool part to output-denied state", () => {
|
|
1192
|
+
const parts: MessageParts = [
|
|
1193
|
+
{
|
|
1194
|
+
type: "tool-calculate",
|
|
1195
|
+
toolCallId: "call_456",
|
|
1196
|
+
toolName: "calculate",
|
|
1197
|
+
state: "approval-requested",
|
|
1198
|
+
input: { a: 5000, b: 3, operator: "*" },
|
|
1199
|
+
approval: { id: "approval-xyz" }
|
|
1200
|
+
} as MessageParts[number]
|
|
1201
|
+
];
|
|
1202
|
+
|
|
1203
|
+
const handled = applyChunkToParts(parts, {
|
|
1204
|
+
type: "tool-output-denied",
|
|
1205
|
+
toolCallId: "call_456"
|
|
1206
|
+
} as StreamChunkData);
|
|
1207
|
+
|
|
1208
|
+
expect(handled).toBe(true);
|
|
1209
|
+
const part = parts[0] as Record<string, unknown>;
|
|
1210
|
+
expect(part.state).toBe("output-denied");
|
|
1211
|
+
// Input and approval should be preserved
|
|
1212
|
+
expect(part.input).toEqual({ a: 5000, b: 3, operator: "*" });
|
|
1213
|
+
expect(part.approval).toEqual({ id: "approval-xyz" });
|
|
1214
|
+
});
|
|
1215
|
+
});
|
|
1216
|
+
|
|
1217
|
+
describe("Tool approval persistence across reconnect", () => {
|
|
1218
|
+
it("persisted messages include approval-requested state after approval-request chunk", async () => {
|
|
1219
|
+
const room = crypto.randomUUID();
|
|
1220
|
+
const ctx = createExecutionContext();
|
|
1221
|
+
const req = new Request(
|
|
1222
|
+
`http://example.com/agents/test-chat-agent/${room}`,
|
|
1223
|
+
{ headers: { Upgrade: "websocket" } }
|
|
1224
|
+
);
|
|
1225
|
+
const res = await worker.fetch(req, env, ctx);
|
|
1226
|
+
expect(res.status).toBe(101);
|
|
1227
|
+
const ws = res.webSocket as WebSocket;
|
|
1228
|
+
ws.accept();
|
|
1229
|
+
await ctx.waitUntil(Promise.resolve());
|
|
1230
|
+
|
|
1231
|
+
const agentStub = env.TestChatAgent.get(env.TestChatAgent.idFromName(room));
|
|
1232
|
+
const toolCallId = "call_persist_approval_test";
|
|
1233
|
+
|
|
1234
|
+
// Manually persist messages that simulate the state after
|
|
1235
|
+
// a tool-approval-request was received and early-persisted.
|
|
1236
|
+
// In a real flow, the streaming handler would do this.
|
|
1237
|
+
await agentStub.persistMessages([
|
|
1238
|
+
{
|
|
1239
|
+
id: "user-1",
|
|
1240
|
+
role: "user",
|
|
1241
|
+
parts: [{ type: "text", text: "Calculate 5000 * 3" }]
|
|
1242
|
+
},
|
|
1243
|
+
{
|
|
1244
|
+
id: "assistant-1",
|
|
1245
|
+
role: "assistant",
|
|
1246
|
+
parts: [
|
|
1247
|
+
{
|
|
1248
|
+
type: "tool-calculate",
|
|
1249
|
+
toolCallId,
|
|
1250
|
+
state: "approval-requested",
|
|
1251
|
+
input: { a: 5000, b: 3, operator: "*" },
|
|
1252
|
+
approval: { id: "approval-persist-test" }
|
|
1253
|
+
}
|
|
1254
|
+
] as ChatMessage["parts"]
|
|
1255
|
+
}
|
|
1256
|
+
]);
|
|
1257
|
+
|
|
1258
|
+
// Verify the messages were persisted with approval-requested state
|
|
1259
|
+
const messages = (await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
1260
|
+
const assistantMessages = messages.filter((m) => m.role === "assistant");
|
|
1261
|
+
expect(assistantMessages.length).toBe(1);
|
|
1262
|
+
|
|
1263
|
+
const toolPart = assistantMessages[0].parts[0] as Record<string, unknown>;
|
|
1264
|
+
expect(toolPart.state).toBe("approval-requested");
|
|
1265
|
+
expect(toolPart.approval).toEqual({ id: "approval-persist-test" });
|
|
1266
|
+
|
|
1267
|
+
// Now simulate a client reconnecting and approving the tool.
|
|
1268
|
+
// A new client would receive these persisted messages and see the approval UI.
|
|
1269
|
+
// When they approve, CF_AGENT_TOOL_APPROVAL is sent.
|
|
1270
|
+
ws.send(
|
|
1271
|
+
JSON.stringify({
|
|
1272
|
+
type: "cf_agent_tool_approval",
|
|
1273
|
+
toolCallId,
|
|
1274
|
+
approved: true
|
|
1275
|
+
})
|
|
1276
|
+
);
|
|
1277
|
+
|
|
1278
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1279
|
+
|
|
1280
|
+
const updatedMessages =
|
|
1281
|
+
(await agentStub.getPersistedMessages()) as ChatMessage[];
|
|
1282
|
+
const updatedAssistant = updatedMessages.filter(
|
|
1283
|
+
(m) => m.role === "assistant"
|
|
1284
|
+
);
|
|
1285
|
+
expect(updatedAssistant.length).toBe(1);
|
|
1286
|
+
|
|
1287
|
+
const updatedToolPart = updatedAssistant[0].parts[0] as Record<
|
|
1288
|
+
string,
|
|
1289
|
+
unknown
|
|
1290
|
+
>;
|
|
1291
|
+
expect(updatedToolPart.state).toBe("approval-responded");
|
|
1292
|
+
// approval.id preserved from the approval-requested state
|
|
1293
|
+
expect(updatedToolPart.approval).toEqual({
|
|
1294
|
+
id: "approval-persist-test",
|
|
1295
|
+
approved: true
|
|
1296
|
+
});
|
|
1297
|
+
|
|
1298
|
+
ws.close(1000);
|
|
856
1299
|
});
|
|
857
1300
|
});
|
|
@@ -62,7 +62,7 @@ describe("Client Tools Broadcast", () => {
|
|
|
62
62
|
// which causes duplicate messages when combined with the stream response
|
|
63
63
|
expect(chatMessagesReceived.length).toBe(0);
|
|
64
64
|
|
|
65
|
-
ws.close();
|
|
65
|
+
ws.close(1000);
|
|
66
66
|
});
|
|
67
67
|
|
|
68
68
|
it("should broadcast CF_AGENT_CHAT_MESSAGES to other connections but not the originator", async () => {
|
|
@@ -133,6 +133,6 @@ describe("Client Tools Broadcast", () => {
|
|
|
133
133
|
expect(ws2ChatMessages.length).toBeGreaterThan(0);
|
|
134
134
|
|
|
135
135
|
ws1.close();
|
|
136
|
-
ws2.close();
|
|
136
|
+
ws2.close(1000);
|
|
137
137
|
});
|
|
138
138
|
});
|
|
@@ -116,7 +116,7 @@ describe("Client tools continuation", () => {
|
|
|
116
116
|
expect(continuationClientTools).toHaveLength(2);
|
|
117
117
|
expect(continuationClientTools).toEqual(clientTools);
|
|
118
118
|
|
|
119
|
-
ws.close();
|
|
119
|
+
ws.close(1000);
|
|
120
120
|
});
|
|
121
121
|
|
|
122
122
|
it("should clear stored client tools when chat is cleared", async () => {
|
|
@@ -208,7 +208,7 @@ describe("Client tools continuation", () => {
|
|
|
208
208
|
const continuationClientTools = await agentStub.getCapturedClientTools();
|
|
209
209
|
expect(continuationClientTools).toBeUndefined();
|
|
210
210
|
|
|
211
|
-
ws.close();
|
|
211
|
+
ws.close(1000);
|
|
212
212
|
});
|
|
213
213
|
|
|
214
214
|
it("should clear stored client tools when new request has no client tools", async () => {
|
|
@@ -309,6 +309,6 @@ describe("Client tools continuation", () => {
|
|
|
309
309
|
capturedTools = await agentStub.getCapturedClientTools();
|
|
310
310
|
expect(capturedTools).toBeUndefined();
|
|
311
311
|
|
|
312
|
-
ws.close();
|
|
312
|
+
ws.close(1000);
|
|
313
313
|
});
|
|
314
314
|
});
|