@copilotkit/react-core 1.6.0-next.9 → 1.6.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/CHANGELOG.md +36 -0
- package/dist/{chunk-5M47BILE.mjs → chunk-37LXOL6B.mjs} +2 -2
- package/dist/{chunk-XERJQUHA.mjs → chunk-4CEQJ2X6.mjs} +2 -2
- package/dist/{chunk-XERJQUHA.mjs.map → chunk-4CEQJ2X6.mjs.map} +1 -1
- package/dist/{chunk-JFCNSGNU.mjs → chunk-4X4XFBC6.mjs} +3 -3
- package/dist/{chunk-F7O6L7C3.mjs → chunk-7XNZHQWJ.mjs} +2 -2
- package/dist/{chunk-7HWSAEOY.mjs → chunk-AT4ALBK4.mjs} +13 -4
- package/dist/{chunk-7HWSAEOY.mjs.map → chunk-AT4ALBK4.mjs.map} +1 -1
- package/dist/{chunk-MPFP6ANM.mjs → chunk-CJTSYEYG.mjs} +3 -3
- package/dist/chunk-CQPYJIBH.mjs +1 -0
- package/dist/{chunk-ALW2T2LL.mjs → chunk-FUO5LKSJ.mjs} +114 -60
- package/dist/chunk-FUO5LKSJ.mjs.map +1 -0
- package/dist/{chunk-XOHLZIZK.mjs → chunk-JHPCDBBM.mjs} +2 -2
- package/dist/{chunk-PR5R5TTF.mjs → chunk-JMFYGW35.mjs} +2 -2
- package/dist/{chunk-T2EFA3D5.mjs → chunk-NY3BUYYZ.mjs} +2 -2
- package/dist/chunk-O3IIH54P.mjs +24 -0
- package/dist/chunk-O3IIH54P.mjs.map +1 -0
- package/dist/{chunk-7YXUCWXF.mjs → chunk-PRWPZCKZ.mjs} +10 -8
- package/dist/chunk-PRWPZCKZ.mjs.map +1 -0
- package/dist/{chunk-ZM56S3LJ.mjs → chunk-PTSWFERP.mjs} +3 -1
- package/dist/chunk-PTSWFERP.mjs.map +1 -0
- package/dist/{chunk-ADTDNMYG.mjs → chunk-RPSMTOER.mjs} +3 -3
- package/dist/{chunk-2F6RYBYS.mjs → chunk-YI7LPACV.mjs} +3 -3
- package/dist/{chunk-QJPWWVJQ.mjs → chunk-ZNWM2EVT.mjs} +4 -4
- package/dist/components/copilot-provider/copilot-messages.js +2 -0
- package/dist/components/copilot-provider/copilot-messages.js.map +1 -1
- package/dist/components/copilot-provider/copilot-messages.mjs +2 -2
- package/dist/components/copilot-provider/copilotkit-props.d.ts +1 -1
- package/dist/components/copilot-provider/copilotkit.d.ts +1 -1
- package/dist/components/copilot-provider/copilotkit.js +5 -1
- package/dist/components/copilot-provider/copilotkit.js.map +1 -1
- package/dist/components/copilot-provider/copilotkit.mjs +4 -4
- package/dist/components/copilot-provider/index.d.ts +1 -1
- package/dist/components/copilot-provider/index.js +5 -1
- package/dist/components/copilot-provider/index.js.map +1 -1
- package/dist/components/copilot-provider/index.mjs +4 -4
- package/dist/components/index.d.ts +1 -1
- package/dist/components/index.js +5 -1
- package/dist/components/index.js.map +1 -1
- package/dist/components/index.mjs +4 -4
- package/dist/context/copilot-context.d.ts +1 -1
- package/dist/context/copilot-context.js +2 -0
- package/dist/context/copilot-context.js.map +1 -1
- package/dist/context/copilot-context.mjs +1 -1
- package/dist/context/index.d.ts +1 -1
- package/dist/context/index.js +2 -0
- package/dist/context/index.js.map +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/{copilot-context-9ae8990b.d.ts → copilot-context-c402f48d.d.ts} +2 -0
- package/dist/hooks/index.d.ts +2 -1
- package/dist/hooks/index.js +159 -79
- package/dist/hooks/index.js.map +1 -1
- package/dist/hooks/index.mjs +20 -16
- package/dist/hooks/use-chat.d.ts +1 -1
- package/dist/hooks/use-chat.js +113 -62
- package/dist/hooks/use-chat.js.map +1 -1
- package/dist/hooks/use-chat.mjs +2 -2
- package/dist/hooks/use-coagent-state-render.js +2 -0
- package/dist/hooks/use-coagent-state-render.js.map +1 -1
- package/dist/hooks/use-coagent-state-render.mjs +2 -2
- package/dist/hooks/use-coagent.d.ts +1 -1
- package/dist/hooks/use-coagent.js +121 -68
- package/dist/hooks/use-coagent.js.map +1 -1
- package/dist/hooks/use-coagent.mjs +8 -8
- package/dist/hooks/use-copilot-action.js +2 -0
- package/dist/hooks/use-copilot-action.js.map +1 -1
- package/dist/hooks/use-copilot-action.mjs +2 -2
- package/dist/hooks/use-copilot-additional-instructions.d.ts +26 -0
- package/dist/hooks/use-copilot-additional-instructions.js +162 -0
- package/dist/hooks/use-copilot-additional-instructions.js.map +1 -0
- package/dist/hooks/use-copilot-additional-instructions.mjs +9 -0
- package/dist/hooks/use-copilot-additional-instructions.mjs.map +1 -0
- package/dist/hooks/use-copilot-authenticated-action.js +2 -0
- package/dist/hooks/use-copilot-authenticated-action.js.map +1 -1
- package/dist/hooks/use-copilot-authenticated-action.mjs +3 -3
- package/dist/hooks/use-copilot-chat.d.ts +1 -1
- package/dist/hooks/use-copilot-chat.js +119 -66
- package/dist/hooks/use-copilot-chat.js.map +1 -1
- package/dist/hooks/use-copilot-chat.mjs +7 -7
- package/dist/hooks/use-copilot-readable.d.ts +5 -1
- package/dist/hooks/use-copilot-readable.js +13 -2
- package/dist/hooks/use-copilot-readable.js.map +1 -1
- package/dist/hooks/use-copilot-readable.mjs +2 -2
- package/dist/hooks/use-langgraph-interrupt-render.js +2 -0
- package/dist/hooks/use-langgraph-interrupt-render.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt-render.mjs +2 -2
- package/dist/hooks/use-langgraph-interrupt.d.ts +1 -1
- package/dist/hooks/use-langgraph-interrupt.js +121 -68
- package/dist/hooks/use-langgraph-interrupt.js.map +1 -1
- package/dist/hooks/use-langgraph-interrupt.mjs +8 -8
- package/dist/hooks/use-make-copilot-document-readable.js +2 -0
- package/dist/hooks/use-make-copilot-document-readable.js.map +1 -1
- package/dist/hooks/use-make-copilot-document-readable.mjs +2 -2
- package/dist/index.d.ts +2 -1
- package/dist/index.js +168 -86
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +21 -17
- package/dist/lib/copilot-task.d.ts +1 -1
- package/dist/lib/copilot-task.js +1 -1
- package/dist/lib/copilot-task.js.map +1 -1
- package/dist/lib/copilot-task.mjs +6 -6
- package/dist/lib/index.d.ts +1 -1
- package/dist/lib/index.js +1 -1
- package/dist/lib/index.js.map +1 -1
- package/dist/lib/index.mjs +6 -6
- package/dist/types/frontend-action.d.ts +2 -1
- package/dist/types/frontend-action.js +1 -1
- package/dist/types/frontend-action.js.map +1 -1
- package/dist/types/frontend-action.mjs +1 -1
- package/dist/types/interrupt-action.d.ts +1 -1
- package/dist/utils/extract.d.ts +1 -1
- package/dist/utils/extract.js.map +1 -1
- package/dist/utils/extract.mjs +4 -4
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/index.mjs +4 -4
- package/package.json +5 -5
- package/src/components/copilot-provider/copilotkit.tsx +3 -1
- package/src/context/copilot-context.tsx +6 -0
- package/src/hooks/index.ts +1 -0
- package/src/hooks/use-chat.ts +133 -58
- package/src/hooks/use-copilot-additional-instructions.ts +85 -0
- package/src/hooks/use-copilot-readable.ts +16 -2
- package/src/types/frontend-action.ts +5 -2
- package/dist/chunk-7YXUCWXF.mjs.map +0 -1
- package/dist/chunk-ALW2T2LL.mjs.map +0 -1
- package/dist/chunk-IGLITGLC.mjs +0 -1
- package/dist/chunk-ZM56S3LJ.mjs.map +0 -1
- /package/dist/{chunk-5M47BILE.mjs.map → chunk-37LXOL6B.mjs.map} +0 -0
- /package/dist/{chunk-JFCNSGNU.mjs.map → chunk-4X4XFBC6.mjs.map} +0 -0
- /package/dist/{chunk-F7O6L7C3.mjs.map → chunk-7XNZHQWJ.mjs.map} +0 -0
- /package/dist/{chunk-MPFP6ANM.mjs.map → chunk-CJTSYEYG.mjs.map} +0 -0
- /package/dist/{chunk-IGLITGLC.mjs.map → chunk-CQPYJIBH.mjs.map} +0 -0
- /package/dist/{chunk-XOHLZIZK.mjs.map → chunk-JHPCDBBM.mjs.map} +0 -0
- /package/dist/{chunk-PR5R5TTF.mjs.map → chunk-JMFYGW35.mjs.map} +0 -0
- /package/dist/{chunk-T2EFA3D5.mjs.map → chunk-NY3BUYYZ.mjs.map} +0 -0
- /package/dist/{chunk-ADTDNMYG.mjs.map → chunk-RPSMTOER.mjs.map} +0 -0
- /package/dist/{chunk-2F6RYBYS.mjs.map → chunk-YI7LPACV.mjs.map} +0 -0
- /package/dist/{chunk-QJPWWVJQ.mjs.map → chunk-ZNWM2EVT.mjs.map} +0 -0
|
@@ -79,6 +79,8 @@ var emptyCopilotContext = {
|
|
|
79
79
|
setIsLoading: () => returnAndThrowInDebug(false),
|
|
80
80
|
chatInstructions: "",
|
|
81
81
|
setChatInstructions: () => returnAndThrowInDebug(""),
|
|
82
|
+
additionalInstructions: [],
|
|
83
|
+
setAdditionalInstructions: () => returnAndThrowInDebug([]),
|
|
82
84
|
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
83
85
|
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
84
86
|
removeDocumentContext: () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hooks/use-coagent-state-render.ts","../../src/context/copilot-context.tsx","../../src/components/toast/toast-provider.tsx"],"sourcesContent":["/**\n * The useCoAgentStateRender hook allows you to render UI components or text based on a Agentic Copilot's state.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n chatComponentsCache,\n availableAgents,\n } = useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n const { addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n addToast({ type: \"warning\", message });\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n });\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: () => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => null,\n removeLangGraphInterruptAction: () => null,\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // We do not display these errors unless we are in dev mode.\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n addToast({\n type: \"error\",\n message: <ErrorToast errors={errors} />,\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1.5rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CA,IAAAA,gBAA8C;;;ACrC9C,mBAAkB;AA4MlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,eAAe,CAAC;AAAA,EAEhB,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI,kBAA0B;AAC5B,YAAM,IAAI,MAAM,uEAAuE;AAAA,IACzF;AA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cAAc,OAAO;AAAA,MAC3B,CAAC;AAAA,IACH;AAAA,EACF,GAAG,CAAC,mBAAmB,CAAC;AAExB,+BAAU,MAAM;AACd,0BAAsB,MAAM,SAAS,MAAa;AAClD,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,oBAAoB,GAAG,IAAI,OAAO;AAAA,IAChE;AACA,WAAO,MAAM;AACX,+BAAyB,MAAM,OAAO;AAAA,IACxC;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA;AAAA,IAEP,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React","import_react"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hooks/use-coagent-state-render.ts","../../src/context/copilot-context.tsx","../../src/components/toast/toast-provider.tsx"],"sourcesContent":["/**\n * The useCoAgentStateRender hook allows you to render UI components or text based on a Agentic Copilot's state.\n * This is particularly useful for showing intermediate state or progress during Agentic Copilot operations.\n *\n * ## Usage\n *\n * ### Simple Usage\n *\n * ```tsx\n * import { useCoAgentStateRender } from \"@copilotkit/react-core\";\n *\n * type YourAgentState = {\n * agent_state_property: string;\n * }\n *\n * useCoAgentStateRender<YourAgentState>({\n * name: \"basic_agent\",\n * nodeName: \"optionally_specify_a_specific_node\",\n * render: ({ status, state, nodeName }) => {\n * return (\n * <YourComponent\n * agentStateProperty={state.agent_state_property}\n * status={status}\n * nodeName={nodeName}\n * />\n * );\n * },\n * });\n * ```\n *\n * This allows for you to render UI components or text based on what is happening within the agent.\n *\n * ### Example\n * A great example of this is in our Perplexity Clone where we render the progress of an agent's internet search as it is happening.\n * You can play around with it below or learn how to build it with its [demo](/coagents/videos/perplexity-clone).\n *\n * <Callout type=\"info\">\n * This example is hosted on Vercel and may take a few seconds to load.\n * </Callout>\n *\n * <iframe src=\"https://examples-coagents-ai-researcher-ui.vercel.app/\" className=\"w-full rounded-lg border h-[700px] my-4\" />\n */\n\nimport { useRef, useContext, useEffect } from \"react\";\nimport { CopilotContext } from \"../context/copilot-context\";\nimport { randomId } from \"@copilotkit/shared\";\nimport { CoAgentStateRender } from \"../types/coagent-action\";\nimport { useToast } from \"../components/toast/toast-provider\";\n\n/**\n * This hook is used to render agent state with custom UI components or text. This is particularly\n * useful for showing intermediate state or progress during Agentic Copilot operations.\n * To get started using rendering intermediate state through this hook, checkout the documentation.\n *\n * https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates\n */\n\n// We implement useCoAgentStateRender dependency handling so that\n// the developer has the option to not provide any dependencies.\n// see useCopilotAction for more details about this approach.\nexport function useCoAgentStateRender<T = any>(\n action: CoAgentStateRender<T>,\n dependencies?: any[],\n): void {\n const {\n setCoAgentStateRender,\n removeCoAgentStateRender,\n coAgentStateRenders,\n chatComponentsCache,\n availableAgents,\n } = useContext(CopilotContext);\n const idRef = useRef<string>(randomId());\n const { addToast } = useToast();\n\n useEffect(() => {\n if (availableAgents?.length && !availableAgents.some((a) => a.name === action.name)) {\n const message = `(useCoAgentStateRender): Agent \"${action.name}\" not found. Make sure the agent exists and is properly configured.`;\n addToast({ type: \"warning\", message });\n }\n }, [availableAgents]);\n\n const key = `${action.name}-${action.nodeName || \"global\"}`;\n\n if (dependencies === undefined) {\n if (coAgentStateRenders[idRef.current]) {\n coAgentStateRenders[idRef.current].handler = action.handler as any;\n if (typeof action.render === \"function\") {\n if (chatComponentsCache.current !== null) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n }\n }\n }\n\n useEffect(() => {\n // Check for duplicates by comparing against all other actions\n const currentId = idRef.current;\n const hasDuplicate = Object.entries(coAgentStateRenders).some(([id, otherAction]) => {\n // Skip comparing with self\n if (id === currentId) return false;\n\n // Different agent names are never duplicates\n if (otherAction.name !== action.name) return false;\n\n // Same agent names:\n const hasNodeName = !!action.nodeName;\n const hasOtherNodeName = !!otherAction.nodeName;\n\n // If neither has nodeName, they're duplicates\n if (!hasNodeName && !hasOtherNodeName) return true;\n\n // If one has nodeName and other doesn't, they're not duplicates\n if (hasNodeName !== hasOtherNodeName) return false;\n\n // If both have nodeName, they're duplicates only if the names match\n return action.nodeName === otherAction.nodeName;\n });\n\n if (hasDuplicate) {\n const message = action.nodeName\n ? `Found multiple state renders for agent ${action.name} and node ${action.nodeName}. State renders might get overridden`\n : `Found multiple state renders for agent ${action.name}. State renders might get overridden`;\n\n addToast({\n type: \"warning\",\n message,\n id: `dup-action-${action.name}`,\n });\n }\n }, [coAgentStateRenders]);\n\n useEffect(() => {\n setCoAgentStateRender(idRef.current, action as any);\n if (chatComponentsCache.current !== null && action.render !== undefined) {\n chatComponentsCache.current.coAgentStateRenders[key] = action.render;\n }\n return () => {\n removeCoAgentStateRender(idRef.current);\n };\n }, [\n setCoAgentStateRender,\n removeCoAgentStateRender,\n action.name,\n // include render only if it's a string\n typeof action.render === \"string\" ? action.render : undefined,\n // dependencies set by the developer\n ...(dependencies || []),\n ]);\n}\n","import { CopilotCloudConfig, FunctionCallHandler } from \"@copilotkit/shared\";\nimport {\n ActionRenderProps,\n CatchAllActionRenderProps,\n FrontendAction,\n} from \"../types/frontend-action\";\nimport React from \"react\";\nimport { TreeNodeId } from \"../hooks/use-tree\";\nimport { DocumentPointer } from \"../types\";\nimport { CopilotChatSuggestionConfiguration } from \"../types/chat-suggestion-configuration\";\nimport { CoAgentStateRender, CoAgentStateRenderProps } from \"../types/coagent-action\";\nimport { CoagentState } from \"../types/coagent-state\";\nimport {\n CopilotRuntimeClient,\n ExtensionsInput,\n ForwardedParametersInput,\n} from \"@copilotkit/runtime-client-gql\";\nimport { Agent } from \"@copilotkit/runtime-client-gql\";\nimport {\n LangGraphInterruptAction,\n LangGraphInterruptActionSetter,\n} from \"../types/interrupt-action\";\n\n/**\n * Interface for the configuration of the Copilot API.\n */\nexport interface CopilotApiConfig {\n /**\n * The public API key for Copilot Cloud.\n */\n publicApiKey?: string;\n\n /**\n * The configuration for Copilot Cloud.\n */\n cloud?: CopilotCloudConfig;\n\n /**\n * The endpoint for the chat API.\n */\n chatApiEndpoint: string;\n\n /**\n * The endpoint for the Copilot transcribe audio service.\n */\n transcribeAudioUrl?: string;\n\n /**\n * The endpoint for the Copilot text to speech service.\n */\n textToSpeechUrl?: string;\n\n /**\n * additional headers to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'Authorization': 'Bearer your_token_here'\n * }\n * ```\n */\n headers: Record<string, string>;\n\n /**\n * Custom properties to be sent with the request\n * @default {}\n * @example\n * ```\n * {\n * 'user_id': 'user_id'\n * }\n * ```\n */\n properties?: Record<string, any>;\n\n /**\n * Indicates whether the user agent should send or receive cookies from the other domain\n * in the case of cross-origin requests.\n */\n credentials?: RequestCredentials;\n}\n\nexport type InChatRenderFunction<TProps = ActionRenderProps<any> | CatchAllActionRenderProps<any>> =\n (props: TProps) => string | JSX.Element;\nexport type CoagentInChatRenderFunction = (\n props: CoAgentStateRenderProps<any>,\n) => string | JSX.Element | undefined | null;\n\nexport interface ChatComponentsCache {\n actions: Record<string, InChatRenderFunction | string>;\n coAgentStateRenders: Record<string, CoagentInChatRenderFunction | string>;\n}\n\nexport interface AgentSession {\n agentName: string;\n threadId?: string;\n nodeName?: string;\n}\n\nexport interface AuthState {\n status: \"authenticated\" | \"unauthenticated\";\n authHeaders: Record<string, string>;\n userId?: string;\n metadata?: Record<string, any>;\n}\n\nexport type ActionName = string;\n\nexport interface CopilotContextParams {\n // function-calling\n actions: Record<string, FrontendAction<any>>;\n setAction: (id: string, action: FrontendAction<any>) => void;\n removeAction: (id: string) => void;\n\n // coagent actions\n coAgentStateRenders: Record<string, CoAgentStateRender<any>>;\n setCoAgentStateRender: (id: string, stateRender: CoAgentStateRender<any>) => void;\n removeCoAgentStateRender: (id: string) => void;\n\n chatComponentsCache: React.RefObject<ChatComponentsCache>;\n\n getFunctionCallHandler: (\n customEntryPoints?: Record<string, FrontendAction<any>>,\n ) => FunctionCallHandler;\n\n // text context\n addContext: (context: string, parentId?: string, categories?: string[]) => TreeNodeId;\n removeContext: (id: TreeNodeId) => void;\n getContextString: (documents: DocumentPointer[], categories: string[]) => string;\n\n // document context\n addDocumentContext: (documentPointer: DocumentPointer, categories?: string[]) => TreeNodeId;\n removeDocumentContext: (documentId: string) => void;\n getDocumentsContext: (categories: string[]) => DocumentPointer[];\n\n isLoading: boolean;\n setIsLoading: React.Dispatch<React.SetStateAction<boolean>>;\n\n chatSuggestionConfiguration: { [key: string]: CopilotChatSuggestionConfiguration };\n addChatSuggestionConfiguration: (\n id: string,\n suggestion: CopilotChatSuggestionConfiguration,\n ) => void;\n removeChatSuggestionConfiguration: (id: string) => void;\n\n chatInstructions: string;\n setChatInstructions: React.Dispatch<React.SetStateAction<string>>;\n\n additionalInstructions?: string[];\n setAdditionalInstructions: React.Dispatch<React.SetStateAction<string[]>>;\n\n // api endpoints\n copilotApiConfig: CopilotApiConfig;\n\n showDevConsole: boolean | \"auto\";\n\n // agents\n coagentStates: Record<string, CoagentState>;\n setCoagentStates: React.Dispatch<React.SetStateAction<Record<string, CoagentState>>>;\n coagentStatesRef: React.RefObject<Record<string, CoagentState>>;\n setCoagentStatesWithRef: (\n value:\n | Record<string, CoagentState>\n | ((prev: Record<string, CoagentState>) => Record<string, CoagentState>),\n ) => void;\n\n agentSession: AgentSession | null;\n setAgentSession: React.Dispatch<React.SetStateAction<AgentSession | null>>;\n\n agentLock: string | null;\n\n threadId: string;\n setThreadId: React.Dispatch<React.SetStateAction<string>>;\n\n runId: string | null;\n setRunId: React.Dispatch<React.SetStateAction<string | null>>;\n\n // The chat abort controller can be used to stop generation globally,\n // i.e. when using `stop()` from `useChat`\n chatAbortControllerRef: React.MutableRefObject<AbortController | null>;\n\n // runtime\n runtimeClient: CopilotRuntimeClient;\n\n /**\n * The forwarded parameters to use for the task.\n */\n forwardedParameters?: Pick<ForwardedParametersInput, \"temperature\">;\n availableAgents: Agent[];\n\n /**\n * The auth states for the CopilotKit.\n */\n authStates_c?: Record<ActionName, AuthState>;\n setAuthStates_c?: React.Dispatch<React.SetStateAction<Record<ActionName, AuthState>>>;\n\n /**\n * The auth config for the CopilotKit.\n */\n authConfig_c?: {\n SignInComponent: React.ComponentType<{\n onSignInComplete: (authState: AuthState) => void;\n }>;\n };\n\n extensions: ExtensionsInput;\n setExtensions: React.Dispatch<React.SetStateAction<ExtensionsInput>>;\n langGraphInterruptAction: LangGraphInterruptAction | null;\n setLangGraphInterruptAction: LangGraphInterruptActionSetter;\n removeLangGraphInterruptAction: () => void;\n}\n\nconst emptyCopilotContext: CopilotContextParams = {\n actions: {},\n setAction: () => {},\n removeAction: () => {},\n\n coAgentStateRenders: {},\n setCoAgentStateRender: () => {},\n removeCoAgentStateRender: () => {},\n\n chatComponentsCache: { current: { actions: {}, coAgentStateRenders: {} } },\n getContextString: (documents: DocumentPointer[], categories: string[]) =>\n returnAndThrowInDebug(\"\"),\n addContext: () => \"\",\n removeContext: () => {},\n\n getFunctionCallHandler: () => returnAndThrowInDebug(async () => {}),\n\n isLoading: false,\n setIsLoading: () => returnAndThrowInDebug(false),\n\n chatInstructions: \"\",\n setChatInstructions: () => returnAndThrowInDebug(\"\"),\n\n additionalInstructions: [],\n setAdditionalInstructions: () => returnAndThrowInDebug([]),\n\n getDocumentsContext: (categories: string[]) => returnAndThrowInDebug([]),\n addDocumentContext: () => returnAndThrowInDebug(\"\"),\n removeDocumentContext: () => {},\n runtimeClient: {} as any,\n\n copilotApiConfig: new (class implements CopilotApiConfig {\n get chatApiEndpoint(): string {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n\n get headers(): Record<string, string> {\n return {};\n }\n get body(): Record<string, any> {\n return {};\n }\n })(),\n\n chatSuggestionConfiguration: {},\n addChatSuggestionConfiguration: () => {},\n removeChatSuggestionConfiguration: () => {},\n showDevConsole: \"auto\",\n coagentStates: {},\n setCoagentStates: () => {},\n coagentStatesRef: { current: {} },\n setCoagentStatesWithRef: () => {},\n agentSession: null,\n setAgentSession: () => {},\n forwardedParameters: {},\n agentLock: null,\n threadId: \"\",\n setThreadId: () => {},\n runId: null,\n setRunId: () => {},\n chatAbortControllerRef: { current: null },\n availableAgents: [],\n extensions: {},\n setExtensions: () => {},\n langGraphInterruptAction: null,\n setLangGraphInterruptAction: () => null,\n removeLangGraphInterruptAction: () => null,\n};\n\nexport const CopilotContext = React.createContext<CopilotContextParams>(emptyCopilotContext);\n\nexport function useCopilotContext(): CopilotContextParams {\n const context = React.useContext(CopilotContext);\n if (context === emptyCopilotContext) {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n }\n return context;\n}\n\nfunction returnAndThrowInDebug<T>(_value: T): T {\n throw new Error(\"Remember to wrap your app in a `<CopilotKit> {...} </CopilotKit>` !!!\");\n}\n","import { GraphQLError } from \"@copilotkit/runtime-client-gql\";\nimport React, { createContext, useContext, useState, useCallback } from \"react\";\nimport { ErrorToast } from \"../error-boundary/error-utils\";\nimport { PartialBy } from \"@copilotkit/shared\";\n\ninterface Toast {\n id: string;\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n duration?: number;\n}\n\ninterface ToastContextValue {\n toasts: Toast[];\n addToast: (toast: PartialBy<Toast, \"id\">) => void;\n addGraphQLErrorsToast: (errors: GraphQLError[]) => void;\n removeToast: (id: string) => void;\n enabled: boolean;\n}\n\nconst ToastContext = createContext<ToastContextValue | undefined>(undefined);\n\nexport function useToast() {\n const context = useContext(ToastContext);\n if (!context) {\n throw new Error(\"useToast must be used within a ToastProvider\");\n }\n return context;\n}\n\nexport function ToastProvider({\n enabled,\n children,\n}: {\n enabled: boolean;\n children: React.ReactNode;\n}) {\n const [toasts, setToasts] = useState<Toast[]>([]);\n const addToast = useCallback(\n (toast: PartialBy<Toast, \"id\">) => {\n // We do not display these errors unless we are in dev mode.\n if (!enabled) {\n return;\n }\n\n const id = toast.id ?? Math.random().toString(36).substring(2, 9);\n\n setToasts((currentToasts) => {\n if (currentToasts.find((toast) => toast.id === id)) return currentToasts;\n return [...currentToasts, { ...toast, id }];\n });\n\n if (toast.duration) {\n setTimeout(() => {\n removeToast(id);\n }, toast.duration);\n }\n },\n [enabled],\n );\n\n const addGraphQLErrorsToast = useCallback((errors: GraphQLError[]) => {\n addToast({\n type: \"error\",\n message: <ErrorToast errors={errors} />,\n });\n }, []);\n\n const removeToast = useCallback((id: string) => {\n setToasts((currentToasts) => currentToasts.filter((toast) => toast.id !== id));\n }, []);\n\n const value = {\n toasts,\n addToast,\n addGraphQLErrorsToast,\n removeToast,\n enabled,\n };\n\n return (\n <ToastContext.Provider value={value}>\n <div\n style={{\n position: \"fixed\",\n bottom: \"1rem\",\n left: \"50%\",\n transform: \"translateX(-50%)\",\n zIndex: 50,\n display: \"flex\",\n flexDirection: \"column\",\n gap: \"0.5rem\",\n }}\n >\n {toasts.length > 1 && (\n <div style={{ textAlign: \"right\" }}>\n <button\n onClick={() => setToasts([])}\n style={{\n padding: \"4px 8px\",\n fontSize: \"12px\",\n cursor: \"pointer\",\n background: \"white\",\n border: \"1px solid rgba(0,0,0,0.2)\",\n borderRadius: \"4px\",\n }}\n >\n Close All\n </button>\n </div>\n )}\n {toasts.map((toast) => (\n <Toast\n key={toast.id}\n message={toast.message}\n type={toast.type}\n onClose={() => removeToast(toast.id)}\n />\n ))}\n </div>\n {children}\n </ToastContext.Provider>\n );\n}\n\nfunction Toast({\n message,\n type = \"info\",\n onClose,\n}: {\n message: string | React.ReactNode;\n type: \"info\" | \"success\" | \"warning\" | \"error\";\n onClose: () => void;\n}) {\n const bgColors = {\n info: \"#3b82f6\",\n success: \"#22c55e\",\n warning: \"#eab308\",\n error: \"#ef4444\",\n };\n\n return (\n <div\n style={{\n backgroundColor: bgColors[type],\n color: \"white\",\n padding: \"0.5rem 1.5rem\",\n borderRadius: \"0.25rem\",\n boxShadow: \"0 2px 4px rgba(0,0,0,0.1)\",\n position: \"relative\",\n minWidth: \"200px\",\n }}\n >\n <div>{message}</div>\n <button\n onClick={onClose}\n style={{\n position: \"absolute\",\n top: \"0\",\n right: \"0\",\n background: \"none\",\n border: \"none\",\n color: \"white\",\n cursor: \"pointer\",\n padding: \"0.5rem\",\n fontSize: \"1rem\",\n }}\n >\n ✕\n </button>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AA2CA,IAAAA,gBAA8C;;;ACrC9C,mBAAkB;AA+MlB,IAAM,sBAA4C;AAAA,EAChD,SAAS,CAAC;AAAA,EACV,WAAW,MAAM;AAAA,EAAC;AAAA,EAClB,cAAc,MAAM;AAAA,EAAC;AAAA,EAErB,qBAAqB,CAAC;AAAA,EACtB,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,0BAA0B,MAAM;AAAA,EAAC;AAAA,EAEjC,qBAAqB,EAAE,SAAS,EAAE,SAAS,CAAC,GAAG,qBAAqB,CAAC,EAAE,EAAE;AAAA,EACzE,kBAAkB,CAAC,WAA8B,eAC/C,sBAAsB,EAAE;AAAA,EAC1B,YAAY,MAAM;AAAA,EAClB,eAAe,MAAM;AAAA,EAAC;AAAA,EAEtB,wBAAwB,MAAM,sBAAsB,MAAY;AAAA,EAAC,EAAC;AAAA,EAElE,WAAW;AAAA,EACX,cAAc,MAAM,sBAAsB,KAAK;AAAA,EAE/C,kBAAkB;AAAA,EAClB,qBAAqB,MAAM,sBAAsB,EAAE;AAAA,EAEnD,wBAAwB,CAAC;AAAA,EACzB,2BAA2B,MAAM,sBAAsB,CAAC,CAAC;AAAA,EAEzD,qBAAqB,CAAC,eAAyB,sBAAsB,CAAC,CAAC;AAAA,EACvE,oBAAoB,MAAM,sBAAsB,EAAE;AAAA,EAClD,uBAAuB,MAAM;AAAA,EAAC;AAAA,EAC9B,eAAe,CAAC;AAAA,EAEhB,kBAAkB,IAAK,MAAkC;AAAA,IACvD,IAAI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;AAErD,eAAS;AAAA,QACP,MAAM;AAAA,QACN;AAAA,QACA,IAAI,cAAc,OAAO;AAAA,MAC3B,CAAC;AAAA,IACH;AAAA,EACF,GAAG,CAAC,mBAAmB,CAAC;AAExB,+BAAU,MAAM;AACd,0BAAsB,MAAM,SAAS,MAAa;AAClD,QAAI,oBAAoB,YAAY,QAAQ,OAAO,WAAW,QAAW;AACvE,0BAAoB,QAAQ,oBAAoB,GAAG,IAAI,OAAO;AAAA,IAChE;AACA,WAAO,MAAM;AACX,+BAAyB,MAAM,OAAO;AAAA,IACxC;AAAA,EACF,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,OAAO;AAAA;AAAA,IAEP,OAAO,OAAO,WAAW,WAAW,OAAO,SAAS;AAAA;AAAA,IAEpD,GAAI,gBAAgB,CAAC;AAAA,EACvB,CAAC;AACH;","names":["import_react","React","import_react"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
useCoAgentStateRender
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-JMFYGW35.mjs";
|
|
4
|
+
import "../chunk-PTSWFERP.mjs";
|
|
5
5
|
import "../chunk-22ENANUU.mjs";
|
|
6
6
|
import "../chunk-O7ARI5CV.mjs";
|
|
7
7
|
import "../chunk-SKC7AJIV.mjs";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as CopilotContextParams } from '../copilot-context-
|
|
1
|
+
import { a as CopilotContextParams } from '../copilot-context-c402f48d.js';
|
|
2
2
|
import { CopilotMessagesContextParams } from '../context/copilot-messages-context.js';
|
|
3
3
|
import { Message } from '@copilotkit/runtime-client-gql';
|
|
4
4
|
import '@copilotkit/shared';
|
|
@@ -111,6 +111,8 @@ var emptyCopilotContext = {
|
|
|
111
111
|
setIsLoading: () => returnAndThrowInDebug(false),
|
|
112
112
|
chatInstructions: "",
|
|
113
113
|
setChatInstructions: () => returnAndThrowInDebug(""),
|
|
114
|
+
additionalInstructions: [],
|
|
115
|
+
setAdditionalInstructions: () => returnAndThrowInDebug([]),
|
|
114
116
|
getDocumentsContext: (categories) => returnAndThrowInDebug([]),
|
|
115
117
|
addDocumentContext: () => returnAndThrowInDebug(""),
|
|
116
118
|
removeDocumentContext: () => {
|
|
@@ -190,7 +192,7 @@ function useCopilotMessagesContext() {
|
|
|
190
192
|
|
|
191
193
|
// src/hooks/use-copilot-chat.ts
|
|
192
194
|
var import_react8 = require("react");
|
|
193
|
-
var
|
|
195
|
+
var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
|
|
194
196
|
|
|
195
197
|
// src/hooks/use-chat.ts
|
|
196
198
|
var import_react6 = require("react");
|
|
@@ -202,7 +204,7 @@ var import_runtime_client_gql = require("@copilotkit/runtime-client-gql");
|
|
|
202
204
|
var import_shared = require("@copilotkit/shared");
|
|
203
205
|
function processActionsForRuntimeRequest(actions) {
|
|
204
206
|
const filteredActions = actions.filter(
|
|
205
|
-
(action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*"
|
|
207
|
+
(action) => action.available !== import_runtime_client_gql.ActionInputAvailability.Disabled && action.disabled !== true && action.name !== "*" && action.available != "frontend" && !action.pairedAction
|
|
206
208
|
).map((action) => {
|
|
207
209
|
let available = import_runtime_client_gql.ActionInputAvailability.Enabled;
|
|
208
210
|
if (action.disabled) {
|
|
@@ -379,8 +381,6 @@ var useCopilotRuntimeClient = (options) => {
|
|
|
379
381
|
};
|
|
380
382
|
|
|
381
383
|
// src/hooks/use-chat.ts
|
|
382
|
-
var import_runtime_client_gql4 = require("@copilotkit/runtime-client-gql");
|
|
383
|
-
var import_shared3 = require("@copilotkit/shared");
|
|
384
384
|
function useChat(options) {
|
|
385
385
|
const {
|
|
386
386
|
messages,
|
|
@@ -429,7 +429,7 @@ function useChat(options) {
|
|
|
429
429
|
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
|
|
430
430
|
setIsLoading(true);
|
|
431
431
|
const interruptEvent = langGraphInterruptAction == null ? void 0 : langGraphInterruptAction.event;
|
|
432
|
-
if ((interruptEvent == null ? void 0 : interruptEvent.name) ===
|
|
432
|
+
if ((interruptEvent == null ? void 0 : interruptEvent.name) === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent && (interruptEvent == null ? void 0 : interruptEvent.value) && !(interruptEvent == null ? void 0 : interruptEvent.response) && agentSessionRef.current) {
|
|
433
433
|
addErrorToast([
|
|
434
434
|
new Error(
|
|
435
435
|
"A message was sent while interrupt is active. This will cause failure on the agent side"
|
|
@@ -523,16 +523,16 @@ function useChat(options) {
|
|
|
523
523
|
setExtensions(extensionsRef.current);
|
|
524
524
|
let rawMessagesResponse = value.generateCopilotResponse.messages;
|
|
525
525
|
((_i = (_h = value.generateCopilotResponse) == null ? void 0 : _h.metaEvents) != null ? _i : []).forEach((ev) => {
|
|
526
|
-
if (ev.name ===
|
|
526
|
+
if (ev.name === import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent) {
|
|
527
527
|
let eventValue = (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev).value;
|
|
528
|
-
eventValue = (0,
|
|
528
|
+
eventValue = (0, import_shared2.parseJson)(eventValue, eventValue);
|
|
529
529
|
setLangGraphInterruptAction({
|
|
530
530
|
event: __spreadProps(__spreadValues({}, (0, import_runtime_client_gql3.langGraphInterruptEvent)(ev)), {
|
|
531
531
|
value: eventValue
|
|
532
532
|
})
|
|
533
533
|
});
|
|
534
534
|
}
|
|
535
|
-
if (ev.name ===
|
|
535
|
+
if (ev.name === import_runtime_client_gql3.MetaEventName.CopilotKitLangGraphInterruptEvent) {
|
|
536
536
|
const data = ev.data;
|
|
537
537
|
rawMessagesResponse = [...rawMessagesResponse, ...data.messages];
|
|
538
538
|
interruptMessages = (0, import_runtime_client_gql3.convertGqlOutputToMessages)(
|
|
@@ -613,7 +613,7 @@ function useChat(options) {
|
|
|
613
613
|
setMessages([...previousMessages, ...newMessages]);
|
|
614
614
|
}
|
|
615
615
|
}
|
|
616
|
-
|
|
616
|
+
let finalMessages = constructFinalMessages(
|
|
617
617
|
[...syncedMessages, ...interruptMessages],
|
|
618
618
|
previousMessages,
|
|
619
619
|
newMessages
|
|
@@ -623,7 +623,7 @@ function useChat(options) {
|
|
|
623
623
|
const lastMessages = [];
|
|
624
624
|
for (let i = finalMessages.length - 1; i >= 0; i--) {
|
|
625
625
|
const message = finalMessages[i];
|
|
626
|
-
if (message.isActionExecutionMessage() && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
|
|
626
|
+
if ((message.isActionExecutionMessage() || message.isResultMessage()) && message.status.code !== import_runtime_client_gql3.MessageStatusCode.Pending) {
|
|
627
627
|
lastMessages.unshift(message);
|
|
628
628
|
} else {
|
|
629
629
|
break;
|
|
@@ -631,59 +631,51 @@ function useChat(options) {
|
|
|
631
631
|
}
|
|
632
632
|
for (const message of lastMessages) {
|
|
633
633
|
setMessages(finalMessages);
|
|
634
|
-
const action = actions.find(
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
"abort",
|
|
651
|
-
() => resolve("Operation was aborted by the user")
|
|
652
|
-
);
|
|
653
|
-
}
|
|
654
|
-
),
|
|
655
|
-
// if the user stopped generation, we also abort consecutive actions
|
|
656
|
-
new Promise((resolve) => {
|
|
657
|
-
var _a2;
|
|
658
|
-
if ((_a2 = chatAbortControllerRef.current) == null ? void 0 : _a2.signal.aborted) {
|
|
659
|
-
resolve("Operation was aborted by the user");
|
|
660
|
-
}
|
|
661
|
-
})
|
|
662
|
-
]);
|
|
663
|
-
} catch (e) {
|
|
664
|
-
error = e;
|
|
665
|
-
addErrorToast([error]);
|
|
666
|
-
result = `Failed to execute action ${message.name}. ${error.message}`;
|
|
667
|
-
console.error(`Failed to execute action ${message.name}: ${error}`);
|
|
668
|
-
}
|
|
634
|
+
const action = actions.find(
|
|
635
|
+
(action2) => action2.name === message.name
|
|
636
|
+
);
|
|
637
|
+
const currentResultMessagePairedFeAction = message.isResultMessage() ? getPairedFeAction(actions, message) : null;
|
|
638
|
+
const executeActionFromMessage = (action2, message2) => __async(this, null, function* () {
|
|
639
|
+
followUp = action2 == null ? void 0 : action2.followUp;
|
|
640
|
+
const resultMessage = yield executeAction({
|
|
641
|
+
onFunctionCall,
|
|
642
|
+
previousMessages,
|
|
643
|
+
message: message2,
|
|
644
|
+
chatAbortControllerRef,
|
|
645
|
+
onError: (error) => {
|
|
646
|
+
addErrorToast([error]);
|
|
647
|
+
console.error(`Failed to execute action ${message2.name}: ${error}`);
|
|
648
|
+
}
|
|
649
|
+
});
|
|
669
650
|
didExecuteAction = true;
|
|
670
|
-
const messageIndex = finalMessages.findIndex((msg) => msg.id ===
|
|
671
|
-
finalMessages.splice(
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
651
|
+
const messageIndex = finalMessages.findIndex((msg) => msg.id === message2.id);
|
|
652
|
+
finalMessages.splice(messageIndex + 1, 0, resultMessage);
|
|
653
|
+
return resultMessage;
|
|
654
|
+
});
|
|
655
|
+
if (action && message.isActionExecutionMessage()) {
|
|
656
|
+
const resultMessage = yield executeActionFromMessage(action, message);
|
|
657
|
+
const pairedFeAction = getPairedFeAction(actions, resultMessage);
|
|
658
|
+
if (pairedFeAction) {
|
|
659
|
+
const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
|
|
660
|
+
name: pairedFeAction.name,
|
|
661
|
+
arguments: (0, import_shared2.parseJson)(resultMessage.result, resultMessage.result),
|
|
662
|
+
status: message.status,
|
|
663
|
+
createdAt: message.createdAt,
|
|
664
|
+
parentMessageId: message.parentMessageId
|
|
665
|
+
});
|
|
666
|
+
yield executeActionFromMessage(pairedFeAction, newExecutionMessage);
|
|
667
|
+
}
|
|
668
|
+
} else if (message.isResultMessage() && currentResultMessagePairedFeAction) {
|
|
669
|
+
const newExecutionMessage = new import_runtime_client_gql3.ActionExecutionMessage({
|
|
670
|
+
name: currentResultMessagePairedFeAction.name,
|
|
671
|
+
arguments: (0, import_shared2.parseJson)(message.result, message.result),
|
|
672
|
+
status: message.status,
|
|
673
|
+
createdAt: message.createdAt
|
|
674
|
+
});
|
|
675
|
+
finalMessages.push(newExecutionMessage);
|
|
676
|
+
yield executeActionFromMessage(
|
|
677
|
+
currentResultMessagePairedFeAction,
|
|
678
|
+
newExecutionMessage
|
|
687
679
|
);
|
|
688
680
|
}
|
|
689
681
|
}
|
|
@@ -754,7 +746,7 @@ function useChat(options) {
|
|
|
754
746
|
if (!event)
|
|
755
747
|
return acc;
|
|
756
748
|
switch (event.name) {
|
|
757
|
-
case
|
|
749
|
+
case import_runtime_client_gql3.MetaEventName.LangGraphInterruptEvent:
|
|
758
750
|
if (event.response) {
|
|
759
751
|
setLangGraphInterruptAction(null);
|
|
760
752
|
const value = event.value;
|
|
@@ -830,11 +822,72 @@ function constructFinalMessages(syncedMessages, previousMessages, newMessages) {
|
|
|
830
822
|
}
|
|
831
823
|
return finalMessages;
|
|
832
824
|
}
|
|
825
|
+
function executeAction(_0) {
|
|
826
|
+
return __async(this, arguments, function* ({
|
|
827
|
+
onFunctionCall,
|
|
828
|
+
previousMessages,
|
|
829
|
+
message,
|
|
830
|
+
chatAbortControllerRef,
|
|
831
|
+
onError
|
|
832
|
+
}) {
|
|
833
|
+
let result;
|
|
834
|
+
let error = null;
|
|
835
|
+
try {
|
|
836
|
+
result = yield Promise.race([
|
|
837
|
+
onFunctionCall({
|
|
838
|
+
messages: previousMessages,
|
|
839
|
+
name: message.name,
|
|
840
|
+
args: message.arguments
|
|
841
|
+
}),
|
|
842
|
+
new Promise(
|
|
843
|
+
(resolve) => {
|
|
844
|
+
var _a;
|
|
845
|
+
return (_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.addEventListener(
|
|
846
|
+
"abort",
|
|
847
|
+
() => resolve("Operation was aborted by the user")
|
|
848
|
+
);
|
|
849
|
+
}
|
|
850
|
+
),
|
|
851
|
+
// if the user stopped generation, we also abort consecutive actions
|
|
852
|
+
new Promise((resolve) => {
|
|
853
|
+
var _a;
|
|
854
|
+
if ((_a = chatAbortControllerRef.current) == null ? void 0 : _a.signal.aborted) {
|
|
855
|
+
resolve("Operation was aborted by the user");
|
|
856
|
+
}
|
|
857
|
+
})
|
|
858
|
+
]);
|
|
859
|
+
} catch (e) {
|
|
860
|
+
onError(e);
|
|
861
|
+
}
|
|
862
|
+
return new import_runtime_client_gql3.ResultMessage({
|
|
863
|
+
id: "result-" + message.id,
|
|
864
|
+
result: import_runtime_client_gql3.ResultMessage.encodeResult(
|
|
865
|
+
error ? {
|
|
866
|
+
content: result,
|
|
867
|
+
error: JSON.parse(JSON.stringify(error, Object.getOwnPropertyNames(error)))
|
|
868
|
+
} : result
|
|
869
|
+
),
|
|
870
|
+
actionExecutionId: message.id,
|
|
871
|
+
actionName: message.name
|
|
872
|
+
});
|
|
873
|
+
});
|
|
874
|
+
}
|
|
875
|
+
function getPairedFeAction(actions, message) {
|
|
876
|
+
let actionName = null;
|
|
877
|
+
if (message.isActionExecutionMessage()) {
|
|
878
|
+
actionName = message.name;
|
|
879
|
+
} else if (message.isResultMessage()) {
|
|
880
|
+
actionName = message.actionName;
|
|
881
|
+
}
|
|
882
|
+
return actions.find(
|
|
883
|
+
(action) => action.name === actionName && action.available === "frontend" || action.pairedAction === actionName
|
|
884
|
+
);
|
|
885
|
+
}
|
|
833
886
|
|
|
834
887
|
// src/components/copilot-provider/copilotkit.tsx
|
|
835
888
|
var import_react7 = require("react");
|
|
836
889
|
var import_react_dom = require("react-dom");
|
|
837
|
-
var
|
|
890
|
+
var import_shared3 = require("@copilotkit/shared");
|
|
838
891
|
var import_jsx_runtime4 = require("react/jsx-runtime");
|
|
839
892
|
var defaultCopilotContextCategories = ["global"];
|
|
840
893
|
|
|
@@ -881,9 +934,9 @@ function useCopilotChat(_a = {}) {
|
|
|
881
934
|
const makeSystemMessageCallback = (0, import_react8.useCallback)(() => {
|
|
882
935
|
const systemMessageMaker = makeSystemMessage || defaultSystemMessage;
|
|
883
936
|
const contextString = latestGetContextString.current([], defaultCopilotContextCategories);
|
|
884
|
-
return new
|
|
937
|
+
return new import_runtime_client_gql4.TextMessage({
|
|
885
938
|
content: systemMessageMaker(contextString, chatInstructions),
|
|
886
|
-
role:
|
|
939
|
+
role: import_runtime_client_gql4.Role.System
|
|
887
940
|
});
|
|
888
941
|
}, [getContextString, makeSystemMessage, chatInstructions]);
|
|
889
942
|
const onCoAgentStateRender = useAsyncCallback(
|
|
@@ -1035,7 +1088,7 @@ ${additionalInstructions}` : "");
|
|
|
1035
1088
|
}
|
|
1036
1089
|
|
|
1037
1090
|
// src/hooks/use-coagent.ts
|
|
1038
|
-
var
|
|
1091
|
+
var import_shared4 = require("@copilotkit/shared");
|
|
1039
1092
|
function useCoAgent(options) {
|
|
1040
1093
|
const generalContext = useCopilotContext();
|
|
1041
1094
|
const { availableAgents } = generalContext;
|
|
@@ -1086,7 +1139,7 @@ function useCoAgent(options) {
|
|
|
1086
1139
|
if (((_d = (_c = result.data) == null ? void 0 : _c.loadAgentState) == null ? void 0 : _d.threadExists) && newState && newState != "{}") {
|
|
1087
1140
|
lastLoadedState.current = newState;
|
|
1088
1141
|
lastLoadedThreadId.current = threadId;
|
|
1089
|
-
const fetchedState = (0,
|
|
1142
|
+
const fetchedState = (0, import_shared4.parseJson)(newState, {});
|
|
1090
1143
|
isExternalStateManagement(options) ? options.setState(fetchedState) : setState(fetchedState);
|
|
1091
1144
|
}
|
|
1092
1145
|
});
|