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
svg_edit_fix
codingFeng101ba43ab2f40dc
diff --git a/agent/cad/svg/patch.md b/agent/cad/svg/patch.mdindex 25ce658..66fd197 100644--- a/agent/cad/svg/patch.md+++ b/agent/cad/svg/patch.md@@ -36,25 +36,143 @@ Constraints (CRITICAL):- Follow UI language policy from system messages for human-readable labels.# CAD Engineering Rules (for touched content)-1. Units: mm; keep existing scale/viewBox.-2. Walls:- - Double-line only.- - Load-bearing 240mm equivalent intent; partitions 100-150mm intent.- - Keep junctions closed (no gaps/overlaps).-3. Doors/windows (if touched):- - Doors should show frame, leaf, swing arc and opening width notes/codes.- - Windows align to wall openings; avoid floating elements.-4. Wet areas (if touched):- - Keep level-drop/drain intent readable.-5. Dimensions/text (if touched):- - Keep annotation legible and non-overlapping.- - Preserve consistent units (dimensions in mm).- - Preserve outer/inner chain logic when editing dimension blocks.- - Preserve consistent lineweight hierarchy already present in the drawing.-6. Quality hard rules:- - No floating geometry.- - No broken topology after patch.- - No collisions introduced by edits.+# ARCHITECTURAL DRAFTING RULES (APPLY ONLY TO TOUCHED CONTENT)++## 5. Drawing System Defaults (SVG-Executable)+- Geometry units: Treat existing SVG `viewBox` user units as millimeters (mm) for touched content IF the current file already behaves like mm-scale. Otherwise, do not rescale; follow existing numeric conventions.+- Elevations: meters with three decimals (e.g., H+-0.000) ONLY if the drawing already uses elevation notes or `cad_plan` provides them. Do NOT fabricate.+- Scale: preserve existing scale/proportions. Never “force 1:100” unless the current SVG already uses it consistently.+- Coordinate system: keep existing `viewBox`, origin, axes, and global transforms unchanged.+- Paper intent: any A3/A4 or “b=0.7mm” references are styling intent only; implement via SVG stroke widths consistent with existing artwork.+- Non-scaling strokes (preferred): for newly added/edited stroked elements, add `vector-effect="non-scaling-stroke"` unless the current SVG consistently avoids it.++## 6. Linework & Typography (For Added/Edited Content Only)+### 6.1 Lineweight policy (MATCH-FIRST, then fallback)+- MATCH-FIRST RULE: If the SVG already has a style system (CSS classes like `.wall`, `.dim`, inline `stroke-width`, symbol definitions), reuse the same classes/attributes instead of inventing new ones.+- Fallback weights (only if no existing system): use these SVG `stroke-width` values (in user units) for touched content:+ - Load-bearing / structure / cut: 0.70+ - Partitions: 0.50+ - Dimensions: 0.25+ - Furniture / symbols: 0.18+ - Section / horizon / cut indicators: 1.00+- Line caps/joins: prefer `stroke-linecap="round"` for dimension ticks/leaders; `stroke-linejoin="miter"` for walls. Match existing if present.++### 6.2 Linetypes (keep consistent)+- Reuse existing `stroke-dasharray` patterns if present.+- If you must introduce a new dashed pattern (rare), keep it simple and consistent:+ - Demolition / projection: `stroke-dasharray="4 2"`+ - Axes / centerlines: `stroke-dasharray="8 2 2 2"`+- Do not mix multiple dash styles for the same semantic category.++### 6.3 Text rules (SVG reality)+- MATCH-FIRST: reuse existing font-family, font-size, fill, stroke, and text styling near the edited area.+- If absent, use:+ - UI zh: `font-family="Heiti, FangSong_GB2312, sans-serif"`+ - UI en: `font-family="Arial, Times New Roman, sans-serif"`+- Use `dominant-baseline` and `text-anchor` to align labels cleanly.+- Text MUST NOT overlap lines. If crowded, offset with a leader or relocate text outside the room boundary.++## 7. Walls (When Modifying Walls)+- Preserve the existing wall representation method:+ - If walls are double-line strokes, continue double-line.+ - If walls are filled polygons/paths, keep that method.+- Thickness conventions (only when you can do it consistently):+ - Load-bearing target thickness: 240mm+ - Partition target thickness: 100–150mm+ - If thickness is not encoded reliably, do NOT “correct” thickness globally; only maintain local consistency.+- Connectivity HARD RULE: all modified wall junctions must remain closed with no gaps, overlaps, or dangling endpoints.+- No micro-gaps: adjacent endpoints must share identical coordinates (exact numeric match) within touched snippets.++## 8. Doors / Windows / Openings (When Touched)+### Doors+- MATCH-FIRST: if the SVG uses door symbols/groups (`<g id="door_*">`, `<symbol>`, reused paths), follow that pattern.+- Door graphics must include frame + leaf + swing arc (90°) UNLESS the entire drawing convention omits swing arcs.+- Door code rule (NO FABRICATION):+ - If door codes exist in current SVG or are provided in `cad_plan`, preserve/add them.+ - If not provided, omit the code rather than inventing “M0921”.+- Bathroom door swing default is a soft rule: inward ONLY if consistent with the current SVG convention.+- Prevent obvious swing collisions with nearby walls/fixtures in the edited area.++### Windows+- Use the existing window convention (triple-line / bold double-line / symbol).+- NO floating: window must be hosted on a wall; ends align to jamb geometry.+- Window metadata rule (NO FABRICATION):+ - If width/sill height labels exist or are in `cad_plan`, preserve/add.+ - If missing, do not fabricate numbers; only add generic labels if the file already does so.++### Openings+- Maintain jamb-to-corner locating dimensions ONLY if that dimensioning scheme already exists locally.+- If the area has no dimensions, do not introduce a full locating system; keep edits minimal.++## 9. Columns / Shafts / Risers / Drains (If Edited)+- MATCH-FIRST: reuse existing symbols/hatches/pattern fills.+- Column: rectangle (filled or stroked) + size label only if sizing labels are used elsewhere.+- Shaft/Flue: rectangle + diagonal hatch if hatch style exists; otherwise labeled rectangle is acceptable.+- Riser: rectangle labeled “RISER/立管” only if consistent with the file.+- Floor drain: small circle + drainage arrow only in wet zones and only if the file already uses that symbol family.++## 10. Space Labels & Wet Zones (If Modified)+- Do NOT fabricate areas/levels.+ - If area labels (m²) exist in the SVG or `cad_plan`, preserve/update them.+ - If not provided, include only the space name.+- Wet areas:+ - Enclosure clarity must remain visible (boundary defined by walls/doors).+ - Step-down level (H-0.020), slope arrows, drain symbols: add only if the current SVG already contains these conventions or `cad_plan` explicitly specifies them.++## 11. Fixtures & Cabinetry (If Modified)+- Prefer existing fixture blocks/groups; do not introduce a new symbol style.+- Kitchen: sink/cooktop/fridge/cabinets only if present elsewhere in the file or explicitly requested.+- “Flue + gas + riser logic”: do NOT infer routes/appliances unless `cad_plan` provides them; never invent pipe networks.+- Bathroom: avoid overlaps; respect reasonable clearances. The toilet centerline 300–500mm from wall is a guideline; do not break established layout to enforce it.++## 12. Flooring Materials (If Modified)+- Add material boundaries/patterns only if the SVG already has a material vocabulary (layer/pattern/style).+- If adding:+ - Use dashed boundary consistent with existing style.+ - Label material/spec only when specified. Otherwise use generic labels (Tile/地砖, Wood/木地板) if consistent with the file.+- Slope arrows (1%–2%) only when wet-zone slope notation already exists or is specified.++## 13. Dimensioning Rules (If Modified)+### 13.1 Local dimension edits (patch-friendly)+- Do not introduce a complete dimension system unless the user explicitly requests it or the current SVG already uses it extensively.+- For any added/edited dimension locally:+ - Units: mm only (text), but do not fabricate numbers.+ - Match existing arrow/tick style (ticks vs arrows).+ - Keep text readable and non-overlapping.+ - Avoid crossing walls/fixtures; reroute with leaders if needed.++### 13.2 Full dimensioning (ONLY if requested AND existing)+If (a) user asks for full dimensioning OR (b) the SVG already has three outer chains and internal dims:+- Maintain the existing chain structure where it already exists.+- Never fabricate totals if segments are unknown; prefer leaving chains unchanged over inventing numbers.+- Avoid loops/duplicates; do not dimension the same segment twice.++## 14. Callouts / Elevations / Symbols (If Modified)+- Callouts/section/elevation symbols are optional unless:+ - user explicitly requests them, OR+ - they already exist in the current SVG and the edit impacts referenced elements.+- If adding, reuse the existing symbol style and numbering scheme; do not invent sheet/detail IDs unless present.++## 15. Legend & Annotation Rules (If Edited)+- Legend edits are not mandatory in a local patch unless:+ - user requests legend changes, OR+ - you introduce a new symbol category not previously used in the drawing.+- If you must add a legend entry, append minimally and match existing formatting.++## 16. Circulation & Compliance (If Geometry Changes)+- Local edits must not create obvious usability issues in the edited area:+ - door-to-door conflicts+ - doors opening into fixtures+ - blocked corridor/entry path+- “Bathroom door should not face kitchen/entry” is context-dependent; do not restructure layout unless explicitly requested.++## 17. Professional Minimum Quality (HARD RULES)+- NO floating geometry: doors/windows/fixtures must be anchored to walls/floors via explicit alignment.+- NO overlaps or open joints in touched geometry.+- NO door swing collisions in the touched area.+- NO unreadable text: if crowded, move label with a leader; never shrink to illegible.+- NO hidden global rescale: do not change viewBox, global transforms, or overall scale.+- When required info is missing, OMIT rather than fabricate (codes, areas, sill heights, elevations, totals).# Output Format```json@@ -66,4 +184,3 @@ Constraints (CRITICAL):{ "search": "EXACT SVG snippet", "replace": "replacement snippet" }]}-```diff --git a/agent/cad/svg/replace.md b/agent/cad/svg/replace.mdindex 7152b4c..c59d9a5 100644--- a/agent/cad/svg/replace.md+++ b/agent/cad/svg/replace.md@@ -31,40 +31,162 @@ Constraints (CRITICAL):- Follow UI language policy from system messages for labels/notes.# CAD Engineering Rules (MANDATORY)-1. Drawing system:- - Units: mm intent.- - Preferred drawing scale intent: 1:100 (fallback 1:50).- - Keep a valid `viewBox`.- - Ensure all geometry fits within the viewBox.-2. Architecture first:- - Draw structure/walls first, then openings, fixtures, annotation.-3. Walls:- - Double-line wall convention.- - Load-bearing and partition walls visually distinguishable.- - All wall junctions must be closed.-4. Doors/windows/openings:- - Doors include opening direction (arc) and readable width/codes where applicable.- - Windows align with openings and wall thickness.- - No floating windows/doors.-5. Space labeling:- - Room names and key notes should be readable and non-overlapping.- - Include room area and key elevation note where applicable.-6. Wet-area essentials (when applicable):- - Show drainage/level intent and enclosure clarity.-7. Fixtures/cabinetry:- - Kitchen and bathroom core fixtures should be represented when part of scope.-8. Dimensioning/annotation:- - Keep dimensions coherent, non-overlapping, and consistent.- - Maintain outer and inner dimension chain readability.- - Units in mm for dimensions; elevation notes in meters where needed.-9. Sheet essentials (when requested or already in style):- - Preserve or add border/title block/north arrow/legend as needed by request.- - Keep a consistent lineweight hierarchy:- - structural > partitions > dimensions > furniture/symbols.-10. Quality hard rules:- - No floating segments.- - No impossible door swings/collisions.- - No malformed SVG.+# CRITICAL ARCHITECTURAL DRAFTING RULES (MANDATORY)++## 0. SVG Document & Layout System (MANDATORY)+- The SVG MUST be self-contained and renderable in modern browsers.+- Use a consistent coordinate system:+ - Prefer `viewBox` user units = millimeters (mm) for the drawing model.+ - If `cad_plan` provides a real-world scale or paper size, align the viewBox accordingly.+ - If unknown, choose a reasonable canvas (e.g., A3 landscape: 420x297 units) and place the plan within margins.+- For stroked geometry, prefer `vector-effect="non-scaling-stroke"` so lineweights remain visually stable when zooming/exporting.+- Organize content into semantic layers using grouped `<g>` elements with stable ids:+ - `layer_walls`, `layer_openings`, `layer_columns_shafts`, `layer_fixtures`, `layer_furniture`,+ `layer_materials`, `layer_dims`, `layer_symbols`, `layer_text`, `layer_legend`, `layer_titleblock`, `layer_north`+- Reuse symbols via `<defs>` (`<symbol>` / `<g id="sym_*">`) for doors/windows/fixtures/arrows to keep consistency.++## A. Walls (MANDATORY, buildable + closed)+- Walls must be represented consistently:+ - Prefer double-line wall convention (two parallel strokes or a closed wall polygon with inner/outer edges).+ - All wall intersections MUST be closed (no gaps, overlaps, dangling endpoints).+- Thickness targets (use when `cad_plan` supports it; otherwise choose sensible defaults and keep consistent):+ - Load-bearing wall = 240mm+ - Partition wall = 100–150mm+- Wall types (only if needed by request or plan):+ - Existing wall = continuous+ - New wall = slightly stronger emphasis + label "NEW/新建" near the segment+ - Demolition wall = dashed + cross-hatch (only when demolition is requested/known)+- Paper intent note:+ - Any “>=0.7mm on paper” is styling intent; implement via SVG stroke widths consistent with the lineweight system below.++## B. Doors & Windows (MANDATORY where applicable)+### Doors (MANDATORY when present)+- Door must show: frame + leaf + 90° swing arc.+- Door must be hosted on a wall (no floating).+- Prevent obvious swing conflicts with adjacent walls/fixtures.+- Door metadata (NO FABRICATION):+ - If `cad_plan` provides opening width/door code, include it.+ - If not provided, you may show opening width ONLY if it can be derived from geometry; otherwise omit codes like “M0921” rather than inventing.+- Bathroom door swing default is a soft rule:+ - Inward by default ONLY if not contradicted by `cad_plan`/user request and does not cause conflicts.++### Windows (MANDATORY when present)+- Use a consistent window convention (triple-line or bold double-line).+- Window must align to jambs and be embedded in wall thickness (NO floating windows).+- Window metadata (NO FABRICATION):+ - Include width/type/sill height ONLY if provided by `cad_plan` or explicitly requested with known values.+ - If unknown, omit numeric sill heights and types; use generic label only if the drawing elsewhere uses it.++### Openings+- Add jamb markers; include locating dimensions only if a dimensioning system is present (see G).++## C. Columns / Shafts / Risers / Drains (MANDATORY where applicable)+- Columns: rectangle (filled or stroked per style) + size label only if size is known (from `cad_plan` or explicit input).+- Flue/Shaft: rectangle + diagonal hatch (prefer pattern fill in `<defs>`).+- Riser: labeled rectangle "RISER/立管" if known/needed.+- Floor drain: small circle + drainage arrow in wet zones only.++## D. Space Labels & Areas (MANDATORY, but NO FABRICATION)+- Every room MUST include a space label:+ - Room name (follow UI language policy from system messages)+- Area and level notes:+ - Include Area (m², 1 decimal) ONLY if `cad_plan` provides it OR it can be reliably computed from a closed boundary polygon.+ - Include Level note (e.g., H+-0.000) ONLY if provided by `cad_plan`/request or if the drawing has a consistent elevation notation.+ - Do NOT invent areas/elevations.+- Wet areas (when present):+ - Must be visually enclosed/legible boundary.+ - Step-down level (H-0.020), drainage arrows, drain symbol: include ONLY if wet-area detailing is requested or provided by `cad_plan`.++## E. Fixtures & Cabinetry (MANDATORY where applicable; keep realistic)+### Kitchen (when present/required)+- Depict: sink, cooktop, fridge, base/upper cabinets in thin lines.+- “Flue + gas + riser / water heater logic”:+ - Show shafts/risers/flues ONLY if provided by `cad_plan` or explicitly requested with placements.+ - Do NOT invent full MEP routing.++### Bathroom (when present/required)+- Depict: toilet, vanity, shower/bath with clearances; avoid overlaps.+- Toilet centerline 300–500mm from wall is a guideline; adapt to actual layout constraints.++### Furniture+- Fixed furniture (wardrobe/TV cabinet/storage): show as dimensioned footprints when sizes are known; otherwise show generic cabinetry blocks consistent with the plan.+- Movable furniture: outline only with thin stroke; avoid clutter.++## F. Flooring Materials (OPTIONAL unless requested; NO FABRICATION)+- Different materials may be shown as zones with dashed boundary and hatch/pattern fill.+- Label material + spec (e.g., 600x1200 tile) ONLY if specified by user or `cad_plan`.+- Wet zones slope arrows (1%–2%) and threshold stones: show ONLY if requested or specified; otherwise omit.++## G. Dimensioning System (CONDITIONAL, avoid “fake precision”)+- Dimensioning is mandatory ONLY if:+ - the user explicitly requests dimensions, OR+ - `cad_plan` includes dimensions/standards requiring them.+- If dimensioning is included:+ - Units: mm only.+ - Style: extension offset ≈ 2 units; overshoot 2–3 units; consistent tick/arrow style; text centered and readable.+ - Avoid overlaps and cross-chain loops.+- Three outer chains (segments → bays → overall) should be included ONLY if:+ - there is a clear building envelope/structural bay logic in `cad_plan`, OR+ - the user requests full construction dimensioning.+- NEVER invent numeric dimensions. If a value cannot be derived or is missing, omit the number rather than guessing.++## H. Elevation / Section / Callout Symbols (CONDITIONAL, not auto-invented)+- Add interior elevation markers / section cuts / detail callouts ONLY if:+ - explicitly requested, OR+ - `cad_plan` provides a numbering scheme, OR+ - the user’s workflow needs them and identifiers are provided.+- Do NOT invent sheet/detail IDs or numbering systems.+- Floor elevation format (H+-0.000) only when elevations are known.++## I. Lineweight System (FIXED intent, implementable in SVG)+- Implement a consistent, minimal lineweight palette in SVG `stroke-width` (user units).+- Prefer class-based styling in a `<style>` block:+ - `.lw_struct { stroke-width: 0.70; }`+ - `.lw_part { stroke-width: 0.50; }`+ - `.lw_dim { stroke-width: 0.25; }`+ - `.lw_sym { stroke-width: 0.18; }`+ - `.lw_cut { stroke-width: 1.00; }`+- Dash rules MUST remain consistent across categories.+- Use `fill="none"` for linework unless a fill is semantically required (columns, hatches, material zones).++## J. Text Style Rules (SVG-safe)+- Follow UI language policy from system messages:+ - UI zh: Heiti / FangSong_GB2312 (with fallbacks)+ - UI en: Arial / Times New Roman (with fallbacks)+- Text must not overlap walls/dimensions. Use leaders/offsets.+- Prefer consistent font sizes relative to the drawing:+ - Title: larger than room labels+ - Room labels: larger than dimensions/notes+ - Dimension text: smallest but readable+- Avoid hardcoding “mm paper height” unless you have an explicit viewBox=mm mapping.++## K. Legend & Symbol Table (CONDITIONAL, layout-safe)+- Include a legend ONLY if:+ - requested by the user, OR+ - you introduce multiple symbol categories that would be ambiguous without a legend.+- Legend entries must match the symbols actually used in the drawing.+- Keep legend compact; place it in a reserved corner area so it does not crowd the plan.++## L. Circulation & Compliance Rules (MANDATORY at high level)+- Maintain clear circulation paths for entry → living → bedrooms (no obvious blockages).+- Avoid door-to-door collisions where doors face each other in close proximity.+- Bathroom door facing kitchen/entry is context-dependent; do not enforce unless requested or required by `cad_plan`.+- Wet areas must be enclosed as a coherent zone (walls/doors define boundary).++## M. Rendering Scope (MANDATORY)+- Draw ONLY a 2D horizontal cut plan.+- Cut height note (1.1–1.5m) may be included as a drawing note if the sheet includes notes/title block.+- Represent post-renovation finished surfaces if the request indicates renovation; otherwise represent existing as specified.+- Include only what is supported by request/plan:+ - Always: walls, doors/windows, key fixtures+ - Optional/conditional: columns/shafts, materials, dimensions, callouts, legend, north arrow, title block++## N. Missing Data Handling (MANDATORY, anti-hallucination)+- If `cad_plan` lacks required info:+ - Infer ONLY safe geometric defaults needed to draw a coherent plan (e.g., partition thickness within 100–150mm).+ - Do NOT fabricate numeric metadata (door/window codes, sill heights, areas, elevation notes, total dimensions, sheet IDs).+ - Prefer omission over guessing for any value that looks “authoritative”.+- DO NOT output explanations; the SVG should simply omit unknown annotations.# Output Format```json@@ -74,4 +196,3 @@ Constraints (CRITICAL):"mode": "replace","full": "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 W H\">...</svg>"}-```diff --git a/agent/ppt/system.md b/agent/ppt/system.mdindex b4c7e0a..df88a62 100644--- a/agent/ppt/system.md+++ b/agent/ppt/system.md@@ -23,6 +23,11 @@ Rules (CRITICAL):3. For visual edit requests, set `instruction` on that slide.4. Output ONLY one markdown code block.5. `ui_language=zh` => Simplified Chinese; `ui_language=en` => English.+6. If style should reference other slides, you may set:+ - `styleRefSlideIds`: string[] (e.g. ["slide-2","slide-5"])+ - `styleRefPolicy`: "style_only" | "style_and_layout"+ - `styleRefImageUrls`: string[] (optional; explicit reference image URLs when slide IDs are unavailable)+7. You may edit multiple slides in one response. Each slide can have its own style reference group.# Output Format```json@@ -36,7 +41,10 @@ Rules (CRITICAL):"description": "...","layout": "...","note": "...",- "instruction": "optional, only for visual edit"+ "instruction": "optional, only for visual edit",+ "styleRefSlideIds": ["slide-2", "slide-5"],+ "styleRefPolicy": "style_only",+ "styleRefImageUrls": ["https://example.com/style-ref-1.png"]}]}diff --git a/api/routes/log-file-parser.ts b/api/routes/log-file-parser.tsnew file mode 100644index 0000000..4daf7bc--- /dev/null+++ b/api/routes/log-file-parser.ts@@ -0,0 +1,2 @@+export { POST } from "../../src/workspaces/flow/api/log-file-parser"+diff --git a/api/routes/third-party-parser.ts b/api/routes/third-party-parser.tsnew file mode 100644index 0000000..ba995bb--- /dev/null+++ b/api/routes/third-party-parser.ts@@ -0,0 +1,2 @@+export { POST } from "../../src/workspaces/flow/api/third-party-parser"+diff --git a/api/server.ts b/api/server.tsindex 21d2d84..ee8b4ca 100644--- a/api/server.ts+++ b/api/server.ts@@ -4,6 +4,8 @@ import { GET as getConfig } from "./routes/config";import { POST as postVerifyAccessCode } from "./routes/verify-access-code";import { POST as postLogFeedback } from "./routes/log-feedback";import { POST as postLogSave } from "./routes/log-save";+import { POST as postLogFileParser } from "./routes/log-file-parser";+import { POST as postThirdPartyParser } from "./routes/third-party-parser";import { POST as postChat } from "./routes/chat";const PORT = Number(process.env.API_PORT || 8787);@@ -97,6 +99,8 @@ app.get("/api/config", async (_req, res) => {app.post("/api/verify-access-code", withHandler(postVerifyAccessCode));app.post("/api/log-feedback", withHandler(postLogFeedback));app.post("/api/log-save", withHandler(postLogSave));+app.post("/api/log-file-parser", withHandler(postLogFileParser));+app.post("/api/third-party-parser", withHandler(postThirdPartyParser));app.post("/api/chat", withHandler(postChat));app.get("/healthz", (_req, res) => {diff --git a/public/svg-editor.html b/public/svg-editor.htmlindex 853f1a8..7aa8357 100644--- a/public/svg-editor.html+++ b/public/svg-editor.html@@ -38,6 +38,7 @@noDefaultExtensions: false,userExtensions: [],no_save_warning: true,+ noStorageOnLoad: true,imgPath: "/vendor/svgedit/images",extPath: "/vendor/svgedit/extensions"});@@ -52,7 +53,18 @@};const normalizeIncomingSvg = (value) => {- const raw = String(value || "").trim();+ const decodeBasicHtmlEntities = (text) =>+ String(text || "")+ .replace(/</gi, "<")+ .replace(/>/gi, ">")+ .replace(/"/gi, '"')+ .replace(/'|'/gi, "'")+ .replace(/&/gi, "&");++ const original = String(value || "").trim();+ const raw = !/<svg[\s/>]/i.test(original) && /<\s*svg[\s\S]*>/i.test(original)+ ? decodeBasicHtmlEntities(original).trim()+ : original;if (!raw) return "";const start = raw.search(/<svg[\s/>]/i);if (start < 0) return "";@@ -119,18 +131,25 @@};const loadSvg = async (svg) => {- const text = normalizeIncomingSvg(svg);- if (!text) return false;+ const text = normalizeIncomingSvg(svg);+ if (!text) return false;++ try {+ const ok = editor?.svgCanvas?.setSvgString?.(text);+ if (ok !== false) return true;+ } catch {+ }++ try {+ const ok = editor?.svgCanvas?.importSvgString?.(text);+ if (ok !== false) return true;+ } catch {+ }try {await editor.loadFromString(text, { noAlert: true });return true;} catch (e) {- try {- const ok = editor?.svgCanvas?.setSvgString?.(text);- if (ok !== false) return true;- } catch {- }console.error("Failed to load SVG", e);return false;}@@ -158,6 +177,8 @@editor.ready(async () => {editorReady = true;+ // Always start from a known blank canvas; prevents stale local restore content.+ await clearSvg();await applyPendingLoad();post({ type: "cad_svg_editor_ready" });});@@ -173,7 +194,8 @@if (!normalized) {post({type: "cad_svg_editor_load_result",- ok: false+ ok: false,+ reason: "empty_or_invalid_svg"});return;}@@ -189,7 +211,8 @@const ok = await loadSvg(normalized);post({type: "cad_svg_editor_load_result",- ok: !!ok+ ok: !!ok,+ reason: ok ? "" : "editor_rejected_svg"});return;}diff --git a/src/lib/ppt-service.ts b/src/lib/ppt-service.tsindex c30a86c..d1a8142 100644--- a/src/lib/ppt-service.ts+++ b/src/lib/ppt-service.ts@@ -21,6 +21,42 @@ export interface SlideEditRoutingItem {instruction: string;}+const normalizeLayoutByLanguage = (layout: string, uiLanguage: "zh" | "en") => {+ const raw = String(layout || "").trim()+ if (!raw) return raw+ const key = raw+ .toLowerCase()+ .replace(/\s+/g, "")+ .replace(/[+_/-]/g, "")+ const map: Record<string, { zh: string; en: string }> = {+ cover: { zh: "封面页", en: "Cover" },+ titlebullets: { zh: "标题+要点", en: "Title + Bullets" },+ titlebullet: { zh: "标题+要点", en: "Title + Bullets" },+ twocolumn: { zh: "双栏布局", en: "Two-column" },+ lefttextrightimage: { zh: "左文右图", en: "Left text, right image" },+ titleandcontent: { zh: "标题+内容", en: "Title + Content" },+ 封面页: { zh: "封面页", en: "Cover" },+ 标题要点: { zh: "标题+要点", en: "Title + Bullets" },+ 双栏布局: { zh: "双栏布局", en: "Two-column" },+ 左文右图: { zh: "左文右图", en: "Left text, right image" },+ 标题内容: { zh: "标题+内容", en: "Title + Content" },+ }+ const hit = map[key]+ if (!hit) return raw+ return uiLanguage === "zh" ? hit.zh : hit.en+}++const normalizeSpeakerNote = (note: string, uiLanguage: "zh" | "en") => {+ const raw = String(note || "").trim()+ if (!raw) return raw+ return raw+ .replace(/^[\s\-*•\d.、]+/gm, "")+ .replace(/\n{2,}/g, "\n")+ .replace(/\n/g, uiLanguage === "zh" ? "," : ", ")+ .replace(/\s{2,}/g, " ")+ .trim()+}+type ReferenceFileInput = { filename: string; content: string };type ReferenceImageAssetInput = { label: string; caption: string; sourceFile: string; sourcePage?: number };@@ -182,7 +218,10 @@ Quality requirements:- Each slide content should have 4-6 bullets.- Each bullet should be specific and informative, not generic placeholders.- description should clearly explain visual hierarchy and key visual elements (including placement hints when useful).-- note should include practical speaking guidance (2-4 concise points).+- note must be a coherent speaker script that can be spoken directly (3-6 connected sentences with natural transitions).+- note must be plain paragraph text, not bullet points and not numbered lists.+- All slide fields (title/content/description/note) MUST follow ui_language.+- If ui_language=zh, use Simplified Chinese (except unavoidable proper nouns/acronyms).`;const response = await generateChatMessage([@@ -195,8 +234,8 @@ Quality requirements:const pages = normalizePages(parsed).map((p, i) => ({...p,id: p.id || `slide-${i + 1}`,- note: typeof p.note === "string" ? p.note : "",- layout: typeof p.layout === "string" ? p.layout : "",+ note: typeof p.note === "string" ? normalizeSpeakerNote(p.note, uiLanguage) : "",+ layout: typeof p.layout === "string" ? normalizeLayoutByLanguage(p.layout, uiLanguage) : "",description: typeof p.description === "string" ? p.description : "",}));if (pages.length === 0) throw new Error("No outline parsed from AI response");@@ -244,7 +283,10 @@ Quality requirements:- Each slide content should have 4-6 bullets.- Each bullet should be specific and informative, not generic placeholders.- description should clearly explain visual hierarchy and key visual elements (including placement hints when useful).-- note should include practical speaking guidance (2-4 concise points).+- note must be a coherent speaker script that can be spoken directly (3-6 connected sentences with natural transitions).+- note must be plain paragraph text, not bullet points and not numbered lists.+- All slide fields (title/content/description/note) MUST follow ui_language.+- If ui_language=zh, use Simplified Chinese (except unavoidable proper nouns/acronyms).`;const response = await generateChatMessage([{ role: "system", content: PPT_OUTLINE_SYSTEM },@@ -255,8 +297,8 @@ Quality requirements:const pages = normalizePages(parsed).map((p, i) => ({...p,id: p.id || `slide-${i + 1}`,- note: typeof p.note === "string" ? p.note : "",- layout: typeof p.layout === "string" ? p.layout : "",+ note: typeof p.note === "string" ? normalizeSpeakerNote(p.note, uiLanguage) : "",+ layout: typeof p.layout === "string" ? normalizeLayoutByLanguage(p.layout, uiLanguage) : "",description: typeof p.description === "string" ? p.description : "",}));if (pages.length === 0) throw new Error("No plan parsed from AI response");@@ -304,6 +346,7 @@ ${currentSlideJson}${refText ? `Reference:\n${refText}\n\n` : ""}Task:- Improve bullets (<= 12 words each), and refine description for image generation.- Optionally add speaker note and layout hint if helpful.+- If note is provided, write it as a coherent spoken script (3-6 connected sentences), not bullets.- Keep id stable.Return JSON only (no extra text).`;@@ -327,8 +370,8 @@ Return JSON only (no extra text).`;title: typeof first.title === "string" ? first.title : page.title,content: Array.isArray(first.content) ? first.content.map((x: any) => String(x)) : page.content,description: typeof first.description === "string" ? first.description : page.description,- note: typeof first.note === "string" ? first.note : page.note,- layout: typeof first.layout === "string" ? first.layout : page.layout,+ note: typeof first.note === "string" ? normalizeSpeakerNote(first.note, "zh") : page.note,+ layout: typeof first.layout === "string" ? normalizeLayoutByLanguage(first.layout, "zh") : page.layout,};} catch {return page;diff --git a/src/workspaces/cad/CadWorkspaceShell.tsx b/src/workspaces/cad/CadWorkspaceShell.tsxindex 5a615b2..240396f 100644--- a/src/workspaces/cad/CadWorkspaceShell.tsx+++ b/src/workspaces/cad/CadWorkspaceShell.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useRef, useState } from "react";+import React, { useEffect, useRef, useState } from "react";import { toast } from "sonner";import { cn } from "@/lib/utils";import { t } from "@/lib/i18n";@@ -14,7 +14,6 @@ import type { ChatMessage } from "@/lib/ai-client";import { generateImage } from "@/lib/ai-client";import { CadWorkspace } from "@/workspaces/cad/workspace/CadWorkspace";import { ChatPanel as CadChatPanel } from "@/workspaces/cad/chat/ChatPanel";-import type { HistoryItem } from "@/workspaces/cad/chat/history-dialog";type Attachment = {id: string;@@ -27,7 +26,6 @@ type CodeActionResult = { ok: boolean; retry?: boolean; error?: string; svg?: stconst CAD_WORKSPACE_STORAGE_KEY = "unified-ai-workspace-cad-state-v1";const CAD_RENDERS_STORAGE_KEY = "unified-ai-workspace-cad-renders-v1";-const CAD_HISTORY_STORAGE_KEY = "unified-ai-workspace-history-cad-v1";const CAD_CHAT_STORAGE_KEY = "chat_history_v2_cad";const CAD_RENDER_SLOT_TITLES = ["装修平面布置图",@@ -55,8 +53,20 @@ const tryParseJson = (text: string) => {}};+const decodeBasicHtmlEntities = (text: string) =>+ String(text || "")+ .replace(/</gi, "<")+ .replace(/>/gi, ">")+ .replace(/"/gi, '"')+ .replace(/'|'/gi, "'")+ .replace(/&/gi, "&");+const normalizeSvgMarkup = (text: string) => {- const raw = String(text || "").trim();+ const original = String(text || "").trim();+ let raw = original;+ if (!/<svg[\s/>]/i.test(raw) && /<\s*svg[\s\S]*>/i.test(raw)) {+ raw = decodeBasicHtmlEntities(raw).trim();+ }if (!raw) return "";const start = raw.search(/<svg[\s/>]/i);if (start < 0) return "";@@ -66,6 +76,37 @@ const normalizeSvgMarkup = (text: string) => {return tail.trim();};+const isValidSvgMarkup = (text: string) => {+ const normalized = normalizeSvgMarkup(text);+ if (!normalized) return false;+ if (typeof DOMParser === "undefined") return /^<svg[\s/>]/i.test(normalized);+ try {+ const doc = new DOMParser().parseFromString(normalized, "image/svg+xml");+ if (doc.querySelector("parsererror")) return false;+ return String(doc.documentElement?.nodeName || "").toLowerCase() === "svg";+ } catch {+ return false;+ }+};++const hasDrawableSvgContent = (text: string) => {+ const normalized = normalizeSvgMarkup(text);+ if (!normalized) return false;+ if (typeof DOMParser === "undefined") return true;+ try {+ const doc = new DOMParser().parseFromString(normalized, "image/svg+xml");+ if (doc.querySelector("parsererror")) return false;+ const root = doc.documentElement;+ if (!root || String(root.nodeName || "").toLowerCase() !== "svg") return false;+ const drawable = root.querySelector(+ "path,rect,circle,ellipse,line,polyline,polygon,text,image,use,foreignObject",+ );+ return !!drawable;+ } catch {+ return false;+ }+};+function applyStringEdits(source: string, edits: { search: string; replace: string }[]) {if (!Array.isArray(edits) || edits.length === 0) throw new Error("Empty patch edits");let out = source;@@ -162,21 +203,19 @@ export function CadWorkspaceShell() {const [attachments, setAttachments] = useState<Attachment[]>([]);const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);- const [versionHistory, setVersionHistory] = useState<HistoryItem[]>(() => {- if (typeof window === "undefined") return [];- try {- const raw = localStorage.getItem(CAD_HISTORY_STORAGE_KEY);- const parsed = raw ? JSON.parse(raw) : [];- return Array.isArray(parsed) ? parsed : [];- } catch {- return [];- }- });const cadImageObjectUrlsRef = useRef<string[]>([]);+ const suppressChatSvgSyncRef = useRef(false);+ const cad2dSvgRef = useRef<string | undefined>(typeof initialCadState?.cad2dSvg === "string" ? initialCadState.cad2dSvg : undefined);const [isChatCollapsed, setIsChatCollapsed] = useState(false);+ const [cadResetTick, setCadResetTick] = useState(0);+ const [cadApplyTick, setCadApplyTick] = useState(0);const chatPanelRef = useRef<PanelImperativeHandle | null>(null);+ useEffect(() => {+ cad2dSvgRef.current = cad2dSvg;+ }, [cad2dSvg]);+useEffect(() => {if (typeof window === "undefined") return;try {@@ -195,14 +234,6 @@ export function CadWorkspaceShell() {}}, [cad2dSvg, cadPlan, cadImages, cadBom, cadFocusPanel]);- useEffect(() => {- if (typeof window === "undefined") return;- try {- localStorage.setItem(CAD_HISTORY_STORAGE_KEY, JSON.stringify(versionHistory));- } catch {- }- }, [versionHistory]);-useEffect(() => {const nextObjectUrls = cadImages.map((x) => x?.url)@@ -220,22 +251,30 @@ export function CadWorkspaceShell() {}, [cadImages]);useEffect(() => {+ if (suppressChatSvgSyncRef.current) {+ if (!Array.isArray(chatHistory) || chatHistory.length === 0) {+ suppressChatSvgSyncRef.current = false;+ }+ return;+ }if (!Array.isArray(chatHistory) || chatHistory.length === 0) return;+ // Only recover from chat history when canvas has no SVG yet.+ const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));+ if (current) return;+for (let i = chatHistory.length - 1; i >= 0; i -= 1) {const msg = chatHistory[i];if (!msg || msg.role !== "assistant" || typeof msg.content !== "string") continue;const svg = extractLatestSvgFromText(msg.content);if (!svg) continue;-- const current = normalizeSvgMarkup(String(cad2dSvg || ""));- if (svg === current) return;+ cad2dSvgRef.current = svg;setCad2dSvg(svg);setCadFocusPanel("2d");addToHistory(svg, "svg");return;}- }, [chatHistory, cad2dSvg]);+ }, [chatHistory]);const toggleCollapse = () => {const panel = chatPanelRef.current;@@ -253,41 +292,7 @@ export function CadWorkspaceShell() {}};- const addToHistory = (content: string, type: HistoryItem["type"]) => {- const item: HistoryItem = {- id: Date.now().toString(),- timestamp: Date.now(),- content,- type,- };- setVersionHistory((prev) => [...prev, item]);- };-- const handleRestore = (item: HistoryItem) => {- 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- .slice(0, 7)- .map((p: any, idx: number) => ({- title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,- url: typeof p?.url === "string" ? p.url : "",- }))- : [];- if (next.length > 0) setCadImages(next);- }- } catch {- }- }- };+ const addToHistory = (_content: string, _type: "svg" | "json") => {};const handleAddToChat = (payload: string) => {const trimmed = String(payload || "").trim();@@ -322,26 +327,44 @@ export function CadWorkspaceShell() {const trimmed = raw.trim();if (!trimmed) return { ok: false, retry: false, error: "Empty input" };- const isDirectSvgPayload = /^(?:<\?xml[\s\S]*?\?>\s*)?<svg[\s/>]/i.test(trimmed);- const normalizedRawSvg = isDirectSvgPayload ? normalizeSvgMarkup(raw) : "";- if (isDirectSvgPayload && normalizedRawSvg) {+ const normalizedRawSvg = !trimmed.startsWith("{") ? normalizeSvgMarkup(raw) : "";+ if (normalizedRawSvg) {+ if (!isValidSvgMarkup(normalizedRawSvg)) {+ toast.warning("SVG may contain XML issues, trying to load anyway");+ }+ if (!hasDrawableSvgContent(normalizedRawSvg)) {+ toast.error("SVG has no drawable content");+ return { ok: false, retry: false, error: "SVG has no drawable content" };+ }+ const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));+ if (normalizedRawSvg === current) {+ // Keep "Apply" idempotent: same SVG still forces editor remount to recover stale iframe state.+ setCadFocusPanel("2d");+ setCadApplyTick((x) => x + 1);+ return { ok: true, svg: current || normalizedRawSvg };+ }+ cad2dSvgRef.current = normalizedRawSvg;setCad2dSvg(normalizedRawSvg);setCadFocusPanel("2d");addToHistory(normalizedRawSvg, "svg");+ setCadApplyTick((x) => x + 1);return { ok: true, svg: normalizedRawSvg };}- if (!trimmed.startsWith("{")) return { ok: true };+ if (!trimmed.startsWith("{")) return { ok: false, retry: false, error: "No SVG found in input" };const parsed = tryParseJson(trimmed);if (!parsed) return { ok: false, retry: false, error: "Invalid JSON" };+ const parsedType = String(parsed?.type || "").trim().toLowerCase();+ const parsedTarget = String(parsed?.target || "").trim().toLowerCase();+ const parsedMode = String(parsed?.mode || "").trim().toLowerCase();- if (parsed?.type === "cad_plan") {+ if (parsedType === "cad_plan") {setCadPlan(parsed);addToHistory(JSON.stringify(parsed), "json");return { ok: true };}- if (parsed?.type === "cad_bom") {+ if (parsedType === "cad_bom") {const fallbackColumns = ["Category", "Name", "Spec", "Qty", "Unit", "Note"];const columns =Array.isArray(parsed.columns) && parsed.columns.length > 0@@ -353,7 +376,7 @@ export function CadWorkspaceShell() {return { ok: true };}- if (parsed?.type === "cad_images") {+ if (parsedType === "cad_images") {const prompts = Array.isArray(parsed.prompts) ? parsed.prompts : [];const items = prompts.map((p: any) => ({@@ -367,7 +390,7 @@ export function CadWorkspaceShell() {setCadImagesLoading(true);setCadImages(Array.from({ length: 7 }).map((_, idx) => ({- title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,+ title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,url: "",})),);@@ -425,7 +448,7 @@ export function CadWorkspaceShell() {const syncPartialImages = () => {setCadImages(Array.from({ length: 7 }).map((_, idx) => ({- title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,+ title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,url: results[idx]?.url || "",})),);@@ -459,13 +482,13 @@ export function CadWorkspaceShell() {}const final = Array.from({ length: 7 }).map((_, idx) => ({- title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,+ title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,url: results[idx]?.url || "",}));setCadImages(final);const failedCount = list.filter((_, idx) => !results[idx]?.url).length;if (failedCount > 0) {- toast.warning(`有 ${failedCount} 张装修图重试后仍失败,请再试一次生成。`);+ toast.warning(`${failedCount} render image(s) failed after retries. Please run generation again.`);}addToHistory(JSON.stringify({ type: "cad_images", prompts: final }, null, 2), "json");} catch (e) {@@ -473,7 +496,7 @@ export function CadWorkspaceShell() {toast.error("CAD image generation failed");setCadImages(Array.from({ length: 7 }).map((_, idx) => ({- title: CAD_RENDER_SLOT_TITLES[idx] || `图纸 ${idx + 1}`,+ title: CAD_RENDER_SLOT_TITLES[idx] || `鍥剧焊 ${idx + 1}`,url: "",})),);@@ -484,29 +507,62 @@ export function CadWorkspaceShell() {return { ok: true };}- if (parsed?.type === "cad_patch" && parsed?.target === "2d_svg") {- const mode = parsed?.mode;- if (mode === "replace" && typeof parsed.full === "string") {+ if (parsedType === "cad_patch" && parsedTarget === "2d_svg") {+ if (parsedMode === "replace" && typeof parsed.full === "string") {const normalizedFull = normalizeSvgMarkup(parsed.full);- if (!normalizedFull) return { ok: false, retry: false, error: "Invalid replace svg" };+ if (!normalizedFull) {+ toast.error("Invalid replace svg");+ return { ok: false, retry: false, error: "Invalid replace svg" };+ }+ if (!isValidSvgMarkup(normalizedFull)) {+ toast.warning("Replace svg may contain XML issues, trying to load anyway");+ }+ if (!hasDrawableSvgContent(normalizedFull)) {+ toast.error("Replace svg has no drawable content");+ return { ok: false, retry: false, error: "Replace svg has no drawable content" };+ }+ const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));+ if (normalizedFull === current) {+ setCadFocusPanel("2d");+ setCadApplyTick((x) => x + 1);+ return { ok: true, svg: current || normalizedFull };+ }+ cad2dSvgRef.current = normalizedFull;setCad2dSvg(normalizedFull);setCadFocusPanel("2d");addToHistory(normalizedFull, "svg");+ setCadApplyTick((x) => x + 1);return { ok: true, svg: normalizedFull };}- if (mode === "patch" && Array.isArray(parsed.edits)) {+ if (parsedMode === "patch" && Array.isArray(parsed.edits)) {try {- const current = normalizeSvgMarkup(cad2dSvg || "");- if (!current) return { ok: false, retry: true, error: "Current 2D SVG is empty, cannot apply patch" };+ const current = normalizeSvgMarkup(String(cad2dSvgRef.current || ""));+ if (!current) {+ toast.error("Current 2D SVG is empty, cannot apply patch");+ return { ok: false, retry: true, error: "Current 2D SVG is empty, cannot apply patch" };+ }const next = applyStringEdits(current, parsed.edits);const normalizedNext = normalizeSvgMarkup(next);- if (!normalizedNext) return { ok: false, retry: true, error: "Patch result is not valid svg" };+ if (!normalizedNext) {+ toast.error("Patch result is not valid svg");+ return { ok: false, retry: true, error: "Patch result is not valid svg" };+ }+ if (!isValidSvgMarkup(normalizedNext)) {+ toast.warning("Patch result may contain XML issues, trying to load anyway");+ }+ if (!hasDrawableSvgContent(normalizedNext)) {+ toast.error("Patch result has no drawable content");+ return { ok: false, retry: true, error: "Patch result has no drawable content" };+ }if (normalizedNext === current) {+ toast.warning("Patch produced no visible SVG change");return { ok: false, retry: true, error: "Patch produced no visible SVG change" };}+ cad2dSvgRef.current = normalizedNext;setCad2dSvg(normalizedNext);setCadFocusPanel("2d");addToHistory(normalizedNext, "svg");+ setCadApplyTick((x) => x + 1);return { ok: true, svg: normalizedNext };} catch (e) {const msg = e instanceof Error ? e.message : String(e);@@ -514,12 +570,16 @@ export function CadWorkspaceShell() {return { ok: false, retry: true, error: msg };}}+ toast.error(`Unsupported cad_patch mode: ${String(parsedMode || "") || "unknown"}`);+ return { ok: false, retry: false, error: `Unsupported cad_patch mode: ${String(parsedMode || "") || "unknown"}` };}return { ok: true };};const clearWorkspace = () => {+ suppressChatSvgSyncRef.current = true;+ cad2dSvgRef.current = undefined;setCad2dSvg(undefined);setCadPlan(null);setCadImages([]);@@ -528,7 +588,6 @@ export function CadWorkspaceShell() {setCadFocusPanel(null);setChatHistory([]);setAttachments([]);- setVersionHistory([]);try {localStorage.removeItem(CAD_WORKSPACE_STORAGE_KEY);} catch {@@ -541,6 +600,11 @@ export function CadWorkspaceShell() {localStorage.removeItem(CAD_CHAT_STORAGE_KEY);} catch {}+ try {+ localStorage.removeItem("unified-ai-workspace-history-cad-v1");+ } catch {+ }+ setCadResetTick((x) => x + 1);};return (@@ -552,8 +616,10 @@ export function CadWorkspaceShell() {><div className="h-full w-full relative bg-muted/20"><CadWorkspace+ key={`cad-ws-${cadResetTick}-${cadApplyTick}`}svg2d={cad2dSvg}onSvgChange={(nextSvg) => {+ cad2dSvgRef.current = nextSvg;setCad2dSvg(nextSvg);addToHistory(nextSvg, "svg");}}@@ -581,7 +647,7 @@ export function CadWorkspaceShell() {className={cn("transition-[flex-grow,flex-basis] duration-300 ease-in-out will-change-[flex-grow,flex-basis]")}><CadChatPanel- key="cad"+ key={`cad-chat-${cadResetTick}`}systemPrompt={CAD_SYSTEM_PROMPT}initialMessages={chatHistory}onMessagesChange={setChatHistory}@@ -595,9 +661,7 @@ export function CadWorkspaceShell() {onRemoveAttachment={(id) => setAttachments((prev) => prev.filter((a) => a.id !== id))}onClearAttachments={() => setAttachments([])}onClearWorkspace={clearWorkspace}- history={versionHistory}- onRestore={handleRestore}- onClearVersionHistory={() => setVersionHistory([])}+ hideHistoryButtoncadContext={{ plan: cadPlan, svg2d: cad2dSvg }}onCodeAction={handleCadCodeAction}/>@@ -606,3 +670,4 @@ export function CadWorkspaceShell() {</ResizablePanelGroup>);}+diff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/src/workspaces/cad/chat/ChatMessageDisplay.tsxindex 024c24a..3ca3e74 100644--- a/src/workspaces/cad/chat/ChatMessageDisplay.tsx+++ b/src/workspaces/cad/chat/ChatMessageDisplay.tsx@@ -85,6 +85,42 @@ interface CadPatchToolPayload {edits: CadPatchEdit[];}+function isCadAutoApplyCodeCandidate(language: string, code: string): boolean {+ const lang = String(language || "").toLowerCase();+ const text = String(code || "").trim();+ if (!text) return false;++ if (lang === "json") {+ try {+ const parsed = JSON.parse(text);+ return (+ String(parsed?.type || "").trim().toLowerCase() === "cad_patch" &&+ String(parsed?.target || "").trim().toLowerCase() === "2d_svg"+ );+ } catch {+ return false;+ }+ }++ return false;+}++function AutoApplyCodeOnce({+ onApplyCode,+ code,+ language,+}: {+ onApplyCode?: (code: string, language?: string) => void | boolean | Promise<void | boolean>;+ code: string;+ language?: string;+}) {+ useEffect(() => {+ if (!onApplyCode) return;+ void onApplyCode(code, language);+ }, [onApplyCode, code, language]);+ return null;+}+function splitTextIntoFileSections(text: string): TextSection[] {const sections: TextSection[] = [];const filePattern = /\[(PDF|File):\s*([^\]]+)\]\n([\s\S]*?)(?=\n\n\[(PDF|File):|$)/g;@@ -450,6 +486,7 @@ export function ChatMessageDisplay({const userScrolledUpRef = useRef(false);const lastScrollTopRef = useRef(0);const lastMessageCountRef = useRef(0);+ const autoAppliedCadPatchCardRef = useRef<Set<string>>(new Set());const copyMessageToClipboard = async (messageId: string, text: string) => {try {@@ -1054,11 +1091,28 @@ export function ChatMessageDisplay({const cardKey = `${message.id}-cad-patch-${idx}-${segIdx}-${ordinal}`;const expanded = expandedCadPatchCards[cardKey] ?? true;const isStreamingPatch = status === "streaming" && isLastAssistantMessage;+ const autoApplyCode = JSON.stringify(cadPatchPayload, null, 2);+ const shouldAutoApply =+ !!onApplyCode &&+ message.role === "assistant" &&+ isLastAssistantMessage &&+ !isStreamingPatch &&+ !autoAppliedCadPatchCardRef.current.has(cardKey);+ if (shouldAutoApply) {+ autoAppliedCadPatchCardRef.current.add(cardKey);+ }return (<divkey={`cad-patch-card-${message.id}-${idx}-${segIdx}-${ordinal}`}className="my-1 rounded-xl border border-border/60 bg-muted/30 overflow-hidden">+ {shouldAutoApply && (+ <AutoApplyCodeOnce+ onApplyCode={onApplyCode}+ code={autoApplyCode}+ language="json"+ />+ )}<div className="flex items-center justify-between px-4 py-3 bg-muted/50"><div className="flex items-center gap-2"><div className="w-6 h-6 rounded-md bg-primary/10 flex items-center justify-center">@@ -1118,14 +1172,38 @@ export function ChatMessageDisplay({);}return (- <CodeBlock- key={`codeblock-${message.id}-${idx}-${segIdx}-${language}-${ordinal}`}- blockId={`${message.id}:${idx}:${segIdx}:${language}:${ordinal}`}- code={code}- language={language}- isStreaming={status === "streaming" && isLastAssistantMessage}- onApply={onApplyCode}- />+ (() => {+ const autoApplyKey = `${message.id}-code-auto-${idx}-${segIdx}-${language}-${ordinal}`;+ const shouldAutoApply =+ !!onApplyCode &&+ message.role === "assistant" &&+ isLastAssistantMessage &&+ status !== "streaming" &&+ isCadAutoApplyCodeCandidate(language, code) &&+ !autoAppliedCadPatchCardRef.current.has(autoApplyKey);+ if (shouldAutoApply) {+ autoAppliedCadPatchCardRef.current.add(autoApplyKey);+ }+ return (+ <React.Fragment key={`codeblock-wrap-${message.id}-${idx}-${segIdx}-${language}-${ordinal}`}>+ {shouldAutoApply && (+ <AutoApplyCodeOnce+ onApplyCode={onApplyCode}+ code={code}+ language={language}+ />+ )}+ <CodeBlock+ key={`codeblock-${message.id}-${idx}-${segIdx}-${language}-${ordinal}`}+ blockId={`${message.id}:${idx}:${segIdx}:${language}:${ordinal}`}+ code={code}+ language={language}+ isStreaming={status === "streaming" && isLastAssistantMessage}+ onApply={onApplyCode}+ />+ </React.Fragment>+ );+ })());})}</div>diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsxindex 81ee124..6445a5a 100644--- a/src/workspaces/cad/chat/ChatPanel.tsx+++ b/src/workspaces/cad/chat/ChatPanel.tsx@@ -21,6 +21,7 @@ import flowPatchAgentPrompt from "../../../../agent/flow/patch.md?raw";import flowReplaceAgentPrompt from "../../../../agent/flow/replace.md?raw";import { t } from "@/lib/i18n";import { useUiLanguage } from "@/lib/use-ui-language";+import { toast } from "sonner";interface Attachment {id: string;@@ -68,6 +69,85 @@ interface ChatPanelProps {}const STORAGE_KEY_PREFIX = 'chat_history_v2_';+const CAD_STORAGE_TRUNCATE_SUFFIX = "\n...[truncated]";+const CAD_STORAGE_DEFAULT_LIMITS = {+ maxMessages: 50,+ maxMessageChars: 24000,+ maxTotalChars: 240000,+};+const CAD_STORAGE_FALLBACK_LIMITS = [+ CAD_STORAGE_DEFAULT_LIMITS,+ { maxMessages: 30, maxMessageChars: 12000, maxTotalChars: 120000 },+ { maxMessages: 16, maxMessageChars: 6000, maxTotalChars: 60000 },+ { maxMessages: 8, maxMessageChars: 3000, maxTotalChars: 30000 },+];++const normalizeStoredChatMessages = (raw: any): ChatMessage[] => {+ if (!Array.isArray(raw)) return [];+ return raw+ .filter((m: any) => m && typeof m === "object")+ .map((m: any) => {+ const roleRaw = String(m.role || "");+ const role: ChatMessage["role"] =+ roleRaw === "user" || roleRaw === "assistant" || roleRaw === "system"+ ? roleRaw+ : "user";+ const content = typeof m.content === "string" ? m.content : String(m.content ?? "");+ return { role, content };+ })+ .filter((m: ChatMessage) => !!m.content);+};++const truncateForStorage = (text: string, maxChars: number) => {+ const value = String(text || "");+ if (maxChars <= 0) return "";+ if (value.length <= maxChars) return value;+ if (maxChars <= CAD_STORAGE_TRUNCATE_SUFFIX.length) {+ return value.slice(0, maxChars);+ }+ return value.slice(0, maxChars - CAD_STORAGE_TRUNCATE_SUFFIX.length) + CAD_STORAGE_TRUNCATE_SUFFIX;+};++const compactCadMessagesForStorage = (+ source: ChatMessage[],+ limits: { maxMessages: number; maxMessageChars: number; maxTotalChars: number },+): ChatMessage[] => {+ const maxMessages = Math.max(1, Number(limits.maxMessages) || 1);+ const maxMessageChars = Math.max(256, Number(limits.maxMessageChars) || 256);+ const maxTotalChars = Math.max(1024, Number(limits.maxTotalChars) || 1024);++ const normalized = normalizeStoredChatMessages(source).slice(-maxMessages).map((m) => ({+ role: m.role,+ content: truncateForStorage(m.content, maxMessageChars),+ }));++ let totalChars = normalized.reduce((sum, m) => sum + m.content.length, 0);+ while (normalized.length > 1 && totalChars > maxTotalChars) {+ const removed = normalized.shift();+ totalChars -= removed?.content.length || 0;+ }++ if (normalized.length === 1 && normalized[0].content.length > maxTotalChars) {+ normalized[0] = {+ role: normalized[0].role,+ content: truncateForStorage(normalized[0].content, maxTotalChars),+ };+ }++ return normalized;+};++const persistCadMessagesWithFallback = (storageKey: string, source: ChatMessage[]) => {+ for (const limits of CAD_STORAGE_FALLBACK_LIMITS) {+ try {+ const compacted = compactCadMessagesForStorage(source, limits);+ localStorage.setItem(storageKey, JSON.stringify(compacted));+ return true;+ } catch {+ }+ }+ return false;+};// Convert internal ChatMessage to UIMessageconst toUIMessage = (msg: ChatMessage, index: number): UIMessage => ({@@ -120,6 +200,10 @@ export function ChatPanel({const saved = localStorage.getItem(storageKey);if (saved) {try {+ if (workspaceId === "cad") {+ const parsed = normalizeStoredChatMessages(JSON.parse(saved));+ return compactCadMessagesForStorage(parsed, CAD_STORAGE_DEFAULT_LIMITS);+ }return JSON.parse(saved);} catch (e) {console.error("Failed to parse chat history", e);@@ -424,9 +508,18 @@ export function ChatPanel({// Persist messagesuseEffect(() => {- localStorage.setItem(storageKey, JSON.stringify(messages));+ if (typeof window !== "undefined") {+ if (workspaceId === "cad") {+ const ok = persistCadMessagesWithFallback(storageKey, messages);+ if (!ok) {+ console.error("Failed to persist CAD chat history after fallback trimming.");+ }+ } else {+ localStorage.setItem(storageKey, JSON.stringify(messages));+ }+ }onMessagesChange?.(messages);- }, [messages, storageKey, onMessagesChange]);+ }, [messages, storageKey, onMessagesChange, workspaceId]);const clearHistory = () => {abortControllerRef.current?.abort();@@ -483,8 +576,47 @@ export function ChatPanel({const text = String(code || "").trim();if (!text) return false;if (workspaceId === "cad") {+ const lang = String(language || "").toLowerCase();+ const hasSvgLanguageHint = lang === "svg" || lang === "xml";+ const expectsCanvasChange =+ hasSvgLanguageHint ||+ /<svg[\s/>]/i.test(text) ||+ /"type"\s*:\s*"cad_patch"/i.test(text);+ let parsedType = "";+ if (text.startsWith("{")) {+ try {+ const parsed = JSON.parse(text);+ parsedType = String(parsed?.type || "").trim().toLowerCase();+ } catch {+ }+ }const r = await runCodeAction(text, "cad");- return !!r.ok;+ if (!r.ok) {+ toast.error(r.error || (uiLang === "zh" ? "应用失败" : "Apply failed"));+ return false;+ }+ if (expectsCanvasChange && !r.svg) {+ toast.error(uiLang === "zh" ? "未检测到画布更新,请检查补丁内容是否匹配当前SVG。" : "No canvas update detected. Check whether patch matches current SVG.");+ return false;+ }+ if (r.svg) {+ toast.success(uiLang === "zh" ? "已应用到 2D 画布" : "Applied to 2D canvas");+ return true;+ }+ if (parsedType === "cad_plan") {+ toast.success(uiLang === "zh" ? "已应用方案数据" : "Plan applied");+ return true;+ }+ if (parsedType === "cad_bom") {+ toast.success(uiLang === "zh" ? "已应用物料清单" : "BOM applied");+ return true;+ }+ if (parsedType === "cad_images") {+ toast.success(uiLang === "zh" ? "已应用装修图任务" : "Render task applied");+ return true;+ }+ toast.error(uiLang === "zh" ? "未检测到可应用内容" : "No applicable CAD payload detected");+ return false;}if (workspaceId === "flow") {const r = await runCodeAction(text, "flow");@@ -495,7 +627,18 @@ export function ChatPanel({};const normalizeSvgMarkup = (text: string): string => {- const raw = String(text || "").trim();+ const decodeBasicHtmlEntities = (value: string) =>+ String(value || "")+ .replace(/</gi, "<")+ .replace(/>/gi, ">")+ .replace(/"/gi, '"')+ .replace(/'|'/gi, "'")+ .replace(/&/gi, "&");++ const original = String(text || "").trim();+ const raw = !/<svg[\s/>]/i.test(original) && /<\s*svg[\s\S]*>/i.test(original)+ ? decodeBasicHtmlEntities(original).trim()+ : original;if (!raw) return "";const start = raw.search(/<svg[\s/>]/i);if (start < 0) return "";@@ -559,6 +702,50 @@ export function ChatPanel({return "";};+ const hasCadPatchPayloadInText = (text: string): boolean => {+ const raw = String(text || "");+ if (!raw.trim()) return false;++ const isCadPatchPayload = (value: any) =>+ value &&+ typeof value === "object" &&+ String(value?.type || "").trim().toLowerCase() === "cad_patch" &&+ String(value?.target || "").trim().toLowerCase() === "2d_svg";++ const jsonRegex = /```json\s*([\s\S]*?)```/g;+ let jm: RegExpExecArray | null;+ while ((jm = jsonRegex.exec(raw))) {+ const jsonText = String(jm[1] || "").trim();+ if (!jsonText) continue;+ try {+ const parsed = JSON.parse(jsonText);+ if (isCadPatchPayload(parsed)) return true;+ } catch {+ }+ }++ const trimmed = raw.trim();+ if (trimmed.startsWith("{")) {+ try {+ const parsed = JSON.parse(trimmed);+ if (isCadPatchPayload(parsed)) return true;+ } catch {+ }+ }++ const start = raw.indexOf("{");+ const end = raw.lastIndexOf("}");+ if (start >= 0 && end > start) {+ try {+ const parsed = JSON.parse(raw.slice(start, end + 1));+ if (isCadPatchPayload(parsed)) return true;+ } catch {+ }+ }++ return /"type"\s*:\s*"cad_patch"/i.test(raw) && /"target"\s*:\s*"2d_svg"/i.test(raw);+ };+const handleAssistantResponse = async (fullResponse: string) => {if (!fullResponse) return { flowPatchFound: false, flowRetryError: null as string | null };@@ -575,11 +762,12 @@ export function ChatPanel({}if (workspaceId === "cad") {+ const hasCadPatchPayload = hasCadPatchPayloadInText(fullResponse);const svgCandidate =extractReplaceSvgFromCadPatchText(fullResponse) ||extractSvgCodeBlock(fullResponse) ||extractRawSvgBlock(fullResponse);- if (svgCandidate) {+ if (!hasCadPatchPayload && svgCandidate) {await runCodeAction(svgCandidate, "cad");}} else {@@ -1503,7 +1691,7 @@ export function ChatPanel({}}- if (!producedHasSvg2d) {+ if (!producedHasSvg2d && !cadPatchFound) {const fallbackSvg = extractReplaceSvgFromCadPatchText(toolFull) || extractSvgCodeBlock(toolFull) || extractRawSvgBlock(toolFull);if (fallbackSvg) {const r = await runCodeAction(fallbackSvg, "cad");@@ -1622,11 +1810,12 @@ export function ChatPanel({}let producedHasSvg2d = false;+ const hasCadPatchPayload = hasCadPatchPayloadInText(routedFull);const svgCandidate =extractReplaceSvgFromCadPatchText(routedFull) ||extractSvgCodeBlock(routedFull) ||extractRawSvgBlock(routedFull);- if (svgCandidate) {+ if (!hasCadPatchPayload && svgCandidate) {const svgResult = await runCodeAction(svgCandidate, "cad");producedHasSvg2d = !!svgResult.ok;}@@ -2227,7 +2416,7 @@ export function ChatPanel({}}- if (!producedHasSvg2d) {+ if (!producedHasSvg2d && !cadPatchFound) {const fallbackSvg = extractReplaceSvgFromCadPatchText(toolFull) || extractSvgCodeBlock(toolFull) || extractRawSvgBlock(toolFull);if (fallbackSvg) {const r = await runCodeAction(fallbackSvg, "cad");@@ -2346,11 +2535,12 @@ export function ChatPanel({}let producedHasSvg2d = false;+ const hasCadPatchPayload = hasCadPatchPayloadInText(routedFull);const svgCandidate =extractReplaceSvgFromCadPatchText(routedFull) ||extractSvgCodeBlock(routedFull) ||extractRawSvgBlock(routedFull);- if (svgCandidate) {+ if (!hasCadPatchPayload && svgCandidate) {const svgResult = await runCodeAction(svgCandidate, "cad");producedHasSvg2d = !!svgResult.ok;}@@ -2619,15 +2809,17 @@ export function ChatPanel({</div>{/* Dialogs */}- <HistoryDialog- showHistory={showHistory}- onToggleHistory={setShowHistory}- history={history}- onRestore={(item) => onRestore && onRestore(item)}- onClear={() => {- onClearVersionHistory?.();- }}- />+ {!hideHistoryButton && (+ <HistoryDialog+ showHistory={showHistory}+ onToggleHistory={setShowHistory}+ history={history}+ onRestore={(item) => onRestore && onRestore(item)}+ onClear={() => {+ onClearVersionHistory?.();+ }}+ />+ )}<ResetWarningModalopen={showResetWarning}onOpenChange={setShowResetWarning}diff --git a/src/workspaces/cad/workspace/CadWorkspace.tsx b/src/workspaces/cad/workspace/CadWorkspace.tsxindex 2e6aa9b..4616c65 100644--- a/src/workspaces/cad/workspace/CadWorkspace.tsx+++ b/src/workspaces/cad/workspace/CadWorkspace.tsx@@ -10,6 +10,7 @@ import { Button } from "@/workspaces/cad/ui/button";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/workspaces/cad/ui/dialog";import { PDFDocument } from "pdf-lib";import { useUiLanguage } from "@/lib/use-ui-language";+import { toast } from "sonner";interface CadWorkspaceProps {onAddToChat?: (code: string) => void;@@ -164,12 +165,15 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [const svgEditorRequestSeedRef = useRef(0);const svgEditorPendingRef = useRef<Map<string, (svg: string) => void>>(new Map());const lastCanvasRecoverAtRef = useRef(0);+ const externalSvgApplyAtRef = useRef(0);+ const EXTERNAL_APPLY_GUARD_MS = 2500;useEffect(() => {if (typeof svg2d === "string") {const normalized = normalizeSvgMarkup(svg2d);setSvgContent(normalized || null);desiredSvgRef.current = normalized;+ externalSvgApplyAtRef.current = Date.now();if (normalized) {loadSvgToEditorWithRetry(normalized);latestLoadedSvgRef.current = normalized;@@ -265,6 +269,12 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [if (type === "cad_svg_editor_load_result") {const ok = Boolean((data as any).ok);if (ok) return;+ const reason = String((data as any).reason || "").trim();+ if (reason) {+ toast.error(uiLang === "zh" ? `SVG加载失败:${reason}` : `SVG load failed: ${reason}`);+ } else {+ toast.error(uiLang === "zh" ? "SVG加载失败" : "SVG load failed");+ }const next = String(desiredSvgRef.current || "").trim();if (!next) return;window.setTimeout(() => {@@ -412,10 +422,28 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [if (!isSvgEditorReady || viewMode !== "2d") return;const timer = window.setInterval(() => {void (async () => {+ // Workspace has been externally cleared: do not rehydrate stale SVG from iframe autosync.+ const propSvg = normalizeSvgMarkup(typeof svg2d === "string" ? svg2d : "");+ const current = normalizeSvgMarkup(typeof svgContent === "string" ? svgContent : "");+ if (!propSvg && !current) {+ if (latestLoadedSvgRef.current !== EMPTY_SENTINEL) {+ postToSvgEditor({ type: "cad_svg_editor_clear" });+ latestLoadedSvgRef.current = EMPTY_SENTINEL;+ }+ return;+ }+const next = String(await requestSvgFromEditor({ preferFallbackOnEmpty: false }) || "").trim();if (!normalizeSvgMarkup(next)) return;- const current = normalizeSvgMarkup(typeof svgContent === "string" ? svgContent : "");const isEmptyCanvas = isEffectivelyEmptySvg(next);+ const desired = normalizeSvgMarkup(String(desiredSvgRef.current || ""));+ const now = Date.now();+ const inExternalApplyGuardWindow = now - externalSvgApplyAtRef.current < EXTERNAL_APPLY_GUARD_MS;+ if (inExternalApplyGuardWindow && desired && next !== desired) {+ // Ignore stale readback briefly after external SVG apply.+ loadSvgToEditorWithRetry(desired);+ return;+ }if (isEmptyCanvas && !current) {return;}@@ -434,7 +462,7 @@ export function CadWorkspace({ onAddToChat, onSvgChange, svg2d, plan, images = [})();}, 1800);return () => window.clearInterval(timer);- }, [isSvgEditorReady, viewMode, svgContent, onSvgChange]);+ }, [isSvgEditorReady, viewMode, svgContent, svg2d, onSvgChange]);const downloadBlob = (blob: Blob, filename: string) => {const link = document.createElement("a");diff --git a/src/workspaces/flow/api/log-file-parser.ts b/src/workspaces/flow/api/log-file-parser.tsnew file mode 100644index 0000000..3c292ce--- /dev/null+++ b/src/workspaces/flow/api/log-file-parser.ts@@ -0,0 +1,33 @@+import { z } from "zod"++const parserLogSchema = z.object({+ workspace: z.string().min(1).max(50),+ fileName: z.string().min(1).max(255),+ mimeType: z.string().max(200).optional(),+ fileSize: z.number().int().nonnegative().optional(),+ parserSource: z.enum([+ "third_party",+ "local",+ "third_party_fallback_local",+ ]),+ detail: z.string().max(500).optional(),+})++export async function POST(req: Request) {+ let data: z.infer<typeof parserLogSchema>+ try {+ data = parserLogSchema.parse(await req.json())+ } catch {+ return Response.json(+ { success: false, error: "Invalid input" },+ { status: 400 },+ )+ }++ const ts = new Date().toISOString()+ console.log(+ `[file-parser] ts=${ts} workspace=${data.workspace} parser=${data.parserSource} file="${data.fileName}" mime="${data.mimeType || ""}" size=${data.fileSize || 0} detail="${data.detail || ""}"`,+ )+ return Response.json({ success: true })+}+diff --git a/src/workspaces/flow/api/third-party-parser.ts b/src/workspaces/flow/api/third-party-parser.tsnew file mode 100644index 0000000..5239e96--- /dev/null+++ b/src/workspaces/flow/api/third-party-parser.ts@@ -0,0 +1,225 @@+import JSZip from "jszip"+import { z } from "zod"++const requestSchema = z.object({+ fileName: z.string().min(1).max(255),+ fileType: z.string().max(200).optional(),+ fileBase64: z.string().min(1),+ apiToken: z.string().min(1),+ apiBase: z.string().url().optional(),+ maxAssets: z.number().int().positive().max(50).optional(),+ maxWaitMs: z.number().int().positive().max(300000).optional(),+})++const getMimeByExt = (name: string) => {+ const lower = String(name || "").toLowerCase()+ if (lower.endsWith(".png")) return "image/png"+ if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg"+ if (lower.endsWith(".webp")) return "image/webp"+ if (lower.endsWith(".gif")) return "image/gif"+ if (lower.endsWith(".bmp")) return "image/bmp"+ if (lower.endsWith(".svg")) return "image/svg+xml"+ return "image/png"+}++const normalizeMineruImagePath = (rawPath: string) => {+ let p = String(rawPath || "").trim().replace(/^['"]|['"]$/g, "")+ if (!p) return ""+ p = p.replace(/\\/g, "/")+ if (p.startsWith("/")) p = p.slice(1)+ if (p.startsWith("file/")) p = p.slice(5)+ if (p.startsWith("files/")) p = p.slice(6)+ return p+}++const findZipImageEntry = (zip: JSZip, relPath: string) => {+ const target = normalizeMineruImagePath(relPath).toLowerCase()+ if (!target) return null+ const entries = Object.values(zip.files).filter((f) => !f.dir)+ const exact = entries.find(+ (e) =>+ String(e.name || "").replace(/\\/g, "/").toLowerCase() === target,+ )+ if (exact) return exact+ const suffix = `/${target}`+ return (+ entries.find((e) => {+ const name = String(e.name || "").replace(/\\/g, "/").toLowerCase()+ return name.endsWith(suffix) || name.endsWith(target)+ }) || null+ )+}++const uint8ToBase64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64")++export async function POST(req: Request) {+ let data: z.infer<typeof requestSchema>+ try {+ data = requestSchema.parse(await req.json())+ } catch {+ return Response.json(+ { success: false, error: "Invalid input" },+ { status: 400 },+ )+ }++ const apiBase = String(data.apiBase || "https://mineru.net")+ .trim()+ .replace(/\/+$/, "")+ const token = String(data.apiToken || "").trim()+ const maxAssets = Math.max(1, data.maxAssets ?? 10)+ const maxWaitMs = Math.max(5000, data.maxWaitMs ?? 120000)+ const fileBytes = Buffer.from(data.fileBase64, "base64")++ const reqHeaders: Record<string, string> = {+ "Content-Type": "application/json",+ Authorization: `Bearer ${token}`,+ }++ try {+ const uploadUrlResp = await fetch(`${apiBase}/api/v4/file-urls/batch`, {+ method: "POST",+ headers: reqHeaders,+ body: JSON.stringify({+ files: [{ name: data.fileName }],+ model_version: "vlm",+ }),+ })+ if (!uploadUrlResp.ok) {+ throw new Error(+ `Third-party parser request failed: ${uploadUrlResp.status}`,+ )+ }+ const uploadPayload = await uploadUrlResp.json()+ if (uploadPayload?.code !== 0) {+ throw new Error(+ String(+ uploadPayload?.msg ||+ "Third-party parser get upload URL failed",+ ),+ )+ }++ const batchId = String(uploadPayload?.data?.batch_id || "")+ const uploadUrl = String(uploadPayload?.data?.file_urls?.[0] || "")+ if (!batchId || !uploadUrl) {+ throw new Error("Third-party parser missing batch id or upload URL")+ }++ const uploadResp = await fetch(uploadUrl, {+ method: "PUT",+ body: fileBytes,+ })+ if (!uploadResp.ok) {+ const body = await uploadResp.text().catch(() => "")+ throw new Error(+ `Third-party parser upload failed: ${uploadResp.status}${body ? ` body=${body.slice(0, 300)}` : ""}`,+ )+ }++ const resultUrl = `${apiBase}/api/v4/extract-results/batch/${batchId}`+ const start = Date.now()+ let fullZipUrl = ""+ while (Date.now() - start < maxWaitMs) {+ const pollResp = await fetch(resultUrl, {+ headers: { Authorization: `Bearer ${token}` },+ })+ if (!pollResp.ok) {+ throw new Error(`Third-party parser poll failed: ${pollResp.status}`)+ }+ const pollPayload = await pollResp.json()+ if (pollPayload?.code !== 0) {+ throw new Error(+ String(+ pollPayload?.msg || "Third-party parser poll returned error",+ ),+ )+ }++ const extractResult = pollPayload?.data?.extract_result?.[0]+ const state = String(extractResult?.state || "")+ if (state === "done") {+ fullZipUrl = String(extractResult?.full_zip_url || "")+ break+ }+ if (state === "failed") {+ throw new Error(+ String(extractResult?.err_msg || "Third-party parser extraction failed"),+ )+ }+ await new Promise((r) => setTimeout(r, 2000))+ }+ if (!fullZipUrl) throw new Error("Third-party parser timeout")++ const zipResp = await fetch(fullZipUrl)+ if (!zipResp.ok) {+ throw new Error(+ `Third-party parser result download failed: ${zipResp.status}`,+ )+ }+ const zipArrayBuffer = await zipResp.arrayBuffer()+ const zip = await JSZip.loadAsync(zipArrayBuffer)++ const markdownEntry =+ Object.values(zip.files).find(+ (f) => !f.dir && /\.md$/i.test(String(f.name || "")),+ ) || null+ const markdown = markdownEntry ? await markdownEntry.async("string") : ""++ const usedImageNames = new Set<string>()+ const assets: Array<{ dataUrl: string; textHint: string }> = []++ if (markdown) {+ const imageRe = /!\[([^\]]*)\]\(([^)]+)\)/g+ let match: RegExpExecArray | null+ while ((match = imageRe.exec(markdown))) {+ if (assets.length >= maxAssets) break+ const alt = String(match[1] || "").trim()+ const relPath = String(match[2] || "").trim()+ if (!relPath || /^https?:\/\//i.test(relPath)) continue++ const entry = findZipImageEntry(zip, relPath)+ if (!entry) continue+ const entryName = String(entry.name || "")+ if (usedImageNames.has(entryName)) continue++ const bytes = await entry.async("uint8array")+ const mime = getMimeByExt(entryName)+ assets.push({+ dataUrl: `data:${mime};base64,${uint8ToBase64(bytes)}`,+ textHint: alt,+ })+ usedImageNames.add(entryName)+ }+ }++ if (assets.length < maxAssets) {+ const imageEntries = Object.values(zip.files)+ .filter((f) => !f.dir)+ .filter((f) =>+ /\.(png|jpg|jpeg|webp|gif|bmp|svg)$/i.test(String(f.name || "")),+ )+ for (const entry of imageEntries) {+ if (assets.length >= maxAssets) break+ const entryName = String(entry.name || "")+ if (usedImageNames.has(entryName)) continue+ const bytes = await entry.async("uint8array")+ const mime = getMimeByExt(entryName)+ assets.push({+ dataUrl: `data:${mime};base64,${uint8ToBase64(bytes)}`,+ textHint: "",+ })+ usedImageNames.add(entryName)+ }+ }++ return Response.json({ success: true, assets })+ } catch (error) {+ const msg = error instanceof Error ? error.message : "Unknown error"+ console.error("[third-party-parser] failed:", msg)+ return Response.json(+ { success: false, error: msg },+ { status: 500 },+ )+ }+}diff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/src/workspaces/flow/next/components/chat-panel.tsxindex 88de6bf..6c0c931 100644--- a/src/workspaces/flow/next/components/chat-panel.tsx+++ b/src/workspaces/flow/next/components/chat-panel.tsx@@ -16,8 +16,10 @@ import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"import { getAIConfig } from "@/workspaces/flow/next/lib/ai-config"import {extractPdfText,+ extractWordText,extractTextFileContent,isPdfFile,+ isWordFile,isTextFile,} from "@/workspaces/flow/next/lib/pdf-utils"import { type FileData, useFileProcessor } from "@/workspaces/flow/next/lib/use-file-processor"@@ -146,7 +148,7 @@ export default function ChatPanel({}// File processing using extracted hook- const { files, pdfData, handleFileChange, setFiles } = useFileProcessor()+ const { files, pdfData, handleFileChange, setFiles } = useFileProcessor("flow")const [showHistory, setShowHistory] = useState(false)const [, setAccessCodeRequired] = useState(false)@@ -619,7 +621,7 @@ Please fix the XML issues. Ensure you are editing exact lines from the current Xtry {if (isDrawioReady) {try {- chartXml = await onFetchChart()+ chartXml = await onFetchChart(false)} catch (error) {console.warn("Failed to fetch chart data, using current state:", error)}@@ -915,7 +917,11 @@ Please fix the XML issues. Ensure you are editing exact lines from the current XextractedText?: string}>}> => {- let userText = baseText+ // Remove previously appended file blocks (legacy or previous retries)+ // to avoid duplicating [File: ...] sections in a new send.+ let userText = String(baseText || "")+ .replace(/\n\n\[(PDF|File):\s*[^\]]+\]\n[\s\S]*$/i, "")+ .trim()const uploadedFiles: Array<{name: stringmediaType: string@@ -923,7 +929,12 @@ Please fix the XML issues. Ensure you are editing exact lines from the current XextractedText?: string}> = []+ const seenFileKeys = new Set<string>()for (const file of files) {+ const dedupeKey = `${file.name}__${file.size}__${file.lastModified}`+ if (seenFileKeys.has(dedupeKey)) continue+ seenFileKeys.add(dedupeKey)+const reader = new FileReader()const dataUrl = await new Promise<string>((resolve) => {reader.onload = () => resolve(reader.result as string)@@ -937,7 +948,7 @@ Please fix the XML issues. Ensure you are editing exact lines from the current X})continue}- if (isPdfFile(file) || isTextFile(file) || file.name.toLowerCase().endsWith(".docx")) {+ if (isPdfFile(file) || isTextFile(file) || isWordFile(file)) {const extracted = pdfData.get(file)let extractedText =extracted && !extracted.isExtracting && extracted.text@@ -950,6 +961,8 @@ Please fix the XML issues. Ensure you are editing exact lines from the current Xtry {if (isPdfFile(file)) {extractedText = await extractPdfText(file)+ } else if (isWordFile(file)) {+ extractedText = await extractWordText(file)} else if (isTextFile(file)) {extractedText = await extractTextFileContent(file)}@@ -967,7 +980,10 @@ Please fix the XML issues. Ensure you are editing exact lines from the current XdataUrl,extractedText,})- userText += `\n\n[File: ${file.name}]\n(Uploaded and parsed by backend)`+ const normalizedExtracted = String(extractedText || "").trim()+ userText += `\n\n[File: ${file.name}]\n${+ normalizedExtracted || "(Failed to read content)"+ }`}}diff --git a/src/workspaces/flow/next/contexts/diagram-context.tsx b/src/workspaces/flow/next/contexts/diagram-context.tsxindex 59b0553..80ad93b 100644--- a/src/workspaces/flow/next/contexts/diagram-context.tsx+++ b/src/workspaces/flow/next/contexts/diagram-context.tsx@@ -39,15 +39,38 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {>([])const [isDrawioReady, setIsDrawioReady] = useState(false)const hasCalledOnLoadRef = useRef(false)+ const latestSvgRef = useRef<string>("")const drawioRef = useRef<DrawIoEmbedRef | null>(null)const resolverRef = useRef<((value: string) => void) | null>(null)// Track if we're expecting an export for history (user-initiated)const expectHistoryExportRef = useRef<boolean>(false)+ const isEffectivelyEmptyDiagramXml = (xml: string) => {+ const safeXml = String(xml || "").trim()+ if (!safeXml) return true+ try {+ const doc = new DOMParser().parseFromString(safeXml, "text/xml")+ if (doc.querySelector("parsererror")) return false+ const cells = Array.from(doc.querySelectorAll("mxCell"))+ const meaningfulCells = cells.filter((cell) => {+ const id = String(cell.getAttribute("id") || "")+ if (id === "0" || id === "1") return false+ return true+ })+ return meaningfulCells.length === 0+ } catch {+ return false+ }+ }+const pushHistorySnapshot = (xml: string, svg?: string) => {const safeXml = String(xml || "").trim()if (!safeXml) return- const safeSvg = typeof svg === "string" ? svg : latestSvg+ if (isEffectivelyEmptyDiagramXml(safeXml)) return+ const safeSvg =+ typeof svg === "string"+ ? svg+ : latestSvgRef.current || latestSvgsetDiagramHistory((prev) => {const last = prev[prev.length - 1]if (last && last.xml === safeXml) return prev@@ -139,6 +162,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {const extractedXML = extractDiagramXML(data.data)setChartXML(extractedXML)setLatestSvg(data.data)+ latestSvgRef.current = String(data.data || "")// Only add to history if this was a user-initiated exportif (expectHistoryExportRef.current) {@@ -157,6 +181,7 @@ export function DiagramProvider({ children }: { children: React.ReactNode }) {// Skip validation for trusted internal template (loadDiagram also sets chartXML)loadDiagram(emptyDiagram, true)setLatestSvg("")+ latestSvgRef.current = ""setDiagramHistory([])}diff --git a/src/workspaces/flow/next/lib/pdf-utils.ts b/src/workspaces/flow/next/lib/pdf-utils.tsindex bba5d76..c0a8077 100644--- a/src/workspaces/flow/next/lib/pdf-utils.ts+++ b/src/workspaces/flow/next/lib/pdf-utils.ts@@ -1467,29 +1467,6 @@ export async function extractWordVisualAssets(return assets}-const normalizeMineruImagePath = (rawPath: string) => {- let p = String(rawPath || "").trim().replace(/^['"]|['"]$/g, "")- if (!p) return ""- p = p.replace(/\\/g, "/")- if (p.startsWith("/")) p = p.slice(1)- if (p.startsWith("file/")) p = p.slice(5)- if (p.startsWith("files/")) p = p.slice(6)- return p-}--const findZipImageEntry = (zip: JSZip, relPath: string) => {- const target = normalizeMineruImagePath(relPath).toLowerCase()- if (!target) return null- const entries = Object.values(zip.files).filter((f) => !f.dir)- const exact = entries.find((e) => String(e.name || "").replace(/\\/g, "/").toLowerCase() === target)- if (exact) return exact- const suffix = `/${target}`- return entries.find((e) => {- const name = String(e.name || "").replace(/\\/g, "/").toLowerCase()- return name.endsWith(suffix) || name.endsWith(target)- }) || null-}-export async function extractThirdPartyVisualAssets(file: File,options: { apiToken: string; apiBase?: string; maxAssets?: number; maxWaitMs?: number }@@ -1499,133 +1476,47 @@ export async function extractThirdPartyVisualAssets(const apiBase = String(options.apiBase || "https://mineru.net").trim().replace(/\/+$/, "")const maxAssets = Math.max(1, options.maxAssets ?? 10)const maxWaitMs = Math.max(5000, options.maxWaitMs ?? 120000)-- const reqHeaders: Record<string, string> = {- "Content-Type": "application/json",- Authorization: `Bearer ${token}`,- }-- const uploadUrlResp = await fetch(`${apiBase}/api/v4/file-urls/batch`, {+ const fileBuf = new Uint8Array(await file.arrayBuffer())+ const resp = await fetch("/api/third-party-parser", {method: "POST",- headers: reqHeaders,+ headers: { "Content-Type": "application/json" },body: JSON.stringify({- files: [{ name: file.name }],- model_version: "vlm",+ fileName: file.name,+ fileType: file.type || "",+ fileBase64: bytesToBase64(fileBuf),+ apiToken: token,+ apiBase,+ maxAssets,+ maxWaitMs,}),})- if (!uploadUrlResp.ok) {- throw new Error(`Third-party parser request failed: ${uploadUrlResp.status}`)- }- const uploadPayload = await uploadUrlResp.json()- if (uploadPayload?.code !== 0) {- throw new Error(String(uploadPayload?.msg || "Third-party parser get upload URL failed"))- }-- const batchId = String(uploadPayload?.data?.batch_id || "")- const uploadUrl = String(uploadPayload?.data?.file_urls?.[0] || "")- if (!batchId || !uploadUrl) throw new Error("Third-party parser missing batch id or upload URL")-- const uploadResp = await fetch(uploadUrl, {- method: "PUT",- body: file,- })- if (!uploadResp.ok) throw new Error(`Third-party parser upload failed: ${uploadResp.status}`)-- const resultUrl = `${apiBase}/api/v4/extract-results/batch/${batchId}`- const start = Date.now()- let fullZipUrl = ""- while (Date.now() - start < maxWaitMs) {- const pollResp = await fetch(resultUrl, { headers: { Authorization: `Bearer ${token}` } })- if (!pollResp.ok) throw new Error(`Third-party parser poll failed: ${pollResp.status}`)- const pollPayload = await pollResp.json()- if (pollPayload?.code !== 0) {- throw new Error(String(pollPayload?.msg || "Third-party parser poll returned error"))- }-- const extractResult = pollPayload?.data?.extract_result?.[0]- const state = String(extractResult?.state || "")- if (state === "done") {- fullZipUrl = String(extractResult?.full_zip_url || "")- break- }- if (state === "failed") {- throw new Error(String(extractResult?.err_msg || "Third-party parser extraction failed"))- }- await new Promise((r) => setTimeout(r, 2000))- }- if (!fullZipUrl) throw new Error("Third-party parser timeout")-- const zipResp = await fetch(fullZipUrl)- if (!zipResp.ok) throw new Error(`Third-party parser result download failed: ${zipResp.status}`)- const zipArrayBuffer = await zipResp.arrayBuffer()- const zip = await JSZip.loadAsync(zipArrayBuffer)-- const markdownEntry =- Object.values(zip.files).find((f) => !f.dir && /\.md$/i.test(String(f.name || ""))) || null- const markdown = markdownEntry ? await markdownEntry.async("string") : ""-- const usedImageNames = new Set<string>()- const assets: ExtractedVisualAsset[] = []-- if (markdown) {- const imageRe = /!\[([^\]]*)\]\(([^)]+)\)/g- let match: RegExpExecArray | null- while ((match = imageRe.exec(markdown))) {- if (assets.length >= maxAssets) break- const alt = String(match[1] || "").trim()- const relPath = String(match[2] || "").trim()- if (!relPath || /^https?:\/\//i.test(relPath)) continue-- const entry = findZipImageEntry(zip, relPath)- if (!entry) continue- const entryName = String(entry.name || "")- if (usedImageNames.has(entryName)) continue-- try {- const bytes = await entry.async("uint8array")- const mime = getMimeByExt(entryName)- assets.push({- id: `third-party-${file.name}-${assets.length + 1}`,- sourceFileName: file.name,- sourceType: "third_party",- order: assets.length + 1,- dataUrl: `data:${mime};base64,${bytesToBase64(bytes)}`,- textHint: alt,- })- usedImageNames.add(entryName)- } catch (e) {- console.error("Failed to load third-party extracted image", entryName, e)- }+ if (!resp.ok) {+ let detail = ""+ try {+ const errPayload = await resp.json()+ detail = String(errPayload?.error || "")+ } catch {}+ throw new Error(+ `Third-party parser proxy failed: ${resp.status}${detail ? ` - ${detail}` : ""}`,+ )}-- if (assets.length < maxAssets) {- const imageEntries = Object.values(zip.files)- .filter((f) => !f.dir)- .filter((f) => /\.(png|jpg|jpeg|webp|gif|bmp|svg)$/i.test(String(f.name || "")))- for (const entry of imageEntries) {- if (assets.length >= maxAssets) break- const entryName = String(entry.name || "")- if (usedImageNames.has(entryName)) continue- try {- const bytes = await entry.async("uint8array")- const mime = getMimeByExt(entryName)- assets.push({- id: `third-party-${file.name}-${assets.length + 1}`,- sourceFileName: file.name,- sourceType: "third_party",- order: assets.length + 1,- dataUrl: `data:${mime};base64,${bytesToBase64(bytes)}`,- textHint: "",- })- usedImageNames.add(entryName)- } catch (e) {- console.error("Failed to load fallback image from third-party zip", entryName, e)- }- }+ const payload = await resp.json()+ if (!payload?.success) {+ throw new Error(String(payload?.error || "Third-party parser proxy error"))}-- return assets+ const items = Array.isArray(payload?.assets) ? payload.assets : []+ return items+ .filter((x: any) => x && typeof x.dataUrl === "string" && x.dataUrl.startsWith("data:image"))+ .slice(0, maxAssets)+ .map((x: any, idx: number) => ({+ id: `third-party-${file.name}-${idx + 1}`,+ sourceFileName: file.name,+ sourceType: "third_party",+ order: idx + 1,+ dataUrl: String(x.dataUrl),+ textHint: typeof x.textHint === "string" ? x.textHint : "",+ }))}diff --git a/src/workspaces/flow/next/lib/use-file-processor.tsx b/src/workspaces/flow/next/lib/use-file-processor.tsxindex 5ccb70e..c052c53 100644--- a/src/workspaces/flow/next/lib/use-file-processor.tsx+++ b/src/workspaces/flow/next/lib/use-file-processor.tsx@@ -30,11 +30,38 @@ export interface FileData {visualAssets?: ExtractedVisualAsset[]}+type ParserSource = "third_party" | "local" | "third_party_fallback_local"++const reportFileParserSource = async (params: {+ workspace: "flow" | "ppt" | "unknown"+ file: File+ parserSource: ParserSource+ detail?: string+}) => {+ try {+ await fetch("/api/log-file-parser", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ workspace: params.workspace,+ fileName: params.file.name,+ mimeType: params.file.type || "",+ fileSize: params.file.size || 0,+ parserSource: params.parserSource,+ detail: params.detail || "",+ }),+ keepalive: true,+ })+ } catch (e) {+ console.warn("Failed to report file parser source", e)+ }+}+/*** Hook for processing file uploads, especially PDFs and text files.* Handles text extraction, character limit validation, and cleanup.*/-export function useFileProcessor() {+export function useFileProcessor(workspace: "flow" | "ppt" | "unknown" = "unknown") {const [files, setFiles] = useState<File[]>([])const [pdfData, setPdfData] = useState<Map<File, FileData>>(new Map())@@ -68,7 +95,10 @@ export function useFileProcessor() {const parserToken = String(aiConfig.fileParserApiToken || "").trim()const parserBase = "https://mineru.net"const supportsThirdParty = isPdfFile(file) || isWordFile(file)- const useThirdPartyVisualParser = Boolean(parserToken) && supportsThirdParty+ // Rule: if MinerU token is configured, prefer third-party parser;+ // otherwise use local extraction.+ const useThirdPartyVisualParser =+ Boolean(parserToken) && supportsThirdPartylet text: stringlet visualAssets: ExtractedVisualAsset[] = []@@ -80,12 +110,30 @@ export function useFileProcessor() {apiBase: parserBase,apiToken: parserToken,})+ void reportFileParserSource({+ workspace,+ file,+ parserSource: "third_party",+ detail: "pdf",+ })} catch (e) {console.error("Third-party parser failed, fallback to local PDF extraction:", e)visualAssets = await extractPdfVisualAssets(file)+ void reportFileParserSource({+ workspace,+ file,+ parserSource: "third_party_fallback_local",+ detail: "pdf",+ })}} else {visualAssets = await extractPdfVisualAssets(file)+ void reportFileParserSource({+ workspace,+ file,+ parserSource: "local",+ detail: "pdf",+ })}} else if (isWordFile(file)) {text = await extractWordText(file)@@ -95,12 +143,30 @@ export function useFileProcessor() {apiBase: parserBase,apiToken: parserToken,})+ void reportFileParserSource({+ workspace,+ file,+ parserSource: "third_party",+ detail: "word",+ })} catch (e) {console.error("Third-party parser failed, fallback to local Word extraction:", e)visualAssets = await extractWordVisualAssets(file)+ void reportFileParserSource({+ workspace,+ file,+ parserSource: "third_party_fallback_local",+ detail: "word",+ })}} else {visualAssets = await extractWordVisualAssets(file)+ void reportFileParserSource({+ workspace,+ file,+ parserSource: "local",+ detail: "word",+ })}} else if (isZipFile(file)) {// LaTeX bundle (.zip): parse tex + includegraphics to extract original figures.diff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/src/workspaces/ppt/PptWorkspaceShell.tsxindex 502193d..1ea869a 100644--- a/src/workspaces/ppt/PptWorkspaceShell.tsx+++ b/src/workspaces/ppt/PptWorkspaceShell.tsx@@ -32,6 +32,7 @@ const PPT_CHAT_STORAGE_KEY = "chat_history_v2_ppt";export function PptWorkspaceShell() {const uiLang = useUiLanguage();+ const didMountRef = useRef(false);const [attachments, setAttachments] = useState<Attachment[]>([]);const [pptIncomingEdit, setPptIncomingEdit] = useState<{ id: string; payload: string } | null>(null);const [pptDraftSlides, setPptDraftSlides] = useState<@@ -66,6 +67,26 @@ export function PptWorkspaceShell() {}}, [versionHistory]);+ useEffect(() => {+ if (!didMountRef.current) {+ didMountRef.current = true;+ return;+ }+ if (pptStage !== "start") return;+ setChatHistory([]);+ setAttachments([]);+ setVersionHistory([]);+ setPptDraftSlides([]);+ try {+ localStorage.removeItem(PPT_CHAT_STORAGE_KEY);+ } catch {+ }+ try {+ localStorage.removeItem(PPT_HISTORY_STORAGE_KEY);+ } catch {+ }+ }, [pptStage]);+useEffect(() => {if (pptChatLocked && isChatCollapsed) {setIsChatCollapsed(false);@@ -191,6 +212,10 @@ export function PptWorkspaceShell() {localStorage.removeItem(PPT_CHAT_STORAGE_KEY);} catch {}+ try {+ localStorage.removeItem(PPT_HISTORY_STORAGE_KEY);+ } catch {+ }setPptResetTick((x) => x + 1);};diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/src/workspaces/ppt/workspace/PptWorkspace.tsxindex 366f2be..5f32b9f 100644--- a/src/workspaces/ppt/workspace/PptWorkspace.tsx+++ b/src/workspaces/ppt/workspace/PptWorkspace.tsx@@ -32,20 +32,59 @@ interface PptData {const localizeLayoutHint = (layout: string, lang: "zh" | "en") => {const raw = String(layout || "").trim();- if (!raw || lang !== "zh") return raw;- const key = raw.toLowerCase().replace(/\s+/g, "");- const map: Record<string, string> = {- "cover": "封面页",- "title+bullets": "标题+要点",- "title+bullet": "标题+要点",- "two-column": "双栏布局",- "twocolumn": "双栏布局",- "left-text-right-image": "左文右图",- "lefttextrightimage": "左文右图",- "title-and-content": "标题+内容",- "titleandcontent": "标题+内容",+ if (!raw) return raw;+ const key = raw+ .toLowerCase()+ .replace(/\s+/g, "")+ .replace(/[+_/-]/g, "");+ const map: Record<string, { zh: string; en: string }> = {+ cover: { zh: "封面页", en: "Cover" },+ titlebullets: { zh: "标题+要点", en: "Title + Bullets" },+ titlebullet: { zh: "标题+要点", en: "Title + Bullets" },+ twocolumn: { zh: "双栏布局", en: "Two-column" },+ lefttextrightimage: { zh: "左文右图", en: "Left text, right image" },+ titleandcontent: { zh: "标题+内容", en: "Title + Content" },+ 封面页: { zh: "封面页", en: "Cover" },+ 标题要点: { zh: "标题+要点", en: "Title + Bullets" },+ 双栏布局: { zh: "双栏布局", en: "Two-column" },+ 左文右图: { zh: "左文右图", en: "Left text, right image" },+ 标题内容: { zh: "标题+内容", en: "Title + Content" },};- return map[key] || raw;+ const hit = map[key];+ if (!hit) return raw;+ return lang === "zh" ? hit.zh : hit.en;+};++const parseSlideNo = (value: string): number | null => {+ const raw = String(value || "").trim();+ if (!raw) return null;+ const m1 = raw.match(/^(?:slide|page)[\s_-]*(\d+)$/i);+ if (m1) return Number(m1[1]);+ const m2 = raw.match(/^第\s*(\d+)\s*页$/i);+ if (m2) return Number(m2[1]);+ const m3 = raw.match(/^(\d+)$/);+ if (m3) return Number(m3[1]);+ return null;+};++const normalizeLocalizedSlideTitle = (+ title: string,+ uiLang: "zh" | "en",+ fallbackNo?: number | null+) => {+ const raw = String(title || "").trim();+ const fromTitle = parseSlideNo(raw);+ const no = fromTitle || (typeof fallbackNo === "number" ? fallbackNo : null);+ if (uiLang === "zh") {+ if (/^(?:slide|page)(?:\s|_|-)*\d*$/i.test(raw) || /^slide$/i.test(raw) || /^page$/i.test(raw)) {+ return no ? `第 ${no} 页` : "幻灯片";+ }+ return raw;+ }+ if (/^第\s*\d+\s*页$/i.test(raw)) {+ return no ? `Slide ${no}` : "Slide";+ }+ return raw;};interface PptWorkspaceProps {@@ -251,7 +290,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChvisualAssets: referenceVisualAssetsRaw,handleFileChange: handleReferenceFileChange,setFiles: setReferenceUploadFiles- } = useFlowFileProcessor();+ } = useFlowFileProcessor("ppt");const [referencePreviewOpen, setReferencePreviewOpen] = useState(false);const [referencePreviewFile, setReferencePreviewFile] = useState<ReferenceFile | null>(null);const [slideMaterials, setSlideMaterials] = useState<Record<string, SlideMaterialImage[]>>(() => {@@ -320,7 +359,8 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChif (typeof window === "undefined") return;try {localStorage.setItem(PPT_TEMPLATE_UPLOADS_KEY, JSON.stringify(uploadedTemplates));- } catch {+ } catch (e) {+ console.error("Failed to persist uploaded PPT templates", e);}}, [uploadedTemplates]);@@ -478,7 +518,30 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChawait addUploadedTemplates(files);};- const addGeneratedTemplate = (dataUrl: string) => {+ const toDataUrlIfNeeded = async (url: string) => {+ const raw = String(url || "").trim();+ if (!raw) return "";+ if (raw.startsWith("data:image")) return raw;+ try {+ const resp = await fetch(raw);+ const blob = await resp.blob();+ return await new Promise<string>((resolve) => {+ const reader = new FileReader();+ reader.onerror = () => resolve("");+ reader.onloadend = () => resolve(typeof reader.result === "string" ? reader.result : "");+ reader.readAsDataURL(blob);+ });+ } catch (e) {+ console.error("Failed to convert generated template to data url", e);+ return "";+ }+ };++ const addGeneratedTemplate = async (imageUrl: string) => {+ const dataUrl = await toDataUrlIfNeeded(imageUrl);+ if (!dataUrl || !dataUrl.startsWith("data:image")) {+ throw new Error(tr("生成模板持久化失败:无法读取图片数据", "Failed to persist generated template: cannot read image data"));+ }const id = `generated-${Date.now()}-${Math.random().toString(16).slice(2)}`;const name = `${tr("AI 模板", "AI Template")}-${Date.now()}`;const created: UploadTemplate = { id, name, dataUrl };@@ -501,7 +564,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChalert(tr("模板生成失败,请重试", "Template generation failed. Please retry."));return;}- addGeneratedTemplate(imageUrl);+ await addGeneratedTemplate(imageUrl);setTemplateGeneratorRequirement("");setTemplateGeneratorOpen(false);} catch (e: any) {@@ -522,13 +585,29 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChconst [isApplyingEdits, setIsApplyingEdits] = useState(false);+ const setSlidesKeepingSelection = (nextSlides: SlideData[]) => {+ const currentId = localSlides[currentSlideIndex]?.id;+ setLocalSlides(nextSlides);+ if (!Array.isArray(nextSlides) || nextSlides.length === 0) {+ setCurrentSlideIndex(0);+ return;+ }+ if (currentId) {+ const nextIdx = nextSlides.findIndex((s) => s.id === currentId);+ if (nextIdx >= 0) {+ setCurrentSlideIndex(nextIdx);+ return;+ }+ }+ setCurrentSlideIndex((prev) => {+ const safePrev = Number.isFinite(prev) ? Math.max(0, Math.floor(prev)) : 0;+ return Math.min(safePrev, nextSlides.length - 1);+ });+ };+useEffect(() => {if (data && data.slides && data.slides.length > 0) {- setLocalSlides(data.slides);- // Reset to first slide if new data comes in- if (data.slides) {- setCurrentSlideIndex(0);- }+ setSlidesKeepingSelection(data.slides);setCreationStep('done');onPptReadyChange?.(true);}@@ -545,20 +624,49 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChconst toolTypeRaw = String(parsed?.type || "").trim().toLowerCase();if (toolTypeRaw && toolTypeRaw !== "ppt_edit") return;- const incomingSlides: any[] = Array.isArray(parsed?.slides)+ const incomingSlidesRaw: any[] = Array.isArray(parsed?.slides)? parsed.slides: Array.isArray(parsed)? parsed: [];- if (incomingSlides.length === 0) return;+ if (incomingSlidesRaw.length === 0) return;const uploadedImages: string[] = Array.isArray(parsed?.uploadedImages) ? parsed.uploadedImages : [];const existingById = new Map(localSlides.map((s) => [s.id, s] as const));+ const getCurrentSlideImageUrlById = (slideId: string) => {+ const versions = imageVersions[slideId] || [];+ const currentVersion = currentImageVersionId[slideId];+ const currentUrl = currentVersion ? versions.find((v) => v.id === currentVersion)?.url : generatedImages[slideId];+ return String(currentUrl || "").trim();+ };++ const existing = localSlides.length > 0 ? [...localSlides] : [];+ const resolveIncomingSlideId = (inc: any): string => {+ const rawId = String(inc?.id || "").trim();+ if (rawId && existing.some((s) => s.id === rawId)) return rawId;+ const fromIdNo = parseSlideNo(rawId);+ if (fromIdNo && existing[fromIdNo - 1]) return existing[fromIdNo - 1].id;+ const titleNo = parseSlideNo(String(inc?.title || "").trim());+ if (titleNo && existing[titleNo - 1]) return existing[titleNo - 1].id;+ return rawId;+ };++ const incomingSlides: any[] = incomingSlidesRaw+ .map((inc) => {+ const resolvedId = resolveIncomingSlideId(inc);+ if (!resolvedId) return null;+ return { ...inc, id: resolvedId };+ })+ .filter(Boolean);++ if (incomingSlides.length === 0) return;const toSlideData = (inc: any, fallbackId: string, source?: SlideData): SlideData => ({id: fallbackId,- title: typeof inc?.title === "string" ? inc.title : (source?.title || tr("幻灯片", "Slide")),+ title: typeof inc?.title === "string"+ ? normalizeLocalizedSlideTitle(inc.title, uiLang as "zh" | "en", parseSlideNo(fallbackId))+ : (source?.title || tr("幻灯片", "Slide")),content: Array.isArray(inc?.content) ? inc.content.map((x: any) => String(x)) : (source?.content || []),description: typeof inc?.description === "string" ? inc.description : source?.description,note: typeof inc?.note === "string" ? inc.note : source?.note,@@ -568,13 +676,16 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChlet mergedSlides: SlideData[] = localSlides.slice();let mergedIncomingSlides = incomingSlides.slice();mergedSlides = (() => {- const existing = localSlides.length > 0 ? [...localSlides] : [];const byId = new Map(existing.map((s) => [s.id, s] as const));const order: string[] = existing.map((s) => s.id);for (const inc of incomingSlides) {const id = String(inc?.id || "");if (!id) continue;+ if (creationStep === "done" && !byId.has(id)) {+ // In slide-edit stage, unknown ids should not append new pages.+ continue;+ }const next: SlideData = toSlideData(inc, id, byId.get(id));byId.set(id, next);if (!order.includes(id)) order.push(id);@@ -583,7 +694,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChreturn order.map((id) => byId.get(id)!).filter(Boolean);})();mergedIncomingSlides = incomingSlides;- setLocalSlides(mergedSlides);+ setSlidesKeepingSelection(mergedSlides);const allowImageEdits = creationStep === "done";if (!allowImageEdits) return;@@ -599,6 +710,44 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh: typeof inc?.instruction === "string"? inc.instruction: "";+ const styleRefSlideIds = Array.isArray(inc?.styleRefSlideIds)+ ? inc.styleRefSlideIds+ .map((x: any) => String(x || "").trim())+ .filter((x: string) => !!x && x !== id)+ : [];+ const styleRefPolicy: "style_only" | "style_and_layout" =+ inc?.styleRefPolicy === "style_and_layout" ? "style_and_layout" : "style_only";+ const explicitStyleRefImageUrls = Array.isArray(inc?.styleRefImageUrls)+ ? inc.styleRefImageUrls+ .map((x: any) => String(x || "").trim())+ .filter((x: string) => !!x)+ : [];+ const styleRefRefsFromSlides = styleRefSlideIds+ .map((sid: string) => {+ const url = getCurrentSlideImageUrlById(sid);+ if (!url) return null;+ const safeSid = sid.replace(/[^a-zA-Z0-9_-]/g, "_");+ return {+ url,+ label: `STYLE_REF_SLIDE_${safeSid}`,+ source: sid,+ };+ })+ .filter(Boolean) as Array<{ url: string; label: string; source: string }>;+ const explicitStyleRefRefs = explicitStyleRefImageUrls.map((url: string, idx: number) => ({+ url,+ label: `STYLE_REF_EXTERNAL_${idx + 1}`,+ source: `external-${idx + 1}`,+ }));+ const styleRefRefs = Array.from(+ new Map(+ [...styleRefRefsFromSlides, ...explicitStyleRefRefs].map((x) => [x.url, x] as const)+ ).values()+ );+ const styleRefImageUrls = styleRefRefs.map((x) => x.url);+ const styleRefMappingText = styleRefRefs.length > 0+ ? styleRefRefs.map((x, i) => `${i + 1}. ${x.label} => ${x.source}`).join("\n")+ : "";const slide = mergedSlides.find((s) => s.id === id);if (!slide) continue;@@ -634,8 +783,26 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChpage,uiLang as "zh" | "en",templateImage || undefined,- getSlideMaterialImageRefs(id),- kind === "both" && instruction.trim() ? instruction : undefined+ [+ ...styleRefRefs.map((x) => ({ url: x.url, label: x.label })),+ ...getSlideMaterialImageRefs(id),+ ],+ [+ kind === "both" && instruction.trim() ? instruction : "",+ styleRefImageUrls.length > 0+ ? (+ styleRefPolicy === "style_and_layout"+ ? tr(+ `风格参考映射如下(标签 => 来源):\n${styleRefMappingText}\n可参考其视觉风格与版式结构,但禁止复用其文字内容。`,+ `Style reference mapping (label => source):\n${styleRefMappingText}\nYou may follow both style and layout, but must not copy their text content.`+ )+ : tr(+ `风格参考映射如下(标签 => 来源):\n${styleRefMappingText}\n仅参考其视觉风格(配色、质感、氛围),不要复制其版式与文字内容。`,+ `Style reference mapping (label => source):\n${styleRefMappingText}\nFollow style only (palette/texture/mood), do not copy their layout or text content.`+ )+ )+ : "",+ ].filter(Boolean).join("\n"));if (rendered) {pushImageVersion(id, rendered, "generated", kind === "both" ? instruction : undefined);@@ -659,10 +826,25 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh};const editedUrl = await pptService.editPageImage(page,- instruction,+ [+ instruction,+ styleRefImageUrls.length > 0+ ? (+ styleRefPolicy === "style_and_layout"+ ? tr(+ `附加参考图中,前 ${styleRefImageUrls.length} 张为风格参考图,顺序与映射如下(序号. 标签 => 来源):\n${styleRefMappingText}\n可参考风格和版式,不可复用文字。`,+ `In additional reference images, the first ${styleRefImageUrls.length} are style references. Mapping (index. label => source):\n${styleRefMappingText}\nYou may follow style and layout, but do not copy text.`+ )+ : tr(+ `附加参考图中,前 ${styleRefImageUrls.length} 张为风格参考图,顺序与映射如下(序号. 标签 => 来源):\n${styleRefMappingText}\n仅参考风格,不可复用版式与文字。`,+ `In additional reference images, the first ${styleRefImageUrls.length} are style references. Mapping (index. label => source):\n${styleRefMappingText}\nStyle only, do not copy layout/text.`+ )+ )+ : "",+ ].filter(Boolean).join("\n"),currentUrl || undefined,templateImage || undefined,- [...uploadedImages, ...getSlideMaterialImageUrls(id)]+ Array.from(new Set([...styleRefImageUrls, ...uploadedImages, ...getSlideMaterialImageUrls(id)])));if (editedUrl) {pushImageVersion(id, editedUrl, "edited", instruction);@@ -1761,7 +1943,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh);const slides: SlideData[] = pages.map((p, i) => ({id: p.id || `slide-${i + 1}`,- title: p.title,+ title: normalizeLocalizedSlideTitle(p.title, uiLang as "zh" | "en", i + 1),content: p.content,description: p.description || "",note: p.note || "",@@ -1806,7 +1988,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh}const slides: SlideData[] = pages.map((p, i) => ({id: `slide-${i + 1}`,- title: p.title,+ title: normalizeLocalizedSlideTitle(p.title, uiLang as "zh" | "en", i + 1),content: p.content,description: p.description,note: p.note,@@ -1848,7 +2030,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh}));try {- setProgress({ current: 0, total: pages.length, message: tr("正在生成页面渲染图...", "Rendering slide images...") });+ setProgress({ current: 0, total: pages.length, message: tr("正在生成幻灯片...", "Generating slides...") });const imageCounter = { done: 0 };const imageTasks = pages.map((_, i) => async () => {@@ -1870,7 +2052,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChsetProgress(prev => ({...prev,current: imageCounter.done,- message: tr(`正在生成页面渲染图... (${imageCounter.done}/${pages.length})`, `Rendering slide images... (${imageCounter.done}/${pages.length})`)+ message: tr(`正在生成幻灯片... (${imageCounter.done}/${pages.length})`, `Generating slides... (${imageCounter.done}/${pages.length})`)}));}});@@ -1891,7 +2073,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChconst handleGenerateImagesOnly = async () => {if (localSlides.length === 0) return;setCreationStep('generating_images');- setProgress({ current: 0, total: localSlides.length, message: tr("正在生成页面渲染图...", "Rendering slide images...") });+ setProgress({ current: 0, total: localSlides.length, message: tr("正在生成幻灯片...", "Generating slides...") });const pages: PptPage[] = localSlides.map((s) => ({id: s.id,@@ -1920,7 +2102,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChsetProgress(prev => ({...prev,current: imageCounter.done,- message: tr(`正在生成页面渲染图... (${imageCounter.done}/${pages.length})`, `Rendering slide images... (${imageCounter.done}/${pages.length})`)+ message: tr(`正在生成幻灯片... (${imageCounter.done}/${pages.length})`, `Generating slides... (${imageCounter.done}/${pages.length})`)}));}});diff --git a/vite.config.ts b/vite.config.tsindex d10d922..f7ec173 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -8,6 +8,8 @@ import { GET as getConfig } from "./api/routes/config";import { POST as postVerifyAccessCode } from "./api/routes/verify-access-code";import { POST as postLogFeedback } from "./api/routes/log-feedback";import { POST as postLogSave } from "./api/routes/log-save";+import { POST as postLogFileParser } from "./api/routes/log-file-parser";+import { POST as postThirdPartyParser } from "./api/routes/third-party-parser";import { POST as postChat } from "./api/routes/chat";type RouteHandler = (request: Request) => Promise<Response>;@@ -17,6 +19,8 @@ const API_ROUTES: Record<string, RouteHandler> = {"POST /api/verify-access-code": postVerifyAccessCode,"POST /api/log-feedback": postLogFeedback,"POST /api/log-save": postLogSave,+ "POST /api/log-file-parser": postLogFileParser,+ "POST /api/third-party-parser": postThirdPartyParser,"POST /api/chat": postChat,};