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.

refactor(chat): extract the shared chat plumbing out of both panels

codingFeng1010b794a637605
diff --git a/src/shared/chat/assistant-stream.ts b/src/shared/chat/assistant-stream.ts
new file mode 100644
index 0000000..bc5de5d
--- /dev/null
+++ b/src/shared/chat/assistant-stream.ts
@@ -0,0 +1,78 @@
+import type { Dispatch, SetStateAction } from "react"
+import type { ChatMessage } from "@/ai/types"
+
+/**
+ * Coalesces streamed assistant chunks into one repaint per frame.
+ *
+ * The model emits far faster than React can usefully re-render a long
+ * message; without this the panel spends its time reconciling text nobody
+ * saw. Only the newest chunk survives a frame, and `flush` guarantees the
+ * final one lands even if the stream ends mid-frame.
+ */
+
+function scheduleFrame(callback: () => void): number {
+ if (typeof requestAnimationFrame === "function") return requestAnimationFrame(callback)
+ if (typeof window !== "undefined") return window.setTimeout(callback, 16)
+ return 0
+}
+
+function cancelFrame(id: number) {
+ if (!id) return
+ if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(id)
+ else if (typeof window !== "undefined") window.clearTimeout(id)
+}
+
+export interface AssistantUpdater {
+ /** Records the newest full text; repaints at most once per frame. */
+ push: (content: string) => void
+ /** Repaints immediately with whatever was last pushed. */
+ flush: () => void
+}
+
+/**
+ * Replaces the trailing assistant turn, or appends one if the last turn was
+ * the user's. Use directly for a one-shot status line; use
+ * {@link createAssistantUpdater} for a stream.
+ *
+ * @param sanitize strips the workspace's tool payloads out of what the user sees
+ */
+export function writeLastAssistant(
+ setMessages: Dispatch<SetStateAction<ChatMessage[]>>,
+ sanitize: (content: string) => string,
+ content: string,
+) {
+ const display = sanitize(content)
+ setMessages((prev) => {
+ const last = prev[prev.length - 1]
+ const message: ChatMessage = { role: "assistant", content: display }
+ return last?.role === "assistant" ? [...prev.slice(0, -1), message] : [...prev, message]
+ })
+}
+
+export function createAssistantUpdater(
+ setMessages: Dispatch<SetStateAction<ChatMessage[]>>,
+ sanitize: (content: string) => string,
+): AssistantUpdater {
+ const write = (content: string) => writeLastAssistant(setMessages, sanitize, content)
+
+ let latest = ""
+ let frameId: number | null = null
+
+ return {
+ push: (content: string) => {
+ latest = content
+ if (frameId !== null) return
+ frameId = scheduleFrame(() => {
+ frameId = null
+ write(latest)
+ })
+ },
+ flush: () => {
+ if (frameId !== null) {
+ cancelFrame(frameId)
+ frameId = null
+ }
+ write(latest)
+ },
+ }
+}
diff --git a/src/shared/chat/bom-table.ts b/src/shared/chat/bom-table.ts
new file mode 100644
index 0000000..05ee222
--- /dev/null
+++ b/src/shared/chat/bom-table.ts
@@ -0,0 +1,44 @@
+/**
+ * Reads a bill-of-materials table out of a model's Markdown reply. The model
+ * is asked for a table, not JSON, because tables survive partial streaming
+ * legibly; this turns the result back into rows.
+ */
+
+export const parseMarkdownBomTable = (text: string) => {
+ const normalized = String(text || "");
+ const lines = normalized.split(/\r?\n/);
+ for (let i = 0; i < lines.length - 2; i += 1) {
+ const header = lines[i];
+ const sep = lines[i + 1];
+ if (!header.includes("|")) continue;
+ if (!/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?\s*$/.test(sep)) continue;
+
+ const parseRow = (line: string) => {
+ const trimmed = line
+ .trim()
+ .replace(/^[-*+]\s+/, "")
+ .replace(/^\d+\.\s+/, "");
+ const body = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed;
+ const body2 = body.endsWith("|") ? body.slice(0, -1) : body;
+ return body2.split("|").map((c) => c.trim());
+ };
+
+ const columns = parseRow(header).filter((c) => c);
+ if (columns.length === 0) continue;
+
+ const rows: any[] = [];
+ for (let j = i + 2; j < lines.length; j += 1) {
+ const rowLine = lines[j];
+ if (!rowLine.includes("|")) break;
+ const row = parseRow(rowLine);
+ if (row.every((c) => !String(c || "").trim())) break;
+ const fixed = row.slice(0, columns.length);
+ while (fixed.length < columns.length) fixed.push("");
+ rows.push(fixed);
+ }
+
+ if (rows.length === 0) continue;
+ return { type: "cad_bom", columns, rows };
+ }
+ return null;
+};
diff --git a/src/shared/chat/chat-errors.ts b/src/shared/chat/chat-errors.ts
new file mode 100644
index 0000000..ba1e61f
--- /dev/null
+++ b/src/shared/chat/chat-errors.ts
@@ -0,0 +1,37 @@
+/**
+ * Maps a provider error onto something a user can act on. The raw message is
+ * usually an HTTP status or a token-count complaint that says nothing about
+ * what to change.
+ */
+export const getChatErrorText = (
+ error: unknown,
+ trText: (zhText: string, enText: string) => string
+) => {
+ const raw = String((error as any)?.message || error || "");
+
+ if (/input token count exceeds|maximum number of tokens allowed|too many tokens|context length/i.test(raw)) {
+ return trText(
+ "本次请求内容过长,通常是图片或附件内容过大。请重试;如果仍失败,请减少附件数量或缩小单个附件内容。",
+ "This request is too large, usually because an image or attachment expanded the input too much. Retry once; if it still fails, reduce the number or size of attachments."
+ );
+ }
+
+ if (/api key|invalid api key|incorrect api key|unauthorized|401/i.test(raw)) {
+ return trText(
+ "API 配置无效,请检查 API key 或服务配置。",
+ "The API configuration is invalid. Check the API key or provider settings."
+ );
+ }
+
+ if (/400|bad request/i.test(raw)) {
+ return trText(
+ "请求格式无效,请检查本次输入或附件内容。",
+ "The request payload is invalid. Check this input or its attachments."
+ );
+ }
+
+ return trText(
+ "抱歉,请求失败,请稍后重试。",
+ "Sorry, the request failed. Please try again."
+ );
+};
diff --git a/src/shared/chat/chat-storage.ts b/src/shared/chat/chat-storage.ts
new file mode 100644
index 0000000..c184263
--- /dev/null
+++ b/src/shared/chat/chat-storage.ts
@@ -0,0 +1,144 @@
+import type { ChatMessage } from "@/ai/types"
+
+/**
+ * Chat history persistence.
+ *
+ * Conversations here carry inline base64 images, so a handful of turns can
+ * blow past the localStorage quota. Two defences, in order: strip the image
+ * payloads (the tag and its label are what the UI re-renders from), then, if
+ * the write still fails, retry with progressively harsher limits. The history
+ * is never dropped wholesale — a shorter history beats none.
+ */
+
+export const CHAT_STORAGE_KEY_PREFIX = "chat_history_v2_"
+
+export const chatStorageKey = (workspaceId: string) => `${CHAT_STORAGE_KEY_PREFIX}${workspaceId}`
+
+const TRUNCATE_SUFFIX = "\n...[truncated]"
+
+interface StorageLimits {
+ maxMessages: number
+ maxMessageChars: number
+ maxTotalChars: number
+}
+
+/** Tried in order until one write succeeds. */
+const FALLBACK_LIMITS: StorageLimits[] = [
+ { maxMessages: 50, maxMessageChars: 24000, maxTotalChars: 240000 },
+ { maxMessages: 30, maxMessageChars: 12000, maxTotalChars: 120000 },
+ { maxMessages: 16, maxMessageChars: 6000, maxTotalChars: 60000 },
+ { maxMessages: 8, maxMessageChars: 3000, maxTotalChars: 30000 },
+]
+
+export function truncateForStorage(text: string, maxChars: number) {
+ const value = String(text || "")
+ if (maxChars <= 0) return ""
+ if (value.length <= maxChars) return value
+ if (maxChars <= TRUNCATE_SUFFIX.length) return value.slice(0, maxChars)
+ return value.slice(0, maxChars - TRUNCATE_SUFFIX.length) + TRUNCATE_SUFFIX
+}
+
+/** Accepts whatever was in storage; drops anything that is not a usable turn. */
+export function normalizeStoredChatMessages(raw: unknown): ChatMessage[] {
+ if (!Array.isArray(raw)) return []
+ return raw
+ .filter((message): message is Record<string, unknown> => !!message && typeof message === "object")
+ .map((message) => {
+ const role = String(message.role || "")
+ return {
+ role: (role === "user" || role === "assistant" || role === "system" ? role : "user") as ChatMessage["role"],
+ content: typeof message.content === "string" ? message.content : String(message.content ?? ""),
+ }
+ })
+ .filter((message) => !!message.content)
+}
+
+/**
+ * Replaces inline image data with a placeholder. `[[IMAGE|label|data:...]]`
+ * keeps its label so the message still reads correctly after a reload.
+ */
+function stripImagePayloads(text: string) {
+ return String(text || "")
+ .replace(/\[\[IMAGE\|([^|\]]*)\|data:image\/[\s\S]*?\]\]/gi, "[[IMAGE|$1|[image-data]]]")
+ .replace(/data:image\/[^)\s]+/gi, "[image-data]")
+}
+
+function compactForStorage(source: ChatMessage[], limits: StorageLimits): ChatMessage[] {
+ const compacted = normalizeStoredChatMessages(source)
+ .slice(-limits.maxMessages)
+ .map((message) => ({
+ role: message.role,
+ content: truncateForStorage(stripImagePayloads(message.content), limits.maxMessageChars),
+ }))
+
+ let totalChars = compacted.reduce((sum, message) => sum + message.content.length, 0)
+ while (compacted.length > 1 && totalChars > limits.maxTotalChars) {
+ totalChars -= compacted.shift()?.content.length || 0
+ }
+
+ // A single oversized message cannot be dropped — it may be the only turn.
+ if (compacted.length === 1 && compacted[0].content.length > limits.maxTotalChars) {
+ compacted[0] = {
+ role: compacted[0].role,
+ content: truncateForStorage(compacted[0].content, limits.maxTotalChars),
+ }
+ }
+
+ return compacted
+}
+
+export function loadChatHistory(storageKey: string, fallback: ChatMessage[] = []): ChatMessage[] {
+ if (typeof window === "undefined") return fallback
+ try {
+ const saved = localStorage.getItem(storageKey)
+ if (!saved) return fallback
+ const parsed = normalizeStoredChatMessages(JSON.parse(saved))
+ return parsed.length > 0 ? parsed : fallback
+ } catch (error) {
+ console.error("Failed to parse chat history", error)
+ return fallback
+ }
+}
+
+/** Returns false only when even the harshest limits could not be written. */
+export function saveChatHistory(storageKey: string, messages: ChatMessage[]): boolean {
+ for (const limits of FALLBACK_LIMITS) {
+ try {
+ localStorage.setItem(storageKey, JSON.stringify(compactForStorage(messages, limits)))
+ return true
+ } catch {
+ // Quota exceeded — try again with a smaller slice.
+ }
+ }
+ console.warn("Failed to persist chat history even at the smallest size")
+ return false
+}
+
+/**
+ * A compact transcript to hand an intent-routing agent, which needs recent
+ * context but not the whole conversation.
+ */
+export function buildRecentHistoryContext(
+ source: ChatMessage[],
+ limits: StorageLimits = { maxMessages: 12, maxMessageChars: 3000, maxTotalChars: 18000 },
+): string {
+ const recent = (source || [])
+ .filter((message) => message && (message.role === "user" || message.role === "assistant"))
+ .slice(-limits.maxMessages)
+ if (recent.length === 0) return ""
+
+ const lines: string[] = []
+ let totalChars = 0
+ for (const message of recent) {
+ const text = truncateForStorage(String(message.content || ""), limits.maxMessageChars)
+ if (!text) continue
+ const remaining = limits.maxTotalChars - totalChars
+ if (remaining <= 0) break
+ const clipped = text.length > remaining ? truncateForStorage(text, remaining) : text
+ lines.push(`[${message.role === "assistant" ? "Assistant" : "User"}] ${clipped}`)
+ totalChars += clipped.length
+ }
+
+ if (lines.length === 0) return ""
+ return `Recent chat history (for intent continuity):\n\n${lines.join("\n\n")}`
+}
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsx
index b7c0530..a656db0 100644
--- a/src/workspaces/cad/chat/ChatPanel.tsx
+++ b/src/workspaces/cad/chat/ChatPanel.tsx
@@ -1,4 +1,4 @@
-import React, { useState, useRef, useEffect } from 'react';
+import React, { useState, useRef, useEffect } from 'react';
import { PanelRightClose, PanelRightOpen } from 'lucide-react';
import { cn } from '@/shared/lib/utils';
import { streamChatMessage, generateChatMessage, ChatMessage, getAIConfig } from '@/ai/client';
@@ -9,7 +9,6 @@ import { ChatMessageDisplay, UIMessage } from '@/workspaces/cad/chat/ChatMessage
import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/shared/chat';
import { HistoryDialog, HistoryItem } from '@/shared/chat';
import { ResetWarningModal } from '@/shared/chat';
-import { useFileProcessor } from '@/shared/files/use-file-processor';
import {
buildCadAnalysisMessages,
buildCadBomMessages,
@@ -28,6 +27,15 @@ import flowPatchAgentPrompt from "../../../../agent/flow/patch.md?raw";
import flowReplaceAgentPrompt from "../../../../agent/flow/replace.md?raw";
import { t, useUiLanguage } from "@/shared/i18n";
import { toast } from "sonner";
+import {
+ buildRecentHistoryContext,
+ chatStorageKey,
+ loadChatHistory,
+ saveChatHistory,
+} from '@/shared/chat/chat-storage';
+import { createAssistantUpdater, writeLastAssistant } from '@/shared/chat/assistant-stream';
+import { getChatErrorText } from '@/shared/chat/chat-errors';
+import { parseMarkdownBomTable } from '@/shared/chat/bom-table';
interface Attachment {
id: string;
@@ -44,7 +52,6 @@ interface ChatPanelProps {
attachments?: Attachment[];
onRemoveAttachment?: (id: string) => void;
pptDraftSlides?: Array<{ id: string; slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>;
- onRemovePptDraftSlide?: (id: string) => void;
onClearPptDraftSlides?: () => void;
onCodeAction?: (code: string, type: 'flow' | 'cad' | 'ppt') => MaybePromise<void | CodeActionResult>;
systemPrompt?: string;
@@ -75,133 +82,13 @@ interface ChatPanelProps {
onClearWorkspace?: () => void;
}
-const STORAGE_KEY_PREFIX = 'chat_history_v2_';
-const CAD_STORAGE_TRUNCATE_SUFFIX = "\n...[truncated]";
-const CAD_STORAGE_DEFAULT_LIMITS = {
- maxMessages: 50,
- maxMessageChars: 24000,
- maxTotalChars: 240000,
-};
-const CAD_STORAGE_FALLBACK_LIMITS = [
- CAD_STORAGE_DEFAULT_LIMITS,
- { maxMessages: 30, maxMessageChars: 12000, maxTotalChars: 120000 },
- { maxMessages: 16, maxMessageChars: 6000, maxTotalChars: 60000 },
- { maxMessages: 8, maxMessageChars: 3000, maxTotalChars: 30000 },
-];
-const CAD_ROUTER_HISTORY_LIMITS = {
- maxMessages: 12,
- maxMessageChars: 3000,
- maxTotalChars: 18000,
-};
-
-const normalizeStoredChatMessages = (raw: any): ChatMessage[] => {
- if (!Array.isArray(raw)) return [];
- return raw
- .filter((m: any) => m && typeof m === "object")
- .map((m: any) => {
- const roleRaw = String(m.role || "");
- const role: ChatMessage["role"] =
- roleRaw === "user" || roleRaw === "assistant" || roleRaw === "system"
- ? roleRaw
- : "user";
- const content = typeof m.content === "string" ? m.content : String(m.content ?? "");
- return { role, content };
- })
- .filter((m: ChatMessage) => !!m.content);
-};
-
-const truncateForStorage = (text: string, maxChars: number) => {
- const value = String(text || "");
- if (maxChars <= 0) return "";
- if (value.length <= maxChars) return value;
- if (maxChars <= CAD_STORAGE_TRUNCATE_SUFFIX.length) {
- return value.slice(0, maxChars);
- }
- return value.slice(0, maxChars - CAD_STORAGE_TRUNCATE_SUFFIX.length) + CAD_STORAGE_TRUNCATE_SUFFIX;
-};
-
-const buildCadRouterHistoryContext = (source: ChatMessage[]) => {
- if (!Array.isArray(source) || source.length === 0) return "";
-
- const recent = source
- .filter((m) => m && (m.role === "user" || m.role === "assistant"))
- .slice(-CAD_ROUTER_HISTORY_LIMITS.maxMessages);
- if (recent.length === 0) return "";
-
- let totalChars = 0;
- const lines: string[] = [];
- for (const m of recent) {
- const raw = truncateForStorage(String(m.content || ""), CAD_ROUTER_HISTORY_LIMITS.maxMessageChars);
- if (!raw) continue;
-
- const remaining = CAD_ROUTER_HISTORY_LIMITS.maxTotalChars - totalChars;
- if (remaining <= 0) break;
-
- const clipped = raw.length > remaining ? truncateForStorage(raw, remaining) : raw;
- const roleLabel = m.role === "assistant" ? "Assistant" : "User";
- lines.push(`[${roleLabel}] ${clipped}`);
- totalChars += clipped.length;
- }
-
- if (lines.length === 0) return "";
- return `Recent chat history (for intent continuity):\n\n${lines.join("\n\n")}`;
-};
-
-const compactCadMessagesForStorage = (
- source: ChatMessage[],
- limits: { maxMessages: number; maxMessageChars: number; maxTotalChars: number },
-): ChatMessage[] => {
- const maxMessages = Math.max(1, Number(limits.maxMessages) || 1);
- const maxMessageChars = Math.max(256, Number(limits.maxMessageChars) || 256);
- const maxTotalChars = Math.max(1024, Number(limits.maxTotalChars) || 1024);
-
- const normalized = normalizeStoredChatMessages(source).slice(-maxMessages).map((m) => ({
- role: m.role,
- content: truncateForStorage(m.content, maxMessageChars),
- }));
-
- let totalChars = normalized.reduce((sum, m) => sum + m.content.length, 0);
- while (normalized.length > 1 && totalChars > maxTotalChars) {
- const removed = normalized.shift();
- totalChars -= removed?.content.length || 0;
- }
-
- if (normalized.length === 1 && normalized[0].content.length > maxTotalChars) {
- normalized[0] = {
- role: normalized[0].role,
- content: truncateForStorage(normalized[0].content, maxTotalChars),
- };
- }
-
- return normalized;
-};
-
-const persistCadMessagesWithFallback = (storageKey: string, source: ChatMessage[]) => {
- for (const limits of CAD_STORAGE_FALLBACK_LIMITS) {
- try {
- const compacted = compactCadMessagesForStorage(source, limits);
- localStorage.setItem(storageKey, JSON.stringify(compacted));
- return true;
- } catch {
- }
- }
- return false;
-};
-
// Convert internal ChatMessage to UIMessage
-const toUIMessage = (msg: ChatMessage, index: number): UIMessage => ({
- id: `msg-${index}-${Date.now()}`,
- role: msg.role as any,
- content: msg.content,
- parts: [{ type: 'text', text: msg.content }]
-});
export function ChatPanel({
className,
attachments = [],
onRemoveAttachment,
pptDraftSlides = [],
- onRemovePptDraftSlide,
onClearPptDraftSlides,
onCodeAction,
systemPrompt = DRAWIO_SYSTEM_PROMPT,
@@ -268,26 +155,11 @@ export function ChatPanel({
...refs.map((ref) => ({ type: "image_url", image_url: { url: ref.url } })),
];
};
- // Persistence key
- const storageKey = `${STORAGE_KEY_PREFIX}${workspaceId}`;
+ const storageKey = chatStorageKey(workspaceId);
- const [messages, setMessages] = useState<ChatMessage[]>(() => {
- if (typeof window !== 'undefined') {
- const saved = localStorage.getItem(storageKey);
- if (saved) {
- try {
- if (workspaceId === "cad") {
- const parsed = normalizeStoredChatMessages(JSON.parse(saved));
- return compactCadMessagesForStorage(parsed, CAD_STORAGE_DEFAULT_LIMITS);
- }
- return JSON.parse(saved);
- } catch (e) {
- console.error("Failed to parse chat history", e);
- }
- }
- }
- return initialMessages.length > 0 ? initialMessages : [];
- });
+ const [messages, setMessages] = useState<ChatMessage[]>(() =>
+ loadChatHistory(storageKey, initialMessages),
+ );
const [input, setInput] = useState('');
const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" }>>([
@@ -367,45 +239,6 @@ export function ChatPanel({
for (const s of added) enqueuePptToken(s.slideId, s.title);
}, [workspaceId, pptDraftSlides, setInput]);
- const parseMarkdownBomTable = (text: string) => {
- const normalized = String(text || "");
- const lines = normalized.split(/\r?\n/);
- for (let i = 0; i < lines.length - 2; i += 1) {
- const header = lines[i];
- const sep = lines[i + 1];
- if (!header.includes("|")) continue;
- if (!/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?\s*$/.test(sep)) continue;
-
- const parseRow = (line: string) => {
- const trimmed = line
- .trim()
- .replace(/^[-*+]\s+/, "")
- .replace(/^\d+\.\s+/, "");
- const body = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed;
- const body2 = body.endsWith("|") ? body.slice(0, -1) : body;
- return body2.split("|").map((c) => c.trim());
- };
-
- const columns = parseRow(header).filter((c) => c);
- if (columns.length === 0) continue;
-
- const rows: any[] = [];
- for (let j = i + 2; j < lines.length; j += 1) {
- const rowLine = lines[j];
- if (!rowLine.includes("|")) break;
- const row = parseRow(rowLine);
- if (row.every((c) => !String(c || "").trim())) break;
- const fixed = row.slice(0, columns.length);
- while (fixed.length < columns.length) fixed.push("");
- rows.push(fixed);
- }
-
- if (rows.length === 0) continue;
- return { type: "cad_bom", columns, rows };
- }
- return null;
- };
-
const sanitizeAssistantContentForDisplay = (content: string) => {
if (workspaceId !== "cad") return content;
if (!content) return content;
@@ -543,65 +376,16 @@ export function ChatPanel({
return next;
};
- const scheduleFrame = (cb: () => void) => {
- if (typeof requestAnimationFrame === "function") return requestAnimationFrame(cb);
- if (typeof window !== "undefined") return window.setTimeout(cb, 16);
- return 0;
- };
-
- const cancelFrame = (id: number) => {
- if (!id) return;
- if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(id);
- else if (typeof window !== "undefined") window.clearTimeout(id);
- };
+ const updateLastAssistant = (content: string) =>
+ writeLastAssistant(setMessages, sanitizeAssistantContentForDisplay, content);
- const updateLastAssistant = (content: string) => {
- const display = sanitizeAssistantContentForDisplay(content);
- setMessages(prev => {
- const last = prev[prev.length - 1];
- if (last?.role === 'assistant') {
- return [...prev.slice(0, -1), { role: 'assistant', content: display }];
- }
- return [...prev, { role: 'assistant', content: display }];
- });
- };
+ const createThrottledAssistantUpdater = () =>
+ createAssistantUpdater(setMessages, sanitizeAssistantContentForDisplay);
- const createThrottledAssistantUpdater = () => {
- let latest = '';
- let frameId: number | null = null;
- return {
- push: (chunk: string) => {
- latest = chunk;
- if (frameId !== null) return;
- frameId = scheduleFrame(() => {
- frameId = null;
- updateLastAssistant(latest);
- });
- },
- flush: () => {
- if (frameId !== null) {
- cancelFrame(frameId);
- frameId = null;
- }
- updateLastAssistant(latest);
- }
- };
- };
-
- // Persist messages
useEffect(() => {
- if (typeof window !== "undefined") {
- if (workspaceId === "cad") {
- const ok = persistCadMessagesWithFallback(storageKey, messages);
- if (!ok) {
- console.error("Failed to persist CAD chat history after fallback trimming.");
- }
- } else {
- localStorage.setItem(storageKey, JSON.stringify(messages));
- }
- }
+ if (typeof window !== "undefined") saveChatHistory(storageKey, messages);
onMessagesChange?.(messages);
- }, [messages, storageKey, onMessagesChange, workspaceId]);
+ }, [messages, storageKey, onMessagesChange]);
const clearHistory = () => {
abortControllerRef.current?.abort();
@@ -622,24 +406,6 @@ export function ChatPanel({
setShowResetWarning(false);
};
- const startNewChat = () => {
- abortControllerRef.current?.abort();
- abortControllerRef.current = null;
- cadApprovedPlanRef.current = null;
- setIsLoading(false);
- setInput('');
- setPptInputSegments([{ type: "text", text: "" }]);
- setFiles([]);
- onClearAttachments?.();
- const newMsgs: ChatMessage[] = [
- { role: 'assistant', content: t(uiLang, "chat.newChat") }
- ];
- setMessages(newMsgs);
- try {
- localStorage.removeItem(storageKey);
- } catch {
- }
- };
const runCodeAction = async (code: string, type: 'flow' | 'cad' | 'ppt') => {
const result = await Promise.resolve(onCodeAction?.(code, type));
@@ -1211,7 +977,7 @@ export function ChatPanel({
: "";
const cadHistoryContextText =
workspaceId === "cad"
- ? buildCadRouterHistoryContext(messages)
+ ? buildRecentHistoryContext(messages)
: "";
const promptParts = [
@@ -2109,7 +1875,7 @@ export function ChatPanel({
}
setMessages(prev => {
const last = prev[prev.length - 1];
- const errorText = trText("抱歉,发生错误。请检查 API Key 设置。", "Sorry, an error occurred. Please check API key settings.");
+ const errorText = getChatErrorText(error, trText);
if (last.role === 'assistant' && !last.content) {
return [...prev.slice(0, -1), { role: 'assistant', content: errorText }];
}
@@ -2156,7 +1922,7 @@ export function ChatPanel({
: "";
const cadHistoryContextText =
workspaceId === "cad"
- ? buildCadRouterHistoryContext(baseMessages.slice(0, -1))
+ ? buildRecentHistoryContext(baseMessages.slice(0, -1))
: "";
const promptContent = [lastUserText, flowContextText, cadContextText, cadHistoryContextText].filter(Boolean).join("\n\n");
@@ -2863,10 +2629,11 @@ export function ChatPanel({
setMessages(prev => {
const last = prev[prev.length - 1];
+ const errorText = getChatErrorText(error, trText);
if (last?.role === 'assistant' && !last.content) {
- return [...prev.slice(0, -1), { role: 'assistant', content: "Sorry, an error occurred. Please check API key settings." }];
+ return [...prev.slice(0, -1), { role: 'assistant', content: errorText }];
}
- return [...prev, { role: 'assistant', content: "Sorry, an error occurred. Please check API key settings." }];
+ return [...prev, { role: 'assistant', content: errorText }];
});
} finally {
setIsLoading(false);
diff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/src/workspaces/ppt/PptWorkspaceShell.tsx
index 4df6b6b..d021120 100644
--- a/src/workspaces/ppt/PptWorkspaceShell.tsx
+++ b/src/workspaces/ppt/PptWorkspaceShell.tsx
@@ -11,7 +11,7 @@ import {
PPT_OUTLINE_EDIT_SYSTEM_PROMPT,
PPT_SLIDES_EDIT_SYSTEM_PROMPT,
} from "@/lib/system-prompts";
-import { PPT_STATE_KEY, pptStore } from "@/workspaces/ppt/storage";
+import { PPT_STATE_KEY, PPT_WORKSPACE_STORAGE_KEY, pptStore } from "@/workspaces/ppt/storage";
import type { ChatMessage } from "@/ai/client";
import { PptWorkspace } from "@/workspaces/ppt/workspace/PptWorkspace";
import { ChatPanel as PptChatPanel } from "@/workspaces/ppt/chat/ChatPanel";
@@ -26,7 +26,6 @@ type Attachment = {
type CodeActionResult = { ok: boolean; retry?: boolean; error?: string };
-const PPT_WORKSPACE_STORAGE_KEY = "CanvasAnvil-ppt-state-v1";
const PPT_RETURN_STAGE_STORAGE_KEY = "CanvasAnvil-ppt-return-stage-v1";
const PPT_HISTORY_STORAGE_KEY = "CanvasAnvil-history-ppt-v1";
const PPT_CHAT_STORAGE_KEY = "chat_history_v2_ppt";
@@ -318,7 +317,6 @@ export function PptWorkspaceShell() {
onRemoveAttachment={(id) => setAttachments((prev) => prev.filter((a) => a.id !== id))}
onClearAttachments={() => setAttachments([])}
pptDraftSlides={pptDraftSlides}
- onRemovePptDraftSlide={(id) => setPptDraftSlides((prev) => prev.filter((s) => s.id !== id))}
onClearPptDraftSlides={() => setPptDraftSlides([])}
onClearWorkspace={clearWorkspace}
history={versionHistory}
diff --git a/src/workspaces/ppt/chat/ChatPanel.tsx b/src/workspaces/ppt/chat/ChatPanel.tsx
index 4df893a..c53621a 100644
--- a/src/workspaces/ppt/chat/ChatPanel.tsx
+++ b/src/workspaces/ppt/chat/ChatPanel.tsx
@@ -5,11 +5,15 @@ import { streamChatMessage, generateChatMessage, generatePptProxyChatMessage, Ch
import { DRAWIO_SYSTEM_PROMPT } from '@/lib/system-prompts';
import { ButtonWithTooltip } from '@/shared/chat';
import { ChatInput } from '@/shared/chat';
+import { chatStorageKey, loadChatHistory, saveChatHistory } from '@/shared/chat/chat-storage';
+import { createAssistantUpdater, writeLastAssistant } from '@/shared/chat/assistant-stream';
+import { getChatErrorText } from '@/shared/chat/chat-errors';
+import { parseMarkdownBomTable } from '@/shared/chat/bom-table';
+import { PPT_WORKSPACE_STORAGE_KEY } from '@/workspaces/ppt/storage';
import { ChatMessageDisplay, UIMessage } from '@/workspaces/ppt/chat/ChatMessageDisplay';
import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/shared/chat';
import { HistoryDialog, HistoryItem } from '@/shared/chat';
import { ResetWarningModal } from '@/shared/chat';
-import { useFileProcessor } from '@/shared/files/use-file-processor';
import { buildCadBomMessages, buildCadImagesMasterMessages, buildCadImagesSheetMessages, buildCadTasksSystemContent } from '@/lib/cad-tasks';
import { CAD_PLAN_AGENT_PROMPT } from '@/lib/cad-agents';
import flowPatchAgentPrompt from "../../../../agent/flow/patch.md?raw";
@@ -31,7 +35,6 @@ interface ChatPanelProps {
attachments?: Attachment[];
onRemoveAttachment?: (id: string) => void;
pptDraftSlides?: Array<{ id: string; slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>;
- onRemovePptDraftSlide?: (id: string) => void;
onClearPptDraftSlides?: () => void;
onCodeAction?: (code: string, type: 'flow' | 'cad' | 'ppt') => MaybePromise<void | CodeActionResult>;
systemPrompt?: string;
@@ -61,72 +64,13 @@ interface ChatPanelProps {
onClearWorkspace?: () => void;
}
-const STORAGE_KEY_PREFIX = 'chat_history_v2_';
-const PPT_WORKSPACE_STORAGE_KEY = "CanvasAnvil-ppt-state-v1";
-const STORAGE_MESSAGE_LIMIT = 40;
-const STORAGE_CONTENT_LIMIT = 4000;
-
// Convert internal ChatMessage to UIMessage
-const toUIMessage = (msg: ChatMessage, index: number): UIMessage => ({
- id: `msg-${index}-${Date.now()}`,
- role: msg.role as any,
- content: msg.content,
- parts: [{ type: 'text', text: msg.content }]
-});
-
-const compactMessageContent = (value: unknown) => {
- const text = String(value || "");
- const withoutImageTags = text.replace(/\[\[IMAGE\|([^|\]]*)\|data:image\/[\s\S]*?\]\]/gi, "[[IMAGE|$1|[image-data]]]");
- const withoutDataUrls = withoutImageTags.replace(/data:image\/[^)\s]+/gi, "[image-data]");
- if (withoutDataUrls.length <= STORAGE_CONTENT_LIMIT) return withoutDataUrls;
- return `${withoutDataUrls.slice(0, STORAGE_CONTENT_LIMIT)}\n...[truncated]`;
-};
-
-const getMessagesForStorage = (messages: ChatMessage[]) =>
- messages.slice(-STORAGE_MESSAGE_LIMIT).map((message) => ({
- role: message.role,
- content: compactMessageContent(message.content),
- }));
-
-const getChatErrorText = (
- error: unknown,
- trText: (zhText: string, enText: string) => string
-) => {
- const raw = String((error as any)?.message || error || "");
-
- if (/input token count exceeds|maximum number of tokens allowed|too many tokens|context length/i.test(raw)) {
- return trText(
- "本次请求内容过长,通常是图片或附件内容过大。请重试;如果仍失败,请减少附件数量或缩小单个附件内容。",
- "This request is too large, usually because an image or attachment expanded the input too much. Retry once; if it still fails, reduce the number or size of attachments."
- );
- }
-
- if (/api key|invalid api key|incorrect api key|unauthorized|401/i.test(raw)) {
- return trText(
- "API 配置无效,请检查 API key 或服务配置。",
- "The API configuration is invalid. Check the API key or provider settings."
- );
- }
-
- if (/400|bad request/i.test(raw)) {
- return trText(
- "请求格式无效,请检查本次输入或附件内容。",
- "The request payload is invalid. Check this input or its attachments."
- );
- }
-
- return trText(
- "抱歉,请求失败,请稍后重试。",
- "Sorry, the request failed. Please try again."
- );
-};
export function ChatPanel({
className,
attachments = [],
onRemoveAttachment,
pptDraftSlides = [],
- onRemovePptDraftSlide,
onClearPptDraftSlides,
onCodeAction,
systemPrompt = DRAWIO_SYSTEM_PROMPT,
@@ -152,22 +96,11 @@ export function ChatPanel({
const uiLang = useUiLanguage();
const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);
const resolvedTitle = title || t(uiLang, "workspace.default.title");
- // Persistence key
- const storageKey = `${STORAGE_KEY_PREFIX}${workspaceId}`;
+ const storageKey = chatStorageKey(workspaceId);
- const [messages, setMessages] = useState<ChatMessage[]>(() => {
- if (typeof window !== 'undefined') {
- const saved = localStorage.getItem(storageKey);
- if (saved) {
- try {
- return JSON.parse(saved);
- } catch (e) {
- console.error("Failed to parse chat history", e);
- }
- }
- }
- return initialMessages.length > 0 ? initialMessages : [];
- });
+ const [messages, setMessages] = useState<ChatMessage[]>(() =>
+ loadChatHistory(storageKey, initialMessages),
+ );
const [input, setInput] = useState('');
const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" }>>([
@@ -242,45 +175,6 @@ export function ChatPanel({
for (const s of added) enqueuePptToken(s.slideId, s.title, s.kind);
}, [workspaceId, pptDraftSlides, setInput]);
- const parseMarkdownBomTable = (text: string) => {
- const normalized = String(text || "");
- const lines = normalized.split(/\r?\n/);
- for (let i = 0; i < lines.length - 2; i += 1) {
- const header = lines[i];
- const sep = lines[i + 1];
- if (!header.includes("|")) continue;
- if (!/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?\s*$/.test(sep)) continue;
-
- const parseRow = (line: string) => {
- const trimmed = line
- .trim()
- .replace(/^[-*+]\s+/, "")
- .replace(/^\d+\.\s+/, "");
- const body = trimmed.startsWith("|") ? trimmed.slice(1) : trimmed;
- const body2 = body.endsWith("|") ? body.slice(0, -1) : body;
- return body2.split("|").map((c) => c.trim());
- };
-
- const columns = parseRow(header).filter((c) => c);
- if (columns.length === 0) continue;
-
- const rows: any[] = [];
- for (let j = i + 2; j < lines.length; j += 1) {
- const rowLine = lines[j];
- if (!rowLine.includes("|")) break;
- const row = parseRow(rowLine);
- if (row.every((c) => !String(c || "").trim())) break;
- const fixed = row.slice(0, columns.length);
- while (fixed.length < columns.length) fixed.push("");
- rows.push(fixed);
- }
-
- if (rows.length === 0) continue;
- return { type: "cad_bom", columns, rows };
- }
- return null;
- };
-
const sanitizeAssistantContentForDisplay = (content: string) => {
if (workspaceId !== "cad") return content;
if (!content) return content;
@@ -328,62 +222,14 @@ export function ChatPanel({
});
};
- const scheduleFrame = (cb: () => void) => {
- if (typeof requestAnimationFrame === "function") return requestAnimationFrame(cb);
- if (typeof window !== "undefined") return window.setTimeout(cb, 16);
- return 0;
- };
-
- const cancelFrame = (id: number) => {
- if (!id) return;
- if (typeof cancelAnimationFrame === "function") cancelAnimationFrame(id);
- else if (typeof window !== "undefined") window.clearTimeout(id);
- };
+ const updateLastAssistant = (content: string) =>
+ writeLastAssistant(setMessages, sanitizeAssistantContentForDisplay, content);
- const updateLastAssistant = (content: string) => {
- const display = sanitizeAssistantContentForDisplay(content);
- setMessages(prev => {
- const last = prev[prev.length - 1];
- if (last?.role === 'assistant') {
- return [...prev.slice(0, -1), { role: 'assistant', content: display }];
- }
- return [...prev, { role: 'assistant', content: display }];
- });
- };
-
- const createThrottledAssistantUpdater = () => {
- let latest = '';
- let frameId: number | null = null;
- return {
- push: (chunk: string) => {
- latest = chunk;
- if (frameId !== null) return;
- frameId = scheduleFrame(() => {
- frameId = null;
- updateLastAssistant(latest);
- });
- },
- flush: () => {
- if (frameId !== null) {
- cancelFrame(frameId);
- frameId = null;
- }
- updateLastAssistant(latest);
- }
- };
- };
+ const createThrottledAssistantUpdater = () =>
+ createAssistantUpdater(setMessages, sanitizeAssistantContentForDisplay);
- // Persist messages
useEffect(() => {
- try {
- localStorage.setItem(storageKey, JSON.stringify(getMessagesForStorage(messages)));
- } catch (error) {
- console.warn("Failed to persist chat history", error);
- try {
- localStorage.removeItem(storageKey);
- } catch {
- }
- }
+ if (typeof window !== "undefined") saveChatHistory(storageKey, messages);
onMessagesChange?.(messages);
}, [messages, storageKey, onMessagesChange]);
@@ -405,23 +251,6 @@ export function ChatPanel({
setShowResetWarning(false);
};
- const startNewChat = () => {
- abortControllerRef.current?.abort();
- abortControllerRef.current = null;
- setIsLoading(false);
- setInput('');
- setPptInputSegments([{ type: "text", text: "" }]);
- setFiles([]);
- onClearAttachments?.();
- const newMsgs: ChatMessage[] = [
- { role: 'assistant', content: t(uiLang, "chat.newChat") }
- ];
- setMessages(newMsgs);
- try {
- localStorage.removeItem(storageKey);
- } catch {
- }
- };
const runCodeAction = async (code: string, type: 'flow' | 'cad' | 'ppt') => {
const result = await Promise.resolve(onCodeAction?.(code, type));
diff --git a/src/workspaces/ppt/storage.ts b/src/workspaces/ppt/storage.ts
index 18afb55..4786f98 100644
--- a/src/workspaces/ppt/storage.ts
+++ b/src/workspaces/ppt/storage.ts
@@ -5,3 +5,6 @@ export const pptStore = createWorkspaceStore("CanvasAnvilPptWorkspaceDB");
export const PPT_STATE_KEY = "primary";
export const PPT_TEMPLATE_LIBRARY_KEY = "template-library";
+
+/** Mirror of the workspace state in localStorage, read by the chat panel. */
+export const PPT_WORKSPACE_STORAGE_KEY = "CanvasAnvil-ppt-state-v1";
diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/src/workspaces/ppt/workspace/PptWorkspace.tsx
index 5d856e6..b267470 100644
--- a/src/workspaces/ppt/workspace/PptWorkspace.tsx
+++ b/src/workspaces/ppt/workspace/PptWorkspace.tsx
@@ -3,7 +3,7 @@ import { motion } from "motion/react";
import { generateImage, generateChatMessage } from '@/ai/client';
import { pptService, PptPage, type PptElement, type PptTextBlock, type SlideEditRoutingItem, resolveTextBlockFontSize, PPT_REFERENCE_SLIDE_HEIGHT, PPT_REFERENCE_SLIDE_WIDTH, textBlocksToPptElements } from '@/lib/ppt-service';
import { getTemplateGenerationPrompt } from '@/lib/ppt-prompts';
-import { PPT_STATE_KEY, PPT_TEMPLATE_LIBRARY_KEY, pptStore } from "@/workspaces/ppt/storage";
+import { PPT_STATE_KEY, PPT_TEMPLATE_LIBRARY_KEY, PPT_WORKSPACE_STORAGE_KEY, pptStore } from "@/workspaces/ppt/storage";
import { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb, X, ArrowLeft, ArrowRight, Eye, Trash2, Maximize2, Minimize2, RefreshCcw } from 'lucide-react';
import {
ContextMenu,
@@ -491,7 +491,6 @@ type TemplateItem =
const PPT_TEMPLATE_UPLOADS_KEY = "ppt_template_uploads_v1";
const PPT_TEMPLATE_HIDDEN_PRESETS_KEY = "ppt_template_hidden_presets_v1";
-const PPT_WORKSPACE_STORAGE_KEY = "CanvasAnvil-ppt-state-v1";
const readLegacyUploadedTemplates = (): UploadTemplate[] => {
if (typeof window === "undefined") return [];