@copilotkit/react-native 2.0.0-rc.5 → 2.0.0-rc.51

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 (113) hide show
  1. package/README.md +334 -2
  2. package/USAGE.md +382 -21
  3. package/dist/CopilotKitProvider-CBVQLdzn.d.cts +77 -0
  4. package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-CCBBonxr.mjs} +63 -43
  5. package/dist/CopilotKitProvider-CCBBonxr.mjs.map +1 -0
  6. package/dist/CopilotKitProvider-CtQg_0S-.d.mts +77 -0
  7. package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-QdcQrrSA.cjs} +69 -42
  8. package/dist/CopilotKitProvider-QdcQrrSA.cjs.map +1 -0
  9. package/dist/{Markdown-C_9Re36O.cjs → Markdown-DLopAh5W.cjs} +10 -10
  10. package/dist/Markdown-DLopAh5W.cjs.map +1 -0
  11. package/dist/{Markdown-JsYh7oSA.d.mts → Markdown-Du-b_Qpr.d.mts} +3 -3
  12. package/dist/{Markdown-1ips7myr.d.cts → Markdown-UXZdDjzs.d.cts} +3 -3
  13. package/dist/{Markdown-C6AsLHmd.mjs → Markdown-VxtPJ_yh.mjs} +4 -4
  14. package/dist/Markdown-VxtPJ_yh.mjs.map +1 -0
  15. package/dist/{MarkdownRendererContext-CAnuohIS.mjs → MarkdownRendererContext-EobUsERg.mjs} +1 -1
  16. package/dist/{MarkdownRendererContext-CAnuohIS.mjs.map → MarkdownRendererContext-EobUsERg.mjs.map} +1 -1
  17. package/dist/MarkdownRendererContext-cDEHvbw9.cjs +40 -0
  18. package/dist/{MarkdownRendererContext-BRNe808d.cjs.map → MarkdownRendererContext-cDEHvbw9.cjs.map} +1 -1
  19. package/dist/chunk-C0xms8kb.cjs +34 -0
  20. package/dist/components/index.cjs +78 -175
  21. package/dist/components/index.cjs.map +1 -1
  22. package/dist/components/index.d.cts +2 -2
  23. package/dist/components/index.d.mts +2 -2
  24. package/dist/components/index.mjs +76 -174
  25. package/dist/components/index.mjs.map +1 -1
  26. package/dist/generative-ui/index.cjs +612 -0
  27. package/dist/generative-ui/index.cjs.map +1 -0
  28. package/dist/generative-ui/index.d.cts +341 -0
  29. package/dist/generative-ui/index.d.mts +341 -0
  30. package/dist/generative-ui/index.mjs +549 -0
  31. package/dist/generative-ui/index.mjs.map +1 -0
  32. package/dist/headless.cjs +3 -2
  33. package/dist/headless.d.cts +3 -3
  34. package/dist/headless.d.mts +3 -3
  35. package/dist/headless.mjs +2 -2
  36. package/dist/index.cjs +132 -162
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +37 -19
  39. package/dist/index.d.mts +37 -19
  40. package/dist/index.mjs +131 -162
  41. package/dist/index.mjs.map +1 -1
  42. package/dist/polyfills/encoding.cjs +115 -5
  43. package/dist/polyfills/encoding.cjs.map +1 -1
  44. package/dist/polyfills/encoding.d.cts +31 -1
  45. package/dist/polyfills/encoding.d.mts +31 -1
  46. package/dist/polyfills/encoding.mjs +113 -6
  47. package/dist/polyfills/encoding.mjs.map +1 -1
  48. package/dist/polyfills/streams.cjs +1 -1
  49. package/dist/polyfills.cjs +218 -2
  50. package/dist/polyfills.cjs.map +1 -1
  51. package/dist/polyfills.mjs +217 -1
  52. package/dist/polyfills.mjs.map +1 -1
  53. package/package.json +51 -21
  54. package/project.json +6 -1
  55. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  56. package/scripts/verify-polyfill-barrel.mjs +158 -11
  57. package/src/CopilotChat.tsx +114 -93
  58. package/src/CopilotKitProvider.tsx +101 -130
  59. package/src/CopilotPopup.tsx +2 -2
  60. package/src/CopilotSidebar.tsx +7 -5
  61. package/src/__mocks__/react-native.ts +31 -0
  62. package/src/__mocks__/test-copilotkit.tsx +9 -3
  63. package/src/__tests__/attachments-integration.test.tsx +15 -2
  64. package/src/__tests__/copilot-chat-agentid.test.tsx +15 -2
  65. package/src/__tests__/copilot-chat-attachments.test.tsx +15 -2
  66. package/src/__tests__/copilot-chat-configuration.test.tsx +82 -0
  67. package/src/__tests__/copilot-chat-threads.test.tsx +232 -0
  68. package/src/__tests__/copilot-popup.test.tsx +15 -2
  69. package/src/__tests__/copilot-sidebar.test.tsx +15 -2
  70. package/src/__tests__/copilotkit-alias-exports.test.ts +16 -0
  71. package/src/__tests__/copilotkit-provider.test.tsx +68 -73
  72. package/src/__tests__/generative-ui-harness.tsx +243 -0
  73. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  74. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  75. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  76. package/src/__tests__/generative-ui.test.tsx +1000 -0
  77. package/src/__tests__/headless-entry-surface.test.ts +979 -61
  78. package/src/__tests__/headless-integration.test.tsx +11 -1
  79. package/src/__tests__/use-attachments.test.ts +27 -2
  80. package/src/components/CopilotChat.tsx +106 -233
  81. package/src/components/CopilotModal.tsx +1 -1
  82. package/src/components/Markdown.tsx +4 -4
  83. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
  84. package/src/components/__tests__/CopilotChat.test.tsx +12 -4
  85. package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
  86. package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
  87. package/src/components/index.ts +6 -0
  88. package/src/components/messages/AssistantMessage.tsx +3 -3
  89. package/src/components/messages/TypingIndicator.tsx +4 -4
  90. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  91. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  92. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  93. package/src/generative-ui/host.tsx +138 -0
  94. package/src/generative-ui/index.ts +93 -0
  95. package/src/generative-ui/internal.ts +55 -0
  96. package/src/headless.ts +4 -0
  97. package/src/hooks/use-attachments.ts +95 -139
  98. package/src/index.ts +10 -4
  99. package/src/polyfills/__tests__/encoding-utf8.test.ts +112 -0
  100. package/src/polyfills/encoding.ts +160 -4
  101. package/src/types.d.ts +0 -13
  102. package/tsdown.config.ts +1 -0
  103. package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
  104. package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
  105. package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
  106. package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
  107. package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
  108. package/dist/Markdown-C_9Re36O.cjs.map +0 -1
  109. package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
  110. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  111. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  112. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  113. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -8,77 +8,37 @@ import type {
8
8
  CopilotKitContextValue,
9
9
  CopilotKitCoreReact as CopilotKitCoreReactInstance,
10
10
  } from "@copilotkit/react-core/context";
