Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

Persist infographic AI conversation history

tianma-if25b14d93f323
diff --git a/apps/web/src/components/InfographicEditorPane.tsx b/apps/web/src/components/InfographicEditorPane.tsx
index f21b4513..d3157c21 100644
--- a/apps/web/src/components/InfographicEditorPane.tsx
+++ b/apps/web/src/components/InfographicEditorPane.tsx
@@ -1,7 +1,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { ChevronLeft, Download, LoaderCircle, Presentation, Sparkles, Undo2 } from "lucide-react";
import { useTranslation } from "react-i18next";
-import { markdownToDoc, infographicFallbackMarkdown, parseInfographicDocument, serializeInfographicDocument, type InfographicDocument, type MemoDetail, type MemoEditSession } from "@edgeever/shared";
+import { markdownToDoc, infographicFallbackMarkdown, parseInfographicDocument, serializeInfographicDocument, type InfographicConversationTurn, type InfographicDocument, type MemoDetail, type MemoEditSession } from "@edgeever/shared";
import type { Infographic as InfographicInstance, SyntaxParseResult } from "@antv/infographic";
import { Button } from "@/components/ui/button";
import { MemoTitleInput } from "@/components/MemoTitleInput";
@@ -173,27 +173,35 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
const parsed = useMemo(() => parseInfographicDocument(memo.contentMarkdown), [memo.contentMarkdown]);
const [title, setTitle] = useState(memo.title ?? "");
const [syntax, setSyntax] = useState(parsed?.syntax ?? "");
+ const [history, setHistory] = useState<InfographicConversationTurn[]>(parsed?.history ?? []);
const [prompt, setPrompt] = useState("");
- const [previousGeneration, setPreviousGeneration] = useState<{ title: string; syntax: string } | null>(null);
+ const [previousGeneration, setPreviousGeneration] = useState<{ title: string; syntax: string; turnId: string } | null>(null);
const [generating, setGenerating] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
const [renderError, setRenderError] = useState<string | null>(null);
const [previewReady, setPreviewReady] = useState(false);
const [ready, setReady] = useState(false);
- const [savedSnapshot, setSavedSnapshot] = useState(JSON.stringify([memo.title ?? "", parsed?.syntax ?? ""]));
+ const [savedSnapshot, setSavedSnapshot] = useState(JSON.stringify([memo.title ?? "", parsed?.syntax ?? "", parsed?.history ?? []]));
+ const [savedHistorySnapshot, setSavedHistorySnapshot] = useState(JSON.stringify(parsed?.history ?? []));
const containerRef = useRef<HTMLDivElement>(null);
+ const historyViewportRef = useRef<HTMLDivElement>(null);
const instanceRef = useRef<InfographicInstance | null>(null);
const sessionRef = useRef<MemoEditSession | null>(null);
const memoRef = useRef(memo);
const saveRef = useRef<() => void>(() => undefined);
- const snapshot = JSON.stringify([title, syntax]);
+ const snapshot = JSON.stringify([title, syntax, history]);
const dirty = snapshot !== savedSnapshot;
+ const historyDirty = JSON.stringify(history) !== savedHistorySnapshot;
useEffect(() => {
memoRef.current = memo;
}, [memo]);
+ useEffect(() => {
+ if (historyViewportRef.current) historyViewportRef.current.scrollTop = historyViewportRef.current.scrollHeight;
+ }, [history]);
+
useEffect(() => {
if (readOnly) return;
let cancelled = false;
@@ -295,6 +303,7 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
if (!previousGeneration) return;
setSyntax(previousGeneration.syntax);
setTitle(previousGeneration.title);
+ setHistory((turns) => turns.map((turn) => turn.id === previousGeneration.turnId ? { ...turn, undoneAt: new Date().toISOString() } : turn));
setPreviousGeneration(null);
setError(null);
};
@@ -307,7 +316,7 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
}
const currentMemo = memoRef.current;
const currentSnapshot = snapshot;
- const document: InfographicDocument = { schemaVersion: 1, syntax };
+ const document: InfographicDocument = { schemaVersion: 1, syntax, ...(history.length ? { history } : {}) };
setSaving(true); setError(null);
try {
const result = await repository.updateMemo(currentMemo, {
@@ -321,6 +330,7 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
});
memoRef.current = result.memo;
setSavedSnapshot(currentSnapshot);
+ setSavedHistorySnapshot(JSON.stringify(history));
await onSaved(result.memo);
} catch (caught) {
setError(caught instanceof Error ? caught.message : t("infographic.saveError"));
@@ -330,9 +340,9 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
useEffect(() => {
if (!dirty || !ready || readOnly || saving || generating || renderError || (syntax.trim() && !previewReady)) return;
- const timer = window.setTimeout(() => saveRef.current(), 1200);
+ const timer = window.setTimeout(() => saveRef.current(), historyDirty ? 0 : 1200);
return () => window.clearTimeout(timer);
- }, [dirty, ready, readOnly, saving, generating, renderError, previewReady, snapshot, syntax]);
+ }, [dirty, ready, readOnly, saving, generating, renderError, previewReady, snapshot, syntax, historyDirty]);
const generate = async () => {
if (!prompt.trim() || generating || readOnly) return;
@@ -379,9 +389,14 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
if (parsedCandidate.errors.length || !parsedCandidate.options.template || !getTemplate(parsedCandidate.options.template)) {
throw new Error(t("infographic.aiInvalidResponse"));
}
- setPreviousGeneration({ title, syntax });
- setSyntax(candidate);
const generatedTitle = selectedOfficial ? String(selectedOfficial.data.title ?? "") : content!.title;
+ const turnId = crypto.randomUUID();
+ setPreviousGeneration({ title, syntax, turnId });
+ setHistory((turns) => [...turns, {
+ id: turnId, prompt: prompt.trim(), createdAt: new Date().toISOString(),
+ kind: syntax.trim() ? "refined" : "generated", resultTitle: generatedTitle,
+ }]);
+ setSyntax(candidate);
if (!title.trim() || title.trim() === t("infographic.name") || (replaceExisting && title.trim() === currentForm?.heading)) setTitle(generatedTitle);
setPrompt("");
} catch (caught) { setError(caught instanceof Error ? caught.message : t("infographic.aiError")); }
@@ -407,8 +422,23 @@ export default function InfographicEditorPane({ memo, repository, readOnly, onBa
</header>
{error ? <p role="alert" className="border-b border-red-100 bg-red-50 px-5 py-2 text-sm text-red-700">{error}</p> : null}
<div className="grid min-h-0 flex-1 grid-cols-1 lg:grid-cols-[minmax(300px,34%)_1fr]">
- <section className="min-h-0 overflow-y-auto border-b border-slate-200 p-5 lg:border-b-0 lg:border-r">
- {!readOnly && <div className="mb-5 rounded-xl border border-emerald-100 bg-emerald-50/50 p-4">
+ <section className="flex min-h-[320px] max-h-[60vh] flex-col border-b border-slate-200 p-5 lg:min-h-0 lg:max-h-none lg:border-b-0 lg:border-r">
+ <div ref={historyViewportRef} className="min-h-0 flex-1 overflow-y-auto" role="log" aria-label={t("infographic.historyTitle")}>
+ {history.length > 0 && <div className="pb-5">
+ <h2 className="mb-3 text-sm font-semibold text-slate-800">{t("infographic.historyTitle")}</h2>
+ <ol className="space-y-4">
+ {history.map((turn) => <li key={turn.id} className="space-y-2 text-sm">
+ <div className="flex justify-end"><div className="max-w-[92%] rounded-xl bg-emerald-50 px-3 py-2 text-slate-800 whitespace-pre-wrap break-words">{turn.prompt}</div></div>
+ <div className="max-w-[92%] rounded-xl border border-slate-200 bg-white px-3 py-2 text-slate-700">
+ <p>{t(turn.kind === "generated" ? "infographic.historyGenerated" : "infographic.historyRefined", { title: turn.resultTitle || t("infographic.name") })}</p>
+ {turn.undoneAt && <p className="mt-1 text-xs text-slate-500">{t("infographic.historyUndone")}</p>}
+ <time className="mt-1 block text-xs text-slate-500" dateTime={turn.createdAt}>{new Date(turn.createdAt).toLocaleString(i18n.resolvedLanguage)}</time>
+ </div>
+ </li>)}
+ </ol>
+ </div>}
+ </div>
+ {!readOnly && <div className="shrink-0 rounded-xl border border-emerald-100 bg-emerald-50/50 p-4">
<label className="mb-2 block text-sm font-medium text-slate-800" htmlFor="infographic-prompt"><Sparkles className="mr-1 inline h-4 w-4 text-emerald-700" />{t(syntax.trim() ? "infographic.refine" : "infographic.describe")}</label>
<textarea id="infographic-prompt" maxLength={1000} className="min-h-24 w-full rounded-md border border-slate-200 bg-white p-3 text-sm outline-none focus-visible:ring-2 focus-visible:ring-emerald-500" placeholder={t(syntax.trim() ? "infographic.refinePrompt" : "infographic.prompt")} value={prompt} onChange={(event) => setPrompt(event.target.value)} />
<div className="mt-2 flex flex-wrap items-center gap-2"><Button size="sm" disabled={!prompt.trim() || generating} onClick={() => void generate()}>{generating ? <LoaderCircle className="mr-1 h-4 w-4 animate-spin" /> : <Sparkles className="mr-1 h-4 w-4" />}{generating ? t("infographic.generating") : t(syntax.trim() ? "infographic.applyRefinement" : "infographic.generate")}</Button>
diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.ts
index af9e52ae..c2ac2326 100644
--- a/packages/shared/src/i18n/en-US.ts
+++ b/packages/shared/src/i18n/en-US.ts
@@ -6,6 +6,7 @@ export const enUS = {
name: "Infographic", autoLayout: "Auto layout", describe: "Describe and generate", chooseTemplate: "Choose a template and fill content",
prompt: "Describe the information, structure, and key points", generate: "Generate infographic", generating: "Generating…",
refine: "Describe what to change", refinePrompt: "For example: change the second item to user growth", applyRefinement: "Revise with AI", undoGeneration: "Undo last generation", fineTune: "Fine-tune manually",
+ historyTitle: "AI conversation history", historyGenerated: "Generated “{{title}}”", historyRefined: "Revised “{{title}}”", historyUndone: "This revision was undone",
doubleClickText: "Double-click text in the graphic to edit it. Changes save automatically.",
structureSettings: "Structure and style · Bulk edit", editSyntax: "Edit source syntax", backToStructure: "Back to structure and style",
title: "Title", description: "Description", items: "Items (one per line, use ‘Title | Description’)", comparisonItems: "One line per side; add aspects as ‘- Aspect | Description’", template: "Template", theme: "Color theme",
diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.ts
index 24703833..2ebd46dc 100644
--- a/packages/shared/src/i18n/ja.ts
+++ b/packages/shared/src/i18n/ja.ts
@@ -6,6 +6,7 @@ export const ja = {
name: "インフォグラフィック", autoLayout: "自動配置", describe: "説明して生成", chooseTemplate: "テンプレートを選んで入力",
prompt: "表示したい情報、構成、要点を説明してください", generate: "インフォグラフィックを生成", generating: "生成中…",
refine: "変更したい点を説明", refinePrompt: "例:2 番目の項目をユーザー成長に変更", applyRefinement: "AI で修正", undoGeneration: "前回の生成を元に戻す", fineTune: "手動で微調整",
+ historyTitle: "AI の対話履歴", historyGenerated: "「{{title}}」を生成しました", historyRefined: "「{{title}}」を修正しました", historyUndone: "この変更は取り消されました",
doubleClickText: "図内の文字をダブルクリックして編集できます。変更は自動保存されます。",
structureSettings: "構成とスタイル · 一括編集", editSyntax: "元の構文を編集", backToStructure: "構成とスタイルに戻る",
title: "タイトル", description: "説明", items: "項目(1 行に 1 件、「タイトル | 説明」)", comparisonItems: "比較する 2 者を各 1 行にし、観点は「- 項目 | 説明」で追加", template: "テンプレート", theme: "配色",
diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.ts
index 80d8154d..d7a42516 100644
--- a/packages/shared/src/i18n/zh-CN.ts
+++ b/packages/shared/src/i18n/zh-CN.ts
@@ -6,6 +6,7 @@ export const zhCN = {
name: "信息图", autoLayout: "自动排版", describe: "描述内容并生成", chooseTemplate: "选择模板手动填内容",
prompt: "描述你想呈现的信息、结构与重点", generate: "生成信息图", generating: "正在生成…",
refine: "描述要修改的地方", refinePrompt: "例如:把第二项改成用户增长,其余内容保留", applyRefinement: "用 AI 修改", undoGeneration: "撤回上次生成", fineTune: "人工微调",
+ historyTitle: "AI 对话记录", historyGenerated: "已生成「{{title}}」", historyRefined: "已修改「{{title}}」", historyUndone: "这次修改已撤回",
doubleClickText: "双击图中文字可直接修改,修改后自动保存。",
structureSettings: "结构与样式 · 批量调整", editSyntax: "编辑源语法", backToStructure: "返回结构与样式",
title: "标题", description: "说明", items: "条目(每行一个,使用“标题 | 说明”)", comparisonItems: "对比双方各占一行;子项用“- 维度 | 说明”", template: "模板", theme: "配色",
diff --git a/packages/shared/src/infographic.test.mjs b/packages/shared/src/infographic.test.mjs
index c290bc1c..4a4ba634 100644
--- a/packages/shared/src/infographic.test.mjs
+++ b/packages/shared/src/infographic.test.mjs
@@ -25,6 +25,19 @@ describe("infographic note format", () => {
expect(getInfographicSummary("regular note")).toEqual({ infographic: false });
});
+ test("keeps AI revision requests with the infographic across reads", () => {
+ const document = {
+ schemaVersion: 1,
+ syntax: "infographic sequence-steps-simple\ndata\n title 发布流程",
+ history: [
+ { id: "one", prompt: "做一个发布流程图", createdAt: "2026-09-24T10:00:00.000Z", kind: "generated", resultTitle: "发布流程" },
+ { id: "two", prompt: "把第二步改成审核", createdAt: "2026-09-24T10:01:00.000Z", kind: "refined", resultTitle: "发布流程", undoneAt: "2026-09-24T10:02:00.000Z" },
+ ],
+ };
+ expect(parseInfographicDocument(serializeInfographicDocument(document))).toEqual(document);
+ expect(parseInfographicDocument(serializeInfographicDocument({ ...document, history: [{ ...document.history[0], prompt: 42 }] }))).toBeNull();
+ });
+
test("infographic syntax and visual diagram IR keep separate envelopes", () => {
const infographic = serializeInfographicDocument({ schemaVersion: 1, syntax: "infographic sequence-steps-simple\ndata\n sequences\n - label 开始" });
const diagram = serializeDiagramDocument(createDefaultDiagramDocument("flowchart"));
diff --git a/packages/shared/src/infographic.ts b/packages/shared/src/infographic.ts
index d9858643..15b8f427 100644
--- a/packages/shared/src/infographic.ts
+++ b/packages/shared/src/infographic.ts
@@ -8,6 +8,16 @@ export type InfographicDocument = {
schemaVersion: typeof INFOGRAPHIC_SCHEMA_VERSION;
// AntV Infographic's native source, separate from the visual diagram IR.
syntax: string;
+ history?: InfographicConversationTurn[];
+};
+
+export type InfographicConversationTurn = {
+ id: string;
+ prompt: string;
+ createdAt: string;
+ kind: "generated" | "refined";
+ resultTitle: string;
+ undoneAt?: string;
};
export const createDefaultInfographicDocument = (): InfographicDocument => ({
@@ -38,7 +48,15 @@ export const parseInfographicDocument = (markdown: string | null | undefined): I
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
const document = value as Record<string, unknown>;
if (document.schemaVersion !== INFOGRAPHIC_SCHEMA_VERSION || typeof document.syntax !== "string" || document.syntax.length > 200_000) return null;
- return { schemaVersion: INFOGRAPHIC_SCHEMA_VERSION, syntax: document.syntax };
+ const history = document.history;
+ if (history !== undefined && (!Array.isArray(history) || !history.every((turn: unknown) => {
+ if (!turn || typeof turn !== "object" || Array.isArray(turn)) return false;
+ const value = turn as Record<string, unknown>;
+ return typeof value.id === "string" && typeof value.prompt === "string" && value.prompt.length <= 1000
+ && typeof value.createdAt === "string" && (value.kind === "generated" || value.kind === "refined")
+ && typeof value.resultTitle === "string" && (value.undoneAt === undefined || typeof value.undoneAt === "string");
+ }))) return null;
+ return { schemaVersion: INFOGRAPHIC_SCHEMA_VERSION, syntax: document.syntax, ...(history ? { history: history as InfographicConversationTurn[] } : {}) };
} catch {
return null;
}