@copilotkit/react-native 2.0.0-rc.4 → 2.0.0-rc.40

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 (111) hide show
  1. package/README.md +334 -2
  2. package/USAGE.md +382 -21
  3. package/dist/CopilotKitProvider-Cbfrm_7u.d.mts +65 -0
  4. package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-CvJYytjn.cjs} +56 -42
  5. package/dist/CopilotKitProvider-CvJYytjn.cjs.map +1 -0
  6. package/dist/CopilotKitProvider-Dv3ISMKf.d.cts +65 -0
  7. package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-oTdmylSY.mjs} +55 -42
  8. package/dist/CopilotKitProvider-oTdmylSY.mjs.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 +2 -2
  33. package/dist/headless.d.cts +2 -2
  34. package/dist/headless.d.mts +2 -2
  35. package/dist/headless.mjs +1 -1
  36. package/dist/index.cjs +131 -162
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +36 -18
  39. package/dist/index.d.mts +36 -18
  40. package/dist/index.mjs +130 -161
  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 +87 -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-provider.test.tsx +68 -73
  71. package/src/__tests__/generative-ui-harness.tsx +243 -0
  72. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  73. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  74. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  75. package/src/__tests__/generative-ui.test.tsx +1000 -0
  76. package/src/__tests__/headless-entry-surface.test.ts +979 -60
  77. package/src/__tests__/headless-integration.test.tsx +11 -1
  78. package/src/__tests__/use-attachments.test.ts +27 -2
  79. package/src/components/CopilotChat.tsx +106 -233
  80. package/src/components/CopilotModal.tsx +1 -1
  81. package/src/components/Markdown.tsx +4 -4
  82. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
  83. package/src/components/__tests__/CopilotChat.test.tsx +12 -4
  84. package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
  85. package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
  86. package/src/components/index.ts +6 -0
  87. package/src/components/messages/AssistantMessage.tsx +3 -3
  88. package/src/components/messages/TypingIndicator.tsx +4 -4
  89. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  90. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  91. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  92. package/src/generative-ui/host.tsx +138 -0
  93. package/src/generative-ui/index.ts +93 -0
  94. package/src/generative-ui/internal.ts +55 -0
  95. package/src/hooks/use-attachments.ts +95 -139
  96. package/src/index.ts +8 -3
  97. package/src/polyfills/__tests__/encoding-utf8.test.ts +112 -0
  98. package/src/polyfills/encoding.ts +160 -4
  99. package/src/types.d.ts +0 -13
  100. package/tsdown.config.ts +1 -0
  101. package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
  102. package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
  103. package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
  104. package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
  105. package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
  106. package/dist/Markdown-C_9Re36O.cjs.map +0 -1
  107. package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
  108. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  109. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  110. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  111. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
package/README.md CHANGED
@@ -5,9 +5,12 @@ Headless React Native bindings for CopilotKit. Provides a lightweight provider a
5
5
  ## Installation
6
6
 
7
7
  ```bash
8
- npm install @copilotkit/react-native
8
+ npm install @copilotkit/react-native zod
9
9
  ```
10
10
 
11
+ Write tool parameters and generative UI catalogs with `zod` 4.2 or later, the
12
+ version `@copilotkit/react-core` depends on.
13
+
11
14
  ## Polyfills
12
15
 
13
16
  React Native's JS runtime (Hermes) lacks several Web APIs that CopilotKit depends on. Import the polyfills **before any other code** in your entry point:
@@ -40,7 +43,7 @@ import {
40
43
  CopilotKitProvider,
41
44
  useAgent,
42
45
  useCopilotKit,
43
- } from "@copilotkit/react-native";
46
+ } from "@copilotkit/react-native/headless";
44
47
 
