🪧 feat: Unify Artifact Triggers as Tool Rows (#15915)

* 🪧 feat: Unify Artifact Triggers as Tool Rows

Every chat-side artifact trigger — code-execution output, a model-authored
`:::artifact` block, and a mermaid diagram — now renders through one
`ArtifactRow` that sits on the tool-row axis instead of three card variants
in a wrapped chip strip. The row carries the file type twice: the language's
brand glyph where one exists, and a format badge for titles that are not
filenames. `kind.rendersPreview` tints the glyph and folds the same fact into
the accessible name, so the row says whether opening it yields a rendered view
or source to read.

The mermaid panel routes every download through its export menu — SVG, PNG and
the diagram source — rather than parking a second, unlabelled button beside it.
The menu turns the pressed format into its own loading row, defers the
synchronous SVG export by a macrotask so the spinner paints before the frame
blocks, and no longer disappears on the code tab. A mermaid download keeps its
real filename: its content *is* the stored `.mmd`, so it is not suffixed
`.preview`.

`useArtifactDownload` holds the original-file vs. edited-content decision that
both the generic download button and the mermaid menu need.

* 🩹 fix: Save the Stored Artifact File, Not Its Cached Text

The panel serialized a mermaid diagram from `artifact.content`, which is the
backend cache `extractUtf8` truncates at 512 KB, so "Download source" saved a
corrupt `.mmd` for any larger stored diagram. An unedited mermaid artifact now
takes the same original-file route as every other text-backed artifact,
`handleDownload` reports whether bytes were actually delivered, and the export
menu turns a failed delivery into its failure status and toast instead of
"Diagram download started.".

A `text/plain` row announced "Opens as source" while the panel opened it on the
rendered markdown preview; it now announces the preview. A pending preview
placeholder keeps the row slot it arrived in rather than sinking to the end of
the artifact group and jumping up once it resolves.

* 🧪 test: Exercise Artifact Rows and Mermaid Exports End to End

Seven acceptance scenarios in the mock harness cover what the unit suites
cannot: that a message which writes five artifacts shows five trigger rows on
one axis, that a row's accessible name matches what the panel actually does
with the artifact (rendered preview vs. source, including `text/plain`), that
the mermaid export menu offers SVG, PNG and the diagram source on both the
preview and the code tab, that "Download source" delivers the stored file and
announces a failure when the stored file is unreachable, and that a pending
preview placeholder keeps the row slot it arrived in.

Each test carries its `@scenario:<id>` tag and is self-contained: fixtures come
from the existing fake-model markers, Mongo seed helpers, or page-scoped route
stubs, and every seeded conversation is deleted again.

* 🏷️ fix: Name a Mermaid Blob After the Preview It Is

A share with snapshots disabled strips the download route from a
code-execution `.mmd` but keeps the cached `attachment.text`, and that text is
what `extractUtf8` truncated at 512 KB. With no route to the stored file the
panel can only serialize that cached copy, and the mermaid exception in
`getArtifactDownloadFilename` handed those partial bytes over as `flow.mmd` —
the stored file's own name, from a menu item labelled "Download source".

Mermaid now follows every other file-backed artifact: a serialized blob is named
`flow.preview.mmd`, and only the original-file route produces `flow.mmd`. A
model-authored diagram has no stored file to be a preview of, so it keeps its
own name.

* 🎹 test: Reach the Export Menu's First Item From Either Start

`supports keyboard export` opened the menu with Enter and pressed ArrowDown
once, assuming no item was active yet. CI observed the opposite — the first item
already active — so the single ArrowDown walked past SVG onto PNG and the test
failed there while passing locally (it failed the same way on the previous head).
`Home` lands on the first item from either starting point.

* 🔧 test: Fix the Fixtures Three Artifact Scenarios Ran On

The first verification run failed five of the seven scenarios on fixture defects,
not on product behavior:

- `artifact-trigger-rows` drove a fake-model marker
  (`E2E_ARTIFACT_SHOWCASE_REPLY`) that does not exist, so the reply carried no
  artifacts and no trigger rows. Both tests now seed the assistant message text
  through Mongo, the way the passing plain-text scenario does.
- `mermaid-source-download` waited for an `ArtifactRow` that a code-execution
  `.mmd` never renders — it renders an inline diagram whose trigger is "Open as
  artifact" — and its cached diagram embedded the literal truncation marker,
  which mermaid cannot parse, so the diagram failed to render at all. The cached
  copy is now a valid shorter diagram and the stored file keeps the sentinel that
  proves which bytes were saved.
- `pending-artifact-row-slot` gave the tool call's id to only one of its two
  attachments. Attachments reach a renderer through `mapAttachments` keyed by
  tool-call id, so the other one rendered nowhere; both now carry the same id and
  land in the one `artifact-row-group` whose ordering the scenario is about.

* 🪜 test: Count Four Authored Rows, Then the Mermaid One\n\nA mermaid fence is not a trigger row while it is inline: it renders the diagram\nwith an "Open as artifact" button and only becomes an ArtifactRow once opened.\nThe axis scenario now asserts the four authored artifacts stack as rows, then\nopens the diagram and asserts its row joins the same column.

* 📐 test: Measure the Row Axis in One Layout State\n\nOpening an artifact narrows the chat column, so comparing the mermaid row's x\nagainst a box measured before the panel opened reported an 8px offset that no\nuser sees. All five rows are now measured after the open, and the panel is\nlocated at page level, where it renders \u2014 not inside the message list.

* 🧩 fix: Give the Mermaid Row Its Own Filename and Download

A code-execution `.mmd` arrives wrapped in a header that prints the filename and
a download button, and that header stayed put when the diagram collapsed into
its trigger row — so the chat showed `flow.mmd` twice and left the download
outside the row that every other file-backed artifact keeps it in.

`Mermaid` now takes the file's download action and hands it to `ArtifactRow`,
and reports whether it is currently rendered as that row; `ToolMermaidArtifact`
drops its header while the row owns both. Opening and closing the diagram
therefore moves the filename and the download between exactly one place each.

* 🔖 test: Match a File-Backed Diagram's Own Trigger Id\n\nThe row ownership scenario looked for a \ trigger id, which\nonly a model-authored fence gets; a code-execution diagram's row carries the\nattachment's artifact id.

* 📱 test: Dismiss the Artifact Sheet Before Using the Row\n\nOn a phone the artifact panel opens as a sheet over the message list, so the\nrow's download button sits behind it. The scenario now closes the panel with its\nown control first, which also shows the trigger stays a row after closing.

* 🔔 fix: Raise One Toast per Failed Source Download\n\n\ already toasts "Error downloading file" before reporting a\nfailed delivery, and the export menu then raised its own — two notifications for\none press, on every ordinary 4xx/5xx, because React Query's refetch resolves\nwith an error result rather than throwing.\n\nA reported failure now only updates the menu's live region, which keeps the\nexport's own phrase for a screen reader; a thrown task still raises the toast,\nsince nothing else has spoken for it.

* 🔕 fix: Let the Download Layer Own Every Failure It Reports

The previous round split the failure notification by cause and left a hole in
the other direction: `useAttachmentLink` toasted only its empty-response
branch, so a thrown fetch — and the artifact hook's own blob failure — returned
`false` with nobody having spoken, and the export menu's live-region-only
announcement reached no sighted user.

One rule instead of two branches: whichever layer returns `false` has already
told the user. `useAttachmentLink` toasts its thrown branch as well, and
`useArtifactDownload` toasts when the blob path throws or there is nothing to
serialize. The mermaid export menu keeps announcing the export's own phrase in
its live region, so one press still raises exactly one toast — this time for
every failure, not just the polite ones.

* 🪄 fix: Hold the Row Slot and the Frame Before Blocking Work

Two fixes on the same theme — a row or a control that moves at exactly the
moment it is meant to stay put.

Writing salience-sorted resolved entries back into their arrival slots still
moved a pending row once it resolved: the placeholder joined the sort and could
pass an empty artifact that had been sitting above it. `attachmentSalience`
reads only `bytes`, which resolution does not change, so one sort over the whole
panel row — pending entries included — is stable across the transition and is
also less code.

The export deferral used `setTimeout(…, 0)`, which only moves the blocking SVG
work to another task; the timer can still run before the browser paints the
loading row, which is the whole point of deferring it. It now waits for an
animation frame and then a task, falling back to a timer when the tab is hidden
and serves no frames.

* 🏷️ fix: Keep the Recovered Filename on the Mermaid Row\n\n\ turns a sandbox-generated \ back into\n\, but that name lived only in the wrapper header. The moment the\ndiagram collapsed into its trigger row, the row title and its download button's\naccessible name fell back to \ — the internal filename.\n\n\ now takes the caller's display name for the row, and\n\ passes the one it already computed.

* 🗂️ fix: Open Each Artifact on the Tab Its Row Promises

A code-only artifact forces the panel onto Code, and that constraint was written
back into the panel's single `activeTab`. The next HTML, Markdown, plain-text,
React or diagram artifact then opened on Code while its trigger row announced
"Opens as a rendered preview" — the row was telling the truth about the artifact
and a lie about the click.

The constrained tab no longer leaks: the panel resets to the preview tab when a
different, unconstrained artifact is opened, so a manual Code choice lasts as
long as that artifact stays open and never follows the user to the next one.
`displayedTab` already derived the forced tab for rendering, so nothing else
depended on the write-back.
This commit is contained in:
Marco Beretta 2026-09-14 21:08:07 +02:00 • committed by GitHub
parent 27acf97ad9
commit 16faadb998
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 2195 additions and 464 deletions

View file

@ -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 (
<div className="group relative my-4 rounded-xl text-sm text-text-primary">
{(() => {
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 (
<button type="button" onClick={handleClick} className={buttonClass}>
<div className="w-fit p-2">
<div className="flex flex-row items-center gap-2">
<FilePreview fileType={fileType} className="relative" />
<div className="overflow-hidden text-left">
<div className="truncate font-medium">{artifact.title}</div>
<div className="truncate text-text-secondary">{actionLabel}</div>
</div>
</div>
</div>
</button>
);
})()}
<br />
</div>
<ArtifactRow
title={artifact.title ?? ''}
kind={artifactRowKind(artifact)}
isSelected={isSelected}
onOpen={handleOpen}
artifactId={artifact.id}
/>
);
};

