🧱 refactor: Draw Structured Message Rows Through ContentRow in @librechat/chat (#17701)

* refactor: Draw Content and Thread Rows Through a ContentRow in @librechat/chat

* test: Cover ContentRow Against Fake Hosts and Register the App Hosts in Row Specs

* test: Add Structured Reply Row Scenarios to the Mock Harness
This commit is contained in:
Marco Beretta 2026-11-02 00:43:42 +01:00 • committed by GitHub
parent d49c09e5a4
commit 47daeb6104
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 630 additions and 294 deletions

View file

@ -1,32 +1,10 @@
import React, { useMemo } from 'react';
import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
import {
HoverButtons,
getHeaderHoverLabel,
revealOnRowHoverClasses,
messageFooterClasses,
Elapsed,
shouldShowElapsed,
SiblingSwitch,
SubRow,
MessageRow,
} from '@librechat/chat/components';
import type { TMessageContentParts } from 'librechat-data-provider';
import { ContentRow, HoverButtons } from '@librechat/chat/components';
import type { TMessageProps, TMessageIcon } from '~/common';
import {
cn,
getMessageAriaLabel,
areMessageRowPropsEqual,
getHeaderPrefixForScreenReader,
} from '~/utils';
import { useLocalize, useAttachments, useMessageHelpers, useContentMetadata } from '~/hooks';
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { showThinkingAtom } from '~/store/showThinking';
import ContentParts from './Content/ContentParts';
import { AuthorContext } from '~/Providers';
import { useLocalize, useAttachments, useMessageHelpers, useContentMetadata } from '~/hooks';
import { areMessageRowPropsEqual } from '~/utils';
import store from '~/store';
/**
@ -61,8 +39,6 @@ function MessageParts(props: TMessageProps) {
} = useMessageHelpers(props, searchResults);
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
const autoExpandTools = useRecoilValue(store.autoExpandTools);
const showThinking = useAtomValue(showThinkingAtom);
const { messageId = null, isCreatedByUser } = message ?? {};
const name = useMemo(() => {
@ -98,14 +74,6 @@ function MessageParts(props: TMessageProps) {
],
);
const author = useMemo(
() => ({
icon: <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />,
label: name,
}),
[iconData, assistant, agent, name],
);
const { hasParallelContent } = useContentMetadata(message);
if (!message) {
@ -119,90 +87,45 @@ function MessageParts(props: TMessageProps) {
onTouchMove={handleScroll}
>
<div className="m-auto justify-center px-4 py-3 sm:px-0">
<MessageRow
<ContentRow
message={message}
id={messageId ?? ''}
icon={author.icon}
label={author.label}
hoverLabel={getHeaderHoverLabel(
hasConfiguredSender,
agent?.model,
assistant?.model,
message.model,
conversation?.model,
)}
timestamp={message.createdAt ?? message.clientTimestamp}
ariaLabel={getMessageAriaLabel(message, localize)}
headerPrefix={getHeaderPrefixForScreenReader(message, localize)}
isCreatedByUser={isCreatedByUser === true}
conversation={conversation ?? null}
index={index}
label={name}
iconData={iconData}
agent={agent}
assistant={assistant}
hasConfiguredSender={hasConfiguredSender}
isLast={isLast}
isLatestMessage={messageId === latestMessageId}
isSubmitting={isSubmitting}
edit={edit}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
siblingCount={siblingCount}
setSiblingIdx={setSiblingIdx}
attachments={attachments}
searchResults={searchResults}
hasParallelContent={hasParallelContent}
fullWidth={maximizeChatSpace}
isEditing={edit}
footer={
<SubRow classes={cn(messageFooterClasses, isCreatedByUser && 'justify-end')}>
{/* The reading holds the column start: it takes over the slot the streaming
dot vacates, so the retry navigation beside it — whose width the footer
reserves whether or not hover has revealed it — must never push the
timer inboard of that column. */}
{shouldShowElapsed({
isSubmitting,
isLatestMessage: messageId === latestMessageId,
isCreatedByUser,
siblingIdx,
siblingCount,
}) && <Elapsed index={index} />}
{/* While the answer is generating every other action is withheld, which
would otherwise leave this counter sitting alone under a half-written
response. It reveals on hover there, like the actions it sits with. */}
<SiblingSwitch
siblingIdx={siblingIdx}
siblingCount={siblingCount}
setSiblingIdx={setSiblingIdx}
className={cn(
isSubmitting && messageId === latestMessageId && revealOnRowHoverClasses,
)}
/>
<HoverButtons
index={index}
isEditing={edit}
message={message}
enterEdit={enterEdit}
conversation={conversation ?? null}
regenerate={() => regenerateMessage()}
copyToClipboard={copyToClipboard}
getCanCopy={getCanCopy}
handleContinue={handleContinue}
latestMessageId={latestMessageId}
isLast={isLast}
/>
</SubRow>
toolbar={
<HoverButtons
index={index}
isEditing={edit}
message={message}
enterEdit={enterEdit}
conversation={conversation ?? null}
regenerate={() => regenerateMessage()}
copyToClipboard={copyToClipboard}
getCanCopy={getCanCopy}
handleContinue={handleContinue}
latestMessageId={latestMessageId}
isLast={isLast}
/>
}
>
<AuthorContext.Provider value={author}>
<ErrorSourceProvider message={message}>
<ContentParts
edit={edit}
isLast={isLast}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
attachments={attachments}
isSubmitting={isSubmitting}
searchResults={searchResults}
manualSkills={message.manualSkills}
messageId={message.messageId}
renderOwnerId={message.clientQueueParentMessageId}
authorHeader={isCreatedByUser === true ? undefined : RESUME_AUTHOR_HEADER}
setSiblingIdx={setSiblingIdx}
isCreatedByUser={message.isCreatedByUser}
conversationId={conversation?.conversationId}
foldLiveActivity={!autoExpandTools}
showThinking={showThinking}
isLatestMessage={messageId === latestMessageId}
content={message.content as Array<TMessageContentParts | undefined>}
/>
</ErrorSourceProvider>
</AuthorContext.Provider>
</MessageRow>
authorHeader={RESUME_AUTHOR_HEADER}
renderOwnerId={message.clientQueueParentMessageId}
/>
</div>
</div>
);

