diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsx index dace40b537..09dbc49060 100644 --- a/client/src/components/Chat/Messages/MessageParts.tsx +++ b/client/src/components/Chat/Messages/MessageParts.tsx @@ -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: , - label: name, - }), - [iconData, assistant, agent, name], - ); - const { hasParallelContent } = useContentMetadata(message); if (!message) { @@ -119,90 +87,45 @@ function MessageParts(props: TMessageProps) { onTouchMove={handleScroll} >
- - {/* 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, - }) && } - {/* 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. */} - - regenerateMessage()} - copyToClipboard={copyToClipboard} - getCanCopy={getCanCopy} - handleContinue={handleContinue} - latestMessageId={latestMessageId} - isLast={isLast} - /> - + toolbar={ + regenerateMessage()} + copyToClipboard={copyToClipboard} + getCanCopy={getCanCopy} + handleContinue={handleContinue} + latestMessageId={latestMessageId} + isLast={isLast} + /> } - > - - - } - /> - - - + authorHeader={RESUME_AUTHOR_HEADER} + renderOwnerId={message.clientQueueParentMessageId} + />
); diff --git a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx index 1f13968670..e5cefddedd 100644 --- a/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx +++ b/client/src/components/Chat/Messages/__tests__/HoverActions.streaming.spec.tsx @@ -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; diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsx index 8425f7b1fd..04bc7cdc69 100644 --- a/client/src/components/Messages/ContentRender.tsx +++ b/client/src/components/Messages/ContentRender.tsx @@ -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: , - label: messageLabel ?? '', - }), - [iconData, assistant, agent, messageLabel], - ); - const { hasParallelContent } = useContentMetadata(msg); if (!msg) { @@ -171,103 +138,63 @@ const ContentRender = memo(function ContentRender({ } return ( - - {/* 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, - }) && } - {/* 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. */} - - - + toolbar={ + } - > - - - {!edit && msg.isCreatedByUser && msg.privacyRevision ? ( - - ) : ( - } - /> - )} - - - {/** 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 ? ( + + ) : 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 ? ( - )} - + ) : undefined + } + /> ); }, areContentRenderPropsEqual); ContentRender.displayName = 'ContentRender'; diff --git a/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx b/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx index eceaac79ff..70f7f2d63e 100644 --- a/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx +++ b/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx @@ -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(); @@ -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 ( -
- {children} - {footer} -
- ); + ContentRow: ({ message }: { message: { messageId: string } }) => { + const id = message.messageId; + mockRowRenders.set(id, (mockRowRenders.get(id) ?? 0) + 1); + return
; }, - Elapsed: () => null, - shouldShowElapsed: () => false, })); jest.mock('~/hooks', () => ({ diff --git a/client/src/components/Messages/__tests__/ContentRender.test.tsx b/client/src/components/Messages/__tests__/ContentRender.test.tsx index d47aa0b1fc..844f227759 100644 --- a/client/src/components/Messages/__tests__/ContentRender.test.tsx +++ b/client/src/components/Messages/__tests__/ContentRender.test.tsx @@ -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 }; diff --git a/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx b/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx index d5df546eee..0165874151 100644 --- a/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx +++ b/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx @@ -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'), diff --git a/client/src/utils/messages.ts b/client/src/utils/messages.ts index a26bd4da75..ae77c7cf11 100644 --- a/client/src/utils/messages.ts +++ b/client/src/utils/messages.ts @@ -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([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']) { diff --git a/e2e/specs/mock/db.ts b/e2e/specs/mock/db.ts index be9d8b6ec4..18cd90d8f6 100644 --- a/e2e/specs/mock/db.ts +++ b/e2e/specs/mock/db.ts @@ -124,6 +124,8 @@ export interface SeedMessage { content?: Record[]; /** 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[]; @@ -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, diff --git a/e2e/specs/mock/scenarios/content-row.spec.ts b/e2e/specs/mock/scenarios/content-row.spec.ts new file mode 100644 index 0000000000..c8f5a23961 --- /dev/null +++ b/e2e/specs/mock/scenarios/content-row.spec.ts @@ -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) { + 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(); + }); +}); diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index e9e2a4a8a3..c35dd64d42 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -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'; diff --git a/packages/chat/src/components/messages/ContentRow.tsx b/packages/chat/src/components/messages/ContentRow.tsx new file mode 100644 index 0000000000..0b89526669 --- /dev/null +++ b/packages/chat/src/components/messages/ContentRow.tsx @@ -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; + /** 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: , + label, + }), + [iconData, assistant, agent, label], + ); + + return ( + + {/* 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, + }) && } + {/* 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. */} + + {toolbar} + + } + > + + + {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 ?? [], + })} + + + {notice} + + ); +} diff --git a/packages/chat/src/components/messages/__tests__/ContentRow.spec.tsx b/packages/chat/src/components/messages/__tests__/ContentRow.spec.tsx new file mode 100644 index 0000000000..9bfd2218f0 --- /dev/null +++ b/packages/chat/src/components/messages/__tests__/ContentRow.spec.tsx @@ -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 ( + + {author?.label}|{source?.partAgentId} + + ); +} + +function renderRow( + props: Partial = {}, + parts: Partial = {}, + renderContentParts = jest.fn((_props: ContentPartsSlotProps) => ( + + + + )), +) { + const partsHost = { + useShowThinking: () => true, + useAutoExpandTools: () => false, + renderContentParts, + ...parts, + } as MessagePartsHost; + const messagesHost = createMessagesHost({ + renderMessageIcon: ({ iconData }) => {iconData?.model}, + }); + render( + + + Copy to clipboard} + {...props} + /> + + , + ); + 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 = header; + 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: header, + }); + + 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:

Private prompt

, + notice:

Stopped at the tool call limit

, + }); + + 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 }), + ); + }); +}); diff --git a/packages/chat/src/components/messages/labels.ts b/packages/chat/src/components/messages/labels.ts new file mode 100644 index 0000000000..d1c0038166 --- /dev/null +++ b/packages/chat/src/components/messages/labels.ts @@ -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; + +/** 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}: `; +};