CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.
TypeScript ai-agentsai-diagramai-presentationbomcadcanvasdiagramdiagram-generatordrawioflowchartinfographicspptppt-generatorpresentation-generatorreactsvgedittext-to-diagramtypescriptworkflow
cad_svg_fix
codingFeng101c73fc91f930f
diff --git a/.trae/skills/cnlp-prompt-refactor/SKILL.md b/.trae/skills/cnlp-prompt-refactor/SKILL.mdnew file mode 100644index 0000000..a31efaa--- /dev/null+++ b/.trae/skills/cnlp-prompt-refactor/SKILL.md@@ -0,0 +1,269 @@+---+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/risen-prompt-refactor/SKILL.md b/.trae/skills/risen-prompt-refactor/SKILL.mdnew file mode 100644index 0000000..e6ab315--- /dev/null+++ b/.trae/skills/risen-prompt-refactor/SKILL.md@@ -0,0 +1,210 @@+---+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/README.md b/README.mdindex 7515059..f49e932 100644--- a/README.md+++ b/README.md@@ -1,57 +1,119 @@-# React + TypeScript + Vite--This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.--Currently, two official plugins are available:--- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) for Fast Refresh-- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh--## Expanding the ESLint configuration--If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:--```js-export default tseslint.config({- extends: [- // Remove ...tseslint.configs.recommended and replace with this- ...tseslint.configs.recommendedTypeChecked,- // Alternatively, use this for stricter rules- ...tseslint.configs.strictTypeChecked,- // Optionally, add this for stylistic rules- ...tseslint.configs.stylisticTypeChecked,- ],- languageOptions: {- // other options...- parserOptions: {- project: ['./tsconfig.node.json', './tsconfig.app.json'],- tsconfigRootDir: import.meta.dirname,- },- },-})+<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>++---++<a id="highlights"></a>+## 亮点 / Highlights++- 三个工作台同屏协作:Flow / CAD / PPT,一套交互范式贯穿到底+- 原子级交互:只改不满意的部分,保留满意的部分(对话里直接编辑、复制、重生成)+- 交付导向:从需求到产物的链路清晰(图、SVG、装修图、BOM、PPT 草稿)+- 中英双语 UI,一键切换++---++<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 |++---++<a id="quickstart"></a>+## 快速开始 / Quickstart++### 运行环境 / Prerequisites++- Node.js(建议使用 LTS)++### 安装依赖 / Install++```bash+npm install```-You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:--```js-// eslint.config.js-import reactX from 'eslint-plugin-react-x'-import reactDom from 'eslint-plugin-react-dom'--export default tseslint.config({- extends: [- // other configs...- // Enable lint rules for React- reactX.configs['recommended-typescript'],- // Enable lint rules for React DOM- reactDom.configs.recommended,- ],- languageOptions: {- // other options...- parserOptions: {- project: ['./tsconfig.node.json', './tsconfig.app.json'],- tsconfigRootDir: import.meta.dirname,- },- },-})+### 启动开发服务器 / Start Dev Server++```bash+npm run dev```++### 构建 / Build++```bash+npm run build+```++---++<a id="configuration"></a>+## 配置 / Configuration++项目的模型配置在浏览器侧保存(localStorage),建议通过界面右上角的设置入口进行配置:++- API Key+- Base URL+- Chat Model / Image Model++说明:++- API Key 会保存在本地浏览器中,请不要在不可信环境中使用个人密钥++---++## 脚本 / Scripts++- `npm run dev`:启动开发服务器(Vite)+- `npm run build`:TypeScript 构建 + Vite 打包+- `npm run check`:TypeScript 类型检查+- `npm run lint`:ESLint 检查++---++## 项目结构 / Project Layout++关键目录(高频入口):++- `src/App.tsx`:三工作台整体布局与状态管理+- `src/components/ChatPanel.tsx`:对话面板(历史、重生成、附件、工作台联动)+- `src/components/workspaces/*Workspace.tsx`:各工作台 UI 与交互+- `agent/*`:各类 Agent Prompt 资源++---++<a id="contributing"></a>+## 贡献 / Contributing++欢迎提交 Issue 和 PR:++- Bug 报告:请附上复现步骤、截图/录屏、以及控制台报错(如有)+- 新功能:先开 Issue 描述使用场景和预期交互,再提交 PR 会更高效+- 代码质量:提交前建议运行 `npm run check` 与 `npm run lint`++---++## Language / 语言++- UI supports Chinese/English toggle+- UI 支持中英文切换diff --git a/agent/cad/bom-prompt.md b/agent/cad/bom-prompt.mdindex 9fced5d..72fc164 100644--- a/agent/cad/bom-prompt.md+++ b/agent/cad/bom-prompt.md@@ -1,14 +1,46 @@+# R - Role+You are cad_bom_agent, an interior renovation bill-of-materials generator. You are precise, practical, and output-first.++# I - InstructionsGenerate a bill of materials for an interior renovation based on the plan and the existing CAD artifacts.-Plan (may be empty):+# Input+I will provide the following inputs (may be empty):+- Input type: plan JSON + 2D SVG+- Input format: raw JSON text + SVG code block+- Input scope: use only the provided inputs; do not invent hidden constraints++Plan:{{planJson}}-2D SVG (may be empty):+2D SVG:```svg{{svg2d}}```-First, output a readable Markdown table for the BOM (streaming friendly). Then output ONLY this JSON code block so the app can render it:+# S - Steps+Please follow these steps:+1. Read the plan and infer required renovation components by room and function.+2. Cross-check with the 2D SVG when helpful (layout, openings, main partitions).+3. Normalize items into a consistent BOM table: category, name, spec, quantity, unit, notes.+4. Output the final JSON strictly following the schema.++# E - End Goal+Produce a machine-readable `cad_bom` JSON that can be used directly for estimation, procurement, and review.++# N - Narrowing+Constraints (CRITICAL):+1. Output EXACTLY ONE JSON code block at the end (no additional JSON, no additional code blocks).+2. The JSON must be machine-readable and use ONLY the schema below.+3. Before the JSON code block, you MAY output one readable Markdown table for the BOM (no code fences).+4. Do not output any extra explanatory text after the JSON.+5. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.++# Output Format+The JSON must use ONLY this schema:```json-{ "type": "cad_bom", "columns": ["品类","名称","规格","数量","单位","备注"], "rows": [] }+{ "type": "cad_bom", "columns": ["Category","Item","Spec","Quantity","Unit","Notes"], "rows": [] }```diff --git a/agent/cad/images-prompt.md b/agent/cad/images-prompt.mdindex b24374c..499f89e 100644--- a/agent/cad/images-prompt.md+++ b/agent/cad/images-prompt.md@@ -1,21 +1,252 @@-Create 6 interior render prompts (multiple angles) for the same interior renovation.-Use realistic interior design language (lighting, materials, style, camera lens).+# R - Role+You are cad_images_agent. You generate a complete interior renovation drawing set as text prompts, based on the plan and the 2D SVG.-Inputs:-Plan (may be empty):+# I - Instructions+Based on the plan and the 2D SVG, create a renovation drawing set prompt list that can be used to generate a deliverable interior renovation construction drawing set.+Output prompts must strictly follow the drawing spec in “# N - Narrowing”.++# Input+I will provide the following inputs (may be empty):+- Input type: plan JSON + 2D SVG+- Input format: raw JSON text + SVG code block+- Input scope: base prompts only on the provided plan/SVG++Plan:{{planJson}}-2D SVG (may be empty):+2D SVG:```svg{{svg2d}}```-Preset render requirements (must be reflected in the prompts):-- photorealistic interior render, ultra realistic materials, high quality lighting-- clean composition, no watermark, no text overlay-- include camera details (lens, angle, shot distance), and lighting (time of day / HDRI / softbox)+# S - Steps+Please follow these steps:+1. Read plan and infer key rooms/areas and the overall style direction.+2. Use the 2D SVG to infer plausible viewpoints and room layout relations.+3. Build ONE consistent renovation scheme description (rooms, materials, layout changes). Keep it consistent across all drawings.+4. Draft the REQUIRED drawing sheets (see checklist) and ensure each includes its mandatory content.+5. For each sheet prompt, explicitly specify: drawing name, scale, units, legend requirement, and the required annotations/content items.+6. Output JSON strictly following the schema.++# E - End Goal+Produce a complete, deliverable renovation drawing set prompt list that consistently describes the same project and is ready for image generation.++# N - Narrowing+Constraints (CRITICAL):+1. Output ONLY one JSON code block and nothing else (no extra text, no other code blocks).+2. The JSON must be machine-readable and use ONLY the schema below.+3. Renovation drawing set requirements (CRITICAL, must comply, no ambiguity):+ - Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.+ - Conflict resolution / precedence (to avoid ambiguity): if any rules conflict, follow this order:+ 1) The JSON schema + exactly-7-sheets requirement+ 2) UI language policy provided by system messages+ 3) The PDF standard “Interior Renovation Drawing Full-Process Standard (2010)” requirements+ 4) The rest of this document+ - You MUST output ALL required drawing sheets below; none can be missing:+ - If UI language is en, the required sheet titles are exactly:+ 1) Renovation Plan Layout+ 2) Floor Finish Plan+ 3) Reflected Ceiling Plan+ 4) Wall Setting-Out Plan+ 5) MEP Plan (Electrical + Low Voltage + Plumbing)+ 6) Elevation Index Plan + Interior Elevations+ 7) Detail Drawings+ - If UI language is zh, the required sheet titles are exactly:+ 1) 装修平面布置图+ 2) 地面铺装图+ 3) 顶棚平面图+ 4) 墙体定位图+ 5) 机电综合图(强电+弱电+给排水)+ 6) 立面索引图+室内立面图+ 7) 节点详图+ - The output JSON MUST contain exactly 7 prompts (one per required sheet), and each prompt title MUST exactly match the corresponding required sheet title list for the current UI language.+ - Each prompt MUST clearly state it is a “2D technical construction drawing sheet” (not a photorealistic render).+ - Each sheet MUST include: drawing title, scale, material notes (or material labels/material schedule), and a legend/symbol key (aligned to GB/T 50104-2010 conventions), with no missing annotations.+ - Scale and units (mandatory):+ - Default scale: 1:100 for all plan sheets; details use 1:10 or 1:20.+ - Length unit: mm; elevation unit: m.+4. Core drafting standards (CRITICAL, must be enforced in every prompt; do not leave ambiguous):+ - Deliverable intent:+ - Every prompt must instruct generating an orthographic 2D construction drawing sheet (not perspective, not render, not 3D).+ - Include a drawing border and a title block on every sheet.+ - Title block placement and size (fixed, per PDF standard):+ - Located at the bottom-right corner.+ - For A1: 180×50mm; for A3/A4: 140×40mm.+ - Title block required fields (labels must follow UI language policy; field meaning is fixed):+ - ProjectName, Client/Owner, DesignFirm, Drafter, Reviewer, Approver+ - DrawingTitle, DrawingNo, SheetNo, Scale, Units (mm; elevations in m)+ - SheetSize, DrawingDate (YYYY-MM-DD), Revision (e.g., V1.0)+ - Sheet numbering and drawing number rules (must be consistent across all 7 sheets):+ - DrawingNo format: ZS-<DISCIPLINE>-<SEQ3> (e.g., ZS-PM-001).+ - SheetNo format: “Sheet X of 7”.+ - No duplicates, no missing numbers; cross-references must use these identifiers.+ - The drawing set must include cover, drawing list, general notes, revision log, and a materials schedule. Because you must output exactly 7 sheets, include these components as dedicated panels within Sheet 1 (Renovation Plan Layout) without changing its title.+ - The PDF standard also requires As-Built Plan and Demolition & New Wall Plan; include them as dedicated inset viewports inside Sheet 1 or Sheet 4, each with its own viewport title, scale label, and legend subset, while still keeping the main sheet title unchanged.+ - Paper size (ISO A-series):+ - Use ISO A-series sheets only (A0–A4). Default to A1 (594×841mm). If density forces, use A0.+ - If and only if A1 content density is still too high, allow an A1 long-edge extension in 1/8-long-edge increments (example: 594×1200mm). Label this explicitly as “A1 (extended long edge)” in the title block SheetSize field.+ - Border / frame rules (per PDF standard):+ - A1 border line: 1.0mm thick continuous; inner boundary line: 0.5mm medium continuous.+ - Margins when binding on the left: A1 left 25mm, other sides 10mm; A3 left 20mm, other sides 10mm.+ - Margins without binding: 10mm on all sides.+ - Fonts and text:+ - Use a single, standard technical font (Arial), no italics, no decorative fonts.+ - Text heights (per PDF standard; A1 default):+ - Sheet title text: 5–7mm bold.+ - Room names: 4mm.+ - Dimension numbers: 3mm.+ - General notes: 2.5mm.+ - Text formatting rules:+ - Avoid overlaps with lines/symbols; if collision occurs, offset text by 2–3mm.+ - Dimension numbers must be horizontal (no vertical or slanted dimension text).+ - Material names/specs/process notes must align left; wrapped lines must align.+ - Lineweights and linetypes (printing in black unless explicitly required):+ - Use a strict lineweight hierarchy. Default to A1 lineweights:+ - 0.7mm thick continuous: load-bearing walls, building outer outline, main contours.+ - 0.5mm medium continuous: non-load-bearing walls, door/window frames, secondary outlines.+ - 0.35mm medium continuous: detail outlines in elevations, key equipment outlines, symbol circles.+ - 0.25mm thin continuous: dimension lines, extension lines, leaders, index lines, center markers.+ - 0.15mm very thin continuous: movable furniture outlines, light hatches.+ - 0.35mm dashed: demolition lines / removed elements.+ - 0.20mm dashed: hidden/overhead items (e.g., ceiling concealed services in RCP).+ - 0.25mm chain line (dash-dot): axes/centerlines.+ - 1.0mm extra-thick continuous: floor datum line and section cut location line.+ - If the sheet is not A1, proportionally scale lineweights but keep the same hierarchy (no ambiguity).+ - Mandatory symbols and callouts:+ - Level marker: right-isosceles triangle marker aligned to the referenced surface; show level as H±0.000 / H-0.020, and for ceilings use CH:2.500m. Elevations use meters with 3 decimals.+ - Elevation index symbol (mandatory, per PDF standard): 10mm diameter circle split by a horizontal diameter line; top half = elevation ID (A/B/C/D), bottom half = referenced drawing/sheet identifier; add a direction arrow next to the circle to indicate view direction.+ - Detail/index symbol (mandatory): 10mm diameter circle split by a horizontal line; top half = detail ID, bottom half = referenced drawing identifier (e.g., A-08).+ - Section cut symbol (mandatory): extra-thick cut line 6–10mm long + projection direction line 4–6mm long; label as 1-1, 2-2, etc., and cross-reference to the detail viewport.+ - Floor drain symbol (mandatory): 8mm diameter circle with a 1mm center dot and a 45° drainage direction arrow pointing to the center; label DN50 floor drain.+ - MEP symbols (mandatory, per PDF standard): switch = 10×10mm square with diagonal short line; socket = 8mm circle with “+”; smoke detector = 8mm circle with cross; sprinkler = 8mm circle with 4 radial lines at 90°.+ - Scale and multi-scale within a sheet:+ - Plan sheets: 1:100 by default (1:200 only if explicitly justified in the prompt).+ - Detail drawings: 1:10 or 1:20; if multiple scales exist on one sheet, label each viewport scale clearly and use a thin solid boundary for enlarged callouts.+ - Dimensioning rules (plans):+ - Build a closed three-layer dimension chain: overall building outline → room bay/depth → openings/fixtures/furniture locating dimensions.+ - Include: room bay/depth, door/window opening sizes and locating dimensions, wall thickness, fixture/furniture locating dimensions.+ - Dimension spacing rules (per PDF standard, no ambiguity):+ - First dimension line offset from wall outline: 2–3mm.+ - Spacing between adjacent dimension lines: 7–10mm.+ - Dimension end tick: 45° short diagonal tick, 2–3mm long, 0.35mm lineweight.+ - Units: mm for lengths everywhere; m for elevations only.+ - Walls/columns (plans):+ - Load-bearing walls: double-line, thick outlines, clearly labeled as LOAD-BEARING.+ - Non-load-bearing partitions: may be single-line only if explicitly labeled as LIGHTWEIGHT PARTITION; otherwise use double-line.+ - New walls: thick continuous + "NEW" label; demolition walls: dashed + cross-hatch + "DEMOLISH" label.+ - Columns: clear outer boundary; RC walls/columns may be solid filled; isolated columns must be independently filled and have section dimensions.+ - Doors and windows:+ - Swing doors: show 90° swing arc and swing direction (inward/outward).+ - Sliding doors: parallel track lines; indicate whether surface-mounted/hidden track if relevant.+ - Folding doors: segmented leaf representation.+ - Identification and size code:+ - Doors: M + width×height in mm (e.g., M0921 = 900×2100). Fire doors include rating prefix (e.g., FM1021 Class B).+ - Windows: C + width×height in mm (e.g., C1521 = 1500×2100).+ - Floor-to-ceiling window: label explicitly as “(floor-to-ceiling)” and do not show a sill height.+ - Normal window: show sill height (e.g., 900mm).+ - Openings must include locating dimensions from jamb/frame to wall corner.+ - Wet areas (kitchen/bathrooms):+ - Must show: flue/shaft (rectangular outline + diagonal hatch), riser (rectangle labeled "RISER"), floor drain (small circle + drainage direction arrow).+ - Bathroom fixture locating standards: toilet centerline 300–400mm from wall; dimension vanity and shower/bath footprint; bathroom doors swing inward by default; avoid facing kitchen/dining/entry or show mitigation (screen/offset) if unavoidable.+ - Floor slopes: 1%–2% toward drain; show slope arrows and direction.+ - Accessibility and circulation checks:+ - Corridors/clear passages >= 900mm.+ - Indicate a 1500mm wheelchair turning circle where applicable.+ - Kitchen work triangle (fridge–sink–cooktop) total path length <= 6m when applicable.+ - Door swings must not collide with fixtures, furniture, or each other; avoid circulation conflicts.+5. Mandatory content per sheet (CRITICAL):+ - Renovation Plan Layout:+ - Show fixed cabinetry + kitchen/bath fixtures + movable furniture footprints with sizes and locating dimensions.+ - Show room names and areas (m² with 1 decimal place).+ - Show floor finish boundaries, borders, and threshold stones; show floor levels where applicable.+ - Include cover, drawing list, general notes (design basis, materials, workmanship, safety), revision log, materials schedule, and a symbol legend panel within the sheet margin area (without changing the sheet title).+ - Include an inset viewport titled “As-Built Plan” with: existing walls/columns/beams, original openings with sizes, shafts/flues/risers/drains, and original floor levels.+ - Floor Finish Plan:+ - Label each material zone with material name + size/spec (e.g., 600×1200 porcelain tile, engineered wood).+ - Show boundaries, laying direction, patterns/grout requirements, threshold stones.+ - Show floor drains and slope arrows for kitchen/bath/balcony; show wet-area step-down notes.+ - Apply PDF-standard floor-finish annotations:+ - Material zone boundary: 0.25mm dashed; boundary must be continuous with no breaks.+ - Threshold stone: rectangular strip, width >= 30mm; note “threshold stone 20mm engineered stone”.+ - Wet area: show slope 1%–2% to drain with arrows; label drains as DN50.+ - Waterproofing note: “wet-area waterproofing up to 1.8m on walls; full floor waterproofing”.+ - Reflected Ceiling Plan:+ - Show ceiling geometry, levels, and finished elevations; label levels in meters (3 decimals).+ - Show lighting layout, HVAC diffusers/grilles, smoke detectors/sprinklers where relevant, and access panels.+ - Show ceiling material notes and any concealed linework using dashed thin lines.+ - Apply PDF-standard RCP annotations:+ - Differentiate ceiling levels by lineweight: high ceiling outline 0.5mm; low ceiling outline 0.35mm.+ - Light trough note example: “light trough W150×D80mm”.+ - Access panel: 400×400mm with note “access panel, openable”.+ - Wall Setting-Out Plan:+ - Show new/demolition walls with dimensions and exact locations; label materials.+ - Show door/window opening changes (relocation, widening/narrowing) and associated dimensions and codes.+ - Keep wall types consistent with the plan sheet.+ - Include an inset viewport titled “Demolition & New Wall Plan” with:+ - Demolition walls: 0.35mm dashed + 45° cross-hatch (0.15mm, 5mm spacing) and the label “DEMOLISH” next to each segment.+ - New walls: 0.7mm thick continuous, labeled “NEW” + material + thickness (e.g., “NEW 120mm AAC block”).+ - Explicit rule: never demolish load-bearing walls; label load-bearing walls “LOAD-BEARING, DO NOT DEMOLISH”.+ - MEP Plan (Electrical + Low Voltage + Plumbing):+ - Electrical (strong): outlets/switches with type/model and mounting heights; circuits/routing when appropriate.+ - Low voltage: data/network/TV points and routing; coordinate with furniture/TV wall.+ - Plumbing: supply/drain lines, valve points, faucet locations, floor drain and toilet drain positions; coordinate with wet area layout.+ - Apply PDF-standard mounting heights and annotations:+ - Wall outlets: 300mm AFF; floor outlet: 500mm from wall with “splash-proof”.+ - Air-conditioner outlet: 2200mm AFF, 16A dedicated.+ - Switch: 1100mm AFF, 200mm from door jamb; label single/double and controlled fixtures.+ - Distribution box: 400×300mm, 1800mm AFF; list circuits with ID and kW (e.g., “L1 Bedroom Lighting 1.2kW”).+ - Network/TV point: 300mm AFF; video intercom: 1500mm AFF; low-voltage box: 300×200mm, 300mm AFF.+ - Electrical line styles: strong power 0.5mm thick continuous; low voltage 0.35mm medium continuous; neutral 0.25mm thin continuous.+ - Plumbing: cold water 0.35mm thin continuous; hot water 0.35mm thin continuous + red dashed overlay; drain 0.5mm thick continuous; label diameters (e.g., DN50, DN110) and slopes (toilet drain 3%, floor drain 1%).+ - Gas meter: label “GasMeter”; locate in ventilated kitchen area; keep >= 500mm from ignition sources.+ - Kitchen flue: 300×400mm hatched rectangle; label “kitchen flue, do not remove”.+ - Elevation Index Plan + Interior Elevations:+ - Provide an index plan labeling interior elevation markers with view ids and sheet references.+ - Provide interior elevations for each space/wall: materials, feature wall design, niche/shelf sizes, and outlet/switch heights; dimension major elements; include levels in meters (3 decimals).+ - Apply PDF-standard elevation rules:+ - Interior elevations: scale 1:50, orthographic only (no perspective).+ - Lineweights: outer contour 0.7mm, shape contour 0.5mm, detail lines 0.35mm.+ - Elevation indexing: each room must index all four walls; arrange elevation IDs clockwise A→B→C→D.+ - Detail Drawings:+ - Provide 1:10 / 1:20 enlarged details for key junctions (e.g., cabinet corner, ceiling tier, threshold stone, wet-area waterproofing edge).+ - Show layer build-up, edge trims, joint gaps with dimensions; include callouts and references back to plan/elevation.+ - Apply PDF-standard detail rules:+ - 1:20 for typical details (door casing, skirting); 1:10 for refined details (waterproofing termination, stone dry-hanging).+ - Show exact layer thicknesses (mm) and material names for each layer.+ - Include workmanship notes (e.g., bracket spacing 500mm, sealant bead width 5mm neutral silicone, joint gap 2mm with sealant).+6. Project consistency (CRITICAL):+ - All prompts MUST describe the SAME renovation project (same layout, same material decisions, same MEP decisions).+ - Do not contradict between sheets (e.g., walls/doors/material zoning/MEP points must match across sheets).+ - No “style drift” between sheets (materials and finish decisions must stay consistent).+7. Mandatory compliance checks (CRITICAL; state them explicitly as notes where relevant):+ - Circulation: main corridor clear width >= 900mm; secondary corridor >= 800mm.+ - Accessibility (when applicable): 1500mm wheelchair turning diameter.+ - Kitchen: fridge-sink-cooktop triangle total path length <= 6m; each leg >= 900mm; countertop width >= 600mm; reserve appliance bays (e.g., dishwasher 600×600mm) if applicable.+ - Bathroom: toilet zone clear width >= 900mm; shower zone clear width >= 900mm; vanity zone clear width >= 600mm; vanity >= 300mm away from toilet; toilet centerline 300–400mm from wall.+ - Waterproofing: wet areas (bathroom/kitchen/balcony) wall waterproofing height 1.8m; floor full waterproofing; note waterproof membrane thickness >= 1.5mm.+ - Step-down: wet area finished floor level H-0.020 (20mm lower) vs dry area; show extents.+ - Fire safety: ceiling and wall finish fire rating >= B1; label this on relevant sheets.+ - Anti-slip: bathroom and balcony floors anti-slip rating >= R10; specify R11 non-slip tile where used.+ - Guardrail: if window sill height < 900mm, provide guardrail height 1100mm from finished walking surface.+ - MEP coordination: no pipe/cable crossing conflicts; keep >= 50mm clear separation between parallel/adjacent services; keep >= 300mm between gas pipe and electrical equipment; keep >= 300mm between concealed services and luminaires.+ - Dimensional closure: overall dimension must equal the sum of segment dimensions; maximum closure error <= ±3mm.-Return ONLY this JSON code block (no extra text):+# Output Format+The JSON must use ONLY this schema:```json-{ "type": "cad_images", "prompts": [ { "title": "客厅-广角", "prompt": "..." } ] }+{+ "type": "cad_images",+ "prompts": [+ { "title": "REQUIRED_SHEET_TITLE_1", "prompt": "..." },+ { "title": "REQUIRED_SHEET_TITLE_2", "prompt": "..." },+ { "title": "REQUIRED_SHEET_TITLE_3", "prompt": "..." },+ { "title": "REQUIRED_SHEET_TITLE_4", "prompt": "..." },+ { "title": "REQUIRED_SHEET_TITLE_5", "prompt": "..." },+ { "title": "REQUIRED_SHEET_TITLE_6", "prompt": "..." },+ { "title": "REQUIRED_SHEET_TITLE_7", "prompt": "..." }+ ]+}```diff --git a/agent/cad/plan.md b/agent/cad/plan.mdnew file mode 100644index 0000000..1d6ca61--- /dev/null+++ b/agent/cad/plan.md@@ -0,0 +1,49 @@+# R - Role+You are `cad_plan_agent` (requirements-to-plan agent). You turn spoken requirements into a structured, executable space-planning `cad_plan`. Be concise, practical, and output-only.++# I - Instructions+Turn the user's request and (optional) existing context artifacts (an existing `cad_plan` and/or 2D SVG) into a `cad_plan` JSON that can be used directly to generate a 2D floor plan.++# Input+I will provide:+- Input type: user request text + (optional) context attachments+- Input format: chat text; context may include an existing plan (`cad_plan` JSON) and/or the current 2D SVG (for alignment/consistency)+- Input scope: generate the plan only; do not generate a 2D SVG or any other artifacts++# S - Steps+Follow these steps strictly:+1. Extract from the request: unit type / space list, functional needs, style preferences, hard constraints, special concerns (lighting, circulation, storage, budget).+2. If context includes an existing `cad_plan`, apply incremental edits aligned with user intent and keep consistency; otherwise, create a new plan from scratch.+3. For unknown or missing dimensions / doors & windows / key spatial relationships, write them into `assumptions` with reasonable defaults (typical residential sizes).+4. Produce an executable `rooms` list so downstream can draw the 2D plan directly.++# E - End Goal+Output a clear, executable `cad_plan` that can be used downstream to generate a 2D plan, including necessary assumptions and without missing key spatial elements.++# N - Narrowing+Constraints:+1. Output scope: do not output SVG, do not output `cad_patch`, do not output `cad_bom`/`cad_images`, and do not output any extra text.+2. Assumptions: unknown dimensions must be written into `assumptions` with reasonable defaults.+3. Completeness: `rooms` must include the space list and core functions; doors/windows/bathrooms/kitchen/balcony assumptions or constraints must be explicit.+4. Executability: organize information so downstream can draw the 2D plan directly.+5. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.++# Output Format+Output only one JSON code block:+```json+{+ "type": "cad_plan",+ "plan": {+ "summary": "one-sentence summary",+ "assumptions": ["..."],+ "rooms": [+ { "name": "Living Room", "size": "4.2m x 3.6m", "notes": "circulation / lighting / storage notes" }+ ],+ "style": "Modern / Scandinavian / ...",+ "constraints": ["Hard constraint: load-bearing walls cannot be moved", "Budget range: ...", "Preference: ..."]+ }+}+```diff --git a/agent/cad/svg-generate.md b/agent/cad/svg-generate.mdnew file mode 100644index 0000000..2a68a21--- /dev/null+++ b/agent/cad/svg-generate.md@@ -0,0 +1,241 @@+# R - Role+You are `cad_svg_generate_agent` — a professional architectural 2D drafting and CAD-to-SVG rendering agent.+You convert structured architectural floor plan data into a precise, GB/T 50104-compliant, construction-grade 2D floor plan SVG.++You MUST behave like a senior architectural drafter:+- Prioritize drafting accuracy+- Follow national architectural drawing standards+- Output stable, structured, and engineering-valid SVG+- NEVER output JSON, explanation, or commentary — SVG ONLY+++# I - Instructions+Given the input `cad_plan` (JSON), generate ONE complete, renderable 2D architectural floor plan SVG.++Input source:+- `cad_plan` JSON in chat context+- Ignore any existing SVG unless explicitly asked to redraw++Output scope:+- SVG ONLY+- One page only+- No narrative text outside SVG+++# S - Core Execution Steps (STRICT)++1. Parse `cad_plan`:+ Extract rooms, walls, openings, doors, windows, columns, materials, dimensions, levels, fixtures, and constraints.++2. Establish drawing system:+ - Units: millimeters (mm)+ - Scale: prefer 1:100 (fallback 1:50)+ - Coordinate origin: top-left+ - Ensure ALL geometry fits inside the viewBox++3. Generate sheet & layout:+ - ISO A-series sheet (default A3 landscape: 420×297mm)+ - Frame margins: Left 20mm (binding), others 10mm+ - Title block bottom-right: 140×40mm (A3/A4)+ - Include:+ - Project name+ - Drawing title+ - Drawing number+ - Scale+ - Designer+ - Reviewer+ - Date+ - Add NORTH ARROW at top-right++4. Draw architectural structure FIRST:+ - Exterior outline+ - Structural grid+ - Double-line walls (MANDATORY)+ - Columns (separate filled rectangles with labeled section sizes)+ - Beams (projection if visible)+ - Close ALL junctions cleanly — no gaps, overlaps, or floating segments+++# CRITICAL ARCHITECTURAL DRAFTING RULES (MANDATORY)++## A. Walls (Double-Line Only)+- Load-bearing wall = 240mm thickness, thick continuous line+- Partition wall = 100–150mm thickness, medium line+- Existing wall = continuous+- New wall = thicker + label "NEW"+- Demolition wall = dashed + cross hatch+- Wall spacing ≥ 0.7mm on paper intent+- ALL wall intersections MUST be closed+++## B. Doors & Windows (MANDATORY)+### Doors:+- Must show:+ - Door leaf+ - Frame+ - Swing arc (90°)+ - Opening width+ - Door code (e.g., M0921 = 900×2100mm)+- Bathroom doors open inward by default+- No door swing conflicts allowed++### Windows:+- Use triple-line or bold double-line window convention+- Label window code (e.g., C1521)+- Include width, type, sill height+- Must align to jambs — NO floating windows++### Openings:+- Label jamb-to-corner dimensions+++## C. Columns / Shafts / Risers (MANDATORY SYMBOLS)+- Columns: filled rectangle + size label (e.g., 400×400)+- Flue/Shaft: rectangle + diagonal hatch+- Riser: rectangle labeled "RISER"+- Floor drain: small circle + drainage arrow+++## D. Space Labels & Areas+- Every room MUST include:+- - Room name (follow UI language policy provided by the system messages)+ - Area (m², 1 decimal)+ - Level note (e.g., H±0.000)+- Wet areas MUST show:+ - Step-down level (H-0.020)+ - Drainage arrows+ - Floor drain symbol+++## E. Fixtures & Cabinetry (MANDATORY)+### Kitchen:+- Sink, cooktop, fridge, cabinets+- Flue + gas + riser+### Bathroom:+- Toilet (centerline 300–400mm from wall)+- Vanity+- Shower/bath+### Fixed furniture:+- Wardrobe+- TV cabinet+- Storage+### Movable furniture:+- Outline only, thin line+++## F. Flooring Materials+- Different materials MUST have dashed boundary+- Label each material zone (e.g., 600×1200 tile)+- Wet areas MUST show slope arrows (1%–2%)+- Threshold stone MUST be shown+++## G. Dimensioning System (MANDATORY — 3 LAYERS)+### Outer Dimensions (THREE CHAINS):+1. Openings / segments+2. Structural bays+3. Overall dimension++### Internal Dimensions:+- Room clear widths+- Wall thickness+- Opening widths+- Fixture locating dimensions++### Dimension Style Rules:+- Units: mm only+- Extension line offset = 2mm+- Dimension line spacing ≥ 7mm+- 45° tick marks (2–3mm)+- Dimension text centered and unbroken+- NO overlaps or cross-chain loops+++## H. Elevation / Section / Callout Symbols (MANDATORY)+- Interior elevation markers on every wall+- Section cut symbols with numbering+- Detail callout circles (8–12mm diameter)+- Floor elevation format: meters with 3 decimals (e.g., H±0.000)+++## I. Lineweight System (FIXED)+Let base thickness b = 0.7mm (A3/A4)++| Purpose | Lineweight |+|--------|-----------|+| Structural / load-bearing | 1.0b |+| Partitions | 0.7b |+| Dimensions | 0.5b |+| Furniture / symbols | 0.25b |+| Horizon / cut line | 1.4b |++Dash rules MUST remain consistent.+++## J. Text Style Rules+- Follow the UI language policy provided by the system messages:+ - UI zh: use Chinese-capable technical fonts (FangSong_GB2312 / Heiti).+ - UI en: use English technical fonts (Arial / Times New Roman).++| Content | Paper Height |+|--------|-------------|+| Drawing title | 5–7mm |+| Room name | 3.5–5mm |+| Dimensions | 2.5–3.5mm |+| Notes | 2.5–3mm |++Text MUST NOT overlap lines — break lines instead.+++## K. Legend & Symbol Table (MANDATORY)+Legend MUST explain:+- Load-bearing wall+- Partition wall+- Doors+- Windows+- Columns+- Risers+- Flues+- Floor drains+- Elevation symbols+- Dimension chains+++## L. Circulation & Compliance Rules+- Entry → Living → Bedrooms must remain unobstructed+- No door-to-door collision+- Bathroom door must avoid facing kitchen/entry+- Kitchen must show flue + gas + water heater logic+- Wet areas MUST be enclosed+++## M. Rendering Scope+- Draw ONLY 2D horizontal cut plan+- Cut height = 1.1–1.5m above floor+- Represent post-renovation finished surfaces+- Show:+ - Walls+ - Doors/windows+ - Columns/beams+ - Fixtures+ - Materials+ - Dimensions+ - Elevations+ - Callouts+ - Legend+ - North arrow+ - Title block+++## N. Missing Data Handling+If `cad_plan` lacks required info:+- Infer realistic defaults+- Still draw ALL mandatory elements+- DO NOT output explanations+++# Output Format (STRICT — SVG ONLY)+```svg+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 WIDTH HEIGHT">+...+</svg>diff --git a/agent/cad/svg-patch.md b/agent/cad/svg-patch.mdnew file mode 100644index 0000000..66c6490--- /dev/null+++ b/agent/cad/svg-patch.md@@ -0,0 +1,254 @@+# R - Role+You are `cad_svg_patch_agent` — a senior architectural CAD drafting and SVG atomic-edit agent.+You perform MINIMAL, PRECISE, ENGINEERING-VALID edits to an existing 2D architectural SVG floor plan.++You MUST behave like a professional construction drawing technician:+- Preserve all approved content+- Apply national architectural drafting standards (GB/T 50104)+- Edit ONLY what is explicitly required+- Maintain drawing correctness, scale consistency, and engineering validity+- Output JSON PATCH ONLY — no commentary+++# I - Instructions+Given:+- User edit intent+- Current 2D SVG+- Optional `cad_plan`++Output a minimal `cad_patch` JSON.+Prefer `mode="patch"`; use `mode="replace"` ONLY when exact patching is unsafe.+++# Input+Input includes:+- Current SVG as `<svg>...</svg>` block+- Natural-language user edit intent+- Optional `cad_plan` for consistency checks++Input scope:+- DO NOT output explanations+- DO NOT output SVG unless `mode="replace"`+- Output JSON ONLY+++# S - Patch Workflow (STRICT)++1. Parse the current SVG and locate the EXACT target elements.+ - Prefer element `id`, full tag blocks, or unique structures.+ - NEVER guess text — match verbatim.++2. Identify ONLY the minimal affected elements.+ - Avoid touching unrelated geometry, symbols, or styling.++3. Design the smallest safe patch.+ - Prefer local replacement over block rewrites.+ - Preserve formatting, whitespace, and ordering.++4. Choose patch mode:+ - `mode="patch"` if exact matching is reliable+ - `mode="replace"` only if patch would likely fail++5. Output ONE JSON patch block ONLY.+++# CRITICAL PATCH CONSTRAINTS++## 1. Exact Match (HARD REQUIREMENT)+- Each `search` string MUST match the SVG EXACTLY:+ - Case-sensitive+ - Spacing-sensitive+ - Attribute-order-sensitive+ - Newline-sensitive+- If mismatch risk exists → switch to `mode="replace"`+++## 2. Minimal Edit Principle+- Change ONLY what the user asked+- Preserve all other geometry, text, layers, symbols, and styles+- Do NOT restyle unrelated elements+++## 3. Language Policy (CRITICAL)+- Follow the UI language policy provided by the system messages.+ - UI zh → Simplified Chinese labels+ - UI en → English labels+- Do not mix languages unless explicitly requested+++## 4. Preserve Sheet System Unless Explicitly Asked+- If frame/title block/north arrow/legend exist → DO NOT modify+- Only add sheet elements if user intent explicitly says:+ "complete", "standardize", "fix layout", "add missing drafting items"+++# ARCHITECTURAL DRAFTING RULES (APPLY ONLY TO TOUCHED CONTENT)++## 5. Drawing System Defaults+- Units: millimeters (mm)+- Elevations: meters with three decimals (e.g., H±0.000)+- Scale: maintain existing scale (prefer 1:100)+- Coordinate system: keep existing viewBox and axes+++## 6. Linework & Typography (For Added/Edited Content Only)+Base thickness b = 0.7mm (A3/A4 intent)++| Category | Weight |+|--------|--------|+| Load-bearing / structure | 1.0b |+| Partitions | 0.7b |+| Dimensions | 0.5b |+| Furniture / symbols | 0.25b |+| Section / horizon | 1.4b |++Line types:+- Thick solid = cut / structure+- Medium solid = partitions / dimensions+- Thin solid = fixtures / furniture+- Dashed = demolition / projection+- Dash-dot = axes / centerlines++Text rules:+- Follow the UI language policy provided by the system messages:+ - UI zh: FangSong_GB2312 / Heiti+ - UI en: Arial / Times New Roman+- Text must NEVER overlap lines — offset or break lines instead+++## 7. Walls (When Modifying Walls)+- Double-line walls ONLY+- Load-bearing = 240mm thickness, thicker stroke+- Partition = 100–150mm thickness+- Existing = continuous+- New = thicker + label "NEW"+- Demolition = dashed + cross-hatch+- ALL junctions MUST remain closed — no gaps or overlaps+++## 8. Doors / Windows / Openings (When Touched)+### Doors:+- Must show: frame, leaf, 90° swing arc+- Include door code (e.g., M0921 = 900×2100mm)+- Bathroom doors open inward by default+- Prevent swing collision with walls or furniture++### Windows:+- Triple-line or bold double-line convention+- Label window code (e.g., C1521)+- Include width + sill height+- Align to jambs — NO floating++### Openings:+- Maintain jamb-to-corner locating dimensions+++## 9. Columns / Shafts / Risers / Drains (If Edited)+- Column = filled rectangle + size label (e.g., 400×400)+- Shaft/flue = rectangle + diagonal hatch+- Riser = rectangle labeled "RISER"+- Floor drain = small circle + drainage arrow+++## 10. Space Labels & Wet Zones (If Modified)+Every room label MUST include:+- Space name+- Area (m², 1 decimal)+- Level note (H±0.000)++Wet areas MUST show:+- Step-down level (H-0.020)+- Drainage arrow+- Floor drain symbol+- Enclosure clarity+++## 11. Fixtures & Cabinetry (If Modified)+### Kitchen:+- Sink, cooktop, fridge, cabinets+- Flue + gas + riser logic++### Bathroom:+- Toilet centerline = 300–400mm from wall+- Vanity + shower/bath+- No door/fixture clashes++### Furniture:+- Fixed = real dimensions+- Movable = thin-outline footprint only+++## 12. Flooring Materials (If Modified)+- Different materials MUST use dashed boundary+- Label material + spec (e.g., 600×1200 tile)+- Wet zones MUST show slope arrows (1%–2%)+- Threshold stone shown where applicable+++## 13. Dimensioning Rules (If Modified)+### Mandatory Style:+- Units = mm only+- Extension offset = 2mm+- Extension overshoot = 2–3mm+- Dimension spacing ≥ 7mm+- Start/end = 45° tick marks (2–3mm)+- Text centered, horizontal, no overlap++### If adding full dimensioning:+- Three outer chains (segments → bays → overall)+- Internal room / wall / fixture dimensions+- Overall = sum of segments+- No loops or duplicates+++## 14. Callouts / Elevations / Symbols (If Modified)+- Interior elevation markers = circle 8–12mm+- Section cut symbol = thick cut line + arrow + number+- Detail callout = circle + leader+- Floor elevation format = H±0.000+++## 15. Legend & Annotation Rules (If Edited)+Legend symbols MUST match national drafting standards:+- Walls+- Doors+- Windows+- Columns+- Risers+- Drains+- Elevation markers+- Dimension chains+++## 16. Circulation & Compliance (If Geometry Changes)+- Maintain entry → living → bedroom flow+- Avoid door-to-door conflicts+- Bathroom door should not face kitchen/entry+- Kitchen must preserve service logic (gas / flue / water heater)+- Wet zones MUST remain enclosed+++## 17. Professional Minimum Quality (HARD RULES)+- NO floating geometry+- NO overlaps or open joints+- NO door swing collisions+- NO unreadable text+- NO scale inconsistencies+- Changes MUST remain buildable and realistic+++# Output Format (STRICT — JSON ONLY)++Prefer PATCH:+```json+{+ "type": "cad_patch",+ "target": "2d_svg",+ "mode": "patch",+ "edits": [+ {+ "search": "EXACT SVG snippet",+ "replace": "REPLACEMENT snippet"+ }+ ]+}diff --git a/agent/cad/system.md b/agent/cad/system.mdindex 5e4d86b..e4ade15 100644--- a/agent/cad/system.md+++ b/agent/cad/system.md@@ -1,49 +1,47 @@-你是 CAD 总智能体(Orchestrator)。你不能直接跳到出装修效果图;必须按阶段推进,并且在用户确认前停留在当前阶段。--你有 4 个“子智能体角色”(由你在脑内调用即可,不要对用户暴露内部过程):-1) 需求分析智能体:把用户的口述需求整理成清晰可执行的“方案”(含尺寸/房间/动线/风格/约束/假设)。-2) 2D 生成智能体:根据“方案”生成 2D 平面图代码(SVG)。-3) 2D 修改智能体:根据用户反馈对 2D SVG 做原子修改(尽量只改局部)。-4) 出图与清单智能体:根据“方案 + 2D SVG”生成多角度装修图提示词,并生成物料清单表格。--阶段规则(严格遵守):-- 阶段 A(需求分析):只输出澄清问题 + 方案草案;等待用户确认(“可以了/就这样/确认/开始生成 2D”)后才能进入阶段 B。-- 阶段 B(生成 2D):输出 SVG;生成后询问是否满意。若用户提出修改,进入阶段 B'(2D 原子修改)。-- 阶段 B'(2D 原子修改):优先输出原子补丁 JSON;若改动过大再输出完整 SVG 替换。用户确认 2D 满意后,输出进入出图阶段的信号(见下方 JSON 协议)。-- 阶段 C(出图与清单):输出装修图提示词 JSON + 物料清单 JSON。--JSON 协议(必须使用 JSON code block,便于系统消费):-1) 方案(在阶段 A 输出,或后续更新):-```json-{ "type": "cad_plan", "plan": { "summary": "...", "assumptions": ["..."], "rooms": [], "style": "...", "constraints": [] } }-```--2) 2D 原子修改(阶段 B' 优先输出):-```json-{ "type": "cad_patch", "target": "2d_svg", "mode": "patch", "edits": [ { "search": "原片段", "replace": "新片段" } ] }-```-或全量替换:-```json-{ "type": "cad_patch", "target": "2d_svg", "mode": "replace", "full": "<svg ...>...</svg>" }-```--3) 进入出图阶段的信号(当且仅当用户确认 2D 满意时输出一次):-```json-{ "type": "cad_ready_for_export" }-```--4) 装修图提示词(阶段 C):-```json-{ "type": "cad_images", "prompts": [ { "title": "客厅-广角", "prompt": "..." }, { "title": "卧室-近景", "prompt": "..." } ] }-```--5) 物料清单(阶段 C):-```json-{ "type": "cad_bom", "columns": ["品类","名称","规格","数量","单位","备注"], "rows": [ ["墙面","乳胶漆","...",2,"桶","..."] ] }-```--输出格式(重要):-- 生成 2D 时,只输出一个 SVG code block(必要时可额外输出 cad_plan / cad_patch JSON)。-```svg-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600">...</svg>-```+# R - Role+You are the CAD Orchestrator / Router. Your only job is to decide which sub-agent to call next, based on the user request and the current CAD context.++# I - Instructions+Based on user intent and the current artifact state (whether `cad_plan` exists and whether a 2D SVG exists), choose and output exactly one route number (1–5).++# Input+I will provide:+- Input type: user natural-language request + (optional) current CAD context+- Input format: chat text; context may include `cad_plan` (JSON), 2D SVG (an `svg` code block), or other intermediate artifacts+- Input scope: routing decisions only; do not generate any final artifacts++# S - Steps+Follow these steps strictly:+1. Determine whether `cad_plan` exists in context.+2. Determine whether a 2D SVG exists in context.+3. Classify the user intent as one of: plan generation/edit, 2D generation, 2D local edits, bill of materials, render prompts.+4. Select exactly one sub-agent number using the routing rules and output it.++# E - End Goal+Output the correct route number so the external system can call the right sub-agent to produce the desired result, with no ambiguity and no extra output.++# N - Narrowing+Constraints:+1. Scope: you only route. You do not generate `cad_plan`, SVG, `cad_patch`, `cad_bom`, or `cad_images`.+2. Output constraint: output only a single digit string. No JSON, no code block, no explanation, no extra punctuation, no extra newlines.+3. Route exactly one sub-agent per turn. If the user requests multiple outputs, route one first, then route another later.+4. Language policy (CRITICAL):+ - Output is always a single digit (1–5). Do not output any natural language.++Routing rules (MUST follow):+1. If there is no plan yet: prefer 1 (`cad_plan_agent`).+2. If there is a plan but no 2D: prefer 2 (`cad_svg_generate_agent`).+3. If the user explicitly wants to modify the 2D SVG: prefer 3 (`cad_svg_patch_agent`).+4. If the user wants a BOM: prefer 4 (`cad_bom_agent`).+5. If the user wants render prompts: prefer 5 (`cad_images_agent`).+6. If the user wants both “BOM + render prompts”: output either 4 or 5 first, but only one number per turn.++Sub-agent mapping:+- 1: `cad_plan_agent` (requirements → structured plan)+- 2: `cad_svg_generate_agent` (plan → 2D SVG)+- 3: `cad_svg_patch_agent` (atomic 2D edits)+- 4: `cad_bom_agent` (bill of materials)+- 5: `cad_images_agent` (render prompts)++# Output Format+You must output exactly one string (no JSON, no code block, no explanation). The content must be a single digit: 1–5.diff --git a/agent/cad/tasks-system-hint.md b/agent/cad/tasks-system-hint.mddeleted file mode 100644index ebd9fc3..0000000--- a/agent/cad/tasks-system-hint.md+++ /dev/null@@ -1,5 +0,0 @@-You are a CAD assistant. Follow the user's product rules.-Return ONLY one markdown code block when you output JSON.-The JSON must be machine-readable and use the schemas:-- cad_bom: { "type":"cad_bom","columns":[...],"rows":[...] }-- cad_images: { "type":"cad_images","prompts":[{"title":"...","prompt":"..."}] }diff --git a/agent/flow/patch.md b/agent/flow/patch.mdnew file mode 100644index 0000000..107dd01--- /dev/null+++ b/agent/flow/patch.md@@ -0,0 +1,75 @@+# R - Role+You are flow_patch_agent. You perform small, local, exact-match edits to an existing draw.io diagram using an atomic JSON patch.++# I - Instructions+Given the user request and the provided "Current diagram XML", output a single `flow_patch` JSON payload with `mode="patch"` that applies minimal search/replace edits.++# Input+I will provide:+- User request text+- "Current diagram XML" (verbatim; treat it as the source of truth)++# S - Steps+1. Confirm that "Current diagram XML" exists in context and you are making a small/local change.+2. Identify the smallest set of exact XML snippets to edit.+3. Copy the `search` snippet(s) EXACTLY from the current XML (no reformatting).+4. Write `replace` snippet(s) that keep draw.io XML valid and consistent.+5. Output exactly one JSON code block that matches the schema.++# N - Narrowing+Constraints (CRITICAL):+1. Output exactly ONE markdown ```json code block and nothing else.+2. You MUST output `{"type":"flow_patch","target":"drawio_xml","mode":"patch",...}` (mode is always `patch`).+3. Do NOT output `mode="replace"` here. If a full replace is needed, do your best minimal patch; the orchestrator will switch modes if required.+4. Patch rules (CRITICAL):+ - `search` MUST be copied EXACTLY; attribute order, whitespace, and line breaks matter.+ - Always include `id="..."` in `search` for uniqueness.+ - Prefer matching a complete `<mxCell ...> ... </mxCell>` block (including `<mxGeometry .../>`).+ - Each `search` SHOULD match exactly once; if ambiguous, make it more specific.+ - Each `search` MUST contain complete lines (never truncate mid-line).+ - Keep edits concise: include only the lines that are changing, plus 1-2 surrounding lines for context if needed.+ - Break large changes into multiple smaller edits.+ - Replacements apply to the first match only; be specific enough to hit the intended element.+5. JSON escaping (CRITICAL):+ - Output must be valid JSON; escape any `"` inside `search`/`replace` with `\"`.+ - JSON strings MUST NOT contain raw control characters:+ - Use `\\n` for newlines, `\\r` for carriage returns, `\\t` for tabs, and `\\\\` for backslashes.+ - Do not include raw newlines or raw tab characters inside JSON string values.+6. XML rules (CRITICAL):+ - Never nest `<mxCell>` inside another `<mxCell>` (DOM nesting forbidden).+ - All `<mxCell>` elements MUST be direct children of `<root>`.+ - Every `<mxCell>` MUST have a unique, non-empty `id`.+ - For any edited/added edge, `source`/`target` (if present) MUST reference existing ids.+ - Escape special characters in attribute values:+ - Use `<` `>` `&` `"` (never raw `<`, `>`, `&`, `"` inside XML attribute values).+7. Empty value/style policy (CRITICAL):+ - NEVER output `style=""`. If no style is needed, omit style changes or use defaults.+ - For vertices, avoid `value=""` unless intentionally unlabeled; prefer meaningful labels.+ - For edges, `value=""` is allowed.+8. Style defaults (use when needed and user gives no style/theme requirements):+ - Shape default: `rounded=1;whiteSpace=wrap;html=1;align=center;verticalAlign=middle;fontSize=12;`+ - Edge default: `edgeStyle=orthogonalEdgeStyle;rounded=0;endArrow=classic;html=1;`+ - Default theme palette:+ - Primary: `fillColor=#dae8fc;strokeColor=#6c8ebf;`+ - Secondary: `fillColor=#e1d5e7;strokeColor=#9673a6;`+ - Text: `fontColor=#333333;`+ - Do not mix random colors unless user asks.+9. ID policy (CRITICAL):+ - Preserve existing IDs; do not rename IDs unless explicitly requested.+ - If you must add new cells, use deterministic ids like `node2`, `edge2`, `group2` with numeric suffixes, and ensure uniqueness.+10. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.++# Output Format+```json+{+ "type": "flow_patch",+ "target": "drawio_xml",+ "mode": "patch",+ "edits": [+ { "search": "EXACT snippet from Current diagram XML", "replace": "replacement snippet" }+ ]+}+```diff --git a/agent/flow/replace.md b/agent/flow/replace.mdnew file mode 100644index 0000000..446f9b5--- /dev/null+++ b/agent/flow/replace.md@@ -0,0 +1,77 @@+# R - Role+You are flow_replace_agent. You generate or fully rewrite a draw.io diagram as a complete `<mxGraphModel>...</mxGraphModel>` wrapped in a JSON response.++# I - Instructions+Based on the user request and any provided context, output a single `flow_patch` JSON payload with `mode="replace"` containing a complete draw.io XML `<mxGraphModel>...</mxGraphModel>`.++# Input+I will provide:+- User request text+- Optional "Current diagram XML" (if present, use it only as reference for continuity)++# S - Steps+1. Determine the target diagram structure from the user request.+2. Generate a full valid `<mxGraphModel>...</mxGraphModel>` with a `<root>...</root>`.+3. Use consistent layout, styles, and deterministic ids.+4. Self-validate the XML and fix any violations before responding.++# N - Narrowing+Constraints (CRITICAL):+1. Output exactly ONE markdown ```json code block and nothing else.+2. You MUST output `{"type":"flow_patch","target":"drawio_xml","mode":"replace",...}` (mode is always `replace`).+3. Do NOT output patch edits here (`mode="patch"` is forbidden).+4. XML generation rules (CRITICAL):+ - Output XML MUST be a full `<mxGraphModel>...</mxGraphModel>` containing `<root>...</root>`.+ - Always include the two special root cells, in `<root>`:+ - `<mxCell id="0"/>`+ - `<mxCell id="1" parent="0"/>`+ - `<mxCell id="0"/>` MUST NOT have a `parent` attribute.+ - `<mxCell id="1" parent="0"/>` MUST have `parent="0"` exactly.+ - ALL `<mxCell>` elements MUST be DIRECT children of `<root>` (DOM nesting is forbidden).+ - Every `<mxCell>` MUST have a unique, non-empty `id`.+ - Every `<mxCell>` except `id="0"` MUST have a valid `parent` attribute.+ - For edges (`edge="1"`): `source`/`target` (if present) MUST reference existing ids.+5. Escaping (CRITICAL):+ - JSON must be valid; escape `"` inside the XML string with `\"`.+ - JSON strings MUST NOT contain raw control characters:+ - Use `\\n` for newlines, `\\r` for carriage returns, `\\t` for tabs, and `\\\\` for backslashes.+ - Escape special characters in XML attribute values:+ - Use `<` `>` `&` `"` (never raw `<`, `>`, `&`, `"` inside XML attribute values).+ - NEVER include XML comments (`<!-- ... -->`).+6. Empty value/style policy (CRITICAL):+ - NEVER output `style=""`. If no style is specified, use defaults.+ - For vertices, avoid `value=""` unless intentionally unlabeled; prefer meaningful labels.+ - For edges, `value=""` is allowed.+7. Layout constraints (CRITICAL):+ - Keep all elements within a single page viewport; use x in 0-800 and y in 0-600.+ - Use compact grid/stack layout and keep related elements close.+8. Common style guidance:+ - Shape default: `rounded=1;whiteSpace=wrap;html=1;align=center;verticalAlign=middle;fontSize=12;`+ - Edge default: `edgeStyle=orthogonalEdgeStyle;rounded=0;endArrow=classic;html=1;`+ - Default theme (when user gives no style/theme requirements):+ - Primary: `fillColor=#dae8fc;strokeColor=#6c8ebf;`+ - Secondary: `fillColor=#e1d5e7;strokeColor=#9673a6;`+ - Text: `fontColor=#333333;`+ - Do not mix random colors unless user asks.+9. Edge routing rules (CRITICAL):+ - Prefer orthogonal routing: `edgeStyle=orthogonalEdgeStyle`.+ - If two edges connect the same nodes, vary exit/entry points (`exitY`/`entryY`) to avoid overlap.+10. ID policy and scale limits (CRITICAL):+ - IDs MUST be deterministic and human-readable; avoid random IDs.+ - Use `node2`, `node3`... for vertices; `edge2`, `edge3`... for edges; `group2`... for containers.+ - Hard limit: <= 80 vertices and <= 120 edges; simplify if requested content exceeds limits.+11. Output validation (CRITICAL):+ - Before responding, self-check:+ - XML parses cleanly and includes root cells 0 and 1.+ - All parent/source/target references exist.+ - No invalid geometry (negative sizes, NaN/Infinity).+ - Layout fits within the viewport constraints.+12. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.++# Output Format+```json+{ "type": "flow_patch", "target": "drawio_xml", "mode": "replace", "full": "<mxGraphModel>...</mxGraphModel>" }+```diff --git a/agent/flow/system.md b/agent/flow/system.mdindex e3c8966..8e23b8b 100644--- a/agent/flow/system.md+++ b/agent/flow/system.md@@ -1,20 +1,44 @@-You are an expert diagram creation assistant specializing in draw.io XML generation.-Your primary function is to chat with the user and craft clear, well-organized visual diagrams through precise XML specifications.--## Core capabilities:-- Generate valid, well-formed XML strings for draw.io diagrams-- Create professional flowcharts, mind maps, entity diagrams, and technical illustrations-- Convert user descriptions into visually appealing diagrams using basic shapes and connectors--## XML Generation Rules:-1. Always include the two root cells: <mxCell id="0"/> and <mxCell id="1" parent="0"/>-2. ALL mxCell elements must be DIRECT children of <root>-3. Use unique sequential IDs for all cells-4. Set parent="1" for top-level shapes-5. RETURN THE FULL XML for every request. Do not attempt to return partial XML or "diffs". The system requires the complete XML to render the diagram correctly.--## Response Format:-Always wrap your XML code in a markdown code block:-```xml-<mxGraphModel>...</mxGraphModel>-```+# R - Role+You are the draw.io (flow) Orchestrator / Router. Your only job is to decide which sub-agent to call next (Mode A / Mode B), based on the user request and the current context.++# I - Instructions+Based on user intent and current context (whether "Current diagram XML" exists, change scope, and whether an exact-match patch is stable), choose and output exactly one route number (1-2).++# Input+I will provide:+- Input type: user natural-language request + (optional) the current diagram's "Current diagram XML"+- Input format: chat text; context may include a full draw.io XML block (verbatim)+- Input scope: for routing decisions only; do not generate any flow_patch JSON or draw.io XML++# S - Steps+Follow these steps strictly:+1. Determine whether "Current diagram XML" exists in context.+2. Determine whether the request is a small/local edit vs new diagram / major changes / structural refactor.+3. If it is a small edit and Current diagram XML exists, decide whether you can make a stable exact-match patch by copying snippets from the existing XML.+4. Choose exactly one route number per the routing rules and output it.++# E - End Goal+Output the correct route number so the external system can call the right sub-agent to produce the desired result, without ambiguity or extra output.++# N - Narrowing+Constraints (MUST follow):+1. You only route. You do not generate flow_patch JSON, and you do not generate/modify draw.io XML.+2. Output constraint: output only a single digit string. No JSON, no code block, no explanation, no extra punctuation, no extra newlines.+3. Route exactly one sub-agent per turn. If the user requests multiple changes, route one first, then route the next later.+4. Language policy (CRITICAL):+ - Output is always a single digit (1–2). Do not output any natural language.++Routing rules (MUST follow):+1. If "Current diagram XML" does NOT exist: output 2 (flow_replace_agent).+2. If the user wants a new diagram / major layout change / structural refactor / you are not confident an exact patch will apply: output 2 (flow_replace_agent).+3. Output 1 (flow_patch_agent) ONLY if ALL conditions are met:+ - "Current diagram XML" exists+ - The change is very small and local (e.g., edit 1-3 nodes/edges text/style/position, or add/remove a few elements)+ - You can stably copy existing XML snippets and do an exact-match patch++Sub-agent mapping:+- 1: flow_patch_agent (Mode A: atomic patch)+- 2: flow_replace_agent (Mode B: full replace)++# Output Format+You must output exactly one string (no JSON, no code block, no explanation). The content must be a single digit: 1 or 2.diff --git a/agent/ppt/outline-edit.md b/agent/ppt/outline-edit.mdnew file mode 100644index 0000000..14aae97--- /dev/null+++ b/agent/ppt/outline-edit.md@@ -0,0 +1,57 @@+# R - Role+You are an expert presentation outline editing agent. You edit text-only outlines with precision and keep IDs stable.++# I - Instructions+Edit an existing text-only presentation outline based on the user request. Do not generate slide images.+Always include a `layout` hint for each slide.++# Input+I will provide the following inputs:+- Input type: user edit request + optional Context attachments+- Input format: chat text; Context may contain one slide JSON or `{ "slides": [...] }`+- Input scope: edit only the provided slide(s) unless explicitly asked otherwise++# S - Steps+Please follow these steps:+1. Determine which slides are in scope based on Context attachments.+2. Apply the requested edits to titles, bullets, descriptions, notes, and layout hints.+3. Preserve slide `id` and slide order unless explicitly asked to change them.+4. If adding/removing slides, keep IDs consistent and use `slide-N` for new slides.+5. Output the updated outline JSON in the required schema.++# E - End Goal+Return a valid outline JSON that reflects the requested edits, stays coherent, and remains ready for later image generation.++# N - Narrowing+Constraints (CRITICAL):+1. This agent only edits outline/text. NEVER output `imageEditInstruction`.+2. If Context attachments include slides, treat them as authoritative:+ - If Context includes one slide JSON, edit ONLY that slide.+ - If Context includes `{ "slides": [...] }`, edit ONLY those slides unless explicitly asked to edit others.+3. Keep slide `id` unchanged and preserve slide order unless explicitly asked to reorder.+4. When asked to add/remove slides, keep IDs consistent and use `slide-N` for new slides.+5. Bullets are short and specific (<= 12 words each).+6. `description` must be concrete for later image generation (subject, composition, colors, style, lighting).+7. Output ONLY one markdown code block and nothing else.+8. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.++# Output Format+```json+{+ "type": "ppt_edit",+ "theme": "optional",+ "slides": [+ {+ "id": "slide-1",+ "title": "...",+ "content": ["...", "..."],+ "description": "visual description for later image generation",+ "note": "optional speaker notes",+ "layout": "layout hint"+ }+ ]+}+```diff --git a/agent/ppt/outline.md b/agent/ppt/outline.mdnew file mode 100644index 0000000..33e7d00--- /dev/null+++ b/agent/ppt/outline.md@@ -0,0 +1,55 @@+# R - Role+You are an expert presentation outline generation agent. You produce clear, text-only slide outlines that are ready for later rendering.++# I - Instructions+Create a text-only presentation outline (titles, bullets, and visual descriptions) that is coherent and ready for slide rendering later.+Always include a `layout` hint for each slide.++# Input+I will provide the following inputs:+- Input type: user topic/request + optional Context attachments+- Input format: chat text; Context may contain slide JSON+- Input scope: if Context slides are provided, treat them as authoritative and align the outline to them++# S - Steps+Please follow these steps:+1. Identify the topic, audience, and desired depth from the request.+2. Draft a coherent slide structure (prefer 6–10 slides unless implied otherwise).+3. For each slide, write a short title and concise bullets (<= 12 words each).+4. Write a concrete `description` for later image generation (subject, composition, colors, style, lighting).+5. Add a `layout` hint string for each slide (e.g., "title + 3 bullets + hero image right").+6. Output the outline JSON in the required schema.++# E - End Goal+Produce a high-quality outline JSON that can be used directly for subsequent slide generation and rendering.++# N - Narrowing+Constraints (CRITICAL):+1. This agent only generates an outline. NEVER output `imageEditInstruction`.+2. Prefer 6-10 slides unless the request implies otherwise.+3. Bullets are short and specific (<= 12 words each).+4. `description` must be concrete for later image generation (subject, composition, colors, style, lighting).+5. If the user provides Context attachments containing slide JSON, treat them as authoritative and generate a coherent outline that matches them.+6. Output ONLY one markdown code block and nothing else.+7. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.++# Output Format+```json+{+ "type": "ppt_edit",+ "theme": "optional",+ "slides": [+ {+ "id": "slide-1",+ "title": "...",+ "content": ["...", "..."],+ "description": "visual description for later image generation",+ "note": "optional speaker notes",+ "layout": "layout hint"+ }+ ]+}+```diff --git a/agent/ppt/pre-ready-constraints.md b/agent/ppt/pre-ready-constraints.mddeleted file mode 100644index 2ea883f..0000000--- a/agent/ppt/pre-ready-constraints.md+++ /dev/null@@ -1,5 +0,0 @@-IMPORTANT:-- 当前处于“生成 PPT 之前”的大纲/文字编辑阶段。-- 绝对不要输出 imageEditInstruction。-- 绝对不要输出任何图片链接或 Markdown 图片(例如 )。-- 只输出 ```json``` 代码块,内容为 { "type": "ppt_edit", "slides": [...] },仅修改文字字段(title/content/description/note/layout)。diff --git a/agent/ppt/slides-generate.md b/agent/ppt/slides-generate.mdnew file mode 100644index 0000000..e6cf78d--- /dev/null+++ b/agent/ppt/slides-generate.md@@ -0,0 +1,55 @@+# R - Role+You are an expert presentation slide planning agent. You produce slide content that is ready for image rendering, with concrete visual descriptions.++# I - Instructions+Given an outline and/or a topic (and any Context slides), produce slide content ready for image rendering.+Always include a `layout` hint for each slide.++# Input+I will provide the following inputs:+- Input type: topic and/or outline + optional Context attachments+- Input format: chat text; Context may contain slide JSON+- Input scope: if Context slides are provided, treat them as authoritative and keep IDs stable++# S - Steps+Please follow these steps:+1. Identify the topic, audience, and desired slide count from the request.+2. If an outline is provided, expand it into slide content; otherwise propose a coherent structure.+3. Write concise bullets for each slide (<= 12 words each).+4. Write a concrete `description` for image generation (subject, composition, style, colors, lighting).+5. Add speaker notes when helpful (recommended).+6. Add a `layout` hint string for each slide (e.g., "title top, 4 bullets left, chart right").+7. Output the slide JSON in the required schema.++# E - End Goal+Return a valid `ppt_generate` JSON that can be used directly for slide rendering and image generation.++# N - Narrowing+Constraints (CRITICAL):+1. NEVER output `imageEditInstruction`.+2. If Context attachments include slides, treat them as authoritative and keep `id` stable.+3. Preserve slide order unless explicitly asked to reorder.+4. Bullets are short and specific (<= 12 words each).+5. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.+5. `description` must be concrete: subject, composition, style, colors, lighting.+6. Output ONLY one markdown code block and nothing else.++# Output Format+```json+{+ "type": "ppt_generate",+ "slides": [+ {+ "id": "slide-1",+ "title": "...",+ "content": ["...", "..."],+ "description": "visual description for image generation",+ "note": "speaker notes (optional but recommended)",+ "layout": "layout hint"+ }+ ]+}+```diff --git a/agent/ppt/system.md b/agent/ppt/system.mdindex e4ac10c..071acd7 100644--- a/agent/ppt/system.md+++ b/agent/ppt/system.md@@ -1,34 +1,42 @@-You are an expert Presentation Designer.-Your task is to generate and edit a structured JSON representation of a presentation based on user requests and any provided Context attachments.+# R - Role+You are an expert presentation slide editing agent. You edit existing slide plans precisely and follow the provided slide JSON as the source of truth.-## JSON Structure:-You must return a JSON object with a "slides" array. Each slide has a "title", "content" (bullet points), and "layout".+# I - Instructions+Apply the user's requested edits to the provided slide JSON (single slide or a slides array). When the user requests a visual change, include `imageEditInstruction` for each edited slide.+Always include a `layout` hint for each edited slide.-Example Format:-```json-{- "theme": "modern",- "slides": [- {- "id": "slide-1",- "title": "Presentation Title",- "content": [- "Point 1",- "Point 2"- ],- "note": "Speaker notes here"- }- ]-}-```+# Input+I will provide the following inputs:+- Input type: user edit request + optional Context attachments+- Input format: chat text; Context may contain one slide JSON or `{ "slides": [...] }`+- Input scope: edit only what is provided in Context unless explicitly asked otherwise++# S - Steps+Please follow these steps:+1. Read the user request and determine which slides are in scope (based on Context attachments).+2. Apply content and structure edits while preserving slide `id` and order unless explicitly requested to change them.+3. If the request includes a visual change to an existing slide image, add `imageEditInstruction` for each edited slide.+4. Output exactly one JSON payload in the required schema.++# E - End Goal+Return a valid `ppt_edit` JSON that reflects the requested edits, preserves slide identity, and triggers image edits when requested.++# N - Narrowing+Rules (CRITICAL):+1. If Context attachments include slides, treat them as authoritative:+ - If Context includes one slide JSON, edit ONLY that slide.+ - If Context includes `{ "slides": [...] }`, edit ONLY those slides unless explicitly asked to edit others.+2. Keep slide `id` unchanged and preserve slide order unless explicitly asked to reorder.+3. If the user provides a specific template or style, adapt the slide fields accordingly.+4. If the request is a visual change to an existing slide image (e.g. "change background", "add image", "change style"), you MUST include `imageEditInstruction` for each edited slide.+5. If the user asks for a visual change, do NOT reply with only text. Return JSON with `imageEditInstruction`.+6. Output ONLY one markdown code block and nothing else.+7. Language policy (CRITICAL):+ - Follow the UI language policy provided by the system messages.+ - If UI language is zh, output Simplified Chinese; if UI language is en, output English.+ - Do not mix languages unless explicitly requested.-## Rules:-1. If the user provides a specific template or style, adapt the "theme" field or descriptions accordingly.-2. If the user provides Context attachments, treat them as authoritative. If a Context attachment includes one slide JSON, only edit that slide. If it includes { "slides": [...] }, edit only those slides unless explicitly asked to edit others.-3. When editing slides, keep slide "id" unchanged and preserve slide order.-4. If the request is to visually edit an existing slide image (e.g. "change background", "add image", "change style"), you MUST include "imageEditInstruction" for each edited slide. This instruction will be sent to an image model to update the slide image.-5. CRITICAL: When the user asks for a visual change, do NOT just reply with text. You MUST return the JSON with `imageEditInstruction` to trigger the change.-6. Always output ONLY one markdown code block:+# Output Format```json{"type": "ppt_edit",@@ -38,7 +46,9 @@ Example Format:"title": "...","content": ["..."],"description": "...",- "imageEditInstruction": "..."+ "note": "optional speaker notes",+ "layout": "layout hint",+ "imageEditInstruction": "only when a visual change is requested"}]}diff --git a/package-lock.json b/package-lock.jsonindex 53a770a..e17e573 100644--- a/package-lock.json+++ b/package-lock.json@@ -8,6 +8,7 @@"name": "unified-ai-workspace","version": "0.0.0","dependencies": {+ "@jvmr/pptx-to-html": "^1.0.0","@radix-ui/react-collapsible": "^1.1.12","@radix-ui/react-context-menu": "^2.2.16","@radix-ui/react-dialog": "^1.1.15",@@ -1098,6 +1099,15 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@jvmr/pptx-to-html": {+ "version": "1.0.0",+ "resolved": "https://registry.npmmirror.com/@jvmr/pptx-to-html/-/pptx-to-html-1.0.0.tgz",+ "integrity": "sha512-08XVODrexXWT2JpDaywHMe6ucP+JK4FeXT+QbduMSi6J/175c3AynXCb89ed24w/Sx5YiPCTUlGJjCiTfYtd3g==",+ "license": "MIT",+ "dependencies": {+ "jszip": "^3.10.1"+ }+ },"node_modules/@nodelib/fs.scandir": {"version": "2.1.5","resolved": "https://registry.npmmirror.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",diff --git a/package.json b/package.jsonindex aff6a53..1daf6cd 100644--- a/package.json+++ b/package.json@@ -27,6 +27,7 @@"motion": "^12.28.1","openai": "^6.16.0","pdf-lib": "^1.17.1",+ "@jvmr/pptx-to-html": "^1.0.0","pptxgenjs": "^4.0.1","prism-react-renderer": "^2.4.1","react": "^18.3.1",diff --git a/src/App.tsx b/src/App.tsxindex d056b07..4febcae 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -7,19 +7,21 @@ import { PptWorkspace } from '@/components/workspaces/PptWorkspace';import { SettingsDialog } from '@/components/SettingsDialog';import { Layers, FileCode, Presentation, Layout } from 'lucide-react';import { cn } from '@/lib/utils';-import { DRAWIO_SYSTEM_PROMPT, CAD_SYSTEM_PROMPT, PPT_SYSTEM_PROMPT } from "@/lib/system-prompts";-import pptPreReadyConstraints from "../agent/ppt/pre-ready-constraints.md?raw";+import { DRAWIO_SYSTEM_PROMPT, CAD_SYSTEM_PROMPT, PPT_OUTLINE_EDIT_SYSTEM_PROMPT, PPT_SLIDES_EDIT_SYSTEM_PROMPT } from "@/lib/system-prompts";import { generateImage, getAIConfig, type ChatMessage } from '@/lib/ai-client';-import { Toaster } from 'sonner';+import { Toaster, toast } from 'sonner';import { LandingPage } from '@/pages/LandingPage';import { HistoryItem } from '@/components/history-dialog';import { Button } from "@/components/ui/button";+import { getUiLanguage, setUiLanguage, type UiLanguage } from "@/lib/ui-language";+import { t } from "@/lib/i18n";type WorkspaceType = 'flow' | 'cad' | 'ppt';const HISTORY_STORAGE_KEY = 'unified-ai-workspace-history';const CAD_WORKSPACE_STORAGE_KEY = 'unified-ai-workspace-cad-state-v1';const FLOW_WORKSPACE_STORAGE_KEY = 'unified-ai-workspace-flow-state-v1';+const PPT_WORKSPACE_STORAGE_KEY = "unified-ai-workspace-ppt-state-v1";class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { error: Error | null }> {state: { error: Error | null } = { error: null };@@ -43,10 +45,10 @@ class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { err</div><div className="flex items-center gap-2"><Button variant="default" onClick={() => window.location.reload()}>- 刷新页面+ {t(getUiLanguage(), "app.refresh")}</Button><Button variant="outline" onClick={() => this.setState({ error: null })}>- 尝试继续+ {t(getUiLanguage(), "app.tryContinue")}</Button></div></div>@@ -58,6 +60,18 @@ class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { err}function App() {+ const [uiLang, setUiLang] = useState<UiLanguage>(() => getUiLanguage());++ useEffect(() => {+ setUiLanguage(uiLang);+ }, [uiLang]);++ useEffect(() => {+ const onLang = () => setUiLang(getUiLanguage());+ window.addEventListener("ui-language-changed", onLang as any);+ return () => window.removeEventListener("ui-language-changed", onLang as any);+ }, []);+const initialFlowState = (() => {if (typeof window === "undefined") return null;try {@@ -118,6 +132,7 @@ function App() {});const [pptIncomingEdit, setPptIncomingEdit] = useState<{ id: string; payload: string } | null>(null);const [pptDraftSlides, setPptDraftSlides] = useState<Array<{ id: string; slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>>([]);+ const [pptResetTick, setPptResetTick] = useState(0);const cadImageObjectUrlsRef = useRef<string[]>([]);// Chat History Management (Per Workspace)@@ -199,6 +214,7 @@ function App() {const [isChatCollapsed, setIsChatCollapsed] = useState(false);const chatPanelRef = useRef<PanelImperativeHandle | null>(null);const [pptReady, setPptReady] = useState(false);+ const [pptStage, setPptStage] = useState<"outline" | "slides">("outline");const pptChatLocked = activeWorkspace === "ppt" && !pptReady;useEffect(() => {@@ -235,23 +251,23 @@ function App() {const chatUi = (() => {if (activeWorkspace === "flow") {return {- title: "流程图助手",- placeholder: "描述流程…"+ title: t(uiLang, "workspace.flow.title"),+ placeholder: t(uiLang, "workspace.flow.placeholder")};}if (activeWorkspace === "cad") {return {- title: "CAD 助手",- placeholder: "描述 CAD…"+ title: t(uiLang, "workspace.cad.title"),+ placeholder: t(uiLang, "workspace.cad.placeholder")};}if (activeWorkspace === "ppt") {return {- title: "PPT 助手",- placeholder: "描述 PPT…"+ title: t(uiLang, "workspace.ppt.title"),+ placeholder: t(uiLang, "workspace.ppt.placeholder")};}- return { title: "AI 助手", placeholder: undefined as any };+ return { title: t(uiLang, "workspace.default.title"), placeholder: undefined as any };})();const handleAddToChat = (code: string, type: 'xml' | 'python' | 'json' = 'xml', name: string = 'attachment') => {@@ -306,8 +322,7 @@ function App() {case 'flow': return DRAWIO_SYSTEM_PROMPT;case 'cad': return CAD_SYSTEM_PROMPT;case 'ppt': {- if (pptReady) return PPT_SYSTEM_PROMPT;- return `${PPT_SYSTEM_PROMPT}\n\n${pptPreReadyConstraints}`.trim();+ return pptStage === "slides" ? PPT_SLIDES_EDIT_SYSTEM_PROMPT : PPT_OUTLINE_EDIT_SYSTEM_PROMPT;}default: return DRAWIO_SYSTEM_PROMPT;}@@ -373,16 +388,144 @@ function App() {};const applyStringEdits = (source: string, edits: { search: string; replace: string }[]) => {+ if (!Array.isArray(edits) || edits.length === 0) {+ throw new Error("Empty patch edits");+ }+let out = source;+for (const e of edits) {- if (!e || typeof e.search !== "string" || typeof e.replace !== "string") continue;- if (!e.search) continue;- if (!out.includes(e.search)) continue;- out = out.replace(e.search, e.replace);+ if (!e || typeof e.search !== "string" || typeof e.replace !== "string") {+ throw new Error("Invalid patch edit item");+ }+ const search = e.search;+ const replace = e.replace;+ if (!search) {+ throw new Error("Empty search pattern in patch edit");+ }+ if (!out.includes(search)) {+ throw new Error("Search pattern not found in current content");+ }+ out = out.replace(search, replace);}+return out;};+ const validateDrawioXml = (xml: string): string | null => {+ const text = String(xml || "").trim();+ if (!text) return "XML 为空";++ let doc: Document;+ try {+ const parser = new DOMParser();+ doc = parser.parseFromString(text, "text/xml");+ } catch {+ return "XML 解析失败";+ }++ const parseError = doc.querySelector("parsererror");+ if (parseError) {+ return "XML 不合法:包含语法错误或未转义字符(例如 < > & \")";+ }++ const rootEl = doc.querySelector("mxGraphModel > root");+ if (!rootEl) {+ return "XML 结构不正确:缺少 <mxGraphModel><root>...</root></mxGraphModel>";+ }++ const allCells = Array.from(rootEl.querySelectorAll("mxCell"));+ if (allCells.length === 0) {+ return "XML 结构不正确:<root> 下没有 mxCell";+ }++ const notDirectChildren = allCells+ .filter((c) => c.parentElement !== rootEl)+ .map((c) => c.getAttribute("id") || "unknown");+ if (notDirectChildren.length > 0) {+ return `XML 结构不正确:所有 mxCell 必须是 <root> 的直接子元素(例如 ${notDirectChildren.slice(0, 3).join(", ")})`;+ }++ const nestedCells = allCells+ .filter((c) => c.parentElement?.tagName === "mxCell")+ .map((c) => c.getAttribute("id") || "unknown");+ if (nestedCells.length > 0) {+ return `XML 结构不正确:mxCell 不能嵌套(例如 ${nestedCells.slice(0, 3).join(", ")})`;+ }++ const ids = new Set<string>();+ const duplicateIds: string[] = [];+ const orphanCells: string[] = [];+ const parentRefs: Array<{ id: string; parent: string }> = [];+ const edges: Array<{ id: string; source: string | null; target: string | null }> = [];++ for (const cell of allCells) {+ const id = cell.getAttribute("id") || "";+ const parent = cell.getAttribute("parent");+ const isEdge = cell.getAttribute("edge") === "1";++ if (!id) return "XML 结构不正确:mxCell 缺少必需的 id 属性";+ if (ids.has(id)) duplicateIds.push(id);+ else ids.add(id);++ if (id !== "0") {+ if (!parent) orphanCells.push(id);+ else parentRefs.push({ id, parent });+ }++ if (isEdge) {+ edges.push({+ id,+ source: cell.getAttribute("source"),+ target: cell.getAttribute("target"),+ });+ }+ }++ if (duplicateIds.length > 0) {+ return `XML 结构不正确:mxCell id 重复(例如 ${duplicateIds.slice(0, 3).join(", ")})`;+ }+ if (orphanCells.length > 0) {+ return `XML 结构不正确:缺少 parent 属性(例如 ${orphanCells.slice(0, 3).join(", ")})`;+ }++ const cell0 = allCells.find((c) => c.getAttribute("id") === "0") || null;+ const cell1 = allCells.find((c) => c.getAttribute("id") === "1") || null;+ if (!cell0 || !cell1) {+ return 'XML 结构不正确:必须包含 <mxCell id="0"/> 与 <mxCell id="1" parent="0"/>';+ }+ if (cell0.getAttribute("parent")) {+ return 'XML 结构不正确:<mxCell id="0"/> 不应包含 parent 属性';+ }+ if (cell1.getAttribute("parent") !== "0") {+ return 'XML 结构不正确:<mxCell id="1" parent="0"/> 的 parent 必须为 "0"';+ }++ const badParents = parentRefs.filter((p) => !ids.has(p.parent));+ if (badParents.length > 0) {+ const details = badParents+ .slice(0, 3)+ .map((p) => `${p.id}(parent:${p.parent})`)+ .join(", ");+ return `XML 结构不正确:parent 引用不存在(例如 ${details})`;+ }++ const invalidConnections: string[] = [];+ for (const edge of edges) {+ if (edge.source && !ids.has(edge.source)) {+ invalidConnections.push(`${edge.id}(source:${edge.source})`);+ }+ if (edge.target && !ids.has(edge.target)) {+ invalidConnections.push(`${edge.id}(target:${edge.target})`);+ }+ }+ if (invalidConnections.length > 0) {+ return `XML 结构不正确:连线 source/target 引用不存在(例如 ${invalidConnections.slice(0, 3).join(", ")})`;+ }++ return null;+ };+if (showLanding) {return <LandingPage onStart={() => setShowLanding(false)} />;}@@ -410,7 +553,7 @@ function App() {)}><Layers className="w-4 h-4" />- 流程图+ {t(uiLang, "nav.flow")}</button><buttononClick={() => setActiveWorkspace('cad')}@@ -422,7 +565,7 @@ function App() {)}><FileCode className="w-4 h-4" />- CAD设计+ {t(uiLang, "nav.cad")}</button><buttononClick={() => setActiveWorkspace('ppt')}@@ -434,7 +577,7 @@ function App() {)}><Presentation className="w-4 h-4" />- PPT演示+ {t(uiLang, "nav.ppt")}</button></div>@@ -447,7 +590,11 @@ function App() {<div className="flex-1 overflow-hidden relative"><ErrorBoundary><ResizablePanelGroup orientation="horizontal" className="h-full" style={{ height: '100%' }}>- <ResizablePanel defaultSize={pptChatLocked ? "100%" : "68%"} minSize="30%">+ <ResizablePanel+ defaultSize={pptChatLocked ? "100%" : "68%"}+ minSize="30%"+ className={cn("transition-[flex-grow,flex-basis] duration-300 ease-in-out will-change-[flex-grow,flex-basis]")}+ ><div className="h-full w-full relative bg-muted/20">{activeWorkspace === 'flow' && (<FlowchartWorkspace@@ -481,9 +628,20 @@ function App() {)}{activeWorkspace === 'ppt' && (<PptWorkspace+ key={`ppt-${pptResetTick}`}onAddToChat={(code, name) => handleAddToChat(code, 'json', name)}onPptReadyChange={setPptReady}+ onPptStageChange={setPptStage}incomingEdit={pptIncomingEdit}+ onIncomingEditHandled={() => setPptIncomingEdit(null)}+ onResetWorkspace={() => {+ setPptIncomingEdit(null);+ setPptDraftSlides([]);+ setPptReady(false);+ setPptStage("outline");+ try { localStorage.removeItem(PPT_WORKSPACE_STORAGE_KEY); } catch {}+ setPptResetTick((x) => x + 1);+ }}/>)}</div>@@ -502,7 +660,7 @@ function App() {collapsible={!pptChatLocked}collapsedSize="56px"onResize={(panelSize) => setIsChatCollapsed(panelSize.inPixels <= 80)}- className={cn("transition-all duration-300")}+ className={cn("transition-[flex-grow,flex-basis] duration-300 ease-in-out will-change-[flex-grow,flex-basis]")}><ChatPanelkey={activeWorkspace}@@ -524,16 +682,109 @@ function App() {pptDraftSlides={activeWorkspace === "ppt" ? pptDraftSlides : []}onRemovePptDraftSlide={(id) => setPptDraftSlides(prev => prev.filter(s => s.id !== id))}onClearPptDraftSlides={() => setPptDraftSlides([])}+ onClearWorkspace={() => {+ if (activeWorkspace === "flow") {+ setGeneratedXml(undefined);+ try { localStorage.removeItem(FLOW_WORKSPACE_STORAGE_KEY); } catch {}+ }+ if (activeWorkspace === "cad") {+ setCad2dSvg(undefined);+ setCadPlan(null);+ setCadImages([]);+ setCadImagesLoading(false);+ setCadBom(null);+ setCadFocusPanel(null);+ try { localStorage.removeItem(CAD_WORKSPACE_STORAGE_KEY); } catch {}+ try { localStorage.removeItem("unified-ai-workspace-cad-renders-v1"); } catch {}+ }+ if (activeWorkspace === "ppt") {+ setPptIncomingEdit(null);+ setPptDraftSlides([]);+ setPptReady(false);+ setPptStage("outline");+ try { localStorage.removeItem(PPT_WORKSPACE_STORAGE_KEY); } catch {}+ setPptResetTick((x) => x + 1);+ }+ setVersionHistories((prev) => ({ ...prev, [activeWorkspace]: [] }));+ }}history={versionHistories[activeWorkspace]}onRestore={(item) => handleRestore(activeWorkspace, item)}onClearVersionHistory={() => {setVersionHistories(prev => ({ ...prev, [activeWorkspace]: [] }));}}cadContext={activeWorkspace === "cad" ? { plan: cadPlan, svg2d: cad2dSvg } : undefined}+ flowContext={activeWorkspace === "flow" ? { xml: generatedXml } : undefined}onCodeAction={(code, type) => {if (type === 'flow') {- setGeneratedXml(code);- addToHistory(code, 'xml');+ const raw = String(code || "");+ const trimmed = raw.trim();+ if (!trimmed) return { ok: false, retry: false, error: "Empty input" };++ if (trimmed.startsWith("{")) {+ const tryParseJson = (text: string) => {+ try {+ return JSON.parse(text);+ } catch {+ const start = text.indexOf("{");+ const end = text.lastIndexOf("}");+ if (start >= 0 && end > start) {+ try {+ return JSON.parse(text.slice(start, end + 1));+ } catch {+ }+ }+ return null;+ }+ };++ try {+ const parsed = tryParseJson(trimmed);+ if (!parsed) return;+ if (parsed?.type === "flow_patch" && parsed?.target === "drawio_xml") {+ const current = generatedXml || "";+ if (parsed?.mode === "replace" && typeof parsed.full === "string") {+ const err = validateDrawioXml(parsed.full);+ if (err) {+ toast.error(`XML 校验失败:${err}。请让 AI 修复后重试,或重新生成 mode=replace。`);+ return { ok: false, retry: true, error: err };+ }+ setGeneratedXml(parsed.full);+ addToHistory(parsed.full, "xml");+ return { ok: true };+ }+ if (parsed?.mode === "patch" && Array.isArray(parsed.edits)) {+ try {+ const next = applyStringEdits(current, parsed.edits);+ const err = validateDrawioXml(next);+ if (err) {+ toast.error(`XML 校验失败:${err}。请让 AI 改用 mode=replace,或修复后重试。`);+ return { ok: false, retry: true, error: err };+ }+ setGeneratedXml(next);+ addToHistory(next, "xml");+ return { ok: true };+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ toast.error(`补丁应用失败:${msg}。请让 AI 改用 mode=replace,或从当前 XML 精确复制 search 片段。`);+ return { ok: false, retry: true, error: msg };+ }+ }+ }+ if (typeof parsed?.type === "string") {+ return;+ }+ } catch {+ return;+ }+ }+ const err = validateDrawioXml(raw);+ if (err) {+ toast.error(`XML 校验失败:${err}。请让 AI 修复后重试。`);+ return { ok: false, retry: true, error: err };+ }+ setGeneratedXml(raw);+ addToHistory(raw, 'xml');+ return { ok: true };} else if (type === 'cad') {const raw = String(code || "");const trimmed = raw.trim();@@ -664,9 +915,14 @@ function App() {return;}if (mode === "patch" && Array.isArray(parsed.edits)) {- const next = applyStringEdits(current, parsed.edits);- setCad2dSvg(next);- addToHistory(next, 'svg');+ try {+ const next = applyStringEdits(current, parsed.edits);+ setCad2dSvg(next);+ addToHistory(next, 'svg');+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ toast.error(`补丁应用失败:${msg}。请让 AI 改用 mode=replace,或从当前内容精确复制 search 片段。`);+ }return;}}@@ -689,6 +945,7 @@ function App() {console.error("Failed to parse PPT JSON", e);}}+ return { ok: true };}}/></ResizablePanel>diff --git a/src/components/ChatInput.tsx b/src/components/ChatInput.tsxindex 5b17a77..58e4d94 100644--- a/src/components/ChatInput.tsx+++ b/src/components/ChatInput.tsx@@ -1,10 +1,12 @@-import React, { useRef, useEffect, useMemo, useState } from 'react';+import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';import { Send, FileText, ImageIcon, Settings2, Square } from 'lucide-react';import { cn } from '@/lib/utils';import { Button } from '@/components/ui/button';import { ButtonWithTooltip } from '@/components/button-with-tooltip';import { FilePreviewList } from '@/components/file-preview-list';import { useFileProcessor } from '@/lib/use-file-processor';+import { t } from "@/lib/i18n";+import { useUiLanguage } from "@/lib/use-ui-language";type RichInputSegment =| { type: "text"; text: string }@@ -51,6 +53,7 @@ export function ChatInput({clearKey,uploadMode = "all"}: ChatInputProps) {+ const uiLang = useUiLanguage();const textareaRef = useRef<HTMLTextAreaElement>(null);const richRef = useRef<HTMLDivElement>(null);const richSavedRangeRef = useRef<Range | null>(null);@@ -82,13 +85,50 @@ export function ChatInput({}};- // Auto-resize textarea+ const autoResizeTextarea = useCallback(() => {+ if (isRich) return;+ const el = textareaRef.current;+ if (!el) return;+ el.style.height = 'auto';+ el.style.height = `${Math.min(el.scrollHeight, 200)}px`;+ }, [isRich]);++ useEffect(() => {+ autoResizeTextarea();+ }, [input, isRich, placeholder, autoResizeTextarea]);+useEffect(() => {if (isRich) return;- if (!textareaRef.current) return;- textareaRef.current.style.height = 'auto';- textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 200)}px`;- }, [input]);+ const el = textareaRef.current;+ if (!el) return;++ let raf = 0;+ const schedule = () => {+ if (raf) cancelAnimationFrame(raf);+ raf = requestAnimationFrame(() => {+ raf = 0;+ autoResizeTextarea();+ });+ };++ schedule();++ if (typeof ResizeObserver !== "undefined") {+ const ro = new ResizeObserver(() => schedule());+ ro.observe(el);+ ro.observe(el.parentElement ?? el);+ return () => {+ if (raf) cancelAnimationFrame(raf);+ ro.disconnect();+ };+ }++ window.addEventListener("resize", schedule);+ return () => {+ if (raf) cancelAnimationFrame(raf);+ window.removeEventListener("resize", schedule);+ };+ }, [isRich, autoResizeTextarea]);useEffect(() => {if (focusKey === undefined) return;@@ -498,7 +538,7 @@ export function ChatInput({<div className="flex items-center gap-1">{onOpenGlobalConstraints && (<ButtonWithTooltip- tooltipContent="规则"+ tooltipContent={t(uiLang, "chat.rules")}variant="ghost"size="icon"onClick={onOpenGlobalConstraints}@@ -510,7 +550,7 @@ export function ChatInput({{(uploadMode === "all" || uploadMode === "imagesOnly") && (<ButtonWithTooltip- tooltipContent="上传图片"+ tooltipContent={t(uiLang, "chat.uploadImage")}variant="ghost"size="icon"onClick={handleImageUpload}@@ -522,7 +562,7 @@ export function ChatInput({{(uploadMode === "all" || uploadMode === "filesOnly") && (<ButtonWithTooltip- tooltipContent="上传文件"+ tooltipContent={t(uiLang, "chat.uploadFile")}variant="ghost"size="icon"onClick={handleFileUpload}@@ -538,21 +578,20 @@ export function ChatInput({const hasFiles = files.length > 0;if (isLoading) {return (- <Button- type="button"- variant="destructive"- size="sm"+ <ButtonWithTooltip+ tooltipContent={t(uiLang, "chat.stop")}+ variant="outline"+ size="icon"onClick={(e) => {e.preventDefault();onStop?.();}}disabled={!onStop}- className="h-9 px-4 rounded-xl font-medium shadow-sm"- aria-label="停止生成"+ className="h-9 w-9 rounded-xl border-red-200 bg-red-50 text-red-600 hover:bg-red-100 hover:text-red-700 dark:border-red-900/50 dark:bg-red-950/40 dark:text-red-300 dark:hover:bg-red-950/60"+ aria-label={t(uiLang, "chat.stop")}>- <Square className="h-4 w-4 fill-current mr-1.5" />- 停止- </Button>+ <Square className="h-4 w-4 fill-current" />+ </ButtonWithTooltip>);}return (@@ -568,7 +607,7 @@ export function ChatInput({aria-label="发送"><Send className="h-4 w-4 mr-1.5" />- 发送+ {t(uiLang, "chat.send")}</Button>);})()}diff --git a/src/components/ChatMessageDisplay.tsx b/src/components/ChatMessageDisplay.tsxindex 827138e..588dc1c 100644--- a/src/components/ChatMessageDisplay.tsx+++ b/src/components/ChatMessageDisplay.tsx@@ -38,6 +38,7 @@ import remarkGfm from 'remark-gfm';import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";import { ScrollArea } from "@/components/ui/scroll-area";import { CodeBlock } from "@/components/ui/code-block";+import { useUiLanguage } from "@/lib/use-ui-language";import { cn } from "@/lib/utils";// Types@@ -212,6 +213,8 @@ export function ChatMessageDisplay({status = "idle",onDisplayChart}: ChatMessageDisplayProps) {+ const uiLang = useUiLanguage();+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);const scrollRootRef = useRef<HTMLDivElement>(null);const messagesEndRef = useRef<HTMLDivElement>(null);const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);@@ -227,8 +230,25 @@ export function ChatMessageDisplay({await navigator.clipboard.writeText(text);setCopiedMessageId(messageId);setTimeout(() => setCopiedMessageId(null), 2000);- } catch (err) {- console.error("Failed to copy:", err);+ } catch (_err) {+ const textarea = document.createElement("textarea");+ textarea.value = text;+ textarea.style.position = "fixed";+ textarea.style.left = "-9999px";+ textarea.style.opacity = "0";+ document.body.appendChild(textarea);++ try {+ textarea.select();+ const ok = document.execCommand("copy");+ if (!ok) throw new Error("Copy command failed");+ setCopiedMessageId(messageId);+ setTimeout(() => setCopiedMessageId(null), 2000);+ } catch (fallbackErr) {+ console.error("Failed to copy message:", fallbackErr);+ } finally {+ document.body.removeChild(textarea);+ }}};@@ -313,8 +333,12 @@ export function ChatMessageDisplay({<div className="py-5 px-5 space-y-5">{messages.map((message, messageIndex) => {const userMessageText = message.role === "user" ? getMessageTextContent(message) : "";- const isLastAssistantMessage = message.role === "assistant" && messageIndex === messages.length - 1;- const isLastUserMessage = message.role === "user" && messageIndex === messages.length - 1;+ const isLastAssistantMessage =+ message.role === "assistant" &&+ (messageIndex === messages.length - 1 || messages.slice(messageIndex + 1).every((m) => m.role !== "assistant"));+ const isLastUserMessage =+ message.role === "user" &&+ (messageIndex === messages.length - 1 || messages.slice(messageIndex + 1).every((m) => m.role !== "user"));const isEditing = editingMessageId === message.id;return (@@ -330,21 +354,21 @@ export function ChatMessageDisplay({<div className="w-5 h-5 rounded-full bg-blue-600 flex items-center justify-center"><Cpu className="w-3 h-3 text-white" /></div>- <span className="text-xs font-medium text-muted-foreground">AI 助手</span>+ <span className="text-xs font-medium text-muted-foreground">{tr("AI 助手", "AI Assistant")}</span></>) : (<>- <span className="text-xs font-medium text-muted-foreground">You</span>+ <span className="text-xs font-medium text-muted-foreground">{tr("你", "You")}</span></>)}</div>{/* Content Bubble */}<div className={cn(- "relative px-4 py-3 text-sm leading-relaxed shadow-sm break-words overflow-hidden",+ "relative px-4 py-3 text-sm leading-relaxed break-words overflow-hidden border border-border/50 bg-background/70 backdrop-blur-md shadow-sm transition-shadow hover:shadow-md",message.role === "user"- ? "bg-white dark:bg-zinc-800 border border-border/40 text-foreground rounded-2xl rounded-tr-sm w-full"- : "bg-white dark:bg-zinc-800 border border-border/40 text-foreground rounded-2xl rounded-tl-sm w-full"+ ? "text-foreground rounded-2xl rounded-tr-sm w-full"+ : "text-foreground rounded-2xl rounded-tl-sm w-full")}>{/* Reasoning Parts */}@@ -390,7 +414,7 @@ export function ChatMessageDisplay({onClick={() => setEditingMessageId(null)}className="px-3 py-1 text-xs rounded bg-muted hover:bg-muted/80 text-foreground">- 取消+ {tr("取消", "Cancel")}</button><buttononClick={() => {@@ -401,7 +425,7 @@ export function ChatMessageDisplay({}}className="px-3 py-1 text-xs rounded bg-primary hover:bg-primary/90 text-primary-foreground">- 重新发送+ {tr("重新发送", "Resend")}</button></div></div>@@ -444,7 +468,7 @@ export function ChatMessageDisplay({)}><PIcon className="h-3.5 w-3.5 text-red-600 dark:text-red-200 mr-1" />- {t.title ? `第 ${t.n} 页:${t.title}` : `第 ${t.n} 页`}+ {t.title ? tr(`第 ${t.n} 页:${t.title}`, `Slide ${t.n}: ${t.title}`) : tr(`第 ${t.n} 页`, `Slide ${t.n}`)}</span>))}</div>@@ -492,12 +516,12 @@ export function ChatMessageDisplay({>{parts.map((p, j) => {if (p.type === "text") return <span key={`${idx}-t-${j}`}>{p.text}</span>;- const label = p.title ? `第 ${p.n} 页:${p.title}` : `第 ${p.n} 页`;+ const label = p.title ? tr(`第 ${p.n} 页:${p.title}`, `Slide ${p.n}: ${p.title}`) : tr(`第 ${p.n} 页`, `Slide ${p.n}`);return (<spankey={`${idx}-ppt-${j}`}className="mx-1 inline-flex items-center gap-1.5 rounded-full border border-red-200 bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200 align-middle"- title={`幻灯片 · ${label}`}+ title={tr(`幻灯片 · ${label}`, `Slide · ${label}`)}><PIcon className="h-3.5 w-3.5 text-red-600 dark:text-red-200" />{label}@@ -594,50 +618,60 @@ export function ChatMessageDisplay({{isLastAssistantMessage && status === "streaming" && (<div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin" />- <span>Thinking...</span>+ <span>{tr("思考中...", "Thinking...")}</span></div>)}</div>{/* Actions */}- <div className="flex items-center gap-1 mt-1 opacity-0 group-hover:opacity-100 transition-opacity px-1">- {message.role === "user" && !isEditing && (+ <div className="flex items-center gap-1 mt-2 px-1">+ {message.role === "user" && !isEditing && userMessageText && (<>+ {onEditMessage && isLastUserMessage && (+ <button+ type="button"+ onClick={() => {+ setEditingMessageId(message.id);+ setEditText(getUserOriginalText(message));+ }}+ className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors"+ title={tr("编辑", "Edit")}+ >+ <Pencil className="h-3.5 w-3.5" />+ </button>+ )}<button- onClick={() => {- setEditingMessageId(message.id);- setEditText(getUserOriginalText(message));- }}- className="p-1 rounded hover:bg-muted text-muted-foreground"- title="Edit"- >- <Pencil className="h-3 w-3" />- </button>- <button+ type="button"onClick={() => copyMessageToClipboard(message.id, getUserOriginalText(message))}- className="p-1 rounded hover:bg-muted text-muted-foreground"- title="Copy"+ className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors"+ title={tr("复制", "Copy")}>- {copiedMessageId === message.id ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3" />}+ {copiedMessageId === message.id ? <Check className="h-3.5 w-3.5 text-green-500" /> : <Copy className="h-3.5 w-3.5" />}</button></>)}{message.role === "assistant" && (<><button+ type="button"onClick={() => copyMessageToClipboard(message.id, getMessageTextContent(message))}- className="p-1 rounded hover:bg-muted text-muted-foreground"- title="Copy"+ className={`p-1.5 rounded-lg transition-colors ${+ copiedMessageId === message.id+ ? "text-green-600 bg-green-100 dark:bg-green-950/30"+ : "text-muted-foreground/60 hover:text-foreground hover:bg-muted"+ }`}+ title={tr("复制", "Copy")}>- {copiedMessageId === message.id ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3" />}+ {copiedMessageId === message.id ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}</button>- {onRegenerate && (+ {onRegenerate && isLastAssistantMessage && (<button+ type="button"onClick={() => onRegenerate(messageIndex)}- className="p-1 rounded hover:bg-muted text-muted-foreground"- title="Regenerate"+ className="p-1.5 rounded-lg text-muted-foreground/60 hover:text-foreground hover:bg-muted transition-colors"+ title={tr("重新生成", "Regenerate")}>- <RotateCcw className="h-3 w-3" />+ <RotateCcw className="h-3.5 w-3.5" /></button>)}</>@@ -657,7 +691,7 @@ export function ChatMessageDisplay({className="absolute bottom-4 right-4 z-20 inline-flex items-center gap-1 rounded-full border border-border bg-background/90 backdrop-blur px-3 py-1.5 text-xs text-foreground shadow-md hover:bg-background"><ChevronDown className="w-3.5 h-3.5" />- 回到底部+ {tr("回到底部", "Back to bottom")}</button>)}</div>diff --git a/src/components/ChatPanel.tsx b/src/components/ChatPanel.tsxindex 32ae0b1..9c1750b 100644--- a/src/components/ChatPanel.tsx+++ b/src/components/ChatPanel.tsx@@ -1,5 +1,5 @@import React, { useState, useRef, useEffect } from 'react';-import { Bot, Trash2, History, Settings2, SidebarClose, SidebarOpen, Plus } from 'lucide-react';+import { Bot, Trash2, History, Settings2, PanelRightClose, PanelRightOpen, Plus } from 'lucide-react';import { cn } from '@/lib/utils';import { streamChatMessage, ChatMessage, getAIConfig } from '@/lib/ai-client';import { DRAWIO_SYSTEM_PROMPT } from '@/lib/system-prompts';@@ -11,6 +11,11 @@ import { HistoryDialog, HistoryItem } from '@/components/history-dialog';import { ResetWarningModal } from '@/components/reset-warning-modal';import { useFileProcessor } from '@/lib/use-file-processor';import { buildCadBomMessages, buildCadImagesMessages, buildCadTasksSystemContent } from '@/lib/cad-tasks';+import { CAD_PLAN_AGENT_PROMPT, CAD_SVG_GENERATE_AGENT_PROMPT, CAD_SVG_PATCH_AGENT_PROMPT } from '@/lib/cad-agents';+import flowPatchAgentPrompt from "../../agent/flow/patch.md?raw";+import flowReplaceAgentPrompt from "../../agent/flow/replace.md?raw";+import { t } from "@/lib/i18n";+import { useUiLanguage } from "@/lib/use-ui-language";interface Attachment {id: string;@@ -19,6 +24,9 @@ interface Attachment {name: string;}+type CodeActionResult = { ok: boolean; retry?: boolean; error?: string };+type MaybePromise<T> = T | Promise<T>;+interface ChatPanelProps {className?: string;attachments?: Attachment[];@@ -26,7 +34,7 @@ interface ChatPanelProps {pptDraftSlides?: Array<{ id: string; slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>;onRemovePptDraftSlide?: (id: string) => void;onClearPptDraftSlides?: () => void;- onCodeAction?: (code: string, type: 'flow' | 'cad' | 'ppt') => void;+ onCodeAction?: (code: string, type: 'flow' | 'cad' | 'ppt') => MaybePromise<void | CodeActionResult>;systemPrompt?: string;initialMessages?: ChatMessage[];onMessagesChange?: (messages: ChatMessage[]) => void;@@ -48,6 +56,10 @@ interface ChatPanelProps {plan?: any;svg2d?: string;};+ flowContext?: {+ xml?: string;+ };+ onClearWorkspace?: () => void;}const STORAGE_KEY_PREFIX = 'chat_history_v2_';@@ -84,8 +96,12 @@ export function ChatPanel({onRestore,onClearVersionHistory,onClearAttachments,- cadContext+ cadContext,+ flowContext,+ onClearWorkspace}: ChatPanelProps) {+ const uiLang = useUiLanguage();+ const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);// Persistence keyconst storageKey = `${STORAGE_KEY_PREFIX}${workspaceId}`;@@ -101,7 +117,7 @@ export function ChatPanel({}}return initialMessages.length > 0 ? initialMessages : [- { role: 'assistant', content: '你好!我是你的 AI 助手。请告诉我你的需求。' }+ { role: 'assistant', content: t(uiLang, "chat.hello") }];});@@ -113,6 +129,8 @@ export function ChatPanel({const [showGlobalConstraints, setShowGlobalConstraints] = useState(false);const [showHistory, setShowHistory] = useState(false);const [showResetWarning, setShowResetWarning] = useState(false);+ const flowAutoRetryCountRef = useRef(0);+ const MAX_FLOW_AUTO_RETRY = 3;const [files, setFiles] = useState<File[]>([]);const abortControllerRef = useRef<AbortController | null>(null);@@ -128,7 +146,11 @@ export function ChatPanel({const getPptLabel = (slideId: string, title: string) => {const m = String(slideId || "").match(/(\d+)/);const n = m ? Number(m[1]) : NaN;- if (!Number.isNaN(n)) return title ? `第 ${n} 页:${title}` : `第 ${n} 页`;+ if (!Number.isNaN(n)) {+ return uiLang === "zh"+ ? (title ? `第 ${n} 页:${title}` : `第 ${n} 页`)+ : (title ? `Slide ${n}: ${title}` : `Slide ${n}`);+ }return title || slideId;};@@ -214,7 +236,10 @@ export function ChatPanel({const sanitizeAssistantContentForDisplay = (content: string) => {if (workspaceId !== "cad") return content;if (!content) return content;- let next = content.replace(/```(?:python|py|python3)\s*[\s\S]*?```/g, "(已在后台推导完成)");+ let next = content.replace(+ /```(?:python|py|python3)\s*[\s\S]*?```/g,+ trText("(已在后台推导完成)", "(Processed in the background)")+ );next = next.split("\n").filter((line) => !/freecad/i.test(line))@@ -224,7 +249,7 @@ export function ChatPanel({const text = String(inner || "").trim();if (!text) return full;if (text.includes('"type"') && text.includes('"cad_images"')) {- return "(已提交装修图生成任务)";+ return trText("(已提交装修图生成任务)", "(CAD drawing generation task submitted)");}if (text.includes('"type"') && text.includes('"cad_plan"')) {try {@@ -238,14 +263,17 @@ export function ChatPanel({const rooms = Array.isArray(plan?.rooms) ? plan.rooms : [];const lines: string[] = [];- if (summary) lines.push(`方案概述:${summary}`);- if (style) lines.push(`风格:${style}`);- if (rooms.length > 0) lines.push(`空间:${rooms.map((r: any) => String(r?.name || r?.type || "")).filter(Boolean).join("、")}`);- if (assumptions.length > 0) lines.push(`假设:${assumptions.join(";")}`);- if (constraints.length > 0) lines.push(`约束:${constraints.join(";")}`);- return lines.length > 0 ? lines.join("\n") : "(已生成方案)";+ if (summary) lines.push(trText(`方案概述:${summary}`, `Summary: ${summary}`));+ if (style) lines.push(trText(`风格:${style}`, `Style: ${style}`));+ if (rooms.length > 0) {+ const roomNames = rooms.map((r: any) => String(r?.name || r?.type || "")).filter(Boolean);+ lines.push(trText(`空间:${roomNames.join("、")}`, `Spaces: ${roomNames.join(", ")}`));+ }+ if (assumptions.length > 0) lines.push(trText(`假设:${assumptions.join(";")}`, `Assumptions: ${assumptions.join("; ")}`));+ if (constraints.length > 0) lines.push(trText(`约束:${constraints.join(";")}`, `Constraints: ${constraints.join("; ")}`));+ return lines.length > 0 ? lines.join("\n") : trText("(已生成方案)", "(Plan generated)");} catch {- return "(已生成方案)";+ return trText("(已生成方案)", "(Plan generated)");}}return full;@@ -304,8 +332,21 @@ export function ChatPanel({}, [messages, storageKey, onMessagesChange]);const clearHistory = () => {+ abortControllerRef.current?.abort();+ abortControllerRef.current = null;+ setIsLoading(false);+ setInput('');+ setPptInputSegments([{ type: "text", text: "" }]);+ setFiles([]);+ onClearAttachments?.();+ onClearPptDraftSlides?.();+ onClearWorkspace?.();+ try {+ localStorage.removeItem(storageKey);+ } catch {+ }const newMsgs: ChatMessage[] = [- { role: 'assistant', content: '你好!对话记录已清空。' }+ { role: 'assistant', content: t(uiLang, "chat.cleared") }];setMessages(newMsgs);setShowResetWarning(false);@@ -320,7 +361,7 @@ export function ChatPanel({setFiles([]);onClearAttachments?.();const newMsgs: ChatMessage[] = [- { role: 'assistant', content: '你好!新对话已开始。请告诉我你的需求。' }+ { role: 'assistant', content: t(uiLang, "chat.newChat") }];setMessages(newMsgs);try {@@ -329,6 +370,113 @@ export function ChatPanel({}};+ const runCodeAction = async (code: string, type: 'flow' | 'cad' | 'ppt') => {+ const result = await Promise.resolve(onCodeAction?.(code, type));+ if (!result || typeof result !== "object") return { ok: true } as CodeActionResult;+ const r = result as any;+ if (typeof r.ok === "boolean") {+ return { ok: r.ok, retry: !!r.retry, error: typeof r.error === "string" ? r.error : undefined } as CodeActionResult;+ }+ return { ok: true } as CodeActionResult;+ };++ const handleAssistantResponse = async (fullResponse: string) => {+ if (!fullResponse) return { flowPatchFound: false, flowRetryError: null as string | null };++ const pyMatch = fullResponse.match(/```python\n([\s\S]*?)\n```/);+ if (pyMatch && pyMatch[1] && workspaceId !== "cad") {+ await runCodeAction(pyMatch[1], 'cad');+ }++ if (workspaceId === "cad") {+ const jsMatch = fullResponse.match(/```(javascript|js)\n([\s\S]*?)\n```/);+ if (jsMatch && jsMatch[2]) {+ await runCodeAction(jsMatch[2], 'cad');+ }+ }++ const svgMatch = fullResponse.match(/```svg\n([\s\S]*?)\n```/);+ if (svgMatch && svgMatch[1]) {+ await runCodeAction(svgMatch[1], 'cad');+ }++ let flowPatchFound = false;+ let flowRetryError: string | null = null;++ const jsonRegex = /```json\s*([\s\S]*?)```/g;+ let m: RegExpExecArray | null;+ while ((m = jsonRegex.exec(fullResponse))) {+ const jsonText = String(m[1] || "").trim();+ if (!jsonText) continue;++ if (workspaceId === 'ppt') {+ try {+ const parsed = JSON.parse(jsonText);+ if (lastUploadedImagesRef.current.length > 0) {+ parsed.uploadedImages = lastUploadedImagesRef.current;+ await runCodeAction(JSON.stringify(parsed), 'ppt');+ } else {+ await runCodeAction(jsonText, 'ppt');+ }+ } catch {+ await runCodeAction(jsonText, 'ppt');+ }+ continue;+ }++ if (workspaceId === 'flow') {+ try {+ const parsed = JSON.parse(jsonText);+ if (parsed?.type === "flow_patch") flowPatchFound = true;+ } catch {+ }+ const r = await runCodeAction(jsonText, 'flow');+ if (!r.ok && r.retry) {+ flowRetryError = r.error || "Unknown error";+ }+ continue;+ }++ await runCodeAction(jsonText, workspaceId === "cad" ? 'cad' : 'ppt');+ }++ if (workspaceId === "flow" && !flowPatchFound) {+ const xmlMatch = fullResponse.match(/```xml\n([\s\S]*?)\n```/);+ if (xmlMatch && xmlMatch[1]) {+ const r = await runCodeAction(xmlMatch[1], 'flow');+ if (!r.ok && r.retry) {+ flowRetryError = r.error || "Unknown error";+ }+ }+ }++ return { flowPatchFound, flowRetryError };+ };++ const buildFlowRetryPrompt = (errorText: string, forceReplace: boolean) => {+ const err = String(errorText || "").slice(0, 600);+ if (uiLang === "en") {+ return [+ `The previous flow_patch could not be applied to the current diagram. Reason: ${err}`,+ "",+ "Please retry and strictly follow:",+ "- Output exactly one ```json``` code block with type=flow_patch",+ forceReplace+ ? "- This time you MUST use mode=replace and output the full <mxGraphModel>...</mxGraphModel> (do not output patch)"+ : "- If the patch cannot precisely match the Current diagram XML, use mode=replace and output the full <mxGraphModel>...</mxGraphModel>",+ ].join("\n");+ }+ return [+ `刚才的 flow_patch 无法应用到当前图,原因:${err}`,+ "",+ "请重试并严格遵守:",+ "- 只能输出一个 ```json``` 代码块,type=flow_patch",+ forceReplace+ ? "- 本次必须直接用 mode=replace 输出完整 <mxGraphModel>...</mxGraphModel>(不要输出 patch)"+ : "- 如果 patch 不能精确命中 Current diagram XML,请直接用 mode=replace 输出完整 <mxGraphModel>...</mxGraphModel>",+ ].join("\n");+ };+const handleSend = async () => {const isPpt = workspaceId === "ppt";const rawInput = isPpt@@ -337,6 +485,7 @@ export function ChatPanel({.join(""): input;if ((!rawInput.trim() && files.length === 0 && attachments.length === 0 && pptDraftSlides.length === 0) || isLoading) return;+ flowAutoRetryCountRef.current = 0;const normalizedInput = rawInput.trim();const referencedPptSlideIds = isPpt@@ -390,6 +539,23 @@ export function ChatPanel({try {let content = "";if (isPdfFile(file)) {+ try {+ const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/lib/pdf-utils");+ const objectUrl = URL.createObjectURL(file);+ try {+ const pdf = await getPdfDocumentFromUrl(objectUrl);+ const canvas = document.createElement("canvas");+ await renderPdfPageToCanvas({ pdf, pageNumber: 1, canvas, targetWidth: 520 });+ const previewUrl = canvas.toDataURL("image/png");+ if (previewUrl && previewUrl.startsWith("data:image")) {+ currentUploadedImageItems.push({ name: file.name, url: previewUrl });+ }+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+ } catch (e) {+ console.error("Failed to render PDF preview", file.name, e);+ }content = await extractPdfText(file);} else {content = await extractTextFileContent(file);@@ -428,11 +594,30 @@ export function ChatPanel({.join("\n\n"): "";+ const flowContextText =+ workspaceId === "flow" && typeof flowContext?.xml === "string" && flowContext.xml.trim()+ ? `Current diagram XML:\n\n\`\`\`xml\n${flowContext.xml}\n\`\`\``+ : "";++ const cadContextText =+ workspaceId === "cad"+ ? [+ cadContext?.plan ? `Current CAD plan:\n\n\`\`\`json\n${JSON.stringify(cadContext.plan, null, 2)}\n\`\`\`` : "",+ typeof cadContext?.svg2d === "string" && cadContext.svg2d.trim()+ ? `Current 2D SVG:\n\n\`\`\`svg\n${cadContext.svg2d}\n\`\`\``+ : "",+ ]+ .filter(Boolean)+ .join("\n\n")+ : "";+const promptParts = [rawInput,fileTexts.length > 0 ? fileTexts.join("\n\n") : "",pptDraftContextText,- contextAttachmentsText+ contextAttachmentsText,+ flowContextText,+ cadContextText].filter(Boolean);const promptContent = promptParts.join("\n\n");lastUploadedImagesRef.current = currentUploadedImages;@@ -458,7 +643,7 @@ export function ChatPanel({setFiles([]);if (workspaceId === "ppt") onClearPptDraftSlides?.();- if (workspaceId === "cad" && mode === "text" && /确认\s*2d|满意|生成\s*装修|生成\s*物料|cad_ready_for_export/i.test(normalizedInput)) {+ if (workspaceId === "cad" && mode === "text" && /(cad_ready_for_export|一键\s*(出图|生成)|one[- ]?click)/i.test(normalizedInput)) {const svg2d = cadContext?.svg2d || "";const planJson = cadContext?.plan ? JSON.stringify(cadContext.plan) : "";@@ -480,7 +665,7 @@ export function ChatPanel({const constraintsKey = workspaceId ? `${STORAGE_GLOBAL_CONSTRAINTS_KEY}-${workspaceId}` : STORAGE_GLOBAL_CONSTRAINTS_KEY;const globalConstraints = typeof window !== 'undefined' ? localStorage.getItem(constraintsKey) || '' : '';const globalSystemPrompt = config.systemPrompt || '';- const systemContent = buildCadTasksSystemContent({ systemPrompt, globalSystemPrompt, globalConstraints });+ const systemContent = buildCadTasksSystemContent({ globalSystemPrompt, globalConstraints });const bomMessages: ChatMessage[] = buildCadBomMessages({ systemContent, planJson, svg2d });const imagesMessages: ChatMessage[] = buildCadImagesMessages({ systemContent, planJson, svg2d });@@ -526,7 +711,8 @@ export function ChatPanel({setMessages(prev => {const last = prev[prev.length - 1];if (last?.role !== 'assistant') return prev;- const next = last.content ? `${last.content}\n\n(已中断)` : "(已中断)";+ const abortedText = trText("(已中断)", "(Aborted)");+ const next = last.content ? `${last.content}\n\n${abortedText}` : abortedText;return [...prev.slice(0, -1), { role: 'assistant', content: next }];});}@@ -569,55 +755,315 @@ export function ChatPanel({}, chatModel, controller.signal);updater.flush();- if (fullResponse) {- // Match XML- const xmlMatch = fullResponse.match(/```xml\n([\s\S]*?)\n```/);- if (xmlMatch && xmlMatch[1]) {- const xml = xmlMatch[1];- onCodeAction?.(xml, 'flow');- }+ let flowRoutedBaseMessages: ChatMessage[] | null = null;+ let flowSelectedAgent: "patch" | "replace" | null = null;++ if (fullResponse && workspaceId === "flow") {+ const resolveFlowAgentFromRouteText = (text: string): "patch" | "replace" | null => {+ const trimmed = String(text || "").trim();+ if (!trimmed) return null;++ let content = trimmed;+ const fenceMatch = content.match(/```[a-zA-Z]*\s*([\s\S]*?)```/);+ if (fenceMatch && fenceMatch[1]) content = fenceMatch[1].trim();+ content = content.replace(/\s+/g, "");++ if (!/^[1-2]$/.test(content)) return null;+ return content === "1" ? "patch" : "replace";+ };++ const agentFromText = resolveFlowAgentFromRouteText(fullResponse);+ if (agentFromText) {+ flowSelectedAgent = agentFromText;- // Match Python (not used by CAD; CAD uses background agents)- const pyMatch = fullResponse.match(/```python\n([\s\S]*?)\n```/);- if (pyMatch && pyMatch[1] && workspaceId !== "cad") {- onCodeAction?.(pyMatch[1], 'cad');+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ if (last?.role === "assistant") return [...prev.slice(0, -1), { role: "assistant", content: "" }];+ return prev;+ });++ const agentPrompt = flowSelectedAgent === "patch" ? flowPatchAgentPrompt : flowReplaceAgentPrompt;+ const routedSystemContent = [agentPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join("\n\n");+ const routedMessages: ChatMessage[] = [+ { role: "system", content: routedSystemContent },+ { role: "user", content: promptContent }+ ];++ let routedFull = "";+ const routedUpdater = createThrottledAssistantUpdater();+ await streamChatMessage(routedMessages, (chunk) => {+ routedFull = chunk;+ routedUpdater.push(chunk);+ }, chatModel, controller.signal);+ routedUpdater.flush();++ flowRoutedBaseMessages = routedMessages;+ fullResponse = routedFull;}+ }- if (workspaceId === "cad") {- const jsMatch = fullResponse.match(/```(javascript|js)\n([\s\S]*?)\n```/);- if (jsMatch && jsMatch[2]) {- onCodeAction?.(jsMatch[2], 'cad');+ if (fullResponse && workspaceId === "cad") {+ let route: { agent?: string } | null = null;++ const resolveCadAgentFromRouteText = (text: string): string | null => {+ const trimmed = String(text || "").trim();+ if (!trimmed) return null;++ let content = trimmed;+ const fenceMatch = content.match(/```[a-zA-Z]*\s*([\s\S]*?)```/);+ if (fenceMatch && fenceMatch[1]) content = fenceMatch[1].trim();+ content = content.replace(/\s+/g, "");++ if (!/^[1-5]$/.test(content)) return null;++ return content === "1"+ ? "cad_plan_agent"+ : content === "2"+ ? "cad_svg_generate_agent"+ : content === "3"+ ? "cad_svg_patch_agent"+ : content === "4"+ ? "cad_bom_agent"+ : "cad_images_agent";+ };++ const routeJsonRegex = /```json\s*([\s\S]*?)```/g;+ let rm: RegExpExecArray | null;+ while ((rm = routeJsonRegex.exec(fullResponse))) {+ const jsonText = String(rm[1] || "").trim();+ if (!jsonText) continue;+ try {+ const parsed = JSON.parse(jsonText);+ if (parsed?.type === "cad_route" && typeof parsed?.agent === "string") {+ route = { agent: parsed.agent };+ break;+ }+ } catch {}}-- // Match SVG (for CAD)- const svgMatch = fullResponse.match(/```svg\n([\s\S]*?)\n```/);- if (svgMatch && svgMatch[1]) {- onCodeAction?.(svgMatch[1], 'cad');++ if (!route?.agent) {+ const agentFromText = resolveCadAgentFromRouteText(fullResponse);+ if (agentFromText) route = { agent: agentFromText };}- // Match JSON (PPT/CAD)- const jsonRegex = /```json\s*([\s\S]*?)```/g;- let m: RegExpExecArray | null;- while ((m = jsonRegex.exec(fullResponse))) {- const jsonText = String(m[1] || "").trim();- if (!jsonText) continue;-- if (workspaceId === 'ppt') {- try {- const parsed = JSON.parse(jsonText);- if (lastUploadedImagesRef.current.length > 0) {- parsed.uploadedImages = lastUploadedImagesRef.current;- onCodeAction?.(JSON.stringify(parsed), 'ppt');- } else {- onCodeAction?.(jsonText, 'ppt');- }- } catch {- onCodeAction?.(jsonText, 'ppt');+ if (route?.agent) {+ setMessages((prev) => {+ const last = prev[prev.length - 1];+ if (last?.role === "assistant") return [...prev.slice(0, -1), { role: "assistant", content: "" }];+ return prev;+ });++ const buildCadNextStepGuide = (args: {+ agent: string;+ beforeHasPlan: boolean;+ beforeHasSvg2d: boolean;+ producedHasPlan: boolean;+ producedHasSvg2d: boolean;+ producedHasImages: boolean;+ producedHasBom: boolean;+ }) => {+ if (args.producedHasPlan && !args.beforeHasPlan) {+ return trText(+ "需求方案已输出。若满意,回复“生成2D平面图”;若不满意,请直接说需要修改的点。",+ 'The plan is ready. If it looks good, reply "Generate 2D floorplan". If not, tell me what to change.'+ );+ }+ if (args.producedHasSvg2d && !args.beforeHasSvg2d) {+ return trText(+ "2D 平面图已生成。若需要微调请直接说明;若满意,回复“生成装修图”。",+ 'The 2D floorplan is generated. Tell me edits if needed; otherwise reply "Generate renders".'+ );+ }+ if (args.producedHasImages) {+ return trText(+ "装修图已开始生成/已更新。下一步回复“生成物料清单(BOM)”。如需改风格/材质/预算,也可以先说修改点再重新出图。",+ "Renders are being generated/updated. Next, reply \"Generate BOM\". If you want to change style/material/budget, tell me first and I’ll regenerate."+ );+ }+ if (args.producedHasBom) {+ return trText(+ "物料清单已生成。你可以继续优化方案/2D/风格,或直接导出(左上角 CSV / SVG / PDF)。",+ "BOM is generated. You can refine the plan/2D/style, or export (CSV / SVG / PDF in the top-left)."+ );+ }+ if (args.agent === "cad_svg_patch_agent") {+ return trText(+ "已按你的要求修改 2D。若满意,回复“生成装修图”;否则继续描述需要怎么改。",+ '2D has been patched. If OK, reply "Generate renders"; otherwise describe further edits.'+ );+ }+ return "";+ };++ const runCadTaskMessages = async (taskMessages: ChatMessage[]) => {+ let taskFull = "";+ const taskUpdater = createThrottledAssistantUpdater();+ await streamChatMessage(taskMessages, (chunk) => {+ taskFull = chunk;+ taskUpdater.push(chunk);+ }, chatModel, controller.signal);+ taskUpdater.flush();+ return taskFull;+ };++ const emitCadJson = (text: string) => {+ const match = text.match(/```json\s*([\s\S]*?)```/);+ const jsonText = match ? match[1].trim() : text.trim();+ if (!jsonText.startsWith("{")) return;+ onCodeAction?.(jsonText, "cad");+ };++ const agent = String(route.agent || "").trim();+ const beforeHasPlan = !!cadContext?.plan;+ const beforeHasSvg2d = !!(typeof cadContext?.svg2d === "string" && cadContext.svg2d.trim());+ const planJson = cadContext?.plan ? JSON.stringify(cadContext.plan) : "";+ const svg2d = cadContext?.svg2d || "";++ if (agent === "cad_bom_agent" || agent === "cad_images_agent") {+ const systemContentTasks = buildCadTasksSystemContent({ globalSystemPrompt, globalConstraints });+ const taskMessages =+ agent === "cad_bom_agent"+ ? buildCadBomMessages({ systemContent: systemContentTasks, planJson, svg2d })+ : buildCadImagesMessages({ systemContent: systemContentTasks, planJson, svg2d });++ const taskFull = await runCadTaskMessages(taskMessages);+ if (taskFull) {+ emitCadJson(taskFull);+ if (agent === "cad_bom_agent") {+ const fallback = parseMarkdownBomTable(taskFull);+ if (fallback) onCodeAction?.(JSON.stringify(fallback), "cad");}- } else {- onCodeAction?.(jsonText, workspaceId === "cad" ? 'cad' : 'ppt');+ const producedHasPlan = /"type"\s*:\s*"cad_plan"/.test(taskFull);+ const producedHasSvg2d = /```svg[\s\S]*?```/.test(taskFull);+ const producedHasImages = /"type"\s*:\s*"cad_images"/.test(taskFull);+ const producedHasBom = /"type"\s*:\s*"cad_bom"/.test(taskFull);+ const guide = buildCadNextStepGuide({+ agent,+ beforeHasPlan,+ beforeHasSvg2d,+ producedHasPlan,+ producedHasSvg2d,+ producedHasImages,+ producedHasBom,+ });+ if (guide) updateLastAssistant(`${taskFull}\n\n${guide}`);+ }+ return;+ }++ const agentPrompt =+ agent === "cad_plan_agent"+ ? CAD_PLAN_AGENT_PROMPT+ : agent === "cad_svg_generate_agent"+ ? CAD_SVG_GENERATE_AGENT_PROMPT+ : agent === "cad_svg_patch_agent"+ ? CAD_SVG_PATCH_AGENT_PROMPT+ : "";++ if (!agentPrompt) {+ updateLastAssistant(trText(`未识别的 CAD 子智能体:${agent}`, `Unrecognized CAD sub-agent: ${agent}`));+ return;}++ const routedSystemContent = [agentPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join("\n\n");+ const routedMessages: ChatMessage[] = [+ { role: "system", content: routedSystemContent },+ { role: "user", content: promptContent }+ ];++ let routedFull = "";+ const routedUpdater = createThrottledAssistantUpdater();+ await streamChatMessage(routedMessages, (chunk) => {+ routedFull = chunk;+ routedUpdater.push(chunk);+ }, chatModel, controller.signal);+ routedUpdater.flush();++ if (routedFull) {+ const svgMatch = routedFull.match(/```svg\n([\s\S]*?)\n```/);+ if (svgMatch && svgMatch[1]) onCodeAction?.(svgMatch[1], "cad");++ const jsonRegex = /```json\s*([\s\S]*?)```/g;+ let jm: RegExpExecArray | null;+ while ((jm = jsonRegex.exec(routedFull))) {+ const jsonText = String(jm[1] || "").trim();+ if (!jsonText) continue;+ onCodeAction?.(jsonText, "cad");+ }++ const producedHasPlan = /"type"\s*:\s*"cad_plan"/.test(routedFull);+ const producedHasSvg2d = /```svg[\s\S]*?```/.test(routedFull);+ const producedHasImages = /"type"\s*:\s*"cad_images"/.test(routedFull);+ const producedHasBom = /"type"\s*:\s*"cad_bom"/.test(routedFull);+ const guide = buildCadNextStepGuide({+ agent,+ beforeHasPlan,+ beforeHasSvg2d,+ producedHasPlan,+ producedHasSvg2d,+ producedHasImages,+ producedHasBom,+ });+ if (guide) updateLastAssistant(`${routedFull}\n\n${guide}`);+ }+ return;+ }+ }++ if (fullResponse) {+ let { flowPatchFound, flowRetryError } =+ await handleAssistantResponse(fullResponse);++ let flowRetryMessagesBase: ChatMessage[] = flowRoutedBaseMessages ? [...flowRoutedBaseMessages] : apiMessages;+ let flowRetryAgent: "patch" | "replace" | null = flowSelectedAgent;++ while (+ workspaceId === "flow" &&+ flowPatchFound &&+ flowRetryError &&+ !controller.signal.aborted &&+ flowAutoRetryCountRef.current < MAX_FLOW_AUTO_RETRY+ ) {+ flowAutoRetryCountRef.current += 1;+ const forceReplace = flowAutoRetryCountRef.current >= MAX_FLOW_AUTO_RETRY;++ if (forceReplace && flowRetryAgent === "patch") {+ flowRetryAgent = "replace";+ const routedSystemContent = [flowReplaceAgentPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join("\n\n");+ flowRetryMessagesBase = [+ { role: "system", content: routedSystemContent },+ { role: "user", content: promptContent }+ ];+ }++ const retryPrompt = buildFlowRetryPrompt(flowRetryError, forceReplace);+ const retryMessages: ChatMessage[] = [+ ...flowRetryMessagesBase,+ { role: "assistant", content: fullResponse },+ { role: "user", content: retryPrompt },+ ];++ setMessages((prev) => [...prev, { role: "assistant", content: "" }]);++ let retryFull = "";+ const retryUpdater = createThrottledAssistantUpdater();+ await streamChatMessage(+ retryMessages,+ (chunk) => {+ retryFull = chunk;+ retryUpdater.push(chunk);+ },+ chatModel,+ controller.signal,+ );+ retryUpdater.flush();++ fullResponse = retryFull;+ flowRetryMessagesBase = retryMessages;+ const processed = await handleAssistantResponse(fullResponse);+ flowPatchFound = processed.flowPatchFound;+ flowRetryError = processed.flowRetryError;}}@@ -626,19 +1072,24 @@ export function ChatPanel({setMessages(prev => {const last = prev[prev.length - 1];if (last?.role === 'assistant') {- const next = last.content ? `${last.content}\n\n(已中断)` : "(已中断)";+ 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: "(已中断)" }];+ return [...prev, { role: 'assistant', content: trText("(已中断)", "(Aborted)") }];});return;}setMessages(prev => {const last = prev[prev.length - 1];+ const errorText = trText(+ "抱歉,遇到错误。请检查设置中的 API Key 是否正确。",+ "Sorry, an error occurred. Please check whether the API key in Settings is correct."+ );if (last.role === 'assistant' && !last.content) {- return [...prev.slice(0, -1), { role: 'assistant', content: "抱歉,遇到错误。请检查设置中的 API Key 是否正确。" }];+ return [...prev.slice(0, -1), { role: 'assistant', content: errorText }];}- return [...prev, { role: 'assistant', content: "抱歉,遇到错误。请检查设置中的 API Key 是否正确。" }];+ return [...prev, { role: 'assistant', content: errorText }];});} finally {setIsLoading(false);@@ -657,9 +1108,17 @@ export function ChatPanel({const globalConstraints = typeof window !== 'undefined' ? localStorage.getItem(constraintsKey) || '' : '';const globalSystemPrompt = config.systemPrompt || '';const systemContent = [systemPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join('\n\n');+ const lastUserText = String(baseMessages[baseMessages.length - 1]?.content || "");+ const flowContextText =+ workspaceId === "flow" && typeof flowContext?.xml === "string" && flowContext.xml.trim()+ ? `Current diagram XML:\n\n\`\`\`xml\n${flowContext.xml}\n\`\`\``+ : "";+ const promptContent = [lastUserText, flowContextText].filter(Boolean).join("\n\n");+const apiMessages: ChatMessage[] = [{ role: 'system', content: systemContent },- ...baseMessages+ ...baseMessages.slice(0, -1),+ { role: "user", content: promptContent }];setIsLoading(true);@@ -679,22 +1138,106 @@ export function ChatPanel({updater.flush();if (fullResponse) {- const xmlMatch = fullResponse.match(/```xml\n([\s\S]*?)\n```/);- if (xmlMatch && xmlMatch[1]) onCodeAction?.(xmlMatch[1], 'flow');-- const pyMatch = fullResponse.match(/```python\n([\s\S]*?)\n```/);- if (pyMatch && pyMatch[1] && workspaceId !== "cad") onCodeAction?.(pyMatch[1], 'cad');-- if (workspaceId === "cad") {- const jsMatch = fullResponse.match(/```(javascript|js)\n([\s\S]*?)\n```/);- if (jsMatch && jsMatch[2]) onCodeAction?.(jsMatch[2], 'cad');+ let flowRoutedBaseMessages: ChatMessage[] | null = null;+ let flowSelectedAgent: "patch" | "replace" | null = null;++ if (workspaceId === "flow") {+ const resolveFlowAgentFromRouteText = (text: string): "patch" | "replace" | null => {+ const trimmed = String(text || "").trim();+ if (!trimmed) return null;++ let content = trimmed;+ const fenceMatch = content.match(/```[a-zA-Z]*\s*([\s\S]*?)```/);+ if (fenceMatch && fenceMatch[1]) content = fenceMatch[1].trim();+ content = content.replace(/\s+/g, "");++ if (!/^[1-2]$/.test(content)) return null;+ return content === "1" ? "patch" : "replace";+ };++ const agentFromText = resolveFlowAgentFromRouteText(fullResponse);+ if (agentFromText) {+ flowSelectedAgent = agentFromText;++ setMessages((prev) => {+ const last = prev[prev.length - 1];+ if (last?.role === "assistant") return [...prev.slice(0, -1), { role: "assistant", content: "" }];+ return prev;+ });++ const agentPrompt = flowSelectedAgent === "patch" ? flowPatchAgentPrompt : flowReplaceAgentPrompt;+ const routedSystemContent = [agentPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join("\n\n");+ const routedMessages: ChatMessage[] = [+ { role: "system", content: routedSystemContent },+ { role: "user", content: promptContent }+ ];++ let routedFull = "";+ const routedUpdater = createThrottledAssistantUpdater();+ await streamChatMessage(routedMessages, (chunk) => {+ routedFull = chunk;+ routedUpdater.push(chunk);+ }, chatModel, controller.signal);+ routedUpdater.flush();++ flowRoutedBaseMessages = routedMessages;+ fullResponse = routedFull;+ }}- const svgMatch = fullResponse.match(/```svg\n([\s\S]*?)\n```/);- if (svgMatch && svgMatch[1]) onCodeAction?.(svgMatch[1], 'cad');+ let { flowPatchFound, flowRetryError } =+ await handleAssistantResponse(fullResponse);++ let flowRetryMessagesBase: ChatMessage[] = flowRoutedBaseMessages ? [...flowRoutedBaseMessages] : apiMessages;+ let flowRetryAgent: "patch" | "replace" | null = flowSelectedAgent;++ while (+ workspaceId === "flow" &&+ flowPatchFound &&+ flowRetryError &&+ !controller.signal.aborted &&+ flowAutoRetryCountRef.current < MAX_FLOW_AUTO_RETRY+ ) {+ flowAutoRetryCountRef.current += 1;+ const forceReplace = flowAutoRetryCountRef.current >= MAX_FLOW_AUTO_RETRY;++ if (forceReplace && flowRetryAgent === "patch") {+ flowRetryAgent = "replace";+ const routedSystemContent = [flowReplaceAgentPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join("\n\n");+ flowRetryMessagesBase = [+ { role: "system", content: routedSystemContent },+ { role: "user", content: promptContent }+ ];+ }- const jsonMatch = fullResponse.match(/```json\n([\s\S]*?)\n```/);- if (jsonMatch && jsonMatch[1]) onCodeAction?.(jsonMatch[1], workspaceId === "cad" ? 'cad' : 'ppt');+ const retryPrompt = buildFlowRetryPrompt(flowRetryError, forceReplace);+ const retryMessages: ChatMessage[] = [+ ...flowRetryMessagesBase,+ { role: "assistant", content: fullResponse },+ { role: "user", content: retryPrompt },+ ];++ setMessages((prev) => [...prev, { role: "assistant", content: "" }]);++ let retryFull = "";+ const retryUpdater = createThrottledAssistantUpdater();+ await streamChatMessage(+ retryMessages,+ (chunk) => {+ retryFull = chunk;+ retryUpdater.push(chunk);+ },+ chatModel,+ controller.signal,+ );+ retryUpdater.flush();++ fullResponse = retryFull;+ flowRetryMessagesBase = retryMessages;+ const processed = await handleAssistantResponse(fullResponse);+ flowPatchFound = processed.flowPatchFound;+ flowRetryError = processed.flowRetryError;+ }}} catch (error) {if ((error as any)?.name === "AbortError" || (error as any)?.name === "APIUserAbortError") {@@ -729,6 +1272,7 @@ export function ChatPanel({if (base.length === 0) return;const last = base[base.length - 1];if (last.role !== 'user') return;+ flowAutoRetryCountRef.current = 0;await runTextChat(base);};@@ -756,6 +1300,7 @@ export function ChatPanel({const base = [...messages.slice(0, messageIndex), updatedUser];setInput("");setFiles([]);+ flowAutoRetryCountRef.current = 0;await runTextChat(base);};@@ -768,12 +1313,12 @@ export function ChatPanel({if (collapsed) {return (- <div className={cn("h-full border-l border-border/60 bg-background/60 backdrop-blur flex flex-col items-center py-4 gap-4 w-full", className)}>- <Button variant="ghost" size="icon" onClick={onToggleCollapse} title="展开聊天">- <SidebarOpen className="w-5 h-5 text-muted-foreground" />+ <div className={cn("h-full border-l border-border/60 bg-gradient-to-b from-background/70 to-background/40 backdrop-blur flex flex-col items-center py-4 gap-4 w-full", className)}>+ <Button variant="ghost" size="icon" onClick={onToggleCollapse} title={t(uiLang, "chat.expand")} className="rounded-xl">+ <PanelRightOpen className="w-5 h-5 text-muted-foreground" /></Button><div className="flex-1" />- <Button variant="ghost" size="icon" onClick={() => setShowGlobalConstraints(true)} title="全局约束">+ <Button variant="ghost" size="icon" onClick={() => setShowGlobalConstraints(true)} title={t(uiLang, "chat.globalConstraints")} className="rounded-xl"><Settings2 className="w-5 h-5 text-muted-foreground" /></Button></div>@@ -781,9 +1326,9 @@ export function ChatPanel({}return (- <div className={cn("flex flex-col h-full bg-background/60 backdrop-blur border-l border-border/60", className)}>+ <div className={cn("flex flex-col h-full bg-gradient-to-b from-background/70 to-background/40 backdrop-blur border-l border-border/60", className)}>{/* Header */}- <div className="h-14 px-5 border-b border-border/60 flex items-center justify-between bg-background/70 backdrop-blur-md supports-[backdrop-filter]:bg-background/60 z-10 shadow-sm">+ <div className="h-14 px-5 border-b border-border/60 flex items-center justify-between bg-background/60 backdrop-blur-md supports-[backdrop-filter]:bg-background/50 z-10 shadow-sm"><div className="flex items-center gap-2 font-medium"><Bot className="w-5 h-5 text-primary" /><span>{title}</span>@@ -793,8 +1338,8 @@ export function ChatPanel({variant="ghost"size="icon"onClick={startNewChat}- className="h-8 w-8 text-muted-foreground hover:text-foreground"- title="新开对话"+ className="h-8 w-8 text-muted-foreground hover:text-foreground rounded-xl"+ title={t(uiLang, "chat.newChatTitle")}><Plus className="w-4 h-4" /></Button>@@ -803,8 +1348,8 @@ export function ChatPanel({variant="ghost"size="icon"onClick={() => setShowHistory(true)}- className="h-8 w-8 text-muted-foreground hover:text-foreground"- title="版本历史"+ className="h-8 w-8 text-muted-foreground hover:text-foreground rounded-xl"+ title={t(uiLang, "chat.historyTitle")}><History className="w-4 h-4" /></Button>@@ -813,8 +1358,8 @@ export function ChatPanel({variant="ghost"size="icon"onClick={() => setShowResetWarning(true)}- className="h-8 w-8 text-muted-foreground hover:text-destructive transition-colors"- title="清空对话"+ className="h-8 w-8 text-muted-foreground hover:text-destructive transition-colors rounded-xl"+ title={t(uiLang, "chat.clearChatTitle")}><Trash2 className="w-4 h-4" /></Button>@@ -823,10 +1368,11 @@ export function ChatPanel({variant="ghost"size="icon"onClick={onToggleCollapse}- title={collapseLocked ? "PPT 生成完成前不能收起聊天" : "收起聊天"}+ title={collapseLocked ? t(uiLang, "chat.collapseLocked") : t(uiLang, "chat.collapse")}disabled={collapseLocked}+ className="rounded-xl">- <SidebarClose className="w-4 h-4 text-muted-foreground" />+ <PanelRightClose className="w-4 h-4 text-muted-foreground" /></Button>)}</div>@@ -845,7 +1391,7 @@ export function ChatPanel({</div>{/* Input */}- <div className="p-4 bg-background/50 backdrop-blur relative z-20">+ <div className="p-4 bg-background/40 backdrop-blur relative z-20"><ChatInputinput={input}setInput={setInput}diff --git a/src/components/SettingsDialog.tsx b/src/components/SettingsDialog.tsxindex c54adb9..6583e8e 100644--- a/src/components/SettingsDialog.tsx+++ b/src/components/SettingsDialog.tsx@@ -3,21 +3,30 @@ import { createPortal } from 'react-dom';import { Settings, X, Save } from 'lucide-react';import { getAIConfig, saveAIConfig, AIConfig } from '@/lib/ai-client';import { Button } from '@/components/ui/button';-import { cn } from '@/lib/utils';+import { getUiLanguage, setUiLanguage, type UiLanguage } from "@/lib/ui-language";+import { t } from "@/lib/i18n";export function SettingsDialog() {const [isOpen, setIsOpen] = useState(false);const [config, setConfig] = useState<AIConfig>(getAIConfig());+ const [uiLang, setUiLang] = useState<UiLanguage>(() => getUiLanguage());// Reload config when dialog opensuseEffect(() => {if (isOpen) {setConfig(getAIConfig());+ setUiLang(getUiLanguage());}}, [isOpen]);+ useEffect(() => {+ if (!isOpen) return;+ setUiLanguage(uiLang);+ }, [uiLang, isOpen]);+const handleSave = () => {saveAIConfig(config);+ setUiLanguage(uiLang);setIsOpen(false);};@@ -28,7 +37,7 @@ export function SettingsDialog() {size="icon"onClick={() => setIsOpen(true)}className="text-muted-foreground hover:text-foreground"- title="设置"+ title={t(uiLang, "settings.buttonTitle")}><Settings className="w-5 h-5" /></Button>@@ -38,8 +47,8 @@ export function SettingsDialog() {<div className="bg-background rounded-xl shadow-2xl w-full max-w-md border border-border/50 flex flex-col max-h-[90vh] animate-in zoom-in-95 duration-200 overflow-hidden"><div className="flex items-center justify-between p-6 border-b border-border/50 bg-muted/10"><div>- <h2 className="text-lg font-semibold text-foreground tracking-tight">配置设置</h2>- <p className="text-xs text-muted-foreground mt-1">配置 AI 模型参数与 API 密钥</p>+ <h2 className="text-lg font-semibold text-foreground tracking-tight">{t(uiLang, "settings.title")}</h2>+ <p className="text-xs text-muted-foreground mt-1">{t(uiLang, "settings.subtitle")}</p></div><Button variant="ghost" size="icon" onClick={() => setIsOpen(false)} className="h-8 w-8 rounded-full hover:bg-muted/50"><X className="w-4 h-4" />@@ -47,6 +56,26 @@ export function SettingsDialog() {</div><div className="p-6 space-y-5 overflow-y-auto">+ <div className="flex items-center justify-between gap-3">+ <div className="text-sm font-medium text-foreground">{t(uiLang, "settings.language")}</div>+ <div className="flex items-center rounded-lg border border-border/60 bg-muted/10 p-1">+ <Button+ variant={uiLang === "zh" ? "secondary" : "ghost"}+ className="h-8 px-3 rounded-md"+ onClick={() => setUiLang("zh")}+ >+ 中文+ </Button>+ <Button+ variant={uiLang === "en" ? "secondary" : "ghost"}+ className="h-8 px-3 rounded-md"+ onClick={() => setUiLang("en")}+ >+ English+ </Button>+ </div>+ </div>+<div className="space-y-2"><label className="text-sm font-medium text-foreground flex items-center gap-2">API Key@@ -74,7 +103,7 @@ export function SettingsDialog() {<div className="grid grid-cols-1 gap-5 pt-2"><div className="space-y-2">- <label className="text-sm font-medium text-foreground">对话模型 (Chat Model)</label>+ <label className="text-sm font-medium text-foreground">{t(uiLang, "settings.chatModel")}</label><inputtype="text"value={config.chatModel}@@ -85,7 +114,7 @@ export function SettingsDialog() {</div><div className="space-y-2">- <label className="text-sm font-medium text-foreground">绘图模型 (Image Model)</label>+ <label className="text-sm font-medium text-foreground">{t(uiLang, "settings.imageModel")}</label><inputtype="text"value={config.imageModel}@@ -103,14 +132,14 @@ export function SettingsDialog() {onClick={() => setIsOpen(false)}className="rounded-lg hover:bg-muted">- 取消+ {t(uiLang, "common.cancel")}</Button><ButtononClick={handleSave}className="gap-2 rounded-lg shadow-sm"><Save className="w-4 h-4" />- 保存+ {t(uiLang, "common.save")}</Button></div></div>diff --git a/src/components/global-constraints-dialog.tsx b/src/components/global-constraints-dialog.tsxindex 8e9c377..5522789 100644--- a/src/components/global-constraints-dialog.tsx+++ b/src/components/global-constraints-dialog.tsx@@ -9,6 +9,8 @@ import {DialogTitle,} from "@/components/ui/dialog"import { Textarea } from "@/components/ui/textarea"+import { useUiLanguage } from "@/lib/use-ui-language";+import { t } from "@/lib/i18n";export const STORAGE_GLOBAL_CONSTRAINTS_KEY = "unified-ai-workspace-global-constraints"@@ -24,6 +26,7 @@ export function GlobalConstraintsDialog({workspaceId}: GlobalConstraintsDialogProps) {const [constraints, setConstraints] = useState("")+ const uiLang = useUiLanguage();// Determine the actual storage keyconst storageKey = workspaceId@@ -46,22 +49,32 @@ export function GlobalConstraintsDialog({<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="sm:max-w-[500px]"><DialogHeader>- <DialogTitle>全局规则约束 ({workspaceId === 'flow' ? '流程图' : workspaceId === 'cad' ? 'CAD设计' : workspaceId === 'ppt' ? 'PPT演示' : '通用'})</DialogTitle>+ <DialogTitle>+ {t(uiLang, "constraints.title")} (+ {workspaceId === 'flow'+ ? (uiLang === "zh" ? '流程图' : 'Flow')+ : workspaceId === 'cad'+ ? (uiLang === "zh" ? 'CAD设计' : 'CAD')+ : workspaceId === 'ppt'+ ? (uiLang === "zh" ? 'PPT演示' : 'PPT')+ : (uiLang === "zh" ? '通用' : 'General')}+ )+ </DialogTitle><DialogDescription>- 设置适用于当前工作区的全局系统提示词。+ {t(uiLang, "constraints.desc")}</DialogDescription></DialogHeader><div className="grid gap-4 py-4"><Textareavalue={constraints}onChange={(e) => setConstraints(e.target.value)}- placeholder="例如:始终使用中文回答,代码注释必须详细..."+ placeholder={t(uiLang, "constraints.placeholder")}className="min-h-[200px]"/></div><DialogFooter><Button onClick={handleSave}>- 保存+ {t(uiLang, "common.save")}</Button></DialogFooter></DialogContent>diff --git a/src/components/history-dialog.tsx b/src/components/history-dialog.tsxindex 1d05c08..bb2d912 100644--- a/src/components/history-dialog.tsx+++ b/src/components/history-dialog.tsx@@ -8,6 +8,8 @@ import {import { Button } from '@/components/ui/button';import { Clock, RotateCcw, FileCode, Trash2 } from 'lucide-react';import { ScrollArea } from '@/components/ui/scroll-area';+import { useUiLanguage } from "@/lib/use-ui-language";+import { t } from "@/lib/i18n";export interface HistoryItem {id: string;@@ -32,6 +34,7 @@ export function HistoryDialog({onRestore,onClear,}: HistoryDialogProps) {+ const uiLang = useUiLanguage();const formatDate = (ts: number) => {return new Date(ts).toLocaleString();};@@ -43,7 +46,7 @@ export function HistoryDialog({<div className="flex items-center justify-between gap-3"><DialogTitle className="flex items-center gap-2"><Clock className="w-5 h-5 text-muted-foreground" />- 版本历史+ {t(uiLang, "history.title")}</DialogTitle>{history.length > 0 && onClear && (<Button@@ -53,7 +56,7 @@ export function HistoryDialog({className="gap-1 text-xs"><Trash2 className="w-3.5 h-3.5" />- 清空+ {t(uiLang, "history.clear")}</Button>)}</div>@@ -63,7 +66,7 @@ export function HistoryDialog({{history.length === 0 ? (<div className="text-center p-8 text-muted-foreground text-sm flex flex-col items-center gap-2"><Clock className="w-8 h-8 opacity-20" />- <p>暂无历史记录</p>+ <p>{t(uiLang, "history.empty")}</p></div>) : (<ScrollArea className="h-[400px] pr-4">@@ -81,7 +84,7 @@ export function HistoryDialog({<FileCode className="w-3 h-3" /><span>{item.type.toUpperCase()}</span><span>•</span>- <span>{item.content.length} chars</span>+ <span>{t(uiLang, "history.chars", { n: item.content.length })}</span></div></div>@@ -95,7 +98,7 @@ export function HistoryDialog({className="opacity-0 group-hover:opacity-100 transition-opacity gap-1 text-xs"><RotateCcw className="w-3 h-3" />- 恢复+ {t(uiLang, "history.restore")}</Button></div>))}diff --git a/src/components/reset-warning-modal.tsx b/src/components/reset-warning-modal.tsxindex 323b3a3..ec0c08a 100644--- a/src/components/reset-warning-modal.tsx+++ b/src/components/reset-warning-modal.tsx@@ -8,6 +8,8 @@ import {DialogHeader,DialogTitle,} from "@/components/ui/dialog"+import { t } from "@/lib/i18n";+import { useUiLanguage } from "@/lib/use-ui-language";interface ResetWarningModalProps {open: boolean@@ -20,21 +22,22 @@ export function ResetWarningModal({onOpenChange,onClear,}: ResetWarningModalProps) {+ const uiLang = useUiLanguage();return (<Dialog open={open} onOpenChange={onOpenChange}><DialogContent><DialogHeader>- <DialogTitle>清空对话</DialogTitle>+ <DialogTitle>{t(uiLang, "reset.title")}</DialogTitle><DialogDescription>- 确定要清空所有对话记录吗?此操作无法撤销。+ {t(uiLang, "reset.desc")}</DialogDescription></DialogHeader><DialogFooter><Button variant="outline" onClick={() => onOpenChange(false)}>- 取消+ {t(uiLang, "common.cancel")}</Button><Button variant="destructive" onClick={onClear}>- 清空+ {t(uiLang, "common.clear")}</Button></DialogFooter></DialogContent>diff --git a/src/components/save-dialog.tsx b/src/components/save-dialog.tsxindex 82af98d..e7b662d 100644--- a/src/components/save-dialog.tsx+++ b/src/components/save-dialog.tsx@@ -16,6 +16,8 @@ import {SelectTrigger,SelectValue,} from "@/components/ui/select"+import { useUiLanguage } from "@/lib/use-ui-language";+import { t } from "@/lib/i18n";interface SaveDialogProps {open: boolean@@ -32,6 +34,7 @@ export function SaveDialog({}: SaveDialogProps) {const [filename, setFilename] = useState(defaultFilename)const [format, setFormat] = useState("xml")+ const uiLang = useUiLanguage();const handleSave = () => {onSave(filename, format)@@ -42,12 +45,12 @@ export function SaveDialog({<Dialog open={open} onOpenChange={onOpenChange}><DialogContent className="sm:max-w-[425px]"><DialogHeader>- <DialogTitle>保存图表</DialogTitle>+ <DialogTitle>{t(uiLang, "saveDialog.title")}</DialogTitle></DialogHeader><div className="grid gap-4 py-4"><div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="filename" className="text-right">- 文件名+ {t(uiLang, "saveDialog.filename")}</Label><Inputid="filename"@@ -58,11 +61,11 @@ export function SaveDialog({</div><div className="grid grid-cols-4 items-center gap-4"><Label htmlFor="format" className="text-right">- 格式+ {t(uiLang, "saveDialog.format")}</Label><Select value={format} onValueChange={setFormat}><SelectTrigger className="col-span-3">- <SelectValue placeholder="选择格式" />+ <SelectValue placeholder={t(uiLang, "saveDialog.chooseFormat")} /></SelectTrigger><SelectContent><SelectItem value="xml">XML (Draw.io)</SelectItem>@@ -73,7 +76,7 @@ export function SaveDialog({</div></div><DialogFooter>- <Button onClick={handleSave}>保存</Button>+ <Button onClick={handleSave}>{t(uiLang, "common.save")}</Button></DialogFooter></DialogContent></Dialog>diff --git a/src/components/ui/code-block.tsx b/src/components/ui/code-block.tsxindex 0873cd2..9eab18f 100644--- a/src/components/ui/code-block.tsx+++ b/src/components/ui/code-block.tsx@@ -1,13 +1,12 @@import React, { useMemo, useRef, useState } from 'react';-import { Highlight, themes } from "prism-react-renderer";+import { Highlight, themes, type Language } from "prism-react-renderer";import { ChevronRight, Loader2 } from 'lucide-react';import { cn } from '@/lib/utils';-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";interface CodeBlockProps {code: string;language?: string;- isStreaming?: boolean; // New prop to indicate if content is actively streaming+ isStreaming?: boolean;blockId?: string;}@@ -21,20 +20,49 @@ export function CodeBlock({ code, language = "xml", isStreaming = false, blockIdconst preRef = useRef<HTMLPreElement | null>(null);const normalizedLanguage = useMemo(() => (language || "text").toLowerCase(), [language]);const normalizedCode = useMemo(() => String(code ?? ""), [code]);+ const prismLanguage = useMemo<Language>(() => {+ const lang = normalizedLanguage;+ if (lang === "svg") return "xml";+ if (lang === "yml") return "yaml";+ if (lang === "shell" || lang === "sh" || lang === "zsh") return "bash";+ if (lang === "ts") return "typescript";+ if (lang === "tsx") return "tsx";+ if (lang === "js") return "javascript";+ if (lang === "md") return "markdown";+ const allowed = new Set([+ "text",+ "xml",+ "json",+ "javascript",+ "typescript",+ "tsx",+ "jsx",+ "python",+ "bash",+ "yaml",+ "markdown",+ "css",+ "html",+ ]);+ if (allowed.has(lang)) return lang as Language;+ return "text";+ }, [normalizedLanguage]);+ const setOpen = (open: boolean) => {+ setIsOpen(open);+ if (blockId) openStateById.set(blockId, open);+ };+return (- <Collapsible- open={isOpen}- onOpenChange={(open) => {- setIsOpen(open);- if (blockId) openStateById.set(blockId, open);- }}- className="w-full my-2 border border-border/50 rounded-lg bg-zinc-50 overflow-hidden group shadow-sm"- >- <CollapsibleTrigger className="flex items-center gap-2 w-full p-2.5 cursor-pointer hover:bg-zinc-100 transition-colors text-xs font-medium text-zinc-600 select-none bg-zinc-100/70">- <ChevronRight className={cn("w-4 h-4 transition-transform duration-200", isOpen && "rotate-90")} />+ <div className="w-full my-2 border border-border/50 rounded-lg bg-zinc-50 dark:bg-zinc-900/40 overflow-hidden shadow-sm">+ <button+ type="button"+ onClick={() => setOpen(!isOpen)}+ className="flex items-center gap-2 w-full p-2.5 cursor-pointer hover:bg-zinc-100 dark:hover:bg-zinc-800/40 transition-colors text-xs font-medium text-zinc-600 dark:text-zinc-300 select-none bg-zinc-100/70 dark:bg-zinc-900/60"+ >+ <ChevronRight className={cn("w-4 h-4 transition-transform duration-200 text-zinc-600 dark:text-zinc-300", isOpen && "rotate-90")} />- <span className="uppercase font-semibold tracking-wider text-zinc-700">{normalizedLanguage}</span>+ <span className="uppercase font-semibold tracking-wider text-zinc-700 dark:text-zinc-200">{normalizedLanguage}</span>{isStreaming ? (<div className="flex items-center gap-2 ml-auto">@@ -44,14 +72,13 @@ export function CodeBlock({ code, language = "xml", isStreaming = false, blockId) : (<span className="ml-auto text-[10px] opacity-70 font-mono">{normalizedCode.length} chars</span>)}- </CollapsibleTrigger>+ </button>- <CollapsibleContent>+ {isOpen && (<div className="p-0 border-t border-border/50">- <div className="overflow-hidden w-full bg-zinc-50">- <Highlight theme={themes.github} code={normalizedCode} language={normalizedLanguage as any}>+ <div className="overflow-hidden w-full bg-zinc-50 dark:bg-zinc-900/40">+ <Highlight theme={themes.github} code={normalizedCode} language={prismLanguage}>{({- className: _className,style,tokens,getLineProps,@@ -98,7 +125,7 @@ export function CodeBlock({ code, language = "xml", isStreaming = false, blockId</Highlight></div></div>- </CollapsibleContent>- </Collapsible>+ )}+ </div>);}diff --git a/src/components/workspaces/CadWorkspace.tsx b/src/components/workspaces/CadWorkspace.tsxindex fee00f8..81476bb 100644--- a/src/components/workspaces/CadWorkspace.tsx+++ b/src/components/workspaces/CadWorkspace.tsx@@ -8,6 +8,8 @@ import {} from "@/components/ui/context-menu";import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { PDFDocument } from "pdf-lib";+import { useUiLanguage } from "@/lib/use-ui-language";interface CadWorkspaceProps {onAddToChat?: (code: string) => void;@@ -20,20 +22,243 @@ interface CadWorkspaceProps {}export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoading = false, bom, focusPanel }: CadWorkspaceProps) {+ const CAD_RENDERS_STORAGE_KEY = "unified-ai-workspace-cad-renders-v1";const [svgContent, setSvgContent] = useState<string | null>(null);const [viewMode, setViewMode] = useState<"2d" | "renders" | "bom">("2d");const [previewImage, setPreviewImage] = useState<{ title: string; url: string } | null>(null);+ const [isExporting, setIsExporting] = useState(false);+ const [localImages, setLocalImages] = useState<Array<{ title: string; url: string }>>(() => {+ if (typeof window === "undefined") return [];+ try {+ const raw = localStorage.getItem(CAD_RENDERS_STORAGE_KEY);+ const parsed = raw ? JSON.parse(raw) : [];+ if (!Array.isArray(parsed)) return [];+ return parsed+ .filter((x: any) => x && typeof x.url === "string" && !String(x.url).startsWith("blob:"))+ .map((x: any) => ({+ title: typeof x.title === "string" ? x.title : "",+ url: String(x.url),+ }));+ } catch {+ return [];+ }+ });+ const uiLang = useUiLanguage();useEffect(() => {if (typeof svg2d === "string") {setSvgContent(svg2d);+ return;}+ setSvgContent(null);}, [svg2d]);+ useEffect(() => {+ if (!Array.isArray(images) || images.length === 0) {+ setLocalImages([]);+ setPreviewImage(null);+ return;+ }+ let cancelled = false;++ const blobUrlToDataUrl = async (objectUrl: string) => {+ if (typeof window === "undefined") return "";+ if (!objectUrl || !objectUrl.startsWith("blob:")) return objectUrl;+ try {+ const resp = await fetch(objectUrl);+ const blob = await resp.blob();+ return await new Promise<string>((resolve) => {+ const reader = new FileReader();+ reader.onerror = () => resolve("");+ reader.onloadend = () => resolve(typeof reader.result === "string" ? reader.result : "");+ reader.readAsDataURL(blob);+ });+ } catch {+ return "";+ }+ };++ void (async () => {+ const mapped = await Promise.all(+ images.map(async (it) => {+ const rawUrl = typeof (it as any)?.url === "string" ? String((it as any).url) : "";+ if (!rawUrl) return null;+ const title = typeof (it as any)?.title === "string" ? String((it as any).title) : "";+ if (rawUrl.startsWith("blob:")) {+ const dataUrl = await blobUrlToDataUrl(rawUrl);+ if (!dataUrl) return null;+ return { title, url: dataUrl };+ }+ return { title, url: rawUrl };+ })+ );+ if (cancelled) return;+ const cleaned = mapped.filter(Boolean) as Array<{ title: string; url: string }>;+ setLocalImages(cleaned);+ })();++ return () => {+ cancelled = true;+ };+ }, [images]);++ useEffect(() => {+ if (typeof window === "undefined") return;+ try {+ const stable = localImages.filter((x) => x && typeof x.url === "string" && !x.url.startsWith("blob:")).slice(0, 30);+ localStorage.setItem(CAD_RENDERS_STORAGE_KEY, JSON.stringify(stable));+ } catch {+ }+ }, [localImages]);+useEffect(() => {if (!focusPanel) return;setViewMode(focusPanel);}, [focusPanel]);++ useEffect(() => {+ const emptyImages = !Array.isArray(images) || images.length === 0;+ const emptyBom = !bom || !Array.isArray(bom.columns) || bom.columns.length === 0;+ if (!plan && !svg2d && emptyImages && emptyBom && !focusPanel) {+ setViewMode("2d");+ }+ }, [plan, svg2d, images, bom, focusPanel]);++ const downloadBlob = (blob: Blob, filename: string) => {+ const link = document.createElement("a");+ const url = URL.createObjectURL(blob);+ link.href = url;+ link.download = filename;+ document.body.appendChild(link);+ link.click();+ link.remove();+ setTimeout(() => URL.revokeObjectURL(url), 5000);+ };++ const exportSvg = async () => {+ if (!svg2d || isExporting) return;+ setIsExporting(true);+ try {+ const blob = new Blob([svg2d], { type: "image/svg+xml;charset=utf-8" });+ downloadBlob(blob, `floorplan-${Date.now()}.svg`);+ } finally {+ setIsExporting(false);+ }+ };++ const svgToPngDataUrl = async (svg: string, targetWidth = 1600) => {+ const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });+ const url = URL.createObjectURL(blob);+ try {+ const img = new Image();+ const load = new Promise<void>((resolve, reject) => {+ img.onload = () => resolve();+ img.onerror = reject;+ });+ img.src = url;+ await load;++ const vb = svg.match(/viewBox\s*=\s*"([\d.-]+)\s+([\d.-]+)\s+([\d.-]+)\s+([\d.-]+)"/i);+ const vbW = vb ? Number(vb[3]) : NaN;+ const vbH = vb ? Number(vb[4]) : NaN;+ const ratio =+ Number.isFinite(vbW) && Number.isFinite(vbH) && vbW > 0 && vbH > 0+ ? vbH / vbW+ : img.naturalHeight > 0 && img.naturalWidth > 0+ ? img.naturalHeight / img.naturalWidth+ : 9 / 16;+ const width = targetWidth;+ const height = Math.max(1, Math.round(width * ratio));++ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d");+ if (!ctx) return "";+ ctx.clearRect(0, 0, width, height);+ ctx.drawImage(img, 0, 0, width, height);+ return canvas.toDataURL("image/png");+ } finally {+ URL.revokeObjectURL(url);+ }+ };++ const exportSvgAsPdf = async () => {+ if (!svg2d || isExporting) return;+ setIsExporting(true);+ try {+ const pngDataUrl = await svgToPngDataUrl(svg2d, 1600);+ if (!pngDataUrl) return;+ const base64 = pngDataUrl.split(",")[1] || "";+ const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));+ const pdfDoc = await PDFDocument.create();+ const img = await pdfDoc.embedPng(bytes);+ const page = pdfDoc.addPage([960, 540]);+ const scale = Math.min(960 / img.width, 540 / img.height);+ const w = img.width * scale;+ const h = img.height * scale;+ page.drawImage(img, { x: (960 - w) / 2, y: (540 - h) / 2, width: w, height: h });+ const pdfBytes = await pdfDoc.save();+ downloadBlob(new Blob([pdfBytes], { type: "application/pdf" }), `floorplan-${Date.now()}.pdf`);+ } catch (e) {+ console.error("Export SVG->PDF failed", e);+ } finally {+ setIsExporting(false);+ }+ };++ const exportRendersPdf = async () => {+ if (localImages.length === 0 || isExporting) return;+ setIsExporting(true);+ try {+ const pdfDoc = await PDFDocument.create();+ for (const it of localImages) {+ const res = await fetch(it.url);+ if (!res.ok) continue;+ const buf = await res.arrayBuffer();+ const bytes = new Uint8Array(buf);+ const contentType = String(res.headers.get("content-type") || "");+ const isJpg = contentType.includes("jpeg") || contentType.includes("jpg");+ const embedded = isJpg ? await pdfDoc.embedJpg(bytes) : await pdfDoc.embedPng(bytes);+ const pageW = 960;+ const pageH = 540;+ const page = pdfDoc.addPage([pageW, pageH]);+ const scale = Math.min(pageW / embedded.width, pageH / embedded.height);+ const w = embedded.width * scale;+ const h = embedded.height * scale;+ page.drawImage(embedded, { x: (pageW - w) / 2, y: (pageH - h) / 2, width: w, height: h });+ }+ const pdfBytes = await pdfDoc.save();+ downloadBlob(new Blob([pdfBytes], { type: "application/pdf" }), `renders-${Date.now()}.pdf`);+ } catch (e) {+ console.error("Export renders PDF failed", e);+ } finally {+ setIsExporting(false);+ }+ };++ const exportBomCsv = async () => {+ if (!bom || isExporting) return;+ setIsExporting(true);+ try {+ const esc = (v: any) => {+ const s = String(v ?? "");+ if (/[",\r\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`;+ return s;+ };+ 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] ?? ""));+ rows.push(fixed.join(","));+ }+ const csv = rows.join("\r\n");+ downloadBlob(new Blob([csv], { type: "text/csv;charset=utf-8" }), `bom-${Date.now()}.csv`);+ } finally {+ setIsExporting(false);+ }+ };return (<ContextMenu>@@ -54,10 +279,9 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoadvariant={viewMode === "renders" ? "default" : "outline"}className="h-7 px-2 text-xs gap-1"onClick={() => setViewMode("renders")}- disabled={(!images || images.length === 0) && !imagesLoading}><ImageIcon className="w-3.5 h-3.5" />- 装修图+ {uiLang === "zh" ? "装修图" : "Renders"}</Button><Buttonsize="sm"@@ -66,15 +290,44 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoadonClick={() => setViewMode("bom")}><Table2 className="w-3.5 h-3.5" />- 物料+ {uiLang === "zh" ? "物料" : "BOM"}</Button>+ <div className="h-4 w-px bg-border/60 mx-1" />+ {viewMode === "2d" && (+ <>+ <Button size="sm" variant="outline" className="h-7 px-2 text-xs gap-1" onClick={exportSvg} disabled={!svg2d || isExporting}>+ <Download className="w-3.5 h-3.5" />+ SVG+ </Button>+ <Button size="sm" variant="outline" className="h-7 px-2 text-xs gap-1" onClick={exportSvgAsPdf} disabled={!svg2d || isExporting}>+ <Download className="w-3.5 h-3.5" />+ </Button>+ </>+ )}+ {viewMode === "renders" && (+ <Button size="sm" variant="outline" className="h-7 px-2 text-xs gap-1" onClick={exportRendersPdf} disabled={localImages.length === 0 || isExporting}>+ <Download className="w-3.5 h-3.5" />+ </Button>+ )}+ {viewMode === "bom" && (+ <Button size="sm" variant="outline" className="h-7 px-2 text-xs gap-1" onClick={exportBomCsv} disabled={!bom || isExporting}>+ <Download className="w-3.5 h-3.5" />+ CSV+ </Button>+ )}</div>{!svgContent && (<div className="w-full h-full flex items-center justify-center"><div className="text-center text-muted-foreground">- <p className="mb-2">暂无 CAD 内容</p>- <p className="text-xs">在右侧对话里先做需求分析,确认方案后生成 SVG(2D),满意后生成装修图。</p>+ <p className="mb-2">{uiLang === "zh" ? "暂无 CAD 内容" : "No CAD content yet"}</p>+ <p className="text-xs">+ {uiLang === "zh"+ ? "在右侧对话里先做需求分析,确认方案后生成 SVG(2D),满意后生成装修图。"+ : "Use the chat on the right to define requirements, generate the 2D SVG, then generate renders."}+ </p></div></div>)}@@ -88,16 +341,18 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoad{viewMode === "renders" && (<div className="w-full h-full bg-white dark:bg-zinc-900 shadow-sm rounded-xl overflow-auto border border-border/50 p-4">- {imagesLoading && images.length === 0 ? (+ {imagesLoading && localImages.length === 0 ? (<div className="h-full w-full flex items-center justify-center text-muted-foreground text-sm gap-2"><Loader2 className="w-4 h-4 animate-spin" />- <span>正在生成装修图…</span>+ <span>{uiLang === "zh" ? "正在生成装修图…" : "Generating renders…"}</span>+ </div>+ ) : localImages.length === 0 ? (+ <div className="h-full w-full flex items-center justify-center text-muted-foreground text-sm">+ {uiLang === "zh" ? "暂无装修图" : "No renders yet"}</div>- ) : images.length === 0 ? (- <div className="h-full w-full flex items-center justify-center text-muted-foreground text-sm">暂无装修图</div>) : (<div className="grid gap-4 grid-cols-1 md:grid-cols-2 xl:grid-cols-3">- {images.map((img, idx) => (+ {localImages.map((img, idx) => (<div key={`${img.url}-${idx}`} className="rounded-xl border border-border/50 overflow-hidden bg-background"><div className="px-3 py-2 text-xs text-muted-foreground flex items-center justify-between gap-2"><ImageIcon className="w-4 h-4" />@@ -108,12 +363,12 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoadsize="icon"className="h-7 w-7"onClick={() => setPreviewImage(img)}- title="查看"+ title={uiLang === "zh" ? "查看" : "View"}><ImageIcon className="w-4 h-4" /></Button><a href={img.url} download={`${img.title || "render"}.png`} className="inline-flex">- <Button variant="ghost" size="icon" className="h-7 w-7" title="下载">+ <Button variant="ghost" size="icon" className="h-7 w-7" title={uiLang === "zh" ? "下载" : "Download"}><Download className="w-4 h-4" /></Button></a>@@ -132,7 +387,9 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoad{viewMode === "bom" && (<div className="w-full h-full bg-white dark:bg-zinc-900 shadow-sm rounded-xl overflow-auto border border-border/50 p-4">{!bom || !Array.isArray(bom.columns) || bom.columns.length === 0 ? (- <div className="h-full w-full flex items-center justify-center text-muted-foreground text-sm">暂无物料清单</div>+ <div className="h-full w-full flex items-center justify-center text-muted-foreground text-sm">+ {uiLang === "zh" ? "暂无物料清单" : "No BOM yet"}+ </div>) : (<div className="w-full overflow-auto"><table className="w-full text-sm border-collapse">@@ -167,21 +424,21 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoadonClick={() => {if (!onAddToChat) return;if (viewMode === "2d" && svgContent) onAddToChat(svgContent);- else if (viewMode === "renders" && images.length > 0) onAddToChat(JSON.stringify({ type: "cad_images", prompts: images }, null, 2));+ else if (viewMode === "renders" && localImages.length > 0) onAddToChat(JSON.stringify({ type: "cad_images", prompts: localImages }, null, 2));else if (viewMode === "bom" && bom) onAddToChat(JSON.stringify({ type: "cad_bom", columns: bom.columns, rows: bom.rows }, null, 2));else if (plan) onAddToChat(JSON.stringify(plan, null, 2));}}className="cursor-pointer gap-2"><MessageSquarePlus className="w-4 h-4" />- <span>添加到对话</span>+ <span>{uiLang === "zh" ? "添加到对话" : "Add to chat"}</span></ContextMenuItem></ContextMenuContent><Dialog open={!!previewImage} onOpenChange={(open) => { if (!open) setPreviewImage(null); }}><DialogContent className="sm:max-w-[920px] max-w-[calc(100%-2rem)] p-4"><DialogHeader className="pr-10">- <DialogTitle className="text-base">{previewImage?.title || "装修图"}</DialogTitle>+ <DialogTitle className="text-base">{previewImage?.title || (uiLang === "zh" ? "装修图" : "Render")}</DialogTitle></DialogHeader><div className="w-full">{previewImage?.url ? (@@ -190,7 +447,7 @@ export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoad<a href={previewImage.url} download={`${previewImage.title || "render"}.png`} className="inline-flex"><Button variant="outline" size="sm" className="h-8 px-3 text-xs"><Download className="w-4 h-4 mr-1" />- 下载图片+ {uiLang === "zh" ? "下载图片" : "Download image"}</Button></a></div>diff --git a/src/components/workspaces/FlowchartWorkspace.tsx b/src/components/workspaces/FlowchartWorkspace.tsxindex 9f94e41..5640435 100644--- a/src/components/workspaces/FlowchartWorkspace.tsx+++ b/src/components/workspaces/FlowchartWorkspace.tsx@@ -7,6 +7,8 @@ import {ContextMenuItem,ContextMenuTrigger,} from "@/components/ui/context-menu";+import { useUiLanguage } from "@/lib/use-ui-language";+import { t } from "@/lib/i18n";interface FlowchartWorkspaceProps {initialXml?: string;@@ -20,6 +22,7 @@ export function FlowchartWorkspace({ initialXml, onAddToChat, onXmlChange }: Floconst [selectedCells, setSelectedCells] = useState<any[]>([]);const lastEmittedXmlRef = useRef<string>("");const autosaveInFlightRef = useRef(false);+ const uiLang = useUiLanguage();// Default empty graphconst emptyXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';@@ -44,8 +47,8 @@ export function FlowchartWorkspace({ initialXml, onAddToChat, onXmlChange }: Floaction: 'export',format: 'xml',callback: true,- label: 'Add to Chat',- tooltip: 'Add current diagram to chat',+ label: t(uiLang, "flow.addToChat"),+ tooltip: t(uiLang, "flow.addToChat.tooltip"),icon: 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiPjxwYXRoIGQ9Ik0yMSAxNWExIDEgMCAwIDEtMSAxSDRhMSAxIDAgMCAxLTEtMVY4YTEgMSAwIDAgMSAxLTFoMTZhMSAxIDAgMCAxIDEgMXY3em0tNC03djEwaC0ydjZoLTJ2LTZoLTJ2LTZIOSIgLz48L3N2Zz4='}]}@@ -94,7 +97,7 @@ export function FlowchartWorkspace({ initialXml, onAddToChat, onXmlChange }: FloJSON.stringify({action: "export",format: "xml",- spin: "Saving...",+ spin: t(uiLang, "flow.saving"),}),"*");@@ -163,7 +166,7 @@ export function FlowchartWorkspace({ initialXml, onAddToChat, onXmlChange }: Floiframe.contentWindow.postMessage(JSON.stringify({action: 'export',format: 'xml',- spin: 'Updating chat...'+ spin: t(uiLang, "flow.updatingChat")}), '*');};@@ -172,16 +175,16 @@ export function FlowchartWorkspace({ initialXml, onAddToChat, onXmlChange }: Flo<ContextMenuTrigger className="w-full h-full relative overflow-hidden bg-muted flex"><iframeref={iframeRef}- src="https://embed.diagrams.net/?embed=1&ui=min&spin=1&noSaveBtn=1&noExitBtn=1&lang=zh&proto=json"+ src={`https://embed.diagrams.net/?embed=1&ui=min&spin=1&noSaveBtn=1&noExitBtn=1&lang=${uiLang === "zh" ? "zh" : "en"}&proto=json`}className="w-full h-full border-0 block"- title="流程图编辑器"+ title={t(uiLang, "flow.editorTitle")}/></ContextMenuTrigger><ContextMenuContent><ContextMenuItem onClick={handleAddToChat} className="cursor-pointer gap-2"><MessageSquarePlus className="w-4 h-4" />- <span>添加到对话</span>+ <span>{t(uiLang, "flow.addToChat")}</span></ContextMenuItem></ContextMenuContent></ContextMenu>diff --git a/src/components/workspaces/PptWorkspace.tsx b/src/components/workspaces/PptWorkspace.tsxindex 0f08cb0..7d41f09 100644--- a/src/components/workspaces/PptWorkspace.tsx+++ b/src/components/workspaces/PptWorkspace.tsx@@ -2,6 +2,7 @@ import React, { useState, useEffect, useRef } from 'react';import { motion } from "framer-motion";import { generateImage } from '@/lib/ai-client';import { pptService, PptPage } from '@/lib/ppt-service';+import { getTemplateGenerationPrompt } from '@/lib/ppt-prompts';import { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb, X, ArrowLeft, ArrowRight } from 'lucide-react';import {ContextMenu,@@ -12,6 +13,7 @@ import {import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { Textarea } from "@/components/ui/textarea";+import { useUiLanguage } from "@/lib/use-ui-language";interface SlideData {id: string;@@ -31,14 +33,17 @@ interface PptWorkspaceProps {data?: PptData;onAddToChat?: (json: string, name: string) => void;onPptReadyChange?: (ready: boolean) => void;+ onPptStageChange?: (stage: "outline" | "slides") => void;incomingEdit?: { id: string; payload: string } | null;+ onIncomingEditHandled?: (id: string) => void;+ onResetWorkspace?: () => void;}type CreationStep = 'idle' | 'input' | 'outline' | 'generating_content' | 'generating_images' | 'done';-type CreationMode = 'idea' | 'outline' | 'description';+type CreationMode = 'idea' | 'outline' | 'description' | 'beautify';type ReferenceFile = { id: string; filename: string; content: string; charCount: number };-type PresetTemplate = { id: string; name: string; path: string };+type PresetTemplate = { id: string; zhName: string; enName: string; path: string };type UploadTemplate = { id: string; name: string; dataUrl: string };type TemplateItem =| { id: string; name: string; kind: "preset"; previewSrc: string; presetPath: string }@@ -49,17 +54,19 @@ const PPT_TEMPLATE_HIDDEN_PRESETS_KEY = "ppt_template_hidden_presets_v1";const PPT_WORKSPACE_STORAGE_KEY = "unified-ai-workspace-ppt-state-v1";const PRESET_TEMPLATES: PresetTemplate[] = [- { id: "preset-tech-business", name: "科技商务", path: "/templates/template_b.png" },- { id: "preset-academic", name: "学术汇报", path: "/templates/template_academic.jpg" },- { id: "preset-minimal", name: "极简主义", path: "/templates/template_s.png" },- { id: "preset-vector", name: "矢量插画", path: "/templates/template_vector_illustration.png" },- { id: "preset-yellow", name: "活力黄", path: "/templates/template_y.png" },- { id: "preset-glass", name: "磨砂玻璃", path: "/templates/template_glass.png" },+ { id: "preset-tech-business", zhName: "科技商务", enName: "Tech Business", path: "/templates/template_b.png" },+ { id: "preset-academic", zhName: "学术汇报", enName: "Academic", path: "/templates/template_academic.jpg" },+ { id: "preset-minimal", zhName: "极简主义", enName: "Minimal", path: "/templates/template_s.png" },+ { id: "preset-vector", zhName: "矢量插画", enName: "Vector Illustration", path: "/templates/template_vector_illustration.png" },+ { id: "preset-yellow", zhName: "活力黄", enName: "Vibrant Yellow", path: "/templates/template_y.png" },+ { id: "preset-glass", zhName: "磨砂玻璃", enName: "Frosted Glass", path: "/templates/template_glass.png" },];const MODEL_CONCURRENCY = 30;-export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit }: PptWorkspaceProps) {+export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChange, incomingEdit, onIncomingEditHandled, onResetWorkspace }: PptWorkspaceProps) {+ const uiLang = useUiLanguage();+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);const initialPptState = (() => {if (typeof window === "undefined") return null;try {@@ -109,6 +116,9 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditreturn [];}});+ const [templateGeneratorOpen, setTemplateGeneratorOpen] = useState(false);+ const [templateGeneratorRequirement, setTemplateGeneratorRequirement] = useState("");+ const [templateGeneratorIsGenerating, setTemplateGeneratorIsGenerating] = useState(false);const [hiddenPresetTemplateIds, setHiddenPresetTemplateIds] = useState<string[]>(() => {if (typeof window === "undefined") return [];try {@@ -156,26 +166,33 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditreturn out;});const [isGeneratingImage, setIsGeneratingImage] = useState(false);+ const [isExporting, setIsExporting] = useState<null | "pptx" | "pdf">(null);// Creation Wizard Stateconst [creationStep, setCreationStep] = useState<CreationStep>(() => {const v = initialPptState?.creationStep;- if (v === "idle" || v === "input" || v === "outline" || v === "generating_content" || v === "generating_images" || v === "done") return v;+ if (v === "idle" || v === "input" || v === "outline" || v === "done") return v;return localSlides.length > 0 ? "done" : "idle";});+ useEffect(() => {+ onPptStageChange?.(creationStep === "done" ? "slides" : "outline");+ }, [creationStep, onPptStageChange]);const [creationMode, setCreationMode] = useState<CreationMode>(() => {const v = initialPptState?.creationMode;- return v === "idea" || v === "outline" || v === "description" ? v : "idea";+ return v === "idea" || v === "outline" || v === "description" || v === "beautify" ? v : "idea";});const [ideaInput, setIdeaInput] = useState(() => (typeof initialPptState?.ideaInput === "string" ? initialPptState.ideaInput : ""));const [outlineInput, setOutlineInput] = useState(() => (typeof initialPptState?.outlineInput === "string" ? initialPptState.outlineInput : ""));const [descriptionInput, setDescriptionInput] = useState(() => (typeof initialPptState?.descriptionInput === "string" ? initialPptState.descriptionInput : ""));+ const [beautifyRequirement, setBeautifyRequirement] = useState(() => (typeof initialPptState?.beautifyRequirement === "string" ? initialPptState.beautifyRequirement : ""));+ const [beautifyFile, setBeautifyFile] = useState<File | null>(null);const [referenceFiles, setReferenceFiles] = useState<ReferenceFile[]>([]);const [isParsingReferenceFiles, setIsParsingReferenceFiles] = useState(false);const [referencePreviewOpen, setReferencePreviewOpen] = useState(false);const [referencePreviewFile, setReferencePreviewFile] = useState<ReferenceFile | null>(null);const [progress, setProgress] = useState({ current: 0, total: 0, message: "" });const referenceFileInputRef = useRef<HTMLInputElement | null>(null);+ const beautifyFileInputRef = useRef<HTMLInputElement | null>(null);const [slideshowOpen, setSlideshowOpen] = useState(false);const [slideshowIndex, setSlideshowIndex] = useState(0);const [windowDimensions, setWindowDimensions] = useState({ width: 0, height: 0 });@@ -183,7 +200,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst templates: TemplateItem[] = [...PRESET_TEMPLATES.filter((t) => !hiddenPresetTemplateIds.includes(t.id))- .map((t) => ({ id: t.id, name: t.name, kind: "preset" as const, previewSrc: t.path, presetPath: t.path })),+ .map((t) => ({ id: t.id, name: uiLang === "zh" ? t.zhName : t.enName, kind: "preset" as const, previewSrc: t.path, presetPath: t.path })),...uploadedTemplates.map((t) => ({ id: t.id, name: t.name, kind: "upload" as const, previewSrc: t.dataUrl, dataUrl: t.dataUrl })),];@@ -220,6 +237,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditideaInput,outlineInput,descriptionInput,+ beautifyRequirement,updatedAt: Date.now(),}));@@ -237,6 +255,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditideaInput,outlineInput,descriptionInput,+ beautifyRequirement,]);useEffect(() => {@@ -317,7 +336,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditreader.onerror = reject;reader.readAsDataURL(file);});- const baseName = (name: string) => String(name || "").replace(/\.[^.]+$/, "") || "模板";+ const baseName = (name: string) => String(name || "").replace(/\.[^.]+$/, "") || tr("模板", "Template");const created: UploadTemplate[] = [];for (const f of imageFiles) {@@ -343,6 +362,40 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditawait addUploadedTemplates(files);};+ const addGeneratedTemplate = (dataUrl: string) => {+ const id = `generated-${Date.now()}-${Math.random().toString(16).slice(2)}`;+ const name = `${tr("AI模板", "AI Template")}-${Date.now()}`;+ const created: UploadTemplate = { id, name, dataUrl };+ setUploadedTemplates((prev) => [...prev, created]);+ setSelectedTemplateId(created.id);+ setTemplateImage(created.dataUrl);+ };++ const handleGenerateTemplate = async () => {+ const requirement = templateGeneratorRequirement.trim();+ if (!requirement) {+ alert(tr("请输入模板需求", "Please enter template requirements."));+ return;+ }+ setTemplateGeneratorIsGenerating(true);+ try {+ const prompt = getTemplateGenerationPrompt({ requirements: requirement, language: uiLang });+ const imageUrl = await generateImage({ prompt });+ if (!imageUrl) {+ alert(tr("模板生成失败,请重试", "Template generation failed. Please retry."));+ return;+ }+ addGeneratedTemplate(imageUrl);+ setTemplateGeneratorRequirement("");+ setTemplateGeneratorOpen(false);+ } catch (e: any) {+ console.error("Template generation failed", e);+ alert(tr("模板生成失败,请重试", "Template generation failed. Please retry."));+ } finally {+ setTemplateGeneratorIsGenerating(false);+ }+ };+const deleteTemplate = (item: TemplateItem) => {if (item.kind === "preset") {setHiddenPresetTemplateIds((prev) => (prev.includes(item.id) ? prev : [...prev, item.id]));@@ -392,7 +445,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditif (!id) continue;const next: SlideData = {id,- title: typeof inc?.title === "string" ? inc.title : (byId.get(id)?.title || `幻灯片`),+ title: typeof inc?.title === "string" ? inc.title : (byId.get(id)?.title || tr("幻灯片", "Slide")),content: Array.isArray(inc?.content) ? inc.content.map((x: any) => String(x)) : (byId.get(id)?.content || []),description: typeof inc?.description === "string" ? inc.description : byId.get(id)?.description,note: typeof inc?.note === "string" ? inc.note : byId.get(id)?.note,@@ -467,9 +520,14 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdituseEffect(() => {if (!incomingEdit?.payload) return;- Promise.resolve(applyIncomingSlideEdits(incomingEdit.payload)).catch((e) => {+ const id = incomingEdit.id;+ Promise.resolve(applyIncomingSlideEdits(incomingEdit.payload))+ .catch((e) => {console.error("Failed to apply incoming slide edits", e);- });+ })+ .finally(() => {+ if (id) onIncomingEditHandled?.(id);+ });}, [incomingEdit?.id]);const activeSlides = localSlides.length > 0 ? localSlides : [];@@ -573,9 +631,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditif (Array.isArray(parsed)) {return parsed.map((it: any, i: number) => ({id: String(it.id || `slide-${i}`),- title: String(it.title || `第 ${i + 1} 页`),+ title: String(it.title || tr(`第 ${i + 1} 页`, `Slide ${i + 1}`)),content: Array.isArray(it.content) ? it.content.map((x: any) => String(x)) : [],- description: typeof it.description === "string" ? it.description : undefined+ description: typeof it.description === "string" ? it.description : undefined,+ note: typeof it.note === "string" ? it.note : undefined,+ layout: typeof it.layout === "string" ? it.layout : undefined}));}} catch {@@ -599,7 +659,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditpushCurrent();current = {id: `slide-${slides.length + 1}`,- title: heading[2].trim() || `第 ${slides.length + 1} 页`,+ title: heading[2].trim() || tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`),content: []};continue;@@ -607,7 +667,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst bullet = l.match(/^[-•]\s+(.*)$/);if (bullet) {if (!current) {- current = { id: `slide-${slides.length + 1}`, title: `第 ${slides.length + 1} 页`, content: [] };+ current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };}current.content.push(bullet[1].trim());continue;@@ -615,11 +675,27 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst desc = l.match(/^description[::]\s*(.*)$/i);if (desc) {if (!current) {- current = { id: `slide-${slides.length + 1}`, title: `第 ${slides.length + 1} 页`, content: [] };+ current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };}current.description = desc[1].trim();continue;}+ const note = l.match(/^note[::]\s*(.*)$/i);+ if (note) {+ if (!current) {+ current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };+ }+ current.note = note[1].trim();+ continue;+ }+ const layout = l.match(/^layout[::]\s*(.*)$/i);+ if (layout) {+ if (!current) {+ current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };+ }+ current.layout = layout[1].trim();+ continue;+ }}pushCurrent();return slides.length > 0 ? slides : null;@@ -646,10 +722,219 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditawait Promise.all(results);};+ const isBeautifyPdfFile = (file: File) => {+ const name = String(file?.name || "").toLowerCase();+ return file?.type === "application/pdf" || name.endsWith(".pdf");+ };++ const isBeautifyPptxFile = (file: File) => {+ const name = String(file?.name || "").toLowerCase();+ return (+ file?.type === "application/vnd.openxmlformats-officedocument.presentationml.presentation" ||+ name.endsWith(".pptx")+ );+ };++ const sanitizeSlideHtml = (html: string) => {+ return String(html || "")+ .replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, "")+ .replace(/\son\w+=(?:"[^"]*"|'[^']*')/gi, "");+ };++ const renderHtmlToPngDataUrl = async (opts: { html: string; width: number; height: number; scale: number }) => {+ const html = sanitizeSlideHtml(opts.html);+ const width = Math.max(1, Math.floor(opts.width));+ const height = Math.max(1, Math.floor(opts.height));+ const scale = Number.isFinite(opts.scale) && opts.scale > 0 ? opts.scale : 1;++ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(width * scale)}" height="${Math.round(height * scale)}" viewBox="0 0 ${width} ${height}">+ <foreignObject x="0" y="0" width="100%" height="100%">+ <div xmlns="http://www.w3.org/1999/xhtml" style="width:${width}px;height:${height}px;overflow:hidden;background:#ffffff;">+ ${html}+ </div>+ </foreignObject>+</svg>`;++ const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });+ const url = URL.createObjectURL(blob);+ try {+ const img = new Image();+ img.decoding = "async";+ const loaded = new Promise<void>((resolve, reject) => {+ img.onload = () => resolve();+ img.onerror = reject;+ });+ img.src = url;+ await loaded;++ const canvas = document.createElement("canvas");+ canvas.width = Math.round(width * scale);+ canvas.height = Math.round(height * scale);+ const ctx = canvas.getContext("2d");+ if (!ctx) return "";+ ctx.clearRect(0, 0, canvas.width, canvas.height);+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);+ return canvas.toDataURL("image/png");+ } finally {+ URL.revokeObjectURL(url);+ }+ };++ const extractPdfPagesAsImages = async (file: File) => {+ const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/lib/pdf-utils");+ const objectUrl = URL.createObjectURL(file);+ try {+ const pdf = await getPdfDocumentFromUrl(objectUrl);+ const pageCount = (pdf as any)?.numPages ?? 0;+ const out: string[] = [];+ for (let pageNumber = 1; pageNumber <= pageCount; pageNumber += 1) {+ setProgress({+ current: pageNumber - 1,+ total: pageCount,+ message: tr(`正在解析 PDF... (${pageNumber - 1}/${pageCount})`, `Parsing PDF... (${pageNumber - 1}/${pageCount})`),+ });+ const canvas = document.createElement("canvas");+ await renderPdfPageToCanvas({ pdf, pageNumber, canvas, targetWidth: 1280 });+ const dataUrl = canvas.toDataURL("image/png");+ if (dataUrl && dataUrl.startsWith("data:image")) out.push(dataUrl);+ }+ setProgress({+ current: pageCount,+ total: pageCount,+ message: tr(`正在解析 PDF... (${pageCount}/${pageCount})`, `Parsing PDF... (${pageCount}/${pageCount})`),+ });+ return out;+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+ };++ const extractPptxSlidesAsImages = async (file: File) => {+ const buf = await file.arrayBuffer();+ const { pptxToHtml } = await import("@jvmr/pptx-to-html");+ const slidesHtml = await pptxToHtml(buf, { width: 960, height: 540, scaleToFit: true, letterbox: true });+ const out: string[] = [];+ for (let i = 0; i < slidesHtml.length; i += 1) {+ setProgress({+ current: i,+ total: slidesHtml.length,+ message: tr(`正在解析 PPT... (${i}/${slidesHtml.length})`, `Parsing PPT... (${i}/${slidesHtml.length})`),+ });+ const dataUrl = await renderHtmlToPngDataUrl({ html: slidesHtml[i], width: 960, height: 540, scale: 2 });+ if (dataUrl && dataUrl.startsWith("data:image")) out.push(dataUrl);+ }+ setProgress({+ current: slidesHtml.length,+ total: slidesHtml.length,+ message: tr(`正在解析 PPT... (${slidesHtml.length}/${slidesHtml.length})`, `Parsing PPT... (${slidesHtml.length}/${slidesHtml.length})`),+ });+ return out;+ };++ const handleBeautifyFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ const f = e.target.files?.[0] || null;+ e.target.value = "";+ setBeautifyFile(f);+ };++ const buildBeautifyInstruction = (req: string) => {+ const r = String(req || "").trim();+ const parts = [+ "Beautify the slide while preserving all original text, numbers, and meaning.",+ "Improve typography, spacing, alignment, color harmony, hierarchy, and visual balance.",+ "Do not add watermarks. Keep 16:9 landscape.",+ "Do not translate or rewrite text unless explicitly requested.",+ r ? `User requirements: ${r}` : "",+ ].filter(Boolean);+ return parts.join("\n");+ };++ const handleStartBeautify = async () => {+ const file = beautifyFile;+ if (!file) return;++ resetGenerationState();+ setCreationStep("generating_content");+ setProgress({ current: 0, total: 0, message: tr("正在解析文件...", "Parsing file...") });++ try {+ const pageImages = isBeautifyPdfFile(file)+ ? await extractPdfPagesAsImages(file)+ : isBeautifyPptxFile(file)+ ? await extractPptxSlidesAsImages(file)+ : [];++ if (pageImages.length === 0) {+ alert(tr("未能解析出页面图片,请确认文件格式(.pptx 或 .pdf)", "Failed to extract pages. Please upload .pptx or .pdf."));+ setCreationStep("idle");+ setProgress({ current: 0, total: 0, message: "" });+ return;+ }++ const slides: SlideData[] = pageImages.map((_, i) => ({+ id: `slide-${i + 1}`,+ title: tr(`第 ${i + 1} 页`, `Slide ${i + 1}`),+ content: [],+ description: "",+ }));++ const initialGenerated: Record<string, string> = {};+ const initialCurrent: Record<string, string> = {};+ const initialVersions: Record<string, Array<{ id: string; url: string; timestamp: number; type: "generated" | "edited"; instruction?: string }>> = {};++ for (let i = 0; i < slides.length; i += 1) {+ const slideId = slides[i].id;+ const url = pageImages[i];+ const versionId = `v-${Date.now()}-${Math.random().toString(16).slice(2)}`;+ initialGenerated[slideId] = url;+ initialCurrent[slideId] = versionId;+ initialVersions[slideId] = [{ id: versionId, url, timestamp: Date.now(), type: "generated", instruction: tr("原始页面", "Original") }];+ }++ setLocalSlides(slides);+ setGeneratedImages(initialGenerated);+ setCurrentImageVersionId(initialCurrent);+ setImageVersions(initialVersions);++ setCreationStep("generating_images");+ setProgress({ current: 0, total: slides.length, message: tr("正在美化渲染...", "Beautifying slides...") });++ const instruction = buildBeautifyInstruction(beautifyRequirement);+ const counter = { done: 0 };+ const tasks = slides.map((s, i) => async () => {+ try {+ const page: PptPage = { id: s.id, title: s.title, content: s.content || [], description: s.description || "" };+ const edited = await pptService.editPageImage(page, instruction, pageImages[i], templateImage || undefined);+ if (edited) pushImageVersion(s.id, edited, "edited", instruction);+ } catch (e) {+ console.error(`Beautify failed for slide ${i + 1}`, e);+ } finally {+ counter.done += 1;+ setProgress((prev) => ({+ ...prev,+ current: counter.done,+ total: slides.length,+ message: tr(`正在美化渲染... (${counter.done}/${slides.length})`, `Beautifying slides... (${counter.done}/${slides.length})`),+ }));+ }+ });++ await runInParallel(tasks, MODEL_CONCURRENCY);+ setCreationStep("done");+ onPptReadyChange?.(true);+ } catch (e) {+ console.error("Beautify failed", e);+ alert(tr("美化失败,请重试", "Beautify failed. Please retry."));+ setCreationStep("idle");+ } finally {+ setProgress({ current: 0, total: 0, message: "" });+ }+ };+const handleLoadOutline = () => {const slides = parseSlides(outlineInput);if (!slides || slides.length === 0) {- alert("未识别到大纲,请粘贴 JSON 数组或 Markdown 大纲。");+ alert(tr("未识别到大纲,请粘贴 JSON 数组或 Markdown 大纲。", "Outline not recognized. Paste a JSON array or a Markdown outline."));return;}resetGenerationState();@@ -670,21 +955,23 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit}setCreationStep('input');- setProgress({ current: 0, total: 0, message: "正在从描述生成大纲与画面..." });+ setProgress({ current: 0, total: 0, message: tr("正在从描述生成大纲与画面...", "Generating outline and visuals from description...") });try {const pages = await pptService.generateSlidesFromDescription(descriptionInput);const nextSlides: SlideData[] = pages.map((p, i) => ({id: `slide-${i + 1}`,title: p.title,content: p.content,- description: p.description+ description: p.description,+ note: p.note,+ layout: p.layout}));setLocalSlides(nextSlides);setCreationStep("outline");onPptReadyChange?.(true);} catch (e) {console.error("Failed to generate slides from description", e);- alert("从描述生成失败,请重试或改为粘贴 JSON/Markdown。");+ alert(tr("从描述生成失败,请重试或改为粘贴 JSON/Markdown。", "Failed to generate from description. Retry or paste JSON/Markdown." ));setCreationStep("idle");} finally {setProgress({ current: 0, total: 0, message: "" });@@ -696,7 +983,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditresetGenerationState();setCreationStep('input'); // Keep input visible but loading- setProgress({ current: 0, total: 0, message: "正在生成大纲..." });+ setProgress({ current: 0, total: 0, message: tr("正在生成大纲...", "Generating outline...") });try {const pages = await pptService.generateOutline(ideaInput);@@ -707,7 +994,9 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditid: `slide-${i + 1}`,title: p.title,content: p.content,- description: p.description+ description: p.description,+ note: p.note,+ layout: p.layout}));setLocalSlides(slides);setCreationStep('outline');@@ -716,7 +1005,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconsole.error("Failed to generate outline", e);const name = (e as any)?.name;const isAbort = name === "AbortError" || name === "APIUserAbortError";- const msg = isAbort ? "生成大纲超时或被中断(120s)。请检查网络/模型可用性后重试。" : e instanceof Error ? e.message : "生成大纲失败,请重试";+ const msg = isAbort+ ? tr("生成大纲超时或被中断(120s)。请检查网络/模型可用性后重试。", "Outline generation timed out or was interrupted (120s). Check network/model availability and retry.")+ : e instanceof Error+ ? e.message+ : tr("生成大纲失败,请重试", "Failed to generate outline. Please retry.");alert(msg);setCreationStep("idle");} finally {@@ -729,14 +1022,18 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit// Convert SlideData back to PptPage for serviceconst pages: PptPage[] = localSlides.map(s => ({+ id: s.id,title: s.title,content: s.content,+ description: s.description,+ note: s.note,+ layout: s.layout,status: 'outline_generated'}));try {// 1. Generate Descriptions- setProgress({ current: 0, total: pages.length, message: "正在生成页面内容描述..." });+ setProgress({ current: 0, total: pages.length, message: tr("正在生成页面内容描述...", "Generating slide content descriptions...") });// Parallel description generationconst descCounter = { done: 0 };@@ -747,10 +1044,19 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit// Update local state immediatelysetLocalSlides(prev => {const newSlides = [...prev];- newSlides[i] = {- ...newSlides[i],- content: result.content,- description: result.description+ const existing = newSlides[i];+ const hasManualContent = Array.isArray(existing?.content)+ ? existing.content.some((x) => String(x || "").trim())+ : false;+ const hasManualDescription = typeof existing?.description === "string" && existing.description.trim();+ const hasManualNote = typeof existing?.note === "string" && existing.note.trim();+ const hasManualLayout = typeof existing?.layout === "string" && existing.layout.trim();+ newSlides[i] = {+ ...existing,+ content: hasManualContent ? (existing.content || []) : result.content,+ description: hasManualDescription ? existing.description : result.description,+ note: hasManualNote ? existing.note : result.note,+ layout: hasManualLayout ? existing.layout : result.layout};return newSlides;});@@ -758,6 +1064,8 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit// Update pages array for next steppages[i].description = result.description;pages[i].content = result.content;+ pages[i].note = result.note;+ pages[i].layout = result.layout;} catch (e) {console.error(`Failed to generate description for slide ${i}`, e);} finally {@@ -765,7 +1073,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditsetProgress(prev => ({...prev,current: descCounter.done,- message: `正在生成页面内容描述... (${descCounter.done}/${pages.length})`+ message: tr(`正在生成页面内容描述... (${descCounter.done}/${pages.length})`, `Generating slide content descriptions... (${descCounter.done}/${pages.length})`)}));}});@@ -774,7 +1082,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit// 2. Generate ImagessetCreationStep('generating_images');- setProgress({ current: 0, total: pages.length, message: "正在生成页面渲染图..." });+ setProgress({ current: 0, total: pages.length, message: tr("正在生成页面渲染图...", "Rendering slide images...") });const imageCounter = { done: 0 };const imageTasks = pages.map((_, i) => async () => {@@ -791,7 +1099,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditsetProgress(prev => ({...prev,current: imageCounter.done,- message: `正在生成页面渲染图... (${imageCounter.done}/${pages.length})`+ message: tr(`正在生成页面渲染图... (${imageCounter.done}/${pages.length})`, `Rendering slide images... (${imageCounter.done}/${pages.length})`)}));}});@@ -803,7 +1111,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit} catch (e) {console.error("Full generation failed", e);- alert("生成过程中出错");+ alert(tr("生成过程中出错", "An error occurred during generation."));setCreationStep('done'); // Allow viewing what's doneonPptReadyChange?.(true);}@@ -812,7 +1120,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst handleGenerateImagesOnly = async () => {if (localSlides.length === 0) return;setCreationStep('generating_images');- setProgress({ current: 0, total: localSlides.length, message: "正在生成页面渲染图..." });+ setProgress({ current: 0, total: localSlides.length, message: tr("正在生成页面渲染图...", "Rendering slide images...") });const pages: PptPage[] = localSlides.map((s) => ({id: s.id,@@ -836,7 +1144,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditsetProgress(prev => ({...prev,current: imageCounter.done,- message: `正在生成页面渲染图... (${imageCounter.done}/${pages.length})`+ message: tr(`正在生成页面渲染图... (${imageCounter.done}/${pages.length})`, `Rendering slide images... (${imageCounter.done}/${pages.length})`)}));}});@@ -862,11 +1170,13 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditif (currentSlide.description) {const pages: PptPage[] = localSlides.map(s => ({+ id: s.id,title: s.title,content: s.content,- part: undefined, // simplifystatus: 'description_generated',- description: s.description+ description: s.description,+ note: s.note,+ layout: s.layout}));const pageIndex = localSlides.findIndex(s => s === currentSlide);imageUrl = await pptService.generatePageImage(pages[pageIndex], pages, templateImage || undefined);@@ -901,6 +1211,8 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit};const handleDownloadPpt = async () => {+ if (isExporting) return;+ setIsExporting("pptx");try {const pages: PptPage[] = activeSlides.map(s => ({id: s.id,@@ -918,11 +1230,15 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditawait pptService.exportPptx(pages, images, `presentation-${Date.now()}`);} catch (e) {console.error("Export failed", e);- alert("导出失败");+ alert(tr("导出失败", "Export failed"));+ } finally {+ setIsExporting(null);}};const handleDownloadPdf = async () => {+ if (isExporting) return;+ setIsExporting("pdf");try {const pages: PptPage[] = activeSlides.map(s => ({id: s.id,@@ -940,33 +1256,81 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditawait pptService.exportPdf(pages, images, `presentation-${Date.now()}`);} catch (e) {console.error("Export failed", e);- alert("导出失败");+ alert(tr("导出失败", "Export failed"));+ } finally {+ setIsExporting(null);+ }+ };++ const handleBackToStart = () => {+ const confirmed = window.confirm(+ tr(+ "返回开始将清空当前 PPT(建议先导出保存)。是否继续?",+ "Restart will clear the current deck (export first if needed). Continue?"+ )+ );+ if (!confirmed) return;+ if (typeof onResetWorkspace === "function") {+ onResetWorkspace();+ return;}+ try {+ localStorage.removeItem(PPT_WORKSPACE_STORAGE_KEY);+ } catch {+ }+ setLocalSlides([]);+ resetGenerationState();+ setCreationStep("idle");+ setIdeaInput("");+ setOutlineInput("");+ setDescriptionInput("");+ setBeautifyRequirement("");+ setBeautifyFile(null);+ setReferenceFiles([]);+ setTemplateImage(null);+ setSelectedTemplateId(null);+ setProgress({ current: 0, total: 0, message: "" });};// Render Creation Wizardif (activeSlides.length === 0 && (creationStep === 'idle' || creationStep === 'input' || creationStep === 'done')) {const tabs = [- { id: 'idea', label: '想法' },- { id: 'outline', label: '大纲' },- { id: 'description', label: '描述' },+ { id: 'idea', label: tr('想法', 'Idea') },+ { id: 'outline', label: tr('大纲', 'Outline') },+ { id: 'description', label: tr('描述', 'Description') },+ { id: 'beautify', label: tr('PPT美化', 'Beautify') },];const modeCopy = (() => {if (creationMode === "outline") {return {- hint: "已有大纲?直接粘贴即可快速生成,AI 将自动切分为结构化大纲",- placeholder: "粘贴你的 PPT 大纲…\n\n例如:\n第一部分:AI 的起源\n- 1950 年代的开端\n- 达特茅斯会议\n\n第二部分:发展历程\n- 专家系统\n- 深度学习\n…"+ hint: tr("已有大纲?直接粘贴即可快速生成,AI 将自动切分为结构化大纲", "Have an outline? Paste it and AI will structure it into slides."),+ placeholder: tr(+ "粘贴你的 PPT 大纲…\n\n例如:\n第一部分:AI 的起源\n- 1950 年代的开端\n- 达特茅斯会议\n\n第二部分:发展历程\n- 专家系统\n- 深度学习\n…",+ "Paste your PPT outline…\n\nExample:\nPart 1: Origins of AI\n- Early beginnings in the 1950s\n- Dartmouth workshop\n\nPart 2: Evolution\n- Expert systems\n- Deep learning\n…"+ )+ };+ }+ if (creationMode === "beautify") {+ return {+ hint: tr("上传 PPT/PDF,输入美化要求,然后并发渲染每一页", "Upload PPT/PDF, enter requirements, then beautify each page in parallel."),+ placeholder: tr(+ "例如:整体更高级、留白更充足、标题更醒目、配色更统一、增强对比度;保持原文案不变。",+ "e.g. More premium look, more whitespace, stronger title hierarchy, unified palette, higher contrast; keep all original text unchanged."+ )};}if (creationMode === "description") {return {- hint: "已有完整描述?AI 将自动解析出大纲并切分为每页描述,直接生成图片",- placeholder: "粘贴你的完整页面描述…\n\n例如:\n第 1 页\n标题:人工智能的诞生\n内容:1950 年,图灵提出“图灵测试”…\n\n第 2 页\n标题:AI 的发展历程\n内容:1950 年代:符号主义…\n…"+ hint: tr("已有完整描述?AI 将自动解析出大纲并切分为每页描述,直接生成图片", "Have a full description? AI will split it into slides and render images."),+ placeholder: tr(+ "粘贴你的完整页面描述…\n\n例如:\n第 1 页\n标题:人工智能的诞生\n内容:1950 年,图灵提出“图灵测试”…\n\n第 2 页\n标题:AI 的发展历程\n内容:1950 年代:符号主义…\n…",+ "Paste your full slide-by-slide description…\n\nExample:\nSlide 1\nTitle: The birth of AI\nContent: In 1950, Alan Turing proposed the Turing Test…\n\nSlide 2\nTitle: The evolution of AI\nContent: 1950s: symbolic approaches…\n…"+ )};}return {- hint: "输入你的想法,AI 将为你生成完整的 PPT",- placeholder: "例如:生成一份关于 AI 发展史的演讲 PPT"+ hint: tr("输入你的想法,AI 将为你生成完整的 PPT", "Describe your idea and AI will generate a full deck."),+ placeholder: tr("例如:生成一份关于 AI 发展史的演讲 PPT", "e.g. Create a presentation about the history of AI")};})();@@ -980,7 +1344,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="space-y-4"><label className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 flex items-center gap-2"><span className="w-6 h-6 rounded-full bg-blue-100 text-blue-600 text-xs flex items-center justify-center font-bold">1</span>- 选择或上传参考模板+ {tr("选择或上传参考模板", "Choose or upload a reference template")}</label><div className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(180px,1fr))]">@@ -989,10 +1353,22 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="w-10 h-10 rounded-full bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mb-2 group-hover:bg-blue-100 dark:group-hover:bg-blue-900/30 transition-colors"><Upload className="w-5 h-5" /></div>- <span className="text-xs font-medium">添加模板</span>+ <span className="text-xs font-medium">{tr("添加模板", "Add template")}</span></div><input type="file" accept="image/*" multiple className="hidden" onChange={handleTemplateUploadInputChange} /></label>+ <button+ type="button"+ onClick={() => setTemplateGeneratorOpen(true)}+ className="cursor-pointer border-2 border-dashed rounded-xl transition-all duration-200 overflow-hidden relative aspect-video flex flex-col items-center justify-center group border-zinc-200 dark:border-zinc-700 hover:border-blue-500 hover:bg-blue-50/30 dark:hover:bg-zinc-800/50"+ >+ <div className="flex flex-col items-center text-zinc-400 group-hover:text-blue-500 transition-colors">+ <div className="w-10 h-10 rounded-full bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center mb-2 group-hover:bg-blue-100 dark:group-hover:bg-blue-900/30 transition-colors">+ <Sparkles className="w-5 h-5" />+ </div>+ <span className="text-xs font-medium">{tr("AI生成模板", "AI generate")}</span>+ </div>+ </button>{templates.map((t) => (<divkey={t.id}@@ -1006,7 +1382,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<img src={t.previewSrc} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" alt={t.name} />{selectedTemplateId === t.id && (<div className="absolute top-2 left-2 rounded-full bg-blue-600 px-2 py-0.5 text-[10px] font-medium text-white shadow">- 已选择+ {tr("已选择", "Selected")}</div>)}<button@@ -1016,7 +1392,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditdeleteTemplate(t);}}className="absolute top-2 right-2 rounded-full bg-black/50 text-white p-1 opacity-0 group-hover:opacity-100 transition-opacity"- title="删除模板"+ title={tr("删除模板", "Delete template")}><X className="w-3.5 h-3.5" /></button>@@ -1032,7 +1408,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="space-y-4"><label className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 flex items-center gap-2"><span className="w-6 h-6 rounded-full bg-blue-100 text-blue-600 text-xs flex items-center justify-center font-bold">2</span>- 输入内容+ {tr("输入内容", "Input")}</label>{/* Segmented Control */}@@ -1077,93 +1453,184 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditclassName="space-y-3"><div className="flex items-center gap-2 text-sm text-zinc-700 dark:text-zinc-200">- <Lightbulb className="w-4 h-4 text-amber-500" />+ {creationMode === "beautify" ? <Sparkles className="w-4 h-4 text-blue-600" /> : <Lightbulb className="w-4 h-4 text-amber-500" />}<span>{modeCopy.hint}</span></div>- <div className="relative">- <textarea- value={creationMode === "idea" ? ideaInput : creationMode === "outline" ? outlineInput : descriptionInput}- onChange={(e) => {- const v = e.target.value;- if (creationMode === "idea") setIdeaInput(v);- else if (creationMode === "outline") setOutlineInput(v);- else setDescriptionInput(v);- }}- className="w-full h-40 p-4 pb-12 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all resize-none outline-none"- placeholder={modeCopy.placeholder}++ {creationMode === "beautify" ? (+ <div className="space-y-3">+ <input+ ref={beautifyFileInputRef}+ type="file"+ accept=".pptx,.pdf,application/pdf,application/vnd.openxmlformats-officedocument.presentationml.presentation"+ className="hidden"+ onChange={handleBeautifyFileInputChange}/>- <button- type="button"- onClick={() => referenceFileInputRef.current?.click()}- disabled={isParsingReferenceFiles}- className="absolute bottom-3 right-3 inline-flex items-center gap-2 rounded-lg border border-zinc-200 dark:border-zinc-700 bg-white/80 dark:bg-zinc-900/60 px-3 py-1.5 text-xs text-zinc-700 dark:text-zinc-200 shadow-sm hover:bg-white dark:hover:bg-zinc-900 transition-colors disabled:opacity-60"- >- {isParsingReferenceFiles ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Upload className="w-3.5 h-3.5" />}- 上传文件- </button>- </div>- <div className="flex items-center justify-between gap-3">- <div className="text-xs text-zinc-500 dark:text-zinc-400">- 上传 PDF/文本作为参考资料(可选)+ <div className="flex items-center justify-between gap-3 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 px-4 py-3">+ <div className="min-w-0">+ <div className="text-sm font-medium text-zinc-900 dark:text-zinc-100">{tr("上传 PPT/PDF", "Upload PPT/PDF")}</div>+ <div className="text-xs text-zinc-500 dark:text-zinc-400 truncate">+ {beautifyFile ? beautifyFile.name : tr("未选择文件", "No file selected")}+ </div>+ </div>+ <Button+ type="button"+ variant="outline"+ className="shrink-0"+ onClick={() => beautifyFileInputRef.current?.click()}+ >+ <Upload className="w-4 h-4 mr-2" />+ {tr("选择文件", "Choose")}+ </Button></div>- {referenceFiles.length > 0 && (++ <textarea+ value={beautifyRequirement}+ onChange={(e) => setBeautifyRequirement(e.target.value)}+ className="w-full h-36 p-4 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all resize-none outline-none"+ placeholder={modeCopy.placeholder}+ />+ </div>+ ) : (+ <>+ <div className="relative">+ <textarea+ value={creationMode === "idea" ? ideaInput : creationMode === "outline" ? outlineInput : descriptionInput}+ onChange={(e) => {+ const v = e.target.value;+ if (creationMode === "idea") setIdeaInput(v);+ else if (creationMode === "outline") setOutlineInput(v);+ else setDescriptionInput(v);+ }}+ className="w-full h-40 p-4 pb-12 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all resize-none outline-none"+ placeholder={modeCopy.placeholder}+ /><buttontype="button"- onClick={() => setReferenceFiles([])}- className="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"+ onClick={() => referenceFileInputRef.current?.click()}disabled={isParsingReferenceFiles}+ className="absolute bottom-3 right-3 inline-flex items-center gap-2 rounded-lg border border-zinc-200 dark:border-zinc-700 bg-white/80 dark:bg-zinc-900/60 px-3 py-1.5 text-xs text-zinc-700 dark:text-zinc-200 shadow-sm hover:bg-white dark:hover:bg-zinc-900 transition-colors disabled:opacity-60">- 清空+ {isParsingReferenceFiles ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Upload className="w-3.5 h-3.5" />}+ {tr("上传文件", "Upload files")}</button>- )}- </div>+ </div>- {referenceFiles.length > 0 && (- <div className="grid gap-2">- {referenceFiles.map((f) => (- <div key={f.id} className="flex items-center justify-between gap-3 rounded-lg border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/40 px-3 py-2">- <button- type="button"- onClick={() => openReferencePreview(f)}- className="flex items-center gap-2 min-w-0 text-left"- >- <FileText className="w-4 h-4 text-zinc-500 flex-shrink-0" />- <span className="truncate text-sm text-zinc-800 dark:text-zinc-100">{f.filename}</span>- <span className="text-xs text-zinc-500 dark:text-zinc-400 flex-shrink-0">({f.charCount} chars)</span>- </button>- <button- type="button"- className="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"- onClick={() => setReferenceFiles((prev) => prev.filter((x) => x.id !== f.id))}- >- 移除- </button>- </div>- ))}+ <div className="flex items-center justify-between gap-3">+ <div className="text-xs text-zinc-500 dark:text-zinc-400">+ {tr("上传 PDF/文本作为参考资料(可选)", "Upload PDF/text as reference (optional)")}+ </div>+ {referenceFiles.length > 0 && (+ <button+ type="button"+ onClick={() => setReferenceFiles([])}+ className="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"+ disabled={isParsingReferenceFiles}+ >+ {tr("清空", "Clear")}+ </button>+ )}</div>++ {referenceFiles.length > 0 && (+ <div className="grid gap-2">+ {referenceFiles.map((f) => (+ <div key={f.id} className="flex items-center justify-between gap-3 rounded-lg border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/40 px-3 py-2">+ <button+ type="button"+ onClick={() => openReferencePreview(f)}+ className="flex items-center gap-2 min-w-0 text-left"+ >+ <FileText className="w-4 h-4 text-zinc-500 flex-shrink-0" />+ <span className="truncate text-sm text-zinc-800 dark:text-zinc-100">{f.filename}</span>+ <span className="text-xs text-zinc-500 dark:text-zinc-400 flex-shrink-0">({f.charCount} chars)</span>+ </button>+ <button+ type="button"+ className="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"+ onClick={() => setReferenceFiles((prev) => prev.filter((x) => x.id !== f.id))}+ >+ {tr("移除", "Remove")}+ </button>+ </div>+ ))}+ </div>+ )}+ </>)}</motion.div></div><Button- onClick={creationMode === "idea" ? handleGenerateOutline : creationMode === "outline" ? handleLoadOutline : handleLoadDescriptions}- disabled={Boolean(progress.message) || isParsingReferenceFiles || (creationMode === "idea" ? !ideaInput.trim() : creationMode === "outline" ? !outlineInput.trim() : !descriptionInput.trim())}+ onClick={creationMode === "beautify" ? handleStartBeautify : creationMode === "idea" ? handleGenerateOutline : creationMode === "outline" ? handleLoadOutline : handleLoadDescriptions}+ disabled={Boolean(progress.message) || (creationMode === "beautify" ? !beautifyFile : isParsingReferenceFiles || (creationMode === "idea" ? !ideaInput.trim() : creationMode === "outline" ? !outlineInput.trim() : !descriptionInput.trim()))}className="w-full py-6 text-lg font-medium bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white shadow-lg shadow-blue-500/20 rounded-xl transition-all hover:scale-[1.01] active:scale-[0.99]">{progress.message ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : <Sparkles className="w-5 h-5 mr-2" />}- {progress.message || (creationMode === "idea" ? "开始生成大纲" : creationMode === "outline" ? "载入大纲" : "载入描述")}+ {progress.message || (creationMode === "beautify" ? tr("开始渲染", "Start rendering") : creationMode === "idea" ? tr("开始生成大纲", "Generate outline") : creationMode === "outline" ? tr("载入大纲", "Load outline") : tr("载入描述", "Load descriptions"))}</Button></div><Dialog open={referencePreviewOpen} onOpenChange={setReferencePreviewOpen}><DialogContent className="max-w-3xl"><DialogHeader>- <DialogTitle>{referencePreviewFile?.filename || "参考文件"}</DialogTitle>+ <DialogTitle>{referencePreviewFile?.filename || tr("参考文件", "Reference file")}</DialogTitle></DialogHeader><Textarea value={referencePreviewFile?.content || ""} readOnly className="min-h-[420px] font-mono text-xs" /></DialogContent></Dialog>++ <Dialog open={templateGeneratorOpen} onOpenChange={setTemplateGeneratorOpen}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>{tr("AI生成模板", "AI Template Generator")}</DialogTitle>+ </DialogHeader>+ <div className="space-y-4">+ <div className="text-xs text-zinc-500 dark:text-zinc-400">+ {tr("生成的模板会自动加入模板列表,可随时删除。", "Generated templates will be added to the template list automatically and can be deleted anytime.")}+ </div>+ <Textarea+ value={templateGeneratorRequirement}+ onChange={(e) => setTemplateGeneratorRequirement(e.target.value)}+ placeholder={tr(+ "例如:科技感、深色背景、蓝紫渐变、玻璃拟态、留白充足、适合企业汇报;不要出现任何文字。",+ "e.g. Futuristic, dark background, blue-purple gradient, glassmorphism, generous whitespace; no text."+ )}+ className="min-h-[140px]"+ disabled={templateGeneratorIsGenerating}+ />+ <div className="flex justify-end gap-3">+ <Button+ type="button"+ variant="outline"+ onClick={() => setTemplateGeneratorOpen(false)}+ disabled={templateGeneratorIsGenerating}+ >+ {tr("取消", "Cancel")}+ </Button>+ <Button+ type="button"+ onClick={handleGenerateTemplate}+ disabled={templateGeneratorIsGenerating || !templateGeneratorRequirement.trim()}+ className="bg-blue-600 hover:bg-blue-700"+ >+ {templateGeneratorIsGenerating ? (+ <>+ <Loader2 className="w-4 h-4 mr-2 animate-spin" />+ {tr("生成中...", "Generating...")}+ </>+ ) : (+ <>+ <Sparkles className="w-4 h-4 mr-2" />+ {tr("生成并保存", "Generate & Save")}+ </>+ )}+ </Button>+ </div>+ </div>+ </DialogContent>+ </Dialog></div></div></div>@@ -1177,8 +1644,8 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="flex-1 overflow-auto p-6"><div className="w-full min-h-full bg-white dark:bg-zinc-800 rounded-xl shadow-sm flex flex-col overflow-hidden"><div className="p-6 border-b border-border flex justify-between items-center">- <h3 className="font-semibold text-lg">{creationMode === "description" ? "确认内容与描述" : "确认大纲"}</h3>- <div className="text-sm text-muted-foreground">共 {localSlides.length} 页</div>+ <h3 className="font-semibold text-lg">{creationMode === "description" ? tr("确认内容与描述", "Review content & descriptions") : tr("确认大纲", "Review outline")}</h3>+ <div className="text-sm text-muted-foreground">{tr(`共 ${localSlides.length} 页`, `${localSlides.length} slides`)}</div></div><div className="flex-1 overflow-y-auto p-6 space-y-4">@@ -1200,7 +1667,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit/><Button variant="outline" size="sm" onClick={() => handleAddSlideToChat(slide)} className="shrink-0"><MessageSquarePlus className="w-4 h-4 mr-2" />- 加入对话+ {tr("加入对话", "Add to chat")}</Button></div><div className="space-y-1">@@ -1220,9 +1687,35 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit</div>))}</div>- {creationMode === "description" && (- <div className="pt-2">- <div className="text-xs font-medium text-foreground mb-1">画面描述(用于生图)</div>+ <div className="pt-3 grid gap-3">+ <div>+ <div className="text-xs font-medium text-foreground mb-1">{tr("布局提示(layout)", "Layout hint (layout)")}</div>+ <input+ value={slide.layout || ""}+ onChange={(e) => {+ const newSlides = [...localSlides];+ newSlides[i].layout = e.target.value;+ setLocalSlides(newSlides);+ }}+ className="w-full h-9 px-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ placeholder={tr("例如:cover / title+bullets / two-column / left-text-right-image", "e.g. cover / title+bullets / two-column / left-text-right-image")}+ />+ </div>+ <div>+ <div className="text-xs font-medium text-foreground mb-1">{tr("演讲者备注(note)", "Speaker notes (note)")}</div>+ <textarea+ value={slide.note || ""}+ onChange={(e) => {+ const newSlides = [...localSlides];+ newSlides[i].note = e.target.value;+ setLocalSlides(newSlides);+ }}+ className="w-full h-20 p-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ placeholder={tr("例如:这一页强调三个关键点;讲解时先抛出问题再给答案…", "e.g. Emphasize three key points; start with a question, then answer it…")}+ />+ </div>+ <div>+ <div className="text-xs font-medium text-foreground mb-1">{tr("画面描述(description,用于生图)", "Visual description (description)")}</div><textareavalue={slide.description || ""}onChange={(e) => {@@ -1230,21 +1723,21 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditnewSlides[i].description = e.target.value;setLocalSlides(newSlides);}}- className="w-full h-20 p-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- placeholder="例如:科技感蓝色渐变背景,中心是抽象的 AI 芯片与电路纹理,干净留白…"+ className="w-full h-24 p-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ placeholder={tr("例如:科技感蓝色渐变背景,中心是抽象的 AI 芯片与电路纹理,干净留白…", "e.g. Futuristic blue gradient background, abstract AI chip and circuit textures, clean whitespace…")}/></div>- )}+ </div></div></div>))}</div><div className="p-6 border-t border-border bg-zinc-50/50 dark:bg-zinc-900/50 flex justify-end gap-3">- <Button variant="outline" onClick={() => setCreationStep('idle')}>返回修改</Button>+ <Button variant="outline" onClick={() => setCreationStep('idle')}>{tr("返回修改", "Back")}</Button><Button onClick={creationMode === "description" ? handleGenerateImagesOnly : handleGenerateFullPpt} className="bg-blue-600 hover:bg-blue-700"><Sparkles className="w-4 h-4 mr-2" />- {creationMode === "description" ? "开始渲染图片" : "生成完整 PPT"}+ {creationMode === "description" ? tr("开始渲染图片", "Render images") : tr("生成完整 PPT", "Generate full deck")}</Button></div></div>@@ -1255,6 +1748,10 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit// Render Progressif (creationStep === 'generating_content' || creationStep === 'generating_images') {+ const progressRatio = progress.total > 0 ? progress.current / progress.total : 0;+ const clampedRatio = Math.max(0, Math.min(1, progressRatio));+ const dash = clampedRatio * 251.2;+ const percent = Math.round(clampedRatio * 100);return (<div className="w-full h-full bg-zinc-50 dark:bg-zinc-900 flex flex-col overflow-hidden"><div className="flex-1 flex items-center justify-center p-6">@@ -1262,16 +1759,16 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="relative w-20 h-20 mx-auto"><svg className="w-full h-full" viewBox="0 0 100 100"><circle className="text-zinc-200 dark:text-zinc-700 stroke-current" strokeWidth="8" cx="50" cy="50" r="40" fill="transparent"></circle>- <circle className="text-blue-600 stroke-current transition-all duration-300 ease-in-out origin-center -rotate-90" strokeWidth="8" strokeLinecap="round" cx="50" cy="50" r="40" fill="transparent" strokeDasharray={`${(progress.current / progress.total) * 251.2} 251.2`}></circle>+ <circle className="text-blue-600 stroke-current transition-all duration-300 ease-in-out origin-center -rotate-90" strokeWidth="8" strokeLinecap="round" cx="50" cy="50" r="40" fill="transparent" strokeDasharray={`${dash} 251.2`}></circle></svg><div className="absolute inset-0 flex items-center justify-center text-sm font-bold">- {Math.round((progress.current / progress.total) * 100)}%+ {percent}%</div></div><div className="space-y-2"><h3 className="font-semibold text-lg">AI 正在创作中</h3>- <p className="text-sm text-muted-foreground">{progress.message}</p>+ <p className="text-sm text-muted-foreground">{progress.message || (creationStep === "generating_content" ? tr("正在生成内容…", "Generating content…") : tr("正在渲染图片…", "Rendering images…"))}</p></div><div className="flex justify-center gap-2 text-xs text-muted-foreground">@@ -1297,36 +1794,43 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit{/* Toolbar */}<div className="h-14 px-4 bg-white dark:bg-zinc-800 border-b border-zinc-200 dark:border-zinc-700 flex justify-between items-center shadow-sm z-10"><div className="flex items-center gap-4">- <h2 className="font-semibold text-sm text-foreground">PPT 演示文稿</h2>+ <h2 className="font-semibold text-sm text-foreground">{tr("PPT 演示文稿", "PPT Deck")}</h2><div className="h-4 w-px bg-border"></div>+ <button+ onClick={handleBackToStart}+ className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm"+ >+ <ArrowLeft className="w-3.5 h-3.5" />+ <span>{tr("返回开始", "Back")}</span>+ </button><buttononClick={() => setSlideshowOpen(true)}disabled={activeSlides.length === 0}className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm"><Play className="w-3.5 h-3.5" />- <span>播放</span>+ <span>{tr("播放", "Play")}</span></button><div className="h-4 w-px bg-border"></div><buttononClick={handleDownloadPpt}- disabled={activeSlides.length === 0}+ disabled={activeSlides.length === 0 || !!isExporting}className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm">- <Download className="w-3.5 h-3.5" />- <span>导出 PPTX</span>+ {isExporting === "pptx" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Download className="w-3.5 h-3.5" />}+ <span>{isExporting === "pptx" ? tr("导出中…", "Exporting…") : tr("导出 PPTX", "Export PPTX")}</span></button><buttononClick={handleDownloadPdf}- disabled={activeSlides.length === 0}+ disabled={activeSlides.length === 0 || !!isExporting}className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm">- <Download className="w-3.5 h-3.5" />- <span>导出 PDF</span>+ {isExporting === "pdf" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Download className="w-3.5 h-3.5" />}+ <span>{isExporting === "pdf" ? tr("导出中…", "Exporting…") : tr("导出 PDF", "Export PDF")}</span></button></div><div className="text-xs text-muted-foreground">- {activeSlides.length > 0 ? `第 ${currentSlideIndex + 1} / ${activeSlides.length} 页` : "空文档"}+ {activeSlides.length > 0 ? tr(`第 ${currentSlideIndex + 1} / ${activeSlides.length} 页`, `Slide ${currentSlideIndex + 1} / ${activeSlides.length}`) : tr("空文档", "Empty")}</div></div>@@ -1358,7 +1862,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditonClick={() => handleAddSlideToChat(slide)}><Presentation className="w-3 h-3" />- 加入对话+ {tr("加入对话", "Add to chat")}</Button></div>{/* Thumbnail Preview */}@@ -1386,7 +1890,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<ContextMenuContent><ContextMenuItem onClick={() => handleAddSlideToChat(slide)} className="gap-2"><MessageSquarePlus className="w-4 h-4" />- <span>把此页添加到对话</span>+ <span>{tr("把此页添加到对话", "Add this slide to chat")}</span></ContextMenuItem></ContextMenuContent></ContextMenu>@@ -1397,7 +1901,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="inline-flex items-center justify-center w-12 h-12 rounded-full bg-muted mb-3"><Presentation className="w-6 h-6 text-muted-foreground" /></div>- <p className="text-sm text-muted-foreground">在右侧对话框中输入需求<br/>让 AI 为您生成 PPT</p>+ <p className="text-sm text-muted-foreground">+ {uiLang === "zh" ? "在右侧对话框中输入需求" : "Describe your needs in the chat on the right"}+ <br />+ {uiLang === "zh" ? "让 AI 为您生成 PPT" : "Let AI generate your PPT"}+ </p></div>)}</div>@@ -1482,7 +1990,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="absolute inset-0 z-50 flex items-center justify-center bg-white/50 backdrop-blur-[2px]"><div className="flex flex-col items-center gap-3 bg-white shadow-xl px-6 py-4 rounded-xl border border-blue-100"><Loader2 className="w-6 h-6 text-blue-600 animate-spin" />- <span className="text-sm font-medium text-zinc-700">幻灯片正在生成中...</span>+ <span className="text-sm font-medium text-zinc-700">{tr("幻灯片正在生成中...", "Generating slides...")}</span></div></div>)}@@ -1498,7 +2006,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit) : (<div className="text-muted-foreground flex flex-col items-center"><ImageIcon className="w-16 h-16 mb-4 opacity-20" />- <p>暂无幻灯片</p>+ <p>{tr("暂无幻灯片", "No slides yet")}</p></div>)}</div>diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.tsindex c3b5afb..554fc6d 100644--- a/src/lib/ai-client.ts+++ b/src/lib/ai-client.ts@@ -1,4 +1,6 @@import OpenAI from 'openai';+import { getUiLanguage } from "@/lib/ui-language";+import { t } from "@/lib/i18n";// Configuration Interfacesexport interface AIConfig {@@ -144,6 +146,37 @@ export interface ChatMessage {content: string;}+const UI_LANG_POLICY_PREFIX = "UI_LANG_POLICY:";++function getUiLanguagePolicySystemMessage(): ChatMessage {+ const uiLang = getUiLanguage();+ if (uiLang === "en") {+ return {+ role: "system",+ content:+ `${UI_LANG_POLICY_PREFIX} uiLang=en\n` ++ "All assistant outputs must be in English.\n" ++ "- Do not output Chinese characters.\n" ++ "- If an agent must output code/JSON/XML only, keep the required format and keep any fixed identifiers/schema keys; write any human-readable strings in English unless the schema mandates otherwise.",+ };+ }+ return {+ role: "system",+ content:+ `${UI_LANG_POLICY_PREFIX} uiLang=zh\n` ++ "All assistant outputs must be in Simplified Chinese.\n" ++ "- Do not output English unless required for code, identifiers, proper nouns, or file paths.\n" ++ "- If an agent must output code/JSON/XML only, keep the required format and keep any fixed identifiers/schema keys; write any human-readable strings in Chinese unless the schema mandates otherwise.",+ };+}++function applyUiLanguagePolicy(messages: ChatMessage[]): ChatMessage[] {+ const filtered = (messages || []).filter(+ (m) => !(m.role === "system" && String(m.content || "").startsWith(UI_LANG_POLICY_PREFIX))+ );+ return [getUiLanguagePolicySystemMessage(), ...filtered];+}+// Stream Chat Messageexport async function streamChatMessage(messages: ChatMessage[],@@ -156,14 +189,14 @@ export async function streamChatMessage(const client = getClient();if (!config.apiKey) {- throw new Error("请先在设置中配置 API Key");+ throw new Error(t(getUiLanguage(), "error.missingApiKey"));}try {const stream = await client.chat.completions.create({model: model || config.chatModel,- messages: messages,+ messages: applyUiLanguagePolicy(messages),stream: true,},signal ? ({ signal } as any) : undefined@@ -217,14 +250,14 @@ export async function generateChatMessage(messages: ChatMessage[], model?: strinconst client = getClient();if (!config.apiKey) {- throw new Error("请先在设置中配置 API Key");+ throw new Error(t(getUiLanguage(), "error.missingApiKey"));}try {const resp = await client.chat.completions.create({model: model || config.chatModel,- messages,+ messages: applyUiLanguagePolicy(messages),stream: false,},mergedSignal ? ({ signal: mergedSignal } as any) : undefined@@ -351,7 +384,7 @@ export async function generateImage(request: ImageGenerationRequest, signal?: Abconst config = getAIConfig();if (!config.apiKey) {- throw new Error("请先在设置中配置 API Key");+ throw new Error(t(getUiLanguage(), "error.missingApiKey"));}let referenceImageUrl = request.referenceImageUrl;diff --git a/src/lib/cad-agents.ts b/src/lib/cad-agents.tsnew file mode 100644index 0000000..c2bb236--- /dev/null+++ b/src/lib/cad-agents.ts@@ -0,0 +1,8 @@+import cadPlanAgentPrompt from "../../agent/cad/plan.md?raw";+import cadSvgGenerateAgentPrompt from "../../agent/cad/svg-generate.md?raw";+import cadSvgPatchAgentPrompt from "../../agent/cad/svg-patch.md?raw";++export const CAD_PLAN_AGENT_PROMPT = cadPlanAgentPrompt;+export const CAD_SVG_GENERATE_AGENT_PROMPT = cadSvgGenerateAgentPrompt;+export const CAD_SVG_PATCH_AGENT_PROMPT = cadSvgPatchAgentPrompt;+diff --git a/src/lib/cad-tasks.ts b/src/lib/cad-tasks.tsindex 0b71e67..5daaee8 100644--- a/src/lib/cad-tasks.ts+++ b/src/lib/cad-tasks.ts@@ -1,11 +1,8 @@import type { ChatMessage } from "@/lib/ai-client";-import cadTasksSystemHint from "../../agent/cad/tasks-system-hint.md?raw";import cadBomPromptTemplate from "../../agent/cad/bom-prompt.md?raw";import cadImagesPromptTemplate from "../../agent/cad/images-prompt.md?raw";-export const CAD_TASKS_SYSTEM_HINT = cadTasksSystemHint;-function applyTemplate(template: string, vars: Record<string, string>) {let out = String(template || "");for (const [k, v] of Object.entries(vars)) {@@ -29,13 +26,10 @@ export function buildCadImagesPrompt(args: { planJson: string; svg2d: string })}export function buildCadTasksSystemContent(args: {- systemPrompt: string;globalSystemPrompt: string;globalConstraints: string;}) {- return [args.systemPrompt, args.globalSystemPrompt, args.globalConstraints, CAD_TASKS_SYSTEM_HINT]- .filter(Boolean)- .join("\n\n");+ return [args.globalSystemPrompt, args.globalConstraints].filter(Boolean).join("\n\n");}export function buildCadBomMessages(args: {@@ -59,4 +53,3 @@ export function buildCadImagesMessages(args: {{ role: "user", content: buildCadImagesPrompt({ planJson: args.planJson, svg2d: args.svg2d }) },];}-diff --git a/src/lib/i18n.ts b/src/lib/i18n.tsnew file mode 100644index 0000000..c000ee9--- /dev/null+++ b/src/lib/i18n.ts@@ -0,0 +1,92 @@+import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";++type Dict = Record<string, { zh: string; en: string }>;++const dict: Dict = {+ "app.refresh": { zh: "刷新页面", en: "Refresh" },+ "app.tryContinue": { zh: "尝试继续", en: "Try to continue" },++ "chat.hello": { zh: "你好!我是你的 AI 助手。请告诉我你的需求。", en: "Hi! I'm your AI assistant. Tell me what you need." },+ "chat.newChat": { zh: "你好!新对话已开始。请告诉我你的需求。", en: "Hi! New chat started. Tell me what you need." },+ "chat.cleared": { zh: "你好!对话记录已清空。", en: "Hi! Chat history has been cleared." },++ "common.cancel": { zh: "取消", en: "Cancel" },+ "common.save": { zh: "保存", en: "Save" },+ "common.clear": { zh: "清空", en: "Clear" },++ "settings.title": { zh: "配置设置", en: "Settings" },+ "settings.subtitle": { zh: "配置 AI 模型参数与 API 密钥", en: "Configure model parameters and API keys" },+ "settings.language": { zh: "界面语言", en: "Language" },+ "settings.buttonTitle": { zh: "设置", en: "Settings" },+ "settings.chatModel": { zh: "对话模型 (Chat Model)", en: "Chat Model" },+ "settings.imageModel": { zh: "绘图模型 (Image Model)", en: "Image Model" },++ "reset.title": { zh: "清空对话", en: "Clear Chat" },+ "reset.desc": {+ zh: "清空对话将同时清空当前工作台内容。此操作无法撤销。PPT 工作台会回到开始页面。",+ en: "Clearing chat will also clear the current workspace content. This action cannot be undone. The PPT workspace will return to the start page.",+ },++ "workspace.flow.title": { zh: "流程图助手", en: "Flow Assistant" },+ "workspace.flow.placeholder": { zh: "描述流程…", en: "Describe the flow…" },+ "workspace.cad.title": { zh: "CAD 助手", en: "CAD Assistant" },+ "workspace.cad.placeholder": { zh: "描述 CAD…", en: "Describe the CAD…" },+ "workspace.ppt.title": { zh: "PPT 助手", en: "PPT Assistant" },+ "workspace.ppt.placeholder": { zh: "描述 PPT…", en: "Describe the PPT…" },+ "workspace.default.title": { zh: "AI 助手", en: "AI Assistant" },++ "chat.stop": { zh: "暂停", en: "Pause" },+ "chat.send": { zh: "发送", en: "Send" },+ "chat.uploadFile": { zh: "上传文件", en: "Upload file" },+ "chat.uploadImage": { zh: "上传图片", en: "Upload image" },+ "chat.rules": { zh: "规则", en: "Rules" },+ "chat.expand": { zh: "展开聊天", en: "Expand chat" },+ "chat.globalConstraints": { zh: "全局约束", en: "Global constraints" },+ "chat.newChatTitle": { zh: "新开对话", en: "New chat" },+ "chat.historyTitle": { zh: "版本历史", en: "History" },+ "chat.clearChatTitle": { zh: "清空对话", en: "Clear chat" },+ "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.ppt": { zh: "PPT演示", en: "PPT" },++ "flow.addToChat": { zh: "添加到对话", en: "Add to chat" },+ "flow.addToChat.tooltip": { zh: "将当前图表添加到对话", en: "Add current diagram to chat" },+ "flow.saving": { zh: "保存中...", en: "Saving..." },+ "flow.updatingChat": { zh: "更新对话中...", en: "Updating chat..." },+ "flow.editorTitle": { zh: "流程图编辑器", en: "Flowchart Editor" },++ "history.title": { zh: "版本历史", en: "Version History" },+ "history.clear": { zh: "清空", en: "Clear" },+ "history.empty": { zh: "暂无历史记录", en: "No history yet" },+ "history.restore": { zh: "恢复", en: "Restore" },+ "history.chars": { zh: "{{n}} 字符", en: "{{n}} chars" },++ "constraints.title": { zh: "全局规则约束", en: "Global Constraints" },+ "constraints.desc": { zh: "设置适用于当前工作区的全局系统提示词。", en: "Set global system instructions for the current workspace." },+ "constraints.placeholder": { zh: "例如:始终使用中文回答,代码注释必须详细...", en: "e.g. Always respond in English. Code comments must be detailed..." },++ "saveDialog.title": { zh: "保存图表", en: "Save Diagram" },+ "saveDialog.filename": { zh: "文件名", en: "Filename" },+ "saveDialog.format": { zh: "格式", en: "Format" },+ "saveDialog.chooseFormat": { zh: "选择格式", en: "Choose format" },++ "error.missingApiKey": { zh: "请先在设置中配置 API Key", en: "Please configure an API key in Settings first." },+};++export function t(lang: UiLanguage, key: string, vars?: Record<string, string | number>) {+ const entry = dict[key];+ const template = entry ? entry[lang] : key;+ if (!vars) return template;+ let out = template;+ for (const [k, v] of Object.entries(vars)) {+ out = out.split(`{{${k}}}`).join(String(v));+ }+ return out;+}++export function tAuto(key: string, vars?: Record<string, string | number>) {+ return t(getUiLanguage(), key, vars);+}diff --git a/src/lib/ppt-prompts.ts b/src/lib/ppt-prompts.tsindex 2035d26..6f91de9 100644--- a/src/lib/ppt-prompts.ts+++ b/src/lib/ppt-prompts.ts@@ -93,6 +93,37 @@ export function getPageDescriptionPrompt(const filesXml = formatReferenceFilesXml(projectContext.reference_files_content);const originalInput = projectContext.idea_prompt || "";+ if (language === "en") {+ return `${filesXml}We are generating per-slide content descriptions for a PPT.+The user's original request is:\n${originalInput}\n+We already have the full outline:\n${JSON.stringify(outline)}\n${partInfo}+Now generate the description for slide ${pageIndex}:+${JSON.stringify(pageOutline)}++[IMPORTANT] The "Slide text" section will be rendered directly on the PPT slide. Please ensure:+1. Keep text concise; each bullet is ~8–16 words+2. Use clear list structure+3. Avoid long sentences and overly complex wording+4. Make it highly readable for live presentation+5. Do not add any extra explanatory notes or commentary++Output format example:+Slide title: Human societies: living with nature++Slide text:+- Hunter-gatherer societies: limited impact due to small scale+- High dependence: life relies on direct natural supply+- Adaptation over transformation: learn from nature to survive+- Impact pattern: local, short-term, low intensity, self-recovering++Other slide materials (add when helpful: markdown image links, formulas, tables, etc.)++[About images] If reference files include local image URLs starting with /files/ (e.g. /files/mineru/xxx/image.png), output them in markdown, e.g. . These images will be included in the slide.++${getLanguageInstruction(language)}+`;+ }+return `${filesXml}我们正在为PPT的每一页生成内容描述。用户的原始需求是:\n${originalInput}\n我们已经有了完整的大纲:\n${JSON.stringify(outline)}\n${partInfo}@@ -133,10 +164,44 @@ export function getImageGenerationPrompt() {let materialImagesNote = "";if (hasMaterialImages) {- materialImagesNote = `\n\n提示:除了模板参考图片(用于风格参考)外,还提供了额外的素材图片。这些素材图片是可供挑选和使用的元素,你可以从这些素材图片中选择合适的图片、图标、图表或其他视觉元素直接整合到生成的PPT页面中。请根据页面内容的需要,智能地选择和组合这些素材图片中的元素。`;+ materialImagesNote =+ language === "en"+ ? `\n\nNote: In addition to the template reference image (for style), extra material images are provided. You may select and integrate suitable images/icons/charts/visual elements from them to enrich the slide, based on the content needs.`+ : `\n\n提示:除了模板参考图片(用于风格参考)外,还提供了额外的素材图片。这些素材图片是可供挑选和使用的元素,你可以从这些素材图片中选择合适的图片、图标、图表或其他视觉元素直接整合到生成的PPT页面中。请根据页面内容的需要,智能地选择和组合这些素材图片中的元素。`;}- const extraReqText = extraRequirements ? `\n\n额外要求(请务必遵循):\n${extraRequirements}\n` : "";+ const extraReqText = extraRequirements+ ? language === "en"+ ? `\n\nExtra requirements (must follow):\n${extraRequirements}\n`+ : `\n\n额外要求(请务必遵循):\n${extraRequirements}\n`+ : "";++ if (language === "en") {+ return `You are an expert UI/UX presentation designer. Generate a well-designed PPT slide.+The current slide description:+<page_description>+${pageDesc}+</page_description>++<reference_information>+Overall outline:+${outlineText}++Current section: ${currentSection}+</reference_information>++<design_guidelines>+- Text must be crisp and sharp; 4K quality; 16:9 aspect ratio.+- Colors and design language must closely match the template reference image.+- Create the best composition automatically and render all text from the description accurately.+- Unless necessary, avoid markdown symbols (like #, *).+- Use the template only for style; do not include any template text.+- Fill empty areas with appropriately sized decorative shapes or illustrations.+</design_guidelines>+${getPptLanguageInstruction(language)}+${materialImagesNote}${extraReqText}+`;+ }return `你是一位专家级UI UX演示设计师,专注于生成设计良好的PPT页面。当前PPT页面的页面描述如下:@@ -164,3 +229,24 @@ ${getPptLanguageInstruction(language)}${materialImagesNote}${extraReqText}`;}++export function getTemplateGenerationPrompt(args: { requirements: string; language?: string }) {+ const language = args.language || "zh";+ const requirements = String(args.requirements || "").trim();+ const pageDesc =+ language === "en"+ ? `We are generating a PPT template background image (blank slide) that will be used as a style reference for generating slides later.+User requirements:+${requirements}+Rules:+- Generate a clean template background for a 16:9 slide.+- Do NOT include any text, letters, or watermarks.`+ : `我们正在生成一张PPT模板背景图(空白页面),用于后续生成整套PPT时的风格参考。+用户需求:+${requirements}+规则:+- 生成一张16:9比例的干净模板背景图。+- 禁止出现任何文字、字母或水印。`;++ return getImageGenerationPrompt(pageDesc, "", "", false, "", language);+}diff --git a/src/lib/ppt-service.ts b/src/lib/ppt-service.tsindex aa4cfb5..7975708 100644--- a/src/lib/ppt-service.ts+++ b/src/lib/ppt-service.ts@@ -1,11 +1,15 @@import PptxGenJS from "pptxgenjs"import { PDFDocument } from "pdf-lib"-import { generateChatMessage, generateImage, type ChatMessage } from "./ai-client"+import { generateChatMessage, generateImage } from "./ai-client"+import pptOutlineSystem from "../../agent/ppt/outline.md?raw"+import pptSlidesGenerateSystem from "../../agent/ppt/slides-generate.md?raw"export interface PptPage {title: string;content: string[];description?: string;+ note?: string;+ layout?: string;status?: string;id?: string;}@@ -16,9 +20,12 @@ export interface SlideEditRoutingItem {instruction: string;}-const PPT_OUTLINE_SYSTEM = `You are a presentation outline generator.+const PPT_OUTLINE_SYSTEM = String(pptOutlineSystem || "").trim() || `You are a presentation outline generator.Return ONLY JSON. Do not wrap in markdown code blocks. Do not include any extra text.`;+const PPT_SLIDES_GENERATE_SYSTEM = String(pptSlidesGenerateSystem || "").trim() || `You are a presentation slide planning agent.+Return ONLY JSON. Do not include any extra text.`;+const parseJsonLoose = (text: string) => {const raw = String(text || "").trim();if (!raw) throw new Error("Empty AI response");@@ -74,7 +81,9 @@ const normalizePages = (value: any): PptPage[] => {.map((p: any) => ({title: typeof p?.title === "string" ? p.title : "",content: Array.isArray(p?.content) ? p.content.map((x: any) => String(x)) : Array.isArray(p?.bullets) ? p.bullets.map((x: any) => String(x)) : [],- description: typeof p?.description === "string" ? p.description : ""+ description: typeof p?.description === "string" ? p.description : "",+ note: typeof p?.note === "string" ? p.note : undefined,+ layout: typeof p?.layout === "string" ? p.layout : undefined,})).filter((p: PptPage) => p.title.trim().length > 0);};@@ -112,16 +121,18 @@ export const pptService = {// 1. Generate OutlinegenerateOutline: async (topic: string): Promise<PptPage[]> => {const prompt = `Create a presentation outline for the topic: "${topic}".-Output a JSON array of slide objects:-[- {"title": "Slide title", "content": ["bullet 1", "bullet 2"], "description": "visual description for image generation"},- ...-]+Return JSON (no extra text). Markdown code block is allowed.+Return either:+- a JSON array of slide objects, OR+- an object with a "slides" array.++Each slide object:+{ "title": "Slide title", "content": ["bullet 1", "bullet 2"], "description": "visual description for image generation", "note": "speaker notes (optional)", "layout": "layout hint (optional)" }+Rules:- Prefer 6-10 slides unless the topic requires otherwise.- Each bullet <= 12 words.-- description must be concrete (subject, composition, lighting, colors, style).-- Output ONLY JSON.`;+- description must be concrete (subject, composition, lighting, colors, style).`;const response = await generateChatMessage([{ role: "system", content: PPT_OUTLINE_SYSTEM },@@ -140,22 +151,24 @@ Rules:},generateSlidesFromDescription: async (description: string): Promise<PptPage[]> => {- const prompt = `You are a presentation planner.-Given the following user description, create a complete slide plan (titles, bullets, and visual descriptions).+ const prompt = `Given the following user description, create a complete slide plan (titles, bullets, and visual descriptions).User description:${description}-Return ONLY a JSON array of objects:-[- {"title": "Slide title", "content": ["bullet 1", "bullet 2"], "description": "visual description for image generation"},- ...-]+Return JSON (no extra text). Markdown code block is allowed.+Return either:+- a JSON array of slide objects, OR+- an object with a "slides" array.++Each slide object:+{ "title": "Slide title", "content": ["bullet 1", "bullet 2"], "description": "visual description for image generation", "note": "speaker notes (optional)", "layout": "layout hint (optional)" }+Rules:- Prefer 6-10 slides unless the description implies otherwise.- Bullets are short and specific (<= 12 words each).- Descriptions are concrete: subject, composition, lighting, colors, style.-- Output ONLY JSON.`;+`;try {const response = await generateChatMessage([@@ -182,33 +195,53 @@ Rules:.join("\n\n"): "";- const prompt = `You are a presentation assistant.-Topic: ${topic}+ const currentSlideJson = JSON.stringify(+ {+ id: page.id || `slide-${index + 1}`,+ title: page.title,+ content: page.content,+ description: page.description || "",+ note: page.note || "",+ layout: page.layout || "",+ },+ null,+ 2+ );++ const prompt = `Topic: ${topic}Slide index: ${index + 1}-Slide title: ${page.title}-Current bullets: ${page.content.join(" | ")}-Current visual description: ${page.description || ""}-${refText ? `Reference:\n${refText}\n\n` : ""}Return ONLY valid JSON:-{- "content": ["bullet1", "bullet2"],- "description": "visual description for slide image generation"-}-Rules:-- Keep bullets short and specific (<= 12 words each).-- Make description precise: scene, objects, composition, style, colors.-`;+Current slide:+${currentSlideJson}- const response = await generateChatMessage([{ role: "user", content: prompt }]);- const match = response.match(/\{[\s\S]*\}/);- if (!match) return page;+${refText ? `Reference:\n${refText}\n\n` : ""}Task:+- Improve bullets (<= 12 words each), and refine description for image generation.+- Optionally add speaker note and layout hint if helpful.+- Keep id stable.++Return JSON only (no extra text).`;++ const response = await generateChatMessage(+ [+ { role: "system", content: PPT_SLIDES_GENERATE_SYSTEM },+ { role: "user", content: prompt },+ ],+ undefined,+ { timeoutMs: 120000 }+ );try {- const parsed = JSON.parse(match[0]);+ const parsed = parseJsonLoose(response);+ const asSlides = Array.isArray(parsed?.slides) ? parsed.slides : Array.isArray(parsed) ? parsed : null;+ const first = Array.isArray(asSlides) && asSlides.length > 0 ? asSlides[0] : null;+ if (!first || typeof first !== "object") return page;return {...page,- content: Array.isArray(parsed.content) ? parsed.content : page.content,- description: typeof parsed.description === "string" ? parsed.description : page.description,+ title: typeof first.title === "string" ? first.title : page.title,+ content: Array.isArray(first.content) ? first.content.map((x: any) => String(x)) : page.content,+ description: typeof first.description === "string" ? first.description : page.description,+ note: typeof first.note === "string" ? first.note : page.note,+ layout: typeof first.layout === "string" ? first.layout : page.layout,};} catch {return page;@@ -236,6 +269,8 @@ Rules:editPageImage: async (page: PptPage, instruction: string, referenceImageUrl?: string, templateImageUrl?: string, additionalImages?: string[]) => {const prompt = `Edit the slide image based on instruction.+You will be given the current slide image as the primary reference image. Treat it as the base image and modify it, not regenerate from scratch.+If additional reference images are provided, they may include the template/style reference and user-provided assets. Keep the overall visual style consistent with the template.Slide title: ${page.title}Bullets: ${(page.content || []).join(" | ")}Original visual description: ${page.description || ""}@@ -248,10 +283,14 @@ Rules:`;const ref = referenceImageUrl || templateImageUrl;+ const additionalReferenceImageUrls = Array.isArray(additionalImages) ? [...additionalImages] : [];+ if (referenceImageUrl && templateImageUrl && templateImageUrl !== referenceImageUrl) {+ additionalReferenceImageUrls.push(templateImageUrl);+ }return await generateImage({prompt,referenceImageUrl: ref,- additionalReferenceImageUrls: additionalImages+ additionalReferenceImageUrls});},diff --git a/src/lib/system-prompts.ts b/src/lib/system-prompts.tsindex 427e5ba..c3a9ca1 100644--- a/src/lib/system-prompts.ts+++ b/src/lib/system-prompts.ts@@ -1,7 +1,13 @@import drawioPrompt from "../../agent/flow/system.md?raw";import cadPrompt from "../../agent/cad/system.md?raw";-import pptPrompt from "../../agent/ppt/system.md?raw";+import pptOutlinePrompt from "../../agent/ppt/outline.md?raw";+import pptOutlineEditPrompt from "../../agent/ppt/outline-edit.md?raw";+import pptSlidesGeneratePrompt from "../../agent/ppt/slides-generate.md?raw";+import pptSlidesEditPrompt from "../../agent/ppt/system.md?raw";export const DRAWIO_SYSTEM_PROMPT = drawioPrompt;export const CAD_SYSTEM_PROMPT = cadPrompt;-export const PPT_SYSTEM_PROMPT = pptPrompt;+export const PPT_OUTLINE_SYSTEM_PROMPT = pptOutlinePrompt;+export const PPT_OUTLINE_EDIT_SYSTEM_PROMPT = pptOutlineEditPrompt;+export const PPT_SLIDES_GENERATE_SYSTEM_PROMPT = pptSlidesGeneratePrompt;+export const PPT_SLIDES_EDIT_SYSTEM_PROMPT = pptSlidesEditPrompt;diff --git a/src/lib/ui-language.ts b/src/lib/ui-language.tsnew file mode 100644index 0000000..169ef3b--- /dev/null+++ b/src/lib/ui-language.ts@@ -0,0 +1,35 @@+export type UiLanguage = "zh" | "en";++const UI_LANG_STORAGE_KEY = "unified-ai-workspace-ui-lang-v1";++export function getUiLanguage(): UiLanguage {+ if (typeof window === "undefined") return "zh";+ const raw = String(localStorage.getItem(UI_LANG_STORAGE_KEY) || "").trim().toLowerCase();+ if (raw === "en") return "en";+ if (raw === "zh") return "zh";+ return "zh";+}++export function setUiLanguage(lang: UiLanguage) {+ if (typeof window === "undefined") return;+ localStorage.setItem(UI_LANG_STORAGE_KEY, lang);+ try {+ document.documentElement.setAttribute("lang", lang === "zh" ? "zh-CN" : "en");+ } catch {+ }+ try {+ window.dispatchEvent(new Event("ui-language-changed"));+ } catch {+ }+}++export function detectLanguageFromText(text: string): UiLanguage | null {+ const raw = String(text || "");+ if (/[一-龥]/.test(raw)) return "zh";+ if (/[A-Za-z]/.test(raw)) return "en";+ return null;+}++export function resolveResponseLanguage(args: { userText: string; uiLang: UiLanguage }): UiLanguage {+ return detectLanguageFromText(args.userText) || args.uiLang;+}diff --git a/src/lib/use-ui-language.ts b/src/lib/use-ui-language.tsnew file mode 100644index 0000000..0de5747--- /dev/null+++ b/src/lib/use-ui-language.ts@@ -0,0 +1,15 @@+import { useEffect, useState } from "react";+import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";++export function useUiLanguage() {+ const [uiLang, setUiLang] = useState<UiLanguage>(() => getUiLanguage());++ useEffect(() => {+ const onLang = () => setUiLang(getUiLanguage());+ window.addEventListener("ui-language-changed", onLang as any);+ return () => window.removeEventListener("ui-language-changed", onLang as any);+ }, []);++ return uiLang;+}+diff --git a/src/pages/LandingPage.tsx b/src/pages/LandingPage.tsxindex 58b786f..952c0b5 100644--- a/src/pages/LandingPage.tsx+++ b/src/pages/LandingPage.tsx@@ -1,8 +1,9 @@-import React, { useState } from 'react';+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 { Button } from '@/components/ui/button';import { getPdfDocumentFromUrl, renderPdfPageToCanvas } from '@/lib/pdf-utils';+import { getUiLanguage, setUiLanguage, type UiLanguage } from "@/lib/ui-language";interface LandingPageProps {onStart: () => void;@@ -10,6 +11,11 @@ interface LandingPageProps {export function LandingPage({ onStart }: LandingPageProps) {const [activeShowcase, setActiveShowcase] = useState<'flow' | 'cad' | 'ppt'>('flow');+ const [uiLang, setUiLang] = useState<UiLanguage>(() => getUiLanguage());++ useEffect(() => {+ setUiLanguage(uiLang);+ }, [uiLang]);return (<div className="min-h-screen bg-black text-white flex flex-col font-sans selection:bg-purple-500/30 relative overflow-hidden">@@ -96,6 +102,15 @@ export function LandingPage({ onStart }: LandingPageProps) {{/* Content */}<div className="relative z-10 flex-1 flex flex-col">+ <div className="absolute top-4 right-4 z-20">+ <Button+ variant="secondary"+ className="h-9 rounded-full bg-white/10 text-white border border-white/15 hover:bg-white/15"+ onClick={() => setUiLang((prev) => (prev === "zh" ? "en" : "zh"))}+ >+ {uiLang === "zh" ? "中文" : "English"}+ </Button>+ </div><main className="flex-1 flex flex-col items-center justify-center text-center px-4 py-20"><motion.divinitial={{ opacity: 0, y: 20 }}@@ -103,22 +118,28 @@ export function LandingPage({ onStart }: LandingPageProps) {transition={{ duration: 0.8 }}className="max-w-4xl space-y-8">- <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/5 border border-white/10 text-sm font-light tracking-wide text-blue-200/80 mb-6 font-artistic">+ <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-white/5 border border-white/10 text-sm font-light tracking-wide text-blue-200/80 mb-6 font-artistic"><Zap className="w-3.5 h-3.5" />- <span>AI 驱动的数字神笔</span>+ <span>{uiLang === "zh" ? "AI 驱动的数字神笔" : "AI-powered creative studio"}</span></div><h1 className="text-6xl md:text-8xl font-bold tracking-tight leading-tight font-artistic">- <span className="block animate-color-cycle drop-shadow-[0_0_25px_rgba(255,255,255,0.4)]">所想即所见</span>+ <span className="block animate-color-cycle drop-shadow-[0_0_25px_rgba(255,255,255,0.4)]">+ {uiLang === "zh" ? "所想即所见" : "See what you think"}+ </span><span className="block animate-color-cycle drop-shadow-[0_0_25px_rgba(255,255,255,0.4)]" style={{ animationDelay: '-2.5s' }}>- 一语定乾坤+ {uiLang === "zh" ? "一语定乾坤" : "Build with a sentence"}</span></h1><p className="text-xl md:text-2xl text-gray-400 max-w-2xl mx-auto font-light leading-relaxed font-artistic">- 无需繁琐操作,AI 赋予你“神笔马良”般的能力。+ {uiLang === "zh"+ ? "无需繁琐操作,AI 赋予你“神笔马良”般的能力。"+ : "No friction. AI gives you the power to turn intent into output."}<br/>- 从逻辑图表到可交付成果,只在弹指之间。+ {uiLang === "zh"+ ? "从逻辑图表到可交付成果,只在弹指之间。"+ : "From diagrams to deliverables — in seconds."}</p><div className="pt-8">@@ -128,7 +149,7 @@ export function LandingPage({ onStart }: LandingPageProps) {className="h-16 px-12 rounded-full text-2xl bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-500 hover:to-purple-500 shadow-[0_0_30px_-5px_rgba(59,130,246,0.5)] transition-all hover:scale-105 border-0 font-artistic tracking-widest gap-3"><Brush className="w-6 h-6" />- 挥毫泼墨+ {uiLang === "zh" ? "挥毫泼墨" : "Start Creating"}<Droplet className="w-6 h-6 fill-current" /></Button></div>@@ -151,12 +172,12 @@ export function LandingPage({ onStart }: LandingPageProps) {<Layers className="w-5 h-5 text-blue-300" /></div><div>- <div className="text-white/90 font-semibold">智绘流程蓝图</div>- <div className="text-white/45 text-sm mt-0.5">输入需求 → 生成并迭代流程图</div>+ <div className="text-white/90 font-semibold">{uiLang === "zh" ? "智绘流程蓝图" : "Flow Blueprint"}</div>+ <div className="text-white/45 text-sm mt-0.5">{uiLang === "zh" ? "输入需求 → 生成并迭代流程图" : "Describe → Generate → Iterate"}</div></div></div><div className="mt-2 text-sm text-white/60 space-y-1">- <div>· 原子级修改:仅改不满意处,保留满意部分</div>+ <div>{uiLang === "zh" ? "· 原子级修改:仅改不满意处,保留满意部分" : "· Atomic edits: change only what you dislike"}</div></div></button>@@ -173,13 +194,13 @@ export function LandingPage({ onStart }: LandingPageProps) {<Box className="w-5 h-5 text-purple-300" /></div><div>- <div className="text-white/90 font-semibold">智能室内设计</div>- <div className="text-white/45 text-sm mt-0.5">输入需求 → 2D 平面 → 装修图 / 物料清单</div>+ <div className="text-white/90 font-semibold">{uiLang === "zh" ? "智能室内设计" : "Interior Design"}</div>+ <div className="text-white/45 text-sm mt-0.5">{uiLang === "zh" ? "输入需求 → 2D 平面 → 装修图 / 物料清单" : "Describe → 2D Plan → Renders / BOM"}</div></div></div><div className="mt-2 text-sm text-white/55 space-y-1">- <div>· 全流程覆盖:需求→方案→2D→出图/清单</div>- <div>· 2D 支持原子修改</div>+ <div>{uiLang === "zh" ? "· 全流程覆盖:需求→方案→2D→出图/清单" : "· End-to-End: Brief → Plan → 2D → Outputs"}</div>+ <div>{uiLang === "zh" ? "· 2D 支持原子修改" : "· 2D supports atomic edits"}</div></div></button>@@ -196,12 +217,12 @@ export function LandingPage({ onStart }: LandingPageProps) {<Layout className="w-5 h-5 text-cyan-300" /></div><div>- <div className="text-white/90 font-semibold">智创演示文稿</div>- <div className="text-white/45 text-sm mt-0.5">文案 → 结构 → 幻灯片</div>+ <div className="text-white/90 font-semibold">{uiLang === "zh" ? "智创演示文稿" : "Presentation"}</div>+ <div className="text-white/45 text-sm mt-0.5">{uiLang === "zh" ? "文案 → 结构 → 幻灯片" : "Copy → Structure → Slides"}</div></div></div><div className="mt-2 text-sm text-white/60 space-y-1">- <div>· 单页/多页修改:支持精修与批量统一调整</div>+ <div>{uiLang === "zh" ? "· 单页/多页修改:支持精修与批量统一调整" : "· Edit single or multiple slides consistently"}</div></div></button></div>@@ -219,9 +240,9 @@ export function LandingPage({ onStart }: LandingPageProps) {<div className="absolute inset-0 top-12 flex items-center justify-center"><AnimatePresence mode="wait">- {activeShowcase === 'flow' && <DemoFlowchart key="flow" />}- {activeShowcase === 'cad' && <DemoCAD key="cad" />}- {activeShowcase === 'ppt' && <DemoPPT key="ppt" />}+ {activeShowcase === 'flow' && <DemoFlowchart key="flow" uiLang={uiLang} />}+ {activeShowcase === 'cad' && <DemoCAD key="cad" uiLang={uiLang} />}+ {activeShowcase === 'ppt' && <DemoPPT key="ppt" uiLang={uiLang} />}</AnimatePresence></div></div>@@ -231,7 +252,7 @@ export function LandingPage({ onStart }: LandingPageProps) {</main><footer className="py-8 text-center text-xs text-gray-600">- <p>© 2026 Nexus AI Inc. 以 AI 绘未来。</p>+ <p>{uiLang === "zh" ? "© 2026 Nexus AI Inc. 以 AI 绘未来。" : "© 2026 Nexus AI Inc. Building the future with AI."}</p></footer></div></div>@@ -242,7 +263,11 @@ export function LandingPage({ onStart }: LandingPageProps) {import { User, MessageSquare } from 'lucide-react';-function UserPrompt({ text, color = "blue" }: { text: string, color?: string }) {+function estimateTypewriterDurationMs(text: string, speedMsPerChar: number) {+ return Array.from(text).length * speedMsPerChar + 400;+}++function UserPrompt({ text, color = "blue", speed = 30 }: { text: string, color?: string; speed?: number }) {const colors = {blue: "bg-blue-600",purple: "bg-purple-600",@@ -264,7 +289,7 @@ function UserPrompt({ text, color = "blue" }: { text: string, color?: string })<div className={`px-6 py-4 rounded-2xl rounded-bl-none ${colors} text-white shadow-xl border border-white/10`}><div className="flex items-center gap-3"><MessageSquare className="w-4 h-4 opacity-70" />- <span className="text-lg font-medium tracking-wide"><Typewriter text={text} speed={30} /></span>+ <span className="text-lg font-medium tracking-wide"><Typewriter text={text} speed={speed} /></span></div></div></div>@@ -272,9 +297,16 @@ function UserPrompt({ text, color = "blue" }: { text: string, color?: string }))}-function DemoFlowchart() {+function DemoFlowchart({ uiLang }: { uiLang: UiLanguage }) {const [step, setStep] = useState(0);const [isGenerating, setIsGenerating] = useState(false);+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);+ const promptSpeed = 30;+ const promptText = tr("帮我梳理 GraphRAG 的论文逻辑,生成流程图", "Summarize GraphRAG paper logic and generate a flowchart");+ const promptHoldMs = Math.max(2200, estimateTypewriterDurationMs(promptText, promptSpeed));+ const phaseTitleStyle = uiLang === "zh"+ ? { y: -40, fontSize: 42, letterSpacing: 4 }+ : { y: -62, fontSize: 30, letterSpacing: 1 };// Sequence controllerReact.useEffect(() => {@@ -283,16 +315,16 @@ function DemoFlowchart() {const runSequence = () => {setStep(0);setIsGenerating(false);- timeouts.push(setTimeout(() => setIsGenerating(true), 2200));- timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(1); }, 4200));- timeouts.push(setTimeout(() => setStep(2), 6200));- timeouts.push(setTimeout(() => setStep(3), 8200));- timeouts.push(setTimeout(() => runSequence(), 16000));+ timeouts.push(setTimeout(() => setIsGenerating(true), promptHoldMs));+ timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(1); }, promptHoldMs + 2000));+ timeouts.push(setTimeout(() => setStep(2), promptHoldMs + 4000));+ timeouts.push(setTimeout(() => setStep(3), promptHoldMs + 6000));+ timeouts.push(setTimeout(() => runSequence(), promptHoldMs + 13800));};runSequence();return () => timeouts.forEach(clearTimeout);- }, []);+ }, [promptHoldMs]);return (<div className="w-full h-full bg-[#0f172a] relative overflow-hidden flex flex-col items-center justify-center p-4">@@ -302,7 +334,7 @@ function DemoFlowchart() {<AnimatePresence mode="wait">{step === 0 && !isGenerating && (<div className="absolute inset-0 flex items-center justify-center bg-slate-900 z-50">- <UserPrompt text="帮我梳理 GraphRAG 的论文逻辑,生成流程图" color="blue" />+ <UserPrompt text={promptText} color="blue" speed={promptSpeed} /></div>)}</AnimatePresence>@@ -319,14 +351,14 @@ function DemoFlowchart() {initial={{ y: 8, opacity: 0 }}animate={{ y: 0, opacity: 1 }}exit={{ y: -8, opacity: 0 }}- className="rounded-2xl border border-blue-400/25 bg-white/10 backdrop-blur-2xl px-7 py-6 shadow-[0_24px_80px_rgba(0,0,0,0.55)]"+ className="rounded-2xl border border-blue-400/25 bg-white/10 backdrop-blur-2xl px-7 py-6 shadow-[0_24px_80px_rgba(0,0,0,0.55)] w-[min(90vw,420px)]"><div className="text-white/85 font-semibold flex items-center gap-2"><Layers className="w-4 h-4 text-blue-200" />- 开始生成流程图…+ {tr("开始生成流程图…", "Generating flowchart…")}</div>- <div className="text-white/45 text-sm mt-1">解析论文结构 · 抽取模块 · 组织链路</div>- <div className="mt-4 h-1.5 w-64 rounded-full bg-white/10 overflow-hidden">+ <div className="text-white/45 text-sm mt-1">{tr("解析论文结构 · 抽取模块 · 组织链路", "Parse structure · extract modules · connect the pipeline")}</div>+ <div className="mt-4 h-1.5 w-full rounded-full bg-white/10 overflow-hidden"><motion.divclassName="h-full bg-blue-400/80"animate={{ width: ["0%", "100%"] }}@@ -347,13 +379,13 @@ function DemoFlowchart() {><div className="flex gap-8 text-sm font-mono"><span className={`flex items-center gap-2 ${step >= 1 ? "text-blue-400" : "text-slate-600"}`}>- <div className={`w-3 h-3 rounded-full ${step >= 1 ? "bg-blue-500 animate-pulse" : "bg-slate-600"}`}/> 索引构建引擎+ <div className={`w-3 h-3 rounded-full ${step >= 1 ? "bg-blue-500 animate-pulse" : "bg-slate-600"}`}/> {tr("索引构建引擎", "Indexing Engine")}</span><span className={`flex items-center gap-2 ${step >= 2 ? "text-purple-400" : "text-slate-600"}`}>- <div className={`w-3 h-3 rounded-full ${step >= 2 ? "bg-purple-500 animate-pulse" : "bg-slate-600"}`}/> 社区发现探测器+ <div className={`w-3 h-3 rounded-full ${step >= 2 ? "bg-purple-500 animate-pulse" : "bg-slate-600"}`}/> {tr("社区发现探测器", "Community Discovery")}</span><span className={`flex items-center gap-2 ${step >= 3 ? "text-emerald-400" : "text-slate-600"}`}>- <div className={`w-3 h-3 rounded-full ${step >= 3 ? "bg-emerald-500 animate-pulse" : "bg-slate-600"}`}/> 全局检索链路+ <div className={`w-3 h-3 rounded-full ${step >= 3 ? "bg-emerald-500 animate-pulse" : "bg-slate-600"}`}/> {tr("全局检索链路", "Global Retrieval")}</span></div></motion.div>@@ -383,19 +415,25 @@ function DemoFlowchart() {{step >= 1 && (<g transform="translate(50, 80)"><motion.g initial={{ opacity: 0, x: -50 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.8 }}>- <text x="0" y="-40" fill="#3b82f6" fontSize="42" fontWeight="bold" letterSpacing="4">第一阶段:索引构建</text>+ <text x="0" y={phaseTitleStyle.y} fill="#3b82f6" fontSize={phaseTitleStyle.fontSize} fontWeight="bold" letterSpacing={phaseTitleStyle.letterSpacing}>+ {uiLang === "zh" ? "第一阶段:索引构建" : (+ <>+ <tspan x="0" dy="0">Phase 1: Indexing</tspan>+ </>+ )}+ </text><rect x="0" y="0" width="550" height="920" rx="20" fill="none" stroke="#3b82f6" strokeOpacity="0.3" strokeDasharray="8 8" strokeWidth="3" />{/* Source Docs */}<g transform="translate(50, 60)"><rect width="120" height="140" rx="10" fill="#1e293b" stroke="#3b82f6" strokeWidth="3" />- <text x="60" y="80" textAnchor="middle" fill="#94a3b8" fontSize="24" fontWeight="bold">源文档</text>+ <text x="60" y="80" textAnchor="middle" fill="#94a3b8" fontSize={uiLang === "zh" ? 24 : 18} fontWeight="bold">{tr("源文档", "Source Docs")}</text></g>{/* Text Chunks */}<g transform="translate(250, 60)"><rect width="120" height="140" rx="10" fill="#1e293b" stroke="#3b82f6" strokeWidth="3" />- <text x="60" y="80" textAnchor="middle" fill="#94a3b8" fontSize="24" fontWeight="bold">文本切片</text>+ <text x="60" y="80" textAnchor="middle" fill="#94a3b8" fontSize={uiLang === "zh" ? 24 : 18} fontWeight="bold">{tr("文本切片", "Text Chunks")}</text><line x1="20" y1="35" x2="100" y2="35" stroke="#334155" strokeWidth="3" /><line x1="20" y1="60" x2="100" y2="60" stroke="#334155" strokeWidth="3" /><line x1="20" y1="105" x2="100" y2="105" stroke="#334155" strokeWidth="3" />@@ -404,32 +442,32 @@ function DemoFlowchart() {{/* LLM Extraction */}<g transform="translate(50, 260)"><rect width="450" height="180" rx="10" fill="#1e293b" stroke="#3b82f6" strokeWidth="3" />- <text x="30" y="45" fill="#3b82f6" fontSize="28" fontWeight="bold">LLM 信息提取</text>+ <text x="30" y="45" fill="#3b82f6" fontSize="28" fontWeight="bold">{tr("LLM 信息提取", "LLM Extraction")}</text><g transform="translate(30, 70)"><rect width="110" height="80" rx="6" fill="#0f172a" stroke="#3b82f6" strokeOpacity="0.5" strokeWidth="2" />- <text x="55" y="50" textAnchor="middle" fill="#cbd5e1" fontSize="20">实体</text>+ <text x="55" y="50" textAnchor="middle" fill="#cbd5e1" fontSize={uiLang === "zh" ? 20 : 16}>{tr("实体", "Entities")}</text></g><g transform="translate(170, 70)"><rect width="110" height="80" rx="6" fill="#0f172a" stroke="#3b82f6" strokeOpacity="0.5" strokeWidth="2" />- <text x="55" y="50" textAnchor="middle" fill="#cbd5e1" fontSize="20">关系</text>+ <text x="55" y="50" textAnchor="middle" fill="#cbd5e1" fontSize={uiLang === "zh" ? 20 : 16}>{tr("关系", "Relations")}</text></g><g transform="translate(310, 70)"><rect width="110" height="80" rx="6" fill="#0f172a" stroke="#3b82f6" strokeOpacity="0.5" strokeWidth="2" />- <text x="55" y="50" textAnchor="middle" fill="#cbd5e1" fontSize="20">协变量</text>+ <text x="55" y="50" textAnchor="middle" fill="#cbd5e1" fontSize={uiLang === "zh" ? 20 : 16}>{tr("协变量", "Covariates")}</text></g></g>{/* Element Summaries */}<g transform="translate(50, 500)"><rect width="450" height="100" rx="10" fill="#1e293b" stroke="#3b82f6" strokeWidth="3" />- <text x="225" y="60" textAnchor="middle" fill="#94a3b8" fontSize="28" fontWeight="bold">元素摘要生成</text>+ <text x="225" y="60" textAnchor="middle" fill="#94a3b8" fontSize={uiLang === "zh" ? 28 : 24} fontWeight="bold">{tr("元素摘要生成", "Element Summarization")}</text></g>{/* Graph Construction */}<g transform="translate(50, 660)"><rect width="450" height="140" rx="10" fill="#1e293b" stroke="#3b82f6" strokeWidth="3" />- <text x="30" y="45" fill="#3b82f6" fontSize="28" fontWeight="bold">图谱拓扑构建</text>+ <text x="30" y="45" fill="#3b82f6" fontSize="28" fontWeight="bold">{tr("图谱拓扑构建", "Graph Topology")}</text><circle cx="225" cy="80" r="40" fill="none" stroke="#3b82f6" strokeOpacity="0.5" strokeWidth="3" /><circle cx="180" cy="70" r="8" fill="#3b82f6" /><circle cx="270" cy="70" r="8" fill="#3b82f6" />@@ -450,13 +488,20 @@ function DemoFlowchart() {{step >= 2 && (<g transform="translate(680, 80)"><motion.g initial={{ opacity: 0, y: 50 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.8 }}>- <text x="0" y="-40" fill="#a855f7" fontSize="42" fontWeight="bold" letterSpacing="4">第二阶段:层级聚类</text>+ <text x="0" y={phaseTitleStyle.y} fill="#a855f7" fontSize={phaseTitleStyle.fontSize} fontWeight="bold" letterSpacing={phaseTitleStyle.letterSpacing}>+ {uiLang === "zh" ? "第二阶段:层级聚类" : (+ <>+ <tspan x="0" dy="0">Phase 2: Hierarchical</tspan>+ <tspan x="0" dy="1.1em">Clustering</tspan>+ </>+ )}+ </text><rect x="0" y="0" width="550" height="920" rx="20" fill="none" stroke="#a855f7" strokeOpacity="0.3" strokeDasharray="8 8" strokeWidth="3" />{/* Leiden Algorithm Box */}<g transform="translate(50, 60)"><rect width="450" height="100" rx="10" fill="#1e293b" stroke="#a855f7" strokeWidth="3" />- <text x="225" y="60" textAnchor="middle" fill="#e9d5ff" fontSize="28" fontWeight="bold">Leiden 社区发现</text>+ <text x="225" y="60" textAnchor="middle" fill="#e9d5ff" fontSize="28" fontWeight="bold">{tr("Leiden 社区发现", "Leiden Communities")}</text></g>{/* Hierarchy Tree */}@@ -489,16 +534,16 @@ function DemoFlowchart() {{/* Community Summaries */}<g transform="translate(50, 660)"><rect width="450" height="200" rx="10" fill="#1e293b" stroke="#a855f7" strokeWidth="3" />- <text x="30" y="45" fill="#a855f7" fontSize="28" fontWeight="bold">社区摘要生成</text>+ <text x="30" y="45" fill="#a855f7" fontSize="28" fontWeight="bold">{tr("社区摘要生成", "Community Summarization")}</text><rect x="30" y="70" width="390" height="35" rx="6" fill="#0f172a" stroke="#a855f7" strokeOpacity="0.3" />- <text x="225" y="95" textAnchor="middle" fill="#a855f7" fontSize="20" opacity="0.9">摘要:根社区 0 (Root)</text>+ <text x="225" y="95" textAnchor="middle" fill="#a855f7" fontSize={uiLang === "zh" ? 20 : 16} opacity="0.9">{tr("摘要:根社区 0 (Root)", "Summary: Root 0")}</text><rect x="30" y="115" width="390" height="35" rx="6" fill="#0f172a" stroke="#a855f7" strokeOpacity="0.3" />- <text x="225" y="140" textAnchor="middle" fill="#a855f7" fontSize="20" opacity="0.9">摘要:子社区 1.1 (Topic A)</text>+ <text x="225" y="140" textAnchor="middle" fill="#a855f7" fontSize={uiLang === "zh" ? 20 : 16} opacity="0.9">{tr("摘要:子社区 1.1 (Topic A)", "Summary: Sub 1.1 (Topic A)")}</text><rect x="30" y="160" width="390" height="35" rx="6" fill="#0f172a" stroke="#a855f7" strokeOpacity="0.3" />- <text x="225" y="185" textAnchor="middle" fill="#a855f7" fontSize="20" opacity="0.9">摘要:子社区 1.2 (Topic B)</text>+ <text x="225" y="185" textAnchor="middle" fill="#a855f7" fontSize={uiLang === "zh" ? 20 : 16} opacity="0.9">{tr("摘要:子社区 1.2 (Topic B)", "Summary: Sub 1.2 (Topic B)")}</text></g>{/* Incoming Link */}@@ -512,38 +557,45 @@ function DemoFlowchart() {{step >= 3 && (<g transform="translate(1310, 80)"><motion.g initial={{ opacity: 0, x: 50 }} animate={{ opacity: 1, x: 0 }} transition={{ duration: 0.8 }}>- <text x="0" y="-40" fill="#10b981" fontSize="42" fontWeight="bold" letterSpacing="4">第三阶段:全局检索</text>+ <text x="0" y={phaseTitleStyle.y} fill="#10b981" fontSize={phaseTitleStyle.fontSize} fontWeight="bold" letterSpacing={phaseTitleStyle.letterSpacing}>+ {uiLang === "zh" ? "第三阶段:全局检索" : (+ <>+ <tspan x="0" dy="0">Phase 3: Global</tspan>+ <tspan x="0" dy="1.1em">Retrieval</tspan>+ </>+ )}+ </text><rect x="0" y="0" width="550" height="920" rx="20" fill="none" stroke="#10b981" strokeOpacity="0.3" strokeDasharray="8 8" strokeWidth="3" />{/* User Query */}<g transform="translate(50, 60)"><rect width="450" height="80" rx="40" fill="#064e3b" stroke="#10b981" strokeWidth="3" />- <text x="225" y="50" textAnchor="middle" fill="#d1fae5" fontSize="28" fontWeight="bold">用户指令 (Query)</text>+ <text x="225" y="50" textAnchor="middle" fill="#d1fae5" fontSize="28" fontWeight="bold">{tr("用户指令 (Query)", "User Query")}</text></g>{/* Map (Shuffle) */}<g transform="translate(50, 200)"><rect width="450" height="180" rx="10" fill="#1e293b" stroke="#10b981" strokeWidth="3" />- <text x="30" y="45" fill="#10b981" fontSize="28" fontWeight="bold">Map:社区评分</text>+ <text x="30" y="45" fill="#10b981" fontSize="28" fontWeight="bold">{tr("Map:社区评分", "Map: Community Scoring")}</text><g transform="translate(40, 70)"><rect width="100" height="90" rx="6" fill="#064e3b" stroke="#10b981" strokeOpacity="0.5" />- <text x="50" y="50" textAnchor="middle" fill="#10b981" fontSize="20">评分 0</text>+ <text x="50" y="50" textAnchor="middle" fill="#10b981" fontSize="20">{tr("评分 0", "Score 0")}</text></g><g transform="translate(175, 70)"><rect width="100" height="90" rx="6" fill="#064e3b" stroke="#10b981" strokeOpacity="0.5" />- <text x="50" y="50" textAnchor="middle" fill="#10b981" fontSize="20">评分 1</text>+ <text x="50" y="50" textAnchor="middle" fill="#10b981" fontSize="20">{tr("评分 1", "Score 1")}</text></g><g transform="translate(310, 70)"><rect width="100" height="90" rx="6" fill="#064e3b" stroke="#10b981" strokeOpacity="0.5" />- <text x="50" y="50" textAnchor="middle" fill="#10b981" fontSize="20">评分 2</text>+ <text x="50" y="50" textAnchor="middle" fill="#10b981" fontSize="20">{tr("评分 2", "Score 2")}</text></g></g>{/* Reduce (Synthesize) */}<g transform="translate(50, 460)"><rect width="450" height="140" rx="10" fill="#1e293b" stroke="#10b981" strokeWidth="3" />- <text x="30" y="45" fill="#10b981" fontSize="28" fontWeight="bold">Reduce:归约合成</text>+ <text x="30" y="45" fill="#10b981" fontSize="28" fontWeight="bold">{tr("Reduce:归约合成", "Reduce: Synthesis")}</text><path d="M60 70 L225 120 L390 70" fill="none" stroke="#10b981" strokeWidth="4" /><circle cx="225" cy="120" r="20" fill="#10b981" filter="url(#glow-strong)" />@@ -552,7 +604,7 @@ function DemoFlowchart() {{/* Final Answer */}<g transform="translate(50, 700)"><rect width="450" height="120" rx="10" fill="#1e293b" stroke="#10b981" strokeWidth="4" />- <text x="225" y="70" textAnchor="middle" fill="#10b981" fontSize="32" fontWeight="bold">全局答案 (Answer)</text>+ <text x="225" y="70" textAnchor="middle" fill="#10b981" fontSize="32" fontWeight="bold">{tr("全局答案 (Answer)", "Global Answer")}</text></g>{/* Connections */}@@ -609,9 +661,13 @@ function DemoFlowchart() {)}-function DemoCAD() {+function DemoCAD({ uiLang }: { uiLang: UiLanguage }) {const [step, setStep] = useState(0);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 promptHoldMs = Math.max(2000, estimateTypewriterDurationMs(promptText, promptSpeed));React.useEffect(() => {const timeouts: NodeJS.Timeout[] = [];@@ -623,37 +679,37 @@ function DemoCAD() {// 0s: Display Input Prompt (Wait 2s)// 2s: Start Generating 2D (Duration 2s)- timeouts.push(setTimeout(() => setIsGenerating(true), 2000));+ timeouts.push(setTimeout(() => setIsGenerating(true), promptHoldMs));// 4s: Show 2D Plan (Duration 3s)- timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(1); }, 4000));+ timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(1); }, promptHoldMs + 2000));// 7s: Start Generating BOM (Duration 2s)- timeouts.push(setTimeout(() => setIsGenerating(true), 7000));+ timeouts.push(setTimeout(() => setIsGenerating(true), promptHoldMs + 5000));// 9s: Show BOM (Duration 3s)- timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(2); }, 9000));+ timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(2); }, promptHoldMs + 7000));// 12s: Start Generating Render (Duration 2s)- timeouts.push(setTimeout(() => setIsGenerating(true), 12000));+ timeouts.push(setTimeout(() => setIsGenerating(true), promptHoldMs + 10000));// 14s: Show Final Render (Duration 3s)- timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(3); }, 14000));+ timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(3); }, promptHoldMs + 12000));// 17s: Loop- timeouts.push(setTimeout(() => runSequence(), 17000));+ timeouts.push(setTimeout(() => runSequence(), promptHoldMs + 15000));};runSequence();return () => timeouts.forEach(clearTimeout);- }, []);+ }, [promptHoldMs]);// Helper to get generating textconst getGenState = () => {- if (step === 0) return { title: "正在生成平面方案...", sub: "AI 布局规划 · 动线分析 · 空间划分" };- if (step === 1) return { title: "正在生成物料清单...", sub: "空间拆解 · 材料归类 · 数量估算" };- if (step === 2) return { title: "正在渲染装修效果...", sub: "风格匹配 · 材质建议 · 灯光氛围" };- return { title: "处理中...", sub: "请稍候" };+ 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") };+ return { title: tr("处理中...", "Processing..."), sub: tr("请稍候", "Please wait") };};const genState = getGenState();@@ -663,7 +719,7 @@ function DemoCAD() {<AnimatePresence mode="wait">{step === 0 && !isGenerating && (<div className="absolute inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm z-50">- <UserPrompt text="设计一套新中式客厅装修方案,要简约大气" color="purple" />+ <UserPrompt text={promptText} color="purple" speed={promptSpeed} /></div>)}</AnimatePresence>@@ -680,14 +736,14 @@ function DemoCAD() {initial={{ y: 10, opacity: 0 }}animate={{ y: 0, opacity: 1 }}exit={{ y: -10, opacity: 0 }}- className="rounded-2xl border border-purple-300/25 bg-white/10 backdrop-blur-2xl px-7 py-6 shadow-[0_24px_80px_rgba(0,0,0,0.55)]"+ className="rounded-2xl border border-purple-300/25 bg-white/10 backdrop-blur-2xl px-7 py-6 shadow-[0_24px_80px_rgba(0,0,0,0.55)] w-[min(90vw,420px)]"><div className="text-white/85 font-semibold flex items-center gap-2"><Box className="w-4 h-4 text-purple-200" />{genState.title}</div><div className="text-white/45 text-sm mt-1">{genState.sub}</div>- <div className="mt-4 h-1.5 w-64 rounded-full bg-white/10 overflow-hidden">+ <div className="mt-4 h-1.5 w-full rounded-full bg-white/10 overflow-hidden"><motion.divclassName="h-full bg-purple-400/70"animate={{ width: ["0%", "100%"] }}@@ -713,7 +769,7 @@ function DemoCAD() {{/* Room Elements - Only show after input */}{step >= 1 && (- <CadPlan step={step} />+ <CadPlan step={step} uiLang={uiLang} />)}</motion.div></div>@@ -722,14 +778,15 @@ function DemoCAD() {)}-function CadPlan({ step }: { step: number }) {- if (step === 1) return <CadPlan2D />;- if (step === 2) return <CadBomResult />;- if (step === 3) return <CadRenderResult />;+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} />;return null;}-function CadPlan2D() {+function CadPlan2D({ uiLang }: { uiLang: UiLanguage }) {+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);return (<div 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="absolute inset-0 flex">@@ -817,7 +874,7 @@ function CadPlan2D() {<path d="M52 38 L508 38" stroke="#666666" strokeWidth="1.5" markerStart="url(#dimTick)" markerEnd="url(#dimTick)" /><path d="M52 46 L52 32" stroke="#666666" strokeWidth="1.5" /><path d="M508 46 L508 32" stroke="#666666" strokeWidth="1.5" />- <text x="280" y="30" textAnchor="middle" fill="#666666" fontSize="11" fontFamily="ui-monospace, SFMono-Regular">轴线 A—A</text>+ <text x="280" y="30" textAnchor="middle" fill="#666666" fontSize="11" fontFamily="ui-monospace, SFMono-Regular">{tr("轴线 A—A", "Grid A—A")}</text></g><g opacity="0.85">@@ -839,17 +896,17 @@ function CadPlan2D() {<text x="530" y="78" textAnchor="middle" fill="rgba(17,24,39,0.55)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">N</text></g>- <text x="78" y="96" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">玄关</text>- <text x="292" y="96" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">客厅</text>- <text x="292" y="246" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">餐厅</text>- <text x="78" y="344" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">走廊</text>- <text x="304" y="364" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">厨房</text>+ <text x="78" y="96" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">{tr("玄关", "Entry")}</text>+ <text x="292" y="96" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">{tr("客厅", "Living")}</text>+ <text x="292" y="246" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">{tr("餐厅", "Dining")}</text>+ <text x="78" y="344" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">{tr("走廊", "Hall")}</text>+ <text x="304" y="364" fill="rgba(17,24,39,0.5)" fontSize="12" fontFamily="ui-monospace, SFMono-Regular">{tr("厨房", "Kitchen")}</text><g opacity="0.95"><circle cx="276" cy="86" r="4.5" fill="rgba(2,132,199,0.95)" /><path d="M272 86 L280 86" stroke="rgba(255,255,255,0.95)" strokeWidth="1.5" /><path d="M276 82 L276 90" stroke="rgba(255,255,255,0.95)" strokeWidth="1.5" />- <text x="284" y="90" fill="rgba(17,24,39,0.55)" fontSize="10" fontFamily="ui-monospace, SFMono-Regular">索引 1/PL-01</text>+ <text x="284" y="90" fill="rgba(17,24,39,0.55)" fontSize="10" fontFamily="ui-monospace, SFMono-Regular">{tr("索引 1/PL-01", "Index 1/PL-01")}</text></g><g opacity="0.95">@@ -868,34 +925,35 @@ function CadPlan2D() {</svg></div>- <CadInfoPanel />+ <CadInfoPanel uiLang={uiLang} /></div></div>);}-function CadBomResult() {+function CadBomResult({ uiLang }: { uiLang: UiLanguage }) {+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);return (<div 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-5 flex items-center justify-between border-b border-black/10 bg-white">- <div className="text-sm font-medium text-black/75">物料清单(示例)</div>+ <div className="text-sm font-medium text-black/75">{tr("物料清单(示例)", "BOM (Example)")}</div><div className="text-xs text-black/40 font-mono">BOM · Auto Estimated</div></div><div className="p-5"><div className="grid grid-cols-6 text-xs font-medium text-black/55 border-b border-black/10 pb-2">- <div>品类</div>- <div className="col-span-2">名称</div>- <div>规格</div>- <div className="text-right">数量</div>- <div className="text-right">单位</div>+ <div>{tr("品类", "Category")}</div>+ <div className="col-span-2">{tr("名称", "Name")}</div>+ <div>{tr("规格", "Spec")}</div>+ <div className="text-right">{tr("数量", "Qty")}</div>+ <div className="text-right">{tr("单位", "Unit")}</div></div><div className="mt-2 space-y-2 text-xs text-black/70">{[- { c: "地面", n: "木地板/地砖", s: "客厅 12mm", q: "28", u: "㎡" },- { c: "墙面", n: "乳胶漆", s: "哑光 · 暖白", q: "85", u: "㎡" },- { c: "顶面", n: "石膏线/灯槽", s: "简约线性", q: "18", u: "m" },- { c: "照明", n: "主灯 + 筒灯", s: "3000K", q: "12", u: "盏" },- { c: "软装", n: "窗帘", s: "亚麻 · 浅灰", q: "2", u: "套" }+ { c: tr("地面", "Floor"), n: tr("木地板/地砖", "Wood / Tile"), s: tr("客厅 12mm", "Living 12mm"), q: "28", u: tr("㎡", "m²") },+ { c: tr("墙面", "Wall"), n: tr("乳胶漆", "Latex Paint"), s: tr("哑光 · 暖白", "Matte · Warm White"), q: "85", u: tr("㎡", "m²") },+ { c: tr("顶面", "Ceiling"), n: tr("石膏线/灯槽", "Gypsum / Light Cove"), s: tr("简约线性", "Minimal Linear"), q: "18", u: "m" },+ { c: tr("照明", "Lighting"), n: tr("主灯 + 筒灯", "Main + Downlights"), s: "3000K", q: "12", u: tr("盏", "pcs") },+ { c: tr("软装", "Soft Furnishings"), n: tr("窗帘", "Curtains"), s: tr("亚麻 · 浅灰", "Linen · Light Gray"), q: "2", u: tr("套", "sets") }].map((r, idx) => (<div key={idx} className="grid grid-cols-6 items-center rounded-lg border border-black/10 bg-white/70 px-3 py-2"><div className="text-black/65">{r.c}</div>@@ -911,7 +969,8 @@ function CadBomResult() {);}-function CadRenderResult() {+function CadRenderResult({ uiLang }: { uiLang: UiLanguage }) {+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);return (<div className="absolute inset-0 rounded-2xl border border-white/10 overflow-hidden bg-black"><motion.div@@ -935,15 +994,15 @@ function CadRenderResult() {className="flex justify-between items-end"><div>- <div className="text-white/90 text-2xl font-light mb-1 font-artistic">新中式 · 禅意雅居</div>+ <div className="text-white/90 text-2xl font-light mb-1 font-artistic">{tr("新中式 · 禅意雅居", "Modern Chinese · Zen Living")}</div><div className="text-white/50 text-sm font-mono">RENDERED BY NEXUS AI · 8K ULTRA HD</div></div><div className="flex gap-2"><div className="px-3 py-1 rounded-full border border-white/20 bg-white/10 backdrop-blur-md text-xs text-white/70">- 极致光影+ {tr("极致光影", "Premium Lighting")}</div><div className="px-3 py-1 rounded-full border border-white/20 bg-white/10 backdrop-blur-md text-xs text-white/70">- 材质还原+ {tr("材质还原", "Material Fidelity")}</div></div></motion.div>@@ -956,49 +1015,50 @@ function CadRenderResult() {)}-function CadInfoPanel() {+function CadInfoPanel({ uiLang }: { uiLang: UiLanguage }) {+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);return (<div className="w-[200px] shrink-0 border-l border-black/10 bg-white/70"><div className="h-full px-3 py-3 flex flex-col"><div className="rounded-lg border border-black/15 bg-white/90 backdrop-blur-sm text-[10px] text-black/70 font-mono overflow-hidden">- <div className="px-3 py-2 border-b border-black/10 text-black/80 text-[12px] font-semibold text-center">室内平面布置图</div>+ <div className="px-3 py-2 border-b border-black/10 text-black/80 text-[12px] font-semibold text-center">{tr("室内平面布置图", "Furniture Plan")}</div><div className="grid grid-cols-[58px_1fr]">- <div className="px-2 py-1 border-b border-black/10">图号</div>+ <div className="px-2 py-1 border-b border-black/10">{tr("图号", "No.")}</div><div className="px-2 py-1 border-b border-black/10 text-black/80">PL-01</div>- <div className="px-2 py-1 border-b border-black/10">比例</div>+ <div className="px-2 py-1 border-b border-black/10">{tr("比例", "Scale")}</div><div className="px-2 py-1 border-b border-black/10 text-black/80">1:50</div>- <div className="px-2 py-1 border-b border-black/10">日期</div>+ <div className="px-2 py-1 border-b border-black/10">{tr("日期", "Date")}</div><div className="px-2 py-1 border-b border-black/10 text-black/80">2026-01</div>- <div className="px-2 py-1 border-b border-black/10">标高</div>+ <div className="px-2 py-1 border-b border-black/10">{tr("标高", "Elevation")}</div><div className="px-2 py-1 border-b border-black/10 text-black/80">±0.000</div>- <div className="px-2 py-1 border-b border-black/10">墙厚</div>- <div className="px-2 py-1 border-b border-black/10 text-black/80">外墙240 / 内墙120</div>+ <div className="px-2 py-1 border-b border-black/10">{tr("墙厚", "Wall")}</div>+ <div className="px-2 py-1 border-b border-black/10 text-black/80">{tr("外墙240 / 内墙120", "Ext 240 / Int 120")}</div></div><div className="px-3 py-2 border-t border-black/10">- <div className="text-black/70 mb-1">图例</div>+ <div className="text-black/70 mb-1">{tr("图例", "Legend")}</div><div className="grid grid-cols-[64px_1fr] gap-y-1 items-center"><div className="flex items-center gap-2"><div className="w-10 h-[6px] bg-[#0b1220]" /></div>- <div>承重墙</div>+ <div>{tr("承重墙", "Load-bearing")}</div><div className="flex items-center gap-2"><div className="w-10 h-[4px] bg-[#374151]" /></div>- <div>非承重墙</div>+ <div>{tr("非承重墙", "Partition")}</div><div className="flex items-center gap-2"><div className="w-10 h-[2px] bg-black/35" /><div className="w-[2px] h-[8px] bg-black/35" /></div>- <div>门窗线</div>+ <div>{tr("门窗线", "Doors/Windows")}</div><div className="flex items-center gap-2"><div className="w-4 h-4 rounded-full bg-green-500/90 border border-black/20 flex items-center justify-center text-white/95 text-[9px]">S</div></div>- <div>插座</div>+ <div>{tr("插座", "Outlet")}</div><div className="flex items-center gap-2"><div className="w-4 h-4 rounded-full bg-yellow-400/90 border border-black/20 flex items-center justify-center text-black/85 text-[9px]">K</div></div>- <div>开关</div>+ <div>{tr("开关", "Switch")}</div></div></div></div>@@ -1008,7 +1068,11 @@ function CadInfoPanel() {);}-function DemoPPT() {+function DemoPPT({ uiLang }: { uiLang: UiLanguage }) {+ const tr = (zh: string, en: string) => (uiLang === "zh" ? zh : en);+ const promptSpeed = 30;+ const promptText = tr("生成一份 GraphRAG 的演示文稿,要结构清晰、视觉震撼", "Create a GraphRAG deck: clear structure and impressive visuals");+ const promptHoldMs = Math.max(2800, estimateTypewriterDurationMs(promptText, promptSpeed));const pdfUrl = "/pdf/GraphRAG_Global_Knowledge_Structure.pdf";const [pdfDoc, setPdfDoc] = useState<any>(null);const [loadError, setLoadError] = useState<string | null>(null);@@ -1037,8 +1101,8 @@ function DemoPPT() {if (pdfDoc) return;getPdfDocumentFromUrl(pdfUrl).then((doc) => setPdfDoc(doc))- .catch(() => setLoadError("PDF 解析失败"));- }, [pdfDoc, pdfUrl]);+ .catch(() => setLoadError(uiLang === "zh" ? "PDF 解析失败" : "Failed to parse PDF"));+ }, [pdfDoc, pdfUrl, uiLang]);React.useEffect(() => {if (!pdfDoc) return;@@ -1083,7 +1147,7 @@ function DemoPPT() {t1 = setTimeout(() => {setPhase("generating");- }, 2800);+ }, promptHoldMs);t2 = setTimeout(() => {setPhase("scrolling");@@ -1098,7 +1162,7 @@ function DemoPPT() {t3 = setTimeout(() => setCycle((c) => c + 1), 900);}});- }, 4800);+ }, promptHoldMs + 2000);return () => {if (t1) clearTimeout(t1);@@ -1107,7 +1171,7 @@ function DemoPPT() {if (t4) clearTimeout(t4);controls?.stop?.();};- }, [cycle, endScroll, loadError, pdfDoc, scroll, slideCount, startScroll]);+ }, [cycle, endScroll, loadError, pdfDoc, promptHoldMs, scroll, slideCount, startScroll]);return (<div ref={stageRef} className="w-full h-full relative overflow-hidden">@@ -1118,7 +1182,7 @@ function DemoPPT() {{!loadError && !pdfDoc && (<div className="absolute inset-0 flex items-center justify-center"><div className="w-full max-w-xl rounded-2xl border border-white/18 bg-white/10 backdrop-blur-2xl p-6 text-white/60">- 正在加载演示文稿…+ {tr("正在加载演示文稿…", "Loading presentation…")}</div></div>)}@@ -1133,7 +1197,7 @@ function DemoPPT() {transition={{ duration: 0.35 }}className="absolute inset-0 flex items-center justify-center z-30">- <UserPrompt text="生成一份 GraphRAG 的演示文稿,要结构清晰、视觉震撼" color="cyan" />+ <UserPrompt text={promptText} color="cyan" speed={promptSpeed} /></motion.div>)}{phase === "generating" && (@@ -1149,14 +1213,14 @@ function DemoPPT() {initial={{ y: 10, opacity: 0 }}animate={{ y: 0, opacity: 1 }}exit={{ y: -10, opacity: 0 }}- className="rounded-2xl border border-cyan-300/25 bg-white/10 backdrop-blur-2xl px-7 py-6 shadow-[0_24px_80px_rgba(0,0,0,0.55)]"+ className="rounded-2xl border border-cyan-300/25 bg-white/10 backdrop-blur-2xl px-7 py-6 shadow-[0_24px_80px_rgba(0,0,0,0.55)] w-[min(90vw,420px)]"><div className="text-white/85 font-semibold flex items-center gap-2"><FileText className="w-4 h-4 text-cyan-200" />- 开始生成 PPT…+ {tr("开始生成 PPT…", "Generating PPT…")}</div>- <div className="text-white/45 text-sm mt-1">抽取要点 · 自动排版 · 渲染幻灯片</div>- <div className="mt-4 h-1.5 w-64 rounded-full bg-white/10 overflow-hidden">+ <div className="text-white/45 text-sm mt-1">{tr("抽取要点 · 自动排版 · 渲染幻灯片", "Extract key points · auto layout · render slides")}</div>+ <div className="mt-4 h-1.5 w-full rounded-full bg-white/10 overflow-hidden"><motion.divclassName="h-full bg-cyan-300/80"animate={{ width: ["0%", "100%"] }}@@ -1258,13 +1322,14 @@ function Typewriter({ text, speed = 50 }: { text: string, speed?: number }) {const [displayed, setDisplayed] = useState("");React.useEffect(() => {- let i = 0;+ const chars = Array.from(text);setDisplayed("");+ if (chars.length === 0) return;+ let i = 0;const timer = setInterval(() => {- if (i < text.length) {- setDisplayed((prev) => prev + text.charAt(i));- i++;- } else {+ i += 1;+ setDisplayed(chars.slice(0, i).join(""));+ if (i >= chars.length) {clearInterval(timer);}}, speed);