View file

@ -13,6 +13,8 @@ import StructuredMessage from '~/components/Messages/MessageContent';
import MessageParts from '~/components/Chat/Messages/MessageParts';
import Message from '~/components/Chat/Messages/Message';
import store from '~/store';
import '~/components/Chat/Messages/Content/register';
import '~/Providers/MessagesHostContext';
let mockHoverButtonsRenderCount = 0;
let mockContentRenderCount = 0;

View file

@ -1,36 +1,14 @@
import { useCallback, useMemo, memo } from 'react';
import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
import { Constants } from 'librechat-data-provider';
import {
HoverButtons,
revealOnRowHoverClasses,
messageFooterClasses,
Elapsed,
shouldShowElapsed,
getHeaderHoverLabel,
SiblingSwitch,
SubRow,
MessageRow,
} from '@librechat/chat/components';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import { ContentRow, HoverButtons } from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
import type { TMessageProps, TMessageIcon, TMessageChatContext } from '~/common';
import {
cn,
isSameTailRelation,
getMessageAriaLabel,
areMessageFieldsEqual,
getHeaderPrefixForScreenReader,
} from '~/utils';
import { useLocalize, useAttachments, useMessageActions, useContentMetadata } from '~/hooks';
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import ToolCallLimitNotice from '~/components/Chat/Messages/Content/ToolCallLimitNotice';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
import { useAttachments, useMessageActions, useContentMetadata } from '~/hooks';
import { PrivateText } from '~/components/Chat/Messages/PrivateText';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { showThinkingAtom } from '~/store/showThinking';
import { AuthorContext } from '~/Providers';
import { areMessageFieldsEqual, isSameTailRelation } from '~/utils';
import store from '~/store';
/**
@ -99,7 +77,6 @@ const ContentRender = memo(function ContentRender({
latestMessageId,
latestMessageDepth,
}: ContentRenderProps) {
const localize = useLocalize();
const { attachments, searchResults } = useAttachments({
messageId: msg?.messageId,
attachments: msg?.attachments,
@ -126,8 +103,6 @@ const ContentRender = memo(function ContentRender({
chatContext,
});
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
const autoExpandTools = useRecoilValue(store.autoExpandTools);
const showThinking = useAtomValue(showThinkingAtom);
const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);
const getLatestMessageId = useCallback(() => chatContext.latestMessageId, [chatContext]);
@ -156,14 +131,6 @@ const ContentRender = memo(function ContentRender({
],
);
const author = useMemo(
() => ({
icon: <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />,
label: messageLabel ?? '',
}),
[iconData, assistant, agent, messageLabel],
);
const { hasParallelContent } = useContentMetadata(msg);
if (!msg) {
@ -171,103 +138,63 @@ const ContentRender = memo(function ContentRender({
}
return (
<MessageRow
<ContentRow
message={msg}
id={msg.messageId}
icon={author.icon}
label={author.label}
hoverLabel={getHeaderHoverLabel(
hasConfiguredSender,
agent?.model,
assistant?.model,
msg.model,
conversation?.model,
)}
timestamp={msg.createdAt ?? msg.clientTimestamp}
ariaLabel={getMessageAriaLabel(msg, localize)}
headerPrefix={getHeaderPrefixForScreenReader(msg, localize)}
isCreatedByUser={msg.isCreatedByUser === true}
conversation={conversation ?? null}
index={index}
label={messageLabel ?? ''}
iconData={iconData}
agent={agent}
assistant={assistant}
hasConfiguredSender={hasConfiguredSender}
isLast={isLast}
isLatestMessage={isLatestMessage}
isSubmitting={isSubmitting}
edit={edit}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
siblingCount={siblingCount}
setSiblingIdx={setSiblingIdx}
attachments={attachments}
searchResults={searchResults}
hasParallelContent={hasParallelContent}
fullWidth={maximizeChatSpace}
isEditing={edit}
footer={
<SubRow classes={cn(messageFooterClasses, msg.isCreatedByUser && 'justify-end')}>
{/* The reading holds the column start: it takes over the slot the streaming
dot vacates, so the retry navigation beside it — whose width the footer
reserves whether or not hover has revealed it — must never push the
timer inboard of that column. */}
{shouldShowElapsed({
isSubmitting,
isLatestMessage,
isCreatedByUser: msg.isCreatedByUser,
siblingIdx,
siblingCount,
}) && <Elapsed index={index} />}
{/* While the answer is generating every other action is withheld, which
would otherwise leave this counter sitting alone under a half-written
response. It reveals on hover there, like the actions it sits with. */}
<SiblingSwitch
siblingIdx={siblingIdx}
siblingCount={siblingCount}
setSiblingIdx={setSiblingIdx}
className={cn(isSubmitting && isLatestMessage && revealOnRowHoverClasses)}
/>
<HoverButtons
index={index}
message={msg}
isEditing={edit}
enterEdit={enterEdit}
conversation={conversation ?? null}
regenerate={handleRegenerateMessage}
copyToClipboard={copyToClipboard}
getCanCopy={getCanCopy}
handleContinue={handleContinue}
latestMessageId={latestMessageId}
getLatestMessageId={getLatestMessageId}
handleFeedback={handleFeedback}
isLast={isLast}
/>
</SubRow>
toolbar={
<HoverButtons
index={index}
message={msg}
isEditing={edit}
enterEdit={enterEdit}
conversation={conversation ?? null}
regenerate={handleRegenerateMessage}
copyToClipboard={copyToClipboard}
getCanCopy={getCanCopy}
handleContinue={handleContinue}
latestMessageId={latestMessageId}
getLatestMessageId={getLatestMessageId}
handleFeedback={handleFeedback}
isLast={isLast}
/>
}
>
<AuthorContext.Provider value={author}>
<ErrorSourceProvider message={msg}>
{!edit && msg.isCreatedByUser && msg.privacyRevision ? (
<PrivateText message={msg} />
) : (
<ContentParts
edit={edit}
isLast={isLast}
enterEdit={enterEdit}
siblingIdx={siblingIdx}
messageId={msg.messageId}
attachments={attachments}
searchResults={searchResults}
manualSkills={msg.manualSkills}
authorHeader={msg.isCreatedByUser === true ? undefined : RESUME_AUTHOR_HEADER}
setSiblingIdx={setSiblingIdx}
isLatestMessage={isLatestMessage}
isSubmitting={isSubmitting}
isCreatedByUser={msg.isCreatedByUser}
createdAt={msg.createdAt ?? msg.clientTimestamp}
foldLiveActivity={!autoExpandTools}
showThinking={showThinking}
conversationId={conversation?.conversationId}
content={msg.content as Array<TMessageContentParts | undefined>}
/>
)}
</ErrorSourceProvider>
</AuthorContext.Provider>
{/** A turn that ran out of agent steps is incomplete, not broken. Rendered
* here rather than inside `ContentParts` because it is a message-level
* outcome, and `ContentParts` also serves surfaces (subagent panels,
* search) that have no message row behind them. */}
{msg.unfinished === true &&
authorHeader={RESUME_AUTHOR_HEADER}
createdAt={msg.createdAt ?? msg.clientTimestamp}
body={
!edit && msg.isCreatedByUser && msg.privacyRevision ? (
<PrivateText message={msg} />
) : undefined
}
notice={
/** A turn that ran out of agent steps is incomplete, not broken. Rendered
* here rather than inside `ContentParts` because it is a message-level
* outcome, and `ContentParts` also serves surfaces (subagent panels,
* search) that have no message row behind them. */
msg.unfinished === true &&
!isSubmitting &&
msg.finish_reason === Constants.TOOL_CALL_LIMIT_FINISH_REASON && (
msg.finish_reason === Constants.TOOL_CALL_LIMIT_FINISH_REASON ? (
<ToolCallLimitNotice message={msg} />
)}
</MessageRow>
) : undefined
}
/>
);
}, areContentRenderPropsEqual);
ContentRender.displayName = 'ContentRender';

