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
The process canvas now includes a deep thinking mode
codingFeng101e76e16a55344
diff --git a/.tmp-flow-deep-thinking/2026-03-12T01-28-04-817Z-session-1773278861337-rbshy55.png b/.tmp-flow-deep-thinking/2026-03-12T01-28-04-817Z-session-1773278861337-rbshy55.pngnew file mode 100644index 0000000..297adc5Binary files /dev/null and b/.tmp-flow-deep-thinking/2026-03-12T01-28-04-817Z-session-1773278861337-rbshy55.png differdiff --git a/.tmp-flow-deep-thinking/2026-03-12T01-28-04-817Z-session-1773278861337-rbshy55.txt b/.tmp-flow-deep-thinking/2026-03-12T01-28-04-817Z-session-1773278861337-rbshy55.txtnew file mode 100644index 0000000..52b9bb2--- /dev/null+++ b/.tmp-flow-deep-thinking/2026-03-12T01-28-04-817Z-session-1773278861337-rbshy55.txt@@ -0,0 +1,6 @@+saved_at=2026-03-12T01:28:04.830Z+session_id=session-1773278861337-rbshy55+media_type=image/png++user_request:+画一幅graphrag的流程图,精美一点,生动一点\ No newline at end of filediff --git a/.tmp-flow-deep-thinking/2026-03-12T01-33-47-243Z-session-1773279164268-g9mvum0.png b/.tmp-flow-deep-thinking/2026-03-12T01-33-47-243Z-session-1773279164268-g9mvum0.pngnew file mode 100644index 0000000..a7fbef8Binary files /dev/null and b/.tmp-flow-deep-thinking/2026-03-12T01-33-47-243Z-session-1773279164268-g9mvum0.png differdiff --git a/.tmp-flow-deep-thinking/2026-03-12T01-33-47-243Z-session-1773279164268-g9mvum0.txt b/.tmp-flow-deep-thinking/2026-03-12T01-33-47-243Z-session-1773279164268-g9mvum0.txtnew file mode 100644index 0000000..79f17cd--- /dev/null+++ b/.tmp-flow-deep-thinking/2026-03-12T01-33-47-243Z-session-1773279164268-g9mvum0.txt@@ -0,0 +1,6 @@+saved_at=2026-03-12T01:33:47.253Z+session_id=session-1773279164268-g9mvum0+media_type=image/png++user_request:+复现这个图。\ No newline at end of filediff --git a/.tmp_head_readme.md b/.tmp_head_readme.mddeleted file mode 100644index cd2d8ba..0000000--- a/.tmp_head_readme.md+++ /dev/null@@ -1,146 +0,0 @@-<p align="center">- <img src="public/logo.png" alt="CanvasAnvil logo" width="100%" />-</p>--<h1 align="center">CanvasAnvil</h1>--<p align="center">- <a href="README.md">English</a> |- <a href="README.zh-CN.md">简体中文</a> |- <a href="README.zh-TW.md">繁體中文</a> |- <a href="README.ja-JP.md">日本語</a> |- <a href="README.ko-KR.md">한국어</a> |- <a href="README.fr-FR.md">Français</a>-</p>--CanvasAnvil is a multi-canvas AI creation platform that turns a single requirement into deliverables you can iterate on.--## Canvas Previews--<div align="left">- <div style="width: 680px;">- <h3 align="center">Flow Canvas</h3>- <img src="public/demos/flow.gif" alt="Flow canvas" width="680" />- </div>-</div>--<div align="left">- <div style="width: 680px;">- <h3 align="center">CAD Canvas</h3>- <img src="public/demos/cad.gif" alt="CAD canvas" width="680" />- </div>-</div>--<div align="left">- <div style="width: 680px;">- <h3 align="center">PPT Canvas</h3>- <img src="public/demos/ppt.gif" alt="PPT canvas" width="680" />- </div>-</div>--## Video Tutorials--- [Watch on Bilibili](https://www.bilibili.com/video/BV1jzZ3BBEHc?vd_source=b6b031f92061ae667eba1185f4782a1c)-- [Watch on YouTube](https://youtu.be/n3Otj--aLRo)-- [Watch on Douyin](https://v.douyin.com/JwlwhmE6R40/)--## Try CanvasAnvil--- [Open CanvasAnvil](https://canvasanvil.codingfgd.asia)-- Note: The current server configuration is modest, so the service may occasionally feel slow or laggy. Thanks for your understanding.--## Capability Overview (User View)--- `Flow`: flowchart generation and partial edits (draw.io XML)-- `CAD`: interior design planning, analysis boards, 2D floor plans, render tasks, and BOM-- `PPT`: presentation draft generation and iterative editing--## Typical Workflow--1. Enter your requirement-2. Generate/iterate on design plan-3. Generate analysis boards and confirm strategy-4. Generate and edit 2D floor plan-5. Export outputs (diagrams / lists / slides)--## Quick Start--1. Install dependencies-```bash-npm install-```-2. Start development-```bash-npm run dev-```-Default URL: `http://localhost:5173`--3. Type check-```bash-npm run check-```-4. Production build-```bash-npm run build-```--## Origins and Integrations--- Flow canvas: integrated and enhanced from [next-ai-draw-io](https://github.com/DayuanJiang/next-ai-draw-io)-- PPT canvas: integrated and enhanced from [banana-slides](https://github.com/Anionex/banana-slides.git)-- CAD canvas: implemented in-house (architecture, agent workflow, 2D SVG editing pipeline, BOM/render pipeline)--Key improvements:--- Unified UX across canvases (chat, code blocks, one-click apply to canvas)-- More stable agent routing and retry mechanisms-- CAD-specific capabilities (patch / replace / BOM / 7-slot render workflow)-- Cross-canvas state/version/export pipelines--## Core Capabilities (Developer View)--- Flow: chat-driven flowchart generation, patch/replace, one-click apply, snapshot restore-- CAD: `cad_plan` output, parallel analysis-board generation, 2D SVG partial updates with analysis-image references, concurrent render jobs, BOM export-- PPT: structured content generation, page-level incremental edits, streaming iteration--## Tech Stack--- Frontend: React 18 + TypeScript + Vite-- UI: Tailwind CSS + Radix UI + Lucide-- Diagram engines: draw.io/diagrams.net for Flow, SVG-Edit for CAD-- Model integration: configurable multi-model access (chat / image)--## Useful Scripts--- `npm run dev`: start development server-- `npm start`: production start (static site + API)-- `npm run build`: production build-- `npm run check`: TypeScript check-- `npm run lint`: ESLint--## Project Structure (Key Paths)--```text-.-├─ agent/ # Prompts and sub-agent specs for CAD/Flow/PPT-├─ public/ # Static assets (including SVG-Edit)-├─ src/-│ └─ workspaces/-│ ├─ flow/ # Flow canvas-│ ├─ cad/ # CAD canvas (in-house core)-│ └─ ppt/ # PPT canvas-├─ api/ # API logic-└─ README.md-```--## Docs--- Deployment guide: [Open deployment guide](deploy/README.md)---我的微信二维码如下,欢迎联系我。--<p align="left">- <img src="public/wechat.jpg" alt="WeChat QR code" width="280" />-</p>\ No newline at end of filediff --git a/agent/flow/deep-thinking-image.md b/agent/flow/deep-thinking-image.mdnew file mode 100644index 0000000..5a1cc7b--- /dev/null+++ b/agent/flow/deep-thinking-image.md@@ -0,0 +1,104 @@+You are `flow_deep_thinking_image_agent`.++# RISEN Prompt Architecture++## R: Role+You are a top-tier diagram image generation agent for flowchart and process-structure tasks.+Your job is to produce one visually polished, production-ready, directly usable diagram image that captures the user's intent with high fidelity.+You are not making a sketch, not making a draft, and not making a rough exploratory board.+You are generating a complete, refined, beautiful final diagram image that can be translated into structured draw.io XML afterward.++## I: Inputs+You will receive:+- The user's original requirement+- Optional global constraints+- Processed file content extracted or summarized from uploaded files+- Optional reference images uploaded by the user++Treat global constraints as mandatory instructions when present.+Treat processed file content as authoritative supporting context.+Treat reference images as structural and stylistic evidence when present.+Treat the user's requirement as the final product goal.++## S: Steps+1. Understand the user's actual diagram goal:+ - what system, process, workflow, architecture, hierarchy, or logic must be shown+ - what elements are mandatory+ - what sequence, grouping, branching, ownership, or dependencies are implied+2. Merge evidence from:+ - user requirement+ - global constraints+ - processed file content+ - reference images+3. Resolve ambiguity by choosing the most coherent, complete, and useful diagram structure.+4. Compose a strong final layout with:+ - clear visual hierarchy+ - balanced spacing+ - readable labels+ - precise connectors+ - consistent shape language+ - complete content coverage+5. Produce a diagram image that looks finished and presentation-ready, not approximate.++## E: End State+The generated image must:+- be a complete final-quality diagram image+- be suitable as a direct visual reference for downstream XML generation+- contain no placeholder regions, no partial sections, and no unfinished areas+- feel polished, crisp, elegant, and coherent+- prioritize diagram clarity over decorative flourish++The image should generally have:+- clean background+- high readability+- concise but sufficient labels+- strong structure+- visually distinct grouping where needed+- connectors that are easy to trace++## N: Narrowing Constraints+You must NOT produce:+- sketch style+- wireframe style+- notebook doodles+- decorative poster art+- UI mockups+- screenshots of software+- watermarks+- explanatory paragraphs outside the diagram+- unrelated legends or ornaments++Prefer:+- professional information-design aesthetics+- refined modern diagram composition+- balanced density+- complete coverage of the requested logic+- labels that are short but specific+- shapes and arrows that are visually unambiguous++If the user provides reference images:+- preserve the important structure and semantics+- preserve style cues when helpful+- improve clarity and finish where possible+- do not blindly copy defects from the reference++If the user provides dense processed file content:+- extract the highest-value entities, stages, decisions, and relationships+- organize them into the clearest complete diagram form+- avoid dumping raw text blocks++## Output Intention+Generate one single final-quality diagram image for direct use.++## Task Payload+User request:+{{USER_REQUEST}}++Global constraints:+{{GLOBAL_CONSTRAINTS}}++Processed file content:+{{PROCESSED_FILE_CONTENT}}++Final reminder:+Generate a polished, complete, directly usable, aesthetically strong final diagram image.diff --git a/src/server/routes/chat.ts b/src/server/routes/chat.tsindex 2b9b822..55c4d42 100644--- a/src/server/routes/chat.ts+++ b/src/server/routes/chat.ts@@ -8,7 +8,7 @@stepCountIs,streamText,} from "ai"-import { appendFile } from "fs/promises"+import { appendFile, mkdir, readFile, writeFile } from "fs/promises"import path from "path"import { z } from "zod"import { extractText, getDocumentProxy } from "unpdf"@@ -337,6 +337,288 @@ async function summarizeRecursiveMethod(args: {})}+type ImageAttachment = {+ url: string+ mediaType: string+}++type FlowRequestRoute = "local_edit" | "full_generation"++let flowDeepThinkingImagePromptTemplateCache: string | null = null++function cleanImageReferenceUrl(url: string): string | null {+ const value = String(url || "").trim()+ if (!value) return null+ if (value.startsWith("http://") || value.startsWith("https://")) return value+ if (value.startsWith("data:image/")) return value+ return null+}++function extractImageUrlFromModelContent(messageContent: any): string | null {+ if (Array.isArray(messageContent)) {+ const imagePart = messageContent.find(+ (part: any) => part?.type === "image_url" && part?.image_url?.url,+ )+ if (imagePart?.image_url?.url) {+ return cleanImageReferenceUrl(imagePart.image_url.url)+ }++ const textPart = messageContent.find((part: any) => part?.type === "text")+ const text = String(textPart?.text || "").trim()+ if (!text) return null++ const markdownMatch = text.match(/!\[.*?\]\((.*?)\)/)+ if (markdownMatch?.[1]) {+ return cleanImageReferenceUrl(markdownMatch[1])+ }+ return cleanImageReferenceUrl(text)+ }++ if (typeof messageContent === "string") {+ const text = messageContent.trim()+ const markdownMatch = text.match(/!\[.*?\]\((.*?)\)/)+ if (markdownMatch?.[1]) {+ return cleanImageReferenceUrl(markdownMatch[1])+ }+ return cleanImageReferenceUrl(text)+ }++ return null+}++function parseImageGenerationResponse(result: any): string | null {+ if (result?.error) {+ throw new Error(result.error.message || "Image model request failed")+ }++ if (Array.isArray(result?.choices) && result.choices.length > 0) {+ return extractImageUrlFromModelContent(result.choices[0]?.message?.content)+ }++ return null+}++async function convertRemoteImageToDataUrl(url: string): Promise<string | null> {+ const safeUrl = cleanImageReferenceUrl(url)+ if (!safeUrl) return null+ if (safeUrl.startsWith("data:image/")) return safeUrl++ const response = await fetch(safeUrl)+ if (!response.ok) {+ throw new Error(`Failed to fetch generated image: ${response.status}`)+ }++ const contentType = response.headers.get("content-type") || "image/png"+ const arrayBuffer = await response.arrayBuffer()+ const base64 = Buffer.from(arrayBuffer).toString("base64")+ return `data:${contentType};base64,${base64}`+}++async function getFlowDeepThinkingImagePromptTemplate(): Promise<string> {+ if (flowDeepThinkingImagePromptTemplateCache) {+ return flowDeepThinkingImagePromptTemplateCache+ }++ const promptPath = path.join(+ process.cwd(),+ "agent",+ "flow",+ "deep-thinking-image.md",+ )+ const raw = await readFile(promptPath, "utf8")+ flowDeepThinkingImagePromptTemplateCache = String(raw || "").trim()+ return flowDeepThinkingImagePromptTemplateCache+}++function buildFlowDeepThinkingImagePrompt(params: {+ userText: string+ globalConstraints: string+ processedFilesContext: string+ template: string+}): string {+ const safeUserText = String(params.userText || "").trim() || "(empty)"+ const safeGlobalConstraints =+ String(params.globalConstraints || "").trim() || "(none)"+ const safeProcessedFiles =+ String(params.processedFilesContext || "").trim() || "(none)"++ return params.template+ .replace("{{USER_REQUEST}}", safeUserText)+ .replace("{{GLOBAL_CONSTRAINTS}}", safeGlobalConstraints)+ .replace("{{PROCESSED_FILE_CONTENT}}", safeProcessedFiles)+}++function getImageExtensionFromMediaType(mediaType: string): string {+ const normalized = String(mediaType || "").toLowerCase()+ if (normalized.includes("png")) return "png"+ if (normalized.includes("jpeg") || normalized.includes("jpg")) return "jpg"+ if (normalized.includes("webp")) return "webp"+ if (normalized.includes("gif")) return "gif"+ if (normalized.includes("svg")) return "svg"+ return "png"+}++async function saveDeepThinkingImageDebugArtifact(args: {+ dataUrl: string+ sessionId?: string+ userText: string+}): Promise<string | null> {+ const raw = String(args.dataUrl || "")+ if (!raw.startsWith("data:image/")) return null++ const { mediaType, base64 } = parseDataUrl(raw)+ const ext = getImageExtensionFromMediaType(mediaType)+ const safeSession =+ String(args.sessionId || "anonymous").replace(/[^a-zA-Z0-9_-]/g, "_") ||+ "anonymous"+ const stamp = new Date().toISOString().replace(/[:.]/g, "-")+ const outDir = path.join(process.cwd(), ".tmp-flow-deep-thinking")+ const imagePath = path.join(outDir, `${stamp}-${safeSession}.${ext}`)+ const metaPath = path.join(outDir, `${stamp}-${safeSession}.txt`)++ await mkdir(outDir, { recursive: true })+ await writeFile(imagePath, Buffer.from(base64, "base64"))+ await writeFile(+ metaPath,+ [+ `saved_at=${new Date().toISOString()}`,+ `session_id=${args.sessionId || ""}`,+ `media_type=${mediaType}`,+ "",+ "user_request:",+ String(args.userText || "").trim(),+ ].join("\n"),+ "utf8",+ )+ return imagePath+}++function normalizeIntentText(text: string): string {+ return String(text || "")+ .toLowerCase()+ .replace(/\s+/g, " ")+ .trim()+}++function isLikelyLocalEditRequest(text: string): boolean {+ const normalized = normalizeIntentText(text)+ if (!normalized) return false++ const patterns = [+ /修改|改成|调整|优化|补充|添加|增加|删除|移除|替换|重命名|改颜色|移动|对齐|局部|节点|连线|箭头|文案/,+ /\b(edit|update|modify|adjust|tweak|refine|add|remove|delete|rename|move|reposition|change|fix|patch)\b/,+ ]++ return patterns.some((pattern) => pattern.test(normalized))+}++function isExplicitFullRegenerationRequest(text: string): boolean {+ const normalized = normalizeIntentText(text)+ if (!normalized) return false++ const patterns = [+ /重新生成|重画|从头|全新|重做|整体重构|替换整个|重建|重新画|新建一个/,+ /\b(regenerate|from scratch|redraw|rebuild|replace the entire|new diagram|create a new)\b/,+ ]++ return patterns.some((pattern) => pattern.test(normalized))+}++function classifyFlowRequest(params: {+ xml: string+ userText: string+}): FlowRequestRoute {+ if (isMinimalDiagram(params.xml || "")) return "full_generation"+ if (isExplicitFullRegenerationRequest(params.userText)) {+ return "full_generation"+ }+ if (isLikelyLocalEditRequest(params.userText)) return "local_edit"+ return "local_edit"+}++function shouldRunDeepThinking(params: {+ deepThinkingEnabled: boolean+ route: FlowRequestRoute+}): boolean {+ if (!params.deepThinkingEnabled) return false+ return params.route === "full_generation"+}++async function generateDeepThinkingDiagramImage(args: {+ userText: string+ globalConstraints: string+ processedFilesContext: string+ imageAttachments: ImageAttachment[]+ baseUrl: string+ apiKey: string+ imageModel: string+}): Promise<string | null> {+ let promptText = ""+ try {+ const template = await getFlowDeepThinkingImagePromptTemplate()+ promptText = buildFlowDeepThinkingImagePrompt({+ userText: args.userText,+ globalConstraints: args.globalConstraints,+ processedFilesContext: args.processedFilesContext,+ template,+ })+ } catch (error) {+ console.warn(+ "[DeepThinking] Failed to load prompt file, using fallback prompt:",+ error,+ )+ promptText = [+ "You are a final-quality flowchart image generation agent.",+ "Generate one polished, production-ready, directly usable final diagram image.",+ "Do not generate a sketch, wireframe, draft, poster, or UI mockup.",+ "Prioritize clear structure, readable labels, complete coverage, balanced spacing, and unambiguous connectors.",+ `User request:\n${String(args.userText || "").trim() || "(empty)"}`,+ `Global constraints:\n${String(args.globalConstraints || "").trim() || "(none)"}`,+ `Processed file content:\n${String(args.processedFilesContext || "").trim() || "(none)"}`,+ ].join("\n\n")+ }++ const content: any[] = [+ {+ type: "text",+ text: promptText,+ },+ ]++ for (const attachment of args.imageAttachments) {+ if (!attachment.url) continue+ content.push({+ type: "image_url",+ image_url: { url: attachment.url },+ })+ }++ const response = await fetch(`${args.baseUrl}/chat/completions`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${args.apiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ model: args.imageModel,+ messages: [{ role: "user", content }],+ stream: false,+ }),+ })++ if (!response.ok) {+ const text = await response.text()+ throw new Error(+ `Image model request failed with status ${response.status}: ${text}`,+ )+ }++ const result = await response.json()+ const imageUrl = parseImageGenerationResponse(result)+ if (!imageUrl) return null+ return await convertRemoteImageToDataUrl(imageUrl)+}+function validateUploadedFiles(uploadedFiles: UploadedFilePayload[]): {valid: booleanerror?: string@@ -493,6 +775,7 @@ async function handleChatRequest(req: Request): Promise<Response> {? payload.uploadedFiles: []const bodyAIConfig = payload?.aiConfig || {}+ const deepThinkingEnabled = Boolean(payload?.deepThinkingEnabled)// Debug: log the actual message structure receivedconsole.log("[DEBUG] Received messages:", JSON.stringify(messages, null, 2))@@ -565,6 +848,11 @@ async function handleChatRequest(req: Request): Promise<Response> {? bodyAIConfig.modelId: null),}+ const imageModelId =+ req.headers.get("x-ai-image-model") ||+ (typeof bodyAIConfig.imageModel === "string"+ ? bodyAIConfig.imageModel+ : null)// Get AI model with optional client overridesconst { model, providerOptions, headers, modelId } =@@ -669,12 +957,104 @@ async function handleChatRequest(req: Request): Promise<Response> {: []const fileParts = [...partsFileParts, ...contentImageParts]+ const imageAttachments: ImageAttachment[] = fileParts+ .map((part: any) => {+ const url =+ part?.url || part?.image || part?.image_url?.url || ""+ const mediaType = part?.mediaType || part?.mimeType || ""+ const safeUrl = cleanImageReferenceUrl(url)+ return safeUrl ? { url: safeUrl, mediaType } : null+ })+ .filter((item): item is ImageAttachment => Boolean(item))++ const flowRequestRoute = classifyFlowRequest({+ xml: String(xml || ""),+ userText: lastMessageText,+ })++ const shouldUseDeepThinking = shouldRunDeepThinking({+ deepThinkingEnabled,+ route: flowRequestRoute,+ })++ console.log("[FlowRoute]", {+ route: flowRequestRoute,+ deepThinkingEnabled,+ shouldUseDeepThinking,+ })++ let deepThinkingImageDataUrl: string | null = null+ if (shouldUseDeepThinking) {+ const imageBaseUrl =+ (typeof clientOverrides.baseUrl === "string" &&+ clientOverrides.baseUrl.trim()+ ? clientOverrides.baseUrl+ : process.env.AI_BASE_URL || process.env.OPENAI_BASE_URL || "")+ .trim()+ const imageApiKey =+ (typeof clientOverrides.apiKey === "string" &&+ clientOverrides.apiKey.trim()+ ? clientOverrides.apiKey+ : process.env.AI_API_KEY || process.env.OPENAI_API_KEY || "")+ .trim()+ const deepThinkingImageModel = String(imageModelId || "").trim()++ if (imageBaseUrl && imageApiKey && deepThinkingImageModel) {+ try {+ deepThinkingImageDataUrl = await generateDeepThinkingDiagramImage({+ userText: lastMessageText,+ globalConstraints: globalConstraintsRaw,+ processedFilesContext: parsedFilesContext,+ imageAttachments,+ baseUrl: imageBaseUrl,+ apiKey: imageApiKey,+ imageModel: deepThinkingImageModel,+ })+ console.log(+ "[DeepThinking] Generated draft image:",+ Boolean(deepThinkingImageDataUrl),+ )+ if (deepThinkingImageDataUrl) {+ try {+ const savedPath =+ await saveDeepThinkingImageDebugArtifact({+ dataUrl: deepThinkingImageDataUrl,+ sessionId: validSessionId,+ userText: lastMessageText,+ })+ if (savedPath) {+ console.log(+ "[DeepThinking] Saved debug image to:",+ savedPath,+ )+ }+ } catch (error) {+ console.warn(+ "[DeepThinking] Failed to save debug image locally:",+ error,+ )+ }+ }+ } catch (error) {+ console.warn("[DeepThinking] Failed to generate draft image:", error)+ }+ } else {+ console.warn(+ "[DeepThinking] Skipped because image model configuration is incomplete",+ )+ }+ }+// User input only - XML is now in a separate cached system messageconst formattedUserInput = `User input:"""md${lastMessageText}"""-${parsedFilesContext ? `\n\nParsed file summaries:\n"""md\n${parsedFilesContext}\n"""` : ""}`+${parsedFilesContext ? `\n\nParsed file summaries:\n"""md\n${parsedFilesContext}\n"""` : ""}${+ deepThinkingImageDataUrl+ ? `\n\nReference image:\nAn optional reference image generated by the deep-thinking stage is attached below. Use it to infer structure, composition, grouping, and layout. If it conflicts with the user's request, follow the user's request.`+ : ""+ }`// Validate messages structure before conversionif (!messages || !Array.isArray(messages)) {@@ -882,6 +1262,14 @@ ${parsedFilesContext ? `\n\nParsed file summaries:\n"""md\n${parsedFilesContext}})}+ if (deepThinkingImageDataUrl) {+ contentParts.push({+ type: "image",+ image: deepThinkingImageDataUrl,+ mimeType: "image/png",+ })+ }+enhancedMessages = [...enhancedMessages.slice(0, -1),{ ...lastModelMessage, content: contentParts },diff --git a/src/workspaces/flow/next/components/chat-input.tsx b/src/workspaces/flow/next/components/chat-input.tsxindex 03fedb4..45130b5 100644--- a/src/workspaces/flow/next/components/chat-input.tsx+++ b/src/workspaces/flow/next/components/chat-input.tsx@@ -1,10 +1,10 @@"use client"import {+ Brain,FileText,History,Image as ImageIcon,- Loader2,ScrollText,Send,Square,@@ -144,8 +144,9 @@ interface ChatInputProps {>showHistory?: booleanonToggleHistory?: (show: boolean) => void- sessionId?: stringerror?: Error | null+ deepThinkingEnabled?: boolean+ onToggleDeepThinking?: () => void}export function ChatInput({@@ -160,8 +161,9 @@ export function ChatInput({pdfData = new Map(),showHistory = false,onToggleHistory = () => {},- sessionId,error = null,+ deepThinkingEnabled = false,+ onToggleDeepThinking = () => {},}: ChatInputProps) {const { t } = useLanguage()const { diagramHistory } = useDiagram()@@ -409,6 +411,26 @@ export function ChatInput({{/* Right actions */}<div className="flex items-center gap-1">+ <ButtonWithTooltip+ type="button"+ variant="ghost"+ size="sm"+ onClick={onToggleDeepThinking}+ disabled={isDisabled}+ tooltipContent={t("tooltip.deep_thinking")}+ className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"+ aria-pressed={deepThinkingEnabled}+ aria-label={t("input.deep_thinking")}+ >+ <Brain+ className={`h-3.5 w-3.5 ${+ deepThinkingEnabled+ ? "text-blue-600"+ : "text-muted-foreground"+ }`}+ />+ </ButtonWithTooltip>+<ButtonWithTooltiptype="button"variant="ghost"diff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/src/workspaces/flow/next/components/chat-panel.tsxindex 2a94881..ec26129 100644--- a/src/workspaces/flow/next/components/chat-panel.tsx+++ b/src/workspaces/flow/next/components/chat-panel.tsx@@ -32,6 +32,7 @@ const STORAGE_MESSAGES_KEY = "next-ai-draw-io-messages"const STORAGE_XML_SNAPSHOTS_KEY = "next-ai-draw-io-xml-snapshots"const STORAGE_SESSION_ID_KEY = "next-ai-draw-io-session-id"export const STORAGE_DIAGRAM_XML_KEY = "next-ai-draw-io-diagram-xml"+const STORAGE_DEEP_THINKING_KEY = "next-ai-draw-io-deep-thinking"// Type for message parts (tool calls and their states)interface MessagePart {@@ -158,6 +159,10 @@ export default function ChatPanel({const [tpmLimit, setTpmLimit] = useState(0)const [defaultModel, setDefaultModel] = useState("")const [isParsingFiles, setIsParsingFiles] = useState(false)+ const [deepThinkingEnabled, setDeepThinkingEnabled] = useState(() => {+ if (typeof window === "undefined") return false+ return localStorage.getItem(STORAGE_DEEP_THINKING_KEY) === "true"+ })// Check config on mountuseEffect(() => {@@ -175,6 +180,14 @@ export default function ChatPanel({})}, [])+ useEffect(() => {+ if (typeof window === "undefined") return+ localStorage.setItem(+ STORAGE_DEEP_THINKING_KEY,+ deepThinkingEnabled ? "true" : "false",+ )+ }, [deepThinkingEnabled])+// Quota management using extracted hookconst quotaManager = useQuotaManager({dailyRequestLimit,@@ -636,7 +649,11 @@ Please fix the XML issues. Ensure you are editing exact lines from the current X// Build user text by concatenating input with pre-extracted text// (Backend only reads first text part, so we must combine them)- setIsParsingFiles(true)+ const hasExtractableFiles = files.some(+ (file) =>+ isPdfFile(file) || isTextFile(file) || isWordFile(file),+ )+ setIsParsingFiles(hasExtractableFiles)const parts: any[] = []const { userText, uploadedFiles } = await processFilesAndAppendContent(input,@@ -869,6 +886,7 @@ Please fix the XML issues. Ensure you are editing exact lines from the current XpreviousXml,sessionId,uploadedFiles,+ deepThinkingEnabled,aiConfig: {provider: config.aiProvider,baseUrl: config.aiBaseUrl,@@ -1212,8 +1230,11 @@ Please fix the XML issues. Ensure you are editing exact lines from the current XpdfData={pdfData}showHistory={showHistory}onToggleHistory={setShowHistory}- sessionId={sessionId}error={error}+ deepThinkingEnabled={deepThinkingEnabled}+ onToggleDeepThinking={() =>+ setDeepThinkingEnabled((prev) => !prev)+ }/></footer></div>diff --git a/src/workspaces/flow/next/lib/system-prompts.ts b/src/workspaces/flow/next/lib/system-prompts.tsindex 3e614b2..a26eaeb 100644--- a/src/workspaces/flow/next/lib/system-prompts.ts+++ b/src/workspaces/flow/next/lib/system-prompts.ts@@ -11,6 +11,7 @@ export const DEFAULT_SYSTEM_PROMPT = `You are an expert diagram creation assistant specializing in draw.io XML generation.Your primary function is chat with user and crafting clear, well-organized visual diagrams through precise XML specifications.You can see images that users upload, and you can read the text content extracted from PDF documents they upload.+You may also receive an optional "Reference image" generated by an upstream deep-thinking stage. When present, use it as a visual guide for structure, composition, grouping, and layout. When absent, ignore this input completely.When you are asked to create a diagram, briefly describe your plan about the layout and structure to avoid object overlapping or edge cross the objects. (2-3 sentences max), then use display_diagram tool to generate the XML.After generating or editing a diagram, you don't need to say anything. The user can see the diagram - no need to describe it.@@ -76,6 +77,7 @@ Note that:- Focus on producing clean, professional diagrams that effectively communicate the intended information through thoughtful layout and design choices.- When artistic drawings are requested, creatively compose them using standard diagram shapes and connectors while maintaining visual clarity.- Return XML only via tool calls, never in text responses.+- If an optional "Reference image" is provided, treat it as a strong visual reference for how the diagram should be organized, while keeping the user's request and the current diagram XML authoritative.- If user asks you to replicate a diagram based on an image, remember to match the diagram style and layout as closely as possible. Especially, pay attention to the lines and shapes, for example, if the lines are straight or curved, and if the shapes are rounded or square.- Note that when you need to generate diagram about aws architecture, use **AWS 2025 icons**.- NEVER include XML comments (<!-- ... -->) in your generated XML. Draw.io strips comments, which breaks edit_diagram patterns.diff --git a/src/workspaces/flow/next/lib/translations.ts b/src/workspaces/flow/next/lib/translations.tsindex 07f4d90..483c2cf 100644--- a/src/workspaces/flow/next/lib/translations.ts+++ b/src/workspaces/flow/next/lib/translations.ts@@ -23,6 +23,7 @@ const en = {"input.stop": "Stop generation","input.history": "History","input.history.toggle": "Toggle history",+ "input.deep_thinking": "Deep Think",// ChatMessageDisplay"message.sending": "Sending message...",@@ -106,6 +107,7 @@ const en = {"examples.animated.desc": "Draw a transformer architecture with animated connectors","tooltip.history": "Diagram history","tooltip.save": "Save diagram",+ "tooltip.deep_thinking": "Deep Think",// HistoryDialog"history.title": "Diagram History",@@ -156,6 +158,7 @@ export const translations = {"input.stop": "停止生成","input.history": "历史记录","input.history.toggle": "切换历史记录",+ "input.deep_thinking": "深度思考",// ChatMessageDisplay"message.sending": "正在发送消息...",@@ -239,6 +242,7 @@ export const translations = {"examples.animated.desc": "绘制带动画连线的 Transformer 架构图","tooltip.history": "流程图历史","tooltip.save": "保存流程图",+ "tooltip.deep_thinking": "深度思考",// HistoryDialog"history.title": "流程图历史记录",