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): recover same-device lost-ack memo updates
tianma-if1ae14f0e6930
diff --git a/apps/web/src/lib/desktop-sync.test.mjs b/apps/web/src/lib/desktop-sync.test.mjsindex a524eb69..107721a3 100644--- a/apps/web/src/lib/desktop-sync.test.mjs+++ b/apps/web/src/lib/desktop-sync.test.mjs@@ -13,6 +13,8 @@ const {orderBootstrapNotebooks,orderDesktopSyncChanges,resolveDesktopMemoSyncBase,+ resolveDesktopStaleMemoUpdate,+ desktopLocalRevisionWitnessesRemote,rewriteStagedResource,shouldAttemptDesktopRecoveryPull,shouldPullDesktopChanges,@@ -143,6 +145,91 @@ describe("desktop memo sync base", () => {{ expectedRevision: 3, expectedContentHash: "cloud-3" },)).toEqual({ expectedRevision: 3, expectedContentHash: "cloud-3" });});++ test("acks a lost save when the cloud already has the queued payload", () => {+ expect(resolveDesktopStaleMemoUpdate({+ current: { revision: 10, contentHash: "hash-a" },+ expected: { expectedRevision: 9, expectedContentHash: "hash-before" },+ payload: { title: "", tags: [], contentMarkdown: "一期验收通过。", contentJson: { type: "doc" } },+ remote: { title: "无标题笔记", tags: [], contentMarkdown: "一期验收通过。", contentHash: "hash-a", contentJson: { type: "doc" } },+ localRevisions: [],+ })).toBe("ack");+ });++ test("rebases a later local draft when a sidecar snapshot already contains the cloud body", () => {+ const remote = {+ title: "无标题笔记",+ tags: [],+ contentMarkdown: "一期验收通过。",+ contentHash: "hash-a",+ contentJson: { type: "doc", content: [{ type: "paragraph" }] },+ };++ expect(desktopLocalRevisionWitnessesRemote([+ {+ id: "revision_local_1",+ revision: 9,+ contentHash: "sidecar-a",+ contentMarkdown: "一期验收通过。",+ contentJson: remote.contentJson,+ },+ ], remote, 9)).toBe(true);++ expect(resolveDesktopStaleMemoUpdate({+ current: { revision: 10, contentHash: "hash-a" },+ expected: { expectedRevision: 9, expectedContentHash: "hash-before" },+ payload: { title: "", tags: [], contentMarkdown: "一期验收通过。然后继续写。", contentJson: { type: "doc" } },+ remote,+ localRevisions: [{+ id: "revision_local_1",+ revision: 9,+ contentHash: "sidecar-a",+ contentMarkdown: "一期验收通过。",+ contentJson: remote.contentJson,+ }],+ })).toBe("rebase");+ });++ test("does not treat an older local snapshot or a remote-cached revision as proof", () => {+ const remote = {+ title: "无标题笔记",+ tags: [],+ contentMarkdown: "别人改过的正文",+ contentHash: "hash-other",+ contentJson: { type: "doc" },+ };++ expect(desktopLocalRevisionWitnessesRemote([+ {+ id: "revision_local_old",+ revision: 3,+ contentHash: "hash-other",+ contentMarkdown: "别人改过的正文",+ contentJson: remote.contentJson,+ },+ {+ id: "rev_remote_cached",+ revision: 10,+ contentHash: "hash-other",+ contentMarkdown: "别人改过的正文",+ contentJson: remote.contentJson,+ },+ ], remote, 9)).toBe(false);++ expect(resolveDesktopStaleMemoUpdate({+ current: { revision: 10, contentHash: "hash-other" },+ expected: { expectedRevision: 9, expectedContentHash: "hash-before" },+ payload: { title: "", tags: [], contentMarkdown: "本地还在写的草稿", contentJson: { type: "doc" } },+ remote,+ localRevisions: [{+ id: "revision_local_9",+ revision: 9,+ contentHash: "sidecar-local",+ contentMarkdown: "本地还在写的草稿",+ contentJson: { type: "doc" },+ }],+ })).toBe("conflict");+ });});describe("desktop sync failure handling", () => {diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.tsindex 743df579..18ba9b95 100644--- a/apps/web/src/lib/desktop-sync.ts+++ b/apps/web/src/lib/desktop-sync.ts@@ -2,10 +2,15 @@ import {getMemoSyncBaseConflictDetails,getSyncRetryAt,hasSyncStateReset,+ isDesktopLocalRevisionId,isMemoSyncBaseCurrent,+ memoUpdatePayloadMatchesRemote,+ resolveSameDeviceMemoSyncRecovery,type DesktopOutboxItem,type DesktopRpcParams,type DesktopRpcResponses,+ type MemoDetail,+ type SameDeviceMemoSyncRecovery,type SyncBootstrapResponse,type SyncChangesResponse,type TiptapDoc,@@ -226,8 +231,8 @@ export const resolveDesktopMemoSyncBase = (// Older desktop clients advanced the cached cloud revision for every local// autosave. A base ahead of the actual server is therefore a local counter,// not evidence of a concurrent remote edit. Rebase that impossible state so- // existing drafts recover automatically. Bases behind the server remain- // conflicts and keep the normal adopt-cloud/copy-draft protection.+ // existing drafts recover automatically. Bases behind the server are inspected+ // by resolveDesktopStaleMemoUpdate before becoming a user-facing conflict.if (expected.expectedRevision > current.revision) {return {expectedRevision: current.revision,@@ -237,6 +242,54 @@ export const resolveDesktopMemoSyncBase = (return expected;};+type DesktopLocalRevisionWitness = {+ id: string;+ revision: number;+ contentHash: string;+ contentMarkdown: string;+ contentJson?: unknown;+};++export const desktopLocalRevisionWitnessesRemote = (+ revisions: ReadonlyArray<DesktopLocalRevisionWitness>,+ remote: { contentHash: string; contentMarkdown: string; contentJson?: unknown },+ expectedRevision: number,+) => revisions.some((revision) => {+ if (!isDesktopLocalRevisionId(revision.id) || revision.revision < expectedRevision) {+ return false;+ }+ if (revision.contentHash === remote.contentHash) {+ return true;+ }+ if (revision.contentMarkdown !== remote.contentMarkdown) {+ return false;+ }+ return revision.contentMarkdown !== ""+ || JSON.stringify(revision.contentJson ?? null) === JSON.stringify(remote.contentJson ?? null);+});++export const resolveDesktopStaleMemoUpdate = (input: {+ current: { revision: number; contentHash: string };+ expected: { expectedRevision: number; expectedContentHash: string };+ payload: {+ title?: unknown;+ tags?: unknown;+ contentMarkdown?: unknown;+ contentJson?: unknown;+ };+ remote: Pick<MemoDetail, "title" | "tags" | "contentMarkdown" | "contentHash" | "contentJson">;+ localRevisions: ReadonlyArray<DesktopLocalRevisionWitness>;+}): SameDeviceMemoSyncRecovery => resolveSameDeviceMemoSyncRecovery({+ current: input.current,+ expected: input.expected,+ payloadMatchesRemote: memoUpdatePayloadMatchesRemote(input.payload, input.remote),+ remoteProducedLocally: desktopLocalRevisionWitnessesRemote(+ input.localRevisions,+ input.remote,+ input.expected.expectedRevision,+ ),+});+const acknowledge = async (item: DesktopOutboxItem,remoteMemo?: DesktopRpcResponses["memo.get"]["memo"],@@ -277,17 +330,44 @@ const syncOutboxItem = async (item: DesktopOutboxItem, stagedRewrites: StagedRes};const currentBase = { revision: editSession.baseRevision, contentHash: editSession.baseContentHash };const expectedBase = resolveDesktopMemoSyncBase(currentBase, queuedBase);+ let syncBase = expectedBase;if (!isMemoSyncBaseCurrent(currentBase, expectedBase)) {- throw new ApiRequestError(- "Note changed before the offline draft could sync.",- 409,- "revision_conflict",- getMemoSyncBaseConflictDetails(currentBase, expectedBase),- );+ const remote = await api.getMemo(memoId, { includeDeleted: true });+ let localRevisions: DesktopLocalRevisionWitness[] = [];+ try {+ localRevisions = (await request("memo.revisions", { memoId, limit: 200 })).revisions;+ } catch {+ // A lost acknowledgement of the exact payload can still be acked+ // without local history. Missing snapshots keep a genuine remote edit+ // as a conflict.+ }+ const recovery = resolveDesktopStaleMemoUpdate({+ current: currentBase,+ expected: expectedBase,+ payload,+ remote: remote.memo,+ localRevisions,+ });+ if (recovery === "ack") {+ await acknowledge(item, remote.memo);+ return remote.memo;+ }+ if (recovery !== "rebase") {+ throw new ApiRequestError(+ "Note changed before the offline draft could sync.",+ 409,+ "revision_conflict",+ getMemoSyncBaseConflictDetails(currentBase, expectedBase),+ );+ }+ syncBase = {+ expectedRevision: currentBase.revision,+ expectedContentHash: currentBase.contentHash,+ };}const data = await api.updateMemo(memoId, {- expectedRevision: expectedBase.expectedRevision,- expectedContentHash: expectedBase.expectedContentHash,+ expectedRevision: syncBase.expectedRevision,+ expectedContentHash: syncBase.expectedContentHash,editSessionId: editSession.id,title: String(payload.title ?? ""),contentJson: payload.contentJson as TiptapDoc,diff --git a/packages/shared/src/desktop-rpc.test.mjs b/packages/shared/src/desktop-rpc.test.mjsindex 78975fc0..9955f20a 100644--- a/packages/shared/src/desktop-rpc.test.mjs+++ b/packages/shared/src/desktop-rpc.test.mjs@@ -1,8 +1,10 @@import { describe, expect, test } from "bun:test";import { readFileSync } from "node:fs";import {+ DESKTOP_LOCAL_REVISION_ID_PREFIX,DESKTOP_RPC_METHODS,DESKTOP_SIDECAR_PROTOCOL_VERSION,+ isDesktopLocalRevisionId,} from "./desktop-rpc.ts";const rustRpcSource = readFileSync(@@ -36,6 +38,12 @@ describe("desktop sidecar RPC contract", () => {expect(rustMemoSource).toContain("LOWER(TRIM(CAST(memo_tag.value AS TEXT))) = LOWER(?5)");});+ test("keeps sidecar local revision ids distinguishable from cached remote revisions", () => {+ expect(rustMemoSource).toContain(`now_id("${DESKTOP_LOCAL_REVISION_ID_PREFIX.slice(0, -1)}")`);+ expect(isDesktopLocalRevisionId("revision_local_1789810000000")).toBe(true);+ expect(isDesktopLocalRevisionId("revision_abc123")).toBe(false);+ });+test("keeps the native and Electron protocol guards aligned", () => {const rustVersion = Number(rustRpcSource.match(/const PROTOCOL_VERSION: i64 = (\d+);/)?.[1]);const electronVersion = Number(diff --git a/packages/shared/src/desktop-rpc.ts b/packages/shared/src/desktop-rpc.tsindex d972aa71..84c0cc11 100644--- a/packages/shared/src/desktop-rpc.ts+++ b/packages/shared/src/desktop-rpc.ts@@ -3,6 +3,12 @@ import type { TiptapDoc } from "./content";export const DESKTOP_SIDECAR_PROTOCOL_VERSION = 2;+/** Sidecar-authored memo revision ids. Remote cached revisions use server ids. */+export const DESKTOP_LOCAL_REVISION_ID_PREFIX = "revision_local_";++export const isDesktopLocalRevisionId = (id: string) =>+ id.startsWith(DESKTOP_LOCAL_REVISION_ID_PREFIX);+export const DESKTOP_RPC_METHODS = ["system.info","storage.health",diff --git a/packages/shared/src/sync.test.mjs b/packages/shared/src/sync.test.mjsindex 0a4b0f04..4c06c562 100644--- a/packages/shared/src/sync.test.mjs+++ b/packages/shared/src/sync.test.mjs@@ -11,6 +11,8 @@ import {hasSyncStateReset,isSyncMetadataInitialized,isMemoSyncBaseCurrent,+ memoUpdatePayloadMatchesRemote,+ resolveSameDeviceMemoSyncRecovery,splitSyncBootstrapWriteBatches,summarizeSyncQueue,} from "./sync.ts";@@ -88,6 +90,47 @@ describe("shared sync queue contract", () => {});});+ test("treats a lost acknowledgement of the same payload as already applied", () => {+ const current = { revision: 10, contentHash: "cloud-a" };+ const expected = { expectedRevision: 9, expectedContentHash: "cloud-before-a" };++ expect(resolveSameDeviceMemoSyncRecovery({+ current,+ expected,+ payloadMatchesRemote: true,+ remoteProducedLocally: false,+ })).toBe("ack");+ expect(memoUpdatePayloadMatchesRemote(+ { title: "", tags: [], contentMarkdown: "我们和客户签合同包含了几期。", contentJson: { type: "doc" } },+ { title: "无标题笔记", tags: [], contentMarkdown: "我们和客户签合同包含了几期。", contentJson: { type: "doc" } },+ )).toBe(true);+ });++ test("rebases a later local draft when this device produced the cloud snapshot", () => {+ const current = { revision: 10, contentHash: "cloud-a" };+ const expected = { expectedRevision: 9, expectedContentHash: "cloud-before-a" };++ expect(resolveSameDeviceMemoSyncRecovery({+ current,+ expected,+ payloadMatchesRemote: false,+ remoteProducedLocally: true,+ })).toBe("rebase");+ });++ test("keeps a genuine remote edit as a conflict", () => {+ expect(resolveSameDeviceMemoSyncRecovery({+ current: { revision: 10, contentHash: "cloud-other" },+ expected: { expectedRevision: 9, expectedContentHash: "cloud-before-a" },+ payloadMatchesRemote: false,+ remoteProducedLocally: false,+ })).toBe("conflict");+ expect(memoUpdatePayloadMatchesRemote(+ { title: "无标题笔记", tags: [], contentMarkdown: "本地草稿", contentJson: { type: "doc", content: [] } },+ { title: "无标题笔记", tags: [], contentMarkdown: "别人改过", contentJson: { type: "doc", content: [] } },+ )).toBe(false);+ });+test("detects a reset shared by mobile and desktop mirrors", () => {expect(hasSyncCursorRewound(42, 7)).toBe(true);expect(hasSyncCursorRewound(42, 42)).toBe(false);diff --git a/packages/shared/src/sync.ts b/packages/shared/src/sync.tsindex ecceae3b..cbccf40c 100644--- a/packages/shared/src/sync.ts+++ b/packages/shared/src/sync.ts@@ -1,3 +1,4 @@+import { DEFAULT_MEMO_TITLE } from "./content";import type { MemoDetail, Notebook } from "./types";export type SyncEntityType = "memo" | "notebook";@@ -101,6 +102,61 @@ export const getMemoSyncBaseConflictDetails = (source: "offline_sync" as const,});+export type SameDeviceMemoSyncRecovery = "ack" | "rebase" | "conflict";++const normalizeMemoSyncTitle = (value: unknown) => {+ const title = typeof value === "string" ? value.trim() : "";+ return title || DEFAULT_MEMO_TITLE;+};++const normalizeMemoSyncTags = (value: unknown) =>+ Array.isArray(value) ? value.filter((tag): tag is string => typeof tag === "string") : [];++export const memoUpdatePayloadMatchesRemote = (+ payload: {+ title?: unknown;+ tags?: unknown;+ contentMarkdown?: unknown;+ contentJson?: unknown;+ },+ remote: {+ title?: string | null;+ tags?: readonly string[];+ contentMarkdown?: string;+ contentJson?: unknown;+ },+) => {+ if (normalizeMemoSyncTitle(payload.title) !== normalizeMemoSyncTitle(remote.title)) {+ return false;+ }+ const payloadTags = normalizeMemoSyncTags(payload.tags);+ const remoteTags = normalizeMemoSyncTags(remote.tags);+ if (payloadTags.length !== remoteTags.length || payloadTags.some((tag, index) => tag !== remoteTags[index])) {+ return false;+ }+ const payloadMarkdown = typeof payload.contentMarkdown === "string" ? payload.contentMarkdown : "";+ const remoteMarkdown = remote.contentMarkdown ?? "";+ if (payloadMarkdown !== "" || remoteMarkdown !== "") {+ return payloadMarkdown === remoteMarkdown;+ }+ return JSON.stringify(payload.contentJson ?? null) === JSON.stringify(remote.contentJson ?? null);+};++export const resolveSameDeviceMemoSyncRecovery = (input: {+ current: MemoSyncBase;+ expected: MemoSyncExpectedBase;+ payloadMatchesRemote: boolean;+ remoteProducedLocally: boolean;+}): SameDeviceMemoSyncRecovery => {+ if (input.payloadMatchesRemote) {+ return "ack";+ }+ if (input.expected.expectedRevision < input.current.revision && input.remoteProducedLocally) {+ return "rebase";+ }+ return "conflict";+};+export const createEmptySyncQueueSummary = (): SyncQueueSummary => ({total: 0,pending: 0,