View file

@ -4,6 +4,8 @@ import { act, render } from '@testing-library/react';
import type { TConversation, TMessage } from 'librechat-data-provider';
import { ChatContext, MessagesViewProvider, useChatContext } from '~/Providers';
import MessageContent from '../MessageContent';
import '~/components/Chat/Messages/Content/register';
import '~/Providers/MessagesHostContext';
const mockRowRenders = new Map<string, number>();
@ -20,25 +22,11 @@ jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
HoverButtons: () => null,
MessageRow: ({
id,
children,
footer,
}: {
id?: string;
children: React.ReactNode;
footer: React.ReactNode;
}) => {
mockRowRenders.set(id ?? '', (mockRowRenders.get(id ?? '') ?? 0) + 1);
return (
<div data-testid={`row-${id}`}>
{children}
{footer}
</div>
);
ContentRow: ({ message }: { message: { messageId: string } }) => {
const id = message.messageId;
mockRowRenders.set(id, (mockRowRenders.get(id) ?? 0) + 1);
return <div data-testid={`row-${id}`} />;
},
Elapsed: () => null,
shouldShowElapsed: () => false,
}));
jest.mock('~/hooks', () => ({

View file

@ -4,6 +4,8 @@ import { render, screen, within } from '@testing-library/react';
import type { Agent, TConversation, TMessage } from 'librechat-data-provider';
import type { TMessageChatContext } from '~/common';
import ContentRender from '../ContentRender';
import '~/components/Chat/Messages/Content/register';
import '~/Providers/MessagesHostContext';
const mockRenders = { parts: 0 };

View file

@ -8,6 +8,8 @@ import { OwnerTextProvider } from '~/components/Chat/Messages/PrivateText';
import MessageRender from '~/components/Chat/Messages/ui/MessageRender';
import ContentRender from '../ContentRender';
import '~/Providers/MessagesHostContext';
import '~/components/Chat/Messages/Content/register';
import '~/Providers/MessagesHostContext';
jest.mock('librechat-data-provider', () => ({
...jest.requireActual('librechat-data-provider'),

View file

@ -13,7 +13,7 @@ import {
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import type { BranchSiblingIndex } from '@librechat/chat';
import type { QueryClient } from '@tanstack/react-query';
import type { LocalizeFunction, TMessageProps } from '~/common';
import type { TMessageProps } from '~/common';
export {
getPartKeyIndex,
@ -224,37 +224,12 @@ export const clearArchivedConversationMessagesCache = (
queryClient.setQueryData<TMessage[]>([QueryKeys.messages, Constants.NEW_CONVO], []);
};
/** Returns a 1-based message number, or null if depth is absent or invalid. */
const getMessageNumber = (message: TMessage): number | null => {
if (message.depth == null || message.depth < 0) {
return null;
}
return message.depth + 1;
};
export const getMessageAriaLabel = (message: TMessage, localize: LocalizeFunction): string => {
const number = getMessageNumber(message);
return number != null
? localize('com_endpoint_message_new', { 0: number })
: localize('com_endpoint_message');
};
/**
* Provides a screen-reader-only heading prefix distinguishing prompts from responses,
* with an optional 1-based turn number derived from message depth.
*/
export const getHeaderPrefixForScreenReader = (
message: TMessage,
localize: LocalizeFunction,
): string => {
const number = getMessageNumber(message);
const suffix = number != null ? ` ${number}` : '';
return message.isCreatedByUser
? `${localize('com_ui_prompt')}${suffix}: `
: `${localize('com_ui_response')}${suffix}: `;
};
export { isValidTimestamp, getMessageTimestamp } from '@librechat/chat/components';
export {
isValidTimestamp,
getMessageTimestamp,
getMessageAriaLabel,
getHeaderPrefixForScreenReader,
} from '@librechat/chat/components';
export type { MessageTimestamp } from '@librechat/chat/components';
export function areMessageFilesEqual(prevFiles?: TMessage['files'], nextFiles?: TMessage['files']) {

View file

@ -124,6 +124,8 @@ export interface SeedMessage {
content?: Record<string, unknown>[];
/** Why the turn stopped; the hover Continue is offered only for some values. */
finish_reason?: string;
/** A turn the server left incomplete, such as one that ran out of agent steps. */
unfinished?: boolean;
model?: string;
/** Attachments on the turn, as the client renders them (an image opens the lightbox). */
files?: Record<string, unknown>[];
@ -149,7 +151,7 @@ export async function seedMessages(
user: userId,
endpoint: 'openAI',
error: false,
unfinished: false,
unfinished: message.unfinished ?? false,
createdAt: new Date(start + index * 1000),
updatedAt: new Date(start + index * 1000),
__v: 0,

View file

@ -0,0 +1,118 @@
import { randomUUID } from 'node:crypto';
import { expect, test } from '@playwright/test';
import type { Page } from '@playwright/test';
import type { SeedMessage } from '../db';
import { getE2EUser } from '../../../setup/user';
import {
seedMessages,
seedConversations,
deleteConversations,
deleteMessagesByConversation,
} from '../db';
/** A structured reply's row, now drawn by `@librechat/chat`'s `ContentRow`: its header and
* actions, an error part named after the row's model, and the outcome notice under it. Seeded
* straight into Mongo, since the mock model cannot persist these part shapes. */
const ROOT_PARENT = '00000000-0000-0000-0000-000000000000';
const userEmail = getE2EUser().email;
const createdConversationIds: string[] = [];
test.describe.configure({ timeout: 120_000 });
test.afterAll(async () => {
await deleteMessagesByConversation(createdConversationIds);
await deleteConversations(createdConversationIds);
});
async function seedReply(reply: Omit<SeedMessage, 'messageId' | 'parentMessageId'>) {
const conversationId = randomUUID();
const userMessageId = randomUUID();
const replyId = randomUUID();
await seedConversations(userEmail, [
{ conversationId, title: `Content row ${conversationId.slice(0, 8)}`, updatedAt: new Date() },
]);
createdConversationIds.push(conversationId);
await seedMessages(userEmail, conversationId, [
{
messageId: userMessageId,
parentMessageId: ROOT_PARENT,
text: 'Check the deployment',
isCreatedByUser: true,
sender: 'User',
},
{ messageId: replyId, parentMessageId: userMessageId, ...reply },
]);
return { conversationId, replyId };
}
async function openReply(page: Page, conversationId: string, replyId: string) {
await page.goto(`/c/${conversationId}`);
const row = page.locator(`[id="${replyId}"]`);
await expect(row).toBeVisible();
await row.hover();
return row;
}
test.describe('structured reply row', () => {
test('a structured reply shows its author, its parts and its actions @scenario:content-row-structured-reply', async ({
page,
}) => {
const { conversationId, replyId } = await seedReply({
text: 'The deployment is healthy.',
isCreatedByUser: false,
sender: 'Ops Agent',
content: [{ type: 'text', text: 'The deployment is healthy.' }],
});
const row = await openReply(page, conversationId, replyId);
await expect(row).toHaveAccessibleName('Message 2');
await expect(row.getByRole('heading', { level: 2 })).toContainText('Ops Agent');
await expect(row.getByText('The deployment is healthy.')).toBeVisible();
await expect(row.getByTestId('copy-response-button')).toBeVisible();
});
test('an error part names the model of the row that failed @scenario:content-row-error-names-row-model', async ({
page,
}) => {
const { conversationId, replyId } = await seedReply({
text: '',
isCreatedByUser: false,
sender: 'OpenAI',
model: 'gpt-4o',
content: [
{
type: 'error',
error: JSON.stringify({ type: 'refusal', info: "I can't help with that request." }),
},
],
});
const row = await openReply(page, conversationId, replyId);
await expect(
row.getByText('gpt-4o declined to answer this request. Rewrite your message and try again.'),
).toBeVisible();
});
test('a turn that ran out of agent steps shows the limit notice after its content @scenario:content-row-tool-call-limit-notice', async ({
page,
}) => {
const { conversationId, replyId } = await seedReply({
text: 'Checked three of five services.',
isCreatedByUser: false,
sender: 'OpenAI',
unfinished: true,
finish_reason: 'tool_call_limit',
content: [{ type: 'text', text: 'Checked three of five services.' }],
});
const row = await openReply(page, conversationId, replyId);
const notice = row.getByRole('group', { name: 'Reached the tool call limit for this turn' });
await expect(notice).toBeVisible();
await expect(row.getByRole('button', { name: 'Keep going' })).toBeVisible();
await row.getByRole('button', { name: 'Dismiss this notice' }).click();
await expect(notice).toHaveCount(0);
await expect(row.getByText('Checked three of five services.')).toBeVisible();
});
});

View file

@ -91,6 +91,9 @@ export { default as Fork } from './components/messages/Fork';
export { default as Feedback } from './components/messages/Feedback';
export { default as MinimalHoverButtons } from './components/messages/MinimalHoverButtons';
export { default as HoverButtons } from './components/messages/HoverButtons';
export { default as ContentRow } from './components/messages/ContentRow';
export type { ContentRowProps } from './components/messages/ContentRow';
export { getMessageAriaLabel, getHeaderPrefixForScreenReader } from './components/messages/labels';
/** Parts: the leaf components and row classes tool cards share. */
export { default as Stdout } from './components/parts/Stdout';

View file

@ -0,0 +1,188 @@
import { useMemo } from 'react';
import { cn, useLocalize } from '@librechat/client';
import type {
Agent,
TMessage,
Assistant,
TAttachment,
TConversation,
SearchResultData,
} from 'librechat-data-provider';
import type { ReactNode } from 'react';
import type { MessageIconData } from '../../react/messages/host';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from './labels';
import { revealOnRowHoverClasses, messageFooterClasses } from './styles';
import { ErrorSourceProvider } from '../../react/messages/error';
import { MessageIconSlot } from '../../react/messages/host';
import { AuthorContext } from '../../react/messages/author';
import Elapsed, { shouldShowElapsed } from './Elapsed';
import { useMessagePartsHost } from '../../react/host';
import { getHeaderHoverLabel } from './HeaderLabel';
import SiblingSwitch from './SiblingSwitch';
import MessageRow from './MessageRow';
import SubRow from './SubRow';
/** A message row whose body is its content parts: what the app's row hooks resolved for it. */
export type ContentRowProps = {
message: TMessage;
conversation: TConversation | null;
/** The pane the row renders in. */
index: number;
/** The author's name, also the icon's model label. */
label: string;
iconData: MessageIconData;
agent?: Agent;
assistant?: Assistant;
/** Whether the sender's name comes from configuration rather than the model. */
hasConfiguredSender: boolean;
isLast: boolean;
isLatestMessage: boolean;
isSubmitting: boolean;
edit: boolean;
enterEdit: (cancel?: boolean) => void;
siblingIdx?: number;
siblingCount?: number;
setSiblingIdx?: ((value: number) => void) | null;
attachments?: TAttachment[];
searchResults?: Record<string, SearchResultData>;
/** Whether the content lays out agent columns side by side, which widens the row. */
hasParallelContent: boolean;
/** Whether the viewer widened the chat to the full window. */
fullWidth: boolean;
/** The row's hover actions, drawn at the end of the footer (the package's `HoverButtons`). */
toolbar: ReactNode;
/** The header restated before content that resumes after a steer; assistant rows only. */
authorHeader?: ReactNode;
/** Client-only parent anchor carried by one response while its server identities hydrate. */
renderOwnerId?: string;
/** Forwarded to the parts as the time parallel column headers show. */
createdAt?: string | null;
/** Replaces the content parts, for a body the app draws itself (a private prompt). */
body?: ReactNode;
/** A message-level outcome drawn after the content. */
notice?: ReactNode;
};
/**
* The row of a message rendered from content parts: header, parts and footer (elapsed time,
* sibling navigation and the caller's toolbar). The parts render through the host's content-parts
* slot, inside the author and error-source contexts their headers and error cards read.
*/
export default function ContentRow({
message,
conversation,
index,
label,
iconData,
agent,
assistant,
hasConfiguredSender,
isLast,
isLatestMessage,
isSubmitting,
edit,
enterEdit,
siblingIdx,
siblingCount,
setSiblingIdx,
attachments,
searchResults,
hasParallelContent,
fullWidth,
toolbar,
authorHeader,
renderOwnerId,
createdAt,
body,
notice,
}: ContentRowProps): ReactNode {
const localize = useLocalize();
const host = useMessagePartsHost();
const showThinking = host.useShowThinking();
const autoExpandTools = host.useAutoExpandTools();
const isCreatedByUser = message.isCreatedByUser === true;
const author = useMemo(
() => ({
icon: <MessageIconSlot iconData={iconData} assistant={assistant} agent={agent} />,
label,
}),
[iconData, assistant, agent, label],
);
return (
<MessageRow
message={message}
id={message.messageId}
icon={author.icon}
label={author.label}
hoverLabel={getHeaderHoverLabel(
hasConfiguredSender,
agent?.model,
assistant?.model,
message.model,
conversation?.model,
)}
timestamp={message.createdAt ?? message.clientTimestamp}
ariaLabel={getMessageAriaLabel(message, localize)}
headerPrefix={getHeaderPrefixForScreenReader(message, localize)}
isCreatedByUser={isCreatedByUser}
hasParallelContent={hasParallelContent}
fullWidth={fullWidth}
isEditing={edit}
footer={
<SubRow classes={cn(messageFooterClasses, isCreatedByUser && 'justify-end')}>
{/* The reading holds the column start: it takes over the slot the streaming
dot vacates, so the retry navigation beside it, whose width the footer
reserves whether or not hover has revealed it, must never push the
timer inboard of that column. */}
{shouldShowElapsed({
isSubmitting,
isLatestMessage,
isCreatedByUser: message.isCreatedByUser,
siblingIdx,
siblingCount,
}) && <Elapsed index={index} />}
{/* While the answer is generating every other action is withheld, which
would otherwise leave this counter sitting alone under a half-written
response. It reveals on hover there, like the actions it sits with. */}
<SiblingSwitch
siblingIdx={siblingIdx}
siblingCount={siblingCount}
setSiblingIdx={setSiblingIdx}
className={cn(isSubmitting && isLatestMessage && revealOnRowHoverClasses)}
/>
{toolbar}
</SubRow>
}
>
<AuthorContext.Provider value={author}>
<ErrorSourceProvider message={message}>
{body ??
host.renderContentParts({
edit,
isLast,
enterEdit,
siblingIdx,
attachments,
searchResults,
isSubmitting,
isLatestMessage,
isCreatedByUser,
renderOwnerId,
createdAt,
showThinking,
authorHeader: isCreatedByUser ? undefined : authorHeader,
setSiblingIdx,
messageId: message.messageId,
manualSkills: message.manualSkills,
foldLiveActivity: !autoExpandTools,
conversationId: conversation?.conversationId ?? null,
content: message.content ?? [],
})}
</ErrorSourceProvider>
</AuthorContext.Provider>
{notice}
</MessageRow>
);
}

View file

@ -0,0 +1,167 @@
/**
* @jest-environment jsdom
*/
import { render, screen, within } from '@testing-library/react';
import { ContentTypes, EModelEndpoint } from 'librechat-data-provider';
import type { TConversation, TMessage } from 'librechat-data-provider';
import type { ContentPartsSlotProps, MessagePartsHost } from '../../../react/host';
import type { ContentRowProps } from '../ContentRow';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { MessagesHostProvider } from '../../../react/messages/host';
import { useAuthorContext } from '../../../react/messages/author';
import { useErrorSource } from '../../../react/messages/error';
import { MessagePartsHostProvider } from '../../../react/host';
import { initEnglish } from '../../../__fixtures__/i18n';
import { MessageContext } from '../../../react/message';
import ContentRow from '../ContentRow';
beforeAll(initEnglish);
const conversation = {
conversationId: 'convo-1',
endpoint: EModelEndpoint.agents,
model: 'gpt-x',
} as TConversation;
const reply = {
messageId: 'assistant-1',
conversationId: 'convo-1',
parentMessageId: 'user-1',
isCreatedByUser: false,
endpoint: EModelEndpoint.agents,
model: 'gpt-x',
depth: 1,
text: '',
content: [
{ type: ContentTypes.TEXT, text: 'Here is the answer' },
{ type: ContentTypes.ERROR, error: 'boom', agentId: 'agent_lane' },
],
} as TMessage;
/** What a part rendered inside the row reads from the row's contexts. */
function PartProbe() {
const author = useAuthorContext();
const source = useErrorSource();
return (
<span data-testid="probe">
{author?.label}|{source?.partAgentId}
</span>
);
}
function renderRow(
props: Partial<ContentRowProps> = {},
parts: Partial<MessagePartsHost> = {},
renderContentParts = jest.fn((_props: ContentPartsSlotProps) => (
<MessageContext.Provider value={{ messageId: 'assistant-1', isExpanded: false, partIndex: 1 }}>
<PartProbe />
</MessageContext.Provider>
)),
) {
const partsHost = {
useShowThinking: () => true,
useAutoExpandTools: () => false,
renderContentParts,
...parts,
} as MessagePartsHost;
const messagesHost = createMessagesHost({
renderMessageIcon: ({ iconData }) => <span data-testid="icon">{iconData?.model}</span>,
});
render(
<MessagesHostProvider host={messagesHost}>
<MessagePartsHostProvider host={partsHost}>
<ContentRow
message={reply}
conversation={conversation}
index={0}
label="Research Agent"
iconData={{ endpoint: EModelEndpoint.agents, model: 'gpt-x' }}
hasConfiguredSender={false}
isLast={true}
isLatestMessage={true}
isSubmitting={false}
edit={false}
enterEdit={jest.fn()}
hasParallelContent={false}
fullWidth={false}
toolbar={<button type="button">Copy to clipboard</button>}
{...props}
/>
</MessagePartsHostProvider>
</MessagesHostProvider>,
);
return renderContentParts;
}
describe('ContentRow', () => {
it('labels the row and draws its author icon through the messages host', () => {
renderRow();
const row = screen.getByRole('group', { name: 'Message 2' });
expect(within(row).getByRole('heading', { level: 2 })).toHaveTextContent('Research Agent');
expect(within(row).getByTestId('icon')).toHaveTextContent('gpt-x');
expect(within(row).getByRole('button', { name: 'Copy to clipboard' })).toBeInTheDocument();
});
it('hands the content-parts slot the row state and the viewer preferences', () => {
const header = <span>header</span>;
const renderContentParts = renderRow({
authorHeader: header,
siblingIdx: 1,
renderOwnerId: 'q-1',
});
expect(renderContentParts).toHaveBeenCalledWith(
expect.objectContaining({
content: reply.content,
messageId: 'assistant-1',
conversationId: 'convo-1',
isCreatedByUser: false,
isLast: true,
isLatestMessage: true,
isSubmitting: false,
siblingIdx: 1,
renderOwnerId: 'q-1',
authorHeader: header,
showThinking: true,
foldLiveActivity: true,
}),
);
});
it('withholds the resume header from a user message', () => {
const renderContentParts = renderRow({
message: { ...reply, isCreatedByUser: true },
authorHeader: <span>header</span>,
});
expect(renderContentParts).toHaveBeenCalledWith(
expect.objectContaining({ isCreatedByUser: true, authorHeader: undefined }),
);
});
it('gives the parts the row author and resolves an error part to its lane agent', () => {
renderRow();
expect(screen.getByTestId('probe')).toHaveTextContent('Research Agent|agent_lane');
});
it('draws a body the app supplies in place of the parts, and a notice after them', () => {
const renderContentParts = renderRow({
body: <p>Private prompt</p>,
notice: <p role="note">Stopped at the tool call limit</p>,
});
expect(renderContentParts).not.toHaveBeenCalled();
expect(screen.getByText('Private prompt')).toBeInTheDocument();
expect(screen.getByRole('note')).toHaveTextContent('Stopped at the tool call limit');
});
it('expands live activity when the viewer asked for tools expanded', () => {
const renderContentParts = renderRow({}, { useAutoExpandTools: () => true });
expect(renderContentParts).toHaveBeenCalledWith(
expect.objectContaining({ foldLiveActivity: false }),
);
});
});

View file

@ -0,0 +1,39 @@
import type { TMessage } from 'librechat-data-provider';
/** The keys these labels read, so any app's localize function that knows them fits. */
type LabelKey =
| 'com_endpoint_message_new'
| 'com_endpoint_message'
| 'com_ui_prompt'
| 'com_ui_response';
/** Translates a key with positional values, as `useLocalize` returns. */
type Localize = (phraseKey: LabelKey, options?: Record<string, string | number>) => string;
/** Returns a 1-based message number, or null if depth is absent or invalid. */
const getMessageNumber = (message: TMessage): number | null => {
if (message.depth == null || message.depth < 0) {
return null;
}
return message.depth + 1;
};
/** The accessible name of a message row, numbered by its depth in the thread when it has one. */
export const getMessageAriaLabel = (message: TMessage, localize: Localize): string => {
const number = getMessageNumber(message);
return number != null
? localize('com_endpoint_message_new', { 0: number })
: localize('com_endpoint_message');
};
/**
* Provides a screen-reader-only heading prefix distinguishing prompts from responses,
* with an optional 1-based turn number derived from message depth.
*/
export const getHeaderPrefixForScreenReader = (message: TMessage, localize: Localize): string => {
const number = getMessageNumber(message);
const suffix = number != null ? ` ${number}` : '';
return message.isCreatedByUser
? `${localize('com_ui_prompt')}${suffix}: `
: `${localize('com_ui_response')}${suffix}: `;
};