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.

version_1.0

codingFeng10136b0833120df
diff --git a/.gitignore b/.gitignore
index 54f07af..d71f6ce 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,19 @@
+# Dependencies
+node_modules/
+.pnpm-store/
+.npm/
+.yarn/
+
+# Build outputs
+dist/
+dist-ssr/
+build/
+coverage/
+*.tsbuildinfo
+vite.svg
+
# Logs
-logs
+logs/
*.log
npm-debug.log*
yarn-debug.log*
@@ -7,18 +21,38 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
-node_modules
-dist
-dist-ssr
+# Env / local config
+.env
+.env.*
+!.env.example
*.local
-# Editor directories and files
+# Cache / temp
+.cache/
+.vite/
+.eslintcache
+tmp/
+temp/
+*.tmp
+*.temp
+
+# Local tool workspaces (not project source)
+.tmp-superpowers/
+.trae/
+
+# IDE / editor
.vscode/*
!.vscode/extensions.json
-.idea
-.DS_Store
+.idea/
*.suo
*.ntvs*
*.njsproj
*.sln
-*.sw?
\ No newline at end of file
+*.sw?
+*.swp
+*.swo
+
+# OS
+.DS_Store
+Thumbs.db
+Desktop.ini
diff --git a/.trae/skills/cnlp-prompt-refactor/SKILL.md b/.trae/skills/cnlp-prompt-refactor/SKILL.md
deleted file mode 100644
index a31efaa..0000000
--- a/.trae/skills/cnlp-prompt-refactor/SKILL.md
+++ /dev/null
@@ -1,269 +0,0 @@
----
-name: "cnlp-prompt-refactor"
-description: "把现有智能体 prompt 重构为 CNL-P Agent 结构,并统一变量占位符({{var}})以便跨语言渲染。需要标准化/重构 prompt 时调用。"
----
-
-# CNL-P Prompt Refactor
-
-将任意“散装 prompt”重构为可维护的 CNL-P Agent 结构(Persona/Audience/Constraints/Concepts/Worker/Flow),同时解决“变量如何在不同语言里嵌入”的工程问题:统一使用 `{{var}}` 作为运行时占位符,并生成各语言渲染方式。
-
-## 何时调用
-
-- 你已经有一段可用但难维护的 prompt,需要拆成明确模块并可复用
-- 你希望把变量从 prompt 中抽离出来,并能在不同语言中稳定注入
-- 你想为某个 Agent 制定清晰的输入/输出契约、执行流程、异常路径与示例
-
-## 你需要我提供的输入(按可得信息给即可)
-
-- 原始 prompt(system/developer/user 任意形态都行)
-- 变量清单(名称、含义、是否必填、期望类型;没有就让我从 prompt 推断)
-- 运行时注入环境(Python/JS/TS/Go/Java/C#…;不知道就默认 JS/TS)
-- 期望输出形态(纯文本、JSON、Markdown、表格等)
-
-## 输出内容(我会生成这些)
-
-- 一份重构后的 CNL-P Agent Prompt(可直接复制使用)
-- 一份变量契约(变量名、类型、必填/可选、默认值/约束)
-- 一份“渲染/注入”适配说明(把 `{{var}}` 填入模板的多语言方式)
-
-## 占位符策略(解决“语法里变量引用 vs 工程注入”冲突)
-
-CNL-P 语法里的引用常写作 `<REF>var_name</REF>`(语义上表示“这里引用变量内容”)。但在工程侧,各语言模板系统不统一:Python `format` 用 `{}`, JS 模板字符串用 `${}`, Go `text/template` 用 `{{.Var}}` 等。
-
-因此本技能采用两层约定:
-
-- **语义层(CNL-P)**:在结构化 prompt 中保留变量名与 I/O 契约(`VARIABLE`、`INPUTS`、`OUTPUTS`),必要时也可写 `<REF>var</REF>` 增强可读性
-- **渲染层(运行时)**:所有需要被程序注入的值,统一在最终发给模型的字符串中使用 `{{var}}`
-
-实操建议(默认做法):
-
-- 在 CNL-P 结构中,正文描述直接写 `{{var}}`,同时在 `VARIABLE`/`INPUTS` 中声明它
-- 如果你更偏“语义可读”,正文可写 `<REF>var</REF>`,并在最后一步把 `<REF>var</REF>` 预处理替换为 `{{var}}` 再渲染
-
-## CNL-P 结构模板(我会按这个组织)
-
-```text
-+DEFINE_AGENT: <agentName> <one-line description>]
-
-+DEFINE_PERSONA:
-Role: <description>
-...(可选更多 AspectName: description)
-+END_PERSONA
-
-+DEFINE_AUDIENCE:
-Audience: <description>
-+END_AUDIENCE
-
-+DEFINE_CONSTRAINTS:
-...(格式/内容/安全/风格等)
-+END_CONSTRAINTS
-
-+DEFINE_CONCEPTS:
-...(术语定义、缩写消歧)
-+END_CONCEPTS
-
-TYPES:
-...(描述会处理的数据类型/Schema)
-
-VARIABLE:
-...(列出会使用/操作的变量,名称+含义+类型+默认值)
-
-+DEFINE_WORKER: <workerName> <what this worker does>]
- ++INPUTS
- REQUIRED <REF>var1</REF>
- OPTIONAL <REF>var2</REF>
- ++END_INPUTS
-
- ++OUTPUTS
- <REF>result1</REF>
- ++END_OUTPUTS
-
- ++EXAMPLES
- <EXPECTED_WORKER_BEHAVIOR> { ... } </EXPECTED_WORKER_BEHAVIOR>
- <DEFECT_WORKER_BEHAVIOR> { defect-type, ... } </DEFECT_WORKER_BEHAVIOR>
- ++END_EXAMPLES
-
- ++MAIN_FLOW
- ++SEQUENTIAL_BLOCK
- COMMAND-1: ...
- COMMAND-2: ...
- ++END_SEQUENTIAL_BLOCK
- ++END_MAIN_FLOW
-
- ++ALTERNATIVE_FLOW: <when triggered>]
- ...
- ++END_ALTERNATIVE_FLOW
-
- ++EXCEPTION_FLOW: <when triggered>]
- LOG: ...
- ...
- ++END_EXCEPTION_FLOW
-+END_WORKER
-
-+END_AGENT
-```
-
-约束遵循:
-
-- `SEQUENTIAL_BLOCK / IF_BLOCK / LOOP_BLOCK` 不嵌套;复杂逻辑拆成新的 `FLOW`
-- `EXAMPLES` 同时提供“期望行为”和“缺陷行为”(缺陷类型+解释)
-
-## 变量注入:各语言最小可用做法(统一处理 `{{var}}`)
-
-下面示例都把 `template` 里的 `{{key}}` 替换为 `vars[key]` 的字符串形式。默认不存在的 key 替换为空字符串(你也可以改为抛错)。
-
-### JavaScript / TypeScript
-
-```ts
-export function renderTemplate(template: string, vars: Record<string, unknown>) {
- return template.replace(/\{\{\s*([a-zA-Z_]\w*)\s*\}\}/g, (_, key) => {
- const v = (vars as any)[key];
- return v === undefined || v === null ? "" : String(v);
- });
-}
-```
-
-### Python
-
-```python
-import re
-
-def render_template(template: str, vars: dict) -> str:
- def repl(m):
- key = m.group(1)
- v = vars.get(key)
- return "" if v is None else str(v)
- return re.sub(r"\{\{\s*([a-zA-Z_]\w*)\s*\}\}", repl, template)
-```
-
-### Go(推荐使用 text/template;先把 `{{var}}` 转为 `{{.var}}`)
-
-```go
-package prompt
-
-import (
- "bytes"
- "regexp"
- "text/template"
-)
-
-var mustacheVar = regexp.MustCompile(`\{\{\s*([a-zA-Z_]\w*)\s*\}\}`)
-
-func RenderTemplate(tpl string, vars map[string]any) (string, error) {
- goTpl := mustacheVar.ReplaceAllString(tpl, "{{.$1}}")
- t, err := template.New("prompt").Option("missingkey=zero").Parse(goTpl)
- if err != nil {
- return "", err
- }
- var buf bytes.Buffer
- if err := t.Execute(&buf, vars); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
-```
-
-### Java / C#
-
-Java(Pattern/Matcher):
-
-```java
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public final class PromptTemplate {
- private static final Pattern VAR = Pattern.compile("\\\\{\\\\{\\\\s*([a-zA-Z_]\\\\w*)\\\\s*\\\\}\\\\}");
-
- public static String render(String template, Map<String, ?> vars) {
- Matcher m = VAR.matcher(template);
- StringBuffer sb = new StringBuffer();
- while (m.find()) {
- String key = m.group(1);
- Object v = vars.get(key);
- m.appendReplacement(sb, Matcher.quoteReplacement(v == null ? "" : String.valueOf(v)));
- }
- m.appendTail(sb);
- return sb.toString();
- }
-}
-```
-
-C#(Regex):
-
-```csharp
-using System.Collections.Generic;
-using System.Text.RegularExpressions;
-
-public static class PromptTemplate
-{
- private static readonly Regex Var = new(@"\{\{\s*([a-zA-Z_]\w*)\s*\}\}", RegexOptions.Compiled);
-
- public static string Render(string template, IReadOnlyDictionary<string, object?> vars)
- => Var.Replace(template, m =>
- {
- var key = m.Groups[1].Value;
- return vars.TryGetValue(key, out var v) && v is not null ? v.ToString()! : "";
- });
-}
-```
-
-## 重构规则(我会自动执行)
-
-- 把“身份/语气/风格”归入 `PERSONA`
-- 把“目标读者/输出层级”归入 `AUDIENCE`
-- 把“必须/禁止/格式”归入 `CONSTRAINTS`
-- 把“术语定义、缩写消歧”归入 `CONCEPTS`
-- 把“输入/输出字段”显式写入 `INPUTS/OUTPUTS`,并同步到 `VARIABLE`
-- 把“步骤/流程”拆成 `MAIN_FLOW`,必要时加 `ALTERNATIVE_FLOW/EXCEPTION_FLOW`
-- 把隐含变量(如 “公司名/产品名/日期/语气”)抽成 `{{var}}` 并写清楚含义
-
-## 示例:把普通 prompt 重构为 CNL-P(示意)
-
-原始 prompt(散装):
-
-```text
-你是资深后端工程师。根据用户给的需求描述,输出一份接口设计(含字段、错误码、示例请求响应),要求用 Markdown。
-需求描述:{{requirement}}
-服务名:{{service_name}}
-```
-
-重构后的关键片段(示意):
-
-```text
-+DEFINE_AGENT: ApiDesigner 生成接口设计文档]
-
-+DEFINE_PERSONA:
-Role: 资深后端工程师,输出严谨、可落地的接口设计
-+END_PERSONA
-
-+DEFINE_CONSTRAINTS:
-OutputFormat: 使用 Markdown,包含字段表、错误码表、示例请求/响应
-NoSecrets: 不输出任何密钥或内部敏感信息
-+END_CONSTRAINTS
-
-VARIABLE:
-requirement: 用户需求描述(text,必填)
-service_name: 服务名(text,必填)
-
-+DEFINE_WORKER: DesignAPI 基于需求生成接口设计]
- ++INPUTS
- REQUIRED <REF>requirement</REF>
- REQUIRED <REF>service_name</REF>
- ++END_INPUTS
- ++OUTPUTS
- <REF>api_doc</REF>
- ++END_OUTPUTS
- ++MAIN_FLOW
- ++SEQUENTIAL_BLOCK
- COMMAND-1: 解析 {{requirement}},抽取资源、动作、实体字段
- COMMAND-2: 设计接口列表与路径,统一命名到 {{service_name}} 语境
- COMMAND-3: 生成 Markdown 文档输出为 api_doc
- ++END_SEQUENTIAL_BLOCK
- ++END_MAIN_FLOW
-+END_WORKER
-
-+END_AGENT
-```
-
-如果你希望正文用 `<REF>requirement</REF>`,我会在最后附上“将 `<REF>` 预处理成 `{{}}`”的规则,让你在运行时统一渲染。
diff --git a/.trae/skills/frontend-designer/SKILL.md b/.trae/skills/frontend-designer/SKILL.md
deleted file mode 100644
index ea94b59..0000000
--- a/.trae/skills/frontend-designer/SKILL.md
+++ /dev/null
@@ -1,44 +0,0 @@
----
-name: "frontend-designer"
-description: "Generates beautiful, modern UI designs using Tailwind CSS and React. Invoke when user asks to improve UI, style, layout, or visual appearance of the application."
----
-
-# Frontend Designer
-
-This skill focuses on creating high-quality, modern, and accessible user interfaces.
-
-## Capabilities
-
-- **Tailwind CSS Mastery**: Use advanced Tailwind utility classes for layout, typography, colors, and effects.
-- **Component Design**: Create reusable, composable React components.
-- **Responsive Design**: Ensure layouts work seamlessly across mobile, tablet, and desktop.
-- **Accessibility**: Implement ARIA attributes and keyboard navigation.
-- **Animation**: Use CSS transitions and animations for delightful micro-interactions.
-
-## Guidelines
-
-1. **Modern Aesthetic**: Prefer clean, minimal, and whitespace-generous designs (e.g., shadcn/ui style).
-2. **Color Palette**: Use semantic color names (bg-background, text-foreground) for dark mode support.
-3. **Typography**: Use clear, legible font stacks.
-4. **Icons**: Use Lucide React icons for visual cues.
-5. **Feedback**: Provide visual feedback for interactions (hover, focus, active states).
-
-## Example: Creating a Card Component
-
-```tsx
-import { cn } from "@/lib/utils";
-
-interface CardProps extends React.HTMLAttributes<HTMLDivElement> {}
-
-export function Card({ className, ...props }: CardProps) {
- return (
- <div
- className={cn(
- "rounded-xl border bg-card text-card-foreground shadow-sm",
- className
- )}
- {...props}
- />
- );
-}
-```
\ No newline at end of file
diff --git a/.trae/skills/risen-prompt-refactor/SKILL.md b/.trae/skills/risen-prompt-refactor/SKILL.md
deleted file mode 100644
index e6ab315..0000000
--- a/.trae/skills/risen-prompt-refactor/SKILL.md
+++ /dev/null
@@ -1,210 +0,0 @@
----
-name: "risen-prompt-refactor"
-description: "把现有智能体 prompt 重构为 RISEN(含 Input/Output)结构,并统一变量占位符为 {{var}} 便于跨语言注入。需要用 RISEN 标准化 prompt 时调用。"
----
-
-# RISEN Prompt Refactor(含 Input/Output)
-
-将任意“散装 prompt / 现有智能体 prompt”重构为增强版 RISEN 提示词结构(R / I / Input / S / E / N / Output),并把所有运行时变量统一为 `{{var}}` 占位符,确保在 Python/JS/TS/Go/Java/C# 等语言里都能稳定注入。
-
-## 何时调用
-
-- 你想把一个混乱的 prompt 改成可复用、可验收、可控输出的结构
-- 你希望明确 Input/Output 契约,让模型不跑偏
-- 你需要把 prompt 变量工程化(统一 `{{var}}`,跨语言渲染)
-
-## 你给我什么
-
-- 原始 prompt(system/developer/user 任意形态)
-- 已知变量(可选):变量名、含义、是否必填、类型/范围
-- 目标语言/运行环境(可选):Python/TS/Go/Java/C#…
-- 输出偏好(可选):Markdown/JSON/纯文本/表格/代码块
-
-## 我输出什么
-
-- 一份重构后的 RISEN Prompt(可直接复制使用)
-- 一份变量契约(变量名、含义、必填/可选、类型、默认值/约束)
-- 一份跨语言注入说明(如何把 `{{var}}` 渲染为最终 prompt)
-
-## RISEN 固定结构(增强版,含 I/O 的位置)
-
-你可以把它理解为“强约束的写作骨架”,关键点是 **Input 固定在 I 之后、S 之前;Output 固定在 N 之后,独立一段**。
-
-```text
-# R - Role
-你是[领域 + 资深程度],擅长[核心能力1 + 核心能力2],语气[简洁严谨/亲切接地气/专业规范],能精准匹配[任务场景]需求,不输出冗余内容、不偏离专业范围。
-
-# I - Instructions
-你的核心任务:[用“动词 + 宾语”的句式,明确 1 个核心任务,不模糊、不冗余]
-
-# Input
-我将给你的输入内容:
-- 输入类型:[文本/表格/代码片段/关键词列表/文件路径…]
-- 输入格式:[每行1条/分点列出/自由文本/两行输入…]
-- 输入范围:[只处理什么/忽略什么/时间范围/类型范围…]
-
-# S - Steps
-请严格按以下步骤执行:
-1. [步骤1:一个具体动作]
-2. [步骤2:一个具体动作]
-3. [步骤3:一个具体动作]
-4. [步骤4:一个具体动作]
-
-# E - End Goal
-最终要达成的效果/验收标准:[关联用户价值 + 明确完成标准]
-
-# N - Narrowing
-约束条件:
-1. 内容约束:[只允许/禁止的内容范围]
-2. 格式约束:[输出格式、是否允许解释、符号规则…]
-3. 量化约束:[字数/准确率/时长/条目数/复杂度…]
-4. 其他约束:[风格一致性/技术限制/禁用项…]
-
-# Output Format
-输出必须严格遵循以下格式:
-1. 结构:[表格/一段式/分点/代码块(含运行示例)…]
-2. 格式符号:[标题/加粗/分隔线/日期格式/代码块语言…]
-3. 禁止:[禁止额外解释/标题/备注/冗余内容/报错崩溃…]
-4. 补充说明(可选):[异常提示格式/示例风格参考…]
-```
-
-## 变量与注入:不必拘泥“Input 里写死真实值”
-
-RISEN 的 Input 目的是“告诉模型你会提供什么”,工程上你完全可以把真实输入作为变量在运行时注入。
-
-推荐约定:
-
-- prompt 内所有需要运行时填充的内容,一律写成 `{{var}}`
-- Input 模块描述“你将给什么类型/格式/范围”,并在其中引用 `{{var}}` 来点明变量与用途
-- Output 模块描述“最终输出的结构/格式/禁止项”,不要把变量值写死在这里
-
-示例(Input 中引用运行时变量):
-
-```text
-# Input
-我将给你的输入内容:
-- 输入类型:需求描述文本
-- 输入格式:自由文本
-- 输入范围:仅处理该需求相关内容
-
-需求描述如下:
-{{requirement}}
-```
-
-## 跨语言渲染/注入(统一处理 `{{var}}`)
-
-下面示例将 `template` 中的 `{{key}}` 替换为 `vars[key]` 的字符串。未提供的 key 默认替换为空字符串(也可改为抛错)。
-
-### JavaScript / TypeScript
-
-```ts
-export function renderTemplate(template: string, vars: Record<string, unknown>) {
- return template.replace(/\{\{\s*([a-zA-Z_]\w*)\s*\}\}/g, (_, key) => {
- const v = (vars as any)[key];
- return v === undefined || v === null ? "" : String(v);
- });
-}
-```
-
-### Python
-
-```python
-import re
-
-_var = re.compile(r"\{\{\s*([a-zA-Z_]\w*)\s*\}\}")
-
-def render_template(template: str, vars: dict) -> str:
- def repl(m):
- key = m.group(1)
- v = vars.get(key)
- return "" if v is None else str(v)
- return _var.sub(repl, template)
-```
-
-### Go(使用 text/template:先把 `{{var}}` 变成 `{{.var}}`)
-
-```go
-package prompt
-
-import (
- "bytes"
- "regexp"
- "text/template"
-)
-
-var mustacheVar = regexp.MustCompile(`\{\{\s*([a-zA-Z_]\w*)\s*\}\}`)
-
-func RenderTemplate(tpl string, vars map[string]any) (string, error) {
- goTpl := mustacheVar.ReplaceAllString(tpl, "{{.$1}}")
- t, err := template.New("prompt").Option("missingkey=zero").Parse(goTpl)
- if err != nil {
- return "", err
- }
- var buf bytes.Buffer
- if err := t.Execute(&buf, vars); err != nil {
- return "", err
- }
- return buf.String(), nil
-}
-```
-
-### Java
-
-```java
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public final class PromptTemplate {
- private static final Pattern VAR = Pattern.compile("\\\\{\\\\{\\\\s*([a-zA-Z_]\\\\w*)\\\\s*\\\\}\\\\}");
-
- public static String render(String template, Map<String, ?> vars) {
- Matcher m = VAR.matcher(template);
- StringBuffer sb = new StringBuffer();
- while (m.find()) {
- String key = m.group(1);
- Object v = vars.get(key);
- m.appendReplacement(sb, Matcher.quoteReplacement(v == null ? "" : String.valueOf(v)));
- }
- m.appendTail(sb);
- return sb.toString();
- }
-}
-```
-
-### C#
-
-```csharp
-using System.Collections.Generic;
-using System.Text.RegularExpressions;
-
-public static class PromptTemplate
-{
- private static readonly Regex Var = new(@"\{\{\s*([a-zA-Z_]\w*)\s*\}\}", RegexOptions.Compiled);
-
- public static string Render(string template, IReadOnlyDictionary<string, object?> vars)
- => Var.Replace(template, m =>
- {
- var key = m.Groups[1].Value;
- return vars.TryGetValue(key, out var v) && v is not null ? v.ToString()! : "";
- });
-}
-```
-
-## 重构规则(我会自动做)
-
-- R:把“身份/资历/语气/擅长领域”聚合为一个可执行角色
-- I:压缩成一个“动词 + 宾语”的核心任务句,去掉冗余口号
-- Input:只描述输入类型/格式/范围,并用 `{{var}}` 承载真实输入
-- S:拆成可执行的小步骤,每步只做一个动作,按“输入→处理→输出”排序
-- E:写清验收标准与用户价值,避免“做好就行”
-- N:写硬约束(量化、明确禁忌),避免“尽量/不要太…”
-- Output:写死输出结构与禁忌,让模型无需猜你要什么格式
-
-## 快速自检(防跑偏)
-
-- Role 是否具体到“领域 + 能力 + 语气”
-- Input 是否包含 类型/格式/范围 三要素
-- Steps 是否不跳步、每步一个动作
-- Narrowing 是否量化且可执行
-- Output 是否明确结构/格式符号/禁止项
diff --git a/agent/cad/svg/patch.md b/agent/cad/svg/patch.md
index 10a4107..66fd197 100644
--- a/agent/cad/svg/patch.md
+++ b/agent/cad/svg/patch.md
@@ -183,4 +183,4 @@ If (a) user asks for full dimensioning OR (b) the SVG already has three outer ch
"edits": [
{ "search": "EXACT SVG snippet", "replace": "replacement snippet" }
]
-}
\ No newline at end of file
+}
diff --git a/agent/cad/svg/replace.md b/agent/cad/svg/replace.md
index 0be8a43..c59d9a5 100644
--- a/agent/cad/svg/replace.md
+++ b/agent/cad/svg/replace.md
@@ -195,4 +195,4 @@ Constraints (CRITICAL):
"target": "2d_svg",
"mode": "replace",
"full": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 W H\">...</svg>"
-}
\ No newline at end of file
+}
diff --git a/deploy/README.md b/deploy/README.md
index 098776e..4f7da0c 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -1,6 +1,11 @@
# Deploy
-该项目为纯前端静态站点(Vite 构建产物为 `dist/`),可用任意静态资源服务器部署。
+该项目包含两部分:
+
+- Web:Vite 构建后的静态站点(`dist/`)
+- API:Node/Express 服务(`/api/*` 路由)
+
+仅部署静态站点会导致依赖 `/api/*` 的功能不可用(例如 Flow Next 的配置与聊天接口)。
## 目录结构
@@ -25,9 +30,18 @@
- `/var/www/unified-ai-workspace/dist`
-3. Nginx 配置
+3. 启动 API 服务(建议使用 `pm2`/`systemd` 守护)
+
+```bash
+npm ci
+npm run start:api
+```
+
+默认监听:`http://127.0.0.1:8787`
+
+4. Nginx 配置
-将 `deploy/host/nginx.conf` 作为站点配置启用(并按实际目录调整 `root`),重载 Nginx 后访问即可。
+将 `deploy/host/nginx.conf` 作为站点配置启用(并按实际目录调整 `root`),其中已包含 `/api` 反向代理到 `127.0.0.1:8787`。重载 Nginx 后访问即可。
## Docker 部署
@@ -39,7 +53,7 @@ docker compose -f deploy/docker/docker-compose.yml up -d --build
默认对外端口:`http://localhost:8080/`
-方式 B:直接构建镜像
+方式 B:仅启动 Web(不含 API,不推荐生产)
```bash
docker build -f deploy/docker/Dockerfile -t unified-ai-workspace:latest .
diff --git a/deploy/docker/Dockerfile.api b/deploy/docker/Dockerfile.api
new file mode 100644
index 0000000..56a73c8
--- /dev/null
+++ b/deploy/docker/Dockerfile.api
@@ -0,0 +1,12 @@
+FROM node:20-alpine
+
+WORKDIR /app
+COPY package.json package-lock.json ./
+RUN npm ci
+
+COPY . .
+
+ENV API_PORT=8787
+EXPOSE 8787
+
+CMD ["npm", "run", "start:api"]
diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.yml
index 74cbe63..9e72956 100644
--- a/deploy/docker/docker-compose.yml
+++ b/deploy/docker/docker-compose.yml
@@ -1,8 +1,21 @@
services:
+ api:
+ build:
+ context: ../..
+ dockerfile: deploy/docker/Dockerfile.api
+ environment:
+ API_PORT: 8787
+ API_BODY_LIMIT: 25mb
+ expose:
+ - "8787"
+ restart: unless-stopped
+
web:
build:
context: ../..
dockerfile: deploy/docker/Dockerfile
+ depends_on:
+ - api
ports:
- "8080:80"
-
+ restart: unless-stopped
diff --git a/deploy/docker/nginx.conf b/deploy/docker/nginx.conf
index 6caae47..1a0b386 100644
--- a/deploy/docker/nginx.conf
+++ b/deploy/docker/nginx.conf
@@ -9,10 +9,23 @@ server {
try_files $uri $uri/ /index.html;
}
+ location /api/ {
+ proxy_pass http://api:8787;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_read_timeout 300s;
+ }
+
+ location = /healthz {
+ proxy_pass http://api:8787/healthz;
+ }
+
location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|webp|ico|woff2?|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
try_files $uri =404;
}
}
-
diff --git a/deploy/host/nginx.conf b/deploy/host/nginx.conf
index 1e2768c..7597ebd 100644
--- a/deploy/host/nginx.conf
+++ b/deploy/host/nginx.conf
@@ -9,6 +9,20 @@ server {
try_files $uri $uri/ /index.html;
}
+ location /api/ {
+ proxy_pass http://127.0.0.1:8787;
+ proxy_http_version 1.1;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_read_timeout 300s;
+ }
+
+ location = /healthz {
+ proxy_pass http://127.0.0.1:8787/healthz;
+ }
+
location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|webp|ico|woff2?|ttf|eot)$ {
expires 30d;
add_header Cache-Control "public, max-age=2592000, immutable";
diff --git a/public/cad/2D.png b/public/cad/2D.png
new file mode 100644
index 0000000..aad03d9
Binary files /dev/null and b/public/cad/2D.png differ
diff --git a/public/cad/bom.png b/public/cad/bom.png
new file mode 100644
index 0000000..3c83962
Binary files /dev/null and b/public/cad/bom.png differ
diff --git a/public/cad/render.png b/public/cad/render.png
new file mode 100644
index 0000000..545e96b
Binary files /dev/null and b/public/cad/render.png differ
diff --git a/src/lib/cad-render-titles.ts b/src/lib/cad-render-titles.ts
new file mode 100644
index 0000000..bd0c056
--- /dev/null
+++ b/src/lib/cad-render-titles.ts
@@ -0,0 +1,21 @@
+import type { UiLanguage } from "@/lib/ui-language";
+
+export const CAD_RENDER_SLOT_TITLES = [
+ { zh: "装修平面布置图", en: "Renovation Plan Layout" },
+ { zh: "地面铺装图", en: "Floor Finish Plan" },
+ { zh: "顶面布置图", en: "Reflected Ceiling Plan" },
+ { zh: "墙体定位图", en: "Wall Setting-Out Plan" },
+ { zh: "机电点位图(强弱电+给排水)", en: "MEP Plan (Electrical + Low Voltage + Plumbing)" },
+ { zh: "立面索引图+室内立面图", en: "Elevation Index Plan + Interior Elevations" },
+ { zh: "节点大样图", en: "Detail Drawings" },
+] as const;
+
+export function getCadRenderSlotTitles(lang: UiLanguage): string[] {
+ return CAD_RENDER_SLOT_TITLES.map((item) => (lang === "zh" ? item.zh : item.en));
+}
+
+export function getCadRenderFallbackTitle(lang: UiLanguage, index: number): string {
+ const item = CAD_RENDER_SLOT_TITLES[index];
+ if (item) return lang === "zh" ? item.zh : item.en;
+ return lang === "zh" ? `图纸 ${index + 1}` : `Drawing ${index + 1}`;
+}
diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts
index c000ee9..44c8752 100644
--- a/src/lib/i18n.ts
+++ b/src/lib/i18n.ts
@@ -1,4 +1,4 @@
-import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";
+import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";
type Dict = Record<string, { zh: string; en: string }>;
@@ -48,8 +48,8 @@ const dict: Dict = {
"chat.collapseLocked": { zh: "PPT 生成完成前不能收起聊天", en: "Chat cannot be collapsed while PPT is generating" },
"chat.collapse": { zh: "收起聊天", en: "Collapse chat" },
- "nav.flow": { zh: "流程图", en: "Flow" },
- "nav.cad": { zh: "CAD设计", en: "CAD" },
+ "nav.flow": { zh: "流程绘制", en: "Flow" },
+ "nav.cad": { zh: "室内设计", en: "CAD" },
"nav.ppt": { zh: "PPT演示", en: "PPT" },
"flow.addToChat": { zh: "添加到对话", en: "Add to chat" },
diff --git a/src/pages/LandingPage.tsx b/src/pages/LandingPage.tsx
index 952c0b5..22eac30 100644
--- a/src/pages/LandingPage.tsx
+++ b/src/pages/LandingPage.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence, animate, useMotionValue, useTransform } from 'framer-motion';
-import { Layers, Zap, Layout, Box, Droplet, Brush, FileText } from 'lucide-react';
+import { Layers, Zap, Layout, Box, Droplet, Brush, FileText, Square, Hammer } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { getPdfDocumentFromUrl, renderPdfPageToCanvas } from '@/lib/pdf-utils';
import { getUiLanguage, setUiLanguage, type UiLanguage } from "@/lib/ui-language";
@@ -102,6 +102,19 @@ export function LandingPage({ onStart }: LandingPageProps) {
{/* Content */}
<div className="relative z-10 flex-1 flex flex-col">
+ <div className="absolute top-4 left-4 z-20">
+ <div className="flex items-center gap-2.5">
+ <div className="relative p-1.5 bg-blue-600/10 rounded-lg shadow-sm ring-1 ring-blue-600/20">
+ <Square className="w-5 h-5 text-blue-200" />
+ <div className="absolute -bottom-1 -right-1 rounded-full bg-black/60 p-0.5 ring-1 ring-blue-300/30">
+ <Hammer className="w-3 h-3 text-blue-100" />
+ </div>
+ </div>
+ <span className="text-xl md:text-2xl font-black tracking-[0.08em] text-transparent bg-clip-text bg-gradient-to-r from-cyan-200 via-white to-blue-300 drop-shadow-[0_0_10px_rgba(96,165,250,0.75)]">
+ CanvasAnvil
+ </span>
+ </div>
+ </div>
<div className="absolute top-4 right-4 z-20">
<Button
variant="secondary"
@@ -666,7 +679,7 @@ function DemoCAD({ uiLang }: { uiLang: UiLanguage }) {
const [isGenerating, setIsGenerating] = useState(false);
const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);
const promptSpeed = 30;
- const promptText = tr("设计一套新中式客厅装修方案,要简约大气", "Design a modern Chinese-style living room renovation, minimal and elegant");
+ const promptText = tr("设计一套新中式室内装修方案,要简约大气", "Design a modern Chinese-style interior renovation plan, minimal and grand");
const promptHoldMs = Math.max(2000, estimateTypewriterDurationMs(promptText, promptSpeed));
React.useEffect(() => {
@@ -684,16 +697,16 @@ function DemoCAD({ uiLang }: { uiLang: UiLanguage }) {
// 4s: Show 2D Plan (Duration 3s)
timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(1); }, promptHoldMs + 2000));
- // 7s: Start Generating BOM (Duration 2s)
+ // 7s: Start Generating Render (Duration 2s)
timeouts.push(setTimeout(() => setIsGenerating(true), promptHoldMs + 5000));
- // 9s: Show BOM (Duration 3s)
+ // 9s: Show Render (Duration 3s)
timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(2); }, promptHoldMs + 7000));
- // 12s: Start Generating Render (Duration 2s)
+ // 12s: Start Generating BOM (Duration 2s)
timeouts.push(setTimeout(() => setIsGenerating(true), promptHoldMs + 10000));
- // 14s: Show Final Render (Duration 3s)
+ // 14s: Show Final BOM (Duration 3s)
timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(3); }, promptHoldMs + 12000));
// 17s: Loop
@@ -707,8 +720,8 @@ function DemoCAD({ uiLang }: { uiLang: UiLanguage }) {
// Helper to get generating text
const getGenState = () => {
if (step === 0) return { title: tr("正在生成平面方案...", "Generating floor plan..."), sub: tr("AI 布局规划 · 动线分析 · 空间划分", "Layout planning · circulation · zoning") };
- if (step === 1) return { title: tr("正在生成物料清单...", "Generating BOM..."), sub: tr("空间拆解 · 材料归类 · 数量估算", "Decompose spaces · classify materials · estimate quantities") };
- if (step === 2) return { title: tr("正在渲染装修效果...", "Rendering design..."), sub: tr("风格匹配 · 材质建议 · 灯光氛围", "Style match · materials · lighting mood") };
+ if (step === 1) return { title: tr("正在渲染装修效果...", "Rendering design..."), sub: tr("风格匹配 · 材质建议 · 灯光氛围", "Style match · materials · lighting mood") };
+ if (step === 2) return { title: tr("正在生成物料清单...", "Generating BOM..."), sub: tr("空间拆解 · 材料归类 · 数量估算", "Decompose spaces · classify materials · estimate quantities") };
return { title: tr("处理中...", "Processing..."), sub: tr("请稍候", "Please wait") };
};
@@ -779,12 +792,90 @@ function DemoCAD({ uiLang }: { uiLang: UiLanguage }) {
}
function CadPlan({ step, uiLang }: { step: number; uiLang: UiLanguage }) {
- if (step === 1) return <CadPlan2D uiLang={uiLang} />;
- if (step === 2) return <CadBomResult uiLang={uiLang} />;
- if (step === 3) return <CadRenderResult uiLang={uiLang} />;
+ if (step === 1) return <CadStage2DImage uiLang={uiLang} />;
+ if (step === 2) return <CadStageRenderImage uiLang={uiLang} />;
+ if (step === 3) return <CadStageBomImage uiLang={uiLang} />;
return null;
}
+const CAD_DEMO_IMAGES = {
+ plan2d: "/cad/2D.png",
+ render: "/cad/render.png",
+ bom: "/cad/bom.png",
+};
+
+function CadStageImageCard({
+ uiLang,
+ src,
+ title,
+ subtitle,
+}: {
+ uiLang: UiLanguage;
+ src: string;
+ title: string;
+ subtitle: string;
+}) {
+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);
+ return (
+ <motion.div
+ initial={{ opacity: 0, scale: 0.985 }}
+ animate={{ opacity: 1, scale: 1 }}
+ transition={{ duration: 0.45, ease: "easeOut" }}
+ className="absolute inset-4 rounded-2xl border border-white/10 bg-white/95 overflow-hidden shadow-[0_20px_80px_rgba(0,0,0,0.45)]"
+ >
+ <div className="h-12 px-4 flex items-center justify-between border-b border-black/10 bg-white">
+ <div className="text-sm font-medium text-black/80">{title}</div>
+ <div className="text-xs text-black/45">{subtitle}</div>
+ </div>
+ <div className="h-[calc(100%-3rem)] bg-zinc-100">
+ <img
+ src={src}
+ alt={title}
+ className="w-full h-full object-contain bg-white"
+ loading="eager"
+ draggable={false}
+ />
+ </div>
+ <div className="absolute bottom-3 right-3 rounded-full border border-black/10 bg-white/85 px-2 py-1 text-[10px] text-black/50">
+ {tr("演示图", "Demo")}
+ </div>
+ </motion.div>
+ );
+}
+
+function CadStage2DImage({ uiLang }: { uiLang: UiLanguage }) {
+ return (
+ <CadStageImageCard
+ uiLang={uiLang}
+ src={CAD_DEMO_IMAGES.plan2d}
+ title={uiLang === "zh" ? "2D 平面图" : "2D Floor Plan"}
+ subtitle={uiLang === "zh" ? "需求输入后生成" : "Generated from requirement input"}
+ />
+ );
+}
+
+function CadStageRenderImage({ uiLang }: { uiLang: UiLanguage }) {
+ return (
+ <CadStageImageCard
+ uiLang={uiLang}
+ src={CAD_DEMO_IMAGES.render}
+ title={uiLang === "zh" ? "装修图" : "Render"}
+ subtitle={uiLang === "zh" ? "2D 结束后生成" : "Generated after 2D completion"}
+ />
+ );
+}
+
+function CadStageBomImage({ uiLang }: { uiLang: UiLanguage }) {
+ return (
+ <CadStageImageCard
+ uiLang={uiLang}
+ src={CAD_DEMO_IMAGES.bom}
+ title={uiLang === "zh" ? "物料清单" : "BOM"}
+ subtitle={uiLang === "zh" ? "最终输出" : "Final output"}
+ />
+ );
+}
+
function CadPlan2D({ uiLang }: { uiLang: UiLanguage }) {
const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);
return (
diff --git a/src/server/routes/chat.ts b/src/server/routes/chat.ts
index ca6c6d6..2b9b822 100644
--- a/src/server/routes/chat.ts
+++ b/src/server/routes/chat.ts
@@ -1066,7 +1066,7 @@ IMPORTANT: Keep edits concise:
- Each search must contain complete lines (never truncate mid-line)
- First match only - be specific enough to target the right element
-鈿狅笍 JSON ESCAPING: Every " inside string values MUST be escaped as \\". Example: x=\\"100\\" y=\\"200\\" - BOTH quotes need backslashes!`,
+IMPORTANT JSON ESCAPING: Every " inside string values MUST be escaped as \\". Example: x=\\"100\\" y=\\"200\\" - BOTH quotes need backslashes!`,
inputSchema: z.object({
edits: z
.array(
diff --git a/src/workspaces/cad/CadWorkspaceShell.tsx b/src/workspaces/cad/CadWorkspaceShell.tsx
index 240396f..dc3bce3 100644
--- a/src/workspaces/cad/CadWorkspaceShell.tsx
+++ b/src/workspaces/cad/CadWorkspaceShell.tsx
@@ -3,6 +3,7 @@ import { toast } from "sonner";
import { cn } from "@/lib/utils";
import { t } from "@/lib/i18n";
import { useUiLanguage } from "@/lib/use-ui-language";
+import { getCadRenderFallbackTitle } from "@/lib/cad-render-titles";
import {
ResizableHandle,
ResizablePanel,
@@ -27,15 +28,6 @@ type CodeActionResult = { ok: boolean; retry?: boolean; error?: string; svg?: st
const CAD_WORKSPACE_STORAGE_KEY = "unified-ai-workspace-cad-state-v1";
const CAD_RENDERS_STORAGE_KEY = "unified-ai-workspace-cad-renders-v1";
const CAD_CHAT_STORAGE_KEY = "chat_history_v2_cad";
-const CAD_RENDER_SLOT_TITLES = [
- "装修平面布置图",
- "地面铺装图",
- "顶面布置图",
- "墙体定位图",
- "机电点位图(强弱电+给排水)",
- "立面索引图+室内立面图",
- "节点大样图",
-];
const tryParseJson = (text: string) => {
try {
@@ -159,8 +151,77 @@ const extractLatestSvgFromText = (text: string) => {
return latest;
};
+type CadRenderItem = { title: string; url: string };
+
+const normalizeCadRenderItems = (
+ input: any,
+ options?: { allowBlob?: boolean; max?: number },
+): CadRenderItem[] => {
+ const allowBlob = options?.allowBlob === true;
+ const max = typeof options?.max === "number" && options.max > 0 ? options.max : 30;
+ if (!Array.isArray(input)) return [];
+ return input
+ .map((x: any) => ({
+ title: typeof x?.title === "string" ? x.title : "",
+ url: typeof x?.url === "string" ? x.url : "",
+ }))
+ .filter((x: CadRenderItem) => {
+ if (!x.url) return false;
+ if (!allowBlob && x.url.startsWith("blob:")) return false;
+ return true;
+ })
+ .slice(0, max);
+};
+
+const readPersistedCadRenders = (): CadRenderItem[] => {
+ if (typeof window === "undefined") return [];
+ try {
+ const raw = localStorage.getItem(CAD_RENDERS_STORAGE_KEY);
+ const parsed = raw ? JSON.parse(raw) : [];
+ return normalizeCadRenderItems(parsed, { allowBlob: false, max: 30 });
+ } catch {
+ return [];
+ }
+};
+
+const blobToDataUrl = async (blob: Blob) =>
+ await new Promise<string>((resolve) => {
+ const reader = new FileReader();
+ reader.onerror = () => resolve("");
+ reader.onloadend = () => resolve(typeof reader.result === "string" ? reader.result : "");
+ reader.readAsDataURL(blob);
+ });
+
+const urlToDataUrl = async (url: string) => {
+ if (typeof window === "undefined") return "";
+ try {
+ const resp = await fetch(url);
+ if (!resp.ok) return "";
+ const blob = await resp.blob();
+ return await blobToDataUrl(blob);
+ } catch {
+ return "";
+ }
+};
+
+const toPersistableRenderUrl = async (url: string) => {
+ const raw = String(url || "").trim();
+ if (!raw) return "";
+ if (raw.startsWith("data:image")) return raw;
+ if (raw.startsWith("blob:")) {
+ const dataUrl = await urlToDataUrl(raw);
+ return dataUrl || "";
+ }
+ if (raw.startsWith("http://") || raw.startsWith("https://")) {
+ const dataUrl = await urlToDataUrl(raw);
+ return dataUrl || raw;
+ }
+ return raw;
+};
+
export function CadWorkspaceShell() {
const uiLang = useUiLanguage();
+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);
const initialCadState = (() => {
if (typeof window === "undefined") return null;
try {
@@ -172,20 +233,21 @@ export function CadWorkspaceShell() {
return null;
}
})();
+ const initialCadRenders = (() => {
+ const fromWorkspaceState = normalizeCadRenderItems(initialCadState?.cadImages, {
+ allowBlob: false,
+ max: 30,
+ });
+ if (fromWorkspaceState.length > 0) return fromWorkspaceState;
+ return readPersistedCadRenders();
+ })();
const [cad2dSvg, setCad2dSvg] = useState<string | undefined>(() => {
const v = initialCadState?.cad2dSvg;
return typeof v === "string" ? v : undefined;
});
const [cadPlan, setCadPlan] = useState<any>(() => initialCadState?.cadPlan ?? null);
- const [cadImages, setCadImages] = useState<{ title: string; url: string }[]>(() => {
- const v = initialCadState?.cadImages;
- return Array.isArray(v)
- ? v
- .filter((x: any) => x && typeof x.title === "string" && typeof x.url === "string")
- .map((x: any) => ({ title: x.title, url: x.url }))
- : [];
- });
+ const [cadImages, setCadImages] = useState<{ title: string; url: string }[]>(() => initialCadRenders);
const [cadImagesLoading, setCadImagesLoading] = useState(false);
const [cadBom, setCadBom] = useState<{ columns: string[]; rows: any[] } | null>(() => {
const v = initialCadState?.cadBom;
@@ -224,7 +286,6 @@ export function CadWorkspaceShell() {
JSON.stringify({
cad2dSvg: typeof cad2dSvg === "string" ? cad2dSvg : null,
cadPlan: cadPlan ?? null,
- cadImages,
cadBom,
cadFocusPanel,
updatedAt: Date.now(),
@@ -232,7 +293,20 @@ export function CadWorkspaceShell() {
);
} catch {
}
- }, [cad2dSvg, cadPlan, cadImages, cadBom, cadFocusPanel]);
+ }, [cad2dSvg, cadPlan, cadBom, cadFocusPanel]);
+
+ useEffect(() => {
+ if (typeof window === "undefined") return;
+ try {
+ const stable = normalizeCadRenderItems(cadImages, { allowBlob: false, max: 30 });
+ if (stable.length > 0) {
+ localStorage.setItem(CAD_RENDERS_STORAGE_KEY, JSON.stringify(stable));
+ } else {
+ localStorage.removeItem(CAD_RENDERS_STORAGE_KEY);
+ }
+ } catch {
+ }
+ }, [cadImages]);
useEffect(() => {
const nextObjectUrls = cadImages
@@ -271,7 +345,6 @@ export function CadWorkspaceShell() {
cad2dSvgRef.current = svg;
setCad2dSvg(svg);
setCadFocusPanel("2d");
- addToHistory(svg, "svg");
return;
}
}, [chatHistory]);
@@ -292,8 +365,6 @@ export function CadWorkspaceShell() {
}
};
- const addToHistory = (_content: string, _type: "svg" | "json") => {};
-
const handleAddToChat = (payload: string) => {
const trimmed = String(payload || "").trim();
if (!trimmed) return;
@@ -325,16 +396,17 @@ export function CadWorkspaceShell() {
const raw = String(code || "");
const trimmed = raw.trim();
- if (!trimmed) return { ok: false, retry: false, error: "Empty input" };
+ if (!trimmed) return { ok: false, retry: false, error: tr("输入为空", "Empty input") };
const normalizedRawSvg = !trimmed.startsWith("{") ? normalizeSvgMarkup(raw) : "";
if (normalizedRawSvg) {
if (!isValidSvgMarkup(normalizedRawSvg)) {
- toast.warning("SVG may contain XML issues, trying to load anyway");
+ toast.warning(tr("SVG 可能包含 XML 问题,仍将尝试加载", "SVG may contain XML issues, trying to load anyway"));
}
if (!hasDrawableSvgContent(normalizedRawSvg)) {
- toast.error("SVG has no drawable content");
- return { ok: false, retry: false, error: "SVG has no drawable content" };
+ const msg = tr("SVG 不包含可绘制内容", "SVG has no drawable content");
+ toast.error(msg);
+ return { ok: false, retry: false, error: msg };
}
const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));
if (normalizedRawSvg === current) {
@@ -346,26 +418,27 @@ export function CadWorkspaceShell() {
cad2dSvgRef.current = normalizedRawSvg;
setCad2dSvg(normalizedRawSvg);
setCadFocusPanel("2d");
- addToHistory(normalizedRawSvg, "svg");
setCadApplyTick((x) => x + 1);
return { ok: true, svg: normalizedRawSvg };
}
- if (!trimmed.startsWith("{")) return { ok: false, retry: false, error: "No SVG found in input" };
+ if (!trimmed.startsWith("{")) return { ok: false, retry: false, error: tr("输入中未找到 SVG", "No SVG found in input") };
const parsed = tryParseJson(trimmed);
- if (!parsed) return { ok: false, retry: false, error: "Invalid JSON" };
+ if (!parsed) return { ok: false, retry: false, error: tr("JSON 无效", "Invalid JSON") };
const parsedType = String(parsed?.type || "").trim().toLowerCase();
const parsedTarget = String(parsed?.target || "").trim().toLowerCase();
const parsedMode = String(parsed?.mode || "").trim().toLowerCase();
if (parsedType === "cad_plan") {
setCadPlan(parsed);
- addToHistory(JSON.stringify(parsed), "json");
return { ok: true };
}
if (parsedType === "cad_bom") {
- const fallbackColumns = ["Category", "Name", "Spec", "Qty", "Unit", "Note"];
+ const fallbackColumns =
+ uiLang === "zh"
+ ? ["类别", "名称", "规格", "数量", "单位", "备注"]
+ : ["Category", "Name", "Spec", "Qty", "Unit", "Note"];
const columns =
Array.isArray(parsed.columns) && parsed.columns.length > 0
? parsed.columns.map((x: any) => String(x))
@@ -380,7 +453,7 @@ export function CadWorkspaceShell() {
const prompts = Array.isArray(parsed.prompts) ? parsed.prompts : [];
const items = prompts
.map((p: any) => ({
- title: typeof p?.title === "string" ? p.title : "View",
+ title: typeof p?.title === "string" ? p.title : tr("视图", "View"),
prompt: typeof p?.prompt === "string" ? p.prompt : "",
}))
.filter((p: any) => p.prompt)
@@ -390,7 +463,7 @@ export function CadWorkspaceShell() {
setCadImagesLoading(true);
setCadImages(
Array.from({ length: 7 }).map((_, idx) => ({
- title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,
+ title: getCadRenderFallbackTitle(uiLang, idx),
url: "",
})),
);
@@ -448,7 +521,7 @@ export function CadWorkspaceShell() {
const syncPartialImages = () => {
setCadImages(
Array.from({ length: 7 }).map((_, idx) => ({
- title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,
+ title: getCadRenderFallbackTitle(uiLang, idx),
url: results[idx]?.url || "",
})),
);
@@ -482,21 +555,30 @@ export function CadWorkspaceShell() {
}
const final = Array.from({ length: 7 }).map((_, idx) => ({
- title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,
+ title: getCadRenderFallbackTitle(uiLang, idx),
url: results[idx]?.url || "",
}));
- setCadImages(final);
+ const persistableFinal = await Promise.all(
+ final.map(async (item) => ({
+ title: item.title,
+ url: await toPersistableRenderUrl(item.url),
+ })),
+ );
+ setCadImages(persistableFinal);
const failedCount = list.filter((_, idx) => !results[idx]?.url).length;
if (failedCount > 0) {
- toast.warning(`${failedCount} render image(s) failed after retries. Please run generation again.`);
+ toast.warning(
+ uiLang === "zh"
+ ? `有 ${failedCount} 张装修图在重试后仍失败,请重新生成。`
+ : `${failedCount} render image(s) failed after retries. Please run generation again.`,
+ );
}
- 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");
+ toast.error(tr("装修图生成失败", "CAD image generation failed"));
setCadImages(
Array.from({ length: 7 }).map((_, idx) => ({
- title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,
+ title: getCadRenderFallbackTitle(uiLang, idx),
url: "",
})),
);
@@ -511,15 +593,17 @@ export function CadWorkspaceShell() {
if (parsedMode === "replace" && typeof parsed.full === "string") {
const normalizedFull = normalizeSvgMarkup(parsed.full);
if (!normalizedFull) {
- toast.error("Invalid replace svg");
- return { ok: false, retry: false, error: "Invalid replace svg" };
+ const msg = tr("replace 模式 SVG 无效", "Invalid replace svg");
+ toast.error(msg);
+ return { ok: false, retry: false, error: msg };
}
if (!isValidSvgMarkup(normalizedFull)) {
- toast.warning("Replace svg may contain XML issues, trying to load anyway");
+ toast.warning(tr("replace SVG 可能包含 XML 问题,仍将尝试加载", "Replace svg may contain XML issues, trying to load anyway"));
}
if (!hasDrawableSvgContent(normalizedFull)) {
- toast.error("Replace svg has no drawable content");
- return { ok: false, retry: false, error: "Replace svg has no drawable content" };
+ const msg = tr("replace SVG 不包含可绘制内容", "Replace svg has no drawable content");
+ toast.error(msg);
+ return { ok: false, retry: false, error: msg };
}
const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));
if (normalizedFull === current) {
@@ -530,7 +614,6 @@ export function CadWorkspaceShell() {
cad2dSvgRef.current = normalizedFull;
setCad2dSvg(normalizedFull);
setCadFocusPanel("2d");
- addToHistory(normalizedFull, "svg");
setCadApplyTick((x) => x + 1);
return { ok: true, svg: normalizedFull };
}
@@ -538,40 +621,46 @@ export function CadWorkspaceShell() {
try {
const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));
if (!current) {
- toast.error("Current 2D SVG is empty, cannot apply patch");
- return { ok: false, retry: true, error: "Current 2D SVG is empty, cannot apply patch" };
+ const msg = tr("当前 2D SVG 为空,无法应用补丁", "Current 2D SVG is empty, cannot apply patch");
+ toast.error(msg);
+ return { ok: false, retry: true, error: msg };
}
const next = applyStringEdits(current, parsed.edits);
const normalizedNext = normalizeSvgMarkup(next);
if (!normalizedNext) {
- toast.error("Patch result is not valid svg");
- return { ok: false, retry: true, error: "Patch result is not valid svg" };
+ const msg = tr("补丁结果不是有效 SVG", "Patch result is not valid svg");
+ toast.error(msg);
+ return { ok: false, retry: true, error: msg };
}
if (!isValidSvgMarkup(normalizedNext)) {
- toast.warning("Patch result may contain XML issues, trying to load anyway");
+ toast.warning(tr("补丁结果可能包含 XML 问题,仍将尝试加载", "Patch result may contain XML issues, trying to load anyway"));
}
if (!hasDrawableSvgContent(normalizedNext)) {
- toast.error("Patch result has no drawable content");
- return { ok: false, retry: true, error: "Patch result has no drawable content" };
+ const msg = tr("补丁结果不包含可绘制内容", "Patch result has no drawable content");
+ toast.error(msg);
+ return { ok: false, retry: true, error: msg };
}
if (normalizedNext === current) {
- toast.warning("Patch produced no visible SVG change");
- return { ok: false, retry: true, error: "Patch produced no visible SVG change" };
+ const msg = tr("补丁未产生可见 SVG 变化", "Patch produced no visible SVG change");
+ toast.warning(msg);
+ return { ok: false, retry: true, error: msg };
}
cad2dSvgRef.current = normalizedNext;
setCad2dSvg(normalizedNext);
setCadFocusPanel("2d");
- addToHistory(normalizedNext, "svg");
setCadApplyTick((x) => x + 1);
return { ok: true, svg: normalizedNext };
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
- toast.error(`Patch apply failed: ${msg}`);
+ const err = uiLang === "zh" ? `补丁应用失败:${msg}` : `Patch apply failed: ${msg}`;
+ toast.error(err);
return { ok: false, retry: true, error: msg };
}
}
- toast.error(`Unsupported cad_patch mode: ${String(parsedMode || "") || "unknown"}`);
- return { ok: false, retry: false, error: `Unsupported cad_patch mode: ${String(parsedMode || "") || "unknown"}` };
+ const mode = String(parsedMode || "") || "unknown";
+ const err = uiLang === "zh" ? `不支持的 cad_patch 模式:${mode}` : `Unsupported cad_patch mode: ${mode}`;
+ toast.error(err);
+ return { ok: false, retry: false, error: err };
}
return { ok: true };
@@ -621,7 +710,6 @@ export function CadWorkspaceShell() {
onSvgChange={(nextSvg) => {
cad2dSvgRef.current = nextSvg;
setCad2dSvg(nextSvg);
- addToHistory(nextSvg, "svg");
}}
plan={cadPlan}
images={cadImages}
diff --git a/src/workspaces/cad/chat/ChatInput.tsx b/src/workspaces/cad/chat/ChatInput.tsx
index d81eabf..cc12f64 100644
--- a/src/workspaces/cad/chat/ChatInput.tsx
+++ b/src/workspaces/cad/chat/ChatInput.tsx
@@ -57,6 +57,7 @@ export function ChatInput({
uploadMode = "all"
}: ChatInputProps) {
const uiLang = useUiLanguage();
+ const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const richRef = useRef<HTMLDivElement>(null);
const richSavedRangeRef = useRef<Range | null>(null);
@@ -414,7 +415,7 @@ export function ChatInput({
<div className="relative">
{showRichPlaceholder && (
<div className="pointer-events-none absolute left-1 top-2 text-[15px] leading-6 text-muted-foreground/60">
- {placeholder || "Type your message..."}
+ {placeholder || trText("请输入消息...", "Type your message...")}
</div>
)}
<div
@@ -522,7 +523,7 @@ export function ChatInput({
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
- placeholder={placeholder || "Type your message..."}
+ placeholder={placeholder || trText("请输入消息...", "Type your message...")}
className={cn(
"w-full resize-none bg-transparent border-none px-1 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[48px]"
)}
diff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
index 3ca3e74..a894a81 100644
--- a/src/workspaces/cad/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
@@ -424,7 +424,8 @@ function slideFieldLabel(key: string, uiLang: "zh" | "en"): string {
return key;
}
-function CadPatchEditsDisplay({ edits }: { edits: CadPatchEdit[] }) {
+function CadPatchEditsDisplay({ edits, uiLang }: { edits: CadPatchEdit[]; uiLang: "zh" | "en" }) {
+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);
return (
<div className="space-y-3">
{edits.map((edit, index) => (
@@ -433,13 +434,17 @@ function CadPatchEditsDisplay({ edits }: { edits: CadPatchEdit[] }) {
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>
+ <span className="text-xs font-medium text-muted-foreground">
+ {tr(`修改 ${index + 1}`, `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>
+ <span className="text-[10px] font-medium text-red-600 uppercase tracking-wide">
+ {tr("删除", "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}
@@ -448,7 +453,9 @@ function CadPatchEditsDisplay({ edits }: { edits: CadPatchEdit[] }) {
<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>
+ <span className="text-[10px] font-medium text-green-600 uppercase tracking-wide">
+ {tr("新增", "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}
@@ -1119,7 +1126,7 @@ export function ChatMessageDisplay({
<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")}
+ {tr("编辑图纸", "Edit Diagram")}
</span>
</div>
<div className="flex items-center gap-2">
@@ -1127,7 +1134,7 @@ export function ChatMessageDisplay({
<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")}
+ {tr("完成", "Complete")}
</span>
)}
{onApplyCode && (
@@ -1142,7 +1149,7 @@ export function ChatMessageDisplay({
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>
+ <span>{tr("应用", "Apply")}</span>
</button>
)}
<button
@@ -1165,7 +1172,7 @@ export function ChatMessageDisplay({
</div>
{expanded && (
<div className="px-4 py-3 border-t border-border/40 bg-muted/20">
- <CadPatchEditsDisplay edits={cadPatchPayload.edits} />
+ <CadPatchEditsDisplay edits={cadPatchPayload.edits} uiLang={uiLang} />
</div>
)}
</div>
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsx
index 3633fc4..6823fa5 100644
--- a/src/workspaces/cad/chat/ChatPanel.tsx
+++ b/src/workspaces/cad/chat/ChatPanel.tsx
@@ -17,6 +17,7 @@ import {
CAD_SVG_FLOW_PATCH_AGENT_PROMPT,
CAD_SVG_FLOW_REPLACE_AGENT_PROMPT,
} from '@/lib/cad-agents';
+import { getCadRenderFallbackTitle, getCadRenderSlotTitles } from "@/lib/cad-render-titles";
import flowPatchAgentPrompt from "../../../../agent/flow/patch.md?raw";
import flowReplaceAgentPrompt from "../../../../agent/flow/replace.md?raw";
import { t } from "@/lib/i18n";
@@ -207,7 +208,7 @@ export function ChatPanel({
collapsed = false,
onToggleCollapse,
collapseLocked = false,
- title = "AI 助手",
+ title,
inputPlaceholder,
history = [],
onRestore,
@@ -219,11 +220,14 @@ export function ChatPanel({
}: ChatPanelProps) {
const uiLang = useUiLanguage();
const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);
+ const panelTitle = title || trText("AI 助手", "AI Assistant");
const cadOutputLanguage = uiLang === "zh" ? "Simplified Chinese (zh-CN)" : "English (en)";
const cadOutputLanguageInstruction =
workspaceId === "cad"
? `Output language: ${cadOutputLanguage}`
: "";
+ const cadRenderFallbackTitles = getCadRenderSlotTitles(uiLang);
+ const cadRenderPromptTitlesEn = getCadRenderSlotTitles("en");
// Persistence key
const storageKey = `${STORAGE_KEY_PREFIX}${workspaceId}`;
@@ -272,7 +276,7 @@ export function ChatPanel({
const m = String(slideId || "").match(/(\\d+)/);
const n = m ? Number(m[1]) : NaN;
if (!Number.isNaN(n)) {
- return title ? `Slide ${n}: ${title}` : `Slide ${n}`;
+ return title ? trText(`第 ${n} 页:${title}`, `Slide ${n}: ${title}`) : trText(`第 ${n} 页`, `Slide ${n}`);
}
return title || slideId;
};
@@ -1162,24 +1166,8 @@ export function ChatPanel({
}
};
- const fallbackTitlesForOutput = [
- trText("装修平面布置图", "装修平面布置图"),
- trText("地面铺装图", "地面铺装图"),
- trText("顶面布置图", "顶面布置图"),
- trText("墙体定位图", "墙体定位图"),
- trText("机电点位图(强弱电+给排水)", "机电点位图(强弱电+给排水)"),
- trText("立面索引图+室内立面图", "立面索引图+室内立面图"),
- trText("节点大样图", "节点大样图"),
- ];
- const fallbackTitlesForPromptEnglish = [
- "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 fallbackTitlesForOutput = cadRenderFallbackTitles;
+ const fallbackTitlesForPromptEnglish = cadRenderPromptTitlesEn;
let masterSchemeJson = "";
try {
@@ -1200,7 +1188,7 @@ export function ChatPanel({
);
const prompts = settled.map((r, idx) => {
- const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("图纸", "图纸");
+ const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || getCadRenderFallbackTitle(uiLang, idx);
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}`;
@@ -1234,7 +1222,7 @@ export function ChatPanel({
setMessages(prev => {
const last = prev[prev.length - 1];
if (last?.role !== 'assistant') return prev;
- const abortedText = trText("(Aborted)", "(Aborted)");
+ const abortedText = trText("(已中止)", "(Aborted)");
const next = last.content ? `${last.content}\n\n${abortedText}` : abortedText;
return [...prev.slice(0, -1), { role: 'assistant', content: next }];
});
@@ -1485,7 +1473,7 @@ export function ChatPanel({
.join("\n\n");
const masterMessages: ChatMessage[] = buildCadImagesMasterMessages({ systemContent: systemContentTasks, planJson, svg2d, outputLanguage: cadOutputLanguage });
- updateLastAssistant(trText("Generating drawing prompts...", "Generating drawing prompts..."));
+ updateLastAssistant(trText("正在生成图纸提示词...", "Generating drawing prompts..."));
const extractJsonText = (text: string) => {
const match = String(text || "").match(/```json\s*([\s\S]*?)```/);
@@ -1509,24 +1497,8 @@ export function ChatPanel({
}
};
- const fallbackTitlesForOutput = [
- trText("装修平面布置图", "装修平面布置图"),
- trText("地面铺装图", "地面铺装图"),
- trText("顶面布置图", "顶面布置图"),
- trText("墙体定位图", "墙体定位图"),
- trText("机电点位图(强弱电+给排水)", "机电点位图(强弱电+给排水)"),
- trText("立面索引图+室内立面图", "立面索引图+室内立面图"),
- trText("节点大样图", "节点大样图"),
- ];
- const fallbackTitlesForPromptEnglish = [
- "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 fallbackTitlesForOutput = cadRenderFallbackTitles;
+ const fallbackTitlesForPromptEnglish = cadRenderPromptTitlesEn;
let masterSchemeJson = "";
try {
@@ -1553,7 +1525,7 @@ export function ChatPanel({
);
const prompts = settled.map((r, idx) => {
- const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("图纸", "图纸");
+ const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || getCadRenderFallbackTitle(uiLang, idx);
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}`;
@@ -1589,7 +1561,7 @@ export function ChatPanel({
producedHasImages: true,
producedHasBom: false,
});
- updateLastAssistant(guide || trText("Drawing tasks generated.", "Drawing tasks generated."));
+ updateLastAssistant(guide || trText("图纸任务已生成。", "Drawing tasks generated."));
return;
}
@@ -1937,20 +1909,17 @@ export function ChatPanel({
setMessages(prev => {
const last = prev[prev.length - 1];
if (last?.role === 'assistant') {
- const abortedText = trText("(Aborted)", "(Aborted)");
+ const abortedText = trText("(已中止)", "(Aborted)");
const next = last.content ? `${last.content}\n\n${abortedText}` : abortedText;
return [...prev.slice(0, -1), { role: 'assistant', content: next }];
}
- return [...prev, { role: 'assistant', content: trText("(Aborted)", "(Aborted)") }];
+ return [...prev, { role: 'assistant', content: trText("(已中止)", "(Aborted)") }];
});
return;
}
setMessages(prev => {
const last = prev[prev.length - 1];
- const errorText = trText(
- "Sorry, an error occurred. Please check API key settings.",
- "Sorry, an error occurred. Please check API key settings."
- );
+ const errorText = trText("抱歉,发生错误。请检查 API Key 设置。", "Sorry, an error occurred. Please check API key settings.");
if (last.role === 'assistant' && !last.content) {
return [...prev.slice(0, -1), { role: 'assistant', content: errorText }];
}
@@ -2225,7 +2194,7 @@ export function ChatPanel({
.join("\n\n");
const masterMessages: ChatMessage[] = buildCadImagesMasterMessages({ systemContent: systemContentTasks, planJson, svg2d, outputLanguage: cadOutputLanguage });
- updateLastAssistant(trText("Generating drawing prompts...", "Generating drawing prompts..."));
+ updateLastAssistant(trText("正在生成图纸提示词...", "Generating drawing prompts..."));
const extractJsonText = (text: string) => {
const match = String(text || "").match(/```json\s*([\s\S]*?)```/);
@@ -2249,24 +2218,8 @@ export function ChatPanel({
}
};
- const fallbackTitlesForOutput = [
- trText("装修平面布置图", "装修平面布置图"),
- trText("地面铺装图", "地面铺装图"),
- trText("顶面布置图", "顶面布置图"),
- trText("墙体定位图", "墙体定位图"),
- trText("机电点位图(强弱电+给排水)", "机电点位图(强弱电+给排水)"),
- trText("立面索引图+室内立面图", "立面索引图+室内立面图"),
- trText("节点大样图", "节点大样图"),
- ];
- const fallbackTitlesForPromptEnglish = [
- "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 fallbackTitlesForOutput = cadRenderFallbackTitles;
+ const fallbackTitlesForPromptEnglish = cadRenderPromptTitlesEn;
let masterSchemeJson = "";
try {
@@ -2293,7 +2246,7 @@ export function ChatPanel({
);
const prompts = settled.map((r, idx) => {
- const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || trText("图纸", "图纸");
+ const fallbackTitleForOutput = fallbackTitlesForOutput[idx] || getCadRenderFallbackTitle(uiLang, idx);
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}`;
@@ -2329,7 +2282,7 @@ export function ChatPanel({
producedHasImages: true,
producedHasBom: false,
});
- updateLastAssistant(guide || trText("Drawing tasks generated.", "Drawing tasks generated."));
+ updateLastAssistant(guide || trText("图纸任务已生成。", "Drawing tasks generated."));
return;
}
@@ -2766,7 +2719,7 @@ export function ChatPanel({
<div className="px-5 py-4 border-b border-border/50">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
- <span className="text-base font-semibold tracking-tight whitespace-nowrap">{title}</span>
+ <span className="text-base font-semibold tracking-tight whitespace-nowrap">{panelTitle}</span>
</div>
<div className="flex items-center gap-1">
{onToggleCollapse && (
@@ -2811,7 +2764,7 @@ export function ChatPanel({
historyDisabled={history.length === 0}
onFilesChange={setFiles}
files={files}
- uploadMode={workspaceId === "ppt" ? "imagesOnly" : workspaceId === "cad" ? "filesOnly" : "all"}
+ uploadMode={workspaceId === "ppt" ? "imagesOnly" : workspaceId === "cad" ? "filesOnly" : "all"}
placeholder={inputPlaceholder}
focusKey={workspaceId === "ppt" ? pptInputFocusTick : undefined}
clearKey={workspaceId === "ppt" ? pptClearTick : undefined}
@@ -2842,10 +2795,10 @@ export function ChatPanel({
type="button"
onClick={() => onRemoveAttachment(a.id)}
className="text-muted-foreground/80 hover:text-foreground transition-colors"
- title="Remove attachment"
- aria-label="Remove attachment"
+ title={trText("移除附件", "Remove attachment")}
+ aria-label={trText("移除附件", "Remove attachment")}
>
- 脳
+ ×
</button>
)}
</div>
diff --git a/src/workspaces/cad/chat/components/reasoning.tsx b/src/workspaces/cad/chat/components/reasoning.tsx
index 2178400..56f8a69 100644
--- a/src/workspaces/cad/chat/components/reasoning.tsx
+++ b/src/workspaces/cad/chat/components/reasoning.tsx
@@ -7,6 +7,7 @@ import {
CollapsibleContent,
CollapsibleTrigger,
} from "@/workspaces/cad/ui/collapsible"
+import { useUiLanguage } from "@/lib/use-ui-language"
import { cn } from "@/lib/utils"
import { Shimmer } from "./shimmer"
@@ -111,24 +112,26 @@ export type ReasoningTriggerProps = ComponentProps<
getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode
}
-const defaultGetThinkingMessage = (isStreaming: boolean, duration?: number) => {
- if (isStreaming || duration === 0) {
- return <Shimmer duration={1}>Thinking...</Shimmer>
- }
- if (duration === undefined) {
- return <p>Thought for a few seconds</p>
- }
- return <p>Thought for {duration} seconds</p>
-}
-
export const ReasoningTrigger = memo(
({
className,
children,
- getThinkingMessage = defaultGetThinkingMessage,
+ getThinkingMessage,
...props
}: ReasoningTriggerProps) => {
const { isStreaming, isOpen, duration } = useReasoning()
+ const uiLang = useUiLanguage()
+ const tr = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText)
+ const fallbackGetThinkingMessage = (thinking: boolean, durationSec?: number) => {
+ if (thinking || durationSec === 0) {
+ return <Shimmer duration={1}>{tr("思考中...", "Thinking...")}</Shimmer>
+ }
+ if (durationSec === undefined) {
+ return <p>{tr("已思考数秒", "Thought for a few seconds")}</p>
+ }
+ return <p>{tr(`已思考 ${durationSec} 秒`, `Thought for ${durationSec} seconds`)}</p>
+ }
+ const thinkingMessage = (getThinkingMessage || fallbackGetThinkingMessage)(isStreaming, duration)
return (
<CollapsibleTrigger
@@ -141,7 +144,7 @@ export const ReasoningTrigger = memo(
{children ?? (
<>
<BrainIcon className="size-4" />
- {getThinkingMessage(isStreaming, duration)}
+ {thinkingMessage}
<ChevronDownIcon
className={cn(
"size-4 transition-transform",
diff --git a/src/workspaces/cad/chat/file-preview-list.tsx b/src/workspaces/cad/chat/file-preview-list.tsx
index 01d625e..6775512 100644
--- a/src/workspaces/cad/chat/file-preview-list.tsx
+++ b/src/workspaces/cad/chat/file-preview-list.tsx
@@ -4,6 +4,7 @@ import { FileCode, FileText, Loader2, X } from "lucide-react"
import { useEffect, useRef, useState } from "react"
import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
import { type FileData } from "@/lib/use-file-processor"
+import { useUiLanguage } from "@/lib/use-ui-language"
function formatCharCount(count: number): string {
if (count >= 1000) {
@@ -23,6 +24,8 @@ export function FilePreviewList({
onRemoveFile,
pdfData = new Map(),
}: FilePreviewListProps) {
+ const uiLang = useUiLanguage()
+ const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText)
const [selectedImage, setSelectedImage] = useState<string | null>(null)
const [imageUrls, setImageUrls] = useState<Map<File, string>>(new Map())
const imageUrlsRef = useRef<Map<File, string>>(new Map())
@@ -88,13 +91,13 @@ export function FilePreviewList({
const isPdf = isPdfFile(file)
const isText = isTextFile(file)
const secondary = pdfInfo?.isExtracting
- ? "Reading..."
+ ? trText("解析中...", "Reading...")
: pdfInfo?.charCount
- ? `${formatCharCount(pdfInfo.charCount)} chars`
+ ? trText(`${formatCharCount(pdfInfo.charCount)} 字符`, `${formatCharCount(pdfInfo.charCount)} chars`)
: isPdf
- ? "PDF"
+ ? trText("PDF 文档", "PDF")
: isText
- ? "Text"
+ ? trText("文本", "Text")
: ""
return (
<div key={file.name + index} className="group">
@@ -141,7 +144,7 @@ export function FilePreviewList({
type="button"
onClick={() => onRemoveFile(file)}
className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
- aria-label="Remove file"
+ aria-label={trText("移除文件", "Remove file")}
>
<X className="h-4 w-4" />
</button>
@@ -160,14 +163,14 @@ export function FilePreviewList({
<button
className="absolute top-4 right-4 z-10 bg-white rounded-full p-2 hover:bg-gray-200 transition-colors"
onClick={() => setSelectedImage(null)}
- aria-label="Close"
+ aria-label={trText("关闭", "Close")}
>
<X className="h-6 w-6" />
</button>
<div className="relative w-auto h-auto max-w-[90vw] max-h-[90vh]">
<img
src={selectedImage}
- alt="Full size preview of uploaded diagram or image"
+ alt={trText("上传图片的全尺寸预览", "Full size preview of uploaded diagram or image")}
className="object-contain max-w-full max-h-[90vh] w-auto h-auto"
onClick={(e) => e.stopPropagation()}
/>
diff --git a/src/workspaces/cad/ui/code-block.tsx b/src/workspaces/cad/ui/code-block.tsx
index a1b2275..fd508d3 100644
--- a/src/workspaces/cad/ui/code-block.tsx
+++ b/src/workspaces/cad/ui/code-block.tsx
@@ -1,6 +1,7 @@
import React, { useMemo, useState } from "react";
import { Check, ChevronDown, ChevronUp, Copy, Cpu, Play, X } from "lucide-react";
import { Highlight, themes, type Language } from "prism-react-renderer";
+import { useUiLanguage } from "@/lib/use-ui-language";
interface CodeBlockProps {
code: string;
@@ -46,6 +47,8 @@ export function CodeBlock({
blockId: _blockId,
onApply,
}: CodeBlockProps) {
+ const uiLang = useUiLanguage();
+ const tr = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);
const [isExpanded, setIsExpanded] = useState(() => {
if (_blockId && openStateById.has(_blockId)) return Boolean(openStateById.get(_blockId));
return true;
@@ -147,14 +150,14 @@ export function CodeBlock({
<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">Generate CAD</span>
+ <span className="text-sm font-medium text-foreground/80">{tr("生成 CAD", "Generate CAD")}</span>
</div>
<div className="flex items-center gap-2">
{_isStreaming ? (
<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">
- Complete
+ {tr("完成", "Complete")}
</span>
)}
<div className="flex items-center gap-1">
@@ -164,7 +167,7 @@ export function CodeBlock({
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"}
+ title={applied ? tr("已应用", "Applied") : applyFailed ? tr("应用失败", "Apply failed") : tr("应用到画布", "Apply to canvas")}
>
{applying ? (
<div className="h-3 w-3 border-2 border-primary border-t-transparent rounded-full animate-spin" />
@@ -175,7 +178,7 @@ export function CodeBlock({
) : (
<Play className="h-3 w-3" />
)}
- <span>{applying ? "Applying" : applied ? "Applied" : "Apply"}</span>
+ <span>{applying ? tr("应用中", "Applying") : applied ? tr("已应用", "Applied") : tr("应用", "Apply")}</span>
</button>
)}
<button
@@ -202,10 +205,10 @@ export function CodeBlock({
className="inline-flex items-center gap-1 rounded-md px-2 py-1 text-[10px] text-muted-foreground hover:bg-muted transition-colors"
title={
copied
- ? "Copied"
+ ? tr("已复制", "Copied")
: copyFailed
- ? "Copy failed"
- : "Copy code"
+ ? tr("复制失败", "Copy failed")
+ : tr("复制代码", "Copy code")
}
>
{copied ? (
@@ -215,7 +218,7 @@ export function CodeBlock({
) : (
<Copy className="h-3 w-3" />
)}
- <span>{copied ? "Copied" : "Copy"}</span>
+ <span>{copied ? tr("已复制", "Copied") : tr("复制", "Copy")}</span>
</button>
</div>
<Highlight theme={themes.github} code={displayCode} language={prismLanguage}>
diff --git a/src/workspaces/cad/ui/dialog.tsx b/src/workspaces/cad/ui/dialog.tsx
index 1388a06..d8d3b56 100644
--- a/src/workspaces/cad/ui/dialog.tsx
+++ b/src/workspaces/cad/ui/dialog.tsx
@@ -5,6 +5,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import { cn } from "@/lib/utils"
+import { useUiLanguage } from "@/lib/use-ui-language"
function Dialog({
...props
@@ -52,6 +53,7 @@ const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => {
+ const uiLang = useUiLanguage()
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
@@ -67,7 +69,7 @@ const DialogContent = React.forwardRef<
{children}
<DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<XIcon />
- <span className="sr-only">Close</span>
+ <span className="sr-only">{uiLang === "zh" ? "关闭" : "Close"}</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
diff --git a/src/workspaces/cad/workspace/CadWorkspace.tsx b/src/workspaces/cad/workspace/CadWorkspace.tsx
index 4616c65..5c2bd66 100644
--- a/src/workspaces/cad/workspace/CadWorkspace.tsx
+++ b/src/workspaces/cad/workspace/CadWorkspace.tsx
@@ -11,6 +11,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/workspaces/c
import { PDFDocument } from "pdf-lib";
import { useUiLanguage } from "@/lib/use-ui-language";
import { toast } from "sonner";
+import { getCadRenderSlotTitles } from "@/lib/cad-render-titles";
interface CadWorkspaceProps {
onAddToChat?: (code: string) => void;
@@ -23,16 +24,6 @@ interface CadWorkspaceProps {
focusPanel?: "2d" | "renders" | "bom" | null;
}
-const RENDER_SLOT_TITLES = [
- "装修平面布置图",
- "地面铺装图",
- "顶面布置图",
- "墙体定位图",
- "机电点位图(强弱电+给排水)",
- "立面索引图+室内立面图",
- "节点大样图",
-];
-
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;
@@ -365,7 +356,11 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
const stable = localImages
.filter((x) => x && typeof x.url === "string" && x.url && !x.url.startsWith("blob:"))
.slice(0, 30);
- localStorage.setItem(CAD_RENDERS_STORAGE_KEY, JSON.stringify(stable));
+ if (stable.length > 0) {
+ localStorage.setItem(CAD_RENDERS_STORAGE_KEY, JSON.stringify(stable));
+ } else {
+ localStorage.removeItem(CAD_RENDERS_STORAGE_KEY);
+ }
} catch {
}
}, [localImages]);
@@ -612,14 +607,15 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
};
const renderSlots = useMemo(() => {
- return RENDER_SLOT_TITLES.map((fallbackTitle, idx) => {
+ const titles = getCadRenderSlotTitles(uiLang);
+ return titles.map((fallbackTitle, idx) => {
const item = localImages[idx];
return {
title: fallbackTitle,
url: item?.url || "",
};
});
- }, [localImages]);
+ }, [localImages, uiLang]);
const hasRenderImages = localImages.some((x) => !!x?.url);
@@ -702,7 +698,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
<div className="w-full h-full bg-white shadow-sm rounded-xl overflow-hidden border border-border/50">
<iframe
ref={svgEditorIframeRef}
- title="CAD SVG Editor"
+ title={uiLang === "zh" ? "CAD SVG 编辑器" : "CAD SVG Editor"}
src={SVG_EDITOR_IFRAME_PATH}
className="h-full w-full border-0"
onLoad={handleSvgEditorIframeLoad}
@@ -729,7 +725,11 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
>
<ImageIcon className="w-4 h-4" />
</Button>
- <a href={img.url || "#"} download={`${img.title || "render"}.png`} className="inline-flex">
+ <a
+ href={img.url || "#"}
+ download={`${img.title || (uiLang === "zh" ? "装修图" : "render")}.png`}
+ className="inline-flex"
+ >
<Button variant="ghost" size="icon" className="h-7 w-7" disabled={!img.url} title={uiLang === "zh" ? "下载" : "Download"}>
<Download className="w-4 h-4" />
</Button>
@@ -815,7 +815,11 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [
{previewImage?.url ? (
<div className="space-y-3">
<div className="flex items-center justify-end">
- <a href={previewImage.url} download={`${previewImage.title || "render"}.png`} className="inline-flex">
+ <a
+ href={previewImage.url}
+ download={`${previewImage.title || (uiLang === "zh" ? "装修图" : "render")}.png`}
+ className="inline-flex"
+ >
<Button variant="outline" size="sm" className="h-8 px-3 text-xs" title={uiLang === "zh" ? "下载图片" : "Download image"}>
<Download className="w-4 h-4 mr-1" />
{uiLang === "zh" ? "下载图片" : "Download image"}
diff --git a/src/workspaces/flow/next/lib/system-prompts.ts b/src/workspaces/flow/next/lib/system-prompts.ts
index 6986077..3e614b2 100644
--- a/src/workspaces/flow/next/lib/system-prompts.ts
+++ b/src/workspaces/flow/next/lib/system-prompts.ts
@@ -90,7 +90,7 @@ When using edit_diagram tool:
- For multiple changes, use separate edits in array
- RETRY POLICY: If pattern not found, retry up to 3 times with adjusted patterns. After 3 failures, use display_diagram instead.
-鈿狅笍 CRITICAL JSON ESCAPING: When outputting edit_diagram tool calls, you MUST escape ALL double quotes inside string values:
+IMPORTANT CRITICAL JSON ESCAPING: When outputting edit_diagram tool calls, you MUST escape ALL double quotes inside string values:
- CORRECT: "y=\\"119\\"" (both quotes escaped)
- WRONG: "y="119\\"" (missing backslash before first quote - causes JSON parse error!)
- Every " inside a JSON string value needs \\" - no exceptions!
@@ -228,7 +228,7 @@ Copy the search pattern EXACTLY from the current XML, including leading spaces,
**BAD:** \`{"search": "<mxCell value=\\"X\\" id=\\"5\\""}\` - Reordered attributes won't match
**GOOD:** \`{"search": "<mxCell id=\\"5\\" parent=\\"1\\" style=\\"...\\" value=\\"Old\\" vertex=\\"1\\">"}\` - Uses unique id with full context
-### 鈿狅笍 JSON Escaping (CRITICAL)
+### IMPORTANT JSON Escaping (CRITICAL)
Every double quote inside JSON string values MUST be escaped with backslash:
- **CORRECT:** \`"x=\\"100\\" y=\\"200\\""\` - both quotes escaped
- **WRONG:** \`"x=\\"100\\" y="200\\""\` - missing backslash causes JSON parse error!