@copilotkit/react-native 2.0.0-rc.4 → 2.0.0-rc.41
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.
- package/README.md +334 -2
- package/USAGE.md +382 -21
- package/dist/CopilotKitProvider-CBVQLdzn.d.cts +77 -0
- package/dist/{CopilotKitProvider-CE4bc6CP.mjs → CopilotKitProvider-CCBBonxr.mjs} +63 -43
- package/dist/CopilotKitProvider-CCBBonxr.mjs.map +1 -0
- package/dist/CopilotKitProvider-CtQg_0S-.d.mts +77 -0
- package/dist/{CopilotKitProvider-Byw3cqe2.cjs → CopilotKitProvider-QdcQrrSA.cjs} +69 -42
- package/dist/CopilotKitProvider-QdcQrrSA.cjs.map +1 -0
- package/dist/{Markdown-C_9Re36O.cjs → Markdown-DLopAh5W.cjs} +10 -10
- package/dist/Markdown-DLopAh5W.cjs.map +1 -0
- package/dist/{Markdown-JsYh7oSA.d.mts → Markdown-Du-b_Qpr.d.mts} +3 -3
- package/dist/{Markdown-1ips7myr.d.cts → Markdown-UXZdDjzs.d.cts} +3 -3
- package/dist/{Markdown-C6AsLHmd.mjs → Markdown-VxtPJ_yh.mjs} +4 -4
- package/dist/Markdown-VxtPJ_yh.mjs.map +1 -0
- package/dist/{MarkdownRendererContext-CAnuohIS.mjs → MarkdownRendererContext-EobUsERg.mjs} +1 -1
- package/dist/{MarkdownRendererContext-CAnuohIS.mjs.map → MarkdownRendererContext-EobUsERg.mjs.map} +1 -1
- package/dist/MarkdownRendererContext-cDEHvbw9.cjs +40 -0
- package/dist/{MarkdownRendererContext-BRNe808d.cjs.map → MarkdownRendererContext-cDEHvbw9.cjs.map} +1 -1
- package/dist/chunk-C0xms8kb.cjs +34 -0
- package/dist/components/index.cjs +78 -175
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.d.cts +2 -2
- package/dist/components/index.d.mts +2 -2
- package/dist/components/index.mjs +76 -174
- package/dist/components/index.mjs.map +1 -1
- package/dist/generative-ui/index.cjs +612 -0
- package/dist/generative-ui/index.cjs.map +1 -0
- package/dist/generative-ui/index.d.cts +341 -0
- package/dist/generative-ui/index.d.mts +341 -0
- package/dist/generative-ui/index.mjs +549 -0
- package/dist/generative-ui/index.mjs.map +1 -0
- package/dist/headless.cjs +3 -2
- package/dist/headless.d.cts +3 -3
- package/dist/headless.d.mts +3 -3
- package/dist/headless.mjs +2 -2
- package/dist/index.cjs +132 -162
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +37 -19
- package/dist/index.d.mts +37 -19
- package/dist/index.mjs +131 -162
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills/encoding.cjs +115 -5
- package/dist/polyfills/encoding.cjs.map +1 -1
- package/dist/polyfills/encoding.d.cts +31 -1
- package/dist/polyfills/encoding.d.mts +31 -1
- package/dist/polyfills/encoding.mjs +113 -6
- package/dist/polyfills/encoding.mjs.map +1 -1
- package/dist/polyfills/streams.cjs +1 -1
- package/dist/polyfills.cjs +218 -2
- package/dist/polyfills.cjs.map +1 -1
- package/dist/polyfills.mjs +217 -1
- package/dist/polyfills.mjs.map +1 -1
- package/package.json +51 -21
- package/project.json +6 -1
- package/scripts/__tests__/verify-polyfill-barrel.test.mjs +150 -0
- package/scripts/verify-polyfill-barrel.mjs +158 -11
- package/src/CopilotChat.tsx +114 -93
- package/src/CopilotKitProvider.tsx +101 -130
- package/src/CopilotPopup.tsx +2 -2
- package/src/CopilotSidebar.tsx +7 -5
- package/src/__mocks__/react-native.ts +31 -0
- package/src/__mocks__/test-copilotkit.tsx +9 -3
- package/src/__tests__/attachments-integration.test.tsx +15 -2
- package/src/__tests__/copilot-chat-agentid.test.tsx +15 -2
- package/src/__tests__/copilot-chat-attachments.test.tsx +15 -2
- package/src/__tests__/copilot-chat-configuration.test.tsx +82 -0
- package/src/__tests__/copilot-chat-threads.test.tsx +232 -0
- package/src/__tests__/copilot-popup.test.tsx +15 -2
- package/src/__tests__/copilot-sidebar.test.tsx +15 -2
- package/src/__tests__/copilotkit-alias-exports.test.ts +16 -0
- package/src/__tests__/copilotkit-provider.test.tsx +68 -73
- package/src/__tests__/generative-ui-harness.tsx +243 -0
- package/src/__tests__/generative-ui-provider-props.test-d.tsx +106 -0
- package/src/__tests__/generative-ui-rn-mock.tsx +54 -0
- package/src/__tests__/generative-ui-wiring.test.tsx +720 -0
- package/src/__tests__/generative-ui.test.tsx +1000 -0
- package/src/__tests__/headless-entry-surface.test.ts +979 -60
- package/src/__tests__/headless-integration.test.tsx +11 -1
- package/src/__tests__/use-attachments.test.ts +27 -2
- package/src/components/CopilotChat.tsx +106 -233
- package/src/components/CopilotModal.tsx +1 -1
- package/src/components/Markdown.tsx +4 -4
- package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -1
- package/src/components/__tests__/CopilotChat.test.tsx +12 -4
- package/src/components/__tests__/CopilotChatInterrupt.test.tsx +208 -0
- package/src/components/__tests__/Markdown.code-alias.test.tsx +1 -1
- package/src/components/index.ts +6 -0
- package/src/components/messages/AssistantMessage.tsx +3 -3
- package/src/components/messages/TypingIndicator.tsx +4 -4
- package/src/generative-ui/GenerativeUIActivity.tsx +235 -0
- package/src/generative-ui/GenerativeUIProvider.tsx +171 -0
- package/src/generative-ui/GenerativeUISurface.tsx +303 -0
- package/src/generative-ui/host.tsx +138 -0
- package/src/generative-ui/index.ts +93 -0
- package/src/generative-ui/internal.ts +55 -0
- package/src/headless.ts +4 -0
- package/src/hooks/use-attachments.ts +95 -139
- package/src/index.ts +8 -3
- package/src/polyfills/__tests__/encoding-utf8.test.ts +112 -0
- package/src/polyfills/encoding.ts +160 -4
- package/src/types.d.ts +0 -13
- package/tsdown.config.ts +1 -0
- package/dist/CopilotKitProvider-BWjzCdHN.d.mts +0 -121
- package/dist/CopilotKitProvider-Btm10msB.d.cts +0 -121
- package/dist/CopilotKitProvider-Byw3cqe2.cjs.map +0 -1
- package/dist/CopilotKitProvider-CE4bc6CP.mjs.map +0 -1
- package/dist/Markdown-C6AsLHmd.mjs.map +0 -1
- package/dist/Markdown-C_9Re36O.cjs.map +0 -1
- package/dist/MarkdownRendererContext-BRNe808d.cjs +0 -72
- package/dist/streaming-fetch-Bm91EsRc.cjs +0 -225
- package/dist/streaming-fetch-Bm91EsRc.cjs.map +0 -1
- package/dist/streaming-fetch-Dm1oN4f2.mjs +0 -219
- package/dist/streaming-fetch-Dm1oN4f2.mjs.map +0 -1
|
@@ -0,0 +1,549 @@
|
|
|
1
|
+
import "../polyfills.mjs";
|
|
2
|
+
import React, { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { useCopilotKit } from "@copilotkit/react-core/context";
|
|
4
|
+
import { GENERATIVE_UI_ACTIVITY_TYPE, GENERATIVE_UI_CHAT_TARGET } from "@copilotkit/shared";
|
|
5
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
6
|
+
import { Pressable, StyleSheet, Text, View } from "react-native";
|
|
7
|
+
import { GenerativeUIError, GenerativeUIHostContext, GenerativeUIRuntimeContext, GenerativeUIToolCallRenderer, SurfaceView, child, childList, createGenerativeUI, exportA2UICatalog, parseGenerativeUISurfaceContent, useGenerativeUIAccessibility, useGenerativeUIActivitySurface, useGenerativeUIFunction, useGenerativeUIRejected, useGenerativeUIRoot, useGenerativeUIRuntime, useGenerativeUIRuntime as useGenerativeUIRuntime$1, useGenerativeUIState, useManagerVersion } from "@copilotkit/react-core/generative-ui/native";
|
|
8
|
+
import { allowedComponents } from "@copilotkit/core/generative-ui";
|
|
9
|
+
|
|
10
|
+
//#region src/generative-ui/host.tsx
|
|
11
|
+
/**
|
|
12
|
+
* A surface needs no box of its own on React Native: the catalog's
|
|
13
|
+
* components lay themselves out. The web theme is a stylesheet of CSS
|
|
14
|
+
* variables, which React Native has no use for. `GenerativeUIProvider` takes
|
|
15
|
+
* no `theme` and drops one that an untyped caller passes, so the `theme` of
|
|
16
|
+
* these props is always undefined, in a custom host too; style the
|
|
17
|
+
* components of your catalog instead.
|
|
18
|
+
*/
|
|
19
|
+
function NativeSurfaceRoot({ children }) {
|
|
20
|
+
return /* @__PURE__ */ jsx(Fragment, { children });
|
|
21
|
+
}
|
|
22
|
+
/** aria-live to React Native's `accessibilityLiveRegion`. */
|
|
23
|
+
const LIVE_REGION = {
|
|
24
|
+
off: "none",
|
|
25
|
+
polite: "polite",
|
|
26
|
+
assertive: "assertive"
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* Carries the envelope's hidden state and live region to the platform (not
|
|
30
|
+
* its label or description: see below).
|
|
31
|
+
*
|
|
32
|
+
* It is a real native view, on every React Native version the package
|
|
33
|
+
* supports. `display: contents` would keep it out of the layout, but it
|
|
34
|
+
* exists only on React Native 0.77+ with the New Architecture, and even
|
|
35
|
+
* there a contents view is dropped from the native tree, and its
|
|
36
|
+
* accessibility props with it. `collapsable={false}` stops Fabric and the
|
|
37
|
+
* Android view flattener from removing it as a layout-only view for the
|
|
38
|
+
* same reason.
|
|
39
|
+
*
|
|
40
|
+
* Layout: it has no style of its own, and it cannot pass the component's
|
|
41
|
+
* sizing on, because the style of the component's root view is not one of
|
|
42
|
+
* the props it gets. The wrapper, not the component, is the flex item of the
|
|
43
|
+
* parent. A default view is a column that stretches its child across, so
|
|
44
|
+
* the component keeps the parent's width (in a column) and its own height.
|
|
45
|
+
* But a component sized against its parent's main axis loses that size: in
|
|
46
|
+
* a column, `flex: 1`, `flexGrow` or a percentage `height` resolves against
|
|
47
|
+
* the wrapper, which is only as tall as its content, so the component no
|
|
48
|
+
* longer fills the parent; in a row, the same holds for `flex`, `flexGrow`,
|
|
49
|
+
* a percentage `width` and `alignSelf`. A component that must fill its
|
|
50
|
+
* parent applies the envelope itself: give its definition
|
|
51
|
+
* `accessibility: "self"` and spread `useGenerativeUIAccessibility()` on its
|
|
52
|
+
* root view (React Native 0.71+ reads `aria-hidden` and `aria-live`), and
|
|
53
|
+
* the engine draws no wrapper around it. A custom host can also replace
|
|
54
|
+
* this wrapper.
|
|
55
|
+
*
|
|
56
|
+
* Hidden: `accessibilityElementsHidden` hides the subtree from VoiceOver,
|
|
57
|
+
* `importantForAccessibility="no-hide-descendants"` from TalkBack, and
|
|
58
|
+
* `aria-hidden` covers both on React Native 0.71+.
|
|
59
|
+
*
|
|
60
|
+
* Live region: `accessibilityLiveRegion` is Android-only. iOS has no
|
|
61
|
+
* live-region prop, so VoiceOver does not announce updates to the
|
|
62
|
+
* component by itself; a component that must be heard on iOS announces
|
|
63
|
+
* its change with `AccessibilityInfo.announceForAccessibility`.
|
|
64
|
+
*
|
|
65
|
+
* Label and description: the envelope's `aria-label` and
|
|
66
|
+
* `aria-description` are not applied. A label on this wrapper would name
|
|
67
|
+
* nothing on iOS, where a view that is not `accessible` is not an element,
|
|
68
|
+
* and making the wrapper `accessible` would merge the component and every
|
|
69
|
+
* control in it into one element. React Native also has no
|
|
70
|
+
* `aria-description` (its nearest prop is `accessibilityHint`). A component
|
|
71
|
+
* that needs a name or a hint reads them with `accessibility: "self"` and
|
|
72
|
+
* `useGenerativeUIAccessibility()`, and sets `accessibilityLabel` /
|
|
73
|
+
* `aria-label` (React Native 0.71+) and `accessibilityHint` on its own
|
|
74
|
+
* root view. Spread only the props React Native knows: it ignores
|
|
75
|
+
* `aria-description`.
|
|
76
|
+
*/
|
|
77
|
+
function NativeAccessibilityWrapper({ attributes, children }) {
|
|
78
|
+
const hidden = attributes["aria-hidden"] === true;
|
|
79
|
+
const live = attributes["aria-live"];
|
|
80
|
+
return /* @__PURE__ */ jsx(View, {
|
|
81
|
+
collapsable: false,
|
|
82
|
+
"aria-hidden": hidden || void 0,
|
|
83
|
+
accessibilityElementsHidden: hidden || void 0,
|
|
84
|
+
importantForAccessibility: hidden ? "no-hide-descendants" : void 0,
|
|
85
|
+
accessibilityLiveRegion: live ? LIVE_REGION[live] : void 0,
|
|
86
|
+
children
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function NativeNodeFallback({ message, componentId, retry }) {
|
|
90
|
+
return /* @__PURE__ */ jsxs(View, {
|
|
91
|
+
accessibilityRole: "alert",
|
|
92
|
+
testID: `generative-ui-error-${componentId}`,
|
|
93
|
+
style: styles$2.fallback,
|
|
94
|
+
children: [/* @__PURE__ */ jsxs(Text, {
|
|
95
|
+
style: styles$2.fallbackText,
|
|
96
|
+
children: ["Couldn’t display this part: ", message]
|
|
97
|
+
}), retry ? /* @__PURE__ */ jsx(Pressable, {
|
|
98
|
+
accessibilityRole: "button",
|
|
99
|
+
onPress: retry,
|
|
100
|
+
children: /* @__PURE__ */ jsx(Text, {
|
|
101
|
+
style: [styles$2.fallbackText, styles$2.retry],
|
|
102
|
+
children: "Retry"
|
|
103
|
+
})
|
|
104
|
+
}) : null]
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
/** The host elements of a surface on React Native. */
|
|
108
|
+
const nativeGenerativeUIHost = {
|
|
109
|
+
SurfaceRoot: NativeSurfaceRoot,
|
|
110
|
+
AccessibilityWrapper: NativeAccessibilityWrapper,
|
|
111
|
+
NodeFallback: NativeNodeFallback
|
|
112
|
+
};
|
|
113
|
+
const styles$2 = StyleSheet.create({
|
|
114
|
+
fallback: {
|
|
115
|
+
borderWidth: 1,
|
|
116
|
+
borderColor: "#fca5a5",
|
|
117
|
+
backgroundColor: "#fef2f2",
|
|
118
|
+
borderRadius: 8,
|
|
119
|
+
paddingVertical: 8,
|
|
120
|
+
paddingHorizontal: 12
|
|
121
|
+
},
|
|
122
|
+
fallbackText: {
|
|
123
|
+
color: "#991b1b",
|
|
124
|
+
fontSize: 13
|
|
125
|
+
},
|
|
126
|
+
retry: {
|
|
127
|
+
marginTop: 4,
|
|
128
|
+
textDecorationLine: "underline"
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region src/generative-ui/internal.ts
|
|
134
|
+
/**
|
|
135
|
+
* Helpers shared by the React Native generative UI components. Not part of
|
|
136
|
+
* the public entry.
|
|
137
|
+
*/
|
|
138
|
+
const isDevelopment = () => process.env.NODE_ENV !== "production";
|
|
139
|
+
/**
|
|
140
|
+
* Warns in development, once for each distinct message of this component
|
|
141
|
+
* instance: a message that stays the same across renders warns once, and so
|
|
142
|
+
* does one that goes away and comes back (A, B, A warns A once and B once).
|
|
143
|
+
* When `resetKey` changes (a new input, such as another activity message or
|
|
144
|
+
* another catalog), every message can warn once again. Each entry of
|
|
145
|
+
* `messages` is checked on its own; undefined entries are skipped.
|
|
146
|
+
*/
|
|
147
|
+
function useDevelopmentWarnings(messages, resetKey) {
|
|
148
|
+
const warned = useRef({
|
|
149
|
+
resetKey,
|
|
150
|
+
messages: /* @__PURE__ */ new Set()
|
|
151
|
+
});
|
|
152
|
+
useEffect(() => {
|
|
153
|
+
if (!isDevelopment()) return;
|
|
154
|
+
if (!Object.is(warned.current.resetKey, resetKey)) warned.current = {
|
|
155
|
+
resetKey,
|
|
156
|
+
messages: /* @__PURE__ */ new Set()
|
|
157
|
+
};
|
|
158
|
+
for (const message of messages) {
|
|
159
|
+
if (message === void 0 || warned.current.messages.has(message)) continue;
|
|
160
|
+
warned.current.messages.add(message);
|
|
161
|
+
console.warn(message);
|
|
162
|
+
}
|
|
163
|
+
}, [messages.join("\0"), resetKey]);
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* A value for a warning, as JSON when it has a JSON form (a string comes out
|
|
167
|
+
* quoted), so an object does not print as "[object Object]".
|
|
168
|
+
*/
|
|
169
|
+
function describeValue(value) {
|
|
170
|
+
try {
|
|
171
|
+
const json = JSON.stringify(value);
|
|
172
|
+
if (json !== void 0) return json;
|
|
173
|
+
} catch {}
|
|
174
|
+
return String(value);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
//#endregion
|
|
178
|
+
//#region src/generative-ui/GenerativeUIProvider.tsx
|
|
179
|
+
/**
|
|
180
|
+
* The number of mounted providers with a `ui`, by CopilotKit core. Each one
|
|
181
|
+
* sets the generative UI of every run on its core, so two of them override
|
|
182
|
+
* each other.
|
|
183
|
+
*/
|
|
184
|
+
const mountedRoots = /* @__PURE__ */ new WeakMap();
|
|
185
|
+
/**
|
|
186
|
+
* Whether a `GenerativeUIProvider` is above, so the components below can tell
|
|
187
|
+
* "no provider" from "a provider without `ui`" (the runtime is null in both).
|
|
188
|
+
*/
|
|
189
|
+
const GenerativeUIProviderPresentContext = createContext(false);
|
|
190
|
+
/**
|
|
191
|
+
* Experimental. Turns on generative UI for the agents of the enclosing
|
|
192
|
+
* `CopilotKitProvider`: the agent renders the components of `ui` (from
|
|
193
|
+
* `createGenerativeUI`) with the `render_ui` tool. Place it inside
|
|
194
|
+
* `CopilotKitProvider`. It applies to every agent run on that CopilotKit
|
|
195
|
+
* core, wherever the run starts in the component tree; limit it to some
|
|
196
|
+
* agents with `agentIds`. Show what the agent
|
|
197
|
+
* renders with `<GenerativeUIActivity>` (any activity message, for example in
|
|
198
|
+
* your own chat list or on a home screen) or `<GenerativeUISurface id>` (a
|
|
199
|
+
* named place in your app).
|
|
200
|
+
*
|
|
201
|
+
* The runtime needs no setup: `CopilotRuntime` adds the `render_ui` tool to
|
|
202
|
+
* the run when the app sends a catalog with at least one component. A
|
|
203
|
+
* catalog with no components gets no `render_ui` tool.
|
|
204
|
+
*
|
|
205
|
+
* Mount exactly one `GenerativeUIProvider` with a `ui` for each
|
|
206
|
+
* `CopilotKitProvider`, above every screen that shows generative UI, rather
|
|
207
|
+
* than one per screen. Each one sets the catalog and the named targets of
|
|
208
|
+
* every run on the core, so two of them override each other, and each
|
|
209
|
+
* shows only the surfaces built for its own catalog. In development, the
|
|
210
|
+
* second one mounted warns.
|
|
211
|
+
*
|
|
212
|
+
* It ingests every generative UI activity message in the messages of the
|
|
213
|
+
* agents it watches. A message whose content is malformed is skipped (in
|
|
214
|
+
* development it warns once for each distinct issue), as
|
|
215
|
+
* `<GenerativeUIActivity>` skips it.
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```tsx
|
|
219
|
+
* const ui = createGenerativeUI({
|
|
220
|
+
* id: "bank",
|
|
221
|
+
* components: {
|
|
222
|
+
* BalanceCard: {
|
|
223
|
+
* description: "An account balance",
|
|
224
|
+
* props: z.object({ accountId: z.string() }),
|
|
225
|
+
* component: BalanceCard,
|
|
226
|
+
* },
|
|
227
|
+
* },
|
|
228
|
+
* });
|
|
229
|
+
*
|
|
230
|
+
* <CopilotKitProvider runtimeUrl={RUNTIME_URL}>
|
|
231
|
+
* <GenerativeUIProvider ui={ui}>
|
|
232
|
+
* <App />
|
|
233
|
+
* </GenerativeUIProvider>
|
|
234
|
+
* </CopilotKitProvider>
|
|
235
|
+
* ```
|
|
236
|
+
*/
|
|
237
|
+
function GenerativeUIProvider({ children, host = nativeGenerativeUIHost, ...props }) {
|
|
238
|
+
const { theme, transport: requestedTransport, ...config } = props;
|
|
239
|
+
const hasTheme = theme !== void 0;
|
|
240
|
+
const otherTransport = requestedTransport === void 0 || requestedTransport === "tool" ? void 0 : describeValue(requestedTransport);
|
|
241
|
+
const hasUI = config.ui !== void 0 && config.ui !== null;
|
|
242
|
+
useDevelopmentWarnings([
|
|
243
|
+
hasTheme ? "[generativeUI] <GenerativeUIProvider> ignores `theme`: React Native has no CSS variables. Style the components of your catalog instead." : void 0,
|
|
244
|
+
otherTransport !== void 0 ? `[generativeUI] <GenerativeUIProvider> ignores transport ${otherTransport}: React Native supports only the tool transport.` : void 0,
|
|
245
|
+
hasUI ? void 0 : "[generativeUI] <GenerativeUIProvider> has no `ui`, so generative UI is off: pass the result of createGenerativeUI."
|
|
246
|
+
]);
|
|
247
|
+
const { copilotkit } = useCopilotKit();
|
|
248
|
+
const runtime = useGenerativeUIRoot(copilotkit, {
|
|
249
|
+
...config,
|
|
250
|
+
transport: "tool"
|
|
251
|
+
});
|
|
252
|
+
const isRoot = runtime !== null;
|
|
253
|
+
const warnedShared = useRef(false);
|
|
254
|
+
useEffect(() => {
|
|
255
|
+
if (!isRoot) return;
|
|
256
|
+
const count = (mountedRoots.get(copilotkit) ?? 0) + 1;
|
|
257
|
+
mountedRoots.set(copilotkit, count);
|
|
258
|
+
if (count > 1 && !warnedShared.current && isDevelopment()) {
|
|
259
|
+
warnedShared.current = true;
|
|
260
|
+
console.warn("[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.");
|
|
261
|
+
}
|
|
262
|
+
return () => {
|
|
263
|
+
mountedRoots.set(copilotkit, (mountedRoots.get(copilotkit) ?? 1) - 1);
|
|
264
|
+
};
|
|
265
|
+
}, [copilotkit, isRoot]);
|
|
266
|
+
return /* @__PURE__ */ jsx(GenerativeUIProviderPresentContext.Provider, {
|
|
267
|
+
value: true,
|
|
268
|
+
children: /* @__PURE__ */ jsx(GenerativeUIRuntimeContext.Provider, {
|
|
269
|
+
value: runtime,
|
|
270
|
+
children: /* @__PURE__ */ jsxs(GenerativeUIHostContext.Provider, {
|
|
271
|
+
value: host,
|
|
272
|
+
children: [runtime ? /* @__PURE__ */ jsx(GenerativeUIToolCallRenderer, {}) : null, children]
|
|
273
|
+
})
|
|
274
|
+
})
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
//#endregion
|
|
279
|
+
//#region src/generative-ui/GenerativeUIActivity.tsx
|
|
280
|
+
/**
|
|
281
|
+
* True for the activity messages that carry a generated surface. A type
|
|
282
|
+
* guard, so `agent.messages.filter(isGenerativeUIActivity)` gives activity
|
|
283
|
+
* messages. It does not check the content: `<GenerativeUIActivity>` does.
|
|
284
|
+
*/
|
|
285
|
+
function isGenerativeUIActivity(message) {
|
|
286
|
+
return message.role === "activity" && message.activityType === GENERATIVE_UI_ACTIVITY_TYPE;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* The default wrapper: the surface, and an error line under it when
|
|
290
|
+
* operations were rejected.
|
|
291
|
+
*
|
|
292
|
+
* It is the flex item of the parent, so it grows (`flexGrow: 1`) to fill
|
|
293
|
+
* the free space of a parent with a fixed size, and the stretch default of
|
|
294
|
+
* `alignItems` gives it the parent's cross size. A catalog root that sizes
|
|
295
|
+
* itself against its parent (`flex: 1`, `flexGrow` or a percentage height)
|
|
296
|
+
* then fills the parent, for example a screen that shows one surface.
|
|
297
|
+
* In a list it does not: a `FlatList` cell and the content of a
|
|
298
|
+
* `ScrollView` are as tall as their content, so there is no free space and
|
|
299
|
+
* each row keeps its own height. Siblings in a parent with a fixed size, or
|
|
300
|
+
* in a `ScrollView` whose `contentContainerStyle` grows, share its free
|
|
301
|
+
* space. Pass a `Wrapper` for any other layout.
|
|
302
|
+
*/
|
|
303
|
+
function DefaultGenerativeUIActivityWrapper({ error, children }) {
|
|
304
|
+
return /* @__PURE__ */ jsxs(View, {
|
|
305
|
+
style: styles$1.wrapper,
|
|
306
|
+
children: [children, error ? /* @__PURE__ */ jsx(Text, {
|
|
307
|
+
accessibilityRole: "alert",
|
|
308
|
+
style: styles$1.error,
|
|
309
|
+
children: "Part of this UI couldn't be shown."
|
|
310
|
+
}) : null]
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Experimental. Shows the surface that an agent rendered with `render_ui`,
|
|
315
|
+
* from its activity message. Put it wherever the app shows the agent's
|
|
316
|
+
* output: in a chat list (one per activity message), or on a screen with no
|
|
317
|
+
* chat at all, for example a home screen that an agent composes.
|
|
318
|
+
*
|
|
319
|
+
* Like the web chat, it shows only surfaces whose target is `"chat"`. A
|
|
320
|
+
* surface aimed at a `<GenerativeUISurface id>` is drawn there (see
|
|
321
|
+
* `target`).
|
|
322
|
+
*
|
|
323
|
+
* It renders nothing when:
|
|
324
|
+
* - the message is not a generative UI activity;
|
|
325
|
+
* - its content is malformed (in development it warns with the issues);
|
|
326
|
+
* - there is no `<GenerativeUIProvider>` above it, or the provider has no
|
|
327
|
+
* `ui` (in development it warns);
|
|
328
|
+
* - the agent is undefined or has no `threadId` yet, since the surface
|
|
329
|
+
* belongs to a thread (in development it warns);
|
|
330
|
+
* - the surface's target is not `target`;
|
|
331
|
+
* - the agent deleted the surface (`deleteSurface`).
|
|
332
|
+
*
|
|
333
|
+
* When the agent's `createSurface` was rejected, the Wrapper renders with
|
|
334
|
+
* `children` set to `null`, and only the error shows.
|
|
335
|
+
*
|
|
336
|
+
* Each instance warns once for each distinct problem, also when a problem
|
|
337
|
+
* goes away and comes back. A `message` with another id warns again.
|
|
338
|
+
*
|
|
339
|
+
* The provider ingests every activity message of `agent.messages` itself,
|
|
340
|
+
* with the same checks: a malformed one is skipped there too (in
|
|
341
|
+
* development it warns), so it cannot break the agent's run.
|
|
342
|
+
*
|
|
343
|
+
* @example
|
|
344
|
+
* ```tsx
|
|
345
|
+
* const { agent } = useAgent({ agentId: "home" });
|
|
346
|
+
* return agent.messages
|
|
347
|
+
* .filter(isGenerativeUIActivity)
|
|
348
|
+
* .map((message) => (
|
|
349
|
+
* <GenerativeUIActivity key={message.id} message={message} agent={agent} />
|
|
350
|
+
* ));
|
|
351
|
+
* ```
|
|
352
|
+
*
|
|
353
|
+
* Render every activity message, not only the latest: the latest can be a
|
|
354
|
+
* surface of a named target, or a deleted surface, and render nothing. For a
|
|
355
|
+
* placeholder until the agent renders, use `<GenerativeUISurface id
|
|
356
|
+
* fallback>`, which knows whether its target has a surface.
|
|
357
|
+
*/
|
|
358
|
+
function GenerativeUIActivity({ message, agent, Wrapper = DefaultGenerativeUIActivityWrapper, target = GENERATIVE_UI_CHAT_TARGET }) {
|
|
359
|
+
const runtime = useGenerativeUIRuntime$1();
|
|
360
|
+
const hasProvider = useContext(GenerativeUIProviderPresentContext);
|
|
361
|
+
const isSurface = isGenerativeUIActivity(message);
|
|
362
|
+
const rawContent = isSurface ? message.content : void 0;
|
|
363
|
+
const parsed = useMemo(() => isSurface ? parseGenerativeUISurfaceContent(rawContent) : void 0, [isSurface, rawContent]);
|
|
364
|
+
const content = parsed?.content;
|
|
365
|
+
const threadId = agent?.threadId;
|
|
366
|
+
const agentId = agent?.agentId;
|
|
367
|
+
let problem;
|
|
368
|
+
if (isSurface) {
|
|
369
|
+
if (!runtime) problem = hasProvider ? "the <GenerativeUIProvider> above it has no `ui`." : "there is no <GenerativeUIProvider> above it.";
|
|
370
|
+
else if (parsed?.issues) problem = `the content of activity message ${JSON.stringify(message.id ?? "")} is malformed: ${parsed.issues.join("; ")}.`;
|
|
371
|
+
else if (!agent) problem = "the agent is undefined.";
|
|
372
|
+
else if (!threadId) problem = "the agent has no threadId yet.";
|
|
373
|
+
}
|
|
374
|
+
useDevelopmentWarnings([problem === void 0 ? void 0 : `[generativeUI] <GenerativeUIActivity> renders nothing: ${problem}`], message.id);
|
|
375
|
+
const { surface, rejected, error } = useGenerativeUIActivitySurface({
|
|
376
|
+
runtime,
|
|
377
|
+
threadId,
|
|
378
|
+
agentId,
|
|
379
|
+
content,
|
|
380
|
+
target
|
|
381
|
+
});
|
|
382
|
+
if (!content || !surface) return null;
|
|
383
|
+
return /* @__PURE__ */ jsx(Wrapper, {
|
|
384
|
+
surfaceId: content.surfaceId,
|
|
385
|
+
isStreaming: content.status === "streaming",
|
|
386
|
+
error,
|
|
387
|
+
rejected,
|
|
388
|
+
children: surface.failed ? null : /* @__PURE__ */ jsx(SurfaceView, { surface })
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
const styles$1 = StyleSheet.create({
|
|
392
|
+
wrapper: { flexGrow: 1 },
|
|
393
|
+
error: {
|
|
394
|
+
marginTop: 8,
|
|
395
|
+
fontSize: 12,
|
|
396
|
+
color: "#dc2626"
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
//#endregion
|
|
401
|
+
//#region src/generative-ui/GenerativeUISurface.tsx
|
|
402
|
+
/**
|
|
403
|
+
* The default wrapper of a named-target surface: the surface, and an alert
|
|
404
|
+
* under it when operations were rejected. It draws no view of its own, so
|
|
405
|
+
* the surface lays out in the view around it (`style`).
|
|
406
|
+
*/
|
|
407
|
+
function DefaultGenerativeUISurfaceWrapper({ error, children }) {
|
|
408
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [children, error ? /* @__PURE__ */ jsx(Text, {
|
|
409
|
+
accessibilityRole: "alert",
|
|
410
|
+
style: styles.error,
|
|
411
|
+
children: "Part of this UI couldn't be shown."
|
|
412
|
+
}) : null] });
|
|
413
|
+
}
|
|
414
|
+
/**
|
|
415
|
+
* Experimental. A named place in the app where the agent can render UI. The
|
|
416
|
+
* agent sees the target, with its `description`, in each run that starts
|
|
417
|
+
* while it is mounted (the target list is sent at the start of the run).
|
|
418
|
+
*
|
|
419
|
+
* A target follows the thread that is active in the provider: the thread of
|
|
420
|
+
* the last run that started on the CopilotKit core, of any agent, including
|
|
421
|
+
* agents that the provider's `agentIds` leaves out. To show the output of
|
|
422
|
+
* one particular agent run, use `<GenerativeUIActivity>` with that agent's
|
|
423
|
+
* activity message.
|
|
424
|
+
*
|
|
425
|
+
* In development it warns once for each distinct problem of this instance
|
|
426
|
+
* (no `ui` on the provider, a `ui` that is not the provider's, unknown
|
|
427
|
+
* component names), and again for any of them after the provider's catalog
|
|
428
|
+
* changes.
|
|
429
|
+
*
|
|
430
|
+
* It throws when there is no `<GenerativeUIProvider>` above it. Under a
|
|
431
|
+
* provider with no `ui`, it shows its fallback (in development it warns).
|
|
432
|
+
* The view around it, with `style` and the test ID
|
|
433
|
+
* `generative-ui-surface-<id>`, is there in both states.
|
|
434
|
+
*
|
|
435
|
+
* @example
|
|
436
|
+
* ```tsx
|
|
437
|
+
* <GenerativeUISurface
|
|
438
|
+
* id="insights"
|
|
439
|
+
* ui={bankUI}
|
|
440
|
+
* description="Under the balances. Show spending insights here."
|
|
441
|
+
* components={["SpendingCard", "InsightCard"]}
|
|
442
|
+
* fallback={<InsightsPlaceholder />}
|
|
443
|
+
* />
|
|
444
|
+
* ```
|
|
445
|
+
*/
|
|
446
|
+
function GenerativeUISurface({ id, description, ui, components, fallback = null, style, onGenerationStart, Wrapper = DefaultGenerativeUISurfaceWrapper }) {
|
|
447
|
+
const runtime = useGenerativeUIRuntime$1();
|
|
448
|
+
const hasProvider = useContext(GenerativeUIProviderPresentContext);
|
|
449
|
+
if (!runtime && !hasProvider) throw new Error(`<GenerativeUISurface id="${id}"> must be rendered inside a <GenerativeUIProvider> from @copilotkit/react-native/generative-ui.`);
|
|
450
|
+
useManagerVersion(runtime);
|
|
451
|
+
const otherUI = runtime !== null && ui !== void 0 && ui !== runtime.ui;
|
|
452
|
+
const componentsKey = components === void 0 ? void 0 : JSON.stringify(components);
|
|
453
|
+
const catalog = runtime?.ui;
|
|
454
|
+
const allowed = useMemo(() => {
|
|
455
|
+
if (!catalog || componentsKey === void 0) return void 0;
|
|
456
|
+
return allowedComponents(JSON.parse(componentsKey), catalog);
|
|
457
|
+
}, [catalog, componentsKey]);
|
|
458
|
+
useDevelopmentWarnings([
|
|
459
|
+
runtime ? void 0 : `[generativeUI] <GenerativeUISurface id="${id}"> shows its fallback: the <GenerativeUIProvider> above it has no \`ui\`.`,
|
|
460
|
+
otherUI ? `[generativeUI] <GenerativeUISurface id="${id}">: the ui prop is not the UI of the provider. The components are checked against the UI of the provider.` : void 0,
|
|
461
|
+
allowed && allowed.warning !== "" ? `[generativeUI] <GenerativeUISurface id="${id}">: ${allowed.warning}.` : void 0
|
|
462
|
+
], catalog);
|
|
463
|
+
const allowedNames = allowed?.names;
|
|
464
|
+
useLayoutEffect(() => {
|
|
465
|
+
if (!runtime) return;
|
|
466
|
+
return runtime.manager.registerTarget(id, {
|
|
467
|
+
description,
|
|
468
|
+
components: allowedNames
|
|
469
|
+
});
|
|
470
|
+
}, [
|
|
471
|
+
runtime,
|
|
472
|
+
id,
|
|
473
|
+
description,
|
|
474
|
+
componentsKey
|
|
475
|
+
]);
|
|
476
|
+
const surface = runtime?.manager.getSurfaceForTarget(id);
|
|
477
|
+
const { rejected, error } = useGenerativeUIRejected(surface?.serverRejected, surface?.clientRejected);
|
|
478
|
+
const seen = useRef({ id });
|
|
479
|
+
const pendingStarts = useRef(0);
|
|
480
|
+
const [, setStartTick] = useState(0);
|
|
481
|
+
useEffect(() => {
|
|
482
|
+
if (!runtime) return;
|
|
483
|
+
const { manager } = runtime;
|
|
484
|
+
if (seen.current.id !== id) seen.current = { id };
|
|
485
|
+
const check = () => {
|
|
486
|
+
const current = manager.getSurfaceForTarget(id);
|
|
487
|
+
const last = seen.current.surface;
|
|
488
|
+
if (!current) {
|
|
489
|
+
if (seen.current.manager === manager) seen.current = {
|
|
490
|
+
id,
|
|
491
|
+
manager
|
|
492
|
+
};
|
|
493
|
+
return;
|
|
494
|
+
}
|
|
495
|
+
const next = {
|
|
496
|
+
key: current.key,
|
|
497
|
+
status: current.status,
|
|
498
|
+
serverRejected: current.serverRejected.length,
|
|
499
|
+
clientRejected: current.clientRejected.length
|
|
500
|
+
};
|
|
501
|
+
seen.current = {
|
|
502
|
+
id,
|
|
503
|
+
manager,
|
|
504
|
+
surface: next
|
|
505
|
+
};
|
|
506
|
+
if (next.status !== "streaming") return;
|
|
507
|
+
if (last === void 0 || last.key !== next.key || last.status !== "streaming" || next.serverRejected < last.serverRejected || next.clientRejected < last.clientRejected) {
|
|
508
|
+
pendingStarts.current += 1;
|
|
509
|
+
setStartTick((n) => n + 1);
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
check();
|
|
513
|
+
return manager.subscribe(check);
|
|
514
|
+
}, [runtime, id]);
|
|
515
|
+
const onStart = useRef(onGenerationStart);
|
|
516
|
+
onStart.current = onGenerationStart;
|
|
517
|
+
useEffect(() => {
|
|
518
|
+
while (pendingStarts.current > 0) {
|
|
519
|
+
pendingStarts.current -= 1;
|
|
520
|
+
const callback = onStart.current;
|
|
521
|
+
if (!callback) continue;
|
|
522
|
+
try {
|
|
523
|
+
callback();
|
|
524
|
+
} catch (callbackError) {
|
|
525
|
+
console.error(`[generativeUI] <GenerativeUISurface id="${id}"> onGenerationStart threw:`, callbackError);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
});
|
|
529
|
+
return /* @__PURE__ */ jsx(View, {
|
|
530
|
+
style,
|
|
531
|
+
testID: `generative-ui-surface-${id}`,
|
|
532
|
+
children: surface ? /* @__PURE__ */ jsx(Wrapper, {
|
|
533
|
+
surfaceId: surface.surfaceId,
|
|
534
|
+
isStreaming: surface.status === "streaming",
|
|
535
|
+
error,
|
|
536
|
+
rejected,
|
|
537
|
+
children: /* @__PURE__ */ jsx(SurfaceView, { surface })
|
|
538
|
+
}) : fallback
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
const styles = StyleSheet.create({ error: {
|
|
542
|
+
marginTop: 8,
|
|
543
|
+
fontSize: 12,
|
|
544
|
+
color: "#dc2626"
|
|
545
|
+
} });
|
|
546
|
+
|
|
547
|
+
//#endregion
|
|
548
|
+
export { DefaultGenerativeUIActivityWrapper, GenerativeUIActivity, GenerativeUIError, GenerativeUIProvider, GenerativeUISurface, NativeNodeFallback, child, childList, createGenerativeUI, exportA2UICatalog, isGenerativeUIActivity, nativeGenerativeUIHost, useGenerativeUIAccessibility, useGenerativeUIFunction, useGenerativeUIRuntime, useGenerativeUIState };
|
|
549
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["styles","styles","useGenerativeUIRuntime","useGenerativeUIRuntime"],"sources":["../../src/generative-ui/host.tsx","../../src/generative-ui/internal.ts","../../src/generative-ui/GenerativeUIProvider.tsx","../../src/generative-ui/GenerativeUIActivity.tsx","../../src/generative-ui/GenerativeUISurface.tsx"],"sourcesContent":["import React from \"react\";\nimport { Pressable, StyleSheet, Text, View } from \"react-native\";\nimport type {\n GenerativeUIAccessibilityWrapperProps,\n GenerativeUIHost,\n GenerativeUINodeFallbackProps,\n GenerativeUISurfaceRootProps,\n} from \"@copilotkit/react-core/generative-ui/native\";\n\n/**\n * A surface needs no box of its own on React Native: the catalog's\n * components lay themselves out. The web theme is a stylesheet of CSS\n * variables, which React Native has no use for. `GenerativeUIProvider` takes\n * no `theme` and drops one that an untyped caller passes, so the `theme` of\n * these props is always undefined, in a custom host too; style the\n * components of your catalog instead.\n */\nfunction NativeSurfaceRoot({ children }: GenerativeUISurfaceRootProps) {\n return <>{children}</>;\n}\n\n/** aria-live to React Native's `accessibilityLiveRegion`. */\nconst LIVE_REGION = {\n off: \"none\",\n polite: \"polite\",\n assertive: \"assertive\",\n} as const;\n\n/**\n * Carries the envelope's hidden state and live region to the platform (not\n * its label or description: see below).\n *\n * It is a real native view, on every React Native version the package\n * supports. `display: contents` would keep it out of the layout, but it\n * exists only on React Native 0.77+ with the New Architecture, and even\n * there a contents view is dropped from the native tree, and its\n * accessibility props with it. `collapsable={false}` stops Fabric and the\n * Android view flattener from removing it as a layout-only view for the\n * same reason.\n *\n * Layout: it has no style of its own, and it cannot pass the component's\n * sizing on, because the style of the component's root view is not one of\n * the props it gets. The wrapper, not the component, is the flex item of the\n * parent. A default view is a column that stretches its child across, so\n * the component keeps the parent's width (in a column) and its own height.\n * But a component sized against its parent's main axis loses that size: in\n * a column, `flex: 1`, `flexGrow` or a percentage `height` resolves against\n * the wrapper, which is only as tall as its content, so the component no\n * longer fills the parent; in a row, the same holds for `flex`, `flexGrow`,\n * a percentage `width` and `alignSelf`. A component that must fill its\n * parent applies the envelope itself: give its definition\n * `accessibility: \"self\"` and spread `useGenerativeUIAccessibility()` on its\n * root view (React Native 0.71+ reads `aria-hidden` and `aria-live`), and\n * the engine draws no wrapper around it. A custom host can also replace\n * this wrapper.\n *\n * Hidden: `accessibilityElementsHidden` hides the subtree from VoiceOver,\n * `importantForAccessibility=\"no-hide-descendants\"` from TalkBack, and\n * `aria-hidden` covers both on React Native 0.71+.\n *\n * Live region: `accessibilityLiveRegion` is Android-only. iOS has no\n * live-region prop, so VoiceOver does not announce updates to the\n * component by itself; a component that must be heard on iOS announces\n * its change with `AccessibilityInfo.announceForAccessibility`.\n *\n * Label and description: the envelope's `aria-label` and\n * `aria-description` are not applied. A label on this wrapper would name\n * nothing on iOS, where a view that is not `accessible` is not an element,\n * and making the wrapper `accessible` would merge the component and every\n * control in it into one element. React Native also has no\n * `aria-description` (its nearest prop is `accessibilityHint`). A component\n * that needs a name or a hint reads them with `accessibility: \"self\"` and\n * `useGenerativeUIAccessibility()`, and sets `accessibilityLabel` /\n * `aria-label` (React Native 0.71+) and `accessibilityHint` on its own\n * root view. Spread only the props React Native knows: it ignores\n * `aria-description`.\n */\nfunction NativeAccessibilityWrapper({\n attributes,\n children,\n}: GenerativeUIAccessibilityWrapperProps) {\n const hidden = attributes[\"aria-hidden\"] === true;\n const live = attributes[\"aria-live\"];\n return (\n <View\n collapsable={false}\n aria-hidden={hidden || undefined}\n accessibilityElementsHidden={hidden || undefined}\n importantForAccessibility={hidden ? \"no-hide-descendants\" : undefined}\n accessibilityLiveRegion={live ? LIVE_REGION[live] : undefined}\n >\n {children}\n </View>\n );\n}\n\nexport function NativeNodeFallback({\n message,\n componentId,\n retry,\n}: GenerativeUINodeFallbackProps) {\n return (\n <View\n accessibilityRole=\"alert\"\n testID={`generative-ui-error-${componentId}`}\n style={styles.fallback}\n >\n <Text style={styles.fallbackText}>\n Couldn’t display this part: {message}\n </Text>\n {retry ? (\n <Pressable accessibilityRole=\"button\" onPress={retry}>\n <Text style={[styles.fallbackText, styles.retry]}>Retry</Text>\n </Pressable>\n ) : null}\n </View>\n );\n}\n\n/** The host elements of a surface on React Native. */\nexport const nativeGenerativeUIHost: GenerativeUIHost = {\n SurfaceRoot: NativeSurfaceRoot,\n AccessibilityWrapper: NativeAccessibilityWrapper,\n NodeFallback: NativeNodeFallback,\n};\n\nconst styles = StyleSheet.create({\n fallback: {\n borderWidth: 1,\n borderColor: \"#fca5a5\",\n backgroundColor: \"#fef2f2\",\n borderRadius: 8,\n paddingVertical: 8,\n paddingHorizontal: 12,\n },\n fallbackText: { color: \"#991b1b\", fontSize: 13 },\n retry: { marginTop: 4, textDecorationLine: \"underline\" },\n});\n","/**\n * Helpers shared by the React Native generative UI components. Not part of\n * the public entry.\n */\nimport { useEffect, useRef } from \"react\";\n\nexport const isDevelopment = () => process.env.NODE_ENV !== \"production\";\n\n/**\n * Warns in development, once for each distinct message of this component\n * instance: a message that stays the same across renders warns once, and so\n * does one that goes away and comes back (A, B, A warns A once and B once).\n * When `resetKey` changes (a new input, such as another activity message or\n * another catalog), every message can warn once again. Each entry of\n * `messages` is checked on its own; undefined entries are skipped.\n */\nexport function useDevelopmentWarnings(\n messages: ReadonlyArray<string | undefined>,\n resetKey?: unknown,\n) {\n const warned = useRef<{ resetKey: unknown; messages: Set<string> }>({\n resetKey,\n messages: new Set(),\n });\n const key = messages.join(\"\\u0000\");\n useEffect(() => {\n if (!isDevelopment()) return;\n if (!Object.is(warned.current.resetKey, resetKey)) {\n warned.current = { resetKey, messages: new Set() };\n }\n for (const message of messages) {\n if (message === undefined || warned.current.messages.has(message)) {\n continue;\n }\n warned.current.messages.add(message);\n console.warn(message);\n }\n // `key` stands for `messages`, which is a new array on every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [key, resetKey]);\n}\n\n/**\n * A value for a warning, as JSON when it has a JSON form (a string comes out\n * quoted), so an object does not print as \"[object Object]\".\n */\nexport function describeValue(value: unknown): string {\n try {\n const json = JSON.stringify(value);\n if (json !== undefined) return json;\n } catch {\n // A cycle or a BigInt: fall through to String().\n }\n return String(value);\n}\n","import React, { createContext, useEffect, useRef } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { useCopilotKit } from \"@copilotkit/react-core/context\";\nimport {\n GenerativeUIHostContext,\n GenerativeUIRuntimeContext,\n GenerativeUIToolCallRenderer,\n useGenerativeUIRoot,\n} from \"@copilotkit/react-core/generative-ui/native\";\nimport type {\n GenerativeUIHost,\n GenerativeUIToolConfig as WebGenerativeUIToolConfig,\n} from \"@copilotkit/react-core/generative-ui/native\";\nimport { nativeGenerativeUIHost } from \"./host\";\nimport {\n describeValue,\n isDevelopment,\n useDevelopmentWarnings,\n} from \"./internal\";\n\n/**\n * The number of mounted providers with a `ui`, by CopilotKit core. Each one\n * sets the generative UI of every run on its core, so two of them override\n * each other.\n */\nconst mountedRoots = new WeakMap<object, number>();\n\n/**\n * The generative UI config of React Native: the web tool transport's config\n * without `theme`. On the web, `theme` sets the `--a2ui-*` CSS variables of\n * the surfaces. React Native has no CSS variables, so the option is left out\n * of the type rather than silently ignored. Style your catalog's components\n * directly.\n */\nexport type GenerativeUIToolConfig = Omit<WebGenerativeUIToolConfig, \"theme\">;\n\n/**\n * The props of {@link GenerativeUIProvider}: {@link GenerativeUIToolConfig},\n * the children and the host elements.\n *\n * A `theme` or a `transport` other than `\"tool\"` that gets past the type (from\n * JavaScript, or through a cast) is dropped before it reaches the runtime, with\n * a warning in development: the surfaces never get a theme, and the transport\n * is always the tool transport.\n */\nexport type GenerativeUIProviderProps = GenerativeUIToolConfig & {\n children: ReactNode;\n /**\n * The host elements around the catalog's components: the surface root, the\n * accessibility wrapper and the error fallback. Defaults to React Native\n * views.\n */\n host?: GenerativeUIHost;\n};\n\n/**\n * Whether a `GenerativeUIProvider` is above, so the components below can tell\n * \"no provider\" from \"a provider without `ui`\" (the runtime is null in both).\n */\nexport const GenerativeUIProviderPresentContext = createContext(false);\n\n/**\n * Experimental. Turns on generative UI for the agents of the enclosing\n * `CopilotKitProvider`: the agent renders the components of `ui` (from\n * `createGenerativeUI`) with the `render_ui` tool. Place it inside\n * `CopilotKitProvider`. It applies to every agent run on that CopilotKit\n * core, wherever the run starts in the component tree; limit it to some\n * agents with `agentIds`. Show what the agent\n * renders with `<GenerativeUIActivity>` (any activity message, for example in\n * your own chat list or on a home screen) or `<GenerativeUISurface id>` (a\n * named place in your app).\n *\n * The runtime needs no setup: `CopilotRuntime` adds the `render_ui` tool to\n * the run when the app sends a catalog with at least one component. A\n * catalog with no components gets no `render_ui` tool.\n *\n * Mount exactly one `GenerativeUIProvider` with a `ui` for each\n * `CopilotKitProvider`, above every screen that shows generative UI, rather\n * than one per screen. Each one sets the catalog and the named targets of\n * every run on the core, so two of them override each other, and each\n * shows only the surfaces built for its own catalog. In development, the\n * second one mounted warns.\n *\n * It ingests every generative UI activity message in the messages of the\n * agents it watches. A message whose content is malformed is skipped (in\n * development it warns once for each distinct issue), as\n * `<GenerativeUIActivity>` skips it.\n *\n * @example\n * ```tsx\n * const ui = createGenerativeUI({\n * id: \"bank\",\n * components: {\n * BalanceCard: {\n * description: \"An account balance\",\n * props: z.object({ accountId: z.string() }),\n * component: BalanceCard,\n * },\n * },\n * });\n *\n * <CopilotKitProvider runtimeUrl={RUNTIME_URL}>\n * <GenerativeUIProvider ui={ui}>\n * <App />\n * </GenerativeUIProvider>\n * </CopilotKitProvider>\n * ```\n */\nexport function GenerativeUIProvider({\n children,\n host = nativeGenerativeUIHost,\n ...props\n}: GenerativeUIProviderProps) {\n // Untyped callers can still pass these. Neither reaches the runtime.\n const {\n theme,\n transport: requestedTransport,\n ...config\n } = props as GenerativeUIToolConfig & {\n theme?: unknown;\n transport?: unknown;\n };\n const hasTheme = theme !== undefined;\n const otherTransport =\n requestedTransport === undefined || requestedTransport === \"tool\"\n ? undefined\n : describeValue(requestedTransport);\n const hasUI = config.ui !== undefined && config.ui !== null;\n useDevelopmentWarnings([\n hasTheme\n ? \"[generativeUI] <GenerativeUIProvider> ignores `theme`: React Native has no CSS variables. Style the components of your catalog instead.\"\n : undefined,\n otherTransport !== undefined\n ? `[generativeUI] <GenerativeUIProvider> ignores transport ${otherTransport}: React Native supports only the tool transport.`\n : undefined,\n hasUI\n ? undefined\n : \"[generativeUI] <GenerativeUIProvider> has no `ui`, so generative UI is off: pass the result of createGenerativeUI.\",\n ]);\n const { copilotkit } = useCopilotKit();\n const runtime = useGenerativeUIRoot(copilotkit, {\n ...config,\n transport: \"tool\",\n });\n const isRoot = runtime !== null;\n const warnedShared = useRef(false);\n useEffect(() => {\n if (!isRoot) return;\n const count = (mountedRoots.get(copilotkit) ?? 0) + 1;\n mountedRoots.set(copilotkit, count);\n if (count > 1 && !warnedShared.current && isDevelopment()) {\n warnedShared.current = true;\n console.warn(\n \"[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.\",\n );\n }\n return () => {\n mountedRoots.set(copilotkit, (mountedRoots.get(copilotkit) ?? 1) - 1);\n };\n }, [copilotkit, isRoot]);\n return (\n <GenerativeUIProviderPresentContext.Provider value={true}>\n <GenerativeUIRuntimeContext.Provider value={runtime}>\n <GenerativeUIHostContext.Provider value={host}>\n {runtime ? <GenerativeUIToolCallRenderer /> : null}\n {children}\n </GenerativeUIHostContext.Provider>\n </GenerativeUIRuntimeContext.Provider>\n </GenerativeUIProviderPresentContext.Provider>\n );\n}\n","import React, { useContext, useMemo } from \"react\";\nimport type { ComponentType, ReactNode } from \"react\";\nimport { StyleSheet, Text, View } from \"react-native\";\nimport {\n GENERATIVE_UI_ACTIVITY_TYPE,\n GENERATIVE_UI_CHAT_TARGET,\n} from \"@copilotkit/shared\";\nimport type { GenerativeUIRejectedOperation } from \"@copilotkit/shared\";\nimport {\n parseGenerativeUISurfaceContent,\n SurfaceView,\n useGenerativeUIActivitySurface,\n useGenerativeUIRuntime,\n} from \"@copilotkit/react-core/generative-ui/native\";\nimport { GenerativeUIProviderPresentContext } from \"./GenerativeUIProvider\";\nimport { useDevelopmentWarnings } from \"./internal\";\n\n/** The message shape this component reads: an AG-UI activity message. */\nexport interface GenerativeUIActivityMessage {\n id?: string;\n role: string;\n activityType?: string;\n content?: unknown;\n}\n\n/** Props of the wrapper around one generated surface. */\nexport interface GenerativeUIActivityWrapperProps {\n surfaceId: string;\n /** The agent is still writing this surface. */\n isStreaming: boolean;\n /**\n * Set when `rejected` is not empty. The message is generic; `error.cause`\n * holds the same list as `rejected`.\n */\n error?: Error;\n /**\n * The rejected operations of the latest `render_ui` call, with the\n * validator's reasons. When the surface is built again from its messages\n * (for example when the app restarts on a stored thread), the call\n * boundaries are not known, so the list can also hold rejections of\n * earlier calls on the surface.\n */\n rejected: GenerativeUIRejectedOperation[];\n /**\n * The surface. `null` when the agent's `createSurface` was rejected, so\n * the surface never existed: only `error` and `rejected` are set.\n */\n children: ReactNode;\n}\n\nexport interface GenerativeUIActivityProps {\n /** An activity message from `agent.messages`. Other messages render nothing. */\n message: GenerativeUIActivityMessage;\n /** The agent whose messages these are (its thread owns the surface). */\n agent: { threadId?: string; agentId?: string } | undefined;\n /** Replaces the default wrapper around the surface. */\n Wrapper?: ComponentType<GenerativeUIActivityWrapperProps>;\n /**\n * The surface target this component shows. Defaults to `\"chat\"`, the\n * target of a surface the agent renders in the conversation, as in the\n * web chat. Surfaces of any other target render nothing.\n *\n * A surface aimed at a named target is drawn by the\n * `<GenerativeUISurface id>` with that id, so a chat list that renders\n * every activity message leaves it out and does not show it twice. The\n * agent can render into a named target only when a\n * `<GenerativeUISurface>` with that id was mounted when the run started\n * (the runtime rejects a `createSurface` for any other target), so this\n * prop does not make a target on its own. Set it to show a surface that the agent rendered into such a\n * target somewhere else, for example on a history screen after the user\n * left the screen with the `<GenerativeUISurface>`. While both are on\n * screen, the surface is drawn twice.\n */\n target?: string;\n}\n\n/**\n * True for the activity messages that carry a generated surface. A type\n * guard, so `agent.messages.filter(isGenerativeUIActivity)` gives activity\n * messages. It does not check the content: `<GenerativeUIActivity>` does.\n */\nexport function isGenerativeUIActivity<M extends GenerativeUIActivityMessage>(\n message: M,\n): message is M & {\n role: \"activity\";\n activityType: typeof GENERATIVE_UI_ACTIVITY_TYPE;\n} {\n return (\n message.role === \"activity\" &&\n message.activityType === GENERATIVE_UI_ACTIVITY_TYPE\n );\n}\n\n/**\n * The default wrapper: the surface, and an error line under it when\n * operations were rejected.\n *\n * It is the flex item of the parent, so it grows (`flexGrow: 1`) to fill\n * the free space of a parent with a fixed size, and the stretch default of\n * `alignItems` gives it the parent's cross size. A catalog root that sizes\n * itself against its parent (`flex: 1`, `flexGrow` or a percentage height)\n * then fills the parent, for example a screen that shows one surface.\n * In a list it does not: a `FlatList` cell and the content of a\n * `ScrollView` are as tall as their content, so there is no free space and\n * each row keeps its own height. Siblings in a parent with a fixed size, or\n * in a `ScrollView` whose `contentContainerStyle` grows, share its free\n * space. Pass a `Wrapper` for any other layout.\n */\nexport function DefaultGenerativeUIActivityWrapper({\n error,\n children,\n}: GenerativeUIActivityWrapperProps) {\n return (\n <View style={styles.wrapper}>\n {children}\n {error ? (\n <Text accessibilityRole=\"alert\" style={styles.error}>\n Part of this UI couldn't be shown.\n </Text>\n ) : null}\n </View>\n );\n}\n\n/**\n * Experimental. Shows the surface that an agent rendered with `render_ui`,\n * from its activity message. Put it wherever the app shows the agent's\n * output: in a chat list (one per activity message), or on a screen with no\n * chat at all, for example a home screen that an agent composes.\n *\n * Like the web chat, it shows only surfaces whose target is `\"chat\"`. A\n * surface aimed at a `<GenerativeUISurface id>` is drawn there (see\n * `target`).\n *\n * It renders nothing when:\n * - the message is not a generative UI activity;\n * - its content is malformed (in development it warns with the issues);\n * - there is no `<GenerativeUIProvider>` above it, or the provider has no\n * `ui` (in development it warns);\n * - the agent is undefined or has no `threadId` yet, since the surface\n * belongs to a thread (in development it warns);\n * - the surface's target is not `target`;\n * - the agent deleted the surface (`deleteSurface`).\n *\n * When the agent's `createSurface` was rejected, the Wrapper renders with\n * `children` set to `null`, and only the error shows.\n *\n * Each instance warns once for each distinct problem, also when a problem\n * goes away and comes back. A `message` with another id warns again.\n *\n * The provider ingests every activity message of `agent.messages` itself,\n * with the same checks: a malformed one is skipped there too (in\n * development it warns), so it cannot break the agent's run.\n *\n * @example\n * ```tsx\n * const { agent } = useAgent({ agentId: \"home\" });\n * return agent.messages\n * .filter(isGenerativeUIActivity)\n * .map((message) => (\n * <GenerativeUIActivity key={message.id} message={message} agent={agent} />\n * ));\n * ```\n *\n * Render every activity message, not only the latest: the latest can be a\n * surface of a named target, or a deleted surface, and render nothing. For a\n * placeholder until the agent renders, use `<GenerativeUISurface id\n * fallback>`, which knows whether its target has a surface.\n */\nexport function GenerativeUIActivity({\n message,\n agent,\n Wrapper = DefaultGenerativeUIActivityWrapper,\n target = GENERATIVE_UI_CHAT_TARGET,\n}: GenerativeUIActivityProps) {\n const runtime = useGenerativeUIRuntime();\n const hasProvider = useContext(GenerativeUIProviderPresentContext);\n const isSurface = isGenerativeUIActivity(message);\n const rawContent = isSurface ? message.content : undefined;\n const parsed = useMemo(\n () => (isSurface ? parseGenerativeUISurfaceContent(rawContent) : undefined),\n [isSurface, rawContent],\n );\n const content = parsed?.content;\n const threadId = agent?.threadId;\n const agentId = agent?.agentId;\n let problem: string | undefined;\n if (isSurface) {\n if (!runtime) {\n problem = hasProvider\n ? \"the <GenerativeUIProvider> above it has no `ui`.\"\n : \"there is no <GenerativeUIProvider> above it.\";\n } else if (parsed?.issues) {\n problem = `the content of activity message ${JSON.stringify(message.id ?? \"\")} is malformed: ${parsed.issues.join(\"; \")}.`;\n } else if (!agent) {\n problem = \"the agent is undefined.\";\n } else if (!threadId) {\n problem = \"the agent has no threadId yet.\";\n }\n }\n useDevelopmentWarnings(\n [\n problem === undefined\n ? undefined\n : `[generativeUI] <GenerativeUIActivity> renders nothing: ${problem}`,\n ],\n message.id,\n );\n // The provider ingests the messages of every agent it watches as well.\n // Ingesting here too covers an agent the provider has not seen yet.\n const { surface, rejected, error } = useGenerativeUIActivitySurface({\n runtime,\n threadId,\n agentId,\n content,\n target,\n });\n\n if (!content || !surface) return null;\n return (\n <Wrapper\n surfaceId={content.surfaceId}\n isStreaming={content.status === \"streaming\"}\n error={error}\n rejected={rejected}\n >\n {surface.failed ? null : <SurfaceView surface={surface} />}\n </Wrapper>\n );\n}\n\nconst styles = StyleSheet.create({\n wrapper: { flexGrow: 1 },\n error: { marginTop: 8, fontSize: 12, color: \"#dc2626\" },\n});\n","import React, {\n useContext,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentType, ReactNode } from \"react\";\nimport { StyleSheet, Text, View } from \"react-native\";\nimport type { StyleProp, ViewStyle } from \"react-native\";\nimport { allowedComponents } from \"@copilotkit/core/generative-ui\";\nimport {\n SurfaceView,\n useGenerativeUIRejected,\n useGenerativeUIRuntime,\n useManagerVersion,\n} from \"@copilotkit/react-core/generative-ui/native\";\nimport type {\n GenerativeUI,\n GenerativeUIComponentName,\n} from \"@copilotkit/react-core/generative-ui/native\";\nimport { GenerativeUIProviderPresentContext } from \"./GenerativeUIProvider\";\nimport type { GenerativeUIActivityWrapperProps } from \"./GenerativeUIActivity\";\nimport { useDevelopmentWarnings } from \"./internal\";\n\n/**\n * The default wrapper of a named-target surface: the surface, and an alert\n * under it when operations were rejected. It draws no view of its own, so\n * the surface lays out in the view around it (`style`).\n */\nfunction DefaultGenerativeUISurfaceWrapper({\n error,\n children,\n}: GenerativeUIActivityWrapperProps) {\n return (\n <>\n {children}\n {error ? (\n <Text accessibilityRole=\"alert\" style={styles.error}>\n Part of this UI couldn't be shown.\n </Text>\n ) : null}\n </>\n );\n}\n\ntype SurfaceManager = NonNullable<\n ReturnType<typeof useGenerativeUIRuntime>\n>[\"manager\"];\n\n/** What the start detection remembers of the surface it saw last. */\ninterface SeenSurface {\n key: string;\n status: string;\n serverRejected: number;\n clientRejected: number;\n}\n\nexport type GenerativeUISurfaceProps<\n UI extends GenerativeUI<any> = GenerativeUI<any>,\n> = {\n /** Target id the agent renders into. */\n id: string;\n /**\n * Tells the model where this surface is and what to show in it, for\n * example \"The home screen, under the greeting.\"\n */\n description?: string;\n /**\n * Shown until a surface targets this id, and while the provider has no\n * `ui`.\n */\n fallback?: ReactNode;\n /**\n * The style of the view around the surface. It applies while the fallback\n * shows, too.\n */\n style?: StyleProp<ViewStyle>;\n /**\n * Called once each time the agent starts to render into this surface: for\n * each `render_ui` call, on a new surface or as an update, also when React\n * batches several starts into one render. Also called when the surface\n * mounts, its `id` changes, or the active thread changes, while the agent\n * is rendering into it. Not called again for the same call when the\n * component renders again, mounts under `<React.StrictMode>`, or gets a\n * new callback or a new runtime. Use it, for example, to scroll the\n * surface into view.\n *\n * A call is seen as new when the surface goes to \"streaming\" from another\n * status, or stays \"streaming\" while its rejected operations are reset\n * (the runtime resets them at the start of each call). When the app never\n * sees the end of one call, for example because a reconnect delivers the\n * next call already streaming and neither call had a rejected operation,\n * the two calls count as one start.\n *\n * It runs after React commits the render. An error it throws is caught\n * and logged with `console.error`, so the surface stays up.\n */\n onGenerationStart?: () => void;\n /**\n * Replaces the default wrapper around the surface, as on\n * `<GenerativeUIActivity>`. It gets the operations of the latest\n * `render_ui` call that were rejected, by the runtime or on the device,\n * and an `error` when there are any. The default draws the surface and,\n * under it, \"Part of this UI couldn't be shown.\" when some were rejected.\n * The fallback is not wrapped. A surface whose `createSurface` was\n * rejected never exists, so the fallback shows; render the activity\n * message with `<GenerativeUIActivity target>` to show that error.\n */\n Wrapper?: ComponentType<GenerativeUIActivityWrapperProps>;\n} & (\n | {\n /** The UI of the provider. It types the names in `components`. */\n ui: UI;\n /**\n * The only components that the agent can use in this surface. Left\n * out, every component of the UI is allowed.\n */\n components?: readonly GenerativeUIComponentName<UI>[];\n }\n | { ui?: undefined; components?: undefined }\n);\n\n/**\n * Experimental. A named place in the app where the agent can render UI. The\n * agent sees the target, with its `description`, in each run that starts\n * while it is mounted (the target list is sent at the start of the run).\n *\n * A target follows the thread that is active in the provider: the thread of\n * the last run that started on the CopilotKit core, of any agent, including\n * agents that the provider's `agentIds` leaves out. To show the output of\n * one particular agent run, use `<GenerativeUIActivity>` with that agent's\n * activity message.\n *\n * In development it warns once for each distinct problem of this instance\n * (no `ui` on the provider, a `ui` that is not the provider's, unknown\n * component names), and again for any of them after the provider's catalog\n * changes.\n *\n * It throws when there is no `<GenerativeUIProvider>` above it. Under a\n * provider with no `ui`, it shows its fallback (in development it warns).\n * The view around it, with `style` and the test ID\n * `generative-ui-surface-<id>`, is there in both states.\n *\n * @example\n * ```tsx\n * <GenerativeUISurface\n * id=\"insights\"\n * ui={bankUI}\n * description=\"Under the balances. Show spending insights here.\"\n * components={[\"SpendingCard\", \"InsightCard\"]}\n * fallback={<InsightsPlaceholder />}\n * />\n * ```\n */\nexport function GenerativeUISurface<\n UI extends GenerativeUI<any> = GenerativeUI<any>,\n>({\n id,\n description,\n ui,\n components,\n fallback = null,\n style,\n onGenerationStart,\n Wrapper = DefaultGenerativeUISurfaceWrapper,\n}: GenerativeUISurfaceProps<UI>) {\n const runtime = useGenerativeUIRuntime();\n const hasProvider = useContext(GenerativeUIProviderPresentContext);\n if (!runtime && !hasProvider) {\n throw new Error(\n `<GenerativeUISurface id=\"${id}\"> must be rendered inside a <GenerativeUIProvider> from @copilotkit/react-native/generative-ui.`,\n );\n }\n useManagerVersion(runtime);\n const otherUI = runtime !== null && ui !== undefined && ui !== runtime.ui;\n // A new array with the same names must not register the target again.\n const componentsKey =\n components === undefined ? undefined : JSON.stringify(components);\n const catalog = runtime?.ui;\n const allowed = useMemo(() => {\n if (!catalog || componentsKey === undefined) return undefined;\n return allowedComponents(JSON.parse(componentsKey) as string[], catalog);\n }, [catalog, componentsKey]);\n useDevelopmentWarnings(\n [\n runtime\n ? undefined\n : `[generativeUI] <GenerativeUISurface id=\"${id}\"> shows its fallback: the <GenerativeUIProvider> above it has no \\`ui\\`.`,\n otherUI\n ? `[generativeUI] <GenerativeUISurface id=\"${id}\">: the ui prop is not the UI of the provider. The components are checked against the UI of the provider.`\n : undefined,\n allowed && allowed.warning !== \"\"\n ? `[generativeUI] <GenerativeUISurface id=\"${id}\">: ${allowed.warning}.`\n : undefined,\n ],\n catalog,\n );\n const allowedNames = allowed?.names;\n useLayoutEffect(() => {\n if (!runtime) return;\n return runtime.manager.registerTarget(id, {\n description,\n components: allowedNames,\n });\n // `allowedNames` changes only with the catalog or the names.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [runtime, id, description, componentsKey]);\n const surface = runtime?.manager.getSurfaceForTarget(id);\n const { rejected, error } = useGenerativeUIRejected(\n surface?.serverRejected,\n surface?.clientRejected,\n );\n\n // Starts are detected from the manager's notifications, which come at\n // most once per ingest (only when it changes something), not from\n // renders: React can batch the \"ready\" of one call and the \"streaming\" of\n // the next into one render. What was seen last is kept in a ref, so an\n // effect that runs again (StrictMode, a new runtime) does not see the\n // same call as a new start. It is reset only when `id` changes. A new\n // runtime has a new, empty manager that the provider fills again from the\n // messages: \"no surface\" counts only from the manager that showed the\n // last one, so the rebuilt surface is not a new start either.\n const seen = useRef<{\n id: string;\n manager?: SurfaceManager;\n surface?: SeenSurface;\n }>({ id });\n const pendingStarts = useRef(0);\n const [, setStartTick] = useState(0);\n useEffect(() => {\n if (!runtime) return;\n const { manager } = runtime;\n if (seen.current.id !== id) seen.current = { id };\n const check = () => {\n const current = manager.getSurfaceForTarget(id);\n const last = seen.current.surface;\n if (!current) {\n if (seen.current.manager === manager) seen.current = { id, manager };\n return;\n }\n const next: SeenSurface = {\n key: current.key,\n status: current.status,\n serverRejected: current.serverRejected.length,\n clientRejected: current.clientRejected.length,\n };\n seen.current = { id, manager, surface: next };\n if (next.status !== \"streaming\") return;\n const isStart =\n last === undefined ||\n last.key !== next.key ||\n last.status !== \"streaming\" ||\n next.serverRejected < last.serverRejected ||\n next.clientRejected < last.clientRejected;\n if (isStart) {\n pendingStarts.current += 1;\n setStartTick((n) => n + 1);\n }\n };\n check();\n return manager.subscribe(check);\n }, [runtime, id]);\n const onStart = useRef(onGenerationStart);\n onStart.current = onGenerationStart;\n // After every commit: calls the callback once for each start seen since.\n useEffect(() => {\n while (pendingStarts.current > 0) {\n pendingStarts.current -= 1;\n const callback = onStart.current;\n if (!callback) continue;\n try {\n callback();\n } catch (callbackError) {\n console.error(\n `[generativeUI] <GenerativeUISurface id=\"${id}\"> onGenerationStart threw:`,\n callbackError,\n );\n }\n }\n });\n return (\n <View style={style} testID={`generative-ui-surface-${id}`}>\n {surface ? (\n <Wrapper\n surfaceId={surface.surfaceId}\n isStreaming={surface.status === \"streaming\"}\n error={error}\n rejected={rejected}\n >\n <SurfaceView surface={surface} />\n </Wrapper>\n ) : (\n fallback\n )}\n </View>\n );\n}\n\nconst styles = StyleSheet.create({\n error: { marginTop: 8, fontSize: 12, color: \"#dc2626\" },\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,SAAS,kBAAkB,EAAE,YAA0C;AACrE,QAAO,gCAAG,WAAY;;;AAIxB,MAAM,cAAc;CAClB,KAAK;CACL,QAAQ;CACR,WAAW;CACZ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDD,SAAS,2BAA2B,EAClC,YACA,YACwC;CACxC,MAAM,SAAS,WAAW,mBAAmB;CAC7C,MAAM,OAAO,WAAW;AACxB,QACE,oBAAC;EACC,aAAa;EACb,eAAa,UAAU;EACvB,6BAA6B,UAAU;EACvC,2BAA2B,SAAS,wBAAwB;EAC5D,yBAAyB,OAAO,YAAY,QAAQ;EAEnD;GACI;;AAIX,SAAgB,mBAAmB,EACjC,SACA,aACA,SACgC;AAChC,QACE,qBAAC;EACC,mBAAkB;EAClB,QAAQ,uBAAuB;EAC/B,OAAOA,SAAO;aAEd,qBAAC;GAAK,OAAOA,SAAO;cAAc,gCACH;IACxB,EACN,QACC,oBAAC;GAAU,mBAAkB;GAAS,SAAS;aAC7C,oBAAC;IAAK,OAAO,CAACA,SAAO,cAAcA,SAAO,MAAM;cAAE;KAAY;IACpD,GACV;GACC;;;AAKX,MAAa,yBAA2C;CACtD,aAAa;CACb,sBAAsB;CACtB,cAAc;CACf;AAED,MAAMA,WAAS,WAAW,OAAO;CAC/B,UAAU;EACR,aAAa;EACb,aAAa;EACb,iBAAiB;EACjB,cAAc;EACd,iBAAiB;EACjB,mBAAmB;EACpB;CACD,cAAc;EAAE,OAAO;EAAW,UAAU;EAAI;CAChD,OAAO;EAAE,WAAW;EAAG,oBAAoB;EAAa;CACzD,CAAC;;;;;;;;ACnIF,MAAa,sBAAsB,QAAQ,IAAI,aAAa;;;;;;;;;AAU5D,SAAgB,uBACd,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AAc,WAAW;AACzB,kBAAc,MAAM,IAAI,EAAE;;;AAG9B,SAAO;AACP,SAAO,QAAQ,UAAU,MAAM;IAC9B,CAAC,SAAS,GAAG,CAAC;CACjB,MAAM,UAAU,OAAO,kBAAkB;AACzC,SAAQ,UAAU;AAElB,iBAAgB;AACd,SAAO,cAAc,UAAU,GAAG;AAChC,iBAAc,WAAW;GACzB,MAAM,WAAW,QAAQ;AACzB,OAAI,CAAC,SAAU;AACf,OAAI;AACF,cAAU;YACH,eAAe;AACtB,YAAQ,MACN,2CAA2C,GAAG,8BAC9C,cACD;;;GAGL;AACF,QACE,oBAAC;EAAY;EAAO,QAAQ,yBAAyB;YAClD,UACC,oBAAC;GACC,WAAW,QAAQ;GACnB,aAAa,QAAQ,WAAW;GACzB;GACG;aAEV,oBAAC,eAAqB,UAAW;IACzB,GAEV;GAEG;;AAIX,MAAM,SAAS,WAAW,OAAO,EAC/B,OAAO;CAAE,WAAW;CAAG,UAAU;CAAI,OAAO;CAAW,EACxD,CAAC"}
|
package/dist/headless.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
-
const
|
|
2
|
+
const require_chunk = require('./chunk-C0xms8kb.cjs');
|
|
3
3
|
require('./polyfills.cjs');
|
|
4
|
-
const require_CopilotKitProvider = require('./CopilotKitProvider-
|
|
4
|
+
const require_CopilotKitProvider = require('./CopilotKitProvider-QdcQrrSA.cjs');
|
|
5
5
|
let _copilotkit_react_core_context = require("@copilotkit/react-core/context");
|
|
6
6
|
let _copilotkit_react_core_headless = require("@copilotkit/react-core/headless");
|
|
7
7
|
let _copilotkit_core = require("@copilotkit/core");
|
|
@@ -19,6 +19,7 @@ Object.defineProperty(exports, 'CopilotChatDefaultLabels', {
|
|
|
19
19
|
return _copilotkit_react_core_headless.CopilotChatDefaultLabels;
|
|
20
20
|
}
|
|
21
21
|
});
|
|
22
|
+
exports.CopilotKit = require_CopilotKitProvider.CopilotKit;
|
|
22
23
|
Object.defineProperty(exports, 'CopilotKitContext', {
|
|
23
24
|
enumerable: true,
|
|
24
25
|
get: function () {
|