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: stop auto-scroll once the user scrolls during streaming (#20696)

YuTengjing78d44d9e6384
diff --git a/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx b/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx
index 28076db525b..42e9b02db41 100644
--- a/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx
+++ b/src/features/Conversation/ChatList/components/AutoScroll/DebugInspector.tsx
@@ -64,13 +64,14 @@ const DebugInspector = memo(() => {
const mounted = useDevDockMounted();
const enabled = useDevDockStore((s) => s.scrollDebug);
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
+ const autoScrollDetached = useConversationStore(virtuaListSelectors.autoScrollDetached);
const isScrolling = useConversationStore(virtuaListSelectors.isScrolling);
const isGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
const virtuaScrollMethods = useConversationStore((s) => s.virtuaScrollMethods);
if (!mounted || !enabled) return null;
- const shouldAutoScroll = atBottom && isGenerating && !isScrolling;
+ const shouldAutoScroll = atBottom && !autoScrollDetached && isGenerating && !isScrolling;
const scrollOffset = virtuaScrollMethods?.getScrollOffset?.() ?? 0;
const scrollSize = virtuaScrollMethods?.getScrollSize?.() ?? 0;
const viewportSize = virtuaScrollMethods?.getViewportSize?.() ?? 0;
@@ -184,6 +185,9 @@ const DebugInspector = memo(() => {
<div style={{ color: isScrolling ? '#f59e0b' : '#6b7280', fontSize: 10 }}>
scrolling: {isScrolling ? 'YES' : 'NO'}
</div>
+ <div style={{ color: autoScrollDetached ? '#f59e0b' : '#6b7280', fontSize: 10 }}>
+ detached: {autoScrollDetached ? 'YES' : 'NO'}
+ </div>
</div>
<div
diff --git a/src/features/Conversation/ChatList/components/AutoScroll/index.tsx b/src/features/Conversation/ChatList/components/AutoScroll/index.tsx
index 0017a997594..c9e508f7d3d 100644
--- a/src/features/Conversation/ChatList/components/AutoScroll/index.tsx
+++ b/src/features/Conversation/ChatList/components/AutoScroll/index.tsx
@@ -1,11 +1,12 @@
'use client';
-import { memo, useEffect } from 'react';
+import { memo, useEffect, useLayoutEffect } from 'react';
import {
dataSelectors,
messageStateSelectors,
useConversationStore,
+ useConversationStoreApi,
virtuaListSelectors,
} from '../../../store';
@@ -18,24 +19,52 @@ import {
*/
const AutoScroll = memo(() => {
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
+ const autoScrollDetached = useConversationStore(virtuaListSelectors.autoScrollDetached);
const isScrolling = useConversationStore(virtuaListSelectors.isScrolling);
const isGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
+ const virtuaScrollMethods = useConversationStore((s) => s.virtuaScrollMethods);
+ const storeApi = useConversationStoreApi();
const dbMessages = useConversationStore(dataSelectors.dbMessages);
- const shouldAutoScroll = atBottom && isGenerating && !isScrolling;
+ const shouldAutoScroll = atBottom && !autoScrollDetached && isGenerating && !isScrolling;
// Get the content length of the last message to monitor streaming output
const lastMessage = dbMessages.at(-1);
const lastMessageContentLength =
typeof lastMessage?.content === 'string' ? lastMessage.content.length : 0;
- useEffect(() => {
+ // Layout effect: the new chunk is already in the DOM, so jump before paint
+ // instead of showing one frame with the newest lines below the fold.
+ useLayoutEffect(() => {
if (shouldAutoScroll) {
scrollToBottom(false);
}
}, [shouldAutoScroll, scrollToBottom, dbMessages.length, lastMessageContentLength]);
+ // Rows also grow outside the content-length change above (e.g. markdown
+ // rendering a chunk in a later commit), and virtua only resizes the list
+ // after measuring them. Follow every rendered row's growth before paint so
+ // the newest lines never sit below the fold. Unlike virtua's own imperative
+ // scroll, this stops as soon as the user scrolls away (`shouldAutoScroll`
+ // turns false).
+ useEffect(() => {
+ if (!shouldAutoScroll) return;
+
+ const content = virtuaScrollMethods?.getScrollElement()?.firstElementChild;
+ if (!content) return;
+
+ const observer = new ResizeObserver(() => {
+ // The user may have started scrolling since this effect last ran.
+ const { autoScrollDetached, isScrolling } = storeApi.getState();
+ if (autoScrollDetached || isScrolling) return;
+ scrollToBottom(false);
+ });
+ observer.observe(content);
+ for (const row of content.children) observer.observe(row);
+ return () => observer.disconnect();
+ }, [shouldAutoScroll, scrollToBottom, storeApi, virtuaScrollMethods, dbMessages.length]);
+
// No visual output - this component only handles auto-scroll logic
return null;
});
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 230d21469ca..590bb001b7f 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -24,6 +24,7 @@ import {
inputSelectors,
messageStateSelectors,
useConversationStore,
+ useConversationStoreApi,
virtuaListSelectors,
} from '../../store';
import {
@@ -33,6 +34,7 @@ import {
import { useEarlierHistoryTrigger } from '../hooks/useEarlierHistoryTrigger';
import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
import { useTopicScrollPersist } from '../hooks/useTopicScrollPersist';
+import { resolveAutoScrollDetached } from '../utils/autoScrollFollow';
import type { ResolvedMessageDeepLink } from '../utils/messageDeepLink';
import AutoScroll from './AutoScroll';
import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';
@@ -54,6 +56,7 @@ const CONVERSATION_HEADER_ID = '__conversation_header__';
// that talk to virtua directly) work in MESSAGE index space; this offset
// translates at the virtua boundary.
const LEADING_ROWS = 1;
+const VLIST_CLASS_NAME = 'conversation-vlist';
const USER_SCROLL_INTENT_TTL_MS = 500;
const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
@@ -76,15 +79,26 @@ const VirtualizedList = memo<VirtualizedListProps>(
const containerRef = useRef<HTMLDivElement>(null);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const lastUserScrollIntentAtRef = useRef(0);
+ // Plain clicks also mark `lastUserScrollIntentAtRef` (scrollbar track
+ // clicks), but a click that collapses a block makes the browser correct the
+ // offset upward β€” so detaching auto-scroll only trusts actual scroll input.
+ const lastActiveScrollInputAtRef = useRef(0);
+ const lastScrollOffsetRef = useRef<number | null>(null);
// Per-topic scroll restoration. Provider does not remount on topic switch,
// so we key the scroll snapshot by the message-map key derived from
// ConversationStore's `context`.
const contextKey = useConversationStore((s) => messageMapKey(s.context));
+ const getScroller = useCallback(
+ () =>
+ containerRef.current?.querySelector<HTMLElement>(`:scope > .${VLIST_CLASS_NAME}`) ?? null,
+ [],
+ );
const { recordScroll } = useTopicScrollPersist({
contextKey,
containerRef,
dataSourceLength: dataSource.length,
+ getScroller,
headerOffset: LEADING_ROWS,
messageDeepLink,
virtuaRef,
@@ -120,9 +134,11 @@ const VirtualizedList = memo<VirtualizedListProps>(
const isSelectionMode = useConversationStore(messageStateSelectors.isSelectionMode);
// Store actions
+ const storeApi = useConversationStoreApi();
const loadEarlierMessages = useConversationStore((s) => s.loadEarlierMessages);
const registerVirtuaScrollMethods = useConversationStore((s) => s.registerVirtuaScrollMethods);
const setScrollState = useConversationStore((s) => s.setScrollState);
+ const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
const resetVisibleItems = useConversationStore((s) => s.resetVisibleItems);
const setActiveIndex = useConversationStore((s) => s.setActiveIndex);
const activeIndex = useConversationStore(virtuaListSelectors.activeIndex);
@@ -133,51 +149,82 @@ const VirtualizedList = memo<VirtualizedListProps>(
lastUserScrollIntentAtRef.current = Date.now();
}, []);
+ // `isScrolling` pauses streaming auto-scroll, so it tracks the user's own
+ // scrolling only. Auto-scroll's jumps also fire scroll events; counting
+ // them would hold the flag and throttle following to one jump per
+ // scroll-end debounce, leaving the newest lines below the fold.
+ const markUserScrolling = useCallback(() => {
+ setScrollState({ isScrolling: true });
+ if (scrollEndTimerRef.current) clearTimeout(scrollEndTimerRef.current);
+ scrollEndTimerRef.current = setTimeout(() => {
+ setScrollState({ isScrolling: false });
+ }, 150);
+ }, [setScrollState]);
+
+ const markActiveScrollInput = useCallback(() => {
+ const now = Date.now();
+ lastUserScrollIntentAtRef.current = now;
+ lastActiveScrollInputAtRef.current = now;
+ // Mark before the resulting scroll event so a streaming chunk landing in
+ // between cannot jump over the user's input.
+ markUserScrolling();
+ }, [markUserScrolling]);
+
+ const handlePointerDown = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ // A press on the scroller's own scrollbar (track click or drag start)
+ // is scroll input; presses on message content are just clicks.
+ const target = event.target as HTMLElement;
+ const isScroller = target.clientWidth > 0 && target.scrollHeight > target.clientHeight;
+ if (isScroller && event.nativeEvent.offsetX > target.clientWidth) {
+ markActiveScrollInput();
+ } else {
+ markUserScrollIntent();
+ }
+ },
+ [markActiveScrollInput, markUserScrollIntent],
+ );
+
const handlePointerMove = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
if (event.buttons > 0) {
- markUserScrollIntent();
+ markActiveScrollInput();
}
},
- [markUserScrollIntent],
+ [markActiveScrollInput],
);
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLDivElement>) => {
if (SCROLL_KEYS.has(event.key)) {
- markUserScrollIntent();
+ markActiveScrollInput();
}
earlierHistory.onKeyDown(event);
},
- [earlierHistory, markUserScrollIntent],
+ [earlierHistory, markActiveScrollInput],
);
const handleWheel = useCallback(
(event: WheelEvent<HTMLDivElement>) => {
- markUserScrollIntent();
+ markActiveScrollInput();
earlierHistory.onWheel(event);
},
- [earlierHistory, markUserScrollIntent],
+ [earlierHistory, markActiveScrollInput],
);
const handleTouchMove = useCallback(
(event: TouchEvent<HTMLDivElement>) => {
- markUserScrollIntent();
+ markActiveScrollInput();
earlierHistory.onTouchMove(event);
},
- [earlierHistory, markUserScrollIntent],
+ [earlierHistory, markActiveScrollInput],
);
- // Check if at bottom based on scroll position
- const checkAtBottom = useCallback(() => {
+ const getDistanceToBottom = useCallback(() => {
const ref = virtuaRef.current;
- if (!ref) return false;
+ if (!ref) return Infinity;
- const scrollOffset = ref.scrollOffset;
- const scrollSize = ref.scrollSize;
- const viewportSize = ref.viewportSize;
-
- return scrollSize - scrollOffset - viewportSize <= AT_BOTTOM_THRESHOLD;
+ return ref.scrollSize - ref.scrollOffset - ref.viewportSize;
}, []);
// Handle scroll events
@@ -196,46 +243,72 @@ const VirtualizedList = memo<VirtualizedListProps>(
if (activeFromFind !== activeIndex) setActiveIndex(activeFromFind);
- setScrollState({ isScrolling: true });
+ const hasUserScrollIntent =
+ Date.now() - lastUserScrollIntentAtRef.current <= USER_SCROLL_INTENT_TTL_MS;
+ if (hasUserScrollIntent) markUserScrolling();
+
+ const distanceToBottom = getDistanceToBottom();
+ const isAtBottom = distanceToBottom <= AT_BOTTOM_THRESHOLD;
// Shrink spacer on scroll up when not streaming
const ref = virtuaRef.current;
if (ref) {
- const hasUserScrollIntent =
- Date.now() - lastUserScrollIntentAtRef.current <= USER_SCROLL_INTENT_TTL_MS;
onScrollOffset(ref.scrollOffset, hasUserScrollIntent);
// Programmatic mount/restore scrolls carry no intent and never fetch.
if (hasUserScrollIntent) earlierHistory.onUserScroll();
- }
- // Check if at bottom
- const isAtBottom = checkAtBottom();
- setScrollState({ atBottom: isAtBottom });
+ const autoScrollDetached = resolveAutoScrollDetached({
+ detached: storeApi.getState().autoScrollDetached,
+ distanceToBottom,
+ hasActiveScrollInput:
+ Date.now() - lastActiveScrollInputAtRef.current <= USER_SCROLL_INTENT_TTL_MS,
+ offset: ref.scrollOffset,
+ prevOffset: lastScrollOffsetRef.current,
+ });
+ lastScrollOffsetRef.current = ref.scrollOffset;
+ setScrollState({ atBottom: isAtBottom, autoScrollDetached });
+ } else {
+ setScrollState({ atBottom: isAtBottom });
+ }
if (ref) {
recordScroll(ref.scrollOffset, isAtBottom);
}
-
- // Clear existing timer
- if (scrollEndTimerRef.current) {
- clearTimeout(scrollEndTimerRef.current);
- }
-
- // Set new timer for scroll end
- scrollEndTimerRef.current = setTimeout(() => {
- setScrollState({ isScrolling: false });
- }, 150);
}, [
activeIndex,
- checkAtBottom,
earlierHistory,
+ getDistanceToBottom,
+ markUserScrolling,
onScrollOffset,
recordScroll,
setActiveIndex,
setScrollState,
+ storeApi,
]);
+ // Sending a message is an explicit request to follow the new reply, so it
+ // re-attaches auto-scroll even if the user had scrolled away earlier.
+ // Keyed on the last id: loading earlier history prepends rows and leaves it
+ // unchanged, so it must not count as a send.
+ const lastMessageId = dataSource.at(-1);
+ const prevLastMessageIdRef = useRef(lastMessageId);
+ useEffect(() => {
+ const lastChanged = lastMessageId !== prevLastMessageIdRef.current;
+ prevLastMessageIdRef.current = lastMessageId;
+ if (lastChanged && isSecondLastMessageFromUser) {
+ setScrollState({ autoScrollDetached: false });
+ }
+ }, [isSecondLastMessageFromUser, lastMessageId, setScrollState]);
+
+ // BackBottom is an explicit request to follow again. While streaming, a
+ // smooth scroll aims at the bottom measured at click time and lands short
+ // once the reply has grown, so jump instead and let auto-scroll take over.
+ const handleBackBottom = useCallback(() => {
+ setScrollState({ autoScrollDetached: false });
+ scrollToBottom(!messageStateSelectors.isAIGenerating(storeApi.getState()));
+ }, [scrollToBottom, setScrollState, storeApi]);
+
const handleScrollEnd = useCallback(() => {
setScrollState({ isScrolling: false });
}, [setScrollState]);
@@ -249,11 +322,16 @@ const VirtualizedList = memo<VirtualizedListProps>(
registerVirtuaScrollMethods({
getItemOffset: (index) => ref.getItemOffset(index + LEADING_ROWS),
getItemSize: (index) => ref.getItemSize(index + LEADING_ROWS),
+ getScrollElement: getScroller,
getScrollOffset: () => ref.scrollOffset,
getScrollSize: () => ref.scrollSize,
getTotalCount: () => totalCountRef.current,
getViewportSize: () => ref.viewportSize,
scrollTo: (offset) => ref.scrollTo(offset),
+ scrollToEnd: () => {
+ const scroller = getScroller();
+ if (scroller) scroller.scrollTop = scroller.scrollHeight;
+ },
scrollToIndex: (index, options) => ref.scrollToIndex(index + LEADING_ROWS, options),
});
@@ -269,7 +347,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
return () => {
registerVirtuaScrollMethods(null);
};
- }, [registerVirtuaScrollMethods, setActiveIndex]);
+ }, [getScroller, registerVirtuaScrollMethods, setActiveIndex]);
// Cleanup on unmount
useEffect(() => {
@@ -314,7 +392,6 @@ const VirtualizedList = memo<VirtualizedListProps>(
}, [dataSource, streamingIndices, selectionMessageIds]);
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
- const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
// The ChatInput's floating overlay (TodoProgress + QueueTray) covers the
// bottom of this scroll viewport like a layer. Extend VList's internal
@@ -367,7 +444,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
ref={containerRef}
style={{ height: '100%', position: 'relative' }}
onKeyDownCapture={handleKeyDown}
- onPointerDownCapture={markUserScrollIntent}
+ onPointerDownCapture={handlePointerDown}
onPointerMoveCapture={handlePointerMove}
onTouchMoveCapture={handleTouchMove}
onTouchStartCapture={earlierHistory.onTouchStart}
@@ -383,6 +460,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
)}
<VList
bufferSize={typeof window !== 'undefined' ? window.innerHeight : 0}
+ className={VLIST_CLASS_NAME}
data={dataWithSlots}
keepMounted={keepMountedIndicesWithSlots}
ref={virtuaRef}
@@ -467,7 +545,7 @@ const VirtualizedList = memo<VirtualizedListProps>(
atBottom={atBottom}
bottomOffset={overlayHeight}
visible={!atBottom}
- onScrollToBottom={() => scrollToBottom(true)}
+ onScrollToBottom={handleBackBottom}
/>
</WideScreenContainer>
</div>
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
index 52564379773..0af75526c11 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.test.ts
@@ -9,7 +9,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { loadScrollSnapshot, saveScrollSnapshot } from '../utils/scrollSnapshotStore';
import { useTopicScrollPersist } from './useTopicScrollPersist';
+interface FakeScroller extends HTMLElement {
+ /** Fires the listeners the hook registered for `type` */
+ emit: (type: string) => void;
+ /** Records every `scrollTop` write made by the hook */
+ setScrollTop: ReturnType<typeof vi.fn<(value: number) => void>>;
+}
+
interface FakeVList {
+ scroller: FakeScroller;
scrollOffset: number;
scrollSize: number;
scrollTo: ReturnType<typeof vi.fn>;
@@ -17,14 +25,46 @@ interface FakeVList {
viewportSize: number;
}
-const createFakeVList = (overrides: Partial<FakeVList> = {}): FakeVList => ({
- scrollOffset: 0,
- scrollSize: 0,
- scrollTo: vi.fn(),
- scrollToIndex: vi.fn(),
- viewportSize: 800,
- ...overrides,
-});
+/** Scroll element whose `scrollHeight` mirrors virtua's `scrollSize` */
+const createFakeScroller = (handle: FakeVList): FakeScroller => {
+ const setScrollTop = vi.fn<(value: number) => void>();
+ const listeners = new Map<string, Set<() => void>>();
+ return {
+ addEventListener: (type: string, listener: () => void) => {
+ if (!listeners.has(type)) listeners.set(type, new Set());
+ listeners.get(type)!.add(listener);
+ },
+ emit: (type: string) => {
+ for (const listener of listeners.get(type) ?? []) listener();
+ },
+ removeEventListener: (type: string, listener: () => void) => {
+ listeners.get(type)?.delete(listener);
+ },
+ get scrollHeight() {
+ return handle.scrollSize;
+ },
+ get scrollTop() {
+ return handle.scrollOffset;
+ },
+ set scrollTop(value: number) {
+ setScrollTop(value);
+ },
+ setScrollTop,
+ } as unknown as FakeScroller;
+};
+
+const createFakeVList = (overrides: Partial<Omit<FakeVList, 'scroller'>> = {}): FakeVList => {
+ const handle = {
+ scrollOffset: 0,
+ scrollSize: 0,
+ scrollTo: vi.fn(),
+ scrollToIndex: vi.fn(),
+ viewportSize: 800,
+ ...overrides,
+ } as FakeVList;
+ handle.scroller = createFakeScroller(handle);
+ return handle;
+};
const refOf = (handle: FakeVList | null): RefObject<VListHandle | null> => ({
current: handle as unknown as VListHandle | null,
@@ -61,6 +101,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
headerOffset: 1,
messageDeepLink: {
displayMessageId: 'assistant-group',
@@ -76,7 +117,7 @@ describe('useTopicScrollPersist', () => {
await advanceFrames(4);
expect(handle.scrollToIndex).toHaveBeenCalledWith(13, { align: 'center' });
- expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalled();
expect(onHandled).toHaveBeenCalledTimes(1);
});
@@ -97,6 +138,7 @@ describe('useTopicScrollPersist', () => {
containerRef: { current: container },
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: 'assistant-group',
id: 'assistant-child',
@@ -134,6 +176,7 @@ describe('useTopicScrollPersist', () => {
containerRef: { current: container },
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: 'assistant-group',
id: 'assistant-child',
@@ -175,6 +218,7 @@ describe('useTopicScrollPersist', () => {
containerRef: { current: container },
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: 'assistant-group',
id: 'assistant-child',
@@ -209,6 +253,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
messageDeepLink: navigationKey
? {
displayMessageId: 'target',
@@ -229,7 +274,7 @@ describe('useTopicScrollPersist', () => {
await advanceFrames(6);
expect(handle.scrollToIndex).toHaveBeenCalledWith(8, { align: 'center' });
- expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalled();
});
it('handles another hash navigation within the same topic', async () => {
@@ -239,6 +284,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
messageDeepLink: {
displayMessageId: `message-${index}`,
id: `message-${index}`,
@@ -258,42 +304,116 @@ describe('useTopicScrollPersist', () => {
expect(handle.scrollToIndex).toHaveBeenNthCalledWith(2, 20, { align: 'center' });
});
- it('falls back to scrollToIndex(last, end) when there is no snapshot', async () => {
+ it('jumps to the end without a virtua imperative scroll when there is no snapshot', async () => {
+ // Regression: virtua's scrollToIndex re-applies its target on every item
+ // resize within 150ms, so a restore landing while a reply streamed kept
+ // pulling the user back to the bottom after they scrolled up.
const handle = createFakeVList({ scrollSize: 5000 });
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
- await advanceFrames(2);
+ await advanceFrames(4);
- expect(handle.scrollToIndex).toHaveBeenCalledTimes(1);
- expect(handle.scrollToIndex).toHaveBeenCalledWith(49, { align: 'end' });
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(5000);
+ expect(handle.scrollToIndex).not.toHaveBeenCalled();
expect(handle.scrollTo).not.toHaveBeenCalled();
});
- it('translates the restore target by headerOffset when a header slot row is present', async () => {
+ it('keeps jumping to the end until the measured height stops changing', async () => {
const handle = createFakeVList({ scrollSize: 5000 });
renderHook(() =>
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
- headerOffset: 1,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ // virtua measures the rows revealed by the first jump.
+ handle.scrollSize = 5600;
+ await advanceFrames(6);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenLastCalledWith(5600);
+ const writes = handle.scroller.setScrollTop.mock.calls.length;
+
+ await advanceFrames(6);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(writes);
+ });
+
+ it('keeps jumping while virtua takes several frames to grow the list', async () => {
+ // Regression: stopping after a single unchanged frame left a freshly
+ // opened topic short of the bottom once virtua re-rendered the
+ // measured rows a few frames later.
+ const handle = createFakeVList({ scrollSize: 5000 });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await advanceFrames(3);
+ handle.scrollSize = 7600;
+ await advanceFrames(12);
+
+ expect(handle.scroller.setScrollTop).toHaveBeenLastCalledWith(7600);
+ });
+
+ it('stops jumping once the user scrolls', async () => {
+ const handle = createFakeVList({ scrollSize: 5000 });
+ handle.scroller.setScrollTop.mockImplementation(() => {
+ handle.scrollSize += 50;
+ });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
await advanceFrames(2);
+ handle.scroller.emit('wheel');
+ await advanceFrames(1);
+ const writes = handle.scroller.setScrollTop.mock.calls.length;
- // Last message sits at virtua row 50 (header row 0 + 50 messages).
- expect(handle.scrollToIndex).toHaveBeenCalledTimes(1);
- expect(handle.scrollToIndex).toHaveBeenCalledWith(50, { align: 'end' });
+ await advanceFrames(10);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(writes);
});
- it('falls back to scrollToIndex(last, end) when snapshot.atBottom is true', async () => {
+ it('stops jumping after the time cap while a streaming reply keeps growing', async () => {
+ const handle = createFakeVList({ scrollSize: 5000 });
+ handle.scroller.setScrollTop.mockImplementation(() => {
+ handle.scrollSize += 50;
+ });
+ renderHook(() =>
+ useTopicScrollPersist({
+ contextKey: 'main_agt_1_tpc_a',
+ dataSourceLength: 50,
+ getScroller: () => handle.scroller,
+ virtuaRef: refOf(handle),
+ }),
+ );
+
+ await vi.advanceTimersByTimeAsync(1200);
+ const writes = handle.scroller.setScrollTop.mock.calls.length;
+ expect(writes).toBeGreaterThan(1);
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(writes);
+ });
+
+ it('jumps to the end when snapshot.atBottom is true', async () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: true,
offset: 9999,
@@ -304,17 +424,18 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
- await advanceFrames(2);
+ await advanceFrames(4);
- expect(handle.scrollToIndex).toHaveBeenCalledWith(49, { align: 'end' });
- expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(5000);
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalledWith(9999);
});
- it('does not call scrollTo immediately when virtua scrollSize is too small', async () => {
+ it('does not write the saved offset immediately when virtua scrollSize is too small', async () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
@@ -325,6 +446,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -332,10 +454,10 @@ describe('useTopicScrollPersist', () => {
// 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();
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalled();
});
- it('calls scrollTo with the saved offset once virtua has measured enough', async () => {
+ it('writes the saved offset once virtua has measured enough', async () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 5000,
@@ -346,23 +468,26 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
await advanceFrames(3);
- expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(handle.scroller.setScrollTop).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);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(1);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(5000);
+ // Written directly so a streaming reply cannot keep re-applying it.
+ expect(handle.scrollTo).not.toHaveBeenCalled();
});
- it('gives up polling after the cap and calls scrollTo anyway', async () => {
+ it('gives up polling after the cap and writes the saved offset anyway', async () => {
saveScrollSnapshot('main_agt_1_tpc_a', {
atBottom: false,
offset: 999_999,
@@ -373,6 +498,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -380,8 +506,8 @@ describe('useTopicScrollPersist', () => {
// 30-frame cap + a few extra for the release rAFs.
await advanceFrames(40);
- expect(handle.scrollTo).toHaveBeenCalledTimes(1);
- expect(handle.scrollTo).toHaveBeenCalledWith(999_999);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledTimes(1);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(999_999);
});
it('converges the snapshot to the actual landing position after capping out', async () => {
@@ -392,7 +518,7 @@ describe('useTopicScrollPersist', () => {
});
const handle = createFakeVList({ scrollSize: 1500, viewportSize: 800 });
// Simulate virtua clamping the request to the actual scrollable range.
- handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scroller.setScrollTop.mockImplementation((offset: number) => {
handle.scrollOffset = Math.min(offset, handle.scrollSize - handle.viewportSize);
});
@@ -400,6 +526,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -421,7 +548,7 @@ describe('useTopicScrollPersist', () => {
savedAt: originalSavedAt,
});
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
- handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scroller.setScrollTop.mockImplementation((offset: number) => {
handle.scrollOffset = offset;
});
@@ -429,6 +556,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -453,19 +581,20 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: length,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
{ initialProps: { length: 0 } },
);
await advanceFrames(3);
- expect(handle.scrollTo).not.toHaveBeenCalled();
+ expect(handle.scroller.setScrollTop).not.toHaveBeenCalled();
expect(handle.scrollToIndex).not.toHaveBeenCalled();
rerender({ length: 50 });
await advanceFrames(3);
- expect(handle.scrollTo).toHaveBeenCalledWith(5000);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(5000);
});
});
@@ -479,6 +608,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -509,6 +639,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -535,7 +666,7 @@ describe('useTopicScrollPersist', () => {
savedAt: fixedNow,
});
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
- handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scroller.setScrollTop.mockImplementation((offset: number) => {
handle.scrollOffset = offset;
});
@@ -544,12 +675,14 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey,
dataSourceLength: length,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
{ initialProps: { contextKey: 'main_agt_1_tpc_a', length: 50 } },
);
- await advanceFrames(4);
+ // The bottom restore settles after its 150ms quiet window.
+ await advanceFrames(10);
act(() => {
result.current.recordScroll(1200, false);
});
@@ -562,7 +695,7 @@ describe('useTopicScrollPersist', () => {
const persistedA = loadScrollSnapshot('main_agt_1_tpc_a');
expect(persistedA?.offset).toBe(1200);
expect(persistedA?.savedAt).toBe(fixedNow + 60_000);
- expect(handle.scrollTo).toHaveBeenCalledWith(3000);
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(3000);
});
it('falls back to the bottom when the new topic has no snapshot', async () => {
@@ -573,18 +706,20 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey,
dataSourceLength: length,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
{ initialProps: { contextKey: 'main_agt_1_tpc_a', length: 50 } },
);
await advanceFrames(4);
- handle.scrollToIndex.mockClear();
+ handle.scroller.setScrollTop.mockClear();
+ handle.scrollSize = 4000;
rerender({ contextKey: 'main_agt_1_tpc_b', length: 30 });
await advanceFrames(4);
- expect(handle.scrollToIndex).toHaveBeenCalledWith(29, { align: 'end' });
+ expect(handle.scroller.setScrollTop).toHaveBeenCalledWith(4000);
});
});
@@ -598,12 +733,13 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
// Initial restore (no snapshot) settles, then the user scrolls up.
- await advanceFrames(2);
+ await advanceFrames(10);
act(() => {
result.current.recordScroll(2000, false);
});
@@ -632,7 +768,7 @@ describe('useTopicScrollPersist', () => {
savedAt: fixedNow,
});
const handle = createFakeVList({ scrollSize: 6000, viewportSize: 800 });
- handle.scrollTo.mockImplementation((offset: number) => {
+ handle.scroller.setScrollTop.mockImplementation((offset: number) => {
handle.scrollOffset = offset;
});
@@ -640,6 +776,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_a',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
@@ -664,6 +801,7 @@ describe('useTopicScrollPersist', () => {
useTopicScrollPersist({
contextKey: 'main_agt_1_tpc_empty',
dataSourceLength: 50,
+ getScroller: () => handle.scroller,
virtuaRef: refOf(handle),
}),
);
diff --git a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
index 0ad2f5b32ed..5d087fc57d7 100644
--- a/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
+++ b/src/features/Conversation/ChatList/hooks/useTopicScrollPersist.ts
@@ -18,6 +18,13 @@ const DEEP_LINK_RETRY_MS = 16;
// 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;
+// The bottom restore keeps jumping until the list height has been stable this
+// long β€” virtua's own settle window for imperative scrolls, since measuring a
+// row and re-rendering the list can take more than one frame.
+const BOTTOM_SETTLE_QUIET_MS = 150;
+// Upper bound while a streaming reply keeps growing; auto-scroll follows after.
+const BOTTOM_SETTLE_MAX_MS = 1000;
+const USER_SCROLL_INPUT_EVENTS = ['keydown', 'pointerdown', 'touchstart', 'wheel'] as const;
interface PendingWrite {
atBottom: boolean;
@@ -29,10 +36,18 @@ interface UseTopicScrollPersistOptions {
containerRef?: RefObject<HTMLDivElement | null>;
contextKey: string;
dataSourceLength: number;
+ /**
+ * Returns the VList scroll element. Snapshot and bottom restores write its
+ * `scrollTop` directly: virtua's `scrollTo` / `scrollToIndex` keep
+ * re-applying their target on every item resize within 150ms, so a restore
+ * that lands while a reply is streaming would pin the viewport and override
+ * the user's own scrolling until the stream ends.
+ */
+ getScroller: () => HTMLElement | null;
/**
* Number of synthetic rows prepended to the VList before the messages
- * (e.g. the headerSlot spacer). Added when targeting the last message so
- * scrollToIndex lands on the right virtua row.
+ * (e.g. the headerSlot spacer). Added when targeting a deep-linked message
+ * so scrollToIndex lands on the right virtua row.
*/
headerOffset?: number;
messageDeepLink?: ResolvedMessageDeepLink;
@@ -91,6 +106,7 @@ export const useTopicScrollPersist = ({
containerRef,
contextKey,
dataSourceLength,
+ getScroller,
headerOffset = 0,
messageDeepLink,
virtuaRef,
@@ -304,8 +320,60 @@ export const useTopicScrollPersist = ({
const targetOffset = snapshot && !snapshot.atBottom ? snapshot.offset : null;
if (targetOffset === null) {
- virtuaRef.current.scrollToIndex(headerOffset + dataSourceLength - 1, { align: 'end' });
- finalize(false);
+ const scroller = getScroller();
+ if (!scroller) {
+ restoringRef.current = false;
+ return;
+ }
+
+ // Jump to the end every frame until the list height stops changing, so
+ // rows that virtua measures after the first jump still end up in view.
+ // Any user scroll input ends it at once, and the time cap bounds it while
+ // a streaming reply keeps growing; streaming auto-scroll follows after.
+ let interrupted = false;
+ const interrupt = () => {
+ interrupted = true;
+ };
+ for (const type of USER_SCROLL_INPUT_EVENTS) {
+ scroller.addEventListener(type, interrupt, { passive: true });
+ }
+ const stopListening = () => {
+ for (const type of USER_SCROLL_INPUT_EVENTS) {
+ scroller.removeEventListener(type, interrupt);
+ }
+ };
+
+ const startedAt = Date.now();
+ let lastChangeAt = startedAt;
+ let lastScrollHeight = -1;
+ const settleAtBottom = () => {
+ if (restoreSequenceRef.current !== restoreSequence) {
+ stopListening();
+ return;
+ }
+ if (interrupted) {
+ stopListening();
+ finalize(false);
+ return;
+ }
+
+ scroller.scrollTop = scroller.scrollHeight;
+ const now = Date.now();
+ if (scroller.scrollHeight !== lastScrollHeight) {
+ lastScrollHeight = scroller.scrollHeight;
+ lastChangeAt = now;
+ }
+ if (
+ now - lastChangeAt >= BOTTOM_SETTLE_QUIET_MS ||
+ now - startedAt >= BOTTOM_SETTLE_MAX_MS
+ ) {
+ stopListening();
+ finalize(false);
+ return;
+ }
+ requestAnimationFrame(settleAtBottom);
+ };
+ settleAtBottom();
return;
}
@@ -326,7 +394,8 @@ export const useTopicScrollPersist = ({
const required = targetOffset + ref.viewportSize;
const cappedOut = attempts >= RESTORE_MAX_FRAMES;
if (ref.scrollSize >= required || cappedOut) {
- ref.scrollTo(targetOffset);
+ const scroller = getScroller();
+ if (scroller) scroller.scrollTop = targetOffset;
finalize(cappedOut);
return;
}
@@ -339,6 +408,7 @@ export const useTopicScrollPersist = ({
contextKey,
dataSourceLength,
flushNow,
+ getScroller,
headerOffset,
messageDeepLink,
virtuaRef,
diff --git a/src/features/Conversation/ChatList/utils/autoScrollFollow.test.ts b/src/features/Conversation/ChatList/utils/autoScrollFollow.test.ts
new file mode 100644
index 00000000000..923a8a5c7b6
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/autoScrollFollow.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest';
+
+import { AT_BOTTOM_THRESHOLD } from '../components/AutoScroll/const';
+import { AUTO_SCROLL_REATTACH_THRESHOLD, resolveAutoScrollDetached } from './autoScrollFollow';
+
+describe('resolveAutoScrollDetached', () => {
+ it('detaches when the user scrolls up while still inside the atBottom band', () => {
+ // Regression: a short wheel-up (< AT_BOTTOM_THRESHOLD) used to keep
+ // auto-scroll engaged, so the next streaming chunk snapped back down.
+ const distanceToBottom = 100;
+ expect(distanceToBottom).toBeLessThan(AT_BOTTOM_THRESHOLD);
+
+ expect(
+ resolveAutoScrollDetached({
+ detached: false,
+ distanceToBottom,
+ hasActiveScrollInput: true,
+ offset: 900,
+ prevOffset: 1000,
+ }),
+ ).toBe(true);
+ });
+
+ it('stays attached when the offset is clamped up at the real bottom', () => {
+ // Collapsing a block near the bottom shrinks the content and pulls the
+ // offset up without the user leaving the bottom.
+ expect(
+ resolveAutoScrollDetached({
+ detached: false,
+ distanceToBottom: 0,
+ hasActiveScrollInput: true,
+ offset: 800,
+ prevOffset: 1000,
+ }),
+ ).toBe(false);
+ });
+
+ it('detaches on a small upward user scroll inside the re-attach band', () => {
+ expect(
+ resolveAutoScrollDetached({
+ detached: false,
+ distanceToBottom: 20,
+ hasActiveScrollInput: true,
+ offset: 980,
+ prevOffset: 1000,
+ }),
+ ).toBe(true);
+ });
+
+ it('re-attaches when the user scrolls down into the re-attach band', () => {
+ expect(
+ resolveAutoScrollDetached({
+ detached: true,
+ distanceToBottom: AUTO_SCROLL_REATTACH_THRESHOLD - 4,
+ hasActiveScrollInput: true,
+ offset: 1000,
+ prevOffset: 900,
+ }),
+ ).toBe(false);
+ });
+
+ it('stays detached while the user scrolls down but has not reached the real bottom', () => {
+ expect(
+ resolveAutoScrollDetached({
+ detached: true,
+ distanceToBottom: AUTO_SCROLL_REATTACH_THRESHOLD + 50,
+ hasActiveScrollInput: true,
+ offset: 950,
+ prevOffset: 900,
+ }),
+ ).toBe(true);
+ });
+
+ it('re-attaches once the viewport reaches the real bottom', () => {
+ expect(
+ resolveAutoScrollDetached({
+ detached: true,
+ distanceToBottom: 0,
+ hasActiveScrollInput: false,
+ offset: 1200,
+ prevOffset: 900,
+ }),
+ ).toBe(false);
+ });
+
+ it('ignores upward offset changes without active scroll input', () => {
+ expect(
+ resolveAutoScrollDetached({
+ detached: false,
+ distanceToBottom: 120,
+ hasActiveScrollInput: false,
+ offset: 900,
+ prevOffset: 1000,
+ }),
+ ).toBe(false);
+ });
+
+ it('keeps the state when there is no previous offset', () => {
+ expect(
+ resolveAutoScrollDetached({
+ detached: true,
+ distanceToBottom: 200,
+ hasActiveScrollInput: true,
+ offset: 900,
+ prevOffset: null,
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/src/features/Conversation/ChatList/utils/autoScrollFollow.ts b/src/features/Conversation/ChatList/utils/autoScrollFollow.ts
new file mode 100644
index 00000000000..251e3222eaa
--- /dev/null
+++ b/src/features/Conversation/ChatList/utils/autoScrollFollow.ts
@@ -0,0 +1,55 @@
+/**
+ * Distance (px) from the real bottom within which a scroll re-attaches
+ * streaming auto-scroll. Kept far tighter than `AT_BOTTOM_THRESHOLD` so a user
+ * reading a few lines above the bottom is not grabbed back by the next chunk.
+ */
+export const AUTO_SCROLL_REATTACH_THRESHOLD = 24;
+
+/**
+ * Sub-pixel slack for "the viewport sits on the real bottom". A user scroll-up
+ * always leaves at least its own delta below the viewport, so an upward move
+ * that still ends here can only be the browser clamping the offset after the
+ * content shrank (e.g. collapsing a block near the bottom).
+ */
+const AT_REAL_BOTTOM_EPSILON = 1;
+
+interface ResolveAutoScrollDetachedParams {
+ /** Current detached state */
+ detached: boolean;
+ /** Remaining distance between the viewport bottom and the content bottom */
+ distanceToBottom: number;
+ /** Whether a wheel / scroll key / touch move / pointer drag happened just before this scroll */
+ hasActiveScrollInput: boolean;
+ /** Scroll offset after this scroll event */
+ offset: number;
+ /** Scroll offset of the previous scroll event, `null` when unknown */
+ prevOffset: number | null;
+}
+
+/**
+ * Decide whether streaming auto-scroll should stay detached after a scroll event.
+ *
+ * - Sitting on the real bottom always stays attached, including an upward
+ * offset clamp caused by content shrinking there.
+ * - A user-initiated upward scroll detaches, even inside the `atBottom` band
+ * and even by a few pixels.
+ * - Reaching the bottom again (by the user, BackBottom, or auto-scroll itself)
+ * re-attaches.
+ * - Anything else keeps the current state, so content growth or programmatic
+ * corrections never flip it.
+ */
+export const resolveAutoScrollDetached = ({
+ detached,
+ distanceToBottom,
+ hasActiveScrollInput,
+ offset,
+ prevOffset,
+}: ResolveAutoScrollDetachedParams): boolean => {
+ if (distanceToBottom <= AT_REAL_BOTTOM_EPSILON) return false;
+
+ if (hasActiveScrollInput && prevOffset !== null && offset < prevOffset) return true;
+
+ if (distanceToBottom <= AUTO_SCROLL_REATTACH_THRESHOLD) return false;
+
+ return detached;
+};
diff --git a/src/features/Conversation/ConversationProvider.test.tsx b/src/features/Conversation/ConversationProvider.test.tsx
index bf4a93e1ce7..12ca9fc6567 100644
--- a/src/features/Conversation/ConversationProvider.test.tsx
+++ b/src/features/Conversation/ConversationProvider.test.tsx
@@ -225,11 +225,13 @@ describe('ConversationProvider', () => {
const fakeScrollMethods = {
getItemOffset: vi.fn(),
getItemSize: vi.fn(),
+ getScrollElement: vi.fn(() => null),
getScrollOffset: vi.fn(),
getScrollSize: vi.fn(),
getTotalCount: vi.fn(),
getViewportSize: vi.fn(),
scrollTo: vi.fn(),
+ scrollToEnd: vi.fn(),
scrollToIndex: vi.fn(),
};
@@ -237,6 +239,7 @@ describe('ConversationProvider', () => {
api!.setState({
activeIndex: 3,
atBottom: false,
+ autoScrollDetached: true,
chatInputOverlayHeight: 48,
editor: fakeEditor,
heteroOverloadRetryAttempts: { msg_old: 2 },
@@ -273,6 +276,7 @@ describe('ConversationProvider', () => {
expect(state.scheduledSendAt).toBeUndefined();
expect(state.activeIndex).toBeNull();
expect(state.atBottom).toBe(true);
+ expect(state.autoScrollDetached).toBe(false);
expect(state.isScrolling).toBe(false);
expect(state.visibleItems.size).toBe(0);
diff --git a/src/features/Conversation/store/initialState.ts b/src/features/Conversation/store/initialState.ts
index d29634ce15e..aaa086e704e 100644
--- a/src/features/Conversation/store/initialState.ts
+++ b/src/features/Conversation/store/initialState.ts
@@ -87,6 +87,7 @@ export const initialState: State = {
export const createEphemeralResetState = (): Partial<State> => ({
activeIndex: null,
atBottom: true,
+ autoScrollDetached: false,
earlierMessagesError: undefined,
heteroOverloadRetryAttempts: {},
heteroOverloadWaitOpIds: {},
diff --git a/src/features/Conversation/store/slices/virtuaList/action.test.ts b/src/features/Conversation/store/slices/virtuaList/action.test.ts
new file mode 100644
index 00000000000..f62bee2b845
--- /dev/null
+++ b/src/features/Conversation/store/slices/virtuaList/action.test.ts
@@ -0,0 +1,64 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { act } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createStore } from '../../index';
+import { type VirtuaScrollMethods } from './initialState';
+
+vi.mock('@lobechat/conversation-flow', () => ({
+ parse: (messages: UIChatMessage[]) => ({
+ flatList: messages,
+ messageMap: Object.fromEntries(messages.map((m) => [m.id, m])),
+ }),
+}));
+
+const messages = [
+ { content: 'hi', createdAt: 1, id: 'u1', role: 'user', updatedAt: 1 },
+ { content: 'hello', createdAt: 2, id: 'a1', role: 'assistant', updatedAt: 2 },
+] as UIChatMessage[];
+
+const createScrollMethods = (): VirtuaScrollMethods => ({
+ getItemOffset: vi.fn(),
+ getItemSize: vi.fn(),
+ getScrollElement: vi.fn(() => null),
+ getScrollOffset: vi.fn(),
+ getScrollSize: vi.fn(),
+ getTotalCount: vi.fn(() => 2),
+ getViewportSize: vi.fn(),
+ scrollTo: vi.fn(),
+ scrollToEnd: vi.fn(),
+ scrollToIndex: vi.fn(),
+});
+
+const createStoreWithMethods = () => {
+ const store = createStore({ context: { agentId: 'agent', threadId: null, topicId: null } });
+ const methods = createScrollMethods();
+ act(() => {
+ store.getState().replaceMessages(messages);
+ store.getState().registerVirtuaScrollMethods(methods);
+ });
+ return { methods, store };
+};
+
+describe('scrollToBottom', () => {
+ it('follows streaming with a one-shot jump instead of a virtua imperative scroll', () => {
+ // Regression: virtua's scrollToIndex re-applies its target on every item
+ // resize within 150ms, so streaming kept pulling a user who scrolled up
+ // back to the bottom.
+ const { methods, store } = createStoreWithMethods();
+
+ store.getState().scrollToBottom(false);
+
+ expect(methods.scrollToEnd).toHaveBeenCalledTimes(1);
+ expect(methods.scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('keeps the smooth BackBottom scroll on virtua', () => {
+ const { methods, store } = createStoreWithMethods();
+
+ store.getState().scrollToBottom(true);
+
+ expect(methods.scrollToIndex).toHaveBeenCalledWith(1, { align: 'end', smooth: true });
+ expect(methods.scrollToEnd).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/store/slices/virtuaList/action.ts b/src/features/Conversation/store/slices/virtuaList/action.ts
index 3db851bc5fe..ecff9cddaa5 100644
--- a/src/features/Conversation/store/slices/virtuaList/action.ts
+++ b/src/features/Conversation/store/slices/virtuaList/action.ts
@@ -38,9 +38,13 @@ export interface VirtuaListAction {
setActiveIndex: (index: number | null) => void;
/**
- * Update scroll state (atBottom, isScrolling)
+ * Update scroll state (atBottom, autoScrollDetached, isScrolling)
*/
- setScrollState: (state: { atBottom?: boolean; isScrolling?: boolean }) => void;
+ setScrollState: (state: {
+ atBottom?: boolean;
+ autoScrollDetached?: boolean;
+ isScrolling?: boolean;
+ }) => void;
/**
* Upsert visible item metrics and recalculate active index
@@ -102,6 +106,11 @@ export const virtuaListSlice: StateCreator<State & VirtuaListAction, [], [], Vir
if (displayMessages.length === 0) return;
if (!virtuaScrollMethods) return;
+ if (!smooth) {
+ virtuaScrollMethods.scrollToEnd();
+ return;
+ }
+
// Target the true last item rather than the last message β€” VList may
// append trailing items (spacer, SubAgent footer hint) that would
// otherwise be left below the viewport and keep atBottom = false.
diff --git a/src/features/Conversation/store/slices/virtuaList/initialState.ts b/src/features/Conversation/store/slices/virtuaList/initialState.ts
index 61296d970f4..3553b921b1d 100644
--- a/src/features/Conversation/store/slices/virtuaList/initialState.ts
+++ b/src/features/Conversation/store/slices/virtuaList/initialState.ts
@@ -8,6 +8,8 @@
export interface VirtuaScrollMethods {
getItemOffset: (index: number) => number;
getItemSize: (index: number) => number;
+ /** The VList scroll element, `null` before it mounts */
+ getScrollElement: () => HTMLElement | null;
getScrollOffset: () => number;
getScrollSize: () => number;
/**
@@ -20,6 +22,15 @@ export interface VirtuaScrollMethods {
getTotalCount: () => number;
getViewportSize: () => number;
scrollTo: (offset: number) => void;
+ /**
+ * One-shot jump to the end by writing the scroller's `scrollTop` directly.
+ *
+ * Streaming auto-scroll must not use `scrollToIndex`: virtua keeps an
+ * imperative scroll alive and re-applies its target on every item resize
+ * that lands within 150ms, so while the reply keeps growing it pins the
+ * viewport to the bottom and overrides the user's own wheel/touch scroll.
+ */
+ scrollToEnd: () => void;
scrollToIndex: (
index: number,
options?: { align?: 'start' | 'center' | 'end'; smooth?: boolean },
@@ -46,6 +57,14 @@ export interface VirtuaListState {
*/
atBottom: boolean;
+ /**
+ * Whether the user scrolled away from the bottom on purpose. While set,
+ * streaming output no longer pulls the viewport down, even when the user is
+ * still inside the `atBottom` threshold band. Cleared when the viewport
+ * reaches the real bottom again, on send, or on context switch.
+ */
+ autoScrollDetached: boolean;
+
/**
* Whether the list is currently scrolling
*/
@@ -65,6 +84,7 @@ export interface VirtuaListState {
export const virtuaListInitialState: VirtuaListState = {
activeIndex: null,
atBottom: true,
+ autoScrollDetached: false,
isScrolling: false,
virtuaScrollMethods: null,
visibleItems: new Map(),
diff --git a/src/features/Conversation/store/slices/virtuaList/selectors.ts b/src/features/Conversation/store/slices/virtuaList/selectors.ts
index 054ae15d20f..a72bd9201d8 100644
--- a/src/features/Conversation/store/slices/virtuaList/selectors.ts
+++ b/src/features/Conversation/store/slices/virtuaList/selectors.ts
@@ -1,6 +1,7 @@
import { type State } from '../../initialState';
const atBottom = (s: State) => s.atBottom;
+const autoScrollDetached = (s: State) => s.autoScrollDetached;
const isScrolling = (s: State) => s.isScrolling;
const activeIndex = (s: State) => s.activeIndex;
const visibleItems = (s: State) => s.visibleItems;
@@ -9,6 +10,7 @@ const virtuaScrollMethods = (s: State) => s.virtuaScrollMethods;
export const virtuaListSelectors = {
activeIndex,
atBottom,
+ autoScrollDetached,
isScrolling,
virtuaScrollMethods,
visibleItems,