@copilotkit/react-native 1.67.1 → 1.68.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.
- package/dist/chunk-C0xms8kb.cjs +34 -0
- package/dist/components/index.cjs +146 -33
- package/dist/components/index.cjs.map +1 -1
- package/dist/components/index.mjs +144 -32
- package/dist/components/index.mjs.map +1 -1
- package/dist/headless.cjs +40 -4
- package/dist/headless.d.cts +3 -3
- package/dist/headless.d.mts +3 -3
- package/dist/headless.mjs +5 -4
- package/dist/index.cjs +43 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +3 -4
- package/dist/index.mjs.map +1 -1
- package/dist/polyfills/encoding.cjs +1 -1
- package/dist/polyfills/streams.cjs +1 -1
- package/dist/useRenderTool-BBxnOOeJ.d.mts +161 -0
- package/dist/useRenderTool-BWo11PCL.d.cts +161 -0
- package/dist/{useRenderTool-DLavcsVB.cjs → useRenderTool-CKEPq7MQ.cjs} +20 -34
- package/dist/useRenderTool-CKEPq7MQ.cjs.map +1 -0
- package/dist/{useRenderTool-DUqpS97B.mjs → useRenderTool-l7M-I8rT.mjs} +18 -33
- package/dist/useRenderTool-l7M-I8rT.mjs.map +1 -0
- package/package.json +9 -6
- package/scripts/__tests__/fixtures/stray-react-dom-headless.js +16 -0
- package/scripts/__tests__/fixtures/tiny-headless.js +10 -0
- package/scripts/__tests__/fixtures/warning-headless.js +13 -0
- package/scripts/__tests__/measure-headless.test.mjs +275 -0
- package/scripts/measure-headless.mjs +310 -0
- package/src/CopilotKitProvider.tsx +1 -2
- package/src/__mocks__/test-copilotkit.tsx +116 -0
- package/src/__mocks__/tool-fixtures.ts +50 -0
- package/src/__tests__/headless-entry-surface.test.ts +464 -46
- package/src/__tests__/headless-integration.test.tsx +12 -1
- package/src/__tests__/headless-value-exports.test.ts +369 -0
- package/src/components/CopilotChat.tsx +218 -32
- package/src/components/__tests__/CopilotChat-edge-cases.test.tsx +5 -126
- package/src/components/__tests__/CopilotChat.test.tsx +5 -49
- package/src/components/__tests__/CopilotChatToolCalls.test.tsx +468 -0
- package/src/headless.ts +36 -14
- package/src/hooks/__tests__/render-tool-call.integration.test.tsx +181 -0
- package/src/hooks/__tests__/useRenderTool.test.tsx +232 -267
- package/src/hooks/index.ts +1 -7
- package/src/hooks/render-tool-types.ts +55 -0
- package/src/hooks/useRenderTool.ts +29 -57
- package/src/index.ts +13 -5
- package/dist/RenderToolContext-CBNKcJqz.cjs +0 -126
- package/dist/RenderToolContext-CBNKcJqz.cjs.map +0 -1
- package/dist/RenderToolContext-D8M-JhD1.mjs +0 -75
- package/dist/RenderToolContext-D8M-JhD1.mjs.map +0 -1
- package/dist/useRenderTool-9YDIfZ0D.d.mts +0 -164
- package/dist/useRenderTool-BugVTDoM.d.cts +0 -164
- package/dist/useRenderTool-DLavcsVB.cjs.map +0 -1
- package/dist/useRenderTool-DUqpS97B.mjs.map +0 -1
- package/src/hooks/RenderToolContext.tsx +0 -150
- package/src/hooks/__tests__/RenderToolContext.test.tsx +0 -264
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
import * as react_jsx_runtime0 from "react/jsx-runtime";
|
|
2
|
-
import React, { ReactNode } from "react";
|
|
3
|
-
import { CopilotKitCoreErrorCode } from "@copilotkit/core";
|
|
4
|
-
import { DebugConfig, StandardSchemaV1 } from "@copilotkit/shared";
|
|
5
|
-
|
|
6
|
-
//#region src/CopilotKitProvider.d.ts
|
|
7
|
-
interface CopilotKitNativeProviderProps {
|
|
8
|
-
children: ReactNode;
|
|
9
|
-
/** URL of the CopilotKit runtime endpoint */
|
|
10
|
-
runtimeUrl: string;
|
|
11
|
-
/** Custom headers sent with every request */
|
|
12
|
-
headers?: Record<string, string> | (() => Record<string, string>);
|
|
13
|
-
/**
|
|
14
|
-
* Credentials mode for fetch requests (e.g., "include" for HTTP-only cookies in cross-origin requests).
|
|
15
|
-
*/
|
|
16
|
-
credentials?: RequestCredentials;
|
|
17
|
-
/** Whether the runtime uses a single-route endpoint */
|
|
18
|
-
useSingleEndpoint?: boolean;
|
|
19
|
-
/** Custom properties forwarded to agents */
|
|
20
|
-
properties?: Record<string, unknown>;
|
|
21
|
-
/**
|
|
22
|
-
* Error handler called when CopilotKit encounters an error.
|
|
23
|
-
* Fires for all error types (runtime connection failures, agent errors, tool errors).
|
|
24
|
-
* If not provided, errors are logged to console.error.
|
|
25
|
-
*/
|
|
26
|
-
onError?: (event: {
|
|
27
|
-
error: Error;
|
|
28
|
-
code: CopilotKitCoreErrorCode;
|
|
29
|
-
context: Record<string, any>;
|
|
30
|
-
}) => void | Promise<void>;
|
|
31
|
-
/**
|
|
32
|
-
* Enable debug logging for the client-side event pipeline.
|
|
33
|
-
* When `true`, enables verbose logging from the core instance.
|
|
34
|
-
*/
|
|
35
|
-
debug?: DebugConfig;
|
|
36
|
-
/**
|
|
37
|
-
* Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`
|
|
38
|
-
* subscriptions. Individual subscriptions can override with their own `throttleMs`.
|
|
39
|
-
*/
|
|
40
|
-
defaultThrottleMs?: number;
|
|
41
|
-
}
|
|
42
|
-
/**
|
|
43
|
-
* CopilotKit provider for React Native.
|
|
44
|
-
*
|
|
45
|
-
* A lightweight alternative to the web CopilotKitProvider that avoids
|
|
46
|
-
* web-only dependencies (DOM, CSS, Radix UI, Lit, etc).
|
|
47
|
-
*
|
|
48
|
-
* Polyfills are auto-imported when `@copilotkit/react-native` is loaded,
|
|
49
|
-
* so a separate `import "@copilotkit/react-native/polyfills"` is no longer
|
|
50
|
-
* required (though it remains available for advanced use).
|
|
51
|
-
*
|
|
52
|
-
* Usage:
|
|
53
|
-
* ```tsx
|
|
54
|
-
* import { CopilotKitProvider } from "@copilotkit/react-native";
|
|
55
|
-
*
|
|
56
|
-
* function App() {
|
|
57
|
-
* return (
|
|
58
|
-
* <CopilotKitProvider runtimeUrl="https://your-runtime/api/copilotkit">
|
|
59
|
-
* <ChatScreen />
|
|
60
|
-
* </CopilotKitProvider>
|
|
61
|
-
* );
|
|
62
|
-
* }
|
|
63
|
-
* ```
|
|
64
|
-
*/
|
|
65
|
-
declare const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps>;
|
|
66
|
-
//#endregion
|
|
67
|
-
//#region src/hooks/RenderToolContext.d.ts
|
|
68
|
-
/**
|
|
69
|
-
* Props passed to a render tool function.
|
|
70
|
-
*/
|
|
71
|
-
interface RenderToolProps<T = Record<string, unknown>> {
|
|
72
|
-
args: T;
|
|
73
|
-
status: "executing" | "complete";
|
|
74
|
-
result?: string;
|
|
75
|
-
}
|
|
76
|
-
/**
|
|
77
|
-
* A render function that returns a React Native element for a tool call.
|
|
78
|
-
* Returns `ReactElement | null` (not ReactNode) because React Native's
|
|
79
|
-
* FlatList cannot render strings or portals.
|
|
80
|
-
*/
|
|
81
|
-
type RenderToolFunction<T = Record<string, unknown>> = (props: RenderToolProps<T>) => React.ReactElement | null;
|
|
82
|
-
/**
|
|
83
|
-
* The registry maps tool names to their render functions.
|
|
84
|
-
*/
|
|
85
|
-
type RenderToolRegistry = Map<string, RenderToolFunction>;
|
|
86
|
-
/**
|
|
87
|
-
* Provider that maintains the render tool registry.
|
|
88
|
-
* Should be nested inside CopilotKitProvider.
|
|
89
|
-
*/
|
|
90
|
-
declare function RenderToolProvider({
|
|
91
|
-
children
|
|
92
|
-
}: {
|
|
93
|
-
children: React.ReactNode;
|
|
94
|
-
}): react_jsx_runtime0.JSX.Element;
|
|
95
|
-
/**
|
|
96
|
-
* Returns the current render tool registry (a Map of tool name to render function).
|
|
97
|
-
* Re-renders when the registry changes.
|
|
98
|
-
*
|
|
99
|
-
* @throws if called outside of RenderToolProvider
|
|
100
|
-
*/
|
|
101
|
-
declare function useRenderToolRegistry(): RenderToolRegistry;
|
|
102
|
-
//#endregion
|
|
103
|
-
//#region src/hooks/useRenderTool.d.ts
|
|
104
|
-
/**
|
|
105
|
-
* Options for the useRenderTool hook.
|
|
106
|
-
*/
|
|
107
|
-
interface UseRenderToolOptions<T extends Record<string, unknown>> {
|
|
108
|
-
/** Unique name for the tool. Must match what the agent calls. */
|
|
109
|
-
name: string;
|
|
110
|
-
/** Human-readable description shown to the agent. */
|
|
111
|
-
description: string;
|
|
112
|
-
/**
|
|
113
|
-
* Schema describing the tool's parameters.
|
|
114
|
-
* Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).
|
|
115
|
-
*/
|
|
116
|
-
parameters: StandardSchemaV1<unknown, T>;
|
|
117
|
-
/**
|
|
118
|
-
* Render function that returns a React Native element for the tool call.
|
|
119
|
-
* Called by CopilotChat when it encounters a tool call message for this tool.
|
|
120
|
-
*
|
|
121
|
-
* Returns ReactElement | null (not ReactNode) because React Native's
|
|
122
|
-
* FlatList cannot render strings or portals.
|
|
123
|
-
*/
|
|
124
|
-
render: RenderToolFunction<T>;
|
|
125
|
-
/**
|
|
126
|
-
* Optional handler executed when the tool is called.
|
|
127
|
-
* If omitted, the tool is render-only (the render function shows UI
|
|
128
|
-
* but the tool returns no result to the agent).
|
|
129
|
-
*/
|
|
130
|
-
handler?: (args: T) => Promise<unknown>;
|
|
131
|
-
/**
|
|
132
|
-
* Optional agent ID to scope this tool to a specific agent.
|
|
133
|
-
*/
|
|
134
|
-
agentId?: string;
|
|
135
|
-
}
|
|
136
|
-
/**
|
|
137
|
-
* Hook that registers a frontend tool AND a render function for it.
|
|
138
|
-
*
|
|
139
|
-
* This bridges `useFrontendTool` (which handles tool registration and
|
|
140
|
-
* handler execution) with a render registry so that CopilotChat can
|
|
141
|
-
* render React Native elements inline when it encounters tool call messages.
|
|
142
|
-
*
|
|
143
|
-
* @example
|
|
144
|
-
* ```tsx
|
|
145
|
-
* useRenderTool({
|
|
146
|
-
* name: "showWeather",
|
|
147
|
-
* description: "Display weather information",
|
|
148
|
-
* parameters: z.object({ city: z.string(), temp: z.number() }),
|
|
149
|
-
* render: ({ args, status }) => (
|
|
150
|
-
* <View>
|
|
151
|
-
* <Text>{args.city}: {args.temp}</Text>
|
|
152
|
-
* {status === "executing" && <ActivityIndicator />}
|
|
153
|
-
* </View>
|
|
154
|
-
* ),
|
|
155
|
-
* handler: async ({ city }) => {
|
|
156
|
-
* return { forecast: "sunny" };
|
|
157
|
-
* },
|
|
158
|
-
* });
|
|
159
|
-
* ```
|
|
160
|
-
*/
|
|
161
|
-
declare function useRenderTool<T extends Record<string, unknown> = Record<string, unknown>>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void;
|
|
162
|
-
//#endregion
|
|
163
|
-
export { useRenderToolRegistry as a, RenderToolProvider as i, useRenderTool as n, CopilotKitNativeProviderProps as o, RenderToolProps as r, CopilotKitProvider as s, UseRenderToolOptions as t };
|
|
164
|
-
//# sourceMappingURL=useRenderTool-BugVTDoM.d.cts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useRenderTool-DLavcsVB.cjs","names":["CopilotKitCoreReact","CopilotKitContext","LicenseContext","RenderToolProvider","useRenderToolContext"],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\nimport { RenderToolProvider } from \"./hooks/RenderToolContext\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n <RenderToolProvider>{children}</RenderToolProvider>\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./RenderToolContext\";\nimport { useRenderToolContext } from \"./RenderToolContext\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /**\n * Schema describing the tool's parameters.\n * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).\n */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function that returns a React Native element for the tool call.\n * Called by CopilotChat when it encounters a tool call message for this tool.\n *\n * Returns ReactElement | null (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\n render: RenderToolFunction<T>;\n /**\n * Optional handler executed when the tool is called.\n * If omitted, the tool is render-only (the render function shows UI\n * but the tool returns no result to the agent).\n */\n handler?: (args: T) => Promise<unknown>;\n /**\n * Optional agent ID to scope this tool to a specific agent.\n */\n agentId?: string;\n}\n\n/**\n * Hook that registers a frontend tool AND a render function for it.\n *\n * This bridges `useFrontendTool` (which handles tool registration and\n * handler execution) with a render registry so that CopilotChat can\n * render React Native elements inline when it encounters tool call messages.\n *\n * @example\n * ```tsx\n * useRenderTool({\n * name: \"showWeather\",\n * description: \"Display weather information\",\n * parameters: z.object({ city: z.string(), temp: z.number() }),\n * render: ({ args, status }) => (\n * <View>\n * <Text>{args.city}: {args.temp}</Text>\n * {status === \"executing\" && <ActivityIndicator />}\n * </View>\n * ),\n * handler: async ({ city }) => {\n * return { forecast: \"sunny\" };\n * },\n * });\n * ```\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n const { register } = useRenderToolContext();\n\n // Register the tool with the core system via useFrontendTool\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n },\n deps,\n );\n\n // Use a ref so the effect cleanup always has the latest render function\n const renderRef = useRef(render);\n renderRef.current = render;\n\n // Register the render function in the RenderToolContext\n useEffect(() => {\n // Wrap in a stable function that delegates to the ref\n const stableRender: RenderToolFunction<T> = (props) =>\n renderRef.current(props);\n\n const unregister = register(name, stableRender as RenderToolFunction);\n return unregister;\n }, [name, register]);\n}\n"],"mappings":"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"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useRenderTool-DUqpS97B.mjs","names":[],"sources":["../src/CopilotKitProvider.tsx","../src/hooks/useRenderTool.ts"],"sourcesContent":["import React, { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n CopilotKitContext,\n LicenseContext,\n} from \"@copilotkit/react-core/v2/context\";\nimport type {\n CopilotKitContextValue,\n CopilotKitCoreReact as CopilotKitCoreReactInstance,\n} from \"@copilotkit/react-core/v2/context\";\nimport { CopilotKitCoreReact } from \"@copilotkit/react-core/v2/headless\";\nimport type { CopilotKitCoreErrorCode } from \"@copilotkit/core\";\nimport type { DebugConfig, RuntimeLicenseStatus } from \"@copilotkit/shared\";\nimport { createLicenseContextValue } from \"@copilotkit/shared\";\nimport { RenderToolProvider } from \"./hooks/RenderToolContext\";\n\nexport interface CopilotKitNativeProviderProps {\n children: ReactNode;\n /** URL of the CopilotKit runtime endpoint */\n runtimeUrl: string;\n /** Custom headers sent with every request */\n headers?: Record<string, string> | (() => Record<string, string>);\n /**\n * Credentials mode for fetch requests (e.g., \"include\" for HTTP-only cookies in cross-origin requests).\n */\n credentials?: RequestCredentials;\n /** Whether the runtime uses a single-route endpoint */\n useSingleEndpoint?: boolean;\n /** Custom properties forwarded to agents */\n properties?: Record<string, unknown>;\n /**\n * Error handler called when CopilotKit encounters an error.\n * Fires for all error types (runtime connection failures, agent errors, tool errors).\n * If not provided, errors are logged to console.error.\n */\n onError?: (event: {\n error: Error;\n code: CopilotKitCoreErrorCode;\n context: Record<string, any>;\n }) => void | Promise<void>;\n /**\n * Enable debug logging for the client-side event pipeline.\n * When `true`, enables verbose logging from the core instance.\n */\n debug?: DebugConfig;\n /**\n * Default throttle interval (ms) for `onMessagesChanged` / `onStateChanged`\n * subscriptions. Individual subscriptions can override with their own `throttleMs`.\n */\n defaultThrottleMs?: number;\n // Cloud features (publicApiKey, licenseToken) — not yet supported on React Native\n}\n\n/**\n * CopilotKit provider for React Native.\n *\n * A lightweight alternative to the web CopilotKitProvider that avoids\n * web-only dependencies (DOM, CSS, Radix UI, Lit, etc).\n *\n * Polyfills are auto-imported when `@copilotkit/react-native` is loaded,\n * so a separate `import \"@copilotkit/react-native/polyfills\"` is no longer\n * required (though it remains available for advanced use).\n *\n * Usage:\n * ```tsx\n * import { CopilotKitProvider } from \"@copilotkit/react-native\";\n *\n * function App() {\n * return (\n * <CopilotKitProvider runtimeUrl=\"https://your-runtime/api/copilotkit\">\n * <ChatScreen />\n * </CopilotKitProvider>\n * );\n * }\n * ```\n */\nexport const CopilotKitProvider: React.FC<CopilotKitNativeProviderProps> = ({\n children,\n runtimeUrl,\n headers: headersProp,\n credentials,\n useSingleEndpoint,\n properties,\n onError,\n debug,\n defaultThrottleMs,\n}) => {\n // Resolve headers from function or static object (matches web provider pattern)\n const resolvedHeaders =\n typeof headersProp === \"function\" ? headersProp() : headersProp;\n\n // Stabilize headers/properties references to avoid effect churn when callers\n // pass inline object literals (e.g. headers={{}} or the undefined default).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableHeaders = useMemo(\n () => resolvedHeaders ?? {},\n [JSON.stringify(resolvedHeaders)],\n );\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const stableProperties = useMemo(\n () => properties ?? {},\n [JSON.stringify(properties)],\n );\n\n const copilotkitRef = useRef<CopilotKitCoreReactInstance | null>(null);\n\n if (copilotkitRef.current === null) {\n const instance: CopilotKitCoreReactInstance = new CopilotKitCoreReact({\n runtimeUrl,\n runtimeTransport:\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n headers: stableHeaders,\n credentials,\n properties: stableProperties,\n debug,\n });\n // Set initial defaultThrottleMs synchronously so child hooks see the\n // correct value on their first render (before useEffect fires).\n if (defaultThrottleMs !== undefined) {\n instance.setDefaultThrottleMs(defaultThrottleMs);\n }\n copilotkitRef.current = instance;\n }\n\n const copilotkit = copilotkitRef.current;\n\n // Sync props to core instance\n useEffect(() => {\n copilotkit.setRuntimeUrl(runtimeUrl);\n copilotkit.setRuntimeTransport(\n useSingleEndpoint === true\n ? \"single\"\n : useSingleEndpoint === false\n ? \"rest\"\n : \"auto\",\n );\n copilotkit.setHeaders(stableHeaders);\n copilotkit.setCredentials(credentials);\n copilotkit.setProperties(stableProperties);\n copilotkit.setDebug(debug);\n }, [\n runtimeUrl,\n useSingleEndpoint,\n stableHeaders,\n credentials,\n stableProperties,\n debug,\n copilotkit,\n ]);\n\n // Sync defaultThrottleMs to the core instance on prop changes.\n // Initial value is set synchronously during instance creation (inside the\n // ref guard above), so this only handles subsequent updates.\n useEffect(() => {\n copilotkit.setDefaultThrottleMs(defaultThrottleMs);\n }, [copilotkit, defaultThrottleMs]);\n\n // Track executing tool call IDs at the provider level.\n // Critical for HITL reconnection: onToolExecutionStart fires before child\n // components mount, so we must capture the state here.\n const [executingToolCallIds, setExecutingToolCallIds] = useState<\n ReadonlySet<string>\n >(() => new Set());\n\n const [runtimeLicenseStatus, setRuntimeLicenseStatus] = useState<\n RuntimeLicenseStatus | undefined\n >(undefined);\n\n // Use ref to avoid subscription churn when onError changes\n const onErrorRef = useRef(onError);\n useEffect(() => {\n onErrorRef.current = onError;\n }, [onError]);\n\n // Single subscription for tool execution tracking and error handling.\n // Tool call IDs are tracked at the provider level because onToolExecutionStart\n // fires before child components mount — critical for HITL reconnection.\n useEffect(() => {\n const subscription = copilotkit.subscribe({\n onToolExecutionStart: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.add(toolCallId);\n return next;\n });\n },\n onToolExecutionEnd: ({ toolCallId }) => {\n setExecutingToolCallIds((prev) => {\n if (!prev.has(toolCallId)) return prev;\n const next = new Set(prev);\n next.delete(toolCallId);\n return next;\n });\n },\n onError: (event) => {\n if (onErrorRef.current) {\n onErrorRef.current(event);\n } else {\n console.error(\n `[CopilotKit] Error (${event.code}):`,\n event.error,\n event.context ?? {},\n );\n }\n },\n onRuntimeConnectionStatusChanged: () => {\n setRuntimeLicenseStatus(copilotkit.licenseStatus);\n },\n });\n return () => subscription.unsubscribe();\n }, [copilotkit]);\n\n const contextValue: CopilotKitContextValue = useMemo(\n () => ({\n copilotkit,\n executingToolCallIds,\n }),\n [copilotkit, executingToolCallIds],\n );\n\n // License context — driven by server-reported status via /info endpoint\n const licenseContextValue = useMemo(\n () => createLicenseContextValue(runtimeLicenseStatus),\n [runtimeLicenseStatus],\n );\n\n return (\n <CopilotKitContext.Provider value={contextValue}>\n <LicenseContext.Provider value={licenseContextValue}>\n <RenderToolProvider>{children}</RenderToolProvider>\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./RenderToolContext\";\nimport { useRenderToolContext } from \"./RenderToolContext\";\n\n/**\n * Options for the useRenderTool hook.\n */\nexport interface UseRenderToolOptions<T extends Record<string, unknown>> {\n /** Unique name for the tool. Must match what the agent calls. */\n name: string;\n /** Human-readable description shown to the agent. */\n description: string;\n /**\n * Schema describing the tool's parameters.\n * Accepts any StandardSchemaV1-compatible schema (Zod, Valibot, ArkType, etc.).\n */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function that returns a React Native element for the tool call.\n * Called by CopilotChat when it encounters a tool call message for this tool.\n *\n * Returns ReactElement | null (not ReactNode) because React Native's\n * FlatList cannot render strings or portals.\n */\n render: RenderToolFunction<T>;\n /**\n * Optional handler executed when the tool is called.\n * If omitted, the tool is render-only (the render function shows UI\n * but the tool returns no result to the agent).\n */\n handler?: (args: T) => Promise<unknown>;\n /**\n * Optional agent ID to scope this tool to a specific agent.\n */\n agentId?: string;\n}\n\n/**\n * Hook that registers a frontend tool AND a render function for it.\n *\n * This bridges `useFrontendTool` (which handles tool registration and\n * handler execution) with a render registry so that CopilotChat can\n * render React Native elements inline when it encounters tool call messages.\n *\n * @example\n * ```tsx\n * useRenderTool({\n * name: \"showWeather\",\n * description: \"Display weather information\",\n * parameters: z.object({ city: z.string(), temp: z.number() }),\n * render: ({ args, status }) => (\n * <View>\n * <Text>{args.city}: {args.temp}</Text>\n * {status === \"executing\" && <ActivityIndicator />}\n * </View>\n * ),\n * handler: async ({ city }) => {\n * return { forecast: \"sunny\" };\n * },\n * });\n * ```\n */\nexport function useRenderTool<\n T extends Record<string, unknown> = Record<string, unknown>,\n>(options: UseRenderToolOptions<T>, deps?: ReadonlyArray<unknown>): void {\n const { name, description, parameters, render, handler, agentId } = options;\n const { register } = useRenderToolContext();\n\n // Register the tool with the core system via useFrontendTool\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n },\n deps,\n );\n\n // Use a ref so the effect cleanup always has the latest render function\n const renderRef = useRef(render);\n renderRef.current = render;\n\n // Register the render function in the RenderToolContext\n useEffect(() => {\n // Wrap in a stable function that delegates to the ref\n const stableRender: RenderToolFunction<T> = (props) =>\n renderRef.current(props);\n\n const unregister = register(name, stableRender as RenderToolFunction);\n return unregister;\n }, [name, register]);\n}\n"],"mappings":"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"}
|
|
@@ -1,150 +0,0 @@
|
|
|
1
|
-
import React, {
|
|
2
|
-
createContext,
|
|
3
|
-
useCallback,
|
|
4
|
-
useContext,
|
|
5
|
-
useMemo,
|
|
6
|
-
useRef,
|
|
7
|
-
useSyncExternalStore,
|
|
8
|
-
} from "react";
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Props passed to a render tool function.
|
|
12
|
-
*/
|
|
13
|
-
export interface RenderToolProps<T = Record<string, unknown>> {
|
|
14
|
-
args: T;
|
|
15
|
-
status: "executing" | "complete";
|
|
16
|
-
result?: string;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* A render function that returns a React Native element for a tool call.
|
|
21
|
-
* Returns `ReactElement | null` (not ReactNode) because React Native's
|
|
22
|
-
* FlatList cannot render strings or portals.
|
|
23
|
-
*/
|
|
24
|
-
export type RenderToolFunction<T = Record<string, unknown>> = (
|
|
25
|
-
props: RenderToolProps<T>,
|
|
26
|
-
) => React.ReactElement | null;
|
|
27
|
-
|
|
28
|
-
/**
|
|
29
|
-
* The registry maps tool names to their render functions.
|
|
30
|
-
*/
|
|
31
|
-
export type RenderToolRegistry = Map<string, RenderToolFunction>;
|
|
32
|
-
|
|
33
|
-
/**
|
|
34
|
-
* Internal store that notifies subscribers when the registry changes.
|
|
35
|
-
* This avoids unnecessary re-renders of the entire tree when a single
|
|
36
|
-
* tool's render function is registered or removed.
|
|
37
|
-
*/
|
|
38
|
-
interface RegistryStore {
|
|
39
|
-
registry: RenderToolRegistry;
|
|
40
|
-
version: number;
|
|
41
|
-
listeners: Set<() => void>;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function createRegistryStore(): RegistryStore {
|
|
45
|
-
return {
|
|
46
|
-
registry: new Map(),
|
|
47
|
-
version: 0,
|
|
48
|
-
listeners: new Set(),
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
function emitChange(store: RegistryStore) {
|
|
53
|
-
store.version++;
|
|
54
|
-
// Create a new Map so useSyncExternalStore detects the reference change
|
|
55
|
-
store.registry = new Map(store.registry);
|
|
56
|
-
for (const listener of store.listeners) {
|
|
57
|
-
listener();
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
interface RenderToolContextValue {
|
|
62
|
-
store: RegistryStore;
|
|
63
|
-
register: (name: string, render: RenderToolFunction) => () => void;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
const RenderToolCtx = createContext<RenderToolContextValue | null>(null);
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Provider that maintains the render tool registry.
|
|
70
|
-
* Should be nested inside CopilotKitProvider.
|
|
71
|
-
*/
|
|
72
|
-
export function RenderToolProvider({
|
|
73
|
-
children,
|
|
74
|
-
}: {
|
|
75
|
-
children: React.ReactNode;
|
|
76
|
-
}) {
|
|
77
|
-
const storeRef = useRef<RegistryStore>(createRegistryStore());
|
|
78
|
-
|
|
79
|
-
const register = useCallback(
|
|
80
|
-
(name: string, render: RenderToolFunction): (() => void) => {
|
|
81
|
-
const store = storeRef.current;
|
|
82
|
-
store.registry.set(name, render);
|
|
83
|
-
emitChange(store);
|
|
84
|
-
|
|
85
|
-
// Return unregister function
|
|
86
|
-
return () => {
|
|
87
|
-
// Only delete if the current render function is the one we registered
|
|
88
|
-
if (store.registry.get(name) === render) {
|
|
89
|
-
store.registry.delete(name);
|
|
90
|
-
emitChange(store);
|
|
91
|
-
}
|
|
92
|
-
};
|
|
93
|
-
},
|
|
94
|
-
[],
|
|
95
|
-
);
|
|
96
|
-
|
|
97
|
-
const value = useMemo<RenderToolContextValue>(
|
|
98
|
-
() => ({ store: storeRef.current, register }),
|
|
99
|
-
[register],
|
|
100
|
-
);
|
|
101
|
-
|
|
102
|
-
return (
|
|
103
|
-
<RenderToolCtx.Provider value={value}>{children}</RenderToolCtx.Provider>
|
|
104
|
-
);
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Returns the current render tool registry (a Map of tool name to render function).
|
|
109
|
-
* Re-renders when the registry changes.
|
|
110
|
-
*
|
|
111
|
-
* @throws if called outside of RenderToolProvider
|
|
112
|
-
*/
|
|
113
|
-
export function useRenderToolRegistry(): RenderToolRegistry {
|
|
114
|
-
const ctx = useContext(RenderToolCtx);
|
|
115
|
-
if (!ctx) {
|
|
116
|
-
throw new Error(
|
|
117
|
-
"useRenderToolRegistry must be used within a RenderToolProvider",
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
const { store } = ctx;
|
|
122
|
-
|
|
123
|
-
// Subscribe to registry changes via useSyncExternalStore for tear-safe reads
|
|
124
|
-
return useSyncExternalStore(
|
|
125
|
-
(onStoreChange) => {
|
|
126
|
-
store.listeners.add(onStoreChange);
|
|
127
|
-
return () => {
|
|
128
|
-
store.listeners.delete(onStoreChange);
|
|
129
|
-
};
|
|
130
|
-
},
|
|
131
|
-
() => store.registry,
|
|
132
|
-
() => store.registry,
|
|
133
|
-
);
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/**
|
|
137
|
-
* Internal hook used by useRenderTool to register a render function.
|
|
138
|
-
* Not exported from the package — consumers use useRenderTool instead.
|
|
139
|
-
*
|
|
140
|
-
* @throws if called outside of RenderToolProvider
|
|
141
|
-
*/
|
|
142
|
-
export function useRenderToolContext() {
|
|
143
|
-
const ctx = useContext(RenderToolCtx);
|
|
144
|
-
if (!ctx) {
|
|
145
|
-
throw new Error(
|
|
146
|
-
"useRenderTool must be used within a RenderToolProvider (inside CopilotKitProvider)",
|
|
147
|
-
);
|
|
148
|
-
}
|
|
149
|
-
return ctx;
|
|
150
|
-
}
|
|
@@ -1,264 +0,0 @@
|
|
|
1
|
-
import React from "react";
|
|
2
|
-
import { render, act } from "@testing-library/react";
|
|
3
|
-
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
4
|
-
import {
|
|
5
|
-
RenderToolProvider,
|
|
6
|
-
useRenderToolRegistry,
|
|
7
|
-
useRenderToolContext,
|
|
8
|
-
} from "../RenderToolContext";
|
|
9
|
-
|
|
10
|
-
describe("RenderToolContext", () => {
|
|
11
|
-
describe("RenderToolProvider", () => {
|
|
12
|
-
it("renders children", () => {
|
|
13
|
-
const { getByText } = render(
|
|
14
|
-
<RenderToolProvider>
|
|
15
|
-
<span>child content</span>
|
|
16
|
-
</RenderToolProvider>,
|
|
17
|
-
);
|
|
18
|
-
expect(getByText("child content")).toBeTruthy();
|
|
19
|
-
});
|
|
20
|
-
|
|
21
|
-
it("provides an initially empty registry", () => {
|
|
22
|
-
let registry: Map<string, any> | null = null;
|
|
23
|
-
|
|
24
|
-
function Reader() {
|
|
25
|
-
registry = useRenderToolRegistry();
|
|
26
|
-
return null;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
render(
|
|
30
|
-
<RenderToolProvider>
|
|
31
|
-
<Reader />
|
|
32
|
-
</RenderToolProvider>,
|
|
33
|
-
);
|
|
34
|
-
|
|
35
|
-
expect(registry).not.toBeNull();
|
|
36
|
-
expect(registry!.size).toBe(0);
|
|
37
|
-
});
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
describe("register and unregister", () => {
|
|
41
|
-
it("register adds a render function to the registry", () => {
|
|
42
|
-
let registry: Map<string, any> | null = null;
|
|
43
|
-
let registerFn: ((name: string, render: any) => () => void) | null = null;
|
|
44
|
-
|
|
45
|
-
function Writer() {
|
|
46
|
-
const ctx = useRenderToolContext();
|
|
47
|
-
registerFn = ctx.register;
|
|
48
|
-
return null;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function Reader() {
|
|
52
|
-
registry = useRenderToolRegistry();
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
render(
|
|
57
|
-
<RenderToolProvider>
|
|
58
|
-
<Writer />
|
|
59
|
-
<Reader />
|
|
60
|
-
</RenderToolProvider>,
|
|
61
|
-
);
|
|
62
|
-
|
|
63
|
-
const renderFn = () => React.createElement("div");
|
|
64
|
-
|
|
65
|
-
act(() => {
|
|
66
|
-
registerFn!("test-tool", renderFn);
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
expect(registry!.has("test-tool")).toBe(true);
|
|
70
|
-
});
|
|
71
|
-
|
|
72
|
-
it("unregister removes the render function", () => {
|
|
73
|
-
let registry: Map<string, any> | null = null;
|
|
74
|
-
let registerFn: ((name: string, render: any) => () => void) | null = null;
|
|
75
|
-
let unregister: (() => void) | null = null;
|
|
76
|
-
|
|
77
|
-
function Writer() {
|
|
78
|
-
const ctx = useRenderToolContext();
|
|
79
|
-
registerFn = ctx.register;
|
|
80
|
-
return null;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
function Reader() {
|
|
84
|
-
registry = useRenderToolRegistry();
|
|
85
|
-
return null;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
render(
|
|
89
|
-
<RenderToolProvider>
|
|
90
|
-
<Writer />
|
|
91
|
-
<Reader />
|
|
92
|
-
</RenderToolProvider>,
|
|
93
|
-
);
|
|
94
|
-
|
|
95
|
-
const renderFn = () => React.createElement("div");
|
|
96
|
-
|
|
97
|
-
act(() => {
|
|
98
|
-
unregister = registerFn!("removal-tool", renderFn);
|
|
99
|
-
});
|
|
100
|
-
|
|
101
|
-
expect(registry!.has("removal-tool")).toBe(true);
|
|
102
|
-
|
|
103
|
-
act(() => {
|
|
104
|
-
unregister!();
|
|
105
|
-
});
|
|
106
|
-
|
|
107
|
-
expect(registry!.has("removal-tool")).toBe(false);
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
it("unregister is safe to call if tool was already replaced", () => {
|
|
111
|
-
let registerFn: ((name: string, render: any) => () => void) | null = null;
|
|
112
|
-
let registry: Map<string, any> | null = null;
|
|
113
|
-
|
|
114
|
-
function Writer() {
|
|
115
|
-
const ctx = useRenderToolContext();
|
|
116
|
-
registerFn = ctx.register;
|
|
117
|
-
return null;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
function Reader() {
|
|
121
|
-
registry = useRenderToolRegistry();
|
|
122
|
-
return null;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
render(
|
|
126
|
-
<RenderToolProvider>
|
|
127
|
-
<Writer />
|
|
128
|
-
<Reader />
|
|
129
|
-
</RenderToolProvider>,
|
|
130
|
-
);
|
|
131
|
-
|
|
132
|
-
const render1 = () => React.createElement("div", null, "v1");
|
|
133
|
-
const render2 = () => React.createElement("div", null, "v2");
|
|
134
|
-
|
|
135
|
-
let unregister1: () => void;
|
|
136
|
-
|
|
137
|
-
act(() => {
|
|
138
|
-
unregister1 = registerFn!("shared-tool", render1);
|
|
139
|
-
});
|
|
140
|
-
|
|
141
|
-
// Re-register with a different render function (simulates a new component mounting)
|
|
142
|
-
act(() => {
|
|
143
|
-
registerFn!("shared-tool", render2);
|
|
144
|
-
});
|
|
145
|
-
|
|
146
|
-
// Calling unregister1 should NOT remove the tool because the current
|
|
147
|
-
// render function is render2, not render1
|
|
148
|
-
act(() => {
|
|
149
|
-
unregister1!();
|
|
150
|
-
});
|
|
151
|
-
|
|
152
|
-
expect(registry!.has("shared-tool")).toBe(true);
|
|
153
|
-
});
|
|
154
|
-
});
|
|
155
|
-
|
|
156
|
-
describe("useSyncExternalStore integration", () => {
|
|
157
|
-
it("returns updated registry after registration", () => {
|
|
158
|
-
let registry: Map<string, any> | null = null;
|
|
159
|
-
let registerFn: ((name: string, render: any) => () => void) | null = null;
|
|
160
|
-
|
|
161
|
-
function Writer() {
|
|
162
|
-
const ctx = useRenderToolContext();
|
|
163
|
-
registerFn = ctx.register;
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
function Reader() {
|
|
168
|
-
registry = useRenderToolRegistry();
|
|
169
|
-
return null;
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
render(
|
|
173
|
-
<RenderToolProvider>
|
|
174
|
-
<Writer />
|
|
175
|
-
<Reader />
|
|
176
|
-
</RenderToolProvider>,
|
|
177
|
-
);
|
|
178
|
-
|
|
179
|
-
const sizeBefore = registry!.size;
|
|
180
|
-
|
|
181
|
-
act(() => {
|
|
182
|
-
registerFn!("tool-a", () => React.createElement("div"));
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
// After registration, the registry should contain the new tool
|
|
186
|
-
expect(registry!.has("tool-a")).toBe(true);
|
|
187
|
-
expect(registry!.size).toBe(sizeBefore + 1);
|
|
188
|
-
});
|
|
189
|
-
|
|
190
|
-
it("notifies multiple subscribers when registry changes", () => {
|
|
191
|
-
let registry1: Map<string, any> | null = null;
|
|
192
|
-
let registry2: Map<string, any> | null = null;
|
|
193
|
-
let registerFn: ((name: string, render: any) => () => void) | null = null;
|
|
194
|
-
|
|
195
|
-
function Writer() {
|
|
196
|
-
const ctx = useRenderToolContext();
|
|
197
|
-
registerFn = ctx.register;
|
|
198
|
-
return null;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function Reader1() {
|
|
202
|
-
registry1 = useRenderToolRegistry();
|
|
203
|
-
return null;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
function Reader2() {
|
|
207
|
-
registry2 = useRenderToolRegistry();
|
|
208
|
-
return null;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
render(
|
|
212
|
-
<RenderToolProvider>
|
|
213
|
-
<Writer />
|
|
214
|
-
<Reader1 />
|
|
215
|
-
<Reader2 />
|
|
216
|
-
</RenderToolProvider>,
|
|
217
|
-
);
|
|
218
|
-
|
|
219
|
-
act(() => {
|
|
220
|
-
registerFn!("multi-sub-tool", () => React.createElement("div"));
|
|
221
|
-
});
|
|
222
|
-
|
|
223
|
-
// Both readers should see the same registry
|
|
224
|
-
expect(registry1!.has("multi-sub-tool")).toBe(true);
|
|
225
|
-
expect(registry2!.has("multi-sub-tool")).toBe(true);
|
|
226
|
-
// They should be the exact same reference
|
|
227
|
-
expect(registry1).toBe(registry2);
|
|
228
|
-
});
|
|
229
|
-
});
|
|
230
|
-
|
|
231
|
-
describe("error handling", () => {
|
|
232
|
-
it("useRenderToolContext throws outside provider", () => {
|
|
233
|
-
function TestComponent() {
|
|
234
|
-
useRenderToolContext();
|
|
235
|
-
return null;
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
239
|
-
|
|
240
|
-
expect(() => {
|
|
241
|
-
render(<TestComponent />);
|
|
242
|
-
}).toThrow("useRenderTool must be used within a RenderToolProvider");
|
|
243
|
-
|
|
244
|
-
spy.mockRestore();
|
|
245
|
-
});
|
|
246
|
-
|
|
247
|
-
it("useRenderToolRegistry throws outside provider", () => {
|
|
248
|
-
function TestComponent() {
|
|
249
|
-
useRenderToolRegistry();
|
|
250
|
-
return null;
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
const spy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
254
|
-
|
|
255
|
-
expect(() => {
|
|
256
|
-
render(<TestComponent />);
|
|
257
|
-
}).toThrow(
|
|
258
|
-
"useRenderToolRegistry must be used within a RenderToolProvider",
|
|
259
|
-
);
|
|
260
|
-
|
|
261
|
-
spy.mockRestore();
|
|
262
|
-
});
|
|
263
|
-
});
|
|
264
|
-
});
|