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
ppt_acc
codingFeng101f43fc34fc2ea
diff --git a/agent/cad/bom-prompt.md b/agent/cad/bom-prompt.mdnew file mode 100644index 0000000..9fced5d--- /dev/null+++ b/agent/cad/bom-prompt.md@@ -0,0 +1,14 @@+Generate a bill of materials for an interior renovation based on the plan and the existing CAD artifacts.++Plan (may be empty):+{{planJson}}++2D SVG (may be empty):+```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:+```json+{ "type": "cad_bom", "columns": ["品类","名称","规格","数量","单位","备注"], "rows": [] }+```diff --git a/agent/cad/images-prompt.md b/agent/cad/images-prompt.mdnew file mode 100644index 0000000..b24374c--- /dev/null+++ b/agent/cad/images-prompt.md@@ -0,0 +1,21 @@+Create 6 interior render prompts (multiple angles) for the same interior renovation.+Use realistic interior design language (lighting, materials, style, camera lens).++Inputs:+Plan (may be empty):+{{planJson}}++2D SVG (may be empty):+```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)++Return ONLY this JSON code block (no extra text):+```json+{ "type": "cad_images", "prompts": [ { "title": "客厅-广角", "prompt": "..." } ] }+```diff --git a/agent/cad/system.md b/agent/cad/system.mdnew file mode 100644index 0000000..5e4d86b--- /dev/null+++ b/agent/cad/system.md@@ -0,0 +1,49 @@+你是 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>+```diff --git a/agent/cad/tasks-system-hint.md b/agent/cad/tasks-system-hint.mdnew file mode 100644index 0000000..ebd9fc3--- /dev/null+++ b/agent/cad/tasks-system-hint.md@@ -0,0 +1,5 @@+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/system.md b/agent/flow/system.mdnew file mode 100644index 0000000..e3c8966--- /dev/null+++ b/agent/flow/system.md@@ -0,0 +1,20 @@+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>+```diff --git a/agent/ppt/pre-ready-constraints.md b/agent/ppt/pre-ready-constraints.mdnew file mode 100644index 0000000..2ea883f--- /dev/null+++ b/agent/ppt/pre-ready-constraints.md@@ -0,0 +1,5 @@+IMPORTANT:+- 当前处于“生成 PPT 之前”的大纲/文字编辑阶段。+- 绝对不要输出 imageEditInstruction。+- 绝对不要输出任何图片链接或 Markdown 图片(例如 )。+- 只输出 ```json``` 代码块,内容为 { "type": "ppt_edit", "slides": [...] },仅修改文字字段(title/content/description/note/layout)。diff --git a/agent/ppt/system.md b/agent/ppt/system.mdnew file mode 100644index 0000000..e4ac10c--- /dev/null+++ b/agent/ppt/system.md@@ -0,0 +1,45 @@+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.++## JSON Structure:+You must return a JSON object with a "slides" array. Each slide has a "title", "content" (bullet points), and "layout".++Example Format:+```json+{+ "theme": "modern",+ "slides": [+ {+ "id": "slide-1",+ "title": "Presentation Title",+ "content": [+ "Point 1",+ "Point 2"+ ],+ "note": "Speaker notes here"+ }+ ]+}+```++## 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:+```json+{+ "type": "ppt_edit",+ "slides": [+ {+ "id": "slide-1",+ "title": "...",+ "content": ["..."],+ "description": "...",+ "imageEditInstruction": "..."+ }+ ]+}+```diff --git a/docs/product-requirements-document.md b/docs/product-requirements-document.mddeleted file mode 100644index bbe74c1..0000000--- a/docs/product-requirements-document.md+++ /dev/null@@ -1,111 +0,0 @@-## 1. 产品概述--统一AI工作空间是一个集成多种工作模式的协作平台,通过分屏布局将工作区与AI聊天面板结合,为用户提供流程图设计、CAD绘图和PPT制作的无缝体验。--该产品主要解决设计师、工程师和项目管理者在多工具间切换的效率问题,通过AI驱动的聊天界面统一控制各种工作模式,提升工作流程的连贯性和智能化水平。--## 2. 核心功能--### 2.1 用户角色--| 角色 | 注册方式 | 核心权限 |-|------|----------|----------|-| 普通用户 | 邮箱注册 | 使用基础工作模式,保存项目 |-| 高级用户 | 邀请码升级 | 导出高级格式,团队协作,AI增强功能 |--### 2.2 功能模块--统一AI工作空间包含以下核心页面:--1. **主工作区**:分屏布局,左侧工作区域,右侧聊天面板-2. **模式切换栏**:流程图模式、CAD模式、PPT模式的快速切换-3. **项目管理**:项目列表、新建、保存、导出功能--### 2.3 页面详情--| 页面名称 | 模块名称 | 功能描述 |-|----------|----------|----------|-| 主工作区 | 分屏布局 | 实现可调整大小的左右分屏,左侧占60%显示工作区,右侧40%显示聊天面板 |-| 主工作区 | 模式切换 | 提供三种工作模式的图标切换按钮,支持快捷键切换 |-| 流程图模式 | draw.io集成 | 嵌入draw.io编辑器,支持节点选择和边选择,点击"添加到聊天"发送XML片段 |-| CAD模式 | SVG渲染器 | 加载和显示2D CAD文件(SVG格式),支持元素点击选择,发送Python/CAD代码片段 |-| PPT模式 | 图片序列 | 按顺序显示多张图片,支持前后翻页,缩略图预览 |-| 聊天面板 | 消息列表 | 显示用户与AI的对话历史,支持消息时间戳和发送者标识 |-| 聊天面板 | 输入框 | 支持多行文本输入,发送按钮,清空聊天记录功能 |-| 项目管理 | 文件操作 | 新建项目、打开项目、保存项目、导出为不同格式 |--## 3. 核心流程--用户进入主工作区后,可以通过顶部工具栏选择工作模式:--**流程图模式流程**:-1. 用户选择流程图模式,加载draw.io编辑器-2. 在左侧绘制流程图,选择节点或连接线-3. 点击"添加到聊天"按钮,将选中元素的XML数据发送到右侧聊天面板-4. 在聊天面板中与AI对话,AI根据流程图内容提供建议--**CAD模式流程**:-1. 用户切换到CAD模式,加载SVG文件-2. 点击CAD图形中的元素进行选择-3. 点击"添加到聊天",发送对应的Python/CAD代码片段-4. AI分析代码并提供修改建议或生成相关代码--**PPT模式流程**:-1. 用户进入PPT模式,上传或选择图片序列-2. 使用导航控件浏览不同页面-3. 在聊天面板中描述需求,AI协助生成新的幻灯片内容--```mermaid-graph TD- A[登录页面] --> B[主工作区]- B --> C[模式选择]- C --> D[流程图模式]- C --> E[CAD模式]- C --> F[PPT模式]- D --> G[draw.io编辑器]- E --> H[SVG渲染器]- F --> I[图片序列展示]- G --> J[添加到聊天]- H --> J- I --> J- J --> K[AI聊天面板]- K --> L[生成建议]- L --> M[应用修改]-```--## 4. 用户界面设计--### 4.1 设计风格--- **主色调**:深蓝色(#1e40af)作为主色,浅灰色(#f3f4f6)作为背景-- **按钮样式**:圆角矩形,悬停效果,主要操作为实心按钮,次要操作为边框按钮-- **字体**:Inter字体族,标题18px,正文14px,小字12px-- **布局风格**:卡片式布局,阴影效果,适当的间距和留白-- **图标风格**:使用Lucide图标库,线条简洁,统一大小20x20px--### 4.2 页面设计概述--| 页面名称 | 模块名称 | UI元素 |-|----------|----------|----------|-| 主工作区 | 分屏布局 | 使用React Resizable Panels,支持拖拽调整比例,最小宽度限制 |-| 主工作区 | 顶部工具栏 | 固定在顶部,包含模式切换按钮组,项目操作按钮,用户信息 |-| 流程图模式 | 编辑器容器 | iframe嵌入draw.io,边框阴影,加载状态指示器 |-| CAD模式 | SVG容器 | 自适应大小,支持缩放和平移,选中元素高亮显示 |-| PPT模式 | 图片容器 | 居中显示,支持键盘左右箭头导航,底部缩略图条 |-| 聊天面板 | 消息气泡 | 用户消息右对齐蓝色背景,AI消息左对齐白色背景 |-| 聊天面板 | 输入区域 | 底部固定,包含文本框和发送按钮,支持Enter快捷键 |--### 4.3 响应式设计--采用桌面优先设计策略:-- 最小支持宽度:1280px-- 工作区与聊天面板比例可在40:60到80:20之间调整-- 移动端采用堆叠布局,工作区在上,聊天面板在下-- 触摸优化:增大点击区域,支持手势缩放--### 4.4 交互细节--- 模式切换使用平滑过渡动画,时长300ms-- 添加到聊天按钮在选中元素后显示,带有脉冲动画提示-- 聊天消息发送后显示打字指示器,模拟AI思考过程-- 所有操作提供视觉反馈,成功/失败状态用颜色和图标区分\ No newline at end of filediff --git a/docs/technical-architecture-document.md b/docs/technical-architecture-document.mddeleted file mode 100644index 6be6e7e..0000000--- a/docs/technical-architecture-document.md+++ /dev/null@@ -1,325 +0,0 @@-## 1. 架构设计--```mermaid-graph TD- A[用户浏览器] --> B[Next.js前端应用]- B --> C[React组件层]- C --> D[状态管理]- C --> E[UI组件库]-- subgraph "前端层"- B- C- D- E- F[draw.io集成]- G[SVG处理器]- H[图片管理器]- end-- subgraph "外部服务"- I[draw.io API]- J[AI服务API]- end-- B --> F- B --> G- B --> H- F --> I- C --> J-```--## 2. 技术描述--- **前端框架**: Next.js@14 + React@18 + TypeScript@5-- **UI组件库**: shadcn/ui + Radix UI + Tailwind CSS@3-- **图标库**: Lucide React-- **布局管理**: React Resizable Panels-- **状态管理**: Zustand-- **构建工具**: Next.js内置构建系统-- **包管理**: pnpm--### 核心依赖-```json-{- "dependencies": {- "next": "^14.0.0",- "react": "^18.2.0",- "react-dom": "^18.2.0",- "@radix-ui/react-": "^latest",- "lucide-react": "^latest",- "react-resizable-panels": "^latest",- "zustand": "^latest",- "clsx": "^latest",- "tailwind-merge": "^latest"- },- "devDependencies": {- "typescript": "^5.0.0",- "@types/react": "^18.2.0",- "@types/react-dom": "^18.2.0",- "tailwindcss": "^3.3.0",- "autoprefixer": "^latest",- "postcss": "^latest"- }-}-```--## 3. 路由定义--| 路由 | 用途 |-|------|------|-| `/` | 主页,重定向到工作区 |-| `/workspace` | 主工作区,包含分屏布局和模式切换 |-| `/workspace/flowchart` | 流程图模式,集成draw.io编辑器 |-| `/workspace/cad` | CAD模式,SVG渲染和交互 |-| `/workspace/ppt` | PPT模式,图片序列展示 |-| `/api/chat` | 聊天API,处理AI对话请求 |-| `/api/project/save` | 项目保存API |-| `/api/project/load` | 项目加载API |-| `/api/project/export` | 项目导出API |--## 4. 核心组件架构--### 4.1 主布局组件-```typescript-interface MainLayoutProps {- children: React.ReactNode;- defaultLayout?: number[];- defaultCollapsed?: boolean;-}--interface PanelLayout {- leftPanel: number; // 百分比 40-80%- rightPanel: number; // 百分比 20-60%-}-```--### 4.2 工作模式状态管理-```typescript-interface WorkspaceState {- currentMode: 'flowchart' | 'cad' | 'ppt';- isLoading: boolean;- selectedElements: SelectedElement[];- chatHistory: ChatMessage[];-}--interface SelectedElement {- id: string;- type: 'node' | 'edge' | 'cad-element' | 'slide';- data: any; // XML, Python代码, 图片数据等- timestamp: number;-}--interface ChatMessage {- id: string;- role: 'user' | 'assistant';- content: string;- timestamp: number;- mode?: string; // 关联的工作模式-}-```--### 4.3 draw.io集成接口-```typescript-interface DrawIOIntegration {- embedUrl: string;- onElementSelect: (element: DrawElement) => void;- getSelectedXML: () => string;- addToChat: (xmlData: string) => void;-}--interface DrawElement {- id: string;- type: 'node' | 'edge';- label: string;- xmlData: string;- bounds: DOMRect;-}-```--### 4.4 CAD模式接口-```typescript-interface CADViewerProps {- svgContent: string;- onElementClick: (element: CADElement) => void;- zoomLevel: number;- panOffset: { x: number; y: number };-}--interface CADElement {- id: string;- type: string; // 'line' | 'circle' | 'rectangle' | 'path'- properties: Record<string, any>;- pythonCode?: string;- cadCode?: string;-}-```--### 4.5 PPT模式接口-```typescript-interface PPTViewerProps {- slides: Slide[];- currentSlide: number;- onSlideChange: (index: number) => void;- showThumbnails: boolean;-}--interface Slide {- id: string;- imageUrl: string;- title?: string;- notes?: string;- order: number;-}-```--## 5. 状态管理设计--```typescript-// Zustand store结构-interface AppStore {- // UI状态- sidebarCollapsed: boolean;- panelLayout: PanelLayout;- theme: 'light' | 'dark';-- // 工作区状态- workspace: WorkspaceState;-- // 项目状态- currentProject: Project | null;- unsavedChanges: boolean;-- // 方法- setPanelLayout: (layout: PanelLayout) => void;- switchMode: (mode: WorkspaceMode) => void;- addToChat: (element: SelectedElement) => void;- sendMessage: (message: string) => Promise<void>;- saveProject: () => Promise<void>;-}--interface Project {- id: string;- name: string;- mode: WorkspaceMode;- data: any; // 模式特定的数据- createdAt: Date;- updatedAt: Date;-}-```--## 6. 组件层次结构--```-src/-├── app/-│ ├── layout.tsx # 根布局-│ ├── page.tsx # 主页-│ └── workspace/-│ ├── page.tsx # 工作区主页面-│ └── [mode]/-│ └── page.tsx # 特定模式页面-├── components/-│ ├── workspace/-│ │ ├── MainLayout.tsx # 主布局组件-│ │ ├── PanelLayout.tsx # 分屏布局组件-│ │ ├── ModeSelector.tsx # 模式选择器-│ │ ├── Toolbar.tsx # 工具栏-│ │ └── StatusBar.tsx # 状态栏-│ ├── flowchart/-│ │ ├── DrawIOViewer.tsx # draw.io查看器-│ │ ├── ElementSelector.tsx # 元素选择器-│ │ └── XMLParser.ts # XML解析工具-│ ├── cad/-│ │ ├── SVGViewer.tsx # SVG查看器-│ │ ├── ElementHighlighter.tsx # 元素高亮-│ │ └── CodeGenerator.ts # 代码生成器-│ ├── ppt/-│ │ ├── SlideViewer.tsx # 幻灯片查看器-│ │ ├── ThumbnailBar.tsx # 缩略图条-│ │ └── ImageUploader.tsx # 图片上传器-│ └── chat/-│ ├── ChatPanel.tsx # 聊天面板-│ ├── MessageList.tsx # 消息列表-│ ├── MessageInput.tsx # 消息输入-│ └── MessageBubble.tsx # 消息气泡-├── lib/-│ ├── hooks/ # 自定义hooks-│ ├── utils/ # 工具函数-│ └── stores/ # 状态管理-└── types/ # TypeScript类型定义-```--## 7. 性能优化策略--### 7.1 代码分割-- 按工作模式进行代码分割,减少初始加载时间-- 动态导入draw.io等大型依赖-- 使用Next.js的自动代码分割功能--### 7.2 缓存策略-- 使用React.memo优化组件重渲染-- 实现虚拟滚动处理大量聊天消息-- 缓存解析后的SVG和XML数据--### 7.3 加载优化-- 图片懒加载和预加载策略-- draw.io编辑器的异步加载-- 骨架屏提升感知性能--## 8. 错误处理--### 8.1 错误边界-```typescript-interface ErrorBoundaryState {- hasError: boolean;- error: Error | null;- errorInfo: ErrorInfo | null;-}-```--### 8.2 错误类型-- 网络错误:API调用失败处理-- 解析错误:XML/SVG解析失败-- 集成错误:draw.io加载失败-- 用户操作错误:文件格式不支持--## 9. 安全性考虑--### 9.1 XSS防护-- 对用户输入进行转义-- SVG内容的安全检查-- iframe的沙箱属性配置--### 9.2 CSRF防护-- API请求使用CSRF token-- 文件上传的安全验证-- 跨域请求的正确配置--## 10. 开发环境配置--### 10.1 环境变量-```env-NEXT_PUBLIC_API_URL=http://localhost:3000/api-NEXT_PUBLIC_DRAWIO_URL=https://embed.diagrams.net-NEXT_PUBLIC_AI_SERVICE_URL=https://api.example.com-```--### 10.2 开发脚本-```json-{- "scripts": {- "dev": "next dev",- "build": "next build",- "start": "next start",- "lint": "next lint",- "type-check": "tsc --noEmit"- }-}-```--### 10.3 构建配置-- Next.js配置文件优化-- Tailwind CSS配置-- TypeScript严格模式启用-- ESLint和Prettier代码规范\ No newline at end of filediff --git a/package.json b/package.jsonindex 9bc84e7..aff6a53 100644--- a/package.json+++ b/package.json@@ -5,7 +5,6 @@"type": "module","scripts": {"dev": "vite",- "freecad:server": "node server/freecad-server.mjs","build": "tsc -b && vite build","lint": "eslint .","preview": "vite preview",diff --git a/server/freecad-server.mjs b/server/freecad-server.mjsdeleted file mode 100644index 3f32476..0000000--- a/server/freecad-server.mjs+++ /dev/null@@ -1,166 +0,0 @@-import http from "node:http"-import { URL } from "node:url"-import { promises as fs } from "node:fs"-import path from "node:path"-import os from "node:os"-import { spawn } from "node:child_process"-import { randomUUID } from "node:crypto"--const PORT = Number(process.env.FREECAD_SERVER_PORT || 43110)-const FREECAD_CMD = process.env.FREECAD_CMD || "E:\\freecad\\bin\\freecad.exe"-const ROOT = path.join(os.tmpdir(), "freecad-runner")--const setCors = (res) => {- res.setHeader("Access-Control-Allow-Origin", "*")- res.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS")- res.setHeader("Access-Control-Allow-Headers", "Content-Type")-}--const send = (res, status, body, headers = {}) => {- setCors(res)- Object.entries(headers).forEach(([k, v]) => res.setHeader(k, v))- res.statusCode = status- res.end(body)-}--const sendJson = (res, status, obj) => {- send(res, status, JSON.stringify(obj), { "Content-Type": "application/json; charset=utf-8" })-}--const readBody = (req) =>- new Promise((resolve, reject) => {- let data = ""- req.on("data", (chunk) => {- data += chunk- if (data.length > 5_000_000) {- req.destroy()- reject(new Error("Body too large"))- }- })- req.on("end", () => resolve(data))- req.on("error", reject)- })--const getFreecadArgs = (exePath, scriptPath) => {- const base = path.basename(exePath).toLowerCase()- if (base.includes("freecadcmd")) return [scriptPath]- return ["-c", scriptPath]-}--const runFreecad = async (code) => {- const id = randomUUID()- const jobDir = path.join(ROOT, id)- await fs.mkdir(jobDir, { recursive: true })-- const scriptPath = path.join(jobDir, "job.py")- const outputPath = path.join(jobDir, "model.stl")- const escapedOutputPath = outputPath.replace(/\\/g, "\\\\")-- const scriptParts = [- "import os",- "import sys",- `output_path = r\"${escapedOutputPath}\"`,- code,- "import FreeCAD as App",- "import Mesh",- "doc = App.ActiveDocument",- "if doc is None:",- " doc = App.newDocument(\"Doc\")",- "doc.recompute()",- "objs = [o for o in doc.Objects if hasattr(o, \"Shape\") and not o.Shape.isNull()]",- "if len(objs) == 0:",- " raise Exception(\"No exportable objects\")",- "Mesh.export(objs, output_path)",- "print(\"EXPORT_OK:\" + output_path)",- ]- const pythonScript = scriptParts.join("\n")-- await fs.writeFile(scriptPath, pythonScript, "utf-8")-- const stdout = []- const stderr = []-- const proc = spawn(FREECAD_CMD, getFreecadArgs(FREECAD_CMD, scriptPath), { windowsHide: true })-- const timeoutMs = Number(process.env.FREECAD_TIMEOUT_MS || 120000)- const timeout = setTimeout(() => {- try {- proc.kill()- } catch {- }- }, timeoutMs)-- const exitCode = await new Promise((resolve, reject) => {- proc.stdout.on("data", (d) => stdout.push(d.toString()))- proc.stderr.on("data", (d) => stderr.push(d.toString()))- proc.on("error", reject)- proc.on("close", resolve)- })-- clearTimeout(timeout)-- const exists = await fs.stat(outputPath).then(() => true).catch(() => false)- if (exitCode !== 0 || !exists) {- const err = stderr.join("") || stdout.join("") || "FreeCAD 执行失败"- throw new Error(err)- }-- return { id }-}--const server = http.createServer(async (req, res) => {- if (!req.url) {- send(res, 404, "Not Found")- return- }-- const url = new URL(req.url, "http://localhost")- const pathname = url.pathname-- if (req.method === "OPTIONS") {- send(res, 204, "")- return- }-- if (req.method === "POST" && pathname === "/api/freecad/run") {- try {- const body = await readBody(req)- const payload = JSON.parse(body || "{}")- const code = String(payload.code || "").trim()- if (!code) {- send(res, 400, "Missing code")- return- }- const result = await runFreecad(code)- sendJson(res, 200, { meshUrl: `/api/freecad/mesh/${result.id}` })- return- } catch (e) {- const message = e instanceof Error ? e.message : "FreeCAD 执行失败"- send(res, 500, message)- return- }- }-- if (req.method === "GET" && pathname.startsWith("/api/freecad/mesh/")) {- const id = pathname.split("/").pop() || ""- if (!/^[a-zA-Z0-9_-]+$/.test(id)) {- send(res, 400, "Invalid id")- return- }- const filePath = path.join(ROOT, id, "model.stl")- try {- const data = await fs.readFile(filePath)- send(res, 200, data, { "Content-Type": "model/stl" })- return- } catch {- send(res, 404, "Not Found")- return- }- }-- send(res, 404, "Not Found")-})--server.listen(PORT, () => {- console.log(`FreeCAD server listening on http://localhost:${PORT}`)-})diff --git a/src/App.tsx b/src/App.tsxindex 529b8e6..ee5be57 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -7,16 +7,54 @@ 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 { getAIConfig, type ChatMessage } from '@/lib/ai-client';+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 { generateImage, getAIConfig, type ChatMessage } from '@/lib/ai-client';import { Toaster } from 'sonner';import { LandingPage } from '@/pages/LandingPage';import { HistoryItem } from '@/components/history-dialog';+import { Button } from "@/components/ui/button";type WorkspaceType = 'flow' | 'cad' | 'ppt';const HISTORY_STORAGE_KEY = 'unified-ai-workspace-history';+class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { error: Error | null }> {+ state: { error: Error | null } = { error: null };++ static getDerivedStateFromError(error: Error) {+ return { error };+ }++ componentDidCatch(error: Error) {+ console.error("UI crashed", error);+ }++ render() {+ if (this.state.error) {+ return (+ <div className="w-full h-full flex items-center justify-center p-6">+ <div className="max-w-[720px] w-full rounded-xl border border-border/60 bg-background p-5">+ <div className="text-base font-medium mb-2">页面发生错误</div>+ <div className="text-sm text-muted-foreground whitespace-pre-wrap break-words mb-4">+ {String(this.state.error?.message || "Unknown error")}+ </div>+ <div className="flex items-center gap-2">+ <Button variant="default" onClick={() => window.location.reload()}>+ 刷新页面+ </Button>+ <Button variant="outline" onClick={() => this.setState({ error: null })}>+ 尝试继续+ </Button>+ </div>+ </div>+ </div>+ );+ }+ return this.props.children as any;+ }+}+function App() {const [showLanding, setShowLanding] = useState(true);const [activeWorkspace, setActiveWorkspace] = useState<WorkspaceType>('flow');@@ -24,8 +62,15 @@ function App() {// Workspace specific statesconst [generatedXml, setGeneratedXml] = useState<string | undefined>(undefined);- const [generatedCadCode, setGeneratedCadCode] = useState<string | undefined>(undefined);+ const [cad2dSvg, setCad2dSvg] = useState<string | undefined>(undefined);+ const [cadPlan, setCadPlan] = useState<any>(null);+ const [cadImages, setCadImages] = useState<{ title: string; url: string }[]>([]);+ const [cadImagesLoading, setCadImagesLoading] = useState(false);+ const [cadBom, setCadBom] = useState<{ columns: string[]; rows: any[] } | null>(null);+ const [cadFocusPanel, setCadFocusPanel] = useState<"2d" | "renders" | "bom" | null>(null);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 cadImageObjectUrlsRef = useRef<string[]>([]);// Chat History Management (Per Workspace)const [chatHistories, setChatHistories] = useState<Record<WorkspaceType, ChatMessage[]>>({@@ -54,6 +99,22 @@ function App() {localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(versionHistories));}, [versionHistories]);+ useEffect(() => {+ const nextObjectUrls = cadImages+ .map((x) => x?.url)+ .filter((u): u is string => typeof u === "string" && u.startsWith("blob:"));+ const prevObjectUrls = cadImageObjectUrlsRef.current;+ for (const u of prevObjectUrls) {+ if (!nextObjectUrls.includes(u)) {+ try {+ URL.revokeObjectURL(u);+ } catch {+ }+ }+ }+ cadImageObjectUrlsRef.current = nextObjectUrls;+ }, [cadImages]);+// Layout Stateconst [isChatCollapsed, setIsChatCollapsed] = useState(false);const chatPanelRef = useRef<PanelImperativeHandle | null>(null);@@ -63,14 +124,12 @@ function App() {useEffect(() => {if (pptChatLocked && isChatCollapsed) {setIsChatCollapsed(false);- chatPanelRef.current?.expand();}}, [pptChatLocked, isChatCollapsed]);useEffect(() => {if (activeWorkspace === "ppt" && !pptChatLocked) {setIsChatCollapsed(false);- chatPanelRef.current?.expand();}}, [activeWorkspace, pptChatLocked]);@@ -78,12 +137,17 @@ function App() {if (pptChatLocked) return;const panel = chatPanelRef.current;if (panel) {- if (panel.isCollapsed?.() || isChatCollapsed) {- panel.expand();+ try {+ if (panel.isCollapsed?.() || isChatCollapsed) {+ panel.expand();+ setIsChatCollapsed(false);+ } else {+ panel.collapse();+ setIsChatCollapsed(true);+ }+ } catch (e) {+ console.error("Failed to toggle chat panel", e);setIsChatCollapsed(false);- } else {- panel.collapse();- setIsChatCollapsed(true);}}};@@ -111,6 +175,41 @@ function App() {})();const handleAddToChat = (code: string, type: 'xml' | 'python' | 'json' = 'xml', name: string = 'attachment') => {+ if (activeWorkspace === "ppt" && type === "json") {+ const tryAddSlide = (slide: any) => {+ if (!slide || typeof slide !== "object") return;+ const slideId = typeof slide.id === "string" && slide.id.trim() ? slide.id.trim() : "";+ if (!slideId) return;+ const title = typeof slide.title === "string" ? slide.title : "";+ const imageUrl = typeof slide.imageUrl === "string" ? slide.imageUrl : "";+ const kind: "outline" | "slide_image" = imageUrl ? "slide_image" : "outline";+ const json = JSON.stringify(slide, null, 2);+ setPptDraftSlides((prev) => {+ const next = prev.filter((x) => x.slideId !== slideId);+ return [...next, { id: `${Date.now()}-${Math.random().toString(16).slice(2)}`, slideId, title, json, kind, imageUrl: imageUrl || undefined }];+ });+ };++ try {+ const parsed = JSON.parse(code);+ if (parsed && typeof parsed === "object" && Array.isArray((parsed as any).slides)) {+ for (const s of (parsed as any).slides) tryAddSlide(s);+ return;+ }+ tryAddSlide(parsed);+ return;+ } catch {+ const m = String(name || "").match(/^(slide-\d+)\.json$/i);+ if (m) {+ setPptDraftSlides((prev) => [+ ...prev,+ { id: `${Date.now()}-${Math.random().toString(16).slice(2)}`, slideId: m[1], title: "", json: String(code || ""), kind: "outline" }+ ]);+ return;+ }+ }+ }+setAttachments(prev => [...prev,{@@ -126,7 +225,10 @@ function App() {switch (type) {case 'flow': return DRAWIO_SYSTEM_PROMPT;case 'cad': return CAD_SYSTEM_PROMPT;- case 'ppt': return PPT_SYSTEM_PROMPT;+ case 'ppt': {+ if (pptReady) return PPT_SYSTEM_PROMPT;+ return `${PPT_SYSTEM_PROMPT}\n\n${pptPreReadyConstraints}`.trim();+ }default: return DRAWIO_SYSTEM_PROMPT;}};@@ -142,7 +244,7 @@ function App() {return undefined;};- const addToHistory = (content: string, type: 'xml' | 'python' | 'json') => {+ const addToHistory = (content: string, type: HistoryItem["type"]) => {const newItem: HistoryItem = {id: Date.now().toString(),timestamp: Date.now(),@@ -155,10 +257,50 @@ function App() {}));};- const handleRestore = (item: HistoryItem) => {- if (item.type === 'xml') setGeneratedXml(item.content);- if (item.type === 'python') setGeneratedCadCode(item.content);- if (item.type === 'json') setPptIncomingEdit({ id: `${Date.now()}`, payload: item.content });+ const handleRestore = (workspace: WorkspaceType, item: HistoryItem) => {+ if (workspace === 'flow') {+ if (item.type === 'xml') setGeneratedXml(item.content);+ return;+ }++ if (workspace === 'ppt') {+ if (item.type === 'json') setPptIncomingEdit({ id: `${Date.now()}`, payload: item.content });+ return;+ }++ if (workspace === 'cad') {+ if (item.type === 'svg') {+ setCad2dSvg(item.content);+ return;+ }+ if (item.type === 'json') {+ try {+ const parsed = JSON.parse(item.content);+ if (parsed?.type === "cad_plan") setCadPlan(parsed);+ if (parsed?.type === "cad_bom") setCadBom({ columns: parsed.columns || [], rows: parsed.rows || [] });+ if (parsed?.type === "cad_images") {+ const next = Array.isArray(parsed.prompts)+ ? parsed.prompts+ .filter((p: any) => p && typeof p.title === "string" && typeof p.url === "string")+ .map((p: any) => ({ title: p.title, url: p.url }))+ : [];+ if (next.length > 0) setCadImages(next);+ }+ } catch {+ }+ }+ }+ };++ const applyStringEdits = (source: string, edits: { search: string; replace: string }[]) => {+ 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);+ }+ return out;};if (showLanding) {@@ -223,7 +365,8 @@ function App() {{/* Main Content Area */}<div className="flex-1 overflow-hidden relative">- <ResizablePanelGroup orientation="horizontal" className="h-full" style={{ height: '100%' }}>+ <ErrorBoundary>+ <ResizablePanelGroup orientation="horizontal" className="h-full" style={{ height: '100%' }}><ResizablePanel defaultSize={pptChatLocked ? "100%" : "68%"} minSize="30%"><div className="h-full w-full relative bg-muted/20">{activeWorkspace === 'flow' && (@@ -234,8 +377,25 @@ function App() {)}{activeWorkspace === 'cad' && (<CadWorkspace- code={generatedCadCode}- onAddToChat={(code) => handleAddToChat(code, 'python', 'script.py')}+ svg2d={cad2dSvg}+ plan={cadPlan}+ images={cadImages}+ imagesLoading={cadImagesLoading}+ bom={cadBom}+ focusPanel={cadFocusPanel}+ onAddToChat={(payload) => {+ const trimmed = String(payload || "").trim();+ if (!trimmed) return;+ if (trimmed.startsWith("<svg")) {+ handleAddToChat(payload, 'xml', 'plan.svg');+ return;+ }+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {+ handleAddToChat(payload, 'json', 'cad.json');+ return;+ }+ handleAddToChat(payload, 'python', 'script.py');+ }}/>)}{activeWorkspace === 'ppt' && (@@ -260,9 +420,7 @@ function App() {maxSize="70%"collapsible={!pptChatLocked}collapsedSize="56px"- onResize={(panelSize) => {- setIsChatCollapsed(panelSize.inPixels <= 80);- }}+ onResize={(panelSize) => setIsChatCollapsed(panelSize.inPixels <= 80)}className={cn("transition-all duration-300")}><ChatPanel@@ -281,15 +439,166 @@ function App() {inputPlaceholder={chatUi.placeholder}onToggleCollapse={handleToggleCollapse}onRemoveAttachment={(id) => setAttachments(prev => prev.filter(a => a.id !== id))}+ onClearAttachments={() => setAttachments([])}+ pptDraftSlides={activeWorkspace === "ppt" ? pptDraftSlides : []}+ onRemovePptDraftSlide={(id) => setPptDraftSlides(prev => prev.filter(s => s.id !== id))}+ onClearPptDraftSlides={() => setPptDraftSlides([])}history={versionHistories[activeWorkspace]}- onRestore={handleRestore}+ onRestore={(item) => handleRestore(activeWorkspace, item)}+ onClearVersionHistory={() => {+ setVersionHistories(prev => ({ ...prev, [activeWorkspace]: [] }));+ }}+ cadContext={activeWorkspace === "cad" ? { plan: cadPlan, svg2d: cad2dSvg } : undefined}onCodeAction={(code, type) => {if (type === 'flow') {setGeneratedXml(code);addToHistory(code, 'xml');} else if (type === 'cad') {- setGeneratedCadCode(code);- addToHistory(code, 'python');+ const raw = String(code || "");+ const trimmed = raw.trim();+ if (!trimmed) return;++ if (trimmed.startsWith("<svg")) {+ setCad2dSvg(raw);+ setCadFocusPanel("2d");+ addToHistory(raw, 'svg');+ return;+ }++ 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 === "cad_plan") {+ setCadPlan(parsed);+ addToHistory(JSON.stringify(parsed), 'json');+ return;+ }+ if (parsed?.type === "cad_bom") {+ const fallbackColumns = ["品类", "名称", "规格", "数量", "单位", "备注"];+ const columns = Array.isArray(parsed.columns) && parsed.columns.length > 0+ ? parsed.columns.map((x: any) => String(x))+ : fallbackColumns;+ const rows = Array.isArray(parsed.rows) ? parsed.rows : [];+ setCadBom({ columns, rows });+ setCadFocusPanel("bom");+ addToHistory(JSON.stringify({ type: "cad_bom", columns, rows }), 'json');+ return;+ }+ if (parsed?.type === "cad_images") {+ const prompts = Array.isArray(parsed.prompts) ? parsed.prompts : [];+ const items = prompts+ .map((p: any) => ({+ title: typeof p?.title === "string" ? p.title : "视角",+ prompt: typeof p?.prompt === "string" ? p.prompt : ""+ }))+ .filter((p: any) => p.prompt);++ (async () => {+ setCadFocusPanel("renders");+ setCadImagesLoading(true);+ setCadImages([]);+ try {+ const results: { title: string; url: string; prompt: string }[] = [];++ const presetRenderPrompt = [+ "photorealistic interior render, ultra realistic materials, high quality lighting",+ "clean composition, no watermark, no text overlay",+ "natural proportions, realistic textures, detailed shadows, global illumination"+ ].join(", ");++ const planText = cadPlan ? JSON.stringify(cadPlan) : "";+ const svgText = typeof cad2dSvg === "string" ? cad2dSvg : "";++ const maxPlanChars = 6000;+ const maxSvgChars = 6000;++ const planShort = planText.length > maxPlanChars ? planText.slice(0, maxPlanChars) : planText;+ const svgShort = svgText.length > maxSvgChars ? svgText.slice(0, maxSvgChars) : svgText;++ const list = items.slice(0, 6);+ const batchSize = 3;+ for (let i = 0; i < list.length; i += batchSize) {+ const batch = list.slice(i, i + batchSize);+ const settled = await Promise.allSettled(+ batch.map(async (p) => {+ const fullPrompt = [+ presetRenderPrompt,+ "",+ "Plan:",+ planShort,+ "",+ "2D SVG:",+ svgShort,+ "",+ "Shot:",+ p.prompt+ ].filter(Boolean).join("\n");+ const url = await generateImage({ prompt: fullPrompt });+ return url ? { title: p.title, url, prompt: p.prompt } : null;+ })+ );+ for (const s of settled) {+ if (s.status === "fulfilled" && s.value?.url) results.push(s.value);+ }+ }++ const final = results.map((r) => ({ title: r.title, url: r.url }));+ setCadImages(final);+ addToHistory(JSON.stringify({ type: "cad_images", prompts: results }), 'json');+ } catch (e) {+ console.error("CAD image generation failed", e);+ setCadImages([]);+ } finally {+ setCadImagesLoading(false);+ setCadFocusPanel("renders");+ }+ })();+ return;+ }+ if (parsed?.type === "cad_patch") {+ const target = parsed?.target;+ const mode = parsed?.mode;+ if (target === "2d_svg") {+ const current = cad2dSvg || "";+ if (mode === "replace" && typeof parsed.full === "string") {+ setCad2dSvg(parsed.full);+ addToHistory(parsed.full, 'svg');+ return;+ }+ if (mode === "patch" && Array.isArray(parsed.edits)) {+ const next = applyStringEdits(current, parsed.edits);+ setCad2dSvg(next);+ addToHistory(next, 'svg');+ return;+ }+ }+ return;+ }++ if (typeof parsed?.type === "string") {+ return;+ }+ } catch (e) {+ console.error("Failed to parse CAD JSON", e);+ }+ }} else if (type === 'ppt') {try {JSON.parse(code);@@ -304,7 +613,8 @@ function App() {</ResizablePanel></>)}- </ResizablePanelGroup>+ </ResizablePanelGroup>+ </ErrorBoundary></div></div>);diff --git a/src/components/ChatInput.tsx b/src/components/ChatInput.tsxindex 85f475c..0f8dfd7 100644--- a/src/components/ChatInput.tsx+++ b/src/components/ChatInput.tsx@@ -1,11 +1,14 @@-import React, { useRef, useEffect, useState, useCallback } from 'react';-import { Send, FileText, ImageIcon, Paperclip, X, Settings2 } from 'lucide-react';+import React, { useRef, useEffect, useMemo, useState } 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 { toast } from 'sonner';++type RichInputSegment =+ | { type: "text"; text: string }+ | { type: "ppt"; slideId: string; label: string; tag: string };interface ChatInputProps {input: string;@@ -17,6 +20,15 @@ interface ChatInputProps {files?: File[]; // Controlled filesonOpenGlobalConstraints?: () => void; // New prop for global constraintsplaceholder?: string;+ topChips?: React.ReactNode;+ bottomChips?: React.ReactNode;+ focusKey?: string | number;+ richSegments?: RichInputSegment[];+ onRichSegmentsChange?: (segments: RichInputSegment[]) => void;+ insertPptToken?: { key: number; slideId: string; label: string; tag: string } | null;+ onInsertPptTokenHandled?: () => void;+ clearKey?: string | number;+ uploadMode?: "all" | "imagesOnly" | "none";}export function ChatInput({@@ -28,13 +40,27 @@ export function ChatInput({onFilesChange,files: controlledFiles,onOpenGlobalConstraints,- placeholder+ placeholder,+ topChips,+ bottomChips,+ focusKey,+ richSegments,+ onRichSegmentsChange,+ insertPptToken,+ onInsertPptTokenHandled,+ clearKey,+ uploadMode = "all"}: ChatInputProps) {const textareaRef = useRef<HTMLTextAreaElement>(null);+ const richRef = useRef<HTMLDivElement>(null);+ const richSavedRangeRef = useRef<Range | null>(null);const fileInputRef = useRef<HTMLInputElement>(null);const imageInputRef = useRef<HTMLInputElement>(null);+ const richAppliedRef = useRef<string>("");+ const [richHasFocus, setRichHasFocus] = useState(false);const { files, handleFileChange, setFiles, pdfData } = useFileProcessor();+ const isRich = !!(richSegments && onRichSegmentsChange);// Sync controlled files if provideduseEffect(() => {@@ -58,13 +84,191 @@ export function ChatInput({// Auto-resize textareauseEffect(() => {- if (textareaRef.current) {- textareaRef.current.style.height = 'auto';- textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 200)}px`;- }+ if (isRich) return;+ if (!textareaRef.current) return;+ textareaRef.current.style.height = 'auto';+ textareaRef.current.style.height = `${Math.min(textareaRef.current.scrollHeight, 200)}px`;}, [input]);+ useEffect(() => {+ if (focusKey === undefined) return;+ if (isRich) richRef.current?.focus();+ else textareaRef.current?.focus();+ }, [focusKey]);++ useEffect(() => {+ if (clearKey === undefined) return;+ if (!isRich) return;+ const root = richRef.current;+ if (!root) return;+ richSavedRangeRef.current = null;+ root.innerHTML = "";+ root.appendChild(document.createTextNode(""));+ richAppliedRef.current = "";+ onRichSegmentsChange?.([{ type: "text", text: "" }]);+ }, [clearKey, isRich]);++ const serializeSegments = (segments: RichInputSegment[]) => {+ return segments+ .map((s) => (s.type === "text" ? `t:${s.text}` : `p:${s.slideId}:${s.tag}`))+ .join("|");+ };++ const buildLabelSpan = (segment: Extract<RichInputSegment, { type: "ppt" }>) => {+ const el = document.createElement("span");+ el.setAttribute("data-token", "ppt");+ el.setAttribute("data-slide-id", segment.slideId);+ el.setAttribute("data-label", segment.label);+ el.setAttribute("data-tag", segment.tag);+ el.setAttribute("contenteditable", "false");+ el.className = "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";+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");+ svg.setAttribute("viewBox", "0 0 24 24");+ svg.setAttribute("fill", "none");+ svg.setAttribute("stroke", "currentColor");+ svg.setAttribute("stroke-width", "2");+ svg.setAttribute("stroke-linecap", "round");+ svg.setAttribute("stroke-linejoin", "round");+ svg.setAttribute("aria-hidden", "true");+ svg.setAttribute("class", "h-3.5 w-3.5 text-red-600 dark:text-red-200");+ const path1 = document.createElementNS("http://www.w3.org/2000/svg", "path");+ // Draw a "P" icon+ path1.setAttribute("d", "M19 7a5 5 0 0 0-5-5H7a1 1 0 0 0-1 1v18a1 1 0 0 0 1 1h1a1 1 0 0 0 1-1v-8h5a5 5 0 0 0 5-5z");+ // Actually a simpler P stroke might be better for 24x24+ // P shape: M8 20V4h6a4 4 0 0 1 0 8H8+ path1.setAttribute("d", "M8 20V4h6a4 4 0 0 1 0 8H8");++ svg.appendChild(path1);+ const text = document.createElement("span");+ text.textContent = segment.label;+ el.appendChild(svg);+ el.appendChild(text);+ return el;+ };++ const setRichContentFromSegments = (segments: RichInputSegment[]) => {+ const root = richRef.current;+ if (!root) return;+ root.innerHTML = "";+ for (const seg of segments) {+ if (seg.type === "text") {+ const parts = String(seg.text || "").split("\n");+ for (let i = 0; i < parts.length; i += 1) {+ if (parts[i]) root.appendChild(document.createTextNode(parts[i]));+ if (i < parts.length - 1) root.appendChild(document.createElement("br"));+ }+ continue;+ }+ root.appendChild(buildLabelSpan(seg));+ root.appendChild(document.createTextNode(" "));+ }+ if (!root.lastChild) root.appendChild(document.createTextNode(""));+ };++ const parseRichSegmentsFromDom = (): RichInputSegment[] => {+ const root = richRef.current;+ if (!root) return [{ type: "text", text: "" }];++ const out: RichInputSegment[] = [];+ const pushText = (t: string) => {+ if (!t) return;+ const last = out[out.length - 1];+ if (last?.type === "text") last.text += t;+ else out.push({ type: "text", text: t });+ };++ for (const node of Array.from(root.childNodes)) {+ if (node.nodeType === Node.TEXT_NODE) {+ pushText(node.textContent || "");+ continue;+ }+ if (node.nodeType !== Node.ELEMENT_NODE) continue;+ const el = node as HTMLElement;+ if (el.tagName === "BR") {+ pushText("\n");+ continue;+ }+ const token = el.getAttribute("data-token");+ if (token === "ppt") {+ const slideId = el.getAttribute("data-slide-id") || "";+ const label = el.getAttribute("data-label") || el.textContent || "";+ const tag = el.getAttribute("data-tag") || "";+ if (slideId && tag) out.push({ type: "ppt", slideId, label, tag });+ continue;+ }+ pushText(el.textContent || "");+ }++ if (out.length === 0) return [{ type: "text", text: "" }];+ return out;+ };++ const syncRichToParent = () => {+ if (!isRich) return;+ const next = parseRichSegmentsFromDom();+ const key = serializeSegments(next);+ if (key === richAppliedRef.current) return;+ richAppliedRef.current = key;+ onRichSegmentsChange?.(next);+ };++ useEffect(() => {+ if (!isRich) return;+ const segments = richSegments || [{ type: "text", text: "" }];+ const key = serializeSegments(segments);+ if (key === richAppliedRef.current) return;+ richAppliedRef.current = key;+ if (richHasFocus) return;+ setRichContentFromSegments(segments);+ }, [isRich, richSegments, richHasFocus]);++ const insertPptTokenAtCursor = (slideId: string, label: string, tag: string) => {+ const root = richRef.current;+ if (!root) return;+ root.focus();+ const sel = window.getSelection();+ let range: Range | null = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;+ if (!range || !root.contains(range.startContainer)) {+ range = richSavedRangeRef.current;+ }+ if (!range || !root.contains(range.startContainer)) {+ range = document.createRange();+ range.selectNodeContents(root);+ range.collapse(false);+ }+ const span = buildLabelSpan({ type: "ppt", slideId, label, tag });+ const space = document.createTextNode(" ");+ range.insertNode(space);+ range.insertNode(span);+ range.setStartAfter(space);+ range.collapse(true);+ if (sel) {+ sel.removeAllRanges();+ sel.addRange(range);+ }+ richSavedRangeRef.current = range;+ syncRichToParent();+ };++ useEffect(() => {+ if (!isRich) return;+ if (!insertPptToken) return;+ insertPptTokenAtCursor(insertPptToken.slideId, insertPptToken.label, insertPptToken.tag);+ onInsertPptTokenHandled?.();+ }, [isRich, insertPptToken?.key]);++ const richPlainText = useMemo(() => {+ const segs = richSegments || [];+ return segs+ .map((s) => (s.type === "text" ? s.text : s.label))+ .join("")+ .replace(/[ \t]+\n/g, "\n");+ }, [richSegments]);++ const showRichPlaceholder = isRich && !richPlainText.trim() && !richHasFocus;+const handlePaste = (e: React.ClipboardEvent) => {+ if (uploadMode === "none") return;const items = e.clipboardData.items;const pastedFiles: File[] = [];@@ -76,16 +280,20 @@ export function ChatInput({}if (pastedFiles.length > 0) {+ const filtered = uploadMode === "imagesOnly" ? pastedFiles.filter((f) => f.type.startsWith("image/")) : pastedFiles;+ if (filtered.length === 0) return;e.preventDefault();- handleFileChange([...files, ...pastedFiles]);+ handleFileChange([...files, ...filtered]);}};const handleDrop = (e: React.DragEvent) => {e.preventDefault();+ if (uploadMode === "none") return;const droppedFiles = Array.from(e.dataTransfer.files);- if (droppedFiles.length > 0) {- handleFileChange([...files, ...droppedFiles]);+ const filtered = uploadMode === "imagesOnly" ? droppedFiles.filter((f) => f.type.startsWith("image/")) : droppedFiles;+ if (filtered.length > 0) {+ handleFileChange([...files, ...filtered]);}};@@ -94,7 +302,9 @@ export function ChatInput({const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {if (e.target.files?.length) {- handleFileChange([...files, ...Array.from(e.target.files)]);+ const incoming = Array.from(e.target.files);+ const filtered = uploadMode === "imagesOnly" ? incoming.filter((f) => f.type.startsWith("image/")) : incoming;+ if (filtered.length > 0) handleFileChange([...files, ...filtered]);e.target.value = ''; // Reset}};@@ -109,21 +319,25 @@ export function ChatInput({onDragOver={(e) => e.preventDefault()}onDrop={handleDrop}>- <input- type="file"- multiple- accept="image/*"- className="hidden"- ref={imageInputRef}- onChange={onFileInputChange}- />- <input- type="file"- multiple- className="hidden"- ref={fileInputRef}- onChange={onFileInputChange}- />+ {uploadMode !== "none" && (+ <input+ type="file"+ multiple+ accept="image/*"+ className="hidden"+ ref={imageInputRef}+ onChange={onFileInputChange}+ />+ )}+ {uploadMode === "all" && (+ <input+ type="file"+ multiple+ className="hidden"+ ref={fileInputRef}+ onChange={onFileInputChange}+ />+ )}{files.length > 0 && (<div className="px-3 pt-3">@@ -135,72 +349,217 @@ export function ChatInput({</div>)}- <div className="flex items-end gap-2 px-2 pb-1 pt-1">- <div className="flex-1 min-w-0 px-2">+ {topChips && (+ <div className="px-3 pt-3">+ {topChips}+ </div>+ )}++ <div className="px-3 pt-2">+ {isRich ? (<div className="relative">- <textarea- ref={textareaRef}- value={input}- onChange={(e) => setInput(e.target.value)}- onKeyDown={handleKeyDown}- onPaste={handlePaste}- placeholder={placeholder || "输入…"}+ {showRichPlaceholder && (+ <div className="pointer-events-none absolute left-1 top-2 text-[15px] leading-6 text-muted-foreground/60">+ {placeholder || "输入…"}+ </div>+ )}+ <div+ ref={richRef}+ contentEditable+ suppressContentEditableWarning+ onKeyDown={(e) => {+ if (e.key === "Enter" && !e.shiftKey) {+ e.preventDefault();+ if (isLoading) onStop?.();+ else onSubmit();+ return;+ }+ if (e.key === "Backspace" || e.key === "Delete") {+ const root = richRef.current;+ if (!root) return;+ const sel = window.getSelection();+ if (!sel || sel.rangeCount === 0) return;+ const r = sel.getRangeAt(0);+ if (!root.contains(r.startContainer) || !r.collapsed) return;+ const container = r.startContainer;+ const offset = r.startOffset;++ const tryRemoveToken = (el: Element | null) => {+ if (!el) return false;+ const token = (el as HTMLElement).getAttribute("data-token");+ if (token !== "ppt") return false;+ el.remove();+ syncRichToParent();+ return true;+ };++ if (container.nodeType === Node.TEXT_NODE) {+ if (e.key === "Backspace" && offset === 0) {+ const prev = (container as Text).previousSibling;+ if (prev && prev.nodeType === Node.ELEMENT_NODE) {+ if (tryRemoveToken(prev as Element)) {+ e.preventDefault();+ return;+ }+ }+ }+ if (e.key === "Delete" && offset === (container as Text).data.length) {+ const next = (container as Text).nextSibling;+ if (next && next.nodeType === Node.ELEMENT_NODE) {+ if (tryRemoveToken(next as Element)) {+ e.preventDefault();+ return;+ }+ }+ }+ } else if (container.nodeType === Node.ELEMENT_NODE) {+ const el = container as Element;+ const child = el.childNodes[offset + (e.key === "Backspace" ? -1 : 0)];+ if (child && child.nodeType === Node.ELEMENT_NODE) {+ if (tryRemoveToken(child as Element)) {+ e.preventDefault();+ return;+ }+ }+ }+ }+ }}+ onPaste={handlePaste as any}+ onFocus={() => setRichHasFocus(true)}+ onBlur={() => {+ setRichHasFocus(false);+ const sel = window.getSelection();+ if (sel && sel.rangeCount > 0) {+ const r = sel.getRangeAt(0);+ if (richRef.current?.contains(r.startContainer)) {+ richSavedRangeRef.current = r;+ }+ }+ syncRichToParent();+ }}+ onInput={() => syncRichToParent()}+ onKeyUp={() => {+ const sel = window.getSelection();+ if (sel && sel.rangeCount > 0) {+ const r = sel.getRangeAt(0);+ if (richRef.current?.contains(r.startContainer)) {+ richSavedRangeRef.current = r;+ }+ }+ }}+ onMouseUp={() => {+ const sel = window.getSelection();+ if (sel && sel.rangeCount > 0) {+ const r = sel.getRangeAt(0);+ if (richRef.current?.contains(r.startContainer)) {+ richSavedRangeRef.current = r;+ }+ }+ }}className={cn(- "w-full resize-none bg-transparent border-none px-2 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[44px]"+ "w-full bg-transparent border-none px-1 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[48px] whitespace-pre-wrap break-words")}- rows={1}/></div>+ ) : (+ <textarea+ ref={textareaRef}+ value={input}+ onChange={(e) => setInput(e.target.value)}+ onKeyDown={handleKeyDown}+ onPaste={handlePaste}+ placeholder={placeholder || "输入…"}+ className={cn(+ "w-full resize-none bg-transparent border-none px-1 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[48px]"+ )}+ rows={1}+ />+ )}+ </div>++ {bottomChips && (+ <div className="px-3 pb-2">+ {bottomChips}</div>+ )}++ <div className="flex items-center justify-between gap-2 px-3 pb-3 pt-1 border-t border-border/40">+ <div className="flex items-center gap-1">+ {onOpenGlobalConstraints && (+ <ButtonWithTooltip+ tooltipContent="规则"+ variant="ghost"+ size="icon"+ onClick={onOpenGlobalConstraints}+ className="h-9 w-9 text-muted-foreground hover:text-primary rounded-lg"+ >+ <Settings2 className="w-4 h-4" />+ </ButtonWithTooltip>+ )}- <div className="flex items-center gap-1 pr-1">- {onOpenGlobalConstraints && (<ButtonWithTooltip- tooltipContent="规则"+ tooltipContent="上传图片"variant="ghost"size="icon"- onClick={onOpenGlobalConstraints}- className="h-9 w-9 text-muted-foreground hover:text-primary rounded-lg mr-1"+ onClick={handleImageUpload}+ className="h-9 w-9 text-muted-foreground hover:text-foreground rounded-lg">- <Settings2 className="w-4 h-4" />+ <ImageIcon className="w-5 h-5" /></ButtonWithTooltip>- )}-- <ButtonWithTooltip- tooltipContent="上传图片"- variant="ghost"- size="icon"- onClick={handleImageUpload}- className="h-9 w-9 text-muted-foreground hover:text-foreground rounded-lg"- >- <ImageIcon className="w-5 h-5" />- </ButtonWithTooltip>-- <ButtonWithTooltip- tooltipContent="上传文件"- variant="ghost"- size="icon"- onClick={handleFileUpload}- className="h-9 w-9 text-muted-foreground hover:text-foreground rounded-lg"- >- <FileText className="w-5 h-5" />- </ButtonWithTooltip>-- <Button- onClick={isLoading ? onStop : onSubmit}- disabled={isLoading ? !onStop : (!input.trim() && files.length === 0)}- size="icon"- className={cn(- "h-9 w-9 rounded-xl transition-all duration-200 ml-1",- (input.trim() || files.length > 0)- ? "bg-primary text-primary-foreground shadow-md hover:scale-105 hover:bg-primary/90"- : "bg-muted text-muted-foreground"++ {uploadMode === "all" && (+ <ButtonWithTooltip+ tooltipContent="上传文件"+ variant="ghost"+ size="icon"+ onClick={handleFileUpload}+ className="h-9 w-9 text-muted-foreground hover:text-foreground rounded-lg"+ >+ <FileText className="w-5 h-5" />+ </ButtonWithTooltip>)}- >- {isLoading ? <X className="w-4 h-4" /> : <Send className="w-4 h-4" />}- </Button>+ </div>++ {(() => {+ const hasText = isRich ? richPlainText.trim().length > 0 : input.trim().length > 0;+ const hasFiles = files.length > 0;+ if (isLoading) {+ return (+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={(e) => {+ e.preventDefault();+ onStop?.();+ }}+ disabled={!onStop}+ className="h-9 px-4 rounded-xl font-medium shadow-sm"+ aria-label="停止生成"+ >+ <Square className="h-4 w-4 fill-current mr-1.5" />+ 停止+ </Button>+ );+ }+ return (+ <Button+ type="button"+ onClick={onSubmit}+ disabled={!hasText && !hasFiles}+ size="sm"+ className={cn(+ "h-9 px-4 rounded-xl font-medium shadow-sm",+ (!hasText && !hasFiles) ? "opacity-60" : ""+ )}+ aria-label="发送"+ >+ <Send className="h-4 w-4 mr-1.5" />+ 发送+ </Button>+ );+ })()}</div></div>- </div>);}diff --git a/src/components/ChatMessageDisplay.tsx b/src/components/ChatMessageDisplay.tsxindex 0e77ebe..827138e 100644--- a/src/components/ChatMessageDisplay.tsx+++ b/src/components/ChatMessageDisplay.tsx@@ -15,7 +15,24 @@ import {ThumbsDown,ThumbsUp,X,+ Presentation, // Import P icon if available, otherwise we use SVG} from "lucide-react";++// Custom P icon component+const PIcon = ({ className }: { className?: string }) => (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ >+ <path d="M8 20V4h6a4 4 0 0 1 0 8H8" />+ </svg>+);import ReactMarkdown from "react-markdown";import remarkGfm from 'remark-gfm';import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/components/ai-elements/reasoning";@@ -98,6 +115,73 @@ function splitTextIntoFileSections(text: string): TextSection[] {return sections;}+type PptSlideTag = { n: number; title?: string };++function extractPptSlideTags(text: string): { tags: PptSlideTag[]; rest: string } {+ const lines = String(text || "").split(/\r?\n/);+ const tags: PptSlideTag[] = [];+ const restLines: string[] = [];+ for (const line of lines) {+ const m = line.match(/^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/);+ if (m) {+ const n = Number(m[1]);+ const title = String(m[2] || "").trim();+ if (!Number.isNaN(n)) tags.push({ n, title: title || undefined });+ continue;+ }+ restLines.push(line);+ }+ const rest = restLines.join("\n").replace(/^\s+|\s+$/g, "");+ return { tags, rest };+}++type ImageTag = { name?: string; url: string };++function extractImageTags(text: string): { images: ImageTag[]; rest: string } {+ const lines = String(text || "").split(/\r?\n/);+ const images: ImageTag[] = [];+ const restLines: string[] = [];+ for (const line of lines) {+ const m = line.match(/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/);+ if (m) {+ const name = String(m[1] || "").trim();+ const url = String(m[2] || "").trim();+ if (url.startsWith("data:image") || url.startsWith("blob:") || url.startsWith("http://") || url.startsWith("https://")) {+ images.push({ name: name || undefined, url });+ continue;+ }+ }+ restLines.push(line);+ }+ const rest = restLines.join("\n").replace(/^\s+|\s+$/g, "");+ return { images, rest };+}++type InlinePptPart =+ | { type: "text"; text: string }+ | { type: "ppt"; n: number; title?: string };++function splitInlinePptTags(text: string): InlinePptPart[] {+ const raw = String(text || "");+ const out: InlinePptPart[] = [];+ const re = /\[\[PPT_SLIDE\|(\d+)\|([\s\S]*?)\]\]/g;+ let lastIndex = 0;+ let m: RegExpExecArray | null;+ while ((m = re.exec(raw))) {+ const before = raw.slice(lastIndex, m.index);+ if (before) out.push({ type: "text", text: before });+ const n = Number(m[1]);+ const title = String(m[2] || "").trim();+ if (!Number.isNaN(n)) out.push({ type: "ppt", n, title: title || undefined });+ else out.push({ type: "text", text: m[0] });+ lastIndex = m.index + m[0].length;+ }+ const rest = raw.slice(lastIndex);+ if (rest) out.push({ type: "text", text: rest });+ if (out.length === 0) out.push({ type: "text", text: raw });+ return out;+}+const getMessageTextContent = (message: UIMessage): string => {if (message.parts && message.parts.length > 0) {return message.parts@@ -110,8 +194,14 @@ const getMessageTextContent = (message: UIMessage): string => {const getUserOriginalText = (message: UIMessage): string => {const fullText = getMessageTextContent(message);+ const withoutTags = fullText+ .split(/\r?\n/)+ .filter((line) => !/^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/.test(line))+ .filter((line) => !/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/.test(line))+ .join("\n")+ .trim();const filePattern = /\n\n\[(PDF|File):\s*[^\]]+\]\n[\s\S]*$/;- return fullText.replace(filePattern, "").trim();+ return withoutTags.replace(filePattern, "").trim();};export function ChatMessageDisplay({@@ -130,6 +220,7 @@ export function ChatMessageDisplay({const [editText, setEditText] = useState<string>("");const [expandedPdfSections, setExpandedPdfSections] = useState<Record<string, boolean>>({});const [isAtBottom, setIsAtBottom] = useState(true);+ const scrollRafRef = useRef<number | null>(null);const copyMessageToClipboard = async (messageId: string, text: string) => {try {@@ -168,9 +259,28 @@ export function ChatMessageDisplay({return () => viewport.removeEventListener("scroll", onScroll as any);}, [getViewport]);+ useEffect(() => {+ return () => {+ if (scrollRafRef.current === null) return;+ if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(scrollRafRef.current);+ else if (typeof window !== "undefined") window.clearTimeout(scrollRafRef.current);+ scrollRafRef.current = null;+ };+ }, []);+useEffect(() => {if (!isAtBottom) return;- scrollToBottom(status === "streaming" ? "auto" : "smooth");+ if (scrollRafRef.current !== null) return;+ const behavior: ScrollBehavior = status === "streaming" ? "auto" : "smooth";+ const schedule = (cb: () => void) => {+ if (typeof requestAnimationFrame === "function") return requestAnimationFrame(cb);+ if (typeof window !== "undefined") return window.setTimeout(cb, 16);+ return 0;+ };+ scrollRafRef.current = schedule(() => {+ scrollRafRef.current = null;+ scrollToBottom(behavior);+ });}, [messages, status, isAtBottom, scrollToBottom]);useEffect(() => {@@ -200,7 +310,7 @@ export function ChatMessageDisplay({return (<div ref={scrollRootRef} className="h-full w-full relative"><ScrollArea className="h-full w-full scrollbar-thin">- <div className="py-4 px-4 space-y-6">+ <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;@@ -233,7 +343,7 @@ export function ChatMessageDisplay({<div className={cn("relative px-4 py-3 text-sm leading-relaxed shadow-sm break-words overflow-hidden",message.role === "user"- ? "bg-primary text-primary-foreground rounded-2xl rounded-tr-sm"+ ? "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")}>@@ -259,8 +369,10 @@ export function ChatMessageDisplay({{/* Text Content */}{(() => {- const text = getMessageTextContent(message);- if (!text) return null;+ const raw = getMessageTextContent(message);+ const { images, rest: withoutImages } = extractImageTags(raw);+ const { tags: pptTags, rest: text } = extractPptSlideTags(withoutImages);+ if (!text && images.length === 0) return null;// Edit Modeif (isEditing && message.role === "user") {@@ -278,7 +390,7 @@ export function ChatMessageDisplay({onClick={() => setEditingMessageId(null)}className="px-3 py-1 text-xs rounded bg-muted hover:bg-muted/80 text-foreground">- Cancel+ 取消</button><buttononClick={() => {@@ -289,7 +401,7 @@ export function ChatMessageDisplay({}}className="px-3 py-1 text-xs rounded bg-primary hover:bg-primary/90 text-primary-foreground">- Save+ 重新发送</button></div></div>@@ -299,8 +411,46 @@ export function ChatMessageDisplay({// Regular Displayconst sections = splitTextIntoFileSections(text);return (- <div className={cn("space-y-3", message.role === "user" ? "text-primary-foreground dark:text-white" : "")}>+ <div className="space-y-3">+ {images.length > 0 && (+ <div className="space-y-2">+ {images.map((img, i) => (+ <div+ key={`${message.id}-img-${i}`}+ className={cn(+ "overflow-hidden rounded-lg border border-border/60 bg-black/5 dark:bg-white/5",+ "max-w-[420px] mx-auto"+ )}+ >+ <img+ src={img.url}+ alt={img.name || "image"}+ className="w-full max-h-[240px] object-contain bg-black/5"+ />+ </div>+ ))}+ </div>+ )}+ {pptTags.length > 0 && (+ <div className="flex flex-wrap gap-1.5">+ {pptTags.map((t, i) => (+ <span+ key={`${message.id}-ppttag-${i}-${t.n}`}+ className={cn(+ "inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] leading-4",+ message.role === "user"+ ? "border-red-200 bg-red-50 text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200"+ : "border-border bg-muted/40 text-foreground"+ )}+ >+ <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} 页`}+ </span>+ ))}+ </div>+ )}{sections.map((section, idx) => {+ if (section.type === "text" && !String(section.content || "").trim()) return null;if (section.type === 'file') {const key = `${message.id}-file-${idx}`;const isExpanded = expandedPdfSections[key] || false;@@ -332,14 +482,75 @@ export function ChatMessageDisplay({// Render Markdown// We need to handle code blocks specially to use our CodeBlock component+ let codeBlockOrdinal = 0;+ if (message.role === "user") {+ const parts = splitInlinePptTags(section.content);+ return (+ <div+ key={idx}+ className="text-[15px] leading-6 whitespace-pre-wrap break-words text-foreground"+ >+ {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} 页`;+ return (+ <span+ key={`${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}`}+ >+ <PIcon className="h-3.5 w-3.5 text-red-600 dark:text-red-200" />+ {label}+ </span>+ );+ })}+ </div>+ );+ }return (<div key={idx} className={cn("prose prose-sm max-w-none break-words",- message.role === "user" ? "prose-invert" : "dark:prose-invert"+ "dark:prose-invert")}><ReactMarkdownremarkPlugins={[remarkGfm]}+ urlTransform={(url) => {+ const u = String(url || "");+ if (!u) return "";+ if (u.startsWith("http://") || u.startsWith("https://")) return u;+ if (u.startsWith("data:image")) return u;+ if (u.startsWith("blob:")) return u;+ if (u.startsWith("/files/")) return u;+ if (u.startsWith("#")) return u;+ return "";+ }}components={{+ table({ children }: any) {+ return <table className="w-full table-fixed">{children}</table>;+ },+ th({ children, ...props }: any) {+ return (+ <th+ {...props}+ className={cn("whitespace-normal break-words", props?.className)}+ >+ {children}+ </th>+ );+ },+ td({ children, ...props }: any) {+ return (+ <td+ {...props}+ className={cn("whitespace-normal break-words", props?.className)}+ >+ {children}+ </td>+ );+ },+ pre({ children }: any) {+ return <>{children}</>;+ },code({node, inline, className, children, ...props}: any) {const match = /language-(\w+)/.exec(className || '')// Check if this is the last message and currently streaming@@ -347,18 +558,26 @@ export function ChatMessageDisplay({// But technically ReactMarkdown renders progressively.// We can check if status is streaming and this is the assistant role.const isStreaming = status === "streaming" && isLastAssistantMessage;-- return !inline && match ? (- <CodeBlock- code={String(children).replace(/\n$/, '')}- language={match[1] as any}- isStreaming={isStreaming}- />- ) : (+ const language = match?.[1] || "text";++ if (!inline) {+ const ordinal = codeBlockOrdinal++;+ return (+ <CodeBlock+ key={`codeblock-${message.id}-${idx}-${language}-${ordinal}`}+ blockId={`${message.id}:${idx}:${language}:${ordinal}`}+ code={String(children).replace(/\n$/, '')}+ language={language as any}+ isStreaming={isStreaming}+ />+ );+ }++ return (<code className={className} {...props}>{children}</code>- )+ );}}}>@@ -412,7 +631,7 @@ export function ChatMessageDisplay({>{copiedMessageId === message.id ? <Check className="h-3 w-3 text-green-500" /> : <Copy className="h-3 w-3" />}</button>- {onRegenerate && isLastAssistantMessage && (+ {onRegenerate && (<buttononClick={() => onRegenerate(messageIndex)}className="p-1 rounded hover:bg-muted text-muted-foreground"diff --git a/src/components/ChatPanel.tsx b/src/components/ChatPanel.tsxindex 359c2a7..2b62995 100644--- a/src/components/ChatPanel.tsx+++ b/src/components/ChatPanel.tsx@@ -1,8 +1,8 @@import React, { useState, useRef, useEffect } from 'react';-import { Bot, Trash2, History, Settings2, SidebarClose, SidebarOpen } from 'lucide-react';+import { Bot, Trash2, History, Settings2, SidebarClose, SidebarOpen, Plus } from 'lucide-react';import { cn } from '@/lib/utils';-import { streamChatMessage, generateImage, ChatMessage, getAIConfig } from '@/lib/ai-client';-import { DRAWIO_SYSTEM_PROMPT } from '@/lib/system-prompt';+import { streamChatMessage, ChatMessage, getAIConfig } from '@/lib/ai-client';+import { DRAWIO_SYSTEM_PROMPT } from '@/lib/system-prompts';import { Button } from '@/components/ui/button';import { ChatInput } from '@/components/ChatInput';import { ChatMessageDisplay, UIMessage } from '@/components/ChatMessageDisplay';@@ -10,6 +10,7 @@ import { GlobalConstraintsDialog, STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/compoimport { 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';interface Attachment {id: string;@@ -22,6 +23,9 @@ interface ChatPanelProps {className?: string;attachments?: Attachment[];onRemoveAttachment?: (id: string) => void;+ 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;systemPrompt?: string;initialMessages?: ChatMessage[];@@ -38,6 +42,12 @@ interface ChatPanelProps {// History propshistory?: HistoryItem[];onRestore?: (item: HistoryItem) => void;+ onClearVersionHistory?: () => void;+ onClearAttachments?: () => void;+ cadContext?: {+ plan?: any;+ svg2d?: string;+ };}const STORAGE_KEY_PREFIX = 'chat_history_v2_';@@ -54,6 +64,9 @@ export function ChatPanel({className,attachments = [],onRemoveAttachment,+ pptDraftSlides = [],+ onRemovePptDraftSlide,+ onClearPptDraftSlides,onCodeAction,systemPrompt = DRAWIO_SYSTEM_PROMPT,initialMessages = [],@@ -68,7 +81,10 @@ export function ChatPanel({title = "AI 助手",inputPlaceholder,history = [],- onRestore+ onRestore,+ onClearVersionHistory,+ onClearAttachments,+ cadContext}: ChatPanelProps) {// Persistence keyconst storageKey = `${STORAGE_KEY_PREFIX}${workspaceId}`;@@ -90,6 +106,9 @@ export function ChatPanel({});const [input, setInput] = useState('');+ const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string }>>([+ { type: "text", text: "" }+ ]);const [isLoading, setIsLoading] = useState(false);const [showGlobalConstraints, setShowGlobalConstraints] = useState(false);const [showHistory, setShowHistory] = useState(false);@@ -97,6 +116,186 @@ export function ChatPanel({const [files, setFiles] = useState<File[]>([]);const abortControllerRef = useRef<AbortController | null>(null);+ const [pptInputFocusTick, setPptInputFocusTick] = useState(0);+ const prevPptDraftCountRef = useRef(0);+ const prevPptDraftIdsRef = useRef<Set<string>>(new Set());+ const [pptInsertToken, setPptInsertToken] = useState<{ key: number; slideId: string; label: string; tag: string } | null>(null);+ const pptInsertQueueRef = useRef<Array<{ slideId: string; title: string; label: string }>>([]);+ const pptInsertBusyRef = useRef(false);+ const [pptClearTick, setPptClearTick] = useState(0);+ const lastUploadedImagesRef = useRef<string[]>([]);++ 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} 页`;+ return title || slideId;+ };++ const getPptTag = (slideId: string, title: string) => {+ const m = String(slideId || "").match(/(\d+)/);+ const n = m ? Number(m[1]) : NaN;+ if (Number.isNaN(n)) return "";+ const safeTitle = String(title || "").split("|").join("/").split("]]").join("】");+ return `[[PPT_SLIDE|${n}|${safeTitle}]]`;+ };++ const pumpPptInsertQueue = () => {+ if (pptInsertBusyRef.current) return;+ const next = pptInsertQueueRef.current.shift();+ if (!next) return;+ pptInsertBusyRef.current = true;+ const tag = getPptTag(next.slideId, next.title);+ setPptInsertToken({ key: Date.now() + Math.random(), slideId: next.slideId, label: next.label, tag });+ };++ const enqueuePptToken = (slideId: string, title: string) => {+ const label = getPptLabel(slideId, title);+ pptInsertQueueRef.current.push({ slideId, title, label });+ pumpPptInsertQueue();+ };++ useEffect(() => {+ if (workspaceId !== "ppt") return;+ const prev = prevPptDraftCountRef.current;+ const next = pptDraftSlides.length;+ prevPptDraftCountRef.current = next;+ if (next > prev) {+ setPptInputFocusTick((x) => x + 1);+ }+ }, [workspaceId, pptDraftSlides.length]);++ useEffect(() => {+ if (workspaceId !== "ppt") return;+ const prevIds = prevPptDraftIdsRef.current;+ const nextIds = new Set(pptDraftSlides.map((s) => s.id));+ const added = pptDraftSlides.filter((s) => !prevIds.has(s.id));+ prevPptDraftIdsRef.current = nextIds;+ if (added.length === 0) return;+ for (const s of added) enqueuePptToken(s.slideId, s.title);+ }, [workspaceId, pptDraftSlides, setInput]);++ const parseMarkdownBomTable = (text: string) => {+ const normalized = String(text || "").replace(/[|]/g, "|");+ const lines = normalized.split(/\r?\n/);+ for (let i = 0; i < lines.length - 2; i += 1) {+ const header = lines[i];+ const sep = lines[i + 1];+ if (!header.includes("|")) continue;+ if (!/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?\s*$/.test(sep)) continue;++ const parseRow = (line: string) => {+ const trimmed = line.trim();+ const body = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed;+ const body2 = body.endsWith("|") ? body.slice(0, -1) : body;+ return body2.split("|").map((c) => c.trim());+ };++ const columns = parseRow(header).filter((c) => c);+ if (columns.length === 0) continue;++ const rows: any[] = [];+ for (let j = i + 2; j < lines.length; j += 1) {+ const rowLine = lines[j];+ if (!rowLine.includes("|")) break;+ const row = parseRow(rowLine);+ if (row.every((c) => !String(c || "").trim())) break;+ const fixed = row.slice(0, columns.length);+ while (fixed.length < columns.length) fixed.push("");+ rows.push(fixed);+ }++ if (rows.length === 0) continue;+ return { type: "cad_bom", columns, rows };+ }+ return null;+ };++ const sanitizeAssistantContentForDisplay = (content: string) => {+ if (workspaceId !== "cad") return content;+ if (!content) return content;+ let next = content.replace(/```(?:python|py|python3)\s*[\s\S]*?```/g, "(已在后台推导完成)");+ next = next+ .split("\n")+ .filter((line) => !/freecad/i.test(line))+ .join("\n");+ next = next.replace(/(?:^|\n)1\.\s*FreeCAD[\s\S]*?(?=\n\d+\.\s|$)/gi, "\n");+ return next.replace(/```json\s*([\s\S]*?)```/g, (full, inner) => {+ const text = String(inner || "").trim();+ if (!text) return full;+ if (text.includes('"type"') && text.includes('"cad_images"')) {+ return "(已提交装修图生成任务)";+ }+ if (text.includes('"type"') && text.includes('"cad_plan"')) {+ try {+ const parsed = JSON.parse(text);+ if (parsed?.type !== "cad_plan") return full;+ const plan = parsed?.plan || {};+ const summary = typeof plan?.summary === "string" ? plan.summary : "";+ const style = typeof plan?.style === "string" ? plan.style : "";+ const assumptions = Array.isArray(plan?.assumptions) ? plan.assumptions.map((x: any) => String(x)).filter(Boolean) : [];+ const constraints = Array.isArray(plan?.constraints) ? plan.constraints.map((x: any) => String(x)).filter(Boolean) : [];+ 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") : "(已生成方案)";+ } catch {+ return "(已生成方案)";+ }+ }+ return full;+ });+ };++ const scheduleFrame = (cb: () => void) => {+ if (typeof requestAnimationFrame === "function") return requestAnimationFrame(cb);+ if (typeof window !== "undefined") return window.setTimeout(cb, 16);+ return 0;+ };++ const cancelFrame = (id: number) => {+ if (!id) return;+ if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(id);+ else if (typeof window !== "undefined") window.clearTimeout(id);+ };++ const updateLastAssistant = (content: string) => {+ const display = sanitizeAssistantContentForDisplay(content);+ setMessages(prev => {+ const last = prev[prev.length - 1];+ if (last?.role === 'assistant') {+ return [...prev.slice(0, -1), { role: 'assistant', content: display }];+ }+ return [...prev, { role: 'assistant', content: display }];+ });+ };++ const createThrottledAssistantUpdater = () => {+ let latest = '';+ let frameId: number | null = null;+ return {+ push: (chunk: string) => {+ latest = chunk;+ if (frameId !== null) return;+ frameId = scheduleFrame(() => {+ frameId = null;+ updateLastAssistant(latest);+ });+ },+ flush: () => {+ if (frameId !== null) {+ cancelFrame(frameId);+ frameId = null;+ }+ updateLastAssistant(latest);+ }+ };+ };// Persist messagesuseEffect(() => {@@ -112,16 +311,77 @@ export function ChatPanel({setShowResetWarning(false);};- const handleSend = async () => {- if ((!input.trim() && files.length === 0 && attachments.length === 0) || isLoading) return;+ const startNewChat = () => {+ abortControllerRef.current?.abort();+ abortControllerRef.current = null;+ setIsLoading(false);+ setInput('');+ setPptInputSegments([{ type: "text", text: "" }]);+ setFiles([]);+ onClearAttachments?.();+ const newMsgs: ChatMessage[] = [+ { role: 'assistant', content: '你好!新对话已开始。请告诉我你的需求。' }+ ];+ setMessages(newMsgs);+ try {+ localStorage.removeItem(storageKey);+ } catch {+ }+ };- let fullContent = input;+ const handleSend = async () => {+ const isPpt = workspaceId === "ppt";+ const rawInput = isPpt+ ? pptInputSegments+ .map((s) => (s.type === "text" ? s.text : s.tag))+ .join("")+ : input;+ if ((!rawInput.trim() && files.length === 0 && attachments.length === 0 && pptDraftSlides.length === 0) || isLoading) return;++ const normalizedInput = rawInput.trim();+ const referencedPptSlideIds = isPpt+ ? new Set(+ pptInputSegments+ .filter((s): s is { type: "ppt"; slideId: string; label: string; tag: string } => s.type === "ppt")+ .map((s) => s.slideId)+ )+ : new Set<string>();+ const pptDraftSlidesSnapshotAll = isPpt ? pptDraftSlides.slice(0, 12) : [];+ const pptDraftSlidesSnapshot =+ isPpt && referencedPptSlideIds.size > 0+ ? pptDraftSlidesSnapshotAll.filter((s) => referencedPptSlideIds.has(s.slideId))+ : [];// Process files for promptconst fileTexts: string[] = [];+ const currentUploadedImages: string[] = [];+ const currentUploadedImageItems: Array<{ name: string; url: string }> = [];++ // Helper to read file as Data URL+ const fileToDataUrl = (file: File): Promise<string> => {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.onerror = reject;+ reader.readAsDataURL(file);+ });+ };+for (const file of files) {if (file.type.startsWith('image/')) {- fileTexts.push(`[Image: ${file.name}]`);+ try {+ const dataUrl = await fileToDataUrl(file);+ // We embed the image directly in the prompt using Markdown syntax.+ // This allows the Agent (if it's a VLM) to see it, or at least we provide the Data URL string+ // which the Agent can echo back in the JSON for the frontend to use.+ fileTexts.push(``);+ fileTexts.push(`[Image Attachment: ${file.name}]`);+ currentUploadedImages.push(dataUrl);+ currentUploadedImageItems.push({ name: file.name, url: dataUrl });+ } catch (e) {+ console.error("Failed to read image", file.name, e);+ fileTexts.push(`[Image: ${file.name}] (Failed to read)`);+ }} else {// Text/PDFconst { extractPdfText, extractTextFileContent, isPdfFile } = await import('@/lib/pdf-utils');@@ -151,90 +411,134 @@ export function ChatPanel({.join("\n\n"): "";- const parts = [fullContent, fileTexts.length > 0 ? fileTexts.join("\n\n") : "", contextAttachmentsText].filter(Boolean);- fullContent = parts.join("\n\n");+ const pptDraftContextText =+ workspaceId === "ppt" && pptDraftSlidesSnapshot.length > 0+ ? pptDraftSlidesSnapshot+ .map((s, idx) => {+ const header = `[Context ${idx + 1}: ${s.slideId}.json | json]`;+ const body = String(s.json || "").slice(0, 12000);+ return `${header}\n\`\`\`json\n${body}\n\`\`\``;+ })+ .join("\n\n")+ : "";- const userMessage: ChatMessage = { role: 'user', content: fullContent };-- const newMessages = [...messages, userMessage];- setMessages(newMessages);- setInput('');+ const promptParts = [+ rawInput,+ fileTexts.length > 0 ? fileTexts.join("\n\n") : "",+ pptDraftContextText,+ contextAttachmentsText+ ].filter(Boolean);+ const promptContent = promptParts.join("\n\n");+ lastUploadedImagesRef.current = currentUploadedImages;++ const safeTagText = (text: string) =>+ String(text || "").split("|").join("/").split("]]").join("】").replace(/\r?\n/g, " ");+ const imageTags = currentUploadedImageItems+ .map((it) => `[[IMAGE|${safeTagText(it.name)}|${it.url}]]`)+ .join("\n");+ const nonImageFiles = files.filter((f) => !f.type.startsWith("image/"));+ const displayParts = [+ imageTags,+ rawInput,+ nonImageFiles.length > 0 ? `(已附加文件:${nonImageFiles.map((f) => f.name).join(",")})` : "",+ ].filter(Boolean);+ const displayContent = displayParts.join("\n\n");++ const userMessageForDisplay: ChatMessage = { role: 'user', content: displayContent };+ const displayMessages = [...messages, userMessageForDisplay];+ setMessages(displayMessages);+ if (isPpt) setPptInputSegments([{ type: "text", text: "" }]);+ else setInput('');+ if (isPpt) setPptClearTick((x) => x + 1);setFiles([]);-- setIsLoading(true);- abortControllerRef.current?.abort();- const controller = new AbortController();- abortControllerRef.current = controller;+ if (workspaceId === "ppt") onClearPptDraftSlides?.();++ if (workspaceId === "cad" && mode === "text" && /确认\s*2d|满意|生成\s*装修|生成\s*物料|cad_ready_for_export/i.test(normalizedInput)) {+ const svg2d = cadContext?.svg2d || "";+ const planJson = cadContext?.plan ? JSON.stringify(cadContext.plan) : "";++ let bomEmitted = false;++ const emitCadJson = (text: string) => {+ const match = text.match(/```json\s*([\s\S]*?)```/);+ const jsonText = match ? match[1].trim() : text.trim();+ if (!jsonText.startsWith("{")) return;+ try {+ const parsed = JSON.parse(jsonText);+ if (parsed?.type === "cad_bom") bomEmitted = true;+ } catch {+ }+ onCodeAction?.(jsonText, 'cad');+ };- try {- if (mode === 'ppt_image') {- const parseSlideFromAttachments = () => {- const jsonAttachments = attachments.filter((a) => a.type === 'json');- for (let i = jsonAttachments.length - 1; i >= 0; i -= 1) {- const a = jsonAttachments[i];- try {- const parsed = JSON.parse(a.content);- if (parsed && typeof parsed === 'object' && typeof parsed.id === 'string') {- return {- id: String(parsed.id),- title: typeof parsed.title === 'string' ? parsed.title : '',- content: Array.isArray(parsed.content) ? parsed.content.map((x: any) => String(x)) : [],- description: typeof parsed.description === 'string' ? parsed.description : '',- imageUrl: typeof parsed.imageUrl === 'string' ? parsed.imageUrl : ''- };- }- } catch {- }- }- return null;- };+ const config = getAIConfig();+ 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 bomMessages: ChatMessage[] = buildCadBomMessages({ systemContent, planJson, svg2d });+ const imagesMessages: ChatMessage[] = buildCadImagesMessages({ systemContent, planJson, svg2d });- const slide = parseSlideFromAttachments();- if (!slide?.imageUrl) {- } else {- const prompt = `Edit a presentation slide image.-${slide ? `Slide id: ${slide.id}\nSlide title: ${slide.title}\nBullets: ${(slide.content || []).join(" | ")}\nExisting description: ${slide.description || ""}\n` : ""}User instruction:-${fullContent}--Rules:-- Keep the slide professional and readable.-- Do not add watermark.-- Avoid long paragraphs of text in the image.-`;-- setMessages(prev => [...prev, { role: 'assistant', content: '' }]);- const imageUrl = await generateImage(- { prompt, referenceImageUrl: slide?.imageUrl || undefined },- controller.signal- );-- if (imageUrl) {- setMessages(prev => {- const last = prev[prev.length - 1];- if (last?.role === 'assistant') {- return [...prev.slice(0, -1), { role: 'assistant', content: `` }];- }- return [...prev, { role: 'assistant', content: `` }];- });+ setIsLoading(true);+ abortControllerRef.current?.abort();+ const controller = new AbortController();+ abortControllerRef.current = controller;++ setMessages(prev => [...prev, { role: 'assistant', content: '' }]);- if (slide?.id) {- const payload = JSON.stringify({ slides: [{ id: slide.id, imageUrl, instruction: fullContent }] });- onCodeAction?.(payload, 'ppt');+ const updater = createThrottledAssistantUpdater();+ let bomFull = '';+ let imagesFull = '';++ const bomTask = (async () => {+ await streamChatMessage(bomMessages, (chunk) => {+ bomFull = chunk;+ updater.push(chunk);+ }, chatModel, controller.signal);+ updater.flush();+ if (bomFull) {+ emitCadJson(bomFull);+ if (!bomEmitted) {+ const fallback = parseMarkdownBomTable(bomFull);+ if (fallback) {+ bomEmitted = true;+ onCodeAction?.(JSON.stringify(fallback), "cad");+ }}- } else {+ }+ })();++ const imagesTask = (async () => {+ await streamChatMessage(imagesMessages, (chunk) => {+ imagesFull = chunk;+ }, chatModel, controller.signal);+ if (imagesFull) emitCadJson(imagesFull);+ })();++ try {+ await Promise.allSettled([bomTask, imagesTask]);+ if (controller.signal.aborted) {setMessages(prev => {const last = prev[prev.length - 1];- if (last?.role === 'assistant') {- return [...prev.slice(0, -1), { role: 'assistant', content: "未能生成图片,请重试。" }];- }- return [...prev, { role: 'assistant', content: "未能生成图片,请重试。" }];+ if (last?.role !== 'assistant') return prev;+ const next = last.content ? `${last.content}\n\n(已中断)` : "(已中断)";+ return [...prev.slice(0, -1), { role: 'assistant', content: next }];});}-- return;- }+ } catch {+ } finally {+ setIsLoading(false);+ abortControllerRef.current = null;}+ return;+ }++ setIsLoading(true);+ abortControllerRef.current?.abort();+ const controller = new AbortController();+ abortControllerRef.current = controller;+ try {// Get Global Configconst config = getAIConfig();// Load global constraints from storage (scoped by workspaceId)@@ -246,22 +550,19 @@ Rules:const apiMessages: ChatMessage[] = [{ role: 'system', content: systemContent },- ...newMessages+ ...messages,+ { role: 'user', content: promptContent }];setMessages(prev => [...prev, { role: 'assistant', content: '' }]);let fullResponse = '';+ const updater = createThrottledAssistantUpdater();await streamChatMessage(apiMessages, (chunk) => {fullResponse = chunk;- setMessages(prev => {- const last = prev[prev.length - 1];- if (last.role === 'assistant') {- return [...prev.slice(0, -1), { role: 'assistant', content: chunk }];- }- return prev;- });+ updater.push(chunk);}, chatModel, controller.signal);+ updater.flush();if (fullResponse) {// Match XML@@ -271,10 +572,17 @@ Rules:onCodeAction?.(xml, 'flow');}- // Match Python+ // Match Python (not used by CAD; CAD uses background agents)const pyMatch = fullResponse.match(/```python\n([\s\S]*?)\n```/);- if (pyMatch && pyMatch[1]) {- onCodeAction?.(pyMatch[1], 'cad');+ 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');+ }}// Match SVG (for CAD)@@ -283,15 +591,33 @@ Rules:onCodeAction?.(svgMatch[1], 'cad');}- // Match JSON (PPT)- const jsonMatch = fullResponse.match(/```json\n([\s\S]*?)\n```/);- if (jsonMatch && jsonMatch[1]) {- onCodeAction?.(jsonMatch[1], 'ppt');+ // 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');+ }+ } else {+ onCodeAction?.(jsonText, workspaceId === "cad" ? 'cad' : 'ppt');+ }}}} catch (error) {- if ((error as any)?.name === "AbortError") {+ if ((error as any)?.name === "AbortError" || (error as any)?.name === "APIUserAbortError") {setMessages(prev => {const last = prev[prev.length - 1];if (last?.role === 'assistant') {@@ -320,6 +646,114 @@ Rules:abortControllerRef.current?.abort();};+ const runTextChat = async (baseMessages: ChatMessage[]) => {+ const config = getAIConfig();+ 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 = [systemPrompt, globalSystemPrompt, globalConstraints].filter(Boolean).join('\n\n');+ const apiMessages: ChatMessage[] = [+ { role: 'system', content: systemContent },+ ...baseMessages+ ];++ setIsLoading(true);+ abortControllerRef.current?.abort();+ const controller = new AbortController();+ abortControllerRef.current = controller;++ setMessages([...baseMessages, { role: 'assistant', content: '' }]);++ let fullResponse = '';+ const updater = createThrottledAssistantUpdater();+ try {+ await streamChatMessage(apiMessages, (chunk) => {+ fullResponse = chunk;+ updater.push(chunk);+ }, chatModel, controller.signal);+ 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');+ }++ const svgMatch = fullResponse.match(/```svg\n([\s\S]*?)\n```/);+ if (svgMatch && svgMatch[1]) onCodeAction?.(svgMatch[1], 'cad');++ const jsonMatch = fullResponse.match(/```json\n([\s\S]*?)\n```/);+ if (jsonMatch && jsonMatch[1]) onCodeAction?.(jsonMatch[1], workspaceId === "cad" ? 'cad' : 'ppt');+ }+ } catch (error) {+ if ((error as any)?.name === "AbortError" || (error as any)?.name === "APIUserAbortError") {+ setMessages(prev => {+ const last = prev[prev.length - 1];+ if (last?.role === 'assistant') {+ const next = last.content ? `${last.content}\n\n(已中断)` : "(已中断)";+ return [...prev.slice(0, -1), { role: 'assistant', content: next }];+ }+ return [...prev, { role: 'assistant', content: "(已中断)" }];+ });+ return;+ }++ setMessages(prev => {+ const last = prev[prev.length - 1];+ if (last?.role === 'assistant' && !last.content) {+ return [...prev.slice(0, -1), { role: 'assistant', content: "抱歉,遇到错误。请检查设置中的 API Key 是否正确。" }];+ }+ return [...prev, { role: 'assistant', content: "抱歉,遇到错误。请检查设置中的 API Key 是否正确。" }];+ });+ } finally {+ setIsLoading(false);+ abortControllerRef.current = null;+ }+ };++ const handleRegenerate = async (messageIndex: number) => {+ if (messageIndex < 0 || messageIndex >= messages.length) return;+ if (messages[messageIndex].role !== 'assistant') return;+ const base = messages.slice(0, messageIndex);+ if (base.length === 0) return;+ const last = base[base.length - 1];+ if (last.role !== 'user') return;+ await runTextChat(base);+ };++ const handleEditAndResend = async (messageIndex: number, newText: string) => {+ if (messageIndex < 0 || messageIndex >= messages.length) return;+ if (messages[messageIndex].role !== 'user') return;++ const original = messages[messageIndex].content || "";+ const lines = original.split(/\r?\n/);+ const prefixTags: string[] = [];+ let i = 0;+ for (; i < lines.length; i += 1) {+ const line = lines[i];+ if (/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/.test(line) || /^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/.test(line)) {+ prefixTags.push(line);+ continue;+ }+ break;+ }+ const rest = lines.slice(i).join("\n");+ const marker = rest.match(/\n\n\[(PDF|File|Context)\b/);+ const preserved = marker && typeof marker.index === "number" ? rest.slice(marker.index) : "";+ const prefix = prefixTags.length > 0 ? `${prefixTags.join("\n")}\n\n` : "";+ const updatedUser: ChatMessage = { role: 'user', content: `${prefix}${newText}${preserved}` };+ const base = [...messages.slice(0, messageIndex), updatedUser];+ setInput("");+ setFiles([]);+ await runTextChat(base);+ };+const uiMessages: UIMessage[] = messages.map((msg, idx) => ({id: `msg-${idx}`,role: msg.role as any,@@ -329,7 +763,7 @@ Rules:if (collapsed) {return (- <div className={cn("h-full border-l border-border bg-background flex flex-col items-center py-4 gap-4 w-full", className)}>+ <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" /></Button>@@ -342,14 +776,23 @@ Rules:}return (- <div className={cn("flex flex-col h-full bg-background border-l border-border", className)}>+ <div className={cn("flex flex-col h-full bg-background/60 backdrop-blur border-l border-border/60", className)}>{/* Header */}- <div className="h-14 px-6 border-b border-border flex items-center justify-between bg-background/50 backdrop-blur z-10">+ <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="flex items-center gap-2 font-medium"><Bot className="w-5 h-5 text-primary" /><span>{title}</span></div><div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="icon"+ onClick={startNewChat}+ className="h-8 w-8 text-muted-foreground hover:text-foreground"+ title="新开对话"+ >+ <Plus className="w-4 h-4" />+ </Button>{!hideHistoryButton && (<Buttonvariant="ghost"@@ -391,33 +834,13 @@ Rules:setInput={setInput}status={isLoading ? "streaming" : "idle"}onDisplayChart={(xml) => onCodeAction?.(xml, 'flow')}+ onRegenerate={handleRegenerate}+ onEditMessage={handleEditAndResend}/></div>{/* Input */}<div className="p-4 bg-background/50 backdrop-blur relative z-20">- {attachments.length > 0 && (- <div className="mb-3 flex flex-wrap gap-2">- {attachments.map((a) => (- <div- key={a.id}- className="flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-xs text-muted-foreground"- title={a.name}- >- <span className="max-w-[240px] truncate">{a.name}</span>- {onRemoveAttachment && (- <button- type="button"- onClick={() => onRemoveAttachment(a.id)}- className="text-muted-foreground/80 hover:text-foreground transition-colors"- >- ×- </button>- )}- </div>- ))}- </div>- )}<ChatInputinput={input}setInput={setInput}@@ -426,8 +849,51 @@ Rules:onStop={handleStop}onFilesChange={setFiles}files={files}+ uploadMode={workspaceId === "ppt" ? "imagesOnly" : "all"}onOpenGlobalConstraints={() => setShowGlobalConstraints(true)}placeholder={inputPlaceholder}+ focusKey={workspaceId === "ppt" ? pptInputFocusTick : undefined}+ clearKey={workspaceId === "ppt" ? pptClearTick : undefined}+ richSegments={workspaceId === "ppt" ? pptInputSegments : undefined}+ onRichSegmentsChange={workspaceId === "ppt" ? setPptInputSegments : undefined}+ insertPptToken={workspaceId === "ppt" ? pptInsertToken : null}+ onInsertPptTokenHandled={workspaceId === "ppt" ? () => {+ pptInsertBusyRef.current = false;+ setPptInsertToken(null);+ pumpPptInsertQueue();+ } : undefined}+ bottomChips={+ attachments.length > 0+ ? (+ <div className="space-y-2">+ {attachments.length > 0 && (+ <div className="overflow-x-auto">+ <div className="flex flex-nowrap items-center gap-2">+ {attachments.map((a) => (+ <div+ key={a.id}+ className="flex items-center gap-2 rounded-full border border-border bg-muted/40 px-3 py-1 text-xs text-muted-foreground shrink-0"+ title={a.name}+ >+ <span className="max-w-[240px] truncate">{a.name}</span>+ {onRemoveAttachment && (+ <button+ type="button"+ onClick={() => onRemoveAttachment(a.id)}+ className="text-muted-foreground/80 hover:text-foreground transition-colors"+ >+ ×+ </button>+ )}+ </div>+ ))}+ </div>+ </div>+ )}+ </div>+ )+ : null+ }/></div>@@ -442,6 +908,9 @@ Rules:onToggleHistory={setShowHistory}history={history}onRestore={(item) => onRestore && onRestore(item)}+ onClear={() => {+ onClearVersionHistory?.();+ }}/><ResetWarningModalopen={showResetWarning}diff --git a/src/components/SettingsDialog.tsx b/src/components/SettingsDialog.tsxindex 6ec8127..c54adb9 100644--- a/src/components/SettingsDialog.tsx+++ b/src/components/SettingsDialog.tsx@@ -19,8 +19,6 @@ export function SettingsDialog() {const handleSave = () => {saveAIConfig(config);setIsOpen(false);- // Reload page to ensure all components pick up new config (simplest way)- window.location.reload();};return (@@ -112,7 +110,7 @@ export function SettingsDialog() {className="gap-2 rounded-lg shadow-sm"><Save className="w-4 h-4" />- 保存并刷新+ 保存</Button></div></div>diff --git a/src/components/history-dialog.tsx b/src/components/history-dialog.tsxindex e89c538..1d05c08 100644--- a/src/components/history-dialog.tsx+++ b/src/components/history-dialog.tsx@@ -6,14 +6,14 @@ import {DialogTitle,} from "@/components/ui/dialog"import { Button } from '@/components/ui/button';-import { Clock, RotateCcw, FileCode } from 'lucide-react';+import { Clock, RotateCcw, FileCode, Trash2 } from 'lucide-react';import { ScrollArea } from '@/components/ui/scroll-area';export interface HistoryItem {id: string;timestamp: number;content: string; // XML or code- type: 'xml' | 'python' | 'json';+ type: 'xml' | 'python' | 'json' | 'svg';summary?: string;}@@ -22,6 +22,7 @@ interface HistoryDialogProps {onToggleHistory: (show: boolean) => void;history: HistoryItem[];onRestore: (item: HistoryItem) => void;+ onClear?: () => void;}export function HistoryDialog({@@ -29,6 +30,7 @@ export function HistoryDialog({onToggleHistory,history,onRestore,+ onClear,}: HistoryDialogProps) {const formatDate = (ts: number) => {return new Date(ts).toLocaleString();@@ -38,10 +40,23 @@ export function HistoryDialog({<Dialog open={showHistory} onOpenChange={onToggleHistory}><DialogContent className="max-w-md max-h-[80vh] flex flex-col"><DialogHeader>- <DialogTitle className="flex items-center gap-2">- <Clock className="w-5 h-5 text-muted-foreground" />- 版本历史- </DialogTitle>+ <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" />+ 版本历史+ </DialogTitle>+ {history.length > 0 && onClear && (+ <Button+ size="sm"+ variant="ghost"+ onClick={onClear}+ className="gap-1 text-xs"+ >+ <Trash2 className="w-3.5 h-3.5" />+ 清空+ </Button>+ )}+ </div></DialogHeader><div className="flex-1 overflow-hidden mt-2">diff --git a/src/components/ui/code-block.tsx b/src/components/ui/code-block.tsxindex b635ef2..0873cd2 100644--- a/src/components/ui/code-block.tsx+++ b/src/components/ui/code-block.tsx@@ -1,4 +1,4 @@-import React, { useState, useEffect } from 'react';+import React, { useMemo, useRef, useState } from 'react';import { Highlight, themes } from "prism-react-renderer";import { ChevronRight, Loader2 } from 'lucide-react';import { cn } from '@/lib/utils';@@ -8,41 +8,48 @@ interface CodeBlockProps {code: string;language?: string;isStreaming?: boolean; // New prop to indicate if content is actively streaming+ blockId?: string;}-export function CodeBlock({ code, language = "xml", isStreaming = false }: CodeBlockProps) {- // Default to closed (false) initially- // If it's streaming, we keep it closed but show spinner.- const [isOpen, setIsOpen] = useState(false);-- // Auto-open if it's a very short snippet? No, user said "always collapsed".- // But we might want to ensure the code block updates even if closed.+const openStateById = new Map<string, boolean>();++export function CodeBlock({ code, language = "xml", isStreaming = false, blockId }: CodeBlockProps) {+ const [isOpen, setIsOpen] = useState(() => {+ if (blockId && openStateById.has(blockId)) return Boolean(openStateById.get(blockId));+ return false;+ });+ const preRef = useRef<HTMLPreElement | null>(null);+ const normalizedLanguage = useMemo(() => (language || "text").toLowerCase(), [language]);+ const normalizedCode = useMemo(() => String(code ?? ""), [code]);return (<Collapsibleopen={isOpen}- onOpenChange={setIsOpen}- className="w-full my-2 border border-border/50 rounded-lg bg-zinc-900 overflow-hidden group shadow-sm"+ 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-800/50 transition-colors text-xs font-medium text-zinc-400 select-none bg-zinc-900/50">+ <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")} />- <span className="uppercase font-semibold tracking-wider text-zinc-300">{language}</span>+ <span className="uppercase font-semibold tracking-wider text-zinc-700">{normalizedLanguage}</span>{isStreaming ? (<div className="flex items-center gap-2 ml-auto">- <span className="text-[10px] text-blue-400 animate-pulse">Generating code...</span>- <Loader2 className="w-3.5 h-3.5 animate-spin text-blue-500" />+ <span className="text-[10px] text-blue-600 animate-pulse">Generating code...</span>+ <Loader2 className="w-3.5 h-3.5 animate-spin text-blue-600" /></div>) : (- <span className="ml-auto text-[10px] opacity-70 font-mono">{code.length} chars</span>+ <span className="ml-auto text-[10px] opacity-70 font-mono">{normalizedCode.length} chars</span>)}</CollapsibleTrigger><CollapsibleContent><div className="p-0 border-t border-border/50">- <div className="overflow-hidden w-full bg-zinc-950/50">- <Highlight theme={themes.github} code={code} language={language}>+ <div className="overflow-hidden w-full bg-zinc-50">+ <Highlight theme={themes.github} code={normalizedCode} language={normalizedLanguage as any}>{({className: _className,style,@@ -51,31 +58,41 @@ export function CodeBlock({ code, language = "xml", isStreaming = false }: CodeBgetTokenProps,}) => (<pre- className="text-[11px] leading-relaxed overflow-x-auto overflow-y-auto max-h-[500px] scrollbar-thin p-3"+ ref={preRef}+ className="text-[11px] leading-relaxed overflow-x-hidden overflow-y-auto overscroll-contain max-h-[500px] scrollbar-thin p-3 whitespace-pre-wrap break-words"style={{...style,fontFamily: "var(--font-mono), ui-monospace, monospace",backgroundColor: "transparent",margin: 0,}}+ onWheelCapture={(e) => {+ const el = preRef.current;+ if (!el) return;+ const atTop = el.scrollTop <= 0;+ const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1;+ const dy = e.deltaY;+ if (dy > 0 && !atBottom) e.stopPropagation();+ if (dy < 0 && !atTop) e.stopPropagation();+ }}>- {tokens.map((line, i) => (- <div- key={i}- {...getLineProps({ line })}- style={{ display: 'table-row' }}- >- <span className="table-cell select-none text-zinc-600 text-right pr-4 w-8">{i + 1}</span>- <span className="table-cell">- {line.map((token, key) => (- <span- key={key}- {...getTokenProps({ token })}- />- ))}- </span>- </div>- ))}+ {tokens.map((line, i) => {+ const lineProps = getLineProps({ line });+ return (+ <div+ key={i}+ {...lineProps}+ className={cn("grid grid-cols-[3.25rem_1fr] gap-0", lineProps?.className)}+ >+ <span className="select-none text-zinc-400 text-right pr-4">{i + 1}</span>+ <span className="min-w-0 whitespace-pre-wrap break-words">+ {line.map((token, key) => (+ <span key={key} {...getTokenProps({ token })} />+ ))}+ </span>+ </div>+ );+ })}</pre>)}</Highlight>diff --git a/src/components/workspaces/Cad3DPreview.tsx b/src/components/workspaces/Cad3DPreview.tsxdeleted file mode 100644index e04b540..0000000--- a/src/components/workspaces/Cad3DPreview.tsx+++ /dev/null@@ -1,264 +0,0 @@-import React, { useEffect, useMemo, useRef } from "react"-import * as THREE from "three"-import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"-import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js"-import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js"--export function Cad3DPreview({- svg,- depth = 240,- meshUrl,- sectionCut = true,-}: {- svg?: string- depth?: number- meshUrl?: string- sectionCut?: boolean-}) {- const containerRef = useRef<HTMLDivElement | null>(null)- const rendererRef = useRef<THREE.WebGLRenderer | null>(null)- const sceneRef = useRef<THREE.Scene | null>(null)- const cameraRef = useRef<THREE.PerspectiveCamera | null>(null)- const controlsRef = useRef<OrbitControls | null>(null)- const meshGroupRef = useRef<THREE.Group | null>(null)- const rafRef = useRef<number | null>(null)-- const parsedSvg = useMemo(() => {- if (!svg) return null- try {- const loader = new SVGLoader();- return loader.parse(svg);- } catch (e) {- console.error("SVG Parse Error", e);- return null- }- }, [svg])-- useEffect(() => {- const container = containerRef.current- if (!container) return-- const scene = new THREE.Scene()- scene.background = new THREE.Color(0xf7f7f8)- sceneRef.current = scene-- const camera = new THREE.PerspectiveCamera(- 45,- container.clientWidth / container.clientHeight,- 0.1,- 10000- )- camera.position.set(0, 200, 400)- cameraRef.current = camera-- const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false })- renderer.setPixelRatio(window.devicePixelRatio || 1)- renderer.setSize(container.clientWidth, container.clientHeight)- renderer.localClippingEnabled = true- rendererRef.current = renderer- container.appendChild(renderer.domElement)-- const controls = new OrbitControls(camera, renderer.domElement)- controls.enableDamping = true- controls.dampingFactor = 0.08- controlsRef.current = controls-- const ambient = new THREE.AmbientLight(0xffffff, 0.75)- scene.add(ambient)- const dir = new THREE.DirectionalLight(0xffffff, 0.85)- dir.position.set(200, 400, 300)- scene.add(dir)-- const grid = new THREE.GridHelper(800, 40, 0xd1d5db, 0xe5e7eb)- grid.position.y = -1- scene.add(grid)-- const animate = () => {- controls.update()- renderer.render(scene, camera)- rafRef.current = requestAnimationFrame(animate)- }- animate()-- const onResize = () => {- const c = containerRef.current- const r = rendererRef.current- const cam = cameraRef.current- if (!c || !r || !cam) return- cam.aspect = c.clientWidth / c.clientHeight- cam.updateProjectionMatrix()- r.setSize(c.clientWidth, c.clientHeight)- }-- window.addEventListener("resize", onResize)-- return () => {- window.removeEventListener("resize", onResize)- if (rafRef.current) cancelAnimationFrame(rafRef.current)- controls.dispose()- renderer.dispose()- if (renderer.domElement.parentElement === container) {- container.removeChild(renderer.domElement)- }- scene.clear()- rendererRef.current = null- sceneRef.current = null- cameraRef.current = null- controlsRef.current = null- meshGroupRef.current = null- }- }, [])-- useEffect(() => {- const scene = sceneRef.current- if (!scene) return-- if (meshGroupRef.current) {- scene.remove(meshGroupRef.current)- meshGroupRef.current.traverse((obj) => {- const mesh = obj as THREE.Mesh- if ((mesh as any).geometry) (mesh as any).geometry.dispose?.()- if ((mesh as any).material) {- const mat = (mesh as any).material- if (Array.isArray(mat)) mat.forEach((m) => m.dispose?.())- else mat.dispose?.()- }- })- meshGroupRef.current = null- }-- const clippingPlane = sectionCut ? new THREE.Plane(new THREE.Vector3(1, 0, 0), 0) : null-- const centerAndFrame = (group: THREE.Group) => {- const box = new THREE.Box3().setFromObject(group)- const size = new THREE.Vector3()- box.getSize(size)- const center = new THREE.Vector3()- box.getCenter(center)- group.position.x -= center.x- group.position.z -= center.z-- const camera = cameraRef.current- const controls = controlsRef.current- if (camera && controls) {- const maxDim = Math.max(size.x, size.y, size.z, 1)- camera.position.set(0, maxDim * 0.9, maxDim * 1.4)- controls.target.set(0, 0, 0)- controls.update()- }- }-- if (meshUrl) {- const loader = new STLLoader()- let canceled = false- loader.load(- meshUrl,- (geometry) => {- if (canceled) return- geometry.computeVertexNormals()- geometry.computeBoundingBox()- const material = new THREE.MeshBasicMaterial({- color: 0xe5e7eb,- transparent: true,- opacity: 0.18,- side: THREE.DoubleSide,- depthWrite: false,- clippingPlanes: clippingPlane ? [clippingPlane] : undefined,- })- const mesh = new THREE.Mesh(geometry, material)- mesh.rotation.x = -Math.PI / 2-- const edgesGeom = new THREE.EdgesGeometry(geometry, 18)- const edgesMat = new THREE.LineBasicMaterial({- color: 0x111827,- transparent: true,- opacity: 0.75,- clippingPlanes: clippingPlane ? [clippingPlane] : undefined,- })- const edges = new THREE.LineSegments(edgesGeom, edgesMat)- edges.rotation.x = -Math.PI / 2-- const group = new THREE.Group()- group.add(mesh)- group.add(edges)- scene.add(group)- meshGroupRef.current = group- centerAndFrame(group)- },- undefined,- (error) => {- if (canceled) return- console.error("STL Load Error", error)- }- )- return () => {- canceled = true- }- }-- if (!parsedSvg) return-- const group = new THREE.Group()- group.rotation.x = -Math.PI / 2-- const paths = parsedSvg.paths || []-- paths.forEach((path, i) => {- const fillColor = path.userData?.style?.fill;- const strokeColor = path.userData?.style?.stroke;-- // 1. Handle Fills (Extruded Meshes)- if (fillColor !== undefined && fillColor !== 'none') {- const shapes = SVGLoader.createShapes(path);- shapes.forEach(shape => {- const geom = new THREE.ExtrudeGeometry(shape, { depth: depth, bevelEnabled: false });- // Center geometry locally if needed, but here we want absolute positioning relative to group- // geom.center() // Do NOT center individual parts, or they lose relative position-- const mat = new THREE.MeshBasicMaterial({- color: 0xd1d5db,- transparent: true,- opacity: 0.22,- side: THREE.DoubleSide,- depthWrite: false,- clippingPlanes: clippingPlane ? [clippingPlane] : undefined,- });- const mesh = new THREE.Mesh(geom, mat);- // Add small Z offset to prevent z-fighting and allow "painters algorithm" in 3D height- mesh.position.z = i * 0.1;- group.add(mesh);- });- }-- // 2. Handle Strokes (Lines/Walls)- if (strokeColor !== undefined && strokeColor !== 'none') {- const shapes = SVGLoader.createShapes(path);- // If createShapes returns empty for strokes, we can manually render lines- // But usually for CAD, strokes might define walls.- // Let's render them as thick lines (using Tubes or just Lines) slightly above the floor-- path.subPaths.forEach(subPath => {- const points = subPath.getPoints();- const geometry = new THREE.BufferGeometry().setFromPoints(points);- const material = new THREE.LineBasicMaterial({- color: strokeColor === '#000000' ? 0x333333 : strokeColor,- linewidth: 2,- clippingPlanes: clippingPlane ? [clippingPlane] : undefined,- });-- const line = new THREE.Line(geometry, material);- // Lift lines slightly above the extruded floor (assuming floor is at z=0 to z=depth)- // If floor is extruded by 'depth', we want lines on top surface- line.position.z = depth + 0.5 + (i * 0.01);- group.add(line);- });- }- });-- scene.add(group)- meshGroupRef.current = group- centerAndFrame(group)- }, [parsedSvg, depth, meshUrl, sectionCut])-- return <div ref={containerRef} className="w-full h-full" />-}diff --git a/src/components/workspaces/CadWorkspace.tsx b/src/components/workspaces/CadWorkspace.tsxindex 66415a2..fee00f8 100644--- a/src/components/workspaces/CadWorkspace.tsx+++ b/src/components/workspaces/CadWorkspace.tsx@@ -1,6 +1,5 @@-import React, { useMemo, useState, useEffect } from 'react';-import { generateChatMessage } from '@/lib/ai-client';-import { Loader2, MessageSquarePlus, Copy, Check, Box, Layers3 } from 'lucide-react';+import React, { useState, useEffect } from 'react';+import { Loader2, MessageSquarePlus, Box, Image as ImageIcon, Table2, Download } from 'lucide-react';import {ContextMenu,ContextMenuContent,@@ -8,133 +7,34 @@ import {ContextMenuTrigger,} from "@/components/ui/context-menu";import { Button } from "@/components/ui/button";-import { Cad3DPreview } from "@/components/workspaces/Cad3DPreview";+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";interface CadWorkspaceProps {onAddToChat?: (code: string) => void;- code?: string; // New prop for incoming code (SVG or Python)+ svg2d?: string;+ plan?: any;+ images?: { title: string; url: string }[];+ imagesLoading?: boolean;+ bom?: { columns: string[]; rows: any[] } | null;+ focusPanel?: "2d" | "renders" | "bom" | null;}-export function CadWorkspace({ onAddToChat, code }: CadWorkspaceProps) {+export function CadWorkspace({ onAddToChat, svg2d, plan, images = [], imagesLoading = false, bom, focusPanel }: CadWorkspaceProps) {const [svgContent, setSvgContent] = useState<string | null>(null);- const [drawioXml, setDrawioXml] = useState<string | null>(null);- const [loading, setLoading] = useState(false);- const [freecadCode, setFreecadCode] = useState<string>("");- const [copied, setCopied] = useState(false);- const [viewMode, setViewMode] = useState<"2d" | "3d" | "freecad">("2d");- const [isGenerating3d, setIsGenerating3d] = useState(false);- const [meshUrl, setMeshUrl] = useState<string | null>(null);- const [meshError, setMeshError] = useState<string | null>(null);- const [isRunningFreecad, setIsRunningFreecad] = useState(false);- const [sectionCut, setSectionCut] = useState(true);+ const [viewMode, setViewMode] = useState<"2d" | "renders" | "bom">("2d");+ const [previewImage, setPreviewImage] = useState<{ title: string; url: string } | null>(null);useEffect(() => {- if (code) {- const trimmed = code.trim();- setMeshUrl(null);- setMeshError(null);- if (trimmed.startsWith('<svg')) {- setSvgContent(code);- setDrawioXml(null);- setViewMode("2d");- return;- }- if (trimmed.startsWith('<mxGraphModel') || trimmed.startsWith('<mxfile')) {- setDrawioXml(code);- setSvgContent(null);- setViewMode("2d");- return;- }- setFreecadCode(code);- setViewMode("freecad");+ if (typeof svg2d === "string") {+ setSvgContent(svg2d);}- }, [code]);-- const handleCopyCode = async () => {- if (freecadCode) {- await navigator.clipboard.writeText(freecadCode);- setCopied(true);- setTimeout(() => setCopied(false), 2000);- }- };-- const freecadServerBase = (import.meta as any).env?.VITE_FREECAD_SERVER || "http://localhost:43110";-- const normalizeMeshUrl = (url: string) => {- if (!url) return null;- if (url.startsWith("http")) return url;- return `${freecadServerBase}${url}`;- };-- const runFreecad = async (codeOverride?: string) => {- const codeToRun = (codeOverride ?? freecadCode).trim();- if (!codeToRun || isRunningFreecad) return;- setIsRunningFreecad(true);- setMeshError(null);- try {- const response = await fetch(`${freecadServerBase}/api/freecad/run`, {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ code: codeToRun }),- });- if (!response.ok) {- const text = await response.text();- throw new Error(text || "FreeCAD 执行失败");- }- const data = await response.json();- const resolvedUrl = normalizeMeshUrl(data.meshUrl || data.url || "");- if (!resolvedUrl) throw new Error("未返回网格地址");- setMeshUrl(resolvedUrl);- setViewMode("3d");- } catch (e) {- const message = e instanceof Error ? e.message : "FreeCAD 执行失败";- setMeshError(message);- } finally {- setIsRunningFreecad(false);- }- };-- const canShow3d = !!meshUrl || !!svgContent || !!freecadCode;-- const handleGenerate3dFrom2d = async () => {- if ((!svgContent && !drawioXml) || isGenerating3d) return;- setIsGenerating3d(true);- try {- const prompt = `You are a CAD assistant using FreeCAD Python.-Input is a 2D floor plan, provided as draw.io XML or SVG.-Goal: generate a real 3D model in FreeCAD (walls/rooms/openings) based on the 2D plan.--Requirements:-- Output ONLY Python code for FreeCAD.-- The script must be runnable inside FreeCAD's Python console/macros.-- Prefer robust geometry: create closed wires, make faces, then extrude solids.-- Use a default wall height of 3000 mm and wall thickness of 200 mm unless specified.-- Create a new document and add solids.-- Add a base/floor slab and extrude walls upward along +Z.-- Keep Z scale realistic. Do not generate a "flat" model.--If draw.io XML is provided:-- Treat rectangles/lines/polylines as plan elements (walls/rooms).-- Use element labels to infer types: "wall", "door", "window", "room".-- Assume 1 draw.io unit = 10 mm if no other scale.--Input:-${drawioXml ? `\`\`\`xml\n${drawioXml}\n\`\`\`` : `\`\`\`svg\n${svgContent}\n\`\`\``}-`;-- const response = await generateChatMessage([{ role: "user", content: prompt }]);- const match = response.match(/```python\s*([\s\S]*?)```/);- const py = match ? match[1].trim() : response.trim();- setFreecadCode(py);- setMeshUrl(null);- await runFreecad(py);- } catch (e) {- console.error("Failed to generate FreeCAD code", e);- } finally {- setIsGenerating3d(false);- }- };+ }, [svg2d]);+ useEffect(() => {+ if (!focusPanel) return;+ setViewMode(focusPanel);+ }, [focusPanel]);+return (<ContextMenu><ContextMenuTrigger className="w-full h-full bg-muted/20 relative overflow-hidden">@@ -144,146 +44,164 @@ ${drawioXml ? `\`\`\`xml\n${drawioXml}\n\`\`\`` : `\`\`\`svg\n${svgContent}\n\`\variant={viewMode === "2d" ? "default" : "outline"}className="h-7 px-2 text-xs gap-1"onClick={() => setViewMode("2d")}- disabled={!svgContent && !drawioXml}+ disabled={!svgContent}><Box className="w-3.5 h-3.5" />2D</Button><Buttonsize="sm"- variant={viewMode === "3d" ? "default" : "outline"}+ variant={viewMode === "renders" ? "default" : "outline"}className="h-7 px-2 text-xs gap-1"- onClick={() => {- if (meshUrl) {- setViewMode("3d");- return;- }- if (freecadCode) {- runFreecad();- return;- }- setViewMode("3d");- }}- disabled={!canShow3d}- >- <Layers3 className="w-3.5 h-3.5" />- 3D- </Button>- <Button- size="sm"- variant={sectionCut ? "default" : "outline"}- className="h-7 px-2 text-xs"- onClick={() => setSectionCut(v => !v)}- disabled={!canShow3d}- >- 剖切- </Button>- <Button- size="sm"- variant={viewMode === "freecad" ? "default" : "outline"}- className="h-7 px-2 text-xs"- onClick={() => setViewMode("freecad")}- disabled={!freecadCode}- >- FreeCAD- </Button>- <div className="w-px h-5 bg-border mx-1" />- <Button- size="sm"- className="h-7 px-2 text-xs"- onClick={handleGenerate3dFrom2d}- disabled={(!svgContent && !drawioXml) || isGenerating3d}+ onClick={() => setViewMode("renders")}+ disabled={(!images || images.length === 0) && !imagesLoading}>- {isGenerating3d ? <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" /> : null}- 由 2D 生成 FreeCAD 3D+ <ImageIcon className="w-3.5 h-3.5" />+ 装修图</Button><Buttonsize="sm"- variant="outline"- className="h-7 px-2 text-xs"- onClick={() => runFreecad()}- disabled={!freecadCode || isRunningFreecad}+ variant={viewMode === "bom" ? "default" : "outline"}+ className="h-7 px-2 text-xs gap-1"+ onClick={() => setViewMode("bom")}>- {isRunningFreecad ? <Loader2 className="w-3.5 h-3.5 mr-1 animate-spin" /> : null}- 运行 FreeCAD 生成 3D+ <Table2 className="w-3.5 h-3.5" />+ 物料</Button></div>- {!svgContent && !freecadCode && !loading && (+ {!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">在右侧对话里让 AI 先生成 SVG(2D),满意后再生成 FreeCAD(3D)。</p>+ <p className="text-xs">在右侧对话里先做需求分析,确认方案后生成 SVG(2D),满意后生成装修图。</p></div></div>)}- {loading && (- <div className="flex flex-col items-center text-muted-foreground">- <Loader2 className="w-8 h-8 animate-spin mb-2 text-blue-600" />- <p>正在生成 2D 视图...</p>- </div>- )}-<div className="w-full h-full pt-16 p-6">- {viewMode === "2d" && svgContent && !loading && (+ {viewMode === "2d" && svgContent && (<div className="w-full h-full bg-white shadow-sm rounded-xl overflow-hidden border border-border/50 p-6 flex items-center justify-center"><div className="w-full h-full overflow-auto" dangerouslySetInnerHTML={{ __html: svgContent }} /></div>)}- {viewMode === "2d" && !svgContent && drawioXml && !loading && (- <div className="w-full h-full bg-zinc-950 shadow-sm rounded-xl overflow-auto border border-border/50 p-4 relative">- <pre className="text-green-400 font-mono text-xs whitespace-pre-wrap">{drawioXml}</pre>- </div>- )}- {viewMode === "3d" && (svgContent || meshUrl) && (- <div className="w-full h-full grid grid-cols-1 lg:grid-cols-2 gap-4">- <div className="bg-white rounded-xl border border-border/50 shadow-sm overflow-hidden">- <div className="h-full min-h-[360px]">- <Cad3DPreview- svg={meshUrl ? undefined : svgContent || undefined}- meshUrl={meshUrl || undefined}- depth={240}- sectionCut={sectionCut}- />+ {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 ? (+ <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></div>- </div>- <div className="bg-zinc-950 rounded-xl border border-border/50 shadow-sm overflow-hidden relative">- <div className="absolute top-2 right-2">- <Button variant="ghost" size="icon" onClick={handleCopyCode} className="h-8 w-8 text-zinc-400 hover:text-white hover:bg-zinc-800" disabled={!freecadCode}>- {copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}- </Button>- </div>- <div className="h-full max-h-[70vh] overflow-auto p-4">- {meshError && (- <div className="text-red-400 text-xs mb-2 whitespace-pre-wrap">{meshError}</div>- )}- <pre className="text-green-400 font-mono text-xs whitespace-pre-wrap">{freecadCode || "点击「由 2D 生成 3D」生成 FreeCAD 脚本。"}</pre>+ ) : 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) => (+ <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" />+ <span className="truncate flex-1">{img.title}</span>+ <div className="flex items-center gap-1">+ <Button+ variant="ghost"+ size="icon"+ className="h-7 w-7"+ onClick={() => setPreviewImage(img)}+ title="查看"+ >+ <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="下载">+ <Download className="w-4 h-4" />+ </Button>+ </a>+ </div>+ </div>+ <div className="aspect-video bg-muted/20 cursor-pointer" onClick={() => setPreviewImage(img)}>+ <img src={img.url} alt={img.title} className="w-full h-full object-cover" />+ </div>+ </div>+ ))}</div>- </div>+ )}</div>)}- {viewMode === "freecad" && freecadCode && (- <div className="w-full h-full bg-zinc-950 shadow-sm rounded-xl overflow-auto border border-border/50 p-4 relative">- <div className="absolute top-2 right-2">- <Button variant="ghost" size="icon" onClick={handleCopyCode} className="h-8 w-8 text-zinc-400 hover:text-white hover:bg-zinc-800">- {copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}- </Button>- </div>- <pre className="text-green-400 font-mono text-xs whitespace-pre-wrap">{freecadCode}</pre>+ {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="w-full overflow-auto">+ <table className="w-full text-sm border-collapse">+ <thead>+ <tr className="text-left border-b border-border/60">+ {bom.columns.map((c, i) => (+ <th key={`${c}-${i}`} className="py-2 px-2 font-medium text-foreground/80 whitespace-normal break-words">{c}</th>+ ))}+ </tr>+ </thead>+ <tbody>+ {(Array.isArray(bom.rows) ? bom.rows : []).map((r, i) => (+ <tr key={i} className="border-b border-border/40">+ {bom.columns.map((_, ci) => (+ <td key={ci} className="py-2 px-2 text-foreground/90 whitespace-normal break-words">+ {Array.isArray(r) ? String(r[ci] ?? "") : String(r?.[bom.columns[ci]] ?? "")}+ </td>+ ))}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}</div>)}</div></ContextMenuTrigger><ContextMenuContent>- <ContextMenuItem onClick={() => onAddToChat && onAddToChat(svgContent || drawioXml || freecadCode)} className="cursor-pointer gap-2">+ <ContextMenuItem+ onClick={() => {+ 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 === "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></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>+ </DialogHeader>+ <div className="w-full">+ {previewImage?.url ? (+ <div className="space-y-3">+ <div className="flex items-center justify-end">+ <a href={previewImage.url} download={`${previewImage.title || "render"}.png`} className="inline-flex">+ <Button variant="outline" size="sm" className="h-8 px-3 text-xs">+ <Download className="w-4 h-4 mr-1" />+ 下载图片+ </Button>+ </a>+ </div>+ <div className="rounded-lg border border-border/50 overflow-hidden bg-muted/10">+ <img src={previewImage.url} alt={previewImage.title} className="w-full h-auto max-h-[70vh] object-contain" />+ </div>+ </div>+ ) : null}+ </div>+ </DialogContent>+ </Dialog></ContextMenu>);}diff --git a/src/components/workspaces/PptWorkspace.tsx b/src/components/workspaces/PptWorkspace.tsxindex 47ea79e..8bd70ae 100644--- a/src/components/workspaces/PptWorkspace.tsx+++ b/src/components/workspaces/PptWorkspace.tsx@@ -2,7 +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 { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb } from 'lucide-react';+import { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb, X, ArrowLeft, ArrowRight } from 'lucide-react';import {ContextMenu,ContextMenuContent,@@ -38,13 +38,22 @@ type CreationStep = 'idle' | 'input' | 'outline' | 'generating_content' | 'genertype CreationMode = 'idea' | 'outline' | 'description';type ReferenceFile = { id: string; filename: string; content: string; charCount: number };-const AVAILABLE_TEMPLATES = [- { name: "科技商务", path: "/templates/template_b.png" },- { name: "学术汇报", path: "/templates/template_academic.jpg" },- { name: "极简主义", path: "/templates/template_s.png" },- { name: "矢量插画", path: "/templates/template_vector_illustration.png" },- { name: "活力黄", path: "/templates/template_y.png" },- { name: "磨砂玻璃", path: "/templates/template_glass.png" },+type PresetTemplate = { id: string; name: string; path: string };+type UploadTemplate = { id: string; name: string; dataUrl: string };+type TemplateItem =+ | { id: string; name: string; kind: "preset"; previewSrc: string; presetPath: string }+ | { id: string; name: string; kind: "upload"; previewSrc: string; dataUrl: string };++const PPT_TEMPLATE_UPLOADS_KEY = "ppt_template_uploads_v1";+const PPT_TEMPLATE_HIDDEN_PRESETS_KEY = "ppt_template_hidden_presets_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" },];const MODEL_CONCURRENCY = 30;@@ -54,16 +63,34 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst [localSlides, setLocalSlides] = useState<SlideData[]>([]);const [currentSlideIndex, setCurrentSlideIndex] = useState(0);const [templateImage, setTemplateImage] = useState<string | null>(null);- const [uploadedTemplateImage, setUploadedTemplateImage] = useState<string | null>(null);- const [selectedTemplatePath, setSelectedTemplatePath] = useState<string | null>(null);+ const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);+ const [uploadedTemplates, setUploadedTemplates] = useState<UploadTemplate[]>(() => {+ if (typeof window === "undefined") return [];+ try {+ const raw = localStorage.getItem(PPT_TEMPLATE_UPLOADS_KEY);+ const parsed = raw ? JSON.parse(raw) : [];+ if (!Array.isArray(parsed)) return [];+ return parsed+ .filter((x: any) => x && typeof x.id === "string" && typeof x.name === "string" && typeof x.dataUrl === "string")+ .map((x: any) => ({ id: x.id, name: x.name, dataUrl: x.dataUrl }));+ } catch {+ return [];+ }+ });+ const [hiddenPresetTemplateIds, setHiddenPresetTemplateIds] = useState<string[]>(() => {+ if (typeof window === "undefined") return [];+ try {+ const raw = localStorage.getItem(PPT_TEMPLATE_HIDDEN_PRESETS_KEY);+ const parsed = raw ? JSON.parse(raw) : [];+ return Array.isArray(parsed) ? parsed.map((x: any) => String(x)) : [];+ } catch {+ return [];+ }+ });const [generatedImages, setGeneratedImages] = useState<Record<string, string>>({});const [imageVersions, setImageVersions] = useState<Record<string, Array<{ id: string; url: string; timestamp: number; type: 'generated' | 'edited'; instruction?: string }>>>({});const [currentImageVersionId, setCurrentImageVersionId] = useState<Record<string, string>>({});const [isGeneratingImage, setIsGeneratingImage] = useState(false);- const [selectedSlideIds, setSelectedSlideIds] = useState<Record<string, boolean>>({});- const [bulkEditOpen, setBulkEditOpen] = useState(false);- const [bulkEditText, setBulkEditText] = useState("");- const [isApplyingBulkEdit, setIsApplyingBulkEdit] = useState(false);// Creation Wizard Stateconst [creationStep, setCreationStep] = useState<CreationStep>('idle');@@ -79,43 +106,132 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst referenceFileInputRef = useRef<HTMLInputElement | null>(null);const [slideshowOpen, setSlideshowOpen] = useState(false);const [slideshowIndex, setSlideshowIndex] = useState(0);- const [slideshowAuto, setSlideshowAuto] = useState(true);-- // Load default template on mount+ const [windowDimensions, setWindowDimensions] = useState({ width: 0, height: 0 });++ const 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 })),+ ...uploadedTemplates.map((t) => ({ id: t.id, name: t.name, kind: "upload" as const, previewSrc: t.dataUrl, dataUrl: t.dataUrl })),+ ];+useEffect(() => {- const loadDefaultTemplate = async () => {- try {- const response = await fetch(AVAILABLE_TEMPLATES[0].path);- const blob = await response.blob();- const reader = new FileReader();- reader.onloadend = () => {- setTemplateImage(reader.result as string);- setSelectedTemplatePath(AVAILABLE_TEMPLATES[0].path);- };- reader.readAsDataURL(blob);- } catch (e) {- console.error("Failed to load default template", e);- }- };- loadDefaultTemplate();+ if (typeof window === "undefined") return;+ try {+ localStorage.setItem(PPT_TEMPLATE_UPLOADS_KEY, JSON.stringify(uploadedTemplates));+ } catch {+ }+ }, [uploadedTemplates]);++ useEffect(() => {+ if (typeof window === "undefined") return;+ try {+ localStorage.setItem(PPT_TEMPLATE_HIDDEN_PRESETS_KEY, JSON.stringify(hiddenPresetTemplateIds));+ } catch {+ }+ }, [hiddenPresetTemplateIds]);++ useEffect(() => {+ if (typeof window === "undefined") return;+ const handleResize = () => {+ setWindowDimensions({ width: window.innerWidth, height: window.innerHeight });+ };+ window.addEventListener('resize', handleResize);+ handleResize();+ return () => window.removeEventListener('resize', handleResize);}, []);- const handleTemplateSelect = async (path: string) => {- try {- const response = await fetch(path);- const blob = await response.blob();+ const getSlideshowDimensions = () => {+ if (!windowDimensions.width) return { width: '90vw', height: '50.625vw' }; // Fallback+ const maxWidth = windowDimensions.width * 0.9;+ const maxHeight = windowDimensions.height * 0.85;++ let w = maxWidth;+ let h = w * 9 / 16;++ if (h > maxHeight) {+ h = maxHeight;+ w = h * 16 / 9;+ }+ return { width: w, height: h };+ };++ const setTemplateFromItem = async (item: TemplateItem) => {+ setSelectedTemplateId(item.id);+ if (item.kind === "upload") {+ setTemplateImage(item.dataUrl);+ return;+ }+ try {+ const response = await fetch(item.presetPath);+ const blob = await response.blob();+ const reader = new FileReader();+ reader.onloadend = () => {+ setTemplateImage(reader.result as string);+ };+ reader.readAsDataURL(blob);+ } catch (e) {+ console.error("Failed to load template", e);+ }+ };++ useEffect(() => {+ if (templates.length === 0) {+ setSelectedTemplateId(null);+ setTemplateImage(null);+ return;+ }+ const exists = selectedTemplateId && templates.some((t) => t.id === selectedTemplateId);+ if (exists) return;+ void setTemplateFromItem(templates[0]);+ }, [selectedTemplateId, hiddenPresetTemplateIds.join("|"), uploadedTemplates.map((t) => t.id).join("|")]);++ const addUploadedTemplates = async (files: File[]) => {+ const imageFiles = Array.from(files || []).filter((f) => f && f.type.startsWith("image/"));+ if (imageFiles.length === 0) return;+ const toDataUrl = (file: File) =>+ new Promise<string>((resolve, reject) => {const reader = new FileReader();- reader.onloadend = () => {- setTemplateImage(reader.result as string);- setSelectedTemplatePath(path);- };- reader.readAsDataURL(blob);+ reader.onload = () => resolve(reader.result as string);+ reader.onerror = reject;+ reader.readAsDataURL(file);+ });+ const baseName = (name: string) => String(name || "").replace(/\.[^.]+$/, "") || "模板";++ const created: UploadTemplate[] = [];+ for (const f of imageFiles) {+ try {+ const dataUrl = await toDataUrl(f);+ const id = `upload-${Date.now()}-${Math.random().toString(16).slice(2)}`;+ const name = baseName(f.name);+ created.push({ id, name, dataUrl });} catch (e) {- console.error("Failed to load template", e);+ console.error("Failed to read template image", e);}+ }+ if (created.length === 0) return;+ setUploadedTemplates((prev) => [...prev, ...created]);+ const last = created[created.length - 1];+ setSelectedTemplateId(last.id);+ setTemplateImage(last.dataUrl);};- // Sync prop data to local state+ const handleTemplateUploadInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {+ const files = Array.from(e.target.files || []);+ e.target.value = "";+ await addUploadedTemplates(files);+ };++ const deleteTemplate = (item: TemplateItem) => {+ if (item.kind === "preset") {+ setHiddenPresetTemplateIds((prev) => (prev.includes(item.id) ? prev : [...prev, item.id]));+ return;+ }+ setUploadedTemplates((prev) => prev.filter((t) => t.id !== item.id));+ };++ const [isApplyingEdits, setIsApplyingEdits] = useState(false);+useEffect(() => {if (data && data.slides && data.slides.length > 0) {setLocalSlides(data.slides);@@ -143,6 +259,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit: null;if (!incomingSlides || incomingSlides.length === 0) return;+ const uploadedImages: string[] = Array.isArray(parsed?.uploadedImages) ? parsed.uploadedImages : [];const mergedSlides: SlideData[] = (() => {const existing = localSlides.length > 0 ? [...localSlides] : [];@@ -168,8 +285,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit})();setLocalSlides(mergedSlides);- setCreationStep('done');- onPptReadyChange?.(true);+ const allowImageEdits = creationStep === 'done';const editTasks: Array<() => Promise<void>> = [];for (const inc of incomingSlides) {@@ -185,16 +301,17 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst slide = mergedSlides.find((s) => s.id === id);if (!slide) continue;- if (incomingImageUrl.trim()) {+ if (allowImageEdits && incomingImageUrl.trim()) {pushImageVersion(id, incomingImageUrl, 'edited', instruction.trim() ? instruction : undefined);continue;}- if (!instruction.trim()) continue;+ if (!allowImageEdits || !instruction.trim()) continue;editTasks.push(async () => {const versions = imageVersions[id] || [];const currentVersion = currentImageVersionId[id];const currentUrl = currentVersion ? versions.find(v => v.id === currentVersion)?.url : generatedImages[id];+ if (!currentUrl) return;const page: PptPage = {id,@@ -202,7 +319,13 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditcontent: slide.content || [],description: slide.description};- const editedUrl = await pptService.editPageImage(page, instruction, currentUrl || undefined, templateImage || undefined);+ const editedUrl = await pptService.editPageImage(+ page,+ instruction,+ currentUrl || undefined,+ templateImage || undefined,+ uploadedImages+ );if (editedUrl) {pushImageVersion(id, editedUrl, 'edited', instruction);}@@ -210,17 +333,22 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit}if (editTasks.length > 0) {+ setIsApplyingEdits(true);try {await runInParallel(editTasks, MODEL_CONCURRENCY);} catch (e) {console.error("Failed to apply image edits", e);+ } finally {+ setIsApplyingEdits(false);}}};useEffect(() => {if (!incomingEdit?.payload) return;- applyIncomingSlideEdits(incomingEdit.payload);+ Promise.resolve(applyIncomingSlideEdits(incomingEdit.payload)).catch((e) => {+ console.error("Failed to apply incoming slide edits", e);+ });}, [incomingEdit?.id]);const activeSlides = localSlides.length > 0 ? localSlides : [];@@ -238,15 +366,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditsetSlideshowIndex(currentSlideIndex);}, [slideshowOpen]);- useEffect(() => {- if (!slideshowOpen || !slideshowAuto) return;- if (activeSlides.length <= 1) return;- const id = window.setInterval(() => {- setSlideshowIndex((prev) => (prev + 1) % activeSlides.length);- }, 3000);- return () => window.clearInterval(id);- }, [slideshowOpen, slideshowAuto, activeSlides.length]);-const pushImageVersion = (slideId: string, url: string, type: 'generated' | 'edited', instruction?: string) => {const versionId = `v-${Date.now()}-${Math.random().toString(16).slice(2)}`;setImageVersions(prev => ({@@ -260,19 +379,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditsetGeneratedImages(prev => ({ ...prev, [slideId]: url }));};- const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {- const file = e.target.files?.[0];- if (file) {- const reader = new FileReader();- reader.onload = (e) => {- setTemplateImage(e.target?.result as string);- setUploadedTemplateImage(e.target?.result as string);- setSelectedTemplatePath("upload");- };- reader.readAsDataURL(file);- }- };-const addReferenceFiles = async (files: File[]) => {if (!files.length) return;setIsParsingReferenceFiles(true);@@ -323,10 +429,10 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit};const resetGenerationState = () => {+ console.log("Resetting generation state...");setGeneratedImages({});setImageVersions({});setCurrentImageVersionId({});- setSelectedSlideIds({});setCurrentSlideIndex(0);};@@ -371,7 +477,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditif (heading) {pushCurrent();current = {- id: `slide-${slides.length}`,+ id: `slide-${slides.length + 1}`,title: heading[2].trim() || `第 ${slides.length + 1} 页`,content: []};@@ -380,7 +486,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst bullet = l.match(/^[-•]\s+(.*)$/);if (bullet) {if (!current) {- current = { id: `slide-${slides.length}`, title: `第 ${slides.length + 1} 页`, content: [] };+ current = { id: `slide-${slides.length + 1}`, title: `第 ${slides.length + 1} 页`, content: [] };}current.content.push(bullet[1].trim());continue;@@ -388,7 +494,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst desc = l.match(/^description[::]\s*(.*)$/i);if (desc) {if (!current) {- current = { id: `slide-${slides.length}`, title: `第 ${slides.length + 1} 页`, content: [] };+ current = { id: `slide-${slides.length + 1}`, title: `第 ${slides.length + 1} 页`, content: [] };}current.description = desc[1].trim();continue;@@ -404,9 +510,13 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditfor (const task of tasks) {const p = Promise.resolve().then(() => task());results.push(p);- const e: Promise<void> = p.then(() => {+ let e: Promise<void>;+ e = p+ .catch(() => {+ })+ .then(() => {executing.splice(executing.indexOf(e), 1);- });+ });executing.push(e);if (executing.length >= limit) {await Promise.race(executing);@@ -443,7 +553,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdittry {const pages = await pptService.generateSlidesFromDescription(descriptionInput);const nextSlides: SlideData[] = pages.map((p, i) => ({- id: `slide-${i}`,+ id: `slide-${i + 1}`,title: p.title,content: p.content,description: p.description@@ -469,8 +579,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdittry {const pages = await pptService.generateOutline(ideaInput);+ if (!Array.isArray(pages) || pages.length === 0) {+ throw new Error("Invalid outline response");+ }const slides: SlideData[] = pages.map((p, i) => ({- id: `slide-${i}`,+ id: `slide-${i + 1}`,title: p.title,content: p.content,description: p.description@@ -480,7 +593,13 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditonPptReadyChange?.(true);} catch (e) {console.error("Failed to generate outline", e);- alert("生成大纲失败,请重试");+ const name = (e as any)?.name;+ const isAbort = name === "AbortError" || name === "APIUserAbortError";+ const msg = isAbort ? "生成大纲超时或被中断(120s)。请检查网络/模型可用性后重试。" : e instanceof Error ? e.message : "生成大纲失败,请重试";+ alert(msg);+ setCreationStep("idle");+ } finally {+ setProgress({ current: 0, total: 0, message: "" });}};@@ -640,7 +759,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit}if (imageUrl) {- const slideId = currentSlide.id || `slide-${currentSlideIndex}`;+ const slideId = currentSlide.id || `slide-${currentSlideIndex + 1}`;pushImageVersion(slideId, imageUrl, 'generated');}} catch (e) {@@ -652,7 +771,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditconst handleAddSlideToChat = (slide: SlideData) => {if (onAddToChat) {- const slideId = slide.id || `slide-${currentSlideIndex}`;+ const slideId = slide.id || `slide-${currentSlideIndex + 1}`;const currentVersion = currentImageVersionId[slideId];const versions = imageVersions[slideId] || [];const imageUrl = currentVersion ? versions.find(v => v.id === currentVersion)?.url : generatedImages[slideId];@@ -660,64 +779,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit}};- const handleAddSelectedSlidesToChat = () => {- if (!onAddToChat) return;- const selected = activeSlides- .filter(s => selectedSlideIds[s.id] )- .map((slide) => {- const slideId = slide.id;- const currentVersion = currentImageVersionId[slideId];- const versions = imageVersions[slideId] || [];- const imageUrl = currentVersion ? versions.find(v => v.id === currentVersion)?.url : generatedImages[slideId];- return { ...slide, imageUrl };- });-- if (selected.length === 0) return;- onAddToChat(JSON.stringify({ slides: selected }, null, 2), `slides-selected.json`);- };-- const handleApplyBulkEdit = async () => {- if (!bulkEditText.trim() || isApplyingBulkEdit) return;- setIsApplyingBulkEdit(true);- try {- const routes = await pptService.routeSlideEdits(- activeSlides.map(s => ({ title: s.title, bullets: s.content || [] })),- bulkEditText- );-- const editTasks = routes.map((r) => async () => {- const idx = r.slideIndex;- const slide = activeSlides[idx];- if (!slide) return;-- const slideId = slide.id;- const versions = imageVersions[slideId] || [];- const currentVersion = currentImageVersionId[slideId];- const currentUrl = currentVersion ? versions.find(v => v.id === currentVersion)?.url : generatedImages[slideId];-- const page: PptPage = {- id: slideId,- title: slide.title,- content: slide.content || [],- description: slide.description- };-- const editedUrl = await pptService.editPageImage(page, r.instruction, currentUrl || undefined, templateImage || undefined);- if (editedUrl) {- pushImageVersion(slideId, editedUrl, 'edited', r.instruction);- }- });-- await runInParallel(editTasks, MODEL_CONCURRENCY);- setBulkEditOpen(false);- setBulkEditText("");- } catch (e) {- console.error("Bulk edit failed", e);- } finally {- setIsApplyingBulkEdit(false);- }- };-const handleDownloadPpt = async () => {try {const pages: PptPage[] = activeSlides.map(s => ({@@ -763,7 +824,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit};// Render Creation Wizard- if (activeSlides.length === 0 && (creationStep === 'idle' || creationStep === 'input')) {+ if (activeSlides.length === 0 && (creationStep === 'idle' || creationStep === 'input' || creationStep === 'done')) {const tabs = [{ id: 'idea', label: '想法' },{ id: 'outline', label: '大纲' },@@ -802,52 +863,42 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit</label><div className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(180px,1fr))]">- {/* Upload Card */}- <label 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 ${- selectedTemplatePath === "upload"- ? "border-blue-500 bg-blue-50/30 dark:bg-zinc-800/50"- : "border-zinc-200 dark:border-zinc-700 hover:border-blue-500 hover:bg-blue-50/30 dark:hover:bg-zinc-800/50"- }`}>- {uploadedTemplateImage ? (- <>- <img src={uploadedTemplateImage} className="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity" alt="Template" />- {selectedTemplatePath === "upload" && (- <div className="absolute top-2 left-2 rounded-full bg-blue-600 px-2 py-0.5 text-[10px] font-medium text-white shadow">- 已选择- </div>- )}- <div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">- <span className="text-white text-xs font-medium px-3 py-1 bg-black/50 rounded-full backdrop-blur-sm">更换图片</span>- </div>- </>- ) : (- <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">- <Upload className="w-5 h-5" />- </div>- <span className="text-xs font-medium">上传参考图</span>+ <label 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">+ <Upload className="w-5 h-5" /></div>- )}- <input type="file" accept="image/*" className="hidden" onChange={handleFileUpload} />+ <span className="text-xs font-medium">添加模板</span>+ </div>+ <input type="file" accept="image/*" multiple className="hidden" onChange={handleTemplateUploadInputChange} /></label>-- {/* Preset Templates */}- {AVAILABLE_TEMPLATES.map((t) => (- <div- key={t.path}- onClick={() => handleTemplateSelect(t.path)}+ {templates.map((t) => (+ <div+ key={t.id}+ onClick={() => void setTemplateFromItem(t)}className={`cursor-pointer border rounded-xl overflow-hidden relative aspect-video group transition-all duration-200 bg-zinc-100 dark:bg-zinc-900 ${- selectedTemplatePath === t.path+ selectedTemplateId === t.id? "border-blue-500 ring-2 ring-blue-500 shadow-md": "border-zinc-200 dark:border-zinc-700 hover:ring-2 hover:ring-blue-500 hover:shadow-md"}`}>- <img src={t.path} className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-105" alt={t.name} />- {selectedTemplatePath === t.path && (+ <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">已选择</div>)}+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ deleteTemplate(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="删除模板"+ >+ <X className="w-3.5 h-3.5" />+ </button><div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 to-transparent p-3 pt-8 opacity-0 group-hover:opacity-100 transition-opacity duration-200"><div className="text-white text-xs font-medium text-center">{t.name}</div></div>@@ -1127,12 +1178,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="flex items-center gap-4"><h2 className="font-semibold text-sm text-foreground">PPT 演示文稿</h2><div className="h-4 w-px bg-border"></div>- <label className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground cursor-pointer transition-colors">- <Upload className="w-3.5 h-3.5" />- <span>{templateImage ? "已上传模板" : "上传模板参考图"}</span>- <input type="file" accept="image/*" className="hidden" onChange={handleFileUpload} />- </label>- <div className="h-4 w-px bg-border"></div><buttononClick={() => setSlideshowOpen(true)}disabled={activeSlides.length === 0}@@ -1168,37 +1213,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit<div className="flex-1 flex overflow-hidden">{/* Thumbnails */}<div className="w-64 bg-zinc-50 dark:bg-zinc-900 border-r border-border overflow-y-auto p-4 space-y-4">- <div className="flex items-center gap-2">- <Button- variant="outline"- size="sm"- className="h-7 px-2 text-xs"- onClick={() => {- const next: Record<string, boolean> = {};- for (const s of activeSlides) next[s.id] = true;- setSelectedSlideIds(next);- }}- >- 全选- </Button>- <Button- variant="outline"- size="sm"- className="h-7 px-2 text-xs"- onClick={() => setSelectedSlideIds({})}- >- 清空- </Button>- <Button- variant="default"- size="sm"- className="h-7 px-2 text-xs ml-auto"- onClick={handleAddSelectedSlidesToChat}- disabled={Object.keys(selectedSlideIds).length === 0}- >- 加入对话- </Button>- </div>{activeSlides.map((slide, index) => {const hasGeneratedImage = generatedImages[slide.id || index];return (@@ -1213,24 +1227,18 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit}`}><div- className="absolute top-1 left-1 z-20 flex items-center gap-1 bg-white/90 dark:bg-zinc-900/80 rounded px-1.5 py-1 border border-border/50"+ className="absolute top-1 left-1 z-20"onClick={(e) => e.stopPropagation()}>- <input- type="checkbox"- checked={!!selectedSlideIds[slide.id]}- onChange={(e) => {- const checked = e.target.checked;- setSelectedSlideIds(prev => {- const next = { ...prev };- if (checked) next[slide.id] = true;- else delete next[slide.id];- return next;- });- }}- className="h-3 w-3"- />- <span className="text-[10px] text-muted-foreground">选中</span>+ <Button+ size="sm"+ variant="destructive"+ className="h-6 px-2 text-[10px] gap-1 shadow-sm opacity-0 group-hover:opacity-100 transition-opacity"+ onClick={() => handleAddSlideToChat(slide)}+ >+ <Presentation className="w-3 h-3" />+ 加入对话+ </Button></div>{/* Thumbnail Preview */}{hasGeneratedImage ? (@@ -1285,15 +1293,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit{isGeneratingImage ? <Loader2 className="w-3 h-3 mr-1 animate-spin" /> : null}重渲染本页</Button>- <Button- size="sm"- variant="outline"- className="h-7 px-2 text-xs"- onClick={() => setBulkEditOpen(true)}- disabled={activeSlides.length === 0}- >- 批量修改- </Button>{currentSlide && (imageVersions[currentSlide.id] || []).length > 0 && (<selectclassName="h-7 text-xs rounded-md border border-input bg-background px-2"@@ -1320,10 +1319,13 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit{currentSlide ? (<ContextMenu><ContextMenuTrigger className="outline-none">- <div className="relative w-full max-w-[1100px] aspect-[16/9] bg-white shadow-2xl rounded-sm overflow-hidden flex flex-col transition-transform duration-300">+ <div+ className="relative w-full max-w-[1100px] bg-white shadow-2xl rounded-sm overflow-hidden flex flex-col transition-transform duration-300"+ style={{ aspectRatio: "16/9" }}+ >{/* Display either generated image or DOM layout */}{currentSlideImage ? (- <img src={currentSlideImage} className="w-full h-full object-cover" alt="AI Generated Slide" />+ <img src={currentSlideImage} className="w-full h-full object-contain bg-white" alt="AI Generated Slide" />) : (<div className="w-full h-full p-12 flex flex-col relative">{/* Background Template */}@@ -1355,6 +1357,14 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit)}{/* Overlay Label if Generated */}+ {(isApplyingEdits || isGeneratingImage) && (+ <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>+ </div>+ </div>+ )}</div></ContextMenuTrigger><ContextMenuContent>@@ -1374,105 +1384,86 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit</div><Dialog open={slideshowOpen} onOpenChange={setSlideshowOpen}>- <DialogContent className="max-w-none w-screen h-screen p-0 bg-black border-none">- <div className="w-full h-full flex flex-col">- <div className="h-14 px-4 flex items-center justify-between text-white/90">- <div className="text-sm">- {activeSlides.length > 0 ? `第 ${slideshowIndex + 1} / ${activeSlides.length} 页` : ""}- </div>- <div className="flex items-center gap-2">- <Button- variant="ghost"- size="sm"- className="text-white hover:text-white hover:bg-white/10"- onClick={() => setSlideshowAuto((v) => !v)}- >- {slideshowAuto ? "暂停" : "自动播放"}- </Button>- <Button- variant="ghost"- size="sm"- className="text-white hover:text-white hover:bg-white/10"- onClick={() => setSlideshowOpen(false)}- >- 退出- </Button>- </div>+ <DialogContent className="inset-0 left-0 top-0 translate-x-0 translate-y-0 w-screen h-screen max-w-none sm:max-w-none rounded-none p-0 bg-black/95 border-none flex flex-col">+ <div className="h-16 px-6 flex items-center justify-between text-white/90 bg-black/50 backdrop-blur-sm z-50">+ <div className="text-sm font-medium">+ {activeSlides.length > 0 ? `第 ${slideshowIndex + 1} / ${activeSlides.length} 页` : ""}</div>- <div className="flex-1 flex items-center justify-center px-6 pb-6">- {activeSlides[slideshowIndex] ? (- <div className="w-full max-w-[1400px] aspect-[16/9] bg-white shadow-2xl overflow-hidden">+ <div className="flex items-center gap-4">+ <Button+ variant="ghost"+ size="sm"+ className="text-white hover:text-white hover:bg-white/10 gap-2"+ onClick={() => setSlideshowOpen(false)}+ >+ <X className="w-4 h-4" />+ 退出+ </Button>+ </div>+ </div>++ <div className="flex-1 flex items-center justify-center p-8 overflow-hidden bg-black/90">+ {activeSlides[slideshowIndex] ? (+ <div className="relative w-full h-full flex items-center justify-center">+ <div+ className="relative bg-white shadow-2xl overflow-hidden rounded-lg mx-auto"+ style={{+ width: getSlideshowDimensions().width,+ height: getSlideshowDimensions().height+ }}+ >{getSlideImageUrl(activeSlides[slideshowIndex].id) ? (<imgsrc={getSlideImageUrl(activeSlides[slideshowIndex].id)}- className="w-full h-full object-cover"+ className="w-full h-full object-contain bg-black"alt="Slide"/>) : (- <div className="w-full h-full p-12 flex flex-col">- <h1 className="text-4xl font-bold mb-8 text-zinc-900 border-b-4 border-blue-600 pb-4 w-fit pr-12">+ <div className="w-full h-full p-16 flex flex-col">+ <h1 className="text-5xl font-bold mb-12 text-zinc-900 border-b-4 border-blue-600 pb-6 w-fit pr-16">{activeSlides[slideshowIndex].title}</h1>- <div className="flex-1 space-y-6">+ <div className="flex-1 space-y-8">{(activeSlides[slideshowIndex].content || []).map((point, i) => (- <div key={i} className="flex gap-4 text-2xl text-zinc-700 leading-relaxed items-start">+ <div key={i} className="flex gap-6 text-3xl text-zinc-700 leading-relaxed items-start"><span className="text-blue-600 mt-2">•</span><span>{point}</span></div>))}</div>- <div className="mt-auto pt-8 flex justify-between text-sm text-zinc-400 border-t border-zinc-100">+ <div className="mt-auto pt-8 flex justify-between text-lg text-zinc-400 border-t border-zinc-100"><span>Generated by Unified AI Workspace</span><span>{slideshowIndex + 1}</span></div></div>)}</div>- ) : null}- </div>- <div className="h-16 px-4 flex items-center justify-center gap-3">- <Button- variant="outline"- className="bg-white/10 border-white/20 text-white hover:bg-white/15"- onClick={() => setSlideshowIndex((v) => (v - 1 + activeSlides.length) % activeSlides.length)}- disabled={activeSlides.length <= 1}- >- 上一页- </Button>- <Button- variant="outline"- className="bg-white/10 border-white/20 text-white hover:bg-white/15"- onClick={() => setSlideshowIndex((v) => (v + 1) % activeSlides.length)}- disabled={activeSlides.length <= 1}- >- 下一页- </Button>- </div>+ </div>+ ) : null}</div>- </DialogContent>- </Dialog>- <Dialog open={bulkEditOpen} onOpenChange={setBulkEditOpen}>- <DialogContent className="sm:max-w-[720px]">- <DialogHeader>- <DialogTitle>批量修改(智能拆分到对应幻灯片)</DialogTitle>- </DialogHeader>- <div className="space-y-3">- <Textarea- value={bulkEditText}- onChange={(e) => setBulkEditText(e.target.value)}- placeholder="把你对多张幻灯片的修改意见一次性写在这里,例如:第1页标题更简洁;第3页配图换成更科技感的插画;结尾页增加总结..."- className="min-h-[180px]"- />- <div className="flex justify-end gap-2">- <Button variant="outline" onClick={() => setBulkEditOpen(false)} disabled={isApplyingBulkEdit}>- 取消- </Button>- <Button onClick={handleApplyBulkEdit} disabled={!bulkEditText.trim() || isApplyingBulkEdit}>- {isApplyingBulkEdit ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}- 开始应用- </Button>+ <div className="h-20 px-4 flex items-center justify-center gap-8 pb-4">+ <Button+ variant="outline"+ size="lg"+ className="bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-white rounded-full w-12 h-12 p-0"+ onClick={() => setSlideshowIndex((v) => (v - 1 + activeSlides.length) % activeSlides.length)}+ disabled={activeSlides.length <= 1}+ >+ <ArrowLeft className="w-6 h-6" />+ </Button>+ <div className="text-white/50 text-sm font-medium">+ {slideshowIndex + 1} / {activeSlides.length}</div>+ <Button+ variant="outline"+ size="lg"+ className="bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-white rounded-full w-12 h-12 p-0"+ onClick={() => setSlideshowIndex((v) => (v + 1) % activeSlides.length)}+ disabled={activeSlides.length <= 1}+ >+ <ArrowRight className="w-6 h-6" />+ </Button></div></DialogContent></Dialog>diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.tsindex 7d2be50..c3b5afb 100644--- a/src/lib/ai-client.ts+++ b/src/lib/ai-client.ts@@ -46,14 +46,38 @@ function createLimiter(max: number) {item.signal.removeEventListener("abort", item.onAbort);item.onAbort = undefined;}+ let finished = false;+ let abortHandler: (() => void) | null = null;- item- .run()- .then(item.resolve, item.reject)- .finally(() => {- active -= 1;- pump();- });+ const finish = () => {+ if (finished) return;+ finished = true;+ if (item.signal && abortHandler) {+ item.signal.removeEventListener("abort", abortHandler as any);+ }+ active -= 1;+ pump();+ };++ if (item.signal) {+ abortHandler = () => {+ const err = Object.assign(new Error("Aborted"), { name: "AbortError" });+ item.reject(err);+ finish();+ };+ item.signal.addEventListener("abort", abortHandler, { once: true });+ }++ item.run().then(+ (value) => {+ item.resolve(value);+ finish();+ },+ (reason) => {+ item.reject(reason);+ finish();+ }+ );}};@@ -87,7 +111,15 @@ export function getAIConfig(): AIConfig {if (typeof window === 'undefined') return DEFAULT_CONFIG;const stored = localStorage.getItem(STORAGE_KEY);if (stored) {- return { ...DEFAULT_CONFIG, ...JSON.parse(stored) };+ try {+ return { ...DEFAULT_CONFIG, ...JSON.parse(stored) };+ } catch {+ try {+ localStorage.removeItem(STORAGE_KEY);+ } catch {+ }+ return DEFAULT_CONFIG;+ }}return DEFAULT_CONFIG;}@@ -145,12 +177,9 @@ export async function streamChatMessage(onChunk(fullContent);}}- console.log("=== AI Chat Response ===");- console.log(fullContent);- console.log("========================");return fullContent;} catch (error) {- if ((error as any)?.name === "AbortError") {+ if ((error as any)?.name === "AbortError" || (error as any)?.name === "APIUserAbortError") {throw error;}console.error("Chat Stream Error:", error);@@ -160,8 +189,58 @@ export async function streamChatMessage(}// Simple non-stream wrapper-export async function generateChatMessage(messages: ChatMessage[], model?: string) {- return streamChatMessage(messages, () => {}, model);+export type GenerateChatMessageOptions = {+ signal?: AbortSignal;+ timeoutMs?: number;+};++export async function generateChatMessage(messages: ChatMessage[], model?: string, options?: GenerateChatMessageOptions) {+ const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : 0;+ const externalSignal = options?.signal;++ const controller = typeof AbortController !== "undefined" ? new AbortController() : null;+ const mergedSignal = controller?.signal || externalSignal;+ let timeoutId: any = null;++ if (controller && externalSignal) {+ if (externalSignal.aborted) controller.abort();+ else externalSignal.addEventListener("abort", () => controller.abort(), { once: true });+ }++ if (controller && timeoutMs > 0) {+ timeoutId = setTimeout(() => controller.abort(), timeoutMs);+ }++ try {+ return await limitModelCall(async () => {+ const config = getAIConfig();+ const client = getClient();++ if (!config.apiKey) {+ throw new Error("请先在设置中配置 API Key");+ }++ try {+ const resp = await client.chat.completions.create(+ {+ model: model || config.chatModel,+ messages,+ stream: false,+ },+ mergedSignal ? ({ signal: mergedSignal } as any) : undefined+ );+ return resp.choices?.[0]?.message?.content || "";+ } catch (error) {+ if ((error as any)?.name === "AbortError" || (error as any)?.name === "APIUserAbortError") {+ throw error;+ }+ console.error("Chat Error:", error);+ throw error;+ }+ }, mergedSignal);+ } finally {+ if (timeoutId) clearTimeout(timeoutId);+ }}// Legacy non-stream function (kept for compatibility if needed)@@ -172,7 +251,8 @@ export async function sendChatMessage(messages: ChatMessage[]) {// Image Generation Clientexport interface ImageGenerationRequest {prompt: string;- referenceImageUrl?: string; // For image-to-image+ referenceImageUrl?: string; // Main reference (kept for backward compatibility)+ additionalReferenceImageUrls?: string[]; // Additional references}// Helper to validate and clean URL@@ -184,6 +264,42 @@ function cleanUrl(url: string) {return null;}+function dataUrlToObjectUrl(dataUrl: string) {+ if (typeof window === "undefined") return null;+ if (!dataUrl.startsWith("data:image")) return null;+ const comma = dataUrl.indexOf(",");+ if (comma < 0) return null;+ const header = dataUrl.slice(0, comma);+ const data = dataUrl.slice(comma + 1);+ const mimeMatch = header.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64$/);+ const mime = mimeMatch?.[1] || "image/png";+ const binary = atob(data);+ const bytes = new Uint8Array(binary.length);+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);+ const blob = new Blob([bytes], { type: mime });+ return URL.createObjectURL(blob);+}++async function objectUrlToDataUrl(objectUrl: string) {+ if (typeof window === "undefined") return null;+ if (!objectUrl || !objectUrl.startsWith("blob:")) return null;+ try {+ const resp = await fetch(objectUrl);+ const blob = await resp.blob();+ return await new Promise<string | null>((resolve) => {+ const reader = new FileReader();+ reader.onerror = () => resolve(null);+ reader.onloadend = () => {+ const result = reader.result;+ resolve(typeof result === "string" ? result : null);+ };+ reader.readAsDataURL(blob);+ });+ } catch {+ return null;+ }+}+function extractImageUrlFromContent(messageContent: any) {if (Array.isArray(messageContent)) {const imagePart = messageContent.find((part: any) => part.type === 'image_url');@@ -219,10 +335,6 @@ function extractImageUrlFromContent(messageContent: any) {}function parseAIResponse(result: any) {- console.log("=== AI Image Response (Parsed) ===");- console.log(JSON.stringify(result, null, 2));- console.log("==================================");-if (result.error) {throw new Error(result.error.message || "API Error");}@@ -242,6 +354,25 @@ export async function generateImage(request: ImageGenerationRequest, signal?: Abthrow new Error("请先在设置中配置 API Key");}+ let referenceImageUrl = request.referenceImageUrl;+ if (referenceImageUrl && referenceImageUrl.startsWith("blob:")) {+ const dataUrl = await objectUrlToDataUrl(referenceImageUrl);+ if (dataUrl) referenceImageUrl = dataUrl;+ else referenceImageUrl = undefined;+ }++ const additionalUrls: string[] = [];+ if (request.additionalReferenceImageUrls && request.additionalReferenceImageUrls.length > 0) {+ for (const url of request.additionalReferenceImageUrls) {+ if (url.startsWith("blob:")) {+ const dataUrl = await objectUrlToDataUrl(url);+ if (dataUrl) additionalUrls.push(dataUrl);+ } else {+ additionalUrls.push(url);+ }+ }+ }+const myHeaders = new Headers();myHeaders.append("Authorization", `Bearer ${config.apiKey}`);myHeaders.append("Content-Type", "application/json");@@ -253,21 +384,30 @@ export async function generateImage(request: ImageGenerationRequest, signal?: Ab}];- if (request.referenceImageUrl) {+ if (referenceImageUrl) {content.push({"type": "image_url","image_url": {- "url": request.referenceImageUrl+ "url": referenceImageUrl}});}++ for (const url of additionalUrls) {+ content.push({+ "type": "image_url",+ "image_url": {+ "url": url+ }+ });+ }const raw = JSON.stringify({"model": config.imageModel,"messages": [{"role": "user",- "content": request.referenceImageUrl ? content : request.prompt+ "content": referenceImageUrl || additionalUrls.length > 0 ? content : request.prompt}],"stream": false@@ -289,7 +429,15 @@ export async function generateImage(request: ImageGenerationRequest, signal?: Ab}const result = await response.json();- return parseAIResponse(result);+ const url = parseAIResponse(result);+ if (url && url.startsWith("data:image")) {+ try {+ const objectUrl = dataUrlToObjectUrl(url);+ if (objectUrl) return objectUrl;+ } catch {+ }+ }+ return url;} catch (error) {console.error("Image Gen Error:", error);throw error;diff --git a/src/lib/cad-tasks.ts b/src/lib/cad-tasks.tsnew file mode 100644index 0000000..0b71e67--- /dev/null+++ b/src/lib/cad-tasks.ts@@ -0,0 +1,62 @@+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)) {+ out = out.split(`{{${k}}}`).join(String(v ?? ""));+ }+ return out;+}++export function buildCadBomPrompt(args: { planJson: string; svg2d: string }) {+ return applyTemplate(cadBomPromptTemplate, {+ planJson: String(args.planJson || ""),+ svg2d: String(args.svg2d || ""),+ });+}++export function buildCadImagesPrompt(args: { planJson: string; svg2d: string }) {+ return applyTemplate(cadImagesPromptTemplate, {+ planJson: String(args.planJson || ""),+ svg2d: String(args.svg2d || ""),+ });+}++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");+}++export function buildCadBomMessages(args: {+ systemContent: string;+ planJson: string;+ svg2d: string;+}): ChatMessage[] {+ return [+ { role: "system", content: args.systemContent },+ { role: "user", content: buildCadBomPrompt({ planJson: args.planJson, svg2d: args.svg2d }) },+ ];+}++export function buildCadImagesMessages(args: {+ systemContent: string;+ planJson: string;+ svg2d: string;+}): ChatMessage[] {+ return [+ { role: "system", content: args.systemContent },+ { role: "user", content: buildCadImagesPrompt({ planJson: args.planJson, svg2d: args.svg2d }) },+ ];+}+diff --git a/src/lib/ppt-prompts.ts b/src/lib/ppt-prompts.tsindex 8ad45e7..2035d26 100644--- a/src/lib/ppt-prompts.ts+++ b/src/lib/ppt-prompts.ts@@ -77,7 +77,7 @@ You can organize the content in two ways:Choose the format that best fits the content. Use parts when the PPT has clear major sections.-The user's request: ${ideaPrompt}. Now generate the outline, don't include any other text.+The user's request: ${ideaPrompt}. Now generate the outline as valid JSON only. Do not wrap in markdown code blocks. Do not include any other text.${getLanguageInstruction(language)}`;}diff --git a/src/lib/ppt-service.ts b/src/lib/ppt-service.tsindex c770d46..aa4cfb5 100644--- a/src/lib/ppt-service.ts+++ b/src/lib/ppt-service.ts@@ -16,6 +16,69 @@ export interface SlideEditRoutingItem {instruction: string;}+const PPT_OUTLINE_SYSTEM = `You are a presentation outline generator.+Return ONLY JSON. Do not wrap in markdown code blocks. Do not include any extra text.`;++const parseJsonLoose = (text: string) => {+ const raw = String(text || "").trim();+ if (!raw) throw new Error("Empty AI response");++ const tryParse = (s: string) => {+ try {+ return JSON.parse(s);+ } catch {+ return null;+ }+ };++ const direct = tryParse(raw);+ if (direct) return direct;++ const jsonBlock = raw.match(/```json\s*([\s\S]*?)\s*```/i);+ if (jsonBlock?.[1]) {+ const inner = String(jsonBlock[1]).trim();+ const parsed = tryParse(inner);+ if (parsed) return parsed;+ }++ const findBalanced = (openChar: "[" | "{", closeChar: "]" | "}") => {+ const start = raw.indexOf(openChar);+ if (start < 0) return null;+ let depth = 0;+ for (let i = start; i < raw.length; i += 1) {+ const ch = raw[i];+ if (ch === openChar) depth += 1;+ if (ch === closeChar) depth -= 1;+ if (depth === 0) {+ const candidate = raw.slice(start, i + 1);+ const parsed = tryParse(candidate);+ if (parsed) return parsed;+ return null;+ }+ }+ return null;+ };++ const arr = findBalanced("[", "]");+ if (arr) return arr;+ const obj = findBalanced("{", "}");+ if (obj) return obj;++ throw new Error("Failed to parse AI JSON");+};++const normalizePages = (value: any): PptPage[] => {+ const asArray = Array.isArray(value) ? value : Array.isArray(value?.slides) ? value.slides : null;+ if (!asArray) return [];+ return asArray+ .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 : ""+ }))+ .filter((p: PptPage) => p.title.trim().length > 0);+};+const urlToDataUri = async (url: string): Promise<string> => {if (!url) return "";if (url.startsWith("data:")) return url;@@ -48,26 +111,31 @@ const downloadBlob = (data: Uint8Array | ArrayBuffer, mime: string, filename: stexport const pptService = {// 1. Generate OutlinegenerateOutline: async (topic: string): Promise<PptPage[]> => {- const prompt = `Create a presentation outline for the topic: "${topic}".- Return ONLY a JSON array of objects with "title" (string) and "content" (array of strings, bullet points) and "description" (string, visual description for image generation).- Example:- [- {"title": "Introduction", "content": ["Point 1", "Point 2"], "description": "A futuristic cityscape"},- ...- ]`;-- const response = await generateChatMessage([{ role: 'user', content: prompt }]);-+ 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"},+ ...+]+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.`;++ const response = await generateChatMessage([+ { role: "system", content: PPT_OUTLINE_SYSTEM },+ { role: "user", content: prompt }+ ], undefined, { timeoutMs: 120000 });+try {- // Extract JSON- const match = response.match(/\[[\s\S]*\]/);- if (match) {- return JSON.parse(match[0]);- }- return JSON.parse(response);+ const parsed = parseJsonLoose(response);+ const pages = normalizePages(parsed);+ if (pages.length === 0) throw new Error("No outline parsed from AI response");+ return pages;} catch (e) {console.error("Failed to parse outline", e);- throw new Error("Failed to parse AI response");+ throw e instanceof Error ? e : new Error("Failed to parse AI response");}},@@ -87,16 +155,20 @@ 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.-- Do not include markdown or extra text outside JSON.`;+- Output ONLY JSON.`;- const response = await generateChatMessage([{ role: 'user', content: prompt }]);try {- const match = response.match(/\[[\s\S]*\]/);- if (match) return JSON.parse(match[0]);- return JSON.parse(response);+ const response = await generateChatMessage([+ { role: "system", content: PPT_OUTLINE_SYSTEM },+ { role: "user", content: prompt }+ ], undefined, { timeoutMs: 120000 });+ const parsed = parseJsonLoose(response);+ const pages = normalizePages(parsed);+ if (pages.length === 0) throw new Error("No slides parsed from AI response");+ return pages;} catch (e) {console.error("Failed to parse slides from description", e);- throw new Error("Failed to parse AI response");+ throw e instanceof Error ? e : new Error("Failed to parse AI response");}},@@ -150,6 +222,7 @@ Title: ${page.title}Bullets: ${(page.content || []).join(" | ")}Visual style: modern, professional, clean layout, high contrast, no watermarks.Scene/subject: ${page.description || page.title}+Format: Landscape 16:9 aspect ratio.Rules:- Avoid large paragraphs of text in the image.- Prefer diagrammatic/illustrative composition matching the bullets.@@ -161,13 +234,14 @@ Rules:});},- editPageImage: async (page: PptPage, instruction: string, referenceImageUrl?: string, templateImageUrl?: string) => {+ editPageImage: async (page: PptPage, instruction: string, referenceImageUrl?: string, templateImageUrl?: string, additionalImages?: string[]) => {const prompt = `Edit the slide image based on instruction.Slide title: ${page.title}Bullets: ${(page.content || []).join(" | ")}Original visual description: ${page.description || ""}Instruction: ${instruction}Style: keep consistent with the template, professional, clean.+Format: Landscape 16:9 aspect ratio.Rules:- Keep layout readable.- Do not add watermark.@@ -176,7 +250,8 @@ Rules:const ref = referenceImageUrl || templateImageUrl;return await generateImage({prompt,- referenceImageUrl: ref+ referenceImageUrl: ref,+ additionalReferenceImageUrls: additionalImages});},diff --git a/src/lib/system-prompt.ts b/src/lib/system-prompt.tsindex 22b086e..aca9490 100644--- a/src/lib/system-prompt.ts+++ b/src/lib/system-prompt.ts@@ -1,38 +1 @@-export const DRAWIO_SYSTEM_PROMPT = `-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.--## Capabilities-- Generate valid, well-formed XML strings for draw.io diagrams.-- Create professional flowcharts, mind maps, entity diagrams, and technical illustrations.-- Optimize element positioning to prevent overlapping and maintain readability.--## Critical Rules for XML Generation-1. **Always use the following basic structure:**-\`\`\`xml-<mxGraphModel>- <root>- <mxCell id="0"/>- <mxCell id="1" parent="0"/>- <!-- Your cells go here, starting with id="2" -->- </root>-</mxGraphModel>-\`\`\`-2. **All mxCell elements must be DIRECT children of <root>**.-3. **Use unique sequential IDs** for all cells (start from "2").-4. **Set parent="1"** for top-level shapes.-5. **Styles**:- - Shapes: \`rounded=1;whiteSpace=wrap;html=1;fillColor=#dae8fc;strokeColor=#6c8ebf;\`- - Edges: \`edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;entryX=0.5;entryY=0;entryDx=0;entryDy=0;\`-6. **Positioning**:- - Use \`x\`, \`y\`, \`width\`, \`height\` in \`<mxGeometry>\`.- - Ensure nodes are spaced out to avoid overlap.--## Output Format-When asked to create a diagram, **you must output the raw XML code inside a markdown code block labeled "xml"**.-Example:-\`\`\`xml-<mxGraphModel>...</mxGraphModel>-\`\`\`-Do not include any other text explanations if you are generating the XML, just the code block.-`;+export { DRAWIO_SYSTEM_PROMPT } from "@/lib/system-prompts";diff --git a/src/lib/system-prompts.ts b/src/lib/system-prompts.tsindex 30a1924..427e5ba 100644--- a/src/lib/system-prompts.ts+++ b/src/lib/system-prompts.ts@@ -1,95 +1,7 @@-export const DRAWIO_SYSTEM_PROMPT = `-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.+import drawioPrompt from "../../agent/flow/system.md?raw";+import cadPrompt from "../../agent/cad/system.md?raw";+import pptPrompt from "../../agent/ppt/system.md?raw";-## 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>-\`\`\`-`;--export const CAD_SYSTEM_PROMPT = `-You are an expert CAD assistant.-Your task is to help users create 2D plans and turn them into real 3D models using FreeCAD Python.--## Rules:-1. For 2D visualization, return valid SVG code with a viewBox and appropriate dimensions.-2. Use standard SVG shapes (rect, circle, path, line, polyline).-3. If the user provides draw.io XML (mxGraphModel/mxfile) as context, you may use it as the authoritative 2D plan source.-4. When the user asks for a real 3D model, output runnable FreeCAD Python that creates solids (faces + extrusions), with realistic Z height (avoid flat models).-5. Default wall height: 3000 mm. Default wall thickness: 200 mm unless specified.--## Response Format:-Always wrap your SVG code in a markdown code block:-\`\`\`svg-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 600">- ...-</svg>-\`\`\`--If you provide FreeCAD Python code:-\`\`\`python-import FreeCAD-...-\`\`\`-`;--export const PPT_SYSTEM_PROMPT = `-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.--## JSON Structure:-You must return a JSON object with a "slides" array. Each slide has a "title", "content" (bullet points), and "layout".--Example Format:-\`\`\`json-{- "theme": "modern",- "slides": [- {- "id": "slide-1",- "title": "Presentation Title",- "content": [- "Point 1",- "Point 2"- ],- "note": "Speaker notes here"- }- ]-}-\`\`\`--## 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, include "imageEditInstruction" for each edited slide. This instruction will be sent to an image model to update the slide image.-5. Always output ONLY one markdown code block:-\`\`\`json-{- "type": "ppt_edit",- "slides": [- {- "id": "slide-1",- "title": "...",- "content": ["..."],- "description": "...",- "imageEditInstruction": "..."- }- ]-}-\`\`\`-`;+export const DRAWIO_SYSTEM_PROMPT = drawioPrompt;+export const CAD_SYSTEM_PROMPT = cadPrompt;+export const PPT_SYSTEM_PROMPT = pptPrompt;diff --git a/src/pages/LandingPage.tsx b/src/pages/LandingPage.tsxindex 82423db..f68e9a6 100644--- a/src/pages/LandingPage.tsx+++ b/src/pages/LandingPage.tsx@@ -3,8 +3,6 @@ import { motion, AnimatePresence, animate, useMotionValue, useTransform } from '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 * as THREE from 'three';-import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';interface LandingPageProps {onStart: () => void;@@ -120,7 +118,7 @@ export function LandingPage({ onStart }: LandingPageProps) {<p className="text-xl md:text-2xl text-gray-400 max-w-2xl mx-auto font-light leading-relaxed font-artistic">无需繁琐操作,AI 赋予你“神笔马良”般的能力。<br/>- 从逻辑图表到三维空间,只在弹指之间。+ 从逻辑图表到可交付成果,只在弹指之间。</p><div className="pt-8">@@ -177,11 +175,11 @@ export function LandingPage({ onStart }: LandingPageProps) {</div><div><div className="text-white/90 font-semibold">智能室内设计</div>- <div className="text-white/45 text-sm mt-0.5">输入需求 → 2D 平面 → 3D 立体</div>+ <div className="text-white/45 text-sm mt-0.5">输入需求 → 2D 平面 → 装修图 / 物料清单</div></div></div><div className="mt-2 text-xs text-white/55 space-y-1">- <div>· 先 2D 后 3D:方案落地更快</div>+ <div>· 先 2D 后 装修图/物料:方案落地更快</div><div>· 风格可控:一键切换风格</div></div></button>@@ -282,7 +280,7 @@ function DemoFlowchart() {// Sequence controllerReact.useEffect(() => {- let timeouts: NodeJS.Timeout[] = [];+ const timeouts: NodeJS.Timeout[] = [];const runSequence = () => {setStep(0);@@ -618,7 +616,7 @@ function DemoCAD() {const [isGenerating, setIsGenerating] = useState(false);React.useEffect(() => {- let timeouts: NodeJS.Timeout[] = [];+ const timeouts: NodeJS.Timeout[] = [];const runSequence = () => {setStep(0);@@ -632,10 +630,10 @@ function DemoCAD() {// 4s: Show 2D Plan (Duration 3s)timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(1); }, 4000));- // 7s: Start Generating 3D (Duration 2s)+ // 7s: Start Generating BOM (Duration 2s)timeouts.push(setTimeout(() => setIsGenerating(true), 7000));- // 9s: Show 3D View (Duration 3s)+ // 9s: Show BOM (Duration 3s)timeouts.push(setTimeout(() => { setIsGenerating(false); setStep(2); }, 9000));// 12s: Start Generating Render (Duration 2s)@@ -655,8 +653,8 @@ function DemoCAD() {// 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: "光线追踪 · 风格化处理 · 8K 级渲染" };+ if (step === 1) return { title: "正在生成物料清单...", sub: "空间拆解 · 材料归类 · 数量估算" };+ if (step === 2) return { title: "正在渲染装修效果...", sub: "风格匹配 · 材质建议 · 灯光氛围" };return { title: "处理中...", sub: "请稍候" };};@@ -704,10 +702,9 @@ function DemoCAD() {</AnimatePresence><div className={`transition-all duration-1000 w-full h-full flex items-center justify-center ${(step === 0 || isGenerating) ? 'opacity-20 blur-sm' : 'opacity-100'}`}>- <div className="perspective-[1200px] w-full h-full flex items-center justify-center">+ <div className="w-full h-full flex items-center justify-center"><motion.divclassName="relative w-[720px] h-[540px] bg-zinc-800/80 border-4 border-white/20 shadow-2xl"- style={{ transformStyle: "preserve-3d" }}initial={{ rotateX: 0, rotateZ: 0 }}animate={step >= 2 ? { rotateX: 0, rotateZ: 0, scale: 1 } : { rotateX: 0, rotateZ: 0, scale: 1 }}transition={{ duration: 1.5, ease: "easeInOut" }}@@ -727,63 +724,9 @@ function DemoCAD() {)}-function CadBox3D({- is3d,- x,- y,- w,- h,- height,- topClassName,- sideClassName,- borderClassName,- roundedClassName-}: {- is3d: boolean;- x: number;- y: number;- w: number;- h: number;- height: number;- topClassName: string;- sideClassName: string;- borderClassName: string;- roundedClassName?: string;-}) {- return (- <div className="absolute" style={{ left: x, top: y, width: w, height: h, transformStyle: "preserve-3d" as any }}>- <motion.div- className={`absolute inset-0 ${topClassName} ${borderClassName} ${roundedClassName ?? ""}`}- style={{ backfaceVisibility: "hidden" }}- animate={is3d ? { z: height } : { z: 0 }}- />- <motion.div- className={`absolute bottom-0 left-0 w-full ${sideClassName} ${borderClassName} origin-bottom ${roundedClassName ?? ""}`}- style={{ backfaceVisibility: "hidden" }}- animate={is3d ? { height, rotateX: -90 } : { height: 0 }}- />- <motion.div- className={`absolute top-0 left-0 w-full ${sideClassName} ${borderClassName} origin-top ${roundedClassName ?? ""}`}- style={{ backfaceVisibility: "hidden" }}- animate={is3d ? { height, rotateX: 90 } : { height: 0 }}- />- <motion.div- className={`absolute top-0 right-0 h-full ${sideClassName} ${borderClassName} origin-right ${roundedClassName ?? ""}`}- style={{ backfaceVisibility: "hidden" }}- animate={is3d ? { width: height, rotateY: 90 } : { width: 0 }}- />- <motion.div- className={`absolute top-0 left-0 h-full ${sideClassName} ${borderClassName} origin-left ${roundedClassName ?? ""}`}- style={{ backfaceVisibility: "hidden" }}- animate={is3d ? { width: height, rotateY: -90 } : { width: 0 }}- />- </div>- );-}-function CadPlan({ step }: { step: number }) {if (step === 1) return <CadPlan2D />;- if (step === 2) return <CadPlan3D />;+ if (step === 2) return <CadBomResult />;if (step === 3) return <CadRenderResult />;return null;}@@ -933,12 +876,38 @@ function CadPlan2D() {);}-function CadPlan3D() {+function CadBomResult() {return (- <div className="absolute inset-4 rounded-2xl border border-white/10 bg-black/25 overflow-hidden">- <div className="absolute inset-0 flex">- <CadThreeViewport />- {/* Info Panel Removed as per request */}+ <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-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>+ <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: "套" }+ ].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>+ <div className="col-span-2">{r.n}</div>+ <div className="text-black/55">{r.s}</div>+ <div className="text-right font-mono">{r.q}</div>+ <div className="text-right text-black/55">{r.u}</div>+ </div>+ ))}+ </div></div></div>);@@ -989,470 +958,6 @@ function CadRenderResult() {)}-function CadThreeViewport() {- const hostRef = React.useRef<HTMLDivElement | null>(null);-- React.useEffect(() => {- const host = hostRef.current;- if (!host) return;-- // --- TEXTURE GENERATION HELPERS ---- // Generates a high-quality wood floor texture using Canvas API- const createWoodTexture = () => {- const canvas = document.createElement('canvas');- canvas.width = 1024;- canvas.height = 1024;- const ctx = canvas.getContext('2d');- if (!ctx) return new THREE.Texture();-- // Base wood color- ctx.fillStyle = '#e8dcca';- ctx.fillRect(0, 0, 1024, 1024);-- // Wood grain noise- for (let i = 0; i < 4000; i++) {- ctx.fillStyle = Math.random() > 0.5 ? '#d4c5b0' : '#f0e6d6';- ctx.globalAlpha = 0.15;- const x = Math.random() * 1024;- const y = Math.random() * 1024;- const w = Math.random() * 200 + 50;- const h = Math.random() * 4 + 1;- ctx.fillRect(x, y, w, h);- }-- // Plank lines- ctx.globalAlpha = 0.6;- ctx.strokeStyle = '#cbbba8';- ctx.lineWidth = 2;- const plankW = 120;- const plankH = 600;-- for (let x = 0; x <= 1024; x += plankW) {- ctx.beginPath();- ctx.moveTo(x, 0);- ctx.lineTo(x, 1024);- ctx.stroke();- }-- // Staggered horizontal joints- for (let x = 0; x <= 1024; x += plankW) {- const offset = (x / plankW) % 2 === 0 ? 0 : plankH / 2;- for (let y = offset; y <= 1024; y += plankH) {- ctx.beginPath();- ctx.moveTo(x, y);- ctx.lineTo(x + plankW, y);- ctx.stroke();- }- }-- const texture = new THREE.CanvasTexture(canvas);- texture.wrapS = THREE.RepeatWrapping;- texture.wrapT = THREE.RepeatWrapping;- // Scale texture to look realistic on the large floor- texture.repeat.set(4, 4);- return texture;- };-- // Generates a subtle stucco/paint texture for walls- const createWallTexture = () => {- const canvas = document.createElement('canvas');- canvas.width = 512;- canvas.height = 512;- const ctx = canvas.getContext('2d');- if (!ctx) return new THREE.Texture();-- // Base paint color- ctx.fillStyle = '#f5f5f5';- ctx.fillRect(0, 0, 512, 512);-- // Noise for "Latex Paint" bumpiness- for (let i = 0; i < 10000; i++) {- ctx.fillStyle = Math.random() > 0.5 ? '#ffffff' : '#eeeeee';- ctx.globalAlpha = 0.08;- ctx.fillRect(Math.random() * 512, Math.random() * 512, 2, 2);- }-- const texture = new THREE.CanvasTexture(canvas);- texture.wrapS = THREE.RepeatWrapping;- texture.wrapT = THREE.RepeatWrapping;- texture.repeat.set(2, 2);- return texture;- };-- // --- SCENE SETUP ---- const scene = new THREE.Scene();- // Use a null background to let the CSS gradient shine through, or a very dark architectural grey- // User complained about "White Screen", so we keep it transparent or dark.- scene.background = null;-- const camera = new THREE.PerspectiveCamera(45, host.clientWidth / host.clientHeight, 0.1, 1000);- // Architectural isometric-ish view- camera.position.set(8, 12, 12);- camera.lookAt(0, 0, 0);-- const renderer = new THREE.WebGLRenderer({- antialias: true,- alpha: true,- preserveDrawingBuffer: true,- powerPreference: "high-performance"- });- renderer.setPixelRatio(Math.min(2, window.devicePixelRatio || 1));- renderer.setSize(host.clientWidth, host.clientHeight);- renderer.useLegacyLights = false;-- // Re-enable shadows for realism, but keep map size reasonable- renderer.shadowMap.enabled = true;- renderer.shadowMap.type = THREE.PCFSoftShadowMap;- renderer.toneMapping = THREE.ACESFilmicToneMapping;- renderer.toneMappingExposure = 1.0;-- host.appendChild(renderer.domElement);-- const controls = new OrbitControls(camera, renderer.domElement);- controls.enableDamping = true;- controls.dampingFactor = 0.05;- controls.maxPolarAngle = Math.PI / 2 - 0.1; // Prevent going below ground- controls.target.set(0, 0, 0);-- // --- LIGHTING (Realistic) ---- const ambient = new THREE.AmbientLight(0xffffff, 0.6);- scene.add(ambient);-- const dirLight = new THREE.DirectionalLight(0xffffff, 1.2);- dirLight.position.set(10, 20, 10);- dirLight.castShadow = true;- dirLight.shadow.mapSize.width = 2048;- dirLight.shadow.mapSize.height = 2048;- dirLight.shadow.camera.near = 0.5;- dirLight.shadow.camera.far = 50;- dirLight.shadow.camera.left = -15;- dirLight.shadow.camera.right = 15;- dirLight.shadow.camera.top = 15;- dirLight.shadow.camera.bottom = -15;- dirLight.shadow.bias = -0.0005;- scene.add(dirLight);-- // Warm accent light for cozy interior feel- const pointLight = new THREE.PointLight(0xffaa00, 0.5, 20);- pointLight.position.set(0, 5, 0);- scene.add(pointLight);-- // --- MATERIALS ---- const wallTexture = createWallTexture();- const floorTexture = createWoodTexture();-- const materials = {- wall: new THREE.MeshStandardMaterial({- map: wallTexture,- color: 0xffffff,- roughness: 0.8,- metalness: 0.1- }),- floor: new THREE.MeshStandardMaterial({- map: floorTexture,- color: 0xffffff,- roughness: 0.5,- metalness: 0.1- }),- glass: new THREE.MeshPhysicalMaterial({- color: 0xaaccff,- transparent: true,- opacity: 0.2,- roughness: 0.0,- metalness: 0.1,- transmission: 0.9,- thickness: 0.5- }),- woodDark: new THREE.MeshStandardMaterial({- color: 0x5c4033,- roughness: 0.6,- metalness: 0.2- }),- woodLight: new THREE.MeshStandardMaterial({- color: 0x8d6e63,- roughness: 0.6,- metalness: 0.1- }),- fabricGrey: new THREE.MeshStandardMaterial({- color: 0xcccccc,- roughness: 0.9,- metalness: 0.0- }),- fabricBlue: new THREE.MeshStandardMaterial({- color: 0x60a5fa,- roughness: 0.9,- metalness: 0.0- }),- metal: new THREE.MeshStandardMaterial({- color: 0x999999,- roughness: 0.2,- metalness: 0.9- }),- kitchenTop: new THREE.MeshStandardMaterial({- color: 0x111111,- roughness: 0.1,- metalness: 0.1- }),- leather: new THREE.MeshStandardMaterial({- color: 0x4a3728,- roughness: 0.4,- metalness: 0.1- }),- rug: new THREE.MeshStandardMaterial({- color: 0xdddddd,- roughness: 1.0- })- };-- const group = new THREE.Group();- scene.add(group);-- // Dimensions (mm)- const mm = {- outerW: 5800,- outerD: 4200,- wallOuter: 240,- wallInner: 120,- height: 2800,- floor: 100- };- const scale = 0.001;- const toUnits = (v: number) => v * scale;-- // --- GEOMETRY CONSTRUCTION ----- // 1. Floor- const floorGeom = new THREE.BoxGeometry(toUnits(mm.outerW + 2000), toUnits(mm.floor), toUnits(mm.outerD + 2000));- const floorMesh = new THREE.Mesh(floorGeom, materials.floor);- floorMesh.position.set(0, -toUnits(mm.floor) / 2, 0);- floorMesh.receiveShadow = true;- group.add(floorMesh);-- // Helper to add boxes- const addBox = (sizeX: number, sizeY: number, sizeZ: number, x: number, y: number, z: number, material: THREE.Material, castsShadow = true) => {- const mesh = new THREE.Mesh(new THREE.BoxGeometry(toUnits(sizeX), toUnits(sizeY), toUnits(sizeZ)), material);- mesh.position.set(toUnits(x), toUnits(y), toUnits(z));- mesh.castShadow = castsShadow;- mesh.receiveShadow = true;- group.add(mesh);- };-- // Helper for table/chair legs- const addLegs = (x: number, y: number, z: number, w: number, d: number, legH: number, legThick: number, mat: THREE.Material) => {- const offsetW = w/2 - legThick/2;- const offsetD = d/2 - legThick/2;- const legY = y - legH/2;- addBox(legThick, legH, legThick, x - offsetW, legY, z - offsetD, mat);- addBox(legThick, legH, legThick, x + offsetW, legY, z - offsetD, mat);- addBox(legThick, legH, legThick, x - offsetW, legY, z + offsetD, mat);- addBox(legThick, legH, legThick, x + offsetW, legY, z + offsetD, mat);- }-- const addTable = (x: number, y: number, z: number, w: number, h: number, d: number, mat: THREE.Material) => {- const topThick = 40;- addBox(w, topThick, d, x, y + h - topThick/2, z, mat); // Top- addLegs(x, y + h - topThick, z, w - 100, d - 100, h - topThick, 60, mat); // Legs- };-- const addChair = (x: number, y: number, z: number, angle: number = 0) => {- const seatH = 450;- const seatW = 450;- const seatD = 450;- const backH = 400;- const mat = materials.woodLight;- const fabric = materials.fabricGrey;-- const chairGroup = new THREE.Group();-- // Seat- const seat = new THREE.Mesh(new THREE.BoxGeometry(toUnits(seatW), toUnits(50), toUnits(seatD)), fabric);- seat.position.set(0, toUnits(seatH), 0);- seat.castShadow = true;- seat.receiveShadow = true;- chairGroup.add(seat);-- // Legs- const legGeo = new THREE.BoxGeometry(toUnits(40), toUnits(seatH), toUnits(40));- const positions = [[-1, -1], [1, -1], [-1, 1], [1, 1]];- positions.forEach(([px, pz]) => {- const leg = new THREE.Mesh(legGeo, mat);- leg.position.set(toUnits(px * (seatW/2 - 20)), toUnits(seatH/2), toUnits(pz * (seatD/2 - 20)));- leg.castShadow = true;- chairGroup.add(leg);- });-- // Back- const back = new THREE.Mesh(new THREE.BoxGeometry(toUnits(seatW), toUnits(backH), toUnits(20)), mat);- back.position.set(0, toUnits(seatH + backH/2), toUnits(-seatD/2 + 10));- back.castShadow = true;- chairGroup.add(back);-- chairGroup.position.set(toUnits(x), toUnits(y), toUnits(z));- chairGroup.rotation.y = angle;- group.add(chairGroup);- };-- const addWallAlongX = (xCenter: number, zCenter: number, length: number, thickness: number, height: number) => {- addBox(length, height, thickness, xCenter, height / 2, zCenter, materials.wall);- };- const addWallAlongZ = (xCenter: number, zCenter: number, length: number, thickness: number, height: number) => {- addBox(thickness, height, length, xCenter, height / 2, zCenter, materials.wall);- };-- const halfW = mm.outerW / 2;- const halfD = mm.outerD / 2;-- // -- Outer Walls --- const winLen = 1400;- const winSill = 900;- const winHeight = 1200;- const winXCenter = 1809;- const northZ = -halfD + mm.wallOuter / 2;-- const nWallLeftLen = (halfW + winXCenter - winLen/2);- const nWallRightLen = (halfW - winXCenter - winLen/2);-- addBox(nWallLeftLen, mm.height, mm.wallOuter, -halfW + nWallLeftLen/2, mm.height/2, northZ, materials.wall);- addBox(nWallRightLen, mm.height, mm.wallOuter, halfW - nWallRightLen/2, mm.height/2, northZ, materials.wall);- addBox(winLen, winSill, mm.wallOuter, winXCenter, winSill/2, northZ, materials.wall);- addBox(winLen, mm.height - (winSill + winHeight), mm.wallOuter, winXCenter, mm.height - (mm.height - (winSill + winHeight))/2, northZ, materials.wall);-- const glassMesh = new THREE.Mesh(new THREE.BoxGeometry(toUnits(winLen), toUnits(winHeight), toUnits(40)), materials.glass);- glassMesh.position.set(toUnits(winXCenter), toUnits(winSill + winHeight/2), toUnits(northZ));- group.add(glassMesh);-- const southZ = halfD - mm.wallOuter / 2;- addWallAlongX(0, southZ, mm.outerW, mm.wallOuter, mm.height);-- const eastX = halfW - mm.wallOuter / 2;- addWallAlongZ(eastX, 0, mm.outerD, mm.wallOuter, mm.height);-- const westX = -halfW + mm.wallOuter / 2;- const doorW = 1000;- const doorH = 2200;- const doorZ = -halfD + 1200;-- const wWallSeg1 = Math.abs(-halfD - (doorZ - doorW/2));- const wWallSeg2 = Math.abs(halfD - (doorZ + doorW/2));-- addBox(mm.wallOuter, mm.height, wWallSeg1, westX, mm.height/2, -halfD + wWallSeg1/2, materials.wall);- addBox(mm.wallOuter, mm.height, wWallSeg2, westX, mm.height/2, halfD - wWallSeg2/2, materials.wall);- addBox(mm.wallOuter, mm.height - doorH, doorW, westX, mm.height - (mm.height - doorH)/2, doorZ, materials.wall);-- const doorPanel = new THREE.Mesh(new THREE.BoxGeometry(toUnits(doorW), toUnits(doorH), toUnits(50)), materials.woodDark);- const doorGroup = new THREE.Group();- doorGroup.add(doorPanel);- doorPanel.position.set(toUnits(doorW/2), toUnits(doorH/2), 0);- doorGroup.position.set(toUnits(westX), 0, toUnits(doorZ - doorW/2));- doorGroup.rotation.y = Math.PI / 4;- group.add(doorGroup);-- // -- Internal Walls --- const innerX = -halfW + mm.wallOuter + 2427;- addWallAlongZ(innerX, -halfD + mm.wallOuter + 930, 1700, mm.wallInner, mm.height);- addWallAlongX(innerX + 1240, -halfD + mm.wallOuter + 1860, 2600, mm.wallInner, mm.height);- addWallAlongX(innerX - 520, -halfD + mm.wallOuter + 1860, 1100, mm.wallInner, mm.height);- addWallAlongZ(innerX - 520, -halfD + mm.wallOuter + 2800, 1500, mm.wallInner, mm.height);- addWallAlongX(-halfW + mm.wallOuter + 520, -halfD + mm.wallOuter + 2760, 1200, mm.wallInner, mm.height);-- // -- Furniture --- // Sofa- addBox(800, 200, 2200, -halfW + 1200, 100, halfD - 1400, materials.woodDark);- addBox(1200, 200, 800, -halfW + 2200, 100, halfD - 2100, materials.woodDark);- addBox(750, 200, 2150, -halfW + 1200, 300, halfD - 1400, materials.fabricGrey);- addBox(1150, 200, 750, -halfW + 2200, 300, halfD - 2100, materials.fabricGrey);- addBox(300, 400, 2200, -halfW + 900, 400, halfD - 1400, materials.fabricGrey);- addBox(1200, 400, 300, -halfW + 2200, 400, halfD - 2450, materials.fabricGrey);- addBox(150, 300, 300, -halfW + 1200, 450, halfD - 2100, materials.fabricBlue);- addBox(150, 300, 300, -halfW + 1200, 450, halfD - 1100, materials.fabricBlue);-- // Coffee Table & Rug- addTable(-halfW + 2000, 0, halfD - 1200, 1000, 400, 600, materials.woodDark);- const rugMesh = new THREE.Mesh(new THREE.BoxGeometry(toUnits(2600), toUnits(20), toUnits(2000)), materials.rug);- rugMesh.position.set(toUnits(-halfW + 1600), toUnits(10), toUnits(halfD - 1600));- rugMesh.receiveShadow = true;- group.add(rugMesh);-- // Floor Lamp- const lampPole = new THREE.Mesh(new THREE.CylinderGeometry(toUnits(20), toUnits(20), toUnits(1600), 12), materials.metal);- lampPole.position.set(toUnits(-halfW + 2500), toUnits(800), toUnits(halfD - 2500));- lampPole.castShadow = true;- group.add(lampPole);- const lampShade = new THREE.Mesh(new THREE.ConeGeometry(toUnits(250), toUnits(300), 32, 1, true), new THREE.MeshStandardMaterial({ color: 0xfff7ed, roughness: 1.0, side: THREE.DoubleSide }));- lampShade.position.set(toUnits(-halfW + 2500), toUnits(1600), toUnits(halfD - 2500));- group.add(lampShade);-- // TV- addBox(400, 500, 2000, innerX - 200, 250, halfD - 1400, materials.woodLight);- addBox(50, 800, 1400, innerX - 180, 800, halfD - 1400, new THREE.MeshStandardMaterial({ color: 0x000000, roughness: 0.2 }));-- // Dining- addTable(innerX + 800, 0, halfD - 1200, 1400, 750, 800, materials.woodLight);- addChair(innerX + 500, 0, halfD - 1200, Math.PI / 2);- addChair(innerX + 1100, 0, halfD - 1200, -Math.PI / 2);- addChair(innerX + 800, 0, halfD - 900, Math.PI);- addChair(innerX + 800, 0, halfD - 1500, 0);-- // Kitchen- const kitchenZ = -halfD + mm.wallOuter + 2860;- addBox(700, 850, 2800, innerX + 350, 425, kitchenZ, materials.woodDark);- addBox(2400, 850, 600, innerX + 1550, 425, -halfD + mm.wallOuter + 300, materials.woodDark);- addBox(700, 40, 2800, innerX + 350, 870, kitchenZ, materials.kitchenTop);- addBox(2400, 40, 600, innerX + 1550, 870, -halfD + mm.wallOuter + 300, materials.kitchenTop);- addBox(500, 700, 2800, innerX + 250, 2000, kitchenZ, materials.woodLight);-- // Bedroom- addBox(1900, 300, 2100, innerX + 1400, 150, -halfD + 1400, materials.woodDark);- addBox(1800, 200, 2000, innerX + 1400, 400, -halfD + 1400, materials.fabricGrey);- addBox(1900, 1000, 100, innerX + 1400, 500, -halfD + 350, materials.leather);- addBox(700, 150, 400, innerX + 1100, 575, -halfD + 600, materials.fabricBlue);- addBox(700, 150, 400, innerX + 1700, 575, -halfD + 600, materials.fabricBlue);- addBox(600, 2400, 2000, innerX + 2700, 1200, -halfD + 1400, materials.woodLight);-- // Shower- const showerGlass = new THREE.Mesh(new THREE.BoxGeometry(toUnits(20), toUnits(2000), toUnits(900)), materials.glass);- showerGlass.position.set(toUnits(innerX - 520 + 750), toUnits(1000), toUnits(-halfD + mm.wallOuter + 3250));- group.add(showerGlass);-- group.position.y = toUnits(mm.floor);-- const ro = new ResizeObserver(() => {- if (!host) return;- const w = host.clientWidth;- const h = host.clientHeight;- if (w === 0 || h === 0) return;- renderer.setSize(w, h, false);- camera.aspect = w / h;- camera.updateProjectionMatrix();- });- ro.observe(host);-- let running = true;- renderer.setAnimationLoop(() => {- if (!running) return;- controls.update();- renderer.render(scene, camera);- });-- return () => {- running = false;- renderer.setAnimationLoop(null);- ro.disconnect();- controls.dispose();-- Object.values(materials).forEach(m => m.dispose());- floorTexture.dispose();- wallTexture.dispose();- renderer.dispose();- if (host.contains(renderer.domElement)) {- host.removeChild(renderer.domElement);- }- };- }, []);-- return <div className="relative flex-1 overflow-hidden" ref={hostRef} />;-}-function CadInfoPanel() {return (<div className="w-[200px] shrink-0 border-l border-black/10 bg-white/70">diff --git a/src/types/three-legacy.d.ts b/src/types/three-legacy.d.tsnew file mode 100644index 0000000..cd3332d--- /dev/null+++ b/src/types/three-legacy.d.ts@@ -0,0 +1,8 @@+import 'three';++declare module 'three' {+ interface WebGLRenderer {+ useLegacyLights: boolean;+ }+}+