AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
fix: 保留图表同步期间的草稿 (#737) (#742)
LuoQianhongd36b4ba3124c
diff --git a/apps/web/src/components/DiagramEditorPane.test.mjs b/apps/web/src/components/DiagramEditorPane.test.mjsindex 9963c4cd..5885cb0a 100644--- a/apps/web/src/components/DiagramEditorPane.test.mjs+++ b/apps/web/src/components/DiagramEditorPane.test.mjs@@ -392,7 +392,7 @@ describe("diagram editor canvas surface", () => {test("does not rebuild the visible diagram after its own autosave", () => {expect(source).toContain("incomingSnapshot !== canvasSnapshot");expect(source).toContain("setGraphReloadVersion((current) => current + 1)");- expect(source).toContain("graphReloadVersion, memo.id, readOnly");+ expect(source).toContain("graphReloadVersion, editorInstanceMemoKey, readOnly");expect(source).not.toContain("dismissFlowQuickCreate, memo.contentHash, memo.id, readOnly");});diff --git a/apps/web/src/components/DiagramEditorPane.tsx b/apps/web/src/components/DiagramEditorPane.tsxindex 739993e4..8f8da7cc 100644--- a/apps/web/src/components/DiagramEditorPane.tsx+++ b/apps/web/src/components/DiagramEditorPane.tsx@@ -4,6 +4,7 @@ import { formatMindMapOutline, projectMindMapOutline, updateMindMapOutlineDraft,import { MindMapOutlineEditor } from "@/components/MindMapOutlineEditor";import { focusArchitectureRelations } from "@/lib/architecture-relations";import { MemoTitleInput } from "@/components/MemoTitleInput";+import { createEditorInstanceMemoIdentity, reconcileEditorInstanceMemoIdentity, remapEditorInstanceMemoIdentity } from "@/components/editor/editor-instance-identity";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type DragEvent as ReactDragEvent, type PointerEvent as ReactPointerEvent } from "react";import { Dom, Export, Graph, History, Keyboard, Scroller, Selection, type Edge, type Node } from "@antv/x6";import * as m from "motion/react-m";@@ -190,7 +191,9 @@ import { DIAGRAM_ZOOM_SCALE_MAX, DIAGRAM_ZOOM_SCALE_MIN } from "@/lib/diagram-zoimport { resolveDiagramPalette, type DiagramAppearance } from "@/lib/diagram-theme";import { isLocalMemoId } from "@/lib/local-mirror";import { isBrowserOffline } from "@/lib/network-status";+import { shouldAcceptRemoteMemoDetail } from "@/lib/memo-detail-freshness";import { statusSettleMotion } from "@/lib/motion";+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";@@ -1761,9 +1764,13 @@ export const DiagramEditorPane = ({const insertNodeRef = useRef<(relation: MindMapInsertRelation, baseNodeId?: string) => void>(() => undefined);const openFlowQuickCreateRef = useRef<(node: Node) => void>(() => undefined);const memoRef = useRef(memo);+ const memoIdentityRef = useRef(createEditorInstanceMemoIdentity(memo.id));+ memoIdentityRef.current = reconcileEditorInstanceMemoIdentity(memoIdentityRef.current, memo.id);+ const editorInstanceMemoKey = memoIdentityRef.current.instanceKey;const editSessionRef = useRef<MemoEditSession | null>(null);const saveRef = useRef<() => void>(() => undefined);- const document = parseDiagramDocument(memo.contentMarkdown);+ const savingRef = useRef(false);+ const document = parseDiagramDocument(memoIdentityRef.current.aliases.has(memoRef.current.id) ? memoRef.current.contentMarkdown : memo.contentMarkdown);const denseArchitecture = document?.kind === "architecture"&& document.edges.length >= 16&& document.edges.length / Math.max(1, document.nodes.filter((node) => node.shape !== "boundary").length) >= 1.1;@@ -1794,6 +1801,8 @@ export const DiagramEditorPane = ({const [tagsDirty, setTagsDirty] = useState(false);const [dirtyVersion, setDirtyVersion] = useState(0);const [graphReloadVersion, setGraphReloadVersion] = useState(0);+ const [memoReconcileVersion, setMemoReconcileVersion] = useState(0);+ const deferredMemoBaselineRef = useRef<{ snapshot: string; tags: string } | null>(null);const [outlineMode, setOutlineMode] = useState(false);const [outlineDraft, setOutlineDraft] = useState<MindMapOutlineDraft | null>(null);const [outlineError, setOutlineError] = useState<MindMapOutlineError | null>(null);@@ -1809,7 +1818,7 @@ export const DiagramEditorPane = ({setOutlineDraft(null);setOutlineError(null);setOutlinePendingBulk(null);- }, [memo.id]);+ }, [editorInstanceMemoKey]);const [saving, setSaving] = useState(false);const [editSessionReady, setEditSessionReady] = useState(false);const [saveError, setSaveError] = useState<string | null>(null);@@ -1846,13 +1855,16 @@ export const DiagramEditorPane = ({const flowQuickCreateRef = useRef<FlowQuickCreateState | null>(null);const flowPointerDragRef = useRef<FlowPointerDragState | null>(null);const nodeEditorRef = useRef<NodeEditorState | null>(null);- const editorDirty = dirty || tagsDirty || Boolean(outlineError) || Boolean(outlinePendingBulk);+ const pendingOutlineRef = useRef(false);+ pendingOutlineRef.current = Boolean(outlineError || outlinePendingBulk);+ const editorDirty = dirty || tagsDirty || Boolean(outlineError) || Boolean(outlinePendingBulk)+ || Boolean(nodeEditor && nodeEditor.value !== nodeEditor.originalValue);spacePanActiveRef.current = spacePanActive;useEffect(() => {setPendingArchitectureItem(null);- }, [memo.id]);+ }, [editorInstanceMemoKey]);useEffect(() => {const isTextInput = (target: EventTarget | null) => target instanceof HTMLElement@@ -1938,50 +1950,156 @@ export const DiagramEditorPane = ({if (graph && pending.restoreHistory) graph.enableHistory();}, []);- useEffect(() => {- setSelectedNodeId(null);- setSelectedNodeLabel("");- setSelectedEdgeId(null);- setSelectedEdgeLabel("");- setHasSelection(false);- flowQuickCreateRef.current = null;- setFlowQuickCreate(null);- nodeEditorRef.current = null;- setNodeEditor(null);- setTheme(documentTheme);- themeRef.current = documentTheme;- setStructure(documentStructure);- structureRef.current = documentStructure;- setHistoryOpen(false);- setShareOpen(false);- setMemoIdCopyNotice(null);- }, [documentStructure, documentTheme, memo.id]);-useEffect(() => () => {if (memoIdCopyTimerRef.current !== null) window.clearTimeout(memoIdCopyTimerRef.current);}, []);useEffect(() => {- memoRef.current = memo;+ const remapped = (event: Event) => {+ const mappings = (event as CustomEvent<ReadonlyMap<string, string>>).detail;+ const previousIdentity = memoIdentityRef.current;+ const nextIdentity = remapEditorInstanceMemoIdentity(previousIdentity, mappings);+ if (nextIdentity === previousIdentity) return;+ memoIdentityRef.current = nextIdentity;+ if (previousIdentity.aliases.has(memoRef.current.id)) {+ memoRef.current = { ...memoRef.current, id: nextIdentity.memoId! };+ }+ const session = editSessionRef.current;+ if (session && previousIdentity.aliases.has(session.memoId)) {+ editSessionRef.current = { ...session, id: `local-edit:${nextIdentity.memoId}`, memoId: nextIdentity.memoId! };+ }+ };+ window.addEventListener(MEMO_ID_REMAPPED_EVENT, remapped);+ return () => window.removeEventListener(MEMO_ID_REMAPPED_EVENT, remapped);+ }, []);++ const advanceSyncBase = useCallback((syncedMemo: MemoDetail) => {+ const currentMemo = memoRef.current;+ if (syncedMemo.id !== currentMemo.id || syncedMemo.revision < currentMemo.revision) return;+ memoRef.current = {+ ...currentMemo,+ revision: syncedMemo.revision,+ contentHash: syncedMemo.contentHash,+ updatedAt: syncedMemo.updatedAt,+ };+ if (editSessionRef.current?.memoId === syncedMemo.id) {+ editSessionRef.current = {+ ...editSessionRef.current,+ baseRevision: syncedMemo.revision,+ baseContentHash: syncedMemo.contentHash,+ };+ }+ }, []);++ useEffect(() => {+ const acknowledged = (event: Event) => advanceSyncBase((event as CustomEvent<MemoDetail>).detail);+ window.addEventListener(MEMO_SYNC_ACKNOWLEDGED_EVENT, acknowledged);+ return () => window.removeEventListener(MEMO_SYNC_ACKNOWLEDGED_EVENT, acknowledged);+ }, [advanceSyncBase]);++ useEffect(() => {+ const incomingDocument = parseDiagramDocument(memo.contentMarkdown);+ const incomingSnapshot = incomingDocument ? diagramEditorSnapshot(memo.title ?? "", incomingDocument) : "";+ const currentMemo = memoRef.current;+ const graph = graphRef.current;+ const sameMemo = memoIdentityRef.current.aliases.has(currentMemo.id) && Boolean(graph);+ if (!sameMemo) deferredMemoBaselineRef.current = null;+ const canvasSnapshot = graph && document ? diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, themeRef.current, structureRef.current),+ ) : "";+ if (sameMemo && !readOnly) {+ if (!shouldAcceptRemoteMemoDetail(currentMemo, memo)) return;+ const savedTags = currentMemo.tags.join("\u0000");+ const hasDraft = canvasSnapshot !== savedSnapshotRef.current+ || parseTagsText(tagsRef.current).join("\u0000") !== savedTags+ || nodeEditorRef.current !== null || flowQuickCreateRef.current !== null+ || pendingOutlineRef.current || savingRef.current;+ if (hasDraft) {+ // An echo of our saved snapshot may advance its base, never its draft.+ // A different remote document keeps the old base for conflict handling.+ if (incomingSnapshot === savedSnapshotRef.current && memo.tags.join("\u0000") === savedTags) {+ advanceSyncBase(memo);+ } else if (!deferredMemoBaselineRef.current) {+ deferredMemoBaselineRef.current = { snapshot: savedSnapshotRef.current, tags: savedTags };+ }+ return;+ }+ }+ deferredMemoBaselineRef.current = null;+ memoRef.current = memo.id === memoIdentityRef.current.memoId ? memo : { ...memo, id: memoIdentityRef.current.memoId! };setTitle(memo.title ?? "");titleRef.current = memo.title ?? "";setTagsText(memo.tags.join(", "));tagsRef.current = memo.tags.join(", ");- savedSnapshotRef.current = document ? diagramEditorSnapshot(memo.title ?? "", document) : "";+ savedSnapshotRef.current = incomingSnapshot;setDirty(false);setTagsDirty(false);setMobileNotebookSheetOpen(false);setSaveError(null);setSaveFailed(false);- editSessionRef.current = null;- setEditSessionReady(false);- if (readOnly || isLocalMemoId(memo.id) || isBrowserOffline() || window.edgeeverDesktop?.isAvailable) {- editSessionRef.current = createLocalEditSession(memo);++ if (!sameMemo || incomingSnapshot !== canvasSnapshot) {+ setSelectedNodeId(null);+ setSelectedNodeLabel("");+ setSelectedEdgeId(null);+ setSelectedEdgeLabel("");+ setHasSelection(false);+ flowQuickCreateRef.current = null;+ setFlowQuickCreate(null);+ nodeEditorRef.current = null;+ setNodeEditor(null);+ const nextTheme = incomingDocument?.kind === "architecture"+ ? resolveDiagramTheme(incomingDocument.theme ?? "brand")+ : incomingDocument?.kind === "flowchart"+ ? resolveFlowchartTheme(incomingDocument.theme)+ : resolveDiagramTheme(incomingDocument?.theme);+ const nextStructure = resolveDiagramStructure(incomingDocument?.structure);+ setTheme(nextTheme);+ themeRef.current = nextTheme;+ setStructure(nextStructure);+ structureRef.current = nextStructure;+ setHistoryOpen(false);+ setShareOpen(false);+ setMemoIdCopyNotice(null);+ if (sameMemo && outlineMode && incomingDocument?.kind === "mind-map") {+ setOutlineDraft(formatMindMapOutline(incomingDocument));+ }+ if (sameMemo) setGraphReloadVersion((current) => current + 1);+ }+ }, [advanceSyncBase, memo, memoReconcileVersion, readOnly]);++ useEffect(() => {+ const deferred = deferredMemoBaselineRef.current;+ const graph = graphRef.current;+ if (!deferred || !graph || !document || savingRef.current || pendingOutlineRef.current+ || nodeEditorRef.current || flowQuickCreateRef.current) return;+ // A canceled input or undo may release a deferred remote update. A newly+ // saved local draft must still keep its old base for conflict handling.+ if (savedSnapshotRef.current !== deferred.snapshot || memoRef.current.tags.join("\u0000") !== deferred.tags+ || parseTagsText(tagsRef.current).join("\u0000") !== deferred.tags) return;+ const currentSnapshot = diagramEditorSnapshot(+ titleRef.current,+ graphToDocument(graph, document.kind, themeRef.current, structureRef.current),+ );+ if (currentSnapshot !== deferred.snapshot) return;+ deferredMemoBaselineRef.current = null;+ setMemoReconcileVersion((current) => current + 1);+ }, [dirty, dirtyVersion, editorInstanceMemoKey, flowQuickCreate, nodeEditor, outlineError, outlinePendingBulk, saving, tagsDirty]);++ useEffect(() => {+ const currentMemo = memoRef.current;+ if (editSessionRef.current?.memoId !== currentMemo.id) {+ editSessionRef.current = null;+ setEditSessionReady(false);+ }+ if (readOnly || isLocalMemoId(currentMemo.id) || isBrowserOffline() || window.edgeeverDesktop?.isAvailable) {+ editSessionRef.current = createLocalEditSession(currentMemo);setEditSessionReady(true);return;}let cancelled = false;- void api.createMemoEditSession(memo.id).then(({ editSession }) => {+ void api.createMemoEditSession(currentMemo.id).then(({ editSession }) => {if (!cancelled) {editSessionRef.current = editSession;setEditSessionReady(true);@@ -2025,19 +2143,6 @@ export const DiagramEditorPane = ({setNodeEditor(nextEditor);}, [resolvedTheme, document?.kind]);- useEffect(() => {- const graph = graphRef.current;- if (!graph || !document) return;- const incomingSnapshot = diagramEditorSnapshot(memo.title ?? "", document);- const canvasSnapshot = diagramEditorSnapshot(- titleRef.current,- graphToDocument(graph, document.kind, themeRef.current, structureRef.current),- );- if (incomingSnapshot !== canvasSnapshot) {- setGraphReloadVersion((current) => current + 1);- }- }, [memo.contentHash]);-useEffect(() => {if (!containerRef.current || !document) return;const appearance = appearanceRef.current;@@ -2610,7 +2715,7 @@ export const DiagramEditorPane = ({graphRef.current = null;graph.dispose();};- }, [beginNodeEdit, dismissFlowQuickCreate, graphReloadVersion, memo.id, readOnly]);+ }, [beginNodeEdit, dismissFlowQuickCreate, graphReloadVersion, editorInstanceMemoKey, readOnly]);useEffect(() => {if (!editorDirty) return;@@ -3191,7 +3296,7 @@ export const DiagramEditorPane = ({const graph = graphRef.current;const currentMemo = memoRef.current;const editSession = editSessionRef.current;- if (!graph || !document || !editSession || readOnly || saving || outlineError || outlinePendingBulk) return false;+ if (!graph || !document || !editSession || readOnly || savingRef.current || outlineError || outlinePendingBulk) return false;if (savedSnapshotRef.current === diagramEditorSnapshot(titleRef.current, graphToDocument(graph, document.kind, themeRef.current, structureRef.current))&& !tagsDirty@@ -3199,6 +3304,7 @@ export const DiagramEditorPane = ({setDirty(false);return true;}+ savingRef.current = true;setSaving(true);setSaveError(null);setSaveFailed(false);@@ -3217,13 +3323,23 @@ export const DiagramEditorPane = ({contentMarkdown: markdown,tags: nextTags,});- memoRef.current = result.memo;+ if (!memoIdentityRef.current.aliases.has(currentMemo.id) || graphRef.current !== graph) {+ await onSaved(result.memo);+ return true;+ }+ const savedMemo = result.memo.id === memoRef.current.id ? result.memo : { ...result.memo, id: memoRef.current.id };+ const syncBase = memoRef.current;+ memoRef.current = syncBase.revision > savedMemo.revision+ ? { ...savedMemo, revision: syncBase.revision, contentHash: syncBase.contentHash, updatedAt: syncBase.updatedAt }+ : savedMemo;savedSnapshotRef.current = nextSnapshot;const currentSnapshot = diagramEditorSnapshot(titleRef.current,graphToDocument(graph, document.kind, themeRef.current, structureRef.current),);- const hasNewChanges = currentSnapshot !== nextSnapshot;+ const hasNewChanges = currentSnapshot !== nextSnapshot+ || Boolean(nodeEditorRef.current && nodeEditorRef.current.value !== nodeEditorRef.current.originalValue)+ || pendingOutlineRef.current;const hasNewTagChanges = parseTagsText(tagsRef.current).join("\u0000") !== result.memo.tags.join("\u0000");setDirty(hasNewChanges);setTagsDirty(hasNewTagChanges);@@ -3232,17 +3348,20 @@ export const DiagramEditorPane = ({tagsRef.current = savedTagsText;setTagsText(savedTagsText);}- if (!hasNewChanges && !hasNewTagChanges) {+ if (!hasNewChanges && !hasNewTagChanges && nodeEditorRef.current === null) {graph.cleanHistory();setHistoryState({ undo: false, redo: false });- await onSaved(result.memo);+ await onSaved(memoRef.current);}return true;} catch (error) {- setSaveFailed(true);- setSaveError(error instanceof Error ? error.message : t("diagram.saveError"));+ if (memoIdentityRef.current.aliases.has(currentMemo.id) && graphRef.current === graph) {+ setSaveFailed(true);+ setSaveError(error instanceof Error ? error.message : t("diagram.saveError"));+ }return false;} finally {+ savingRef.current = false;setSaving(false);}};@@ -3313,7 +3432,7 @@ export const DiagramEditorPane = ({return (graphRef.current?.getNodes() ?? []).filter((node) =>(node.getData<NodeData>()?.label ?? "").toLocaleLowerCase().includes(query),);- }, [dirtyVersion, memo.id, searchOpen, searchQuery]);+ }, [dirtyVersion, editorInstanceMemoKey, searchOpen, searchQuery]);const selectSearchMatch = useCallback((index: number) => {const graph = graphRef.current;diff --git a/apps/web/src/lib/desktop-sync.test.mjs b/apps/web/src/lib/desktop-sync.test.mjsindex 57e5e5cc..e9b1b3c9 100644--- a/apps/web/src/lib/desktop-sync.test.mjs+++ b/apps/web/src/lib/desktop-sync.test.mjs@@ -76,9 +76,11 @@ test("desktop creates notebooks before notes and rereads remapped queue versionsconst originalCreateNotebook = api.createNotebook;const originalCreateMemo = api.createMemo;const calls = [];+ const createdPayloads = [];+ const contentJson = { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "body 2" }] }] };let queue = [{ id: 1, version: 1, kind: "notebook.create", entityId: "nb_local_parent", payload: { name: "对对对" } },- ...[2, 3].map((id) => ({ id, version: 1, kind: "memo.create", entityId: `memo_local_${id}`, payload: { notebookId: "nb_local_parent", contentMarkdown: `body ${id}` } })),+ ...[2, 3].map((id) => ({ id, version: 1, kind: "memo.create", entityId: `memo_local_${id}`, payload: { notebookId: "nb_local_parent", contentMarkdown: `body ${id}`, ...(id === 2 ? { contentJson } : {}) } })),];globalThis.window = {dispatchEvent: () => true,@@ -109,6 +111,7 @@ test("desktop creates notebooks before notes and rereads remapped queue versions};api.createMemo = async (payload) => {expect(payload.notebookId).toBe("nb_cloud");+ createdPayloads.push(payload);calls.push(payload.contentMarkdown);return { memo: { id: `memo_cloud_${calls.length}`, contentMarkdown: payload.contentMarkdown, contentJson: { type: "doc", content: [] } } };};@@ -117,6 +120,8 @@ test("desktop creates notebooks before notes and rereads remapped queue versionsexpect(result.failed).toBe(0);expect(result.synced).toBe(3);expect(calls).toEqual(["notebook", "body 2", "body 3"]);+ expect(createdPayloads[0].contentJson).toEqual(contentJson);+ expect(createdPayloads[1].contentJson).toBeUndefined();expect(queue).toEqual([]);} finally {api.createNotebook = originalCreateNotebook;diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.tsindex 82d5443d..44adfc1a 100644--- a/apps/web/src/lib/desktop-sync.ts+++ b/apps/web/src/lib/desktop-sync.ts@@ -368,6 +368,7 @@ const syncOutboxItem = async (item: DesktopOutboxItem, stagedRewrites: StagedResconst data = await api.createMemo({notebookId: String(payload.notebookId),title: String(payload.title ?? ""),+ contentJson: payload.contentJson as TiptapDoc | undefined,contentMarkdown: typeof payload.contentMarkdown === "string" ? payload.contentMarkdown : undefined,tags: Array.isArray(payload.tags) ? payload.tags.filter((tag): tag is string => typeof tag === "string") : [],createdAt: typeof payload.createdAt === "string" ? payload.createdAt : undefined,diff --git a/docs/changes/2026-10-31-diagram-sync-drafts.md b/docs/changes/2026-10-31-diagram-sync-drafts.mdnew file mode 100644index 00000000..7dc15d23--- /dev/null+++ b/docs/changes/2026-10-31-diagram-sync-drafts.md@@ -0,0 +1,96 @@+# Preserve diagram drafts during synchronization++## Problem and goal++[Issue #737](https://github.com/tianma-if/edgeever/issues/737) reports disappearing mind-map edits while the client displays a synchronized status. The shared diagram editor clears its dirty state when a memo revision changes and reloads the canvas when its content hash changes, including while newer local edits are unsaved. Preserve those edits and keep the save status accurate.++## Allowed changes and acceptance++- Reconcile incoming snapshots in the shared mind-map, flowchart, and architecture editor without replacing unsaved canvas, title, tags, inline node text, or outline edits. A sync acknowledgment for this device may advance the concurrency base, but must not discard a draft, cancel its autosave, or clear its undo history.+- Treat a new note's temporary-to-server ID remapping as the same editor session, retaining the canvas, focus, and unsaved input. If an incoming remote snapshot is deferred while input is active, apply it when that input is canceled or the draft returns to its saved baseline; do not rebase a genuinely changed draft onto remote content.+- Keep edits made while a local save is pending dirty until their own save completes. A completed save acknowledges only the memo, canvas, and snapshot it submitted, including when the user has started editing another node.+- Continue to apply genuine remote changes when the editor has no local draft. When a genuine remote change arrives during editing, preserve the draft and its original concurrency base so the existing synchronization conflict handling remains effective.+- Add a focused browser regression: delay a sync acknowledgment until a subsequent graph edit or inline edit exists, then verify the edit remains and reaches durable storage after autosave and reopening. Cover revision-only and content-hash updates, metadata, and an idle editor receiving a remote update with the same focused workflow or the existing isolated reproduction where needed. Make the regression fixtures independent of existing tags and selected notebooks; wait for API health through the Web proxy before initializing browser sessions.+- Run the affected diagram checks, `bun run typecheck`, `bun run typecheck:mobile`, and `bun run build:web`. Inspect the rendered editor and exercise its edit/save path. Record desktop-client coverage separately from browser checks.+- Capture a controlled before/after comparison on the PR's v2.16.0 baseline and fixed renderer through the same macOS native development entry: hold a real save response, make identical later node/title edits, then release the response. Show both versions immediately before and after the acknowledgment, and check the resulting local and server content after autosave.+- Preserve the queued structured `contentJson` in desktop `memo.create` requests, using the existing API field and resource-URL normalization. Keep Markdown-only queue entries supported, and verify that a pending creation written by the unmodified v2.15.0 native client uploads and remains editable after loading the fixed renderer on the same SQLite profile. Do not weaken the suspicious-overwrite protection. Verify that creating a diagram and then changing its title and nodes uploads successfully without counting serialized metadata as note text.+- Verify the macOS native client through the project's standard local-development entry, using its pinned Electron and a locally compiled Rust sidecar from v2.15.0 source. Verify the Linux native client under Xvfb with the formal v2.15.0 runtime. Both use a renderer built from that source with only this task's fixes applied. Use temporary application data, databases, and test services with auto-update disabled; do not replace an installed client or change an existing service.++## Unchanged boundaries++Keep the existing 1,200 ms autosave delay, input rules, save-failure behavior, repository entry points, synchronization protocol, conflict resolution, database schema, backups, and native platform implementations. Do not change the text, table, poster, or infographic editors, add dependencies, or publish a release. Existing unrelated note-import work is outside this change.++## Risk and rollback++Incorrect acknowledgment classification could hide a genuine remote change or advance a draft onto the wrong concurrency base. Verify self-sync and genuine remote updates separately. The desktop-create change affects the initial server content and its hash; a mismatched structured document could corrupt that initial representation. Verify queued structured content and legacy Markdown-only entries, then exercise the real native create/edit/sync/restart path on macOS and Linux. Revert the diagram-editor reconciliation changes and desktop-create field forwarding to roll back; no data migration is required.++## Completion check++- The product diff is limited to `DiagramEditorPane.tsx` and the desktop `memo.create` request in `desktop-sync.ts`. Snapshot reconciliation preserves local drafts and active input, advances self-sync bases separately, refreshes edit sessions without blocking autosave, and binds save responses to their originating logical memo and canvas. It reuses the existing editor-identity helper to retain the graph, outline, and focus across ID remapping. Deferred remote updates resume when input is canceled or the draft returns to its saved baseline; the actual outline and dirty states drive this decision rather than an aggregate dirty flag. A newly saved local draft retains its original concurrency base for conflict handling.+- The three Chrome scenarios in `tests/e2e/memo-sync-race.spec.ts` pass, including the existing text-caret regression. The diagram scenarios verify: delayed real API acknowledgments preserve node/title/tag edits and survive reopening; new-note ID remapping retains focus and the original graph before saving and reopening; idle remote updates apply, including after canceling unchanged node input or restoring an outline removal while tags have returned to their baseline. Remote changes during genuine editing preserve the draft's original revision/hash. Run `bunx playwright test tests/e2e/memo-sync-race.spec.ts --grep 'mind-map'` with a Playwright browser installed.+- Isolated browser checks held a local save open while editing the title and another node, and remapped a note with an invalid outline still being edited. Drafts, input focus, and the original graph were retained; the successor save used the acknowledged revision. Input and undo remained usable after self-sync. The rendered editor was inspected.+- All 67 diagram editor, snapshot, editor-identity, and desktop-sync checks pass, covering structured creation payloads and existing Markdown-only queue entries. `bun run typecheck`, `bun run typecheck:mobile`, and `bun run build:web` pass with both fixes.+- Linux packaged-runtime checks under Xvfb pass with the formal v2.15.0 Electron/sidecar and the patched renderer: delayed acknowledgments retain later node/title edits; temporary-ID remapping retains the graph and focused input; genuine remote changes apply while idle and after canceling unchanged input. Both diagrams, including a new diagram whose title and nodes changed during creation, are present in real sidecar SQLite and server storage and survive a full application restart.+- The desktop create request now forwards its normalized structured `contentJson`. Serialized diagram metadata is no longer counted as note text during creation, so the subsequent title/node edit is uploaded without weakening `suspicious_memo_overwrite` protection. A pending creation written through the unmodified v2.15.0 native client's sidecar is uploaded after switching the same SQLite profile to the fixed renderer, remains editable, and survives another full restart with no pending, failed, or conflicted queue items.+- The macOS native client passes the same four workflows through the standard local-development entry: delayed acknowledgments, focused input across ID remapping, genuine remote updates, and persistence after a full restart. It uses Electron 44.7.0, a locally compiled Rust sidecar, real SQLite, and the real test API from v2.15.0 source. This covers native functionality; signed-installer and updater validation remains with the release workflow. Windows native validation remains unperformed.++## Controlled macOS native comparison++The unmodified v2.16.0 baseline (`01422910`) and fixed renderer (`e0e1b678`) use the same standard native development entry, Electron 44.7.0, Rust sidecar, real SQLite, and real API. Both use a 1440 × 900 window; screenshots crop the same editor area at 100% zoom.++1. Open an eight-node mind map and change its title to “上次自动保存的标题”. Let the real API store that autosave, but hold its response.+2. Before the next 1,200 ms autosave, add “【新增】回执返回也不能丢” and change the title to “刚输入的新标题(不能丢)”. Pause the renderer clock to keep this draft pending, then release the older response.+3. Advance the clock by 1,400 ms, synchronize, read the native SQLite memo and server memo, then fully quit and restart the native client and reopen the note. The API response and memo data are not rewritten by the test.++| Stage | Before the fix | After the fix |+| --- | --- | --- |+| Older response still held | New title, 9 nodes, unsaved | New title, 9 nodes, unsaved |+| Older response delivered | Title reverts; 9 nodes remain visible, but status incorrectly says synchronized | New title and 9 nodes remain; status correctly stays unsaved |+| Autosave and reopen | Local/server storage never received the new node; only 8 nodes and the old title reopen | Local/server storage contains the new node and title; all 9 nodes reopen synchronized |++The disappearing node in this reproduction occurs on reopening, not immediately on acknowledgment: the incorrect clean state cancels the pending autosave. [Recorded native and API observations](evidence/2026-10-31-diagram-sync-drafts/macos-controlled-comparison.json).++### The visible difference after restart++**Before the fix: the new node disappears, the count drops from 9 to 8, and the title reverts.**++++**After the fix: the new node and title remain, with all 9 nodes after restart.**++++<details>+<summary>Show the four screenshots before and after the older acknowledgment</summary>++#### Response held: both versions have the same new, unsaved draft++Before the fix:++++After the fix:++++#### Response delivered: the baseline reverts the title and falsely reports synchronized; the fix retains the unsaved draft++Before the fix:++++After the fix:++++</details>++## Additional native restart screenshots (v2.15.0)++macOS, through the standard native development entry: the renamed diagram, added node, and remote update remain after a full application restart.++++Linux, with the formal v2.15.0 runtime and patched renderer under Xvfb: the same changes remain after restart and the client reports synchronized.++diff --git a/docs/changes/2026-10-31-diagram-sync-drafts.zh-CN.md b/docs/changes/2026-10-31-diagram-sync-drafts.zh-CN.mdnew file mode 100644index 00000000..1b97de8d--- /dev/null+++ b/docs/changes/2026-10-31-diagram-sync-drafts.zh-CN.md@@ -0,0 +1,96 @@+# 同步时保留图表草稿++## 问题与目标++[Issue #737](https://github.com/tianma-if/edgeever/issues/737) 反馈思维导图编辑内容消失,而客户端显示已同步。共用图表编辑器在笔记版本变化时清除未保存状态,并在内容哈希变化时重载画布,没有保护更新的本地草稿。本次修复应保留这些编辑,并使保存状态准确。++## 允许变更与验收++- 思维导图、流程图和架构图的共用编辑器接收笔记快照时,不覆盖未保存的画布、标题、标签、节点文字输入或大纲编辑。本设备的同步回执可以推进并发版本基线,但不能丢弃草稿、取消其自动保存或清除撤销历史。+- 新笔记的临时 ID 映射为服务端 ID 时,仍视为同一编辑会话,保留画布、焦点和未保存输入。输入期间暂缓的远端快照,在取消输入或草稿恢复到已保存基线后继续应用;真正改动过的草稿不自动变更到远端内容的版本基线。+- 本地保存尚未完成时产生的编辑,必须保留未保存状态,直到其自身保存完成。保存回执只能确认该请求所属的笔记、画布和提交的快照;用户已经开始编辑另一个节点时也须遵守。+- 没有本地草稿时继续应用真正的远端修改。编辑期间收到真正的远端修改时,保留草稿及其原并发版本基线,沿用现有同步冲突处理。+- 新增定向浏览器回归:延迟同步回执,直到产生后续画布编辑或节点文字输入,验证编辑仍在,并在自动保存、重新打开后从持久存储读回。版本号变化、内容哈希变化、元数据和空闲编辑器接收远端修改,复用同一定向流程或现有隔离复现进行覆盖。回归数据不依赖已有标签或当前选中的笔记本;浏览器会话初始化前,通过 Web 代理等待 API 健康就绪。+- 运行受影响的图表检查、`bun run typecheck`、`bun run typecheck:mobile` 和 `bun run build:web`;检查实际界面并操作编辑、保存流程。分别记录桌面客户端与浏览器的验证范围。+- 在 PR 的 v2.16.0 基线与修复后的渲染器上,通过相同的 macOS 原生开发入口截取受控修复前后对比:暂缓真实保存回执,进行相同的后续节点和标题编辑,再放行回执。分别展示两版在回执到达前后的状态,并在自动保存后检查本地及服务端内容。+- 桌面端 `memo.create` 请求保留队列中的结构化 `contentJson`,复用已有 API 字段和资源 URL 规范化;仍支持只有 Markdown 的旧队列;验证未修改的 v2.15.0 原生端留下的待上传创建队列,在同一 SQLite 数据目录切换修复版渲染器后可以上传并继续编辑。不放宽异常覆盖保护。验证新建图表后修改标题和节点可成功上传,序列化元数据不再被计入正文。+- 通过项目标准的本地开发入口验证 macOS 原生客户端,使用项目固定版本的 Electron,以及由 v2.15.0 源码本地编译的 Rust sidecar。Linux 原生端使用 Xvfb 和正式 v2.15.0 运行时。两端均使用在对应源码上仅应用本任务修复后构建的渲染器。使用临时应用数据、数据库和测试服务,禁用自动升级,不替换已安装客户端或修改已有服务。++## 保持不变的边界++保留现有 1,200 ms 自动保存延迟、输入规则、保存失败行为、Repository 入口、同步协议、冲突解决、数据库结构、备份和原生平台实现。不修改文本、表格、海报或信息图编辑器,不新增依赖,不发布版本。已有第三方笔记导入改动不属于本次任务。++## 风险与回滚++同步回执判断错误可能隐藏真正的远端修改,或把草稿推进到错误的并发版本基线。分别验证自身同步和真正的远端更新。桌面创建请求的改动影响服务端初始正文及其哈希;结构化文档不匹配时可能损坏初始表示。验证结构化队列及只有 Markdown 的旧队列,并在 macOS、Linux 原生端操作真实创建、编辑、同步和重启流程。回退图表快照协调和桌面创建字段透传即可恢复原实现,无需数据迁移。++## 完成核对++- 产品改动仅涉及 `DiagramEditorPane.tsx`,以及 `desktop-sync.ts` 中桌面端的 `memo.create` 请求。快照协调保留本地草稿和正在输入的内容,单独推进自身同步基线,刷新编辑会话时不再阻断自动保存,并把保存回执绑定到原逻辑笔记和画布。复用现有编辑器身份辅助函数,在 ID 映射时保留图表、大纲和焦点。取消输入或草稿恢复已保存基线后继续应用暂缓的远端更新,判断依据包括实际的大纲和未保存状态,不再仅依赖聚合标记;新保存的本地草稿仍保留原并发基线,沿用现有冲突处理。+- `tests/e2e/memo-sync-race.spec.ts` 的 3 个 Chrome 场景通过,包含原有文本光标回归。图表场景验证:延迟真实 API 回执后,节点、标题和标签编辑均保留并可重新打开读回;新笔记 ID 映射时保留焦点和原画布,随后可保存并重新打开;空闲时接受远端更新,未修改节点输入后取消、标签回到原值后恢复大纲删除时也会继续应用更新。真正编辑期间收到远端修改时,草稿的原版本号/哈希保持不变。在已安装 Playwright 浏览器的环境运行 `bunx playwright test tests/e2e/memo-sync-race.spec.ts --grep 'mind-map'` 可复验。+- 隔离浏览器检查延迟了本地保存,并在此期间继续修改标题和另一个节点;还在无效大纲正在输入时进行了 ID 映射。草稿、输入焦点和原画布均保留,后续保存使用已确认版本;自身同步后输入和撤销仍可操作。已检查实际编辑器界面。+- 67 项图表编辑器、快照、编辑器身份和桌面同步检查均通过,覆盖结构化创建内容及只有 Markdown 的旧队列。包含两项修复的代码通过 `bun run typecheck`、`bun run typecheck:mobile` 和 `bun run build:web`。+- Linux 打包运行时在 Xvfb 下的检查通过,使用正式 v2.15.0 Electron/sidecar 与修复后的渲染器:延迟同步回执时保留后续节点和标题编辑;临时 ID 映射时保留原画布和输入焦点;空闲及取消未修改输入后接受真正的远端更新。两张导图均可从真实 sidecar SQLite 和服务端读回,并在完整退出、重启客户端后保留,包括创建期间同时修改标题和节点的新导图。+- 桌面创建请求现已携带规范化后的结构化 `contentJson`,创建时不再把序列化图表元数据计入正文,后续标题和节点修改可上传;未放宽 `suspicious_memo_overwrite` 保护。未修改的 v2.15.0 原生客户端通过 sidecar 写入的待上传创建队列,在同一 SQLite 数据目录切换修复版渲染器后上传成功,可继续修改,并在再次完整重启后保留;队列无待处理、失败或冲突项。+- macOS 原生客户端通过标准本地开发入口完成相同四项回归:延迟同步回执、ID 映射期间的输入焦点、真正的远端更新,以及完整重启后的持久化读回。使用 v2.15.0 源码、Electron 44.7.0、本地编译的 Rust sidecar、真实 SQLite 和真实测试 API。本次覆盖原生功能;签名安装包及自动升级验收仍由 Release 工作流负责。Windows 原生端尚未验证。++## macOS 原生端受控修复前后对比++未修改的 v2.16.0 基线(`01422910`)与修复后的渲染器(`e0e1b678`)使用相同的标准原生开发入口、Electron 44.7.0、Rust sidecar、真实 SQLite 和真实 API。两版窗口均为 1440 × 900,截图截取相同的编辑器区域,缩放均为 100%。++1. 打开含 8 个节点的思维导图,把标题改为“上次自动保存的标题”。让真实 API 写入这次自动保存,但暂缓返回回执。+2. 在下一次 1,200 ms 自动保存前,新增“【新增】回执返回也不能丢”,标题改为“刚输入的新标题(不能丢)”。暂停渲染器时钟,使这份草稿保持待保存,再放行旧回执。+3. 推进时钟 1,400 ms 并同步,读取原生 SQLite 与服务端笔记,再完整退出、重启原生客户端并重新打开笔记。测试不改写 API 回执或笔记数据。++| 阶段 | 修复前 | 修复后 |+| --- | --- | --- |+| 旧回执尚未返回 | 新标题、9 个节点、未保存 | 新标题、9 个节点、未保存 |+| 旧回执返回 | 标题回退;9 个节点暂时仍可见,却错误显示已同步 | 新标题和 9 个节点保留,正确保持未保存 |+| 自动保存并重新打开 | 本地和服务端均未收到新增节点;重开仅剩 8 个节点及旧标题 | 本地和服务端均保存新节点及标题;重开仍为 9 个节点、已同步 |++本场景的节点是在重开后消失,而不是回执返回瞬间消失:错误的已保存状态取消了后续自动保存。[原生端与 API 实测记录](evidence/2026-10-31-diagram-sync-drafts/macos-controlled-comparison.json)。++### 重启后的实际差别++**修复前:新增节点丢失,9 个节点变回 8 个,标题回退。**++++**修复后:新增节点和新标题保留,重启后仍为 9 个节点。**++++<details>+<summary>查看旧回执返回前后的 4 张截图</summary>++#### 回执返回前:两版均为相同新草稿、未保存++修复前:++++修复后:++++#### 回执返回后:旧版标题回退并误报已同步,修复版保持新草稿、未保存++修复前:++++修复后:++++</details>++## 补充原生重启截图(v2.15.0)++macOS 标准原生开发入口:完整退出、重启后,修改的标题、新增节点和远端更新仍保留。++++Linux 正式 v2.15.0 运行时与修复后的渲染器,运行于 Xvfb:重启后相同改动仍保留,客户端显示已同步。++diff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/linux-native-reopened.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/linux-native-reopened.pngnew file mode 100644index 00000000..777acd4cBinary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/linux-native-reopened.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-after-ack.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-after-ack.pngnew file mode 100644index 00000000..a61605ccBinary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-after-ack.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-before-ack.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-before-ack.pngnew file mode 100644index 00000000..ece654aeBinary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-before-ack.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-reopened.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-reopened.pngnew file mode 100644index 00000000..6fe5a40dBinary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-baseline-reopened.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-controlled-comparison.json b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-controlled-comparison.jsonnew file mode 100644index 00000000..5797a6ca--- /dev/null+++ b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-controlled-comparison.json@@ -0,0 +1,122 @@+{+ "scenario": "An earlier autosave response arrives while a newer mind-map node/title draft is waiting for its autosave",+ "responseGate": "The real API stores the first PATCH and returns its original response only after the newer draft is visible",+ "autosaveMs": 1200,+ "advanceAfterAcknowledgmentMs": 1400,+ "sharedRuntime": "Unmodified v2.16.0 Electron host, locally compiled Rust sidecar and real Bun API with SQLite; each variant uses isolated fresh data",+ "captures": "Original native-window screenshots, cropped to the same editor area; canvas scrolling only for visibility",+ "observations": {+ "baseline": {+ "variant": "baseline",+ "runtime": {+ "platform": "darwin",+ "electron": "44.7.0",+ "packaged": false,+ "version": "2.16.0"+ },+ "viewport": {+ "width": 1440,+ "height": 900+ },+ "clip": {+ "x": 600,+ "y": 0,+ "width": 840,+ "height": 720+ },+ "previousTitle": "上次自动保存的标题",+ "newTitle": "刚输入的新标题(不能丢)",+ "nodeLabel": "【新增】回执返回也不能丢",+ "before": {+ "title": "刚输入的新标题(不能丢)",+ "nodeCount": 9,+ "hasNewNode": true,+ "saveStatus": "未保存"+ },+ "after": {+ "title": "上次自动保存的标题",+ "nodeCount": 9,+ "hasNewNode": true,+ "saveStatus": "已同步",+ "originalGraphConnected": true+ },+ "persisted": {+ "server": {+ "title": "上次自动保存的标题",+ "nodeCount": 8,+ "hasNewNode": false+ },+ "local": {+ "title": "上次自动保存的标题",+ "hasNewNode": false+ }+ },+ "reopened": {+ "title": "上次自动保存的标题",+ "nodeCount": 8,+ "hasNewNode": false,+ "saveStatus": "已同步"+ },+ "pageErrors": [],+ "sourceCommit": "01422910520633b00ad59afbde56c91d8e189915",+ "nativeEntry": "standard local development entry",+ "reopenedAfter": "full native application exit and restart on the same SQLite profile"+ },+ "fixed": {+ "variant": "fixed",+ "runtime": {+ "platform": "darwin",+ "electron": "44.7.0",+ "packaged": false,+ "version": "2.16.0"+ },+ "viewport": {+ "width": 1440,+ "height": 900+ },+ "clip": {+ "x": 600,+ "y": 0,+ "width": 840,+ "height": 720+ },+ "previousTitle": "上次自动保存的标题",+ "newTitle": "刚输入的新标题(不能丢)",+ "nodeLabel": "【新增】回执返回也不能丢",+ "before": {+ "title": "刚输入的新标题(不能丢)",+ "nodeCount": 9,+ "hasNewNode": true,+ "saveStatus": "未保存"+ },+ "after": {+ "title": "刚输入的新标题(不能丢)",+ "nodeCount": 9,+ "hasNewNode": true,+ "saveStatus": "未保存",+ "originalGraphConnected": true+ },+ "persisted": {+ "server": {+ "title": "刚输入的新标题(不能丢)",+ "nodeCount": 9,+ "hasNewNode": true+ },+ "local": {+ "title": "刚输入的新标题(不能丢)",+ "hasNewNode": true+ }+ },+ "reopened": {+ "title": "刚输入的新标题(不能丢)",+ "nodeCount": 9,+ "hasNewNode": true,+ "saveStatus": "已同步"+ },+ "pageErrors": [],+ "sourceCommit": "e0e1b6787d1452661ddeaad95cd26c65f88ee5d9",+ "nativeEntry": "standard local development entry",+ "reopenedAfter": "full native application exit and restart on the same SQLite profile"+ }+ }+}diff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-after-ack.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-after-ack.pngnew file mode 100644index 00000000..ea0828fbBinary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-after-ack.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-before-ack.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-before-ack.pngnew file mode 100644index 00000000..ece654aeBinary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-before-ack.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-reopened.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-reopened.pngnew file mode 100644index 00000000..b2053ba8Binary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-fixed-reopened.png differdiff --git a/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-native-debug-reopened.png b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-native-debug-reopened.pngnew file mode 100644index 00000000..f2517f91Binary files /dev/null and b/docs/changes/evidence/2026-10-31-diagram-sync-drafts/macos-native-debug-reopened.png differdiff --git a/playwright.config.ts b/playwright.config.tsindex 27aaba13..e385e525 100644--- a/playwright.config.ts+++ b/playwright.config.ts@@ -25,7 +25,7 @@ export default defineConfig({],webServer: {command: "bun run dev",- url: "http://127.0.0.1:5173",+ url: "http://127.0.0.1:5173/api/health",reuseExistingServer: !process.env.CI,timeout: 120_000,stdout: "pipe",diff --git a/tests/e2e/memo-sync-race.spec.ts b/tests/e2e/memo-sync-race.spec.tsindex 7a1ffd65..532a6d03 100644--- a/tests/e2e/memo-sync-race.spec.ts+++ b/tests/e2e/memo-sync-race.spec.ts@@ -1,4 +1,6 @@import { expect, test, type Page, type Route } from "@playwright/test";+import { createDefaultDiagramDocument, diagramFallbackMarkdown, parseDiagramDocument, serializeDiagramDocument } from "../../packages/shared/src/diagram";+import { markdownToDoc } from "../../packages/shared/src/content";type StoredQueueItem = {kind?: string;@@ -101,7 +103,7 @@ test("keeps the caret and rebases edits made while autosave sync is in flight",try {await page.goto("/");- await page.getByRole("button", { name: new RegExp(notebookName!) }).click();+ await page.locator('[data-notebook-tree-button="true"]').filter({ hasText: notebookName! }).first().click();await page.getByPlaceholder("搜索笔记").fill(marker);await page.locator(`[data-memo-id="${memoId}"]`).locator("button").first().click();await page.getByRole("button", { name: "清空搜索", exact: true }).click();@@ -165,3 +167,271 @@ test("keeps the caret and rebases edits made while autosave sync is in flight",await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);}});++test("preserves a mind-map draft when an earlier autosave is acknowledged", async ({ page }) => {+ const marker = `diagram-sync-race-${Date.now()}`;+ const tag = `${marker}-tag`;+ const deferredTag = `${marker}-defer`;+ const notebooksResponse = await page.request.get("/api/v1/notebooks");+ expect(notebooksResponse.ok()).toBe(true);+ const { notebooks } = await notebooksResponse.json() as { notebooks: Array<{ id: string; name: string }> };+ const notebook = notebooks[0]!;+ const document = createDefaultDiagramDocument("mind-map");+ const createResponse = await page.request.post("/api/v1/memos", {+ data: {+ notebookId: notebook.id,+ title: marker,+ contentJson: markdownToDoc(diagramFallbackMarkdown(document)),+ contentMarkdown: serializeDiagramDocument(document),+ },+ });+ expect(createResponse.status()).toBe(201);+ const memoId = (await createResponse.json() as { memo: { id: string } }).memo.id;+ let releaseAcknowledgment!: () => void;+ let markUpdateStored!: () => void;+ const acknowledgmentGate = new Promise<void>((resolve) => { releaseAcknowledgment = resolve; });+ const updateStored = new Promise<void>((resolve) => { markUpdateStored = resolve; });+ let updateCount = 0;+ await page.route(`**/api/v1/memos/${memoId}`, async (route) => {+ if (route.request().method() !== "PATCH" || ++updateCount !== 1) {+ await route.continue();+ return;+ }+ const response = await route.fetch();+ expect(response.ok(), await response.text()).toBe(true);+ markUpdateStored();+ await acknowledgmentGate;+ await route.fulfill({ response });+ });++ try {+ await page.goto("/");+ await page.locator('[data-notebook-tree-button="true"]').filter({ hasText: notebook.name }).first().click();+ await page.getByPlaceholder("搜索笔记").fill(marker);+ await page.locator(`[data-memo-id="${memoId}"]`).locator("button").first().click();+ await page.getByRole("button", { name: "清空搜索", exact: true }).click();+ const canvas = page.locator('[data-diagram-kind="mind-map"]');+ await expect(canvas.locator(".x6-node")).toHaveCount(8);++ const title = page.getByRole("textbox", { name: "图表标题", exact: true });+ await title.fill(`${marker}-first-save`);+ await waitForQueuedContent(page, memoId, "first-save");+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));+ await updateStored;++ // 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 canvas.focus();+ await page.keyboard.press("Tab");+ await page.clock.runFor(100);+ const nodeInput = page.getByRole("textbox", { name: "编辑节点文字", exact: true });+ await nodeInput.fill("draft-during-sync");+ await canvas.focus();+ await title.fill(`${marker}-newer-title`);+ await page.getByRole("button", { name: "选择笔记标签", exact: true }).click();+ const tagDialog = page.getByRole("dialog");+ await tagDialog.getByRole("textbox").fill(tag);+ await tagDialog.locator('button[type="submit"]').click();+ await page.keyboard.press("Escape");+ await page.clock.runFor(100);+ await expect(canvas).toContainText("draft-during-sync");++ const completed = waitForSyncCompleted(page);+ releaseAcknowledgment();+ await completed;+ await expect(title).toHaveValue(`${marker}-newer-title`);+ await expect(canvas.locator(".x6-node")).toHaveCount(9);+ await expect(page.getByText("未保存", { exact: true }).last()).toBeVisible();++ const nextUpdate = page.waitForResponse((response) => response.request().method() === "PATCH"+ && new URL(response.url()).pathname === `/api/v1/memos/${memoId}`+ && response.request().postDataJSON()?.contentMarkdown?.includes("draft-during-sync"));+ await page.clock.runFor(1_300);+ await expect.poll(async () => {+ if (await queueItemWithContent(page, memoId, "draft-during-sync")) return true;+ const response = await page.request.get(`/api/v1/memos/${memoId}`);+ const body = await response.json() as { memo: { contentMarkdown: string } };+ return body.memo.contentMarkdown.includes("draft-during-sync");+ }).toBe(true);+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));+ const nextResponse = await nextUpdate;+ expect(nextResponse.ok(), await nextResponse.text()).toBe(true);+ const savedResponse = await page.request.get(`/api/v1/memos/${memoId}`);+ const { memo: saved } = await savedResponse.json() as { memo: { title: string; tags: string[]; contentMarkdown: string } };+ expect(saved.title).toBe(`${marker}-newer-title`);+ expect(saved.tags).toContain(tag);+ expect(saved.contentMarkdown).toContain("draft-during-sync");++ await page.clock.resume();+ await page.reload();+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();+ await page.getByPlaceholder("搜索笔记").fill(`${marker}-newer-title`);+ await page.locator(`[data-memo-id="${memoId}"]`).locator("button").first().click();+ await expect(canvas).toContainText("draft-during-sync");+ await expect(title).toHaveValue(`${marker}-newer-title`);++ const changeRemoteRoot = async (label: string) => {+ const response = await page.request.get(`/api/v1/memos/${memoId}`);+ const { memo: remote } = await response.json() as { memo: { contentMarkdown: string } };+ const next = parseDiagramDocument(remote.contentMarkdown)!;+ next.nodes.find((node) => node.id === "topic-root")!.label = label;+ const sessionResponse = await page.request.post(`/api/v1/memos/${memoId}/edit-sessions`);+ const { editSession } = await sessionResponse.json() as {+ editSession: { id: string; baseRevision: number; baseContentHash: string };+ };+ const update = await page.request.patch(`/api/v1/memos/${memoId}`, {+ data: {+ expectedRevision: editSession.baseRevision,+ expectedContentHash: editSession.baseContentHash,+ editSessionId: editSession.id,+ contentJson: markdownToDoc(diagramFallbackMarkdown(next)),+ contentMarkdown: serializeDiagramDocument(next),+ },+ });+ expect(update.ok(), await update.text()).toBe(true);+ const { memo: incoming } = await update.json();+ await page.evaluate((detail) => window.dispatchEvent(new CustomEvent("edgeever:memo-detail-refreshed", { detail })), incoming);+ return incoming as { revision: number; contentHash: string };+ };++ // A genuinely different remote document still updates an idle editor.+ await changeRemoteRoot("remote-when-idle");+ await expect(canvas).toContainText("remote-when-idle");+ await expect(canvas.locator(".x6-node")).toHaveCount(9);++ await canvas.locator('.x6-node[data-cell-id="topic-root"]').dblclick();+ await expect(nodeInput).toHaveValue("remote-when-idle");+ await changeRemoteRoot("remote-after-cancel");+ await expect(nodeInput).toHaveValue("remote-when-idle");+ await nodeInput.press("Escape");+ await expect(canvas).toContainText("remote-after-cancel");++ await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 50));+ // Returning tags to their saved values leaves the existing tagsDirty flag+ // set. It must not mask an outline confirmation being canceled.+ await page.getByRole("button", { name: "选择笔记标签", exact: true }).click();+ await tagDialog.getByRole("textbox").fill(deferredTag);+ await tagDialog.locator('button[type="submit"]').click();+ await tagDialog.locator("button").filter({ hasText: `#${deferredTag}` }).first().click();+ await page.keyboard.press("Escape");+ await page.getByRole("button", { name: "大纲视图", exact: true }).click();+ const outline = page.getByRole("textbox", { name: "大纲视图", exact: true });+ const outlineBeforeRemoval = await outline.inputValue();+ await outline.fill(outlineBeforeRemoval.split("\n")[0]!);+ const outlinePane = page.locator('section[aria-label="大纲视图"]');+ await expect(outlinePane.getByRole("button", { name: /恢复/ })).toBeVisible();+ const idleRemote = await changeRemoteRoot("remote-after-outline-restore");+ // Flush the query notification before restoring, then X6's async paint.+ await page.clock.runFor(50);+ await outlinePane.getByRole("button", { name: /恢复/ }).click();+ await page.clock.runFor(50);+ await expect(canvas).toContainText("remote-after-outline-restore");+ await expect(outline).toHaveValue(new RegExp("remote-after-outline-restore"));+ await page.getByRole("button", { name: "画布视图", exact: true }).click();++ await canvas.focus();+ await page.keyboard.press("Tab");+ await page.clock.runFor(100);+ await nodeInput.fill("inline-draft-during-remote-update");+ await changeRemoteRoot("remote-while-editing");+ await page.clock.runFor(50);+ await expect(nodeInput).toHaveValue("inline-draft-during-remote-update");+ await expect(canvas).toContainText("remote-after-outline-restore");+ await canvas.focus();+ await page.clock.runFor(1_300);+ await waitForQueuedContent(page, memoId, "inline-draft-during-remote-update");+ const draft = await queueItemWithContent(page, memoId, "inline-draft-during-remote-update");+ expect(draft?.payload).toMatchObject({+ expectedRevision: idleRemote.revision,+ expectedContentHash: idleRemote.contentHash,+ });+ const remoteResponse = await page.request.get(`/api/v1/memos/${memoId}`);+ const { memo: remoteAfterDraft } = await remoteResponse.json() as { memo: { contentMarkdown: string } };+ expect(remoteAfterDraft.contentMarkdown).toContain("remote-while-editing");+ expect(remoteAfterDraft.contentMarkdown).not.toContain("inline-draft-during-remote-update");+ } finally {+ releaseAcknowledgment();+ await page.unroute(`**/api/v1/memos/${memoId}`);+ await page.request.delete(`/api/v1/memos/${memoId}`);+ await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);+ }+});++test("keeps a new mind-map editor and its draft when its temporary id is remapped", async ({ page }) => {+ let releaseCreate!: () => void;+ let created!: (id: string) => void;+ const createGate = new Promise<void>((resolve) => { releaseCreate = resolve; });+ const createdId = new Promise<string>((resolve) => { created = resolve; });+ let memoId: 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);+ const body = await response.json() as { memo: { id: string } };+ created(body.memo.id);+ await createGate;+ await route.fulfill({ response });+ });++ try {+ await page.goto("/");+ await page.getByRole("button", { name: "选择笔记类型", exact: true }).click();+ await page.getByRole("menuitem", { name: "思维导图", exact: true }).click();+ memoId = await createdId;+ 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());+ const title = page.getByRole("textbox", { name: "图表标题", exact: true });+ const marker = `new-diagram-${Date.now()}`;+ await title.fill(marker);+ await canvas.focus();+ await page.keyboard.press("Tab");+ await page.clock.runFor(100);+ const input = page.getByRole("textbox", { name: "编辑节点文字", exact: true });+ await input.fill("draft-during-id-remap");+ const originalGraph = await canvas.locator(".x6-graph-svg").elementHandle();+ const mapped = page.evaluate(() => new Promise<void>((resolve) => {+ window.addEventListener("edgeever:memo-id-remapped", () => resolve(), { once: true });+ }));+ releaseCreate();+ await mapped;+ await expect(page.locator(`[data-memo-id="${memoId}"]`)).toBeVisible();+ await expect(title).toHaveValue(marker);+ await expect(input).toHaveValue("draft-during-id-remap");+ await expect(input).toBeFocused();+ expect(await originalGraph!.evaluate((graph) => graph.isConnected)).toBe(true);+ await expect(canvas.locator(".x6-node")).toHaveCount(9);++ const saved = page.waitForResponse((response) => response.request().method() === "PATCH"+ && new URL(response.url()).pathname === `/api/v1/memos/${memoId}`+ && response.request().postDataJSON()?.contentMarkdown?.includes("draft-during-id-remap"));+ await canvas.focus();+ await page.clock.runFor(1_300);+ await expect.poll(async () => {+ if (await queueItemWithContent(page, memoId!, "draft-during-id-remap")) return true;+ const response = await page.request.get(`/api/v1/memos/${memoId}`);+ const body = await response.json() as { memo: { contentMarkdown: string } };+ return body.memo.contentMarkdown.includes("draft-during-id-remap");+ }).toBe(true);+ await page.evaluate(() => window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed")));+ const response = await saved;+ expect(response.ok(), await response.text()).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="${memoId}"]`).locator("button").first().click();+ await expect(title).toHaveValue(marker);+ await expect(canvas).toContainText("draft-during-id-remap");+ } finally {+ releaseCreate();+ await page.unroute("**/api/v1/memos");+ if (memoId) {+ await page.request.delete(`/api/v1/memos/${memoId}`);+ await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);+ }+ }+});