mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-20 15:02:02 +00:00
🔠 fix: Name Artifact Downloads After Their Titles (#15836)
* fix: Use artifact titles for download filenames * fix: Match artifact filenames to downloaded content * fix: Preserve raw artifact extensions and GFM headings * fix: Download complete artifact files and retain filename provenance * fix: Distinguish cached artifact exports from originals * fix: Name unnamed artifact originals by their media type * fix: Recognize legacy CSV MIME in artifact filenames
This commit is contained in:
parent
980f3ede77
commit
ab506011e5
7 changed files with 571 additions and 17 deletions
|
|
@ -14,6 +14,9 @@ export const MERMAID_ARTIFACT_TYPE = 'application/vnd.mermaid' as const;
|
|||
* the rendered preview `content`.
|
||||
*/
|
||||
export interface ArtifactDownload {
|
||||
/** Original attachment name; null means the attachment supplied no filename. */
|
||||
filename?: string | null;
|
||||
mimeType?: string;
|
||||
filepath?: string;
|
||||
file_id?: string;
|
||||
source?: string;
|
||||
|
|
|
|||
|
|
@ -2,12 +2,16 @@ 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 { isPreviewOnlyArtifact } from '~/utils/artifacts';
|
||||
import { useCodeState } from '~/Providers/EditorContext';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
|
|
@ -17,12 +21,8 @@ const DownloadArtifact = ({ artifact }: { artifact: Artifact }) => {
|
|||
const [isDownloaded, setIsDownloaded] = useState(false);
|
||||
const { fileKey: fileName } = useArtifactProps({ artifact });
|
||||
|
||||
/* Office artifacts (pptx/xlsx/docx) render a server-generated HTML
|
||||
* preview in `content`, not the binary file — serializing that blob
|
||||
* would download the preview instead of the original. Fetch the real
|
||||
* file through the same path the inline card uses. Source-code and
|
||||
* text artifacts keep the blob path: their `content` IS the file (and
|
||||
* reflects any in-panel edits). */
|
||||
/* 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
|
||||
|
|
@ -37,10 +37,12 @@ const DownloadArtifact = ({ artifact }: { artifact: Artifact }) => {
|
|||
(download?.file_id != null &&
|
||||
download?.user != null &&
|
||||
isLocallyStoredSource(download?.source));
|
||||
const downloadOriginalFile = isPreviewOnlyArtifact(artifact.type) && hasUsableRoute;
|
||||
const hasEdits = currentCode != null && currentCode !== artifact.content;
|
||||
const downloadOriginalFile =
|
||||
hasUsableRoute && (isPreviewOnlyArtifact(artifact.type) || !hasEdits);
|
||||
const { handleDownload: downloadAttachment } = useAttachmentLink({
|
||||
href: download?.filepath ?? '',
|
||||
filename: artifact.title ?? fileName,
|
||||
filename: getOriginalArtifactFilename(artifact, fileName),
|
||||
file_id: download?.file_id,
|
||||
user: download?.user,
|
||||
source: download?.source,
|
||||
|
|
@ -52,15 +54,15 @@ const DownloadArtifact = ({ artifact }: { artifact: Artifact }) => {
|
|||
};
|
||||
|
||||
const downloadContent = () => {
|
||||
const content = currentCode ?? artifact.content ?? '';
|
||||
if (!content) {
|
||||
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 = fileName;
|
||||
link.download = getArtifactDownloadFilename(artifact, fileName, content);
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import React from 'react';
|
||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
||||
import type { Artifact } from '~/common';
|
||||
import { TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
|
||||
import { fileToArtifact, TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
|
||||
import DownloadArtifact from '../DownloadArtifact';
|
||||
|
||||
const mockFileDownload = jest.fn();
|
||||
const mockAttachmentOptions = jest.fn();
|
||||
let mockFileKey = 'index.html';
|
||||
let mockCurrentCode: string | undefined;
|
||||
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize:
|
||||
|
|
@ -15,11 +18,11 @@ jest.mock('~/hooks', () => ({
|
|||
|
||||
jest.mock('~/hooks/Artifacts/useArtifactProps', () => ({
|
||||
__esModule: true,
|
||||
default: () => ({ fileKey: 'index.html', files: {}, template: 'static', sharedProps: {} }),
|
||||
default: () => ({ fileKey: mockFileKey, files: {}, template: 'static', sharedProps: {} }),
|
||||
}));
|
||||
|
||||
jest.mock('~/Providers/EditorContext', () => ({
|
||||
useCodeState: () => ({ currentCode: undefined }),
|
||||
useCodeState: () => ({ currentCode: mockCurrentCode }),
|
||||
}));
|
||||
|
||||
/* MorphIcon renders a single morphing <svg> with no per-icon class, so map
|
||||
|
|
@ -37,7 +40,10 @@ jest.mock('@librechat/client', () => {
|
|||
});
|
||||
|
||||
jest.mock('~/components/Chat/Messages/Content/Parts/LogLink', () => ({
|
||||
useAttachmentLink: () => ({ handleDownload: mockFileDownload }),
|
||||
useAttachmentLink: (options: { filename: string }) => {
|
||||
mockAttachmentOptions(options);
|
||||
return { handleDownload: mockFileDownload };
|
||||
},
|
||||
isLocallyStoredSource: (source?: string) =>
|
||||
['local', 'firebase', 's3', 'cloudfront', 'azure_blob'].includes(source ?? ''),
|
||||
}));
|
||||
|
|
@ -101,6 +107,8 @@ describe('DownloadArtifact', () => {
|
|||
let anchorClick: jest.SpyInstance;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFileKey = 'index.html';
|
||||
mockCurrentCode = undefined;
|
||||
mockFileDownload.mockReset();
|
||||
// The attachment helper resolves to `true` when a file was delivered.
|
||||
mockFileDownload.mockResolvedValue(true);
|
||||
|
|
@ -123,6 +131,254 @@ describe('DownloadArtifact', () => {
|
|||
anchorClick.mockRestore();
|
||||
});
|
||||
|
||||
it.each([
|
||||
['text/markdown', 'Migration Plan', 'content.md', undefined, 'Migration Plan.md'],
|
||||
['text/md', 'Second Report', 'content.md', undefined, 'Second Report.md'],
|
||||
['text/markdown', 'Report.MD', 'content.md', undefined, 'Report.MD'],
|
||||
['text/plain', 'Meeting Notes', 'content.md', undefined, 'Meeting Notes.txt'],
|
||||
['text/plain', 'notes.odt', 'content.md', undefined, 'notes.odt.txt'],
|
||||
['text/plain', 'report.docx', 'content.md', undefined, 'report.docx.txt'],
|
||||
['text/plain', 'notes.TXT', 'content.md', undefined, 'notes.TXT'],
|
||||
['text/markdown', 'Release Notes v1.0', 'content.md', undefined, 'Release Notes v1.0.md'],
|
||||
['text/html', 'example.com', 'index.html', undefined, 'example.com.html'],
|
||||
[TOOL_ARTIFACT_TYPES.CODE, 'script.py', 'content.md', 'python', 'script.py'],
|
||||
[TOOL_ARTIFACT_TYPES.CODE, 'script.py', 'content.md', undefined, 'script.py'],
|
||||
[TOOL_ARTIFACT_TYPES.CODE, 'example.com', 'content.md', 'python', 'example.com.py'],
|
||||
[TOOL_ARTIFACT_TYPES.CODE, 'Analysis', 'content.md', 'python', 'Analysis.py'],
|
||||
[TOOL_ARTIFACT_TYPES.CODE, '', 'content.md', 'typescript', 'code.ts'],
|
||||
['text/html', 'Landing Page', 'index.html', undefined, 'Landing Page.html'],
|
||||
['application/vnd.react', 'Dashboard', 'App.tsx', undefined, 'Dashboard.tsx'],
|
||||
['application/vnd.mermaid', 'Flow', 'diagram.mmd', undefined, 'Flow.mmd'],
|
||||
['text/markdown', ' ', 'content.md', undefined, 'content.md'],
|
||||
['text/plain', undefined, 'content.md', undefined, 'content.txt'],
|
||||
['text/markdown', 'Plan: Q3/Q4', 'content.md', undefined, 'Plan_ Q3_Q4.md'],
|
||||
[TOOL_ARTIFACT_TYPES.PRESENTATION, 'deck.pptx', 'index.html', undefined, 'deck.pptx.html'],
|
||||
])('names %s download with title %s', async (type, title, fileKey, language, expected) => {
|
||||
mockFileKey = fileKey;
|
||||
mockCurrentCode = 'edited content';
|
||||
render(<DownloadArtifact artifact={{ ...htmlArtifact, type, title, language }} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(anchorClick.mock.instances[0].download).toBe(expected);
|
||||
const blob = createObjectURL.mock.calls[0][0] as Blob;
|
||||
const content = await new Promise<string>((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result));
|
||||
reader.readAsText(blob);
|
||||
});
|
||||
expect(content).toBe('edited content');
|
||||
expect(mockFileDownload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([undefined, 'untitled', 'Generated artifact'])(
|
||||
'names untitled Markdown from the edited heading (%s)',
|
||||
async (title) => {
|
||||
mockFileKey = 'content.md';
|
||||
mockCurrentCode = '# New **migration** [plan](https://example.com) for `migrate_users.py`';
|
||||
render(
|
||||
<DownloadArtifact
|
||||
artifact={{ ...htmlArtifact, type: 'text/markdown', title, content: '# Old heading' }}
|
||||
/>,
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(anchorClick.mock.instances[0].download).toBe(
|
||||
'New migration plan for migrate_users.py.md',
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['Component.jsx', 'App.tsx'],
|
||||
['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' });
|
||||
expect(artifact).not.toBeNull();
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
const dot = filename.lastIndexOf('.');
|
||||
expect(anchorClick.mock.instances[0].download).toBe(
|
||||
`${filename.slice(0, dot)}.preview${filename.slice(dot)}`,
|
||||
);
|
||||
expect(mockFileDownload).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['untitled', 'Generated artifact', 'Component.jsx', 'notes.txt'])(
|
||||
'keeps the exact original filename when fetching %s',
|
||||
async (filename) => {
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename,
|
||||
type: 'text/markdown',
|
||||
text: 'Complete file\n\n…[truncated]',
|
||||
filepath: '/api/files/code/output/file',
|
||||
});
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).toHaveBeenCalledTimes(1);
|
||||
expect(createObjectURL).not.toHaveBeenCalled();
|
||||
expect(mockAttachmentOptions).toHaveBeenLastCalledWith(expect.objectContaining({ filename }));
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['text/markdown', 'content.md', 'content.md'],
|
||||
['text/x-python', 'content.md', 'code.py'],
|
||||
['text/html', 'index.html', 'content.html'],
|
||||
['application/vnd.react', 'App.tsx', 'App.tsx'],
|
||||
['application/vnd.oasis.opendocument.text', 'content.md', 'content.odt'],
|
||||
[
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'index.html',
|
||||
'content.docx',
|
||||
],
|
||||
['text/csv', 'index.html', 'content.csv'],
|
||||
['text/comma-separated-values', 'index.html', 'content.csv'],
|
||||
['text/comma-separated-values; charset=utf-8', 'index.html', 'content.csv'],
|
||||
['application/x-dos_ms_excel', 'index.html', 'content.xls'],
|
||||
])(
|
||||
'uses an original-format fallback when %s has no filename',
|
||||
async (type, fileKey, expected) => {
|
||||
mockFileKey = fileKey;
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
type,
|
||||
text: 'Preview',
|
||||
filepath: '/api/files/code/output/file',
|
||||
});
|
||||
expect(artifact?.download?.filename).toBeNull();
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).toHaveBeenCalledTimes(1);
|
||||
expect(createObjectURL).not.toHaveBeenCalled();
|
||||
expect(mockAttachmentOptions).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ filename: expected }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('uses a fallback for an empty attachment filename', async () => {
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename: '',
|
||||
type: 'text/markdown',
|
||||
text: '# Heading',
|
||||
filepath: '/api/files/code/output/file',
|
||||
});
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).toHaveBeenCalledTimes(1);
|
||||
expect(mockAttachmentOptions).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ filename: 'content.md' }),
|
||||
);
|
||||
});
|
||||
|
||||
it.each([undefined, 'Prefix\n\n…[truncated]'])(
|
||||
'fetches the complete original for unedited cached content (%s)',
|
||||
async (currentCode) => {
|
||||
mockCurrentCode = currentCode;
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename: 'large.py',
|
||||
text: 'Prefix\n\n…[truncated]',
|
||||
filepath: '/api/files/code/output/large.py',
|
||||
});
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).toHaveBeenCalledTimes(1);
|
||||
expect(createObjectURL).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['Edited prefix', ''])(
|
||||
'exports edits to a truncated preview with a distinct name (%s)',
|
||||
async (edit) => {
|
||||
mockCurrentCode = edit;
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename: 'large.py',
|
||||
text: 'Prefix\n\n…[truncated]',
|
||||
filepath: '/api/files/code/output/large.py',
|
||||
});
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).not.toHaveBeenCalled();
|
||||
expect(anchorClick.mock.instances[0].download).toBe('large.preview.py');
|
||||
const blob = createObjectURL.mock.calls[0][0] as Blob;
|
||||
expect(blob.size).toBe(edit.length);
|
||||
},
|
||||
);
|
||||
|
||||
it('names a truncated preview distinctly when the original route is unavailable', async () => {
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename: 'large.txt',
|
||||
text: 'Prefix\n\n…[truncated]',
|
||||
});
|
||||
render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).not.toHaveBeenCalled();
|
||||
expect(anchorClick.mock.instances[0].download).toBe('large.preview.txt');
|
||||
});
|
||||
|
||||
it('does not silently substitute a preview after an original download fails, and can retry', async () => {
|
||||
mockFileDownload.mockResolvedValueOnce(false);
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename: 'large.py',
|
||||
text: 'Prefix\n\n…[truncated]',
|
||||
filepath: '/api/files/code/output/large.py',
|
||||
});
|
||||
const { container } = render(<DownloadArtifact artifact={artifact!} />);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(createObjectURL).not.toHaveBeenCalled();
|
||||
expect(container.querySelector('[data-icon="circle-check-big"]')).toBeNull();
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(mockFileDownload).toHaveBeenCalledTimes(2);
|
||||
expect(container.querySelector('[data-icon="circle-check-big"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('preserves extensionless source filenames', async () => {
|
||||
render(
|
||||
<DownloadArtifact
|
||||
artifact={{
|
||||
...htmlArtifact,
|
||||
type: TOOL_ARTIFACT_TYPES.CODE,
|
||||
title: 'Dockerfile',
|
||||
download: { file_id: 'source' },
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
await act(async () => {
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
});
|
||||
expect(anchorClick.mock.instances[0].download).toBe('Dockerfile.preview');
|
||||
});
|
||||
|
||||
it('downloads the original file (not the preview) for an office artifact and shows success', async () => {
|
||||
const { container } = render(<DownloadArtifact artifact={officeArtifact} />);
|
||||
await act(async () => {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { FileSources } from 'librechat-data-provider';
|
|||
import type { ToolArtifactType } from '../artifacts';
|
||||
import {
|
||||
buildSandpackOptions,
|
||||
getArtifactDownloadFilename,
|
||||
detectArtifactTypeFromFile,
|
||||
fileToArtifact,
|
||||
isCodeOnlyArtifact,
|
||||
|
|
@ -715,6 +716,8 @@ describe('fileToArtifact', () => {
|
|||
expect(artifact).not.toBeNull();
|
||||
expect(artifact!.type).toBe(TOOL_ARTIFACT_TYPES.PRESENTATION);
|
||||
expect(artifact!.download).toEqual({
|
||||
filename: 'deck.pptx',
|
||||
mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
||||
filepath: '/api/files/code/output/deck.pptx',
|
||||
file_id: 'fid-1',
|
||||
source: FileSources.execute_code,
|
||||
|
|
@ -974,3 +977,149 @@ describe('isCodeOnlyArtifact', () => {
|
|||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('getArtifactDownloadFilename', () => {
|
||||
it.each([
|
||||
['# Migration Plan', 'Migration Plan.md'],
|
||||
['# ~~Deprecated~~ Plan', 'Deprecated Plan.md'],
|
||||
['# migrate_users.py', 'migrate_users.py.md'],
|
||||
['# The **Q3** [report](https://example.com)', 'The Q3 report.md'],
|
||||
['# Hello & goodbye', 'Hello & goodbye.md'],
|
||||
['```bash\n# comment\n```\n# Actual heading', 'Actual heading.md'],
|
||||
['````\n```bash\n# Still code\n```\n````\n# Actual heading', 'Actual heading.md'],
|
||||
['~~~\n```\n# Still code\n~~~\n# Actual heading', 'Actual heading.md'],
|
||||
['---\n# Metadata comment\n---\n# Actual heading', 'Actual heading.md'],
|
||||
['<div>\n# Hidden heading\n</div>\n\n# Actual heading', 'Actual heading.md'],
|
||||
['A real setext heading\n===', 'A real setext heading.md'],
|
||||
['No heading', 'content.md'],
|
||||
])('derives a Markdown filename from %s', (content, expected) => {
|
||||
expect(
|
||||
getArtifactDownloadFilename(
|
||||
{ id: 'a', lastUpdateTime: 0, type: 'text/markdown', content },
|
||||
'content.md',
|
||||
),
|
||||
).toBe(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['Component.jsx', 'App.tsx'],
|
||||
['Component.tsx', 'App.tsx'],
|
||||
['index.htm', 'index.html'],
|
||||
['index.html', 'index.html'],
|
||||
['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'],
|
||||
['notes.TXT', 'content.md'],
|
||||
])('preserves raw file extensions in preview exports: %s', (filename, fileKey) => {
|
||||
const artifact = fileToArtifact({ file_id: 'file', filename, text: 'Raw content' });
|
||||
expect(artifact).not.toBeNull();
|
||||
const dot = filename.lastIndexOf('.');
|
||||
const expected =
|
||||
dot > 0 ? `${filename.slice(0, dot)}.preview${filename.slice(dot)}` : `${filename}.preview`;
|
||||
expect(getArtifactDownloadFilename(artifact!, fileKey)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each(['untitled', 'Generated artifact'])(
|
||||
'preserves the real attachment filename %s',
|
||||
(filename) => {
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename,
|
||||
type: 'text/markdown',
|
||||
text: '# Heading',
|
||||
});
|
||||
expect(getArtifactDownloadFilename(artifact!, 'content.md')).toBe(`${filename}.preview`);
|
||||
},
|
||||
);
|
||||
|
||||
it('uses the heading when an attachment supplied no filename', () => {
|
||||
const artifact = fileToArtifact({ file_id: 'file', type: 'text/markdown', text: '# Heading' });
|
||||
expect(getArtifactDownloadFilename(artifact!, 'content.md')).toBe('Heading.preview.md');
|
||||
});
|
||||
|
||||
it('preserves sentinel filenames in older artifact metadata', () => {
|
||||
expect(
|
||||
getArtifactDownloadFilename(
|
||||
{
|
||||
id: 'a',
|
||||
lastUpdateTime: 0,
|
||||
type: 'text/markdown',
|
||||
title: 'untitled',
|
||||
content: '# Heading',
|
||||
download: { file_id: 'file' },
|
||||
},
|
||||
'content.md',
|
||||
),
|
||||
).toBe('untitled.preview');
|
||||
});
|
||||
|
||||
it.each(['script.py', 'notes.txt', 'README.md', 'Dockerfile'])(
|
||||
'distinguishes cached preview exports of %s',
|
||||
(filename) => {
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename,
|
||||
text: 'Prefix\n\n…[truncated]',
|
||||
});
|
||||
const expected = filename.includes('.')
|
||||
? filename.replace(/(\.[^.]+)$/, '.preview$1')
|
||||
: `${filename}.preview`;
|
||||
expect(getArtifactDownloadFilename(artifact!, 'content.md')).toBe(expected);
|
||||
expect(getArtifactDownloadFilename(artifact!, 'content.md', 'Edited prefix')).toBe(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(['odt', 'docx', 'pptx'])('names extracted %s bytes as text after file routing', (ext) => {
|
||||
const artifact = fileToArtifact({
|
||||
file_id: 'file',
|
||||
filename: `report.${ext}`,
|
||||
text: 'Extracted text',
|
||||
});
|
||||
expect(artifact?.type).toBe(TOOL_ARTIFACT_TYPES.PLAIN_TEXT);
|
||||
expect(getArtifactDownloadFilename(artifact!, 'content.md')).toBe(`report.${ext}.preview.txt`);
|
||||
});
|
||||
|
||||
it.each(['Complete file', 'Complete file\n\n…[truncated]'])(
|
||||
'does not infer truncation from cached file text: %s',
|
||||
(content) => {
|
||||
const artifact = fileToArtifact({ file_id: 'file', filename: 'notes.txt', text: content });
|
||||
expect(getArtifactDownloadFilename(artifact!, 'content.md')).toBe('notes.preview.txt');
|
||||
},
|
||||
);
|
||||
|
||||
it('does not read source comments as document headings', () => {
|
||||
expect(
|
||||
getArtifactDownloadFilename(
|
||||
{
|
||||
id: 'a',
|
||||
lastUpdateTime: 0,
|
||||
type: TOOL_ARTIFACT_TYPES.CODE,
|
||||
language: 'python',
|
||||
content: '# Copyright',
|
||||
},
|
||||
'content.md',
|
||||
),
|
||||
).toBe('code.py');
|
||||
});
|
||||
|
||||
it('preserves a long file-backed source extension during sanitization', () => {
|
||||
const filename = `${'a'.repeat(200)}.py`;
|
||||
expect(
|
||||
getArtifactDownloadFilename(
|
||||
{
|
||||
id: 'a',
|
||||
lastUpdateTime: 0,
|
||||
type: TOOL_ARTIFACT_TYPES.CODE,
|
||||
title: filename,
|
||||
download: { file_id: 'file' },
|
||||
},
|
||||
'content.md',
|
||||
),
|
||||
).toBe(`${'a'.repeat(97)}.preview.py`);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,12 +1,22 @@
|
|||
import dedent from 'dedent';
|
||||
import { excelMimeTypes, shadcnComponents } from 'librechat-data-provider';
|
||||
import filenamify from 'filenamify';
|
||||
import { gfm } from 'micromark-extension-gfm';
|
||||
import { gfmFromMarkdown } from 'mdast-util-gfm';
|
||||
import { fromMarkdown } from 'mdast-util-from-markdown';
|
||||
import {
|
||||
excelMimeTypes,
|
||||
shadcnComponents,
|
||||
getDocumentFileExtension,
|
||||
} from 'librechat-data-provider';
|
||||
import type {
|
||||
SandpackProviderProps,
|
||||
SandpackPredefinedTemplate,
|
||||
} from '@codesandbox/sandpack-react';
|
||||
import type { TStartupConfig, TAttachment, TFile } from 'librechat-data-provider';
|
||||
import type { PhrasingContent } from 'mdast';
|
||||
import type { Artifact } from '~/common';
|
||||
import { MERMAID_ARTIFACT_TYPE } from '~/common/artifacts';
|
||||
import { getCodeBlockFilename } from './downloadFile';
|
||||
|
||||
const artifactFilename = {
|
||||
'application/vnd.react': 'App.tsx',
|
||||
|
|
@ -74,6 +84,101 @@ export function getArtifactFilename(type: string, language?: string): string {
|
|||
return artifactFilename[key] ?? artifactFilename.default;
|
||||
}
|
||||
|
||||
/** Extract visible heading text without removing literal Markdown punctuation. */
|
||||
function headingText(nodes: PhrasingContent[]): string {
|
||||
return nodes
|
||||
.map((node) => {
|
||||
if ('children' in node) {
|
||||
return headingText(node.children);
|
||||
}
|
||||
if (node.type === 'text' || node.type === 'inlineCode') {
|
||||
return node.value;
|
||||
}
|
||||
if (node.type === 'image' || node.type === 'imageReference') {
|
||||
return node.alt ?? '';
|
||||
}
|
||||
return '';
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
/** Name for bytes fetched from the original attachment, rather than its cached preview. */
|
||||
export function getOriginalArtifactFilename(artifact: Artifact, fileKey: string): string {
|
||||
if (artifact.download?.filename) {
|
||||
return artifact.download.filename;
|
||||
}
|
||||
if (artifact.download?.filename === undefined) {
|
||||
return artifact.title || fileKey;
|
||||
}
|
||||
const extension = getDocumentFileExtension(artifact.download.mimeType);
|
||||
if (extension) {
|
||||
return `content${extension}`;
|
||||
}
|
||||
if (isPreviewOnlyArtifact(artifact.type) || artifact.type === TOOL_ARTIFACT_TYPES.PLAIN_TEXT) {
|
||||
return 'content.bin';
|
||||
}
|
||||
return getArtifactDownloadFilename(
|
||||
{ ...artifact, title: undefined, download: undefined },
|
||||
fileKey,
|
||||
'',
|
||||
);
|
||||
}
|
||||
|
||||
/** Names the downloaded bytes independently of the Sandpack preview file. */
|
||||
export function getArtifactDownloadFilename(
|
||||
artifact: Artifact,
|
||||
fileKey: string,
|
||||
content = artifact.content,
|
||||
): string {
|
||||
const isCode = artifact.type === TOOL_ARTIFACT_TYPES.CODE;
|
||||
const isMarkdown = artifact.type === TOOL_ARTIFACT_TYPES.MARKDOWN || artifact.type === 'text/md';
|
||||
let fallback = fileKey;
|
||||
if (isCode) {
|
||||
fallback = getCodeBlockFilename(
|
||||
artifact.language || lookupOwn(CODE_EXTENSION_TO_LANGUAGE, extensionOf(artifact.title)),
|
||||
);
|
||||
} else if (artifact.type === TOOL_ARTIFACT_TYPES.PLAIN_TEXT) {
|
||||
fallback = 'content.txt';
|
||||
}
|
||||
let title = (artifact.download?.filename ?? artifact.title)?.trim() ?? '';
|
||||
const hasOriginalName = artifact.download != null && artifact.download.filename !== null;
|
||||
if (!hasOriginalName && (title === 'Generated artifact' || title === 'untitled')) {
|
||||
title = '';
|
||||
}
|
||||
const hasSourceFilename =
|
||||
hasOriginalName &&
|
||||
title !== '' &&
|
||||
artifact.type !== TOOL_ARTIFACT_TYPES.PLAIN_TEXT &&
|
||||
!isPreviewOnlyArtifact(artifact.type);
|
||||
if (!title && isMarkdown) {
|
||||
const markdown = (content ?? '').replace(
|
||||
/^\uFEFF?---[^\S\r\n]*\r?\n[\s\S]*?\r?\n(?:---|\.\.\.)[^\S\r\n]*(?:\r?\n|$)/,
|
||||
'',
|
||||
);
|
||||
const heading = fromMarkdown(markdown, {
|
||||
extensions: [gfm()],
|
||||
mdastExtensions: [gfmFromMarkdown()],
|
||||
}).children.find((node) => node.type === 'heading');
|
||||
if (heading?.type === 'heading') {
|
||||
title = headingText(heading.children).trim();
|
||||
}
|
||||
}
|
||||
const extension = fallback.slice(fallback.lastIndexOf('.'));
|
||||
const hasMatchingExtension = title.toLowerCase().endsWith(extension);
|
||||
let filename = fallback;
|
||||
if (title) {
|
||||
filename = hasSourceFilename || hasMatchingExtension ? title : `${title}${extension}`;
|
||||
}
|
||||
filename = filenamify(filename, { replacement: '_' });
|
||||
/* File-backed blobs export cached preview content, not the original file. */
|
||||
if (artifact.download) {
|
||||
const dot = filename.lastIndexOf('.');
|
||||
filename =
|
||||
dot > 0 ? `${filename.slice(0, dot)}.preview${filename.slice(dot)}` : `${filename}.preview`;
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
|
||||
export function getTemplate(type: string, language?: string): SandpackPredefinedTemplate {
|
||||
const key = getKey(type, language);
|
||||
return artifactTemplate[key] ?? (artifactTemplate.default as SandpackPredefinedTemplate);
|
||||
|
|
@ -907,6 +1012,8 @@ export function fileToArtifact(
|
|||
* binary — serializing `content` would hand the user the preview
|
||||
* instead of the .pptx/.xlsx/.docx. */
|
||||
download: {
|
||||
filename: attachment.filename || null,
|
||||
mimeType: attachment.type,
|
||||
filepath: attachment.filepath,
|
||||
file_id: attachment.file_id,
|
||||
source: attachment.source,
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import {
|
|||
fileConfigSchema,
|
||||
isAnthropicTextDocumentType,
|
||||
getConfiguredMimeAccept,
|
||||
getDocumentFileExtension,
|
||||
bedrockDocumentMimeTypes,
|
||||
isAnthropicDocumentType,
|
||||
isPermissiveMimeConfig,
|
||||
|
|
@ -1995,3 +1996,32 @@ describe('agent attachment context limits', () => {
|
|||
expect(mergeFileConfig({ fileContextCharLimit: 250_000 }).fileContextCharLimit).toBe(250_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDocumentFileExtension', () => {
|
||||
it.each([
|
||||
['text/markdown', '.md'],
|
||||
[' TEXT/PLAIN; charset=UTF-8', '.txt'],
|
||||
['application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.docx'],
|
||||
['application/vnd.oasis.opendocument.text', '.odt'],
|
||||
['text/csv', '.csv'],
|
||||
['application/csv', '.csv'],
|
||||
['text/comma-separated-values', '.csv'],
|
||||
[' TEXT/COMMA-SEPARATED-VALUES; charset=utf-8', '.csv'],
|
||||
['application/vnd.ms-excel', '.xls'],
|
||||
['application/msexcel', '.xls'],
|
||||
['application/x-msexcel', '.xls'],
|
||||
['application/x-ms-excel', '.xls'],
|
||||
['application/x-excel', '.xls'],
|
||||
['application/x-dos_ms_excel', '.xls'],
|
||||
['application/xls', '.xls'],
|
||||
['application/x-xls', '.xls'],
|
||||
['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', '.xlsx'],
|
||||
['application/vnd.oasis.opendocument.spreadsheet', '.ods'],
|
||||
['application/vnd.openxmlformats-officedocument.presentationml.presentation', '.pptx'],
|
||||
['application/vnd.openxmlformats-officedocument.presentationml.template', '.potx'],
|
||||
['application/unknown', undefined],
|
||||
[undefined, undefined],
|
||||
])('resolves %s', (mimeType, expected) => {
|
||||
expect(getDocumentFileExtension(mimeType)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -791,6 +791,13 @@ const documentMimeExtensions: ReadonlyArray<readonly [string, readonly string[]]
|
|||
['message/rfc822', ['.eml']],
|
||||
];
|
||||
|
||||
/** Preferred extension for a known document MIME type, including its leading dot. */
|
||||
export function getDocumentFileExtension(mimeType?: string): string | undefined {
|
||||
const normalized = mimeType?.split(';', 1)[0].trim().toLowerCase();
|
||||
const canonical = normalized === 'text/comma-separated-values' ? 'text/csv' : normalized;
|
||||
return documentMimeExtensions.find(([type]) => type === canonical)?.[1][0];
|
||||
}
|
||||
|
||||
const documentMimeSet = new Set(documentMimeExtensions.map(([mimeType]) => mimeType));
|
||||
|
||||
/** Every MIME type LibreChat may accept, used to detect patterns that reach beyond the representable set. */
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue