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(conversation): stop topic scroll restore from corrupting its own snapshot (#14247)

Arvin Xuc1e2d134edfa
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
new file mode 100644
index 00000000000..458fce24e99
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
@@ -0,0 +1,299 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { type RefObject } from 'react';
+import { type VListHandle } from 'virtua';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { loadScrollSnapshot, saveScrollSnapshot } from '../utils/scrollSnapshotStore';
+import { useTopicScrollPersist } from './useTopicScrollPersist';
+
+interface FakeVList {
+ scrollOffset: number;
+ scrollSize: number;
+ scrollTo: ReturnType<typeof vi.fn>;
+ scrollToIndex: ReturnType<typeof vi.fn>;
+ viewportSize: number;
+}
+
+const createFakeVList = (overrides: Partial<FakeVList> = {}): FakeVList => ({
+ scrollOffset: 0,
+ scrollSize: 0,
+ scrollTo: vi.fn(),
+ scrollToIndex: vi.fn(),
+ viewportSize: 800,
+ ...overrides,
+});
+
+const refOf = (handle: FakeVList | null): RefObject<VListHandle | null> => ({
+ current: handle as unknown as VListHandle | null,
+});
+
+// One rAF tick in happy-dom is ~16ms; advancing 32ms covers two scheduled
+// frames reliably without running all queued timers (which would fire the
+// entire poll loop at once).
+const advanceFrames = async (frames: number) => {
+ await vi.advanceTimersByTimeAsync(frames * 32);
+};
+
+describe('useTopicScrollPersist', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ describe('initial restore', () => {
+ it('falls back to scrollToIndex(last, end) when there is no snapshot', async () => {
+ const handle = createFakeVList({ scrollSize: 5000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(2);
+
+ expect(handle.scrollToIndex).toHaveBeenCalledTimes(1);
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(49, { align: 'end' });
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+ });
+
+ it('falls back to scrollToIndex(last, end) when snapshot.atBottom is true', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: true,
+ offset: 9999,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 5000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(2);
+
+ expect(handle.scrollToIndex).toHaveBeenCalledWith(49, { align: 'end' });
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+ });
+
+ it('does not call scrollTo immediately when virtua scrollSize is too small', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // A few frames in, virtua still hasn't measured items below the fold β€”
+ // scrollTo would be clamped, so the hook must keep polling instead.
+ await advanceFrames(4);
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+ });
+
+ it('calls scrollTo with the saved offset once virtua has measured enough', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(3);
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+
+ // Simulate virtua finishing layout β€” now scrollSize is big enough to
+ // accommodate target + viewport.
+ handle.scrollSize = 6000;
+ await advanceFrames(3);
+
+ expect(handle.scrollTo).toHaveBeenCalledTimes(1);
+ expect(handle.scrollTo).toHaveBeenCalledWith(5000);
+ });
+
+ it('gives up polling after the cap and calls scrollTo anyway', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 999_999,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 1000, viewportSize: 800 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // 30-frame cap + a few extra for the release rAFs.
+ await advanceFrames(40);
+
+ expect(handle.scrollTo).toHaveBeenCalledTimes(1);
+ expect(handle.scrollTo).toHaveBeenCalledWith(999_999);
+ });
+
+ it('converges the snapshot to the actual landing position after capping out', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 999_999,
+ savedAt: Date.now() - 60_000,
+ });
+ const handle = createFakeVList({ scrollSize: 1500, viewportSize: 800 });
+ // Simulate virtua clamping the request to the actual scrollable range.
+ handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scrollOffset = Math.min(offset, handle.scrollSize - handle.viewportSize);
+ });
+
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(40);
+
+ // 1500 - 800 = 700; this is what virtua actually landed on.
+ const persisted = loadScrollSnapshot('main_agt_1_tpc_a');
+ expect(persisted?.offset).toBe(700);
+ // 1500 - 700 - 800 = 0 ≀ 300 β†’ at bottom now that we've clamped.
+ expect(persisted?.atBottom).toBe(true);
+ });
+
+ it('does not rewrite the snapshot when the saved offset was reached without capping', async () => {
+ const originalSavedAt = Date.now() - 60_000;
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: originalSavedAt,
+ });
+ const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
+ handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scrollOffset = offset;
+ });
+
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(20);
+
+ // Snapshot is untouched β€” same offset and same savedAt.
+ const persisted = loadScrollSnapshot('main_agt_1_tpc_a');
+ expect(persisted?.offset).toBe(5000);
+ expect(persisted?.savedAt).toBe(originalSavedAt);
+ });
+
+ it('skips the entire restore until dataSourceLength becomes non-zero', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 6000 });
+ const { rerender } = renderHook(
+ ({ length }: { length: number }) =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: length,
+ virtuaRef: refOf(handle),
+ }),
+ { initialProps: { length: 0 } },
+ );
+
+ await advanceFrames(3);
+ expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(handle.scrollToIndex).not.toHaveBeenCalled();
+
+ rerender({ length: 50 });
+ await advanceFrames(3);
+
+ expect(handle.scrollTo).toHaveBeenCalledWith(5000);
+ });
+ });
+
+ describe('recordScroll suppression during restore', () => {
+ it('drops recordScroll calls fired before the restore lands', async () => {
+ const startingSnapshot = { atBottom: false, offset: 5000, savedAt: Date.now() };
+ saveScrollSnapshot('main_agt_1_tpc_a', startingSnapshot);
+ const handle = createFakeVList({ scrollSize: 6000 });
+
+ const { result } = renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // Simulate the onScroll volley triggered by the programmatic scrollTo
+ // landing at offset 0 (because virtua clamped β€” what used to corrupt
+ // the snapshot before the fix).
+ act(() => {
+ result.current.recordScroll(0, true);
+ });
+
+ // Let the restore + flush window pass.
+ await advanceFrames(20);
+ await vi.advanceTimersByTimeAsync(300);
+
+ expect(loadScrollSnapshot('main_agt_1_tpc_a')?.offset).toBe(5000);
+ });
+
+ it('resumes recordScroll after the restore settles', async () => {
+ saveScrollSnapshot('main_agt_1_tpc_a', {
+ atBottom: false,
+ offset: 5000,
+ savedAt: Date.now(),
+ });
+ const handle = createFakeVList({ scrollSize: 6000 });
+
+ const { result } = renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // Wait for restore to land + guard release (2 rAFs after scrollTo).
+ await advanceFrames(20);
+
+ act(() => {
+ result.current.recordScroll(7777, false);
+ });
+ await vi.advanceTimersByTimeAsync(300);
+
+ expect(loadScrollSnapshot('main_agt_1_tpc_a')?.offset).toBe(7777);
+ });
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
index b86182086a5..2ac50971d98 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
@@ -2,6 +2,7 @@ import type { RefObject } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import type { VListHandle } from 'virtua';
+import { AT_BOTTOM_THRESHOLD } from '../components/AutoScroll/const';
import {
isDraftPromotionKey,
loadScrollSnapshot,
@@ -11,6 +12,9 @@ import {
} from '../utils/scrollSnapshotStore';
const FLUSH_THROTTLE_MS = 200;
+// Cap polling for virtua's scrollSize to settle so we don't loop forever when
+// the saved offset is unreachable (e.g. messages were trimmed since save).
+const RESTORE_MAX_FRAMES = 30;
interface PendingWrite {
atBottom: boolean;
@@ -27,9 +31,11 @@ interface UseTopicScrollPersistOptions {
/**
* Persists per-topic chat scroll position to localStorage.
*
- * The Provider does not remount on topic switch β€” the same VirtualizedList
- * instance handles every topic, so we react to `contextKey` changes ourselves
- * to flush the previous topic and restore the next.
+ * In practice `ChatList` shows a SkeletonList while `messagesInit` is false,
+ * so VirtualizedList unmounts on every topic switch and this hook is
+ * re-initialized fresh. The contextKey-change branch below still exists for
+ * the in-place draft β†’ real-id promotion path, where the same instance
+ * survives the key change.
*/
export const useTopicScrollPersist = ({
contextKey,
@@ -43,6 +49,11 @@ export const useTopicScrollPersist = ({
const prevContextKeyRef = useRef(contextKey);
const dataSourceLengthRef = useRef(dataSourceLength);
dataSourceLengthRef.current = dataSourceLength;
+ // 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
+ // virtua clamps the target, locking the user at the top on every revisit.
+ const restoringRef = useRef(false);
const flushNow = useCallback(() => {
if (flushTimerRef.current) {
@@ -61,6 +72,7 @@ export const useTopicScrollPersist = ({
const recordScroll = useCallback(
(offset: number, atBottom: boolean) => {
+ if (restoringRef.current) return;
pendingWriteRef.current = { atBottom, key: contextKey, offset };
if (flushTimerRef.current) return;
flushTimerRef.current = setTimeout(() => {
@@ -105,20 +117,66 @@ export const useTopicScrollPersist = ({
if (!virtuaRef.current || dataSourceLength === 0) return;
needsRestoreRef.current = false;
+ restoringRef.current = true;
- const snapshot = loadScrollSnapshot(contextKey);
-
- if (snapshot && !snapshot.atBottom) {
- // virtua needs item sizes measured before scrollTo lands at the right
- // pixel β€” defer one frame so the just-mounted items have layout.
+ // 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.
+ const finalize = (convergeSnapshot: boolean) => {
requestAnimationFrame(() => {
- virtuaRef.current?.scrollTo(snapshot.offset);
+ requestAnimationFrame(() => {
+ if (convergeSnapshot) {
+ const ref = virtuaRef.current;
+ if (ref) {
+ const isAtBottom =
+ ref.scrollSize - ref.scrollOffset - ref.viewportSize <= AT_BOTTOM_THRESHOLD;
+ pendingWriteRef.current = {
+ atBottom: isAtBottom,
+ key: contextKey,
+ offset: ref.scrollOffset,
+ };
+ flushNow();
+ }
+ }
+ restoringRef.current = false;
+ });
});
+ };
+
+ const snapshot = loadScrollSnapshot(contextKey);
+ const targetOffset = snapshot && !snapshot.atBottom ? snapshot.offset : null;
+
+ if (targetOffset === null) {
+ virtuaRef.current.scrollToIndex(dataSourceLength - 1, { align: 'end' });
+ finalize(false);
return;
}
- virtuaRef.current.scrollToIndex(dataSourceLength - 1, { align: 'end' });
- }, [contextKey, dataSourceLength, virtuaRef]);
+ // Wait for virtua to measure enough items so scrollTo(targetOffset)
+ // doesn't get clamped against the still-incomplete scrollSize of the
+ // freshly-mounted VList. A single rAF isn't enough β€” only the viewport-
+ // visible items have laid out by then, and ResizeObserver hasn't reported
+ // below-the-fold heights yet.
+ let attempts = 0;
+ const tryScroll = () => {
+ const ref = virtuaRef.current;
+ if (!ref) {
+ restoringRef.current = false;
+ return;
+ }
+ const required = targetOffset + ref.viewportSize;
+ const cappedOut = attempts >= RESTORE_MAX_FRAMES;
+ if (ref.scrollSize >= required || cappedOut) {
+ ref.scrollTo(targetOffset);
+ finalize(cappedOut);
+ return;
+ }
+ attempts += 1;
+ requestAnimationFrame(tryScroll);
+ };
+ requestAnimationFrame(tryScroll);
+ }, [contextKey, dataSourceLength, flushNow, virtuaRef]);
// One-shot housekeeping: drop expired entries and enforce the cap.
useEffect(() => {