@copilotkit/react-core 1.75.2 → 1.77.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.
Files changed (43) hide show
  1. package/dist/{copilotkit-Beiw32bn.cjs → copilotkit-CFPkj9B9.cjs} +155 -54
  2. package/dist/copilotkit-CFPkj9B9.cjs.map +1 -0
  3. package/dist/{copilotkit-D9iy3p2l.mjs → copilotkit-CP9qPAqV.mjs} +159 -57
  4. package/dist/copilotkit-CP9qPAqV.mjs.map +1 -0
  5. package/dist/{copilotkit-CGlSOKHM.d.mts → copilotkit-Cqa0TfEo.d.mts} +43 -17
  6. package/dist/copilotkit-Cqa0TfEo.d.mts.map +1 -0
  7. package/dist/{copilotkit-Cjj9wDI8.d.cts → copilotkit-DGc2YiW9.d.cts} +35 -4
  8. package/dist/copilotkit-DGc2YiW9.d.cts.map +1 -0
  9. package/dist/index.cjs +2 -2
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +1 -1
  12. package/dist/index.d.cts.map +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.d.mts.map +1 -1
  15. package/dist/index.mjs +4 -4
  16. package/dist/index.mjs.map +1 -1
  17. package/dist/index.umd.js +90 -44
  18. package/dist/index.umd.js.map +1 -1
  19. package/dist/v2/context.cjs.map +1 -1
  20. package/dist/v2/context.d.cts +5 -0
  21. package/dist/v2/context.d.cts.map +1 -1
  22. package/dist/v2/context.d.mts +5 -0
  23. package/dist/v2/context.d.mts.map +1 -1
  24. package/dist/v2/context.mjs.map +1 -1
  25. package/dist/v2/headless.cjs +36 -24
  26. package/dist/v2/headless.cjs.map +1 -1
  27. package/dist/v2/headless.d.cts +5 -0
  28. package/dist/v2/headless.d.cts.map +1 -1
  29. package/dist/v2/headless.d.mts +2 -2
  30. package/dist/v2/headless.d.mts.map +1 -1
  31. package/dist/v2/headless.mjs +38 -26
  32. package/dist/v2/headless.mjs.map +1 -1
  33. package/dist/v2/index.cjs +302 -121
  34. package/dist/v2/index.d.cts +2 -2
  35. package/dist/v2/index.d.mts +2 -2
  36. package/dist/v2/index.mjs +2 -2
  37. package/dist/v2/index.umd.js +457 -177
  38. package/dist/v2/index.umd.js.map +1 -1
  39. package/package.json +10 -10
  40. package/dist/copilotkit-Beiw32bn.cjs.map +0 -1
  41. package/dist/copilotkit-CGlSOKHM.d.mts.map +0 -1
  42. package/dist/copilotkit-Cjj9wDI8.d.cts.map +0 -1
  43. package/dist/copilotkit-D9iy3p2l.mjs.map +0 -1
@@ -42,6 +42,7 @@ _radix_ui_react_tooltip = __toESM(_radix_ui_react_tooltip);
42
42
  let _radix_ui_react_dropdown_menu = require("@radix-ui/react-dropdown-menu");
43
43
  _radix_ui_react_dropdown_menu = __toESM(_radix_ui_react_dropdown_menu);
44
44
  let streamdown = require("streamdown");
45
+ let _ag_ui_core = require("@ag-ui/core");
45
46
  let zod = require("zod");
46
47
  let _copilotkit_mcp_apps_renderer_activity = require("@copilotkit/mcp-apps-renderer/activity");
47
48
  let _copilotkit_a2ui_renderer = require("@copilotkit/a2ui-renderer");
@@ -170,6 +171,25 @@ const CopilotChatConfigurationProvider = ({ children, labels, agentId, threadId,
170
171
  parentConfig?.threadId,
171
172
  activeThreadOverride
172
173
  ]);
