Skip to content

AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.

fix(mobile): delete offline-created and empty notes from list selection

tianma-if95db3ee5a344
diff --git a/apps/mobile/src/lib/local-mirror.ts b/apps/mobile/src/lib/local-mirror.ts
index 8a080b1a..3de6d1f4 100644
--- a/apps/mobile/src/lib/local-mirror.ts
+++ b/apps/mobile/src/lib/local-mirror.ts
@@ -163,6 +163,22 @@ export const deleteLocalMemo = async (scope: string, memoId: string) => {
await db.runAsync(`DELETE FROM mobile_memos WHERE scope = ? AND id = ?`, scope, memoId);
};
+/** Soft-delete a mirror row so list views hide it without waiting for a remote sync. */
+export const softDeleteLocalMemo = async (scope: string, memoId: string) => {
+ const memo = await getLocalMemo(scope, memoId);
+ if (!memo || memo.isDeleted) {
+ return false;
+ }
+ const now = new Date().toISOString();
+ await upsertLocalMemo(scope, {
+ ...memo,
+ isDeleted: true,
+ deletedAt: now,
+ updatedAt: now,
+ });
+ return true;
+};
+
export const replaceLocalMemoId = async (scope: string, temporaryId: string, memo: MemoDetail) => {
const db = await getDatabase();
await db.withExclusiveTransactionAsync(async (tx) => {
diff --git a/apps/mobile/src/lib/mobile-memo-delete.test.ts b/apps/mobile/src/lib/mobile-memo-delete.test.ts
new file mode 100644
index 00000000..51d520af
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-memo-delete.test.ts
@@ -0,0 +1,139 @@
+import { beforeEach, expect, mock, test } from "bun:test";
+
+const storage = new Map<string, string>();
+const memos = new Map<string, { id: string; isDeleted?: boolean }>();
+
+mock.module("@react-native-async-storage/async-storage", () => ({
+ default: {
+ getItem: async (key: string) => storage.get(key) ?? null,
+ removeItem: async (key: string) => {
+ storage.delete(key);
+ },
+ setItem: async (key: string, value: string) => {
+ storage.set(key, value);
+ },
+ },
+}));
+
+mock.module("./local-mirror", () => ({
+ deleteLocalMemo: async (_scope: string, memoId: string) => {
+ memos.delete(memoId);
+ },
+ resolveLocalMemo: async (_scope: string, memoId: string) => {
+ if (memos.has(memoId)) {
+ return memos.get(memoId);
+ }
+ if (memoId.startsWith("local:")) {
+ const mapped = [...memos.values()].find((memo) => memo.id === "memo-mapped");
+ return mapped ?? null;
+ }
+ return null;
+ },
+ softDeleteLocalMemo: async (_scope: string, memoId: string) => {
+ const memo = memos.get(memoId);
+ if (!memo) return false;
+ memos.set(memoId, { ...memo, isDeleted: true });
+ return true;
+ },
+}));
+
+const {
+ queueMobileMemoCreate,
+ listMobileSyncQueueItems,
+} = await import("./sync-queue");
+const { deleteMobileMemos } = await import("./mobile-memo-delete");
+
+beforeEach(() => {
+ storage.clear();
+ memos.clear();
+});
+
+test("deletes offline-created notes without calling the API", async () => {
+ const scope = "https://one.example";
+ memos.set("local:empty", { id: "local:empty" });
+ await queueMobileMemoCreate(scope, {
+ memoId: "local:empty",
+ title: "Untitled",
+ contentMarkdown: "",
+ notebookId: "notebook-1",
+ tags: [],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ });
+
+ const deletedRemote: string[] = [];
+ const result = await deleteMobileMemos({
+ client: {
+ deleteMemo: async (memoId: string) => {
+ deletedRemote.push(memoId);
+ return { ok: true as const };
+ },
+ deleteMemos: async ({ memoIds }: { memoIds: string[] }) => {
+ deletedRemote.push(...memoIds);
+ return { ok: true as const, deleted: memoIds.length };
+ },
+ } as never,
+ dataScope: scope,
+ syncQueueScope: scope,
+ memoIds: ["local:empty"],
+ permanent: false,
+ });
+
+ expect(result).toEqual({ deleted: 1, localOnly: 1, remote: 0 });
+ expect(deletedRemote).toEqual([]);
+ expect(memos.has("local:empty")).toBe(false);
+ expect(await listMobileSyncQueueItems(scope)).toHaveLength(0);
+});
+
+test("soft-deletes synced notes through the API and local mirror", async () => {
+ const scope = "https://one.example";
+ memos.set("memo-1", { id: "memo-1" });
+ memos.set("memo-2", { id: "memo-2" });
+
+ const deletedBatches: string[][] = [];
+ const result = await deleteMobileMemos({
+ client: {
+ deleteMemo: async () => {
+ throw new Error("should use batch delete for multiple ids");
+ },
+ deleteMemos: async ({ memoIds }: { memoIds: string[] }) => {
+ deletedBatches.push(memoIds);
+ return { ok: true as const, deleted: memoIds.length };
+ },
+ } as never,
+ dataScope: scope,
+ syncQueueScope: scope,
+ memoIds: ["memo-1", "memo-2"],
+ permanent: false,
+ });
+
+ expect(result).toEqual({ deleted: 2, localOnly: 0, remote: 2 });
+ expect(deletedBatches).toEqual([["memo-1", "memo-2"]]);
+ expect(memos.get("memo-1")?.isDeleted).toBe(true);
+ expect(memos.get("memo-2")?.isDeleted).toBe(true);
+});
+
+test("resolves remapped temporary ids to remote deletes", async () => {
+ const scope = "https://one.example";
+ memos.set("memo-mapped", { id: "memo-mapped" });
+
+ const deletedMemoIds: string[] = [];
+ const result = await deleteMobileMemos({
+ client: {
+ deleteMemo: async (memoId: string) => {
+ deletedMemoIds.push(memoId);
+ return { ok: true as const };
+ },
+ deleteMemos: async () => {
+ throw new Error("should use single delete");
+ },
+ } as never,
+ dataScope: scope,
+ syncQueueScope: scope,
+ memoIds: ["local:stale"],
+ permanent: false,
+ });
+
+ expect(result).toEqual({ deleted: 1, localOnly: 0, remote: 1 });
+ expect(deletedMemoIds).toEqual(["memo-mapped"]);
+ expect(memos.get("memo-mapped")?.isDeleted).toBe(true);
+});
diff --git a/apps/mobile/src/lib/mobile-memo-delete.ts b/apps/mobile/src/lib/mobile-memo-delete.ts
new file mode 100644
index 00000000..36efa411
--- /dev/null
+++ b/apps/mobile/src/lib/mobile-memo-delete.ts
@@ -0,0 +1,92 @@
+import type { createEdgeEverClient } from "@edgeever/client";
+import { clearMobileMemoDraft } from "./mobile-drafts";
+import { deleteLocalMemo, resolveLocalMemo, softDeleteLocalMemo } from "./local-mirror";
+import { cancelMobileMemoQueueItems, listMobileSyncQueueItems } from "./sync-queue";
+
+type MobileClient = ReturnType<typeof createEdgeEverClient>;
+
+const isLocalTemporaryId = (memoId: string) => memoId.startsWith("local:");
+
+/**
+ * Delete notes from the mobile client.
+ *
+ * Offline-created notes (`local:…` / pending `memo.create`) never hit the
+ * server — cancel their queue work and drop the local mirror row.
+ * Synced notes soft-delete (or permanently delete) on the API and update the
+ * local mirror optimistically so the list updates immediately.
+ */
+export const deleteMobileMemos = async ({
+ client,
+ dataScope,
+ syncQueueScope,
+ memoIds,
+ permanent = false,
+}: {
+ client: MobileClient | null;
+ dataScope: string;
+ syncQueueScope: string;
+ memoIds: string[];
+ permanent?: boolean;
+}): Promise<{ deleted: number; localOnly: number; remote: number }> => {
+ const uniqueIds = Array.from(new Set(memoIds.filter(Boolean)));
+ if (uniqueIds.length === 0) {
+ return { deleted: 0, localOnly: 0, remote: 0 };
+ }
+
+ const queueItems = await listMobileSyncQueueItems(syncQueueScope);
+ const pendingCreateIds = new Set(
+ queueItems.filter((item) => item.kind === "memo.create").map((item) => item.memoId)
+ );
+
+ const localOnlyIds: string[] = [];
+ const remoteIds: string[] = [];
+
+ for (const memoId of uniqueIds) {
+ if (pendingCreateIds.has(memoId) || isLocalTemporaryId(memoId)) {
+ if (isLocalTemporaryId(memoId) && !pendingCreateIds.has(memoId)) {
+ const resolved = await resolveLocalMemo(dataScope, memoId);
+ if (resolved && !isLocalTemporaryId(resolved.id) && !pendingCreateIds.has(resolved.id)) {
+ remoteIds.push(resolved.id);
+ continue;
+ }
+ }
+ localOnlyIds.push(memoId);
+ continue;
+ }
+ remoteIds.push(memoId);
+ }
+
+ for (const memoId of localOnlyIds) {
+ await cancelMobileMemoQueueItems(syncQueueScope, memoId);
+ await deleteLocalMemo(dataScope, memoId);
+ await clearMobileMemoDraft(memoId);
+ }
+
+ const uniqueRemoteIds = Array.from(new Set(remoteIds));
+ if (uniqueRemoteIds.length > 0) {
+ if (!client) {
+ throw new Error("当前无法连接实例,请稍后重试");
+ }
+ if (uniqueRemoteIds.length === 1) {
+ await client.deleteMemo(uniqueRemoteIds[0]!, { permanent });
+ } else {
+ await client.deleteMemos({ memoIds: uniqueRemoteIds, permanent });
+ }
+ await Promise.all(
+ uniqueRemoteIds.map(async (memoId) => {
+ if (permanent) {
+ await deleteLocalMemo(dataScope, memoId);
+ } else {
+ await softDeleteLocalMemo(dataScope, memoId);
+ }
+ await clearMobileMemoDraft(memoId);
+ })
+ );
+ }
+
+ return {
+ deleted: localOnlyIds.length + uniqueRemoteIds.length,
+ localOnly: localOnlyIds.length,
+ remote: uniqueRemoteIds.length,
+ };
+};
diff --git a/apps/mobile/src/lib/sync-queue.test.ts b/apps/mobile/src/lib/sync-queue.test.ts
index 5e46c4b7..6fcf9d1d 100644
--- a/apps/mobile/src/lib/sync-queue.test.ts
+++ b/apps/mobile/src/lib/sync-queue.test.ts
@@ -17,6 +17,7 @@ mock.module("@react-native-async-storage/async-storage", () => ({
}));
const {
+ cancelMobileMemoQueueItems,
discardMobileMemoConflict,
getMobileConflictDraftClipboardText,
listMobileSyncQueueItems,
@@ -216,6 +217,64 @@ test("promotes an edit made while an offline create is syncing", async () => {
expect(queued?.payload.expectedContentHash).toBe("hash-remote");
});
+test("cancels queue items for a memo", async () => {
+ const scope = "https://one.example";
+ await queueMobileMemoCreate(scope, {
+ memoId: "local:one",
+ title: "Offline",
+ contentMarkdown: "body",
+ notebookId: "notebook-1",
+ tags: [],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ });
+ await queueMobileMemoUpdate(scope, { ...basePayload, memoId: "memo-2" });
+
+ await cancelMobileMemoQueueItems(scope, "local:one");
+
+ const remaining = await listMobileSyncQueueItems(scope);
+ expect(remaining).toHaveLength(1);
+ expect(remaining[0]?.memoId).toBe("memo-2");
+});
+
+test("soft-deletes the remote orphan when an offline create is cancelled mid-sync", async () => {
+ const scope = "https://one.example";
+ await queueMobileMemoCreate(scope, {
+ memoId: "local:one",
+ title: "Offline",
+ contentMarkdown: "first",
+ notebookId: "notebook-1",
+ tags: [],
+ createdAt: "2026-01-01T00:00:00.000Z",
+ });
+ let markCreateStarted: (() => void) | undefined;
+ const createStarted = new Promise<void>((resolve) => {
+ markCreateStarted = resolve;
+ });
+ let resolveCreate: ((memo: MemoDetail) => void) | undefined;
+ const createResponse = new Promise<MemoDetail>((resolve) => {
+ resolveCreate = resolve;
+ });
+ const deletedMemoIds: string[] = [];
+ const client = {
+ createMemo: async () => {
+ markCreateStarted?.();
+ return createResponse.then((memo) => ({ memo }));
+ },
+ deleteMemo: async (memoId: string) => {
+ deletedMemoIds.push(memoId);
+ return { ok: true as const };
+ },
+ };
+ const sync = syncMobileQueuedChanges(client as never, scope);
+ await createStarted;
+ await cancelMobileMemoQueueItems(scope, "local:one");
+ resolveCreate?.(createMemo({ id: "memo-remote", revision: 0, contentHash: "hash-remote" }));
+ await sync;
+
+ expect(deletedMemoIds).toEqual(["memo-remote"]);
+ expect(await listMobileSyncQueueItems(scope)).toHaveLength(0);
+});
+
const createMemo = (overrides: Partial<MemoDetail> = {}): MemoDetail => ({
id: "memo-1",
notebookId: "notebook-1",
diff --git a/apps/mobile/src/lib/sync-queue.ts b/apps/mobile/src/lib/sync-queue.ts
index 1909181b..95b396d8 100644
--- a/apps/mobile/src/lib/sync-queue.ts
+++ b/apps/mobile/src/lib/sync-queue.ts
@@ -147,6 +147,12 @@ export const deleteMobileSyncQueueItem = async (scope: string, id: string) => {
return loadMobileSyncQueueSummary(scope);
};
+/** Drop every create/update queue entry for a memo (used when discarding local-only notes). */
+export const cancelMobileMemoQueueItems = async (scope: string, memoId: string) => {
+ await mutateMobileSyncQueue(scope, (items) => items.filter((item) => item.memoId !== memoId));
+ return loadMobileSyncQueueSummary(scope);
+};
+
/**
* Discard a single note's conflicted local queue item and return the
* authoritative cloud memo so the UI can rehydrate cleanly.
@@ -232,8 +238,19 @@ export const syncMobileQueuedChanges = async (
if (removed) {
await options.onSynced?.(memo, item);
} else if (item.kind === "memo.create") {
- await promoteQueuedMemoCreate(scope, item.id, itemVersion, memo);
- await options.onSynced?.(memo, item);
+ const promoted = await promoteQueuedMemoCreate(scope, item.id, itemVersion, memo);
+ if (promoted) {
+ await options.onSynced?.(memo, item);
+ } else {
+ // User cancelled the offline create while it was in flight. The local
+ // row is already gone; soft-delete the remote orphan so it does not
+ // reappear on the next mirror sync.
+ try {
+ await client.deleteMemo(memo.id, { permanent: false });
+ } catch {
+ // Best-effort cleanup; a later full sync can still reconcile.
+ }
+ }
} else {
await rebaseQueuedMemoUpdate(scope, item.id, itemVersion, memo);
}
@@ -385,14 +402,21 @@ const rebaseQueuedMemoUpdate = async (scope: string, id: string, syncedVersion:
);
};
-const promoteQueuedMemoCreate = async (scope: string, id: string, syncedVersion: number, memo: MemoDetail) => {
+const promoteQueuedMemoCreate = async (
+ scope: string,
+ id: string,
+ syncedVersion: number,
+ memo: MemoDetail
+): Promise<boolean> => {
+ let promoted = false;
await mutateMobileSyncQueue(scope, (items) => {
const current = items.find((item) => item.id === id);
if (!current || current.kind !== "memo.create" || current.version <= syncedVersion) {
return items;
}
+ promoted = true;
const now = new Date().toISOString();
- const promoted: MobileMemoUpdateSyncQueueItem = {
+ const promotedItem: MobileMemoUpdateSyncQueueItem = {
id: getMobileMemoUpdateQueueId(memo.id),
kind: "memo.update",
memoId: memo.id,
@@ -413,8 +437,9 @@ const promoteQueuedMemoCreate = async (scope: string, id: string, syncedVersion:
updatedAt: now,
version: 1,
};
- return [promoted, ...items.filter((item) => item.id !== id && item.id !== promoted.id)];
+ return [promotedItem, ...items.filter((item) => item.id !== id && item.id !== promotedItem.id)];
});
+ return promoted;
};
const mutateMobileSyncQueue = async (scope: string, mutate: (items: MobileSyncQueueItem[]) => MobileSyncQueueItem[]) => {
diff --git a/apps/mobile/src/screens/WorkspaceScreen.tsx b/apps/mobile/src/screens/WorkspaceScreen.tsx
index 63a36876..a4b851c8 100644
--- a/apps/mobile/src/screens/WorkspaceScreen.tsx
+++ b/apps/mobile/src/screens/WorkspaceScreen.tsx
@@ -90,6 +90,7 @@ import {
queueMobileMemoUpdate,
type MobileSyncQueueItem,
} from "../lib/sync-queue";
+import { deleteMobileMemos } from "../lib/mobile-memo-delete";
import {
createMobileDataScope,
getLocalMemo,
@@ -224,6 +225,15 @@ export const WorkspaceScreen = ({
const incomingShareUrl = useMemo(() => getSharedWebUrl(incomingSharePayloads), [incomingSharePayloads]);
const handleMemoIdRemapped = useCallback((temporaryId: string, memo: MemoDetail) => {
setSelectedMemoId((current) => current === temporaryId ? memo.id : current);
+ setSelectedMemoIds((current) => {
+ if (!current.has(temporaryId)) {
+ return current;
+ }
+ const next = new Set(current);
+ next.delete(temporaryId);
+ next.add(memo.id);
+ return next;
+ });
}, []);
const {
refreshSyncQueueItems,
@@ -794,11 +804,14 @@ export const WorkspaceScreen = ({
const deleteMemoMutation = useMutation({
mutationFn: async ({ memo, permanent }: { memo: MemoDetail; permanent: boolean }) => {
- if (!client) {
- throw new Error("Client is not ready");
- }
-
- await client.deleteMemo(memo.id, { permanent });
+ await deleteMobileMemos({
+ client,
+ dataScope,
+ syncQueueScope,
+ memoIds: [memo.id],
+ permanent,
+ });
+ await refreshSyncQueueItems();
return { memo, permanent };
},
onSuccess: async () => {
@@ -806,6 +819,9 @@ export const WorkspaceScreen = ({
setRichEditingSession(null);
setSelectedMemoId(null);
},
+ onError: (error) => {
+ Alert.alert("删除失败", error instanceof Error ? error.message : "请检查网络后重试");
+ },
});
const restoreMemoMutation = useMutation({
@@ -874,16 +890,23 @@ export const WorkspaceScreen = ({
const deleteMemosMutation = useMutation({
mutationFn: async ({ memoIds, permanent }: { memoIds: string[]; permanent: boolean }) => {
- if (!client) {
- throw new Error("Client is not ready");
- }
-
- return client.deleteMemos({ memoIds, permanent });
+ const result = await deleteMobileMemos({
+ client,
+ dataScope,
+ syncQueueScope,
+ memoIds,
+ permanent,
+ });
+ await refreshSyncQueueItems();
+ return result;
},
onSuccess: async () => {
await invalidateWorkspace();
clearSelection();
},
+ onError: (error) => {
+ Alert.alert("删除失败", error instanceof Error ? error.message : "请检查网络后重试");
+ },
});
const handleTogglePin = (memo: MemoDetail) => {