@copilotkit/react-native 1.85.0 → 1.86.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 (55) hide show
  1. package/README.md +341 -2
  2. package/USAGE.md +388 -21
  3. package/dist/{CopilotKitProvider-DBq4AhRP.d.cts → CopilotKitProvider-CQ-DpvY1.d.cts} +2 -2
  4. package/dist/{CopilotKitProvider-D8sn7G_C.mjs → CopilotKitProvider-CXQGv39c.mjs} +1 -1
  5. package/dist/{CopilotKitProvider-D8sn7G_C.mjs.map → CopilotKitProvider-CXQGv39c.mjs.map} +1 -1
  6. package/dist/{CopilotKitProvider-fW21Gb7T.d.mts → CopilotKitProvider-Dc1Vbv7K.d.mts} +1 -1
  7. package/dist/{CopilotKitProvider-CjoPnabW.cjs → CopilotKitProvider-zSfbWwIg.cjs} +1 -1
  8. package/dist/{CopilotKitProvider-CjoPnabW.cjs.map → CopilotKitProvider-zSfbWwIg.cjs.map} +1 -1
  9. package/dist/components/index.cjs +1 -0
  10. package/dist/components/index.cjs.map +1 -1
  11. package/dist/components/index.mjs +1 -0
  12. package/dist/components/index.mjs.map +1 -1
  13. package/dist/generative-ui/index.cjs +612 -0
  14. package/dist/generative-ui/index.cjs.map +1 -0
  15. package/dist/generative-ui/index.d.cts +341 -0
  16. package/dist/generative-ui/index.d.mts +341 -0
  17. package/dist/generative-ui/index.mjs +549 -0
  18. package/dist/generative-ui/index.mjs.map +1 -0
  19. package/dist/headless.cjs +1 -1
  20. package/dist/headless.d.cts +1 -1
  21. package/dist/headless.d.mts +1 -1
  22. package/dist/headless.mjs +1 -1
  23. package/dist/index.cjs +2 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +2 -2
  26. package/dist/index.d.mts +1 -1
  27. package/dist/index.mjs +2 -1
  28. package/dist/index.mjs.map +1 -1
  29. package/dist/polyfills.cjs +218 -2
  30. package/dist/polyfills.cjs.map +1 -1
  31. package/dist/polyfills.mjs +217 -1
  32. package/dist/polyfills.mjs.map +1 -1
  33. package/package.json +12 -4
  34. package/project.json +6 -1
  35. package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
  36. package/scripts/verify-polyfill-barrel.mjs +154 -5
  37. package/src/__tests__/generative-ui-harness.tsx +243 -0
  38. package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
  39. package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
  40. package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
  41. package/src/__tests__/generative-ui.test.tsx +1000 -0
  42. package/src/__tests__/headless-entry-surface.test.ts +964 -34
  43. package/src/components/index.ts +6 -0
  44. package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
  45. package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
  46. package/src/generative-ui/GenerativeUISurface.tsx +303 -0
  47. package/src/generative-ui/host.tsx +138 -0
  48. package/src/generative-ui/index.ts +99 -0
  49. package/src/generative-ui/internal.ts +55 -0
  50. package/src/index.ts +8 -3
  51. package/tsdown.config.ts +1 -0
  52. package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
  53. package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
  54. package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
  55. package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
@@ -2,6 +2,12 @@
2
2
  * Component barrel — importable via `@copilotkit/react-native/components`.
3
3
  */
4
4
 
5
+ // Auto-install polyfills before anything else loads: an app can import this
6
+ // entry before the root one, and @copilotkit/core and @ag-ui/client fail at
7
+ // load time on Hermes without them (scripts/verify-polyfill-barrel.mjs checks
8
+ // that this stays the built entry's first statement).
9
+ import "../polyfills";
10
+
5
11
  export { CopilotChat } from "./CopilotChat";
6
12
  export type { CopilotChatProps } from "./CopilotChat";
7
13
 
