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: Preview SVG Artifacts From Their Edited Source (#16123)
lia-by-librechat[bot]61fe243151a3
diff --git a/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx b/client/src/components/Artifacts/SandboxArtifactTabs.test.tsxnew file mode 100644index 0000000000..dd3ca02f4d--- /dev/null+++ b/client/src/components/Artifacts/SandboxArtifactTabs.test.tsx@@ -0,0 +1,130 @@+import React from 'react';+import * as Tabs from '@radix-ui/react-tabs';+import { render } from '@testing-library/react';+import type { SandpackPreviewRef } from '@codesandbox/sandpack-react/unstyled';+import type { Artifact } from '~/common';+import SandboxArtifactTabs from './SandboxArtifactTabs';++interface PreviewProps {+ files: Record<string, string>;+ fileKey: string;+ currentCode?: string;+}++const mockPreview = jest.fn((_props: PreviewProps) => null);+let mockCurrentCode: string | undefined;++jest.mock('./ArtifactCodeEditor', () => ({+ ArtifactCodeEditor: () => null,+}));++jest.mock('./ArtifactPreview', () => ({+ ArtifactPreview: (props: PreviewProps) => mockPreview(props),+}));++jest.mock('~/Providers/EditorContext', () => ({+ useCodeState: () => ({ currentCode: mockCurrentCode, setCurrentCode: jest.fn() }),+}));++jest.mock('~/Providers', () => ({+ useShareContext: () => ({ shareId: undefined }),+}));++jest.mock('~/data-provider', () => ({+ useGetStartupConfig: () => ({ data: {} }),+ useGetSharedStartupConfig: () => ({ data: {} }),+}));++const previewRef = {+ current: Object.create(null) as SandpackPreviewRef,+} as React.MutableRefObject<SandpackPreviewRef>;++const original =+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>';+const edited =+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><circle cx="5" cy="5" r="4"/></svg>';++const svgArtifact: Artifact = {+ id: 'svg-artifact-1',+ type: 'image/svg+xml',+ title: 'Chart',+ content: original,+ lastUpdateTime: 1,+};++function renderTabs(artifact: Artifact = svgArtifact) {+ return render(+ <Tabs.Root value="preview">+ <SandboxArtifactTabs artifact={artifact} previewRef={previewRef} />+ </Tabs.Root>,+ );+}++function lastFiles(): Record<string, string> {+ return mockPreview.mock.calls.at(-1)?.[0].files ?? {};+}++describe('SandboxArtifactTabs SVG preview', () => {+ beforeEach(() => {+ mockCurrentCode = undefined;+ mockPreview.mockClear();+ });++ /** An SVG preview renders a derived `index.html`, so an edit that only+ * replaced `index.svg` left the preview showing the original drawing. */+ it('rebuilds the preview shell from the edited source', () => {+ const { rerender } = renderTabs();+ expect(lastFiles()['index.html']).toContain(original);++ /* Editor text belongs to the preview only once it was typed against the+ * artifact on screen, so it lands on a later render, not on mount. */+ mockCurrentCode = edited;+ rerender(+ <Tabs.Root value="preview">+ <SandboxArtifactTabs artifact={svgArtifact} previewRef={previewRef} />+ </Tabs.Root>,+ );++ const files = lastFiles();+ expect(files['index.svg']).toBe(edited);+ expect(files['index.html']).toContain(edited);+ expect(files['index.html']).not.toContain('<rect');+ });++ it('keeps the artifact source when the editor is emptied', () => {+ const { rerender } = renderTabs();++ mockCurrentCode = '';+ rerender(+ <Tabs.Root value="preview">+ <SandboxArtifactTabs artifact={svgArtifact} previewRef={previewRef} />+ </Tabs.Root>,+ );++ expect(lastFiles()['index.html']).toContain(original);+ });++ it('leaves artifacts whose preview entry is the edited file untouched', () => {+ const htmlArtifact: Artifact = {+ id: 'html-artifact-1',+ type: 'text/html',+ title: 'Page',+ content: '<p>original</p>',+ lastUpdateTime: 1,+ };++ const { rerender } = renderTabs(htmlArtifact);++ mockCurrentCode = '<p>edited</p>';+ rerender(+ <Tabs.Root value="preview">+ <SandboxArtifactTabs artifact={htmlArtifact} previewRef={previewRef} />+ </Tabs.Root>,+ );++ /* `ArtifactPreview` owns this swap; the tabs must not pre-empt it. */+ const call = mockPreview.mock.calls.at(-1)?.[0];+ expect(call?.files['index.html']).toBe('<p>original</p>');+ expect(call?.currentCode).toBe('<p>edited</p>');+ });+});diff --git a/client/src/components/Artifacts/SandboxArtifactTabs.tsx b/client/src/components/Artifacts/SandboxArtifactTabs.tsxindex 2fcede516a..acde5944e2 100644--- a/client/src/components/Artifacts/SandboxArtifactTabs.tsx+++ b/client/src/components/Artifacts/SandboxArtifactTabs.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef } from 'react';+import { useEffect, useMemo, useRef } from 'react';import * as Tabs from '@radix-ui/react-tabs';import type { SandpackPreviewRef } from '@codesandbox/sandpack-react/unstyled';import type { editor } from 'monaco-editor';@@ -42,7 +42,16 @@ export default function SandboxArtifactTabs({lastIdRef.current = artifact.id;}, [artifact.id, setCurrentCode]);- const { files, fileKey, template, sharedProps } = useArtifactProps({ artifact });+ const { files, fileKey, template, sharedProps, deriveFiles } = useArtifactProps({ artifact });+ const editedCode = hasCurrentArtifactCode ? currentCode : undefined;++ /* An artifact whose preview entry is derived from its source needs the whole+ * set rebuilt from the editor text; `ArtifactPreview` can only swap the file+ * the editor owns. Empty text counts as no edit there, so it does here too. */+ const previewFiles = useMemo(+ () => (deriveFiles != null && editedCode ? deriveFiles(editedCode) : files),+ [deriveFiles, editedCode, files],+ );return (<div className="flex h-full w-full flex-col">@@ -65,12 +74,12 @@ export default function SandboxArtifactTabs({tabIndex={-1}><ArtifactPreview- files={files}+ files={previewFiles}fileKey={fileKey}template={template}previewRef={previewRef}sharedProps={sharedProps}- currentCode={hasCurrentArtifactCode ? currentCode : undefined}+ currentCode={editedCode}startupConfig={resolvedStartupConfig}/></Tabs.Content>diff --git a/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts b/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.tsindex 1f71e4c2c0..76044d7a57 100644--- a/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts+++ b/client/src/hooks/Artifacts/__tests__/useArtifactProps.test.ts@@ -1,7 +1,7 @@import { renderHook } from '@testing-library/react';-import useArtifactProps from '../useArtifactProps';-import { TOOL_ARTIFACT_TYPES, wrapAsFencedCodeBlock } from '~/utils/artifacts';import type { Artifact } from '~/common';+import { TOOL_ARTIFACT_TYPES, wrapAsFencedCodeBlock } from '~/utils/artifacts';+import useArtifactProps from '../useArtifactProps';describe('useArtifactProps', () => {const createArtifact = (partial: Partial<Artifact>): Artifact => ({@@ -184,6 +184,51 @@ describe('useArtifactProps', () => {});});+ describe('svg artifacts', () => {+ const svg =+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600"><rect width="800" height="600" fill="#0f172a"/></svg>';++ it('uses index.svg as the editor fileKey on the static template', () => {+ const artifact = createArtifact({ type: 'image/svg+xml', content: svg });+ const { result } = renderHook(() => useArtifactProps({ artifact }));+ expect(result.current.fileKey).toBe('index.svg');+ expect(result.current.template).toBe('static');+ });++ it('keeps the source on index.svg and wraps it in index.html for preview', () => {+ const artifact = createArtifact({ type: 'image/svg+xml', content: svg });+ const { result } = renderHook(() => useArtifactProps({ artifact }));+ expect(result.current.files['index.svg']).toBe(svg);+ expect(result.current.files['index.html']).toMatch(/<!DOCTYPE html>/i);+ expect(result.current.files['index.html']).toContain(svg);+ });++ it('accepts the image/svg alias', () => {+ const artifact = createArtifact({ type: 'image/svg', content: '<svg></svg>' });+ const { result } = renderHook(() => useArtifactProps({ artifact }));+ expect(result.current.fileKey).toBe('index.svg');+ expect(result.current.files['index.html']).toContain('<svg></svg>');+ });++ it('exposes deriveFiles so edited source can rebuild the derived preview entry', () => {+ const artifact = createArtifact({ type: 'image/svg+xml', content: svg });+ const { result } = renderHook(() => useArtifactProps({ artifact }));++ const edited = '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="5" cy="5" r="4"/></svg>';+ const rebuilt = result.current.deriveFiles?.(edited) ?? {};++ expect(rebuilt['index.svg']).toBe(edited);+ expect(rebuilt['index.html']).toContain(edited);+ expect(rebuilt['index.html']).not.toContain('<rect');+ });++ it('leaves deriveFiles unset when the edited file is the preview entry', () => {+ const artifact = createArtifact({ type: 'text/html', content: '<p>hi</p>' });+ const { result } = renderHook(() => useArtifactProps({ artifact }));+ expect(result.current.deriveFiles).toBeUndefined();+ });+ });+describe('edge cases', () => {it('should handle artifact with language parameter', () => {const artifact = createArtifact({diff --git a/client/src/hooks/Artifacts/useArtifactProps.ts b/client/src/hooks/Artifacts/useArtifactProps.tsindex 017bdb195d..26271390a0 100644--- a/client/src/hooks/Artifacts/useArtifactProps.ts+++ b/client/src/hooks/Artifacts/useArtifactProps.ts@@ -7,6 +7,8 @@ import {getProps,getTemplate,getArtifactFilename,+ getSvgFiles,+ isSvgArtifactType,languageForFilename,wrapAsFencedCodeBlock,TOOL_ARTIFACT_TYPES,@@ -67,6 +69,10 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) {];}+ if (isSvgArtifactType(type)) {+ return [getArtifactFilename(type), getSvgFiles(artifact.content ?? '')];+ }+const fileKey = getArtifactFilename(artifact.type ?? '', artifact.language);const files = removeNullishValues({[fileKey]: artifact.content,@@ -88,10 +94,20 @@ export default function useArtifactProps({ artifact }: { artifact: Artifact }) {const sharedProps = useMemo(() => getProps(artifact.type ?? ''), [artifact.type]);+ /* SVG previews render a *derived* `index.html`, not the edited file itself,+ * so swapping `fileKey` alone would leave the preview on the original+ * source while the code tab shows the new one. Consumers that hold editor+ * text rebuild the whole set through this instead. */+ const deriveFiles = useMemo(+ () => (isSvgArtifactType(artifact.type ?? '') ? getSvgFiles : undefined),+ [artifact.type],+ );+return {files,fileKey,template,sharedProps,+ deriveFiles,};}diff --git a/client/src/utils/__tests__/artifacts.test.ts b/client/src/utils/__tests__/artifacts.test.tsindex 874d361bb0..11d2fedb6d 100644--- a/client/src/utils/__tests__/artifacts.test.ts+++ b/client/src/utils/__tests__/artifacts.test.ts@@ -4,16 +4,100 @@ import {artifactRowKind,buildSandpackOptions,getArtifactDownloadFilename,+ getArtifactFilename,+ getDependencies,+ getSvgFiles,+ getTemplate,detectArtifactTypeFromFile,fileToArtifact,isCodeOnlyArtifact,isPreviewOnlyArtifact,+ isSvgArtifactType,languageForFilename,TOOL_ARTIFACT_TYPES,} from '../artifacts';const TAILWIND_CDN = 'https://cdn.tailwindcss.com/3.4.17#tailwind.js';+describe('SVG artifact template mapping (#16087)', () => {+ /* Bare `<svg>` handed to the static template as `index.html` renders+ * blank. These types must map to a dedicated SVG file (and empty+ * Sandpack deps) instead of riding `artifactFilename.default`. */+ it.each(['image/svg+xml', 'image/svg'])(+ 'maps %s to index.svg on the static template, not default index.html',+ (type) => {+ expect(getArtifactFilename(type)).toBe('index.svg');+ expect(getTemplate(type)).toBe('static');+ expect(getDependencies(type)).toEqual({});+ },+ );++ it('wraps a bare SVG in an HTML document for the static preview entry', () => {+ const svg =+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600"><rect width="800" height="600" fill="#0f172a"/></svg>';+ const files = getSvgFiles(svg);+ expect(files['index.svg']).toBe(svg);+ expect(files['index.html']).toMatch(/<!DOCTYPE html>/i);+ expect(files['index.html']).toContain('<body');+ expect(files['index.html']).toContain(svg);+ });++ it('strips an XML declaration so the HTML shell stays a valid HTML document', () => {+ const svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"></svg>';+ const files = getSvgFiles(`<?xml version="1.0" encoding="UTF-8"?>\n${svg}`);+ expect(files['index.html']).not.toMatch(/<\?xml/i);+ expect(files['index.html']).toContain(svg);+ });++ it('sizes only the root SVG so a nested viewport keeps its own geometry', () => {+ const originalHead = document.head.innerHTML;+ const originalBody = document.body.innerHTML;+ try {+ const html = getSvgFiles(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">' ++ '<svg id="sprite" width="20" height="20" x="5" y="5"><rect width="20" height="20"/></svg>' ++ '</svg>',+ )['index.html'];+ /* Mount the shell's own generated style and body. CSS overrides SVG+ * presentation attributes, so an unscoped `svg` rule would stretch the+ * nested viewport to the panel and corrupt the drawing's layout. */+ const css = html.match(/<style>([\s\S]*?)<\/style>/i)?.[1] ?? '';+ const markup = html.match(/<body>([\s\S]*?)<\/body>/i)?.[1] ?? '';+ document.head.innerHTML = `<style>${css}</style>`;+ document.body.innerHTML = markup;++ const root = document.body.querySelector('svg');+ const nested = document.getElementById('sprite');+ if (root == null || nested == null) {+ throw new Error('expected the mounted shell to hold both SVG viewports');+ }+ expect(getComputedStyle(root).width).toBe('100%');+ expect(getComputedStyle(root).height).toBe('100%');+ expect(getComputedStyle(nested).width).not.toBe('100%');+ expect(getComputedStyle(nested).height).not.toBe('100%');+ } finally {+ document.head.innerHTML = originalHead;+ document.body.innerHTML = originalBody;+ }+ });++ it('recognizes both SVG artifact types and nothing else', () => {+ expect(isSvgArtifactType('image/svg+xml')).toBe(true);+ expect(isSvgArtifactType('image/svg')).toBe(true);+ expect(isSvgArtifactType('image/png')).toBe(false);+ expect(isSvgArtifactType('text/html')).toBe(false);+ expect(isSvgArtifactType('')).toBe(false);+ });++ it('rebuilds both entries so no original source survives an edit', () => {+ const edited = '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="5" cy="5" r="4"/></svg>';+ const files = getSvgFiles(edited);+ expect(files['index.svg']).toBe(edited);+ expect(files['index.html']).toContain(edited);+ expect(files['index.html']).not.toContain('<rect');+ });+});+describe('buildSandpackOptions', () => {it('includes externalResources with .js fragment hint for static template', () => {const options = buildSandpackOptions('static');diff --git a/client/src/utils/artifacts.ts b/client/src/utils/artifacts.tsindex cae3937eef..e192e93061 100644--- a/client/src/utils/artifacts.ts+++ b/client/src/utils/artifacts.ts@@ -31,6 +31,11 @@ const artifactFilename = {'application/vnd.librechat.docx-preview': 'index.html','application/vnd.librechat.spreadsheet-preview': 'index.html','application/vnd.librechat.presentation-preview': 'index.html',+ /* SVG artifacts are a bare `<svg>` document. The Sandpack `static`+ * template always loads `index.html`, so `getSvgFiles` ships a+ * companion HTML shell; the editor/download file stays `index.svg`. */+ 'image/svg+xml': 'index.svg',+ 'image/svg': 'index.svg',// mermaid and markdown types are handled separately in useArtifactProps.tsdefault: 'index.html',// 'css': 'css',@@ -68,6 +73,8 @@ const artifactTemplate: Record<'application/vnd.librechat.docx-preview': 'static','application/vnd.librechat.spreadsheet-preview': 'static','application/vnd.librechat.presentation-preview': 'static',+ 'image/svg+xml': 'static',+ 'image/svg': 'static',default: 'static',// 'css': 'css',// 'javascript': 'js',@@ -189,6 +196,47 @@ export function getTemplate(type: string, language?: string): SandpackPredefinedreturn artifactTemplate[key] ?? (artifactTemplate.default as SandpackPredefinedTemplate);}+/** `image/svg` is the alias some callers emit for `image/svg+xml`. */+export function isSvgArtifactType(type: string): boolean {+ return type === 'image/svg+xml' || type === 'image/svg';+}++/**+ * Files for an `image/svg+xml` (or `image/svg`) artifact. The Sandpack+ * `static` template always loads `index.html`; a bare SVG in that slot+ * renders blank. Keep the source on `index.svg` for the code tab and wrap+ * a copy in a full-viewport HTML shell for the preview. viewBox-only+ * sources fill the panel via `body > svg { width/height: 100% }`, scoped to+ * the root because CSS beats presentation attributes: an unscoped `svg` rule+ * would stretch a nested `<svg>` viewport, such as a sprite or inset diagram,+ * over its own `width`/`height` and corrupt the artifact's internal layout.+ *+ * The shell holds a *copy* of the source, so an edit cannot be applied by+ * replacing `index.svg` alone — both entries have to be rebuilt from the+ * new text. `useArtifactProps` exposes this builder as `deriveFiles` for+ * exactly that.+ */+export function getSvgFiles(content: string): Record<string, string> {+ const svg = content.replace(/^\uFEFF?\s*<\?xml\b[^?]*\?>\s*/i, '');+ return {+ 'index.svg': content,+ 'index.html': `<!DOCTYPE html>+<html>+<head>+<meta charset="utf-8"/>+<meta name="viewport" content="width=device-width, initial-scale=1"/>+<style>+html,body{margin:0;height:100%;overflow:hidden}+body>svg{display:block;width:100%;height:100%}+</style>+</head>+<body>+${svg}+</body>+</html>`,+ };+}+const standardDependencies = {three: '^0.167.1','lucide-react': '^0.394.0',@@ -265,6 +313,9 @@ const dependenciesMap: Record<'application/vnd.librechat.docx-preview': {},'application/vnd.librechat.spreadsheet-preview': {},'application/vnd.librechat.presentation-preview': {},+ /* SVG preview is a static HTML shell + the source file; no npm deps. */+ 'image/svg+xml': {},+ 'image/svg': {},default: standardDependencies,};