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.

refactor(cad): one ladder for applying a patch, not two

codingFeng1018c582519af61
diff --git a/client/workspaces/cad/chat/ChatPanel.tsx b/client/workspaces/cad/chat/ChatPanel.tsx
index ea0cceb..fb9add0 100644
--- a/client/workspaces/cad/chat/ChatPanel.tsx
+++ b/client/workspaces/cad/chat/ChatPanel.tsx
@@ -23,6 +23,7 @@ import {
CAD_SVG_FLOW_REPLACE_AGENT_PROMPT,
} from '@/workspaces/cad/lib/agents';
import { getCadRenderFallbackTitle, getCadRenderSlotTitles } from "@/workspaces/cad/lib/render-titles";
+import { applyCadPatchFromReply } from "@/workspaces/cad/lib/apply-cad-patch";
import {
assembleDisplay,
assemblePrompt,
@@ -1198,113 +1199,14 @@ export function ChatPanel({
}, chatModel, controller.signal);
toolUpdater.flush();
- let cadPatchFound = false;
- let cadPatchRetryError: string | null = null;
- let producedHasSvg2d = false;
- let appliedSvg = "";
-
- const jsonRegex = /```json\s*([\s\S]*?)```/g;
- let jm: RegExpExecArray | null;
- while ((jm = jsonRegex.exec(toolFull))) {
- const jsonText = String(jm[1] || "").trim();
- if (!jsonText) continue;
-
- let parsed: any = null;
- try {
- parsed = JSON.parse(jsonText);
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
-
- const isCadPatch = parsed?.type === "cad_patch" && parsed?.target === "2d_svg";
- if (isCadPatch) cadPatchFound = true;
-
- const result = await runCodeAction(jsonText, "cad");
- if (isCadPatch && result.ok) {
- producedHasSvg2d = true;
- const normalizedAppliedSvg = normalizeSvgMarkup(result.svg || "");
- if (normalizedAppliedSvg) appliedSvg = normalizedAppliedSvg;
- }
- if (isCadPatch && !result.ok && result.retry) {
- cadPatchRetryError = result.error || "Unknown error";
- }
- }
-
- if (!cadPatchFound) {
- const trimmed = String(toolFull || "").trim();
- if (trimmed.startsWith("{")) {
- let rawParsed: unknown = null;
- try {
- rawParsed = JSON.parse(trimmed);
- } catch {
- // Not JSON at all; this fallback only guesses at the payload.
- }
-
- const patch = rawParsed as { type?: string; target?: string } | null;
- if (patch?.type === "cad_patch" && patch?.target === "2d_svg") {
- cadPatchFound = true;
- const result = await runCodeAction(trimmed, "cad");
- if (result.ok) {
- producedHasSvg2d = true;
- const normalizedAppliedSvg = normalizeSvgMarkup(result.svg || "");
- if (normalizedAppliedSvg) appliedSvg = normalizedAppliedSvg;
- }
- if (!result.ok && result.retry) cadPatchRetryError = result.error || "Unknown error";
- }
- }
- }
-
- if (!cadPatchFound) {
- const start = toolFull.indexOf("{");
- const end = toolFull.lastIndexOf("}");
- if (start >= 0 && end > start) {
- const maybeJson = toolFull.slice(start, end + 1).trim();
- let rawParsed: unknown = null;
- try {
- rawParsed = JSON.parse(maybeJson);
- } catch {
- // Not JSON at all; this fallback only guesses at the payload.
- }
-
- const patch = rawParsed as { type?: string; target?: string } | null;
- if (patch?.type === "cad_patch" && patch?.target === "2d_svg") {
- cadPatchFound = true;
- const result = await runCodeAction(maybeJson, "cad");
- if (result.ok) {
- producedHasSvg2d = true;
- const normalizedAppliedSvg = normalizeSvgMarkup(result.svg || "");
- if (normalizedAppliedSvg) appliedSvg = normalizedAppliedSvg;
- }
- if (!result.ok && result.retry) cadPatchRetryError = result.error || "Unknown error";
- }
- }
- }
-
- if (!cadPatchFound) {
- const svgText = extractSvgFence(toolFull) || extractRawSvg(toolFull);
- if (svgText) {
- const r = await runCodeAction(svgText, "cad");
- if (r.ok) {
- producedHasSvg2d = true;
- appliedSvg = normalizeSvgMarkup(r.svg || "") || svgText;
- }
- if (!r.ok && r.retry) cadPatchRetryError = r.error || "Unknown error";
- }
- }
-
- if (!producedHasSvg2d && !cadPatchFound) {
- const fallbackSvg = extractCadPatchFullSvg(toolFull) || extractSvgFence(toolFull) || extractRawSvg(toolFull);
- if (fallbackSvg) {
- const r = await runCodeAction(fallbackSvg, "cad");
- if (r.ok) {
- producedHasSvg2d = true;
- appliedSvg = normalizeSvgMarkup(r.svg || "") || fallbackSvg;
- }
- if (!r.ok && r.retry) cadPatchRetryError = r.error || "Unknown error";
- }
- }
-
- return { toolFull, cadPatchFound, cadPatchRetryError, producedHasSvg2d, appliedSvg };
+ const applied = await applyCadPatchFromReply(toolFull, runCodeAction);
+ return {
+ toolFull,
+ cadPatchFound: applied.patchFound,
+ cadPatchRetryError: applied.retryError,
+ producedHasSvg2d: applied.producedSvg,
+ appliedSvg: applied.appliedSvg,
+ };
};
const getCadSvgToolPrompt = (tool: "patch" | "replace") =>
@@ -1865,113 +1767,14 @@ export function ChatPanel({
}, chatModel, controller.signal);
toolUpdater.flush();
- let cadPatchFound = false;
- let cadPatchRetryError: string | null = null;
- let producedHasSvg2d = false;
- let appliedSvg = "";
-
- const jsonRegex = /```json\s*([\s\S]*?)```/g;
- let jm: RegExpExecArray | null;
- while ((jm = jsonRegex.exec(toolFull))) {
- const jsonText = String(jm[1] || "").trim();
- if (!jsonText) continue;
-
- let parsed: any = null;
- try {
- parsed = JSON.parse(jsonText);
- } catch {
- // Not this payload; the caller falls through to the next shape.
- }
-
- const isCadPatch = parsed?.type === "cad_patch" && parsed?.target === "2d_svg";
- if (isCadPatch) cadPatchFound = true;
-
- const result = await runCodeAction(jsonText, "cad");
- if (isCadPatch && result.ok) {
- producedHasSvg2d = true;
- const normalizedAppliedSvg = normalizeSvgMarkup(result.svg || "");
- if (normalizedAppliedSvg) appliedSvg = normalizedAppliedSvg;
- }
- if (isCadPatch && !result.ok && result.retry) {
- cadPatchRetryError = result.error || "Unknown error";
- }
- }
-
- if (!cadPatchFound) {
- const trimmed = String(toolFull || "").trim();
- if (trimmed.startsWith("{")) {
- let rawParsed: unknown = null;
- try {
- rawParsed = JSON.parse(trimmed);
- } catch {
- // Not JSON at all; this fallback only guesses at the payload.
- }
-
- const patch = rawParsed as { type?: string; target?: string } | null;
- if (patch?.type === "cad_patch" && patch?.target === "2d_svg") {
- cadPatchFound = true;
- const result = await runCodeAction(trimmed, "cad");
- if (result.ok) {
- producedHasSvg2d = true;
- const normalizedAppliedSvg = normalizeSvgMarkup(result.svg || "");
- if (normalizedAppliedSvg) appliedSvg = normalizedAppliedSvg;
- }
- if (!result.ok && result.retry) cadPatchRetryError = result.error || "Unknown error";
- }
- }
- }
-
- if (!cadPatchFound) {
- const start = toolFull.indexOf("{");
- const end = toolFull.lastIndexOf("}");
- if (start >= 0 && end > start) {
- const maybeJson = toolFull.slice(start, end + 1).trim();
- let rawParsed: unknown = null;
- try {
- rawParsed = JSON.parse(maybeJson);
- } catch {
- // Not JSON at all; this fallback only guesses at the payload.
- }
-
- const patch = rawParsed as { type?: string; target?: string } | null;
- if (patch?.type === "cad_patch" && patch?.target === "2d_svg") {
- cadPatchFound = true;
- const result = await runCodeAction(maybeJson, "cad");
- if (result.ok) {
- producedHasSvg2d = true;
- const normalizedAppliedSvg = normalizeSvgMarkup(result.svg || "");
- if (normalizedAppliedSvg) appliedSvg = normalizedAppliedSvg;
- }
- if (!result.ok && result.retry) cadPatchRetryError = result.error || "Unknown error";
- }
- }
- }
-
- if (!cadPatchFound) {
- const svgText = extractSvgFence(toolFull) || extractRawSvg(toolFull);
- if (svgText) {
- const r = await runCodeAction(svgText, "cad");
- if (r.ok) {
- producedHasSvg2d = true;
- appliedSvg = normalizeSvgMarkup(r.svg || "") || svgText;
- }
- if (!r.ok && r.retry) cadPatchRetryError = r.error || "Unknown error";
- }
- }
-
- if (!producedHasSvg2d && !cadPatchFound) {
- const fallbackSvg = extractCadPatchFullSvg(toolFull) || extractSvgFence(toolFull) || extractRawSvg(toolFull);
- if (fallbackSvg) {
- const r = await runCodeAction(fallbackSvg, "cad");
- if (r.ok) {
- producedHasSvg2d = true;
- appliedSvg = normalizeSvgMarkup(r.svg || "") || fallbackSvg;
- }
- if (!r.ok && r.retry) cadPatchRetryError = r.error || "Unknown error";
- }
- }
-
- return { toolFull, cadPatchFound, cadPatchRetryError, producedHasSvg2d, appliedSvg };
+ const applied = await applyCadPatchFromReply(toolFull, runCodeAction);
+ return {
+ toolFull,
+ cadPatchFound: applied.patchFound,
+ cadPatchRetryError: applied.retryError,
+ producedHasSvg2d: applied.producedSvg,
+ appliedSvg: applied.appliedSvg,
+ };
};
const getCadSvgToolPrompt = (tool: "patch" | "replace") =>
diff --git a/client/workspaces/cad/lib/apply-cad-patch.ts b/client/workspaces/cad/lib/apply-cad-patch.ts
new file mode 100644
index 0000000..1ea6c9d
--- /dev/null
+++ b/client/workspaces/cad/lib/apply-cad-patch.ts
@@ -0,0 +1,118 @@
+import {
+ extractCadPatchFullSvg,
+ extractRawSvg,
+ extractSvgFence,
+ normalizeSvgMarkup,
+} from "@/workspaces/cad/lib/svg-markup";
+
+/** What running one payload through the canvas reported back. */
+export interface CodeActionResult {
+ ok: boolean;
+ retry?: boolean;
+ error?: string;
+ svg?: string;
+}
+
+export type RunCodeAction = (payload: string, workspace: "cad") => Promise<CodeActionResult>;
+
+export interface AppliedPatch {
+ /** A cad_patch payload was recognised, whether or not it applied cleanly. */
+ patchFound: boolean;
+ /** The canvas now holds new SVG. */
+ producedSvg: boolean;
+ /** The markup the canvas ended up with, normalised. */
+ appliedSvg: string;
+ /** Set when the patch failed in a way worth asking the model to redo. */
+ retryError: string | null;
+}
+
+const isCadPatch = (value: unknown): boolean => {
+ const record = value as Record<string, unknown> | null;
+ return (
+ !!record &&
+ typeof record === "object" &&
+ String(record.type || "").trim().toLowerCase() === "cad_patch" &&
+ String(record.target || "").trim().toLowerCase() === "2d_svg"
+ );
+};
+
+const tryParse = (text: string): unknown => {
+ try {
+ return JSON.parse(text);
+ } catch {
+ // Not JSON; the caller decides what to do with the text anyway.
+ return null;
+ }
+};
+
+/**
+ * Applies whatever a CAD agent's reply is carrying.
+ *
+ * The agent is asked for a cad_patch payload but does not reliably send one,
+ * so each shape below is a form real replies arrive in, tried in descending
+ * order of confidence: a fenced payload, a reply that is bare JSON, the
+ * outermost brace pair, then plain SVG, then a last sweep.
+ *
+ * Every fenced payload is run, not only the patches: the canvas dispatches on
+ * payload type, so a cad_plan or a bill of materials sent in the same reply is
+ * applied by the same call. Only cad_patch results count towards the drawing.
+ */
+export async function applyCadPatchFromReply(
+ reply: string,
+ runCodeAction: RunCodeAction,
+): Promise<AppliedPatch> {
+ const raw = String(reply || "");
+ let patchFound = false;
+ let producedSvg = false;
+ let appliedSvg = "";
+ let retryError: string | null = null;
+
+ const record = (result: CodeActionResult, fallbackSvg?: string) => {
+ if (result.ok) {
+ producedSvg = true;
+ const normalized = normalizeSvgMarkup(result.svg || "");
+ appliedSvg = normalized || fallbackSvg || appliedSvg;
+ }
+ if (!result.ok && result.retry) retryError = result.error || "Unknown error";
+ };
+
+ const fence = /```json\s*([\s\S]*?)```/g;
+ let match: RegExpExecArray | null;
+ while ((match = fence.exec(raw))) {
+ const text = String(match[1] || "").trim();
+ if (!text) continue;
+ const isPatch = isCadPatch(tryParse(text));
+ if (isPatch) patchFound = true;
+ const result = await runCodeAction(text, "cad");
+ if (isPatch) record(result);
+ }
+
+ /** Runs a candidate only if it declares itself a patch. */
+ const tryPatchCandidate = async (text: string) => {
+ if (patchFound || !text) return;
+ if (!isCadPatch(tryParse(text))) return;
+ patchFound = true;
+ record(await runCodeAction(text, "cad"));
+ };
+
+ const trimmed = raw.trim();
+ if (trimmed.startsWith("{")) await tryPatchCandidate(trimmed);
+
+ const start = raw.indexOf("{");
+ const end = raw.lastIndexOf("}");
+ if (start >= 0 && end > start) await tryPatchCandidate(raw.slice(start, end + 1).trim());
+
+ // No patch declared, but a drawing was sent anyway.
+ if (!patchFound) {
+ const svg = extractSvgFence(raw) || extractRawSvg(raw);
+ if (svg) record(await runCodeAction(svg, "cad"), svg);
+ }
+
+ // Nothing applied at all: one last sweep, including a patch's own document.
+ if (!producedSvg && !patchFound) {
+ const svg = extractCadPatchFullSvg(raw) || extractSvgFence(raw) || extractRawSvg(raw);
+ if (svg) record(await runCodeAction(svg, "cad"), svg);
+ }
+
+ return { patchFound, producedSvg, appliedSvg, retryError };
+}
diff --git a/tests/cad-apply-patch.test.ts b/tests/cad-apply-patch.test.ts
new file mode 100644
index 0000000..54aa96a
--- /dev/null
+++ b/tests/cad-apply-patch.test.ts
@@ -0,0 +1,152 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ applyCadPatchFromReply,
+ type CodeActionResult,
+} from "../client/workspaces/cad/lib/apply-cad-patch";
+
+/**
+ * Applying whatever a CAD agent's reply is carrying.
+ *
+ * The agent is asked for a cad_patch payload and does not reliably send one,
+ * so this walks a ladder of shapes. What matters is that a drawing is never
+ * applied twice, that a reply carrying nothing usable changes nothing, and
+ * that non-patch payloads in the same reply still reach the canvas.
+ */
+
+const SVG = '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>';
+
+/** Records every payload handed to the canvas and answers as told. */
+function fakeCanvas(answer: (payload: string) => CodeActionResult = () => ({ ok: true })) {
+ const calls: string[] = [];
+ const run = async (payload: string) => {
+ calls.push(payload);
+ return answer(payload);
+ };
+ return { calls, run: run as (p: string, w: "cad") => Promise<CodeActionResult> };
+}
+
+const patch = (over: Record<string, unknown> = {}) =>
+ JSON.stringify({ type: "cad_patch", target: "2d_svg", mode: "patch", edits: [], ...over });
+
+test("a fenced patch is applied and reported", async () => {
+ const canvas = fakeCanvas(() => ({ ok: true, svg: SVG }));
+ const out = await applyCadPatchFromReply("```json\n" + patch() + "\n```", canvas.run);
+
+ assert.equal(out.patchFound, true);
+ assert.equal(out.producedSvg, true);
+ assert.equal(out.appliedSvg, SVG);
+ assert.equal(out.retryError, null);
+ assert.equal(canvas.calls.length, 1);
+});
+
+test("a reply that is bare JSON is applied too", async () => {
+ const canvas = fakeCanvas(() => ({ ok: true, svg: SVG }));
+ const out = await applyCadPatchFromReply(patch(), canvas.run);
+ assert.equal(out.patchFound, true);
+ assert.equal(out.appliedSvg, SVG);
+});
+
+test("a patch buried in prose is still found", async () => {
+ const canvas = fakeCanvas(() => ({ ok: true, svg: SVG }));
+ const out = await applyCadPatchFromReply(`Sure. ${patch()} Done.`, canvas.run);
+ assert.equal(out.patchFound, true);
+ assert.equal(canvas.calls.length, 1);
+});
+
+test("a payload that is not a patch still reaches the canvas", async () => {
+ // The canvas dispatches on payload type, so a plan sent in the same reply
+ // has to be applied by the same call.
+ const canvas = fakeCanvas();
+ const plan = JSON.stringify({ type: "cad_plan", plan: { rooms: [] } });
+ const out = await applyCadPatchFromReply("```json\n" + plan + "\n```", canvas.run);
+
+ assert.equal(canvas.calls.length, 1, "the plan was handed over");
+ assert.equal(out.patchFound, false, "but it is not a drawing");
+ assert.equal(out.producedSvg, false);
+});
+
+test("a plan and a patch in one reply are both applied", async () => {
+ const canvas = fakeCanvas(() => ({ ok: true, svg: SVG }));
+ const plan = JSON.stringify({ type: "cad_plan", plan: {} });
+ const reply = ["```json", plan, "```", "```json", patch(), "```"].join("\n");
+ const out = await applyCadPatchFromReply(reply, canvas.run);
+
+ assert.equal(canvas.calls.length, 2);
+ assert.equal(out.patchFound, true);
+ assert.equal(out.producedSvg, true);
+});
+
+test("bare SVG is applied when no patch was declared", async () => {
+ const canvas = fakeCanvas(() => ({ ok: true }));
+ const out = await applyCadPatchFromReply(`here it is:\n${SVG}`, canvas.run);
+
+ assert.equal(out.patchFound, false);
+ assert.equal(out.producedSvg, true);
+ assert.equal(out.appliedSvg, SVG, "the canvas returned no svg, so the sent one stands");
+ assert.equal(canvas.calls.length, 1);
+});
+
+test("a drawing sent both ways is applied once", async () => {
+ const canvas = fakeCanvas(() => ({ ok: true, svg: SVG }));
+ const reply = ["```json", patch({ mode: "replace", full: SVG }), "```", SVG].join("\n");
+ const out = await applyCadPatchFromReply(reply, canvas.run);
+
+ assert.equal(canvas.calls.length, 1, "the declared patch wins; the bare copy is not re-applied");
+ assert.equal(out.patchFound, true);
+});
+
+test("a reply with nothing usable changes nothing", async () => {
+ const canvas = fakeCanvas();
+ const out = await applyCadPatchFromReply("I could not draw that, sorry.", canvas.run);
+
+ assert.deepEqual(out, { patchFound: false, producedSvg: false, appliedSvg: "", retryError: null });
+ assert.equal(canvas.calls.length, 0, "nothing was handed to the canvas");
+});
+
+test("an empty reply is a no-op", async () => {
+ const canvas = fakeCanvas();
+ assert.equal((await applyCadPatchFromReply("", canvas.run)).patchFound, false);
+ assert.equal(canvas.calls.length, 0);
+});
+
+test("a retryable failure is reported for the model to redo", async () => {
+ const canvas = fakeCanvas(() => ({ ok: false, retry: true, error: "Search pattern not found" }));
+ const out = await applyCadPatchFromReply("```json\n" + patch() + "\n```", canvas.run);
+
+ assert.equal(out.patchFound, true, "the patch was recognised");
+ assert.equal(out.producedSvg, false, "but nothing was drawn");
+ assert.equal(out.retryError, "Search pattern not found");
+});
+
+test("a failure the model cannot fix is not offered for retry", async () => {
+ const canvas = fakeCanvas(() => ({ ok: false, retry: false, error: "SVG has no drawable content" }));
+ const out = await applyCadPatchFromReply("```json\n" + patch() + "\n```", canvas.run);
+
+ assert.equal(out.patchFound, true);
+ assert.equal(out.retryError, null, "retry is the canvas's call, not ours");
+});
+
+test("a failed retry still names an error when the canvas gives none", async () => {
+ const canvas = fakeCanvas(() => ({ ok: false, retry: true }));
+ const out = await applyCadPatchFromReply("```json\n" + patch() + "\n```", canvas.run);
+ assert.equal(out.retryError, "Unknown error");
+});
+
+test("the last of several patches is the one left on the canvas", async () => {
+ const first = '<svg id="first"/>';
+ const second = '<svg id="second"/>';
+ const canvas = fakeCanvas((payload) => ({ ok: true, svg: payload.includes("one") ? first : second }));
+ const reply = [
+ "```json",
+ patch({ note: "one" }),
+ "```",
+ "```json",
+ patch({ note: "two" }),
+ "```",
+ ].join("\n");
+
+ const out = await applyCadPatchFromReply(reply, canvas.run);
+ assert.equal(canvas.calls.length, 2);
+ assert.equal(out.appliedSvg, second);
+});