174
+ const copilotkit = (0, react.useContext)(_copilotkit_react_core_v2_context.CopilotKitContext)?.copilotkit;
175
+ const openThreadRef = (0, react.useRef)(null);
176
+ const latestThreadIdRef = (0, react.useRef)(resolvedThreadId);
177
+ latestThreadIdRef.current = resolvedThreadId;
178
+ (0, react.useEffect)(() => {
179
+ if (copilotkit === void 0) return;
180
+ const registration = copilotkit.registerOpenThread({
181
+ agentId: resolvedAgentId,
182
+ threadId: latestThreadIdRef.current
183
+ });
184
+ openThreadRef.current = registration;
185
+ return () => {
186
+ registration.unregister();
187
+ openThreadRef.current = null;
188
+ };
189
+ }, [copilotkit, resolvedAgentId]);
190
+ (0, react.useEffect)(() => {
191
+ openThreadRef.current?.update(resolvedThreadId);
192
+ }, [resolvedThreadId]);
173
193
  const resolvedHasExplicitThreadId = (threadIdPropIsAuthoritative ? true : activeThreadOverride?.explicit ?? hasExplicitThreadId ?? false) || !!parentConfig?.hasExplicitThreadId;
174
194
  const [internalModalOpen, setInternalModalOpen] = (0, react.useState)(isModalDefaultOpen ?? true);
175
195
  const hasExplicitDefault = isModalDefaultOpen !== void 0;
@@ -1539,7 +1559,7 @@ const ToolCallRenderer = react.default.memo(function ToolCallRenderer({ toolCall
1539
1559
  toolCallId: toolCall.id,
1540
1560
  args,
1541
1561
  status: _copilotkit_core.ToolCallStatus.Complete,
1542
- result: toolMessage.content
1562
+ result: (0, _ag_ui_core.contentToText)(toolMessage.content)
1543
1563
  });
1544
1564
  else if (isExecuting) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(RenderComponent, {
1545
1565
  name: toolName,
@@ -1635,7 +1655,7 @@ function useRenderToolCall() {
1635
1655
 
1636
1656
  //#endregion
1637
1657
  //#region package.json
1638
- var version = "1.75.2";
1658
+ var version = "1.77.0";
1639
1659
 
1640
1660
  //#endregion
1641
1661
  //#region src/v2/components/CopilotKitInspector.tsx
@@ -1871,12 +1891,14 @@ function InlineFeatureWarning({ featureName }) {
1871
1891
  * Fetches resource content on-demand via proxied MCP requests. The React shell
1872
1892
  * owns the iframe; `bindMcpApp` owns the protocol.
1873
1893
  */
1874
- const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agent }) {
1894
+ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, message, agent }) {
1875
1895
  const { copilotkit } = (0, _copilotkit_react_core_v2_context.useCopilotKit)();
1896
+ const messageId = message?.id;
1876
1897
  const containerRef = (0, react.useRef)(null);
1877
1898
  const iframeRef = (0, react.useRef)(null);
1878
1899
  const sessionRef = (0, react.useRef)(null);
1879
1900
  const [error, setError] = (0, react.useState)(null);
1901
+ const [contentError, setContentError] = (0, react.useState)(null);
1880
1902
  const [isLoading, setIsLoading] = (0, react.useState)(true);
1881
1903
  const [iframeSize, setIframeSize] = (0, react.useState)({});
1882
1904
  const [fetchedResource, setFetchedResource] = (0, react.useState)(null);
@@ -1895,6 +1917,7 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1895
1917
  let mounted = true;
1896
1918
  setIsLoading(true);
1897
1919
  setError(null);
1920
+ setContentError(null);
1898
1921
  const iframe = document.createElement("iframe");
1899
1922
  iframe.style.width = "100%";
1900
1923
  iframe.style.height = "100px";
@@ -1917,6 +1940,7 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1917
1940
  getContent: () => contentRef.current,
1918
1941
  getAgent: () => agentRef.current,
1919
1942
  host: copilotkit,
1943
+ messageId,
1920
1944
  hooks: {
1921
1945
  onResource: (resource) => {
1922
1946
  if (!mounted) return;
@@ -1926,6 +1950,9 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1926
1950
  onSizeChanged: (size) => {
1927
1951
  if (mounted) setIframeSize(size);
1928
1952
  },
1953
+ onContentError: (err) => {
1954
+ if (mounted) setContentError(err);
1955
+ },
1929
1956
  onError: (err) => {
1930
1957
  if (!mounted) return;
1931
1958
  setError(err);
@@ -1934,9 +1961,7 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1934
1961
  }
1935
1962
  });
1936
1963
  sessionRef.current = session;
1937
- const current = contentRef.current;
1938
- if (current.toolInput) session.sendToolInput(current.toolInput);
1939
- if (current.result) session.sendToolResult(current.result);
1964
+ session.syncContent(contentRef.current);
1940
1965
  } catch (err) {
1941
1966
  console.error("[MCPAppsRenderer] Setup error:", err);
1942
1967
  if (mounted) {
@@ -1956,6 +1981,7 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1956
1981
  }, [
1957
1982
  agent,
1958
1983
  copilotkit,
1984
+ messageId,
1959
1985
  content.resourceUri,
1960
1986
  content.serverHash,
1961
1987
  content.serverId
@@ -1970,11 +1996,8 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1970
1996
  }
1971
1997
  }, [iframeSize]);
1972
1998
  (0, react.useEffect)(() => {
1973
- if (content.toolInput) sessionRef.current?.sendToolInput(content.toolInput);
1974
- }, [content.toolInput]);
1975
- (0, react.useEffect)(() => {
1976
- if (content.result) sessionRef.current?.sendToolResult(content.result);
1977
- }, [content.result]);
1999
+ sessionRef.current?.syncContent(contentRef.current);
2000
+ }, [content.toolInput, content.result]);
1978
2001
  const borderStyle = fetchedResource?._meta?.ui?.prefersBorder === true ? {
1979
2002
  borderRadius: "8px",
1980
2003
  backgroundColor: "#f9f9f9",
@@ -1996,12 +2019,12 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, agen
1996
2019
  color: "#666"
1997
2020
  },