11
- import { CopilotKitCoreReact } from "@copilotkit/react-core/headless";
11
+ import {
12
+ CopilotKitCoreReact,
13
+ ɵuseOwnedCore,
14
+ } from "@copilotkit/react-core/headless";
12
15
  import type {
13
- CopilotKitCoreErrorCode,
14
- CopilotKitMessageFilter,
16
+ ɵCopilotKitProviderBaseOptions,
17
+ ɵRuntimeInfo,
18
+ } from "@copilotkit/core";
19
+ import {
20
+ ɵreportProviderConfigDiagnostics,
21
+ ɵresolveProviderConfig,
15
22
  } from "@copilotkit/core";
16
- import type { DebugConfig, RuntimeLicenseStatus } from "@copilotkit/shared";
17
23
  import { createLicenseContextValue } from "@copilotkit/shared";
18
24
  import { MarkdownRendererProvider } from "./components/MarkdownRendererContext";
19
25
  import type { MarkdownRendererValue } from "./components/MarkdownRendererContext";
20
26
 
21
- export interface CopilotKitNativeProviderProps {
27
+ export interface CopilotKitNativeProviderProps extends Pick<
28
+ ɵCopilotKitProviderBaseOptions,
29
+ | "credentials"
30
+ | "messageFilter"
31
+ | "useSingleEndpoint"
32
+ | "properties"
33
+ | "onError"
34
+ | "debug"
35
+ | "defaultThrottleMs"
36
+ > {
22
37
  children: ReactNode;
23
38
  /** URL of the CopilotKit runtime endpoint */
24
39
  runtimeUrl: string;
25
40
  /** Custom headers sent with every request */
26
41
  headers?: Record<string, string> | (() => Record<string, string>);
27
- /**
28
- * Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
29
- */
30
- credentials?: RequestCredentials;
31
- /**
32
- * Rewrites the message list sent to runtime agents on every run.
33
- *
34
- * CopilotKit sends the whole thread each time. When your agent already
35
- * stores the conversation, most of that payload is waste, and an agent that
36
- * merges the inbound list with its own store can show the model every turn
37
- * twice. Return the messages to send:
38
- *
39
- * ```tsx
40
- * <CopilotKitProvider
41
- * runtimeUrl="/api/copilotkit"
42
- * messageFilter={(messages) => messages.slice(-1)}
43
- * />
44
- * ```
45
- *
46
- * The filter changes the request body only. The transcript the UI renders is
47
- * untouched. Broken tool-call pairs are repaired before the request is sent,
48
- * so a filter this blunt cannot strand a tool result mid-HITL.
49
- *
50
- * Agents reached through your CopilotRuntime honor this. An agent your app
51
- * passes in directly does not, and neither Intelligence runs nor suggestion
52
- * runs are ever filtered.
53
- *
54
- * Prefer a stable reference (`useCallback`). An inline arrow re-registers the
55
- * filter on every render, which is harmless but needless.
56
- */
57
- messageFilter?: CopilotKitMessageFilter;
58
- /** Whether the runtime uses a single-route endpoint */
59
- useSingleEndpoint?: boolean;
60
- /** Custom properties forwarded to agents */
61
- properties?: Record<string, unknown>;
62
- /**
63
- * Error handler called when CopilotKit encounters an error.
64
- * Fires for all error types (runtime connection failures, agent errors, tool errors).
65
- * If not provided, errors are logged to console.error.
66
- */
67
- onError?: (event: {
68
- error: Error;
69
- code: CopilotKitCoreErrorCode;
70
- context: Record<string, any>;
71
- }) => void | Promise<void>;
72
- /**
73
- * Enable debug logging for the client-side event pipeline.
74
- * When `true`, enables verbose logging from the core instance.
75
- */
76
- debug?: DebugConfig;
77
- /**
78
- * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`
79
- * subscriptions. Individual subscriptions can override with their own `throttleMs`.
80
- */
81
- defaultThrottleMs?: number;
82
42
  /**
83
43
  * Custom markdown renderer for assistant messages. Either a component (escape
84
44
  * hatch — receives `content` and an optional `isStreaming` flag) used instead
@@ -143,66 +103,75 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
143
103
  [JSON.stringify(properties)],
144
104
  );
145
105
 
106
+ // Transport mapping and config checks come from core.
107
+ const resolvedConfig = useMemo(
108
+ () =>
109
+ ɵresolveProviderConfig({
110
+ runtimeUrl,
111
+ useSingleEndpoint,
112
+ properties: stableProperties,
113
+ }),
114
+ [runtimeUrl, useSingleEndpoint, stableProperties],
115
+ );
116
+ const loggedDiagnosticsRef = useRef(new Set<string>());
117
+ ɵreportProviderConfigDiagnostics(resolvedConfig.diagnostics, {
118
+ isProduction: process.env.NODE_ENV === "production",
119
+ logged: loggedDiagnosticsRef.current,
120
+ });
121
+
122
+ // One core for the provider lifetime, disposed on unmount (StrictMode
123
+ // safe, see `ɵuseOwnedCore`).
146
124
  const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);
125
+ const copilotkit = ɵuseOwnedCore(
126
+ copilotkitRef,
127
+ (): CopilotKitCoreReactInstance =>
128
+ new CopilotKitCoreReact({
129
+ runtimeUrl: resolvedConfig.runtimeUrl,
130
+ runtimeTransport: resolvedConfig.runtimeTransport,
131
+ // `/info` starts from the effect below, so a render React discards
132
+ // never fetches it (#5801).
133
+ deferInitialConnection: true,
134
+ headers: stableHeaders,
135
+ credentials,
136
+ messageFilter,
137
+ properties: resolvedConfig.properties,
138
+ debug,
139
+ // Set at construction so child hooks see it on their first render.
140
+ defaultThrottleMs,
141
+ onError,
142
+ }),
143
+ );
144
+
145
+ // Core calls `onError`, and logs the error itself when there is none.
146
+ useEffect(() => {
147
+ copilotkit.setErrorHandler(onError);
148
+ }, [copilotkit, onError]);
147
149
 
148
- if (copilotkitRef.current === null) {
149
- const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({
150
- runtimeUrl,
151
- runtimeTransport:
152
- useSingleEndpoint === true
153
- ? "single"
154
- : useSingleEndpoint === false
155
- ? "rest"
156
- : "auto",
150
+ // Sync props to the core. Core applies only what changed.
151
+ useEffect(() => {
152
+ copilotkit.ɵupdateConfig({
153
+ messageFilter,
154
+ runtimeUrl: resolvedConfig.runtimeUrl,
155
+ runtimeTransport: resolvedConfig.runtimeTransport,
157
156
  headers: stableHeaders,
158
157
  credentials,
159
- messageFilter,
160
- properties: stableProperties,
158
+ properties: resolvedConfig.properties,
161
159
  debug,
160
+ defaultThrottleMs,
162
161
  });
163
- // Set initial defaultThrottleMs synchronously so child hooks see the
164
- // correct value on their first render (before useEffect fires).
165
- if (defaultThrottleMs !== undefined) {
166
- instance.setDefaultThrottleMs(defaultThrottleMs);
167
- }
168
- copilotkitRef.current = instance;
169
- }
170
-
171
- const copilotkit = copilotkitRef.current;
172
-
173
- // Sync props to core instance
174
- useEffect(() => {
175
- copilotkit.setRuntimeUrl(runtimeUrl);
176
- copilotkit.setRuntimeTransport(
177
- useSingleEndpoint === true
178
- ? "single"
179
- : useSingleEndpoint === false
180
- ? "rest"
181
- : "auto",
182
- );
183
- copilotkit.setHeaders(stableHeaders);
184
- copilotkit.setCredentials(credentials);
185
- copilotkit.setMessageFilter(messageFilter);
186
- copilotkit.setProperties(stableProperties);
187
- copilotkit.setDebug(debug);
162
+ copilotkit.connect();
188
163
  }, [
189
- runtimeUrl,
190
- useSingleEndpoint,
164
+ copilotkit,
165
+ messageFilter,
166
+ resolvedConfig.runtimeUrl,
167
+ resolvedConfig.runtimeTransport,
191
168
  stableHeaders,
192
169
  credentials,
193
- messageFilter,
194
- stableProperties,
170
+ resolvedConfig.properties,
195
171
  debug,
196
- copilotkit,
172
+ defaultThrottleMs,
197
173
  ]);
198
174
 
199
- // Sync defaultThrottleMs to the core instance on prop changes.
200
- // Initial value is set synchronously during instance creation (inside the
201
- // ref guard above), so this only handles subsequent updates.
202
- useEffect(() => {
203
- copilotkit.setDefaultThrottleMs(defaultThrottleMs);
204
- }, [copilotkit, defaultThrottleMs]);
205
-
206
175
  // Track executing tool call IDs at the provider level.
207
176
  // Critical for HITL reconnection: onToolExecutionStart fires before child
208
177
  // components mount, so we must capture the state here.
@@ -210,17 +179,19 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
210
179
  ReadonlySet<string>
211
180
  >(() => new Set());
212
181
 
213
- const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<
214
- RuntimeLicenseStatus | undefined
215
- >(undefined);
182
+ const [runtimeInfo, setRuntimeInfo] = useState<ɵRuntimeInfo | null>(null);
183
+ const runtimeLicenseStatus = runtimeInfo?.licenseStatus;
216
184
 
217
- // Use ref to avoid subscription churn when onError changes
218
- const onErrorRef = useRef(onError);
185
+ // Project core's runtime info snapshot; the catch-up read reflects a status
186
+ // that settled before this effect ran.
219
187
  useEffect(() => {
220
- onErrorRef.current = onError;
221
- }, [onError]);
188
+ const syncRuntimeInfo = () => setRuntimeInfo(copilotkit.ɵruntimeInfo);
189
+ const unsubscribe = copilotkit.ɵsubscribeToRuntimeInfo(syncRuntimeInfo);
190
+ syncRuntimeInfo();
191
+ return unsubscribe;
192
+ }, [copilotkit]);
222
193
 
223
- // Single subscription for tool execution tracking and error handling.
194
+ // Tool execution tracking.
224
195
  // Tool call IDs are tracked at the provider level because onToolExecutionStart
225
196
  // fires before child components mount — critical for HITL reconnection.
226
197
  useEffect(() => {
@@ -241,20 +212,6 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
241
212
  return next;
242
213
  });
243
214
  },
244
- onError: (event) => {
245
- if (onErrorRef.current) {
246
- onErrorRef.current(event);
247
- } else {
248
- console.error(
249
- `[CopilotKit] Error (${event.code}):`,
250
- event.error,
251
- event.context ?? {},
252
- );
253
- }
254
- },
255
- onRuntimeConnectionStatusChanged: () => {
256
- setRuntimeLicenseStatus(copilotkit.licenseStatus);
257
- },
258
215
  });
259
216
  return () => subscription.unsubscribe();
260
217
  }, [copilotkit]);
@@ -283,3 +240,17 @@ export const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({
283
240
  </CopilotKitContext.Provider>
284
241
  );
285
242
  };
243
+
244
+ /**
245
+ * Alias of {@link CopilotKitProvider}: the same component under its v1 name,
246
+ * so `<CopilotKit>` keeps working. `CopilotKitProvider` is the preferred name.
247
+ *
248
+ * @alias
249
+ */
250
+ export const CopilotKit = CopilotKitProvider;
251
+
252
+ /**
253
+ * Alias of {@link CopilotKitNativeProviderProps}, the props of
254
+ * {@link CopilotKit}. Prefer `CopilotKitProviderProps` in new code.
255
+ */
256
+ export type CopilotKitProps = CopilotKitNativeProviderProps;
@@ -78,8 +78,8 @@ export interface CopilotPopupProps {
78
78
  attachments?: NativeAttachmentsConfig;
79
79
 
80
80
  /**
81
- * Optional children rendered below the CopilotChat content
82
- * inside the popup card.
81
+ * Your chat UI, rendered inside the popup card below the header. The inner
82
+ * CopilotChat is headless and draws no messages or input of its own.
83
83
  */
84
84
  children?: ReactNode;
85
85
 
@@ -9,7 +9,6 @@ import React, {
9
9
  import type { ReactNode } from "react";
10
10
  import {
11
11
  Animated,
12
- Dimensions,
13
12
  Pressable,
14
13
  StyleSheet,
15
14
  Text,
@@ -70,7 +69,10 @@ export interface CopilotSidebarProps extends Omit<
70
69
  /** Custom style applied to the drawer container. */
71
70
  style?: ViewStyle;
72
71
 
73
- /** Content rendered inside the drawer below the chat area. */
72
+ /**
73
+ * Your chat UI, rendered inside the drawer below the header. The inner
74
+ * CopilotChat is headless and draws no messages or input of its own.
75
+ */
74
76
  children?: ReactNode;
75
77
  }
76
78
 
@@ -133,9 +135,9 @@ export const CopilotSidebar = forwardRef<
133
135
 
134
136
  // Animation & open state -------------------------------------------------
135
137
  const [isOpen, setIsOpen] = useState(defaultOpen);
136
- const slideAnim = useRef(
137
- new Animated.Value(defaultOpen ? 0 : drawerWidth),
138
- ).current;
138
+ const [slideAnim] = useState(
139
+ () => new Animated.Value(defaultOpen ? 0 : drawerWidth),
140
+ );
139
141
 
140
142
  // Keep the animated value in sync when drawerWidth changes while closed
141
143
  useEffect(() => {
@@ -30,6 +30,36 @@ export const ScrollView = createMockComponent("ScrollView");
30
30
  export const ActivityIndicator = createMockComponent("ActivityIndicator");
31
31
  export const Image = createMockComponent("Image");
32
32
 
33
+ // A no-op Animated API. Components such as TypingIndicator create
34
+ // Animated.Value instances and start timing loops at render time; in tests the
35
+ // values never change and the animations never run.
36
+ class AnimatedValue {
37
+ constructor(private value: number) {}
38
+ setValue(value: number) {
39
+ this.value = value;
40
+ }
41
+ interpolate({ outputRange }: { outputRange: unknown[] }) {
42
+ return outputRange[0];
43
+ }
44
+ }
45
+
46
+ const noopAnimation = () => ({
47
+ start: () => {},
48
+ stop: () => {},
49
+ reset: () => {},
50
+ });
51
+
52
+ export const Animated = {
53
+ Value: AnimatedValue,
54
+ View: createMockComponent("Animated.View"),
55
+ Text: createMockComponent("Animated.Text"),
56
+ timing: noopAnimation,
57
+ sequence: noopAnimation,
58
+ parallel: noopAnimation,
59
+ loop: noopAnimation,
60
+ delay: noopAnimation,
61
+ };
62
+
33
63
  export const Platform = {
34
64
  OS: "ios" as const,
35
65
  select: <T>(obj: { ios?: T; android?: T; default?: T }): T | undefined =>
@@ -49,4 +79,5 @@ export default {
49
79
  ActivityIndicator,
50
80
  Image,
51
81
  Platform,
82
+ Animated,
52
83
  };
@@ -9,7 +9,7 @@
9
9
  * would stub the very thing under test. Driving a real core exercises the
10
10
  * production path end-to-end.
11
11
  *
12
- * The core and its single "default" agent are created ONCE (via refs) and kept
12
+ * The core and its agents are created ONCE (via refs) and kept
13
13
  * stable across re-renders. That stability is load-bearing: `useRenderTool`
14
14
  * registers its renderer into core and deliberately does NOT remove it on
15
15
  * unmount, so a renderer registered on one render must survive a later
@@ -38,7 +38,7 @@ import type { CopilotKitContextValue } from "@copilotkit/react-core/context";
38
38
  * bundler cannot resolve a bare `rxjs` import. A throw-only body is assignable
39
39
  * to any declared return type, so no Observable value is constructed.
40
40
  */
41
- class SeededAgent extends AbstractAgent {
41
+ export class SeededAgent extends AbstractAgent {
42
42
  run(): ReturnType<AbstractAgent["run"]> {
43
43
  throw new Error("SeededAgent.run() is not used in tests");
44
44
  }
@@ -83,6 +83,11 @@ export interface TestCopilotKitProps {
83
83
  * instance, and therefore the registered renderers, must stay stable).
84
84
  */
85
85
  agent?: AbstractAgent;
86
+ /**
87
+ * More agents to register next to "default", keyed by agent id, for tests
88
+ * that pick a non-default agent. Captured on first render like `agent`.
89
+ */
90
+ agents?: Record<string, AbstractAgent>;
86
91
  children: React.ReactNode;
87
92
  }
88
93
 
@@ -91,6 +96,7 @@ export function TestCopilotKit({
91
96
  executingToolCallIds = EMPTY_SET,
92
97
  agentRef: publishAgentRef,
93
98
  agent,
99
+ agents,
94
100
  children,
95
101
  }: TestCopilotKitProps) {
96
102
  const agentRef = useRef<AbstractAgent | null>(null);
@@ -102,7 +108,7 @@ export function TestCopilotKit({
102
108
  const copilotkitRef = useRef<CopilotKitCoreReact | null>(null);
103
109
  if (copilotkitRef.current === null) {
104
110
  copilotkitRef.current = new CopilotKitCoreReact({
105
- agents__unsafe_dev_only: { default: agentRef.current },
111
+ agents__unsafe_dev_only: { ...agents, default: agentRef.current },
106
112
  });
107
113
  }
108
114
 
@@ -62,6 +62,12 @@ function createMockCore() {
62
62
  setMessageFilter: vi.fn(),
63
63
  setDebug: vi.fn(),
64
64
  setDefaultThrottleMs: vi.fn(),
65
+ ɵupdateConfig: vi.fn(),
66
+ ɵruntimeInfo: { status: "disconnected" },
67
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
68
+ setErrorHandler: vi.fn(),
69
+ connect: vi.fn(),
70
+ dispose: vi.fn(),
65
71
  getAgent: vi.fn(() => undefined),
66
72
  runAgent: (...args: any[]) => mockRunAgent(...args),
67
73
  runtimeUrl: "https://api.test",
@@ -82,13 +88,17 @@ function createMockCore() {
82
88
 
83
89
  let mockCoreInstance: ReturnType<typeof createMockCore>;
84
90
 
85
- vi.mock("@copilotkit/react-core/headless", () => {
91
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
92
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
93
+ const actual =
94
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
86
95
  function CopilotKitCoreReact(this: any, ...args: any[]) {
87
96
  hoisted.MockCoreConstructor(...args);
88
97
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
89
98
  if (instance) Object.assign(this, instance);
90
99
  }
91
100
  return {
101
+ ...actual,
92
102
  CopilotKitCoreReact,
93
103
  useAgent: () => {
94
104
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -147,7 +157,10 @@ vi.mock("@copilotkit/react-core/context", () => {
147
157
  };
148
158
  });
149
159
 
150
- vi.mock("@copilotkit/shared", () => ({
160
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
161
+ // The real module first: the provider evaluates @copilotkit/core, which
162
+ // needs shared's value exports.
163
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
151
164
  DEFAULT_AGENT_ID: "default",
152
165
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
153
166
  getModalityFromMimeType: (mimeType: string) => {
@@ -33,6 +33,12 @@ function createMockCore() {
33
33
  setMessageFilter: vi.fn(),
34
34
  setDebug: vi.fn(),
35
35
  setDefaultThrottleMs: vi.fn(),
36
+ ɵupdateConfig: vi.fn(),
37
+ ɵruntimeInfo: { status: "disconnected" },
38
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
39
+ setErrorHandler: vi.fn(),
40
+ connect: vi.fn(),
41
+ dispose: vi.fn(),
36
42
  getAgent: vi.fn(() => undefined),
37
43
  runtimeUrl: "https://api.test",
38
44
  runtimeTransport: "auto",
@@ -52,13 +58,17 @@ function createMockCore() {
52
58
 
53
59
  let mockCoreInstance: ReturnType<typeof createMockCore>;
54
60
 
55
- vi.mock("@copilotkit/react-core/headless", () => {
61
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
62
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
63
+ const actual =
64
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
56
65
  function CopilotKitCoreReact(this: any, ...args: any[]) {
57
66
  hoisted.MockCoreConstructor(...args);
58
67
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
59
68
  if (instance) Object.assign(this, instance);
60
69
  }
61
70
  return {
71
+ ...actual,
62
72
  CopilotKitCoreReact,
63
73
  useAgent: (props: any) => {
64
74
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -118,7 +128,10 @@ vi.mock("@copilotkit/react-core/context", () => {
118
128
  };
119
129
  });
120
130
 
121
- vi.mock("@copilotkit/shared", () => ({
131
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
132
+ // The real module first: the provider evaluates @copilotkit/core, which
133
+ // needs shared's value exports.
134
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
122
135
  DEFAULT_AGENT_ID: "default",
123
136
  createLicenseContextValue: () => ({
124
137
  status: null,
@@ -60,6 +60,12 @@ function createMockCore() {
60
60
  setMessageFilter: vi.fn(),
61
61
  setDebug: vi.fn(),
62
62
  setDefaultThrottleMs: vi.fn(),
63
+ ɵupdateConfig: vi.fn(),
64
+ ɵruntimeInfo: { status: "disconnected" },
65
+ ɵsubscribeToRuntimeInfo: vi.fn(() => () => {}),
66
+ setErrorHandler: vi.fn(),
67
+ connect: vi.fn(),
68
+ dispose: vi.fn(),
63
69
  getAgent: vi.fn(() => undefined),
64
70
  runAgent: mockRunAgent,
65
71
  runtimeUrl: "https://api.test",
@@ -80,13 +86,17 @@ function createMockCore() {
80
86
 
81
87
  let mockCoreInstance: ReturnType<typeof createMockCore>;
82
88
 
83
- vi.mock("@copilotkit/react-core/headless", () => {
89
+ vi.mock("@copilotkit/react-core/headless", async (importOriginal) => {
90
+ // The real entry, so the provider gets the real `ɵuseOwnedCore`.
91
+ const actual =
92
+ await importOriginal<typeof import("@copilotkit/react-core/headless")>();
84
93
  function CopilotKitCoreReact(this: any, ...args: any[]) {
85
94
  hoisted.MockCoreConstructor(...args);
86
95
  const instance = hoisted.MockCoreConstructor.mock.results.at(-1)?.value;
87
96
  if (instance) Object.assign(this, instance);
88
97
  }
89
98
  return {
99
+ ...actual,
90
100
  CopilotKitCoreReact,
91
101
  useAgent: () => {
92
102
  const ctx = require("react").useContext(hoisted.RealContext);
@@ -145,7 +155,10 @@ vi.mock("@copilotkit/react-core/context", () => {
145
155
  };
146
156
  });
147
157
 
148
- vi.mock("@copilotkit/shared", () => ({
158
+ vi.mock("@copilotkit/shared", async (importOriginal) => ({
159
+ // The real module first: the provider evaluates @copilotkit/core, which
160
+ // needs shared's value exports.
161
+ ...(await importOriginal<typeof import("@copilotkit/shared")>()),
149
162
  DEFAULT_AGENT_ID: "default",
150
163
  randomUUID: () => "test-uuid-" + Math.random().toString(36).slice(2, 8),
151
164
  getModalityFromMimeType: (mimeType: string) => {
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Hooks inside the headless `<CopilotChat agentId>` must use that chat's agent,
3
+ * as they do inside the web CopilotChat. Runs on a REAL `CopilotKitCoreReact`
4
+ * (via `TestCopilotKit`) and the real react-core hooks: mocking
5
+ * `@copilotkit/react-core/headless` (as the sibling chat tests do) would
6
+ * stub the chat configuration under test.
7
+ */
8
+ import React from "react";
9
+ import { render } from "@testing-library/react";
10
+ import { describe, it, expect } from "vitest";
11
+ import type { AbstractAgent } from "@ag-ui/client";
12
+ import {
13
+ useAgent,
14
+ useCopilotChatConfiguration,
15
+ } from "@copilotkit/react-core/headless";
16
+ import { CopilotChat, useCopilotChatContext } from "../CopilotChat";
17
+ import { SeededAgent, TestCopilotKit } from "../__mocks__/test-copilotkit";
18
+
19
+ function renderInChat(chat: React.ReactElement) {
20
+ const agents = { x: new SeededAgent() };
21
+ render(
22
+ <TestCopilotKit messages={[]} agents={agents}>
23
+ {chat}
24
+ </TestCopilotKit>,
25
+ );
26
+ return agents;
27
+ }
28
+
29
+ describe("headless CopilotChat chat configuration", () => {
30
+ it("gives hooks inside <CopilotChat agentId> that agent", () => {
31
+ let seen: AbstractAgent | undefined;
32
+ function Probe() {
33
+ seen = useAgent().agent;
34
+ return null;
35
+ }
36
+
37
+ const agents = renderInChat(
38
+ <CopilotChat agentId="x">
39
+ <Probe />
40
+ </CopilotChat>,
41
+ );
42
+
43
+ expect(seen).toBe(agents.x);
44
+ });
45
+
46
+ it("gives hooks inside <CopilotChat threadId> that thread", () => {
47
+ let seenThreadId: string | undefined;
48
+ function Probe() {
49
+ seenThreadId = useCopilotChatConfiguration()?.threadId;
50
+ return null;
51
+ }
52
+
53
+ renderInChat(
54
+ <CopilotChat agentId="x" threadId="thread-1">
55
+ <Probe />
56
+ </CopilotChat>,
57
+ );
58
+
59
+ expect(seenThreadId).toBe("thread-1");
60
+ });
61
+
62
+ it("gives a <CopilotChat> without agentId the agent of the chat around it", () => {
63
+ let seenByChat: AbstractAgent | undefined;
64
+ let seenByHook: AbstractAgent | undefined;
65
+ function Probe() {
66
+ seenByChat = useCopilotChatContext().agent;
67
+ seenByHook = useAgent().agent;
68
+ return null;
69
+ }
70
+
71
+ const agents = renderInChat(
72
+ <CopilotChat agentId="x">
73
+ <CopilotChat>
74
+ <Probe />
75
+ </CopilotChat>
76
+ </CopilotChat>,
77
+ );
78
+
79
+ expect(seenByChat).toBe(agents.x);
80
+ expect(seenByHook).toBe(agents.x);
81
+ });
82
+ });