π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(chat): preserve sent-turn scroll and restore 500-row history pages (#22030)
Inneib8b872752763
diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.tsindex 4d178616114..3be6b22327c 100644--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.test.ts@@ -1,6 +1,7 @@/*** @vitest-environment happy-dom*/+import type { UIChatMessage } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { createRef, type RefObject } from 'react';import { type VListHandle } from 'virtua';@@ -117,7 +118,9 @@ describe('useConversationScroll β pin behavior', () => {* to verify "user + assistant pair was just appended".*/type StoreFixture = {- displayMessages: Array<{ id: string; role: 'user' | 'assistant' }>;+ displayMessages: Array<+ Pick<UIChatMessage, 'id' | 'role'> & Partial<Pick<UIChatMessage, 'extra' | 'parentId'>>+ >;hasLaterMessages?: boolean;isAIGenerating: boolean;virtuaScrollMethods: {@@ -194,14 +197,16 @@ describe('useConversationScroll β pin behavior', () => {const rerender = (next: {contextKey?: string;dataSource: string[];+ fixture?: Partial<StoreFixture>;hasLaterMessages?: boolean;isSecondLastMessageFromUser: boolean;}) => {- const { hasLaterMessages, ...props } = next;+ const { fixture, hasLaterMessages, ...props } = next;currentFixture = {...currentFixture,displayMessages: deriveDisplayMessages(next.isSecondLastMessageFromUser),hasLaterMessages: hasLaterMessages ?? currentFixture.hasLaterMessages,+ ...fixture,};hook.rerender({ contextKey: undefined, ...props });};@@ -286,6 +291,132 @@ describe('useConversationScroll β pin behavior', () => {expect(scrollToIndex).not.toHaveBeenCalled();});+ it('keeps a sent turn pinned when an earlier history page arrives', async () => {+ let offsets = [0, 100, 200, 350];+ let sizes = [100, 100, 150, 100];+ const { result, rerender } = renderScrollHook({+ dataSource: ['m0', 'm1'],+ fixture: {+ virtuaScrollMethods: {+ getItemOffset: (index) => offsets[index],+ getItemSize: (index) => sizes[index],+ getViewportSize: () => 800,+ },+ },+ isSecondLastMessageFromUser: false,+ });++ rerender({+ dataSource: ['m0', 'm1', userId, assistantId],+ isSecondLastMessageFromUser: true,+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(32);+ });+ expect(result.current.spacerHeight).toBe(550);+ scrollToIndex.mockClear();++ offsets = [0, 50, 100, 200, 3000, 3150];+ sizes = [50, 50, 100, 2800, 150, 100];+ rerender({+ dataSource: ['older-user', 'older-assistant', 'm0', 'm1', userId, assistantId],+ isSecondLastMessageFromUser: true,+ });+ expect(scrollToIndex).not.toHaveBeenCalled();++ act(() => {+ result.current.registerSpacerNode(document.createElement('div'));+ });++ expect(scrollToIndex).toHaveBeenLastCalledWith(4, { align: 'start', smooth: true });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(32);+ });+ expect(result.current.spacerHeight).toBe(550);+ });++ it.each(['assistant', 'assistantGroup', 'agentCouncil', 'supervisor'] as const)(+ 'remeasures a regenerated %s reply as it grows',+ async (role) => {+ let assistantHeight = 100;+ const replacementId = 'replacement-assistant';+ const userNode = document.createElement('div');+ userNode.dataset.messageId = userId;+ userNode.getBoundingClientRect = () => ({ height: 150 }) as DOMRect;+ const replacementNode = document.createElement('div');+ replacementNode.dataset.messageId = replacementId;+ replacementNode.getBoundingClientRect = () => ({ height: assistantHeight }) as DOMRect;+ document.body.append(userNode);++ try {+ const { result, rerender } = renderScrollHook({+ dataSource: ['m0', 'm1'],+ fixture: {+ virtuaScrollMethods: {+ getItemOffset: (index) => [0, 100, 200, 350][index],+ getItemSize: (index) => (index === 3 ? assistantHeight : 150),+ getViewportSize: () => 800,+ },+ },+ isSecondLastMessageFromUser: false,+ });+ rerender({+ dataSource: ['m0', 'm1', userId, assistantId],+ isSecondLastMessageFromUser: true,+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(32);+ });+ expect(result.current.spacerHeight).toBe(550);++ // Regeneration leaves the user alone before its new branch is rendered.+ rerender({+ dataSource: ['m0', 'm1', userId],+ fixture: {+ displayMessages: [{ id: userId, role: 'user' }],+ isAIGenerating: true,+ },+ isSecondLastMessageFromUser: false,+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(32);+ });+ expect(result.current.spacerHeight).toBe(650);++ document.body.append(replacementNode);+ rerender({+ dataSource: ['m0', 'm1', userId, replacementId],+ fixture: {+ displayMessages: [+ { id: userId, role: 'user' },+ role === 'agentCouncil'+ ? { extra: { parentMessageId: userId }, id: replacementId, role }+ : { id: replacementId, parentId: userId, role },+ ],+ },+ isSecondLastMessageFromUser: true,+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(32);+ });+ expect(result.current.spacerHeight).toBe(550);++ assistantHeight = 700;+ act(() => {+ const observer = MockResizeObserver.latest;+ if (observer?.observed.includes(replacementNode)) observer.trigger();+ });+ await act(async () => {+ await vi.advanceTimersByTimeAsync(32);+ });+ expect(result.current.spacerHeight).toBe(0);+ } finally {+ userNode.remove();+ replacementNode.remove();+ }+ },+ );+it('does not scroll when only the assistant message is appended', () => {const { rerender } = renderScrollHook({dataSource: [userId, assistantId],diff --git a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts b/src/features/Conversation/ChatList/hooks/useConversationScroll.tsindex d057573b7da..410d2c67566 100644--- a/src/features/Conversation/ChatList/hooks/useConversationScroll.ts+++ b/src/features/Conversation/ChatList/hooks/useConversationScroll.ts@@ -297,40 +297,46 @@ 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; sentAt: number } | null;+type PinState = { messageId: string; seenActive: boolean; sentAt: number } | null;const usePinController = ({+ dataSource,headerOffset,virtuaRef,}: {+ dataSource: string[];headerOffset: number;virtuaRef: RefObject<VListHandle | null>;}) => {const pinRef = useRef<PinState>(null);+ const dataSourceRef = useRef(dataSource);+ dataSourceRef.current = dataSource;const scrollToPinned = useCallback((reason: string) => {const pin = pinRef.current;if (!pin) return;+ const index = dataSourceRef.current.indexOf(pin.messageId);+ if (index < 0) return;const scrollToIndex = virtuaRef.current?.scrollToIndex;if (!scrollToIndex) {- log('scrollToPinned skipped: virtua not ready (%s) index=%d', reason, pin.index);+ log('scrollToPinned skipped: virtua not ready (%s) index=%d', reason, index);return;}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.- scrollToIndex(pin.index + headerOffset, { align: 'start', smooth });+ log('scrollToPinned (%s) index=%d smooth=%s', reason, index, smooth);+ // Resolve the message index again after paging; the header shifts virtua rows.+ scrollToIndex(index + headerOffset, { align: 'start', smooth });},[headerOffset, virtuaRef],);const clearPin = useCallback((reason: string) => {if (!pinRef.current) return;- log('clearPin (%s) index=%d', reason, pinRef.current.index);+ log('clearPin (%s) message=%s', reason, pinRef.current.messageId);pinRef.current = null;}, []);@@ -478,12 +484,17 @@ export const useConversationScroll = ({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);+ // Pin the user by ID so paging cannot move the turn. Its visible response+ // is the next row and can be replaced by regeneration; do not retain the+ // old response ID or cross into the next user turn while a reply is absent.+ const [userMessageId, setUserMessageId] = useState<string | null>(null);+ const userIndex = userMessageId === null ? -1 : dataSource.indexOf(userMessageId);+ const nextMessageId = userIndex < 0 ? undefined : dataSource[userIndex + 1];+ const nextMessage = nextMessageId+ ? displayMessages.find((message) => message.id === nextMessageId)+ : undefined;+ const userMessageIndex = userIndex < 0 ? null : userIndex;+ const assistantMessageIndex = nextMessage && nextMessage.role !== 'user' ? userIndex + 1 : null;const lastId = dataSource.at(-1);const prevLengthRef = useRef(dataSource.length);const prevLastIdRef = useRef<string | undefined>(lastId);@@ -522,7 +533,11 @@ export const useConversationScroll = ({userMessageIndex,});- const { clearPin, pinRef, scrollToPinned } = usePinController({ headerOffset, virtuaRef });+ const { clearPin, pinRef, scrollToPinned } = usePinController({+ dataSource,+ headerOffset,+ virtuaRef,+ });const { onScrollOffset, prevScrollOffsetRef } = useScrollShrink({clearPin,@@ -546,8 +561,7 @@ export const useConversationScroll = ({prevLastIdRef.current = dataSource.at(-1);hadLaterMessagesRef.current = hasLaterMessages;clearPin('context switch');- setUserMessageIndex(null);- setAssistantMessageIndex(null);+ setUserMessageId(null);setMounted(false);setScrollReduction(() => 0);prevScrollOffsetRef.current = null;@@ -577,15 +591,17 @@ export const useConversationScroll = ({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, sentAt: Date.now() };+ setUserMessageId(dataSource[userIndex]);+ pinRef.current = {+ messageId: dataSource[userIndex],+ seenActive: mountedRef.current,+ sentAt: Date.now(),+ };// Scroll immediately. If virtuaRef isn't ready yet, the spacerLayoutVersion// bumps that follow mount+measurement will retry.diff --git a/src/services/message/roundCursorPage.test.ts b/src/services/message/roundCursorPage.test.tsindex 0bac1ac60d8..1be575ff2ac 100644--- a/src/services/message/roundCursorPage.test.ts+++ b/src/services/message/roundCursorPage.test.ts@@ -32,13 +32,28 @@ let seq = 0;const nextContext = () => ({ agentId: 'agent-1', topicId: 'topic-1', topicShareId: `s${++seq}` });describe('toRoundCursorQueryInput', () => {- it('reads a gateway display page with the 50-row budget', () => {- const input = toRoundCursorQueryInput(- { agentId: 'a', projectToolPayloads: true, topicId: 't' },- null,+ it('requests 500-row gateway pages for the initial window and older history', async () => {+ query.mockReset();+ const service = new MessageService();+ const context = { ...nextContext(), projectToolPayloads: true };+ const cursor = { createdAt: '2026-01-01T00:00:00.000000Z', id: 'oldest-head' };+ const messages = Array.from({ length: 500 }, (_, index) => ({ id: `head-${index}` }));+ query.mockResolvedValueOnce({ ...page('head'), hasMore: true, messages, nextCursor: cursor });+ query.mockResolvedValueOnce(page('older'));++ const head = await service.getMessageListPage(context);+ const older = await service.getEarlierMessages(context, cursor);++ expect(query).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({ countBudget: 500, cursor: null, projectToolPayloads: true }),);-- expect(input).toMatchObject({ countBudget: 50, roundLimit: 1000 });+ expect(query).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ countBudget: 500, cursor, projectToolPayloads: true }),+ );+ expect(head).toEqual({ messages, olderCursor: cursor });+ expect(older).toEqual({ messages: [{ id: 'older' }], olderCursor: null });});it('keeps the full window for client-mode reads', () => {diff --git a/src/services/message/roundCursorPage.ts b/src/services/message/roundCursorPage.tsindex 5d06e8a9d54..94e731d36ef 100644--- a/src/services/message/roundCursorPage.ts+++ b/src/services/message/roundCursorPage.ts@@ -12,7 +12,7 @@ import type { MessageListPage, MessageRoundCursor } from './cache';export const MESSAGE_PAGE_ROW_BUDGET = 1000;// Client-mode reads keep the full budget: the client runtime replays the loaded rows as model history.-export const GATEWAY_PAGE_ROW_BUDGET = 50;+export const GATEWAY_PAGE_ROW_BUDGET = 500;/** Page sizes for reading a topic forward from its first round. */export interface ForwardPageSize {