Skip to content

CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.

fix(cad): give the three files one way to read SVG out of a reply

codingFeng101bae2178e074c
diff --git a/client/workspaces/cad/CadWorkspace.tsx b/client/workspaces/cad/CadWorkspace.tsx
index 37f488c..121c5fd 100644
--- a/client/workspaces/cad/CadWorkspace.tsx
+++ b/client/workspaces/cad/CadWorkspace.tsx
@@ -11,6 +11,12 @@ import {
type PanelImperativeHandle,
} from "@/shared/ui/resizable";
import { CAD_SYSTEM_PROMPT } from "@/workspaces/cad/lib/prompts";
+import {
+ applyStringEdits,
+ extractLatestSvgFromText,
+ normalizeSvgMarkup,
+} from "@/workspaces/cad/lib/svg-markup";
+import { hasDrawableSvgContent, isValidSvgMarkup } from "@/workspaces/cad/lib/svg-dom";
import type { ChatMessage } from "@/ai/client";
import { generateImage } from "@/ai/client";
import { CadCanvas } from "@/workspaces/cad/canvas/CadCanvas";
@@ -50,113 +56,6 @@ const tryParseJson = (text: string) => {
}
};
-const decodeBasicHtmlEntities = (text: string) =>
- String(text || "")
- .replace(/&lt;/gi, "<")
- .replace(/&gt;/gi, ">")
- .replace(/&quot;/gi, '"')
- .replace(/&#39;|&apos;/gi, "'")
- .replace(/&amp;/gi, "&");
-
-const normalizeSvgMarkup = (text: string) => {
- const original = String(text || "").trim();
- let raw = original;
- if (!/<svg[\s/>]/i.test(raw) && /&lt;\s*svg[\s\S]*&gt;/i.test(raw)) {
- raw = decodeBasicHtmlEntities(raw).trim();
- }
- if (!raw) return "";
- const start = raw.search(/<svg[\s/>]/i);
- if (start < 0) return "";
- const tail = raw.slice(start);
- const end = tail.toLowerCase().lastIndexOf("</svg>");
- if (end >= 0) return tail.slice(0, end + "</svg>".length).trim();
- return tail.trim();
-};
-
-const isValidSvgMarkup = (text: string) => {
- const normalized = normalizeSvgMarkup(text);
- if (!normalized) return false;
- if (typeof DOMParser === "undefined") return /^<svg[\s/>]/i.test(normalized);
- try {
- const doc = new DOMParser().parseFromString(normalized, "image/svg+xml");
- if (doc.querySelector("parsererror")) return false;
- return String(doc.documentElement?.nodeName || "").toLowerCase() === "svg";
- } catch {
- return false;
- }
-};
-
-const hasDrawableSvgContent = (text: string) => {
- const normalized = normalizeSvgMarkup(text);
- if (!normalized) return false;
- if (typeof DOMParser === "undefined") return true;
- try {
- const doc = new DOMParser().parseFromString(normalized, "image/svg+xml");
- if (doc.querySelector("parsererror")) return false;
- const root = doc.documentElement;
- if (!root || String(root.nodeName || "").toLowerCase() !== "svg") return false;
- const drawable = root.querySelector(
- "path,rect,circle,ellipse,line,polyline,polygon,text,image,use,foreignObject",
- );
- return !!drawable;
- } catch {
- return false;
- }
-};
-
-function applyStringEdits(source: string, edits: { search: string; replace: string }[]) {
- if (!Array.isArray(edits) || edits.length === 0) throw new Error("Empty patch edits");
- let out = source;
- for (const edit of edits) {
- if (!edit || typeof edit.search !== "string" || typeof edit.replace !== "string") {
- throw new Error("Invalid patch edit item");
- }
- if (!edit.search) throw new Error("Empty search pattern in patch edit");
- if (!out.includes(edit.search)) throw new Error("Search pattern not found in current content");
- out = out.replace(edit.search, edit.replace);
- }
- return out;
-}
-
-const extractLatestSvgFromText = (text: string) => {
- const raw = String(text || "");
- let latest = "";
-
- const svgFence = /```svg\s*([\s\S]*?)```/gi;
- let fenceMatch: RegExpExecArray | null;
- while ((fenceMatch = svgFence.exec(raw))) {
- const normalized = normalizeSvgMarkup(String(fenceMatch[1] || ""));
- if (normalized) latest = normalized;
- }
-
- if (latest) return latest;
-
- const rawSvg = /<svg[\s\S]*?<\/svg>/gi;
- let svgMatch: RegExpExecArray | null;
- while ((svgMatch = rawSvg.exec(raw))) {
- const normalized = normalizeSvgMarkup(String(svgMatch[0] || ""));
- if (normalized) latest = normalized;
- }
-
- if (latest) return latest;
-
- const jsonFence = /```json\s*([\s\S]*?)```/gi;
- let jsonMatch: RegExpExecArray | null;
- while ((jsonMatch = jsonFence.exec(raw))) {
- try {
- const parsed = JSON.parse(String(jsonMatch[1] || ""));
- const normalized = normalizeSvgMarkup(String(parsed?.full || ""));
- if (parsed?.type === "cad_patch" && parsed?.target === "2d_svg" && normalized) {
- latest = normalized;
- }
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
- }
-
- return latest;
-};
-
type CadRenderItem = { title: string; url: string };
const normalizeCadRenderItems = (
diff --git a/client/workspaces/cad/canvas/CadCanvas.tsx b/client/workspaces/cad/canvas/CadCanvas.tsx
index e5a9547..c92e0d8 100644
--- a/client/workspaces/cad/canvas/CadCanvas.tsx
+++ b/client/workspaces/cad/canvas/CadCanvas.tsx
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useLatestRef } from "@/shared/lib/use-latest-ref";
+import { normalizeSvgMarkup } from "@/workspaces/cad/lib/svg-markup";
import { Loader2, MessageSquarePlus, Box, Image as ImageIcon, Table2, Download } from 'lucide-react';
import {
ContextMenu,
@@ -33,17 +34,6 @@ const EMPTY_SENTINEL = "__EMPTY_SVG__";
const ENABLE_EDITOR_AUTOSYNC = false;
const SVG_EDITOR_IFRAME_PATH = "/svg-editor.html";
-const normalizeSvgMarkup = (text: string) => {
- const raw = String(text || "").trim();
- if (!raw) return "";
- const start = raw.search(/<svg[\s/>]/i);
- if (start < 0) return "";
- const tail = raw.slice(start);
- const end = tail.toLowerCase().lastIndexOf("</svg>");
- if (end >= 0) return tail.slice(0, end + "</svg>".length).trim();
- return tail.trim();
-};
-
const unwrapMarkdownStrong = (text: string) => {
let out = String(text || "").trim();
for (let i = 0; i < 3; i += 1) {
diff --git a/client/workspaces/cad/chat/ChatPanel.tsx b/client/workspaces/cad/chat/ChatPanel.tsx
index b7a6b4b..31dddff 100644
--- a/client/workspaces/cad/chat/ChatPanel.tsx
+++ b/client/workspaces/cad/chat/ChatPanel.tsx
@@ -23,6 +23,13 @@ import {
CAD_SVG_FLOW_REPLACE_AGENT_PROMPT,
} from '@/workspaces/cad/lib/agents';
import { getCadRenderFallbackTitle, getCadRenderSlotTitles } from "@/workspaces/cad/lib/render-titles";
+import {
+ extractCadPatchFullSvg,
+ extractRawSvg,
+ extractSvgFence,
+ hasCadPatchPayload,
+ normalizeSvgMarkup,
+} from "@/workspaces/cad/lib/svg-markup";
import { t, useUiLanguage } from "@/shared/i18n";
import { toast } from "sonner";
import {
@@ -509,131 +516,6 @@ export function ChatPanel({
return !!r.ok;
};
- const normalizeSvgMarkup = (text: string): string => {
- const decodeBasicHtmlEntities = (value: string) =>
- String(value || "")
- .replace(/&lt;/gi, "<")
- .replace(/&gt;/gi, ">")
- .replace(/&quot;/gi, '"')
- .replace(/&#39;|&apos;/gi, "'")
- .replace(/&amp;/gi, "&");
-
- const original = String(text || "").trim();
- const raw = !/<svg[\s/>]/i.test(original) && /&lt;\s*svg[\s\S]*&gt;/i.test(original)
- ? decodeBasicHtmlEntities(original).trim()
- : original;
- if (!raw) return "";
- const start = raw.search(/<svg[\s/>]/i);
- if (start < 0) return "";
- const tail = raw.slice(start);
- const end = tail.toLowerCase().lastIndexOf("</svg>");
- if (end >= 0) return tail.slice(0, end + "</svg>".length).trim();
- return tail.trim();
- };
-
- const extractSvgCodeBlock = (text: string): string => {
- const raw = String(text || "");
- const re = /```svg\s*([\s\S]*?)```/gi;
- let m: RegExpExecArray | null;
- let last = "";
- while ((m = re.exec(raw))) {
- const candidate = normalizeSvgMarkup(m?.[1] || "");
- if (candidate) last = candidate;
- }
- return last;
- };
-
- const extractRawSvgBlock = (text: string): string => {
- const raw = String(text || "");
- const re = /<svg[\s\S]*?<\/svg>/gi;
- let m: RegExpExecArray | null;
- let last = "";
- while ((m = re.exec(raw))) {
- const candidate = normalizeSvgMarkup(m?.[0] || "");
- if (candidate) last = candidate;
- }
- return last;
- };
-
- const extractReplaceSvgFromCadPatchText = (text: string): string => {
- const raw = String(text || "");
- const jsonRegex = /```json\s*([\s\S]*?)```/g;
- let m: RegExpExecArray | null;
- while ((m = jsonRegex.exec(raw))) {
- const jsonText = String(m[1] || "").trim();
- if (!jsonText) continue;
- try {
- const parsed = JSON.parse(jsonText);
- const full = normalizeSvgMarkup(parsed?.full || "");
- if (parsed?.type === "cad_patch" && parsed?.target === "2d_svg" && parsed?.mode === "replace" && full) {
- return full;
- }
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
- }
- const trimmed = raw.trim();
- if (trimmed.startsWith("{")) {
- try {
- const parsed = JSON.parse(trimmed);
- const full = normalizeSvgMarkup(parsed?.full || "");
- if (parsed?.type === "cad_patch" && parsed?.target === "2d_svg" && parsed?.mode === "replace" && full) {
- return full;
- }
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
- }
- return "";
- };
-
- const hasCadPatchPayloadInText = (text: string): boolean => {
- const raw = String(text || "");
- if (!raw.trim()) return false;
-
- const isCadPatchPayload = (value: any) =>
- value &&
- typeof value === "object" &&
- String(value?.type || "").trim().toLowerCase() === "cad_patch" &&
- String(value?.target || "").trim().toLowerCase() === "2d_svg";
-
- const jsonRegex = /```json\s*([\s\S]*?)```/g;
- let jm: RegExpExecArray | null;
- while ((jm = jsonRegex.exec(raw))) {
- const jsonText = String(jm[1] || "").trim();
- if (!jsonText) continue;
- try {
- const parsed = JSON.parse(jsonText);
- if (isCadPatchPayload(parsed)) return true;
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
- }
-
- const trimmed = raw.trim();
- if (trimmed.startsWith("{")) {
- try {
- const parsed = JSON.parse(trimmed);
- if (isCadPatchPayload(parsed)) return true;
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
- }
-
- const start = raw.indexOf("{");
- const end = raw.lastIndexOf("}");
- if (start >= 0 && end > start) {
- try {
- const parsed = JSON.parse(raw.slice(start, end + 1));
- if (isCadPatchPayload(parsed)) return true;
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
- }
-
- return /"type"\s*:\s*"cad_patch"/i.test(raw) && /"target"\s*:\s*"2d_svg"/i.test(raw);
- };
-
const handleAssistantResponse = async (fullResponse: string) => {
if (!fullResponse) return { flowPatchFound: false, flowRetryError: null as string | null };
@@ -645,16 +527,16 @@ export function ChatPanel({
}
if (workspaceId === "cad") {
- const hasCadPatchPayload = hasCadPatchPayloadInText(fullResponse);
+ const hasPatch = hasCadPatchPayload(fullResponse);
const svgCandidate =
- extractReplaceSvgFromCadPatchText(fullResponse) ||
- extractSvgCodeBlock(fullResponse) ||
- extractRawSvgBlock(fullResponse);
- if (!hasCadPatchPayload && svgCandidate) {
+ extractCadPatchFullSvg(fullResponse) ||
+ extractSvgFence(fullResponse) ||
+ extractRawSvg(fullResponse);
+ if (!hasPatch && svgCandidate) {
await runCodeAction(svgCandidate, "cad");
}
} else {
- const svgText = extractSvgCodeBlock(fullResponse);
+ const svgText = extractSvgFence(fullResponse);
if (svgText) {
await runCodeAction(svgText, "cad");
}
@@ -1415,7 +1297,7 @@ export function ChatPanel({
}
if (!cadPatchFound) {
- const svgText = extractSvgCodeBlock(toolFull) || extractRawSvgBlock(toolFull);
+ const svgText = extractSvgFence(toolFull) || extractRawSvg(toolFull);
if (svgText) {
const r = await runCodeAction(svgText, "cad");
if (r.ok) {
@@ -1427,7 +1309,7 @@ export function ChatPanel({
}
if (!producedHasSvg2d && !cadPatchFound) {
- const fallbackSvg = extractReplaceSvgFromCadPatchText(toolFull) || extractSvgCodeBlock(toolFull) || extractRawSvgBlock(toolFull);
+ const fallbackSvg = extractCadPatchFullSvg(toolFull) || extractSvgFence(toolFull) || extractRawSvg(toolFull);
if (fallbackSvg) {
const r = await runCodeAction(fallbackSvg, "cad");
if (r.ok) {
@@ -1506,7 +1388,7 @@ export function ChatPanel({
if (producedHasSvg2d && !hasSvgFence && !hasCadPatchJson) {
const svgForDisplay = normalizeSvgMarkup(appliedSvg)
? normalizeSvgMarkup(appliedSvg)
- : extractReplaceSvgFromCadPatchText(cadSvgToolFull) || extractRawSvgBlock(cadSvgToolFull);
+ : extractCadPatchFullSvg(cadSvgToolFull) || extractRawSvg(cadSvgToolFull);
if (svgForDisplay) assistantOutput = `${assistantOutput}\n\n\`\`\`svg\n${svgForDisplay}\n\`\`\``;
}
if (guide) updateLastAssistant(`${assistantOutput}\n\n${guide}`);
@@ -1545,12 +1427,12 @@ export function ChatPanel({
}
let producedHasSvg2d = false;
- const hasCadPatchPayload = hasCadPatchPayloadInText(routedFull);
+ const hasPatch = hasCadPatchPayload(routedFull);
const svgCandidate =
- extractReplaceSvgFromCadPatchText(routedFull) ||
- extractSvgCodeBlock(routedFull) ||
- extractRawSvgBlock(routedFull);
- if (!hasCadPatchPayload && svgCandidate) {
+ extractCadPatchFullSvg(routedFull) ||
+ extractSvgFence(routedFull) ||
+ extractRawSvg(routedFull);
+ if (!hasPatch && svgCandidate) {
const svgResult = await runCodeAction(svgCandidate, "cad");
producedHasSvg2d = !!svgResult.ok;
}
@@ -2082,7 +1964,7 @@ export function ChatPanel({
}
if (!cadPatchFound) {
- const svgText = extractSvgCodeBlock(toolFull) || extractRawSvgBlock(toolFull);
+ const svgText = extractSvgFence(toolFull) || extractRawSvg(toolFull);
if (svgText) {
const r = await runCodeAction(svgText, "cad");
if (r.ok) {
@@ -2094,7 +1976,7 @@ export function ChatPanel({
}
if (!producedHasSvg2d && !cadPatchFound) {
- const fallbackSvg = extractReplaceSvgFromCadPatchText(toolFull) || extractSvgCodeBlock(toolFull) || extractRawSvgBlock(toolFull);
+ const fallbackSvg = extractCadPatchFullSvg(toolFull) || extractSvgFence(toolFull) || extractRawSvg(toolFull);
if (fallbackSvg) {
const r = await runCodeAction(fallbackSvg, "cad");
if (r.ok) {
@@ -2173,7 +2055,7 @@ export function ChatPanel({
if (producedHasSvg2d && !hasSvgFence && !hasCadPatchJson) {
const svgForDisplay = normalizeSvgMarkup(appliedSvg)
? normalizeSvgMarkup(appliedSvg)
- : extractReplaceSvgFromCadPatchText(cadSvgToolFull) || extractRawSvgBlock(cadSvgToolFull);
+ : extractCadPatchFullSvg(cadSvgToolFull) || extractRawSvg(cadSvgToolFull);
if (svgForDisplay) assistantOutput = `${assistantOutput}\n\n\`\`\`svg\n${svgForDisplay}\n\`\`\``;
}
if (guide) updateLastAssistant(`${assistantOutput}\n\n${guide}`);
@@ -2212,12 +2094,12 @@ export function ChatPanel({
}
let producedHasSvg2d = false;
- const hasCadPatchPayload = hasCadPatchPayloadInText(routedFull);
+ const hasPatch = hasCadPatchPayload(routedFull);
const svgCandidate =
- extractReplaceSvgFromCadPatchText(routedFull) ||
- extractSvgCodeBlock(routedFull) ||
- extractRawSvgBlock(routedFull);
- if (!hasCadPatchPayload && svgCandidate) {
+ extractCadPatchFullSvg(routedFull) ||
+ extractSvgFence(routedFull) ||
+ extractRawSvg(routedFull);
+ if (!hasPatch && svgCandidate) {
const svgResult = await runCodeAction(svgCandidate, "cad");
producedHasSvg2d = !!svgResult.ok;
}
diff --git a/client/workspaces/cad/lib/svg-dom.ts b/client/workspaces/cad/lib/svg-dom.ts
new file mode 100644
index 0000000..8d10700
--- /dev/null
+++ b/client/workspaces/cad/lib/svg-dom.ts
@@ -0,0 +1,43 @@
+import { normalizeSvgMarkup } from "@/workspaces/cad/lib/svg-markup";
+
+/**
+ * The two questions that need a real parser: is this SVG the browser will
+ * accept, and does it draw anything?
+ *
+ * Both degrade to a cheap check where there is no DOMParser, so the same
+ * code runs during a server render. They are exercised in the browser rather
+ * than by the test runner for that reason.
+ */
+
+function parse(markup: string): Document | null {
+ try {
+ const doc = new DOMParser().parseFromString(markup, "image/svg+xml");
+ return doc.querySelector("parsererror") ? null : doc;
+ } catch {
+ // A parser that throws is the same answer as one that reports an error.
+ return null;
+ }
+}
+
+export function isValidSvgMarkup(text: string): boolean {
+ const normalized = normalizeSvgMarkup(text);
+ if (!normalized) return false;
+ if (typeof DOMParser === "undefined") return /^<svg[\s/>]/i.test(normalized);
+
+ const doc = parse(normalized);
+ return String(doc?.documentElement?.nodeName || "").toLowerCase() === "svg";
+}
+
+/** Elements that put something on screen; a document of only defs draws nothing. */
+const DRAWABLE = "path,rect,circle,ellipse,line,polyline,polygon,text,image,use,foreignObject";
+
+export function hasDrawableSvgContent(text: string): boolean {
+ const normalized = normalizeSvgMarkup(text);
+ if (!normalized) return false;
+ if (typeof DOMParser === "undefined") return true;
+
+ const doc = parse(normalized);
+ const root = doc?.documentElement;
+ if (!root || String(root.nodeName || "").toLowerCase() !== "svg") return false;
+ return !!root.querySelector(DRAWABLE);
+}
diff --git a/client/workspaces/cad/lib/svg-markup.ts b/client/workspaces/cad/lib/svg-markup.ts
new file mode 100644
index 0000000..f1866af
--- /dev/null
+++ b/client/workspaces/cad/lib/svg-markup.ts
@@ -0,0 +1,171 @@
+/**
+ * Getting usable SVG out of a model reply.
+ *
+ * The CAD agent answers with SVG in several shapes -- a ```svg fence, bare
+ * markup in prose, or the `full` field of a cad_patch payload -- and
+ * sometimes with its angle brackets HTML-escaped. Everything that touches
+ * that markup goes through here, so the workspace, the canvas and the chat
+ * panel cannot disagree about what a given reply means.
+ */
+
+const ENTITIES: Array<[RegExp, string]> = [
+ [/&lt;/gi, "<"],
+ [/&gt;/gi, ">"],
+ [/&quot;/gi, '"'],
+ [/&#39;|&apos;/gi, "'"],
+ // Ampersand last: decoding it first would corrupt the entities above.
+ [/&amp;/gi, "&"],
+];
+
+export function decodeBasicHtmlEntities(text: string): string {
+ return ENTITIES.reduce((out, [pattern, char]) => out.replace(pattern, char), String(text || ""));
+}
+
+/**
+ * Trims a reply down to the SVG document inside it, or "" if there is none.
+ *
+ * Markup that arrived HTML-escaped is decoded first: a model that writes
+ * `&lt;svg&gt;` means the same thing as one that writes `<svg>`, and treating
+ * the escaped form as "no SVG here" silently drops the drawing.
+ */
+export function normalizeSvgMarkup(text: string): string {
+ const original = String(text || "").trim();
+ const raw =
+ !/<svg[\s/>]/i.test(original) && /&lt;\s*svg[\s\S]*&gt;/i.test(original)
+ ? decodeBasicHtmlEntities(original).trim()
+ : original;
+ if (!raw) return "";
+
+ const start = raw.search(/<svg[\s/>]/i);
+ if (start < 0) return "";
+
+ const tail = raw.slice(start);
+ const end = tail.toLowerCase().lastIndexOf("</svg>");
+ // A stream cut off mid-document still gives the caller what arrived.
+ return end >= 0 ? tail.slice(0, end + "</svg>".length).trim() : tail.trim();
+}
+
+/** The last ```svg fence in the reply, normalised. */
+export function extractSvgFence(text: string): string {
+ return lastMatch(String(text || ""), /```svg\s*([\s\S]*?)```/gi, (m) => m[1]);
+}
+
+/** The last bare `<svg>…</svg>` in the reply, normalised. */
+export function extractRawSvg(text: string): string {
+ return lastMatch(String(text || ""), /<svg[\s\S]*?<\/svg>/gi, (m) => m[0]);
+}
+
+function lastMatch(raw: string, pattern: RegExp, pick: (m: RegExpExecArray) => string): string {
+ let last = "";
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(raw))) {
+ const candidate = normalizeSvgMarkup(pick(match) || "");
+ if (candidate) last = candidate;
+ }
+ return last;
+}
+
+const isCadPatch = (value: unknown, mode?: string): boolean => {
+ const record = value as Record<string, unknown> | null;
+ if (!record || typeof record !== "object") return false;
+ if (String(record.type || "").trim().toLowerCase() !== "cad_patch") return false;
+ if (String(record.target || "").trim().toLowerCase() !== "2d_svg") return false;
+ return mode ? String(record.mode || "").trim().toLowerCase() === mode : true;
+};
+
+/** The `full` SVG of a whole-document cad_patch, if the reply carries one. */
+export function extractCadPatchFullSvg(text: string): string {
+ for (const candidate of jsonCandidates(String(text || ""))) {
+ if (!isCadPatch(candidate, "replace")) continue;
+ const full = normalizeSvgMarkup(String((candidate as { full?: unknown }).full || ""));
+ if (full) return full;
+ }
+ return "";
+}
+
+/** Whether the reply contains a cad_patch at all, in any of its shapes. */
+export function hasCadPatchPayload(text: string): boolean {
+ const raw = String(text || "");
+ if (!raw.trim()) return false;
+ if (jsonCandidates(raw).some((value) => isCadPatch(value))) return true;
+
+ // A payload split across a truncated stream still names itself.
+ return /"type"\s*:\s*"cad_patch"/i.test(raw) && /"target"\s*:\s*"2d_svg"/i.test(raw);
+}
+
+/**
+ * Every JSON value the reply might be hiding, in the order worth trying:
+ * each ```json fence, then the whole reply, then the outermost brace pair.
+ */
+export function jsonCandidates(text: string): unknown[] {
+ const raw = String(text || "");
+ const out: unknown[] = [];
+
+ const fence = /```json\s*([\s\S]*?)```/gi;
+ let match: RegExpExecArray | null;
+ while ((match = fence.exec(raw))) {
+ const parsed = tryParse(String(match[1] || "").trim());
+ if (parsed !== undefined) out.push(parsed);
+ }
+
+ const trimmed = raw.trim();
+ if (trimmed.startsWith("{")) {
+ const parsed = tryParse(trimmed);
+ if (parsed !== undefined) out.push(parsed);
+ }
+
+ const start = raw.indexOf("{");
+ const end = raw.lastIndexOf("}");
+ if (start >= 0 && end > start) {
+ const parsed = tryParse(raw.slice(start, end + 1));
+ if (parsed !== undefined) out.push(parsed);
+ }
+
+ return out;
+}
+
+function tryParse(text: string): unknown {
+ if (!text) return undefined;
+ try {
+ return JSON.parse(text);
+ } catch {
+ // Not JSON; the caller moves on to the next candidate.
+ return undefined;
+ }
+}
+
+/**
+ * The newest drawing in a reply, preferring the most explicit form: a ```svg
+ * fence, then a cad_patch's full document, then bare markup in prose.
+ *
+ * Scanning for bare markup has to come last. Inside a JSON payload the SVG
+ * is a string, so a raw `<svg` match there returns it with the JSON escaping
+ * still in it -- markup no parser will accept.
+ */
+export function extractLatestSvgFromText(text: string): string {
+ return extractSvgFence(text) || extractCadPatchFullSvg(text) || extractRawSvg(text);
+}
+
+/**
+ * Applies a patch's search/replace pairs in order.
+ *
+ * Every failure throws rather than skipping: a patch that half-applied would
+ * leave a drawing neither the user nor the model can reason about.
+ */
+export function applyStringEdits(
+ source: string,
+ edits: { search: string; replace: string }[],
+): string {
+ if (!Array.isArray(edits) || edits.length === 0) throw new Error("Empty patch edits");
+
+ let out = source;
+ for (const edit of edits) {
+ if (!edit || typeof edit.search !== "string" || typeof edit.replace !== "string") {
+ throw new Error("Invalid patch edit item");
+ }
+ if (!edit.search) throw new Error("Empty search pattern in patch edit");
+ if (!out.includes(edit.search)) throw new Error("Search pattern not found in current content");
+ out = out.replace(edit.search, edit.replace);
+ }
+ return out;
+}
diff --git a/tests/cad-svg-markup.test.ts b/tests/cad-svg-markup.test.ts
new file mode 100644
index 0000000..a5673eb
--- /dev/null
+++ b/tests/cad-svg-markup.test.ts
@@ -0,0 +1,164 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ applyStringEdits,
+ decodeBasicHtmlEntities,
+ extractCadPatchFullSvg,
+ extractLatestSvgFromText,
+ extractRawSvg,
+ extractSvgFence,
+ hasCadPatchPayload,
+ jsonCandidates,
+ normalizeSvgMarkup,
+} from "../client/workspaces/cad/lib/svg-markup";
+
+/**
+ * Getting usable SVG out of a CAD reply. The workspace, the canvas and the
+ * chat panel all read the same reply, so any disagreement here shows up as a
+ * drawing that appears in one place and not another.
+ */
+
+const SVG = '<svg viewBox="0 0 10 10"><rect x="1" y="1" width="8" height="8"/></svg>';
+
+test("prose around an SVG is trimmed away", () => {
+ assert.equal(normalizeSvgMarkup(`Here you go:\n${SVG}\nHope that helps.`), SVG);
+});
+
+test("a reply with no SVG gives back nothing", () => {
+ assert.equal(normalizeSvgMarkup("just some text"), "");
+ assert.equal(normalizeSvgMarkup(""), "");
+});
+
+test("an HTML-escaped SVG is decoded rather than discarded", () => {
+ // This is the divergence that used to exist between the three copies: the
+ // canvas's version had no decoding and returned "" for this input.
+ const escaped = "&lt;svg viewBox=&quot;0 0 10 10&quot;&gt;&lt;rect/&gt;&lt;/svg&gt;";
+ const out = normalizeSvgMarkup(escaped);
+ assert.ok(out.startsWith("<svg"), out);
+ assert.ok(out.endsWith("</svg>"), out);
+ assert.ok(out.includes('viewBox="0 0 10 10"'), out);
+});
+
+test("markup that is already unescaped is left alone", () => {
+ assert.equal(normalizeSvgMarkup(SVG), SVG);
+});
+
+test("the ampersand is decoded last so other entities survive", () => {
+ // Decoding & first would turn "&amp;lt;" into "<" rather than "&lt;".
+ assert.equal(decodeBasicHtmlEntities("&amp;lt;"), "&lt;");
+ assert.equal(decodeBasicHtmlEntities("&lt;a&gt; &quot;b&quot; &#39;c&#39;"), `<a> "b" 'c'`);
+});
+
+test("a stream cut off mid-document returns what arrived", () => {
+ const partial = '<svg viewBox="0 0 10 10"><rect x="1"';
+ assert.equal(normalizeSvgMarkup(partial), partial);
+});
+
+test("trailing content after the last close tag is dropped", () => {
+ assert.equal(normalizeSvgMarkup(`${SVG}\n\nAnything else?`), SVG);
+});
+
+test("the last svg fence wins", () => {
+ const reply = ["```svg", "<svg><rect/></svg>", "```", "actually:", "```svg", SVG, "```"].join("\n");
+ assert.equal(extractSvgFence(reply), SVG);
+});
+
+test("a fence with nothing usable in it is skipped", () => {
+ assert.equal(extractSvgFence("```svg\nnot markup\n```"), "");
+});
+
+test("bare markup is found when there is no fence", () => {
+ assert.equal(extractRawSvg(`before ${SVG} after`), SVG);
+ assert.equal(extractRawSvg("no svg here"), "");
+});
+
+test("a whole-document patch yields its full svg", () => {
+ const payload = JSON.stringify({ type: "cad_patch", target: "2d_svg", mode: "replace", full: SVG });
+ assert.equal(extractCadPatchFullSvg("```json\n" + payload + "\n```"), SVG);
+ assert.equal(extractCadPatchFullSvg(payload), SVG, "unfenced works too");
+});
+
+test("a patch that only edits parts of the drawing has no full svg", () => {
+ const payload = JSON.stringify({
+ type: "cad_patch",
+ target: "2d_svg",
+ mode: "patch",
+ edits: [{ search: "a", replace: "b" }],
+ });
+ assert.equal(extractCadPatchFullSvg(payload), "", "mode must be replace");
+});
+
+test("another tool's payload is not mistaken for a patch", () => {
+ const payload = JSON.stringify({ type: "cad_plan", plan: {} });
+ assert.equal(extractCadPatchFullSvg(payload), "");
+ assert.equal(hasCadPatchPayload(payload), false);
+});
+
+test("a patch is recognised in any of its shapes", () => {
+ const payload = JSON.stringify({ type: "cad_patch", target: "2d_svg", mode: "patch", edits: [] });
+ assert.equal(hasCadPatchPayload("```json\n" + payload + "\n```"), true, "fenced");
+ assert.equal(hasCadPatchPayload(payload), true, "bare");
+ assert.equal(hasCadPatchPayload(`text ${payload} more`), true, "embedded");
+});
+
+test("a truncated patch still names itself", () => {
+ // The stream stopped before the closing brace, so nothing parses; the
+ // caller still needs to know a patch was on its way.
+ assert.equal(hasCadPatchPayload('{"type": "cad_patch", "target": "2d_svg", "edits": [{"sea'), true);
+});
+
+test("an empty reply carries no patch", () => {
+ assert.equal(hasCadPatchPayload(""), false);
+ assert.equal(hasCadPatchPayload(" "), false);
+});
+
+test("json candidates are offered fence-first", () => {
+ const found = jsonCandidates('```json\n{"a":1}\n```\nand {"b":2}');
+ assert.deepEqual(found[0], { a: 1 }, "the fence is tried before the loose braces");
+ assert.ok(found.length >= 1);
+});
+
+test("a reply with no json yields no candidates", () => {
+ assert.deepEqual(jsonCandidates("plain prose"), []);
+});
+
+test("the most explicit form of the drawing wins", () => {
+ const patch = JSON.stringify({ type: "cad_patch", target: "2d_svg", mode: "replace", full: "<svg><circle/></svg>" });
+ const reply = ["```svg", SVG, "```", "```json", patch, "```"].join("\n");
+ assert.equal(extractLatestSvgFromText(reply), SVG, "a fence beats a patch payload");
+});
+
+test("the patch payload is used when nothing else is offered", () => {
+ const patch = JSON.stringify({ type: "cad_patch", target: "2d_svg", mode: "replace", full: SVG });
+ assert.equal(extractLatestSvgFromText("```json\n" + patch + "\n```"), SVG);
+});
+
+test("edits apply in order", () => {
+ const out = applyStringEdits("one two three", [
+ { search: "one", replace: "1" },
+ { search: "three", replace: "3" },
+ ]);
+ assert.equal(out, "1 two 3");
+});
+
+test("an edit that does not match refuses rather than half-applying", () => {
+ // A drawing patched halfway is one neither the user nor the model can
+ // reason about, so the whole patch fails.
+ assert.throws(
+ () => applyStringEdits("abc", [{ search: "a", replace: "x" }, { search: "zzz", replace: "y" }]),
+ /Search pattern not found/,
+ );
+});
+
+test("a malformed patch is refused", () => {
+ assert.throws(() => applyStringEdits("abc", []), /Empty patch edits/);
+ assert.throws(() => applyStringEdits("abc", [{ search: "", replace: "x" }]), /Empty search pattern/);
+ assert.throws(
+ () => applyStringEdits("abc", [{ search: "a" } as { search: string; replace: string }]),
+ /Invalid patch edit item/,
+ );
+});
+
+test("only the first occurrence of a search is replaced", () => {
+ assert.equal(applyStringEdits("a a a", [{ search: "a", replace: "b" }]), "b a a");
+});