View file

@ -65,7 +65,7 @@ jest.mock('./ArtifactVersion', () => ({
jest.mock('./DownloadArtifact', () => ({
__esModule: true,
default: () => null,
default: () => <div data-testid="download-artifact" />,
}));
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(
<RecoilRoot>
<Artifacts />
</RecoilRoot>,
);
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: '<h1>hi</h1>',
lastUpdateTime: 2,
},
});
rerender(
<RecoilRoot>
<Artifacts />
</RecoilRoot>,
);
await waitFor(() => expect(setActiveTab).toHaveBeenCalledWith('preview'));
});
it('keeps the Mermaid export action on the code tab', async () => {
render(
<RecoilRoot>
<Artifacts />
@ -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: '<h1>Hi</h1>',
lastUpdateTime: 1,
},
orderedArtifactIds: ['html-artifact-1'],
setCurrentArtifactId: jest.fn(),
});
render(
<RecoilRoot>
<Artifacts />
</RecoilRoot>,
);
await screen.findByRole('region', { name: 'Page' });
expect(screen.getByTestId('download-artifact')).toBeInTheDocument();
expect(screen.queryByTestId('mermaid-export')).not.toBeInTheDocument();
});

View file

@ -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<string | null>(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 ? (
<MermaidExport
artifact={currentArtifact}
exportData={mermaidExportData}
portalElement={isFullscreen ? fullscreenPortalRef.current : undefined}
/>
) : (
<DownloadArtifact artifact={currentArtifact} />
)}
<DownloadArtifact artifact={currentArtifact} />
<Button
size="icon"
variant="ghost"

