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(sync): rebuild local mirrors after server reset
tianma-if4857315f4ceb
diff --git a/apps/web/src/lib/desktop-sync.test.mjs b/apps/web/src/lib/desktop-sync.test.mjsindex e342138a..d519eac8 100644--- a/apps/web/src/lib/desktop-sync.test.mjs+++ b/apps/web/src/lib/desktop-sync.test.mjs@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";const {isStagedResourceReferenced,+ hasDesktopSyncStateReset,mergeMemoIdMappings,mergeSyncedMemos,orderBootstrapNotebooks,@@ -60,6 +61,13 @@ describe("desktop staged resource sync", () => {});describe("desktop bootstrap sync", () => {+ test("rebuilds when the server cursor rewinds or its identity changes", () => {+ const local = { cursor: 42, syncIdentity: "workspace-a" };+ expect(hasDesktopSyncStateReset(local, { serverCursor: 7, syncIdentity: "workspace-a" })).toBe(true);+ expect(hasDesktopSyncStateReset(local, { serverCursor: 42, syncIdentity: "workspace-b" })).toBe(true);+ expect(hasDesktopSyncStateReset(local, { serverCursor: 64, syncIdentity: "workspace-a" })).toBe(false);+ });+test("orders parent notebooks before their children", () => {const child = { id: "child", parentId: "parent", name: "Child" };const parent = { id: "parent", parentId: null, name: "Parent" };diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.tsindex 36906a3e..5471dd1f 100644--- a/apps/web/src/lib/desktop-sync.ts+++ b/apps/web/src/lib/desktop-sync.ts@@ -404,6 +404,13 @@ const applyBootstrap = async (page: SyncBootstrapResponse) => {if (changes.length > 0) await request("sync.apply", { changes });};+export const hasDesktopSyncStateReset = (+ local: { cursor: number; syncIdentity: string },+ remote: Pick<SyncChangesResponse, "serverCursor" | "syncIdentity">,+) => remote.serverCursor < local.cursor || Boolean(+ remote.syncIdentity && remote.syncIdentity !== local.syncIdentity,+);+export const orderBootstrapNotebooks = (notebooks: SyncBootstrapResponse["notebooks"]) => {const remaining = new Map(notebooks.map((notebook) => [notebook.id, notebook]));const ordered: SyncBootstrapResponse["notebooks"] = [];@@ -425,31 +432,47 @@ export const orderBootstrapNotebooks = (notebooks: SyncBootstrapResponse["noteboreturn ordered;};+const bootstrapDesktopMirror = async (reset: boolean) => {+ await request("sync.bootstrap.prepare", reset ? { reset: true } : {});+ let afterId: string | null = null;+ let firstPage = true;+ let snapshotCursor = 0;+ let syncIdentity = "";+ do {+ const page = await api.syncBootstrap({ afterId, limit: 200 });+ if (firstPage) {+ snapshotCursor = page.snapshotCursor;+ syncIdentity = page.syncIdentity ?? "";+ firstPage = false;+ }+ await applyBootstrap(page);+ afterId = page.nextAfterId;+ } while (afterId);+ await request("sync.cursor.set", { cursor: snapshotCursor, syncIdentity });+};+const pullRemoteChanges = async () => {const status = await request("sync.status", {});if (!status.syncIdentity) {- await request("sync.bootstrap.prepare", {});- let afterId: string | null = null;- let snapshotCursor = 0;- let syncIdentity = "";- do {- const page = await api.syncBootstrap({ afterId, limit: 200 });- if (!snapshotCursor) snapshotCursor = page.snapshotCursor;- syncIdentity = page.syncIdentity ?? syncIdentity;- await applyBootstrap(page);- afterId = page.nextAfterId;- } while (afterId);- await request("sync.cursor.set", { cursor: snapshotCursor, syncIdentity });+ await bootstrapDesktopMirror(false);return;}let cursor = status.cursor;let response: SyncChangesResponse = await api.syncChanges({ cursor, limit: 200 });+ if (hasDesktopSyncStateReset({ cursor: status.cursor, syncIdentity: status.syncIdentity }, response)) {+ await bootstrapDesktopMirror(true);+ return;+ }while (response.changes.length > 0) {await request("sync.apply", { changes: response.changes });cursor = response.cursor;if (!response.hasMore) break;response = await api.syncChanges({ cursor, limit: 200 });+ if (hasDesktopSyncStateReset({ cursor, syncIdentity: status.syncIdentity }, response)) {+ await bootstrapDesktopMirror(true);+ return;+ }}await request("sync.cursor.set", { cursor: response.cursor ?? cursor, syncIdentity: response.syncIdentity ?? status.syncIdentity });};diff --git a/apps/web/src/lib/local-mirror.test.mjs b/apps/web/src/lib/local-mirror.test.mjsindex 1548f78d..8550084e 100644--- a/apps/web/src/lib/local-mirror.test.mjs+++ b/apps/web/src/lib/local-mirror.test.mjs@@ -33,7 +33,10 @@ const {listLocalResources,replaceLocalResources,remapLocalDraftMemoId,+ hasLocalSyncCursorRewound,+ syncLocalMirror,} = await import("./local-mirror.ts");+const { api } = await import("./api.ts");const { getCachedLocalResourceBytes } = await import("./local-resource-cache.ts");afterEach(async () => {@@ -57,6 +60,48 @@ afterEach(async () => {});describe("local mirror", () => {+ test("rebuilds the browser mirror when the server change cursor rewinds", () => {+ expect(hasLocalSyncCursorRewound(42, 7)).toBe(true);+ expect(hasLocalSyncCursorRewound(42, 42)).toBe(false);+ expect(hasLocalSyncCursorRewound(42, 64)).toBe(false);+ expect(hasLocalSyncCursorRewound(42)).toBe(false);+ });++ test("replaces stale IndexedDB data after the server change log is reset", async () => {+ const scope = createLocalDataScope("https://demo.edgeever.org", "user-1");+ await createLocalMemo(scope, { notebookId: "old-notebook", title: "Stale cached note" });+ await localDb.syncMeta.bulkPut([+ { scope, key: "cursor", value: "42", updatedAt: "2026-01-01T00:00:00.000Z" },+ { scope, key: "identity", value: "same-workspace", updatedAt: "2026-01-01T00:00:00.000Z" },+ ]);+ const originalSyncChanges = api.syncChanges;+ const originalSyncBootstrap = api.syncBootstrap;+ api.syncChanges = async () => ({+ changes: [],+ cursor: 42,+ hasMore: false,+ serverCursor: 7,+ syncIdentity: "same-workspace",+ });+ api.syncBootstrap = async () => ({+ notebooks: [],+ memos: [],+ snapshotCursor: 7,+ syncIdentity: "same-workspace",+ totalCount: 0,+ nextAfterId: null,+ });++ try {+ expect(await syncLocalMirror(scope)).toEqual({ bootstrapped: true, changed: 0 });+ expect((await listLocalMemos(scope, {})).totalCount).toBe(0);+ expect((await localDb.syncMeta.get([scope, "cursor"]))?.value).toBe("7");+ } finally {+ api.syncChanges = originalSyncChanges;+ api.syncBootstrap = originalSyncBootstrap;+ }+ });+test("keeps the newest draft when memo ids are remapped more than once", async () => {await localDb.drafts.put({memoId: "local-memo",diff --git a/apps/web/src/lib/local-mirror.ts b/apps/web/src/lib/local-mirror.tsindex e90c8acd..aff7b08c 100644--- a/apps/web/src/lib/local-mirror.ts+++ b/apps/web/src/lib/local-mirror.ts@@ -36,6 +36,9 @@ export const createLocalDataScope = (baseUrl: string, userId?: string | null) =>const getMeta = async (scope: string, key: string) =>(await localDb.syncMeta.get([scope, key]))?.value ?? null;+export const hasLocalSyncCursorRewound = (localCursor: number, serverCursor?: number) =>+ typeof serverCursor === "number" && Number.isFinite(serverCursor) && serverCursor < localCursor;+export const isLocalMirrorInitialized = async (scope: string) => Boolean(await getMeta(scope, SYNC_IDENTITY_KEY));export const hasLocalMirrorData = async (scope: string) =>@@ -142,7 +145,15 @@ const performSyncLocalMirror = async (scope: string) => {let currentCursor = cursor;let response = await api.syncChanges({ cursor: currentCursor, limit: CHANGE_PAGE_SIZE });- if (response.syncIdentity && response.syncIdentity !== storedIdentity) {+ if (+ hasLocalSyncCursorRewound(currentCursor, response.serverCursor) ||+ (response.syncIdentity && response.syncIdentity !== storedIdentity)+ ) {+ // Restoring or clearing a server database can restart the change-log+ // sequence without replacing the workspace row. In that case the saved+ // browser cursor is ahead of the server and an incremental request looks+ // empty even though the IndexedDB mirror is stale. Rebuild from the+ // authoritative snapshot just as we do for a changed sync identity.changed = await bootstrapScope(scope);return { bootstrapped: true, changed };}diff --git a/crates/desktop-sidecar/src/main.rs b/crates/desktop-sidecar/src/main.rsindex 5d6f60b8..fc41726d 100644--- a/crates/desktop-sidecar/src/main.rs+++ b/crates/desktop-sidecar/src/main.rs@@ -1136,9 +1136,72 @@ fn sync_status(database: &Connection) -> Result<Value, String> {}))}-fn prepare_sync_bootstrap(database: &Connection) -> Result<Value, String> {+const SYNC_BOOTSTRAP_RESET_KEY: &str = "sync.bootstrap.reset_pending";++fn reset_sync_mirror(database: &Connection) -> Result<(), String> {+ let tx = database+ .unchecked_transaction()+ .map_err(|e| e.to_string())?;+ tx.execute_batch(+ "CREATE TEMP TABLE IF NOT EXISTS _edgeever_bootstrap_preserved_memos (id TEXT PRIMARY KEY);+ CREATE TEMP TABLE IF NOT EXISTS _edgeever_bootstrap_preserved_notebooks (id TEXT PRIMARY KEY);+ DELETE FROM _edgeever_bootstrap_preserved_memos;+ DELETE FROM _edgeever_bootstrap_preserved_notebooks;+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_memos (id)+ SELECT m.id FROM memos m+ WHERE EXISTS (+ SELECT 1 FROM _edgeever_sidecar_outbox o+ WHERE o.entity_id = m.id OR instr(o.payload_json, m.id) > 0+ );+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)+ SELECT n.id FROM notebooks n+ WHERE EXISTS (+ SELECT 1 FROM _edgeever_sidecar_outbox o+ WHERE o.entity_id = n.id OR instr(o.payload_json, n.id) > 0+ );+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)+ SELECT DISTINCT m.notebook_id+ FROM memos m+ INNER JOIN _edgeever_bootstrap_preserved_memos p ON p.id = m.id;+ WITH RECURSIVE preserved_ancestors(id, parent_id) AS (+ SELECT n.id, n.parent_id+ FROM notebooks n+ INNER JOIN _edgeever_bootstrap_preserved_notebooks p ON p.id = n.id+ UNION+ SELECT parent.id, parent.parent_id+ FROM notebooks parent+ INNER JOIN preserved_ancestors child ON child.parent_id = parent.id+ )+ INSERT OR IGNORE INTO _edgeever_bootstrap_preserved_notebooks (id)+ SELECT id FROM preserved_ancestors;+ DELETE FROM resources+ WHERE memo_id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_memos);+ DELETE FROM memos+ WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_memos);+ UPDATE notebooks SET parent_id = NULL+ WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_notebooks);+ DELETE FROM notebooks+ WHERE id NOT IN (SELECT id FROM _edgeever_bootstrap_preserved_notebooks);+ DELETE FROM _edgeever_sidecar_meta+ WHERE key IN ('sync.cursor', 'sync.identity', 'sync.last_synced_at');+ INSERT INTO _edgeever_sidecar_meta (key, value, updated_at)+ VALUES ('sync.bootstrap.reset_pending', '1', strftime('%Y-%m-%dT%H:%M:%fZ','now'))+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at;",+ )+ .map_err(|e| e.to_string())?;+ tx.commit().map_err(|e| e.to_string())+}++fn prepare_sync_bootstrap(database: &Connection, params: &Value) -> Result<Value, String> {+ let reset_requested = bool_param(params, "reset", false)+ || meta_value(database, SYNC_BOOTSTRAP_RESET_KEY).as_deref() == Some("1");+ if reset_requested {+ reset_sync_mirror(database)?;+ return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": true }));+ }+if meta_value(database, "sync.identity").is_some_and(|identity| !identity.is_empty()) {- return Ok(json!({ "clearedSeedData": false }));+ return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": false }));}let outbox_count = database@@ -1163,7 +1226,7 @@ fn prepare_sync_bootstrap(database: &Connection) -> Result<Value, String> {.map_err(|e| e.to_string())?;if outbox_count > 0 || non_seed_memos > 0 || non_seed_notebooks > 0 {- return Ok(json!({ "clearedSeedData": false }));+ return Ok(json!({ "clearedSeedData": false, "rebuiltMirror": false }));}let tx = database@@ -1178,7 +1241,7 @@ fn prepare_sync_bootstrap(database: &Connection) -> Result<Value, String> {).map_err(|e| e.to_string())?;tx.commit().map_err(|e| e.to_string())?;- Ok(json!({ "clearedSeedData": true }))+ Ok(json!({ "clearedSeedData": true, "rebuiltMirror": false }))}fn sync_outbox_list(database: &Connection, params: &Value) -> Result<Value, String> {@@ -1410,6 +1473,7 @@ fn apply_sync_changes(database: &Connection, params: &Value) -> Result<Value, St.get("changes").and_then(Value::as_array).ok_or_else(|| "Missing changes array".to_owned())?;+ let rebuilding = meta_value(database, SYNC_BOOTSTRAP_RESET_KEY).as_deref() == Some("1");let tx = database.unchecked_transaction().map_err(|e| e.to_string())?;@@ -1417,6 +1481,23 @@ fn apply_sync_changes(database: &Connection, params: &Value) -> Result<Value, Stlet entity_type = string_param(change, "entityType")?;let operation = string_param(change, "operation")?;let entity_id = string_param(change, "entityId")?;+ if rebuilding {+ let preserved_table = if entity_type == "notebook" {+ "_edgeever_bootstrap_preserved_notebooks"+ } else {+ "_edgeever_bootstrap_preserved_memos"+ };+ let preserved = tx+ .query_row(+ &format!("SELECT EXISTS(SELECT 1 FROM {preserved_table} WHERE id = ?1)"),+ [&entity_id],+ |row| row.get::<_, bool>(0),+ )+ .unwrap_or(false);+ if preserved {+ continue;+ }+ }if entity_type == "notebook" {if operation == "delete" {tx.execute("UPDATE notebooks SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1", [&entity_id]).map_err(|e| e.to_string())?;@@ -1479,7 +1560,7 @@ fn handle("storage.backups" => list_backups(root).map_err(|error| error.to_string()),"storage.restore" => restore_database(database, root, migrations, &request.params),"sync.status" => sync_status(database),- "sync.bootstrap.prepare" => prepare_sync_bootstrap(database),+ "sync.bootstrap.prepare" => prepare_sync_bootstrap(database, &request.params),"sync.outbox.list" => sync_outbox_list(database, &request.params),"sync.outbox.ack" => sync_outbox_ack(database, &request.params),"sync.outbox.fail" => sync_outbox_fail(database, &request.params),@@ -1506,6 +1587,18 @@ fn handle(.unwrap_or(""),)?;set_meta(database, "sync.last_synced_at", &chrono_like_now())?;+ database+ .execute(+ "DELETE FROM _edgeever_sidecar_meta WHERE key = ?1",+ [SYNC_BOOTSTRAP_RESET_KEY],+ )+ .map_err(|e| e.to_string())?;+ database+ .execute_batch(+ "DROP TABLE IF EXISTS temp._edgeever_bootstrap_preserved_memos;+ DROP TABLE IF EXISTS temp._edgeever_bootstrap_preserved_notebooks;",+ )+ .map_err(|e| e.to_string())?;Ok(json!({ "ok": true }))}"notebook.list" => list_notebooks(database),@@ -1655,4 +1748,94 @@ mod tests {).is_err());}++ #[test]+ fn mirror_reset_removes_stale_cache_and_preserves_outbox_drafts() {+ 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 _edgeever_sidecar_outbox (id INTEGER PRIMARY KEY, kind TEXT NOT NULL, entity_id TEXT NOT NULL, payload_json TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending');+ CREATE TABLE notebooks (id TEXT PRIMARY KEY, parent_id TEXT REFERENCES notebooks(id) ON DELETE RESTRICT, name TEXT NOT NULL);+ CREATE TABLE memos (id TEXT PRIMARY KEY, notebook_id TEXT NOT NULL REFERENCES notebooks(id) ON DELETE RESTRICT, title TEXT);+ CREATE TABLE memo_contents (memo_id TEXT PRIMARY KEY REFERENCES memos(id) ON DELETE CASCADE, content_markdown TEXT NOT NULL);+ CREATE TABLE resources (id TEXT PRIMARY KEY, memo_id TEXT NOT NULL REFERENCES memos(id) ON DELETE RESTRICT);+ INSERT INTO _edgeever_sidecar_meta VALUES ('sync.cursor', '42', 'now'), ('sync.identity', 'workspace-a', 'now');+ INSERT INTO notebooks VALUES ('stale-notebook', NULL, 'Stale'), ('draft-parent', NULL, 'Draft parent'), ('draft-notebook', 'draft-parent', 'Draft');+ INSERT INTO memos VALUES ('stale-memo', 'stale-notebook', 'Stale cache'), ('draft-memo', 'draft-notebook', 'Unsynced draft');+ INSERT INTO memo_contents VALUES ('stale-memo', 'stale'), ('draft-memo', 'local changes');+ INSERT INTO resources VALUES ('stale-resource', 'stale-memo'), ('draft-resource', 'draft-memo');+ INSERT INTO _edgeever_sidecar_outbox (id, kind, entity_id, payload_json) VALUES (1, 'memo.update', 'draft-memo', '{\"memoId\":\"draft-memo\"}');",+ )+ .unwrap();++ let result = prepare_sync_bootstrap(&database, &json!({ "reset": true })).unwrap();+ assert_eq!(+ result.get("rebuiltMirror").and_then(Value::as_bool),+ Some(true)+ );+ assert_eq!(+ database+ .query_row(+ "SELECT COUNT(*) FROM memos WHERE id = 'stale-memo'",+ [],+ |row| row.get::<_, i64>(0)+ )+ .unwrap(),+ 0+ );+ assert_eq!(+ database+ .query_row(+ "SELECT content_markdown FROM memo_contents WHERE memo_id = 'draft-memo'",+ [],+ |row| row.get::<_, String>(0)+ )+ .unwrap(),+ "local changes"+ );+ assert_eq!(+ database+ .query_row(+ "SELECT COUNT(*) FROM notebooks WHERE id IN ('draft-parent', 'draft-notebook')",+ [],+ |row| row.get::<_, i64>(0)+ )+ .unwrap(),+ 2+ );+ assert_eq!(+ database+ .query_row(+ "SELECT COUNT(*) FROM resources WHERE id = 'draft-resource'",+ [],+ |row| row.get::<_, i64>(0)+ )+ .unwrap(),+ 1+ );+ assert!(meta_value(&database, "sync.cursor").is_none());++ apply_sync_changes(+ &database,+ &json!({ "changes": [{+ "entityType": "memo",+ "operation": "upsert",+ "entityId": "draft-memo",+ "memo": { "title": "Cloud snapshot must not overwrite this" }+ }] }),+ )+ .unwrap();+ assert_eq!(+ database+ .query_row(+ "SELECT title FROM memos WHERE id = 'draft-memo'",+ [],+ |row| row.get::<_, String>(0)+ )+ .unwrap(),+ "Unsynced draft"+ );+ }}diff --git a/packages/shared/src/desktop-rpc.ts b/packages/shared/src/desktop-rpc.tsindex 3068cef1..7e6cbbf0 100644--- a/packages/shared/src/desktop-rpc.ts+++ b/packages/shared/src/desktop-rpc.ts@@ -106,7 +106,7 @@ export type DesktopRpcResponses = {"memo.restoreRevision": { memo: MemoDetail };"memo.revision.cache": { ok: true };"sync.status": { pending: number; syncing: number; conflict: number; error: number; cursor: number; syncIdentity: string | null; lastSyncedAt: string | null };- "sync.bootstrap.prepare": { clearedSeedData: boolean };+ "sync.bootstrap.prepare": { clearedSeedData: boolean; rebuiltMirror: boolean };"sync.outbox.list": { items: DesktopOutboxItem[] };"sync.outbox.ack": { ok: true; memo: MemoDetail | null; notebook: Notebook | null; template: MemoTemplate | null };"sync.outbox.fail": { ok: true };@@ -152,7 +152,7 @@ export type DesktopRpcParams = {"memo.restoreRevision": { memoId: string; revisionId: string };"memo.revision.cache": { revision: import("./types").MemoRevision };"sync.status": Record<string, never>;- "sync.bootstrap.prepare": Record<string, never>;+ "sync.bootstrap.prepare": { reset?: boolean };"sync.outbox.list": { limit?: number };"sync.outbox.ack": { id: number; remoteMemo?: MemoDetail; remoteNotebook?: Notebook; remoteTemplate?: MemoTemplate };"sync.outbox.fail": { id: number; error: string; conflict?: boolean };