Skip to content

CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.

ppt_fin

codingFeng1017283b25f446e
diff --git a/agent/ppt/outline-edit.md b/agent/ppt/outline-edit.md
index 14aae97..adaf44b 100644
--- a/agent/ppt/outline-edit.md
+++ b/agent/ppt/outline-edit.md
@@ -1,56 +1,52 @@
-# R - Role
-You are an expert presentation outline editing agent. You edit text-only outlines with precision and keep IDs stable.
+# R - Role
+You are `PlanEditAgent`, a PPT plan text editor.
+You edit plan fields only and do not generate images.
# I - Instructions
-Edit an existing text-only presentation outline based on the user request. Do not generate slide images.
-Always include a `layout` hint for each slide.
+Apply user feedback to the provided slide plan context.
+Return patch-style updates only for changed slides.
# Input
-I will provide the following inputs:
-- Input type: user edit request + optional Context attachments
-- Input format: chat text; Context may contain one slide JSON or `{ "slides": [...] }`
-- Input scope: edit only the provided slide(s) unless explicitly asked otherwise
+- required: `context` with slide data (`{ slides: [...] }`), can be full set or subset
+- required: `user_feedback`
+- required: `ui_language`
-# S - Steps
-Please follow these steps:
-1. Determine which slides are in scope based on Context attachments.
-2. Apply the requested edits to titles, bullets, descriptions, notes, and layout hints.
-3. Preserve slide `id` and slide order unless explicitly asked to change them.
-4. If adding/removing slides, keep IDs consistent and use `slide-N` for new slides.
-5. Output the updated outline JSON in the required schema.
+Notes:
+- If user referenced specific slides/tokens, `context.slides` may be subset.
+- If user did not reference any slide, `context.slides` is full set.
-# E - End Goal
-Return a valid outline JSON that reflects the requested edits, stays coherent, and remains ready for later image generation.
+# S - Steps
+1. Read `user_feedback` and determine exactly which slides need edits.
+2. Edit only those slides in context scope.
+3. Keep `id` stable.
+4. For each changed slide, keep fields complete and coherent:
+- `title`
+- `content`
+- `description`
+- `layout`
+- `note`
+5. Return one patch payload only.
# N - Narrowing
-Constraints (CRITICAL):
-1. This agent only edits outline/text. NEVER output `imageEditInstruction`.
-2. If Context attachments include slides, treat them as authoritative:
- - If Context includes one slide JSON, edit ONLY that slide.
- - If Context includes `{ "slides": [...] }`, edit ONLY those slides unless explicitly asked to edit others.
-3. Keep slide `id` unchanged and preserve slide order unless explicitly asked to reorder.
-4. When asked to add/remove slides, keep IDs consistent and use `slide-N` for new slides.
-5. Bullets are short and specific (<= 12 words each).
-6. `description` must be concrete for later image generation (subject, composition, colors, style, lighting).
-7. Output ONLY one markdown code block and nothing else.
-8. Language policy (CRITICAL):
- - Follow the UI language policy provided by the system messages.
- - If UI language is zh, output Simplified Chinese; if UI language is en, output English.
- - Do not mix languages unless explicitly requested.
+Rules (CRITICAL):
+1. Text editing only. Do NOT output image URLs.
+2. Do NOT output `imageEditInstruction`.
+3. Do not return unchanged slides.
+4. Output ONLY one markdown code block.
+5. `ui_language=zh` => Simplified Chinese; `ui_language=en` => English.
# Output Format
```json
{
"type": "ppt_edit",
- "theme": "optional",
"slides": [
{
- "id": "slide-1",
+ "id": "slide-3",
"title": "...",
- "content": ["...", "..."],
- "description": "visual description for later image generation",
- "note": "optional speaker notes",
- "layout": "layout hint"
+ "content": ["..."],
+ "description": "...",
+ "layout": "...",
+ "note": "..."
}
]
}
diff --git a/agent/ppt/outline.md b/agent/ppt/outline.md
index 33e7d00..9ca87bb 100644
--- a/agent/ppt/outline.md
+++ b/agent/ppt/outline.md
@@ -1,54 +1,62 @@
-# R - Role
-You are an expert presentation outline generation agent. You produce clear, text-only slide outlines that are ready for later rendering.
+# R - Role
+You are the PPT planning agent and can work in two planning modes:
+1) `PlanFromIdeaAgent`
+2) `PlanFromOutlineAgent`
# I - Instructions
-Create a text-only presentation outline (titles, bullets, and visual descriptions) that is coherent and ready for slide rendering later.
-Always include a `layout` hint for each slide.
+Generate a complete `PptPlan` for rendering.
+Every slide must contain all required fields:
+- `id`
+- `title`
+- `content`
+- `description`
+- `layout`
+- `note`
# Input
-I will provide the following inputs:
-- Input type: user topic/request + optional Context attachments
-- Input format: chat text; Context may contain slide JSON
-- Input scope: if Context slides are provided, treat them as authoritative and align the outline to them
+You may receive either one of these input sets:
+1) Idea mode (`PlanFromIdeaAgent`)
+- required: `idea_prompt`, `ui_language`
+- optional: `reference_files_content` (`[{filename, content}]`)
-# S - Steps
-Please follow these steps:
-1. Identify the topic, audience, and desired depth from the request.
-2. Draft a coherent slide structure (prefer 6–10 slides unless implied otherwise).
-3. For each slide, write a short title and concise bullets (<= 12 words each).
-4. Write a concrete `description` for later image generation (subject, composition, colors, style, lighting).
-5. Add a `layout` hint string for each slide (e.g., "title + 3 bullets + hero image right").
-6. Output the outline JSON in the required schema.
+2) Outline mode (`PlanFromOutlineAgent`)
+- required: `outline_text`, `ui_language`
+- optional: `reference_files_content` (`[{filename, content}]`)
-# E - End Goal
-Produce a high-quality outline JSON that can be used directly for subsequent slide generation and rendering.
+# S - Steps
+1. Determine whether the task is idea-to-plan or outline-to-plan.
+2. Build a coherent slide sequence (prefer 6-10 slides unless user intent implies otherwise).
+3. For each slide:
+- concise title
+- concise bullets (`content`, each bullet <= 12 words)
+- concrete `description` for image generation (subject/composition/style/colors/lighting)
+- explicit `layout` hint
+- `note` (speaker note; can be short but must exist as string)
+4. If reference files are provided, absorb relevant facts and align terminology.
+5. Keep language aligned with `ui_language`.
+6. Return one JSON payload only.
# N - Narrowing
-Constraints (CRITICAL):
-1. This agent only generates an outline. NEVER output `imageEditInstruction`.
-2. Prefer 6-10 slides unless the request implies otherwise.
-3. Bullets are short and specific (<= 12 words each).
-4. `description` must be concrete for later image generation (subject, composition, colors, style, lighting).
-5. If the user provides Context attachments containing slide JSON, treat them as authoritative and generate a coherent outline that matches them.
-6. Output ONLY one markdown code block and nothing else.
-7. Language policy (CRITICAL):
- - Follow the UI language policy provided by the system messages.
- - If UI language is zh, output Simplified Chinese; if UI language is en, output English.
- - Do not mix languages unless explicitly requested.
+Rules (CRITICAL):
+1. This planning agent only outputs plan JSON; do not output image URLs.
+2. Do not output `imageEditInstruction`.
+3. Keep `id` stable if slide IDs are already implied by context; otherwise use `slide-1`, `slide-2`, ...
+4. Output ONLY one markdown code block.
+5. `ui_language=zh` => Simplified Chinese; `ui_language=en` => English.
# Output Format
```json
{
- "type": "ppt_edit",
+ "type": "ppt_plan",
"theme": "optional",
"slides": [
{
"id": "slide-1",
"title": "...",
"content": ["...", "..."],
- "description": "visual description for later image generation",
- "note": "optional speaker notes",
- "layout": "layout hint"
+ "description": "...",
+ "layout": "...",
+ "note": "..."
}
]
}
diff --git a/agent/ppt/slides-generate.md b/agent/ppt/slides-generate.md
index e6cf78d..d980b2e 100644
--- a/agent/ppt/slides-generate.md
+++ b/agent/ppt/slides-generate.md
@@ -1,55 +1,37 @@
-# R - Role
-You are an expert presentation slide planning agent. You produce slide content that is ready for image rendering, with concrete visual descriptions.
+# R - Role
+You are `EditRouterAgent` for PPT edits.
# I - Instructions
-Given an outline and/or a topic (and any Context slides), produce slide content ready for image rendering.
-Always include a `layout` hint for each slide.
+Classify user feedback into per-slide edit actions and indicate whether each action is content-only, visual-only, or both.
# Input
-I will provide the following inputs:
-- Input type: topic and/or outline + optional Context attachments
-- Input format: chat text; Context may contain slide JSON
-- Input scope: if Context slides are provided, treat them as authoritative and keep IDs stable
+- required: `slides_summary` (each slide includes `id`, `title`, `content`, `description`, `layout`, `note`)
+- required: `user_feedback`
# S - Steps
-Please follow these steps:
-1. Identify the topic, audience, and desired slide count from the request.
-2. If an outline is provided, expand it into slide content; otherwise propose a coherent structure.
-3. Write concise bullets for each slide (<= 12 words each).
-4. Write a concrete `description` for image generation (subject, composition, style, colors, lighting).
-5. Add speaker notes when helpful (recommended).
-6. Add a `layout` hint string for each slide (e.g., "title top, 4 bullets left, chart right").
-7. Output the slide JSON in the required schema.
-
-# E - End Goal
-Return a valid `ppt_generate` JSON that can be used directly for slide rendering and image generation.
+1. Parse the feedback and map intent to slide(s).
+2. For each target slide, produce one routing item.
+3. Set `kind` as one of:
+- `content`
+- `visual`
+- `both`
+4. Write concise executable `instruction` text.
# N - Narrowing
-Constraints (CRITICAL):
-1. NEVER output `imageEditInstruction`.
-2. If Context attachments include slides, treat them as authoritative and keep `id` stable.
-3. Preserve slide order unless explicitly asked to reorder.
-4. Bullets are short and specific (<= 12 words each).
-5. Language policy (CRITICAL):
- - Follow the UI language policy provided by the system messages.
- - If UI language is zh, output Simplified Chinese; if UI language is en, output English.
- - Do not mix languages unless explicitly requested.
-5. `description` must be concrete: subject, composition, style, colors, lighting.
-6. Output ONLY one markdown code block and nothing else.
+Rules (CRITICAL):
+1. Output JSON array only.
+2. One item per targeted slide.
+3. `slideId` must match existing ids in `slides_summary`.
+4. Do not invent new slide ids.
+5. Output ONLY one markdown code block.
# Output Format
```json
-{
- "type": "ppt_generate",
- "slides": [
- {
- "id": "slide-1",
- "title": "...",
- "content": ["...", "..."],
- "description": "visual description for image generation",
- "note": "speaker notes (optional but recommended)",
- "layout": "layout hint"
- }
- ]
-}
+[
+ {
+ "slideId": "slide-2",
+ "kind": "content|visual|both",
+ "instruction": "..."
+ }
+]
```
diff --git a/agent/ppt/system.md b/agent/ppt/system.md
index 071acd7..b4c7e0a 100644
--- a/agent/ppt/system.md
+++ b/agent/ppt/system.md
@@ -1,40 +1,28 @@
-# R - Role
-You are an expert presentation slide editing agent. You edit existing slide plans precisely and follow the provided slide JSON as the source of truth.
+# R - Role
+You are `PlanEditAgent` + `SlideImageEditAgent` coordinator for existing slides.
# I - Instructions
-Apply the user's requested edits to the provided slide JSON (single slide or a slides array). When the user requests a visual change, include `imageEditInstruction` for each edited slide.
-Always include a `layout` hint for each edited slide.
+Use provided slide context to return plan edits. For visual change requests, include a direct image edit instruction in `instruction`.
# Input
-I will provide the following inputs:
-- Input type: user edit request + optional Context attachments
-- Input format: chat text; Context may contain one slide JSON or `{ "slides": [...] }`
-- Input scope: edit only what is provided in Context unless explicitly asked otherwise
+- required: user feedback text
+- required: slide context attachments (`{slides:[...]}` or single slide JSON)
+- required: `ui_language`
# S - Steps
-Please follow these steps:
-1. Read the user request and determine which slides are in scope (based on Context attachments).
-2. Apply content and structure edits while preserving slide `id` and order unless explicitly requested to change them.
-3. If the request includes a visual change to an existing slide image, add `imageEditInstruction` for each edited slide.
-4. Output exactly one JSON payload in the required schema.
-
-# E - End Goal
-Return a valid `ppt_edit` JSON that reflects the requested edits, preserves slide identity, and triggers image edits when requested.
+1. Identify targeted slides from context and feedback.
+2. Update plan fields (`title/content/description/layout/note`) when needed.
+3. If visual change is requested, include `instruction` for image editing.
+4. Keep `id` stable.
+5. Return changed slides only.
# N - Narrowing
Rules (CRITICAL):
-1. If Context attachments include slides, treat them as authoritative:
- - If Context includes one slide JSON, edit ONLY that slide.
- - If Context includes `{ "slides": [...] }`, edit ONLY those slides unless explicitly asked to edit others.
-2. Keep slide `id` unchanged and preserve slide order unless explicitly asked to reorder.
-3. If the user provides a specific template or style, adapt the slide fields accordingly.
-4. If the request is a visual change to an existing slide image (e.g. "change background", "add image", "change style"), you MUST include `imageEditInstruction` for each edited slide.
-5. If the user asks for a visual change, do NOT reply with only text. Return JSON with `imageEditInstruction`.
-6. Output ONLY one markdown code block and nothing else.
-7. Language policy (CRITICAL):
- - Follow the UI language policy provided by the system messages.
- - If UI language is zh, output Simplified Chinese; if UI language is en, output English.
- - Do not mix languages unless explicitly requested.
+1. Do not output full deck unless all slides changed.
+2. Do not output image URL directly.
+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.
# Output Format
```json
@@ -46,9 +34,9 @@ Rules (CRITICAL):
"title": "...",
"content": ["..."],
"description": "...",
- "note": "optional speaker notes",
- "layout": "layout hint",
- "imageEditInstruction": "only when a visual change is requested"
+ "layout": "...",
+ "note": "...",
+ "instruction": "optional, only for visual edit"
}
]
}
diff --git a/api/routes/chat.ts b/api/routes/chat.ts
index 887f49f..5af0145 100644
--- a/api/routes/chat.ts
+++ b/api/routes/chat.ts
@@ -1,1233 +1 @@
-import {
- APICallError,
- convertToModelMessages,
- createUIMessageStream,
- createUIMessageStreamResponse,
- generateText,
- LoadAPIKeyError,
- stepCountIs,
- streamText,
-} from "ai"
-import { appendFile } from "fs/promises"
-import path from "path"
-import { z } from "zod"
-import { extractText, getDocumentProxy } from "unpdf"
-import mammoth from "mammoth"
-import {
- getAIModel,
- supportsPromptCaching,
-} from "../../src/workspaces/flow/next/lib/ai-providers"
-import {
- getTelemetryConfig,
- setTraceInput,
- setTraceOutput,
- wrapWithObserve,
-} from "../../src/workspaces/flow/next/lib/langfuse"
-import { getSystemPrompt } from "../../src/workspaces/flow/next/lib/system-prompts"
-
-export const maxDuration = 300
-
-// File upload limits (must match client-side)
-const MAX_FILE_SIZE = 2 * 1024 * 1024 // 2MB
-const MAX_FILES = 5
-
-const SUMMARY_CONCURRENCY = 50
-const CHUNK_TOKEN_TARGET = 2500
-const RECURSIVE_THRESHOLD_TOKENS = 50000
-
-type UploadedFilePayload = {
- name: string
- mediaType?: string
- dataUrl: string
- extractedText?: string
-}
-
-function estimateTokens(text: string): number {
- return Math.ceil(String(text || "").length / 4)
-}
-
-function cleanExtractedText(input: string): string {
- const text = String(input || "")
- .replace(/\r/g, "\n")
- .replace(/[ \t]+\n/g, "\n")
- .replace(/\n{3,}/g, "\n\n")
- .replace(/[ \t]{2,}/g, " ")
- .trim()
- return text
- .split("\n")
- .filter((line) => {
- const l = line.trim()
- if (!l) return false
- if (/^arXiv:\d{4}\.\d{4,5}/i.test(l)) return false
- if (/^\[\d+\]\s*$/.test(l)) return false
- if (/^Page\s+\d+(\s+of\s+\d+)?$/i.test(l)) return false
- return true
- })
- .join("\n")
- .trim()
-}
-
-function splitByApproxTokens(text: string, chunkTokens: number): string[] {
- const chunkChars = Math.max(2000, chunkTokens * 4)
- const overlapChars = Math.floor(chunkChars * 0.1)
- const normalized = String(text || "").trim()
- if (!normalized) return []
- const chunks: string[] = []
- let start = 0
- while (start < normalized.length) {
- const end = Math.min(start + chunkChars, normalized.length)
- chunks.push(normalized.slice(start, end))
- if (end >= normalized.length) break
- start = Math.max(0, end - overlapChars)
- }
- return chunks
-}
-
-async function runWithConcurrency<T, R>(
- items: T[],
- limit: number,
- worker: (item: T, index: number) => Promise<R>,
-): Promise<R[]> {
- if (items.length === 0) return []
- const results = new Array<R>(items.length)
- let cursor = 0
- const runners = Array.from({ length: Math.min(limit, items.length) }).map(
- async () => {
- while (true) {
- const idx = cursor
- cursor += 1
- if (idx >= items.length) return
- results[idx] = await worker(items[idx], idx)
- }
- },
- )
- await Promise.all(runners)
- return results
-}
-
-function getFileExtension(name: string): string {
- const n = String(name || "")
- const i = n.lastIndexOf(".")
- return i >= 0 ? n.slice(i).toLowerCase() : ""
-}
-
-function parseDataUrl(dataUrl: string): { mediaType: string; base64: string } {
- const raw = String(dataUrl || "")
- const m = raw.match(/^data:([^;]+);base64,(.*)$/)
- if (!m) throw new Error("Invalid data URL")
- return { mediaType: m[1], base64: m[2] }
-}
-
-async function extractUploadedFileText(file: UploadedFilePayload): Promise<string> {
- const providedText =
- typeof file.extractedText === "string"
- ? cleanExtractedText(file.extractedText)
- : ""
-
- const { mediaType, base64 } = parseDataUrl(file.dataUrl)
- const buffer = Buffer.from(base64, "base64")
- const ext = getFileExtension(file.name)
- const mt = String(file.mediaType || mediaType || "").toLowerCase()
-
- if (mt.includes("pdf") || ext === ".pdf") {
- // If client already extracted enough text, trust it.
- if (providedText.length >= 200) return providedText
-
- const pdf = await getDocumentProxy(new Uint8Array(buffer))
- const { text } = await extractText(pdf, { mergePages: true })
- const parsed = cleanExtractedText(String(text || ""))
- return parsed.length >= providedText.length ? parsed : providedText
- }
-
- if (mt.includes("wordprocessingml.document") || ext === ".docx") {
- if (providedText) return providedText
- const result = await mammoth.extractRawText({ buffer })
- return cleanExtractedText(String(result.value || ""))
- }
-
- if (
- mt.startsWith("text/") ||
- [".txt", ".md", ".markdown", ".json", ".csv", ".xml", ".yaml", ".yml", ".toml", ".py", ".js", ".ts"].includes(ext)
- ) {
- if (providedText) return providedText
- return cleanExtractedText(buffer.toString("utf8"))
- }
-
- return providedText || cleanExtractedText(buffer.toString("utf8"))
-}
-
-async function summarizeChunk(
- model: any,
- providerOptions: any,
- headers: any,
- chunk: string,
-): Promise<string> {
- return generateSummaryWithRetry({
- model,
- providerOptions,
- headers,
- system:
- "You are a strict summarizer. Output only direct summary text, no questions, no instructions.",
- user: `任务:仅根据下述文本输出摘要(<=300字)。禁止提问、禁止让用户补充内容、禁止输出模板化客套。\n\n文本:\n${chunk}`,
- maxOutputTokens: 600,
- maxChars: 300,
- fallbackSource: chunk,
- })
-}
-
-function extractiveFallbackSummary(source: string, maxChars: number): string {
- const cleaned = cleanExtractedText(String(source || ""))
- .replace(/\s+/g, " ")
- .trim()
- if (!cleaned) return ""
- const sentences = cleaned
- .split(/(?<=[。!?.!?])\s+/)
- .map((s) => s.trim())
- .filter(Boolean)
- const out: string[] = []
- let total = 0
- for (const s of sentences) {
- if (s.length < 10) continue
- if (total + s.length > maxChars) break
- out.push(s)
- total += s.length + 1
- if (out.length >= 6) break
- }
- if (out.length > 0) return out.join(" ")
- return cleaned.slice(0, maxChars)
-}
-
-function sanitizeSummaryText(summary: string, fallbackSource: string, maxChars: number): string {
- const text = String(summary || "").trim()
- if (!text) return extractiveFallbackSummary(fallbackSource, maxChars)
- const bannedPatterns = [
- /请提供/i,
- /请粘贴/i,
- /需要合并/i,
- /如有偏好/i,
- /目标读者/i,
- /是否保留术语/i,
- /是否需要强调/i,
- /I can|please provide|paste|preference/i,
- ]
- if (bannedPatterns.some((p) => p.test(text))) {
- return extractiveFallbackSummary(fallbackSource, maxChars)
- }
- return text.slice(0, Math.max(120, maxChars))
-}
-
-function isBadSummaryText(text: string): boolean {
- const t = String(text || "").trim()
- if (!t) return true
- return [
- /请提供/i,
- /请粘贴/i,
- /需要合并/i,
- /如有偏好/i,
- /是否保留术语/i,
- /please provide|paste/i,
- ].some((p) => p.test(t))
-}
-
-async function generateSummaryWithRetry(args: {
- model: any
- providerOptions: any
- headers: any
- system: string
- user: string
- maxOutputTokens: number
- maxChars: number
- fallbackSource: string
-}): Promise<string> {
- for (let i = 0; i < 2; i++) {
- const r = await generateText({
- model: args.model,
- messages: [
- { role: "system" as const, content: args.system },
- { role: "user" as const, content: args.user },
- ],
- ...(args.providerOptions && { providerOptions: args.providerOptions }),
- ...(args.headers && { headers: args.headers }),
- maxOutputTokens: args.maxOutputTokens,
- })
- const text = sanitizeSummaryText(
- String(r.text || "").trim(),
- args.fallbackSource,
- args.maxChars,
- )
- if (!isBadSummaryText(text)) return text
- }
- return extractiveFallbackSummary(args.fallbackSource, args.maxChars)
-}
-
-async function summarizeBlockMethod(args: {
- model: any
- providerOptions: any
- headers: any
- text: string
-}): Promise<string> {
- const chunks = splitByApproxTokens(args.text, CHUNK_TOKEN_TARGET)
- const partial = await runWithConcurrency(
- chunks,
- SUMMARY_CONCURRENCY,
- (chunk) => summarizeChunk(args.model, args.providerOptions, args.headers, chunk),
- )
- const merged = partial.filter(Boolean).join("\n")
- return generateSummaryWithRetry({
- model: args.model,
- providerOptions: args.providerOptions,
- headers: args.headers,
- system:
- "You produce concise, faithful merged summaries. Output only summary text.",
- user: `任务:将以下分块摘要合并为完整摘要(<=1000字)。禁止提问、禁止请求补充材料,仅输出摘要正文。\n\n${merged}`,
- maxOutputTokens: 1800,
- maxChars: 1000,
- fallbackSource: merged,
- })
-}
-
-async function summarizeRecursiveMethod(args: {
- model: any
- providerOptions: any
- headers: any
- text: string
-}): Promise<string> {
- const baseChunks = splitByApproxTokens(args.text, 3000)
- let level = await runWithConcurrency(
- baseChunks,
- SUMMARY_CONCURRENCY,
- (chunk) => summarizeChunk(args.model, args.providerOptions, args.headers, chunk),
- )
- level = level.filter(Boolean)
-
- while (level.length > 2) {
- const groups: string[] = []
- for (let i = 0; i < level.length; i += 5) {
- groups.push(level.slice(i, i + 5).join("\n"))
- }
- level = await runWithConcurrency(
- groups,
- SUMMARY_CONCURRENCY,
- async (group) =>
- generateSummaryWithRetry({
- model: args.model,
- providerOptions: args.providerOptions,
- headers: args.headers,
- system:
- "You merge summaries into a higher-level summary. Output only summary text.",
- user: `任务:把这组摘要提炼成更高层摘要(<=350字)。禁止提问、禁止让用户补充,只输出摘要。\n\n${group}`,
- maxOutputTokens: 800,
- maxChars: 350,
- fallbackSource: group,
- }),
- )
- level = level.filter(Boolean)
- }
-
- return generateSummaryWithRetry({
- model: args.model,
- providerOptions: args.providerOptions,
- headers: args.headers,
- system:
- "You produce final executive summaries with hierarchical fidelity and no hallucination. Output only summary text.",
- user: `任务:输出最终摘要(<=1000字)。禁止提问、禁止请求更多信息,仅输出摘要正文。\n\n${level.join("\n")}`,
- maxOutputTokens: 1800,
- maxChars: 1000,
- fallbackSource: level.join("\n"),
- })
-}
-
-function validateUploadedFiles(uploadedFiles: UploadedFilePayload[]): {
- valid: boolean
- error?: string
-} {
- if (uploadedFiles.length > MAX_FILES) {
- return {
- valid: false,
- error: `Too many files. Maximum ${MAX_FILES} allowed.`,
- }
- }
- for (const f of uploadedFiles) {
- try {
- const { base64 } = parseDataUrl(f.dataUrl)
- const sizeInBytes = Math.ceil((base64.length * 3) / 4)
- if (sizeInBytes > MAX_FILE_SIZE) {
- return {
- valid: false,
- error: `File exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit.`,
- }
- }
- } catch {
- return {
- valid: false,
- error: `Invalid uploaded file payload: ${f.name || "unknown"}`,
- }
- }
- }
- return { valid: true }
-}
-
-// Helper function to validate file parts in messages
-function validateFileParts(messages: any[]): {
- valid: boolean
- error?: string
-} {
- const lastMessage = messages[messages.length - 1]
- const fileParts =
- lastMessage?.parts?.filter((p: any) => p.type === "file") || []
-
- if (fileParts.length > MAX_FILES) {
- return {
- valid: false,
- error: `Too many files. Maximum ${MAX_FILES} allowed.`,
- }
- }
-
- for (const filePart of fileParts) {
- // Data URLs format: data:image/png;base64,<data>
- // Base64 increases size by ~33%, so we check the decoded size
- if (filePart.url?.startsWith("data:")) {
- const base64Data = filePart.url.split(",")[1]
- if (base64Data) {
- const sizeInBytes = Math.ceil((base64Data.length * 3) / 4)
- if (sizeInBytes > MAX_FILE_SIZE) {
- return {
- valid: false,
- error: `File exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit.`,
- }
- }
- }
- }
- }
-
- return { valid: true }
-}
-
-// Helper function to check if diagram is minimal/empty
-function isMinimalDiagram(xml: string): boolean {
- const stripped = xml.replace(/\s/g, "")
- return !stripped.includes('id="2"')
-}
-
-// Helper function to replace historical tool call XML with placeholders
-// This reduces token usage and forces LLM to rely on the current diagram XML (source of truth)
-function replaceHistoricalToolInputs(messages: any[]): any[] {
- return messages.map((msg) => {
- if (msg.role !== "assistant" || !Array.isArray(msg.content)) {
- return msg
- }
- const replacedContent = msg.content.map((part: any) => {
- if (part.type === "tool-call") {
- const toolName = part.toolName
- if (
- toolName === "display_diagram" ||
- toolName === "edit_diagram"
- ) {
- return {
- ...part,
- input: {
- placeholder:
- "[XML content replaced - see current diagram XML in system context]",
- },
- }
- }
- }
- return part
- })
- return { ...msg, content: replacedContent }
- })
-}
-
-// Helper function to fix tool call inputs for Bedrock API
-// Bedrock requires toolUse.input to be a JSON object, not a string
-function fixToolCallInputs(messages: any[]): any[] {
- return messages.map((msg) => {
- if (msg.role !== "assistant" || !Array.isArray(msg.content)) {
- return msg
- }
- const fixedContent = msg.content.map((part: any) => {
- if (part.type === "tool-call") {
- if (typeof part.input === "string") {
- try {
- const parsed = JSON.parse(part.input)
- return { ...part, input: parsed }
- } catch {
- // If parsing fails, wrap the string in an object
- return { ...part, input: { rawInput: part.input } }
- }
- }
- // Input is already an object, but verify it's not null/undefined
- if (part.input === null || part.input === undefined) {
- return { ...part, input: {} }
- }
- }
- return part
- })
- return { ...msg, content: fixedContent }
- })
-}
-
-// Inner handler function
-async function handleChatRequest(req: Request): Promise<Response> {
- console.log('[EARLY DEBUG] handleChatRequest executed')
- // Check for access code
- const accessCodes =
- process.env.ACCESS_CODE_LIST?.split(",")
- .map((code) => code.trim())
- .filter(Boolean) || []
- if (accessCodes.length > 0) {
- const accessCodeHeader = req.headers.get("x-access-code")
- if (!accessCodeHeader || !accessCodes.includes(accessCodeHeader)) {
- return Response.json(
- {
- error: "Invalid or missing access code. Please configure it in Settings.",
- },
- { status: 401 },
- )
- }
- }
-
- const payload = await req.json()
- const { messages, xml, previousXml, sessionId } = payload || {}
- const uploadedFiles: UploadedFilePayload[] = Array.isArray(payload?.uploadedFiles)
- ? payload.uploadedFiles
- : []
- const bodyAIConfig = payload?.aiConfig || {}
-
- // Debug: log the actual message structure received
- console.log("[DEBUG] Received messages:", JSON.stringify(messages, null, 2))
- console.log("[DEBUG] First message structure:", messages?.[0] ? JSON.stringify(messages[0], null, 2) : "No messages")
-
- // Validate messages array
- if (!messages || !Array.isArray(messages)) {
- return Response.json(
- { error: "Messages must be an array" },
- { status: 400 }
- )
- }
-
- // Get user IP for Langfuse tracking
- const forwardedFor = req.headers.get("x-forwarded-for")
- const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous"
-
- // Validate sessionId for Langfuse (must be string, max 200 chars)
- const validSessionId =
- sessionId && typeof sessionId === "string" && sessionId.length <= 200
- ? sessionId
- : undefined
-
- // Extract user input text for Langfuse trace
- const currentMessage = messages[messages.length - 1]
- const userInputText =
- currentMessage?.parts?.find((p: any) => p.type === "text")?.text || ""
-
- // Update Langfuse trace with input, session, and user
- setTraceInput({
- input: userInputText,
- sessionId: validSessionId,
- userId: userId,
- })
-
- // === FILE VALIDATION START ===
- const fileValidation = validateFileParts(messages)
- if (!fileValidation.valid) {
- return Response.json({ error: fileValidation.error }, { status: 400 })
- }
- const uploadedValidation = validateUploadedFiles(uploadedFiles)
- if (!uploadedValidation.valid) {
- return Response.json({ error: uploadedValidation.error }, { status: 400 })
- }
- // === FILE VALIDATION END ===
-
- // Read client AI provider overrides from headers first, then body fallback.
- const clientOverrides = {
- provider:
- req.headers.get("x-ai-provider") ||
- (typeof bodyAIConfig.provider === "string"
- ? bodyAIConfig.provider
- : null),
- baseUrl:
- req.headers.get("x-ai-base-url") ||
- (typeof bodyAIConfig.baseUrl === "string"
- ? bodyAIConfig.baseUrl
- : null),
- apiKey:
- req.headers.get("x-ai-api-key") ||
- (typeof bodyAIConfig.apiKey === "string"
- ? bodyAIConfig.apiKey
- : null),
- modelId:
- req.headers.get("x-ai-model") ||
- req.headers.get("x-ai-chat-model") ||
- (typeof bodyAIConfig.chatModel === "string"
- ? bodyAIConfig.chatModel
- : typeof bodyAIConfig.modelId === "string"
- ? bodyAIConfig.modelId
- : null),
- }
-
- // Get AI model with optional client overrides
- const { model, providerOptions, headers, modelId } =
- getAIModel(clientOverrides)
-
- // Check if model supports prompt caching
- const shouldCache = supportsPromptCaching(modelId)
- console.log(
- `[Prompt Caching] ${shouldCache ? "ENABLED" : "DISABLED"} for model: ${modelId}`,
- )
-
- let parsedFilesContext = ""
- if (uploadedFiles.length > 0) {
- const fileSummaries = await runWithConcurrency(
- uploadedFiles,
- SUMMARY_CONCURRENCY,
- async (file) => {
- const extracted = await extractUploadedFileText(file)
- const tokens = estimateTokens(extracted)
- const method =
- tokens >= RECURSIVE_THRESHOLD_TOKENS ? "recursive" : "chunk"
- const summary =
- method === "recursive"
- ? await summarizeRecursiveMethod({
- model,
- providerOptions,
- headers,
- text: extracted,
- })
- : await summarizeBlockMethod({
- model,
- providerOptions,
- headers,
- text: extracted,
- })
- return { name: file.name, tokens, method, summary }
- },
- )
-
- parsedFilesContext = fileSummaries
- .map(
- (item, idx) =>
- `[Parsed File ${idx + 1}: ${item.name}]\nmethod=${item.method}; estimated_tokens=${item.tokens}\n${item.summary}`,
- )
- .join("\n\n")
- }
-
- // Get the appropriate system prompt based on model (extended for Opus/Haiku 4.5)
- let systemMessage = getSystemPrompt(modelId)
-
- // Append global constraints if present
- const globalConstraintsHeader = req.headers.get("x-ai-constraints")
- const globalConstraintsBody =
- typeof payload?.aiConstraints === "string"
- ? payload.aiConstraints
- : ""
- const globalConstraintsRaw =
- globalConstraintsHeader || globalConstraintsBody
- if (globalConstraintsRaw) {
- const globalConstraints = globalConstraintsHeader
- ? decodeURIComponent(globalConstraintsRaw)
- : globalConstraintsRaw
- systemMessage += `\n\n=== GLOBAL CONSTRAINTS ===\nThe user has set the following global constraints which MUST be followed for every response:\n${globalConstraints}\n==========================\n`
- }
-
- const lastMessage = messages[messages.length - 1]
-
- // Handle case where messages array is empty
- if (!lastMessage) {
- return Response.json(
- { error: "No messages provided" },
- { status: 400 }
- )
- }
-
- // Extract text from the last message parts or content
- let lastMessageText = ""
- if (lastMessage.content && typeof lastMessage.content === "string") {
- lastMessageText = lastMessage.content
- } else if (Array.isArray(lastMessage.content)) {
- lastMessageText = lastMessage.content
- .filter((part: any) => part.type === "text" || typeof part === "string")
- .map((part: any) => (typeof part === "string" ? part : part.text || ""))
- .join("")
- } else {
- lastMessageText =
- lastMessage.parts?.find((part: any) => part.type === "text")?.text || ""
- }
-
- // Extract file parts (images) from the last message
- // Note: If using standard 'content' array with images, they might need different handling
- // but for now we primarily support our custom 'parts' format for files
- const partsFileParts =
- lastMessage.parts?.filter((part: any) => part.type === "file") || []
- const contentImageParts = Array.isArray(lastMessage.content)
- ? lastMessage.content.filter(
- (part: any) =>
- part?.type === "image_url" ||
- part?.type === "image" ||
- part?.type === "file",
- )
- : []
- const fileParts = [...partsFileParts, ...contentImageParts]
-
- // User input only - XML is now in a separate cached system message
- const formattedUserInput = `User input:
-"""md
-${lastMessageText}
-"""
-${parsedFilesContext ? `\n\nParsed file summaries:\n"""md\n${parsedFilesContext}\n"""` : ""}`
-
- // Validate messages structure before conversion
- if (!messages || !Array.isArray(messages)) {
- return Response.json(
- { error: "Invalid messages format: expected array" },
- { status: 400 }
- )
- }
-
- // Validate each message has required structure
- for (let i = 0; i < messages.length; i++) {
- const message = messages[i]
- console.log(`[DEBUG] Validating message ${i}:`, JSON.stringify(message, null, 2))
-
- if (!message || typeof message !== 'object') {
- return Response.json(
- { error: `Invalid message format: expected object at index ${i}` },
- { status: 400 }
- )
- }
- if (!message.role || typeof message.role !== 'string') {
- return Response.json(
- { error: `Invalid message format: missing role at index ${i}` },
- { status: 400 }
- )
- }
- // Vercel AI SDK can send messages with different content formats
- // - messages with parts array (our custom format)
- // - messages with content array (standard format)
- // - messages with content string (standard format)
- if (!message.parts && !message.content) {
- return Response.json(
- { error: `Invalid message format: missing content or parts at index ${i}, message: ${JSON.stringify(message)}` },
- { status: 400 }
- )
- }
- if (message.parts && !Array.isArray(message.parts)) {
- return Response.json(
- { error: `Invalid message format: parts must be array at index ${i}` },
- { status: 400 }
- )
- }
- if (message.content && typeof message.content !== 'string' && !Array.isArray(message.content)) {
- return Response.json(
- { error: `Invalid message format: content must be string or array at index ${i}` },
- { status: 400 }
- )
- }
- }
-
- // Normalize messages to expected format (convert content to parts if needed)
- const normalizedMessages = messages.map((message: any, index: number) => {
- // Handle completely malformed messages
- if (!message) {
- console.log(`[DEBUG] Message ${index} is null/undefined, creating default structure`)
- return { role: 'user', parts: [{ type: 'text', text: '' }] }
- }
-
- // If message already has parts, keep it as is
- if (message.parts && Array.isArray(message.parts)) {
- return message
- }
-
- // If message has content, convert to parts format
- if (message.content) {
- let parts: any[] = []
-
- if (typeof message.content === 'string') {
- // Convert string content to text part
- parts = [{ type: 'text', text: message.content }]
- } else if (Array.isArray(message.content)) {
- // Convert content array to parts array
- parts = message.content.map((item: any) => {
- if (typeof item === 'string') {
- return { type: 'text', text: item }
- } else if (item.type === 'text') {
- return { type: 'text', text: item.text || '' }
- } else if (item.type === 'image') {
- return { type: 'image', image: item.image || item.url, mimeType: item.mimeType }
- } else if (item.type === "image_url") {
- return {
- type: "image",
- image: item.image_url?.url || item.url || "",
- mimeType: item.mimeType,
- }
- } else if (item.type === "file") {
- return {
- type: "image",
- image: item.url || item.image || "",
- mimeType: item.mediaType || item.mimeType,
- }
- }
- return { type: 'text', text: String(item) }
- })
- }
-
- return { ...message, parts, content: undefined }
- }
-
- // Handle messages with no content and no parts but have role
- if (message.role) {
- console.log(`[DEBUG] Message ${index} has role but no content/parts, adding empty parts`)
- return { ...message, parts: [] }
- }
-
- // Fallback: create default message structure
- console.log(`[DEBUG] Message ${index} is malformed, creating default structure:`, JSON.stringify(message))
- return { role: 'user', parts: [{ type: 'text', text: '' }] }
- })
-
- // Convert UIMessages to ModelMessages and add system message
- console.log('[DEBUG] Before convertToModelMessages - normalizedMessages:', JSON.stringify(normalizedMessages, null, 2))
- const modelMessages = convertToModelMessages(normalizedMessages)
- console.log('[DEBUG] After convertToModelMessages - modelMessages:', JSON.stringify(modelMessages, null, 2))
-
- // Fix tool call inputs for Bedrock API (requires JSON objects, not strings)
- console.log('[DEBUG] Before fixToolCallInputs - modelMessages:', JSON.stringify(modelMessages, null, 2))
- const fixedMessages = fixToolCallInputs(modelMessages)
- console.log('[DEBUG] After fixToolCallInputs - fixedMessages:', JSON.stringify(fixedMessages, null, 2))
-
- // Replace historical tool call XML with placeholders to reduce tokens
- // Disabled by default - some models (e.g. minimax) copy placeholders instead of generating XML
- const enableHistoryReplace =
- process.env.ENABLE_HISTORY_XML_REPLACE === "true"
- const placeholderMessages = enableHistoryReplace
- ? replaceHistoricalToolInputs(fixedMessages)
- : fixedMessages
-
- // Filter out messages with empty content arrays (Bedrock API rejects these)
- // This is a safety measure - ideally convertToModelMessages should handle all cases
- console.log('[DEBUG] Before filtering - placeholderMessages:', JSON.stringify(placeholderMessages, null, 2))
- let enhancedMessages = placeholderMessages.filter(
- (msg: any) => {
- // Check for both content and parts arrays since messages can have either format
- const hasValidContent = (msg.content && Array.isArray(msg.content) && msg.content.length > 0) ||
- (msg.parts && Array.isArray(msg.parts) && msg.parts.length > 0)
-
- if (!hasValidContent) {
- console.log(`[DEBUG] Message filtered (empty content/parts): role=${msg.role}`)
- return false
- }
-
- // Additional check for empty text-only messages from user
- // This prevents wrapping empty user input in the "User input: ..." block
- if (msg.role === 'user') {
- let parts: any[] = []
- if (msg.parts) {
- parts = msg.parts
- } else if (Array.isArray(msg.content)) {
- parts = msg.content
- } else if (typeof msg.content === 'string') {
- // If content is a non-empty string, it's valid
- if (msg.content.trim() !== '') {
- return true
- }
- // If empty string, fall through to check logic (parts=[])
- }
-
- // Check if there is any non-empty text part
- const hasNonEmptyText = parts.some((p: any) => p.type === 'text' && p.text && p.text.trim() !== '')
- // Check if there are any non-text parts (like images, files)
- const hasOtherParts = parts.some((p: any) => p.type !== 'text')
-
- // If it has only text parts and all are empty, filter it out
- if (!hasNonEmptyText && !hasOtherParts) {
- console.log(`[DEBUG] Message filtered (empty user text): role=${msg.role}`)
- return false
- }
- }
-
- return true
- }
- )
- console.log('[DEBUG] After filtering - enhancedMessages:', JSON.stringify(enhancedMessages, null, 2))
-
- // Update the last message with user input only (XML moved to separate cached system message)
- if (enhancedMessages.length >= 1) {
- const lastModelMessage = enhancedMessages[enhancedMessages.length - 1]
- if (lastModelMessage.role === "user") {
- // Check if this user message is effectively empty (no text content and no files)
- // This acts as a final safety net if the filter above missed it
- const isTextEmpty = !lastMessageText || lastMessageText.trim() === ''
- const hasFiles = fileParts.length > 0
-
- if (isTextEmpty && !hasFiles) {
- console.log('[DEBUG] Dropping empty user message from final payload (safety net)')
- enhancedMessages = enhancedMessages.slice(0, -1)
- } else {
- // Build content array with user input text and file parts
- const contentParts: any[] = [
- { type: "text", text: formattedUserInput },
- ]
-
- // Add image parts back
- for (const filePart of fileParts) {
- const imageUrl =
- filePart?.url ||
- filePart?.image ||
- filePart?.image_url?.url
- if (!imageUrl) continue
- contentParts.push({
- type: "image",
- image: imageUrl,
- mimeType: filePart.mediaType || filePart.mimeType,
- })
- }
-
- enhancedMessages = [
- ...enhancedMessages.slice(0, -1),
- { ...lastModelMessage, content: contentParts },
- ]
- }
- }
- }
-
- // Add cache point to the last assistant message in conversation history
- // This caches the entire conversation prefix for subsequent requests
- // Strategy: system (cached) + history with last assistant (cached) + new user message
- if (shouldCache && enhancedMessages.length >= 2) {
- // Find the last assistant message (should be second-to-last, before current user message)
- for (let i = enhancedMessages.length - 2; i >= 0; i--) {
- if (enhancedMessages[i].role === "assistant") {
- enhancedMessages[i] = {
- ...enhancedMessages[i],
- providerOptions: {
- bedrock: { cachePoint: { type: "default" } },
- },
- }
- break // Only cache the last assistant message
- }
- }
- }
-
- // System messages with multiple cache breakpoints for optimal caching:
- // - Breakpoint 1: Static instructions (~1500 tokens) - rarely changes
- // - Breakpoint 2: Current XML context - changes per diagram, but constant within a conversation turn
- // This allows: if only user message changes, both system caches are reused
- // if XML changes, instruction cache is still reused
- const systemMessages = [
- {
- role: "system" as const,
- content: systemMessage,
- ...(shouldCache && {
- providerOptions: {
- bedrock: { cachePoint: { type: "default" } },
- },
- }),
- },
- {
- role: "system" as const,
- content: `${previousXml ? `Previous diagram XML (before user's last message):\n"""xml\n${previousXml}\n"""\n\n` : ""}Current diagram XML (AUTHORITATIVE - the source of truth):\n"""xml\n${xml || ""}\n"""\n\nIMPORTANT: The "Current diagram XML" is the SINGLE SOURCE OF TRUTH for what's on the canvas right now. The user can manually add, delete, or modify shapes directly in draw.io. Always count and describe elements based on the CURRENT XML, not on what you previously generated. If both previous and current XML are shown, compare them to understand what the user changed. When using edit_diagram, COPY search patterns exactly from the CURRENT XML - attribute order matters!`,
- ...(shouldCache && {
- providerOptions: {
- bedrock: { cachePoint: { type: "default" } },
- },
- }),
- },
- ]
-
- const allMessages = [...systemMessages, ...enhancedMessages]
-
- const promptPayload = {
- timestamp: new Date().toISOString(),
- modelId,
- sessionId: validSessionId,
- userId,
- messages: allMessages,
- }
-
- const promptLog = JSON.stringify(promptPayload, null, 2)
-
- console.log("[PROMPT]", promptLog)
-
- try {
- const logDir = process.env.PROMPT_LOG_DIR || process.cwd()
- const logPath = path.join(logDir, "llm-prompts.log")
- await appendFile(logPath, `${promptLog}\n`)
- } catch (error) {
- console.error("[PROMPT] Failed to write prompt log:", error)
- }
-
- const stream = createUIMessageStream({
- execute: async ({ writer }) => {
- try {
- const maxTokensEnv = process.env.MAX_OUTPUT_TOKENS
- const parsedMaxTokens = maxTokensEnv
- ? Number.parseInt(maxTokensEnv, 10)
- : undefined
- const safeMaxTokens =
- parsedMaxTokens && parsedMaxTokens > 0
- ? parsedMaxTokens
- : 8192
-
- const result = await streamText({
- model,
- stopWhen: stepCountIs(5),
- messages: allMessages,
- ...(safeMaxTokens && { maxTokens: safeMaxTokens }),
- ...(providerOptions && { providerOptions }),
- ...(headers && { headers }),
- ...(getTelemetryConfig({ sessionId: validSessionId, userId }) && {
- experimental_telemetry: getTelemetryConfig({
- sessionId: validSessionId,
- userId,
- }),
- }),
- experimental_repairToolCall: async ({ toolCall }) => {
- const rawJson =
- typeof toolCall.input === "string"
- ? toolCall.input
- : null
- if (rawJson) {
- try {
- const fixed = rawJson.replace(
- /([a-zA-Z])="(\d+)"/g,
- '$1=\\"$2\\"',
- )
- const parsed = JSON.parse(fixed)
- return {
- type: "tool-call" as const,
- toolCallId: toolCall.toolCallId,
- toolName: toolCall.toolName,
- input: JSON.stringify(parsed),
- }
- } catch {
- // Ignore repair failure and fall through
- }
- }
- return null
- },
- onFinish: ({ text, usage }) => {
- setTraceOutput(text, {
- promptTokens: usage?.inputTokens,
- completionTokens: usage?.outputTokens,
- })
- },
- tools: {
- display_diagram: {
- description: `Display a diagram on draw.io. Pass the XML content inside <root> tags.
-
-VALIDATION RULES (XML will be rejected if violated):
-1. All mxCell elements must be DIRECT children of <root> - never nested
-2. Every mxCell needs a unique id
-3. Every mxCell (except id="0") needs a valid parent attribute
-4. Edge source/target must reference existing cell IDs
-5. Escape special chars in values: &lt; &gt; &amp; &quot;
-6. Always start with: <mxCell id="0"/><mxCell id="1" parent="0"/>
-
-Example with swimlanes and edges (note: all mxCells are siblings):
-<root>
- <mxCell id="0"/>
- <mxCell id="1" parent="0"/>
- <mxCell id="lane1" value="Frontend" style="swimlane;" vertex="1" parent="1">
- <mxGeometry x="40" y="40" width="200" height="200" as="geometry"/>
- </mxCell>
- <mxCell id="step1" value="Step 1" style="rounded=1;" vertex="1" parent="lane1">
- <mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
- </mxCell>
- <mxCell id="lane2" value="Backend" style="swimlane;" vertex="1" parent="1">
- <mxGeometry x="280" y="40" width="200" height="200" as="geometry"/>
- </mxCell>
- <mxCell id="step2" value="Step 2" style="rounded=1;" vertex="1" parent="lane2">
- <mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
- </mxCell>
- <mxCell id="edge1" style="edgeStyle=orthogonalEdgeStyle;endArrow=classic;" edge="1" parent="1" source="step1" target="step2">
- <mxGeometry relative="1" as="geometry"/>
- </mxCell>
-</root>
-
-Notes:
-- For AWS diagrams, use **AWS 2025 icons**.
-- For animated connectors, add "flowAnimation=1" to edge style.
-`,
- inputSchema: z.object({
- xml: z
- .string()
- .describe(
- "XML string to be displayed on draw.io",
- ),
- }),
- },
- edit_diagram: {
- description: `Edit specific parts of the current diagram by replacing exact line matches. Use this tool to make targeted fixes without regenerating the entire XML.
-CRITICAL: Copy-paste the EXACT search pattern from the "Current diagram XML" in system context. Do NOT reorder attributes or reformat - the attribute order in draw.io XML varies and you MUST match it exactly.
-IMPORTANT: Keep edits concise:
-- COPY the exact mxCell line from the current XML (attribute order matters!)
-- Only include the lines that are changing, plus 1-2 surrounding lines for context if needed
-- Break large changes into multiple smaller edits
-- Each search must contain complete lines (never truncate mid-line)
-- First match only - be specific enough to target the right element
-
-鈿狅笍 JSON ESCAPING: Every " inside string values MUST be escaped as \\". Example: x=\\"100\\" y=\\"200\\" - BOTH quotes need backslashes!`,
- inputSchema: z.object({
- edits: z
- .array(
- z.object({
- search: z
- .string()
- .describe(
- "EXACT lines copied from current XML (preserve attribute order!)",
- ),
- replace: z
- .string()
- .describe("Replacement lines"),
- }),
- )
- .describe(
- "Array of search/replace pairs to apply sequentially",
- ),
- }),
- },
- },
- ...(process.env.TEMPERATURE !== undefined && {
- temperature: parseFloat(process.env.TEMPERATURE),
- }),
- })
-
- const uiStream = result.toUIMessageStream()
-
- for await (const message of uiStream as any) {
- const hasToolName =
- (message as any)?.toolName ||
- (Array.isArray((message as any)?.parts) &&
- (message as any).parts.some(
- (part: any) =>
- part.toolName ||
- (part.type &&
- String(part.type).includes("tool")),
- ))
-
- if (hasToolName) {
- console.log(
- "[TOOL EVENT]",
- JSON.stringify(message, null, 2),
- )
- }
-
- writer.write(message)
- }
- } catch (error) {
- console.error("[CRITICAL] streamText failed:", error)
- writer.write({
- type: "error",
- errorText:
- error instanceof Error
- ? error.message
- : String(error),
- })
- }
- },
- })
-
- return createUIMessageStreamResponse({ stream })
-
-}
-
-// Helper to categorize errors and return appropriate response
-function handleError(error: unknown): Response {
- console.error("Error in chat route:", error)
-
- const isDev = process.env.NODE_ENV === "development"
-
- // Check for specific AI SDK error types
- if (APICallError.isInstance(error)) {
- return Response.json(
- {
- error: error.message,
- ...(isDev && {
- details: error.responseBody,
- stack: error.stack,
- }),
- },
- { status: error.statusCode || 500 },
- )
- }
-
- if (LoadAPIKeyError.isInstance(error)) {
- return Response.json(
- {
- error: "Authentication failed. Please check your API key.",
- ...(isDev && {
- stack: error.stack,
- }),
- },
- { status: 401 },
- )
- }
-
- // Fallback for other errors with safety filter
- const message =
- error instanceof Error ? error.message : "An unexpected error occurred"
- const status = (error as any)?.statusCode || (error as any)?.status || 500
-
- // Configuration errors should be explicit so users can fix settings quickly.
- if (
- message.includes("AI_MODEL environment variable is required") ||
- message.includes("API Key is missing")
- ) {
- return Response.json(
- {
- error: "AI configuration is missing. Please fill API Key and Chat Model in top settings.",
- ...(isDev && {
- details: message,
- stack: error instanceof Error ? error.stack : undefined,
- }),
- },
- { status: 400 },
- )
- }
-
- // Prevent leaking API keys, tokens, or other sensitive data
- const lowerMessage = message.toLowerCase()
- const safeMessage =
- lowerMessage.includes("key") ||
- lowerMessage.includes("token") ||
- lowerMessage.includes("sig") ||
- lowerMessage.includes("signature") ||
- lowerMessage.includes("secret") ||
- lowerMessage.includes("password") ||
- lowerMessage.includes("credential")
- ? "Authentication failed. Please check your credentials."
- : message
-
- return Response.json(
- {
- error: safeMessage,
- ...(isDev && {
- details: message,
- stack: error instanceof Error ? error.stack : undefined,
- }),
- },
- { status },
- )
-}
-
-// Wrap handler with error handling
-async function safeHandler(req: Request): Promise<Response> {
- try {
- return await handleChatRequest(req)
- } catch (error) {
- return handleError(error)
- }
-}
-
-// Wrap with Langfuse observe (if configured)
-const observedHandler = wrapWithObserve(safeHandler)
-
-export async function POST(req: Request) {
- return observedHandler(req)
-}
-
-
-
-
-
-
+export { POST } from "../../src/workspaces/flow/api/chat"
diff --git a/api/routes/config.ts b/api/routes/config.ts
index 9db6f4a..6b543c6 100644
--- a/api/routes/config.ts
+++ b/api/routes/config.ts
@@ -1,13 +1 @@
-export async function GET() {
- return Response.json({
- accessCodeRequired: !!process.env.ACCESS_CODE_LIST,
- dailyRequestLimit: Number(process.env.DAILY_REQUEST_LIMIT) || 0,
- dailyTokenLimit: Number(process.env.DAILY_TOKEN_LIMIT) || 0,
- tpmLimit: Number(process.env.TPM_LIMIT) || 0,
- // Expose safe AI config for frontend defaults
- defaultProvider: process.env.AI_PROVIDER || "openai",
- defaultModel: process.env.AI_MODEL || "gpt-4o",
- defaultBaseUrl: process.env.AI_BASE_URL || "",
- })
-}
-
+export { GET } from "../../src/workspaces/flow/api/config"
diff --git a/api/routes/log-feedback.ts b/api/routes/log-feedback.ts
index 3add99a..cd4533d 100644
--- a/api/routes/log-feedback.ts
+++ b/api/routes/log-feedback.ts
@@ -1,113 +1 @@
-import { randomUUID } from "crypto"
-import { z } from "zod"
-import { getLangfuseClient } from "../../src/workspaces/flow/next/lib/langfuse"
-
-const feedbackSchema = z.object({
- messageId: z.string().min(1).max(200),
- feedback: z.enum(["good", "bad"]),
- sessionId: z.string().min(1).max(200).optional(),
-})
-
-export async function POST(req: Request) {
- const langfuse = getLangfuseClient()
- if (!langfuse) {
- return Response.json({ success: true, logged: false })
- }
-
- // Validate input
- let data
- try {
- data = feedbackSchema.parse(await req.json())
- } catch {
- return Response.json(
- { success: false, error: "Invalid input" },
- { status: 400 },
- )
- }
-
- const { messageId, feedback, sessionId } = data
-
- // Get user IP for tracking
- const forwardedFor = req.headers.get("x-forwarded-for")
- const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous"
-
- try {
- // Find the most recent chat trace for this session to attach the score to
- const tracesResponse = await langfuse.api.trace.list({
- sessionId,
- limit: 1,
- })
-
- const traces = tracesResponse.data || []
- const latestTrace = traces[0]
-
- if (!latestTrace) {
- // No trace found for this session - create a standalone feedback trace
- const traceId = randomUUID()
- const timestamp = new Date().toISOString()
-
- await langfuse.api.ingestion.batch({
- batch: [
- {
- type: "trace-create",
- id: randomUUID(),
- timestamp,
- body: {
- id: traceId,
- name: "user-feedback",
- sessionId,
- userId,
- input: { messageId, feedback },
- metadata: {
- source: "feedback-button",
- note: "standalone - no chat trace found",
- },
- timestamp,
- },
- },
- {
- type: "score-create",
- id: randomUUID(),
- timestamp,
- body: {
- id: randomUUID(),
- traceId,
- name: "user-feedback",
- value: feedback === "good" ? 1 : 0,
- comment: `User gave ${feedback} feedback`,
- },
- },
- ],
- })
- } else {
- // Attach score to the existing chat trace
- const timestamp = new Date().toISOString()
-
- await langfuse.api.ingestion.batch({
- batch: [
- {
- type: "score-create",
- id: randomUUID(),
- timestamp,
- body: {
- id: randomUUID(),
- traceId: latestTrace.id,
- name: "user-feedback",
- value: feedback === "good" ? 1 : 0,
- comment: `User gave ${feedback} feedback`,
- },
- },
- ],
- })
- }
-
- return Response.json({ success: true, logged: true })
- } catch (error) {
- console.error("Langfuse feedback error:", error)
- return Response.json(
- { success: false, error: "Failed to log feedback" },
- { status: 500 },
- )
- }
-}
-
+export { POST } from "../../src/workspaces/flow/api/log-feedback"
diff --git a/api/routes/log-save.ts b/api/routes/log-save.ts
index c713e16..f343766 100644
--- a/api/routes/log-save.ts
+++ b/api/routes/log-save.ts
@@ -1,72 +1 @@
-import { randomUUID } from "crypto"
-import { z } from "zod"
-import { getLangfuseClient } from "../../src/workspaces/flow/next/lib/langfuse"
-
-const saveSchema = z.object({
- filename: z.string().min(1).max(255),
- format: z.enum(["drawio", "png", "svg"]),
- sessionId: z.string().min(1).max(200).optional(),
-})
-
-export async function POST(req: Request) {
- const langfuse = getLangfuseClient()
- if (!langfuse) {
- return Response.json({ success: true, logged: false })
- }
-
- // Validate input
- let data
- try {
- data = saveSchema.parse(await req.json())
- } catch {
- return Response.json(
- { success: false, error: "Invalid input" },
- { status: 400 },
- )
- }
-
- const { filename, format, sessionId } = data
-
- try {
- const timestamp = new Date().toISOString()
-
- // Find the most recent chat trace for this session to attach the save flag
- const tracesResponse = await langfuse.api.trace.list({
- sessionId,
- limit: 1,
- })
-
- const traces = tracesResponse.data || []
- const latestTrace = traces[0]
-
- if (latestTrace) {
- // Add a score to the existing trace to flag that user saved
- await langfuse.api.ingestion.batch({
- batch: [
- {
- type: "score-create",
- id: randomUUID(),
- timestamp,
- body: {
- id: randomUUID(),
- traceId: latestTrace.id,
- name: "diagram-saved",
- value: 1,
- comment: `User saved diagram as ${filename}.${format}`,
- },
- },
- ],
- })
- }
- // If no trace found, skip logging (user hasn't chatted yet)
-
- return Response.json({ success: true, logged: !!latestTrace })
- } catch (error) {
- console.error("Langfuse save error:", error)
- return Response.json(
- { success: false, error: "Failed to log save" },
- { status: 500 },
- )
- }
-}
-
+export { POST } from "../../src/workspaces/flow/api/log-save"
diff --git a/api/routes/verify-access-code.ts b/api/routes/verify-access-code.ts
index eb2dc80..5152f2e 100644
--- a/api/routes/verify-access-code.ts
+++ b/api/routes/verify-access-code.ts
@@ -1,33 +1 @@
-export async function POST(req: Request) {
- const accessCodes =
- process.env.ACCESS_CODE_LIST?.split(",")
- .map((code) => code.trim())
- .filter(Boolean) || []
-
- // If no access codes configured, verification always passes
- if (accessCodes.length === 0) {
- return Response.json({
- valid: true,
- message: "No access code required",
- })
- }
-
- const accessCodeHeader = req.headers.get("x-access-code")
-
- if (!accessCodeHeader) {
- return Response.json(
- { valid: false, message: "Access code is required" },
- { status: 401 },
- )
- }
-
- if (!accessCodes.includes(accessCodeHeader)) {
- return Response.json(
- { valid: false, message: "Invalid access code" },
- { status: 401 },
- )
- }
-
- return Response.json({ valid: true, message: "Access code is valid" })
-}
-
+export { POST } from "../../src/workspaces/flow/api/verify-access-code"
diff --git a/src/App.tsx b/src/App.tsx
index 927bedc..f9c0b14 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,6 +1,6 @@
import React, { useState } from "react";
import { Toaster } from "sonner";
-import { FileCode, Layers, Layout, Presentation } from "lucide-react";
+import { FileCode, Hammer, Layers, Presentation, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import { SettingsDialog } from "@/components/SettingsDialog";
import { LandingPage } from "@/pages/LandingPage";
@@ -89,10 +89,13 @@ function App() {
className="flex items-center gap-2.5 font-semibold text-lg tracking-tight text-foreground/90 cursor-pointer"
onClick={() => setShowLanding(true)}
>
- <div className="p-1.5 bg-blue-600/10 rounded-lg shadow-sm ring-1 ring-blue-600/20">
- <Layout className="w-5 h-5 text-blue-600" />
+ <div className="relative p-1.5 bg-blue-600/10 rounded-lg shadow-sm ring-1 ring-blue-600/20">
+ <Square className="w-5 h-5 text-blue-600" />
+ <div className="absolute -bottom-1 -right-1 rounded-full bg-background p-0.5 ring-1 ring-blue-600/25">
+ <Hammer className="w-3 h-3 text-blue-700" />
+ </div>
</div>
- <span>Unified AI Workspace</span>
+ <span>CanvasAnvil</span>
</div>
<div className="flex items-center bg-muted/50 p-1 rounded-xl border border-border/50 shadow-inner">
diff --git a/src/lib/ppt-service.ts b/src/lib/ppt-service.ts
index 7975708..c30a86c 100644
--- a/src/lib/ppt-service.ts
+++ b/src/lib/ppt-service.ts
@@ -10,22 +10,45 @@ export interface PptPage {
description?: string;
note?: string;
layout?: string;
+ materialLabels?: string[];
status?: string;
id?: string;
}
export interface SlideEditRoutingItem {
- slideIndex: number;
- title?: string;
+ slideId: string;
+ kind: "content" | "visual" | "both";
instruction: string;
}
+type ReferenceFileInput = { filename: string; content: string };
+type ReferenceImageAssetInput = { label: string; caption: string; sourceFile: string; sourcePage?: number };
+
const PPT_OUTLINE_SYSTEM = String(pptOutlineSystem || "").trim() || `You are a presentation outline generator.
Return ONLY JSON. Do not wrap in markdown code blocks. Do not include any extra text.`;
const PPT_SLIDES_GENERATE_SYSTEM = String(pptSlidesGenerateSystem || "").trim() || `You are a presentation slide planning agent.
Return ONLY JSON. Do not include any extra text.`;
+const formatReferenceFiles = (referenceFiles?: ReferenceFileInput[]) => {
+ if (!Array.isArray(referenceFiles) || referenceFiles.length === 0) return "";
+ return referenceFiles
+ .slice(0, 5)
+ .map((f, i) => `Reference ${i + 1}: ${f.filename}\n${String(f.content || "").slice(0, 4000)}`)
+ .join("\n\n");
+};
+
+const formatReferenceImageAssets = (assets?: ReferenceImageAssetInput[]) => {
+ if (!Array.isArray(assets) || assets.length === 0) return "";
+ return assets
+ .slice(0, 30)
+ .map((a) => {
+ const pageText = typeof a.sourcePage === "number" ? `, page=${a.sourcePage}` : "";
+ return `- ${a.label}: ${a.caption} (source=${a.sourceFile}${pageText})`;
+ })
+ .join("\n");
+};
+
const parseJsonLoose = (text: string) => {
const raw = String(text || "").trim();
if (!raw) throw new Error("Empty AI response");
@@ -84,6 +107,11 @@ const normalizePages = (value: any): PptPage[] => {
description: typeof p?.description === "string" ? p.description : "",
note: typeof p?.note === "string" ? p.note : undefined,
layout: typeof p?.layout === "string" ? p.layout : undefined,
+ materialLabels: Array.isArray(p?.materialLabels)
+ ? p.materialLabels.map((x: any) => String(x)).filter(Boolean)
+ : Array.isArray(p?.material_labels)
+ ? p.material_labels.map((x: any) => String(x)).filter(Boolean)
+ : [],
}))
.filter((p: PptPage) => p.title.trim().length > 0);
};
@@ -118,21 +146,44 @@ const downloadBlob = (data: Uint8Array | ArrayBuffer, mime: string, filename: st
};
export const pptService = {
- // 1. Generate Outline
- generateOutline: async (topic: string): Promise<PptPage[]> => {
- const prompt = `Create a presentation outline for the topic: "${topic}".
-Return JSON (no extra text). Markdown code block is allowed.
-Return either:
-- a JSON array of slide objects, OR
-- an object with a "slides" array.
-
-Each slide object:
-{ "title": "Slide title", "content": ["bullet 1", "bullet 2"], "description": "visual description for image generation", "note": "speaker notes (optional)", "layout": "layout hint (optional)" }
-
-Rules:
-- Prefer 6-10 slides unless the topic requires otherwise.
-- Each bullet <= 12 words.
-- description must be concrete (subject, composition, lighting, colors, style).`;
+ // A1. PlanFromIdeaAgent
+ generateOutline: async (
+ topic: string,
+ uiLanguage: "zh" | "en" = "zh",
+ referenceFiles?: ReferenceFileInput[],
+ referenceImageAssets?: ReferenceImageAssetInput[]
+ ): Promise<PptPage[]> => {
+ const refText = formatReferenceFiles(referenceFiles);
+ const imageAssetText = formatReferenceImageAssets(referenceImageAssets);
+ const prompt = `PlanFromIdeaAgent
+required:
+- idea_prompt: ${topic}
+- ui_language: ${uiLanguage}
+optional:
+- reference_files_content:
+${refText || "(none)"}
+- reference_image_assets:
+${imageAssetText || "(none)"}
+
+Generate a complete PptPlan.
+Return JSON only (markdown json block allowed).
+Every slide must include:
+- id
+- title
+- content (array of detailed bullets)
+- description
+- layout
+- note
+- materialLabels (array of labels selected from reference_image_assets, max 3; no label not in assets list)
+Rules for materialLabels:
+- Only assign when truly relevant to this slide.
+- It is valid to return [] for slides that do not need material images.
+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).
+`;
const response = await generateChatMessage([
{ role: "system", content: PPT_OUTLINE_SYSTEM },
@@ -141,7 +192,13 @@ Rules:
try {
const parsed = parseJsonLoose(response);
- const pages = normalizePages(parsed);
+ 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 : "",
+ description: typeof p.description === "string" ? p.description : "",
+ }));
if (pages.length === 0) throw new Error("No outline parsed from AI response");
return pages;
} catch (e) {
@@ -150,41 +207,71 @@ Rules:
}
},
- generateSlidesFromDescription: async (description: string): Promise<PptPage[]> => {
- const prompt = `Given the following user description, create a complete slide plan (titles, bullets, and visual descriptions).
-
-User description:
-${description}
-
-Return JSON (no extra text). Markdown code block is allowed.
-Return either:
-- a JSON array of slide objects, OR
-- an object with a "slides" array.
-
-Each slide object:
-{ "title": "Slide title", "content": ["bullet 1", "bullet 2"], "description": "visual description for image generation", "note": "speaker notes (optional)", "layout": "layout hint (optional)" }
-
-Rules:
-- Prefer 6-10 slides unless the description implies otherwise.
-- Bullets are short and specific (<= 12 words each).
-- Descriptions are concrete: subject, composition, lighting, colors, style.
+ // B1. PlanFromOutlineAgent
+ generatePlanFromOutline: async (
+ outlineText: string,
+ uiLanguage: "zh" | "en" = "zh",
+ referenceFiles?: ReferenceFileInput[],
+ referenceImageAssets?: ReferenceImageAssetInput[]
+ ): Promise<PptPage[]> => {
+ const refText = formatReferenceFiles(referenceFiles);
+ const imageAssetText = formatReferenceImageAssets(referenceImageAssets);
+ const prompt = `PlanFromOutlineAgent
+required:
+- outline_text:
+${outlineText}
+- ui_language: ${uiLanguage}
+optional:
+- reference_files_content:
+${refText || "(none)"}
+- reference_image_assets:
+${imageAssetText || "(none)"}
+
+Generate a complete PptPlan from this outline.
+Return JSON only (markdown json block allowed).
+Every slide must include:
+- id
+- title
+- content
+- description
+- layout
+- note
+- materialLabels (array of labels selected from reference_image_assets, max 3; no label not in assets list)
+Rules for materialLabels:
+- Only assign when truly relevant to this slide.
+- It is valid to return [] for slides that do not need material images.
+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).
`;
-
+ const response = await generateChatMessage([
+ { role: "system", content: PPT_OUTLINE_SYSTEM },
+ { role: "user", content: prompt }
+ ], undefined, { timeoutMs: 120000 });
try {
- const response = await generateChatMessage([
- { role: "system", content: PPT_OUTLINE_SYSTEM },
- { role: "user", content: prompt }
- ], undefined, { timeoutMs: 120000 });
const parsed = parseJsonLoose(response);
- const pages = normalizePages(parsed);
- if (pages.length === 0) throw new Error("No slides parsed from AI response");
+ 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 : "",
+ description: typeof p.description === "string" ? p.description : "",
+ }));
+ if (pages.length === 0) throw new Error("No plan parsed from AI response");
return pages;
} catch (e) {
- console.error("Failed to parse slides from description", e);
+ console.error("Failed to parse plan from outline", e);
throw e instanceof Error ? e : new Error("Failed to parse AI response");
}
},
+ // Backward-compatible alias used by legacy workspace path.
+ generateSlidesFromDescription: async (description: string): Promise<PptPage[]> => {
+ return await pptService.generateOutline(description, "zh");
+ },
+
// 2. Generate Description (Refinement)
generatePageDescription: async (pages: PptPage[], index: number, topic: string, referenceFiles: any[]): Promise<PptPage> => {
const page = pages[index];
@@ -249,21 +336,52 @@ Return JSON only (no extra text).`;
},
// 3. Generate Image
- generatePageImage: async (page: PptPage, allPages: PptPage[], templateImage?: string): Promise<string> => {
+ generatePageImage: async (
+ page: PptPage,
+ uiLanguageOrAllPages: "zh" | "en" | PptPage[],
+ templateImageUrl?: string,
+ additionalImagesOrMaterialUrls?: Array<{ url: string; label?: string }> | string[],
+ extraRequirements?: string,
+ ): Promise<string> => {
+ const uiLanguage: "zh" | "en" = Array.isArray(uiLanguageOrAllPages) ? "zh" : uiLanguageOrAllPages;
+ const normalizedAdditional: Array<{ url: string; label?: string }> = Array.isArray(additionalImagesOrMaterialUrls)
+ ? (additionalImagesOrMaterialUrls as any[]).map((x, i) =>
+ typeof x === "string" ? { url: x, label: `MATERIAL_${i + 1}` } : { url: String(x?.url || ""), label: x?.label }
+ ).filter((x) => x.url)
+ : [];
+ const additionalLabelText = normalizedAdditional.length > 0
+ ? normalizedAdditional
+ .map((x, i) => `${i + 1}. ${x.label || `MATERIAL_${i + 1}`}`)
+ .join("\n")
+ : "(none)";
const prompt = `Design a presentation slide image.
Title: ${page.title}
Bullets: ${(page.content || []).join(" | ")}
+Language: ${uiLanguage}
Visual style: modern, professional, clean layout, high contrast, no watermarks.
Scene/subject: ${page.description || page.title}
Format: Landscape 16:9 aspect ratio.
Rules:
+- MUST follow the template reference image style consistently for this slide.
- Avoid large paragraphs of text in the image.
- Prefer diagrammatic/illustrative composition matching the bullets.
+- Uploaded material labels and order (matches additional reference images order exactly):
+${additionalLabelText}
+- If slide description contains token {{image:Name}}, you MUST use the material image whose label is Name.
+- Preserve referenced material image identity exactly: do not redraw, restyle, recolor, or replace with similar content.
+- Keep referenced material aspect ratio and key details intact; avoid cropping away chart/table/flow core content.
+- Follow position instructions in Scene/subject when placing referenced materials (left/right/top/bottom/center/background).
+- If no token is present for a material label, do not force that material into the slide.
+${extraRequirements ? `- Extra requirements: ${extraRequirements}` : ""}
`;
-
+ const additionalReferenceImageUrls = Array.isArray(normalizedAdditional)
+ ? normalizedAdditional.map((x) => String(x?.url || "")).filter(Boolean)
+ : [];
+
return await generateImage({
prompt,
- referenceImageUrl: templateImage
+ referenceImageUrl: templateImageUrl,
+ additionalReferenceImageUrls,
});
},
@@ -294,9 +412,9 @@ Rules:
});
},
- routeSlideEdits: async (slides: Array<{ title: string; bullets: string[] }>, feedback: string): Promise<SlideEditRoutingItem[]> => {
+ routeSlideEdits: async (slides: Array<{ id: string; title: string; bullets: string[]; description?: string; layout?: string; note?: string }>, feedback: string): Promise<SlideEditRoutingItem[]> => {
const slideList = slides
- .map((s, i) => `${i + 1}. ${s.title} :: ${(s.bullets || []).join(" | ")}`)
+ .map((s, i) => `${i + 1}. id=${s.id}; title=${s.title}; bullets=${(s.bullets || []).join(" | ")}; description=${s.description || ""}; layout=${s.layout || ""}; note=${s.note || ""}`)
.join("\n");
const prompt = `You are a routing agent for slide edits.
@@ -307,17 +425,17 @@ User feedback:
${feedback}
Return ONLY JSON array, each item:
-{
- "slideIndex": number, // 0-based
- "instruction": string
-}
+{ "slideId": "slide-2", "kind": "content|visual|both", "instruction": "..." }
Rules:
- If feedback mentions multiple slides, split into multiple items.
- If you are unsure, assign to the most relevant slide.
- Do not invent new slides.
`;
- const response = await generateChatMessage([{ role: "user", content: prompt }]);
+ const response = await generateChatMessage([
+ { role: "system", content: PPT_SLIDES_GENERATE_SYSTEM },
+ { role: "user", content: prompt }
+ ]);
const match = response.match(/\[[\s\S]*\]/);
if (!match) return [];
try {
@@ -325,10 +443,11 @@ Rules:
if (!Array.isArray(parsed)) return [];
return parsed
.map((it: any) => ({
- slideIndex: Number(it.slideIndex),
+ slideId: String(it.slideId || ""),
+ kind: it.kind === "content" || it.kind === "visual" || it.kind === "both" ? it.kind : "both",
instruction: String(it.instruction || ""),
}))
- .filter((it: SlideEditRoutingItem) => Number.isFinite(it.slideIndex) && it.instruction.trim().length > 0);
+ .filter((it: SlideEditRoutingItem) => it.slideId.trim().length > 0 && it.instruction.trim().length > 0);
} catch {
return [];
}
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsx
index 9f2e3f5..9394b1a 100644
--- a/src/workspaces/cad/chat/ChatPanel.tsx
+++ b/src/workspaces/cad/chat/ChatPanel.tsx
@@ -90,7 +90,7 @@ export function ChatPanel({
collapsed = false,
onToggleCollapse,
collapseLocked = false,
- title = "AI 鍔╂墜",
+ title = "AI 助手",
inputPlaceholder,
history = [],
onRestore,
@@ -238,7 +238,7 @@ export function ChatPanel({
if (!content) return content;
let next = content.replace(
/```(?:python|py|python3)\s*[\s\S]*?```/g,
- trText("锛堝凡鍦ㄥ悗鍙版帹瀵煎畬鎴愶級", "(Processed in the background)")
+ trText("(已在后台处理完成)", "(Processed in the background)")
);
next = next
.split("\n")
@@ -249,7 +249,7 @@ export function ChatPanel({
const text = String(inner || "").trim();
if (!text) return full;
if (text.includes('"type"') && text.includes('"cad_images"')) {
- return trText("锛堝凡鎻愪氦瑁呬慨鍥剧敓鎴愪换鍔★級", "(CAD drawing generation task submitted)");
+ return trText("(已提交装修图生成任务)", "(CAD drawing generation task submitted)");
}
if (text.includes('"type"') && text.includes('"cad_plan"')) {
try {
@@ -643,7 +643,7 @@ export function ChatPanel({
setFiles([]);
if (workspaceId === "ppt") onClearPptDraftSlides?.();
- if (workspaceId === "cad" && mode === "text" && /(cad_ready_for_export|涓€閿甛s*(鍑哄浘|鐢熸垚)|one[- ]?click)/i.test(normalizedInput)) {
+ if (workspaceId === "cad" && mode === "text" && /(cad_ready_for_export|一键\s*(出图|生成)|one[- ]?click)/i.test(normalizedInput)) {
const svg2d = cadContext?.svg2d || "";
const planJson = cadContext?.plan ? JSON.stringify(cadContext.plan) : "";
@@ -1163,7 +1163,7 @@ export function ChatPanel({
: "";
if (!agentPrompt) {
- updateLastAssistant(trText(`鏈瘑鍒殑 CAD 瀛愭櫤鑳戒綋锛?{agent}`, `Unrecognized CAD sub-agent: ${agent}`));
+ updateLastAssistant(trText(`未识别的 CAD 子智能体:${agent}`, `Unrecognized CAD sub-agent: ${agent}`));
return;
}
@@ -1645,3 +1645,4 @@ export function ChatPanel({
</div>
);
}
+
diff --git a/src/workspaces/flow/api/chat.ts b/src/workspaces/flow/api/chat.ts
new file mode 100644
index 0000000..9c829c2
--- /dev/null
+++ b/src/workspaces/flow/api/chat.ts
@@ -0,0 +1,1234 @@
+import {
+ APICallError,
+ convertToModelMessages,
+ createUIMessageStream,
+ createUIMessageStreamResponse,
+ generateText,
+ LoadAPIKeyError,
+ stepCountIs,
+ streamText,
+} from "ai"
+import { appendFile } from "fs/promises"
+import path from "path"
+import { z } from "zod"
+import { extractText, getDocumentProxy } from "unpdf"
+import mammoth from "mammoth"
+import {
+ getAIModel,
+ supportsPromptCaching,
+} from "../next/lib/ai-providers"
+import {
+ getTelemetryConfig,
+ setTraceInput,
+ setTraceOutput,
+ wrapWithObserve,
+} from "../next/lib/langfuse"
+import { getSystemPrompt } from "../next/lib/system-prompts"
+
+export const maxDuration = 300
+
+// File upload limits (must match client-side)
+const MAX_FILE_SIZE = 2 * 1024 * 1024 // 2MB
+const MAX_FILES = 5
+
+const SUMMARY_CONCURRENCY = 50
+const CHUNK_TOKEN_TARGET = 2500
+const RECURSIVE_THRESHOLD_TOKENS = 50000
+
+type UploadedFilePayload = {
+ name: string
+ mediaType?: string
+ dataUrl: string
+ extractedText?: string
+}
+
+function estimateTokens(text: string): number {
+ return Math.ceil(String(text || "").length / 4)
+}
+
+function cleanExtractedText(input: string): string {
+ const text = String(input || "")
+ .replace(/\r/g, "\n")
+ .replace(/[ \t]+\n/g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .replace(/[ \t]{2,}/g, " ")
+ .trim()
+ return text
+ .split("\n")
+ .filter((line) => {
+ const l = line.trim()
+ if (!l) return false
+ if (/^arXiv:\d{4}\.\d{4,5}/i.test(l)) return false
+ if (/^\[\d+\]\s*$/.test(l)) return false
+ if (/^Page\s+\d+(\s+of\s+\d+)?$/i.test(l)) return false
+ return true
+ })
+ .join("\n")
+ .trim()
+}
+
+function splitByApproxTokens(text: string, chunkTokens: number): string[] {
+ const chunkChars = Math.max(2000, chunkTokens * 4)
+ const overlapChars = Math.floor(chunkChars * 0.1)
+ const normalized = String(text || "").trim()
+ if (!normalized) return []
+ const chunks: string[] = []
+ let start = 0
+ while (start < normalized.length) {
+ const end = Math.min(start + chunkChars, normalized.length)
+ chunks.push(normalized.slice(start, end))
+ if (end >= normalized.length) break
+ start = Math.max(0, end - overlapChars)
+ }
+ return chunks
+}
+
+async function runWithConcurrency<T, R>(
+ items: T[],
+ limit: number,
+ worker: (item: T, index: number) => Promise<R>,
+): Promise<R[]> {
+ if (items.length === 0) return []
+ const results = new Array<R>(items.length)
+ let cursor = 0
+ const runners = Array.from({ length: Math.min(limit, items.length) }).map(
+ async () => {
+ while (true) {
+ const idx = cursor
+ cursor += 1
+ if (idx >= items.length) return
+ results[idx] = await worker(items[idx], idx)
+ }
+ },
+ )
+ await Promise.all(runners)
+ return results
+}
+
+function getFileExtension(name: string): string {
+ const n = String(name || "")
+ const i = n.lastIndexOf(".")
+ return i >= 0 ? n.slice(i).toLowerCase() : ""
+}
+
+function parseDataUrl(dataUrl: string): { mediaType: string; base64: string } {
+ const raw = String(dataUrl || "")
+ const m = raw.match(/^data:([^;]+);base64,(.*)$/)
+ if (!m) throw new Error("Invalid data URL")
+ return { mediaType: m[1], base64: m[2] }
+}
+
+async function extractUploadedFileText(file: UploadedFilePayload): Promise<string> {
+ const providedText =
+ typeof file.extractedText === "string"
+ ? cleanExtractedText(file.extractedText)
+ : ""
+
+ const { mediaType, base64 } = parseDataUrl(file.dataUrl)
+ const buffer = Buffer.from(base64, "base64")
+ const ext = getFileExtension(file.name)
+ const mt = String(file.mediaType || mediaType || "").toLowerCase()
+
+ if (mt.includes("pdf") || ext === ".pdf") {
+ // If client already extracted enough text, trust it.
+ if (providedText.length >= 200) return providedText
+
+ const pdf = await getDocumentProxy(new Uint8Array(buffer))
+ const { text } = await extractText(pdf, { mergePages: true })
+ const parsed = cleanExtractedText(String(text || ""))
+ return parsed.length >= providedText.length ? parsed : providedText
+ }
+
+ if (mt.includes("wordprocessingml.document") || ext === ".docx") {
+ if (providedText) return providedText
+ const result = await mammoth.extractRawText({ buffer })
+ return cleanExtractedText(String(result.value || ""))
+ }
+
+ if (
+ mt.startsWith("text/") ||
+ [".txt", ".md", ".markdown", ".json", ".csv", ".xml", ".yaml", ".yml", ".toml", ".py", ".js", ".ts"].includes(ext)
+ ) {
+ if (providedText) return providedText
+ return cleanExtractedText(buffer.toString("utf8"))
+ }
+
+ return providedText || cleanExtractedText(buffer.toString("utf8"))
+}
+
+async function summarizeChunk(
+ model: any,
+ providerOptions: any,
+ headers: any,
+ chunk: string,
+): Promise<string> {
+ return generateSummaryWithRetry({
+ model,
+ providerOptions,
+ headers,
+ system:
+ "You are a strict summarizer. Output only direct summary text, no questions, no instructions.",
+ user: `���񣺽����������ı����ժҪ��<=300�֣�����ֹ���ʡ���ֹ���û��������ݡ���ֹ���ģ�廯���ס�\n\n�ı���\n${chunk}`,
+ maxOutputTokens: 600,
+ maxChars: 300,
+ fallbackSource: chunk,
+ })
+}
+
+function extractiveFallbackSummary(source: string, maxChars: number): string {
+ const cleaned = cleanExtractedText(String(source || ""))
+ .replace(/\s+/g, " ")
+ .trim()
+ if (!cleaned) return ""
+ const sentences = cleaned
+ .split(/(?<=[������.!?])\s+/)
+ .map((s) => s.trim())
+ .filter(Boolean)
+ const out: string[] = []
+ let total = 0
+ for (const s of sentences) {
+ if (s.length < 10) continue
+ if (total + s.length > maxChars) break
+ out.push(s)
+ total += s.length + 1
+ if (out.length >= 6) break
+ }
+ if (out.length > 0) return out.join(" ")
+ return cleaned.slice(0, maxChars)
+}
+
+function sanitizeSummaryText(summary: string, fallbackSource: string, maxChars: number): string {
+ const text = String(summary || "").trim()
+ if (!text) return extractiveFallbackSummary(fallbackSource, maxChars)
+ const bannedPatterns = [
+ /���ṩ/i,
+ /��ճ��/i,
+ /��Ҫ�ϲ�/i,
+ /����ƫ��/i,
+ /Ŀ�����/i,
+ /�Ƿ�������/i,
+ /�Ƿ���Ҫǿ��/i,
+ /I can|please provide|paste|preference/i,
+ ]
+ if (bannedPatterns.some((p) => p.test(text))) {
+ return extractiveFallbackSummary(fallbackSource, maxChars)
+ }
+ return text.slice(0, Math.max(120, maxChars))
+}
+
+function isBadSummaryText(text: string): boolean {
+ const t = String(text || "").trim()
+ if (!t) return true
+ return [
+ /���ṩ/i,
+ /��ճ��/i,
+ /��Ҫ�ϲ�/i,
+ /����ƫ��/i,
+ /�Ƿ�������/i,
+ /please provide|paste/i,
+ ].some((p) => p.test(t))
+}
+
+async function generateSummaryWithRetry(args: {
+ model: any
+ providerOptions: any
+ headers: any
+ system: string
+ user: string
+ maxOutputTokens: number
+ maxChars: number
+ fallbackSource: string
+}): Promise<string> {
+ for (let i = 0; i < 2; i++) {
+ const r = await generateText({
+ model: args.model,
+ messages: [
+ { role: "system" as const, content: args.system },
+ { role: "user" as const, content: args.user },
+ ],
+ ...(args.providerOptions && { providerOptions: args.providerOptions }),
+ ...(args.headers && { headers: args.headers }),
+ maxOutputTokens: args.maxOutputTokens,
+ })
+ const text = sanitizeSummaryText(
+ String(r.text || "").trim(),
+ args.fallbackSource,
+ args.maxChars,
+ )
+ if (!isBadSummaryText(text)) return text
+ }
+ return extractiveFallbackSummary(args.fallbackSource, args.maxChars)
+}
+
+async function summarizeBlockMethod(args: {
+ model: any
+ providerOptions: any
+ headers: any
+ text: string
+}): Promise<string> {
+ const chunks = splitByApproxTokens(args.text, CHUNK_TOKEN_TARGET)
+ const partial = await runWithConcurrency(
+ chunks,
+ SUMMARY_CONCURRENCY,
+ (chunk) => summarizeChunk(args.model, args.providerOptions, args.headers, chunk),
+ )
+ const merged = partial.filter(Boolean).join("\n")
+ return generateSummaryWithRetry({
+ model: args.model,
+ providerOptions: args.providerOptions,
+ headers: args.headers,
+ system:
+ "You produce concise, faithful merged summaries. Output only summary text.",
+ user: `���񣺽����·ֿ�ժҪ�ϲ�Ϊ����ժҪ��<=1000�֣�����ֹ���ʡ���ֹ���󲹳���ϣ������ժҪ���ġ�\n\n${merged}`,
+ maxOutputTokens: 1800,
+ maxChars: 1000,
+ fallbackSource: merged,
+ })
+}
+
+async function summarizeRecursiveMethod(args: {
+ model: any
+ providerOptions: any
+ headers: any
+ text: string
+}): Promise<string> {
+ const baseChunks = splitByApproxTokens(args.text, 3000)
+ let level = await runWithConcurrency(
+ baseChunks,
+ SUMMARY_CONCURRENCY,
+ (chunk) => summarizeChunk(args.model, args.providerOptions, args.headers, chunk),
+ )
+ level = level.filter(Boolean)
+
+ while (level.length > 2) {
+ const groups: string[] = []
+ for (let i = 0; i < level.length; i += 5) {
+ groups.push(level.slice(i, i + 5).join("\n"))
+ }
+ level = await runWithConcurrency(
+ groups,
+ SUMMARY_CONCURRENCY,
+ async (group) =>
+ generateSummaryWithRetry({
+ model: args.model,
+ providerOptions: args.providerOptions,
+ headers: args.headers,
+ system:
+ "You merge summaries into a higher-level summary. Output only summary text.",
+ user: `���񣺰�����ժҪ�����ɸ��߲�ժҪ��<=350�֣�����ֹ���ʡ���ֹ���û����䣬ֻ���ժҪ��\n\n${group}`,
+ maxOutputTokens: 800,
+ maxChars: 350,
+ fallbackSource: group,
+ }),
+ )
+ level = level.filter(Boolean)
+ }
+
+ return generateSummaryWithRetry({
+ model: args.model,
+ providerOptions: args.providerOptions,
+ headers: args.headers,
+ system:
+ "You produce final executive summaries with hierarchical fidelity and no hallucination. Output only summary text.",
+ user: `�����������ժҪ��<=1000�֣�����ֹ���ʡ���ֹ���������Ϣ�������ժҪ���ġ�\n\n${level.join("\n")}`,
+ maxOutputTokens: 1800,
+ maxChars: 1000,
+ fallbackSource: level.join("\n"),
+ })
+}
+
+function validateUploadedFiles(uploadedFiles: UploadedFilePayload[]): {
+ valid: boolean
+ error?: string
+} {
+ if (uploadedFiles.length > MAX_FILES) {
+ return {
+ valid: false,
+ error: `Too many files. Maximum ${MAX_FILES} allowed.`,
+ }
+ }
+ for (const f of uploadedFiles) {
+ try {
+ const { base64 } = parseDataUrl(f.dataUrl)
+ const sizeInBytes = Math.ceil((base64.length * 3) / 4)
+ if (sizeInBytes > MAX_FILE_SIZE) {
+ return {
+ valid: false,
+ error: `File exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit.`,
+ }
+ }
+ } catch {
+ return {
+ valid: false,
+ error: `Invalid uploaded file payload: ${f.name || "unknown"}`,
+ }
+ }
+ }
+ return { valid: true }
+}
+
+// Helper function to validate file parts in messages
+function validateFileParts(messages: any[]): {
+ valid: boolean
+ error?: string
+} {
+ const lastMessage = messages[messages.length - 1]
+ const fileParts =
+ lastMessage?.parts?.filter((p: any) => p.type === "file") || []
+
+ if (fileParts.length > MAX_FILES) {
+ return {
+ valid: false,
+ error: `Too many files. Maximum ${MAX_FILES} allowed.`,
+ }
+ }
+
+ for (const filePart of fileParts) {
+ // Data URLs format: data:image/png;base64,<data>
+ // Base64 increases size by ~33%, so we check the decoded size
+ if (filePart.url?.startsWith("data:")) {
+ const base64Data = filePart.url.split(",")[1]
+ if (base64Data) {
+ const sizeInBytes = Math.ceil((base64Data.length * 3) / 4)
+ if (sizeInBytes > MAX_FILE_SIZE) {
+ return {
+ valid: false,
+ error: `File exceeds ${MAX_FILE_SIZE / 1024 / 1024}MB limit.`,
+ }
+ }
+ }
+ }
+ }
+
+ return { valid: true }
+}
+
+// Helper function to check if diagram is minimal/empty
+function isMinimalDiagram(xml: string): boolean {
+ const stripped = xml.replace(/\s/g, "")
+ return !stripped.includes('id="2"')
+}
+
+// Helper function to replace historical tool call XML with placeholders
+// This reduces token usage and forces LLM to rely on the current diagram XML (source of truth)
+function replaceHistoricalToolInputs(messages: any[]): any[] {
+ return messages.map((msg) => {
+ if (msg.role !== "assistant" || !Array.isArray(msg.content)) {
+ return msg
+ }
+ const replacedContent = msg.content.map((part: any) => {
+ if (part.type === "tool-call") {
+ const toolName = part.toolName
+ if (
+ toolName === "display_diagram" ||
+ toolName === "edit_diagram"
+ ) {
+ return {
+ ...part,
+ input: {
+ placeholder:
+ "[XML content replaced - see current diagram XML in system context]",
+ },
+ }
+ }
+ }
+ return part
+ })
+ return { ...msg, content: replacedContent }
+ })
+}
+
+// Helper function to fix tool call inputs for Bedrock API
+// Bedrock requires toolUse.input to be a JSON object, not a string
+function fixToolCallInputs(messages: any[]): any[] {
+ return messages.map((msg) => {
+ if (msg.role !== "assistant" || !Array.isArray(msg.content)) {
+ return msg
+ }
+ const fixedContent = msg.content.map((part: any) => {
+ if (part.type === "tool-call") {
+ if (typeof part.input === "string") {
+ try {
+ const parsed = JSON.parse(part.input)
+ return { ...part, input: parsed }
+ } catch {
+ // If parsing fails, wrap the string in an object
+ return { ...part, input: { rawInput: part.input } }
+ }
+ }
+ // Input is already an object, but verify it's not null/undefined
+ if (part.input === null || part.input === undefined) {
+ return { ...part, input: {} }
+ }
+ }
+ return part
+ })
+ return { ...msg, content: fixedContent }
+ })
+}
+
+// Inner handler function
+async function handleChatRequest(req: Request): Promise<Response> {
+ console.log('[EARLY DEBUG] handleChatRequest executed')
+ // Check for access code
+ const accessCodes =
+ process.env.ACCESS_CODE_LIST?.split(",")
+ .map((code) => code.trim())
+ .filter(Boolean) || []
+ if (accessCodes.length > 0) {
+ const accessCodeHeader = req.headers.get("x-access-code")
+ if (!accessCodeHeader || !accessCodes.includes(accessCodeHeader)) {
+ return Response.json(
+ {
+ error: "Invalid or missing access code. Please configure it in Settings.",
+ },
+ { status: 401 },
+ )
+ }
+ }
+
+ const payload = await req.json()
+ const { messages, xml, previousXml, sessionId } = payload || {}
+ const uploadedFiles: UploadedFilePayload[] = Array.isArray(payload?.uploadedFiles)
+ ? payload.uploadedFiles
+ : []
+ const bodyAIConfig = payload?.aiConfig || {}
+
+ // Debug: log the actual message structure received
+ console.log("[DEBUG] Received messages:", JSON.stringify(messages, null, 2))
+ console.log("[DEBUG] First message structure:", messages?.[0] ? JSON.stringify(messages[0], null, 2) : "No messages")
+
+ // Validate messages array
+ if (!messages || !Array.isArray(messages)) {
+ return Response.json(
+ { error: "Messages must be an array" },
+ { status: 400 }
+ )
+ }
+
+ // Get user IP for Langfuse tracking
+ const forwardedFor = req.headers.get("x-forwarded-for")
+ const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous"
+
+ // Validate sessionId for Langfuse (must be string, max 200 chars)
+ const validSessionId =
+ sessionId && typeof sessionId === "string" && sessionId.length <= 200
+ ? sessionId
+ : undefined
+
+ // Extract user input text for Langfuse trace
+ const currentMessage = messages[messages.length - 1]
+ const userInputText =
+ currentMessage?.parts?.find((p: any) => p.type === "text")?.text || ""
+
+ // Update Langfuse trace with input, session, and user
+ setTraceInput({
+ input: userInputText,
+ sessionId: validSessionId,
+ userId: userId,
+ })
+
+ // === FILE VALIDATION START ===
+ const fileValidation = validateFileParts(messages)
+ if (!fileValidation.valid) {
+ return Response.json({ error: fileValidation.error }, { status: 400 })
+ }
+ const uploadedValidation = validateUploadedFiles(uploadedFiles)
+ if (!uploadedValidation.valid) {
+ return Response.json({ error: uploadedValidation.error }, { status: 400 })
+ }
+ // === FILE VALIDATION END ===
+
+ // Read client AI provider overrides from headers first, then body fallback.
+ const clientOverrides = {
+ provider:
+ req.headers.get("x-ai-provider") ||
+ (typeof bodyAIConfig.provider === "string"
+ ? bodyAIConfig.provider
+ : null),
+ baseUrl:
+ req.headers.get("x-ai-base-url") ||
+ (typeof bodyAIConfig.baseUrl === "string"
+ ? bodyAIConfig.baseUrl
+ : null),
+ apiKey:
+ req.headers.get("x-ai-api-key") ||
+ (typeof bodyAIConfig.apiKey === "string"
+ ? bodyAIConfig.apiKey
+ : null),
+ modelId:
+ req.headers.get("x-ai-model") ||
+ req.headers.get("x-ai-chat-model") ||
+ (typeof bodyAIConfig.chatModel === "string"
+ ? bodyAIConfig.chatModel
+ : typeof bodyAIConfig.modelId === "string"
+ ? bodyAIConfig.modelId
+ : null),
+ }
+
+ // Get AI model with optional client overrides
+ const { model, providerOptions, headers, modelId } =
+ getAIModel(clientOverrides)
+
+ // Check if model supports prompt caching
+ const shouldCache = supportsPromptCaching(modelId)
+ console.log(
+ `[Prompt Caching] ${shouldCache ? "ENABLED" : "DISABLED"} for model: ${modelId}`,
+ )
+
+ let parsedFilesContext = ""
+ if (uploadedFiles.length > 0) {
+ const fileSummaries = await runWithConcurrency(
+ uploadedFiles,
+ SUMMARY_CONCURRENCY,
+ async (file) => {
+ const extracted = await extractUploadedFileText(file)
+ const tokens = estimateTokens(extracted)
+ const method =
+ tokens >= RECURSIVE_THRESHOLD_TOKENS ? "recursive" : "chunk"
+ const summary =
+ method === "recursive"
+ ? await summarizeRecursiveMethod({
+ model,
+ providerOptions,
+ headers,
+ text: extracted,
+ })
+ : await summarizeBlockMethod({
+ model,
+ providerOptions,
+ headers,
+ text: extracted,
+ })
+ return { name: file.name, tokens, method, summary }
+ },
+ )
+
+ parsedFilesContext = fileSummaries
+ .map(
+ (item, idx) =>
+ `[Parsed File ${idx + 1}: ${item.name}]\nmethod=${item.method}; estimated_tokens=${item.tokens}\n${item.summary}`,
+ )
+ .join("\n\n")
+ }
+
+ // Get the appropriate system prompt based on model (extended for Opus/Haiku 4.5)
+ let systemMessage = getSystemPrompt(modelId)
+
+ // Append global constraints if present
+ const globalConstraintsHeader = req.headers.get("x-ai-constraints")
+ const globalConstraintsBody =
+ typeof payload?.aiConstraints === "string"
+ ? payload.aiConstraints
+ : ""
+ const globalConstraintsRaw =
+ globalConstraintsHeader || globalConstraintsBody
+ if (globalConstraintsRaw) {
+ const globalConstraints = globalConstraintsHeader
+ ? decodeURIComponent(globalConstraintsRaw)
+ : globalConstraintsRaw
+ systemMessage += `\n\n=== GLOBAL CONSTRAINTS ===\nThe user has set the following global constraints which MUST be followed for every response:\n${globalConstraints}\n==========================\n`
+ }
+
+ const lastMessage = messages[messages.length - 1]
+
+ // Handle case where messages array is empty
+ if (!lastMessage) {
+ return Response.json(
+ { error: "No messages provided" },
+ { status: 400 }
+ )
+ }
+
+ // Extract text from the last message parts or content
+ let lastMessageText = ""
+ if (lastMessage.content && typeof lastMessage.content === "string") {
+ lastMessageText = lastMessage.content
+ } else if (Array.isArray(lastMessage.content)) {
+ lastMessageText = lastMessage.content
+ .filter((part: any) => part.type === "text" || typeof part === "string")
+ .map((part: any) => (typeof part === "string" ? part : part.text || ""))
+ .join("")
+ } else {
+ lastMessageText =
+ lastMessage.parts?.find((part: any) => part.type === "text")?.text || ""
+ }
+
+ // Extract file parts (images) from the last message
+ // Note: If using standard 'content' array with images, they might need different handling
+ // but for now we primarily support our custom 'parts' format for files
+ const partsFileParts =
+ lastMessage.parts?.filter((part: any) => part.type === "file") || []
+ const contentImageParts = Array.isArray(lastMessage.content)
+ ? lastMessage.content.filter(
+ (part: any) =>
+ part?.type === "image_url" ||
+ part?.type === "image" ||
+ part?.type === "file",
+ )
+ : []
+ const fileParts = [...partsFileParts, ...contentImageParts]
+
+ // User input only - XML is now in a separate cached system message
+ const formattedUserInput = `User input:
+"""md
+${lastMessageText}
+"""
+${parsedFilesContext ? `\n\nParsed file summaries:\n"""md\n${parsedFilesContext}\n"""` : ""}`
+
+ // Validate messages structure before conversion
+ if (!messages || !Array.isArray(messages)) {
+ return Response.json(
+ { error: "Invalid messages format: expected array" },
+ { status: 400 }
+ )
+ }
+
+ // Validate each message has required structure
+ for (let i = 0; i < messages.length; i++) {
+ const message = messages[i]
+ console.log(`[DEBUG] Validating message ${i}:`, JSON.stringify(message, null, 2))
+
+ if (!message || typeof message !== 'object') {
+ return Response.json(
+ { error: `Invalid message format: expected object at index ${i}` },
+ { status: 400 }
+ )
+ }
+ if (!message.role || typeof message.role !== 'string') {
+ return Response.json(
+ { error: `Invalid message format: missing role at index ${i}` },
+ { status: 400 }
+ )
+ }
+ // Vercel AI SDK can send messages with different content formats
+ // - messages with parts array (our custom format)
+ // - messages with content array (standard format)
+ // - messages with content string (standard format)
+ if (!message.parts && !message.content) {
+ return Response.json(
+ { error: `Invalid message format: missing content or parts at index ${i}, message: ${JSON.stringify(message)}` },
+ { status: 400 }
+ )
+ }
+ if (message.parts && !Array.isArray(message.parts)) {
+ return Response.json(
+ { error: `Invalid message format: parts must be array at index ${i}` },
+ { status: 400 }
+ )
+ }
+ if (message.content && typeof message.content !== 'string' && !Array.isArray(message.content)) {
+ return Response.json(
+ { error: `Invalid message format: content must be string or array at index ${i}` },
+ { status: 400 }
+ )
+ }
+ }
+
+ // Normalize messages to expected format (convert content to parts if needed)
+ const normalizedMessages = messages.map((message: any, index: number) => {
+ // Handle completely malformed messages
+ if (!message) {
+ console.log(`[DEBUG] Message ${index} is null/undefined, creating default structure`)
+ return { role: 'user', parts: [{ type: 'text', text: '' }] }
+ }
+
+ // If message already has parts, keep it as is
+ if (message.parts && Array.isArray(message.parts)) {
+ return message
+ }
+
+ // If message has content, convert to parts format
+ if (message.content) {
+ let parts: any[] = []
+
+ if (typeof message.content === 'string') {
+ // Convert string content to text part
+ parts = [{ type: 'text', text: message.content }]
+ } else if (Array.isArray(message.content)) {
+ // Convert content array to parts array
+ parts = message.content.map((item: any) => {
+ if (typeof item === 'string') {
+ return { type: 'text', text: item }
+ } else if (item.type === 'text') {
+ return { type: 'text', text: item.text || '' }
+ } else if (item.type === 'image') {
+ return { type: 'image', image: item.image || item.url, mimeType: item.mimeType }
+ } else if (item.type === "image_url") {
+ return {
+ type: "image",
+ image: item.image_url?.url || item.url || "",
+ mimeType: item.mimeType,
+ }
+ } else if (item.type === "file") {
+ return {
+ type: "image",
+ image: item.url || item.image || "",
+ mimeType: item.mediaType || item.mimeType,
+ }
+ }
+ return { type: 'text', text: String(item) }
+ })
+ }
+
+ return { ...message, parts, content: undefined }
+ }
+
+ // Handle messages with no content and no parts but have role
+ if (message.role) {
+ console.log(`[DEBUG] Message ${index} has role but no content/parts, adding empty parts`)
+ return { ...message, parts: [] }
+ }
+
+ // Fallback: create default message structure
+ console.log(`[DEBUG] Message ${index} is malformed, creating default structure:`, JSON.stringify(message))
+ return { role: 'user', parts: [{ type: 'text', text: '' }] }
+ })
+
+ // Convert UIMessages to ModelMessages and add system message
+ console.log('[DEBUG] Before convertToModelMessages - normalizedMessages:', JSON.stringify(normalizedMessages, null, 2))
+ const modelMessages = convertToModelMessages(normalizedMessages)
+ console.log('[DEBUG] After convertToModelMessages - modelMessages:', JSON.stringify(modelMessages, null, 2))
+
+ // Fix tool call inputs for Bedrock API (requires JSON objects, not strings)
+ console.log('[DEBUG] Before fixToolCallInputs - modelMessages:', JSON.stringify(modelMessages, null, 2))
+ const fixedMessages = fixToolCallInputs(modelMessages)
+ console.log('[DEBUG] After fixToolCallInputs - fixedMessages:', JSON.stringify(fixedMessages, null, 2))
+
+ // Replace historical tool call XML with placeholders to reduce tokens
+ // Disabled by default - some models (e.g. minimax) copy placeholders instead of generating XML
+ const enableHistoryReplace =
+ process.env.ENABLE_HISTORY_XML_REPLACE === "true"
+ const placeholderMessages = enableHistoryReplace
+ ? replaceHistoricalToolInputs(fixedMessages)
+ : fixedMessages
+
+ // Filter out messages with empty content arrays (Bedrock API rejects these)
+ // This is a safety measure - ideally convertToModelMessages should handle all cases
+ console.log('[DEBUG] Before filtering - placeholderMessages:', JSON.stringify(placeholderMessages, null, 2))
+ let enhancedMessages = placeholderMessages.filter(
+ (msg: any) => {
+ // Check for both content and parts arrays since messages can have either format
+ const hasValidContent = (msg.content && Array.isArray(msg.content) && msg.content.length > 0) ||
+ (msg.parts && Array.isArray(msg.parts) && msg.parts.length > 0)
+
+ if (!hasValidContent) {
+ console.log(`[DEBUG] Message filtered (empty content/parts): role=${msg.role}`)
+ return false
+ }
+
+ // Additional check for empty text-only messages from user
+ // This prevents wrapping empty user input in the "User input: ..." block
+ if (msg.role === 'user') {
+ let parts: any[] = []
+ if (msg.parts) {
+ parts = msg.parts
+ } else if (Array.isArray(msg.content)) {
+ parts = msg.content
+ } else if (typeof msg.content === 'string') {
+ // If content is a non-empty string, it's valid
+ if (msg.content.trim() !== '') {
+ return true
+ }
+ // If empty string, fall through to check logic (parts=[])
+ }
+
+ // Check if there is any non-empty text part
+ const hasNonEmptyText = parts.some((p: any) => p.type === 'text' && p.text && p.text.trim() !== '')
+ // Check if there are any non-text parts (like images, files)
+ const hasOtherParts = parts.some((p: any) => p.type !== 'text')
+
+ // If it has only text parts and all are empty, filter it out
+ if (!hasNonEmptyText && !hasOtherParts) {
+ console.log(`[DEBUG] Message filtered (empty user text): role=${msg.role}`)
+ return false
+ }
+ }
+
+ return true
+ }
+ )
+ console.log('[DEBUG] After filtering - enhancedMessages:', JSON.stringify(enhancedMessages, null, 2))
+
+ // Update the last message with user input only (XML moved to separate cached system message)
+ if (enhancedMessages.length >= 1) {
+ const lastModelMessage = enhancedMessages[enhancedMessages.length - 1]
+ if (lastModelMessage.role === "user") {
+ // Check if this user message is effectively empty (no text content and no files)
+ // This acts as a final safety net if the filter above missed it
+ const isTextEmpty = !lastMessageText || lastMessageText.trim() === ''
+ const hasFiles = fileParts.length > 0
+
+ if (isTextEmpty && !hasFiles) {
+ console.log('[DEBUG] Dropping empty user message from final payload (safety net)')
+ enhancedMessages = enhancedMessages.slice(0, -1)
+ } else {
+ // Build content array with user input text and file parts
+ const contentParts: any[] = [
+ { type: "text", text: formattedUserInput },
+ ]
+
+ // Add image parts back
+ for (const filePart of fileParts) {
+ const imageUrl =
+ filePart?.url ||
+ filePart?.image ||
+ filePart?.image_url?.url
+ if (!imageUrl) continue
+ contentParts.push({
+ type: "image",
+ image: imageUrl,
+ mimeType: filePart.mediaType || filePart.mimeType,
+ })
+ }
+
+ enhancedMessages = [
+ ...enhancedMessages.slice(0, -1),
+ { ...lastModelMessage, content: contentParts },
+ ]
+ }
+ }
+ }
+
+ // Add cache point to the last assistant message in conversation history
+ // This caches the entire conversation prefix for subsequent requests
+ // Strategy: system (cached) + history with last assistant (cached) + new user message
+ if (shouldCache && enhancedMessages.length >= 2) {
+ // Find the last assistant message (should be second-to-last, before current user message)
+ for (let i = enhancedMessages.length - 2; i >= 0; i--) {
+ if (enhancedMessages[i].role === "assistant") {
+ enhancedMessages[i] = {
+ ...enhancedMessages[i],
+ providerOptions: {
+ bedrock: { cachePoint: { type: "default" } },
+ },
+ }
+ break // Only cache the last assistant message
+ }
+ }
+ }
+
+ // System messages with multiple cache breakpoints for optimal caching:
+ // - Breakpoint 1: Static instructions (~1500 tokens) - rarely changes
+ // - Breakpoint 2: Current XML context - changes per diagram, but constant within a conversation turn
+ // This allows: if only user message changes, both system caches are reused
+ // if XML changes, instruction cache is still reused
+ const systemMessages = [
+ {
+ role: "system" as const,
+ content: systemMessage,
+ ...(shouldCache && {
+ providerOptions: {
+ bedrock: { cachePoint: { type: "default" } },
+ },
+ }),
+ },
+ {
+ role: "system" as const,
+ content: `${previousXml ? `Previous diagram XML (before user's last message):\n"""xml\n${previousXml}\n"""\n\n` : ""}Current diagram XML (AUTHORITATIVE - the source of truth):\n"""xml\n${xml || ""}\n"""\n\nIMPORTANT: The "Current diagram XML" is the SINGLE SOURCE OF TRUTH for what's on the canvas right now. The user can manually add, delete, or modify shapes directly in draw.io. Always count and describe elements based on the CURRENT XML, not on what you previously generated. If both previous and current XML are shown, compare them to understand what the user changed. When using edit_diagram, COPY search patterns exactly from the CURRENT XML - attribute order matters!`,
+ ...(shouldCache && {
+ providerOptions: {
+ bedrock: { cachePoint: { type: "default" } },
+ },
+ }),
+ },
+ ]
+
+ const allMessages = [...systemMessages, ...enhancedMessages]
+
+ const promptPayload = {
+ timestamp: new Date().toISOString(),
+ modelId,
+ sessionId: validSessionId,
+ userId,
+ messages: allMessages,
+ }
+
+ const promptLog = JSON.stringify(promptPayload, null, 2)
+
+ console.log("[PROMPT]", promptLog)
+
+ try {
+ const logDir = process.env.PROMPT_LOG_DIR || process.cwd()
+ const logPath = path.join(logDir, "llm-prompts.log")
+ await appendFile(logPath, `${promptLog}\n`)
+ } catch (error) {
+ console.error("[PROMPT] Failed to write prompt log:", error)
+ }
+
+ const stream = createUIMessageStream({
+ execute: async ({ writer }) => {
+ try {
+ const maxTokensEnv = process.env.MAX_OUTPUT_TOKENS
+ const parsedMaxTokens = maxTokensEnv
+ ? Number.parseInt(maxTokensEnv, 10)
+ : undefined
+ const safeMaxTokens =
+ parsedMaxTokens && parsedMaxTokens > 0
+ ? parsedMaxTokens
+ : 8192
+
+ const result = await streamText({
+ model,
+ stopWhen: stepCountIs(5),
+ messages: allMessages,
+ ...(safeMaxTokens && { maxTokens: safeMaxTokens }),
+ ...(providerOptions && { providerOptions }),
+ ...(headers && { headers }),
+ ...(getTelemetryConfig({ sessionId: validSessionId, userId }) && {
+ experimental_telemetry: getTelemetryConfig({
+ sessionId: validSessionId,
+ userId,
+ }),
+ }),
+ experimental_repairToolCall: async ({ toolCall }) => {
+ const rawJson =
+ typeof toolCall.input === "string"
+ ? toolCall.input
+ : null
+ if (rawJson) {
+ try {
+ const fixed = rawJson.replace(
+ /([a-zA-Z])="(\d+)"/g,
+ '$1=\\"$2\\"',
+ )
+ const parsed = JSON.parse(fixed)
+ return {
+ type: "tool-call" as const,
+ toolCallId: toolCall.toolCallId,
+ toolName: toolCall.toolName,
+ input: JSON.stringify(parsed),
+ }
+ } catch {
+ // Ignore repair failure and fall through
+ }
+ }
+ return null
+ },
+ onFinish: ({ text, usage }) => {
+ setTraceOutput(text, {
+ promptTokens: usage?.inputTokens,
+ completionTokens: usage?.outputTokens,
+ })
+ },
+ tools: {
+ display_diagram: {
+ description: `Display a diagram on draw.io. Pass the XML content inside <root> tags.
+
+VALIDATION RULES (XML will be rejected if violated):
+1. All mxCell elements must be DIRECT children of <root> - never nested
+2. Every mxCell needs a unique id
+3. Every mxCell (except id="0") needs a valid parent attribute
+4. Edge source/target must reference existing cell IDs
+5. Escape special chars in values: &lt; &gt; &amp; &quot;
+6. Always start with: <mxCell id="0"/><mxCell id="1" parent="0"/>
+
+Example with swimlanes and edges (note: all mxCells are siblings):
+<root>
+ <mxCell id="0"/>
+ <mxCell id="1" parent="0"/>
+ <mxCell id="lane1" value="Frontend" style="swimlane;" vertex="1" parent="1">
+ <mxGeometry x="40" y="40" width="200" height="200" as="geometry"/>
+ </mxCell>
+ <mxCell id="step1" value="Step 1" style="rounded=1;" vertex="1" parent="lane1">
+ <mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
+ </mxCell>
+ <mxCell id="lane2" value="Backend" style="swimlane;" vertex="1" parent="1">
+ <mxGeometry x="280" y="40" width="200" height="200" as="geometry"/>
+ </mxCell>
+ <mxCell id="step2" value="Step 2" style="rounded=1;" vertex="1" parent="lane2">
+ <mxGeometry x="20" y="60" width="160" height="40" as="geometry"/>
+ </mxCell>
+ <mxCell id="edge1" style="edgeStyle=orthogonalEdgeStyle;endArrow=classic;" edge="1" parent="1" source="step1" target="step2">
+ <mxGeometry relative="1" as="geometry"/>
+ </mxCell>
+</root>
+
+Notes:
+- For AWS diagrams, use **AWS 2025 icons**.
+- For animated connectors, add "flowAnimation=1" to edge style.
+`,
+ inputSchema: z.object({
+ xml: z
+ .string()
+ .describe(
+ "XML string to be displayed on draw.io",
+ ),
+ }),
+ },
+ edit_diagram: {
+ description: `Edit specific parts of the current diagram by replacing exact line matches. Use this tool to make targeted fixes without regenerating the entire XML.
+CRITICAL: Copy-paste the EXACT search pattern from the "Current diagram XML" in system context. Do NOT reorder attributes or reformat - the attribute order in draw.io XML varies and you MUST match it exactly.
+IMPORTANT: Keep edits concise:
+- COPY the exact mxCell line from the current XML (attribute order matters!)
+- Only include the lines that are changing, plus 1-2 surrounding lines for context if needed
+- Break large changes into multiple smaller edits
+- Each search must contain complete lines (never truncate mid-line)
+- First match only - be specific enough to target the right element
+
+⚠️ JSON ESCAPING: Every " inside string values MUST be escaped as \\". Example: x=\\"100\\" y=\\"200\\" - BOTH quotes need backslashes!`,
+ inputSchema: z.object({
+ edits: z
+ .array(
+ z.object({
+ search: z
+ .string()
+ .describe(
+ "EXACT lines copied from current XML (preserve attribute order!)",
+ ),
+ replace: z
+ .string()
+ .describe("Replacement lines"),
+ }),
+ )
+ .describe(
+ "Array of search/replace pairs to apply sequentially",
+ ),
+ }),
+ },
+ },
+ ...(process.env.TEMPERATURE !== undefined && {
+ temperature: parseFloat(process.env.TEMPERATURE),
+ }),
+ })
+
+ const uiStream = result.toUIMessageStream()
+
+ for await (const message of uiStream as any) {
+ const hasToolName =
+ (message as any)?.toolName ||
+ (Array.isArray((message as any)?.parts) &&
+ (message as any).parts.some(
+ (part: any) =>
+ part.toolName ||
+ (part.type &&
+ String(part.type).includes("tool")),
+ ))
+
+ if (hasToolName) {
+ console.log(
+ "[TOOL EVENT]",
+ JSON.stringify(message, null, 2),
+ )
+ }
+
+ writer.write(message)
+ }
+ } catch (error) {
+ console.error("[CRITICAL] streamText failed:", error)
+ writer.write({
+ type: "error",
+ errorText:
+ error instanceof Error
+ ? error.message
+ : String(error),
+ })
+ }
+ },
+ })
+
+ return createUIMessageStreamResponse({ stream })
+
+}
+
+// Helper to categorize errors and return appropriate response
+function handleError(error: unknown): Response {
+ console.error("Error in chat route:", error)
+
+ const isDev = process.env.NODE_ENV === "development"
+
+ // Check for specific AI SDK error types
+ if (APICallError.isInstance(error)) {
+ return Response.json(
+ {
+ error: error.message,
+ ...(isDev && {
+ details: error.responseBody,
+ stack: error.stack,
+ }),
+ },
+ { status: error.statusCode || 500 },
+ )
+ }
+
+ if (LoadAPIKeyError.isInstance(error)) {
+ return Response.json(
+ {
+ error: "Authentication failed. Please check your API key.",
+ ...(isDev && {
+ stack: error.stack,
+ }),
+ },
+ { status: 401 },
+ )
+ }
+
+ // Fallback for other errors with safety filter
+ const message =
+ error instanceof Error ? error.message : "An unexpected error occurred"
+ const status = (error as any)?.statusCode || (error as any)?.status || 500
+
+ // Configuration errors should be explicit so users can fix settings quickly.
+ if (
+ message.includes("AI_MODEL environment variable is required") ||
+ message.includes("API Key is missing")
+ ) {
+ return Response.json(
+ {
+ error: "AI configuration is missing. Please fill API Key and Chat Model in top settings.",
+ ...(isDev && {
+ details: message,
+ stack: error instanceof Error ? error.stack : undefined,
+ }),
+ },
+ { status: 400 },
+ )
+ }
+
+ // Prevent leaking API keys, tokens, or other sensitive data
+ const lowerMessage = message.toLowerCase()
+ const safeMessage =
+ lowerMessage.includes("key") ||
+ lowerMessage.includes("token") ||
+ lowerMessage.includes("sig") ||
+ lowerMessage.includes("signature") ||
+ lowerMessage.includes("secret") ||
+ lowerMessage.includes("password") ||
+ lowerMessage.includes("credential")
+ ? "Authentication failed. Please check your credentials."
+ : message
+
+ return Response.json(
+ {
+ error: safeMessage,
+ ...(isDev && {
+ details: message,
+ stack: error instanceof Error ? error.stack : undefined,
+ }),
+ },
+ { status },
+ )
+}
+
+// Wrap handler with error handling
+async function safeHandler(req: Request): Promise<Response> {
+ try {
+ return await handleChatRequest(req)
+ } catch (error) {
+ return handleError(error)
+ }
+}
+
+// Wrap with Langfuse observe (if configured)
+const observedHandler = wrapWithObserve(safeHandler)
+
+export async function POST(req: Request) {
+ return observedHandler(req)
+}
+
+
+
+
+
+
+
diff --git a/src/workspaces/flow/api/config.ts b/src/workspaces/flow/api/config.ts
new file mode 100644
index 0000000..9db6f4a
--- /dev/null
+++ b/src/workspaces/flow/api/config.ts
@@ -0,0 +1,13 @@
+export async function GET() {
+ return Response.json({
+ accessCodeRequired: !!process.env.ACCESS_CODE_LIST,
+ dailyRequestLimit: Number(process.env.DAILY_REQUEST_LIMIT) || 0,
+ dailyTokenLimit: Number(process.env.DAILY_TOKEN_LIMIT) || 0,
+ tpmLimit: Number(process.env.TPM_LIMIT) || 0,
+ // Expose safe AI config for frontend defaults
+ defaultProvider: process.env.AI_PROVIDER || "openai",
+ defaultModel: process.env.AI_MODEL || "gpt-4o",
+ defaultBaseUrl: process.env.AI_BASE_URL || "",
+ })
+}
+
diff --git a/src/workspaces/flow/api/log-feedback.ts b/src/workspaces/flow/api/log-feedback.ts
new file mode 100644
index 0000000..dfb1c35
--- /dev/null
+++ b/src/workspaces/flow/api/log-feedback.ts
@@ -0,0 +1,114 @@
+import { randomUUID } from "crypto"
+import { z } from "zod"
+import { getLangfuseClient } from "../next/lib/langfuse"
+
+const feedbackSchema = z.object({
+ messageId: z.string().min(1).max(200),
+ feedback: z.enum(["good", "bad"]),
+ sessionId: z.string().min(1).max(200).optional(),
+})
+
+export async function POST(req: Request) {
+ const langfuse = getLangfuseClient()
+ if (!langfuse) {
+ return Response.json({ success: true, logged: false })
+ }
+
+ // Validate input
+ let data
+ try {
+ data = feedbackSchema.parse(await req.json())
+ } catch {
+ return Response.json(
+ { success: false, error: "Invalid input" },
+ { status: 400 },
+ )
+ }
+
+ const { messageId, feedback, sessionId } = data
+
+ // Get user IP for tracking
+ const forwardedFor = req.headers.get("x-forwarded-for")
+ const userId = forwardedFor?.split(",")[0]?.trim() || "anonymous"
+
+ try {
+ // Find the most recent chat trace for this session to attach the score to
+ const tracesResponse = await langfuse.api.trace.list({
+ sessionId,
+ limit: 1,
+ })
+
+ const traces = tracesResponse.data || []
+ const latestTrace = traces[0]
+
+ if (!latestTrace) {
+ // No trace found for this session - create a standalone feedback trace
+ const traceId = randomUUID()
+ const timestamp = new Date().toISOString()
+
+ await langfuse.api.ingestion.batch({
+ batch: [
+ {
+ type: "trace-create",
+ id: randomUUID(),
+ timestamp,
+ body: {
+ id: traceId,
+ name: "user-feedback",
+ sessionId,
+ userId,
+ input: { messageId, feedback },
+ metadata: {
+ source: "feedback-button",
+ note: "standalone - no chat trace found",
+ },
+ timestamp,
+ },
+ },
+ {
+ type: "score-create",
+ id: randomUUID(),
+ timestamp,
+ body: {
+ id: randomUUID(),
+ traceId,
+ name: "user-feedback",
+ value: feedback === "good" ? 1 : 0,
+ comment: `User gave ${feedback} feedback`,
+ },
+ },
+ ],
+ })
+ } else {
+ // Attach score to the existing chat trace
+ const timestamp = new Date().toISOString()
+
+ await langfuse.api.ingestion.batch({
+ batch: [
+ {
+ type: "score-create",
+ id: randomUUID(),
+ timestamp,
+ body: {
+ id: randomUUID(),
+ traceId: latestTrace.id,
+ name: "user-feedback",
+ value: feedback === "good" ? 1 : 0,
+ comment: `User gave ${feedback} feedback`,
+ },
+ },
+ ],
+ })
+ }
+
+ return Response.json({ success: true, logged: true })
+ } catch (error) {
+ console.error("Langfuse feedback error:", error)
+ return Response.json(
+ { success: false, error: "Failed to log feedback" },
+ { status: 500 },
+ )
+ }
+}
+
+
diff --git a/src/workspaces/flow/api/log-save.ts b/src/workspaces/flow/api/log-save.ts
new file mode 100644
index 0000000..c6ff654
--- /dev/null
+++ b/src/workspaces/flow/api/log-save.ts
@@ -0,0 +1,73 @@
+import { randomUUID } from "crypto"
+import { z } from "zod"
+import { getLangfuseClient } from "../next/lib/langfuse"
+
+const saveSchema = z.object({
+ filename: z.string().min(1).max(255),
+ format: z.enum(["drawio", "png", "svg"]),
+ sessionId: z.string().min(1).max(200).optional(),
+})
+
+export async function POST(req: Request) {
+ const langfuse = getLangfuseClient()
+ if (!langfuse) {
+ return Response.json({ success: true, logged: false })
+ }
+
+ // Validate input
+ let data
+ try {
+ data = saveSchema.parse(await req.json())
+ } catch {
+ return Response.json(
+ { success: false, error: "Invalid input" },
+ { status: 400 },
+ )
+ }
+
+ const { filename, format, sessionId } = data
+
+ try {
+ const timestamp = new Date().toISOString()
+
+ // Find the most recent chat trace for this session to attach the save flag
+ const tracesResponse = await langfuse.api.trace.list({
+ sessionId,
+ limit: 1,
+ })
+
+ const traces = tracesResponse.data || []
+ const latestTrace = traces[0]
+
+ if (latestTrace) {
+ // Add a score to the existing trace to flag that user saved
+ await langfuse.api.ingestion.batch({
+ batch: [
+ {
+ type: "score-create",
+ id: randomUUID(),
+ timestamp,
+ body: {
+ id: randomUUID(),
+ traceId: latestTrace.id,
+ name: "diagram-saved",
+ value: 1,
+ comment: `User saved diagram as ${filename}.${format}`,
+ },
+ },
+ ],
+ })
+ }
+ // If no trace found, skip logging (user hasn't chatted yet)
+
+ return Response.json({ success: true, logged: !!latestTrace })
+ } catch (error) {
+ console.error("Langfuse save error:", error)
+ return Response.json(
+ { success: false, error: "Failed to log save" },
+ { status: 500 },
+ )
+ }
+}
+
+
diff --git a/src/workspaces/flow/api/verify-access-code.ts b/src/workspaces/flow/api/verify-access-code.ts
new file mode 100644
index 0000000..eb2dc80
--- /dev/null
+++ b/src/workspaces/flow/api/verify-access-code.ts
@@ -0,0 +1,33 @@
+export async function POST(req: Request) {
+ const accessCodes =
+ process.env.ACCESS_CODE_LIST?.split(",")
+ .map((code) => code.trim())
+ .filter(Boolean) || []
+
+ // If no access codes configured, verification always passes
+ if (accessCodes.length === 0) {
+ return Response.json({
+ valid: true,
+ message: "No access code required",
+ })
+ }
+
+ const accessCodeHeader = req.headers.get("x-access-code")
+
+ if (!accessCodeHeader) {
+ return Response.json(
+ { valid: false, message: "Access code is required" },
+ { status: 401 },
+ )
+ }
+
+ if (!accessCodes.includes(accessCodeHeader)) {
+ return Response.json(
+ { valid: false, message: "Invalid access code" },
+ { status: 401 },
+ )
+ }
+
+ return Response.json({ valid: true, message: "Access code is valid" })
+}
+
diff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/src/workspaces/flow/next/components/chat-panel.tsx
index 15709b8..88de6bf 100644
--- a/src/workspaces/flow/next/components/chat-panel.tsx
+++ b/src/workspaces/flow/next/components/chat-panel.tsx
@@ -297,8 +297,8 @@ ${xml}
}
}
} else if (toolCall.toolName === "edit_diagram") {
- // 浠?LLM 鐨勫伐鍏疯皟鐢ㄥ弬鏁颁腑瑙f瀯鍑?edits 鏁扮粍
- // 姣忎釜鍏冪礌閮芥槸 { search: 鍘熸潵鐨?XML 鐗囨, replace: 瑕佹浛鎹㈡垚鐨勬柊鐗囨 }
+ // Parse edits from tool-call params.
+ // Each item is { search: original XML snippet, replace: new snippet }.
const { edits } = toolCall.input as {
edits: Array<{ search: string; replace: string }>
}
@@ -306,8 +306,8 @@ ${xml}
let currentXml = ""
try {
console.log("[edit_diagram] Starting...")
- // 浼樺厛浣跨敤鍐呭瓨涓紦瀛樼殑 chartXML锛岄伩鍏嶆瘡娆¢兘鍚?draw.io 瀵煎嚭 XML
- // 杩欐牱鏇寸ǔ瀹氾紙灏ゅ叾鏄湪杩滅▼鐜锛屾瘮濡?Vercel 涓?iframe 鍙兘鏈夊欢杩燂級
+ // Prefer cached chart XML to avoid exporting from draw.io each time.
+ // This is more stable in remote iframe environments.
const cachedXML = chartXMLRef.current
if (cachedXML) {
currentXml = cachedXML
@@ -316,7 +316,7 @@ ${xml}
currentXml.length,
)
} else {
- // 濡傛灉娌℃湁缂撳瓨锛堜緥濡傞〉闈㈠垰鍒锋柊锛夛紝閫€鍥炲埌浠?draw.io iframe 瀵煎嚭涓€娆″畬鏁?XML
+ // Fallback: export full XML from draw.io iframe.
console.log(
"[edit_diagram] No cached XML, fetching from DrawIO...",
)
@@ -327,14 +327,14 @@ ${xml}
)
}
- // 鍔ㄦ€佸紩鍏ュ伐鍏峰嚱鏁帮紝鐢?search/replace 瀵瑰師濮?XML 鍋氬眬閮ㄦ浛鎹?
+ // Apply local search/replace edits against current XML.
const { replaceXMLParts } = await import("@/workspaces/flow/next/lib/utils")
const editedXml = replaceXMLParts(currentXml, edits)
- // 鎶婃浛鎹㈠悗鐨?XML 閲嶆柊鍔犺浇鍒扮敾甯冧笂锛屽悓鏃跺仛涓€娆$粨鏋勬牎楠?
+ // Reload edited XML and validate.
const validationError = onDisplayChart(editedXml)
if (validationError) {
- // 濡傛灉鏂?XML 闈炴硶锛屽氨鍦ㄨ亰澶╅噷缁欏嚭閿欒淇℃伅锛屾彁绀虹敤鎴?/ 妯″瀷閲嶆柊鐢熸垚
+ // If XML is invalid, surface the error in chat.
console.warn(
"[edit_diagram] Validation error:",
validationError,
@@ -348,7 +348,7 @@ ${xml}
Please fix the XML issues. Ensure you are editing exact lines from the current XML.`,
})
} else {
- // 鎴愬姛锛氭洿鏂扮紦瀛樹腑鐨?XML锛屽苟鍦ㄨ亰澶╅噷璁板綍鈥滅紪杈戞垚鍔熲€?
+ // Success: update cache and log completion.
chartXMLRef.current = editedXml
addToolOutput({
tool: "edit_diagram",
@@ -357,7 +357,7 @@ Please fix the XML issues. Ensure you are editing exact lines from the current X
})
}
} catch (error) {
- // 浠讳綍杩愯鏃堕敊璇兘浼氳蛋杩欓噷锛堟瘮濡?search 鏈懡涓€佸瓧绗︿覆鏇挎崲澶辫触绛夛級
+ // Catch any runtime failure (search miss, replace failure, etc.).
console.error("[edit_diagram] Error:", error)
addToolOutput({
tool: "edit_diagram",
diff --git a/src/workspaces/flow/next/lib/cached-responses.ts b/src/workspaces/flow/next/lib/cached-responses.ts
index 5cdc5a0..6a499b0 100644
--- a/src/workspaces/flow/next/lib/cached-responses.ts
+++ b/src/workspaces/flow/next/lib/cached-responses.ts
@@ -657,27 +657,27 @@ export const CACHED_EXAMPLE_RESPONSES: CachedResponse[] = [
</mxCell>
<mxCell id="model1" parent="1"
style="text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=11;spacingLeft=10;"
- value="鈥?GPT-3 (175B)" vertex="1">
+ value="• GPT-3 (175B)" vertex="1">
<mxGeometry height="20" width="90" x="400" y="480" as="geometry" />
</mxCell>
<mxCell id="model2" parent="1"
style="text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=11;spacingLeft=10;"
- value="鈥?LaMDA (137B)" vertex="1">
+ value="• LaMDA (137B)" vertex="1">
<mxGeometry height="20" width="90" x="400" y="500" as="geometry" />
</mxCell>
<mxCell id="model3" parent="1"
style="text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=11;spacingLeft=10;"
- value="鈥?PaLM (540B)" vertex="1">
+ value="• PaLM (540B)" vertex="1">
<mxGeometry height="20" width="90" x="400" y="520" as="geometry" />
</mxCell>
<mxCell id="model4" parent="1"
style="text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=11;spacingLeft=10;"
- value="鈥?Codex" vertex="1">
+ value="• Codex" vertex="1">
<mxGeometry height="20" width="80" x="490" y="480" as="geometry" />
</mxCell>
<mxCell id="model5" parent="1"
style="text;html=1;strokeColor=none;fillColor=none;align=left;verticalAlign=middle;whiteSpace=wrap;rounded=0;fontSize=11;spacingLeft=10;"
- value="鈥?UL2 (20B)" vertex="1">
+ value="• UL2 (20B)" vertex="1">
<mxGeometry height="20" width="80" x="490" y="500" as="geometry" />
</mxCell>
<mxCell id="model_note" parent="1"
@@ -737,7 +737,7 @@ export const CACHED_EXAMPLE_RESPONSES: CachedResponse[] = [
</mxCell>
<mxCell id="limit_box" parent="1"
style="rounded=1;whiteSpace=wrap;html=1;fillColor=#FFEBEE;strokeColor=#C62828;fontSize=10;align=left;spacingLeft=8;"
- value="鈥?Requires large models (~100B+)&lt;br&gt;鈥?No guarantee of correct reasoning&lt;br&gt;鈥?Costly to serve in production"
+ value="• Requires large models (~100B+)&lt;br&gt;• No guarantee of correct reasoning&lt;br&gt;• Costly to serve in production"
vertex="1">
<mxGeometry height="55" width="200" x="310" y="600" as="geometry" />
</mxCell>
diff --git a/src/workspaces/flow/next/lib/pdf-utils.ts b/src/workspaces/flow/next/lib/pdf-utils.ts
index 4ea1f94..cb04b1c 100644
--- a/src/workspaces/flow/next/lib/pdf-utils.ts
+++ b/src/workspaces/flow/next/lib/pdf-utils.ts
@@ -1,5 +1,7 @@
import { extractText, getDocumentProxy } from "unpdf"
-
+import * as mammoth from "mammoth"
+import JSZip from "jszip"
+import { ungzip } from "pako"
// Maximum characters allowed for extracted text (configurable via env)
const DEFAULT_MAX_EXTRACTED_CHARS = 150000 // 150k chars
const viteMaxExtractedChars =
@@ -41,6 +43,7 @@ const TEXT_EXTENSIONS = [
".sh",
".bash",
".zsh",
+ ".tex",
]
/**
@@ -61,6 +64,18 @@ export function isPdfFile(file: File): boolean {
return file.type === "application/pdf" || file.name.endsWith(".pdf")
}
+/**
+ * Check if a file is a Word document (.docx).
+ */
+export function isWordFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ return (
+ file.type ===
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
+ name.endsWith(".docx")
+ )
+}
+
/**
* Check if a file is a text file
*/
@@ -73,6 +88,24 @@ export function isTextFile(file: File): boolean {
)
}
+export function isZipFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ const type = String(file.type || "").toLowerCase()
+ if (name.endsWith(".zip")) return true
+ return (
+ type === "application/zip" ||
+ type === "application/x-zip-compressed" ||
+ type === "application/octet-stream"
+ )
+}
+
+export function isTarGzFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ const type = String(file.type || "").toLowerCase()
+ if (name.endsWith(".tgz") || name.endsWith(".tar.gz")) return true
+ return type === "application/gzip" || type === "application/x-gzip"
+}
+
/**
* Extract text content from a text file
*/
@@ -80,3 +113,1358 @@ export async function extractTextFileContent(file: File): Promise<string> {
return await file.text()
}
+/**
+ * Extract text content from a .docx file.
+ */
+export async function extractWordText(file: File): Promise<string> {
+ const arrayBuffer = await file.arrayBuffer()
+ const result = await mammoth.extractRawText({ arrayBuffer })
+ return String(result.value || "")
+}
+
+const stripLatexToText = (raw: string) => {
+ const s = String(raw || "")
+ .replace(/\r/g, "")
+ .replace(/(^|[^\\])%.*$/gm, "$1")
+ .replace(/\\(begin|end)\{[^}]*\}/g, " ")
+ .replace(/\\[a-zA-Z@]+(\[[^\]]*\])?(\{[^}]*\})?/g, " ")
+ .replace(/\{|\}/g, " ")
+ .replace(/\s+/g, " ")
+ .trim()
+ return s
+}
+
+type ArchiveEntry = { name: string; bytes: Uint8Array }
+type LatexGraphicRef = { includePath: string; sourceTexPath: string; caption: string; searchDirs: string[] }
+
+const parseTarEntries = (tarBytes: Uint8Array): ArchiveEntry[] => {
+ const out: ArchiveEntry[] = []
+ const block = 512
+ let offset = 0
+ while (offset + block <= tarBytes.length) {
+ const header = tarBytes.subarray(offset, offset + block)
+ const isZero = header.every((b) => b === 0)
+ if (isZero) break
+
+ const nameRaw = new TextDecoder("utf-8").decode(header.subarray(0, 100))
+ const prefixRaw = new TextDecoder("utf-8").decode(header.subarray(345, 500))
+ const base = nameRaw.replace(/\0.*$/, "").trim()
+ const prefix = prefixRaw.replace(/\0.*$/, "").trim()
+ const name = `${prefix ? `${prefix}/` : ""}${base}`
+ const sizeRaw = new TextDecoder("utf-8")
+ .decode(header.subarray(124, 136))
+ .replace(/\0.*$/, "")
+ .trim()
+ const size = parseInt(sizeRaw || "0", 8) || 0
+ const typeflag = String.fromCharCode(header[156] || 48)
+
+ const dataStart = offset + block
+ const dataEnd = dataStart + size
+ if (size > 0 && dataEnd <= tarBytes.length && typeflag !== "5") {
+ out.push({ name, bytes: tarBytes.subarray(dataStart, dataEnd) })
+ }
+ const padded = Math.ceil(size / block) * block
+ offset = dataStart + padded
+ }
+ return out
+}
+
+const pickMainTexEntry = (zip: JSZip) => {
+ const texEntries = Object.values(zip.files).filter((f) => !f.dir && /\.tex$/i.test(String(f.name || "")))
+ if (texEntries.length === 0) return null
+ const preferredNames = ["main.tex", "paper.tex", "manuscript.tex", "document.tex"]
+ for (const name of preferredNames) {
+ const hit = texEntries.find((e) => String(e.name || "").toLowerCase().endsWith(name))
+ if (hit) return hit
+ }
+ const score = (entryName: string) => {
+ const n = String(entryName || "").toLowerCase()
+ const depth = n.split("/").length
+ const base = n.split("/").pop() || n
+ let s = 0
+ if (base.includes("main")) s += 6
+ if (base.includes("paper")) s += 4
+ if (base.includes("manuscript")) s += 3
+ if (base.includes("camera")) s += 2
+ if (n.includes("arxiv")) s += 1
+ // Prefer shallower and shorter names.
+ s += Math.max(0, 6 - depth)
+ s += Math.max(0, 140 - n.length) / 50
+ return s
+ }
+ return (
+ texEntries
+ .slice()
+ .sort((a, b) => score(String(b.name || "")) - score(String(a.name || "")))[0] || texEntries[0]
+ )
+}
+
+const pickMainTexFromEntries = (entries: ArchiveEntry[]) => {
+ const texEntries = entries.filter((e) => /\.tex$/i.test(String(e.name || "")))
+ if (texEntries.length === 0) return null
+ const preferredNames = ["main.tex", "paper.tex", "manuscript.tex", "document.tex"]
+ for (const name of preferredNames) {
+ const hit = texEntries.find((e) => String(e.name || "").toLowerCase().endsWith(name))
+ if (hit) return hit
+ }
+ const score = (entryName: string) => {
+ const n = String(entryName || "").toLowerCase()
+ const depth = n.split("/").length
+ const base = n.split("/").pop() || n
+ let s = 0
+ if (base.includes("main")) s += 6
+ if (base.includes("paper")) s += 4
+ if (base.includes("manuscript")) s += 3
+ if (base.includes("camera")) s += 2
+ if (n.includes("arxiv")) s += 1
+ s += Math.max(0, 6 - depth)
+ s += Math.max(0, 140 - n.length) / 50
+ return s
+ }
+ return texEntries.slice().sort((a, b) => score(String(b.name || "")) - score(String(a.name || "")))[0] || texEntries[0]
+}
+
+const normalizePathLike = (value: string) =>
+ String(value || "")
+ .replace(/\\/g, "/")
+ .replace(/^\.\//, "")
+ .replace(/\/{2,}/g, "/")
+ .trim()
+
+const extractGraphicPathDirs = (tex: string, sourceTexPath: string) => {
+ const dirs: string[] = []
+ const baseDir = dirnameOf(sourceTexPath)
+ const gpRe = /\\graphicspath\s*\{([\s\S]*?)\}/g
+ let gm: RegExpExecArray | null
+ while ((gm = gpRe.exec(tex))) {
+ const body = String(gm[1] || "")
+ const dirRe = /\{([^}]+)\}/g
+ let dm: RegExpExecArray | null
+ while ((dm = dirRe.exec(body))) {
+ const d = normalizePathLike(String(dm[1] || "").trim().replace(/^["']|["']$/g, ""))
+ if (!d) continue
+ dirs.push(joinPathLike(baseDir, d))
+ }
+ }
+ return Array.from(new Set(dirs))
+}
+
+const dirnameOf = (path: string) => {
+ const n = normalizePathLike(path)
+ const idx = n.lastIndexOf("/")
+ if (idx < 0) return ""
+ return n.slice(0, idx)
+}
+
+const joinPathLike = (baseDir: string, rel: string) => {
+ const parts = `${baseDir ? `${baseDir}/` : ""}${rel}`.split("/")
+ const out: string[] = []
+ for (const part of parts) {
+ if (!part || part === ".") continue
+ if (part === "..") {
+ out.pop()
+ continue
+ }
+ out.push(part)
+ }
+ return out.join("/")
+}
+
+const resolveTexPathInMap = (baseTexPath: string, target: string, texMap: Map<string, string>) => {
+ const rel = normalizePathLike(target).replace(/^["']|["']$/g, "")
+ if (!rel) return null
+ const hasExt = /\.[a-z0-9]+$/i.test(rel)
+ const candidates = hasExt ? [rel] : [rel, `${rel}.tex`]
+ const baseDir = dirnameOf(baseTexPath)
+
+ for (const c of candidates) {
+ const joined = normalizePathLike(joinPathLike(baseDir, c))
+ if (texMap.has(joined)) return joined
+ const suffix = `/${joined}`
+ const bySuffix = Array.from(texMap.keys()).find((k) => k.endsWith(suffix) || k === joined)
+ if (bySuffix) return bySuffix
+ }
+ return null
+}
+
+const buildTexMapFromZip = async (zip: JSZip) => {
+ const texEntries = Object.values(zip.files).filter((f) => !f.dir && /\.tex$/i.test(String(f.name || "")))
+ const map = new Map<string, string>()
+ for (const entry of texEntries) {
+ const key = normalizePathLike(String(entry.name || ""))
+ const value = await entry.async("string")
+ map.set(key, value)
+ }
+ return map
+}
+
+const buildTexMapFromEntries = (entries: ArchiveEntry[]) => {
+ const map = new Map<string, string>()
+ for (const entry of entries) {
+ if (!/\.tex$/i.test(String(entry.name || ""))) continue
+ const key = normalizePathLike(String(entry.name || ""))
+ const value = new TextDecoder("utf-8").decode(entry.bytes)
+ map.set(key, value)
+ }
+ return map
+}
+
+const collectLatexGraphicsFromMap = (rootTexPath: string, texMap: Map<string, string>) => {
+ const visited = new Set<string>()
+ const graphics: LatexGraphicRef[] = []
+ const textChunks: string[] = []
+
+ const walk = (texPath: string, depth: number) => {
+ if (depth > 20) return
+ const key = normalizePathLike(texPath)
+ if (!key || visited.has(key)) return
+ const tex = texMap.get(key)
+ if (typeof tex !== "string") return
+ visited.add(key)
+ textChunks.push(tex)
+
+ const searchDirs = extractGraphicPathDirs(tex, key)
+ const includeRe = /\\includegraphics\s*(?:\[[\s\S]*?\])?\s*\{([^}]+)\}/g
+ let gm: RegExpExecArray | null
+ while ((gm = includeRe.exec(tex))) {
+ const includePath = String(gm[1] || "").trim()
+ if (!includePath) continue
+ graphics.push({
+ includePath,
+ sourceTexPath: key,
+ caption: extractLatexCaptionNear(tex, gm.index),
+ searchDirs,
+ })
+ }
+
+ const subRe = /\\(?:input|include)\s*\{([^}]+)\}/g
+ let sm: RegExpExecArray | null
+ while ((sm = subRe.exec(tex))) {
+ const target = String(sm[1] || "").trim()
+ const resolved = resolveTexPathInMap(key, target, texMap)
+ if (!resolved) continue
+ walk(resolved, depth + 1)
+ }
+ }
+
+ walk(rootTexPath, 0)
+ return { graphics, mergedText: textChunks.join("\n\n") }
+}
+
+const resolveZipEntryForGraphic = (zip: JSZip, graphicPath: string) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const normalized = raw.replace(/\\/g, "/").replace(/^\.?\//, "")
+ const lower = normalized.toLowerCase()
+ const hasExt = /\.[a-z0-9]+$/i.test(lower)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg"]
+
+ const candidates: string[] = []
+ for (const ext of tryExts) candidates.push(lower + ext)
+
+ const entries = Object.values(zip.files).filter((f) => !f.dir)
+ for (const want of candidates) {
+ const exact = entries.find((e) => String(e.name || "").toLowerCase() === want)
+ if (exact) return exact
+ }
+ for (const want of candidates) {
+ const hit = entries.find((e) => {
+ const n = String(e.name || "").toLowerCase()
+ return n.endsWith(`/${want}`) || n.endsWith(want)
+ })
+ if (hit) return hit
+ }
+ return null
+}
+
+const resolveZipEntryForGraphicFromTex = (zip: JSZip, sourceTexPath: string, graphicPath: string, searchDirs: string[] = []) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const rel = normalizePathLike(raw).replace(/^\.?\//, "")
+ const baseDir = dirnameOf(sourceTexPath)
+ const withBase = joinPathLike(baseDir, rel)
+ const hasExt = /\.[a-z0-9]+$/i.test(rel)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".pdf"]
+ const candidates = [withBase, rel, ...searchDirs.map((d) => joinPathLike(d, rel))]
+ .flatMap((p) => tryExts.map((ext) => normalizePathLike(`${p}${ext}`)))
+ .filter(Boolean)
+
+ const entries = Object.values(zip.files).filter((f) => !f.dir)
+ for (const want of candidates) {
+ const exact = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase() === want.toLowerCase())
+ if (exact) return exact
+ const suffix = `/${want.toLowerCase()}`
+ const bySuffix = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase().endsWith(suffix))
+ if (bySuffix) return bySuffix
+ }
+ return null
+}
+
+const resolveArchiveEntryForGraphic = (entries: ArchiveEntry[], graphicPath: string) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const normalized = raw.replace(/\\/g, "/").replace(/^\.?\//, "")
+ const lower = normalized.toLowerCase()
+ const hasExt = /\.[a-z0-9]+$/i.test(lower)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg"]
+
+ const candidates: string[] = []
+ for (const ext of tryExts) candidates.push(lower + ext)
+
+ for (const want of candidates) {
+ const exact = entries.find((e) => String(e.name || "").toLowerCase() === want)
+ if (exact) return exact
+ }
+ for (const want of candidates) {
+ const hit = entries.find((e) => {
+ const n = String(e.name || "").toLowerCase()
+ return n.endsWith(`/${want}`) || n.endsWith(want)
+ })
+ if (hit) return hit
+ }
+ return null
+}
+
+const resolveArchiveEntryForGraphicFromTex = (entries: ArchiveEntry[], sourceTexPath: string, graphicPath: string, searchDirs: string[] = []) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const rel = normalizePathLike(raw).replace(/^\.?\//, "")
+ const baseDir = dirnameOf(sourceTexPath)
+ const withBase = joinPathLike(baseDir, rel)
+ const hasExt = /\.[a-z0-9]+$/i.test(rel)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".pdf"]
+ const candidates = [withBase, rel, ...searchDirs.map((d) => joinPathLike(d, rel))]
+ .flatMap((p) => tryExts.map((ext) => normalizePathLike(`${p}${ext}`)))
+ .filter(Boolean)
+
+ for (const want of candidates) {
+ const exact = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase() === want.toLowerCase())
+ if (exact) return exact
+ const suffix = `/${want.toLowerCase()}`
+ const bySuffix = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase().endsWith(suffix))
+ if (bySuffix) return bySuffix
+ }
+ return null
+}
+
+const extractLatexCaptionNear = (tex: string, matchIndex: number) => {
+ const windowStart = Math.max(0, matchIndex - 1200)
+ const windowEnd = Math.min(tex.length, matchIndex + 2400)
+ const window = tex.slice(windowStart, windowEnd)
+ const cap = window.match(/\\caption(?:\[[^\]]*\])?\{([\s\S]*?)\}/)
+ if (cap && cap[1]) return stripLatexToText(cap[1]).slice(0, 220)
+ return ""
+}
+
+export async function extractLatexZipText(file: File): Promise<string> {
+ const buffer = await file.arrayBuffer()
+ const zip = await JSZip.loadAsync(buffer)
+ const main = pickMainTexEntry(zip)
+ if (!main) throw new Error("No .tex file found in zip")
+ const texMap = await buildTexMapFromZip(zip)
+ const root = normalizePathLike(String(main.name || ""))
+ const { mergedText } = collectLatexGraphicsFromMap(root, texMap)
+ return stripLatexToText(mergedText || (await main.async("string")))
+}
+
+export async function extractLatexZipVisualAssets(
+ file: File,
+ options?: { maxAssets?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const maxAssets = Math.max(1, options?.maxAssets ?? 12)
+ const buffer = await file.arrayBuffer()
+ const zip = await JSZip.loadAsync(buffer)
+ const main = pickMainTexEntry(zip)
+ if (!main) return []
+ const texMap = await buildTexMapFromZip(zip)
+ const root = normalizePathLike(String(main.name || ""))
+ let { graphics } = collectLatexGraphicsFromMap(root, texMap)
+ if (graphics.length === 0) {
+ for (const texPath of texMap.keys()) {
+ const hit = collectLatexGraphicsFromMap(texPath, texMap).graphics
+ if (hit.length > 0) {
+ graphics = hit
+ break
+ }
+ }
+ }
+ const assets: ExtractedVisualAsset[] = []
+ let order = 0
+ for (const g of graphics) {
+ if (assets.length >= maxAssets) break
+ const entry =
+ resolveZipEntryForGraphicFromTex(zip, g.sourceTexPath, g.includePath, g.searchDirs) ||
+ resolveZipEntryForGraphic(zip, g.includePath)
+ if (!entry) continue
+ const bytes = await entry.async("uint8array")
+ const dataUrl = await latexAssetBytesToDataUrl(entry.name, bytes)
+ if (!dataUrl.startsWith("data:image")) continue
+ order += 1
+ const caption = String(g.caption || "").trim()
+ const hint = caption ? `LaTeX caption: ${caption}` : `LaTeX includegraphics: ${g.includePath}`
+ assets.push({
+ id: `latex-${file.name}-${order}`,
+ sourceFileName: file.name,
+ sourceType: "latex",
+ order,
+ dataUrl,
+ textHint: hint.slice(0, 800),
+ })
+ }
+ return assets
+}
+
+export async function extractLatexTarGzText(file: File): Promise<string> {
+ const buffer = await file.arrayBuffer()
+ const tarBytes = ungzip(new Uint8Array(buffer))
+ const entries = parseTarEntries(tarBytes)
+ const main = pickMainTexFromEntries(entries)
+ if (!main) throw new Error("No .tex file found in tar.gz")
+ const texMap = buildTexMapFromEntries(entries)
+ const root = normalizePathLike(String(main.name || ""))
+ const { mergedText } = collectLatexGraphicsFromMap(root, texMap)
+ return stripLatexToText(mergedText || new TextDecoder("utf-8").decode(main.bytes))
+}
+
+export async function extractLatexTarGzVisualAssets(
+ file: File,
+ options?: { maxAssets?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const maxAssets = Math.max(1, options?.maxAssets ?? 12)
+ const buffer = await file.arrayBuffer()
+ const tarBytes = ungzip(new Uint8Array(buffer))
+ const entries = parseTarEntries(tarBytes)
+ const main = pickMainTexFromEntries(entries)
+ if (!main) return []
+ const texMap = buildTexMapFromEntries(entries)
+ const root = normalizePathLike(String(main.name || ""))
+ let { graphics } = collectLatexGraphicsFromMap(root, texMap)
+ if (graphics.length === 0) {
+ for (const texPath of texMap.keys()) {
+ const hit = collectLatexGraphicsFromMap(texPath, texMap).graphics
+ if (hit.length > 0) {
+ graphics = hit
+ break
+ }
+ }
+ }
+ const assets: ExtractedVisualAsset[] = []
+ let order = 0
+ for (const g of graphics) {
+ if (assets.length >= maxAssets) break
+ const entry =
+ resolveArchiveEntryForGraphicFromTex(entries, g.sourceTexPath, g.includePath, g.searchDirs) ||
+ resolveArchiveEntryForGraphic(entries, g.includePath)
+ if (!entry) continue
+ const dataUrl = await latexAssetBytesToDataUrl(entry.name, entry.bytes)
+ if (!dataUrl.startsWith("data:image")) continue
+ order += 1
+ const caption = String(g.caption || "").trim()
+ const hint = caption ? `LaTeX caption: ${caption}` : `LaTeX includegraphics: ${g.includePath}`
+ assets.push({
+ id: `latex-tgz-${file.name}-${order}`,
+ sourceFileName: file.name,
+ sourceType: "latex",
+ order,
+ dataUrl,
+ textHint: hint.slice(0, 800),
+ })
+ }
+ return assets
+}
+
+export interface ExtractedVisualAsset {
+ id: string
+ sourceFileName: string
+ sourceType: "pdf" | "word" | "latex"
+ page?: number
+ order: number
+ dataUrl: string
+ textHint: string
+}
+
+type PdfTextBox = { text: string; x: number; y: number; w: number; h: number }
+type RegionBox = { x: number; y: number; w: number; h: number }
+type PdfTextLine = { text: string; x: number; y: number; w: number; h: number }
+type VisualCategory =
+ | "framework"
+ | "result_table"
+ | "mechanism"
+ | "key_visual"
+ | "data_structure"
+ | "other"
+
+const USEFUL_VISUAL_PATTERNS = [
+ /(framework|pipeline|workflow|architecture|system diagram|method overview|flowchart|block diagram|methods?|approach|methodology|方法框架|流程图|系统结构|模型架构)/i,
+ /(table\s*\d+|main results|comparison|baseline|sota|significance|accuracy|f1|auc|results table|主实验|结果对比|对比表|显著性|表\s*\d+)/i,
+ /(ablation|sensitivity|parameter analysis|influence|impact|mechanism|变量分析|消融|参数敏感性|影响因素|机制分析)/i,
+ /(qualitative|visualization|case study|example|heatmap|confusion matrix|roc|pr curve|结果可视化|案例图|关键结果图|可视化)/i,
+ /(dataset|data distribution|sample structure|demographics|statistics|数据分布|样本构成|数据结构|样本结构)/i,
+]
+
+const EXCLUDED_VISUAL_HINT_RE =
+ /(equation|theorem|proof|appendix|related work|literature review|survey|公式|定理|证明|附录|相关工作|文献综述|参数设置)/i
+
+const CAPTION_ANCHOR_RE = /(\bfig(?:ure)?\.?\s*\d+\b|\btable\s*\d+\b|图\s*\d+|表\s*\d+)/i
+const CAPTION_LINE_START_RE = /^\s*(fig(?:ure)?\.?|table|图|表)\s*\d+/i
+
+const CATEGORY_PATTERNS: Array<{ category: VisualCategory; re: RegExp[] }> = [
+ {
+ category: "framework",
+ re: [
+ /(framework|pipeline|workflow|architecture|flowchart|block diagram|method overview|模型架构|方法框架|流程图|系统结构)/i,
+ ],
+ },
+ {
+ category: "result_table",
+ re: [
+ /(table\s*\d+|main results|comparison|baseline|sota|significance|results table|结果对比|对比表|显著性|主实验|表\s*\d+)/i,
+ ],
+ },
+ {
+ category: "mechanism",
+ re: [
+ /(ablation|sensitivity|parameter analysis|influence|impact|mechanism|消融|参数敏感性|影响因素|机制分析)/i,
+ ],
+ },
+ {
+ category: "key_visual",
+ re: [
+ /(qualitative|visualization|case study|example|heatmap|confusion matrix|roc|pr curve|可视化|案例图|关键结果图)/i,
+ ],
+ },
+ {
+ category: "data_structure",
+ re: [
+ /(dataset|data distribution|sample structure|demographics|statistics|数据分布|样本构成|数据结构|样本结构)/i,
+ ],
+ },
+]
+const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v))
+
+const bytesToBase64 = (bytes: Uint8Array) => {
+ let binary = ""
+ const chunk = 0x8000
+ for (let i = 0; i < bytes.length; i += chunk) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk))
+ }
+ return btoa(binary)
+}
+
+const getMimeByExt = (name: string) => {
+ const n = String(name || "").toLowerCase()
+ if (n.endsWith(".png")) return "image/png"
+ if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg"
+ if (n.endsWith(".webp")) return "image/webp"
+ if (n.endsWith(".gif")) return "image/gif"
+ if (n.endsWith(".bmp")) return "image/bmp"
+ if (n.endsWith(".svg")) return "image/svg+xml"
+ return "image/png"
+}
+
+const latexAssetBytesToDataUrl = async (name: string, bytes: Uint8Array) => {
+ const n = String(name || "").toLowerCase()
+ if (n.endsWith(".pdf")) {
+ try {
+ const pdf = await getDocumentProxy(bytes)
+ const page = await (pdf as any).getPage(1)
+ const viewport1 = page.getViewport({ scale: 1 })
+ const scale = 1400 / Math.max(1, viewport1.width)
+ const viewport = page.getViewport({ scale })
+ const canvas = document.createElement("canvas")
+ canvas.width = Math.max(1, Math.floor(viewport.width))
+ canvas.height = Math.max(1, Math.floor(viewport.height))
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return ""
+ await page.render({ canvasContext: ctx, viewport }).promise
+ return canvas.toDataURL("image/png")
+ } catch {
+ return ""
+ }
+ }
+ const mime = getMimeByExt(name)
+ return `data:${mime};base64,${bytesToBase64(bytes)}`
+}
+
+const decodeXmlText = (raw: string) => {
+ const s = String(raw || "")
+ return s
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">")
+ .replace(/&quot;/g, '"')
+ .replace(/&apos;/g, "'")
+ .replace(/&amp;/g, "&")
+ .replace(/&#(\d+);/g, (_, n) => {
+ const code = Number(n)
+ if (!Number.isFinite(code)) return ""
+ try {
+ return String.fromCharCode(code)
+ } catch {
+ return ""
+ }
+ })
+}
+
+const renderPdfPageCanvas = async (page: any, targetWidth = 980) => {
+ const viewportAtScale1 = page.getViewport({ scale: 1 })
+ const scale = targetWidth / Math.max(1, viewportAtScale1.width)
+ const viewport = page.getViewport({ scale })
+
+ const canvas = document.createElement("canvas")
+ canvas.width = Math.max(1, Math.floor(viewport.width))
+ canvas.height = Math.max(1, Math.floor(viewport.height))
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return null
+
+ await page.render({ canvasContext: ctx, viewport }).promise
+
+ let pageText = ""
+ const textBoxes: PdfTextBox[] = []
+ try {
+ const text = await page.getTextContent()
+ const items = Array.isArray(text?.items) ? text.items : []
+ for (const it of items) {
+ const str = String((it as any)?.str || "").trim()
+ if (!str) continue
+ pageText += `${str} `
+
+ const transform = Array.isArray((it as any)?.transform) ? (it as any).transform : [1, 0, 0, 1, 0, 0]
+ const tx = Number(transform[4] || 0)
+ const ty = Number(transform[5] || 0)
+ const vw = Math.abs(Number((it as any)?.width || 0) * scale)
+ const vh = Math.max(8, Math.abs(Number((it as any)?.height || 0) * scale))
+ const [vx, vy] = viewport.convertToViewportPoint(tx, ty)
+ const x = clamp(Math.floor(vx), 0, canvas.width - 1)
+ const y = clamp(Math.floor(vy - vh), 0, canvas.height - 1)
+ const w = clamp(Math.ceil(vw || str.length * 6), 6, canvas.width - x)
+ const h = clamp(Math.ceil(vh), 8, canvas.height - y)
+ textBoxes.push({ text: str, x, y, w, h })
+ }
+ } catch {
+ }
+
+ return { canvas, textBoxes, pageText: pageText.trim() }
+}
+
+const buildTextMask = (width: number, height: number, textBoxes: PdfTextBox[]) => {
+ const mask = new Uint8Array(width * height)
+ for (const box of textBoxes) {
+ const x0 = clamp(box.x - 2, 0, width - 1)
+ const y0 = clamp(box.y - 2, 0, height - 1)
+ const x1 = clamp(box.x + box.w + 2, 0, width - 1)
+ const y1 = clamp(box.y + box.h + 2, 0, height - 1)
+ for (let y = y0; y <= y1; y += 1) {
+ const row = y * width
+ for (let x = x0; x <= x1; x += 1) mask[row + x] = 1
+ }
+ }
+ return mask
+}
+
+const detectVisualRegions = (canvas: HTMLCanvasElement, textMask: Uint8Array): RegionBox[] => {
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return []
+ const width = canvas.width
+ const height = canvas.height
+ const imageData = ctx.getImageData(0, 0, width, height).data
+
+ const step = 2
+ const sw = Math.max(1, Math.floor(width / step))
+ const sh = Math.max(1, Math.floor(height / step))
+ const small = new Uint8Array(sw * sh)
+
+ for (let sy = 0; sy < sh; sy += 1) {
+ for (let sx = 0; sx < sw; sx += 1) {
+ const x = sx * step
+ const y = sy * step
+ const idx = (y * width + x) * 4
+ const r = imageData[idx]
+ const g = imageData[idx + 1]
+ const b = imageData[idx + 2]
+ const a = imageData[idx + 3]
+ if (a < 10) continue
+ const bright = (r + g + b) / 3
+ if (bright > 245) continue
+ const pixelIdx = y * width + x
+ if (textMask[pixelIdx]) continue
+ small[sy * sw + sx] = 1
+ }
+ }
+
+ const visited = new Uint8Array(sw * sh)
+ const boxes: RegionBox[] = []
+ const queueX = new Int32Array(sw * sh)
+ const queueY = new Int32Array(sw * sh)
+ const minArea = Math.max(140, Math.floor(sw * sh * 0.0012))
+
+ for (let y = 0; y < sh; y += 1) {
+ for (let x = 0; x < sw; x += 1) {
+ const start = y * sw + x
+ if (!small[start] || visited[start]) continue
+
+ let qh = 0
+ let qt = 0
+ visited[start] = 1
+ queueX[qt] = x
+ queueY[qt] = y
+ qt += 1
+
+ let minX = x
+ let minY = y
+ let maxX = x
+ let maxY = y
+ let area = 0
+
+ while (qh < qt) {
+ const cx = queueX[qh]
+ const cy = queueY[qh]
+ qh += 1
+ area += 1
+ minX = Math.min(minX, cx)
+ minY = Math.min(minY, cy)
+ maxX = Math.max(maxX, cx)
+ maxY = Math.max(maxY, cy)
+
+ for (let ny = cy - 1; ny <= cy + 1; ny += 1) {
+ for (let nx = cx - 1; nx <= cx + 1; nx += 1) {
+ if (nx < 0 || ny < 0 || nx >= sw || ny >= sh) continue
+ const ni = ny * sw + nx
+ if (!small[ni] || visited[ni]) continue
+ visited[ni] = 1
+ queueX[qt] = nx
+ queueY[qt] = ny
+ qt += 1
+ }
+ }
+ }
+
+ if (area < minArea) continue
+ const bw = (maxX - minX + 1) * step
+ const bh = (maxY - minY + 1) * step
+ const ratio = (bw * bh) / Math.max(1, width * height)
+ if (ratio > 0.75) continue
+ if (bw < 80 || bh < 60) continue
+ boxes.push({
+ x: clamp(minX * step - 8, 0, width - 1),
+ y: clamp(minY * step - 8, 0, height - 1),
+ w: clamp(bw + 16, 1, width),
+ h: clamp(bh + 16, 1, height),
+ })
+ }
+ }
+
+ if (boxes.length <= 1) return boxes
+
+ const merged: RegionBox[] = []
+ for (const box of boxes.sort((a, b) => a.y - b.y || a.x - b.x)) {
+ let hit = false
+ for (const m of merged) {
+ const overlapX = Math.max(0, Math.min(box.x + box.w, m.x + m.w) - Math.max(box.x, m.x))
+ const overlapY = Math.max(0, Math.min(box.y + box.h, m.y + m.h) - Math.max(box.y, m.y))
+ const overlap = overlapX * overlapY
+ const minArea2 = Math.min(box.w * box.h, m.w * m.h)
+ const near =
+ Math.abs(box.x + box.w / 2 - (m.x + m.w / 2)) < 80 &&
+ Math.abs(box.y + box.h / 2 - (m.y + m.h / 2)) < 80
+ if (overlap > minArea2 * 0.2 || near) {
+ const nx = Math.min(m.x, box.x)
+ const ny = Math.min(m.y, box.y)
+ const nw = Math.max(m.x + m.w, box.x + box.w) - nx
+ const nh = Math.max(m.y + m.h, box.y + box.h) - ny
+ m.x = nx
+ m.y = ny
+ m.w = nw
+ m.h = nh
+ hit = true
+ break
+ }
+ }
+ if (!hit) merged.push({ ...box })
+ }
+
+ return merged
+}
+
+const cropRegionToDataUrl = (canvas: HTMLCanvasElement, box: RegionBox) => {
+ const c = document.createElement("canvas")
+ c.width = clamp(Math.floor(box.w), 1, canvas.width)
+ c.height = clamp(Math.floor(box.h), 1, canvas.height)
+ const ctx = c.getContext("2d")
+ if (!ctx) return ""
+ ctx.drawImage(canvas, box.x, box.y, box.w, box.h, 0, 0, c.width, c.height)
+ // Use PNG for sharper tables/diagrams; we keep maxAssets small to control payload size.
+ return c.toDataURL("image/png")
+}
+
+const buildRegionTextHint = (box: RegionBox, textBoxes: PdfTextBox[]) => {
+ const centerY = box.y + box.h / 2
+ const candidates = textBoxes
+ .filter((t) => {
+ const horizontalOverlap = Math.max(0, Math.min(box.x + box.w, t.x + t.w) - Math.max(box.x, t.x))
+ const overlapRatio = horizontalOverlap / Math.max(1, Math.min(box.w, t.w))
+ const verticalDistance = Math.abs(t.y + t.h / 2 - centerY)
+ return overlapRatio > 0.2 && verticalDistance < 240
+ })
+ .sort((a, b) => Math.abs(a.y + a.h / 2 - centerY) - Math.abs(b.y + b.h / 2 - centerY))
+ .slice(0, 10)
+ return candidates.map((x) => x.text).join(" ").trim().slice(0, 600)
+}
+
+const expandRegion = (box: RegionBox, width: number, height: number, padX: number, padY: number): RegionBox => {
+ const x = clamp(Math.floor(box.x - padX), 0, width - 1)
+ const y = clamp(Math.floor(box.y - padY), 0, height - 1)
+ const right = clamp(Math.ceil(box.x + box.w + padX), x + 1, width)
+ const bottom = clamp(Math.ceil(box.y + box.h + padY), y + 1, height)
+ return { x, y, w: right - x, h: bottom - y }
+}
+
+const tightenRegionByPixels = (canvas: HTMLCanvasElement, box: RegionBox): RegionBox => {
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return box
+ const sx = clamp(Math.floor(box.x), 0, canvas.width - 1)
+ const sy = clamp(Math.floor(box.y), 0, canvas.height - 1)
+ const sw = clamp(Math.floor(box.w), 1, canvas.width - sx)
+ const sh = clamp(Math.floor(box.h), 1, canvas.height - sy)
+ const data = ctx.getImageData(sx, sy, sw, sh).data
+
+ let minX = sw
+ let minY = sh
+ let maxX = -1
+ let maxY = -1
+
+ for (let y = 0; y < sh; y += 1) {
+ for (let x = 0; x < sw; x += 1) {
+ const idx = (y * sw + x) * 4
+ const r = data[idx]
+ const g = data[idx + 1]
+ const b = data[idx + 2]
+ const a = data[idx + 3]
+ if (a < 20) continue
+ const bright = (r + g + b) / 3
+ if (bright > 244) continue
+ minX = Math.min(minX, x)
+ minY = Math.min(minY, y)
+ maxX = Math.max(maxX, x)
+ maxY = Math.max(maxY, y)
+ }
+ }
+
+ if (maxX < 0 || maxY < 0) return box
+ const pad = 16
+ const nx = clamp(sx + minX - pad, 0, canvas.width - 1)
+ const ny = clamp(sy + minY - pad, 0, canvas.height - 1)
+ const nr = clamp(sx + maxX + pad + 1, nx + 1, canvas.width)
+ const nb = clamp(sy + maxY + pad + 1, ny + 1, canvas.height)
+ return { x: nx, y: ny, w: nr - nx, h: nb - ny }
+}
+
+const buildTextLines = (textBoxes: PdfTextBox[]): PdfTextLine[] => {
+ const sorted = [...textBoxes].sort((a, b) => a.y - b.y || a.x - b.x)
+ const lines: Array<{ boxes: PdfTextBox[]; yCenter: number }> = []
+
+ for (const box of sorted) {
+ const center = box.y + box.h / 2
+ let target = lines.find((line) => Math.abs(line.yCenter - center) <= 10)
+ if (!target) {
+ target = { boxes: [], yCenter: center }
+ lines.push(target)
+ }
+ target.boxes.push(box)
+ target.yCenter = (target.yCenter * (target.boxes.length - 1) + center) / target.boxes.length
+ }
+
+ return lines
+ .map((line) => {
+ const boxes = line.boxes.sort((a, b) => a.x - b.x)
+ const x = Math.min(...boxes.map((b) => b.x))
+ const y = Math.min(...boxes.map((b) => b.y))
+ const right = Math.max(...boxes.map((b) => b.x + b.w))
+ const bottom = Math.max(...boxes.map((b) => b.y + b.h))
+ const text = boxes.map((b) => b.text).join(" ").replace(/\s+/g, " ").trim()
+ return { text, x, y, w: right - x, h: bottom - y }
+ })
+ .filter((line) => line.text.length > 0)
+}
+
+const collectCaptionAnchorRegions = (
+ canvas: HTMLCanvasElement,
+ textBoxes: PdfTextBox[]
+): Array<{ box: RegionBox; hint: string }> => {
+ const width = canvas.width
+ const height = canvas.height
+ const lines = buildTextLines(textBoxes)
+ const anchors = lines.filter((line) => {
+ if (EXCLUDED_VISUAL_HINT_RE.test(line.text)) return false
+ return CAPTION_ANCHOR_RE.test(line.text) || USEFUL_VISUAL_PATTERNS.some((re) => re.test(line.text))
+ })
+
+ const results: Array<{ box: RegionBox; hint: string }> = []
+ for (const line of anchors) {
+ const isTable = /(table|表)/i.test(line.text)
+ const isFigure = /(fig|figure|图)/i.test(line.text)
+ const yCenter = line.y + line.h / 2
+
+ let top = yCenter - height * 0.35
+ let bottom = yCenter + height * 0.35
+ if (isTable) {
+ top = yCenter - height * 0.08
+ bottom = yCenter + height * 0.48
+ } else if (isFigure) {
+ top = yCenter - height * 0.58
+ bottom = yCenter + height * 0.12
+ }
+
+ const base: RegionBox = {
+ x: Math.floor(width * 0.05),
+ y: clamp(Math.floor(top), 0, height - 1),
+ w: Math.floor(width * 0.9),
+ h: clamp(Math.floor(bottom - top), 1, height),
+ }
+ const expanded = expandRegion(base, width, height, 18, 20)
+ const tightened = tightenRegionByPixels(canvas, expanded)
+ const areaRatio = (tightened.w * tightened.h) / Math.max(1, width * height)
+ if (areaRatio < 0.05 || areaRatio > 0.9) continue
+ results.push({ box: tightened, hint: line.text })
+ }
+
+ return results
+}
+
+const unionBoxes = (a: RegionBox, b: RegionBox): RegionBox => {
+ const x = Math.min(a.x, b.x)
+ const y = Math.min(a.y, b.y)
+ const right = Math.max(a.x + a.w, b.x + b.w)
+ const bottom = Math.max(a.y + a.h, b.y + b.h)
+ return { x, y, w: right - x, h: bottom - y }
+}
+
+const detectCaptionKind = (text: string): "figure" | "table" => {
+ const t = String(text || "").toLowerCase()
+ if (t.startsWith("table") || t.includes(" table ") || /表\s*\d+/.test(text)) return "table"
+ return "figure"
+}
+
+const collectCaptionBasedCrops = (args: {
+ canvas: HTMLCanvasElement
+ textBoxes: PdfTextBox[]
+ detectedRegions: RegionBox[]
+}): Array<{ box: RegionBox; hint: string; kind: "figure" | "table" }> => {
+ const { canvas, textBoxes, detectedRegions } = args
+ const width = canvas.width
+ const height = canvas.height
+ const lines = buildTextLines(textBoxes)
+
+ const candidates = lines
+ .filter((line) => {
+ const text = String(line.text || "")
+ if (!CAPTION_LINE_START_RE.test(text)) return false
+ // Avoid catching in-paragraph references like "see Figure 1"
+ const trimmed = text.trim()
+ const looksLikeCaption = /^(\s*(fig(?:ure)?\.?|table|图|表)\s*\d+)\s*[:.]/i.test(trimmed)
+ return looksLikeCaption || trimmed.length <= 80
+ })
+ .slice(0, 40)
+
+ const out: Array<{ box: RegionBox; hint: string; kind: "figure" | "table" }> = []
+
+ for (const line of candidates) {
+ const kind = detectCaptionKind(line.text)
+ const captionBox: RegionBox = expandRegion(
+ { x: line.x, y: line.y, w: line.w, h: line.h },
+ width,
+ height,
+ 14,
+ 10
+ )
+
+ const captionTop = captionBox.y
+ const captionBottom = captionBox.y + captionBox.h
+
+ const window: RegionBox = (() => {
+ if (kind === "table") {
+ // Table captions are often above the table; capture below by default.
+ const top = clamp(Math.floor(captionTop - height * 0.06), 0, height - 1)
+ const bottom = clamp(Math.floor(captionBottom + height * 0.62), top + 1, height)
+ return { x: Math.floor(width * 0.04), y: top, w: Math.floor(width * 0.92), h: bottom - top }
+ }
+ // Figure captions are often below the figure; capture above by default.
+ const top = clamp(Math.floor(captionTop - height * 0.68), 0, height - 1)
+ const bottom = clamp(Math.floor(captionBottom + height * 0.10), top + 1, height)
+ return { x: Math.floor(width * 0.04), y: top, w: Math.floor(width * 0.92), h: bottom - top }
+ })()
+
+ const windowBottom = window.y + window.h
+ const windowTop = window.y
+
+ const inWindow = detectedRegions
+ .map((r) => ({ r, cy: r.y + r.h / 2, cx: r.x + r.w / 2 }))
+ .filter(({ r, cy }) => {
+ const within = cy >= windowTop && cy <= windowBottom
+ if (!within) return false
+ if (kind === "figure") return r.y + r.h <= captionTop + 36
+ return r.y >= captionBottom - 36
+ })
+
+ const pick = (() => {
+ if (inWindow.length === 0) return null
+ const scored = inWindow
+ .map(({ r }) => {
+ const area = r.w * r.h
+ const dist = kind === "figure"
+ ? Math.abs((r.y + r.h) - captionTop)
+ : Math.abs(r.y - captionBottom)
+ // Prefer big + close regions.
+ const score = area - dist * 120
+ return { r, score }
+ })
+ .sort((a, b) => b.score - a.score)
+ return scored[0]?.r || null
+ })()
+
+ let cropBox: RegionBox
+ if (pick) {
+ cropBox = unionBoxes(pick, captionBox)
+ // Include any nearby regions that likely belong to the same figure/table.
+ for (const { r } of inWindow) {
+ const overlapX = Math.max(0, Math.min(cropBox.x + cropBox.w, r.x + r.w) - Math.max(cropBox.x, r.x))
+ const overlapY = Math.max(0, Math.min(cropBox.y + cropBox.h, r.y + r.h) - Math.max(cropBox.y, r.y))
+ const overlap = overlapX * overlapY
+ const minArea = Math.min(cropBox.w * cropBox.h, r.w * r.h)
+ const near = Math.abs((r.y + r.h / 2) - (cropBox.y + cropBox.h / 2)) < 120
+ if (overlap > minArea * 0.08 || near) cropBox = unionBoxes(cropBox, r)
+ }
+ cropBox = expandRegion(cropBox, width, height, 24, 22)
+ cropBox = tightenRegionByPixels(canvas, cropBox)
+ } else {
+ // No clear visual region detected; fall back to a reasonable window around the caption.
+ cropBox = tightenRegionByPixels(canvas, expandRegion(window, width, height, 8, 10))
+ }
+
+ const ratio = (cropBox.w * cropBox.h) / Math.max(1, width * height)
+ if (ratio < 0.04) {
+ // Too small => half page fallback.
+ const half: RegionBox =
+ kind === "table"
+ ? { x: 0, y: Math.floor(height * 0.45), w: width, h: height - Math.floor(height * 0.45) }
+ : { x: 0, y: 0, w: width, h: Math.floor(height * 0.60) }
+ cropBox = tightenRegionByPixels(canvas, expandRegion(half, width, height, 0, 0))
+ }
+ const ratio2 = (cropBox.w * cropBox.h) / Math.max(1, width * height)
+ if (ratio2 < 0.06) {
+ // Still abnormal => full page fallback.
+ cropBox = { x: 0, y: 0, w: width, h: height }
+ }
+
+ out.push({ box: cropBox, hint: String(line.text || "").slice(0, 200), kind })
+ }
+
+ return out
+}
+
+const detectVisualCategory = (hintText: string): VisualCategory => {
+ const text = String(hintText || "")
+ for (const item of CATEGORY_PATTERNS) {
+ if (item.re.some((re) => re.test(text))) return item.category
+ }
+ return "other"
+}
+
+const scoreUsefulVisualHint = (text: string) => {
+ const hint = String(text || "")
+ let score = 0
+ let matched = 0
+ for (const re of USEFUL_VISUAL_PATTERNS) {
+ if (!re.test(hint)) continue
+ matched += 1
+ score += 2
+ }
+ if (/(figure|fig\.?\s*\d+|图\s*\d+)/i.test(hint)) score += 1
+ if (/(table\s*\d+|表\s*\d+)/i.test(hint)) score += 1
+ if (EXCLUDED_VISUAL_HINT_RE.test(hint)) score -= 3
+ return { score, matched }
+}
+
+export async function extractPdfVisualAssets(
+ file: File,
+ options?: { maxPages?: number; maxAssets?: number; targetWidth?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const maxPages = Math.max(1, options?.maxPages ?? 12)
+ const maxAssets = Math.max(1, options?.maxAssets ?? 10)
+ // Higher default resolution to preserve figure/table readability.
+ const targetWidth = Math.max(980, options?.targetWidth ?? 1400)
+
+ const buffer = await file.arrayBuffer()
+ const pdf = await getDocumentProxy(new Uint8Array(buffer))
+ const pageCount = Number((pdf as any)?.numPages || 0)
+ if (!pageCount) return []
+
+ type CandidateAsset = {
+ page: number
+ score: number
+ textHint: string
+ dataUrl: string
+ areaRatio: number
+ category: VisualCategory
+ }
+
+ const accepted: CandidateAsset[] = []
+ const fallback: CandidateAsset[] = []
+
+ for (let pageNo = 1; pageNo <= Math.min(pageCount, maxPages); pageNo += 1) {
+ try {
+ const page = await (pdf as any).getPage(pageNo)
+ const rendered = await renderPdfPageCanvas(page, targetWidth)
+ if (!rendered) continue
+
+ const pageText = String(rendered.pageText || "").slice(0, 1400)
+ const textMask = buildTextMask(rendered.canvas.width, rendered.canvas.height, rendered.textBoxes)
+ const detectedRegions = detectVisualRegions(rendered.canvas, textMask)
+ const captionCrops = collectCaptionBasedCrops({
+ canvas: rendered.canvas,
+ textBoxes: rendered.textBoxes,
+ detectedRegions,
+ })
+ const anchorRegions = collectCaptionAnchorRegions(rendered.canvas, rendered.textBoxes)
+ const candidateRegions = [
+ ...captionCrops.map((item) => ({ box: item.box, seedHint: item.hint, source: "caption" as const })),
+ ...anchorRegions.map((item) => ({ box: item.box, seedHint: item.hint, source: "anchor" as const })),
+ ...detectedRegions.map((box) => ({ box, seedHint: "", source: "detected" as const })),
+ ]
+
+ for (const candidate of candidateRegions) {
+ if (accepted.length >= maxAssets * 8) break
+ const expanded =
+ candidate.source === "caption"
+ ? expandRegion(candidate.box, rendered.canvas.width, rendered.canvas.height, 6, 8)
+ : expandRegion(candidate.box, rendered.canvas.width, rendered.canvas.height, 28, 28)
+ const region = tightenRegionByPixels(rendered.canvas, expanded)
+
+ const dataUrl = cropRegionToDataUrl(rendered.canvas, region)
+ if (!dataUrl.startsWith("data:image")) continue
+
+ const areaRatio = (region.w * region.h) / Math.max(1, rendered.canvas.width * rendered.canvas.height)
+ const localHint = buildRegionTextHint(region, rendered.textBoxes)
+ const textHint = `${candidate.seedHint} ${localHint} ${pageText}`.trim().slice(0, 1200)
+ const scored = scoreUsefulVisualHint(`${textHint} ${pageText}`)
+ const category = detectVisualCategory(textHint)
+ const fullRegionBonus = areaRatio > 0.08 && areaRatio < 0.88 ? 1 : 0
+ const anchorBonus = candidate.source === "caption" ? 4 : candidate.source === "anchor" ? 2 : 0
+ const categoryBonus = category !== "other" ? 1 : 0
+ const finalScore = scored.score + fullRegionBonus + anchorBonus + categoryBonus
+ const item: CandidateAsset = { page: pageNo, score: finalScore, textHint, dataUrl, areaRatio, category }
+
+ if ((scored.matched > 0 || candidate.source === "caption") && finalScore > 0) {
+ accepted.push(item)
+ } else if (areaRatio > 0.08 && areaRatio < 0.9) {
+ fallback.push(item)
+ }
+ }
+ } catch (e) {
+ console.error("Failed to extract visual asset from PDF page", pageNo, e)
+ }
+ }
+
+ const dedupeByData = (items: CandidateAsset[]) => {
+ const seen = new Set<string>()
+ const out: CandidateAsset[] = []
+ for (const item of items.sort((a, b) => b.score - a.score || a.page - b.page)) {
+ const key = `${item.page}|${item.dataUrl.slice(0, 120)}`
+ if (seen.has(key)) continue
+ seen.add(key)
+ out.push(item)
+ }
+ return out
+ }
+
+ const pickByPriority = (items: CandidateAsset[]) => {
+ const priority: VisualCategory[] = [
+ "framework",
+ "result_table",
+ "mechanism",
+ "key_visual",
+ "data_structure",
+ ]
+ const sorted = dedupeByData(items)
+ const picked: CandidateAsset[] = []
+ const used = new Set<string>()
+
+ for (const category of priority) {
+ const hit = sorted.find((item) => item.category === category && !used.has(item.dataUrl))
+ if (!hit) continue
+ picked.push(hit)
+ used.add(hit.dataUrl)
+ if (picked.length >= maxAssets) return picked
+ }
+
+ for (const item of sorted) {
+ if (used.has(item.dataUrl)) continue
+ picked.push(item)
+ used.add(item.dataUrl)
+ if (picked.length >= maxAssets) break
+ }
+
+ return picked
+ }
+
+ const selected = pickByPriority(accepted.length > 0 ? accepted : fallback).sort((a, b) => a.page - b.page)
+
+ return selected.map((x, idx) => ({
+ id: `pdf-${file.name}-${x.page}-${idx + 1}`,
+ sourceFileName: file.name,
+ sourceType: "pdf",
+ page: x.page,
+ order: idx + 1,
+ dataUrl: x.dataUrl,
+ textHint: x.textHint,
+ }))
+}
+
+export async function extractWordVisualAssets(
+ file: File,
+ options?: { maxAssets?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const maxAssets = Math.max(1, options?.maxAssets ?? 10)
+ const buffer = await file.arrayBuffer()
+ const zip = await JSZip.loadAsync(buffer)
+ const mediaEntries = Object.values(zip.files).filter(
+ (f) => !f.dir && /^word\/media\//i.test(String(f.name || ""))
+ )
+ const assets: ExtractedVisualAsset[] = []
+
+ const relsXml = zip.file("word/_rels/document.xml.rels")
+ ? await zip.file("word/_rels/document.xml.rels")!.async("string")
+ : ""
+ const docXml = zip.file("word/document.xml")
+ ? await zip.file("word/document.xml")!.async("string")
+ : ""
+
+ const ridToTarget = new Map<string, string>()
+ if (relsXml) {
+ const relRe = /<Relationship\b[^>]*\bId="([^"]+)"[^>]*\bTarget="([^"]+)"[^>]*\/>/g
+ let rm: RegExpExecArray | null
+ while ((rm = relRe.exec(relsXml))) {
+ const id = String(rm[1] || "").trim()
+ const target = String(rm[2] || "").trim()
+ if (!id || !target) continue
+ ridToTarget.set(id, target.replace(/\\/g, "/"))
+ }
+ }
+
+ const paragraphs: Array<{ text: string; embeds: string[]; metrics: Record<string, { w: number; h: number; area: number }> }> = []
+ if (docXml) {
+ const pRe = /<w:p\b[\s\S]*?<\/w:p>/g
+ const embedsRe = /\br:embed="(rId\d+)"/g
+ const tRe = /<w:t\b[^>]*>([\s\S]*?)<\/w:t>/g
+ const extentRe = /<(?:wp:extent|a:ext)\b[^>]*\bcx="(\d+)"[^>]*\bcy="(\d+)"/g
+ const emuToPx = (v: number) => Math.max(0, Math.round(v / 9525))
+ let pm: RegExpExecArray | null
+ while ((pm = pRe.exec(docXml))) {
+ const p = pm[0]
+ const embeds: string[] = []
+ let em: RegExpExecArray | null
+ while ((em = embedsRe.exec(p))) embeds.push(String(em[1] || ""))
+ const parts: string[] = []
+ let tm: RegExpExecArray | null
+ while ((tm = tRe.exec(p))) parts.push(decodeXmlText(tm[1] || ""))
+ const text = parts.join("").replace(/\s+/g, " ").trim()
+ const metricList: Array<{ w: number; h: number; area: number }> = []
+ let xm: RegExpExecArray | null
+ while ((xm = extentRe.exec(p))) {
+ const cx = Number(xm[1] || 0)
+ const cy = Number(xm[2] || 0)
+ if (!Number.isFinite(cx) || !Number.isFinite(cy)) continue
+ const w = emuToPx(cx)
+ const h = emuToPx(cy)
+ metricList.push({ w, h, area: w * h })
+ }
+ const metrics: Record<string, { w: number; h: number; area: number }> = {}
+ for (let i = 0; i < embeds.length; i += 1) {
+ metrics[embeds[i]] = metricList[i] || { w: 0, h: 0, area: 0 }
+ }
+ paragraphs.push({ text, embeds, metrics })
+ }
+ }
+
+ const captionRe = /^(fig(?:ure)?\.?|table|图|表)\s*\d+\s*[:.]/i
+ const mediaHintByName = new Map<string, string>()
+ const mediaMetricByName = new Map<string, { w: number; h: number; area: number }>()
+ for (let i = 0; i < paragraphs.length; i += 1) {
+ const p = paragraphs[i]
+ if (!p.embeds || p.embeds.length === 0) continue
+ for (const rid of p.embeds) {
+ const target = ridToTarget.get(rid) || ""
+ const media = target ? `word/${target.replace(/^\.?\//, "")}` : ""
+ if (!media) continue
+ const prev = paragraphs[i - 1]?.text || ""
+ const next = paragraphs[i + 1]?.text || ""
+ const here = p.text || ""
+ const cap = [prev, next, here].find((t) => captionRe.test(String(t || "").trim()))
+ const hint = [cap || "", prev, here, next].filter(Boolean).join(" ").replace(/\s+/g, " ").trim().slice(0, 800)
+ if (hint) mediaHintByName.set(media.toLowerCase(), hint)
+ const m = p.metrics?.[rid]
+ if (m && m.area > 0) mediaMetricByName.set(media.toLowerCase(), m)
+ }
+ }
+
+ type Candidate = { entry: any; hint: string; metric: { w: number; h: number; area: number }; score: number; category: VisualCategory }
+ const excludedHintRe =
+ /(equation|formula|eq\.?\s*\(?\d+\)?|proof|appendix|related work|supplement|公式|推导|证明|附录|文献综述|参数设置)/i
+ const candidates: Candidate[] = []
+
+ for (const entry of mediaEntries) {
+ const key = String(entry.name || "").toLowerCase()
+ const hint = mediaHintByName.get(key) || ""
+ const metric = mediaMetricByName.get(key) || { w: 0, h: 0, area: 0 }
+ const scored = scoreUsefulVisualHint(hint)
+ const isCaptionLike = captionRe.test(String(hint || "").trim())
+ const isExcluded = excludedHintRe.test(hint) || EXCLUDED_VISUAL_HINT_RE.test(hint)
+ const sizeBonus = metric.area >= 180000 ? 2 : metric.area >= 70000 ? 1 : 0
+ const tinyPenalty = metric.area > 0 && metric.area < 14000 ? 4 : 0
+ const score = scored.score + (isCaptionLike ? 2 : 0) + sizeBonus - tinyPenalty - (isExcluded ? 6 : 0)
+ const category = detectVisualCategory(hint)
+ candidates.push({ entry, hint, metric, score, category })
+ }
+
+ const priority: VisualCategory[] = [
+ "framework",
+ "result_table",
+ "mechanism",
+ "key_visual",
+ "data_structure",
+ "other",
+ ]
+
+ const keep = candidates
+ .filter((c) => c.score > 0 || c.metric.area >= 260000)
+ .sort((a, b) => {
+ const pa = priority.indexOf(a.category)
+ const pb = priority.indexOf(b.category)
+ if (pa !== pb) return pa - pb
+ if (b.score !== a.score) return b.score - a.score
+ return (b.metric.area || 0) - (a.metric.area || 0)
+ })
+ .slice(0, maxAssets)
+
+ for (let i = 0; i < keep.length; i += 1) {
+ const { entry, hint } = keep[i]
+ try {
+ const bytes = await entry.async("uint8array")
+ const mime = getMimeByExt(entry.name)
+ const dataUrl = `data:${mime};base64,${bytesToBase64(bytes)}`
+ assets.push({
+ id: `word-${file.name}-${i + 1}`,
+ sourceFileName: file.name,
+ sourceType: "word",
+ order: i + 1,
+ dataUrl,
+ textHint: hint,
+ })
+ } catch (e) {
+ console.error("Failed to extract visual asset from Word", entry.name, e)
+ }
+ }
+
+ return assets
+}
+
+
diff --git a/src/workspaces/flow/next/lib/use-file-processor.tsx b/src/workspaces/flow/next/lib/use-file-processor.tsx
index 2c9f322..279428d 100644
--- a/src/workspaces/flow/next/lib/use-file-processor.tsx
+++ b/src/workspaces/flow/next/lib/use-file-processor.tsx
@@ -4,9 +4,20 @@ import { useState } from "react"
import { toast } from "sonner"
import {
extractPdfText,
+ extractWordText,
extractTextFileContent,
+ extractPdfVisualAssets,
+ extractWordVisualAssets,
+ extractLatexZipText,
+ extractLatexZipVisualAssets,
+ extractLatexTarGzText,
+ extractLatexTarGzVisualAssets,
+ type ExtractedVisualAsset,
isPdfFile,
+ isWordFile,
isTextFile,
+ isZipFile,
+ isTarGzFile,
MAX_EXTRACTED_CHARS,
} from "@/workspaces/flow/next/lib/pdf-utils"
@@ -14,6 +25,7 @@ export interface FileData {
text: string
charCount: number
isExtracting: boolean
+ visualAssets?: ExtractedVisualAsset[]
}
/**
@@ -30,7 +42,8 @@ export function useFileProcessor() {
// Extract text immediately for new PDF/text files
for (const file of newFiles) {
const needsExtraction =
- (isPdfFile(file) || isTextFile(file)) && !pdfData.has(file)
+ (isPdfFile(file) || isWordFile(file) || isTextFile(file) || isZipFile(file) || isTarGzFile(file)) &&
+ !pdfData.has(file)
if (needsExtraction) {
// Mark as extracting
setPdfData((prev) => {
@@ -46,8 +59,21 @@ export function useFileProcessor() {
// Extract text asynchronously
try {
let text: string
+ let visualAssets: ExtractedVisualAsset[] = []
if (isPdfFile(file)) {
text = await extractPdfText(file)
+ visualAssets = await extractPdfVisualAssets(file)
+ } else if (isWordFile(file)) {
+ text = await extractWordText(file)
+ visualAssets = await extractWordVisualAssets(file)
+ } else if (isZipFile(file)) {
+ // LaTeX bundle (.zip): parse tex + includegraphics to extract original figures.
+ text = await extractLatexZipText(file)
+ visualAssets = await extractLatexZipVisualAssets(file)
+ } else if (isTarGzFile(file)) {
+ // LaTeX bundle (.tar.gz/.tgz)
+ text = await extractLatexTarGzText(file)
+ visualAssets = await extractLatexTarGzVisualAssets(file)
} else {
text = await extractTextFileContent(file)
}
@@ -74,6 +100,7 @@ export function useFileProcessor() {
text,
charCount: text.length,
isExtracting: false,
+ visualAssets,
})
return next
})
@@ -104,6 +131,7 @@ export function useFileProcessor() {
return {
files,
pdfData,
+ visualAssets: Array.from(pdfData.values()).flatMap((x) => x.visualAssets || []),
handleFileChange,
setFiles, // Export for external control (e.g., clearing files)
}
diff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/src/workspaces/ppt/PptWorkspaceShell.tsx
index 6803eb8..502193d 100644
--- a/src/workspaces/ppt/PptWorkspaceShell.tsx
+++ b/src/workspaces/ppt/PptWorkspaceShell.tsx
@@ -39,7 +39,7 @@ export function PptWorkspaceShell() {
>([]);
const [pptResetTick, setPptResetTick] = useState(0);
const [pptReady, setPptReady] = useState(false);
- const [pptStage, setPptStage] = useState<"outline" | "slides">("outline");
+ const [pptStage, setPptStage] = useState<"start" | "outline" | "slides">("start");
const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
const [versionHistory, setVersionHistory] = useState<HistoryItem[]>(() => {
@@ -55,7 +55,8 @@ export function PptWorkspaceShell() {
const [isChatCollapsed, setIsChatCollapsed] = useState(false);
const chatPanelRef = useRef<PanelImperativeHandle | null>(null);
- const pptChatLocked = !pptReady;
+ const showPptChat = pptStage === "outline" || pptStage === "slides";
+ const pptChatLocked = !showPptChat || !pptReady;
useEffect(() => {
if (typeof window === "undefined") return;
@@ -178,7 +179,8 @@ export function PptWorkspaceShell() {
setPptIncomingEdit(null);
setPptDraftSlides([]);
setPptReady(false);
- setPptStage("outline");
+ setPptStage("start");
+ setChatHistory([]);
setAttachments([]);
setVersionHistory([]);
try {
@@ -212,7 +214,7 @@ export function PptWorkspaceShell() {
</div>
</ResizablePanel>
- {!pptChatLocked && (
+ {showPptChat && (
<>
<ResizableHandle withHandle className="bg-border/50 hover:bg-primary/50 transition-colors w-1.5" />
<ResizablePanel
@@ -257,4 +259,3 @@ export function PptWorkspaceShell() {
</ResizablePanelGroup>
);
}
-
diff --git a/src/workspaces/ppt/chat/ChatInput.tsx b/src/workspaces/ppt/chat/ChatInput.tsx
index 7e31d64..74ab3eb 100644
--- a/src/workspaces/ppt/chat/ChatInput.tsx
+++ b/src/workspaces/ppt/chat/ChatInput.tsx
@@ -9,7 +9,7 @@ import { useUiLanguage } from "@/lib/use-ui-language";
type RichInputSegment =
| { type: "text"; text: string }
- | { type: "ppt"; slideId: string; label: string; tag: string };
+ | { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" };
interface ChatInputProps {
input: string;
@@ -28,7 +28,7 @@ interface ChatInputProps {
focusKey?: string | number;
richSegments?: RichInputSegment[];
onRichSegmentsChange?: (segments: RichInputSegment[]) => void;
- insertPptToken?: { key: number; slideId: string; label: string; tag: string } | null;
+ insertPptToken?: { key: number; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" } | null;
onInsertPptTokenHandled?: () => void;
clearKey?: string | number;
uploadMode?: "all" | "imagesOnly" | "filesOnly" | "none";
@@ -153,38 +153,30 @@ export function ChatInput({
const serializeSegments = (segments: RichInputSegment[]) => {
return segments
- .map((s) => (s.type === "text" ? `t:${s.text}` : `p:${s.slideId}:${s.tag}`))
+ .map((s) => (s.type === "text" ? `t:${s.text}` : `p:${s.tokenKind}:${s.slideId}:${s.tag}`))
.join("|");
};
const buildLabelSpan = (segment: Extract<RichInputSegment, { type: "ppt" }>) => {
+ const isOutline = segment.tokenKind === "outline";
const el = document.createElement("span");
el.setAttribute("data-token", "ppt");
el.setAttribute("data-slide-id", segment.slideId);
el.setAttribute("data-label", segment.label);
el.setAttribute("data-tag", segment.tag);
+ el.setAttribute("data-token-kind", segment.tokenKind);
el.setAttribute("contenteditable", "false");
- el.className = "inline-flex items-center gap-1.5 rounded-full border border-red-200 bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200 align-middle";
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
- svg.setAttribute("viewBox", "0 0 24 24");
- svg.setAttribute("fill", "none");
- svg.setAttribute("stroke", "currentColor");
- svg.setAttribute("stroke-width", "2");
- svg.setAttribute("stroke-linecap", "round");
- svg.setAttribute("stroke-linejoin", "round");
- svg.setAttribute("aria-hidden", "true");
- svg.setAttribute("class", "h-3.5 w-3.5 text-red-600 dark:text-red-200");
- const path1 = document.createElementNS("http://www.w3.org/2000/svg", "path");
- // Draw a "P" icon
- path1.setAttribute("d", "M19 7a5 5 0 0 0-5-5H7a1 1 0 0 0-1 1v18a1 1 0 0 0 1 1h1a1 1 0 0 0 1-1v-8h5a5 5 0 0 0 5-5z");
- // Actually a simpler P stroke might be better for 24x24
- // P shape: M8 20V4h6a4 4 0 0 1 0 8H8
- path1.setAttribute("d", "M8 20V4h6a4 4 0 0 1 0 8H8");
-
- svg.appendChild(path1);
+ el.className = isOutline
+ ? "inline-flex items-center gap-1.5 rounded-full border border-blue-200 bg-blue-50 px-2 py-0.5 text-xs font-medium text-blue-700 dark:border-blue-400/30 dark:bg-blue-950/40 dark:text-blue-200 align-middle"
+ : "inline-flex items-center gap-1.5 rounded-full border border-red-200 bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200 align-middle";
+ const icon = document.createElement("span");
+ icon.className = isOutline
+ ? "inline-flex h-4 w-4 items-center justify-center rounded-full bg-blue-600 text-[10px] font-semibold text-white"
+ : "inline-flex h-4 w-4 items-center justify-center rounded-full bg-red-600 text-[10px] font-semibold text-white";
+ icon.textContent = isOutline ? "T" : "P";
const text = document.createElement("span");
text.textContent = segment.label;
- el.appendChild(svg);
+ el.appendChild(icon);
el.appendChild(text);
return el;
};
@@ -236,7 +228,12 @@ export function ChatInput({
const slideId = el.getAttribute("data-slide-id") || "";
const label = el.getAttribute("data-label") || el.textContent || "";
const tag = el.getAttribute("data-tag") || "";
- if (slideId && tag) out.push({ type: "ppt", slideId, label, tag });
+ const tokenKindAttr = el.getAttribute("data-token-kind");
+ const tokenKind: "outline" | "slide_image" =
+ tokenKindAttr === "outline" || tokenKindAttr === "slide_image"
+ ? tokenKindAttr
+ : "slide_image";
+ if (slideId && tag) out.push({ type: "ppt", slideId, label, tag, tokenKind });
continue;
}
pushText(el.textContent || "");
@@ -265,7 +262,7 @@ export function ChatInput({
setRichContentFromSegments(segments);
}, [isRich, richSegments, richHasFocus]);
- const insertPptTokenAtCursor = (slideId: string, label: string, tag: string) => {
+ const insertPptTokenAtCursor = (slideId: string, label: string, tag: string, tokenKind: "outline" | "slide_image") => {
const root = richRef.current;
if (!root) return;
root.focus();
@@ -279,7 +276,7 @@ export function ChatInput({
range.selectNodeContents(root);
range.collapse(false);
}
- const span = buildLabelSpan({ type: "ppt", slideId, label, tag });
+ const span = buildLabelSpan({ type: "ppt", slideId, label, tag, tokenKind });
const space = document.createTextNode(" ");
range.insertNode(space);
range.insertNode(span);
@@ -296,7 +293,7 @@ export function ChatInput({
useEffect(() => {
if (!isRich) return;
if (!insertPptToken) return;
- insertPptTokenAtCursor(insertPptToken.slideId, insertPptToken.label, insertPptToken.tag);
+ insertPptTokenAtCursor(insertPptToken.slideId, insertPptToken.label, insertPptToken.tag, insertPptToken.tokenKind);
onInsertPptTokenHandled?.();
}, [isRich, insertPptToken?.key]);
diff --git a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
index ceb71ce..3fc00c9 100644
--- a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
@@ -1,4 +1,4 @@
-import React, { useRef, useEffect, useState, useCallback } from 'react';
+import React, { useRef, useEffect, useState, useCallback } from 'react';
import {
Check,
ChevronDown,
@@ -15,24 +15,7 @@ import {
ThumbsDown,
ThumbsUp,
X,
- Presentation, // Import P icon if available, otherwise we use SVG
} from "lucide-react";
-
-// Custom P icon component
-const PIcon = ({ className }: { className?: string }) => (
- <svg
- xmlns="http://www.w3.org/2000/svg"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- className={className}
- >
- <path d="M8 20V4h6a4 4 0 0 1 0 8H8" />
- </svg>
-);
import ReactMarkdown from "react-markdown";
import remarkGfm from 'remark-gfm';
import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/workspaces/ppt/chat/components/reasoning";
@@ -78,6 +61,16 @@ interface TextSection {
fileType?: "pdf" | "text";
}
+interface PptEditSlidePatch {
+ id?: string;
+ [key: string]: any;
+}
+
+interface PptToolPayload {
+ type: "ppt_edit" | "ppt_delete" | "ppt_crate";
+ slides: PptEditSlidePatch[];
+}
+
function splitTextIntoFileSections(text: string): TextSection[] {
const sections: TextSection[] = [];
const filePattern = /\[(PDF|File):\s*([^\]]+)\]\n([\s\S]*?)(?=\n\n\[(PDF|File):|$)/g;
@@ -116,18 +109,26 @@ function splitTextIntoFileSections(text: string): TextSection[] {
return sections;
}
-type PptSlideTag = { n: number; title?: string };
+type PptSlideTag = { n: number; title?: string; kind?: "outline" | "slide_image" };
function extractPptSlideTags(text: string): { tags: PptSlideTag[]; rest: string } {
const lines = String(text || "").split(/\r?\n/);
const tags: PptSlideTag[] = [];
const restLines: string[] = [];
for (const line of lines) {
- const m = line.match(/^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/);
+ const m = line.match(/^\[\[PPT_SLIDE\|(\d+)\|([^|]*)\|(outline|slide_image)\]\]$/);
if (m) {
const n = Number(m[1]);
const title = String(m[2] || "").trim();
- if (!Number.isNaN(n)) tags.push({ n, title: title || undefined });
+ const kind = m[3] as "outline" | "slide_image";
+ if (!Number.isNaN(n)) tags.push({ n, title: title || undefined, kind });
+ continue;
+ }
+ const legacy = line.match(/^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/);
+ if (legacy) {
+ const n = Number(legacy[1]);
+ const title = String(legacy[2] || "").trim();
+ if (!Number.isNaN(n)) tags.push({ n, title: title || undefined, kind: "slide_image" });
continue;
}
restLines.push(line);
@@ -160,7 +161,7 @@ function extractImageTags(text: string): { images: ImageTag[]; rest: string } {
type InlinePptPart =
| { type: "text"; text: string }
- | { type: "ppt"; n: number; title?: string };
+ | { type: "ppt"; n: number; title?: string; kind?: "outline" | "slide_image" };
function splitInlinePptTags(text: string): InlinePptPart[] {
const raw = String(text || "");
@@ -173,7 +174,19 @@ function splitInlinePptTags(text: string): InlinePptPart[] {
if (before) out.push({ type: "text", text: before });
const n = Number(m[1]);
const title = String(m[2] || "").trim();
- if (!Number.isNaN(n)) out.push({ type: "ppt", n, title: title || undefined });
+ if (!Number.isNaN(n)) {
+ let kind: "outline" | "slide_image" = "slide_image";
+ let normalizedTitle = title;
+ const parts = title.split("|");
+ if (parts.length >= 2) {
+ const maybeKind = parts[parts.length - 1].trim();
+ if (maybeKind === "outline" || maybeKind === "slide_image") {
+ kind = maybeKind;
+ normalizedTitle = parts.slice(0, -1).join("|").trim();
+ }
+ }
+ out.push({ type: "ppt", n, title: normalizedTitle || undefined, kind });
+ }
else out.push({ type: "text", text: m[0] });
lastIndex = m.index + m[0].length;
}
@@ -197,6 +210,7 @@ const getUserOriginalText = (message: UIMessage): string => {
const fullText = getMessageTextContent(message);
const withoutTags = fullText
.split(/\r?\n/)
+ .filter((line) => !/^\[\[PPT_SLIDE\|(\d+)\|([^|]*)\|(outline|slide_image)\]\]$/.test(line))
.filter((line) => !/^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/.test(line))
.filter((line) => !/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/.test(line))
.join("\n")
@@ -205,6 +219,86 @@ const getUserOriginalText = (message: UIMessage): string => {
return withoutTags.replace(filePattern, "").trim();
};
+function extractPptToolPayload(text: string): PptToolPayload | null {
+ const raw = String(text || "").trim();
+ if (!raw) return null;
+ const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)\s*```/i);
+ const candidate = (fenced?.[1] ?? raw).trim();
+ let parsed: any;
+ try {
+ parsed = JSON.parse(candidate);
+ } catch {
+ return null;
+ }
+ if (Array.isArray(parsed)) {
+ return { type: "ppt_edit", slides: parsed.filter((s: any) => s && typeof s === "object") };
+ }
+ if (!parsed || typeof parsed !== "object") return null;
+ const typeRaw = String((parsed as any).type || "").trim().toLowerCase();
+ const type: "ppt_edit" | "ppt_delete" | "ppt_crate" =
+ typeRaw === "ppt_delete"
+ ? "ppt_delete"
+ : typeRaw === "ppt_crate" || typeRaw === "ppt_create"
+ ? "ppt_crate"
+ : "ppt_edit";
+ const slides = Array.isArray((parsed as any).slides)
+ ? (parsed as any).slides.filter((s: any) => s && typeof s === "object")
+ : [];
+ return slides.length > 0 ? { type, slides } : null;
+}
+
+function getSlideNumber(slide: PptEditSlidePatch, index: number): number {
+ const id = String(slide?.id || "");
+ const m = id.match(/slide-(\d+)/i);
+ if (m) {
+ const n = Number(m[1]);
+ if (!Number.isNaN(n)) return n;
+ }
+ return index + 1;
+}
+
+function slidePatchEntries(slide: PptEditSlidePatch): Array<{ key: string; value: string }> {
+ const keys = ["title", "description", "layout", "note", "content"];
+ const rows: Array<{ key: string; value: string }> = [];
+ for (const key of keys) {
+ if (!(key in slide)) continue;
+ const raw = (slide as any)[key];
+ if (Array.isArray(raw)) {
+ const text = raw.map((x) => String(x || "").trim()).filter(Boolean).join(";");
+ rows.push({ key, value: text || "(空)" });
+ continue;
+ }
+ if (raw && typeof raw === "object") {
+ rows.push({ key, value: JSON.stringify(raw) });
+ continue;
+ }
+ rows.push({ key, value: String(raw ?? "").trim() || "(空)" });
+ }
+ for (const [k, v] of Object.entries(slide)) {
+ if (k === "id" || keys.includes(k)) continue;
+ if (v === undefined) continue;
+ rows.push({ key: k, value: typeof v === "string" ? v : JSON.stringify(v) });
+ }
+ return rows;
+}
+
+function slideFieldLabel(key: string, uiLang: "zh" | "en"): string {
+ const dict: Record<string, { zh: string; en: string }> = {
+ title: { zh: "标题", en: "Title" },
+ description: { zh: "画面描述", en: "Description" },
+ layout: { zh: "布局", en: "Layout" },
+ note: { zh: "备注", en: "Note" },
+ content: { zh: "内容", en: "Content" },
+ };
+ const hit = dict[key];
+ if (hit) return uiLang === "zh" ? hit.zh : hit.en;
+ return key;
+}
+
+function pptToolTypeLabel(type: "ppt_edit" | "ppt_delete" | "ppt_crate"): string {
+ return type;
+}
+
export function ChatMessageDisplay({
messages,
setInput,
@@ -222,6 +316,7 @@ export function ChatMessageDisplay({
const editTextareaRef = useRef<HTMLTextAreaElement>(null);
const [editText, setEditText] = useState<string>("");
const [expandedPdfSections, setExpandedPdfSections] = useState<Record<string, boolean>>({});
+ const [expandedSlideCards, setExpandedSlideCards] = useState<Record<string, boolean>>({});
const [isAtBottom, setIsAtBottom] = useState(true);
const scrollRafRef = useRef<number | null>(null);
@@ -346,7 +441,12 @@ export function ChatMessageDisplay({
key={message.id}
className={`flex w-full ${message.role === "user" ? "justify-end" : "justify-start"}`}
>
- <div className={cn("max-w-[95%] min-w-0 flex flex-col", message.role === "user" ? "items-end" : "items-start")}>
+ <div
+ className={cn(
+ "min-w-0 flex flex-col",
+ message.role === "assistant" ? "w-full max-w-[95%] items-start" : "max-w-[95%] items-end"
+ )}
+ >
{/* Role Icon / Header */}
<div className="flex items-center gap-2 mb-1.5 px-1">
{message.role === 'assistant' ? (
@@ -463,11 +563,20 @@ export function ChatMessageDisplay({
className={cn(
"inline-flex items-center rounded-full border px-2 py-0.5 text-[11px] leading-4",
message.role === "user"
- ? "border-red-200 bg-red-50 text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200"
+ ? t.kind === "outline"
+ ? "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-400/30 dark:bg-blue-950/40 dark:text-blue-200"
+ : "border-red-200 bg-red-50 text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200"
: "border-border bg-muted/40 text-foreground"
)}
>
- <PIcon className="h-3.5 w-3.5 text-red-600 dark:text-red-200 mr-1" />
+ <span
+ className={cn(
+ "mr-1 inline-flex h-4 w-4 items-center justify-center rounded-full text-[10px] font-semibold text-white",
+ t.kind === "outline" ? "bg-blue-600" : "bg-red-600"
+ )}
+ >
+ {t.kind === "outline" ? "T" : "P"}
+ </span>
{t.title ? tr(`第 ${t.n} 页:${t.title}`, `Slide ${t.n}: ${t.title}`) : tr(`第 ${t.n} 页`, `Slide ${t.n}`)}
</span>
))}
@@ -516,14 +625,27 @@ export function ChatMessageDisplay({
>
{parts.map((p, j) => {
if (p.type === "text") return <span key={`${idx}-t-${j}`}>{p.text}</span>;
+ const kind = p.kind === "outline" ? "outline" : "slide_image";
const label = p.title ? tr(`第 ${p.n} 页:${p.title}`, `Slide ${p.n}: ${p.title}`) : tr(`第 ${p.n} 页`, `Slide ${p.n}`);
return (
<span
key={`${idx}-ppt-${j}`}
- className="mx-1 inline-flex items-center gap-1.5 rounded-full border border-red-200 bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200 align-middle"
+ className={cn(
+ "mx-1 inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium align-middle",
+ kind === "outline"
+ ? "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-400/30 dark:bg-blue-950/40 dark:text-blue-200"
+ : "border-red-200 bg-red-50 text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200"
+ )}
title={tr(`幻灯片 · ${label}`, `Slide · ${label}`)}
>
- <PIcon className="h-3.5 w-3.5 text-red-600 dark:text-red-200" />
+ <span
+ className={cn(
+ "inline-flex h-4 w-4 items-center justify-center rounded-full text-[10px] font-semibold text-white",
+ kind === "outline" ? "bg-blue-600" : "bg-red-600"
+ )}
+ >
+ {kind === "outline" ? "T" : "P"}
+ </span>
{label}
</span>
);
@@ -531,27 +653,81 @@ export function ChatMessageDisplay({
</div>
);
}
+ const pptToolPayload = message.role === "assistant"
+ ? extractPptToolPayload(section.content)
+ : null;
+ if (pptToolPayload && pptToolPayload.slides.length > 0) {
+ return (
+ <div key={idx} className="w-full min-w-0 space-y-2">
+ <div className="inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-2 py-1 text-[11px] font-medium text-blue-700">
+ {pptToolTypeLabel(pptToolPayload.type)}
+ </div>
+ {pptToolPayload.slides.map((slide, slideIdx) => {
+ const slideNumber = getSlideNumber(slide, slideIdx);
+ const rows = (() => {
+ if (pptToolPayload.type === "ppt_delete") {
+ return [
+ {
+ key: "id",
+ value: String(slide?.id || tr("未提供", "Missing")),
+ },
+ ];
+ }
+ return slidePatchEntries(slide);
+ })();
+ const cardKey = `${message.id}-ppt-edit-${idx}-${slideIdx}`;
+ const expanded = expandedSlideCards[cardKey] ?? true;
+ return (
+ <div
+ key={cardKey}
+ className="w-full min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background/70"
+ >
+ <button
+ type="button"
+ onClick={() => setExpandedSlideCards((prev) => ({ ...prev, [cardKey]: !expanded }))}
+ className="flex w-full items-center justify-between px-3 py-2 text-left hover:bg-muted/40"
+ >
+ <span className="inline-flex items-center gap-2 text-sm font-medium text-foreground">
+ <span className="h-2.5 w-2.5 rounded-full bg-emerald-500" />
+ {tr(`第 ${slideNumber} 张幻灯片`, `Slide ${slideNumber}`)}
+ </span>
+ {expanded ? <ChevronUp className="h-4 w-4 text-muted-foreground" /> : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
+ </button>
+ {expanded && (
+ <div className="space-y-2 border-t border-border/50 px-3 py-2">
+ {rows.map((r, rIdx) => (
+ <div key={`${message.id}-ppt-edit-row-${idx}-${slideIdx}-${rIdx}`} className="rounded-lg border border-border/40 bg-muted/20 px-2.5 py-2">
+ <div className="mb-1 text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
+ {slideFieldLabel(r.key, uiLang)}
+ </div>
+ <div className="whitespace-pre-wrap break-words text-sm text-foreground">
+ {r.value}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ );
+ }
return (
<div key={idx} className={cn(
"prose prose-sm max-w-none break-words",
"dark:prose-invert"
)}>
- <ReactMarkdown
+ <ReactMarkdown
remarkPlugins={[remarkGfm]}
urlTransform={(url) => {
const u = String(url || "");
if (!u) return "";
if (u.startsWith("http://") || u.startsWith("https://")) return u;
if (u.startsWith("data:image")) return u;
- if (u.startsWith("blob:")) return u;
- if (u.startsWith("/files/")) return u;
- if (u.startsWith("#")) return u;
return "";
}}
components={{
- table({ children }: any) {
- return <table className="w-full table-fixed">{children}</table>;
- },
th({ children, ...props }: any) {
return (
<th
@@ -575,28 +751,22 @@ export function ChatMessageDisplay({
pre({ children }: any) {
return <>{children}</>;
},
- code({node, inline, className, children, ...props}: any) {
- const match = /language-(\w+)/.exec(className || '')
- // Check if this is the last message and currently streaming
- // We only show spinner for the last code block of the last message if streaming
- // But technically ReactMarkdown renders progressively.
- // We can check if status is streaming and this is the assistant role.
+ code({ node, inline, className, children, ...props }: any) {
+ const match = /language-(\w+)/.exec(className || "");
const isStreaming = status === "streaming" && isLastAssistantMessage;
const language = match?.[1] || "text";
-
if (!inline) {
const ordinal = codeBlockOrdinal++;
return (
<CodeBlock
key={`codeblock-${message.id}-${idx}-${language}-${ordinal}`}
blockId={`${message.id}:${idx}:${language}:${ordinal}`}
- code={String(children).replace(/\n$/, '')}
+ code={String(children).replace(/\n$/, "")}
language={language as any}
isStreaming={isStreaming}
/>
);
}
-
return (
<code className={className} {...props}>
{children}
diff --git a/src/workspaces/ppt/chat/ChatPanel.tsx b/src/workspaces/ppt/chat/ChatPanel.tsx
index 033f72c..1177e47 100644
--- a/src/workspaces/ppt/chat/ChatPanel.tsx
+++ b/src/workspaces/ppt/chat/ChatPanel.tsx
@@ -63,6 +63,7 @@ interface ChatPanelProps {
}
const STORAGE_KEY_PREFIX = 'chat_history_v2_';
+const PPT_WORKSPACE_STORAGE_KEY = "unified-ai-workspace-ppt-state-v1";
// Convert internal ChatMessage to UIMessage
const toUIMessage = (msg: ChatMessage, index: number): UIMessage => ({
@@ -90,7 +91,7 @@ export function ChatPanel({
collapsed = false,
onToggleCollapse,
collapseLocked = false,
- title = "AI 鍔╂墜",
+ title = "AI 助手",
inputPlaceholder,
history = [],
onRestore,
@@ -116,13 +117,11 @@ export function ChatPanel({
}
}
}
- return initialMessages.length > 0 ? initialMessages : [
- { role: 'assistant', content: t(uiLang, "chat.hello") }
- ];
+ return initialMessages.length > 0 ? initialMessages : [];
});
const [input, setInput] = useState('');
- const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string }>>([
+ const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" }>>([
{ type: "text", text: "" }
]);
const [isLoading, setIsLoading] = useState(false);
@@ -136,14 +135,14 @@ export function ChatPanel({
const [pptInputFocusTick, setPptInputFocusTick] = useState(0);
const prevPptDraftCountRef = useRef(0);
const prevPptDraftIdsRef = useRef<Set<string>>(new Set());
- const [pptInsertToken, setPptInsertToken] = useState<{ key: number; slideId: string; label: string; tag: string } | null>(null);
- const pptInsertQueueRef = useRef<Array<{ slideId: string; title: string; label: string }>>([]);
+ const [pptInsertToken, setPptInsertToken] = useState<{ key: number; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" } | null>(null);
+ const pptInsertQueueRef = useRef<Array<{ slideId: string; title: string; label: string; kind: "outline" | "slide_image" }>>([]);
const pptInsertBusyRef = useRef(false);
const [pptClearTick, setPptClearTick] = useState(0);
const lastUploadedImagesRef = useRef<string[]>([]);
const getPptLabel = (slideId: string, title: string) => {
- const m = String(slideId || "").match(/(\\d+)/);
+ const m = String(slideId || "").match(/(\d+)/);
const n = m ? Number(m[1]) : NaN;
if (!Number.isNaN(n)) {
return title ? `Slide ${n}: ${title}` : `Slide ${n}`;
@@ -151,12 +150,12 @@ export function ChatPanel({
return title || slideId;
};
- const getPptTag = (slideId: string, title: string) => {
- const m = String(slideId || "").match(/(\\d+)/);
+ const getPptTag = (slideId: string, title: string, kind: "outline" | "slide_image") => {
+ const m = String(slideId || "").match(/(\d+)/);
const n = m ? Number(m[1]) : NaN;
if (Number.isNaN(n)) return "";
const safeTitle = String(title || "").split("|").join(",").split("]]").join("");
- return `[[PPT_SLIDE|${n}|${safeTitle}]]`;
+ return `[[PPT_SLIDE|${n}|${safeTitle}|${kind}]]`;
};
const pumpPptInsertQueue = () => {
@@ -164,13 +163,13 @@ export function ChatPanel({
const next = pptInsertQueueRef.current.shift();
if (!next) return;
pptInsertBusyRef.current = true;
- const tag = getPptTag(next.slideId, next.title);
- setPptInsertToken({ key: Date.now() + Math.random(), slideId: next.slideId, label: next.label, tag });
+ const tag = getPptTag(next.slideId, next.title, next.kind);
+ setPptInsertToken({ key: Date.now() + Math.random(), slideId: next.slideId, label: next.label, tag, tokenKind: next.kind });
};
- const enqueuePptToken = (slideId: string, title: string) => {
+ const enqueuePptToken = (slideId: string, title: string, kind: "outline" | "slide_image") => {
const label = getPptLabel(slideId, title);
- pptInsertQueueRef.current.push({ slideId, title, label });
+ pptInsertQueueRef.current.push({ slideId, title, label, kind });
pumpPptInsertQueue();
};
@@ -191,7 +190,7 @@ export function ChatPanel({
const added = pptDraftSlides.filter((s) => !prevIds.has(s.id));
prevPptDraftIdsRef.current = nextIds;
if (added.length === 0) return;
- for (const s of added) enqueuePptToken(s.slideId, s.title);
+ for (const s of added) enqueuePptToken(s.slideId, s.title, s.kind);
}, [workspaceId, pptDraftSlides, setInput]);
const parseMarkdownBomTable = (text: string) => {
@@ -238,7 +237,7 @@ export function ChatPanel({
if (!content) return content;
let next = content.replace(
/```(?:python|py|python3)\s*[\s\S]*?```/g,
- trText("锛堝凡鍦ㄥ悗鍙版帹瀵煎畬鎴愶級", "(Processed in the background)")
+ trText("(已在后台处理完成)", "(Processed in the background)")
);
next = next
.split("\n")
@@ -249,7 +248,7 @@ export function ChatPanel({
const text = String(inner || "").trim();
if (!text) return full;
if (text.includes('"type"') && text.includes('"cad_images"')) {
- return trText("锛堝凡鎻愪氦瑁呬慨鍥剧敓鎴愪换鍔★級", "(CAD drawing generation task submitted)");
+ return trText("(已提交装修图生成任务)", "(CAD drawing generation task submitted)");
}
if (text.includes('"type"') && text.includes('"cad_plan"')) {
try {
@@ -491,15 +490,59 @@ export function ChatPanel({
const referencedPptSlideIds = isPpt
? new Set(
pptInputSegments
- .filter((s): s is { type: "ppt"; slideId: string; label: string; tag: string } => s.type === "ppt")
+ .filter((s): s is { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" } => s.type === "ppt")
.map((s) => s.slideId)
)
: new Set<string>();
- const pptDraftSlidesSnapshotAll = isPpt ? pptDraftSlides.slice(0, 12) : [];
+ const loadAllOutlineSlides = () => {
+ if (!isPpt || typeof window === "undefined") return [] as Array<{ slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>;
+ try {
+ const raw = localStorage.getItem(PPT_WORKSPACE_STORAGE_KEY);
+ const parsed = raw ? JSON.parse(raw) : null;
+ const localSlides = Array.isArray(parsed?.localSlides) ? parsed.localSlides : [];
+ return localSlides
+ .filter((s: any) => s && typeof s.id === "string")
+ .slice(0, 24)
+ .map((s: any) => ({
+ slideId: String(s.id),
+ title: typeof s.title === "string" ? s.title : "",
+ json: JSON.stringify({
+ id: String(s.id),
+ title: typeof s.title === "string" ? s.title : "",
+ content: Array.isArray(s.content) ? s.content : [],
+ description: typeof s.description === "string" ? s.description : "",
+ layout: typeof s.layout === "string" ? s.layout : "",
+ note: typeof s.note === "string" ? s.note : "",
+ }, null, 2),
+ kind: "outline" as const,
+ }));
+ } catch {
+ return [] as Array<{ slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>;
+ }
+ };
+ const pptDraftSlidesSnapshotAll = isPpt ? pptDraftSlides.slice(0, 24) : [];
+ const pptAllOutlineSlides = loadAllOutlineSlides();
+ const mergedAllSlides = isPpt
+ ? (() => {
+ const byId = new Map<string, { slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>();
+ for (const s of pptAllOutlineSlides) byId.set(s.slideId, s);
+ for (const s of pptDraftSlidesSnapshotAll) byId.set(s.slideId, s);
+ return Array.from(byId.values());
+ })()
+ : [];
const pptDraftSlidesSnapshot =
isPpt && referencedPptSlideIds.size > 0
- ? pptDraftSlidesSnapshotAll.filter((s) => referencedPptSlideIds.has(s.slideId))
- : [];
+ ? mergedAllSlides.filter((s) => referencedPptSlideIds.has(s.slideId))
+ : mergedAllSlides;
+ const hasPptTagInInput = /\[\[PPT_SLIDE\|/.test(rawInput);
+ const autoPptTags =
+ isPpt && !hasPptTagInInput && pptDraftSlidesSnapshot.length > 0
+ ? pptDraftSlidesSnapshot
+ .map((s) => getPptTag(s.slideId, s.title, s.kind))
+ .filter(Boolean)
+ .join("\n")
+ : "";
+ const inputWithAutoTags = [autoPptTags, rawInput].filter(Boolean).join("\n");
// Process files for prompt
const fileTexts: string[] = [];
@@ -612,7 +655,7 @@ export function ChatPanel({
: "";
const promptParts = [
- rawInput,
+ inputWithAutoTags,
fileTexts.length > 0 ? fileTexts.join("\n\n") : "",
pptDraftContextText,
contextAttachmentsText,
@@ -627,9 +670,10 @@ export function ChatPanel({
const imageTags = currentUploadedImageItems
.map((it) => `[[IMAGE|${safeTagText(it.name)}|${it.url}]]`)
.join("\n");
+ const displayInput = hasPptTagInInput ? rawInput : normalizedInput;
const displayParts = [
imageTags,
- rawInput,
+ displayInput,
displayFileTexts.length > 0 ? displayFileTexts.join("\n\n") : "",
].filter(Boolean);
const displayContent = displayParts.join("\n\n");
@@ -643,7 +687,7 @@ export function ChatPanel({
setFiles([]);
if (workspaceId === "ppt") onClearPptDraftSlides?.();
- if (workspaceId === "cad" && mode === "text" && /(cad_ready_for_export|涓€閿甛s*(鍑哄浘|鐢熸垚)|one[- ]?click)/i.test(normalizedInput)) {
+ if (workspaceId === "cad" && mode === "text" && /(cad_ready_for_export|一键\s*(出图|生成)|one[- ]?click)/i.test(normalizedInput)) {
const svg2d = cadContext?.svg2d || "";
const planJson = cadContext?.plan ? JSON.stringify(cadContext.plan) : "";
@@ -1163,7 +1207,7 @@ export function ChatPanel({
: "";
if (!agentPrompt) {
- updateLastAssistant(trText(`鏈瘑鍒殑 CAD 瀛愭櫤鑳戒綋锛?{agent}`, `Unrecognized CAD sub-agent: ${agent}`));
+ updateLastAssistant(trText(`未识别的 CAD 子智能体:${agent}`, `Unrecognized CAD sub-agent: ${agent}`));
return;
}
@@ -1487,7 +1531,7 @@ export function ChatPanel({
let i = 0;
for (; i < lines.length; i += 1) {
const line = lines[i];
- if (/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/.test(line) || /^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/.test(line)) {
+ if (/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/.test(line) || /^\[\[PPT_SLIDE\|(\d+)\|([^|]*)\|(outline|slide_image)\]\]$/.test(line) || /^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/.test(line)) {
prefixTags.push(line);
continue;
}
@@ -1612,7 +1656,7 @@ export function ChatPanel({
title="Remove attachment"
aria-label="Remove attachment"
>
- 脳
+ ×
</button>
)}
</div>
@@ -1645,3 +1689,4 @@ export function ChatPanel({
</div>
);
}
+
diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/src/workspaces/ppt/workspace/PptWorkspace.tsx
index 0c2f259..a7a028e 100644
--- a/src/workspaces/ppt/workspace/PptWorkspace.tsx
+++ b/src/workspaces/ppt/workspace/PptWorkspace.tsx
@@ -1,9 +1,9 @@
-import React, { useState, useEffect, useRef } from 'react';
+import React, { useState, useEffect, useRef } from 'react';
import { motion } from "framer-motion";
-import { generateImage } from '@/lib/ai-client';
+import { generateImage, generateChatMessage } from '@/lib/ai-client';
import { pptService, PptPage } from '@/lib/ppt-service';
import { getTemplateGenerationPrompt } from '@/lib/ppt-prompts';
-import { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb, X, ArrowLeft, ArrowRight } from 'lucide-react';
+import { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb, X, ArrowLeft, ArrowRight, Eye, Trash2, Maximize2, Minimize2 } from 'lucide-react';
import {
ContextMenu,
ContextMenuContent,
@@ -11,9 +11,10 @@ import {
ContextMenuTrigger,
} from "@/workspaces/ppt/ui/context-menu";
import { Button } from "@/workspaces/ppt/ui/button";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/workspaces/ppt/ui/dialog";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/workspaces/ppt/ui/dialog";
import { Textarea } from "@/workspaces/ppt/ui/textarea";
import { useUiLanguage } from "@/lib/use-ui-language";
+import { useFileProcessor as useFlowFileProcessor } from "@/workspaces/flow/next/lib/use-file-processor";
interface SlideData {
id: string;
@@ -33,15 +34,34 @@ interface PptWorkspaceProps {
data?: PptData;
onAddToChat?: (json: string, name: string) => void;
onPptReadyChange?: (ready: boolean) => void;
- onPptStageChange?: (stage: "outline" | "slides") => void;
+ onPptStageChange?: (stage: "start" | "outline" | "slides") => void;
incomingEdit?: { id: string; payload: string } | null;
onIncomingEditHandled?: (id: string) => void;
onResetWorkspace?: () => void;
}
type CreationStep = 'idle' | 'input' | 'outline' | 'generating_content' | 'generating_images' | 'done';
-type CreationMode = 'idea' | 'outline' | 'description' | 'beautify';
+type CreationMode = 'idea' | 'outline' | 'beautify';
type ReferenceFile = { id: string; filename: string; content: string; charCount: number };
+type SlideMaterialImage = {
+ id: string;
+ name: string;
+ fileName: string;
+ dataUrl: string;
+ refLabel?: string;
+ caption?: string;
+ sourceFileName?: string;
+ sourcePage?: number;
+};
+type ReferenceVisualAsset = {
+ id: string;
+ label: string;
+ caption: string;
+ sourceFileName: string;
+ sourcePage?: number;
+ dataUrl: string;
+ textHint: string;
+};
type PresetTemplate = { id: string; zhName: string; enName: string; path: string };
type UploadTemplate = { id: string; name: string; dataUrl: string };
@@ -62,7 +82,10 @@ const PRESET_TEMPLATES: PresetTemplate[] = [
{ id: "preset-glass", zhName: "磨砂玻璃", enName: "Frosted Glass", path: "/templates/template_glass.png" },
];
-const MODEL_CONCURRENCY = 30;
+const MODEL_CONCURRENCY = 5;
+const BEAUTIFY_CONCURRENCY = 5;
+const BEAUTIFY_RETRY_MAX_ATTEMPTS = 3;
+const BEAUTIFY_RETRY_BASE_DELAY_MS = 1200;
export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageChange, incomingEdit, onIncomingEditHandled, onResetWorkspace }: PptWorkspaceProps) {
const uiLang = useUiLanguage();
@@ -117,6 +140,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}
});
const [templateGeneratorOpen, setTemplateGeneratorOpen] = useState(false);
+ const [backConfirmOpen, setBackConfirmOpen] = useState(false);
const [templateGeneratorRequirement, setTemplateGeneratorRequirement] = useState("");
const [templateGeneratorIsGenerating, setTemplateGeneratorIsGenerating] = useState(false);
const [hiddenPresetTemplateIds, setHiddenPresetTemplateIds] = useState<string[]>(() => {
@@ -175,27 +199,97 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
return localSlides.length > 0 ? "done" : "idle";
});
useEffect(() => {
- onPptStageChange?.(creationStep === "done" ? "slides" : "outline");
+ if (creationStep === "done") {
+ onPptStageChange?.("slides");
+ return;
+ }
+ if (creationStep === "outline") {
+ onPptStageChange?.("outline");
+ return;
+ }
+ onPptStageChange?.("start");
}, [creationStep, onPptStageChange]);
const [creationMode, setCreationMode] = useState<CreationMode>(() => {
const v = initialPptState?.creationMode;
- return v === "idea" || v === "outline" || v === "description" || v === "beautify" ? v : "idea";
+ return v === "idea" || v === "outline" || v === "beautify" ? v : "idea";
});
const [ideaInput, setIdeaInput] = useState(() => (typeof initialPptState?.ideaInput === "string" ? initialPptState.ideaInput : ""));
const [outlineInput, setOutlineInput] = useState(() => (typeof initialPptState?.outlineInput === "string" ? initialPptState.outlineInput : ""));
- const [descriptionInput, setDescriptionInput] = useState(() => (typeof initialPptState?.descriptionInput === "string" ? initialPptState.descriptionInput : ""));
const [beautifyRequirement, setBeautifyRequirement] = useState(() => (typeof initialPptState?.beautifyRequirement === "string" ? initialPptState.beautifyRequirement : ""));
+ const [beautifyUseTemplate, setBeautifyUseTemplate] = useState(() => Boolean(initialPptState?.beautifyUseTemplate));
const [beautifyFile, setBeautifyFile] = useState<File | null>(null);
- const [referenceFiles, setReferenceFiles] = useState<ReferenceFile[]>([]);
- const [isParsingReferenceFiles, setIsParsingReferenceFiles] = useState(false);
+ const [beautifyFailures, setBeautifyFailures] = useState<Record<string, string>>(() => {
+ const v = initialPptState?.beautifyFailures;
+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};
+ const out: Record<string, string> = {};
+ for (const [k, val] of Object.entries(v)) {
+ if (typeof k === "string" && typeof val === "string" && val.trim()) out[k] = val;
+ }
+ return out;
+ });
+ const {
+ files: referenceUploadFiles,
+ pdfData: referencePdfData,
+ visualAssets: referenceVisualAssetsRaw,
+ handleFileChange: handleReferenceFileChange,
+ setFiles: setReferenceUploadFiles
+ } = useFlowFileProcessor();
const [referencePreviewOpen, setReferencePreviewOpen] = useState(false);
const [referencePreviewFile, setReferencePreviewFile] = useState<ReferenceFile | null>(null);
+ const [slideMaterials, setSlideMaterials] = useState<Record<string, SlideMaterialImage[]>>(() => {
+ const v = initialPptState?.slideMaterials;
+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};
+ const out: Record<string, SlideMaterialImage[]> = {};
+ for (const [k, val] of Object.entries(v)) {
+ if (typeof k !== "string" || !Array.isArray(val)) continue;
+ out[k] = val
+ .filter((x: any) => x && typeof x.id === "string" && typeof x.name === "string" && typeof x.dataUrl === "string")
+ .map((x: any) => ({
+ id: x.id,
+ name: x.name,
+ fileName: typeof x.fileName === "string" ? x.fileName : x.name,
+ dataUrl: x.dataUrl,
+ }));
+ }
+ return out;
+ });
+ const [materialPickerSlideId, setMaterialPickerSlideId] = useState<string | null>(null);
+ const [materialPickerPos, setMaterialPickerPos] = useState<{ left: number; top: number } | null>(null);
+ const [materialPickerActiveIndex, setMaterialPickerActiveIndex] = useState(0);
+ const materialPickerReplaceRangeRef = useRef<Range | null>(null);
+ const materialPickerRef = useRef<HTMLDivElement | null>(null);
const [progress, setProgress] = useState({ current: 0, total: 0, message: "" });
const referenceFileInputRef = useRef<HTMLInputElement | null>(null);
const beautifyFileInputRef = useRef<HTMLInputElement | null>(null);
+ const slideMaterialInputRefs = useRef<Record<string, HTMLInputElement | null>>({});
+ const descriptionTextareaRefs = useRef<Record<string, HTMLTextAreaElement | null>>({});
+ const descriptionEditorRefs = useRef<Record<string, HTMLDivElement | null>>({});
+ const descriptionEditorAppliedRef = useRef<Record<string, string>>({});
+ const descriptionEditorFocusedRef = useRef<string | null>(null);
+ const assetCaptionCacheRef = useRef<Record<string, string>>({});
const [slideshowOpen, setSlideshowOpen] = useState(false);
const [slideshowIndex, setSlideshowIndex] = useState(0);
+ const [slideshowFullscreen, setSlideshowFullscreen] = useState(false);
+ const slideshowRootRef = useRef<HTMLDivElement | null>(null);
+ const [materialPreview, setMaterialPreview] = useState<{ open: boolean; slideTitle: string; item: SlideMaterialImage | null }>({
+ open: false,
+ slideTitle: "",
+ item: null
+ });
const [windowDimensions, setWindowDimensions] = useState({ width: 0, height: 0 });
+ const isParsingReferenceFiles = Array.from(referencePdfData.values()).some((x) => x.isExtracting);
+ const referenceFiles: ReferenceFile[] = referenceUploadFiles
+ .map((file) => {
+ const meta = referencePdfData.get(file);
+ if (!meta || meta.isExtracting || !meta.text) return null;
+ return {
+ id: `ref-${file.name}-${file.lastModified}-${file.size}`,
+ filename: file.name,
+ content: String(meta.text || "").slice(0, 150000),
+ charCount: meta.charCount || 0,
+ } as ReferenceFile;
+ })
+ .filter((x): x is ReferenceFile => !!x);
const templates: TemplateItem[] = [
...PRESET_TEMPLATES
@@ -236,8 +330,10 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
creationMode,
ideaInput,
outlineInput,
- descriptionInput,
+ slideMaterials,
beautifyRequirement,
+ beautifyUseTemplate,
+ beautifyFailures,
updatedAt: Date.now(),
})
);
@@ -254,8 +350,10 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
creationMode,
ideaInput,
outlineInput,
- descriptionInput,
+ slideMaterials,
beautifyRequirement,
+ beautifyUseTemplate,
+ beautifyFailures,
]);
useEffect(() => {
@@ -364,7 +462,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
const addGeneratedTemplate = (dataUrl: string) => {
const id = `generated-${Date.now()}-${Math.random().toString(16).slice(2)}`;
- const name = `${tr("AI模板", "AI Template")}-${Date.now()}`;
+ const name = `${tr("AI 模板", "AI Template")}-${Date.now()}`;
const created: UploadTemplate = { id, name, dataUrl };
setUploadedTemplates((prev) => [...prev, created]);
setSelectedTemplateId(created.id);
@@ -374,7 +472,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
const handleGenerateTemplate = async () => {
const requirement = templateGeneratorRequirement.trim();
if (!requirement) {
- alert(tr("请输入模板需求", "Please enter template requirements."));
+ alert(tr("请输入模板需求。", "Please enter template requirements."));
return;
}
setTemplateGeneratorIsGenerating(true);
@@ -419,103 +517,255 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}, [data]);
const applyIncomingSlideEdits = async (payload: string) => {
- let parsed: any;
- try {
- parsed = JSON.parse(payload);
- } catch {
- return;
- }
+ let parsed: any;
+ try {
+ parsed = JSON.parse(payload);
+ } catch {
+ return;
+ }
- const incomingSlides: any[] | null = Array.isArray(parsed?.slides)
- ? parsed.slides
- : Array.isArray(parsed)
- ? parsed
- : null;
-
- if (!incomingSlides || incomingSlides.length === 0) return;
- const uploadedImages: string[] = Array.isArray(parsed?.uploadedImages) ? parsed.uploadedImages : [];
-
- const mergedSlides: SlideData[] = (() => {
- const existing = localSlides.length > 0 ? [...localSlides] : [];
- 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;
- const next: SlideData = {
- id,
- title: typeof inc?.title === "string" ? inc.title : (byId.get(id)?.title || tr("幻灯片", "Slide")),
- content: Array.isArray(inc?.content) ? inc.content.map((x: any) => String(x)) : (byId.get(id)?.content || []),
- description: typeof inc?.description === "string" ? inc.description : byId.get(id)?.description,
- note: typeof inc?.note === "string" ? inc.note : byId.get(id)?.note,
- layout: typeof inc?.layout === "string" ? inc.layout : byId.get(id)?.layout,
- };
- byId.set(id, next);
- if (!order.includes(id)) order.push(id);
- }
+ const toolTypeRaw = String(parsed?.type || "").trim().toLowerCase();
+ const toolType = toolTypeRaw === "ppt_delete" || toolTypeRaw === "ppt_crate" || toolTypeRaw === "ppt_create"
+ ? toolTypeRaw
+ : "ppt_edit";
+
+ const incomingSlides: any[] = Array.isArray(parsed?.slides)
+ ? parsed.slides
+ : Array.isArray(parsed)
+ ? parsed
+ : [];
+
+ if (incomingSlides.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 makeUniqueSlideId = (candidate: string, used: Set<string>) => {
+ const base = candidate.trim() || `slide-${used.size + 1}`;
+ if (!used.has(base)) return base;
+ let next = 2;
+ while (used.has(`${base}-${next}`)) next += 1;
+ return `${base}-${next}`;
+ };
+
+ const toSlideData = (inc: any, fallbackId: string, source?: SlideData): SlideData => ({
+ id: fallbackId,
+ title: typeof inc?.title === "string" ? inc.title : (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,
+ layout: typeof inc?.layout === "string" ? inc.layout : source?.layout,
+ });
- return order.map((id) => byId.get(id)!).filter(Boolean);
- })();
+ const getCreateAnchor = (inc: any): { beforeId?: string; afterId?: string; position?: number } => {
+ const beforeId = typeof inc?.insertBeforeId === "string"
+ ? inc.insertBeforeId
+ : typeof inc?.beforeId === "string"
+ ? inc.beforeId
+ : typeof inc?.between?.beforeId === "string"
+ ? inc.between.beforeId
+ : undefined;
+ const afterId = typeof inc?.insertAfterId === "string"
+ ? inc.insertAfterId
+ : typeof inc?.afterId === "string"
+ ? inc.afterId
+ : typeof inc?.between?.afterId === "string"
+ ? inc.between.afterId
+ : undefined;
+ const pos = Number(inc?.position);
+ const position = Number.isFinite(pos) ? pos : undefined;
+ return { beforeId, afterId, position };
+ };
+
+ let mergedSlides: SlideData[] = localSlides.slice();
+ let mergedIncomingSlides = incomingSlides.slice();
+
+ if (toolType === "ppt_delete") {
+ const deleteIds = new Set(
+ incomingSlides
+ .map((inc) => String(inc?.id || "").trim())
+ .filter(Boolean)
+ );
+ if (deleteIds.size === 0) return;
+
+ mergedSlides = localSlides.filter((slide) => !deleteIds.has(slide.id));
+ mergedIncomingSlides = [];
setLocalSlides(mergedSlides);
- const allowImageEdits = creationStep === 'done';
+ setSlideMaterials((prev) => {
+ const next = { ...prev };
+ for (const id of deleteIds) delete next[id];
+ return next;
+ });
+ setGeneratedImages((prev) => {
+ const next = { ...prev };
+ for (const id of deleteIds) delete next[id];
+ return next;
+ });
+ setImageVersions((prev) => {
+ const next = { ...prev };
+ for (const id of deleteIds) delete next[id];
+ return next;
+ });
+ setCurrentImageVersionId((prev) => {
+ const next = { ...prev };
+ for (const id of deleteIds) delete next[id];
+ return next;
+ });
+ setCurrentSlideIndex((prev) => {
+ if (mergedSlides.length === 0) return 0;
+ return Math.max(0, Math.min(prev, mergedSlides.length - 1));
+ });
+ return;
+ }
- const editTasks: Array<() => Promise<void>> = [];
- for (const inc of incomingSlides) {
+ if (toolType === "ppt_crate" || toolType === "ppt_create") {
+ const used = new Set(localSlides.map((s) => s.id));
+ const nextSlides = localSlides.slice();
+ const normalizedIncoming: any[] = [];
+
+ for (let i = 0; i < incomingSlides.length; i += 1) {
+ const inc = incomingSlides[i];
+ const requestedId = String(inc?.id || "").trim();
+ const newId = makeUniqueSlideId(requestedId || `slide-${nextSlides.length + 1}`, used);
+ used.add(newId);
+ const slide = toSlideData(inc, newId);
+ const { beforeId, afterId, position } = getCreateAnchor(inc);
+
+ let insertAt = nextSlides.length;
+ if (beforeId) {
+ const idx = nextSlides.findIndex((s) => s.id === beforeId);
+ if (idx >= 0) insertAt = idx;
+ } else if (afterId) {
+ const idx = nextSlides.findIndex((s) => s.id === afterId);
+ if (idx >= 0) insertAt = idx + 1;
+ } else if (position !== undefined) {
+ const maybeZeroBased = position >= 0 && position <= nextSlides.length ? position : position - 1;
+ insertAt = Math.max(0, Math.min(nextSlides.length, Math.floor(maybeZeroBased)));
+ }
+
+ nextSlides.splice(insertAt, 0, slide);
+ normalizedIncoming.push({ ...inc, id: newId });
+ }
+
+ mergedSlides = nextSlides;
+ mergedIncomingSlides = normalizedIncoming;
+ setLocalSlides(mergedSlides);
+ } else {
+ 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;
- const incomingImageUrl = typeof inc?.imageUrl === "string" ? inc.imageUrl : "";
- const instruction = typeof inc?.imageEditInstruction === "string"
- ? inc.imageEditInstruction
- : typeof inc?.instruction === "string"
- ? inc.instruction
- : "";
-
- const slide = mergedSlides.find((s) => s.id === id);
- if (!slide) continue;
-
- if (allowImageEdits && incomingImageUrl.trim()) {
- pushImageVersion(id, incomingImageUrl, 'edited', instruction.trim() ? instruction : undefined);
- continue;
- }
+ const next: SlideData = toSlideData(inc, id, byId.get(id));
+ byId.set(id, next);
+ if (!order.includes(id)) order.push(id);
+ }
- if (!allowImageEdits || !instruction.trim()) continue;
- editTasks.push(async () => {
- const versions = imageVersions[id] || [];
- const currentVersion = currentImageVersionId[id];
- const currentUrl = currentVersion ? versions.find(v => v.id === currentVersion)?.url : generatedImages[id];
- if (!currentUrl) return;
-
- const page: PptPage = {
- id,
- title: slide.title,
- content: slide.content || [],
- description: slide.description
- };
- const editedUrl = await pptService.editPageImage(
- page,
- instruction,
- currentUrl || undefined,
- templateImage || undefined,
- uploadedImages
- );
- if (editedUrl) {
- pushImageVersion(id, editedUrl, 'edited', instruction);
- }
- });
+ return order.map((id) => byId.get(id)!).filter(Boolean);
+ })();
+ mergedIncomingSlides = incomingSlides;
+ setLocalSlides(mergedSlides);
+ }
+
+ const allowImageEdits = creationStep === "done";
+ if (!allowImageEdits) return;
+
+ const editTasks: Array<() => Promise<void>> = [];
+ for (const inc of mergedIncomingSlides) {
+ const id = String(inc?.id || "");
+ if (!id) continue;
+ const incomingImageUrl = typeof inc?.imageUrl === "string" ? inc.imageUrl : "";
+ const kind = inc?.kind === "content" || inc?.kind === "visual" || inc?.kind === "both" ? inc.kind : null;
+ const instruction = typeof inc?.imageEditInstruction === "string"
+ ? inc.imageEditInstruction
+ : typeof inc?.instruction === "string"
+ ? inc.instruction
+ : "";
+
+ const slide = mergedSlides.find((s) => s.id === id);
+ if (!slide) continue;
+
+ if (incomingImageUrl.trim()) {
+ pushImageVersion(id, incomingImageUrl, "edited", instruction.trim() ? instruction : undefined);
+ continue;
}
- if (editTasks.length > 0) {
- setIsApplyingEdits(true);
- try {
- await runInParallel(editTasks, MODEL_CONCURRENCY);
- } catch (e) {
- console.error("Failed to apply image edits", e);
- } finally {
- setIsApplyingEdits(false);
+ const before = existingById.get(id);
+ const changedByPatch =
+ !!before &&
+ (
+ before.title !== slide.title ||
+ before.description !== slide.description ||
+ before.layout !== slide.layout ||
+ before.note !== slide.note ||
+ JSON.stringify(before.content || []) !== JSON.stringify(slide.content || [])
+ );
+ const isNewSlide = !before;
+
+ if (kind === "content" || kind === "both" || (!kind && (changedByPatch || isNewSlide))) {
+ editTasks.push(async () => {
+ const page: PptPage = {
+ id,
+ title: slide.title,
+ content: slide.content || [],
+ description: slide.description,
+ note: slide.note,
+ layout: slide.layout,
+ };
+ const rendered = await pptService.generatePageImage(
+ page,
+ uiLang as "zh" | "en",
+ templateImage || undefined,
+ getSlideMaterialImageRefs(id),
+ kind === "both" && instruction.trim() ? instruction : undefined
+ );
+ if (rendered) {
+ pushImageVersion(id, rendered, "generated", kind === "both" ? instruction : undefined);
}
+ });
+ if (kind === "content" || kind === "both") continue;
+ }
+
+ if (!instruction.trim()) continue;
+ editTasks.push(async () => {
+ const versions = imageVersions[id] || [];
+ const currentVersion = currentImageVersionId[id];
+ const currentUrl = currentVersion ? versions.find((v) => v.id === currentVersion)?.url : generatedImages[id];
+ if (!currentUrl) return;
+
+ const page: PptPage = {
+ id,
+ title: slide.title,
+ content: slide.content || [],
+ description: slide.description
+ };
+ const editedUrl = await pptService.editPageImage(
+ page,
+ instruction,
+ currentUrl || undefined,
+ templateImage || undefined,
+ [...uploadedImages, ...getSlideMaterialImageUrls(id)]
+ );
+ if (editedUrl) {
+ pushImageVersion(id, editedUrl, "edited", instruction);
+ }
+ });
+ }
+
+ if (editTasks.length > 0) {
+ setIsApplyingEdits(true);
+ try {
+ await runInParallel(editTasks, MODEL_CONCURRENCY);
+ } catch (e) {
+ console.error("Failed to apply image edits", e);
+ } finally {
+ setIsApplyingEdits(false);
}
+ }
};
useEffect(() => {
@@ -539,11 +789,103 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
return v?.url || generatedImages[slideId] || "";
};
const currentSlideImage = currentSlide ? getSlideImageUrl(currentSlide.id) : "";
+ const failedBeautifyCount = activeSlides.reduce((n, s) => n + (beautifyFailures[s.id] ? 1 : 0), 0);
+ const currentSlideFailure = currentSlide ? beautifyFailures[currentSlide.id] : "";
+
+ const enterSlideshowFullscreen = async () => {
+ if (typeof document === "undefined") return;
+ const root = slideshowRootRef.current;
+ if (!root) return;
+ try {
+ if (document.fullscreenElement === root) return;
+ if (root.requestFullscreen) {
+ await root.requestFullscreen();
+ return;
+ }
+ const anyRoot = root as any;
+ if (typeof anyRoot.webkitRequestFullscreen === "function") {
+ anyRoot.webkitRequestFullscreen();
+ }
+ } catch {
+ }
+ };
+
+ const exitSlideshowFullscreen = async () => {
+ if (typeof document === "undefined") return;
+ try {
+ if (document.fullscreenElement && document.exitFullscreen) {
+ await document.exitFullscreen();
+ return;
+ }
+ const anyDoc = document as any;
+ if (typeof anyDoc.webkitExitFullscreen === "function") {
+ anyDoc.webkitExitFullscreen();
+ }
+ } catch {
+ }
+ };
+
+ const closeSlideshow = () => {
+ setSlideshowOpen(false);
+ void exitSlideshowFullscreen();
+ };
+
+ const openSlideshow = () => {
+ if (activeSlides.length === 0) return;
+ setSlideshowOpen(true);
+ };
useEffect(() => {
if (!slideshowOpen) return;
setSlideshowIndex(currentSlideIndex);
- }, [slideshowOpen]);
+ const timer = window.setTimeout(() => {
+ void enterSlideshowFullscreen();
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, [slideshowOpen, currentSlideIndex]);
+
+ useEffect(() => {
+ if (typeof document === "undefined") return;
+ const onFullscreenChange = () => {
+ const root = slideshowRootRef.current;
+ const fullEl = document.fullscreenElement || (document as any).webkitFullscreenElement || null;
+ setSlideshowFullscreen(!!root && !!fullEl && (fullEl === root || root.contains(fullEl)));
+ };
+ document.addEventListener("fullscreenchange", onFullscreenChange);
+ document.addEventListener("webkitfullscreenchange", onFullscreenChange as EventListener);
+ onFullscreenChange();
+ return () => {
+ document.removeEventListener("fullscreenchange", onFullscreenChange);
+ document.removeEventListener("webkitfullscreenchange", onFullscreenChange as EventListener);
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!slideshowOpen) return;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (activeSlides.length === 0) return;
+ if (e.key === "ArrowRight" || e.key === "PageDown" || e.key === " ") {
+ e.preventDefault();
+ setSlideshowIndex((v) => (v + 1) % activeSlides.length);
+ return;
+ }
+ if (e.key === "ArrowLeft" || e.key === "PageUp") {
+ e.preventDefault();
+ setSlideshowIndex((v) => (v - 1 + activeSlides.length) % activeSlides.length);
+ return;
+ }
+ if (e.key === "Escape") {
+ e.preventDefault();
+ if (slideshowFullscreen) {
+ void exitSlideshowFullscreen();
+ } else {
+ closeSlideshow();
+ }
+ }
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [slideshowOpen, activeSlides.length, slideshowFullscreen]);
const pushImageVersion = (slideId: string, url: string, type: 'generated' | 'edited', instruction?: string) => {
const versionId = `v-${Date.now()}-${Math.random().toString(16).slice(2)}`;
@@ -558,48 +900,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
setGeneratedImages(prev => ({ ...prev, [slideId]: url }));
};
- const addReferenceFiles = async (files: File[]) => {
- if (!files.length) return;
- setIsParsingReferenceFiles(true);
- try {
- const { extractPdfText, extractTextFileContent, isPdfFile, isTextFile } = await import('@/lib/pdf-utils');
- const nextItems: ReferenceFile[] = [];
-
- for (const file of files) {
- try {
- let content = "";
- if (isPdfFile(file)) {
- content = await extractPdfText(file);
- } else if (isTextFile(file)) {
- content = await extractTextFileContent(file);
- } else {
- continue;
- }
-
- const clipped = String(content || "").slice(0, 150000);
- nextItems.push({
- id: `ref-${Date.now()}-${Math.random().toString(16).slice(2)}`,
- filename: file.name,
- content: clipped,
- charCount: clipped.length
- });
- } catch (e) {
- console.error("Failed to parse reference file", file.name, e);
- }
- }
-
- if (nextItems.length > 0) {
- setReferenceFiles((prev) => [...prev, ...nextItems]);
- }
- } finally {
- setIsParsingReferenceFiles(false);
- }
- };
-
const handleReferenceFileInputChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
e.target.value = "";
- await addReferenceFiles(files);
+ if (files.length === 0) return;
+ await handleReferenceFileChange([...referenceUploadFiles, ...files]);
};
const openReferencePreview = (file: ReferenceFile) => {
@@ -607,6 +912,540 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
setReferencePreviewOpen(true);
};
+ const getMaterialLabel = (index: number) => {
+ return uiLang === "zh" ? `第${index}张` : `Image ${index}`;
+ };
+
+ const parseJsonLoose = (text: string) => {
+ const raw = String(text || "").trim();
+ if (!raw) return null;
+ try {
+ return JSON.parse(raw);
+ } catch {
+ }
+ const jsonBlock = raw.match(/```json\s*([\s\S]*?)\s*```/i);
+ if (jsonBlock?.[1]) {
+ try {
+ return JSON.parse(String(jsonBlock[1]).trim());
+ } catch {
+ }
+ }
+ const firstBracket = raw.indexOf("[");
+ const lastBracket = raw.lastIndexOf("]");
+ if (firstBracket >= 0 && lastBracket > firstBracket) {
+ const candidate = raw.slice(firstBracket, lastBracket + 1);
+ try {
+ return JSON.parse(candidate);
+ } catch {
+ }
+ }
+ return null;
+ };
+
+ const buildReferenceVisualAssetsWithCaptions = async (): Promise<ReferenceVisualAsset[]> => {
+ const raw = (referenceVisualAssetsRaw || []).filter((x: any) => x && typeof x.dataUrl === "string" && x.dataUrl.startsWith("data:image"));
+ if (raw.length === 0) return [];
+
+ const baseItems = raw.slice(0, 24).map((x: any, idx: number) => {
+ const label = `FIG_${idx + 1}`;
+ const sourcePage = typeof x.page === "number" ? x.page : undefined;
+ const textHint = String(x.textHint || "").slice(0, 800);
+ const cached = assetCaptionCacheRef.current[x.id];
+ const fallbackCaption = cached || (sourcePage ? tr(`来自第 ${sourcePage} 页的图表`, `Figure/table from page ${sourcePage}`) : tr("参考素材图片", "Reference visual asset"));
+ return {
+ id: String(x.id || `asset-${idx + 1}`),
+ label,
+ sourceFileName: String(x.sourceFileName || tr("参考文件", "Reference file")),
+ sourcePage,
+ dataUrl: String(x.dataUrl || ""),
+ textHint,
+ caption: fallbackCaption,
+ } as ReferenceVisualAsset;
+ });
+
+ const uncached = baseItems.filter((item) => !assetCaptionCacheRef.current[item.id]);
+ if (uncached.length === 0) return baseItems;
+
+ try {
+ const prompt = [
+ "你是论文素材caption生成器。返回JSON数组,不要任何额外文字。",
+ "任务:为每个素材生成一句简短中文说明(18-36字),偏重实验数据/图表含义,不要编造具体数值。",
+ "格式:[{\"id\":\"...\",\"caption\":\"...\"}]",
+ "素材列表:",
+ ...uncached.map((item, idx) => {
+ const pageText = typeof item.sourcePage === "number" ? `page=${item.sourcePage}` : "page=NA";
+ return `${idx + 1}. id=${item.id}; source=${item.sourceFileName}; ${pageText}; text_hint=${item.textHint || "(none)"}`;
+ }),
+ ].join("\n");
+
+ const resp = await generateChatMessage([{ role: "user", content: prompt }], undefined, { timeoutMs: 90000 });
+ const parsed = parseJsonLoose(resp);
+ const arr = Array.isArray(parsed) ? parsed : [];
+ for (const it of arr) {
+ const id = String(it?.id || "").trim();
+ const caption = String(it?.caption || "").trim();
+ if (!id || !caption) continue;
+ assetCaptionCacheRef.current[id] = caption.slice(0, 80);
+ }
+ } catch (e) {
+ console.error("Failed to generate asset captions", e);
+ }
+
+ return baseItems.map((item) => ({
+ ...item,
+ caption: assetCaptionCacheRef.current[item.id] || item.caption,
+ }));
+ };
+
+ const ensureDescriptionHasMaterialTokens = (description: string, materials: Array<{ name: string; caption?: string }>) => {
+ const source = String(description || "");
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const placementsZh = [
+ "放在左侧主视觉区域,约占画面宽度 40%",
+ "放在右上区域,作为辅助图示",
+ "放在底部横向区域,作为补充对比",
+ ];
+ const placementsEn = [
+ "place it in the left primary visual area, about 40% width",
+ "place it in the upper-right area as a supporting visual",
+ "place it in the bottom horizontal area as supplementary comparison",
+ ];
+
+ let working = source;
+ const lines: string[] = [];
+ for (let i = 0; i < materials.length; i += 1) {
+ const m = materials[i];
+ const token = `{{image:${m.name}}}`;
+ const tokenEscaped = escapeRegExp(token);
+ const placement = uiLang === "zh"
+ ? placementsZh[Math.min(i, placementsZh.length - 1)]
+ : placementsEn[Math.min(i, placementsEn.length - 1)];
+ const captionPart = String(m.caption || "").trim();
+ const sentence = uiLang === "zh"
+ ? `${token}${placement}${captionPart ? `,内容重点为:${captionPart}` : ""}。`
+ : `${token} ${placement}${captionPart ? `, focus: ${captionPart}` : ""}.`;
+
+ const wrongLangPlacementRe = uiLang === "zh"
+ ? new RegExp(`${tokenEscaped}[^\\n]*\\bplace\\b[^\\n]*`, "gi")
+ : new RegExp(`${tokenEscaped}[^\\n]*放在[^\\n]*`, "g");
+ if (wrongLangPlacementRe.test(working)) {
+ working = working.replace(wrongLangPlacementRe, "");
+ }
+
+ const hasToken = working.includes(token);
+ const hasPlacement = uiLang === "zh"
+ ? new RegExp(`${tokenEscaped}[^\\n]*放在`).test(working)
+ : new RegExp(`${tokenEscaped}[^\\n]*\\bplace\\b`, "i").test(working);
+ if (!hasToken || !hasPlacement) lines.push(sentence);
+ }
+
+ working = working
+ .replace(/[ \t]+\n/g, "\n")
+ .replace(/\n{3,}/g, "\n\n")
+ .trim();
+ if (lines.length === 0) return working || source;
+ const trimmed = working.trim();
+ if (!trimmed) return lines.join("\n");
+ return `${trimmed}\n${lines.join("\n")}`;
+ };
+
+ const buildSlideMaterialsFromAutoLabels = (
+ pages: PptPage[],
+ slides: SlideData[],
+ assets: ReferenceVisualAsset[]
+ ) => {
+ const assetMap = new Map<string, ReferenceVisualAsset>();
+ for (const a of assets) assetMap.set(a.label, a);
+
+ const pageLabels: string[][] = slides.map((_, idx) => {
+ const labels = Array.isArray(pages[idx]?.materialLabels)
+ ? pages[idx]!.materialLabels!.map((x) => String(x || "").trim()).filter(Boolean)
+ : [];
+ return labels.slice(0, 3);
+ });
+ const explicitLabelCount = pageLabels.reduce((sum, arr) => sum + arr.length, 0);
+
+ // Fallback: if AI returned no labels at all but assets exist, attach a few assets
+ // to representative slides so users can review and adjust instead of seeing empty materials.
+ if (explicitLabelCount === 0 && assets.length > 0 && slides.length > 0) {
+ const fallbackCount = Math.min(assets.length, Math.max(1, Math.min(6, Math.ceil(slides.length / 2))));
+ const step = Math.max(1, Math.floor(slides.length / fallbackCount));
+ for (let n = 0; n < fallbackCount; n += 1) {
+ const slideIndex = Math.min(slides.length - 1, n * step);
+ const label = assets[n]?.label;
+ if (!label) continue;
+ if (!pageLabels[slideIndex]) pageLabels[slideIndex] = [];
+ if (!pageLabels[slideIndex].includes(label)) pageLabels[slideIndex].push(label);
+ }
+ }
+
+ const nextMaterials: Record<string, SlideMaterialImage[]> = {};
+ const nextSlides = slides.map((slide, idx) => {
+ const labels = (pageLabels[idx] || []).slice(0, 3);
+ const matched = labels
+ .map((lb) => assetMap.get(lb))
+ .filter((x): x is ReferenceVisualAsset => !!x)
+ .slice(0, 3);
+ if (matched.length === 0) return slide;
+
+ const materialItems: SlideMaterialImage[] = matched.map((asset, mIdx) => ({
+ id: `auto-mat-${slide.id}-${asset.label}-${mIdx + 1}`,
+ name: getMaterialLabel(mIdx + 1),
+ fileName: asset.sourceFileName,
+ dataUrl: asset.dataUrl,
+ refLabel: asset.label,
+ caption: asset.caption,
+ sourceFileName: asset.sourceFileName,
+ sourcePage: asset.sourcePage,
+ }));
+ nextMaterials[slide.id] = materialItems;
+
+ const withTokens = ensureDescriptionHasMaterialTokens(
+ String(slide.description || ""),
+ materialItems.map((m) => ({ name: m.name, caption: m.caption }))
+ );
+ return { ...slide, description: withTokens };
+ });
+
+ return { nextSlides, nextMaterials };
+ };
+
+ const addSlideMaterialImages = async (slideId: string, files: File[]) => {
+ const imageFiles = files.filter((f) => f.type.startsWith("image/"));
+ if (imageFiles.length === 0) return;
+ const toDataUrl = (file: File) =>
+ new Promise<string>((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(String(reader.result || ""));
+ reader.onerror = reject;
+ reader.readAsDataURL(file);
+ });
+
+ const currentCount = (slideMaterials[slideId] || []).length;
+ const created: SlideMaterialImage[] = [];
+ for (let i = 0; i < imageFiles.length; i += 1) {
+ const file = imageFiles[i];
+ try {
+ const dataUrl = await toDataUrl(file);
+ if (!dataUrl.startsWith("data:image")) continue;
+ const label = getMaterialLabel(currentCount + i + 1);
+ created.push({
+ id: `mat-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ name: label,
+ fileName: file.name,
+ dataUrl,
+ });
+ } catch (e) {
+ console.error("Failed to read slide material image", file.name, e);
+ }
+ }
+ if (created.length === 0) return;
+ setSlideMaterials((prev) => ({
+ ...prev,
+ [slideId]: [...(prev[slideId] || []), ...created],
+ }));
+ };
+
+ const removeSlideMaterialImage = (slideId: string, id: string) => {
+ const removed = (slideMaterials[slideId] || []).find((x) => x.id === id);
+ setSlideMaterials((prev) => ({
+ ...prev,
+ [slideId]: (prev[slideId] || []).filter((x) => x.id !== id),
+ }));
+ if (!removed) return;
+
+ const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const tokenRe = new RegExp(`\\{\\{image:${escapeRegExp(removed.name)}\\}\\}`, "g");
+ setLocalSlides((prev) =>
+ prev.map((s) => {
+ if (s.id !== slideId) return s;
+ const nextDesc = String(s.description || "")
+ .replace(tokenRe, "")
+ .replace(/[ \t]{2,}/g, " ")
+ .replace(/ *\n */g, "\n");
+ return { ...s, description: nextDesc };
+ })
+ );
+
+ const editor = descriptionEditorRefs.current[slideId];
+ if (editor) {
+ for (const node of Array.from(editor.querySelectorAll("[data-material-token]"))) {
+ const el = node as HTMLElement;
+ if (el.getAttribute("data-material-token") === removed.name) {
+ el.remove();
+ }
+ }
+ }
+ };
+
+ const getSlideMaterialImageUrls = (slideId: string) =>
+ (slideMaterials[slideId] || []).map((x) => x.dataUrl).filter(Boolean);
+
+ const getSlideMaterialImageRefs = (slideId: string) =>
+ (slideMaterials[slideId] || [])
+ .map((x) => ({ url: x.dataUrl, label: x.name }))
+ .filter((x) => !!x.url);
+
+ const getTextAreaCaretPosition = (textarea: HTMLTextAreaElement) => {
+ const div = document.createElement("div");
+ const style = window.getComputedStyle(textarea);
+ const props = [
+ "boxSizing", "width", "height", "overflowX", "overflowY", "borderTopWidth", "borderRightWidth",
+ "borderBottomWidth", "borderLeftWidth", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft",
+ "fontStyle", "fontVariant", "fontWeight", "fontStretch", "fontSize", "fontSizeAdjust", "lineHeight",
+ "fontFamily", "textAlign", "textTransform", "textIndent", "textDecoration", "letterSpacing", "wordSpacing",
+ "tabSize", "MozTabSize",
+ ] as const;
+ div.style.position = "absolute";
+ div.style.visibility = "hidden";
+ div.style.whiteSpace = "pre-wrap";
+ div.style.wordWrap = "break-word";
+ for (const prop of props) {
+ (div.style as any)[prop] = (style as any)[prop];
+ }
+ div.textContent = textarea.value.substring(0, textarea.selectionStart || 0);
+ const span = document.createElement("span");
+ span.textContent = textarea.value.substring(textarea.selectionStart || 0) || ".";
+ div.appendChild(span);
+ document.body.appendChild(div);
+ const rect = textarea.getBoundingClientRect();
+ const caretRect = span.getBoundingClientRect();
+ const left = caretRect.left - rect.left + textarea.scrollLeft;
+ const top = caretRect.top - rect.top + textarea.scrollTop + 2;
+ document.body.removeChild(div);
+ return { left, top };
+ };
+
+ const extractMaterialTokenNames = (text: string) => {
+ const out: string[] = [];
+ const re = /\{\{image:([^}]+)\}\}/g;
+ let m: RegExpExecArray | null;
+ while ((m = re.exec(String(text || "")))) {
+ const name = String(m[1] || "").trim();
+ if (name) out.push(name);
+ }
+ return out;
+ };
+
+ const insertMaterialTokenToSlideDescription = (slideIndex: number, slideId: string, materialName: string) => {
+ const token = `{{image:${materialName}}}`;
+ const editor = descriptionEditorRefs.current[slideId];
+ if (editor) {
+ const sel = window.getSelection();
+ const replaceRange = materialPickerReplaceRangeRef.current;
+ if (replaceRange) {
+ replaceRange.deleteContents();
+ const chip = document.createElement("span");
+ chip.setAttribute("data-material-token", materialName);
+ chip.setAttribute("contenteditable", "false");
+ chip.className = "mx-0.5 inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-1.5 py-0.5 text-xs font-medium text-blue-700 align-middle";
+ chip.textContent = materialName;
+ replaceRange.insertNode(chip);
+ const space = document.createTextNode(" ");
+ replaceRange.collapse(false);
+ replaceRange.insertNode(space);
+ const next = document.createRange();
+ next.setStartAfter(space);
+ next.collapse(true);
+ if (sel) {
+ sel.removeAllRanges();
+ sel.addRange(next);
+ }
+ } else {
+ const chip = document.createElement("span");
+ chip.setAttribute("data-material-token", materialName);
+ chip.setAttribute("contenteditable", "false");
+ chip.className = "mx-0.5 inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-1.5 py-0.5 text-xs font-medium text-blue-700 align-middle";
+ chip.textContent = materialName;
+ editor.appendChild(chip);
+ }
+
+ const parseEditorValue = () => {
+ const parts: string[] = [];
+ for (const node of Array.from(editor.childNodes)) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ parts.push(node.textContent || "");
+ continue;
+ }
+ if (node.nodeType !== Node.ELEMENT_NODE) continue;
+ const el = node as HTMLElement;
+ if (el.tagName === "BR") {
+ parts.push("\n");
+ continue;
+ }
+ const tokenName = el.getAttribute("data-material-token");
+ if (tokenName) {
+ parts.push(`{{image:${tokenName}}}`);
+ continue;
+ }
+ parts.push(el.textContent || "");
+ }
+ return parts.join("");
+ };
+
+ const nextValue = parseEditorValue();
+ descriptionEditorAppliedRef.current[slideId] = nextValue;
+ const newSlides = [...localSlides];
+ newSlides[slideIndex].description = nextValue;
+ setLocalSlides(newSlides);
+ setMaterialPickerSlideId(null);
+ setMaterialPickerPos(null);
+ setMaterialPickerActiveIndex(0);
+ materialPickerReplaceRangeRef.current = null;
+ return;
+ }
+
+ const textarea = descriptionTextareaRefs.current[slideId];
+ const prev = localSlides[slideIndex]?.description || "";
+ if (!textarea) {
+ const newSlides = [...localSlides];
+ newSlides[slideIndex].description = `${prev}${token}`;
+ setLocalSlides(newSlides);
+ setMaterialPickerSlideId(null);
+ setMaterialPickerPos(null);
+ setMaterialPickerActiveIndex(0);
+ return;
+ }
+
+ const cursor = textarea.selectionStart ?? prev.length;
+ const before = prev.slice(0, cursor);
+ const slashAt = Math.max(before.lastIndexOf("/"), before.lastIndexOf("/"));
+ const nextValue =
+ slashAt >= 0 ? `${prev.slice(0, slashAt)}${token}${prev.slice(cursor)}` : `${before}${token}${prev.slice(cursor)}`;
+ const nextCursor = (slashAt >= 0 ? slashAt : cursor) + token.length;
+ const newSlides = [...localSlides];
+ newSlides[slideIndex].description = nextValue;
+ setLocalSlides(newSlides);
+ setMaterialPickerSlideId(null);
+ setMaterialPickerPos(null);
+ setMaterialPickerActiveIndex(0);
+ requestAnimationFrame(() => {
+ const input = descriptionTextareaRefs.current[slideId];
+ if (!input) return;
+ input.focus();
+ input.setSelectionRange(nextCursor, nextCursor);
+ });
+ };
+
+ const openMaterialPickerAtCaret = (slideId: string) => {
+ const editor = descriptionEditorRefs.current[slideId];
+ if (!editor) return;
+ const sel = window.getSelection();
+ if (!sel || sel.rangeCount === 0) return;
+ const r = sel.getRangeAt(0);
+ if (!editor.contains(r.startContainer)) return;
+ if (!r.collapsed) return;
+ if (r.startContainer.nodeType !== Node.TEXT_NODE) return;
+ const textNode = r.startContainer as Text;
+ if (r.startOffset <= 0) return;
+ const prevChar = textNode.data[r.startOffset - 1];
+ if (prevChar !== "/" && prevChar !== "/") return;
+
+ const replaceRange = document.createRange();
+ replaceRange.setStart(textNode, r.startOffset - 1);
+ replaceRange.setEnd(textNode, r.startOffset);
+ materialPickerReplaceRangeRef.current = replaceRange;
+
+ const marker = r.cloneRange();
+ marker.setStart(textNode, r.startOffset);
+ marker.collapse(true);
+ const rect = marker.getBoundingClientRect();
+ const hostRect = editor.getBoundingClientRect();
+ setMaterialPickerPos({
+ left: editor.offsetLeft + (rect.left - hostRect.left),
+ top: editor.offsetTop + (rect.bottom - hostRect.top) + 2,
+ });
+ setMaterialPickerActiveIndex(0);
+ setMaterialPickerSlideId(slideId);
+ };
+
+ useEffect(() => {
+ if (!materialPickerSlideId) return;
+ const onPointerDown = (ev: MouseEvent) => {
+ const target = ev.target as Node | null;
+ if (!target) return;
+ if (materialPickerRef.current?.contains(target)) return;
+ setMaterialPickerSlideId(null);
+ setMaterialPickerPos(null);
+ setMaterialPickerActiveIndex(0);
+ materialPickerReplaceRangeRef.current = null;
+ };
+ document.addEventListener("mousedown", onPointerDown);
+ return () => document.removeEventListener("mousedown", onPointerDown);
+ }, [materialPickerSlideId]);
+
+ useEffect(() => {
+ if (!materialPickerSlideId) return;
+ const len = (slideMaterials[materialPickerSlideId] || []).length;
+ if (len <= 0) return;
+ setMaterialPickerActiveIndex((prev) => {
+ if (prev < 0) return 0;
+ if (prev >= len) return len - 1;
+ return prev;
+ });
+ }, [materialPickerSlideId, slideMaterials]);
+
+ const renderDescriptionEditor = (slideId: string, value: string) => {
+ const editor = descriptionEditorRefs.current[slideId];
+ if (!editor) return;
+ if (descriptionEditorFocusedRef.current === slideId) return;
+ if (descriptionEditorAppliedRef.current[slideId] === value) return;
+ descriptionEditorAppliedRef.current[slideId] = value;
+ editor.innerHTML = "";
+ const text = String(value || "");
+ const re = /\{\{image:([^}]+)\}\}/g;
+ let last = 0;
+ let m: RegExpExecArray | null;
+ const appendText = (s: string) => {
+ const lines = s.split("\n");
+ for (let i = 0; i < lines.length; i += 1) {
+ if (lines[i]) editor.appendChild(document.createTextNode(lines[i]));
+ if (i < lines.length - 1) editor.appendChild(document.createElement("br"));
+ }
+ };
+ while ((m = re.exec(text))) {
+ const before = text.slice(last, m.index);
+ if (before) appendText(before);
+ const name = String(m[1] || "").trim();
+ const chip = document.createElement("span");
+ chip.setAttribute("data-material-token", name);
+ chip.setAttribute("contenteditable", "false");
+ chip.className = "mx-0.5 inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-1.5 py-0.5 text-xs font-medium text-blue-700 align-middle";
+ chip.textContent = name;
+ editor.appendChild(chip);
+ editor.appendChild(document.createTextNode(" "));
+ last = m.index + m[0].length;
+ }
+ const rest = text.slice(last);
+ if (rest) appendText(rest);
+ if (!editor.lastChild) editor.appendChild(document.createTextNode(""));
+ };
+
+ const parseDescriptionEditor = (slideId: string) => {
+ const editor = descriptionEditorRefs.current[slideId];
+ if (!editor) return "";
+ const out: string[] = [];
+ for (const node of Array.from(editor.childNodes)) {
+ if (node.nodeType === Node.TEXT_NODE) {
+ out.push(node.textContent || "");
+ continue;
+ }
+ if (node.nodeType !== Node.ELEMENT_NODE) continue;
+ const el = node as HTMLElement;
+ if (el.tagName === "BR") {
+ out.push("\n");
+ continue;
+ }
+ const name = el.getAttribute("data-material-token");
+ if (name) {
+ out.push(`{{image:${name}}}`);
+ continue;
+ }
+ out.push(el.textContent || "");
+ }
+ return out.join("");
+ };
+
const resetGenerationState = () => {
console.log("Resetting generation state...");
setGeneratedImages({});
@@ -621,84 +1460,85 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
};
const parseSlides = (raw: string): SlideData[] | null => {
- const trimmed = raw.trim();
- if (!trimmed) return null;
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
- const jsonArrayText = extractJsonArray(trimmed);
- if (jsonArrayText) {
- try {
- const parsed = JSON.parse(jsonArrayText);
- if (Array.isArray(parsed)) {
- return parsed.map((it: any, i: number) => ({
- id: String(it.id || `slide-${i}`),
- title: String(it.title || tr(`第 ${i + 1} 页`, `Slide ${i + 1}`)),
- content: Array.isArray(it.content) ? it.content.map((x: any) => String(x)) : [],
- description: typeof it.description === "string" ? it.description : undefined,
- note: typeof it.note === "string" ? it.note : undefined,
- layout: typeof it.layout === "string" ? it.layout : undefined
- }));
- }
- } catch {
- }
+ const jsonArrayText = extractJsonArray(trimmed);
+ if (jsonArrayText) {
+ try {
+ const parsed = JSON.parse(jsonArrayText);
+ if (Array.isArray(parsed)) {
+ return parsed.map((it: any, i: number) => ({
+ id: String(it.id || `slide-${i + 1}`),
+ title: String(it.title || tr(`第 ${i + 1} 页`, `Slide ${i + 1}`)),
+ content: Array.isArray(it.content) ? it.content.map((x: any) => String(x)) : [],
+ description: typeof it.description === "string" ? it.description : undefined,
+ note: typeof it.note === "string" ? it.note : undefined,
+ layout: typeof it.layout === "string" ? it.layout : undefined,
+ }));
+ }
+ } catch {
}
+ }
- const lines = trimmed.split(/\r?\n/);
- const slides: SlideData[] = [];
- let current: SlideData | null = null;
+ const lines = trimmed.split(/\r?\n/);
+ const slides: SlideData[] = [];
+ let current: SlideData | null = null;
+ const ensureCurrent = () => {
+ if (!current) {
+ current = {
+ id: `slide-${slides.length + 1}`,
+ title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`),
+ content: [],
+ };
+ }
+ return current;
+ };
+ const pushCurrent = () => {
+ if (current) slides.push(current);
+ current = null;
+ };
+
+ for (const line of lines) {
+ const l = line.trim();
+ if (!l) continue;
+
+ const heading = l.match(/^(#{1,3})\s+(.*)$/);
+ if (heading) {
+ pushCurrent();
+ current = {
+ id: `slide-${slides.length + 1}`,
+ title: heading[2].trim() || tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`),
+ content: [],
+ };
+ continue;
+ }
- const pushCurrent = () => {
- if (current) slides.push(current);
- current = null;
- };
+ const bullet = l.match(/^[-*•]\s+(.*)$/);
+ if (bullet) {
+ ensureCurrent().content.push(bullet[1].trim());
+ continue;
+ }
- for (const line of lines) {
- const l = line.trim();
- if (!l) continue;
- const heading = l.match(/^(#{1,3})\s+(.*)$/);
- if (heading) {
- pushCurrent();
- current = {
- id: `slide-${slides.length + 1}`,
- title: heading[2].trim() || tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`),
- content: []
- };
- continue;
- }
- const bullet = l.match(/^[-•]\s+(.*)$/);
- if (bullet) {
- if (!current) {
- current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };
- }
- current.content.push(bullet[1].trim());
- continue;
- }
- const desc = l.match(/^description[::]\s*(.*)$/i);
- if (desc) {
- if (!current) {
- current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };
- }
- current.description = desc[1].trim();
- continue;
- }
- const note = l.match(/^note[::]\s*(.*)$/i);
- if (note) {
- if (!current) {
- current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };
- }
- current.note = note[1].trim();
- continue;
- }
- const layout = l.match(/^layout[::]\s*(.*)$/i);
- if (layout) {
- if (!current) {
- current = { id: `slide-${slides.length + 1}`, title: tr(`第 ${slides.length + 1} 页`, `Slide ${slides.length + 1}`), content: [] };
- }
- current.layout = layout[1].trim();
- continue;
- }
+ const desc = l.match(/^description[::]\s*(.*)$/i);
+ if (desc) {
+ ensureCurrent().description = desc[1].trim();
+ continue;
+ }
+
+ const note = l.match(/^note[::]\s*(.*)$/i);
+ if (note) {
+ ensureCurrent().note = note[1].trim();
+ continue;
+ }
+
+ const layout = l.match(/^layout[::]\s*(.*)$/i);
+ if (layout) {
+ ensureCurrent().layout = layout[1].trim();
}
- pushCurrent();
- return slides.length > 0 ? slides : null;
+ }
+ pushCurrent();
+ return slides.length > 0 ? slides : null;
};
const runInParallel = async (tasks: (() => Promise<void>)[], limit: number) => {
@@ -727,59 +1567,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
return file?.type === "application/pdf" || name.endsWith(".pdf");
};
- const isBeautifyPptxFile = (file: File) => {
- const name = String(file?.name || "").toLowerCase();
- return (
- file?.type === "application/vnd.openxmlformats-officedocument.presentationml.presentation" ||
- name.endsWith(".pptx")
- );
- };
-
- const sanitizeSlideHtml = (html: string) => {
- return String(html || "")
- .replace(/<script[\s\S]*?>[\s\S]*?<\/script>/gi, "")
- .replace(/\son\w+=(?:"[^"]*"|'[^']*')/gi, "");
- };
-
- const renderHtmlToPngDataUrl = async (opts: { html: string; width: number; height: number; scale: number }) => {
- const html = sanitizeSlideHtml(opts.html);
- const width = Math.max(1, Math.floor(opts.width));
- const height = Math.max(1, Math.floor(opts.height));
- const scale = Number.isFinite(opts.scale) && opts.scale > 0 ? opts.scale : 1;
-
- const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(width * scale)}" height="${Math.round(height * scale)}" viewBox="0 0 ${width} ${height}">
- <foreignObject x="0" y="0" width="100%" height="100%">
- <div xmlns="http://www.w3.org/1999/xhtml" style="width:${width}px;height:${height}px;overflow:hidden;background:#ffffff;">
- ${html}
- </div>
- </foreignObject>
-</svg>`;
-
- const blob = new Blob([svg], { type: "image/svg+xml;charset=utf-8" });
- const url = URL.createObjectURL(blob);
- try {
- const img = new Image();
- img.decoding = "async";
- const loaded = new Promise<void>((resolve, reject) => {
- img.onload = () => resolve();
- img.onerror = reject;
- });
- img.src = url;
- await loaded;
-
- const canvas = document.createElement("canvas");
- canvas.width = Math.round(width * scale);
- canvas.height = Math.round(height * scale);
- const ctx = canvas.getContext("2d");
- if (!ctx) return "";
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
- return canvas.toDataURL("image/png");
- } finally {
- URL.revokeObjectURL(url);
- }
- };
-
const extractPdfPagesAsImages = async (file: File) => {
const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/lib/pdf-utils");
const objectUrl = URL.createObjectURL(file);
@@ -809,27 +1596,6 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}
};
- const extractPptxSlidesAsImages = async (file: File) => {
- const buf = await file.arrayBuffer();
- const { pptxToHtml } = await import("@jvmr/pptx-to-html");
- const slidesHtml = await pptxToHtml(buf, { width: 960, height: 540, scaleToFit: true, letterbox: true });
- const out: string[] = [];
- for (let i = 0; i < slidesHtml.length; i += 1) {
- setProgress({
- current: i,
- total: slidesHtml.length,
- message: tr(`正在解析 PPT... (${i}/${slidesHtml.length})`, `Parsing PPT... (${i}/${slidesHtml.length})`),
- });
- const dataUrl = await renderHtmlToPngDataUrl({ html: slidesHtml[i], width: 960, height: 540, scale: 2 });
- if (dataUrl && dataUrl.startsWith("data:image")) out.push(dataUrl);
- }
- setProgress({
- current: slidesHtml.length,
- total: slidesHtml.length,
- message: tr(`正在解析 PPT... (${slidesHtml.length}/${slidesHtml.length})`, `Parsing PPT... (${slidesHtml.length}/${slidesHtml.length})`),
- });
- return out;
- };
const handleBeautifyFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const f = e.target.files?.[0] || null;
@@ -849,23 +1615,69 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
return parts.join("\n");
};
+ const getErrorMessage = (error: unknown) => {
+ if (error instanceof Error && error.message) return error.message;
+ if (typeof error === "string" && error.trim()) return error.trim();
+ return tr("未知错误", "Unknown error");
+ };
+
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+ const isRetryableBeautifyError = (error: unknown) => {
+ const msg = getErrorMessage(error).toLowerCase();
+ return (
+ msg.includes("429") ||
+ msg.includes("524") ||
+ msg.includes("timeout") ||
+ msg.includes("timed out") ||
+ msg.includes("networkerror") ||
+ msg.includes("fetch") ||
+ msg.includes("rate limit")
+ );
+ };
+
+ const editPageImageWithRetry = async (
+ page: PptPage,
+ instruction: string,
+ baseImageUrl: string,
+ beautifyTemplate?: string
+ ) => {
+ let lastError: unknown = null;
+ for (let attempt = 1; attempt <= BEAUTIFY_RETRY_MAX_ATTEMPTS; attempt += 1) {
+ try {
+ const edited = await pptService.editPageImage(page, instruction, baseImageUrl, beautifyTemplate);
+ if (edited) return edited;
+ lastError = new Error(tr("模型返回空结果", "Empty model result"));
+ } catch (e) {
+ lastError = e;
+ if (!isRetryableBeautifyError(e) || attempt >= BEAUTIFY_RETRY_MAX_ATTEMPTS) break;
+ }
+
+ if (attempt < BEAUTIFY_RETRY_MAX_ATTEMPTS) {
+ const jitter = Math.floor(Math.random() * 350);
+ const delay = BEAUTIFY_RETRY_BASE_DELAY_MS * Math.pow(2, attempt - 1) + jitter;
+ await sleep(delay);
+ }
+ }
+ throw lastError instanceof Error ? lastError : new Error(getErrorMessage(lastError));
+ };
+
const handleStartBeautify = async () => {
const file = beautifyFile;
if (!file) return;
resetGenerationState();
+ setBeautifyFailures({});
setCreationStep("generating_content");
setProgress({ current: 0, total: 0, message: tr("正在解析文件...", "Parsing file...") });
try {
const pageImages = isBeautifyPdfFile(file)
? await extractPdfPagesAsImages(file)
- : isBeautifyPptxFile(file)
- ? await extractPptxSlidesAsImages(file)
- : [];
+ : [];
if (pageImages.length === 0) {
- alert(tr("未能解析出页面图片,请确认文件格式(.pptx 或 .pdf)", "Failed to extract pages. Please upload .pptx or .pdf."));
+ alert(tr("无法解析页面图片,请确认文件格式(仅支持 .pdf)。", "Failed to extract pages. Please upload a .pdf file."));
setCreationStep("idle");
setProgress({ current: 0, total: 0, message: "" });
return;
@@ -900,14 +1712,26 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
setProgress({ current: 0, total: slides.length, message: tr("正在美化渲染...", "Beautifying slides...") });
const instruction = buildBeautifyInstruction(beautifyRequirement);
+ const beautifyTemplate = beautifyUseTemplate ? (templateImage || undefined) : undefined;
const counter = { done: 0 };
const tasks = slides.map((s, i) => async () => {
try {
const page: PptPage = { id: s.id, title: s.title, content: s.content || [], description: s.description || "" };
- const edited = await pptService.editPageImage(page, instruction, pageImages[i], templateImage || undefined);
- if (edited) pushImageVersion(s.id, edited, "edited", instruction);
+ const edited = await editPageImageWithRetry(page, instruction, pageImages[i], beautifyTemplate);
+ if (edited) {
+ pushImageVersion(s.id, edited, "edited", instruction);
+ setBeautifyFailures((prev) => {
+ if (!prev[s.id]) return prev;
+ const next = { ...prev };
+ delete next[s.id];
+ return next;
+ });
+ } else {
+ setBeautifyFailures((prev) => ({ ...prev, [s.id]: tr("模型返回空结果", "Empty model result") }));
+ }
} catch (e) {
console.error(`Beautify failed for slide ${i + 1}`, e);
+ setBeautifyFailures((prev) => ({ ...prev, [s.id]: getErrorMessage(e) }));
} finally {
counter.done += 1;
setProgress((prev) => ({
@@ -919,7 +1743,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}
});
- await runInParallel(tasks, MODEL_CONCURRENCY);
+ await runInParallel(tasks, BEAUTIFY_CONCURRENCY);
setCreationStep("done");
onPptReadyChange?.(true);
} catch (e) {
@@ -931,62 +1755,138 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}
};
- const handleLoadOutline = () => {
- const slides = parseSlides(outlineInput);
- if (!slides || slides.length === 0) {
- alert(tr("未识别到大纲,请粘贴 JSON 数组或 Markdown 大纲。", "Outline not recognized. Paste a JSON array or a Markdown outline."));
+ const handleRetryFailedBeautify = async () => {
+ if (creationMode !== "beautify") return;
+ const failedSlideIds = activeSlides
+ .map((s) => s.id)
+ .filter((id) => !!beautifyFailures[id]);
+ if (failedSlideIds.length === 0) return;
+
+ setCreationStep("generating_images");
+ setProgress({
+ current: 0,
+ total: failedSlideIds.length,
+ message: tr(`正在重试失败页... (0/${failedSlideIds.length})`, `Retrying failed slides... (0/${failedSlideIds.length})`),
+ });
+
+ try {
+ const instruction = buildBeautifyInstruction(beautifyRequirement);
+ const beautifyTemplate = beautifyUseTemplate ? (templateImage || undefined) : undefined;
+ const counter = { done: 0 };
+ const tasks = failedSlideIds.map((slideId) => async () => {
+ const slide = activeSlides.find((x) => x.id === slideId);
+ const baseImageUrl = generatedImages[slideId] || getSlideImageUrl(slideId);
+ if (!slide || !baseImageUrl) {
+ setBeautifyFailures((prev) => ({ ...prev, [slideId]: tr("缺少可重试的原始图片", "Missing base image for retry") }));
+ counter.done += 1;
+ setProgress((prev) => ({
+ ...prev,
+ current: counter.done,
+ total: failedSlideIds.length,
+ message: tr(`正在重试失败页... (${counter.done}/${failedSlideIds.length})`, `Retrying failed slides... (${counter.done}/${failedSlideIds.length})`),
+ }));
return;
- }
- resetGenerationState();
- setLocalSlides(slides);
- setCreationStep("outline");
+ }
+ try {
+ const page: PptPage = { id: slide.id, title: slide.title, content: slide.content || [], description: slide.description || "" };
+ const edited = await editPageImageWithRetry(page, instruction, baseImageUrl, beautifyTemplate);
+ if (!edited) {
+ setBeautifyFailures((prev) => ({ ...prev, [slideId]: tr("模型返回空结果", "Empty model result") }));
+ } else {
+ pushImageVersion(slideId, edited, "edited", instruction);
+ setBeautifyFailures((prev) => {
+ if (!prev[slideId]) return prev;
+ const next = { ...prev };
+ delete next[slideId];
+ return next;
+ });
+ }
+ } catch (e) {
+ setBeautifyFailures((prev) => ({ ...prev, [slideId]: getErrorMessage(e) }));
+ } finally {
+ counter.done += 1;
+ setProgress((prev) => ({
+ ...prev,
+ current: counter.done,
+ total: failedSlideIds.length,
+ message: tr(`正在重试失败页... (${counter.done}/${failedSlideIds.length})`, `Retrying failed slides... (${counter.done}/${failedSlideIds.length})`),
+ }));
+ }
+ });
+
+ await runInParallel(tasks, BEAUTIFY_CONCURRENCY);
+ setCreationStep("done");
onPptReadyChange?.(true);
+ } catch (e) {
+ console.error("Retry failed slides error", e);
+ alert(tr("重试失败页时出错,请重试。", "Retrying failed slides failed. Please try again."));
+ setCreationStep("done");
+ } finally {
+ setProgress({ current: 0, total: 0, message: "" });
+ }
};
- const handleLoadDescriptions = async () => {
- const slides = parseSlides(descriptionInput);
+ const handleLoadOutline = async () => {
+ if (!outlineInput.trim()) return;
resetGenerationState();
-
- if (slides && slides.length > 0) {
- setLocalSlides(slides);
- setCreationStep("outline");
- onPptReadyChange?.(true);
- return;
- }
-
- setCreationStep('input');
- setProgress({ current: 0, total: 0, message: tr("正在从描述生成大纲与画面...", "Generating outline and visuals from description...") });
+ setCreationStep("input");
+ setProgress({ current: 0, total: 0, message: tr("正在解析参考素材...", "Preparing reference assets...") });
try {
- const pages = await pptService.generateSlidesFromDescription(descriptionInput);
- const nextSlides: SlideData[] = pages.map((p, i) => ({
- id: `slide-${i + 1}`,
- title: p.title,
- content: p.content,
- description: p.description,
- note: p.note,
- layout: p.layout
- }));
- setLocalSlides(nextSlides);
- setCreationStep("outline");
- onPptReadyChange?.(true);
+ const referenceVisualAssets = await buildReferenceVisualAssetsWithCaptions();
+ setProgress({ current: 0, total: 0, message: tr("正在生成计划...", "Generating plan...") });
+ const pages = await pptService.generatePlanFromOutline(
+ outlineInput,
+ uiLang as "zh" | "en",
+ referenceFiles,
+ referenceVisualAssets.map((x) => ({
+ label: x.label,
+ caption: x.caption,
+ sourceFile: x.sourceFileName,
+ sourcePage: x.sourcePage,
+ }))
+ );
+ const slides: SlideData[] = pages.map((p, i) => ({
+ id: p.id || `slide-${i + 1}`,
+ title: p.title,
+ content: p.content,
+ description: p.description || "",
+ note: p.note || "",
+ layout: p.layout || "",
+ }));
+ const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets);
+ setSlideMaterials(autoMaterial.nextMaterials);
+ setLocalSlides(autoMaterial.nextSlides);
+ setCreationStep("outline");
+ onPptReadyChange?.(true);
} catch (e) {
- console.error("Failed to generate slides from description", e);
- alert(tr("从描述生成失败,请重试或改为粘贴 JSON/Markdown。", "Failed to generate from description. Retry or paste JSON/Markdown." ));
- setCreationStep("idle");
+ console.error("Failed to build plan from outline", e);
+ alert(e instanceof Error ? e.message : tr("大纲转计划失败,请重试。", "Failed to build plan from outline. Please retry."));
+ setCreationStep("idle");
} finally {
- setProgress({ current: 0, total: 0, message: "" });
+ setProgress({ current: 0, total: 0, message: "" });
}
};
-
const handleGenerateOutline = async () => {
if (!ideaInput.trim()) return;
resetGenerationState();
setCreationStep('input'); // Keep input visible but loading
- setProgress({ current: 0, total: 0, message: tr("正在生成大纲...", "Generating outline...") });
+ setProgress({ current: 0, total: 0, message: tr("正在解析参考素材...", "Preparing reference assets...") });
try {
- const pages = await pptService.generateOutline(ideaInput);
+ const referenceVisualAssets = await buildReferenceVisualAssetsWithCaptions();
+ setProgress({ current: 0, total: 0, message: tr("正在生成大纲...", "Generating outline...") });
+ const pages = await pptService.generateOutline(
+ ideaInput,
+ uiLang as "zh" | "en",
+ referenceFiles,
+ referenceVisualAssets.map((x) => ({
+ label: x.label,
+ caption: x.caption,
+ sourceFile: x.sourceFileName,
+ sourcePage: x.sourcePage,
+ }))
+ );
if (!Array.isArray(pages) || pages.length === 0) {
throw new Error("Invalid outline response");
}
@@ -998,7 +1898,9 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
note: p.note,
layout: p.layout
}));
- setLocalSlides(slides);
+ const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets);
+ setSlideMaterials(autoMaterial.nextMaterials);
+ setLocalSlides(autoMaterial.nextSlides);
setCreationStep('outline');
onPptReadyChange?.(true);
} catch (e) {
@@ -1006,7 +1908,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
const name = (e as any)?.name;
const isAbort = name === "AbortError" || name === "APIUserAbortError";
const msg = isAbort
- ? tr("生成大纲超时或被中断(120s)。请检查网络/模型可用性后重试。", "Outline generation timed out or was interrupted (120s). Check network/model availability and retry.")
+ ? tr("生成大纲超时或被中断(120s)。请检查网络和模型可用性后重试。", "Outline generation timed out or was interrupted (120s). Check network/model availability and retry.")
: e instanceof Error
? e.message
: tr("生成大纲失败,请重试", "Failed to generate outline. Please retry.");
@@ -1018,7 +1920,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
};
const handleGenerateFullPpt = async () => {
- setCreationStep('generating_content');
+ setCreationStep('generating_images');
// Convert SlideData back to PptPage for service
const pages: PptPage[] = localSlides.map(s => ({
@@ -1032,62 +1934,17 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}));
try {
- // 1. Generate Descriptions
- setProgress({ current: 0, total: pages.length, message: tr("正在生成页面内容描述...", "Generating slide content descriptions...") });
-
- // Parallel description generation
- const descCounter = { done: 0 };
- const descTasks = pages.map((_, i) => async () => {
- try {
- const result = await pptService.generatePageDescription(pages, i, ideaInput, referenceFiles);
-
- // Update local state immediately
- setLocalSlides(prev => {
- const newSlides = [...prev];
- const existing = newSlides[i];
- const hasManualContent = Array.isArray(existing?.content)
- ? existing.content.some((x) => String(x || "").trim())
- : false;
- const hasManualDescription = typeof existing?.description === "string" && existing.description.trim();
- const hasManualNote = typeof existing?.note === "string" && existing.note.trim();
- const hasManualLayout = typeof existing?.layout === "string" && existing.layout.trim();
- newSlides[i] = {
- ...existing,
- content: hasManualContent ? (existing.content || []) : result.content,
- description: hasManualDescription ? existing.description : result.description,
- note: hasManualNote ? existing.note : result.note,
- layout: hasManualLayout ? existing.layout : result.layout
- };
- return newSlides;
- });
-
- // Update pages array for next step
- pages[i].description = result.description;
- pages[i].content = result.content;
- pages[i].note = result.note;
- pages[i].layout = result.layout;
- } catch (e) {
- console.error(`Failed to generate description for slide ${i}`, e);
- } finally {
- descCounter.done += 1;
- setProgress(prev => ({
- ...prev,
- current: descCounter.done,
- message: tr(`正在生成页面内容描述... (${descCounter.done}/${pages.length})`, `Generating slide content descriptions... (${descCounter.done}/${pages.length})`)
- }));
- }
- });
-
- await runInParallel(descTasks, MODEL_CONCURRENCY);
-
- // 2. Generate Images
- setCreationStep('generating_images');
setProgress({ current: 0, total: pages.length, message: tr("正在生成页面渲染图...", "Rendering slide images...") });
const imageCounter = { done: 0 };
const imageTasks = pages.map((_, i) => async () => {
try {
- const imageUrl = await pptService.generatePageImage(pages[i], pages, templateImage || undefined);
+ const imageUrl = await pptService.generatePageImage(
+ pages[i],
+ uiLang as "zh" | "en",
+ templateImage || undefined,
+ getSlideMaterialImageRefs(pages[i].id || `slide-${i + 1}`)
+ );
if (imageUrl) {
const slideId = localSlides[i]?.id || `slide-${i}`;
pushImageVersion(slideId, imageUrl, 'generated');
@@ -1111,7 +1968,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
} catch (e) {
console.error("Full generation failed", e);
- alert(tr("生成过程中出错", "An error occurred during generation."));
+ alert(tr("生成过程中出错。", "An error occurred during generation."));
setCreationStep('done'); // Allow viewing what's done
onPptReadyChange?.(true);
}
@@ -1133,7 +1990,12 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
const imageCounter = { done: 0 };
const imageTasks = pages.map((_, i) => async () => {
try {
- const imageUrl = await pptService.generatePageImage(pages[i], pages, templateImage || undefined);
+ const imageUrl = await pptService.generatePageImage(
+ pages[i],
+ uiLang as "zh" | "en",
+ templateImage || undefined,
+ getSlideMaterialImageRefs(pages[i].id || `slide-${i + 1}`)
+ );
if (imageUrl) {
pushImageVersion(pages[i].id || `slide-${i}`, imageUrl, 'generated');
}
@@ -1179,7 +2041,12 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
layout: s.layout
}));
const pageIndex = localSlides.findIndex(s => s === currentSlide);
- imageUrl = await pptService.generatePageImage(pages[pageIndex], pages, templateImage || undefined);
+ imageUrl = await pptService.generatePageImage(
+ pages[pageIndex],
+ uiLang as "zh" | "en",
+ templateImage || undefined,
+ getSlideMaterialImageRefs(currentSlide.id || `slide-${pageIndex + 1}`)
+ );
} else {
// Fallback to simple prompt
const prompt = `Design a presentation slide. Title: "${currentSlide.title}". Content: ${(currentSlide.content || []).join('; ')}. Style: Professional, Modern.`;
@@ -1206,7 +2073,15 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
const currentVersion = currentImageVersionId[slideId];
const versions = imageVersions[slideId] || [];
const imageUrl = currentVersion ? versions.find(v => v.id === currentVersion)?.url : generatedImages[slideId];
- onAddToChat(JSON.stringify({ ...slide, imageUrl }, null, 2), `${slideId}.json`);
+ const materialImages = (slideMaterials[slideId] || []).map((x) => ({
+ name: x.name,
+ url: x.dataUrl,
+ caption: x.caption || "",
+ sourceFileName: x.sourceFileName || "",
+ sourcePage: typeof x.sourcePage === "number" ? x.sourcePage : undefined,
+ refLabel: x.refLabel || "",
+ }));
+ onAddToChat(JSON.stringify({ ...slide, imageUrl, materialImages }, null, 2), `${slideId}.json`);
}
};
@@ -1262,14 +2137,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}
};
- const handleBackToStart = () => {
- const confirmed = window.confirm(
- tr(
- "返回开始将清空当前 PPT(建议先导出保存)。是否继续?",
- "Restart will clear the current deck (export first if needed). Continue?"
- )
- );
- if (!confirmed) return;
+ const resetToStart = () => {
if (typeof onResetWorkspace === "function") {
onResetWorkspace();
return;
@@ -1283,53 +2151,86 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
setCreationStep("idle");
setIdeaInput("");
setOutlineInput("");
- setDescriptionInput("");
setBeautifyRequirement("");
+ setBeautifyUseTemplate(false);
setBeautifyFile(null);
- setReferenceFiles([]);
+ setBeautifyFailures({});
+ setReferenceUploadFiles([]);
+ setSlideMaterials({});
+ setMaterialPickerSlideId(null);
setTemplateImage(null);
setSelectedTemplateId(null);
setProgress({ current: 0, total: 0, message: "" });
};
+ const handleBackToStart = () => {
+ setBackConfirmOpen(true);
+ };
+
+ const handleBackToInputFromOutline = () => {
+ setLocalSlides([]);
+ setSlideMaterials({});
+ resetGenerationState();
+ setCreationStep("idle");
+ };
+
+ const createOutlineSlide = (displayIndex: number): SlideData => ({
+ id: `slide-${Date.now()}-${Math.random().toString(16).slice(2)}`,
+ title: tr(`第 ${displayIndex + 1} 页`, `Slide ${displayIndex + 1}`),
+ content: [],
+ description: "",
+ note: "",
+ layout: "",
+ });
+
+ const handleAddOutlineSlide = (afterIndex?: number) => {
+ setLocalSlides((prev) => {
+ const insertAt = typeof afterIndex === "number"
+ ? Math.max(0, Math.min(afterIndex + 1, prev.length))
+ : prev.length;
+ const next = [...prev];
+ next.splice(insertAt, 0, createOutlineSlide(insertAt));
+ return next;
+ });
+ };
+
+ const handleDeleteOutlineSlide = (slideId: string) => {
+ setLocalSlides((prev) => prev.filter((s) => s.id !== slideId));
+ setSlideMaterials((prev) => {
+ const next = { ...prev };
+ delete next[slideId];
+ return next;
+ });
+ };
+
// Render Creation Wizard
if (activeSlides.length === 0 && (creationStep === 'idle' || creationStep === 'input' || creationStep === 'done')) {
const tabs = [
{ id: 'idea', label: tr('想法', 'Idea') },
{ id: 'outline', label: tr('大纲', 'Outline') },
- { id: 'description', label: tr('描述', 'Description') },
{ id: 'beautify', label: tr('PPT美化', 'Beautify') },
];
const modeCopy = (() => {
if (creationMode === "outline") {
return {
- hint: tr("已有大纲?直接粘贴即可快速生成,AI 将自动切分为结构化大纲", "Have an outline? Paste it and AI will structure it into slides."),
+ hint: tr("已有大纲?直接粘贴即可快速生成,AI 将自动结构化。", "Have an outline? Paste it and AI will structure it into slides."),
placeholder: tr(
- "粘贴你的 PPT 大纲…\n\n例如:\n第一部分:AI 的起源\n- 1950 年代的开端\n- 达特茅斯会议\n\n第二部分:发展历程\n- 专家系统\n- 深度学习\n…",
- "Paste your PPT outline…\n\nExample:\nPart 1: Origins of AI\n- Early beginnings in the 1950s\n- Dartmouth workshop\n\nPart 2: Evolution\n- Expert systems\n- Deep learning\n…"
+ "粘贴你的 PPT 大纲,例如:\n第一部分:AI 起源\n- 1950 年代\n- 达特茅斯会议",
+ "Paste your PPT outline, for example:\nPart 1: Origins of AI\n- 1950s\n- Dartmouth workshop"
)
};
}
if (creationMode === "beautify") {
return {
- hint: tr("上传 PPT/PDF,输入美化要求,然后并发渲染每一页", "Upload PPT/PDF, enter requirements, then beautify each page in parallel."),
+ hint: tr("上传 PDF,输入美化要求,然后并发渲染每一页。", "Upload PDF, enter requirements, then beautify each page in parallel."),
placeholder: tr(
- "例如:整体更高级、留白更充足、标题更醒目、配色更统一、增强对比度;保持原文案不变。",
+ "例如:整体更高级、留白更充足、标题层级更明显、配色更统一;保持原文案不变。",
"e.g. More premium look, more whitespace, stronger title hierarchy, unified palette, higher contrast; keep all original text unchanged."
)
};
}
- if (creationMode === "description") {
- return {
- hint: tr("已有完整描述?AI 将自动解析出大纲并切分为每页描述,直接生成图片", "Have a full description? AI will split it into slides and render images."),
- placeholder: tr(
- "粘贴你的完整页面描述…\n\n例如:\n第 1 页\n标题:人工智能的诞生\n内容:1950 年,图灵提出“图灵测试”…\n\n第 2 页\n标题:AI 的发展历程\n内容:1950 年代:符号主义…\n…",
- "Paste your full slide-by-slide description…\n\nExample:\nSlide 1\nTitle: The birth of AI\nContent: In 1950, Alan Turing proposed the Turing Test…\n\nSlide 2\nTitle: The evolution of AI\nContent: 1950s: symbolic approaches…\n…"
- )
- };
- }
return {
- hint: tr("输入你的想法,AI 将为你生成完整的 PPT", "Describe your idea and AI will generate a full deck."),
+ hint: tr("输入你的想法,AI 将为你生成完整 PPT", "Describe your idea and AI will generate a full deck."),
placeholder: tr("例如:生成一份关于 AI 发展史的演讲 PPT", "e.g. Create a presentation about the history of AI")
};
})();
@@ -1360,6 +2261,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<button
type="button"
onClick={() => setTemplateGeneratorOpen(true)}
+ title={tr("AI生成模板", "AI generate template")}
className="cursor-pointer border-2 border-dashed rounded-xl transition-all duration-200 overflow-hidden relative aspect-video flex flex-col items-center justify-center group border-zinc-200 dark:border-zinc-700 hover:border-blue-500 hover:bg-blue-50/30 dark:hover:bg-zinc-800/50"
>
<div className="flex flex-col items-center text-zinc-400 group-hover:text-blue-500 transition-colors">
@@ -1417,6 +2319,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<button
key={tab.id}
onClick={() => setCreationMode(tab.id as any)}
+ title={tab.label}
className={`relative flex-1 sm:flex-none px-6 py-2 text-sm font-medium rounded-md transition-all duration-200 ${
creationMode === tab.id
? "text-zinc-900 dark:text-zinc-100 shadow-sm"
@@ -1439,7 +2342,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
ref={referenceFileInputRef}
type="file"
multiple
- accept=".pdf,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml"
+ accept=".pdf,.docx,.zip,.tex,.tgz,.tar.gz,application/pdf,application/zip,application/x-zip-compressed,application/gzip,application/x-gzip,application/vnd.openxmlformats-officedocument.wordprocessingml.document,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"
className="hidden"
onChange={handleReferenceFileInputChange}
/>
@@ -1462,14 +2365,14 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<input
ref={beautifyFileInputRef}
type="file"
- accept=".pptx,.pdf,application/pdf,application/vnd.openxmlformats-officedocument.presentationml.presentation"
+ accept=".pdf,application/pdf"
className="hidden"
onChange={handleBeautifyFileInputChange}
/>
<div className="flex items-center justify-between gap-3 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 px-4 py-3">
<div className="min-w-0">
- <div className="text-sm font-medium text-zinc-900 dark:text-zinc-100">{tr("上传 PPT/PDF", "Upload PPT/PDF")}</div>
+ <div className="text-sm font-medium text-zinc-900 dark:text-zinc-100">{tr("上传 PDF", "Upload PDF")}</div>
<div className="text-xs text-zinc-500 dark:text-zinc-400 truncate">
{beautifyFile ? beautifyFile.name : tr("未选择文件", "No file selected")}
</div>
@@ -1485,6 +2388,21 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
</Button>
</div>
+ <label className="flex items-center justify-between gap-3 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 px-4 py-3 cursor-pointer">
+ <div className="min-w-0">
+ <div className="text-sm font-medium text-zinc-900 dark:text-zinc-100">{tr("启用模板美化(可选)", "Use template for beautify (optional)")}</div>
+ <div className="text-xs text-zinc-500 dark:text-zinc-400">
+ {tr("开启后将把当前模板传给美化模型;关闭则仅基于上传的幻灯片美化。", "When enabled, current template is passed to beautify model; otherwise beautify uses only uploaded slides.")}
+ </div>
+ </div>
+ <input
+ type="checkbox"
+ checked={beautifyUseTemplate}
+ onChange={(e) => setBeautifyUseTemplate(e.target.checked)}
+ className="h-4 w-4 rounded border-zinc-300 text-blue-600 focus:ring-blue-500"
+ />
+ </label>
+
<textarea
value={beautifyRequirement}
onChange={(e) => setBeautifyRequirement(e.target.value)}
@@ -1496,12 +2414,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<>
<div className="relative">
<textarea
- value={creationMode === "idea" ? ideaInput : creationMode === "outline" ? outlineInput : descriptionInput}
+ value={creationMode === "idea" ? ideaInput : outlineInput}
onChange={(e) => {
const v = e.target.value;
if (creationMode === "idea") setIdeaInput(v);
- else if (creationMode === "outline") setOutlineInput(v);
- else setDescriptionInput(v);
+ else setOutlineInput(v);
}}
className="w-full h-40 p-4 pb-12 rounded-xl border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-900/50 text-sm focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition-all resize-none outline-none"
placeholder={modeCopy.placeholder}
@@ -1510,6 +2427,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
type="button"
onClick={() => referenceFileInputRef.current?.click()}
disabled={isParsingReferenceFiles}
+ title={tr("上传参考文件", "Upload reference files")}
className="absolute bottom-3 right-3 inline-flex items-center gap-2 rounded-lg border border-zinc-200 dark:border-zinc-700 bg-white/80 dark:bg-zinc-900/60 px-3 py-1.5 text-xs text-zinc-700 dark:text-zinc-200 shadow-sm hover:bg-white dark:hover:bg-zinc-900 transition-colors disabled:opacity-60"
>
{isParsingReferenceFiles ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Upload className="w-3.5 h-3.5" />}
@@ -1519,12 +2437,16 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<div className="flex items-center justify-between gap-3">
<div className="text-xs text-zinc-500 dark:text-zinc-400">
- {tr("上传 PDF/文本作为参考资料(可选)", "Upload PDF/text as reference (optional)")}
+ {tr(
+ "上传 PDF/Word/LaTeX/TXT作为参考资料(可选);推荐 Word/LaTeX,图表素材更稳定。",
+ "Upload PDF/Word/LaTeX/TXT as reference (optional); Word/LaTeX recommended for stable figures."
+ )}
</div>
{referenceFiles.length > 0 && (
<button
type="button"
- onClick={() => setReferenceFiles([])}
+ onClick={() => setReferenceUploadFiles([])}
+ title={tr("清空参考文件", "Clear reference files")}
className="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"
disabled={isParsingReferenceFiles}
>
@@ -1540,6 +2462,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<button
type="button"
onClick={() => openReferencePreview(f)}
+ title={tr("预览文件", "Preview file")}
className="flex items-center gap-2 min-w-0 text-left"
>
<FileText className="w-4 h-4 text-zinc-500 flex-shrink-0" />
@@ -1549,7 +2472,11 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<button
type="button"
className="text-xs text-zinc-500 hover:text-zinc-800 dark:hover:text-zinc-200"
- onClick={() => setReferenceFiles((prev) => prev.filter((x) => x.id !== f.id))}
+ title={tr("移除文件", "Remove file")}
+ onClick={() => {
+ const nextFiles = referenceUploadFiles.filter((rf) => rf.name !== f.filename);
+ void handleReferenceFileChange(nextFiles);
+ }}
>
{tr("移除", "Remove")}
</button>
@@ -1563,12 +2490,12 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
</div>
<Button
- onClick={creationMode === "beautify" ? handleStartBeautify : creationMode === "idea" ? handleGenerateOutline : creationMode === "outline" ? handleLoadOutline : handleLoadDescriptions}
- disabled={Boolean(progress.message) || (creationMode === "beautify" ? !beautifyFile : isParsingReferenceFiles || (creationMode === "idea" ? !ideaInput.trim() : creationMode === "outline" ? !outlineInput.trim() : !descriptionInput.trim()))}
+ onClick={creationMode === "beautify" ? handleStartBeautify : creationMode === "idea" ? handleGenerateOutline : handleLoadOutline}
+ disabled={Boolean(progress.message) || (creationMode === "beautify" ? !beautifyFile : isParsingReferenceFiles || (creationMode === "idea" ? !ideaInput.trim() : !outlineInput.trim()))}
className="w-full py-6 text-lg font-medium bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white shadow-lg shadow-blue-500/20 rounded-xl transition-all hover:scale-[1.01] active:scale-[0.99]"
>
{progress.message ? <Loader2 className="w-5 h-5 mr-2 animate-spin" /> : <Sparkles className="w-5 h-5 mr-2" />}
- {progress.message || (creationMode === "beautify" ? tr("开始渲染", "Start rendering") : creationMode === "idea" ? tr("开始生成大纲", "Generate outline") : creationMode === "outline" ? tr("载入大纲", "Load outline") : tr("载入描述", "Load descriptions"))}
+ {progress.message || (creationMode === "beautify" ? tr("开始渲染", "Start rendering") : creationMode === "idea" ? tr("开始生成大纲", "Generate outline") : tr("载入大纲", "Load outline"))}
</Button>
</div>
@@ -1594,7 +2521,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
value={templateGeneratorRequirement}
onChange={(e) => setTemplateGeneratorRequirement(e.target.value)}
placeholder={tr(
- "例如:科技感、深色背景、蓝紫渐变、玻璃拟态、留白充足、适合企业汇报;不要出现任何文字。",
+ "例如:科技感、深色背景、蓝紫渐变、玻璃拟态、留白充足;不要出现任何文字。",
"e.g. Futuristic, dark background, blue-purple gradient, glassmorphism, generous whitespace; no text."
)}
className="min-h-[140px]"
@@ -1644,48 +2571,68 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<div className="flex-1 overflow-auto p-6">
<div className="w-full min-h-full bg-white dark:bg-zinc-800 rounded-xl shadow-sm flex flex-col overflow-hidden">
<div className="p-6 border-b border-border flex justify-between items-center">
- <h3 className="font-semibold text-lg">{creationMode === "description" ? tr("确认内容与描述", "Review content & descriptions") : tr("确认大纲", "Review outline")}</h3>
+ <h3 className="font-semibold text-lg">{tr("确认大纲", "Review outline")}</h3>
<div className="text-sm text-muted-foreground">{tr(`共 ${localSlides.length} 页`, `${localSlides.length} slides`)}</div>
</div>
<div className="flex-1 overflow-y-auto p-6 space-y-4">
+ {localSlides.length === 0 && (
+ <div className="rounded-lg border border-dashed border-zinc-300 bg-zinc-50 px-4 py-6 text-center text-sm text-zinc-500">
+ {tr("当前没有大纲,请返回修改后重新生成。", "No outline yet. Go back and regenerate.")}
+ </div>
+ )}
{localSlides.map((slide, i) => (
- <div key={i} className="flex gap-4 p-4 border rounded-lg bg-zinc-50 dark:bg-zinc-900/50">
+ <div key={slide.id || i} className="flex gap-4 p-4 border rounded-lg bg-zinc-50 dark:bg-zinc-900/50">
<div className="w-8 h-8 flex items-center justify-center bg-white dark:bg-zinc-800 rounded-full border text-sm font-medium text-muted-foreground">
{i + 1}
</div>
<div className="flex-1 space-y-2">
<div className="flex items-start justify-between gap-3">
- <input
- value={slide.title}
- onChange={(e) => {
- const newSlides = [...localSlides];
- newSlides[i].title = e.target.value;
- setLocalSlides(newSlides);
- }}
- className="w-full font-medium bg-transparent border-none focus:outline-none focus:ring-0 p-0"
- />
+ <input
+ value={slide.title}
+ onChange={(e) => {
+ const newSlides = [...localSlides];
+ newSlides[i].title = e.target.value;
+ setLocalSlides(newSlides);
+ }}
+ className="w-full font-medium bg-transparent border-none focus:outline-none focus:ring-0 p-0"
+ />
+ <div className="flex items-center gap-2 shrink-0">
+ <Button variant="outline" size="sm" onClick={() => handleAddOutlineSlide(i)} title={tr("在当前页后新增大纲", "Add outline after current")}>
+ <Plus className="w-4 h-4 mr-1" />
+ {tr("新增", "Add")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => handleDeleteOutlineSlide(slide.id)}
+ title={tr("删除当前大纲", "Delete current outline")}
+ >
+ <Trash2 className="w-4 h-4 mr-1" />
+ {tr("删除", "Delete")}
+ </Button>
<Button variant="outline" size="sm" onClick={() => handleAddSlideToChat(slide)} className="shrink-0">
- <MessageSquarePlus className="w-4 h-4 mr-2" />
- {tr("加入对话", "Add to chat")}
+ <MessageSquarePlus className="w-4 h-4 mr-2" />
+ {tr("加入对话", "Add to chat")}
</Button>
+ </div>
</div>
- <div className="space-y-1">
- {(slide.content || []).map((point, j) => (
- <div key={j} className="flex gap-2 text-sm text-muted-foreground">
- <span>•</span>
- <input
- value={point}
- onChange={(e) => {
- const newSlides = [...localSlides];
- if (!newSlides[i].content) newSlides[i].content = [];
- newSlides[i].content[j] = e.target.value;
- setLocalSlides(newSlides);
- }}
- className="flex-1 bg-transparent border-none focus:outline-none focus:ring-0 p-0"
- />
- </div>
- ))}
+ <div>
+ <div className="text-xs font-medium text-foreground mb-1">{tr("要点内容(content)", "Bullet content (content)")}</div>
+ <textarea
+ value={(slide.content || []).join("\n")}
+ onChange={(e) => {
+ const lines = String(e.target.value || "")
+ .split(/\r?\n/)
+ .map((x) => x.trim())
+ .filter((x) => x.length > 0);
+ const newSlides = [...localSlides];
+ newSlides[i].content = lines;
+ setLocalSlides(newSlides);
+ }}
+ className="w-full h-24 p-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ placeholder={tr("每行一个要点,例如:\n市场现状与挑战\n核心方案与价值\n落地计划与里程碑", "One bullet per line, e.g.:\nMarket status and challenges\nCore solution and value\nExecution plan and milestones")}
+ />
</div>
<div className="pt-3 grid gap-3">
<div>
@@ -1711,21 +2658,212 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
setLocalSlides(newSlides);
}}
className="w-full h-20 p-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- placeholder={tr("例如:这一页强调三个关键点;讲解时先抛出问题再给答案…", "e.g. Emphasize three key points; start with a question, then answer it…")}
+ placeholder={tr("例如:这一页强调三个关键点;讲解时先抛出问题再给答案。", "e.g. Emphasize three key points; start with a question, then answer it.")}
/>
</div>
- <div>
+ <div className="relative">
<div className="text-xs font-medium text-foreground mb-1">{tr("画面描述(description,用于生图)", "Visual description (description)")}</div>
- <textarea
- value={slide.description || ""}
- onChange={(e) => {
+ <div
+ ref={(el) => {
+ descriptionEditorRefs.current[slide.id] = el;
+ if (el) renderDescriptionEditor(slide.id, slide.description || "");
+ }}
+ contentEditable
+ suppressContentEditableWarning
+ onFocus={() => {
+ descriptionEditorFocusedRef.current = slide.id;
+ }}
+ onBlur={() => {
+ descriptionEditorFocusedRef.current = null;
+ const nextValue = parseDescriptionEditor(slide.id);
+ descriptionEditorAppliedRef.current[slide.id] = nextValue;
+ const newSlides = [...localSlides];
+ newSlides[i].description = nextValue;
+ setLocalSlides(newSlides);
+ }}
+ onInput={() => {
+ const nextValue = parseDescriptionEditor(slide.id);
+ descriptionEditorAppliedRef.current[slide.id] = nextValue;
const newSlides = [...localSlides];
- newSlides[i].description = e.target.value;
+ newSlides[i].description = nextValue;
setLocalSlides(newSlides);
}}
- className="w-full h-24 p-3 rounded-md border border-input bg-background text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- placeholder={tr("例如:科技感蓝色渐变背景,中心是抽象的 AI 芯片与电路纹理,干净留白…", "e.g. Futuristic blue gradient background, abstract AI chip and circuit textures, clean whitespace…")}
+ onKeyDown={(e) => {
+ if (materialPickerSlideId === slide.id && (slideMaterials[slide.id] || []).length > 0) {
+ const list = slideMaterials[slide.id] || [];
+ const len = list.length;
+ if (e.key === "ArrowDown") {
+ e.preventDefault();
+ setMaterialPickerActiveIndex((prev) => (prev + 1) % len);
+ return;
+ }
+ if (e.key === "ArrowUp") {
+ e.preventDefault();
+ setMaterialPickerActiveIndex((prev) => (prev - 1 + len) % len);
+ return;
+ }
+ if (e.key === "Enter") {
+ e.preventDefault();
+ const idx = Math.max(0, Math.min(materialPickerActiveIndex, len - 1));
+ const picked = list[idx];
+ if (picked) {
+ insertMaterialTokenToSlideDescription(i, slide.id, picked.name);
+ }
+ return;
+ }
+ }
+ if (e.key === "Escape") {
+ setMaterialPickerSlideId(null);
+ setMaterialPickerPos(null);
+ setMaterialPickerActiveIndex(0);
+ materialPickerReplaceRangeRef.current = null;
+ return;
+ }
+ if ((e.key === "Backspace" || e.key === "Delete") && e.currentTarget) {
+ const root = e.currentTarget;
+ const sel = window.getSelection();
+ if (!sel || sel.rangeCount === 0) return;
+ const r = sel.getRangeAt(0);
+ if (!root.contains(r.startContainer) || !r.collapsed) return;
+ const tryRemoveToken = (el: Element | null) => {
+ if (!el) return false;
+ const token = (el as HTMLElement).getAttribute("data-material-token");
+ if (!token) return false;
+ el.remove();
+ return true;
+ };
+ if (r.startContainer.nodeType === Node.TEXT_NODE) {
+ const t = r.startContainer as Text;
+ if (e.key === "Backspace" && r.startOffset === 0) {
+ const prev = t.previousSibling;
+ if (prev && prev.nodeType === Node.ELEMENT_NODE && tryRemoveToken(prev as Element)) {
+ e.preventDefault();
+ }
+ }
+ if (e.key === "Delete" && r.startOffset === t.data.length) {
+ const next = t.nextSibling;
+ if (next && next.nodeType === Node.ELEMENT_NODE && tryRemoveToken(next as Element)) {
+ e.preventDefault();
+ }
+ }
+ }
+ }
+ }}
+ onKeyUp={(e) => {
+ if ((slideMaterials[slide.id] || []).length === 0) return;
+ if (e.key === "/" || e.key === "/") {
+ openMaterialPickerAtCaret(slide.id);
+ }
+ }}
+ className="w-full min-h-[96px] max-h-[200px] overflow-y-auto whitespace-pre-wrap break-words rounded-md border border-input bg-background p-3 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ data-placeholder={tr("例如:科技感蓝色渐变背景,中间是 AI 芯片与电路纹理,留白清晰。", "e.g. Futuristic blue gradient background, abstract AI chip and circuit textures, clean whitespace.")}
/>
+ {materialPickerSlideId === slide.id && (slideMaterials[slide.id] || []).length > 0 && (
+ <div
+ ref={materialPickerRef}
+ className="absolute z-20 w-56 rounded-md border border-border bg-popover p-2 shadow-sm"
+ style={{ left: materialPickerPos?.left ?? 8, top: materialPickerPos?.top ?? 8 }}
+ >
+ <div className="max-h-56 space-y-1 overflow-y-auto">
+ {(slideMaterials[slide.id] || []).map((img, idx) => (
+ <button
+ key={img.id}
+ type="button"
+ onClick={() => insertMaterialTokenToSlideDescription(i, slide.id, img.name)}
+ onMouseEnter={() => setMaterialPickerActiveIndex(idx)}
+ title={tr(`插入第 ${idx + 1} 张素材`, `Insert material ${idx + 1}`)}
+ className={`flex w-full items-center gap-2 rounded-md border px-2 py-1.5 text-left text-xs ${
+ materialPickerActiveIndex === idx
+ ? "border-blue-300 bg-blue-100 text-blue-800 ring-1 ring-blue-300"
+ : "border-blue-200 bg-blue-50 text-blue-700 hover:bg-blue-100"
+ }`}
+ >
+ <img src={img.dataUrl} alt={img.name} className="h-8 w-8 rounded object-cover" />
+ <span className="truncate">{img.name}</span>
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ <div>
+ <div className="mb-1 flex items-center justify-between text-xs font-medium text-foreground">
+ <span>{tr("素材图片(用于该页生图)", "Material images (for this slide)")}</span>
+ <button
+ type="button"
+ onClick={() => slideMaterialInputRefs.current[slide.id]?.click()}
+ title={tr("上传素材图片", "Upload material images")}
+ className="inline-flex items-center gap-1 rounded-md border border-zinc-300 px-2 py-1 text-xs text-zinc-700 hover:bg-zinc-100"
+ >
+ <Upload className="h-3.5 w-3.5" />
+ {tr("上传", "Upload")}
+ </button>
+ <input
+ ref={(el) => {
+ slideMaterialInputRefs.current[slide.id] = el;
+ }}
+ type="file"
+ accept="image/*"
+ multiple
+ className="hidden"
+ onChange={(e) => {
+ const files = Array.from(e.target.files || []);
+ e.target.value = "";
+ void addSlideMaterialImages(slide.id, files);
+ }}
+ />
+ </div>
+ {(slideMaterials[slide.id] || []).length === 0 ? (
+ <div className="rounded-md border border-dashed border-zinc-300 px-3 py-2 text-xs text-zinc-500">
+ {tr("暂无素材,上传后可在 description 输入 / 选择变量", "No materials yet. Upload images, then type / in description to insert variables.")}
+ </div>
+ ) : (
+ <div className="flex flex-wrap gap-3">
+ {(slideMaterials[slide.id] || []).map((img) => (
+ <div key={img.id} className="w-20">
+ <div
+ className="group relative h-20 w-20 cursor-zoom-in overflow-hidden rounded-md border bg-background"
+ onClick={() => setMaterialPreview({ open: true, slideTitle: slide.title, item: img })}
+ title={tr("点击查看素材", "Click to preview material")}
+ >
+ <img src={img.dataUrl} alt={img.name} className="h-full w-full object-cover" />
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ setMaterialPreview({ open: true, slideTitle: slide.title, item: img });
+ }}
+ className="absolute bottom-1 left-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-blue-600/85 text-white opacity-0 transition-all group-hover:opacity-100 hover:bg-blue-700"
+ aria-label={tr("查看素材", "Preview material")}
+ title={tr("查看", "Preview")}
+ >
+ <Eye className="h-3 w-3" />
+ </button>
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ removeSlideMaterialImage(slide.id, img.id);
+ }}
+ className="absolute right-1 top-1 inline-flex h-5 w-5 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-all group-hover:opacity-100 hover:bg-black/80"
+ aria-label={tr("移除素材", "Remove material")}
+ title={tr("移除", "Remove")}
+ >
+ ×
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={() => setMaterialPreview({ open: true, slideTitle: slide.title, item: img })}
+ className="mt-1 w-full truncate text-center text-xs text-foreground hover:text-blue-600"
+ title={tr("点击查看素材", "Click to preview material")}
+ >
+ {img.name}
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
</div>
</div>
</div>
@@ -1734,12 +2872,50 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
</div>
<div className="p-6 border-t border-border bg-zinc-50/50 dark:bg-zinc-900/50 flex justify-end gap-3">
- <Button variant="outline" onClick={() => setCreationStep('idle')}>{tr("返回修改", "Back")}</Button>
- <Button onClick={creationMode === "description" ? handleGenerateImagesOnly : handleGenerateFullPpt} className="bg-blue-600 hover:bg-blue-700">
+ <Button variant="outline" onClick={handleBackToInputFromOutline}>{tr("返回修改", "Back")}</Button>
+ <Button onClick={handleGenerateFullPpt} className="bg-blue-600 hover:bg-blue-700" disabled={localSlides.length === 0}>
<Sparkles className="w-4 h-4 mr-2" />
- {creationMode === "description" ? tr("开始渲染图片", "Render images") : tr("生成完整 PPT", "Generate full deck")}
+ {tr("生成完整 PPT", "Generate full deck")}
</Button>
</div>
+ <Dialog
+ open={materialPreview.open}
+ onOpenChange={(open) => setMaterialPreview((prev) => ({ ...prev, open }))}
+ >
+ <DialogContent className="w-[92vw] max-w-[92vw] max-h-[92vh] overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>{tr("素材预览", "Material preview")}</DialogTitle>
+ </DialogHeader>
+ {materialPreview.item && (
+ <div className="space-y-3">
+ <div className="h-[72vh] min-h-[360px] w-full overflow-auto rounded-lg border bg-muted/20 flex items-center justify-center">
+ <img
+ src={materialPreview.item.dataUrl}
+ alt={materialPreview.item.name}
+ className="block max-h-full max-w-full object-scale-down"
+ />
+ </div>
+ <div className="grid gap-1 text-xs text-muted-foreground">
+ <div>{tr("所在幻灯片", "Slide")}: {materialPreview.slideTitle || "-"}</div>
+ <div>{tr("素材编号", "Material label")}: {materialPreview.item.name}</div>
+ {materialPreview.item.refLabel ? <div>{tr("来源标签", "Reference label")}: {materialPreview.item.refLabel}</div> : null}
+ {materialPreview.item.caption ? <div>{tr("简短说明", "Caption")}: {materialPreview.item.caption}</div> : null}
+ {materialPreview.item.sourceFileName ? <div>{tr("来源文件", "Source file")}: {materialPreview.item.sourceFileName}</div> : null}
+ {typeof materialPreview.item.sourcePage === "number" ? <div>{tr("来源页码", "Source page")}: {materialPreview.item.sourcePage}</div> : null}
+ </div>
+ <div className="flex justify-end">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => window.open(materialPreview.item!.dataUrl, "_blank", "noopener,noreferrer")}
+ >
+ {tr("在新窗口查看原图", "Open full image in new tab")}
+ </Button>
+ </div>
+ </div>
+ )}
+ </DialogContent>
+ </Dialog>
</div>
</div>
</div>
@@ -1767,19 +2943,16 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
</div>
<div className="space-y-2">
- <h3 className="font-semibold text-lg">AI 正在创作中</h3>
- <p className="text-sm text-muted-foreground">{progress.message || (creationStep === "generating_content" ? tr("正在生成内容…", "Generating content…") : tr("正在渲染图片…", "Rendering images…"))}</p>
+ <h3 className="font-semibold text-lg">{tr("AI 正在创作中", "AI is creating")}</h3>
+ <p className="text-sm text-muted-foreground">
+ {progress.message || tr("正在渲染图片…", "Rendering images...")}
+ </p>
</div>
<div className="flex justify-center gap-2 text-xs text-muted-foreground">
- <div className={`flex items-center gap-1 ${creationStep === 'generating_content' ? 'text-blue-600' : 'text-green-600'}`}>
- {creationStep === 'generating_content' ? <Loader2 className="w-3 h-3 animate-spin" /> : <Check className="w-3 h-3" />}
- <span>生成内容</span>
- </div>
- <span className="text-zinc-300">→</span>
- <div className={`flex items-center gap-1 ${creationStep === 'generating_images' ? 'text-blue-600' : 'text-zinc-400'}`}>
- {creationStep === 'generating_images' && <Loader2 className="w-3 h-3 animate-spin" />}
- <span>渲染图片</span>
+ <div className={`flex items-center gap-1 ${creationStep === 'generating_images' ? 'text-blue-600' : 'text-green-600'}`}>
+ {creationStep === 'generating_images' ? <Loader2 className="w-3 h-3 animate-spin" /> : <Check className="w-3 h-3" />}
+ <span>{tr("渲染图片", "Render images")}</span>
</div>
</div>
</div>
@@ -1798,14 +2971,16 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<div className="h-4 w-px bg-border"></div>
<button
onClick={handleBackToStart}
+ title={tr("返回开始", "Back to start")}
className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm"
>
<ArrowLeft className="w-3.5 h-3.5" />
<span>{tr("返回开始", "Back")}</span>
</button>
<button
- onClick={() => setSlideshowOpen(true)}
+ onClick={openSlideshow}
disabled={activeSlides.length === 0}
+ title={tr("播放幻灯片", "Play slideshow")}
className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm"
>
<Play className="w-3.5 h-3.5" />
@@ -1815,22 +2990,41 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<button
onClick={handleDownloadPpt}
disabled={activeSlides.length === 0 || !!isExporting}
+ title={tr("导出 PPTX", "Export PPTX")}
className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm"
>
{isExporting === "pptx" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Download className="w-3.5 h-3.5" />}
- <span>{isExporting === "pptx" ? tr("导出中…", "Exporting…") : tr("导出 PPTX", "Export PPTX")}</span>
+ <span>{isExporting === "pptx" ? tr("导出中…", "Exporting...") : tr("导出 PPTX", "Export PPTX")}</span>
</button>
<button
onClick={handleDownloadPdf}
disabled={activeSlides.length === 0 || !!isExporting}
+ title={tr("导出 PDF", "Export PDF")}
className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm"
>
{isExporting === "pdf" ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Download className="w-3.5 h-3.5" />}
- <span>{isExporting === "pdf" ? tr("导出中…", "Exporting…") : tr("导出 PDF", "Export PDF")}</span>
+ <span>{isExporting === "pdf" ? tr("导出中…", "Exporting...") : tr("导出 PDF", "Export PDF")}</span>
</button>
+ {creationMode === "beautify" && (
+ <button
+ onClick={handleRetryFailedBeautify}
+ disabled={failedBeautifyCount === 0 || Boolean(progress.message)}
+ title={tr("重试失败页", "Retry failed slides")}
+ className="flex items-center gap-2 px-3 py-1.5 bg-zinc-100 dark:bg-zinc-700 hover:bg-zinc-200 dark:hover:bg-zinc-600 text-xs rounded transition-colors shadow-sm disabled:opacity-60"
+ >
+ <Sparkles className="w-3.5 h-3.5" />
+ <span>{tr("重试失败页", "Retry failed")}</span>
+ {failedBeautifyCount > 0 ? <span className="rounded bg-red-100 px-1.5 py-0.5 text-[10px] text-red-700">{failedBeautifyCount}</span> : null}
+ </button>
+ )}
</div>
- <div className="text-xs text-muted-foreground">
- {activeSlides.length > 0 ? tr(`第 ${currentSlideIndex + 1} / ${activeSlides.length} 页`, `Slide ${currentSlideIndex + 1} / ${activeSlides.length}`) : tr("空文档", "Empty")}
+ <div className="flex items-center gap-3 text-xs text-muted-foreground">
+ {creationMode === "beautify" && failedBeautifyCount > 0 ? (
+ <span className="rounded border border-red-200 bg-red-50 px-2 py-1 text-red-700">
+ {tr(`失败 ${failedBeautifyCount} 页`, `${failedBeautifyCount} failed`)}
+ </span>
+ ) : null}
+ <span>{activeSlides.length > 0 ? tr(`第 ${currentSlideIndex + 1} / ${activeSlides.length} 页`, `Slide ${currentSlideIndex + 1} / ${activeSlides.length}`) : tr("空文档", "Empty")}</span>
</div>
</div>
@@ -1840,6 +3034,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<div className="w-64 bg-zinc-50 dark:bg-zinc-900 border-r border-border overflow-y-auto p-4 space-y-4">
{activeSlides.map((slide, index) => {
const hasGeneratedImage = generatedImages[slide.id || index];
+ const slideFailure = beautifyFailures[slide.id];
return (
<ContextMenu key={slide.id || index}>
<ContextMenuTrigger>
@@ -1885,6 +3080,14 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<div className="absolute bottom-1 right-1 bg-black/60 text-white text-[10px] px-1.5 rounded-sm backdrop-blur-sm">
{index + 1}
</div>
+ {slideFailure ? (
+ <div
+ className="absolute top-1 right-1 bg-red-600/90 text-white text-[10px] px-1.5 py-0.5 rounded-sm max-w-[85%] truncate"
+ title={slideFailure}
+ >
+ {tr("美化失败", "Beautify failed")}
+ </div>
+ ) : null}
</div>
</ContextMenuTrigger>
<ContextMenuContent>
@@ -1920,7 +3123,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
disabled={!currentSlide || isGeneratingImage}
>
{isGeneratingImage ? <Loader2 className="w-3 h-3 mr-1 animate-spin" /> : null}
- 重渲染本页
+ {tr("重新渲染本页", "Regenerate this slide")}
</Button>
{currentSlide && (imageVersions[currentSlide.id] || []).length > 0 && (
<select
@@ -1939,12 +3142,18 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
>
{(imageVersions[currentSlide.id] || []).map((v, idx) => (
<option key={v.id} value={v.id}>
- {idx + 1} · {new Date(v.timestamp).toLocaleString()}
+ {idx + 1} 路 {new Date(v.timestamp).toLocaleString()}
</option>
))}
</select>
)}
</div>
+ {currentSlideFailure ? (
+ <div className="absolute top-16 left-4 z-30 max-w-[520px] rounded-lg border border-red-200 bg-red-50/95 px-3 py-2 text-xs text-red-700 shadow-sm">
+ <span className="font-medium mr-1">{tr("本页美化失败:", "Slide beautify failed:")}</span>
+ <span>{currentSlideFailure}</span>
+ </div>
+ ) : null}
{currentSlide ? (
<ContextMenu>
<ContextMenuTrigger className="outline-none">
@@ -2012,21 +3221,38 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
</div>
</div>
- <Dialog open={slideshowOpen} onOpenChange={setSlideshowOpen}>
- <DialogContent className="inset-0 left-0 top-0 translate-x-0 translate-y-0 w-screen h-screen max-w-none sm:max-w-none rounded-none p-0 bg-black/95 border-none flex flex-col">
+ <Dialog open={slideshowOpen} onOpenChange={(open) => (open ? setSlideshowOpen(true) : closeSlideshow())}>
+ <DialogContent className="inset-0 left-0 top-0 translate-x-0 translate-y-0 w-screen h-screen max-w-none sm:max-w-none rounded-none p-0 bg-black/95 border-none">
+ <div ref={slideshowRootRef} className="w-full h-full flex flex-col">
<div className="h-16 px-6 flex items-center justify-between text-white/90 bg-black/50 backdrop-blur-sm z-50">
<div className="text-sm font-medium">
- {activeSlides.length > 0 ? `第 ${slideshowIndex + 1} / ${activeSlides.length} 页` : ""}
+ {activeSlides.length > 0 ? `${uiLang === "zh" ? "第" : "Slide "}${slideshowIndex + 1} / ${activeSlides.length}${uiLang === "zh" ? " 页" : ""}` : ""}
</div>
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="sm"
+ title={slideshowFullscreen ? tr("退出全屏", "Exit fullscreen") : tr("进入全屏", "Enter fullscreen")}
className="text-white hover:text-white hover:bg-white/10 gap-2"
- onClick={() => setSlideshowOpen(false)}
+ onClick={() => {
+ if (slideshowFullscreen) {
+ void exitSlideshowFullscreen();
+ } else {
+ void enterSlideshowFullscreen();
+ }
+ }}
+ >
+ {slideshowFullscreen ? <Minimize2 className="w-4 h-4" /> : <Maximize2 className="w-4 h-4" />}
+ {slideshowFullscreen ? tr("退出全屏", "Exit fullscreen") : tr("全屏", "Fullscreen")}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-white hover:text-white hover:bg-white/10 gap-2"
+ onClick={closeSlideshow}
>
<X className="w-4 h-4" />
- 退出
+ {tr("退出", "Close")}
</Button>
</div>
</div>
@@ -2094,8 +3320,77 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
<ArrowRight className="w-6 h-6" />
</Button>
</div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog open={backConfirmOpen} onOpenChange={setBackConfirmOpen}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>{tr("确认返回开始", "Confirm restart")}</DialogTitle>
+ </DialogHeader>
+ <div className="text-sm text-muted-foreground">
+ {tr(
+ "返回开始将清空当前 PPT(建议先导出保存)。是否继续?",
+ "Restart will clear the current deck (export first if needed). Continue?"
+ )}
+ </div>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => setBackConfirmOpen(false)}>
+ {tr("取消", "Cancel")}
+ </Button>
+ <Button
+ variant="destructive"
+ onClick={() => {
+ setBackConfirmOpen(false);
+ resetToStart();
+ }}
+ >
+ {tr("确认返回", "Confirm")}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={materialPreview.open}
+ onOpenChange={(open) => setMaterialPreview((prev) => ({ ...prev, open }))}
+ >
+ <DialogContent className="w-[92vw] max-w-[92vw] max-h-[92vh] overflow-hidden">
+ <DialogHeader>
+ <DialogTitle>{tr("素材预览", "Material preview")}</DialogTitle>
+ </DialogHeader>
+ {materialPreview.item && (
+ <div className="space-y-3">
+ <div className="h-[72vh] min-h-[360px] w-full overflow-auto rounded-lg border bg-muted/20 flex items-center justify-center">
+ <img
+ src={materialPreview.item.dataUrl}
+ alt={materialPreview.item.name}
+ className="block max-h-full max-w-full object-scale-down"
+ />
+ </div>
+ <div className="grid gap-1 text-xs text-muted-foreground">
+ <div>{tr("所在幻灯片", "Slide")}: {materialPreview.slideTitle || "-"}</div>
+ <div>{tr("素材编号", "Material label")}: {materialPreview.item.name}</div>
+ {materialPreview.item.refLabel ? <div>{tr("来源标签", "Reference label")}: {materialPreview.item.refLabel}</div> : null}
+ {materialPreview.item.caption ? <div>{tr("简短说明", "Caption")}: {materialPreview.item.caption}</div> : null}
+ {materialPreview.item.sourceFileName ? <div>{tr("来源文件", "Source file")}: {materialPreview.item.sourceFileName}</div> : null}
+ {typeof materialPreview.item.sourcePage === "number" ? <div>{tr("来源页码", "Source page")}: {materialPreview.item.sourcePage}</div> : null}
+ </div>
+ <div className="flex justify-end">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => window.open(materialPreview.item!.dataUrl, "_blank", "noopener,noreferrer")}
+ >
+ {tr("在新窗口查看原图", "Open full image in new tab")}
+ </Button>
+ </div>
+ </div>
+ )}
</DialogContent>
</Dialog>
</div>
);
}
+
+
+