@copilotkit/react-core 0.0.0-main-20260220223427 → 0.0.0-main-20260403195251

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 (186) hide show
  1. package/CHANGELOG.md +540 -71
  2. package/dist/copilotkit-BK_zLoVm.mjs +7661 -0
  3. package/dist/copilotkit-BK_zLoVm.mjs.map +1 -0
  4. package/dist/copilotkit-BYNyIuE7.d.cts +2208 -0
  5. package/dist/copilotkit-BYNyIuE7.d.cts.map +1 -0
  6. package/dist/copilotkit-BYNyIuE7.d.ts +2208 -0
  7. package/dist/copilotkit-BYNyIuE7.d.ts.map +1 -0
  8. package/dist/copilotkit-CDZGGOIB.cjs +8074 -0
  9. package/dist/copilotkit-CDZGGOIB.cjs.map +1 -0
  10. package/dist/copilotkit-rBCfdqIo.d.mts +2208 -0
  11. package/dist/copilotkit-rBCfdqIo.d.mts.map +1 -0
  12. package/dist/index.cjs +166 -2200
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +14 -674
  15. package/dist/index.d.cts.map +1 -1
  16. package/dist/index.d.mts +14 -674
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.d.ts +667 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.mjs +119 -2124
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/index.umd.js +2252 -230
  23. package/dist/index.umd.js.map +1 -1
  24. package/dist/v2/index.cjs +78 -6
  25. package/dist/v2/index.css +1 -2
  26. package/dist/v2/index.d.cts +6 -2
  27. package/dist/v2/index.d.mts +6 -2
  28. package/dist/v2/index.d.ts +6 -0
  29. package/dist/v2/index.mjs +8 -3
  30. package/dist/v2/index.umd.js +7786 -12
  31. package/dist/v2/index.umd.js.map +1 -0
  32. package/package.json +66 -39
  33. package/scripts/scope-preflight.mjs +100 -0
  34. package/src/components/CopilotListeners.tsx +2 -6
  35. package/src/components/copilot-provider/__tests__/copilot-messages-key.test.tsx +92 -0
  36. package/src/components/copilot-provider/copilot-messages.tsx +1 -1
  37. package/src/components/copilot-provider/copilotkit-props.tsx +1 -1
  38. package/src/components/copilot-provider/copilotkit.tsx +120 -68
  39. package/src/context/copilot-messages-context.tsx +1 -1
  40. package/src/hooks/__tests__/use-coagent-config.test.ts +2 -2
  41. package/src/hooks/__tests__/use-coagent-state-render.e2e.test.tsx +5 -6
  42. package/src/hooks/__tests__/use-copilot-chat-internal-connect.test.tsx +242 -0
  43. package/src/hooks/__tests__/use-frontend-tool-available.test.tsx +1 -1
  44. package/src/hooks/__tests__/use-frontend-tool-remount.e2e.test.tsx +4 -4
  45. package/src/hooks/index.ts +0 -1
  46. package/src/hooks/use-agent-nodename.ts +1 -1
  47. package/src/hooks/use-coagent-state-render-bridge.tsx +1 -4
  48. package/src/hooks/use-coagent.ts +1 -1
  49. package/src/hooks/use-configure-chat-suggestions.tsx +2 -2
  50. package/src/hooks/use-copilot-chat-suggestions.tsx +2 -2
  51. package/src/hooks/use-copilot-chat_internal.ts +73 -13
  52. package/src/hooks/use-copilot-readable.ts +1 -1
  53. package/src/hooks/use-frontend-tool.ts +2 -2
  54. package/src/hooks/use-human-in-the-loop.ts +2 -2
  55. package/src/hooks/use-langgraph-interrupt.ts +95 -38
  56. package/src/hooks/use-lazy-tool-renderer.tsx +1 -1
  57. package/src/hooks/use-render-tool-call.ts +1 -1
  58. package/src/lib/copilot-task.ts +1 -1
  59. package/src/setupTests.ts +18 -14
  60. package/src/types/interrupt-action.ts +5 -0
  61. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +176 -0
  62. package/src/v2/__tests__/globalSetup.ts +14 -0
  63. package/src/v2/__tests__/setup.ts +93 -0
  64. package/src/v2/__tests__/utils/test-helpers.tsx +503 -0
  65. package/src/v2/a2ui/A2UIMessageRenderer.tsx +206 -0
  66. package/src/v2/components/CopilotKitInspector.tsx +50 -0
  67. package/src/v2/components/MCPAppsActivityRenderer.tsx +785 -0
  68. package/src/v2/components/WildcardToolCallRender.tsx +86 -0
  69. package/src/v2/components/__tests__/license-warning-banner.test.tsx +46 -0
  70. package/src/v2/components/chat/CopilotChat.tsx +433 -0
  71. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +375 -0
  72. package/src/v2/components/chat/CopilotChatAudioRecorder.tsx +350 -0
  73. package/src/v2/components/chat/CopilotChatInput.tsx +1302 -0
  74. package/src/v2/components/chat/CopilotChatMessageView.tsx +561 -0
  75. package/src/v2/components/chat/CopilotChatReasoningMessage.tsx +252 -0
  76. package/src/v2/components/chat/CopilotChatSuggestionPill.tsx +59 -0
  77. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +133 -0
  78. package/src/v2/components/chat/CopilotChatToggleButton.tsx +171 -0
  79. package/src/v2/components/chat/CopilotChatToolCallsView.tsx +40 -0
  80. package/src/v2/components/chat/CopilotChatUserMessage.tsx +388 -0
  81. package/src/v2/components/chat/CopilotChatView.tsx +598 -0
  82. package/src/v2/components/chat/CopilotModalHeader.tsx +129 -0
  83. package/src/v2/components/chat/CopilotPopup.tsx +81 -0
  84. package/src/v2/components/chat/CopilotPopupView.tsx +317 -0
  85. package/src/v2/components/chat/CopilotSidebar.tsx +76 -0
  86. package/src/v2/components/chat/CopilotSidebarView.tsx +255 -0
  87. package/src/v2/components/chat/__tests__/CopilotChat.e2e.test.tsx +1113 -0
  88. package/src/v2/components/chat/__tests__/CopilotChat.onError.test.tsx +73 -0
  89. package/src/v2/components/chat/__tests__/CopilotChat.slots.e2e.test.tsx +432 -0
  90. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +150 -0
  91. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.slots.e2e.test.tsx +624 -0
  92. package/src/v2/components/chat/__tests__/CopilotChatAssistantMessage.test.tsx +702 -0
  93. package/src/v2/components/chat/__tests__/CopilotChatCssClasses.test.tsx +107 -0
  94. package/src/v2/components/chat/__tests__/CopilotChatInput.slots.e2e.test.tsx +929 -0
  95. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +986 -0
  96. package/src/v2/components/chat/__tests__/CopilotChatMessageView.slots.e2e.test.tsx +1004 -0
  97. package/src/v2/components/chat/__tests__/CopilotChatMessageView.test.tsx +169 -0
  98. package/src/v2/components/chat/__tests__/CopilotChatSuggestionView.slots.e2e.test.tsx +530 -0
  99. package/src/v2/components/chat/__tests__/CopilotChatToolRendering.e2e.test.tsx +785 -0
  100. package/src/v2/components/chat/__tests__/CopilotChatToolRerenders.e2e.test.tsx +2416 -0
  101. package/src/v2/components/chat/__tests__/CopilotChatUserMessage.slots.e2e.test.tsx +621 -0
  102. package/src/v2/components/chat/__tests__/CopilotChatView.onClick.e2e.test.tsx +853 -0
  103. package/src/v2/components/chat/__tests__/CopilotChatView.slots.e2e.test.tsx +1050 -0
  104. package/src/v2/components/chat/__tests__/CopilotModalHeader.slots.e2e.test.tsx +484 -0
  105. package/src/v2/components/chat/__tests__/CopilotPopupView.slots.e2e.test.tsx +612 -0
  106. package/src/v2/components/chat/__tests__/CopilotSidebarView.slots.e2e.test.tsx +502 -0
  107. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +1027 -0
  108. package/src/v2/components/chat/__tests__/setup.ts +1 -0
  109. package/src/v2/components/chat/index.ts +79 -0
  110. package/src/v2/components/index.ts +7 -0
  111. package/src/v2/components/license-warning-banner.tsx +198 -0
  112. package/src/v2/components/ui/button.tsx +123 -0
  113. package/src/v2/components/ui/dropdown-menu.tsx +258 -0
  114. package/src/v2/components/ui/tooltip.tsx +60 -0
  115. package/src/v2/hooks/__tests__/standard-schema-types.test.tsx +152 -0
  116. package/src/v2/hooks/__tests__/standard-schema.test.tsx +282 -0
  117. package/src/v2/hooks/__tests__/use-agent-context-timing.e2e.test.tsx +140 -0
  118. package/src/v2/hooks/__tests__/use-agent-context.test.tsx +401 -0
  119. package/src/v2/hooks/__tests__/use-agent-error-state.test.tsx +44 -0
  120. package/src/v2/hooks/__tests__/use-agent-stability.test.tsx +205 -0
  121. package/src/v2/hooks/__tests__/use-agent-thread-isolation.test.tsx +327 -0
  122. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +728 -0
  123. package/src/v2/hooks/__tests__/use-agent.e2e.test.tsx +159 -0
  124. package/src/v2/hooks/__tests__/use-component.test.tsx +123 -0
  125. package/src/v2/hooks/__tests__/use-configure-suggestions.e2e.test.tsx +696 -0
  126. package/src/v2/hooks/__tests__/use-default-render-tool.test.tsx +153 -0
  127. package/src/v2/hooks/__tests__/use-frontend-tool-available.test.tsx +167 -0
  128. package/src/v2/hooks/__tests__/use-frontend-tool.e2e.test.tsx +2148 -0
  129. package/src/v2/hooks/__tests__/use-human-in-the-loop.e2e.test.tsx +1261 -0
  130. package/src/v2/hooks/__tests__/use-interrupt.test.tsx +397 -0
  131. package/src/v2/hooks/__tests__/use-katex-styles.test.tsx +56 -0
  132. package/src/v2/hooks/__tests__/use-keyboard-height.test.tsx +192 -0
  133. package/src/v2/hooks/__tests__/use-render-tool.test.tsx +259 -0
  134. package/src/v2/hooks/__tests__/use-suggestions.e2e.test.tsx +524 -0
  135. package/src/v2/hooks/__tests__/use-threads.test.tsx +433 -0
  136. package/src/v2/hooks/__tests__/zod-regression.test.tsx +311 -0
  137. package/src/v2/hooks/index.ts +18 -0
  138. package/src/v2/hooks/use-agent-context.tsx +45 -0
  139. package/src/v2/hooks/use-agent.tsx +358 -0
  140. package/src/v2/hooks/use-component.tsx +89 -0
  141. package/src/v2/hooks/use-configure-suggestions.tsx +187 -0
  142. package/src/v2/hooks/use-default-render-tool.tsx +254 -0
  143. package/src/v2/hooks/use-frontend-tool.tsx +43 -0
  144. package/src/v2/hooks/use-human-in-the-loop.tsx +81 -0
  145. package/src/v2/hooks/use-interrupt.tsx +305 -0
  146. package/src/v2/hooks/use-keyboard-height.tsx +67 -0
  147. package/src/v2/hooks/use-render-activity-message.tsx +73 -0
  148. package/src/v2/hooks/use-render-custom-messages.tsx +98 -0
  149. package/src/v2/hooks/use-render-tool-call.tsx +175 -0
  150. package/src/v2/hooks/use-render-tool.tsx +181 -0
  151. package/src/v2/hooks/use-suggestions.tsx +91 -0
  152. package/src/v2/hooks/use-threads.tsx +256 -0
  153. package/src/v2/hooks/useKatexStyles.ts +27 -0
  154. package/src/v2/index.css +1 -1
  155. package/src/v2/index.ts +21 -2
  156. package/src/v2/lib/__tests__/completePartialMarkdown.test.ts +495 -0
  157. package/src/v2/lib/__tests__/renderSlot.test.tsx +588 -0
  158. package/src/v2/lib/react-core.ts +156 -0
  159. package/src/v2/lib/slots.tsx +143 -0
  160. package/src/v2/lib/transcription-client.ts +184 -0
  161. package/src/v2/lib/utils.ts +8 -0
  162. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +162 -0
  163. package/src/v2/providers/CopilotKitProvider.tsx +600 -0
  164. package/src/v2/providers/__tests__/CopilotChatConfigurationProvider.test.tsx +546 -0
  165. package/src/v2/providers/__tests__/CopilotKitProvider.license.test.tsx +101 -0
  166. package/src/v2/providers/__tests__/CopilotKitProvider.onError.test.tsx +69 -0
  167. package/src/v2/providers/__tests__/CopilotKitProvider.renderCustomMessages.e2e.test.tsx +881 -0
  168. package/src/v2/providers/__tests__/CopilotKitProvider.stability.test.tsx +740 -0
  169. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +642 -0
  170. package/src/v2/providers/__tests__/CopilotKitProvider.wildcard.test.tsx +294 -0
  171. package/src/v2/providers/index.ts +14 -0
  172. package/src/v2/styles/globals.css +231 -0
  173. package/src/v2/types/__tests__/defineToolCallRenderer.test.tsx +525 -0
  174. package/src/v2/types/defineToolCallRenderer.ts +65 -0
  175. package/src/v2/types/frontend-tool.ts +8 -0
  176. package/src/v2/types/human-in-the-loop.ts +33 -0
  177. package/src/v2/types/index.ts +7 -0
  178. package/src/v2/types/interrupt.ts +15 -0
  179. package/src/v2/types/react-activity-message-renderer.ts +27 -0
  180. package/src/v2/types/react-custom-message-renderer.ts +17 -0
  181. package/src/v2/types/react-tool-call-renderer.ts +32 -0
  182. package/tsdown.config.ts +34 -10
  183. package/vitest.config.mjs +4 -3
  184. package/LICENSE +0 -21
  185. package/dist/v2/index.css.map +0 -1
  186. package/src/hooks/use-langgraph-interrupt-render.ts +0 -147
