Skip to content

Commit 4273701

Browse files
committed
fix(web): preserve scroll intent during thread restoration
1 parent fcd7aa2 commit 4273701

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
@@ -5906,13 +5906,6 @@ export default function ChatView(props: ChatViewProps) {
59065906
}
59075907
}
59085908
}, []);
5909-
const cancelTimelineLiveFollowForUserNavigationRef = useRef(
5910-
cancelTimelineLiveFollowForUserNavigation,
5911-
);
5912-
useEffect(() => {
5913-
cancelTimelineLiveFollowForUserNavigationRef.current =
5914-
cancelTimelineLiveFollowForUserNavigation;
5915-
}, [cancelTimelineLiveFollowForUserNavigation]);
59165909
useEffect(() => {
59175910
const previous = observedTimelineActivityRef.current;
59185911
const dispatchedUserItem =
@@ -6011,161 +6004,140 @@ export default function ChatView(props: ChatViewProps) {
60116004
void legendListRef.current?.scrollToEnd?.({ animated });
60126005
});
60136006
}, []);
6014-
useEffect(() => {
6015-
let removeListeners: (() => void) | null = null;
6016-
let frame: number | null = null;
6017-
const attach = (remainingAttempts: number) => {
6018-
frame = requestAnimationFrame(() => {
6019-
frame = null;
6020-
const scrollNode = legendListRef.current?.getScrollableNode();
6021-
if (!scrollNode) {
6022-
// The list may not have mounted on the first frame after a thread
6023-
// switch — without a retry the opt-out listeners never attach and
6024-
// live-follow becomes impossible to escape for the whole thread.
6025-
if (remainingAttempts > 0) {
6026-
attach(remainingAttempts - 1);
6007+
const handleTimelineScrollNodeMount = useCallback(
6008+
(scrollNode: HTMLElement) => {
6009+
// The gestures below must only break follow when they can actually
6010+
// move the viewport away from the live edge (#5566): a spurious break
6011+
// while pinned at the end produces no scroll event, never re-arms,
6012+
// and streaming silently stops following. Underflowing content can't
6013+
// scroll at all, so nothing there should break follow.
6014+
const contentScrollsUp = () => timelineRealContentOverflowsViewport();
6015+
// The follow re-arm band, not the strict flag: streaming growth makes
6016+
// isAtEnd flicker false for a frame before the follow scroll catches
6017+
// up, and a gesture landing in that window while still pinned would
6018+
// otherwise break follow with no scroll event left to re-arm it.
6019+
const viewportIsAwayFromEnd = () =>
6020+
resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
6021+
// Only an upward wheel is a navigation intent; wheeling down while
6022+
// following either does nothing (at the end) or moves toward it.
6023+
const handleWheel = (event: WheelEvent) => {
6024+
if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
6025+
return;
6026+
if (event.deltaY > 0) {
6027+
timelineScrollIntentRef.current = "toward-end";
6028+
if (isAtEndRef.current) {
6029+
composerRef.current?.restoreAfterTimelineReachedEnd();
6030+
}
6031+
} else if (event.deltaY < 0) {
6032+
timelineScrollIntentRef.current = "away-from-end";
6033+
}
6034+
if (event.deltaY < 0 && contentScrollsUp()) {
6035+
cancelTimelineLiveFollowForUserNavigation();
6036+
}
6037+
};
6038+
// Touch direction isn't observable here (touchmove fires on any
6039+
// finger motion, scrolling or not), so break only once the drag has
6040+
// actually carried the viewport out of the end band — an upward flick
6041+
// gets there within its first few events and later touchmoves break.
6042+
const handleTouchMove = () => {
6043+
if (viewportIsAwayFromEnd()) {
6044+
cancelTimelineLiveFollowForUserNavigation();
6045+
}
6046+
};
6047+
// Scrollbar drags produce no wheel/touch events; they are the only
6048+
// pointerdowns whose target is the scroll node itself rather than a
6049+
// message row. Content clicks break follow only away from the end
6050+
// (reading or selecting up there must hold position); clicking near
6051+
// the live edge keeps following.
6052+
const handlePointerDown = (event: PointerEvent) => {
6053+
if (event.target === scrollNode) {
6054+
if (contentScrollsUp()) {
6055+
cancelTimelineLiveFollowForUserNavigation();
60276056
}
60286057
return;
60296058
}
6030-
const handleManualNavigation = () => {
6031-
cancelTimelineLiveFollowForUserNavigationRef.current();
6032-
};
6033-
// The gestures below must only break follow when they can actually
6034-
// move the viewport away from the live edge (#5566): a spurious break
6035-
// while pinned at the end produces no scroll event, never re-arms,
6036-
// and streaming silently stops following. Underflowing content can't
6037-
// scroll at all, so nothing there should break follow.
6038-
const contentScrollsUp = () => timelineRealContentOverflowsViewport();
6039-
// The follow re-arm band, not the strict flag: streaming growth makes
6040-
// isAtEnd flicker false for a frame before the follow scroll catches
6041-
// up, and a gesture landing in that window while still pinned would
6042-
// otherwise break follow with no scroll event left to re-arm it.
6043-
const viewportIsAwayFromEnd = () =>
6044-
resolveTimelineIsAtEnd(legendListRef.current?.getState()) === false;
6045-
// Only an upward wheel is a navigation intent; wheeling down while
6046-
// following either does nothing (at the end) or moves toward it.
6047-
const handleWheel = (event: WheelEvent) => {
6048-
if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY))
6049-
return;
6050-
if (event.deltaY > 0) {
6051-
timelineScrollIntentRef.current = "toward-end";
6052-
if (isAtEndRef.current) {
6053-
composerRef.current?.restoreAfterTimelineReachedEnd();
6054-
}
6055-
} else if (event.deltaY < 0) {
6059+
if (viewportIsAwayFromEnd()) {
6060+
cancelTimelineLiveFollowForUserNavigation();
6061+
}
6062+
};
6063+
// Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
6064+
// pointer events entirely; without this the timeline yanks back to
6065+
// the end on the next stream chunk. Clicking message text can leave
6066+
// DOM focus on body, so these keys must also be heard at document.
6067+
const handleKeyDown = (event: KeyboardEvent) => {
6068+
if (
6069+
!(event.target instanceof Node) ||
6070+
(!scrollNode.contains(event.target) &&
6071+
event.target !== document.body &&
6072+
event.target !== document.documentElement) ||
6073+
event.defaultPrevented ||
6074+
event.isComposing ||
6075+
event.altKey ||
6076+
event.ctrlKey ||
6077+
event.metaKey ||
6078+
event.shiftKey ||
6079+
eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
6080+
document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
6081+
) {
6082+
return;
6083+
}
6084+
if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
6085+
return;
6086+
const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
6087+
if (
6088+
scrollNode.contains(event.target) &&
6089+
!isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
6090+
)
6091+
return;
6092+
switch (event.key) {
6093+
case "PageUp":
6094+
case "Home":
6095+
case "ArrowUp":
60566096
timelineScrollIntentRef.current = "away-from-end";
6057-
}
6058-
if (event.deltaY < 0 && contentScrollsUp()) {
6059-
handleManualNavigation();
6060-
}
6061-
};
6062-
// Touch direction isn't observable here (touchmove fires on any
6063-
// finger motion, scrolling or not), so break only once the drag has
6064-
// actually carried the viewport out of the end band — an upward flick
6065-
// gets there within its first few events and later touchmoves break.
6066-
const handleTouchMove = () => {
6067-
if (viewportIsAwayFromEnd()) {
6068-
handleManualNavigation();
6069-
}
6070-
};
6071-
// Scrollbar drags produce no wheel/touch events; they are the only
6072-
// pointerdowns whose target is the scroll node itself rather than a
6073-
// message row. Content clicks break follow only away from the end
6074-
// (reading or selecting up there must hold position); clicking near
6075-
// the live edge keeps following.
6076-
const handlePointerDown = (event: PointerEvent) => {
6077-
if (event.target === scrollNode) {
60786097
if (contentScrollsUp()) {
6079-
handleManualNavigation();
6080-
}
6081-
return;
6082-
}
6083-
if (viewportIsAwayFromEnd()) {
6084-
handleManualNavigation();
6085-
}
6086-
};
6087-
// Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and
6088-
// pointer events entirely; without this the timeline yanks back to
6089-
// the end on the next stream chunk. Clicking message text can leave
6090-
// DOM focus on body, so these keys must also be heard at document.
6091-
const handleKeyDown = (event: KeyboardEvent) => {
6092-
if (
6093-
!(event.target instanceof Node) ||
6094-
(!scrollNode.contains(event.target) &&
6095-
event.target !== document.body &&
6096-
event.target !== document.documentElement) ||
6097-
event.defaultPrevented ||
6098-
event.isComposing ||
6099-
event.altKey ||
6100-
event.ctrlKey ||
6101-
event.metaKey ||
6102-
event.shiftKey ||
6103-
eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
6104-
document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)
6105-
) {
6106-
return;
6107-
}
6108-
if (!["PageUp", "Home", "ArrowUp", "PageDown", "End", "ArrowDown"].includes(event.key))
6109-
return;
6110-
const scrollDirection = ["PageUp", "Home", "ArrowUp"].includes(event.key) ? -1 : 1;
6111-
if (
6112-
scrollNode.contains(event.target) &&
6113-
!isTimelineScrollTarget(event.target, scrollNode, scrollDirection)
6114-
)
6115-
return;
6116-
switch (event.key) {
6117-
case "PageUp":
6118-
case "Home":
6119-
case "ArrowUp":
6120-
timelineScrollIntentRef.current = "away-from-end";
6121-
if (contentScrollsUp()) {
6122-
handleManualNavigation();
6123-
composerRef.current?.collapseForTimelineScrollKey(event.key);
6124-
}
6125-
break;
6126-
case "PageDown":
6127-
case "End":
6128-
case "ArrowDown":
6129-
timelineScrollIntentRef.current = "toward-end";
6130-
if (viewportIsAwayFromEnd()) {
6131-
handleManualNavigation();
6132-
}
6098+
cancelTimelineLiveFollowForUserNavigation();
61336099
composerRef.current?.collapseForTimelineScrollKey(event.key);
6134-
if (isTimelineAtLogicalEnd()) {
6135-
composerRef.current?.restoreAfterTimelineReachedEnd();
6136-
}
6137-
break;
6138-
default:
6139-
break;
6140-
}
6141-
};
6142-
scrollNode.addEventListener("wheel", handleWheel, {
6143-
passive: true,
6144-
});
6145-
scrollNode.addEventListener("touchmove", handleTouchMove, {
6146-
passive: true,
6147-
});
6148-
scrollNode.addEventListener("pointerdown", handlePointerDown, {
6149-
passive: true,
6150-
});
6151-
document.addEventListener("keydown", handleKeyDown);
6152-
removeListeners = () => {
6153-
scrollNode.removeEventListener("wheel", handleWheel);
6154-
scrollNode.removeEventListener("touchmove", handleTouchMove);
6155-
scrollNode.removeEventListener("pointerdown", handlePointerDown);
6156-
document.removeEventListener("keydown", handleKeyDown);
6157-
};
6100+
}
6101+
break;
6102+
case "PageDown":
6103+
case "End":
6104+
case "ArrowDown":
6105+
timelineScrollIntentRef.current = "toward-end";
6106+
if (viewportIsAwayFromEnd()) {
6107+
cancelTimelineLiveFollowForUserNavigation();
6108+
}
6109+
composerRef.current?.collapseForTimelineScrollKey(event.key);
6110+
if (isTimelineAtLogicalEnd()) {
6111+
composerRef.current?.restoreAfterTimelineReachedEnd();
6112+
}
6113+
break;
6114+
default:
6115+
break;
6116+
}
6117+
};
6118+
scrollNode.addEventListener("wheel", handleWheel, {
6119+
passive: true,
61586120
});
6159-
};
6160-
attach(12);
6161-
6162-
return () => {
6163-
if (frame !== null) {
6164-
cancelAnimationFrame(frame);
6165-
}
6166-
removeListeners?.();
6167-
};
6168-
}, [activeThread?.id, isTimelineAtLogicalEnd, timelineRealContentOverflowsViewport]);
6121+
scrollNode.addEventListener("touchmove", handleTouchMove, {
6122+
passive: true,
6123+
});
6124+
scrollNode.addEventListener("pointerdown", handlePointerDown, {
6125+
passive: true,
6126+
});
6127+
scrollNode.ownerDocument.addEventListener("keydown", handleKeyDown);
6128+
return () => {
6129+
scrollNode.removeEventListener("wheel", handleWheel);
6130+
scrollNode.removeEventListener("touchmove", handleTouchMove);
6131+
scrollNode.removeEventListener("pointerdown", handlePointerDown);
6132+
scrollNode.ownerDocument.removeEventListener("keydown", handleKeyDown);
6133+
};
6134+
},
6135+
[
6136+
cancelTimelineLiveFollowForUserNavigation,
6137+
isTimelineAtLogicalEnd,
6138+
timelineRealContentOverflowsViewport,
6139+
],
6140+
);
61696141

