Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(ui): render visual fences consistently across chat and documents

rubenluetke10-beepd056c4220fc1
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
index 837975e521..105cfa9b88 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.test.tsx
@@ -4,6 +4,36 @@ import { ChatMarkdown, mediaKind, normalizeMediaMarkup, safeMediaUrl } from "./C
afterEach(cleanup);
+describe("chat visual fences", () => {
+ it.each(["HTML", "htm", "text/html"])("previews %s instead of leaving source", async language => {
+ render(<ChatMarkdown text={`\`\`\`${language}\n<div>Visual card</div>\n\`\`\``} />);
+ expect((await screen.findByTestId("inline-html-frame")).getAttribute("srcdoc")).toContain("Visual card");
+ });
+
+ it.each(["SVG", "xml", "image/svg+xml", ""])("previews SVG with the %s label", async language => {
+ render(<ChatMarkdown text={`\`\`\`${language}\n<svg width="80" height="40"><rect width="80" height="40"/></svg>\n\`\`\``} />);
+ const image = await screen.findByTestId("inline-svg");
+ expect(decodeURIComponent(image.getAttribute("src")!)).toContain('xmlns="http://www.w3.org/2000/svg"');
+ });
+
+ it.each(["~~~", "````", "```"])("preserves HTML media during streaming in %s fences", async marker => {
+ const code = '<div><img src="https://example.test/chart.png"></div>';
+ const text = `${marker}html\n${code}\n`;
+ expect(normalizeMediaMarkup(text)).toBe(text);
+ expect(normalizeMediaMarkup(text + marker)).toBe(text + marker);
+ const { rerender } = render(<ChatMarkdown text={text} />);
+ expect((await screen.findByTestId("inline-html-frame")).getAttribute("srcdoc")).toContain(code);
+ rerender(<ChatMarkdown text={text + marker} />);
+ expect(screen.getByTestId("inline-html-frame").getAttribute("srcdoc")).toContain(code);
+ });
+
+ it("keeps JSON results and explicit text as code", () => {
+ const { container } = render(<ChatMarkdown text={'```json\n{"ok":true,"artifacts":[]}\n```\n\n```text\n<svg><rect/></svg>\n```'} />);
+ expect(container.querySelectorAll("pre")).toHaveLength(2);
+ expect(screen.queryByTestId("rendered-fence")).toBeNull();
+ });
+});
+
describe("shared chat media", () => {
it("renders every image and video in a mixed response", () => {
const { container } = render(<ChatMarkdown text={'![First](https://example.test/a.png)\n\n![Second](https://example.test/b.webp)\n\n[Clip](https://example.test/video.mp4)\n\n[Audio](https://example.test/audio.mp3)'} />);
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
index 28319d0732..af7318afe6 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatMarkdown.tsx
@@ -1,10 +1,11 @@
-import { Children, createContext, isValidElement, lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";
+import { Children, createContext, lazy, Suspense, useContext, useEffect, useMemo, useRef, useState } from "react";
import ReactMarkdown, { defaultUrlTransform, type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
import { AlertCircle, Download, Maximize2, X } from "lucide-react";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { openExternalUrl } from "@/lib/openExternal";
+import { readFence, visualFenceLanguage } from "@/lib/visualFence";
import * as Dialog from "@radix-ui/react-dialog";
const RenderedFence = lazy(() => import("@/components/outputs/RenderedFence").then(module => ({ default: module.RenderedFence })));
@@ -53,7 +54,25 @@ function assetKey(raw: string): string {
/** Recognize media tags without executing arbitrary model-authored HTML. */
export function normalizeMediaMarkup(text: string): string {
const attr = (markup: string, name: string) => markup.match(new RegExp(`\\b${name}\\s*=\\s*["']([^"']*)["']`, "i"))?.[1];
- const parts = text.split(/(```[\s\S]*?```)/);
+ // Protect CommonMark fences, including tilde fences and a still-streaming
+ // block. Rewriting an <img> inside HTML code corrupts the eventual preview.
+ const parts: string[] = [""];
+ let fence: string | null = null;
+ for (const line of text.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*?)(?:\r?\n)?$/.exec(line);
+ if (!fence && marker && !(marker[1][0] === "`" && marker[2].includes("`"))) {
+ fence = marker[1];
+ parts.push(line);
+ } else if (fence) {
+ parts[parts.length - 1] += line;
+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) {
+ fence = null;
+ parts.push("");
+ }
+ } else {
+ parts[parts.length - 1] += line;
+ }
+ }
return parts.map((part, i) => i % 2 ? part : part
.replace(/<(video|audio)\b([^>]*)>([\s\S]*?)<\/\1>/gi, (original, kind: string, head: string, body: string) => {
const source = attr(head, "src") ?? attr(body.match(/<source\b[^>]*>/i)?.[0] ?? "", "src");
@@ -138,10 +157,10 @@ const MARKDOWN_COMPONENTS: Components = {
}}>{children}</a>;
},
pre: ({ children, node: _node, ...props }) => {
- const child = Children.toArray(children)[0];
- if (isValidElement<{ className?: string; children?: unknown }>(child)) {
- const language = child.props.className?.match(/language-(html|svg)\b/)?.[1];
- if (language === "html" || language === "svg") return <Suspense fallback={<pre>{children}</pre>}><RenderedFence language={language} code={String(child.props.children ?? "").replace(/\n$/, "")} /></Suspense>;
+ const fence = readFence(children);
+ if (fence) {
+ const language = visualFenceLanguage(fence.language, fence.code);
+ if (language) return <Suspense fallback={<pre>{children}</pre>}><RenderedFence language={language} code={fence.code} /></Suspense>;
}
return <pre {...props}>{children}</pre>;
},
diff --git a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
index f150b1dfae..5443d5189d 100644
--- a/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
+++ b/jarvis/ui/web/frontend/src/components/outputs/MarkdownProse.tsx
@@ -16,7 +16,7 @@
* archive. The typography is the caller's — the reader passes its own
* classes, the output page the artifact standard's.
*/
-import { Children, isValidElement, useMemo, type ReactNode } from "react";
+import { useMemo } from "react";
import ReactMarkdown, { type Components } from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -27,6 +27,8 @@ import { CodeBlock } from "@/components/docs/CodeBlock";
import { RenderedFence } from "@/components/outputs/RenderedFence";
import { AsciiTableFence } from "@/components/outputs/AsciiTableFence";
import { fenceLooseAsciiTables, parseAsciiTable } from "@/lib/asciiTable";
+import { readFence, visualFenceLanguage } from "@/lib/visualFence";
+export { readFence } from "@/lib/visualFence";
/**
* Split a leading YAML front matter block (`---` … `---`) off a document.
@@ -64,30 +66,6 @@ export function resolveSiblingPath(fromPath: string, href: string): string | nul
/** Languages whose fences may hold an ASCII grid table rather than code. */
const PLAIN_FENCE_LANGUAGES = new Set(["", "text", "txt", "plain", "plaintext", "ascii"]);
-/**
- * Read the fence back out of a Markdown `<pre>`.
- *
- * The fence has to be handled HERE and not in the `code` component, because
- * react-markdown 9 dropped the `inline` prop: the same `code` component serves
- * inline `` `code` `` and block fences and cannot tell them apart. The parent
- * element can — a fence is the only `code` inside a `pre`. What arrives as
- * `children` is our own `code` component still unrendered, so its props are the
- * ORIGINAL ones: the `language-…` class and the raw fence text.
- *
- * A fence with no language tag lands here with `language: ""`. That case is
- * exactly what used to escape as a bare `<code>` with no `<pre>` around it,
- * which collapses every line break and renders a table as one run-on line.
- */
-export function readFence(children: ReactNode): { language: string; code: string } | null {
- const element = Children.toArray(children).find((child) => isValidElement(child));
- if (!isValidElement<{ className?: string; children?: ReactNode }>(element)) return null;
- const match = /language-([\w+#.-]+)/.exec(element.props.className ?? "");
- return {
- language: match ? match[1].toLowerCase() : "",
- code: String(element.props.children ?? "").replace(/\n$/, ""),
- };
-}
-
/**
* The typographic base every Markdown document shares: Tailwind's prose in
* both themes, links in the accent, inline code on a quiet chip, tables and
@@ -138,8 +116,9 @@ export function MarkdownProse({
const fence = readFence(children);
if (fence === null) return <pre>{children}</pre>;
const { language, code } = fence;
- if (language === "html" || language === "svg") {
- return <RenderedFence language={language} code={code} />;
+ const visualLanguage = visualFenceLanguage(language, code);
+ if (visualLanguage) {
+ return <RenderedFence language={visualLanguage} code={code} />;
}
if (PLAIN_FENCE_LANGUAGES.has(language)) {
const grid = parseAsciiTable(code);
diff --git a/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx
index e88c2d2a32..b46a4d7a02 100644
--- a/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.test.tsx
@@ -11,10 +11,17 @@ import {
INLINE_HTML_CSP,
INLINE_HTML_SIZE_MESSAGE,
wrapInlineHtml,
+ svgDataUrl,
} from "@/components/outputs/RenderedFence";
afterEach(() => cleanup());
+it("adds the standalone SVG namespace without replacing a declared namespace", () => {
+ expect(decodeURIComponent(svgDataUrl('<svg viewBox="0 0 10 10"><rect/></svg>'))).toContain('<svg xmlns="http://www.w3.org/2000/svg"');
+ const declared = '<svg xmlns="http://www.w3.org/2000/svg"><rect/></svg>';
+ expect(decodeURIComponent(svgDataUrl(declared)).split(",")[1]).toBe(declared);
+});
+
const SVG = '<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>';
describe("wrapInlineHtml", () => {
@@ -45,6 +52,10 @@ describe("wrapInlineHtml", () => {
});
describe("MarkdownProse fences", () => {
+ it.each(["SVG", "xml", "image/svg+xml", ""])("draws a complete SVG with label %s", language => {
+ render(<MarkdownProse slug="r" path="r.md" files={[]} text={`\`\`\`${language}\n${SVG}\n\`\`\``} />);
+ expect(screen.getByTestId("inline-svg")).toBeDefined();
+ });
it("draws an svg fence as a picture and an html fence in a sandboxed frame", () => {
render(
<MarkdownProse
diff --git a/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx
index 9728b9730c..76dc0e5084 100644
--- a/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx
+++ b/jarvis/ui/web/frontend/src/components/outputs/RenderedFence.tsx
@@ -104,7 +104,11 @@ export function wrapInlineHtml(html: string, theme: Theme, token: string): strin
/** An SVG snippet as an inert picture. */
export function svgDataUrl(svg: string): string {
- return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
+ // Inline HTML supplies this namespace implicitly; an SVG image document does not.
+ const document = svg.replace(/<svg(?=[\s>])[^>]*>/, root =>
+ /\sxmlns\s*=/.test(root) ? root : root.replace("<svg", '<svg xmlns="http://www.w3.org/2000/svg"'),
+ );
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(document)}`;
}
/** The sandboxed frame an inline HTML snippet runs in, sized to its content. */
diff --git a/jarvis/ui/web/frontend/src/lib/visualFence.ts b/jarvis/ui/web/frontend/src/lib/visualFence.ts
new file mode 100644
index 0000000000..33e5384959
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/lib/visualFence.ts
@@ -0,0 +1,23 @@
+import { Children, isValidElement, type ReactNode } from "react";
+
+/** Read block code without confusing it with inline code. */
+export function readFence(children: ReactNode): { language: string; code: string } | null {
+ const element = Children.toArray(children).find(child => isValidElement(child));
+ if (!isValidElement<{ className?: string; children?: ReactNode }>(element)) return null;
+ return {
+ language: /language-(\S+)/.exec(element.props.className ?? "")?.[1].toLowerCase() ?? "",
+ code: String(element.props.children ?? "").replace(/\n$/, ""),
+ };
+}
+
+/** Infer only complete visual roots; ordinary code and explicit text stay source. */
+export function visualFenceLanguage(language: string, code: string): "html" | "svg" | null {
+ const tag = language.toLowerCase();
+ if (["html", "htm", "text/html"].includes(tag)) return "html";
+ if (["svg", "image/svg+xml"].includes(tag)) return "svg";
+ if (tag !== "" && tag !== "xml") return null;
+ const source = code.trim().replace(/^<\?xml\s[^?]*\?>\s*/i, "");
+ if (/^<svg(?:\s[^>]*)?>[\s\S]*<\/svg>$/i.test(source)) return "svg";
+ if (tag === "" && /^(?:<!doctype html>\s*)?<html(?:\s[^>]*)?>[\s\S]*<\/html>$/i.test(source)) return "html";
+ return null;
+}