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.
TypeScript ai-agentsai-diagramai-presentationbomcadcanvasdiagramdiagram-generatordrawioflowchartinfographicspptppt-generatorpresentation-generatorreactsvgedittext-to-diagramtypescriptworkflow
refactor(cad): lift the turn's prompt assembly out of handleSend
codingFeng101c86fc9f3f20b
diff --git a/client/workspaces/cad/chat/ChatPanel.tsx b/client/workspaces/cad/chat/ChatPanel.tsxindex 31dddff..ea0cceb 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 {+ assembleDisplay,+ assemblePrompt,+ buildContextAttachments,+ buildImageTags,+ type Attachment,+} from "@/workspaces/cad/lib/chat-prompt";import {extractCadPatchFullSvg,extractRawSvg,@@ -42,13 +49,6 @@ import { createAssistantUpdater, writeLastAssistant } from '@/shared/chat/assistimport { getChatErrorText } from '@/shared/chat/chat-errors';import { parseMarkdownBomTable } from '@/shared/chat/bom-table';-interface Attachment {- id: string;- type: 'xml' | 'python' | 'json' | 'image' | 'text';- content: string;- name: string;-}-type CodeActionResult = { ok: boolean; retry?: boolean; error?: string; svg?: string };type MaybePromise<T> = T | Promise<T>;@@ -659,16 +659,7 @@ export function ChatPanel({}}- const contextAttachmentsText = attachments.length > 0- ? attachments- .slice(0, 12)- .map((a, idx) => {- const header = `[Context ${idx + 1}: ${a.name} | ${a.type}]`;- const body = String(a.content || "").slice(0, 12000);- return `${header}\n\`\`\`${a.type}\n${body}\n\`\`\``;- })- .join("\n\n")- : "";+ const contextAttachmentsText = buildContextAttachments(attachments);const effectiveCadPlan = cadApprovedPlanRef.current ?? cadContext?.plan;const cadContextText =@@ -692,27 +683,20 @@ export function ChatPanel({? buildRecentHistoryContext(messages): "";- const promptParts = [+ const promptContent = assemblePrompt({rawInput,- fileTexts.length > 0 ? fileTexts.join("\n\n") : "",- contextAttachmentsText,- cadContextText,- cadHistoryContextText,- ].filter(Boolean);- const promptContent = promptParts.join("\n\n");+ fileTexts,+ contextAttachments: contextAttachmentsText,+ cadContext: cadContextText,+ history: cadHistoryContextText,+ });lastUploadedImagesRef.current = currentUploadedImages;- const safeTagText = (text: string) =>- String(text || "").split("|").join(",").split("]]").join("").replace(/\r?\n/g, " ");- const imageTags = currentUploadedImageItems- .map((it) => `[[IMAGE|${safeTagText(it.name)}|${it.url}]]`)- .join("\n");- const displayParts = [- imageTags,+ const displayContent = assembleDisplay(+ buildImageTags(currentUploadedImageItems),rawInput,- displayFileTexts.length > 0 ? displayFileTexts.join("\n\n") : "",- ].filter(Boolean);- const displayContent = displayParts.join("\n\n");+ displayFileTexts,+ );const userMessageForDisplay: ChatMessage = { role: 'user', content: displayContent };const displayMessages = [...messages, userMessageForDisplay];diff --git a/client/workspaces/cad/lib/chat-prompt.ts b/client/workspaces/cad/lib/chat-prompt.tsnew file mode 100644index 0000000..63907d2--- /dev/null+++ b/client/workspaces/cad/lib/chat-prompt.ts@@ -0,0 +1,104 @@+/**+ * Turning what the user typed and attached into the two texts a turn needs:+ * the prompt the model sees, and the message the transcript shows.+ *+ * They differ deliberately. The prompt carries extracted file text and the+ * current CAD context; the transcript carries image tags and the same files+ * as collapsible attachments, so the user sees what they sent rather than+ * the wall of text the model got.+ */++/** A document the user pinned to the conversation as reference material. */+export interface Attachment {+ id: string;+ type: "xml" | "python" | "json" | "image" | "text";+ content: string;+ name: string;+}++/** How much of the attached context the prompt will carry. */+const MAX_CONTEXT_ATTACHMENTS = 12;+const MAX_CONTEXT_CHARS = 12_000;++export interface UploadedImage {+ name: string;+ url: string;+}++/**+ * The pieces of a turn, in the order they are joined. Empty ones are dropped+ * rather than leaving blank gaps the model has to read past.+ */+export interface PromptSections {+ rawInput: string;+ fileTexts: string[];+ contextAttachments: string;+ cadContext: string;+ history: string;+}++export function assemblePrompt(sections: PromptSections): string {+ return [+ sections.rawInput,+ sections.fileTexts.length > 0 ? sections.fileTexts.join("\n\n") : "",+ sections.contextAttachments,+ sections.cadContext,+ sections.history,+ ]+ .filter(Boolean)+ .join("\n\n");+}++/** What the transcript shows: the images sent, the text typed, the files attached. */+export function assembleDisplay(+ imageTags: string,+ rawInput: string,+ displayFileTexts: string[],+): string {+ return [imageTags, rawInput, displayFileTexts.length > 0 ? displayFileTexts.join("\n\n") : ""]+ .filter(Boolean)+ .join("\n\n");+}++/**+ * Attached context, capped twice: at a number of files and at a size each.+ *+ * Both caps matter for the same reason -- everything here is spent from the+ * model's context window, and a single large paste would otherwise crowd out+ * the user's actual question.+ */+export function buildContextAttachments(attachments: Attachment[]): string {+ if (!attachments || attachments.length === 0) return "";++ return attachments+ .slice(0, MAX_CONTEXT_ATTACHMENTS)+ .map((attachment, index) => {+ const header = `[Context ${index + 1}: ${attachment.name} | ${attachment.type}]`;+ const body = String(attachment.content || "").slice(0, MAX_CONTEXT_CHARS);+ return `${header}\n\`\`\`${attachment.type}\n${body}\n\`\`\``;+ })+ .join("\n\n");+}++/**+ * Strips the characters that would break an `[[IMAGE|name|url]]` marker.+ *+ * The name comes from a filename, so it can contain anything; a pipe or a+ * `]]` in it would end the marker early and leave the rest as visible junk+ * in the transcript.+ */+export function safeTagText(text: string): string {+ return String(text || "")+ .split("|")+ .join(",")+ .split("]]")+ .join("")+ .replace(/\r?\n/g, " ");+}++/** One marker per uploaded image, for the transcript to render inline. */+export function buildImageTags(images: UploadedImage[]): string {+ return (images || [])+ .map((image) => `[[IMAGE|${safeTagText(image.name)}|${image.url}]]`)+ .join("\n");+}diff --git a/tests/cad-chat-prompt.test.ts b/tests/cad-chat-prompt.test.tsnew file mode 100644index 0000000..103cc58--- /dev/null+++ b/tests/cad-chat-prompt.test.ts@@ -0,0 +1,124 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import {+ assembleDisplay,+ assemblePrompt,+ buildContextAttachments,+ buildImageTags,+ safeTagText,+ type Attachment,+} from "../client/workspaces/cad/lib/chat-prompt";++/**+ * A CAD turn produces two texts from the same input: the prompt the model+ * reads and the message the transcript shows. They differ on purpose, so the+ * user is not shown the extracted file text and the model is not shown the+ * image markers.+ */++const sections = (over: Partial<Parameters<typeof assemblePrompt>[0]> = {}) => ({+ rawInput: "",+ fileTexts: [],+ contextAttachments: "",+ cadContext: "",+ history: "",+ ...over,+});++test("the sections join in a fixed order", () => {+ const prompt = assemblePrompt(+ sections({+ rawInput: "make it wider",+ fileTexts: ["[File: a.txt]\nAAA"],+ contextAttachments: "[Context 1: b.json | json]",+ cadContext: "Current 2D SVG:",+ history: "Recent chat history:",+ }),+ );+ const order = ["make it wider", "[File: a.txt]", "[Context 1:", "Current 2D SVG:", "Recent chat history:"];+ const positions = order.map((needle) => prompt.indexOf(needle));+ assert.deepEqual([...positions].sort((a, b) => a - b), positions, prompt);+ assert.ok(positions.every((p) => p >= 0));+});++test("empty sections leave no blank gaps", () => {+ const prompt = assemblePrompt(sections({ rawInput: "hello", history: "history" }));+ assert.equal(prompt, "hello\n\nhistory", "no run of blank lines where sections were skipped");+});++test("a turn with nothing in it produces nothing", () => {+ assert.equal(assemblePrompt(sections()), "");+});++test("several files are separated from each other", () => {+ const prompt = assemblePrompt(sections({ fileTexts: ["one", "two"] }));+ assert.equal(prompt, "one\n\ntwo");+});++test("the transcript shows images, the words typed, and the files", () => {+ const display = assembleDisplay("[[IMAGE|a.png|data:x]]", "look at this", ["[PDF: r.pdf]\ntext"]);+ assert.ok(display.indexOf("[[IMAGE") < display.indexOf("look at this"));+ assert.ok(display.indexOf("look at this") < display.indexOf("[PDF: r.pdf]"));+});++test("a turn with only text shows only text", () => {+ assert.equal(assembleDisplay("", "just words", []), "just words");+});++const attachment = (over: Partial<Attachment> = {}): Attachment => ({+ id: "a1",+ name: "notes.txt",+ type: "text",+ content: "body",+ ...over,+});++test("an attachment is fenced with its own type", () => {+ const out = buildContextAttachments([attachment({ type: "json", content: "{}" })]);+ assert.ok(out.startsWith("[Context 1: notes.txt | json]"), out);+ assert.ok(out.includes("```json\n{}\n```"), out);+});++test("attachments are numbered as the user sees them", () => {+ const out = buildContextAttachments([attachment({ name: "a" }), attachment({ name: "b" })]);+ assert.ok(out.includes("[Context 1: a"), out);+ assert.ok(out.includes("[Context 2: b"), out);+});++test("only the first twelve attachments are carried", () => {+ // Everything here is spent from the model's context window.+ const many = Array.from({ length: 20 }, (_, i) => attachment({ id: `a${i}`, name: `f${i}` }));+ const out = buildContextAttachments(many);+ assert.ok(out.includes("f11"), "the twelfth is kept");+ assert.ok(!out.includes("f12"), "the thirteenth is not");+});++test("one huge paste cannot crowd out the question", () => {+ const out = buildContextAttachments([attachment({ content: "x".repeat(50_000) })]);+ assert.ok(out.length < 13_000, `expected a capped body, got ${out.length}`);+});++test("no attachments means no section at all", () => {+ assert.equal(buildContextAttachments([]), "");+});++test("a filename cannot break the image marker", () => {+ // The name comes from a file, so it can contain anything; a pipe or a `]]`+ // would end the marker early and leave the rest as junk in the transcript.+ assert.equal(safeTagText("a|b"), "a,b");+ assert.equal(safeTagText("weird]]name"), "weirdname");+ assert.equal(safeTagText("two\nlines"), "two lines");+ assert.equal(safeTagText(""), "");+});++test("one marker per image, one per line", () => {+ const tags = buildImageTags([+ { name: "a.png", url: "data:1" },+ { name: "b|c.png", url: "data:2" },+ ]);+ assert.deepEqual(tags.split("\n"), ["[[IMAGE|a.png|data:1]]", "[[IMAGE|b,c.png|data:2]]"]);+});++test("no images means no markers", () => {+ assert.equal(buildImageTags([]), "");+});