@copilotkit/react-core 1.87.1 → 1.89.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 (38) hide show
  1. package/dist/{copilotkit-BNPEXnEE.d.mts → copilotkit-CfnudBCL.d.mts} +25 -5
  2. package/dist/copilotkit-CfnudBCL.d.mts.map +1 -0
  3. package/dist/{copilotkit-DFxtDD2N.cjs → copilotkit-DHJJxCeI.cjs} +330 -73
  4. package/dist/copilotkit-DHJJxCeI.cjs.map +1 -0
  5. package/dist/{copilotkit-BJ-6BoJ_.mjs → copilotkit-GWoyxfzS.mjs} +334 -77
  6. package/dist/copilotkit-GWoyxfzS.mjs.map +1 -0
  7. package/dist/{copilotkit-Bop-sY6y.d.cts → copilotkit-XLp7jKQk.d.cts} +25 -5
  8. package/dist/copilotkit-XLp7jKQk.d.cts.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.d.cts +1 -1
  11. package/dist/index.d.mts +1 -1
  12. package/dist/index.mjs +1 -1
  13. package/dist/index.umd.js +22 -12
  14. package/dist/index.umd.js.map +1 -1
  15. package/dist/v2/generative-ui.d.cts +116 -116
  16. package/dist/v2/generative-ui.d.cts.map +1 -1
  17. package/dist/v2/generative-ui.d.mts +116 -116
  18. package/dist/v2/generative-ui.d.mts.map +1 -1
  19. package/dist/v2/headless.cjs +7 -2
  20. package/dist/v2/headless.cjs.map +1 -1
  21. package/dist/v2/headless.d.cts +5 -0
  22. package/dist/v2/headless.d.cts.map +1 -1
  23. package/dist/v2/headless.d.mts +5 -0
  24. package/dist/v2/headless.d.mts.map +1 -1
  25. package/dist/v2/headless.mjs +7 -2
  26. package/dist/v2/headless.mjs.map +1 -1
  27. package/dist/v2/index.cjs +19 -1
  28. package/dist/v2/index.css +1 -1
  29. package/dist/v2/index.d.cts +2 -2
  30. package/dist/v2/index.d.mts +2 -2
  31. package/dist/v2/index.mjs +2 -2
  32. package/dist/v2/index.umd.js +347 -72
  33. package/dist/v2/index.umd.js.map +1 -1
  34. package/package.json +10 -10
  35. package/dist/copilotkit-BJ-6BoJ_.mjs.map +0 -1
  36. package/dist/copilotkit-BNPEXnEE.d.mts.map +0 -1
  37. package/dist/copilotkit-Bop-sY6y.d.cts.map +0 -1
  38. package/dist/copilotkit-DFxtDD2N.cjs.map +0 -1