1998
2021
  children: "Loading..."
1999
- }), error && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2022
+ }), (error ?? contentError) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
2000
2023
  style: {
2001
2024
  color: "red",
2002
2025
  padding: "1rem"
2003
2026
  },
2004
- children: ["Error: ", error.message]
2027
+ children: ["Error: ", (error ?? contentError).message]
2005
2028
  })]
2006
2029
  });
2007
2030
  };
@@ -3399,7 +3422,7 @@ function useStableArrayProp(prop, warningMessage, isMeaningfulChange) {
3399
3422
  }, [value, warningMessage]);
3400
3423
  return value;
3401
3424
  }
3402
- const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, messageFilter, publicApiKey, publicLicenseKey, licenseToken, properties = EMPTY_PROPERTIES, agents__unsafe_dev_only: agents = EMPTY_AGENTS, selfManagedAgents = EMPTY_AGENTS, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, openGenerativeUI, enableInspector, agentId, useSingleEndpoint, onError, a2ui, defaultThrottleMs, debug }) => {
3425
+ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY_HEADERS, credentials, messageFilter, publicApiKey, publicLicenseKey, licenseToken, properties = EMPTY_PROPERTIES, agents__unsafe_dev_only: agents = EMPTY_AGENTS, selfManagedAgents = EMPTY_AGENTS, renderToolCalls, renderActivityMessages, renderCustomMessages, frontendTools, humanInTheLoop, openGenerativeUI, enableInspector, agentId, showIntelligenceIndicator = true, useSingleEndpoint, onError, a2ui, defaultThrottleMs, debug, learning }) => {
3403
3426
  const [shouldRenderInspector, setShouldRenderInspector] = (0, react.useState)(false);
3404
3427
  const [inspectorVisible, setInspectorVisible] = (0, react.useState)(false);
3405
3428
  (0, react.useEffect)(() => {
@@ -3634,7 +3657,8 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
3634
3657
  renderToolCalls: allRenderToolCalls,
3635
3658
  renderActivityMessages: allActivityRenderers,
3636
3659
  renderCustomMessages: renderCustomMessagesList,
3637
- debug
3660
+ debug,
3661
+ learning
3638
3662
  });
3639
3663
  if (defaultThrottleMs !== void 0) copilotkitRef.current.setDefaultThrottleMs(defaultThrottleMs);
3640
3664
  }
@@ -3739,6 +3763,32 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
3739
3763
  useSingleEndpoint,
3740
3764
  debug
3741
3765
  ]);
