Skip to content

πŸ› Bug: Virtual scrolling jitters badly with messages of varying heightsΒ #6089

Open

Description

@891806797

♻️ Reproduction Steps

  1. Description

When the chat message list contains messages with significantly different heights β€” especially long code blocks or SQL
output β€” scrolling feels extremely jittery. The content "jumps" in chunks rather than scrolling smoothly. It feels
like the virtual scroller is repeatedly recalculating and snapping to incorrect positions during scroll.

Steps to reproduce

  1. Have a conversation with a mix of short text messages and very long code block messages (e.g. 50+ line SQL scripts)
  2. Scroll up and down through the history
  3. Observe: every scroll event causes the viewport content to "hop" β€” jumping by a large chunk instead of moving
    pixel-by-pixel

Expected behavior

Smooth native-like scrolling regardless of message height variance. The scroll position should track the user's scroll
input linearly.

Environment

  • CopilotKit version: @copilotkit/react-core@v2
  • Browser: Electron 34 (Chromium-based)
  • OS: Windows 11

Possible cause

This appears to be related to virtual scrolling with highly variable item sizes. When the virtual list estimates item
heights and the actual rendered height differs greatly (e.g. a code block renders much taller than the estimate), the
scroller recalculates and snaps to a new position, causing the visible "hop."

A common fix in virtual scroll libraries (@tanstack/react-virtual, virtua, etc.) is to measure actual rendered heights
and update the virtualizer's item size cache without snapping. If CopilotKit uses its own virtual scrolling
implementation, it may need similar handling for variable-height items.
3.
...

βœ… Expected Behavior

❌ Actual Behavior

Screenshots

𝌚 CopilotKit Version

-

πŸ“„ Logs (Optional)

