@copilotkit/react-native 1.57.3 → 1.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/USAGE.md +116 -0
  2. package/dist/RenderToolContext-CBNKcJqz.cjs +126 -0
  3. package/dist/RenderToolContext-CBNKcJqz.cjs.map +1 -0
  4. package/dist/RenderToolContext-CszHyes6.mjs +75 -0
  5. package/dist/RenderToolContext-CszHyes6.mjs.map +1 -0
  6. package/dist/components/index.cjs +722 -0
  7. package/dist/components/index.cjs.map +1 -0
  8. package/dist/components/index.d.cts +203 -0
  9. package/dist/components/index.d.mts +203 -0
  10. package/dist/components/index.mjs +714 -0
  11. package/dist/components/index.mjs.map +1 -0
  12. package/dist/index.cjs +53 -38
  13. package/dist/index.cjs.map +1 -1
  14. package/dist/index.d.cts +102 -6
  15. package/dist/index.d.mts +100 -4
  16. package/dist/index.mjs +49 -3
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/polyfills/encoding.cjs +1 -1
  19. package/dist/polyfills/streams.cjs +1 -1
  20. package/package.json +24 -4
  21. package/src/CopilotKitProvider.tsx +2 -1
  22. package/src/__mocks__/react-native-streamdown.ts +16 -0
  23. package/src/__mocks__/react-native.ts +52 -0
  24. package/src/__tests__/headless-integration.test.tsx +16 -0
  25. package/src/components/CopilotChat.tsx +465 -0
  26. package/src/components/CopilotModal.tsx +210 -0
  27. package/src/components/Markdown.tsx +124 -0
  28. package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +418 -0
  29. package/src/components/__tests__/CopilotChat.test.tsx +390 -0
  30. package/src/components/__tests__/CopilotModal.test.tsx +257 -0
  31. package/src/components/__tests__/Markdown.test.tsx +106 -0
  32. package/src/components/index.ts +18 -0
  33. package/src/components/messages/AssistantMessage.tsx +73 -0
  34. package/src/components/messages/TypingIndicator.tsx +103 -0
  35. package/src/components/messages/UserMessage.tsx +68 -0
  36. package/src/components/messages/__tests__/messages-edge-cases.test.tsx +179 -0
  37. package/src/components/messages/__tests__/messages.test.tsx +189 -0
  38. package/src/components/messages/__tests__/utils.test.ts +39 -0
  39. package/src/components/messages/index.ts +8 -0
  40. package/src/components/messages/utils.ts +11 -0
  41. package/src/hooks/RenderToolContext.tsx +150 -0
  42. package/src/hooks/__tests__/RenderToolContext.test.tsx +264 -0
  43. package/src/hooks/__tests__/useRenderTool.test.tsx +334 -0
  44. package/src/hooks/index.ts +9 -0
  45. package/src/hooks/useRenderTool.ts +96 -0
  46. package/src/index.ts +10 -3
  47. package/tsdown.config.ts +9 -0
  48. package/vitest.config.mjs +10 -0
@@ -0,0 +1,334 @@
1
+ import React from "react";
2
+ import { render } from "@testing-library/react";
3
+ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
4
+
5
+ // ─── Mocks ────────────────────────────────────────────────────────────────────
6
+
7
+ const hoisted = vi.hoisted(() => {
8
+ const _React = require("react");
9
+ return {
10
+ RealContext: _React.createContext(null),
11
+ mockAddTool: vi.fn(),
12
+ mockRemoveTool: vi.fn(),
13
+ mockGetTool: vi.fn(() => undefined),
14
+ mockAddHookRenderToolCall: vi.fn(),
15
+ mockSubscribe: vi.fn(() => ({ unsubscribe: vi.fn() })),
16
+ };
17
+ });
18
+
19
+ vi.mock("@copilotkit/react-core/v2/headless", () => {
20
+ return {
21
+ useFrontendTool: vi.fn((_tool: any, _deps?: any) => {
22
+ // Require context — mirrors real behavior
23
+ const ctx = require("react").useContext(hoisted.RealContext);
24
+ if (!ctx) {
25
+ throw new Error("useCopilotKit must be used within CopilotKitProvider");
26
+ }
27
+ // Simulate addTool call
28
+ hoisted.mockAddTool(_tool);
29
+ }),
30
+ CopilotKitCoreReact: function CopilotKitCoreReact() {},
31
+ CopilotChatConfigurationProvider: ({ children }: any) => children,
32
+ useCopilotChatConfiguration: () => null,
33
+ CopilotChatDefaultLabels: {},
34
+ };
35
+ });
36
+
37
+ vi.mock("@copilotkit/react-core/v2/context", () => {
38
+ const _React = require("react");
39
+ return {
40
+ CopilotKitContext: hoisted.RealContext,
41
+ LicenseContext: _React.createContext({
42
+ status: null,
43
+ license: null,
44
+ checkFeature: () => true,
45
+ getLimit: () => null,
46
+ }),
47
+ useCopilotKit: () => {
48
+ const ctx = _React.useContext(hoisted.RealContext);
49
+ if (!ctx) {
50
+ throw new Error("useCopilotKit must be used within CopilotKitProvider");
51
+ }
52
+ return ctx;
53
+ },
54
+ useLicenseContext: () => ({
55
+ status: null,
56
+ license: null,
57
+ checkFeature: () => true,
58
+ getLimit: () => null,
59
+ }),
60
+ };
61
+ });
62
+
63
+ vi.mock("@copilotkit/shared", () => ({
64
+ createLicenseContextValue: () => ({
65
+ status: null,
66
+ license: null,
67
+ checkFeature: () => true,
68
+ getLimit: () => null,
69
+ }),
70
+ }));
71
+
72
+ // Import after mocks
73
+ import { useRenderTool } from "../useRenderTool";
74
+ import {
75
+ RenderToolProvider,
76
+ useRenderToolRegistry,
77
+ } from "../RenderToolContext";
78
+
79
+ // Minimal wrapper that provides both CopilotKit context and RenderToolProvider
80
+ function TestProviders({ children }: { children: React.ReactNode }) {
81
+ const mockCtx = {
82
+ copilotkit: {
83
+ addTool: hoisted.mockAddTool,
84
+ removeTool: hoisted.mockRemoveTool,
85
+ getTool: hoisted.mockGetTool,
86
+ addHookRenderToolCall: hoisted.mockAddHookRenderToolCall,
87
+ subscribe: hoisted.mockSubscribe,
88
+ },
89
+ executingToolCallIds: new Set<string>(),
90
+ };
91
+
92
+ return (
93
+ <hoisted.RealContext.Provider value={mockCtx as any}>
94
+ <RenderToolProvider>{children}</RenderToolProvider>
95
+ </hoisted.RealContext.Provider>
96
+ );
97
+ }
98
+
99
+ // ─── Tests ────────────────────────────────────────────────────────────────────
100
+
101
+ describe("useRenderTool", () => {
102
+ beforeEach(() => {
103
+ vi.clearAllMocks();
104
+ });
105
+
106
+ afterEach(() => {
107
+ vi.restoreAllMocks();
108
+ });
109
+
110
+ it("registers a tool via useFrontendTool", () => {
111
+ const mockSchema = { "~standard": { vendor: "test", version: 1 } };
112
+
113
+ function TestComponent() {
114
+ useRenderTool({
115
+ name: "test-render-tool",
116
+ description: "A tool with render",
117
+ parameters: mockSchema as any,
118
+ render: ({ args, status }) =>
119
+ React.createElement("View", null, `${status}`),
120
+ handler: async () => "done",
121
+ });
122
+ return null;
123
+ }
124
+
125
+ render(
126
+ <TestProviders>
127
+ <TestComponent />
128
+ </TestProviders>,
129
+ );
130
+
131
+ // useFrontendTool should have been called with the tool config
132
+ expect(hoisted.mockAddTool).toHaveBeenCalledWith(
133
+ expect.objectContaining({
134
+ name: "test-render-tool",
135
+ description: "A tool with render",
136
+ }),
137
+ );
138
+ });
139
+
140
+ it("stores render function in the registry", () => {
141
+ let registry: Map<string, any> | null = null;
142
+ const mockSchema = { "~standard": { vendor: "test", version: 1 } };
143
+
144
+ const renderFn = ({ args, status }: any) =>
145
+ React.createElement("View", null, `${status}`);
146
+
147
+ function ToolRegistrar() {
148
+ useRenderTool({
149
+ name: "weather-tool",
150
+ description: "Show weather",
151
+ parameters: mockSchema as any,
152
+ render: renderFn,
153
+ });
154
+ return null;
155
+ }
156
+
157
+ function RegistryReader() {
158
+ registry = useRenderToolRegistry();
159
+ return null;
160
+ }
161
+
162
+ render(
163
+ <TestProviders>
164
+ <ToolRegistrar />
165
+ <RegistryReader />
166
+ </TestProviders>,
167
+ );
168
+
169
+ expect(registry).not.toBeNull();
170
+ expect(registry!.has("weather-tool")).toBe(true);
171
+ // The stored function is a stable wrapper, not the original
172
+ expect(typeof registry!.get("weather-tool")).toBe("function");
173
+ });
174
+
175
+ it("render function in registry produces expected output", () => {
176
+ let registry: Map<string, any> | null = null;
177
+ const mockSchema = { "~standard": { vendor: "test", version: 1 } };
178
+
179
+ function ToolRegistrar() {
180
+ useRenderTool({
181
+ name: "greeting-tool",
182
+ description: "Greet someone",
183
+ parameters: mockSchema as any,
184
+ render: ({ args, status }) =>
185
+ React.createElement("Text", null, `Hello ${status}`),
186
+ });
187
+ return null;
188
+ }
189
+
190
+ function RegistryReader() {
191
+ registry = useRenderToolRegistry();
192
+ return null;
193
+ }
194
+
195
+ render(
196
+ <TestProviders>
197
+ <ToolRegistrar />
198
+ <RegistryReader />
199
+ </TestProviders>,
200
+ );
201
+
202
+ const renderFn = registry!.get("greeting-tool");
203
+ const element = renderFn({ args: {}, status: "executing" });
204
+ expect(element).not.toBeNull();
205
+ expect(element.type).toBe("Text");
206
+ expect(element.props.children).toBe("Hello executing");
207
+ });
208
+
209
+ it("throws when useRenderTool is called outside RenderToolProvider", () => {
210
+ const mockSchema = { "~standard": { vendor: "test", version: 1 } };
211
+
212
+ function TestComponent() {
213
+ useRenderTool({
214
+ name: "orphan-tool",
215
+ description: "No provider",
216
+ parameters: mockSchema as any,
217
+ render: () => React.createElement("View"),
218
+ });
219
+ return null;
220
+ }
221
+
222
+ // Need CopilotKit context but no RenderToolProvider
223
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
224
+
225
+ expect(() => {
226
+ render(
227
+ <hoisted.RealContext.Provider
228
+ value={{ copilotkit: {}, executingToolCallIds: new Set() } as any}
229
+ >
230
+ <TestComponent />
231
+ </hoisted.RealContext.Provider>,
232
+ );
233
+ }).toThrow("useRenderTool must be used within a RenderToolProvider");
234
+
235
+ spy.mockRestore();
236
+ });
237
+
238
+ it("throws when useRenderToolRegistry is called outside RenderToolProvider", () => {
239
+ function TestComponent() {
240
+ useRenderToolRegistry();
241
+ return null;
242
+ }
243
+
244
+ const spy = vi.spyOn(console, "error").mockImplementation(() => {});
245
+
246
+ expect(() => {
247
+ render(<TestComponent />);
248
+ }).toThrow(
249
+ "useRenderToolRegistry must be used within a RenderToolProvider",
250
+ );
251
+
252
+ spy.mockRestore();
253
+ });
254
+
255
+ it("unregisters the render function on unmount", () => {
256
+ let registry: Map<string, any> | null = null;
257
+ const mockSchema = { "~standard": { vendor: "test", version: 1 } };
258
+
259
+ function ToolRegistrar() {
260
+ useRenderTool({
261
+ name: "ephemeral-tool",
262
+ description: "Will unmount",
263
+ parameters: mockSchema as any,
264
+ render: () => React.createElement("View"),
265
+ });
266
+ return null;
267
+ }
268
+
269
+ function RegistryReader() {
270
+ registry = useRenderToolRegistry();
271
+ return null;
272
+ }
273
+
274
+ const { rerender } = render(
275
+ <TestProviders>
276
+ <ToolRegistrar />
277
+ <RegistryReader />
278
+ </TestProviders>,
279
+ );
280
+
281
+ expect(registry!.has("ephemeral-tool")).toBe(true);
282
+
283
+ // Re-render without the ToolRegistrar
284
+ rerender(
285
+ <TestProviders>
286
+ <RegistryReader />
287
+ </TestProviders>,
288
+ );
289
+
290
+ expect(registry!.has("ephemeral-tool")).toBe(false);
291
+ });
292
+
293
+ it("supports multiple tools registered simultaneously", () => {
294
+ let registry: Map<string, any> | null = null;
295
+ const mockSchema = { "~standard": { vendor: "test", version: 1 } };
296
+
297
+ function ToolA() {
298
+ useRenderTool({
299
+ name: "tool-a",
300
+ description: "Tool A",
301
+ parameters: mockSchema as any,
302
+ render: () => React.createElement("View"),
303
+ });
304
+ return null;
305
+ }
306
+
307
+ function ToolB() {
308
+ useRenderTool({
309
+ name: "tool-b",
310
+ description: "Tool B",
311
+ parameters: mockSchema as any,
312
+ render: () => React.createElement("View"),
313
+ });
314
+ return null;
315
+ }
316
+
317
+ function RegistryReader() {
318
+ registry = useRenderToolRegistry();
319
+ return null;
320
+ }
321
+
322
+ render(
323
+ <TestProviders>
324
+ <ToolA />
325
+ <ToolB />
326
+ <RegistryReader />
327
+ </TestProviders>,
328
+ );
329
+
330
+ expect(registry!.has("tool-a")).toBe(true);
331
+ expect(registry!.has("tool-b")).toBe(true);
332
+ expect(registry!.size).toBe(2);
333
+ });
334
+ });
@@ -0,0 +1,9 @@
1
+ export { useRenderTool } from "./useRenderTool";
2
+ export type { UseRenderToolOptions } from "./useRenderTool";
3
+
4
+ export { RenderToolProvider, useRenderToolRegistry } from "./RenderToolContext";
5
+ export type {
6
+ RenderToolProps,
7
+ RenderToolFunction,
8
+ RenderToolRegistry,
9
+ } from "./RenderToolContext";
@@ -0,0 +1,96 @@
1
+ import { useEffect, useRef } from "react";
2
+ import { useFrontendTool } from "@copilotkit/react-core/v2/headless";
3
+ import type { StandardSchemaV1 } from "@copilotkit/shared";
4
+ import type { RenderToolFunction } from "./RenderToolContext";
5
+ import { useRenderToolContext } from "./RenderToolContext";
6
+
7
+ /**
8
+ * Options for the useRenderTool hook.
9
+ */
10
+ export interface UseRenderToolOptions<T extends Record<string, unknown>> {
11
+ /** Unique name for the tool. Must match what the agent calls. */
12
+ name: string;
13
+ /** Human-readable description shown to the agent. */
14
+ description: string;
15
+ /**
16
+ * Schema describing the tool's parameters.
17
+ * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).
18
+ */
19
+ parameters: StandardSchemaV1<unknown, T>;
20
+ /**
21
+ * Render function that returns a React Native element for the tool call.
22
+ * Called by CopilotChat when it encounters a tool call message for this tool.
23
+ *
24
+ * Returns ReactElement | null (not ReactNode) because React Native's
25
+ * FlatList cannot render strings or portals.
26
+ */
27
+ render: RenderToolFunction<T>;
28
+ /**
29
+ * Optional handler executed when the tool is called.
30
+ * If omitted, the tool is render-only (the render function shows UI
31
+ * but the tool returns no result to the agent).
32
+ */
33
+ handler?: (args: T) => Promise<unknown>;
34
+ /**
35
+ * Optional agent ID to scope this tool to a specific agent.
36
+ */
37
+ agentId?: string;
38
+ }
39
+
40
+ /**
41
+ * Hook that registers a frontend tool AND a render function for it.
42
+ *
43
+ * This bridges `useFrontendTool` (which handles tool registration and
44
+ * handler execution) with a render registry so that CopilotChat can
45
+ * render React Native elements inline when it encounters tool call messages.
46
+ *
47
+ * @example
48
+ * ```tsx
49
+ * useRenderTool({
50
+ * name: "showWeather",
51
+ * description: "Display weather information",
52
+ * parameters: z.object({ city: z.string(), temp: z.number() }),
53
+ * render: ({ args, status }) => (
54
+ * <View>
55
+ * <Text>{args.city}: {args.temp}</Text>
56
+ * {status === "executing" && <ActivityIndicator />}
57
+ * </View>
58
+ * ),
59
+ * handler: async ({ city }) => {
60
+ * return { forecast: "sunny" };
61
+ * },
62
+ * });
63
+ * ```
64
+ */
65
+ export function useRenderTool<
66
+ T extends Record<string, unknown> = Record<string, unknown>,
67
+ >(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {
68
+ const { name, description, parameters, render, handler, agentId } = options;
69
+ const { register } = useRenderToolContext();
70
+
71
+ // Register the tool with the core system via useFrontendTool
72
+ useFrontendTool<T>(
73
+ {
74
+ name,
75
+ description,
76
+ parameters,
77
+ handler,
78
+ agentId,
79
+ },
80
+ deps,
81
+ );
82
+
83
+ // Use a ref so the effect cleanup always has the latest render function
84
+ const renderRef = useRef(render);
85
+ renderRef.current = render;
86
+
87
+ // Register the render function in the RenderToolContext
88
+ useEffect(() => {
89
+ // Wrap in a stable function that delegates to the ref
90
+ const stableRender: RenderToolFunction<T> = (props) =>
91
+ renderRef.current(props);
92
+
93
+ const unregister = register(name, stableRender as RenderToolFunction);
94
+ return unregister;
95
+ }, [name, register]);
96
+ }
package/src/index.ts CHANGED
@@ -69,7 +69,6 @@ export {
69
69
  useConfigureSuggestions,
70
70
  useAgentContext,
71
71
  useThreads,
72
- useRenderTool,
73
72
  useCapabilities,
74
73
  defineToolCallRenderer,
75
74
  CopilotChatDefaultLabels,
@@ -87,7 +86,6 @@ export {
87
86
  type InterruptRenderProps,
88
87
  type ReactFrontendTool,
89
88
  type ReactHumanInTheLoop,
90
- type RenderToolProps,
91
89
  type RenderToolInProgressProps,
92
90
  type RenderToolExecutingProps,
93
91
  type RenderToolCompleteProps,
@@ -110,9 +108,18 @@ export type {
110
108
  // Re-export AG-UI types for consumer convenience (matches web SDK surface)
111
109
  export type {
112
110
  Message,
113
- AssistantMessage,
111
+ AssistantMessage as AssistantMessageType,
114
112
  ToolCall,
115
113
  ToolMessage,
116
114
  AbstractAgent,
117
115
  AgentCapabilities,
118
116
  } from "@ag-ui/client";
117
+
118
+ // Render tool hook (React Native version with render registry integration)
119
+ export { useRenderTool } from "./hooks/useRenderTool";
120
+ export type { UseRenderToolOptions } from "./hooks/useRenderTool";
121
+ export {
122
+ RenderToolProvider,
123
+ useRenderToolRegistry,
124
+ } from "./hooks/RenderToolContext";
125
+ export type { RenderToolProps } from "./hooks/RenderToolContext";
package/tsdown.config.ts CHANGED
@@ -3,6 +3,7 @@ import { defineConfig } from "tsdown";
3
3
  export default defineConfig({
4
4
  entry: [
5
5
  "src/index.ts",
6
+ "src/components/index.ts",
6
7
  "src/polyfills.ts",
7
8
  "src/polyfills/streams.ts",
8
9
  "src/polyfills/encoding.ts",
@@ -22,5 +23,13 @@ export default defineConfig({
22
23
  "@copilotkit/react-core",
23
24
  "@copilotkit/core",
24
25
  "@copilotkit/shared",
26
+ "@ag-ui/client",
27
+ "@gorhom/bottom-sheet",
28
+ "react-native-streamdown",
29
+ "react-native-gesture-handler",
30
+ "react-native-reanimated",
31
+ "react-native-enriched-markdown",
32
+ "react-native-worklets",
33
+ "remend",
25
34
  ],
26
35
  });
package/vitest.config.mjs CHANGED
@@ -15,6 +15,16 @@ export default defineConfig({
15
15
  __dirname,
16
16
  "src/__tests__/__mocks__/expo-file-system.ts",
17
17
  ),
18
+ // react-native uses Flow syntax that vite/rollup cannot parse.
19
+ // This alias redirects to a minimal stub for test environments.
20
+ "react-native": path.resolve(__dirname, "src/__mocks__/react-native.ts"),
21
+ // react-native-streamdown is a peer dependency that won't be installed
22
+ // in the monorepo dev environment; tests mock it via vi.mock().
23
+ // This alias prevents vite's import-analysis from failing on the import.
24
+ "react-native-streamdown": path.resolve(
25
+ __dirname,
26
+ "src/__mocks__/react-native-streamdown.ts",
27
+ ),
18
28
  },
19
29
  },
20
30
  test: {