45
48
  export default function App() {
46
49
  return (
@@ -53,12 +56,341 @@ export default function App() {
53
56
 
54
57
  Re-exports hooks from `@copilotkit/react-core`: `useAgent`, `useFrontendTool`, `useComponent`, `useHumanInTheLoop`, `useInterrupt`, `useSuggestions`, `useConfigureSuggestions`, `useAgentContext`, `useThreads`, and `useCopilotKit`.
55
58
 
59
+ ## Generative UI (experimental)
60
+
61
+ `@copilotkit/react-native/generative-ui` lets the agent render a catalog of your
62
+ own native components with the `render_ui` tool. Write the catalog with `zod`
63
+ 4.2 or later: `child()` and `childList()` return zod 4 schemas. The runtime needs no change by default: `CopilotRuntime` adds the
64
+ tool when the app sends a catalog with at least one component, unless the
65
+ server sets `generativeUI: false` or limits it with
66
+ `generativeUI: { agents: [...] }`. This example needs a `home` agent on the
67
+ runtime: once the runtime has connected, `useAgent` throws without it.
68
+
69
+ ```tsx
70
+ import { useCallback, useEffect, useRef, useState } from "react";
71
+ import {
72
+ ActivityIndicator,
73
+ Pressable,
74
+ ScrollView,
75
+ Text,
76
+ View,
77
+ } from "react-native";
78
+ import { z } from "zod";
79
+ import {
80
+ CopilotKitCoreErrorCode,
81
+ CopilotKitCoreRuntimeConnectionStatus,
82
+ CopilotKitProvider,
83
+ useAgent,
84
+ useAgentContext,
85
+ useCopilotKit,
86
+ } from "@copilotkit/react-native/headless";
87
+ import {
88
+ GenerativeUIActivity,
89
+ GenerativeUIProvider,
90
+ createGenerativeUI,
91
+ isGenerativeUIActivity,
92
+ useGenerativeUIRuntime,
93
+ type GenerativeUIActivityMessage,
94
+ } from "@copilotkit/react-native/generative-ui";
95
+
96
+ const ui = createGenerativeUI({
97
+ id: "acme/bank@1",
98
+ components: {
99
+ BalanceCard: {
100
+ component: ({ account, amount }: { account: string; amount: number }) => (
101
+ <View>
102
+ <Text>{account}</Text>
103
+ <Text>{amount}</Text>
104
+ </View>
105
+ ),
106
+ description:
107
+ "The balance of one account. Copy the values from the context.",
108
+ props: z.object({ account: z.string(), amount: z.number() }),
109
+ },
110
+ },
111
+ });
112
+
113
+ type CopilotKit = ReturnType<typeof useCopilotKit>["copilotkit"];
114
+ type Agent = ReturnType<typeof useAgent>["agent"];
115
+
116
+ /**
117
+ * The errors that end a run. A failed tool call is not one of them
118
+ * (TOOL_HANDLER_FAILED, TOOL_ARGUMENT_PARSE_FAILED): its error goes back to
119
+ * the model as the result of the call, and the run goes on.
120
+ */
121
+ const RUN_FAILURES: ReadonlySet<CopilotKitCoreErrorCode> = new Set([
122
+ CopilotKitCoreErrorCode.AGENT_RUN_FAILED,
123
+ CopilotKitCoreErrorCode.AGENT_RUN_FAILED_EVENT,
124
+ CopilotKitCoreErrorCode.AGENT_RUN_ERROR_EVENT,
125
+ CopilotKitCoreErrorCode.AGENT_THREAD_LOCKED,
126
+ ]);
127
+
128
+ // Date.now() alone repeats within a millisecond; with a counter, ids do not.
129
+ let sent = 0;
130
+
131
+ /**
132
+ * Sends one user message and runs the agent. Resolves with the run's error,
133
+ * or undefined; it never rejects. It counts every run failure of this agent
134
+ * while it waits, so start one run of an agent at a time.
135
+ */
136
+ async function runTurn(copilotkit: CopilotKit, agent: Agent, content: string) {
137
+ const before = agent.messages.map((message) => message.id);
138
+ const { threadId } = agent;
139
+ let failure: Error | undefined;
140
+ const subscription = copilotkit.subscribe({
141
+ onError: ({ error, code, context }) => {
142
+ if (context.agentId === agent.agentId && RUN_FAILURES.has(code)) {
143
+ failure ??= error;
144
+ }
145
+ },
146
+ });
147
+ try {
148
+ sent += 1;
149
+ agent.addMessage({
150
+ id: `user-${Date.now()}-${sent}`,
151
+ role: "user",
152
+ content,
153
+ });
154
+ await copilotkit.runAgent({ agent });
155
+ } catch (error) {
156
+ failure ??= error instanceof Error ? error : new Error(String(error));
157
+ } finally {
158
+ subscription.unsubscribe();
159
+ }
160
+ try {
161
+ if (failure) takeBack(agent, before, threadId);
162
+ } catch (error) {
163
+ console.error("Could not take the failed turn back:", error);
164
+ }
165
+ return failure;
166
+ }
167
+
168
+ /**
169
+ * Removes the messages added since `before` (their ids), such as the user
170
+ * message and a partial reply. It keeps the surfaces: the provider keeps
171
+ * every surface that a run rendered, and the model still sees it, so the
172
+ * screen shows it too.
173
+ */
174
+ function takeBack(
175
+ agent: Agent,
176
+ before: readonly string[],
177
+ threadId: string | undefined,
178
+ ) {
179
+ // The agent moved to another thread: those messages are not this turn's.
180
+ if (agent.threadId !== threadId) return;
181
+ const kept = new Set(before);
182
+ agent.setMessages(
183
+ agent.messages.filter(
184
+ (message) => kept.has(message.id) || isGenerativeUIActivity(message),
185
+ ),
186
+ );
187
+ }
188
+
189
+ /**
190
+ * An activity message that GenerativeUIActivity draws: its surface is aimed at
191
+ * the chat (the target it shows) and the agent has not deleted it.
192
+ */
193
+ function isChatSurface(message: GenerativeUIActivityMessage) {
194
+ if (!isGenerativeUIActivity(message)) return false;
195
+ const content = message.content as {
196
+ target?: unknown;
197
+ operations?: unknown;
198
+ } | null;
199
+ const operations = Array.isArray(content?.operations)
200
+ ? content.operations
201
+ : [];
202
+ return (
203
+ content?.target === "chat" &&
204
+ !operations.some(
205
+ (op) => typeof op === "object" && op !== null && "deleteSurface" in op,
206
+ )
207
+ );
208
+ }
209
+
210
+ /**
211
+ * The chat surfaces that this device built, each message id with its operations,
212
+ * to tell whether a run rendered or updated one here. The operations alone: each
213
+ * call of the agent also refills the list of rejected operations, so a call whose
214
+ * updates were all rejected changes the content but not the surface. A surface
215
+ * whose createSurface the app rejected (`failed`) does not count: the app checks
216
+ * the operations again, prop values included, and GenerativeUIActivity then shows
217
+ * only an error line.
218
+ */
219
+ function chatSurfaces(
220
+ messages: readonly GenerativeUIActivityMessage[],
221
+ failed: (surfaceId: string) => boolean,
222
+ ) {
223
+ const built = new Map<string | undefined, string>();
224
+ for (const message of messages.filter(isChatSurface)) {
225
+ const { surfaceId, operations } = message.content as {
226
+ surfaceId?: unknown;
227
+ operations?: unknown;
228
+ };
229
+ if (typeof surfaceId === "string" && failed(surfaceId)) continue;
230
+ built.set(message.id, JSON.stringify(operations));
231
+ }
232
+ return built;
233
+ }
234
+
235
+ // Your app's data. The agent sees only what you give it with useAgentContext.
236
+ const accounts = [
237
+ { account: "Chequing", amount: 3482.1 },
238
+ { account: "Savings", amount: 6150 },
239
+ ];
240
+
241
+ function Home() {
242
+ const { copilotkit } = useCopilotKit();
243
+ // Until the runtime connects, `agent` is a stand-in (`isReady` is false). The
244
+ // registered agent replaces it, so a run started on the stand-in is lost.
245
+ // Once the runtime has connected, useAgent throws if it has no `home` agent.
246
+ const { agent, isReady } = useAgent({ agentId: "home" });
247
+ const runtime = useGenerativeUIRuntime();
248
+ // The thread it last checked: a ref, so StrictMode's second effect run sees it.
249
+ const checkedThread = useRef<string | undefined>(undefined);
250
+ const composing = useRef(false); // a ref, so a second tap is ignored at once
251
+ const [checked, setChecked] = useState(false);
252
+ const [busy, setBusy] = useState(false);
253
+ const [error, setError] = useState<string>();
254
+
255
+ useAgentContext({
256
+ description:
257
+ "The user's accounts. Show only these, with these exact balances.",
258
+ value: accounts,
259
+ });
260
+
261
+ const failed = useCallback(
262
+ (surfaceId: string) =>
263
+ !!runtime?.manager.getFailedSurface(agent.threadId, surfaceId),
264
+ [runtime, agent],
265
+ );
266
+
267
+ const compose = useCallback(async () => {
268
+ // A stand-in agent (not ready) would lose the run.
269
+ if (composing.current || !isReady) return;
270
+ composing.current = true;
271
+ setBusy(true);
272
+ setError(undefined);
273
+ try {
274
+ const before = agent.messages.map((message) => message.id);
275
+ const { threadId } = agent;
276
+ const shownBefore = chatSurfaces(agent.messages, failed);
277
+ const failure = await runTurn(copilotkit, agent, "Show my balances.");
278
+ const shownAfter = chatSurfaces(agent.messages, failed);
279
+ if (failure) {
280
+ // runTurn took the prompt back, so a retry sends it once.
281
+ setError(failure.message);
282
+ } else if (
283
+ ![...shownAfter].some(
284
+ ([id, content]) => shownBefore.get(id) !== content,
285
+ )
286
+ ) {
287
+ // This run rendered or updated nothing here. Take its prompt back too.
288
+ takeBack(agent, before, threadId);
289
+ setError("The agent rendered nothing for this screen.");
290
+ }
291
+ } catch (reason) {
292
+ setError(reason instanceof Error ? reason.message : String(reason));
293
+ } finally {
294
+ composing.current = false;
295
+ setBusy(false);
296
+ }
297
+ }, [agent, copilotkit, failed, isReady]);
298
+
299
+ // The agent and its messages live in the core and outlive this screen. Run only
300
+ // when the registered agent has no surface here yet and is not running, so a
301
+ // screen that mounts again shows what it has instead of composing it again.
302
+ // Check again when the agent moves to another thread, once it is not running
303
+ // and no compose is under way (`busy` reruns this when one ends).
304
+ useEffect(() => {
305
+ if (
306
+ !isReady ||
307
+ busy ||
308
+ composing.current ||
309
+ agent.isRunning ||
310
+ checkedThread.current === agent.threadId
311
+ ) {
312
+ return;
313
+ }
314
+ checkedThread.current = agent.threadId;
315
+ setChecked(true);
316
+ setError(undefined);
317
+ if (chatSurfaces(agent.messages, failed).size === 0) {
318
+ void compose();
319
+ }
320
+ }, [isReady, busy, agent, agent.threadId, agent.isRunning, compose, failed]);
321
+
322
+ const surfaces = agent.messages.filter(isChatSurface);
323
+ const built = chatSurfaces(agent.messages, failed);
324
+ const unreachable =
325
+ copilotkit.runtimeConnectionStatus ===
326
+ CopilotKitCoreRuntimeConnectionStatus.Error;
327
+ const waiting = !isReady || !checked || busy || agent.isRunning;
328
+
329
+ return (
330
+ <ScrollView contentContainerStyle={{ padding: 16 }}>
331
+ {surfaces.map((message) => (
332
+ <GenerativeUIActivity
333
+ key={message.id}
334
+ message={message}
335
+ agent={agent}
336
+ />
337
+ ))}
338
+ {unreachable ? (
339
+ <Text accessibilityRole="alert">
340
+ Can't reach the agent. Check the runtime URL.
341
+ </Text>
342
+ ) : waiting ? (
343
+ <ActivityIndicator />
344
+ ) : error || built.size === 0 ? (
345
+ <Pressable accessibilityRole="button" onPress={() => void compose()}>
346
+ <Text>
347
+ Couldn't load your balances{error ? ` (${error})` : ""}. Tap to try
348
+ again.
349
+ </Text>
350
+ </Pressable>
351
+ ) : null}
352
+ </ScrollView>
353
+ );
354
+ }
355
+
356
+ export default function App() {
357
+ return (
358
+ <CopilotKitProvider runtimeUrl="https://your-server/api/copilotkit">
359
+ <GenerativeUIProvider ui={ui}>
360
+ <Home />
361
+ </GenerativeUIProvider>
362
+ </CopilotKitProvider>
363
+ );
364
+ }
365
+ ```
366
+
367
+ `GenerativeUIActivity` renders the surface of one activity message, in your own
368
+ message list or on a screen with no chat. Like the web chat, it shows only
369
+ surfaces aimed at the chat; pass `target` to show another target. It renders
370
+ nothing (and warns in development) without a `GenerativeUIProvider`, under a
371
+ provider without `ui`, or while the agent has no `threadId`. The example shows
372
+ a spinner, an unreachable runtime and a retry with the reason. A failed run's
373
+ prompt is taken back, but the surfaces it rendered stay: the provider and the
374
+ model keep them. The docs add a chat list.
375
+ `GenerativeUISurface` marks a named place in the app; `style` applies while its
376
+ fallback shows too. Tool transport only; there is no standard catalog, no
377
+ `theme` prop (a `theme` passed from JavaScript is dropped with a development
378
+ warning) and no `openUrl` (it fails with "openUrl is not available on this
379
+ platform"), and the prebuilt `CopilotChat` does not draw surfaces yet. See the
380
+ [React Native docs](https://docs.copilotkit.ai/react-native#generative-ui-with-your-own-components).
381
+
56
382
  ## API Surface
57
383
 
58
384
  The root import (`@copilotkit/react-native`) IS the v2 API.
59
385
  Unlike the web SDK which has `/v2` subpath, React Native exports
60
386
  the v2 API directly from the package root.
61
387
 
388
+ The root also re-exports the chat components and `useAttachments`, which
389
+ imports `expo-document-picker` and `expo-file-system`; Metro resolves them at
390
+ bundle time, so an app that imports from the root must install both.
391
+ `@copilotkit/react-native/headless` exports the provider and hooks without
392
+ them, which is why the Quick Start above uses it.
393
+
62
394
  ## Documentation
63
395
 
64
396
  For full setup instructions, usage examples, and troubleshooting, see the [React Native docs](https://docs.copilotkit.ai/react-native).