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): restore the slide when a sent message pins to the top (#19264)

Innei0382b49ea2cf
diff --git a/e2e/src/features/journeys/agent/agent-scroll.feature b/e2e/src/features/journeys/agent/agent-scroll.feature
index 081e2c480e4..79acd147fed 100644
--- a/e2e/src/features/journeys/agent/agent-scroll.feature
+++ b/e2e/src/features/journeys/agent/agent-scroll.feature
@@ -44,6 +44,18 @@ Feature: 发送消息与流式输出期间的视口滚动行为
When 用户发送一条触发长文输出的消息
Then 用户消息应固定在聊天列表顶部
+ # Regression guard for the lost pin animation: the send scroll fires before
+ # the spacer row exists and gets clamped, so the visible slide is the settle
+ # re-pin after mount. An instant re-pin there turns the slide into a jump.
+ @AGENT-SCROLL-007 @P0 @journey
+ Scenario: 发送消息后,用户消息以多帧平滑滚动过渡到列表顶部
+ Given 流式响应被放慢以模拟长文输出
+ And 用户进入 Lobe AI 对话页面
+ When 用户完成一轮用于垫高列表的长回复对话
+ And 开始记录聊天列表滚动轨迹
+ And 用户发送一条触发长文输出的消息
+ 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.
diff --git a/e2e/src/probes/scrollTrace.test.ts b/e2e/src/probes/scrollTrace.test.ts
new file mode 100644
index 00000000000..a77170ce3df
--- /dev/null
+++ b/e2e/src/probes/scrollTrace.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+
+import { classifyScrollTrace } from './scrollTrace';
+
+describe('classifyScrollTrace', () => {
+ it('reports a multi-frame monotonic descent as a slide', () => {
+ const samples = [0, 0, 6, 17, 27, 51, 67, 148, 236, 314, 449, 600, 600, 600];
+
+ expect(classifyScrollTrace(samples).motion).toBe('slide');
+ });
+
+ it('reports a single-frame landing as a jump', () => {
+ const samples = [0, 0, 0, 600, 600, 600];
+
+ expect(classifyScrollTrace(samples).motion).toBe('jump');
+ });
+
+ it('reports a clamped stub followed by an instant landing as a jump', () => {
+ const samples = [0, 3, 8, 12, 12, 600, 600];
+
+ expect(classifyScrollTrace(samples).motion).toBe('jump');
+ });
+
+ it('reports no movement as none', () => {
+ expect(classifyScrollTrace([120, 120, 120]).motion).toBe('none');
+ });
+});
diff --git a/e2e/src/probes/scrollTrace.ts b/e2e/src/probes/scrollTrace.ts
new file mode 100644
index 00000000000..17b3efd4d8f
--- /dev/null
+++ b/e2e/src/probes/scrollTrace.ts
@@ -0,0 +1,67 @@
+import type { Page } from '@playwright/test';
+
+export type ScrollMotion = 'jump' | 'none' | 'slide';
+
+export interface ScrollTraceSummary {
+ frames: number;
+ largestFrameDelta: number;
+ motion: ScrollMotion;
+ movingFrames: number;
+ travel: number;
+}
+
+const TRACE_KEY = '__lobehubE2EScrollTrace';
+const MIN_SLIDE_FRAMES = 4;
+const JUMP_SHARE = 0.9;
+
+export const classifyScrollTrace = (samples: number[]): ScrollTraceSummary => {
+ const deltas = samples.slice(1).map((value, i) => value - samples[i]);
+ const moving = deltas.filter((d) => d !== 0);
+ const travel = Math.abs(samples.at(-1)! - samples[0]);
+ const largestFrameDelta = Math.max(0, ...moving.map(Math.abs));
+
+ let motion: ScrollMotion = 'none';
+ if (travel > 0) {
+ const oneFrameJump = largestFrameDelta >= travel * JUMP_SHARE;
+ motion = !oneFrameJump && moving.length >= MIN_SLIDE_FRAMES ? 'slide' : 'jump';
+ }
+
+ return { frames: samples.length, largestFrameDelta, motion, movingFrames: moving.length, travel };
+};
+
+// Injected as source text: the tsx/esbuild transform wraps named inner
+// functions in a `__name` helper that does not exist in the page.
+const START_SCRIPT = `(() => {
+ const key = ${JSON.stringify(TRACE_KEY)};
+ if (window[key]) cancelAnimationFrame(window[key].raf);
+ const trace = { raf: 0, samples: [] };
+ const tick = () => {
+ let el = document.querySelector('.message-wrapper');
+ while (el) {
+ const overflowY = getComputedStyle(el).overflowY;
+ if (overflowY === 'auto' || overflowY === 'scroll') break;
+ el = el.parentElement;
+ }
+ trace.samples.push(el ? el.scrollTop : NaN);
+ trace.raf = requestAnimationFrame(tick);
+ };
+ trace.raf = requestAnimationFrame(tick);
+ window[key] = trace;
+})()`;
+
+const STOP_SCRIPT = `(() => {
+ const key = ${JSON.stringify(TRACE_KEY)};
+ const trace = window[key];
+ if (!trace) return [];
+ cancelAnimationFrame(trace.raf);
+ delete window[key];
+ return trace.samples.filter((v) => !Number.isNaN(v));
+})()`;
+
+export const startScrollTrace = async (page: Page): Promise<void> => {
+ await page.evaluate(START_SCRIPT);
+};
+
+export const stopScrollTrace = async (page: Page): Promise<number[]> => {
+ return page.evaluate<number[]>(STOP_SCRIPT);
+};
diff --git a/e2e/src/steps/agent/scroll.steps.ts b/e2e/src/steps/agent/scroll.steps.ts
index d1e1f38d4ff..05d4c91fc27 100644
--- a/e2e/src/steps/agent/scroll.steps.ts
+++ b/e2e/src/steps/agent/scroll.steps.ts
@@ -13,6 +13,7 @@ import { After, Given, Then, When } from '@cucumber/cucumber';
import { expect } from '@playwright/test';
import { llmMockManager, presetResponses } from '../../mocks/llm';
+import { classifyScrollTrace, startScrollTrace, stopScrollTrace } from '../../probes/scrollTrace';
import type { CustomWorld } from '../../support/world';
// How close to the scroll container's bottom is considered "at bottom".
@@ -335,6 +336,10 @@ When('用户在流式响应进行中向上滚动 {int} 像素', async function (
await this.page.waitForTimeout(400);
});
+When('开始记录聊天列表滚动轨迹', async function (this: CustomWorld) {
+ await startScrollTrace(this.page);
+});
+
When('等待流式响应结束', { timeout: 60_000 }, async function (this: CustomWorld) {
await waitForAssistantMessageToSettle(this, 200);
});
@@ -423,6 +428,22 @@ Then('用户消息应固定在聊天列表顶部', async function (this: CustomW
.toBeLessThanOrEqual(PIN_SLACK);
});
+Then('聊天列表应以多帧平滑滚动把用户消息顶到顶部', async function (this: CustomWorld) {
+ const PIN_SLACK = 150;
+ await expect
+ .poll(
+ async () => {
+ const rect = await measurePinDelta(this);
+ return rect ? Math.abs(rect.delta) : null;
+ },
+ { message: 'latest user message did not reach the pinned position', timeout: 5000 },
+ )
+ .toBeLessThanOrEqual(PIN_SLACK);
+
+ const summary = classifyScrollTrace(await stopScrollTrace(this.page));
+ expect(summary, `scroll trace: ${JSON.stringify(summary)}`).toMatchObject({ motion: 'slide' });
+});
+
Then('聊天列表底部补偿区域高度不应收缩', async function (this: CustomWorld) {
const before = this.testContext.scrollCompensationHeight as number | undefined;
expect(before, 'missing recorded bottom compensation height').toBeDefined();
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
index 17bbf18709a..cfc3b4bd653 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts
@@ -398,10 +398,35 @@ describe('useConversationScroll — pin behavior', () => {
expect(scrollToIndex).not.toHaveBeenCalled();
});
+ // Regression: the send scroll fires before the spacer row exists and gets
+ // clamped by virtua, so the visible slide is the settle re-pin after mount.
+ // An instant re-pin there aborts the animation (the "no slide" bug).
+ it('keeps settle re-pins smooth right after send', () => {
+ const { result, rerender } = renderScrollHook({
+ dataSource: [assistantId, 'prev'],
+ isSecondLastMessageFromUser: false,
+ });
+
+ rerender({
+ dataSource: ['m0', 'm1', userId, assistantId],
+ isSecondLastMessageFromUser: true,
+ });
+ expect(scrollToIndex).toHaveBeenCalledWith(2, { align: 'start', smooth: true });
+ scrollToIndex.mockClear();
+
+ vi.advanceTimersByTime(100);
+ const spacerNode = document.createElement('div');
+ act(() => {
+ result.current.registerSpacerNode(spacerNode);
+ });
+
+ expect(scrollToIndex).toHaveBeenCalledWith(2, { align: 'start', smooth: true });
+ });
+
// Regression: settle re-pins fire while the content height is still changing
// (e.g. a workflow collapse at turn completion). A smooth scroll there is
- // itself a visible slide, so only the initial send scroll may animate.
- it('re-pins without smooth scrolling once the spacer layout settles', () => {
+ // itself a visible slide, so late re-pins must land instantly.
+ it('re-pins without smooth scrolling once the send animation window has passed', () => {
const { result, rerender } = renderScrollHook({
dataSource: [assistantId, 'prev'],
isSecondLastMessageFromUser: false,
@@ -411,11 +436,9 @@ describe('useConversationScroll — pin behavior', () => {
dataSource: ['m0', 'm1', userId, assistantId],
isSecondLastMessageFromUser: true,
});
- expect(scrollToIndex).toHaveBeenCalledWith(2, { align: 'start', smooth: true });
scrollToIndex.mockClear();
- // Registering the spacer node bumps spacerLayoutVersion, which is the
- // "layout settled" beat the pin controller retries on.
+ vi.advanceTimersByTime(1000);
const spacerNode = document.createElement('div');
act(() => {
result.current.registerSpacerNode(spacerNode);
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
index 1b175a6b42c..fac186bce74 100644
--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts
@@ -20,8 +20,12 @@ export const CONVERSATION_SPACER_TRANSITION_MS = 200;
const SCROLL_SHRINK_END_DELAY_MS = 150;
-/** The one `scrollToPinned` reason that is allowed to animate — see `scrollToPinned`. */
-const SEND_SCROLL_REASON = 'send';
+// The send scroll fires before the spacer row exists, so virtua clamps it and
+// the slide really happens on the settle re-pins that follow mount. Those must
+// stay smooth too, otherwise their instant `scroll()` aborts the in-flight
+// animation. Settles after this window (e.g. the workflow collapse at turn
+// completion) must stay instant so the correction is imperceptible.
+const SEND_SCROLL_ANIMATION_WINDOW_MS = 800;
// -------- pure helpers --------
@@ -293,7 +297,7 @@ const useSpacerHeight = ({
// 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;
+type PinState = { index: number; seenActive: boolean; sentAt: number } | null;
const usePinController = ({
headerOffset,
@@ -315,11 +319,7 @@ const usePinController = ({
return;
}
- // Only the initial send scroll animates. Settle re-pins fire while the
- // content height is still changing (e.g. the workflow collapse at turn
- // completion); a smooth scroll there is itself a visible slide, so the
- // correction must land in the same frame to stay imperceptible.
- const smooth = reason === SEND_SCROLL_REASON;
+ const smooth = Date.now() - pin.sentAt < SEND_SCROLL_ANIMATION_WINDOW_MS;
log('scrollToPinned (%s) index=%d smooth=%s', reason, pin.index, smooth);
// pin.index is a message index; the header slot row shifts virtua rows.
@@ -564,11 +564,11 @@ export const useConversationScroll = ({
prevScrollOffsetRef.current = getScrollOffset?.() ?? null;
setUserMessageIndex(userIndex);
setAssistantMessageIndex(assistantIndex);
- pinRef.current = { index: userIndex, seenActive: mountedRef.current };
+ pinRef.current = { index: userIndex, seenActive: mountedRef.current, sentAt: Date.now() };
// Scroll immediately. If virtuaRef isn't ready yet, the spacerLayoutVersion
// bumps that follow mount+measurement will retry.
- scrollToPinned(SEND_SCROLL_REASON);
+ scrollToPinned('send');
requestAnimationFrame(() => {
updateSpacerHeight();