Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6879 fix(chat): don't paint the chat where the newest message was predicted (#7816)
Bohan Jiang0a7992c20ca8
diff --git a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx b/packages/views/chat/components/chat-message-list.autoscroll.test.tsxindex d404d38d23..ca0f0a7c19 100644--- a/packages/views/chat/components/chat-message-list.autoscroll.test.tsx+++ b/packages/views/chat/components/chat-message-list.autoscroll.test.tsx@@ -427,6 +427,71 @@ describe("ChatMessageList auto-scroll", () => {expect(scroll.directScrollTopWrites()).toBe(0);});+ // MUL-6879: Virtuoso opens the list by scrolling to where it PREDICTS the+ // newest message is, paints there, and only then measures the rows and+ // corrects — so the first painted frame showed the wrong part of the+ // conversation and the next one jumped. Readiness is judged from the+ // newest row's own box, because during the estimate the scroll geometry+ // reports the viewport as being at the live end.+ it("stays hidden until the newest message has actually landed at the bottom", () => {+ const { view, scroll } = renderStreamingChat();++ const box = (el: Element, top: number, bottom: number) => {+ el.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;+ };+ box(scroll.el, 0, VIEWPORT);+ const liveEndRow = view.container.querySelector("[data-chat-live-end]");+ if (!liveEndRow) throw new Error("the newest row is not marked as the live end");++ const frames = (count: number) => {+ for (let i = 0; i < count; i++) act(() => renderFrame());+ };++ expect(scroll.el.className).toContain("invisible");++ // Rows are on screen, but sitting where the estimate put them: below the+ // fold, still to be corrected. This is the frame that used to flicker.+ box(liveEndRow, 4600, 5200);+ frames(20);+ expect(scroll.el.className).toContain("invisible");++ // The correction lands and the newest row reaches the bottom — but the+ // list holds until the content has stopped moving there.+ box(liveEndRow, VIEWPORT - 200, VIEWPORT - 16);+ frames(2);+ expect(scroll.el.className).toContain("invisible");++ frames(20);+ expect(scroll.el.className).not.toContain("invisible");+ });++ // A row settling after its first paint — an image decoding, a code block+ // highlighting — moves the content under a reader pinned to the bottom.+ // Reaching the live end once is not enough to reveal (MUL-6879).+ it("keeps waiting while rows are still changing size at the live end", () => {+ const { view, scroll } = renderStreamingChat();++ const box = (el: Element, top: number, bottom: number) => {+ el.getBoundingClientRect = () => ({ top, bottom }) as DOMRect;+ };+ box(scroll.el, 0, VIEWPORT);+ const liveEndRow = view.container.querySelector("[data-chat-live-end]");+ if (!liveEndRow) throw new Error("the newest row is not marked as the live end");+ box(liveEndRow, VIEWPORT - 200, VIEWPORT - 16);++ // Content keeps arriving: every settle window restarts.+ for (let i = 0; i < 6; i++) {+ scroll.grow(120);+ act(() => renderFrame());+ act(() => renderFrame());+ }+ expect(scroll.el.className).toContain("invisible");++ // It stops, and the list appears.+ for (let i = 0; i < 20; i++) act(() => renderFrame());+ expect(scroll.el.className).not.toContain("invisible");+ });+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.tsxindex 0afa18cd19..c5d5e9fdc7 100644--- a/packages/views/chat/components/chat-message-list.tsx+++ b/packages/views/chat/components/chat-message-list.tsx@@ -49,7 +49,7 @@ import { OnboardingStarterCards } from "./onboarding-starter-cards";import { TaskStatusPill } from "./task-status-pill";import { CHAT_COLUMN, CHAT_GUTTER } from "./chat-column";import { FOLLOW_EDGE_THRESHOLD } from "../../common/task-transcript/transcript-follow";-import { useStickToBottom } from "./stick-to-bottom";+import { LIVE_END_ROW_ATTR, useStickToBottom } from "./stick-to-bottom";import { formatElapsedMs } from "../lib/format";import { splitTimeline, extractCopyText } from "../lib/copy-text";import { stripChatQuickActionsProtocol } from "../lib/quick-actions";@@ -198,7 +198,7 @@ export function ChatMessageList({const pinToLiveEnd = useCallback(() => {virtuosoRef.current?.scrollToIndex({ index: "LAST", align: "end" });}, []);- const { isFollowing, onContentHeightChanged } = useStickToBottom(+ const { isFollowing, onContentHeightChanged, hasReachedLiveEnd } = useStickToBottom(scrollContainerEl,pinToLiveEnd,);@@ -274,6 +274,7 @@ export function ChatMessageList({}, [messages, hasLive, pendingTaskId]);const firstIndex = renderItems.length > 0 ? firstItemIndex : 0;+ const liveEndKey = renderItems[renderItems.length - 1]?.key ?? null;const listContext: ChatListContext = {isFetchingOlderMessages,@@ -311,7 +312,11 @@ export function ChatMessageList({// The gutter lives on the scroll container, so it applies once to the// whole list — rows, header, footer — and the scrollbar still rides the// surface edge rather than being inset with the text.- className={cn("flex-1 overflow-y-auto", CHAT_GUTTER)}+ // Hidden until Virtuoso has actually landed on the newest message. The+ // container paints nothing for that whole window anyway — the rows are+ // not measured yet — so this costs no visible time and spares the+ // reader a frame of the wrong messages (see stick-to-bottom.ts).+ className={cn("flex-1 overflow-y-auto", CHAT_GUTTER, !hasReachedLiveEnd && "invisible")}>{/* Already inside the gutter + column, so this pre-mount frame renders the* skeleton BODY rather than <ChatMessageSkeleton>, which brings its own@@ -364,7 +369,10 @@ export function ChatMessageList({context={listContext}components={LIST_COMPONENTS}itemContent={(_, item) => (- <div className={cn(CHAT_COLUMN, "py-2")}>+ <div+ className={cn(CHAT_COLUMN, "py-2")}+ {...(item.key === liveEndKey ? { [LIVE_END_ROW_ATTR]: "" } : {})}+ ><MessageBubbleitem={item}isPending={!!pendingTaskId && item.taskId === pendingTaskId}diff --git a/packages/views/chat/components/stick-to-bottom.ts b/packages/views/chat/components/stick-to-bottom.tsindex 57331216e6..1a4012f296 100644--- a/packages/views/chat/components/stick-to-bottom.ts+++ b/packages/views/chat/components/stick-to-bottom.ts@@ -1,6 +1,6 @@"use client";-import { useCallback, useEffect, useMemo, useRef } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {createLiveEndFollow,FOLLOW_EDGE_THRESHOLD,@@ -46,11 +46,62 @@ export function isAtLiveEnd(m: ScrollMetrics): boolean {return distanceFromBottom(m) <= FOLLOW_EDGE_THRESHOLD;}+/**+ * Marks the newest row so the list can tell "the reader is looking at the+ * newest message" from "the viewport is where that message was predicted to+ * be". See `useStickToBottom`'s `hasReachedLiveEnd`.+ */+export const LIVE_END_ROW_ATTR = "data-chat-live-end";++/**+ * Whether the newest row's own box has arrived at the bottom of the viewport.+ *+ * Measured, never predicted: scroll geometry is derived from `scrollHeight`,+ * which is an estimate over the unrendered rows, and while that estimate is+ * still wrong it reports the viewport as being at the live end. The row's+ * rect comes from layout, so it only lines up once the rows underneath it+ * have actually been measured.+ */+export function isShowingLiveEndRow(scrollEl: HTMLElement): boolean {+ const row = scrollEl.querySelector(`[${LIVE_END_ROW_ATTR}]`);+ if (!row) return false;+ const viewport = scrollEl.getBoundingClientRect();+ const rect = row.getBoundingClientRect();+ // Its end is on screen — at or above the fold (the footer inset keeps it a+ // little above the edge), and not scrolled off the top.+ return rect.bottom <= viewport.bottom + 1 && rect.bottom > viewport.top;+}++/**+ * How long the newest message must sit at the fold, with the scroll extent+ * unchanged, before the list is revealed.+ *+ * Reaching the live end once is not enough: rows keep settling after their+ * first paint (an image decodes, a code block highlights, a font swaps), and+ * each one moves the content under a reader who is pinned to the bottom. This+ * is the window the list waits for that to stop — raise it to absorb slower+ * content at the cost of showing the conversation later, lower it to paint+ * sooner and let late arrivals shift the view.+ */+const LIVE_END_SETTLE_MS = 120;++// A list whose content never stops moving must not stay hidden. Past this,+// reveal whatever Virtuoso has: a shift beats a blank chat.+const REVEAL_DEADLINE_MS = 1000;+export interface StickToBottom {/** For `followOutput`: the reader is still following the live end. */isFollowing(): boolean;/** Wire to Virtuoso's `totalListHeightChanged`: the content resized. */onContentHeightChanged(): void;+ /**+ * False until the newest message has actually arrived at the bottom of the+ * viewport. Keep the list hidden until then: Virtuoso opens it by scrolling+ * to where it PREDICTS that message is, paints there, and only then+ * measures and corrects — so the first painted frame shows the wrong part+ * of the conversation and the next one jumps (MUL-6879).+ */+ hasReachedLiveEnd: boolean;}/**@@ -92,6 +143,39 @@ export function useStickToBottom(pinRef.current();}, []);+ // Polled rather than driven off Virtuoso's callbacks: `atBottomStateChange`+ // still reads true from before the rows existed, `itemsRendered` reports+ // rows that a measuring pass is about to unmount again, and neither fires+ // on the frame the correcting scroll lands. A frame loop that stops as soon+ // as the list holds still costs a handful of rect reads at open.+ const [hasReachedLiveEnd, setHasReachedLiveEnd] = useState(false);+ useEffect(() => {+ if (!scrollEl || hasReachedLiveEnd) return;+ let frame = 0;+ // The scroll extent is the cheapest proxy for "some row changed size":+ // every late arrival that would shift the view also moves it.+ let lastHeight = -1;+ let steadySince: number | null = null;+ const poll = (now: number) => {+ const height = scrollEl.scrollHeight;+ const steady = height === lastHeight && isShowingLiveEndRow(scrollEl);+ lastHeight = height;+ if (!steady) steadySince = null;+ else if (steadySince === null) steadySince = now;+ else if (now - steadySince >= LIVE_END_SETTLE_MS) {+ setHasReachedLiveEnd(true);+ return;+ }+ frame = requestAnimationFrame(poll);+ };+ frame = requestAnimationFrame(poll);+ const deadline = setTimeout(() => setHasReachedLiveEnd(true), REVEAL_DEADLINE_MS);+ return () => {+ cancelAnimationFrame(frame);+ clearTimeout(deadline);+ };+ }, [scrollEl, hasReachedLiveEnd]);+// Content grew or the viewport resized — displacement with no scroll event,// so it can never promote staged reader input.const onResize = useCallback(() => {@@ -216,7 +300,8 @@ export function useStickToBottom(() => ({isFollowing: () => follow.isFollowing(),onContentHeightChanged: onResize,+ hasReachedLiveEnd,}),- [follow, onResize],+ [follow, onResize, hasReachedLiveEnd],);}