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.

test: characterise the logic the refactor has to preserve

codingFeng1010deb10377b50
diff --git a/package.json b/package.json
index ccf2595..51f54de 100644
--- a/package.json
+++ b/package.json
@@ -10,7 +10,7 @@
"start": "tsx server/index.ts",
"build": "tsc -b && vite build",
"lint": "eslint .",
- "test": "tsx --test tests/*.test.ts",
+ "test": "tsx --import ./tests/support/register.mjs --test tests/*.test.ts",
"preview": "vite preview --host 0.0.0.0 --port 8001",
"check": "tsc -b --noEmit"
},
diff --git a/tests/chat-storage.test.ts b/tests/chat-storage.test.ts
new file mode 100644
index 0000000..4be05b5
--- /dev/null
+++ b/tests/chat-storage.test.ts
@@ -0,0 +1,186 @@
+import assert from "node:assert/strict";
+import { afterEach, beforeEach, test } from "node:test";
+import type { ChatMessage } from "../contracts/ai";
+import {
+ buildRecentHistoryContext,
+ chatStorageKey,
+ loadChatHistory,
+ normalizeStoredChatMessages,
+ saveChatHistory,
+ truncateForStorage,
+} from "../client/shared/chat/chat-storage";
+
+/**
+ * Chat history carries inline base64 images, so writing it is the one place
+ * the storage quota is regularly hit. What matters is that a failed write
+ * degrades to a shorter history rather than throwing away the conversation.
+ */
+
+const KEY = "chat_history_v2_test";
+
+/** A localStorage stand-in whose quota can be capped to force the fallbacks. */
+class FakeStorage {
+ private data = new Map<string, string>();
+ limit = Infinity;
+ writes = 0;
+
+ getItem(key: string) {
+ return this.data.has(key) ? this.data.get(key)! : null;
+ }
+
+ setItem(key: string, value: string) {
+ this.writes += 1;
+ if (value.length > this.limit) {
+ const error = new Error("QuotaExceededError");
+ error.name = "QuotaExceededError";
+ throw error;
+ }
+ this.data.set(key, value);
+ }
+
+ removeItem(key: string) {
+ this.data.delete(key);
+ }
+}
+
+let storage: FakeStorage;
+const originalWindow = (globalThis as Record<string, unknown>).window;
+const originalStorage = (globalThis as Record<string, unknown>).localStorage;
+
+beforeEach(() => {
+ storage = new FakeStorage();
+ (globalThis as Record<string, unknown>).localStorage = storage;
+ (globalThis as Record<string, unknown>).window = globalThis;
+});
+
+afterEach(() => {
+ (globalThis as Record<string, unknown>).localStorage = originalStorage;
+ (globalThis as Record<string, unknown>).window = originalWindow;
+});
+
+const message = (role: ChatMessage["role"], content: string): ChatMessage => ({ role, content });
+
+test("the storage key is namespaced per workspace", () => {
+ assert.equal(chatStorageKey("cad"), "chat_history_v2_cad");
+ assert.notEqual(chatStorageKey("cad"), chatStorageKey("ppt"));
+});
+
+test("truncateForStorage marks what it cut", () => {
+ assert.equal(truncateForStorage("short", 100), "short");
+ const cut = truncateForStorage("x".repeat(100), 40);
+ assert.equal(cut.length, 40);
+ assert.ok(cut.endsWith("[truncated]"), cut.slice(-20));
+ // Too small to hold the marker: fall back to a plain slice.
+ assert.equal(truncateForStorage("abcdef", 3), "abc");
+ assert.equal(truncateForStorage("abcdef", 0), "");
+});
+
+test("normalizeStoredChatMessages drops what it cannot use", () => {
+ const parsed = normalizeStoredChatMessages([
+ { role: "user", content: "keep" },
+ { role: "assistant", content: "keep too" },
+ { role: "nonsense", content: "role coerced to user" },
+ { role: "user", content: "" },
+ null,
+ "a string",
+ { role: "user" },
+ ]);
+
+ assert.deepEqual(parsed, [
+ { role: "user", content: "keep" },
+ { role: "assistant", content: "keep too" },
+ { role: "user", content: "role coerced to user" },
+ ]);
+ assert.deepEqual(normalizeStoredChatMessages("not an array"), []);
+});
+
+test("a round trip returns the conversation", () => {
+ const messages = [message("user", "hello"), message("assistant", "hi")];
+ assert.equal(saveChatHistory(KEY, messages), true);
+ assert.deepEqual(loadChatHistory(KEY), messages);
+});
+
+test("loading falls back when nothing is stored or it is corrupt", () => {
+ const fallback = [message("assistant", "welcome")];
+ assert.deepEqual(loadChatHistory(KEY, fallback), fallback);
+
+ storage.setItem(KEY, "{ this is not json");
+ assert.deepEqual(loadChatHistory(KEY, fallback), fallback);
+
+ // An array of unusable entries is empty after normalising, so the caller's
+ // fallback stands rather than handing back a blank conversation.
+ storage.setItem(KEY, JSON.stringify([null, { role: "user" }]));
+ assert.deepEqual(loadChatHistory(KEY, fallback), fallback);
+});
+
+test("inline image data never reaches storage", () => {
+ const png = "data:image/png;base64," + "A".repeat(5000);
+ saveChatHistory(KEY, [message("user", `[[IMAGE|diagram.png|${png}]] look at this`)]);
+
+ const written = storage.getItem(KEY)!;
+ assert.ok(!written.includes("AAAA"), "base64 payload must be stripped");
+ assert.ok(written.includes("[image-data]"), "a placeholder should remain");
+ assert.ok(written.includes("diagram.png"), "the label the UI renders is kept");
+});
+
+test("a write that will not fit retries smaller instead of dropping everything", () => {
+ const long = "x".repeat(20000);
+ const messages = Array.from({ length: 40 }, (_, i) => message("user", `${i} ${long}`));
+
+ // Small enough that the first tiers cannot fit, large enough that one can.
+ storage.limit = 40000;
+ assert.equal(saveChatHistory(KEY, messages), true);
+ assert.ok(storage.writes > 1, "expected at least one retry at a smaller size");
+
+ const kept = loadChatHistory(KEY);
+ assert.ok(kept.length > 0, "history must survive, even if shortened");
+ assert.ok(kept.length < messages.length, "and it should be shorter than the input");
+});
+
+test("an impossible write reports failure without wiping what was there", () => {
+ saveChatHistory(KEY, [message("user", "previously saved")]);
+ storage.limit = 1;
+ assert.equal(saveChatHistory(KEY, [message("user", "x".repeat(100))]), false);
+ assert.deepEqual(loadChatHistory(KEY), [message("user", "previously saved")]);
+});
+
+test("buildRecentHistoryContext summarises the tail for an intent router", () => {
+ const context = buildRecentHistoryContext([
+ message("system", "ignored"),
+ message("user", "draw a login flow"),
+ message("assistant", "here it is"),
+ ]);
+
+ assert.ok(context.startsWith("Recent chat history"));
+ assert.ok(context.includes("[User] draw a login flow"));
+ assert.ok(context.includes("[Assistant] here it is"));
+ assert.ok(!context.includes("ignored"), "system turns are not conversation");
+ assert.equal(buildRecentHistoryContext([]), "");
+});
+
+test("buildRecentHistoryContext respects its budget", () => {
+ const messages = Array.from({ length: 50 }, (_, i) => message("user", `turn ${i} ${"y".repeat(500)}`));
+ const context = buildRecentHistoryContext(messages, {
+ maxMessages: 5,
+ maxMessageChars: 100,
+ maxTotalChars: 300,
+ });
+
+ assert.ok(context.length < 600, `expected a small context, got ${context.length}`);
+});
+
+test("KNOWN ODDITY: over budget, it drops the newest turns, not the oldest", () => {
+ // It takes the last maxMessages turns, then fills forward from the oldest of
+ // those until maxTotalChars runs out — so turns 48 and 49 are the ones lost.
+ // For something labelled "recent chat history (for intent continuity)" that
+ // is backwards. Pinned as-is so the fix is a deliberate, visible change.
+ const messages = Array.from({ length: 50 }, (_, i) => message("user", `turn ${i} ${"y".repeat(500)}`));
+ const context = buildRecentHistoryContext(messages, {
+ maxMessages: 5,
+ maxMessageChars: 100,
+ maxTotalChars: 300,
+ });
+
+ assert.ok(context.includes("turn 45"), "keeps the oldest of the window");
+ assert.ok(!context.includes("turn 49"), "and drops the newest turn");
+});
diff --git a/tests/drawio-xml.test.ts b/tests/drawio-xml.test.ts
new file mode 100644
index 0000000..ce627e4
--- /dev/null
+++ b/tests/drawio-xml.test.ts
@@ -0,0 +1,171 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ autoFixXml,
+ convertToLegalXml,
+ formatXML,
+ validateMxCellStructure,
+ wrapWithMxFile,
+} from "../client/workspaces/flow/lib/drawio-xml";
+import { isMxCellXmlComplete } from "../client/workspaces/flow/lib/diagram-operations";
+
+/**
+ * The repair layer between what the model emits and what draw.io will accept.
+ * A mistake here is visible as a broken or silently emptied canvas.
+ *
+ * Only the DOM-free paths are covered: validateMxCellStructure's later checks,
+ * replaceNodes and replaceXMLParts all need a DOMParser, so they are exercised
+ * in the browser rather than here.
+ */
+
+const ROOT_CELLS = '<mxCell id="0"/><mxCell id="1" parent="0"/>';
+const CELL = '<mxCell id="2" value="Start" vertex="1" parent="1"><mxGeometry x="10" y="10" as="geometry"/></mxCell>';
+
+test("wrapWithMxFile builds an empty document from nothing", () => {
+ const wrapped = wrapWithMxFile("");
+ assert.ok(wrapped.startsWith("<mxfile>"));
+ assert.ok(wrapped.includes(ROOT_CELLS), "the two root cells draw.io requires");
+});
+
+test("wrapWithMxFile leaves an already-complete document alone", () => {
+ const complete = `<mxfile><diagram><mxGraphModel><root>${ROOT_CELLS}</root></mxGraphModel></diagram></mxfile>`;
+ assert.equal(wrapWithMxFile(complete), complete);
+});
+
+test("wrapWithMxFile wraps a bare mxGraphModel", () => {
+ const model = `<mxGraphModel><root>${ROOT_CELLS}</root></mxGraphModel>`;
+ const wrapped = wrapWithMxFile(model);
+ assert.ok(wrapped.startsWith("<mxfile><diagram"));
+ assert.ok(wrapped.includes(model), "the model is kept verbatim");
+});
+
+test("wrapWithMxFile supplies the root cells for loose mxCells", () => {
+ const wrapped = wrapWithMxFile(CELL);
+ assert.ok(wrapped.includes(ROOT_CELLS));
+ assert.ok(wrapped.includes('id="2"'));
+});
+
+test("wrapWithMxFile does not duplicate root cells the model already sent", () => {
+ // The prompt tells the model not to emit id 0 and 1, but it sometimes does;
+ // emitting them twice makes draw.io reject the whole diagram.
+ const wrapped = wrapWithMxFile(`${ROOT_CELLS}${CELL}`);
+ assert.equal(wrapped.match(/id="0"/g)?.length, 1, "exactly one root cell 0");
+ assert.equal(wrapped.match(/id="1"/g)?.length, 1, "exactly one root cell 1");
+ assert.ok(wrapped.includes('id="2"'), "and the real content survives");
+});
+
+test("wrapWithMxFile does not repair a truncated stream, and does not need to", () => {
+ // Truncation is caught upstream: the chat panel checks isMxCellXmlComplete
+ // and asks the model to continue with append_diagram before wrapping. This
+ // pins the division of responsibility — wrapWithMxFile only trims a trailing
+ // run of closing tags, not a half-written one.
+ const wrapped = wrapWithMxFile(`${CELL}<mxCell id="3" value="cut off`);
+ assert.ok(wrapped.includes("cut off"), "the partial cell is passed through as-is");
+});
+
+test("isMxCellXmlComplete is what actually catches a truncated stream", () => {
+ assert.equal(isMxCellXmlComplete(CELL), true);
+ assert.equal(isMxCellXmlComplete(`<root>${CELL}</root>`), true, "trailing closers are fine");
+ assert.equal(isMxCellXmlComplete(`${CELL}<mxCell id="3" value="cut off`), false);
+ assert.equal(isMxCellXmlComplete(""), false);
+ assert.equal(isMxCellXmlComplete("<mxCell id=\"2\""), false, "nothing has closed yet");
+});
+
+test("convertToLegalXml keeps only complete cells", () => {
+ const converted = convertToLegalXml(
+ `${CELL}<mxCell id="3" value="unterminated" vertex="1" parent="1"`,
+ );
+ assert.ok(converted.startsWith("<root>"));
+ assert.ok(converted.trimEnd().endsWith("</root>"));
+ assert.ok(converted.includes('id="2"'));
+ assert.ok(!converted.includes("unterminated"), "a half-written cell is left out");
+});
+
+test("convertToLegalXml removes orphaned mxPoints", () => {
+ // An mxPoint without an `as` attribute makes draw.io log
+ // "Could not add object mxPoint" and skip the edge.
+ const converted = convertToLegalXml(
+ '<mxCell id="4" edge="1" parent="1"><mxGeometry as="geometry">' +
+ '<mxPoint x="1" y="1"/><mxPoint x="2" y="2" as="sourcePoint"/>' +
+ "</mxGeometry></mxCell>",
+ );
+ assert.ok(converted.includes('as="sourcePoint"'), "a labelled point is kept");
+ assert.ok(!/<mxPoint x="1" y="1"\/>/.test(converted), "the orphan is dropped");
+});
+
+test("convertToLegalXml keeps every point inside an Array as=points", () => {
+ const waypoints =
+ '<mxCell id="5" edge="1" parent="1"><mxGeometry as="geometry">' +
+ '<Array as="points"><mxPoint x="1" y="1"/><mxPoint x="2" y="2"/></Array>' +
+ "</mxGeometry></mxCell>";
+ const converted = convertToLegalXml(waypoints);
+ assert.equal(converted.match(/<mxPoint/g)?.length, 2, "waypoints are not orphans");
+});
+
+test("formatXML indents nested tags", () => {
+ const formatted = formatXML("<root><mxCell id=\"2\"/></root>");
+ const lines = formatted.split("\n").filter(Boolean);
+ assert.ok(lines.length > 1, "output is broken across lines");
+ assert.ok(lines[1].startsWith(" "), "children are indented");
+});
+
+test("autoFixXml unescapes XML that arrived JSON-encoded", () => {
+ const { fixed, fixes } = autoFixXml('<mxCell id=\\"2\\" value=\\"A\\"/>');
+ assert.ok(fixed.includes('id="2"'));
+ assert.ok(fixes.some((f) => f.includes("JSON-escaped")), fixes.join(", "));
+});
+
+test("autoFixXml strips a CDATA wrapper", () => {
+ const { fixed, fixes } = autoFixXml(`<![CDATA[${CELL}]]>`);
+ assert.ok(fixed.startsWith("<mxCell"));
+ assert.ok(fixes.some((f) => f.includes("CDATA")), fixes.join(", "));
+});
+
+test("autoFixXml escapes a bare ampersand but leaves real entities", () => {
+ const { fixed } = autoFixXml('<mxCell id="2" value="Tom & Jerry &amp; Co &#65;"/>');
+ assert.ok(fixed.includes("Tom &amp; Jerry"), fixed);
+ assert.ok(fixed.includes("&amp; Co"), "an already-escaped entity is not double-escaped");
+ assert.ok(fixed.includes("&#65;"), "a numeric entity is left alone");
+});
+
+test("autoFixXml corrects the tag name models get wrong", () => {
+ const { fixed } = autoFixXml('<Cell id="2" vertex="1" parent="1"></Cell>');
+ assert.ok(fixed.includes("<mxCell"), fixed);
+ assert.ok(fixed.includes("</mxCell>"), fixed);
+ assert.ok(!fixed.includes("<Cell"), fixed);
+});
+
+test("autoFixXml reports no fixes for XML that was already fine", () => {
+ const { fixed, fixes } = autoFixXml(CELL);
+ assert.equal(fixes.length, 0);
+ assert.equal(fixed, CELL);
+});
+
+test("validation rejects a duplicated structural attribute", () => {
+ // Two `parent` attributes: the browser silently keeps one, so the diagram
+ // comes out attached to the wrong node.
+ const error = validateMxCellStructure('<mxCell id="2" parent="1" parent="0" vertex="1"/>');
+ assert.ok(error, "expected an error");
+ assert.ok(/parent/.test(error!), error!);
+});
+
+test("validation rejects mismatched tags", () => {
+ const error = validateMxCellStructure("<root><mxCell id=\"2\"></mxGeometry></root>");
+ assert.ok(error, "expected an error");
+});
+
+test("validation rejects an unescaped ampersand", () => {
+ const error = validateMxCellStructure('<mxCell id="2" value="A & B"/>');
+ assert.ok(error, "expected an error");
+ assert.ok(/&amp;/.test(error!), error!);
+});
+
+test("an unknown entity is reported as an unescaped ampersand", () => {
+ // &nbsp; trips the unescaped-& check first, because that check only whitelists
+ // lt/gt/amp/quot/apos and numeric forms. The dedicated "invalid entity"
+ // message is therefore only reachable for something like &ltx;. The advice
+ // it gives is still right; pinned so the wording is a deliberate choice.
+ const error = validateMxCellStructure('<mxCell id="2" value="A&nbsp;B"/>');
+ assert.ok(error, "expected an error");
+ assert.ok(/&amp;/.test(error!), error!);
+});
diff --git a/tests/flow-intent.test.ts b/tests/flow-intent.test.ts
new file mode 100644
index 0000000..ba28c86
--- /dev/null
+++ b/tests/flow-intent.test.ts
@@ -0,0 +1,89 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ classifyFlowRequest,
+ isExplicitFullRegenerationRequest,
+ isLikelyLocalEditRequest,
+ normalizeIntentText,
+ shouldRunDeepThinking,
+} from "../server/chat/intent";
+
+/**
+ * Routing a Flow turn wrong is destructive: choosing full_generation for what
+ * was meant as a tweak replaces the user's diagram. These pin the decision.
+ */
+
+const EMPTY_DIAGRAM = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';
+const DIAGRAM_WITH_CONTENT =
+ '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/>' +
+ '<mxCell id="2" value="Start" vertex="1" parent="1"/></root></mxGraphModel>';
+
+test("normalizeIntentText lowercases and collapses whitespace", () => {
+ assert.equal(normalizeIntentText(" Add a\tNODE\n"), "add a node");
+ assert.equal(normalizeIntentText(""), "");
+ assert.equal(normalizeIntentText(null as unknown as string), "");
+});
+
+test("recognises local edits in both languages", () => {
+ for (const text of ["把这个节点改成红色", "删除第二个框", "调整一下连线", "add a node", "remove the arrow", "rename that box"]) {
+ assert.equal(isLikelyLocalEditRequest(text), true, text);
+ }
+});
+
+test("does not mistake an unrelated sentence for an edit", () => {
+ assert.equal(isLikelyLocalEditRequest("这是什么"), false);
+ assert.equal(isLikelyLocalEditRequest("what does this show"), false);
+ assert.equal(isLikelyLocalEditRequest(""), false);
+});
+
+test("recognises an explicit request to start over", () => {
+ for (const text of ["重新生成一张", "从头画一个", "整体重构", "regenerate this", "redraw it from scratch", "create a new diagram"]) {
+ assert.equal(isExplicitFullRegenerationRequest(text), true, text);
+ }
+});
+
+test("an edit phrase alone is not a regeneration request", () => {
+ assert.equal(isExplicitFullRegenerationRequest("改成蓝色"), false);
+ assert.equal(isExplicitFullRegenerationRequest("add a node"), false);
+});
+
+test("an empty canvas always routes to full generation", () => {
+ // Nothing to preserve, so the wording of the request cannot matter.
+ assert.equal(classifyFlowRequest({ xml: "", userText: "改一下颜色" }), "full_generation");
+ assert.equal(classifyFlowRequest({ xml: EMPTY_DIAGRAM, userText: "add a node" }), "full_generation");
+});
+
+test("an explicit regeneration request wins over the edit heuristics", () => {
+ // "修改" reads as a local edit; "重新生成" has to override it, or the user
+ // asking to start over gets a patch instead.
+ assert.equal(
+ classifyFlowRequest({ xml: DIAGRAM_WITH_CONTENT, userText: "重新生成,不要修改原来的" }),
+ "full_generation",
+ );
+});
+
+test("anything else on a non-empty canvas stays a local edit", () => {
+ for (const text of ["改成红色", "这是什么", "", "explain this diagram"]) {
+ assert.equal(classifyFlowRequest({ xml: DIAGRAM_WITH_CONTENT, userText: text }), "local_edit", text);
+ }
+});
+
+test("classification ignores isLikelyLocalEditRequest entirely", () => {
+ // Both remaining branches return local_edit, so the helper does not affect
+ // the outcome. Pinned so that removing the branch is a deliberate choice
+ // rather than a silent behaviour change.
+ const recognised = "add a node";
+ const unrecognised = "这是什么";
+ assert.equal(isLikelyLocalEditRequest(recognised), true);
+ assert.equal(isLikelyLocalEditRequest(unrecognised), false);
+ assert.equal(
+ classifyFlowRequest({ xml: DIAGRAM_WITH_CONTENT, userText: recognised }),
+ classifyFlowRequest({ xml: DIAGRAM_WITH_CONTENT, userText: unrecognised }),
+ );
+});
+
+test("deep thinking runs only for a full generation the user asked for", () => {
+ assert.equal(shouldRunDeepThinking({ deepThinkingEnabled: true, route: "full_generation" }), true);
+ assert.equal(shouldRunDeepThinking({ deepThinkingEnabled: true, route: "local_edit" }), false);
+ assert.equal(shouldRunDeepThinking({ deepThinkingEnabled: false, route: "full_generation" }), false);
+});
diff --git a/tests/ppt-editor-adapters.test.ts b/tests/ppt-editor-adapters.test.ts
new file mode 100644
index 0000000..e74ce90
--- /dev/null
+++ b/tests/ppt-editor-adapters.test.ts
@@ -0,0 +1,153 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ canvasAnvilSlidesToEditorSlides,
+ canvasAnvilToEditorSlide,
+ extractEditorTextBlocks,
+ extractEditorTextElements,
+} from "../client/features/ppt-editor/adapters/fromCanvasAnvil";
+import { editorSlideToExportPayload } from "../client/features/ppt-editor/adapters/toCanvasAnvil";
+import type { PptTextBlock } from "../client/workspaces/ppt/lib/ppt-service";
+
+/**
+ * The conversion behind "Export editable PPTX": a workspace slide becomes an
+ * editor slide, and the editor slide becomes the page pptxgenjs writes. Losing
+ * a text block here means losing text from the user's deck.
+ */
+
+const slide = {
+ id: "slide-1",
+ title: "Quarterly Review",
+ content: ["Revenue up", "Costs flat"],
+ description: "a description",
+ note: "speaker note",
+ layout: "title-content",
+};
+
+let nextBlockId = 0;
+const textBlock = (text: string, y: number, role: PptTextBlock["role"] = "bullet"): PptTextBlock => ({
+ id: `block-${(nextBlockId += 1)}`,
+ text,
+ x: 0.1,
+ y,
+ w: 0.8,
+ h: 0.1,
+ role,
+ style: { fontSize: 24, color: "#111111" },
+});
+
+const renderLayer = {
+ backgroundImageUrl: "data:image/png;base64,bg",
+ textBlocks: [textBlock("Quarterly Review", 0.1, "title"), textBlock("Revenue up", 0.3)],
+ elements: [],
+ status: "ready" as const,
+};
+
+test("a slide with no render layer still converts", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide);
+ assert.equal(editorSlide.id, "slide-1");
+ assert.equal(editorSlide.title, "Quarterly Review");
+ assert.deepEqual(editorSlide.content, ["Revenue up", "Costs flat"]);
+ assert.deepEqual(editorSlide.elements, [], "nothing to place without a layer");
+ assert.equal(editorSlide.backgroundImageUrl, undefined);
+});
+
+test("a render layer's text blocks become editor elements", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, { renderLayer });
+ assert.equal(editorSlide.backgroundImageUrl, "data:image/png;base64,bg");
+ assert.equal(editorSlide.elements.length, 2);
+ assert.deepEqual(
+ extractEditorTextElements(editorSlide).map((e) => e.text),
+ ["Quarterly Review", "Revenue up"],
+ );
+});
+
+test("the layer's background wins over the fallback", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, {
+ renderLayer,
+ backgroundImageUrl: "fallback.png",
+ });
+ assert.equal(editorSlide.backgroundImageUrl, "data:image/png;base64,bg");
+});
+
+test("the fallback background is used when the layer has none", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, {
+ renderLayer: { ...renderLayer, backgroundImageUrl: "" },
+ backgroundImageUrl: "fallback.png",
+ });
+ assert.equal(editorSlide.backgroundImageUrl, "fallback.png");
+});
+
+test("text survives the round trip to an export page", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, { renderLayer });
+ const { page, textBlocks, elements } = editorSlideToExportPayload(editorSlide);
+
+ assert.equal(page.id, "slide-1");
+ assert.equal(page.status, "completed");
+ assert.equal(page.backgroundImageUrl, "data:image/png;base64,bg");
+ assert.deepEqual(
+ textBlocks.map((b) => b.text),
+ ["Quarterly Review", "Revenue up"],
+ "no text is lost on the way out",
+ );
+ assert.equal(page.textBlocks, textBlocks, "the page carries the same blocks");
+ assert.equal(page.elements, elements);
+});
+
+test("styling survives the round trip", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, { renderLayer });
+ const { textBlocks } = editorSlideToExportPayload(editorSlide);
+ assert.equal(textBlocks[0].style?.fontSize, 24);
+ assert.equal(textBlocks[0].style?.color, "#111111");
+});
+
+test("positions survive the round trip", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, { renderLayer });
+ const { textBlocks } = editorSlideToExportPayload(editorSlide);
+ assert.equal(textBlocks[0].x, 0.1);
+ assert.equal(textBlocks[1].y, 0.3);
+ assert.equal(textBlocks[0].w, 0.8);
+});
+
+test("an empty deck exports an empty page rather than throwing", () => {
+ const { page, textBlocks } = editorSlideToExportPayload(canvasAnvilToEditorSlide(slide));
+ assert.deepEqual(textBlocks, []);
+ assert.equal(page.title, "Quarterly Review", "the outline text is still there");
+});
+
+test("extractEditorTextBlocks reads back what the editor holds", () => {
+ const editorSlide = canvasAnvilToEditorSlide(slide, { renderLayer });
+ assert.deepEqual(
+ extractEditorTextBlocks(editorSlide).map((b) => b.text),
+ ["Quarterly Review", "Revenue up"],
+ );
+});
+
+test("a deck converts slide by slide, each with its own layer", () => {
+ const slides = [slide, { ...slide, id: "slide-2", title: "Outlook" }];
+ const layers: Record<string, typeof renderLayer> = {
+ "slide-1": renderLayer,
+ "slide-2": { ...renderLayer, textBlocks: [textBlock("Outlook", 0.1)] },
+ };
+
+ const editorSlides = canvasAnvilSlidesToEditorSlides(
+ slides,
+ (id) => layers[id],
+ (id) => `${id}-fallback.png`,
+ );
+
+ assert.equal(editorSlides.length, 2);
+ assert.equal(editorSlides[0].elements.length, 2);
+ assert.equal(editorSlides[1].elements.length, 1);
+ assert.equal(extractEditorTextElements(editorSlides[1])[0].text, "Outlook");
+});
+
+test("a slide the lookup does not know still converts, on its fallback background", () => {
+ const editorSlides = canvasAnvilSlidesToEditorSlides(
+ [slide],
+ () => undefined,
+ () => "only-fallback.png",
+ );
+ assert.equal(editorSlides[0].backgroundImageUrl, "only-fallback.png");
+ assert.deepEqual(editorSlides[0].elements, []);
+});
diff --git a/tests/ppt-persisted-state.test.ts b/tests/ppt-persisted-state.test.ts
new file mode 100644
index 0000000..490a406
--- /dev/null
+++ b/tests/ppt-persisted-state.test.ts
@@ -0,0 +1,215 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ filterRecordByAllowedKeys,
+ migrateLegacyTextlessVersions,
+ normalizePersistedImageMap,
+ normalizePersistedImageVersions,
+ normalizePersistedRenderLayers,
+ normalizePersistedSlideMaterials,
+ normalizePersistedSlides,
+ normalizePersistedStringArray,
+ normalizePersistedStringMap,
+ normalizePersistedUploadedTemplates,
+ shouldInlinePersistImageUrl,
+} from "../client/workspaces/ppt/canvas/persisted-state";
+
+/**
+ * These readers stand between a user's saved deck and the workspace. Every one
+ * of them is deliberately defensive: the stored shape has changed across
+ * releases, and one malformed entry must not take a whole deck down.
+ */
+
+test("slides keep their fields and drop entries without an id", () => {
+ const slides = normalizePersistedSlides([
+ { id: "s1", title: "Cover", content: ["a", "b"], note: "n", layout: "title", description: "d" },
+ { id: "s2" },
+ { title: "no id" },
+ null,
+ "nonsense",
+ ]);
+
+ assert.equal(slides.length, 2);
+ assert.deepEqual(slides[0], {
+ id: "s1",
+ title: "Cover",
+ content: ["a", "b"],
+ note: "n",
+ layout: "title",
+ description: "d",
+ });
+ // A slide with only an id still loads, with empty defaults.
+ assert.deepEqual(slides[1], {
+ id: "s2",
+ title: "",
+ content: [],
+ note: undefined,
+ layout: undefined,
+ description: undefined,
+ });
+});
+
+test("slide content keeps only strings", () => {
+ const [slide] = normalizePersistedSlides([{ id: "s1", content: ["ok", 42, null, "also ok"] }]);
+ assert.deepEqual(slide.content, ["ok", "also ok"]);
+});
+
+test("non-array input yields no slides rather than throwing", () => {
+ assert.deepEqual(normalizePersistedSlides(null), []);
+ assert.deepEqual(normalizePersistedSlides({ id: "s1" }), []);
+ assert.deepEqual(normalizePersistedSlides("[]"), []);
+});
+
+test("image maps keep only string-to-string pairs", () => {
+ assert.deepEqual(
+ normalizePersistedImageMap({ s1: "data:image/png;base64,x", s2: 42, s3: null }),
+ { s1: "data:image/png;base64,x" },
+ );
+ assert.deepEqual(normalizePersistedImageMap(["not", "an", "object"]), {});
+ assert.deepEqual(normalizePersistedImageMap(null), {});
+});
+
+test("image versions require id, url, timestamp and a known type", () => {
+ const versions = normalizePersistedImageVersions({
+ s1: [
+ { id: "v1", url: "u", timestamp: 1, type: "generated" },
+ { id: "v2", url: "u", timestamp: 2, type: "edited", instruction: "make it blue" },
+ { id: "v3", url: "u", timestamp: 3, type: "unknown-type" },
+ { id: "v4", url: "u", type: "generated" },
+ { url: "u", timestamp: 5, type: "generated" },
+ ],
+ s2: "not an array",
+ });
+
+ assert.deepEqual(Object.keys(versions), ["s1"]);
+ assert.deepEqual(versions.s1.map((v) => v.id), ["v1", "v2"]);
+ assert.equal(versions.s1[1].instruction, "make it blue");
+});
+
+test("render layers derive their elements when none were stored", () => {
+ const layers = normalizePersistedRenderLayers({
+ s1: {
+ v1: {
+ backgroundImageUrl: "bg.png",
+ textBlocks: [{ text: "Title", x: 0, y: 0, w: 1, h: 0.2 }],
+ },
+ },
+ });
+
+ assert.equal(layers.s1.v1.backgroundImageUrl, "bg.png");
+ assert.equal(layers.s1.v1.status, "ready", "an unrecognised status defaults to ready");
+ assert.ok(layers.s1.v1.elements.length > 0, "elements are derived from the text blocks");
+});
+
+test("render layers keep a pending or failed status", () => {
+ const layers = normalizePersistedRenderLayers({
+ s1: {
+ v1: { backgroundImageUrl: "", textBlocks: [], status: "pending" },
+ v2: { backgroundImageUrl: "", textBlocks: [], status: "failed", error: "boom" },
+ v3: { backgroundImageUrl: "", textBlocks: [], status: "nonsense" },
+ },
+ });
+
+ assert.equal(layers.s1.v1.status, "pending");
+ assert.equal(layers.s1.v2.status, "failed");
+ assert.equal(layers.s1.v2.error, "boom");
+ assert.equal(layers.s1.v3.status, "ready");
+});
+
+test("string maps can require a non-blank value", () => {
+ const input = { a: "x", b: " ", c: 1 };
+ assert.deepEqual(normalizePersistedStringMap(input), { a: "x", b: " " });
+ assert.deepEqual(normalizePersistedStringMap(input, true), { a: "x" });
+});
+
+test("filterRecordByAllowedKeys keeps only what still exists", () => {
+ assert.deepEqual(
+ filterRecordByAllowedKeys({ s1: 1, s2: 2, gone: 3 }, new Set(["s1", "s2"])),
+ { s1: 1, s2: 2 },
+ );
+});
+
+test("slide materials need id, name and dataUrl", () => {
+ const materials = normalizePersistedSlideMaterials({
+ s1: [
+ { id: "m1", name: "logo", dataUrl: "data:image/png;base64,x", sourcePage: 2 },
+ { id: "m2", name: "missing url" },
+ { name: "missing id", dataUrl: "d" },
+ ],
+ });
+
+ assert.equal(materials.s1.length, 1);
+ assert.equal(materials.s1[0].fileName, "logo", "fileName falls back to name");
+ assert.equal(materials.s1[0].sourcePage, 2);
+});
+
+test("uploaded templates and string arrays are coerced", () => {
+ assert.deepEqual(
+ normalizePersistedUploadedTemplates([{ id: "t1", name: "n", dataUrl: "d" }, { id: "t2" }]),
+ [{ id: "t1", name: "n", dataUrl: "d" }],
+ );
+ assert.deepEqual(normalizePersistedStringArray(["a", 1, null]), ["a", "1", "null"]);
+ assert.deepEqual(normalizePersistedStringArray("nope"), []);
+});
+
+test("only a blob or http URL needs inlining", () => {
+ assert.equal(shouldInlinePersistImageUrl("blob:http://x/1"), true);
+ assert.equal(shouldInlinePersistImageUrl("https://example.test/a.png"), true);
+ assert.equal(shouldInlinePersistImageUrl("data:image/png;base64,x"), false);
+ assert.equal(shouldInlinePersistImageUrl(""), false);
+});
+
+test("the textless migration folds a derived layer back onto its source", () => {
+ // Older releases stored the text layer against a separate "derived_textless"
+ // version. The migration moves those text blocks onto the source version and
+ // drops the derived one, so the deck keeps its editable text.
+ const migrated = migrateLegacyTextlessVersions({
+ imageVersions: {
+ s1: [
+ { id: "v1", url: "bg.png", timestamp: 1, type: "generated" },
+ { id: "v2", url: "textless.png", timestamp: 2, type: "derived_textless", sourceVersionId: "v1" },
+ ],
+ },
+ renderLayers: {
+ s1: {
+ v1: { backgroundImageUrl: "bg.png", textBlocks: [], elements: [], status: "ready" },
+ v2: {
+ backgroundImageUrl: "textless.png",
+ textBlocks: [{ text: "Title", x: 0, y: 0, w: 1, h: 0.2 }],
+ elements: [],
+ status: "ready",
+ },
+ },
+ },
+ currentImageVersionId: { s1: "v2" },
+ });
+
+ assert.deepEqual(migrated.imageVersions.s1.map((v: { id: string }) => v.id), ["v1"],
+ "the derived version is gone");
+ assert.equal(migrated.renderLayers.s1.v1.textBlocks.length, 1,
+ "its text blocks moved onto the source version");
+ assert.equal(migrated.currentImageVersionId.s1, "v1",
+ "and the selection follows, rather than pointing at a version that no longer exists");
+});
+
+test("the migration leaves a deck without derived versions alone", () => {
+ const state = {
+ imageVersions: { s1: [{ id: "v1", url: "u", timestamp: 1, type: "generated" }] },
+ renderLayers: { s1: { v1: { backgroundImageUrl: "u", textBlocks: [], elements: [], status: "ready" } } },
+ currentImageVersionId: { s1: "v1" },
+ somethingElse: "preserved",
+ };
+
+ const migrated = migrateLegacyTextlessVersions(state);
+ assert.deepEqual(migrated.imageVersions, state.imageVersions);
+ assert.equal(migrated.currentImageVersionId.s1, "v1");
+ assert.equal(migrated.somethingElse, "preserved", "unrelated keys pass through");
+});
+
+test("the migration tolerates junk instead of throwing", () => {
+ assert.equal(migrateLegacyTextlessVersions(null), null);
+ assert.equal(migrateLegacyTextlessVersions("nonsense"), "nonsense");
+ const migrated = migrateLegacyTextlessVersions({ imageVersions: "bad", renderLayers: [] });
+ assert.deepEqual(migrated.imageVersions, {});
+ assert.deepEqual(migrated.renderLayers, {});
+});
diff --git a/tests/support/raw-md-loader.mjs b/tests/support/raw-md-loader.mjs
new file mode 100644
index 0000000..b003293
--- /dev/null
+++ b/tests/support/raw-md-loader.mjs
@@ -0,0 +1,31 @@
+/**
+ * Teaches Node the `?raw` import suffix.
+ *
+ * The client loads its agent prompts as strings with Vite's `?raw` — plain
+ * Node sees a ".md" it cannot parse, which otherwise puts every module that
+ * transitively reaches a prompt out of reach of the test runner.
+ */
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+
+const RAW = "?raw";
+
+export async function resolve(specifier, context, next) {
+ if (!specifier.endsWith(RAW)) return next(specifier, context);
+
+ // Resolve without the suffix so the tsconfig path aliases still apply,
+ // then put it back so `load` below recognises the request.
+ const resolved = await next(specifier.slice(0, -RAW.length), context);
+ return { ...resolved, url: `${resolved.url}${RAW}`, shortCircuit: true };
+}
+
+export async function load(url, context, next) {
+ if (!url.endsWith(RAW)) return next(url, context);
+
+ const text = await readFile(fileURLToPath(url.slice(0, -RAW.length)), "utf8");
+ return {
+ format: "module",
+ shortCircuit: true,
+ source: `export default ${JSON.stringify(text)};`,
+ };
+}
diff --git a/tests/support/register.mjs b/tests/support/register.mjs
new file mode 100644
index 0000000..88aeb4a
--- /dev/null
+++ b/tests/support/register.mjs
@@ -0,0 +1,4 @@
+import { register } from "node:module";
+
+/** Installed via `node --import` so the hooks are in place before any test loads. */
+register("./raw-md-loader.mjs", import.meta.url);