From 5ebba27035bcd4bb2beec2c5ef1c64676fac8eec Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Tue, 3 Nov 2026 21:44:22 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=9B=9E=20refactor:=20Run=20Message=20Scro?= =?UTF-8?q?lling=20Inside=20@librechat/chat=20(#17752)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: Move Message Scrolling Into @librechat/chat * refactor: Run Message Scrolling in the Package Message List * test: Pin the Scroll Throttle's Coalescing Window --- client/src/Providers/MessagesHostContext.tsx | 11 +- .../Messages/__tests__/MessagesView.spec.tsx | 8 - client/src/hooks/Messages/index.ts | 3 +- client/src/hooks/index.ts | 1 - client/src/hooks/useScrollToRef.ts | 74 -------- .../scenarios/long-conversation-mount.spec.ts | 44 +++++ .../chat/src/__fixtures__/messagesHost.ts | 8 - .../src/components/messages/MessagesView.tsx | 26 ++- .../messages/__tests__/MessagesView.spec.tsx | 81 ++++---- .../thread/__tests__/MultiMessage.spec.tsx | 3 - packages/chat/src/react.ts | 6 +- .../messages}/__tests__/messageLayout.spec.ts | 3 + .../__tests__/useMessageScrolling.spec.tsx | 179 +++++++----------- .../__tests__/useScrollToRef.spec.tsx | 29 +++ packages/chat/src/react/messages/host.tsx | 44 +---- .../chat/src/react/messages}/messageLayout.ts | 0 .../react/messages}/useMessageScrolling.ts | 60 ++++-- .../chat/src/react/messages/useScrollToRef.ts | 98 ++++++++++ packages/chat/test/consumer.spec.tsx | 8 - 19 files changed, 367 insertions(+), 319 deletions(-) delete mode 100644 client/src/hooks/useScrollToRef.ts rename {client/src/hooks/Messages => packages/chat/src/react/messages}/__tests__/messageLayout.spec.ts (97%) rename {client/src/hooks/Messages => packages/chat/src/react/messages}/__tests__/useMessageScrolling.spec.tsx (83%) rename {client/src/hooks => packages/chat/src/react/messages}/__tests__/useScrollToRef.spec.tsx (79%) rename {client/src/hooks/Messages => packages/chat/src/react/messages}/messageLayout.ts (100%) rename {client/src/hooks/Messages => packages/chat/src/react/messages}/useMessageScrolling.ts (90%) create mode 100644 packages/chat/src/react/messages/useScrollToRef.ts diff --git a/client/src/Providers/MessagesHostContext.tsx b/client/src/Providers/MessagesHostContext.tsx index 631bec5951..d8b40b80ad 100644 --- a/client/src/Providers/MessagesHostContext.tsx +++ b/client/src/Providers/MessagesHostContext.tsx @@ -10,7 +10,6 @@ import type { MessageCopyInput, ForkPreferences, ForkConversation, - MessagesScrolling, MessageAudioProps, } from '@librechat/chat/react'; import type { TMessage } from 'librechat-data-provider'; @@ -21,7 +20,6 @@ import { useCopyMessageToClipboard, } from '~/hooks'; import useConversationSeen from '~/hooks/Conversations/useConversationSeen'; -import useMessageScrolling from '~/hooks/Messages/useMessageScrolling'; import { useOptionalMessagesOperations } from './MessagesViewContext'; import ThreadMessage from '~/components/Chat/Messages/Thread/Message'; import MessageAudio from '~/components/Chat/Messages/MessageAudio'; @@ -72,12 +70,6 @@ function useAppForkConversation(): ForkConversation { ); } -/** The app's scrolling hook, as the message list reads it. */ -function useScrolling(messagesTree: TMessage[] | null | undefined): MessagesScrolling { - const { conversation, ...scrolling } = useMessageScrolling(messagesTree); - return { ...scrolling, conversationId: conversation?.conversationId }; -} - function useAppMessageCopy({ message, searchResults, variant }: MessageCopyInput): MessageCopy { const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]); const copyToClipboard = useCopyMessageToClipboard({ @@ -110,7 +102,7 @@ function AppMessageAudio(props: MessageAudioProps) { } /** What the message list reads from the app: the viewer's clock format and fork defaults, the - * fork request, the rich-text copy, its scrolling, screenshot and seen reporting, the thread's + * fork request, the rich-text copy, its auto-scroll preference, screenshot and seen reporting, the thread's * file map, and the row pieces that still live here: the message body and the subagent activity * group. Registered as the default when this module loads, so rows read it on every route, the * shared view included. */ @@ -123,7 +115,6 @@ export const appMessagesHost: MessagesHost = { useGetMessages: useAppGetMessages, useHasPendingTurn: useAppHasPendingTurn, renderMessageAudio: (props) => , - useScrolling, useScreenshotTarget: () => useScreenshot().screenshotTargetRef, useAutoScroll: () => useAtomValue(autoScrollAtom), useConversationSeen, diff --git a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx index 38e96b73ed..fc815a3436 100644 --- a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx +++ b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx @@ -93,14 +93,6 @@ const host: MessagesHost = { useGetMessages: () => () => undefined, useHasPendingTurn: () => false, renderMessageAudio: () => null, - useScrolling: () => ({ - contentRef: { current: null }, - scrollableRef: { current: null }, - messagesEndRef: { current: null }, - handleSmoothToRef: () => undefined, - debouncedHandleScroll: () => undefined, - handleNearBottomChange: () => undefined, - }), useScreenshotTarget: () => undefined, useAutoScroll: () => false, useConversationSeen: () => () => undefined, diff --git a/client/src/hooks/Messages/index.ts b/client/src/hooks/Messages/index.ts index 9eb6786b3e..4ecee927b4 100644 --- a/client/src/hooks/Messages/index.ts +++ b/client/src/hooks/Messages/index.ts @@ -3,7 +3,7 @@ export { getRenderedContentMaxScrollTop, reconcileMessageContentLayout, scheduleMessageContentLayoutReconcile, -} from './messageLayout'; +} from '@librechat/chat/react'; export { EXPAND_TRANSITION } from './useExpandCollapse'; export { default as useAttachments } from './useAttachments'; export { default as useSubmitMessage } from './useSubmitMessage'; @@ -24,5 +24,4 @@ export { useCopyMessageToClipboard, } from './useCopyToClipboard'; export { default as useContentMetadata } from './useContentMetadata'; -export { default as useMessageScrolling } from './useMessageScrolling'; export { default as useSmoothStreaming } from './useSmoothStreaming'; diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.ts index 217e64fdb2..2103439a7a 100644 --- a/client/src/hooks/index.ts +++ b/client/src/hooks/index.ts @@ -33,7 +33,6 @@ export { default as useFocusTrap } from './useFocusTrap'; export { default as useFavorites } from './useFavorites'; export { default as useToolFavorites } from './useToolFavorites'; export { default as useAdaptiveIcon } from './useAdaptiveIcon'; -export { default as useScrollToRef } from './useScrollToRef'; export { default as useIsActiveItem } from './useIsActiveItem'; export { default as useLocalStorage } from './useLocalStorage'; export { default as useDocumentTitle } from './useDocumentTitle'; diff --git a/client/src/hooks/useScrollToRef.ts b/client/src/hooks/useScrollToRef.ts deleted file mode 100644 index 18acbe7003..0000000000 --- a/client/src/hooks/useScrollToRef.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { useEffect, useMemo, useRef } from 'react'; -import throttle from 'lodash/throttle'; -import type { RefObject } from 'react'; - -type TUseScrollToRef = { - targetRef: RefObject; - callback: () => void; - smoothCallback: () => void; -}; - -type ThrottledFunction = (() => void) & { - cancel: () => void; - flush: () => void; -}; - -type ScrollToRefReturn = { - scrollToRef?: ThrottledFunction; - handleSmoothToRef: React.MouseEventHandler; -}; - -export default function useScrollToRef({ - targetRef, - callback, - smoothCallback, -}: TUseScrollToRef): ScrollToRefReturn { - const callbacksRef = useRef({ callback, smoothCallback }); - useEffect(() => { - callbacksRef.current = { callback, smoothCallback }; - }, [callback, smoothCallback]); - - const scrollToRef = useMemo( - () => - throttle( - () => { - targetRef.current?.scrollIntoView({ behavior: 'instant' }); - callbacksRef.current.callback(); - }, - 145, - { leading: true }, - ), - [targetRef], - ); - - const scrollToRefSmooth = useMemo( - () => - throttle( - () => { - targetRef.current?.scrollIntoView({ behavior: 'smooth' }); - callbacksRef.current.smoothCallback(); - }, - 750, - { leading: true }, - ), - [targetRef], - ); - - useEffect( - () => () => { - scrollToRef.cancel(); - scrollToRefSmooth.cancel(); - }, - [scrollToRef, scrollToRefSmooth], - ); - - const handleSmoothToRef: React.MouseEventHandler = (e) => { - e.preventDefault(); - scrollToRefSmooth(); - }; - - return { - scrollToRef, - handleSmoothToRef, - }; -} diff --git a/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts b/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts index 2a758b99f4..7deb391349 100644 --- a/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts +++ b/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts @@ -6,6 +6,13 @@ import { seedConversations, seedMessages, } from '../db'; +import { + replyText, + replyPrompt, + sendMessage, + MOCK_ENDPOINTS, + selectMockEndpoint, +} from '../helpers'; import { getE2EUser } from '../../../setup/user'; /** Past the row count at which the thread mounts progressively instead of all at once. */ @@ -86,4 +93,41 @@ test.describe('long conversations', () => { await expect(latest).toBeInViewport(); await expect(scrollControl).toBeHidden(); }); + + test('opening a long conversation lands on its latest turn @scenario:long-conversation-opens-at-its-latest-turn', async ({ + page, + }) => { + await page.goto(`/c/${conversationId}`); + + const thread = page.locator(`[data-conversation-id="${conversationId}"]`); + await expect(thread.locator('.message-render')).toHaveCount(TURNS); + + await expect( + thread.getByText(`Turn ${TURNS} of the long conversation`, { exact: true }), + ).toBeInViewport(); + await expect( + thread.getByText('Turn 1 of the long conversation', { exact: true }), + ).not.toBeInViewport(); + }); + + test('a reply sent from the top of a long conversation is followed into view @scenario:sent-reply-is-followed-into-view', async ({ + page, + }) => { + await page.goto(`/c/${conversationId}`); + + const thread = page.locator(`[data-conversation-id="${conversationId}"]`); + await expect(thread.locator('.message-render')).toHaveCount(TURNS); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + const first = thread.getByText('Turn 1 of the long conversation', { exact: true }); + await first.scrollIntoViewIfNeeded(); + await expect(first).toBeInViewport(); + + const label = randomUUID().slice(0, 8); + await sendMessage(page, replyPrompt(label)); + + const reply = thread.getByText(replyText(label)); + await expect(reply).toBeVisible({ timeout: 30_000 }); + await expect(reply).toBeInViewport(); + await expect(first).not.toBeInViewport(); + }); }); diff --git a/packages/chat/src/__fixtures__/messagesHost.ts b/packages/chat/src/__fixtures__/messagesHost.ts index 93f763d555..61c974946f 100644 --- a/packages/chat/src/__fixtures__/messagesHost.ts +++ b/packages/chat/src/__fixtures__/messagesHost.ts @@ -19,14 +19,6 @@ export function createMessagesHost(overrides: Partial = {}): Messa useGetMessages: () => () => undefined, useHasPendingTurn: () => false, renderMessageAudio: () => null, - useScrolling: () => ({ - contentRef: { current: null }, - scrollableRef: { current: null }, - messagesEndRef: { current: null }, - handleSmoothToRef: () => undefined, - debouncedHandleScroll: () => undefined, - handleNearBottomChange: () => undefined, - }), useScreenshotTarget: () => undefined, useAutoScroll: () => false, useConversationSeen: () => () => undefined, diff --git a/packages/chat/src/components/messages/MessagesView.tsx b/packages/chat/src/components/messages/MessagesView.tsx index e3f4236a1b..ced2df542b 100644 --- a/packages/chat/src/components/messages/MessagesView.tsx +++ b/packages/chat/src/components/messages/MessagesView.tsx @@ -8,6 +8,7 @@ import { RowMountProvider, useProgressiveRowMount, } from '../../react/messages/useProgressiveRowMount'; +import useMessageScrolling from '../../react/messages/useMessageScrolling'; import useScrollbarGutter from '../../react/messages/useScrollbarGutter'; import { useMessagesHost } from '../../react/messages/host'; import { useChatContext } from '../../react/chat/context'; @@ -85,25 +86,40 @@ export default function MessagesView({ const [currentEditId, setCurrentEditId] = useState(-1); const { - conversationId, + index, + conversation, + isSubmitting, + abortScroll, + setAbortScroll, + latestMessageId, + latestMessageDepth, + messagesKey, + } = useChatContext(); + const conversationId = conversation?.conversationId; + const autoScroll = host.useAutoScroll(); + const { contentRef, scrollableRef, messagesEndRef, handleSmoothToRef, debouncedHandleScroll, handleNearBottomChange, - } = host.useScrolling(messagesTree); + } = useMessageScrolling({ + messagesTree, + conversationId, + isSubmitting, + abortScroll, + setAbortScroll, + autoScroll, + }); useScrollbarGutter(scrollableRef); - const { index, isSubmitting, latestMessageId, latestMessageDepth, messagesKey } = - useChatContext(); /** Re-arm from the conversation that owns the RENDERED tree: the app's conversation id lags * the route during warm-cache navigation, and keying off it would first mount the new tree * unwindowed, then narrow it after the fact, visibly unmounting rows the user is already * reading. An empty tree has no message to name its owner, so the route's key stands in. */ const treeConversationId = messagesTree?.[0]?.conversationId ?? (messagesKey || conversationId); - const autoScroll = host.useAutoScroll(); /** Direct measurement for the one trigger the observer cannot serve: after a messages * revalidation commits, the end marker may sit where no threshold was crossed, so no diff --git a/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx b/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx index 298d02ef5a..c8955d661c 100644 --- a/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx +++ b/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx @@ -2,10 +2,10 @@ * @jest-environment jsdom */ import { useRef } from 'react'; -import { render, screen } from '@testing-library/react'; +import { fireEvent, render, screen } from '@testing-library/react'; import type { TMessage } from 'librechat-data-provider'; -import type { MessagesHost, MessagesScrolling } from '../../../react/messages/host'; import type { MessagesScrollButtonProps, MessagesViewProps } from '../MessagesView'; +import type { MessagesHost } from '../../../react/messages/host'; import type { ChatContract } from '../../../react/chat/contract'; import type { MessagePartsHost } from '../../../react/host'; import { createMessagesHost } from '../../../__fixtures__/messagesHost'; @@ -22,42 +22,42 @@ const tree = [{ messageId: 'reply-1', conversationId: 'convo-1' }] as TMessage[] const partsHost = { useFontSize: () => 'text-base' } as unknown as MessagePartsHost; function createHost(overrides: Partial = {}) { - const scrolling: { current?: MessagesScrolling } = {}; const reportNearBottom = jest.fn(); const useConversationSeen = jest.fn< jest.Mock, [string | undefined, boolean, () => boolean | null, (messageId: string) => boolean] >(() => reportNearBottom); const host = createMessagesHost({ - useScrolling: () => { - const contentRef = useRef(null); - const scrollableRef = useRef(null); - const messagesEndRef = useRef(null); - scrolling.current = { - conversationId: 'convo-1', - contentRef, - scrollableRef, - messagesEndRef, - handleSmoothToRef: jest.fn(), - debouncedHandleScroll: jest.fn(), - handleNearBottomChange: jest.fn(), - }; - return scrolling.current; - }, useScreenshotTarget: () => useRef(null), useAutoScroll: () => false, useConversationSeen, ...overrides, }); - return { host, scrolling, reportNearBottom, useConversationSeen }; + return { host, reportNearBottom, useConversationSeen }; } -const contract = { - index: 0, - isSubmitting: false, - latestMessageDepth: 0, - messagesKey: 'convo-1', -} as ChatContract; +/** What the list's scrolling reads from the pane. */ +const scrollingInputs: Pick = { + abortScroll: false, + setAbortScroll: jest.fn(), + conversation: { + conversationId: 'convo-1', + endpoint: null, + title: null, + createdAt: '2026-11-03T00:00:00.000Z', + updatedAt: '2026-11-03T00:00:00.000Z', + }, +}; + +const contract: ChatContract = Object.assign( + { + index: 0, + isSubmitting: false, + latestMessageDepth: 0, + messagesKey: 'convo-1', + } as ChatContract, + scrollingInputs, +); function renderView(props: Partial, host: MessagesHost, chat = contract) { const view = (next: Partial) => ( @@ -144,13 +144,13 @@ describe('MessagesView', () => { }); it('wires the scroll control to the end marker and to both near-bottom listeners', () => { - const { host, scrolling, reportNearBottom } = createHost(); + const { host, reportNearBottom } = createHost(); let button: MessagesScrollButtonProps | undefined; const { container } = renderView( { renderScrollButton: (props) => { button = props; - return null; + return ; }, }, host, @@ -159,10 +159,19 @@ describe('MessagesView', () => { expect(button?.enabled).toBe(true); expect(button?.conversationId).toBe('convo-1'); expect(button?.messagesEndRef.current).toBe(container.querySelector('#messages-end')); - expect(button?.scrollHandler).toBe(scrolling.current?.handleSmoothToRef); + expect(button?.scrollableRef.current).toBe( + container.querySelector('#messages-end')?.closest('.scrollbar-gutter-stable'), + ); + + const end = container.querySelector('#messages-end'); + const scrollIntoView = jest.fn(); + if (end) { + end.scrollIntoView = scrollIntoView; + } + fireEvent.click(screen.getByRole('button', { name: 'Jump' })); + expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth' }); button?.onNearBottomChange(false); - expect(scrolling.current?.handleNearBottomChange).toHaveBeenCalledWith(false); expect(reportNearBottom).toHaveBeenCalledWith(false); }); @@ -192,10 +201,18 @@ describe('MessagesView', () => { }); it('listens to the scroll container and keeps native scroll anchoring outside a mount window', () => { - const { host, scrolling } = createHost(); - renderView({}, host); + let button: MessagesScrollButtonProps | undefined; + renderView( + { + renderScrollButton: (props) => { + button = props; + return null; + }, + }, + createHost().host, + ); - const scrollable = scrolling.current?.scrollableRef.current; + const scrollable = button?.scrollableRef.current; expect(scrollable).toHaveClass('scrollbar-gutter-stable', 'overflow-y-auto'); expect(scrollable).not.toHaveClass('[overflow-anchor:none]'); }); diff --git a/packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx b/packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx index c02900b6bc..66c720e46c 100644 --- a/packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx +++ b/packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx @@ -33,9 +33,6 @@ const host: MessagesHost = { useGetMessages: () => () => undefined, useHasPendingTurn: () => false, renderMessageAudio: () => null, - useScrolling: () => { - throw new Error('not used by the thread'); - }, useScreenshotTarget: () => undefined, useAutoScroll: () => false, useConversationSeen: () => () => undefined, diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index 8f94128277..f7cce18079 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -130,6 +130,11 @@ export { useComposerOverlay, composerOverlayCountFamily } from './react/overlay' export { default as useTimeTick } from './react/tick'; export { default as useGenerationsByLatest } from './react/messages/generations'; export type { Generations, TUseGenerations } from './react/messages/generations'; +export { + reconcileMessageContentLayout, + getRenderedContentMaxScrollTop, + scheduleMessageContentLayoutReconcile, +} from './react/messages/messageLayout'; export { useMessagesHost, MessagesHostProvider, @@ -145,7 +150,6 @@ export type { ForkPreferences, ForkConversation, ActivitySlotProps, - MessagesScrolling, ReportNearBottom, MessageIconData, MessageIconProps, diff --git a/client/src/hooks/Messages/__tests__/messageLayout.spec.ts b/packages/chat/src/react/messages/__tests__/messageLayout.spec.ts similarity index 97% rename from client/src/hooks/Messages/__tests__/messageLayout.spec.ts rename to packages/chat/src/react/messages/__tests__/messageLayout.spec.ts index d2e365aac9..e1ad29cbf3 100644 --- a/client/src/hooks/Messages/__tests__/messageLayout.spec.ts +++ b/packages/chat/src/react/messages/__tests__/messageLayout.spec.ts @@ -1,3 +1,6 @@ +/** + * @jest-environment jsdom + */ import { reconcileMessageContentLayout } from '../messageLayout'; function setRect(element: HTMLElement, rect: Partial): void { diff --git a/client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsx b/packages/chat/src/react/messages/__tests__/useMessageScrolling.spec.tsx similarity index 83% rename from client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsx rename to packages/chat/src/react/messages/__tests__/useMessageScrolling.spec.tsx index 0330e1583c..cee231ebad 100644 --- a/client/src/hooks/Messages/__tests__/useMessageScrolling.spec.tsx +++ b/packages/chat/src/react/messages/__tests__/useMessageScrolling.spec.tsx @@ -1,12 +1,10 @@ -import React from 'react'; -import { RecoilRoot } from 'recoil'; -import { Provider, createStore } from 'jotai'; +/** + * @jest-environment jsdom + */ +import { createContext, useContext } from 'react'; import { act, fireEvent, render, screen } from '@testing-library/react'; -import type { TConversation, TMessage } from 'librechat-data-provider'; -import { - MessagesViewContext, - type MessagesViewContextValue, -} from '~/Providers/MessagesViewContext'; +import type { TMessage } from 'librechat-data-provider'; +import type { MessageScrollingInput } from '../useMessageScrolling'; type MockScrollToBottom = jest.Mock & { cancel: jest.Mock; @@ -19,7 +17,7 @@ mockScrollToBottom.flush = jest.fn(); const mockHandleSmoothToRef = jest.fn(); let mockScrollCallback: (() => void) | undefined; -jest.mock('~/hooks/useScrollToRef', () => ({ +jest.mock('../useScrollToRef', () => ({ __esModule: true, default: ({ callback }: { callback: () => void }) => { mockScrollCallback = callback; @@ -36,7 +34,6 @@ jest.mock('../messageLayout', () => ({ import useMessageScrolling from '../useMessageScrolling'; import { reconcileMessageContentLayout } from '../messageLayout'; -import { autoScrollAtom } from '~/store/autoScroll'; const mockReconcileMessageContentLayout = reconcileMessageContentLayout as jest.Mock; @@ -108,42 +105,34 @@ function setRect(element: HTMLElement, rect: Partial): void { ); } -const conversation = { - conversationId: 'conversation-1', - endpoint: 'openAI', - model: 'gpt-4', -} as TConversation; - const message = { messageId: 'message-1', - conversationId: conversation.conversationId, + conversationId: 'conversation-1', isCreatedByUser: false, } as TMessage; -function createContextValue( - overrides: Partial = {}, -): MessagesViewContextValue { +type ScrollingInputs = Omit; + +function createContextValue(overrides: Partial = {}): ScrollingInputs { return { - conversation, - conversationId: conversation.conversationId, + conversationId: 'conversation-1', isSubmitting: true, abortScroll: false, setAbortScroll: jest.fn(), - ask: jest.fn(), - regenerate: jest.fn(), - handleContinue: jest.fn(), - index: 0, - latestMessageId: message.messageId, - latestMessageDepth: 0, - getMessages: jest.fn(), - setMessages: jest.fn(), + autoScroll: true, ...overrides, - } as MessagesViewContextValue; + }; } +/** Stands in for the message list, which feeds the hook from the chat context. */ +const ScrollingInputsContext = createContext(createContextValue()); + function ScrollingHarness({ messagesTree }: { messagesTree?: TMessage[] | null }) { - const { contentRef, scrollableRef, messagesEndRef, debouncedHandleScroll } = - useMessageScrolling(messagesTree); + const inputs = useContext(ScrollingInputsContext); + const { contentRef, scrollableRef, messagesEndRef, debouncedHandleScroll } = useMessageScrolling({ + ...inputs, + messagesTree, + }); return (
@@ -158,15 +147,13 @@ function renderScrolling({ contextOverrides, messagesTree, }: { - contextOverrides?: Partial; + contextOverrides?: Partial; messagesTree?: TMessage[] | null; } = {}) { return render( - - - - - , + + + , ); } @@ -393,11 +380,9 @@ describe('useMessageScrolling resize reconciliation', () => { jest.useFakeTimers(); try { const view = render( - - - - - , + + + , ); const scrollable = screen.getByTestId('scrollable'); @@ -408,11 +393,9 @@ describe('useMessageScrolling resize reconciliation', () => { scrollable.scrollTop = 0; view.rerender( - - - - - , + + + , ); expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' }); @@ -444,11 +427,9 @@ describe('useMessageScrolling resize reconciliation', () => { */ it('starts the turn once a stale abort flag clears', () => { const view = render( - - - - - , + + + , ); const scrollable = screen.getByTestId('scrollable'); @@ -462,26 +443,22 @@ describe('useMessageScrolling resize reconciliation', () => { fireEvent.wheel(scrollable, { deltaY: -120 }); view.rerender( - - - - - , + + + , ); expect(scrollTo).not.toHaveBeenCalled(); /** The connection opens and lowers the flag. */ view.rerender( - - - - - , + + + , ); expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' }); @@ -489,11 +466,9 @@ describe('useMessageScrolling resize reconciliation', () => { it('leaves the send glide alone while the answer streams in', () => { const view = render( - - - - - , + + + , ); const scrollable = screen.getByTestId('scrollable'); @@ -504,11 +479,9 @@ describe('useMessageScrolling resize reconciliation', () => { scrollable.scrollTop = 0; view.rerender( - - - - - , + + + , ); expect(scrollTo).toHaveBeenCalledWith({ top: 800, behavior: 'smooth' }); @@ -516,11 +489,9 @@ describe('useMessageScrolling resize reconciliation', () => { /** The next delta of the answer arrives while the glide is still travelling. */ Object.defineProperty(scrollable, 'scrollHeight', { value: 1100, configurable: true }); view.rerender( - - - - - , + + + , ); /** A plain follow would have written scrollTop outright and killed the animation. */ @@ -534,11 +505,9 @@ describe('useMessageScrolling resize reconciliation', () => { */ it('catches up to the new bottom when the glide lands', () => { const view = render( - - - - - , + + + , ); const scrollable = screen.getByTestId('scrollable'); @@ -548,11 +517,9 @@ describe('useMessageScrolling resize reconciliation', () => { scrollable.scrollTop = 0; view.rerender( - - - - - , + + + , ); /** The whole answer arrives before the glide reports that it landed. */ @@ -597,23 +564,15 @@ describe('useMessageScrolling navigation landing', () => { ]; const harness = ( - store: ReturnType, + autoScroll: boolean, conversationId: string, messagesTree: TMessage[] | null, ) => ( - - - - - - - + + + ); function renderLanding( @@ -621,13 +580,11 @@ describe('useMessageScrolling navigation landing', () => { messagesTree: TMessage[] | null, autoScroll = true, ) { - const store = createStore(); - store.set(autoScrollAtom, autoScroll); - const view = render(harness(store, conversationId, messagesTree)); + const view = render(harness(autoScroll, conversationId, messagesTree)); return { ...view, rerenderWith: (nextId: string, nextTree: TMessage[] | null) => - view.rerender(harness(store, nextId, nextTree)), + view.rerender(harness(autoScroll, nextId, nextTree)), }; } diff --git a/client/src/hooks/__tests__/useScrollToRef.spec.tsx b/packages/chat/src/react/messages/__tests__/useScrollToRef.spec.tsx similarity index 79% rename from client/src/hooks/__tests__/useScrollToRef.spec.tsx rename to packages/chat/src/react/messages/__tests__/useScrollToRef.spec.tsx index 5466eb415c..ddb2b52821 100644 --- a/client/src/hooks/__tests__/useScrollToRef.spec.tsx +++ b/packages/chat/src/react/messages/__tests__/useScrollToRef.spec.tsx @@ -1,3 +1,6 @@ +/** + * @jest-environment jsdom + */ import { StrictMode, createRef, useRef } from 'react'; import { act, fireEvent, render, screen } from '@testing-library/react'; import type { RefObject } from 'react'; @@ -98,6 +101,32 @@ describe('useScrollToRef lifecycle', () => { }, ); + it.each(scrollActions)( + 'coalesces a burst of $label calls into one trailing call, as lodash throttle does', + ({ label, interval }) => { + const callback = jest.fn(); + render(, { wrapper: StrictMode }); + screen.getByTestId('end').scrollIntoView = jest.fn(); + + fireEvent.click(screen.getByText(label)); + fireEvent.click(screen.getByText(label)); + fireEvent.click(screen.getByText(label)); + fireEvent.click(screen.getByText(label)); + expect(callback).toHaveBeenCalledTimes(1); + + act(() => jest.advanceTimersByTime(interval)); + expect(callback).toHaveBeenCalledTimes(2); + + /** The trailing run opens a window of its own; with nothing queued in it, nothing more runs. */ + act(() => jest.advanceTimersByTime(interval * 3)); + expect(callback).toHaveBeenCalledTimes(2); + + /** Once that window closes, the next call is a leading call again. */ + fireEvent.click(screen.getByText(label)); + expect(callback).toHaveBeenCalledTimes(3); + }, + ); + it.each(scrollActions)('cancels queued $label work when the target ref changes', ({ label }) => { const callback = jest.fn(); const previousRef = createRef(); diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx index 3bccafb19b..8603a162c9 100644 --- a/packages/chat/src/react/messages/host.tsx +++ b/packages/chat/src/react/messages/host.tsx @@ -10,24 +10,6 @@ import type { } from 'librechat-data-provider'; import type { Dispatch, ReactNode, MouseEvent, RefObject, SetStateAction } from 'react'; -/** The scroll machinery of the message list, as the app's scrolling hook drives it. */ -export type MessagesScrolling = { - /** The conversation the scrolling follows. */ - conversationId?: string | null; - /** Wraps the rendered thread. */ - contentRef: RefObject; - /** The scroll container. */ - scrollableRef: RefObject; - /** The zero-height marker after the last row. */ - messagesEndRef: RefObject; - /** Scrolls smoothly to the end, from the scroll-to-bottom control. */ - handleSmoothToRef: (event: MouseEvent) => void; - /** The container's scroll listener. */ - debouncedHandleScroll: () => void; - /** Reports whether the end marker is in view. */ - handleNearBottomChange: (isNearBottom: boolean) => void; -}; - /** What the message slot renders one visible row of the thread from. */ export type MessageRowSlotProps = { message: TMessage; @@ -152,14 +134,6 @@ export interface MessagesHost { useHasPendingTurn: (conversationId: string) => boolean; /** Renders the app's read-aloud control, or `null` while read-aloud is off. */ renderMessageAudio: (props: MessageAudioProps) => ReactNode; - /** - * Drives the list's scrolling: follows the stream, lands on a conversation's end and keeps - * the reader's position. - * - * @deprecated On arrival: a bridge to the app's `useMessageScrolling`, which reads the app's - * messages providers, until it moves into this package and the list runs it itself. - */ - useScrolling: (messagesTree: TMessage[] | null | undefined) => MessagesScrolling; /** The element the app's conversation screenshot captures; none outside a screenshot provider. */ useScreenshotTarget: () => RefObject | undefined; /** Whether the viewer asked the thread to follow new content to the bottom. */ @@ -196,27 +170,12 @@ const fallbackForkPreferences: ForkPreferences = { setRememberOption: noop, }; -/** Scrolling with nothing behind it: live refs, inert handlers. */ -function useInertScrolling(): MessagesScrolling { - const contentRef = useRef(null); - const scrollableRef = useRef(null); - const messagesEndRef = useRef(null); - return { - contentRef, - scrollableRef, - messagesEndRef, - handleSmoothToRef: () => undefined, - debouncedHandleScroll: () => undefined, - handleNearBottomChange: () => undefined, - }; -} - const ignoreNearBottom: ReportNearBottom = () => undefined; const noMessages = (): TMessage[] | undefined => undefined; /** The host rows read outside any provider before an app registers one: locale clock, no slots, - * no forking, no copying, no thread, no queued turn, no read-aloud, inert scrolling. */ + * no forking, no copying, no thread, no queued turn, no read-aloud. */ const fallbackHost: MessagesHost = { useHour12: () => undefined, renderFiles: () => null, @@ -226,7 +185,6 @@ const fallbackHost: MessagesHost = { useGetMessages: () => noMessages, useHasPendingTurn: () => false, renderMessageAudio: () => null, - useScrolling: useInertScrolling, useScreenshotTarget: () => useRef(null), useAutoScroll: () => false, useConversationSeen: () => ignoreNearBottom, diff --git a/client/src/hooks/Messages/messageLayout.ts b/packages/chat/src/react/messages/messageLayout.ts similarity index 100% rename from client/src/hooks/Messages/messageLayout.ts rename to packages/chat/src/react/messages/messageLayout.ts diff --git a/client/src/hooks/Messages/useMessageScrolling.ts b/packages/chat/src/react/messages/useMessageScrolling.ts similarity index 90% rename from client/src/hooks/Messages/useMessageScrolling.ts rename to packages/chat/src/react/messages/useMessageScrolling.ts index cd5ae9df63..7d51d86224 100644 --- a/client/src/hooks/Messages/useMessageScrolling.ts +++ b/packages/chat/src/react/messages/useMessageScrolling.ts @@ -1,11 +1,41 @@ import { useRef, useCallback, useEffect } from 'react'; -import { useAtomValue } from 'jotai'; import { Constants } from 'librechat-data-provider'; +import type { Dispatch, MouseEvent, RefObject, SetStateAction } from 'react'; import type { TMessage } from 'librechat-data-provider'; -import { useMessagesConversation, useMessagesSubmission } from '~/Providers'; +import type { ThrottledFunction } from './useScrollToRef'; import { reconcileMessageContentLayout } from './messageLayout'; -import useScrollToRef from '~/hooks/useScrollToRef'; -import { autoScrollAtom } from '~/store/autoScroll'; +import useScrollToRef from './useScrollToRef'; + +/** What the list's scrolling follows: the rendered thread, its conversation, the pane's + * submission state and the viewer's auto-scroll preference. */ +export type MessageScrollingInput = { + messagesTree?: TMessage[] | null; + conversationId?: string | null; + isSubmitting: boolean; + /** Whether the reader vetoed riding the stream for the current turn. */ + abortScroll: boolean; + setAbortScroll: Dispatch>; + /** Whether opening a conversation lands the reader on its newest message. */ + autoScroll: boolean; +}; + +/** The scroll machinery of the message list. */ +export type MessageScrolling = { + /** Wraps the rendered thread. */ + contentRef: RefObject; + /** The scroll container. */ + scrollableRef: RefObject; + /** The zero-height marker after the last row. */ + messagesEndRef: RefObject; + /** Jumps to the end marker; absent until the target ref exists. */ + scrollToBottom?: ThrottledFunction; + /** Scrolls smoothly to the end, from the scroll-to-bottom control. */ + handleSmoothToRef: (event: MouseEvent) => void; + /** The container's scroll listener. */ + debouncedHandleScroll: () => void; + /** Reports whether the end marker is in view. */ + handleNearBottomChange: (isNearBottom: boolean) => void; +}; const resizeFollowThreshold = 120; @@ -25,9 +55,16 @@ const prefersReducedMotion = () => typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; -export default function useMessageScrolling(messagesTree?: TMessage[] | null) { - const autoScroll = useAtomValue(autoScrollAtom); - +/** Follows the stream, lands on a conversation's end once its rows mount, and keeps the + * reader's position when they scroll away. */ +export default function useMessageScrolling({ + messagesTree, + conversationId, + isSubmitting, + abortScroll, + setAbortScroll, + autoScroll, +}: MessageScrollingInput): MessageScrolling { const scrollableRef = useRef(null); const contentRef = useRef(null); const messagesEndRef = useRef(null); @@ -51,8 +88,6 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) { /** The conversation whose newest message has already been landed on, so the * stream deltas that follow cannot re-take a reader who scrolled away. */ const landedConversationRef = useRef(null); - const { conversation, conversationId } = useMessagesConversation(); - const { setAbortScroll, isSubmitting, abortScroll } = useMessagesSubmission(); const getIsNearBottom = useCallback(() => { const scrollEl = scrollableRef.current; @@ -134,7 +169,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) { * `Message` raises this on every wheel tick, downward ones included, so * it is set again on the way here; and the value this closure can see is * a render behind, so a conditional clear loses the race and leaves the - * ride vetoed for the rest of the answer. Recoil no-ops an unchanged + * ride vetoed for the rest of the answer. The setter no-ops an unchanged * write, so repeating it costs nothing. */ setAbortScroll(false); } @@ -409,7 +444,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) { return () => { if (abortScroll === true) { - scrollToBottom && scrollToBottom.cancel(); + scrollToBottom?.cancel(); } }; }, [isSubmitting, messagesTree, scrollToBottom, abortScroll, followBottom]); @@ -420,7 +455,7 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) { * Keyed on the conversation whose rows are actually MOUNTED, not on the id * alone. The id reaches this hook a commit or more before the tree does, and * firing on it scrolled the outgoing thread to its end and then never ran - * again — the reader was left wherever that put them, which on a long thread + * again: the reader was left wherever that put them, which on a long thread * is the top. Waiting for the rendered tree to name the same conversation * costs nothing and is the only moment `messages-end` is where the reader * expects it. @@ -469,7 +504,6 @@ export default function useMessageScrolling(messagesTree?: TMessage[] | null) { }, [autoScroll, conversationId, messagesTree, scrollToBottom]); return { - conversation, contentRef, scrollableRef, messagesEndRef, diff --git a/packages/chat/src/react/messages/useScrollToRef.ts b/packages/chat/src/react/messages/useScrollToRef.ts new file mode 100644 index 0000000000..d558e59ece --- /dev/null +++ b/packages/chat/src/react/messages/useScrollToRef.ts @@ -0,0 +1,98 @@ +import { useEffect, useMemo, useRef } from 'react'; +import type { MouseEventHandler, RefObject } from 'react'; + +type TUseScrollToRef = { + targetRef: RefObject; + callback: () => void; + smoothCallback: () => void; +}; + +/** A throttled call that runs on the leading edge and once more on the trailing edge. */ +export type ThrottledFunction = (() => void) & { + /** Drops the pending trailing call. */ + cancel: () => void; +}; + +type ScrollToRefReturn = { + scrollToRef?: ThrottledFunction; + handleSmoothToRef: MouseEventHandler; +}; + +/** Runs `run` at once, then at most once per `wait` ms while calls keep arriving: a call + * inside the window is deferred to the window's end, and that run opens the next window. */ +function throttle(run: () => void, wait: number): ThrottledFunction { + let timer: ReturnType | null = null; + let pending = false; + const closeWindow = () => { + if (!pending) { + timer = null; + return; + } + pending = false; + run(); + timer = setTimeout(closeWindow, wait); + }; + const throttled = () => { + if (timer != null) { + pending = true; + return; + } + run(); + timer = setTimeout(closeWindow, wait); + }; + throttled.cancel = () => { + if (timer != null) { + clearTimeout(timer); + } + timer = null; + pending = false; + }; + return throttled; +} + +export default function useScrollToRef({ + targetRef, + callback, + smoothCallback, +}: TUseScrollToRef): ScrollToRefReturn { + const callbacksRef = useRef({ callback, smoothCallback }); + useEffect(() => { + callbacksRef.current = { callback, smoothCallback }; + }, [callback, smoothCallback]); + + const scrollToRef = useMemo( + () => + throttle(() => { + targetRef.current?.scrollIntoView({ behavior: 'instant' }); + callbacksRef.current.callback(); + }, 145), + [targetRef], + ); + + const scrollToRefSmooth = useMemo( + () => + throttle(() => { + targetRef.current?.scrollIntoView({ behavior: 'smooth' }); + callbacksRef.current.smoothCallback(); + }, 750), + [targetRef], + ); + + useEffect( + () => () => { + scrollToRef.cancel(); + scrollToRefSmooth.cancel(); + }, + [scrollToRef, scrollToRefSmooth], + ); + + const handleSmoothToRef: MouseEventHandler = (e) => { + e.preventDefault(); + scrollToRefSmooth(); + }; + + return { + scrollToRef, + handleSmoothToRef, + }; +} diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx index de61ccf649..36f7efc270 100644 --- a/packages/chat/test/consumer.spec.tsx +++ b/packages/chat/test/consumer.spec.tsx @@ -228,14 +228,6 @@ const messagesHost: MessagesHost = { useGetMessages: () => () => undefined, useHasPendingTurn: () => false, renderMessageAudio: () => null, - useScrolling: () => ({ - contentRef: { current: null }, - scrollableRef: { current: null }, - messagesEndRef: { current: null }, - handleSmoothToRef: () => undefined, - debouncedHandleScroll: () => undefined, - handleNearBottomChange: () => undefined, - }), useScreenshotTarget: () => undefined, useAutoScroll: () => false, useConversationSeen: () => () => undefined,