Skip to content

Commit a2a1053

Browse files
committed
fix(web): preserve thread reading positions
1 parent 384de08 commit a2a1053

4 files changed

Lines changed: 251 additions & 38 deletions

File tree

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

Lines changed: 10 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@ import { type LegendListRef } from "@legendapp/list/react";
136136
import {
137137
CHAT_TIMELINE_ANCHOR_OFFSET,
138138
getAnchoredTurnMetrics,
139+
readTimelinePosition,
139140
timelineContentOverflowsViewport,
140141
type TimelineScrollMode,
141142
} from "./chat/timelineScrollAnchoring";
@@ -5320,21 +5321,6 @@ export default function ChatView(props: ChatViewProps) {
53205321
void legendListRef.current?.scrollToEnd?.({ animated });
53215322
});
53225323
}, []);
5323-
const displayedTimelineKeyRef = useRef(displayedTimeline.displayThreadKey);
5324-
useLayoutEffect(() => {
5325-
const displayKey = displayedTimeline.displayThreadKey;
5326-
if (displayKey === null || displayKey !== activeThreadKey) {
5327-
displayedTimelineKeyRef.current = displayKey;
5328-
return;
5329-
}
5330-
if (displayedTimelineKeyRef.current === displayKey) {
5331-
return;
5332-
}
5333-
displayedTimelineKeyRef.current = displayKey;
5334-
// Keep the list mounted across jumps; pin the newly displayed thread to
5335-
// its end the way a remount used to via initialScrollAtEnd.
5336-
scrollToEnd();
5337-
}, [activeThreadKey, displayedTimeline.displayThreadKey, scrollToEnd]);
53385324
useLayoutEffect(() => {
53395325
if (timelineScrollModeRef.current !== "anchoring-new-turn") {
53405326
return;
@@ -5644,19 +5630,22 @@ export default function ChatView(props: ChatViewProps) {
56445630

56455631
useEffect(() => {
56465632
setPullRequestDialogState(null);
5647-
isAtEndRef.current = true;
5633+
const followEnd = readTimelinePosition(routeThreadKey)?.atEnd !== false;
5634+
isAtEndRef.current = followEnd;
56485635
timelineScrollIntentRef.current = null;
5649-
timelineScrollModeRef.current = "following-end";
5650-
liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;
5651-
setTimelineLiveFollowEnabled(true);
5636+
timelineScrollModeRef.current = followEnd ? "following-end" : "free-scrolling";
5637+
liveFollowUserScrollGenerationRef.current = followEnd
5638+
? anchorUserScrollGenerationRef.current
5639+
: null;
5640+
setTimelineLiveFollowEnabled(followEnd);
56525641
pendingTimelineAnchorRef.current = null;
56535642
positionedTimelineAnchorRef.current = null;
56545643
settledTimelineAnchorRef.current = null;
56555644
activeTimelineAnchorIndexRef.current = null;
56565645
showScrollDebouncer.current.cancel();
5657-
setShowScrollToBottom(false);
5646+
setShowScrollToBottom(!followEnd);
56585647
// activeThreadRef resets transitively with the active thread.
5659-
}, [activeThread?.id]);
5648+
}, [activeThread?.id, routeThreadKey]);
56605649

56615650
useEffect(() => {
56625651
if (!activeThread?.id || terminalUiState.terminalOpen) return;

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

Lines changed: 188 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ import { ProposedPlanCard } from "./ProposedPlanCard";
151151
import { ChangedFilesCard } from "./ChangedFilesTree";
152152
import {
153153
CHAT_TIMELINE_ANCHOR_OFFSET,
154+
readTimelinePosition,
155+
rememberTimelinePosition,
154156
timelineContentOverflowsViewport,
155157
} from "./timelineScrollAnchoring";
156158
import { MessageCopyButton } from "./MessageCopyButton";
@@ -514,16 +516,27 @@ export const MessagesTimeline = memo(function MessagesTimeline({
514516
steerQueuedMessageShortcutLabel = null,
515517
onRemoveQueuedMessage = NOOP_QUEUED_MESSAGE_ACTION,
516518
}: MessagesTimelineProps) {
517-
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
518-
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
519-
// Preserve member disclosure state across virtualization.
519+
const listIdentityKey = displayThreadKey ?? routeThreadKey;
520+
const rememberedPosition = useMemo(
521+
() => readTimelinePosition(listIdentityKey),
522+
[listIdentityKey],
523+
);
524+
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(
525+
() => rememberedPosition?.disclosures?.turns ?? new Set(),
526+
);
527+
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(
528+
() => rememberedPosition?.disclosures?.workGroups ?? new Set(),
529+
);
520530
const [expandedSpawnEntryIds, setExpandedSpawnEntryIds] = useState<ReadonlySet<string>>(
521-
new Set(),
531+
() => rememberedPosition?.disclosures?.spawnEntries ?? new Set(),
522532
);
523533
const [expandedReasoningMessageIds, setExpandedReasoningMessageIds] = useState<
524534
ReadonlySet<string>
525-
>(new Set());
526-
const listIdentityKey = displayThreadKey ?? routeThreadKey;
535+
>(() => rememberedPosition?.disclosures?.reasoningMessages ?? new Set());
536+
const [positionedThreadKey, setPositionedThreadKey] = useState<string | null>(() =>
537+
rememberedPosition?.atEnd === false ? null : listIdentityKey,
538+
);
539+
const restoringThreadPosition = positionedThreadKey !== listIdentityKey;
527540
const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
528541
const listIdentityRef = useRef(listIdentityKey);
529542
const previousLatestTurnRef = useRef(latestTurn);
@@ -536,12 +549,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
536549
let paintedExpandedReasoningMessageIds = expandedReasoningMessageIds;
537550
if (listIdentityRef.current !== listIdentityKey) {
538551
listIdentityRef.current = listIdentityKey;
552+
setPositionedThreadKey(null);
539553
previousLatestTurnRef.current = latestTurn;
540554
setSettlingListIdentity(listIdentityKey);
541-
paintedExpandedTurnIds = new Set();
542-
paintedExpandedWorkGroupIds = new Set();
543-
paintedExpandedSpawnEntryIds = new Set();
544-
paintedExpandedReasoningMessageIds = new Set();
555+
paintedExpandedTurnIds = rememberedPosition?.disclosures?.turns ?? new Set();
556+
paintedExpandedWorkGroupIds = rememberedPosition?.disclosures?.workGroups ?? new Set();
557+
paintedExpandedSpawnEntryIds = rememberedPosition?.disclosures?.spawnEntries ?? new Set();
558+
paintedExpandedReasoningMessageIds =
559+
rememberedPosition?.disclosures?.reasoningMessages ?? new Set();
545560
setExpandedTurnIds(paintedExpandedTurnIds);
546561
setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
547562
setExpandedSpawnEntryIds(paintedExpandedSpawnEntryIds);
@@ -563,10 +578,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
563578
current.has(turnId) ? current : new Set([...current, turnId]),
564579
);
565580
}, []);
566-
// Scroll/disclosure state outlives virtualized rows, but never the current thread.
581+
// Nested tool state shares the bounded thread-position cache.
567582
const workGroupViewState = useMemo<WorkGroupViewState>(
568-
() => ({ scrollPositions: new Map(), expandedEntries: new Set() }),
569-
[listIdentityKey],
583+
() =>
584+
rememberedPosition?.disclosures?.workGroupState ?? {
585+
scrollPositions: new Map(),
586+
expandedEntries: new Set(),
587+
},
588+
[listIdentityKey, rememberedPosition],
570589
);
571590
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
572591
const [minimapStripMap] = useState(() => new Map<string, HTMLSpanElement>());
@@ -784,6 +803,122 @@ export const MessagesTimeline = memo(function MessagesTimeline({
784803
]);
785804
const rows = useStableRows(rawRows, listIdentityKey);
786805
const minimapItems = useMemo(() => deriveTimelineMinimapItems(rows), [rows]);
806+
const restoreRowIndex =
807+
restoringThreadPosition && rememberedPosition?.atEnd === false
808+
? rows.findIndex((row) => row.id === rememberedPosition.rowId)
809+
: -1;
810+
const restoringAlwaysRender = useMemo(
811+
() =>
812+
restoringThreadPosition && restoreRowIndex >= 0 ? { indices: [restoreRowIndex] } : undefined,
813+
[restoreRowIndex, restoringThreadPosition],
814+
);
815+
useLayoutEffect(() => {
816+
if (!restoringThreadPosition || rows.length === 0) return;
817+
const list = listRef.current;
818+
if (!list) return;
819+
if (citationRequest !== null) {
820+
setPositionedThreadKey(listIdentityKey);
821+
return;
822+
}
823+
let cancelled = false;
824+
let settleFrame: number | null = null;
825+
const viewport: HTMLElement | null = list.getScrollableNode();
826+
const cancelForNavigation = () => {
827+
if (cancelled) return;
828+
cancelled = true;
829+
if (settleFrame !== null) cancelAnimationFrame(settleFrame);
830+
// Supersede any pending estimated-index scroll before the browser applies the gesture.
831+
if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
832+
onManualNavigation();
833+
setPositionedThreadKey(listIdentityKey);
834+
};
835+
const onScrollKey = (event: globalThis.KeyboardEvent) => {
836+
if (
837+
["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key) &&
838+
!(
839+
event.target instanceof Element &&
840+
event.target.closest("input, textarea, [contenteditable=true]")
841+
)
842+
)
843+
cancelForNavigation();
844+
};
845+
viewport?.addEventListener("wheel", cancelForNavigation, { passive: true });
846+
viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });
847+
viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });
848+
viewport?.ownerDocument.addEventListener("keydown", onScrollKey);
849+
const position = rememberedPosition;
850+
const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
851+
if (position?.atEnd === false) onManualNavigation();
852+
const scrolling =
853+
position?.atEnd === false
854+
? index >= 0
855+
? list.scrollToIndex({
856+
index,
857+
animated: false,
858+
viewPosition: 0,
859+
viewOffset: -position.offsetWithinRow,
860+
})
861+
: list.scrollToOffset({ offset: position.scrollOffset, animated: false })
862+
: list.scrollToEnd({ animated: false });
863+
void Promise.resolve(scrolling).then(() => {
864+
if (cancelled) return;
865+
if (position?.atEnd !== false || index < 0) {
866+
setPositionedThreadKey(listIdentityKey);
867+
return;
868+
}
869+
// Index scrolling starts from estimates. Keep the saved row mounted
870+
// until its measured position and the DOM agree for two layout frames.
871+
let stableFrames = 0;
872+
const reconcile = () => {
873+
if (cancelled) return;
874+
const state = list.getState();
875+
const rowIndex = state.indexByKey(position.rowId);
876+
const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
877+
const element = list.getScrollableNode();
878+
if (!row || !element) return;
879+
const offset = Math.max(
880+
0,
881+
Math.min(
882+
element.scrollTop +
883+
row.getBoundingClientRect().top -
884+
element.getBoundingClientRect().top +
885+
position.offsetWithinRow,
886+
element.scrollHeight - element.clientHeight,
887+
),
888+
);
889+
if (Math.abs(element.scrollTop - offset) > 1) {
890+
stableFrames = 0;
891+
void list.scrollToOffset({ offset, animated: false }).then(() => {
892+
if (!cancelled) settleFrame = requestAnimationFrame(reconcile);
893+
});
894+
return;
895+
}
896+
if (++stableFrames >= 2) {
897+
setPositionedThreadKey(listIdentityKey);
898+
} else {
899+
settleFrame = requestAnimationFrame(reconcile);
900+
}
901+
};
902+
settleFrame = requestAnimationFrame(reconcile);
903+
});
904+
return () => {
905+
cancelled = true;
906+
if (settleFrame !== null) cancelAnimationFrame(settleFrame);
907+
viewport?.removeEventListener("wheel", cancelForNavigation);
908+
viewport?.removeEventListener("touchmove", cancelForNavigation);
909+
viewport?.removeEventListener("pointerdown", cancelForNavigation);
910+
viewport?.ownerDocument.removeEventListener("keydown", onScrollKey);
911+
};
912+
}, [
913+
citationRequest,
914+
listIdentityKey,
915+
listRef,
916+
onManualNavigation,
917+
rememberedPosition,
918+
restoringThreadPosition,
919+
rows,
920+
]);
921+
787922
const [timelineViewportElement, setTimelineViewportElement] = useState<HTMLDivElement | null>(
788923
null,
789924
);
@@ -804,6 +939,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
804939
onManualNavigation,
805940
});
806941
const [minimapHasPersistentGutter, setMinimapHasPersistentGutter] = useState(false);
942+
const alwaysRender = citationAlwaysRender ?? restoringAlwaysRender;
807943
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
808944
const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
809945
const handleAnchorReady = useCallback(
@@ -866,7 +1002,30 @@ export const MessagesTimeline = memo(function MessagesTimeline({
8661002

8671003
const handleScroll = useCallback(() => {
8681004
const state = listRef.current?.getState?.();
1005+
if (restoringThreadPosition || state?.data !== rows) return;
8691006
const isAtEnd = resolveTimelineIsAtEnd(state);
1007+
const position = state?.data?.length ? resolveWorkGroupScrollAnchor(state) : undefined;
1008+
if (position && state && isAtEnd !== undefined) {
1009+
const index = state.indexByKey(position.rowId);
1010+
const row = index === undefined ? undefined : state.elementAtIndex(index);
1011+
const element = listRef.current?.getScrollableNode();
1012+
if (row && element) {
1013+
rememberTimelinePosition(listIdentityKey, {
1014+
...position,
1015+
// DOM geometry includes the header and the virtualizer's layout adjustment.
1016+
offsetWithinRow: element.getBoundingClientRect().top - row.getBoundingClientRect().top,
1017+
scrollOffset: element.scrollTop,
1018+
atEnd: isAtEnd,
1019+
disclosures: {
1020+
turns: paintedExpandedTurnIds,
1021+
workGroups: paintedExpandedWorkGroupIds,
1022+
spawnEntries: paintedExpandedSpawnEntryIds,
1023+
reasoningMessages: paintedExpandedReasoningMessageIds,
1024+
workGroupState: workGroupViewState,
1025+
},
1026+
});
1027+
}
1028+
}
8701029
if (isAtEnd !== undefined && !citationPositioning) {
8711030
onIsAtEndChange(isAtEnd);
8721031
}
@@ -907,6 +1066,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
9071066
);
9081067
}, [
9091068
citationPositioning,
1069+
paintedExpandedTurnIds,
1070+
paintedExpandedWorkGroupIds,
1071+
paintedExpandedSpawnEntryIds,
1072+
paintedExpandedReasoningMessageIds,
1073+
workGroupViewState,
1074+
rows,
1075+
listIdentityKey,
1076+
restoringThreadPosition,
9101077
listRef,
9111078
minimapItems,
9121079
minimapStripMap,
@@ -1099,15 +1266,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
10991266
getItemType={getItemType}
11001267
renderItem={renderItem}
11011268
estimatedItemSize={90}
1102-
initialScrollAtEnd={citationRequest === null}
1269+
initialScrollAtEnd={citationRequest === null && rememberedPosition?.atEnd !== false}
11031270
// Legend needs a data refresh to mount new pins without a scroll event.
1104-
{...(readyCitationRequest ? { dataVersion: readyCitationRequest.key } : {})}
1105-
{...(citationAlwaysRender ? { alwaysRender: citationAlwaysRender } : {})}
1271+
dataVersion={readyCitationRequest?.key ?? listIdentityKey}
1272+
{...(alwaysRender ? { alwaysRender } : {})}
11061273
onLoad={onCitationListLoad}
11071274
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
11081275
contentInsetEndAdjustment={anchoredEndSpace ? contentInsetEndAdjustment : 0}
11091276
maintainScrollAtEnd={
11101277
citationPositioning ||
1278+
(restoringThreadPosition && rememberedPosition?.atEnd === false) ||
11111279
anchoredEndSpace ||
11121280
!liveFollowEnabled ||
11131281
disclosureToggleSettling
@@ -1117,7 +1285,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
11171285
: TIMELINE_MAINTAIN_SCROLL_AT_END
11181286
}
11191287
maintainVisibleContentPosition={
1120-
citationPositioning ? false : maintainVisibleContentPosition
1288+
citationPositioning ||
1289+
(restoringThreadPosition && rememberedPosition?.atEnd === false)
1290+
? false
1291+
: maintainVisibleContentPosition
11211292
}
11221293
maintainScrollAtEndThreshold={1}
11231294
onScroll={handleScroll}

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

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vite-plus/test";
22
import {
33
getAnchoredTurnMetrics,
44
getRowBottom,
5+
readTimelinePosition,
6+
rememberTimelinePosition,
57
timelineContentOverflowsViewport,
68
} from "./timelineScrollAnchoring";
79

@@ -171,3 +173,19 @@ describe("timeline scroll anchoring", () => {
171173
expect(withComposer?.overflowsUsableViewport).toBe(true);
172174
});
173175
});
176+
177+
describe("remembered timeline positions", () => {
178+
it("keeps reading positions and end-follow independent across threads and environments", () => {
179+
const reading = { rowId: "message-4", offsetWithinRow: 32, scrollOffset: 932, atEnd: false };
180+
const following = { rowId: "message-9", offsetWithinRow: 10, scrollOffset: 2010, atEnd: true };
181+
rememberTimelinePosition("scroll-test-a:thread-1", reading);
182+
rememberTimelinePosition("scroll-test-a:thread-2", following);
183+
rememberTimelinePosition("scroll-test-b:thread-1", following);
184+
expect(readTimelinePosition("scroll-test-a:thread-1")).toEqual(reading);
185+
expect(readTimelinePosition("scroll-test-a:thread-2")).toEqual(following);
186+
expect(readTimelinePosition("scroll-test-b:thread-1")).toEqual(following);
187+
expect(readTimelinePosition("scroll-test-a:unvisited")).toBeUndefined();
188+
rememberTimelinePosition("scroll-test-a:thread-1", following);
189+
expect(readTimelinePosition("scroll-test-a:thread-1")).toEqual(following);
190+
});
191+
});

0 commit comments

Comments
 (0)