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(desktop): tolerate merged memo sync ordering
tianma-if9274fdf7d788
diff --git a/crates/desktop-sidecar/src/main.rs b/crates/desktop-sidecar/src/main.rsindex 115ceecf..b78be099 100644--- a/crates/desktop-sidecar/src/main.rs+++ b/crates/desktop-sidecar/src/main.rs@@ -345,4 +345,108 @@ mod tests {"Unsynced draft");}++ #[test]+ fn remote_merge_links_tolerate_bootstrap_page_order() {+ let database = Connection::open_in_memory().unwrap();+ database+ .execute_batch(+ "PRAGMA foreign_keys = ON;+ CREATE TABLE _edgeever_sidecar_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL, updated_at TEXT NOT NULL);+ CREATE TABLE notebooks (id TEXT PRIMARY KEY);+ CREATE TABLE memos (+ id TEXT PRIMARY KEY,+ notebook_id TEXT NOT NULL REFERENCES notebooks(id),+ title TEXT,+ excerpt TEXT NOT NULL,+ tags_json TEXT NOT NULL,+ is_pinned INTEGER NOT NULL,+ is_archived INTEGER NOT NULL,+ is_deleted INTEGER NOT NULL,+ source_memo_ids TEXT NOT NULL,+ merge_source_count INTEGER NOT NULL,+ merged_into_memo_id TEXT REFERENCES memos(id),+ created_at TEXT NOT NULL,+ updated_at TEXT NOT NULL,+ deleted_at TEXT+ );+ CREATE TABLE memo_contents (+ memo_id TEXT PRIMARY KEY REFERENCES memos(id) ON DELETE CASCADE,+ content_json TEXT NOT NULL,+ content_markdown TEXT NOT NULL,+ content_text TEXT NOT NULL,+ content_hash TEXT NOT NULL,+ revision INTEGER NOT NULL,+ updated_at TEXT NOT NULL DEFAULT 'now'+ );+ INSERT INTO notebooks VALUES ('notebook-1');",+ )+ .unwrap();++ let memo = |id: &str, merged_into: Option<&str>, source_ids: Vec<&str>| {+ json!({+ "id": id,+ "notebookId": "notebook-1",+ "title": id,+ "excerpt": "",+ "tags": [],+ "isPinned": false,+ "isArchived": false,+ "isDeleted": merged_into.is_some(),+ "sourceMemoIds": source_ids,+ "mergeSourceCount": 0,+ "mergedIntoMemoId": merged_into,+ "createdAt": "2026-09-06T00:00:00.000Z",+ "updatedAt": "2026-09-06T00:00:00.000Z",+ "deletedAt": merged_into.map(|_| "2026-09-06T00:00:00.000Z"),+ "contentJson": { "type": "doc", "content": [] },+ "contentMarkdown": "",+ "contentText": "",+ "contentHash": id,+ "revision": 0+ })+ };+ let apply_memo = |value: Value| {+ let id = value.get("id").and_then(Value::as_str).unwrap().to_owned();+ apply_sync_changes(+ &database,+ &json!({ "changes": [{+ "entityType": "memo",+ "operation": "upsert",+ "entityId": id,+ "memo": value+ }] }),+ )+ .unwrap();+ };++ apply_memo(memo("source-before", Some("merged"), vec![]));+ assert_eq!(+ database+ .query_row(+ "SELECT merged_into_memo_id FROM memos WHERE id = 'source-before'",+ [],+ |row| row.get::<_, Option<String>>(0),+ )+ .unwrap(),+ None+ );++ apply_memo(memo("merged", None, vec!["source-before", "source-after"]));+ apply_memo(memo("source-after", Some("merged"), vec![]));++ for source_id in ["source-before", "source-after"] {+ assert_eq!(+ database+ .query_row(+ "SELECT merged_into_memo_id FROM memos WHERE id = ?1",+ [source_id],+ |row| row.get::<_, Option<String>>(0),+ )+ .unwrap()+ .as_deref(),+ Some("merged")+ );+ }+ }}diff --git a/crates/desktop-sidecar/src/sync.rs b/crates/desktop-sidecar/src/sync.rsindex ce522531..1f4037d0 100644--- a/crates/desktop-sidecar/src/sync.rs+++ b/crates/desktop-sidecar/src/sync.rs@@ -656,17 +656,42 @@ pub(crate) fn apply_sync_changes(database: &Connection, params: &Value) -> Resul.cloned().unwrap_or_else(|| json!([])).to_string();- let source_ids = memo+ let source_memo_ids = memo.get("sourceMemoIds")+ .and_then(Value::as_array).cloned()- .unwrap_or_else(|| json!([]))- .to_string();+ .unwrap_or_default();+ let source_ids = Value::Array(source_memo_ids.clone()).to_string();+ let requested_merge_target = memo.get("mergedIntoMemoId").and_then(Value::as_str);+ // Bootstrap pages are ordered by memo id, not by merge dependency. A+ // deleted source can therefore arrive before the merged memo it+ // references. Cache the source without the unresolved foreign key;+ // the target's sourceMemoIds backfills it when that page arrives.+ let merge_target = if let Some(target_id) = requested_merge_target {+ let target_exists = tx+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM memos WHERE id = ?1)",+ [target_id],+ |row| row.get::<_, bool>(0),+ )+ .map_err(|e| e.to_string())?;+ target_exists.then_some(target_id)+ } else {+ None+ };let content_json = memo.get("contentJson").cloned().unwrap_or_else(|| json!({"type":"doc","content":[]}));- tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted, source_memo_ids, merge_source_count, merged_into_memo_id, created_at, updated_at, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14) ON CONFLICT(id) DO UPDATE SET notebook_id=excluded.notebook_id, title=excluded.title, excerpt=excluded.excerpt, tags_json=excluded.tags_json, is_pinned=excluded.is_pinned, is_archived=excluded.is_archived, is_deleted=excluded.is_deleted, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at", rusqlite::params![entity_id, string_param(memo, "notebookId")?, memo.get("title").and_then(Value::as_str), string_param(memo, "excerpt")?, tags, memo.get("isPinned").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isArchived").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isDeleted").and_then(Value::as_bool).unwrap_or(false) as i64, source_ids, memo.get("mergeSourceCount").and_then(Value::as_i64).unwrap_or(0), memo.get("mergedIntoMemoId").and_then(Value::as_str), string_param(memo, "createdAt")?, string_param(memo, "updatedAt")?, memo.get("deletedAt").and_then(Value::as_str)]).map_err(|e| e.to_string())?;+ tx.execute("INSERT INTO memos (id, notebook_id, title, excerpt, tags_json, is_pinned, is_archived, is_deleted, source_memo_ids, merge_source_count, merged_into_memo_id, created_at, updated_at, deleted_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14) ON CONFLICT(id) DO UPDATE SET notebook_id=excluded.notebook_id, title=excluded.title, excerpt=excluded.excerpt, tags_json=excluded.tags_json, is_pinned=excluded.is_pinned, is_archived=excluded.is_archived, is_deleted=excluded.is_deleted, source_memo_ids=excluded.source_memo_ids, merge_source_count=excluded.merge_source_count, merged_into_memo_id=excluded.merged_into_memo_id, updated_at=excluded.updated_at, deleted_at=excluded.deleted_at", rusqlite::params![entity_id, string_param(memo, "notebookId")?, memo.get("title").and_then(Value::as_str), string_param(memo, "excerpt")?, tags, memo.get("isPinned").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isArchived").and_then(Value::as_bool).unwrap_or(false) as i64, memo.get("isDeleted").and_then(Value::as_bool).unwrap_or(false) as i64, source_ids, memo.get("mergeSourceCount").and_then(Value::as_i64).unwrap_or(0), merge_target, string_param(memo, "createdAt")?, string_param(memo, "updatedAt")?, memo.get("deletedAt").and_then(Value::as_str)]).map_err(|e| e.to_string())?;tx.execute("INSERT INTO memo_contents (memo_id, content_json, content_markdown, content_text, content_hash, revision) VALUES (?1, ?2, ?3, ?4, ?5, ?6) ON CONFLICT(memo_id) DO UPDATE SET content_json=excluded.content_json, content_markdown=excluded.content_markdown, content_text=excluded.content_text, content_hash=excluded.content_hash, revision=excluded.revision, updated_at=strftime('%Y-%m-%dT%H:%M:%fZ','now')", rusqlite::params![entity_id, content_json.to_string(), string_param(memo, "contentMarkdown")?, string_param(memo, "contentText")?, string_param(memo, "contentHash")?, memo.get("revision").and_then(Value::as_i64).unwrap_or(0)]).map_err(|e| e.to_string())?;+ for source_id in source_memo_ids.iter().filter_map(Value::as_str) {+ tx.execute(+ "UPDATE memos SET merged_into_memo_id = ?1 WHERE id = ?2",+ rusqlite::params![entity_id, source_id],+ )+ .map_err(|e| e.to_string())?;+ }}tx.commit().map_err(|e| e.to_string())?;Ok(json!({ "applied": changes.len() }))