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.

feat: drop image-to-PPT, add generation timeouts, smooth chat streaming

codingFeng1013ecdf74710b3
diff --git a/.gitignore b/.gitignore
index f9b457a..85f4ab1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -63,3 +63,6 @@ Desktop.ini
# Large local test fixtures (see tests/ppt-vision-fixture.test.ts)
tests/fixtures/
+
+# Tutorial video tooling and its recordings stay local
+tools/video/
diff --git a/client/pages/portal/PortalPage.tsx b/client/pages/portal/PortalPage.tsx
index 4d2a57e..8d8c8e4 100644
--- a/client/pages/portal/PortalPage.tsx
+++ b/client/pages/portal/PortalPage.tsx
@@ -122,10 +122,10 @@ const detailConfigs: Record<PortalWorkspace, DetailConfig> = {
},
cad: {
title: "\u5ba4\u5185\u8bbe\u8ba1",
- subtitle: "\u4ece\u7a7a\u95f4\u9700\u6c42\u5230\u6210\u5957\u56fe\u7eb8\u4e0e\u6e32\u67d3",
- intro: "\u5ba4\u5185\u8bbe\u8ba1\u5c06\u7a7a\u95f4\u9700\u6c42\u8f6c\u5316\u4e3a\u5b8c\u6574\u7684\u8bbe\u8ba1\u65b9\u6848\uff0c\u81ea\u52a8\u751f\u6210\u5e73\u9762\u5e03\u5c40\u3001\u7acb\u9762\u4e0e\u8be6\u56fe\uff0c\u8f93\u51fa\u6e32\u67d3\u53ca\u6750\u6599\u6e05\u5355\u3002",
- tags: ["\u7a7a\u95f4\u89c4\u5212", "2D SVG", "\u6e32\u67d3 / \u6750\u6599\u6e05\u5355"],
- bullets: ["\u6237\u578b\u89e3\u6790\u4e0e\u529f\u80fd\u5206\u533a\uff0c\u5feb\u901f\u786e\u5b9a\u7a7a\u95f4\u5e03\u5c40", "\u591a\u56fe\u7eb8\u8054\u52a8\u751f\u6210\uff0c\u5e73\u9762\u3001\u7acb\u9762\u3001\u8be6\u56fe\u4e00\u4f53\u5316", "\u6548\u679c\u56fe\u4e0e\u6750\u6599\u53c2\u8003\uff0c\u5448\u73b0\u771f\u5b9e\u7a7a\u95f4\u6548\u679c", "\u6750\u6599\u6e05\u5355\u4e0e\u56fe\u7eb8\u5bfc\u51fa\uff0c\u652f\u6301\u65bd\u5de5\u4ea4\u4ed8"],
+ subtitle: "\u4ece\u7a7a\u95f4\u9700\u6c42\u5230\u6210\u5957\u56fe\u7eb8\u4e0e\u7269\u6599\u6e05\u5355",
+ intro: "\u5ba4\u5185\u8bbe\u8ba1\u5c06\u7a7a\u95f4\u9700\u6c42\u8f6c\u5316\u4e3a\u5b8c\u6574\u7684\u8bbe\u8ba1\u65b9\u6848\uff0c\u81ea\u52a8\u751f\u6210\u5e73\u9762\u5e03\u5c40\u3001\u7acb\u9762\u4e0e\u8be6\u56fe\uff0c\u8f93\u51fa\u88c5\u4fee\u56fe\u7eb8\u53ca\u6750\u6599\u6e05\u5355\u3002",
+ tags: ["\u7a7a\u95f4\u89c4\u5212", "2D SVG", "\u56fe\u7eb8 / \u6750\u6599\u6e05\u5355"],
+ bullets: ["\u6237\u578b\u89e3\u6790\u4e0e\u529f\u80fd\u5206\u533a\uff0c\u5feb\u901f\u786e\u5b9a\u7a7a\u95f4\u5e03\u5c40", "\u591a\u56fe\u7eb8\u8054\u52a8\u751f\u6210\uff0c\u5e73\u9762\u3001\u7acb\u9762\u3001\u8be6\u56fe\u4e00\u4f53\u5316", "\u5206\u6790\u56fe\u677f\u68b3\u7406\u65b9\u6848\uff0c\u5206\u533a\u4e0e\u7b56\u7565\u4e00\u76ee\u4e86\u7136", "\u6750\u6599\u6e05\u5355\u4e0e\u56fe\u7eb8\u5bfc\u51fa\uff0c\u652f\u6301\u65bd\u5de5\u4ea4\u4ed8"],
previews: [
{ title: "\u88c5\u4fee\u5e73\u9762\u5e03\u7f6e\u56fe", image: "/examples/cad/01.png" },
{ title: "\u5730\u9762\u94fa\u88c5\u56fe", image: "/examples/cad/02.png" },
@@ -137,8 +137,8 @@ const detailConfigs: Record<PortalWorkspace, DetailConfig> = {
{ title: "\u7a7a\u95f4\u5206\u6790", text: "\u5206\u6790\u529f\u80fd\u5206\u533a\u4e0e\u52a8\u7ebf\u3002", icon: Package },
{ title: "\u751f\u6210\u5e73\u9762", text: "\u751f\u6210\u5e73\u9762\u5e03\u7f6e\u4e0e\u5c3a\u5bf8\u6807\u6ce8\u3002", icon: Home },
{ title: "\u8054\u52a8\u56fe\u7eb8", text: "\u8054\u52a8\u7acb\u9762\u3001\u5929\u82b1\u548c\u8282\u70b9\u56fe\u3002", icon: Layers3 },
- { title: "\u6e32\u67d3\u6821\u9a8c", text: "\u751f\u6210\u6548\u679c\u56fe\u5e76\u6821\u9a8c\u6750\u8d28\u3002", icon: Image },
- { title: "\u5bfc\u51fa\u56fe\u7eb8", text: "\u5bfc\u51fa CAD/PDF/SVG \u4e0e\u6750\u6599\u6e05\u5355\u3002", icon: Upload },
+ { title: "\u56fe\u7eb8\u6210\u5957", text: "\u4e00\u6b21\u751f\u6210\u4e03\u5f20\u88c5\u4fee\u65bd\u5de5\u56fe\u7eb8\u3002", icon: Image },
+ { title: "\u5bfc\u51fa\u56fe\u7eb8", text: "\u5bfc\u51fa SVG\u3001JPG\u3001PDF \u4e0e\u6750\u6599\u6e05\u5355\u3002", icon: Upload },
],
cta: "\u5f00\u59cb\u8bbe\u8ba1",
slogan: "\u8ba9\u5ba4\u5185\u8bbe\u8ba1\u50cf\u753b\u5e03\u4e00\u6837\u81ea\u7531\u521b\u4f5c",
@@ -148,7 +148,7 @@ const detailConfigs: Record<PortalWorkspace, DetailConfig> = {
subtitle: "\u4ece\u4e3b\u9898\u5230\u6f14\u793a\u6587\u7a3f\uff0c\u6309\u9875\u9762\u6301\u7eed\u8fed\u4ee3",
intro: "PPT \u6f14\u793a\u5c06\u4e3b\u9898\u7ed3\u6784\u5316\u4e3a\u53ef\u6f14\u793a\u7684\u903b\u8f91\u5185\u5bb9\uff0c\u81ea\u52a8\u751f\u6210\u6f14\u793a\u6587\u7a3f\u5927\u7eb2\u5e76\u62c6\u5206\u9875\u9762\u7c7b\u578b\uff0c\u652f\u6301\u9875\u9762\u751f\u6210\u4e0e\u5c40\u90e8\u8fed\u4ee3\u3002",
tags: ["\u7ed3\u6784\u5316\u751f\u6210", "\u9875\u9762\u7ea7\u7f16\u8f91", "\u6a21\u677f\u5bf9\u9f50"],
- bullets: ["\u4e3b\u9898\u8f6c\u5927\u7eb2\uff0c\u6784\u5efa\u6e05\u6670\u7684\u6f14\u793a\u903b\u8f91", "\u81ea\u52a8\u62c6\u5206\u9875\u9762\u7c7b\u578b\uff0c\u5339\u914d\u6700\u4f73\u8868\u8fbe\u65b9\u5f0f", "\u652f\u6301\u5c40\u90e8\u7eed\u5199\u4e0e\u6539\u5199\uff0c\u7cbe\u7ec6\u8c03\u6574\u6bcf\u4e00\u9875", "\u5bfc\u51fa\u53ef\u7f16\u8f91\u6f14\u793a\u7a3f\uff0c\u81ea\u7531\u8c03\u6574\u4e0e\u590d\u7528"],
+ bullets: ["\u4e3b\u9898\u8f6c\u5927\u7eb2\uff0c\u6784\u5efa\u6e05\u6670\u7684\u6f14\u793a\u903b\u8f91", "\u81ea\u52a8\u62c6\u5206\u9875\u9762\u7c7b\u578b\uff0c\u5339\u914d\u6700\u4f73\u8868\u8fbe\u65b9\u5f0f", "\u652f\u6301\u5c40\u90e8\u7eed\u5199\u4e0e\u6539\u5199\uff0c\u7cbe\u7ec6\u8c03\u6574\u6bcf\u4e00\u9875", "\u5bfc\u51fa PDF \u4e0e\u56fe\u7247\u7248 PPT\uff0c\u65b9\u4fbf\u5206\u4eab\u4e0e\u6f14\u793a"],
previews: [
{ title: "AI\u5185\u5bb9\u521b\u4f5c\u6d41\u7a0b", image: "/examples/readme-previews/ppt/ppt1.png" },
{ title: "\u667a\u80fd\u534f\u4f5c\u589e\u957f", image: "/examples/readme-previews/ppt/ppt2.png" },
@@ -161,7 +161,7 @@ const detailConfigs: Record<PortalWorkspace, DetailConfig> = {
{ title: "\u62c6\u5206\u9875\u9762", text: "\u81ea\u52a8\u8bc6\u522b\u5c01\u9762\u3001\u76ee\u5f55\u3001\u56fe\u8868\u3001\u7ed3\u8bba\u7b49\u7ed3\u6784\u3002", icon: Blocks },
{ title: "\u9875\u9762\u751f\u6210", text: "\u6309\u5927\u7eb2\u548c\u9875\u9762\u7c7b\u578b\u751f\u6210\u5185\u5bb9\u3002", icon: Presentation },
{ title: "\u5c40\u90e8\u8fed\u4ee3", text: "\u652f\u6301\u9875\u9762\u7eed\u5199\u3001\u6539\u5199\u4e0e\u8c03\u6574\u3002", icon: Pencil },
- { title: "\u5bfc\u51fa PPT", text: "\u5bfc\u51fa\u53ef\u7f16\u8f91\u7684 PPT \u683c\u5f0f\u3002", icon: Upload },
+ { title: "\u5bfc\u51fa PPT", text: "\u5bfc\u51fa PDF \u6216\u56fe\u7247\u7248 PPT\u3002", icon: Upload },
],
cta: "\u5f00\u59cb\u5236\u4f5c",
slogan: "\u8ba9\u6f14\u793a\u521b\u4f5c\u50cf\u753b\u5e03\u4e00\u6837\u81ea\u7531\u6d41\u7545",
@@ -220,17 +220,17 @@ const detailConfigsEn: Record<PortalWorkspace, DetailConfig> = {
},
cad: {
title: "Interior Design",
- subtitle: "From spatial requirements to drawings, renders, and material lists",
- intro: "The Interior Design workspace turns room requirements into design packages, including layouts, elevations, details, render references, and material lists.",
- tags: ["Space planning", "2D SVG", "Renders / Materials"],
- bullets: ["Analyze floor plans and functional zones", "Generate linked plan, elevation, ceiling, and detail drawings", "Use render references and material cues to present the space", "Export drawings and material lists for delivery"],
+ subtitle: "From spatial requirements to drawing sets and material lists",
+ intro: "The Interior Design workspace turns room requirements into design packages, including layouts, elevations, details, analysis boards, and material lists.",
+ tags: ["Space planning", "2D SVG", "Drawings / Materials"],
+ bullets: ["Analyze floor plans and functional zones", "Generate linked plan, elevation, ceiling, and detail drawings", "Map zones and key strategies on analysis boards", "Export drawings and material lists for delivery"],
previews: withTitles(detailConfigs.cad.previews, ["Furnished floor plan", "Floor finish plan", "Reflected ceiling plan", "Construction details"]),
steps: [
{ title: "Input Brief", text: "Provide room information and design needs.", icon: FileText },
{ title: "Plan Space", text: "Analyze zoning and circulation.", icon: Package },
{ title: "Create Plan", text: "Generate layout drawings and dimensions.", icon: Home },
{ title: "Link Drawings", text: "Connect elevations, ceilings, and details.", icon: Layers3 },
- { title: "Render Check", text: "Generate render references and review materials.", icon: Image },
+ { title: "Drawing Set", text: "Generate seven renovation drawing sheets in one pass.", icon: Image },
{ title: "Export", text: "Export drawings and material lists.", icon: Upload },
],
cta: "Start Designing",
@@ -241,7 +241,7 @@ const detailConfigsEn: Record<PortalWorkspace, DetailConfig> = {
subtitle: "From topic to deck, with page-level iteration",
intro: "The PPT workspace structures your topic into a presentation outline, splits it into slide types, and supports slide generation, review, and local revision.",
tags: ["Outline first", "Slide editing", "Template aligned"],
- bullets: ["Turn a topic into a clear deck outline", "Split content into cover, agenda, chart, and conclusion slides", "Revise or extend individual slides", "Export editable presentation files"],
+ bullets: ["Turn a topic into a clear deck outline", "Split content into cover, agenda, chart, and conclusion slides", "Revise or extend individual slides", "Export as PDF or image-based PPT"],
previews: withTitles(detailConfigs.ppt.previews, ["AI content creation", "Growth through collaboration", "Business innovation", "Low-carbon campus"]),
steps: [
{ title: "Input Topic", text: "Enter the topic and target audience.", icon: FileText },
@@ -249,7 +249,7 @@ const detailConfigsEn: Record<PortalWorkspace, DetailConfig> = {
{ title: "Split Slides", text: "Identify cover, agenda, chart, and summary pages.", icon: Blocks },
{ title: "Generate", text: "Create slides from the outline and page types.", icon: Presentation },
{ title: "Iterate", text: "Rewrite, extend, or adjust selected pages.", icon: Pencil },
- { title: "Export PPT", text: "Export an editable PPT file.", icon: Upload },
+ { title: "Export PPT", text: "Export as PDF or image-based PPT.", icon: Upload },
],
cta: "Start Building",
slogan: "Make presentation creation smooth and visual",
diff --git a/client/pages/portal/data.ts b/client/pages/portal/data.ts
index 9ab5eea..ce5538e 100644
--- a/client/pages/portal/data.ts
+++ b/client/pages/portal/data.ts
@@ -33,8 +33,8 @@ export const portalCanvasItems: PortalCanvasItem[] = [
id: "cad",
zhTitle: "室内设计",
enTitle: "Interior Design",
- zhSummary: "平面方案、效果图与材料清单联动",
- enSummary: "Layouts, renders, and material lists in one pass",
+ zhSummary: "平面方案、施工图纸与材料清单联动",
+ enSummary: "Layouts, drawing sets, and material lists in one pass",
image: "/examples/cad/01.png",
angle: 0,
accent: "#7C8B6E",
@@ -43,8 +43,8 @@ export const portalCanvasItems: PortalCanvasItem[] = [
id: "ppt",
zhTitle: "PPT 演示",
enTitle: "PPT",
- zhSummary: "先大纲后视觉,导出可编辑稿、PDF 和图片版",
- enSummary: "Outline-first decks with editable, PDF, and image exports",
+ zhSummary: "先大纲后视觉,导出 PDF 和图片版 PPT",
+ enSummary: "Outline-first decks with PDF and image-PPT exports",
image: "/examples/ppt/ppt1/01.png",
angle: 90,
accent: "#A8825C",
diff --git a/client/shared/chat/code-card.tsx b/client/shared/chat/code-card.tsx
index 89b34be..9e15c58 100644
--- a/client/shared/chat/code-card.tsx
+++ b/client/shared/chat/code-card.tsx
@@ -189,11 +189,20 @@ export function CodeCard({
</>
);
- const body = (
+ const preClassName =
+ "scrollbar-thin max-h-48 overflow-y-auto overflow-x-hidden whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed";
+
+ // Highlighting re-tokenises the whole block, so doing it on every streamed
+ // chunk costs more the longer the code gets. Plain text until it settles.
+ const body = isStreaming ? (
+ <pre className={preClassName} style={{ margin: 0, padding: 0, wordBreak: "break-word" }}>
+ {displayCode}
+ </pre>
+ ) : (
<Highlight theme={syntaxTheme} code={displayCode} language={prismLanguage}>
{({ style, tokens, getLineProps, getTokenProps }) => (
<pre
- className="scrollbar-thin max-h-48 overflow-y-auto overflow-x-hidden whitespace-pre-wrap break-words font-mono text-[11px] leading-relaxed"
+ className={preClassName}
style={{
...style,
backgroundColor: "transparent",
diff --git a/client/shared/i18n/messages.ts b/client/shared/i18n/messages.ts
index 22331bb..8cc2eb3 100644
--- a/client/shared/i18n/messages.ts
+++ b/client/shared/i18n/messages.ts
@@ -48,8 +48,8 @@ const messages = {
"empty.diagram.ex3": { zh: "把 RAG 检索增强生成的流程画成从左到右的步骤图", en: "Draw the RAG (retrieval-augmented generation) pipeline as left-to-right steps" },
"empty.cad.title": { zh: "从一句需求开始做方案", en: "Start a design from one sentence" },
"empty.cad.desc": {
- zh: "告诉助手户型、面积、风格和预算,它会生成分析图、二维图纸、效果图和物料清单。",
- en: "Tell the assistant the layout, size, style and budget, and it produces analysis boards, 2D drawings, renders and a material list.",
+ zh: "告诉助手户型、面积、风格和预算,它会生成分析图、2D 平面图、装修图纸和物料清单。",
+ en: "Tell the assistant the layout, size, style and budget, and it produces analysis boards, a 2D plan, renovation drawings and a material list.",
},
"empty.cad.ex1": { zh: "两室一厅 89㎡,现代简约风,预算 15 万,帮我出一套方案", en: "Two bedrooms, 89㎡, modern minimal, ¥150k budget — draft a full scheme" },
"empty.cad.ex2": { zh: "一间 30㎡ 的开放式办公室,需要 6 个工位和一个洽谈区", en: "A 30㎡ open office with six desks and a small meeting corner" },
diff --git a/client/workspaces/cad/CadWorkspace.tsx b/client/workspaces/cad/CadWorkspace.tsx
index 22cb072..2cb4494 100644
--- a/client/workspaces/cad/CadWorkspace.tsx
+++ b/client/workspaces/cad/CadWorkspace.tsx
@@ -35,6 +35,12 @@ const CAD_WORKSPACE_STORAGE_KEY = "CanvasAnvil-cad-state-v1";
const CAD_RENDERS_STORAGE_KEY = "CanvasAnvil-cad-renders-v1";
const CAD_ANALYSIS_IMAGES_STORAGE_KEY = "CanvasAnvil-cad-analysis-images-v1";
const CAD_CHAT_STORAGE_KEY = "chat_history_v2_cad";
+/**
+ * Image gateways sometimes accept a request and never answer. Without a limit
+ * that sheet spins forever and holds up the rest of its batch; with one it
+ * falls through to the retries below.
+ */
+const CAD_IMAGE_TIMEOUT_MS = 240_000;
/** What the model returns for a CAD image request; every field is unverified. */
type CadImagePrompt = { title?: unknown; prompt?: unknown };
@@ -580,7 +586,7 @@ export function CadWorkspace() {
const generateWithRetry = async (prompt: string, maxRetries: number, retryDelayMs: number) => {
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
try {
- const url = await generateImage({ prompt });
+ const url = await generateImage({ prompt }, AbortSignal.timeout(CAD_IMAGE_TIMEOUT_MS));
if (url) return url;
} catch (err) {
if (attempt >= maxRetries) {
@@ -704,7 +710,7 @@ export function CadWorkspace() {
const generateWithRetry = async (fullPrompt: string, maxRetries: number, retryDelayMs: number) => {
for (let attempt = 0; attempt <= maxRetries; attempt += 1) {
try {
- const url = await generateImage({ prompt: fullPrompt });
+ const url = await generateImage({ prompt: fullPrompt }, AbortSignal.timeout(CAD_IMAGE_TIMEOUT_MS));
if (url) return url;
} catch (err) {
if (attempt >= maxRetries) {
diff --git a/client/workspaces/diagram/chat/ChatMessageDisplay.tsx b/client/workspaces/diagram/chat/ChatMessageDisplay.tsx
index 88ee51c..66f280f 100644
--- a/client/workspaces/diagram/chat/ChatMessageDisplay.tsx
+++ b/client/workspaces/diagram/chat/ChatMessageDisplay.tsx
@@ -61,6 +61,9 @@ import {
import { convertToLegalXml, replaceNodes, validateMxCellStructure } from "@/workspaces/diagram/lib/drawio-xml"
import { CodeBlock } from "./code-block"
+/** Minimum gap between canvas redraws while a diagram's XML streams in. */
+const STREAM_PREVIEW_INTERVAL_MS = 400
+
// Tool part interface for type safety
interface ToolPartLike {
type: string
@@ -138,6 +141,7 @@ export function ChatMessageDisplay({
const messagesEndRef = useRef<HTMLDivElement>(null)
const previousXML = useRef<string>("")
const assembledXmlRef = useRef<string>("")
+ const lastStreamPreviewAtRef = useRef(0)
const processedToolCalls = processedToolCallsRef
const [expandedTools, setExpandedTools] = useState<Record<string, boolean>>(
{},
@@ -278,6 +282,18 @@ export function ChatMessageDisplay({
}, [editingMessageId])
useEffect(() => {
+ // Each preview is a full reload inside draw.io, so while the XML is
+ // still streaming in, redraw at most every STREAM_PREVIEW_INTERVAL_MS.
+ // "input-available" (the complete XML) always goes through.
+ const now = Date.now()
+ const streamPreviewDue =
+ now - lastStreamPreviewAtRef.current >= STREAM_PREVIEW_INTERVAL_MS
+ const previewStreaming = (xml: string) => {
+ if (!streamPreviewDue) return
+ lastStreamPreviewAtRef.current = now
+ handleDisplayChart(xml)
+ }
+
messages.forEach((message) => {
if (message.parts) {
message.parts.forEach((part) => {
@@ -286,16 +302,21 @@ export function ChatMessageDisplay({
const { toolCallId, state, input } = toolPart
if (state === "output-available") {
- setExpandedTools((prev) => ({
- ...prev,
- [toolCallId]: false,
- }))
+ // Returning prev when already collapsed skips a
+ // rerender for every finished tool in the history.
+ setExpandedTools((prev) =>
+ prev[toolCallId] === false
+ ? prev
+ : { ...prev, [toolCallId]: false },
+ )
}
if (part.type === "tool-display_diagram" && input?.xml) {
const xml = String(input.xml)
assembledXmlRef.current = xml
- if (state === "input-streaming" || state === "input-available") {
+ if (state === "input-streaming") {
+ previewStreaming(xml)
+ } else if (state === "input-available") {
handleDisplayChart(xml)
} else if (!processedToolCalls.current.has(toolCallId)) {
handleDisplayChart(xml)
@@ -305,7 +326,9 @@ export function ChatMessageDisplay({
if (part.type === "tool-append_diagram" && input?.xml) {
const combinedXml = `${assembledXmlRef.current}${String(input.xml)}`
- if (state === "input-streaming" || state === "input-available") {
+ if (state === "input-streaming") {
+ previewStreaming(combinedXml)
+ } else if (state === "input-available") {
handleDisplayChart(combinedXml)
} else if (!processedToolCalls.current.has(toolCallId)) {
assembledXmlRef.current = combinedXml
@@ -405,7 +428,13 @@ export function ChatMessageDisplay({
{input && isExpanded && (
<div className="px-4 py-3 border-t border-border/40 bg-muted/20">
{typeof input === "object" && input.xml ? (
- <CodeBlock code={input.xml} language="xml" onApply={applyCodeToDiagram} framed={false} />
+ <CodeBlock
+ code={input.xml}
+ language="xml"
+ onApply={applyCodeToDiagram}
+ framed={false}
+ isStreaming={state === "input-streaming"}
+ />
) : typeof input === "object" &&
input.operations &&
Array.isArray(input.operations) ? (
diff --git a/client/workspaces/diagram/chat/ChatPanel.tsx b/client/workspaces/diagram/chat/ChatPanel.tsx
index bb33864..29cc80e 100644
--- a/client/workspaces/diagram/chat/ChatPanel.tsx
+++ b/client/workspaces/diagram/chat/ChatPanel.tsx
@@ -221,6 +221,10 @@ export default function ChatPanel({
const chat: any = (useChat as any)({
api: "/api/chat",
+ // Without this every streamed token is its own render: the whole
+ // message list, the XML code block and the persistence effects below
+ // all rerun per token, and the page stutters while a reply streams.
+ experimental_throttle: 100,
onError: (error: unknown) => {
setIsParsingFiles(false)
console.error('[ChatPanel] useChat error:', error)
@@ -689,15 +693,18 @@ Please fix the XML issues. Ensure cell_id values exist in the current XML and th
}, 500)
}, [isDrawioReady, onDisplayChart])
- // Save messages to localStorage whenever they change
+ // Save messages to localStorage once a reply settles. Mid-stream saves
+ // would serialise the whole history (attachments included) on every
+ // update; the beforeunload handler below covers a reload mid-reply.
useEffect(() => {
if (!hasRestoredRef.current) return
+ if (status === "streaming" || status === "submitted") return
try {
localStorage.setItem(STORAGE_MESSAGES_KEY, JSON.stringify(messages))
} catch (error) {
console.error("Failed to save messages to localStorage:", error)
}
- }, [messages])
+ }, [messages, status])
// Save diagram XML to localStorage whenever it changes
useEffect(() => {
diff --git a/client/workspaces/ppt/PptWorkspace.tsx b/client/workspaces/ppt/PptWorkspace.tsx
index 9119997..01cac5b 100644
--- a/client/workspaces/ppt/PptWorkspace.tsx
+++ b/client/workspaces/ppt/PptWorkspace.tsx
@@ -46,7 +46,6 @@ export function PptWorkspace() {
return "start";
}
});
- const [pptCreationMode, setPptCreationMode] = useState<"idea" | "outline" | "beautify" | "image_transform">("idea");
const [pptExportReviewActive, setPptExportReviewActive] = useState(false);
const [chatHistory, setChatHistory] = useState<ChatMessage[]>([]);
@@ -64,9 +63,7 @@ export function PptWorkspace() {
const [isChatCollapsed, setIsChatCollapsed] = useState(false);
const chatPanelRef = useRef<PanelImperativeHandle | null>(null);
const showPptChat =
- (pptStage === "outline" || pptStage === "slides") &&
- pptCreationMode !== "image_transform" &&
- !pptExportReviewActive;
+ (pptStage === "outline" || pptStage === "slides") && !pptExportReviewActive;
const pptChatLocked = !showPptChat || !pptReady;
useEffect(() => {
@@ -239,7 +236,6 @@ export function PptWorkspace() {
setPptDraftSlides([]);
setPptReady(false);
setPptStage("start");
- setPptCreationMode("idea");
setPptExportReviewActive(false);
setChatHistory([]);
setAttachments([]);
@@ -282,7 +278,6 @@ export function PptWorkspace() {
onAddToChat={handleAddToChat}
onPptReadyChange={setPptReady}
onPptStageChange={setPptStage}
- onCreationModeChange={setPptCreationMode}
onExportReviewModeChange={setPptExportReviewActive}
incomingEdit={pptIncomingEdit}
onIncomingEditHandled={() => setPptIncomingEdit(null)}
diff --git a/client/workspaces/ppt/canvas/PptCanvas.tsx b/client/workspaces/ppt/canvas/PptCanvas.tsx
index 398eaa4..2c0381e 100644
--- a/client/workspaces/ppt/canvas/PptCanvas.tsx
+++ b/client/workspaces/ppt/canvas/PptCanvas.tsx
@@ -9,7 +9,6 @@ import { OutlineReview } from "./views/OutlineReview";
import { CreationStart } from "./views/CreationStart";
import { DeckView } from "./views/DeckView";
import {
- getOriginalSlideVersion as originalVersionOf,
getTextlessBackgroundVersion as textlessBackgroundOf,
getVisibleSlideVersions as getVisibleVersions,
resolveSlideVersion,
@@ -34,6 +33,7 @@ import { buildBeautifyInstruction } from "./lib/beautify-instruction";
import { describeRebuildEvent, type RebuildLogEntry } from "./lib/rebuild-log";
import { generateChatMessage } from '@/ai/client';
import {
+ PLAN_TIMEOUT_MS,
pptService,
PptPage,
type PptElement,
@@ -84,7 +84,6 @@ interface PptCanvasProps {
onAddToChat?: (json: string, name: string) => void;
onPptReadyChange?: (ready: boolean) => void;
onPptStageChange?: (stage: "start" | "outline" | "slides") => void;
- onCreationModeChange?: (mode: "idea" | "outline" | "beautify" | "image_transform") => void;
onExportReviewModeChange?: (active: boolean) => void;
incomingEdit?: { id: string; payload: string } | null;
onIncomingEditHandled?: (id: string) => void;
@@ -96,7 +95,6 @@ export function PptCanvas({
onAddToChat,
onPptReadyChange,
onPptStageChange,
- onCreationModeChange,
onExportReviewModeChange,
incomingEdit,
onIncomingEditHandled,
@@ -245,15 +243,11 @@ export function PptCanvas({
}
onPptStageChange?.("start");
}, [creationStep, onPptStageChange]);
- const inputs = useCreationInputs({
- initialState: initialPptState,
- onCreationModeChange,
- });
+ const inputs = useCreationInputs({ initialState: initialPptState });
const { creationMode, setCreationMode, ideaInput, outlineInput } = inputs;
const { setIdeaInput, setOutlineInput } = inputs;
const { setRequirement: setBeautifyRequirement, setUseTemplate: setBeautifyUseTemplate,
setFailures: setBeautifyFailures } = inputs.beautify;
- const { setFailures: setImageTransformFailures } = inputs.imageTransform;
const materials = useSlideMaterials({
localSlides,
setLocalSlides,
@@ -367,8 +361,7 @@ export function PptCanvas({
setCreationMode(
coreState?.creationMode === "idea" ||
coreState?.creationMode === "outline" ||
- coreState?.creationMode === "beautify" ||
- coreState?.creationMode === "image_transform"
+ coreState?.creationMode === "beautify"
? coreState.creationMode
: "idea",
);
@@ -384,12 +377,6 @@ export function PptCanvas({
allowedSlideIds,
),
);
- setImageTransformFailures(
- filterRecordByAllowedKeys(
- normalizePersistedStringMap(coreState?.imageTransformFailures, true),
- allowedSlideIds,
- ),
- );
setSlideMaterials(nextSlideMaterials);
latestWorkspaceUpdatedAtRef.current = Math.max(snapshotUpdatedAt, persistedUpdatedAt);
} catch (e) {
@@ -411,7 +398,6 @@ export function PptCanvas({
setBeautifyRequirement,
setBeautifyUseTemplate,
setBeautifyFailures,
- setImageTransformFailures,
]);
useEffect(() => {
@@ -435,7 +421,6 @@ export function PptCanvas({
beautifyRequirement: inputs.beautify.requirement,
beautifyUseTemplate: inputs.beautify.useTemplate,
beautifyFailures: inputs.beautify.failures,
- imageTransformFailures: inputs.imageTransform.failures,
updatedAt,
};
try {
@@ -457,7 +442,6 @@ export function PptCanvas({
beautifyRequirement: inputs.beautify.requirement,
beautifyUseTemplate: inputs.beautify.useTemplate,
beautifyFailures: inputs.beautify.failures,
- imageTransformFailures: inputs.imageTransform.failures,
updatedAt,
})
);
@@ -483,7 +467,6 @@ export function PptCanvas({
inputs.beautify.requirement,
inputs.beautify.useTemplate,
inputs.beautify.failures,
- inputs.imageTransform.failures,
isPersistenceHydrated,
]);
@@ -1168,7 +1151,6 @@ export function PptCanvas({
(slideId: string) => getVisibleVersions(slideId, versionState, originalVersionLabel),
[versionState, originalVersionLabel],
);
- const getOriginalSlideVersion = (slideId: string) => originalVersionOf(slideId, versionState);
const getTextlessBackgroundVersion = (slideId: string) => textlessBackgroundOf(slideId, versionState);
const getSlideImageUrl = (slideId: string) => getSlideVersionMeta(slideId).imageUrl;
const getSlideRenderLayer = useCallback((slideId: string) => {
@@ -1237,10 +1219,7 @@ export function PptCanvas({
const currentReviewLayer = currentSlide ? getSlideRenderLayer(currentSlide.id) : undefined;
const failedBeautifyCount = activeSlides.reduce((n, s) => n + (inputs.beautify.failures[s.id] ? 1 : 0), 0);
- const failedImageTransformCount = activeSlides.reduce((n, s) => n + (inputs.imageTransform.failures[s.id] ? 1 : 0), 0);
- const currentSlideFailure = currentSlide
- ? (creationMode === "image_transform" ? inputs.imageTransform.failures[currentSlide.id] : inputs.beautify.failures[currentSlide.id])
- : "";
+ const currentSlideFailure = currentSlide ? inputs.beautify.failures[currentSlide.id] : "";
const formatImageVersionLabel = (version: SlideImageVersion, index: number) => {
if (version.type === "derived_textless") {
@@ -1430,97 +1409,6 @@ export function PptCanvas({
});
}, [tr]);
- const extractImageDeckPages = async (file: File) => {
- if (isPdfFile(file)) {
- return await extractPdfPagesAsImages(file, reportPdfParseProgress);
- }
- throw new Error(tr("仅支持 PDF 文件。", "Only PDF files are supported."));
- };
-
-
-
-
- const createImageTransformSlideVersion = async (slide: SlideData, sourceUrl: string) => {
- const persistedSourceUrl = await persistImageUrlIfNeeded(sourceUrl);
- const versionId = pushImageVersion(
- slide.id,
- persistedSourceUrl,
- "generated",
- tr("原始上传页", "Original uploaded page"),
- );
- setImageTransformFailures((prev) => {
- if (!prev[slide.id]) return prev;
- const next = { ...prev };
- delete next[slide.id];
- return next;
- });
- return versionId;
-
- };
-
- const handleStartImageTransform = async () => {
- const file = inputs.imageTransform.file;
- if (!file) return;
-
- resetGenerationState();
- setBeautifyFailures({});
- setImageTransformFailures({});
- dispatchCreation({ type: "writing", message: tr("正在解析文件...", "Parsing file...") });
-
- try {
- const pageImages = await extractImageDeckPages(file);
- if (pageImages.length === 0) {
- alert(tr("无法解析页面图片,请确认文件格式。", "Failed to extract slide images. Please check the file format."));
- dispatchCreation({ type: "failed" });
- return;
- }
-
- const slides: SlideData[] = pageImages.map((_, i) => ({
- id: `slide-${i + 1}`,
- title: tr(`第 ${i + 1} 页`, `Slide ${i + 1}`),
- content: [],
- description: "",
- }));
-
- setLocalSlides(slides);
- dispatchCreation({ type: "rendering" });
-
- const progressTracker = createTwoStageSlideProgressTracker(
- slides.length,
- "正在创建原始版本...",
- "Importing slide images...",
- "正在重建可编辑文字层...",
- "Finishing import...",
- );
- progressTracker.start();
-
- const tasks = slides.map((slide, index) => async () => {
- let baseReady = false;
- try {
- progressTracker.markBaseReady();
- baseReady = true;
- await createImageTransformSlideVersion(slide, pageImages[index]);
- } catch (error) {
- setImageTransformFailures((prev) => ({
- ...prev,
- [slide.id]: getErrorMessage(error),
- }));
- } finally {
- progressTracker.markSlideFinished(baseReady);
- }
- });
-
- await runInParallel(tasks, MODEL_CONCURRENCY);
- dispatchCreation({ type: "finished" });
- onPptReadyChange?.(true);
- } catch (error) {
- console.error("Image PPT transform failed", error);
- alert(getErrorMessage(error));
- dispatchCreation({ type: "failed" });
- }
- };
-
-
const getErrorMessage = useCallback(
(error: unknown) => errorText(error) || tr("未知错误", "Unknown error"),
[tr],
@@ -1798,7 +1686,10 @@ export function PptCanvas({
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(
+ `生成大纲超时或被中断(${PLAN_TIMEOUT_MS / 1000}s)。请检查网络和模型可用性后重试。`,
+ `Outline generation timed out or was interrupted (${PLAN_TIMEOUT_MS / 1000}s). Check network/model availability and retry.`,
+ )
: e instanceof Error
? e.message
: tr("生成大纲失败,请重试", "Failed to generate outline. Please retry.");
@@ -1872,12 +1763,6 @@ export function PptCanvas({
setIsGeneratingImage(true);
try {
- if (creationMode === "image_transform") {
- const originalVersion = getOriginalSlideVersion(currentSlide.id);
- if (!originalVersion?.url) return;
- await createImageTransformSlideVersion(currentSlide, originalVersion.url);
- return;
- }
let imageUrl: string | null = null;
const pages: PptPage[] = localSlides.map(s => ({
id: s.id,
@@ -2221,9 +2106,7 @@ export function PptCanvas({
setBeautifyRequirement("");
setBeautifyUseTemplate(false);
inputs.beautify.setFile(null);
- inputs.imageTransform.setFile(null);
setBeautifyFailures({});
- setImageTransformFailures({});
inputs.reference.setUploadFiles([]);
setSlideMaterials({});
materials.picker.close();
@@ -2306,12 +2189,6 @@ export function PptCanvas({
delete next[slideId];
return next;
});
- setImageTransformFailures((prev) => {
- if (!(slideId in prev)) return prev;
- const next = { ...prev };
- delete next[slideId];
- return next;
- });
setSlideMaterials((prev) => {
const next = { ...prev };
delete next[slideId];
@@ -2330,7 +2207,6 @@ export function PptCanvas({
onGenerateOutline={handleGenerateOutline}
onLoadOutline={handleLoadOutline}
onStartBeautify={handleStartBeautify}
- onStartImageTransform={handleStartImageTransform}
/>
);
}
@@ -2397,7 +2273,6 @@ export function PptCanvas({
status={{
currentSlideFailure,
failedBeautifyCount,
- failedImageTransformCount,
isApplyingEdits,
isGeneratingImage,
exportProgress: editableExportProgress,
diff --git a/client/workspaces/ppt/canvas/hooks/use-creation-inputs.ts b/client/workspaces/ppt/canvas/hooks/use-creation-inputs.ts
index 600174b..7ad616b 100644
--- a/client/workspaces/ppt/canvas/hooks/use-creation-inputs.ts
+++ b/client/workspaces/ppt/canvas/hooks/use-creation-inputs.ts
@@ -1,4 +1,4 @@
-import { useEffect, useRef, useState } from "react";
+import { useRef, useState } from "react";
import { useFileProcessor } from "@/shared/files/use-file-processor";
import type { CreationMode, ReferenceFile } from "@/workspaces/ppt/canvas/types";
@@ -12,12 +12,10 @@ interface PersistedInputs {
beautifyRequirement?: unknown;
beautifyUseTemplate?: unknown;
beautifyFailures?: unknown;
- imageTransformFailures?: unknown;
}
export interface CreationInputsOptions {
initialState: PersistedInputs | undefined;
- onCreationModeChange?: (mode: CreationMode) => void;
}
const readString = (v: unknown) => (typeof v === "string" ? v : "");
@@ -34,22 +32,20 @@ function readFailureMap(v: unknown): Record<string, string> {
/**
* Everything the user supplies before a deck exists: which flow they picked,
- * what they typed, the file they are beautifying or converting, and the
+ * what they typed, the file they are beautifying, and the
* reference documents whose text and figures feed the prompt.
*
* The per-slide failure maps live here too, because they belong to the run the
* inputs started and are cleared when a new one begins.
*/
-export function useCreationInputs({ initialState, onCreationModeChange }: CreationInputsOptions) {
+export function useCreationInputs({ initialState }: CreationInputsOptions) {
const [creationMode, setCreationMode] = useState<CreationMode>(() => {
const v = initialState?.creationMode;
- return v === "idea" || v === "outline" || v === "beautify" || v === "image_transform" ? v : "idea";
+ // Anything else -- including the removed "image_transform" flow a saved
+ // workspace may still name -- falls back to the default flow.
+ return v === "idea" || v === "outline" || v === "beautify" ? v : "idea";
});
- useEffect(() => {
- onCreationModeChange?.(creationMode);
- }, [creationMode, onCreationModeChange]);
-
const [ideaInput, setIdeaInput] = useState(() => readString(initialState?.ideaInput));
const [outlineInput, setOutlineInput] = useState(() => readString(initialState?.outlineInput));
const [beautifyRequirement, setBeautifyRequirement] = useState(() =>
@@ -60,15 +56,11 @@ export function useCreationInputs({ initialState, onCreationModeChange }: Creati
);
const [beautifyFile, setBeautifyFile] = useState<File | null>(null);
- const [imageTransformFile, setImageTransformFile] = useState<File | null>(null);
// Which slides failed in the last run, so the user can retry just those.
const [beautifyFailures, setBeautifyFailures] = useState<Record<string, string>>(() =>
readFailureMap(initialState?.beautifyFailures),
);
- const [imageTransformFailures, setImageTransformFailures] = useState<Record<string, string>>(() =>
- readFailureMap(initialState?.imageTransformFailures),
- );
const {
files: uploadFiles,
@@ -83,7 +75,6 @@ export function useCreationInputs({ initialState, onCreationModeChange }: Creati
const referenceInputRef = useRef<HTMLInputElement | null>(null);
const beautifyInputRef = useRef<HTMLInputElement | null>(null);
- const imageTransformInputRef = useRef<HTMLInputElement | null>(null);
const isParsing = Array.from(pdfData.values()).some((x) => x.isExtracting);
@@ -116,12 +107,6 @@ export function useCreationInputs({ initialState, onCreationModeChange }: Creati
setBeautifyFile(file);
};
- const handleImageTransformInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0] || null;
- e.target.value = "";
- setImageTransformFile(file);
- };
-
const openPreview = (file: ReferenceFile) => {
setPreviewFile(file);
setPreviewOpen(true);
@@ -146,14 +131,6 @@ export function useCreationInputs({ initialState, onCreationModeChange }: Creati
failures: beautifyFailures,
setFailures: setBeautifyFailures,
},
- imageTransform: {
- file: imageTransformFile,
- setFile: setImageTransformFile,
- inputRef: imageTransformInputRef,
- onInputChange: handleImageTransformInputChange,
- failures: imageTransformFailures,
- setFailures: setImageTransformFailures,
- },
reference: {
files: referenceFiles,
uploadFiles,
diff --git a/client/workspaces/ppt/canvas/types.ts b/client/workspaces/ppt/canvas/types.ts
index 1c7581e..07b8860 100644
--- a/client/workspaces/ppt/canvas/types.ts
+++ b/client/workspaces/ppt/canvas/types.ts
@@ -37,7 +37,7 @@ export interface PptData {
}
export type CreationStep = 'idle' | 'input' | 'outline' | 'generating_content' | 'generating_images' | 'done';
-export type CreationMode = 'idea' | 'outline' | 'beautify' | 'image_transform';
+export type CreationMode = 'idea' | 'outline' | 'beautify';
export type ReferenceFile = { id: string; filename: string; content: string; charCount: number };
diff --git a/client/workspaces/ppt/canvas/views/CreationStart.tsx b/client/workspaces/ppt/canvas/views/CreationStart.tsx
index 0072c51..829067e 100644
--- a/client/workspaces/ppt/canvas/views/CreationStart.tsx
+++ b/client/workspaces/ppt/canvas/views/CreationStart.tsx
@@ -1,10 +1,9 @@
import { motion } from "motion/react";
import { SPRING } from "@/shared/motion";
-import { FileText, Lightbulb, Loader2, Presentation, Sparkles, Upload } from "lucide-react";
+import { FileText, Lightbulb, Loader2, Sparkles, Upload } from "lucide-react";
import { Button } from "@/shared/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/ui/dialog";
import { Textarea } from "@/shared/ui/textarea";
-import { isPdfFile } from "@/workspaces/ppt/canvas/lib/deck-source";
import type { CreationProgress } from "@/workspaces/ppt/canvas/lib/creation-machine";
import type { useCreationInputs } from "@/workspaces/ppt/canvas/hooks/use-creation-inputs";
import type { useTemplateLibrary } from "@/workspaces/ppt/canvas/hooks/use-template-library";
@@ -18,12 +17,11 @@ interface CreationStartProps {
onGenerateOutline: () => void;
onLoadOutline: () => void;
onStartBeautify: () => void;
- onStartImageTransform: () => void;
}
/**
* The first screen: pick a template, pick a flow, and give it something to
- * work from. Four flows share it because they differ only in what they take
+ * work from. Three flows share it because they differ only in what they take
* as input -- an idea, an outline, or a PDF to rework.
*/
export function CreationStart({
@@ -34,14 +32,12 @@ export function CreationStart({
onGenerateOutline,
onLoadOutline,
onStartBeautify,
- onStartImageTransform,
}: CreationStartProps) {
const { creationMode } = inputs;
const tabs = [
{ id: 'idea', label: tr('想法', 'Idea') },
{ id: 'outline', label: tr('大纲', 'Outline') },
{ id: 'beautify', label: tr('PPT美化', 'Beautify') },
- { id: 'image_transform', label: tr('图片PPT转化', 'Image PPT Transform') },
];
const modeCopy = (() => {
if (creationMode === "outline") {
@@ -62,12 +58,6 @@ export function CreationStart({
)
};
}
- if (creationMode === "image_transform") {
- return {
- hint: tr("上传 PDF,系统会将每一页导入为一张图片幻灯片。", "Upload a PDF and each page is imported as an image slide."),
- placeholder: "",
- };
- }
return {
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")
@@ -76,11 +66,6 @@ export function CreationStart({
/** Why the start button is disabled, when it is for a reason the user can fix. */
const blockedReason = (() => {
if (creationMode === "beautify") return inputs.beautify.file ? "" : tr("先上传要美化的 PDF", "Upload the PDF to beautify first");
- if (creationMode === "image_transform") {
- const file = inputs.imageTransform.file;
- if (!file) return tr("先上传要转化的 PDF", "Upload the PDF to transform first");
- return isPdfFile(file) ? "" : tr("只支持 PDF 文件", "Only PDF files are supported");
- }
if (inputs.reference.isParsing) return tr("参考资料解析中,请稍候…", "Still reading your reference files…");
if (creationMode === "idea") return inputs.ideaInput.trim() ? "" : tr("先在上面写下你的想法", "Write your idea above first");
return inputs.outlineInput.trim() ? "" : tr("先在上面粘贴大纲", "Paste your outline above first");
@@ -143,7 +128,7 @@ export function CreationStart({
className="space-y-3"
>
<div className="flex items-center gap-2 text-sm text-foreground/80">
- {creationMode === "beautify" ? <Sparkles className="w-4 h-4 text-primary-strong" /> : creationMode === "image_transform" ? <Presentation className="w-4 h-4 text-primary-strong" /> : <Lightbulb className="w-4 h-4 text-primary-strong" />}
+ {creationMode === "beautify" ? <Sparkles className="w-4 h-4 text-primary-strong" /> : <Lightbulb className="w-4 h-4 text-primary-strong" />}
<span>{modeCopy.hint}</span>
</div>
@@ -197,39 +182,6 @@ export function CreationStart({
placeholder={modeCopy.placeholder}
/>
</div>
- ) : creationMode === "image_transform" ? (
- <div className="space-y-3">
- <input
- ref={inputs.imageTransform.inputRef}
- type="file"
- accept=".pdf,application/pdf"
- className="hidden"
- onChange={inputs.imageTransform.onInputChange}
- />
-
- <div className="flex items-center justify-between gap-3 rounded-xl border border-border bg-sunken px-4 py-3">
- <div className="min-w-0">
- <div className="text-sm font-medium text-foreground">{tr("上传 PDF", "Upload PDF")}</div>
- <div className="text-xs text-muted-foreground truncate">
- {inputs.imageTransform.file ? inputs.imageTransform.file.name : tr("未选择文件", "No file selected")}
- </div>
- </div>
- <Button
- type="button"
- variant="outline"
- className="shrink-0"
- onClick={() => inputs.imageTransform.inputRef.current?.click()}
- >
- <Upload className="w-4 h-4 mr-2" />
- {tr("选择文件", "Choose")}
- </Button>
- </div>
-
- <div className="rounded-xl border border-border bg-sunken px-4 py-3 text-xs text-muted-foreground leading-6">
- <div>{tr("处理结果:", "Output:")}</div>
- <div>{tr("系统会把 PDF 每一页导入为图片幻灯片。", "The system imports each PDF page as an image slide.")}</div>
- </div>
- </div>
) : (
<>
<div className="relative">
@@ -310,8 +262,8 @@ export function CreationStart({
</div>
<Button
- onClick={creationMode === "beautify" ? onStartBeautify : creationMode === "image_transform" ? onStartImageTransform : creationMode === "idea" ? onGenerateOutline : onLoadOutline}
- disabled={Boolean(progress.message) || (creationMode === "beautify" ? !inputs.beautify.file : creationMode === "image_transform" ? !inputs.imageTransform.file || !isPdfFile(inputs.imageTransform.file) : inputs.reference.isParsing || (creationMode === "idea" ? !inputs.ideaInput.trim() : !inputs.outlineInput.trim()))}
+ onClick={creationMode === "beautify" ? onStartBeautify : creationMode === "idea" ? onGenerateOutline : onLoadOutline}
+ disabled={Boolean(progress.message) || (creationMode === "beautify" ? !inputs.beautify.file : inputs.reference.isParsing || (creationMode === "idea" ? !inputs.ideaInput.trim() : !inputs.outlineInput.trim()))}
size="lg"
// The blue-to-indigo gradient was the loudest element on
// the screen; the solid variant carries the same weight
@@ -322,7 +274,7 @@ export function CreationStart({
`[&_svg:not([class*='size-'])]:size-4` rule outranks a
plain width/height pair, so these icons were 16px. */}
{progress.message ? <Loader2 className="size-5 mr-2 animate-spin" /> : <Sparkles className="size-5 mr-2" />}
- {progress.message || (creationMode === "beautify" ? tr("开始渲染", "Start rendering") : creationMode === "image_transform" ? tr("开始转化", "Start transform") : creationMode === "idea" ? tr("开始生成大纲", "Generate outline") : tr("载入大纲", "Load outline"))}
+ {progress.message || (creationMode === "beautify" ? tr("开始渲染", "Start rendering") : creationMode === "idea" ? tr("开始生成大纲", "Generate outline") : tr("载入大纲", "Load outline"))}
</Button>
{/* Says why the button is unavailable instead of leaving
the user to guess. */}
@@ -333,18 +285,16 @@ export function CreationStart({
{/* Below the button, at the user's request: the template is
a refinement, not the first decision. The header carries
the current selection so it stays visible from up there. */}
- {creationMode !== "image_transform" ? (
- <TemplatePicker
- templateLibrary={templateLibrary}
- tr={tr}
- heading={
- <label className="text-sm font-semibold text-foreground flex items-center gap-2">
- <span className="w-6 h-6 rounded-full bg-primary/12 text-primary-strong text-xs flex items-center justify-center font-bold">2</span>
- {tr("选择或上传参考模板", "Choose or upload a reference template")}
- </label>
- }
- />
- ) : null}
+ <TemplatePicker
+ templateLibrary={templateLibrary}
+ tr={tr}
+ heading={
+ <label className="text-sm font-semibold text-foreground flex items-center gap-2">
+ <span className="w-6 h-6 rounded-full bg-primary/12 text-primary-strong text-xs flex items-center justify-center font-bold">2</span>
+ {tr("选择或上传参考模板", "Choose or upload a reference template")}
+ </label>
+ }
+ />
</div>
<Dialog open={inputs.reference.previewOpen} onOpenChange={inputs.reference.setPreviewOpen}>
diff --git a/client/workspaces/ppt/canvas/views/DeckView.tsx b/client/workspaces/ppt/canvas/views/DeckView.tsx
index ff30a31..7b6268f 100644
--- a/client/workspaces/ppt/canvas/views/DeckView.tsx
+++ b/client/workspaces/ppt/canvas/views/DeckView.tsx
@@ -108,7 +108,6 @@ interface DeckViewProps {
status: {
currentSlideFailure: string | undefined;
failedBeautifyCount: number;
- failedImageTransformCount: number;
isApplyingEdits: boolean;
isGeneratingImage: boolean;
/** Which slide the editable export is on, while it runs. */
@@ -275,11 +274,6 @@ export function DeckView({
{tr(`失败 ${status.failedBeautifyCount} 页`, `${status.failedBeautifyCount} failed`)}
</span>
) : null}
- {creationMode === "image_transform" && status.failedImageTransformCount > 0 ? (
- <span className="rounded border border-destructive/25 bg-destructive/[0.08] px-2 py-1 text-destructive">
- {tr(`转化失败 ${status.failedImageTransformCount} 页`, `${status.failedImageTransformCount} failed`)}
- </span>
- ) : null}
<span>{deck.slides.length > 0 ? tr(`第 ${deck.currentIndex + 1} / ${deck.slides.length} 页`, `Slide ${deck.currentIndex + 1} / ${deck.slides.length}`) : tr("空文档", "Empty")}</span>
</div>
</div>
@@ -290,7 +284,7 @@ export function DeckView({
<div className="w-64 bg-sunken border-r border-border overflow-y-auto p-4 space-y-4">
{deck.slides.map((slide, index) => {
const hasGeneratedImage = deck.getBackgroundUrl(slide.id);
- const slideFailure = creationMode === "image_transform" ? inputs.imageTransform.failures[slide.id] : inputs.beautify.failures[slide.id];
+ const slideFailure = inputs.beautify.failures[slide.id];
return (
<ContextMenu key={slide.id || index}>
<ContextMenuTrigger asChild>
@@ -303,22 +297,20 @@ export function DeckView({
: 'border-transparent hover:border-border hover:-translate-y-0.5 bg-card shadow-xs'
}`}
>
- {creationMode !== "image_transform" ? (
- <div
- className="absolute top-1 left-1 z-20"
- onClick={(e) => e.stopPropagation()}
+ <div
+ className="absolute top-1 left-1 z-20"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <Button
+ size="sm"
+ variant="destructive"
+ className="h-6 px-2 text-[10px] gap-1 shadow-sm opacity-0 group-hover:opacity-100 transition-opacity"
+ onClick={() => actions.addSlideToChat(slide)}
>
- <Button
- size="sm"
- variant="destructive"
- className="h-6 px-2 text-[10px] gap-1 shadow-sm opacity-0 group-hover:opacity-100 transition-opacity"
- onClick={() => actions.addSlideToChat(slide)}
- >
- <Presentation className="w-3 h-3" />
- {tr("加入对话", "Add to chat")}
- </Button>
- </div>
- ) : null}
+ <Presentation className="w-3 h-3" />
+ {tr("加入对话", "Add to chat")}
+ </Button>
+ </div>
{/* Thumbnail Preview */}
{hasGeneratedImage ? (
// The scene lays out at a fixed 240x135 while this slot is
@@ -349,19 +341,17 @@ export function DeckView({
className="absolute top-1 right-1 bg-destructive/90 text-destructive-foreground text-[10px] px-1.5 py-0.5 rounded-sm max-w-[85%] truncate"
title={slideFailure}
>
- {creationMode === "image_transform" ? tr("转化失败", "Transform failed") : tr("美化失败", "Beautify failed")}
+ {tr("美化失败", "Beautify failed")}
</div>
) : null}
</div>
</ContextMenuTrigger>
- {creationMode !== "image_transform" ? (
- <ContextMenuContent>
- <ContextMenuItem onClick={() => actions.addSlideToChat(slide)} className="gap-2">
- <MessageSquarePlus className="w-4 h-4" />
- <span>{tr("把此页添加到对话", "Add this slide to chat")}</span>
- </ContextMenuItem>
- </ContextMenuContent>
- ) : null}
+ <ContextMenuContent>
+ <ContextMenuItem onClick={() => actions.addSlideToChat(slide)} className="gap-2">
+ <MessageSquarePlus className="w-4 h-4" />
+ <span>{tr("把此页添加到对话", "Add this slide to chat")}</span>
+ </ContextMenuItem>
+ </ContextMenuContent>
</ContextMenu>
)})}
@@ -431,7 +421,7 @@ export function DeckView({
</div>
{status.currentSlideFailure ? (
<div className="absolute top-16 left-4 z-30 max-w-[520px] rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-xs text-destructive shadow-sm">
- <span className="font-medium mr-1">{creationMode === "image_transform" ? tr("本页转化失败:", "Slide transform failed:") : tr("本页美化失败:", "Slide beautify failed:")}</span>
+ <span className="font-medium mr-1">{tr("本页美化失败:", "Slide beautify failed:")}</span>
<span>{status.currentSlideFailure}</span>
</div>
) : null}
@@ -493,14 +483,12 @@ export function DeckView({
)}
</div>
</ContextMenuTrigger>
- {creationMode !== "image_transform" ? (
- <ContextMenuContent>
- <ContextMenuItem onClick={() => deck.currentSlide && actions.addSlideToChat(deck.currentSlide)} className="gap-2">
- <MessageSquarePlus className="w-4 h-4" />
- <span>{tr("把此页添加到对话", "Add this slide to the chat")}</span>
- </ContextMenuItem>
- </ContextMenuContent>
- ) : null}
+ <ContextMenuContent>
+ <ContextMenuItem onClick={() => deck.currentSlide && actions.addSlideToChat(deck.currentSlide)} className="gap-2">
+ <MessageSquarePlus className="w-4 h-4" />
+ <span>{tr("把此页添加到对话", "Add this slide to the chat")}</span>
+ </ContextMenuItem>
+ </ContextMenuContent>
</ContextMenu>
) : (
<div className="text-muted-foreground flex flex-col items-center">
diff --git a/client/workspaces/ppt/lib/ppt-service.ts b/client/workspaces/ppt/lib/ppt-service.ts
index 4a3dad9..cde7d1f 100644
--- a/client/workspaces/ppt/lib/ppt-service.ts
+++ b/client/workspaces/ppt/lib/ppt-service.ts
@@ -1003,6 +1003,22 @@ const outlineTemplateRule = (hasTemplate: boolean) =>
? "\n5. description must stay inside the template image's colour scheme and art style, and must never describe a look that contradicts it.\n6. description must not reproduce the template's layout -- where its title, text blocks, cards or pictures sit; vary the layout to fit each slide's content."
: "";
+/**
+ * A whole-deck plan is one long JSON answer (every slide's bullets, notes and
+ * image description), sent with the template image when there is one; slower
+ * models need well over two minutes for an eight-slide deck.
+ */
+export const PLAN_TIMEOUT_MS = 300_000;
+
+/**
+ * Image gateways sometimes accept a request and never answer. Without a limit
+ * that slide spins forever and so does the whole deck's progress bar; with one
+ * it gets one more try and then fails, where "re-render this slide" can pick
+ * it up.
+ */
+export const SLIDE_IMAGE_TIMEOUT_MS = 240_000;
+const SLIDE_IMAGE_ATTEMPTS = 2;
+
export const pptService = {
// A1. PlanFromIdeaAgent
@@ -1028,7 +1044,7 @@ export const pptService = {
const response = hasTemplate
? await generateVisionChatMessage(PPT_OUTLINE_SYSTEM, prompt, [templateImage], undefined, {
- timeoutMs: 120000,
+ timeoutMs: PLAN_TIMEOUT_MS,
})
: await generateChatMessage(
[
@@ -1036,7 +1052,7 @@ export const pptService = {
{ role: "user", content: prompt },
],
undefined,
- { timeoutMs: 120000 },
+ { timeoutMs: PLAN_TIMEOUT_MS },
);
try {
@@ -1078,7 +1094,7 @@ export const pptService = {
});
const response = hasTemplate
? await generateVisionChatMessage(PPT_OUTLINE_SYSTEM, prompt, [templateImage], undefined, {
- timeoutMs: 120000,
+ timeoutMs: PLAN_TIMEOUT_MS,
})
: await generateChatMessage(
[
@@ -1086,7 +1102,7 @@ export const pptService = {
{ role: "user", content: prompt },
],
undefined,
- { timeoutMs: 120000 },
+ { timeoutMs: PLAN_TIMEOUT_MS },
);
try {
const parsed = parseJsonLoose(response);
@@ -1200,13 +1216,27 @@ export const pptService = {
? normalizedAdditional.map((x) => String(x?.url || "")).filter(Boolean)
: [];
- const imageUrl = await generateImage({
- prompt,
- referenceImageUrl: templateImageUrl || undefined,
- additionalReferenceImageUrls,
- });
- if (!imageUrl) throw new Error("Slide image generation returned no image.");
- return imageUrl;
+ let lastError: unknown;
+ for (let attempt = 1; attempt <= SLIDE_IMAGE_ATTEMPTS; attempt++) {
+ try {
+ const imageUrl = await generateImage(
+ {
+ prompt,
+ referenceImageUrl: templateImageUrl || undefined,
+ additionalReferenceImageUrls,
+ },
+ AbortSignal.timeout(SLIDE_IMAGE_TIMEOUT_MS),
+ );
+ if (!imageUrl) throw new Error("Slide image generation returned no image.");
+ return imageUrl;
+ } catch (error) {
+ lastError = error;
+ // Only a stalled request is worth repeating; a rejected one would fail the same way again.
+ const name = (error as { name?: string })?.name;
+ if (name !== "TimeoutError" && name !== "AbortError") break;
+ }
+ }
+ throw lastError;
},
/**
diff --git a/public/svg-editor.html b/public/svg-editor.html
index 7aa8357..05f3f15 100644
--- a/public/svg-editor.html
+++ b/public/svg-editor.html
@@ -7,12 +7,23 @@
<base href="/vendor/svgedit/" />
<link rel="stylesheet" href="/vendor/svgedit/svgedit.css" />
<style>
+ /*
+ * Lighter work area and rulers to sit with the rest of the app. The toolbars
+ * stay mid-grey: svgedit's tool icons are drawn in white.
+ */
+ :root {
+ --main-bg-color: #868e92;
+ --icon-bg-color: #868e92;
+ --canvas-bg-color: #e9edf0;
+ --ruler-color: #dfe4e8;
+ --input-color: #f4f6f8;
+ }
html, body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
- background: #5f6467;
+ background: #e9edf0;
}
#svgedit-container {
width: 100vw;
@@ -43,6 +54,13 @@
extPath: "/vendor/svgedit/extensions"
});
+ // svgedit's storage extension asks (in English) whether to keep preferences
+ // and content locally the first time it opens. CanvasAnvil keeps the plan
+ // itself, so answer "preferences only" up front instead of interrupting.
+ if (!/(?:^|;\s*)svgeditstore=/.test(document.cookie)) {
+ document.cookie = "svgeditstore=prefsOnly; path=/; max-age=31536000";
+ }
+
editor.init();
const origin = window.location.origin;
@@ -130,24 +148,43 @@
return /^<svg[\s/>]/i.test(raw) ? raw : "";
};
+ // Loading straight into the canvas skips the editor's own resize, so the
+ // drawing would sit at 100% in a corner; resize the work area and zoom the
+ // whole sheet into view instead.
+ const fitToView = () => {
+ try {
+ editor.updateCanvas?.(true);
+ editor.zoomChanged?.(window, "canvas");
+ } catch {
+ // An editor that cannot zoom still shows the drawing, just not framed.
+ }
+ };
+
const loadSvg = async (svg) => {
const text = normalizeIncomingSvg(svg);
if (!text) return false;
try {
const ok = editor?.svgCanvas?.setSvgString?.(text);
- if (ok !== false) return true;
+ if (ok !== false) {
+ fitToView();
+ return true;
+ }
} catch {
}
try {
const ok = editor?.svgCanvas?.importSvgString?.(text);
- if (ok !== false) return true;
+ if (ok !== false) {
+ fitToView();
+ return true;
+ }
} catch {
}
try {
await editor.loadFromString(text, { noAlert: true });
+ fitToView();
return true;
} catch (e) {
console.error("Failed to load SVG", e);
diff --git a/vite.config.ts b/vite.config.ts
index 4dbf97a..95b155a 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -25,7 +25,13 @@ function localApiPlugin(): Plugin {
}
export default defineConfig({
- server: { host: "0.0.0.0", port: 8001 },
+ server: {
+ host: "0.0.0.0",
+ port: 8001,
+ // Tutorial recordings write tens of thousands of frames here; watching
+ // them stalls the dev server.
+ watch: { ignored: ["**/tools/video/out/**"] },
+ },
preview: { host: "0.0.0.0", port: 8001 },
resolve: {
alias: {