@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,503 @@
1
+ import React from "react";
2
+ import { render, act } from "@testing-library/react";
3
+ import { CopilotKitProvider } from "../../providers/CopilotKitProvider";
4
+ import { CopilotChat } from "../../components/chat/CopilotChat";
5
+ import { CopilotChatConfigurationProvider } from "../../providers/CopilotChatConfigurationProvider";
6
+ import { DEFAULT_AGENT_ID } from "@copilotkit/shared";
7
+ import {
8
+ AbstractAgent,
9
+ EventType,
10
+ type BaseEvent,
11
+ type RunAgentInput,
12
+ } from "@ag-ui/client";
13
+ import { Observable, Subject, from, delay } from "rxjs";
14
+ import {
15
+ ReactActivityMessageRenderer,
16
+ ReactToolCallRenderer,
17
+ } from "../../types";
18
+ import { ReactCustomMessageRenderer } from "../../types/react-custom-message-renderer";
19
+
20
+ /**
21
+ * A controllable mock agent for deterministic E2E testing.
22
+ * Exposes emit() and complete() methods to drive agent events step-by-step.
23
+ */
24
+ export class MockStepwiseAgent extends AbstractAgent {
25
+ private subject = new Subject<BaseEvent>();
26
+
27
+ /**
28
+ * Emit a single agent event
29
+ */
30
+ emit(event: BaseEvent) {
31
+ if (event.type === EventType.RUN_STARTED) {
32
+ this.isRunning = true;
33
+ } else if (
34
+ event.type === EventType.RUN_FINISHED ||
35
+ event.type === EventType.RUN_ERROR
36
+ ) {
37
+ this.isRunning = false;
38
+ }
39
+ act(() => {
40
+ this.subject.next(event);
41
+ });
42
+ }
43
+
44
+ /**
45
+ * Complete the agent stream
46
+ */
47
+ complete() {
48
+ this.isRunning = false;
49
+ act(() => {
50
+ this.subject.complete();
51
+ });
52
+ }
53
+
54
+ clone(): this {
55
+ // Return a new instance that shares the same subject so tests can keep
56
+ // controlling events via the original reference while satisfying the
57
+ // clone() contract (must return a distinct object).
58
+ // Use the concrete constructor so subclasses (e.g. FailingConnectAgent)
59
+ // preserve their overridden methods.
60
+ const cloned = new (this
61
+ .constructor as new () => MockStepwiseAgent)() as this;
62
+ cloned.agentId = this.agentId;
63
+ (cloned as unknown as { subject: Subject<BaseEvent> }).subject =
64
+ this.subject;
65
+ return cloned;
66
+ }
67
+
68
+ // No-op: prevent the base class from tearing down the Subject
69
+ // before tests have finished emitting events.
70
+ async detachActiveRun(): Promise<void> {}
71
+
72
+ run(_input: RunAgentInput): Observable<BaseEvent> {
73
+ return this.subject.asObservable();
74
+ }
75
+ }
76
+
77
+ /**
78
+ * A mock agent that supports both run() and connect() for testing reconnection scenarios.
79
+ * On run(), emits events and stores them.
80
+ * On connect(), replays stored events (simulating thread history replay).
81
+ */
82
+ export class MockReconnectableAgent extends AbstractAgent {
83
+ private subject = new Subject<BaseEvent>();
84
+ private storedEvents: BaseEvent[] = [];
85
+
86
+ /**
87
+ * Emit a single agent event during run
88
+ */
89
+ emit(event: BaseEvent) {
90
+ if (event.type === EventType.RUN_STARTED) {
91
+ this.isRunning = true;
92
+ } else if (
93
+ event.type === EventType.RUN_FINISHED ||
94
+ event.type === EventType.RUN_ERROR
95
+ ) {
96
+ this.isRunning = false;
97
+ }
98
+ this.storedEvents.push(event);
99
+ act(() => {
100
+ this.subject.next(event);
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Complete the agent stream
106
+ */
107
+ complete() {
108
+ this.isRunning = false;
109
+ act(() => {
110
+ this.subject.complete();
111
+ });
112
+ }
113
+
114
+ /**
115
+ * Reset for reconnection test - creates new subject for connect
116
+ */
117
+ reset() {
118
+ this.subject = new Subject<BaseEvent>();
119
+ }
120
+
121
+ clone(): MockReconnectableAgent {
122
+ const cloned = new MockReconnectableAgent();
123
+ cloned.agentId = this.agentId;
124
+ (
125
+ cloned as unknown as {
126
+ subject: Subject<BaseEvent>;
127
+ storedEvents: BaseEvent[];
128
+ }
129
+ ).subject = this.subject;
130
+ (
131
+ cloned as unknown as {
132
+ subject: Subject<BaseEvent>;
133
+ storedEvents: BaseEvent[];
134
+ }
135
+ ).storedEvents = this.storedEvents;
136
+ return cloned;
137
+ }
138
+
139
+ // No-op: prevent the base class from tearing down the Subject
140
+ // before tests have finished emitting events.
141
+ async detachActiveRun(): Promise<void> {}
142
+
143
+ run(_input: RunAgentInput): Observable<BaseEvent> {
144
+ return this.subject.asObservable();
145
+ }
146
+
147
+ connect(_input: RunAgentInput): Observable<BaseEvent> {
148
+ // Replay stored events with async delay to simulate HTTP transport
149
+ // This is critical for reproducing timing bugs that occur in real scenarios
150
+ return from(this.storedEvents).pipe(delay(10));
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Helper to render components with CopilotKitProvider for E2E tests
156
+ */
157
+ export function renderWithCopilotKit({
158
+ agent,
159
+ agents,
160
+ renderToolCalls,
161
+ renderCustomMessages,
162
+ renderActivityMessages,
163
+ frontendTools,
164
+ humanInTheLoop,
165
+ agentId,
166
+ threadId,
167
+ children,
168
+ }: {
169
+ agent?: AbstractAgent;
170
+ agents?: Record<string, AbstractAgent>;
171
+ renderToolCalls?: ReactToolCallRenderer<any>[];
172
+ renderCustomMessages?: ReactCustomMessageRenderer[];
173
+ renderActivityMessages?: ReactActivityMessageRenderer<any>[];
174
+ frontendTools?: any[];
175
+ humanInTheLoop?: any[];
176
+ agentId?: string;
177
+ threadId?: string;
178
+ children?: React.ReactNode;
179
+ }): ReturnType<typeof render> {
180
+ const resolvedAgents = agents || (agent ? { default: agent } : undefined);
181
+ const resolvedAgentId = agentId ?? DEFAULT_AGENT_ID;
182
+ const resolvedThreadId = threadId ?? "test-thread";
183
+
184
+ return render(
185
+ <CopilotKitProvider
186
+ agents__unsafe_dev_only={resolvedAgents}
187
+ renderToolCalls={renderToolCalls}
188
+ renderCustomMessages={renderCustomMessages}
189
+ renderActivityMessages={renderActivityMessages}
190
+ frontendTools={frontendTools}
191
+ humanInTheLoop={humanInTheLoop}
192
+ >
193
+ <CopilotChatConfigurationProvider
194
+ agentId={resolvedAgentId}
195
+ threadId={resolvedThreadId}
196
+ >
197
+ {children || (
198
+ <div style={{ height: 400 }}>
199
+ <CopilotChat welcomeScreen={false} />
200
+ </div>
201
+ )}
202
+ </CopilotChatConfigurationProvider>
203
+ </CopilotKitProvider>,
204
+ );
205
+ }
206
+
207
+ /**
208
+ * Helper to create a RUN_STARTED event
209
+ */
210
+ export function runStartedEvent(): BaseEvent {
211
+ return { type: EventType.RUN_STARTED } as BaseEvent;
212
+ }
213
+
214
+ /**
215
+ * Helper to create a RUN_FINISHED event
216
+ */
217
+ export function runFinishedEvent(): BaseEvent {
218
+ return { type: EventType.RUN_FINISHED } as BaseEvent;
219
+ }
220
+
221
+ /**
222
+ * Helper to create a STATE_SNAPSHOT event
223
+ */
224
+ export function stateSnapshotEvent(snapshot: unknown): BaseEvent {
225
+ return {
226
+ type: EventType.STATE_SNAPSHOT,
227
+ snapshot,
228
+ } as BaseEvent;
229
+ }
230
+
231
+ /**
232
+ * Helper to create an ACTIVITY_SNAPSHOT event
233
+ */
234
+ export function activitySnapshotEvent({
235
+ messageId,
236
+ activityType,
237
+ content,
238
+ }: {
239
+ messageId: string;
240
+ activityType: string;
241
+ content: Record<string, unknown>;
242
+ }): BaseEvent {
243
+ return {
244
+ type: EventType.ACTIVITY_SNAPSHOT,
245
+ messageId,
246
+ activityType,
247
+ content,
248
+ } as BaseEvent;
249
+ }
250
+
251
+ /**
252
+ * Helper to start an assistant text message
253
+ */
254
+ export function textMessageStartEvent(
255
+ messageId: string,
256
+ role: "assistant" | "developer" | "system" | "user" = "assistant",
257
+ ): BaseEvent {
258
+ return {
259
+ type: EventType.TEXT_MESSAGE_START,
260
+ messageId,
261
+ role,
262
+ } as BaseEvent;
263
+ }
264
+
265
+ /**
266
+ * Helper to stream text message content
267
+ */
268
+ export function textMessageContentEvent(
269
+ messageId: string,
270
+ delta: string,
271
+ ): BaseEvent {
272
+ return {
273
+ type: EventType.TEXT_MESSAGE_CONTENT,
274
+ messageId,
275
+ delta,
276
+ } as BaseEvent;
277
+ }
278
+
279
+ /**
280
+ * Helper to end a text message
281
+ */
282
+ export function textMessageEndEvent(messageId: string): BaseEvent {
283
+ return {
284
+ type: EventType.TEXT_MESSAGE_END,
285
+ messageId,
286
+ } as BaseEvent;
287
+ }
288
+
289
+ /**
290
+ * Helper to create a TEXT_MESSAGE_CHUNK event
291
+ */
292
+ export function textChunkEvent(messageId: string, delta: string): BaseEvent {
293
+ return {
294
+ type: EventType.TEXT_MESSAGE_CHUNK,
295
+ messageId,
296
+ delta,
297
+ } as BaseEvent;
298
+ }
299
+
300
+ /**
301
+ * Helper to create a TOOL_CALL_CHUNK event
302
+ */
303
+ export function toolCallChunkEvent({
304
+ toolCallId,
305
+ toolCallName,
306
+ parentMessageId,
307
+ delta,
308
+ }: {
309
+ toolCallId: string;
310
+ toolCallName?: string;
311
+ parentMessageId: string;
312
+ delta: string;
313
+ }): BaseEvent {
314
+ return {
315
+ type: EventType.TOOL_CALL_CHUNK,
316
+ toolCallId,
317
+ toolCallName,
318
+ parentMessageId,
319
+ delta,
320
+ } as BaseEvent;
321
+ }
322
+
323
+ /**
324
+ * Helper to create a TOOL_CALL_RESULT event
325
+ */
326
+ export function toolCallResultEvent({
327
+ toolCallId,
328
+ messageId,
329
+ content,
330
+ }: {
331
+ toolCallId: string;
332
+ messageId: string;
333
+ content: string;
334
+ }): BaseEvent {
335
+ return {
336
+ type: EventType.TOOL_CALL_RESULT,
337
+ toolCallId,
338
+ messageId,
339
+ content,
340
+ } as BaseEvent;
341
+ }
342
+
343
+ /**
344
+ * Helper to create a REASONING_START event
345
+ */
346
+ export function reasoningStartEvent(messageId: string): BaseEvent {
347
+ return {
348
+ type: EventType.REASONING_START,
349
+ messageId,
350
+ } as BaseEvent;
351
+ }
352
+
353
+ /**
354
+ * Helper to create a REASONING_MESSAGE_START event
355
+ */
356
+ export function reasoningMessageStartEvent(messageId: string): BaseEvent {
357
+ return {
358
+ type: EventType.REASONING_MESSAGE_START,
359
+ messageId,
360
+ role: "reasoning",
361
+ } as BaseEvent;
362
+ }
363
+
364
+ /**
365
+ * Helper to create a REASONING_MESSAGE_CONTENT event
366
+ */
367
+ export function reasoningMessageContentEvent(
368
+ messageId: string,
369
+ delta: string,
370
+ ): BaseEvent {
371
+ return {
372
+ type: EventType.REASONING_MESSAGE_CONTENT,
373
+ messageId,
374
+ delta,
375
+ } as BaseEvent;
376
+ }
377
+
378
+ /**
379
+ * Helper to create a REASONING_MESSAGE_END event
380
+ */
381
+ export function reasoningMessageEndEvent(messageId: string): BaseEvent {
382
+ return {
383
+ type: EventType.REASONING_MESSAGE_END,
384
+ messageId,
385
+ } as BaseEvent;
386
+ }
387
+
388
+ /**
389
+ * Helper to create a REASONING_END event
390
+ */
391
+ export function reasoningEndEvent(messageId: string): BaseEvent {
392
+ return {
393
+ type: EventType.REASONING_END,
394
+ messageId,
395
+ } as BaseEvent;
396
+ }
397
+
398
+ /**
399
+ * Helper to emit a complete reasoning sequence (all 5 events)
400
+ */
401
+ export function emitReasoningSequence(
402
+ agent: MockStepwiseAgent,
403
+ messageId: string,
404
+ content: string,
405
+ ) {
406
+ agent.emit(reasoningStartEvent(messageId));
407
+ agent.emit(reasoningMessageStartEvent(messageId));
408
+ agent.emit(reasoningMessageContentEvent(messageId, content));
409
+ agent.emit(reasoningMessageEndEvent(messageId));
410
+ agent.emit(reasoningEndEvent(messageId));
411
+ }
412
+
413
+ /**
414
+ * Helper to generate unique IDs for tests
415
+ */
416
+ export function testId(prefix: string): string {
417
+ return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
418
+ }
419
+
420
+ /**
421
+ * Helper to emit a complete suggestion tool call with streaming chunks
422
+ */
423
+ export function emitSuggestionToolCall(
424
+ agent: MockStepwiseAgent,
425
+ {
426
+ toolCallId,
427
+ parentMessageId,
428
+ suggestions,
429
+ }: {
430
+ toolCallId: string;
431
+ parentMessageId: string;
432
+ suggestions: Array<{ title: string; message: string }>;
433
+ },
434
+ ) {
435
+ // Convert suggestions to JSON string
436
+ const suggestionsJson = JSON.stringify({ suggestions });
437
+
438
+ // Emit the tool call name first
439
+ agent.emit(
440
+ toolCallChunkEvent({
441
+ toolCallId,
442
+ toolCallName: "copilotkitSuggest",
443
+ parentMessageId,
444
+ delta: "",
445
+ }),
446
+ );
447
+
448
+ // Stream the JSON in chunks to simulate streaming
449
+ const chunkSize = 10; // Characters per chunk
450
+ for (let i = 0; i < suggestionsJson.length; i += chunkSize) {
451
+ const chunk = suggestionsJson.substring(i, i + chunkSize);
452
+ agent.emit(
453
+ toolCallChunkEvent({
454
+ toolCallId,
455
+ parentMessageId,
456
+ delta: chunk,
457
+ }),
458
+ );
459
+ }
460
+ }
461
+
462
+ /**
463
+ * A MockStepwiseAgent that emits suggestion events when run() is called
464
+ */
465
+ export class SuggestionsProviderAgent extends MockStepwiseAgent {
466
+ // Shared via a container so clone() and original see the same value even
467
+ // when setSuggestions() is called after the clone is created.
468
+ private _shared: { suggestions: Array<{ title: string; message: string }> } =
469
+ { suggestions: [] };
470
+
471
+ setSuggestions(suggestions: Array<{ title: string; message: string }>) {
472
+ this._shared.suggestions = suggestions;
473
+ }
474
+
475
+ clone(): this {
476
+ const cloned = super.clone();
477
+ (cloned as unknown as { _shared: typeof this._shared })._shared =
478
+ this._shared;
479
+ return cloned;
480
+ }
481
+
482
+ run(_input: RunAgentInput): Observable<BaseEvent> {
483
+ // Call the parent's run() to get the Subject that's already set up
484
+ const parentObservable = super.run(_input);
485
+
486
+ // Use setTimeout to emit events asynchronously through the existing subject
487
+ setTimeout(() => {
488
+ const messageId = testId("suggest-msg");
489
+ this.emit({ type: EventType.RUN_STARTED } as BaseEvent);
490
+
491
+ emitSuggestionToolCall(this, {
492
+ toolCallId: testId("tc"),
493
+ parentMessageId: messageId,
494
+ suggestions: this._shared.suggestions,
495
+ });
496
+
497
+ this.emit({ type: EventType.RUN_FINISHED } as BaseEvent);
498
+ this.complete();
499
+ }, 0);
500
+
501
+ return parentObservable;
502
+ }
503
+ }
@@ -0,0 +1,206 @@
1
+ import { useCopilotKit } from "../providers";
2
+ import type { ReactActivityMessageRenderer } from "../types/react-activity-message-renderer";
3
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
4
+ import { z } from "zod";
5
+ import {
6
+ A2UIProvider,
7
+ useA2UIActions,
8
+ A2UIRenderer,
9
+ initializeDefaultCatalog,
10
+ injectStyles,
11
+ DEFAULT_SURFACE_ID,
12
+ } from "@copilotkit/a2ui-renderer";
13
+ import type { Theme, A2UIClientEventMessage } from "@copilotkit/a2ui-renderer";
14
+
15
+ // Initialize the React renderer's component catalog and styles once
16
+ let initialized = false;
17
+ function ensureInitialized() {
18
+ if (!initialized) {
19
+ initializeDefaultCatalog();
20
+ injectStyles();
21
+ initialized = true;
22
+ }
23
+ }
24
+
25
+ export type A2UIMessageRendererOptions = {
26
+ theme: Theme;
27
+ };
28
+
29
+ export function createA2UIMessageRenderer(
30
+ options: A2UIMessageRendererOptions,
31
+ ): ReactActivityMessageRenderer<any> {
32
+ const { theme } = options;
33
+
34
+ return {
35
+ activityType: "a2ui-surface",
36
+ content: z.any(),
37
+ render: ({ content, agent }) => {
38
+ ensureInitialized();
39
+
40
+ const [operations, setOperations] = useState<any[]>([]);
41
+ const lastSignatureRef = useRef<string | null>(null);
42
+ const { copilotkit } = useCopilotKit();
43
+
44
+ useEffect(() => {
45
+ if (!content || !Array.isArray(content.operations)) {
46
+ lastSignatureRef.current = null;
47
+ setOperations([]);
48
+ return;
49
+ }
50
+
51
+ const incoming = content.operations as any[];
52
+ const signature = stringifyOperations(incoming);
53
+
54
+ if (signature && signature === lastSignatureRef.current) {
55
+ return;
56
+ }
57
+
58
+ lastSignatureRef.current = signature;
59
+ setOperations(incoming);
60
+ }, [content]);
61
+
62
+ // Group operations by surface ID
63
+ const groupedOperations = useMemo(() => {
64
+ const groups = new Map<string, any[]>();
65
+
66
+ for (const operation of operations) {
67
+ const surfaceId =
68
+ getOperationSurfaceId(operation) ?? DEFAULT_SURFACE_ID;
69
+
70
+ if (!groups.has(surfaceId)) {
71
+ groups.set(surfaceId, []);
72
+ }
73
+ groups.get(surfaceId)!.push(operation);
74
+ }
75
+
76
+ return groups;
77
+ }, [operations]);
78
+
79
+ if (!groupedOperations.size) {
80
+ return null;
81
+ }
82
+
83
+ return (
84
+ <div className="cpk:flex cpk:min-h-0 cpk:flex-1 cpk:flex-col cpk:gap-6 cpk:overflow-auto cpk:py-6">
85
+ {Array.from(groupedOperations.entries()).map(([surfaceId, ops]) => (
86
+ <ReactSurfaceHost
87
+ key={surfaceId}
88
+ surfaceId={surfaceId}
89
+ operations={ops}
90
+ theme={theme}
91
+ agent={agent}
92
+ copilotkit={copilotkit}
93
+ />
94
+ ))}
95
+ </div>
96
+ );
97
+ },
98
+ };
99
+ }
100
+
101
+ type ReactSurfaceHostProps = {
102
+ surfaceId: string;
103
+ operations: any[];
104
+ theme: Theme;
105
+ agent: any;
106
+ copilotkit: any;
107
+ };
108
+
109
+ /**
110
+ * Renders a single A2UI surface using the React renderer.
111
+ * Wraps A2UIProvider + A2UIRenderer and bridges actions back to CopilotKit.
112
+ */
113
+ function ReactSurfaceHost({
114
+ surfaceId,
115
+ operations,
116
+ theme,
117
+ agent,
118
+ copilotkit,
119
+ }: ReactSurfaceHostProps) {
120
+ // Bridge: when the React renderer dispatches an action, send it to CopilotKit
121
+ const handleAction = useCallback(
122
+ async (message: A2UIClientEventMessage) => {
123
+ if (!agent) return;
124
+
125
+ try {
126
+ console.info("[A2UI] Action dispatched", message.userAction);
127
+
128
+ copilotkit.setProperties({
129
+ ...(copilotkit.properties ?? {}),
130
+ a2uiAction: message,
131
+ });
132
+
133
+ await copilotkit.runAgent({ agent });
134
+ } finally {
135
+ if (copilotkit.properties) {
136
+ const { a2uiAction, ...rest } = copilotkit.properties;
137
+ copilotkit.setProperties(rest);
138
+ }
139
+ }
140
+ },
141
+ [agent, copilotkit],
142
+ );
143
+
144
+ return (
145
+ <div className="cpk:flex cpk:w-full cpk:flex-none cpk:flex-col cpk:gap-4">
146
+ <A2UIProvider onAction={handleAction} theme={theme}>
147
+ <SurfaceMessageProcessor
148
+ surfaceId={surfaceId}
149
+ operations={operations}
150
+ />
151
+ <A2UIRenderer surfaceId={surfaceId} className="cpk:flex cpk:flex-1" />
152
+ </A2UIProvider>
153
+ </div>
154
+ );
155
+ }
156
+
157
+ /**
158
+ * Processes A2UI operations into the provider's message processor.
159
+ * Must be a child of A2UIProvider to access the actions context.
160
+ */
161
+ function SurfaceMessageProcessor({
162
+ surfaceId,
163
+ operations,
164
+ }: {
165
+ surfaceId: string;
166
+ operations: any[];
167
+ }) {
168
+ const { processMessages } = useA2UIActions();
169
+ const lastProcessedRef = useRef<string>("");
170
+
171
+ useEffect(() => {
172
+ const key = `${surfaceId}-${JSON.stringify(operations)}`;
173
+ if (key === lastProcessedRef.current) return;
174
+ lastProcessedRef.current = key;
175
+
176
+ processMessages(operations);
177
+ }, [processMessages, surfaceId, operations]);
178
+
179
+ return null;
180
+ }
181
+
182
+ function getOperationSurfaceId(operation: any): string | null {
183
+ if (!operation || typeof operation !== "object") {
184
+ return null;
185
+ }
186
+
187
+ if (typeof operation.surfaceId === "string") {
188
+ return operation.surfaceId;
189
+ }
190
+
191
+ return (
192
+ operation?.beginRendering?.surfaceId ??
193
+ operation?.surfaceUpdate?.surfaceId ??
194
+ operation?.dataModelUpdate?.surfaceId ??
195
+ operation?.deleteSurface?.surfaceId ??
196
+ null
197
+ );
198
+ }
199
+
200
+ function stringifyOperations(ops: any[]): string | null {
201
+ try {
202
+ return JSON.stringify(ops);
203
+ } catch (error) {
204
+ return null;
205
+ }
206
+ }