Skip to content

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

fix: preserve infographic drafts during synchronization

tianma-if238b2c8628d6
diff --git a/apps/web/src/components/InfographicEditorPane.tsx b/apps/web/src/components/InfographicEditorPane.tsx
index e38c0e3c..4f785dc9 100644
--- a/apps/web/src/components/InfographicEditorPane.tsx
+++ b/apps/web/src/components/InfographicEditorPane.tsx
@@ -20,6 +20,7 @@ import { MemoEditorFocusModeButton, MemoEditorTopRowLeading } from "@/components
import { MEMO_EDITOR_METADATA_ROW_CLASS_NAME, MEMO_EDITOR_TOP_ROW_CLASS_NAME, nextTitleStatusClearance } from "@/components/MemoEditorChromeDensity";
import { MemoEditorToolbarDivider } from "@/components/MemoEditorToolbarChrome";
import { MemoTitleInput } from "@/components/MemoTitleInput";
+import { createEditorInstanceMemoIdentity, reconcileEditorInstanceMemoIdentity, remapEditorInstanceMemoIdentity } from "@/components/editor/editor-instance-identity";
import { api } from "@/lib/api";
import { readAiSidebarAdapter, readAiSidebarSource } from "@/lib/desktop-acp";
import { buildInfographicLocalAgentContext, collectInfographicLocalAgentText, infographicLocalAgentErrorKey, parseInfographicLocalReply } from "@/lib/infographic-local-agent";
@@ -30,6 +31,8 @@ import { infographicSessionHistory, infographicSessionStamp, infographicSessionT
import { canvasToPngBlob, downloadBlob, frameInfographicExportSvg, infographicExportBasename, rasterizeInfographicSvg, readInfographicSheetColor } from "@/lib/infographic-image-export";
import { buildInfographicSyntax, buildOfficialInfographicSyntax, infographicAgentCandidates, infographicNoteTitleIsAutomatic, infographicSyntaxTitle, INFOGRAPHIC_TEMPLATES, nextInfographicNoteTitle, parseGeneratedOfficialData, type InfographicItem } from "@/lib/infographic-generation";
import { statusSettleMotion } from "@/lib/motion";
+import { advanceInfographicSyncBase, classifyInfographicUpdate, infographicEditorSnapshot, infographicMemoSnapshot } from "@/lib/infographic-sync";
+import { MEMO_ID_REMAPPED_EVENT, MEMO_SYNC_ACKNOWLEDGED_EVENT } from "@/lib/sync-events";
import type { EdgeEverRepository } from "@/lib/repository";
import { cn, parseTagsText } from "@/lib/utils";
@@ -192,7 +195,21 @@ const applyOfficialVisualTextChange = (syntax: string, payload: VisualTextChange
return buildOfficialInfographicSyntax(parsed.options.template, data, editable.dark);
};
-export default function InfographicEditorPane({
+export default function InfographicEditorPane(props: Props) {
+ const identity = useRef(createEditorInstanceMemoIdentity(props.memo.id));
+ identity.current = reconcileEditorInstanceMemoIdentity(identity.current, props.memo.id);
+ useLayoutEffect(() => {
+ const remap = (event: Event) => {
+ identity.current = remapEditorInstanceMemoIdentity(identity.current, (event as CustomEvent<ReadonlyMap<string, string>>).detail);
+ };
+ window.addEventListener(MEMO_ID_REMAPPED_EVENT, remap);
+ return () => window.removeEventListener(MEMO_ID_REMAPPED_EVENT, remap);
+ }, []);
+ // A real note switch resets state; a temporary ID receiving its durable ID does not.
+ return <InfographicEditorSession key={identity.current.instanceKey} {...props} />;
+}
+
+function InfographicEditorSession({
memo,
notebooks,
repository,
@@ -232,7 +249,7 @@ export default function InfographicEditorPane({
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 ?? "", parsed?.history ?? [], initialTags, parsed?.activeSessionId ?? null]));
+ const [savedSnapshot, setSavedSnapshot] = useState(() => infographicMemoSnapshot(memo) ?? "");
const [savedHistorySnapshot, setSavedHistorySnapshot] = useState(JSON.stringify(parsed?.history ?? []));
const [galleryDialogOpen, setGalleryDialogOpen] = useState(false);
const [mobileNotebookSheetOpen, setMobileNotebookSheetOpen] = useState(false);
@@ -246,17 +263,80 @@ export default function InfographicEditorPane({
const generationControllerRef = useRef<AbortController | null>(null);
const handledAiAssistantOpenTokenRef = useRef(aiAssistantOpenToken);
const memoRef = useRef(memo);
+ const mountedRef = useRef(true);
+ const savingRef = useRef(false);
+ const savedSnapshotRef = useRef(savedSnapshot);
+ const acknowledgedMemoRef = useRef<MemoDetail | null>(null);
+ const deferredBaselineRef = useRef<string | null>(null);
+ const [visualEditing, setVisualEditing] = useState(false);
const tagsRef = useRef(initialTags);
const saveRef = useRef<() => boolean | Promise<boolean>>(() => false);
const snapshotSessionId = readOnly ? (parsed?.activeSessionId ?? null) : activeSessionId;
- const snapshot = JSON.stringify([title, syntax, history, tagsText, snapshotSessionId]);
+ const snapshot = infographicEditorSnapshot(title, { schemaVersion: 1, syntax, history, ...(snapshotSessionId ? { activeSessionId: snapshotSessionId } : {}) }, parseTagsText(tagsText));
const notebookOptions = useMemo(() => getNotebookMoveOptions(notebooks), [notebooks]);
const dirty = snapshot !== savedSnapshot;
const historyDirty = JSON.stringify(history) !== savedHistorySnapshot;
useEffect(() => {
+ mountedRef.current = true;
+ const remap = (event: Event) => {
+ const mappings = (event as CustomEvent<ReadonlyMap<string, string>>).detail;
+ const id = mappings.get(memoRef.current.id);
+ if (!id) return;
+ memoRef.current = { ...memoRef.current, id };
+ if (sessionRef.current) sessionRef.current = { ...sessionRef.current, id: `local-edit:${id}`, memoId: id };
+ };
+ const acknowledged = (event: Event) => {
+ const receipt = (event as CustomEvent<MemoDetail>).detail;
+ const advanced = advanceInfographicSyncBase(memoRef.current, receipt);
+ if (advanced !== memoRef.current) acknowledgedMemoRef.current = receipt;
+ memoRef.current = advanced;
+ };
+ window.addEventListener(MEMO_ID_REMAPPED_EVENT, remap);
+ window.addEventListener(MEMO_SYNC_ACKNOWLEDGED_EVENT, acknowledged);
+ return () => {
+ mountedRef.current = false;
+ window.removeEventListener(MEMO_ID_REMAPPED_EVENT, remap);
+ window.removeEventListener(MEMO_SYNC_ACKNOWLEDGED_EVENT, acknowledged);
+ };
+ }, []);
+
+ useEffect(() => {
+ // A locally saved draft that deferred a remote change still owns its old
+ // conflict base. Becoming locally clean must not authorize a remote rebase.
+ const deferred = deferredBaselineRef.current;
+ const hasDraft = snapshot !== savedSnapshotRef.current || generating || visualEditing
+ || (deferred !== null && snapshot !== deferred);
+ const update = classifyInfographicUpdate(memo, memoRef.current, savedSnapshotRef.current, hasDraft, savingRef.current, acknowledgedMemoRef.current);
+ if (update === "ignore") return;
+ if (update === "defer") {
+ deferredBaselineRef.current ??= savedSnapshotRef.current;
+ return;
+ }
+ if (update === "rebase") {
+ memoRef.current = advanceInfographicSyncBase(memoRef.current, memo);
+ deferredBaselineRef.current = null;
+ return;
+ }
+ const incoming = parseInfographicDocument(memo.contentMarkdown)!;
+ const nextSnapshot = infographicMemoSnapshot(memo)!;
memoRef.current = memo;
- }, [memo]);
+ deferredBaselineRef.current = null;
+ savedSnapshotRef.current = nextSnapshot;
+ tagsRef.current = memo.tags.join(", ");
+ setTitle(memo.title ?? "");
+ setTagsText(tagsRef.current);
+ setSyntax(incoming.syntax);
+ setHistory(incoming.history ?? []);
+ setActiveSessionId(incoming.activeSessionId ?? null);
+ setSavedSnapshot(nextSnapshot);
+ setSavedHistorySnapshot(JSON.stringify(incoming.history ?? []));
+ setPreviousGeneration(null);
+ titleEditedByUserRef.current = !infographicNoteTitleIsAutomatic({
+ noteTitle: memo.title ?? "", graphicTitle: infographicSyntaxTitle(incoming.syntax),
+ defaultTitle: t("infographic.name"), earlierTitles: (incoming.history ?? []).map((turn) => turn.resultTitle),
+ });
+ }, [memo, snapshot, generating, visualEditing, saving, t]);
useEffect(() => () => generationControllerRef.current?.abort(), []);
@@ -275,16 +355,17 @@ export default function InfographicEditorPane({
useEffect(() => {
if (readOnly) return;
let cancelled = false;
- if (requiresLocalEditSession(memo)) {
- sessionRef.current = createLocalEditSession(memo);
+ const currentMemo = memoRef.current;
+ if (requiresLocalEditSession(currentMemo)) {
+ sessionRef.current = createLocalEditSession(currentMemo);
setReady(true);
return;
}
- void api.createMemoEditSession(memo.id).then(({ editSession }) => {
+ void api.createMemoEditSession(currentMemo.id).then(({ editSession }) => {
if (!cancelled) { sessionRef.current = editSession; setReady(true); }
}).catch(() => { if (!cancelled) setError(t("infographic.sessionError")); });
return () => { cancelled = true; };
- }, [memo.id, readOnly, t]);
+ }, [memo.id, memo.contentHash, memo.revision, readOnly, t]);
useEffect(() => {
setPreviewReady(false);
@@ -398,7 +479,7 @@ export default function InfographicEditorPane({
};
const save = async () => {
- if (readOnly || saving || !dirty || !ready || !sessionRef.current) return false;
+ if (readOnly || savingRef.current || !dirty || !ready || !sessionRef.current || visualEditing) return false;
if (syntax.trim() && (renderError || !previewReady || !instanceRef.current)) {
setError(renderError ?? t("infographic.invalidSyntax"));
return false;
@@ -406,6 +487,7 @@ export default function InfographicEditorPane({
const currentMemo = memoRef.current;
const currentSnapshot = snapshot;
const document: InfographicDocument = { schemaVersion: 1, syntax, ...(history.length ? { history } : {}), ...(activeSessionId ? { activeSessionId } : {}) };
+ savingRef.current = true;
setSaving(true); setError(null);
try {
const result = await repository.updateMemo(currentMemo, {
@@ -417,15 +499,24 @@ export default function InfographicEditorPane({
contentMarkdown: serializeInfographicDocument(document),
tags: parseTagsText(tagsRef.current),
});
- memoRef.current = result.memo;
+ if (!mountedRef.current) {
+ await onSaved(result.memo);
+ return true;
+ }
+ const savedMemo = { ...result.memo, id: memoRef.current.id };
+ const acknowledgedBase = memoRef.current;
+ memoRef.current = acknowledgedBase.revision > savedMemo.revision
+ ? { ...savedMemo, revision: acknowledgedBase.revision, contentHash: acknowledgedBase.contentHash, updatedAt: acknowledgedBase.updatedAt }
+ : savedMemo;
+ savedSnapshotRef.current = currentSnapshot;
setSavedSnapshot(currentSnapshot);
setSavedHistorySnapshot(JSON.stringify(history));
- await onSaved(result.memo);
+ await onSaved(memoRef.current);
return true;
} catch (caught) {
- setError(caught instanceof Error ? caught.message : t("infographic.saveError"));
+ if (mountedRef.current) setError(caught instanceof Error ? caught.message : t("infographic.saveError"));
return false;
- } finally { setSaving(false); }
+ } finally { savingRef.current = false; if (mountedRef.current) setSaving(false); }
};
saveRef.current = () => save();
@@ -453,10 +544,17 @@ export default function InfographicEditorPane({
};
useEffect(() => {
- if (!dirty || !ready || readOnly || saving || generating || renderError || (syntax.trim() && !previewReady)) return;
+ if (!dirty || !ready || readOnly || saving || generating || visualEditing || renderError || (syntax.trim() && !previewReady)) return;
const timer = window.setTimeout(() => saveRef.current(), historyDirty ? 0 : 1200);
return () => window.clearTimeout(timer);
- }, [dirty, ready, readOnly, saving, generating, renderError, previewReady, snapshot, syntax, historyDirty]);
+ }, [dirty, ready, readOnly, saving, generating, visualEditing, renderError, previewReady, snapshot, syntax, historyDirty]);
+
+ useEffect(() => {
+ if (readOnly || (!dirty && !visualEditing)) return;
+ const warn = (event: BeforeUnloadEvent) => event.preventDefault();
+ window.addEventListener("beforeunload", warn);
+ return () => window.removeEventListener("beforeunload", warn);
+ }, [dirty, readOnly, visualEditing]);
useLayoutEffect(() => {
const titleSlot = headerTitleSlot;
@@ -628,7 +726,7 @@ export default function InfographicEditorPane({
};
const previewUsesLightSheet = Boolean(syntax.trim()) && syntax.split("\n")[1] !== "theme dark";
- const saveStatus = saving ? "saving" : dirty ? "unsaved" : "saved";
+ const saveStatus = saving ? "saving" : dirty || visualEditing ? "unsaved" : "saved";
const saveLabel = t(`editor.saveState.${saveStatus}`);
const saveStatusClassName = saveStatus === "saved" ? "text-slate-400" : "bg-slate-100 text-slate-700";
const viewingSessionId = resolveInfographicSessionId(history, activeSessionId);
@@ -654,7 +752,16 @@ export default function InfographicEditorPane({
},
};
- return <div className="relative flex h-full min-h-0 min-w-0 bg-card text-foreground">
+ return <div className="relative flex h-full min-h-0 min-w-0 bg-card text-foreground"
+ onFocusCapture={(event) => {
+ if (containerRef.current?.contains(event.target) && event.target.closest('[contenteditable="true"]')) setVisualEditing(true);
+ }}
+ onBlurCapture={() => {
+ queueMicrotask(() => {
+ if (mountedRef.current) setVisualEditing(Boolean(containerRef.current?.querySelector('[contenteditable="true"]')));
+ });
+ }}
+ >
<div className="relative flex h-full min-h-0 min-w-0 flex-1 flex-col">
<header className="shrink-0 border-b border-slate-200 bg-card">
<div className={cn(MEMO_EDITOR_TOP_ROW_CLASS_NAME, "border-b-0")}>
diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsx
index 0c9a65f7..86f9ee5f 100644
--- a/apps/web/src/components/WorkspaceApp.tsx
+++ b/apps/web/src/components/WorkspaceApp.tsx
@@ -3815,7 +3815,6 @@ export const WorkspaceApp = ({
/>
) : selectedMemo && selectedInfographicNote ? (
<InfographicEditorPane
- key={selectedMemo.id}
memo={selectedMemo}
notebooks={notebooks}
repository={repository}
diff --git a/apps/web/src/lib/infographic-sync.test.mjs b/apps/web/src/lib/infographic-sync.test.mjs
new file mode 100644
index 00000000..4a2d25a0
--- /dev/null
+++ b/apps/web/src/lib/infographic-sync.test.mjs
@@ -0,0 +1,51 @@
+import { expect, test } from "bun:test";
+import { serializeInfographicDocument } from "@edgeever/shared";
+import { advanceInfographicSyncBase, classifyInfographicUpdate, infographicEditorSnapshot, infographicMemoSnapshot } from "./infographic-sync";
+
+const document = { schemaVersion: 1, syntax: "graphic", history: [] };
+const base = { id: "memo", title: "Saved", tags: ["work"], contentMarkdown: serializeInfographicDocument(document), revision: 3, contentHash: "base", updatedAt: "2026-10-31T00:00:00Z" };
+const receipt = { ...base, revision: 4, contentHash: "ack", updatedAt: "2026-10-31T00:01:00Z" };
+const saved = infographicMemoSnapshot(base);
+
+test("old receipts advance only the base and cannot confirm a newer title, graphic, tags or conversation", () => {
+ const draft = { ...base, title: "New title", tags: ["new"], contentMarkdown: serializeInfographicDocument({ ...document, syntax: "new graphic", activeSessionId: "new-session", history: [{ id: "turn", prompt: "change", createdAt: "now", kind: "generated", resultTitle: "new" }] }) };
+ const advanced = advanceInfographicSyncBase(draft, receipt);
+ expect(advanced).toEqual({ ...draft, revision: 4, contentHash: "ack", updatedAt: receipt.updatedAt });
+ expect(infographicMemoSnapshot(advanced)).not.toBe(saved);
+ expect(classifyInfographicUpdate(receipt, base, saved, true, false)).toBe("rebase");
+ expect(base.revision).toBe(3);
+});
+
+test("real remote changes apply only to idle editors and preserve an editing draft's original base", () => {
+ const remote = { ...receipt, contentMarkdown: serializeInfographicDocument({ ...document, syntax: "remote graphic" }) };
+ expect(classifyInfographicUpdate(remote, base, saved, false, false)).toBe("replace");
+ expect(classifyInfographicUpdate(remote, base, saved, true, false)).toBe("defer");
+ expect(classifyInfographicUpdate(remote, base, saved, false, true)).toBe("defer");
+ expect(classifyInfographicUpdate(remote, base, saved, true, true)).toBe("defer");
+});
+
+test("a receipt cannot replace a successor draft that has already been saved locally", () => {
+ const successor = { ...base, title: "Already saved locally", updatedAt: "2026-10-31T00:02:00Z" };
+ const advanced = advanceInfographicSyncBase(successor, receipt);
+ const successorSnapshot = infographicMemoSnapshot(successor);
+ expect(classifyInfographicUpdate(receipt, advanced, successorSnapshot, false, false, receipt)).toBe("rebase");
+ expect(advanced.title).toBe(successor.title);
+ expect(infographicMemoSnapshot(advanced)).toBe(successorSnapshot);
+ // Matching revision/hash alone cannot disguise another device's metadata edit.
+ expect(classifyInfographicUpdate({ ...receipt, title: "Remote title" }, advanced, successorSnapshot, true, false, receipt)).toBe("defer");
+});
+
+test("rejects stale or unrelated snapshots and receipts", () => {
+ expect(classifyInfographicUpdate(base, receipt, saved, false, false)).toBe("ignore");
+ expect(classifyInfographicUpdate({ ...receipt, id: "other" }, base, saved, false, false)).toBe("ignore");
+ expect(advanceInfographicSyncBase(receipt, base)).toBe(receipt);
+ expect(advanceInfographicSyncBase(base, { ...receipt, id: "other" })).toBe(base);
+ expect(classifyInfographicUpdate({ ...receipt, contentMarkdown: "invalid" }, base, saved, false, false)).toBe("ignore");
+});
+
+test("equivalent tag order and optional empty history do not create false drafts", () => {
+ expect(infographicEditorSnapshot("Title", document, ["b", "a"]))
+ .toBe(infographicEditorSnapshot("Title", { schemaVersion: 1, syntax: document.syntax }, ["a", "b"]));
+ expect(infographicEditorSnapshot("Title", { ...document, activeSessionId: "another-session" }, ["a", "b"]))
+ .not.toBe(infographicEditorSnapshot("Title", document, ["a", "b"]));
+});
diff --git a/apps/web/src/lib/infographic-sync.ts b/apps/web/src/lib/infographic-sync.ts
new file mode 100644
index 00000000..2ed1909a
--- /dev/null
+++ b/apps/web/src/lib/infographic-sync.ts
@@ -0,0 +1,36 @@
+import { parseInfographicDocument, type InfographicDocument, type MemoDetail } from "@edgeever/shared";
+import { shouldAcceptRemoteMemoDetail } from "./memo-detail-freshness";
+
+export const infographicEditorSnapshot = (title: string, document: InfographicDocument, tags: string[]) =>
+ JSON.stringify([title, document.syntax, document.history ?? [], [...tags].sort(), document.activeSessionId ?? null]);
+
+export const infographicMemoSnapshot = (memo: MemoDetail) => {
+ const document = parseInfographicDocument(memo.contentMarkdown);
+ return document ? infographicEditorSnapshot(memo.title ?? "", document, memo.tags) : null;
+};
+
+/** A receipt updates concurrency metadata only; the editor owns its current draft. */
+export const advanceInfographicSyncBase = (base: MemoDetail, receipt: MemoDetail): MemoDetail =>
+ receipt.id === base.id && shouldAcceptRemoteMemoDetail(base, receipt)
+ ? { ...base, revision: receipt.revision, contentHash: receipt.contentHash, updatedAt: receipt.updatedAt }
+ : base;
+
+export const classifyInfographicUpdate = (
+ incoming: MemoDetail,
+ base: MemoDetail,
+ savedSnapshot: string,
+ hasDraft: boolean,
+ saving: boolean,
+ acknowledged?: MemoDetail | null,
+) => {
+ if (incoming.id !== base.id || !shouldAcceptRemoteMemoDetail(base, incoming)) return "ignore";
+ if (saving) return "defer";
+ const incomingSnapshot = infographicMemoSnapshot(incoming);
+ if (incomingSnapshot === null) return "ignore";
+ // A receipt can arrive after a successor draft was already saved locally.
+ // It still confirms only its own snapshot, even though that draft is clean.
+ if (acknowledged && incoming.revision === acknowledged.revision && incoming.contentHash === acknowledged.contentHash
+ && incomingSnapshot === infographicMemoSnapshot(acknowledged)) return "rebase";
+ if (incomingSnapshot === savedSnapshot) return "rebase";
+ return hasDraft ? "defer" : "replace";
+};
diff --git a/docs/changes/2026-10-31-infographic-sync-drafts.md b/docs/changes/2026-10-31-infographic-sync-drafts.md
new file mode 100644
index 00000000..91d5100c
--- /dev/null
+++ b/docs/changes/2026-10-31-infographic-sync-drafts.md
@@ -0,0 +1,22 @@
+# Preserve infographic drafts during synchronization
+
+## Findings and scope
+
+- The infographic editor accepted every memo prop as its next save base without reconciling the displayed document. A remote update could remain invisible, then authorize uploading an older graphic with the remote revision/hash.
+- The workspace keyed the editor by the raw memo ID. A temporary-to-server ID mapping recreated the editor and discarded input still waiting for autosave. Both the idle remote-refresh failure and the title reset were reproduced in browser regressions before the fix.
+- Local saves already captured their submitted snapshot. Retain that behavior; a delayed receipt must never confirm later edits or replace a successor already saved locally.
+
+## Change and risk
+
+- Reuse the existing logical editor identity helpers. Real note switches reset the editor; ID mappings preserve its input, focus, conversation and canvas.
+- Separate saved snapshots from synchronization metadata. This device's receipts advance only revision/hash/time. Stale or unrelated snapshots are ignored. Genuine remote updates apply when idle; drafts, generation and active inline editing defer them without adopting the remote concurrency base.
+- Returning to the original baseline releases a deferred update. Saving a conflicting draft locally does not release it or silently authorize an overwrite.
+- Bind async local-save completion to its mounted editor. Preserve newer acknowledged revisions and confirm only the submitted snapshot. Track active inline editing before its text is committed by AntV.
+- Changes are limited to the shared Web/desktop infographic editor and its workspace mounting. No schema, synchronization protocol, native host, installer or updater changes. Roll back these product changes to revert; no migration is needed.
+
+## Verification boundaries
+
+- Focused unit coverage includes stale receipts, locally saved successors, real remote changes, conversation/session snapshots and tag normalization.
+- Browser regressions use real local API/storage: delayed receipts with title/tag/inline edits and reopening; idle remote updates and conflicting drafts; temporary-ID mapping, focus and reopening; a locally queued successor receiving an older receipt.
+- Existing text and diagram synchronization regressions are also run. Required checks: `bun run typecheck`, `bun run typecheck:mobile`, `bun run build:web`.
+- Browser checks do not establish Windows/macOS/Linux native functionality, a native old-to-new-version transition, or installer/updater compatibility. Those native validations remain unperformed for this change.
diff --git a/docs/changes/2026-10-31-infographic-sync-drafts.zh-CN.md b/docs/changes/2026-10-31-infographic-sync-drafts.zh-CN.md
new file mode 100644
index 00000000..51115677
--- /dev/null
+++ b/docs/changes/2026-10-31-infographic-sync-drafts.zh-CN.md
@@ -0,0 +1,22 @@
+# 保留信息图同步期间的草稿
+
+## 问题与范围
+
+- 信息图编辑器把每次收到的笔记属性直接作为下次保存基线,却不协调屏幕中的文档。远端更新可能不可见,随后旧图形却带着远端新版本号和哈希上传。
+- 工作区使用原始笔记 ID 作为编辑器键。临时 ID 映射到服务端 ID 时会重建编辑器,丢弃仍在等待自动保存的输入。修复前的浏览器回归已复现空闲远端刷新失效和标题回退。
+- 本地保存原本已经捕获提交时的快照。保留该行为;延迟回执不得确认后续编辑,也不得替换已经保存到本地的后继草稿。
+
+## 修复与风险
+
+- 复用现有逻辑编辑器身份辅助函数。真正切换笔记时重置编辑器;ID 映射时保留输入、焦点、对话和画布。
+- 分离已保存快照与同步元数据。本设备回执只推进版本号、哈希和时间,忽略陈旧或其他笔记的快照。真正的远端更新在空闲时应用;有草稿、生成任务或行内编辑时暂缓,不采用远端并发基线。
+- 草稿回到原始基线后继续应用暂缓的更新。把冲突草稿保存到本地,不会解除保护或默许覆盖远端。
+- 异步本地保存回执绑定其仍挂载的编辑器,保留更新的已确认版本,只确认本次提交的快照。在 AntV 提交行内文字前跟踪正在进行的编辑。
+- 产品改动仅涉及 Web/桌面共用信息图编辑器及工作区挂载方式,不修改数据库结构、同步协议、原生宿主、安装器或升级器。撤销这些产品代码即可回滚,无需迁移。
+
+## 验证边界
+
+- 定向单元测试覆盖陈旧回执、已存入本地的后继草稿、真正的远端修改、对话和会话快照、标签规范化。
+- 浏览器回归使用真实本地 API 和存储,覆盖:延迟回执期间编辑标题、标签和行内文字并重开;空闲远端更新及冲突草稿;临时 ID 映射、焦点和重开;已入本地队列的后继草稿收到旧回执。
+- 同时运行已有文本和图表同步回归。必需检查:`bun run typecheck`、`bun run typecheck:mobile`、`bun run build:web`。
+- 浏览器结果不等于 Windows/macOS/Linux 原生功能、原生旧版到新版链路、安装器或自动升级兼容性验证。本次尚未完成这些原生验证。
diff --git a/tests/e2e/infographic-sync-race.spec.ts b/tests/e2e/infographic-sync-race.spec.ts
new file mode 100644
index 00000000..076cc639
--- /dev/null
+++ b/tests/e2e/infographic-sync-race.spec.ts
@@ -0,0 +1,265 @@
+import { expect, test, type Page } from "@playwright/test";
+import { infographicFallbackMarkdown, serializeInfographicDocument } from "../../packages/shared/src/infographic";
+import { markdownToDoc } from "../../packages/shared/src/content";
+
+const syntax = (heading: string) => `infographic list-row-simple-horizontal-arrow\ndata\n title ${heading}\n lists\n - label First\n - label Second`;
+const content = (heading: string) => {
+ const document = { schemaVersion: 1 as const, syntax: syntax(heading) };
+ return { contentMarkdown: serializeInfographicDocument(document), contentJson: markdownToDoc(infographicFallbackMarkdown(document)) };
+};
+const openMemo = async (page: Page, id: string, title: string) => {
+ await page.goto("/");
+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();
+ await page.getByPlaceholder("搜索笔记").fill(title);
+ await page.locator(`[data-memo-id="${id}"]`).locator("button").first().click();
+ await expect(page.locator(".edgeever-infographic-preview svg")).toBeVisible();
+};
+const createMemo = async (page: Page, title: string) => {
+ const { notebooks } = await (await page.request.get("/api/v1/notebooks")).json();
+ const response = await page.request.post("/api/v1/memos", { data: { notebookId: notebooks[0].id, title, ...content("Original graphic") } });
+ expect(response.status()).toBe(201);
+ return (await response.json()).memo;
+};
+const changeRemote = async (page: Page, id: string, heading: string) => {
+ const { editSession } = await (await page.request.post(`/api/v1/memos/${id}/edit-sessions`)).json();
+ const response = await page.request.patch(`/api/v1/memos/${id}`, { data: {
+ expectedRevision: editSession.baseRevision, expectedContentHash: editSession.baseContentHash,
+ editSessionId: editSession.id, ...content(heading),
+ } });
+ expect(response.ok(), await response.text()).toBe(true);
+ const { memo } = await response.json();
+ await page.evaluate((detail) => window.dispatchEvent(new CustomEvent("edgeever:memo-detail-refreshed", { detail })), memo);
+ return memo;
+};
+const removeMemo = async (page: Page, id: string) => {
+ await page.request.delete(`/api/v1/memos/${id}`);
+ await page.request.delete(`/api/v1/memos/${id}?permanent=1`);
+};
+const queuedUpdate = (page: Page, id: string) => page.evaluate((memoId) => new Promise<{ status: string; payload: { expectedRevision: number; expectedContentHash: string; title: string } } | undefined>((resolve, reject) => {
+ const open = indexedDB.open("edgeever-local");
+ open.onerror = () => reject(open.error);
+ open.onsuccess = () => {
+ const database = open.result;
+ const request = database.transaction("syncQueue", "readonly").objectStore("syncQueue").get(`memo.update:${memoId}`);
+ request.onerror = () => { database.close(); reject(request.error); };
+ request.onsuccess = () => { database.close(); resolve(request.result); };
+ };
+}), id);
+
+test("infographic keeps newer title, tags and inline text when an older save is acknowledged", async ({ page }) => {
+ const marker = `infographic-ack-${Date.now()}`;
+ const memo = await createMemo(page, marker);
+ let release!: () => void;
+ let stored!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const firstStored = new Promise<void>((resolve) => { stored = resolve; });
+ let updates = 0;
+ await page.route(`**/api/v1/memos/${memo.id}`, async (route) => {
+ if (route.request().method() !== "PATCH" || ++updates !== 1) return route.continue();
+ const response = await route.fetch();
+ expect(response.ok(), await response.text()).toBe(true);
+ stored();
+ await gate;
+ await route.fulfill({ response });
+ });
+ try {
+ await openMemo(page, memo.id, marker);
+ const title = page.getByRole("textbox", { name: "信息图", exact: true });
+ const preview = page.locator(".edgeever-infographic-preview");
+ await title.fill(`${marker}-first`);
+ await expect.poll(async () => (await queuedUpdate(page, memo.id))?.payload.title).toBe(`${marker}-first`);
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));
+ await firstStored;
+ await page.clock.install();
+ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1_000));
+ await title.fill(`${marker}-newer`);
+ await page.getByRole("button", { name: "选择笔记标签", exact: true }).click();
+ const dialog = page.getByRole("dialog");
+ await dialog.getByRole("textbox").fill(marker);
+ await dialog.locator('button[type="submit"]').click();
+ await page.keyboard.press("Escape");
+ await preview.locator('[data-element-type="title"]').dblclick();
+ const inline = preview.locator('[contenteditable="true"]');
+ await inline.fill("New inline draft");
+ const originalSvg = await preview.locator("svg").elementHandle();
+ const completed = page.evaluate(() => new Promise<void>((resolve) => window.addEventListener("edgeever:sync-completed", () => resolve(), { once: true })));
+ release();
+ await completed;
+ await expect(title).toHaveValue(`${marker}-newer`);
+ await expect(inline).toHaveText("New inline draft");
+ await expect(inline).toBeFocused();
+ expect(await originalSvg!.evaluate((svg) => svg.isConnected)).toBe(true);
+ await expect(page.getByText("未保存", { exact: true }).last()).toBeVisible();
+ await title.click();
+ const nextSaved = page.waitForResponse((response) => response.request().method() === "PATCH"
+ && new URL(response.url()).pathname === `/api/v1/memos/${memo.id}`
+ && response.request().postDataJSON()?.contentMarkdown?.includes("New inline draft"));
+ await page.clock.runFor(1_600);
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));
+ const response = await nextSaved;
+ expect(response.ok(), await response.text()).toBe(true);
+ const { memo: saved } = await (await page.request.get(`/api/v1/memos/${memo.id}`)).json();
+ expect(saved.title).toBe(`${marker}-newer`);
+ expect(saved.tags).toContain(marker);
+ expect(saved.contentMarkdown).toContain("New inline draft");
+ await page.clock.resume();
+ await openMemo(page, memo.id, `${marker}-newer`);
+ await expect(preview).toContainText("New inline draft");
+ await expect(title).toHaveValue(`${marker}-newer`);
+ } finally {
+ release();
+ await page.unroute(`**/api/v1/memos/${memo.id}`);
+ await removeMemo(page, memo.id);
+ }
+});
+
+test("infographic applies idle remote changes but retains a draft's original conflict base", async ({ page }) => {
+ const marker = `infographic-remote-${Date.now()}`;
+ const memo = await createMemo(page, marker);
+ try {
+ await openMemo(page, memo.id, marker);
+ const preview = page.locator(".edgeever-infographic-preview");
+ await changeRemote(page, memo.id, "Remote while idle");
+ await expect(preview).toContainText("Remote while idle");
+ await page.clock.install();
+ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1_000));
+ const title = page.getByRole("textbox", { name: "信息图", exact: true });
+ await title.fill(`${marker}-canceled`);
+ await changeRemote(page, memo.id, "Remote after undo");
+ await page.clock.runFor(50);
+ await expect(preview).toContainText("Remote while idle");
+ await title.fill(marker);
+ await page.clock.runFor(350);
+ await expect(preview).toContainText("Remote after undo");
+ // Even unchanged active inline text must not be destroyed by a refresh.
+ await preview.locator('[data-element-type="title"]').dblclick();
+ await changeRemote(page, memo.id, "Remote after blur");
+ await page.clock.runFor(50);
+ await expect(preview.locator('[contenteditable="true"]')).toBeFocused();
+ await expect(preview).toContainText("Remote after undo");
+ await title.click();
+ await page.clock.runFor(350);
+ await expect.poll(async () => {
+ await page.clock.runFor(100);
+ return preview.textContent();
+ }).toContain("Remote after blur");
+ await title.fill(`${marker}-draft`);
+ const incoming = await changeRemote(page, memo.id, "Remote during draft");
+ await page.clock.runFor(50);
+ await expect(preview).toContainText("Remote after blur");
+ await page.clock.runFor(1_300);
+ await expect.poll(async () => (await queuedUpdate(page, memo.id))?.payload.title).toBe(`${marker}-draft`);
+ const queued = (await queuedUpdate(page, memo.id))!;
+ expect(queued.payload.expectedRevision).toBe(incoming.revision - 1);
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));
+ await expect.poll(async () => (await queuedUpdate(page, memo.id))?.status).toBe("conflict");
+ // A newer remote base must never authorize uploading the older graphic.
+ const { memo: stored } = await (await page.request.get(`/api/v1/memos/${memo.id}`)).json();
+ expect(stored.contentMarkdown).toBe(incoming.contentMarkdown);
+ await expect(page.getByRole("textbox", { name: "信息图", exact: true })).toHaveValue(`${marker}-draft`);
+ } finally { await removeMemo(page, memo.id); }
+});
+
+test("infographic does not roll back an already queued successor when the older receipt reaches the editor", async ({ page }) => {
+ const marker = `infographic-queued-${Date.now()}`;
+ const memo = await createMemo(page, marker);
+ let release!: () => void;
+ let stored!: () => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const firstStored = new Promise<void>((resolve) => { stored = resolve; });
+ let updates = 0;
+ let receipt: unknown;
+ await page.route(`**/api/v1/memos/${memo.id}`, async (route) => {
+ if (route.request().method() !== "PATCH" || ++updates !== 1) return route.continue();
+ const response = await route.fetch();
+ expect(response.ok(), await response.text()).toBe(true);
+ receipt = (await response.json()).memo;
+ stored();
+ await gate;
+ await route.fulfill({ response });
+ });
+ try {
+ await openMemo(page, memo.id, marker);
+ const title = page.getByRole("textbox", { name: "信息图", exact: true });
+ await title.fill(`${marker}-first`);
+ await expect.poll(async () => (await queuedUpdate(page, memo.id))?.payload.title).toBe(`${marker}-first`);
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));
+ await firstStored;
+ await page.clock.install();
+ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1_000));
+ await title.fill(`${marker}-second`);
+ await page.clock.runFor(1_300);
+ await expect.poll(async () => (await queuedUpdate(page, memo.id))?.payload.title).toBe(`${marker}-second`);
+ // Replay the real first receipt through the same two editor notifications.
+ // The successor is locally saved (clean), but has not reached the server.
+ await page.evaluate((detail) => {
+ window.dispatchEvent(new CustomEvent("edgeever:memo-sync-acknowledged", { detail }));
+ window.dispatchEvent(new CustomEvent("edgeever:memo-detail-refreshed", { detail }));
+ }, receipt);
+ await page.clock.runFor(50);
+ await expect(title).toHaveValue(`${marker}-second`);
+ const nextSaved = page.waitForResponse((response) => response.request().method() === "PATCH"
+ && new URL(response.url()).pathname === `/api/v1/memos/${memo.id}` && response.request().postDataJSON()?.title === `${marker}-second`);
+ const completed = page.evaluate(() => new Promise<void>((resolve) => window.addEventListener("edgeever:sync-completed", () => resolve(), { once: true })));
+ release();
+ await completed;
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));
+ expect((await nextSaved).ok()).toBe(true);
+ await page.clock.resume();
+ await openMemo(page, memo.id, `${marker}-second`);
+ await expect(title).toHaveValue(`${marker}-second`);
+ } finally {
+ release();
+ await page.unroute(`**/api/v1/memos/${memo.id}`);
+ await removeMemo(page, memo.id);
+ }
+});
+
+test("infographic keeps title input and focus across temporary id remapping", async ({ page }) => {
+ let release!: () => void;
+ let created!: (id: string) => void;
+ const gate = new Promise<void>((resolve) => { release = resolve; });
+ const createdId = new Promise<string>((resolve) => { created = resolve; });
+ let id: string | undefined;
+ await page.route("**/api/v1/memos", async (route) => {
+ if (route.request().method() !== "POST") return route.continue();
+ const response = await route.fetch();
+ expect(response.status()).toBe(201);
+ created((await response.json()).memo.id);
+ await gate;
+ await route.fulfill({ response });
+ });
+ try {
+ await page.goto("/");
+ await page.getByRole("button", { name: "选择笔记类型", exact: true }).click();
+ await page.getByRole("menuitem", { name: "信息图", exact: true }).click();
+ id = await createdId;
+ await page.clock.install();
+ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1_000));
+ const title = page.getByRole("textbox", { name: "信息图", exact: true });
+ const marker = `infographic-remap-${Date.now()}`;
+ await title.fill(marker);
+ const originalInput = await title.elementHandle();
+ const mapped = page.evaluate(() => new Promise<void>((resolve) => window.addEventListener("edgeever:memo-id-remapped", () => resolve(), { once: true })));
+ release();
+ await mapped;
+ await expect(page.locator(`[data-memo-id="${id}"]`)).toBeVisible();
+ await expect(title).toHaveValue(marker);
+ await expect(title).toBeFocused();
+ expect(await originalInput!.evaluate((input) => input.isConnected)).toBe(true);
+ const saved = page.waitForResponse((response) => response.request().method() === "PATCH" && new URL(response.url()).pathname === `/api/v1/memos/${id}`);
+ await page.clock.runFor(1_300);
+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));
+ expect((await saved).ok()).toBe(true);
+ await page.clock.resume();
+ await page.reload();
+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();
+ await page.getByPlaceholder("搜索笔记").fill(marker);
+ await page.locator(`[data-memo-id="${id}"]`).locator("button").first().click();
+ await expect(title).toHaveValue(marker);
+ } finally {
+ release();
+ await page.unroute("**/api/v1/memos");
+ if (id) await removeMemo(page, id);
+ }
+});
diff --git a/tests/e2e/memo-sync-race.spec.ts b/tests/e2e/memo-sync-race.spec.ts
index 532a6d03..2bbac80c 100644
--- a/tests/e2e/memo-sync-race.spec.ts
+++ b/tests/e2e/memo-sync-race.spec.ts
@@ -222,7 +222,7 @@ test("preserves a mind-map draft when an earlier autosave is acknowledged", asyn
// Keep the next edit inside the real 1,200 ms debounce window while the
// previous response arrives. X6 still gets its animation frames.
await page.clock.install();
- await page.clock.pauseAt(new Date());
+ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1_000));
await canvas.focus();
await page.keyboard.press("Tab");
await page.clock.runFor(100);
@@ -383,7 +383,7 @@ test("keeps a new mind-map editor and its draft when its temporary id is remappe
const canvas = page.locator('[data-diagram-kind="mind-map"]');
await expect(canvas.locator(".x6-node")).toHaveCount(8);
await page.clock.install();
- await page.clock.pauseAt(new Date());
+ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1_000));
const title = page.getByRole("textbox", { name: "图表标题", exact: true });
const marker = `new-diagram-${Date.now()}`;
await title.fill(marker);