@copilotkit/react-native 1.70.3 → 1.71.1
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/USAGE.md +76 -5
- package/dist/headless.cjs +1 -1
- package/dist/headless.d.cts +59 -3
- package/dist/headless.d.mts +59 -3
- package/dist/headless.mjs +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/useRenderTool-DFz206nL.d.cts +149 -0
- package/dist/useRenderTool-DsCxzyAP.d.mts +149 -0
- package/dist/useRenderTool-L3Rw6SYD.cjs +298 -0
- package/dist/useRenderTool-L3Rw6SYD.cjs.map +1 -0
- package/dist/useRenderTool-pLM3upcs.mjs +285 -0
- package/dist/useRenderTool-pLM3upcs.mjs.map +1 -0
- package/package.json +4 -4
- package/src/__mocks__/test-copilotkit.tsx +14 -2
- package/src/__tests__/frontend-tool-render.test-d.tsx +148 -0
- package/src/__tests__/headless-entry-surface.test.ts +232 -2
- package/src/__tests__/headless-value-exports.test.ts +16 -5
- package/src/components/__tests__/CopilotChatToolCalls.test.tsx +26 -22
- package/src/headless.ts +79 -7
- package/src/hooks/__tests__/render-tool-call.integration.test.tsx +17 -15
- package/src/hooks/__tests__/useRenderTool.test.tsx +733 -202
- package/src/hooks/useRenderTool.ts +482 -49
- package/dist/useRenderTool-BBxnOOeJ.d.mts +0 -161
- package/dist/useRenderTool-BWo11PCL.d.cts +0 -161
- package/dist/useRenderTool-CKEPq7MQ.cjs +0 -162
- package/dist/useRenderTool-CKEPq7MQ.cjs.map +0 -1
- package/dist/useRenderTool-l7M-I8rT.mjs +0 -149
- package/dist/useRenderTool-l7M-I8rT.mjs.map +0 -1
- package/src/hooks/index.ts +0 -3
- package/src/hooks/render-tool-types.ts +0 -55
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"useRenderTool-l7M-I8rT.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\";\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 {children}\n </LicenseContext.Provider>\n </CopilotKitContext.Provider>\n );\n};\n","import { useFrontendTool } from \"@copilotkit/react-core/v2/headless\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { RenderToolFunction } from \"./render-tool-types\";\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 /** Schema describing the tool's parameters (any StandardSchemaV1 library). */\n parameters: StandardSchemaV1<unknown, T>;\n /**\n * Render function returning a React Native element for the tool call.\n * Rendered by `CopilotChat` inline, and by `useRenderToolCall()` anywhere else.\n *\n * Arguments STREAM: on `status: \"inProgress\"` the props are partial, because\n * the model has not finished writing the JSON. Write renderers that tolerate\n * missing fields — that is what makes UI build progressively.\n */\n render: RenderToolFunction<T>;\n /** Optional handler. Omit for render-only (display IS the effect). */\n handler?: (args: T) => Promise<unknown>;\n /** Scope this tool to a single agent. */\n agentId?: string;\n}\n\n/**\n * Registers a frontend tool AND its renderer.\n *\n * Registration goes through react-core's `useFrontendTool`, which writes the\n * renderer into `CopilotKitCoreReact.renderToolCalls` — the canonical registry\n * that RN's provider already instantiates. There is deliberately NO React\n * Native-local registry: this package previously kept its own Map, which meant\n * `useComponent` (registering into core's) rendered nowhere on RN, and renderers\n * were dropped from chat history on unmount.\n */\n/**\n * @param deps Optional dependency array. The `render` function is captured at\n * registration and only refreshed when `deps` change — it does NOT re-read the\n * latest closure on every render. If your `render` closes over component state\n * or props that change over time, you MUST pass those values in `deps`, or the\n * chat will keep painting with the stale closure.\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\n useFrontendTool<T>(\n {\n name,\n description,\n parameters,\n handler,\n agentId,\n // No cast needed: ReactFrontendTool.render is ReactToolCallRenderer<T>[\"render\"],\n // and RenderToolFunction is derived from exactly that props type, returning\n // ReactElement | null (assignable to ComponentType's ReactNode).\n render,\n },\n deps,\n );\n}\n\nexport type { RenderToolProps, RenderToolFunction } from \"./render-tool-types\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,MAAa,sBAA+D,EAC1E,UACA,YACA,SAAS,aACT,aACA,mBACA,YACA,SACA,OACA,wBACI;CAEJ,MAAM,kBACJ,OAAO,gBAAgB,aAAa,aAAa,GAAG;CAKtD,MAAM,gBAAgB,cACd,mBAAmB,EAAE,EAC3B,CAAC,KAAK,UAAU,gBAAgB,CAAC,CAClC;CAED,MAAM,mBAAmB,cACjB,cAAc,EAAE,EACtB,CAAC,KAAK,UAAU,WAAW,CAAC,CAC7B;CAED,MAAM,gBAAgB,OAA2C,KAAK;AAEtE,KAAI,cAAc,YAAY,MAAM;EAClC,MAAM,WAAwC,IAAI,oBAAoB;GACpE;GACA,kBACE,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA;GACR,SAAS;GACT;GACA,YAAY;GACZ;GACD,CAAC;AAGF,MAAI,sBAAsB,OACxB,UAAS,qBAAqB,kBAAkB;AAElD,gBAAc,UAAU;;CAG1B,MAAM,aAAa,cAAc;AAGjC,iBAAgB;AACd,aAAW,cAAc,WAAW;AACpC,aAAW,oBACT,sBAAsB,OAClB,WACA,sBAAsB,QACpB,SACA,OACP;AACD,aAAW,WAAW,cAAc;AACpC,aAAW,eAAe,YAAY;AACtC,aAAW,cAAc,iBAAiB;AAC1C,aAAW,SAAS,MAAM;I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AEd,SAAkC,MAAqC;CACvE,MAAM,EAAE,MAAM,aAAa,YAAY,QAAQ,SAAS,YAAY;AAEpE,iBACE;EACE;EACA;EACA;EACA;EACA;EAIA;EACD,EACD,KACD"}
|
package/src/hooks/index.ts
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import type React from "react";
|
|
2
|
-
import type { ReactToolCallRenderer } from "@copilotkit/react-core/v2/headless";
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* Props a React Native render function receives for a tool call.
|
|
6
|
-
*
|
|
7
|
-
* DERIVED from react-core's canonical `ReactToolCallRenderer` contract rather
|
|
8
|
-
* than declared separately. This is deliberate: RN previously declared its own
|
|
9
|
-
* shape and drifted from that contract — RN's `status` was a two-member
|
|
10
|
-
* `"executing" | "complete"` union with no in-progress state, RN omitted
|
|
11
|
-
* `name`/`toolCallId` entirely, and RN's `args` was unconditionally the full
|
|
12
|
-
* `T`, promising complete arguments even before they had finished streaming.
|
|
13
|
-
*
|
|
14
|
-
* What the derivation buys, precisely: RN's props cannot drift from
|
|
15
|
-
* `ReactToolCallRenderer` — the contract every registered renderer is
|
|
16
|
-
* actually invoked against, and the type this alias reads through
|
|
17
|
-
* `React.ComponentProps`. Change that contract and RN's public type changes
|
|
18
|
-
* with it, so `check-types` names every RN renderer the change breaks.
|
|
19
|
-
*
|
|
20
|
-
* What it does NOT buy: parity with the type react-core *publicly exports*
|
|
21
|
-
* under this same name. Web's `RenderToolProps<S>`
|
|
22
|
-
* (react-core `src/v2/hooks/use-render-tool.tsx`) is a separate union, generic
|
|
23
|
-
* over a schema rather than over the parsed args, carrying arguments under
|
|
24
|
-
* `parameters` (not `args`) and declaring `status` as the string literals
|
|
25
|
-
* `"inProgress"` / `"executing"` / `"complete"` rather than as `ToolCallStatus`
|
|
26
|
-
* members. Both divergences are live today and nothing type-checks them shut:
|
|
27
|
-
* the two types share no structural relation, and the one place they meet —
|
|
28
|
-
* react-core's own bridge, which spreads the enum-typed renderer props into
|
|
29
|
-
* the literal-typed slot — compiles because a string-enum member is
|
|
30
|
-
* assignable to its own literal type (not the reverse). Web's `status` is a
|
|
31
|
-
* widening of the canonical contract, not a derivation from it. RN's entry
|
|
32
|
-
* point also re-exports web's three `RenderTool*Props` arms, so both shapes
|
|
33
|
-
* ship under confusingly similar names.
|
|
34
|
-
*
|
|
35
|
-
* `status` is the discriminant of a three-arm union, typed as the
|
|
36
|
-
* `ToolCallStatus` enum (`@copilotkit/core`), so narrow with the enum members
|
|
37
|
-
* rather than the raw strings: `args` is `Partial<T>` only on
|
|
38
|
-
* `ToolCallStatus.InProgress`, and `result` is a string only on
|
|
39
|
-
* `ToolCallStatus.Complete`.
|
|
40
|
-
*/
|
|
41
|
-
export type RenderToolProps<T = Record<string, unknown>> = React.ComponentProps<
|
|
42
|
-
ReactToolCallRenderer<T>["render"]
|
|
43
|
-
>;
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* A render function returning a React Native element.
|
|
47
|
-
*
|
|
48
|
-
* This is the one place RN legitimately narrows `ReactToolCallRenderer`:
|
|
49
|
-
* `FlatList`'s `renderItem` cannot render strings or portals, so RN requires
|
|
50
|
-
* `ReactElement | null` where that contract permits any `ReactNode`. The PROPS
|
|
51
|
-
* come from it unchanged; only the return type is platform-specific.
|
|
52
|
-
*/
|
|
53
|
-
export type RenderToolFunction<T = Record<string, unknown>> = (
|
|
54
|
-
props: RenderToolProps<T>,
|
|
55
|
-
) => React.ReactElement | null;
|