@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,208 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
import {
|
|
3
|
+
act,
|
|
4
|
+
fireEvent,
|
|
5
|
+
render,
|
|
6
|
+
screen,
|
|
7
|
+
waitFor,
|
|
8
|
+
} from "@testing-library/react";
|
|
9
|
+
import { describe, expect, it, vi } from "vitest";
|
|
10
|
+
import { EventType, HttpAgent } from "@ag-ui/client";
|
|
11
|
+
import type { RunAgentInput } from "@ag-ui/client";
|
|
12
|
+
import { useCopilotKit } from "@copilotkit/react-core/context";
|
|
13
|
+
import type { CopilotKitCoreReact } from "@copilotkit/react-core/context";
|
|
14
|
+
|
|
15
|
+
// The shared react-native stub passes FlatList props through unused. This one
|
|
16
|
+
// renders the rows and then the footer, which is where CopilotChat draws the
|
|
17
|
+
// interrupt element.
|
|
18
|
+
vi.mock("react-native", async () => {
|
|
19
|
+
const actual = await vi.importActual<any>("../../__mocks__/react-native");
|
|
20
|
+
return {
|
|
21
|
+
...actual,
|
|
22
|
+
FlatList: ({
|
|
23
|
+
data,
|
|
24
|
+
renderItem,
|
|
25
|
+
keyExtractor,
|
|
26
|
+
ListEmptyComponent,
|
|
27
|
+
ListFooterComponent,
|
|
28
|
+
}: any) =>
|
|
29
|
+
React.createElement(
|
|
30
|
+
"div",
|
|
31
|
+
{ "data-testid": "flatlist" },
|
|
32
|
+
data?.length
|
|
33
|
+
? data.map((item: any, index: number) =>
|
|
34
|
+
React.createElement(
|
|
35
|
+
"div",
|
|
36
|
+
{ key: keyExtractor?.(item) ?? index },
|
|
37
|
+
renderItem({ item, index, separators: {} }),
|
|
38
|
+
),
|
|
39
|
+
)
|
|
40
|
+
: ListEmptyComponent,
|
|
41
|
+
ListFooterComponent,
|
|
42
|
+
),
|
|
43
|
+
};
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
import { CopilotChat } from "../CopilotChat";
|
|
47
|
+
import { useInterrupt } from "../../headless";
|
|
48
|
+
import { TestCopilotKit } from "../../__mocks__/test-copilotkit";
|
|
49
|
+
|
|
50
|
+
function CoreProbe({
|
|
51
|
+
coreRef,
|
|
52
|
+
}: {
|
|
53
|
+
coreRef: { current: CopilotKitCoreReact | null };
|
|
54
|
+
}) {
|
|
55
|
+
coreRef.current = useCopilotKit().copilotkit;
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* An agent whose first run stops on an approval interrupt and whose later runs
|
|
61
|
+
* finish normally. It streams real AG-UI events over SSE, so core and
|
|
62
|
+
* useInterrupt see the same run lifecycle as in an app.
|
|
63
|
+
*/
|
|
64
|
+
function createInterruptingAgent() {
|
|
65
|
+
const inputs: RunAgentInput[] = [];
|
|
66
|
+
const agent = new HttpAgent({
|
|
67
|
+
url: "http://localhost/agent",
|
|
68
|
+
fetch: async (_url, init) => {
|
|
69
|
+
const input = JSON.parse(String(init.body)) as RunAgentInput;
|
|
70
|
+
inputs.push(input);
|
|
71
|
+
const { threadId, runId } = input;
|
|
72
|
+
const events = [
|
|
73
|
+
{ type: EventType.RUN_STARTED, threadId, runId },
|
|
74
|
+
{
|
|
75
|
+
type: EventType.RUN_FINISHED,
|
|
76
|
+
threadId,
|
|
77
|
+
runId,
|
|
78
|
+
...(inputs.length === 1
|
|
79
|
+
? {
|
|
80
|
+
outcome: {
|
|
81
|
+
type: "interrupt",
|
|
82
|
+
interrupts: [
|
|
83
|
+
{ id: "approve", reason: "approval", message: "Deploy?" },
|
|
84
|
+
],
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
: {}),
|
|
88
|
+
},
|
|
89
|
+
];
|
|
90
|
+
return new Response(
|
|
91
|
+
events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""),
|
|
92
|
+
{ headers: { "Content-Type": "text/event-stream" } },
|
|
93
|
+
);
|
|
94
|
+
},
|
|
95
|
+
});
|
|
96
|
+
return { agent, inputs };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Uses useInterrupt with the default renderInChat: true. */
|
|
100
|
+
function Approval() {
|
|
101
|
+
useInterrupt({
|
|
102
|
+
render: ({ interrupt, resolve }) => (
|
|
103
|
+
<button
|
|
104
|
+
data-testid="interrupt-ui"
|
|
105
|
+
onClick={() => void resolve({ approved: true })}
|
|
106
|
+
>
|
|
107
|
+
{interrupt?.message}
|
|
108
|
+
</button>
|
|
109
|
+
),
|
|
110
|
+
});
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const messages = [
|
|
115
|
+
{ id: "u1", role: "user", content: "Deploy the app" },
|
|
116
|
+
{ id: "a1", role: "assistant", content: "I need your approval first." },
|
|
117
|
+
];
|
|
118
|
+
|
|
119
|
+
function Chat({
|
|
120
|
+
agent,
|
|
121
|
+
coreRef,
|
|
122
|
+
withApproval = true,
|
|
123
|
+
}: {
|
|
124
|
+
agent: HttpAgent;
|
|
125
|
+
coreRef: { current: CopilotKitCoreReact | null };
|
|
126
|
+
withApproval?: boolean;
|
|
127
|
+
}) {
|
|
128
|
+
return (
|
|
129
|
+
<TestCopilotKit messages={messages} agent={agent}>
|
|
130
|
+
<CoreProbe coreRef={coreRef} />
|
|
131
|
+
{withApproval && <Approval />}
|
|
132
|
+
<CopilotChat />
|
|
133
|
+
</TestCopilotKit>
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Mounts the chat and runs the agent until it stops on the interrupt. */
|
|
138
|
+
async function renderInterruptedChat() {
|
|
139
|
+
const { agent, inputs } = createInterruptingAgent();
|
|
140
|
+
const coreRef: { current: CopilotKitCoreReact | null } = { current: null };
|
|
141
|
+
const view = render(<Chat agent={agent} coreRef={coreRef} />);
|
|
142
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
143
|
+
|
|
144
|
+
await act(async () => {
|
|
145
|
+
await coreRef.current!.runAgent({ agent });
|
|
146
|
+
});
|
|
147
|
+
await waitFor(() => expect(screen.getByTestId("interrupt-ui")).toBeTruthy());
|
|
148
|
+
return { ...view, agent, inputs, coreRef };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
describe("CopilotChat interrupt rendering", () => {
|
|
152
|
+
it("draws the interrupt element that useInterrupt publishes to core", () => {
|
|
153
|
+
const coreRef: { current: CopilotKitCoreReact | null } = { current: null };
|
|
154
|
+
render(
|
|
155
|
+
<TestCopilotKit messages={[]}>
|
|
156
|
+
<CoreProbe coreRef={coreRef} />
|
|
157
|
+
<CopilotChat />
|
|
158
|
+
</TestCopilotKit>,
|
|
159
|
+
);
|
|
160
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
161
|
+
|
|
162
|
+
act(() => {
|
|
163
|
+
coreRef.current!.setInterruptElement(
|
|
164
|
+
<div data-testid="interrupt-ui">Approve?</div>,
|
|
165
|
+
);
|
|
166
|
+
});
|
|
167
|
+
expect(screen.getByTestId("interrupt-ui").textContent).toBe("Approve?");
|
|
168
|
+
|
|
169
|
+
act(() => {
|
|
170
|
+
coreRef.current!.setInterruptElement(null);
|
|
171
|
+
});
|
|
172
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it("draws a useInterrupt element after the last message and removes it once resolved", async () => {
|
|
176
|
+
const { inputs } = await renderInterruptedChat();
|
|
177
|
+
|
|
178
|
+
const interrupt = screen.getByTestId("interrupt-ui");
|
|
179
|
+
expect(interrupt.textContent).toBe("Deploy?");
|
|
180
|
+
const lastMessage = screen.getByText("I need your approval first.");
|
|
181
|
+
expect(
|
|
182
|
+
lastMessage.compareDocumentPosition(interrupt) &
|
|
183
|
+
Node.DOCUMENT_POSITION_FOLLOWING,
|
|
184
|
+
).toBeTruthy();
|
|
185
|
+
|
|
186
|
+
await act(async () => {
|
|
187
|
+
fireEvent.click(interrupt);
|
|
188
|
+
});
|
|
189
|
+
await waitFor(() => expect(inputs).toHaveLength(2));
|
|
190
|
+
expect(inputs[1]!.resume).toEqual([
|
|
191
|
+
{
|
|
192
|
+
interruptId: "approve",
|
|
193
|
+
status: "resolved",
|
|
194
|
+
payload: { approved: true },
|
|
195
|
+
},
|
|
196
|
+
]);
|
|
197
|
+
await waitFor(() =>
|
|
198
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull(),
|
|
199
|
+
);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it("removes the useInterrupt element when its component unmounts", async () => {
|
|
203
|
+
const { agent, coreRef, rerender } = await renderInterruptedChat();
|
|
204
|
+
|
|
205
|
+
rerender(<Chat agent={agent} coreRef={coreRef} withApproval={false} />);
|
|
206
|
+
expect(screen.queryByTestId("interrupt-ui")).toBeNull();
|
|
207
|
+
});
|
|
208
|
+
});
|
|
@@ -14,7 +14,7 @@ vi.mock("react-native", () => ({
|
|
|
14
14
|
// Capture the props handed to the underlying streaming renderer so we can
|
|
15
15
|
// assert how CopilotMarkdown translates its public style map.
|
|
16
16
|
const capturedProps: any[] = [];
|
|
17
|
-
vi.mock("@copilotkit/markdown
|
|
17
|
+
vi.mock("@copilotkit/markdown/react-native", () => ({
|
|
18
18
|
StreamingMarkdownRenderer: (props: any) => {
|
|
19
19
|
capturedProps.push(props);
|
|
20
20
|
return null;
|
package/src/components/index.ts
CHANGED
|
@@ -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
|
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import React from "react";
|
|
2
|
-
import { View, Text, StyleSheet
|
|
2
|
+
import { View, Text, StyleSheet } from "react-native";
|
|
3
|
+
import type { ViewStyle } from "react-native";
|
|
3
4
|
import { CopilotMarkdown } from "../Markdown";
|
|
4
5
|
import {
|
|
5
6
|
useMarkdownRenderer,
|
|
@@ -10,7 +11,6 @@ import { formatTimestamp } from "./utils";
|
|
|
10
11
|
|
|
11
12
|
// ─── Colors ──────────────────────────────────────────────────────────────────
|
|
12
13
|
const ASSISTANT_BUBBLE_BG = "#F0F0F0";
|
|
13
|
-
const ASSISTANT_TEXT_COLOR = "#1A1A1A";
|
|
14
14
|
const TIMESTAMP_COLOR = "#999999";
|
|
15
15
|
|
|
16
16
|
/**
|
|
@@ -19,7 +19,7 @@ const TIMESTAMP_COLOR = "#999999";
|
|
|
19
19
|
export interface AssistantMessageProps {
|
|
20
20
|
/** Markdown content to render inside the bubble */
|
|
21
21
|
content: string;
|
|
22
|
-
/** When true, shows a typing indicator
|
|
22
|
+
/** When true, shows a typing indicator below any content */
|
|
23
23
|
isLoading?: boolean;
|
|
24
24
|
/** Optional timestamp displayed below the bubble */
|
|
25
25
|
timestamp?: Date;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import React, { useEffect,
|
|
1
|
+
import React, { useEffect, useState } from "react";
|
|
2
2
|
import { View, Animated, StyleSheet } from "react-native";
|
|
3
3
|
import type { ViewStyle } from "react-native";
|
|
4
4
|
|
|
@@ -21,9 +21,9 @@ const ANIMATION_DURATION = 400;
|
|
|
21
21
|
* Uses React Native's built-in `Animated` API (no Reanimated dependency).
|
|
22
22
|
*/
|
|
23
23
|
export function TypingIndicator({ style }: TypingIndicatorProps) {
|
|
24
|
-
const dot1 =
|
|
25
|
-
const dot2 =
|
|
26
|
-
const dot3 =
|
|
24
|
+
const [dot1] = useState(() => new Animated.Value(0));
|
|
25
|
+
const [dot2] = useState(() => new Animated.Value(0));
|
|
26
|
+
const [dot3] = useState(() => new Animated.Value(0));
|
|
27
27
|
|
|
28
28
|
useEffect(() => {
|
|
29
29
|
const createPulse = (dot: Animated.Value, delay: number) =>
|
|
@@ -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/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/context";
|
|
4
|
+
import {
|
|
5
|
+
GenerativeUIHostContext,
|
|
6
|
+
GenerativeUIRuntimeContext,
|
|
7
|
+
GenerativeUIToolCallRenderer,
|
|
8
|
+
useGenerativeUIRoot,
|
|
9
|
+
} from "@copilotkit/react-core/generative-ui/native";
|
|
10
|
+
import type {
|
|
11
|
+
GenerativeUIHost,
|
|
12
|
+
GenerativeUIToolConfig as WebGenerativeUIToolConfig,
|
|
13
|
+
} from "@copilotkit/react-core/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
|
+
}
|