Skip to content

Commit fa1347d

Browse files
t3dotggECutericlaude
authored
fix(web): switched threads and Scroll to end land on the real end (pingdotgg#24622)
Takes over pingdotgg#23490 by Ennio Cuteri, adding a frame limit on the settle loop and reporting positioned when its target disappears. Co-authored-by: Ennio Cuteri <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 91ea0e1 commit fa1347d

3 files changed

Lines changed: 114 additions & 45 deletions

File tree

‎apps/web/src/components/chat/useTimelineFollow.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { type ChatComposerHandle } from "./ChatComposer";
2828
import { createPageScrollController, type PageScrollKey } from "./pageScrollController";
2929
import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
3030
import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
31+
import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";
3132
import { shouldReleaseTimelineAnchorForToolActivity } from "../ChatView.logic";
3233
import { releaseChatTimelineAnchor } from "../ChatView.logic";
3334
import type { Dispatch, RefObject } from "react";
@@ -272,9 +273,19 @@ export function useTimelineFollow(input: TimelineFollowInput) {
272273
// The anchored end space must be gone before the scroll measures, or the
273274
// list lands short of the real end (#6519).
274275
requestAnimationFrame(() => {
275-
void legendListRef.current?.scrollToEnd?.({
276-
animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
277-
});
276+
const list = legendListRef.current;
277+
if (!list) return;
278+
void Promise.resolve(
279+
list.scrollToEnd?.({
280+
animated: animated && !window.matchMedia("(prefers-reduced-motion: reduce)").matches,
281+
}),
282+
).then(() =>
283+
settleListScroll(
284+
list,
285+
measuredEndOffset,
286+
() => timelineScrollModeRef.current !== "following-end" || legendListRef.current !== list,
287+
),
288+
);
278289
});
279290
};
280291
const scrollToEndStable = useStableCallback(scrollToEnd);
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { describe, expect, it, vi } from "vite-plus/test";
2+
import { measuredEndOffset, settleListScroll } from "./useTimelinePositionRestore";
3+
4+
describe("settleListScroll", () => {
5+
it("hands off when a streaming reply keeps moving the end", async () => {
6+
vi.useFakeTimers();
7+
// The node test environment has no animation frames; fake ones run on the fake clock.
8+
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) =>
9+
setTimeout(() => callback(0), 16),
10+
);
11+
// Every correction lands, then the reply grows before the next frame.
12+
const element = { scrollTop: 0, scrollHeight: 5_000, clientHeight: 800 };
13+
const list = {
14+
getScrollableNode: () => element as unknown as HTMLElement,
15+
scrollToOffset: async ({ offset }: { offset: number }) => {
16+
element.scrollTop = offset;
17+
element.scrollHeight += 40;
18+
},
19+
};
20+
21+
let settled = false;
22+
void settleListScroll(list, measuredEndOffset, () => false).then(() => {
23+
settled = true;
24+
});
25+
await vi.advanceTimersByTimeAsync(5_000);
26+
vi.useRealTimers();
27+
vi.unstubAllGlobals();
28+
29+
expect(settled).toBe(true);
30+
});
31+
});

‎apps/web/src/components/chat/useTimelinePositionRestore.ts‎

Lines changed: 69 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,48 @@ import type { AssistantCitationRequest } from "./AssistantCitationSource";
44
import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
55
import type { RememberedTimelinePosition } from "./timelineScrollAnchoring";
66

