Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
📥 fix: Download Original File From Artifact Preview Panel for Office Documents (#14026)
Marco Beretta6576688f1b82
diff --git a/client/src/common/artifacts.ts b/client/src/common/artifacts.tsindex 168b0d56e3..3630ac3f24 100644--- a/client/src/common/artifacts.ts+++ b/client/src/common/artifacts.ts@@ -4,6 +4,20 @@ export interface CodeBlock {content: string;}+/**+ * Original-file download metadata for artifacts backed by a real+ * code-interpreter file (e.g. an office document whose panel preview is+ * a server-rendered HTML render, not the binary itself). When present,+ * the panel download button fetches this file instead of serializing+ * the rendered preview `content`.+ */+export interface ArtifactDownload {+ filepath?: string;+ file_id?: string;+ source?: string;+ user?: string;+}+export interface Artifact {id: string;lastUpdateTime: number;@@ -14,6 +28,7 @@ export interface Artifact {content?: string;title?: string;type?: string;+ download?: ArtifactDownload;}export type ArtifactFiles =diff --git a/client/src/components/Artifacts/DownloadArtifact.tsx b/client/src/components/Artifacts/DownloadArtifact.tsxindex b6d2873c46..3e2ff7b0e2 100644--- a/client/src/components/Artifacts/DownloadArtifact.tsx+++ b/client/src/components/Artifacts/DownloadArtifact.tsx@@ -1,8 +1,13 @@import React, { useState } from 'react';+import { Button } from '@librechat/client';import { Download, CircleCheckBig } from 'lucide-react';import type { Artifact } from '~/common';-import { Button } from '@librechat/client';+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';@@ -12,23 +17,70 @@ const DownloadArtifact = ({ artifact }: { artifact: Artifact }) => {const [isDownloaded, setIsDownloaded] = useState(false);const { fileKey: fileName } = useArtifactProps({ artifact });- const handleDownload = () => {+ /* 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). */+ 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 downloadOriginalFile = isPreviewOnlyArtifact(artifact.type) && hasUsableRoute;+ const { handleDownload: downloadAttachment } = useAttachmentLink({+ href: download?.filepath ?? '',+ filename: artifact.title ?? fileName,+ file_id: download?.file_id,+ user: download?.user,+ source: download?.source,+ });++ const markDownloaded = () => {+ setIsDownloaded(true);+ setTimeout(() => setIsDownloaded(false), 3000);+ };++ const downloadContent = () => {+ const content = currentCode ?? artifact.content ?? '';+ if (!content) {+ 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;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ window.URL.revokeObjectURL(url);+ markDownloaded();+ };++ const handleDownload = async (event: React.MouseEvent<HTMLButtonElement>) => {try {- const content = currentCode ?? artifact.content ?? '';- if (!content) {+ 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;}- 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;- document.body.appendChild(link);- link.click();- document.body.removeChild(link);- window.URL.revokeObjectURL(url);- setIsDownloaded(true);- setTimeout(() => setIsDownloaded(false), 3000);+ downloadContent();} catch (error) {console.error('Download failed:', error);}diff --git a/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsx b/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsxnew file mode 100644index 0000000000..45f62bf67c--- /dev/null+++ b/client/src/components/Artifacts/__tests__/DownloadArtifact.test.tsx@@ -0,0 +1,165 @@+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 DownloadArtifact from '../DownloadArtifact';++const mockFileDownload = jest.fn();++jest.mock('~/hooks', () => ({+ useLocalize:+ () =>+ (key: string): string =>+ key,+}));++jest.mock('~/hooks/Artifacts/useArtifactProps', () => ({+ __esModule: true,+ default: () => ({ fileKey: 'index.html', files: {}, template: 'static', sharedProps: {} }),+}));++jest.mock('~/Providers/EditorContext', () => ({+ useCodeState: () => ({ currentCode: undefined }),+}));++jest.mock('~/components/Chat/Messages/Content/Parts/LogLink', () => ({+ useAttachmentLink: () => ({ handleDownload: mockFileDownload }),+ isLocallyStoredSource: (source?: string) =>+ ['local', 'firebase', 's3', 'cloudfront', 'azure_blob'].includes(source ?? ''),+}));++const officeArtifact: Artifact = {+ id: 'tool-artifact-fid-1',+ lastUpdateTime: 0,+ type: TOOL_ARTIFACT_TYPES.PRESENTATION,+ title: 'deck.pptx',+ content: '<html><body>slide text scrape</body></html>',+ download: {+ filepath: '/api/files/code/output/deck.pptx',+ file_id: 'fid-1',+ source: 'execute_code',+ user: 'user-1',+ },+};++const htmlArtifact: Artifact = {+ id: 'llm-artifact-1',+ lastUpdateTime: 0,+ type: TOOL_ARTIFACT_TYPES.HTML,+ title: 'Authored Page',+ content: '<h1>hello</h1>',+};++/* Shared link to a non-snapshotted code-execution office artifact: share+ * sanitization strips source/user and `applyShareFileRoute` deletes+ * filepath, leaving only file_id. There is no route to fetch the+ * original, so the panel must fall back to the preview-content blob. */+const sharedNoRouteArtifact: Artifact = {+ id: 'tool-artifact-fid-2',+ lastUpdateTime: 0,+ type: TOOL_ARTIFACT_TYPES.PRESENTATION,+ title: 'deck.pptx',+ content: '<html><body>slide text scrape</body></html>',+ download: {+ file_id: 'fid-2',+ },+};++/* Locally-stored office artifact with no filepath but full local-file+ * metadata: the API download path (isLocallyStoredSource + file_id ++ * user) can still fetch the original. */+const localMetadataArtifact: Artifact = {+ id: 'tool-artifact-fid-3',+ lastUpdateTime: 0,+ type: TOOL_ARTIFACT_TYPES.SPREADSHEET,+ title: 'book.xlsx',+ content: '<html><body>sheet scrape</body></html>',+ download: {+ file_id: 'fid-3',+ source: 'local',+ user: 'user-3',+ },+};++describe('DownloadArtifact', () => {+ let createObjectURL: jest.Mock;+ let revokeObjectURL: jest.Mock;+ let anchorClick: jest.SpyInstance;++ beforeEach(() => {+ mockFileDownload.mockReset();+ // The attachment helper resolves to `true` when a file was delivered.+ mockFileDownload.mockResolvedValue(true);+ createObjectURL = jest.fn(() => 'blob:mock');+ revokeObjectURL = jest.fn();+ Object.defineProperty(window.URL, 'createObjectURL', {+ configurable: true,+ value: createObjectURL,+ });+ Object.defineProperty(window.URL, 'revokeObjectURL', {+ configurable: true,+ value: revokeObjectURL,+ });+ anchorClick = jest+ .spyOn(HTMLAnchorElement.prototype, 'click')+ .mockImplementation(() => undefined);+ });++ afterEach(() => {+ anchorClick.mockRestore();+ });++ 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 () => {+ fireEvent.click(screen.getByRole('button'));+ });+ expect(mockFileDownload).toHaveBeenCalledTimes(1);+ // The preview HTML must NOT be serialized into a blob download.+ expect(createObjectURL).not.toHaveBeenCalled();+ // A delivered file flips the button to the success checkmark.+ expect(container.querySelector('.lucide-circle-check-big')).not.toBeNull();+ });++ it('does NOT show success when the original-file download fails', async () => {+ // Expired code-output URL / 404 share download: the helper resolves+ // to false instead of throwing. The checkmark must stay hidden.+ mockFileDownload.mockResolvedValueOnce(false);+ const { container } = render(<DownloadArtifact artifact={officeArtifact} />);+ await act(async () => {+ fireEvent.click(screen.getByRole('button'));+ });+ expect(mockFileDownload).toHaveBeenCalledTimes(1);+ expect(container.querySelector('.lucide-circle-check-big')).toBeNull();+ expect(container.querySelector('.lucide-download')).not.toBeNull();+ });++ it('serializes content as a blob for a non-file-backed (LLM-authored) artifact', async () => {+ render(<DownloadArtifact artifact={htmlArtifact} />);+ await act(async () => {+ fireEvent.click(screen.getByRole('button'));+ });+ expect(createObjectURL).toHaveBeenCalledTimes(1);+ expect(mockFileDownload).not.toHaveBeenCalled();+ });++ it('falls back to the preview blob when an office artifact has only a lone file_id (no usable route)', async () => {+ render(<DownloadArtifact artifact={sharedNoRouteArtifact} />);+ await act(async () => {+ fireEvent.click(screen.getByRole('button'));+ });+ // No filepath/share route and no local metadata: must NOT call the+ // empty attachment fetch; serialize the preview content instead.+ expect(mockFileDownload).not.toHaveBeenCalled();+ expect(createObjectURL).toHaveBeenCalledTimes(1);+ });++ it('downloads the original via the local-file path when filepath is absent but local metadata is present', async () => {+ render(<DownloadArtifact artifact={localMetadataArtifact} />);+ await act(async () => {+ fireEvent.click(screen.getByRole('button'));+ });+ expect(mockFileDownload).toHaveBeenCalledTimes(1);+ expect(createObjectURL).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/Chat/Messages/Content/Parts/LogLink.tsx b/client/src/components/Chat/Messages/Content/Parts/LogLink.tsxindex 7d81a7c42e..2ffbb3b1d1 100644--- a/client/src/components/Chat/Messages/Content/Parts/LogLink.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/LogLink.tsx@@ -27,7 +27,7 @@ interface AttachmentLinkOptions {* Files with these sources are stored on the LibreChat server and should* use the /api/files/download endpoint instead of direct URL access.*/-const isLocallyStoredSource = (source?: string): boolean => {+export const isLocallyStoredSource = (source?: string): boolean => {if (!source) {return false;}@@ -54,7 +54,16 @@ export const useAttachmentLink = ({const { refetch: downloadFromApi } = useFileDownload(user, file_id, { source });const { refetch: downloadFromUrl } = useCodeOutputDownload(href);- const handleDownload = async (event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>) => {+ /**+ * Triggers the download and reports whether a file was actually+ * delivered: `true` once a download is initiated, `false` on a fetch+ * error or an empty/denied response (e.g. an expired code-output URL or+ * a 404 share download). Callers that show success feedback should gate+ * it on this result rather than on the promise merely resolving.+ */+ const handleDownload = async (+ event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement>,+ ): Promise<boolean> => {event.preventDefault();try {// In a shared view, a snapshotted file's href is rewritten to the share@@ -63,12 +72,12 @@ export const useAttachmentLink = ({// original href / code-output path still works when snapshots are disabled.if (shareId && file_id && href.startsWith('/api/share/')) {triggerDownload(sharedFileDownload(shareId, file_id), filename);- return;+ return true;}if (!useLocalDownload && isHttpDownloadTarget(href)) {triggerDownload(href, filename);- return;+ return true;}const stream = useLocalDownload ? await downloadFromApi() : await downloadFromUrl();@@ -78,11 +87,13 @@ export const useAttachmentLink = ({status: 'error',message: 'Error downloading file',});- return;+ return false;}triggerDownload(stream.data, filename);+ return true;} catch (error) {console.error('Error downloading file:', error);+ return false;}};diff --git a/client/src/utils/__tests__/artifacts.test.ts b/client/src/utils/__tests__/artifacts.test.tsindex be65a095e1..b8439008d5 100644--- a/client/src/utils/__tests__/artifacts.test.ts+++ b/client/src/utils/__tests__/artifacts.test.ts@@ -1,3 +1,5 @@+import { FileSources } from 'librechat-data-provider';+import type { ToolArtifactType } from '../artifacts';import {buildSandpackOptions,detectArtifactTypeFromFile,@@ -7,7 +9,6 @@ import {languageForFilename,TOOL_ARTIFACT_TYPES,} from '../artifacts';-import type { ToolArtifactType } from '../artifacts';const TAILWIND_CDN = 'https://cdn.tailwindcss.com/3.4.17#tailwind.js';@@ -691,6 +692,31 @@ describe('fileToArtifact', () => {expect(fileToArtifact({ ...baseFile, filename: 'flow.mmd', type: '', text: '' })).toBeNull();});+ it('threads original-file download metadata onto the artifact', () => {+ /* The panel download button needs the original-file coordinates to+ * fetch the real binary (e.g. a pptx) instead of serializing the+ * server-rendered HTML preview. `fileToArtifact` must carry them+ * through from the attachment. */+ const artifact = fileToArtifact({+ ...baseFile,+ filename: 'deck.pptx',+ type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ text: '<html><body>slides</body></html>',+ textFormat: 'html',+ filepath: '/api/files/code/output/deck.pptx',+ source: FileSources.execute_code,+ user: 'user-1',+ });+ expect(artifact).not.toBeNull();+ expect(artifact!.type).toBe(TOOL_ARTIFACT_TYPES.PRESENTATION);+ expect(artifact!.download).toEqual({+ filepath: '/api/files/code/output/deck.pptx',+ file_id: 'fid-1',+ source: FileSources.execute_code,+ user: 'user-1',+ });+ });+it('uses the caller-provided placeholder when a deferred-extraction file has no text', () => {/* Plain-text and markdown remain on the lenient empty-text gate so the* artifact card can render a "preparing preview…" placeholder whilediff --git a/client/src/utils/artifacts.ts b/client/src/utils/artifacts.tsindex b5ff9552e7..fd1de0de4f 100644--- a/client/src/utils/artifacts.ts+++ b/client/src/utils/artifacts.ts@@ -842,6 +842,8 @@ export function fileToArtifact(| 'textFormat'| 'updatedAt'| 'createdAt'+ | 'source'+ | 'user'>>,options?: FileToArtifactOptions,@@ -894,6 +896,18 @@ export function fileToArtifact(language,messageId: attachment.messageId ?? undefined,lastUpdateTime: toLastUpdate(attachment),+ /* Preserve the original-file download coordinates so the panel's+ * download button can fetch the real file (matching the inline+ * card's `useAttachmentLink` path). Critical for office buckets+ * whose `content` is a server-rendered HTML preview, not the+ * binary — serializing `content` would hand the user the preview+ * instead of the .pptx/.xlsx/.docx. */+ download: {+ filepath: attachment.filepath,+ file_id: attachment.file_id,+ source: attachment.source,+ user: attachment.user,+ },};}