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: delete empty child notebooks with their parent
tianma-if968ac71aa61b
diff --git a/apps/api/src/notebook-service.test.mjs b/apps/api/src/notebook-service.test.mjsindex 25eb1cd6..7d3e22a3 100644--- a/apps/api/src/notebook-service.test.mjs+++ b/apps/api/src/notebook-service.test.mjs@@ -234,4 +234,50 @@ describe("notebook identity", () => {fixture.sqlite.close();}});++ test("deletes an empty notebook together with its empty descendants", async () => {+ const fixture = createFixture();+ try {+ fixture.sqlite.exec(`+ UPDATE notebooks SET name = '注册考试' WHERE id = 'nb_notes';+ INSERT INTO notebooks (id, workspace_id, parent_id, name, slug, is_deleted, created_at, updated_at) VALUES+ ('nb_law', 'ws_1', 'nb_notes', '法律法规', 'law', 0, '2026-09-10T00:00:00.000Z', '2026-09-10T00:00:00.000Z'),+ ('nb_history', 'ws_1', 'nb_notes', '建筑史', 'history', 0, '2026-09-10T00:00:00.000Z', '2026-09-10T00:00:00.000Z'),+ ('nb_outline', 'ws_1', 'nb_history', '大纲', 'outline', 0, '2026-09-10T00:00:00.000Z', '2026-09-10T00:00:00.000Z');+ INSERT INTO memos (id, workspace_id, notebook_id, title, is_deleted, updated_at)+ VALUES ('memo_trashed', 'ws_1', 'nb_law', '已删除', 1, '2026-09-10T00:00:00.000Z');+ `);++ await deleteNotebookRecord(fixture.db, "ws_1", "nb_notes", actor);++ expect(+ fixture.sqlite.query("SELECT id FROM notebooks WHERE workspace_id = 'ws_1' AND is_deleted = 0 ORDER BY id").all(),+ ).toEqual([{ id: "ws_1_inbox" }]);+ await expect(deleteNotebookRecord(fixture.db, "ws_1", "nb_notes", actor)).resolves.toBeUndefined();+ } finally {+ fixture.sqlite.close();+ }+ });++ test("keeps the whole notebook tree when any descendant still has a note", async () => {+ const fixture = createFixture();+ try {+ fixture.sqlite.exec(`+ INSERT INTO notebooks (id, workspace_id, parent_id, name, slug, is_deleted, created_at, updated_at) VALUES+ ('nb_child', 'ws_1', 'nb_notes', '子笔记本', 'child', 0, '2026-09-10T00:00:00.000Z', '2026-09-10T00:00:00.000Z');+ INSERT INTO memos (id, workspace_id, notebook_id, title, is_deleted, updated_at)+ VALUES ('memo_keep', 'ws_1', 'nb_child', '还在', 0, '2026-09-10T00:00:00.000Z');+ `);++ await expect(deleteNotebookRecord(fixture.db, "ws_1", "nb_notes", actor)).rejects.toMatchObject({+ code: "notebook_not_empty",+ status: 409,+ });+ expect(+ fixture.sqlite.query("SELECT id FROM notebooks WHERE workspace_id = 'ws_1' AND is_deleted = 1").all(),+ ).toEqual([]);+ } finally {+ fixture.sqlite.close();+ }+ });});diff --git a/apps/api/src/notebook-service.ts b/apps/api/src/notebook-service.tsindex ce1e88c5..e818b47f 100644--- a/apps/api/src/notebook-service.ts+++ b/apps/api/src/notebook-service.ts@@ -241,43 +241,96 @@ export const updateNotebookRecord = async (return notebook;};+const NOTEBOOK_DELETE_ID_CHUNK = 80;++const chunkValues = <T>(values: T[], size: number) => {+ const chunks: T[][] = [];+ for (let index = 0; index < values.length; index += size) {+ chunks.push(values.slice(index, index + size));+ }+ return chunks;+};++// Active notebooks in this subtree. The anchor may already be deleted so a+// retried parent delete can still remove descendants that were left behind.+const listActiveNotebookTree = async (db: DatabaseAdapter, workspaceId: string, id: string) => {+ const rows = await db.prepare(+ `WITH RECURSIVE tree(id) AS (+ SELECT id FROM notebooks WHERE workspace_id = ? AND id = ?+ UNION ALL+ SELECT n.id+ FROM notebooks n+ INNER JOIN tree t ON n.parent_id = t.id+ WHERE n.workspace_id = ?+ )+ SELECT n.id, n.slug+ FROM notebooks n+ INNER JOIN tree t ON t.id = n.id+ WHERE n.workspace_id = ? AND n.is_deleted = 0`+ ).bind(workspaceId, id, workspaceId, workspaceId).all<{ id: string; slug: string | null }>();++ return rows.results;+};++const countActiveMemosInNotebooks = async (db: DatabaseAdapter, workspaceId: string, notebookIds: string[]) => {+ let total = 0;+ for (const chunk of chunkValues(notebookIds, NOTEBOOK_DELETE_ID_CHUNK)) {+ const placeholders = chunk.map(() => "?").join(", ");+ const row = await db.prepare(+ `SELECT COUNT(*) AS count FROM memos WHERE workspace_id = ? AND is_deleted = 0 AND notebook_id IN (${placeholders})`+ ).bind(workspaceId, ...chunk).first<{ count: number }>();+ total += Number(row?.count ?? 0);+ }+ return total;+};+export const deleteNotebookRecord = async (db: DatabaseAdapter,workspaceId: string,id: string,actor: AuditActor) => {- const current = await getNotebook(db, workspaceId, id);+ const current = await db.prepare(+ `SELECT id, slug, is_deleted FROM notebooks WHERE id = ? AND workspace_id = ?`+ ).bind(id, workspaceId).first<{ id: string; slug: string | null; is_deleted: number }>();if (!current) throw new AppError("not_found", "Notebook not found", 404);if (isInboxNotebook(current, workspaceId)) {+ if (current.is_deleted) return;throw new AppError("bad_request", "等待分类不能删除。", 400);}- const [childCount, memoCount] = await Promise.all([- db.prepare(`SELECT COUNT(*) AS count FROM notebooks WHERE workspace_id = ? AND parent_id = ? AND is_deleted = 0`)- .bind(workspaceId, id)- .first<{ count: number }>(),- db.prepare(`SELECT COUNT(*) AS count FROM memos WHERE workspace_id = ? AND notebook_id = ? AND is_deleted = 0`)- .bind(workspaceId, id)- .first<{ count: number }>(),- ]);+ const tree = await listActiveNotebookTree(db, workspaceId, id);+ if (tree.length === 0) return;+ if (tree.some((notebook) => isInboxNotebook(notebook, workspaceId))) {+ throw new AppError("bad_request", "等待分类不能删除。", 400);+ }- if ((childCount?.count ?? 0) > 0 || (memoCount?.count ?? 0) > 0) {+ const notebookIds = tree.map((notebook) => notebook.id);+ // Empty child notebooks are removed with the parent. Notes anywhere in the+ // subtree block the whole delete so a parent click cannot orphan them.+ if (await countActiveMemosInNotebooks(db, workspaceId, notebookIds) > 0) {throw new AppError("notebook_not_empty",- "Move or delete child notebooks and memos before deleting this notebook.",+ "Move or delete notes in this notebook and its child notebooks before deleting it.",409);}const now = isoNow();- await db.prepare(- `UPDATE notebooks- SET is_deleted = 1, deleted_at = ?, updated_at = ?- WHERE id = ? AND workspace_id = ? AND slug <> 'inbox'- AND id <> 'nb_inbox' AND id <> ?`- ).bind(now, now, id, workspaceId, workspaceInboxId(workspaceId)).run();- await audit(db, actor.actorType, actor.actorId, "notebook.delete", "notebook", id, {});+ const inboxId = workspaceInboxId(workspaceId);+ const statements = chunkValues(notebookIds, NOTEBOOK_DELETE_ID_CHUNK).map((chunk) => {+ const placeholders = chunk.map(() => "?").join(", ");+ return db.prepare(+ `UPDATE notebooks+ SET is_deleted = 1, deleted_at = ?, updated_at = ?+ WHERE workspace_id = ? AND is_deleted = 0 AND id IN (${placeholders})+ AND slug <> 'inbox' AND id <> 'nb_inbox' AND id <> ?`+ ).bind(now, now, workspaceId, ...chunk, inboxId);+ });+ statements.push(auditStatement(db, actor.actorType, actor.actorId, "notebook.delete", "notebook", id, {+ notebookIds,+ }));+ await db.batch(statements);};export const restoreNotebookRecord = async (diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsxindex 7bf01f24..20864dbc 100644--- a/apps/web/src/components/WorkspaceApp.tsx+++ b/apps/web/src/components/WorkspaceApp.tsx@@ -103,6 +103,7 @@ import {putLocalMemo,putLocalNotebook,} from "@/lib/local-mirror";+import { isNotebookNotEmptyError } from "@/lib/notebook-delete";import { getPersistentDataScopeOrigin } from "@/lib/app-page-path";import { createRepository } from "@/lib/repository";import { notifyRepositoryMutation } from "@/lib/repository-events";@@ -1215,6 +1216,15 @@ export const WorkspaceApp = ({await queryClient.invalidateQueries({ queryKey: ["notebooks"] });await queryClient.invalidateQueries({ queryKey: ["memos"] });},+ onError: (error) => {+ setNotebookDeleteConfirmation(null);+ setAppNoticeDialog({+ title: t("workspaceDialogs.deleteNotebookFailedTitle"),+ description: isNotebookNotEmptyError(error)+ ? t("workspaceDialogs.deleteNotebookNotEmpty")+ : t("workspaceDialogs.deleteNotebookFailed"),+ });+ },});const revealCreatedMemo = (memo: MemoDetail) => {diff --git a/apps/web/src/hooks/useWorkspaceQueuedSync.ts b/apps/web/src/hooks/useWorkspaceQueuedSync.tsindex c609954f..cf59cb37 100644--- a/apps/web/src/hooks/useWorkspaceQueuedSync.ts+++ b/apps/web/src/hooks/useWorkspaceQueuedSync.ts@@ -161,6 +161,7 @@ export const useWorkspaceQueuedSync = ({},});window.dispatchEvent(new CustomEvent("edgeever:sync-completed", { detail: result }));+ if (result.failed > 0) await invalidateSyncQueries();} finally {setIsSyncingQueuedChanges(false);}diff --git a/apps/web/src/lib/desktop-sync.ts b/apps/web/src/lib/desktop-sync.tsindex 18ba9b95..b9f7bdfc 100644--- a/apps/web/src/lib/desktop-sync.ts+++ b/apps/web/src/lib/desktop-sync.ts@@ -17,6 +17,7 @@ import {} from "@edgeever/shared";import { api, ApiRequestError } from "@/lib/api";import { isDesktopResourceRuntime, mapMarkdownResourceUrls, mapTiptapResourceUrls, toApiResourceUrl } from "@/lib/desktop-resources";+import { notebookDeleteIdsFromPayload } from "@/lib/notebook-delete";import { notifyMemoIdRemapped, notifyMemoSyncAcknowledged } from "@/lib/sync-events";type StagedResourceRewrite = { memoId: string; placeholder: string; url: string };@@ -433,7 +434,9 @@ const syncOutboxItem = async (item: DesktopOutboxItem, stagedRewrites: StagedRes}if (item.kind === "notebook.delete") {- await api.deleteNotebook(String(payload.notebookId ?? item.entityId));+ for (const notebookId of notebookDeleteIdsFromPayload(payload, String(payload.notebookId ?? item.entityId))) {+ await api.deleteNotebook(notebookId);+ }await acknowledge(item);return null;}diff --git a/apps/web/src/lib/local-mirror.test.mjs b/apps/web/src/lib/local-mirror.test.mjsindex ecb48ac1..aa1852e7 100644--- a/apps/web/src/lib/local-mirror.test.mjs+++ b/apps/web/src/lib/local-mirror.test.mjs@@ -1,4 +1,5 @@import { afterEach, describe, expect, test } from "bun:test";+import { NotebookNotEmptyError } from "./notebook-delete.ts";import { IDBKeyRange, indexedDB } from "fake-indexeddb";globalThis.indexedDB = indexedDB;@@ -24,7 +25,9 @@ const {updateLocalNotebook,getLocalNotebook,deleteLocalNotebook,+ deleteLocalNotebookTree,putLocalNotebook,+ reconcileLocalNotebooks,mergeLocalMemos,putLocalMemoRevisions,listLocalMemoRevisions,@@ -343,6 +346,74 @@ describe("local mirror", () => {expect(await getLocalNotebook(scope, "notebook-1")).toBeNull();});+ test("deletes an empty notebook subtree and refuses one that still has notes", async () => {+ const scope = createLocalDataScope("https://demo.edgeever.org", "user-1");+ const notebook = (id, parentId, name) => putLocalNotebook(scope, {+ id,+ parentId,+ name,+ slug: null,+ icon: null,+ color: null,+ sortOrder: 0,+ memoCount: 0,+ lastMemoUpdatedAt: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ });+ await notebook("exam", null, "注册考试");+ await notebook("law", "exam", "法律法规");+ await notebook("history", "exam", "建筑史");+ await notebook("games", null, "游戏");++ const deletedIds = await deleteLocalNotebookTree(scope, "exam");+ expect(new Set(deletedIds)).toEqual(new Set(["law", "history", "exam"]));+ expect(deletedIds.at(-1)).toBe("exam");+ expect(await getLocalNotebook(scope, "exam")).toBeNull();+ expect(await getLocalNotebook(scope, "law")).toBeNull();+ expect(await getLocalNotebook(scope, "history")).toBeNull();+ expect(await getLocalNotebook(scope, "games")).not.toBeNull();++ await notebook("blocked", null, "仍有笔记");+ await notebook("blocked-child", "blocked", "子笔记本");+ await createLocalMemo(scope, { notebookId: "blocked-child", title: "还在", tags: [] });+ await expect(deleteLocalNotebookTree(scope, "blocked")).rejects.toBeInstanceOf(NotebookNotEmptyError);+ expect(await getLocalNotebook(scope, "blocked")).not.toBeNull();+ expect(await getLocalNotebook(scope, "blocked-child")).not.toBeNull();+ });++ test("does not restore a notebook that is waiting to be deleted", async () => {+ const scope = createLocalDataScope("https://demo.edgeever.org", "user-1");+ const notebook = (id, parentId, name) => ({+ id,+ parentId,+ name,+ slug: null,+ icon: null,+ color: null,+ sortOrder: 0,+ memoCount: 0,+ lastMemoUpdatedAt: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-01T00:00:00.000Z",+ });+ await putLocalNotebook(scope, notebook("exam", null, "注册考试"));+ await putLocalNotebook(scope, notebook("law", "exam", "法律法规"));+ await putLocalNotebook(scope, notebook("local_new", null, "未同步"));++ await reconcileLocalNotebooks(+ scope,+ [notebook("exam", null, "注册考试"), notebook("law", "exam", "法律法规"), notebook("games", null, "游戏")],+ new Set(["exam", "law"]),+ new Set(["local_new"]),+ );++ expect(await getLocalNotebook(scope, "exam")).toBeNull();+ expect(await getLocalNotebook(scope, "law")).toBeNull();+ expect(await getLocalNotebook(scope, "local_new")).not.toBeNull();+ expect((await getLocalNotebook(scope, "games"))?.name).toBe("游戏");+ });+test("merges memos locally and marks source notes as deleted", async () => {const scope = createLocalDataScope("https://demo.edgeever.org", "user-1");const first = await createLocalMemo(scope, { notebookId: "inbox", title: "First", contentMarkdown: "one", tags: ["a"] });diff --git a/apps/web/src/lib/local-mirror.ts b/apps/web/src/lib/local-mirror.tsindex 5a2d57f3..2c6c6a8b 100644--- a/apps/web/src/lib/local-mirror.ts+++ b/apps/web/src/lib/local-mirror.ts@@ -7,6 +7,7 @@ import {markdownToDoc,mergeMemoDocs,getDiagramSummary,+ getNotebookDescendantIds,resolveMemoContentDoc,resolveMergedMemoTitle,type MemoDetail,@@ -23,6 +24,7 @@ import type { MemoFilterMode, MemoSortMode } from "@/lib/app-helpers";import { api, type SyncChangesResponse } from "@/lib/api";import { localDb, selectNewestLocalDraft, type LocalDraft, type LocalMemo, type LocalNotebook, type LocalResource, type LocalRevision } from "@/lib/local-db";import { cacheLocalResourceBytes, localResourceUrl, removeCachedLocalResourceBytes } from "@/lib/local-resource-cache";+import { NotebookNotEmptyError, notebooksBlockedByPendingDeletes } from "@/lib/notebook-delete";import { isBrowserOffline } from "@/lib/network-status";import { parseTagsText } from "@/lib/utils";import { createClientUuid } from "@/lib/client-id";@@ -556,6 +558,72 @@ export const deleteLocalNotebook = async (scope: string, notebookId: string) =>return true;};+const isProtectedInboxNotebook = (notebook: Pick<Notebook, "id" | "slug">) =>+ notebook.slug === "inbox" || notebook.id === "nb_inbox" || notebook.id.endsWith("_inbox");++// Removes the notebook and its empty descendants. Ids are leaves-first so a+// server that still deletes one notebook at a time can apply them in order.+export const deleteLocalNotebookTree = async (scope: string, notebookId: string) => {+ const { notebooks } = await listLocalNotebooks(scope);+ const ids = getNotebookDescendantIds(notebooks, notebookId);+ const idSet = new Set(ids);+ const selected = notebooks.filter((notebook) => idSet.has(notebook.id));+ if (selected.length === 0) return [notebookId];+ if (selected.some((notebook) => notebook.memoCount > 0)) throw new NotebookNotEmptyError();+ if (selected.some((notebook) => isProtectedInboxNotebook(notebook))) throw new Error("inbox_not_deletable");+ await Promise.all(selected.map((notebook) => localDb.notebooks.delete([scope, notebook.id])));+ return [...ids].reverse();+};++export const readNotebookSyncGuards = async (scope: string) => {+ const items = (await localDb.syncQueue.where("status").anyOf("pending", "syncing", "error").toArray())+ .filter((item) => item.scope === scope);+ const pendingDeleteIds = new Set<string>();+ const pendingCreateIds = new Set<string>();+ for (const item of items) {+ if (item.kind === "notebook.create") {+ pendingCreateIds.add(item.memoId);+ const temporaryId = (item.payload as { temporaryId?: unknown }).temporaryId;+ if (typeof temporaryId === "string" && temporaryId.length > 0) pendingCreateIds.add(temporaryId);+ }+ if (item.kind !== "notebook.delete" || (item.status !== "pending" && item.status !== "syncing")) continue;+ const payload = item.payload as { notebookId?: unknown; notebookIds?: unknown };+ if (typeof payload.notebookId === "string") pendingDeleteIds.add(payload.notebookId);+ if (Array.isArray(payload.notebookIds)) {+ for (const id of payload.notebookIds) {+ if (typeof id === "string" && id.length > 0) pendingDeleteIds.add(id);+ }+ }+ if (item.memoId) pendingDeleteIds.add(item.memoId);+ }+ return { pendingDeleteIds, pendingCreateIds };+};++export const reconcileLocalNotebooks = async (+ scope: string,+ remoteNotebooks: Notebook[],+ pendingDeleteIds: ReadonlySet<string>,+ pendingCreateIds: ReadonlySet<string>,+) => {+ const blocked = notebooksBlockedByPendingDeletes(remoteNotebooks, pendingDeleteIds);+ const remoteIds = new Set(remoteNotebooks.map((notebook) => notebook.id));+ const keep = (notebook: { id: string }) => {+ if (pendingDeleteIds.has(notebook.id) || blocked.has(notebook.id)) return false;+ if (remoteIds.has(notebook.id)) return true;+ return pendingCreateIds.has(notebook.id) || notebook.id.startsWith("local_");+ };++ await localDb.transaction("rw", localDb.notebooks, async () => {+ const local = await localDb.notebooks.where("scope").equals(scope).toArray();+ for (const notebook of local) {+ if (!keep(notebook)) await localDb.notebooks.delete([scope, notebook.id]);+ }+ for (const notebook of remoteNotebooks) {+ if (keep(notebook)) await localDb.notebooks.put({ ...notebook, scope });+ }+ });+};+export const createLocalNotebook = async (scope: string, input: { name: string; parentId?: string | null }) => {const now = new Date().toISOString();const notebook: Notebook = {diff --git a/apps/web/src/lib/notebook-delete.test.mjs b/apps/web/src/lib/notebook-delete.test.mjsnew file mode 100644index 00000000..b0f0fffc--- /dev/null+++ b/apps/web/src/lib/notebook-delete.test.mjs@@ -0,0 +1,26 @@+import { describe, expect, test } from "bun:test";+import { notebookDeleteIdsFromPayload, notebooksBlockedByPendingDeletes } from "./notebook-delete.ts";++describe("notebook delete ids", () => {+ test("uses the ordered descendant list and falls back to the single id", () => {+ expect(notebookDeleteIdsFromPayload({ notebookId: "parent", notebookIds: ["child", "parent"] }, "other")).toEqual(["child", "parent"]);+ expect(notebookDeleteIdsFromPayload({ notebookId: "parent" }, "other")).toEqual(["parent"]);+ expect(notebookDeleteIdsFromPayload({}, "parent")).toEqual(["parent"]);+ });++ test("hides a notebook and every descendant covered by a pending delete", () => {+ const notebooks = [+ { id: "exam", parentId: null },+ { id: "law", parentId: "exam" },+ { id: "history", parentId: "exam" },+ { id: "outline", parentId: "history" },+ { id: "games", parentId: null },+ ];++ expect(notebooksBlockedByPendingDeletes(notebooks, new Set(["exam"]))).toEqual(new Set(["exam", "law", "history", "outline"]));+ expect(notebooksBlockedByPendingDeletes(+ notebooks.filter((notebook) => notebook.id !== "exam"),+ new Set(["exam"]),+ )).toEqual(new Set(["law", "history", "outline"]));+ });+});diff --git a/apps/web/src/lib/notebook-delete.ts b/apps/web/src/lib/notebook-delete.tsnew file mode 100644index 00000000..61f6aaa4--- /dev/null+++ b/apps/web/src/lib/notebook-delete.ts@@ -0,0 +1,60 @@+export class NotebookNotEmptyError extends Error {+ readonly code = "notebook_not_empty";++ constructor() {+ super("notebook_not_empty");+ this.name = "NotebookNotEmptyError";+ }+}++export const isNotebookNotEmptyError = (error: unknown) => {+ if (error instanceof NotebookNotEmptyError) return true;+ if (typeof error === "object" && error !== null && "code" in error && (error as { code?: unknown }).code === "notebook_not_empty") {+ return true;+ }+ return error instanceof Error && error.message === "notebook_not_empty";+};++export const notebookDeleteIdsFromPayload = (+ payload: { notebookId?: unknown; notebookIds?: unknown } | null | undefined,+ fallbackId: string,+) => {+ const listed = Array.isArray(payload?.notebookIds)+ ? payload.notebookIds.filter((id): id is string => typeof id === "string" && id.length > 0)+ : [];+ if (listed.length > 0) return listed;+ const notebookId = typeof payload?.notebookId === "string" && payload.notebookId.length > 0+ ? payload.notebookId+ : fallbackId;+ return notebookId ? [notebookId] : [];+};++// A pending delete of a parent must also hide descendants that the server+// still lists, including when the parent itself is already absent.+export const notebooksBlockedByPendingDeletes = (+ notebooks: Array<{ id: string; parentId?: string | null }>,+ pendingDeleteIds: ReadonlySet<string>,+) => {+ const parentById = new Map(notebooks.map((notebook) => [notebook.id, notebook.parentId ?? null]));+ const blocked = new Set<string>();++ for (const notebook of notebooks) {+ const seen = new Set<string>();+ let currentId: string | null = notebook.id;+ while (currentId && !seen.has(currentId)) {+ if (pendingDeleteIds.has(currentId)) {+ blocked.add(notebook.id);+ break;+ }+ seen.add(currentId);+ const parentId: string | null = parentById.get(currentId) ?? null;+ if (parentId && pendingDeleteIds.has(parentId)) {+ blocked.add(notebook.id);+ break;+ }+ currentId = parentId;+ }+ }++ return blocked;+};diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.tsindex e58c6bf7..09ce5ce1 100644--- a/apps/web/src/lib/repository.ts+++ b/apps/web/src/lib/repository.ts@@ -17,8 +17,10 @@ import {applyLocalEmptyTrash,applyLocalMemoPin,updateLocalNotebook,- deleteLocalNotebook,+ deleteLocalNotebookTree,createLocalNotebook,+ readNotebookSyncGuards,+ reconcileLocalNotebooks,createLocalTemplate,updateLocalTemplate,mergeLocalMemos,@@ -178,6 +180,21 @@ const acceptRemoteMemoDetail = async (return true;};+const notebookListGeneration = new Map<string, number>();++const beginNotebookListRefresh = (scope: string) => {+ const generation = (notebookListGeneration.get(scope) ?? 0) + 1;+ notebookListGeneration.set(scope, generation);+ return generation;+};++const applyRemoteNotebookList = async (scope: string, notebooks: Notebook[], generation: number) => {+ if (notebookListGeneration.get(scope) !== generation) return;+ const guards = await readNotebookSyncGuards(scope);+ if (notebookListGeneration.get(scope) !== generation) return;+ await reconcileLocalNotebooks(scope, notebooks, guards.pendingDeleteIds, guards.pendingCreateIds);+};+export const createWebRepository = (scope: string): EdgeEverRepository => {const isOffline = isBrowserOffline;@@ -185,12 +202,18 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {async listNotebooks() {const local = await listLocalNotebooks(scope);if (local.notebooks.length > 0 || isOffline()) {- if (!isOffline()) void api.listNotebooks().then((remote) => Promise.all(remote.notebooks.map((notebook) => putLocalNotebook(scope, notebook)))).catch(() => {});+ if (!isOffline()) {+ const generation = beginNotebookListRefresh(scope);+ void api.listNotebooks()+ .then((remote) => applyRemoteNotebookList(scope, remote.notebooks, generation))+ .catch(() => {});+ }return local;}+ const generation = beginNotebookListRefresh(scope);const remote = await api.listNotebooks();- await Promise.all(remote.notebooks.map((notebook) => putLocalNotebook(scope, notebook)));+ await applyRemoteNotebookList(scope, remote.notebooks, generation);return remote;},@@ -215,8 +238,8 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {},async deleteNotebook(notebookId) {- await deleteLocalNotebook(scope, notebookId);- await queueLocalAction(scope, "notebook.delete", notebookId, { notebookId });+ const notebookIds = await deleteLocalNotebookTree(scope, notebookId);+ await queueLocalAction(scope, "notebook.delete", notebookId, { notebookId, notebookIds });window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));return { ok: true as const };},diff --git a/apps/web/src/lib/sync-queue.ts b/apps/web/src/lib/sync-queue.tsindex 2ff1081d..87351ed4 100644--- a/apps/web/src/lib/sync-queue.ts+++ b/apps/web/src/lib/sync-queue.ts@@ -32,6 +32,7 @@ import { getCachedLocalResourceBytes, removeCachedLocalResourceBytes } from "@/limport { isBrowserOffline } from "@/lib/network-status";import { parseTagsText } from "@/lib/utils";import { createClientUuid } from "@/lib/client-id";+import { notebookDeleteIdsFromPayload } from "@/lib/notebook-delete";export type { SyncQueueSummary, SyncRunResult } from "@edgeever/shared";export type SyncQueueResult = MemoDetail | Notebook | MemoTemplate | Resource | null;@@ -422,6 +423,15 @@ const runQueuedChanges = async (options: {result.synced += 1;}} catch (error) {+ if (+ item.kind === "notebook.delete"+ && error instanceof ApiRequestError+ && (error.code === "notebook_not_empty" || error.code === "bad_request")+ ) {+ await localDb.syncQueue.delete(item.id);+ result.failed += 1;+ continue;+ }const conflictInfo = getMemoSaveConflictInfo(error);const status = conflictInfo ? "conflict" : "error";const attemptCount = item.attemptCount + 1;@@ -721,7 +731,9 @@ const syncQueueItem = async (item: SyncQueueItem): Promise<SyncQueueResult> => {}if (item.kind === "notebook.delete") {const payload = item.payload as LocalActionPayload;- await api.deleteNotebook(String(payload.notebookId ?? item.memoId));+ for (const notebookId of notebookDeleteIdsFromPayload(payload, String(payload.notebookId ?? item.memoId))) {+ await api.deleteNotebook(notebookId);+ }return null;}if (item.kind === "template.create") {diff --git a/crates/desktop-sidecar/src/catalog.rs b/crates/desktop-sidecar/src/catalog.rsindex ef82420d..585dcf98 100644--- a/crates/desktop-sidecar/src/catalog.rs+++ b/crates/desktop-sidecar/src/catalog.rs@@ -1,4 +1,4 @@-use rusqlite::Connection;+use rusqlite::{Connection, OptionalExtension};use serde_json::{json, Value};use std::time::{SystemTime, UNIX_EPOCH};@@ -94,32 +94,119 @@ pub(crate) fn update_notebook(database: &Connection, params: &Value) -> Result<VOk(notebook)}+struct ActiveNotebook {+ id: String,+ slug: Option<String>,+}++fn active_notebook_tree(database: &Connection, notebook_id: &str) -> Result<Vec<ActiveNotebook>, String> {+ let mut statement = database+ .prepare(+ "WITH RECURSIVE tree(id, depth) AS (+ SELECT id, 0 FROM notebooks WHERE id = ?1+ UNION ALL+ SELECT n.id, tree.depth + 1+ FROM notebooks n+ INNER JOIN tree ON n.parent_id = tree.id+ WHERE n.is_deleted = 0+ )+ SELECT n.id, n.slug+ FROM tree+ INNER JOIN notebooks n ON n.id = tree.id+ WHERE n.is_deleted = 0+ ORDER BY tree.depth DESC, n.id",+ )+ .map_err(|e| e.to_string())?;+ let rows = statement+ .query_map([notebook_id], |row| {+ Ok(ActiveNotebook {+ id: row.get(0)?,+ slug: row.get(1)?,+ })+ })+ .map_err(|e| e.to_string())?;+ rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())+}+pub(crate) fn delete_notebook(database: &Connection, params: &Value) -> Result<Value, String> {let notebook_id = string_param(params, "notebookId")?;- let child_count: i64 = database+ let current_slug: Option<Option<String>> = database.query_row(- "SELECT COUNT(*) FROM notebooks WHERE parent_id = ?1 AND is_deleted = 0",+ "SELECT slug FROM notebooks WHERE id = ?1",[¬ebook_id],|row| row.get(0),)+ .optional().map_err(|e| e.to_string())?;+ let Some(current_slug) = current_slug else {+ return Err(format!("Notebook not found: {notebook_id}"));+ };+ if is_inbox_notebook(¬ebook_id, current_slug.as_deref()) {+ return Err("inbox_not_deletable".to_owned());+ }++ let tree = active_notebook_tree(database, ¬ebook_id)?;+ if tree.is_empty() {+ let exists: bool = database+ .query_row(+ "SELECT EXISTS(SELECT 1 FROM notebooks WHERE id = ?1)",+ [¬ebook_id],+ |row| row.get(0),+ )+ .map_err(|e| e.to_string())?;+ if !exists {+ return Err(format!("Notebook not found: {notebook_id}"));+ }+ return Ok(json!({ "ok": true }));+ }+ if tree.iter().any(|notebook| is_inbox_notebook(¬ebook.id, notebook.slug.as_deref())) {+ return Err("inbox_not_deletable".to_owned());+ }+let memo_count: i64 = database.query_row(- "SELECT COUNT(*) FROM memos WHERE notebook_id = ?1 AND is_deleted = 0",+ "WITH RECURSIVE tree(id) AS (+ SELECT id FROM notebooks WHERE id = ?1+ UNION ALL+ SELECT n.id FROM notebooks n+ INNER JOIN tree ON n.parent_id = tree.id+ WHERE n.is_deleted = 0+ )+ SELECT COUNT(*) FROM memos+ WHERE is_deleted = 0 AND notebook_id IN (+ SELECT n.id FROM notebooks n INNER JOIN tree ON tree.id = n.id WHERE n.is_deleted = 0+ )",[¬ebook_id],|row| row.get(0),).map_err(|e| e.to_string())?;- if child_count > 0 || memo_count > 0 {+ if memo_count > 0 {return Err("notebook_not_empty".to_owned());}- database.execute("UPDATE notebooks SET is_deleted = 1, deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'), updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now') WHERE id = ?1 AND slug <> 'inbox' AND id <> 'nb_inbox' AND id NOT GLOB '*_inbox'", [¬ebook_id]).map_err(|e| e.to_string())?;++ let ids: Vec<String> = tree.iter().map(|notebook| notebook.id.clone()).collect();+ let tx = database.unchecked_transaction().map_err(|e| e.to_string())?;+ for id in &ids {+ tx.execute(+ "UPDATE notebooks+ SET is_deleted = 1,+ deleted_at = strftime('%Y-%m-%dT%H:%M:%fZ','now'),+ updated_at = strftime('%Y-%m-%dT%H:%M:%fZ','now')+ WHERE id = ?1 AND is_deleted = 0+ AND slug <> 'inbox' AND id <> 'nb_inbox' AND id NOT GLOB '*_inbox'",+ [id],+ )+ .map_err(|e| e.to_string())?;+ }+ // Leaves are ordered before parents so an older server can delete one+ // empty notebook at a time. A current server also accepts the root alone.enqueue_change(- database,+ &tx,"notebook.delete",¬ebook_id,- &json!({ "notebookId": notebook_id }),+ &json!({ "notebookId": notebook_id, "notebookIds": ids }),)?;+ tx.commit().map_err(|e| e.to_string())?;Ok(json!({ "ok": true }))}diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex b27d6c92..6adb7f7d 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -2075,7 +2075,10 @@ export const enUS = {emptyTrashFailedTitle: "Couldn't empty trash",emptyTrashFailedDescription: "Your notes have been restored to Trash. Please try again.",deleteNotebookTitle: "Delete notebook “{{name}}”",- deleteNotebookDescription: "Clear its notes and child notebooks first. It cannot be restored from here after deletion.",+ deleteNotebookDescription: "Empty child notebooks are deleted with it. Move or delete any notes inside first. It cannot be restored from here.",+ deleteNotebookFailedTitle: "Couldn't delete this notebook",+ deleteNotebookNotEmpty: "This notebook or one of its child notebooks still has notes. Move or delete those notes, then try again.",+ deleteNotebookFailed: "The notebook is still here. Please try again.",ok: "OK",resizeMemoList: "Resize note list",resizeMemoListHint: "Drag to resize the list column, double-click to reset, or use arrow keys for fine tuning",diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 6aa7c48a..066072dd 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -2075,7 +2075,10 @@ export const ja = {emptyTrashFailedTitle: "ゴミ箱を空にできませんでした",emptyTrashFailedDescription: "ノートはゴミ箱に戻しました。再試行してください。",deleteNotebookTitle: "ノートブック「{{name}}」を削除",- deleteNotebookDescription: "先に中のノートと子ノートブックを空にしてください。削除後はここから復元できません。",+ deleteNotebookDescription: "空の子ノートブックも一緒に削除されます。中にノートがあるときは、先に移動または削除してください。削除後はここから復元できません。",+ deleteNotebookFailedTitle: "このノートブックを削除できませんでした",+ deleteNotebookNotEmpty: "このノートブックか子ノートブックにノートが残っています。先にノートを移動または削除してから、もう一度お試しください。",+ deleteNotebookFailed: "ノートブックは残っています。しばらくしてからもう一度お試しください。",ok: "OK",resizeMemoList: "ノート一覧の幅を変更",resizeMemoListHint: "ドラッグで一覧欄の幅を変え、ダブルクリックでリセット、矢印キーで微調整できます",diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 02e2b3b1..33b64029 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -2073,7 +2073,10 @@ export const zhCN = {emptyTrashFailedTitle: "清空回收站失败",emptyTrashFailedDescription: "笔记已恢复到回收站,请稍后重试。",deleteNotebookTitle: "删除笔记本「{{name}}」",- deleteNotebookDescription: "请先清空其中的笔记和子笔记本。删除后无法从这里恢复。",+ deleteNotebookDescription: "其中的空子笔记本会一起删除。如果里面还有笔记,需要先移走或删除。删除后无法从这里恢复。",+ deleteNotebookFailedTitle: "没能删除这个笔记本",+ deleteNotebookNotEmpty: "这个笔记本或它的子笔记本里还有笔记。请先把笔记移走或删除,再删除笔记本。",+ deleteNotebookFailed: "删除没有完成,笔记本还在。请稍后重试。",ok: "知道了",resizeMemoList: "调整笔记列表宽度",resizeMemoListHint: "拖拽调整列表栏宽度,双击恢复默认,方向键微调",diff --git a/scripts/test-desktop-sidecar.mjs b/scripts/test-desktop-sidecar.mjsindex 43e95ca8..3255f4c8 100644--- a/scripts/test-desktop-sidecar.mjs+++ b/scripts/test-desktop-sidecar.mjs@@ -465,6 +465,22 @@ assert.ok((await request("sync.outbox.list", { limit: 200, includeConflicts: truawait request("sync.outbox.discard", { id: conflictCandidate.id });assert.equal((await request("sync.status")).conflict, 0);+const examNotebook = (await request("notebook.create", { name: "注册考试" })).notebook;+const lawNotebook = (await request("notebook.create", { name: "法律法规", parentId: examNotebook.id })).notebook;+const historyNotebook = (await request("notebook.create", { name: "建筑史", parentId: examNotebook.id })).notebook;+await request("notebook.delete", { notebookId: examNotebook.id });+const remainingNotebookIds = new Set((await request("notebook.list")).notebooks.map((notebook) => notebook.id));+assert.equal(remainingNotebookIds.has(examNotebook.id), false, "an empty parent notebook should be deleted with its children");+assert.equal(remainingNotebookIds.has(lawNotebook.id), false, "an empty child notebook should be deleted with its parent");+assert.equal(remainingNotebookIds.has(historyNotebook.id), false, "every empty descendant should be deleted with the parent");+const blockedNotebook = (await request("notebook.create", { name: "仍有笔记" })).notebook;+const blockedChild = (await request("notebook.create", { name: "子笔记本", parentId: blockedNotebook.id })).notebook;+await request("memo.create", { notebookId: blockedChild.id, title: "还在", contentMarkdown: "keep", tags: [] });+await assert.rejects(request("notebook.delete", { notebookId: blockedNotebook.id }), /notebook_not_empty/);+const blockedNotebookIds = new Set((await request("notebook.list")).notebooks.map((notebook) => notebook.id));+assert.equal(blockedNotebookIds.has(blockedNotebook.id), true, "a notebook with notes in a child should stay");+assert.equal(blockedNotebookIds.has(blockedChild.id), true, "a child notebook that still has notes should stay");+child.stdin.end();await new Promise((resolve) => child.once("close", resolve));-console.log(JSON.stringify({ ok: true, checked: ["memo.create", "memo.list.search", "memo.list.tag", "memo.list.subtree", "memo.update", "memo.update.coalesce", "memo.revisions", "memo.restoreRevision", "memo.revision.cache", "tag.rename", "memo.moveBatch", "memo.pinBatch", "memo.deleteBatch", "memo.restore", "memo.emptyTrash", "memo.merge", "template.cache", "template.create.payload", "template.delete", "storage.backup", "storage.backups", "storage.restore", "sync.apply.merge-page-order", "sync.apply.deleted-notebook", "sync.apply.renamed-inbox", "sync.outbox", "sync.outbox.retry", "sync.outbox.recoverMemoUpdate", "sync.outbox.discard"] }));+console.log(JSON.stringify({ ok: true, checked: ["memo.create", "memo.list.search", "memo.list.tag", "memo.list.subtree", "memo.update", "memo.update.coalesce", "memo.revisions", "memo.restoreRevision", "memo.revision.cache", "tag.rename", "memo.moveBatch", "memo.pinBatch", "memo.deleteBatch", "memo.restore", "memo.emptyTrash", "memo.merge", "template.cache", "template.create.payload", "template.delete", "storage.backup", "storage.backups", "storage.restore", "sync.apply.merge-page-order", "sync.apply.deleted-notebook", "sync.apply.renamed-inbox", "sync.outbox", "sync.outbox.retry", "sync.outbox.recoverMemoUpdate", "sync.outbox.discard", "notebook.delete.empty-tree", "notebook.delete.not-empty"] }));