Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧩 refactor: Route Message Parts Through a @librechat/chat Part Dispatcher and Host (#16976)
Marco Berettaa30b11b4c7a2
diff --git a/.github/workflows/frontend-review.yml b/.github/workflows/frontend-review.ymlindex bcb1616407..a1075e1039 100644--- a/.github/workflows/frontend-review.yml+++ b/.github/workflows/frontend-review.yml@@ -331,6 +331,12 @@ jobs:name: build-data-providerpath: packages/data-provider/dist+ - name: Download client-package build+ uses: actions/download-artifact@v7+ with:+ name: build-client-package+ path: packages/client/dist+- name: Use Bun 1.4.3uses: oven-sh/setup-bun@v2with:diff --git a/client/src/Providers/MessageContext.tsx b/client/src/Providers/MessageContext.tsxindex c699397606..e90ebe0215 100644--- a/client/src/Providers/MessageContext.tsx+++ b/client/src/Providers/MessageContext.tsx@@ -1,16 +1 @@-import { createContext, useContext } from 'react';--type MessageContext = {- messageId: string;- nextType?: string;- partIndex?: number;- isExpanded: boolean;- conversationId?: string | null;- /** Submission state for cursor display - only true for latest message when submitting */- isSubmitting?: boolean;- /** Whether this is the latest message in the conversation */- isLatestMessage?: boolean;-};--export const MessageContext = createContext<MessageContext>({} as MessageContext);-export const useMessageContext = () => useContext(MessageContext);+export { MessageContext, useMessageContext } from '@librechat/chat/react';diff --git a/client/src/Providers/MessagePartsHostContext.tsx b/client/src/Providers/MessagePartsHostContext.tsxindex 8923c7c467..b4fe17343f 100644--- a/client/src/Providers/MessagePartsHostContext.tsx+++ b/client/src/Providers/MessagePartsHostContext.tsx@@ -1,6 +1,7 @@-import { createContext, useCallback, useContext, useMemo } from 'react';+import { useCallback, useMemo } from 'react';import { useAtomValue, useSetAtom } from 'jotai';import { useToastContext } from '@librechat/client';+import { setDefaultMessagePartsHost } from '@librechat/chat/react';import {useRecoilCallback,useRecoilState,@@ -8,7 +9,6 @@ import {useResetRecoilState,useSetRecoilState,} from 'recoil';-import type { ReactNode } from 'react';import type {MessagePartArtifactPanel,MessagePartsUserTextPreferences,@@ -90,7 +90,10 @@ function useAppLiveAppliedSteer(steerId: string): [boolean, (steerId: string) =>return [isLiveApplied, consume];}-/** The host the app's own views supply: the Recoil and Jotai stores and the app providers. */+/**+ * The host the app's own views supply: the Recoil and Jotai stores and the app providers. It is+ * registered as the default, so parts rendered outside a provider read the app's stores.+ */export const appMessagePartsHost: MessagePartsHost = {useMessage: useAppMessage,useFontSize: () => useAtomValue(fontSizeAtom),@@ -116,19 +119,6 @@ export const appMessagePartsHost: MessagePartsHost = {useLiveAppliedSteer: useAppLiveAppliedSteer,};-const MessagePartsHostContext = createContext<MessagePartsHost>(appMessagePartsHost);+setDefaultMessagePartsHost(appMessagePartsHost);-/** Supplies the host the message parts read from. Without one, parts read the app's stores. */-export function MessagePartsHostProvider({- host,- children,-}: {- host: MessagePartsHost;- children: ReactNode;-}) {- return (- <MessagePartsHostContext.Provider value={host}>{children}</MessagePartsHostContext.Provider>- );-}--export const useMessagePartsHost = () => useContext(MessagePartsHostContext);+export { MessagePartsHostProvider, useMessagePartsHost } from '@librechat/chat/react';diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsxindex d1b057d3e4..cc0d0a47b4 100644--- a/client/src/components/Chat/Messages/Content/Part.tsx+++ b/client/src/components/Chat/Messages/Content/Part.tsx@@ -1,4 +1,5 @@import { memo } from 'react';+import { Part as ChatPart } from '@librechat/chat/components';import {Tools,Constants,@@ -9,7 +10,14 @@ import {hasToolCallPreview,getToolCallPreviewRevision,} from 'librechat-data-provider';+import type {+ ToolRenderer,+ AgentToolCall,+ PartRenderers,+ ToolRenderProps,+} from '@librechat/chat/components';import type { TMessageContentParts, TAttachment, PartMetadata } from 'librechat-data-provider';+import type { ReactNode } from 'react';import {ImageGen,ExecuteCode,@@ -39,7 +47,6 @@ import AskUserQuestionCall from './AskUserQuestionCall';import { isBashProgrammaticToolCall } from './routing';import { isError } from './ToolOutput/OutputRenderer';import { ToolPreparation } from './preparation';-import { useMessageContext } from '~/Providers';import { ErrorMessage } from './MessageContent';import AskUserQuestion from './AskUserQuestion';import RetrievalCall from './RetrievalCall';@@ -58,34 +65,507 @@ const isFailedImageCall = (runStepStatus !== 'cancelled' &&(runStepStatus === 'failed' || (typeof output === 'string' && isError(output)));-type PartProps = {- part?: TMessageContentParts;- isLast?: boolean;- isSubmitting: boolean;- showCursor: boolean;- isCreatedByUser: boolean;- attachments?: TAttachment[];- hideAttachments?: boolean;- onToolExpand?: () => void;+const renderExecuteCode: ToolRenderer = ({+ toolCall,+ toolCallId,+ attachments,+ isSubmitting,+ hideAttachments,+ onToolExpand,+}) => (+ <ExecuteCode+ stepId={toolCall.stepId}+ attachments={attachments}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ backgrounded={toolCall.backgrounded}+ backgroundCancelled={toolCall.backgroundTask?.cancelled === true}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ args={toolCall.args}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ toolCallId={toolCallId}+ />+);++const renderImageGen: ToolRenderer = ({+ toolCall,+ attachments,+ isSubmitting,+ isLast,+ hideAttachments,+ onToolExpand,+}) => {+ if (isFailedImageCall(toolCall.output, toolCall.runStepStatus)) {+ return (+ <ToolCall+ stepId={toolCall.stepId}+ name={toolCall.name}+ args={toolCall.args ?? ''}+ output={toolCall.output}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ isLast={isLast}+ runStepStatus={toolCall.runStepStatus}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );+ }+ return (+ <ImageGen+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ toolName={toolCall.name}+ args={toolCall.args ?? ''}+ output={toolCall.output ?? ''}+ attachments={attachments}+ hideAttachments={hideAttachments}+ />+ );};-const Part = memo(function Part({- part,+const renderMemory =+ (toolName: 'set_memory' | 'delete_memory'): ToolRenderer =>+ ({ toolCall, attachments, isSubmitting, hideAttachments, onToolExpand }) => (+ <MemoryCall+ toolName={toolName}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );++const renderFileAuthoring =+ (toolName: 'create_file' | 'edit_file'): ToolRenderer =>+ ({ toolCall, attachments, isSubmitting, hideAttachments, onToolExpand }) => (+ <FileAuthoringCall+ toolName={toolName}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );++const renderRetrieval: ToolRenderer = ({ toolCall, attachments, isSubmitting, onToolExpand }) => (+ <RetrievalCall+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ args={toolCall.args}+ output={toolCall.output ?? undefined}+ attachments={attachments}+ onExpand={onToolExpand}+ />+);++const renderBashProgrammatic: ToolRenderer = ({+ toolCall,+ toolCallId,+ attachments,isSubmitting,+ hideAttachments,+ onToolExpand,+}) => (+ <BashCall+ stepId={toolCall.stepId}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ backgrounded={toolCall.backgrounded}+ backgroundCancelled={toolCall.backgroundTask?.cancelled === true}+ attachments={attachments}+ commandField="code"+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ toolCallId={toolCallId}+ />+);++const renderHandoff: ToolRenderer = ({ toolCall }) => (+ <AgentHandoff args={toolCall.args ?? ''} name={toolCall.name || ''} />+);++/** Agent tool cards by tool name; any other name draws the generic card. */+const tools: Record<string, ToolRenderer> = {+ [Tools.execute_code]: renderExecuteCode,+ [Constants.PROGRAMMATIC_TOOL_CALLING]: renderExecuteCode,+ [Constants.BASH_PROGRAMMATIC_TOOL_CALLING]: renderExecuteCode,+ image_gen_oai: renderImageGen,+ image_edit_oai: renderImageGen,+ gemini_image_gen: renderImageGen,+ /** Dedicated Q&A record: the generic tool card would label the+ * interrupt-resolved call "cancelled" and dump raw JSON args. */+ ask_user_question: ({ toolCall, isSubmitting, showCursor, onToolExpand }) => (+ <AskUserQuestionCall+ args={toolCall.args}+ output={typeof toolCall.output === 'string' ? toolCall.output : ''}+ toolCallId={toolCall.id}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ showCursor={showCursor}+ failed={'inputValidationError' in toolCall && toolCall.inputValidationError === true}+ onExpand={onToolExpand}+ />+ ),+ [Constants.CHECK_BACKGROUND_TASK]: ({+ toolCall,+ toolCallId,+ attachments,+ isSubmitting,+ hideAttachments,+ onToolExpand,+ }) => (+ <BackgroundTaskCall+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ toolCallId={toolCallId}+ />+ ),+ skill: ({ toolCall, attachments, isSubmitting, hideAttachments, onToolExpand }) => (+ <SkillCall+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ ),+ [Constants.SUBAGENT]: ({ part, toolCall, attachments, isSubmitting, hideAttachments }) => {+ /** `subagent_content` is the aggregated content-parts array the+ * backend writes onto the tool_call at message-save time so the+ * child's activity survives a page refresh. Not present on older+ * runs recorded before the persistence path existed; those fall+ * back to the Recoil atom (live session) or the raw tool output+ * inside `SubagentCall`. */+ const persistedContent = (+ toolCall as unknown as {+ subagent_content?: TMessageContentParts[];+ }+ ).subagent_content;+ return (+ <SubagentCall+ toolCallId={toolCall.id ?? ''}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ attachments={attachments}+ persistedContent={persistedContent}+ contentPreview={+ hasToolCallPreview(toolCall)+ ? {+ revision: getToolCallPreviewRevision(toolCall),+ stepId: toolCall.stepId,+ agentId: part.agentId,+ }+ : undefined+ }+ subagentIdentity={toolCall.subagentIdentity}+ hideAttachments={hideAttachments}+ />+ );+ },+ set_memory: renderMemory('set_memory'),+ delete_memory: renderMemory('delete_memory'),+ read_file: ({+ toolCall,+ toolCallId,+ attachments,+ isSubmitting,+ hideAttachments,+ onToolExpand,+ }) => (+ <ReadFileCall+ toolCallId={toolCallId}+ stepId={toolCall.stepId}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ ),+ create_file: renderFileAuthoring('create_file'),+ edit_file: renderFileAuthoring('edit_file'),+ [Tools.bash_tool]: ({+ toolCall,+ toolCallId,+ attachments,+ isSubmitting,+ hideAttachments,+ onToolExpand,+ }) => (+ <BashCall+ stepId={toolCall.stepId}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ backgrounded={toolCall.backgrounded}+ backgroundCancelled={toolCall.backgroundTask?.cancelled === true}+ executor={toolCall.executor}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ toolCallId={toolCallId}+ />+ ),+ [Tools.web_search]: ({+ toolCall,+ attachments,+ isSubmitting,+ isLast,+ hideAttachments,+ onToolExpand,+ }) => (+ <WebSearch+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ attachments={attachments}+ hideAttachments={hideAttachments}+ isLast={isLast}+ onExpand={onToolExpand}+ />+ ),+ file_search: renderRetrieval,+ retrieval: renderRetrieval,+};++const renderDefaultTool: ToolRenderer = ({+ toolCall,+ toolCallId,attachments,+ isSubmitting,+ isLast,+ hideAttachments,+ onToolExpand,+}) => (+ <ToolCall+ stepId={toolCall.stepId}+ args={toolCall.args ?? ''}+ name={toolCall.name || ''}+ toolCallId={toolCallId}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ attachments={attachments}+ auth={toolCall.auth}+ isLast={isLast}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ runStepStatus={+ toolCall.backgroundTask?.cancelled === true ? 'cancelled' : toolCall.runStepStatus+ }+ runStepDurationMs={toolCall.runStepDurationMs}+ toolPreparationStartedAt={toolCall.toolPreparationStartedAt}+ toolDispatchedAt={toolCall.toolDispatchedAt}+ toolPreparationDurationMs={toolCall.toolPreparationDurationMs}+ toolExecutionDurationMs={toolCall.toolExecutionDurationMs}+ />+);++/** Calls a name alone cannot route: programmatic bash by its arguments, handoffs by prefix. */+const matchTool = ({ name, args }: AgentToolCall): ToolRenderer | undefined => {+ if (isBashProgrammaticToolCall(name, args)) {+ return renderBashProgrammatic;+ }+ if (name?.startsWith(Constants.LC_TRANSFER_TO_)) {+ return renderHandoff;+ }+ return undefined;+};++/**+ * Render approval controls for ANY paused agent tool, not just the generic+ * card, so a HITL policy that gates a specialized tool (bash, code, file…)+ * still surfaces approve/reject/edit/respond. Only while the call is unresolved+ * (no output yet).+ */+const wrapTool = (card: ReactNode, { toolCall, isSubmitting }: ToolRenderProps) => {+ const preparedCard = (+ <ToolPreparation call={toolCall} isSubmitting={isSubmitting}>+ {card}+ </ToolPreparation>+ );+ if (toolCall.approval != null && (toolCall.output?.length ?? 0) === 0) {+ return (+ <>+ {preparedCard}+ <ToolApproval+ approval={toolCall.approval}+ toolCallId={toolCall.id ?? ''}+ args={toolCall.args}+ />+ </>+ );+ }+ return preparedCard;+};++/** The Assistants tool call shapes: code interpreter, retrieval, and function calls. */+const renderAssistantsToolCall: PartRenderers['parts'][ContentTypes.TOOL_CALL] = ({+ part,+ attachments,+ isSubmitting,isLast,showCursor,isCreatedByUser,hideAttachments,onToolExpand,-}: PartProps) {- const { partIndex } = useMessageContext();- if (!part) {- return null;+}) => {+ const toolCall = part[ContentTypes.TOOL_CALL];+ if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {+ const code_interpreter = toolCall[ToolCallTypes.CODE_INTERPRETER];+ return (+ <CodeAnalyze+ initialProgress={toolCall.progress ?? 0.1}+ code={code_interpreter.input}+ outputs={code_interpreter.outputs ?? []}+ onExpand={onToolExpand}+ />+ );+ } else if (+ toolCall.type === ToolCallTypes.RETRIEVAL ||+ toolCall.type === ToolCallTypes.FILE_SEARCH+ ) {+ return (+ <RetrievalCall+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ output={(toolCall as { output?: string }).output}+ attachments={attachments}+ onExpand={onToolExpand}+ />+ );+ } else if (+ toolCall.type === ToolCallTypes.FUNCTION &&+ ToolCallTypes.FUNCTION in toolCall &&+ imageGenTools.has(toolCall.function.name)+ ) {+ if (isFailedImageCall(toolCall.function.output, toolCall.runStepStatus)) {+ return (+ <ToolCall+ name={toolCall.function.name}+ args={toolCall.function.arguments as string}+ output={toolCall.function.output}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ isLast={isLast}+ runStepStatus={toolCall.runStepStatus}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );+ }+ return (+ <ToolPreparation+ call={{+ args: toolCall.function.arguments as string,+ name: toolCall.function.name,+ output: toolCall.function.output,+ progress: toolCall.progress,+ runStepStatus: toolCall.runStepStatus,+ toolPreparationStartedAt: toolCall.toolPreparationStartedAt,+ toolDispatchedAt: toolCall.toolDispatchedAt,+ }}+ isSubmitting={isSubmitting}+ >+ <ImageGen+ initialProgress={toolCall.progress ?? 0.1}+ args={toolCall.function.arguments as string}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ toolName={toolCall.function.name}+ output={toolCall.function.output ?? ''}+ />+ </ToolPreparation>+ );+ } else if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {+ if (isImageVisionTool(toolCall)) {+ if (isSubmitting && showCursor) {+ return (+ <Container>+ <Text text={''} isCreatedByUser={isCreatedByUser} showCursor={showCursor} />+ </Container>+ );+ }+ return null;+ }++ return (+ <ToolCall+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ args={toolCall.function.arguments as string}+ name={toolCall.function.name}+ output={toolCall.function.output}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ toolPreparationStartedAt={toolCall.toolPreparationStartedAt}+ toolDispatchedAt={toolCall.toolDispatchedAt}+ toolPreparationDurationMs={toolCall.toolPreparationDurationMs}+ toolExecutionDurationMs={toolCall.toolExecutionDurationMs}+ isLast={isLast}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );}+ return null;+};- const askUserQuestion = getAskUserQuestionPart(part);- if (askUserQuestion) {+/** The app's part renderers: every visual the package `Part` routes to. */+const renderers: PartRenderers = {+ claim: ({ part }) => {+ const askUserQuestion = getAskUserQuestionPart(part);+ if (!askUserQuestion) {+ return undefined;+ }return (<AskUserQuestionkey={askUserQuestion.ask_user_question.actionId}@@ -94,10 +574,9 @@ const Part = memo(function Part({questions={askUserQuestion.ask_user_question.questions}/>);- }-- if (part.type === ContentTypes.STEER) {- return (+ },+ parts: {+ [ContentTypes.STEER]: ({ part, isSubmitting }) => (<SteerPartsteer={part[ContentTypes.STEER]}files={part.files}@@ -106,11 +585,8 @@ const Part = memo(function Part({createdAt={part.createdAt}isSubmitting={isSubmitting}/>- );- }-- if (part.type === ContentTypes.ERROR) {- return (+ ),+ [ContentTypes.ERROR]: ({ part }) => (<ErrorMessagetext={part[ContentTypes.ERROR] ??@@ -121,9 +597,8 @@ const Part = memo(function Part({}className="my-2"/>- );- } else if (part.type === ContentTypes.AGENT_UPDATE) {- return (+ ),+ [ContentTypes.AGENT_UPDATE]: ({ part, isLast, showCursor }) => (<><AgentUpdate currentAgentId={part[ContentTypes.AGENT_UPDATE]?.agentId} />{isLast && showCursor && (@@ -132,54 +607,55 @@ const Part = memo(function Part({</Container>)}</>- );- } else if (part.type === ContentTypes.TEXT) {- const text = typeof part.text === 'string' ? part.text : part.text?.value;+ ),+ [ContentTypes.TEXT]: ({ part, isLast, showCursor, isCreatedByUser }) => {+ const text = typeof part.text === 'string' ? part.text : part.text?.value;- if (typeof text !== 'string') {- return null;- }- if (part.tool_call_ids != null && !text) {- return null;- }- /** Handle whitespace-only text to avoid layout shift */- if (text.length > 0 && /^\s*$/.test(text)) {- /** Show placeholder for whitespace-only last part during streaming */- if (isLast && showCursor) {- return (- <Container>- <EmptyText />- </Container>- );+ if (typeof text !== 'string') {+ return null;}- /** Skip rendering non-last whitespace-only parts to avoid empty Container */- if (!isLast) {+ if (part.tool_call_ids != null && !text) {return null;}- }- return (- <Container>- <Text text={text} isCreatedByUser={isCreatedByUser} showCursor={showCursor} />- </Container>- );- } else if (part.type === ContentTypes.THINK) {- const reasoning = typeof part.think === 'string' ? part.think : part.think?.value;- if (typeof reasoning !== 'string') {- return null;- }- if (reasoning.trim() === '' && part.reasoning_unavailable === true) {- return <ReasoningMarker label={part.reasoning_label} />;- }- return (- <Reasoning- partKeyIndex={getPartKeyIndex(part, partIndex ?? 0)}- reasoning={reasoning}- isLast={isLast ?? false}- reasoningLabel={part.reasoning_label}- />- );- } else if (part.type === ContentTypes.SUMMARY) {- return (+ /** Handle whitespace-only text to avoid layout shift */+ if (text.length > 0 && /^\s*$/.test(text)) {+ /** Show placeholder for whitespace-only last part during streaming */+ if (isLast && showCursor) {+ return (+ <Container>+ <EmptyText />+ </Container>+ );+ }+ /** Skip rendering non-last whitespace-only parts to avoid empty Container */+ if (!isLast) {+ return null;+ }+ }+ return (+ <Container>+ <Text text={text} isCreatedByUser={isCreatedByUser} showCursor={showCursor} />+ </Container>+ );+ },+ [ContentTypes.THINK]: ({ part, partIndex, isLast }) => {+ const reasoning = typeof part.think === 'string' ? part.think : part.think?.value;+ if (typeof reasoning !== 'string') {+ return null;+ }+ if (reasoning.trim() === '' && part.reasoning_unavailable === true) {+ return <ReasoningMarker label={part.reasoning_label} />;+ }+ return (+ <Reasoning+ partKeyIndex={getPartKeyIndex(part, partIndex ?? 0)}+ reasoning={reasoning}+ isLast={isLast ?? false}+ reasoningLabel={part.reasoning_label}+ />+ );+ },+ [ContentTypes.SUMMARY]: ({ part }) => (<Summarycontent={part.content}model={part.model}@@ -189,448 +665,59 @@ const Part = memo(function Part({summarizing={part.summarizing}failed={part.failed}/>- );- } else if (part.type === ContentTypes.ACTIVITY_LABEL) {+ ),/** Orphan label (its block's parts were filtered/hidden): renders as a* standalone line. Labeled blocks normally render via ToolCallGroup,* which consumes the label part as the group header instead. */- const display = getActivityLabelText(getActivityLabelPart(part));- if (!display) {- return null;- }- const failed = part.status === 'failed' || part.status === 'partial';- return (- <div- className={`my-1 pl-1 text-sm break-words italic ${failed ? 'text-text-warning' : 'text-text-secondary'}`}- >- {display}- </div>- );- } else if (part.type === ContentTypes.TOOL_CALL) {- const toolCall = part[ContentTypes.TOOL_CALL];-- if (!toolCall) {- return null;- }-- const isToolCall =- 'args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);- if (isToolCall) {- const toolCallId =- 'id' in toolCall && typeof toolCall.id === 'string' ? toolCall.id : undefined;- const card = (() => {- if (isBashProgrammaticToolCall(toolCall.name, toolCall.args)) {- return (- <BashCall- stepId={toolCall.stepId}- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- backgrounded={toolCall.backgrounded}- backgroundCancelled={toolCall.backgroundTask?.cancelled === true}- attachments={attachments}- commandField="code"- hideAttachments={hideAttachments}- onExpand={onToolExpand}- toolCallId={toolCallId}- />- );- } else if (- toolCall.name === Tools.execute_code ||- toolCall.name === Constants.PROGRAMMATIC_TOOL_CALLING ||- toolCall.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING- ) {- return (- <ExecuteCode- stepId={toolCall.stepId}- attachments={attachments}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- backgrounded={toolCall.backgrounded}- backgroundCancelled={toolCall.backgroundTask?.cancelled === true}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- args={toolCall.args}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- toolCallId={toolCallId}- />- );- } else if (- toolCall.name === 'image_gen_oai' ||- toolCall.name === 'image_edit_oai' ||- toolCall.name === 'gemini_image_gen'- ) {- if (isFailedImageCall(toolCall.output, toolCall.runStepStatus)) {- return (- <ToolCall- stepId={toolCall.stepId}- name={toolCall.name}- args={toolCall.args ?? ''}- output={toolCall.output}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- isLast={isLast}- runStepStatus={toolCall.runStepStatus}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- />- );- }- return (- <ImageGen- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- toolName={toolCall.name}- args={toolCall.args ?? ''}- output={toolCall.output ?? ''}- attachments={attachments}- hideAttachments={hideAttachments}- />- );- } else if (toolCall.name === 'ask_user_question') {- /** Dedicated Q&A record — the generic tool card would label the- * interrupt-resolved call "cancelled" and dump raw JSON args. */- return (- <AskUserQuestionCall- args={toolCall.args}- output={typeof toolCall.output === 'string' ? toolCall.output : ''}- toolCallId={toolCall.id}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- showCursor={showCursor}- failed={'inputValidationError' in toolCall && toolCall.inputValidationError === true}- onExpand={onToolExpand}- />- );- } else if (toolCall.name === Constants.CHECK_BACKGROUND_TASK) {- return (- <BackgroundTaskCall- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- toolCallId={toolCallId}- />- );- } else if (toolCall.name === 'skill') {- return (- <SkillCall- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- />- );- } else if (toolCall.name === Constants.SUBAGENT) {- /** `subagent_content` is the aggregated content-parts array the- * backend writes onto the tool_call at message-save time so the- * child's activity survives a page refresh. Not present on older- * runs recorded before the persistence path existed — those fall- * back to the Recoil atom (live session) or the raw tool output- * inside `SubagentCall`. */- const persistedContent = (- toolCall as unknown as {- subagent_content?: TMessageContentParts[];- }- ).subagent_content;- return (- <SubagentCall- toolCallId={toolCall.id ?? ''}- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- attachments={attachments}- persistedContent={persistedContent}- contentPreview={- hasToolCallPreview(toolCall)- ? {- revision: getToolCallPreviewRevision(toolCall),- stepId: toolCall.stepId,- agentId: part.agentId,- }- : undefined- }- subagentIdentity={toolCall.subagentIdentity}- hideAttachments={hideAttachments}- />- );- } else if (toolCall.name === 'set_memory' || toolCall.name === 'delete_memory') {- return (- <MemoryCall- toolName={toolCall.name}- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- />- );- } else if (toolCall.name === 'read_file') {- return (- <ReadFileCall- toolCallId={toolCallId}- stepId={toolCall.stepId}- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- />- );- } else if (toolCall.name === 'create_file' || toolCall.name === 'edit_file') {- return (- <FileAuthoringCall- toolName={toolCall.name}- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- />- );- } else if (toolCall.name === Tools.bash_tool) {- return (- <BashCall- stepId={toolCall.stepId}- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- backgrounded={toolCall.backgrounded}- backgroundCancelled={toolCall.backgroundTask?.cancelled === true}- executor={toolCall.executor}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- toolCallId={toolCallId}- />- );- } else if (toolCall.name === Tools.web_search) {- return (- <WebSearch- args={toolCall.args}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- attachments={attachments}- hideAttachments={hideAttachments}- isLast={isLast}- onExpand={onToolExpand}- />- );- } else if (toolCall.name === 'file_search' || toolCall.name === 'retrieval') {- return (- <RetrievalCall- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- args={toolCall.args}- output={toolCall.output ?? undefined}- attachments={attachments}- onExpand={onToolExpand}- />- );- } else if (toolCall.name?.startsWith(Constants.LC_TRANSFER_TO_)) {- return <AgentHandoff args={toolCall.args ?? ''} name={toolCall.name || ''} />;- }- return (- <ToolCall- stepId={toolCall.stepId}- args={toolCall.args ?? ''}- name={toolCall.name || ''}- toolCallId={toolCallId}- output={toolCall.output ?? ''}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- attachments={attachments}- auth={toolCall.auth}- isLast={isLast}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- runStepStatus={- toolCall.backgroundTask?.cancelled === true ? 'cancelled' : toolCall.runStepStatus- }- runStepDurationMs={toolCall.runStepDurationMs}- toolPreparationStartedAt={toolCall.toolPreparationStartedAt}- toolDispatchedAt={toolCall.toolDispatchedAt}- toolPreparationDurationMs={toolCall.toolPreparationDurationMs}- toolExecutionDurationMs={toolCall.toolExecutionDurationMs}- />- );- })();- const preparedCard = (- <ToolPreparation call={toolCall} isSubmitting={isSubmitting}>- {card}- </ToolPreparation>- );-- /** Render approval controls for ANY paused agent tool — not just the generic- * card — so a HITL policy that gates a specialized tool (bash, code, file…)- * still surfaces approve/reject/edit/respond. Only while the call is unresolved- * (no output yet). */- if (toolCall.approval != null && (toolCall.output?.length ?? 0) === 0) {- return (- <>- {preparedCard}- <ToolApproval- approval={toolCall.approval}- toolCallId={toolCall.id ?? ''}- args={toolCall.args}- />- </>- );- }- return preparedCard;- } else if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {- const code_interpreter = toolCall[ToolCallTypes.CODE_INTERPRETER];- return (- <CodeAnalyze- initialProgress={toolCall.progress ?? 0.1}- code={code_interpreter.input}- outputs={code_interpreter.outputs ?? []}- onExpand={onToolExpand}- />- );- } else if (- toolCall.type === ToolCallTypes.RETRIEVAL ||- toolCall.type === ToolCallTypes.FILE_SEARCH- ) {- return (- <RetrievalCall- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- output={(toolCall as { output?: string }).output}- attachments={attachments}- onExpand={onToolExpand}- />- );- } else if (- toolCall.type === ToolCallTypes.FUNCTION &&- ToolCallTypes.FUNCTION in toolCall &&- imageGenTools.has(toolCall.function.name)- ) {- if (isFailedImageCall(toolCall.function.output, toolCall.runStepStatus)) {- return (- <ToolCall- name={toolCall.function.name}- args={toolCall.function.arguments as string}- output={toolCall.function.output}- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- isLast={isLast}- runStepStatus={toolCall.runStepStatus}- attachments={attachments}- hideAttachments={hideAttachments}- onExpand={onToolExpand}- />- );+ [ContentTypes.ACTIVITY_LABEL]: ({ part }) => {+ const display = getActivityLabelText(getActivityLabelPart(part));+ if (!display) {+ return null;}+ const failed = part.status === 'failed' || part.status === 'partial';return (- <ToolPreparation- call={{- args: toolCall.function.arguments as string,- name: toolCall.function.name,- output: toolCall.function.output,- progress: toolCall.progress,- runStepStatus: toolCall.runStepStatus,- toolPreparationStartedAt: toolCall.toolPreparationStartedAt,- toolDispatchedAt: toolCall.toolDispatchedAt,- }}- isSubmitting={isSubmitting}+ <div+ className={`my-1 pl-1 text-sm break-words italic ${failed ? 'text-text-warning' : 'text-text-secondary'}`}>- <ImageGen- initialProgress={toolCall.progress ?? 0.1}- args={toolCall.function.arguments as string}- isSubmitting={isSubmitting}- runStepStatus={toolCall.runStepStatus}- toolName={toolCall.function.name}- output={toolCall.function.output ?? ''}- />- </ToolPreparation>+ {display}+ </div>);- } else if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {- if (isImageVisionTool(toolCall)) {- if (isSubmitting && showCursor) {- return (- <Container>- <Text text={''} isCreatedByUser={isCreatedByUser} showCursor={showCursor} />- </Container>- );- }- return null;- }-+ },+ [ContentTypes.TOOL_CALL]: renderAssistantsToolCall,+ [ContentTypes.IMAGE_FILE]: ({ part, isCreatedByUser }) => {+ const imageFile = part[ContentTypes.IMAGE_FILE];+ const cached = imageFile.file_id ? getCachedPreview(imageFile.file_id) : undefined;return (- <ToolCall- initialProgress={toolCall.progress ?? 0.1}- isSubmitting={isSubmitting}- args={toolCall.function.arguments as string}- name={toolCall.function.name}- output={toolCall.function.output}- runStepStatus={toolCall.runStepStatus}- runStepDurationMs={toolCall.runStepDurationMs}- toolPreparationStartedAt={toolCall.toolPreparationStartedAt}- toolDispatchedAt={toolCall.toolDispatchedAt}- toolPreparationDurationMs={toolCall.toolPreparationDurationMs}- toolExecutionDurationMs={toolCall.toolExecutionDurationMs}- isLast={isLast}- hideAttachments={hideAttachments}- onExpand={onToolExpand}+ <Image+ imagePath={cached ?? imageFile.filepath}+ altText={imageFile.filename ?? 'Uploaded Image'}+ alignRight={isCreatedByUser}+ width={imageFile.width}+ height={imageFile.height}/>);- }- } else if (part.type === ContentTypes.IMAGE_FILE) {- const imageFile = part[ContentTypes.IMAGE_FILE];- const cached = imageFile.file_id ? getCachedPreview(imageFile.file_id) : undefined;- return (- <Image- imagePath={cached ?? imageFile.filepath}- altText={imageFile.filename ?? 'Uploaded Image'}- alignRight={isCreatedByUser}- width={imageFile.width}- height={imageFile.height}- />- );- }+ },+ },+ tools,+ matchTool,+ defaultTool: renderDefaultTool,+ wrapTool,+};- return null;+type PartProps = {+ part?: TMessageContentParts;+ isLast?: boolean;+ isSubmitting: boolean;+ showCursor: boolean;+ isCreatedByUser: boolean;+ attachments?: TAttachment[];+ hideAttachments?: boolean;+ onToolExpand?: () => void;+};++/** One content part, drawn with the app's renderers. */+const Part = memo(function Part(props: PartProps) {+ return <ChatPart {...props} renderers={renderers} />;});Part.displayName = 'Part';diff --git a/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsxnew file mode 100644index 0000000000..762cfde5cb--- /dev/null+++ b/client/src/components/Chat/Messages/Content/__tests__/Part.registry.test.tsx@@ -0,0 +1,191 @@+import React from 'react';+import { render } from '@testing-library/react';+import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';+import type { TMessageContentParts } from 'librechat-data-provider';+import Part from '../Part';++function mockStub(testId: string) {+ return function Stub() {+ return <div data-testid={testId} />;+ };+}++function mockPassthrough({ children }: { children?: React.ReactNode }) {+ return <>{children}</>;+}++jest.mock('../Parts', () => ({+ ImageGen: mockStub('image-gen'),+ ExecuteCode: mockStub('execute-code'),+ AgentUpdate: mockStub('agent-update'),+ EmptyText: mockStub('empty-text'),+ Reasoning: mockStub('reasoning'),+ ReasoningMarker: mockStub('reasoning-marker'),+ Summary: mockStub('summary'),+ Text: mockStub('text'),+ SkillCall: mockStub('skill-call'),+ MemoryCall: mockStub('memory-call'),+ ReadFileCall: mockStub('read-file-call'),+ FileAuthoringCall: mockStub('file-authoring-call'),+ BashCall: mockStub('bash-call'),+ SubagentCall: mockStub('subagent-call'),+ SteerPart: mockStub('steer-part'),+}));+jest.mock('../Parts/BackgroundTaskCall', () => ({+ __esModule: true,+ default: mockStub('background-task-call'),+}));+jest.mock('../MessageContent', () => ({ ErrorMessage: mockStub('error-message') }));+jest.mock('../AskUserQuestionCall', () => ({+ __esModule: true,+ default: mockStub('ask-user-question-call'),+}));+jest.mock('../AskUserQuestion', () => ({+ __esModule: true,+ default: mockStub('ask-user-question'),+}));+jest.mock('../RetrievalCall', () => ({ __esModule: true, default: mockStub('retrieval-call') }));+jest.mock('../ToolApproval', () => ({ __esModule: true, default: mockStub('tool-approval') }));+jest.mock('../AgentHandoff', () => ({ __esModule: true, default: mockStub('agent-handoff') }));+jest.mock('../CodeAnalyze', () => ({ __esModule: true, default: mockStub('code-analyze') }));+jest.mock('../WebSearch', () => ({ __esModule: true, default: mockStub('web-search') }));+jest.mock('../ToolCall', () => ({ __esModule: true, default: mockStub('tool-call') }));+jest.mock('../Image', () => ({ __esModule: true, default: mockStub('image') }));+jest.mock('../Container', () => ({ __esModule: true, default: mockPassthrough }));+jest.mock('../preparation', () => ({ ToolPreparation: mockPassthrough }));++/** What `Part` drew: the stubbed component's test id, or the text of an inline element. */+const drawn = (part: TMessageContentParts): string | null => {+ const { container, unmount } = render(+ <Part part={part} isSubmitting={false} showCursor={false} isCreatedByUser={false} />,+ );+ const element = container.firstElementChild;+ const result = element?.getAttribute('data-testid') ?? element?.textContent ?? null;+ unmount();+ return result;+};++const asPart = (part: Record<string, unknown>) => part as unknown as TMessageContentParts;++const agentCall = (name: string, args = '{}') =>+ asPart({+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: { id: 'call_1', name, args, output: 'done', progress: 1 },+ });++const assistantsCall = (toolCall: Record<string, unknown>) =>+ asPart({ type: ContentTypes.TOOL_CALL, [ContentTypes.TOOL_CALL]: { progress: 1, ...toolCall } });++const INHERITED = ['constructor', '__proto__', 'toString', 'hasOwnProperty'];++/** Every branch of the switch `Part` replaced, with the component that branch drew. */+const PART_TYPES: [string, TMessageContentParts, string | null][] = [+ ['steer', asPart({ type: ContentTypes.STEER, [ContentTypes.STEER]: 'go' }), 'steer-part'],+ ['error', asPart({ type: ContentTypes.ERROR, [ContentTypes.ERROR]: 'bad' }), 'error-message'],+ [+ 'agent update',+ asPart({ type: ContentTypes.AGENT_UPDATE, [ContentTypes.AGENT_UPDATE]: { agentId: 'a' } }),+ 'agent-update',+ ],+ ['text', asPart({ type: ContentTypes.TEXT, text: 'hello' }), 'text'],+ ['text without a string', asPart({ type: ContentTypes.TEXT }), null],+ ['reasoning', asPart({ type: ContentTypes.THINK, think: 'hmm' }), 'reasoning'],+ [+ 'unavailable reasoning',+ asPart({ type: ContentTypes.THINK, think: '', reasoning_unavailable: true }),+ 'reasoning-marker',+ ],+ ['summary', asPart({ type: ContentTypes.SUMMARY, content: [] }), 'summary'],+ [+ 'activity label',+ asPart({ type: ContentTypes.ACTIVITY_LABEL, [ContentTypes.ACTIVITY_LABEL]: 'Searched' }),+ 'Searched',+ ],+ ['empty activity label', asPart({ type: ContentTypes.ACTIVITY_LABEL }), null],+ [+ 'image file',+ asPart({ type: ContentTypes.IMAGE_FILE, [ContentTypes.IMAGE_FILE]: { filepath: '/a.png' } }),+ 'image',+ ],+ [+ 'ask user question',+ asPart({+ type: 'ask_user_question',+ ask_user_question: { actionId: 'action-1', question: 'Which?' },+ }),+ 'ask-user-question',+ ],+ [+ 'code interpreter call',+ assistantsCall({+ type: ToolCallTypes.CODE_INTERPRETER,+ [ToolCallTypes.CODE_INTERPRETER]: { input: '', outputs: [] },+ }),+ 'code-analyze',+ ],+ ['retrieval call', assistantsCall({ type: ToolCallTypes.RETRIEVAL }), 'retrieval-call'],+ ['file search call', assistantsCall({ type: ToolCallTypes.FILE_SEARCH }), 'retrieval-call'],+ [+ 'image function call',+ assistantsCall({+ type: ToolCallTypes.FUNCTION,+ function: { name: 'dalle', arguments: '{}', output: 'ok' },+ }),+ 'image-gen',+ ],+ [+ 'function call',+ assistantsCall({+ type: ToolCallTypes.FUNCTION,+ function: { name: 'lookup', arguments: '{}', output: 'ok' },+ }),+ 'tool-call',+ ],+ ['unknown type', asPart({ type: 'not_a_part' }), null],+ ...INHERITED.map((type): [string, TMessageContentParts, null] => [+ `inherited ${type}`,+ asPart({ type }),+ null,+ ]),+];++/** Every agent tool name the switch named, with the card it drew. */+const TOOL_NAMES: [string, string, string][] = [+ [Tools.execute_code, '{}', 'execute-code'],+ [+ Constants.PROGRAMMATIC_TOOL_CALLING as string,+ '{"lang":"py","code":"print(1)"}',+ 'execute-code',+ ],+ [Constants.PROGRAMMATIC_TOOL_CALLING as string, '{"code":"echo hi"}', 'bash-call'],+ [Constants.BASH_PROGRAMMATIC_TOOL_CALLING as string, '{"code":"echo hi"}', 'bash-call'],+ ['image_gen_oai', '{}', 'image-gen'],+ ['image_edit_oai', '{}', 'image-gen'],+ ['gemini_image_gen', '{}', 'image-gen'],+ ['ask_user_question', '{}', 'ask-user-question-call'],+ [Constants.CHECK_BACKGROUND_TASK as string, '{}', 'background-task-call'],+ ['skill', '{}', 'skill-call'],+ [Constants.SUBAGENT as string, '{}', 'subagent-call'],+ ['set_memory', '{}', 'memory-call'],+ ['delete_memory', '{}', 'memory-call'],+ ['read_file', '{}', 'read-file-call'],+ ['create_file', '{}', 'file-authoring-call'],+ ['edit_file', '{}', 'file-authoring-call'],+ [Tools.bash_tool, '{}', 'bash-call'],+ [Tools.web_search, '{}', 'web-search'],+ ['file_search', '{}', 'retrieval-call'],+ ['retrieval', '{}', 'retrieval-call'],+ [`${Constants.LC_TRANSFER_TO_}research`, '{}', 'agent-handoff'],+ ['some_mcp_tool', '{}', 'tool-call'],+ ...INHERITED.map((name): [string, string, string] => [name, '{}', 'tool-call']),+];++describe('Part registry parity with the replaced switch', () => {+ it.each(PART_TYPES)('routes the %s part to the same component', (_label, part, expected) => {+ expect(drawn(part)).toBe(expected);+ });++ it.each(TOOL_NAMES)('routes a %s call with args %s to the same card', (name, args, expected) => {+ expect(drawn(agentCall(name, args))).toBe(expected);+ });+});diff --git a/client/src/hooks/Chat/contract.ts b/client/src/hooks/Chat/contract.tsindex 5fa7ede1d7..e71f0a9053 100644--- a/client/src/hooks/Chat/contract.ts+++ b/client/src/hooks/Chat/contract.ts@@ -1,5 +1,4 @@import type {- TFile,TUser,TPreset,TMessage,@@ -11,7 +10,6 @@ import type {ChatTransportRequest,} from 'librechat-data-provider';import type { SetStateAction, Dispatch, MouseEvent } from 'react';-import type { TShowToast } from '@librechat/client';import type {ArmSteerParams,ArmSteerResponse,@@ -278,33 +276,13 @@ export interface Transport {}) => Promise<AgentQueuedTurnReceipt>;}-/** The message a part renders in, as its host reports it. */-export type MessagePartMessage = {- /** Id of the message that owns the part, or `''` outside a message. */- messageId: string;- /** Whether that message is still generating. */- isSubmitting?: boolean;- /** Whether that message is the tail of the active branch. */- isLatestMessage?: boolean;- /** Content type of the part after this one, when known. */- nextType?: string;-};--/** How the viewer prefers user-authored text to display. */-export type MessagePartsUserTextPreferences = {- /** Whether user-authored text renders as markdown. */- enableUserMsgMarkdown: boolean;- /** Whether long user-authored text collapses behind a toggle. */- collapseLongUserMessages: boolean;- /** Whether user turns are labeled with the user's name. */- usernameDisplay: boolean;-};--/** The signed-in user as the parts label it; `undefined` on a public share. */-export type MessagePartsUser = { name?: string; username?: string } | undefined;--/** Shows a transient notification. */-export type MessagePartsToast = (toast: TShowToast) => void;+export type {+ MessagePartsHost,+ MessagePartsUser,+ MessagePartsToast,+ MessagePartMessage,+ MessagePartsUserTextPreferences,+} from '@librechat/chat/react';/** The artifact panel as one tool artifact card drives it. */export type MessagePartArtifactPanel = {@@ -325,52 +303,14 @@ export type MessagePartArtifactPanel = {consumeJustResolved: (messageId: string, fileId: string) => boolean;};-/**- * Everything the message part components read from the app, supplied by the view that renders- * them through `MessagePartsHostProvider`. Members are hooks, called unconditionally by the parts- * that need them, so keyed reads subscribe to one key only. A host must stay the same object for- * the life of the tree it wraps. Setters are typed as React dispatchers, so the contract names no- * state library.- */-export type MessagePartsHost = {- /** The message the calling part renders in. */- useMessage: () => MessagePartMessage;- /** The viewer's font size utility, applied to reasoning and summary text. */- useFontSize: () => string;- /** Whether the viewer wants reasoning expanded by default. */- useShowThinking: () => boolean;- /** Whether the viewer wants tool cards and tool groups expanded by default. */- useAutoExpandTools: () => boolean;- /** How the viewer prefers user-authored text to display. */- useUserTextPreferences: () => MessagePartsUserTextPreferences;- /** The signed-in user. */- useUser: () => MessagePartsUser;- /** The user's uploaded files keyed by file id, used to hydrate attachment metadata. */- useFileMap: () => Record<string, TFile> | undefined;- /** The notification function. */- useToast: () => MessagePartsToast;- /** Whether the sandbox for a code tool call is still starting. */- useSandboxStarting: (toolCallId: string) => boolean;- /** Live inner-call trace of one programmatic tool call in one message. */- usePtcTrace: (messageId: string, toolCallId: string) => PtcTrace;- /**- * Which mounted card owns the row for a tool artifact, so one file renders once across tool- * calls and messages. The key is the artifact id.- */- useToolArtifactClaim: (- artifactId: string,- ) => [string | null, Dispatch<SetStateAction<string | null>>];- /** The artifact panel, scoped to one artifact. */- useArtifactPanel: (artifactId: string) => MessagePartArtifactPanel;- /** Steers sent to a conversation that the server has not confirmed yet. */- usePendingSteers: (conversationId: string) => PendingSteer[];- /** Whether a steer in a conversation is being escalated to an interrupt. */- useSteerEscalating: (conversationId: string) => boolean;- /** The conversation a pane is showing, or `null`. */- usePaneConversationId: (index: number) => string | null;- /**- * Whether a steer was just applied live (and should animate in), plus a stable function that- * clears that mark for a steer id once the part has seen it.- */- useLiveAppliedSteer: (steerId: string) => [boolean, (steerId: string) => void];-};+/** The host members of parts the app still owns, whose types the app still owns too. */+declare module '@librechat/chat/react' {+ interface MessagePartsHost {+ /** Live inner-call trace of one programmatic tool call in one message. */+ usePtcTrace: (messageId: string, toolCallId: string) => PtcTrace;+ /** The artifact panel, scoped to one artifact. */+ useArtifactPanel: (artifactId: string) => MessagePartArtifactPanel;+ /** Steers sent to a conversation that the server has not confirmed yet. */+ usePendingSteers: (conversationId: string) => PendingSteer[];+ }+}diff --git a/e2e/specs/mock/scenarios/message-parts-host.spec.ts b/e2e/specs/mock/scenarios/message-parts-host.spec.tsindex 6cab256366..ce98fad568 100644--- a/e2e/specs/mock/scenarios/message-parts-host.spec.ts+++ b/e2e/specs/mock/scenarios/message-parts-host.spec.ts@@ -184,6 +184,72 @@ test.describe('message parts host', () => {await expect(row).toHaveAttribute('aria-expanded', 'false');});+ test('tool calls route to their cards by prefix and by name, with any other name on the generic card @scenario:tool-calls-route-to-their-cards', async ({+ page,+ }) => {+ test.setTimeout(60000);+ const conversationId = unique('e2e-part-routing');+ const messageId = `${conversationId}-msg`;+ const now = new Date(0).toISOString();+ const toolCall = (name: string, suffix: string) => ({+ type: 'tool_call',+ tool_call: {+ id: `${conversationId}-${suffix}`,+ name,+ args: '{}',+ output: 'ok',+ progress: 1,+ },+ });+ const message = {+ messageId,+ conversationId,+ parentMessageId: NO_PARENT,+ isCreatedByUser: false,+ sender: 'Assistant',+ endpoint: 'Mock Provider A',+ model: 'mock-model-a',+ text: '',+ content: [+ toolCall('lc_transfer_to_researcher', 'handoff'),+ { type: 'text', text: 'Between the calls.' },+ toolCall('weather_lookup', 'generic'),+ ],+ createdAt: now,+ updatedAt: now,+ };+ const conversation = {+ conversationId,+ title: 'Part routing',+ endpoint: 'Mock Provider A',+ endpointType: 'custom',+ model: 'mock-model-a',+ createdAt: now,+ updatedAt: now,+ };+ const convoIdRe = escapeRe(conversationId);+ await page.route(new RegExp(`/api/convos/${convoIdRe}(?:\\?.*)?$`), (route: Route) =>+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(conversation),+ }),+ );+ await page.route(new RegExp(`/api/messages/${convoIdRe}(?:\\?.*)?$`), (route: Route) =>+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify([message]),+ }),+ );++ await page.goto(`/c/${conversationId}`, { timeout: 30000 });+ const view = messagesView(page);+ await expect(view.getByText('Between the calls.')).toBeVisible({ timeout: 15000 });+ await expect(view.getByText('Transferred to', { exact: true })).toBeVisible();+ await expect(view.getByText(/weather_lookup/i).first()).toBeVisible();+ });+test('a shared link renders parts without a host @scenario:shared-link-renders-parts-without-host', async ({page,}) => {diff --git a/package-lock.json b/package-lock.jsonindex a9f124ce90..f8a9c9a2fa 100644--- a/package-lock.json+++ b/package-lock.json@@ -41551,16 +41551,24 @@"@babel/preset-env": "^7.29.5","@babel/preset-react": "^7.22.15","@babel/preset-typescript": "^7.21.0",+ "@librechat/client": "*",+ "@testing-library/react": "^14.0.0","@types/jest": "^29.5.2",+ "@types/react": "^18.2.11","babel-plugin-replace-ts-export-assignment": "^0.0.2","jest": "^30.2.0",+ "jest-environment-jsdom": "^30.2.0","librechat-data-provider": "*",+ "react": "^18.2.0",+ "react-dom": "^18.2.0","rimraf": "^6.1.3","tsdown": "0.22.2","typescript": "^5.9.3"},"peerDependencies": {- "librechat-data-provider": "*"+ "@librechat/client": "*",+ "librechat-data-provider": "*",+ "react": "^18.2.0 || ^19.1.0"}},"packages/chat/node_modules/@babel/generator": {diff --git a/packages/chat/package.json b/packages/chat/package.jsonindex 37ddbcbf0f..5df9e705b7 100644--- a/packages/chat/package.json+++ b/packages/chat/package.json@@ -58,7 +58,9 @@"test:ci": "jest --ci"},"peerDependencies": {- "librechat-data-provider": "*"+ "@librechat/client": "*",+ "librechat-data-provider": "*",+ "react": "^18.2.0 || ^19.1.0"},"dependencies": {"sse.js": "^2.8.0"@@ -67,10 +69,16 @@"@babel/preset-env": "^7.29.5","@babel/preset-react": "^7.22.15","@babel/preset-typescript": "^7.21.0",+ "@librechat/client": "*",+ "@testing-library/react": "^14.0.0","@types/jest": "^29.5.2",+ "@types/react": "^18.2.11","babel-plugin-replace-ts-export-assignment": "^0.0.2","jest": "^30.2.0",+ "jest-environment-jsdom": "^30.2.0","librechat-data-provider": "*",+ "react": "^18.2.0",+ "react-dom": "^18.2.0","rimraf": "^6.1.3","tsdown": "0.22.2","typescript": "^5.9.3"diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.tsindex 8464f3bcb2..f4d8e06be9 100644--- a/packages/chat/src/components.ts+++ b/packages/chat/src/components.ts@@ -1,2 +1,12 @@/** Themed message and part components. Populated as the components move in. */-export {};+export { Part } from './components/Part';+export type {+ PartProps,+ ContentPart,+ PartRenderer,+ ToolRenderer,+ AgentToolCall,+ PartRenderers,+ PartRenderProps,+ ToolRenderProps,+} from './components/Part';diff --git a/packages/chat/src/components/Part.tsx b/packages/chat/src/components/Part.tsxnew file mode 100644index 0000000000..e1c386195b--- /dev/null+++ b/packages/chat/src/components/Part.tsx@@ -0,0 +1,131 @@+import { memo } from 'react';+import { ContentTypes, ToolCallTypes } from 'librechat-data-provider';+import type { TMessageContentParts, TAttachment } from 'librechat-data-provider';+import type { MemoExoticComponent, ReactNode } from 'react';+import { useMessageContext } from '../react/message';++/** A content part of one type. */+export type ContentPart<T extends ContentTypes = ContentTypes> = Extract<+ TMessageContentParts,+ { type: T }+>;++type ToolCallPart = ContentPart<ContentTypes.TOOL_CALL>;+type ToolCallValue = ToolCallPart[ContentTypes.TOOL_CALL];++/** A tool call an agent made, as opposed to the Assistants code, retrieval and function shapes. */+export type AgentToolCall = Extract<ToolCallValue, { args?: unknown }>;++/** What a part renderer receives. */+export type PartRenderProps<P extends TMessageContentParts = TMessageContentParts> = {+ part: P;+ /** The part's position in its message, from the message context. */+ partIndex: number | undefined;+ isLast?: boolean;+ isSubmitting: boolean;+ showCursor: boolean;+ isCreatedByUser: boolean;+ attachments?: TAttachment[];+ hideAttachments?: boolean;+ onToolExpand?: () => void;+};++/** Draws one part; `null` draws nothing. */+export type PartRenderer<P extends TMessageContentParts = TMessageContentParts> = (+ props: PartRenderProps<P>,+) => ReactNode;++/** What a tool renderer receives: the part, plus its agent tool call. */+export type ToolRenderProps = PartRenderProps<ToolCallPart> & {+ toolCall: AgentToolCall;+ /** The provider's id for the call, when it has one. */+ toolCallId: string | undefined;+};++/** Draws one agent tool call. */+export type ToolRenderer = (props: ToolRenderProps) => ReactNode;++/**+ * How a host draws each kind of part. `Part` only routes: every visual comes from here, so a host+ * adds a tool card by adding an entry to `tools`, the way an AI SDK app switches on+ * `tool-<name>` parts.+ */+export type PartRenderers = {+ /** Claims a part before it is routed by type, or returns `undefined` to let it through. */+ claim?: PartRenderer;+ /** Parts by content type. A tool call reaches its entry only in the Assistants shapes. */+ parts: { [T in ContentTypes]?: PartRenderer<ContentPart<T>> };+ /** Agent tool calls by tool name. */+ tools: Record<string, ToolRenderer>;+ /** Routes the calls a name alone cannot (by arguments, by name prefix); checked first. */+ matchTool?: (toolCall: AgentToolCall) => ToolRenderer | undefined;+ /** Agent tool calls no other entry claims. */+ defaultTool: ToolRenderer;+ /** Wraps every agent tool call's card, for state shared by all of them. */+ wrapTool?: (card: ReactNode, props: ToolRenderProps) => ReactNode;+};++export type PartProps = Omit<PartRenderProps, 'part' | 'partIndex'> & {+ part?: TMessageContentParts;+ renderers: PartRenderers;+};++/**+ * A registry entry the host set itself. Tool names and part types come from message data, so a+ * name like `constructor` must not reach a member every object inherits.+ */+const ownEntry = <T,>(+ registry: Partial<Record<string, T>>,+ key: string | undefined,+): T | undefined =>+ key != null && Object.prototype.hasOwnProperty.call(registry, key) ? registry[key] : undefined;++const isAgentToolCall = (toolCall: ToolCallValue): toolCall is AgentToolCall =>+ 'args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);++const renderToolCall = (+ renderers: PartRenderers,+ props: PartRenderProps<ToolCallPart>,+): ReactNode => {+ const toolCall = props.part[ContentTypes.TOOL_CALL];+ if (!toolCall) {+ return null;+ }+ if (!isAgentToolCall(toolCall)) {+ return renderers.parts[ContentTypes.TOOL_CALL]?.(props) ?? null;+ }+ const toolProps: ToolRenderProps = {+ ...props,+ toolCall,+ toolCallId: 'id' in toolCall && typeof toolCall.id === 'string' ? toolCall.id : undefined,+ };+ const render =+ renderers.matchTool?.(toolCall) ??+ ownEntry(renderers.tools, toolCall.name) ??+ renderers.defaultTool;+ const card = render(toolProps);+ return renderers.wrapTool ? renderers.wrapTool(card, toolProps) : card;+};++/** Routes one content part to the host's renderer for it. */+export const Part: MemoExoticComponent<(props: PartProps) => ReactNode> = memo(function Part({+ part,+ renderers,+ ...rest+}: PartProps) {+ const { partIndex } = useMessageContext();+ if (!part) {+ return null;+ }+ const props: PartRenderProps = { ...rest, part, partIndex };+ const claimed = renderers.claim?.(props);+ if (claimed !== undefined) {+ return claimed;+ }+ if (part.type === ContentTypes.TOOL_CALL) {+ return renderToolCall(renderers, { ...props, part });+ }+ const render = ownEntry(renderers.parts, part.type) as PartRenderer | undefined;+ return render?.(props) ?? null;+});+Part.displayName = 'Part';diff --git a/packages/chat/src/components/__tests__/Part.spec.tsx b/packages/chat/src/components/__tests__/Part.spec.tsxnew file mode 100644index 0000000000..5ec9da7123--- /dev/null+++ b/packages/chat/src/components/__tests__/Part.spec.tsx@@ -0,0 +1,165 @@+/**+ * @jest-environment jsdom+ */+import { render, screen } from '@testing-library/react';+import { ContentTypes, ToolCallTypes } from 'librechat-data-provider';+import type { TMessageContentParts } from 'librechat-data-provider';+import type { PartRenderers, ToolRenderer } from '../Part';+import { MessageContext } from '../../react/message';+import { Part } from '../Part';++const toolPart = (toolCall: Record<string, unknown>) =>+ ({+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: { type: ToolCallTypes.TOOL_CALL, args: '{}', ...toolCall },+ }) as unknown as TMessageContentParts;++const named =+ (label: string): ToolRenderer =>+ ({ toolCall, toolCallId }) => (+ <p>+ {label}:{toolCall.name}:{toolCallId ?? 'none'}+ </p>+ );++function createRenderers(overrides: Partial<PartRenderers> = {}): PartRenderers {+ return {+ parts: {+ [ContentTypes.TEXT]: ({ part, partIndex, isLast }) => (+ <p>+ text:{typeof part.text === 'string' ? part.text : part.text?.value}:{partIndex}:+ {String(isLast)}+ </p>+ ),+ [ContentTypes.TOOL_CALL]: ({ part }) => <p>assistants:{part.tool_call.type}</p>,+ },+ tools: { web_search: named('search') },+ defaultTool: named('generic'),+ ...overrides,+ };+}++const baseProps = { isSubmitting: false, showCursor: false, isCreatedByUser: false };++describe('Part', () => {+ it('routes a part to the renderer for its type, with its index from the message', () => {+ render(+ <MessageContext.Provider value={{ messageId: 'm1', isExpanded: false, partIndex: 3 }}>+ <Part+ {...baseProps}+ isLast={true}+ part={{ type: ContentTypes.TEXT, text: 'hello' }}+ renderers={createRenderers()}+ />+ </MessageContext.Provider>,+ );+ expect(screen.getByText('text:hello:3:true')).toBeTruthy();+ });++ it('draws nothing for a missing part or a type without a renderer', () => {+ const renderers = createRenderers();+ const { container } = render(+ <>+ <Part {...baseProps} renderers={renderers} />+ <Part+ {...baseProps}+ part={{ type: ContentTypes.THINK, think: 'hmm' }}+ renderers={renderers}+ />+ </>,+ );+ expect(container.innerHTML).toBe('');+ });++ it('routes an agent tool call by name, falling back to the default tool', () => {+ render(+ <>+ <Part+ {...baseProps}+ part={toolPart({ id: 'call-1', name: 'web_search' })}+ renderers={createRenderers()}+ />+ <Part+ {...baseProps}+ part={toolPart({ name: 'unknown_tool' })}+ renderers={createRenderers()}+ />+ </>,+ );+ expect(screen.getByText('search:web_search:call-1')).toBeTruthy();+ expect(screen.getByText('generic:unknown_tool:none')).toBeTruthy();+ });++ it.each(['constructor', '__proto__', 'toString', 'hasOwnProperty'])(+ 'treats the inherited member %s as unknown in both registries',+ (name) => {+ const { container } = render(+ <>+ <Part {...baseProps} part={toolPart({ name })} renderers={createRenderers()} />+ <Part+ {...baseProps}+ part={{ type: name } as unknown as TMessageContentParts}+ renderers={createRenderers()}+ />+ </>,+ );+ expect(container.textContent).toBe(`generic:${name}:none`);+ },+ );++ it('lets a matcher route a call before its name, and wraps every agent tool card', () => {+ const renderers = createRenderers({+ matchTool: (toolCall) => (toolCall.name?.startsWith('lc_') ? named('matched') : undefined),+ wrapTool: (card, { toolCall }) => (+ <section aria-label={`wrapped ${toolCall.name}`}>{card}</section>+ ),+ });+ render(<Part {...baseProps} part={toolPart({ name: 'lc_transfer' })} renderers={renderers} />);+ const wrapper = screen.getByRole('region', { name: 'wrapped lc_transfer' });+ expect(wrapper.textContent).toBe('matched:lc_transfer:none');+ });++ it('sends the Assistants tool call shapes to the tool call part renderer, unwrapped', () => {+ const wrapTool = jest.fn((card: React.ReactNode) => card);+ render(+ <Part+ {...baseProps}+ part={+ {+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ type: ToolCallTypes.CODE_INTERPRETER,+ code_interpreter: { input: '', outputs: [] },+ },+ } as unknown as TMessageContentParts+ }+ renderers={createRenderers({ wrapTool })}+ />,+ );+ expect(screen.getByText(`assistants:${ToolCallTypes.CODE_INTERPRETER}`)).toBeTruthy();+ expect(wrapTool).not.toHaveBeenCalled();+ });++ it('lets a claim take a part before type routing, and pass on the rest', () => {+ const renderers = createRenderers({+ claim: ({ part }) =>+ part.type === ContentTypes.TEXT && part.text === 'claimed' ? <p>claim</p> : undefined,+ });+ render(+ <>+ <Part+ {...baseProps}+ part={{ type: ContentTypes.TEXT, text: 'claimed' }}+ renderers={renderers}+ />+ <Part+ {...baseProps}+ part={{ type: ContentTypes.TEXT, text: 'free' }}+ renderers={renderers}+ />+ </>,+ );+ expect(screen.getByText('claim')).toBeTruthy();+ expect(screen.getByText('text:free::undefined')).toBeTruthy();+ });+});diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.tsindex f2ee47cbd7..a6053d3d41 100644--- a/packages/chat/src/react.ts+++ b/packages/chat/src/react.ts@@ -1,2 +1,14 @@/** React bindings for the core `Chat`: providers and `useChat`. Populated as the hooks move in. */-export {};+export { MessageContext, useMessageContext } from './react/message';+export {+ useMessagePartsHost,+ MessagePartsHostProvider,+ setDefaultMessagePartsHost,+} from './react/host';+export type {+ MessagePartsHost,+ MessagePartsUser,+ MessagePartsToast,+ MessagePartMessage,+ MessagePartsUserTextPreferences,+} from './react/host';diff --git a/packages/chat/src/react/__tests__/host.spec.tsx b/packages/chat/src/react/__tests__/host.spec.tsxnew file mode 100644index 0000000000..cce9ac76dc--- /dev/null+++ b/packages/chat/src/react/__tests__/host.spec.tsx@@ -0,0 +1,52 @@+/**+ * @jest-environment jsdom+ */+import { render, screen } from '@testing-library/react';+import type { MessagePartsHost } from '../host';+import { MessagePartsHostProvider, setDefaultMessagePartsHost, useMessagePartsHost } from '../host';++const createHost = (fontSize: string): MessagePartsHost => ({+ useMessage: () => ({ messageId: 'm1' }),+ useFontSize: () => fontSize,+ useShowThinking: () => false,+ useAutoExpandTools: () => false,+ useUserTextPreferences: () => ({+ usernameDisplay: false,+ enableUserMsgMarkdown: false,+ collapseLongUserMessages: false,+ }),+ useUser: () => undefined,+ useFileMap: () => undefined,+ useToast: () => jest.fn(),+ useSandboxStarting: () => false,+ useToolArtifactClaim: () => [null, jest.fn()],+ useSteerEscalating: () => false,+ usePaneConversationId: () => null,+ useLiveAppliedSteer: () => [false, jest.fn()],+});++function FontSize() {+ const { useFontSize } = useMessagePartsHost();+ return <p>{useFontSize()}</p>;+}++describe('message parts host', () => {+ it('requires a host when no provider or default supplies one', () => {+ jest.spyOn(console, 'error').mockImplementation(() => undefined);+ expect(() => render(<FontSize />)).toThrow(/MessagePartsHostProvider/);+ });++ it('reads the registered default outside a provider, and the provider inside one', () => {+ setDefaultMessagePartsHost(createHost('text-default'));+ render(+ <>+ <FontSize />+ <MessagePartsHostProvider host={createHost('text-provided')}>+ <FontSize />+ </MessagePartsHostProvider>+ </>,+ );+ expect(screen.getByText('text-default')).toBeTruthy();+ expect(screen.getByText('text-provided')).toBeTruthy();+ });+});diff --git a/packages/chat/src/react/host.tsx b/packages/chat/src/react/host.tsxnew file mode 100644index 0000000000..79640d8828--- /dev/null+++ b/packages/chat/src/react/host.tsx@@ -0,0 +1,116 @@+import { createContext, useContext } from 'react';+import type { Dispatch, ReactNode, SetStateAction } from 'react';+import type { TFile } from 'librechat-data-provider';+import type { TShowToast } from '@librechat/client';++/** The message a part renders in, as its host reports it. */+export type MessagePartMessage = {+ /** Id of the message that owns the part, or `''` outside a message. */+ messageId: string;+ /** Whether that message is still generating. */+ isSubmitting?: boolean;+ /** Whether that message is the tail of the active branch. */+ isLatestMessage?: boolean;+ /** Content type of the part after this one, when known. */+ nextType?: string;+};++/** How the viewer prefers user-authored text to display. */+export type MessagePartsUserTextPreferences = {+ /** Whether user-authored text renders as markdown. */+ enableUserMsgMarkdown: boolean;+ /** Whether long user-authored text collapses behind a toggle. */+ collapseLongUserMessages: boolean;+ /** Whether user turns are labeled with the user's name. */+ usernameDisplay: boolean;+};++/** The signed-in user as the parts label it; `undefined` on a public share. */+export type MessagePartsUser = { name?: string; username?: string } | undefined;++/** Shows a transient notification. */+export type MessagePartsToast = (toast: TShowToast) => void;++/**+ * Everything the message part components read from the app, supplied by the view that renders+ * them through `MessagePartsHostProvider`. Members are hooks, called unconditionally by the parts+ * that need them, so keyed reads subscribe to one key only. A host must stay the same object for+ * the life of the tree it wraps. Setters are typed as React dispatchers, so+ * the contract names no state library.+ *+ * It is an interface so an app can declare the members of parts it has not handed to this+ * package yet, by augmenting `@librechat/chat/react`.+ */+export interface MessagePartsHost {+ /** The message the calling part renders in. */+ useMessage: () => MessagePartMessage;+ /** The viewer's font size utility, applied to reasoning and summary text. */+ useFontSize: () => string;+ /** Whether the viewer wants reasoning expanded by default. */+ useShowThinking: () => boolean;+ /** Whether the viewer wants tool cards and tool groups expanded by default. */+ useAutoExpandTools: () => boolean;+ /** How the viewer prefers user-authored text to display. */+ useUserTextPreferences: () => MessagePartsUserTextPreferences;+ /** The signed-in user. */+ useUser: () => MessagePartsUser;+ /** The user's uploaded files keyed by file id, used to hydrate attachment metadata. */+ useFileMap: () => Record<string, TFile> | undefined;+ /** The notification function. */+ useToast: () => MessagePartsToast;+ /** Whether the sandbox for a code tool call is still starting. */+ useSandboxStarting: (toolCallId: string) => boolean;+ /**+ * Which mounted card owns the row for a tool artifact, so one file renders once across tool+ * calls and messages. The key is the artifact id.+ */+ useToolArtifactClaim: (+ artifactId: string,+ ) => [string | null, Dispatch<SetStateAction<string | null>>];+ /** Whether a steer in a conversation is being escalated to an interrupt. */+ useSteerEscalating: (conversationId: string) => boolean;+ /** The conversation a pane is showing, or `null`. */+ usePaneConversationId: (index: number) => string | null;+ /**+ * Whether a steer was just applied live (and should animate in), plus a stable function that+ * clears that mark for a steer id once the part has seen it.+ */+ useLiveAppliedSteer: (steerId: string) => [boolean, (steerId: string) => void];+}++const MessagePartsHostContext = createContext<MessagePartsHost | null>(null);++let defaultHost: MessagePartsHost | null = null;++/**+ * Registers the host that parts rendered outside any `MessagePartsHostProvider` read, the way+ * `react-i18next` registers its instance. An app registers its own once, when the module that+ * builds it loads; a provider always wins over it.+ */+export function setDefaultMessagePartsHost(host: MessagePartsHost): void {+ defaultHost = host;+}++/** Supplies the host the message parts read from. */+export function MessagePartsHostProvider({+ host,+ children,+}: {+ host: MessagePartsHost;+ children: ReactNode;+}): ReactNode {+ return (+ <MessagePartsHostContext.Provider value={host}>{children}</MessagePartsHostContext.Provider>+ );+}++/** The host of the nearest provider, or the registered default. */+export function useMessagePartsHost(): MessagePartsHost {+ const host = useContext(MessagePartsHostContext) ?? defaultHost;+ if (host == null) {+ throw new Error(+ 'Message parts need a host: render them inside MessagePartsHostProvider or register one with setDefaultMessagePartsHost.',+ );+ }+ return host;+}diff --git a/packages/chat/src/react/message.ts b/packages/chat/src/react/message.tsnew file mode 100644index 0000000000..2369db95ee--- /dev/null+++ b/packages/chat/src/react/message.ts@@ -0,0 +1,20 @@+import { createContext, useContext } from 'react';+import type { Context } from 'react';++/** The message a part renders in, as the view rendering it reports. */+export type MessageContext = {+ messageId: string;+ nextType?: string;+ partIndex?: number;+ isExpanded: boolean;+ conversationId?: string | null;+ /** Submission state for cursor display - only true for latest message when submitting */+ isSubmitting?: boolean;+ /** Whether this is the latest message in the conversation */+ isLatestMessage?: boolean;+};++export const MessageContext: Context<MessageContext> = createContext<MessageContext>(+ {} as MessageContext,+);+export const useMessageContext = (): MessageContext => useContext(MessageContext);diff --git a/scripts/static-checks.mts b/scripts/static-checks.mtsindex 55944b3233..afeaace4b7 100644--- a/scripts/static-checks.mts+++ b/scripts/static-checks.mts@@ -1775,6 +1775,7 @@ const BUILD_ORDER = ['build:data-schemas','build:api','build:client-package',+ 'build:chat',];/** Returns the failing build's outcome, or null when every build succeeded. */@@ -1975,13 +1976,14 @@ const TYPECHECK_PROJECTS = [project: 'packages/chat/tsconfig.json',paths: ['packages/data-provider/**',+ 'packages/client/**','packages/chat/**',...ROOT_MANIFESTS,TYPECHECK_SCRIPT,FRONTEND_REVIEW,'!**.md',],- requires: ['build:data-provider'],+ requires: ['build:data-provider', 'build:client-package'],},{project: 'client/tsconfig.json',@@ -1989,12 +1991,13 @@ const TYPECHECK_PROJECTS = ['client/**','packages/data-provider/**','packages/client/**',+ 'packages/chat/**',...ROOT_MANIFESTS,TYPECHECK_SCRIPT,FRONTEND_REVIEW,'!**.md',],- requires: ['build:data-provider', 'build:client-package'],+ requires: ['build:data-provider', 'build:client-package', 'build:chat'],},];