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.

♻️ refactor(conversation): unify scroll-to-user + spacer hooks (#14132)

Inneib55cf6b9363c
diff --git a/e2e/src/features/journeys/agent/agent-scroll.feature b/e2e/src/features/journeys/agent/agent-scroll.feature
new file mode 100644
index 00000000000..56d72d4c01c
--- /dev/null
+++ b/e2e/src/features/journeys/agent/agent-scroll.feature
@@ -0,0 +1,57 @@
+@journey @agent @conversation @scroll
+Feature: 发送消息与流式输出期间的视口滚动行为
+ 作为用户,我希望视口能按我的设置正确响应 AI 流式输出:
+ - 开启时视口应跟随最新内容,保持贴近底部
+ - 关闭时视口应停留在我刚发送的消息,便于阅读
+ - 流式过程中我手动向上滚动后,视口不应被自动拉回底
+
+ Background:
+ Given 用户已登录系统
+
+ @AGENT-SCROLL-001 @P0 @journey
+ Scenario: 开启流式自动滚动后,视口在流式输出结束时贴近底部
+ Given 用户在设置中开启 "AI 回复时自动滚动"
+ And 用户进入 Lobe AI 对话页面
+ When 用户发送长文消息并等待回复完成
+ Then 视口应贴近聊天列表底部
+
+ @AGENT-SCROLL-002 @P0 @journey
+ Scenario: 关闭流式自动滚动后,用户消息固定在顶部且视口不跟随
+ Given 用户在设置中关闭 "AI 回复时自动滚动"
+ And 用户进入 Lobe AI 对话页面
+ When 用户发送长文消息并等待回复完成
+ Then 用户消息应固定在聊天列表顶部
+ And 视口不应贴近聊天列表底部
+
+ # Mid-stream scroll-up cancellation is covered at the unit level in
+ # `useConversationScroll.test.ts`. An end-to-end version is pending until
+ # the LLM mock can emit a truly chunked SSE response (the current mock
+ # fulfils the whole body at once, which collapses the mid-stream window
+ # to a few hundred milliseconds and makes the interaction race-prone).
+ @AGENT-SCROLL-003 @P1 @journey @skip
+ Scenario: 流式输出过程中手动向上滚动后,消息 pin 被取消
+ Given 用户在设置中开启 "AI 回复时自动滚动"
+ And 流式响应被放慢以模拟长文输出
+ And 用户进入 Lobe AI 对话页面
+ When 用户发送一条触发长文输出的消息
+ And 用户在流式响应进行中向上滚动 200 像素
+ Then 用户消息不应固定在聊天列表顶部
+
+ @AGENT-SCROLL-004 @P0 @journey
+ Scenario: 发送消息后,滚动条自动把用户发送的消息顶到列表顶部
+ Given 流式响应被放慢以模拟长文输出
+ And 用户进入 Lobe AI 对话页面
+ When 用户发送一条触发长文输出的消息
+ Then 用户消息应固定在聊天列表顶部
+
+ # Regression guard for the memo-staleness issue where the message
+ # ResizeObserver could skip rebinding to the new turn's user/assistant DOM
+ # nodes, making spacer height drift off the second send.
+ @AGENT-SCROLL-005 @P0 @journey
+ Scenario: 连续发送两轮消息后,第二轮用户消息仍固定在顶部
+ Given 流式响应被放慢以模拟长文输出
+ And 用户进入 Lobe AI 对话页面
+ When 用户发送一条触发长文输出的消息
+ And 等待流式响应结束
+ And 用户发送一条触发长文输出的消息
+ Then 用户消息应固定在聊天列表顶部
diff --git a/e2e/src/mocks/llm/index.ts b/e2e/src/mocks/llm/index.ts
index 02ad6d58205..ad1e138c327 100644
--- a/e2e/src/mocks/llm/index.ts
+++ b/e2e/src/mocks/llm/index.ts
@@ -111,6 +111,22 @@ export class LLMMockManager {
this.customResponses.set(userMessage.toLowerCase().trim(), response);
}
+ /**
+ * Merge partial config overrides. Used by tests that need a slower or faster
+ * stream than the defaults (e.g. to simulate mid-stream user interactions).
+ */
+ setConfig(partial: Partial<LLMMockConfig>): void {
+ this.config = { ...this.config, ...partial };
+ }
+
+ /**
+ * Reset config to factory defaults. Call from `After` hooks so a test's
+ * timing overrides do not bleed into the next scenario.
+ */
+ resetConfig(): void {
+ this.config = { ...defaultConfig };
+ }
+
/**
* Clear all custom responses
*/
@@ -232,6 +248,18 @@ export const presetResponses = {
error: 'I apologize, but I encountered an error processing your request.',
greeting: 'Hello! I am Lobe AI, your AI assistant. How can I help you today?',
+ // Much longer response so the chat surely exceeds the viewport and scroll
+ // behavior is observable (used by @AGENT-SCROLL-* scenarios).
+ longScrollArticle: Array.from({ length: 30 }, (_, i) => `这是第 ${i + 1} 段内容。`)
+ .concat(
+ Array.from(
+ { length: 30 },
+ (_, i) =>
+ `段落 ${i + 1}:人工智能是计算机科学的一个分支,它企图了解智能的实质,并生产出一种新的能以人类智能相似的方式做出反应的智能机器。研究领域包括机器人、语言识别、图像识别、自然语言处理和专家系统等。`,
+ ),
+ )
+ .join('\n\n'),
+
// Long response for stop generation test
longArticle:
'这是一篇很长的文章。第一段:人工智能是计算机科学的一个分支,它企图了解智能的实质,并生产出一种新的能以人类智能相似的方式做出反应的智能机器。第二段:人工智能研究的主要目标包括推理、知识、规划、学习、自然语言处理、感知和移动与操控物体的能力。第三段:目前,人工智能已经在许多领域取得了重大突破,包括图像识别、语音识别、自然语言处理等。',
diff --git a/e2e/src/steps/agent/scroll.steps.ts b/e2e/src/steps/agent/scroll.steps.ts
new file mode 100644
index 00000000000..620047bdcdc
--- /dev/null
+++ b/e2e/src/steps/agent/scroll.steps.ts
@@ -0,0 +1,308 @@
+/**
+ * Agent Scroll Steps
+ *
+ * Step definitions for @AGENT-SCROLL-* scenarios. These verify that the
+ * `useConversationScroll` hook + `<AutoScroll />` component cooperate
+ * correctly under the three real-world cases:
+ *
+ * 1. `enableAutoScrollOnStreaming = true` → viewport stays near bottom
+ * 2. `enableAutoScrollOnStreaming = false` → user message pinned to top
+ * 3. User scrolls up mid-stream → viewport stays put
+ */
+import { After, Given, Then, When } from '@cucumber/cucumber';
+import { expect } from '@playwright/test';
+
+import { llmMockManager, presetResponses } from '../../mocks/llm';
+import type { CustomWorld } from '../../support/world';
+
+// How close to the scroll container's bottom is considered "at bottom".
+// Matches (with slack) the product's own AT_BOTTOM_THRESHOLD (300 px).
+const AT_BOTTOM_EPSILON = 320;
+// Distance the user manually scrolls up for scenario 3.
+const MANUAL_SCROLL_UP_DELTA = 200;
+
+interface ScrollSnapshot {
+ clientHeight: number;
+ distanceToBottom: number;
+ scrollHeight: number;
+ scrollTop: number;
+}
+
+// ---------------------------------------------------------------------------
+// DOM helpers (executed inside the page)
+// ---------------------------------------------------------------------------
+
+// Find the scrollable ancestor of the first `.message-wrapper`. This is the
+// virtua VList's inner scroll container — product code doesn't add a stable
+// data-testid to it, but the structure is reliable enough for an e2e test.
+async function getScrollSnapshot(world: CustomWorld): Promise<ScrollSnapshot | null> {
+ return world.page.evaluate(() => {
+ const msg = document.querySelector('.message-wrapper');
+ let el: HTMLElement | null = (msg?.parentElement as HTMLElement) || null;
+ while (el) {
+ const style = window.getComputedStyle(el);
+ if (style.overflowY === 'auto' || style.overflowY === 'scroll') {
+ return {
+ clientHeight: el.clientHeight,
+ distanceToBottom: el.scrollHeight - el.scrollTop - el.clientHeight,
+ scrollHeight: el.scrollHeight,
+ scrollTop: el.scrollTop,
+ };
+ }
+ el = el.parentElement;
+ }
+ return null;
+ });
+}
+
+async function scrollBy(world: CustomWorld, deltaY: number): Promise<void> {
+ await world.page.evaluate((dy) => {
+ const msg = document.querySelector('.message-wrapper');
+ let el: HTMLElement | null = (msg?.parentElement as HTMLElement) || null;
+ while (el) {
+ const style = window.getComputedStyle(el);
+ if (style.overflowY === 'auto' || style.overflowY === 'scroll') {
+ el.scrollTop = Math.max(0, el.scrollTop + dy);
+ el.dispatchEvent(new Event('scroll', { bubbles: true }));
+ return;
+ }
+ el = el.parentElement;
+ }
+ }, deltaY);
+}
+
+// ---------------------------------------------------------------------------
+// Setting toggle via the chat-appearance settings page
+// ---------------------------------------------------------------------------
+
+async function setAutoScrollEnabled(world: CustomWorld, desired: boolean): Promise<void> {
+ await world.page.goto('/settings/chat-appearance');
+ // `networkidle` can take a while on the very first compile in dev mode
+ // (Next.js builds the settings route on demand); a generous timeout avoids
+ // flakes when the test suite warms up a cold server.
+ await world.page.waitForLoadState('networkidle', { timeout: 60_000 });
+
+ // Match both EN ("Auto-scroll During AI Response") and zh-CN ("AI 回复时自动滚动").
+ const title = world.page.getByText(/Auto-scroll During AI Response|AI 回复时自动滚动/);
+ await expect(title).toBeVisible({ timeout: 45_000 });
+
+ // The switch lives inside the same FormGroup as the title.
+ const switcher = world.page
+ .locator('[role="switch"], button.ant-switch')
+ .filter({
+ has: title,
+ })
+ .or(
+ world.page
+ .locator('div')
+ .filter({ has: title })
+ .last()
+ .locator('[role="switch"], button.ant-switch')
+ .first(),
+ );
+
+ // Fall back: the switch is the nearest role=switch sibling of the title node.
+ const nearestSwitch = world.page.locator('[role="switch"]').first();
+ const target = (await switcher.count()) > 0 ? switcher.first() : nearestSwitch;
+
+ const currentChecked = (await target.getAttribute('aria-checked')) === 'true';
+ if (currentChecked !== desired) {
+ await target.click();
+ // Give the optimistic update + debounced server call a moment to settle.
+ await world.page.waitForTimeout(400);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Given steps
+// ---------------------------------------------------------------------------
+
+Given(
+ '用户在设置中开启 {string}',
+ { timeout: 90_000 },
+ async function (this: CustomWorld, _label: string) {
+ await setAutoScrollEnabled(this, true);
+ },
+);
+
+Given(
+ '用户在设置中关闭 {string}',
+ { timeout: 90_000 },
+ async function (this: CustomWorld, _label: string) {
+ await setAutoScrollEnabled(this, false);
+ },
+);
+
+Given('流式响应被放慢以模拟长文输出', async function (this: CustomWorld) {
+ // A ~1.5s head-delay gives the test room to interact (manual scroll) while
+ // the assistant placeholder is mounted but no tokens have streamed yet.
+ llmMockManager.setConfig({ responseDelay: 1500, streamChunkSize: 8, streamDelay: 60 });
+ this.testContext.scrollMockAdjusted = true;
+});
+
+// ---------------------------------------------------------------------------
+// When steps
+// ---------------------------------------------------------------------------
+
+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');
+
+ // Wait for assistant message to appear and its content to stabilize.
+ const messageWrappers = this.page.locator('.message-wrapper');
+ await expect(messageWrappers)
+ .toHaveCount(2, { timeout: 15_000 })
+ .catch(() => {});
+
+ const assistantMessage = this.page
+ .locator('.message-wrapper')
+ .filter({ has: this.page.locator('text=Lobe AI') })
+ .last();
+ 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);
+ }
+});
+
+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');
+
+ // Wait long enough for pin's smooth scrollToIndex to finish. Virtua drives
+ // the smooth animation via rAF and would otherwise overwrite a manual
+ // scroll while the animation is still in flight.
+ await this.page.waitForTimeout(1200);
+});
+
+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
+ // setting `scrollTop` directly. Move the cursor into the list viewport
+ // first — wheel events fire against whatever element is under the cursor.
+ await this.page.mouse.move(640, 400);
+ await this.page.mouse.wheel(0, -delta);
+ await scrollBy(this, -delta);
+ // Let the onScroll handler run (pin cancel + spacer shrink).
+ await this.page.waitForTimeout(400);
+});
+
+When('等待流式响应结束', { timeout: 30_000 }, async function (this: CustomWorld) {
+ const assistantMessage = this.page
+ .locator('.message-wrapper')
+ .filter({ has: this.page.locator('text=Lobe AI') })
+ .last();
+
+ 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 > 200 && len === prevLen) stableTicks += 1;
+ else stableTicks = 0;
+ prevLen = len;
+ if (stableTicks >= 3) break;
+ await this.page.waitForTimeout(250);
+ }
+});
+
+// ---------------------------------------------------------------------------
+// Then steps
+// ---------------------------------------------------------------------------
+
+Then('视口应贴近聊天列表底部', async function (this: CustomWorld) {
+ const snap = await getScrollSnapshot(this);
+ expect(snap, 'failed to locate scroll container').not.toBeNull();
+ expect(snap!.distanceToBottom).toBeLessThanOrEqual(AT_BOTTOM_EPSILON);
+});
+
+Then('视口不应贴近聊天列表底部', async function (this: CustomWorld) {
+ const snap = await getScrollSnapshot(this);
+ expect(snap, 'failed to locate scroll container').not.toBeNull();
+ expect(snap!.distanceToBottom).toBeGreaterThan(AT_BOTTOM_EPSILON);
+});
+
+// Reset LLM mock timing overrides so the slowdown from scenario 3 does not
+// leak into later unrelated scenarios.
+After({ tags: '@scroll' }, async function (this: CustomWorld) {
+ if (this.testContext.scrollMockAdjusted) {
+ llmMockManager.resetConfig();
+ this.testContext.scrollMockAdjusted = false;
+ }
+});
+
+Then('用户消息不应固定在聊天列表顶部', async function (this: CustomWorld) {
+ const rect = await this.page.evaluate(() => {
+ const wrappers = Array.from(document.querySelectorAll('.message-wrapper'));
+ if (wrappers.length < 2) return null;
+ const userWrapper = wrappers.at(-2) as HTMLElement;
+ let scrollParent: HTMLElement | null = userWrapper.parentElement;
+ while (scrollParent) {
+ const style = window.getComputedStyle(scrollParent);
+ if (style.overflowY === 'auto' || style.overflowY === 'scroll') break;
+ scrollParent = scrollParent.parentElement;
+ }
+ if (!scrollParent) return null;
+ const wrapperRect = userWrapper.getBoundingClientRect();
+ const parentRect = scrollParent.getBoundingClientRect();
+ return { delta: wrapperRect.top - parentRect.top };
+ });
+
+ expect(rect).not.toBeNull();
+ // Pin is cancelled: the user message should have been pushed down by the
+ // manual scroll. Anything beyond the "pinned" slack (150 px) means the
+ // anchor was released.
+ expect(Math.abs(rect!.delta)).toBeGreaterThan(150);
+});
+
+Then('用户消息应固定在聊天列表顶部', async function (this: CustomWorld) {
+ // Find the user message (the penultimate `.message-wrapper`) and check its
+ // top is close to the scroll container top. We allow some slack because
+ // virtua lays out with some padding and the header can stick.
+ const rect = await this.page.evaluate(() => {
+ const wrappers = Array.from(document.querySelectorAll('.message-wrapper'));
+ if (wrappers.length < 2) return null;
+ const userWrapper = wrappers.at(-2) as HTMLElement;
+ let scrollParent: HTMLElement | null = userWrapper.parentElement;
+ while (scrollParent) {
+ const style = window.getComputedStyle(scrollParent);
+ if (style.overflowY === 'auto' || style.overflowY === 'scroll') break;
+ scrollParent = scrollParent.parentElement;
+ }
+ if (!scrollParent) return null;
+ const wrapperRect = userWrapper.getBoundingClientRect();
+ const parentRect = scrollParent.getBoundingClientRect();
+ return {
+ parentTop: parentRect.top,
+ userTop: wrapperRect.top,
+ delta: wrapperRect.top - parentRect.top,
+ };
+ });
+
+ expect(rect, 'failed to resolve user message + scroll parent').not.toBeNull();
+ // Pin anchors with `align: 'start'` — tolerate ~150 px of slack for headers.
+ expect(Math.abs(rect!.delta)).toBeLessThanOrEqual(150);
+});
diff --git a/src/features/Conversation/ChatList/components/AutoScroll/const.ts b/src/features/Conversation/ChatList/components/AutoScroll/const.ts
index 4c2c44a3776..f25f3ff0da3 100644
--- a/src/features/Conversation/ChatList/components/AutoScroll/const.ts
+++ b/src/features/Conversation/ChatList/components/AutoScroll/const.ts
@@ -2,4 +2,4 @@
* Threshold for determining if at the bottom (unit: px)
* When the distance to the bottom is less than or equal to this value, considered at the bottom
*/
-export const AT_BOTTOM_THRESHOLD = 100;
+export const AT_BOTTOM_THRESHOLD = 300;
diff --git a/src/features/Conversation/ChatList/components/VirtualizedList.tsx b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
index 86dbc725f10..7b44d35e82d 100644
--- a/src/features/Conversation/ChatList/components/VirtualizedList.tsx
+++ b/src/features/Conversation/ChatList/components/VirtualizedList.tsx
@@ -16,9 +16,8 @@ import {
} from '../../store';
import {
CONVERSATION_SPACER_TRANSITION_MS,
- useConversationSpacer,
-} from '../hooks/useConversationSpacer';
-import { useScrollToUserMessage } from '../hooks/useScrollToUserMessage';
+ useConversationScroll,
+} from '../hooks/useConversationScroll';
import { useSelectionMessageIds } from '../hooks/useSelectionMessageIds';
import AutoScroll from './AutoScroll';
import { AT_BOTTOM_THRESHOLD } from './AutoScroll/const';
@@ -40,17 +39,25 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
const virtuaRef = useRef<VListHandle>(null);
const didInitialScrollRef = useRef(false);
const scrollEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ // Second-to-last message is the user turn when sending (user + assistant pair)
+ const isSecondLastMessageFromUser = useConversationStore(
+ dataSelectors.isSecondLastMessageFromUser,
+ );
+
const {
- cancelPinMessageIndex,
- handleScrollOffset,
+ isScrollShrinking,
isSpacerMessage,
listData,
+ onScrollOffset,
registerSpacerNode,
- scrollShrinking,
- spacerHeight,
spacerActive,
- spacerLayoutVersion,
- } = useConversationSpacer(dataSource);
+ spacerHeight,
+ } = useConversationScroll({
+ dataSource,
+ isSecondLastMessageFromUser,
+ virtuaRef,
+ });
const isAutoScrollEnabled = useAutoScrollEnabled();
// Store actions
@@ -89,7 +96,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
// Shrink spacer on scroll up when not streaming
const ref = virtuaRef.current;
if (ref) {
- handleScrollOffset(ref.scrollOffset);
+ onScrollOffset(ref.scrollOffset);
}
// Check if at bottom
@@ -105,7 +112,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
scrollEndTimerRef.current = setTimeout(() => {
setScrollState({ isScrolling: false });
}, 150);
- }, [activeIndex, checkAtBottom, handleScrollOffset, setActiveIndex, setScrollState]);
+ }, [activeIndex, checkAtBottom, onScrollOffset, setActiveIndex, setScrollState]);
const handleScrollEnd = useCallback(() => {
setScrollState({ isScrolling: false });
@@ -147,12 +154,6 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
};
}, [resetVisibleItems]);
- // Get the second-to-last message to check if it's a user message
- // (When sending a message, user + assistant messages are created as a pair)
- const displayMessages = useConversationStore(dataSelectors.displayMessages);
- const secondLastMessage = displayMessages.at(-2);
- const isSecondLastMessageFromUser = secondLastMessage?.role === 'user';
-
// Keep currently-streaming items mounted so vlist recycling never triggers
// Markdown animation replay when the user scrolls them back into view.
const streamingIndices = useConversationStore(
@@ -182,18 +183,6 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
return [...merged].sort((a, b) => a - b);
}, [dataSource, streamingIndices, selectionMessageIds]);
- // 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,
- scrollToIndex: virtuaRef.current?.scrollToIndex ?? null,
- spacerActive,
- spacerLayoutVersion,
- });
-
// Scroll to bottom on initial render
useEffect(() => {
if (didInitialScrollRef.current || !virtuaRef.current || dataSource.length === 0) return;
@@ -225,7 +214,7 @@ const VirtualizedList = memo<VirtualizedListProps>(({ dataSource, itemContent })
// instantly so virtua's scrollSize updates in a single frame and
// scrollToIndex can reach the user message without trailing behind
// a 200ms transition.
- const shouldAnimate = !scrollShrinking && spacerHeight === 0;
+ const shouldAnimate = !isScrollShrinking && spacerHeight === 0;
return (
<WideScreenContainer key={messageId} style={{ position: 'relative' }}>
<div
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
new file mode 100644
index 00000000000..a65266d2a85
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
@@ -0,0 +1,399 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { createRef, type RefObject } from 'react';
+import { type VListHandle } from 'virtua';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ConversationStoreModule from '../../store';
+import { useConversationStore } from '../../store';
+import {
+ calculateConversationSpacerHeight,
+ CONVERSATION_SPACER_ID,
+ getConversationSpacerScrollEffect,
+ useConversationScroll,
+} from './useConversationScroll';
+
+vi.mock('zustand/traditional');
+
+vi.mock('../../store', async (importOriginal) => {
+ const actual = await importOriginal<typeof ConversationStoreModule>();
+ return {
+ ...actual,
+ useConversationStore: vi.fn(),
+ };
+});
+
+// ResizeObserver mock capturing the latest callback so tests can trigger it.
+class MockResizeObserver {
+ static latest: MockResizeObserver | null = null;
+ callback: ResizeObserverCallback;
+ observed: Element[] = [];
+ constructor(callback: ResizeObserverCallback) {
+ this.callback = callback;
+ MockResizeObserver.latest = this;
+ }
+ observe(el: Element) {
+ this.observed.push(el);
+ }
+ disconnect() {
+ this.observed = [];
+ }
+ unobserve() {}
+ trigger() {
+ this.callback([], this as unknown as ResizeObserver);
+ }
+}
+
+describe('useConversationScroll — helpers', () => {
+ it('calculates remaining spacer height behind the latest assistant message', () => {
+ expect(calculateConversationSpacerHeight(800, 200, 80)).toBe(520);
+ });
+
+ it('clamps spacer height to zero when content already fills the viewport', () => {
+ expect(calculateConversationSpacerHeight(800, 300, 600)).toBe(0);
+ });
+
+ it('keeps the reserved spacer id stable', () => {
+ expect(CONVERSATION_SPACER_ID).toBe('__conversation_spacer__');
+ });
+
+ it('cancels pin retries without shrinking the spacer while AI is streaming', () => {
+ expect(
+ getConversationSpacerScrollEffect({
+ delta: -24,
+ hasPrevOffset: true,
+ isAIGenerating: true,
+ isMounted: true,
+ }),
+ ).toEqual({ cancelPin: true, shrinkSpacer: false });
+ });
+
+ it('both cancels pin retries and shrinks the spacer after streaming stops', () => {
+ expect(
+ getConversationSpacerScrollEffect({
+ delta: -24,
+ hasPrevOffset: true,
+ isAIGenerating: false,
+ isMounted: true,
+ }),
+ ).toEqual({ cancelPin: true, shrinkSpacer: true });
+ });
+
+ it('does nothing when there is no previous offset to diff against', () => {
+ expect(
+ getConversationSpacerScrollEffect({
+ delta: -999,
+ hasPrevOffset: false,
+ isAIGenerating: false,
+ isMounted: true,
+ }),
+ ).toEqual({ cancelPin: false, shrinkSpacer: false });
+ });
+});
+
+describe('useConversationScroll — pin behavior', () => {
+ const scrollToIndex = vi.fn();
+ const virtuaRef: RefObject<VListHandle | null> = createRef<VListHandle>();
+ const assistantId = 'assistant-1';
+ const userId = 'user-1';
+
+ /**
+ * State the mocked store will return. displayMessages is read by the hook
+ * to verify "user + assistant pair was just appended".
+ */
+ type StoreFixture = {
+ displayMessages: Array<{ id: string; role: 'user' | 'assistant' }>;
+ isAIGenerating: boolean;
+ virtuaScrollMethods: {
+ getItemOffset?: (i: number) => number;
+ getItemSize?: (i: number) => number;
+ getScrollOffset?: () => number;
+ getViewportSize?: () => number;
+ } | null;
+ };
+
+ // Latest fixture is mutable so rerenders see up-to-date displayMessages.
+ let currentFixture: StoreFixture = {
+ displayMessages: [],
+ isAIGenerating: false,
+ virtuaScrollMethods: null,
+ };
+
+ const deriveDisplayMessages = (isSecondLastFromUser: boolean) =>
+ isSecondLastFromUser
+ ? [
+ { id: userId, role: 'user' as const },
+ { id: assistantId, role: 'assistant' as const },
+ ]
+ : [{ id: assistantId, role: 'assistant' as const }];
+
+ const installStoreMock = () => {
+ vi.mocked(useConversationStore).mockImplementation((selector: any) => {
+ const probe: any = {
+ displayMessages: currentFixture.displayMessages,
+ operationState: { isAIGenerating: currentFixture.isAIGenerating },
+ virtuaScrollMethods: currentFixture.virtuaScrollMethods,
+ };
+ return selector(probe);
+ });
+ };
+
+ const renderScrollHook = (props: {
+ dataSource: string[];
+ isSecondLastMessageFromUser: boolean;
+ fixture?: Partial<StoreFixture>;
+ }) => {
+ currentFixture = {
+ displayMessages: deriveDisplayMessages(props.isSecondLastMessageFromUser),
+ isAIGenerating: false,
+ virtuaScrollMethods: {
+ getScrollOffset: () => 0,
+ getViewportSize: () => 800,
+ },
+ ...props.fixture,
+ };
+ installStoreMock();
+
+ const hook = renderHook(
+ ({ dataSource, isSecondLastMessageFromUser }) =>
+ useConversationScroll({ dataSource, isSecondLastMessageFromUser, virtuaRef }),
+ {
+ initialProps: {
+ dataSource: props.dataSource,
+ isSecondLastMessageFromUser: props.isSecondLastMessageFromUser,
+ },
+ },
+ );
+
+ const rerender = (next: { dataSource: string[]; isSecondLastMessageFromUser: boolean }) => {
+ currentFixture = {
+ ...currentFixture,
+ displayMessages: deriveDisplayMessages(next.isSecondLastMessageFromUser),
+ };
+ hook.rerender(next);
+ };
+
+ return { ...hook, rerender };
+ };
+
+ beforeEach(() => {
+ scrollToIndex.mockReset();
+ // Attach a live mock handle; scrollToPinned reads virtuaRef.current at call time.
+ virtuaRef.current = { scrollToIndex } as unknown as VListHandle;
+ vi.stubGlobal('ResizeObserver', MockResizeObserver);
+ MockResizeObserver.latest = null;
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it('scrolls to the user message when a user+assistant pair is appended', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: [assistantId, 'prev'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ rerender({
+ dataSource: ['m0', 'm1', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).toHaveBeenCalledTimes(1);
+ expect(scrollToIndex).toHaveBeenCalledWith(2, { align: 'start', smooth: true });
+ });
+
+ it('does not scroll when only the assistant message is appended', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: [userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+ scrollToIndex.mockClear();
+
+ rerender({
+ dataSource: [userId, assistantId, 'followup'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('does not scroll when the dataSource length is unchanged', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: ['a', 'b', 'c', 'd'],
+ isSecondLastMessageFromUser: true,
+ });
+ scrollToIndex.mockClear();
+
+ rerender({
+ dataSource: ['a', 'b', 'c', 'd'],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('does not scroll when the dataSource shrinks (deletion)', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: ['a', 'b', 'c', 'd', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+ scrollToIndex.mockClear();
+
+ rerender({
+ dataSource: ['a', 'b', 'c', 'd'],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('does not throw or scroll when virtuaRef is not ready at send time', () => {
+ virtuaRef.current = null;
+
+ const { rerender } = renderScrollHook({
+ dataSource: [assistantId],
+ isSecondLastMessageFromUser: false,
+ });
+
+ expect(() =>
+ rerender({
+ dataSource: ['m0', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ }),
+ ).not.toThrow();
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('stops pinning once the user scrolls up', () => {
+ const { result, rerender } = renderScrollHook({
+ dataSource: [assistantId, 'prev'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ rerender({
+ dataSource: ['m0', 'm1', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+ expect(scrollToIndex).toHaveBeenCalledTimes(1);
+ scrollToIndex.mockClear();
+
+ // User scrolls up: offset decreased (hook tracks prev via getScrollOffset=0)
+ act(() => {
+ // 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);
+ });
+
+ // Simulate a later layout bump that would have re-fired a scroll before.
+ // Since pin was cleared, no scroll should be called.
+ // Re-render with same dataSource triggers the pin-re-fire effect path only
+ // when pinRef is set; it's null now.
+ rerender({
+ dataSource: ['m0', 'm1', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('does not scroll on initial render', () => {
+ renderScrollHook({
+ dataSource: ['a', 'b', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).not.toHaveBeenCalled();
+ });
+
+ it('targets the correct index when multiple turns accumulate', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: ['a', 'b', 'c', 'd'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ rerender({
+ dataSource: ['a', 'b', 'c', 'd', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).toHaveBeenLastCalledWith(4, { align: 'start', smooth: true });
+ });
+
+ it('updates the pin index for the latest turn when a second pair is appended', () => {
+ const { rerender } = renderScrollHook({
+ dataSource: ['a', 'b'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ // first send
+ rerender({
+ dataSource: ['a', 'b', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+ expect(scrollToIndex).toHaveBeenLastCalledWith(2, { align: 'start', smooth: true });
+
+ // second send — fixture keeps displayMessages ending in user+assistant
+ rerender({
+ dataSource: ['a', 'b', userId, assistantId, 'u2', 'a2'],
+ isSecondLastMessageFromUser: true,
+ });
+
+ expect(scrollToIndex).toHaveBeenLastCalledWith(4, { align: 'start', smooth: true });
+ });
+
+ // Regression: the messages ResizeObserver must rebind to the freshly sent
+ // user + assistant DOM nodes. The earlier memo had `[dataSource,
+ // displayMessages]` deps but read an ref that is updated later inside the
+ // send-detection effect — so the signature could remain stale on the next
+ // render and the observer would never hook the new turn.
+ it('observes the freshly sent user + assistant DOM nodes after a send', async () => {
+ // Render user/assistant nodes with data-message-id so the hook's
+ // document.querySelector('[data-message-id="..."]') can find them.
+ const userEl = document.createElement('div');
+ userEl.setAttribute('data-message-id', userId);
+ const assistantEl = document.createElement('div');
+ assistantEl.setAttribute('data-message-id', assistantId);
+ document.body.append(userEl, assistantEl);
+
+ try {
+ const { rerender } = renderScrollHook({
+ dataSource: [assistantId, 'prev'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ // Grab the observer that was created before the send. It may already
+ // exist (empty deps) or not; either way we reset the "latest" slot so
+ // the post-send observer is the one we inspect.
+ MockResizeObserver.latest = null;
+
+ rerender({
+ dataSource: ['m0', 'm1', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+
+ // Flush any pending microtasks + rAFs the send effect scheduled.
+ await act(async () => {
+ vi.runAllTimers();
+ await Promise.resolve();
+ });
+
+ const observer = MockResizeObserver.latest as MockResizeObserver | null;
+ expect(observer, 'no ResizeObserver was created for messages').not.toBeNull();
+ const observedIds = observer!.observed.map((el: Element) =>
+ (el as HTMLElement).getAttribute('data-message-id'),
+ );
+ expect(observedIds).toContain(userId);
+ expect(observedIds).toContain(assistantId);
+ } finally {
+ userEl.remove();
+ assistantEl.remove();
+ }
+ });
+});
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
new file mode 100644
index 00000000000..02079147c54
--- /dev/null
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
@@ -0,0 +1,586 @@
+import { type AssistantContentBlock, type UIChatMessage } from '@lobechat/types';
+import debug from 'debug';
+import { type RefObject, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { type VListHandle } from 'virtua';
+
+import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
+
+const log = debug('lobe:conversation:scroll');
+
+export const CONVERSATION_SPACER_ID = '__conversation_spacer__';
+export const CONVERSATION_SPACER_TRANSITION_MS = 200;
+
+const SCROLL_SHRINK_END_DELAY_MS = 150;
+
+// -------- pure helpers --------
+
+export const calculateConversationSpacerHeight = (
+ viewportHeight: number,
+ userHeight: number,
+ 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;
+
+ return document.querySelector(`[data-message-id="${messageId}"]`) as HTMLElement | null;
+};
+
+const getMessageHeight = (messageId: string | null) => {
+ return getMessageElement(messageId)?.getBoundingClientRect().height || 0;
+};
+
+const getRenderableTailSignature = (message: UIChatMessage | undefined) => {
+ if (!message) return '';
+
+ const tailBlock: AssistantContentBlock | UIChatMessage =
+ message.children && message.children.length > 0 ? message.children.at(-1)! : message;
+
+ const contentLength = tailBlock.content?.length || 0;
+ const reasoningLength = tailBlock.reasoning?.content?.length || 0;
+ const toolCount = tailBlock.tools?.length || 0;
+
+ return `${contentLength}:${reasoningLength}:${toolCount}:${message.updatedAt || 0}`;
+};
+
+// ---------------------------------------------------------------------------
+// Sub-hook: spacer layout signal
+// ---------------------------------------------------------------------------
+//
+// Watches the spacer DOM node with a scoped ResizeObserver. Every size change
+// bumps `spacerLayoutVersion`, which the pin controller uses as "layout
+// settled" beats to retry its scroll.
+//
+// A scoped observer (rather than a document-wide selector) is deliberate:
+// ConversationProvider can mount several chat lists simultaneously, and a
+// global selector would attach to another panel's spacer.
+// ---------------------------------------------------------------------------
+const useSpacerLayoutSignal = () => {
+ const [spacerLayoutVersion, setSpacerLayoutVersion] = useState(0);
+ const observerRef = useRef<ResizeObserver | null>(null);
+
+ const cleanup = useCallback(() => {
+ observerRef.current?.disconnect();
+ observerRef.current = null;
+ }, []);
+
+ const registerSpacerNode = useCallback(
+ (node: HTMLElement | null) => {
+ cleanup();
+
+ if (!node || typeof ResizeObserver === 'undefined') return;
+
+ const observer = new ResizeObserver(() => {
+ setSpacerLayoutVersion((v) => v + 1);
+ });
+ observer.observe(node);
+ observerRef.current = observer;
+ setSpacerLayoutVersion((v) => v + 1);
+ },
+ [cleanup],
+ );
+
+ useEffect(() => cleanup, [cleanup]);
+
+ return { registerSpacerNode, spacerLayoutVersion };
+};
+
+// ---------------------------------------------------------------------------
+// Sub-hook: spacer height & mount lifecycle
+// ---------------------------------------------------------------------------
+//
+// Owns the spacer's natural height, its mount/unmount timing, and the user-
+// driven shrink reduction. Measures via virtua's item methods when available,
+// falling back to DOM `getBoundingClientRect` otherwise.
+//
+// Also hosts the ResizeObserver for the tracked user/assistant messages so
+// that spacer height stays in sync as those messages grow.
+// ---------------------------------------------------------------------------
+interface UseSpacerHeightArgs {
+ assistantMessageIndex: number | null;
+ dataSource: string[];
+ getItemOffset: ((index: number) => number) | undefined;
+ getItemSize: ((index: number) => number) | undefined;
+ getViewportSize: (() => number) | undefined;
+ latestAssistantSignature: string;
+ userMessageIndex: number | null;
+}
+
+const useSpacerHeight = ({
+ dataSource,
+ getItemOffset,
+ getItemSize,
+ getViewportSize,
+ latestAssistantSignature,
+ userMessageIndex,
+ assistantMessageIndex,
+}: UseSpacerHeightArgs) => {
+ const [naturalHeight, setNaturalHeight] = useState(0);
+ const [scrollReduction, setScrollReduction] = useState(0);
+ const [mounted, setMounted] = useState(false);
+
+ const mountedRef = useRef(false);
+ mountedRef.current = mounted;
+
+ const removeTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const messagesObserverRef = useRef<ResizeObserver | null>(null);
+
+ const renderedHeight = Math.max(naturalHeight - scrollReduction, 0);
+ const isScrollShrinking = scrollReduction > 0;
+
+ const getTrackedMessages = useCallback(() => {
+ const userIndex = userMessageIndex;
+ const assistantIndex = assistantMessageIndex;
+
+ return {
+ assistantId:
+ assistantIndex !== null && assistantIndex >= 0 ? dataSource[assistantIndex] || null : null,
+ assistantIndex,
+ userId: userIndex !== null && userIndex >= 0 ? dataSource[userIndex] || null : null,
+ userIndex,
+ };
+ }, [assistantMessageIndex, dataSource, userMessageIndex]);
+
+ const clearRemoveTimer = useCallback(() => {
+ if (removeTimerRef.current) {
+ clearTimeout(removeTimerRef.current);
+ removeTimerRef.current = null;
+ }
+ }, []);
+
+ const cleanupMessagesObserver = useCallback(() => {
+ messagesObserverRef.current?.disconnect();
+ messagesObserverRef.current = null;
+ }, []);
+
+ const scheduleSpacerUnmount = useCallback(() => {
+ clearRemoveTimer();
+
+ removeTimerRef.current = setTimeout(() => {
+ setMounted(false);
+ removeTimerRef.current = null;
+ }, CONVERSATION_SPACER_TRANSITION_MS);
+ }, [clearRemoveTimer]);
+
+ const updateSpacerHeight = useCallback(() => {
+ clearRemoveTimer();
+ const { assistantId, assistantIndex, userId, userIndex } = getTrackedMessages();
+ const viewportHeight = getViewportSize?.() || window.innerHeight;
+
+ let nextHeight: number;
+
+ if (userIndex !== null && assistantIndex !== null && getItemOffset && getItemSize) {
+ const userTop = getItemOffset(userIndex);
+ const assistantBottom = getItemOffset(assistantIndex) + getItemSize(assistantIndex);
+
+ nextHeight = Math.max(Math.round(viewportHeight - (assistantBottom - userTop)), 0);
+ } else {
+ const userHeight = getMessageHeight(userId);
+ if (!userHeight) return;
+
+ const assistantHeight = getMessageHeight(assistantId);
+
+ nextHeight = calculateConversationSpacerHeight(viewportHeight, userHeight, assistantHeight);
+ }
+
+ if (nextHeight === 0) {
+ setNaturalHeight(0);
+ scheduleSpacerUnmount();
+ return;
+ }
+
+ setMounted(true);
+ setNaturalHeight(nextHeight);
+ }, [
+ clearRemoveTimer,
+ getTrackedMessages,
+ getItemOffset,
+ getItemSize,
+ getViewportSize,
+ scheduleSpacerUnmount,
+ ]);
+
+ // Observe tracked message heights; keep spacer in sync while assistant grows.
+ useEffect(() => {
+ const { assistantId, userId } = getTrackedMessages();
+
+ cleanupMessagesObserver();
+
+ if (!assistantId || !userId || typeof ResizeObserver === 'undefined') return;
+
+ const observer = new ResizeObserver(() => {
+ requestAnimationFrame(() => {
+ updateSpacerHeight();
+ });
+ });
+
+ messagesObserverRef.current = observer;
+
+ const userEl = getMessageElement(userId);
+ const assistantEl = getMessageElement(assistantId);
+
+ if (userEl) observer.observe(userEl);
+ if (assistantEl) observer.observe(assistantEl);
+
+ requestAnimationFrame(() => {
+ updateSpacerHeight();
+ });
+
+ return cleanupMessagesObserver;
+ }, [cleanupMessagesObserver, getTrackedMessages, latestAssistantSignature, updateSpacerHeight]);
+
+ useEffect(() => {
+ return () => {
+ cleanupMessagesObserver();
+ clearRemoveTimer();
+ };
+ }, [cleanupMessagesObserver, clearRemoveTimer]);
+
+ return {
+ isScrollShrinking,
+ mounted,
+ mountedRef,
+ renderedHeight,
+ setMounted,
+ setScrollReduction,
+ updateSpacerHeight,
+ };
+};
+
+// ---------------------------------------------------------------------------
+// Sub-hook: pin controller
+// ---------------------------------------------------------------------------
+//
+// Owns the pin state machine. Pin is "we just sent a message and want the
+// viewport anchored to the user turn until the spacer stops resizing or the
+// user scrolls away."
+//
+// `scrollToPinned` reads `virtuaRef.current?.scrollToIndex` at call time, not
+// during render — this avoids the race where a send effect ran before the
+// ref was attached and silently dropped the scroll.
+// ---------------------------------------------------------------------------
+type PinState = { index: number; seenActive: boolean } | null;
+
+const usePinController = ({ virtuaRef }: { virtuaRef: RefObject<VListHandle | null> }) => {
+ const pinRef = useRef<PinState>(null);
+
+ const scrollToPinned = useCallback(
+ (reason: string) => {
+ const pin = pinRef.current;
+ if (!pin) return;
+
+ const scrollToIndex = virtuaRef.current?.scrollToIndex;
+ if (!scrollToIndex) {
+ log('scrollToPinned skipped: virtua not ready (%s) index=%d', reason, pin.index);
+ return;
+ }
+
+ log('scrollToPinned (%s) index=%d', reason, pin.index);
+ scrollToIndex(pin.index, { align: 'start', smooth: true });
+ },
+ [virtuaRef],
+ );
+
+ const clearPin = useCallback((reason: string) => {
+ if (!pinRef.current) return;
+ log('clearPin (%s) index=%d', reason, pinRef.current.index);
+ pinRef.current = null;
+ }, []);
+
+ return { clearPin, pinRef, scrollToPinned };
+};
+
+// ---------------------------------------------------------------------------
+// Sub-hook: scroll cancel + shrink
+// ---------------------------------------------------------------------------
+//
+// Converts raw scrollOffset deltas into pin cancellation and spacer-shrink
+// actions. Streaming vs. idle behavior is identical about canceling the pin;
+// shrinking only happens after streaming has ended so the spacer doesn't
+// fight the assistant's growth animation.
+// ---------------------------------------------------------------------------
+interface UseScrollShrinkArgs {
+ clearPin: (reason: string) => void;
+ getScrollOffset: (() => number) | undefined;
+ isAIGenerating: boolean;
+ isAIGeneratingRef: RefObject<boolean>;
+ mountedRef: RefObject<boolean>;
+ setScrollReduction: (updater: (prev: number) => number) => void;
+}
+
+const useScrollShrink = ({
+ clearPin,
+ getScrollOffset,
+ isAIGenerating,
+ isAIGeneratingRef,
+ mountedRef,
+ setScrollReduction,
+}: UseScrollShrinkArgs) => {
+ const prevScrollOffsetRef = useRef<number | null>(null);
+ const scrollShrinkEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const onScrollOffset = useCallback(
+ (currentScrollOffset: number) => {
+ const prevOffset = prevScrollOffsetRef.current;
+ prevScrollOffsetRef.current = currentScrollOffset;
+
+ const delta = prevOffset === null ? 0 : currentScrollOffset - prevOffset;
+ const { cancelPin, shrinkSpacer } = getConversationSpacerScrollEffect({
+ delta,
+ hasPrevOffset: prevOffset !== null,
+ isAIGenerating: isAIGeneratingRef.current,
+ isMounted: mountedRef.current,
+ });
+
+ if (!cancelPin) return;
+
+ clearPin('user scrolled up');
+
+ if (!shrinkSpacer) return;
+
+ setScrollReduction((prev) => prev + Math.abs(delta));
+
+ if (scrollShrinkEndTimerRef.current) clearTimeout(scrollShrinkEndTimerRef.current);
+ scrollShrinkEndTimerRef.current = setTimeout(() => {
+ scrollShrinkEndTimerRef.current = null;
+ }, SCROLL_SHRINK_END_DELAY_MS);
+ },
+ [clearPin, isAIGeneratingRef, mountedRef, setScrollReduction],
+ );
+
+ // Seed prev offset on generation flip — avoids stale deltas across streaming boundaries.
+ useEffect(() => {
+ prevScrollOffsetRef.current = getScrollOffset?.() ?? null;
+ }, [getScrollOffset, isAIGenerating]);
+
+ useEffect(() => {
+ return () => {
+ if (scrollShrinkEndTimerRef.current) clearTimeout(scrollShrinkEndTimerRef.current);
+ };
+ }, []);
+
+ return { onScrollOffset, prevScrollOffsetRef };
+};
+
+// ---------------------------------------------------------------------------
+// Main hook
+// ---------------------------------------------------------------------------
+//
+// Design notes:
+//
+// - A single `prevLengthRef` and a single send-detection effect replace the
+// two legacy hooks (`useConversationSpacer` + `useScrollToUserMessage`)
+// that each tracked length independently and could disagree across
+// renders, causing the "send but no scroll" regressions.
+// - `virtuaRef` is passed through, not `scrollToIndex`, so the pin reads the
+// ref at call time — closing the race where the ref hadn't been attached.
+// - Retries are layout-driven: each `spacerLayoutVersion` bump re-fires
+// `scrollToIndex` once. The old 0/32/96ms timer fan-out is gone.
+// ---------------------------------------------------------------------------
+export interface UseConversationScrollOptions {
+ dataSource: string[];
+ isSecondLastMessageFromUser: boolean;
+ virtuaRef: RefObject<VListHandle | null>;
+}
+
+export interface UseConversationScrollResult {
+ /**
+ * True while the user is actively dragging the spacer shorter via scroll-up.
+ * Consumers can use this to disable the spacer's height transition so it
+ * follows the pointer 1:1 instead of animating.
+ */
+ isScrollShrinking: boolean;
+ isSpacerMessage: (id: string) => boolean;
+ listData: string[];
+ onScrollOffset: (scrollOffset: number) => void;
+ registerSpacerNode: (node: HTMLElement | null) => void;
+ spacerActive: boolean;
+ spacerHeight: number;
+}
+
+export const useConversationScroll = ({
+ dataSource,
+ isSecondLastMessageFromUser,
+ virtuaRef,
+}: UseConversationScrollOptions): UseConversationScrollResult => {
+ const displayMessages = useConversationStore(dataSelectors.displayMessages);
+ 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 isAIGeneratingRef = useRef(isAIGenerating);
+ isAIGeneratingRef.current = isAIGenerating;
+
+ // State (not ref) so that downstream memos / effects re-run when a new turn
+ // is pinned. The pin indices are only set from the send-detection effect;
+ // using state keeps the observer & signature in sync on the very next
+ // render rather than waiting for an unrelated dep to change.
+ const [userMessageIndex, setUserMessageIndex] = useState<number | null>(null);
+ const [assistantMessageIndex, setAssistantMessageIndex] = useState<number | null>(null);
+ const prevLengthRef = useRef(dataSource.length);
+
+ const { registerSpacerNode, spacerLayoutVersion } = useSpacerLayoutSignal();
+
+ const latestAssistantSignature = useMemo(() => {
+ const assistantId =
+ assistantMessageIndex !== null && assistantMessageIndex >= 0
+ ? dataSource[assistantMessageIndex]
+ : null;
+ if (!assistantId) return '';
+ const assistantMessage = displayMessages.find((message) => message.id === assistantId);
+ return getRenderableTailSignature(assistantMessage);
+ }, [assistantMessageIndex, dataSource, displayMessages]);
+
+ const {
+ isScrollShrinking,
+ mounted,
+ mountedRef,
+ renderedHeight,
+ setMounted,
+ setScrollReduction,
+ updateSpacerHeight,
+ } = useSpacerHeight({
+ assistantMessageIndex,
+ dataSource,
+ getItemOffset,
+ getItemSize,
+ getViewportSize,
+ latestAssistantSignature,
+ userMessageIndex,
+ });
+
+ const { clearPin, pinRef, scrollToPinned } = usePinController({ virtuaRef });
+
+ const { onScrollOffset, prevScrollOffsetRef } = useScrollShrink({
+ clearPin,
+ getScrollOffset,
+ isAIGenerating,
+ isAIGeneratingRef,
+ mountedRef,
+ setScrollReduction,
+ });
+
+ // --- send detection: single source of truth ---
+ useEffect(() => {
+ const newMessageCount = dataSource.length - prevLengthRef.current;
+ prevLengthRef.current = dataSource.length;
+
+ if (newMessageCount !== 2 || !isSecondLastMessageFromUser) return;
+
+ const userMessage = displayMessages.at(-2);
+ const assistantMessage = displayMessages.at(-1);
+ if (userMessage?.role !== 'user' || !assistantMessage) return;
+
+ const userIndex = dataSource.length - 2;
+ const assistantIndex = dataSource.length - 1;
+
+ log('send detected userIndex=%d', userIndex);
+
+ setScrollReduction(() => 0);
+ prevScrollOffsetRef.current = getScrollOffset?.() ?? null;
+ setUserMessageIndex(userIndex);
+ setAssistantMessageIndex(assistantIndex);
+ pinRef.current = { index: userIndex, seenActive: mountedRef.current };
+
+ // Scroll immediately. If virtuaRef isn't ready yet, the spacerLayoutVersion
+ // bumps that follow mount+measurement will retry.
+ scrollToPinned('send');
+
+ requestAnimationFrame(() => {
+ updateSpacerHeight();
+ });
+ }, [
+ dataSource,
+ displayMessages,
+ getScrollOffset,
+ isSecondLastMessageFromUser,
+ mountedRef,
+ pinRef,
+ prevScrollOffsetRef,
+ scrollToPinned,
+ setScrollReduction,
+ updateSpacerHeight,
+ ]);
+
+ // --- pin re-fire: every time spacer layout settles ---
+ useEffect(() => {
+ const pin = pinRef.current;
+ if (!pin) return;
+
+ if (mounted) {
+ pin.seenActive = true;
+ }
+
+ // Once the spacer has been seen mounted and is now gone, the pin window
+ // closes — either we've reached the target or the user scrolled away.
+ if (pin.seenActive && !mounted) {
+ clearPin('spacer unmounted after activation');
+ return;
+ }
+
+ scrollToPinned('spacer layout settle');
+ }, [clearPin, mounted, pinRef, scrollToPinned, spacerLayoutVersion]);
+
+ // Collapse spacer to unmount once the user has shrunk it to zero.
+ useEffect(() => {
+ if (renderedHeight === 0 && mounted && isScrollShrinking) {
+ setMounted(false);
+ setScrollReduction(() => 0);
+ prevScrollOffsetRef.current = null;
+ }
+ }, [
+ isScrollShrinking,
+ mounted,
+ prevScrollOffsetRef,
+ renderedHeight,
+ setMounted,
+ setScrollReduction,
+ ]);
+
+ // Recompute spacer height when generation state or tail signature flips.
+ useEffect(() => {
+ if (!mounted) return;
+
+ requestAnimationFrame(() => {
+ updateSpacerHeight();
+ });
+ }, [isAIGenerating, latestAssistantSignature, mounted, updateSpacerHeight]);
+
+ const listData = useMemo(
+ () => (mounted ? [...dataSource, CONVERSATION_SPACER_ID] : dataSource),
+ [dataSource, mounted],
+ );
+
+ return {
+ isScrollShrinking,
+ isSpacerMessage: (id: string) => id === CONVERSATION_SPACER_ID,
+ listData,
+ onScrollOffset,
+ registerSpacerNode,
+ spacerActive: mounted,
+ spacerHeight: renderedHeight,
+ };
+};
diff --git a/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts b/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts
deleted file mode 100644
index f53a3d8f716..00000000000
--- a/src/features/Conversation/ChatList/hooks/useConversationSpacer.test.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import {
- calculateConversationSpacerHeight,
- CONVERSATION_SPACER_ID,
- getConversationSpacerScrollEffect,
-} from './useConversationSpacer';
-
-describe('useConversationSpacer helpers', () => {
- it('should calculate the remaining spacer height behind the latest assistant message', () => {
- expect(calculateConversationSpacerHeight(800, 200, 80)).toBe(520);
- });
-
- it('should clamp spacer height to zero when content already fills the viewport', () => {
- expect(calculateConversationSpacerHeight(800, 300, 600)).toBe(0);
- });
-
- 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
deleted file mode 100644
index edd9e94206b..00000000000
--- a/src/features/Conversation/ChatList/hooks/useConversationSpacer.ts
+++ /dev/null
@@ -1,321 +0,0 @@
-import { type AssistantContentBlock, type UIChatMessage } from '@lobechat/types';
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-
-import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
-
-export const CONVERSATION_SPACER_ID = '__conversation_spacer__';
-export const CONVERSATION_SPACER_TRANSITION_MS = 200;
-
-export const calculateConversationSpacerHeight = (
- viewportHeight: number,
- userHeight: number,
- 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;
-
- return document.querySelector(`[data-message-id="${messageId}"]`) as HTMLElement | null;
-};
-
-const getMessageHeight = (messageId: string | null) => {
- return getMessageElement(messageId)?.getBoundingClientRect().height || 0;
-};
-
-const getRenderableTailSignature = (message: UIChatMessage | undefined) => {
- if (!message) return '';
-
- const tailBlock: AssistantContentBlock | UIChatMessage =
- message.children && message.children.length > 0 ? message.children.at(-1)! : message;
-
- const contentLength = tailBlock.content?.length || 0;
- const reasoningLength = tailBlock.reasoning?.content?.length || 0;
- const toolCount = tailBlock.tools?.length || 0;
-
- return `${contentLength}:${reasoningLength}:${toolCount}:${message.updatedAt || 0}`;
-};
-
-export const useConversationSpacer = (dataSource: string[]) => {
- const displayMessages = useConversationStore(dataSelectors.displayMessages);
- 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);
- const resizeObserverRef = useRef<ResizeObserver | null>(null);
- const spacerObserverRef = useRef<ResizeObserver | null>(null);
- const userMessageIndexRef = useRef<number | null>(null);
- const assistantMessageIndexRef = useRef<number | null>(null);
-
- // Refs for scroll-shrink feature (stable callback access)
- const mountedRef = useRef(false);
- mountedRef.current = mounted;
- const isAIGeneratingRef = useRef(isAIGenerating);
- isAIGeneratingRef.current = isAIGenerating;
- const prevScrollOffsetRef = useRef<number | null>(null);
- const scrollShrinkEndTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- // Derived rendered height: natural height minus user scroll reduction
- const renderedHeight = Math.max(naturalHeight - scrollReduction, 0);
- const isScrollShrinking = scrollReduction > 0;
-
- const getTrackedMessages = useCallback(() => {
- const userIndex = userMessageIndexRef.current;
- const assistantIndex = assistantMessageIndexRef.current;
-
- return {
- assistantId:
- assistantIndex !== null && assistantIndex >= 0 ? dataSource[assistantIndex] || null : null,
- assistantIndex,
- userId: userIndex !== null && userIndex >= 0 ? dataSource[userIndex] || null : null,
- userIndex,
- };
- }, [dataSource]);
-
- const latestAssistantSignature = (() => {
- const { assistantId } = getTrackedMessages();
- if (!assistantId) return '';
-
- const assistantMessage = displayMessages.find((message) => message.id === assistantId);
- return getRenderableTailSignature(assistantMessage);
- })();
-
- const clearRemoveTimer = useCallback(() => {
- if (removeTimerRef.current) {
- clearTimeout(removeTimerRef.current);
- removeTimerRef.current = null;
- }
- }, []);
-
- const cleanupObserver = useCallback(() => {
- resizeObserverRef.current?.disconnect();
- resizeObserverRef.current = null;
- }, []);
-
- const cleanupSpacerObserver = useCallback(() => {
- spacerObserverRef.current?.disconnect();
- spacerObserverRef.current = null;
- }, []);
-
- const scheduleUnmount = useCallback(() => {
- clearRemoveTimer();
-
- removeTimerRef.current = setTimeout(() => {
- setMounted(false);
- removeTimerRef.current = null;
- }, CONVERSATION_SPACER_TRANSITION_MS);
- }, [clearRemoveTimer]);
-
- const updateSpacerHeight = useCallback(() => {
- clearRemoveTimer();
- const { assistantId, assistantIndex, userId, userIndex } = getTrackedMessages();
- const viewportHeight = getViewportSize?.() || window.innerHeight;
-
- let nextHeight: number;
-
- if (userIndex !== null && assistantIndex !== null && getItemOffset && getItemSize) {
- const userTop = getItemOffset(userIndex);
- const assistantBottom = getItemOffset(assistantIndex) + getItemSize(assistantIndex);
-
- nextHeight = Math.max(Math.round(viewportHeight - (assistantBottom - userTop)), 0);
- } else {
- const userHeight = getMessageHeight(userId);
- if (!userHeight) return;
-
- const assistantHeight = getMessageHeight(assistantId);
-
- nextHeight = calculateConversationSpacerHeight(viewportHeight, userHeight, assistantHeight);
- }
-
- if (nextHeight === 0) {
- setNaturalHeight(0);
- scheduleUnmount();
- return;
- }
-
- setMounted(true);
- setNaturalHeight(nextHeight);
- }, [
- clearRemoveTimer,
- getTrackedMessages,
- getItemOffset,
- getItemSize,
- getViewportSize,
- scheduleUnmount,
- ]);
-
- // Reset prev scroll offset when generation state changes to avoid stale deltas
- useEffect(() => {
- 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;
-
- const delta = prevOffset === null ? 0 : currentScrollOffset - prevOffset;
- const { cancelPin, shrinkSpacer } = getConversationSpacerScrollEffect({
- delta,
- hasPrevOffset: prevOffset !== null,
- isAIGenerating: isAIGeneratingRef.current,
- isMounted: mountedRef.current,
- });
-
- if (!cancelPin) return;
-
- if (userMessageIndexRef.current !== null) {
- setCancelPinMessageIndex(userMessageIndexRef.current);
- }
- if (!shrinkSpacer) return;
-
- setScrollReduction((prev) => prev + Math.abs(delta));
-
- if (scrollShrinkEndTimerRef.current) clearTimeout(scrollShrinkEndTimerRef.current);
- scrollShrinkEndTimerRef.current = setTimeout(() => {
- scrollShrinkEndTimerRef.current = null;
- }, 150);
- }, []);
-
- // Unmount when rendered height reaches zero via scroll reduction
- useEffect(() => {
- if (renderedHeight === 0 && mounted && scrollReduction > 0) {
- setMounted(false);
- setScrollReduction(0);
- prevScrollOffsetRef.current = null;
- }
- }, [renderedHeight, mounted, scrollReduction]);
-
- useEffect(() => {
- return () => {
- cleanupObserver();
- cleanupSpacerObserver();
- clearRemoveTimer();
- if (scrollShrinkEndTimerRef.current) clearTimeout(scrollShrinkEndTimerRef.current);
- };
- }, [cleanupObserver, cleanupSpacerObserver, clearRemoveTimer]);
-
- // Ref callback bound to this hook's own spacer node. Using a ref (rather than
- // a document-wide querySelector) scopes observation to the spacer owned by
- // this list instance — ConversationProvider supports multiple simultaneously
- // mounted lists, so a global selector could attach to another panel's spacer
- // and drive spacerLayoutVersion from unrelated layout changes.
- const registerSpacerNode = useCallback(
- (node: HTMLElement | null) => {
- cleanupSpacerObserver();
-
- if (!node || typeof ResizeObserver === 'undefined') return;
-
- const observer = new ResizeObserver(() => {
- setSpacerLayoutVersion((v) => v + 1);
- });
- observer.observe(node);
- spacerObserverRef.current = observer;
- setSpacerLayoutVersion((v) => v + 1);
- },
- [cleanupSpacerObserver],
- );
-
- useEffect(() => {
- const newMessageCount = dataSource.length - prevLengthRef.current;
- prevLengthRef.current = dataSource.length;
-
- const userMessage = displayMessages.at(-2);
- const assistantMessage = displayMessages.at(-1);
-
- if (newMessageCount !== 2 || userMessage?.role !== 'user' || !assistantMessage) return;
-
- setCancelPinMessageIndex(null);
- setScrollReduction(0);
- prevScrollOffsetRef.current = getScrollOffset?.() ?? null;
- userMessageIndexRef.current = dataSource.length - 2;
- assistantMessageIndexRef.current = dataSource.length - 1;
-
- requestAnimationFrame(() => {
- updateSpacerHeight();
- });
- }, [dataSource.length, displayMessages, getScrollOffset, updateSpacerHeight]);
-
- useEffect(() => {
- const { assistantId, userId } = getTrackedMessages();
-
- cleanupObserver();
-
- if (!assistantId || !userId || typeof ResizeObserver === 'undefined') return;
-
- const observer = new ResizeObserver(() => {
- requestAnimationFrame(() => {
- updateSpacerHeight();
- });
- });
-
- resizeObserverRef.current = observer;
-
- const userEl = getMessageElement(userId);
- const assistantEl = getMessageElement(assistantId);
-
- if (userEl) observer.observe(userEl);
- if (assistantEl) observer.observe(assistantEl);
-
- requestAnimationFrame(() => {
- updateSpacerHeight();
- });
-
- return cleanupObserver;
- }, [cleanupObserver, getTrackedMessages, latestAssistantSignature, updateSpacerHeight]);
-
- useEffect(() => {
- if (!mounted) return;
-
- requestAnimationFrame(() => {
- updateSpacerHeight();
- });
- }, [isAIGenerating, latestAssistantSignature, mounted, updateSpacerHeight]);
-
- const listData = useMemo(
- () => (mounted ? [...dataSource, CONVERSATION_SPACER_ID] : dataSource),
- [dataSource, mounted],
- );
-
- return {
- handleScrollOffset,
- isSpacerMessage: (id: string) => id === CONVERSATION_SPACER_ID,
- listData,
- registerSpacerNode,
- cancelPinMessageIndex,
- scrollShrinking: isScrollShrinking,
- spacerActive: mounted,
- spacerHeight: renderedHeight,
- spacerLayoutVersion,
- };
-};
diff --git a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
deleted file mode 100644
index 750d498af2c..00000000000
--- a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.test.ts
+++ /dev/null
@@ -1,574 +0,0 @@
-import { act, renderHook } from '@testing-library/react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { useScrollToUserMessage } from './useScrollToUserMessage';
-
-type Props = {
- cancelPinMessageIndex?: number | null;
- dataSourceLength: number;
- isSecondLastMessageFromUser: boolean;
- scrollShrinking?: boolean;
- spacerActive: boolean;
- spacerLayoutVersion?: number;
-};
-
-const makeRender = (scrollToIndex: ReturnType<typeof vi.fn> | null, initialProps: Props) =>
- renderHook(
- (props: Props) =>
- useScrollToUserMessage({
- cancelPinMessageIndex: props.cancelPinMessageIndex,
- dataSourceLength: props.dataSourceLength,
- isSecondLastMessageFromUser: props.isSecondLastMessageFromUser,
- scrollShrinking: props.scrollShrinking,
- scrollToIndex,
- spacerActive: props.spacerActive,
- spacerLayoutVersion: props.spacerLayoutVersion,
- }),
- { initialProps },
- );
-
-describe('useScrollToUserMessage', () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- describe('when user sends a new message', () => {
- it('should retry scrolling to user message when 2 new messages are added and spacer is active', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- // send-triggered retries + spacerActive follow-up fire in the same tick;
- // executeScroll clears prior pending timers so only the last retry wave runs.
- expect(scrollToIndex).toHaveBeenCalledTimes(3);
- expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
- });
-
- it('should scroll immediately and re-scroll when spacer becomes active', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).toHaveBeenCalledTimes(3);
- expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
-
- scrollToIndex.mockClear();
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).toHaveBeenCalledTimes(3);
- expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
- });
-
- it('should re-scroll whenever spacerLayoutVersion bumps while active', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- // user sends message; spacer becomes active
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
- scrollToIndex.mockClear();
-
- // spacer DOM is measured; version bumps -> should re-fire scroll
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 1,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).toHaveBeenCalledTimes(3);
- expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
- });
-
- it('should stop re-scrolling once the spacer unmounts', () => {
- 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();
-
- // spacer unmounts -> pending cleared
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 1,
- });
-
- // a subsequent version bump with spacer gone must not re-scroll
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 2,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should cancel queued retry timers when user scrolls up before they fire', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- // user sends message -> 0/32/96ms retry timers are scheduled but not fired yet
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- // user immediately starts scrolling up before any retry timer fires
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- scrollShrinking: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- // no queued retry should have yanked the viewport back
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should cancel queued retry timers when spacer unmounts before they fire', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- // spacer unmounts before any retry timer fires
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should stop pinning when user starts shrinking the spacer manually', () => {
- 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();
-
- // user scrolls up -> scrollShrinking true, pending cleared
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- scrollShrinking: true,
- spacerActive: true,
- spacerLayoutVersion: 1,
- });
-
- // even if layout keeps ticking, we must not pin back to top
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- scrollShrinking: true,
- spacerActive: true,
- spacerLayoutVersion: 2,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- 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();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).toHaveBeenCalledTimes(3);
- expect(scrollToIndex).toHaveBeenNthCalledWith(1, 2, { align: 'start', smooth: true });
- });
-
- it('should scroll to correct index when multiple user messages are sent', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 6,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- act(() => {
- vi.runAllTimers();
- });
-
- expect(scrollToIndex).toHaveBeenNthCalledWith(1, 4, { align: 'start', smooth: true });
- });
- });
-
- describe('when AI/agent responds', () => {
- it('should NOT scroll when only 1 new message is added (AI response)', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 5,
- isSecondLastMessageFromUser: false,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should NOT scroll when multiple agents respond in group chat', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 5,
- isSecondLastMessageFromUser: false,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
-
- rerender({
- dataSourceLength: 6,
- isSecondLastMessageFromUser: false,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should NOT scroll when 2 messages added but second-to-last is not user', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 6,
- isSecondLastMessageFromUser: false,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
- });
-
- describe('edge cases', () => {
- it('should NOT scroll when length decreases (message deleted)', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 6,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should NOT scroll when length stays the same', () => {
- const scrollToIndex = vi.fn();
-
- const { rerender } = makeRender(scrollToIndex, {
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
-
- it('should handle null scrollToIndex gracefully', () => {
- const { rerender } = makeRender(null, {
- dataSourceLength: 2,
- isSecondLastMessageFromUser: false,
- spacerActive: false,
- spacerLayoutVersion: 0,
- });
-
- expect(() => {
- rerender({
- dataSourceLength: 4,
- isSecondLastMessageFromUser: true,
- spacerActive: true,
- spacerLayoutVersion: 0,
- });
- }).not.toThrow();
- });
-
- it('should NOT scroll on initial render', () => {
- const scrollToIndex = vi.fn();
-
- renderHook(() =>
- useScrollToUserMessage({
- dataSourceLength: 6,
- isSecondLastMessageFromUser: true,
- scrollToIndex,
- spacerActive: true,
- spacerLayoutVersion: 0,
- }),
- );
-
- expect(scrollToIndex).not.toHaveBeenCalled();
- });
- });
-});
diff --git a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts b/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
deleted file mode 100644
index 7369a6e25ce..00000000000
--- a/src/features/Conversation/ChatList/hooks/useScrollToUserMessage.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-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)
- */
- dataSourceLength: number;
- /**
- * Whether the second-to-last message is from the user
- * (When sending a message, user + assistant messages are created as a pair)
- */
- isSecondLastMessageFromUser: boolean;
- /**
- * User is manually shrinking the spacer (scrolled up). When true, stop pinning
- * so we don't fight the user's scroll.
- */
- scrollShrinking?: boolean;
- /**
- * Function to scroll to a specific index
- */
- scrollToIndex:
- | ((index: number, options?: { align?: 'start' | 'center' | 'end'; smooth?: boolean }) => void)
- | null;
- /**
- * Whether the conversation spacer is mounted and providing fill height.
- * When the spacer mounts after the initial scroll, a follow-up scroll is
- * fired so the user message lands at the correct position once the extra
- * height is available.
- */
- spacerActive: boolean;
- /**
- * A counter that increments each time the spacer DOM's real size changes
- * (observed via ResizeObserver). Used as a layout-settled signal so we can
- * re-fire scrollToIndex after virtua finishes measuring the spacer and
- * scrollSize expands enough to let the user message reach the top.
- */
- spacerLayoutVersion?: number;
-}
-
-/**
- * Hook to handle scrolling to user message when user sends a new message.
- * Only triggers scroll when user sends a new message (detected by checking if
- * 2 new messages were added and the second-to-last is from user).
- *
- * Scrolls immediately on message send (works when content already fills the
- * viewport). When a conversation spacer mounts afterwards and its DOM is
- * measured by virtua, scrollSize expands and we re-fire scroll so the user
- * message lands correctly. The pending state clears when the spacer unmounts
- * or the user starts scrolling manually.
- */
-export function useScrollToUserMessage({
- cancelPinMessageIndex = null,
- dataSourceLength,
- isSecondLastMessageFromUser,
- scrollToIndex,
- scrollShrinking = false,
- spacerActive,
- spacerLayoutVersion = 0,
-}: UseScrollToUserMessageOptions): void {
- const prevLengthRef = useRef(dataSourceLength);
- const timerIdsRef = useRef<number[]>([]);
- // Index of the user message that needs to be scrolled to, or null if no pending scroll
- const pendingScrollIndexRef = useRef<number | null>(null);
-
- const clearPendingPins = useCallback(() => {
- timerIdsRef.current.forEach((timerId) => {
- window.clearTimeout(timerId);
- });
- timerIdsRef.current = [];
- }, []);
-
- const executeScroll = useCallback(
- (userMessageIndex: number) => {
- if (!scrollToIndex) return;
-
- clearPendingPins();
-
- PIN_RETRY_DELAYS.forEach((delay) => {
- const timerId = window.setTimeout(() => {
- scrollToIndex(userMessageIndex, {
- align: 'start',
- smooth: true,
- });
- }, delay);
-
- timerIdsRef.current.push(timerId);
- });
- },
- [clearPendingPins, scrollToIndex],
- );
-
- useEffect(() => {
- return clearPendingPins;
- }, [clearPendingPins]);
-
- // Detect when user sends a new message and scroll immediately
- useEffect(() => {
- const newMessageCount = dataSourceLength - prevLengthRef.current;
- prevLengthRef.current = dataSourceLength;
-
- // Only scroll when user sends a new message (2 messages added: user + assistant pair)
- if (newMessageCount === 2 && isSecondLastMessageFromUser && scrollToIndex) {
- const userMessageIndex = dataSourceLength - 2;
-
- // Always scroll immediately – works when content already fills the viewport.
- // Also store the index so follow-up scrolls can fire as the spacer settles.
- pendingScrollIndexRef.current = userMessageIndex;
- executeScroll(userMessageIndex);
- }
- }, [dataSourceLength, isSecondLastMessageFromUser, scrollToIndex, executeScroll]);
-
- // Clear pending scroll when the spacer unmounts or user scrolls manually so
- // subsequent layout ticks don't keep pinning against the user's intent.
- // Also cancel any already-scheduled retry timers — otherwise a pin wave
- // fired just before the user scrolled up would still call scrollToIndex at
- // 32/96ms and yank the viewport back down.
- useEffect(() => {
- const pendingScrollIndex = pendingScrollIndexRef.current;
- const pinCanceledByUserScroll =
- pendingScrollIndex !== null && cancelPinMessageIndex === pendingScrollIndex;
-
- if (!spacerActive || scrollShrinking || pinCanceledByUserScroll) {
- pendingScrollIndexRef.current = null;
- 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(() => {
- const index = pendingScrollIndexRef.current;
- const pinCanceledByUserScroll = index !== null && cancelPinMessageIndex === index;
-
- if (!spacerActive || scrollShrinking || pinCanceledByUserScroll) return;
- if (index === null) return;
- executeScroll(index);
- }, [cancelPinMessageIndex, spacerActive, spacerLayoutVersion, scrollShrinking, executeScroll]);
-}
diff --git a/src/features/Conversation/store/slices/data/selectors.ts b/src/features/Conversation/store/slices/data/selectors.ts
index 9bcebc372e9..fdc82e535b0 100644
--- a/src/features/Conversation/store/slices/data/selectors.ts
+++ b/src/features/Conversation/store/slices/data/selectors.ts
@@ -122,6 +122,8 @@ const currentTopicSummary = () => {
const pendingInterventions = (s: State) => getPendingInterventions(s.displayMessages);
+const isSecondLastMessageFromUser = (s: State) => s.displayMessages.at(-2)?.role === 'user';
+
export const dataSelectors = {
currentTopicSummary,
dbMessages,
@@ -132,6 +134,7 @@ export const dataSelectors = {
getDbMessageByToolCallId,
getDisplayMessageById,
getGroupLatestMessageWithoutTools,
+ isSecondLastMessageFromUser,
messagesInit,
pendingInterventions,
skipFetch,