7+
// A streaming reply moves the end every frame, so the target may never hold
8+
// still. Past this many frames the list's own end maintenance takes over.
9+
const SETTLE_MAX_FRAMES = 60;
10+
11+
/**
12+
* Index and end scrolling start from estimated row sizes, so they can stop
13+
* short of a tall row. Corrects against the DOM until the viewport holds the
14+
* target for two layout frames, the frame budget runs out, the caller cancels,
15+
* or the target disappears.
16+
*/
17+
export function settleListScroll(
18+
list: Pick<LegendListRef, "getScrollableNode" | "scrollToOffset">,
19+
target: (element: HTMLElement) => number | undefined,
20+
isCancelled: () => boolean,
21+
): Promise<void> {
22+
return new Promise((resolve) => {
23+
let stableFrames = 0;
24+
let frames = 0;
25+
const reconcile = () => {
26+
if (isCancelled()) return resolve();
27+
const element = list.getScrollableNode();
28+
const offset = element ? target(element) : undefined;
29+
frames += 1;
30+
if (!element || offset === undefined || frames > SETTLE_MAX_FRAMES) return resolve();
31+
if (Math.abs(element.scrollTop - offset) > 1) {
32+
stableFrames = 0;
33+
void list.scrollToOffset({ offset, animated: false }).then(() => {
34+
requestAnimationFrame(reconcile);
35+
});
36+
return;
37+
}
38+
stableFrames += 1;
39+
if (stableFrames >= 2) resolve();
40+
else requestAnimationFrame(reconcile);
41+
};
42+
requestAnimationFrame(reconcile);
43+
});
44+
}
45+
46+
export const measuredEndOffset = (element: HTMLElement) =>
47+
element.scrollHeight - element.clientHeight;
48+
749
/**
850
* Scrolls a newly shown thread back to where the user left it, or to its end,
951
* and reports the thread positioned once the saved row settles.
@@ -55,12 +97,10 @@ export function useTimelinePositionRestore({
5597
return;
5698
}
5799
let cancelled = false;
58-
let settleFrame: number | null = null;
59100
const viewport: HTMLElement | null = list.getScrollableNode();
60101
const cancelRestoration = () => {
61102
if (cancelled) return;
62103
cancelled = true;
63-
if (settleFrame !== null) cancelAnimationFrame(settleFrame);
64104
if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
65105
onPositioned(listIdentityKey);
66106
};
@@ -99,54 +139,41 @@ export function useTimelinePositionRestore({
99139
: listOpenedOnRef.current?.identity === listIdentityKey
100140
? undefined
101141
: list.scrollToEnd({ animated: false });
102-
void Promise.resolve(scrolling).then(() => {
142+
const settlesAtEnd = position?.atEnd !== false && scrolling !== undefined;
143+
void Promise.resolve(scrolling).then(async () => {
103144
if (cancelled) return;
104-
if (position?.atEnd !== false || index < 0) {
105-
onPositioned(listIdentityKey);
106-
return;
107-
}
108-
// Index scrolling starts from estimates. Keep the saved row mounted
109-
// until its measured position and the DOM agree for two layout frames.
110-
let stableFrames = 0;
111-
const reconcile = () => {
112-
if (cancelled) return;
113-
const state = list.getState();
114-
const rowIndex = state.indexByKey(position.rowId);
115-
const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
116-
const element = list.getScrollableNode();
117-
if (!row || !element) return;
118-
const offset = Math.max(
119-
0,
120-
Math.min(
121-
element.scrollTop +
122-
row.getBoundingClientRect().top -
123-
element.getBoundingClientRect().top +
124-
position.offsetWithinRow,
125-
element.scrollHeight - element.clientHeight,
126-
),
145+
if (settlesAtEnd) {
146+
await settleListScroll(list, measuredEndOffset, () => cancelled);
147+
} else if (position?.atEnd === false && index >= 0) {
148+
// Keep the saved row mounted until its measured position and the DOM agree.
149+
await settleListScroll(
150+
list,
151+
(element) => {
152+
const state = list.getState();
153+
const rowIndex = state.indexByKey(position.rowId);
154+
const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
155+
if (!row) return undefined;
156+
return Math.max(
157+
0,
158+
Math.min(
159+
element.scrollTop +
160+
row.getBoundingClientRect().top -
161+
element.getBoundingClientRect().top +
162+
position.offsetWithinRow,
163+
measuredEndOffset(element),
164+
),
165+
);
166+
},
167+
() => cancelled,
127168
);
128-
if (Math.abs(element.scrollTop - offset) > 1) {
129-
stableFrames = 0;
130-
void list.scrollToOffset({ offset, animated: false }).then(() => {
131-
if (!cancelled) settleFrame = requestAnimationFrame(reconcile);
132-
});
133-
return;
134-
}
135-
stableFrames += 1;
136-
if (stableFrames >= 2) {
137-
onPositioned(listIdentityKey);
138-
} else {
139-
settleFrame = requestAnimationFrame(reconcile);
140-
}
141-
};
142-
settleFrame = requestAnimationFrame(reconcile);
169+
}
170+
if (!cancelled) onPositioned(listIdentityKey);
143171
});
144172
return () => {
145173
cancelled = true;
146174
if (cancelPositionRestoreRef?.current === cancelRestoration) {
147175
cancelPositionRestoreRef.current = null;
148176
}
149-
if (settleFrame !== null) cancelAnimationFrame(settleFrame);
150177
viewport?.removeEventListener("wheel", cancelForNavigation);
151178
viewport?.removeEventListener("touchmove", cancelForNavigation);
152179
viewport?.removeEventListener("pointerdown", cancelForNavigation);

0 commit comments

Comments
 (0)