Skip to content

Commit 546881a

Browse files
committed
fix(web): preserve scroll intent during thread restoration
1 parent aa5260a commit 546881a

3 files changed

Lines changed: 198 additions & 178 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 129 additions & 156 deletions
Original file line numberDiff line numberDiff line change
@@ -6156,13 +6156,6 @@ export default function ChatView(props: ChatViewProps) {
61566156
}
61576157
}
61586158
}, []);
6159-
const cancelTimelineLiveFollowForUserNavigationRef = useRef(
6160-
cancelTimelineLiveFollowForUserNavigation,
6161-
);
6162-
useEffect(() => {
6163-
cancelTimelineLiveFollowForUserNavigationRef.current =
6164-
cancelTimelineLiveFollowForUserNavigation;
6165-
}, [cancelTimelineLiveFollowForUserNavigation]);
61666159
useEffect(() => {
61676160
const previous = observedTimelineActivityRef.current;
61686161
const dispatchedUserItem =
@@ -6261,161 +6254,140 @@ export default function ChatView(props: ChatViewProps) {
62616254
void legendListRef.current?.scrollToEnd?.({ animated });
62626255
});
62636256
}, []);
6264-
useEffect(() => {
6265-
let removeListeners: (() => void) | null = null;
6266-
let frame: number | null = null;
6267-
const attach = (remainingAttempts: number) => {
6268-
frame = requestAnimationFrame(() => {
6269-
frame = null;
6270-
const scrollNode = legendListRef.current?.getScrollableNode();
6271-
if (!scrollNode) {
6272-
// The list may not have mounted on the first frame after a thread
6273-
// switch — without a retry the opt-out listeners never attach and
6274-
// live-follow becomes impossible to escape for the whole thread.
6275-
if (remainingAttempts > 0) {
6276-
attach(remainingAttempts - 1);
6257+
const handleTimelineScrollNodeMount = useCallback(
6258+
(scrollNode: HTMLElement) => {
6259+
// The gestures below must only break follow when they can actually
6260+
// move the viewport away from the live edge (#5566): a spurious break
6261+
// while pinned at the end produces no scroll event, never re-arms,
6262+
// and streaming silently stops following. Underflowing content can't
6263+
// scroll at all, so nothing there should break follow.
6264+
const contentScrollsUp = () => timelineRealContentOverflowsViewport();
6265+
// The follow re-arm band, not the strict flag: streaming growth makes
6266+
// isAtEnd flicker false for a frame before the follow scroll catches
6267+
// up, and a gesture landing in that window while still pinned would
6268+
// otherwise break follow with no scroll event left to re-arm it.
6269+
const viewportIsAwayFromEnd = () =>
6270+
resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
6271+
// Only an upward wheel is a navigation intent; wheeling down while
6272+
// following either does nothing (at the end) or moves toward it.
6273+
const handleWheel = (event: WheelEvent) => {
6274+
if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
6275+
return;
6276+
if (event.deltaY > 0) {
6277+
timelineScrollIntentRef.current = "toward-end";
6278+
if (isAtEndRef.current) {
6279+
composerRef.current?.restoreAfterTimelineReachedEnd();
6280+
}
6281+
} else if (event.deltaY < 0) {
6282+
timelineScrollIntentRef.current = "away-from-end";
6283+
}
6284+
if (event.deltaY < 0 && contentScrollsUp()) {
6285+
cancelTimelineLiveFollowForUserNavigation();
6286+
}
6287+
};
6288+
// Touch direction isn't observable here (touchmove fires on any
6289+
// finger motion, scrolling or not), so break only once the drag has
6290+
// actually carried the viewport out of the end band — an upward flick
6291+
// gets there within its first few events and later touchmoves break.
6292+
const handleTouchMove = () => {
6293+
if (viewportIsAwayFromEnd()) {
6294+
cancelTimelineLiveFollowForUserNavigation();
6295+
}
6296+
};
6297+
// Scrollbar drags produce no wheel/touch events; they are the only
6298+
// pointerdowns whose target is the scroll node itself rather than a
6299+
// message row. Content clicks break follow only away from the end
6300+
// (reading or selecting up there must hold position); clicking near
6301+
// the live edge keeps following.
6302+
const handlePointerDown = (event: PointerEvent) => {
6303+
if (event.target === scrollNode) {
6304+
if (contentScrollsUp()) {
6305+
cancelTimelineLiveFollowForUserNavigation();
62776306
}
62786307
return;
62796308
}
6280-
const handleManualNavigation = () => {
6281-
cancelTimelineLiveFollowForUserNavigationRef.current();
6282-
};
6283-
// The gestures below must only break follow when they can actually
6284-
// move the viewport away from the live edge (#5566): a spurious break
6285-
// while pinned at the end produces no scroll event, never re-arms,
6286-
// and streaming silently stops following. Underflowing content can't
6287-
// scroll at all, so nothing there should break follow.
6288-
const contentScrollsUp = () => timelineRealContentOverflowsViewport();
6289-
// The follow re-arm band, not the strict flag: streaming growth makes
6290-
// isAtEnd flicker false for a frame before the follow scroll catches
6291-
// up, and a gesture landing in that window while still pinned would
6292-
// otherwise break follow with no scroll event left to re-arm it.
6293-
const viewportIsAwayFromEnd = () =>
6294-
resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
6295-
// Only an upward wheel is a navigation intent; wheeling down while
6296-
// following either does nothing (at the end) or moves toward it.
6297-
const handleWheel = (event: WheelEvent) => {
6298-
if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
6299-
return;
6300-
if (event.deltaY > 0) {
6301-
timelineScrollIntentRef.current = "toward-end";
6302-
if (isAtEndRef.current) {
6303-
composerRef.current?.restoreAfterTimelineReachedEnd();
6304-
}
6305-
} else if (event.deltaY < 0) {
6309+
if (viewportIsAwayFromEnd()) {
6310+
cancelTimelineLiveFollowForUserNavigation();
6311+
}
6312+
};
6313+
// Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
6314+
// pointer events entirely; without this the timeline yanks back to
6315+
// the end on the next stream chunk. Clicking message text can leave
6316+
// DOM focus on body, so these keys must also be heard at document.
6317+
const handleKeyDown = (event: KeyboardEvent) => {
6318+
if (
6319+
!(event.target instanceof Node) ||
6320+
(!scrollNode.contains(event.target) &&
6321+
event.target !== document.body &&
6322+
event.target !== document.documentElement) ||
6323+
event.defaultPrevented ||
6324+
event.isComposing ||
6325+
event.altKey ||
6326+
event.ctrlKey ||
6327+
event.metaKey ||
6328+
event.shiftKey ||
6329+
eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
6330+
document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
6331+
) {
6332+
return;
6333+
}
6334+
if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
6335+
return;
6336+
const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
6337+
if (
6338+
scrollNode.contains(event.target) &&
6339+
!isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
6340+
)
6341+
return;
6342+
switch (event.key) {
6343+
case "PageUp":
6344+
case "Home":
6345+
case "ArrowUp":
63066346
timelineScrollIntentRef.current = "away-from-end";
6307-
}
6308-
if (event.deltaY < 0 && contentScrollsUp()) {
6309-
handleManualNavigation();
6310-
}
6311-
};
6312-
// Touch direction isn't observable here (touchmove fires on any
6313-
// finger motion, scrolling or not), so break only once the drag has
6314-
// actually carried the viewport out of the end band — an upward flick
6315-
// gets there within its first few events and later touchmoves break.
6316-
const handleTouchMove = () => {
6317-
if (viewportIsAwayFromEnd()) {
6318-
handleManualNavigation();
6319-
}
6320-
};
6321-
// Scrollbar drags produce no wheel/touch events; they are the only
6322-
// pointerdowns whose target is the scroll node itself rather than a
6323-
// message row. Content clicks break follow only away from the end
6324-
// (reading or selecting up there must hold position); clicking near
6325-
// the live edge keeps following.
6326-
const handlePointerDown = (event: PointerEvent) => {
6327-
if (event.target === scrollNode) {
63286347
if (contentScrollsUp()) {
6329-
handleManualNavigation();
6330-
}
6331-
return;
6332-
}
6333-
if (viewportIsAwayFromEnd()) {
6334-
handleManualNavigation();
6335-
}
6336-
};
6337-
// Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
6338-
// pointer events entirely; without this the timeline yanks back to
6339-
// the end on the next stream chunk. Clicking message text can leave
6340-
// DOM focus on body, so these keys must also be heard at document.
6341-
const handleKeyDown = (event: KeyboardEvent) => {
6342-
if (
6343-
!(event.target instanceof Node) ||
6344-
(!scrollNode.contains(event.target) &&
6345-
event.target !== document.body &&
6346-
event.target !== document.documentElement) ||
6347-
event.defaultPrevented ||
6348-
event.isComposing ||
6349-
event.altKey ||
6350-
event.ctrlKey ||
6351-
event.metaKey ||
6352-
event.shiftKey ||
6353-
eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
6354-
document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
6355-
) {
6356-
return;
6357-
}
6358-
if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
6359-
return;
6360-
const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
6361-
if (
6362-
scrollNode.contains(event.target) &&
6363-
!isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
6364-
)
6365-
return;
6366-
switch (event.key) {
6367-
case "PageUp":
6368-
case "Home":
6369-
case "ArrowUp":
6370-
timelineScrollIntentRef.current = "away-from-end";
6371-
if (contentScrollsUp()) {
6372-
handleManualNavigation();
6373-
composerRef.current?.collapseForTimelineScrollKey(event.key);
6374-
}
6375-
break;
6376-
case "PageDown":
6377-
case "End":
6378-
case "ArrowDown":
6379-
timelineScrollIntentRef.current = "toward-end";
6380-
if (viewportIsAwayFromEnd()) {
6381-
handleManualNavigation();
6382-
}
6348+
cancelTimelineLiveFollowForUserNavigation();
63836349
composerRef.current?.collapseForTimelineScrollKey(event.key);
6384-
if (isTimelineAtLogicalEnd()) {
6385-
composerRef.current?.restoreAfterTimelineReachedEnd();
6386-
}
6387-
break;
6388-
default:
6389-
break;
6390-
}
6391-
};
6392-
scrollNode.addEventListener("wheel", handleWheel, {
6393-
passive: true,
6394-
});
6395-
scrollNode.addEventListener("touchmove", handleTouchMove, {
6396-
passive: true,
6397-
});
6398-
scrollNode.addEventListener("pointerdown", handlePointerDown, {
6399-
passive: true,
6400-
});
6401-
document.addEventListener("keydown", handleKeyDown);
6402-
removeListeners = () => {
6403-
scrollNode.removeEventListener("wheel", handleWheel);
6404-
scrollNode.removeEventListener("touchmove", handleTouchMove);
6405-
scrollNode.removeEventListener("pointerdown", handlePointerDown);
6406-
document.removeEventListener("keydown", handleKeyDown);
6407-
};
6350+
}
6351+
break;
6352+
case "PageDown":
6353+
case "End":
6354+
case "ArrowDown":
6355+
timelineScrollIntentRef.current = "toward-end";
6356+
if (viewportIsAwayFromEnd()) {
6357+
cancelTimelineLiveFollowForUserNavigation();
6358+
}
6359+
composerRef.current?.collapseForTimelineScrollKey(event.key);
6360+
if (isTimelineAtLogicalEnd()) {
6361+
composerRef.current?.restoreAfterTimelineReachedEnd();
6362+
}
6363+
break;
6364+
default:
6365+
break;
6366+
}
6367+
};
6368+
scrollNode.addEventListener("wheel", handleWheel, {
6369+
passive: true,
64086370
});
6409-
};
6410-
attach(12);
6411-
6412-
return () => {
6413-
if (frame !== null) {
6414-
cancelAnimationFrame(frame);
6415-
}
6416-
removeListeners?.();
6417-
};
6418-
}, [activeThread?.id, isTimelineAtLogicalEnd, timelineRealContentOverflowsViewport]);
6371+
scrollNode.addEventListener("touchmove", handleTouchMove, {
6372+
passive: true,
6373+
});
6374+
scrollNode.addEventListener("pointerdown", handlePointerDown, {
6375+
passive: true,
6376+
});
6377+
scrollNode.ownerDocument.addEventListener("keydown", handleKeyDown);
6378+
return () => {
6379+
scrollNode.removeEventListener("wheel", handleWheel);
6380+
scrollNode.removeEventListener("touchmove", handleTouchMove);
6381+
scrollNode.removeEventListener("pointerdown", handlePointerDown);
6382+
scrollNode.ownerDocument.removeEventListener("keydown", handleKeyDown);
6383+
};
6384+
},
6385+
[
6386+
cancelTimelineLiveFollowForUserNavigation,
6387+
isTimelineAtLogicalEnd,
6388+
timelineRealContentOverflowsViewport,
6389+
],
6390+
);
64196391

64206392
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
64216393
if (pendingTimelineAnchorRef.current === messageId) {
@@ -6565,7 +6537,7 @@ export default function ChatView(props: ChatViewProps) {
65656537
timelineLiveFollowEnabled,
65666538
]);
65676539

6568-
useEffect(() => {
6540+
useLayoutEffect(() => {
65696541
setPullRequestDialogState(null);
65706542
const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
65716543
isAtEndRef.current = followEnd;
@@ -11035,6 +11007,7 @@ export default function ChatView(props: ChatViewProps) {
1103511007
{...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
1103611008
isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree}
1103711009
listRef={legendListRef}
11010+
onScrollNodeMount={handleTimelineScrollNodeMount}
1103811011
timelineEntries={displayedTimeline.entries}
1103911012
providerStatuses={
1104011013
environmentById.get(

‎apps/web/src/components/chat/MessagesTimeline.test.tsx‎

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1365,7 +1365,7 @@ describe("MessagesTimeline", () => {
13651365
});
13661366
let entries = [workEntry(0)];
13671367
const noop = () => {};
1368-
const listeners = new Map<string, () => void>();
1368+
const listeners = new Map<string, (event?: { deltaY: number }) => void>();
13691369
const viewport = {
13701370
scrollTop: 0,
13711371
scrollHeight: 2000,
@@ -1508,15 +1508,53 @@ describe("MessagesTimeline", () => {
15081508
}
15091509
});
15101510

1511-
it("keeps following when a gesture interrupts a restore to the end", async () => {
1511+
it.each([
1512+
["grow", "wheel", "frame"],
1513+
["grow", "frame", "wheel"],
1514+
["wheel", "grow", "frame"],
1515+
["wheel", "frame", "grow"],
1516+
["frame", "grow", "wheel"],
1517+
["frame", "wheel", "grow"],
1518+
])("reaches the end through downward input: %s, %s, %s", async (...events) => {
15121519
const { harness, switchThread, cleanup } = await switchToRememberedThread(true);
15131520
try {
15141521
await switchThread();
1515-
act(() => harness.listeners.get("wheel")?.());
1522+
for (const event of events) {
1523+
if (event === "grow") harness.viewport.scrollHeight = 5000;
1524+
if (event === "frame") await harness.flushFrame();
1525+
if (event === "wheel") {
1526+
act(() => {
1527+
harness.listeners.get("wheel")?.({ deltaY: 40 });
1528+
harness.viewport.scrollTop = Math.min(
1529+
harness.viewport.scrollTop + 40,
1530+
harness.viewport.scrollHeight - harness.viewport.clientHeight,
1531+
);
1532+
});
1533+
}
1534+
}
1535+
for (let frame = 0; frame < 6; frame += 1) await harness.flushFrame();
15161536

1517-
// ChatView's own listeners decide whether the gesture leaves the end.
1537+
expect(harness.viewport.scrollTop).toBe(4200);
1538+
expect(harness.atEndCalls).toContain(true);
15181539
expect(harness.manualNavigations).toBe(0);
1519-
expect(harness.listeners.has("wheel")).toBe(false);
1540+
} finally {
1541+
cleanup();
1542+
}
1543+
});
1544+
1545+
it("yields a saved reading position to a downward wheel before reconciliation", async () => {
1546+
const { harness, switchThread, cleanup } = await switchToRememberedThread(false);
1547+
try {
1548+
await switchThread();
1549+
act(() => {
1550+
harness.listeners.get("wheel")?.({ deltaY: 40 });
1551+
harness.viewport.scrollTop = 40;
1552+
});
1553+
for (let frame = 0; frame < 6; frame += 1) await harness.flushFrame();
1554+
1555+
expect(harness.viewport.scrollTop).toBe(40);
1556+
expect(harness.atEndCalls).toContain(false);
1557+
expect(harness.manualNavigations).toBe(1);
15201558
} finally {
15211559
cleanup();
15221560
}

0 commit comments

Comments
 (0)