@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
@@ -14,10 +14,19 @@ function sleep(ms: number) {
14
14
  return new Promise((resolve) => setTimeout(resolve, ms));
15
15
  }
16
16
 
17
- function createAgent({ name, url }: { name: string; url: string }) {
17
+ function createAgent({
18
+ name,
19
+ url,
20
+ send
21
+ }: {
22
+ name: string;
23
+ url: string;
24
+ send?: (data: string) => void;
25
+ }) {
18
26
  const target = new EventTarget();
19
27
  const baseAgent = {
20
28
  _pkurl: url,
29
+ _pk: name, // Use name as pk to distinguish agents
21
30
  _url: null as string | null,
22
31
  addEventListener: target.addEventListener.bind(target),
23
32
  agent: "Chat",
@@ -25,7 +34,7 @@ function createAgent({ name, url }: { name: string; url: string }) {
25
34
  id: "fake-agent",
26
35
  name,
27
36
  removeEventListener: target.removeEventListener.bind(target),
28
- send: () => {},
37
+ send: send ?? (() => {}),
29
38
  dispatchEvent: target.dispatchEvent.bind(target)
30
39
  };
31
40
  return baseAgent as unknown as ReturnType<typeof useAgent>;
@@ -622,3 +631,730 @@ describe("useAgentChat client-side tool execution (issue #728)", () => {
622
631
  .toHaveTextContent("output-available");
623
632
  });
624
633
  });
634
+
635
+ describe("useAgentChat setMessages", () => {
636
+ it("should handle functional updater and sync resolved messages to server", async () => {
637
+ const sentMessages: string[] = [];
638
+ const agent = createAgent({
639
+ name: "set-messages-test",
640
+ url: "ws://localhost:3000/agents/chat/set-messages-test?_pk=abc",
641
+ send: (data: string) => sentMessages.push(data)
642
+ });
643
+
644
+ const initialMessages: UIMessage[] = [
645
+ {
646
+ id: "msg-1",
647
+ role: "user",
648
+ parts: [{ type: "text", text: "Hello" }]
649
+ },
650
+ {
651
+ id: "msg-2",
652
+ role: "assistant",
653
+ parts: [{ type: "text", text: "Hi there!" }]
654
+ }
655
+ ];
656
+
657
+ let chatInstance: ReturnType<typeof useAgentChat> | null = null;
658
+
659
+ const TestComponent = () => {
660
+ const chat = useAgentChat({
661
+ agent,
662
+ getInitialMessages: () => Promise.resolve(initialMessages)
663
+ });
664
+ chatInstance = chat;
665
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
666
+ };
667
+
668
+ const screen = await act(async () => {
669
+ const screen = render(<TestComponent />, {
670
+ wrapper: ({ children }) => (
671
+ <StrictMode>
672
+ <Suspense fallback="Loading...">{children}</Suspense>
673
+ </StrictMode>
674
+ )
675
+ });
676
+ await sleep(10);
677
+ return screen;
678
+ });
679
+
680
+ await expect
681
+ .element(screen.getByTestId("messages-count"))
682
+ .toHaveTextContent("2");
683
+
684
+ // Use functional updater to append a message
685
+ const newMessage: UIMessage = {
686
+ id: "msg-3",
687
+ role: "user",
688
+ parts: [{ type: "text", text: "Follow up" }]
689
+ };
690
+
691
+ await act(async () => {
692
+ chatInstance!.setMessages((prev) => [...prev, newMessage]);
693
+ await sleep(10);
694
+ });
695
+
696
+ await expect
697
+ .element(screen.getByTestId("messages-count"))
698
+ .toHaveTextContent("3");
699
+
700
+ // Verify the server received the RESOLVED messages (not empty array)
701
+ const chatMessagesSent = sentMessages
702
+ .map((m) => JSON.parse(m))
703
+ .filter((m) => m.type === "cf_agent_chat_messages");
704
+
705
+ expect(chatMessagesSent.length).toBeGreaterThan(0);
706
+ const lastSent = chatMessagesSent[chatMessagesSent.length - 1];
707
+ // Should have the full 3 messages, NOT an empty array
708
+ expect(lastSent.messages.length).toBe(3);
709
+ expect(lastSent.messages[2].id).toBe("msg-3");
710
+ });
711
+
712
+ it("should handle array setMessages and sync to server", async () => {
713
+ const sentMessages: string[] = [];
714
+ const agent = createAgent({
715
+ name: "set-messages-array-test",
716
+ url: "ws://localhost:3000/agents/chat/set-messages-array-test?_pk=abc",
717
+ send: (data: string) => sentMessages.push(data)
718
+ });
719
+
720
+ let chatInstance: ReturnType<typeof useAgentChat> | null = null;
721
+
722
+ const TestComponent = () => {
723
+ const chat = useAgentChat({
724
+ agent,
725
+ getInitialMessages: null,
726
+ messages: [] as UIMessage[]
727
+ });
728
+ chatInstance = chat;
729
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
730
+ };
731
+
732
+ await act(async () => {
733
+ render(<TestComponent />, {
734
+ wrapper: ({ children }) => (
735
+ <StrictMode>
736
+ <Suspense fallback="Loading...">{children}</Suspense>
737
+ </StrictMode>
738
+ )
739
+ });
740
+ await sleep(10);
741
+ });
742
+
743
+ // Set messages with an array directly
744
+ const newMessages: UIMessage[] = [
745
+ {
746
+ id: "arr-1",
747
+ role: "user",
748
+ parts: [{ type: "text", text: "Replaced" }]
749
+ }
750
+ ];
751
+
752
+ await act(async () => {
753
+ chatInstance!.setMessages(newMessages);
754
+ await sleep(10);
755
+ });
756
+
757
+ // Verify the server received the array
758
+ const chatMessagesSent = sentMessages
759
+ .map((m) => JSON.parse(m))
760
+ .filter((m) => m.type === "cf_agent_chat_messages");
761
+
762
+ expect(chatMessagesSent.length).toBeGreaterThan(0);
763
+ const lastSent = chatMessagesSent[chatMessagesSent.length - 1];
764
+ expect(lastSent.messages.length).toBe(1);
765
+ expect(lastSent.messages[0].id).toBe("arr-1");
766
+ });
767
+ });
768
+
769
+ describe("useAgentChat clearHistory", () => {
770
+ it("should clear local state and send CF_AGENT_CHAT_CLEAR to server", async () => {
771
+ const sentMessages: string[] = [];
772
+ const agent = createAgent({
773
+ name: "clear-test",
774
+ url: "ws://localhost:3000/agents/chat/clear-test?_pk=abc",
775
+ send: (data: string) => sentMessages.push(data)
776
+ });
777
+
778
+ const initialMessages: UIMessage[] = [
779
+ {
780
+ id: "clear-1",
781
+ role: "user",
782
+ parts: [{ type: "text", text: "Hello" }]
783
+ }
784
+ ];
785
+
786
+ let chatInstance: ReturnType<typeof useAgentChat> | null = null;
787
+
788
+ const TestComponent = () => {
789
+ const chat = useAgentChat({
790
+ agent,
791
+ getInitialMessages: () => Promise.resolve(initialMessages)
792
+ });
793
+ chatInstance = chat;
794
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
795
+ };
796
+
797
+ const screen = await act(async () => {
798
+ const screen = render(<TestComponent />, {
799
+ wrapper: ({ children }) => (
800
+ <StrictMode>
801
+ <Suspense fallback="Loading...">{children}</Suspense>
802
+ </StrictMode>
803
+ )
804
+ });
805
+ await sleep(10);
806
+ return screen;
807
+ });
808
+
809
+ await expect
810
+ .element(screen.getByTestId("messages-count"))
811
+ .toHaveTextContent("1");
812
+
813
+ await act(async () => {
814
+ chatInstance!.clearHistory();
815
+ await sleep(10);
816
+ });
817
+
818
+ await expect
819
+ .element(screen.getByTestId("messages-count"))
820
+ .toHaveTextContent("0");
821
+
822
+ // Verify CF_AGENT_CHAT_CLEAR was sent
823
+ const clearMessages = sentMessages
824
+ .map((m) => JSON.parse(m))
825
+ .filter((m) => m.type === "cf_agent_chat_clear");
826
+ expect(clearMessages.length).toBe(1);
827
+ });
828
+ });
829
+
830
+ describe("useAgentChat autoContinueAfterToolResult default", () => {
831
+ it("should send autoContinue: true by default with tool results", async () => {
832
+ const sentMessages: string[] = [];
833
+ const agent = createAgent({
834
+ name: "auto-continue-default",
835
+ url: "ws://localhost:3000/agents/chat/auto-continue-default?_pk=abc",
836
+ send: (data: string) => sentMessages.push(data)
837
+ });
838
+
839
+ const initialMessages: UIMessage[] = [
840
+ {
841
+ id: "msg-1",
842
+ role: "assistant",
843
+ parts: [
844
+ {
845
+ type: "tool-getLocation",
846
+ toolCallId: "tc-default-1",
847
+ state: "input-available",
848
+ input: {}
849
+ }
850
+ ]
851
+ }
852
+ ];
853
+
854
+ const TestComponent = () => {
855
+ const chat = useAgentChat({
856
+ agent,
857
+ getInitialMessages: () => Promise.resolve(initialMessages),
858
+ // No explicit autoContinueAfterToolResult — should default to true
859
+ onToolCall: ({ toolCall, addToolOutput }) => {
860
+ addToolOutput({
861
+ toolCallId: toolCall.toolCallId,
862
+ output: { lat: 51.5, lng: -0.1 }
863
+ });
864
+ }
865
+ });
866
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
867
+ };
868
+
869
+ await act(async () => {
870
+ render(<TestComponent />, {
871
+ wrapper: ({ children }) => (
872
+ <StrictMode>
873
+ <Suspense fallback="Loading...">{children}</Suspense>
874
+ </StrictMode>
875
+ )
876
+ });
877
+ await sleep(50);
878
+ });
879
+
880
+ // Find the CF_AGENT_TOOL_RESULT message
881
+ const toolResultMessages = sentMessages
882
+ .map((m) => JSON.parse(m))
883
+ .filter((m) => m.type === "cf_agent_tool_result");
884
+
885
+ expect(toolResultMessages.length).toBeGreaterThanOrEqual(1);
886
+ // Default should be autoContinue: true
887
+ expect(toolResultMessages[0].autoContinue).toBe(true);
888
+ });
889
+
890
+ it("should send autoContinue: false when explicitly disabled", async () => {
891
+ const sentMessages: string[] = [];
892
+ const agent = createAgent({
893
+ name: "auto-continue-disabled",
894
+ url: "ws://localhost:3000/agents/chat/auto-continue-disabled?_pk=abc",
895
+ send: (data: string) => sentMessages.push(data)
896
+ });
897
+
898
+ const initialMessages: UIMessage[] = [
899
+ {
900
+ id: "msg-1",
901
+ role: "assistant",
902
+ parts: [
903
+ {
904
+ type: "tool-getLocation",
905
+ toolCallId: "tc-disabled-1",
906
+ state: "input-available",
907
+ input: {}
908
+ }
909
+ ]
910
+ }
911
+ ];
912
+
913
+ const TestComponent = () => {
914
+ const chat = useAgentChat({
915
+ agent,
916
+ getInitialMessages: () => Promise.resolve(initialMessages),
917
+ autoContinueAfterToolResult: false, // Explicitly disabled
918
+ onToolCall: ({ toolCall, addToolOutput }) => {
919
+ addToolOutput({
920
+ toolCallId: toolCall.toolCallId,
921
+ output: { lat: 51.5, lng: -0.1 }
922
+ });
923
+ }
924
+ });
925
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
926
+ };
927
+
928
+ await act(async () => {
929
+ render(<TestComponent />, {
930
+ wrapper: ({ children }) => (
931
+ <StrictMode>
932
+ <Suspense fallback="Loading...">{children}</Suspense>
933
+ </StrictMode>
934
+ )
935
+ });
936
+ await sleep(50);
937
+ });
938
+
939
+ const toolResultMessages = sentMessages
940
+ .map((m) => JSON.parse(m))
941
+ .filter((m) => m.type === "cf_agent_tool_result");
942
+
943
+ expect(toolResultMessages.length).toBeGreaterThanOrEqual(1);
944
+ expect(toolResultMessages[0].autoContinue).toBe(false);
945
+ });
946
+
947
+ it("should send autoContinue: true by default with tool approvals", async () => {
948
+ const sentMessages: string[] = [];
949
+ const agent = createAgent({
950
+ name: "auto-continue-approval",
951
+ url: "ws://localhost:3000/agents/chat/auto-continue-approval?_pk=abc",
952
+ send: (data: string) => sentMessages.push(data)
953
+ });
954
+
955
+ // Tool part must have approval.id so the wrapper can find the toolCallId
956
+ const initialMessages: UIMessage[] = [
957
+ {
958
+ id: "msg-1",
959
+ role: "assistant",
960
+ parts: [
961
+ {
962
+ type: "tool-dangerousAction",
963
+ toolCallId: "tc-approval-1",
964
+ state: "approval-requested",
965
+ input: { action: "delete" },
966
+ approval: { id: "approval-req-1" }
967
+ }
968
+ ]
969
+ }
970
+ ];
971
+
972
+ let chatInstance: ReturnType<typeof useAgentChat> | null = null;
973
+
974
+ const TestComponent = () => {
975
+ const chat = useAgentChat({
976
+ agent,
977
+ getInitialMessages: () => Promise.resolve(initialMessages)
978
+ // No explicit autoContinueAfterToolResult — should default to true
979
+ });
980
+ chatInstance = chat;
981
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
982
+ };
983
+
984
+ await act(async () => {
985
+ render(<TestComponent />, {
986
+ wrapper: ({ children }) => (
987
+ <StrictMode>
988
+ <Suspense fallback="Loading...">{children}</Suspense>
989
+ </StrictMode>
990
+ )
991
+ });
992
+ await sleep(50);
993
+ });
994
+
995
+ // Send approval via the hook using the approval request ID
996
+ await act(async () => {
997
+ if (chatInstance) {
998
+ chatInstance.addToolApprovalResponse({
999
+ id: "approval-req-1",
1000
+ approved: true
1001
+ });
1002
+ }
1003
+ await sleep(10);
1004
+ });
1005
+
1006
+ // Find the CF_AGENT_TOOL_APPROVAL message
1007
+ const approvalMessages = sentMessages
1008
+ .map((m) => JSON.parse(m))
1009
+ .filter((m) => m.type === "cf_agent_tool_approval");
1010
+
1011
+ expect(approvalMessages.length).toBeGreaterThanOrEqual(1);
1012
+ expect(approvalMessages[0].autoContinue).toBe(true);
1013
+ expect(approvalMessages[0].approved).toBe(true);
1014
+ });
1015
+ });
1016
+
1017
+ describe("useAgentChat onToolCall", () => {
1018
+ it("should fire onToolCall for input-available tool parts", async () => {
1019
+ const agent = createAgent({
1020
+ name: "ontoolcall-test",
1021
+ url: "ws://localhost:3000/agents/chat/ontoolcall-test?_pk=abc",
1022
+ send: () => {}
1023
+ });
1024
+
1025
+ const toolCallReceived = vi.fn();
1026
+
1027
+ const initialMessages: UIMessage[] = [
1028
+ {
1029
+ id: "msg-tool-1",
1030
+ role: "assistant",
1031
+ parts: [
1032
+ {
1033
+ type: "tool-getLocation",
1034
+ toolCallId: "tc-1",
1035
+ state: "input-available",
1036
+ input: { query: "current" }
1037
+ }
1038
+ ]
1039
+ }
1040
+ ];
1041
+
1042
+ const TestComponent = () => {
1043
+ const chat = useAgentChat({
1044
+ agent,
1045
+ getInitialMessages: () => Promise.resolve(initialMessages),
1046
+ onToolCall: ({ toolCall, addToolOutput }) => {
1047
+ toolCallReceived(toolCall);
1048
+ addToolOutput({
1049
+ toolCallId: toolCall.toolCallId,
1050
+ output: { lat: 40.7, lng: -74.0 }
1051
+ });
1052
+ }
1053
+ });
1054
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1055
+ };
1056
+
1057
+ await act(async () => {
1058
+ render(<TestComponent />, {
1059
+ wrapper: ({ children }) => (
1060
+ <StrictMode>
1061
+ <Suspense fallback="Loading...">{children}</Suspense>
1062
+ </StrictMode>
1063
+ )
1064
+ });
1065
+ await sleep(50);
1066
+ });
1067
+
1068
+ // onToolCall should have been called with the tool call details
1069
+ expect(toolCallReceived).toHaveBeenCalledWith(
1070
+ expect.objectContaining({
1071
+ toolCallId: "tc-1",
1072
+ toolName: "getLocation",
1073
+ input: { query: "current" }
1074
+ })
1075
+ );
1076
+ });
1077
+ });
1078
+
1079
+ describe("useAgentChat re-render stability", () => {
1080
+ it("should not cause infinite re-renders when idle", async () => {
1081
+ const agent = createAgent({
1082
+ name: "rerender-idle",
1083
+ url: "ws://localhost:3000/agents/chat/rerender-idle?_pk=abc"
1084
+ });
1085
+
1086
+ let renderCount = 0;
1087
+
1088
+ const TestComponent = () => {
1089
+ renderCount++;
1090
+ const chat = useAgentChat({
1091
+ agent,
1092
+ getInitialMessages: null,
1093
+ messages: []
1094
+ });
1095
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1096
+ };
1097
+
1098
+ await act(async () => {
1099
+ render(<TestComponent />, {
1100
+ wrapper: ({ children }) => (
1101
+ <StrictMode>
1102
+ <Suspense fallback="Loading...">{children}</Suspense>
1103
+ </StrictMode>
1104
+ )
1105
+ });
1106
+ await sleep(10);
1107
+ });
1108
+
1109
+ // Capture render count after initial mount
1110
+ const afterMountCount = renderCount;
1111
+
1112
+ // Wait to see if more renders happen (would indicate an infinite loop)
1113
+ await sleep(200);
1114
+
1115
+ // In Strict Mode, React double-renders. After mount stabilizes,
1116
+ // there should be NO additional renders (no infinite loop).
1117
+ expect(renderCount).toBe(afterMountCount);
1118
+ });
1119
+
1120
+ it("should not re-render excessively when messages are set", async () => {
1121
+ const agent = createAgent({
1122
+ name: "rerender-messages",
1123
+ url: "ws://localhost:3000/agents/chat/rerender-messages?_pk=abc"
1124
+ });
1125
+
1126
+ let renderCount = 0;
1127
+ let chatInstance: ReturnType<typeof useAgentChat> | null = null;
1128
+
1129
+ const TestComponent = () => {
1130
+ renderCount++;
1131
+ const chat = useAgentChat({
1132
+ agent,
1133
+ getInitialMessages: null,
1134
+ messages: [] as UIMessage[]
1135
+ });
1136
+ chatInstance = chat;
1137
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1138
+ };
1139
+
1140
+ await act(async () => {
1141
+ render(<TestComponent />, {
1142
+ wrapper: ({ children }) => (
1143
+ <StrictMode>
1144
+ <Suspense fallback="Loading...">{children}</Suspense>
1145
+ </StrictMode>
1146
+ )
1147
+ });
1148
+ await sleep(10);
1149
+ });
1150
+
1151
+ const beforeSetMessages = renderCount;
1152
+
1153
+ // Set messages
1154
+ await act(async () => {
1155
+ chatInstance!.setMessages([
1156
+ {
1157
+ id: "msg-1",
1158
+ role: "user",
1159
+ parts: [{ type: "text", text: "Hello" }]
1160
+ }
1161
+ ]);
1162
+ await sleep(10);
1163
+ });
1164
+
1165
+ const afterSetMessages = renderCount;
1166
+
1167
+ // Wait to see if renders stabilize
1168
+ await sleep(200);
1169
+
1170
+ // Should have re-rendered for the setMessages call but then stopped.
1171
+ // Allow some re-renders (React batching, state updates) but not infinite.
1172
+ const rendersFromSetMessages = afterSetMessages - beforeSetMessages;
1173
+ expect(rendersFromSetMessages).toBeLessThan(10);
1174
+
1175
+ // No additional renders after stabilizing
1176
+ expect(renderCount).toBe(afterSetMessages);
1177
+ });
1178
+
1179
+ it("should stabilize after receiving a broadcast message", async () => {
1180
+ const target = new EventTarget();
1181
+ const agent = createAgent({
1182
+ name: "rerender-broadcast",
1183
+ url: "ws://localhost:3000/agents/chat/rerender-broadcast?_pk=abc"
1184
+ });
1185
+ // Override addEventListener/removeEventListener to use our target
1186
+ (agent as unknown as Record<string, unknown>).addEventListener =
1187
+ target.addEventListener.bind(target);
1188
+ (agent as unknown as Record<string, unknown>).removeEventListener =
1189
+ target.removeEventListener.bind(target);
1190
+
1191
+ let renderCount = 0;
1192
+
1193
+ const TestComponent = () => {
1194
+ renderCount++;
1195
+ const chat = useAgentChat({
1196
+ agent,
1197
+ getInitialMessages: null,
1198
+ messages: []
1199
+ });
1200
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1201
+ };
1202
+
1203
+ await act(async () => {
1204
+ render(<TestComponent />, {
1205
+ wrapper: ({ children }) => (
1206
+ <StrictMode>
1207
+ <Suspense fallback="Loading...">{children}</Suspense>
1208
+ </StrictMode>
1209
+ )
1210
+ });
1211
+ await sleep(10);
1212
+ });
1213
+
1214
+ const beforeBroadcast = renderCount;
1215
+
1216
+ // Simulate a server broadcast (CF_AGENT_CHAT_MESSAGES)
1217
+ await act(async () => {
1218
+ target.dispatchEvent(
1219
+ new MessageEvent("message", {
1220
+ data: JSON.stringify({
1221
+ type: "cf_agent_chat_messages",
1222
+ messages: [
1223
+ {
1224
+ id: "broadcast-1",
1225
+ role: "user",
1226
+ parts: [{ type: "text", text: "From other tab" }]
1227
+ }
1228
+ ]
1229
+ })
1230
+ })
1231
+ );
1232
+ await sleep(10);
1233
+ });
1234
+
1235
+ const afterBroadcast = renderCount;
1236
+
1237
+ // Wait for stabilization
1238
+ await sleep(200);
1239
+
1240
+ // Should have re-rendered for the broadcast but then stopped
1241
+ const rendersFromBroadcast = afterBroadcast - beforeBroadcast;
1242
+ expect(rendersFromBroadcast).toBeGreaterThan(0); // Must have re-rendered
1243
+ expect(rendersFromBroadcast).toBeLessThan(10); // But not infinitely
1244
+
1245
+ // No additional renders after stabilizing
1246
+ expect(renderCount).toBe(afterBroadcast);
1247
+ });
1248
+ });
1249
+
1250
+ describe("useAgentChat body option", () => {
1251
+ it("should include static body fields in sent messages", async () => {
1252
+ const sentMessages: string[] = [];
1253
+ const agent = createAgent({
1254
+ name: "body-static-test",
1255
+ url: "ws://localhost:3000/agents/chat/body-static-test?_pk=abc",
1256
+ send: (data: string) => sentMessages.push(data)
1257
+ });
1258
+
1259
+ const TestComponent = () => {
1260
+ const chat = useAgentChat({
1261
+ agent,
1262
+ getInitialMessages: null,
1263
+ messages: [],
1264
+ body: { timezone: "America/New_York", userId: "user-123" }
1265
+ });
1266
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1267
+ };
1268
+
1269
+ await act(async () => {
1270
+ render(<TestComponent />, {
1271
+ wrapper: ({ children }) => (
1272
+ <StrictMode>
1273
+ <Suspense fallback="Loading...">{children}</Suspense>
1274
+ </StrictMode>
1275
+ )
1276
+ });
1277
+ await sleep(10);
1278
+ });
1279
+
1280
+ // The body fields should be included when the transport sends messages
1281
+ // We can verify by checking that the component rendered without errors
1282
+ // (the actual body merging is tested via the sent WS messages)
1283
+ expect(sentMessages).toBeDefined();
1284
+ });
1285
+
1286
+ it("should include dynamic body fields from function", async () => {
1287
+ const sentMessages: string[] = [];
1288
+ let callCount = 0;
1289
+ const agent = createAgent({
1290
+ name: "body-dynamic-test",
1291
+ url: "ws://localhost:3000/agents/chat/body-dynamic-test?_pk=abc",
1292
+ send: (data: string) => sentMessages.push(data)
1293
+ });
1294
+
1295
+ const TestComponent = () => {
1296
+ const chat = useAgentChat({
1297
+ agent,
1298
+ getInitialMessages: null,
1299
+ messages: [],
1300
+ body: () => {
1301
+ callCount++;
1302
+ return { timestamp: Date.now(), requestNumber: callCount };
1303
+ }
1304
+ });
1305
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1306
+ };
1307
+
1308
+ await act(async () => {
1309
+ render(<TestComponent />, {
1310
+ wrapper: ({ children }) => (
1311
+ <StrictMode>
1312
+ <Suspense fallback="Loading...">{children}</Suspense>
1313
+ </StrictMode>
1314
+ )
1315
+ });
1316
+ await sleep(10);
1317
+ });
1318
+
1319
+ // Component should render without errors with function body
1320
+ expect(callCount).toBeDefined();
1321
+ });
1322
+
1323
+ it("should work alongside prepareSendMessagesRequest", async () => {
1324
+ const sentMessages: string[] = [];
1325
+ const agent = createAgent({
1326
+ name: "body-combined-test",
1327
+ url: "ws://localhost:3000/agents/chat/body-combined-test?_pk=abc",
1328
+ send: (data: string) => sentMessages.push(data)
1329
+ });
1330
+
1331
+ const prepareSendMessagesRequest = vi.fn(() => ({
1332
+ body: { fromPrepare: true }
1333
+ }));
1334
+
1335
+ const TestComponent = () => {
1336
+ const chat = useAgentChat({
1337
+ agent,
1338
+ getInitialMessages: null,
1339
+ messages: [],
1340
+ body: { fromBody: true },
1341
+ prepareSendMessagesRequest
1342
+ });
1343
+ return <div data-testid="messages-count">{chat.messages.length}</div>;
1344
+ };
1345
+
1346
+ await act(async () => {
1347
+ render(<TestComponent />, {
1348
+ wrapper: ({ children }) => (
1349
+ <StrictMode>
1350
+ <Suspense fallback="Loading...">{children}</Suspense>
1351
+ </StrictMode>
1352
+ )
1353
+ });
1354
+ await sleep(10);
1355
+ });
1356
+
1357
+ // Both body and prepareSendMessagesRequest should coexist without errors
1358
+ expect(sentMessages).toBeDefined();
1359
+ });
1360
+ });