Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6879 fix(chat): stop the bottom-stick fighting Virtuoso's height estimate (#7811)

Bohan Jiang66f612008735
diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx
index 68cfdcd695..d404d38d23 100644
--- a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx
+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx
@@ -17,19 +17,25 @@ import { ChatMessageList } from "./chat-message-list";
// the browser (clamps), input-led moves model the reader.
// Virtuoso cannot render rows in jsdom's zero-height viewport. The stub keeps
-// the row count visible, surfaces `followOutput` verdicts as attributes, and
+// the row count visible, surfaces `followOutput` verdicts as attributes,
// captures `totalListHeightChanged` so the harness can report content growth
-// the way the real Virtuoso does.
+// the way the real Virtuoso does, and answers `scrollToIndex` by moving the
+// scroller to the bottom — the real component's job, and the only route the
+// bottom-stick may take (MUL-6879).
let reportContentHeightChanged: (() => void) | undefined;
+let pinCalls: unknown[] = [];
+let scrollToLastItemEnd: (() => void) | undefined;
vi.mock("react-virtuoso", () => ({
Virtuoso: ({
+ ref,
data,
itemContent,
computeItemKey,
followOutput,
totalListHeightChanged,
}: {
+ ref?: { current: unknown } | ((handle: unknown) => void);
data: unknown[];
itemContent: (i: number, item: unknown) => ReactElement;
computeItemKey: (i: number, item: unknown) => string;
@@ -37,6 +43,14 @@ vi.mock("react-virtuoso", () => ({
totalListHeightChanged?: () => void;
}) => {
reportContentHeightChanged = totalListHeightChanged;
+ const handle = {
+ scrollToIndex: (location: unknown) => {
+ pinCalls.push(location);
+ scrollToLastItemEnd?.();
+ },
+ };
+ if (typeof ref === "function") ref(handle);
+ else if (ref) ref.current = handle;
return (
<div
data-testid="virtuoso-rows"
@@ -95,6 +109,8 @@ beforeEach(() => {
animationFrames = new Map();
nextAnimationFrameId = 1;
reportContentHeightChanged = undefined;
+ pinCalls = [];
+ scrollToLastItemEnd = undefined;
now = 0;
vi.spyOn(Date, "now").mockImplementation(() => now);
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
@@ -168,12 +184,17 @@ interface Scroller {
shiftSpaceFromRowControl(): void;
/** The browser scrolls the list itself (answering a key), no input seen. */
browserScrollsListUp(px: number): void;
+ /** Every `scrollToIndex` the bottom-stick asked Virtuoso for. */
+ pinCalls(): unknown[];
+ /** Writes to `scrollTop` from outside Virtuoso — always a bug (MUL-6879). */
+ directScrollTopWrites(): number;
}
function scroller(el: HTMLElement, initialContent = 2000): Scroller {
const state = { scrollTop: 0, contentHeight: initialContent, viewportHeight: VIEWPORT };
// Open at the bottom, matching Virtuoso's `initialTopMostItemIndex: LAST`.
state.scrollTop = Math.max(0, state.contentHeight - state.viewportHeight);
+ let directScrollTopWrites = 0;
Object.defineProperties(el, {
scrollHeight: { configurable: true, get: () => state.contentHeight },
@@ -182,11 +203,20 @@ function scroller(el: HTMLElement, initialContent = 2000): Scroller {
configurable: true,
get: () => state.scrollTop,
set: (value: number) => {
+ directScrollTopWrites++;
state.scrollTop = value;
},
},
});
+ // What the mock Virtuoso does for `scrollToIndex({ index: "LAST", align:
+ // "end" })`: the list moves its own scroller. Nothing else may write
+ // scrollTop, so this bypasses the counted setter.
+ scrollToLastItemEnd = () => {
+ state.scrollTop = Math.max(0, state.contentHeight - state.viewportHeight);
+ };
+ pinCalls = [];
+
const scrollEvent = () => {
act(() => {
el.dispatchEvent(new Event("scroll"));
@@ -312,6 +342,12 @@ function scroller(el: HTMLElement, initialContent = 2000): Scroller {
state.scrollTop -= px;
scrollEvent();
},
+ pinCalls() {
+ return pinCalls;
+ },
+ directScrollTopWrites() {
+ return directScrollTopWrites;
+ },
};
}
@@ -372,6 +408,25 @@ describe("ChatMessageList auto-scroll", () => {
expect(scroll.distanceFromBottom()).toBe(0);
});
+ // MUL-6879: the pin used to write `scrollTop = scrollHeight - clientHeight`
+ // on the container. In a virtualised list that height is an estimate over
+ // the unrendered rows, so the pin landed Virtuoso somewhere it then
+ // re-measured, moving the estimate — and the next height change pinned
+ // again. The loop swallowed the reader's wheel scrolls, leaving the list
+ // shaking and immovable. Corrections must go through Virtuoso.
+ it("corrects through Virtuoso rather than writing scrollTop on the container", () => {
+ const { scroll } = renderStreamingChat();
+
+ scroll.grow(180);
+ scroll.shrinkViewport(72);
+
+ expect(scroll.pinCalls()).toEqual([
+ { index: "LAST", align: "end" },
+ { index: "LAST", align: "end" },
+ ]);
+ expect(scroll.directScrollTopWrites()).toBe(0);
+ });
+
it("keeps the newest content clear of a composer that grew", () => {
const { scroll } = renderStreamingChat();
diff --git a/packages/views/chat/components/chat-message-list.tsx b/packages/views/chat/components/chat-message-list.tsx
index ce5aa92f04..0afa18cd19 100644
--- a/packages/views/chat/components/chat-message-list.tsx
+++ b/packages/views/chat/components/chat-message-list.tsx
@@ -3,7 +3,7 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
-import { Virtuoso, type Components } from "react-virtuoso";
+import { Virtuoso, type Components, type VirtuosoHandle } from "react-virtuoso";
import { cn } from "@multica/ui/lib/utils";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import { Button } from "@multica/ui/components/ui/button";
@@ -191,7 +191,17 @@ export function ChatMessageList({
scrollRef.current = node;
setScrollContainerEl(node);
}, []);
- const { isFollowing, onContentHeightChanged } = useStickToBottom(scrollContainerEl);
+ const virtuosoRef = useRef<VirtuosoHandle>(null);
+ // The bottom-stick corrects through Virtuoso, never by writing `scrollTop`
+ // on the container: `scrollHeight` is an estimate over the unrendered rows,
+ // so the pixel bottom moves as Virtuoso measures (see stick-to-bottom.ts).
+ const pinToLiveEnd = useCallback(() => {
+ virtuosoRef.current?.scrollToIndex({ index: "LAST", align: "end" });
+ }, []);
+ const { isFollowing, onContentHeightChanged } = useStickToBottom(
+ scrollContainerEl,
+ pinToLiveEnd,
+ );
// Soft edge fade hinting more content above/below. Kept small so it barely
// grazes full-bleed previews (image / HTML) at the edges.
const fadeStyle = useScrollFade(scrollRef, 16);
@@ -316,6 +326,7 @@ export function ChatMessageList({
// otherwise a diagram only starts loading once it is already on screen.
<RichContentScrollRootProvider scrollRoot={scrollContainerEl}>
<Virtuoso
+ ref={virtuosoRef}
customScrollParent={scrollContainerEl}
data={renderItems}
firstItemIndex={firstIndex}
diff --git a/packages/views/chat/components/stick-to-bottom.test.ts b/packages/views/chat/components/stick-to-bottom.test.ts
index 7b9a60e98c..e4bf3a46ef 100644
--- a/packages/views/chat/components/stick-to-bottom.test.ts
+++ b/packages/views/chat/components/stick-to-bottom.test.ts
@@ -1,11 +1,6 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
-import {
- bottomPinTarget,
- distanceFromBottom,
- isAtLiveEnd,
- type ScrollMetrics,
-} from "./stick-to-bottom";
+import { distanceFromBottom, isAtLiveEnd, type ScrollMetrics } from "./stick-to-bottom";
import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";
const VIEWPORT = 600;
@@ -26,6 +21,16 @@ describe("distanceFromBottom", () => {
it("floors at zero when the content is shorter than the viewport", () => {
expect(distanceFromBottom({ clientHeight: 600, scrollHeight: 200, scrollTop: 0 })).toBe(0);
});
+
+ it("sees the live end slide away when the composer shrinks the viewport", () => {
+ expect(
+ distanceFromBottom({
+ clientHeight: VIEWPORT - 72,
+ scrollHeight: 2000,
+ scrollTop: 2000 - VIEWPORT,
+ }),
+ ).toBe(72);
+ });
});
describe("isAtLiveEnd", () => {
@@ -34,29 +39,3 @@ describe("isAtLiveEnd", () => {
expect(isAtLiveEnd(at(4000, FOLLOW_EDGE_THRESHOLD + 1))).toBe(false);
});
});
-
-describe("bottomPinTarget", () => {
- it("pins a grown row back to the bottom", () => {
- expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 920, scrollTop: 200 })).toBe(320);
- });
-
- it("pins past a reply taller than the viewport in one step", () => {
- expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 50_000, scrollTop: 0 })).toBe(
- 50_000 - VIEWPORT,
- );
- });
-
- it("re-pins when the composer grows and shrinks the viewport", () => {
- const shrunk = { clientHeight: VIEWPORT - 72, scrollHeight: 2000, scrollTop: 2000 - VIEWPORT };
- expect(distanceFromBottom(shrunk)).toBe(72);
- expect(bottomPinTarget(shrunk)).toBe(2000 - (VIEWPORT - 72));
- });
-
- it("never pins upward when content shrinks under a pinned viewport", () => {
- expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 1000, scrollTop: 900 })).toBeNull();
- });
-
- it("reports no work when the viewport is already at the bottom", () => {
- expect(bottomPinTarget({ clientHeight: VIEWPORT, scrollHeight: 2000, scrollTop: 1400 })).toBeNull();
- });
-});
diff --git a/packages/views/chat/components/stick-to-bottom.ts b/packages/views/chat/components/stick-to-bottom.ts
index f9d4c9866e..57331216e6 100644
--- a/packages/views/chat/components/stick-to-bottom.ts
+++ b/packages/views/chat/components/stick-to-bottom.ts
@@ -46,12 +46,6 @@ export function isAtLiveEnd(m: ScrollMetrics): boolean {
return distanceFromBottom(m) <= FOLLOW_EDGE_THRESHOLD;
}
-/** Returns a downward-only scroll target, or `null` when no scrolling is needed. */
-export function bottomPinTarget(m: ScrollMetrics): number | null {
- const target = Math.max(0, m.scrollHeight - m.clientHeight);
- return target > m.scrollTop ? target : null;
-}
-
export interface StickToBottom {
/** For `followOutput`: the reader is still following the live end. */
isFollowing(): boolean;
@@ -64,8 +58,24 @@ export interface StickToBottom {
* end. Viewport resizes (the composer) are observed here; content resizes
* (streaming) must be reported through `onContentHeightChanged`, because a
* ResizeObserver on the container never sees its scroll extent.
+ *
+ * `pinToLiveEnd` applies the correction and MUST scroll through Virtuoso
+ * (`scrollToIndex` at the last row), never by writing `scrollTop` here. In a
+ * virtualised list `scrollHeight` covers unrendered rows with an ESTIMATE, so
+ * `scrollHeight - clientHeight` is not the bottom. Jumping there drops
+ * Virtuoso outside its rendered window; it measures the rows it lands on, the
+ * estimate moves, the "bottom" moves with it, and the next height change pins
+ * again — a correction that never converges. Worse, each of those jumps
+ * reaches the latch as displacement no input can account for, so the reader's
+ * own wheel scrolls are refused attribution and pinned away: the follow never
+ * releases and the list cannot be scrolled at all (MUL-6879). An index-based
+ * scroll to the last row is what Virtuoso's own `followOutput` does, and it
+ * converges because Virtuoso measures that row before deciding where to stop.
*/
-export function useStickToBottom(scrollEl: HTMLElement | null): StickToBottom {
+export function useStickToBottom(
+ scrollEl: HTMLElement | null,
+ pinToLiveEnd: () => void,
+): StickToBottom {
const followRef = useRef<LiveEndFollow | null>(null);
if (followRef.current === null) {
followRef.current = createLiveEndFollow();
@@ -76,11 +86,11 @@ export function useStickToBottom(scrollEl: HTMLElement | null): StickToBottom {
}
const follow = followRef.current;
+ const pinRef = useRef(pinToLiveEnd);
+ pinRef.current = pinToLiveEnd;
const pin = useCallback(() => {
- if (!scrollEl) return;
- const target = bottomPinTarget(scrollEl);
- if (target !== null) scrollEl.scrollTop = target;
- }, [scrollEl]);
+ pinRef.current();
+ }, []);
// Content grew or the viewport resized — displacement with no scroll event,
// so it can never promote staged reader input.