|
| 1 | +"use client"; |
| 2 | + |
| 3 | +import { createContext, useContext, useEffect, useReducer } from "react"; |
| 4 | +import { CopilotKitCoreReact } from "./lib/react-core"; |
| 5 | +import type { CopilotKitCoreReactConfig } from "./lib/react-core"; |
| 6 | +import type { LicenseContextValue } from "@copilotkit/shared"; |
| 7 | + |
| 8 | +// Re-export so headless.ts (and consumers) reference the same type declaration. |
| 9 | +export { CopilotKitCoreReact }; |
| 10 | +export type { CopilotKitCoreReactConfig }; |
| 11 | + |
| 12 | +export interface CopilotKitContextValue { |
| 13 | + copilotkit: CopilotKitCoreReact; |
| 14 | + /** |
| 15 | + * Set of tool call IDs currently being executed. |
| 16 | + * This is tracked at the provider level to ensure tool execution events |
| 17 | + * are captured even before child components mount. |
| 18 | + */ |
| 19 | + executingToolCallIds: ReadonlySet<string>; |
| 20 | +} |
| 21 | + |
| 22 | +export const EMPTY_SET: ReadonlySet<string> = new Set(); |
| 23 | + |
| 24 | +export const CopilotKitContext = createContext<CopilotKitContextValue | null>( |
| 25 | + null, |
| 26 | +); |
| 27 | + |
| 28 | +export const useCopilotKit = (): CopilotKitContextValue => { |
| 29 | + const context = useContext(CopilotKitContext); |
| 30 | + const [, forceUpdate] = useReducer((x: number) => x + 1, 0); |
| 31 | + |
| 32 | + if (!context) { |
| 33 | + throw new Error("useCopilotKit must be used within CopilotKitProvider"); |
| 34 | + } |
| 35 | + useEffect(() => { |
| 36 | + const subscription = context.copilotkit.subscribe({ |
| 37 | + onRuntimeConnectionStatusChanged: () => { |
| 38 | + forceUpdate(); |
| 39 | + }, |
| 40 | + }); |
| 41 | + return () => { |
| 42 | + subscription.unsubscribe(); |
| 43 | + }; |
| 44 | + // eslint-disable-next-line react-hooks/exhaustive-deps |
| 45 | + }, []); |
| 46 | + |
| 47 | + return context; |
| 48 | +}; |
| 49 | + |
| 50 | +// License context — shared between web and RN providers. |
| 51 | +// Default is permissive (all features allowed) — providers override via createLicenseContextValue. |
| 52 | +// Inlined here to avoid a runtime import from @copilotkit/shared, which pulls in |
| 53 | +// Node-only deps (jose) that break React Native's Metro bundler. |
| 54 | +export const LicenseContext = createContext<LicenseContextValue>({ |
| 55 | + status: null, |
| 56 | + license: null, |
| 57 | + checkFeature: () => true, |
| 58 | + getLimit: () => null, |
| 59 | +} as LicenseContextValue); |
| 60 | + |
| 61 | +export const useLicenseContext = (): LicenseContextValue => |
| 62 | + useContext(LicenseContext); |
0 commit comments