@copilotkit/react-core 1.51.4-next.1 → 1.51.4-next.3

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 CHANGED
@@ -1,5 +1,25 @@
1
1
  # ui
2
2
 
3
+ ## 1.51.4-next.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 6b9c60e: fix: add dependencies to fix stale state of regenerate method
8
+ - Updated dependencies [a3090d5]
9
+ - @copilotkitnext/react@1.51.4-next.3
10
+ - @copilotkit/runtime-client-gql@1.51.4-next.3
11
+ - @copilotkit/shared@1.51.4-next.3
12
+ - @copilotkitnext/core@1.51.4-next.3
13
+
14
+ ## 1.51.4-next.2
15
+
16
+ ### Patch Changes
17
+
18
+ - @copilotkit/runtime-client-gql@1.51.4-next.2
19
+ - @copilotkit/shared@1.51.4-next.2
20
+ - @copilotkitnext/core@1.51.4-next.2
21
+ - @copilotkitnext/react@1.51.4-next.2
22
+
3
23
  ## 1.51.4-next.1
4
24
 
5
25
  ### Patch Changes
@@ -93,8 +93,10 @@ function useCopilotChatInternal({
93
93
  const reload = useAsyncCallback(
94
94
  (reloadMessageId) => __async(this, null, function* () {
95
95
  var _a2;
96
+ if (!agent)
97
+ return;
96
98
  const messages = (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : [];
97
- const isLoading = false;
99
+ const isLoading = agent.isRunning;
98
100
  if (isLoading || messages.length === 0) {
99
101
  return;
100
102
  }
@@ -132,7 +134,7 @@ function useCopilotChatInternal({
132
134
  }
133
135
  return;
134
136
  }),
135
- [agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
137
+ [agent == null ? void 0 : agent.messages.length, agent == null ? void 0 : agent.isRunning, agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
136
138
  );
137
139
  const latestSendMessageFunc = useAsyncCallback(
138
140
  (message, options) => __async(this, null, function* () {
@@ -403,4 +405,4 @@ export {
403
405
  useCopilotChatInternal,
404
406
  defaultSystemMessage
405
407
  };
406
- //# sourceMappingURL=chunk-LO4RRITI.mjs.map
408
+ //# sourceMappingURL=chunk-KNJHRVKW.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/use-copilot-chat_internal.ts"],"sourcesContent":["import { useRef, useEffect, useCallback, useMemo, useState, createElement } from \"react\";\nimport { useCopilotContext } from \"../context/copilot-context\";\nimport { SystemMessageFunction } from \"../types\";\nimport { useAsyncCallback } from \"../components/error-boundary/error-utils\";\nimport { Message } from \"@copilotkit/shared\";\nimport { gqlToAGUI, Message as DeprecatedGqlMessage } from \"@copilotkit/runtime-client-gql\";\nimport { useLangGraphInterruptRender } from \"./use-langgraph-interrupt-render\";\nimport {\n useAgent,\n useCopilotChatConfiguration,\n useCopilotKit,\n useRenderCustomMessages,\n useSuggestions,\n} from \"@copilotkitnext/react\";\nimport { Suggestion } from \"@copilotkitnext/core\";\nimport { useLazyToolRenderer } from \"./use-lazy-tool-renderer\";\nimport { AbstractAgent, AGUIConnectNotImplementedError } from \"@ag-ui/client\";\nimport {\n CoAgentStateRenderBridge,\n type CoAgentStateRenderBridgeProps,\n} from \"./use-coagent-state-render-bridge\";\n\n/**\n * The type of suggestions to use in the chat.\n *\n * `auto` - Suggestions are generated automatically.\n * `manual` - Suggestions are controlled programmatically.\n * `SuggestionItem[]` - Static suggestions array.\n */\nexport type ChatSuggestions = \"auto\" | \"manual\" | Omit<Suggestion, \"isLoading\">[];\n\nexport interface AppendMessageOptions {\n /**\n * Whether to run the chat completion after appending the message. Defaults to `true`.\n */\n followUp?: boolean;\n /**\n * Whether to clear the suggestions after appending the message. Defaults to `true`.\n */\n clearSuggestions?: boolean;\n}\n\nexport interface OnStopGenerationArguments {\n /**\n * The name of the currently executing agent.\n */\n currentAgentName: string | undefined;\n\n /**\n * The messages in the chat.\n */\n messages: Message[];\n}\n\nexport type OnReloadMessagesArguments = OnStopGenerationArguments & {\n /**\n * The message on which \"regenerate\" was pressed\n */\n messageId: string;\n};\n\nexport type OnStopGeneration = (args: OnStopGenerationArguments) => void;\n\nexport type OnReloadMessages = (args: OnReloadMessagesArguments) => void;\n\nexport interface UseCopilotChatOptions {\n /**\n * A unique identifier for the chat. If not provided, a random one will be\n * generated. When provided, the `useChat` hook with the same `id` will\n * have shared states across components.\n */\n id?: string;\n\n /**\n * HTTP headers to be sent with the API request.\n */\n headers?: Record<string, string> | Headers;\n\n /**\n * Initial messages to populate the chat with.\n */\n initialMessages?: Message[];\n\n /**\n * A function to generate the system message. Defaults to `defaultSystemMessage`.\n */\n makeSystemMessage?: SystemMessageFunction;\n\n /**\n * Disables inclusion of CopilotKit’s default system message. When true, no system message is sent (this also suppresses any custom message from <code>makeSystemMessage</code>).\n */\n disableSystemMessage?: boolean;\n /**\n * Controls the behavior of suggestions in the chat interface.\n *\n * `auto` (default) - Suggestions are generated automatically:\n * - When the chat is first opened (empty state)\n * - After each message exchange completes\n * - Uses configuration from `useCopilotChatSuggestions` hooks\n *\n * `manual` - Suggestions are controlled programmatically:\n * - Use `setSuggestions()` to set custom suggestions\n * - Use `generateSuggestions()` to trigger AI generation\n * - Access via `useCopilotChat` hook\n *\n * `SuggestionItem[]` - Static suggestions array:\n * - Always shows the same suggestions\n * - No AI generation involved\n */\n suggestions?: ChatSuggestions;\n\n onInProgress?: (isLoading: boolean) => void;\n onSubmitMessage?: (messageContent: string) => Promise<void> | void;\n onStopGeneration?: OnStopGeneration;\n onReloadMessages?: OnReloadMessages;\n}\n\nexport interface MCPServerConfig {\n endpoint: string;\n apiKey?: string;\n}\n\n// Old suggestion item interface, for returning from useCopilotChatInternal\ninterface SuggestionItem {\n title: string;\n message: string;\n partial?: boolean;\n className?: string;\n}\n\nexport interface UseCopilotChatReturn {\n /**\n * @deprecated use `messages` instead, this is an old non ag-ui version of the messages\n * Array of messages currently visible in the chat interface\n *\n * This is the visible messages, not the raw messages from the runtime client.\n */\n visibleMessages: DeprecatedGqlMessage[];\n\n /**\n * The messages that are currently in the chat in AG-UI format.\n */\n messages: Message[];\n\n /** @deprecated use `sendMessage` in `useCopilotChatHeadless_c` instead. This will be removed in a future major version. */\n appendMessage: (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Send a new message to the chat\n *\n * ```tsx\n * await sendMessage({\n * id: \"123\",\n * role: \"user\",\n * content: \"Hello, process this request\",\n * });\n * ```\n */\n sendMessage: (message: Message, options?: AppendMessageOptions) => Promise<void>;\n\n /**\n * Replace all messages in the chat\n *\n * ```tsx\n * setMessages([\n * { id: \"123\", role: \"user\", content: \"Hello, process this request\" },\n * { id: \"456\", role: \"assistant\", content: \"Hello, I'm the assistant\" },\n * ]);\n * ```\n *\n * **Deprecated** non-ag-ui version:\n *\n * ```tsx\n * setMessages([\n * new TextMessage({\n * content: \"Hello, process this request\",\n * role: gqlRole.User,\n * }),\n * new TextMessage({\n * content: \"Hello, I'm the assistant\",\n * role: gqlRole.Assistant,\n * ]);\n * ```\n *\n */\n setMessages: (messages: Message[] | DeprecatedGqlMessage[]) => void;\n\n /**\n * Remove a specific message by ID\n *\n * ```tsx\n * deleteMessage(\"123\");\n * ```\n */\n deleteMessage: (messageId: string) => void;\n\n /**\n * Regenerate the response for a specific message\n *\n * ```tsx\n * reloadMessages(\"123\");\n * ```\n */\n reloadMessages: (messageId: string) => Promise<void>;\n\n /**\n * Stop the current message generation\n *\n * ```tsx\n * if (isLoading) {\n * stopGeneration();\n * }\n * ```\n */\n stopGeneration: () => void;\n\n /**\n * Clear all messages and reset chat state\n *\n * ```tsx\n * reset();\n * console.log(messages); // []\n * ```\n */\n reset: () => void;\n\n /**\n * Whether the chat is currently generating a response\n *\n * ```tsx\n * if (isLoading) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isLoading: boolean;\n\n /**\n * Whether the chat agent is available to generate responses\n *\n * ```tsx\n * if (isAvailable) {\n * console.log(\"Loading...\");\n * } else {\n * console.log(\"Not loading\");\n * }\n */\n isAvailable: boolean;\n\n /** Manually trigger chat completion (advanced usage) */\n runChatCompletion: () => Promise<Message[]>;\n\n /** MCP (Model Context Protocol) server configurations */\n mcpServers: MCPServerConfig[];\n\n /** Update MCP server configurations */\n setMcpServers: (mcpServers: MCPServerConfig[]) => void;\n\n /**\n * Current suggestions array\n * Use this to read the current suggestions or in conjunction with setSuggestions for manual control\n */\n suggestions: Suggestion[];\n\n /**\n * Manually set suggestions\n * Useful for manual mode or custom suggestion workflows\n */\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) => void;\n\n /**\n * Trigger AI-powered suggestion generation\n * Uses configurations from useCopilotChatSuggestions hooks\n * Respects global debouncing - only one generation can run at a time\n *\n * ```tsx\n * generateSuggestions();\n * console.log(suggestions); // [suggestion1, suggestion2, suggestion3]\n * ```\n */\n generateSuggestions: () => Promise<void>;\n\n /**\n * Clear all current suggestions\n * Also resets suggestion generation state\n */\n resetSuggestions: () => void;\n\n /** Whether suggestions are currently being generated */\n isLoadingSuggestions: boolean;\n\n /** Interrupt content for human-in-the-loop workflows */\n interrupt: string | React.ReactElement | null;\n\n agent?: ReturnType<typeof useAgent>[\"agent\"];\n\n threadId?: string;\n}\n\nexport function useCopilotChatInternal({\n suggestions,\n onInProgress,\n onSubmitMessage,\n onStopGeneration,\n onReloadMessages,\n}: UseCopilotChatOptions = {}): UseCopilotChatReturn {\n const { copilotkit } = useCopilotKit();\n const { threadId, agentSession } = useCopilotContext();\n const existingConfig = useCopilotChatConfiguration();\n const [agentAvailable, setAgentAvailable] = useState(false);\n\n // Apply priority: props > existing config > defaults\n const resolvedAgentId = existingConfig?.agentId ?? \"default\";\n const { agent } = useAgent({ agentId: resolvedAgentId });\n\n useEffect(() => {\n const connect = async (agent: AbstractAgent) => {\n setAgentAvailable(false);\n try {\n await copilotkit.connectAgent({ agent });\n setAgentAvailable(true);\n } catch (error) {\n if (error instanceof AGUIConnectNotImplementedError) {\n // connect not implemented, ignore\n } else {\n console.error(\"CopilotChat: connectAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n };\n if (agent && existingConfig?.threadId && agent.threadId !== existingConfig.threadId) {\n agent.threadId = existingConfig.threadId;\n connect(agent);\n }\n return () => {};\n }, [existingConfig?.threadId, agent, copilotkit, resolvedAgentId]);\n\n useEffect(() => {\n onInProgress?.(Boolean(agent?.isRunning));\n }, [agent?.isRunning, onInProgress]);\n\n const interrupt = useLangGraphInterruptRender(agent);\n\n const reset = () => {\n agent?.setMessages([]);\n agent?.setState(null);\n };\n\n const deleteMessage = useCallback(\n (messageId: string) => {\n const filteredMessages = (agent?.messages ?? []).filter(\n (message) => message.id !== messageId,\n );\n agent?.setMessages(filteredMessages);\n },\n [agent?.setMessages, agent?.messages],\n );\n\n const latestDelete = useUpdatedRef(deleteMessage);\n const latestDeleteFunc = useCallback(\n (messageId: string) => {\n return latestDelete.current(messageId);\n },\n [latestDelete],\n );\n\n const currentSuggestions = useSuggestions({ agentId: resolvedAgentId });\n\n const reload = useAsyncCallback(\n async (reloadMessageId: string): Promise<void> => {\n if (!agent) return;\n const messages = agent?.messages ?? [];\n const isLoading = agent.isRunning;\n if (isLoading || messages.length === 0) {\n return;\n }\n\n const reloadMessageIndex = messages.findIndex((msg) => msg.id === reloadMessageId);\n if (reloadMessageIndex === -1) {\n console.warn(`Message with id ${reloadMessageId} not found`);\n return;\n }\n\n const reloadMessageRole = messages[reloadMessageIndex].role;\n if (reloadMessageRole !== \"assistant\") {\n console.warn(`Regenerate cannot be performed on ${reloadMessageRole} role`);\n return;\n }\n let historyCutoff: Message[] = [messages[0]];\n\n if (messages.length > 2 && reloadMessageIndex !== 0) {\n // message to regenerate from is now first.\n // Work backwards to find the first the closest user message\n const lastUserMessageBeforeRegenerate = messages\n .slice(0, reloadMessageIndex)\n .reverse()\n .find((msg) => msg.role === \"user\");\n\n if (!lastUserMessageBeforeRegenerate) {\n historyCutoff = [messages[0]];\n } else {\n const indexOfLastUserMessageBeforeRegenerate = messages.findIndex(\n (msg) => msg.id === lastUserMessageBeforeRegenerate.id,\n );\n // Include the user message, remove everything after it\n historyCutoff = messages.slice(0, indexOfLastUserMessageBeforeRegenerate + 1);\n }\n } else if (messages.length > 2 && reloadMessageIndex === 0) {\n historyCutoff = [messages[0], messages[1]];\n }\n\n agent?.setMessages(historyCutoff);\n\n if (agent) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed during reload\", error);\n // Error will be reported through subscription\n }\n }\n return;\n },\n [agent?.messages.length, agent?.isRunning ,agent?.setMessages, copilotkit?.runAgent],\n );\n\n const latestSendMessageFunc = useAsyncCallback(\n async (message: Message, options?: AppendMessageOptions) => {\n if (!agent) return;\n const followUp = options?.followUp ?? true;\n if (options?.clearSuggestions) {\n copilotkit.clearSuggestions(resolvedAgentId);\n }\n\n // Call onSubmitMessage BEFORE adding message and running agent\n // This allows users to perform actions (e.g., open chat window) before agent starts processing\n if (onSubmitMessage) {\n const content =\n typeof message.content === \"string\"\n ? message.content\n : message.content && \"text\" in message.content\n ? message.content.text\n : message.content && \"filename\" in message.content\n ? message.content.filename\n : \"\";\n try {\n await onSubmitMessage(content);\n } catch (error) {\n console.error(\"Error in onSubmitMessage:\", error);\n }\n }\n\n agent?.addMessage(message);\n if (followUp) {\n try {\n await copilotkit.runAgent({ agent });\n } catch (error) {\n console.error(\"CopilotChat: runAgent failed\", error);\n // Error will be reported through subscription\n }\n }\n },\n [agent, copilotkit, resolvedAgentId, onSubmitMessage],\n );\n\n const latestAppendFunc = useAsyncCallback(\n async (message: DeprecatedGqlMessage, options?: AppendMessageOptions) => {\n return latestSendMessageFunc(gqlToAGUI([message])[0], options);\n },\n [latestSendMessageFunc],\n );\n\n const latestSetMessagesFunc = useCallback(\n (messages: Message[] | DeprecatedGqlMessage[]) => {\n if (messages.every((message) => message instanceof DeprecatedGqlMessage)) {\n return agent?.setMessages?.(gqlToAGUI(messages));\n }\n return agent?.setMessages?.(messages);\n },\n [agent?.setMessages, agent],\n );\n\n const latestReload = useUpdatedRef(reload);\n const latestReloadFunc = useAsyncCallback(\n async (messageId: string) => {\n onReloadMessages?.({\n messageId,\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return await latestReload.current(messageId);\n },\n [latestReload, agent, onReloadMessages],\n );\n\n const latestStopFunc = useCallback(() => {\n onStopGeneration?.({\n currentAgentName: agent?.agentId,\n messages: agent?.messages ?? [],\n });\n return agent?.abortRun?.();\n }, [onStopGeneration, agent]);\n\n const latestReset = useUpdatedRef(reset);\n const latestResetFunc = useCallback(() => {\n return latestReset.current();\n }, [latestReset]);\n\n const lazyToolRendered = useLazyToolRenderer();\n const renderCustomMessage = useRenderCustomMessages();\n const legacyCustomMessageRenderer = useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId: resolvedAgentId,\n threadId: existingConfig?.threadId ?? threadId,\n });\n const allMessages = agent?.messages ?? [];\n const resolvedMessages = useMemo(() => {\n let processedMessages = allMessages.map((message) => {\n if (message.role !== \"assistant\") {\n return message;\n }\n\n const lazyRendered = lazyToolRendered(message, allMessages);\n if (lazyRendered) {\n const renderedGenUi = lazyRendered();\n if (renderedGenUi) {\n return { ...message, generativeUI: () => renderedGenUi };\n }\n }\n\n const bridgeRenderer =\n legacyCustomMessageRenderer || renderCustomMessage\n ? () => {\n if (legacyCustomMessageRenderer) {\n return legacyCustomMessageRenderer({ message, position: \"before\" });\n }\n try {\n return renderCustomMessage?.({ message, position: \"before\" }) ?? null;\n } catch (error) {\n console.warn(\n \"[CopilotKit] renderCustomMessages failed, falling back to legacy renderer\",\n error,\n );\n return null;\n }\n }\n : null;\n\n if (bridgeRenderer) {\n // Attach a position so react-ui can render the custom UI above the assistant content.\n return {\n ...message,\n generativeUI: bridgeRenderer,\n generativeUIPosition: \"before\" as const,\n };\n }\n return message;\n });\n\n const hasAssistantMessages = processedMessages.some((msg) => msg.role === \"assistant\");\n const canUseCustomRenderer = Boolean(\n renderCustomMessage && copilotkit?.getAgent?.(resolvedAgentId),\n );\n const placeholderRenderer = legacyCustomMessageRenderer\n ? legacyCustomMessageRenderer\n : canUseCustomRenderer\n ? renderCustomMessage\n : null;\n\n const shouldRenderPlaceholder =\n Boolean(agent?.isRunning) || Boolean(agent?.state && Object.keys(agent.state).length);\n\n const effectiveThreadId = threadId ?? agent?.threadId ?? \"default\";\n let latestUserIndex = -1;\n for (let i = processedMessages.length - 1; i >= 0; i -= 1) {\n if (processedMessages[i].role === \"user\") {\n latestUserIndex = i;\n break;\n }\n }\n const latestUserMessageId =\n latestUserIndex >= 0 ? processedMessages[latestUserIndex].id : undefined;\n const currentRunId = latestUserMessageId\n ? copilotkit.getRunIdForMessage(resolvedAgentId, effectiveThreadId, latestUserMessageId) ||\n `pending:${latestUserMessageId}`\n : undefined;\n const hasAssistantForCurrentRun =\n latestUserIndex >= 0\n ? processedMessages\n .slice(latestUserIndex + 1)\n .some((msg) => msg.role === \"assistant\")\n : hasAssistantMessages;\n\n // Insert a placeholder assistant message so state snapshots can render before any\n // assistant text exists for the current run.\n if (placeholderRenderer && shouldRenderPlaceholder && !hasAssistantForCurrentRun) {\n const placeholderId = currentRunId\n ? `coagent-state-render-${resolvedAgentId}-${currentRunId}`\n : `coagent-state-render-${resolvedAgentId}`;\n const placeholderMessage: Message = {\n id: placeholderId,\n role: \"assistant\",\n content: \"\",\n name: \"coagent-state-render\",\n runId: currentRunId,\n };\n processedMessages = [\n ...processedMessages,\n {\n ...placeholderMessage,\n generativeUIPosition: \"before\" as const,\n generativeUI: () =>\n placeholderRenderer({\n message: placeholderMessage,\n position: \"before\",\n }),\n } as Message,\n ];\n }\n\n return processedMessages;\n }, [\n agent?.messages,\n lazyToolRendered,\n allMessages,\n renderCustomMessage,\n legacyCustomMessageRenderer,\n resolvedAgentId,\n copilotkit,\n agent?.isRunning,\n agent?.state,\n ]);\n\n const renderedSuggestions = useMemo(() => {\n if (Array.isArray(suggestions)) {\n return {\n suggestions: suggestions.map((s) => ({ ...s, isLoading: false })),\n isLoading: false,\n };\n }\n return currentSuggestions;\n }, [suggestions, currentSuggestions]);\n\n // @ts-ignore\n return {\n messages: resolvedMessages,\n sendMessage: latestSendMessageFunc,\n appendMessage: latestAppendFunc,\n setMessages: latestSetMessagesFunc,\n reloadMessages: latestReloadFunc,\n stopGeneration: latestStopFunc,\n reset: latestResetFunc,\n deleteMessage: latestDeleteFunc,\n isAvailable: agentAvailable,\n isLoading: Boolean(agent?.isRunning),\n // mcpServers,\n // setMcpServers,\n suggestions: renderedSuggestions.suggestions,\n setSuggestions: (suggestions: Omit<Suggestion, \"isLoading\">[]) =>\n copilotkit.addSuggestionsConfig({ suggestions }),\n generateSuggestions: async () => copilotkit.reloadSuggestions(resolvedAgentId),\n resetSuggestions: () => copilotkit.clearSuggestions(resolvedAgentId),\n isLoadingSuggestions: renderedSuggestions.isLoading,\n interrupt,\n agent,\n threadId,\n };\n}\n\n// store `value` in a ref and update\n// it whenever it changes.\nfunction useUpdatedRef<T>(value: T) {\n const ref = useRef(value);\n\n useEffect(() => {\n ref.current = value;\n }, [value]);\n\n return ref;\n}\n\ntype LegacyRenderParams = {\n message: Message;\n position: \"before\" | \"after\";\n};\n\ntype LegacyRenderer = ((args: LegacyRenderParams) => any) | null;\n\nfunction useLegacyCoagentRenderer({\n copilotkit,\n agent,\n agentId,\n threadId,\n}: {\n copilotkit: ReturnType<typeof useCopilotKit>[\"copilotkit\"];\n agent?: AbstractAgent;\n agentId: string;\n threadId?: string;\n}): LegacyRenderer {\n return useMemo(() => {\n if (!copilotkit || !agent) {\n return null;\n }\n\n return ({ message, position }: LegacyRenderParams) => {\n const effectiveThreadId = threadId ?? agent.threadId ?? \"default\";\n const providedRunId = (message as any).runId as string | undefined;\n const existingRunId = providedRunId\n ? providedRunId\n : copilotkit.getRunIdForMessage(agentId, effectiveThreadId, message.id);\n const runId = existingRunId || `pending:${message.id}`;\n const messageIndex = Math.max(\n agent.messages.findIndex((msg) => msg.id === message.id),\n 0,\n );\n\n const bridgeProps: CoAgentStateRenderBridgeProps = {\n message: message as any,\n position,\n runId,\n messageIndex,\n messageIndexInRun: 0,\n numberOfMessagesInRun: 1,\n agentId,\n stateSnapshot: (message as any).state,\n };\n\n return createElement(CoAgentStateRenderBridge, bridgeProps) as any;\n };\n }, [agent, agentId, copilotkit, threadId]);\n}\n\nexport function defaultSystemMessage(\n contextString: string,\n additionalInstructions?: string,\n): string {\n return (\n `\nPlease act as an efficient, competent, conscientious, and industrious professional assistant.\n\nHelp the user achieve their goals, and you do so in a way that is as efficient as possible, without unnecessary fluff, but also without sacrificing professionalism.\nAlways be polite and respectful, and prefer brevity over verbosity.\n\nThe user has provided you with the following context:\n\\`\\`\\`\n${contextString}\n\\`\\`\\`\n\nThey have also provided you with functions you can call to initiate actions on their behalf, or functions you can call to receive more information.\n\nPlease assist them as best you can.\n\nYou can ask them for clarifying questions if needed, but don't be annoying about it. If you can reasonably 'fill in the blanks' yourself, do so.\n\nIf you would like to call a function, call it without saying anything else.\nIn case of a function error:\n- If this error stems from incorrect function parameters or syntax, you may retry with corrected arguments.\n- If the error's source is unclear or seems unrelated to your input, do not attempt further retries.\n` + (additionalInstructions ? `\\n\\n${additionalInstructions}` : \"\")\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,QAAQ,WAAW,aAAa,SAAS,UAAU,qBAAqB;AAKjF,SAAS,WAAW,WAAW,4BAA4B;AAE3D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAwB,sCAAsC;AA4RvD,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,IAA2B,CAAC,GAAyB;AAlTrD;AAmTE,QAAM,EAAE,WAAW,IAAI,cAAc;AACrC,QAAM,EAAE,UAAU,aAAa,IAAI,kBAAkB;AACrD,QAAM,iBAAiB,4BAA4B;AACnD,QAAM,CAAC,gBAAgB,iBAAiB,IAAI,SAAS,K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OAAO,SAAS,YAAY,QAAQ,CAAC;AAC3C;AAEO,SAAS,qBACd,eACA,wBACQ;AACR,SACE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAaG,yBAAyB;AAAA;AAAA,EAAO,2BAA2B;AAEhE;","names":["agent","_a","_b","suggestions"]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotChatInternal
3
- } from "./chunk-LO4RRITI.mjs";
3
+ } from "./chunk-KNJHRVKW.mjs";
4
4
  import {
5
5
  useCopilotContext
6
6
  } from "./chunk-AFNWX62Q.mjs";
@@ -83,4 +83,4 @@ function useCopilotChatHeadless_c(options = {}) {
83
83
  export {
84
84
  useCopilotChatHeadless_c
85
85
  };
86
- //# sourceMappingURL=chunk-XZFIJ7XF.mjs.map
86
+ //# sourceMappingURL=chunk-MA3CUMCY.mjs.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  useCopilotChatInternal
3
- } from "./chunk-LO4RRITI.mjs";
3
+ } from "./chunk-KNJHRVKW.mjs";
4
4
 
5
5
  // src/hooks/use-copilot-chat.ts
6
6
  function useCopilotChat(options = {}) {
@@ -33,4 +33,4 @@ function useCopilotChat(options = {}) {
33
33
  export {
34
34
  useCopilotChat
35
35
  };
36
- //# sourceMappingURL=chunk-NXHQDCZF.mjs.map
36
+ //# sourceMappingURL=chunk-QDES5PDW.mjs.map
@@ -992,8 +992,10 @@ function useCopilotChatInternal({
992
992
  const reload = useAsyncCallback(
993
993
  (reloadMessageId) => __async(this, null, function* () {
994
994
  var _a2;
995
+ if (!agent)
996
+ return;
995
997
  const messages = (_a2 = agent == null ? void 0 : agent.messages) != null ? _a2 : [];
996
- const isLoading = false;
998
+ const isLoading = agent.isRunning;
997
999
  if (isLoading || messages.length === 0) {
998
1000
  return;
999
1001
  }
@@ -1031,7 +1033,7 @@ function useCopilotChatInternal({
1031
1033
  }
1032
1034
  return;
1033
1035
  }),
1034
- [agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
1036
+ [agent == null ? void 0 : agent.messages.length, agent == null ? void 0 : agent.isRunning, agent == null ? void 0 : agent.setMessages, copilotkit == null ? void 0 : copilotkit.runAgent]
1035
1037
  );
1036
1038
  const latestSendMessageFunc = useAsyncCallback(
1037
1039
  (message, options) => __async(this, null, function* () {