@@ -0,0 +1,728 @@
1
+ import React from "react";
2
+ import { render, act, screen } from "@testing-library/react";
3
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
4
+ import { useAgent, UseAgentUpdate } from "../use-agent";
5
+ import { useCopilotKit } from "../../providers/CopilotKitProvider";
6
+ import { MockStepwiseAgent } from "../../__tests__/utils/test-helpers";
7
+ import { CopilotKitCoreRuntimeConnectionStatus } from "@copilotkit/core";
8
+ import type { Message } from "@ag-ui/core";
9
+ import type { RunAgentInput } from "@ag-ui/client";
10
+
11
+ vi.mock("../../providers/CopilotKitProvider", () => ({
12
+ useCopilotKit: vi.fn(),
13
+ }));
14
+
15
+ vi.mock("../../providers/CopilotChatConfigurationProvider", () => ({
16
+ useCopilotChatConfiguration: vi.fn(() => undefined),
17
+ }));
18
+
19
+ const mockUseCopilotKit = useCopilotKit as ReturnType<typeof vi.fn>;
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Message factories — eliminates `as any` on every message literal
23
+ // ---------------------------------------------------------------------------
24
+
25
+ function userMsg(id: string, content = `msg-${id}`): Message {
26
+ return { id, role: "user" as const, content };
27
+ }
28
+
29
+ function assistantMsg(id: string, content = `msg-${id}`): Message {
30
+ return { id, role: "assistant" as const, content };
31
+ }
32
+
33
+ /** Create N alternating user/assistant messages (ids "1" … "N") */
34
+ function createMessages(count: number): Message[] {
35
+ return Array.from({ length: count }, (_, i) =>
36
+ i % 2 === 0
37
+ ? userMsg(String(i + 1), `tok${i + 1}`)
38
+ : assistantMsg(String(i + 1), `tok${i + 1}`),
39
+ );
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Subscriber notification helpers
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /** Helper: fire onMessagesChanged on all agent subscribers */
47
+ function notifyMessagesChanged(agent: MockStepwiseAgent) {
48
+ agent.subscribers.forEach((s) =>
49
+ s.onMessagesChanged?.({
50
+ messages: agent.messages,
51
+ state: agent.state,
52
+ agent,
53
+ }),
54
+ );
55
+ }
56
+
57
+ /** Helper: fire onStateChanged on all agent subscribers */
58
+ function notifyStateChanged(agent: MockStepwiseAgent) {
59
+ agent.subscribers.forEach((s) =>
60
+ s.onStateChanged?.({
61
+ state: agent.state,
62
+ messages: agent.messages,
63
+ agent,
64
+ }),
65
+ );
66
+ }
67
+
68
+ function createMockRunAgentInput(
69
+ overrides?: Partial<RunAgentInput>,
70
+ ): RunAgentInput {
71
+ return {
72
+ threadId: "t-1",
73
+ runId: "r-1",
74
+ state: {},
75
+ messages: [],
76
+ tools: [],
77
+ context: [],
78
+ forwardedProps: {},
79
+ ...overrides,
80
+ };
81
+ }
82
+
83
+ /** Helper: fire onRunInitialized on all agent subscribers */
84
+ function notifyRunInitialized(agent: MockStepwiseAgent) {
85
+ agent.subscribers.forEach((s) =>
86
+ s.onRunInitialized?.({
87
+ messages: agent.messages,
88
+ state: agent.state,
89
+ agent,
90
+ input: createMockRunAgentInput(),
91
+ }),
92
+ );
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // Test component factory
97
+ // ---------------------------------------------------------------------------
98
+
99
+ /** Helper: create a test component that tracks render count */
100
+ function createTestComponent(
101
+ options: {
102
+ updates?: UseAgentUpdate[];
103
+ throttleMs?: number;
104
+ renderCount?: { current: number };
105
+ } = {},
106
+ ) {
107
+ const {
108
+ updates = [UseAgentUpdate.OnMessagesChanged],
109
+ throttleMs,
110
+ renderCount,
111
+ } = options;
112
+
113
+ return function TestComponent() {
114
+ if (renderCount) renderCount.current++;
115
+ const { agent } = useAgent({
116
+ agentId: "test-agent",
117
+ updates,
118
+ throttleMs,
119
+ });
120
+ return (
121
+ <>
122
+ <div data-testid="count">{agent.messages.length}</div>
123
+ <div data-testid="state">{JSON.stringify(agent.state)}</div>
124
+ </>
125
+ );
126
+ };
127
+ }
128
+
129
+ describe("useAgent throttleMs", () => {
130
+ let mockAgent: MockStepwiseAgent;
131
+
132
+ beforeEach(() => {
133
+ vi.useFakeTimers();
134
+ mockAgent = new MockStepwiseAgent();
135
+ mockAgent.agentId = "test-agent";
136
+
137
+ mockUseCopilotKit.mockReturnValue({
138
+ copilotkit: {
139
+ getAgent: () => mockAgent,
140
+ runtimeUrl: "http://localhost:3000/api/copilot",
141
+ runtimeConnectionStatus:
142
+ CopilotKitCoreRuntimeConnectionStatus.Connected,
143
+ runtimeTransport: "rest",
144
+ headers: {},
145
+ agents: { "test-agent": mockAgent },
146
+ },
147
+ executingToolCallIds: new Set(),
148
+ });
149
+ });
150
+
151
+ afterEach(() => {
152
+ vi.useRealTimers();
153
+ vi.restoreAllMocks();
154
+ });
155
+
156
+ it("without throttleMs, component reflects latest messages after notification", () => {
157
+ const TestComponent = createTestComponent();
158
+
159
+ render(<TestComponent />);
160
+ expect(screen.getByTestId("count").textContent).toBe("0");
161
+
162
+ act(() => {
163
+ mockAgent.messages = [userMsg("1", "hello")];
164
+ notifyMessagesChanged(mockAgent);
165
+ });
166
+
167
+ expect(screen.getByTestId("count").textContent).toBe("1");
168
+ });
169
+
170
+ it("with throttleMs: 0 (explicit), behaves identically to omitting throttleMs", () => {
171
+ const TestComponent = createTestComponent({ throttleMs: 0 });
172
+
173
+ render(<TestComponent />);
174
+ expect(screen.getByTestId("count").textContent).toBe("0");
175
+
176
+ act(() => {
177
+ mockAgent.messages = [userMsg("1", "hello")];
178
+ notifyMessagesChanged(mockAgent);
179
+ });
180
+
181
+ expect(screen.getByTestId("count").textContent).toBe("1");
182
+
183
+ // Second notification also fires immediately (no throttle)
184
+ act(() => {
185
+ mockAgent.messages = [userMsg("1", "hello"), assistantMsg("2", "world")];
186
+ notifyMessagesChanged(mockAgent);
187
+ });
188
+
189
+ expect(screen.getByTestId("count").textContent).toBe("2");
190
+ });
191
+
192
+ it("with throttleMs, first notification fires immediately (leading edge)", () => {
193
+ const TestComponent = createTestComponent({ throttleMs: 100 });
194
+
195
+ render(<TestComponent />);
196
+ expect(screen.getByTestId("count").textContent).toBe("0");
197
+
198
+ act(() => {
199
+ mockAgent.messages = [userMsg("1", "hello")];
200
+ notifyMessagesChanged(mockAgent);
201
+ });
202
+
203
+ expect(screen.getByTestId("count").textContent).toBe("1");
204
+ });
205
+
206
+ it("with throttleMs, second notification within window is deferred until trailing edge", () => {
207
+ const TestComponent = createTestComponent({ throttleMs: 100 });
208
+
209
+ render(<TestComponent />);
210
+
211
+ // First notification — leading edge, fires immediately
212
+ act(() => {
213
+ mockAgent.messages = [userMsg("1", "a")];
214
+ notifyMessagesChanged(mockAgent);
215
+ });
216
+ expect(screen.getByTestId("count").textContent).toBe("1");
217
+
218
+ // Second notification 10ms later — within throttle window
219
+ act(() => {
220
+ vi.advanceTimersByTime(10);
221
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
222
+ notifyMessagesChanged(mockAgent);
223
+ });
224
+
225
+ // The throttle should have deferred this — component still shows 1
226
+ expect(screen.getByTestId("count").textContent).toBe("1");
227
+
228
+ // Advance past the throttle window — trailing edge fires
229
+ act(() => {
230
+ vi.advanceTimersByTime(100);
231
+ });
232
+ expect(screen.getByTestId("count").textContent).toBe("2");
233
+ });
234
+
235
+ it("with throttleMs, rapid burst of many notifications results in exactly 2 renders (leading + trailing)", () => {
236
+ const renderCount = { current: 0 };
237
+ const TestComponent = createTestComponent({ throttleMs: 100, renderCount });
238
+
239
+ render(<TestComponent />);
240
+ const rendersAfterMount = renderCount.current;
241
+
242
+ // Leading edge — fires immediately
243
+ act(() => {
244
+ mockAgent.messages = [userMsg("1", "tok1")];
245
+ notifyMessagesChanged(mockAgent);
246
+ });
247
+ expect(renderCount.current).toBe(rendersAfterMount + 1);
248
+
249
+ // Fire 10 rapid notifications within the throttle window (1ms apart)
250
+ for (let i = 2; i <= 11; i++) {
251
+ act(() => {
252
+ vi.advanceTimersByTime(1);
253
+ mockAgent.messages = createMessages(i);
254
+ notifyMessagesChanged(mockAgent);
255
+ });
256
+ }
257
+
258
+ // Should still be at leading-edge render count (burst was coalesced)
259
+ expect(renderCount.current).toBe(rendersAfterMount + 1);
260
+ expect(screen.getByTestId("count").textContent).toBe("1");
261
+
262
+ // Advance past the throttle window — trailing edge fires once
263
+ act(() => {
264
+ vi.advanceTimersByTime(100);
265
+ });
266
+ expect(renderCount.current).toBe(rendersAfterMount + 2);
267
+ expect(screen.getByTestId("count").textContent).toBe("11");
268
+ });
269
+
270
+ it("with throttleMs, new notification after trailing edge fires immediately (new cycle)", () => {
271
+ const TestComponent = createTestComponent({ throttleMs: 100 });
272
+
273
+ render(<TestComponent />);
274
+
275
+ // Leading edge
276
+ act(() => {
277
+ mockAgent.messages = [userMsg("1", "a")];
278
+ notifyMessagesChanged(mockAgent);
279
+ });
280
+ expect(screen.getByTestId("count").textContent).toBe("1");
281
+
282
+ // Second notification — deferred
283
+ act(() => {
284
+ vi.advanceTimersByTime(10);
285
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
286
+ notifyMessagesChanged(mockAgent);
287
+ });
288
+
289
+ // Trailing edge fires
290
+ act(() => {
291
+ vi.advanceTimersByTime(100);
292
+ });
293
+ expect(screen.getByTestId("count").textContent).toBe("2");
294
+
295
+ // New notification well after the window — should fire immediately as a new leading edge
296
+ act(() => {
297
+ vi.advanceTimersByTime(200);
298
+ mockAgent.messages = [
299
+ userMsg("1", "a"),
300
+ assistantMsg("2", "b"),
301
+ userMsg("3", "c"),
302
+ ];
303
+ notifyMessagesChanged(mockAgent);
304
+ });
305
+ expect(screen.getByTestId("count").textContent).toBe("3");
306
+ });
307
+
308
+ it("with throttleMs, onStateChanged still fires immediately", () => {
309
+ const TestComponent = createTestComponent({
310
+ updates: [
311
+ UseAgentUpdate.OnMessagesChanged,
312
+ UseAgentUpdate.OnStateChanged,
313
+ ],
314
+ throttleMs: 100,
315
+ });
316
+
317
+ render(<TestComponent />);
318
+
319
+ // Fire onMessagesChanged to start the throttle window
320
+ act(() => {
321
+ mockAgent.messages = [userMsg("1", "a")];
322
+ notifyMessagesChanged(mockAgent);
323
+ });
324
+
325
+ // Fire onStateChanged 10ms later — should render immediately, not throttled
326
+ act(() => {
327
+ vi.advanceTimersByTime(10);
328
+ mockAgent.state = { count: 42 };
329
+ notifyStateChanged(mockAgent);
330
+ });
331
+
332
+ expect(screen.getByTestId("state").textContent).toBe('{"count":42}');
333
+ });
334
+
335
+ it("with throttleMs, pending trailing timer does not fire after unmount", () => {
336
+ const renderCount = { current: 0 };
337
+ const TestComponent = createTestComponent({ throttleMs: 100, renderCount });
338
+
339
+ const { unmount } = render(<TestComponent />);
340
+
341
+ // Leading edge — fires immediately
342
+ act(() => {
343
+ mockAgent.messages = [userMsg("1", "a")];
344
+ notifyMessagesChanged(mockAgent);
345
+ });
346
+
347
+ // Second notification — schedules trailing timer
348
+ act(() => {
349
+ vi.advanceTimersByTime(10);
350
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
351
+ notifyMessagesChanged(mockAgent);
352
+ });
353
+
354
+ const countBeforeUnmount = renderCount.current;
355
+
356
+ // Unmount before trailing fires
357
+ unmount();
358
+
359
+ // Advancing past the window should NOT cause additional renders
360
+ act(() => {
361
+ vi.advanceTimersByTime(100);
362
+ });
363
+
364
+ expect(renderCount.current).toBe(countBeforeUnmount);
365
+ });
366
+
367
+ it("with throttleMs and updates excluding OnMessagesChanged, throttle is a no-op", () => {
368
+ const TestComponent = createTestComponent({
369
+ updates: [UseAgentUpdate.OnStateChanged],
370
+ throttleMs: 100,
371
+ });
372
+
373
+ render(<TestComponent />);
374
+
375
+ // Only onStateChanged is subscribed — should fire immediately
376
+ act(() => {
377
+ mockAgent.state = { value: "test" };
378
+ notifyStateChanged(mockAgent);
379
+ });
380
+
381
+ expect(screen.getByTestId("state").textContent).toBe('{"value":"test"}');
382
+
383
+ // No onMessagesChanged subscription should exist
384
+ act(() => {
385
+ mockAgent.messages = [userMsg("1", "a")];
386
+ notifyMessagesChanged(mockAgent);
387
+ });
388
+
389
+ // onMessagesChanged was sent but no handler is subscribed, so no
390
+ // re-render is triggered. We verify by checking state still shows the
391
+ // last rendered value.
392
+ expect(screen.getByTestId("state").textContent).toBe('{"value":"test"}');
393
+ });
394
+
395
+ it.each([
396
+ { label: "NaN", value: NaN },
397
+ { label: "Infinity", value: Infinity },
398
+ { label: "-1", value: -1 },
399
+ { label: "-Infinity", value: -Infinity },
400
+ ])(
401
+ "with invalid throttleMs ($label), falls back to unthrottled and warns",
402
+ ({ value }) => {
403
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
404
+ const TestComponent = createTestComponent({ throttleMs: value });
405
+
406
+ render(<TestComponent />);
407
+
408
+ // Should warn about the invalid value
409
+ expect(errorSpy).toHaveBeenCalledWith(
410
+ expect.stringContaining(
411
+ "throttleMs must be a non-negative finite number",
412
+ ),
413
+ );
414
+
415
+ // Should behave as unthrottled — every notification fires immediately
416
+ act(() => {
417
+ mockAgent.messages = [userMsg("1", "a")];
418
+ notifyMessagesChanged(mockAgent);
419
+ });
420
+ expect(screen.getByTestId("count").textContent).toBe("1");
421
+
422
+ act(() => {
423
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
424
+ notifyMessagesChanged(mockAgent);
425
+ });
426
+ expect(screen.getByTestId("count").textContent).toBe("2");
427
+ },
428
+ );
429
+
430
+ it("trailing-edge render reflects the latest messages, not stale data", () => {
431
+ const TestComponent = createTestComponent({ throttleMs: 100 });
432
+ render(<TestComponent />);
433
+
434
+ // Leading edge
435
+ act(() => {
436
+ mockAgent.messages = [userMsg("1", "A")];
437
+ notifyMessagesChanged(mockAgent);
438
+ });
439
+ expect(screen.getByTestId("count").textContent).toBe("1");
440
+
441
+ // Multiple deferred notifications with increasing messages
442
+ act(() => {
443
+ vi.advanceTimersByTime(20);
444
+ mockAgent.messages = [userMsg("1", "A"), assistantMsg("2", "B")];
445
+ notifyMessagesChanged(mockAgent);
446
+ });
447
+
448
+ act(() => {
449
+ vi.advanceTimersByTime(20);
450
+ mockAgent.messages = [
451
+ userMsg("1", "A"),
452
+ assistantMsg("2", "B"),
453
+ assistantMsg("3", "C"),
454
+ ];
455
+ notifyMessagesChanged(mockAgent);
456
+ });
457
+
458
+ // Still deferred
459
+ expect(screen.getByTestId("count").textContent).toBe("1");
460
+
461
+ // Trailing edge fires — must show all 3 messages (latest state)
462
+ act(() => {
463
+ vi.advanceTimersByTime(100);
464
+ });
465
+ expect(screen.getByTestId("count").textContent).toBe("3");
466
+ });
467
+
468
+ it("trailing edge fires at exactly throttleMs after the leading edge", () => {
469
+ const TestComponent = createTestComponent({ throttleMs: 100 });
470
+ render(<TestComponent />);
471
+
472
+ // Leading edge at T=0
473
+ act(() => {
474
+ mockAgent.messages = [userMsg("1", "a")];
475
+ notifyMessagesChanged(mockAgent);
476
+ });
477
+ expect(screen.getByTestId("count").textContent).toBe("1");
478
+
479
+ // Deferred notification at T=40
480
+ act(() => {
481
+ vi.advanceTimersByTime(40);
482
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
483
+ notifyMessagesChanged(mockAgent);
484
+ });
485
+ expect(screen.getByTestId("count").textContent).toBe("1");
486
+
487
+ // At T=99, trailing has NOT fired yet
488
+ act(() => {
489
+ vi.advanceTimersByTime(59);
490
+ });
491
+ expect(screen.getByTestId("count").textContent).toBe("1");
492
+
493
+ // At T=100, trailing fires
494
+ act(() => {
495
+ vi.advanceTimersByTime(1);
496
+ });
497
+ expect(screen.getByTestId("count").textContent).toBe("2");
498
+ });
499
+
500
+ it("changing throttleMs cleans up pending timers from the previous configuration", () => {
501
+ function DynamicThrottleComponent({ throttleMs }: { throttleMs: number }) {
502
+ const { agent } = useAgent({
503
+ agentId: "test-agent",
504
+ updates: [UseAgentUpdate.OnMessagesChanged],
505
+ throttleMs,
506
+ });
507
+ return <div data-testid="count">{agent.messages.length}</div>;
508
+ }
509
+
510
+ const { rerender } = render(<DynamicThrottleComponent throttleMs={200} />);
511
+
512
+ // Leading edge
513
+ act(() => {
514
+ mockAgent.messages = [userMsg("1", "a")];
515
+ notifyMessagesChanged(mockAgent);
516
+ });
517
+ expect(screen.getByTestId("count").textContent).toBe("1");
518
+
519
+ // Deferred notification — pending timer set for 200ms
520
+ act(() => {
521
+ vi.advanceTimersByTime(50);
522
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
523
+ notifyMessagesChanged(mockAgent);
524
+ });
525
+ expect(screen.getByTestId("count").textContent).toBe("1");
526
+
527
+ // Change throttleMs — effect re-runs, old 200ms timer should be cleaned up
528
+ rerender(<DynamicThrottleComponent throttleMs={50} />);
529
+
530
+ // New notification fires as leading edge under the new 50ms throttle
531
+ act(() => {
532
+ mockAgent.messages = [
533
+ userMsg("1", "a"),
534
+ assistantMsg("2", "b"),
535
+ userMsg("3", "c"),
536
+ ];
537
+ notifyMessagesChanged(mockAgent);
538
+ });
539
+ expect(screen.getByTestId("count").textContent).toBe("3");
540
+
541
+ // Advance past what would have been the old 200ms trailing edge —
542
+ // no ghost render should occur from the old timer
543
+ act(() => {
544
+ vi.advanceTimersByTime(200);
545
+ });
546
+ expect(screen.getByTestId("count").textContent).toBe("3");
547
+ });
548
+
549
+ it("notification immediately after trailing edge is throttled (trailing restarts the window)", () => {
550
+ const renderCount = { current: 0 };
551
+ const TestComponent = createTestComponent({ throttleMs: 100, renderCount });
552
+
553
+ render(<TestComponent />);
554
+ const rendersAfterMount = renderCount.current;
555
+
556
+ // T=0: Leading edge fires immediately
557
+ act(() => {
558
+ mockAgent.messages = [userMsg("1", "a")];
559
+ notifyMessagesChanged(mockAgent);
560
+ });
561
+ expect(renderCount.current).toBe(rendersAfterMount + 1);
562
+ expect(screen.getByTestId("count").textContent).toBe("1");
563
+
564
+ // T=10: Deferred notification — schedules trailing
565
+ act(() => {
566
+ vi.advanceTimersByTime(10);
567
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
568
+ notifyMessagesChanged(mockAgent);
569
+ });
570
+
571
+ // T=100: Trailing fires (render #2) and restarts window
572
+ act(() => {
573
+ vi.advanceTimersByTime(90);
574
+ });
575
+ expect(renderCount.current).toBe(rendersAfterMount + 2);
576
+ expect(screen.getByTestId("count").textContent).toBe("2");
577
+
578
+ // T=101: Notification 1ms after trailing — should be DEFERRED (within new window), not immediate
579
+ act(() => {
580
+ vi.advanceTimersByTime(1);
581
+ mockAgent.messages = [
582
+ userMsg("1", "a"),
583
+ assistantMsg("2", "b"),
584
+ userMsg("3", "c"),
585
+ ];
586
+ notifyMessagesChanged(mockAgent);
587
+ });
588
+ // Still 2 — the notification was deferred, not a new leading edge
589
+ expect(renderCount.current).toBe(rendersAfterMount + 2);
590
+ expect(screen.getByTestId("count").textContent).toBe("2");
591
+
592
+ // T=200: New trailing fires (render #3)
593
+ act(() => {
594
+ vi.advanceTimersByTime(99);
595
+ });
596
+ expect(renderCount.current).toBe(rendersAfterMount + 3);
597
+ expect(screen.getByTestId("count").textContent).toBe("3");
598
+ });
599
+
600
+ it("cleans up all subscriptions after unmount", () => {
601
+ const TestComponent = createTestComponent({
602
+ updates: [
603
+ UseAgentUpdate.OnMessagesChanged,
604
+ UseAgentUpdate.OnStateChanged,
605
+ ],
606
+ throttleMs: 100,
607
+ });
608
+
609
+ const subscriberCountBefore = mockAgent.subscribers.length;
610
+ const { unmount } = render(<TestComponent />);
611
+
612
+ // Should have added subscriber(s)
613
+ expect(mockAgent.subscribers.length).toBeGreaterThan(subscriberCountBefore);
614
+
615
+ unmount();
616
+
617
+ // All subscriptions should be cleaned up
618
+ expect(mockAgent.subscribers.length).toBe(subscriberCountBefore);
619
+ });
620
+
621
+ it("single notification within window does not trigger a trailing re-render", () => {
622
+ const renderCount = { current: 0 };
623
+ const TestComponent = createTestComponent({ throttleMs: 100, renderCount });
624
+
625
+ render(<TestComponent />);
626
+ const rendersAfterMount = renderCount.current;
627
+
628
+ // Leading edge — fires immediately
629
+ act(() => {
630
+ mockAgent.messages = [userMsg("1", "a")];
631
+ notifyMessagesChanged(mockAgent);
632
+ });
633
+ expect(renderCount.current).toBe(rendersAfterMount + 1);
634
+
635
+ // Advance well past the throttle window — no trailing should fire
636
+ act(() => {
637
+ vi.advanceTimersByTime(200);
638
+ });
639
+
640
+ // No additional render since there was no second notification
641
+ expect(renderCount.current).toBe(rendersAfterMount + 1);
642
+ });
643
+
644
+ it("with throttleMs, onRunInitialized still fires immediately during throttle window", () => {
645
+ const renderCount = { current: 0 };
646
+ const TestComponent = createTestComponent({
647
+ updates: [
648
+ UseAgentUpdate.OnMessagesChanged,
649
+ UseAgentUpdate.OnRunStatusChanged,
650
+ ],
651
+ throttleMs: 100,
652
+ renderCount,
653
+ });
654
+
655
+ render(<TestComponent />);
656
+ const rendersAfterMount = renderCount.current;
657
+
658
+ // Fire onMessagesChanged to start the throttle window
659
+ act(() => {
660
+ mockAgent.messages = [userMsg("1", "a")];
661
+ notifyMessagesChanged(mockAgent);
662
+ });
663
+ expect(renderCount.current).toBe(rendersAfterMount + 1);
664
+
665
+ // Fire onRunInitialized 10ms later — should render immediately
666
+ act(() => {
667
+ vi.advanceTimersByTime(10);
668
+ notifyRunInitialized(mockAgent);
669
+ });
670
+
671
+ // Run status notification is NOT throttled — renders immediately
672
+ expect(renderCount.current).toBe(rendersAfterMount + 2);
673
+ });
674
+
675
+ it("changing throttleMs from positive to 0 disables throttling immediately", () => {
676
+ function DynamicThrottleComponent({ throttleMs }: { throttleMs: number }) {
677
+ const { agent } = useAgent({
678
+ agentId: "test-agent",
679
+ updates: [UseAgentUpdate.OnMessagesChanged],
680
+ throttleMs,
681
+ });
682
+ return <div data-testid="count">{agent.messages.length}</div>;
683
+ }
684
+
685
+ const { rerender } = render(<DynamicThrottleComponent throttleMs={200} />);
686
+
687
+ // Leading edge with throttle active
688
+ act(() => {
689
+ mockAgent.messages = [userMsg("1", "a")];
690
+ notifyMessagesChanged(mockAgent);
691
+ });
692
+ expect(screen.getByTestId("count").textContent).toBe("1");
693
+
694
+ // Deferred notification — within throttle window
695
+ act(() => {
696
+ vi.advanceTimersByTime(50);
697
+ mockAgent.messages = [userMsg("1", "a"), assistantMsg("2", "b")];
698
+ notifyMessagesChanged(mockAgent);
699
+ });
700
+ expect(screen.getByTestId("count").textContent).toBe("1");
701
+
702
+ // Switch to unthrottled
703
+ rerender(<DynamicThrottleComponent throttleMs={0} />);
704
+
705
+ // Both notifications should fire immediately now
706
+ act(() => {
707
+ mockAgent.messages = [
708
+ userMsg("1", "a"),
709
+ assistantMsg("2", "b"),
710
+ userMsg("3", "c"),
711
+ ];
712
+ notifyMessagesChanged(mockAgent);
713
+ });
714
+ expect(screen.getByTestId("count").textContent).toBe("3");
715
+
716
+ // Second immediate notification also fires (no coalescing)
717
+ act(() => {
718
+ mockAgent.messages = [
719
+ userMsg("1", "a"),
720
+ assistantMsg("2", "b"),
721
+ userMsg("3", "c"),
722
+ assistantMsg("4", "d"),
723
+ ];
724
+ notifyMessagesChanged(mockAgent);
725
+ });
726
+ expect(screen.getByTestId("count").textContent).toBe("4");
727
+ });
728
+ });