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 repinning after manual scroll (#14099)

Inneifa0ec62d71a1
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 9b3980dbe37..86dbc725f10 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -38,8 +38,10 @@ interface VirtualizedListProps {
*/
const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent }) => {
const virtuaRef = useRef<VListHandle>(null);
+ const didInitialScrollRef = useRef(false);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const {
+ cancelPinMessageIndex,
handleScrollOffset,
isSpacerMessage,
listData,
@@ -68,7 +70,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
const viewportSize = ref.viewportSize;
return scrollSize - scrollOffset - viewportSize <= AT_BOTTOM_THRESHOLD;
- }, [AT_BOTTOM_THRESHOLD]);
+ }, []);
// Handle scroll events
const handleScroll = useCallback(() => {
@@ -183,6 +185,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
// Auto scroll to user message when user sends a new message
// Only scroll when 2 new messages are added and second-to-last is from user
useScrollToUserMessage({
+ cancelPinMessageIndex,
dataSourceLength: dataSource.length,
isSecondLastMessageFromUser,
scrollShrinking,
@@ -193,10 +196,11 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
// Scroll to bottom on initial render
useEffect(() => {
- if (virtuaRef.current && dataSource.length > 0) {
- virtuaRef.current.scrollToIndex(dataSource.length - 1, { align: 'end' });
- }
- }, []);
+ if (didInitialScrollRef.current || !virtuaRef.current || dataSource.length === 0) return;
+
+ virtuaRef.current.scrollToIndex(dataSource.length - 1, { align: 'end' });
+ didInitialScrollRef.current = true;
+ }, [dataSource.length]);
const atBottom = useConversationStore(virtuaListSelectors.atBottom);
const scrollToBottom = useConversationStore((s) => s.scrollToBottom);
diff --git a/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts b/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts
index 2bc8834a4ba..f53a3d8f716 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { calculateConversationSpacerHeight, CONVERSATION_SPACER_ID } from './useConversationSpacer';
+import {
+ calculateConversationSpacerHeight,
+ CONVERSATION_SPACER_ID,
+ getConversationSpacerScrollEffect,
+} from './useConversationSpacer';
describe('useConversationSpacer helpers', () => {
it('should calculate the remaining spacer height behind the latest assistant message', () => {
@@ -14,4 +18,32 @@ describe('useConversationSpacer helpers', () => {
it('should keep the reserved spacer id stable', () => {
expect(CONVERSATION_SPACER_ID).toBe('__conversation_spacer__');
});
+
+ it('should cancel pin retries without shrinking the spacer while AI is still streaming', () => {
+ expect(
+ getConversationSpacerScrollEffect({
+ delta: -24,
+ hasPrevOffset: true,
+ isAIGenerating: true,
+ isMounted: true,
+ }),
+ ).toEqual({
+ cancelPin: true,
+ shrinkSpacer: false,
+ });
+ });
+
+ it('should both cancel pin retries and shrink the spacer after streaming stops', () => {
+ expect(
+ getConversationSpacerScrollEffect({
+ delta: -24,
+ hasPrevOffset: true,
+ isAIGenerating: false,
+ isMounted: true,
+ }),
+ ).toEqual({
+ cancelPin: true,
+ shrinkSpacer: true,
+ });
+ });
});
diff --git a/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts b/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
index 67a788e825a..edd9e94206b 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
@@ -12,6 +12,27 @@ export const calculateConversationSpacerHeight = (
assistantHeight: number,
) => Math.max(Math.round(viewportHeight - userHeight - assistantHeight), 0);
+interface ConversationSpacerScrollEffectOptions {
+ delta: number;
+ hasPrevOffset: boolean;
+ isAIGenerating: boolean;
+ isMounted: boolean;
+}
+
+export const getConversationSpacerScrollEffect = ({
+ delta,
+ hasPrevOffset,
+ isAIGenerating,
+ isMounted,
+}: ConversationSpacerScrollEffectOptions) => {
+ const cancelPin = isMounted && hasPrevOffset && delta < 0;
+
+ return {
+ cancelPin,
+ shrinkSpacer: cancelPin && !isAIGenerating,
+ };
+};
+
const getMessageElement = (messageId: string | null) => {
if (!messageId) return null;
@@ -40,12 +61,14 @@ export const useConversationSpacer = (dataSource: string[]) => {
const isAIGenerating = useConversationStore(messageStateSelectors.isAIGenerating);
const getItemOffset = useConversationStore((s) => s.virtuaScrollMethods?.getItemOffset);
const getItemSize = useConversationStore((s) => s.virtuaScrollMethods?.getItemSize);
+ const getScrollOffset = useConversationStore((s) => s.virtuaScrollMethods?.getScrollOffset);
const getViewportSize = useConversationStore((s) => s.virtuaScrollMethods?.getViewportSize);
const [naturalHeight, setNaturalHeight] = useState(0);
const [scrollReduction, setScrollReduction] = useState(0);
const [mounted, setMounted] = useState(false);
const [spacerLayoutVersion, setSpacerLayoutVersion] = useState(0);
+ const [cancelPinMessageIndex, setCancelPinMessageIndex] = useState<number | null>(null);
const prevLengthRef = useRef(dataSource.length);
const removeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -153,18 +176,28 @@ export const useConversationSpacer = (dataSource: string[]) => {
// Reset prev scroll offset when generation state changes to avoid stale deltas
useEffect(() => {
- prevScrollOffsetRef.current = null;
- }, [isAIGenerating]);
+ prevScrollOffsetRef.current = getScrollOffset?.() ?? null;
+ }, [getScrollOffset, isAIGenerating]);
// Stable scroll handler for shrinking spacer on scroll-up when not streaming
const handleScrollOffset = useCallback((currentScrollOffset: number) => {
const prevOffset = prevScrollOffsetRef.current;
prevScrollOffsetRef.current = currentScrollOffset;
- if (!mountedRef.current || isAIGeneratingRef.current || prevOffset === null) return;
+ const delta = prevOffset === null ? 0 : currentScrollOffset - prevOffset;
+ const { cancelPin, shrinkSpacer } = getConversationSpacerScrollEffect({
+ delta,
+ hasPrevOffset: prevOffset !== null,
+ isAIGenerating: isAIGeneratingRef.current,
+ isMounted: mountedRef.current,
+ });
+
+ if (!cancelPin) return;
- const delta = currentScrollOffset - prevOffset;
- if (delta >= 0) return;
+ if (userMessageIndexRef.current !== null) {
+ setCancelPinMessageIndex(userMessageIndexRef.current);
+ }
+ if (!shrinkSpacer) return;
setScrollReduction((prev) => prev + Math.abs(delta));
@@ -222,15 +255,16 @@ export const useConversationSpacer = (dataSource: string[]) => {
if (newMessageCount !== 2 || userMessage?.role !== 'user' || !assistantMessage) return;
+ setCancelPinMessageIndex(null);
setScrollReduction(0);
- prevScrollOffsetRef.current = null;
+ prevScrollOffsetRef.current = getScrollOffset?.() ?? null;
userMessageIndexRef.current = dataSource.length - 2;
assistantMessageIndexRef.current = dataSource.length - 1;
requestAnimationFrame(() => {
updateSpacerHeight();
});
- }, [dataSource.length, displayMessages, updateSpacerHeight]);
+ }, [dataSource.length, displayMessages, getScrollOffset, updateSpacerHeight]);
useEffect(() => {
const { assistantId, userId } = getTrackedMessages();
@@ -278,6 +312,7 @@ export const useConversationSpacer = (dataSource: string[]) => {
isSpacerMessage: (id: string) => id === CONVERSATION_SPACER_ID,
listData,
registerSpacerNode,
+ cancelPinMessageIndex,
scrollShrinking: isScrollShrinking,
spacerActive: mounted,
spacerHeight: renderedHeight,
diff --git a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
index 51c291184bf..750d498af2c 100644
--- a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useScrollToUserMessage } from './useScrollToUserMessage';
type Props = {
+ cancelPinMessageIndex?: number | null;
dataSourceLength: number;
isSecondLastMessageFromUser: boolean;
scrollShrinking?: boolean;
@@ -15,6 +16,7 @@ const makeRender = (scrollToIndex: ReturnType<typeof vi.fn> | null, initialProps
renderHook(
(props: Props) =>
useScrollToUserMessage({
+ cancelPinMessageIndex: props.cancelPinMessageIndex,
dataSourceLength: props.dataSourceLength,
isSecondLastMessageFromUser: props.isSecondLastMessageFromUser,
scrollShrinking: props.scrollShrinking,
@@ -301,6 +303,78 @@ describe('useScrollToUserMessage', () => {
expect(scrollToIndex).not.toHaveBeenCalled();
});
+ it('should stop pinning when user scrolls up during streaming without shrinking the spacer', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ dataSourceLength: 2,
+ isSecondLastMessageFromUser: false,
+ spacerActive: false,
+ spacerLayoutVersion: 0,
+ });
+
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 1,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+ scrollToIndex.mockClear();
+
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ cancelPinMessageIndex: 2,
+ spacerActive: true,
+ spacerLayoutVersion: 1,
+ });
+
+ rerender({
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ cancelPinMessageIndex: 2,
+ spacerActive: true,
+ spacerLayoutVersion: 2,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('should preserve a fresh pin when the cancellation index belongs to the previous turn', () => {
+ const scrollToIndex = vi.fn();
+
+ const { rerender } = makeRender(scrollToIndex, {
+ cancelPinMessageIndex: 2,
+ dataSourceLength: 4,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ rerender({
+ cancelPinMessageIndex: 2,
+ dataSourceLength: 6,
+ isSecondLastMessageFromUser: true,
+ spacerActive: true,
+ spacerLayoutVersion: 0,
+ });
+
+ act(() => {
+ vi.runAllTimers();
+ });
+
+ expect(scrollToIndex).toHaveBeenCalledTimes(3);
+ expect(scrollToIndex).toHaveBeenNthCalledWith(1, 4, { align: 'start', smooth: true });
+ });
+
it('should scroll without spacer when spacer never mounts (content fills viewport)', () => {
const scrollToIndex = vi.fn();
diff --git a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
index 644809ccb80..7369a6e25ce 100644
--- a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
+++ b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
@@ -3,6 +3,11 @@ import { useCallback, useEffect, useRef } from 'react';
const PIN_RETRY_DELAYS = [0, 32, 96];
interface UseScrollToUserMessageOptions {
+ /**
+ * Message index whose pending pin should be canceled because the user
+ * manually scrolled up while that reply turn was still active.
+ */
+ cancelPinMessageIndex?: number | null;
/**
* Current data source length (number of messages)
*/
@@ -51,6 +56,7 @@ interface UseScrollToUserMessageOptions {
* or the user starts scrolling manually.
*/
export function useScrollToUserMessage({
+ cancelPinMessageIndex = null,
dataSourceLength,
isSecondLastMessageFromUser,
scrollToIndex,
@@ -116,18 +122,24 @@ export function useScrollToUserMessage({
// fired just before the user scrolled up would still call scrollToIndex at
// 32/96ms and yank the viewport back down.
useEffect(() => {
- if (!spacerActive || scrollShrinking) {
+ const pendingScrollIndex = pendingScrollIndexRef.current;
+ const pinCanceledByUserScroll =
+ pendingScrollIndex !== null && cancelPinMessageIndex === pendingScrollIndex;
+
+ if (!spacerActive || scrollShrinking || pinCanceledByUserScroll) {
pendingScrollIndexRef.current = null;
clearPendingPins();
}
- }, [spacerActive, scrollShrinking, clearPendingPins]);
+ }, [cancelPinMessageIndex, spacerActive, scrollShrinking, clearPendingPins]);
// Re-scroll whenever the spacer's real layout settles (version bumps) or the
// spacer becomes active. Skip when user is manually shrinking the spacer.
useEffect(() => {
- if (!spacerActive || scrollShrinking) return;
const index = pendingScrollIndexRef.current;
+ const pinCanceledByUserScroll = index !== null && cancelPinMessageIndex === index;
+
+ if (!spacerActive || scrollShrinking || pinCanceledByUserScroll) return;
if (index === null) return;
executeScroll(index);
- }, [spacerActive, spacerLayoutVersion, scrollShrinking, executeScroll]);
+ }, [cancelPinMessageIndex, spacerActive, spacerLayoutVersion, scrollShrinking, executeScroll]);
}