Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(chat): only restore chat scroll position within a 5-min window (#16266)

Arvin Xua5b9d9f88442
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
index 458fce24e99..b04ad3c4614 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
@@ -296,4 +296,93 @@ describe('useTopicScrollPersist', () => {
expect(loadScrollSnapshot('main_agt_1_tpc_a')?.offset).toBe(7777);
});
});
+
+ describe('leave-time re-stamp', () => {
+ it('refreshes savedAt on unmount using the last scrolled position', async () => {
+ const fixedNow = 1_000_000_000_000;
+ vi.setSystemTime(fixedNow);
+ const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
+
+ const { result, unmount } = renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // Initial restore (no snapshot) settles, then the user scrolls up.
+ await advanceFrames(2);
+ act(() => {
+ result.current.recordScroll(2000, false);
+ });
+ await vi.advanceTimersByTimeAsync(300);
+
+ // Simulate idle reading: time passes well beyond the 5-min window with no
+ // further scrolling, then the user switches topics (unmount).
+ vi.setSystemTime(fixedNow + 10 * 60 * 1000);
+ unmount();
+
+ const persisted = loadScrollSnapshot('main_agt_1_tpc_a');
+ expect(persisted?.offset).toBe(2000);
+ // savedAt is the departure time, not the last-scroll time, so a quick
+ // return still restores the position.
+ expect(persisted?.savedAt).toBe(fixedNow + 10 * 60 * 1000);
+ });
+
+ it('refreshes savedAt on unmount even when the user never scrolled after restore', async () => {
+ const fixedNow = 1_000_000_000_000;
+ vi.setSystemTime(fixedNow);
+ // Existing snapshot restored to offset 5000; user then reads without
+ // scrolling and leaves after the window would have expired.
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: fixedNow,
+ });
+ const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
+ handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scrollOffset = offset;
+ });
+
+ const { unmount } = renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // Let the restore land and seed lastKnownRef from where it landed.
+ await advanceFrames(4);
+
+ vi.setSystemTime(fixedNow + 10 * 60 * 1000);
+ unmount();
+
+ const persisted = loadScrollSnapshot('main_agt_1_tpc_a');
+ expect(persisted?.offset).toBe(5000);
+ expect(persisted?.savedAt).toBe(fixedNow + 10 * 60 * 1000);
+ });
+
+ it('does not create a snapshot on unmount when nothing was ever recorded', async () => {
+ // No prior snapshot, restore falls back to scroll-to-bottom, and the user
+ // never scrolls. scrollOffset stays 0 (bottom in the fake) so we still
+ // record an at-bottom position β€” which restores to the bottom anyway.
+ const handle = createFakeVList({ scrollSize: 0, viewportSize: 800 });
+ const { unmount } = renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_empty',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(4);
+ unmount();
+
+ // Either no snapshot, or an at-bottom one β€” both restore to the bottom.
+ const persisted = loadScrollSnapshot('main_agt_1_tpc_empty');
+ expect(persisted?.atBottom ?? true).toBe(true);
+ });
+ });
});
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
index 2ac50971d98..cde0538b1aa 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
@@ -44,11 +44,21 @@ export const useTopicScrollPersist = ({
}: UseTopicScrollPersistOptions) => {
const pendingWriteRef = useRef<PendingWrite | null>(null);
const flushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // The most recent known scroll position for the active topic, kept in sync on
+ // every user scroll and seeded once a restore lands. Unlike `pendingWriteRef`
+ // (cleared after each throttled flush), this survives idle reading so a
+ // leave-time re-stamp can refresh `savedAt` even when the user hasn't
+ // scrolled β€” see `persistFresh`.
+ const lastKnownRef = useRef<{ atBottom: boolean; offset: number } | null>(null);
// Initial mount counts as a "key change" so the first restore attempt fires.
const needsRestoreRef = useRef(true);
const prevContextKeyRef = useRef(contextKey);
const dataSourceLengthRef = useRef(dataSourceLength);
dataSourceLengthRef.current = dataSourceLength;
+ // Mirror the active key so unmount / beforeunload handlers (bound once) can
+ // re-stamp the topic the user is actually leaving.
+ const contextKeyRef = useRef(contextKey);
+ contextKeyRef.current = contextKey;
// True from the moment a restore starts until the resulting onScroll has
// settled. Without this guard, the programmatic scroll would feed back into
// recordScroll and overwrite the snapshot β€” typically with offset 0 when
@@ -73,6 +83,7 @@ export const useTopicScrollPersist = ({
const recordScroll = useCallback(
(offset: number, atBottom: boolean) => {
if (restoringRef.current) return;
+ lastKnownRef.current = { atBottom, offset };
pendingWriteRef.current = { atBottom, key: contextKey, offset };
if (flushTimerRef.current) return;
flushTimerRef.current = setTimeout(() => {
@@ -83,7 +94,24 @@ export const useTopicScrollPersist = ({
[contextKey, flushNow],
);
- // On contextKey change: flush any pending writes against the previous key,
+ // Re-stamp the last known position for `key` with a fresh `savedAt`. Called
+ // when the user leaves a topic (switch, unmount, or tab close) so the 5-min
+ // restore window is measured from *departure*, not from the last scroll β€”
+ // otherwise idle-reading a topic for over 5 min would expire its snapshot
+ // before the user even leaves. No-op until a position is known (the user
+ // never scrolled and no restore has landed).
+ const persistFresh = useCallback((key: string) => {
+ if (flushTimerRef.current) {
+ clearTimeout(flushTimerRef.current);
+ flushTimerRef.current = null;
+ }
+ pendingWriteRef.current = null;
+ const last = lastKnownRef.current;
+ if (!last) return;
+ saveScrollSnapshot(key, { atBottom: last.atBottom, offset: last.offset, savedAt: Date.now() });
+ }, []);
+
+ // On contextKey change: re-stamp the previous key with the latest position,
// then either preserve scroll (draft β†’ real-id promotion of the same
// conversation) or arm a restore (real topic switch).
useEffect(() => {
@@ -91,7 +119,9 @@ export const useTopicScrollPersist = ({
if (prevKey === contextKey) return;
prevContextKeyRef.current = contextKey;
- flushNow();
+ // Re-stamp the topic we're leaving so its snapshot stays within the restore
+ // window if the user comes back soon.
+ persistFresh(prevKey);
if (isDraftPromotionKey(prevKey, contextKey)) {
// `onTopicCreated` mutates context mid-stream: same conversation, new
@@ -108,7 +138,7 @@ export const useTopicScrollPersist = ({
}
needsRestoreRef.current = true;
- }, [contextKey, flushNow]);
+ }, [contextKey, persistFresh]);
// Restore (or fall back to scroll-to-bottom) once data is available for
// the active contextKey. Re-runs on contextKey or data length change.
@@ -119,18 +149,23 @@ export const useTopicScrollPersist = ({
needsRestoreRef.current = false;
restoringRef.current = true;
- // After two rAFs the programmatic scroll's onScroll volley has flushed,
- // so we can re-enable recording. When `convergeSnapshot` is set, the
- // target was unreachable β€” persist the actual landing position so the
- // snapshot self-heals and future revisits don't burn the polling budget.
+ // After two rAFs the programmatic scroll's onScroll volley has flushed, so
+ // we can re-enable recording and record where the restore landed.
const finalize = (convergeSnapshot: boolean) => {
requestAnimationFrame(() => {
requestAnimationFrame(() => {
- if (convergeSnapshot) {
- const ref = virtuaRef.current;
- if (ref) {
- const isAtBottom =
- ref.scrollSize - ref.scrollOffset - ref.viewportSize <= AT_BOTTOM_THRESHOLD;
+ const ref = virtuaRef.current;
+ if (ref) {
+ const isAtBottom =
+ ref.scrollSize - ref.scrollOffset - ref.viewportSize <= AT_BOTTOM_THRESHOLD;
+ // Seed the last-known position from where the restore actually
+ // landed so a later leave-time re-stamp (persistFresh) has a
+ // position to refresh even if the user reads without scrolling.
+ lastKnownRef.current = { atBottom: isAtBottom, offset: ref.scrollOffset };
+ if (convergeSnapshot) {
+ // Target was unreachable β€” persist the actual landing position so
+ // the snapshot self-heals and future revisits don't burn the
+ // polling budget.
pendingWriteRef.current = {
atBottom: isAtBottom,
key: contextKey,
@@ -183,15 +218,18 @@ export const useTopicScrollPersist = ({
pruneScrollSnapshots();
}, []);
- // Flush on unmount and on tab close so the most recent offset survives.
+ // Re-stamp on unmount (topic switch remounts this list) and on tab close so
+ // the latest position survives with a fresh `savedAt`. Reading virtuaRef here
+ // is unreliable β€” VList's imperative handle is detached before this cleanup
+ // runs β€” so we rely on the continuously-tracked lastKnownRef instead.
useEffect(() => {
- const handleBeforeUnload = () => flushNow();
+ const handleBeforeUnload = () => persistFresh(contextKeyRef.current);
window.addEventListener('beforeunload', handleBeforeUnload);
return () => {
window.removeEventListener('beforeunload', handleBeforeUnload);
- flushNow();
+ persistFresh(contextKeyRef.current);
};
- }, [flushNow]);
+ }, [persistFresh]);
return { recordScroll };
};
diff --git a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts
index b4ea7bec455..b65f99717ff 100644
--- a/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts
+++ b/src/features/Conversation/ChatList/utils/scrollSnapshotStore.ts
@@ -1,6 +1,12 @@
export const SCROLL_SNAPSHOT_KEY_PREFIX = 'LOBEHUB_SCROLL';
export const SCROLL_SNAPSHOT_MAX_ENTRIES = 500;
-export const SCROLL_SNAPSHOT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
+// A scroll snapshot is only meant to survive a quick back-and-forth between
+// topics. Beyond this window we intentionally drop it so revisiting a topic
+// (e.g. the next day) lands at the bottom on the latest messages instead of
+// restoring a stale reading position. Because both `loadScrollSnapshot` (read
+// time) and `pruneScrollSnapshots` (mount time) evict entries past this age,
+// the short TTL also keeps the localStorage key count tiny.
+export const SCROLL_SNAPSHOT_MAX_AGE_MS = 5 * 60 * 1000;
export interface ScrollSnapshot {
atBottom: boolean;