@copilotkit/react-core 1.88.0 → 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.
@@ -1326,7 +1326,7 @@ function useRenderToolCall() {
1326
1326
 
1327
1327
  //#endregion
1328
1328
  //#region package.json
1329
- var version = "1.88.0";
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];
@@ -7430,9 +7435,12 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
7430
7435
  }
7431
7436
  };
7432
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);
7433
7440
  const boundMarkdownRenderer = renderSlot(markdownRenderer, CopilotChatAssistantMessage.MarkdownRenderer, {
7434
7441
  content: message.content || "",
7435
- messageId: message.id
7442
+ messageId: message.id,
7443
+ mode: isStreaming ? "streaming" : "static"
7436
7444
  });
7437
7445
  const boundCopyButton = renderSlot(copyButton, CopilotChatAssistantMessage.CopyButton, { onClick: async () => {
7438
7446
  if (message.content) return await (0, _copilotkit_shared.copyToClipboard)(message.content);
@@ -7474,7 +7482,6 @@ function CopilotChatAssistantMessage({ message, messages, isRunning, isLatest, o
7474
7482
  messages
7475
7483
  });
7476
7484
  const hasContent = !!(message.content && message.content.trim().length > 0);
7477
- const isLatestAssistantMessage = message.role === "assistant" && (isLatest ?? messages?.[messages.length - 1]?.id === message.id);
7478
7485
  const shouldShowToolbar = toolbarVisible && (hasContent || showInspectorShortcut) && !(isRunning && isLatestAssistantMessage);
7479
7486
  const { open: commentOpen, close: closeComment } = comment;
7480
7487
  (0, react.useEffect)(() => {
@@ -8814,25 +8821,14 @@ const MemoizedCustomMessage = react.default.memo(function MemoizedCustomMessage(
8814
8821
  return true;
8815
8822
  });
8816
8823
  /**
8817
- * Deduplicates messages by ID. For assistant messages, merges occurrences:
8818
- * recovers non-empty content from any earlier occurrence if the latest wiped it
8819
- * (empty string means the streaming update cleared the field, not blank text),
8820
- * and similarly recovers toolCalls from earlier occurrences if the latest is
8821
- * undefined (an empty array [] is treated as intentional and kept as-is).
8822
- * For all other roles, keeps the last entry.
8823
- *
8824
- * @internal Exported for unit testing only — not part of the public API.
8825
- */
8826
- /**
8827
8824
  * Collapse tool calls that share an id, keeping first-seen order.
8828
8825
  *
8829
- * AG-UI's TOOL_CALL_START handler appends to the parent message's `toolCalls`
8830
- * without checking whether that id is already present. So whenever a start
8831
- * event is applied twice — which the human-in-the-loop flow triggers when the
8832
- * run syncs after `respond()` — the message ends up carrying the same call
8833
- * twice. The second copy has EMPTY `arguments`, because a start event carries
8834
- * none; the args arrive later as TOOL_CALL_ARGS deltas addressed to the first
8835
- * 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.
8836
8832
  *
8837
8833
  * Left alone that renders the same tool call twice: once populated and once
8838
8834
  * blank (an approval card with no transaction id, offering live buttons for an
@@ -8854,13 +8850,42 @@ function dedupeToolCalls(toolCalls) {
8854
8850
  }
8855
8851
  return byId.size === toolCalls.length ? toolCalls : [...byId.values()];
8856
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
+ */
8857
8882
  function deduplicateMessages(messages) {
8858
8883
  const acc = /* @__PURE__ */ new Map();
8859
8884
  for (const message of messages) {
8860
8885
  const existing = acc.get(message.id);
8861
8886
  if (existing && message.role === "assistant" && existing.role === "assistant") {
8862
8887
  const content = message.content || existing.content;
8863
- 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;
8864
8889
  acc.set(message.id, {
8865
8890
  ...existing,
8866
8891
  ...message,
@@ -8875,6 +8900,8 @@ function deduplicateMessages(messages) {
8875
8900
  }
8876
8901
  return [...acc.values()];
8877
8902
  }
8903
+ /** At most this many rows are rendered beyond the viewport on either side. */
8904
+ const MAX_OVERSCAN_ROWS = 400;
8878
8905
  /** A row holding a single message, rendered as it would be ungrouped. */
8879
8906
  function messageRow(message) {
8880
8907
  return {
@@ -8892,6 +8919,17 @@ function messageGroup(group) {
8892
8919
  const GROUP_ROW_KEY_PREFIX = "copilotkit-group:";
8893
8920
  const MESSAGE_ROW_KEY_PREFIX = "copilotkit-message:";
8894
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;
8895
8933
  function CopilotChatMessageView({ messages = [], assistantMessage, userMessage, reasoningMessage, cursor, intelligenceIndicator, workSummary, isRunning = false, transformMessages, groupMessages, messageFeedback = true, toolCallDisplay = "grouped", children, className, ...props }) {
8896
8934
  const isPinnedToBottom = (0, react.useContext)(ScrollPinnedContext);
8897
8935
  const renderCustomMessage = useRenderCustomMessages();
@@ -9166,20 +9204,49 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9166
9204
  ]);
9167
9205
  const measuredRef = react.default.useRef({
9168
9206
  total: 0,
9169
- sizes: /* @__PURE__ */ new Map()
9207
+ sizes: /* @__PURE__ */ new Map(),
9208
+ estimates: /* @__PURE__ */ new Map()
9170
9209
  });
9171
9210
  const rowKeysRef = react.default.useRef(rowKeys);
9172
9211
  rowKeysRef.current = rowKeys;
9173
9212
  const resizeAnchorRef = react.default.useRef(null);
9174
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]);
9175
9240
  const firstMessageId = deduplicatedMessages[0]?.id;
9176
9241
  const measuredThreadRef = react.default.useRef(firstMessageId);
9177
9242
  if (measuredThreadRef.current !== firstMessageId) {
9178
9243
  measuredThreadRef.current = firstMessageId;
9179
9244
  resizeAnchorRef.current = null;
9245
+ heldOffsetRef.current = 0;
9180
9246
  measuredRef.current = {
9181
9247
  total: 0,
9182
- sizes: /* @__PURE__ */ new Map()
9248
+ sizes: /* @__PURE__ */ new Map(),
9249
+ estimates: /* @__PURE__ */ new Map()
9183
9250
  };
9184
9251
  }
9185
9252
  const measuredKeysRef = react.default.useRef(rowKeys);
@@ -9191,10 +9258,19 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9191
9258
  measured.sizes.delete(key);
9192
9259
  measured.total -= height;
9193
9260
  }
9261
+ for (const key of measured.estimates.keys()) if (!live.has(key)) measured.estimates.delete(key);
9194
9262
  }
9195
- const estimateRowSize = react.default.useCallback(() => {
9196
- const { total, sizes } = measuredRef.current;
9197
- return sizes.size > 0 ? Math.max(1, Math.round(total / sizes.size)) : 100;
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;
9198
9274
  }, []);
9199
9275
  const getRowKey = react.default.useCallback((index) => rowKeys[index] ?? index, [rowKeys]);
9200
9276
  const isPinnedToBottomRef = react.default.useRef(isPinnedToBottom);
@@ -9209,7 +9285,7 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9209
9285
  };
9210
9286
  return;
9211
9287
  }
9212
- const offset = instance.scrollElement?.scrollTop ?? 0;
9288
+ const offset = (instance.scrollElement?.scrollTop ?? 0) + heldOffsetRef.current;
9213
9289
  const anchor = instance.getVirtualItemForOffset(offset);
9214
9290
  if (anchor) resizeAnchorRef.current = {
9215
9291
  index: anchor.index,
@@ -9219,20 +9295,46 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9219
9295
  }, []);
9220
9296
  const measureRowElement = react.default.useCallback((el, _entry, instance) => {
9221
9297
  captureResizeAnchor(instance);
9222
- const height = el?.getBoundingClientRect().height ?? 0;
9298
+ const rect = el?.getBoundingClientRect();
9299
+ const height = rect?.height ?? 0;
9223
9300
  const index = Number(el?.dataset?.index);
9224
9301
  const key = Number.isInteger(index) ? rowKeysRef.current[index] : void 0;
9225
- if (height > 0 && key !== 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) {
9226
9309
  const { total, sizes } = measuredRef.current;
9227
9310
  measuredRef.current.total = total - (sizes.get(key) ?? 0) + height;
9228
9311
  sizes.set(key, height);
9229
9312
  }
9230
- return height > 0 ? height : (key === void 0 ? void 0 : measuredRef.current.sizes.get(key)) ?? 100;
9313
+ return height > 0 || !hidden ? height : (key === void 0 ? void 0 : measuredRef.current.sizes.get(key)) ?? 100;
9231
9314
  }, [captureResizeAnchor]);
9232
- 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;
9233
9318
  if (isPinnedToBottomRef.current || resizeAnchorRef.current || restoringVisibilityRef.current) return false;
9234
9319
  const scrollAdjustments = instance.scrollAdjustments ?? 0;
9235
- 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);
9236
9338
  }, []);
9237
9339
  const observeScrollRect = react.default.useCallback((instance, notify) => {
9238
9340
  let frame;
@@ -9263,7 +9365,8 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9263
9365
  instance.getTotalSize();
9264
9366
  measuredRef.current = {
9265
9367
  total: 0,
9266
- sizes: /* @__PURE__ */ new Map()
9368
+ sizes: /* @__PURE__ */ new Map(),
9369
+ estimates: /* @__PURE__ */ new Map()
9267
9370
  };
9268
9371
  instance.elementsCache.forEach((element) => {
9269
9372
  measureRowElement(element, void 0, instance);
@@ -9288,28 +9391,120 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9288
9391
  resizeAnchorRef.current = null;
9289
9392
  };
9290
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
+ }, []);
9291
9414
  const virtualizer = (0, _tanstack_react_virtual.useVirtualizer)({
9292
9415
  count: shouldVirtualize ? rows.length : 0,
9293
9416
  getScrollElement: () => shouldVirtualize ? scrollElement : null,
9294
9417
  observeElementRect: observeScrollRect,
9418
+ observeElementOffset: observeListOffset,
9419
+ scrollToFn: scrollToListOffset,
9295
9420
  estimateSize: estimateRowSize,
9296
9421
  getItemKey: getRowKey,
9297
9422
  overscan: 5,
9423
+ rangeExtractor,
9298
9424
  measureElement: measureRowElement,
9299
9425
  initialRect: {
9300
9426
  width: 0,
9301
9427
  height: 600
9302
9428
  }
9303
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
+ ]);
9304
9497
  isPinnedToBottomRef.current = isPinnedToBottom;
9305
9498
  virtualizer.shouldAdjustScrollPositionOnItemSizeChange = shouldAdjustScrollOnResize;
9306
9499
  (0, react.useLayoutEffect)(() => {
9307
9500
  const anchor = resizeAnchorRef.current;
9308
9501
  if (!anchor?.ready || restoringVisibilityRef.current) return;
9502
+ if (scrollElement) releaseHeldOffset(scrollElement, heldOffsetRef.current);
9309
9503
  const position = virtualizer.getOffsetForIndex(anchor.index, "start");
9310
9504
  if (position && !isPinnedToBottomRef.current) {
9311
9505
  const target = position[0] + anchor.offset;
9312
- 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);
9313
9508
  }
9314
9509
  const frame = requestAnimationFrame(() => {
9315
9510
  if (resizeAnchorRef.current === anchor) resizeAnchorRef.current = null;
@@ -9527,26 +9722,37 @@ function CopilotChatMessageView({ messages = [], assistantMessage, userMessage,
9527
9722
  ...props,
9528
9723
  children: [
9529
9724
  shouldVirtualize ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9725
+ ref: spacerRef,
9530
9726
  style: {
9531
- height: virtualizer.getTotalSize(),
9727
+ height: renderedTotalRef.current - heldOffsetRef.current,
9532
9728
  position: "relative",
9533
9729
  overflowAnchor: "none"
9534
9730
  },
9535
- children: virtualizer.getVirtualItems().map((virtualItem) => {
9536
- const row = rows[virtualItem.index];
9537
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
9538
- "data-index": virtualItem.index,
9539
- "data-scroll-anchor": rowKey(row),
9540
- ref: virtualizer.measureElement,
9541
- style: {
9542
- position: "absolute",
9543
- top: 0,
9544
- left: 0,
9545
- width: "100%",
9546
- transform: `translateY(${virtualItem.start}px)`
9547
- },
9548
- children: renderRow(row)
9549
- }, 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
+ })
9550
9756
  })
9551
9757
  }) : messageElements,
9552
9758
  interruptElement,
@@ -10427,7 +10633,7 @@ function CopilotChatView({ messageView, input, scrollView, suggestionView, welco
10427
10633
  ...props,
10428
10634
  children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Loader2, {
10429
10635
  "aria-hidden": "true",
10430
- 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"
10431
10637
  }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
10432
10638
  className: "cpk:sr-only",
10433
10639
  children: labels.chatConnectingLabel
@@ -15044,4 +15250,4 @@ Object.defineProperty(exports, 'useToast', {
15044
15250
  return useToast;
15045
15251
  }
15046
15252
  });
15047
- //# sourceMappingURL=copilotkit-D4AAgBT1.cjs.map
15253
+ //# sourceMappingURL=copilotkit-DHJJxCeI.cjs.map