3766
+ const learningEnabled = learning !== void 0;
3767
+ const trajectoryId = learning?.trajectoryId;
3768
+ const learningContainerIdsRef = (0, react.useRef)(learning?.learningContainerIds);
3769
+ (0, react.useEffect)(() => {
3770
+ copilotkit.setLearningConfig(learning);
3771
+ learningContainerIdsRef.current = learning?.learningContainerIds;
3772
+ if (learning?.sink === void 0 && learning?.trajectoryId === void 0 && learning?.learningContainerIds !== void 0) console.warn("[CopilotKit] learningContainerIds is supported only with a custom sink. Authenticated Trajectory capture does not assign Learning Containers; remove learningContainerIds from the capture options.");
3773
+ }, [copilotkit, learning]);
3774
+ (0, react.useEffect)(() => {
3775
+ if (!learningEnabled) return;
3776
+ let disposed = false;
3777
+ if (trajectoryId !== void 0) copilotkit.startTrajectory({
3778
+ trajectoryId,
3779
+ learningContainerIds: learningContainerIdsRef.current
3780
+ }).catch(() => {
3781
+ if (!disposed) console.warn("[CopilotKit] Failed to start interaction capture.");
3782
+ });
3783
+ return () => {
3784
+ disposed = true;
3785
+ copilotkit.stopTrajectory();
3786
+ };
3787
+ }, [
3788
+ copilotkit,
3789
+ learningEnabled,
3790
+ trajectoryId
3791
+ ]);
3742
3792
  const didMountRef = (0, react.useRef)(false);
3743
3793
  (0, react.useEffect)(() => {
3744
3794
  if (!didMountRef.current) return;
@@ -3801,8 +3851,13 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
3801
3851
  ]);
3802
3852
  const contextValue = (0, react.useMemo)(() => ({
3803
3853
  copilotkit,
3804
- executingToolCallIds
3805
- }), [copilotkit, executingToolCallIds]);
3854
+ executingToolCallIds,
3855
+ showIntelligenceIndicator
3856
+ }), [
3857
+ copilotkit,
3858
+ executingToolCallIds,
3859
+ showIntelligenceIndicator
3860
+ ]);
3806
3861
  const retryableRuntimeEntitlementFailure = runtimeEntitlements?.status !== "ready" && runtimeEntitlements?.error.retryable === true;
3807
3862
  const hasNonReadyRuntimeEntitlement = runtimeEntitlements !== void 0 && runtimeEntitlements.status !== "ready";
3808
3863
  const hasLegacyRuntimeEntitlementFallback = runtimeLicenseStatus === "valid" || runtimeLicenseStatus === "expiring";
@@ -4683,7 +4738,7 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
4683
4738
  updateFlags
4684
4739
  ]);
