diff --git a/client/src/components/Artifacts/ArtifactButton.tsx b/client/src/components/Artifacts/ArtifactButton.tsx index 64aa26292e..5853503104 100644 --- a/client/src/components/Artifacts/ArtifactButton.tsx +++ b/client/src/components/Artifacts/ArtifactButton.tsx @@ -3,13 +3,12 @@ import debounce from 'lodash/debounce'; import { useLocation } from 'react-router-dom'; import { useRecoilState, useSetRecoilState, useResetRecoilState } from 'recoil'; import type { Artifact } from '~/common'; -import FilePreview from '~/components/Chat/Input/Files/FilePreview'; -import { cn, getFileType, logger, isArtifactRoute } from '~/utils'; -import { useLocalize } from '~/hooks'; +import ArtifactRow from '~/components/Chat/Messages/Content/Parts/ArtifactRow'; +import { artifactRowKind } from '~/utils/artifacts'; +import { logger, isArtifactRoute } from '~/utils'; import store from '~/store'; const ArtifactButton = ({ artifact }: { artifact: Artifact | null }) => { - const localize = useLocalize(); const location = useLocation(); const setVisible = useSetRecoilState(store.artifactsVisibility); const [artifacts, setArtifacts] = useRecoilState(store.artifactsState); @@ -51,54 +50,33 @@ const ArtifactButton = ({ artifact }: { artifact: Artifact | null }) => { if (artifact === null || artifact === undefined) { return null; } - const fileType = getFileType('artifact'); + const handleOpen = () => { + if (isSelected) { + resetCurrentArtifactId(); + setVisible(false); + return; + } + + setCurrentArtifactId(artifact.id); + setVisible(true); + + if (artifacts?.[artifact.id] == null) { + setArtifacts(visibleArtifacts); + } + }; + + /* Model-authored artifacts have no file behind them — the panel's own + * `DownloadArtifact` serializes the (possibly edited) content, which + * needs the editor context this row doesn't sit in. */ return ( -
- {(() => { - const handleClick = () => { - if (isSelected) { - resetCurrentArtifactId(); - setVisible(false); - return; - } - - setCurrentArtifactId(artifact.id); - setVisible(true); - - if (artifacts?.[artifact.id] == null) { - setArtifacts(visibleArtifacts); - } - }; - - const buttonClass = cn( - 'relative overflow-hidden rounded-xl transition-all duration-300 hover:border-border-medium hover:bg-surface-hover hover:shadow-lg active:scale-[0.98]', - { - 'border-border-medium bg-surface-hover shadow-lg': isSelected, - 'border-border-light bg-surface-tertiary shadow-sm': !isSelected, - }, - ); - - const actionLabel = isSelected - ? localize('com_ui_click_to_close') - : localize('com_ui_artifact_click'); - - return ( - - ); - })()} -
-
+ ); }; diff --git a/client/src/components/Artifacts/Artifacts.test.tsx b/client/src/components/Artifacts/Artifacts.test.tsx index 49461439a7..6b3206349e 100644 --- a/client/src/components/Artifacts/Artifacts.test.tsx +++ b/client/src/components/Artifacts/Artifacts.test.tsx @@ -65,7 +65,7 @@ jest.mock('./ArtifactVersion', () => ({ jest.mock('./DownloadArtifact', () => ({ __esModule: true, - default: () => null, + default: () =>
, })); jest.mock('./Mermaid/Export', () => ({ @@ -135,9 +135,63 @@ describe('Artifacts panel accessibility', () => { await screen.findByRole('region', { name: 'Diagram' }); expect(screen.queryByRole('button', { name: 'com_ui_refresh' })).not.toBeInTheDocument(); expect(screen.getByTestId('mermaid-export')).toBeInTheDocument(); + /* The export menu owns SVG, PNG and the source, so a second download + * control beside it would be a fourth, unlabelled way to save the same + * diagram. */ + expect(screen.queryByTestId('download-artifact')).not.toBeInTheDocument(); }); - it('hides the Mermaid export action outside the preview tab', async () => { + it('opens a preview-capable artifact on its preview tab after a code-only one', async () => { + /* A code-only artifact forces the Code tab. That constraint used to be + * written back into the panel's shared `activeTab`, so the next HTML or + * diagram row opened on Code while announcing a rendered preview. */ + const setActiveTab = jest.fn(); + const codeOnly = { + activeTab: 'code', + setActiveTab, + currentIndex: 0, + currentArtifact: { + id: 'code-artifact-1', + type: 'application/vnd.code', + title: 'ingest.py', + content: 'print(1)', + lastUpdateTime: 1, + }, + orderedArtifactIds: ['code-artifact-1', 'html-artifact-1'], + setCurrentArtifactId: jest.fn(), + }; + mockUseArtifacts.mockReturnValue(codeOnly); + + const { rerender } = render( + + + , + ); + await screen.findByRole('region', { name: 'ingest.py' }); + /* Nothing to reset while the constrained artifact is the open one. */ + expect(setActiveTab).not.toHaveBeenCalledWith('preview'); + + mockUseArtifacts.mockReturnValue({ + ...codeOnly, + currentIndex: 1, + currentArtifact: { + id: 'html-artifact-1', + type: 'text/html', + title: 'dashboard.html', + content: '

hi

', + lastUpdateTime: 2, + }, + }); + rerender( + + + , + ); + + await waitFor(() => expect(setActiveTab).toHaveBeenCalledWith('preview')); + }); + + it('keeps the Mermaid export action on the code tab', async () => { render( @@ -145,6 +199,36 @@ describe('Artifacts panel accessibility', () => { ); await screen.findByRole('region', { name: 'Diagram' }); + /* Saving the source never needed a rendered preview, and a download + * control that disappears when the user switches tabs reads as a bug. */ + expect(screen.getByTestId('mermaid-export')).toBeInTheDocument(); + expect(screen.queryByTestId('download-artifact')).not.toBeInTheDocument(); + }); + + it('keeps the generic download control for non-Mermaid artifacts', async () => { + mockUseArtifacts.mockReturnValue({ + activeTab: 'preview', + setActiveTab: jest.fn(), + currentIndex: 0, + currentArtifact: { + id: 'html-artifact-1', + type: 'text/html', + title: 'Page', + content: '

Hi

', + lastUpdateTime: 1, + }, + orderedArtifactIds: ['html-artifact-1'], + setCurrentArtifactId: jest.fn(), + }); + + render( + + + , + ); + + await screen.findByRole('region', { name: 'Page' }); + expect(screen.getByTestId('download-artifact')).toBeInTheDocument(); expect(screen.queryByTestId('mermaid-export')).not.toBeInTheDocument(); }); diff --git a/client/src/components/Artifacts/Artifacts.tsx b/client/src/components/Artifacts/Artifacts.tsx index a3fdeecdc4..ccdf927af0 100644 --- a/client/src/components/Artifacts/Artifacts.tsx +++ b/client/src/components/Artifacts/Artifacts.tsx @@ -207,11 +207,23 @@ export default function Artifacts() { } return [filename ? { ...tab, label: filename } : tab]; }, [allTabOptions, constrainedTab, currentArtifact?.title]); + /* The panel keeps one `activeTab`, but a trigger row promises what + * opening *that* artifact does. Writing a constrained tab back into the + * shared state leaked it to the next artifact — after a `.py` (code-only) + * every preview-capable row opened on Code while announcing a rendered + * preview — so the tab is reset per artifact instead, and a manual choice + * survives only while that artifact stays open. */ + const openedArtifactRef = useRef(null); useEffect(() => { - if (constrainedTab != null && activeTab !== constrainedTab) { - setActiveTab(constrainedTab); + const openedId = currentArtifact?.id ?? null; + if (openedId === openedArtifactRef.current) { + return; } - }, [constrainedTab, activeTab, setActiveTab]); + openedArtifactRef.current = openedId; + if (openedId != null && constrainedTab == null && activeTab !== 'preview') { + setActiveTab('preview'); + } + }, [activeTab, constrainedTab, currentArtifact?.id, setActiveTab]); const handleCopyArtifact = useCallback(() => { const content = currentArtifact?.content ?? ''; @@ -481,14 +493,18 @@ export default function Artifacts() { portalElement={isFullscreen ? fullscreenPortalRef.current : undefined} onClick={handleCopyArtifact} /> - {isMermaidArtifact && displayedTab === 'preview' && ( + {/* Mermaid diagrams route every download through the export + menu — SVG, PNG and the source — so the generic button does + not sit beside it offering a fourth, unlabelled option. */} + {isMermaidArtifact ? ( + ) : ( + )} - + {onDownload != null && ( + + )} +
+ ); +}); + +export default ArtifactRow; diff --git a/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx b/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx index f02e8a4189..c7c51b584b 100644 --- a/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx @@ -1,4 +1,5 @@ import { memo, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'; +import { Button } from '@librechat/client'; import { Tools } from 'librechat-data-provider'; import { Loader2, AlertCircle, Download, ChevronDown, Files as FilesIcon } from 'lucide-react'; import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider'; @@ -16,32 +17,28 @@ import { import { useLocalize, useAttachmentPreviewSync, useExpandCollapse } from '~/hooks'; import FileContainer from '~/components/Chat/Input/Files/FileContainer'; import { fileToArtifact, TOOL_ARTIFACT_TYPES } from '~/utils/artifacts'; -import FilePreview from '~/components/Chat/Input/Files/FilePreview'; import Image from '~/components/Chat/Messages/Content/Image'; +import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from '../rows'; import ToolMermaidArtifact from './ToolMermaidArtifact'; import ToolArtifactCard from './ToolArtifactCard'; import { useAttachmentLink } from './LogLink'; -import { cn, getFileType } from '~/utils'; +import { cn } from '~/utils'; const COLLAPSED_MAX_HEIGHT = 320; /** - * Card-shaped placeholder for a code-execution office file whose - * inline preview is still rendering (or failed). Visually mirrors - * `ToolArtifactCard`'s chrome — same rounded card, split body + - * download — so when the deferred render lands and the routing - * upgrades to the real `PanelArtifact` card the user sees a smooth - * transition between two card-shaped things, not a jarring jump from - * a small file chip to a big artifact card. + * Row placeholder for a code-execution office file whose inline preview + * is still rendering (or failed). Takes `ArtifactRow`'s exact box — same + * glyph slot, title, trailing download — so when the deferred render + * lands and the routing upgrades to the real `PanelArtifact` the row + * stays put instead of the list reflowing around a new shape. * - * The body is non-interactive while pending (there's no panel to - * open yet). On `'failed'` the body is also non-interactive — the - * download button is the only meaningful action since extraction - * never produced anything to render. Status reads via the spinner / - * alert subtitle inside the card, mirroring `ToolArtifactCard`'s - * "click to open" subtitle slot. + * Non-interactive in both states: while pending there is no panel to + * open yet, and on `'failed'` extraction never produced anything to + * render, so download is the only meaningful action. Status reads from + * the spinner / alert glyph plus the trailing text. */ -const PreviewPlaceholderCard = memo( +const PreviewPlaceholderRow = memo( ({ attachment, status, @@ -60,63 +57,43 @@ const PreviewPlaceholderCard = memo( user: file.user, source: file.source, }); - const fileType = getFileType('artifact'); const visibleFilename = displayFilename(attachment.filename); const subtitleText = status === 'pending' ? localize('com_ui_preview_preparing') : localize('com_ui_preview_failed'); return ( -
-
+ + -
-
- {/* Don't pass `file` here — it triggers `SourceIcon`'s - Terminal overlay for code-exec files (matches the - `metadata.fileIdentifier` marker), which is the - download-chip look. The artifact card doesn't show - that overlay; the placeholder shouldn't either, so - the pending→resolved transition is visually seamless. */} - -
-
- {visibleFilename} -
-
- {status === 'pending' ? ( -
-
-
-
-
- +
); }, ); -PreviewPlaceholderCard.displayName = 'PreviewPlaceholderCard'; +PreviewPlaceholderRow.displayName = 'PreviewPlaceholderRow'; const FileAttachment = memo(({ attachment }: { attachment: Partial }) => { const [isVisible, setIsVisible] = useState(false); @@ -164,7 +141,7 @@ const FileAttachment = memo(({ attachment }: { attachment: Partial WebkitFontSmoothing: 'subpixel-antialiased', }} > - = []; const mermaidArtifacts: TAttachment[] = []; @@ -579,13 +556,11 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] } // engines (V8 ≥ 7.0) so equal-weight entries keep their input order. fileAttachments.sort(bySalience); textAttachments.sort(bySalience); - /* Sort only the typed (resolved) entries; pending placeholders bubble - * to the end of the row so resolved siblings catch the eye first. */ - const resolvedPanel = panelRow.filter( - (e): e is { attachment: TAttachment; type: ToolArtifactType } => e.type != null, - ); - const pendingPanel = panelRow.filter((e) => e.type == null); - resolvedPanel.sort(byEntrySalience); + /* Pending placeholders sort by the same salience as their resolved + * selves — `attachmentSalience` reads only `bytes`, which resolution + * does not change — so a row keeps its slot across the loading-to-ready + * transition instead of jumping once the preview lands. */ + const orderedPanel = [...panelRow].sort(byEntrySalience); mermaidArtifacts.sort(bySalience); imageAttachments.sort(bySalience); @@ -608,23 +583,28 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] } {groupedFileAttachments.length > 0 && ( )} - {(resolvedPanel.length > 0 || pendingPanel.length > 0) && ( -
- {resolvedPanel.map(({ attachment, type }, index) => ( - - ))} - {pendingPanel.map(({ attachment }, index) => - attachment.filepath ? ( + {orderedPanel.length > 0 && ( +
+ {orderedPanel.map(({ attachment, type }, index) => { + if (type != null) { + return ( + + ); + } + if (!attachment.filepath) { + return null; + } + return ( - ) : null, - )} + ); + })}
)} {mermaidArtifacts.length > 0 && ( diff --git a/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx b/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx index a37419cd54..8cd0077938 100644 --- a/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/LogContent.tsx @@ -181,7 +181,7 @@ const LogContent: React.FC = ({ output = '', renderImages, atta
)} {panelAttachments.length > 0 && ( -
+
{panelAttachments.map(({ attachment, artifact }, index) => ( { + const localize = useLocalize(); const { showToast } = useToastContext(); const { shareId } = useShareContext(); @@ -62,10 +64,12 @@ export const useAttachmentLink = ({ * error or an empty/denied response (e.g. an expired code-output URL or * a 404 share download). Callers that show success feedback should gate * it on this result rather than on the promise merely resolving. + * + * Every `false` is announced here, by the layer that knows the cause, so + * a caller can report the failure in its own live region without racing + * this toast — one press never raises two notifications. */ - const handleDownload = async ( - event: React.MouseEvent, - ): Promise => { + const handleDownload = async (event: React.MouseEvent): Promise => { event.preventDefault(); try { // In a shared view, a snapshotted file's href is rewritten to the share @@ -85,16 +89,14 @@ export const useAttachmentLink = ({ const stream = useLocalDownload ? await downloadFromApi() : await downloadFromUrl(); if (stream.data == null || stream.data === '') { console.error('Error downloading file: No data found'); - showToast({ - status: 'error', - message: 'Error downloading file', - }); + showToast({ status: 'error', message: localize('com_ui_download_error') }); return false; } triggerDownload(stream.data, downloadFilename); return true; } catch (error) { console.error('Error downloading file:', error); + showToast({ status: 'error', message: localize('com_ui_download_error') }); return false; } }; diff --git a/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx b/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx index 75d234783d..de6940ddda 100644 --- a/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/ToolArtifactCard.tsx @@ -1,5 +1,4 @@ import { memo, useEffect, useId, useLayoutEffect, useRef } from 'react'; -import { Download } from 'lucide-react'; import { useRecoilCallback, useRecoilState, @@ -9,12 +8,10 @@ import { } 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 { isCodeOnlyArtifact } from '~/utils/artifacts'; +import { artifactRowKind, isCodeOnlyArtifact } from '~/utils/artifacts'; import { displayFilename } from './attachmentTypes'; import { useAttachmentLink } from './LogLink'; -import { cn, getFileType } from '~/utils'; -import { useLocalize } from '~/hooks'; +import ArtifactRow from './ArtifactRow'; import store from '~/store'; interface ToolArtifactCardProps { @@ -68,7 +65,6 @@ interface ToolArtifactCardProps { * of context. */ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps) => { - const localize = useLocalize(); const claimKey = useId(); const file = attachment as TFile & TAttachmentMetadata; const fileId = file.file_id; @@ -212,61 +208,25 @@ const ToolArtifactCard = memo(({ attachment, artifact }: ToolArtifactCardProps) }; // Another card with the same artifact id has the active claim — render - // nothing here, that card is the canonical chip for this file. + // nothing here, that row is the canonical trigger 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'); - const visibleFilename = displayFilename(attachment.filename); // The artifact's stored `title` mirrors the on-disk `filename` for // tool artifacts, so re-derive the user-facing label rather than // showing the collision-suffixed name. const visibleTitle = displayFilename(artifact.title); return ( -
- - -
+ ); }); diff --git a/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx b/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx index 8083190ace..1431c3052a 100644 --- a/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/ToolMermaidArtifact.tsx @@ -1,4 +1,4 @@ -import { memo, useId, useLayoutEffect, useMemo } from 'react'; +import { memo, useId, useLayoutEffect, useMemo, useState } from 'react'; import { Download } from 'lucide-react'; import { useRecoilState } from 'recoil'; import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider'; @@ -29,6 +29,10 @@ const ToolMermaidArtifact = memo(({ attachment, text }: ToolMermaidArtifactProps const claimKey = useId(); const [claim, setClaim] = useRecoilState(store.toolArtifactClaim(toolArtifactKey(file))); const isMyClaim = claim === claimKey; + /* Once the diagram collapses into its trigger row, that row carries the + * filename and the download itself, so this header would repeat both + * beside it. */ + const [isRowMode, setIsRowMode] = useState(false); useLayoutEffect(() => { setClaim(claimKey); @@ -58,7 +62,7 @@ const ToolMermaidArtifact = memo(({ attachment, text }: ToolMermaidArtifactProps return (
- {(attachment.filename || attachment.filepath) && ( + {!isRowMode && (attachment.filename || attachment.filepath) && (
{attachment.filename && (
+ {text} ) : ( - {text} + + {text} + )}
); 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 index 9772a23a50..8ed2bc4e4d 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx @@ -147,11 +147,12 @@ describe('Attachment routing for tool artifacts', () => { } as Partial); renderWith(); - // Card body shows the artifact title + // Row shows the artifact title and names its format expect(screen.getByText('index.html')).toBeInTheDocument(); - // Open-panel button carries aria-pressed (auto-focused on mount per the + expect(screen.getByText('com_ui_artifact_format_html')).toBeInTheDocument(); + // Open-panel button carries aria-expanded (auto-focused on mount per the // legacy auto-open behaviour). - expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument(); + expect(screen.getByRole('button', { expanded: true })).toBeInTheDocument(); // Download button has the download aria-label expect( screen.getByRole('button', { name: /com_ui_download.*index\.html/i }), @@ -236,9 +237,9 @@ describe('Attachment routing for tool artifacts', () => { } as Partial); renderWith(); expect(screen.getByText(filename)).toBeInTheDocument(); - /* Auto-pressed open button (streaming + non-CODE bucket) — same UX as + /* Auto-expanded open button (streaming + non-CODE bucket) — same UX as * the HTML panel artifact above. */ - expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument(); + expect(screen.getByRole('button', { expanded: true })).toBeInTheDocument(); const downloadPattern = new RegExp(`com_ui_download.*${filename.replace('.', '\\.')}`, 'i'); expect(screen.getByRole('button', { name: downloadPattern })).toBeInTheDocument(); }); @@ -266,8 +267,8 @@ describe('ToolArtifactCard click behaviour', () => { it('toggles closed when the user clicks the (already-selected) card', () => { const { getSnapshot } = renderWithProbe(); - // Mount auto-focuses; the open button is in the pressed state. - const closeButton = screen.getByRole('button', { pressed: true }); + // Mount auto-focuses; the open button reads as expanded. + const closeButton = screen.getByRole('button', { expanded: true }); act(() => { fireEvent.click(closeButton); }); @@ -281,13 +282,13 @@ describe('ToolArtifactCard click behaviour', () => { it('reopens after a close (regression: artifact still openable post-close)', () => { const { getSnapshot } = renderWithProbe(); act(() => { - fireEvent.click(screen.getByRole('button', { pressed: true })); + fireEvent.click(screen.getByRole('button', { expanded: true })); }); expect(getSnapshot().visibility).toBe(false); expect(getSnapshot().currentArtifactId).toBeNull(); - // Click the now-unpressed open button again. + // Click the now-collapsed open button again. act(() => { - fireEvent.click(screen.getByRole('button', { pressed: false })); + fireEvent.click(screen.getByRole('button', { expanded: false })); }); const snap = getSnapshot(); expect(snap.currentArtifactId).toBe('tool-artifact-html-1'); @@ -309,8 +310,8 @@ describe('ToolArtifactCard click behaviour', () => { text: '

v1

', } as Partial); const { container } = renderWith(); - // Dedup atom keeps just one card visible. - expect(container.querySelectorAll('div[title="index.html"]')).toHaveLength(1); + // Dedup atom keeps just one row visible. + expect(container.querySelectorAll('[data-artifact-trigger]')).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'), @@ -381,8 +382,7 @@ describe('ToolArtifactCard click behaviour', () => { , ); - const titles = container.querySelectorAll('div[title="index.html"]'); - expect(titles.length).toBe(1); + expect(container.querySelectorAll('[data-artifact-trigger]')).toHaveLength(1); }); it('dedups two mermaid cards for the same file_id across groups (latest mount wins)', () => { @@ -678,8 +678,8 @@ describe('ToolArtifactCard click behaviour', () => { }); expect(getSnapshot().currentArtifactId).toBeNull(); /** Pin to the panel-open button by name — the download button has no - * `aria-pressed`, but `getByRole('button', { pressed: false })` - * relies on DOM order, which silently shifts if the chip's button + * `aria-expanded`, but `getByRole('button', { expanded: false })` + * relies on DOM order, which silently shifts if the row's button * order changes. */ const openButton = screen.getByRole('button', { name: /com_ui_artifact_click/i }); act(() => { @@ -840,13 +840,76 @@ describe('AttachmentGroup routing', () => { const { container } = renderWith(); - /* Two rows: file row (plain.zip) + panel row (resolved + pending). */ - const rows = container.querySelectorAll('div.flex.flex-wrap'); - expect(rows.length).toBe(2); - /* Resolved artifact card title visible. */ - expect(screen.getByText('index.html')).toBeInTheDocument(); - /* Pending placeholder is a FileContainer rendering. */ - expect(screen.getAllByTestId('file-container').length).toBeGreaterThanOrEqual(1); + /* The resolved artifact and the still-pending one share the artifact + * group, so when the preview lands the row stays put instead of + * jumping between buckets. The plain download keeps its own group. */ + const group = screen.getByTestId('artifact-row-group'); + expect(group).toContainElement(container.querySelector('[data-artifact-trigger]')); + expect(group).toContainElement(screen.getByText('index.html')); + expect(group).toContainElement(screen.getByText('data.xlsx')); + expect(group).not.toContainElement(screen.getByText('archive.zip')); + }); + + it('keeps a pending placeholder in the row slot it arrived in', () => { + /* Sinking every pending entry to the end of the group made the + * placeholder jump the moment its preview resolved and joined the + * salience-sorted siblings. The slot it arrived in is the slot it + * upgrades in. */ + const attachments = [ + baseAttachment({ + file_id: 'pending-1', + filename: 'data.xlsx', + status: 'pending', + } as Partial), + baseAttachment({ + file_id: 'resolved', + filename: 'index.html', + text: '

hi

', + } as Partial), + ] as TAttachment[]; + + renderWith(); + + const rows = Array.from(screen.getByTestId('artifact-row-group').children); + expect(rows.findIndex((row) => row.textContent?.includes('data.xlsx'))).toBe(0); + expect(rows.findIndex((row) => row.textContent?.includes('index.html'))).toBe(1); + }); + + it('keeps a pending row above an empty artifact through its transition', () => { + /* The empty artifact sinks by salience, and a pending file carries the + * same `bytes` before and after its preview resolves, so both renders + * must order the pair identically — otherwise the row jumps exactly + * when the preview lands. */ + const empty = baseAttachment({ + file_id: 'empty', + filename: 'notes.md', + text: '', + bytes: 0, + } as Partial); + const loading = baseAttachment({ + file_id: 'pending-2', + filename: 'report.xlsx', + bytes: 4096, + status: 'pending', + } as Partial); + const resolved = baseAttachment({ + file_id: 'pending-2', + filename: 'report.xlsx', + bytes: 4096, + text: '
', + textFormat: 'html', + } as Partial); + + const order = (attachments: TAttachment[]) => { + const { unmount } = renderWith(); + const rows = Array.from(screen.getByTestId('artifact-row-group').children); + const positions = rows.map((row) => (row.textContent?.includes('report.xlsx') ? 'x' : 'e')); + unmount(); + return positions.join(''); + }; + + expect(order([empty, loading] as TAttachment[])).toBe('xe'); + expect(order([empty, resolved] as TAttachment[])).toBe('xe'); }); it('renders separate buckets for panel artifacts, mermaid, text, and plain files', () => { 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 index 19feccef2c..ddf841af49 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx @@ -86,8 +86,8 @@ describe('LogContent attachment routing', () => { text: '

hi

', } as Partial); renderWith(); - // The panel card carries an aria-pressed state; auto-focused on mount. - expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument(); + // The artifact row carries an aria-expanded state; auto-focused on mount. + expect(screen.getByRole('button', { expanded: true })).toBeInTheDocument(); expect(screen.getByText('index.html')).toBeInTheDocument(); }); @@ -100,7 +100,7 @@ describe('LogContent attachment routing', () => { renderWith(); expect(screen.getByTestId('mermaid-render')).toHaveTextContent('graph TD'); // Panel card not rendered for mermaid - expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { expanded: true })).not.toBeInTheDocument(); }); it('routes text-bearing JSON through inline
, not the panel', () => {
@@ -114,7 +114,7 @@ describe('LogContent attachment routing', () => {
     });
     const { container } = renderWith();
     expect(container.querySelector('pre')).not.toBeNull();
-    expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+    expect(screen.queryByRole('button', { expanded: true })).not.toBeInTheDocument();
     expect(screen.queryByTestId('mermaid-render')).not.toBeInTheDocument();
   });
 
@@ -151,7 +151,7 @@ describe('LogContent attachment routing', () => {
       text: undefined,
     });
     renderWith();
-    expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+    expect(screen.queryByRole('button', { expanded: true })).not.toBeInTheDocument();
     expect(screen.getByTestId('log-link')).toHaveAttribute('data-filename', 'slides.pptx');
   });
 
@@ -169,7 +169,7 @@ describe('LogContent attachment routing', () => {
     });
     renderWith();
     // No panel card and no log-link (the expired branch returns plain text).
-    expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
+    expect(screen.queryByRole('button', { expanded: 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.
@@ -184,7 +184,7 @@ describe('LogContent attachment routing', () => {
       expiresAt: Date.now() + 60_000,
     } as Partial);
     renderWith();
-    expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument();
+    expect(screen.getByRole('button', { expanded: true })).toBeInTheDocument();
   });
 
   it('splits a mixed list into the right buckets', () => {
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogLink.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogLink.test.tsx
index 8152714bc2..add673b236 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogLink.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogLink.test.tsx
@@ -60,6 +60,37 @@ describe('LogLink download routing', () => {
     expect(mockDownloadFromApi).not.toHaveBeenCalled();
   });
 
+  it('reports a thrown fetch to the user instead of failing silently', async () => {
+    /* A caller gates its own success feedback on the returned `false`, so
+     * this layer owns the visible notification for every failure — the
+     * empty-response one and the thrown one alike. Otherwise a network
+     * error leaves the press with no feedback at all. */
+    const filename = 'file.pdf';
+    mockDownloadFromApi.mockRejectedValue(new Error('network down'));
+
+    render(
+      
+        {filename}
+      ,
+    );
+
+    fireEvent.click(screen.getByRole('link', { name: filename }));
+
+    await waitFor(() =>
+      expect(mockShowToast).toHaveBeenCalledWith({
+        status: 'error',
+        message: 'Error downloading file. The file may have been deleted.',
+      }),
+    );
+    expect(mockTriggerDownload).not.toHaveBeenCalled();
+  });
+
   it('uses the authorized file download route when stored metadata is available', async () => {
     const filename = 'file.pdf';
     mockDownloadFromApi.mockResolvedValue({ data: 'https://cdn.example.com/signed/file.pdf' });
diff --git a/client/src/components/Messages/Content/LangIcon.tsx b/client/src/components/Messages/Content/LangIcon.tsx
index bebdad06b9..4dcaea8d48 100644
--- a/client/src/components/Messages/Content/LangIcon.tsx
+++ b/client/src/components/Messages/Content/LangIcon.tsx
@@ -77,6 +77,20 @@ const NAME_MAP: Record = {
   groovy: 'apachegroovy',
 };
 
+/**
+ * Whether `lang` resolves to a brand glyph. Callers that need a fallback
+ * icon of their own can't infer it from `LangIcon` returning `null`,
+ * since that happens inside React's render.
+ */
+export function hasLangIcon(lang: string): boolean {
+  const key = lang.toLowerCase();
+  if (key === 'txt' || key === 'text') {
+    return true;
+  }
+  const resolved = LANG_ALIASES[key] ?? key;
+  return LANG_ICON_PATHS[NAME_MAP[resolved] ?? resolved] != null;
+}
+
 const LangIcon = React.memo(function LangIcon({ lang, className }: LangIconProps) {
   const key = lang.toLowerCase();
   if (key === 'txt' || key === 'text') {
diff --git a/client/src/components/Messages/Content/Mermaid/Export.test.tsx b/client/src/components/Messages/Content/Mermaid/Export.test.tsx
index a9ab3a8268..211503595c 100644
--- a/client/src/components/Messages/Content/Mermaid/Export.test.tsx
+++ b/client/src/components/Messages/Content/Mermaid/Export.test.tsx
@@ -1,6 +1,6 @@
 import React from 'react';
 import userEvent from '@testing-library/user-event';
-import { act, render, screen, waitFor, within } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
 import { downloadMermaidPng, downloadMermaidSvg } from '~/utils/diagram/export';
 import MermaidExport from './Export';
 
@@ -70,20 +70,24 @@ describe('MermaidExport', () => {
     await user.click(trigger);
     expect(await screen.findByRole('menu')).toHaveClass('popover-ui');
     await user.click(await screen.findByRole('menuitem', { name: 'com_ui_export_svg' }));
-    expect(mockDownloadMermaidSvg).toHaveBeenCalledWith(
-      '',
-      'flow.mmd',
-      'rgb(23 23 23)',
+    await waitFor(() =>
+      expect(mockDownloadMermaidSvg).toHaveBeenCalledWith(
+        '',
+        'flow.mmd',
+        'rgb(23 23 23)',
+      ),
     );
     await waitFor(() => expect(trigger).toHaveFocus());
 
     await user.click(trigger);
     await user.click(await screen.findByRole('menuitem', { name: 'com_ui_export_png' }));
-    expect(mockDownloadMermaidPng).toHaveBeenCalledWith(
-      '',
-      'flow.mmd',
-      { width: 400, height: 200 },
-      'rgb(23 23 23)',
+    await waitFor(() =>
+      expect(mockDownloadMermaidPng).toHaveBeenCalledWith(
+        '',
+        'flow.mmd',
+        { width: 400, height: 200 },
+        'rgb(23 23 23)',
+      ),
     );
   });
 
@@ -115,18 +119,25 @@ describe('MermaidExport', () => {
 
     await user.keyboard('{Enter}');
     const svgItem = await screen.findByRole('menuitem', { name: 'com_ui_export_svg' });
-    expect(svgItem).toHaveFocus();
+    /* `Home` rather than `ArrowDown`: opening from the keyboard sometimes
+     * lands on the first item already (CI observed it active), and one
+     * ArrowDown from there walks past SVG onto PNG. `Home` is the first
+     * item from either starting point, which is what a keyboard user gets. */
+    await user.keyboard('{Home}');
+    await waitFor(() => expect(svgItem).toHaveFocus());
     await user.keyboard('{Enter}');
 
-    expect(mockDownloadMermaidSvg).toHaveBeenCalledWith(
-      '',
-      'flow.mmd',
-      'rgb(23 23 23)',
+    await waitFor(() =>
+      expect(mockDownloadMermaidSvg).toHaveBeenCalledWith(
+        '',
+        'flow.mmd',
+        'rgb(23 23 23)',
+      ),
     );
     await waitFor(() => expect(trigger).toHaveFocus());
   });
 
-  it('announces PNG generation and prevents duplicate export actions', async () => {
+  it('turns the pressed format into its own loading row and blocks the other', async () => {
     const user = userEvent.setup();
     let finishExport: (() => void) | undefined;
     mockDownloadMermaidPng.mockImplementationOnce(
@@ -144,17 +155,128 @@ describe('MermaidExport', () => {
     expect(trigger).toHaveAttribute('aria-busy', 'true');
     expect(trigger.querySelector('.lucide-loader-circle')).not.toBeNull();
     expect(screen.getByRole('status')).toHaveTextContent('com_ui_mermaid_exporting_png');
+    await waitFor(() => expect(mockDownloadMermaidPng).toHaveBeenCalled());
 
     await user.click(trigger);
-    expect(
-      within(screen.getByRole('menu')).getByText('com_ui_mermaid_exporting_png'),
-    ).toBeVisible();
-    expect(screen.getByRole('menuitem', { name: 'com_ui_export_png' })).toHaveAttribute(
+    const menu = within(screen.getByRole('menu'));
+    /* The menu keeps exactly its two format rows: the pressed one becomes the
+     * loading row in place, rather than a third status row appearing beside
+     * two options that still look idle. */
+    expect(menu.getAllByRole('menuitem')).toHaveLength(2);
+    const running = menu.getByRole('menuitem', { name: 'com_ui_mermaid_exporting_png' });
+    expect(running).toHaveTextContent('com_ui_loading');
+    expect(running.querySelector('.lucide-loader-circle')).not.toBeNull();
+    expect(running).toHaveAttribute('aria-disabled', 'true');
+    expect(menu.queryByText('com_ui_export_png')).not.toBeInTheDocument();
+    /* The other format cannot be started on top of the running one. */
+    expect(menu.getByRole('menuitem', { name: 'com_ui_export_svg' })).toHaveAttribute(
       'aria-disabled',
       'true',
     );
 
     await act(async () => finishExport?.());
     expect(screen.getByRole('status')).toHaveTextContent('com_ui_mermaid_export_complete');
+    /* The menu is still open from the click above — the rows recover in place. */
+    expect(menu.getByRole('menuitem', { name: 'com_ui_export_png' })).not.toHaveAttribute(
+      'aria-disabled',
+      'true',
+    );
+  });
+
+  it('waits for a paint, not just a later task, before a synchronous export', async () => {
+    /* `downloadMermaidSvg` blocks the frame it runs in, so it must not start
+     * until the browser has had a rendering opportunity to show the loading
+     * row: a bare `setTimeout` can fire before that paint. `fireEvent` is
+     * synchronous, so nothing has flushed the deferral yet. */
+    const user = userEvent.setup();
+    const frames: Array = [];
+    const rafSpy = jest
+      .spyOn(window, 'requestAnimationFrame')
+      .mockImplementation((callback: FrameRequestCallback) => {
+        frames.push(callback);
+        return frames.length;
+      });
+    try {
+      render('} filename="flow.mmd" />);
+
+      const trigger = screen.getByRole('button', { name: 'com_ui_export_mermaid' });
+      await user.click(trigger);
+      fireEvent.click(await screen.findByRole('menuitem', { name: 'com_ui_export_svg' }));
+
+      expect(mockDownloadMermaidSvg).not.toHaveBeenCalled();
+      expect(trigger).toHaveAttribute('aria-busy', 'true');
+      /* Still nothing on timers alone: the export is behind a frame. */
+      await act(async () => {
+        jest.advanceTimersByTime?.(0);
+      });
+      expect(mockDownloadMermaidSvg).not.toHaveBeenCalled();
+
+      await act(async () => {
+        frames.splice(0).forEach((frame) => frame(0));
+      });
+      await waitFor(() => expect(mockDownloadMermaidSvg).toHaveBeenCalledTimes(1));
+      await waitFor(() => expect(trigger).not.toHaveAttribute('aria-busy'));
+    } finally {
+      rafSpy.mockRestore();
+    }
+  });
+
+  it('saves the diagram source from the menu before any preview SVG exists', async () => {
+    /* The source is the artifact's own content, so it is the one item that
+     * never waits on a render — and the only enabled item on the code tab. */
+    const user = userEvent.setup();
+    const onDownloadSource = jest.fn().mockResolvedValue(true);
+    render();
+
+    await user.click(screen.getByRole('button', { name: 'com_ui_export_mermaid' }));
+    const sourceItem = await screen.findByRole('menuitem', {
+      name: 'com_ui_export_mermaid_source',
+    });
+    expect(sourceItem).not.toHaveAttribute('aria-disabled', 'true');
+
+    await user.click(sourceItem);
+    await waitFor(() => expect(onDownloadSource).toHaveBeenCalledTimes(1));
+    await waitFor(() =>
+      expect(screen.getByRole('status')).toHaveTextContent('com_ui_mermaid_export_complete'),
+    );
+  });
+
+  it('announces a failed source download without a second toast', async () => {
+    /* The stored file can be gone (expired code-output URL, deleted file):
+     * the download helper reports that as `false` after raising its own
+     * "Error downloading file" toast, so the menu only updates its live
+     * region — announcing "export complete" would be a lie and a second
+     * toast would be noise. */
+    const user = userEvent.setup();
+    const onDownloadSource = jest.fn().mockResolvedValue(false);
+    render();
+
+    await user.click(screen.getByRole('button', { name: 'com_ui_export_mermaid' }));
+    await user.click(await screen.findByRole('menuitem', { name: 'com_ui_export_mermaid_source' }));
+
+    await waitFor(() => expect(onDownloadSource).toHaveBeenCalledTimes(1));
+    await waitFor(() =>
+      expect(screen.getByRole('status')).toHaveTextContent('com_ui_mermaid_export_failed'),
+    );
+    expect(mockShowToast).not.toHaveBeenCalled();
+  });
+
+  it('raises its own toast when an export throws', async () => {
+    /* A thrown task told nobody, so this menu is the only layer that can
+     * report it. */
+    const user = userEvent.setup();
+    const onDownloadSource = jest.fn().mockRejectedValue(new Error('boom'));
+    render();
+
+    await user.click(screen.getByRole('button', { name: 'com_ui_export_mermaid' }));
+    await user.click(await screen.findByRole('menuitem', { name: 'com_ui_export_mermaid_source' }));
+
+    await waitFor(() =>
+      expect(mockShowToast).toHaveBeenCalledWith({
+        status: 'error',
+        message: 'com_ui_mermaid_export_failed',
+      }),
+    );
+    expect(screen.getByRole('status')).toHaveTextContent('com_ui_mermaid_export_failed');
   });
 });
diff --git a/client/src/components/Messages/Content/Mermaid/Export.tsx b/client/src/components/Messages/Content/Mermaid/Export.tsx
index e92d61af4a..171ca0bd9c 100644
--- a/client/src/components/Messages/Content/Mermaid/Export.tsx
+++ b/client/src/components/Messages/Content/Mermaid/Export.tsx
@@ -1,8 +1,10 @@
 import React, { memo, useCallback, useId, useMemo, useRef, useState } from 'react';
 import * as Ariakit from '@ariakit/react';
-import { FileCode2, FileImage, ImageDown, LoaderCircle } from 'lucide-react';
 import { DropdownPopup, TooltipAnchor, useToastContext } from '@librechat/client';
+import { FileCode2, FileImage, ImageDown, LoaderCircle, Workflow } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
 import type { MermaidDimensions } from '~/utils/diagram/export';
+import type { TranslationKeys } from '~/hooks/useLocalize';
 import type { MenuItemProps } from '~/common';
 import { downloadMermaidPng, downloadMermaidSvg } from '~/utils/diagram/export';
 import { useLocalize } from '~/hooks';
@@ -16,6 +18,17 @@ interface MermaidExportProps {
   /** Fullscreen re-roots the panel, so a menu portalled to the body would be
    *  rendered outside the visible fullscreen element. */
   portalElement?: HTMLElement | null;
+  /**
+   * Saves the diagram's own source. Supplied only by the artifacts panel,
+   * where this menu replaces the generic download button rather than sitting
+   * next to it — one control that offers every form the diagram comes in,
+   * instead of two buttons whose difference is invisible until you press one.
+   * Unlike the rendered formats it does not need a preview, so it stays
+   * available while the panel is on the code tab.
+   */
+  onDownloadSource?: (
+    event: React.MouseEvent,
+  ) => boolean | void | Promise;
 }
 
 function surfaceBackground(): string | undefined {
@@ -31,91 +44,187 @@ function surfaceBackground(): string | undefined {
   return value.startsWith('var(') ? undefined : value;
 }
 
+type ExportFormat = 'svg' | 'png' | 'source';
+
+/** Rendered formats, in menu order. Each needs the preview's SVG. */
+const EXPORT_FORMATS = [
+  { format: 'svg', labelKey: 'com_ui_export_svg', Icon: FileCode2 },
+  { format: 'png', labelKey: 'com_ui_export_png', Icon: FileImage },
+] as const satisfies ReadonlyArray<{
+  format: Exclude;
+  labelKey: TranslationKeys;
+  Icon: LucideIcon;
+}>;
+
+const EXPORTING_KEYS: Record = {
+  svg: 'com_ui_mermaid_exporting_svg',
+  png: 'com_ui_mermaid_exporting_png',
+  source: 'com_ui_mermaid_exporting_source',
+};
+
 const MermaidExport = memo(function MermaidExport({
   filename,
   svg,
   dimensions,
   buttonClassName,
   portalElement,
+  onDownloadSource,
 }: MermaidExportProps) {
   const localize = useLocalize();
   const { showToast } = useToastContext();
   const instanceId = useId().replace(/[^a-zA-Z0-9_-]/g, '');
   const triggerRef = useRef(null);
   const [isOpen, setIsOpen] = useState(false);
-  const [isExportingPng, setIsExportingPng] = useState(false);
+  const [exporting, setExporting] = useState(null);
   const [exportStatus, setExportStatus] = useState('');
-  const isBusy = isExportingPng;
-  let liveMessage = exportStatus;
-  if (isExportingPng) {
-    liveMessage = localize('com_ui_mermaid_exporting_png');
-  }
+  const isBusy = exporting != null;
+  const liveMessage = exporting == null ? exportStatus : localize(EXPORTING_KEYS[exporting]);
 
+  /* A task that throws told nobody, so the menu raises the toast itself. */
   const showExportError = useCallback(() => {
     setExportStatus(localize('com_ui_mermaid_export_failed'));
     showToast({ status: 'error', message: localize('com_ui_mermaid_export_failed') });
   }, [localize, showToast]);
 
+  /* A task that reports `false` failed inside a layer that names the cause
+   * better than this menu can — `useAttachmentLink` already toasts
+   * "Error downloading file" — so only the live region speaks here, or one
+   * press raises two toasts. */
+  const announceExportError = useCallback(() => {
+    setExportStatus(localize('com_ui_mermaid_export_failed'));
+  }, [localize]);
+
   const restoreTriggerFocus = useCallback(() => {
     requestAnimationFrame(() => triggerRef.current?.focus());
   }, []);
 
+  /**
+   * Runs `task` after the browser has had a rendering opportunity, not
+   * merely in a later task: a bare `setTimeout` can fire before the paint
+   * that would have shown the loading row, which is the whole point of
+   * deferring a synchronous export. A hidden tab serves no animation
+   * frames, and an export must not stall until refocus, so fall back to a
+   * timer there.
+   */
+  const deferPastPaint = useCallback((task: () => void) => {
+    if (typeof requestAnimationFrame !== 'function' || document.hidden) {
+      setTimeout(task, 0);
+      return;
+    }
+    requestAnimationFrame(() => setTimeout(task, 0));
+  }, []);
+
+  /**
+   * Every menu action runs through here so the menu can show the in-flight
+   * one as its own loading row rather than growing an extra status row
+   * beside options that still look idle.
+   *
+   * The work waits for a paint (see `deferPastPaint`). That matters most for
+   * SVG, whose export is synchronous: calling it inline blocks the frame
+   * that would have shown its spinner, so a large diagram froze the open
+   * menu with both options looking idle.
+   */
+  const runExport = useCallback(
+    (format: ExportFormat, task: () => boolean | void | Promise) => {
+      if (exporting != null) {
+        return;
+      }
+      setExporting(format);
+      setExportStatus('');
+      deferPastPaint(() => {
+        void Promise.resolve()
+          .then(task)
+          .then((delivered) => {
+            /* A task that reports `false` delivered nothing — the source
+             * download fetches the stored file and swallows an expired or
+             * denied route — so the menu must not announce completion. */
+            if (delivered === false) {
+              announceExportError();
+              return;
+            }
+            setExportStatus(localize('com_ui_mermaid_export_complete'));
+          })
+          .catch(showExportError)
+          .finally(() => setExporting(null));
+      });
+      restoreTriggerFocus();
+    },
+    [
+      announceExportError,
+      deferPastPaint,
+      exporting,
+      localize,
+      restoreTriggerFocus,
+      showExportError,
+    ],
+  );
+
   const handleSvgExport = useCallback(() => {
     if (svg == null) {
       return;
     }
-
-    try {
-      downloadMermaidSvg(svg, filename, surfaceBackground());
-      setExportStatus(localize('com_ui_mermaid_export_complete'));
-    } catch {
-      showExportError();
-    } finally {
-      restoreTriggerFocus();
-    }
-  }, [filename, localize, restoreTriggerFocus, showExportError, svg]);
+    runExport('svg', () => downloadMermaidSvg(svg, filename, surfaceBackground()));
+  }, [filename, runExport, svg]);
 
   const handlePngExport = useCallback(() => {
-    if (svg == null || isExportingPng) {
+    if (svg == null) {
       return;
     }
+    runExport('png', () => downloadMermaidPng(svg, filename, dimensions, surfaceBackground()));
+  }, [dimensions, filename, runExport, svg]);
 
-    setIsExportingPng(true);
-    setExportStatus('');
-    void downloadMermaidPng(svg, filename, dimensions, surfaceBackground())
-      .then(() => setExportStatus(localize('com_ui_mermaid_export_complete')))
-      .catch(showExportError)
-      .finally(() => setIsExportingPng(false));
-    restoreTriggerFocus();
-  }, [dimensions, filename, isExportingPng, localize, restoreTriggerFocus, showExportError, svg]);
+  const handleSourceExport = useCallback(
+    (event: React.MouseEvent) => {
+      if (onDownloadSource == null) {
+        return;
+      }
+      runExport('source', () => onDownloadSource(event));
+    },
+    [onDownloadSource, runExport],
+  );
 
+  /**
+   * The visible label collapses to a generic "Loading…" so the row reads as
+   * the control the user just pressed; the format-specific phrase stays on
+   * `ariaLabel`, which is what a screen reader announces, so "which export"
+   * is not lost to the swap.
+   */
   const dropdownItems = useMemo(() => {
-    const statusItems: MenuItemProps[] = [];
-    if (isBusy) {
-      statusItems.push({
-        label: liveMessage,
-        disabled: true,
-        icon: ,
-        className: 'text-text-secondary',
+    const loadingRow = (format: ExportFormat) => ({
+      label: localize('com_ui_loading'),
+      ariaLabel: localize(EXPORTING_KEYS[format]),
+      icon: ,
+      className: 'text-text-secondary',
+    });
+    const items: MenuItemProps[] = EXPORT_FORMATS.map(({ format, labelKey, Icon }) => ({
+      label: localize(labelKey),
+      icon: ,
+      ...(exporting === format ? loadingRow(format) : {}),
+      disabled: svg == null || isBusy,
+      onClick: format === 'svg' ? handleSvgExport : handlePngExport,
+    }));
+    if (onDownloadSource != null) {
+      items.push({
+        label: localize('com_ui_export_mermaid_source'),
+        icon: ,
+        ...(exporting === 'source' ? loadingRow('source') : {}),
+        /* The source is the artifact's own content, so unlike SVG and PNG it
+         * does not wait on a rendered preview. */
+        disabled: isBusy,
+        onClick: handleSourceExport,
       });
     }
-
-    return [
-      ...statusItems,
-      {
-        label: localize('com_ui_export_svg'),
-        icon: ,
-        disabled: svg == null || isExportingPng,
-        onClick: handleSvgExport,
-      },
-      {
-        label: localize('com_ui_export_png'),
-        icon: ,
-        disabled: svg == null || isExportingPng,
-        onClick: handlePngExport,
-      },
-    ];
-  }, [handlePngExport, handleSvgExport, isBusy, isExportingPng, liveMessage, localize, svg]);
+    return items;
+  }, [
+    exporting,
+    handlePngExport,
+    handleSourceExport,
+    handleSvgExport,
+    isBusy,
+    localize,
+    onDownloadSource,
+    svg,
+  ]);
 
   return (
     <>
diff --git a/client/src/components/Messages/Content/Mermaid/Mermaid.test.tsx b/client/src/components/Messages/Content/Mermaid/Mermaid.test.tsx
index 594b5ded65..5d1b1b5b52 100644
--- a/client/src/components/Messages/Content/Mermaid/Mermaid.test.tsx
+++ b/client/src/components/Messages/Content/Mermaid/Mermaid.test.tsx
@@ -160,12 +160,14 @@ describe('Mermaid Artifact expansion', () => {
     const artifactButton = await screen.findByRole('button', { expanded: true });
     expect(screen.queryByTestId('mermaid-dialog')).not.toBeInTheDocument();
     expect(screen.getByText('com_ui_mermaid_diagram')).toBeInTheDocument();
-    expect(screen.getByText('com_ui_close_artifact')).toBeInTheDocument();
+    expect(artifactButton).toHaveAccessibleName(/com_ui_click_to_close/);
     expect(artifactButton).toHaveAttribute('aria-controls', 'artifact-viewer');
-    expect(artifactButton).toHaveClass('w-fit', 'max-w-full', 'bg-surface-hover');
+    /* The mermaid trigger is an `ArtifactRow` like every other artifact in
+     * the stream: the diagram glyph sits in the row's glyph slot, tinted
+     * with the `status-info` accent that marks a rendered preview. */
+    expect(artifactButton).toHaveClass('text-text-primary');
     expect(container.querySelector('.lucide-workflow')).not.toBeNull();
     expect(container.querySelector('.lucide-workflow')?.parentElement).toHaveClass(
-      'bg-status-info-subtle',
       'text-status-info',
     );
     await waitFor(() => expect(artifactButton).toHaveFocus());
@@ -183,14 +185,95 @@ describe('Mermaid Artifact expansion', () => {
     fireEvent.click(artifactButton);
     expect(state.currentArtifactId).toBeNull();
     expect(state.visible).toBe(false);
-    expect(artifactButton).toHaveClass('bg-surface-tertiary');
-    expect(screen.getByText('com_ui_open_artifact')).toBeInTheDocument();
+    expect(artifactButton).not.toHaveClass('text-text-primary');
+    expect(artifactButton).toHaveAccessibleName(/com_ui_artifact_click/);
 
     fireEvent.click(screen.getByRole('button', { expanded: false }));
     expect(state.currentArtifactId).toBe(artifact?.id);
     expect(state.visible).toBe(true);
   });
 
+  it('hands a file-backed diagram its download and reports the row mode', async () => {
+    /* A code-execution `.mmd` arrives wrapped in a header that shows the
+     * filename and its own download button. Once the diagram becomes its
+     * trigger row, the row takes both over, and the wrapper needs to know
+     * so it stops repeating them beside it. */
+    const onDownload = jest.fn();
+    const rowModes: boolean[] = [];
+    render(
+      
+        
+          
+            B',
+                  lastUpdateTime: 1,
+                } as Artifact
+              }
+              onDownload={onDownload}
+              onRowModeChange={(isRow) => rowModes.push(isRow)}
+            >
+              {'graph TD\nA-->B'}
+            
+          
+        
+      ,
+    );
+
+    expect(rowModes).toEqual([false]);
+    fireEvent.click(screen.getByRole('button', { name: mockOpenAsArtifactLabel }));
+
+    const downloadButton = await screen.findByRole('button', { name: 'com_ui_download flow.mmd' });
+    fireEvent.click(downloadButton);
+    expect(onDownload).toHaveBeenCalledTimes(1);
+    await waitFor(() => expect(rowModes[rowModes.length - 1]).toBe(true));
+  });
+
+  it('shows the caller-supplied display name on the row, not the raw title', async () => {
+    /* A sandbox-generated `_.flow-abcdef.mmd` reads as `.flow.mmd` through
+     * `displayFilename`; the row and its download button must not regress
+     * to the internal filename once the diagram collapses. */
+    render(
+      
+        
+          
+            B',
+                  lastUpdateTime: 1,
+                } as Artifact
+              }
+              rowTitle=".flow.mmd"
+              onDownload={jest.fn()}
+            >
+              {'graph TD\nA-->B'}
+            
+          
+        
+      ,
+    );
+
+    fireEvent.click(screen.getByRole('button', { name: mockOpenAsArtifactLabel }));
+
+    expect(await screen.findByText('.flow.mmd')).toBeInTheDocument();
+    expect(screen.queryByText('_.flow-abcdef.mmd')).not.toBeInTheDocument();
+    expect(screen.getByRole('button', { name: 'com_ui_download .flow.mmd' })).toBeInTheDocument();
+  });
+
   it('separates diagrams that sit in different content parts of one message', async () => {
     let state: ArtifactStateSnapshot = {
       artifacts: null,
diff --git a/client/src/components/Messages/Content/Mermaid/Mermaid.tsx b/client/src/components/Messages/Content/Mermaid/Mermaid.tsx
index cc39519dd7..3e98d5e8fd 100644
--- a/client/src/components/Messages/Content/Mermaid/Mermaid.tsx
+++ b/client/src/components/Messages/Content/Mermaid/Mermaid.tsx
@@ -4,8 +4,9 @@ import { useLocation } from 'react-router-dom';
 import { Button, Spinner } from '@librechat/client';
 import { useRecoilValue, useSetRecoilState } from 'recoil';
 import type { ProcessedMermaidSvg } from '~/utils/diagram/export';
+import ArtifactRow from '~/components/Chat/Messages/Content/Parts/ArtifactRow';
 import { MERMAID_ARTIFACT_TYPE, type Artifact } from '~/common/artifacts';
-import MermaidArtifactCard from './MermaidArtifactCard';
+import { artifactRowKind } from '~/utils/artifacts';
 import useSvgProcessing from './useSvgProcessing';
 import { useMessageContext } from '~/Providers';
 import useMermaidZoom from './useMermaidZoom';
@@ -22,9 +23,27 @@ interface MermaidProps {
   id?: string;
   theme?: string;
   artifact?: Artifact;
+  /**
+   * Saves the file a code-execution diagram came from. Once the diagram
+   * collapses into its trigger row, the row owns this action the way every
+   * other file-backed artifact row does, so the caller's own header can
+   * step aside instead of repeating the filename beside it.
+   */
+  onDownload?: (event: React.MouseEvent) => void;
+  /** Reports whether the diagram is currently rendered as its trigger row. */
+  onRowModeChange?: (isRow: boolean) => void;
+  /**
+   * Name to show on the trigger row, when the caller holds a friendlier one
+   * than the artifact's raw title — a sandbox-generated `_.flow-abcdef.mmd`
+   * reads as `.flow.mmd` through `displayFilename`, and the row (plus its
+   * download button's accessible name) must not regress to the internal
+   * filename the way it would by falling back to `artifact.title`.
+   */
+  rowTitle?: string;
 }
 
-interface MermaidRendererProps extends Omit {
+interface MermaidRendererProps
+  extends Omit {
   fillContainer?: boolean;
   onExpand?: () => void;
   onExportReady?: (data: ProcessedMermaidSvg | null) => void;
@@ -33,7 +52,16 @@ interface MermaidRendererProps extends Omit {
   showHeader?: boolean;
 }
 
-const Mermaid: React.FC = memo(({ children, id, theme, artifact: artifactProp }) => {
+const Mermaid: React.FC = memo((props) => {
+  const {
+    children,
+    id,
+    theme,
+    artifact: artifactProp,
+    onDownload,
+    onRowModeChange,
+    rowTitle,
+  } = props;
   const localize = useLocalize();
   const location = useLocation();
   const instanceId = useId().replace(/[^a-zA-Z0-9_-]/g, '');
@@ -136,14 +164,21 @@ const Mermaid: React.FC = memo(({ children, id, theme, artifact: a
     shouldFocusArtifactCardRef.current = false;
   }, [isArtifactCard]);
 
-  if (canOpenArtifact && isArtifactCard) {
+  const isRowMode = canOpenArtifact && isArtifactCard;
+  useEffect(() => {
+    onRowModeChange?.(isRowMode);
+  }, [isRowMode, onRowModeChange]);
+
+  if (isRowMode) {
     return (
-      
     );
   }
diff --git a/client/src/components/Messages/Content/Mermaid/MermaidArtifactCard.tsx b/client/src/components/Messages/Content/Mermaid/MermaidArtifactCard.tsx
deleted file mode 100644
index 100219aac2..0000000000
--- a/client/src/components/Messages/Content/Mermaid/MermaidArtifactCard.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-import React, { forwardRef } from 'react';
-import { Workflow } from 'lucide-react';
-import { Button } from '@librechat/client';
-import { useLocalize } from '~/hooks';
-import cn from '~/utils/cn';
-
-interface MermaidArtifactCardProps {
-  artifactId: string;
-  isSelected: boolean;
-  title: string;
-  onClick: () => void;
-}
-
-const MermaidArtifactCard = forwardRef(
-  ({ artifactId, isSelected, title, onClick }, ref) => {
-    const localize = useLocalize();
-    const actionLabel = isSelected
-      ? localize('com_ui_close_artifact')
-      : localize('com_ui_open_artifact');
-
-    return (
-      
-    );
-  },
-);
-
-MermaidArtifactCard.displayName = 'MermaidArtifactCard';
-
-export default MermaidArtifactCard;
diff --git a/client/src/hooks/Artifacts/useArtifactDownload.ts b/client/src/hooks/Artifacts/useArtifactDownload.ts
new file mode 100644
index 0000000000..cd2b5252a6
--- /dev/null
+++ b/client/src/hooks/Artifacts/useArtifactDownload.ts
@@ -0,0 +1,139 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { useToastContext } from '@librechat/client';
+import type { Artifact } from '~/common';
+import {
+  getArtifactDownloadFilename,
+  getOriginalArtifactFilename,
+  isPreviewOnlyArtifact,
+} from '~/utils/artifacts';
+import {
+  useAttachmentLink,
+  isLocallyStoredSource,
+} from '~/components/Chat/Messages/Content/Parts/LogLink';
+import useArtifactProps from '~/hooks/Artifacts/useArtifactProps';
+import { useCodeState } from '~/Providers/EditorContext';
+import useLocalize from '~/hooks/useLocalize';
+
+export interface ArtifactDownload {
+  /** Briefly true after a file actually reached the user, for the check-mark swap. */
+  isDownloaded: boolean;
+  /**
+   * Resolves to whether bytes actually reached the user, and every `false`
+   * has already been reported to them: the attachment route swallows fetch
+   * errors and toasts them itself, and the blob path below does the same,
+   * so a caller that announces completion (the mermaid export menu) gates
+   * it on this result and only has to speak in its own live region.
+   */
+  handleDownload: (event: React.MouseEvent) => Promise;
+}
+
+/**
+ * Saves an artifact to disk, picking between the original file and the
+ * (possibly edited) panel content.
+ *
+ * A hook rather than logic inside the download button because mermaid
+ * artifacts expose the same action as an item in their export menu instead
+ * of a second icon beside it — two entry points, one decision about what the
+ * bytes should be.
+ */
+export default function useArtifactDownload(artifact: Artifact): ArtifactDownload {
+  const { currentCode } = useCodeState();
+  const { showToast } = useToastContext();
+  const localize = useLocalize();
+  const [isDownloaded, setIsDownloaded] = useState(false);
+  const { fileKey: fileName } = useArtifactProps({ artifact });
+  const resetTimer = useRef>();
+  useEffect(() => () => clearTimeout(resetTimer.current), []);
+
+  /* Unedited file-backed artifacts download the original: cached extraction
+   * can be truncated or transformed. Edited content is exported as a blob. */
+  const { download } = artifact;
+  /* Only take the original-file branch when `useAttachmentLink` can
+   * actually fetch something: a usable `filepath` (http target, share
+   * route, or code-output URL) OR enough metadata for the local-file
+   * API path (`isLocallyStoredSource` + file_id + user). A shared link
+   * to a non-snapshotted code-execution artifact strips source/user and
+   * deletes filepath while keeping file_id; without this guard that lone
+   * file_id would route to an empty fetch and download nothing instead
+   * of falling back to the preview-content blob. */
+  const hasUsableRoute =
+    (download?.filepath != null && download.filepath !== '') ||
+    (download?.file_id != null &&
+      download?.user != null &&
+      isLocallyStoredSource(download?.source));
+  const hasEdits = currentCode != null && currentCode !== artifact.content;
+  /**
+   * Mermaid is no exception, even though the panel renders the diagram
+   * straight from `content`: that content is the cached extraction, and
+   * `extractUtf8` keeps only the first 512 KB plus a truncation marker, so
+   * a stored `.mmd` above that cap would otherwise be saved corrupt. When
+   * the route is missing (a share that dropped it) or the panel holds
+   * edits, the content blob below is still the right bytes.
+   */
+  const downloadOriginalFile =
+    hasUsableRoute && (isPreviewOnlyArtifact(artifact.type) || !hasEdits);
+  const { handleDownload: downloadAttachment } = useAttachmentLink({
+    href: download?.filepath ?? '',
+    filename: getOriginalArtifactFilename(artifact, fileName),
+    file_id: download?.file_id,
+    user: download?.user,
+    source: download?.source,
+  });
+
+  const markDownloaded = useCallback(() => {
+    setIsDownloaded(true);
+    clearTimeout(resetTimer.current);
+    resetTimer.current = setTimeout(() => setIsDownloaded(false), 3000);
+  }, []);
+
+  const handleDownload = useCallback(
+    async (event: React.MouseEvent): Promise => {
+      try {
+        if (downloadOriginalFile) {
+          // Only flag success when a file was actually delivered; the
+          // attachment helper swallows fetch errors (e.g. an expired
+          // code-output URL or a 404 share download) and resolves either way.
+          const downloaded = await downloadAttachment(event);
+          if (downloaded) {
+            markDownloaded();
+          }
+          return downloaded;
+        }
+        const content = currentCode ?? artifact.content;
+        if (content == null) {
+          /* Nothing to serialize and no route to fetch: the press has to
+           * say something, or it looks like the download worked. */
+          showToast({ status: 'error', message: localize('com_ui_download_error') });
+          return false;
+        }
+        const blob = new Blob([content], { type: 'text/plain' });
+        const url = window.URL.createObjectURL(blob);
+        const link = document.createElement('a');
+        link.href = url;
+        link.download = getArtifactDownloadFilename(artifact, fileName, content);
+        document.body.appendChild(link);
+        link.click();
+        document.body.removeChild(link);
+        window.URL.revokeObjectURL(url);
+        markDownloaded();
+        return true;
+      } catch (error) {
+        console.error('Download failed:', error);
+        showToast({ status: 'error', message: localize('com_ui_download_error') });
+        return false;
+      }
+    },
+    [
+      artifact,
+      currentCode,
+      downloadAttachment,
+      downloadOriginalFile,
+      fileName,
+      localize,
+      markDownloaded,
+      showToast,
+    ],
+  );
+
+  return { isDownloaded, handleDownload };
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 6074636d3f..64de2fe31b 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1041,7 +1041,17 @@
   "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_format_diagram": "Diagram",
+  "com_ui_artifact_format_document": "Document",
+  "com_ui_artifact_format_html": "HTML",
+  "com_ui_artifact_format_markdown": "Markdown",
+  "com_ui_artifact_format_presentation": "Presentation",
+  "com_ui_artifact_format_react": "React",
+  "com_ui_artifact_format_spreadsheet": "Spreadsheet",
+  "com_ui_artifact_format_text": "Text",
   "com_ui_artifact_preview_pending": "_Preview not available yet — click **Download** to view the file._",
+  "com_ui_artifact_renders": "Opens as a rendered preview",
+  "com_ui_artifact_source": "Opens as source",
   "com_ui_artifacts": "Artifacts",
   "com_ui_artifacts_mode": "Mode",
   "com_ui_artifacts_mode_custom": "Custom",
@@ -1168,7 +1178,6 @@
   "com_ui_client_id": "Client ID",
   "com_ui_client_secret": "Client Secret",
   "com_ui_close": "Close",
-  "com_ui_close_artifact": "Close artifact",
   "com_ui_close_menu": "Close Menu",
   "com_ui_close_settings": "Close Settings",
   "com_ui_close_var": "Close {{0}}",
@@ -1435,6 +1444,7 @@
   "com_ui_export_file_search": "File Search",
   "com_ui_export_image": "Image",
   "com_ui_export_mermaid": "Export diagram",
+  "com_ui_export_mermaid_source": "Download source",
   "com_ui_export_png": "Export as PNG",
   "com_ui_export_retrieval": "Retrieval",
   "com_ui_export_share_link_active": "Export/Share, link active",
@@ -1764,6 +1774,8 @@
   "com_ui_mermaid_export_complete": "Diagram download started.",
   "com_ui_mermaid_export_failed": "Could not export this diagram. Please try again.",
   "com_ui_mermaid_exporting_png": "Creating PNG...",
+  "com_ui_mermaid_exporting_source": "Preparing source file...",
+  "com_ui_mermaid_exporting_svg": "Creating SVG...",
   "com_ui_mermaid_failed": "Failed to render diagram:",
   "com_ui_message_input": "Message input",
   "com_ui_message_model": "Model: {{0}}",
@@ -1867,7 +1879,6 @@
   "com_ui_one_action_cancelled": "1 cancelled",
   "com_ui_one_action_failed": "1 failed",
   "com_ui_open_archived_chat_new_tab_title": "{{title}} (opens in new tab)",
-  "com_ui_open_artifact": "Open artifact",
   "com_ui_open_as_artifact": "Open as artifact",
   "com_ui_open_project": "Open project",
   "com_ui_open_source_chat_new_tab": "Open Source Chat in New Tab",
diff --git a/client/src/utils/__tests__/artifacts.test.ts b/client/src/utils/__tests__/artifacts.test.ts
index 41288b4eb2..874d361bb0 100644
--- a/client/src/utils/__tests__/artifacts.test.ts
+++ b/client/src/utils/__tests__/artifacts.test.ts
@@ -1,6 +1,7 @@
 import { FileSources } from 'librechat-data-provider';
 import type { ToolArtifactType } from '../artifacts';
 import {
+  artifactRowKind,
   buildSandpackOptions,
   getArtifactDownloadFilename,
   detectArtifactTypeFromFile,
@@ -1009,8 +1010,6 @@ describe('getArtifactDownloadFilename', () => {
     ['README.markdown', 'content.md'],
     ['README.mdx', 'content.md'],
     ['README.md', 'content.md'],
-    ['flow.mermaid', 'diagram.mmd'],
-    ['flow.mmd', 'diagram.mmd'],
     ['script.pyi', 'content.md'],
     ['Dockerfile', 'content.md'],
     ['Makefile', 'content.md'],
@@ -1024,6 +1023,38 @@ describe('getArtifactDownloadFilename', () => {
     expect(getArtifactDownloadFilename(artifact!, fileKey)).toBe(expected);
   });
 
+  it.each(['flow.mermaid', 'flow.mmd'])(
+    'marks a file-backed mermaid blob as a preview of its stored file: %s',
+    (filename) => {
+      /* The blob is the cached extraction, which the backend truncates past
+       * 512 KB — only the original-file route delivers the stored `.mmd`,
+       * so these bytes must not take the stored file's name. */
+      const artifact = fileToArtifact({ file_id: 'file', filename, text: 'graph TD\nA-->B' });
+      expect(artifact?.type).toBe(TOOL_ARTIFACT_TYPES.MERMAID);
+      const dot = filename.lastIndexOf('.');
+      expect(getArtifactDownloadFilename(artifact!, 'diagram.mmd')).toBe(
+        `${filename.slice(0, dot)}.preview${filename.slice(dot)}`,
+      );
+    },
+  );
+
+  it('keeps a model-authored mermaid diagram under its own name', () => {
+    /* No stored file exists for an authored diagram, so its content is the
+     * only artifact there is and nothing is being previewed. */
+    expect(
+      getArtifactDownloadFilename(
+        {
+          id: 'artifact-1',
+          lastUpdateTime: 0,
+          type: TOOL_ARTIFACT_TYPES.MERMAID,
+          title: 'Flow',
+          content: 'graph TD\nA-->B',
+        },
+        'diagram.mmd',
+      ),
+    ).toBe('Flow.mmd');
+  });
+
   it.each(['untitled', 'Generated artifact'])(
     'preserves the real attachment filename %s',
     (filename) => {
@@ -1123,3 +1154,69 @@ describe('getArtifactDownloadFilename', () => {
     ).toBe(`${'a'.repeat(97)}.preview.py`);
   });
 });
+
+describe('artifactRowKind', () => {
+  it('marks the rendered buckets as previews and code as source', () => {
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.HTML }).rendersPreview).toBe(true);
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.REACT }).rendersPreview).toBe(true);
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.MARKDOWN }).rendersPreview).toBe(true);
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.SPREADSHEET }).rendersPreview).toBe(true);
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.CODE, title: 'a.py' }).rendersPreview).toBe(
+      false,
+    );
+    /* Plain text opens on the panel's rendered markdown preview
+     * (`useArtifactProps` -> `getMarkdownFiles`), so the row announces a
+     * preview rather than source. */
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.PLAIN_TEXT }).rendersPreview).toBe(true);
+  });
+
+  it('names each rendered format with its own label', () => {
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.HTML }).label).toEqual({
+      key: 'com_ui_artifact_format_html',
+    });
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.PRESENTATION }).label).toEqual({
+      key: 'com_ui_artifact_format_presentation',
+    });
+  });
+
+  it('resolves the model-authored type spellings to the same buckets', () => {
+    /* The markdown `:::artifact` path passes the authored attribute
+     * through verbatim, so these aliases reach the row alongside the
+     * canonical MIMEs. */
+    expect(artifactRowKind({ type: 'application/vnd.ant.react' })).toEqual(
+      artifactRowKind({ type: TOOL_ARTIFACT_TYPES.REACT }),
+    );
+    expect(artifactRowKind({ type: 'application/vnd.code-html' })).toEqual(
+      artifactRowKind({ type: TOOL_ARTIFACT_TYPES.HTML }),
+    );
+    expect(artifactRowKind({ type: 'text/md' })).toEqual(
+      artifactRowKind({ type: TOOL_ARTIFACT_TYPES.MARKDOWN }),
+    );
+  });
+
+  it('labels a code artifact with its language, preferring the stored hint', () => {
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.CODE, language: 'python' })).toMatchObject({
+      lang: 'python',
+      label: { text: 'python' },
+    });
+    /* No stored hint (older records, markdown path) — derive it from the
+     * title the way the panel derives its fence hint. */
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.CODE, title: 'main.rs' })).toMatchObject({
+      lang: 'rust',
+      label: { text: 'rust' },
+    });
+    /* Neither: an extensionless, unrecognized name still needs a label. */
+    expect(artifactRowKind({ type: TOOL_ARTIFACT_TYPES.CODE, title: 'script' })).toMatchObject({
+      lang: '',
+      label: { key: 'com_ui_code' },
+    });
+  });
+
+  it('treats an unknown type as a rendered artifact, matching the static template fallback', () => {
+    expect(artifactRowKind({ type: 'application/x-unheard-of' })).toMatchObject({
+      rendersPreview: true,
+      fallbackGlyph: 'preview',
+    });
+    expect(artifactRowKind({})).toMatchObject({ rendersPreview: true });
+  });
+});
diff --git a/client/src/utils/artifacts.ts b/client/src/utils/artifacts.ts
index c3e473d56b..cae3937eef 100644
--- a/client/src/utils/artifacts.ts
+++ b/client/src/utils/artifacts.ts
@@ -14,6 +14,7 @@ import type {
 } from '@codesandbox/sandpack-react';
 import type { TStartupConfig, TAttachment, TFile } from 'librechat-data-provider';
 import type { PhrasingContent } from 'mdast';
+import type { TranslationKeys } from '~/hooks/useLocalize';
 import type { Artifact } from '~/common';
 import { MERMAID_ARTIFACT_TYPE } from '~/common/artifacts';
 import { getCodeBlockFilename } from './downloadFile';
@@ -170,7 +171,11 @@ export function getArtifactDownloadFilename(
     filename = hasSourceFilename || hasMatchingExtension ? title : `${title}${extension}`;
   }
   filename = filenamify(filename, { replacement: '_' });
-  /* File-backed blobs export cached preview content, not the original file. */
+  /* A file-backed artifact's blob is the cached extraction (or an edit of
+   * it), never the stored file: `extractUtf8` truncates past 512 KB, so
+   * handing these bytes over under the original name would claim to be
+   * the file. Mermaid is no exception — a share that dropped the download
+   * route leaves only that same cached text. */
   if (artifact.download) {
     const dot = filename.lastIndexOf('.');
     filename =
@@ -448,6 +453,168 @@ export function isCodeOnlyArtifact(type: string | null | undefined): boolean {
   return type === TOOL_ARTIFACT_TYPES.CODE;
 }
 
+/**
+ * Glyph buckets an artifact row falls back to when the file type has no
+ * brand icon in `LANG_ICON_PATHS` (React, the office previews, mermaid,
+ * and every code language without a logo).
+ */
+export type ArtifactGlyph =
+  | 'preview'
+  | 'code'
+  | 'text'
+  | 'diagram'
+  | 'document'
+  | 'spreadsheet'
+  | 'presentation';
+
+/**
+ * How a chat row presents one artifact.
+ *
+ * `rendersPreview` is the distinction the row exists to carry: an HTML,
+ * React, markdown or office artifact opens as something to *look at*,
+ * while a `.py` or `.sql` artifact opens as source to *read*. The panel
+ * already knows the difference (`isCodeOnlyArtifact` hides its preview
+ * tab); before this, the chat trigger showed both as the same `<>` chip.
+ */
+export interface ArtifactRowKind {
+  /** `LangIcon` hint; `''` when no brand glyph applies. */
+  lang: string;
+  /**
+   * Format name shown beside the title. A translation key for named
+   * formats; a raw language identifier (`python`, `hcl`) for the CODE
+   * bucket, which follows `CodeWindowHeader` in printing the hint
+   * verbatim rather than inventing a localized name per language.
+   */
+  label: { key: ArtifactFormatKey } | { text: string };
+  /** Opening this artifact yields a rendered view, not source. */
+  rendersPreview: boolean;
+  fallbackGlyph: ArtifactGlyph;
+}
+
+type ArtifactFormatKey = Extract<
+  TranslationKeys,
+  | 'com_ui_artifact_format_html'
+  | 'com_ui_artifact_format_react'
+  | 'com_ui_artifact_format_markdown'
+  | 'com_ui_artifact_format_text'
+  | 'com_ui_artifact_format_diagram'
+  | 'com_ui_artifact_format_document'
+  | 'com_ui_artifact_format_spreadsheet'
+  | 'com_ui_artifact_format_presentation'
+  | 'com_ui_code'
+  | 'com_ui_preview'
+>;
+
+/**
+ * Legacy and model-authored spellings of the canonical buckets. The
+ * markdown `:::artifact` path takes its type straight from the authored
+ * attribute, so these arrive alongside the values in
+ * `TOOL_ARTIFACT_TYPES`; `artifactTemplate` carries the same aliases.
+ */
+const ARTIFACT_TYPE_ALIASES: Record = {
+  'application/vnd.ant.react': TOOL_ARTIFACT_TYPES.REACT,
+  'application/vnd.code-html': TOOL_ARTIFACT_TYPES.HTML,
+  'text/md': TOOL_ARTIFACT_TYPES.MARKDOWN,
+};
+
+const ARTIFACT_ROW_KINDS: Record = {
+  [TOOL_ARTIFACT_TYPES.HTML]: {
+    lang: 'html',
+    label: { key: 'com_ui_artifact_format_html' },
+    rendersPreview: true,
+    fallbackGlyph: 'preview',
+  },
+  [TOOL_ARTIFACT_TYPES.REACT]: {
+    lang: '',
+    label: { key: 'com_ui_artifact_format_react' },
+    rendersPreview: true,
+    fallbackGlyph: 'preview',
+  },
+  [TOOL_ARTIFACT_TYPES.MARKDOWN]: {
+    lang: 'markdown',
+    label: { key: 'com_ui_artifact_format_markdown' },
+    rendersPreview: true,
+    fallbackGlyph: 'text',
+  },
+  [TOOL_ARTIFACT_TYPES.MERMAID]: {
+    lang: '',
+    label: { key: 'com_ui_artifact_format_diagram' },
+    rendersPreview: true,
+    fallbackGlyph: 'diagram',
+  },
+  [TOOL_ARTIFACT_TYPES.DOCX]: {
+    lang: '',
+    label: { key: 'com_ui_artifact_format_document' },
+    rendersPreview: true,
+    fallbackGlyph: 'document',
+  },
+  [TOOL_ARTIFACT_TYPES.SPREADSHEET]: {
+    lang: '',
+    label: { key: 'com_ui_artifact_format_spreadsheet' },
+    rendersPreview: true,
+    fallbackGlyph: 'spreadsheet',
+  },
+  [TOOL_ARTIFACT_TYPES.PRESENTATION]: {
+    lang: '',
+    label: { key: 'com_ui_artifact_format_presentation' },
+    rendersPreview: true,
+    fallbackGlyph: 'presentation',
+  },
+  [TOOL_ARTIFACT_TYPES.PLAIN_TEXT]: {
+    lang: '',
+    label: { key: 'com_ui_artifact_format_text' },
+    /* `useArtifactProps` routes plain text through `getMarkdownFiles` and
+     * `isCodeOnlyArtifact` covers only CODE, so the panel opens a `.txt`
+     * on its rendered preview tab — the row must say so. */
+    rendersPreview: true,
+    fallbackGlyph: 'text',
+  },
+};
+
+/**
+ * Resolve the glyph, format name and preview/source split for one
+ * artifact row. Takes the fields rather than the whole `Artifact` so
+ * both the file-backed path (where `title` is the on-disk filename) and
+ * the markdown path (where it is authored prose) can call it.
+ */
+export function artifactRowKind({
+  type,
+  language,
+  title,
+}: {
+  type?: string | null;
+  language?: string | null;
+  title?: string | null;
+}): ArtifactRowKind {
+  const resolvedType = (type != null && lookupOwn(ARTIFACT_TYPE_ALIASES, type)) || type;
+  if (resolvedType != null) {
+    const known = lookupOwn(ARTIFACT_ROW_KINDS, resolvedType);
+    if (known != null) {
+      return known;
+    }
+  }
+  /* `language` is written at construction for the CODE bucket, but the
+   * markdown path never sets it, so fall back to the title the way the
+   * panel's fence hint does. */
+  const lang = language || languageForFilename(title ?? undefined);
+  if (resolvedType === TOOL_ARTIFACT_TYPES.CODE) {
+    return {
+      lang,
+      label: lang ? { text: lang } : { key: 'com_ui_code' },
+      rendersPreview: false,
+      fallbackGlyph: 'code',
+    };
+  }
+  /* Unknown types ride `artifactTemplate.default` — a `static` Sandpack
+   * template — so the panel renders them. */
+  return {
+    lang,
+    label: lang ? { text: lang } : { key: 'com_ui_preview' },
+    rendersPreview: true,
+    fallbackGlyph: 'preview',
+  };
+}
+
 /**
  * Extension → fenced-code-block language hint for the CODE bucket. The
  * key is the lowercased file extension (no dot); the value is the
diff --git a/e2e/specs/mock/mermaid-artifacts.spec.ts b/e2e/specs/mock/mermaid-artifacts.spec.ts
index 0d44454748..ed410ae468 100644
--- a/e2e/specs/mock/mermaid-artifacts.spec.ts
+++ b/e2e/specs/mock/mermaid-artifacts.spec.ts
@@ -71,11 +71,12 @@ test.describe('Mermaid Artifact resource boundary', () => {
     expect(canvasBox).not.toBeNull();
     expect(canvasBox!.height).toBeGreaterThan(panelBox!.height * 0.75);
     await expect(panel.locator('iframe')).toHaveCount(0);
-    const artifactCard = messages.locator('[data-artifact-trigger^="mermaid-artifact-"]');
-    await expect(artifactCard).toHaveAttribute('aria-expanded', 'true');
-    await expect(artifactCard).toHaveClass(/\bw-fit\b/);
-    await expect(artifactCard.locator('.lucide-workflow').locator('..')).toHaveClass(
-      /\bbg-status-info-subtle\b/,
+    const artifactRow = messages.locator('[data-artifact-trigger^="mermaid-artifact-"]');
+    await expect(artifactRow).toHaveAttribute('aria-expanded', 'true');
+    /* The trigger is an `ArtifactRow`: the diagram glyph rides the row's
+     * glyph slot, tinted with the accent that marks a rendered preview. */
+    await expect(artifactRow.locator('.lucide-workflow').locator('..')).toHaveClass(
+      /\btext-status-info\b/,
     );
 
     expect(await unexpectedRequest).toBeNull();
@@ -89,7 +90,7 @@ test.describe('Mermaid Artifact resource boundary', () => {
     expect(response.ok()).toBeTruthy();
 
     const artifactButton = messagesView(page).getByRole('button', {
-      name: 'E2E HTML Artifact Click to open',
+      name: 'E2E HTML Artifact HTML Opens as a rendered preview Click to open',
       exact: true,
     });
     await expect(artifactButton).toBeVisible();
diff --git a/e2e/specs/mock/scenarios/artifact-trigger-rows.spec.ts b/e2e/specs/mock/scenarios/artifact-trigger-rows.spec.ts
new file mode 100644
index 0000000000..098f6d2b17
--- /dev/null
+++ b/e2e/specs/mock/scenarios/artifact-trigger-rows.spec.ts
@@ -0,0 +1,193 @@
+import { randomUUID } from 'node:crypto';
+import { expect, test } from '@playwright/test';
+import { getE2EUser } from '../../../setup/user';
+import {
+  deleteConversations,
+  deleteMessagesByConversation,
+  seedConversations,
+  seedMessages,
+} from '../db';
+import type { SeedMessage } from '../db';
+import { messagesView } from '../helpers';
+
+const ROOT_PARENT = '00000000-0000-0000-0000-000000000000';
+const SHOWCASE_TEXT = [
+  ':::artifact{identifier="e2e-dashboard" type="text/html" title="dashboard.html"}',
+  '

Dashboard

', + ':::', + '', + ':::artifact{identifier="e2e-ingest" type="application/vnd.code" title="ingest.py"}', + '```python', + 'print("ingest")', + '```', + ':::', + '', + ':::artifact{identifier="e2e-schema" type="application/vnd.code" title="schema.sql"}', + '```sql', + 'SELECT 1;', + '```', + ':::', + '', + ':::artifact{identifier="e2e-findings" type="text/markdown" title="findings.md"}', + '## Findings', + '', + 'No findings.', + ':::', + '', + '```mermaid', + 'flowchart LR', + ' A[Start] --> B[Done]', + '```', +].join('\n'); + +test.describe('artifact trigger rows', () => { + test( + 'showcase artifacts share one tool row axis ' + + '@scenario:artifact-triggers-share-one-tool-row-axis', + async ({ page }) => { + const conversationId = randomUUID(); + const messageId = randomUUID(); + const userEmail = getE2EUser().email; + const message: SeedMessage = { + messageId, + parentMessageId: ROOT_PARENT, + text: SHOWCASE_TEXT, + isCreatedByUser: false, + sender: 'Assistant', + model: 'mock-model-a', + }; + + try { + await seedConversations(userEmail, [ + { conversationId, title: 'Artifact trigger rows', updatedAt: new Date() }, + ]); + await seedMessages(userEmail, conversationId, [message]); + await page.goto(`/c/${conversationId}`, { timeout: 10000 }); + + const messages = messagesView(page); + const rows = messages.locator('[data-artifact-trigger]'); + await expect(rows).toHaveCount(4); + + for (let index = 0; index < (await rows.count()); index++) { + const row = rows.nth(index); + await row.scrollIntoViewIfNeeded(); + await expect(row).toBeVisible(); + } + + const boxes = await rows.evaluateAll((elements) => + elements.map((element) => { + const box = element.getBoundingClientRect(); + return { x: box.x, y: box.y + window.scrollY }; + }), + ); + expect(boxes).toHaveLength(4); + for (let index = 1; index < boxes.length; index++) { + expect(boxes[index].y).toBeGreaterThan(boxes[index - 1].y); + expect(Math.abs(boxes[index].x - boxes[0].x)).toBeLessThanOrEqual(1); + } + + const expectedRows = [ + ['dashboard.html', 'HTML'], + ['ingest.py', 'python'], + ['schema.sql', 'sql'], + ['findings.md', 'Markdown'], + ] as const; + for (const [title, format] of expectedRows) { + const row = rows.filter({ hasText: title }); + await expect(row).toHaveCount(1); + await expect(row.getByText(format, { exact: true })).toBeVisible(); + } + + const openMermaidButton = messages.getByRole('button', { + name: 'Open as artifact', + exact: true, + }); + await openMermaidButton.click(); + + const mermaidRow = messages.locator('[data-artifact-trigger^="mermaid-artifact-"]'); + await expect(mermaidRow).toHaveCount(1); + await expect(mermaidRow).toBeVisible(); + await expect(rows).toHaveCount(5); + await expect(rows.nth(4)).toHaveAttribute('data-artifact-trigger', /^mermaid-artifact-/); + + /* Opening an artifact narrows the chat column, so the axis is only + * meaningful when every row is measured in the same layout state. */ + const finalBoxes = await rows.evaluateAll((elements) => + elements.map((element) => { + const box = element.getBoundingClientRect(); + return { x: box.x, y: box.y + window.scrollY }; + }), + ); + expect(finalBoxes).toHaveLength(5); + for (let index = 1; index < finalBoxes.length; index++) { + expect(finalBoxes[index].y).toBeGreaterThan(finalBoxes[index - 1].y); + expect(Math.abs(finalBoxes[index].x - finalBoxes[0].x)).toBeLessThanOrEqual(1); + } + await expect(mermaidRow.getByText('Diagram', { exact: true })).toBeVisible(); + } finally { + await deleteMessagesByConversation([conversationId]); + await deleteConversations([conversationId]); + } + }, + ); + + test( + 'artifact rows announce preview or source honestly ' + + '@scenario:artifact-row-announces-preview-or-source', + async ({ page }) => { + const conversationId = randomUUID(); + const messageId = randomUUID(); + const userEmail = getE2EUser().email; + const message: SeedMessage = { + messageId, + parentMessageId: ROOT_PARENT, + text: SHOWCASE_TEXT, + isCreatedByUser: false, + sender: 'Assistant', + model: 'mock-model-a', + }; + + try { + await seedConversations(userEmail, [ + { conversationId, title: 'Artifact trigger rows', updatedAt: new Date() }, + ]); + await seedMessages(userEmail, conversationId, [message]); + await page.goto(`/c/${conversationId}`, { timeout: 10000 }); + + const messages = messagesView(page); + const rows = messages.locator('[data-artifact-trigger]'); + await expect(rows).toHaveCount(4); + + const dashboard = rows.filter({ hasText: 'dashboard.html' }); + await expect(dashboard).toHaveAccessibleName( + /dashboard\.html.*HTML.*Opens as a rendered preview/, + ); + + const ingest = rows.filter({ hasText: 'ingest.py' }); + await expect(ingest).toHaveAccessibleName(/ingest\.py.*python.*Opens as source/); + + const findings = rows.filter({ hasText: 'findings.md' }); + await expect(findings).toHaveAccessibleName( + /findings\.md.*Markdown.*Opens as a rendered preview/, + ); + + await ingest.click(); + await expect(ingest).toHaveAttribute('aria-expanded', 'true'); + await expect(ingest).toHaveAccessibleName(/Click to close/); + + const panel = page.locator('#artifact-viewer'); + await expect(panel).toBeVisible(); + await expect(panel).toHaveAttribute('aria-label', 'ingest.py'); + await expect(panel.getByRole('radio', { name: 'Preview', exact: true })).toHaveCount(0); + const width = page.viewportSize()?.width ?? 0; + if (width >= 869) { + await expect(panel.getByRole('radio')).toHaveCount(1); + await expect(panel.getByRole('radio', { name: 'ingest.py', exact: true })).toBeVisible(); + } + } finally { + await deleteMessagesByConversation([conversationId]); + await deleteConversations([conversationId]); + } + }, + ); +}); diff --git a/e2e/specs/mock/scenarios/mermaid-export-menu.spec.ts b/e2e/specs/mock/scenarios/mermaid-export-menu.spec.ts new file mode 100644 index 0000000000..30a5eb6cf2 --- /dev/null +++ b/e2e/specs/mock/scenarios/mermaid-export-menu.spec.ts @@ -0,0 +1,81 @@ +import { expect, test } from '@playwright/test'; +import type { Download } from '@playwright/test'; +import { + MOCK_ENDPOINTS, + NEW_CHAT_PATH, + messagesView, + selectMockEndpoint, + sendMessage, +} from '../helpers'; + +async function downloadBytes(download: Download): Promise { + const stream = await download.createReadStream(); + const chunks: Buffer[] = []; + for await (const chunk of stream as AsyncIterable) { + chunks.push(Buffer.from(chunk)); + } + return Buffer.concat(chunks); +} + +test.describe('Mermaid artifact export menu', () => { + test( + 'offers every Mermaid export format on both tabs ' + + '@scenario:mermaid-export-menu-offers-every-format-on-both-tabs', + async ({ page }) => { + await page.goto(NEW_CHAT_PATH, { timeout: 10000 }); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + + const response = await sendMessage(page, 'E2E_MERMAID_ARTIFACT_REPLY'); + expect(response.ok()).toBeTruthy(); + + const messages = messagesView(page); + await expect(messages.getByRole('img', { name: 'Mermaid diagram' })).toBeVisible(); + await messages.getByRole('button', { name: 'Open as artifact', exact: true }).click(); + + /* The panel is a `region` on desktop and a `dialog` on mobile + * (Artifacts.tsx:344), so address it by its stable id. */ + const panel = page.locator('#artifact-viewer'); + await expect(panel).toBeVisible(); + await expect(panel.getByRole('img', { name: 'Mermaid diagram' })).toBeVisible(); + + const exportButton = panel.getByRole('button', { name: 'Export diagram', exact: true }); + await expect(exportButton).toHaveCount(1); + await expect(panel.getByRole('button', { name: /^Download / })).toHaveCount(0); + + await exportButton.click(); + const menu = page.getByRole('menu').last(); + await expect( + menu.getByRole('menuitem', { name: 'Export as SVG', exact: true }), + ).toBeEnabled(); + await expect( + menu.getByRole('menuitem', { name: 'Export as PNG', exact: true }), + ).toBeEnabled(); + await expect( + menu.getByRole('menuitem', { name: 'Download source', exact: true }), + ).toBeEnabled(); + await expect(menu.getByRole('menuitem')).toHaveCount(3); + + await exportButton.click(); + const codeTab = panel.getByRole('radio', { name: 'Code', exact: true }); + await codeTab.click(); + await expect(codeTab).toHaveAttribute('aria-checked', 'true'); + await expect(exportButton).toBeVisible(); + await exportButton.click(); + + const codeMenu = page.getByRole('menu').last(); + await expect( + codeMenu.getByRole('menuitem', { name: 'Export as SVG', exact: true }), + ).toBeVisible(); + await expect( + codeMenu.getByRole('menuitem', { name: 'Export as PNG', exact: true }), + ).toBeVisible(); + const sourceItem = codeMenu.getByRole('menuitem', { name: 'Download source', exact: true }); + await expect(sourceItem).toBeEnabled(); + await expect(codeMenu.getByRole('menuitem')).toHaveCount(3); + + const [download] = await Promise.all([page.waitForEvent('download'), sourceItem.click()]); + expect(download.suggestedFilename()).toMatch(/\.mmd$/); + expect((await downloadBytes(download)).toString('utf8')).toContain('flowchart LR'); + }, + ); +}); diff --git a/e2e/specs/mock/scenarios/mermaid-source-download.spec.ts b/e2e/specs/mock/scenarios/mermaid-source-download.spec.ts new file mode 100644 index 0000000000..2ff8804718 --- /dev/null +++ b/e2e/specs/mock/scenarios/mermaid-source-download.spec.ts @@ -0,0 +1,208 @@ +import { randomUUID } from 'crypto'; +import { expect, test } from '@playwright/test'; +import type { Page, Route } from '@playwright/test'; +import { getE2EUser } from '../../../setup/user'; +import { escapeRegExp } from '../helpers'; + +const NO_PARENT = '00000000-0000-0000-0000-000000000000'; +const CACHED_DIAGRAM = `flowchart LR + A[Start] --> B[Middle]`; +const STORED_DIAGRAM = `flowchart LR\n A[Start] --> B[Middle]\n B --> Z[StoredOnly]\n`; +const FAILURE_MESSAGE = 'Could not export this diagram. Please try again.'; +const SUCCESS_MESSAGE = 'Diagram download started.'; +const DOWNLOAD_ERROR_MESSAGE = 'Error downloading file. The file may have been deleted.'; + +async function installFixture(page: Page, fail: boolean) { + const conversationId = `e2e-mermaid-source-${randomUUID()}`; + const messageId = `${conversationId}-message`; + const fileId = `${conversationId}-file`; + const downloadUser = getE2EUser().email; + const filename = 'flow.mmd'; + const attachment = { + file_id: fileId, + filename, + filepath: `/uploads/${downloadUser}/${fileId}__${filename}`, + type: 'execute_code', + source: 'local', + user: downloadUser, + text: CACHED_DIAGRAM, + bytes: Buffer.byteLength(STORED_DIAGRAM), + messageId, + conversationId, + toolCallId: `${conversationId}-tool-call`, + }; + const now = new Date().toISOString(); + const conversation = { + conversationId, + title: 'Mermaid source download fixture', + endpoint: 'Mock Provider A', + endpointType: 'custom', + model: 'mock-model-a', + createdAt: now, + updatedAt: now, + }; + const message = { + messageId, + conversationId, + parentMessageId: NO_PARENT, + isCreatedByUser: false, + sender: 'Assistant', + endpoint: 'Mock Provider A', + model: 'mock-model-a', + text: '', + content: [ + { + type: 'tool_call', + tool_call: { + id: attachment.toolCallId, + name: 'execute_code', + args: '{"lang":"mermaid","code":"flowchart LR"}', + output: 'generated flow.mmd', + progress: 1, + }, + }, + ], + attachments: [attachment], + createdAt: now, + updatedAt: now, + }; + const conversationRe = escapeRegExp(conversationId); + const downloadRe = new RegExp( + `/api/files/download/${escapeRegExp(downloadUser)}/${escapeRegExp(fileId)}(?:\\?.*)?$`, + ); + + await page.route(new RegExp(`/api/convos/${conversationRe}(?:\\?.*)?$`), (route: Route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(conversation), + }), + ); + await page.route(new RegExp(`/api/messages/${conversationRe}(?:\\?.*)?$`), (route: Route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([message]), + }), + ); + await page.route(downloadRe, (route: Route) => + fail + ? route.fulfill({ status: 500, contentType: 'text/plain', body: 'stored file unavailable' }) + : route.fulfill({ + status: 200, + contentType: 'text/plain', + body: STORED_DIAGRAM, + }), + ); + + return conversationId; +} + +async function openSourceMenu(page: Page, conversationId: string) { + await page.goto(`/c/${conversationId}`, { timeout: 30000 }); + const messages = page.getByTestId('messages-view'); + const artifactButton = messages.getByRole('button', { + name: 'Open as artifact', + exact: true, + }); + await expect(artifactButton).toBeVisible({ timeout: 30000 }); + await artifactButton.click(); + + const panel = page.locator('#artifact-viewer'); + await expect(panel).toBeVisible(); + const exportButton = panel.getByRole('button', { name: 'Export diagram', exact: true }); + await exportButton.click(); + const sourceItem = page.getByRole('menuitem', { name: 'Download source', exact: true }); + await expect(sourceItem).toBeEnabled(); + return { panel, sourceItem }; +} + +test.describe('Mermaid source downloads', () => { + test( + 'saves the complete stored Mermaid file rather than cached text ' + + '@scenario:mermaid-source-download-saves-the-stored-file', + async ({ page }) => { + const conversationId = await installFixture(page, false); + const { panel, sourceItem } = await openSourceMenu(page, conversationId); + + const [download] = await Promise.all([page.waitForEvent('download'), sourceItem.click()]); + expect(download.suggestedFilename()).toBe('flow.mmd'); + const stream = await download.createReadStream(); + const chunks: Buffer[] = []; + for await (const chunk of stream as AsyncIterable) { + chunks.push(Buffer.from(chunk)); + } + const source = Buffer.concat(chunks).toString('utf8'); + expect(source).toContain('Z[StoredOnly]'); + await expect(panel.getByRole('status')).toHaveText(SUCCESS_MESSAGE); + }, + ); + + test( + 'announces when the stored Mermaid source cannot be downloaded ' + + '@scenario:mermaid-source-download-failure-is-announced', + async ({ page }) => { + const conversationId = await installFixture(page, true); + const { panel, sourceItem } = await openSourceMenu(page, conversationId); + + await sourceItem.click(); + const status = panel.getByRole('status'); + await expect(status).toHaveText(FAILURE_MESSAGE); + await expect(status).not.toHaveText(SUCCESS_MESSAGE); + /* One press, one toast: the download layer names the cause in the + * notification, and the menu's live region carries the export's own + * failure phrase. */ + const toasts = page.getByRole('region', { name: /Notifications/ }); + await expect(toasts.getByText(DOWNLOAD_ERROR_MESSAGE, { exact: true })).toHaveCount(1); + await expect(toasts.getByText(FAILURE_MESSAGE, { exact: true })).toHaveCount(0); + }, + ); + + test( + 'the opened diagram row carries its filename and download once ' + + '@scenario:file-backed-mermaid-row-owns-its-filename-and-download', + async ({ page }) => { + const conversationId = await installFixture(page, false); + await page.goto(`/c/${conversationId}`, { timeout: 30000 }); + + const messages = page.getByTestId('messages-view'); + const openButton = messages.getByRole('button', { name: 'Open as artifact', exact: true }); + await expect(openButton).toBeVisible({ timeout: 30000 }); + /* Before opening, the wrapper header is the only place the filename + * and its download live. */ + await expect(messages.getByRole('button', { name: 'Download flow.mmd' })).toHaveCount(1); + await openButton.click(); + + /* A file-backed diagram's trigger carries the attachment's artifact + * id, not the `mermaid-artifact-` id a model-authored fence gets. */ + const row = messages.locator('[data-artifact-trigger]'); + await expect(row).toHaveCount(1); + await expect(row).toHaveAccessibleName(/flow\.mmd Diagram/); + /* The row replaced the wrapper header rather than stacking on top of + * it: one filename, one download, both inside the row. */ + await expect(messages.getByText('flow.mmd', { exact: true })).toHaveCount(1); + const download = messages.getByRole('button', { name: 'Download flow.mmd' }); + await expect(download).toHaveCount(1); + const rowBox = await row.boundingBox(); + const downloadBox = await download.boundingBox(); + expect(rowBox).not.toBeNull(); + expect(downloadBox).not.toBeNull(); + expect(downloadBox!.y).toBeGreaterThanOrEqual(rowBox!.y - 1); + expect(downloadBox!.y + downloadBox!.height).toBeLessThanOrEqual( + rowBox!.y + rowBox!.height + 1, + ); + + /* On a phone the artifact opens as a sheet over the message list, so + * dismiss the panel with its own close control before reaching the + * row's download; the trigger stays a row once opened. */ + await page.locator('#artifact-viewer').getByRole('button', { name: 'Close' }).click(); + await expect(page.locator('#artifact-viewer')).toBeHidden(); + await expect(row).toHaveAttribute('aria-expanded', 'false'); + await expect(messages.getByText('flow.mmd', { exact: true })).toHaveCount(1); + await expect(download).toHaveCount(1); + + const [file] = await Promise.all([page.waitForEvent('download'), download.click()]); + expect(file.suggestedFilename()).toBe('flow.mmd'); + }, + ); +}); diff --git a/e2e/specs/mock/scenarios/pending-artifact-row-slot.spec.ts b/e2e/specs/mock/scenarios/pending-artifact-row-slot.spec.ts new file mode 100644 index 0000000000..884c4d656f --- /dev/null +++ b/e2e/specs/mock/scenarios/pending-artifact-row-slot.spec.ts @@ -0,0 +1,165 @@ +import { expect, test } from '@playwright/test'; +import type { Route } from '@playwright/test'; + +const NO_PARENT = '00000000-0000-0000-0000-000000000000'; + +const unique = (prefix: string) => `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`; +const escapeRe = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +test.describe('pending artifact row ordering', () => { + test.afterEach(async ({ page }) => { + await page.unrouteAll(); + }); + + test('keeps a pending artifact preview in its row slot @scenario:pending-artifact-preview-keeps-its-row-slot', async ({ + page, + }) => { + test.setTimeout(60000); + + const conversationId = unique('e2e-pending-row-slot'); + const messageId = `${conversationId}-msg`; + const pendingFileId = `${conversationId}-xlsx`; + const resolvedFileId = `${conversationId}-html`; + const now = new Date(0).toISOString(); + const pendingFilename = 'data.xlsx'; + const resolvedFilename = 'index.html'; + const toolCallId = `${conversationId}-tool`; + + const pendingAttachment = { + file_id: pendingFileId, + filename: pendingFilename, + filepath: `/uploads/e2e/${pendingFileId}__${pendingFilename}`, + type: 'execute_code', + source: 'local', + bytes: 2048, + messageId, + conversationId, + toolCallId, + status: 'pending', + metadata: { + codeEnvRef: { kind: 'user', id: 'e2e-user', storage_session_id: 'e2e-session' }, + }, + }; + const resolvedAttachment = { + file_id: resolvedFileId, + filename: resolvedFilename, + filepath: `/uploads/e2e/${resolvedFileId}__${resolvedFilename}`, + type: 'execute_code', + source: 'local', + bytes: 16, + messageId, + conversationId, + toolCallId, + status: 'ready', + text: '

hi

', + textFormat: 'html', + }; + const message = { + messageId, + conversationId, + parentMessageId: NO_PARENT, + isCreatedByUser: false, + sender: 'Assistant', + endpoint: 'Mock Provider A', + model: 'mock-model-a', + text: '', + content: [ + { + type: 'tool_call', + tool_call: { + id: toolCallId, + name: 'execute_code', + args: '{}', + output: 'created files', + progress: 1, + }, + }, + ], + attachments: [pendingAttachment, resolvedAttachment], + createdAt: now, + updatedAt: now, + }; + const conversation = { + conversationId, + title: 'Pending artifact row slot', + endpoint: 'Mock Provider A', + endpointType: 'custom', + model: 'mock-model-a', + createdAt: now, + updatedAt: now, + }; + + let previewRequests = 0; + const convoIdRe = escapeRe(conversationId); + const pendingFileIdRe = escapeRe(pendingFileId); + 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.route( + new RegExp(`/api/files/${pendingFileIdRe}/preview(?:\\?.*)?$`), + (route: Route) => { + previewRequests += 1; + const preview = + previewRequests === 1 + ? { file_id: pendingFileId, status: 'pending' } + : { + file_id: pendingFileId, + status: 'ready', + text: '
ready
', + textFormat: 'html', + }; + return route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(preview), + }); + }, + ); + + await page.goto(`/c/${conversationId}`, { timeout: 30000 }); + + const group = page.getByTestId('artifact-row-group'); + await expect(group).toBeVisible(); + const pendingTitle = group.getByText(pendingFilename, { exact: true }); + await expect(pendingTitle).toHaveAttribute('aria-busy', 'true', { timeout: 15000 }); + const initialPendingDownload = group.getByRole('button', { + name: `Download ${pendingFilename}`, + exact: true, + }); + const initialResolvedDownload = group.getByRole('button', { + name: `Download ${resolvedFilename}`, + exact: true, + }); + const initialPendingBox = await initialPendingDownload.boundingBox(); + const initialResolvedBox = await initialResolvedDownload.boundingBox(); + expect(initialPendingBox).not.toBeNull(); + expect(initialResolvedBox).not.toBeNull(); + expect(initialPendingBox!.y).toBeLessThan(initialResolvedBox!.y); + + const pendingArtifactRow = group.getByRole('button', { + name: new RegExp(`^${escapeRe(pendingFilename)} Spreadsheet Opens as a rendered preview`), + }); + await expect(pendingArtifactRow).toBeVisible({ timeout: 15000 }); + await expect(pendingTitle).not.toHaveAttribute('aria-busy', 'true'); + + const resolvedArtifactRow = group.getByRole('button', { + name: new RegExp(`^${escapeRe(resolvedFilename)} HTML Opens as a rendered preview`), + }); + const finalPendingBox = await pendingArtifactRow.boundingBox(); + const finalResolvedBox = await resolvedArtifactRow.boundingBox(); + expect(finalPendingBox).not.toBeNull(); + expect(finalResolvedBox).not.toBeNull(); + expect(finalPendingBox!.y).toBeLessThan(finalResolvedBox!.y); + }); +}); diff --git a/e2e/specs/mock/scenarios/plain-text-artifact-row.spec.ts b/e2e/specs/mock/scenarios/plain-text-artifact-row.spec.ts new file mode 100644 index 0000000000..4c4104616c --- /dev/null +++ b/e2e/specs/mock/scenarios/plain-text-artifact-row.spec.ts @@ -0,0 +1,70 @@ +import { randomUUID } from 'node:crypto'; +import { expect, test } from '@playwright/test'; +import { getE2EUser } from '../../../setup/user'; +import { + deleteConversations, + deleteMessagesByConversation, + seedConversations, + seedMessages, +} from '../db'; +import type { SeedMessage } from '../db'; +import { messagesView } from '../helpers'; + +const ROOT_PARENT = '00000000-0000-0000-0000-000000000000'; +const PLAIN_TEXT = + ':::artifact{identifier="e2e-plain" type="text/plain" title="notes.txt"}\n' + + 'plain notes body\n' + + ':::'; + +test.describe('plain text artifact row', () => { + test( + 'announces a rendered preview for plain text artifacts ' + + '@scenario:plain-text-artifact-row-announces-rendered-preview', + async ({ page }) => { + const conversationId = randomUUID(); + const messageId = randomUUID(); + const userEmail = getE2EUser().email; + const message: SeedMessage = { + messageId, + parentMessageId: ROOT_PARENT, + text: PLAIN_TEXT, + isCreatedByUser: false, + sender: 'Assistant', + model: 'mock-model-a', + }; + + try { + await seedConversations(userEmail, [ + { conversationId, title: 'Plain text artifact', updatedAt: new Date() }, + ]); + await seedMessages(userEmail, conversationId, [message]); + + await page.goto(`/c/${conversationId}`, { timeout: 10000 }); + + const row = messagesView(page).getByRole('button', { name: /notes\.txt/ }); + await expect(row).toBeVisible(); + await expect(row).toHaveAccessibleName(/notes\.txt.*Text.*Opens as a rendered preview/); + await expect(row).not.toHaveAccessibleName(/Opens as source/); + + await row.click(); + const panel = page.locator('#artifact-viewer'); + await expect(panel).toBeVisible(); + await expect(panel).toHaveAttribute('aria-label', 'notes.txt'); + await expect( + panel.locator('iframe').contentFrame().getByText('plain notes body'), + ).toBeVisible({ timeout: 20000 }); + + const width = page.viewportSize()?.width ?? 0; + if (width >= 869) { + const previewTab = panel.getByRole('radio', { name: 'Preview', exact: true }); + await expect(previewTab).toBeVisible(); + await expect(previewTab).toHaveAttribute('aria-checked', 'true'); + await expect(panel.getByRole('radio', { name: 'Code', exact: true })).toBeVisible(); + } + } finally { + await deleteMessagesByConversation([conversationId]); + await deleteConversations([conversationId]); + } + }, + ); +});