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.

MinerU_add

codingFeng101906921f6ec72
diff --git a/README.md b/README.md
index f49e932..ff9025d 100644
--- a/README.md
+++ b/README.md
@@ -1,119 +1,144 @@
-<div align="center">
- <h1>Unified AI Workspace</h1>
- <p>一个把对话、可视化工作台与可交付产物整合在一起的 AI 创作工作区</p>
- <p>An AI creation studio that unifies chat, visual workspaces, and deliverables</p>
- <p>
- <img alt="React" src="https://img.shields.io/badge/React-18-61DAFB?logo=react&logoColor=white" />
- <img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-5-3178C6?logo=typescript&logoColor=white" />
- <img alt="Vite" src="https://img.shields.io/badge/Vite-6-646CFF?logo=vite&logoColor=white" />
- </p>
- <p>
- <a href="#highlights">亮点</a> ·
- <a href="#quickstart">快速开始</a> ·
- <a href="#workspaces">工作台</a> ·
- <a href="#configuration">配置</a> ·
- <a href="#contributing">贡献</a>
- </p>
- <p>如果这个项目对你有帮助,欢迎点个 Star</p>
-</div>
+# CanvasAnvil / Unified AI Workspace
+
+一个面向生产场景的多工作台 AI 应用,统一了三类能力:
+- Flow:流程图生成与局部编辑(draw.io XML)
+- CAD:室内装修方案、2D 平面图、装修图与物料清单
+- PPT:演示文稿草稿生成与迭代编辑
---
-<a id="highlights"></a>
-## 亮点 / Highlights
+## 项目来源与说明
+
+本项目并非从零开始重复造轮子,而是在优秀开源项目基础上做了工程级集成与优化:
+
+- Flow 工作台:基于 `next-ai-draw-io` 集成与增强
+ https://github.com/DayuanJiang/next-ai-draw-io
+- PPT 工作台:基于 `banana-slides` 集成与增强
+ https://github.com/Anionex/banana-slides.git
+- CAD 工作台:本项目自研(架构、Agent 工作流、2D SVG 编辑链路、BOM/装修图链路)
-- 三个工作台同屏协作:Flow / CAD / PPT,一套交互范式贯穿到底
-- 原子级交互:只改不满意的部分,保留满意的部分(对话里直接编辑、复制、重生成)
-- 交付导向:从需求到产物的链路清晰(图、SVG、装修图、BOM、PPT 草稿)
-- 中英双语 UI,一键切换
+优化方向包含但不限于:
+- 三工作台统一交互范式(聊天、代码块、一键应用到画布)
+- 更稳定的 Agent 路由与重试机制
+- CAD 专项能力(局部 patch / 全量 replace / BOM / 7 槽装修图)
+- 跨工作台状态管理、版本管理和导出链路
---
-<a id="workspaces"></a>
-## 工作台 / Workspaces
+## 核心能力
-| Workspace | 你能做什么 | 产出 |
-|---|---|---|
-| Flow | 通过对话生成/迭代流程图(draw.io XML)并渲染预览 | draw.io XML |
-| CAD | 需求 → 方案(plan)→ 2D SVG → 装修图 / 物料清单(BOM) | SVG / renders / BOM |
-| PPT | 生成/编辑 PPT 结构与页面草稿,支持对指定页定向编辑 | slide JSON / images |
+### 1) Flow 工作台
+- 通过对话生成流程图
+- 支持局部 patch 与全量 replace
+- 支持代码块一键应用到当前画布
+- 支持图形历史快照与恢复
+
+### 2) CAD 工作台
+- 需求分析 -> `cad_plan` 结构化方案
+- 2D SVG 生成与局部修改
+- 装修图提示词与并发出图(含失败重试)
+- BOM 物料清单展示与导出
+- 版本历史聚焦 2D 平面图,不记录 BOM 条目
+
+### 3) PPT 工作台
+- 幻灯片结构化内容生成
+- 面向页级别的增量编辑
+- 图文内容流式生成与迭代
---
-<a id="quickstart"></a>
-## 快速开始 / Quickstart
+## 技术栈
+
+- 前端:React 18 + TypeScript + Vite
+- UI:Tailwind CSS + Radix + Lucide
+- 图形引擎:
+- Flow:draw.io 集成
+- CAD:SVG-Edit 集成
+- 模型接入:可配置多模型(Chat / Image)
-### 运行环境 / Prerequisites
+---
-- Node.js(建议使用 LTS)
+## 快速开始
-### 安装依赖 / Install
+### 1. 安装依赖
```bash
npm install
```
-### 启动开发服务器 / Start Dev Server
+### 2. 启动开发环境
```bash
npm run dev
```
-### 构建 / Build
+默认地址:
+- `http://localhost:5173`
+
+### 3. 类型检查
```bash
-npm run build
+npm run check
```
----
-
-<a id="configuration"></a>
-## 配置 / Configuration
-
-项目的模型配置在浏览器侧保存(localStorage),建议通过界面右上角的设置入口进行配置:
+### 4. 生产构建
-- API Key
-- Base URL
-- Chat Model / Image Model
-
-说明:
-
-- API Key 会保存在本地浏览器中,请不要在不可信环境中使用个人密钥
+```bash
+npm run build
+```
---
-## 脚本 / Scripts
+## 常用脚本
-- `npm run dev`:启动开发服务器(Vite)
-- `npm run build`:TypeScript 构建 + Vite 打包
+- `npm run dev`:启动开发服务器
+- `npm run build`:生产构建
- `npm run check`:TypeScript 类型检查
- `npm run lint`:ESLint 检查
---
-## 项目结构 / Project Layout
+## 目录结构(关键部分)
+
+```text
+.
+├─ agent/ # CAD/Flow/PPT 的提示词与子智能体定义
+├─ public/ # 静态资源(含 SVG-Edit 等)
+├─ src/
+│ └─ workspaces/
+│ ├─ flow/ # 流程图工作台
+│ ├─ cad/ # CAD 工作台(自研核心)
+│ └─ ppt/ # PPT 工作台
+├─ api/ # API 相关逻辑
+└─ README.md
+```
-关键目录(高频入口):
+---
-- `src/App.tsx`:三工作台整体布局与状态管理
-- `src/components/ChatPanel.tsx`:对话面板(历史、重生成、附件、工作台联动)
-- `src/components/workspaces/*Workspace.tsx`:各工作台 UI 与交互
-- `agent/*`:各类 Agent Prompt 资源
+## CAD 工作流(简版)
----
+1. Router 决策子智能体(plan / svg / bom / images)
+2. `cad_plan_agent` 产出结构化方案
+3. `cad_svg_agent` 产出 `cad_patch`:
+- 局部:`mode=patch` + `edits`
+- 全量:`mode=replace` + `full svg`
+4. `cad_bom_agent` 产出物料清单 JSON
+5. `cad_images_agent` 产出 7 槽装修图提示词并并发生成
-<a id="contributing"></a>
-## 贡献 / Contributing
+---
-欢迎提交 Issue 和 PR:
+## 配置说明
-- Bug 报告:请附上复现步骤、截图/录屏、以及控制台报错(如有)
-- 新功能:先开 Issue 描述使用场景和预期交互,再提交 PR 会更高效
-- 代码质量:提交前建议运行 `npm run check` 与 `npm run lint`
+模型与接口配置通过应用设置注入(如 API Key、Base URL、模型名)。
+请勿在不受信任环境暴露私有密钥。
---
-## Language / 语言
+## 致谢
+
+感谢以下开源项目提供基础能力与灵感:
+- `next-ai-draw-io`:https://github.com/DayuanJiang/next-ai-draw-io
+- `banana-slides`:https://github.com/Anionex/banana-slides.git
+
+本仓库在其基础上进行了面向统一工作流的重构、集成与扩展。
-- UI supports Chinese/English toggle
-- UI 支持中英文切换
diff --git a/public/svg-editor.html b/public/svg-editor.html
index c460469..853f1a8 100644
--- a/public/svg-editor.html
+++ b/public/svg-editor.html
@@ -29,6 +29,8 @@
const container = document.getElementById("svgedit-container");
const editor = new Editor(container);
const EMPTY_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1000" viewBox="0 0 1600 1000"></svg>`;
+ let editorReady = false;
+ let pendingSvgLoad = "";
editor.setConfig({
allowInitialUserOverride: true,
@@ -117,8 +119,8 @@
};
const loadSvg = async (svg) => {
- const text = normalizeIncomingSvg(svg);
- if (!text) return false;
+ const text = normalizeIncomingSvg(svg);
+ if (!text) return false;
try {
await editor.loadFromString(text, { noAlert: true });
@@ -135,18 +137,28 @@
};
const clearSvg = async () => {
+ const ok = await loadSvg(EMPTY_SVG);
+ if (ok) return;
try {
if (typeof editor?.svgCanvas?.clear === "function") {
editor.svgCanvas.clear();
- return;
}
} catch (e) {
console.error("Failed to clear SVG canvas directly", e);
}
- await loadSvg(EMPTY_SVG);
};
- editor.ready(() => {
+ const applyPendingLoad = async () => {
+ if (!editorReady) return;
+ const next = String(pendingSvgLoad || "").trim();
+ if (!next) return;
+ pendingSvgLoad = "";
+ await loadSvg(next);
+ };
+
+ editor.ready(async () => {
+ editorReady = true;
+ await applyPendingLoad();
post({ type: "cad_svg_editor_ready" });
});
@@ -157,7 +169,24 @@
const type = String(data.type || "");
if (type === "cad_svg_editor_load") {
- const ok = await loadSvg(data.svg);
+ const normalized = normalizeIncomingSvg(data.svg);
+ if (!normalized) {
+ post({
+ type: "cad_svg_editor_load_result",
+ ok: false
+ });
+ return;
+ }
+ if (!editorReady) {
+ pendingSvgLoad = normalized;
+ post({
+ type: "cad_svg_editor_load_result",
+ ok: true,
+ queued: true
+ });
+ return;
+ }
+ const ok = await loadSvg(normalized);
post({
type: "cad_svg_editor_load_result",
ok: !!ok
@@ -166,6 +195,10 @@
}
if (type === "cad_svg_editor_clear") {
+ if (!editorReady) {
+ pendingSvgLoad = EMPTY_SVG;
+ return;
+ }
await clearSvg();
return;
}
diff --git a/src/components/ChatInput.tsx b/src/components/ChatInput.tsx
index 58e4d94..6e6f93d 100644
--- a/src/components/ChatInput.tsx
+++ b/src/components/ChatInput.tsx
@@ -381,8 +381,8 @@ export function ChatInput({
multiple
accept={
uploadMode === "filesOnly"
- ? ".pdf,application/pdf,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
- : "image/*,.pdf,application/pdf,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
+ ? ".pdf,.docx,.zip,.tex,.tgz,.tar.gz,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
+ : "image/*,.pdf,.docx,.zip,.tex,.tgz,.tar.gz,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
}
className="hidden"
ref={fileInputRef}
diff --git a/src/components/SettingsDialog.tsx b/src/components/SettingsDialog.tsx
index 6583e8e..0fd8742 100644
--- a/src/components/SettingsDialog.tsx
+++ b/src/components/SettingsDialog.tsx
@@ -123,6 +123,27 @@ export function SettingsDialog() {
placeholder="gemini-2.5-flash-image-preview"
/>
</div>
+
+ <div className="space-y-2">
+ <label className="text-sm font-medium text-foreground flex items-center gap-2">
+ MinerU Token (optional)
+ <a
+ href="https://mineru.net/"
+ target="_blank"
+ rel="noreferrer noopener"
+ className="text-xs text-blue-600 hover:text-blue-500 underline underline-offset-2 font-normal"
+ >
+ Get token
+ </a>
+ </label>
+ <input
+ type="password"
+ value={config.fileParserApiToken || ""}
+ onChange={(e) => setConfig({ ...config, fileParserApiToken: e.target.value })}
+ className="flex h-10 w-full rounded-lg border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-0 disabled:cursor-not-allowed disabled:opacity-50 transition-all shadow-sm"
+ placeholder="Leave empty to use local extraction (default)"
+ />
+ </div>
</div>
</div>
diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.ts
index f12bef5..ce9e858 100644
--- a/src/lib/ai-client.ts
+++ b/src/lib/ai-client.ts
@@ -8,6 +8,7 @@ export interface AIConfig {
baseUrl: string;
chatModel: string;
imageModel: string;
+ fileParserApiToken?: string;
systemPrompt?: string;
}
@@ -17,6 +18,7 @@ const DEFAULT_CONFIG: AIConfig = {
baseUrl: "",
chatModel: "gpt-3.5-turbo",
imageModel: "gemini-2.5-flash-image-preview",
+ fileParserApiToken: "",
systemPrompt: ""
};
diff --git a/src/workspaces/cad/CadWorkspaceShell.tsx b/src/workspaces/cad/CadWorkspaceShell.tsx
index 6e10e87..5a615b2 100644
--- a/src/workspaces/cad/CadWorkspaceShell.tsx
+++ b/src/workspaces/cad/CadWorkspaceShell.tsx
@@ -30,13 +30,13 @@ const CAD_RENDERS_STORAGE_KEY = "unified-ai-workspace-cad-renders-v1";
const CAD_HISTORY_STORAGE_KEY = "unified-ai-workspace-history-cad-v1";
const CAD_CHAT_STORAGE_KEY = "chat_history_v2_cad";
const CAD_RENDER_SLOT_TITLES = [
- "Renovation Plan Layout",
- "Floor Finish Plan",
- "Reflected Ceiling Plan",
- "Wall Setting-Out Plan",
- "MEP Plan (Electrical + Low Voltage + Plumbing)",
- "Elevation Index Plan + Interior Elevations",
- "Detail Drawings",
+ "装修平面布置图",
+ "地面铺装图",
+ "顶面布置图",
+ "墙体定位图",
+ "机电点位图(强弱电+给排水)",
+ "立面索引图+室内立面图",
+ "节点大样图",
];
const tryParseJson = (text: string) => {
@@ -278,7 +278,7 @@ export function CadWorkspaceShell() {
? parsed.prompts
.slice(0, 7)
.map((p: any, idx: number) => ({
- title: typeof p?.title === "string" ? p.title : CAD_RENDER_SLOT_TITLES[idx] || "Drawing",
+ title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,
url: typeof p?.url === "string" ? p.url : "",
}))
: [];
@@ -350,7 +350,6 @@ export function CadWorkspaceShell() {
const rows = Array.isArray(parsed.rows) ? parsed.rows : [];
setCadBom({ columns, rows });
setCadFocusPanel("bom");
- addToHistory(JSON.stringify({ type: "cad_bom", columns, rows }), "json");
return { ok: true };
}
@@ -368,7 +367,7 @@ export function CadWorkspaceShell() {
setCadImagesLoading(true);
setCadImages(
Array.from({ length: 7 }).map((_, idx) => ({
- title: items[idx]?.title || CAD_RENDER_SLOT_TITLES[idx] || `Drawing ${idx + 1}`,
+ title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,
url: "",
})),
);
@@ -388,48 +387,93 @@ export function CadWorkspaceShell() {
const svgShort = svgText.length > 6000 ? svgText.slice(0, 6000) : svgText;
const list = items.slice(0, 7);
- const batchSize = 3;
- for (let i = 0; i < list.length; i += batchSize) {
- const batch = list.slice(i, i + batchSize);
- const settled = await Promise.allSettled(
- batch.map(async (p) => {
- const fullPrompt = [
- presetRenderPrompt,
- "",
- "Plan:",
- planShort,
- "",
- "2D SVG:",
- svgShort,
- "",
- "Sheet:",
- p.prompt,
- ]
- .filter(Boolean)
- .join("\n");
+ const buildFullPrompt = (sheetPrompt: string) =>
+ [
+ presetRenderPrompt,
+ "",
+ "Plan:",
+ planShort,
+ "",
+ "2D SVG:",
+ svgShort,
+ "",
+ "Sheet:",
+ sheetPrompt,
+ ]
+ .filter(Boolean)
+ .join("\n");
+
+ const wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
+
+ const generateWithRetry = async (fullPrompt: string, maxRetries: number, retryDelayMs: number) => {
+ for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
+ try {
const url = await generateImage({ prompt: fullPrompt });
- return url ? { title: p.title, url, prompt: p.prompt } : null;
- }),
+ if (url) return url;
+ } catch (err) {
+ if (attempt >= maxRetries) {
+ console.error("CAD image generation attempt failed", err);
+ }
+ }
+ if (attempt < maxRetries) {
+ await wait(retryDelayMs * (attempt + 1));
+ }
+ }
+ return "";
+ };
+
+ const syncPartialImages = () => {
+ setCadImages(
+ Array.from({ length: 7 }).map((_, idx) => ({
+ title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,
+ url: results[idx]?.url || "",
+ })),
);
- for (let bi = 0; bi < settled.length; bi += 1) {
- const s = settled[bi];
- const globalIdx = i + bi;
- if (s.status === "fulfilled" && s.value?.url) results[globalIdx] = s.value;
+ };
+
+ const runPass = async (indices: number[], batchSize: number, maxRetriesPerItem: number, retryDelayMs: number) => {
+ for (let i = 0; i < indices.length; i += batchSize) {
+ const batch = indices.slice(i, i + batchSize);
+ const settled = await Promise.allSettled(
+ batch.map(async (idx) => {
+ const p = list[idx];
+ if (!p?.prompt) return null;
+ const url = await generateWithRetry(buildFullPrompt(p.prompt), maxRetriesPerItem, retryDelayMs);
+ return url ? { idx, value: { title: p.title, url, prompt: p.prompt } } : null;
+ }),
+ );
+ for (const s of settled) {
+ if (s.status === "fulfilled" && s.value?.idx !== undefined && s.value?.value?.url) {
+ results[s.value.idx] = s.value.value;
+ }
+ }
+ syncPartialImages();
}
+ };
+
+ const allIndices = list.map((_, idx) => idx);
+ await runPass(allIndices, 3, 1, 1200);
+ const failedAfterConcurrent = allIndices.filter((idx) => !results[idx]?.url);
+ if (failedAfterConcurrent.length > 0) {
+ await runPass(failedAfterConcurrent, 1, 2, 1800);
}
const final = Array.from({ length: 7 }).map((_, idx) => ({
- title: items[idx]?.title || CAD_RENDER_SLOT_TITLES[idx] || `Drawing ${idx + 1}`,
+ title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,
url: results[idx]?.url || "",
}));
setCadImages(final);
+ const failedCount = list.filter((_, idx) => !results[idx]?.url).length;
+ if (failedCount > 0) {
+ toast.warning(`有 ${failedCount} 张装修图重试后仍失败,请再试一次生成。`);
+ }
addToHistory(JSON.stringify({ type: "cad_images", prompts: final }, null, 2), "json");
} catch (e) {
console.error("CAD image generation failed", e);
toast.error("CAD image generation failed");
setCadImages(
Array.from({ length: 7 }).map((_, idx) => ({
- title: items[idx]?.title || CAD_RENDER_SLOT_TITLES[idx] || `Drawing ${idx + 1}`,
+ title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,
url: "",
})),
);
@@ -452,9 +496,14 @@ export function CadWorkspaceShell() {
}
if (mode === "patch" && Array.isArray(parsed.edits)) {
try {
- const next = applyStringEdits(cad2dSvg || "", parsed.edits);
+ const current = normalizeSvgMarkup(cad2dSvg || "");
+ if (!current) return { ok: false, retry: true, error: "Current 2D SVG is empty, cannot apply patch" };
+ const next = applyStringEdits(current, parsed.edits);
const normalizedNext = normalizeSvgMarkup(next);
if (!normalizedNext) return { ok: false, retry: true, error: "Patch result is not valid svg" };
+ if (normalizedNext === current) {
+ return { ok: false, retry: true, error: "Patch produced no visible SVG change" };
+ }
setCad2dSvg(normalizedNext);
setCadFocusPanel("2d");
addToHistory(normalizedNext, "svg");
@@ -477,6 +526,7 @@ export function CadWorkspaceShell() {
setCadImagesLoading(false);
setCadBom(null);
setCadFocusPanel(null);
+ setChatHistory([]);
setAttachments([]);
setVersionHistory([]);
try {
diff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
index 82a5161..024c24a 100644
--- a/src/workspaces/cad/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
@@ -4,12 +4,14 @@ import {
ChevronDown,
ChevronUp,
Copy,
+ Cpu,
FileCode,
FileText,
Loader2,
Minus,
Pencil,
Plus,
+ Play,
RotateCcw,
ThumbsDown,
ThumbsUp,
@@ -45,6 +47,7 @@ export interface UIMessage {
interface ChatMessageDisplayProps {
messages: UIMessage[];
setInput: (input: string) => void;
+ onApplyCode?: (code: string, language?: string) => void | boolean | Promise<void | boolean>;
onRegenerate?: (messageIndex: number) => void;
onEditMessage?: (messageIndex: number, newText: string) => void;
status?: "streaming" | "submitted" | "idle" | "error" | "ready";
@@ -70,6 +73,18 @@ interface PptToolPayload {
slides: PptEditSlidePatch[];
}
+interface CadPatchEdit {
+ search: string;
+ replace: string;
+}
+
+interface CadPatchToolPayload {
+ type: "cad_patch";
+ target: "2d_svg";
+ mode: "patch";
+ edits: CadPatchEdit[];
+}
+
function splitTextIntoFileSections(text: string): TextSection[] {
const sections: TextSection[] = [];
const filePattern = /\[(PDF|File):\s*([^\]]+)\]\n([\s\S]*?)(?=\n\n\[(PDF|File):|$)/g;
@@ -204,31 +219,51 @@ function splitMarkdownAndCodeBlocks(text: string): MarkdownSegment[] {
if (!raw) return [];
const segments: MarkdownSegment[] = [];
- const fencePattern = /```([^\n`]*)\n?([\s\S]*?)```/g;
- let lastIndex = 0;
- let match: RegExpExecArray | null;
-
const pushMarkdown = (value: string) => {
const normalized = value.replace(/^\n+|\n+$/g, "");
if (normalized.trim().length === 0) return;
segments.push({ type: "markdown", content: normalized });
};
- while ((match = fencePattern.exec(raw)) !== null) {
- pushMarkdown(raw.slice(lastIndex, match.index));
+ let cursor = 0;
+ while (cursor < raw.length) {
+ const open = raw.indexOf("```", cursor);
+ if (open < 0) {
+ pushMarkdown(raw.slice(cursor));
+ break;
+ }
+
+ pushMarkdown(raw.slice(cursor, open));
- const language = String(match[1] || "text")
+ const infoStart = open + 3;
+ const infoEnd = raw.indexOf("\n", infoStart);
+ const hasInfoLine = infoEnd >= 0;
+ const info = hasInfoLine ? raw.slice(infoStart, infoEnd) : raw.slice(infoStart);
+ const language = String(info || "")
.trim()
.split(/\s+/)[0]
.toLowerCase() || "text";
- const code = String(match[2] || "")
+ const codeStart = hasInfoLine ? infoEnd + 1 : infoStart;
+ const close = raw.indexOf("```", codeStart);
+ if (close < 0) {
+ // Streaming case: opening fence arrived but closing fence not yet emitted.
+ const code = hasInfoLine
+ ? String(raw.slice(codeStart))
+ .replace(/\r\n/g, "\n")
+ .replace(/\n$/, "")
+ : "";
+ segments.push({ type: "code", language, code });
+ cursor = raw.length;
+ break;
+ }
+
+ const code = String(raw.slice(codeStart, close))
.replace(/\r\n/g, "\n")
.replace(/\n$/, "");
segments.push({ type: "code", language, code });
- lastIndex = match.index + match[0].length;
+ cursor = close + 3;
}
- pushMarkdown(raw.slice(lastIndex));
if (segments.length === 0 && raw.trim().length > 0) {
segments.push({ type: "markdown", content: raw.trim() });
}
@@ -275,6 +310,36 @@ function extractPptToolPayload(text: string): PptToolPayload | null {
return slides.length > 0 ? { type, slides } : null;
}
+function extractCadPatchToolPayload(text: string): CadPatchToolPayload | null {
+ const raw = String(text || "").trim();
+ if (!raw) return null;
+ const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
+ const candidate = String(fenced?.[1] ?? raw).trim();
+ let parsed: any;
+ try {
+ parsed = JSON.parse(candidate);
+ } catch {
+ return null;
+ }
+ if (!parsed || typeof parsed !== "object") return null;
+ if (String(parsed?.type || "").trim() !== "cad_patch") return null;
+ if (String(parsed?.target || "").trim() !== "2d_svg") return null;
+ if (String(parsed?.mode || "").trim() !== "patch") return null;
+ const edits = Array.isArray(parsed?.edits)
+ ? parsed.edits
+ .filter(
+ (e: any) =>
+ e &&
+ typeof e === "object" &&
+ typeof e.search === "string" &&
+ typeof e.replace === "string"
+ )
+ .map((e: any) => ({ search: String(e.search), replace: String(e.replace) }))
+ : [];
+ if (edits.length === 0) return null;
+ return { type: "cad_patch", target: "2d_svg", mode: "patch", edits };
+}
+
function getSlideNumber(slide: PptEditSlidePatch, index: number): number {
const id = String(slide?.id || "");
const m = id.match(/slide-(\d+)/i);
@@ -323,9 +388,47 @@ function slideFieldLabel(key: string, uiLang: "zh" | "en"): string {
return key;
}
+function CadPatchEditsDisplay({ edits }: { edits: CadPatchEdit[] }) {
+ return (
+ <div className="space-y-3">
+ {edits.map((edit, index) => (
+ <div
+ key={`${(edit.search || "").slice(0, 40)}-${(edit.replace || "").slice(0, 40)}-${index}`}
+ className="rounded-lg border border-border/50 overflow-hidden bg-background/50"
+ >
+ <div className="px-3 py-1.5 bg-muted/40 border-b border-border/30 flex items-center gap-2">
+ <span className="text-xs font-medium text-muted-foreground">Change {index + 1}</span>
+ </div>
+ <div className="divide-y divide-border/30">
+ <div className="px-3 py-2">
+ <div className="flex items-center gap-1.5 mb-1.5">
+ <Minus className="w-3 h-3 text-red-500" />
+ <span className="text-[10px] font-medium text-red-600 uppercase tracking-wide">Remove</span>
+ </div>
+ <pre className="text-[11px] font-mono text-red-700 bg-red-50 rounded px-2 py-1.5 overflow-x-auto whitespace-pre-wrap break-all">
+ {edit.search}
+ </pre>
+ </div>
+ <div className="px-3 py-2">
+ <div className="flex items-center gap-1.5 mb-1.5">
+ <Plus className="w-3 h-3 text-green-500" />
+ <span className="text-[10px] font-medium text-green-600 uppercase tracking-wide">Add</span>
+ </div>
+ <pre className="text-[11px] font-mono text-green-700 bg-green-50 rounded px-2 py-1.5 overflow-x-auto whitespace-pre-wrap break-all">
+ {edit.replace}
+ </pre>
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
export function ChatMessageDisplay({
messages,
setInput,
+ onApplyCode,
onRegenerate,
onEditMessage,
status = "idle",
@@ -341,6 +444,7 @@ export function ChatMessageDisplay({
const [editText, setEditText] = useState<string>("");
const [expandedPdfSections, setExpandedPdfSections] = useState<Record<string, boolean>>({});
const [expandedSlideCards, setExpandedSlideCards] = useState<Record<string, boolean>>({});
+ const [expandedCadPatchCards, setExpandedCadPatchCards] = useState<Record<string, boolean>>({});
const [isAtBottom, setIsAtBottom] = useState(true);
const scrollRafRef = useRef<number | null>(null);
const userScrolledUpRef = useRef(false);
@@ -883,6 +987,29 @@ export function ChatMessageDisplay({
</td>
);
},
+ pre({ children, ...props }: any) {
+ return (
+ <pre
+ {...props}
+ className={cn(
+ "max-w-full overflow-x-hidden whitespace-pre-wrap break-words",
+ props?.className
+ )}
+ >
+ {children}
+ </pre>
+ );
+ },
+ code({ children, className, ...props }: any) {
+ return (
+ <code
+ {...props}
+ className={cn("whitespace-pre-wrap break-words", className)}
+ >
+ {children}
+ </code>
+ );
+ },
}}
>
{content}
@@ -920,6 +1047,76 @@ export function ChatMessageDisplay({
const code = seg.code || "";
if (!code.trim()) return null;
const ordinal = codeBlockOrdinal++;
+ const cadPatchPayload = language === "json"
+ ? extractCadPatchToolPayload(code)
+ : null;
+ if (cadPatchPayload && cadPatchPayload.edits.length > 0) {
+ const cardKey = `${message.id}-cad-patch-${idx}-${segIdx}-${ordinal}`;
+ const expanded = expandedCadPatchCards[cardKey] ?? true;
+ const isStreamingPatch = status === "streaming" && isLastAssistantMessage;
+ return (
+ <div
+ key={`cad-patch-card-${message.id}-${idx}-${segIdx}-${ordinal}`}
+ className="my-1 rounded-xl border border-border/60 bg-muted/30 overflow-hidden"
+ >
+ <div className="flex items-center justify-between px-4 py-3 bg-muted/50">
+ <div className="flex items-center gap-2">
+ <div className="w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center">
+ <Cpu className="w-3.5 h-3.5 text-primary" />
+ </div>
+ <span className="text-sm font-medium text-foreground/80">
+ {tr("Edit Diagram", "Edit Diagram")}
+ </span>
+ </div>
+ <div className="flex items-center gap-2">
+ {isStreamingPatch ? (
+ <div className="h-4 w-4 border-2 border-primary border-t-transparent rounded-full animate-spin" />
+ ) : (
+ <span className="text-xs font-medium text-green-600 bg-green-50 px-2 py-0.5 rounded-full">
+ {tr("Complete", "Complete")}
+ </span>
+ )}
+ {onApplyCode && (
+ <button
+ type="button"
+ onClick={() =>
+ onApplyCode(
+ JSON.stringify(cadPatchPayload, null, 2),
+ "json"
+ )
+ }
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-muted-foreground hover:bg-muted transition-colors"
+ >
+ <Play className="h-3 w-3" />
+ <span>{tr("Apply", "Apply")}</span>
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() =>
+ setExpandedCadPatchCards((prev) => ({
+ ...prev,
+ [cardKey]: !expanded,
+ }))
+ }
+ className="p-1 rounded hover:bg-muted transition-colors"
+ >
+ {expanded ? (
+ <ChevronUp className="w-4 h-4 text-muted-foreground" />
+ ) : (
+ <ChevronDown className="w-4 h-4 text-muted-foreground" />
+ )}
+ </button>
+ </div>
+ </div>
+ {expanded && (
+ <div className="px-4 py-3 border-t border-border/40 bg-muted/20">
+ <CadPatchEditsDisplay edits={cadPatchPayload.edits} />
+ </div>
+ )}
+ </div>
+ );
+ }
return (
<CodeBlock
key={`codeblock-${message.id}-${idx}-${segIdx}-${language}-${ordinal}`}
@@ -927,6 +1124,7 @@ export function ChatMessageDisplay({
code={code}
language={language}
isStreaming={status === "streaming" && isLastAssistantMessage}
+ onApply={onApplyCode}
/>
);
})}
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsx
index a4114fc..81ee124 100644
--- a/src/workspaces/cad/chat/ChatPanel.tsx
+++ b/src/workspaces/cad/chat/ChatPanel.tsx
@@ -246,6 +246,7 @@ export function ChatPanel({
const sanitizeAssistantContentForDisplay = (content: string) => {
if (workspaceId !== "cad") return content;
if (!content) return content;
+ const bomUpdatedText = trText("(已更新物料清单)", "(BOM updated)");
const formatCadPlanForDisplay = (parsed: any) => {
if (parsed?.type !== "cad_plan") return null;
const plan = parsed?.plan || {};
@@ -328,9 +329,13 @@ export function ChatPanel({
return `\`\`\`svg\n${parsed.full.trim()}\n\`\`\``;
}
if (mode === "patch") {
- return trText("(已执行2D局部修改)", "(2D patch applied)");
+ // Keep patch JSON for structured diff rendering in chat UI.
+ return full;
}
}
+ if (parsed?.type === "cad_bom") {
+ return bomUpdatedText;
+ }
} catch {
}
if (text.includes('"type"') && text.includes('"cad_images"')) {
@@ -356,6 +361,19 @@ export function ChatPanel({
// Fallback: if whole message is raw cad_plan JSON (not wrapped in code fences), render as readable text.
const prettyWhole = tryParseCadPlanJson(next);
if (prettyWhole) return prettyWhole;
+ try {
+ const parsedWhole = JSON.parse(String(next || "").trim());
+ if (
+ parsedWhole?.type === "cad_patch" &&
+ parsedWhole?.target === "2d_svg" &&
+ String(parsedWhole?.mode || "") === "patch" &&
+ Array.isArray(parsedWhole?.edits)
+ ) {
+ return `\`\`\`json\n${JSON.stringify(parsedWhole, null, 2)}\n\`\`\``;
+ }
+ if (parsedWhole?.type === "cad_bom") return bomUpdatedText;
+ } catch {
+ }
return next;
};
@@ -461,6 +479,21 @@ export function ChatPanel({
return { ok: true } as CodeActionResult;
};
+ const applyCodeFromMessage = async (code: string, language?: string) => {
+ const text = String(code || "").trim();
+ if (!text) return false;
+ if (workspaceId === "cad") {
+ const r = await runCodeAction(text, "cad");
+ return !!r.ok;
+ }
+ if (workspaceId === "flow") {
+ const r = await runCodeAction(text, "flow");
+ return !!r.ok;
+ }
+ const r = await runCodeAction(text, "ppt");
+ return !!r.ok;
+ };
+
const normalizeSvgMarkup = (text: string): string => {
const raw = String(text || "").trim();
if (!raw) return "";
@@ -905,13 +938,13 @@ export function ChatPanel({
};
const fallbackTitlesForOutput = [
- trText("Renovation Plan Layout", "Renovation Plan Layout"),
- trText("Floor Finish Plan", "Floor Finish Plan"),
- trText("Reflected Ceiling Plan", "Reflected Ceiling Plan"),
- trText("Wall Setting-Out Plan", "Wall Setting-Out Plan"),
- trText("MEP Plan (Electrical + Low Voltage + Plumbing)", "MEP Plan (Electrical + Low Voltage + Plumbing)"),
- trText("Elevation Index Plan + Interior Elevations", "Elevation Index Plan + Interior Elevations"),
- trText("Detail Drawings", "Detail Drawings"),
+ trText("装修平面布置图", "装修平面布置图"),
+ trText("地面铺装图", "地面铺装图"),
+ trText("顶面布置图", "顶面布置图"),
+ trText("墙体定位图", "墙体定位图"),
+ trText("机电点位图(强弱电+给排水)", "机电点位图(强弱电+给排水)"),
+ trText("立面索引图+室内立面图", "立面索引图+室内立面图"),
+ trText("节点大样图", "节点大样图"),
];
const fallbackTitlesForPromptEnglish = [
"Renovation Plan Layout",
@@ -942,7 +975,7 @@ export function ChatPanel({
);
const prompts = settled.map((r, idx) => {
- const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("Drawing", "Drawing");
+ const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("图纸", "图纸");
const fallbackTitleForPrompt = fallbackTitlesForPromptEnglish[idx] || "Drawing";
const onSheetLanguageRule = "All on-sheet labels/notes/title block text must be in English.";
const fallbackPrompt = `Generate an orthographic 2D technical construction drawing sheet: ${fallbackTitleForPrompt}. Include border, bottom-right title block, scale/units, legend/symbols, key annotations and dimensions, consistent with the provided plan JSON and 2D SVG. ${onSheetLanguageRule}`;
@@ -1252,13 +1285,13 @@ export function ChatPanel({
};
const fallbackTitlesForOutput = [
- trText("Renovation Plan Layout", "Renovation Plan Layout"),
- trText("Floor Finish Plan", "Floor Finish Plan"),
- trText("Reflected Ceiling Plan", "Reflected Ceiling Plan"),
- trText("Wall Setting-Out Plan", "Wall Setting-Out Plan"),
- trText("MEP Plan (Electrical + Low Voltage + Plumbing)", "MEP Plan (Electrical + Low Voltage + Plumbing)"),
- trText("Elevation Index Plan + Interior Elevations", "Elevation Index Plan + Interior Elevations"),
- trText("Detail Drawings", "Detail Drawings"),
+ trText("装修平面布置图", "装修平面布置图"),
+ trText("地面铺装图", "地面铺装图"),
+ trText("顶面布置图", "顶面布置图"),
+ trText("墙体定位图", "墙体定位图"),
+ trText("机电点位图(强弱电+给排水)", "机电点位图(强弱电+给排水)"),
+ trText("立面索引图+室内立面图", "立面索引图+室内立面图"),
+ trText("节点大样图", "节点大样图"),
];
const fallbackTitlesForPromptEnglish = [
"Renovation Plan Layout",
@@ -1295,7 +1328,7 @@ export function ChatPanel({
);
const prompts = settled.map((r, idx) => {
- const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("Drawing", "Drawing");
+ const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("图纸", "图纸");
const fallbackTitleForPrompt = fallbackTitlesForPromptEnglish[idx] || "Drawing";
const onSheetLanguageRule = "All on-sheet labels/notes/title block text must be in English.";
const fallbackPrompt = `Generate an orthographic 2D technical construction drawing sheet: ${fallbackTitleForPrompt}. Include border, bottom-right title block, scale/units, legend/symbols, key annotations and dimensions, consistent with the provided plan JSON and 2D SVG. ${onSheetLanguageRule}`;
@@ -1976,13 +2009,13 @@ export function ChatPanel({
};
const fallbackTitlesForOutput = [
- trText("Renovation Plan Layout", "Renovation Plan Layout"),
- trText("Floor Finish Plan", "Floor Finish Plan"),
- trText("Reflected Ceiling Plan", "Reflected Ceiling Plan"),
- trText("Wall Setting-Out Plan", "Wall Setting-Out Plan"),
- trText("MEP Plan (Electrical + Low Voltage + Plumbing)", "MEP Plan (Electrical + Low Voltage + Plumbing)"),
- trText("Elevation Index Plan + Interior Elevations", "Elevation Index Plan + Interior Elevations"),
- trText("Detail Drawings", "Detail Drawings"),
+ trText("装修平面布置图", "装修平面布置图"),
+ trText("地面铺装图", "地面铺装图"),
+ trText("顶面布置图", "顶面布置图"),
+ trText("墙体定位图", "墙体定位图"),
+ trText("机电点位图(强弱电+给排水)", "机电点位图(强弱电+给排水)"),
+ trText("立面索引图+室内立面图", "立面索引图+室内立面图"),
+ trText("节点大样图", "节点大样图"),
];
const fallbackTitlesForPromptEnglish = [
"Renovation Plan Layout",
@@ -2019,7 +2052,7 @@ export function ChatPanel({
);
const prompts = settled.map((r, idx) => {
- const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("Drawing", "Drawing");
+ const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("图纸", "图纸");
const fallbackTitleForPrompt = fallbackTitlesForPromptEnglish[idx] || "Drawing";
const onSheetLanguageRule = "All on-sheet labels/notes/title block text must be in English.";
const fallbackPrompt = `Generate an orthographic 2D technical construction drawing sheet: ${fallbackTitleForPrompt}. Include border, bottom-right title block, scale/units, legend/symbols, key annotations and dimensions, consistent with the provided plan JSON and 2D SVG. ${onSheetLanguageRule}`;
@@ -2517,6 +2550,7 @@ export function ChatPanel({
setInput={setInput}
status={isLoading ? "streaming" : "idle"}
onDisplayChart={(xml) => onCodeAction?.(xml, 'flow')}
+ onApplyCode={applyCodeFromMessage}
onRegenerate={handleRegenerate}
onEditMessage={handleEditAndResend}
/>
diff --git a/src/workspaces/cad/chat/components/code-block.tsx b/src/workspaces/cad/chat/components/code-block.tsx
index e1a11dd..0d3eda8 100644
--- a/src/workspaces/cad/chat/components/code-block.tsx
+++ b/src/workspaces/cad/chat/components/code-block.tsx
@@ -1,5 +1,5 @@
import React, { useMemo, useState } from "react";
-import { Check, ChevronDown, ChevronUp, Copy, Cpu, X } from "lucide-react";
+import { Check, ChevronDown, ChevronUp, Copy, Cpu, Play, X } from "lucide-react";
import { Highlight, themes, type Language } from "prism-react-renderer";
interface CodeBlockProps {
@@ -7,6 +7,7 @@ interface CodeBlockProps {
language?: string;
isStreaming?: boolean;
blockId?: string;
+ onApply?: (code: string, language: string) => void | boolean | Promise<void | boolean>;
}
const openStateById = new Map<string, boolean>();
@@ -38,13 +39,16 @@ function formatXmlLike(input: string): string {
.join("\n");
}
-export function CodeBlock({ code, language = "xml", isStreaming = false, blockId }: CodeBlockProps) {
+export function CodeBlock({ code, language = "xml", isStreaming = false, blockId, onApply }: CodeBlockProps) {
const [isExpanded, setIsExpanded] = useState(() => {
if (blockId && openStateById.has(blockId)) return Boolean(openStateById.get(blockId));
return true;
});
const [copied, setCopied] = useState(false);
const [copyFailed, setCopyFailed] = useState(false);
+ const [applying, setApplying] = useState(false);
+ const [applied, setApplied] = useState(false);
+ const [applyFailed, setApplyFailed] = useState(false);
const normalizedLanguage = useMemo(() => (language || "text").toLowerCase(), [language]);
const normalizedCode = useMemo(() => String(code ?? ""), [code]);
const prismLanguage = useMemo<Language>(() => {
@@ -101,6 +105,29 @@ export function CodeBlock({ code, language = "xml", isStreaming = false, blockId
}
};
+ const applyCode = async () => {
+ if (!onApply || applying) return;
+ try {
+ setApplying(true);
+ const result = await onApply(normalizedCode, normalizedLanguage);
+ if (result === false) {
+ setApplyFailed(true);
+ setApplied(false);
+ setTimeout(() => setApplyFailed(false), 1500);
+ return;
+ }
+ setApplied(true);
+ setApplyFailed(false);
+ setTimeout(() => setApplied(false), 1500);
+ } catch {
+ setApplyFailed(true);
+ setApplied(false);
+ setTimeout(() => setApplyFailed(false), 1500);
+ } finally {
+ setApplying(false);
+ }
+ };
+
const setExpanded = (next: boolean) => {
setIsExpanded(next);
if (blockId) openStateById.set(blockId, next);
@@ -123,17 +150,39 @@ export function CodeBlock({ code, language = "xml", isStreaming = false, blockId
Complete
</span>
)}
- <button
- type="button"
- onClick={() => setExpanded(!isExpanded)}
- className="p-1 rounded hover:bg-muted transition-colors"
- >
- {isExpanded ? (
- <ChevronUp className="w-4 h-4 text-muted-foreground" />
- ) : (
- <ChevronDown className="w-4 h-4 text-muted-foreground" />
+ <div className="flex items-center gap-1">
+ {onApply && (
+ <button
+ type="button"
+ onClick={applyCode}
+ disabled={applying}
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-muted-foreground hover:bg-muted transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
+ title={applied ? "Applied" : applyFailed ? "Apply failed" : "Apply to canvas"}
+ >
+ {applying ? (
+ <div className="h-3 w-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />
+ ) : applied ? (
+ <Check className="h-3 w-3 text-green-500" />
+ ) : applyFailed ? (
+ <X className="h-3 w-3 text-red-500" />
+ ) : (
+ <Play className="h-3 w-3" />
+ )}
+ <span>{applying ? "Applying" : applied ? "Applied" : "Apply"}</span>
+ </button>
)}
- </button>
+ <button
+ type="button"
+ onClick={() => setExpanded(!isExpanded)}
+ className="p-1 rounded hover:bg-muted transition-colors"
+ >
+ {isExpanded ? (
+ <ChevronUp className="w-4 h-4 text-muted-foreground" />
+ ) : (
+ <ChevronDown className="w-4 h-4 text-muted-foreground" />
+ )}
+ </button>
+ </div>
</div>
</div>
{isExpanded && (
diff --git a/src/workspaces/cad/ui/code-block.tsx b/src/workspaces/cad/ui/code-block.tsx
index 5f0761c..a1b2275 100644
--- a/src/workspaces/cad/ui/code-block.tsx
+++ b/src/workspaces/cad/ui/code-block.tsx
@@ -1,5 +1,5 @@
import React, { useMemo, useState } from "react";
-import { Check, ChevronDown, ChevronUp, Copy, Cpu, X } from "lucide-react";
+import { Check, ChevronDown, ChevronUp, Copy, Cpu, Play, X } from "lucide-react";
import { Highlight, themes, type Language } from "prism-react-renderer";
interface CodeBlockProps {
@@ -7,6 +7,7 @@ interface CodeBlockProps {
language?: string;
isStreaming?: boolean;
blockId?: string;
+ onApply?: (code: string, language: string) => void | boolean | Promise<void | boolean>;
}
const openStateById = new Map<string, boolean>();
@@ -38,13 +39,22 @@ function formatXmlLike(input: string): string {
.join("\n");
}
-export function CodeBlock({ code, language = "xml", isStreaming: _isStreaming = false, blockId: _blockId }: CodeBlockProps) {
+export function CodeBlock({
+ code,
+ language = "xml",
+ isStreaming: _isStreaming = false,
+ blockId: _blockId,
+ onApply,
+}: CodeBlockProps) {
const [isExpanded, setIsExpanded] = useState(() => {
if (_blockId && openStateById.has(_blockId)) return Boolean(openStateById.get(_blockId));
return true;
});
const [copied, setCopied] = useState(false);
const [copyFailed, setCopyFailed] = useState(false);
+ const [applying, setApplying] = useState(false);
+ const [applied, setApplied] = useState(false);
+ const [applyFailed, setApplyFailed] = useState(false);
const normalizedLanguage = useMemo(() => (language || "text").toLowerCase(), [language]);
const normalizedCode = useMemo(() => String(code ?? ""), [code]);
const prismLanguage = useMemo<Language>(() => {
@@ -102,6 +112,29 @@ export function CodeBlock({ code, language = "xml", isStreaming: _isStreaming =
}
};
+ const applyCode = async () => {
+ if (!onApply || applying) return;
+ try {
+ setApplying(true);
+ const result = await onApply(normalizedCode, normalizedLanguage);
+ if (result === false) {
+ setApplyFailed(true);
+ setApplied(false);
+ setTimeout(() => setApplyFailed(false), 1500);
+ return;
+ }
+ setApplied(true);
+ setApplyFailed(false);
+ setTimeout(() => setApplied(false), 1500);
+ } catch {
+ setApplyFailed(true);
+ setApplied(false);
+ setTimeout(() => setApplyFailed(false), 1500);
+ } finally {
+ setApplying(false);
+ }
+ };
+
const setExpanded = (next: boolean) => {
setIsExpanded(next);
if (_blockId) openStateById.set(_blockId, next);
@@ -124,17 +157,39 @@ export function CodeBlock({ code, language = "xml", isStreaming: _isStreaming =
Complete
</span>
)}
- <button
- type="button"
- onClick={() => setExpanded(!isExpanded)}
- className="p-1 rounded hover:bg-muted transition-colors"
- >
- {isExpanded ? (
- <ChevronUp className="w-4 h-4 text-muted-foreground" />
- ) : (
- <ChevronDown className="w-4 h-4 text-muted-foreground" />
+ <div className="flex items-center gap-1">
+ {onApply && (
+ <button
+ type="button"
+ onClick={applyCode}
+ disabled={applying}
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-muted-foreground hover:bg-muted transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
+ title={applied ? "Applied" : applyFailed ? "Apply failed" : "Apply to canvas"}
+ >
+ {applying ? (
+ <div className="h-3 w-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />
+ ) : applied ? (
+ <Check className="h-3 w-3 text-green-500" />
+ ) : applyFailed ? (
+ <X className="h-3 w-3 text-red-500" />
+ ) : (
+ <Play className="h-3 w-3" />
+ )}
+ <span>{applying ? "Applying" : applied ? "Applied" : "Apply"}</span>
+ </button>
)}
- </button>
+ <button
+ type="button"
+ onClick={() => setExpanded(!isExpanded)}
+ className="p-1 rounded hover:bg-muted transition-colors"
+ >
+ {isExpanded ? (
+ <ChevronUp className="w-4 h-4 text-muted-foreground" />
+ ) : (
+ <ChevronDown className="w-4 h-4 text-muted-foreground" />
+ )}
+ </button>
+ </div>
</div>
</div>
{isExpanded && (
diff --git a/src/workspaces/cad/workspace/CadWorkspace.tsx b/src/workspaces/cad/workspace/CadWorkspace.tsx
index 25f0809..2e6aa9b 100644
--- a/src/workspaces/cad/workspace/CadWorkspace.tsx
+++ b/src/workspaces/cad/workspace/CadWorkspace.tsx
@@ -23,18 +23,19 @@ interface CadWorkspaceProps {
}
const RENDER_SLOT_TITLES = [
- "Renovation Plan Layout",
- "Floor Finish Plan",
- "Reflected Ceiling Plan",
- "Wall Setting-Out Plan",
- "MEP Plan (Electrical + Low Voltage + Plumbing)",
- "Elevation Index Plan + Interior Elevations",
- "Detail Drawings",
+ "装修平面布置图",
+ "地面铺装图",
+ "顶面布置图",
+ "墙体定位图",
+ "机电点位图(强弱电+给排水)",
+ "立面索引图+室内立面图",
+ "节点大样图",
];
const EMPTY_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1600 1000"></svg>`;
const EMPTY_SENTINEL = "__EMPTY_SVG__";
const ENABLE_EDITOR_AUTOSYNC = false;
+const SVG_EDITOR_IFRAME_PATH = "/svg-editor.html";
const normalizeSvgMarkup = (text: string) => {
const raw = String(text || "").trim();
@@ -47,6 +48,31 @@ const normalizeSvgMarkup = (text: string) => {
return tail.trim();
};
+const unwrapMarkdownStrong = (text: string) => {
+ let out = String(text || "").trim();
+ for (let i = 0; i < 3; i += 1) {
+ const fromAsterisks = out.replace(/^\*\*\s*([\s\S]*?)\s*\*\*$/u, "$1").trim();
+ if (fromAsterisks !== out) {
+ out = fromAsterisks;
+ continue;
+ }
+ const fromUnderscores = out.replace(/^__\s*([\s\S]*?)\s*__$/u, "$1").trim();
+ if (fromUnderscores !== out) {
+ out = fromUnderscores;
+ continue;
+ }
+ break;
+ }
+ return out;
+};
+
+const readBomCellText = (row: any, columns: string[], columnIndex: number) => {
+ const raw = Array.isArray(row) ? row[columnIndex] : row?.[columns[columnIndex]];
+ const text = String(raw ?? "").trim();
+ if (columnIndex === 0) return unwrapMarkdownStrong(text);
+ return text;
+};
+
const NON_CONTENT_PARENTS = new Set([
"defs",
"marker",
@@ -134,6 +160,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
const uiLang = useUiLanguage();
const svgEditorIframeRef = useRef<HTMLIFrameElement | null>(null);
const latestLoadedSvgRef = useRef<string>("");
+ const desiredSvgRef = useRef<string>("");
const svgEditorRequestSeedRef = useRef(0);
const svgEditorPendingRef = useRef<Map<string, (svg: string) => void>>(new Map());
const lastCanvasRecoverAtRef = useRef(0);
@@ -142,23 +169,21 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
if (typeof svg2d === "string") {
const normalized = normalizeSvgMarkup(svg2d);
setSvgContent(normalized || null);
- if (isSvgEditorReady) {
- if (normalized) {
- loadSvgToEditorWithRetry(normalized);
- latestLoadedSvgRef.current = normalized;
- } else {
- postToSvgEditor({ type: "cad_svg_editor_clear" });
- latestLoadedSvgRef.current = EMPTY_SENTINEL;
- }
+ desiredSvgRef.current = normalized;
+ if (normalized) {
+ loadSvgToEditorWithRetry(normalized);
+ latestLoadedSvgRef.current = normalized;
+ } else {
+ postToSvgEditor({ type: "cad_svg_editor_clear" });
+ latestLoadedSvgRef.current = EMPTY_SENTINEL;
}
return;
}
setSvgContent(null);
- if (isSvgEditorReady) {
- postToSvgEditor({ type: "cad_svg_editor_clear" });
- latestLoadedSvgRef.current = EMPTY_SENTINEL;
- }
- }, [svg2d, isSvgEditorReady]);
+ desiredSvgRef.current = "";
+ postToSvgEditor({ type: "cad_svg_editor_clear" });
+ latestLoadedSvgRef.current = EMPTY_SENTINEL;
+ }, [svg2d]);
const postToSvgEditor = (payload: Record<string, unknown>) => {
const win = svgEditorIframeRef.current?.contentWindow;
@@ -167,6 +192,32 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
return true;
};
+ const handleSvgEditorIframeLoad = () => {
+ setIsSvgEditorReady(false);
+ const iframe = svgEditorIframeRef.current;
+ const win = iframe?.contentWindow;
+ if (!iframe || !win) return;
+ try {
+ const href = String(win.location.href || "");
+ if (!href) return;
+ const url = new URL(href, window.location.origin);
+ const path = String(url.pathname || "");
+ if (path !== SVG_EDITOR_IFRAME_PATH) {
+ iframe.src = SVG_EDITOR_IFRAME_PATH;
+ return;
+ }
+ const next = String(desiredSvgRef.current || "").trim();
+ if (next) {
+ loadSvgToEditorWithRetry(next);
+ latestLoadedSvgRef.current = next;
+ } else {
+ postToSvgEditor({ type: "cad_svg_editor_clear" });
+ latestLoadedSvgRef.current = EMPTY_SENTINEL;
+ }
+ } catch {
+ }
+ };
+
const loadSvgToEditorWithRetry = (svg: string) => {
const normalized = normalizeSvgMarkup(svg);
if (!normalized) return false;
@@ -191,7 +242,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
if (type === "cad_svg_editor_ready") {
setIsSvgEditorReady(true);
- const next = normalizeSvgMarkup(typeof svgContent === "string" ? svgContent : "");
+ const next = String(desiredSvgRef.current || "").trim();
if (next) {
loadSvgToEditorWithRetry(next);
latestLoadedSvgRef.current = next;
@@ -214,7 +265,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
if (type === "cad_svg_editor_load_result") {
const ok = Boolean((data as any).ok);
if (ok) return;
- const next = normalizeSvgMarkup(typeof svgContent === "string" ? svgContent : "");
+ const next = String(desiredSvgRef.current || "").trim();
if (!next) return;
window.setTimeout(() => {
loadSvgToEditorWithRetry(next);
@@ -227,11 +278,11 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
window.removeEventListener("message", onMessage);
svgEditorPendingRef.current.clear();
};
- }, [svgContent]);
+ }, []);
useEffect(() => {
const next = normalizeSvgMarkup(typeof svgContent === "string" ? svgContent : "");
- if (!isSvgEditorReady) return;
+ desiredSvgRef.current = next;
if (next) {
if (latestLoadedSvgRef.current === next) return;
if (loadSvgToEditorWithRetry(next)) {
@@ -244,7 +295,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
if (postToSvgEditor({ type: "cad_svg_editor_clear" })) {
latestLoadedSvgRef.current = EMPTY_SENTINEL;
}
- }, [isSvgEditorReady, svgContent]);
+ }, [svgContent]);
useEffect(() => {
if (!Array.isArray(images) || images.length === 0) {
@@ -522,8 +573,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
const rows: string[] = [];
rows.push((bom.columns || []).map(esc).join(","));
for (const r of bom.rows || []) {
- const arr = Array.isArray(r) ? r : [];
- const fixed = (bom.columns || []).map((_, i) => esc(arr[i] ?? ""));
+ const fixed = (bom.columns || []).map((_, i) => esc(readBomCellText(r, bom.columns || [], i)));
rows.push(fixed.join(","));
}
const csv = `\uFEFF${rows.join("\r\n")}`;
@@ -537,7 +587,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
return RENDER_SLOT_TITLES.map((fallbackTitle, idx) => {
const item = localImages[idx];
return {
- title: item?.title || fallbackTitle,
+ title: fallbackTitle,
url: item?.url || "",
};
});
@@ -625,9 +675,9 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
<iframe
ref={svgEditorIframeRef}
title="CAD SVG Editor"
- src="/svg-editor.html"
+ src={SVG_EDITOR_IFRAME_PATH}
className="h-full w-full border-0"
- onLoad={() => setIsSvgEditorReady(false)}
+ onLoad={handleSvgEditorIframeLoad}
/>
</div>
)}
@@ -695,7 +745,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
<tr key={i} className="border-b border-border/40">
{bom.columns.map((_, ci) => (
<td key={ci} className="py-2 px-2 text-foreground/90 whitespace-normal break-words">
- {Array.isArray(r) ? String(r[ci] ?? "") : String(r?.[bom.columns[ci]] ?? "")}
+ {readBomCellText(r, bom.columns, ci)}
</td>
))}
</tr>
diff --git a/src/workspaces/flow/next/components/chat-message-display.tsx b/src/workspaces/flow/next/components/chat-message-display.tsx
index 6a876dd..dcd5428 100644
--- a/src/workspaces/flow/next/components/chat-message-display.tsx
+++ b/src/workspaces/flow/next/components/chat-message-display.tsx
@@ -13,6 +13,7 @@ import {
Loader2,
Minus,
Pencil,
+ Play,
Plus,
RotateCcw,
X,
@@ -30,6 +31,7 @@ import { ScrollArea } from "@/workspaces/flow/next/components/ui/scroll-area"
import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
import {
convertToLegalXml,
+ replaceXMLParts,
replaceNodes,
validateMxCellStructure,
} from "@/workspaces/flow/next/lib/utils"
@@ -259,6 +261,50 @@ export function ChatMessageDisplay({
}
}
+ const applyCodeToDiagram = useCallback(
+ async (code: string, language: "xml" | "json"): Promise<boolean> => {
+ const raw = String(code || "").trim()
+ if (!raw) return false
+ const baseXML =
+ chartXML ||
+ `<mxfile><diagram name="Page-1" id="page-1"><mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel></diagram></mxfile>`
+ try {
+ if (language === "xml") {
+ const nextXml = raw.includes("<mxfile")
+ ? raw
+ : replaceNodes(baseXML, convertToLegalXml(raw))
+ const err = onDisplayChart(nextXml, true)
+ return !err
+ }
+
+ const parsed = JSON.parse(raw)
+ if (parsed?.type === "flow_patch") {
+ if (String(parsed?.mode || "").trim() === "replace" && typeof parsed?.full === "string") {
+ const nextXml = String(parsed.full).trim()
+ if (!nextXml) return false
+ const err = onDisplayChart(nextXml, true)
+ return !err
+ }
+ if (Array.isArray(parsed?.edits) && parsed.edits.length > 0) {
+ const editedXml = replaceXMLParts(baseXML, parsed.edits)
+ const err = onDisplayChart(editedXml, true)
+ return !err
+ }
+ }
+ if (parsed?.type === "display_diagram" && typeof parsed?.xml === "string") {
+ const nextXml = String(parsed.xml).trim()
+ if (!nextXml) return false
+ const err = onDisplayChart(nextXml, true)
+ return !err
+ }
+ return false
+ } catch {
+ return false
+ }
+ },
+ [chartXML, onDisplayChart],
+ )
+
const handleDisplayChart = useCallback(
(xml: string) => {
const currentXml = xml || ""
@@ -408,16 +454,43 @@ export function ChatMessageDisplay({
{input && isExpanded && (
<div className="px-4 py-3 border-t border-border/40 bg-muted/20">
{typeof input === "object" && input.xml ? (
- <CodeBlock code={input.xml} language="xml" />
+ <CodeBlock code={input.xml} language="xml" onApply={applyCodeToDiagram} />
) : typeof input === "object" &&
input.edits &&
Array.isArray(input.edits) ? (
- <EditDiffDisplay edits={input.edits} />
+ <div className="space-y-2">
+ <div className="flex justify-end">
+ <button
+ type="button"
+ onClick={() =>
+ void applyCodeToDiagram(
+ JSON.stringify(
+ {
+ type: "flow_patch",
+ mode: "patch",
+ edits: input.edits,
+ },
+ null,
+ 2,
+ ),
+ "json",
+ )
+ }
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-muted-foreground hover:bg-muted transition-colors"
+ title="Apply to canvas"
+ >
+ <Play className="h-3 w-3" />
+ <span>Apply</span>
+ </button>
+ </div>
+ <EditDiffDisplay edits={input.edits} />
+ </div>
) : typeof input === "object" &&
Object.keys(input).length > 0 ? (
<CodeBlock
code={JSON.stringify(input, null, 2)}
language="json"
+ onApply={applyCodeToDiagram}
/>
) : null}
</div>
@@ -1030,7 +1103,31 @@ export function ChatMessageDisplay({
key={`${message.id}-textsection-${partIndex}-${sectionIndex}`}
className="prose prose-sm max-w-none break-words [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 dark:prose-invert"
>
- <ReactMarkdown>
+ <ReactMarkdown
+ components={{
+ code({ inline, className, children, ...props }: any) {
+ if (inline) {
+ return (
+ <code className={className} {...props}>
+ {children}
+ </code>
+ )
+ }
+ const match = /language-(\w+)/.exec(String(className || ""))
+ const lang = String(match?.[1] || "xml").toLowerCase()
+ const codeText = String(children || "").replace(/\n$/, "")
+ const normalizedLang: "xml" | "json" =
+ lang === "json" ? "json" : "xml"
+ return (
+ <CodeBlock
+ code={codeText}
+ language={normalizedLang}
+ onApply={applyCodeToDiagram}
+ />
+ )
+ },
+ }}
+ >
{
section.content
}
diff --git a/src/workspaces/flow/next/components/code-block.tsx b/src/workspaces/flow/next/components/code-block.tsx
index 45948d0..e403712 100644
--- a/src/workspaces/flow/next/components/code-block.tsx
+++ b/src/workspaces/flow/next/components/code-block.tsx
@@ -1,17 +1,21 @@
"use client"
-import { Check, Copy, X } from "lucide-react"
+import { Check, Copy, Play, X } from "lucide-react"
import { Highlight, themes } from "prism-react-renderer"
import { useState } from "react"
interface CodeBlockProps {
code: string
language?: "xml" | "json"
+ onApply?: (code: string, language: "xml" | "json") => void | boolean | Promise<void | boolean>
}
-export function CodeBlock({ code, language = "xml" }: CodeBlockProps) {
+export function CodeBlock({ code, language = "xml", onApply }: CodeBlockProps) {
const [copied, setCopied] = useState(false)
const [copyFailed, setCopyFailed] = useState(false)
+ const [applying, setApplying] = useState(false)
+ const [applied, setApplied] = useState(false)
+ const [applyFailed, setApplyFailed] = useState(false)
const copyCode = async () => {
try {
@@ -26,9 +30,52 @@ export function CodeBlock({ code, language = "xml" }: CodeBlockProps) {
}
}
+ const applyCode = async () => {
+ if (!onApply || applying) return
+ try {
+ setApplying(true)
+ const result = await onApply(code, language)
+ if (result === false) {
+ setApplyFailed(true)
+ setApplied(false)
+ setTimeout(() => setApplyFailed(false), 1500)
+ return
+ }
+ setApplied(true)
+ setApplyFailed(false)
+ setTimeout(() => setApplied(false), 1500)
+ } catch {
+ setApplyFailed(true)
+ setApplied(false)
+ setTimeout(() => setApplyFailed(false), 1500)
+ } finally {
+ setApplying(false)
+ }
+ }
+
return (
<div className="overflow-hidden w-full">
- <div className="mb-1 flex justify-end">
+ <div className="mb-1 flex justify-end gap-1">
+ {onApply ? (
+ <button
+ type="button"
+ onClick={applyCode}
+ disabled={applying}
+ className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-muted-foreground hover:bg-muted transition-colors disabled:opacity-60 disabled:cursor-not-allowed"
+ title={applied ? "Applied" : applyFailed ? "Apply failed" : "Apply to canvas"}
+ >
+ {applying ? (
+ <div className="h-3 w-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />
+ ) : applied ? (
+ <Check className="h-3 w-3 text-green-500" />
+ ) : applyFailed ? (
+ <X className="h-3 w-3 text-red-500" />
+ ) : (
+ <Play className="h-3 w-3" />
+ )}
+ <span>{applying ? "Applying" : applied ? "Applied" : "Apply"}</span>
+ </button>
+ ) : null}
<button
type="button"
onClick={copyCode}
diff --git a/src/workspaces/flow/next/lib/pdf-utils.ts b/src/workspaces/flow/next/lib/pdf-utils.ts
index cb04b1c..bba5d76 100644
--- a/src/workspaces/flow/next/lib/pdf-utils.ts
+++ b/src/workspaces/flow/next/lib/pdf-utils.ts
@@ -576,7 +576,7 @@ export async function extractLatexTarGzVisualAssets(
export interface ExtractedVisualAsset {
id: string
sourceFileName: string
- sourceType: "pdf" | "word" | "latex"
+ sourceType: "pdf" | "word" | "latex" | "third_party"
page?: number
order: number
dataUrl: string
@@ -1467,4 +1467,165 @@ export async function extractWordVisualAssets(
return assets
}
+const normalizeMineruImagePath = (rawPath: string) => {
+ let p = String(rawPath || "").trim().replace(/^['"]|['"]$/g, "")
+ if (!p) return ""
+ p = p.replace(/\\/g, "/")
+ if (p.startsWith("/")) p = p.slice(1)
+ if (p.startsWith("file/")) p = p.slice(5)
+ if (p.startsWith("files/")) p = p.slice(6)
+ return p
+}
+
+const findZipImageEntry = (zip: JSZip, relPath: string) => {
+ const target = normalizeMineruImagePath(relPath).toLowerCase()
+ if (!target) return null
+ const entries = Object.values(zip.files).filter((f) => !f.dir)
+ const exact = entries.find((e) => String(e.name || "").replace(/\\/g, "/").toLowerCase() === target)
+ if (exact) return exact
+ const suffix = `/${target}`
+ return entries.find((e) => {
+ const name = String(e.name || "").replace(/\\/g, "/").toLowerCase()
+ return name.endsWith(suffix) || name.endsWith(target)
+ }) || null
+}
+
+export async function extractThirdPartyVisualAssets(
+ file: File,
+ options: { apiToken: string; apiBase?: string; maxAssets?: number; maxWaitMs?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const token = String(options.apiToken || "").trim()
+ if (!token) throw new Error("Third-party parser token is empty")
+ const apiBase = String(options.apiBase || "https://mineru.net").trim().replace(/\/+$/, "")
+ const maxAssets = Math.max(1, options.maxAssets ?? 10)
+ const maxWaitMs = Math.max(5000, options.maxWaitMs ?? 120000)
+
+ const reqHeaders: Record<string, string> = {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${token}`,
+ }
+
+ const uploadUrlResp = await fetch(`${apiBase}/api/v4/file-urls/batch`, {
+ method: "POST",
+ headers: reqHeaders,
+ body: JSON.stringify({
+ files: [{ name: file.name }],
+ model_version: "vlm",
+ }),
+ })
+ if (!uploadUrlResp.ok) {
+ throw new Error(`Third-party parser request failed: ${uploadUrlResp.status}`)
+ }
+ const uploadPayload = await uploadUrlResp.json()
+ if (uploadPayload?.code !== 0) {
+ throw new Error(String(uploadPayload?.msg || "Third-party parser get upload URL failed"))
+ }
+
+ const batchId = String(uploadPayload?.data?.batch_id || "")
+ const uploadUrl = String(uploadPayload?.data?.file_urls?.[0] || "")
+ if (!batchId || !uploadUrl) throw new Error("Third-party parser missing batch id or upload URL")
+
+ const uploadResp = await fetch(uploadUrl, {
+ method: "PUT",
+ body: file,
+ })
+ if (!uploadResp.ok) throw new Error(`Third-party parser upload failed: ${uploadResp.status}`)
+
+ const resultUrl = `${apiBase}/api/v4/extract-results/batch/${batchId}`
+ const start = Date.now()
+ let fullZipUrl = ""
+ while (Date.now() - start < maxWaitMs) {
+ const pollResp = await fetch(resultUrl, { headers: { Authorization: `Bearer ${token}` } })
+ if (!pollResp.ok) throw new Error(`Third-party parser poll failed: ${pollResp.status}`)
+ const pollPayload = await pollResp.json()
+ if (pollPayload?.code !== 0) {
+ throw new Error(String(pollPayload?.msg || "Third-party parser poll returned error"))
+ }
+
+ const extractResult = pollPayload?.data?.extract_result?.[0]
+ const state = String(extractResult?.state || "")
+ if (state === "done") {
+ fullZipUrl = String(extractResult?.full_zip_url || "")
+ break
+ }
+ if (state === "failed") {
+ throw new Error(String(extractResult?.err_msg || "Third-party parser extraction failed"))
+ }
+ await new Promise((r) => setTimeout(r, 2000))
+ }
+ if (!fullZipUrl) throw new Error("Third-party parser timeout")
+
+ const zipResp = await fetch(fullZipUrl)
+ if (!zipResp.ok) throw new Error(`Third-party parser result download failed: ${zipResp.status}`)
+ const zipArrayBuffer = await zipResp.arrayBuffer()
+ const zip = await JSZip.loadAsync(zipArrayBuffer)
+
+ const markdownEntry =
+ Object.values(zip.files).find((f) => !f.dir && /\.md$/i.test(String(f.name || ""))) || null
+ const markdown = markdownEntry ? await markdownEntry.async("string") : ""
+
+ const usedImageNames = new Set<string>()
+ const assets: ExtractedVisualAsset[] = []
+
+ if (markdown) {
+ const imageRe = /!\[([^\]]*)\]\(([^)]+)\)/g
+ let match: RegExpExecArray | null
+ while ((match = imageRe.exec(markdown))) {
+ if (assets.length >= maxAssets) break
+ const alt = String(match[1] || "").trim()
+ const relPath = String(match[2] || "").trim()
+ if (!relPath || /^https?:\/\//i.test(relPath)) continue
+
+ const entry = findZipImageEntry(zip, relPath)
+ if (!entry) continue
+ const entryName = String(entry.name || "")
+ if (usedImageNames.has(entryName)) continue
+
+ try {
+ const bytes = await entry.async("uint8array")
+ const mime = getMimeByExt(entryName)
+ assets.push({
+ id: `third-party-${file.name}-${assets.length + 1}`,
+ sourceFileName: file.name,
+ sourceType: "third_party",
+ order: assets.length + 1,
+ dataUrl: `data:${mime};base64,${bytesToBase64(bytes)}`,
+ textHint: alt,
+ })
+ usedImageNames.add(entryName)
+ } catch (e) {
+ console.error("Failed to load third-party extracted image", entryName, e)
+ }
+ }
+ }
+
+ if (assets.length < maxAssets) {
+ const imageEntries = Object.values(zip.files)
+ .filter((f) => !f.dir)
+ .filter((f) => /\.(png|jpg|jpeg|webp|gif|bmp|svg)$/i.test(String(f.name || "")))
+ for (const entry of imageEntries) {
+ if (assets.length >= maxAssets) break
+ const entryName = String(entry.name || "")
+ if (usedImageNames.has(entryName)) continue
+ try {
+ const bytes = await entry.async("uint8array")
+ const mime = getMimeByExt(entryName)
+ assets.push({
+ id: `third-party-${file.name}-${assets.length + 1}`,
+ sourceFileName: file.name,
+ sourceType: "third_party",
+ order: assets.length + 1,
+ dataUrl: `data:${mime};base64,${bytesToBase64(bytes)}`,
+ textHint: "",
+ })
+ usedImageNames.add(entryName)
+ } catch (e) {
+ console.error("Failed to load fallback image from third-party zip", entryName, e)
+ }
+ }
+ }
+
+ return assets
+}
+
diff --git a/src/workspaces/flow/next/lib/use-file-processor.tsx b/src/workspaces/flow/next/lib/use-file-processor.tsx
index 279428d..5ccb70e 100644
--- a/src/workspaces/flow/next/lib/use-file-processor.tsx
+++ b/src/workspaces/flow/next/lib/use-file-processor.tsx
@@ -8,6 +8,7 @@ import {
extractTextFileContent,
extractPdfVisualAssets,
extractWordVisualAssets,
+ extractThirdPartyVisualAssets,
extractLatexZipText,
extractLatexZipVisualAssets,
extractLatexTarGzText,
@@ -20,6 +21,7 @@ import {
isTarGzFile,
MAX_EXTRACTED_CHARS,
} from "@/workspaces/flow/next/lib/pdf-utils"
+import { getAIConfig } from "@/lib/ai-client"
export interface FileData {
text: string
@@ -42,7 +44,11 @@ export function useFileProcessor() {
// Extract text immediately for new PDF/text files
for (const file of newFiles) {
const needsExtraction =
- (isPdfFile(file) || isWordFile(file) || isTextFile(file) || isZipFile(file) || isTarGzFile(file)) &&
+ (isPdfFile(file) ||
+ isWordFile(file) ||
+ isTextFile(file) ||
+ isZipFile(file) ||
+ isTarGzFile(file)) &&
!pdfData.has(file)
if (needsExtraction) {
// Mark as extracting
@@ -58,14 +64,44 @@ export function useFileProcessor() {
// Extract text asynchronously
try {
+ const aiConfig = getAIConfig()
+ const parserToken = String(aiConfig.fileParserApiToken || "").trim()
+ const parserBase = "https://mineru.net"
+ const supportsThirdParty = isPdfFile(file) || isWordFile(file)
+ const useThirdPartyVisualParser = Boolean(parserToken) && supportsThirdParty
+
let text: string
let visualAssets: ExtractedVisualAsset[] = []
if (isPdfFile(file)) {
text = await extractPdfText(file)
- visualAssets = await extractPdfVisualAssets(file)
+ if (useThirdPartyVisualParser) {
+ try {
+ visualAssets = await extractThirdPartyVisualAssets(file, {
+ apiBase: parserBase,
+ apiToken: parserToken,
+ })
+ } catch (e) {
+ console.error("Third-party parser failed, fallback to local PDF extraction:", e)
+ visualAssets = await extractPdfVisualAssets(file)
+ }
+ } else {
+ visualAssets = await extractPdfVisualAssets(file)
+ }
} else if (isWordFile(file)) {
text = await extractWordText(file)
- visualAssets = await extractWordVisualAssets(file)
+ if (useThirdPartyVisualParser) {
+ try {
+ visualAssets = await extractThirdPartyVisualAssets(file, {
+ apiBase: parserBase,
+ apiToken: parserToken,
+ })
+ } catch (e) {
+ console.error("Third-party parser failed, fallback to local Word extraction:", e)
+ visualAssets = await extractWordVisualAssets(file)
+ }
+ } else {
+ visualAssets = await extractWordVisualAssets(file)
+ }
} else if (isZipFile(file)) {
// LaTeX bundle (.zip): parse tex + includegraphics to extract original figures.
text = await extractLatexZipText(file)