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): prevent synthetic scroll from shrinking spacer (#14584)

Innei217afcf1af9d
diff --git a/e2e/src/features/journeys/agent/agent-scroll.feature b/e2e/src/features/journeys/agent/agent-scroll.feature
index 56d72d4c01c..081e2c480e4 100644
--- a/e2e/src/features/journeys/agent/agent-scroll.feature
+++ b/e2e/src/features/journeys/agent/agent-scroll.feature
@@ -55,3 +55,16 @@ Feature: 发送消息与流式输出期间的视口滚动行为
And 等待流式响应结束
And 用户发送一条触发长文输出的消息
Then 用户消息应固定在聊天列表顶部
+
+ # Regression guard for the spacer-shrink issue: after streaming has ended,
+ # layout/virtual-list offset corrections can emit scroll events without any
+ # wheel, touch, keyboard, or pointer scroll input. Those synthetic negative
+ # offsets must not be treated as user scroll-up intent.
+ @AGENT-SCROLL-006 @P0 @journey
+ Scenario: 非用户触发的上移不应收缩底部补偿区域
+ Given 用户进入 Lobe AI 对话页面
+ When 用户完成一轮用于垫高列表的长回复对话
+ And 用户发送一条触发短回复的消息并等待回复完成
+ And 记录聊天列表底部补偿区域高度
+ And 模拟非用户触发的聊天列表上移 120 像素
+ Then 聊天列表底部补偿区域高度不应收缩
diff --git a/e2e/src/steps/agent/scroll.steps.ts b/e2e/src/steps/agent/scroll.steps.ts
index 620047bdcdc..83c7da7f1f7 100644
--- a/e2e/src/steps/agent/scroll.steps.ts
+++ b/e2e/src/steps/agent/scroll.steps.ts
@@ -22,6 +22,7 @@ const AT_BOTTOM_EPSILON = 320;
const MANUAL_SCROLL_UP_DELTA = 200;
interface ScrollSnapshot {
+ bottomCompensationHeight: number;
clientHeight: number;
distanceToBottom: number;
scrollHeight: number;
@@ -42,7 +43,18 @@ async function getScrollSnapshot(world: CustomWorld): Promise<ScrollSnapshot | n
while (el) {
const style = window.getComputedStyle(el);
if (style.overflowY === 'auto' || style.overflowY === 'scroll') {
+ const bottomCompensationHeight = Math.max(
+ 0,
+ ...Array.from(el.querySelectorAll<HTMLElement>('div[aria-hidden="true"]'))
+ .filter((node) => {
+ const nodeStyle = window.getComputedStyle(node);
+ return nodeStyle.pointerEvents === 'none' && node.offsetWidth > 0;
+ })
+ .map((node) => node.getBoundingClientRect().height),
+ );
+
return {
+ bottomCompensationHeight,
clientHeight: el.clientHeight,
distanceToBottom: el.scrollHeight - el.scrollTop - el.clientHeight,
scrollHeight: el.scrollHeight,
@@ -55,6 +67,41 @@ async function getScrollSnapshot(world: CustomWorld): Promise<ScrollSnapshot | n
});
}
+async function sendPrompt(world: CustomWorld, prompt: string, response: string): Promise<void> {
+ llmMockManager.setResponse(prompt, response);
+
+ await world.page.keyboard.type(prompt, { delay: 20 });
+ await world.page.waitForTimeout(200);
+ await world.page.keyboard.press('Enter');
+}
+
+async function waitForAssistantMessageToSettle(
+ world: CustomWorld,
+ minLength: number,
+): Promise<void> {
+ const assistantMessage = world.page
+ .locator('.message-wrapper')
+ .filter({ has: world.page.locator('text=Lobe AI') })
+ .last();
+
+ await expect(assistantMessage).toBeVisible({ timeout: 15_000 });
+
+ let prevLen = 0;
+ let stableTicks = 0;
+ for (let i = 0; i < 60; i++) {
+ const len =
+ (await assistantMessage
+ .innerText()
+ .then((t) => t.length)
+ .catch(() => 0)) || 0;
+ if (len > minLength && len === prevLen) stableTicks += 1;
+ else stableTicks = 0;
+ prevLen = len;
+ if (stableTicks >= 3) break;
+ await world.page.waitForTimeout(250);
+ }
+}
+
async function scrollBy(world: CustomWorld, deltaY: number): Promise<void> {
await world.page.evaluate((dy) => {
const msg = document.querySelector('.message-wrapper');
@@ -146,11 +193,7 @@ Given('流式响应被放慢以模拟长文输出', async function (this: Custom
When('用户发送长文消息并等待回复完成', { timeout: 45_000 }, async function (this: CustomWorld) {
const prompt = '请输出一篇很长的文章';
- llmMockManager.setResponse(prompt, presetResponses.longScrollArticle);
-
- await this.page.keyboard.type(prompt, { delay: 20 });
- await this.page.waitForTimeout(200);
- await this.page.keyboard.press('Enter');
+ await sendPrompt(this, prompt, presetResponses.longScrollArticle);
// Wait for assistant message to appear and its content to stabilize.
const messageWrappers = this.page.locator('.message-wrapper');
@@ -165,29 +208,12 @@ When('用户发送长文消息并等待回复完成', { timeout: 45_000 }, async
await expect(assistantMessage).toBeVisible({ timeout: 15_000 });
// Poll until text has grown past an obvious threshold, then plateaus.
- let prevLen = 0;
- let stableTicks = 0;
- for (let i = 0; i < 40; i++) {
- const len =
- (await assistantMessage
- .innerText()
- .then((t) => t.length)
- .catch(() => 0)) || 0;
- if (len > 200 && len === prevLen) stableTicks += 1;
- else stableTicks = 0;
- prevLen = len;
- if (stableTicks >= 3) break;
- await this.page.waitForTimeout(250);
- }
+ await waitForAssistantMessageToSettle(this, 200);
});
When('用户发送一条触发长文输出的消息', async function (this: CustomWorld) {
const prompt = '请输出一篇很长的文章';
- llmMockManager.setResponse(prompt, presetResponses.longScrollArticle);
-
- await this.page.keyboard.type(prompt, { delay: 20 });
- await this.page.waitForTimeout(200);
- await this.page.keyboard.press('Enter');
+ await sendPrompt(this, prompt, presetResponses.longScrollArticle);
// Wait long enough for pin's smooth scrollToIndex to finish. Virtua drives
// the smooth animation via rAF and would otherwise overwrite a manual
@@ -195,6 +221,42 @@ When('用户发送一条触发长文输出的消息', async function (this: Cust
await this.page.waitForTimeout(1200);
});
+When(
+ '用户完成一轮用于垫高列表的长回复对话',
+ { timeout: 45_000 },
+ async function (this: CustomWorld) {
+ const prompt = '请先输出一篇很长的文章用于垫高列表';
+ await sendPrompt(this, prompt, presetResponses.longScrollArticle);
+ await waitForAssistantMessageToSettle(this, 200);
+ },
+);
+
+When(
+ '用户发送一条触发短回复的消息并等待回复完成',
+ { timeout: 30_000 },
+ async function (this: CustomWorld) {
+ const prompt = '请输出一段短回复用于测试底部补偿区域';
+ await sendPrompt(this, prompt, '这是一个短回复,用于让底部补偿区域保持可见。');
+ await waitForAssistantMessageToSettle(this, 10);
+ await this.page.waitForTimeout(400);
+ },
+);
+
+When('记录聊天列表底部补偿区域高度', async function (this: CustomWorld) {
+ const snap = await getScrollSnapshot(this);
+ expect(snap, 'failed to locate scroll container').not.toBeNull();
+ expect(snap!.bottomCompensationHeight).toBeGreaterThan(0);
+ expect(snap!.scrollTop).toBeGreaterThan(120);
+
+ this.testContext.scrollCompensationHeight = snap!.bottomCompensationHeight;
+ this.testContext.scrollHeightBeforeSyntheticOffset = snap!.scrollHeight;
+});
+
+When('模拟非用户触发的聊天列表上移 {int} 像素', async function (this: CustomWorld, px: number) {
+ await scrollBy(this, -Math.abs(px));
+ await this.page.waitForTimeout(400);
+});
+
When('用户在流式响应进行中向上滚动 {int} 像素', async function (this: CustomWorld, px: number) {
const delta = Math.abs(px) || MANUAL_SCROLL_UP_DELTA;
// Mouse wheel over the list, more faithful to real-user interaction than
@@ -306,3 +368,13 @@ Then('用户消息应固定在聊天列表顶部', async function (this: CustomW
// Pin anchors with `align: 'start'` — tolerate ~150 px of slack for headers.
expect(Math.abs(rect!.delta)).toBeLessThanOrEqual(150);
});
+
+Then('聊天列表底部补偿区域高度不应收缩', async function (this: CustomWorld) {
+ const before = this.testContext.scrollCompensationHeight as number | undefined;
+ expect(before, 'missing recorded bottom compensation height').toBeDefined();
+
+ const snap = await getScrollSnapshot(this);
+ expect(snap, 'failed to locate scroll container').not.toBeNull();
+
+ expect(snap!.bottomCompensationHeight).toBeGreaterThanOrEqual(before! - 2);
+});
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 12680dab7b7..0f464cc8859 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -1,7 +1,7 @@
'use client';
import isEqual from 'fast-deep-equal';
-import type { ReactElement, ReactNode } from 'react';
+import type { KeyboardEvent, PointerEvent, ReactElement, ReactNode } from 'react';
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
import type { VListHandle } from 'virtua';
import { VList } from 'virtua';
@@ -30,6 +30,8 @@ import { useAutoScrollEnabled } from './AutoScroll/useAutoScrollEnabled';
import BackBottom from './BackBottom';
const CONVERSATION_FOOTER_ID = '__conversation_footer__';
+const USER_SCROLL_INTENT_TTL_MS = 500;
+const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
interface VirtualizedListProps {
dataSource: string[];
@@ -45,6 +47,7 @@ interface VirtualizedListProps {
const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, itemContent }) => {
const virtuaRef = useRef<VListHandle>(null);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const lastUserScrollIntentAtRef = useRef(0);
// Per-topic scroll restoration. Provider does not remount on topic switch,
// so we key the scroll snapshot by the message-map key derived from
@@ -84,6 +87,28 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, it
const setActiveIndex = useConversationStore((s) => s.setActiveIndex);
const activeIndex = useConversationStore(virtuaListSelectors.activeIndex);
+ const markUserScrollIntent = useCallback(() => {
+ lastUserScrollIntentAtRef.current = Date.now();
+ }, []);
+
+ const handlePointerMove = useCallback(
+ (event: PointerEvent<HTMLDivElement>) => {
+ if (event.buttons > 0) {
+ markUserScrollIntent();
+ }
+ },
+ [markUserScrollIntent],
+ );
+
+ const handleKeyDown = useCallback(
+ (event: KeyboardEvent<HTMLDivElement>) => {
+ if (SCROLL_KEYS.has(event.key)) {
+ markUserScrollIntent();
+ }
+ },
+ [markUserScrollIntent],
+ );
+
// Check if at bottom based on scroll position
const checkAtBottom = useCallback(() => {
const ref = virtuaRef.current;
@@ -113,7 +138,9 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, it
// Shrink spacer on scroll up when not streaming
const ref = virtuaRef.current;
if (ref) {
- onScrollOffset(ref.scrollOffset);
+ const hasUserScrollIntent =
+ Date.now() - lastUserScrollIntentAtRef.current <= USER_SCROLL_INTENT_TTL_MS;
+ onScrollOffset(ref.scrollOffset, hasUserScrollIntent);
}
// Check if at bottom
@@ -229,7 +256,14 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, footerSlot, it
totalCountRef.current = dataWithFooter.length;
return (
- <div style={{ height: '100%', position: 'relative' }}>
+ <div
+ style={{ height: '100%', position: 'relative' }}
+ onKeyDownCapture={handleKeyDown}
+ onPointerDownCapture={markUserScrollIntent}
+ onPointerMoveCapture={handlePointerMove}
+ onTouchMoveCapture={markUserScrollIntent}
+ onWheelCapture={markUserScrollIntent}
+ >
{/* Debug Inspector - placed outside VList so it won't be recycled by the virtual list */}
{OPEN_DEV_INSPECTOR && <DebugInspector />}
<VList
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
index a65266d2a85..d4a877b7ec7 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
@@ -64,6 +64,7 @@ describe('useConversationScroll — helpers', () => {
getConversationSpacerScrollEffect({
delta: -24,
hasPrevOffset: true,
+ hasUserIntent: true,
isAIGenerating: true,
isMounted: true,
}),
@@ -75,6 +76,7 @@ describe('useConversationScroll — helpers', () => {
getConversationSpacerScrollEffect({
delta: -24,
hasPrevOffset: true,
+ hasUserIntent: true,
isAIGenerating: false,
isMounted: true,
}),
@@ -86,6 +88,19 @@ describe('useConversationScroll — helpers', () => {
getConversationSpacerScrollEffect({
delta: -999,
hasPrevOffset: false,
+ hasUserIntent: true,
+ isAIGenerating: false,
+ isMounted: true,
+ }),
+ ).toEqual({ cancelPin: false, shrinkSpacer: false });
+ });
+
+ it('ignores layout-driven negative offsets without user scroll intent', () => {
+ expect(
+ getConversationSpacerScrollEffect({
+ delta: -24,
+ hasPrevOffset: true,
+ hasUserIntent: false,
isAIGenerating: false,
isMounted: true,
}),
@@ -288,7 +303,7 @@ describe('useConversationScroll — pin behavior', () => {
// simulate viewport mount via prev offset seeding: first call seeds prev=0
result.current.onScrollOffset(0);
// then user scrolls up (negative delta)
- result.current.onScrollOffset(-50);
+ result.current.onScrollOffset(-50, true);
});
// Simulate a later layout bump that would have re-fired a scroll before.
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
index 02079147c54..b2c93b5a3c7 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
@@ -23,6 +23,7 @@ export const calculateConversationSpacerHeight = (
interface ConversationSpacerScrollEffectOptions {
delta: number;
hasPrevOffset: boolean;
+ hasUserIntent: boolean;
isAIGenerating: boolean;
isMounted: boolean;
}
@@ -30,10 +31,11 @@ interface ConversationSpacerScrollEffectOptions {
export const getConversationSpacerScrollEffect = ({
delta,
hasPrevOffset,
+ hasUserIntent,
isAIGenerating,
isMounted,
}: ConversationSpacerScrollEffectOptions) => {
- const cancelPin = isMounted && hasPrevOffset && delta < 0;
+ const cancelPin = isMounted && hasPrevOffset && hasUserIntent && delta < 0;
return {
cancelPin,
@@ -341,7 +343,7 @@ const useScrollShrink = ({
const scrollShrinkEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const onScrollOffset = useCallback(
- (currentScrollOffset: number) => {
+ (currentScrollOffset: number, hasUserIntent = false) => {
const prevOffset = prevScrollOffsetRef.current;
prevScrollOffsetRef.current = currentScrollOffset;
@@ -349,6 +351,7 @@ const useScrollShrink = ({
const { cancelPin, shrinkSpacer } = getConversationSpacerScrollEffect({
delta,
hasPrevOffset: prevOffset !== null,
+ hasUserIntent,
isAIGenerating: isAIGeneratingRef.current,
isMounted: mountedRef.current,
});
@@ -413,7 +416,7 @@ export interface UseConversationScrollResult {
isScrollShrinking: boolean;
isSpacerMessage: (id: string) => boolean;
listData: string[];
- onScrollOffset: (scrollOffset: number) => void;
+ onScrollOffset: (scrollOffset: number, hasUserIntent?: boolean) => void;
registerSpacerNode: (node: HTMLElement | null) => void;
spacerActive: boolean;
spacerHeight: number;