4685
4740
  (0, react.useEffect)(() => {
4686
- if (agent instanceof _ag_ui_client.HttpAgent) copilotkit.applyHeadersToAgent(agent);
4741
+ if ((0, _copilotkit_core.ɵisHttpAgent)(agent)) copilotkit.applyHeadersToAgent(agent);
4687
4742
  if (agent instanceof _copilotkit_core.ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
4688
4743
  }, [
4689
4744
  agent,
@@ -5021,7 +5076,6 @@ function useInterrupt(config) {
5021
5076
  pendingRef.current = pending;
5022
5077
  const [handlerResult, setHandlerResult] = (0, react.useState)(null);
5023
5078
  const interruptStateRef = (0, react.useRef)(new _copilotkit_core.ɵInterruptState());
5024
- const legacyRunIdRef = (0, react.useRef)(void 0);
5025
5079
  (0, react.useEffect)(() => {
5026
5080
  const interruptState = interruptStateRef.current;
5027
5081
  let localLegacy = null;
@@ -5039,16 +5093,14 @@ function useInterrupt(config) {
5039
5093
  onRunStartedEvent: () => {
5040
5094
  localLegacy = null;
5041
5095
  localStandard = null;
5042
- legacyRunIdRef.current = void 0;
5043
5096
  interruptState.clear();
5044
5097
  setPending(null);
5045
5098
  },
5046
- onRunFinalized: (params) => {
5099
+ onRunFinalized: () => {
5047
5100
  if (localStandard && localStandard.length > 0) {
5048
5101
  interruptState.setStandard(localStandard);
5049
5102
  setPending(interruptState.pending);
5050
5103
  } else if (localLegacy) {
5051
- legacyRunIdRef.current = params.input.runId;
5052
5104
  interruptState.setLegacy(localLegacy);
5053
5105
  setPending(interruptState.pending);
5054
5106
  }
@@ -5058,7 +5110,6 @@ function useInterrupt(config) {
5058
5110
  onRunFailed: () => {
5059
5111
  localLegacy = null;
5060
5112
  localStandard = null;
5061
- legacyRunIdRef.current = void 0;
5062
5113
  interruptState.clear();
5063
5114
  setPending(null);
5064
5115
  }
@@ -5073,22 +5124,18 @@ function useInterrupt(config) {
5073
5124
  if (!current) return;
5074
5125
  if (current.kind === "standard" && current.interrupts.length > 1 && interruptId === void 0) console.warn(`[CopilotKit] useInterrupt: resolve()/cancel() called without an interruptId while ${current.interrupts.length} interrupts are open; defaulting to the first. Pass an interruptId to address a specific interrupt.`);
5075
5126
  const decision = interruptStateRef.current.resolve(payload, interruptId);
5076
- if (decision.kind === "legacy-resume") {
5077
- const runId = legacyRunIdRef.current;
5078
- try {
5079
- return await copilotkit.runAgent({
5080
- agent,
5081
- ...runId !== void 0 ? { runId } : {},
5082
- forwardedProps: { command: {
5083
- resume: decision.payload,
5084
- interruptEvent: decision.interruptValue
5085
- } }
5086
- });
5087
- } catch (err) {
5088
- console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
5089
- setPending(null);
5090
- throw err;
5091
- }
5127
+ if (decision.kind === "legacy-resume") try {
5128
+ return await copilotkit.runAgent({
5129
+ agent,
5130
+ forwardedProps: { command: {
5131
+ resume: decision.payload,
5132
+ interruptEvent: decision.interruptValue
5133
+ } }
5134
+ });
5135
+ } catch (err) {
5136
+ console.error("[CopilotKit] useInterrupt resolve: runAgent rejected; clearing pending + rethrowing", err);
5137
+ setPending(null);
5138
+ throw err;
5092
5139
  }
5093
5140
  if (decision.kind === "expired") {
5094
5141
  console.error(`[CopilotKit] useInterrupt: interrupt ${decision.interrupt.id} expired at ${decision.interrupt.expiresAt}; not resuming.`);
@@ -6044,13 +6091,23 @@ function useLearningContainersInCurrentThread({ learningContainers }) {
6044
6091
  //#region src/v2/components/chat/CopilotChatToolCallsView.tsx
6045
6092
  function CopilotChatToolCallsView({ message, messages = [] }) {
6046
6093
  const renderToolCall = useRenderToolCall();
6094
+ const { copilotkit } = (0, _copilotkit_react_core_v2_context.useCopilotKit)();
6095
+ const subscribe = (0, react.useCallback)((onChange) => copilotkit.ɵsubscribeToLearningConfigured(onChange), [copilotkit]);
6096
+ const getSnapshot = () => copilotkit.ɵlearningConfigured;
6097
+ const learningConfigured = (0, react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
6047
6098
  if (!message.toolCalls || message.toolCalls.length === 0) return null;
6048
6099
  return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: message.toolCalls.map((toolCall) => {
6049
- const toolMessage = messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id);
6050
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.default.Fragment, { children: renderToolCall({
6100
+ const rendered = renderToolCall({
6051
6101
  toolCall,
6052
- toolMessage
6053
- }) }, toolCall.id);
6102
+ toolMessage: messages.find((m) => m.role === "tool" && m.toolCallId === toolCall.id)
6103
+ });
6104
+ if (rendered === null) return null;
6105
+ if (!learningConfigured) return rendered;
6106
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
6107
+ "data-tool-call-id": toolCall.id,
6108
+ style: { display: "contents" },
6109
+ children: rendered
6110
+ }, toolCall.id);
6054
6111
  }) });
6055
6112
  }
6056
6113
 
@@ -6394,6 +6451,7 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
6394
6451
  const shouldShowToolbar = toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatestAssistantMessage);
6395
6452
  if (children) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
6396
6453
  "data-copilotkit": true,
6454
+ "data-message-id": message.id,
6397
6455
  style: { display: "contents" },
6398
6456
  children: children({
6399
6457
  markdownRenderer: boundMarkdownRenderer,
@@ -7631,7 +7689,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
7631
7689
  const isPinnedToBottom = (0, react.useContext)(ScrollPinnedContext);
7632
7690
  const renderCustomMessage = useRenderCustomMessages();
7633
7691
  const { renderActivityMessage } = useRenderActivityMessage();
7634
- const { copilotkit } = (0, _copilotkit_react_core_v2_context.useCopilotKit)();
7692
+ const { copilotkit, showIntelligenceIndicator = true } = (0, _copilotkit_react_core_v2_context.useCopilotKit)();
7635
7693
  const config = useCopilotChatConfiguration();
7636
7694
  const [, forceUpdate] = (0, react.useReducer)((x) => x + 1, 0);
7637
7695
  (0, react.useEffect)(() => {
@@ -7818,7 +7876,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
7818
7876
  renderCustomMessage,
7819
7877
  stateSnapshot
7820
7878
  }, `${rowKey}-custom-after`));
7821
- const intelligenceTurnId = intelligenceTurnAnchors.get(message.id);
7879
+ const intelligenceTurnId = showIntelligenceIndicator ? intelligenceTurnAnchors.get(message.id) : void 0;
7822
7880
  if (intelligenceTurnId !== void 0) elements.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(IntelligenceIndicator, {
7823
7881
  message,
7824
7882
  agentId: config?.agentId ?? _copilotkit_shared.DEFAULT_AGENT_ID,
@@ -8943,6 +9001,8 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
8943
9001
  const hasNativeIntelligenceRunActivity = hasExplicitThreadId && runtimeStatus === "Connected" && !!copilotkit.intelligence?.wsUrl && copilotkit.threadEndpoints?.realtimeMetadata === true;
8944
9002
  const [standaloneRunActivityStore] = (0, react.useState)(() => (0, _copilotkit_core.ɵcreateThreadStore)({ fetch: copilotkit.ɵruntimeFetch }));
8945
9003
  const previousThreadRef = (0, react.useRef)(null);
9004
+ const detachPromisesRef = (0, react.useRef)(/* @__PURE__ */ new WeakMap());
9005
+ const pendingTeardownRef = (0, react.useRef)(Promise.resolve());
8946
9006
  const hasExplicitThreadIdRef = (0, react.useRef)(hasExplicitThreadId);
8947
9007
  hasExplicitThreadIdRef.current = hasExplicitThreadId;
8948
9008
  const rememberRecentlyLocalRunId = (0, react.useCallback)((runId) => {
@@ -8985,23 +9045,59 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
8985
9045
  const previousThread = previousThreadRef.current;
8986
9046
  const threadChanged = previousThread?.threadId !== resolvedThreadId;
8987
9047
  const inspectorTransition = threadChanged && previousThread !== null && previousThread.inspectorRequestId !== inspectorRequestId && (previousThread.inspectorRequestId !== null || inspectorRequestId !== null);
8988
- previousThreadRef.current = {
9048
+ const selection = {
8989
9049
  threadId: resolvedThreadId,
8990
- inspectorRequestId
9050
+ inspectorRequestId,
9051
+ agent
8991
9052
  };
9053
+ previousThreadRef.current = selection;
9054
+ const discardedThreadId = previousThread?.agent === agent ? previousThread.threadId : agent.threadId;
8992
9055
  if (inspectorTransition) if (typeof copilotkit.stopAgent === "function") copilotkit.stopAgent({ agent });
8993
9056
  else agent.abortRun?.();
8994
9057
  agent.threadId = resolvedThreadId;
8995
9058
  if (!hasExplicitThreadId) {
8996
- if (threadChanged && agent.messages.length > 0) agent.setMessages([]);
8997
- return;
9059
+ let active = true;
9060
+ if (threadChanged && previousThread !== null) {
9061
+ let resetPending = true;
9062
+ const clearCursor = () => {
9063
+ if ("clearReplayCursor" in agent && typeof agent.clearReplayCursor === "function") agent.clearReplayCursor(discardedThreadId);
9064
+ if ("clearReconnectCursor" in agent && typeof agent.clearReconnectCursor === "function") agent.clearReconnectCursor(discardedThreadId);
9065
+ };
9066
+ const clearDiscardedBaseline = () => {
9067
+ if (!active || !resetPending || previousThreadRef.current !== selection) return;
9068
+ agent.setMessages([]);
9069
+ agent.setState({});
9070
+ agent.pendingInterrupts = [];
9071
+ clearCursor();
9072
+ };
9073
+ if (previousThread.agent === agent) previousThread.clearDiscardedBaseline = clearDiscardedBaseline;
9074
+ const detach = detachPromisesRef.current.get(agent) ?? agent.detachActiveRun();
9075
+ detachPromisesRef.current.set(agent, detach);
9076
+ const finishReset = () => {
9077
+ if (!resetPending) return;
9078
+ clearCursor();
9079
+ clearDiscardedBaseline();
9080
+ resetPending = false;
9081
+ };
9082
+ clearDiscardedBaseline();
9083
+ pendingTeardownRef.current = Promise.all([pendingTeardownRef.current, detach]).then(finishReset).catch((error) => {
9084
+ console.error("CopilotChat: detachActiveRun failed", error);
9085
+ }).finally(() => {
9086
+ if (detachPromisesRef.current.get(agent) === detach) detachPromisesRef.current.delete(agent);
9087
+ });
9088
+ }
9089
+ return () => {
9090
+ active = false;
9091
+ };
8998
9092
  }
8999
9093
  let detached = false;
9000
9094
  const connectAbortController = new AbortController();
9001
- if (agent instanceof _ag_ui_client.HttpAgent) agent.abortController = connectAbortController;
9002
9095
  const connect = async (agentToConnect) => {
9003
9096
  activeConnectCountRef.current += 1;
9004
9097
  try {
9098
+ await pendingTeardownRef.current;
9099
+ if (detached) return;
9100
+ if ((0, _copilotkit_core.ɵisHttpAgent)(agentToConnect)) agentToConnect.abortController = connectAbortController;
9005
9101
  await copilotkit.connectAgent({ agent: agentToConnect });
9006
9102
  } catch (error) {
9007
9103
  if (detached) return;
@@ -9011,7 +9107,7 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
9011
9107
  if (!detached) (typeof requestAnimationFrame === "function" ? requestAnimationFrame : (cb) => setTimeout(cb, 16))(() => {
9012
9108
  if (!detached) setLastConnectedThreadId(resolvedThreadId);
9013
9109
  });
9014
- else if (!hasExplicitThreadIdRef.current) agentToConnect.setMessages([]);
9110
+ else if (!hasExplicitThreadIdRef.current) selection.clearDiscardedBaseline?.();
9015
9111
  activeConnectCountRef.current = Math.max(0, activeConnectCountRef.current - 1);
9016
9112
  if (!detached && activeConnectCountRef.current === 0) {
9017
9113
  const startReconnect = startRunActivityReconnectRef.current;
@@ -9026,7 +9122,12 @@ function CopilotChat({ agentId, threadId, labels, inspectorTools, chatView, isMo
9026
9122
  return () => {
9027
9123
  detached = true;
9028
9124
  connectAbortController.abort();
9029
- agent.detachActiveRun().catch(() => {});
9125
+ const detach = agent.detachActiveRun().catch(() => {});
9126
+ detachPromisesRef.current.set(agent, detach);
9127
+ pendingTeardownRef.current = Promise.all([pendingTeardownRef.current, detach]).then(() => {});
9128
+ detach.then(() => {
9129
+ if (detachPromisesRef.current.get(agent) === detach) detachPromisesRef.current.delete(agent);
9130
+ });
9030
9131
  };
9031
9132
  }, [
9032
9133
  resolvedThreadId,
@@ -9902,7 +10003,7 @@ function CopilotPopupViewInternal({ header, toggleButton, width, height, clickOu
9902
10003
  const popupAnimationClass = isPopupOpen && !isAnimatingOut ? "cpk:pointer-events-auto cpk:translate-y-0 cpk:opacity-100 cpk:md:scale-100" : "cpk:pointer-events-none cpk:translate-y-4 cpk:opacity-0 cpk:md:translate-y-5 cpk:md:scale-[0.95]";
9903
10004
  return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [toggleButtonElement, isRendered ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9904
10005
  "data-copilotkit": true,
9905
- className: cn("cpk:fixed cpk:inset-0 cpk:z-[1200] cpk:flex cpk:max-w-full cpk:flex-col cpk:items-stretch", "cpk:md:inset-auto cpk:md:bottom-24 cpk:md:right-6 cpk:md:items-end cpk:md:gap-4"),
10006
+ className: cn("cpk:fixed cpk:inset-0 cpk:z-[1200] cpk:flex cpk:max-w-full cpk:flex-col cpk:items-stretch cpk:bg-transparent", "cpk:md:inset-auto cpk:md:bottom-24 cpk:md:right-6 cpk:md:items-end cpk:md:gap-4"),
9906
10007
  children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
9907
10008
  ref: containerRef,
9908
10009
  tabIndex: -1,
@@ -13105,4 +13206,4 @@ Object.defineProperty(exports, 'useToast', {
13105
13206
  return useToast;
13106
13207
  }
13107
13208
  });
13108
- //# sourceMappingURL=copilotkit-Beiw32bn.cjs.map
13209
+ //# sourceMappingURL=copilotkit-CFPkj9B9.cjs.map