View file

@ -1,92 +1,12 @@
import React, { useState } from 'react';
import { Download, CircleCheckBig } from 'lucide';
import { Button, MorphIcon } 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 useArtifactDownload from '~/hooks/Artifacts/useArtifactDownload';
import { useLocalize } from '~/hooks';
const DownloadArtifact = ({ artifact }: { artifact: Artifact }) => {
const localize = useLocalize();
const { currentCode } = useCodeState();
const [isDownloaded, setIsDownloaded] = useState(false);
const { fileKey: fileName } = useArtifactProps({ artifact });
/* 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;
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 = () => {
setIsDownloaded(true);
setTimeout(() => setIsDownloaded(false), 3000);
};
const downloadContent = () => {
const content = currentCode ?? artifact.content;
if (content == null) {
return;
}
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();
};
const handleDownload = async (event: React.MouseEvent<HTMLButtonElement>) => {
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;
}
downloadContent();
} catch (error) {
console.error('Download failed:', error);
}
};
const { isDownloaded, handleDownload } = useArtifactDownload(artifact);
return (
<Button

View file

@ -10,6 +10,7 @@ interface ExportProps {
dimensions?: ProcessedMermaidSvg['dimensions'];
filename: string;
buttonClassName?: string;
onDownloadSource?: (event: React.MouseEvent<HTMLElement>) => void | Promise<void>;
}
const mockExport = jest.fn((_props: ExportProps) => null);
@ -26,6 +27,13 @@ jest.mock('~/hooks', () => ({
key,
}));
const mockArtifactDownload = jest.fn();
jest.mock('~/hooks/Artifacts/useArtifactDownload', () => ({
__esModule: true,
default: () => ({ isDownloaded: false, handleDownload: mockArtifactDownload }),
}));
const artifact: Artifact = {
id: 'tool-artifact-flow chart.mmd',
type: TOOL_ARTIFACT_TYPES.MERMAID,
@ -54,12 +62,17 @@ describe('Artifact Mermaid export', () => {
filename: 'flow.mmd',
}),
);
expect(mockExport.mock.calls[0][0]).not.toHaveProperty('source');
});
it('does not offer export before the preview SVG is ready', () => {
/* The panel renders no separate download button for mermaid, so this menu
* has to carry the source download — including before any preview has
* rendered, when SVG and PNG have nothing to work from. */
it('offers the source download even before the preview SVG is ready', () => {
render(<MermaidExport artifact={artifact} />);
expect(mockExport).not.toHaveBeenCalled();
expect(mockExport).toHaveBeenCalledTimes(1);
const props = mockExport.mock.calls[0][0];
expect(props.svg).toBeUndefined();
expect(props.onDownloadSource).toBe(mockArtifactDownload);
});
});

View file