Activity

  1. added
    bug
    on Jul 21, 2026
  2. copilotkit-outpost-bot commented on Jul 21, 2026

    @copilotkit-outpost-bot

    🎫 Ticket TKT-34KH6RM3 created. Our AI assistant is reviewing your issue...

  3. copilotkit-outpost-bot commented on Jul 21, 2026

    @copilotkit-outpost-bot

    ⚠️ This is an AI-generated response and may be incomplete. We've escalated this to our engineering team β€” someone will follow up in this thread shortly.

    Jittery Scrolling with Variable-Height Messages

    This is a known pain point with virtual scrolling and variable-height content. You've correctly identified the root cause β€” let me break down what's happening and your options.


    Why This Happens

    Virtual scrollers work by:

    1. Estimating item heights before render
    2. Rendering only visible items
    3. Recalculating positions when actual heights differ from estimates

    When a code block renders at 800px but was estimated at 80px, the virtualizer corrects the total scroll height mid-scroll β†’ position snap/jump.


    Workarounds You Can Try Today

    Option 1: Disable virtual scrolling (simplest fix)

    CopilotKit's <CopilotChat> accepts custom components. You can replace the message list with a plain scrollable div:

    Code example (tsx)
    import { CopilotChat } from "@copilotkit/react-ui";
    
    function MyChat() {
      return (
        <CopilotChat
          // Override the messages container to use native scroll
          // instead of a virtual list
          Messages={(props) => (
            <div
              style={{
                overflowY: "auto",
                height: "100%",
                display: "flex",
                flexDirection: "column",
              }}
            >
              {props.messages.map((msg) => (
                <props.MessageComponent key={msg.id} message={msg} />
              ))}
            </div>
          )}
        />
      );
    }

    ⚠️ This trades scroll performance for smoothness β€” fine for most chat UIs unless you have thousands of messages.


    Option 2: Use virtua with measured sizes

    If you need virtual scrolling, virtua handles dynamic heights better than most alternatives:

    Code example (tsx)
    import { VList } from "virtua";
    
    function MessageList({ messages }) {
      return (
        <VList style={{ height: "100%" }}>
          {messages.map((msg) => (
            <MessageItem key={msg.id} message={msg} />
          ))}
        </VList>
      );
    }

    virtua measures actual rendered heights and updates positions without snapping, which directly addresses your issue.


    Option 3: Increase estimated item size

    If CopilotKit exposes virtualizer config, bumping the estimatedItemSize closer to your average message height reduces correction magnitude:

    </details>tsx
    // Hypothetical config β€” check your CopilotKit version's API
    <CopilotChat
      virtualizerOptions={{
        estimatedItemSize: 200, // bump from default ~50px
      }}
    />
    

    Recommended Action

    Scenario Recommendation
    < 500 messages typical Disable virtual scroll entirely
    Large message histories Switch to virtua
    Want to stay on CopilotKit defaults File a GitHub issue with this repro

    File a Bug Report

    This is worth reporting upstream so the CopilotKit team can address it in the default <CopilotChat> component:

    πŸ‘‰ github.com/CopilotKit/CopilotKit/issues

    Include your repro steps, the Electron/Windows environment, and mention the variable-height code block scenario specifically.


    Would you like help implementing a custom Messages component that bypasses virtual scrolling entirely, or wiring up virtua as a drop-in replacement?


    πŸ€– Generated by CopilotKit AI Support Β· Documentation


    Was this helpful? React with πŸ‘ or πŸ‘Ž

  4. BenTaylorDev commented on Jul 21, 2026

    @BenTaylorDev
    Contributor

    Cross-linking: this is closely related to #5979 β€” both involve the v2 message-list virtualizer (@tanstack/react-virtual in CopilotChatMessageView). This report is the variable-height jitter/hop case; #5979 is the overlap/corruption-after-tab-return case. Keeping both open for now since the triggers differ, but they likely share a fix in the virtualizer's measured-height handling.

  5. copilotkit-outpost-bot commented on Jul 21, 2026

    @copilotkit-outpost-bot

    ⚠️ This is an AI-generated response and may be incomplete. We've escalated this to our engineering team β€” someone will follow up in this thread shortly.

    Thanks for the Cross-Link β€” That's Really Useful Context

    Good detective work connecting these two. You're right that they almost certainly share a root cause.


    The Unified Root Cause

    Both issues trace back to @tanstack/react-virtual's measured-height cache becoming stale or incorrect:

    Issue Trigger Symptom
    This report Variable-height items (code blocks) Jitter/hop during scroll
    #5979 Tab visibility change β†’ layout recalc Overlap/corruption on return

    The common thread: the virtualizer's size cache diverges from actual DOM measurements, and when it corrects, it does so abruptly.


    The Likely Shared Fix

    The fix in @tanstack/react-virtual for both cases is ensuring measureElement is called correctly and that the cache is invalidated on the right lifecycle events:

    Code example (tsx)
    // Current pattern (likely in CopilotChatMessageView.tsx)
    const virtualizer = useVirtualizer({
      count: messages.length,
      getScrollElement: () => scrollRef.current,
      estimateSize: () => 50, // ← static estimate is the problem
    });
    
    // Fixed pattern
    const virtualizer = useVirtualizer({
      count: messages.length,
      getScrollElement: () => scrollRef.current,
      estimateSize: (index) => cachedSizes.current[index] ?? 100, // use last known size
      measureElement: (el) => el?.getBoundingClientRect().height, // explicit measurement
    });
    
    // For the tab-return case (#5979) β€” force remeasure on visibility change
    useEffect(() => {
      const handleVisibilityChange = () => {
        if (document.visibilityState === "visible") {
          virtualizer.measure(); // invalidate entire cache on tab return
        }
      };
      document.addEventListener("visibilitychange", handleVisibilityChange);
      return () =>
        document.removeEventListener("visibilitychange", handleVisibilityChange);
    }, [virtualizer]);

    What to Flag in the GitHub Issues

    Since you're already cross-linking, it's worth explicitly calling out to the maintainers:

    • βœ… Both issues are in CopilotChatMessageView β€” single file, single fix
    • βœ… @tanstack/react-virtual does support dynamic measurement via measureElement β€” it just needs to be wired up correctly
    • βœ… The tab-return case likely needs an explicit virtualizer.measure() call on visibilitychange
    • βœ… Consider bumping @tanstack/react-virtual if the version in use predates the measureElement API stabilization

    Suggested Fix PR Scope

    Code example
    CopilotChatMessageView.tsx
      β”œβ”€β”€ Replace static estimateSize with index-aware cached estimate
      β”œβ”€β”€ Add explicit measureElement callback
      β”œβ”€β”€ Add visibilitychange listener β†’ virtualizer.measure()
      └── Optional: ResizeObserver per message item for dynamic content
    

    A ResizeObserver per message item would also catch cases where content reflows after initial render (e.g. syntax highlighting, image load):

    useEffect(() => {
      if (!itemRef.current) return;
      const ro = new ResizeObserver(() => virtualizer.measureElement(itemRef.current));
      ro.observe(itemRef.current);
      return () => ro.disconnect();
    }, []);

    This is a well-scoped, reproducible bug with a clear fix path β€” good candidate for a community PR if the maintainers are slow to pick it up. Want help drafting the actual patch against CopilotChatMessageView?


    πŸ€– Generated by CopilotKit AI Support Β· Documentation


    Was this helpful? React with πŸ‘ or πŸ‘Ž

  6. linear commented on Jul 21, 2026

    @linear
  7. BenTaylorDev commented on Sep 2, 2026

    @BenTaylorDev
    Contributor

    Status update, since this has picked up a couple of PRs.

    This is still open, and neither PR that linked to it fixes it.

    Both #6564 and #6274 add getItemKey to the virtualizer. That is a reasonable change on its own, because deduplicatedMessages can drop an entry mid-list and shift every later index. It does not address what is reported here. getItemKey re-keys the virtualizer's internal measurement cache, and on an append-only chat, index keys and id keys already agree.

    The mechanism in this report is height variance against a fixed estimate. CopilotChatMessageView.tsx sets estimateSize: () => 100, so a 50-line SQL block measures roughly an order of magnitude larger. Every time such an item enters the overscan window and gets measured, @tanstack/react-virtual applies a scroll correction, which is the hopping you see.

    A fix needs to attack the estimate and the correction behavior, not the cache key. Two directions worth trying:

    • Feed a better estimateSize, for example a per-message estimate derived from content length, so the first measurement delta is small.
    • Set shouldAdjustScrollPositionOnItemSizeChange so measurements of items below the viewport do not shift the current scroll offset.

    Anyone picking this up: please include a reproduction with mixed short messages and long code blocks, and confirm the fix against it. Thanks for the patience here.

  8. BenTaylorDev commented on Oct 1, 2026

    @BenTaylorDev
    Contributor

    Update: the change I described on 2026-09-02 shipped.

    #7243 (merged 2026-09-23, first released in v1.74.0) changed two things in the v2 virtualizer in CopilotChatMessageView:

    • The row-size estimate is now the mean of the rows already measured in the thread. Before, it was a flat 100 px. Rows that do not render yet get an estimate close to the real heights, so a tall code block causes a smaller correction.
    • Scroll correction now applies only to rows above the viewport, and it stops while the chat is pinned to the bottom. Before, every resize could move your scroll position.

    @891806797, can you retest on @copilotkit/react-core 1.74.0 or later? If the jitter is gone, I will close this issue. If it is still there, please post a short screen recording and a sample of the messages (code-block sizes are enough), and I will take it from there.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions