⏳ refactor: Render the Pending Turn and Steers From @librechat/chat by Default (#18134)

- refactor: Render Pending Turn and Steers from the Package
- refactor: Keep Package Pending Rows Inert Without a Steer Host
- fix: Read the Host Thread Mode on Every Render
- fix: Point the Hosts Guard at the Messages Loader
- fix: Follow the Moved Pending Rows in the Guard and Lazy Chunk Specs
- fix: Ship Message Body Typography With the Shared Theme Styles
- fix: Keep the App Message Typography Cascade With the Shared Styles
This commit is contained in:
Marco Beretta 2026-11-14 17:01:27 +01:00 • committed by GitHub
parent 4c6da07a7a
commit e714aba067
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 844 additions and 525 deletions

View file

@ -24,17 +24,22 @@
"client/src/__tests__/hosts.test.tsx": [
"client/src/App.jsx",
"client/src/components/Chat/Messages/hosts.ts",
"client/src/components/Chat/Messages/slots.tsx",
"client/src/components/Chat/Messages/load.tsx",
"client/src/components/Chat/Presentation.tsx",
"client/src/routes/ShareRoute.tsx",
"client/src/routes/Search.tsx"
],
"client/src/__tests__/messageContentCascade.spec.ts": [
"client/src/style.css",
"packages/client/src/theme/parts.css"
],
"client/src/__tests__/loadingCanvas.spec.ts": ["client/index.html"],
"client/src/__tests__/loadingSpinner.spec.tsx": ["client/index.html"],
"client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts": [
"client/src/components/Chat/",
"client/src/hooks/Input/usePaletteEntries.tsx",
"packages/chat/src/components/composer/"
"packages/chat/src/components/composer/",
"packages/chat/src/components/messages/PendingSteers.tsx"
],
"client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts": [
"client/src/components/Chat/Input/",
@ -79,6 +84,7 @@
],
"packages/client/src/components/__tests__/radixLayers.spec.ts": ["package-lock.json"],
"packages/client/src/theme/defaults.spec.ts": ["packages/client/src/theme/defaults.css"],
"packages/client/src/theme/parts.spec.ts": ["packages/client/src/theme/parts.css"],
"packages/client/src/theme/primitives.spec.ts": [
"eslint-suppressions.json",
"packages/client/src/components/"

View file

@ -32,6 +32,7 @@ import useConversationSeenSource from '~/hooks/Conversations/seenSource';
import useGetAddedConvo from '~/hooks/Conversations/useGetAddedConvo';
import { useOptionalMessagesOperations } from './MessagesViewContext';
import { PrivateText } from '~/components/Chat/Messages/PrivateText';
import { FLAT_THREAD } from '~/components/Chat/Messages/Thread/flag';
import MessageAudio from '~/components/Chat/Messages/MessageAudio';
import { useAssistantsMapContext } from './AssistantsMapContext';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
@ -156,6 +157,7 @@ export const appMessagesHost: MessagesHost = {
useSeenSource: useConversationSeenSource,
renderMessageIcon: (props) => <MessageIcon {...props} />,
useMaximizeChatSpace: () => useRecoilValue(store.maximizeChatSpace),
useFlatThread: () => FLAT_THREAD,
useHideSelectedAuthor,
useAgentsMap: useAgentsMapContext,
renderMessageBody: (props) => <MessageContent {...props} />,

View file

@ -37,7 +37,7 @@ const ROW_HOSTS = [
];
const ROW_HOSTS_MODULE = '~/components/Chat/Messages/hosts';
const ROW_SURFACES = [
'components/Chat/Messages/slots.tsx',
'components/Chat/Messages/load.tsx',
'components/Chat/Presentation.tsx',
'routes/ShareRoute.tsx',
'routes/Search.tsx',
@ -68,6 +68,16 @@ describe('app host registration', () => {
}
});
it('keeps the flat thread flag on the messages host', () => {
const { FLAT_THREAD } = jest.requireActual<
typeof import('~/components/Chat/Messages/Thread/flag')
>('~/components/Chat/Messages/Thread/flag');
const { appMessagesHost } = jest.requireActual<
typeof import('~/Providers/MessagesHostContext')
>('~/Providers/MessagesHostContext');
expect(appMessagesHost.useFlatThread()).toBe(FLAT_THREAD);
});
it('registers the row hosts on every surface that draws message rows', () => {
const hosts = readSource('components/Chat/Messages/hosts.ts');
for (const path of ROW_HOSTS) {

View file

@ -0,0 +1,47 @@
import fs from 'fs';
import path from 'path';
import postcss from 'postcss';
const read = (...segments: string[]) =>
fs.readFileSync(path.resolve(__dirname, ...segments), 'utf8');
/** The library stylesheet loads before the app's, as `main.jsx` imports them. */
const sheets = [read('../../../packages/client/src/theme/parts.css'), read('../style.css')];
const ELEMENT_CLASSES = new Set(['markdown', 'prose', 'message-content']);
/**
* The declaration that wins for `property` on a `.markdown.prose.message-content` element. Every
* rule here is a single class selector at the top level, so specificity ties and source order
* decides: the last matching rule wins.
*/
function winner(property: string): string | undefined {
let value: string | undefined;
for (const css of sheets) {
postcss.parse(css).each((node) => {
if (node.type !== 'rule') {
return;
}
const matches = node.selectors.some(
(selector) => /^\.[\w-]+$/.test(selector) && ELEMENT_CLASSES.has(selector.slice(1)),
);
if (!matches) {
return;
}
node.each((decl) => {
if (decl.type === 'decl' && decl.prop === property) {
value = decl.value.replace(/\s+/g, ' ').trim();
}
});
});
}
return value;
}
describe('message body cascade with the library styles first', () => {
it('keeps the message typography the app has always drawn', () => {
expect(winner('line-height')).toBe('1.6');
expect(winner('font-size')).toBe('var(--markdown-font-size, var(--font-size-base))');
expect(winner('max-width')).toBe('none');
});
});

View file

@ -28,7 +28,7 @@ const protectedModules = [
__dirname,
'../../../../../../../packages/chat/src/components/composer/EscalateNowButton.tsx',
),
join(__dirname, '..', '..', '..', 'Messages', 'Content', 'Parts', 'PendingSteers.tsx'),
join(__dirname, '../../../../../../../packages/chat/src/components/messages/PendingSteers.tsx'),
join(__dirname, '..', '..', '..', '..', '..', 'hooks', 'Input', 'usePaletteEntries.tsx'),
];

View file

@ -4,9 +4,14 @@ import { EModelEndpoint } from 'librechat-data-provider';
import { act, render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { QueuedTurnPortalProvider, useQueuedTurnPortal } from '@librechat/chat/components';
import { MessagePartsHostProvider } from '@librechat/chat/react';
import {
QueuedTurnPortalProvider,
PendingTurn,
useQueuedTurnPortal,
} from '@librechat/chat/components';
import type { MessagePartsHost } from '@librechat/chat/react';
import type { TConversation } from 'librechat-data-provider';
import PendingTurn from '~/components/Chat/Messages/PendingTurn';
import { ChatContext } from '~/Providers';
jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
@ -19,6 +24,16 @@ jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
Container: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));
const partsHost = {
useUser: () => ({ name: 'Danny' }),
useUserTextPreferences: () => ({
enableUserMsgMarkdown: false,
collapseLongUserMessages: false,
usernameDisplay: false,
}),
renderMarkdown: ({ content }: { content: string }) => content,
} as unknown as MessagePartsHost;
const conversationId = 'convo-queued-turn';
const conversation = {
conversationId,
@ -48,10 +63,12 @@ it('registers the revealed user turn action target only while it is visible', ()
{ conversation, latestMessageId, index: 0 } as React.ContextType<typeof ChatContext>
}
>
<QueuedTurnPortalProvider>
<PendingTurn />
<PortalTarget />
</QueuedTurnPortalProvider>
<MessagePartsHostProvider host={partsHost}>
<QueuedTurnPortalProvider>
<PendingTurn />
<PortalTarget />
</QueuedTurnPortalProvider>
</MessagePartsHostProvider>
</ChatContext.Provider>
</JotaiProvider>
</RecoilRoot>

View file

@ -1,63 +0,0 @@
import { useRecoilValue } from 'recoil';
import { PendingTurn as PackagePendingTurn, Container } from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
import type { RefObject } from 'react';
import type { TMessageIcon } from '~/common';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { useAuthContext } from '~/hooks/AuthContext';
import MarkdownLite from './Content/MarkdownLite';
import { useChatContext } from '~/Providers';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import store from '~/store';
/** The app's side of the queued follow-up row: who sent it, their icon, and how the text reads. */
export default function PendingTurn({
scrollableRef,
messages,
maximizeChatSpace = false,
}: {
scrollableRef?: RefObject<HTMLDivElement | null>;
messages?: TMessage[] | null;
maximizeChatSpace?: boolean;
}) {
const localize = useLocalize();
const { user } = useAuthContext();
const { conversation, latestMessageId } = useChatContext();
const usernameDisplay = useRecoilValue(store.UsernameDisplay);
const enableUserMsgMarkdown = useRecoilValue(store.enableUserMsgMarkdown);
const label = usernameDisplay
? (user?.name ?? '') || (user?.username ?? '')
: localize('com_user_message');
const iconData: TMessageIcon = {
endpoint: conversation?.endpoint,
model: conversation?.model,
modelLabel: label,
isCreatedByUser: true,
};
return (
<PackagePendingTurn
scrollableRef={scrollableRef}
messages={messages}
maximizeChatSpace={maximizeChatSpace}
conversationId={conversation?.conversationId ?? ''}
latestMessageId={latestMessageId}
label={label}
icon={<MessageIcon iconData={iconData} />}
renderBody={(message, text) => (
<Container message={message}>
<div
className={cn(
'markdown prose message-content light text-text-primary w-full break-words',
!enableUserMsgMarkdown && 'whitespace-pre-wrap',
)}
>
{enableUserMsgMarkdown ? <MarkdownLite content={text} /> : text}
</div>
</Container>
)}
/>
);
}

View file

@ -1,125 +0,0 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { EModelEndpoint } from 'librechat-data-provider';
import { act, render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TConversation, TMessage } from 'librechat-data-provider';
import type { RevealedQueuedTurn } from '@librechat/chat/react';
import PendingTurn from '~/components/Chat/Messages/PendingTurn';
import { ChatContext } from '~/Providers';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
jest.mock('~/hooks/AuthContext', () => ({
useAuthContext: () => ({ user: { name: 'Danny', username: 'danny' } }),
}));
jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
__esModule: true,
default: () => <span data-testid="message-icon" />,
}));
jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
__esModule: true,
default: ({ content }: { content: string }) => <span data-testid="markdown-lite">{content}</span>,
}));
const CONVO_ID = 'convo-pending';
const RESPONSE_ID = 'response-1';
const conversation = {
conversationId: CONVO_ID,
endpoint: EModelEndpoint.agents,
model: 'gpt-x',
} as TConversation;
const reveal = (overrides: Partial<RevealedQueuedTurn> = {}): RevealedQueuedTurn => ({
clientRequestId: 'client-request-1',
parentMessageId: RESPONSE_ID,
text: 'queued follow-up',
revealedAt: '2026-09-14T00:00:00.000Z',
...overrides,
});
function renderPendingTurn({
revealed,
latestMessageId = RESPONSE_ID,
messages,
}: {
revealed?: RevealedQueuedTurn | null;
latestMessageId?: string | undefined;
messages?: TMessage[];
}) {
const jotaiStore = createStore();
if (revealed != null) {
jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), revealed);
}
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const chatContext = { conversation, latestMessageId, index: 0 } as unknown as React.ContextType<
typeof ChatContext
>;
const rendered = render(
<QueryClientProvider client={queryClient}>
<RecoilRoot>
<JotaiProvider store={jotaiStore}>
<ChatContext.Provider value={chatContext}>
<PendingTurn messages={messages} />
</ChatContext.Provider>
</JotaiProvider>
</RecoilRoot>
</QueryClientProvider>,
);
return { ...rendered, jotaiStore };
}
describe('PendingTurn', () => {
it('draws the revealed queued turn as a user turn after the response it follows', () => {
const { container } = renderPendingTurn({ revealed: reveal() });
const row = screen.getByTestId('pending-turn');
expect(row.querySelector('.message-render')).not.toBeNull();
expect(row.querySelector('.user-turn')).not.toBeNull();
expect(row).toHaveTextContent('queued follow-up');
expect(screen.getByRole('status')).toHaveTextContent('Starting as the next turn');
expect(container.querySelectorAll('button')).toHaveLength(0);
});
it('renders nothing without a reveal', () => {
renderPendingTurn({ revealed: null });
expect(screen.queryByTestId('pending-turn')).toBeNull();
});
it('renders nothing while the thread shows a different tail than the response it follows', () => {
renderPendingTurn({ revealed: reveal(), latestMessageId: 'another-branch' });
expect(screen.queryByTestId('pending-turn')).toBeNull();
});
it('leaves the thread the moment the reveal ends', () => {
const { jotaiStore } = renderPendingTurn({ revealed: reveal() });
expect(screen.getByTestId('pending-turn')).toBeInTheDocument();
act(() => {
jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), null);
});
expect(screen.queryByTestId('pending-turn')).toBeNull();
});
it('hides the drawing once history has a successor while the handoff guard remains', () => {
const { jotaiStore } = renderPendingTurn({
revealed: reveal(),
messages: [
{
messageId: 'real-successor',
parentMessageId: RESPONSE_ID,
isCreatedByUser: true,
} as TMessage,
],
});
expect(screen.queryByTestId('pending-turn')).toBeNull();
expect(jotaiStore.get(revealedQueuedTurnFamily(CONVO_ID))).not.toBeNull();
});
});

View file

@ -4,19 +4,18 @@ import { render, screen } from '@testing-library/react';
import type { ChatScreenMessagesSlots } from '@librechat/chat/components';
const mockLoadScreenMessages = jest.fn();
const mockSlots: ChatScreenMessagesSlots = { flatThread: true };
jest.mock('@librechat/chat/components', () => ({
loadScreenMessages: () => mockLoadScreenMessages(),
}));
jest.mock('../slots', () => ({ messagesSlots: mockSlots }));
jest.mock('../hosts', () => ({}));
type ListProps = { messages: unknown; slots?: ChatScreenMessagesSlots };
function PackageList({ messages, slots }: ListProps) {
return (
<p>
{String(messages)} {slots === mockSlots ? 'app slots' : 'no slots'}
{String(messages)} {slots == null ? 'package defaults' : 'app slots'}
</p>
);
}
@ -34,7 +33,7 @@ describe('message list loader', () => {
mockLoadScreenMessages.mockReset();
});
it('draws the package list with the app slots once both have loaded', async () => {
it('draws the package list once its hosts have loaded', async () => {
mockLoadScreenMessages.mockResolvedValue({ default: PackageList });
const { renderMessages } = loadModule();
@ -45,7 +44,7 @@ describe('message list loader', () => {
);
expect(screen.getByRole('status')).toBeInTheDocument();
expect(await screen.findByText('null app slots')).toBeInTheDocument();
expect(await screen.findByText('null package defaults')).toBeInTheDocument();
});
it('loads the list once for every caller', async () => {

View file

@ -9,19 +9,14 @@ type MessagesModule = { default: ComponentType<ChatScreenMessagesProps> };
let pending: Promise<MessagesModule> | null = null;
/**
* Loads the package message list together with the app's hosts and slots, once. A routed
* Loads the package message list together with the app's hosts, once. A routed
* conversation and the composer start it early so the list is not fetched only after the
* conversation's messages arrive; a failed load is dropped so the next attempt retries.
* The list renders its own pending turn, pending steers and thread mode from those hosts.
*/
export function preloadMessages(): Promise<MessagesModule> {
pending ??= importWithRecovery(() =>
Promise.all([loadScreenMessages(), import('./slots')]).then(([list, app]) => {
const ScreenMessages = list.default;
function AppScreenMessages(props: ChatScreenMessagesProps): ReactElement {
return <ScreenMessages {...props} slots={app.messagesSlots} />;
}
return { default: AppScreenMessages };
}),
Promise.all([loadScreenMessages(), import('./hosts')]).then(([list]) => list),
).catch((error: unknown) => {
pending = null;
throw error;

View file

@ -1,12 +0,0 @@
import type { ChatScreenMessagesSlots } from '@librechat/chat/components';
import PendingSteers from './Content/Parts/PendingSteers';
import PendingTurn from './PendingTurn';
import { FLAT_THREAD } from './Thread';
import './hosts';
/** The app's pieces of the package message list, loaded with it. */
export const messagesSlots: ChatScreenMessagesSlots = {
flatThread: FLAT_THREAD,
renderPendingTurn: (props) => <PendingTurn {...props} />,
renderPendingSteers: (props) => <PendingSteers {...props} />,
};

View file

@ -1,20 +1,12 @@
import React, { createRef, isValidElement } from 'react';
import React from 'react';
import '@testing-library/jest-dom';
import type { ChatScreenMessagesSlots, ChatScreenProps } from '@librechat/chat/components';
import type { ReactElement, ReactNode } from 'react';
import PendingSteers from '../Messages/Content/Parts/PendingSteers';
import PendingTurn from '../Messages/PendingTurn';
import { messagesSlots } from '../Messages/slots';
import type { ChatScreenProps } from '@librechat/chat/components';
import { renderMessages } from '../Messages/load';
import { FLAT_THREAD } from '../Messages/Thread';
import { render } from 'test/layout-test-utils';
import ChatView from '../ChatView';
const mockScreenProps = jest.fn<void, [ChatScreenProps]>();
/** The row hosts import the whole message renderer; the slots under test do not need them. */
jest.mock('../Messages/hosts', () => ({}));
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({ conversationId: 'convo-1' }),
@ -75,50 +67,11 @@ jest.mock('../Footer', () => ({
useLandingFooter: () => true,
}));
/** The slots load with the list, so ChatView hands the screen the loader's renderer. */
const screenSlots = (): ChatScreenMessagesSlots => messagesSlots;
const scrollableRef = createRef<HTMLDivElement>();
/** A slot's output as an element, failing the test when the slot rendered nothing. */
function element(node: ReactNode): ReactElement {
if (!isValidElement(node)) {
throw new Error('The slot did not render an element');
}
return node;
}
describe('ChatView message list slots', () => {
test('hands the screen the on-demand list instead of the slots', () => {
describe('ChatView message list', () => {
test('hands the screen the on-demand list and no message slots', () => {
render(<ChatView />);
const props = mockScreenProps.mock.calls.at(-1)?.[0];
expect(props?.renderMessages).toBe(renderMessages);
expect(props?.messagesSlots).toBeUndefined();
});
test('leaves the list to ChatScreen and fills it with the app thread mode', () => {
expect(screenSlots().flatThread).toBe(FLAT_THREAD);
});
test('leaves the scroll control to the package list', () => {
expect(screenSlots().renderScrollButton).toBeUndefined();
});
test('renders the app pending turn and steers with what the list passes', () => {
const slots = screenSlots();
const turn = { scrollableRef, messages: null, maximizeChatSpace: true };
const steers = { conversationId: 'convo-1', index: 0, fullWidth: false };
const turnElement = element(slots.renderPendingTurn?.(turn));
const steersElement = element(slots.renderPendingSteers?.(steers));
expect(turnElement.type).toBe(PendingTurn);
expect(turnElement.props).toEqual(turn);
expect(steersElement.type).toBe(PendingSteers);
expect(steersElement.props).toEqual(steers);
});
test('leaves the navigation rail to the package list', () => {
expect(screenSlots().renderNav).toBeUndefined();
});
});

View file

@ -1,6 +1,8 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import { SteerHostProvider } from '@librechat/chat/react';
import { MessagesHostTestProvider } from 'test/messagesHost';
import { inertSteerHost } from 'test/inertSteerHost';
import { ChatSurfaceHarness } from 'test/harness';
import ChatView from '../ChatView';
/** The app registers its parts host at boot (App.jsx); the child's list reads it. */
@ -80,9 +82,6 @@ jest.mock('~/data-provider', () => ({
}));
jest.mock('../Input/ConversationStarters', () => () => null);
/** The package list renders the child's messages; the app's pieces of it are not under test. */
jest.mock('../Messages/PendingTurn', () => () => null);
jest.mock('../Messages/Content/Parts/PendingSteers', () => () => null);
jest.mock('../Presentation', () => ({ children }: { children: React.ReactNode }) => (
<>{children}</>
));
@ -130,7 +129,9 @@ describe('ChatView child-thread execution identity', () => {
render(
<ChatSurfaceHarness>
<MessagesHostTestProvider>
<ChatView />
<SteerHostProvider host={inertSteerHost}>
<ChatView />
</SteerHostProvider>
</MessagesHostTestProvider>
</ChatSurfaceHarness>,
);

View file

@ -1832,6 +1832,9 @@ html {
transform-origin: 50% 50%;
}
/* `.message-content` is also published in @librechat/client (theme/parts.css) for other hosts.
* That stylesheet loads before this one, so `.prose` and `.markdown` above would win; keeping the
* rule here at its original place preserves the app's message line height and width. */
.message-content,
.message-editor-text {
font-size: var(--markdown-font-size, var(--font-size-base));

View file

@ -0,0 +1,34 @@
import type { SteerHost } from '@librechat/chat/react';
/** A steer host whose transport does nothing, for specs that mount the package list
* outside the app shell. */
export const inertSteerHost: SteerHost = {
useSteerMessage: () => () => undefined,
useSteerMessageAsync: () => async () => ({
status: 'queued',
steerId: 'steer-1',
position: 0,
conversationId: 'convo-1',
}),
useCancelSteer: () => async () => ({ removed: true }),
useArmSteer: () => async () => ({ armed: true }),
useMarkFilesUsage: () => () => undefined,
useEnqueueQueuedTurn: () => () => undefined,
useCancelQueuedTurn: () => async () => {
throw new Error('not queued');
},
useQueuedTurns: () => undefined,
useQueuedTurnCache: () => ({ read: () => ({}), subscribe: () => () => undefined }),
useFetchStreamStatus: () => async () => ({ active: false }),
useRouteConversationId: () => undefined,
useCodeApprovalInputs: () => ({ conversation: null, reachable: { agents: [], complete: true } }),
useLocalize: () => (key) => key,
useNotify: () => () => undefined,
useFileMap: () => undefined,
useClearFilesToDelete: () => () => undefined,
useSettings: () => ({
duringRunDefaultAction: 'steer',
setDuringRunDefaultAction: () => undefined,
getPaneConversations: () => [],
}),
};

View file

@ -36,6 +36,7 @@ export const testMessagesHost: MessagesHost = {
}),
renderMessageIcon: () => null,
useMaximizeChatSpace: () => false,
useFlatThread: () => true,
useHideSelectedAuthor: () => false,
useAgentsMap: () => undefined,
renderMessageBody: () => null,

View file

@ -25,8 +25,8 @@ function recordOnDemandChunks(page: Page): string[] {
return seen;
}
/** The message list and the app's row hosts and slots, which the welcome screen never draws. */
const MESSAGE_LIST_CHUNK = /\/assets\/(messages|slots|hosts)\.[^/"]+\.js/g;
/** The message list and the app's row hosts, which the welcome screen never draws. */
const MESSAGE_LIST_CHUNK = /\/assets\/(messages|hosts)\.[^/"]+\.js/g;
/** The mock fleet runs without the trace viewer, so the served config and availability turn it on. */
async function enableTraceViewer(page: Page): Promise<void> {
@ -95,7 +95,7 @@ test.describe('surfaces that load on demand', () => {
const seen = new Set<string>();
page.on('request', (request) => {
const match = new URL(request.url()).pathname.match(/\/assets\/(messages|slots)\./);
const match = new URL(request.url()).pathname.match(/\/assets\/(messages|hosts)\./);
if (match) {
seen.add(match[1]);
}
@ -104,7 +104,7 @@ test.describe('surfaces that load on demand', () => {
await expect(messagesView(page).getByText(replyText('lazy-list-link'))).toBeVisible();
await expect(messagesView(page).getByText(replyPrompt('lazy-list-link'))).toBeVisible();
expect([...seen].sort()).toEqual(['messages', 'slots']);
expect([...seen].sort()).toEqual(['hosts', 'messages']);
});
test('the first message of a fresh chat appears in the list @scenario:first-message-draws-message-list', async ({

View file

@ -34,6 +34,7 @@ export function createMessagesHost(overrides: Partial<MessagesHost> = {}): Messa
}),
renderMessageIcon: () => null,
useMaximizeChatSpace: () => false,
useFlatThread: () => true,
useHideSelectedAuthor: () => false,
useAgentsMap: () => undefined,
renderMessageBody: () => null,

View file

@ -0,0 +1,39 @@
import type { SteerHost } from '../react/steer/host';
/** A steer host whose transport does nothing, for specs that mount the pending row. */
export function createSteerHost(overrides: Partial<SteerHost> = {}): SteerHost {
return {
useSteerMessage: () => () => undefined,
useSteerMessageAsync: () => async () => ({
status: 'queued',
steerId: 'steer-1',
position: 0,
conversationId: 'convo-1',
}),
useCancelSteer: () => async () => ({ removed: true }),
useArmSteer: () => async () => ({ armed: true }),
useMarkFilesUsage: () => () => undefined,
useEnqueueQueuedTurn: () => () => undefined,
useCancelQueuedTurn: () => async () => {
throw new Error('not queued');
},
useQueuedTurns: () => undefined,
useQueuedTurnCache: () => ({ read: () => ({}), subscribe: () => () => undefined }),
useFetchStreamStatus: () => async () => ({ active: false }),
useRouteConversationId: () => undefined,
useCodeApprovalInputs: () => ({
conversation: null,
reachable: { agents: [], complete: true },
}),
useLocalize: () => (key) => key,
useNotify: () => () => undefined,
useFileMap: () => undefined,
useClearFilesToDelete: () => () => undefined,
useSettings: () => ({
duringRunDefaultAction: 'steer',
setDuringRunDefaultAction: () => undefined,
getPaneConversations: () => [],
}),
...overrides,
};
}

View file

@ -105,6 +105,8 @@ export { default as MessageRow } from './components/messages/MessageRow';
export { default as WakeupRow } from './components/messages/WakeupRow';
export { default as PendingTurn } from './components/messages/PendingTurn';
export type { PendingTurnProps } from './components/messages/PendingTurn';
export { default as PendingSteers } from './components/messages/PendingSteers';
export type { PendingSteersProps } from './components/messages/PendingSteers';
export { default as MessageTimestamp } from './components/messages/MessageTimestamp';
export { getMessageRowWidthClass } from './components/messages/width';
export { isValidTimestamp, getMessageTimestamp } from './components/messages/time';

View file

@ -12,10 +12,13 @@ import {
import useMessageScrolling from '../../react/messages/useMessageScrolling';
import useConversationSeen from '../../react/messages/useConversationSeen';
import useScrollbarGutter from '../../react/messages/useScrollbarGutter';
import { useOptionalSteerHost } from '../../react/steer/host';
import { useMessagesHost } from '../../react/messages/host';
import { useChatContext } from '../../react/chat/context';
import { useMessagePartsHost } from '../../react/host';
import PendingSteers from './PendingSteers';
import ScrollButton from './ScrollButton';
import PendingTurn from './PendingTurn';
import MessageNav from './MessageNav';
import Thread from './thread/Thread';
@ -65,25 +68,50 @@ const renderDefaultNav: NonNullable<MessagesViewProps['renderNav']> = ({
<MessageNav key={conversationId} conversationId={conversationId} scrollableRef={scrollableRef} />
);
const renderDefaultPendingTurn: NonNullable<MessagesViewProps['renderPendingTurn']> = ({
scrollableRef,
messages,
maximizeChatSpace,
}) => (
<PendingTurn
scrollableRef={scrollableRef}
messages={messages}
maximizeChatSpace={maximizeChatSpace}
/>
);
const renderDefaultPendingSteers: NonNullable<MessagesViewProps['renderPendingSteers']> = (
props,
) => <PendingSteers {...props} />;
/**
* 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.
* window, the pending tail, and the end marker the scroll and seen reporting watch. The
* pending turn, pending steers, scroll control and navigation rail are the package's own
* unless a caller passes a slot. The pending rows stay unmounted when no steer host is
* present, so a shared page does not call the steer hooks.
*/
export default function MessagesView({
messagesTree,
messages,
showScrollButton,
maximizeChatSpace,
flatThread = true,
flatThread,
renderThread = renderDefaultThread,
renderPendingTurn,
renderPendingSteers,
renderPendingTurn: renderPendingTurnSlot,
renderPendingSteers: renderPendingSteersSlot,
renderScrollButton = renderDefaultScrollButton,
renderNav = renderDefaultNav,
}: MessagesViewProps): ReactElement {
const localize = useLocalize();
const host = useMessagesHost();
const steerHost = useOptionalSteerHost();
const renderPendingTurn =
renderPendingTurnSlot ?? (steerHost == null ? undefined : renderDefaultPendingTurn);
const renderPendingSteers =
renderPendingSteersSlot ?? (steerHost == null ? undefined : renderDefaultPendingSteers);
const hostFlatThread = host.useFlatThread();
const flat = flatThread ?? hostFlatThread;
const fontSize = useMessagePartsHost().useFontSize();
const screenshotTargetRef = host.useScreenshotTarget();
const [currentEditId, setCurrentEditId] = useState<string | number | null>(-1);
@ -227,7 +255,7 @@ export default function MessagesView({
messagesTree,
messages,
conversationId: treeConversationId,
flat: flatThread,
flat,
currentEditId,
setCurrentEditId,
})}

View file

@ -1,45 +1,67 @@
import { memo, useMemo, useRef, useState } from 'react';
import { hasLiveRunPause } from '@librechat/chat';
import { useAtomValue } from 'jotai';
import { Clock, TextQuote, X } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { Button, TooltipAnchor } from '@librechat/client';
import { QueryKeys, type TMessage } from 'librechat-data-provider';
import { SteerPart, EscalateNowButton, getMessageRowWidthClass } from '@librechat/chat/components';
import {
useSteerCancel,
import { Button, TooltipAnchor, useLocalize } from '@librechat/client';
import type { ReactElement, NamedExoticComponent } from 'react';
import type { TMessage } from 'librechat-data-provider';
import type { SteerReceiptState } from '../composer/steering/Receipt';
import useSteerCancel, {
useSteerMoveToQueue,
useSteerRehome,
useSteerEscalate,
useSteerRecovery,
} from '@librechat/chat/react';
import type { SteerReceiptState } from '@librechat/chat/components';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { cn, isLegacyDeliveryUncertain } from '~/utils';
import { useCachedMessages } from '~/data-provider';
import { useLatestMessage } from '~/hooks/Messages';
import { useLocalize } from '~/hooks';
} from '../../react/steering/useSteerCancel';
import { hasLiveRunPause, isLegacyDeliveryUncertain } from '../../core';
import useSteerRecovery from '../../react/steering/useSteerRecovery';
import useSteerEscalate from '../../react/steering/useSteerEscalate';
import { pendingSteersByConvoId } from '../../react/steer/atoms';
import EscalateNowButton from '../composer/EscalateNowButton';
import { useMessagesHost } from '../../react/messages/host';
import { useMessagePartsHost } from '../../react/host';
import { useBranchTail } from '../../react/latest';
import { getMessageRowWidthClass } from './width';
import SteerPart from '../parts/SteerPart';
/**
* Steers that have not been confirmed by the server yet, rendered at the tail
* of the streaming reply (the place the words will land) instead of in a
* floating overlay over the composer. Confirmation swaps them for the real
* `ContentTypes.STEER` part (`useResumableSSE` removes the pending entry), so
* the row's whole job is to hold the position and admit it is provisional.
*/
interface PendingSteersProps {
/** Steers the server has not confirmed, at the tail of the reply they will join.
* Confirmation swaps them for the real steer part, so the row holds the place
* and says it is provisional. */
export interface PendingSteersProps {
conversationId: string;
/** The pane rendering this tree: its sibling selection picks the branch the
* pause check reads, which another pane's selection would get wrong. */
/** The pane rendering this tree. Its sibling selection is the branch the pause
* check reads; another pane's selection would get that wrong. */
index?: number;
fullWidth?: boolean;
}
function PendingSteers({ conversationId, index = 0, fullWidth = false }: PendingSteersProps) {
/** Whether escalation must stay off. A multi-message cache follows the branch on
* screen once this pane owns the conversation, and any branch until then. A
* one-message cache is that branch. */
function resolvePaused(
cachedMessages: TMessage[],
paneConversationId: string | null,
conversationId: string,
latestMessage: TMessage | null,
fallbackPaused: boolean | undefined,
): boolean {
if (cachedMessages.length > 1) {
if (paneConversationId === conversationId && latestMessage != null) {
return hasLiveRunPause(latestMessage);
}
return cachedMessages.some((message) => hasLiveRunPause(message));
}
if (fallbackPaused != null) {
return fallbackPaused;
}
return cachedMessages.length === 1 && hasLiveRunPause(cachedMessages[0]);
}
function PendingSteers({
conversationId,
index = 0,
fullWidth = false,
}: PendingSteersProps): ReactElement | null {
const localize = useLocalize();
const { useToast, usePendingSteers, useSteerEscalating, usePaneConversationId } =
useMessagePartsHost();
const { useToast, useSteerEscalating, usePaneConversationId } = useMessagePartsHost();
const showToast = useToast();
const steers = usePendingSteers(conversationId);
const steers = useAtomValue(pendingSteersByConvoId(conversationId));
const { retry, sendAsNew } = useSteerRecovery(conversationId);
const cancelSteer = useSteerCancel(conversationId);
const escalate = useSteerEscalate(conversationId);
@ -47,33 +69,14 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending
const rehomeSteer = useSteerRehome(conversationId);
const [movingId, setMovingId] = useState<string | null>(null);
const escalating = useSteerEscalating(conversationId);
/* Resolve the cache to the branch the user is viewing before applying the
shared pause predicate. The cache contains every sibling branch, while
`useLatestMessage` follows the same selection state as the message view. */
const queryClient = useQueryClient();
const cachedMessages =
queryClient.getQueryData<TMessage[]>([QueryKeys.messages, conversationId]) ?? [];
const latestMessage = useLatestMessage(index, conversationId);
const paneConversationId = usePaneConversationId(index);
const { data: fallbackPaused } = useCachedMessages(conversationId, hasLiveRunPause);
/* A one-message cache is necessarily the active branch. Until the
conversation atom reaches useLatestMessage, retain the query's established
single-branch result so a live question cannot re-enable escalation. The
branch tail is keyed by the pane's conversation, which can still name the
previous chat while this one renders from cache; until the pane owns this
conversation, a pause on any branch keeps escalation off. */
const resolvePaused = (): boolean => {
if (cachedMessages.length > 1) {
if (paneConversationId === conversationId && latestMessage != null) {
return hasLiveRunPause(latestMessage);
}
return cachedMessages.some((message) => hasLiveRunPause(message));
}
if (fallbackPaused != null) {
return fallbackPaused;
}
return cachedMessages.length === 1 && hasLiveRunPause(cachedMessages[0]);
};
const cached = useMessagesHost().useConversationMessages(conversationId, true);
const latestMessage = useBranchTail(
paneConversationId,
paneConversationId ? conversationId : null,
);
const cachedMessages = cached ?? [];
const fallbackPaused = cached == null ? undefined : hasLiveRunPause(cached);
/** Arming removes the control that was activated, so the row's Cancel button
* (which survives the `preempt` flip) is where keyboard focus goes next. */
const cancelButtonRefs = useRef(new Map<string, HTMLButtonElement | null>());
@ -85,7 +88,13 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending
if (steers.length === 0) {
return null;
}
const paused = resolvePaused();
const paused = resolvePaused(
cachedMessages,
paneConversationId,
conversationId,
latestMessage,
fallbackPaused,
);
const queueSteer = async (steer: (typeof steers)[number]) => {
if (movingId != null) {
@ -134,7 +143,7 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending
<div
role="list"
aria-label={localize('com_ui_steer_in_flight')}
className={cn('mx-auto min-w-0 px-4', getMessageRowWidthClass({ fullWidth }))}
className={`mx-auto min-w-0 px-4 ${getMessageRowWidthClass({ fullWidth })}`}
data-testid="pending-steers"
>
{steers.map((steer) => {
@ -266,4 +275,6 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending
);
}
export default memo(PendingSteers);
const MemoizedPendingSteers: NamedExoticComponent<PendingSteersProps> = memo(PendingSteers);
export default MemoizedPendingSteers;

View file

@ -1,13 +1,17 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { useLocalize } from '@librechat/client';
import type { ReactElement, ReactNode, RefObject } from 'react';
import type { TMessage } from 'librechat-data-provider';
import type { ReactElement, RefObject } from 'react';
import { hasRevealSuccessor, buildRevealedMessage } from '../../react/steering/useQueuedTurnReveal';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from './labels';
import { useQueuedTurnPortal } from '../composer/steering/QueuedTurnPortal';
import { revealedQueuedTurnFamily } from '../../react/steer/rows';
import { useMessagesHost } from '../../react/messages/host';
import { useChatContext } from '../../react/chat/context';
import { useMessagePartsHost } from '../../react/host';
import { messageFooterClasses } from './styles';
import Container from '../parts/Container';
import MessageRow from './MessageRow';
import SubRow from './SubRow';
@ -19,34 +23,28 @@ export type PendingTurnProps = {
scrollableRef?: RefObject<HTMLDivElement | null>;
messages?: TMessage[] | null;
maximizeChatSpace?: boolean;
/** The routed conversation: its reveal is the turn drawn. */
conversationId: string;
/** The thread's current tail; the turn is drawn only after the response it follows. */
latestMessageId?: string;
/** Who the turn is attributed to. */
label: string;
/** The author's icon. */
icon: ReactNode;
/** The turn's text, drawn inside the row (the host decides markdown and wrappers). */
renderBody: (message: TMessage, text: string) => ReactNode;
};
/**
* The queued follow-up the server is about to admit, drawn as the user turn after the completed
* response it follows. It is not persisted: its actions come from the composer that owns the
* queue, and it leaves as soon as the thread gains a turn after that response.
*
* The pane context names the conversation, including while a warm navigation still shows the
* previous chat there. The label, icon and text come from the hosts.
*/
export default function PendingTurn({
scrollableRef,
messages,
maximizeChatSpace = false,
conversationId,
latestMessageId,
label,
icon,
renderBody,
}: PendingTurnProps): ReactElement | null {
const localize = useLocalize();
const { conversation, latestMessageId } = useChatContext();
const conversationId = conversation?.conversationId ?? '';
const { useUser, useUserTextPreferences, renderMarkdown } = useMessagePartsHost();
const renderMessageIcon = useMessagesHost().renderMessageIcon;
const user = useUser();
const { usernameDisplay, enableUserMsgMarkdown } = useUserTextPreferences();
const reveal = useAtomValue(revealedQueuedTurnFamily(conversationId));
const setPortalTarget = useQueuedTurnPortal()?.setTarget;
const clientRequestId = reveal?.clientRequestId;
@ -93,10 +91,28 @@ export default function PendingTurn({
row.scrollIntoView({ block: 'end', behavior: reduceMotion ? 'auto' : 'smooth' });
}, [shown, scrollableRef]);
if (!shown) {
if (!shown || message == null || reveal == null) {
return null;
}
const label = usernameDisplay
? (user?.name ?? '') || (user?.username ?? '')
: localize('com_user_message');
const icon = renderMessageIcon({
iconData: {
endpoint: conversation?.endpoint,
model: conversation?.model ?? undefined,
modelLabel: label,
isCreatedByUser: true,
},
});
const bodyClass = [
'markdown prose message-content light text-text-primary w-full break-words',
enableUserMsgMarkdown ? '' : 'whitespace-pre-wrap',
]
.filter((part) => part !== '')
.join(' ');
return (
<div
ref={rowRef}
@ -126,7 +142,17 @@ export default function PendingTurn({
</SubRow>
}
>
{renderBody(message, reveal.text)}
<Container message={message}>
<div className={bodyClass}>
{enableUserMsgMarkdown
? renderMarkdown({
content: reveal.text,
variant: 'lite',
isLatestMessage: false,
})
: reveal.text}
</div>
</Container>
</MessageRow>
</div>
</div>

View file

@ -1,7 +1,7 @@
/**
* @jest-environment jsdom
*/
import { useRef } from 'react';
import { useRef, useState } from 'react';
import { QueryKeys } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
@ -9,10 +9,12 @@ import type { TMessage } from 'librechat-data-provider';
import type { ConversationSeenSource, MessagesHost } from '../../../react/messages/host';
import type { MessagesScrollButtonProps, MessagesViewProps } from '../MessagesView';
import type { ChatContract } from '../../../react/chat/contract';
import type { MessagePartsHost } from '../../../react/host';
import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { MessagesHostProvider } from '../../../react/messages/host';
import { createSteerHost } from '../../../__fixtures__/steerHost';
import { MessagePartsHostProvider } from '../../../react/host';
import { SteerHostProvider } from '../../../react/steer/host';
import { ChatContext } from '../../../react/chat/context';
import { initEnglish } from '../../../__fixtures__/i18n';
import MessagesView from '../MessagesView';
@ -21,7 +23,7 @@ beforeAll(initEnglish);
const tree = [{ messageId: 'reply-1', conversationId: 'convo-1' }] as TMessage[];
const partsHost = { useFontSize: () => 'text-base' } as unknown as MessagePartsHost;
const partsHost = createMessagePartsHost({ useFontSize: () => 'text-base' });
const RESPONDED_AT = '2026-11-03T10:00:00.000Z';
@ -82,23 +84,25 @@ function renderView(props: Partial<MessagesViewProps>, host: MessagesHost, chat
queryClient.setQueryData([QueryKeys.messages, 'convo-1'], tree);
const view = (next: Partial<MessagesViewProps>) => (
<QueryClientProvider client={queryClient}>
<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>
<SteerHostProvider host={createSteerHost()}>
<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>
</SteerHostProvider>
</QueryClientProvider>
);
const result = render(view({}));
@ -125,6 +129,26 @@ describe('MessagesView', () => {
expect(renderThread).not.toHaveBeenCalled();
});
it('takes the thread mode from the host unless the caller sets it', () => {
const renderThread = jest.fn((_props: { flat?: boolean }) => null);
const { rerenderView } = renderView(
{ renderThread },
createHost({ useFlatThread: () => false }).host,
);
expect(renderThread).toHaveBeenLastCalledWith(expect.objectContaining({ flat: false }));
rerenderView({ flatThread: true });
expect(renderThread).toHaveBeenLastCalledWith(expect.objectContaining({ flat: true }));
});
it('keeps the host hook order when the thread mode prop comes and goes', () => {
const host = createHost({ useFlatThread: () => useState(false)[0] }).host;
const { rerenderView } = renderView({ flatThread: true }, host);
expect(() => rerenderView({ flatThread: undefined })).not.toThrow();
});
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[];

View file

@ -1,57 +1,59 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { MemoryRouter } from 'react-router-dom';
/**
* @jest-environment jsdom
*/
import { useEffect } from 'react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { pendingSteersByConvoId } from '@librechat/chat/react';
import { hasLiveRunPause, applyPendingAction } from '@librechat/chat';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider';
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';
import type { Agents, TConversation, TMessage } from 'librechat-data-provider';
import type { PendingSteer } from '@librechat/chat';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
import { setAppPartRenderers } from '../slots';
import type { Agents, TMessage } from 'librechat-data-provider';
import type {
PendingSteer,
ChatSteerResult,
ChatArmSteerResult,
ChatCancelSteerResult,
} from '../../../core';
import type { RestoreToComposer } from '../../../react/steer/restore';
import {
pendingSteersByConvoId,
activeGenerationCreatedAtByConvoId,
activeGenerationProtocolVersionByConvoId,
} from '../../../react/steer/atoms';
import { ComposerRestoreProvider, useComposerRestoreHost } from '../../../react/steer/restore';
import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { queuedMessagesByConvoId } from '../../../react/steer/queue';
import { siblingIdxFamily, siblingKey } from '../../../react/thread';
import { hasLiveRunPause, applyPendingAction } from '../../../core';
import { MessagesHostProvider } from '../../../react/messages/host';
import { createSteerHost } from '../../../__fixtures__/steerHost';
import { MessagePartsHostProvider } from '../../../react/host';
import { SteerHostProvider } from '../../../react/steer/host';
import PendingSteers from '../PendingSteers';
import store from '~/store';
const mockRetry = jest.fn();
const mockSendAsNew = jest.fn();
const mockEscalate = jest.fn();
const mockMoveToQueue = jest.fn();
const mockRehome = jest.fn(() => 'composer' as const);
const mockShowToast = jest.fn();
const cancelSteer = jest.fn(async (): Promise<ChatCancelSteerResult> => ({ removed: true }));
const armSteer = jest.fn(async (): Promise<ChatArmSteerResult> => ({ armed: true }));
const steerMessage = jest.fn(
(): Promise<ChatSteerResult> => new Promise<ChatSteerResult>(() => undefined),
);
const showToast = jest.fn();
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
useToastContext: () => ({ showToast: mockShowToast }),
}));
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
jest.mock('@librechat/chat/react', () => ({
...jest.requireActual('@librechat/chat/react'),
useSteerEscalate: () => mockEscalate,
useSteerCancel: () => jest.fn(),
useSteerMoveToQueue: () => mockMoveToQueue,
useSteerRehome: () => mockRehome,
useSteerRecovery: () => ({ retry: mockRetry, sendAsNew: mockSendAsNew }),
}));
jest.mock('~/Providers', () => ({
useShareContext: () => ({}),
useFileMapContext: () => ({}),
}));
/** The parts barrel registers the app's renderers; this spec loads PendingSteers alone. */
setAppPartRenderers({
renderMarkdown: ({ content }) => <span>{content}</span>,
renderAgentIcon: () => null,
renderImage: () => null,
renderFilePreview: () => null,
});
function PublishRestore({ restore }: { restore?: RestoreToComposer }) {
const host = useComposerRestoreHost();
useEffect(() => {
if (restore == null) {
return;
}
host.publish(restore);
return () => host.publish(null);
}, [host, restore]);
return null;
}
const CONVO_ID = 'convo-1';
@ -72,9 +74,8 @@ function renderPending(
/** Pane 0 still names the previous chat while this one renders from cache. */
stalePaneConversationId?: string,
fullWidth = false,
restore?: RestoreToComposer,
) {
/* The escalation control resolves the cache through the branch-aware
latest-message hook, using the same providers the chat view supplies. */
const queryClient = new QueryClient({
defaultOptions: {
queries: { retry: false, staleTime: Infinity },
@ -84,6 +85,8 @@ function renderPending(
queryClient.setQueryData([QueryKeys.messages, CONVO_ID], messages ?? []);
const jotaiStore = createStore();
jotaiStore.set(pendingSteersByConvoId(CONVO_ID), steers);
jotaiStore.set(activeGenerationCreatedAtByConvoId(CONVO_ID), 1);
jotaiStore.set(activeGenerationProtocolVersionByConvoId(CONVO_ID), 1);
if (activeSiblingIndex != null) {
jotaiStore.set(
siblingIdxFamily(
@ -94,34 +97,54 @@ function renderPending(
activeSiblingIndex,
);
}
return render(
<MemoryRouter>
<QueryClientProvider client={queryClient}>
<JotaiProvider store={jotaiStore}>
<RecoilRoot
initializeState={({ set }) => {
set(store.conversationByIndex(0), {
conversationId: pane?.otherConversationId ?? stalePaneConversationId ?? CONVO_ID,
} as TConversation);
if (pane != null) {
set(store.conversationByIndex(pane.index), {
conversationId: CONVO_ID,
} as TConversation);
}
}}
>
<PendingSteers conversationId={CONVO_ID} index={pane?.index} fullWidth={fullWidth} />
</RecoilRoot>
</JotaiProvider>
</QueryClientProvider>
</MemoryRouter>,
const paneIds: Record<number, string | null> = {
0: pane?.otherConversationId ?? stalePaneConversationId ?? CONVO_ID,
};
if (pane != null) {
paneIds[pane.index] = CONVO_ID;
}
const partsHost = createMessagePartsHost({
useToast: () => showToast,
usePaneConversationId: (paneIndex) => paneIds[paneIndex] ?? null,
renderMarkdown: ({ content }) => <span>{content}</span>,
});
const messagesHost = createMessagesHost({
useConversationMessages: (id) =>
queryClient.getQueryData<TMessage[]>([QueryKeys.messages, id ?? '']),
});
const steerHost = createSteerHost({
useCancelSteer: () => cancelSteer,
useArmSteer: () => armSteer,
useSteerMessageAsync: () => steerMessage,
});
const view = render(
<QueryClientProvider client={queryClient}>
<JotaiProvider store={jotaiStore}>
<SteerHostProvider host={steerHost}>
<MessagesHostProvider host={messagesHost}>
<MessagePartsHostProvider host={partsHost}>
<ComposerRestoreProvider>
<PublishRestore restore={restore} />
<PendingSteers
conversationId={CONVO_ID}
index={pane?.index}
fullWidth={fullWidth}
/>
</ComposerRestoreProvider>
</MessagePartsHostProvider>
</MessagesHostProvider>
</SteerHostProvider>
</JotaiProvider>
</QueryClientProvider>,
);
return { ...view, jotaiStore };
}
describe('PendingSteers', () => {
beforeEach(() => {
jest.clearAllMocks();
mockMoveToQueue.mockResolvedValue('reclaimed');
cancelSteer.mockResolvedValue({ removed: true });
armSteer.mockResolvedValue({ armed: true });
});
it('renders nothing with no pending steers', () => {
@ -255,21 +278,29 @@ describe('PendingSteers', () => {
it('reclaims an acknowledged steer before moving it to the queue', async () => {
const steer = pending({ status: 'pending', steerId: 's-ack' });
renderPending([steer]);
const { jotaiStore } = renderPending([steer]);
fireEvent.click(screen.getByRole('button', { name: 'com_ui_convert_to_queue' }));
await waitFor(() => expect(mockMoveToQueue).toHaveBeenCalledWith(steer));
await waitFor(() =>
expect(cancelSteer).toHaveBeenCalledWith(
expect.objectContaining({ conversationId: CONVO_ID, steerId: steer.steerId }),
),
);
await waitFor(() => expect(screen.queryByRole('listitem')).not.toBeInTheDocument());
expect(jotaiStore.get(queuedMessagesByConvoId(CONVO_ID)).map((item) => item.text)).toContain(
steer.text,
);
});
it('reports when a steer reached the agent before it could be reclaimed', async () => {
mockMoveToQueue.mockResolvedValue('applied');
cancelSteer.mockResolvedValue({ removed: false });
renderPending([pending({ status: 'pending' })]);
fireEvent.click(screen.getByRole('button', { name: 'com_ui_convert_to_queue' }));
await waitFor(() =>
expect(mockShowToast).toHaveBeenCalledWith({
expect(showToast).toHaveBeenCalledWith({
message: 'com_ui_steer_already_applied',
status: 'info',
}),
@ -279,26 +310,50 @@ describe('PendingSteers', () => {
it('retries the failed steer by id', () => {
renderPending([pending({ status: 'failed', steerId: 's-failed' })]);
fireEvent.click(screen.getByText('com_ui_retry'));
expect(mockRetry).toHaveBeenCalledWith('s-failed');
expect(mockSendAsNew).not.toHaveBeenCalled();
expect(steerMessage).toHaveBeenCalledWith(
expect.objectContaining({
conversationId: CONVO_ID,
text: 'change of plan',
clientSteerId: 's-failed',
}),
);
});
it('sends the failed steer as new by id', () => {
renderPending([pending({ status: 'failed', steerId: 's-failed' })]);
const { jotaiStore } = renderPending([pending({ status: 'failed', steerId: 's-failed' })]);
fireEvent.click(screen.getByText('com_ui_send_as_new'));
expect(mockSendAsNew).toHaveBeenCalledWith('s-failed');
expect(mockRetry).not.toHaveBeenCalled();
expect(steerMessage).not.toHaveBeenCalled();
expect(screen.queryByText('com_ui_retry')).not.toBeInTheDocument();
expect(jotaiStore.get(queuedMessagesByConvoId(CONVO_ID)).map((item) => item.text)).toContain(
'change of plan',
);
});
it('returns a definitively failed steer whole so it can be corrected', () => {
const restore = jest.fn(() => true);
const steer = pending({ status: 'failed', steerId: 's-failed', quotes: ['excerpt'] });
renderPending([steer]);
renderPending([steer], undefined, undefined, undefined, undefined, false, restore);
fireEvent.click(screen.getByText('com_ui_edit'));
/* Queued as a fallback it must wait for an explicit send: the server
refused this payload, so the run-end drain must not send it anyway. */
expect(mockRehome).toHaveBeenCalledWith(steer, { rejectedByServer: true });
expect(mockSendAsNew).not.toHaveBeenCalled();
expect(mockRetry).not.toHaveBeenCalled();
expect(restore).toHaveBeenCalledWith(
steer.text,
undefined,
expect.objectContaining({ quotes: ['excerpt'] }),
CONVO_ID,
);
expect(showToast).not.toHaveBeenCalled();
expect(steerMessage).not.toHaveBeenCalled();
});
it('queues a rejected steer for an explicit send when the composer will not take it', () => {
const { jotaiStore } = renderPending([
pending({ status: 'failed', steerId: 's-failed', quotes: ['excerpt'] }),
]);
fireEvent.click(screen.getByText('com_ui_edit'));
expect(showToast).toHaveBeenCalledWith({
message: 'com_ui_steer_moved_to_queue',
status: 'info',
});
expect(jotaiStore.get(queuedMessagesByConvoId(CONVO_ID))[0]?.needsExplicitSend).toBe(true);
});
/* An uncertain delivery may still be held by the server, so every action that
@ -317,30 +372,27 @@ describe('PendingSteers', () => {
expect(screen.getByTestId('steer-escalate-now')).toBeEnabled();
});
it('arms the steer by id, carrying its own generation', () => {
it('arms the steer by id, carrying its own generation', async () => {
renderPending([pending({ status: 'pending', steerId: 's-ack', generationCreatedAt: 4141 })]);
fireEvent.click(screen.getByTestId('steer-escalate-now'));
expect(mockEscalate).toHaveBeenCalledWith(
{
await waitFor(() =>
expect(armSteer).toHaveBeenCalledWith({
conversationId: CONVO_ID,
steerId: 's-ack',
generationCreatedAt: 4141,
},
expect.any(Function),
}),
);
});
/* Arming removes the control that was just activated, so a keyboard user
would be dropped on the document body in the middle of the thread. */
it('moves focus to the row`s cancel action once the arm is confirmed', () => {
it('moves focus to the row`s cancel action once the arm is confirmed', async () => {
renderPending([pending({ status: 'pending', steerId: 's-ack' })]);
fireEvent.click(screen.getByTestId('steer-escalate-now'));
const onArmed = mockEscalate.mock.calls[0][1] as () => void;
act(() => {
onArmed();
});
expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toHaveFocus();
await waitFor(() =>
expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toHaveFocus(),
);
});
it.each([

View file

@ -1,11 +1,20 @@
/**
* @jest-environment jsdom
*/
import { EModelEndpoint } from 'librechat-data-provider';
import { act, render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import type { TMessage } from 'librechat-data-provider';
import type { TConversation, TMessage } from 'librechat-data-provider';
import type { ReactNode } from 'react';
import type { MessagesHost } from '../../../react/messages/host';
import type { ChatContract } from '../../../react/chat/contract';
import type { RevealedQueuedTurn } from '../../../react';
import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { revealedQueuedTurnFamily } from '../../../react/steer/rows';
import { MessagesHostProvider } from '../../../react/messages/host';
import { MessagePartsHostProvider } from '../../../react/host';
import { ChatContext } from '../../../react/chat/context';
import PendingTurn from '../PendingTurn';
jest.mock('@librechat/client', () => ({
@ -16,6 +25,12 @@ jest.mock('@librechat/client', () => ({
const CONVO_ID = 'convo-pending';
const RESPONSE_ID = 'response-1';
const conversation = {
conversationId: CONVO_ID,
endpoint: EModelEndpoint.agents,
model: 'gpt-x',
} as TConversation;
const reveal = (overrides: Partial<RevealedQueuedTurn> = {}): RevealedQueuedTurn => ({
clientRequestId: 'client-request-1',
parentMessageId: RESPONSE_ID,
@ -28,28 +43,57 @@ function renderPendingTurn({
revealed,
latestMessageId = RESPONSE_ID,
messages,
usernameDisplay = false,
userName = 'Danny',
enableUserMsgMarkdown = false,
renderMarkdown = ({ content }: { content: string }) => (
<span data-testid="markdown">{content}</span>
),
renderMessageIcon = jest.fn(() => <span data-testid="message-icon" />),
}: {
revealed?: RevealedQueuedTurn | null;
latestMessageId?: string;
messages?: TMessage[];
}) {
usernameDisplay?: boolean;
userName?: string;
enableUserMsgMarkdown?: boolean;
renderMarkdown?: (props: { content: string }) => ReactNode;
renderMessageIcon?: MessagesHost['renderMessageIcon'];
} = {}) {
const store = createStore();
if (revealed != null) {
store.set(revealedQueuedTurnFamily(CONVO_ID), revealed);
}
const partsHost = createMessagePartsHost({
useUser: () => ({ name: userName, username: 'danny' }),
useUserTextPreferences: () => ({
enableUserMsgMarkdown,
collapseLongUserMessages: false,
usernameDisplay,
}),
renderMarkdown,
});
const messagesHost = createMessagesHost({ renderMessageIcon });
const rendered = render(
<JotaiProvider store={store}>
<PendingTurn
messages={messages}
conversationId={CONVO_ID}
latestMessageId={latestMessageId}
label="Danny"
icon={<span data-testid="message-icon" />}
renderBody={(_message, text) => <span data-testid="body">{text}</span>}
/>
<ChatContext.Provider
value={
{
conversation,
latestMessageId,
index: 0,
} as ChatContract
}
>
<MessagesHostProvider host={messagesHost}>
<MessagePartsHostProvider host={partsHost}>
<PendingTurn messages={messages} />
</MessagePartsHostProvider>
</MessagesHostProvider>
</ChatContext.Provider>
</JotaiProvider>,
);
return { ...rendered, store };
return { ...rendered, store, renderMessageIcon };
}
describe('PendingTurn', () => {
@ -59,11 +103,56 @@ describe('PendingTurn', () => {
const row = screen.getByTestId('pending-turn');
expect(row.querySelector('.message-render')).not.toBeNull();
expect(row.querySelector('.user-turn')).not.toBeNull();
expect(screen.getByTestId('body')).toHaveTextContent('queued follow-up');
expect(row).toHaveTextContent('queued follow-up');
expect(screen.getByRole('status')).toHaveTextContent('com_ui_queued_turn_starting');
expect(container.querySelectorAll('button')).toHaveLength(0);
});
it('labels the turn with the signed-in name when the viewer asks for it', () => {
const { renderMessageIcon } = renderPendingTurn({
revealed: reveal(),
usernameDisplay: true,
});
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('Danny');
expect(renderMessageIcon).toHaveBeenCalledWith({
iconData: {
endpoint: EModelEndpoint.agents,
model: 'gpt-x',
modelLabel: 'Danny',
isCreatedByUser: true,
},
});
});
it('uses the generic user label when names are hidden', () => {
renderPendingTurn({ revealed: reveal(), usernameDisplay: false });
expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('com_user_message');
});
it('renders plain text unless the viewer wants user markdown', () => {
const { container, renderMessageIcon: plainIcon } = renderPendingTurn({
revealed: reveal(),
});
expect(container.querySelector('.whitespace-pre-wrap')).not.toBeNull();
expect(screen.queryByTestId('markdown')).toBeNull();
expect(plainIcon).toHaveBeenCalled();
const markdown = jest.fn(({ content }: { content: string }) => (
<span data-testid="markdown">{content}</span>
));
renderPendingTurn({
revealed: reveal(),
enableUserMsgMarkdown: true,
renderMarkdown: markdown,
});
expect(screen.getByTestId('markdown')).toHaveTextContent('queued follow-up');
expect(markdown).toHaveBeenCalledWith(
expect.objectContaining({ content: 'queued follow-up', variant: 'lite' }),
);
});
it('renders nothing without a reveal', () => {
renderPendingTurn({ revealed: null });
expect(screen.queryByTestId('pending-turn')).toBeNull();

View file

@ -0,0 +1,123 @@
/**
* @jest-environment jsdom
*/
import { render, screen } from '@testing-library/react';
import { Provider as JotaiProvider, createStore } from 'jotai';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { TMessage } from 'librechat-data-provider';
import type { RevealedQueuedTurn } from '../../../react/steer/rows';
import type { ChatContract } from '../../../react/chat/contract';
import type { PendingSteer } from '../../../core';
import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { revealedQueuedTurnFamily } from '../../../react/steer/rows';
import { pendingSteersByConvoId } from '../../../react/steer/atoms';
import { MessagesHostProvider } from '../../../react/messages/host';
import { createSteerHost } from '../../../__fixtures__/steerHost';
import { MessagePartsHostProvider } from '../../../react/host';
import { SteerHostProvider } from '../../../react/steer/host';
import { ChatContext } from '../../../react/chat/context';
import { initEnglish } from '../../../__fixtures__/i18n';
import MessagesView from '../MessagesView';
beforeAll(() => {
Element.prototype.scrollIntoView = () => undefined;
return initEnglish();
});
const CONVO_ID = 'shared-convo';
const RESPONSE_ID = 'reply-1';
const messages = [
{ messageId: RESPONSE_ID, conversationId: CONVO_ID, text: 'shared reply' },
] as TMessage[];
const reveal: RevealedQueuedTurn = {
clientRequestId: 'queued-request',
parentMessageId: RESPONSE_ID,
text: 'queued follow-up',
revealedAt: '2026-09-14T00:00:00.000Z',
};
const steer: PendingSteer = {
steerId: 's1',
text: 'change of plan',
status: 'sending',
createdAt: 1,
};
const chat: ChatContract = Object.assign(
{
index: 0,
isSubmitting: false,
latestMessageId: RESPONSE_ID,
latestMessageDepth: 0,
messagesKey: CONVO_ID,
} as ChatContract,
{
abortScroll: false,
setAbortScroll: () => undefined,
conversation: {
conversationId: CONVO_ID,
endpoint: null,
title: null,
createdAt: '2026-09-14T00:00:00.000Z',
updatedAt: '2026-09-14T00:00:00.000Z',
},
},
);
function renderList(withSteerHost: boolean) {
const store = createStore();
store.set(pendingSteersByConvoId(CONVO_ID), [steer]);
store.set(revealedQueuedTurnFamily(CONVO_ID), reveal);
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
const list = (
<QueryClientProvider client={queryClient}>
<JotaiProvider store={store}>
<ChatContext.Provider value={chat}>
<MessagesHostProvider host={createMessagesHost()}>
<MessagePartsHostProvider host={createMessagePartsHost()}>
<MessagesView
messagesTree={messages}
messages={messages}
showScrollButton={false}
maximizeChatSpace={false}
renderThread={({ messagesTree }) => (
<ol>
{messagesTree?.map((message) => (
<li key={message.messageId}>{message.text}</li>
))}
</ol>
)}
/>
</MessagePartsHostProvider>
</MessagesHostProvider>
</ChatContext.Provider>
</JotaiProvider>
</QueryClientProvider>
);
return render(
withSteerHost ? <SteerHostProvider host={createSteerHost()}>{list}</SteerHostProvider> : list,
);
}
describe('MessagesView pending defaults', () => {
it('renders the thread and no pending rows when no steer host is mounted', () => {
renderList(false);
expect(screen.getByText('shared reply')).toBeInTheDocument();
expect(screen.queryByTestId('pending-turn')).not.toBeInTheDocument();
expect(screen.queryByTestId('pending-steers')).not.toBeInTheDocument();
});
it('renders the pending turn and pending steers when a steer host is mounted', () => {
renderList(true);
expect(screen.getByText('shared reply')).toBeInTheDocument();
expect(screen.getByTestId('pending-turn')).toHaveTextContent('queued follow-up');
expect(screen.getByTestId('pending-steers')).toHaveTextContent('change of plan');
});
});

View file

@ -12,7 +12,9 @@ import type { MessagePartsHost } from '../../../../react/host';
import type { MessagesViewProps } from '../../MessagesView';
import { createMessagesHost } from '../../../../__fixtures__/messagesHost';
import { MessagesHostProvider } from '../../../../react/messages/host';
import { createSteerHost } from '../../../../__fixtures__/steerHost';
import { MessagePartsHostProvider } from '../../../../react/host';
import { SteerHostProvider } from '../../../../react/steer/host';
import { ChatContext } from '../../../../react/chat/context';
import { initEnglish } from '../../../../__fixtures__/i18n';
import { resolveThreadRows } from '../../../../core/thread';
@ -115,18 +117,20 @@ function renderThread(
const view = (next: Partial<MessagesViewProps>) => (
<Provider store={store}>
<QueryClientProvider client={queryClient}>
<ChatContext.Provider value={contract}>
<MessagesHostProvider host={host}>
<MessagePartsHostProvider host={partsHost}>
<MessagesView
showScrollButton={false}
maximizeChatSpace={false}
{...props}
{...next}
/>
</MessagePartsHostProvider>
</MessagesHostProvider>
</ChatContext.Provider>
<SteerHostProvider host={createSteerHost()}>
<ChatContext.Provider value={contract}>
<MessagesHostProvider host={host}>
<MessagePartsHostProvider host={partsHost}>
<MessagesView
showScrollButton={false}
maximizeChatSpace={false}
{...props}
{...next}
/>
</MessagePartsHostProvider>
</MessagesHostProvider>
</ChatContext.Provider>
</SteerHostProvider>
</QueryClientProvider>
</Provider>
);

View file

@ -37,9 +37,8 @@ function MessageNav({ conversationId }: { conversationId?: string | null }) {
return <div data-testid="message-nav" data-conversation-id={conversationId} />;
}
/** The app's slots, the way ChatView fills them, with each piece reduced to what it was handed. */
/** A host's optional replacements. Flat thread mode comes from the messages host. */
const slots = (): ChatScreenMessagesSlots => ({
flatThread: mockFlatThread,
renderPendingTurn: () => null,
renderPendingSteers: ({ conversationId, fullWidth }) => (
<div
@ -114,6 +113,7 @@ const host: MessagesHost = {
}),
renderMessageIcon: () => null,
useMaximizeChatSpace: () => false,
useFlatThread: () => mockFlatThread,
useHideSelectedAuthor: () => false,
useAgentsMap: () => undefined,
renderMessageBody: ({ message }) => <div data-testid="row">{message.messageId}</div>,

View file

@ -5,15 +5,12 @@ import { MessagesViewProvider } from '../../react/messages/view';
import { useChatSurface } from '../../react/subagents/surface';
import MessagesView from '../messages/MessagesView';
/** The list's slots the app fills: thread mode, pending pieces, scroll control and rail. */
/** The list's slots a host may replace: the thread, pending pieces, scroll control and rail.
* Flat thread mode is a host setting (`useFlatThread`), and the pending pieces render
* themselves when a slot is absent. */
export type ChatScreenMessagesSlots = Pick<
MessagesViewProps,
| 'flatThread'
| 'renderThread'
| 'renderPendingTurn'
| 'renderPendingSteers'
| 'renderScrollButton'
| 'renderNav'
'renderThread' | 'renderPendingTurn' | 'renderPendingSteers' | 'renderScrollButton' | 'renderNav'
>;
/** What the message list receives: the session's messages and the tree built from them. */

View file

@ -78,7 +78,7 @@ export {
abortScrollFamily,
launchedConversationFamily,
} from './react/generation';
export { SteerHostProvider, useSteerHost } from './react/steer/host';
export { SteerHostProvider, useOptionalSteerHost, useSteerHost } from './react/steer/host';
export type {
SteerHost,
SteerPane,

View file

@ -232,6 +232,9 @@ export interface MessagesHost {
renderMessageIcon: (props: MessageIconProps) => ReactNode;
/** Whether rows drop the reading-width cap and fill the pane. */
useMaximizeChatSpace: () => boolean;
/** Whether the thread renders as a flat row list. The flat renderer is the default;
* an app turns it off for the recursive tree. */
useFlatThread: () => boolean;
/** Whether a response by the agent the header's model selector shows drops its avatar and name
* (`interface.messageAuthor: whenDifferent`). */
useHideSelectedAuthor: () => boolean;
@ -297,6 +300,7 @@ const fallbackHost: MessagesHost = {
useMessageFeedback: () => noFeedback,
renderMessageIcon: () => null,
useMaximizeChatSpace: () => false,
useFlatThread: () => true,
useHideSelectedAuthor: () => false,
useAgentsMap: () => undefined,
renderMessageBody: () => null,

View file

@ -4,7 +4,7 @@
import { renderHook } from '@testing-library/react';
import type { ReactNode } from 'react';
import type { SteerHost } from '../host';
import { SteerHostProvider, useSteerHost } from '../host';
import { SteerHostProvider, useOptionalSteerHost, useSteerHost } from '../host';
const createHost = (label: string): SteerHost => ({
useSteerMessage: () => () => undefined,
@ -57,4 +57,18 @@ describe('useSteerHost', () => {
);
consoleError.mockRestore();
});
it('returns null from the optional lookup when no provider is mounted', () => {
const { result } = renderHook(() => useOptionalSteerHost());
expect(result.current).toBeNull();
});
it('returns the provided host from the optional lookup', () => {
const host = createHost('provided');
const wrapper = ({ children }: { children: ReactNode }) => (
<SteerHostProvider host={host}>{children}</SteerHostProvider>
);
const { result } = renderHook(() => useOptionalSteerHost(), { wrapper });
expect(result.current).toBe(host);
});
});

View file

@ -149,8 +149,14 @@ export function SteerHostProvider({
return <SteerHostContext.Provider value={host}>{children}</SteerHostContext.Provider>;
}
/** The nearest steer host, or null when this tree has none. A surface that can render without
* steering, such as a shared conversation, uses this and leaves the pending rows unmounted. */
export function useOptionalSteerHost(): SteerHost | null {
return useContext(SteerHostContext);
}
export function useSteerHost(): SteerHost {
const host = useContext(SteerHostContext);
const host = useOptionalSteerHost();
if (host == null) {
throw new Error('The steer hooks need a SteerHostProvider above them.');
}

View file

@ -33,10 +33,12 @@ import {
MessagePartIndex,
StreamHostProvider,
ChatSurfaceProvider,
SteerHostProvider,
MessagesHostProvider,
MessagePartsHostProvider,
ParentSubagentsProvider,
} from '@librechat/chat/react';
import { createSteerHost } from '../src/__fixtures__/steerHost';
import type {
ChatEvent,
TMessage,
@ -246,6 +248,7 @@ const messagesHost: MessagesHost = {
}),
renderMessageIcon: () => null,
useMaximizeChatSpace: () => false,
useFlatThread: () => true,
useHideSelectedAuthor: () => false,
useAgentsMap: () => undefined,
renderMessageBody: () => null,
@ -670,16 +673,18 @@ describe('a consumer rendering subagent activity', () => {
<I18nextProvider i18n={i18n}>
<QueryClientProvider client={new QueryClient()}>
<ChatContext.Provider value={contract}>
<MessagesHostProvider host={threadHost}>
<MessagePartsHostProvider host={host}>
<MessagesView
messages={messages}
messagesTree={messages}
showScrollButton={false}
maximizeChatSpace={false}
/>
</MessagePartsHostProvider>
</MessagesHostProvider>
<SteerHostProvider host={createSteerHost()}>
<MessagesHostProvider host={threadHost}>
<MessagePartsHostProvider host={host}>
<MessagesView
messages={messages}
messagesTree={messages}
showScrollButton={false}
maximizeChatSpace={false}
/>
</MessagePartsHostProvider>
</MessagesHostProvider>
</SteerHostProvider>
</ChatContext.Provider>
</QueryClientProvider>
</I18nextProvider>,

View file

@ -174,3 +174,14 @@
font-size: inherit;
line-height: inherit;
}
/**
* Message body typography for the package's message text, steers and queued turns. Following the
* chat font setting, it ships here so a consumer with only `@librechat/client/style.css` gets it.
*/
.message-content {
font-size: var(--markdown-font-size, var(--font-size-base, 1rem));
line-height: 1.6;
/* `.prose` sets max-width: 65ch; fill the message column instead. */
max-width: none;
}

View file

@ -0,0 +1,15 @@
import fs from 'fs';
import path from 'path';
const stylesheet = fs.readFileSync(path.resolve(__dirname, 'parts.css'), 'utf8');
describe('shared message body typography', () => {
it('ships the message-content rule with the published styles', () => {
const rule = stylesheet.match(/^\.message-content \{([^}]*)\}/m);
expect(rule).not.toBeNull();
const body = rule?.[1] ?? '';
expect(body).toMatch(/font-size:\s*var\(--markdown-font-size/);
expect(body).toMatch(/line-height:\s*1\.6/);
expect(body).toMatch(/max-width:\s*none/);
});
});