@@ -1326,7 +1326,7 @@ function useRenderToolCall() {
1326
1326
 
1327
1327
  //#endregion
1328
1328
  //#region package.json
1329
- var version = "1.87.1";
1329
+ var version = "1.89.0";
1330
1330
 
1331
1331
  //#endregion
1332
1332
  //#region src/v2/components/CopilotKitInspector.tsx
@@ -1562,7 +1562,7 @@ function InlineFeatureWarning({ featureName }) {
1562
1562
  * Fetches resource content on-demand via proxied MCP requests. The React shell
1563
1563
  * owns the iframe; `bindMcpApp` owns the protocol.
1564
1564
  */
1565
- const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, message, agent, allowSameOriginFallback }) {
1565
+ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, message, agent, allowSameOriginFallback, modelContext }) {
1566
1566
  const { copilotkit } = (0, _copilotkit_react_core_v2_context.useCopilotKit)();
1567
1567
  const messageId = message?.id;
1568
1568
  const containerRef = (0, react.useRef)(null);
@@ -1612,7 +1612,10 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, mess
1612
1612
  getAgent: () => agentRef.current,
1613
1613
  host: copilotkit,
1614
1614
  messageId,
1615
- options: { allowSameOriginFallback },
1615
+ options: {
1616
+ allowSameOriginFallback,
1617
+ modelContext
1618
+ },
1616
1619
  hooks: {
1617
1620
  onResource: (resource) => {
1618
1621
  if (!mounted) return;
@@ -1655,6 +1658,7 @@ const MCPAppsActivityRenderer = function MCPAppsActivityRenderer({ content, mess
1655
1658
  copilotkit,
1656
1659
  messageId,
1657
1660
  allowSameOriginFallback,
1661
+ modelContext,
1658
1662
  content.resourceUri,
1659
1663
  content.serverHash,
1660
1664
  content.serverId
@@ -3198,11 +3202,6 @@ const DEFAULT_DESIGN_SKILL = `When generating UI with generateSandboxedUi, follo
3198
3202
  - Use CSS Grid or Flexbox for layout. Ensure the UI looks good at any width.
3199
3203
  - Minimal transitions (150ms) for hover/focus states only. No decorative animations.
3200
3204
  - Keep the UI focused and dense — avoid excessive padding. Use compact spacing (8–12px gaps, 10–14px padding in controls).`;
3201
- /** The MCP Apps renderer with `mcpApps.allowSameOriginFallback` applied. */
3202
- const SameOriginMCPAppsActivityRenderer = (props) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MCPAppsActivityRenderer, {
3203
- ...props,
3204
- allowSameOriginFallback: true
3205
- });
3206
3205
  const DEFAULT_LEARNING = Object.freeze({});
3207
3206
  function toLearningConfig(learning) {
3208
3207
  if (learning === true) return DEFAULT_LEARNING;
@@ -3279,11 +3278,17 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
3279
3278
  return (0, _copilotkit_a2ui_renderer.filterCatalog)(rawCatalog, (name) => core ? core.isCatalogComponentEnabled(name) : true);
3280
3279
  }, [rawCatalog, catalogToggleVersion]);
3281
3280
  const mcpAppsAllowSameOrigin = mcpApps?.allowSameOriginFallback === true;
3281
+ const mcpAppsModelContext = mcpApps?.modelContext === true;
3282
+ const mcpAppsRenderer = (0, react.useMemo)(() => mcpAppsAllowSameOrigin || mcpAppsModelContext ? (props) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MCPAppsActivityRenderer, {
3283
+ ...props,
3284
+ allowSameOriginFallback: mcpAppsAllowSameOrigin,
3285
+ modelContext: mcpAppsModelContext
3286
+ }) : MCPAppsActivityRenderer, [mcpAppsAllowSameOrigin, mcpAppsModelContext]);
3282
3287
  const builtInActivityRenderers = (0, react.useMemo)(() => {
3283
3288
  const renderers = [{
3284
3289
  activityType: _copilotkit_mcp_apps_renderer_activity.MCPAppsActivityType,
3285
3290
  content: _copilotkit_mcp_apps_renderer_activity.MCPAppsActivityContentSchema,
3286
- render: mcpAppsAllowSameOrigin ? SameOriginMCPAppsActivityRenderer : MCPAppsActivityRenderer
3291
+ render: mcpAppsRenderer
3287
3292
  }];
3288
3293
  if (openGenUIActive) renderers.push({
3289
3294
  activityType: OpenGenerativeUIActivityType,
@@ -3304,7 +3309,7 @@ const CopilotKitProvider = ({ children, runtimeUrl, headers: headersProp = EMPTY
3304
3309
  generativeUIActive,
3305
3310
  a2ui,
3306
3311
  filteredCatalog,
3307
- mcpAppsAllowSameOrigin
3312
+ mcpAppsRenderer
3308
3313
  ]);
3309
3314
  const allActivityRenderers = (0, react.useMemo)(() => {
3310
3315
  return [...renderActivityMessagesList, ...builtInActivityRenderers];
@@ -4882,6 +4887,11 @@ const ALL_UPDATES = [
4882
4887
  UseAgentUpdate.OnStateChanged,
4883
4888
  UseAgentUpdate.OnRunStatusChanged
4884
4889
  ];
4890
+ /**
4891
+ * Returns the selected agent and its readiness, subscribing to agent updates.
4892
+ * Uses a shared agent by default, or a private proxy when `agentId`,
4893
+ * `runtimeAgentId`, and `threadId` are supplied together.
4894
+ */
4885
4895
  function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {}) {
4886
4896
  if (threadId != null && runtimeAgentId == null) throw new Error(`useAgent: \`threadId\` requires \`runtimeAgentId\`. A threadId is written onto a single agent, but an agent resolved by agentId alone is shared, so scoping a thread to it would clobber other useAgent callers. Pass a distinct local \`agentId\` and the runtime agent to route to, e.g. useAgent({ agentId: "chat-1", runtimeAgentId: "${agentId ?? "default"}", threadId }).`);
4887
4897
  if (runtimeAgentId != null && threadId == null) throw new Error(`useAgent: \`runtimeAgentId\` requires \`threadId\`. A proxied agent exists to scope a thread to a private instance; without a threadId it behaves like the shared agent while adding a registration and a local agentId to keep unique. Either pass the thread, e.g. useAgent({ agentId: "${agentId ?? "chat-1"}", runtimeAgentId: "${runtimeAgentId}", threadId }), or bind to the agent directly with useAgent({ agentId: "${runtimeAgentId}" }).`);
@@ -5008,7 +5018,7 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
5008
5018
  copilotkit.runtimeUrl,
5009
5019
  copilotkit.runtimeTransport,
5010
5020
  copilotkit.credentials,
5011
- JSON.stringify(copilotkit.headers)
5021
+ copilotkit.ɵheadersGeneration
5012
5022
  ]);
5013
5023
  (0, react.useEffect)(() => {
5014
5024
  if (updateFlags.length === 0) return;
@@ -5051,7 +5061,7 @@ function useAgent({ agentId, threadId, runtimeAgentId, updates, throttleMs } = {
5051
5061
  if (agent instanceof _copilotkit_core.ProxiedCopilotRuntimeAgent) agent.credentials = copilotkit.credentials;
5052
5062
  }, [
5053
5063
  agent,
5054
- JSON.stringify(copilotkit.headers),
5064
+ copilotkit.ɵheadersGeneration,
5055
5065
  copilotkit.credentials
5056
5066
  ]);
5057
5067
  const configThreadId = chatConfig?.threadId;
@@ -6498,9 +6508,14 @@ function getToolCallLayouts(rendered, all, renderers) {
6498
6508
  }
6499
6509
  /**
6500
6510
  * Finds the working phase of every reply in `rendered`: its messages up to the
6501
- * last one that calls a tool. Text in there was narration; what follows is the
6511
+ * last one that calls a tool, plus the thinking and the silent messages that
6512
+ * trail it. Text in there was narration; the first text after the work is the
6502
6513
  * reply itself. Replies that called no tools are omitted, except the latest,
6503
6514
  * which may be about to.
6515
+ *
6516
+ * The trailing part matters: an agent that thinks once more after its last
6517
+ * tool call would otherwise leave those "Thought for 2 seconds" lines outside
6518
+ * the work, where nothing ever folds them away.
6504
6519
  */
6505
6520
  function getTurnWork(rendered, layouts) {
6506
6521
  const turns = /* @__PURE__ */ new Map();
@@ -6519,6 +6534,13 @@ function getTurnWork(rendered, layouts) {
6519
6534
  visible.forEach((message, index) => {
6520
6535
  if (message.role === "assistant" && message.toolCalls?.some((call) => shown.has(call.id))) lastWork = index;
6521
6536
  });
6537
+ let workEnd = lastWork;
6538
+ for (let index = lastWork + 1; lastWork >= 0 && index < visible.length; index++) {
6539
+ const message = visible[index];
6540
+ const content = message.content;
6541
+ if (message.role === "assistant" && typeof content === "string" && content.trim()) break;
6542
+ workEnd = index;
6543
+ }
6522
6544
  const first = visible[0];
6523
6545
  if (first && (calls.length > 0 || isLatest)) {
6524
6546
  let lastAssistant = -1;
@@ -6526,11 +6548,13 @@ function getTurnWork(rendered, layouts) {
6526
6548
  if (message.role === "assistant") lastAssistant = index;
6527
6549
  });
6528
6550
  const replyText = visible[lastAssistant]?.content;
6529
- const endsWithWork = lastAssistant >= 0 && lastAssistant <= lastWork && typeof replyText === "string" && replyText.trim().length > 0;
6551
+ const endsWithWork = lastAssistant >= 0 && lastAssistant <= workEnd && typeof replyText === "string" && replyText.trim().length > 0;
6552
+ const work = visible.slice(0, workEnd + 1);
6530
6553
  turns.set(key, {
6531
6554
  key,
6532
6555
  firstMessageId: first.id,
6533
- workMessageIds: new Set(visible.slice(0, lastWork + 1).map((message) => message.id)),
6556
+ workMessageIds: new Set(work.map((message) => message.id)),
6557
+ reasoningIds: work.filter((message) => message.role === "reasoning").map((message) => message.id),
6534
6558
  replyTextMessageId: endsWithWork ? visible[lastAssistant].id : void 0,
6535
6559
  calls,
6536
6560
  isLatest
@@ -7411,9 +7435,12 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
7411
7435
  }
7412
7436
  };
7413
7437
  };
7438
+ const isLatestAssistantMessage = message.role === "assistant" && (isLatest ?? messages?.[messages.length - 1]?.id === message.id);
7439
+ const isStreaming = !!isRunning && (isLatest === void 0 && messages === void 0 ? true : isLatestAssistantMessage);
7414
7440
  const boundMarkdownRenderer = renderSlot(markdownRenderer, CopilotChatAssistantMessage.MarkdownRenderer, {
7415
7441
  content: message.content || "",
7416
- messageId: message.id
7442
+ messageId: message.id,
7443
+ mode: isStreaming ? "streaming" : "static"
7417
7444
  });
7418
7445
  const boundCopyButton = renderSlot(copyButton, CopilotChatAssistantMessage.CopyButton, { onClick: async () => {
7419
7446
  if (message.content) return await (0, _copilotkit_shared.copyToClipboard)(message.content);
@@ -7455,7 +7482,6 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
7455
7482
  messages
7456
7483
  });
7457
7484
  const hasContent = !!(message.content && message.content.trim().length > 0);
7458
- const isLatestAssistantMessage = message.role === "assistant" && (isLatest ?? messages?.[messages.length - 1]?.id === message.id);
7459
7485
  const shouldShowToolbar = toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatestAssistantMessage);
7460
7486
  const { open: commentOpen, close: closeComment } = comment;
7461
7487
  (0, react.useEffect)(() => {
@@ -8145,7 +8171,7 @@ function CopilotChatReasoningMessage({ message, messages, isRunning, isLatest: i
8145
8171
  ...headerProps,
8146
8172
  children: [
8147
8173
  /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
8148
- className: "cpk:font-medium",
8174
+ className: (0, tailwind_merge.twMerge)("cpk:font-medium", isStreaming && "cpk-shimmer"),
8149
8175
  children: label
8150
8176
  }),
8151
8177
  isStreaming && !hasContent && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
@@ -8795,25 +8821,14 @@ const MemoizedCustomMessage = react.default.memo(function MemoizedCustomMessage(
8795
8821
  return true;
8796
8822
  });
8797
8823
  /**
8798
- * Deduplicates messages by ID. For assistant messages, merges occurrences:
8799
- * recovers non-empty content from any earlier occurrence if the latest wiped it
8800
- * (empty string means the streaming update cleared the field, not blank text),
8801
- * and similarly recovers toolCalls from earlier occurrences if the latest is
8802
- * undefined (an empty array [] is treated as intentional and kept as-is).
8803
- * For all other roles, keeps the last entry.
8804
- *
8805
- * @internal Exported for unit testing only — not part of the public API.
8806
- */
8807
- /**
8808
8824
  * Collapse tool calls that share an id, keeping first-seen order.
8809
8825
  *
8810
- * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
8811
- * without checking whether that id is already present. So whenever a start
8812
- * event is applied twice — which the human-in-the-loop flow triggers when the
8813
- * run syncs after `respond()` — the message ends up carrying the same call
8814
- * twice. The second copy has EMPTY `arguments`, because a start event carries
8815
- * none; the args arrive later as TOOL_CALL_ARGS deltas addressed to the first
8816
- * copy.
8826
+ * Older AG-UI clients appended to the parent message's `toolCalls` without
8827
+ * checking whether that id was already present. So whenever a start event was
8828
+ * applied twice — which the human-in-the-loop flow triggers when the run syncs
8829
+ * after `respond()` — the message ended up carrying the same call twice. The
8830
+ * second copy has EMPTY `arguments`, because a start event carries none; the
8831
+ * args arrive later as TOOL_CALL_ARGS deltas addressed to the first copy.
8817
8832
  *
8818
8833
  * Left alone that renders the same tool call twice: once populated and once
8819
8834
  * blank (an approval card with no transaction id, offering live buttons for an
@@ -8835,13 +8850,42 @@ function dedupeToolCalls(toolCalls) {
8835
8850
  }
8836
8851
  return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
8837
8852
  }
8853
+ /**
8854
+ * Unite the tool calls of two occurrences of the same assistant message,
8855
+ * keeping first-seen order. Each occurrence can hold only some of the calls,
8856
+ * so neither list may replace the other.
8857
+ *
8858
+ * For an id present in both, the later occurrence wins when it carries
8859
+ * arguments: it is the newer streaming update. A blank later copy never
8860
+ * replaces a populated one.
8861
+ */
8862
+ function mergeToolCalls(earlier, later) {
8863
+ const byId = new Map(earlier.map((toolCall) => [toolCall.id, toolCall]));
8864
+ for (const toolCall of later) {
8865
+ const existing = byId.get(toolCall.id);
8866
+ if (!existing || toolCall.function?.arguments || !existing.function?.arguments) byId.set(toolCall.id, toolCall);
8867
+ }
8868
+ return [...byId.values()];
8869
+ }
8870
+ /**
8871
+ * Deduplicates messages by ID. For assistant messages, merges occurrences:
8872
+ * recovers non-empty content from any earlier occurrence if the latest wiped it
8873
+ * (empty string means the streaming update cleared the field, not blank text).
8874
+ * Tool calls from every occurrence are kept: a copy can hold only some of the
8875
+ * calls, so when two occurrences both carry tool calls they are united by id.
8876
+ * If the latest has undefined toolCalls they are recovered from earlier
8877
+ * occurrences; an explicit empty array [] is treated as intentional and kept.
8878
+ * For all other roles, keeps the last entry.
8879
+ *
8880
+ * @internal Exported for unit testing only — not part of the public API.
8881
+ */
8838
8882
  function deduplicateMessages(messages) {
8839
8883
  const acc = /* @__PURE__ */ new Map();
8840
8884
  for (const message of messages) {
8841
8885
  const existing = acc.get(message.id);
8842
8886
  if (existing && message.role === "assistant" && existing.role === "assistant") {
8843
8887
  const content = message.content || existing.content;
8844
- const toolCalls = message.toolCalls ?? existing.toolCalls;
8888
+ const toolCalls = message.toolCalls?.length && existing.toolCalls?.length ? mergeToolCalls(dedupeToolCalls(existing.toolCalls), dedupeToolCalls(message.toolCalls)) : message.toolCalls ?? existing.toolCalls;
8845
8889
  acc.set(message.id, {
8846
8890
  ...existing,
8847
8891
  ...message,
@@ -8856,6 +8900,8 @@ function deduplicateMessages(messages) {
8856
8900
  }
8857
8901
  return [...acc.values()];
8858
8902
  }
8903
+ /** At most this many rows are rendered beyond the viewport on either side. */
8904
+ const MAX_OVERSCAN_ROWS = 400;
8859
8905
  /** A row holding a single message, rendered as it would be ungrouped. */
8860
8906
  function messageRow(message) {
8861
8907
  return {
@@ -8871,7 +8917,19 @@ function messageGroup(group) {
8871
8917
  };
8872
8918
  }
8873
8919
  const GROUP_ROW_KEY_PREFIX = "copilotkit-group:";
8920
+ const MESSAGE_ROW_KEY_PREFIX = "copilotkit-message:";
8874
8921
  const VIRTUALIZE_THRESHOLD = 50;
8922
+ /**
8923
+ * How long the scroll position must stay still, with no wheel or touch input,
8924
+ * before a correction held back during scrolling is written to `scrollTop`.
8925
+ */
8926
+ const SCROLL_SETTLE_MS = 250;
8927
+ /**
8928
+ * The most a held correction moves per frame once it is written. Safari can
8929
+ * still drop a write when a new gesture starts in the same frame; a small
8930
+ * step keeps that from showing.
8931
+ */
8932
+ const SETTLE_STEP_PX = 4;
8875
8933
  function CopilotChatMessageView({ messages = [], assistantMessage, userMessage, reasoningMessage, cursor, intelligenceIndicator, workSummary, isRunning = false, transformMessages, groupMessages, messageFeedback = true, toolCallDisplay = "grouped", children, className, ...props }) {
8876
8934
  const isPinnedToBottom = (0, react.useContext)(ScrollPinnedContext);
8877
8935
  const renderCustomMessage = useRenderCustomMessages();
@@ -8975,6 +9033,17 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
8975
9033
  isRunning,
8976
9034
  latestTurnKey
8977
9035
  ]);
9036
+ const supersededReasoning = (0, react.useMemo)(() => {
9037
+ const ids = /* @__PURE__ */ new Set();
9038
+ if (!isRunning) return ids;
9039
+ const turn = turnWork?.get(latestTurnKey);
9040
+ for (const id of turn?.reasoningIds.slice(0, -1) ?? []) ids.add(id);
9041
+ return ids;
9042
+ }, [
9043
+ turnWork,
9044
+ latestTurnKey,
9045
+ isRunning
9046
+ ]);
8978
9047
  const toolCallDisplayContext = (0, react.useMemo)(() => ({
8979
9048
  display: toolCallDisplay,
8980
9049
  isRunning,
@@ -9044,6 +9113,14 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9044
9113
  (0, _copilotkit_shared.commitRowKeyStore)(rowKeyStore, renderedMessages);
9045
9114
  }, [rowKeyStore, renderedMessages]);
9046
9115
  const stableGroupKey = (key) => rowRenderKeys.get(key) ?? key;
9116
+ const rowKey = (row) => row.type === "group" ? `${GROUP_ROW_KEY_PREFIX}${stableGroupKey(row.key)}` : `${MESSAGE_ROW_KEY_PREFIX}${rowRenderKeys.get(row.message.id) ?? row.message.id}`;
9117
+ const previousRowKeysRef = (0, react.useRef)([]);
9118
+ const rowKeys = (0, react.useMemo)(() => {
9119
+ const next = rows.map(rowKey);
9120
+ const previous = previousRowKeysRef.current;
9121
+ return next.length === previous.length && next.every((key, index) => key === previous[index]) ? previous : next;
9122
+ }, [rows, rowRenderKeys]);
9123
+ previousRowKeysRef.current = rowKeys;
9047
9124
  const groupStateRef = (0, react.useRef)(/* @__PURE__ */ new Map());
9048
9125
  const groupSettersRef = (0, react.useRef)(/* @__PURE__ */ new Map());
9049
9126
  const groupStateThreadRef = (0, react.useRef)(config?.threadId);
@@ -9127,24 +9204,75 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9127
9204
  ]);
9128
9205
  const measuredRef = react.default.useRef({
9129
9206
  total: 0,
9130
- sizes: /* @__PURE__ */ new Map()
9207
+ sizes: /* @__PURE__ */ new Map(),
9208
+ estimates: /* @__PURE__ */ new Map()
9131
9209
  });
9210
+ const rowKeysRef = react.default.useRef(rowKeys);
9211
+ rowKeysRef.current = rowKeys;
9132
9212
  const resizeAnchorRef = react.default.useRef(null);
9133
9213
  const restoringVisibilityRef = react.default.useRef(false);
9214
+ const heldOffsetRef = react.default.useRef(0);
9215
+ const spacerRef = react.default.useRef(null);
9216
+ const shiftedRowsRef = react.default.useRef(null);
9217
+ const lastMeasuredRef = react.default.useRef(null);
9218
+ const userScrollingRef = react.default.useRef(false);
9219
+ const ownScrollWriteRef = react.default.useRef(null);
9220
+ const renderedTotalRef = (0, react.useRef)(0);
9221
+ const applyHeldOffset = react.default.useCallback(() => {
9222
+ const held = heldOffsetRef.current;
9223
+ if (spacerRef.current) spacerRef.current.style.height = `${renderedTotalRef.current - held}px`;
9224
+ if (shiftedRowsRef.current) shiftedRowsRef.current.style.transform = held ? `translateY(${-held}px)` : "";
9225
+ }, []);
9226
+ const keepListTopInView = react.default.useCallback((scrollTop) => {
9227
+ if (heldOffsetRef.current >= 0 || scrollTop + heldOffsetRef.current >= 0) return false;
9228
+ heldOffsetRef.current = scrollTop > 0 ? -scrollTop : 0;
9229
+ return true;
9230
+ }, []);
9231
+ const releaseHeldOffset = react.default.useCallback((element, amount) => {
9232
+ if (amount === 0) return;
9233
+ const scrollTop = element.scrollTop;
9234
+ heldOffsetRef.current -= amount;
9235
+ applyHeldOffset();
9236
+ const target = Math.max(0, scrollTop + amount);
9237
+ ownScrollWriteRef.current = target;
9238
+ element.scrollTop = target;
9239
+ }, [applyHeldOffset]);
9134
9240
  const firstMessageId = deduplicatedMessages[0]?.id;
9135
9241
  const measuredThreadRef = react.default.useRef(firstMessageId);
9136
9242
  if (measuredThreadRef.current !== firstMessageId) {
9137
9243
  measuredThreadRef.current = firstMessageId;
9138
9244
  resizeAnchorRef.current = null;
9245
+ heldOffsetRef.current = 0;
9139
9246
  measuredRef.current = {
9140
9247
  total: 0,
9141
- sizes: /* @__PURE__ */ new Map()
9248
+ sizes: /* @__PURE__ */ new Map(),
9249
+ estimates: /* @__PURE__ */ new Map()
9142
9250
  };
9143
9251
  }
9144
- const estimateRowSize = react.default.useCallback(() => {
9145
- const { total, sizes } = measuredRef.current;
9146
- return sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;
9252
+ const measuredKeysRef = react.default.useRef(rowKeys);
9253
+ if (measuredKeysRef.current !== rowKeys) {
9254
+ measuredKeysRef.current = rowKeys;
9255
+ const live = new Set(rowKeys);
9256
+ const measured = measuredRef.current;
9257
+ for (const [key, height] of measured.sizes) if (!live.has(key)) {
9258
+ measured.sizes.delete(key);
9259
+ measured.total -= height;
9260
+ }
9261
+ for (const key of measured.estimates.keys()) if (!live.has(key)) measured.estimates.delete(key);
9262
+ }
9263
+ const estimateRowSize = react.default.useCallback((index) => {
9264
+ const { total, sizes, estimates } = measuredRef.current;
9265
+ const mean = sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;
9266
+ const key = rowKeysRef.current[index];
9267
+ if (key === void 0) return mean;
9268
+ let estimate = estimates.get(key);
9269
+ if (estimate === void 0) {
9270
+ estimate = mean;
9271
+ estimates.set(key, estimate);
9272
+ }
9273
+ return estimate;
9147
9274
  }, []);
9275
+ const getRowKey = react.default.useCallback((index) => rowKeys[index] ?? index, [rowKeys]);
9148
9276
  const isPinnedToBottomRef = react.default.useRef(isPinnedToBottom);
9149
9277
  const measuredWidthRef = react.default.useRef(null);
9150
9278
  const captureResizeAnchor = react.default.useCallback((instance) => {
@@ -9157,7 +9285,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9157
9285
  };
9158
9286
  return;
9159
9287
  }
9160
- const offset = instance.scrollElement?.scrollTop ?? 0;
9288
+ const offset = (instance.scrollElement?.scrollTop ?? 0) + heldOffsetRef.current;
9161
9289
  const anchor = instance.getVirtualItemForOffset(offset);
9162
9290
  if (anchor) resizeAnchorRef.current = {
9163
9291
  index: anchor.index,
@@ -9167,19 +9295,46 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9167
9295
  }, []);
9168
9296
  const measureRowElement = react.default.useCallback((el, _entry, instance) => {
9169
9297
  captureResizeAnchor(instance);
9170
- const height = el?.getBoundingClientRect().height ?? 0;
9298
+ const rect = el?.getBoundingClientRect();
9299
+ const height = rect?.height ?? 0;
9171
9300
  const index = Number(el?.dataset?.index);
9172
- if (height > 0 && Number.isInteger(index)) {
9301
+ const key = Number.isInteger(index) ? rowKeysRef.current[index] : void 0;
9302
+ const viewportTop = typeof rect?.top === "number" ? instance.scrollElement?.getBoundingClientRect().top : void 0;
9303
+ lastMeasuredRef.current = Number.isInteger(index) && typeof rect?.top === "number" && typeof viewportTop === "number" ? {
9304
+ index,
9305
+ above: rect.top < viewportTop
9306
+ } : null;
9307
+ const hidden = !el?.isConnected || !instance.scrollElement?.clientHeight;
9308
+ if ((height > 0 || !hidden) && key !== void 0) {
9173
9309
  const { total, sizes } = measuredRef.current;
9174
- measuredRef.current.total = total - (sizes.get(index) ?? 0) + height;
9175
- sizes.set(index, height);
9310
+ measuredRef.current.total = total - (sizes.get(key) ?? 0) + height;
9311
+ sizes.set(key, height);
9176
9312
  }
9177
- return height > 0 ? height : measuredRef.current.sizes.get(index) ?? 100;
9313
+ return height > 0 || !hidden ? height : (key === void 0 ? void 0 : measuredRef.current.sizes.get(key)) ?? 100;
9178
9314
  }, [captureResizeAnchor]);
9179
- const shouldAdjustScrollOnResize = react.default.useCallback((item, _delta, instance) => {
9315
+ const shouldAdjustScrollOnResize = react.default.useCallback((item, delta, instance) => {
9316
+ const measured = lastMeasuredRef.current;
9317
+ lastMeasuredRef.current = null;
9180
9318
  if (isPinnedToBottomRef.current || resizeAnchorRef.current || restoringVisibilityRef.current) return false;
9181
9319
  const scrollAdjustments = instance.scrollAdjustments ?? 0;
9182
- return item.start < (instance.scrollOffset ?? 0) + scrollAdjustments;
9320
+ if (!(measured?.index === item.index ? measured.above : item.start < (instance.scrollOffset ?? 0) + scrollAdjustments)) return false;
9321
+ if (userScrollingRef.current || heldOffsetRef.current !== 0) {
9322
+ const held = heldOffsetRef.current;
9323
+ heldOffsetRef.current += delta;
9324
+ keepListTopInView(instance.scrollElement?.scrollTop ?? 0);
9325
+ instance.scrollOffset = (instance.scrollOffset ?? 0) + heldOffsetRef.current - held;
9326
+ return false;
9327
+ }
9328
+ return true;
9329
+ }, [keepListTopInView]);
9330
+ const observeListOffset = react.default.useCallback((instance, notify) => (0, _tanstack_react_virtual.observeElementOffset)(instance, (offset, isScrolling) => {
9331
+ if (keepListTopInView(offset)) applyHeldOffset();
9332
+ notify(offset + heldOffsetRef.current, isScrolling);
9333
+ }), [keepListTopInView, applyHeldOffset]);
9334
+ const scrollToListOffset = react.default.useCallback((offset, options, instance) => {
9335
+ const elementOffset = offset - heldOffsetRef.current;
9336
+ ownScrollWriteRef.current = elementOffset + (options.adjustments ?? 0);
9337
+ (0, _tanstack_react_virtual.elementScroll)(elementOffset, options, instance);
9183
9338
  }, []);
9184
9339
  const observeScrollRect = react.default.useCallback((instance, notify) => {
9185
9340
  let frame;
@@ -9210,7 +9365,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9210
9365
  instance.getTotalSize();
9211
9366
  measuredRef.current = {
9212
9367
  total: 0,
9213
- sizes: /* @__PURE__ */ new Map()
9368
+ sizes: /* @__PURE__ */ new Map(),
9369
+ estimates: /* @__PURE__ */ new Map()
9214
9370
  };
9215
9371
  instance.elementsCache.forEach((element) => {
9216
9372
  measureRowElement(element, void 0, instance);
@@ -9235,27 +9391,120 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9235
9391
  resizeAnchorRef.current = null;
9236
9392
  };
9237
9393
  }, [captureResizeAnchor, measureRowElement]);
9394
+ const virtualizerRef = (0, react.useRef)(null);
9395
+ const rangeExtractor = react.default.useCallback((range) => {
9396
+ const instance = virtualizerRef.current;
9397
+ const items = instance?.measurementsCache;
9398
+ const reach = instance?.scrollRect?.height ?? 0;
9399
+ if (!items || items.length !== range.count || reach <= 0) return (0, _tanstack_react_virtual.defaultRangeExtractor)(range);
9400
+ let start = range.startIndex;
9401
+ for (let above = 0; start > 0 && range.startIndex - start < MAX_OVERSCAN_ROWS && (range.startIndex - start < range.overscan || above < reach);) {
9402
+ start -= 1;
9403
+ above += items[start].size;
9404
+ }
9405
+ let end = range.endIndex;
9406
+ for (let below = 0; end < range.count - 1 && end - range.endIndex < MAX_OVERSCAN_ROWS && (end - range.endIndex < range.overscan || below < reach);) {
9407
+ end += 1;
9408
+ below += items[end].size;
9409
+ }
9410
+ const indexes = [];
9411
+ for (let index = start; index <= end; index++) indexes.push(index);
9412
+ return indexes;
9413
+ }, []);
9238
9414
  const virtualizer = (0, _tanstack_react_virtual.useVirtualizer)({
9239
9415
  count: shouldVirtualize ? rows.length : 0,
9240
9416
  getScrollElement: () => shouldVirtualize ? scrollElement : null,
9241
9417
  observeElementRect: observeScrollRect,
9418
+ observeElementOffset: observeListOffset,
9419
+ scrollToFn: scrollToListOffset,
9242
9420
  estimateSize: estimateRowSize,
9421
+ getItemKey: getRowKey,
9243
9422
  overscan: 5,
9423
+ rangeExtractor,
9244
9424
  measureElement: measureRowElement,
9245
9425
  initialRect: {
9246
9426
  width: 0,
9247
9427
  height: 600
9248
9428
  }
9249
9429
  });
9430
+ virtualizerRef.current = virtualizer;
9431
+ renderedTotalRef.current = virtualizer.getTotalSize();
9432
+ (0, react.useLayoutEffect)(applyHeldOffset);
9433
+ (0, react.useEffect)(() => {
9434
+ const element = shouldVirtualize ? scrollElement : null;
9435
+ if (!element) return;
9436
+ let settleTimer;
9437
+ let settleFrame;
9438
+ let touching = false;
9439
+ const settleStep = () => {
9440
+ settleFrame = void 0;
9441
+ const held = heldOffsetRef.current;
9442
+ if (userScrollingRef.current || touching || held === 0) return;
9443
+ releaseHeldOffset(element, Math.sign(held) * Math.min(Math.abs(held), SETTLE_STEP_PX));
9444
+ if (heldOffsetRef.current !== 0) settleFrame = requestAnimationFrame(settleStep);
9445
+ };
9446
+ const settle = () => {
9447
+ settleTimer = void 0;
9448
+ if (touching) return;
9449
+ userScrollingRef.current = false;
9450
+ if (heldOffsetRef.current !== 0 && settleFrame === void 0) settleFrame = requestAnimationFrame(settleStep);
9451
+ };
9452
+ const scrolling = () => {
9453
+ userScrollingRef.current = true;
9454
+ if (settleFrame !== void 0) {
9455
+ cancelAnimationFrame(settleFrame);
9456
+ settleFrame = void 0;
9457
+ }
9458
+ if (settleTimer !== void 0) clearTimeout(settleTimer);
9459
+ settleTimer = setTimeout(settle, SCROLL_SETTLE_MS);
9460
+ };
9461
+ const onScroll = () => {
9462
+ const own = ownScrollWriteRef.current;
9463
+ if (own !== null && Math.abs(element.scrollTop - own) < 1) {
9464
+ ownScrollWriteRef.current = null;
9465
+ return;
9466
+ }
9467
+ scrolling();
9468
+ };
9469
+ const onTouchStart = () => {
9470
+ touching = true;
9471
+ scrolling();
9472
+ };
9473
+ const onTouchEnd = () => {
9474
+ touching = false;
9475
+ scrolling();
9476
+ };
9477
+ element.addEventListener("scroll", onScroll, { passive: true });
9478
+ element.addEventListener("wheel", scrolling, { passive: true });
9479
+ element.addEventListener("touchstart", onTouchStart, { passive: true });
9480
+ element.addEventListener("touchend", onTouchEnd, { passive: true });
9481
+ element.addEventListener("touchcancel", onTouchEnd, { passive: true });
9482
+ return () => {
9483
+ if (settleTimer !== void 0) clearTimeout(settleTimer);
9484
+ if (settleFrame !== void 0) cancelAnimationFrame(settleFrame);
9485
+ userScrollingRef.current = false;
9486
+ element.removeEventListener("scroll", onScroll);
9487
+ element.removeEventListener("wheel", scrolling);
9488
+ element.removeEventListener("touchstart", onTouchStart);
9489
+ element.removeEventListener("touchend", onTouchEnd);
9490
+ element.removeEventListener("touchcancel", onTouchEnd);
9491
+ };
9492
+ }, [
9493
+ shouldVirtualize,
9494
+ scrollElement,
9495
+ releaseHeldOffset
9496
+ ]);
9250
9497
  isPinnedToBottomRef.current = isPinnedToBottom;
9251
9498
  virtualizer.shouldAdjustScrollPositionOnItemSizeChange = shouldAdjustScrollOnResize;
9252
9499
  (0, react.useLayoutEffect)(() => {
9253
9500
  const anchor = resizeAnchorRef.current;
9254
9501
  if (!anchor?.ready || restoringVisibilityRef.current) return;
9502
+ if (scrollElement) releaseHeldOffset(scrollElement, heldOffsetRef.current);
9255
9503
  const position = virtualizer.getOffsetForIndex(anchor.index, "start");
9256
9504
  if (position && !isPinnedToBottomRef.current) {
9257
9505
  const target = position[0] + anchor.offset;
9258
- if (Math.abs((scrollElement?.scrollTop ?? 0) - target) > .5) virtualizer.scrollToOffset(target);
9506
+ const listOffset = (scrollElement?.scrollTop ?? 0) + heldOffsetRef.current;
9507
+ if (Math.abs(listOffset - target) > .5) virtualizer.scrollToOffset(target);
9259
9508
  }
9260
9509
  const frame = requestAnimationFrame(() => {
9261
9510
  if (resizeAnchorRef.current === anchor) resizeAnchorRef.current = null;
@@ -9309,7 +9558,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9309
9558
  slotProps: reasoningSlotProps
9310
9559
  }, rowKey);
9311
9560
  elements.push(toolCallDisplay === "turn" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Collapsible, {
9312
- open: workOpen.get(message.id) ?? true,
9561
+ open: (workOpen.get(message.id) ?? true) && !supersededReasoning.has(message.id),
9313
9562
  children: reasoning
9314
9563
  }, rowKey) : reasoning);
9315
9564
  }
@@ -9327,7 +9576,6 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9327
9576
  }, `intelligence-${intelligenceTurnId}`));
9328
9577
  return elements.filter(Boolean);
9329
9578
  };
9330
- const rowKey = (row) => row.type === "group" ? `${GROUP_ROW_KEY_PREFIX}${stableGroupKey(row.key)}` : rowRenderKeys.get(row.message.id) ?? row.message.id;
9331
9579
  const renderRow = (row) => {
9332
9580
  if (row.type === "message") return renderMessageBlock(row.message);
9333
9581
  const Wrapper = row.wrapper;
@@ -9340,8 +9588,6 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9340
9588
  children: row.messages.flatMap(renderMessageBlock)
9341
9589
  }, rowKey(row))];
9342
9590
  };
9343
- const rowKeysRef = (0, react.useRef)([]);
9344
- rowKeysRef.current = rows.map(rowKey);
9345
9591
  const virtualModeRef = (0, react.useRef)(shouldVirtualize);
9346
9592
  virtualModeRef.current = shouldVirtualize;
9347
9593
  (0, react.useEffect)(() => {
@@ -9476,26 +9722,37 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9476
9722
  ...props,
9477
9723
  children: [
9478
9724
  shouldVirtualize ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9725
+ ref: spacerRef,
9479
9726
  style: {
9480
- height: virtualizer.getTotalSize(),
9727
+ height: renderedTotalRef.current - heldOffsetRef.current,
9481
9728
  position: "relative",
9482
9729
  overflowAnchor: "none"
9483
9730
  },
9484
- children: virtualizer.getVirtualItems().map((virtualItem) => {
9485
- const row = rows[virtualItem.index];
9486
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9487
- "data-index": virtualItem.index,
9488
- "data-scroll-anchor": rowKey(row),
9489
- ref: virtualizer.measureElement,
9490
- style: {
9491
- position: "absolute",
9492
- top: 0,
9493
- left: 0,
9494
- width: "100%",
9495
- transform: `translateY(${virtualItem.start}px)`
9496
- },
9497
- children: renderRow(row)
9498
- }, rowKey(row));
9731
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9732
+ ref: shiftedRowsRef,
9733
+ style: {
9734
+ position: "absolute",
9735
+ top: 0,
9736
+ left: 0,
9737
+ width: "100%",
9738
+ transform: heldOffsetRef.current ? `translateY(${-heldOffsetRef.current}px)` : void 0
9739
+ },
9740
+ children: virtualizer.getVirtualItems().map((virtualItem) => {
9741
+ const row = rows[virtualItem.index];
9742
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9743
+ "data-index": virtualItem.index,
9744
+ "data-scroll-anchor": rowKey(row),
9745
+ ref: virtualizer.measureElement,
9746
+ style: {
9747
+ position: "absolute",
9748
+ top: 0,
9749
+ left: 0,
9750
+ width: "100%",
9751
+ transform: `translateY(${virtualItem.start}px)`
9752
+ },
9753
+ children: renderRow(row)
9754
+ }, rowKey(row));
9755
+ })
9499
9756
  })
9500
9757
  }) : messageElements,
9501
9758
  interruptElement,
@@ -10376,7 +10633,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10376
10633
  ...props,
10377
10634
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Loader2, {
10378
10635
  "aria-hidden": "true",
10379
- className: "cpk:size-6 cpk:animate-spin cpk:text-muted-foreground"
10636
+ className: "cpk:size-6 cpk:text-muted-foreground cpk:*:origin-center cpk:*:animate-spin"
10380
10637
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
10381
10638
  className: "cpk:sr-only",
10382
10639
  children: labels.chatConnectingLabel
@@ -14993,4 +15250,4 @@ Object.defineProperty(exports, 'useToast', {
14993
15250
  return useToast;
14994
15251
  }
14995
15252
  });
14996
- //# sourceMappingURL=copilotkit-DFxtDD2N.cjs.map
15253
+ //# sourceMappingURL=copilotkit-DHJJxCeI.cjs.map