fix: isolate generated SVG figures as images

This commit is contained in:
amosblomqvist
2026-10-25 23:29:00 +02:00
parent fc3673466d
commit 6701503801
5 changed files with 282 additions and 50 deletions
+37
View File
@@ -0,0 +1,37 @@
/** Two display-only repairs for inputs the old HTML embedding accepted.
* Do not rewrite stored artifacts/downloads or attempt general XML repair.
* Comments, CDATA and processing instructions are copied verbatim. */
export function svgImageSource(svg: string): string {
let foundRoot = false;
return svg.replace(
/<!--[\s\S]*?(?:-->|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>|$)|<\?[\s\S]*?(?:\?>|$)|<\/?[a-zA-Z](?:[^<>"']|"[^"]*"|'[^']*')*>|&nbsp;/g,
(token) => {
if (token.startsWith("<!--") || token.startsWith("<![CDATA[") || token.startsWith("<?")) return token;
if (!foundRoot && /^<svg(?=[\s/>])/i.test(token)) {
foundRoot = true;
// Consume complete attribute values, so text mentioning xmlns
// inside a different attribute cannot masquerade as a declaration.
const attrs = token.matchAll(/\s([^\s=/>]+)(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+))?/g);
const hasNamespace = Array.from(attrs).some((attr) => attr[1] === "xmlns");
if (!hasNamespace) token = token.replace(/^<svg/i, '$& xmlns="http://www.w3.org/2000/svg"');
}
return token.replace(/&nbsp;/g, "&#160;");
},
);
}
/** Keep generated SVG in an image document, outside the app's CSS and ID scope.
* This is a display boundary, not a sanitizer for the original SVG download. */
export function SvgImage({
svg,
className,
width,
}: {
svg: string;
className?: string;
width?: number;
}) {
// The source is already an in-memory vector image; no Next image optimization.
// eslint-disable-next-line @next/next/no-img-element
return <img src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgImageSource(svg))}`} alt="Figure" className={className} width={width} draggable={false} />;
}
+12 -18
View File
@@ -8,6 +8,7 @@ import { Toggle } from "@/components/settings/controls";
import { useSessionMermaid } from "@/components/session-overlay";
import { downloadFile } from "@/components/artifacts/download";
import { DispatchCard } from "@/components/artifacts/dispatch-card";
import { SvgImage } from "@/components/artifacts/svg-image";
import type { ArtifactPartProps, VisualResult } from "@/src/core";
/**
@@ -16,22 +17,10 @@ import type { ArtifactPartProps, VisualResult } from "@/src/core";
* the chat view's jobs feed). The SVG itself renders from the steer message
* (sub-agent result delivery) via VisualOutputCard.
*
* The SVG is model-authored for the learner's own machine (their own teacher
* wrote it, verified by looking) — dangerouslySetInnerHTML is acceptable
* here, with a cheap hygiene pass (sanitizeSvg: strip <script> blocks, on*
* handlers, and javascript:/data:text/html URLs) since it lands in the
* app's DOM.
* Both display modes use an SVG image document: generated markup and its
* styles never join the app's DOM. Downloads still contain the original SVG.
*/
/** Cheap SVG hygiene — not a full sanitizer, just removing the obvious exec vectors. */
export function sanitizeSvg(svg: string): string {
return svg
.replace(/<script[\s\S]*?<\/script\s*>/gi, "")
.replace(/<script[^>]*\/?>/gi, "")
.replace(/\son[a-z]+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi, "")
.replace(/(href|xlink:href)\s*=\s*(?:"\s*(?:javascript|data:text\/html)[^"]*"|'\s*(?:javascript|data:text\/html)[^']*'|(?:javascript|data:text\/html)[^\s>]*)/gi, "");
}
/** The svg root's DECLARED width in px, when there is one — the natural
* size the card displays at instead of stretching to full width (owner,
* 2026-10-07). %, em, "auto", or a missing attribute → null (the caller
@@ -122,13 +111,18 @@ export function VisualOutputCard({
<div
className={
natural !== null
? "w-fit max-w-full overflow-hidden rounded-lg bg-white [&_svg]:h-auto [&_svg]:max-w-full"
: "w-full overflow-hidden rounded-lg bg-white [&_svg]:h-auto [&_svg]:w-full"
? "w-fit max-w-full overflow-hidden rounded-lg bg-white"
: "w-full overflow-hidden rounded-lg bg-white"
}
style={{ filter: inverted ? "invert(1) hue-rotate(180deg)" : undefined }}
dangerouslySetInnerHTML={{ __html: sanitizeSvg(result.svg) }}
data-testid="visual-svg"
/>
>
<SvgImage
svg={result.svg}
width={natural ?? undefined}
className={natural !== null ? "block h-auto max-w-full" : "block h-auto w-full"}
/>
</div>
<div className="mt-2 flex items-center justify-between gap-2">
<div className="text-xs font-medium uppercase tracking-wide text-muted-foreground">Figure</div>
<div className="flex items-center gap-1.5">
+19 -16
View File
@@ -7,6 +7,7 @@ import { fitGraphView, fitZoomFor, zoomedGraphView, type Viewport } from "@/comp
import { renderMermaid } from "@/components/mermaid-render";
import { MermaidError } from "@/components/mermaid-error";
import { Hint } from "@/components/ui/hint";
import { SvgImage } from "@/components/artifacts/svg-image";
/**
* SESSION-SCOPED OVERLAYS (owner wave, 2026-09-19): the "fullscreen"
@@ -269,22 +270,24 @@ export function MermaidOverlay({
: "transform 180ms ease-out, opacity 160ms ease-out",
}}
>
{/* data-lh-overlay-chart: globals.css pins the svg to the
wrapper's width (kills mermaid's inline max-width cap)
so the wrapper IS the natural-size box the fit math
centers. FIGURE MODE: a white stage (the figure's
backing law — models draw for a white page) with the
caller's invert filter riding it, exactly like the
in-card holder. */}
<div
data-lh-overlay-chart
className={cn(
"[&_svg]:h-auto [&_svg]:w-full",
rawSvg !== undefined && "bg-white",
)}
style={rawSvg !== undefined && inverted ? { filter: "invert(1) hue-rotate(180deg)" } : undefined}
dangerouslySetInnerHTML={{ __html: svg }}
/>
{/* Figures share the card's image boundary and white backing.
Mermaid keeps its inline renderer; globals.css removes
its max-width cap so it fills the natural-size box. */}
{rawSvg !== undefined ? (
<div
data-lh-overlay-chart
className="bg-white"
style={inverted ? { filter: "invert(1) hue-rotate(180deg)" } : undefined}
>
<SvgImage svg={svg} className="block h-auto w-full" />
</div>
) : (
<div
data-lh-overlay-chart
className="[&_svg]:h-auto [&_svg]:w-full"
dangerouslySetInnerHTML={{ __html: svg }}
/>
)}
</div>
<div className="pointer-events-none absolute inset-x-0 bottom-0 flex items-end justify-between p-2">
<span className="text-xs text-muted-foreground/60">Drag to pan · scroll to zoom</span>