@copilotkit/react-core 1.54.1 → 1.55.0-next.7

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 (183) hide show
  1. package/CHANGELOG.md +117 -116
  2. package/dist/copilotkit-B3Mb1yVE.cjs +7975 -0
  3. package/dist/copilotkit-B3Mb1yVE.cjs.map +1 -0
  4. package/dist/copilotkit-DBzgOMby.d.cts +2182 -0
  5. package/dist/copilotkit-DBzgOMby.d.cts.map +1 -0
  6. package/dist/copilotkit-DNYSFuz5.mjs +7562 -0
  7. package/dist/copilotkit-DNYSFuz5.mjs.map +1 -0
  8. package/dist/copilotkit-Dy5w3qEV.d.mts +2182 -0
  9. package/dist/copilotkit-Dy5w3qEV.d.mts.map +1 -0
  10. package/dist/index.cjs +27 -28
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +3 -3
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.mts +3 -3
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +4 -5
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/index.umd.js +1941 -35
  19. package/dist/index.umd.js.map +1 -1
  20. package/dist/v2/index.cjs +77 -7
  21. package/dist/v2/index.css +1 -2
  22. package/dist/v2/index.d.cts +6 -4
  23. package/dist/v2/index.d.mts +6 -4
  24. package/dist/v2/index.mjs +7 -4
  25. package/dist/v2/index.umd.js +5725 -24
  26. package/dist/v2/index.umd.js.map +1 -1
  27. package/package.json +37 -9
  28. package/scripts/scope-preflight.mjs +101 -0
  29. package/src/components/CopilotListeners.tsx +2 -6
  30. package/src/components/copilot-provider/copilot-messages.tsx +1 -1
  31. package/src/components/copilot-provider/copilotkit-props.tsx +1 -1
  32. package/src/components/copilot-provider/copilotkit.tsx +4 -4
  33. package/src/context/copilot-messages-context.tsx +1 -1
  34. package/src/hooks/__tests__/use-coagent-config.test.ts +2 -2
  35. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +2 -2
  36. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +3 -7
  37. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +1 -1
  38. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +4 -4
  39. package/src/hooks/use-agent-nodename.ts +1 -1
  40. package/src/hooks/use-coagent-state-render-bridge.tsx +1 -4
  41. package/src/hooks/use-coagent.ts +1 -1
  42. package/src/hooks/use-configure-chat-suggestions.tsx +2 -2
  43. package/src/hooks/use-copilot-chat-suggestions.tsx +2 -2
  44. package/src/hooks/use-copilot-chat_internal.ts +2 -2
  45. package/src/hooks/use-copilot-readable.ts +1 -1
  46. package/src/hooks/use-frontend-tool.ts +2 -2
  47. package/src/hooks/use-human-in-the-loop.ts +2 -2
  48. package/src/hooks/use-langgraph-interrupt.ts +2 -5
  49. package/src/hooks/use-lazy-tool-renderer.tsx +1 -1
  50. package/src/hooks/use-render-tool-call.ts +1 -1
  51. package/src/lib/copilot-task.ts +1 -1
  52. package/src/setupTests.ts +18 -14
  53. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +176 -0
  54. package/src/v2/__tests__/globalSetup.ts +14 -0
  55. package/src/v2/__tests__/setup.ts +93 -0
  56. package/src/v2/__tests__/utils/test-helpers.tsx +470 -0
  57. package/src/v2/a2ui/A2UIMessageRenderer.tsx +206 -0
  58. package/src/v2/components/CopilotKitInspector.tsx +50 -0
  59. package/src/v2/components/MCPAppsActivityRenderer.tsx +785 -0
  60. package/src/v2/components/WildcardToolCallRender.tsx +86 -0
  61. package/src/v2/components/__tests__/license-warning-banner.test.tsx +46 -0
  62. package/src/v2/components/chat/CopilotChat.tsx +431 -0
  63. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +375 -0
  64. package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +350 -0
  65. package/src/v2/components/chat/CopilotChatInput.tsx +1302 -0
  66. package/src/v2/components/chat/CopilotChatMessageView.tsx +556 -0
  67. package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +252 -0
  68. package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +59 -0
  69. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +133 -0
  70. package/src/v2/components/chat/CopilotChatToggleButton.tsx +171 -0
  71. package/src/v2/components/chat/CopilotChatToolCallsView.tsx +40 -0
  72. package/src/v2/components/chat/CopilotChatUserMessage.tsx +388 -0
  73. package/src/v2/components/chat/CopilotChatView.tsx +598 -0
  74. package/src/v2/components/chat/CopilotModalHeader.tsx +129 -0
  75. package/src/v2/components/chat/CopilotPopup.tsx +81 -0
  76. package/src/v2/components/chat/CopilotPopupView.tsx +317 -0
  77. package/src/v2/components/chat/CopilotSidebar.tsx +76 -0
  78. package/src/v2/components/chat/CopilotSidebarView.tsx +255 -0
  79. package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +1113 -0
  80. package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +73 -0
  81. package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +432 -0
  82. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +150 -0
  83. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +624 -0
  84. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +702 -0
  85. package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +107 -0
  86. package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +929 -0
  87. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +986 -0
  88. package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +1004 -0
  89. package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +169 -0
  90. package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +530 -0
  91. package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +782 -0
  92. package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +2413 -0
  93. package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +621 -0
  94. package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +853 -0
  95. package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +1050 -0
  96. package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +484 -0
  97. package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +612 -0
  98. package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +502 -0
  99. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +1011 -0
  100. package/src/v2/components/chat/__tests__/setup.ts +1 -0
  101. package/src/v2/components/chat/index.ts +79 -0
  102. package/src/v2/components/index.ts +7 -0
  103. package/src/v2/components/license-warning-banner.tsx +198 -0
  104. package/src/v2/components/ui/button.tsx +123 -0
  105. package/src/v2/components/ui/dropdown-menu.tsx +258 -0
  106. package/src/v2/components/ui/tooltip.tsx +60 -0
  107. package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +152 -0
  108. package/src/v2/hooks/__tests__/standard-schema.test.tsx +282 -0
  109. package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +132 -0
  110. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +401 -0
  111. package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +44 -0
  112. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +205 -0
  113. package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +148 -0
  114. package/src/v2/hooks/__tests__/use-component.test.tsx +123 -0
  115. package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +696 -0
  116. package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +153 -0
  117. package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +167 -0
  118. package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +2129 -0
  119. package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +1261 -0
  120. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +397 -0
  121. package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +56 -0
  122. package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +192 -0
  123. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +259 -0
  124. package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +524 -0
  125. package/src/v2/hooks/__tests__/use-threads.test.tsx +433 -0
  126. package/src/v2/hooks/__tests__/zod-regression.test.tsx +311 -0
  127. package/src/v2/hooks/index.ts +18 -0
  128. package/src/v2/hooks/use-agent-context.tsx +45 -0
  129. package/src/v2/hooks/use-agent.tsx +155 -0
  130. package/src/v2/hooks/use-component.tsx +89 -0
  131. package/src/v2/hooks/use-configure-suggestions.tsx +187 -0
  132. package/src/v2/hooks/use-default-render-tool.tsx +254 -0
  133. package/src/v2/hooks/use-frontend-tool.tsx +43 -0
  134. package/src/v2/hooks/use-human-in-the-loop.tsx +81 -0
  135. package/src/v2/hooks/use-interrupt.tsx +305 -0
  136. package/src/v2/hooks/use-keyboard-height.tsx +67 -0
  137. package/src/v2/hooks/use-render-activity-message.tsx +73 -0
  138. package/src/v2/hooks/use-render-custom-messages.tsx +93 -0
  139. package/src/v2/hooks/use-render-tool-call.tsx +175 -0
  140. package/src/v2/hooks/use-render-tool.tsx +181 -0
  141. package/src/v2/hooks/use-suggestions.tsx +91 -0
  142. package/src/v2/hooks/use-threads.tsx +256 -0
  143. package/src/v2/hooks/useKatexStyles.ts +27 -0
  144. package/src/v2/index.css +1 -1
  145. package/src/v2/index.ts +18 -2
  146. package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +495 -0
  147. package/src/v2/lib/__tests__/renderSlot.test.tsx +588 -0
  148. package/src/v2/lib/react-core.ts +156 -0
  149. package/src/v2/lib/slots.tsx +143 -0
  150. package/src/v2/lib/transcription-client.ts +184 -0
  151. package/src/v2/lib/utils.ts +8 -0
  152. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +162 -0
  153. package/src/v2/providers/CopilotKitProvider.tsx +600 -0
  154. package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +546 -0
  155. package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +101 -0
  156. package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +69 -0
  157. package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +881 -0
  158. package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +740 -0
  159. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +642 -0
  160. package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +294 -0
  161. package/src/v2/providers/index.ts +14 -0
  162. package/src/v2/styles/globals.css +230 -0
  163. package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +525 -0
  164. package/src/v2/types/defineToolCallRenderer.ts +65 -0
  165. package/src/v2/types/frontend-tool.ts +8 -0
  166. package/src/v2/types/human-in-the-loop.ts +33 -0
  167. package/src/v2/types/index.ts +7 -0
  168. package/src/v2/types/interrupt.ts +15 -0
  169. package/src/v2/types/react-activity-message-renderer.ts +27 -0
  170. package/src/v2/types/react-custom-message-renderer.ts +17 -0
  171. package/src/v2/types/react-tool-call-renderer.ts +32 -0
  172. package/tsdown.config.ts +34 -10
  173. package/vitest.config.mjs +4 -3
  174. package/LICENSE +0 -21
  175. package/dist/copilotkit-BRPQ2sqS.d.cts +0 -670
  176. package/dist/copilotkit-BRPQ2sqS.d.cts.map +0 -1
  177. package/dist/copilotkit-C94ayZbs.cjs +0 -2161
  178. package/dist/copilotkit-C94ayZbs.cjs.map +0 -1
  179. package/dist/copilotkit-CwZMFmSK.d.mts +0 -670
  180. package/dist/copilotkit-CwZMFmSK.d.mts.map +0 -1
  181. package/dist/copilotkit-Yh_Ld_FX.mjs +0 -2031
  182. package/dist/copilotkit-Yh_Ld_FX.mjs.map +0 -1
  183. package/dist/v2/index.css.map +0 -1
@@ -0,0 +1,401 @@
1
+ import React, { useState } from "react";
2
+ import { render, act } from "@testing-library/react";
3
+ import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
4
+ import { useAgentContext, type AgentContextInput } from "../use-agent-context";
5
+ import { useCopilotKit } from "../../providers/CopilotKitProvider";
6
+
7
+ // Mock the CopilotKitProvider
8
+ vi.mock("../../providers/CopilotKitProvider", () => ({
9
+ useCopilotKit: vi.fn(),
10
+ }));
11
+
12
+ const mockUseCopilotKit = useCopilotKit as ReturnType<typeof vi.fn>;
13
+
14
+ describe("useAgentContext", () => {
15
+ let addContextMock: ReturnType<typeof vi.fn>;
16
+ let removeContextMock: ReturnType<typeof vi.fn>;
17
+ let contextIdCounter: number;
18
+
19
+ beforeEach(() => {
20
+ contextIdCounter = 0;
21
+ addContextMock = vi.fn(() => `context-${++contextIdCounter}`);
22
+ removeContextMock = vi.fn();
23
+
24
+ mockUseCopilotKit.mockReturnValue({
25
+ copilotkit: {
26
+ addContext: addContextMock,
27
+ removeContext: removeContextMock,
28
+ },
29
+ } as any);
30
+ });
31
+
32
+ afterEach(() => {
33
+ vi.clearAllMocks();
34
+ });
35
+
36
+ describe("context cleanup on unmount", () => {
37
+ it("removes the context when the component unmounts", () => {
38
+ const TestComponent: React.FC<{ context: AgentContextInput }> = ({
39
+ context,
40
+ }) => {
41
+ useAgentContext(context);
42
+ return <div>Test</div>;
43
+ };
44
+
45
+ const { unmount } = render(
46
+ <TestComponent
47
+ context={{ description: "test context", value: "test value" }}
48
+ />,
49
+ );
50
+
51
+ // Context should be added
52
+ expect(addContextMock).toHaveBeenCalledTimes(1);
53
+ expect(addContextMock).toHaveBeenCalledWith({
54
+ description: "test context",
55
+ value: "test value",
56
+ });
57
+
58
+ const addedContextId = addContextMock.mock.results[0]?.value;
59
+
60
+ // Unmount the component
61
+ unmount();
62
+
63
+ // Context should be removed with the correct ID
64
+ expect(removeContextMock).toHaveBeenCalledTimes(1);
65
+ expect(removeContextMock).toHaveBeenCalledWith(addedContextId);
66
+ });
67
+
68
+ it("removes context when conditionally unmounted", () => {
69
+ const ContextUser: React.FC = () => {
70
+ useAgentContext({
71
+ description: "conditional context",
72
+ value: "conditional value",
73
+ });
74
+ return <div data-testid="context-user">Context User</div>;
75
+ };
76
+
77
+ const ParentComponent: React.FC = () => {
78
+ const [showContext, setShowContext] = useState(true);
79
+ return (
80
+ <>
81
+ <button
82
+ data-testid="toggle"
83
+ onClick={() => setShowContext((prev) => !prev)}
84
+ >
85
+ Toggle
86
+ </button>
87
+ {showContext && <ContextUser />}
88
+ </>
89
+ );
90
+ };
91
+
92
+ const { getByTestId, queryByTestId } = render(<ParentComponent />);
93
+
94
+ // Context should be added
95
+ expect(addContextMock).toHaveBeenCalledTimes(1);
96
+ expect(queryByTestId("context-user")).not.toBeNull();
97
+
98
+ const addedContextId = addContextMock.mock.results[0]?.value;
99
+
100
+ // Toggle off - should unmount ContextUser
101
+ act(() => {
102
+ getByTestId("toggle").click();
103
+ });
104
+
105
+ // Context should be removed
106
+ expect(removeContextMock).toHaveBeenCalledTimes(1);
107
+ expect(removeContextMock).toHaveBeenCalledWith(addedContextId);
108
+ expect(queryByTestId("context-user")).toBeNull();
109
+ });
110
+ });
111
+
112
+ describe("re-render idempotence", () => {
113
+ it("does not add additional context on re-render with same values", () => {
114
+ const TestComponent: React.FC<{
115
+ context: AgentContextInput;
116
+ counter: number;
117
+ }> = ({ context, counter }) => {
118
+ useAgentContext(context);
119
+ return <div>Counter: {counter}</div>;
120
+ };
121
+
122
+ const context: AgentContextInput = {
123
+ description: "stable context",
124
+ value: "stable value",
125
+ };
126
+
127
+ const { rerender } = render(
128
+ <TestComponent context={context} counter={0} />,
129
+ );
130
+
131
+ // Initial render - context added once
132
+ expect(addContextMock).toHaveBeenCalledTimes(1);
133
+
134
+ // Re-render with different counter but same context
135
+ rerender(<TestComponent context={context} counter={1} />);
136
+
137
+ // Context should not be added again
138
+ expect(addContextMock).toHaveBeenCalledTimes(1);
139
+
140
+ // Re-render again
141
+ rerender(<TestComponent context={context} counter={2} />);
142
+
143
+ // Still only one add
144
+ expect(addContextMock).toHaveBeenCalledTimes(1);
145
+ });
146
+
147
+ it("does not add additional context when parent re-renders", () => {
148
+ const ContextUser: React.FC = () => {
149
+ useAgentContext({
150
+ description: "child context",
151
+ value: "child value",
152
+ });
153
+ return <div>Child</div>;
154
+ };
155
+
156
+ const ParentComponent: React.FC = () => {
157
+ const [counter, setCounter] = useState(0);
158
+ return (
159
+ <>
160
+ <button
161
+ data-testid="increment"
162
+ onClick={() => setCounter((c) => c + 1)}
163
+ >
164
+ Increment ({counter})
165
+ </button>
166
+ <ContextUser />
167
+ </>
168
+ );
169
+ };
170
+
171
+ const { getByTestId } = render(<ParentComponent />);
172
+
173
+ // Initial render
174
+ expect(addContextMock).toHaveBeenCalledTimes(1);
175
+
176
+ // Trigger parent re-render multiple times
177
+ act(() => {
178
+ getByTestId("increment").click();
179
+ });
180
+ act(() => {
181
+ getByTestId("increment").click();
182
+ });
183
+ act(() => {
184
+ getByTestId("increment").click();
185
+ });
186
+
187
+ // Context should still only be added once
188
+ expect(addContextMock).toHaveBeenCalledTimes(1);
189
+ // No removals should have happened
190
+ expect(removeContextMock).toHaveBeenCalledTimes(0);
191
+ });
192
+
193
+ it("re-adds context when description changes", () => {
194
+ const TestComponent: React.FC<{ description: string }> = ({
195
+ description,
196
+ }) => {
197
+ useAgentContext({ description, value: "same value" });
198
+ return <div>{description}</div>;
199
+ };
200
+
201
+ const { rerender } = render(<TestComponent description="first" />);
202
+
203
+ expect(addContextMock).toHaveBeenCalledTimes(1);
204
+ expect(addContextMock).toHaveBeenLastCalledWith({
205
+ description: "first",
206
+ value: "same value",
207
+ });
208
+
209
+ const firstContextId = addContextMock.mock.results[0]?.value;
210
+
211
+ // Change description
212
+ rerender(<TestComponent description="second" />);
213
+
214
+ // Old context removed, new context added
215
+ expect(removeContextMock).toHaveBeenCalledTimes(1);
216
+ expect(removeContextMock).toHaveBeenCalledWith(firstContextId);
217
+ expect(addContextMock).toHaveBeenCalledTimes(2);
218
+ expect(addContextMock).toHaveBeenLastCalledWith({
219
+ description: "second",
220
+ value: "same value",
221
+ });
222
+ });
223
+
224
+ it("re-adds context when value changes", () => {
225
+ const TestComponent: React.FC<{ value: string }> = ({ value }) => {
226
+ useAgentContext({ description: "same description", value });
227
+ return <div>{value}</div>;
228
+ };
229
+
230
+ const { rerender } = render(<TestComponent value="first" />);
231
+
232
+ expect(addContextMock).toHaveBeenCalledTimes(1);
233
+ const firstContextId = addContextMock.mock.results[0]?.value;
234
+
235
+ // Change value
236
+ rerender(<TestComponent value="second" />);
237
+
238
+ // Old context removed, new context added
239
+ expect(removeContextMock).toHaveBeenCalledTimes(1);
240
+ expect(removeContextMock).toHaveBeenCalledWith(firstContextId);
241
+ expect(addContextMock).toHaveBeenCalledTimes(2);
242
+ });
243
+ });
244
+
245
+ describe("JSON serialization", () => {
246
+ it("passes string values through unchanged", () => {
247
+ const TestComponent: React.FC = () => {
248
+ useAgentContext({
249
+ description: "string context",
250
+ value: "plain string value",
251
+ });
252
+ return null;
253
+ };
254
+
255
+ render(<TestComponent />);
256
+
257
+ expect(addContextMock).toHaveBeenCalledWith({
258
+ description: "string context",
259
+ value: "plain string value",
260
+ });
261
+ });
262
+
263
+ it("serializes object values to JSON", () => {
264
+ const TestComponent: React.FC = () => {
265
+ useAgentContext({
266
+ description: "object context",
267
+ value: { name: "John", age: 30 },
268
+ });
269
+ return null;
270
+ };
271
+
272
+ render(<TestComponent />);
273
+
274
+ expect(addContextMock).toHaveBeenCalledWith({
275
+ description: "object context",
276
+ value: '{"name":"John","age":30}',
277
+ });
278
+ });
279
+
280
+ it("serializes array values to JSON", () => {
281
+ const TestComponent: React.FC = () => {
282
+ useAgentContext({
283
+ description: "array context",
284
+ value: [1, 2, 3, "four"],
285
+ });
286
+ return null;
287
+ };
288
+
289
+ render(<TestComponent />);
290
+
291
+ expect(addContextMock).toHaveBeenCalledWith({
292
+ description: "array context",
293
+ value: '[1,2,3,"four"]',
294
+ });
295
+ });
296
+
297
+ it("serializes number values to JSON", () => {
298
+ const TestComponent: React.FC = () => {
299
+ useAgentContext({
300
+ description: "number context",
301
+ value: 42,
302
+ });
303
+ return null;
304
+ };
305
+
306
+ render(<TestComponent />);
307
+
308
+ expect(addContextMock).toHaveBeenCalledWith({
309
+ description: "number context",
310
+ value: "42",
311
+ });
312
+ });
313
+
314
+ it("serializes boolean values to JSON", () => {
315
+ const TestComponent: React.FC = () => {
316
+ useAgentContext({
317
+ description: "boolean context",
318
+ value: true,
319
+ });
320
+ return null;
321
+ };
322
+
323
+ render(<TestComponent />);
324
+
325
+ expect(addContextMock).toHaveBeenCalledWith({
326
+ description: "boolean context",
327
+ value: "true",
328
+ });
329
+ });
330
+
331
+ it("serializes null values to JSON", () => {
332
+ const TestComponent: React.FC = () => {
333
+ useAgentContext({
334
+ description: "null context",
335
+ value: null,
336
+ });
337
+ return null;
338
+ };
339
+
340
+ render(<TestComponent />);
341
+
342
+ expect(addContextMock).toHaveBeenCalledWith({
343
+ description: "null context",
344
+ value: "null",
345
+ });
346
+ });
347
+
348
+ it("serializes nested objects to JSON", () => {
349
+ const TestComponent: React.FC = () => {
350
+ useAgentContext({
351
+ description: "nested context",
352
+ value: {
353
+ user: {
354
+ name: "Alice",
355
+ settings: {
356
+ theme: "dark",
357
+ notifications: true,
358
+ },
359
+ },
360
+ items: [1, 2, { nested: "value" }],
361
+ },
362
+ });
363
+ return null;
364
+ };
365
+
366
+ render(<TestComponent />);
367
+
368
+ expect(addContextMock).toHaveBeenCalledWith({
369
+ description: "nested context",
370
+ value:
371
+ '{"user":{"name":"Alice","settings":{"theme":"dark","notifications":true}},"items":[1,2,{"nested":"value"}]}',
372
+ });
373
+ });
374
+ });
375
+
376
+ describe("copilotkit not available", () => {
377
+ it("does nothing when copilotkit is null", () => {
378
+ mockUseCopilotKit.mockReturnValue({
379
+ copilotkit: null,
380
+ } as any);
381
+
382
+ const TestComponent: React.FC = () => {
383
+ useAgentContext({
384
+ description: "test",
385
+ value: "test",
386
+ });
387
+ return null;
388
+ };
389
+
390
+ const { unmount } = render(<TestComponent />);
391
+
392
+ // Should not throw and should not call addContext
393
+ expect(addContextMock).not.toHaveBeenCalled();
394
+
395
+ unmount();
396
+
397
+ // Should not call removeContext either
398
+ expect(removeContextMock).not.toHaveBeenCalled();
399
+ });
400
+ });
401
+ });
@@ -0,0 +1,44 @@
1
+ import React from "react";
2
+ import { render, screen } from "@testing-library/react";
3
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
4
+ import { CopilotKitProvider } from "../../providers/CopilotKitProvider";
5
+ import { useAgent } from "../use-agent";
6
+
7
+ describe("useAgent error state", () => {
8
+ const originalFetch = global.fetch;
9
+ const originalWindow = (globalThis as { window?: unknown }).window;
10
+
11
+ beforeEach(() => {
12
+ // Simulate browser environment
13
+ (globalThis as { window?: unknown }).window = {};
14
+ // Mock fetch to reject (simulates runtime unreachable)
15
+ global.fetch = vi.fn().mockRejectedValue(new Error("network failure"));
16
+ });
17
+
18
+ afterEach(() => {
19
+ vi.restoreAllMocks();
20
+ global.fetch = originalFetch;
21
+ if (originalWindow === undefined) {
22
+ delete (globalThis as { window?: unknown }).window;
23
+ } else {
24
+ (globalThis as { window?: unknown }).window = originalWindow;
25
+ }
26
+ });
27
+
28
+ it("returns a provisional agent instead of throwing when runtime is in error state", async () => {
29
+ function TestComponent() {
30
+ const { agent } = useAgent({ agentId: "nonexistent" });
31
+ return <div data-testid="agent-id">{agent.agentId}</div>;
32
+ }
33
+
34
+ render(
35
+ <CopilotKitProvider runtimeUrl="http://localhost:59999/nonexistent">
36
+ <TestComponent />
37
+ </CopilotKitProvider>,
38
+ );
39
+
40
+ // Should render without crashing — agent is provisional
41
+ const el = await screen.findByTestId("agent-id");
42
+ expect(el.textContent).toBe("nonexistent");
43
+ });
44
+ });
@@ -0,0 +1,205 @@
1
+ import React from "react";
2
+ import { render } from "@testing-library/react";
3
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
4
+ import { AbstractAgent } from "@ag-ui/client";
5
+ import { useCopilotKit } from "../../providers/CopilotKitProvider";
6
+ import { MockStepwiseAgent } from "../../__tests__/utils/test-helpers";
7
+ import { useAgent } from "../use-agent";
8
+ import { CopilotKitCoreRuntimeConnectionStatus } from "@copilotkit/core";
9
+
10
+ // Mock the CopilotKitProvider to control copilotkit state directly
11
+ vi.mock("../../providers/CopilotKitProvider", () => ({
12
+ useCopilotKit: vi.fn(),
13
+ }));
14
+
15
+ const mockUseCopilotKit = useCopilotKit as ReturnType<typeof vi.fn>;
16
+
17
+ /**
18
+ * Tests for useAgent referential stability during runtime connection lifecycle.
19
+ *
20
+ * Bug: useAgent creates multiple ProxiedCopilotRuntimeAgent instances during
21
+ * Disconnected→Connecting→Connected transitions because the useMemo recalculates
22
+ * on every dependency change and creates a new agent each time.
23
+ */
24
+ describe("useAgent stability during runtime connection", () => {
25
+ let mockCopilotkit: {
26
+ getAgent: ReturnType<typeof vi.fn>;
27
+ runtimeUrl: string | undefined;
28
+ runtimeConnectionStatus: CopilotKitCoreRuntimeConnectionStatus;
29
+ runtimeTransport: string;
30
+ headers: Record<string, string>;
31
+ agents: Record<string, AbstractAgent>;
32
+ };
33
+
34
+ beforeEach(() => {
35
+ mockCopilotkit = {
36
+ getAgent: vi.fn(() => undefined),
37
+ runtimeUrl: "http://localhost:3000/api/copilotkit",
38
+ runtimeConnectionStatus:
39
+ CopilotKitCoreRuntimeConnectionStatus.Disconnected,
40
+ runtimeTransport: "rest",
41
+ headers: {},
42
+ agents: {},
43
+ };
44
+
45
+ mockUseCopilotKit.mockReturnValue({
46
+ copilotkit: mockCopilotkit,
47
+ executingToolCallIds: new Set(),
48
+ });
49
+ });
50
+
51
+ afterEach(() => {
52
+ vi.restoreAllMocks();
53
+ });
54
+
55
+ it("should reuse the same provisional agent across re-renders during Disconnected→Connecting", () => {
56
+ const agentInstances: AbstractAgent[] = [];
57
+
58
+ function AgentTracker() {
59
+ const { agent } = useAgent({ agentId: "test-agent" });
60
+ if (
61
+ agentInstances.length === 0 ||
62
+ agentInstances[agentInstances.length - 1] !== agent
63
+ ) {
64
+ agentInstances.push(agent);
65
+ }
66
+ return <div>{agent.threadId}</div>;
67
+ }
68
+
69
+ // Render 1: Disconnected — creates provisional agent
70
+ const { rerender } = render(<AgentTracker />);
71
+ expect(agentInstances.length).toBe(1);
72
+ const provisionalThreadId = agentInstances[0]!.threadId;
73
+
74
+ // Render 2: Connecting — should reuse same provisional agent
75
+ mockCopilotkit.runtimeConnectionStatus =
76
+ CopilotKitCoreRuntimeConnectionStatus.Connecting;
77
+ rerender(<AgentTracker />);
78
+
79
+ // BUG: Current code creates a new agent instance here (agentInstances.length === 2)
80
+ // FIX: Should still be 1 (same provisional reused)
81
+ expect(agentInstances.length).toBe(1);
82
+ expect(agentInstances[0]!.threadId).toBe(provisionalThreadId);
83
+ });
84
+
85
+ it("should reuse provisional agent when headers change during connecting", () => {
86
+ const agentInstances: AbstractAgent[] = [];
87
+
88
+ function AgentTracker() {
89
+ const { agent } = useAgent({ agentId: "test-agent" });
90
+ if (
91
+ agentInstances.length === 0 ||
92
+ agentInstances[agentInstances.length - 1] !== agent
93
+ ) {
94
+ agentInstances.push(agent);
95
+ }
96
+ return <div>{agent.threadId}</div>;
97
+ }
98
+
99
+ // Render 1: Disconnected
100
+ const { rerender } = render(<AgentTracker />);
101
+ expect(agentInstances.length).toBe(1);
102
+
103
+ // Render 2: Connecting
104
+ mockCopilotkit.runtimeConnectionStatus =
105
+ CopilotKitCoreRuntimeConnectionStatus.Connecting;
106
+ rerender(<AgentTracker />);
107
+
108
+ // Render 3: Headers change (e.g., auth token set)
109
+ mockCopilotkit.headers = { "X-CopilotCloud-Public-Api-Key": "test-key" };
110
+ rerender(<AgentTracker />);
111
+
112
+ // Render 4: Another minor change
113
+ mockCopilotkit.headers = {
114
+ "X-CopilotCloud-Public-Api-Key": "test-key",
115
+ "X-Custom": "value",
116
+ };
117
+ rerender(<AgentTracker />);
118
+
119
+ // BUG: Current code creates a new agent on each re-render (agentInstances.length >= 3)
120
+ // FIX: Should still be 1 (same provisional reused throughout connecting phase)
121
+ expect(agentInstances.length).toBe(1);
122
+ });
123
+
124
+ it("should keep the same agent instance across the full Disconnected→Connected lifecycle", () => {
125
+ const agentInstances: AbstractAgent[] = [];
126
+
127
+ function AgentTracker() {
128
+ const { agent } = useAgent({ agentId: "test-agent" });
129
+ if (
130
+ agentInstances.length === 0 ||
131
+ agentInstances[agentInstances.length - 1] !== agent
132
+ ) {
133
+ agentInstances.push(agent);
134
+ }
135
+ return <div>{agent.threadId}</div>;
136
+ }
137
+
138
+ // Phase 1: Disconnected — provisional created
139
+ const { rerender } = render(<AgentTracker />);
140
+ const provisionalThreadId = agentInstances[0]!.threadId;
141
+
142
+ // Phase 2: Connecting
143
+ mockCopilotkit.runtimeConnectionStatus =
144
+ CopilotKitCoreRuntimeConnectionStatus.Connecting;
145
+ rerender(<AgentTracker />);
146
+
147
+ // Phase 3: Headers change during connecting
148
+ mockCopilotkit.headers = { "X-Auth": "token" };
149
+ rerender(<AgentTracker />);
150
+
151
+ // Phase 4: Connected — registered agent now available
152
+ const registeredAgent = new MockStepwiseAgent();
153
+ registeredAgent.agentId = "test-agent";
154
+ registeredAgent.description = "Agent from /info";
155
+
156
+ mockCopilotkit.getAgent.mockReturnValue(registeredAgent);
157
+ mockCopilotkit.runtimeConnectionStatus =
158
+ CopilotKitCoreRuntimeConnectionStatus.Connected;
159
+ mockCopilotkit.agents = { "test-agent": registeredAgent };
160
+ rerender(<AgentTracker />);
161
+
162
+ // Phase 5: agents notification (separate re-render in real app)
163
+ rerender(<AgentTracker />);
164
+
165
+ // 2 instances: 1 provisional (Disconnected/Connecting) + 1 registered (Connected).
166
+ // The provisional is stable across all pre-connection renders.
167
+ // CopilotChat's connect guard ensures connect fires only once (when Connected),
168
+ // so the agent reference change doesn't cause a duplicate connect.
169
+ expect(agentInstances.length).toBe(2);
170
+ // First instance was the provisional
171
+ expect(agentInstances[0]!.threadId).toBe(provisionalThreadId);
172
+ // Second instance is the registered agent
173
+ expect(agentInstances[1]).toBe(registeredAgent);
174
+ });
175
+
176
+ it("should return local dev agents directly without a provisional", () => {
177
+ const localAgent = new MockStepwiseAgent();
178
+ localAgent.agentId = "local-agent";
179
+
180
+ // Simulate agents__unsafe_dev_only: no runtimeUrl, agent found immediately
181
+ mockCopilotkit.runtimeUrl = undefined;
182
+ mockCopilotkit.getAgent.mockReturnValue(localAgent);
183
+ mockCopilotkit.agents = { "local-agent": localAgent };
184
+
185
+ const agentInstances: AbstractAgent[] = [];
186
+
187
+ function AgentTracker() {
188
+ const { agent } = useAgent({ agentId: "local-agent" });
189
+ if (
190
+ agentInstances.length === 0 ||
191
+ agentInstances[agentInstances.length - 1] !== agent
192
+ ) {
193
+ agentInstances.push(agent);
194
+ }
195
+ return <div>{agent.threadId}</div>;
196
+ }
197
+
198
+ const { rerender } = render(<AgentTracker />);
199
+ rerender(<AgentTracker />);
200
+
201
+ // Local agent is returned directly — exactly 1 instance, the original
202
+ expect(agentInstances.length).toBe(1);
203
+ expect(agentInstances[0]).toBe(localAgent);
204
+ });
205
+ });