Skip to content

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

🪟 feat: Render Code-Execution Text Artifacts as Side-Panel Artifacts (#12832)

Danny Avila47f65fe39a9b
diff --git a/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx b/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx
index 2d7fb56ffc..67fc2a5da8 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx
@@ -1,9 +1,18 @@
-import { memo, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
+import { memo, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Tools } from 'librechat-data-provider';
import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
-import { isImageAttachment, isTextAttachment } from './attachmentTypes';
+import type { ToolArtifactType } from '~/utils/artifacts';
+import {
+ artifactTypeForAttachment,
+ isImageAttachment,
+ isTextAttachment,
+ renderAttachmentKey,
+} from './attachmentTypes';
import FileContainer from '~/components/Chat/Input/Files/FileContainer';
+import { fileToArtifact, TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
import Image from '~/components/Chat/Messages/Content/Image';
+import ToolMermaidArtifact from './ToolMermaidArtifact';
+import ToolArtifactCard from './ToolArtifactCard';
import { useAttachmentLink } from './LogLink';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -174,6 +183,40 @@ const ImageAttachment = memo(({ attachment }: { attachment: TAttachment }) => {
);
});
+interface PanelArtifactProps {
+ attachment: TAttachment;
+ /** Pre-classified type from the routing decision tree, threaded down so
+ * `fileToArtifact` doesn't re-run `detectArtifactTypeFromFile`. */
+ type: ToolArtifactType;
+}
+
+const PanelArtifact = memo(({ attachment, type }: PanelArtifactProps) => {
+ const localize = useLocalize();
+ const placeholder = localize('com_ui_artifact_preview_pending');
+ const artifact = useMemo(
+ () =>
+ fileToArtifact(attachment as TFile & TAttachmentMetadata, {
+ placeholder,
+ preClassifiedType: type,
+ }),
+ [attachment, type, placeholder],
+ );
+ if (!artifact) {
+ return null;
+ }
+ return <ToolArtifactCard attachment={attachment} artifact={artifact} />;
+});
+PanelArtifact.displayName = 'PanelArtifact';
+
+const MermaidArtifact = memo(({ attachment }: { attachment: TAttachment }) => {
+ const file = attachment as TFile & TAttachmentMetadata;
+ if (!file.text) {
+ return null;
+ }
+ return <ToolMermaidArtifact attachment={attachment} text={file.text} />;
+});
+MermaidArtifact.displayName = 'MermaidArtifact';
+
export default function Attachment({ attachment }: { attachment?: TAttachment }) {
if (!attachment) {
return null;
@@ -185,6 +228,16 @@ export default function Attachment({ attachment }: { attachment?: TAttachment })
if (isImageAttachment(attachment)) {
return <ImageAttachment attachment={attachment} />;
}
+ // Single classification call. The result is threaded into
+ // `PanelArtifact` -> `fileToArtifact` so the panel path doesn't
+ // re-run `detectArtifactTypeFromFile` a second time.
+ const artType = artifactTypeForAttachment(attachment);
+ if (artType === TOOL_ARTIFACT_TYPES.MERMAID) {
+ return <MermaidArtifact attachment={attachment} />;
+ }
+ if (artType != null) {
+ return <PanelArtifact attachment={attachment} type={artType} />;
+ }
if (isTextAttachment(attachment)) {
return <TextAttachment attachment={attachment} />;
}
@@ -202,6 +255,8 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] }
const fileAttachments: TAttachment[] = [];
const imageAttachments: TAttachment[] = [];
const textAttachments: TAttachment[] = [];
+ const panelArtifacts: Array<{ attachment: TAttachment; type: ToolArtifactType }> = [];
+ const mermaidArtifacts: TAttachment[] = [];
attachments.forEach((attachment) => {
if (attachment.type === Tools.web_search) {
@@ -211,6 +266,15 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] }
imageAttachments.push(attachment);
return;
}
+ const artType = artifactTypeForAttachment(attachment);
+ if (artType === TOOL_ARTIFACT_TYPES.MERMAID) {
+ mermaidArtifacts.push(attachment);
+ return;
+ }
+ if (artType != null) {
+ panelArtifacts.push({ attachment, type: artType });
+ return;
+ }
if (isTextAttachment(attachment)) {
textAttachments.push(attachment);
return;
@@ -224,22 +288,52 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] }
<div className="my-2 flex flex-wrap items-center gap-2.5">
{fileAttachments.map((attachment, index) =>
attachment.filepath ? (
- <FileAttachment attachment={attachment} key={`file-${index}`} />
+ <FileAttachment
+ attachment={attachment}
+ key={renderAttachmentKey('file', attachment, index)}
+ />
) : null,
)}
</div>
)}
+ {panelArtifacts.length > 0 && (
+ <div className="my-2 flex flex-wrap items-center gap-2">
+ {panelArtifacts.map(({ attachment, type }, index) => (
+ <PanelArtifact
+ attachment={attachment}
+ type={type}
+ key={renderAttachmentKey('artifact', attachment, index)}
+ />
+ ))}
+ </div>
+ )}
+ {mermaidArtifacts.length > 0 && (
+ <div className="my-2 flex flex-col gap-3">
+ {mermaidArtifacts.map((attachment, index) => (
+ <MermaidArtifact
+ attachment={attachment}
+ key={renderAttachmentKey('mermaid', attachment, index)}
+ />
+ ))}
+ </div>
+ )}
{textAttachments.length > 0 && (
<div className="my-2 flex flex-col gap-3">
{textAttachments.map((attachment, index) => (
- <TextAttachment attachment={attachment} key={`text-${index}`} />
+ <TextAttachment
+ attachment={attachment}
+ key={renderAttachmentKey('text', attachment, index)}
+ />
))}
</div>
)}
{imageAttachments.length > 0 && (
<div className="mb-2 flex flex-wrap items-center">
{imageAttachments.map((attachment, index) => (
- <ImageAttachment attachment={attachment} key={`image-${index}`} />
+ <ImageAttachment
+ attachment={attachment}
+ key={renderAttachmentKey('image', attachment, index)}
+ />
))}
</div>
)}
diff --git a/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx b/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx
index 3de9628024..21ceaebdde 100644
--- a/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx
@@ -2,11 +2,29 @@ import { isAfter } from 'date-fns';
import React, { useMemo } from 'react';
import { imageExtRegex } from 'librechat-data-provider';
import type { TFile, TAttachment, TAttachmentMetadata } from 'librechat-data-provider';
+import type { Artifact } from '~/common';
+import {
+ artifactTypeForAttachment,
+ isTextAttachment,
+ renderAttachmentKey,
+} from './attachmentTypes';
+import { fileToArtifact, TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
import Image from '~/components/Chat/Messages/Content/Image';
-import { isTextAttachment } from './attachmentTypes';
+import ToolMermaidArtifact from './ToolMermaidArtifact';
+import ToolArtifactCard from './ToolArtifactCard';
import { useLocalize } from '~/hooks';
import LogLink from './LogLink';
+interface PanelEntry {
+ attachment: TAttachment;
+ artifact: Artifact;
+}
+
+interface MermaidEntry {
+ attachment: TAttachment;
+ text: string;
+}
+
interface LogContentProps {
output?: string;
renderImages?: boolean;
@@ -17,6 +35,7 @@ type ImageAttachment = TFile & TAttachmentMetadata;
const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, attachments }) => {
const localize = useLocalize();
+ const artifactPreviewPending = localize('com_ui_artifact_preview_pending');
const processedContent = useMemo(() => {
if (!output) {
@@ -27,11 +46,20 @@ const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, atta
return parts[0].trim();
}, [output]);
- const { imageAttachments, textAttachments, nonInlineAttachments } = useMemo(() => {
+ const {
+ imageAttachments,
+ textAttachments,
+ panelAttachments,
+ mermaidAttachments,
+ nonInlineAttachments,
+ } = useMemo(() => {
const imageAtts: ImageAttachment[] = [];
const textAtts: Array<TFile & TAttachmentMetadata> = [];
+ const panelAtts: PanelEntry[] = [];
+ const mermaidAtts: MermaidEntry[] = [];
const otherAtts: TAttachment[] = [];
+ const now = new Date();
attachments?.forEach((attachment) => {
const fileData = attachment as TFile & TAttachmentMetadata;
const { filepath = null } = fileData;
@@ -42,6 +70,39 @@ const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, atta
imageAtts.push(attachment as ImageAttachment);
return;
}
+ // Expired downloads must keep the legacy "download expired" message.
+ // Panel cards and the mermaid renderer would otherwise present an
+ // active-looking surface backed by a dead link, so route expired
+ // entries through `renderAttachment` instead.
+ const expiresAt =
+ 'expiresAt' in attachment && typeof attachment.expiresAt === 'number'
+ ? new Date(attachment.expiresAt)
+ : null;
+ const isExpired = expiresAt != null && isAfter(now, expiresAt);
+ if (isExpired) {
+ otherAtts.push(attachment);
+ return;
+ }
+ const artType = artifactTypeForAttachment(attachment);
+ if (artType === TOOL_ARTIFACT_TYPES.MERMAID) {
+ if (fileData.text) {
+ mermaidAtts.push({
+ attachment,
+ text: fileData.text,
+ });
+ }
+ return;
+ }
+ if (artType != null) {
+ const artifact = fileToArtifact(fileData, {
+ placeholder: artifactPreviewPending,
+ preClassifiedType: artType,
+ });
+ if (artifact) {
+ panelAtts.push({ attachment, artifact });
+ }
+ return;
+ }
if (isTextAttachment(attachment)) {
textAtts.push(fileData);
return;
@@ -52,9 +113,11 @@ const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, atta
return {
imageAttachments: renderImages === true ? imageAtts : null,
textAttachments: textAtts,
+ panelAttachments: panelAtts,
+ mermaidAttachments: mermaidAtts,
nonInlineAttachments: otherAtts,
};
- }, [attachments, renderImages]);
+ }, [attachments, renderImages, artifactPreviewPending]);
const renderAttachment = (file: TAttachment) => {
const now = new Date();
@@ -91,18 +154,40 @@ const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, atta
<div>
<p>{localize('com_generated_files')}</p>
{nonInlineAttachments.map((file, index) => (
- <React.Fragment key={file.filepath}>
+ <React.Fragment key={renderAttachmentKey('nonInline', file, index)}>
{renderAttachment(file)}
{index < nonInlineAttachments.length - 1 && ', '}
</React.Fragment>
))}
</div>
)}
+ {panelAttachments.length > 0 && (
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {panelAttachments.map(({ attachment, artifact }, index) => (
+ <ToolArtifactCard
+ key={renderAttachmentKey('artifact', attachment, index)}
+ attachment={attachment}
+ artifact={artifact}
+ />
+ ))}
+ </div>
+ )}
+ {mermaidAttachments.length > 0 && (
+ <div className="mt-2 flex flex-col gap-3">
+ {mermaidAttachments.map(({ attachment, text }, index) => (
+ <ToolMermaidArtifact
+ key={renderAttachmentKey('mermaid', attachment, index)}
+ attachment={attachment}
+ text={text}
+ />
+ ))}
+ </div>
+ )}
{textAttachments.length > 0 && (
<div className="mt-2 flex flex-col gap-3">
- {textAttachments.map((file) => (
+ {textAttachments.map((file, index) => (
<div
- key={file.filepath ?? file.file_id ?? file.filename}
+ key={renderAttachmentKey('text', file, index)}
className="rounded-lg bg-surface-secondary p-3"
>
{file.filename && (
@@ -129,11 +214,11 @@ const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, atta
))}
</div>
)}
- {imageAttachments?.map((attachment) => (
+ {imageAttachments?.map((attachment, index) => (
<Image
width={attachment.width}
height={attachment.height}
- key={attachment.filepath}
+ key={renderAttachmentKey('image', attachment, index)}
altText={attachment.filename}
imagePath={attachment.filepath}
/>
diff --git a/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx b/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx
new file mode 100644
index 0000000000..cae6d197ff
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx
@@ -0,0 +1,179 @@
+import { memo, useEffect, useId, useLayoutEffect } from 'react';
+import { Download } from 'lucide-react';
+import { useRecoilState, useRecoilValue, useResetRecoilState, useSetRecoilState } from 'recoil';
+import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
+import type { Artifact } from '~/common';
+import FilePreview from '~/components/Chat/Input/Files/FilePreview';
+import { useAttachmentLink } from './LogLink';
+import { useLocalize } from '~/hooks';
+import { cn, getFileType } from '~/utils';
+import store from '~/store';
+
+interface ToolArtifactCardProps {
+ attachment: TAttachment;
+ artifact: Artifact;
+}
+
+/**
+ * Card that opens a code-execution-produced artifact in the side panel.
+ *
+ * Three effects, separately scoped:
+ *
+ * 1. **Dedup claim** (`useLayoutEffect`, runs synchronously before
+ * paint). The same file can appear in multiple tool calls within a
+ * single message (e.g. the agent reads back what it just wrote) or
+ * across messages. Each card claims `toolArtifactClaim(artifact.id)`
+ * with its unique component-instance key on mount; the latest card
+ * to mount wins, so older duplicates re-render to `null`. The atom
+ * is family-keyed by artifact id, so claims for unrelated artifacts
+ * don't trigger re-renders here. Cleanup releases the claim if it's
+ * still ours so a subsequent re-mount can take it.
+ *
+ * 2. **Self-heal registration** subscribes to the per-id selector
+ * `artifactByIdSelector(artifact.id)` and writes only when the
+ * entry is missing or the cached content/type/title drifted. The
+ * panel's `useArtifacts` hook resets `artifactsState` on close, so
+ * this re-fires deterministically once the slice transitions back
+ * to `undefined` — without the no-deps render-loop pattern. The
+ * write is also gated on `isMyClaim`, making the registration
+ * single-writer per id: when two cards exist for the same file
+ * across turns, only the latest (claim-holder) updates state.
+ * Without that guard, both cards would observe each other's write
+ * and trade overwrites in a loop.
+ *
+ * 3. **Focus on mount** (deps: artifact.id). A freshly-mounted card
+ * means a new artifact has arrived; we steal panel focus to match
+ * the legacy streaming-artifact UX where the latest artifact
+ * auto-opens. Cards that re-render with the same artifact don't
+ * refire this, so user clicks on older cards aren't overridden.
+ *
+ * Visibility is intentionally not toggled. The Recoil default is `true`,
+ * which auto-opens the panel on first registration; a user who has
+ * explicitly closed the panel keeps it closed until they click.
+ */
+const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps) => {
+ const localize = useLocalize();
+ const claimKey = useId();
+ const setVisible = useSetRecoilState(store.artifactsVisibility);
+ const setArtifacts = useSetRecoilState(store.artifactsState);
+ const setCurrentArtifactId = useSetRecoilState(store.currentArtifactId);
+ const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);
+ const currentArtifactId = useRecoilValue(store.currentArtifactId);
+ const existingEntry = useRecoilValue(store.artifactByIdSelector(artifact.id));
+ const [claim, setClaim] = useRecoilState(store.toolArtifactClaim(artifact.id));
+ const isSelected = artifact.id === currentArtifactId;
+ const isMyClaim = claim === claimKey;
+
+ useLayoutEffect(() => {
+ // Always (re)claim on mount — a later card for the same id displaces
+ // an earlier one, so the chip migrates to the most recent mention.
+ setClaim(claimKey);
+ return () => {
+ // Only release when the claim is still ours; if a sibling already
+ // took over we don't want to clobber its claim.
+ setClaim((prev) => (prev === claimKey ? null : prev));
+ };
+ }, [claimKey, setClaim]);
+
+ useEffect(() => {
+ // Only the claim-winner writes. Two cards with the same `artifact.id`
+ // but divergent content (same file_id reused across turns) would
+ // otherwise see each other's write through `existingEntry`, detect
+ // drift, and trade overwrites in a loop. Gating on `isMyClaim`
+ // makes registration single-writer per id.
+ if (!isMyClaim) {
+ return;
+ }
+ if (
+ existingEntry != null &&
+ existingEntry.content === artifact.content &&
+ existingEntry.type === artifact.type &&
+ existingEntry.title === artifact.title
+ ) {
+ return;
+ }
+ setArtifacts((prev) => ({ ...(prev ?? {}), [artifact.id]: artifact }));
+ }, [artifact, existingEntry, isMyClaim, setArtifacts]);
+
+ useEffect(() => {
+ setCurrentArtifactId(artifact.id);
+ }, [artifact.id, setCurrentArtifactId]);
+
+ const file = attachment as TFile & TAttachmentMetadata;
+ const { handleDownload } = useAttachmentLink({
+ href: attachment.filepath ?? '',
+ filename: attachment.filename ?? '',
+ file_id: file.file_id,
+ user: file.user,
+ source: file.source,
+ });
+
+ const handleOpen = () => {
+ if (isSelected) {
+ resetCurrentArtifactId();
+ setVisible(false);
+ return;
+ }
+ // Registration already happened in the mount effect; the click only
+ // needs to focus + reveal the panel for users who have closed it.
+ setCurrentArtifactId(artifact.id);
+ setVisible(true);
+ };
+
+ // Another card with the same artifact id has the active claim — render
+ // nothing here, that card is the canonical chip for this file.
+ if (claim != null && !isMyClaim) {
+ return null;
+ }
+
+ const fileType = getFileType('artifact');
+ const actionLabel = isSelected
+ ? localize('com_ui_click_to_close')
+ : localize('com_ui_artifact_click');
+
+ return (
+ <div className="group relative my-2 inline-flex max-w-fit items-stretch gap-px overflow-hidden rounded-xl text-sm text-text-primary shadow-sm">
+ <button
+ type="button"
+ onClick={handleOpen}
+ aria-pressed={isSelected}
+ className={cn(
+ 'relative overflow-hidden rounded-l-xl transition-all duration-200 hover:bg-surface-hover active:scale-[0.99]',
+ {
+ 'border-border-medium bg-surface-hover': isSelected,
+ 'border-border-light bg-surface-tertiary': !isSelected,
+ },
+ )}
+ >
+ <div className="w-fit p-2">
+ <div className="flex flex-row items-center gap-2">
+ <FilePreview fileType={fileType} className="relative" />
+ <div className="overflow-hidden text-left">
+ <div className="truncate font-medium" title={attachment.filename ?? ''}>
+ {artifact.title}
+ </div>
+ <div className="truncate text-xs text-text-secondary">{actionLabel}</div>
+ </div>
+ </div>
+ </div>
+ </button>
+ <button
+ type="button"
+ onClick={handleDownload}
+ aria-label={`${localize('com_ui_download')} ${attachment.filename ?? ''}`}
+ title={localize('com_ui_download')}
+ className={cn(
+ 'flex shrink-0 items-center justify-center px-3 transition-colors duration-200',
+ 'rounded-r-xl bg-surface-tertiary text-text-secondary hover:bg-surface-hover hover:text-text-primary',
+ 'border-l border-border-light focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
+ )}
+ >
+ <Download className="size-4" aria-hidden="true" />
+ </button>
+ </div>
+ );
+});
+
+ToolArtifactCard.displayName = 'ToolArtifactCard';
+
+export default ToolArtifactCard;
diff --git a/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx b/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx
new file mode 100644
index 0000000000..65e917e7c5
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx
@@ -0,0 +1,91 @@
+import { memo, useId, useLayoutEffect } from 'react';
+import { Download } from 'lucide-react';
+import { useRecoilState } from 'recoil';
+import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
+import Mermaid from '~/components/Messages/Content/Mermaid/Mermaid';
+import { toolArtifactKey } from '~/utils/artifacts';
+import { useAttachmentLink } from './LogLink';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+import store from '~/store';
+
+interface ToolMermaidArtifactProps {
+ attachment: TAttachment;
+ text: string;
+}
+
+/**
+ * Renders a code-execution-produced mermaid artifact inline. Skips the
+ * sandpack/react path the side-panel artifacts use — the standalone
+ * Mermaid component has its own zoom/expand/code-toggle UI and we want
+ * to reuse it without bringing the bundler chrome along.
+ *
+ * Shares the `toolArtifactClaim` dedup atom with `ToolArtifactCard` so
+ * the same `.mmd` file can't double-render across tool calls / messages.
+ */
+const ToolMermaidArtifact = memo(({ attachment, text }: ToolMermaidArtifactProps) => {
+ const localize = useLocalize();
+ const file = attachment as TFile & TAttachmentMetadata;
+ const claimKey = useId();
+ const [claim, setClaim] = useRecoilState(store.toolArtifactClaim(toolArtifactKey(file)));
+ const isMyClaim = claim === claimKey;
+
+ useLayoutEffect(() => {
+ setClaim(claimKey);
+ return () => {
+ setClaim((prev) => (prev === claimKey ? null : prev));
+ };
+ }, [claimKey, setClaim]);
+
+ const { handleDownload } = useAttachmentLink({
+ href: attachment.filepath ?? '',
+ filename: attachment.filename ?? '',
+ file_id: file.file_id,
+ user: file.user,
+ source: file.source,
+ });
+
+ if (claim != null && !isMyClaim) {
+ return null;
+ }
+
+ return (
+ <div className="my-2 flex w-full flex-col gap-1">
+ {(attachment.filename || attachment.filepath) && (
+ <div className="flex items-center justify-between gap-2">
+ {attachment.filename && (
+ <div
+ className="truncate text-[10px] font-medium uppercase tracking-wide text-text-secondary"
+ title={attachment.filename}
+ >
+ {attachment.filename}
+ </div>
+ )}
+ {attachment.filepath && (
+ <button
+ type="button"
+ onClick={handleDownload}
+ aria-label={`${localize('com_ui_download')} ${attachment.filename ?? ''}`}
+ title={localize('com_ui_download')}
+ className={cn(
+ 'inline-flex shrink-0 items-center gap-1 rounded-md px-2 py-1 text-xs',
+ 'text-text-secondary transition-colors hover:bg-surface-hover hover:text-text-primary',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
+ )}
+ >
+ <Download className="size-3" aria-hidden="true" />
+ {localize('com_ui_download')}
+ </button>
+ )}
+ </div>
+ )}
+ {/* `id` is optional on Mermaid; pass only when we have a real file_id
+ so the component generates a unique render target on its own. */}
+ {file.file_id ? <Mermaid id={file.file_id}>{text}</Mermaid> : <Mermaid>{text}</Mermaid>}
+ </div>
+ );
+});
+
+ToolMermaidArtifact.displayName = 'ToolMermaidArtifact';
+
+export default ToolMermaidArtifact;
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx
new file mode 100644
index 0000000000..317dc11844
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx
@@ -0,0 +1,394 @@
+import React from 'react';
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import { RecoilRoot, useRecoilValue } from 'recoil';
+import type { TAttachment } from 'librechat-data-provider';
+import Attachment, { AttachmentGroup } from '../Attachment';
+import store from '~/store';
+
+jest.mock('~/hooks', () => ({
+ useLocalize:
+ () =>
+ (key: string): string =>
+ key,
+}));
+
+jest.mock('../LogLink', () => ({
+ useAttachmentLink: () => ({ handleDownload: jest.fn() }),
+}));
+
+jest.mock('~/components/Chat/Input/Files/FileContainer', () => ({
+ __esModule: true,
+ default: ({ file }: { file: { filename?: string } }) => (
+ <div data-testid="file-container">{file.filename ?? ''}</div>
+ ),
+}));
+
+jest.mock('~/components/Chat/Input/Files/FilePreview', () => ({
+ __esModule: true,
+ default: () => <div data-testid="file-preview" />,
+}));
+
+jest.mock('~/components/Chat/Messages/Content/Image', () => ({
+ __esModule: true,
+ default: ({ altText }: { altText?: string }) => <img alt={altText ?? ''} data-testid="image" />,
+}));
+
+jest.mock('~/components/Messages/Content/Mermaid/Mermaid', () => ({
+ __esModule: true,
+ default: ({ children }: { children: string }) => (
+ <div data-testid="mermaid-render">{children}</div>
+ ),
+}));
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
+ getFileType: () => ({ paths: [], color: '', title: 'Artifact' }),
+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() },
+ isArtifactRoute: () => false,
+}));
+
+const baseAttachment = (overrides: Partial<TAttachment> = {}): TAttachment =>
+ ({
+ file_id: 'file-1',
+ filename: 'unset',
+ filepath: '/files/file-1',
+ type: 'application/octet-stream',
+ ...overrides,
+ }) as TAttachment;
+
+const renderWith = (ui: React.ReactElement) => render(<RecoilRoot>{ui}</RecoilRoot>);
+
+interface ArtifactsSnapshot {
+ visibility: boolean;
+ currentArtifactId: string | null;
+ artifactIds: string[];
+}
+
+const StateProbe = ({ onSnapshot }: { onSnapshot: (snap: ArtifactsSnapshot) => void }) => {
+ const visibility = useRecoilValue(store.artifactsVisibility);
+ const currentArtifactId = useRecoilValue(store.currentArtifactId);
+ const artifacts = useRecoilValue(store.artifactsState);
+ React.useEffect(() => {
+ onSnapshot({
+ visibility,
+ currentArtifactId,
+ artifactIds: Object.keys(artifacts ?? {}),
+ });
+ });
+ return null;
+};
+
+const renderWithProbe = (ui: React.ReactElement) => {
+ let snapshot: ArtifactsSnapshot = {
+ visibility: false,
+ currentArtifactId: null,
+ artifactIds: [],
+ };
+ const utils = render(
+ <RecoilRoot>
+ <StateProbe
+ onSnapshot={(snap) => {
+ snapshot = snap;
+ }}
+ />
+ {ui}
+ </RecoilRoot>,
+ );
+ return {
+ ...utils,
+ getSnapshot: () => snapshot,
+ };
+};
+
+describe('Attachment routing for tool artifacts', () => {
+ it('renders an HTML artifact card (panel artifact) and exposes a download control', () => {
+ const html = baseAttachment({
+ filename: 'index.html',
+ text: '<h1>hi</h1>',
+ } as Partial<TAttachment>);
+ renderWith(<Attachment attachment={html} />);
+
+ // Card body shows the artifact title
+ expect(screen.getByText('index.html')).toBeInTheDocument();
+ // Open-panel button carries aria-pressed (auto-focused on mount per the
+ // legacy auto-open behaviour).
+ expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument();
+ // Download button has the download aria-label
+ expect(
+ screen.getByRole('button', { name: /com_ui_download.*index\.html/i }),
+ ).toBeInTheDocument();
+ });
+
+ it('renders a JSX artifact card', () => {
+ const jsx = baseAttachment({
+ filename: 'App.tsx',
+ text: 'export default () => null;',
+ } as Partial<TAttachment>);
+ renderWith(<Attachment attachment={jsx} />);
+ expect(screen.getByText('App.tsx')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /com_ui_download.*App\.tsx/i })).toBeInTheDocument();
+ });
+
+ it('renders a Markdown artifact card', () => {
+ const md = baseAttachment({
+ filename: 'notes.md',
+ text: '# hi',
+ } as Partial<TAttachment>);
+ renderWith(<Attachment attachment={md} />);
+ expect(screen.getByText('notes.md')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /com_ui_download.*notes\.md/i })).toBeInTheDocument();
+ });
+
+ it.each([
+ ['readme.txt', 'Lorem ipsum'],
+ ['report.docx', 'Extracted document text'],
+ ['notes.odt', 'OpenDocument body text'],
+ ['slides.pptx', 'Slide titles and bullets'],
+ ])('renders a panel artifact card for %s (text/plain bucket)', (filename, text) => {
+ const file = baseAttachment({
+ filename,
+ text,
+ } as Partial<TAttachment>);
+ renderWith(<Attachment attachment={file} />);
+ expect(screen.getByText(filename)).toBeInTheDocument();
+ const downloadPattern = new RegExp(`com_ui_download.*${filename.replace('.', '\\.')}`, 'i');
+ expect(screen.getByRole('button', { name: downloadPattern })).toBeInTheDocument();
+ });
+
+ it('renders a Mermaid artifact through the standalone Mermaid component (not the panel)', () => {
+ const mmd = baseAttachment({
+ filename: 'flow.mmd',
+ text: 'graph TD\nA-->B',
+ } as Partial<TAttachment>);
+ renderWith(<Attachment attachment={mmd} />);
+ expect(screen.getByTestId('mermaid-render')).toHaveTextContent('graph TD');
+ // The card-style trigger should NOT be rendered for mermaid
+ expect(screen.queryByText('com_ui_artifact_click')).not.toBeInTheDocument();
+ });
+
+ it('falls through to the inline <pre> for unsupported text types (CSV)', () => {
+ const csv = baseAttachment({
+ filename: 'data.csv',
+ text: 'a,b,c\n1,2,3',
+ } as Partial<TAttachment>);
+ const { container } = renderWith(<Attachment attachment={csv} />);
+ expect(container.querySelector('pre')).not.toBeNull();
+ expect(screen.queryByTestId('mermaid-render')).not.toBeInTheDocument();
+ });
+});
+
+describe('ToolArtifactCard click behaviour', () => {
+ const html = (): TAttachment =>
+ baseAttachment({
+ file_id: 'html-1',
+ filename: 'index.html',
+ text: '<h1>hi</h1>',
+ } as Partial<TAttachment>);
+
+ // Auto-open invariant: rendering a tool-artifact card must (a) register
+ // the artifact in `artifactsState` and (b) focus it via
+ // `currentArtifactId`. With `artifactsVisibility` defaulting to `true`,
+ // this surfaces the latest tool artifact in the side panel — matching
+ // the legacy streaming-artifact UX.
+ it('registers and auto-focuses the artifact on mount', () => {
+ const { getSnapshot } = renderWithProbe(<Attachment attachment={html()} />);
+ const snap = getSnapshot();
+ expect(snap.artifactIds).toContain('tool-artifact-html-1');
+ expect(snap.currentArtifactId).toBe('tool-artifact-html-1');
+ });
+
+ it('toggles closed when the user clicks the (already-selected) card', () => {
+ const { getSnapshot } = renderWithProbe(<Attachment attachment={html()} />);
+ // Mount auto-focuses; the open button is in the pressed state.
+ const closeButton = screen.getByRole('button', { pressed: true });
+ act(() => {
+ fireEvent.click(closeButton);
+ });
+ const snap = getSnapshot();
+ expect(snap.currentArtifactId).toBeNull();
+ expect(snap.visibility).toBe(false);
+ // Self-heal effect keeps the artifact registered so re-opening works.
+ expect(snap.artifactIds).toContain('tool-artifact-html-1');
+ });
+
+ it('reopens after a close (regression: artifact still openable post-close)', () => {
+ const { getSnapshot } = renderWithProbe(<Attachment attachment={html()} />);
+ act(() => {
+ fireEvent.click(screen.getByRole('button', { pressed: true }));
+ });
+ expect(getSnapshot().visibility).toBe(false);
+ expect(getSnapshot().currentArtifactId).toBeNull();
+ // Click the now-unpressed open button again.
+ act(() => {
+ fireEvent.click(screen.getByRole('button', { pressed: false }));
+ });
+ const snap = getSnapshot();
+ expect(snap.currentArtifactId).toBe('tool-artifact-html-1');
+ expect(snap.visibility).toBe(true);
+ expect(snap.artifactIds).toContain('tool-artifact-html-1');
+ });
+
+ it('renders sibling cards with the same file_id in one group without React key collisions', () => {
+ // Real-world: rare but possible (a single tool call writing the same
+ // path twice). The dedup atom collapses duplicates to one rendered
+ // chip, but React still has to reconcile both children pre-effect —
+ // they need unique keys per occurrence so the wrong card-instance
+ // doesn't get reused (and effects reordered) during reconciliation.
+ const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
+ try {
+ const dup = baseAttachment({
+ file_id: 'dup-same-group',
+ filename: 'index.html',
+ text: '<h1>v1</h1>',
+ } as Partial<TAttachment>);
+ const { container } = renderWith(<AttachmentGroup attachments={[dup, dup]} />);
+ // Dedup atom keeps just one card visible.
+ expect(container.querySelectorAll('div[title="index.html"]')).toHaveLength(1);
+ // No "two children with the same key" warning fired.
+ const keyWarning = errorSpy.mock.calls.find(
+ (args) => typeof args[0] === 'string' && args[0].includes('same key'),
+ );
+ expect(keyWarning).toBeUndefined();
+ } finally {
+ errorSpy.mockRestore();
+ }
+ });
+
+ it('does not ping-pong artifactsState when same file_id has divergent content across turns', () => {
+ // Real production path: a code-execution file is overwritten across
+ // turns (same file_id, new content). Both ToolArtifactCard
+ // instances stay mounted; the older one renders null, but its
+ // self-heal effect still ran. Without claim-gating, the older card
+ // would observe the newer card's write through `existingEntry`,
+ // detect drift, and overwrite it back — old → new → old → ... in a
+ // loop. Gating registration on `isMyClaim` makes the write
+ // single-writer per id; final state must reflect the newer card.
+ interface ContentSnapshot {
+ ids: string[];
+ contentForDup: string | null;
+ }
+ let snapshot: ContentSnapshot = { ids: [], contentForDup: null };
+ const ContentProbe = () => {
+ const artifacts = useRecoilValue(store.artifactsState);
+ React.useEffect(() => {
+ const ids = Object.keys(artifacts ?? {});
+ const dup = artifacts?.['tool-artifact-dup-divergent'];
+ snapshot = { ids, contentForDup: dup?.content ?? null };
+ });
+ return null;
+ };
+ const older = baseAttachment({
+ file_id: 'dup-divergent',
+ filename: 'output.html',
+ text: '<h1>v1 (older)</h1>',
+ } as Partial<TAttachment>);
+ const newer = baseAttachment({
+ file_id: 'dup-divergent',
+ filename: 'output.html',
+ text: '<h1>v2 (newer)</h1>',
+ } as Partial<TAttachment>);
+ render(
+ <RecoilRoot>
+ <ContentProbe />
+ <AttachmentGroup attachments={[older]} />
+ <AttachmentGroup attachments={[newer]} />
+ </RecoilRoot>,
+ );
+ expect(snapshot.ids).toContain('tool-artifact-dup-divergent');
+ // Newer (claim-winner) content must win and stay won.
+ expect(snapshot.contentForDup).toBe('<h1>v2 (newer)</h1>');
+ });
+
+ it('dedups cards for the same file_id across separate AttachmentGroups (latest mount wins)', () => {
+ // Real scenario: each tool call renders its own AttachmentGroup; the
+ // same file (same file_id) shows up in two of them. We expect only
+ // ONE card chip in total — the dedup atom collapses them.
+ const dup = baseAttachment({
+ file_id: 'dup',
+ filename: 'index.html',
+ text: '<h1>v1</h1>',
+ } as Partial<TAttachment>);
+ const { container } = renderWith(
+ <>
+ <AttachmentGroup attachments={[dup]} />
+ <AttachmentGroup attachments={[dup]} />
+ </>,
+ );
+ const titles = container.querySelectorAll('div[title="index.html"]');
+ expect(titles.length).toBe(1);
+ });
+
+ it('dedups two mermaid cards for the same file_id across groups (latest mount wins)', () => {
+ const dupMermaid = baseAttachment({
+ file_id: 'mmd-dup',
+ filename: 'flow.mmd',
+ text: 'graph TD\nA-->B',
+ } as Partial<TAttachment>);
+ renderWith(
+ <>
+ <AttachmentGroup attachments={[dupMermaid]} />
+ <AttachmentGroup attachments={[dupMermaid]} />
+ </>,
+ );
+ expect(screen.getAllByTestId('mermaid-render')).toHaveLength(1);
+ });
+
+ it('focuses the latest card when multiple artifacts mount (legacy parity)', () => {
+ // Order: older first, newer last. Last-mounted should win currentArtifactId.
+ const olderHtml = baseAttachment({
+ file_id: 'older',
+ filename: 'old.html',
+ text: '<p>1</p>',
+ } as Partial<TAttachment>);
+ const newerHtml = baseAttachment({
+ file_id: 'newer',
+ filename: 'new.html',
+ text: '<p>2</p>',
+ } as Partial<TAttachment>);
+ const { getSnapshot } = renderWithProbe(
+ <AttachmentGroup attachments={[olderHtml, newerHtml]} />,
+ );
+ expect(getSnapshot().currentArtifactId).toBe('tool-artifact-newer');
+ expect(getSnapshot().artifactIds).toEqual(
+ expect.arrayContaining(['tool-artifact-older', 'tool-artifact-newer']),
+ );
+ });
+});
+
+describe('AttachmentGroup routing', () => {
+ it('renders separate buckets for panel artifacts, mermaid, text, and plain files', () => {
+ const attachments = [
+ baseAttachment({
+ file_id: 'a',
+ filename: 'index.html',
+ text: '<h1>hi</h1>',
+ } as Partial<TAttachment>),
+ baseAttachment({
+ file_id: 'b',
+ filename: 'flow.mmd',
+ text: 'graph TD\nA-->B',
+ } as Partial<TAttachment>),
+ baseAttachment({
+ file_id: 'c',
+ filename: 'data.csv',
+ text: 'a,b,c\n1,2,3',
+ } as Partial<TAttachment>),
+ baseAttachment({
+ file_id: 'd',
+ filename: 'archive.zip',
+ text: undefined as unknown as string,
+ } as Partial<TAttachment>),
+ ] as TAttachment[];
+
+ const { container } = renderWith(<AttachmentGroup attachments={attachments} />);
+
+ // Panel artifact card title
+ expect(screen.getByText('index.html')).toBeInTheDocument();
+ // Mermaid render
+ expect(screen.getByTestId('mermaid-render')).toBeInTheDocument();
+ // Inline text fallback for CSV
+ expect(container.querySelector('pre')).not.toBeNull();
+ // FileContainer for the plain zip (and potentially others)
+ expect(screen.getAllByTestId('file-container').length).toBeGreaterThan(0);
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx
new file mode 100644
index 0000000000..a397b8c21c
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx
@@ -0,0 +1,186 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import { RecoilRoot } from 'recoil';
+import type { TAttachment } from 'librechat-data-provider';
+import LogContent from '../LogContent';
+
+jest.mock('~/hooks', () => ({
+ useLocalize:
+ () =>
+ (key: string): string =>
+ key,
+}));
+
+jest.mock('../LogLink', () => ({
+ __esModule: true,
+ default: ({
+ href,
+ filename,
+ children,
+ }: {
+ href: string;
+ filename: string;
+ children?: React.ReactNode;
+ }) => (
+ <a data-testid="log-link" href={href} data-filename={filename}>
+ {children}
+ </a>
+ ),
+ useAttachmentLink: () => ({ handleDownload: jest.fn() }),
+}));
+
+jest.mock('~/components/Chat/Input/Files/FilePreview', () => ({
+ __esModule: true,
+ default: () => <div data-testid="file-preview" />,
+}));
+
+jest.mock('~/components/Chat/Messages/Content/Image', () => ({
+ __esModule: true,
+ default: ({ altText }: { altText?: string }) => <img alt={altText ?? ''} data-testid="image" />,
+}));
+
+jest.mock('~/components/Messages/Content/Mermaid/Mermaid', () => ({
+ __esModule: true,
+ default: ({ children }: { children: string }) => (
+ <div data-testid="mermaid-render">{children}</div>
+ ),
+}));
+
+jest.mock('~/utils', () => ({
+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
+ getFileType: () => ({ paths: [], color: '', title: 'Artifact' }),
+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() },
+ isArtifactRoute: () => false,
+}));
+
+const baseAttachment = (overrides: Partial<TAttachment> = {}): TAttachment =>
+ ({
+ file_id: 'file-1',
+ filename: 'unset',
+ filepath: '/files/file-1',
+ type: 'application/octet-stream',
+ ...overrides,
+ }) as TAttachment;
+
+const renderWith = (ui: React.ReactElement) => render(<RecoilRoot>{ui}</RecoilRoot>);
+
+describe('LogContent attachment routing', () => {
+ it('routes HTML attachments through ToolArtifactCard (panel)', () => {
+ const html = baseAttachment({
+ file_id: 'a',
+ filename: 'index.html',
+ text: '<h1>hi</h1>',
+ } as Partial<TAttachment>);
+ renderWith(<LogContent output="" attachments={[html]} />);
+ // The panel card carries an aria-pressed state; auto-focused on mount.
+ expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument();
+ expect(screen.getByText('index.html')).toBeInTheDocument();
+ });
+
+ it('routes mermaid attachments through the standalone Mermaid component', () => {
+ const mmd = baseAttachment({
+ file_id: 'b',
+ filename: 'flow.mmd',
+ text: 'graph TD\nA-->B',
+ } as Partial<TAttachment>);
+ renderWith(<LogContent output="" attachments={[mmd]} />);
+ expect(screen.getByTestId('mermaid-render')).toHaveTextContent('graph TD');
+ // Panel card not rendered for mermaid
+ expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+ });
+
+ it('routes text-bearing CSV through inline <pre>, not the panel', () => {
+ const csv = baseAttachment({
+ file_id: 'c',
+ filename: 'data.csv',
+ text: 'a,b,c\n1,2,3',
+ } as Partial<TAttachment>);
+ const { container } = renderWith(<LogContent output="" attachments={[csv]} />);
+ expect(container.querySelector('pre')).not.toBeNull();
+ expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+ expect(screen.queryByTestId('mermaid-render')).not.toBeInTheDocument();
+ });
+
+ it('routes files without text or panel-eligibility to the LogLink download', () => {
+ const zip = baseAttachment({
+ file_id: 'd',
+ filename: 'archive.zip',
+ type: 'application/zip',
+ } as Partial<TAttachment>);
+ renderWith(<LogContent output="" attachments={[zip]} />);
+ expect(screen.getByTestId('log-link')).toHaveAttribute('data-filename', 'archive.zip');
+ });
+
+ it('renders a panel card for pptx with empty text using the placeholder', () => {
+ // pptx text extraction is deferred; the artifact still routes through
+ // the panel and gets the localized placeholder content. Here the
+ // localize mock returns the key, so we assert by class/structure.
+ const pptx = baseAttachment({
+ file_id: 'e',
+ filename: 'slides.pptx',
+ text: undefined as unknown as string,
+ } as Partial<TAttachment>);
+ renderWith(<LogContent output="" attachments={[pptx]} />);
+ expect(screen.getByText('slides.pptx')).toBeInTheDocument();
+ });
+
+ it('routes an expired panel-eligible attachment through the legacy expired path', () => {
+ // Without this gate, an expired pptx/html/etc. would render as a
+ // clickable artifact card backed by a dead download link. The
+ // legacy "download expired" message must win for any panel-eligible
+ // entry whose `expiresAt` is in the past.
+ const expired = baseAttachment({
+ file_id: 'x-expired',
+ filename: 'slides.pptx',
+ text: undefined as unknown as string,
+ expiresAt: Date.now() - 60_000,
+ } as Partial<TAttachment>);
+ renderWith(<LogContent output="" attachments={[expired]} />);
+ // No panel card and no log-link (the expired branch returns plain text).
+ expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+ expect(screen.queryByTestId('log-link')).not.toBeInTheDocument();
+ // The localize mock returns the key, so we assert the expired-message key
+ // appears in the rendered output alongside the filename.
+ expect(screen.getByText(/slides\.pptx com_download_expired/)).toBeInTheDocument();
+ });
+
+ it('still routes a non-expired panel attachment through the panel', () => {
+ const fresh = baseAttachment({
+ file_id: 'x-fresh',
+ filename: 'index.html',
+ text: '<h1>hi</h1>',
+ expiresAt: Date.now() + 60_000,
+ } as Partial<TAttachment>);
+ renderWith(<LogContent output="" attachments={[fresh]} />);
+ expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument();
+ });
+
+ it('splits a mixed list into the right buckets', () => {
+ const attachments = [
+ baseAttachment({
+ file_id: 'h',
+ filename: 'index.html',
+ text: '<h1>hi</h1>',
+ } as Partial<TAttachment>),
+ baseAttachment({
+ file_id: 'm',
+ filename: 'flow.mmd',
+ text: 'graph TD\nA-->B',
+ } as Partial<TAttachment>),
+ baseAttachment({
+ file_id: 't',
+ filename: 'notes.csv',
+ text: 'a,b\n1,2',
+ } as Partial<TAttachment>),
+ ] as TAttachment[];
+ const { container } = renderWith(
+ <LogContent output="" attachments={attachments} renderImages={true} />,
+ );
+ // panel artifact card present (find the html title)
+ expect(screen.getByText('index.html')).toBeInTheDocument();
+ // mermaid render present
+ expect(screen.getByTestId('mermaid-render')).toBeInTheDocument();
+ // CSV inline pre present
+ expect(container.querySelector('pre')).not.toBeNull();
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx
index 0f6c52a05a..7a6d0b003e 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx
@@ -34,8 +34,23 @@ jest.mock('~/components/Chat/Messages/Content/Image', () => ({
default: ({ altText }: { altText?: string }) => <img alt={altText ?? ''} data-testid="image" />,
}));
+jest.mock('~/components/Messages/Content/Mermaid/Mermaid', () => ({
+ __esModule: true,
+ default: ({ children }: { children: string }) => (
+ <div data-testid="mermaid-render">{children}</div>
+ ),
+}));
+
+jest.mock('~/components/Chat/Input/Files/FilePreview', () => ({
+ __esModule: true,
+ default: () => <div data-testid="file-preview" />,
+}));
+
jest.mock('~/utils', () => ({
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
+ getFileType: () => ({ paths: [], color: '', title: 'Artifact' }),
+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn() },
+ isArtifactRoute: () => false,
}));
const textAttachment = (overrides: Partial<TAttachment> = {}): TAttachment =>
@@ -148,7 +163,10 @@ describe('AttachmentGroup', () => {
});
it('routes text-bearing attachments through the text rendering path', () => {
- const attachments = [textAttachment({ file_id: 'a', filename: 'a.txt' })] as TAttachment[];
+ // `.csv` is text-bearing but not artifact-eligible (CSV gets a
+ // dedicated viewer in a follow-up), so it falls through to the
+ // inline <pre> renderer rather than the side panel card.
+ const attachments = [textAttachment({ file_id: 'a', filename: 'a.csv' })] as TAttachment[];
const { container } = render(<AttachmentGroup attachments={attachments} />);
expect(container.querySelector('pre')).not.toBeNull();
});
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/attachmentTypes.test.ts b/client/src/components/Chat/Messages/Content/Parts/__tests__/attachmentTypes.test.ts
index ecbbd19eff..43354e2e11 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/attachmentTypes.test.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/attachmentTypes.test.ts
@@ -1,5 +1,6 @@
import type { TAttachment } from 'librechat-data-provider';
-import { isImageAttachment, isTextAttachment } from '../attachmentTypes';
+import { TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
+import { artifactTypeForAttachment, isImageAttachment, isTextAttachment } from '../attachmentTypes';
const baseAttachment = (overrides: Partial<TAttachment> = {}): TAttachment =>
({
@@ -91,3 +92,72 @@ describe('isTextAttachment', () => {
expect(isTextAttachment(attachment)).toBe(false);
});
});
+
+describe('artifactTypeForAttachment', () => {
+ it.each([
+ ['index.html', 'text/html'],
+ ['site.htm', 'text/html'],
+ ['App.jsx', 'application/vnd.react'],
+ ['App.tsx', 'application/vnd.react'],
+ ['notes.md', 'text/markdown'],
+ ['readme.markdown', 'text/markdown'],
+ ['flow.mmd', 'application/vnd.mermaid'],
+ ['flow.mermaid', 'application/vnd.mermaid'],
+ ])('classifies %s as %s', (filename, expected) => {
+ const attachment = baseAttachment({
+ filename,
+ text: 'content',
+ } as Partial<TAttachment>);
+ expect(artifactTypeForAttachment(attachment)).toBe(expected);
+ });
+
+ it('falls back to MIME for HTML when extension is missing', () => {
+ const attachment = baseAttachment({
+ filename: 'noext',
+ type: 'text/html',
+ text: 'content',
+ } as unknown as Partial<TAttachment>);
+ expect(artifactTypeForAttachment(attachment)).toBe('text/html');
+ });
+
+ it('returns null when there is no text content', () => {
+ const attachment = baseAttachment({ filename: 'index.html' });
+ expect(artifactTypeForAttachment(attachment)).toBeNull();
+ });
+
+ it('returns null for unsupported extensions', () => {
+ const attachment = baseAttachment({
+ filename: 'data.csv',
+ text: 'a,b,c',
+ } as Partial<TAttachment>);
+ expect(artifactTypeForAttachment(attachment)).toBeNull();
+ });
+});
+
+describe('artifactTypeForAttachment branching', () => {
+ it('returns the mermaid type for .mmd files', () => {
+ const attachment = baseAttachment({
+ filename: 'flow.mmd',
+ text: 'graph TD\nA-->B',
+ } as Partial<TAttachment>);
+ expect(artifactTypeForAttachment(attachment)).toBe(TOOL_ARTIFACT_TYPES.MERMAID);
+ });
+
+ it.each([
+ ['index.html', TOOL_ARTIFACT_TYPES.HTML],
+ ['App.tsx', TOOL_ARTIFACT_TYPES.REACT],
+ ['notes.md', TOOL_ARTIFACT_TYPES.MARKDOWN],
+ ])('returns the panel type for %s (not mermaid)', (filename, expected) => {
+ const attachment = baseAttachment({
+ filename,
+ text: 'content',
+ } as Partial<TAttachment>);
+ const type = artifactTypeForAttachment(attachment);
+ expect(type).toBe(expected);
+ expect(type).not.toBe(TOOL_ARTIFACT_TYPES.MERMAID);
+ });
+
+ it('returns null when there is no text', () => {
+ expect(artifactTypeForAttachment(baseAttachment({ filename: 'index.html' }))).toBeNull();
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/Parts/attachmentTypes.ts b/client/src/components/Chat/Messages/Content/Parts/attachmentTypes.ts
index a53b882394..2dde3b2463 100644
--- a/client/src/components/Chat/Messages/Content/Parts/attachmentTypes.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/attachmentTypes.ts
@@ -1,5 +1,7 @@
import { imageExtRegex } from 'librechat-data-provider';
import type { TAttachment, TAttachmentMetadata, TFile } from 'librechat-data-provider';
+import type { ToolArtifactType } from '~/utils/artifacts';
+import { detectArtifactTypeFromFile } from '~/utils/artifacts';
/**
* An attachment is treated as an image only when it has the dimensions and
@@ -25,3 +27,33 @@ export const isTextAttachment = (attachment: TAttachment): boolean => {
const { text } = attachment as TFile & TAttachmentMetadata;
return typeof text === 'string' && text.length > 0;
};
+
+/**
+ * The artifact MIME type a tool-output attachment maps to, or `null` if
+ * we don't have a viewer for it. Layered on `detectArtifactTypeFromFile`
+ * so the routing logic stays in one place; classifying happens here so
+ * the message-render code reads cleanly.
+ */
+export const artifactTypeForAttachment = (attachment: TAttachment): ToolArtifactType | null => {
+ const file = attachment as TFile & TAttachmentMetadata;
+ return detectArtifactTypeFromFile(file);
+};
+
+/**
+ * Per-rendered-occurrence React key for an attachment. The `file_id`
+ * provides stability across re-renders for the common case (each tool
+ * call's output has unique file ids), and the index suffix disambiguates
+ * the rare case where the same `file_id` appears twice in one bucket
+ * (e.g. a tool call writing the same path twice). Without the suffix the
+ * duplicates would share a key and React would reconcile them as a single
+ * child — undermining the latest-mention dedup since the two cards would
+ * share an instance instead of contesting the claim.
+ */
+export const renderAttachmentKey = (
+ prefix: string,
+ attachment: TAttachment,
+ index: number,
+): string => {
+ const fileId = (attachment as TFile & TAttachmentMetadata).file_id;
+ return `${prefix}-${fileId ?? 'noid'}-${index}`;
+};
diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx
index 7daee0f18a..ca1142dd45 100644
--- a/client/src/components/Chat/Presentation.tsx
+++ b/client/src/components/Chat/Presentation.tsx
@@ -2,6 +2,7 @@ import { useEffect, useMemo } from 'react';
import { useRecoilValue } from 'recoil';
import { FileSources, LocalStorageKeys } from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
+import useResetArtifactsOnConversationChange from '~/hooks/Artifacts/useResetArtifactsOnConversationChange';
import DragDropWrapper from '~/components/Chat/Input/Files/DragDropWrapper';
import { EditorProvider, ArtifactsProvider } from '~/Providers';
import { useDeleteFilesMutation } from '~/data-provider';
@@ -14,6 +15,8 @@ export default function Presentation({ children }: { children: React.ReactNode }
const artifacts = useRecoilValue(store.artifactsState);
const artifactsVisibility = useRecoilValue(store.artifactsVisibility);
+ useResetArtifactsOnConversationChange();
+
const setFilesToDelete = useSetFilesToDelete();
const { mutateAsync } = useDeleteFilesMutation({
diff --git a/client/src/hooks/Artifacts/__tests__/useResetArtifactsOnConversationChange.test.tsx b/client/src/hooks/Artifacts/__tests__/useResetArtifactsOnConversationChange.test.tsx
new file mode 100644
index 0000000000..2a41257568
--- /dev/null
+++ b/client/src/hooks/Artifacts/__tests__/useResetArtifactsOnConversationChange.test.tsx
@@ -0,0 +1,129 @@
+import React from 'react';
+import { act, render } from '@testing-library/react';
+import { RecoilRoot, useRecoilCallback, useSetRecoilState } from 'recoil';
+import type { MutableSnapshot } from 'recoil';
+import type { Artifact } from '~/common';
+import type { TConversation } from 'librechat-data-provider';
+import useResetArtifactsOnConversationChange from '../useResetArtifactsOnConversationChange';
+import store from '~/store';
+
+const buildArtifact = (id: string): Artifact => ({
+ id,
+ title: id,
+ type: 'text/html',
+ content: '<h1>x</h1>',
+ messageId: 'msg-1',
+ lastUpdateTime: 1,
+});
+
+const buildConversation = (conversationId: string | null): TConversation =>
+ ({ conversationId }) as TConversation;
+
+interface HarnessHandle {
+ setConversation: (conversationId: string | null) => void;
+ readArtifacts: () => Record<string, Artifact | undefined> | null;
+ readCurrentId: () => string | null;
+}
+
+const Harness = ({ handleRef }: { handleRef: React.MutableRefObject<HarnessHandle | null> }) => {
+ useResetArtifactsOnConversationChange();
+ const setConvo = useSetRecoilState(store.conversationByIndex(0));
+ // useRecoilCallback's snapshot is read fresh at call time, so the test
+ // sees the latest committed atom values rather than a stale render-time
+ // closure.
+ const readArtifacts = useRecoilCallback(
+ ({ snapshot }) =>
+ () =>
+ snapshot.getLoadable(store.artifactsState).getValue(),
+ [],
+ );
+ const readCurrentId = useRecoilCallback(
+ ({ snapshot }) =>
+ () =>
+ snapshot.getLoadable(store.currentArtifactId).getValue(),
+ [],
+ );
+
+ if (handleRef.current == null) {
+ handleRef.current = {
+ setConversation: (conversationId) => setConvo(buildConversation(conversationId)),
+ readArtifacts,
+ readCurrentId,
+ };
+ }
+ return null;
+};
+
+const renderHarness = (initial: {
+ conversationId: string | null;
+ artifacts: Record<string, Artifact>;
+ currentId: string | null;
+}) => {
+ const initializeState = (snapshot: MutableSnapshot) => {
+ snapshot.set(store.conversationByIndex(0), buildConversation(initial.conversationId));
+ snapshot.set(store.artifactsState, initial.artifacts);
+ snapshot.set(store.currentArtifactId, initial.currentId);
+ };
+ const handleRef: React.MutableRefObject<HarnessHandle | null> = { current: null };
+ render(
+ <RecoilRoot initializeState={initializeState}>
+ <Harness handleRef={handleRef} />
+ </RecoilRoot>,
+ );
+ if (!handleRef.current) {
+ throw new Error('Harness did not attach handle');
+ }
+ return handleRef.current;
+};
+
+describe('useResetArtifactsOnConversationChange', () => {
+ it('does not reset on first render (no previous conversation to compare against)', () => {
+ const handle = renderHarness({
+ conversationId: 'conv-A',
+ artifacts: { 'art-1': buildArtifact('art-1') },
+ currentId: 'art-1',
+ });
+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });
+ expect(handle.readCurrentId()).toBe('art-1');
+ });
+
+ it('preserves artifacts when the conversation id stays the same', () => {
+ const handle = renderHarness({
+ conversationId: 'conv-A',
+ artifacts: { 'art-1': buildArtifact('art-1') },
+ currentId: 'art-1',
+ });
+ act(() => handle.setConversation('conv-A'));
+ expect(handle.readArtifacts()).toEqual({ 'art-1': buildArtifact('art-1') });
+ expect(handle.readCurrentId()).toBe('art-1');
+ });
+
+ it('wipes artifactsState and currentArtifactId when the conversation id changes', () => {
+ // Reproduces the codex-flagged leak: panel was closed in conv-A, the
+ // ToolArtifactCard's self-heal effect re-registered while
+ // artifactsVisibility stayed false, and then the user switched to
+ // conv-B. Without this hook the next panel open in conv-B would show
+ // conv-A's artifacts in the version list.
+ const handle = renderHarness({
+ conversationId: 'conv-A',
+ artifacts: { 'leftover-from-A': buildArtifact('leftover-from-A') },
+ currentId: 'leftover-from-A',
+ });
+ act(() => handle.setConversation('conv-B'));
+ expect(handle.readArtifacts()).toBeNull();
+ expect(handle.readCurrentId()).toBeNull();
+ });
+
+ it('treats an initial null → defined transition as a first observation, not a switch', () => {
+ // Initial conversation can flicker through `null` while a fresh chat
+ // is still loading. Treating that null as a "previous" id would
+ // wipe the very first artifacts that arrive.
+ const handle = renderHarness({
+ conversationId: null,
+ artifacts: {},
+ currentId: null,
+ });
+ act(() => handle.setConversation('conv-A'));
+ expect(handle.readArtifacts()).toEqual({});
+ });
+});
diff --git a/client/src/hooks/Artifacts/useResetArtifactsOnConversationChange.ts b/client/src/hooks/Artifacts/useResetArtifactsOnConversationChange.ts
new file mode 100644
index 0000000000..81151fcc1f
--- /dev/null
+++ b/client/src/hooks/Artifacts/useResetArtifactsOnConversationChange.ts
@@ -0,0 +1,30 @@
+import { useEffect, useRef } from 'react';
+import { useRecoilValue, useResetRecoilState } from 'recoil';
+import store from '~/store';
+
+/**
+ * Wipes `artifactsState` / `currentArtifactId` whenever the active
+ * conversation changes. `useArtifacts` already runs this cleanup, but
+ * only while the side panel is mounted — so without a top-level guard,
+ * tool-artifact cards that self-heal their entries while the panel is
+ * closed would leak into the next conversation's panel on open. The
+ * matching cards for the new conversation re-register via their own
+ * self-heal subscription after this wipe lands.
+ */
+export default function useResetArtifactsOnConversationChange(): void {
+ const conversationId = useRecoilValue(store.conversationIdByIndex(0));
+ const resetArtifacts = useResetRecoilState(store.artifactsState);
+ const resetCurrentArtifactId = useResetRecoilState(store.currentArtifactId);
+ const prevConversationIdRef = useRef<string | null>(null);
+
+ useEffect(() => {
+ const prev = prevConversationIdRef.current;
+ const next = conversationId ?? null;
+ prevConversationIdRef.current = next;
+ if (prev == null || prev === next) {
+ return;
+ }
+ resetArtifacts();
+ resetCurrentArtifactId();
+ }, [conversationId, resetArtifacts, resetCurrentArtifactId]);
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index c59f3f203b..bdd98d0558 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -769,6 +769,7 @@
"com_ui_archive_delete_error": "Failed to delete archived conversation",
"com_ui_archive_error": "Failed to archive conversation",
"com_ui_artifact_click": "Click to open",
+ "com_ui_artifact_preview_pending": "_Preview not available yet — click **Download** to view the file._",
"com_ui_artifacts": "Artifacts",
"com_ui_artifacts_options": "Artifacts Options",
"com_ui_artifacts_toggle": "Toggle Artifacts UI",
diff --git a/client/src/store/artifacts.ts b/client/src/store/artifacts.ts
index d8a23d1dbe..2222b3a1c0 100644
--- a/client/src/store/artifacts.ts
+++ b/client/src/store/artifacts.ts
@@ -1,4 +1,4 @@
-import { atom } from 'recoil';
+import { atom, atomFamily, selectorFamily } from 'recoil';
import { logger } from '~/utils';
import type { Artifact } from '~/common';
@@ -47,6 +47,47 @@ export const artifactsVisibility = atom<boolean>({
] as const,
});
+/**
+ * Per-artifact-id claim used by `ToolArtifactCard` to dedup the same file
+ * across tool calls / messages. Holds the unique component-instance key
+ * of whichever card most recently mounted for that id; cards whose key
+ * doesn't match return `null` so the same chip doesn't render twice.
+ *
+ * Keyed by `artifact.id` (which is `tool-artifact-${file_id}`), so each
+ * card subscribes only to its own slice — adding or removing a claim
+ * for one artifact never re-renders cards for unrelated artifacts.
+ *
+ * Lifetime: atom entries remain in the family map even after a card
+ * unmounts (Recoil doesn't GC `atomFamily` entries). Card unmount
+ * resets the value to `null`, so the residual cost per artifact is one
+ * key + a `null` value — negligible at typical session scale (dozens
+ * of files per conversation). If this ever becomes a memory concern
+ * we can fold the family into a single `Record` atom and reset it from
+ * `useArtifacts`'s conversation-change cleanup.
+ */
+export const toolArtifactClaim = atomFamily<string | null, string>({
+ key: 'toolArtifactClaim',
+ default: null,
+});
+
+/**
+ * Per-artifact-id slice of `artifactsState`. Used by `ToolArtifactCard`
+ * for self-heal registration: the card subscribes only to its own
+ * entry, so the registration effect re-runs deterministically when the
+ * entry is wiped (e.g. by `useArtifacts`'s panel-unmount cleanup) or
+ * when the artifact's content meaningfully changes — instead of firing
+ * on every parent render via a no-deps `useEffect`.
+ */
+export const artifactByIdSelector = selectorFamily<Artifact | undefined, string>({
+ key: 'artifactById',
+ get:
+ (artifactId) =>
+ ({ get }) => {
+ const artifacts = get(artifactsState);
+ return artifacts?.[artifactId];
+ },
+});
+
export const visibleArtifacts = atom<Record<string, Artifact | undefined> | null>({
key: 'visibleArtifacts',
default: null,
diff --git a/client/src/utils/__tests__/artifacts.test.ts b/client/src/utils/__tests__/artifacts.test.ts
index bf5c1919c7..2d1216995c 100644
--- a/client/src/utils/__tests__/artifacts.test.ts
+++ b/client/src/utils/__tests__/artifacts.test.ts
@@ -1,4 +1,9 @@
-import { buildSandpackOptions } from '../artifacts';
+import {
+ buildSandpackOptions,
+ detectArtifactTypeFromFile,
+ fileToArtifact,
+ TOOL_ARTIFACT_TYPES,
+} from '../artifacts';
const TAILWIND_CDN = 'https://cdn.tailwindcss.com/3.4.17#tailwind.js';
@@ -36,3 +41,211 @@ describe('buildSandpackOptions', () => {
expect(options?.bundlerURL).toBeUndefined();
});
});
+
+describe('detectArtifactTypeFromFile', () => {
+ it.each([
+ ['index.html', TOOL_ARTIFACT_TYPES.HTML],
+ ['index.HTM', TOOL_ARTIFACT_TYPES.HTML],
+ ['App.jsx', TOOL_ARTIFACT_TYPES.REACT],
+ ['App.tsx', TOOL_ARTIFACT_TYPES.REACT],
+ ['notes.md', TOOL_ARTIFACT_TYPES.MARKDOWN],
+ ['notes.markdown', TOOL_ARTIFACT_TYPES.MARKDOWN],
+ ['notes.mdx', TOOL_ARTIFACT_TYPES.MARKDOWN],
+ ['flow.mmd', TOOL_ARTIFACT_TYPES.MERMAID],
+ ['flow.mermaid', TOOL_ARTIFACT_TYPES.MERMAID],
+ ['readme.txt', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ['report.docx', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ['notes.odt', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ['slides.pptx', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ])('classifies %s by extension', (filename, expected) => {
+ expect(detectArtifactTypeFromFile({ filename, type: '', text: 'content' })).toBe(expected);
+ });
+
+ it.each([
+ ['index.html', TOOL_ARTIFACT_TYPES.HTML],
+ ['App.tsx', TOOL_ARTIFACT_TYPES.REACT],
+ ['flow.mmd', TOOL_ARTIFACT_TYPES.MERMAID],
+ ])('returns null when %s has no text (%s viewer needs real content)', (filename) => {
+ expect(detectArtifactTypeFromFile({ filename, type: '', text: '' })).toBeNull();
+ expect(detectArtifactTypeFromFile({ filename, type: '', text: undefined })).toBeNull();
+ });
+
+ it.each([
+ ['readme.txt', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ['slides.pptx', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ['report.docx', TOOL_ARTIFACT_TYPES.PLAIN_TEXT],
+ ['notes.md', TOOL_ARTIFACT_TYPES.MARKDOWN],
+ ])(
+ 'still routes %s through the panel without text (deferred-extraction case)',
+ (filename, expected) => {
+ expect(detectArtifactTypeFromFile({ filename, type: '', text: '' })).toBe(expected);
+ expect(detectArtifactTypeFromFile({ filename, type: '', text: undefined })).toBe(expected);
+ },
+ );
+
+ it('falls back to MIME when the extension is unknown', () => {
+ expect(detectArtifactTypeFromFile({ filename: 'noext', type: 'text/html', text: 'x' })).toBe(
+ TOOL_ARTIFACT_TYPES.HTML,
+ );
+ expect(
+ detectArtifactTypeFromFile({ filename: 'noext', type: 'text/markdown', text: 'x' }),
+ ).toBe(TOOL_ARTIFACT_TYPES.MARKDOWN);
+ });
+
+ it.each([
+ ['text/html; charset=utf-8', TOOL_ARTIFACT_TYPES.HTML],
+ ['text/html;charset=utf-8', TOOL_ARTIFACT_TYPES.HTML],
+ ['TEXT/HTML; CHARSET=UTF-8', TOOL_ARTIFACT_TYPES.HTML],
+ ['text/markdown; charset=utf-8', TOOL_ARTIFACT_TYPES.MARKDOWN],
+ ['application/vnd.react; foo=bar', TOOL_ARTIFACT_TYPES.REACT],
+ ])('strips MIME parameters before lookup (%s)', (mime, expected) => {
+ expect(detectArtifactTypeFromFile({ filename: 'noext', type: mime, text: 'x' })).toBe(expected);
+ });
+
+ it.each([
+ ['application/vnd.react'],
+ ['application/vnd.ant.react'],
+ ['application/vnd.mermaid'],
+ ['application/vnd.code-html'],
+ ])('routes %s by MIME alone', (mime) => {
+ const result = detectArtifactTypeFromFile({ filename: 'noext', type: mime, text: 'x' });
+ expect(result).not.toBeNull();
+ });
+
+ it('returns null for unsupported types', () => {
+ expect(
+ detectArtifactTypeFromFile({ filename: 'output.csv', type: 'text/csv', text: 'a,b' }),
+ ).toBeNull();
+ expect(
+ detectArtifactTypeFromFile({ filename: 'doc.pdf', type: 'application/pdf', text: 'x' }),
+ ).toBeNull();
+ });
+
+ it('does not route bare text/plain MIME without a recognized extension', () => {
+ // Files with text/plain MIME and an unrecognized name (extensionless
+ // scripts, .env, etc.) should keep the inline <pre> rendering, not
+ // hijack the artifact panel.
+ expect(
+ detectArtifactTypeFromFile({ filename: 'unknown', type: 'text/plain', text: 'x' }),
+ ).toBeNull();
+ expect(
+ detectArtifactTypeFromFile({ filename: '.env', type: 'text/plain', text: 'KEY=value' }),
+ ).toBeNull();
+ });
+});
+
+describe('fileToArtifact', () => {
+ const baseFile = {
+ file_id: 'fid-1',
+ filename: 'index.html',
+ type: 'text/html',
+ text: '<h1>hi</h1>',
+ messageId: 'msg-1',
+ updatedAt: '2026-04-26T10:00:00.000Z',
+ };
+
+ it('builds an Artifact for supported files, with stable id derived from file_id', () => {
+ const artifact = fileToArtifact(baseFile);
+ expect(artifact).not.toBeNull();
+ expect(artifact!.id).toBe('tool-artifact-fid-1');
+ expect(artifact!.type).toBe(TOOL_ARTIFACT_TYPES.HTML);
+ expect(artifact!.title).toBe('index.html');
+ expect(artifact!.content).toBe('<h1>hi</h1>');
+ expect(artifact!.messageId).toBe('msg-1');
+ expect(artifact!.lastUpdateTime).toBe(new Date(baseFile.updatedAt).getTime());
+ });
+
+ it('returns null for unsupported types so callers can fall through', () => {
+ expect(fileToArtifact({ ...baseFile, filename: 'data.csv', type: 'text/csv' })).toBeNull();
+ });
+
+ it('returns null when an HTML/React/Mermaid file has no text', () => {
+ expect(fileToArtifact({ ...baseFile, text: '' })).toBeNull();
+ expect(fileToArtifact({ ...baseFile, filename: 'App.tsx', type: '', text: '' })).toBeNull();
+ expect(fileToArtifact({ ...baseFile, filename: 'flow.mmd', type: '', text: '' })).toBeNull();
+ });
+
+ it('uses the caller-provided placeholder when a deferred-extraction file has no text', () => {
+ // Backend extractor returns null for pptx (deferred). Client sees
+ // `text === null` and substitutes the localized placeholder.
+ const artifact = fileToArtifact(
+ {
+ ...baseFile,
+ filename: 'slides.pptx',
+ type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ text: null as unknown as string,
+ },
+ { placeholder: '_Coming soon_' },
+ );
+ expect(artifact).not.toBeNull();
+ expect(artifact!.type).toBe(TOOL_ARTIFACT_TYPES.PLAIN_TEXT);
+ expect(artifact!.content).toBe('_Coming soon_');
+ });
+
+ it('falls back to empty content when no placeholder is supplied and text is missing', () => {
+ const artifact = fileToArtifact({
+ ...baseFile,
+ filename: 'slides.pptx',
+ type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ text: undefined,
+ });
+ expect(artifact!.content).toBe('');
+ });
+
+ it('preserves an empty string as legitimate content (does not fall through to placeholder)', () => {
+ // A user can write a 0-byte `.md` or `.txt`; that's a valid artifact
+ // with empty content, not "extraction unavailable."
+ const artifact = fileToArtifact(
+ { ...baseFile, filename: 'empty.md', type: 'text/markdown', text: '' },
+ { placeholder: '_should not appear_' },
+ );
+ expect(artifact!.content).toBe('');
+ });
+
+ it('uses real text when present for deferred-extraction file types', () => {
+ const artifact = fileToArtifact({
+ ...baseFile,
+ filename: 'slides.pptx',
+ type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ text: 'Slide 1: Intro\nSlide 2: Outro',
+ });
+ expect(artifact!.content).toBe('Slide 1: Intro\nSlide 2: Outro');
+ });
+
+ it('skips re-classification when preClassifiedType is provided', () => {
+ // Filename would normally classify as html, but caller forces plain-text.
+ const artifact = fileToArtifact(
+ { ...baseFile, filename: 'index.html', type: 'text/html', text: 'x' },
+ { preClassifiedType: TOOL_ARTIFACT_TYPES.PLAIN_TEXT },
+ );
+ expect(artifact!.type).toBe(TOOL_ARTIFACT_TYPES.PLAIN_TEXT);
+ });
+
+ it.each([[TOOL_ARTIFACT_TYPES.HTML], [TOOL_ARTIFACT_TYPES.REACT], [TOOL_ARTIFACT_TYPES.MERMAID]])(
+ 'returns null when preClassifiedType=%s is paired with empty text (defense in depth)',
+ (preClassifiedType) => {
+ // Bypassing classification with a strict-viewer type but no text
+ // would otherwise hand sandpack/mermaid.js an empty buffer that
+ // throws. Internal guard catches it before construction.
+ const artifact = fileToArtifact(
+ { ...baseFile, filename: 'whatever', type: '', text: '' },
+ { preClassifiedType },
+ );
+ expect(artifact).toBeNull();
+ },
+ );
+
+ it('falls back to createdAt when updatedAt is missing', () => {
+ const artifact = fileToArtifact({
+ ...baseFile,
+ updatedAt: undefined,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ });
+ expect(artifact!.lastUpdateTime).toBe(new Date('2026-01-01T00:00:00.000Z').getTime());
+ });
+
+ it('falls back to filename when file_id is missing', () => {
+ const artifact = fileToArtifact({ ...baseFile, file_id: undefined as unknown as string });
+ expect(artifact!.id).toBe('tool-artifact-index.html');
+ });
+});
diff --git a/client/src/utils/artifacts.ts b/client/src/utils/artifacts.ts
index 2ca02422a2..88fe1f688a 100644
--- a/client/src/utils/artifacts.ts
+++ b/client/src/utils/artifacts.ts
@@ -4,7 +4,8 @@ import type {
SandpackProviderProps,
SandpackPredefinedTemplate,
} from '@codesandbox/sandpack-react';
-import type { TStartupConfig } from 'librechat-data-provider';
+import type { TStartupConfig, TAttachment, TFile } from 'librechat-data-provider';
+import type { Artifact } from '~/common';
const artifactFilename = {
'application/vnd.react': 'App.tsx',
@@ -162,6 +163,208 @@ export function buildSandpackOptions(
};
}
+/**
+ * Artifact MIME types we currently know how to render in the side panel
+ * (or, for mermaid, inline). Plain text covers files we can show as raw
+ * content even without a dedicated viewer (txt, docx-extracted text, …);
+ * `useArtifactProps` routes `text/plain` through the markdown template
+ * so the panel renders them cleanly.
+ */
+export const TOOL_ARTIFACT_TYPES = {
+ HTML: 'text/html',
+ REACT: 'application/vnd.react',
+ MARKDOWN: 'text/markdown',
+ MERMAID: 'application/vnd.mermaid',
+ PLAIN_TEXT: 'text/plain',
+} as const;
+
+export type ToolArtifactType = (typeof TOOL_ARTIFACT_TYPES)[keyof typeof TOOL_ARTIFACT_TYPES];
+
+const EXTENSION_TO_TOOL_ARTIFACT_TYPE: Record<string, ToolArtifactType> = {
+ html: TOOL_ARTIFACT_TYPES.HTML,
+ htm: TOOL_ARTIFACT_TYPES.HTML,
+ jsx: TOOL_ARTIFACT_TYPES.REACT,
+ tsx: TOOL_ARTIFACT_TYPES.REACT,
+ md: TOOL_ARTIFACT_TYPES.MARKDOWN,
+ markdown: TOOL_ARTIFACT_TYPES.MARKDOWN,
+ mdx: TOOL_ARTIFACT_TYPES.MARKDOWN,
+ mmd: TOOL_ARTIFACT_TYPES.MERMAID,
+ mermaid: TOOL_ARTIFACT_TYPES.MERMAID,
+ // Plain text + office documents fall through to the markdown-style
+ // viewer until dedicated renderers land. `pptx` is wired up here so
+ // the routing fires as soon as backend text extraction is added.
+ txt: TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+ docx: TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+ odt: TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+ pptx: TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+};
+
+const extensionOf = (filename: string | undefined): string => {
+ if (!filename) {
+ return '';
+ }
+ const dot = filename.lastIndexOf('.');
+ if (dot < 0 || dot === filename.length - 1) {
+ return '';
+ }
+ return filename.slice(dot + 1).toLowerCase();
+};
+
+/** Strip charset / boundary parameters so we can do exact MIME comparisons. */
+const baseMime = (mime: string | undefined): string => {
+ if (!mime) {
+ return '';
+ }
+ const semi = mime.indexOf(';');
+ return (semi < 0 ? mime : mime.slice(0, semi)).trim().toLowerCase();
+};
+
+const MIME_TO_TOOL_ARTIFACT_TYPE: Record<string, ToolArtifactType> = {
+ 'text/html': TOOL_ARTIFACT_TYPES.HTML,
+ 'application/vnd.code-html': TOOL_ARTIFACT_TYPES.HTML,
+ 'text/markdown': TOOL_ARTIFACT_TYPES.MARKDOWN,
+ 'text/md': TOOL_ARTIFACT_TYPES.MARKDOWN,
+ 'application/vnd.react': TOOL_ARTIFACT_TYPES.REACT,
+ 'application/vnd.ant.react': TOOL_ARTIFACT_TYPES.REACT,
+ 'application/vnd.mermaid': TOOL_ARTIFACT_TYPES.MERMAID,
+ // Office MIME types fall through to the plain-text bucket here too —
+ // matches the extension map so a file whose extension was stripped
+ // somewhere upstream still routes to the panel.
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
+ TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+ 'application/vnd.oasis.opendocument.text': TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
+ TOOL_ARTIFACT_TYPES.PLAIN_TEXT,
+ // Note: bare `text/plain` is NOT mapped here. The extension map handles
+ // `.txt` explicitly; routing every unrecognized-extension `text/plain`
+ // file (extensionless scripts, .env, etc.) through the panel would be a
+ // wider catch than intended. Those still render via the inline `<pre>`.
+};
+
+/**
+ * Decide whether a tool-produced file should render through the artifacts
+ * panel (or inline mermaid component). Returns the canonical artifact MIME
+ * type if so, or `null` to let the caller fall through to the existing
+ * download / inline-text rendering.
+ *
+ * Empty `text` is tolerated for the plain-text and markdown buckets so a
+ * file whose extraction is still TBD (e.g. pptx, or a docx where the
+ * extractor errored) keeps visual parity with its docx/odt siblings — the
+ * card still routes through the panel and `fileToArtifact` substitutes a
+ * placeholder so the panel renders something sensible. The HTML, React,
+ * and Mermaid buckets still require real content because their viewers
+ * (sandpack / mermaid.js) error on empty input.
+ */
+export function detectArtifactTypeFromFile(
+ attachment: Partial<Pick<TFile, 'filename' | 'type' | 'text'>>,
+): ToolArtifactType | null {
+ const byExtension = EXTENSION_TO_TOOL_ARTIFACT_TYPE[extensionOf(attachment.filename)];
+ const type = byExtension ?? MIME_TO_TOOL_ARTIFACT_TYPE[baseMime(attachment.type)] ?? null;
+ if (type == null) {
+ return null;
+ }
+ if (
+ !attachment.text &&
+ type !== TOOL_ARTIFACT_TYPES.PLAIN_TEXT &&
+ type !== TOOL_ARTIFACT_TYPES.MARKDOWN
+ ) {
+ return null;
+ }
+ return type;
+}
+
+/**
+ * Stable per-file key used for both the artifactsState entry and the
+ * `toolArtifactClaim` atom that dedups duplicate cards. Same call shape
+ * everywhere so a panel card and a mermaid card for the same file share
+ * the same claim. Falls through `file_id` → `filename` → `filepath` to
+ * minimise collision risk for any caller that (rarely) lacks `file_id`.
+ */
+export const toolArtifactKey = (
+ file: Partial<Pick<TFile, 'file_id' | 'filename' | 'filepath'>>,
+): string => `tool-artifact-${file.file_id ?? file.filename ?? file.filepath ?? 'unknown'}`;
+
+/**
+ * Stable epoch fallback (instead of `Date.now()`) when neither timestamp
+ * is available. `useArtifacts` sorts by `lastUpdateTime`, so a fresh
+ * `Date.now()` on every call would re-sort entries non-deterministically
+ * across renders. Using `0` parks unsorted entries at the bottom of the
+ * panel's tab strip until real timestamps arrive.
+ */
+const toLastUpdate = (file: Partial<Pick<TFile, 'updatedAt' | 'createdAt'>>): number => {
+ const value = file.updatedAt ?? file.createdAt;
+ if (value == null) {
+ return 0;
+ }
+ const ms = new Date(value as string | number | Date).getTime();
+ return Number.isFinite(ms) ? ms : 0;
+};
+
+interface FileToArtifactOptions {
+ /**
+ * Markdown rendered in the panel when the underlying file has no text
+ * yet (e.g. a pptx whose extractor hasn't run). Callers should provide
+ * a localized string via `useLocalize`; if omitted, an empty string is
+ * substituted (the panel will look bare but won't crash).
+ */
+ placeholder?: string;
+ /**
+ * Pre-classified artifact type from a prior `detectArtifactTypeFromFile`
+ * call; skips re-classification. Used by the routing decision tree
+ * which has already classified to pick which renderer to use.
+ */
+ preClassifiedType?: ToolArtifactType;
+}
+
+/**
+ * Convert a code-execution attachment to an `Artifact` shape if (and only
+ * if) we have a viewer for it. The id is derived from `file_id` so the
+ * same file across renders maps to the same artifact entry.
+ */
+export function fileToArtifact(
+ // Every picked field is read with a fallback in the implementation
+ // (`detectArtifactTypeFromFile`, `toolArtifactKey`, `toLastUpdate`,
+ // and the empty-string nullish coalesces below), so the input type
+ // mirrors that and marks them optional. Required-by-strict-pick was
+ // making every test fixture and many real callers fail typecheck for
+ // fields the function never strictly needs.
+ attachment: Partial<
+ Pick<TAttachment, 'messageId'> &
+ Pick<TFile, 'file_id' | 'filename' | 'filepath' | 'type' | 'text' | 'updatedAt' | 'createdAt'>
+ >,
+ options?: FileToArtifactOptions,
+): Artifact | null {
+ const type = options?.preClassifiedType ?? detectArtifactTypeFromFile(attachment);
+ if (!type) {
+ return null;
+ }
+ // Mirror the empty-text gate from `detectArtifactTypeFromFile` so a
+ // caller that supplies `preClassifiedType` (and thus skips that gate)
+ // can't accidentally hand HTML/React/Mermaid an empty buffer that
+ // their viewers would error on. Plain-text and markdown are still
+ // tolerated empty — the markdown viewer renders empty cleanly.
+ if (
+ !attachment.text &&
+ type !== TOOL_ARTIFACT_TYPES.PLAIN_TEXT &&
+ type !== TOOL_ARTIFACT_TYPES.MARKDOWN
+ ) {
+ return null;
+ }
+ return {
+ id: toolArtifactKey(attachment),
+ type,
+ title: attachment.filename ?? 'Generated artifact',
+ // Nullish coalesce — an empty string is a legitimate file (e.g. a
+ // user wrote an empty `.md`) and should render as empty in the
+ // panel rather than be replaced by the deferred-extraction
+ // placeholder. Only `null`/`undefined` fall through to the
+ // placeholder, matching "no extraction has run yet."
+ content: attachment.text ?? options?.placeholder ?? '',
+ messageId: attachment.messageId ?? undefined,
+ lastUpdateTime: toLastUpdate(attachment),
+ };
+}
+
export const sharedFiles = {
'/lib/utils.ts': shadcnComponents.utils,
'/components/ui/accordion.tsx': shadcnComponents.accordian,
diff --git a/packages/api/src/files/code/classify.spec.ts b/packages/api/src/files/code/classify.spec.ts
index 8a1e3d9f5c..7e713427a0 100644
--- a/packages/api/src/files/code/classify.spec.ts
+++ b/packages/api/src/files/code/classify.spec.ts
@@ -123,6 +123,16 @@ describe('classifyCodeArtifact', () => {
expect(classifyCodeArtifact('SCRIPT.PY', 'application/octet-stream')).toBe('utf8-text');
});
+ describe('diagram files', () => {
+ it.each([
+ ['flow.mmd', 'application/octet-stream'],
+ ['diagram.mermaid', 'application/octet-stream'],
+ ['FLOW.MMD', 'application/octet-stream'],
+ ])('classifies %s as utf8-text', (name, mime) => {
+ expect(classifyCodeArtifact(name, mime)).toBe('utf8-text');
+ });
+ });
+
describe('extensionless filenames', () => {
it.each([
['Makefile', 'application/octet-stream'],
diff --git a/packages/api/src/files/code/classify.ts b/packages/api/src/files/code/classify.ts
index 4c4b9c319b..d4b782553d 100644
--- a/packages/api/src/files/code/classify.ts
+++ b/packages/api/src/files/code/classify.ts
@@ -93,6 +93,9 @@ const UTF8_TEXT_EXTENSIONS = new Set<string>([
'hcl',
'patch',
'diff',
+ // diagrams
+ 'mmd',
+ 'mermaid',
]);
const UTF8_TEXT_MIME_PREFIXES = ['text/'] as const;