Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(notes): tell the task system when a batch delete fails
Elian Doran036249a85a96
diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 7a46b65cd6..daa40aa7b5 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -333,7 +333,8 @@"notes": {"new-note": "New note","duplicate-note-suffix": "(dup)",- "duplicate-note-title": "{{- noteTitle }} {{ duplicateNoteSuffix }}"+ "duplicate-note-title": "{{- noteTitle }} {{ duplicateNoteSuffix }}",+ "delete-notes-failed": "Deleting notes failed: {{- message}}"},"note_conversion": {"revision_before_markdown": "Before conversion to Markdown",diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.tsindex 253bab1840..8e4ec2864d 100644--- a/packages/trilium-core/src/routes/api/notes.spec.ts+++ b/packages/trilium-core/src/routes/api/notes.spec.ts@@ -1,6 +1,7 @@import { beforeAll, describe, expect, it, vi } from "vitest";import becca from "../../becca/becca";+import eraseService from "../../services/erase";import noteService from "../../services/notes";import { getSql } from "../../services/sql/index";import ws from "../../services/ws";@@ -440,6 +441,45 @@ describe("Notes API (core)", () => {}});+ it("tells the task system when it fails, and keeps the selection", async () => {+ const { noteId, branchId } = await createTextNote(api, { title: "Delete that fails" });+ const messages = vi.spyOn(ws, "sendMessageToAllClients").mockImplementation(() => {});+ const erase = vi.spyOn(eraseService, "eraseNotesWithDeleteIds")+ .mockImplementation(() => {+ throw new Error("erase blew up");+ });++ try {+ const res = await api.post("/api/delete-notes", {+ body: {+ branchIdsToDelete: [ branchId ],+ eraseNotes: true,+ taskId: "test-batch-failure"+ }+ });+ expect(res.status).toBe(500);++ const sent = messages.mock.calls.map(([ message ]) => message);++ // Without a terminal message the client's progress toast stays up, and it has no+ // close button of its own.+ expect(sent.filter((message) => message.type === "taskError")).toEqual([+ expect.objectContaining({+ taskId: "test-batch-failure",+ taskType: "deleteNotes",+ message: expect.stringContaining("erase blew up")+ })+ ]);+ expect(sent.filter((message) => message.type === "taskSucceeded")).toEqual([]);++ // The throw rolls the transaction back, so nothing of the selection is gone.+ expect(noteIsDeleted(noteId)).toBe(0);+ } finally {+ erase.mockRestore();+ messages.mockRestore();+ }+ });+it("400s without a taskId or a branch id array", async () => {const { noteId, branchId } = await createTextNote(api, { title: "Needs a task id" });diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.tsindex f7760287ba..1101a9dadb 100644--- a/packages/trilium-core/src/routes/api/notes.ts+++ b/packages/trilium-core/src/routes/api/notes.ts@@ -1,4 +1,6 @@import type { AttributeRow, CreateChildrenResponse, DeleteNotesPreview, MetadataResponse } from "@triliumnext/commons";+import { t } from "i18next";+import type { Request } from "../../http_interface";import blobService from "../../services/blob";@@ -455,41 +457,52 @@ function deleteNotes(req: Request) {taskContext.setTotalCount(totalCount);}- for (const branchId of branchIdsToDelete) {- const branch = becca.getBranch(branchId);+ try {+ for (const branchId of branchIdsToDelete) {+ const branch = becca.getBranch(branchId);- if (!branch) {- // Either a stale id, or a branch an earlier one of the selection took down with- // its subtree.- getLog().info(`Branch '${branchId}' was not found, skipping its deletion.`);- continue;- }+ if (!branch) {+ // Either a stale id, or a branch an earlier one of the selection took down with+ // its subtree.+ getLog().info(`Branch '${branchId}' was not found, skipping its deletion.`);+ continue;+ }- const deleteId = randomString(10);+ const deleteId = randomString(10);- // Erasing one branch would leave the note's other clones pointing at erased content, so- // eraseNotes deletes the note everywhere it hangs.- if (deleteAllClones || eraseNotes) {- branch.getNote().deleteNote(deleteId, taskContext);- } else {- branch.deleteBranch(deleteId, taskContext);- }+ // Erasing one branch would leave the note's other clones pointing at erased content, so+ // eraseNotes deletes the note everywhere it hangs.+ if (deleteAllClones || eraseNotes) {+ branch.getNote().deleteNote(deleteId, taskContext);+ } else {+ branch.deleteBranch(deleteId, taskContext);+ }- if (eraseNotes) {- taskContext.scheduleErase(deleteId);+ if (eraseNotes) {+ taskContext.scheduleErase(deleteId);+ }}- }- const deleteIdsToErase = taskContext.takeScheduledErases();+ const deleteIdsToErase = taskContext.takeScheduledErases();- if (deleteIdsToErase.length > 0) {- // Erasing is bulk SQL over the whole batch with no per-note step to count, so it reports a- // phase rather than letting the bar sit at its last value.- taskContext.reportPhase("erasing");- eraseService.eraseNotesWithDeleteIds(deleteIdsToErase);- }+ if (deleteIdsToErase.length > 0) {+ // Erasing is bulk SQL over the whole batch with no per-note step to count, so it+ // reports a phase rather than letting the bar sit at its last value.+ taskContext.reportPhase("erasing");+ eraseService.eraseNotesWithDeleteIds(deleteIdsToErase);+ }- taskContext.taskSucceeded(null);+ taskContext.taskSucceeded(null);+ } catch (e: unknown) {+ // The progress toast has no close button, so a failure the task system never hears about+ // leaves it on screen until the page is reloaded. Rethrown rather than answered with a+ // status, because the surrounding transaction rolls back on the throw — returning here+ // would commit a half-deleted selection.+ const message = e instanceof Error ? e.message : String(e);+ getLog().error(`Deleting notes failed: ${message}`);+ taskContext.reportError(t("notes.delete-notes-failed", { message }));+ throw e;+ }}function forceSaveRevision(req: Request<{ noteId: string }>) {