@copilotkit/react-core 1.55.0-next.9 → 1.55.1-next.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 (81) hide show
  1. package/CHANGELOG.md +46 -6
  2. package/dist/{copilotkit-DeOzjPsb.mjs → copilotkit-BY5S1-0P.mjs} +2402 -552
  3. package/dist/copilotkit-BY5S1-0P.mjs.map +1 -0
  4. package/dist/{copilotkit-BqcyhQjT.d.mts → copilotkit-BuhSUZHb.d.mts} +228 -17
  5. package/dist/copilotkit-BuhSUZHb.d.mts.map +1 -0
  6. package/dist/{copilotkit-BDNjFNmk.cjs → copilotkit-Bz5-ImDl.cjs} +2421 -541
  7. package/dist/copilotkit-Bz5-ImDl.cjs.map +1 -0
  8. package/dist/{copilotkit-l-IBF4Xp.d.cts → copilotkit-dwDWYpya.d.cts} +228 -17
  9. package/dist/copilotkit-dwDWYpya.d.cts.map +1 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.mts +1 -1
  13. package/dist/index.mjs +1 -1
  14. package/dist/index.umd.js +1400 -238
  15. package/dist/index.umd.js.map +1 -1
  16. package/dist/v2/index.cjs +13 -1
  17. package/dist/v2/index.css +1 -1
  18. package/dist/v2/index.d.cts +3 -3
  19. package/dist/v2/index.d.mts +3 -3
  20. package/dist/v2/index.mjs +3 -2
  21. package/dist/v2/index.umd.js +2442 -552
  22. package/dist/v2/index.umd.js.map +1 -1
  23. package/package.json +62 -54
  24. package/scripts/scope-preflight.mjs +1 -2
  25. package/src/components/CopilotListeners.tsx +41 -8
  26. package/src/components/copilot-provider/copilotkit-props.tsx +4 -2
  27. package/src/components/toast/toast-provider.tsx +269 -194
  28. package/src/v2/__tests__/A2UIMessageRenderer.test.tsx +86 -22
  29. package/src/v2/__tests__/utils/test-helpers.tsx +67 -0
  30. package/src/v2/a2ui/A2UICatalogContext.tsx +79 -0
  31. package/src/v2/a2ui/A2UIMessageRenderer.tsx +125 -37
  32. package/src/v2/a2ui/A2UIToolCallRenderer.tsx +290 -0
  33. package/src/v2/components/CopilotKitInspector.tsx +2 -0
  34. package/src/v2/components/OpenGenerativeUIRenderer.tsx +598 -0
  35. package/src/v2/components/__tests__/OpenGenerativeUIRenderer.test.tsx +665 -0
  36. package/src/v2/components/chat/CopilotChat.tsx +193 -50
  37. package/src/v2/components/chat/CopilotChatAssistantMessage.tsx +17 -2
  38. package/src/v2/components/chat/CopilotChatAttachmentQueue.tsx +481 -0
  39. package/src/v2/components/chat/CopilotChatAttachmentRenderer.tsx +139 -0
  40. package/src/v2/components/chat/CopilotChatInput.tsx +146 -77
  41. package/src/v2/components/chat/CopilotChatMessageView.tsx +253 -149
  42. package/src/v2/components/chat/CopilotChatSuggestionView.tsx +1 -0
  43. package/src/v2/components/chat/CopilotChatUserMessage.tsx +54 -0
  44. package/src/v2/components/chat/CopilotChatView.tsx +179 -66
  45. package/src/v2/components/chat/__tests__/CopilotChat.attachments.test.tsx +168 -0
  46. package/src/v2/components/chat/__tests__/CopilotChatActivityRendering.e2e.test.tsx +63 -2
  47. package/src/v2/components/chat/__tests__/CopilotChatInput.test.tsx +544 -1
  48. package/src/v2/components/chat/__tests__/CopilotChatPerf.e2e.test.tsx +268 -0
  49. package/src/v2/components/chat/__tests__/CopilotChatPropsRerender.e2e.test.tsx +249 -0
  50. package/src/v2/components/chat/__tests__/MCPAppsActivityRenderer.e2e.test.tsx +43 -2
  51. package/src/v2/components/chat/__tests__/copilot-chat-throttle.test.tsx +138 -0
  52. package/src/v2/components/chat/index.ts +9 -0
  53. package/src/v2/components/chat/scroll-element-context.ts +13 -0
  54. package/src/v2/hooks/__tests__/use-agent-throttle.test.tsx +1003 -0
  55. package/src/v2/hooks/__tests__/use-attachments.test.tsx +169 -0
  56. package/src/v2/hooks/__tests__/use-threads.test.tsx +54 -0
  57. package/src/v2/hooks/index.ts +5 -0
  58. package/src/v2/hooks/use-agent.tsx +95 -10
  59. package/src/v2/hooks/use-attachments.tsx +269 -0
  60. package/src/v2/hooks/use-frontend-tool.tsx +5 -2
  61. package/src/v2/hooks/use-render-activity-message.tsx +9 -2
  62. package/src/v2/hooks/use-threads.tsx +35 -15
  63. package/src/v2/index.ts +5 -1
  64. package/src/v2/lib/__tests__/processPartialHtml.test.ts +112 -0
  65. package/src/v2/lib/__tests__/slots.test.ts +56 -0
  66. package/src/v2/lib/processPartialHtml.ts +45 -0
  67. package/src/v2/lib/slots.tsx +42 -1
  68. package/src/v2/providers/CopilotChatConfigurationProvider.tsx +9 -3
  69. package/src/v2/providers/CopilotKitProvider.tsx +268 -32
  70. package/src/v2/providers/SandboxFunctionsContext.ts +10 -0
  71. package/src/v2/providers/__tests__/CopilotKitProvider.sandboxFunctions.test.tsx +198 -0
  72. package/src/v2/providers/__tests__/CopilotKitProvider.test.tsx +71 -0
  73. package/src/v2/providers/index.ts +7 -0
  74. package/src/v2/styles/globals.css +2 -1
  75. package/src/v2/types/index.ts +1 -0
  76. package/src/v2/types/sandbox-function.ts +11 -0
  77. package/dist/copilotkit-BDNjFNmk.cjs.map +0 -1
  78. package/dist/copilotkit-BqcyhQjT.d.mts.map +0 -1
  79. package/dist/copilotkit-DeOzjPsb.mjs.map +0 -1
  80. package/dist/copilotkit-l-IBF4Xp.d.cts.map +0 -1
  81. package/src/v2/components/__tests__/license-warning-banner.test.tsx +0 -46
