fix(web): let LegendList own end-follow and disclosure anchoring (#5449)

Complete the #5449 architecture on the v2 timeline, following the
LegendList author's direction to lean on the list's native mechanisms
instead of app-side scroll layers:

- maintainScrollAtEnd is enabled and owned by LegendList, gated off only
  while the user reads history (liveFollowEnabled), while a sent turn
  anchors near the top (anchoredEndSpace), or during the two-frame settle
  of a fold toggle.
- maintainVisibleContentPosition compensates size changes natively
  ({data, size, shouldRestorePosition}); fold toggles anchor compensation
  to the toggled row via a disclosure anchor key, so the trigger stays
  under the pointer instead of the viewport chasing the end.
- ChatView's hand-rolled streaming follow (double-rAF scrollToEnd on
  every data change) is gone; the app now only owns streaming
  adjustments during anchored-end-space mode, mirroring main.
- timelineLiveFollowEnabled state mirrors the follow refs so the
  render-visible gate switches native follow off when a gesture breaks
  follow and back on when the viewport returns to the end band.

Timeline tests updated to assert the native-ownership invariants.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Fable 5 committed 2026-08-14 11:23:33 +02:00
1 parent 66d820ed32
commit c178154106
3 files changed
+135 -57

No files matched your search

+23 -25
View File
@@ -3652,6 +3652,10 @@ function ChatViewContent(props: ChatViewProps) {
new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),
);
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);
@@ -3676,6 +3680,7 @@ function ChatViewContent(props: ChatViewProps) {
const wasProgrammaticScrollMode = timelineScrollModeRef.current !== "free-scrolling";
timelineScrollModeRef.current = "free-scrolling";
liveFollowUserScrollGenerationRef.current = null;
setTimelineLiveFollowEnabled(false);
pendingTimelineAnchorRef.current = null;
positionedTimelineAnchorRef.current = null;
settledTimelineAnchorRef.current = null;
@@ -3814,6 +3819,7 @@ function ChatViewContent(props: ChatViewProps) {
isAtEndRef.current = true;
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = null;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
@@ -4034,6 +4040,7 @@ function ChatViewContent(props: ChatViewProps) {
if (isAtEnd) {
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
showScrollDebouncer.current.cancel();
setShowScrollToBottom(false);
} else {
@@ -4043,6 +4050,10 @@ function ChatViewContent(props: ChatViewProps) {
}
}, []);
// Anchored end space intentionally disables LegendList's normal end-follow so
// the sent message can stay near the top. T3 only owns streaming adjustments
// during that mode; LegendList owns ordinary end-follow everywhere else
// (#5449, maintainScrollAtEnd gated by liveFollowEnabled in the timeline).
useEffect(() => {
if (!activeThread?.id) {
return;
@@ -4050,6 +4061,9 @@ function ChatViewContent(props: ChatViewProps) {
if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {
return;
}
if (timelineScrollModeRef.current !== "anchoring-new-turn") {
return;
}
let secondFrame: number | null = null;
const frame = requestAnimationFrame(() => {
@@ -4071,28 +4085,13 @@ function ChatViewContent(props: ChatViewProps) {
return;
}
if (timelineScrollModeRef.current === "anchoring-new-turn") {
const metrics = getActiveTimelineTurnMetrics(list);
if (!metrics) {
return;
}
if (metrics.scrollDeltaToRevealEnd <= 1) {
return;
}
const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;
void list.scrollToOffset({ offset: nextOffset, animated: false });
const metrics = getActiveTimelineTurnMetrics(list);
if (!metrics || metrics.scrollDeltaToRevealEnd <= 1) {
return;
}
if (timelineScrollModeRef.current !== "following-end") {
return;
}
if (!timelineRealContentOverflowsViewport(list)) {
return;
}
void list.scrollToEnd?.({ animated: false });
const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;
void list.scrollToOffset({ offset: nextOffset, animated: false });
});
});
@@ -4102,18 +4101,14 @@ function ChatViewContent(props: ChatViewProps) {
cancelAnimationFrame(secondFrame);
}
};
}, [
activeThread?.id,
timelineEntries,
getActiveTimelineTurnMetrics,
timelineRealContentOverflowsViewport,
]);
}, [activeThread?.id, timelineEntries, getActiveTimelineTurnMetrics]);
useEffect(() => {
setPullRequestDialogState(null);
isAtEndRef.current = true;
timelineScrollModeRef.current = "following-end";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = null;
positionedTimelineAnchorRef.current = null;
settledTimelineAnchorRef.current = null;
@@ -5182,6 +5177,7 @@ function ChatViewContent(props: ChatViewProps) {
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
@@ -5619,6 +5615,7 @@ function ChatViewContent(props: ChatViewProps) {
isAtEndRef.current = true;
timelineScrollModeRef.current = "anchoring-new-turn";
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
setTimelineLiveFollowEnabled(true);
pendingTimelineAnchorRef.current = messageIdForSend;
activeTimelineAnchorIndexRef.current = null;
showScrollDebouncer.current.cancel();
@@ -6328,6 +6325,7 @@ function ChatViewContent(props: ChatViewProps) {
onAnchorReady={onTimelineAnchorReady}
onAnchorSizeChanged={onTimelineAnchorSizeChanged}
contentInsetEndAdjustment={composerOverlayHeight}
liveFollowEnabled={timelineLiveFollowEnabled}
onIsAtEndChange={onIsAtEndChange}
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
hideEmptyPlaceholder={isDraftHeroState}
@@ -90,6 +90,11 @@ vi.mock("@legendapp/list/react", async () => {
? props.maintainVisibleContentPosition.size
: undefined
}
data-maintain-visible-content-position-restore={
typeof props.maintainVisibleContentPosition === "object"
? Boolean(props.maintainVisibleContentPosition.shouldRestorePosition)
: undefined
}
>
{props.ListHeaderComponent}
{props.data.map((item) => (
@@ -196,6 +201,7 @@ function buildProps() {
onAnchorReady: () => {},
onAnchorSizeChanged: () => {},
contentInsetEndAdjustment: 0,
liveFollowEnabled: true,
onIsAtEndChange: () => {},
onManualNavigation: () => {},
};
@@ -428,7 +434,8 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-maintain-visible-content-position="object"');
expect(markup).toContain('data-maintain-visible-content-position-data="true"');
expect(markup).toContain('data-maintain-visible-content-position-size="false"');
expect(markup).toContain('data-maintain-visible-content-position-size="true"');
expect(markup).toContain('data-maintain-visible-content-position-restore="true"');
expect(onAnchorReady).toHaveBeenCalledOnce();
expect(onAnchorReady).toHaveBeenCalledWith(secondEntry.message.id, 1);
expect(onAnchorSizeChanged).toHaveBeenCalledWith(secondEntry.message.id, 240);
@@ -443,10 +450,13 @@ describe("MessagesTimeline", () => {
);
expect(markup).toContain("Show full message");
// LegendList's internal maintainScrollAtEnd stays off: it races post-mount
// measurement and snaps the view to stale content ends. End-following is
// owned by ChatView's live-follow, which respects user scroll gestures.
expect(markup).not.toContain('data-maintain-scroll-at-end="enabled"');
// LegendList owns ordinary end-follow (#5449): with live follow on and no
// anchored end space, its maintainScrollAtEnd is enabled.
expect(markup).toContain('data-maintain-scroll-at-end="enabled"');
expect(markup).toContain('data-maintain-scroll-at-end-animated="false"');
expect(markup).toContain('data-maintain-scroll-at-end-data-change="true"');
expect(markup).toContain('data-maintain-scroll-at-end-item-layout="true"');
expect(markup).toContain('data-maintain-scroll-at-end-layout="true"');
expect(markup).toContain('data-user-message-collapsed="true"');
expect(markup).toContain('data-user-message-fade="true"');
expect(markup).toContain('data-user-message-footer="true"');
@@ -178,6 +178,14 @@ const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
const TIMELINE_MAINTAIN_SCROLL_AT_END = {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
} as const;
const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray<ServerProvider> = [];
const EMPTY_TIMELINE_RUNS: ReadonlyArray<HandoffTimelineRun> = [];
@@ -229,6 +237,13 @@ interface MessagesTimelineProps {
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
/**
* Whether the timeline should keep pinning to the live edge as content
* grows. Off while the user is reading history; LegendList's own
* maintainScrollAtEnd would otherwise re-pin regardless of ChatView's
* scroll-mode refs whenever the user drifts near the bottom.
*/
liveFollowEnabled: boolean;
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
topFadeEnabled?: boolean;
@@ -270,6 +285,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onAnchorSizeChanged,
contentInsetEndAdjustment,
onIsAtEndChange,
liveFollowEnabled,
onManualNavigation,
hideEmptyPlaceholder = false,
topFadeEnabled = false,
@@ -279,30 +295,81 @@ export const MessagesTimeline = memo(function MessagesTimeline({
new Set(),
);
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
const disclosureAnchorKeyRef = useRef<string | null>(null);
const disclosureSettleFrameRef = useRef<number | null>(null);
const disclosureSettleSecondFrameRef = useRef<number | null>(null);
const onToggleTurnFold = useCallback((runId: RunId) => {
setExpandedRunIds((existing) => {
const next = new Set(existing);
if (next.has(runId)) {
next.delete(runId);
} else {
next.add(runId);
useEffect(() => {
return () => {
if (disclosureSettleFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleFrameRef.current);
}
return next;
if (disclosureSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
}
};
}, []);
// A fold toggle inserts/removes rows around the toggled row. Suspending
// LegendList's end-scroll maintenance for two frames and anchoring
// maintainVisibleContentPosition to the toggled row keeps the trigger
// stationary under the pointer instead of the viewport chasing the end.
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string) => {
disclosureAnchorKeyRef.current = anchorKey;
setDisclosureToggleSettling(true);
if (disclosureSettleFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleFrameRef.current);
}
if (disclosureSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
}
disclosureSettleFrameRef.current = requestAnimationFrame(() => {
disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
disclosureAnchorKeyRef.current = null;
setDisclosureToggleSettling(false);
disclosureSettleFrameRef.current = null;
disclosureSettleSecondFrameRef.current = null;
});
});
}, []);
const onToggleAttemptFold = useCallback((attemptId: RunAttemptId) => {
setExpandedAttemptIds((existing) => {
const next = new Set(existing);
if (next.has(attemptId)) {
next.delete(attemptId);
} else {
next.add(attemptId);
}
return next;
});
const shouldRestoreVisibleContentPosition = useCallback((row: MessagesTimelineRow) => {
const disclosureAnchorKey = disclosureAnchorKeyRef.current;
return disclosureAnchorKey === null || row.id === disclosureAnchorKey;
}, []);
const onToggleTurnFold = useCallback(
(runId: RunId) => {
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${runId}`);
setExpandedRunIds((existing) => {
const next = new Set(existing);
if (next.has(runId)) {
next.delete(runId);
} else {
next.add(runId);
}
return next;
});
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onToggleAttemptFold = useCallback(
(attemptId: RunAttemptId) => {
suspendEndScrollMaintenanceForDisclosure(`attempt-fold:${attemptId}`);
setExpandedAttemptIds((existing) => {
const next = new Set(existing);
if (next.has(attemptId)) {
next.delete(attemptId);
} else {
next.add(attemptId);
}
return next;
});
},
[suspendEndScrollMaintenanceForDisclosure],
);
// An in-session interrupt leaves its turn expanded so the user keeps their
// place; the next turn (or a reload, since this is local state) folds it.
const previousLatestRunRef = useRef(latestRun);
@@ -394,9 +461,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
const maintainVisibleContentPosition = useMemo(
() => ({
data: true,
size: false,
size: true,
shouldRestorePosition: shouldRestoreVisibleContentPosition,
}),
[],
[shouldRestoreVisibleContentPosition],
);
const handleScroll = useCallback(() => {
@@ -574,13 +642,15 @@ export const MessagesTimeline = memo(function MessagesTimeline({
initialScrollAtEnd
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
contentInsetEndAdjustment={contentInsetEndAdjustment}
// The app owns end-following (ChatView live-follow + scroll-to-end
// pill), which respects the user's scroll gestures. LegendList's
// internal maintainScrollAtEnd races post-mount measurement: it
// caches its at-end flag while a maintain cycle is active, so
// overlapping item-layout reconciliations keep snapping the view
// to stale content ends even after the user scrolled away.
maintainScrollAtEnd={false}
// LegendList owns ordinary end-follow (#5449): the app only turns
// it off while the user reads history (liveFollowEnabled), while a
// sent turn anchors near the top (anchoredEndSpace), or for the
// two-frame settle window of a fold toggle.
maintainScrollAtEnd={
anchoredEndSpace || !liveFollowEnabled || disclosureToggleSettling
? false
: TIMELINE_MAINTAIN_SCROLL_AT_END
}
maintainVisibleContentPosition={maintainVisibleContentPosition}
onScroll={handleScroll}
className={cn(