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