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): recover stalled local note saves
tianma-if630bb98e3f64
diff --git a/apps/web/src/components/EditorPane.tsx b/apps/web/src/components/EditorPane.tsxindex 61941200..05baeecc 100644--- a/apps/web/src/components/EditorPane.tsx+++ b/apps/web/src/components/EditorPane.tsx@@ -144,7 +144,9 @@ import { DEFAULT_IMAGE_WIDTH_PERCENT } from "@edgeever/shared/image-display";import { createEdgeEverMathematics } from "@edgeever/shared/mathematics";import { codeBlockLowlight, EdgeEverCodeBlock } from "@/lib/code-block";import { compressImageForUpload } from "@/lib/image-compression";-import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";+import { LOCAL_DATABASE_INTERRUPTED_EVENT, localDb, selectNewestLocalDraft, type MemoUpdateSyncPayload } from "@/lib/local-db";+import { LocalDatabaseUnavailableError } from "@/lib/local-database-recovery";+import { persistEmergencyDraft, readEmergencyDraft, removeEmergencyDraft } from "@/lib/emergency-draft";import { getMemoUpdateQueueId, isMemoUpdateAlreadyApplied, queueMemoUpdate, shouldQueueMemoSaveError } from "@/lib/sync-queue";import {formatLocalDraftClipboardText,@@ -792,7 +794,12 @@ const RichEditorPane = ({} = useEditorSaveStatus();const [conflictActionPending, setConflictActionPending] = useState<"adopt" | "copy" | null>(null);const [conflictActionMessage, setConflictActionMessage] = useState<string | null>(null);+ const [storageSaveError, setStorageSaveError] = useState(false);const [hydratedEditorMemoId, setHydratedEditorMemoId] = useState<string | null>(null);++ useEffect(() => {+ setStorageSaveError(false);+ }, [memo?.id]);const [editorStateVersion, setEditorStateVersion] = useState(0);const [editorContentVersion, setEditorContentVersion] = useState(0);const [imageUploadState, setImageUploadState] = useState<"idle" | "compressing" | "uploading" | "error">("idle");@@ -2507,6 +2514,30 @@ const RichEditorPane = ({});}, [getCurrentContentJson, tagsText, title]);+ useEffect(() => {+ const handleLocalDatabaseInterrupted = () => {+ const currentMemo = memoRef.current;+ const contentJson = getCurrentContentJson();+ if (currentMemo && contentJson && !currentMemo.isDeleted) {+ persistEmergencyDraft({+ memoId: currentMemo.id,+ expectedRevision: currentMemo.revision,+ title,+ tagsText,+ contentJson,+ updatedAt: new Date().toISOString(),+ });+ setHasUnsavedChanges(true);+ }+ setStorageSaveError(true);+ setSaveConflictInfo(null);+ setSaveState("error");+ };++ window.addEventListener(LOCAL_DATABASE_INTERRUPTED_EVENT, handleLocalDatabaseInterrupted);+ return () => window.removeEventListener(LOCAL_DATABASE_INTERRUPTED_EVENT, handleLocalDatabaseInterrupted);+ }, [getCurrentContentJson, setHasUnsavedChanges, setSaveConflictInfo, setSaveState, tagsText, title]);+useEffect(() => {const currentEditor = editorRef.current;let cancelled = false;@@ -2526,6 +2557,7 @@ const RichEditorPane = ({setIsMarkdownMode(false);setMobilePlainTextElementValue(mobileTextAreaRef.current, "");setSaveState("idle");+ setStorageSaveError(false);if (isEditorReady(currentEditor)) {currentEditor.commands.clearContent();}@@ -2593,12 +2625,13 @@ const RichEditorPane = ({memoRef.current = memo;void (async () => {- let [draft, queuedUpdate] = memo.isDeleted+ let [indexedDbDraft, queuedUpdate] = memo.isDeleted? [null, null]: await Promise.all([localDb.drafts.get(memo.id),localDb.syncQueue.get(getMemoUpdateQueueId(memo.id)),]);+ let draft = selectNewestLocalDraft(indexedDbDraft, readEmergencyDraft(memo.id));if (cancelled) {return;@@ -2609,6 +2642,7 @@ const RichEditorPane = ({localDb.syncQueue.delete(queuedUpdate.id),localDb.drafts.delete(memo.id),]);+ removeEmergencyDraft(memo.id);draft = null;queuedUpdate = undefined;}@@ -2616,6 +2650,7 @@ const RichEditorPane = ({const resolvedDraft = resolveEditorDraftState({ memo, draft, queuedUpdate });if (draft && !queuedUpdate && resolvedDraft.source === "memo") {await localDb.drafts.delete(memo.id);+ removeEmergencyDraft(memo.id);}const {title: nextTitle,@@ -3227,11 +3262,24 @@ const RichEditorPane = ({contentMarkdown: useMarkdownSourceEditor ? markdownSource : undefined,tags: parseTagsText(tagsText),};+ persistEmergencyDraft({+ memoId: currentMemo.id,+ expectedRevision: currentMemo.revision,+ title,+ tagsText,+ contentJson,+ updatedAt: new Date().toISOString(),+ });const { memo: localMemo } = await repository.updateMemo(currentMemo, payload);return { memo: localMemo, snapshot, queued: true };},- onMutate: () => setSaveState("saving"),+ onMutate: () => {+ setStorageSaveError(false);+ setSaveState("saving");+ },onSuccess: async ({ memo: savedMemo, snapshot, queued }) => {+ setStorageSaveError(false);+ removeEmergencyDraft(savedMemo.id);memoRef.current = savedMemo;const currentEditSession = editSessionRef.current;if (currentEditSession) {@@ -3260,7 +3308,7 @@ const RichEditorPane = ({if (currentSnapshot() === snapshot) {setMobilePlainText(docToMarkdown(savedMemo.contentJson));setHasUnsavedChanges(false);- await localDb.drafts.delete(savedMemo.id);+ void localDb.drafts.delete(savedMemo.id).catch(() => undefined);setSaveConflictInfo(null);setSaveState(queued ? "queued" : "saved");if (!queued) {@@ -3275,6 +3323,13 @@ const RichEditorPane = ({setSaveState("idle");},onError: async (error) => {+ if (error instanceof LocalDatabaseUnavailableError) {+ setStorageSaveError(true);+ setSaveConflictInfo(null);+ setSaveState("error");+ return;+ }+ setStorageSaveError(false);const sourceError = error instanceof MemoSaveRequestError ? error.originalError : error;const conflictInfo = getMemoSaveConflictInfo(sourceError);@@ -3293,6 +3348,7 @@ const RichEditorPane = ({contentJson: error.payload.contentJson,updatedAt: new Date().toISOString(),});+ removeEmergencyDraft(error.payload.memoId);setHasUnsavedChanges(false);setSaveConflictInfo(null);@@ -3602,7 +3658,7 @@ const RichEditorPane = ({if (!hasUnsavedChangesRef.current) {setHasUnsavedChanges(true);setSaveState((current) => (current === "conflict" ? current : "idle"));- } else if (saveState === "saved") {+ } else if (saveState === "saved" || saveState === "error") {setSaveState("idle");}@@ -3624,7 +3680,8 @@ const RichEditorPane = ({memoRef.current.isDeleted ||!hasUnsavedChangesRef.current ||saveMutationPending ||- saveState === "conflict"+ saveState === "conflict" ||+ saveState === "error") {return;}@@ -3693,7 +3750,8 @@ const RichEditorPane = ({!editor ||!hasUnsavedChanges ||saveMutationPending ||- saveState === "conflict"+ saveState === "conflict" ||+ saveState === "error") {return;}@@ -4766,6 +4824,42 @@ const RichEditorPane = ({</div></div>) : null}+ {saveState === "error" && storageSaveError ? (+ <div+ className="flex flex-col gap-2 border-t border-rose-100 bg-rose-50 px-3 py-2 text-xs leading-relaxed text-rose-800 sm:px-5"+ role="alert"+ >+ <div className="flex items-start gap-2">+ <CircleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden="true" />+ <span className="min-w-0 flex-1">{t("editor.saveState.storageUnavailable")}</span>+ </div>+ <div className="flex flex-wrap items-center gap-2 pl-5">+ <Button+ size="sm"+ variant="solid"+ className="h-7 bg-rose-700 px-2.5 text-[11px] text-white hover:bg-rose-800"+ disabled={saveMutationPending}+ onClick={() => mutateSave()}+ >+ {t("editor.saveState.storageRetry")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ className="h-7 px-2.5 text-[11px] text-rose-800 hover:bg-rose-100"+ disabled={conflictActionPending !== null}+ onClick={() => void handleCopyLocalDraft()}+ >+ {t("editor.saveState.conflictCopyDraft")}+ </Button>+ {conflictActionMessage ? (+ <span className="text-[11px] font-medium text-rose-700" role="status" aria-live="polite">+ {conflictActionMessage}+ </span>+ ) : null}+ </div>+ </div>+ ) : null}</header><divdiff --git a/apps/web/src/lib/emergency-draft.test.mjs b/apps/web/src/lib/emergency-draft.test.mjsnew file mode 100644index 00000000..9d68f925--- /dev/null+++ b/apps/web/src/lib/emergency-draft.test.mjs@@ -0,0 +1,41 @@+import { describe, expect, test } from "bun:test";+import { persistEmergencyDraft, readEmergencyDraft, removeEmergencyDraft } from "./emergency-draft";++const createStorage = () => {+ const values = new Map();+ return {+ getItem: (key) => values.get(key) ?? null,+ setItem: (key, value) => values.set(key, value),+ removeItem: (key) => values.delete(key),+ };+};++describe("emergency editor drafts", () => {+ test("round-trips and removes a draft independently of IndexedDB", () => {+ const storage = createStorage();+ const draft = {+ memoId: "memo-1",+ expectedRevision: 3,+ title: "Local title",+ tagsText: "draft",+ contentJson: { type: "doc", content: [] },+ updatedAt: "2026-08-29T12:00:00.000Z",+ };++ expect(persistEmergencyDraft(draft, storage)).toBe(true);+ expect(readEmergencyDraft(draft.memoId, storage)).toEqual(draft);+ removeEmergencyDraft(draft.memoId, storage);+ expect(readEmergencyDraft(draft.memoId, storage)).toBeNull();+ });++ test("fails closed when browser storage is unavailable", () => {+ const storage = { setItem: () => { throw new Error("quota"); } };+ expect(persistEmergencyDraft({+ memoId: "memo-1",+ title: "",+ tagsText: "",+ contentJson: { type: "doc", content: [] },+ updatedAt: "2026-08-29T12:00:00.000Z",+ }, storage)).toBe(false);+ });+});diff --git a/apps/web/src/lib/emergency-draft.ts b/apps/web/src/lib/emergency-draft.tsnew file mode 100644index 00000000..bf29d00d--- /dev/null+++ b/apps/web/src/lib/emergency-draft.ts@@ -0,0 +1,51 @@+import type { LocalDraft } from "@/lib/local-db";++const EMERGENCY_DRAFT_PREFIX = "edgeever.emergency-draft.";++const getStorage = () => {+ try {+ return typeof window === "undefined" ? null : window.localStorage;+ } catch {+ return null;+ }+};++const storageKey = (memoId: string) => `${EMERGENCY_DRAFT_PREFIX}${memoId}`;++export const persistEmergencyDraft = (draft: LocalDraft, storage: Storage | null = getStorage()) => {+ try {+ storage?.setItem(storageKey(draft.memoId), JSON.stringify(draft));+ return Boolean(storage);+ } catch {+ return false;+ }+};++export const readEmergencyDraft = (memoId: string, storage: Storage | null = getStorage()): LocalDraft | null => {+ try {+ const value = storage?.getItem(storageKey(memoId));+ if (!value) return null;+ const draft = JSON.parse(value) as Partial<LocalDraft>;+ if (+ draft.memoId !== memoId ||+ typeof draft.title !== "string" ||+ typeof draft.tagsText !== "string" ||+ typeof draft.updatedAt !== "string" ||+ !draft.contentJson ||+ typeof draft.contentJson !== "object"+ ) {+ return null;+ }+ return draft as LocalDraft;+ } catch {+ return null;+ }+};++export const removeEmergencyDraft = (memoId: string, storage: Storage | null = getStorage()) => {+ try {+ storage?.removeItem(storageKey(memoId));+ } catch {+ // A failed cleanup must not make an already durable save fail.+ }+};diff --git a/apps/web/src/lib/local-database-recovery.test.mjs b/apps/web/src/lib/local-database-recovery.test.mjsnew file mode 100644index 00000000..85046d1d--- /dev/null+++ b/apps/web/src/lib/local-database-recovery.test.mjs@@ -0,0 +1,48 @@+import { describe, expect, test } from "bun:test";+import {+ LocalDatabaseUnavailableError,+ runLocalDatabaseOperationWithRecovery,+} from "./local-database-recovery";++describe("local database recovery", () => {+ test("reopens and retries once after a storage operation times out", async () => {+ let attempts = 0;+ let reopens = 0;+ const result = await runLocalDatabaseOperationWithRecovery(+ async () => {+ attempts += 1;+ if (attempts === 1) return new Promise(() => {});+ return "saved";+ },+ {+ reopen: async () => { reopens += 1; },+ timeoutMs: 5,+ },+ );++ expect(result).toBe("saved");+ expect(attempts).toBe(2);+ expect(reopens).toBe(1);+ });++ test("fails explicitly instead of waiting forever when retry also times out", async () => {+ let attempts = 0;+ await expect(runLocalDatabaseOperationWithRecovery(+ async () => {+ attempts += 1;+ return new Promise(() => {});+ },+ { reopen: async () => {}, timeoutMs: 5 },+ )).rejects.toBeInstanceOf(LocalDatabaseUnavailableError);+ expect(attempts).toBe(2);+ });++ test("does not retry non-recoverable validation errors", async () => {+ let reopens = 0;+ await expect(runLocalDatabaseOperationWithRecovery(+ async () => { throw new TypeError("Invalid memo payload"); },+ { reopen: async () => { reopens += 1; }, timeoutMs: 5 },+ )).rejects.toThrow("Invalid memo payload");+ expect(reopens).toBe(0);+ });+});diff --git a/apps/web/src/lib/local-database-recovery.ts b/apps/web/src/lib/local-database-recovery.tsnew file mode 100644index 00000000..91276916--- /dev/null+++ b/apps/web/src/lib/local-database-recovery.ts@@ -0,0 +1,67 @@+export const LOCAL_DATABASE_OPERATION_TIMEOUT_MS = 8_000;+const LOCAL_DATABASE_REOPEN_TIMEOUT_MS = 4_000;++class LocalDatabaseOperationTimeoutError extends Error {+ constructor() {+ super("Browser local storage operation timed out");+ this.name = "LocalDatabaseOperationTimeoutError";+ }+}++export class LocalDatabaseUnavailableError extends Error {+ readonly cause: unknown;++ constructor(cause: unknown) {+ super("Browser local storage is not responding");+ this.name = "LocalDatabaseUnavailableError";+ this.cause = cause;+ }+}++const withTimeout = <T>(operation: Promise<T>, timeoutMs: number) => new Promise<T>((resolve, reject) => {+ const timer = globalThis.setTimeout(() => reject(new LocalDatabaseOperationTimeoutError()), timeoutMs);+ operation.then(+ (value) => {+ globalThis.clearTimeout(timer);+ resolve(value);+ },+ (error) => {+ globalThis.clearTimeout(timer);+ reject(error);+ },+ );+});++const isRecoverableLocalDatabaseError = (error: unknown) =>+ error instanceof LocalDatabaseOperationTimeoutError ||+ (error instanceof Error && ["AbortError", "DatabaseClosedError", "InvalidStateError", "UnknownError"].includes(error.name));++export const reopenLocalDatabase = async () => {+ const { localDb } = await import("@/lib/local-db");+ localDb.close({ disableAutoOpen: false });+ await localDb.open();+};++export const runLocalDatabaseOperationWithRecovery = async <T>(+ operation: () => Promise<T>,+ {+ reopen = reopenLocalDatabase,+ timeoutMs = LOCAL_DATABASE_OPERATION_TIMEOUT_MS,+ }: {+ reopen?: () => Promise<void>;+ timeoutMs?: number;+ } = {},+) => {+ try {+ return await withTimeout(operation(), timeoutMs);+ } catch (error) {+ if (!isRecoverableLocalDatabaseError(error)) throw error;+ }++ try {+ await withTimeout(reopen(), Math.min(timeoutMs, LOCAL_DATABASE_REOPEN_TIMEOUT_MS));+ return await withTimeout(operation(), timeoutMs);+ } catch (error) {+ throw new LocalDatabaseUnavailableError(error);+ }+};diff --git a/apps/web/src/lib/local-db.ts b/apps/web/src/lib/local-db.tsindex 2a6e3409..586e6647 100644--- a/apps/web/src/lib/local-db.ts+++ b/apps/web/src/lib/local-db.ts@@ -1,6 +1,13 @@import type { MemoDetail, MemoRevision, MemoTemplate, Notebook, ResourceListItem, TiptapDoc } from "@edgeever/shared";import Dexie, { type Table } from "dexie";+export const LOCAL_DATABASE_INTERRUPTED_EVENT = "edgeever:local-database-interrupted";++const notifyLocalDatabaseInterrupted = (reason: "blocked" | "versionchange") => {+ if (typeof window === "undefined") return;+ window.dispatchEvent(new CustomEvent(LOCAL_DATABASE_INTERRUPTED_EVENT, { detail: { reason } }));+};+export type LocalDraft = {memoId: string;expectedRevision?: number;@@ -103,6 +110,8 @@ class EdgeEverLocalDb extends Dexie {constructor() {super("edgeever-local");+ this.on("blocked", () => notifyLocalDatabaseInterrupted("blocked"));+ this.on("versionchange", () => notifyLocalDatabaseInterrupted("versionchange"));this.version(1).stores({drafts: "memoId, updatedAt",});diff --git a/apps/web/src/lib/repository.test.mjs b/apps/web/src/lib/repository.test.mjsindex be2f14dc..27dbda62 100644--- a/apps/web/src/lib/repository.test.mjs+++ b/apps/web/src/lib/repository.test.mjs@@ -21,8 +21,9 @@ const installTestWindow = ({ hostname = "localhost" } = {}) => {};afterEach(async () => {- await localDb.transaction("rw", [localDb.templates, localDb.notebooks, localDb.memos, localDb.resources, localDb.revisions, localDb.syncMeta, localDb.syncQueue], async () => {+ await localDb.transaction("rw", [localDb.drafts, localDb.templates, localDb.notebooks, localDb.memos, localDb.resources, localDb.revisions, localDb.syncMeta, localDb.syncQueue], async () => {await Promise.all([+ localDb.drafts.clear(),localDb.templates.clear(),localDb.notebooks.clear(),localDb.memos.clear(),@@ -123,6 +124,34 @@ describe("web repository offline boundaries", () => {}});+ test("rolls back the local memo when queuing its sync update fails", async () => {+ const restoreWindow = installTestWindow();+ const scope = "https://demo.edgeever.org|user-1";+ const memo = await createLocalMemo(scope, { notebookId: "nb-1", contentMarkdown: "Original" });+ const failQueueWrite = () => { throw new Error("queue unavailable"); };+ localDb.syncQueue.hook("creating", failQueueWrite);++ try {+ await expect(createWebRepository(scope).updateMemo(memo, {+ expectedRevision: memo.revision,+ expectedContentHash: memo.contentHash,+ editSessionId: "local-edit",+ title: "Changed",+ contentJson: {+ type: "doc",+ content: [{ type: "paragraph", content: [{ type: "text", text: "Changed" }] }],+ },+ tags: [],+ })).rejects.toThrow("queue unavailable");++ expect((await localDb.memos.get([scope, memo.id]))?.contentText).toBe("Original");+ expect(await localDb.syncQueue.get(`memo.update:${memo.id}`)).toBeUndefined();+ } finally {+ localDb.syncQueue.hook("creating").unsubscribe(failQueueWrite);+ restoreWindow();+ }+ });+test("uses the remote detail when the local database is blocked and navigator falsely reports offline", async () => {const previousOnline = globalThis.navigator?.onLine;if (globalThis.navigator) Object.defineProperty(globalThis.navigator, "onLine", { configurable: true, value: false });diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.tsindex 54055406..60c117ea 100644--- a/apps/web/src/lib/repository.ts+++ b/apps/web/src/lib/repository.ts@@ -39,8 +39,9 @@ import {type LocalMemoListParams,type LocalMemoListResponse,} from "@/lib/local-mirror";-import { discardWebMemoConflict, getMemoUpdateQueueId, queueLocalAction, queueMemoCreate, queueMemoDelete, queueMemoRestore, queueMemoUpdate } from "@/lib/sync-queue";+import { discardWebMemoConflict, getMemoUpdateQueueId, putMemoUpdateQueueItem, queueLocalAction, queueMemoCreate, queueMemoDelete, queueMemoRestore, queueMemoUpdate } from "@/lib/sync-queue";import { localDb, type MemoUpdateSyncPayload } from "@/lib/local-db";+import { runLocalDatabaseOperationWithRecovery } from "@/lib/local-database-recovery";import { createDesktopRepository } from "@/lib/desktop-repository";import { isBrowserOffline } from "@/lib/network-status";import { notifySyncQueueDeferred } from "@/lib/sync-events";@@ -472,8 +473,13 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {async updateMemo(memo, input) {const payload: MemoUpdateSyncPayload = { ...input, memoId: memo.id };- const updated = await putLocalMemoUpdate(scope, memo, payload);- await queueMemoUpdate(payload, scope);+ const updated = await runLocalDatabaseOperationWithRecovery(() =>+ localDb.transaction("rw", [localDb.memos, localDb.syncQueue], async () => {+ const nextMemo = await putLocalMemoUpdate(scope, memo, payload);+ await putMemoUpdateQueueItem(payload, scope);+ return nextMemo;+ })+ );notifySyncQueueDeferred();return { memo: updated, queued: true };},diff --git a/apps/web/src/lib/sync-queue.ts b/apps/web/src/lib/sync-queue.tsindex c87f64c0..c7513e5e 100644--- a/apps/web/src/lib/sync-queue.ts+++ b/apps/web/src/lib/sync-queue.ts@@ -67,44 +67,45 @@ export const queueLocalAction = async (scope: string, kind: LocalActionKind, ent});};-export const queueMemoUpdate = async (payload: MemoUpdateSyncPayload, scope?: string) => {+export const putMemoUpdateQueueItem = async (payload: MemoUpdateSyncPayload, scope?: string) => {const id = getMemoUpdateQueueId(payload.memoId);const now = new Date().toISOString();- await localDb.transaction("rw", localDb.syncQueue, async () => {- const existing = await localDb.syncQueue.get(id);- const existingPayload = existing?.kind === "memo.update"- ? existing.payload as MemoUpdateSyncPayload- : null;- // A previous in-flight save may already have advanced this queue row to a- // newer acknowledged server base. A local autosave that started just- // before that acknowledgement must not move the successor back again.- const nextPayload = existingPayload && existingPayload.expectedRevision > payload.expectedRevision- ? {- ...payload,- expectedRevision: existingPayload.expectedRevision,- expectedContentHash: existingPayload.expectedContentHash,- }- : payload;-- await localDb.syncQueue.put({- id,- kind: "memo.update",- scope: scope ?? existing?.scope,- memoId: payload.memoId,- status: "pending",- payload: nextPayload,- attemptCount: existing?.attemptCount ?? 0,- lastError: null,- lastErrorCode: null,- lastErrorDetails: null,- nextAttemptAt: null,- claimId: null,- createdAt: existing?.createdAt ?? now,- updatedAt: now,- });+ const existing = await localDb.syncQueue.get(id);+ const existingPayload = existing?.kind === "memo.update"+ ? existing.payload as MemoUpdateSyncPayload+ : null;+ // A previous in-flight save may already have advanced this queue row to a+ // newer acknowledged server base. A local autosave that started just+ // before that acknowledgement must not move the successor back again.+ const nextPayload = existingPayload && existingPayload.expectedRevision > payload.expectedRevision+ ? {+ ...payload,+ expectedRevision: existingPayload.expectedRevision,+ expectedContentHash: existingPayload.expectedContentHash,+ }+ : payload;++ await localDb.syncQueue.put({+ id,+ kind: "memo.update",+ scope: scope ?? existing?.scope,+ memoId: payload.memoId,+ status: "pending",+ payload: nextPayload,+ attemptCount: existing?.attemptCount ?? 0,+ lastError: null,+ lastErrorCode: null,+ lastErrorDetails: null,+ nextAttemptAt: null,+ claimId: null,+ createdAt: existing?.createdAt ?? now,+ updatedAt: now,});};+export const queueMemoUpdate = async (payload: MemoUpdateSyncPayload, scope?: string) =>+ localDb.transaction("rw", localDb.syncQueue, () => putMemoUpdateQueueItem(payload, scope));+export const queueMemoCreate = async (scope: string, payload: MemoCreateSyncPayload) => {const id = getMemoCreateQueueId(payload.temporaryId);const now = new Date().toISOString();diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex f8b23123..c0d6c72a 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -1088,6 +1088,8 @@ export const enUS = {conflict: "Conflict",error: "Save failed",unsaved: "Unsaved",+ storageUnavailable: "Browser local storage stopped responding. Keep this page open, close other EdgeEver tabs, then retry. Copy the local draft before clearing any browser data.",+ storageRetry: "Retry save",conflictReason: {revisionWithVersions: "The cloud note was updated (local base revision {{expected}}, cloud is {{current}}). Common causes: another browser tab, another device, or a cloud change while you were offline. Copy your local draft, then use the cloud version before editing again.",revision: "The cloud note was updated elsewhere. Common causes: another browser tab, another device, or a cloud change while you were offline. Copy your local draft, then use the cloud version before editing again.",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 2af3f20d..500303d6 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -1088,6 +1088,8 @@ export const zhCN = {conflict: "有冲突",error: "保存失败",unsaved: "未保存",+ storageUnavailable: "浏览器本地存储无响应。请保持当前页面打开,关闭其他 EdgeEver 标签页后重试。清除浏览器数据前请先复制本地草稿。",+ storageRetry: "重试保存",conflictReason: {revisionWithVersions: "云端笔记已更新(本地基于版本 {{expected}},云端已是 {{current}})。常见原因:其他标签页、其他设备,或离线期间云端被改过。可先复制本地草稿,再采用云端版本后继续编辑。",revision: "云端笔记已在其他位置被更新。常见原因:其他标签页、其他设备,或离线期间云端被改过。可先复制本地草稿,再采用云端版本后继续编辑。",diff --git a/tests/e2e/local-storage-recovery.spec.ts b/tests/e2e/local-storage-recovery.spec.tsnew file mode 100644index 00000000..9b51c99a--- /dev/null+++ b/tests/e2e/local-storage-recovery.spec.ts@@ -0,0 +1,71 @@+import { expect, test, type Page } from "@playwright/test";++const openMemo = async (page: Page, memoId: string, title: string) => {+ await page.getByRole("button", { name: "全部笔记", exact: true }).click();+ await page.getByPlaceholder("搜索笔记").fill(title);+ await page.locator(`[data-memo-id="${memoId}"]`).locator("button").first().click();+};++const deleteLocalDatabase = (page: Page) => page.evaluate(() => new Promise<void>((resolve, reject) => {+ const request = indexedDB.deleteDatabase("edgeever-local");+ request.onerror = () => reject(request.error);+ request.onblocked = () => reject(new Error("Deleting edgeever-local was blocked"));+ request.onsuccess = () => resolve();+}));++const readEmergencyDraft = (page: Page, memoId: string) => page.evaluate(+ (id) => window.localStorage.getItem(`edgeever.emergency-draft.${id}`),+ memoId,+);++test("preserves the current draft and recovers after IndexedDB is interrupted", async ({ page }) => {+ const marker = `storage-recovery-${Date.now()}`;+ const title = `Storage recovery ${Date.now()}`;+ const notebooksResponse = await page.request.get("/api/v1/notebooks");+ expect(notebooksResponse.ok()).toBe(true);+ const notebooks = await notebooksResponse.json() as { notebooks: Array<{ id: string }> };+ const notebookId = notebooks.notebooks[0]?.id;+ expect(notebookId).toBeTruthy();++ const createResponse = await page.request.post("/api/v1/memos", {+ data: { notebookId, title, contentMarkdown: "Content before storage interruption" },+ });+ expect(createResponse.status()).toBe(201);+ const memoId = (await createResponse.json() as { memo: { id: string } }).memo.id;++ try {+ await page.goto("/");+ await openMemo(page, memoId, title);++ const editor = page.locator(".ProseMirror[contenteditable='true']");+ await expect(editor).toContainText("Content before storage interruption");+ await editor.click();+ await page.keyboard.press("End");+ await page.keyboard.insertText(` ${marker}`);++ await deleteLocalDatabase(page);++ const storageAlert = page.getByRole("alert").filter({ hasText: "浏览器本地存储无响应" });+ await expect(storageAlert).toBeVisible();+ await expect(page.getByText("保存中", { exact: true })).toHaveCount(0);+ await expect.poll(() => readEmergencyDraft(page, memoId)).toContain(marker);++ await storageAlert.getByRole("button", { name: "重试保存", exact: true }).click();+ await expect(storageAlert).toHaveCount(0);+ await expect.poll(() => readEmergencyDraft(page, memoId)).toBeNull();++ await expect.poll(async () => {+ const response = await page.request.get(`/api/v1/memos/${memoId}`);+ if (!response.ok()) return "";+ const body = await response.json() as { memo: { contentJson: unknown } };+ return JSON.stringify(body.memo.contentJson);+ }, { timeout: 20_000 }).toContain(marker);++ await page.reload();+ await openMemo(page, memoId, title);+ await expect(page.locator(".ProseMirror[contenteditable='true']")).toContainText(marker);+ } finally {+ await page.request.delete(`/api/v1/memos/${memoId}`);+ await page.request.delete(`/api/v1/memos/${memoId}?permanent=1`);+ }+});