@copilotkit/react-core
Version:
<img src="https://github.com/user-attachments/assets/0a6b64d9-e193-4940-a3f6-60334ac34084" alt="banner" style="border-radius: 12px; border: 2px solid #d6d4fa;" />
1 lines • 14.5 kB
Source Map (JSON)
{"version":3,"sources":["../src/hooks/use-coagent-state-render-bridge.tsx"],"sourcesContent":["import { ReactCustomMessageRendererPosition, useAgent } from \"@copilotkitnext/react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { AgentSubscriber } from \"@ag-ui/client\";\nimport { useCoAgentStateRenders } from \"../context\";\nimport { dataToUUID, parseJson } from \"@copilotkit/shared\";\n\nfunction getStateWithoutConstantKeys(state: any) {\n if (!state) return {};\n const { messages, tools, copilotkit, ...stateWithoutConstantKeys } = state;\n return stateWithoutConstantKeys;\n}\n\n// Function that compares states, without the constant keys\nfunction areStatesEquals(a: any, b: any) {\n if ((a && !b) || (!a && b)) return false;\n const { messages, tools, copilotkit, ...aWithoutConstantKeys } = a;\n const {\n messages: bMessages,\n tools: bTools,\n copilotkit: bCopilotkit,\n ...bWithoutConstantKeys\n } = b;\n\n return JSON.stringify(aWithoutConstantKeys) === JSON.stringify(bWithoutConstantKeys);\n}\n\n/**\n * Bridge hook that connects agent state renders to chat messages.\n *\n * ## Purpose\n * This hook finds matching state render configurations (registered via useCoAgentStateRender)\n * and returns UI to render in chat.\n * It ensures each state render appears bound to a specific message, preventing duplicates while\n * allowing re-binding when the underlying state changes significantly.\n *\n * ## Message-ID-Based Claiming System\n *\n * ### The Problem\n * Multiple bridge component instances render simultaneously (one per message). Without coordination,\n * they would all try to render the same state render, causing duplicates.\n *\n * ### The Solution: Message-ID Claims with State Comparison\n * Each state render is \"claimed\" by exactly one **message ID** (not runId):\n *\n * **Claim Structure**: `claimsRef.current[messageId] = { stateRenderId, runId, stateSnapshot, locked }`\n *\n * **Primary binding is by messageId because**:\n * - runId is not always available immediately (starts as \"pending\")\n * - messageId is the stable identifier throughout the message lifecycle\n * - Claims persist across component remounts via context ref\n *\n * ### Claiming Logic Flow\n *\n * 1. **Message already has a claim**:\n * - Check if the claim matches the current stateRenderId\n * - If yes → render (this message owns this render)\n * - Update runId if it was \"pending\" and now available\n *\n * 2. **State render claimed by another message**:\n * - Compare state snapshots (ignoring constant keys: messages, tools, copilotkit)\n * - If states are identical → block rendering (duplicate)\n * - **If states are different → allow claiming** (new data, new message)\n * - This handles cases where the same render type shows different states in different messages\n *\n * 3. **Unclaimed state render**:\n * - Only allow claiming if runId is \"pending\" (initial render)\n * - If runId is real but no claim exists → block (edge case protection)\n * - Create new claim: `claimsRef.current[messageId] = { stateRenderId, runId }`\n *\n * ### State Snapshot Locking\n *\n * Once a state snapshot is captured and locked for a message:\n * - The UI always renders with the locked snapshot (not live agent.state)\n * - Prevents UI from appearing \"wiped\" during state transitions\n * - Locked when: stateSnapshot prop is available (from message persistence)\n * - Unlocked state: can still update from live agent.state\n *\n * ### Synchronous Claiming (Ref-based)\n *\n * Claims are stored in a context-level ref (not React state):\n * - Multiple bridges render in the same tick\n * - State updates are async - would allow duplicates before update completes\n * - Ref provides immediate, synchronous claim checking\n * - Survives component remounts (stored in context, not component)\n *\n * ## Flow Example\n *\n * ```\n * Time 1: Message A renders, runId=undefined, state={progress: 50%}\n * → effectiveRunId = \"pending\"\n * → Claims: claimsRef[\"msgA\"] = { stateRenderId: \"tasks\", runId: \"pending\", stateSnapshot: {progress: 50%} }\n * → Renders UI with 50% progress\n *\n * Time 2: Message B renders, runId=undefined, same state\n * → Checks: \"tasks\" already claimed by msgA with same state\n * → Returns null (blocked - duplicate)\n *\n * Time 3: Real runId appears (e.g., \"run-123\")\n * → Updates claim: claimsRef[\"msgA\"].runId = \"run-123\"\n * → Message A continues rendering\n *\n * Time 4: Agent processes more, state={progress: 100%}\n * → Message A: locked to 50% (stateSnapshot locked)\n * → Message C renders with state={progress: 100%}\n * → Checks: \"tasks\" claimed by msgA but state is DIFFERENT (50% vs 100%)\n * → Allows new claim: claimsRef[\"msgC\"] = { stateRenderId: \"tasks\", runId: \"run-123\", stateSnapshot: {progress: 100%} }\n * → Both messages render independently with their own snapshots\n * ```\n */\nexport interface CoAgentStateRenderBridgeProps {\n message: any;\n position: ReactCustomMessageRendererPosition;\n runId: string;\n messageIndex: number;\n messageIndexInRun: number;\n numberOfMessagesInRun: number;\n agentId: string;\n stateSnapshot: any;\n}\n\nexport function useCoagentStateRenderBridge(agentId: string, props: CoAgentStateRenderBridgeProps) {\n const { stateSnapshot, messageIndexInRun, message } = props;\n const { coAgentStateRenders, claimsRef } = useCoAgentStateRenders();\n const { agent } = useAgent({ agentId });\n const [nodeName, setNodeName] = useState<string | undefined>(undefined);\n\n const runId = props.runId ?? message.runId;\n const effectiveRunId = runId || \"pending\";\n\n useEffect(() => {\n if (!agent) return;\n const subscriber: AgentSubscriber = {\n onStepStartedEvent: ({ event }) => {\n if (event.stepName !== nodeName) {\n setNodeName(event.stepName);\n }\n },\n onStepFinishedEvent: ({ event }) => {\n if (event.stepName === nodeName) {\n setNodeName(undefined);\n }\n },\n };\n\n const { unsubscribe } = agent.subscribe(subscriber);\n return () => {\n unsubscribe();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [agentId, nodeName]);\n\n const getStateRender = useCallback(\n (messageId: string) => {\n return Object.entries(coAgentStateRenders).find(([stateRenderId, stateRender]) => {\n if (claimsRef.current[messageId]) {\n return stateRenderId === claimsRef.current[messageId].stateRenderId;\n }\n const matchingAgentName = stateRender.name === agentId;\n const matchesNodeContext = stateRender.nodeName ? stateRender.nodeName === nodeName : true;\n return matchingAgentName && matchesNodeContext;\n });\n },\n [coAgentStateRenders, nodeName, agentId],\n );\n\n // Message ID-based claim system - A state render can only be claimed by one message ID\n const handleRenderRequest = ({\n stateRenderId,\n messageId,\n runId,\n stateSnapshot: renderSnapshot,\n }: {\n stateRenderId: string;\n messageId: string;\n runId?: string;\n stateSnapshot?: any;\n }): boolean => {\n // Check if this message has already claimed this state render\n if (claimsRef.current[messageId]) {\n const canRender = claimsRef.current[messageId].stateRenderId === stateRenderId;\n\n // Update runId if it doesn't exist\n if (\n canRender &&\n runId &&\n (!claimsRef.current[messageId].runId || claimsRef.current[messageId].runId === \"pending\")\n ) {\n claimsRef.current[messageId].runId = runId;\n }\n\n return canRender;\n }\n\n // Do not allow render if any other message has claimed this state render\n const renderClaimedByOtherMessage = Object.values(claimsRef.current).find(\n (c) =>\n c.stateRenderId === stateRenderId &&\n dataToUUID(getStateWithoutConstantKeys(c.stateSnapshot)) ===\n dataToUUID(getStateWithoutConstantKeys(renderSnapshot)),\n );\n if (renderClaimedByOtherMessage) {\n // If:\n // - state render already claimed\n // - snapshot exists in the claiming object and is different from current,\n if (\n renderSnapshot &&\n renderClaimedByOtherMessage.stateSnapshot &&\n !areStatesEquals(renderClaimedByOtherMessage.stateSnapshot, renderSnapshot)\n ) {\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n }\n return false;\n }\n\n // No existing claim anywhere yet – allow this message to claim even if we already know the runId.\n if (!runId) {\n return false;\n }\n\n claimsRef.current[messageId] = { stateRenderId, runId };\n return true;\n };\n\n return useMemo(() => {\n if (messageIndexInRun !== 0) {\n return null;\n }\n\n const [stateRenderId, stateRender] = getStateRender(message.id) ?? [];\n\n if (!stateRender || !stateRenderId) {\n return null;\n }\n\n // Is there any state we can use?\n const snapshot = stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : agent?.state;\n\n // Synchronously check/claim - returns true if this message can render\n const canRender = handleRenderRequest({\n stateRenderId,\n messageId: message.id,\n runId: effectiveRunId,\n stateSnapshot: snapshot,\n });\n if (!canRender) {\n return null;\n }\n\n // If we found state, and given that now there's a claim for the current message, let's save it in the claim\n if (snapshot && !claimsRef.current[message.id].locked) {\n if (stateSnapshot) {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n claimsRef.current[message.id].locked = true;\n } else {\n claimsRef.current[message.id].stateSnapshot = snapshot;\n }\n }\n\n if (stateRender.handler) {\n stateRender.handler({\n state: stateSnapshot ? parseJson(stateSnapshot, stateSnapshot) : (agent?.state ?? {}),\n nodeName: nodeName ?? \"\",\n });\n }\n\n if (stateRender.render) {\n const status = agent?.isRunning ? \"inProgress\" : \"complete\";\n\n if (typeof stateRender.render === \"string\") return stateRender.render;\n\n return stateRender.render({\n status,\n // Always use state from claim, to make sure the state does not seem \"wiped\" for a fraction of a second\n state: claimsRef.current[message.id].stateSnapshot ?? {},\n nodeName: nodeName ?? \"\",\n });\n }\n }, [\n getStateRender,\n stateSnapshot,\n agent?.state,\n agent?.isRunning,\n nodeName,\n effectiveRunId,\n message.id,\n messageIndexInRun,\n ]);\n}\n\nexport function CoAgentStateRenderBridge(props: CoAgentStateRenderBridgeProps) {\n return useCoagentStateRenderBridge(props.agentId, props);\n}\n"],"mappings":";;;;;;;;AAAA,SAA6C,gBAAgB;AAC7D,SAAS,aAAa,WAAW,SAAS,gBAAgB;AAG1D,SAAS,YAAY,iBAAiB;AAEtC,SAAS,4BAA4B,OAAY;AAC/C,MAAI,CAAC;AAAO,WAAO,CAAC;AACpB,QAAqE,YAA7D,YAAU,OAAO,WAR3B,IAQuE,IAA7B,qCAA6B,IAA7B,CAAhC,YAAU,SAAO;AACzB,SAAO;AACT;AAGA,SAAS,gBAAgB,GAAQ,GAAQ;AACvC,MAAK,KAAK,CAAC,KAAO,CAAC,KAAK;AAAI,WAAO;AACnC,QAAiE,QAAzD,YAAU,OAAO,WAf3B,IAemE,IAAzB,iCAAyB,IAAzB,CAAhC,YAAU,SAAO;AACzB,QAKI,QAJF;AAAA,cAAU;AAAA,IACV,OAAO;AAAA,IACP,YAAY;AAAA,EAnBhB,IAqBM,IADC,iCACD,IADC;AAAA,IAHH;AAAA,IACA;AAAA,IACA;AAAA;AAIF,SAAO,KAAK,UAAU,oBAAoB,MAAM,KAAK,UAAU,oBAAoB;AACrF;AAgGO,SAAS,4BAA4B,SAAiB,OAAsC;AAxHnG;AAyHE,QAAM,EAAE,eAAe,mBAAmB,QAAQ,IAAI;AACtD,QAAM,EAAE,qBAAqB,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