@@ -0,0 +1,268 @@
1
+ import React from "react";
2
+ import { act, screen, fireEvent, waitFor } from "@testing-library/react";
3
+ import {
4
+ MockStepwiseAgent,
5
+ renderWithCopilotKit,
6
+ runStartedEvent,
7
+ runFinishedEvent,
8
+ textChunkEvent,
9
+ stateSnapshotEvent,
10
+ generateMessages,
11
+ } from "../../../__tests__/utils/test-helpers";
12
+ import { CopilotChat } from "../CopilotChat";
13
+ import { CopilotChatAssistantMessage } from "../CopilotChatAssistantMessage";
14
+ import CopilotChatMessageView from "../CopilotChatMessageView";
15
+ import { ScrollElementContext } from "../scroll-element-context";
16
+ import type { Message } from "@ag-ui/core";
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // Spy component — must be module-level so its reference is stable across
20
+ // renders. MemoizedAssistantMessage's custom comparator bails out if
21
+ // AssistantMessageComponent changes reference, so an unstable spy would
22
+ // produce false positives.
23
+ // ---------------------------------------------------------------------------
24
+ const renderCounts = new Map<string, number>();
25
+
26
+ const SpyAssistantMessage = (
27
+ props: React.ComponentProps<typeof CopilotChatAssistantMessage>,
28
+ ) => {
29
+ renderCounts.set(
30
+ props.message.id,
31
+ (renderCounts.get(props.message.id) ?? 0) + 1,
32
+ );
33
+ return React.createElement(CopilotChatAssistantMessage, props);
34
+ };
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // Helpers
38
+ // ---------------------------------------------------------------------------
39
+
40
+ /** Render CopilotChat with the spy wired in as the assistant message component. */
41
+ function renderWithSpy(agent: MockStepwiseAgent) {
42
+ return renderWithCopilotKit({
43
+ agent,
44
+ children: (
45
+ <div style={{ height: 400 }}>
46
+ <CopilotChat
47
+ welcomeScreen={false}
48
+ messageView={
49
+ {
50
+ assistantMessage:
51
+ SpyAssistantMessage as unknown as typeof CopilotChatAssistantMessage,
52
+ } as any
53
+ }
54
+ />
55
+ </div>
56
+ ),
57
+ });
58
+ }
59
+
60
+ /**
61
+ * Submit a dummy user message so CopilotChat calls agent.run() and subscribes
62
+ * to the Subject. Without this, emitted events are dropped since nothing is
63
+ * listening to the observable yet.
64
+ */
65
+ async function triggerRun() {
66
+ const input = await screen.findByRole("textbox");
67
+ fireEvent.change(input, { target: { value: "go" } });
68
+ fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
69
+ // Wait for the user message to appear in the DOM before emitting agent events
70
+ await waitFor(() => {
71
+ expect(screen.getByText("go")).toBeDefined();
72
+ });
73
+ }
74
+
75
+ /**
76
+ * Trigger a run then emit generateMessages(n) and wait for all n assistant
77
+ * messages to have been rendered at least once by the spy.
78
+ */
79
+ async function emitBatch(agent: MockStepwiseAgent, n: number) {
80
+ await triggerRun();
81
+
82
+ agent.emit(runStartedEvent());
83
+ for (const event of generateMessages(n)) {
84
+ agent.emit(event);
85
+ }
86
+ // Don't call agent.complete() — that terminates the Subject and subsequent
87
+ // agent.emit() calls would be silently dropped. runFinishedEvent() alone is
88
+ // sufficient to mark the run as done without closing the stream.
89
+ agent.emit(runFinishedEvent());
90
+
91
+ await waitFor(
92
+ () => {
93
+ expect(renderCounts.size).toBeGreaterThanOrEqual(n);
94
+ },
95
+ { timeout: 10_000 },
96
+ );
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Tests
101
+ // ---------------------------------------------------------------------------
102
+
103
+ // Note: the virtual render path (useVirtualizer, activated above VIRTUALIZE_THRESHOLD=50)
104
+ // is not exercised here. jsdom always returns clientHeight=0, which causes the
105
+ // jsdom guard in CopilotChatMessageView to skip virtualization. The 100-message
106
+ // test below runs the flat path even at 100 messages. Browser/Playwright tests
107
+ // are required to cover the virtual path.
108
+ //
109
+ // Note: the MemoizedAssistantMessage comparator is not tested for the case where
110
+ // a non-last message's content changes after being committed. A bug returning
111
+ // `true` (bail-out) in that scenario would cause stale renders silently.
112
+
113
+ describe("CopilotChat perf — re-render regression", () => {
114
+ beforeEach(() => {
115
+ renderCounts.clear();
116
+ });
117
+
118
+ it("completed messages do not re-render when a new message is added", async () => {
119
+ const agent = new MockStepwiseAgent();
120
+ renderWithSpy(agent);
121
+
122
+ await emitBatch(agent, 20);
123
+
124
+ const baselineCounts = new Map(renderCounts);
125
+ expect(baselineCounts.size).toBeGreaterThan(0);
126
+
127
+ // Add one fresh assistant message in a second run
128
+ const newMsgId = "perf-new-assistant-msg";
129
+ agent.emit(runStartedEvent());
130
+ agent.emit(textChunkEvent(newMsgId, "A brand new message"));
131
+ agent.emit(runFinishedEvent());
132
+ agent.complete();
133
+
134
+ await waitFor(() => {
135
+ expect(renderCounts.get(newMsgId)).toBeGreaterThan(0);
136
+ });
137
+
138
+ // None of the original 20 assistant messages should have re-rendered
139
+ for (const [id, count] of baselineCounts) {
140
+ expect(renderCounts.get(id)).toBe(count);
141
+ }
142
+ });
143
+
144
+ it("completed messages do not re-render when a state snapshot arrives", async () => {
145
+ const agent = new MockStepwiseAgent();
146
+ renderWithSpy(agent);
147
+
148
+ await emitBatch(agent, 10);
149
+
150
+ const baselineCounts = new Map(renderCounts);
151
+
152
+ // STATE_SNAPSHOT triggers forceUpdate inside CopilotChatMessageView.
153
+ // With deduplicatedMessages memoized on [messages], the same messages
154
+ // array reference is passed down and MemoizedAssistantMessage wrappers
155
+ // should not re-render.
156
+ agent.emit(stateSnapshotEvent({ counter: 1 }));
157
+ agent.emit(stateSnapshotEvent({ counter: 2 }));
158
+
159
+ // Flush React's update queue so all snapshot-triggered re-renders are
160
+ // committed before we inspect render counts. The Observable subscription
161
+ // ends after RUN_FINISHED so we cannot use a sentinel message to create a
162
+ // positive signal; act+tick is the idiomatic jsdom alternative.
163
+ await act(async () => {
164
+ await new Promise<void>((r) => setTimeout(r, 50));
165
+ });
166
+
167
+ // None of the original 10 assistant messages should have re-rendered
168
+ for (const [id, count] of baselineCounts) {
169
+ expect(renderCounts.get(id)).toBe(count);
170
+ }
171
+ });
172
+
173
+ it("virtual path: renders only a window of messages above VIRTUALIZE_THRESHOLD", async () => {
174
+ const TOTAL = 60; // above VIRTUALIZE_THRESHOLD (50)
175
+
176
+ // Create a fake scroll element that passes two jsdom guards:
177
+ // 1. clientHeight > 0 — our guard in CopilotChatMessageView
178
+ // 2. getBoundingClientRect().height > 0 — TanStack Virtual calls this
179
+ // immediately in observeElementRect() to set the viewport size. Without
180
+ // this, it overrides initialRect with { height: 0 } and renders no items.
181
+ const fakeScrollEl = document.createElement("div");
182
+ Object.defineProperty(fakeScrollEl, "clientHeight", {
183
+ get: () => 600,
184
+ configurable: true,
185
+ });
186
+ fakeScrollEl.getBoundingClientRect = () =>
187
+ ({
188
+ height: 600,
189
+ width: 800,
190
+ top: 0,
191
+ left: 0,
192
+ bottom: 600,
193
+ right: 800,
194
+ x: 0,
195
+ y: 0,
196
+ toJSON: () => ({}),
197
+ }) as DOMRect;
198
+
199
+ const messages: Message[] = Array.from({ length: TOTAL }, (_, i) => ({
200
+ id: `virt-msg-${i}`,
201
+ role: "assistant" as const,
202
+ content: `Message ${i}`,
203
+ }));
204
+
205
+ const { unmount } = renderWithCopilotKit({
206
+ children: (
207
+ <ScrollElementContext.Provider value={fakeScrollEl}>
208
+ <div style={{ height: 600 }}>
209
+ <CopilotChatMessageView messages={messages} />
210
+ </div>
211
+ </ScrollElementContext.Provider>
212
+ ),
213
+ });
214
+
215
+ await waitFor(() => {
216
+ // The virtual container div (position:relative, height = estimateSize × count)
217
+ // must exist — this confirms the virtual code path activated.
218
+ const virtualContainer = document.querySelector(
219
+ '[data-testid="copilot-message-list"] > div[style*="position: relative"]',
220
+ );
221
+ expect(virtualContainer).not.toBeNull();
222
+ // jsdom can't measure the viewport (getBoundingClientRect returns {height:0}
223
+ // for child elements that TanStack Virtual measures internally), so
224
+ // getVirtualItems() returns []. nodes.length === 0, which is still less
225
+ // than TOTAL — virtualization is active even if the window is empty in jsdom.
226
+ const nodes = document.querySelectorAll("[data-message-id]");
227
+ expect(nodes.length).toBeLessThan(TOTAL);
228
+ });
229
+
230
+ // Drain pending animation frames before unmounting. TanStack Virtual
231
+ // schedules rAF callbacks for measurement; if they fire after jsdom tears
232
+ // down (window === null) they produce a spurious uncaught exception.
233
+ await act(async () => {
234
+ await new Promise<void>((r) => requestAnimationFrame(() => r()));
235
+ await new Promise<void>((r) => requestAnimationFrame(() => r()));
236
+ });
237
+ unmount();
238
+ });
239
+
240
+ it("renders 100 messages without error and within 5 s", async () => {
241
+ const agent = new MockStepwiseAgent();
242
+ renderWithCopilotKit({ agent });
243
+
244
+ await triggerRun();
245
+
246
+ const start = performance.now();
247
+
248
+ agent.emit(runStartedEvent());
249
+ for (const event of generateMessages(100)) {
250
+ agent.emit(event);
251
+ }
252
+ agent.emit(runFinishedEvent());
253
+ agent.complete();
254
+
255
+ await waitFor(
256
+ () => {
257
+ const nodes = document.querySelectorAll("[data-message-id]");
258
+ expect(nodes.length).toBeGreaterThanOrEqual(100);
259
+ },
260
+ { timeout: 5_000 },
261
+ );
262
+
263
+ const elapsed = performance.now() - start;
264
+ // 5 000 ms is a generous CI-safe ceiling; the /perf page is the right tool
265
+ // for tighter measurements against browser rendering.
266
+ expect(elapsed).toBeLessThan(5_000);
267
+ });
268
+ });
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Regression tests for FOR-75: messageView / labels props freeze
3
+ *
4
+ * These tests prove that passing `messageView` or `labels` as inline props
5
+ * to CopilotChat does NOT cause completed assistant messages to re-render on
6
+ * every keystroke.
7
+ *
8
+ * Tests FAIL on unfixed code (reproducing the bug).
9
+ * Tests PASS after the fix is applied.
10
+ *
11
+ * Render counts are deterministic regardless of hardware — the bug is about
12
+ * reference instability, not wall-clock timing.
13
+ */
14
+ import React from "react";
15
+ import {
16
+ render,
17
+ screen,
18
+ fireEvent,
19
+ waitFor,
20
+ act,
21
+ } from "@testing-library/react";
22
+ import {
23
+ AbstractAgent,
24
+ EventType,
25
+ type BaseEvent,
26
+ type RunAgentInput,
27
+ } from "@ag-ui/client";
28
+ import { Observable, Subject } from "rxjs";
29
+ import { CopilotKitProvider } from "../../../providers/CopilotKitProvider";
30
+ import { CopilotChat } from "../CopilotChat";
31
+ import { CopilotChatAssistantMessage } from "../CopilotChatAssistantMessage";
32
+ import { useCopilotChatConfiguration } from "../../../providers/CopilotChatConfigurationProvider";
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Shared mock agent (same pattern as CopilotChatToolRerenders.e2e.test.tsx)
36
+ // ---------------------------------------------------------------------------
37
+ class MockStepwiseAgent extends AbstractAgent {
38
+ private subject = new Subject<BaseEvent>();
39
+
40
+ emit(event: BaseEvent) {
41
+ if (event.type === EventType.RUN_STARTED) {
42
+ this.isRunning = true;
43
+ } else if (
44
+ event.type === EventType.RUN_FINISHED ||
45
+ event.type === EventType.RUN_ERROR
46
+ ) {
47
+ this.isRunning = false;
48
+ }
49
+ act(() => {
50
+ this.subject.next(event);
51
+ });
52
+ }
53
+
54
+ complete() {
55
+ this.isRunning = false;
56
+ this.subject.complete();
57
+ }
58
+
59
+ clone(): MockStepwiseAgent {
60
+ const cloned = new MockStepwiseAgent();
61
+ cloned.agentId = this.agentId;
62
+ (cloned as unknown as { subject: Subject<BaseEvent> }).subject =
63
+ this.subject;
64
+ return cloned;
65
+ }
66
+
67
+ async detachActiveRun(): Promise<void> {}
68
+
69
+ run(_input: RunAgentInput): Observable<BaseEvent> {
70
+ return this.subject.asObservable();
71
+ }
72
+ }
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Helper: submit a user message (triggers agent.run()), then emit a complete
76
+ // assistant response and wait for the counting component to appear in the DOM.
77
+ //
78
+ // Uses data-testid rather than text content to avoid false positives from
79
+ // components that render fixed strings regardless of the message payload.
80
+ // ---------------------------------------------------------------------------
81
+ async function submitAndReceiveAssistantMessage(
82
+ agent: MockStepwiseAgent,
83
+ messageId: string,
84
+ ) {
85
+ const input = await screen.findByRole("textbox");
86
+ fireEvent.change(input, { target: { value: "hello" } });
87
+ fireEvent.keyDown(input, { key: "Enter", code: "Enter" });
88
+
89
+ await waitFor(() => {
90
+ expect(screen.getByText("hello")).toBeDefined();
91
+ });
92
+
93
+ agent.emit({ type: EventType.RUN_STARTED } as BaseEvent);
94
+ agent.emit({
95
+ type: EventType.TEXT_MESSAGE_CHUNK,
96
+ messageId,
97
+ delta: "assistant reply",
98
+ } as BaseEvent);
99
+ agent.emit({ type: EventType.RUN_FINISHED } as BaseEvent);
100
+
101
+ await waitFor(() => {
102
+ expect(screen.getByTestId("counting-assistant")).toBeDefined();
103
+ });
104
+
105
+ await act(async () => {
106
+ agent.complete();
107
+ });
108
+ }
109
+
110
+ // ---------------------------------------------------------------------------
111
+ // Test 1 — messageView inline object
112
+ //
113
+ // Counting component defined OUTSIDE the test so its function reference is
114
+ // stable. The outer messageView object is inline (new ref on every render),
115
+ // which is what triggers the bug.
116
+ // ---------------------------------------------------------------------------
117
+ let assistantRenderCount = 0;
118
+ function CountingAssistantMessage(
119
+ _props: React.ComponentProps<typeof CopilotChatAssistantMessage>,
120
+ ) {
121
+ assistantRenderCount++;
122
+ return <div data-testid="counting-assistant" />;
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // Test 2 — labels inline object
127
+ //
128
+ // Reads directly from useCopilotChatConfiguration() so that context churn
129
+ // (caused by the labels fix being absent) is observable independently of
130
+ // whether the messageView slot is re-rendered. Context consumers re-render
131
+ // when their context value changes regardless of parent memoization, so this
132
+ // is a genuine guard for the labels stabilization fix.
133
+ // ---------------------------------------------------------------------------
134
+ let labelConsumerRenderCount = 0;
135
+ function LabelConsumerMessage(
136
+ _props: React.ComponentProps<typeof CopilotChatAssistantMessage>,
137
+ ) {
138
+ useCopilotChatConfiguration(); // subscribe to CopilotChatConfiguration context
139
+ labelConsumerRenderCount++;
140
+ return <div data-testid="counting-assistant" />;
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // Tests
145
+ // ---------------------------------------------------------------------------
146
+
147
+ describe("FOR-75: messageView / labels props — no re-renders on input change", () => {
148
+ beforeEach(() => {
149
+ assistantRenderCount = 0;
150
+ labelConsumerRenderCount = 0;
151
+ });
152
+
153
+ /**
154
+ * Test 1: messageView inline object
155
+ *
156
+ * When `messageView` is passed as an inline object prop (e.g.
157
+ * `messageView={{ assistantMessage: Cmp }}`), a new object reference is
158
+ * created on every parent render. Without the fix, ts-deepmerge clones the
159
+ * value, producing a new reference that defeats MemoizedSlotWrapper's
160
+ * shallow equality check → the whole message list re-renders on every
161
+ * keystroke.
162
+ *
163
+ * Fix: useShallowStableRef in CopilotChat.tsx keeps the same object
164
+ * reference as long as the slot props are shallowly equal.
165
+ */
166
+ it("messageView inline object: completed messages do not re-render on keystroke", async () => {
167
+ const agent = new MockStepwiseAgent();
168
+
169
+ render(
170
+ <CopilotKitProvider agents__unsafe_dev_only={{ default: agent }}>
171
+ <div style={{ height: 400 }}>
172
+ <CopilotChat
173
+ messageView={{
174
+ assistantMessage:
175
+ CountingAssistantMessage as unknown as typeof CopilotChatAssistantMessage,
176
+ }}
177
+ />
178
+ </div>
179
+ </CopilotKitProvider>,
180
+ );
181
+
182
+ await submitAndReceiveAssistantMessage(agent, "msg-1");
183
+
184
+ const renderCountAfterMessage = assistantRenderCount;
185
+ expect(renderCountAfterMessage).toBeGreaterThan(0);
186
+
187
+ // Type into the input — only inputValue state changes; messages unchanged.
188
+ // Completed messages must NOT re-render.
189
+ const input = screen.getByRole("textbox");
190
+ fireEvent.change(input, { target: { value: "a" } });
191
+ fireEvent.change(input, { target: { value: "ab" } });
192
+ fireEvent.change(input, { target: { value: "abc" } });
193
+
194
+ await act(async () => {});
195
+
196
+ expect(assistantRenderCount).toBe(renderCountAfterMessage);
197
+ });
198
+
199
+ /**
200
+ * Test 2: labels inline object
201
+ *
202
+ * When `labels` is passed as an inline object, it is a new reference every
203
+ * render. Without the fix, this invalidates the mergedLabels useMemo in
204
+ * CopilotChatConfigurationProvider → new context value → all context
205
+ * consumers re-render on every keystroke.
206
+ *
207
+ * LabelConsumerMessage reads directly from useCopilotChatConfiguration(),
208
+ * making it a genuine guard for this fix: context consumers re-render when
209
+ * their context value changes regardless of parent memo boundaries, so
210
+ * labelConsumerRenderCount increases if the labels fix is regressed.
211
+ *
212
+ * Fix: useJsonStable in CopilotChatConfigurationProvider stabilizes the
213
+ * labels reference so the context value doesn't change when the caller
214
+ * passes an inline object.
215
+ */
216
+ it("labels inline object: context consumers do not re-render on keystroke", async () => {
217
+ const agent = new MockStepwiseAgent();
218
+
219
+ render(
220
+ <CopilotKitProvider agents__unsafe_dev_only={{ default: agent }}>
221
+ <div style={{ height: 400 }}>
222
+ <CopilotChat
223
+ messageView={{
224
+ assistantMessage:
225
+ LabelConsumerMessage as unknown as typeof CopilotChatAssistantMessage,
226
+ }}
227
+ // Inline labels object — new reference on every render of the
228
+ // parent. Without the fix, this churns the context value.
229
+ labels={{ chatInputPlaceholder: "Type here..." }}
230
+ />
231
+ </div>
232
+ </CopilotKitProvider>,
233
+ );
234
+
235
+ await submitAndReceiveAssistantMessage(agent, "msg-labels-1");
236
+
237
+ const renderCountAfterMessage = labelConsumerRenderCount;
238
+ expect(renderCountAfterMessage).toBeGreaterThan(0);
239
+
240
+ const input = screen.getByRole("textbox");
241
+ fireEvent.change(input, { target: { value: "a" } });
242
+ fireEvent.change(input, { target: { value: "ab" } });
243
+ fireEvent.change(input, { target: { value: "abc" } });
244
+
245
+ await act(async () => {});
246
+
247
+ expect(labelConsumerRenderCount).toBe(renderCountAfterMessage);
248
+ });
249
+ });
@@ -8,6 +8,7 @@
8
8
  * 4. Tool calls proxied back through the agent
9
9
  */
10
10
  import { fireEvent, screen, waitFor, act } from "@testing-library/react";
11
+ import { z } from "zod";
11
12
  import { vi } from "vitest";
12
13
  import {
13
14
  activitySnapshotEvent,
@@ -94,6 +95,44 @@ class MockMCPProxyAgent extends AbstractAgent {
94
95
  (cloned as unknown as Internal).runAgentResponses = (
95
96
  this as unknown as Internal
96
97
  ).runAgentResponses;
98
+ // Share isRunning with the original so that emit(runFinishedEvent()) on the
99
+ // registry is visible to waitForAgentIdle() which now receives the clone.
100
+ //
101
+ // Also proxy runAgent dynamically so tests that monkey-patch agent.runAgent
102
+ // after renderWithCopilotKit (which creates the clone) still take effect.
103
+ // The clone is created and cached before tests can override runAgent, so a
104
+ // static copy would always see the pre-patch prototype method.
105
+ const registry = this;
106
+ Object.defineProperty(cloned, "isRunning", {
107
+ get() {
108
+ return registry.isRunning;
109
+ },
110
+ set(v: boolean) {
111
+ registry.isRunning = v;
112
+ },
113
+ configurable: true,
114
+ enumerable: true,
115
+ });
116
+ // Override runAgent so that:
117
+ // - Proxied MCP requests delegate to registry.runAgent (picking up any
118
+ // monkey-patches the test installed after renderWithCopilotKit).
119
+ // - User-message runs call the prototype method with `this = clone` so
120
+ // that clone.messages is updated (CopilotKit renders clone.messages).
121
+ const proto = MockMCPProxyAgent.prototype;
122
+ cloned.runAgent = async function (
123
+ input?: Partial<RunAgentInput>,
124
+ ): Promise<RunAgentResult> {
125
+ const proxiedRequest = input?.forwardedProps?.__proxiedMCPRequest;
126
+ if (proxiedRequest) {
127
+ // Delegate to the registry so that monkey-patches applied by tests
128
+ // (e.g. "throws an error", "uses a controlled promise") take effect.
129
+ return registry.runAgent(input);
130
+ }
131
+ // For user-message runs: call the prototype method bound to the clone
132
+ // so AbstractAgent.runAgent processes events on clone and updates
133
+ // clone.messages (which is what CopilotKit reads to render messages).
134
+ return proto.runAgent.call(cloned, input);
135
+ };
97
136
  return cloned;
98
137
  }
99
138
 
@@ -605,12 +644,14 @@ describe("MCP Apps Activity Renderer E2E", () => {
605
644
  agent.agentId = agentId;
606
645
 
607
646
  // Custom renderer that overrides the built-in
608
- const customRenderer: ReactActivityMessageRenderer<unknown> = {
647
+ const customRenderer: ReactActivityMessageRenderer<
648
+ z.infer<typeof MCPAppsActivityContentSchema>
649
+ > = {
609
650
  activityType: MCPAppsActivityType,
610
651
  content: MCPAppsActivityContentSchema,
611
652
  render: ({ content }) => (
612
653
  <div data-testid="custom-mcp-renderer">
613
- Custom MCP Renderer: {(content as any).resourceUri}
654
+ Custom MCP Renderer: {content.resourceUri}
614
655
  </div>
615
656
  ),
616
657
  };