TypeScript
fix(web): switched threads and Scroll to end land on the real end (#24622)
Theo Brownefa1347daa299
diff --git a/apps/web/src/components/chat/useTimelineFollow.ts b/apps/web/src/components/chat/useTimelineFollow.tsindex 191b1d2e8ea..059781d3c0f 100644--- a/apps/web/src/components/chat/useTimelineFollow.ts+++ b/apps/web/src/components/chat/useTimelineFollow.ts@@ -28,6 +28,7 @@ import { type ChatComposerHandle } from "./ChatComposer";import { createPageScrollController, type PageScrollKey } from "./pageScrollController";import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";+import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";import { releaseChatTimelineAnchor } from "../ChatView.logic";import type { Dispatch, RefObject } from "react";@@ -272,9 +273,19 @@ export function useTimelineFollow(input: TimelineFollowInput) {// The anchored end space must be gone before the scroll measures, or the// list lands short of the real end (#6519).requestAnimationFrame(() => {- void legendListRef.current?.scrollToEnd?.({- animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,- });+ const list = legendListRef.current;+ if (!list) return;+ void Promise.resolve(+ list.scrollToEnd?.({+ animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,+ }),+ ).then(() =>+ settleListScroll(+ list,+ measuredEndOffset,+ () => timelineScrollModeRef.current !== "following-end" || legendListRef.current !== list,+ ),+ );});};const scrollToEndStable = useStableCallback(scrollToEnd);diff --git a/apps/web/src/components/chat/useTimelinePositionRestore.test.ts b/apps/web/src/components/chat/useTimelinePositionRestore.test.tsnew file mode 100644index 00000000000..551d20c2cca--- /dev/null+++ b/apps/web/src/components/chat/useTimelinePositionRestore.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it, vi } from "vite-plus/test";+import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";++describe("settleListScroll", () => {+ it("hands off when a streaming reply keeps moving the end", async () => {+ vi.useFakeTimers();+ // The node test environment has no animation frames; fake ones run on the fake clock.+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>+ setTimeout(() => callback(0), 16),+ );+ // Every correction lands, then the reply grows before the next frame.+ const element = { scrollTop: 0, scrollHeight: 5_000, clientHeight: 800 };+ const list = {+ getScrollableNode: () => element as unknown as HTMLElement,+ scrollToOffset: async ({ offset }: { offset: number }) => {+ element.scrollTop = offset;+ element.scrollHeight += 40;+ },+ };++ let settled = false;+ void settleListScroll(list, measuredEndOffset, () => false).then(() => {+ settled = true;+ });+ await vi.advanceTimersByTimeAsync(5_000);+ vi.useRealTimers();+ vi.unstubAllGlobals();++ expect(settled).toBe(true);+ });+});diff --git a/apps/web/src/components/chat/useTimelinePositionRestore.ts b/apps/web/src/components/chat/useTimelinePositionRestore.tsindex 700a2a41af0..52cd99c96c4 100644--- a/apps/web/src/components/chat/useTimelinePositionRestore.ts+++ b/apps/web/src/components/chat/useTimelinePositionRestore.ts@@ -4,6 +4,48 @@ import type { AssistantCitationRequest } from "./AssistantCitationSource";import type { MessagesTimelineRow } from "./MessagesTimeline.logic";import type { RememberedTimelinePosition } from "./timelineScrollAnchoring";+// A streaming reply moves the end every frame, so the target may never hold+// still. Past this many frames the list's own end maintenance takes over.+const SETTLE_MAX_FRAMES = 60;++/**+ * Index and end scrolling start from estimated row sizes, so they can stop+ * short of a tall row. Corrects against the DOM until the viewport holds the+ * target for two layout frames, the frame budget runs out, the caller cancels,+ * or the target disappears.+ */+export function settleListScroll(+ list: Pick<LegendListRef, "getScrollableNode" | "scrollToOffset">,+ target: (element: HTMLElement) => number | undefined,+ isCancelled: () => boolean,+): Promise<void> {+ return new Promise((resolve) => {+ let stableFrames = 0;+ let frames = 0;+ const reconcile = () => {+ if (isCancelled()) return resolve();+ const element = list.getScrollableNode();+ const offset = element ? target(element) : undefined;+ frames += 1;+ if (!element || offset === undefined || frames > SETTLE_MAX_FRAMES) return resolve();+ if (Math.abs(element.scrollTop - offset) > 1) {+ stableFrames = 0;+ void list.scrollToOffset({ offset, animated: false }).then(() => {+ requestAnimationFrame(reconcile);+ });+ return;+ }+ stableFrames += 1;+ if (stableFrames >= 2) resolve();+ else requestAnimationFrame(reconcile);+ };+ requestAnimationFrame(reconcile);+ });+}++export const measuredEndOffset = (element: HTMLElement) =>+ element.scrollHeight - element.clientHeight;+/*** Scrolls a newly shown thread back to where the user left it, or to its end,* and reports the thread positioned once the saved row settles.@@ -55,12 +97,10 @@ export function useTimelinePositionRestore({return;}let cancelled = false;- let settleFrame: number | null = null;const viewport: HTMLElement | null = list.getScrollableNode();const cancelRestoration = () => {if (cancelled) return;cancelled = true;- if (settleFrame !== null) cancelAnimationFrame(settleFrame);if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });onPositioned(listIdentityKey);};@@ -99,54 +139,41 @@ export function useTimelinePositionRestore({: listOpenedOnRef.current?.identity === listIdentityKey? undefined: list.scrollToEnd({ animated: false });- void Promise.resolve(scrolling).then(() => {+ const settlesAtEnd = position?.atEnd !== false && scrolling !== undefined;+ void Promise.resolve(scrolling).then(async () => {if (cancelled) return;- if (position?.atEnd !== false || index < 0) {- onPositioned(listIdentityKey);- return;- }- // Index scrolling starts from estimates. Keep the saved row mounted- // until its measured position and the DOM agree for two layout frames.- let stableFrames = 0;- const reconcile = () => {- if (cancelled) return;- const state = list.getState();- const rowIndex = state.indexByKey(position.rowId);- const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);- const element = list.getScrollableNode();- if (!row || !element) return;- const offset = Math.max(- 0,- Math.min(- element.scrollTop +- row.getBoundingClientRect().top -- element.getBoundingClientRect().top +- position.offsetWithinRow,- element.scrollHeight - element.clientHeight,- ),+ if (settlesAtEnd) {+ await settleListScroll(list, measuredEndOffset, () => cancelled);+ } else if (position?.atEnd === false && index >= 0) {+ // Keep the saved row mounted until its measured position and the DOM agree.+ await settleListScroll(+ list,+ (element) => {+ const state = list.getState();+ const rowIndex = state.indexByKey(position.rowId);+ const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);+ if (!row) return undefined;+ return Math.max(+ 0,+ Math.min(+ element.scrollTop ++ row.getBoundingClientRect().top -+ element.getBoundingClientRect().top ++ position.offsetWithinRow,+ measuredEndOffset(element),+ ),+ );+ },+ () => cancelled,);- if (Math.abs(element.scrollTop - offset) > 1) {- stableFrames = 0;- void list.scrollToOffset({ offset, animated: false }).then(() => {- if (!cancelled) settleFrame = requestAnimationFrame(reconcile);- });- return;- }- stableFrames += 1;- if (stableFrames >= 2) {- onPositioned(listIdentityKey);- } else {- settleFrame = requestAnimationFrame(reconcile);- }- };- settleFrame = requestAnimationFrame(reconcile);+ }+ if (!cancelled) onPositioned(listIdentityKey);});return () => {cancelled = true;if (cancelPositionRestoreRef?.current === cancelRestoration) {cancelPositionRestoreRef.current = null;}- if (settleFrame !== null) cancelAnimationFrame(settleFrame);viewport?.removeEventListener("wheel", cancelForNavigation);viewport?.removeEventListener("touchmove", cancelForNavigation);viewport?.removeEventListener("pointerdown", cancelForNavigation);