Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(markdown): preserve preview styles in standalone SVG exports
o_liushengf60e5daf35f8
diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 50a21d1f7..5ef5195e3 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -291,6 +291,7 @@ function MermaidBlock({ code, ...position }: { code: string } & SourcePositionPr[reactId],);const rootRef = useRef<HTMLDivElement>(null);+ const svgPreviewRef = useRef<HTMLDivElement>(null);const nearViewport = useNearViewport(rootRef);const renderedSourceRef = useRef("");const [svg, setSvg] = useState("");@@ -355,7 +356,7 @@ function MermaidBlock({ code, ...position }: { code: string } & SourcePositionPr<span>mermaid</span></span><div className="mermaid-block-actions">- <MermaidSvgActions svg={!error && !loading ? svg : ""} />+ <MermaidSvgActions svg={!error && !loading ? svg : ""} previewRef={svgPreviewRef} />{svg && !error ? (<TooltipButtontype="button"@@ -398,15 +399,18 @@ function MermaidBlock({ code, ...position }: { code: string } & SourcePositionPr<pre className="mermaid-source"><code>{code}</code></pre>- ) : svg ? (+ ) : null}+ {svg && !error ? (<div+ ref={svgPreviewRef}+ hidden={sourceVisible}className={`mermaid-svg${loading ? " refreshing" : ""}`}role="img"aria-label={t("chat.mermaidDiagram")}// Mermaid strict mode output is sanitized again in renderMermaidSvg.dangerouslySetInnerHTML={{ __html: svg }}/>- ) : (+ ) : !sourceVisible ? (<divclassName="mermaid-loading"role="status"@@ -416,7 +420,7 @@ function MermaidBlock({ code, ...position }: { code: string } & SourcePositionPr<span aria-hidden /><span aria-hidden /></div>- )}+ ) : null}</div></div>);diff --git a/apps/desktop/src/components/MermaidSvgActions.tsx b/apps/desktop/src/components/MermaidSvgActions.tsxindex 870663ddd..be742092e 100644--- a/apps/desktop/src/components/MermaidSvgActions.tsx+++ b/apps/desktop/src/components/MermaidSvgActions.tsx@@ -1,16 +1,25 @@+import type { RefObject } from "react";import { useTranslation } from "react-i18next";import { downloadMermaidSvg, standaloneMermaidSvg } from "../lib/mermaid-export";import { useAppStore } from "../stores/app-store";import { IconDownload, IconImage } from "./icons";import { TooltipButton } from "./ui";-export function MermaidSvgActions({ svg }: { svg: string }) {+export function MermaidSvgActions({ svg, previewRef }: {+ svg: string;+ previewRef: RefObject<HTMLDivElement | null>;+}) {const { t } = useTranslation();const showToast = useAppStore((state) => state.showToast);+ const exportSvg = () => {+ const preview = previewRef.current?.firstElementChild;+ if (!(preview instanceof SVGSVGElement)) throw new Error("Mermaid preview unavailable");+ return standaloneMermaidSvg(svg, preview);+ };const copy = async () => {if (!svg) return;try {- await navigator.clipboard.writeText(standaloneMermaidSvg(svg));+ await navigator.clipboard.writeText(exportSvg());showToast(t("chat.diagramSvgCopied"), { variant: "success" });} catch {showToast(t("chat.copyFailed"), { variant: "error" });@@ -19,7 +28,7 @@ export function MermaidSvgActions({ svg }: { svg: string }) {const download = () => {if (!svg) return;try {- downloadMermaidSvg(standaloneMermaidSvg(svg));+ downloadMermaidSvg(exportSvg());} catch {showToast(t("chat.diagramSvgExportFailed"), { variant: "error" });}diff --git a/apps/desktop/src/lib/mermaid-export.ts b/apps/desktop/src/lib/mermaid-export.tsindex 1d733a7d6..862bdce50 100644--- a/apps/desktop/src/lib/mermaid-export.ts+++ b/apps/desktop/src/lib/mermaid-export.ts@@ -1,20 +1,67 @@-/** Convert already-sanitized Mermaid output into a standalone SVG document. */-export function standaloneMermaidSvg(svg: string): string {+/** Freeze variable-dependent declarations using each preview element's context. */+function materializeVariables(root: Element, preview: SVGSVGElement): void {+ const exported = [root, ...root.querySelectorAll("*")];+ const rendered = [preview, ...preview.querySelectorAll("*")];+ if (exported.length !== rendered.length || exported.some((node, index) => node.localName !== rendered[index].localName)) {+ throw new Error("Mermaid preview does not match exported SVG");+ }+ const copies = new Map(rendered.map((node, index) => [node, exported[index]]));+ const hasVariable = (value: string) => /var\s*\(/i.test(value);+ const freeze = (renderedNode: Element, property: string) => {+ const copy = copies.get(renderedNode);+ if (copy instanceof SVGElement) {+ const value = getComputedStyle(renderedNode).getPropertyValue(property);+ copy.style.setProperty(property, value, "important");+ }+ };+ for (const [index, copy] of exported.entries()) {+ const original = rendered[index];+ if (copy instanceof SVGElement) {+ for (const property of Array.from(copy.style)) {+ if (hasVariable(copy.style.getPropertyValue(property))) freeze(original, property);+ }+ }+ for (const attribute of Array.from(copy.attributes)) {+ if (attribute.name !== "style" && hasVariable(attribute.value) && CSS.supports(attribute.name, attribute.value)) {+ const value = getComputedStyle(original).getPropertyValue(attribute.name);+ if (value) copy.setAttribute(attribute.name, value);+ else copy.removeAttribute(attribute.name);+ }+ }+ }+ for (const style of root.querySelectorAll("style")) {+ const sheet = new CSSStyleSheet();+ sheet.replaceSync(style.textContent ?? "");+ const visit = (rules: CSSRuleList) => {+ for (const rule of Array.from(rules)) {+ if (rule instanceof CSSStyleRule) {+ for (const property of Array.from(rule.style)) {+ if (!hasVariable(rule.style.getPropertyValue(property))) continue;+ const targets = [...preview.querySelectorAll(rule.selectorText)];+ if (preview.matches(rule.selectorText)) targets.unshift(preview);+ for (const target of targets) freeze(target, property);+ // The resolved inline declaration wins; no app token is needed.+ rule.style.removeProperty(property);+ }+ } else if ("cssRules" in rule) {+ visit((rule as CSSGroupingRule).cssRules);+ }+ }+ };+ visit(sheet.cssRules);+ style.textContent = Array.from(sheet.cssRules, (rule) => rule.cssText).join("\n");+ }+}++/** Serialize sanitized SVG without changing the live preview or relying on app CSS. */+export function standaloneMermaidSvg(svg: string, preview: SVGSVGElement): string {const document = new DOMParser().parseFromString(svg, "image/svg+xml");const root = document.documentElement;if (root.localName !== "svg" || document.querySelector("parsererror")) {throw new Error("Invalid Mermaid SVG");}root.setAttribute("xmlns", "http://www.w3.org/2000/svg");- // The preview inherits this app token; external viewers do not have it.- const font = getComputedStyle(window.document.documentElement).getPropertyValue("--font-sans").trim() || "sans-serif";- for (const style of root.querySelectorAll("style")) {- style.textContent = style.textContent?.replaceAll("var(--font-sans)", () => font) ?? "";- }- for (const element of [root, ...root.querySelectorAll("[style]")]) {- const style = element.getAttribute("style");- if (style) element.setAttribute("style", style.replaceAll("var(--font-sans)", () => font));- }+ materializeVariables(root, preview);// Mermaid uses a responsive percentage width in-app. Preserve its natural// dimensions when the SVG is opened as a file or imported into an editor.const viewBox = root.getAttribute("viewBox")?.trim().split(/[\s,]+/).map(Number);diff --git a/apps/desktop/src/styles/prose.css b/apps/desktop/src/styles/prose.cssindex 313021093..4b312eeb9 100644--- a/apps/desktop/src/styles/prose.css+++ b/apps/desktop/src/styles/prose.css@@ -637,6 +637,10 @@opacity: 0.72;}+.mermaid-svg[hidden] {+ display: none;+}+.mermaid-svg > svg {display: block;width: 100%;diff --git a/apps/desktop/test/fixtures/mermaid-export-runner.cjs b/apps/desktop/test/fixtures/mermaid-export-runner.cjsindex 656319208..0312d29fa 100644--- a/apps/desktop/test/fixtures/mermaid-export-runner.cjs+++ b/apps/desktop/test/fixtures/mermaid-export-runner.cjs@@ -14,7 +14,10 @@ app.whenReady().then(async () => {const wait = async (source) => {const deadline = Date.now() + 10_000;while (!await evaluate(source)) {- if (Date.now() > deadline) throw Error(`Timed out: ${source}`);+ if (Date.now() > deadline) {+ console.error(await evaluate('document.body.innerText'));+ throw Error(`Timed out: ${source}`);+ }await new Promise((resolve) => setTimeout(resolve, 20));}};@@ -31,14 +34,17 @@ app.whenReady().then(async () => {};await win.loadFile(join(dir, "index.html"));await wait("Boolean(window.mermaidFixture)");- const source = "```mermaid\nflowchart LR\n A[开始] --> B[完成]\n```";+ const diagramSource = "flowchart LR\n A[开始] --> B[完成]\n classDef appTheme fill:#123456,stroke:#abcdef,color:#dce6f0\n class A,B appTheme";+ const source = "```mermaid\n" + diagramSource + "\n```";await evaluate(`window.mermaidFixture.openReadme(${JSON.stringify(source)})`);- await wait('Boolean(document.querySelector(".mermaid-svg svg"))');+ await wait('Boolean(document.querySelector(".mermaid-svg svg, .mermaid-block-error"))');+ assert.equal(await evaluate('Boolean(document.querySelector(".mermaid-svg svg"))'), true, "Expected a rendered diagram");assert.equal(await evaluate('document.querySelector(".file-viewer-path").textContent'), "README.md");assert.equal(await evaluate('Boolean(document.querySelector(".file-viewer-markdown .mermaid-svg svg"))'), true);+ const previewBefore = await evaluate('document.querySelector(".mermaid-svg svg").outerHTML');await click("Copy diagram source");await wait('document.querySelector(".code-copy-btn.copied, .mermaid-action-btn.copied")');- assert.equal(clipboard.readText().replaceAll("\r\n", "\n"), "flowchart LR\n A[开始] --> B[完成]");+ assert.equal(clipboard.readText().replaceAll("\r\n", "\n"), diagramSource);await click("Copy diagram as SVG");await wait('window.mermaidFixture.toast()?.message === "SVG copied"');const svg = clipboard.readText().replaceAll("\r\n", "\n");@@ -46,8 +52,35 @@ app.whenReady().then(async () => {assert.match(svg, /xmlns="http:\/\/www.w3.org\/2000\/svg"/);assert.match(svg, /开始/);assert.match(svg, /完成/);- assert.doesNotMatch(svg, /var\(--font-sans\)/);- assert.match(svg, /Arial/);+ assert.doesNotMatch(svg, /var\s*\(/);+ assert.match(svg, /Courier New/);+ assert.doesNotMatch(svg, /Arial/);+ assert.equal(await evaluate('document.querySelector(".mermaid-svg svg").outerHTML'), previewBefore);+ assert.equal(await evaluate(`(async () => {+ const original = document.querySelector('.mermaid-svg svg');+ const rect = original.querySelector('.node rect');+ const label = original.querySelector('.node text');+ const expected = [getComputedStyle(rect).fill, getComputedStyle(rect).stroke, getComputedStyle(label).fontFamily, getComputedStyle(label).fill];+ if (expected[0] !== 'rgb(18, 52, 86)' || !expected[2].includes('Courier New')) throw Error('Preview did not apply container theme/font');+ const url = URL.createObjectURL(new Blob([${JSON.stringify(svg)}], {type:'image/svg+xml'}));+ const frame = document.createElement('iframe');+ const previousFocus = document.activeElement;+ frame.tabIndex = -1; frame.style.display = 'none';+ try {+ const loaded = new Promise((resolve, reject) => { frame.onload = resolve; frame.onerror = reject; });+ frame.src = url; document.body.append(frame); await loaded;+ const standalone = frame.contentDocument.documentElement;+ const exportedRect = standalone.querySelector('.node rect');+ const exportedLabel = standalone.querySelector('.node text');+ const computed = frame.contentWindow.getComputedStyle.bind(frame.contentWindow);+ const actual = [computed(exportedRect).fill, computed(exportedRect).stroke, computed(exportedLabel).fontFamily, computed(exportedLabel).fill];+ if (JSON.stringify(actual) !== JSON.stringify(expected)) throw Error('Standalone styles differ: ' + JSON.stringify({expected, actual}));+ return true;+ } finally {+ frame.remove(); URL.revokeObjectURL(url); window.focus();+ if (previousFocus instanceof HTMLElement) previousFocus.focus();+ }+ })()`), true);assert.equal(await evaluate(`(() => {const root = new DOMParser().parseFromString(${JSON.stringify(svg)}, 'image/svg+xml').documentElement;return root.localName === 'svg' && Number(root.getAttribute('width')) > 0 && Number(root.getAttribute('height')) > 0;@@ -62,9 +95,39 @@ app.whenReady().then(async () => {await click("Export diagram as SVG");await downloaded;assert.equal(readFileSync(join(dir, "diagram.svg"), "utf8"), svg);+ assert.equal(await evaluate('document.querySelector(".mermaid-svg svg").outerHTML'), previewBefore);await click("Show diagram source");await wait('Boolean(document.querySelector(".mermaid-source"))');+ assert.equal(await evaluate('getComputedStyle(document.querySelector(".mermaid-svg")).display'), "none");assert.equal(await evaluate('document.querySelector(\'button[aria-label="Copy diagram as SVG"]\').disabled'), false);+ const previousCopyToast = await evaluate('window.mermaidFixture.toast()?.id');+ clipboard.writeText("waiting for SVG copy from source view");+ await click("Copy diagram as SVG");+ await wait(`window.mermaidFixture.toast()?.id !== ${JSON.stringify(previousCopyToast)}`);+ assert.equal(clipboard.readText().replaceAll("\r\n", "\n"), svg);+ assert.equal(await evaluate(`(() => {+ const source = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 60" style="font-family:var(--font-sans)"><style>.node { fill:var(--paint, var(--missing, rgb(1, 2, 3))); }</style><g style="--paint:rgb(10, 20, 30)"><rect class="node" width="10" height="10"/></g><rect class="node" y="20" width="10" height="10"/><text y="50" fill="var(--absent, rgb(11, 22, 33))" style="color:var(--absent,var(--paint))">Hi</text></svg>';+ const host = document.createElement('div');+ host.style.setProperty('--paint', 'rgb(18, 52, 86)');+ host.style.setProperty('--font-sans', '"Courier New", monospace');+ host.innerHTML = source; document.body.append(host);+ const isolated = document.createElement('div');+ isolated.style.setProperty('--paint', 'rgb(255, 0, 0)');+ isolated.style.setProperty('--font-sans', 'serif');+ document.body.append(isolated);+ try {+ const live = host.querySelector('svg'); const before = live.outerHTML;+ const output = window.mermaidFixture.standaloneMermaidSvg(source, live);+ if (/var\\s*\\(/.test(output)) throw Error('An unresolved CSS variable escaped');+ if (live.outerHTML !== before) throw Error('The preview was mutated');+ isolated.innerHTML = output;+ const fills = [...isolated.querySelectorAll('rect')].map(node => getComputedStyle(node).fill);+ if (fills[0] !== 'rgb(10, 20, 30)' || fills[1] !== 'rgb(18, 52, 86)') throw Error('Per-node overrides or fallback failed: ' + fills);+ const text = getComputedStyle(isolated.querySelector('text'));+ if (text.fill !== 'rgb(11, 22, 33)' || text.color !== 'rgb(18, 52, 86)' || !text.fontFamily.includes('Courier New')) throw Error('Inline style, presentation attribute, or nested fallback failed');+ return true;+ } finally { isolated.remove(); host.remove(); }+ })()`), true);// Source/theme changes must export the newly rendered SVG, even in source view.await evaluate(`window.mermaidFixture.render(${JSON.stringify(source.replace("完成", "新版"))}, "zh-CN", "dark")`);await wait('document.querySelector(".mermaid-svg svg")?.textContent.includes("新版")');diff --git a/apps/desktop/test/fixtures/mermaid-export.jsx b/apps/desktop/test/fixtures/mermaid-export.jsxindex 24354dbab..a0f09f01e 100644--- a/apps/desktop/test/fixtures/mermaid-export.jsx+++ b/apps/desktop/test/fixtures/mermaid-export.jsx@@ -8,6 +8,11 @@ import { FilesTab } from "../../src/components/workpanel/FilesTab";import { Markdown } from "../../src/components/Markdown";import { useAppStore } from "../../src/stores/app-store";import { standaloneMermaidSvg } from "../../src/lib/mermaid-export";+import "../../src/styles/prose.css";++const previewStyle = {+ "--font-sans": '"Courier New", monospace',+};const i18n = createInstance();await i18n.init({ lng: "en", resources: Object.fromEntries(@@ -29,13 +34,13 @@ window.mermaidFixture = {document.documentElement.dataset.theme = "light";document.documentElement.style.setProperty("--font-sans", '\"Arial\", sans-serif');useAppStore.setState({ workspace: { path: "/fixture", name: "fixture" }, workPanelFileRequest: { seq: 1, path: "README.md" } });- flushSync(() => root.render(<I18nextProvider i18n={i18n}><FilesTab /></I18nextProvider>));+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><section style={previewStyle}><FilesTab /></section></I18nextProvider>));},async render(source, locale = "en", theme = "light") {document.documentElement.dataset.theme = theme;document.documentElement.style.setProperty("--font-sans", '"Arial", sans-serif');await i18n.changeLanguage(locale);- flushSync(() => root.render(<I18nextProvider i18n={i18n}><Markdown source={source} /></I18nextProvider>));+ flushSync(() => root.render(<I18nextProvider i18n={i18n}><section style={previewStyle}><Markdown source={source} /></section></I18nextProvider>));},toast: () => useAppStore.getState().toasts.at(-1),};diff --git a/apps/desktop/test/mermaid-export-user-path.test.mjs b/apps/desktop/test/mermaid-export-user-path.test.mjsindex 06f1996f9..5647491c8 100644--- a/apps/desktop/test/mermaid-export-user-path.test.mjs+++ b/apps/desktop/test/mermaid-export-user-path.test.mjs@@ -21,7 +21,7 @@ test("Mermaid preview copies standalone SVG and downloads the same diagram", {define: { "import.meta.env.DEV": "false", "process.env.NODE_ENV": '"production"' },loader: { ".woff2": "file", ".woff": "file", ".ttf": "file" },});- await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><link rel="stylesheet" href="renderer.css"><div id="root"></div><script type="module" src="renderer.js"></script>');+ await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; frame-src blob:"><link rel="stylesheet" href="renderer.css"><div id="root"></div><script type="module" src="renderer.js"></script>');const env = { ...process.env, PI_MERMAID_TEST_DIR: temp };delete env.ELECTRON_RUN_AS_NODE;const child = spawn(resolveElectronBinary(root).electronBinary,diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 486f17b32..10282a09c 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2270,8 +2270,12 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shiand **Export diagram as SVG** downloads `diagram.svg` with the same bytes.Both actions are disabled while rendering or when no valid SVG is available;failures show localized feedback. Export preserves the sanitized SVG,- viewBox dimensions, and resolved UI font without rerunning Mermaid or- requiring new host permissions. These actions also appear in host Markdown+ viewBox dimensions, and the preview's resolved fonts and colors. Variable-+ dependent CSS rules, inline styles, and presentation attributes are frozen+ from each rendered element's computed style, including nested fallbacks and+ subtree overrides. Only the detached export is modified. Source view hides+ but retains the SVG so copying there uses the same style context, without+ rerunning Mermaid or requiring new host permissions. These actions also appear in host Markdownfile previews, including README files. Light/dark theme changes re-render the SVG. Thinking prose deliberately keeps `mermaid` fences assource code so a collapsed reasoning trace cannot start diagram layout.- **Syntax highlighting**: Shiki singleton with the JavaScript regex enginediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0b032dfeb..7bcf24a29 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7681,7 +7681,13 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.and switch between light and dark themes.3. Copy SVG and export SVG; parse the clipboard text and downloaded fileas standalone SVG, verify the diagram labels, explicit dimensions and- resolved UI font, then repeat in a README preview. Deny clipboard access+ resolved UI font, then repeat in a README preview. Give the preview a+ different font from the document root and themed node colors; open+ exported SVG in an isolated SVG document and compare computed fonts and+ colors. In SVG export fixtures, verify app CSS variables, per-node+ overrides, nested fallbacks, inline styles and presentation attributes,+ export from source+ view, and that the live SVG remains unchanged. Deny clipboard accessand force download setup failure; verify localized error feedback.Repeat while rendering and with invalid input: SVG actions stay disabled.Switch diagrams/themes and confirm subsequent exports use the new SVG.