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(web): prevent stale remote detail from clobbering editor state
tianma-ifb20d43e642ef
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex d33957e7..edfdb225 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -111,6 +111,7 @@ import { compressImageForUpload } from "@/lib/image-compression";import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";import { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate, shouldQueueMemoSaveError } from "@/lib/sync-queue";import { isLocalMemoId } from "@/lib/local-mirror";+import { shouldAcceptRemoteMemoDetail } from "@/lib/memo-detail-freshness";import type { EdgeEverRepository } from "@/lib/repository";import {EDITOR_LOCAL_SAVE_DELAY_MS,@@ -956,6 +957,8 @@ const RichEditorPane = ({const noteReplaceInputRef = useRef<HTMLInputElement | null>(null);const hydratingRef = useRef(false);const hydratedMemoIdRef = useRef<string | null>(null);+ /** Last content source applied to the editor — used to skip redundant setContent. */+ const appliedEditorSourceKeyRef = useRef<string | null>(null);const hasUnsavedChangesRef = useRef(false);const editingMemoIdRef = useRef<string | null>(memo?.id ?? null);const imageCompressionEnabledRef = useRef(imageCompressionEnabled);@@ -1821,6 +1824,7 @@ const RichEditorPane = ({memoRef.current = null;editSessionRef.current = null;hydratedMemoIdRef.current = null;+ appliedEditorSourceKeyRef.current = null;setHydratedEditorMemoId(null);editingMemoIdRef.current = null;hasUnsavedChangesRef.current = false;@@ -1838,25 +1842,72 @@ const RichEditorPane = ({return;}+ const previousMemo = memoRef.current;const sameMemo = editingMemoIdRef.current === memo.id;- memoRef.current = memo;if (!sameMemo) {hydratedMemoIdRef.current = null;+ appliedEditorSourceKeyRef.current = null;setHydratedEditorMemoId(null);}+ // While the user still has unsaved keystrokes, ignore memo prop churn entirely+ // unless the incoming snapshot is strictly fresher (e.g. another device).if (sameMemo && hasUnsavedChangesRef.current && !memo.isDeleted) {+ if (previousMemo && shouldAcceptRemoteMemoDetail(previousMemo, memo)) {+ memoRef.current = memo;+ }+ return;+ }++ // After local autosave clears dirty, reject stale remote props that would+ // call setContent and roll the document back (cursor jump / deleted text returns).+ if (+ sameMemo &&+ !memo.isDeleted &&+ previousMemo &&+ previousMemo.id === memo.id &&+ !shouldAcceptRemoteMemoDetail(previousMemo, memo)+ ) {return;}+ // Same memo already on screen and the query only re-emitted an equivalent+ // snapshot (common when switching away/back triggers a detail refetch).+ // Refresh the edit session quietly — never touch document or selection.+ if (+ sameMemo &&+ !memo.isDeleted &&+ hydratedMemoIdRef.current === memo.id &&+ previousMemo &&+ previousMemo.id === memo.id &&+ previousMemo.revision === memo.revision &&+ previousMemo.updatedAt === memo.updatedAt &&+ previousMemo.contentHash === memo.contentHash &&+ previousMemo.title === memo.title &&+ previousMemo.tags.length === memo.tags.length &&+ previousMemo.tags.every((tag, index) => tag === memo.tags[index])+ ) {+ memoRef.current = memo;+ if (!requiresLocalEditSession(memo)) {+ void api.createMemoEditSession(memo.id).then((response) => {+ if (cancelled || editingMemoIdRef.current !== memo.id) return;+ editSessionRef.current = response.editSession;+ }).catch(() => {+ // Keep the previous session; the next save can open a new one.+ });+ }+ return;+ }++ memoRef.current = memo;+void (async () => {- let [draft, queuedUpdate, editSessionResponse] = memo.isDeleted- ? [null, null, null]+ let [draft, queuedUpdate] = memo.isDeleted+ ? [null, null]: await Promise.all([localDb.drafts.get(memo.id),localDb.syncQueue.get(getMemoUpdateQueueId(memo.id)),- requiresLocalEditSession(memo) ? Promise.resolve(null) : api.createMemoEditSession(memo.id),]);if (cancelled) {@@ -1875,13 +1926,74 @@ const RichEditorPane = ({const draftUpdatedAt = draft ? Date.parse(draft.updatedAt) : 0;const remoteUpdatedAt = Date.parse(memo.updatedAt);const useDraft = Boolean(draft && (queuedUpdate || draftUpdatedAt >= remoteUpdatedAt));- const nextTitle = useDraft && draft ? draft.title : getEditableMemoTitle(memo.title);- const nextTagsText = useDraft && draft ? draft.tagsText : memo.tags.join(", ");+ const queuedPayload =+ queuedUpdate && queuedUpdate.kind === "memo.update"+ ? (queuedUpdate.payload as MemoUpdateSyncPayload)+ : null;+ // Prefer an unpushed local queue payload over a stale memo prop when the+ // draft was already cleared by a successful local save.+ const useQueuedPayload = Boolean(queuedPayload && !useDraft && !isMemoUpdateAlreadyApplied(memo, queuedUpdate!));++ const nextTitle = useDraft && draft+ ? draft.title+ : useQueuedPayload && queuedPayload+ ? getEditableMemoTitle(queuedPayload.title)+ : getEditableMemoTitle(memo.title);+ const nextTagsText = useDraft && draft+ ? draft.tagsText+ : useQueuedPayload && queuedPayload+ ? queuedPayload.tags.join(", ")+ : memo.tags.join(", ");const nextContent = useDraft && draft? draft.contentJson- : resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown);+ : useQueuedPayload && queuedPayload+ ? queuedPayload.contentJson+ : resolveMemoContentDoc(memo.contentJson, memo.contentMarkdown);const nextMarkdown = docToMarkdown(nextContent);const nextHasUnsavedChanges = Boolean(useDraft && !queuedUpdate);+ const sourceKey = useDraft && draft+ ? `draft:${memo.id}:${draft.updatedAt}:${nextTitle}:${nextTagsText}:${nextMarkdown}`+ : useQueuedPayload && queuedUpdate+ ? `queue:${memo.id}:${queuedUpdate.updatedAt}:${nextTitle}:${nextTagsText}:${nextMarkdown}`+ : `memo:${memo.id}:${memo.revision}:${memo.updatedAt}:${memo.contentHash}:${nextTitle}:${nextTagsText}:${nextMarkdown}`;++ const alreadyHydratedSameMemo = sameMemo && hydratedMemoIdRef.current === memo.id;+ const editorMarkdownMatches = Boolean(+ alreadyHydratedSameMemo &&+ isEditorReady(currentEditor) &&+ docToMarkdown(currentEditor.getJSON() as TiptapDoc) === nextMarkdown &&+ title === nextTitle &&+ tagsText === nextTagsText+ );+ const sourceAlreadyApplied = alreadyHydratedSameMemo && appliedEditorSourceKeyRef.current === sourceKey;++ // Skip a full document replace when content already matches — setContent+ // always resets the selection and feels like a line jump / jump-to-end.+ if (sourceAlreadyApplied || editorMarkdownMatches) {+ editingMemoIdRef.current = memo.id;+ appliedEditorSourceKeyRef.current = sourceKey;+ if (queuedUpdate) {+ setSaveState(syncStatusToSaveState(queuedUpdate.status));+ }+ if (requiresLocalEditSession(memo)) {+ editSessionRef.current = editSessionRef.current ?? createLocalEditSession(memo);+ } else {+ void api.createMemoEditSession(memo.id).then((response) => {+ if (cancelled || editingMemoIdRef.current !== memo.id) return;+ editSessionRef.current = response.editSession;+ }).catch(() => {+ // Keep any previous session for this memo.+ });+ }+ return;+ }++ const previousSelection = alreadyHydratedSameMemo && isEditorReady(currentEditor)+ ? {+ from: currentEditor.state.selection.from,+ to: currentEditor.state.selection.to,+ }+ : null;hydratingRef.current = true;editingMemoIdRef.current = memo.id;@@ -1901,12 +2013,34 @@ const RichEditorPane = ({console.error("Failed to set TipTap contentJson, falling back to markdownToDoc:", err);currentEditor.commands.setContent(markdownToDoc(nextMarkdown));}++ // Re-applying content on an already-open note (e.g. draft vs server)+ // must not yank the caret to the document end.+ if (previousSelection) {+ const maxPos = currentEditor.state.doc.content.size;+ const from = Math.max(1, Math.min(previousSelection.from, maxPos));+ const to = Math.max(1, Math.min(previousSelection.to, maxPos));+ currentEditor.commands.setTextSelection({ from, to });+ }}+ appliedEditorSourceKeyRef.current = sourceKey;hydratedMemoIdRef.current = memo.id;- editSessionRef.current = editSessionResponse?.editSession ?? (requiresLocalEditSession(memo) ? createLocalEditSession(memo) : null);setHydratedEditorMemoId(memo.id);+ if (requiresLocalEditSession(memo)) {+ editSessionRef.current = createLocalEditSession(memo);+ } else {+ // Do not block first paint / caret on the edit-session network round-trip.+ void api.createMemoEditSession(memo.id).then((response) => {+ if (cancelled || editingMemoIdRef.current !== memo.id) return;+ editSessionRef.current = response.editSession;+ }).catch(() => {+ if (cancelled || editingMemoIdRef.current !== memo.id) return;+ editSessionRef.current = createLocalEditSession(memo);+ });+ }+window.setTimeout(() => {hydratingRef.current = false;}, 0);@@ -1915,6 +2049,9 @@ const RichEditorPane = ({return () => {cancelled = true;};+ // title/tagsText are read only for same-content skip detection; re-running on+ // every keystroke would re-hydrate the editor while the user is typing.+ // eslint-disable-next-line react-hooks/exhaustive-deps -- intentional}, [isTrashView, memo, editor]);useEffect(() => {diff --git a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx b/apps/web/src/components/MobileStandaloneTiptapEditor.tsxindex c04c2d30..55840606 100644--- a/apps/web/src/components/MobileStandaloneTiptapEditor.tsx+++ b/apps/web/src/components/MobileStandaloneTiptapEditor.tsx@@ -18,7 +18,7 @@ import {import { EDITOR_LOCAL_SAVE_DELAY_MS, getEditableMemoTitle, getNotebookMoveOptions } from "@/lib/app-helpers";import { defaultLocale, normalizeLocale } from "@/i18n/locales";import { compressImageForUpload } from "@/lib/image-compression";-import { localDb, type LocalDraft } from "@/lib/local-db";+import { localDb, type LocalDraft, type MemoUpdateSyncPayload } from "@/lib/local-db";import {getStandaloneMobileEditorReturnPath,markStandaloneMobileEditorReturning,@@ -715,6 +715,13 @@ export const MobileStandaloneTiptapEditor = ({queuedUpdate = undefined;}const useDraft = Boolean(draft && (queuedUpdate || Date.parse(draft.updatedAt || "") >= Date.parse(data.memo.updatedAt || "")));+ const queuedPayload =+ queuedUpdate && queuedUpdate.kind === "memo.update"+ ? (queuedUpdate.payload as MemoUpdateSyncPayload)+ : null;+ const useQueuedPayload = Boolean(+ queuedPayload && !useDraft && queuedUpdate && !isMemoUpdateAlreadyApplied(data.memo, queuedUpdate),+ );setMemo(data.memo);@@ -729,6 +736,23 @@ export const MobileStandaloneTiptapEditor = ({setSaveStateStable("local-draft");scheduleMetadataSave();focusEditorAfterLoad();+ } else if (useQueuedPayload && queuedPayload) {+ const queuedTitle = getEditableMemoTitle(queuedPayload.title);+ const queuedTagsText = queuedPayload.tags.join(", ");+ setTitle(queuedTitle);+ titleRef.current = queuedTitle;+ setTagsText(queuedTagsText);+ tagsTextRef.current = queuedTagsText;+ contentJsonRef.current = queuedPayload.contentJson || emptyDoc();+ editor.commands.setContent(contentJsonRef.current, { emitUpdate: false });+ lastSavedSnapshotRef.current = JSON.stringify({+ title: queuedTitle,+ tagsText: queuedTagsText,+ contentJson: contentJsonRef.current,+ });+ dirtyRef.current = false;+ setSaveStateStable("local-draft");+ focusEditorAfterLoad();} else {setTitle(nextTitle);titleRef.current = nextTitle;diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsxindex 04ee2b36..70d7672c 100644--- a/apps/web/src/components/WorkspaceApp.tsx+++ b/apps/web/src/components/WorkspaceApp.tsx@@ -86,6 +86,7 @@ import {} from "@/lib/app-helpers";import { useBrowserBackLayer } from "@/lib/app-hooks";import { updateMemoSummaryInLists, type MemoListQueryData } from "@/lib/memo-list-cache";+import { shouldAcceptRemoteMemoDetail } from "@/lib/memo-detail-freshness";import { emptySyncQueueSummary, type SyncQueueSummary } from "@/lib/sync-queue";import { notifyMemoIdRemapped } from "@/lib/sync-events";import {@@ -1482,9 +1483,21 @@ export const WorkspaceApp = ({const memo = (event as CustomEvent<MemoDetail>).detail;if (!memo?.id) return;- queryClient.setQueryData(memoDetailQueryKey(memo.id, "notebook"), { memo });- queryClient.setQueryData(memoDetailQueryKey(memo.id, "trash"), { memo });- updateMemoSummaryInLists(queryClient, memoToSummary(memo));+ // Repository already filters stale remotes; still refuse to regress the+ // in-memory query cache if a newer local snapshot is already present.+ let accepted = false;+ for (const view of ["notebook", "trash"] as const) {+ const key = memoDetailQueryKey(memo.id, view);+ const current = queryClient.getQueryData<{ memo: MemoDetail }>(key)?.memo;+ if (current && !shouldAcceptRemoteMemoDetail(current, memo)) {+ continue;+ }+ queryClient.setQueryData(key, { memo });+ accepted = true;+ }+ if (accepted) {+ updateMemoSummaryInLists(queryClient, memoToSummary(memo));+ }};window.addEventListener("edgeever:memo-detail-refreshed", handleMemoDetailRefreshed);diff --git a/apps/web/src/lib/memo-detail-freshness.test.mjs b/apps/web/src/lib/memo-detail-freshness.test.mjsnew file mode 100644index 00000000..423c5f7c--- /dev/null+++ b/apps/web/src/lib/memo-detail-freshness.test.mjs@@ -0,0 +1,67 @@+import { describe, expect, test } from "bun:test";+import {+ isActiveLocalMemoUpdateStatus,+ shouldAcceptRemoteMemoDetail,+} from "./memo-detail-freshness.ts";++describe("memo detail freshness", () => {+ test("treats pending/syncing/error queue statuses as active local updates", () => {+ expect(isActiveLocalMemoUpdateStatus("pending")).toBe(true);+ expect(isActiveLocalMemoUpdateStatus("syncing")).toBe(true);+ expect(isActiveLocalMemoUpdateStatus("error")).toBe(true);+ expect(isActiveLocalMemoUpdateStatus("conflict")).toBe(false);+ expect(isActiveLocalMemoUpdateStatus("idle")).toBe(false);+ expect(isActiveLocalMemoUpdateStatus(undefined)).toBe(false);+ });++ test("accepts remote when there is no local snapshot", () => {+ expect(+ shouldAcceptRemoteMemoDetail(null, {+ revision: 1,+ updatedAt: "2026-01-01T00:00:00.000Z",+ }),+ ).toBe(true);+ });++ test("rejects remote while a local memo.update is still queued", () => {+ expect(+ shouldAcceptRemoteMemoDetail(+ { revision: 3, updatedAt: "2026-01-02T00:00:00.000Z" },+ { revision: 4, updatedAt: "2026-01-03T00:00:00.000Z" },+ { hasPendingLocalUpdate: true },+ ),+ ).toBe(false);+ });++ test("accepts a strictly higher remote revision without pending local updates", () => {+ expect(+ shouldAcceptRemoteMemoDetail(+ { revision: 3, updatedAt: "2026-01-02T00:00:00.000Z" },+ { revision: 4, updatedAt: "2026-01-01T00:00:00.000Z" },+ ),+ ).toBe(true);+ });++ test("rejects a lower remote revision", () => {+ expect(+ shouldAcceptRemoteMemoDetail(+ { revision: 5, updatedAt: "2026-01-02T00:00:00.000Z" },+ { revision: 4, updatedAt: "2026-01-03T00:00:00.000Z" },+ ),+ ).toBe(false);+ });++ test("at the same revision prefers the newer updatedAt (local autosave case)", () => {+ const local = { revision: 2, updatedAt: "2026-01-02T12:00:01.000Z" };+ const staleRemote = { revision: 2, updatedAt: "2026-01-02T12:00:00.000Z" };+ const fresherRemote = { revision: 2, updatedAt: "2026-01-02T12:00:02.000Z" };++ expect(shouldAcceptRemoteMemoDetail(local, staleRemote)).toBe(false);+ expect(shouldAcceptRemoteMemoDetail(local, fresherRemote)).toBe(true);+ });++ test("accepts remote when revision and updatedAt match", () => {+ const snapshot = { revision: 2, updatedAt: "2026-01-02T12:00:00.000Z" };+ expect(shouldAcceptRemoteMemoDetail(snapshot, snapshot)).toBe(true);+ });+});diff --git a/apps/web/src/lib/memo-detail-freshness.ts b/apps/web/src/lib/memo-detail-freshness.tsnew file mode 100644index 00000000..9aa6c29c--- /dev/null+++ b/apps/web/src/lib/memo-detail-freshness.ts@@ -0,0 +1,39 @@+import type { MemoDetail } from "@edgeever/shared";+import type { SyncQueueStatus } from "@/lib/local-db";++export type MemoDetailFreshnessFields = Pick<MemoDetail, "revision" | "updatedAt">;++/** Queue statuses that mean local edits must not be overwritten by a stale remote detail. */+const ACTIVE_LOCAL_UPDATE_STATUSES = new Set<SyncQueueStatus>(["pending", "syncing", "error"]);++export const isActiveLocalMemoUpdateStatus = (status: string | null | undefined): boolean =>+ Boolean(status && ACTIVE_LOCAL_UPDATE_STATUSES.has(status as SyncQueueStatus));++/**+ * Decide whether a remote memo detail should replace the local/editor snapshot.+ *+ * Local autosave updates content and `updatedAt` without bumping `revision` until+ * the server accepts the change. While a memo.update is still queued, or while the+ * local row is newer at the same revision, the remote snapshot is treated as stale.+ */+export const shouldAcceptRemoteMemoDetail = (+ local: MemoDetailFreshnessFields | null | undefined,+ remote: MemoDetailFreshnessFields,+ options: { hasPendingLocalUpdate?: boolean } = {},+): boolean => {+ if (!local) return true;+ if (options.hasPendingLocalUpdate) return false;++ if (remote.revision > local.revision) return true;+ if (remote.revision < local.revision) return false;++ const localUpdatedAt = Date.parse(local.updatedAt);+ const remoteUpdatedAt = Date.parse(remote.updatedAt);+ if (Number.isFinite(localUpdatedAt) && Number.isFinite(remoteUpdatedAt)) {+ if (remoteUpdatedAt > localUpdatedAt) return true;+ if (remoteUpdatedAt < localUpdatedAt) return false;+ }++ // Same revision and equal/unknown timestamps: allow remote (e.g. external metadata).+ return true;+};diff --git a/apps/web/src/lib/repository.test.mjs b/apps/web/src/lib/repository.test.mjsindex f719b170..8f7c8f3d 100644--- a/apps/web/src/lib/repository.test.mjs+++ b/apps/web/src/lib/repository.test.mjs@@ -9,6 +9,17 @@ const { api } = await import("./api.ts");const { createWebRepository } = await import("./repository.ts");const { createLocalMemo } = await import("./local-mirror.ts");+const installTestWindow = ({ hostname = "localhost" } = {}) => {+ const previousWindow = globalThis.window;+ const eventTarget = new EventTarget();+ globalThis.window = Object.assign(eventTarget, {+ location: { hostname, href: `http://${hostname}/` },+ });+ return () => {+ globalThis.window = previousWindow;+ };+};+afterEach(async () => {await localDb.transaction("rw", [localDb.templates, localDb.notebooks, localDb.memos, localDb.resources, localDb.revisions, localDb.syncMeta, localDb.syncQueue], async () => {await Promise.all([@@ -25,15 +36,13 @@ afterEach(async () => {describe("web repository offline boundaries", () => {test("saves memo edits locally while deferring remote synchronization", async () => {- const previousWindow = globalThis.window;- const eventTarget = new EventTarget();- globalThis.window = eventTarget;+ const restoreWindow = installTestWindow();let immediateEvents = 0;let deferredEvents = 0;- eventTarget.addEventListener("edgeever:sync-queue-changed", () => {+ window.addEventListener("edgeever:sync-queue-changed", () => {immediateEvents += 1;});- eventTarget.addEventListener("edgeever:sync-queue-deferred", () => {+ window.addEventListener("edgeever:sync-queue-deferred", () => {deferredEvents += 1;});@@ -60,7 +69,7 @@ describe("web repository offline boundaries", () => {expect(deferredEvents).toBe(1);expect(immediateEvents).toBe(0);} finally {- globalThis.window = previousWindow;+ restoreWindow();}});@@ -110,6 +119,7 @@ describe("web repository offline boundaries", () => {test("returns cached detail immediately and refreshes it in the background", async () => {const previousOnline = globalThis.navigator?.onLine;if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: true });+ const restoreWindow = installTestWindow();const scope = "https://demo.edgeever.org|user-1";const localMemo = {id: "memo-1",@@ -129,6 +139,8 @@ describe("web repository offline boundaries", () => {contentText: "cached",contentHash: "cached",sourceMemoIds: [],+ mergeSourceCount: 0,+ mergedIntoMemoId: null,};const remoteMemo = { ...localMemo, title: "Remote title", contentMarkdown: "remote", contentText: "remote", revision: 2 };await localDb.memos.put({ ...localMemo, scope });@@ -141,10 +153,154 @@ describe("web repository offline boundaries", () => {try {const repository = createWebRepository(scope);expect((await repository.getMemo("memo-1")).memo.title).toBe("Cached title");- await new Promise((resolve) => setTimeout(resolve, 30));+ await new Promise((resolve) => setTimeout(resolve, 50));expect((await localDb.memos.get([scope, "memo-1"])).title).toBe("Remote title");} finally {api.getMemo = originalGetMemo;+ restoreWindow();+ if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: previousOnline });+ }+ });++ test("does not overwrite a newer local autosave with a stale remote detail", async () => {+ const previousOnline = globalThis.navigator?.onLine;+ if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: true });+ const restoreWindow = installTestWindow();+ let refreshEvents = 0;+ window.addEventListener("edgeever:memo-detail-refreshed", () => {+ refreshEvents += 1;+ });++ const scope = "https://demo.edgeever.org|user-1";+ const localMemo = {+ id: "memo-stale-remote",+ notebookId: "nb-1",+ title: "Local autosave",+ excerpt: "local",+ tags: [],+ isPinned: false,+ isArchived: false,+ isDeleted: false,+ revision: 3,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-02T12:00:01.000Z",+ deletedAt: null,+ contentJson: { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "local" }] }] },+ contentMarkdown: "local",+ contentText: "local",+ contentHash: "local-hash",+ sourceMemoIds: [],+ mergeSourceCount: 0,+ mergedIntoMemoId: null,+ };+ // Same revision, older updatedAt — the classic "server has not received the autosave yet" case.+ const remoteMemo = {+ ...localMemo,+ title: "Stale remote",+ excerpt: "remote",+ updatedAt: "2026-01-02T12:00:00.000Z",+ contentMarkdown: "remote",+ contentText: "remote",+ contentHash: "remote-hash",+ };+ await localDb.memos.put({ ...localMemo, scope });+ await localDb.syncQueue.put({+ id: `memo.update:${localMemo.id}`,+ kind: "memo.update",+ scope,+ memoId: localMemo.id,+ status: "pending",+ payload: {+ memoId: localMemo.id,+ expectedRevision: 3,+ expectedContentHash: "local-hash",+ editSessionId: "edit-1",+ title: "Local autosave",+ contentJson: localMemo.contentJson,+ tags: [],+ },+ attemptCount: 0,+ lastError: null,+ nextAttemptAt: null,+ claimId: null,+ createdAt: localMemo.updatedAt,+ updatedAt: localMemo.updatedAt,+ });++ const originalGetMemo = api.getMemo;+ api.getMemo = async () => {+ await new Promise((resolve) => setTimeout(resolve, 20));+ return { memo: remoteMemo };+ };++ try {+ const repository = createWebRepository(scope);+ expect((await repository.getMemo(localMemo.id)).memo.title).toBe("Local autosave");+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect((await localDb.memos.get([scope, localMemo.id])).title).toBe("Local autosave");+ expect(refreshEvents).toBe(0);+ } finally {+ api.getMemo = originalGetMemo;+ restoreWindow();+ if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: previousOnline });+ }+ });++ test("does not prefer a stale remote that wins the local/remote race", async () => {+ const previousOnline = globalThis.navigator?.onLine;+ if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: true });+ const restoreWindow = installTestWindow();++ const scope = "https://demo.edgeever.org|user-1";+ const localMemo = {+ id: "memo-race",+ notebookId: "nb-1",+ title: "Local wins",+ excerpt: "local",+ tags: [],+ isPinned: false,+ isArchived: false,+ isDeleted: false,+ revision: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-02T12:00:01.000Z",+ deletedAt: null,+ contentJson: { type: "doc", content: [] },+ contentMarkdown: "local",+ contentText: "local",+ contentHash: "local",+ sourceMemoIds: [],+ mergeSourceCount: 0,+ mergedIntoMemoId: null,+ };+ const remoteMemo = {+ ...localMemo,+ title: "Stale remote race",+ updatedAt: "2026-01-02T12:00:00.000Z",+ contentMarkdown: "remote",+ contentText: "remote",+ };+ await localDb.memos.put({ ...localMemo, scope });++ const originalGetMemo = api.getMemo;+ const originalLocalGet = localDb.memos.get;+ api.getMemo = async () => ({ memo: remoteMemo });+ // Delay local read so remote wins Promise.race.+ localDb.memos.get = async (...args) => {+ await new Promise((resolve) => setTimeout(resolve, 30));+ return originalLocalGet.apply(localDb.memos, args);+ };++ try {+ const repository = createWebRepository(scope);+ const result = await repository.getMemo(localMemo.id);+ expect(result.memo.title).toBe("Local wins");+ localDb.memos.get = originalLocalGet;+ expect((await localDb.memos.get([scope, localMemo.id])).title).toBe("Local wins");+ } finally {+ api.getMemo = originalGetMemo;+ localDb.memos.get = originalLocalGet;+ restoreWindow();if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: previousOnline });}});@@ -152,6 +308,8 @@ describe("web repository offline boundaries", () => {test("returns empty initialized collections without cloud fallbacks", async () => {const previousOnline = globalThis.navigator?.onLine;if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: false });+ // Non-loopback host so navigator.onLine=false is treated as offline.+ const restoreWindow = installTestWindow({ hostname: "demo.edgeever.org" });const scope = "https://demo.edgeever.org|user-1";await localDb.syncMeta.put({ scope, key: "identity", value: "sync-1", updatedAt: new Date().toISOString() });const original = {@@ -176,6 +334,7 @@ describe("web repository offline boundaries", () => {api.listTemplates = original.listTemplates;api.listResources = original.listResources;api.listNotebooks = original.listNotebooks;+ restoreWindow();if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: previousOnline });}});diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.tsindex 885d512f..63caec85 100644--- a/apps/web/src/lib/repository.ts+++ b/apps/web/src/lib/repository.ts@@ -39,11 +39,12 @@ import {type LocalMemoListParams,type LocalMemoListResponse,} from "@/lib/local-mirror";-import { queueLocalAction, queueMemoCreate, queueMemoDelete, queueMemoRestore, queueMemoUpdate } from "@/lib/sync-queue";-import type { MemoUpdateSyncPayload } from "@/lib/local-db";+import { getMemoUpdateQueueId, queueLocalAction, queueMemoCreate, queueMemoDelete, queueMemoRestore, queueMemoUpdate } from "@/lib/sync-queue";+import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";import { createDesktopRepository } from "@/lib/desktop-repository";import { isBrowserOffline } from "@/lib/network-status";import { notifySyncQueueDeferred } from "@/lib/sync-events";+import { isActiveLocalMemoUpdateStatus, shouldAcceptRemoteMemoDetail } from "@/lib/memo-detail-freshness";export type EdgeEverRepository = {listNotebooks(): Promise<{ notebooks: Notebook[] }>;@@ -95,6 +96,40 @@ const cacheMemoWithoutBlocking = (scope: string, memo: MemoDetail) => {});};+const hasActiveLocalMemoUpdate = async (memoId: string) => {+ const item = await localDb.syncQueue.get(getMemoUpdateQueueId(memoId));+ return isActiveLocalMemoUpdateStatus(item?.status);+};++/**+ * Persist and surface a remote detail only when it is strictly fresher than the+ * local mirror (and no memo.update is still waiting to push). Returns whether+ * the remote snapshot was accepted.+ */+const acceptRemoteMemoDetail = async (+ scope: string,+ remote: MemoDetail,+ local: MemoDetail | null | undefined,+ options: { emitRefreshEvent?: boolean } = {},+) => {+ // Re-read local + queue at decision time: a save may land during the network RTT.+ // Use the non-blocking local read so a stuck IndexedDB never freezes getMemo.+ const [latestLocal, pendingLocalUpdate] = await Promise.all([+ getLocalMemoWithoutBlocking(scope, remote.id),+ hasActiveLocalMemoUpdate(remote.id),+ ]);+ const baseline = latestLocal ?? local ?? null;+ if (!shouldAcceptRemoteMemoDetail(baseline, remote, { hasPendingLocalUpdate: pendingLocalUpdate })) {+ return false;+ }++ cacheMemoWithoutBlocking(scope, remote);+ if (options.emitRefreshEvent) {+ window.dispatchEvent(new CustomEvent("edgeever:memo-detail-refreshed", { detail: remote }));+ }+ return true;+};+export const createWebRepository = (scope: string): EdgeEverRepository => {const isOffline = isBrowserOffline;@@ -332,6 +367,16 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {]);if (firstResult.source === "remote") {+ const local = await localPromise;+ const usableLocal = local && (includeDeleted || !local.isDeleted) ? local : null;+ const accepted = await acceptRemoteMemoDetail(scope, firstResult.remote.memo, usableLocal);+ if (accepted) {+ return firstResult.remote;+ }+ if (usableLocal) {+ return { memo: usableLocal };+ }+ // No usable local snapshot — surface remote even if queue checks rejected it.cacheMemoWithoutBlocking(scope, firstResult.remote.memo);return firstResult.remote;}@@ -342,9 +387,8 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {if (usableLocal) {if (firstResult.source === "local") {void remotePromise- .then((remote) => {- cacheMemoWithoutBlocking(scope, remote.memo);- window.dispatchEvent(new CustomEvent("edgeever:memo-detail-refreshed", { detail: remote.memo }));+ .then(async (remote) => {+ await acceptRemoteMemoDetail(scope, remote.memo, usableLocal, { emitRefreshEvent: true });}).catch(() => {// The local detail remains usable when the background refresh fails.