@ -2,8 +2,19 @@ import React, { memo } from 'react';
import type { ProcessedMermaidSvg } from '~/utils/diagram/export';
import type { Artifact } from '~/common';
import MermaidExport from '~/components/Messages/Content/Mermaid/Export';
import useArtifactDownload from '~/hooks/Artifacts/useArtifactDownload';
import { useLocalize } from '~/hooks';
/**
* The artifacts panel's single download control for a mermaid diagram.
*
* It renders whether or not the preview has produced an SVG yet: SVG and PNG
* stay disabled until it has, but saving the diagram source never needed a
* render, and a control that vanishes between the code and preview tabs is
* worse than one whose items are honestly disabled. Because this menu also
* owns the source download, the panel does not render `DownloadArtifact`
* beside it for mermaid.
*/
const ArtifactMermaidExport = memo(function ArtifactMermaidExport({
artifact,
exportData,
@ -14,19 +25,17 @@ const ArtifactMermaidExport = memo(function ArtifactMermaidExport({
portalElement?: HTMLElement | null;
}) {
const localize = useLocalize();
if (exportData == null) {
return null;
}
const { handleDownload } = useArtifactDownload(artifact);
return (
<MermaidExport
key={artifact.id}
svg={exportData.svg}
dimensions={exportData.dimensions}
svg={exportData?.svg}
dimensions={exportData?.dimensions}
filename={artifact.title ?? localize('com_ui_mermaid_diagram')}
buttonClassName="h-9 w-9 p-0"
portalElement={portalElement}
onDownloadSource={handleDownload}
/>
);
});

View file

@ -1,4 +1,5 @@
import React from 'react';
import { FileSources } from 'librechat-data-provider';
import { render, screen, fireEvent, act } from '@testing-library/react';
import type { Artifact } from '~/common';
import { fileToArtifact, TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
@ -25,6 +26,8 @@ jest.mock('~/Providers/EditorContext', () => ({
useCodeState: () => ({ currentCode: mockCurrentCode }),
}));
const mockShowToast = jest.fn();
/* MorphIcon renders a single morphing <svg> with no per-icon class, so map
* the lucide icon data it was handed back to a stable name instead. */
jest.mock('@librechat/client', () => {
@ -32,6 +35,7 @@ jest.mock('@librechat/client', () => {
const { Download, CircleCheckBig } = jest.requireActual('lucide');
return {
...jest.requireActual('@librechat/client'),
useToastContext: () => ({ showToast: mockShowToast }),
MorphIcon: createMorphIconMock([
[Download, 'download'],
[CircleCheckBig, 'circle-check-big'],
@ -110,6 +114,7 @@ describe('DownloadArtifact', () => {
mockFileKey = 'index.html';
mockCurrentCode = undefined;
mockFileDownload.mockReset();
mockShowToast.mockReset();
// The attachment helper resolves to `true` when a file was delivered.
mockFileDownload.mockResolvedValue(true);
createObjectURL = jest.fn(() => 'blob:mock');
@ -195,7 +200,6 @@ describe('DownloadArtifact', () => {
['page.htm', 'index.html'],
['README.markdown', 'content.md'],
['README.mdx', 'content.md'],
['diagram.mermaid', 'diagram.mmd'],
])('downloads file-backed raw content as %s', async (filename, fileKey) => {
mockFileKey = fileKey;
const artifact = fileToArtifact({ file_id: 'file', filename, text: 'Raw content' });
@ -404,6 +408,76 @@ describe('DownloadArtifact', () => {
expect(container.querySelector('[data-icon="download"]')).not.toBeNull();
});
it('reports a failed blob export instead of looking like it worked', async () => {
/* The mermaid export menu only speaks in its live region for a reported
* failure, on the rule that whichever layer returned `false` already
* told the user. This is that layer for the blob path. */
createObjectURL.mockImplementation(() => {
throw new Error('no object url');
});
const { container } = render(<DownloadArtifact artifact={htmlArtifact} />);
await act(async () => {
fireEvent.click(screen.getByRole('button'));
});
/* The hook localizes through `~/hooks/useLocalize` directly, outside
* this file's `~/hooks` mock, so the real string lands here. */
expect(mockShowToast).toHaveBeenCalledWith({
status: 'error',
message: 'Error downloading file. The file may have been deleted.',
});
expect(container.querySelector('[data-icon="circle-check-big"]')).toBeNull();
});
it('downloads an unedited mermaid diagram from its stored file, not the cached text', async () => {
/* `attachment.text` is the backend's cached extraction, and
* `extractUtf8` keeps only the first 512 KB of it, so a large stored
* `.mmd` would be saved truncated if the panel serialized `content`
* instead of fetching the file. */
mockFileKey = 'diagram.mmd';
const artifact = fileToArtifact({
file_id: 'file',
filename: 'flow.mmd',
text: 'graph TD\nA-->B\n\n…[truncated]',
filepath: '/api/files/code/output/session/flow.mmd',
source: FileSources.execute_code,
user: 'user-1',
});
expect(artifact?.type).toBe(TOOL_ARTIFACT_TYPES.MERMAID);
const { container } = render(<DownloadArtifact artifact={artifact!} />);
await act(async () => {
fireEvent.click(screen.getByRole('button'));
});
expect(mockFileDownload).toHaveBeenCalledTimes(1);
expect(mockAttachmentOptions).toHaveBeenCalledWith(
expect.objectContaining({ filename: 'flow.mmd' }),
);
expect(createObjectURL).not.toHaveBeenCalled();
expect(container.querySelector('[data-icon="circle-check-big"]')).not.toBeNull();
});
it('serializes an edited mermaid diagram from the panel content', async () => {
/* Edits live only in the editor, so the stored file is the wrong bytes.
* The blob is named as a preview of that file: the panel's copy is the
* cached extraction, which the backend truncates past 512 KB. */
mockFileKey = 'diagram.mmd';
mockCurrentCode = 'graph TD\nA-->C';
const artifact = fileToArtifact({
file_id: 'file',
filename: 'flow.mmd',
text: 'graph TD\nA-->B',
filepath: '/api/files/code/output/session/flow.mmd',
source: FileSources.execute_code,
user: 'user-1',
});
render(<DownloadArtifact artifact={artifact!} />);
await act(async () => {
fireEvent.click(screen.getByRole('button'));
});
expect(mockFileDownload).not.toHaveBeenCalled();
expect(createObjectURL).toHaveBeenCalledTimes(1);
expect(anchorClick.mock.instances[0].download).toBe('flow.preview.mmd');
});
it('serializes content as a blob for a non-file-backed (LLM-authored) artifact', async () => {
render(<DownloadArtifact artifact={htmlArtifact} />);
await act(async () => {

View file

@ -0,0 +1,140 @@
import { forwardRef } from 'react';
import { Button } from '@librechat/client';
import {
AppWindow,
Download,
FileCode2,
FileSpreadsheet,
FileText,
Presentation,
Workflow,
} from 'lucide-react';
import type { ArtifactGlyph, ArtifactRowKind } from '~/utils/artifacts';
import LangIcon, { hasLangIcon } from '~/components/Messages/Content/LangIcon';
import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from '../rows';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
const FALLBACK_GLYPHS: Record<ArtifactGlyph, React.ComponentType<{ className?: string }>> = {
preview: AppWindow,
code: FileCode2,
text: FileText,
diagram: Workflow,
document: FileText,
spreadsheet: FileSpreadsheet,
presentation: Presentation,
};
interface ArtifactRowProps {
/** Filename for file-backed artifacts, authored title for markdown ones. */
title: string;
kind: ArtifactRowKind;
/** This artifact is the one the panel is currently showing. */
isSelected: boolean;
onOpen: () => void;
/**
* Omitted when no real file backs the artifact (model-authored
* content). Takes the event because `useAttachmentLink`'s handler
* needs it to suppress the anchor default.
*/
onDownload?: (event: React.MouseEvent<HTMLButtonElement>) => void;
/** Stable trigger id, for the panel's focus handoff and for e2e. */
artifactId?: string;
}
/**
* The single chat-side trigger for every artifact: code-execution output,
* a model-authored `:::artifact` block, and a mermaid diagram all render
* through here.
*
* It is a tool row, not a card. Artifacts arrive interleaved with the
* rows that produced them, and the previous three-card-variant chip
* layout broke that column: a wrapped strip of fixed-width chips at a
* fourth indentation, so a message that wrote five files read as five
* unrelated buttons rather than five steps. `TOOL_ROW_CLASSES` plus
* `ROW_GLYPH_SLOT` put the glyph on the message header's avatar axis and
* the title where every other row's text starts.
*
* The file type is carried twice, because neither signal alone is enough:
* the glyph is the language's own brand mark where one exists (an `.html`
* artifact is not a `.py` artifact), and the format badge names the
* format for titles that aren't filenames. `kind.rendersPreview` tints
* the glyph with the `status-info` accent the mermaid trigger already
* used — the row says whether opening this yields something to look at
* or source to read, which is what the panel does differently.
*/
const ArtifactRow = forwardRef<HTMLButtonElement, ArtifactRowProps>(function ArtifactRow(
{ title, kind, isSelected, onOpen, onDownload, artifactId },
ref,
) {
const localize = useLocalize();
const actionLabel = isSelected
? localize('com_ui_click_to_close')
: localize('com_ui_artifact_click');
const label = 'key' in kind.label ? localize(kind.label.key) : kind.label.text;
const Fallback = FALLBACK_GLYPHS[kind.fallbackGlyph];
let glyph = <Fallback className="size-4 shrink-0" />;
if (kind.lang !== '' && hasLangIcon(kind.lang)) {
glyph = <LangIcon lang={kind.lang} className="size-4 shrink-0" />;
}
return (
<div className={cn(TOOL_ROW_CLASSES, 'text-sm text-text-secondary')}>
<Button
ref={ref}
type="button"
variant="ghost"
aria-controls="artifact-viewer"
aria-expanded={isSelected}
data-artifact-trigger={artifactId}
onClick={onOpen}
className={cn(
'inline-flex h-auto min-w-0 flex-1 items-center justify-start gap-2.5 rounded-none p-0',
'hover:bg-transparent hover:text-text-primary focus-visible:ring-text-primary focus-visible:ring-offset-0',
isSelected && 'text-text-primary',
)}
>
<span
className={cn(ROW_GLYPH_SLOT, kind.rendersPreview && 'text-status-info')}
aria-hidden="true"
>
{glyph}
</span>
<span className="min-w-0 truncate font-medium" title={title}>
{title}
</span>
{/* No vertical padding: `TOOL_ROW_CLASSES` fixes the row at 20px so
the streaming cursor and a call header can trade places without
moving what is under them, and a taller child here would push
past that box. */}
<span className="shrink-0 rounded px-1.5 text-[10px] font-medium uppercase leading-5 tracking-wide text-text-tertiary ring-1 ring-inset ring-border-light">
{label}
</span>
{/* The glyph's tint is the visual half of the preview/source split
and reaches nobody using a screen reader, so the same fact is
folded into the button's accessible name. */}
<span className="sr-only">
{`${
kind.rendersPreview
? localize('com_ui_artifact_renders')
: localize('com_ui_artifact_source')
} ${actionLabel}`}
</span>
</Button>
{onDownload != null && (
<Button
type="button"
variant="ghost"
size="icon"
onClick={onDownload}
aria-label={`${localize('com_ui_download')} ${title}`}
className="size-5 shrink-0 rounded text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-text-primary focus-visible:ring-offset-0"
>
<Download className="size-4" aria-hidden="true" />
</Button>
)}
</div>
);
});
export default ArtifactRow;

View file

@ -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 (
<div className="group relative my-2 inline-flex max-w-fit items-stretch gap-px overflow-hidden rounded-xl text-sm text-text-primary shadow-sm">
<div
aria-disabled="true"
<div className={cn(TOOL_ROW_CLASSES, 'text-sm text-text-secondary')}>
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
{status === 'pending' ? (
<Loader2 className="size-4 shrink-0 animate-spin" />
) : (
<AlertCircle className="size-4 shrink-0" />
)}
</span>
<span
className="min-w-0 truncate font-medium"
title={status === 'failed' ? (previewError ?? subtitleText) : visibleFilename}
aria-busy={status === 'pending'}
className="relative overflow-hidden rounded-l-xl border-border-light bg-surface-tertiary"
title={status === 'failed' ? (previewError ?? subtitleText) : undefined}
>
<div className="w-fit p-2">
<div className="flex flex-row items-center gap-2">
{/* 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. */}
<FilePreview fileType={fileType} className="relative" />
<div className="overflow-hidden text-left">
<div className="truncate font-medium" title={visibleFilename}>
{visibleFilename}
</div>
<div className="flex items-center gap-1.5 truncate text-xs text-text-secondary">
{status === 'pending' ? (
<Loader2 className="h-3 w-3 shrink-0 animate-spin" aria-hidden="true" />
) : (
<AlertCircle className="h-3 w-3 shrink-0" aria-hidden="true" />
)}
<span className="truncate">{subtitleText}</span>
</div>
</div>
</div>
</div>
</div>
<button
{visibleFilename}
</span>
<span className="min-w-0 shrink-[100] truncate text-xs font-normal">{subtitleText}</span>
<Button
type="button"
variant="ghost"
size="icon"
onClick={handleDownload}
aria-label={`${localize('com_ui_download')} ${visibleFilename}`}
title={localize('com_ui_download')}
className={cn(
'flex shrink-0 items-center justify-center px-3 transition-colors duration-200',
'rounded-r-xl bg-surface-tertiary text-text-secondary hover:bg-surface-hover hover:text-text-primary',
'border-l border-border-light focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
)}
className="size-5 shrink-0 rounded text-text-secondary hover:bg-surface-hover hover:text-text-primary focus-visible:ring-text-primary focus-visible:ring-offset-0"
>
<Download className="size-4" aria-hidden="true" />
</button>
</Button>
</div>
);
},
);
PreviewPlaceholderCard.displayName = 'PreviewPlaceholderCard';
PreviewPlaceholderRow.displayName = 'PreviewPlaceholderRow';
const FileAttachment = memo(({ attachment }: { attachment: Partial<TAttachment> }) => {
const [isVisible, setIsVisible] = useState(false);
@ -164,7 +141,7 @@ const FileAttachment = memo(({ attachment }: { attachment: Partial<TAttachment>
WebkitFontSmoothing: 'subpixel-antialiased',
}}
>
<PreviewPlaceholderCard
<PreviewPlaceholderRow
attachment={attachment}
status={previewStatus}
previewError={previewError}
@ -538,7 +515,7 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] }
const textAttachments: TAttachment[] = [];
/* Pending-preview chips share this row with their future selves —
* `type` is null while pending so the renderer falls back to
* FileAttachment (PreviewPlaceholderCard); on resolution it switches
* FileAttachment (PreviewPlaceholderRow); on resolution it switches
* to PanelArtifact in place. */
const panelRow: Array<{ attachment: TAttachment; type: ToolArtifactType | null }> = [];
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 && (
<FileAttachmentGroup attachments={groupedFileAttachments} />
)}
{(resolvedPanel.length > 0 || pendingPanel.length > 0) && (
<div className="my-2 flex flex-wrap items-center gap-2">
{resolvedPanel.map(({ attachment, type }, index) => (
<PanelArtifact
attachment={attachment}
type={type}
key={renderAttachmentKey('artifact', attachment, index)}
/>
))}
{pendingPanel.map(({ attachment }, index) =>
attachment.filepath ? (
{orderedPanel.length > 0 && (
<div className="my-2 flex w-full max-w-full flex-col" data-testid="artifact-row-group">
{orderedPanel.map(({ attachment, type }, index) => {
if (type != null) {
return (
<PanelArtifact
attachment={attachment}
type={type}
key={renderAttachmentKey('artifact', attachment, index)}
/>
);
}
if (!attachment.filepath) {
return null;
}
return (
<FileAttachment
attachment={attachment}
key={renderAttachmentKey('pending', attachment, index)}
/>
) : null,
)}
);
})}
</div>
)}
{mermaidArtifacts.length > 0 && (

View file

@ -181,7 +181,7 @@ const LogContent: React.FC<LogContentProps> = ({ output = '', renderImages, atta
</div>
)}
{panelAttachments.length > 0 && (
<div className="mt-2 flex flex-wrap items-center gap-2">
<div className="mt-2 flex w-full max-w-full flex-col">
{panelAttachments.map(({ attachment, artifact }, index) => (
<ToolArtifactCard
key={renderAttachmentKey('artifact', attachment, index)}

View file

@ -3,6 +3,7 @@ import { useToastContext } from '@librechat/client';
import { FileSources, sharedFileDownload } from 'librechat-data-provider';
import { getDownloadFilename, isHttpDownloadTarget, triggerDownload } from '~/utils';
import { useCodeOutputDownload, useFileDownload } from '~/data-provider';
import useLocalize from '~/hooks/useLocalize';
import { useShareContext } from '~/Providers';
interface LogLinkProps {
@ -48,6 +49,7 @@ export const useAttachmentLink = ({
user,
source,
}: AttachmentLinkOptions) => {
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<HTMLAnchorElement | HTMLButtonElement>,
): Promise<boolean> => {
const handleDownload = async (event: React.MouseEvent<HTMLElement>): Promise<boolean> => {
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;
}
};

View file

@ -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 (
<div className="group relative my-2 inline-flex max-w-fit items-stretch gap-px overflow-hidden rounded-xl text-sm text-text-primary shadow-sm">
<button
type="button"
onClick={handleOpen}
aria-pressed={isSelected}
className={cn(
'relative overflow-hidden rounded-l-xl transition-all duration-200 hover:bg-surface-hover active:scale-[0.99]',
{
'border-border-medium bg-surface-hover': isSelected,
'border-border-light bg-surface-tertiary': !isSelected,
},
)}
>
<div className="w-fit p-2">
<div className="flex flex-row items-center gap-2">
<FilePreview fileType={fileType} className="relative" />
<div className="overflow-hidden text-left">
<div className="truncate font-medium" title={visibleFilename}>
{visibleTitle}
</div>
<div className="truncate text-xs text-text-secondary">{actionLabel}</div>
</div>
</div>
</div>
</button>
<button
type="button"
onClick={handleDownload}
aria-label={`${localize('com_ui_download')} ${visibleFilename}`}
title={localize('com_ui_download')}
className={cn(
'flex shrink-0 items-center justify-center px-3 transition-colors duration-200',
'rounded-r-xl bg-surface-tertiary text-text-secondary hover:bg-surface-hover hover:text-text-primary',
'border-l border-border-light focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',
)}
>
<Download className="size-4" aria-hidden="true" />
</button>
</div>
<ArtifactRow
title={visibleTitle}
kind={artifactRowKind(artifact)}
isSelected={isSelected}
onOpen={handleOpen}
onDownload={handleDownload}
artifactId={artifact.id}
/>
);
});

View file

@ -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 (
<div className="my-2 flex w-full flex-col gap-1">
{(attachment.filename || attachment.filepath) && (
{!isRowMode && (attachment.filename || attachment.filepath) && (
<div className="flex items-center justify-between gap-2">
{attachment.filename && (
<div
@ -89,11 +93,24 @@ const ToolMermaidArtifact = memo(({ attachment, text }: ToolMermaidArtifactProps
{/* `id` is optional on Mermaid; pass only when we have a real file_id
so the component generates a unique render target on its own. */}
{file.file_id ? (
<Mermaid id={file.file_id} artifact={artifact ?? undefined}>
<Mermaid
id={file.file_id}
artifact={artifact ?? undefined}
onDownload={attachment.filepath ? handleDownload : undefined}
onRowModeChange={setIsRowMode}
rowTitle={attachment.filename ? visibleFilename : undefined}
>
{text}
</Mermaid>
) : (
<Mermaid artifact={artifact ?? undefined}>{text}</Mermaid>
<Mermaid
artifact={artifact ?? undefined}
onDownload={attachment.filepath ? handleDownload : undefined}
onRowModeChange={setIsRowMode}
rowTitle={attachment.filename ? visibleFilename : undefined}
>
{text}
</Mermaid>
)}
</div>
);

View file

@ -147,11 +147,12 @@ describe('Attachment routing for tool artifacts', () => {
} as Partial<TAttachment>);
renderWith(<Attachment attachment={html} />);
// 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<TAttachment>);
renderWith(<Attachment attachment={att} />);
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(<Attachment attachment={html()} />);
// 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(<Attachment attachment={html()} />);
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: '<h1>v1</h1>',
} as Partial<TAttachment>);
const { container } = renderWith(<AttachmentGroup attachments={[dup, dup]} />);
// Dedup atom keeps just one card visible.
expect(container.querySelectorAll('div[title="index.html"]')).toHaveLength(1);
// 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', () => {
<AttachmentGroup attachments={[dup]} />
</>,
);
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(<AttachmentGroup attachments={attachments} />);
/* 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<TAttachment>),
baseAttachment({
file_id: 'resolved',
filename: 'index.html',
text: '<h1>hi</h1>',
} as Partial<TAttachment>),
] as TAttachment[];
renderWith(<AttachmentGroup attachments={attachments} />);
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<TAttachment>);
const loading = baseAttachment({
file_id: 'pending-2',
filename: 'report.xlsx',
bytes: 4096,
status: 'pending',
} as Partial<TAttachment>);
const resolved = baseAttachment({
file_id: 'pending-2',
filename: 'report.xlsx',
bytes: 4096,
text: '<table></table>',
textFormat: 'html',
} as Partial<TAttachment>);
const order = (attachments: TAttachment[]) => {
const { unmount } = renderWith(<AttachmentGroup attachments={attachments} />);
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', () => {

View file

@ -86,8 +86,8 @@ describe('LogContent attachment routing', () => {
text: '<h1>hi</h1>',
} as Partial<TAttachment>);
renderWith(<LogContent output="" attachments={[html]} />);
// The panel card carries an aria-pressed state; auto-focused on mount.
expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument();
// 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(<LogContent output="" attachments={[mmd]} />);
expect(screen.getByTestId('mermaid-render')).toHaveTextContent('graph TD');
// Panel card not rendered for mermaid
expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { expanded: true })).not.toBeInTheDocument();
});
it('routes text-bearing JSON through inline <pre>, not the panel', () => {
@ -114,7 +114,7 @@ describe('LogContent attachment routing', () => {
});
const { container } = renderWith(<LogContent output="" attachments={[json]} />);
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(<LogContent output="" attachments={[pptx]} />);
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(<LogContent output="" attachments={[expired]} />);
// No panel card and no log-link (the expired branch returns plain text).
expect(screen.queryByRole('button', { pressed: true })).not.toBeInTheDocument();
expect(screen.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<TAttachment>);
renderWith(<LogContent output="" attachments={[fresh]} />);
expect(screen.getByRole('button', { pressed: true })).toBeInTheDocument();
expect(screen.getByRole('button', { expanded: true })).toBeInTheDocument();
});
it('splits a mixed list into the right buckets', () => {

View file

@ -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(
<LogLink
user="user-1"
file_id="file-1"
filename={filename}
source={FileSources.cloudfront}
href="https://cdn.example.com/uploads/file.pdf"
>
{filename}
</LogLink>,
);
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' });

View file

@ -77,6 +77,20 @@ const NAME_MAP: Record<string, string> = {
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') {

View file

@ -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(
'<svg viewBox="0 0 400 200" />',
'flow.mmd',
'rgb(23 23 23)',
await waitFor(() =>
expect(mockDownloadMermaidSvg).toHaveBeenCalledWith(
'<svg viewBox="0 0 400 200" />',
'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(
'<svg viewBox="0 0 400 200" />',
'flow.mmd',
{ width: 400, height: 200 },
'rgb(23 23 23)',
await waitFor(() =>
expect(mockDownloadMermaidPng).toHaveBeenCalledWith(
'<svg viewBox="0 0 400 200" />',
'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(
'<svg viewBox="0 0 400 200" />',
'flow.mmd',
'rgb(23 23 23)',
await waitFor(() =>
expect(mockDownloadMermaidSvg).toHaveBeenCalledWith(
'<svg viewBox="0 0 400 200" />',
'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<FrameRequestCallback> = [];
const rafSpy = jest
.spyOn(window, 'requestAnimationFrame')
.mockImplementation((callback: FrameRequestCallback) => {
frames.push(callback);
return frames.length;
});
try {
render(<MermaidExport svg={'<svg viewBox="0 0 400 200" />'} 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(<MermaidExport filename="flow.mmd" onDownloadSource={onDownloadSource} />);
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(<MermaidExport filename="flow.mmd" onDownloadSource={onDownloadSource} />);
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(<MermaidExport filename="flow.mmd" onDownloadSource={onDownloadSource} />);
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');
});
});

View file

@ -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<HTMLElement>,
) => boolean | void | Promise<boolean | void>;
}
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<ExportFormat, 'source'>;
labelKey: TranslationKeys;
Icon: LucideIcon;
}>;
const EXPORTING_KEYS: Record<ExportFormat, TranslationKeys> = {
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<HTMLButtonElement>(null);
const [isOpen, setIsOpen] = useState(false);
const [isExportingPng, setIsExportingPng] = useState(false);
const [exporting, setExporting] = useState<ExportFormat | null>(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<boolean | void>) => {
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<HTMLButtonElement | HTMLDivElement>) => {
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<MenuItemProps[]>(() => {
const statusItems: MenuItemProps[] = [];
if (isBusy) {
statusItems.push({
label: liveMessage,
disabled: true,
icon: <LoaderCircle className="size-4 animate-spin motion-reduce:animate-none" />,
className: 'text-text-secondary',
const loadingRow = (format: ExportFormat) => ({
label: localize('com_ui_loading'),
ariaLabel: localize(EXPORTING_KEYS[format]),
icon: <LoaderCircle className="size-4 animate-spin motion-reduce:animate-none" />,
className: 'text-text-secondary',
});
const items: MenuItemProps[] = EXPORT_FORMATS.map(({ format, labelKey, Icon }) => ({
label: localize(labelKey),
icon: <Icon className="size-4 text-text-secondary" />,
...(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: <Workflow className="size-4 text-text-secondary" />,
...(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: <FileCode2 className="size-4 text-text-secondary" />,
disabled: svg == null || isExportingPng,
onClick: handleSvgExport,
},
{
label: localize('com_ui_export_png'),
icon: <FileImage className="size-4 text-text-secondary" />,
disabled: svg == null || isExportingPng,
onClick: handlePngExport,
},
];
}, [handlePngExport, handleSvgExport, isBusy, isExportingPng, liveMessage, localize, svg]);
return items;
}, [
exporting,
handlePngExport,
handleSourceExport,
handleSvgExport,
isBusy,
localize,
onDownloadSource,
svg,
]);
return (
<>

View file

@ -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(
<RecoilRoot>
<MemoryRouter initialEntries={['/c/conversation-1']}>
<MessageContext.Provider
value={{ messageId: 'message-1', conversationId: 'conversation-1', isExpanded: true }}
>
<Mermaid
id="flow-file"
artifact={
{
id: 'tool-artifact-flow',
type: 'application/vnd.mermaid',
title: 'flow.mmd',
content: 'graph TD\nA-->B',
lastUpdateTime: 1,
} as Artifact
}
onDownload={onDownload}
onRowModeChange={(isRow) => rowModes.push(isRow)}
>
{'graph TD\nA-->B'}
</Mermaid>
</MessageContext.Provider>
</MemoryRouter>
</RecoilRoot>,
);
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(
<RecoilRoot>
<MemoryRouter initialEntries={['/c/conversation-1']}>
<MessageContext.Provider
value={{ messageId: 'message-1', conversationId: 'conversation-1', isExpanded: true }}
>
<Mermaid
id="flow-hidden"
artifact={
{
id: 'tool-artifact-hidden',
type: 'application/vnd.mermaid',
title: '_.flow-abcdef.mmd',
content: 'graph TD\nA-->B',
lastUpdateTime: 1,
} as Artifact
}
rowTitle=".flow.mmd"
onDownload={jest.fn()}
>
{'graph TD\nA-->B'}
</Mermaid>
</MessageContext.Provider>
</MemoryRouter>
</RecoilRoot>,
);
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,

View file

@ -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<HTMLButtonElement>) => 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<MermaidProps, 'artifact'> {
interface MermaidRendererProps
extends Omit<MermaidProps, 'artifact' | 'onDownload' | 'onRowModeChange' | 'rowTitle'> {
fillContainer?: boolean;
onExpand?: () => void;
onExportReady?: (data: ProcessedMermaidSvg | null) => void;
@ -33,7 +52,16 @@ interface MermaidRendererProps extends Omit<MermaidProps, 'artifact'> {
showHeader?: boolean;
}
const Mermaid: React.FC<MermaidProps> = memo(({ children, id, theme, artifact: artifactProp }) => {
const Mermaid: React.FC<MermaidProps> = 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<MermaidProps> = 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 (
<MermaidArtifactCard
<ArtifactRow
ref={artifactButtonRef}
artifactId={artifact.id}
title={artifact.title ?? defaultTitle}
title={rowTitle ?? artifact.title ?? defaultTitle}
kind={artifactRowKind(artifact)}
isSelected={isSelected}
onClick={handleArtifactClick}
onOpen={handleArtifactClick}
onDownload={onDownload}
/>
);
}

View file

@ -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<HTMLButtonElement, MermaidArtifactCardProps>(
({ artifactId, isSelected, title, onClick }, ref) => {
const localize = useLocalize();
const actionLabel = isSelected
? localize('com_ui_close_artifact')
: localize('com_ui_open_artifact');
return (
<Button
ref={ref}
variant="subtle"
aria-controls="artifact-viewer"
aria-expanded={isSelected}
data-artifact-trigger={artifactId}
onClick={onClick}
className={cn(
'group my-2 h-auto w-fit max-w-full justify-start gap-2 overflow-hidden whitespace-normal rounded-xl p-2 text-left text-sm shadow-sm',
'border-border-light bg-surface-tertiary transition-all duration-200 hover:bg-surface-hover active:scale-[0.99] motion-reduce:transition-none',
isSelected && 'border-border-medium bg-surface-hover',
)}
>
<span className="flex size-8 shrink-0 items-center justify-center rounded-lg bg-status-info-subtle text-status-info">
<Workflow className="size-4" aria-hidden="true" />
</span>
<span className="min-w-0 max-w-64 flex-1 overflow-hidden">
<span className="block truncate font-medium text-text-primary">{title}</span>
<span className="block truncate text-xs font-normal text-text-secondary">
{actionLabel}
</span>
</span>
</Button>
);
},
);
MermaidArtifactCard.displayName = 'MermaidArtifactCard';
export default MermaidArtifactCard;

View file

@ -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<HTMLElement>) => Promise<boolean>;
}
/**
* 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<ReturnType<typeof setTimeout>>();
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<HTMLElement>): Promise<boolean> => {
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 };
}

View file

@ -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",

View file

@ -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 });
});
});

View file

@ -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<string, string> = {
'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<string, ArtifactRowKind> = {
[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

View file

@ -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();

View file

@ -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"}',
'<main><h1>Dashboard</h1></main>',
':::',
'',
':::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]);
}
},
);
});

View file

@ -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<Buffer> {
const stream = await download.createReadStream();
const chunks: Buffer[] = [];
for await (const chunk of stream as AsyncIterable<Uint8Array>) {
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');
},
);
});

View file

@ -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<Uint8Array>) {
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');
},
);
});

View file

@ -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: '<h1>hi</h1>',
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: '<table><tr><td>ready</td></tr></table>',
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);
});
});

View file

@ -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]);
}
},
);
});