diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 7fd73739d919..8bae6244a558 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -47,6 +47,7 @@ import { toastManager } from "../ui/toast"; import type { CitedHistory } from "./citationProcedure"; import type { TimelineNavigation } from "./timelineViewport"; import { rememberTimelinePosition } from "./timelineScrollAnchoring"; +import { useTimelineFollow } from "./useTimelineFollow"; import { COMPOSER_CONTEXT_CLIPBOARD_MIME, decodeComposerContextFragment, @@ -294,6 +295,89 @@ describe("MessagesTimeline work rows", () => { ); }); +/** The timeline with the follow logic ChatView and GuestPage give it. */ +function FollowingTimeline({ + props, + entries, +}: { + props: Omit; + entries: ReadonlyArray; +}) { + const follow = useTimelineFollow({ + legendListRef: props.listRef, + composerTimelineInset: 0, + routeThreadKey: props.routeThreadKey, + activeThreadKey: props.routeThreadKey, + isServerThread: false, + serverProjection: null, + threadStatus: "live", + activeActivityRun: null, + activeRunningTurnId: null, + timelineEntries: entries as Entry[], + timelineAnchorMessageId: null, + setTimelineAnchor: () => {}, + }); + return ( + <> + + {follow.showScrollToBottom ? : null} + + ); +} + +describe("MessagesTimeline following", () => { + it("reaches the end of a long answer when the turn ends while it scrolls there", async () => { + const props = { ...baseProps(), isWorking: true }; + const history = Array.from({ length: 30 }, (_, index) => + message(`Reply ${index}\n\n${"word ".repeat(200)}`, { role: "assistant" }, `reply-${index}`), + ); + const viewport = () => props.listRef.current!.getScrollableNode()!; + const distanceFromEnd = () => + viewport().scrollHeight - viewport().clientHeight - viewport().scrollTop; + // Before mounting: the list arms its opening-target timer on mount. + using _timers = fakeTimers(); + await using screen = await renderElement(); + await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThanOrEqual(1)); + // The list re-snaps to its opening target on new data until that target expires. + await act(() => vi.advanceTimersByTime(2_500)); + + // The whole answer arrives in one update while the turn works, so the list glides to it. + const answer = message( + Array.from({ length: 200 }, (_, index) => `${index + 1}. ${"fact ".repeat(30)}`).join("\n"), + { role: "assistant" }, + "answer", + ); + const scrollBeforeAnswer = viewport().scrollTop; + await screen.rerender(); + await vi.waitFor(() => { + expect(viewport().scrollTop).toBeGreaterThan(scrollBeforeAnswer + 2_000); + expect(distanceFromEnd()).toBeGreaterThan(viewport().clientHeight * 2); + }); + + // Mid-glide the turn ends and a row above changes height; keeping it in place is an + // instant scroll, which stops the glide. It grows here: an upward adjustment can read + // as the user scrolling up, which rightly releases follow instead. + const finished = [ + ...history.slice(0, -1), + message(`Reply 29\n\n${"word ".repeat(220)}`, { role: "assistant" }, "reply-29"), + answer, + ]; + await screen.rerender( + , + ); + + // Chrome's smooth scroll over this distance runs past waitFor's default second. + await vi.waitFor(() => expect(distanceFromEnd()).toBeLessThanOrEqual(1), { timeout: 5000 }); + expect(screen.buttons("Scroll to end")).toHaveLength(0); + }); +}); + describe("MessagesTimeline messages", () => { it("settles when equally long messages have very different rendered heights", async () => { const props = baseProps(); diff --git a/apps/web/src/components/chat/useTimelineFollow.ts b/apps/web/src/components/chat/useTimelineFollow.ts index e872b13404e5..2f75296bf2f9 100644 --- a/apps/web/src/components/chat/useTimelineFollow.ts +++ b/apps/web/src/components/chat/useTimelineFollow.ts @@ -68,6 +68,9 @@ function createVisitScrollState( // thread switches. LegendList fires scroll events with isAtEnd=false while // initialScrollAtEnd is settling; hiding is always immediate. showScrollDebouncer: new Debouncer(() => showScrollToBottom(visit), { wait: 150 }), + // LegendList only re-pins within one viewport of the end, so a follow scroll + // cut short further up (an instant adjustment cancels a smooth one) stays there. + repinEndDebouncer: new Debouncer((repinEnd: () => void) => repinEnd(), { wait: 150 }), positionedAnchor: null as MessageId | null, settledAnchor: null as MessageId | null, releaseAnchorScrollHold: null as (() => void) | null, @@ -348,6 +351,16 @@ export function useTimelineFollow(input: TimelineFollowInput) { }); }; const scrollToEndStable = useStableCallback(scrollToEnd); + const repinEnd = () => { + if ( + readFollow().mode === "following" && + timelineAnchorMessageId === null && + resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false + ) { + scrollToEnd(); + } + }; + const repinEndStable = useStableCallback(repinEnd); // The list does not follow footer layout, so the resting composer cannot scroll it. Growth // above the composer (a new notice) would cover the last rows instead. const followedInsetRef = useRef(composerTimelineInset); @@ -492,8 +505,13 @@ export function useTimelineFollow(input: TimelineFollowInput) { if (!isAtEnd && readFollow().mode === "following") { scroll.showScrollDebouncer.cancel(); setShowScrollToBottom(false); + // Every scroll event reports again, so this runs once scrolling stops short. + scroll.repinEndDebouncer.maybeExecute(() => { + if (visitScrollRef.current === scroll) repinEndStable(); + }); return; } + scroll.repinEndDebouncer.cancel(); const { before, after } = followStore.dispatch(visit, { type: isAtEnd ? "reachedEnd" : "leftEnd", });