TypeScript
fix(web): find shows its match after a thread switch, and the timeline hears scrolling through one viewport signal (#25463)
Julius Marminge3cb16cf16509
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex dae9caa8729..587bd706ccb 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -1999,9 +1999,7 @@ export default function ChatView(props: ChatViewProps) {const {showScrollToBottom,timelineLiveFollowEnabled,- cancelPositionRestoreRef,isTimelineAtLogicalEndStable,- cancelTimelineLiveFollowForUserNavigationStable,onComposerPageScrollKeyDownStable,onComposerPageScrollKeyUpStable,onComposerPageScrollReleaseStable,@@ -2011,14 +2009,14 @@ export default function ChatView(props: ChatViewProps) {onToolOutputCollapsedAtEndStable,onIsAtEndChangeStable,anchorNewTurn,+ attachTimelineViewport,+ attachComposerOverlay: attachFollowComposerOverlay,} = useTimelineFollow({legendListRef,composerRef,- composerOverlayElement,composerTimelineInset,routeThreadKey,activeThreadKey,- activeThreadId: activeThread?.id,isServerThread,serverProjection,threadStatus,@@ -3365,8 +3363,7 @@ export default function ChatView(props: ChatViewProps) {onIsAtEndChange={onIsAtEndChangeStable}onContentOverflowChange={setTimelineOverflows}onToolOutputCollapsedAtEnd={onToolOutputCollapsedAtEndStable}- onManualNavigation={cancelTimelineLiveFollowForUserNavigationStable}- cancelPositionRestoreRef={cancelPositionRestoreRef}+ onViewportAttach={attachTimelineViewport}hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}emptyPlaceholderInset={composerReservedHeight}topFadeEnabled={!hasTimelineTopBanner}@@ -3387,7 +3384,10 @@ export default function ChatView(props: ChatViewProps) {</div><div- ref={setComposerOverlayElement}+ ref={(overlay: HTMLDivElement | null) => {+ setComposerOverlayElement(overlay);+ attachFollowComposerOverlay(overlay);+ }}inert={isRevertingCheckpoint}data-chat-composer-overlay="true"className={diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsxindex 9005cf2808b..9323dfb5174 100644--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx@@ -24,6 +24,8 @@ import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";import { collectThreadFindRanges } from "./threadFindHighlights";import { toastManager } from "../ui/toast";import type { CitedHistory } from "./citationProcedure";+import type { TimelineNavigation } from "./timelineViewport";+import { rememberTimelinePosition } from "./timelineScrollAnchoring";const environmentQuery = vi.hoisted(() => ({error: "Pull request not found",@@ -91,7 +93,6 @@ function baseProps(): Omit<TimelineProps, "timelineEntries"> {emptyPlaceholderInset: 0,liveFollowEnabled: true,onIsAtEndChange: () => {},- onManualNavigation: () => {},};}@@ -638,6 +639,125 @@ describe("MessagesTimeline attachments", () => {});});+describe("MessagesTimeline thread find", () => {+ // Opening find is navigation; on a list already showing the thread the open+ // action navigates, so the list itself releases follow only when it starts+ // showing a thread whose find is already open.+ function renderObserved() {+ const navigations: TimelineNavigation[] = [];+ const base = baseProps();+ const element = (next: Partial<TimelineProps>) => (+ <MessagesTimeline+ {...base}+ timelineEntries={[message("Where is the sidebar fix?")]}+ onViewportAttach={(viewport) =>+ viewport.subscribe((navigation) => navigations.push(navigation))+ }+ {...next}+ />+ );+ return { navigations, element };+ }+ const released = { source: "command", releasesFollow: true };++ it("releases follow once when it starts showing a thread whose find is open", async () => {+ setup();+ const { navigations, element } = renderObserved();+ await using screen = await renderElement(element({}));+ expect(navigations).toEqual([]);++ const other = "environment-local:thread-find-open";+ await screen.rerender(element({ routeThreadKey: other, findOpen: true }));+ expect(navigations).toEqual([released]);+ await screen.rerender(element({ routeThreadKey: other, findOpen: false }));+ await screen.rerender(element({ routeThreadKey: other, findOpen: true }));+ expect(navigations).toEqual([released]);+ });++ it("releases follow once when it mounts on a thread whose find is open", async () => {+ setup();+ const { navigations, element } = renderObserved();+ await using screen = await renderElement(element({ findOpen: true }));+ await screen.rerender(element({ findOpen: true }));+ expect(navigations).toEqual([released]);+ });++ it("still restores the position of a thread it switches to whose find is open", async () => {+ setup();+ const base = baseProps();+ const other = "environment-local:thread-find-open-positioned";+ const replies = Array.from({ length: 40 }, (_, index) =>+ message(`Reply ${index}\n\n${"line\n\n".repeat(8)}`, { role: "assistant" }, `r-${index}`),+ );+ rememberTimelinePosition(+ other,+ { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },+ false,+ );+ await using screen = await renderElement(+ <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />,+ );+ await screen.rerender(+ <MessagesTimeline+ {...base}+ routeThreadKey={other}+ timelineEntries={replies}+ liveFollowEnabled={false}+ findOpen+ />,+ );+ const viewport = base.listRef.current!.getScrollableNode()!;+ await vi.waitFor(() => {+ const row = screen.container.querySelector('[data-timeline-row-id="entry-r-20"]');+ expect(row).not.toBeNull();+ expect(+ Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top),+ ).toBeLessThanOrEqual(2);+ });+ });+ it("reveals find's match, not the remembered row, on a thread it switches to", async () => {+ setup();+ const base = baseProps();+ const other = "environment-local:thread-find-open-match";+ const replies = Array.from({ length: 40 }, (_, index) =>+ message(+ `${index === 5 ? "Needle here" : `Reply ${index}`}\n\n${"line\n\n".repeat(8)}`,+ { role: "assistant" },+ `r-${index}`,+ ),+ );+ rememberTimelinePosition(+ other,+ { rowId: "entry-r-20", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },+ false,+ );+ await using screen = await renderElement(+ <MessagesTimeline {...base} timelineEntries={[message("Short thread")]} />,+ );+ await screen.rerender(+ <MessagesTimeline+ {...base}+ routeThreadKey={other}+ timelineEntries={replies}+ liveFollowEnabled={false}+ findOpen+ findExpanded+ findQuery="Needle"+ activeFindMatch={{ entryId: "entry-r-5", runId: null, occurrence: 0 }}+ />,+ );+ const viewport = base.listRef.current!.getScrollableNode()!;+ await vi.waitFor(() => {+ const row = screen.container.querySelector('[data-timeline-row-id="entry-r-5"]');+ expect(row).not.toBeNull();+ const bounds = viewport.getBoundingClientRect();+ const top = row!.getBoundingClientRect().top;+ expect(top).toBeGreaterThanOrEqual(bounds.top);+ expect(top).toBeLessThan(bounds.bottom);+ });+ });+});+describe("compact reasoning math", () => {it("keeps formulas while flattening compact reasoning previews", () => {const tree = parseMarkdownWithMath("## Reasoning\n\nUse **norm** $|x|$ and \\[x^2\\]");diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex 66b2492d227..6458bd12e58 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -30,7 +30,6 @@ import {memo,use,useContext,- useEffect,useLayoutEffect,useRef,useState,@@ -78,7 +77,6 @@ import { useThreadFindNavigation } from "./useThreadFindNavigation";import { TooltipScrollDismissArea } from "../ui/tooltip";import { WorktreeSetupCard } from "./WorktreeSetupCard";import { useOpenPrLink } from "~/lib/openPullRequestLink";-import { useClientSettings } from "~/hooks/useSettings";import { useMediaQuery } from "~/hooks/useMediaQuery";import { cn } from "~/lib/utils";import { type TimestampFormat } from "@t3tools/contracts/settings";@@ -112,7 +110,13 @@ import {McpAppTimelineRow,} from "./TimelineAssistantRows";import { V2EventTimelineRow } from "./TimelineV2EventRow";-import { useTimelinePositionRestore } from "./useTimelinePositionRestore";+import { startTimelinePositionRestore } from "./useTimelinePositionRestore";+import {+ attachTimelineViewport,+ nextListOpening,+ type TimelineListOpening,+ type TimelineViewport,+} from "./timelineViewport";import { useThreadFindPositionReader } from "./useThreadFindPositionReader";import { ThreadActivityAnnouncer } from "./ThreadActivityAnnouncer";import { useStableHandoffRuns, useIncrementalTimelineRows, useStableRows } from "./useTimelineRows";@@ -260,9 +264,9 @@ interface MessagesTimelineProps {liveFollowEnabled: boolean;onContentOverflowChange?: (overflows: boolean) => void;onToolOutputCollapsedAtEnd?: () => void;- onManualNavigation: () => void;+ /** Receives the list's viewport when it mounts; the returned cleanup runs when it goes away. */+ onViewportAttach?: (viewport: TimelineViewport) => () => void;findOpen?: boolean;- cancelPositionRestoreRef?: React.RefObject<(() => void) | null> | undefined;hideEmptyPlaceholder?: boolean;/** Composer space to center the empty state against; held steady through collapse. */emptyPlaceholderInset: number;@@ -277,10 +281,6 @@ interface MessagesTimelineProps {export function MessagesTimeline(props: MessagesTimelineProps) {const find = useContext(ThreadFindTimelineContext);const findOpen = find?.findOpen ?? props.findOpen;- const { onManualNavigation } = props;- useEffect(() => {- if (findOpen) onManualNavigation();- }, [findOpen, onManualNavigation]);return (<ConversationTimeline{...props}@@ -311,6 +311,7 @@ const ConversationTimeline = memo(function ConversationTimeline({awaitingRequestId = null,listRef,timelineEntries,+ findOpen = false,findExpanded = false,findQuery = "",activeFindMatch = null,@@ -358,8 +359,7 @@ const ConversationTimeline = memo(function ConversationTimeline({onContentOverflowChange,liveFollowEnabled,onToolOutputCollapsedAtEnd,- onManualNavigation,- cancelPositionRestoreRef,+ onViewportAttach,hideEmptyPlaceholder = false,emptyPlaceholderInset,topFadeEnabled = false,@@ -367,7 +367,12 @@ const ConversationTimeline = memo(function ConversationTimeline({}: MessagesTimelineProps) {const listIdentityKey = displayThreadKey ?? routeThreadKey;// Snapshot restore positions on identity changes; ongoing scroll writes must not move them.- const [listState, setListState] = useState(() => timelineListStateFor(listIdentityKey));+ // Find open at the opening is part of the snapshot: opening find later+ // announces its own navigation (threadFindStore's announceOpening).+ const [listState, setListState] = useState(() => ({+ ...timelineListStateFor(listIdentityKey),+ findOpenAtOpening: findOpen,+ }));const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(() => listState.rememberedPosition?.disclosures?.runs ?? new Set(),);@@ -377,8 +382,10 @@ const ConversationTimeline = memo(function ConversationTimeline({const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(() => listState.rememberedPosition?.disclosures?.attempts ?? new Set(),);+ // A list that opens on a thread with find open takes the opening step below,+ // so the restore runs and releases follow once for find.const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>- listState.rememberedPosition?.atEnd === false ? null : listIdentityKey,+ listState.rememberedPosition?.atEnd === false || findOpen ? null : listIdentityKey,);const restoringThreadPosition = positionedThreadKey !== listIdentityKey;const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");@@ -386,6 +393,7 @@ const ConversationTimeline = memo(function ConversationTimeline({const [playingAudioRows, setPlayingAudioRows] = useState<ReadonlyMap<HTMLAudioElement, string>>(() => new Map(),);+ const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);let paintedExpandedRunIds = expandedRunIds;let paintedExpandedWorkGroupIds = expandedWorkGroupIds;let paintedExpandedAttemptIds = expandedAttemptIds;@@ -395,9 +403,17 @@ const ConversationTimeline = memo(function ConversationTimeline({: listState;if (identityChanged) {setPlayingAudioRows(new Map());- setListState({ identity: listIdentityKey, rememberedPosition, workGroupViewState });+ setListState({+ identity: listIdentityKey,+ rememberedPosition,+ workGroupViewState,+ findOpenAtOpening: findOpen,+ });setPositionedThreadKey(null);setSettlingListIdentity(listIdentityKey);+ // A viewer pinned in another thread must not keep live follow off here,+ // nor when that thread comes back.+ setFullscreenAppRowId(null);paintedExpandedRunIds = rememberedPosition?.disclosures?.runs ?? new Set();paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();paintedExpandedAttemptIds = rememberedPosition?.disclosures?.attempts ?? new Set();@@ -415,31 +431,6 @@ const ConversationTimeline = memo(function ConversationTimeline({const normalizedFindQuery = findQuery.trim();const findActive = findExpanded;- useEffect(() => {- return () => {- if (disclosureSettleFrameRef.current !== null) {- cancelAnimationFrame(disclosureSettleFrameRef.current);- }- if (disclosureSettleSecondFrameRef.current !== null) {- cancelAnimationFrame(disclosureSettleSecondFrameRef.current);- }- };- }, []);-- useEffect(() => {- if (settlingListIdentity === null) return;- let second: number | null = null;- const first = requestAnimationFrame(() => {- second = requestAnimationFrame(() => {- setSettlingListIdentity((current) => (current === settlingListIdentity ? null : current));- });- });- return () => {- cancelAnimationFrame(first);- if (second !== null) cancelAnimationFrame(second);- };- }, [settlingListIdentity]);-const disclosurePinsEndRef = useRef(false);const disclosureCollapsedRef = useRef(false);const pinDisclosureToEnd = () => {@@ -525,32 +516,42 @@ const ConversationTimeline = memo(function ConversationTimeline({});};- const previousLatestRunRef = useRef({ identity: listIdentityKey, run: latestRun });- useEffect(() => {- const { identity, run: previous } = previousLatestRunRef.current;- previousLatestRunRef.current = { identity: listIdentityKey, run: latestRun };- if (identity !== listIdentityKey || !latestRun || previous?.runId === undefined) {- return;- }- if (latestRun.runId === previous.runId) {- if (previous.status === "running" && latestRun.status === "interrupted") {+ // An interrupted run opens its fold; a newer run closes the previous run's.+ const [observedLatestRun, setObservedLatestRun] = useState({+ identity: listIdentityKey,+ runId: latestRun?.runId,+ status: latestRun?.status,+ });+ if (+ observedLatestRun.identity !== listIdentityKey ||+ observedLatestRun.runId !== latestRun?.runId ||+ observedLatestRun.status !== latestRun?.status+ ) {+ setObservedLatestRun({+ identity: listIdentityKey,+ runId: latestRun?.runId,+ status: latestRun?.status,+ });+ const previousRunId = observedLatestRun.runId;+ if (+ observedLatestRun.identity === listIdentityKey &&+ latestRun &&+ previousRunId !== undefined+ ) {+ if (latestRun.runId === previousRunId) {+ if (observedLatestRun.status === "running" && latestRun.status === "interrupted") {+ setExpandedRunIds((existing) => new Set(existing).add(latestRun.runId));+ }+ } else {setExpandedRunIds((existing) => {+ if (!existing.has(previousRunId)) return existing;const next = new Set(existing);- next.add(latestRun.runId);+ next.delete(previousRunId);return next;});}- return;}- setExpandedRunIds((existing) => {- if (!existing.has(previous.runId)) {- return existing;- }- const next = new Set(existing);- next.delete(previous.runId);- return next;- });- }, [latestRun, listIdentityKey]);+ }// Imported turns and post-steer work fold under synthetic keys, not the entries' run ids.const findFoldRunIds = findActive@@ -665,22 +666,53 @@ const ConversationTimeline = memo(function ConversationTimeline({: -1;const restoringAlwaysRender =restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined;- useTimelinePositionRestore({- listRef,+ const showsEmptyState =+ rows.length === 0 &&+ !isWorking &&+ parentThreadLink === null &&+ historyControls === undefined &&+ footer === null;+ const [listOpening, setListOpening] = useState<TimelineListOpening>(() =>+ nextListOpening({ mounted: false }, !showsEmptyState, listIdentityKey),+ );+ const nextOpening = nextListOpening(listOpening, !showsEmptyState, listIdentityKey);+ if (nextOpening !== listOpening) setListOpening(nextOpening);+ const listOpenedOn = nextOpening.mounted ? nextOpening.identity : null;+ const viewportRef = useRef<TimelineViewport | null>(null);+ const navigateTimeline = () => viewportRef.current?.navigate({ releasesFollow: true });+ const restoreReady = restoringThreadPosition && rows.length > 0;+ // Z: syncs LegendList's scroll position with which thread it shows. The list+ // is not keyed per thread and reports no "new data" event, and the restore+ // must land before paint, after LegendList's own layout effects applied the+ // new data. A citation request that arrives mid-restore takes over.+ const { findOpenAtOpening } = identityChanged ? { findOpenAtOpening: findOpen } : listState;+ useLayoutEffect(() => {+ const list = listRef.current;+ const viewport = viewportRef.current;+ if (!restoreReady || !list || !viewport) return;+ return startTimelinePositionRestore({+ list,+ viewport,+ listIdentityKey,+ listOpenedOn,+ rememberedPosition,+ citationPending: citationRequest !== null,+ releaseForFind: findOpenAtOpening,+ onPositioned: setPositionedThreadKey,+ });+ }, [+ citationRequest,+ findOpenAtOpening,listIdentityKey,- restoringThreadPosition,+ listOpenedOn,+ listRef,rememberedPosition,- rows,- citationRequest,- cancelPositionRestoreRef,- onManualNavigation,- onPositioned: setPositionedThreadKey,- });+ restoreReady,+ ]);const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(null,);- const chatWidth = useClientSettings((settings) => settings.chatWidth);const {target: readyCitationRequest,positioning: citationPositioning,@@ -697,7 +729,7 @@ const ConversationTimeline = memo(function ConversationTimeline({}): null,viewport: timelineViewportElement,- onManualNavigation,+ onManualNavigation: navigateTimeline,});const [findListReady, setFindListReady] = useState(false);const handleListLoad = () => {@@ -705,7 +737,8 @@ const ConversationTimeline = memo(function ConversationTimeline({setFindListReady(true);};const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);- const [fullscreenAppRowId, setFullscreenAppRowId] = useState<string | null>(null);+ // Every full-screen viewer reports false when it unmounts, so a row that leaves the list+ // while full screen releases its pin too.const onAppFullscreenChange = (rowId: string, fullscreen: boolean) => {setFullscreenAppRowId((current) => (fullscreen ? rowId : current === rowId ? null : current));};@@ -780,12 +813,6 @@ const ConversationTimeline = memo(function ConversationTimeline({onContentOverflowChange(measureContentOverflow());});};- useEffect(() => cancelContentOverflowFrame, [cancelContentOverflowFrame]);- useLayoutEffect(() => {- cancelContentOverflowFrame();- onContentOverflowChange?.(measureContentOverflow());- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows change the content height.- }, [cancelContentOverflowFrame, measureContentOverflow, onContentOverflowChange, rows.length]);const refreshMinimap = useStableCallback(() => {const state = listRef.current?.getState?.();@@ -841,34 +868,53 @@ const ConversationTimeline = memo(function ConversationTimeline({});};- const handleScroll = () => {+ // The measurement the last remember wrote, so a follow release can rewrite+ // it without reading render state from a listener.+ const lastRememberedRef = useRef<{+ readonly data: unknown;+ readonly threadKey: string;+ readonly position: Parameters<typeof rememberTimelinePosition>[1];+ } | null>(null);+ const rememberPosition = (followingEnd: boolean) => {const state = listRef.current?.getState?.();if (restoringThreadPosition || state?.data !== rows) return;const isAtEnd = resolveTimelineIsAtEnd(state);- const position = state?.data?.length ? resolveWorkGroupScrollAnchor(state) : undefined;- if (position && state && isAtEnd !== undefined && !paintOnly) {+ const position = state.data.length ? resolveWorkGroupScrollAnchor(state) : undefined;+ if (position && isAtEnd !== undefined && !paintOnly) {const index = state.indexByKey(position.rowId);const row = index === undefined ? undefined : state.elementAtIndex(index);const element = listRef.current?.getScrollableNode();if (row && element) {- rememberTimelinePosition(- listIdentityKey,- {- ...position,- offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,- scrollOffset: element.scrollTop,- atEnd: isAtEnd,- disclosures: {- runs: paintedExpandedRunIds,- workGroups: paintedExpandedWorkGroupIds,- attempts: paintedExpandedAttemptIds,- workGroupState: workGroupViewState,- },+ const measured = {+ ...position,+ offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,+ scrollOffset: element.scrollTop,+ atEnd: isAtEnd,+ disclosures: {+ runs: paintedExpandedRunIds,+ workGroups: paintedExpandedWorkGroupIds,+ attempts: paintedExpandedAttemptIds,+ workGroupState: workGroupViewState,},- liveFollowEnabled && !anchoredEndSpace,- );+ };+ lastRememberedRef.current = { data: rows, threadKey: listIdentityKey, position: measured };+ rememberTimelinePosition(listIdentityKey, measured, followingEnd);}}+ return isAtEnd;+ };+ // A follow release without a scroll after it would leave the position+ // remembered as following.+ const rememberReleasedPosition = () => {+ const last = lastRememberedRef.current;+ if (last && listRef.current?.getState().data === last.data) {+ rememberTimelinePosition(last.threadKey, last.position, false);+ }+ };++ const handleScroll = () => {+ if (restoringThreadPosition || listRef.current?.getState?.().data !== rows) return;+ const isAtEnd = rememberPosition(liveFollowEnabled && !anchoredEndSpace);if (isAtEnd !== undefined && !citationPositioning) {onIsAtEndChange(isAtEnd);}@@ -885,61 +931,55 @@ const ConversationTimeline = memo(function ConversationTimeline({scheduleMinimapRefresh();};- useEffect(- () => () => {- if (minimapRefreshFrameRef.current !== null) {- cancelAnimationFrame(minimapRefreshFrameRef.current);- minimapRefreshFrameRef.current = null;- }- },- [],- );-- useEffect(() => {- const frame = requestAnimationFrame(handleScroll);- return () => cancelAnimationFrame(frame);- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Added or removed rows move the scroll position.- }, [handleScroll, rows.length]);-- const savedLiveFollowEnabledRef = useRef(liveFollowEnabled);- useLayoutEffect(() => {- const wasFollowing = savedLiveFollowEnabledRef.current;- savedLiveFollowEnabledRef.current = liveFollowEnabled;- if (wasFollowing && !liveFollowEnabled) handleScroll();- }, [handleScroll, liveFollowEnabled]);-- useEffect(() => {- if (!timelineViewportElement) {- return;+ const measureTimelineGutter = (viewportElement: HTMLElement) => {+ const viewportWidth = viewportElement.getBoundingClientRect().width;+ const contentWidth =+ viewportElement.querySelector<HTMLElement>("[data-timeline-root]")?.getBoundingClientRect()+ .width ?? viewportWidth;+ const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(+ viewportWidth,+ contentWidth,+ );+ setMinimapHasPersistentGutter((current) =>+ current === nextHasPersistentGutter ? current : nextHasPersistentGutter,+ );+ setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth));+ };+ // Rows added, removed or rewrapped (chat width) change the content size,+ // which moves the scroll position, the overflow, and the content lane width.+ const handleContentSizeChanged = useStableCallback((laidOutData: unknown) => {+ // The first laid-out content of a newly shown thread ends its settling; a+ // frame the previous thread scheduled laid out the previous thread's rows.+ if (laidOutData === rows) {+ setSettlingListIdentity((current) => (current === listIdentityKey ? null : current));}-- const measure = () => {- const viewportWidth = timelineViewportElement.getBoundingClientRect().width;- const contentWidth =- timelineViewportElement- .querySelector<HTMLElement>("[data-timeline-root]")- ?.getBoundingClientRect().width ?? viewportWidth;- const nextHasPersistentGutter = resolveTimelineMinimapHasPersistentGutter(- viewportWidth,- contentWidth,- );- setMinimapHasPersistentGutter((current) =>- current === nextHasPersistentGutter ? current : nextHasPersistentGutter,- );- setMinimapHitStripWidth(resolveTimelineMinimapHitStripWidth(viewportWidth, contentWidth));- reportContentOverflow();- };-- const frame = requestAnimationFrame(measure);-- const stopObserving = observeResize(timelineViewportElement, measure);-+ handleScroll();+ });+ // The content lane only changes width with the viewport or the chat width+ // setting, never with streamed content; measuring per content frame would+ // force a layout on every chunk.+ const measuredLaneWidthRef = useRef<number | null>(null);+ const observeLaneWidth = (lane: HTMLDivElement | null) => {+ if (!lane) return;+ return observeResize(lane, (entries) => {+ const width = entries.at(-1)?.contentRect.width;+ if (width === undefined || width === measuredLaneWidthRef.current) return;+ measuredLaneWidthRef.current = width;+ const viewportElement = lane.closest<HTMLElement>("[data-assistant-citation-viewport]");+ if (viewportElement) measureTimelineGutter(viewportElement);+ });+ };+ const attachTimelineViewportElement = (viewportElement: HTMLDivElement | null) => {+ setTimelineViewportElement(viewportElement);+ if (!viewportElement) return;+ const stopObserving = observeResize(viewportElement, () =>+ measureTimelineGutter(viewportElement),+ );return () => {- cancelAnimationFrame(frame);stopObserving();+ setTimelineViewportElement(null);};- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Rows and chat width resize the content without resizing the viewport.- }, [timelineViewportElement, rows.length, reportContentOverflow, chatWidth]);+ };const sharedState: TimelineRowSharedState = {citationRequest: readyCitationRequest,@@ -1049,11 +1089,55 @@ const ConversationTimeline = memo(function ConversationTimeline({const registerTimeline = canvas?.registerTimeline;const setTimelineList = (list: LegendListRef | null) => {listRef.current = list;- registerTimeline?.(list?.getScrollableNode() ?? null);+ const scrollNode: HTMLElement | null = list?.getScrollableNode() ?? null;+ registerTimeline?.(scrollNode);+ const viewport = scrollNode ? attachTimelineViewport(scrollNode) : null;+ viewportRef.current = viewport;+ const detachViewport = viewport ? onViewportAttach?.(viewport) : undefined;+ const stopRememberingRelease = viewport?.onFollowReleased(rememberReleasedPosition);+ let contentSizeFrame: number | null = null;+ // LegendList lays rows out from layout effects; the next frame sees them settled.+ let scheduledData: unknown = null;+ const scheduleContentSizeChanged = () => {+ if (!list) return;+ const laidOutData = list.getState().data;+ if (contentSizeFrame !== null) {+ if (scheduledData === laidOutData) return;+ cancelAnimationFrame(contentSizeFrame);+ }+ scheduledData = laidOutData;+ contentSizeFrame = requestAnimationFrame(() => {+ contentSizeFrame = null;+ handleContentSizeChanged(laidOutData);+ });+ };+ const stopListeningToContentSize = list+ ?.getState()+ .listen("totalSize", () => scheduleContentSizeChanged());+ scheduleContentSizeChanged();+ return () => {+ stopListeningToContentSize?.();+ stopRememberingRelease?.();+ onContentOverflowChange?.(false);+ if (contentSizeFrame !== null) cancelAnimationFrame(contentSizeFrame);+ detachViewport?.();+ viewport?.dispose();+ if (viewportRef.current === viewport) viewportRef.current = null;+ // Refresh frames only read the list; disclosure frames still run so the+ // settle flag clears.+ cancelContentOverflowFrame();+ if (minimapRefreshFrameRef.current !== null) {+ cancelAnimationFrame(minimapRefreshFrameRef.current);+ minimapRefreshFrameRef.current = null;+ }+ listRef.current = null;+ registerTimeline?.(null);+ };};useThreadFindPositionReader({threadKey: listIdentityKey,+ navigate: navigateTimeline,timelineViewportElement,findFoldRunIds,timelineEntries,@@ -1066,7 +1150,9 @@ const ConversationTimeline = memo(function ConversationTimeline({});useThreadFindNavigation({- listReady: findListReady,+ // Find reveals its match only after the opening restore settles; both+ // scroll the list directly, so the restore would otherwise pull it back.+ listReady: findListReady && !restoringThreadPosition,historyControls,entries: timelineEntries,container: timelineViewportElement,@@ -1108,6 +1194,7 @@ const ConversationTimeline = memo(function ConversationTimeline({onEndedCapture={(event) => onAudioPlaybackChange(item.id, event)}><div+ ref={observeLaneWidth}className="@container/chat-lane chat-content-lane overflow-x-clip"data-timeline-root="true">@@ -1125,13 +1212,7 @@ const ConversationTimeline = memo(function ConversationTimeline({if (scrollNode) forwardWheelToTimeline(event, scrollNode);};- if (- rows.length === 0 &&- !isWorking &&- parentThreadLink === null &&- historyControls === undefined &&- footer === null- ) {+ if (showsEmptyState) {if (hideEmptyPlaceholder) {return (<>@@ -1159,7 +1240,7 @@ const ConversationTimeline = memo(function ConversationTimeline({<MarkdownFindContext value={findActive}><TimelineRowActivityCtx value={activityState}><TooltipScrollDismissArea- ref={setTimelineViewportElement}+ ref={attachTimelineViewportElement}className="relative h-full min-h-0"data-assistant-citation-viewport="true">@@ -1209,6 +1290,8 @@ const ConversationTimeline = memo(function ConversationTimeline({maintainScrollAtEndThreshold={1}onScroll={handleScroll}onItemSizeChanged={handleItemSizeChanged}+ // A viewport resize changes how much of the content fits.+ onLayout={reportContentOverflow}className={cn("messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",topFadeEnabled && "topbar-scroll-fade",@@ -1224,7 +1307,7 @@ const ConversationTimeline = memo(function ConversationTimeline({stripMap={minimapStripMap}onWheel={forwardMinimapWheel}onSelect={(item) => {- onManualNavigation();+ navigateTimeline();void listRef.current?.scrollToIndex({index: item.rowIndex,animated: !window.matchMedia("(prefers-reduced-motion: reduce)").matches,diff --git a/apps/web/src/components/chat/threadFindStore.test.ts b/apps/web/src/components/chat/threadFindStore.test.tsindex f6620e77180..3819d8a4110 100644--- a/apps/web/src/components/chat/threadFindStore.test.ts+++ b/apps/web/src/components/chat/threadFindStore.test.ts@@ -19,21 +19,25 @@ const threadKey = "env-1:thread-1";function setup() {closeThreadFind();+ const navigate = vi.fn();const readPosition = vi.fn(() => ({ entryId: "entry-9", occurrence: 1 }));- return { readPosition, timeline: { threadKey, readPosition } };+ return { navigate, readPosition, timeline: { threadKey, navigate, readPosition } };}describe("thread find store", () => {it("restarts an open query from the viewport of the timeline showing the thread", () => {- const { readPosition, timeline } = setup();+ const { navigate, readPosition, timeline } = setup();const detach = attachThreadFindTimeline(timeline);openThreadFind(threadKey);+ // Opening find is manual navigation; reopening it is not.+ expect(navigate).toHaveBeenCalledTimes(1);expect(useThreadFindStore.getState()).toMatchObject({ threadKey, focusRequestId: 1 });setThreadFindQuery(threadKey, " needle ");expect(readPosition).toHaveBeenLastCalledWith("needle");// Opening again refocuses and restarts the search from where the viewport is.openThreadFind(threadKey);+ expect(navigate).toHaveBeenCalledTimes(1);expect(useThreadFindStore.getState()).toMatchObject({query: " needle ",focusRequestId: 2,@@ -45,7 +49,7 @@ describe("thread find store", () => {});it("opens a search result's find for a thread before its timeline shows it", () => {- const { readPosition, timeline } = setup();+ const { navigate, readPosition, timeline } = setup();const detach = attachThreadFindTimeline({ ...timeline, threadKey: "env-1:thread-2" });openThreadFindOnQuery(threadKey, { query: "Café", start: { entryId: "m", occurrence: 0 } });expect(useThreadFindStore.getState()).toMatchObject({@@ -56,6 +60,7 @@ describe("thread find store", () => {// Another thread's timeline does not answer for this one.setThreadFindQuery(threadKey, "Caf");expect(readPosition).not.toHaveBeenCalled();+ expect(navigate).not.toHaveBeenCalled();detach();});diff --git a/apps/web/src/components/chat/threadFindStore.ts b/apps/web/src/components/chat/threadFindStore.tsindex d2ed7cd0403..ea52de6c274 100644--- a/apps/web/src/components/chat/threadFindStore.ts+++ b/apps/web/src/components/chat/threadFindStore.ts@@ -49,6 +49,8 @@ export const useThreadFindStore = create<ThreadFindState>(() => CLOSED_THREAD_FIinterface ThreadFindTimeline {readonly threadKey: string;readonly readPosition: ThreadFindPositionReader;+ /** Opening find is manual navigation: it releases live follow. */+ readonly navigate: () => void;}let attachedTimeline: ThreadFindTimeline | null = null;@@ -69,12 +71,23 @@ function readThreadFindPosition(threadKey: string, query: string): ThreadFindStareturn timelineFor(threadKey)?.readPosition(query);}+/**+ * Navigates the timeline showing the thread when find newly opens there. A+ * timeline that starts showing the thread later (a search result opened find+ * before the route switched or the thread painted) releases follow itself as+ * it opens on the thread.+ */+function announceOpening(previous: ThreadFindState, threadKey: string): void {+ if (previous.threadKey !== threadKey) timelineFor(threadKey)?.navigate();+}+/** Opens find, or refocuses it and restarts its search from the viewport when already open. */export function openThreadFind(threadKey: string): void {const previous = useThreadFindStore.getState();const current = previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND;const query = current.query.trim();const start = query ? readThreadFindPosition(threadKey, query) : undefined;+ announceOpening(previous, threadKey);useThreadFindStore.setState({...current,threadKey,@@ -103,6 +116,7 @@ export interface PendingThreadFind {*/export function openThreadFindOnQuery(threadKey: string, find: PendingThreadFind): void {const previous = useThreadFindStore.getState();+ announceOpening(previous, threadKey);useThreadFindStore.setState({...(previous.threadKey === threadKey ? previous : CLOSED_THREAD_FIND),threadKey,diff --git a/apps/web/src/components/chat/timelineViewport.test.ts b/apps/web/src/components/chat/timelineViewport.test.tsnew file mode 100644index 00000000000..f5d6264053c--- /dev/null+++ b/apps/web/src/components/chat/timelineViewport.test.ts@@ -0,0 +1,103 @@+import { describe, expect, it } from "vite-plus/test";++import {+ FOLLOWING,+ initialTimelineFollow,+ navigationReleasesFollow,+ nextListOpening,+ transitionTimelineFollow,+ type TimelineFollow,+ type TimelineListOpening,+} from "./timelineViewport";++describe("nextListOpening", () => {+ const unmounted: TimelineListOpening = { mounted: false };++ it("records the thread a list mounts on", () => {+ expect(nextListOpening(unmounted, true, "a")).toEqual({ mounted: true, identity: "a" });+ });++ it("drops the opening once the list shows another thread, even after returning", () => {+ const switched = nextListOpening({ mounted: true, identity: "a" }, true, "b");+ expect(switched).toEqual({ mounted: true, identity: null });+ expect(nextListOpening(switched, true, "a")).toBe(switched);+ });++ it("records a fresh opening after the list unmounts and remounts", () => {+ const gone = nextListOpening({ mounted: true, identity: null }, false, "b");+ expect(gone).toEqual(unmounted);+ expect(nextListOpening(gone, true, "b")).toEqual({ mounted: true, identity: "b" });+ });++ it("keeps the same state object when nothing changes", () => {+ const opened: TimelineListOpening = { mounted: true, identity: "a" };+ expect(nextListOpening(opened, true, "a")).toBe(opened);+ expect(nextListOpening(unmounted, false, "a")).toBe(unmounted);+ });+});++describe("transitionTimelineFollow", () => {+ const releasedAtEnd: TimelineFollow = { mode: "released", atEnd: true };+ const releasedAway: TimelineFollow = { mode: "released", atEnd: false };++ it("releases on navigation and stays released", () => {+ expect(transitionTimelineFollow(FOLLOWING, { type: "navigated" })).toEqual(releasedAtEnd);+ expect(transitionTimelineFollow(releasedAway, { type: "navigated" })).toBe(releasedAway);+ });++ it("ignores the end band flicker while following", () => {+ expect(transitionTimelineFollow(FOLLOWING, { type: "leftEnd" })).toBe(FOLLOWING);+ });++ it("re-arms only after the released view leaves the end and comes back", () => {+ expect(transitionTimelineFollow(releasedAtEnd, { type: "reachedEnd" })).toBe(releasedAtEnd);+ const away = transitionTimelineFollow(releasedAtEnd, { type: "leftEnd" });+ expect(away).toEqual(releasedAway);+ expect(transitionTimelineFollow(away, { type: "reachedEnd" })).toBe(FOLLOWING);+ });++ it("follows the end on request from any state", () => {+ expect(transitionTimelineFollow(releasedAway, { type: "followEnd" })).toBe(FOLLOWING);+ });++ it("starts a thread visit from its remembered position", () => {+ expect(initialTimelineFollow(true)).toBe(FOLLOWING);+ expect(initialTimelineFollow(false)).toEqual(releasedAway);+ });+});++describe("navigationReleasesFollow", () => {+ const viewport = (contentScrollsUp: boolean, awayFromEnd: boolean) => ({+ contentScrollsUp: () => contentScrollsUp,+ awayFromEnd: () => awayFromEnd,+ });++ it("releases on upward input only when the content can scroll up", () => {+ const up = { source: "wheel", direction: "up" } as const;+ expect(navigationReleasesFollow(up, viewport(true, false))).toBe(true);+ expect(navigationReleasesFollow(up, viewport(false, true))).toBe(false);+ expect(+ navigationReleasesFollow({ source: "wheel", direction: "down" }, viewport(true, true)),+ ).toBe(false);+ });++ it("releases on downward keys, touch and row clicks only away from the end", () => {+ const down = { source: "key", key: "PageDown", direction: "down" } as const;+ expect(navigationReleasesFollow(down, viewport(true, false))).toBe(false);+ expect(navigationReleasesFollow(down, viewport(false, true))).toBe(true);+ expect(navigationReleasesFollow({ source: "touch" }, viewport(true, false))).toBe(false);+ expect(+ navigationReleasesFollow({ source: "pointer", onScrollbar: false }, viewport(true, false)),+ ).toBe(false);+ expect(+ navigationReleasesFollow({ source: "pointer", onScrollbar: true }, viewport(true, false)),+ ).toBe(true);+ });++ it("lets commands decide for themselves", () => {+ expect(+ navigationReleasesFollow({ source: "command", releasesFollow: false }, viewport(true, true)),+ ).toBe(false);+ expect(navigationReleasesFollow({ source: "scroll" }, viewport(false, false))).toBe(true);+ });+});diff --git a/apps/web/src/components/chat/timelineViewport.ts b/apps/web/src/components/chat/timelineViewport.tsnew file mode 100644index 00000000000..2dcbc4ae1d2--- /dev/null+++ b/apps/web/src/components/chat/timelineViewport.ts@@ -0,0 +1,243 @@+import { registerCommands } from "../../shortcuts/dispatcher";+import {+ eventPathContainsSelector,+ TYPE_TO_FOCUS_EDITABLE_SELECTOR,+ TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,+} from "./composerFocusRedirect";+import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";+import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";++/**+ * Which thread the mounted timeline list opened on. LegendList's+ * initialScrollAtEnd only measures for that thread; once the same list shows+ * another thread the opening no longer applies, even if it later returns.+ */+export type TimelineListOpening =+ | { readonly mounted: false }+ | { readonly mounted: true; readonly identity: string | null };++export function nextListOpening(+ current: TimelineListOpening,+ listMounted: boolean,+ identity: string,+): TimelineListOpening {+ if (!listMounted) return current.mounted ? { mounted: false } : current;+ if (!current.mounted) return { mounted: true, identity };+ if (current.identity !== null && current.identity !== identity) {+ return { mounted: true, identity: null };+ }+ return current;+}++export type TimelineScrollDirection = "up" | "down";++/**+ * One user attempt to move the timeline. Gestures come from the viewport's own+ * listeners; "command" is a UI action that is about to move it (minimap,+ * citation, composer page keys, scroll to end).+ */+export type TimelineNavigation =+ | { readonly source: "wheel"; readonly direction: TimelineScrollDirection }+ | { readonly source: "touch" }+ | { readonly source: "pointer"; readonly onScrollbar: boolean }+ | { readonly source: "key"; readonly key: string; readonly direction: TimelineScrollDirection }+ | { readonly source: "scroll" }+ | { readonly source: "command"; readonly releasesFollow: boolean };++export interface TimelineViewport {+ readonly scrollNode: HTMLElement;+ /** Every consumer hears the same navigation, in subscription order. */+ readonly subscribe: (listener: (navigation: TimelineNavigation) => void) => () => void;+ readonly navigate: (options: { readonly releasesFollow: boolean }) => void;+ /**+ * Marks our own scrolling (anchoring a turn, restoring a position) so the+ * upward scroll it causes is not read as the user's. Returns the release.+ */+ readonly holdProgrammaticScroll: () => () => void;+ /** Follow announces letting go, so the list can remember it is reading history. */+ readonly followReleased: () => void;+ readonly onFollowReleased: (listener: () => void) => () => void;+}++const UP_KEYS = new Set(["PageUp", "Home", "ArrowUp"]);+const DOWN_KEYS = new Set(["PageDown", "End", "ArrowDown", " "]);++/**+ * Owns the timeline scroll node's input listeners for as long as the node is+ * mounted, and turns them into one navigation signal.+ */+export function attachTimelineViewport(scrollNode: HTMLElement): TimelineViewport & {+ readonly dispose: () => void;+} {+ const listeners = new Set<(navigation: TimelineNavigation) => void>();+ const followReleasedListeners = new Set<() => void>();+ let programmaticHolds = 0;+ const emit = (navigation: TimelineNavigation) => {+ for (const listener of listeners) listener(navigation);+ };+ const handleWheel = (event: WheelEvent) => {+ if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY)) return;+ emit({ source: "wheel", direction: event.deltaY < 0 ? "up" : "down" });+ };+ const handleTouchMove = () => emit({ source: "touch" });+ // Scrollbar drags produce no wheel/touch events; they are the only+ // pointerdowns whose target is the scroll node itself rather than a row.+ const handlePointerDown = (event: PointerEvent) =>+ emit({ source: "pointer", onScrollbar: event.target === scrollNode });+ // Clicking message text can leave DOM focus on body, and keyboard scrolling+ // bypasses wheel and pointer events, so scroll keys are heard app-wide.+ const handleKeyDown = (event: KeyboardEvent, consumed: boolean) => {+ const direction = UP_KEYS.has(event.key) ? "up" : DOWN_KEYS.has(event.key) ? "down" : null;+ if (+ direction === null ||+ consumed ||+ !(event.target instanceof Node) ||+ (!scrollNode.contains(event.target) &&+ event.target !== document.body &&+ event.target !== document.documentElement) ||+ event.isComposing ||+ event.altKey ||+ event.ctrlKey ||+ event.metaKey ||+ event.shiftKey ||+ eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||+ document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR) ||+ (scrollNode.contains(event.target) &&+ !isTimelineScrollTarget(event.target, scrollNode, direction === "up" ? -1 : 1))+ ) {+ return;+ }+ emit({ source: "key", key: event.key, direction });+ };+ // Input inside an embedded frame reaches none of the listeners above, but+ // its scroll still chains out to the timeline.+ const scrolledUp = createUpwardScrollDetector({+ top: scrollNode.scrollTop,+ height: scrollNode.scrollHeight,+ });+ const handleScroll = () => {+ if (+ scrolledUp({+ top: scrollNode.scrollTop,+ height: scrollNode.scrollHeight,+ programmatic: programmaticHolds > 0,+ }) &&+ // LegendList updates its scroll state on the next animation frame.+ resolveTimelineIsAtEnd({+ contentLength: scrollNode.scrollHeight,+ scroll: scrollNode.scrollTop,+ scrollLength: scrollNode.clientHeight,+ }) === false+ ) {+ emit({ source: "scroll" });+ }+ };+ scrollNode.addEventListener("scroll", handleScroll, { passive: true });+ scrollNode.addEventListener("wheel", handleWheel, { passive: true });+ scrollNode.addEventListener("touchmove", handleTouchMove, { passive: true });+ scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true });+ const unregisterKeyDown = registerCommands({}, { observe: handleKeyDown });+ return {+ scrollNode,+ subscribe: (listener) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ navigate: ({ releasesFollow }) => emit({ source: "command", releasesFollow }),+ holdProgrammaticScroll: () => {+ programmaticHolds += 1;+ let released = false;+ return () => {+ if (released) return;+ released = true;+ programmaticHolds -= 1;+ };+ },+ followReleased: () => {+ for (const listener of followReleasedListeners) listener();+ },+ onFollowReleased: (listener) => {+ followReleasedListeners.add(listener);+ return () => followReleasedListeners.delete(listener);+ },+ dispose: () => {+ listeners.clear();+ followReleasedListeners.clear();+ scrollNode.removeEventListener("scroll", handleScroll);+ scrollNode.removeEventListener("wheel", handleWheel);+ scrollNode.removeEventListener("touchmove", handleTouchMove);+ scrollNode.removeEventListener("pointerdown", handlePointerDown);+ unregisterKeyDown();+ },+ };+}++/**+ * Whether a navigation can carry the viewport away from the live edge. A spurious+ * release while pinned never re-arms, so streaming stops following. Downward input+ * counts only outside the end band: streaming growth makes isAtEnd flicker false+ * for a frame, and a gesture then must not release follow.+ */+export function navigationReleasesFollow(+ navigation: TimelineNavigation,+ viewport: { readonly contentScrollsUp: () => boolean; readonly awayFromEnd: () => boolean },+): boolean {+ switch (navigation.source) {+ case "wheel":+ return navigation.direction === "up" && viewport.contentScrollsUp();+ case "key":+ return navigation.direction === "up" ? viewport.contentScrollsUp() : viewport.awayFromEnd();+ case "pointer":+ return navigation.onScrollbar ? viewport.contentScrollsUp() : viewport.awayFromEnd();+ case "touch":+ // Touch direction is not observable; an upward flick leaves the end+ // band within its first few events.+ return viewport.awayFromEnd();+ case "scroll":+ return true;+ case "command":+ return navigation.releasesFollow;+ }+}++/**+ * Whether the timeline keeps the live end in view. An anchored new turn is+ * following with an anchor present (the anchor lives with the thread's+ * timeline state). `atEnd` only matters once released: while following, the+ * list is at its end by definition.+ */+export type TimelineFollow =+ | { readonly mode: "following" }+ | { readonly mode: "released"; readonly atEnd: boolean };++export type TimelineFollowEvent =+ | { readonly type: "navigated" }+ | { readonly type: "followEnd" }+ | { readonly type: "reachedEnd" }+ | { readonly type: "leftEnd" };++export const FOLLOWING: TimelineFollow = { mode: "following" };++export function initialTimelineFollow(followEnd: boolean): TimelineFollow {+ return followEnd ? FOLLOWING : { mode: "released", atEnd: false };+}++export function transitionTimelineFollow(+ state: TimelineFollow,+ event: TimelineFollowEvent,+): TimelineFollow {+ switch (event.type) {+ case "navigated":+ return state.mode === "released" ? state : { mode: "released", atEnd: true };+ case "followEnd":+ return FOLLOWING;+ case "reachedEnd":+ // Navigating away while still at the end stays released until the list+ // reports leaving and returning, so a scroll key at the end cannot re-arm.+ return state.mode === "released" && !state.atEnd ? FOLLOWING : state;+ case "leftEnd":+ // While following, the list leaves the end band for a frame on every+ // streamed chunk before the follow scroll catches up.+ return state.mode === "released" && state.atEnd ? { mode: "released", atEnd: false } : state;+ }+}diff --git a/apps/web/src/components/chat/useThreadFindPositionReader.ts b/apps/web/src/components/chat/useThreadFindPositionReader.tsindex c64a910487f..6568db9d04d 100644--- a/apps/web/src/components/chat/useThreadFindPositionReader.ts+++ b/apps/web/src/components/chat/useThreadFindPositionReader.ts@@ -13,6 +13,7 @@ import { readThreadFindPosition } from "./threadFindPosition";/** Hands thread find how to read the find position of this timeline's viewport. */export function useThreadFindPositionReader({threadKey,+ navigate,timelineViewportElement,findFoldRunIds,timelineEntries,@@ -24,6 +25,7 @@ export function useThreadFindPositionReader({contentInsetEndAdjustment,}: {readonly threadKey: string;+ readonly navigate: () => void;readonly timelineViewportElement: HTMLDivElement | null;readonly findFoldRunIds: ReadonlyMap<string, RunId> | null;readonly timelineEntries: ReadonlyArray<TimelineEntry>;@@ -83,11 +85,12 @@ export function useThreadFindPositionReader({contentInsetEndAdjustment,);};- return attachThreadFindTimeline({ threadKey, readPosition: read });+ return attachThreadFindTimeline({ threadKey, readPosition: read, navigate });}, [contentInsetEndAdjustment,findFoldRunIds,isWorking,+ navigate,threadKey,latestRun,rows,diff --git a/apps/web/src/components/chat/useTimelineFollow.ts b/apps/web/src/components/chat/useTimelineFollow.tsindex 0d94898466d..4ebf6312dfa 100644--- a/apps/web/src/components/chat/useTimelineFollow.ts+++ b/apps/web/src/components/chat/useTimelineFollow.ts@@ -1,19 +1,13 @@import { useStableCallback } from "../../hooks/useStableCallback";-import {- eventPathContainsSelector,- TYPE_TO_FOCUS_EDITABLE_SELECTOR,- TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,-} from "./composerFocusRedirect";-import { type MessageId, type ThreadId, type RunId } from "@t3tools/contracts";+import { type MessageId, type RunId } from "@t3tools/contracts";import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";import { Debouncer } from "@tanstack/react-pacer";import {type SetStateAction,- useEffect,- useEffectEvent,useLayoutEffect,useRef,useState,+ useSyncExternalStore,} from "react";import { type LegendListRef } from "@legendapp/list/react";import {@@ -22,15 +16,25 @@ import {readTimelinePosition,observeTimelineRun,type TimelineRunObservation,- type TimelineScrollMode,} from "./timelineScrollAnchoring";import { type ChatComposerHandle } from "./ChatComposer";import { createPageScrollController, type PageScrollKey } from "./pageScrollController";-import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";-import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";+import {+ FOLLOWING,+ initialTimelineFollow,+ navigationReleasesFollow,+ transitionTimelineFollow,+ type TimelineFollow,+ type TimelineFollowEvent,+ type TimelineNavigation,+ type TimelineViewport,+} from "./timelineViewport";+import { resolveTimelineIsAtEnd, type MessagesTimelineRow } from "./MessagesTimeline.logic";import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";-import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";-import { releaseChatTimelineAnchor } from "../ChatView.logic";+import {+ releaseChatTimelineAnchor,+ shouldReleaseTimelineAnchorForToolActivity,+} from "../ChatView.logic";import type { Dispatch, RefObject } from "react";import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";import type { deriveThreadActivityRun } from "@t3tools/client-runtime/state/thread-execution";@@ -44,14 +48,110 @@ interface TimelineAnchor {readonly messageId: MessageId | null;}+/** One visit to a thread; a switch starts a new one from the remembered position. */+interface TimelineFollowVisit {+ readonly threadKey: string | null;+ readonly followEnd: boolean;+}++/**+ * Scroll bookkeeping that belongs to one visit. Handlers fetch it for the+ * current visit, so a thread switch leaves the old one behind instead of+ * resetting it.+ */+function createVisitScrollState(+ visit: TimelineFollowVisit,+ showScrollToBottom: (visit: TimelineFollowVisit) => void,+) {+ return {+ visit,+ intent: null as "toward-end" | "away-from-end" | null,+ // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during+ // thread switches. LegendList fires scroll events with isAtEnd=false while+ // initialScrollAtEnd is settling; hiding is always immediate.+ showScrollDebouncer: new Debouncer(() => showScrollToBottom(visit), { wait: 150 }),+ positionedAnchor: null as MessageId | null,+ settledAnchor: null as MessageId | null,+ releaseAnchorScrollHold: null as (() => void) | null,+ pendingAnchorScrollRestore: null as {+ readonly messageId: MessageId;+ readonly offset: number;+ } | null,+ anchorScrollRestoreFrame: null as number | null,+ };+}+type VisitScrollState = ReturnType<typeof createVisitScrollState>;++function stopAnchorPositioning(scroll: VisitScrollState) {+ scroll.positionedAnchor = null;+ scroll.settledAnchor = null;+ scroll.releaseAnchorScrollHold?.();+ scroll.releaseAnchorScrollHold = null;+}++/** Whether the list still shows the anchored message; a thread switch replaces its data. */+function listShowsMessage(list: LegendListRef | null, messageId: MessageId): boolean {+ const rows = list?.getState().data as ReadonlyArray<MessagesTimelineRow> | undefined;+ return rows?.some((row) => row.kind === "message" && row.message.id === messageId) === true;+}++/**+ * The follow mode, read by scroll listeners at event time and by render+ * through useSyncExternalStore. State recorded for an earlier visit is+ * discarded, so a thread switch needs no reset step.+ */+function createTimelineFollowStore() {+ let snapshot: { readonly visit: TimelineFollowVisit | null; readonly follow: TimelineFollow } = {+ visit: null,+ follow: FOLLOWING,+ };+ const listeners = new Set<() => void>();+ // Page keys read the overlay at keypress time; it changes no rendered state.+ let composerOverlay: HTMLElement | null = null;+ const read = (visit: TimelineFollowVisit) =>+ snapshot.visit === visit ? snapshot.follow : initialTimelineFollow(visit.followEnd);+ return {+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ },+ snapshot: () => snapshot,+ read,+ /** Ref callback for the composer overlay. */+ attachComposerOverlay: (element: HTMLElement | null) => {+ composerOverlay = element;+ },+ readComposerOverlayHeight: () => composerOverlay?.getBoundingClientRect().height ?? 0,+ dispatch: (visit: TimelineFollowVisit, event: TimelineFollowEvent) => {+ const before = read(visit);+ const after = transitionTimelineFollow(before, event);+ if (snapshot.visit !== visit || after !== snapshot.follow) {+ snapshot = { visit, follow: after };+ for (const listener of listeners) listener();+ }+ return { before, after };+ },+ };+}++function sameRunObservation(+ next: TimelineRunObservation,+ previous: TimelineRunObservation | null,+): boolean {+ return (+ previous !== null &&+ next.threadKey === previous.threadKey &&+ next.hydrated === previous.hydrated &&+ next.runId === previous.runId+ );+}+interface TimelineFollowInput {readonly legendListRef: RefObject<LegendListRef | null>;readonly composerRef: RefObject<ChatComposerHandle | null>;- readonly composerOverlayElement: HTMLDivElement | null;readonly composerTimelineInset: number;readonly routeThreadKey: string;readonly activeThreadKey: string | null;- readonly activeThreadId: ThreadId | undefined;readonly isServerThread: boolean;readonly serverProjection: ThreadStructure | null;readonly threadStatus: EnvironmentThreadStatus;@@ -64,18 +164,17 @@ interface TimelineFollowInput {/*** Keeps the timeline following the live end, anchoring a newly sent turn near- * the top, and letting the user scroll away. The scroll handlers read refs, so- * a scroll gesture does not re-render ChatView unless the follow mode flips.+ * the top, and letting the user scroll away. Follow lives in a store the+ * viewport's navigation signal writes, so a scroll gesture does not re-render+ * ChatView unless the follow mode flips.*/export function useTimelineFollow(input: TimelineFollowInput) {const {legendListRef,composerRef,- composerOverlayElement,composerTimelineInset,routeThreadKey,activeThreadKey,- activeThreadId,isServerThread,serverProjection,threadStatus,@@ -85,54 +184,75 @@ export function useTimelineFollow(input: TimelineFollowInput) {timelineAnchorMessageId,setTimelineAnchor,} = input;- const [showScrollToBottom, setShowScrollToBottom] = useState(false);- const isAtEndRef = useRef(true);- const isTimelineAtLogicalEnd = () =>- resolveTimelineIsAtEnd(legendListRef.current?.getState()) ?? isAtEndRef.current;- const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);- // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during- // thread switches. LegendList fires scroll events with isAtEnd=false while- // initialScrollAtEnd is settling; hiding is always immediate.- const showScrollDebouncer = useRef(- new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),+ const [visitState, setVisit] = useState<TimelineFollowVisit>({+ threadKey: activeThreadKey,+ followEnd: true,+ });+ let visit = visitState;+ if (visit.threadKey !== activeThreadKey) {+ visit = {+ threadKey: activeThreadKey,+ followEnd: readTimelinePosition(routeThreadKey)?.atEnd !== false,+ };+ setVisit(visit);+ }+ // Keyed by visit, so a pill decision from the previous thread (a pending+ // debounce) never shows here.+ const [pill, setPill] = useState<{ readonly visit: TimelineFollowVisit; readonly show: boolean }>(+ { visit, show: false },);- const timelineScrollIntentRef = useRef<"toward-end" | "away-from-end" | null>(null);- const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");- // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd- // re-pins on its own (independent of the refs), so the timeline needs a- // render-visible flag to switch it off once the user scrolls away.- const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);- const pendingTimelineAnchorRef = useRef<MessageId | null>(null);- const positionedTimelineAnchorRef = useRef<MessageId | null>(null);- const settledTimelineAnchorRef = useRef<MessageId | null>(null);- const activeTimelineAnchorIndexRef = useRef<number | null>(null);- const observedTimelineActivityRef = useRef<TimelineRunObservation | null>(null);- const anchorUserScrollGenerationRef = useRef(0);- const cancelPositionRestoreRef = useRef<(() => void) | null>(null);- const liveFollowUserScrollGenerationRef = useRef<number | null>(0);- const pendingAnchorScrollRestoreRef = useRef<{- readonly messageId: MessageId;- readonly offset: number;- readonly userScrollGeneration: number;- } | null>(null);- const anchorScrollRestoreFrameRef = useRef<number | null>(null);- const cancelTimelineLiveFollowForUserNavigation = () => {- cancelPositionRestoreRef.current?.();- anchorUserScrollGenerationRef.current += 1;- const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";- timelineScrollModeRef.current = "free-scrolling";- liveFollowUserScrollGenerationRef.current = null;- setTimelineLiveFollowEnabled(false);- pendingTimelineAnchorRef.current = null;- positionedTimelineAnchorRef.current = null;- settledTimelineAnchorRef.current = null;- activeTimelineAnchorIndexRef.current = null;- pendingAnchorScrollRestoreRef.current = null;- if (anchorScrollRestoreFrameRef.current !== null) {- cancelAnimationFrame(anchorScrollRestoreFrameRef.current);- anchorScrollRestoreFrameRef.current = null;+ const showScrollToBottom = pill.visit === visit ? pill.show : !visit.followEnd;+ // Called on every streamed chunk while following; an unchanged pill must+ // bail out instead of re-rendering ChatView.+ const setShowScrollToBottom = (show: boolean) =>+ setPill((current) =>+ current.visit === visit && current.show === show ? current : { visit, show },+ );+ const [followStore] = useState(createTimelineFollowStore);+ const followSnapshot = useSyncExternalStore(followStore.subscribe, followStore.snapshot);+ const follow =+ followSnapshot.visit === visit ? followSnapshot.follow : initialTimelineFollow(visit.followEnd);+ const timelineLiveFollowEnabled = follow.mode === "following";+ const readFollow = () => followStore.read(visit);+ // Async settles outlive their render; this reads the visit shown now.+ const readCurrentFollow = useStableCallback(readFollow);+ const isTimelineAtLogicalEnd = () => {+ const current = readFollow();+ return (+ resolveTimelineIsAtEnd(legendListRef.current?.getState()) ??+ (current.mode === "following" || current.atEnd)+ );+ };+ const isTimelineAtLogicalEndStable = useStableCallback(isTimelineAtLogicalEnd);+ const visitScrollRef = useRef<VisitScrollState | null>(null);+ /** Only from handlers: the bookkeeping of the visit they run in. */+ const visitScroll = () => {+ if (visitScrollRef.current?.visit !== visit) {+ visitScrollRef.current = createVisitScrollState(visit, (shownVisit) => {+ // A debounce that outlived its visit must not overwrite the current one's pill.+ if (visitScrollRef.current?.visit === shownVisit)+ setPill({ visit: shownVisit, show: true });+ });}- if (wasProgrammaticScrollMode) {+ return visitScrollRef.current;+ };+ // The anchor whose list position LegendList reported ready; until then a+ // newly started run must not re-anchor.+ const [laidOutAnchor, setLaidOutAnchor] = useState<MessageId | null>(null);+ const anchorPending =+ timelineAnchorMessageId !== null && laidOutAnchor !== timelineAnchorMessageId;+ const viewportRef = useRef<TimelineViewport | null>(null);+ const releaseFollowForNavigation = () => {+ const { before } = followStore.dispatch(visit, { type: "navigated" });+ if (before.mode === "following") viewportRef.current?.followReleased();+ const scroll = visitScroll();+ stopAnchorPositioning(scroll);+ scroll.pendingAnchorScrollRestore = null;+ if (scroll.anchorScrollRestoreFrame !== null) {+ cancelAnimationFrame(scroll.anchorScrollRestoreFrame);+ scroll.anchorScrollRestoreFrame = null;+ }+ if (before.mode === "following") {// LegendList may run queued scrolls after user navigation. A new imperative// scroll cancels that queue; a missing item cancels without moving the view.void legendListRef.current?.scrollToItem({@@ -152,96 +272,51 @@ export function useTimelineFollow(input: TimelineFollowInput) {}}};- const cancelTimelineLiveFollowForUserNavigationStable = useStableCallback(- cancelTimelineLiveFollowForUserNavigation,- );- const cancelTimelineLiveFollowForUserNavigationRef = useRef(- cancelTimelineLiveFollowForUserNavigationStable,- );- useEffect(() => {- cancelTimelineLiveFollowForUserNavigationRef.current =- cancelTimelineLiveFollowForUserNavigationStable;- }, [cancelTimelineLiveFollowForUserNavigationStable]);- useEffect(() => {- const previous = observedTimelineActivityRef.current;- const dispatchedUserItem =- previous?.hydrated &&- previous.threadKey === activeThreadKey &&- activeActivityRun !== null &&- previous.runId !== activeActivityRun.runId- ? serverProjection?.visibleTurnItems.find(- (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,- )- : undefined;- const { observation, anchorMessageId: messageId } = observeTimelineRun(previous, {- threadKey: activeThreadKey,- hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),- runId: activeActivityRun?.runId ?? null,- queued: activeActivityRun?.status === "queued",- messageId:- dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,- });- observedTimelineActivityRef.current = observation;- if (messageId === null) return;- if (- pendingTimelineAnchorRef.current !== null ||- timelineScrollModeRef.current === "free-scrolling"- ) {- return;- }- isAtEndRef.current = true;- timelineScrollModeRef.current = "anchoring-new-turn";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- pendingTimelineAnchorRef.current = messageId;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();- setShowScrollToBottom(false);- setTimelineAnchor({ threadKey: activeThreadKey, messageId });- }, [- activeActivityRun,- activeThreadKey,- isServerThread,- serverProjection,- setTimelineAnchor,- threadStatus,- ]);- const timelineRealContentOverflowsViewport = (list?: LegendListRef | null) =>- timelineContentOverflowsViewport((list ?? legendListRef.current)?.getState(), {+ // A run that starts while the live end is followed anchors its user message+ // near the top, unless the previous anchor has not been laid out yet.+ const [observedRun, setObservedRun] = useState<TimelineRunObservation | null>(null);+ const dispatchedUserItem =+ observedRun?.hydrated &&+ observedRun.threadKey === activeThreadKey &&+ activeActivityRun !== null &&+ observedRun.runId !== activeActivityRun.runId+ ? serverProjection?.visibleTurnItems.find(+ (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId,+ )+ : undefined;+ const runObservation = observeTimelineRun(observedRun, {+ threadKey: activeThreadKey,+ hydrated: !isServerThread || (serverProjection !== null && threadStatus === "live"),+ runId: activeActivityRun?.runId ?? null,+ queued: activeActivityRun?.status === "queued",+ messageId:+ dispatchedUserItem?.item.type === "user_message" ? dispatchedUserItem.item.messageId : null,+ });+ if (!sameRunObservation(runObservation.observation, observedRun)) {+ setObservedRun(runObservation.observation);+ const startedRunAnchor = runObservation.anchorMessageId;+ if (startedRunAnchor !== null && !anchorPending && timelineLiveFollowEnabled) {+ setShowScrollToBottom(false);+ setTimelineAnchor({ threadKey: activeThreadKey, messageId: startedRunAnchor });+ }+ }+ const timelineRealContentOverflowsViewport = () =>+ timelineContentOverflowsViewport(legendListRef.current?.getState(), {composerInset: composerTimelineInset,anchorOffset: CHAT_TIMELINE_ANCHOR_OFFSET,});- const timelineRealContentOverflowsViewportStable = useStableCallback(- timelineRealContentOverflowsViewport,- );const pageScrollControllerRef = useRef<ReturnType<typeof createPageScrollController> | null>(null,);- const handlePageScrollStart = useEffectEvent((key: PageScrollKey) => {- timelineScrollIntentRef.current = key === "PageUp" ? "away-from-end" : "toward-end";+ const handlePageScrollStart = useStableCallback((key: PageScrollKey) => {+ visitScroll().intent = key === "PageUp" ? "away-from-end" : "toward-end";composerRef.current?.collapseForTimelineScrollKey(key);- if (- (key === "PageUp" && timelineRealContentOverflowsViewportStable()) ||- !isTimelineAtLogicalEndStable()- ) {- cancelTimelineLiveFollowForUserNavigationStable();+ if ((key === "PageUp" && timelineRealContentOverflowsViewport()) || !isTimelineAtLogicalEnd()) {+ // Through the viewport, so a running position restore stops too.+ viewportRef.current?.navigate({ releasesFollow: true });}});- useEffect(() => {- const controller = createPageScrollController({- getContainer: () => legendListRef.current?.getScrollableNode() ?? null,- getScrollPaddingBottomPx: () => composerOverlayElement?.getBoundingClientRect().height ?? 0,- onScrollStart: handlePageScrollStart,- });- pageScrollControllerRef.current = controller;-- return () => {- controller.dispose();- if (pageScrollControllerRef.current === controller) {- pageScrollControllerRef.current = null;- }- };- }, [composerOverlayElement, legendListRef]);const onComposerPageScrollKeyDown = (key: PageScrollKey) => {pageScrollControllerRef.current?.handleKeyDown(key);};@@ -255,14 +330,10 @@ export function useTimelineFollow(input: TimelineFollowInput) {};const onComposerPageScrollReleaseStable = useStableCallback(onComposerPageScrollRelease);const scrollToEnd = (animated: boolean = false) => {- cancelPositionRestoreRef.current?.();- isAtEndRef.current = true;- timelineScrollModeRef.current = "following-end";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);- pendingTimelineAnchorRef.current = null;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();+ // Stops a running position restore; follow itself is re-armed below.+ viewportRef.current?.navigate({ releasesFollow: false });+ followStore.dispatch(visit, { type: "followEnd" });+ visitScroll().showScrollDebouncer.cancel();setShowScrollToBottom(false);setTimelineAnchor(releaseChatTimelineAnchor);// The anchored end space must be gone before the scroll measures, or the@@ -278,217 +349,96 @@ export function useTimelineFollow(input: TimelineFollowInput) {settleListScroll(list,measuredEndOffset,- () => timelineScrollModeRef.current !== "following-end" || legendListRef.current !== list,+ () => readCurrentFollow().mode !== "following" || legendListRef.current !== list,),);});};const scrollToEndStable = useStableCallback(scrollToEnd);- useEffect(() => {- const composer = composerRef;- let removeListeners: (() => void) | null = null;- let frame: number | null = null;- const attach = (remainingAttempts: number) => {- frame = requestAnimationFrame(() => {- frame = null;- const scrollNode = legendListRef.current?.getScrollableNode();- if (!scrollNode) {- // The list may not have mounted on the first frame after a thread- // switch — without a retry the opt-out listeners never attach and- // live-follow becomes impossible to escape for the whole thread.- if (remainingAttempts > 0) {- attach(remainingAttempts - 1);- }- return;- }- const handleManualNavigation = () => {- cancelTimelineLiveFollowForUserNavigationRef.current();- };- // Only break follow for gestures that can move away from the live edge.- // A spurious break emits no scroll event to re-arm follow, so streaming stops- // following. Underflowing content cannot scroll and must keep following.- const contentScrollsUp = () => timelineRealContentOverflowsViewportStable();- // The follow re-arm band, not the strict flag: streaming growth makes- // isAtEnd flicker false for a frame before the follow scroll catches- // up, and a gesture landing in that window while still pinned would- // otherwise break follow with no scroll event left to re-arm it.- const viewportIsAwayFromEnd = () =>- resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;- const handleWheel = (event: WheelEvent) => {- if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))- return;- if (event.deltaY > 0) {- timelineScrollIntentRef.current = "toward-end";- if (isAtEndRef.current) {- composer.current?.restoreAfterTimelineReachedEnd();- }- } else if (event.deltaY < 0) {- timelineScrollIntentRef.current = "away-from-end";- }- if (event.deltaY < 0 && contentScrollsUp()) {- handleManualNavigation();- }- };- // Touch direction isn't observable here (touchmove fires on any- // finger motion, scrolling or not), so break only once the drag has- // actually carried the viewport out of the end band — an upward flick- // gets there within its first few events and later touchmoves break.- const handleTouchMove = () => {- if (viewportIsAwayFromEnd()) {- handleManualNavigation();- }- };- // Scrollbar drags produce no wheel/touch events; they are the only- // pointerdowns whose target is the scroll node itself rather than a- // message row.- const handlePointerDown = (event: PointerEvent) => {- if (event.target === scrollNode) {- if (contentScrollsUp()) {- handleManualNavigation();- }- return;- }- if (viewportIsAwayFromEnd()) {- handleManualNavigation();- }- };- // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and- // pointer events entirely; without this the timeline yanks back to- // the end on the next stream chunk. Clicking message text can leave- // DOM focus on body, so these keys must also be heard at document.- const handleKeyDown = (event: KeyboardEvent) => {- if (- !(event.target instanceof Node) ||- (!scrollNode.contains(event.target) &&- event.target !== document.body &&- event.target !== document.documentElement) ||- event.defaultPrevented ||- event.isComposing ||- event.altKey ||- event.ctrlKey ||- event.metaKey ||- event.shiftKey ||- eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||- document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)- ) {- return;- }- if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))- return;- const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;- if (- scrollNode.contains(event.target) &&- !isTimelineScrollTarget(event.target, scrollNode, scrollDirection)- )- return;- switch (event.key) {- case "PageUp":- case "Home":- case "ArrowUp":- timelineScrollIntentRef.current = "away-from-end";- if (contentScrollsUp()) {- handleManualNavigation();- composer.current?.collapseForTimelineScrollKey(event.key);- }- break;- case "PageDown":- case "End":- case "ArrowDown":- timelineScrollIntentRef.current = "toward-end";- if (viewportIsAwayFromEnd()) {- handleManualNavigation();- }- composer.current?.collapseForTimelineScrollKey(event.key);- if (isTimelineAtLogicalEndStable()) {- composer.current?.restoreAfterTimelineReachedEnd();- }- break;- default:- break;- }- };- // Input inside an embedded frame reaches none of the listeners above,- // but its scroll still chains out to the timeline.- const scrolledUp = createUpwardScrollDetector({- top: scrollNode.scrollTop,- height: scrollNode.scrollHeight,- });- const handleScroll = () => {- if (- scrolledUp({- top: scrollNode.scrollTop,- height: scrollNode.scrollHeight,- programmatic:- positionedTimelineAnchorRef.current !== null &&- positionedTimelineAnchorRef.current !== settledTimelineAnchorRef.current,- }) &&- timelineScrollModeRef.current !== "free-scrolling" &&- // LegendList updates its scroll state on the next animation frame.- resolveTimelineIsAtEnd({- contentLength: scrollNode.scrollHeight,- scroll: scrollNode.scrollTop,- scrollLength: scrollNode.clientHeight,- }) === false- ) {- handleManualNavigation();- }- };- scrollNode.addEventListener("scroll", handleScroll, { passive: true });- scrollNode.addEventListener("wheel", handleWheel, {- passive: true,- });- scrollNode.addEventListener("touchmove", handleTouchMove, {- passive: true,- });- scrollNode.addEventListener("pointerdown", handlePointerDown, {- passive: true,- });- document.addEventListener("keydown", handleKeyDown);- removeListeners = () => {- scrollNode.removeEventListener("scroll", handleScroll);- scrollNode.removeEventListener("wheel", handleWheel);- scrollNode.removeEventListener("touchmove", handleTouchMove);- scrollNode.removeEventListener("pointerdown", handlePointerDown);- document.removeEventListener("keydown", handleKeyDown);- };- });- };- attach(12);- return () => {- if (frame !== null) {- cancelAnimationFrame(frame);+ const handleNavigation = (navigation: TimelineNavigation) => {+ const composer = composerRef.current;+ const awayFromEnd = () => resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;+ const releases = navigationReleasesFollow(navigation, {+ contentScrollsUp: timelineRealContentOverflowsViewport,+ awayFromEnd,+ });+ if (navigation.source === "wheel") {+ visitScroll().intent = navigation.direction === "down" ? "toward-end" : "away-from-end";+ const current = readFollow();+ if (navigation.direction === "down" && (current.mode === "following" || current.atEnd)) {+ composer?.restoreAfterTimelineReachedEnd();+ }+ }+ if (navigation.source === "key") {+ visitScroll().intent = navigation.direction === "down" ? "toward-end" : "away-from-end";+ }+ if (releases) releaseFollowForNavigation();+ if (navigation.source === "key" && navigation.key !== " ") {+ if (navigation.direction === "up") {+ if (releases) composer?.collapseForTimelineScrollKey(navigation.key);+ } else {+ composer?.collapseForTimelineScrollKey(navigation.key);+ if (isTimelineAtLogicalEnd()) composer?.restoreAfterTimelineReachedEnd();}- removeListeners?.();+ }+ };+ const handleNavigationStable = useStableCallback(handleNavigation);+ /**+ * Attached by the timeline's list ref callback, so follow hears the+ * viewport's navigation exactly as long as the scroll node exists.+ */+ const attachTimelineViewport = (viewport: TimelineViewport) => {+ viewportRef.current = viewport;+ const unsubscribe = viewport.subscribe(handleNavigationStable);+ const controller = createPageScrollController({+ getContainer: () => viewport.scrollNode,+ getScrollPaddingBottomPx: followStore.readComposerOverlayHeight,+ onScrollStart: handlePageScrollStart,+ });+ pageScrollControllerRef.current = controller;+ return () => {+ unsubscribe();+ controller.dispose();+ if (pageScrollControllerRef.current === controller) pageScrollControllerRef.current = null;+ if (viewportRef.current === viewport) viewportRef.current = null;+ const scroll = visitScrollRef.current;+ scroll?.releaseAnchorScrollHold?.();+ if (scroll) scroll.releaseAnchorScrollHold = null;};- }, [- // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A thread switch remounts the list's scroll node, so the listeners reattach.- activeThreadId,- composerRef,- isTimelineAtLogicalEndStable,- legendListRef,- timelineRealContentOverflowsViewportStable,- ]);+ };const onTimelineAnchorReady = (messageId: MessageId, anchorIndex: number) => {- if (pendingTimelineAnchorRef.current === messageId) {- pendingTimelineAnchorRef.current = null;- }- activeTimelineAnchorIndexRef.current = anchorIndex;- if (positionedTimelineAnchorRef.current === messageId) {+ setLaidOutAnchor(messageId);+ const scroll = visitScroll();+ if (scroll.positionedAnchor === messageId) {return;}- positionedTimelineAnchorRef.current = messageId;- settledTimelineAnchorRef.current = null;+ stopAnchorPositioning(scroll);+ scroll.positionedAnchor = messageId;+ // The positioning scroll moves up when the anchor sits above the view.+ const releaseHold = viewportRef.current?.holdProgrammaticScroll() ?? (() => {});+ scroll.releaseAnchorScrollHold = releaseHold;+ const isPositioning = () =>+ scroll.positionedAnchor === messageId && listShowsMessage(legendListRef.current, messageId);+ // Releasing is idempotent, so an attempt that is no longer current (the+ // thread switched, the user navigated) always lets go of its own hold.+ const abandon = () => {+ releaseHold();+ if (scroll.positionedAnchor === messageId) stopAnchorPositioning(scroll);+ };const positionAnchor = (remainingAttempts: number) => {requestAnimationFrame(() => {- if (positionedTimelineAnchorRef.current !== messageId) {+ if (!isPositioning()) {+ abandon();return;}const list = legendListRef.current;if (!list) {if (remainingAttempts > 0) {positionAnchor(remainingAttempts - 1);+ } else {+ abandon();}return;}@@ -501,11 +451,12 @@ export function useTimelineFollow(input: TimelineFollowInput) {viewOffset: CHAT_LIST_ANCHOR_OFFSET,}).then(() => {- if (- legendListRef.current === list &&- positionedTimelineAnchorRef.current === messageId- ) {- settledTimelineAnchorRef.current = messageId;+ if (legendListRef.current === list && isPositioning()) {+ scroll.settledAnchor = messageId;+ releaseHold();+ scroll.releaseAnchorScrollHold = null;+ } else {+ abandon();}});});@@ -514,35 +465,25 @@ export function useTimelineFollow(input: TimelineFollowInput) {};const onTimelineAnchorReadyStable = useStableCallback(onTimelineAnchorReady);const onTimelineAnchorSizeChanged = (messageId: MessageId) => {- if (settledTimelineAnchorRef.current !== messageId) {- return;- }- if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) {+ const scroll = visitScroll();+ if (scroll.settledAnchor !== messageId || readFollow().mode === "following") {return;}const scrollOffset = legendListRef.current?.getState().scroll;if (scrollOffset === undefined) {return;}- if (pendingAnchorScrollRestoreRef.current === null) {- pendingAnchorScrollRestoreRef.current = {- messageId,- offset: scrollOffset,- userScrollGeneration: anchorUserScrollGenerationRef.current,- };+ if (scroll.pendingAnchorScrollRestore === null) {+ scroll.pendingAnchorScrollRestore = { messageId, offset: scrollOffset };}- if (anchorScrollRestoreFrameRef.current !== null) {+ if (scroll.anchorScrollRestoreFrame !== null) {return;}- anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => {- anchorScrollRestoreFrameRef.current = null;- const pending = pendingAnchorScrollRestoreRef.current;- pendingAnchorScrollRestoreRef.current = null;- if (- pending &&- settledTimelineAnchorRef.current === pending.messageId &&- pending.userScrollGeneration === anchorUserScrollGenerationRef.current- ) {+ scroll.anchorScrollRestoreFrame = requestAnimationFrame(() => {+ scroll.anchorScrollRestoreFrame = null;+ const pending = scroll.pendingAnchorScrollRestore;+ scroll.pendingAnchorScrollRestore = null;+ if (pending && scroll.settledAnchor === pending.messageId) {const list = legendListRef.current;const currentScrollOffset = list?.getState().scroll;if (@@ -562,30 +503,25 @@ export function useTimelineFollow(input: TimelineFollowInput) {const onToolOutputCollapsedAtEndStable = useStableCallback(onToolOutputCollapsedAtEnd);const onIsAtEndChange = (isAtEnd: boolean) => {- if (- !isAtEnd &&- liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current- ) {- showScrollDebouncer.current.cancel();+ const scroll = visitScroll();+ if (!isAtEnd && readFollow().mode === "following") {+ scroll.showScrollDebouncer.cancel();setShowScrollToBottom(false);return;}- if (isAtEndRef.current === isAtEnd) return;- isAtEndRef.current = isAtEnd;- if (isAtEnd) {- if (timelineScrollIntentRef.current === "toward-end") {+ const { before, after } = followStore.dispatch(visit, {+ type: isAtEnd ? "reachedEnd" : "leftEnd",+ });+ if (after === before) return;+ if (after.mode === "following") {+ if (scroll.intent === "toward-end") {composerRef.current?.restoreAfterTimelineReachedEnd();}- timelineScrollModeRef.current = "following-end";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);setTimelineAnchor(releaseChatTimelineAnchor);- showScrollDebouncer.current.cancel();+ scroll.showScrollDebouncer.cancel();setShowScrollToBottom(false);} else {- timelineScrollModeRef.current = "free-scrolling";- liveFollowUserScrollGenerationRef.current = null;- showScrollDebouncer.current.maybeExecute();+ scroll.showScrollDebouncer.maybeExecute();}};const onIsAtEndChangeStable = useStableCallback(onIsAtEndChange);@@ -597,10 +533,14 @@ export function useTimelineFollow(input: TimelineFollowInput) {serverProjection?.visibleTurnItems.some((row) => row.item.type === "reasoning" && row.item.runId === activeRunningTurnId,) === true;+ // Z: the release scrolls, and that scroll must follow the commit that drops+ // the anchored end space; the trigger is streamed thread data. A+ // totalSize listener cannot replace it: the anchored end space can already+ // be 0, so dropping it changes no size and no list event fires.useLayoutEffect(() => {- if (timelineScrollModeRef.current !== "anchoring-new-turn") return;+ if (timelineAnchorMessageId === null || !timelineLiveFollowEnabled) return;if (- (runningTurnHasReasoning && timelineAnchorMessageId !== null && timelineLiveFollowEnabled) ||+ runningTurnHasReasoning ||shouldReleaseTimelineAnchorForToolActivity({anchorMessageId: timelineAnchorMessageId,liveFollowEnabled: timelineLiveFollowEnabled,@@ -619,42 +559,10 @@ export function useTimelineFollow(input: TimelineFollowInput) {timelineLiveFollowEnabled,]);- // A thread switch restores that thread's remembered follow state; the refs- // the scroll handlers read catch up after commit.- const [timelineThreadReset, setTimelineThreadReset] = useState({- threadKey: activeThreadKey,- followEnd: true,- });- if (timelineThreadReset.threadKey !== activeThreadKey) {- const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;- setTimelineThreadReset({ threadKey: activeThreadKey, followEnd });- setTimelineLiveFollowEnabled(followEnd);- setShowScrollToBottom(!followEnd);- }- useEffect(() => {- const { followEnd } = timelineThreadReset;- isAtEndRef.current = followEnd;- timelineScrollIntentRef.current = null;- timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";- liveFollowUserScrollGenerationRef.current = followEnd- ? anchorUserScrollGenerationRef.current- : null;- pendingTimelineAnchorRef.current = null;- positionedTimelineAnchorRef.current = null;- settledTimelineAnchorRef.current = null;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();- }, [timelineThreadReset]);-/** Arms the anchor for a message the user just sent, before its run exists. */const anchorNewTurn = (threadKey: string, messageId: MessageId) => {- isAtEndRef.current = true;- timelineScrollModeRef.current = "anchoring-new-turn";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);- pendingTimelineAnchorRef.current = messageId;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();+ followStore.dispatch(visit, { type: "followEnd" });+ visitScroll().showScrollDebouncer.cancel();setShowScrollToBottom(false);setTimelineAnchor({ threadKey, messageId });};@@ -662,9 +570,7 @@ export function useTimelineFollow(input: TimelineFollowInput) {return {showScrollToBottom,timelineLiveFollowEnabled,- cancelPositionRestoreRef,isTimelineAtLogicalEndStable,- cancelTimelineLiveFollowForUserNavigationStable,onComposerPageScrollKeyDownStable,onComposerPageScrollKeyUpStable,onComposerPageScrollReleaseStable,@@ -674,5 +580,7 @@ export function useTimelineFollow(input: TimelineFollowInput) {onToolOutputCollapsedAtEndStable,onIsAtEndChangeStable,anchorNewTurn,+ attachTimelineViewport,+ attachComposerOverlay: followStore.attachComposerOverlay,};}diff --git a/apps/web/src/components/chat/useTimelinePositionRestore.ts b/apps/web/src/components/chat/useTimelinePositionRestore.tsindex 52cd99c96c4..97374d7c19f 100644--- a/apps/web/src/components/chat/useTimelinePositionRestore.ts+++ b/apps/web/src/components/chat/useTimelinePositionRestore.ts@@ -1,8 +1,7 @@-import { useLayoutEffect, useRef } from "react";import type { LegendListRef } from "@legendapp/list/react";-import type { AssistantCitationRequest } from "./AssistantCitationSource";import type { MessagesTimelineRow } from "./MessagesTimeline.logic";import type { RememberedTimelinePosition } from "./timelineScrollAnchoring";+import type { TimelineViewport } from "./timelineViewport";// 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.@@ -48,146 +47,104 @@ export const measuredEndOffset = (element: HTMLElement) =>/*** 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.+ * and reports the thread positioned once the saved row settles. Any navigation+ * on the viewport cancels it where it is. Returns the cancel for the+ * operation's owner.*/-export function useTimelinePositionRestore({- listRef,+export function startTimelinePositionRestore({+ list,+ viewport,listIdentityKey,- restoringThreadPosition,- rememberedPosition,- rows,- citationRequest,- cancelPositionRestoreRef,- onManualNavigation,+ listOpenedOn,+ rememberedPosition: position,+ citationPending,+ releaseForFind,onPositioned,}: {- readonly listRef: React.RefObject<LegendListRef | null>;+ readonly list: LegendListRef;+ readonly viewport: TimelineViewport;readonly listIdentityKey: string;- readonly restoringThreadPosition: boolean;+ /** The identity the mounted list opened on, until it shows another; see nextListOpening. */+ readonly listOpenedOn: string | null;readonly rememberedPosition: RememberedTimelinePosition | undefined;- readonly rows: MessagesTimelineRow[];- readonly citationRequest: AssistantCitationRequest | null;- readonly cancelPositionRestoreRef: React.RefObject<(() => void) | null> | undefined;- readonly onManualNavigation: () => void;+ readonly citationPending: boolean;+ /**+ * Find was open when the list started showing the thread. Opening find is+ * navigation, so follow lets go; the thread still opens where it was left,+ * and MessagesTimeline holds find's reveal until this reports it positioned.+ */+ readonly releaseForFind: boolean;readonly onPositioned: (identity: string) => void;-}) {- // Preserve initialScrollAtEnd's measured target until the list is reused- // for another thread; scrollToEnd would replace it with an estimated offset.- const listOpenedOnRef = useRef<{- readonly list: LegendListRef;- identity: string | null;- } | null>(null);- useLayoutEffect(() => {- const list = listRef.current;- const opened = listOpenedOnRef.current;- if (!list) return;- if (opened?.list !== list) {- listOpenedOnRef.current = { list, identity: listIdentityKey };- } else if (opened.identity !== listIdentityKey) {- opened.identity = null;- }+}): () => void {+ if (citationPending) {+ // The citation scroll owns positioning once the list has mounted.+ onPositioned(listIdentityKey);+ return () => {};+ }+ let cancelled = false;+ const rows = list.getState().data as ReadonlyArray<MessagesTimelineRow>;+ const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;+ // Reading history or finding: follow lets go before the restore claims the viewport.+ if (position?.atEnd === false || releaseForFind) viewport.navigate({ releasesFollow: true });+ const releaseScrollHold = viewport.holdProgrammaticScroll();+ const stop = () => {+ cancelled = true;+ releaseScrollHold();+ unsubscribe();+ };+ const unsubscribe = viewport.subscribe(() => {+ if (cancelled) return;+ stop();+ void list.scrollToOffset({ offset: viewport.scrollNode.scrollTop, animated: false });+ onPositioned(listIdentityKey);});- useLayoutEffect(() => {- if (!restoringThreadPosition || rows.length === 0) return;- const list = listRef.current;- if (!list) return;- if (citationRequest !== null) {- // The citation scroll owns positioning once the list has mounted.- onPositioned(listIdentityKey);- return;+ const finish = () => {+ stop();+ onPositioned(listIdentityKey);+ };+ const scrolling =+ position?.atEnd === false+ ? index >= 0+ ? list.scrollToIndex({+ index,+ animated: false,+ viewPosition: 0,+ viewOffset: -position.offsetWithinRow,+ })+ : list.scrollToOffset({ offset: position.scrollOffset, animated: false })+ : // initialScrollAtEnd measured this target; scrollToEnd would replace it with an estimate.+ listOpenedOn === listIdentityKey+ ? undefined+ : list.scrollToEnd({ animated: false });+ const settlesAtEnd = position?.atEnd !== false && scrolling !== undefined;+ void Promise.resolve(scrolling).then(async () => {+ if (cancelled) return;+ 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,+ );}- let cancelled = false;- const viewport: HTMLElement | null = list.getScrollableNode();- const cancelRestoration = () => {- if (cancelled) return;- cancelled = true;- if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });- onPositioned(listIdentityKey);- };- const cancelForNavigation = () => {- cancelRestoration();- onManualNavigation();- };- const onScrollKey = (event: globalThis.KeyboardEvent) => {- if (- ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key) &&- !(- event.target instanceof Element &&- event.target.closest("input, textarea, [contenteditable=true]")- )- )- cancelForNavigation();- };- viewport?.addEventListener("wheel", cancelForNavigation, { passive: true });- viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });- viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });- viewport?.ownerDocument.addEventListener("keydown", onScrollKey);- const position = rememberedPosition;- const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;- if (position?.atEnd === false) onManualNavigation();- if (cancelPositionRestoreRef) cancelPositionRestoreRef.current = cancelRestoration;- const scrolling =- position?.atEnd === false- ? index >= 0- ? list.scrollToIndex({- index,- animated: false,- viewPosition: 0,- viewOffset: -position.offsetWithinRow,- })- : list.scrollToOffset({ offset: position.scrollOffset, animated: false })- : listOpenedOnRef.current?.identity === listIdentityKey- ? undefined- : list.scrollToEnd({ animated: false });- const settlesAtEnd = position?.atEnd !== false && scrolling !== undefined;- void Promise.resolve(scrolling).then(async () => {- if (cancelled) return;- 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 (!cancelled) onPositioned(listIdentityKey);- });- return () => {- cancelled = true;- if (cancelPositionRestoreRef?.current === cancelRestoration) {- cancelPositionRestoreRef.current = null;- }- viewport?.removeEventListener("wheel", cancelForNavigation);- viewport?.removeEventListener("touchmove", cancelForNavigation);- viewport?.removeEventListener("pointerdown", cancelForNavigation);- viewport?.ownerDocument.removeEventListener("keydown", onScrollKey);- };- }, [- citationRequest,- cancelPositionRestoreRef,- listIdentityKey,- listRef,- onManualNavigation,- onPositioned,- rememberedPosition,- restoringThreadPosition,- rows,- ]);+ if (!cancelled) finish();+ });+ return stop;}diff --git a/apps/web/src/components/guest/GuestPage.tsx b/apps/web/src/components/guest/GuestPage.tsxindex 28b28161866..f8268d9fe49 100644--- a/apps/web/src/components/guest/GuestPage.tsx+++ b/apps/web/src/components/guest/GuestPage.tsx@@ -392,11 +392,9 @@ function GuestThread({const follow = useTimelineFollow({legendListRef: listRef,composerRef: NO_COMPOSER,- composerOverlayElement: null,composerTimelineInset: 0,routeThreadKey: threadKey,activeThreadKey: threadKey,- activeThreadId: undefined,// Not a server thread: new turns follow the end instead of anchoring near the top.isServerThread: false,serverProjection: null,@@ -476,8 +474,7 @@ function GuestThread({emptyPlaceholderInset={0}liveFollowEnabled={follow.timelineLiveFollowEnabled}onIsAtEndChange={follow.onIsAtEndChangeStable}- onManualNavigation={follow.cancelTimelineLiveFollowForUserNavigationStable}- cancelPositionRestoreRef={follow.cancelPositionRestoreRef}+ onViewportAttach={follow.attachTimelineViewport}footer={unplaced.length === 0 ? null : (<ol ref={footerRef} className="chat-content-lane flex flex-col gap-4 pb-4">