Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📜 refactor: Move the MessagesView Root Into @librechat/chat (#17589)

Marco Berettae9e7c6b7b341
diff --git a/client/src/Providers/MessagesHostContext.tsx b/client/src/Providers/MessagesHostContext.tsx
index 1ee355def8..7a6b7f20d8 100644
--- a/client/src/Providers/MessagesHostContext.tsx
+++ b/client/src/Providers/MessagesHostContext.tsx
@@ -1,4 +1,5 @@
import { useCallback, useMemo, useRef } from 'react';
+import { useAtomValue } from 'jotai';
import { useRecoilState } from 'recoil';
import { setDefaultMessagesHost } from '@librechat/chat/react';
import type {
@@ -6,10 +7,16 @@ import type {
MessagesHost,
ForkPreferences,
ForkConversation,
+ MessagesScrolling,
} from '@librechat/chat/react';
+import type { TMessage } from 'librechat-data-provider';
+import useConversationSeen from '~/hooks/Conversations/useConversationSeen';
+import useMessageScrolling from '~/hooks/Messages/useMessageScrolling';
import Files from '~/components/Chat/Messages/Content/Files';
+import { useScreenshot } from '~/hooks/ScreenshotContext';
import { useForkConvoMutation } from '~/data-provider';
import useClockFormat from '~/hooks/useClockFormat';
+import { autoScrollAtom } from '~/store/autoScroll';
import { useNavigateToConvo } from '~/hooks';
import store from '~/store';
@@ -51,14 +58,26 @@ 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 };
+}
+
/** What the message list reads from the app: the viewer's clock format and fork defaults, the
- * fork request, and the row pieces that still live here. Registered as the default when this
- * module loads, so rows read it on every route, the shared view included. */
+ * fork request, its scrolling, screenshot and seen reporting, and the row pieces that still live
+ * here. Registered as the default when this module loads, so rows read it on every route, the
+ * shared view included. */
export const appMessagesHost: MessagesHost = {
useHour12: useClockFormat,
renderFiles: (message) => <Files message={message} />,
useForkPreferences: useAppForkPreferences,
useForkConversation: useAppForkConversation,
+
+ useScrolling,
+ useScreenshotTarget: () => useScreenshot().screenshotTargetRef,
+ useAutoScroll: () => useAtomValue(autoScrollAtom),
+ useConversationSeen,
};
setDefaultMessagesHost(appMessagesHost);
diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsx
index 4a12058d6b..1a41e87a1f 100644
--- a/client/src/components/Chat/Messages/MessagesView.tsx
+++ b/client/src/components/Chat/Messages/MessagesView.tsx
@@ -1,231 +1,72 @@
-import { useState, useCallback, useEffect } from 'react';
-import { useAtomValue } from 'jotai';
-import { Constants } from 'librechat-data-provider';
-import {
- useIsSubmitting,
- RowMountProvider,
- useScrollbarGutter,
- useProgressiveRowMount,
-} from '@librechat/chat/react';
+import { MessagesView as MessagesList } from '@librechat/chat/components';
+import type { MessagesThreadProps } from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
import { MessagePartsHostProvider, appMessagePartsHost } from '~/Providers/MessagePartsHostContext';
-import { useLocalize, useScreenshot, useMessageScrolling, useConversationSeen } from '~/hooks';
-import { MessagesViewProvider, useChatContext, useFileMapContext } from '~/Providers';
+import { MessagesViewProvider, useFileMapContext } from '~/Providers';
import { useChatSurface } from '~/components/Chat/Subagents/surface';
import useThreadRows from '~/hooks/Messages/useThreadRows';
import PendingSteers from './Content/Parts/PendingSteers';
-import { autoScrollAtom } from '~/store/autoScroll';
import { FLAT_THREAD, ThreadList } from './Thread';
-import { fontSizeAtom } from '~/store/fontSize';
import MultiMessage from './MultiMessage';
import ScrollButton from './ScrollButton';
import PendingTurn from './PendingTurn';
import MessageNav from './MessageNav';
-import { cn } from '~/utils';
+
+/** The flat thread renderer by default, the recursive one when the flag turns it off. */
+function Thread({
+ messagesTree,
+ messages,
+ conversationId,
+ currentEditId,
+ setCurrentEditId,
+}: MessagesThreadProps) {
+ const fileMap = useFileMapContext();
+ const threadRows = useThreadRows(FLAT_THREAD ? messages : null, conversationId, fileMap);
+ if (FLAT_THREAD && threadRows) {
+ return (
+ <ThreadList
+ rows={threadRows}
+ setCurrentEditId={setCurrentEditId}
+ currentEditId={currentEditId ?? null}
+ />
+ );
+ }
+ return (
+ <MultiMessage
+ messagesTree={messagesTree}
+ messageId={conversationId ?? null}
+ setCurrentEditId={setCurrentEditId}
+ currentEditId={currentEditId ?? null}
+ />
+ );
+}
function MessagesViewContent({
- messagesTree: _messagesTree,
+ messagesTree,
messages,
}: {
messagesTree?: TMessage[] | null;
messages?: TMessage[] | null;
}) {
- const localize = useLocalize();
- const fontSize = useAtomValue(fontSizeAtom);
- const { screenshotTargetRef } = useScreenshot();
- const [currentEditId, setCurrentEditId] = useState<number | string | null>(-1);
-
- const {
- conversation,
- contentRef,
- scrollableRef,
- messagesEndRef,
- handleSmoothToRef,
- debouncedHandleScroll,
- handleNearBottomChange,
- } = useMessageScrolling(_messagesTree);
-
- useScrollbarGutter(scrollableRef);
-
- const { conversationId } = conversation ?? {};
- const { index, latestMessageId, latestMessageDepth, messagesKey } = useChatContext();
- /** Re-arm from the conversation that owns the RENDERED tree: the Recoil
- * 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 fileMap = useFileMapContext();
- const threadRows = useThreadRows(FLAT_THREAD ? messages : null, treeConversationId, fileMap);
- const isSubmitting = useIsSubmitting(index);
const { showScrollButton, maximizeChatSpace } = useChatSurface();
- const autoScroll = useAtomValue(autoScrollAtom);
-
- /** 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
- * report comes; the seen hook re-measures the committed tree instead. Mirrors the
- * observer's near-bottom meaning: the end marker inside the scrollable viewport. */
- const measureNearBottom = useCallback(() => {
- const end = messagesEndRef.current;
- const scrollable = scrollableRef.current;
- if (!end || !scrollable) {
- return null;
- }
- return end.getBoundingClientRect().top <= scrollable.getBoundingClientRect().bottom + 1;
- }, [messagesEndRef, scrollableRef]);
-
- /** MessageRow owns the durable DOM id. Scoping the lookup to this content root prevents a stale
- * row in another mounted surface from proving a hidden sibling branch visible. A body child is
- * required because progressive mounting can expose the row shell before its body commits. */
- const isResponseRendered = useCallback(
- (messageId: string) => {
- const content = contentRef.current;
- const row = document.getElementById(messageId);
- if (!content || !row || !content.contains(row)) {
- return false;
- }
- const body = row.querySelector('[data-testid="message-body"]');
- return (
- body != null && (body.childElementCount > 0 || (body.textContent?.trim().length ?? 0) > 0)
- );
- },
- [contentRef],
- );
-
- /** Piggybacks the messages-end observer rather than adding a second one, and stays a plain
- * callback so intersection flips keep re-rendering only `ScrollButton`. */
- const reportNearBottom = useConversationSeen(
- conversationId ?? undefined,
- isSubmitting,
- measureNearBottom,
- isResponseRendered,
- );
- const handleNearBottom = useCallback(
- (isNearBottom: boolean) => {
- handleNearBottomChange(isNearBottom);
- reportNearBottom(isNearBottom);
- },
- [handleNearBottomChange, reportNearBottom],
- );
-
- const mountWindow = useProgressiveRowMount({
- tailDepth: latestMessageDepth,
- anchorBottom: autoScroll || isSubmitting,
- isSubmitting,
- conversationId: treeConversationId,
- scrollableRef,
- });
- useEffect(() => {
- const isNearBottom = measureNearBottom();
- if (isNearBottom != null) {
- reportNearBottom(isNearBottom);
- }
- }, [latestMessageId, measureNearBottom, mountWindow, reportNearBottom, _messagesTree]);
-
- /* The redesign renders pending steers inside the streaming reply rather than
- as a stack floating over the bottom of the thread, so there is no band to
- reserve here and nothing publishes an overlay height. Composer panels that
- do float (an answer popover, a tool-approval review) are handled by
- ScrollButton through `composerOverlayCountFamily`. */
- const overlayConversationId = conversationId ?? Constants.NEW_CONVO;
return (
- <>
- <div className="relative flex-1 overflow-hidden overflow-y-auto">
- <div className="relative h-full">
- <div
- className="scrollbar-gutter-stable overflow-y-auto"
- onScroll={debouncedHandleScroll}
- ref={scrollableRef}
- style={{
- height: '100%',
- width: '100%',
- /** The mount hook pins the anchor row itself (document-space
- * measurement); native scroll anchoring reacting to the same
- * insertions would double-correct. */
- overflowAnchor: mountWindow != null ? 'none' : undefined,
- }}
- >
- <div ref={contentRef} className="flex flex-col pt-14 pb-9">
- {(_messagesTree && _messagesTree.length == 0) || _messagesTree === null ? (
- <div
- className={cn(
- 'text-text-secondary flex w-full items-center justify-center p-3',
- fontSize,
- )}
- >
- {localize('com_ui_nothing_found')}
- </div>
- ) : (
- <>
- <div
- key={treeConversationId}
- ref={screenshotTargetRef}
- data-conversation-id={treeConversationId}
- data-testid="screenshot-target"
- >
- <RowMountProvider mountWindow={mountWindow}>
- {FLAT_THREAD && threadRows ? (
- <ThreadList
- rows={threadRows}
- setCurrentEditId={setCurrentEditId}
- currentEditId={currentEditId ?? null}
- />
- ) : (
- <MultiMessage
- messagesTree={_messagesTree}
- messageId={treeConversationId ?? null}
- setCurrentEditId={setCurrentEditId}
- currentEditId={currentEditId ?? null}
- />
- )}
- </RowMountProvider>
- </div>
- <PendingTurn
- scrollableRef={scrollableRef}
- messages={messages}
- maximizeChatSpace={maximizeChatSpace}
- />
- </>
- )}
- {/** The pending surface is renderer-independent: both ThreadList
- * and MultiMessage end at this shared thread tail. Keeping its
- * mount here also preserves recovery controls when the message
- * tree is temporarily empty during navigation or delivery.
- *
- * It keys off the RENDERED tree for the same reason the mount
- * window does: during warm-cache navigation the Recoil
- * conversation id still names the source chat, and its Cancel
- * and Escalate actions would mutate that run while sitting at
- * the destination thread's tail. */}
- {treeConversationId != null && (
- <PendingSteers
- conversationId={treeConversationId}
- index={index}
- fullWidth={maximizeChatSpace}
- />
- )}
- <div id="messages-end" className="group h-0 w-full shrink-0" ref={messagesEndRef} />
- </div>
- </div>
-
- <ScrollButton
- conversationId={overlayConversationId}
- enabled={showScrollButton}
- maximizeChatSpace={maximizeChatSpace}
- scrollableRef={scrollableRef}
- messagesEndRef={messagesEndRef}
- scrollHandler={handleSmoothToRef}
- onNearBottomChange={handleNearBottom}
- />
-
- <MessageNav
- key={treeConversationId}
- conversationId={treeConversationId}
- scrollableRef={scrollableRef}
- />
- </div>
- </div>
- </>
+ <MessagesList
+ messagesTree={messagesTree}
+ messages={messages}
+ showScrollButton={showScrollButton}
+ maximizeChatSpace={maximizeChatSpace}
+ renderThread={(props) => <Thread {...props} />}
+ renderPendingTurn={(props) => <PendingTurn {...props} />}
+ renderPendingSteers={(props) => <PendingSteers {...props} />}
+ renderScrollButton={(props) => <ScrollButton {...props} />}
+ renderNav={({ conversationId, scrollableRef }) => (
+ <MessageNav
+ key={conversationId}
+ conversationId={conversationId}
+ scrollableRef={scrollableRef}
+ />
+ )}
+ />
);
}
diff --git a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx
index e145a0cc3b..7d0c6bdc80 100644
--- a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx
+++ b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx
@@ -1,7 +1,10 @@
import React from 'react';
import { Provider, createStore } from 'jotai';
+import { ChatContext } from '@librechat/chat/react';
import { render, screen } from '@testing-library/react';
+import type { ChatContract } from '@librechat/chat/react';
import type { TMessage } from 'librechat-data-provider';
+import type { ReactElement } from 'react';
import { siblingIdxFamily } from '~/components/Chat/Messages/Thread/state';
import useThreadRows from '~/hooks/Messages/useThreadRows';
import * as thread from '~/utils/thread';
@@ -21,34 +24,11 @@ jest.mock('recoil', () => ({
useRecoilValue: () => false,
}));
-jest.mock('~/hooks', () => ({
- useScreenshot: () => ({ screenshotTargetRef: { current: null } }),
- useMessageScrolling: () => ({
- conversation: { conversationId: 'convo-1' },
- contentRef: { current: null },
- scrollableRef: { current: null },
- messagesEndRef: { current: null },
- handleSmoothToRef: jest.fn(),
- debouncedHandleScroll: jest.fn(),
- handleNearBottomChange: jest.fn(),
- }),
- useConversationSeen: () => jest.fn(),
- useLocalize: () => (key: string) => key,
-}));
-
jest.mock('~/Providers', () => ({
MessagesViewProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- useChatContext: () => ({ index: 0, latestMessageDepth: 0, messagesKey: mockMessagesKey }),
useFileMapContext: () => ({}),
}));
-jest.mock('@librechat/chat/react', () => ({
- ...jest.requireActual('@librechat/chat/react'),
- useScrollbarGutter: jest.fn(),
- RowMountProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
- useProgressiveRowMount: () => null,
-}));
-
jest.mock('~/hooks/Messages/useThreadRows', () => ({
__esModule: true,
default: jest.fn(() => []),
@@ -58,7 +38,6 @@ jest.mock('~/components/Chat/Subagents/surface', () => ({
useChatSurface: () => ({ showScrollButton: false, maximizeChatSpace: mockMaximizeChatSpace }),
}));
-jest.mock('~/store/autoScroll', () => ({ autoScrollAtom: {} }));
jest.mock('~/store', () => ({
__esModule: true,
default: {},
@@ -111,12 +90,24 @@ jest.mock('../MessageNav', () => {
};
});
-jest.mock('~/utils', () => ({
- cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
-}));
-
import MessagesView from '../MessagesView';
+/** The pane's chat contract, as far as the list reads it: the pane and the routed key. */
+const withChat = (ui: ReactElement) => (
+ <ChatContext.Provider
+ value={
+ {
+ index: 0,
+ isSubmitting: false,
+ latestMessageDepth: 0,
+ messagesKey: mockMessagesKey,
+ } as unknown as ChatContract
+ }
+ >
+ {ui}
+ </ChatContext.Provider>
+);
+
const messageTree = [
{
messageId: 'assistant-1',
@@ -133,7 +124,7 @@ describe('MessagesView pending steers', () => {
});
it('keeps the failed-steer surface mounted in the recursive renderer', () => {
- render(<MessagesView messagesTree={messageTree} messages={messageTree} />);
+ render(withChat(<MessagesView messagesTree={messageTree} messages={messageTree} />));
expect(screen.getByTestId('multi-message')).toBeInTheDocument();
expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-1');
@@ -144,7 +135,7 @@ describe('MessagesView pending steers', () => {
'passes the host chat width preference (%s) to pending steers',
(fullWidth) => {
mockMaximizeChatSpace = fullWidth;
- render(<MessagesView messagesTree={messageTree} messages={messageTree} />);
+ render(withChat(<MessagesView messagesTree={messageTree} messages={messageTree} />));
expect(screen.getByTestId('pending-steers')).toHaveAttribute(
'data-full-width',
@@ -156,7 +147,7 @@ describe('MessagesView pending steers', () => {
it('passes the full-width preference in the flat renderer too', () => {
mockMaximizeChatSpace = true;
mockFlatThread = true;
- render(<MessagesView messagesTree={messageTree} messages={messageTree} />);
+ render(withChat(<MessagesView messagesTree={messageTree} messages={messageTree} />));
expect(screen.getByTestId('flat-thread')).toBeInTheDocument();
expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-full-width', 'true');
@@ -171,7 +162,7 @@ describe('MessagesView pending steers', () => {
{ messageId: 'assistant-2', conversationId: 'convo-2' },
] as unknown as TMessage[];
- render(<MessagesView messagesTree={destinationTree} messages={destinationTree} />);
+ render(withChat(<MessagesView messagesTree={destinationTree} messages={destinationTree} />));
expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-2');
});
@@ -187,9 +178,9 @@ describe('MessagesView pending steers', () => {
messageId: `large-${index}`,
parentMessageId: index === 0 ? null : `large-${index - 1}`,
}));
- const view = render(<MessagesView messagesTree={large} messages={large} />);
+ const view = render(withChat(<MessagesView messagesTree={large} messages={large} />));
const small = [{ ...messageTree[0], conversationId: 'convo-2', messageId: 'small' }];
- view.rerender(<MessagesView messagesTree={small} messages={small} />);
+ view.rerender(withChat(<MessagesView messagesTree={small} messages={small} />));
expect(resolve).toHaveBeenLastCalledWith(expect.anything(), 'convo-2', expect.anything(), null);
view.unmount();
@@ -210,7 +201,7 @@ describe('MessagesView pending steers', () => {
];
render(
<Provider store={jotaiStore}>
- <MessagesView messagesTree={destination} messages={destination} />
+ {withChat(<MessagesView messagesTree={destination} messages={destination} />)}
</Provider>,
);
@@ -221,25 +212,31 @@ describe('MessagesView pending steers', () => {
it('uses the rendered owner for recursive root sibling choices too', () => {
const destination = [{ ...messageTree[0], conversationId: 'convo-2' }];
- render(<MessagesView messagesTree={destination} messages={destination} />);
+ render(withChat(<MessagesView messagesTree={destination} messages={destination} />));
expect(screen.getByTestId('multi-message')).toHaveAttribute('data-parent-id', 'convo-2');
});
- it('uses the routed owner for flat rows when the destination tree is empty', () => {
+ it('shows the empty note instead of a thread while the destination tree is empty', () => {
mockFlatThread = true;
mockMessagesKey = 'convo-2';
- render(<MessagesView messagesTree={[]} messages={[]} />);
+ render(withChat(<MessagesView messagesTree={[]} messages={[]} />));
- expect(useThreadRows).toHaveBeenLastCalledWith([], 'convo-2', expect.anything());
+ expect(screen.getByText('Nothing found')).toBeInTheDocument();
+ expect(screen.queryByTestId('flat-thread')).not.toBeInTheDocument();
+ expect(useThreadRows).not.toHaveBeenCalled();
});
it('pins the screenshot identity to the rendered transcript and replaces it on navigation', () => {
- const view = render(<MessagesView messagesTree={messageTree} messages={messageTree} />);
+ const view = render(
+ withChat(<MessagesView messagesTree={messageTree} messages={messageTree} />),
+ );
const initialTarget = screen.getByTestId('screenshot-target');
expect(initialTarget).toHaveAttribute('data-conversation-id', 'convo-1');
const destinationTree = [{ ...messageTree[0], conversationId: 'convo-2' }];
- view.rerender(<MessagesView messagesTree={destinationTree} messages={destinationTree} />);
+ view.rerender(
+ withChat(<MessagesView messagesTree={destinationTree} messages={destinationTree} />),
+ );
const destinationTarget = screen.getByTestId('screenshot-target');
expect(destinationTarget).toHaveAttribute('data-conversation-id', 'convo-2');
expect(destinationTarget).not.toBe(initialTarget);
@@ -247,22 +244,24 @@ describe('MessagesView pending steers', () => {
});
it('releases the outgoing navigation rail on a warm switch, not on same-chat updates', () => {
- const view = render(<MessagesView messagesTree={messageTree} messages={messageTree} />);
+ const view = render(
+ withChat(<MessagesView messagesTree={messageTree} messages={messageTree} />),
+ );
expect(mockNavMount).toHaveBeenCalledTimes(1);
const updated = [{ ...messageTree[0], text: 'updated' }];
- view.rerender(<MessagesView messagesTree={updated} messages={updated} />);
+ view.rerender(withChat(<MessagesView messagesTree={updated} messages={updated} />));
expect(mockNavMount).toHaveBeenCalledTimes(1);
expect(mockNavUnmount).not.toHaveBeenCalled();
const destination = [{ ...messageTree[0], conversationId: 'convo-2' }];
- view.rerender(<MessagesView messagesTree={destination} messages={destination} />);
+ view.rerender(withChat(<MessagesView messagesTree={destination} messages={destination} />));
expect(mockNavUnmount).toHaveBeenCalledTimes(1);
expect(mockNavMount).toHaveBeenCalledTimes(2);
});
it('keeps recovery visible while the message tree is temporarily empty', () => {
- render(<MessagesView messagesTree={[]} messages={[]} />);
+ render(withChat(<MessagesView messagesTree={[]} messages={[]} />));
expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-1');
});
@@ -271,7 +270,7 @@ describe('MessagesView pending steers', () => {
/** Warm navigation to a chat whose tree is still empty: no message names the
* destination, and the context still names the source run. */
mockMessagesKey = 'convo-2';
- render(<MessagesView messagesTree={[]} messages={[]} />);
+ render(withChat(<MessagesView messagesTree={[]} messages={[]} />));
expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-2');
});
diff --git a/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts b/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts
index 65ef33011a..2a758b99f4 100644
--- a/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts
+++ b/e2e/specs/mock/scenarios/long-conversation-mount.spec.ts
@@ -62,4 +62,28 @@ test.describe('long conversations', () => {
await latest.scrollIntoViewIfNeeded();
await expect(latest).toBeInViewport();
});
+
+ test('the scroll control appears once the reader scrolls up and lands on the latest turn @scenario:scroll-control-lands-on-the-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);
+ const latest = thread.getByText(`Turn ${TURNS} of the long conversation`, { exact: true });
+ await thread
+ .getByText('Turn 1 of the long conversation', { exact: true })
+ .scrollIntoViewIfNeeded();
+ await expect(latest).not.toBeInViewport();
+
+ /** The thread's own control, not the navigation rail's end marker, which shares its name. */
+ const scrollControl = page
+ .getByRole('button', { name: 'Scroll to bottom' })
+ .and(page.locator(':not([data-msg-id])'));
+ await expect(scrollControl).toBeEnabled();
+ await scrollControl.click();
+
+ await expect(latest).toBeInViewport();
+ await expect(scrollControl).toBeHidden();
+ });
});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 4e9470adda..d3cba89fce 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -418,11 +418,6 @@
"count": 1
}
},
- "client/src/components/Chat/Messages/MessagesView.tsx": {
- "shadcn/no-inline-styles": {
- "count": 1
- }
- },
"client/src/components/Chat/Messages/MinimalHoverButtons.tsx": {
"shadcn/no-restyle": {
"count": 2
diff --git a/packages/chat/src/__fixtures__/messagesHost.ts b/packages/chat/src/__fixtures__/messagesHost.ts
index e45c1d76d9..7918fe485c 100644
--- a/packages/chat/src/__fixtures__/messagesHost.ts
+++ b/packages/chat/src/__fixtures__/messagesHost.ts
@@ -1,7 +1,7 @@
import type { MessagesHost } from '../react/messages/host';
-/** A messages host for specs: locale clock, no slots, no forking, with the members a spec needs
- * overridden. */
+/** A messages host for specs: locale clock, no slots, no forking, inert scrolling, with the
+ * members a spec needs overridden. */
export function createMessagesHost(overrides: Partial<MessagesHost> = {}): MessagesHost {
return {
useHour12: () => undefined,
@@ -15,6 +15,17 @@ export function createMessagesHost(overrides: Partial<MessagesHost> = {}): Messa
setRememberOption: () => undefined,
}),
useForkConversation: () => null,
+ useScrolling: () => ({
+ contentRef: { current: null },
+ scrollableRef: { current: null },
+ messagesEndRef: { current: null },
+ handleSmoothToRef: () => undefined,
+ debouncedHandleScroll: () => undefined,
+ handleNearBottomChange: () => undefined,
+ }),
+ useScreenshotTarget: () => undefined,
+ useAutoScroll: () => false,
+ useConversationSeen: () => () => undefined,
...overrides,
};
}
diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts
index 043034baec..f88c4fe6c7 100644
--- a/packages/chat/src/components.ts
+++ b/packages/chat/src/components.ts
@@ -108,3 +108,11 @@ export { default as ChatPane } from './components/pane/ChatPane';
export { getChatPaneView } from './components/pane/view';
export type { ChatPaneProps } from './components/pane/ChatPane';
export type { ChatPaneView, ChatPaneColumn } from './components/pane/view';
+
+/** Message list root: the scroll container, mount window and pending tail around the thread. */
+export { default as MessagesView } from './components/messages/MessagesView';
+export type {
+ MessagesViewProps,
+ MessagesThreadProps,
+ MessagesScrollButtonProps,
+} from './components/messages/MessagesView';
diff --git a/packages/chat/src/components/messages/MessagesView.tsx b/packages/chat/src/components/messages/MessagesView.tsx
new file mode 100644
index 0000000000..1440efce8f
--- /dev/null
+++ b/packages/chat/src/components/messages/MessagesView.tsx
@@ -0,0 +1,258 @@
+import { useState, useCallback, useEffect } from 'react';
+import { Constants } from 'librechat-data-provider';
+import { cn, useLocalize } from '@librechat/client';
+import type {
+ Dispatch,
+ RefObject,
+ ReactNode,
+ MouseEvent,
+ ReactElement,
+ SetStateAction,
+} from 'react';
+import type { TMessage } from 'librechat-data-provider';
+import {
+ RowMountProvider,
+ useProgressiveRowMount,
+} from '../../react/messages/useProgressiveRowMount';
+import useScrollbarGutter from '../../react/messages/useScrollbarGutter';
+import { useMessagesHost } from '../../react/messages/host';
+import { useChatContext } from '../../react/chat/context';
+import { useMessagePartsHost } from '../../react/host';
+
+/** What the thread slot renders the conversation from. */
+export type MessagesThreadProps = {
+ messagesTree?: TMessage[];
+ messages?: TMessage[] | null;
+ /** The conversation that owns the rendered tree. */
+ conversationId?: string | null;
+ currentEditId: string | number | null;
+ setCurrentEditId: Dispatch<SetStateAction<string | number | null>>;
+};
+
+/** What the scroll-to-bottom slot needs to watch the end marker and scroll to it. */
+export type MessagesScrollButtonProps = {
+ conversationId: string;
+ enabled: boolean;
+ maximizeChatSpace: boolean;
+ scrollableRef: RefObject<HTMLDivElement>;
+ messagesEndRef: RefObject<HTMLDivElement>;
+ scrollHandler: (event: MouseEvent<HTMLButtonElement>) => void;
+ onNearBottomChange: (isNearBottom: boolean) => void;
+};
+
+export type MessagesViewProps = {
+ messagesTree?: TMessage[] | null;
+ messages?: TMessage[] | null;
+ /** The viewer's preference for the scroll-to-bottom control. */
+ showScrollButton: boolean;
+ /** The viewer's chat-width preference. */
+ maximizeChatSpace: boolean;
+ /** Renders the conversation's rows. */
+ renderThread: (props: MessagesThreadProps) => ReactNode;
+ /** Renders the turn the reader just sent, ahead of its reply, at the thread's tail. */
+ renderPendingTurn?: (props: {
+ scrollableRef: RefObject<HTMLDivElement>;
+ messages?: TMessage[] | null;
+ maximizeChatSpace: boolean;
+ }) => ReactNode;
+ /** Renders the steers waiting on the conversation's run, after the last row. */
+ renderPendingSteers?: (props: {
+ conversationId: string;
+ index: number;
+ fullWidth: boolean;
+ }) => ReactNode;
+ /** Renders the scroll-to-bottom control. */
+ renderScrollButton?: (props: MessagesScrollButtonProps) => ReactNode;
+ /** Renders the in-thread navigation rail. */
+ renderNav?: (props: {
+ conversationId?: string | null;
+ scrollableRef: RefObject<HTMLDivElement>;
+ }) => ReactNode;
+};
+
+/**
+ * The message list: the scroll container, the rendered thread with its progressive mount
+ * window, the pending tail, and the end marker the scroll and seen reporting watch. The rows,
+ * the pending pieces, the scroll control and the navigation rail arrive as slots.
+ */
+export default function MessagesView({
+ messagesTree,
+ messages,
+ showScrollButton,
+ maximizeChatSpace,
+ renderThread,
+ renderPendingTurn,
+ renderPendingSteers,
+ renderScrollButton,
+ renderNav,
+}: MessagesViewProps): ReactElement {
+ const localize = useLocalize();
+ const host = useMessagesHost();
+ const fontSize = useMessagePartsHost().useFontSize();
+ const screenshotTargetRef = host.useScreenshotTarget();
+ const [currentEditId, setCurrentEditId] = useState<string | number | null>(-1);
+
+ const {
+ conversationId,
+ contentRef,
+ scrollableRef,
+ messagesEndRef,
+ handleSmoothToRef,
+ debouncedHandleScroll,
+ handleNearBottomChange,
+ } = host.useScrolling(messagesTree);
+
+ 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
+ * report comes; the seen hook re-measures the committed tree instead. Mirrors the
+ * observer's near-bottom meaning: the end marker inside the scrollable viewport. */
+ const measureNearBottom = useCallback(() => {
+ const end = messagesEndRef.current;
+ const scrollable = scrollableRef.current;
+ if (!end || !scrollable) {
+ return null;
+ }
+ return end.getBoundingClientRect().top <= scrollable.getBoundingClientRect().bottom + 1;
+ }, [messagesEndRef, scrollableRef]);
+
+ /** MessageRow owns the durable DOM id. Scoping the lookup to this content root prevents a stale
+ * row in another mounted surface from proving a hidden sibling branch visible. A body child is
+ * required because progressive mounting can expose the row shell before its body commits. */
+ const isResponseRendered = useCallback(
+ (messageId: string) => {
+ const content = contentRef.current;
+ const row = document.getElementById(messageId);
+ if (!content || !row || !content.contains(row)) {
+ return false;
+ }
+ const body = row.querySelector('[data-testid="message-body"]');
+ return (
+ body != null && (body.childElementCount > 0 || (body.textContent?.trim().length ?? 0) > 0)
+ );
+ },
+ [contentRef],
+ );
+
+ /** Piggybacks the messages-end observer rather than adding a second one, and stays a plain
+ * callback so intersection flips keep re-rendering only the scroll control. */
+ const reportNearBottom = host.useConversationSeen(
+ conversationId ?? undefined,
+ isSubmitting,
+ measureNearBottom,
+ isResponseRendered,
+ );
+ const handleNearBottom = useCallback(
+ (isNearBottom: boolean) => {
+ handleNearBottomChange(isNearBottom);
+ reportNearBottom(isNearBottom);
+ },
+ [handleNearBottomChange, reportNearBottom],
+ );
+
+ const mountWindow = useProgressiveRowMount({
+ tailDepth: latestMessageDepth,
+ anchorBottom: autoScroll || isSubmitting,
+ isSubmitting,
+ conversationId: treeConversationId,
+ scrollableRef,
+ });
+ useEffect(() => {
+ const isNearBottom = measureNearBottom();
+ if (isNearBottom != null) {
+ reportNearBottom(isNearBottom);
+ }
+ }, [latestMessageId, measureNearBottom, mountWindow, reportNearBottom, messagesTree]);
+
+ /* Pending steers render inside the streaming reply rather than as a stack floating over the
+ bottom of the thread, so there is no band to reserve here and nothing publishes an overlay
+ height. Composer panels that do float (an answer popover, a tool-approval review) are
+ handled by the scroll control through `composerOverlayCountFamily`. */
+ const overlayConversationId = conversationId ?? Constants.NEW_CONVO;
+ return (
+ <div className="relative flex-1 overflow-hidden overflow-y-auto">
+ <div className="relative h-full">
+ {/* The mount hook pins the anchor row itself (document-space measurement); native
+ scroll anchoring reacting to the same insertions would double-correct. */}
+ <div
+ className={cn(
+ 'h-full w-full scrollbar-gutter-stable overflow-y-auto',
+ mountWindow != null && '[overflow-anchor:none]',
+ )}
+ onScroll={debouncedHandleScroll}
+ ref={scrollableRef}
+ >
+ <div ref={contentRef} className="flex flex-col pt-14 pb-9">
+ {messagesTree === null || messagesTree?.length === 0 ? (
+ <div
+ className={cn(
+ 'text-text-secondary flex w-full items-center justify-center p-3',
+ fontSize,
+ )}
+ >
+ {localize('com_ui_nothing_found')}
+ </div>
+ ) : (
+ <>
+ <div
+ key={treeConversationId}
+ ref={screenshotTargetRef}
+ data-conversation-id={treeConversationId}
+ data-testid="screenshot-target"
+ >
+ <RowMountProvider mountWindow={mountWindow}>
+ {renderThread({
+ messagesTree,
+ messages,
+ conversationId: treeConversationId,
+ currentEditId,
+ setCurrentEditId,
+ })}
+ </RowMountProvider>
+ </div>
+ {renderPendingTurn?.({ scrollableRef, messages, maximizeChatSpace })}
+ </>
+ )}
+ {/** The pending surface is renderer-independent: every thread renderer ends at
+ * this shared tail. Keeping its mount here also preserves recovery controls when
+ * the tree is temporarily empty during navigation or delivery.
+ *
+ * It keys off the RENDERED tree for the same reason the mount window does: during
+ * warm-cache navigation the app's conversation id still names the source chat, and
+ * its Cancel and Escalate actions would mutate that run while sitting at the
+ * destination thread's tail. */}
+ {treeConversationId != null &&
+ renderPendingSteers?.({
+ conversationId: treeConversationId,
+ index,
+ fullWidth: maximizeChatSpace,
+ })}
+ <div id="messages-end" className="group h-0 w-full shrink-0" ref={messagesEndRef} />
+ </div>
+ </div>
+
+ {renderScrollButton?.({
+ conversationId: overlayConversationId,
+ enabled: showScrollButton,
+ maximizeChatSpace,
+ scrollableRef,
+ messagesEndRef,
+ scrollHandler: handleSmoothToRef,
+ onNearBottomChange: handleNearBottom,
+ })}
+
+ {renderNav?.({ conversationId: treeConversationId, scrollableRef })}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx b/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx
new file mode 100644
index 0000000000..298d02ef5a
--- /dev/null
+++ b/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx
@@ -0,0 +1,202 @@
+/**
+ * @jest-environment jsdom
+ */
+import { useRef } from 'react';
+import { 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 { ChatContract } from '../../../react/chat/contract';
+import type { MessagePartsHost } from '../../../react/host';
+import { createMessagesHost } from '../../../__fixtures__/messagesHost';
+import { MessagesHostProvider } from '../../../react/messages/host';
+import { MessagePartsHostProvider } from '../../../react/host';
+import { ChatContext } from '../../../react/chat/context';
+import { initEnglish } from '../../../__fixtures__/i18n';
+import MessagesView from '../MessagesView';
+
+beforeAll(initEnglish);
+
+const tree = [{ messageId: 'reply-1', conversationId: 'convo-1' }] as TMessage[];
+
+const partsHost = { useFontSize: () => 'text-base' } as unknown as MessagePartsHost;
+
+function createHost(overrides: Partial<MessagesHost> = {}) {
+ 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<HTMLDivElement>(null);
+ const scrollableRef = useRef<HTMLDivElement>(null);
+ const messagesEndRef = useRef<HTMLDivElement>(null);
+ scrolling.current = {
+ conversationId: 'convo-1',
+ contentRef,
+ scrollableRef,
+ messagesEndRef,
+ handleSmoothToRef: jest.fn(),
+ debouncedHandleScroll: jest.fn(),
+ handleNearBottomChange: jest.fn(),
+ };
+ return scrolling.current;
+ },
+ useScreenshotTarget: () => useRef<HTMLDivElement>(null),
+ useAutoScroll: () => false,
+ useConversationSeen,
+ ...overrides,
+ });
+ return { host, scrolling, reportNearBottom, useConversationSeen };
+}
+
+const contract = {
+ index: 0,
+ isSubmitting: false,
+ latestMessageDepth: 0,
+ messagesKey: 'convo-1',
+} as ChatContract;
+
+function renderView(props: Partial<MessagesViewProps>, host: MessagesHost, chat = contract) {
+ const view = (next: Partial<MessagesViewProps>) => (
+ <ChatContext.Provider value={chat}>
+ <MessagesHostProvider host={host}>
+ <MessagePartsHostProvider host={partsHost}>
+ <MessagesView
+ messagesTree={tree}
+ messages={tree}
+ showScrollButton
+ maximizeChatSpace={false}
+ renderThread={({ conversationId }) => (
+ <ol aria-label="Thread" data-conversation-id={conversationId} />
+ )}
+ {...props}
+ {...next}
+ />
+ </MessagePartsHostProvider>
+ </MessagesHostProvider>
+ </ChatContext.Provider>
+ );
+ const result = render(view({}));
+ return {
+ ...result,
+ rerenderView: (next: Partial<MessagesViewProps>) => result.rerender(view(next)),
+ };
+}
+
+describe('MessagesView', () => {
+ it('renders the thread inside the screenshot target of the conversation it belongs to', () => {
+ renderView({}, createHost().host);
+
+ const target = screen.getByTestId('screenshot-target');
+ expect(target).toHaveAttribute('data-conversation-id', 'convo-1');
+ expect(target).toContainElement(screen.getByRole('list', { name: 'Thread' }));
+ });
+
+ it('shows the empty note instead of a thread for an empty tree', () => {
+ const renderThread = jest.fn(() => null);
+ renderView({ messagesTree: [], messages: [], renderThread }, createHost().host);
+
+ expect(screen.getByText('Nothing found')).toBeInTheDocument();
+ expect(renderThread).not.toHaveBeenCalled();
+ });
+
+ it('keys the thread and the rail to the rendered tree, not the lagging conversation', () => {
+ const renderNav = jest.fn(() => null);
+ const destination = [{ messageId: 'reply-2', conversationId: 'convo-2' }] as TMessage[];
+ renderView({ messagesTree: destination, messages: destination, renderNav }, createHost().host);
+
+ expect(screen.getByRole('list', { name: 'Thread' })).toHaveAttribute(
+ 'data-conversation-id',
+ 'convo-2',
+ );
+ expect(renderNav).toHaveBeenLastCalledWith(
+ expect.objectContaining({ conversationId: 'convo-2' }),
+ );
+ });
+
+ it('keys the pending steers to the routed conversation while the tree is empty', () => {
+ const renderPendingSteers = jest.fn(() => null);
+ renderView(
+ { messagesTree: [], messages: [], renderPendingSteers, maximizeChatSpace: true },
+ createHost().host,
+ { ...contract, messagesKey: 'convo-2' } as ChatContract,
+ );
+
+ expect(renderPendingSteers).toHaveBeenLastCalledWith({
+ conversationId: 'convo-2',
+ index: 0,
+ fullWidth: true,
+ });
+ });
+
+ it('replaces the screenshot target when the rendered conversation changes', () => {
+ const { rerenderView } = renderView({}, createHost().host);
+ const first = screen.getByTestId('screenshot-target');
+
+ const destination = [{ messageId: 'reply-2', conversationId: 'convo-2' }] as TMessage[];
+ rerenderView({ messagesTree: destination, messages: destination });
+
+ expect(screen.getByTestId('screenshot-target')).not.toBe(first);
+ expect(first.isConnected).toBe(false);
+ });
+
+ it('wires the scroll control to the end marker and to both near-bottom listeners', () => {
+ const { host, scrolling, reportNearBottom } = createHost();
+ let button: MessagesScrollButtonProps | undefined;
+ const { container } = renderView(
+ {
+ renderScrollButton: (props) => {
+ button = props;
+ return null;
+ },
+ },
+ host,
+ );
+
+ 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);
+
+ button?.onNearBottomChange(false);
+ expect(scrolling.current?.handleNearBottomChange).toHaveBeenCalledWith(false);
+ expect(reportNearBottom).toHaveBeenCalledWith(false);
+ });
+
+ it('asks the seen reporter about the conversation and whether a reply has rendered', () => {
+ const { host, useConversationSeen } = createHost();
+ renderView(
+ {
+ renderThread: () => (
+ <div id="reply-1">
+ <div data-testid="message-body">Hello</div>
+ </div>
+ ),
+ },
+ host,
+ );
+
+ expect(useConversationSeen).toHaveBeenCalledWith(
+ 'convo-1',
+ false,
+ expect.any(Function),
+ expect.any(Function),
+ );
+ const { calls } = useConversationSeen.mock;
+ const isResponseRendered = calls[calls.length - 1][3];
+ expect(isResponseRendered('reply-1')).toBe(true);
+ expect(isResponseRendered('elsewhere')).toBe(false);
+ });
+
+ it('listens to the scroll container and keeps native scroll anchoring outside a mount window', () => {
+ const { host, scrolling } = createHost();
+ renderView({}, host);
+
+ const scrollable = scrolling.current?.scrollableRef.current;
+ expect(scrollable).toHaveClass('scrollbar-gutter-stable', 'overflow-y-auto');
+ expect(scrollable).not.toHaveClass('[overflow-anchor:none]');
+ });
+});
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index bc3b5a781d..00ac7a83c9 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -133,6 +133,8 @@ export type {
MessagesHost,
ForkPreferences,
ForkConversation,
+ MessagesScrolling,
+ ReportNearBottom,
} from './react/messages/host';
export {
SoleToolContext,
diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx
index 52b82f4bcf..4f729e65ca 100644
--- a/packages/chat/src/react/messages/host.tsx
+++ b/packages/chat/src/react/messages/host.tsx
@@ -1,6 +1,27 @@
-import { createContext, useContext } from 'react';
+import { useRef, createContext, useContext } from 'react';
import type { TMessage, TForkConvoRequest } from 'librechat-data-provider';
-import type { ReactNode } from 'react';
+import type { MouseEvent, ReactNode, RefObject } 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<HTMLDivElement>;
+ /** The scroll container. */
+ scrollableRef: RefObject<HTMLDivElement>;
+ /** The zero-height marker after the last row. */
+ messagesEndRef: RefObject<HTMLDivElement>;
+ /** Scrolls smoothly to the end, from the scroll-to-bottom control. */
+ handleSmoothToRef: (event: MouseEvent<HTMLButtonElement>) => void;
+ /** The container's scroll listener. */
+ debouncedHandleScroll: () => void;
+ /** Reports whether the end marker is in view. */
+ handleNearBottomChange: (isNearBottom: boolean) => void;
+};
+
+/** Reports, from the end marker's visibility, that the reader has seen the conversation. */
+export type ReportNearBottom = (isNearBottom: boolean) => void;
/** The viewer's fork defaults, kept across sessions. */
export type ForkPreferences = {
@@ -41,6 +62,27 @@ export interface MessagesHost {
useForkPreferences: () => ForkPreferences;
/** Forks a conversation and opens the copy; `null` where forking is unavailable. */
useForkConversation: () => ForkConversation | null;
+
+ /**
+ * 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<HTMLDivElement> | undefined;
+ /** Whether the viewer asked the thread to follow new content to the bottom. */
+ useAutoScroll: () => boolean;
+ /** Marks the conversation seen once its latest reply is on screen; returns the reporter the
+ * end marker's visibility feeds. */
+ useConversationSeen: (
+ conversationId: string | undefined,
+ isSubmitting: boolean,
+ measureNearBottom: () => boolean | null,
+ isResponseRendered: (messageId: string) => boolean,
+ ) => ReportNearBottom;
}
const noop = (): void => undefined;
@@ -54,12 +96,34 @@ const fallbackForkPreferences: ForkPreferences = {
setRememberOption: noop,
};
+/** Scrolling with nothing behind it: live refs, inert handlers. */
+function useInertScrolling(): MessagesScrolling {
+ const contentRef = useRef<HTMLDivElement>(null);
+ const scrollableRef = useRef<HTMLDivElement>(null);
+ const messagesEndRef = useRef<HTMLDivElement>(null);
+ return {
+ contentRef,
+ scrollableRef,
+ messagesEndRef,
+ handleSmoothToRef: () => undefined,
+ debouncedHandleScroll: () => undefined,
+ handleNearBottomChange: () => undefined,
+ };
+}
+
+const ignoreNearBottom: ReportNearBottom = () => undefined;
+
/** The host rows read outside any provider before an app registers one: locale clock, no slots, no forking. */
const fallbackHost: MessagesHost = {
useHour12: () => undefined,
renderFiles: () => null,
useForkPreferences: () => fallbackForkPreferences,
useForkConversation: () => null,
+
+ useScrolling: useInertScrolling,
+ useScreenshotTarget: () => useRef<HTMLDivElement>(null),
+ useAutoScroll: () => false,
+ useConversationSeen: () => ignoreNearBottom,
};
const MessagesHostContext = createContext<MessagesHost | null>(null);
diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx
index 664a8908d8..9f6da2aa1d 100644
--- a/packages/chat/test/consumer.spec.tsx
+++ b/packages/chat/test/consumer.spec.tsx
@@ -187,6 +187,17 @@ const messagesHost: MessagesHost = {
setRememberOption: () => undefined,
}),
useForkConversation: () => null,
+ useScrolling: () => ({
+ contentRef: { current: null },
+ scrollableRef: { current: null },
+ messagesEndRef: { current: null },
+ handleSmoothToRef: () => undefined,
+ debouncedHandleScroll: () => undefined,
+ handleNearBottomChange: () => undefined,
+ }),
+ useScreenshotTarget: () => undefined,
+ useAutoScroll: () => false,
+ useConversationSeen: () => () => undefined,
};
const renderers: PartRenderers = {