@@ -0,0 +1,235 @@
1
+ import React, { useContext, useMemo } from "react";
2
+ import type { ComponentType, ReactNode } from "react";
3
+ import { StyleSheet, Text, View } from "react-native";
4
+ import {
5
+ GENERATIVE_UI_ACTIVITY_TYPE,
6
+ GENERATIVE_UI_CHAT_TARGET,
7
+ } from "@copilotkit/shared";
8
+ import type { GenerativeUIRejectedOperation } from "@copilotkit/shared";
9
+ import {
10
+ parseGenerativeUISurfaceContent,
11
+ SurfaceView,
12
+ useGenerativeUIActivitySurface,
13
+ useGenerativeUIRuntime,
14
+ } from "@copilotkit/react-core/v2/generative-ui/native";
15
+ import { GenerativeUIProviderPresentContext } from "./GenerativeUIProvider";
16
+ import { useDevelopmentWarnings } from "./internal";
17
+
18
+ /** The message shape this component reads: an AG-UI activity message. */
19
+ export interface GenerativeUIActivityMessage {
20
+ id?: string;
21
+ role: string;
22
+ activityType?: string;
23
+ content?: unknown;
24
+ }
25
+
26
+ /** Props of the wrapper around one generated surface. */
27
+ export interface GenerativeUIActivityWrapperProps {
28
+ surfaceId: string;
29
+ /** The agent is still writing this surface. */
30
+ isStreaming: boolean;
31
+ /**
32
+ * Set when `rejected` is not empty. The message is generic; `error.cause`
33
+ * holds the same list as `rejected`.
34
+ */
35
+ error?: Error;
36
+ /**
37
+ * The rejected operations of the latest `render_ui` call, with the
38
+ * validator's reasons. When the surface is built again from its messages
39
+ * (for example when the app restarts on a stored thread), the call
40
+ * boundaries are not known, so the list can also hold rejections of
41
+ * earlier calls on the surface.
42
+ */
43
+ rejected: GenerativeUIRejectedOperation[];
44
+ /**
45
+ * The surface. `null` when the agent's `createSurface` was rejected, so
46
+ * the surface never existed: only `error` and `rejected` are set.
47
+ */
48
+ children: ReactNode;
49
+ }
50
+
51
+ export interface GenerativeUIActivityProps {
52
+ /** An activity message from `agent.messages`. Other messages render nothing. */
53
+ message: GenerativeUIActivityMessage;
54
+ /** The agent whose messages these are (its thread owns the surface). */
55
+ agent: { threadId?: string; agentId?: string } | undefined;
56
+ /** Replaces the default wrapper around the surface. */
57
+ Wrapper?: ComponentType<GenerativeUIActivityWrapperProps>;
58
+ /**
59
+ * The surface target this component shows. Defaults to `"chat"`, the
60
+ * target of a surface the agent renders in the conversation, as in the
61
+ * web chat. Surfaces of any other target render nothing.
62
+ *
63
+ * A surface aimed at a named target is drawn by the
64
+ * `<GenerativeUISurface id>` with that id, so a chat list that renders
65
+ * every activity message leaves it out and does not show it twice. The
66
+ * agent can render into a named target only when a
67
+ * `<GenerativeUISurface>` with that id was mounted when the run started
68
+ * (the runtime rejects a `createSurface` for any other target), so this
69
+ * prop does not make a target on its own. Set it to show a surface that the agent rendered into such a
70
+ * target somewhere else, for example on a history screen after the user
71
+ * left the screen with the `<GenerativeUISurface>`. While both are on
72
+ * screen, the surface is drawn twice.
73
+ */
74
+ target?: string;
75
+ }
76
+
77
+ /**
78
+ * True for the activity messages that carry a generated surface. A type
79
+ * guard, so `agent.messages.filter(isGenerativeUIActivity)` gives activity
80
+ * messages. It does not check the content: `<GenerativeUIActivity>` does.
81
+ */
82
+ export function isGenerativeUIActivity<M extends GenerativeUIActivityMessage>(
83
+ message: M,
84
+ ): message is M & {
85
+ role: "activity";
86
+ activityType: typeof GENERATIVE_UI_ACTIVITY_TYPE;
87
+ } {
88
+ return (
89
+ message.role === "activity" &&
90
+ message.activityType === GENERATIVE_UI_ACTIVITY_TYPE
91
+ );
92
+ }
93
+
94
+ /**
95
+ * The default wrapper: the surface, and an error line under it when
96
+ * operations were rejected.
97
+ *
98
+ * It is the flex item of the parent, so it grows (`flexGrow: 1`) to fill
99
+ * the free space of a parent with a fixed size, and the stretch default of
100
+ * `alignItems` gives it the parent's cross size. A catalog root that sizes
101
+ * itself against its parent (`flex: 1`, `flexGrow` or a percentage height)
102
+ * then fills the parent, for example a screen that shows one surface.
103
+ * In a list it does not: a `FlatList` cell and the content of a
104
+ * `ScrollView` are as tall as their content, so there is no free space and
105
+ * each row keeps its own height. Siblings in a parent with a fixed size, or
106
+ * in a `ScrollView` whose `contentContainerStyle` grows, share its free
107
+ * space. Pass a `Wrapper` for any other layout.
108
+ */
109
+ export function DefaultGenerativeUIActivityWrapper({
110
+ error,
111
+ children,
112
+ }: GenerativeUIActivityWrapperProps) {
113
+ return (
114
+ <View style={styles.wrapper}>
115
+ {children}
116
+ {error ? (
117
+ <Text accessibilityRole="alert" style={styles.error}>
118
+ Part of this UI couldn't be shown.
119
+ </Text>
120
+ ) : null}
121
+ </View>
122
+ );
123
+ }
124
+
125
+ /**
126
+ * Experimental. Shows the surface that an agent rendered with `render_ui`,
127
+ * from its activity message. Put it wherever the app shows the agent's
128
+ * output: in a chat list (one per activity message), or on a screen with no
129
+ * chat at all, for example a home screen that an agent composes.
130
+ *
131
+ * Like the web chat, it shows only surfaces whose target is `"chat"`. A
132
+ * surface aimed at a `<GenerativeUISurface id>` is drawn there (see
133
+ * `target`).
134
+ *
135
+ * It renders nothing when:
136
+ * - the message is not a generative UI activity;
137
+ * - its content is malformed (in development it warns with the issues);
138
+ * - there is no `<GenerativeUIProvider>` above it, or the provider has no
139
+ * `ui` (in development it warns);
140
+ * - the agent is undefined or has no `threadId` yet, since the surface
141
+ * belongs to a thread (in development it warns);
142
+ * - the surface's target is not `target`;
143
+ * - the agent deleted the surface (`deleteSurface`).
144
+ *
145
+ * When the agent's `createSurface` was rejected, the Wrapper renders with
146
+ * `children` set to `null`, and only the error shows.
147
+ *
148
+ * Each instance warns once for each distinct problem, also when a problem
149
+ * goes away and comes back. A `message` with another id warns again.
150
+ *
151
+ * The provider ingests every activity message of `agent.messages` itself,
152
+ * with the same checks: a malformed one is skipped there too (in
153
+ * development it warns), so it cannot break the agent's run.
154
+ *
155
+ * @example
156
+ * ```tsx
157
+ * const { agent } = useAgent({ agentId: "home" });
158
+ * return agent.messages
159
+ * .filter(isGenerativeUIActivity)
160
+ * .map((message) => (
161
+ * <GenerativeUIActivity key={message.id} message={message} agent={agent} />
162
+ * ));
163
+ * ```
164
+ *
165
+ * Render every activity message, not only the latest: the latest can be a
166
+ * surface of a named target, or a deleted surface, and render nothing. For a
167
+ * placeholder until the agent renders, use `<GenerativeUISurface id
168
+ * fallback>`, which knows whether its target has a surface.
169
+ */
170
+ export function GenerativeUIActivity({
171
+ message,
172
+ agent,
173
+ Wrapper = DefaultGenerativeUIActivityWrapper,
174
+ target = GENERATIVE_UI_CHAT_TARGET,
175
+ }: GenerativeUIActivityProps) {
176
+ const runtime = useGenerativeUIRuntime();
177
+ const hasProvider = useContext(GenerativeUIProviderPresentContext);
178
+ const isSurface = isGenerativeUIActivity(message);
179
+ const rawContent = isSurface ? message.content : undefined;
180
+ const parsed = useMemo(
181
+ () => (isSurface ? parseGenerativeUISurfaceContent(rawContent) : undefined),
182
+ [isSurface, rawContent],
183
+ );
184
+ const content = parsed?.content;
185
+ const threadId = agent?.threadId;
186
+ const agentId = agent?.agentId;
187
+ let problem: string | undefined;
188
+ if (isSurface) {
189
+ if (!runtime) {
190
+ problem = hasProvider
191
+ ? "the <GenerativeUIProvider> above it has no `ui`."
192
+ : "there is no <GenerativeUIProvider> above it.";
193
+ } else if (parsed?.issues) {
194
+ problem = `the content of activity message ${JSON.stringify(message.id ?? "")} is malformed: ${parsed.issues.join("; ")}.`;
195
+ } else if (!agent) {
196
+ problem = "the agent is undefined.";
197
+ } else if (!threadId) {
198
+ problem = "the agent has no threadId yet.";
199
+ }
200
+ }
201
+ useDevelopmentWarnings(
202
+ [
203
+ problem === undefined
204
+ ? undefined
205
+ : `[generativeUI] <GenerativeUIActivity> renders nothing: ${problem}`,
206
+ ],
207
+ message.id,
208
+ );
209
+ // The provider ingests the messages of every agent it watches as well.
210
+ // Ingesting here too covers an agent the provider has not seen yet.
211
+ const { surface, rejected, error } = useGenerativeUIActivitySurface({
212
+ runtime,
213
+ threadId,
214
+ agentId,
215
+ content,
216
+ target,
217
+ });
218
+
219
+ if (!content || !surface) return null;
220
+ return (
221
+ <Wrapper
222
+ surfaceId={content.surfaceId}
223
+ isStreaming={content.status === "streaming"}
224
+ error={error}
225
+ rejected={rejected}
226
+ >
227
+ {surface.failed ? null : <SurfaceView surface={surface} />}
228
+ </Wrapper>
229
+ );
230
+ }
231
+
232
+ const styles = StyleSheet.create({
233
+ wrapper: { flexGrow: 1 },
234
+ error: { marginTop: 8, fontSize: 12, color: "#dc2626" },
235
+ });
@@ -0,0 +1,171 @@
1
+ import React, { createContext, useEffect, useRef } from "react";
2
+ import type { ReactNode } from "react";
3
+ import { useCopilotKit } from "@copilotkit/react-core/v2/context";
4
+ import {
5
+ GenerativeUIHostContext,
6
+ GenerativeUIRuntimeContext,
7
+ GenerativeUIToolCallRenderer,
8
+ useGenerativeUIRoot,
9
+ } from "@copilotkit/react-core/v2/generative-ui/native";
10
+ import type {
11
+ GenerativeUIHost,
12
+ GenerativeUIToolConfig as WebGenerativeUIToolConfig,
13
+ } from "@copilotkit/react-core/v2/generative-ui/native";
14
+ import { nativeGenerativeUIHost } from "./host";
15
+ import {
16
+ describeValue,
17
+ isDevelopment,
18
+ useDevelopmentWarnings,
19
+ } from "./internal";
20
+
21
+ /**
22
+ * The number of mounted providers with a `ui`, by CopilotKit core. Each one
23
+ * sets the generative UI of every run on its core, so two of them override
24
+ * each other.
25
+ */
26
+ const mountedRoots = new WeakMap<object, number>();
27
+
28
+ /**
29
+ * The generative UI config of React Native: the web tool transport's config
30
+ * without `theme`. On the web, `theme` sets the `--a2ui-*` CSS variables of
31
+ * the surfaces. React Native has no CSS variables, so the option is left out
32
+ * of the type rather than silently ignored. Style your catalog's components
33
+ * directly.
34
+ */
35
+ export type GenerativeUIToolConfig = Omit<WebGenerativeUIToolConfig, "theme">;
36
+
37
+ /**
38
+ * The props of {@link GenerativeUIProvider}: {@link GenerativeUIToolConfig},
39
+ * the children and the host elements.
40
+ *
41
+ * A `theme` or a `transport` other than `"tool"` that gets past the type (from
42
+ * JavaScript, or through a cast) is dropped before it reaches the runtime, with
43
+ * a warning in development: the surfaces never get a theme, and the transport
44
+ * is always the tool transport.
45
+ */
46
+ export type GenerativeUIProviderProps = GenerativeUIToolConfig & {
47
+ children: ReactNode;
48
+ /**
49
+ * The host elements around the catalog's components: the surface root, the
50
+ * accessibility wrapper and the error fallback. Defaults to React Native
51
+ * views.
52
+ */
53
+ host?: GenerativeUIHost;
54
+ };
55
+
56
+ /**
57
+ * Whether a `GenerativeUIProvider` is above, so the components below can tell
58
+ * "no provider" from "a provider without `ui`" (the runtime is null in both).
59
+ */
60
+ export const GenerativeUIProviderPresentContext = createContext(false);
61
+
62
+ /**
63
+ * Experimental. Turns on generative UI for the agents of the enclosing
64
+ * `CopilotKitProvider`: the agent renders the components of `ui` (from
65
+ * `createGenerativeUI`) with the `render_ui` tool. Place it inside
66
+ * `CopilotKitProvider`. It applies to every agent run on that CopilotKit
67
+ * core, wherever the run starts in the component tree; limit it to some
68
+ * agents with `agentIds`. Show what the agent
69
+ * renders with `<GenerativeUIActivity>` (any activity message, for example in
70
+ * your own chat list or on a home screen) or `<GenerativeUISurface id>` (a
71
+ * named place in your app).
72
+ *
73
+ * The runtime needs no setup: `CopilotRuntime` adds the `render_ui` tool to
74
+ * the run when the app sends a catalog with at least one component. A
75
+ * catalog with no components gets no `render_ui` tool.
76
+ *
77
+ * Mount exactly one `GenerativeUIProvider` with a `ui` for each
78
+ * `CopilotKitProvider`, above every screen that shows generative UI, rather
79
+ * than one per screen. Each one sets the catalog and the named targets of
80
+ * every run on the core, so two of them override each other, and each
81
+ * shows only the surfaces built for its own catalog. In development, the
82
+ * second one mounted warns.
83
+ *
84
+ * It ingests every generative UI activity message in the messages of the
85
+ * agents it watches. A message whose content is malformed is skipped (in
86
+ * development it warns once for each distinct issue), as
87
+ * `<GenerativeUIActivity>` skips it.
88
+ *
89
+ * @example
90
+ * ```tsx
91
+ * const ui = createGenerativeUI({
92
+ * id: "bank",
93
+ * components: {
94
+ * BalanceCard: {
95
+ * description: "An account balance",
96
+ * props: z.object({ accountId: z.string() }),
97
+ * component: BalanceCard,
98
+ * },
99
+ * },
100
+ * });
101
+ *
102
+ * <CopilotKitProvider runtimeUrl={RUNTIME_URL}>
103
+ * <GenerativeUIProvider ui={ui}>
104
+ * <App />
105
+ * </GenerativeUIProvider>
106
+ * </CopilotKitProvider>
107
+ * ```
108
+ */
109
+ export function GenerativeUIProvider({
110
+ children,
111
+ host = nativeGenerativeUIHost,
112
+ ...props
113
+ }: GenerativeUIProviderProps) {
114
+ // Untyped callers can still pass these. Neither reaches the runtime.
115
+ const {
116
+ theme,
117
+ transport: requestedTransport,
118
+ ...config
119
+ } = props as GenerativeUIToolConfig & {
120
+ theme?: unknown;
121
+ transport?: unknown;
122
+ };
123
+ const hasTheme = theme !== undefined;
124
+ const otherTransport =
125
+ requestedTransport === undefined || requestedTransport === "tool"
126
+ ? undefined
127
+ : describeValue(requestedTransport);
128
+ const hasUI = config.ui !== undefined && config.ui !== null;
129
+ useDevelopmentWarnings([
130
+ hasTheme
131
+ ? "[generativeUI] <GenerativeUIProvider> ignores `theme`: React Native has no CSS variables. Style the components of your catalog instead."
132
+ : undefined,
133
+ otherTransport !== undefined
134
+ ? `[generativeUI] <GenerativeUIProvider> ignores transport ${otherTransport}: React Native supports only the tool transport.`
135
+ : undefined,
136
+ hasUI
137
+ ? undefined
138
+ : "[generativeUI] <GenerativeUIProvider> has no `ui`, so generative UI is off: pass the result of createGenerativeUI.",
139
+ ]);
140
+ const { copilotkit } = useCopilotKit();
141
+ const runtime = useGenerativeUIRoot(copilotkit, {
142
+ ...config,
143
+ transport: "tool",
144
+ });
145
+ const isRoot = runtime !== null;
146
+ const warnedShared = useRef(false);
147
+ useEffect(() => {
148
+ if (!isRoot) return;
149
+ const count = (mountedRoots.get(copilotkit) ?? 0) + 1;
150
+ mountedRoots.set(copilotkit, count);
151
+ if (count > 1 && !warnedShared.current && isDevelopment()) {
152
+ warnedShared.current = true;
153
+ console.warn(
154
+ "[generativeUI] more than one <GenerativeUIProvider> with a `ui` is mounted under one CopilotKitProvider. Each one sets the catalog and the targets of every agent run on that core, so they override each other. Mount one <GenerativeUIProvider> for each CopilotKitProvider, above every screen that shows generative UI.",
155
+ );
156
+ }
157
+ return () => {
158
+ mountedRoots.set(copilotkit, (mountedRoots.get(copilotkit) ?? 1) - 1);
159
+ };
160
+ }, [copilotkit, isRoot]);
161
+ return (
162
+ <GenerativeUIProviderPresentContext.Provider value={true}>
163
+ <GenerativeUIRuntimeContext.Provider value={runtime}>
164
+ <GenerativeUIHostContext.Provider value={host}>
165
+ {runtime ? <GenerativeUIToolCallRenderer /> : null}
166
+ {children}
167
+ </GenerativeUIHostContext.Provider>
168
+ </GenerativeUIRuntimeContext.Provider>
169
+ </GenerativeUIProviderPresentContext.Provider>
170
+ );
171
+ }