61706142
const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {
61716143
if (pendingTimelineAnchorRef.current === messageId) {
@@ -6315,7 +6287,7 @@ export default function ChatView(props: ChatViewProps) {
63156287
timelineLiveFollowEnabled,
63166288
]);
63176289

6318-
useEffect(() => {
6290+
useLayoutEffect(() => {
63196291
setPullRequestDialogState(null);
63206292
const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
63216293
isAtEndRef.current = followEnd;
@@ -10659,6 +10631,7 @@ export default function ChatView(props: ChatViewProps) {
1065910631
{...(onOpenWorktreeSetupTerminal ? { onOpenWorktreeSetupTerminal } : {})}
1066010632
isPreparingWorktree={!paintOnlyDisplayedTimeline && isPreparingWorktree}
1066110633
listRef={legendListRef}
10634+
onScrollNodeMount={handleTimelineScrollNodeMount}
1066210635
timelineEntries={displayedTimeline.entries}
1066310636
providerStatuses={
1066410637
environmentById.get(

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

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1242,7 +1242,7 @@ describe("MessagesTimeline", () => {
12421242
});
12431243
let entries = [workEntry(0)];
12441244
const noop = () => {};
1245-
const listeners = new Map<string, () => void>();
1245+
const listeners = new Map<string, (event?: { deltaY: number }) => void>();
12461246
const viewport = {
12471247
scrollTop: 0,
12481248
scrollHeight: 2000,
@@ -1385,15 +1385,53 @@ describe("MessagesTimeline", () => {
13851385
}
13861386
});
13871387

1388-
it("keeps following when a gesture interrupts a restore to the end", async () => {
1388+
it.each([
1389+
["grow", "wheel", "frame"],
1390+
["grow", "frame", "wheel"],
1391+
["wheel", "grow", "frame"],
1392+
["wheel", "frame", "grow"],
1393+
["frame", "grow", "wheel"],
1394+
["frame", "wheel", "grow"],
1395+
])("reaches the end through downward input: %s, %s, %s", async (...events) => {
13891396
const { harness, switchThread, cleanup } = await switchToRememberedThread(true);
13901397
try {
13911398
await switchThread();
1392-
act(() => harness.listeners.get("wheel")?.());
1399+
for (const event of events) {
1400+
if (event === "grow") harness.viewport.scrollHeight = 5000;
1401+
if (event === "frame") await harness.flushFrame();
1402+
if (event === "wheel") {
1403+
act(() => {
1404+
harness.listeners.get("wheel")?.({ deltaY: 40 });
1405+
harness.viewport.scrollTop = Math.min(
1406+
harness.viewport.scrollTop + 40,
1407+
harness.viewport.scrollHeight - harness.viewport.clientHeight,
1408+
);
1409+
});
1410+
}
1411+
}
1412+
for (let frame = 0; frame < 6; frame += 1) await harness.flushFrame();
13931413

1394-
// ChatView's own listeners decide whether the gesture leaves the end.
1414+
expect(harness.viewport.scrollTop).toBe(4200);
1415+
expect(harness.atEndCalls).toContain(true);
13951416
expect(harness.manualNavigations).toBe(0);
1396-
expect(harness.listeners.has("wheel")).toBe(false);
1417+
} finally {
1418+
cleanup();
1419+
}
1420+
});
1421+
1422+
it("yields a saved reading position to a downward wheel before reconciliation", async () => {
1423+
const { harness, switchThread, cleanup } = await switchToRememberedThread(false);
1424+
try {
1425+
await switchThread();
1426+
act(() => {
1427+
harness.listeners.get("wheel")?.({ deltaY: 40 });
1428+
harness.viewport.scrollTop = 40;
1429+
});
1430+
for (let frame = 0; frame < 6; frame += 1) await harness.flushFrame();
1431+
1432+
expect(harness.viewport.scrollTop).toBe(40);
1433+
expect(harness.atEndCalls).toContain(false);
1434+
expect(harness.manualNavigations).toBe(1);
13971435
} finally {
13981436
cleanup();
13991437
}

0 commit comments

Comments
 (0)