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(scripting): roll back a failed script run and toast only its own failures
Claude3731661dad0d
diff --git a/apps/client/src/services/backend_scripting.spec.ts b/apps/client/src/services/backend_scripting.spec.tsindex 17a925294e..3d024ad8c0 100644--- a/apps/client/src/services/backend_scripting.spec.ts+++ b/apps/client/src/services/backend_scripting.spec.ts@@ -28,14 +28,11 @@ describe("readScriptFailure", () => {.toEqual({ message: "boom", noteId: "child1" });});- it("answers without a note where the server named none", () => {- expect(readScriptFailure(responseBody({ message: "boom" }))).toEqual({ message: "boom" });- });-- it("falls back to what it was given", () => {- expect(readScriptFailure("not json at all")).toEqual({ message: "not json at all" });- expect(readScriptFailure(new Error("thrown"))).toEqual({ message: "thrown" });- expect(readScriptFailure(undefined)).toEqual({ message: "undefined" });+ it("answers nothing for a response that is not a script failure", () => {+ expect(readScriptFailure(responseBody({ message: "Note 'x' doesn't exist." }))).toBeUndefined();+ expect(readScriptFailure("not json at all")).toBeUndefined();+ expect(readScriptFailure(new Error("thrown"))).toBeUndefined();+ expect(readScriptFailure(undefined)).toBeUndefined();});});@@ -74,4 +71,14 @@ describe("runBackendScript", () => {expect(mocks.showErrorForScriptNote).toHaveBeenCalledWith("childModule", "boom", { monospace: true });});++ // `server.ts` has already reported a failure that is not the route's script failure, such as a+ // 404 for a deleted note or a dropped connection.+ it("adds no scripting error to a failure the request reported itself", async () => {+ mocks.post.mockRejectedValue(responseBody({ message: "Note 'gone' doesn't exist." }));++ await expect(runBackendScript("gone")).rejects.toBeDefined();++ expect(mocks.showErrorForScriptNote).not.toHaveBeenCalled();+ });});diff --git a/apps/client/src/services/backend_scripting.ts b/apps/client/src/services/backend_scripting.tsindex 6b481eb9af..2f430a604f 100644--- a/apps/client/src/services/backend_scripting.ts+++ b/apps/client/src/services/backend_scripting.ts@@ -67,39 +67,43 @@ export function showBackendScriptingDisabledToast(noteId: string) {* Runs a backend script note, reporting a failure as a scripting error rather than as a request* that went wrong.*- * The generic report names a status code and a URL, which say where the failure was noticed rather- * than what a script author did — and the toast raised here shows the note itself, so it can be- * opened from the failure. Rethrows, so a caller can still tell the run did not happen.+ * The toast names the failing note, so it can be opened from the failure. Rethrows, so a caller can+ * still tell the run did not happen.*/export async function runBackendScript(noteId: string): Promise<void> {try {await server.postWithSilentInternalServerError(`script/run/${noteId}`);} catch (e) {+ // Anything other than the route's own script failure was already reported by `server.ts`.const failure = readScriptFailure(e);- // The note the server named is the one that failed, which is a child module note where one- // of those did; the note asked for is the fallback where it named none.- showErrorForScriptNote(failure.noteId ?? noteId, failure.message, { monospace: true });+ if (failure) {+ showErrorForScriptNote(failure.noteId, failure.message, { monospace: true });+ }throw e;}}-/** What the server said failed, as it answers it — parts rather than one sentence to unpick. */-export function readScriptFailure(e: unknown): ScriptFailure {+/**+ * Reads the script failure `POST script/run` answers with, or `undefined` for any other failure.+ *+ * The route always names a note in a script failure, which tells it apart from the `{ message }`+ * body of an error raised before the script ran.+ */+export function readScriptFailure(e: unknown): Required<ScriptFailure> | undefined {if (typeof e !== "string") {- return { message: e instanceof Error ? e.message : String(e) };+ return undefined;}try {- const parsed = JSON.parse(e);- if (parsed && typeof parsed.message === "string") {- return {- message: parsed.message,- ...(typeof parsed.noteId === "string" ? { noteId: parsed.noteId } : {})- };+ const parsed: unknown = JSON.parse(e);+ if (parsed && typeof parsed === "object"+ && "message" in parsed && typeof parsed.message === "string"+ && "noteId" in parsed && typeof parsed.noteId === "string") {+ return { message: parsed.message, noteId: parsed.noteId };}} catch {- // Not JSON, so the body is the best the server said.+ // Not JSON, so not a script failure.}- return { message: e };+ return undefined;}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.htmlindex fe48d503dc..a5d9d3914d 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.html@@ -24,6 +24,11 @@<h2>Running backend scripts</h2><p>Backend scripts can be either run manually (via the Execute button onthe script page), or they can be triggered on certain events.</p>+<p>When a script run manually or from a launcher throws an error, Trilium+ shows a <em>Scripting error</em> notification with the error message and+ a link to the note that failed. If the error comes from a child note the+ script requires, the link points to that child note. Changes the script+ made to notes before the error are rolled back.</p><p>In addition, scripts can be run automatically when the server starts up,on a fixed time interval or when a certain event occurs (such as an attributebeing modified). For more information, see the dedicated <a class="reference-link"diff --git a/docs/User Guide/User Guide/Scripting/Backend scripts.md b/docs/User Guide/User Guide/Scripting/Backend scripts.mdindex a548262644..89b06e1fc3 100644--- a/docs/User Guide/User Guide/Scripting/Backend scripts.md+++ b/docs/User Guide/User Guide/Scripting/Backend scripts.md@@ -20,6 +20,8 @@ Create a new <a class="reference-link" href="../Note%20Types/Code.md">Code</a>Backend scripts can be either run manually (via the Execute button on the script page), or they can be triggered on certain events.+When a script run manually or from a launcher throws an error, Trilium shows a _Scripting error_ notification with the error message and a link to the note that failed. If the error comes from a child note the script requires, the link points to that child note. Changes the script made to notes before the error are rolled back.+In addition, scripts can be run automatically when the server starts up, on a fixed time interval or when a certain event occurs (such as an attribute being modified). For more information, see the dedicated <a class="reference-link" href="Backend%20scripts/Backend%20Events.md">Events</a> page.## Script APIdiff --git a/packages/trilium-core/src/routes/api/script.spec.ts b/packages/trilium-core/src/routes/api/script.spec.tsindex 81cdfedd38..a0fe6dc71e 100644--- a/packages/trilium-core/src/routes/api/script.spec.ts+++ b/packages/trilium-core/src/routes/api/script.spec.ts@@ -2,8 +2,10 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport attributeService from "../../services/attributes";import config from "../../services/config";+import { getLog } from "../../services/log";import { getPlatform } from "../../services/platform";import scriptService from "../../services/script";+import { getSql } from "../../services/sql/index";import { createTextNote } from "../../test/api_fixtures";import { CoreApiTester } from "../../test/api_tester";@@ -116,6 +118,36 @@ describe("Script API (core)", () => {expect(res.body.executionResult).toBe(123);expect(spy).toHaveBeenCalledOnce();});++ it("rolls back what a failing script wrote, and answers the failure in parts", async () => {+ const noteId = await createCodeNote("return 0;");+ const before = getSql().getValue<string>("SELECT title FROM notes WHERE noteId = ?", [noteId]);+ vi.spyOn(scriptService, "executeNote").mockImplementation(() => {+ getSql().execute("UPDATE notes SET title = 'written by the script' WHERE noteId = ?", [noteId]);+ throw new Error("boom");+ });+ const logError = vi.spyOn(getLog(), "error");++ const res = await api.post<{ message: string; noteId: string }>(`/api/script/run/${noteId}`);++ expect(res.status).toBe(500);+ expect(getSql().getValue("SELECT title FROM notes WHERE noteId = ?", [noteId])).toBe(before);+ expect(logError).toHaveBeenCalledWith(expect.stringContaining("boom"));+ expect(res.body).toEqual({ message: "boom", noteId });+ });++ it("answers a disabled backend as a failure of the note", async () => {+ const noteId = await createCodeNote("return 0;");+ config.Security.backendScriptingEnabled = false;+ try {+ const res = await api.post<{ message: string; noteId: string }>(`/api/script/run/${noteId}`);+ expect(res.status).toBe(500);+ expect(res.body.noteId).toBe(noteId);+ expect(res.body.message).toContain("backendScriptingEnabled");+ } finally {+ config.Security.backendScriptingEnabled = true;+ }+ });});describe("startup bundles", () => {diff --git a/packages/trilium-core/src/routes/api/script.ts b/packages/trilium-core/src/routes/api/script.tsindex 3a85d7112a..510bc48cd7 100644--- a/packages/trilium-core/src/routes/api/script.ts+++ b/packages/trilium-core/src/routes/api/script.ts@@ -4,6 +4,7 @@ import type { Request } from "../../http_interface";import becca from "../../becca/becca.js";import attributeService from "../../services/attributes.js";+import { getLog } from "../../services/log.js";import { getPlatform } from "../../services/platform.js";import scriptService, { type Bundle, describeScriptFailure } from "../../services/script.js";import syncService from "../../services/sync.js";@@ -48,16 +49,22 @@ async function exec(req: Request) {}function run(req: Request<{ noteId: string }>) {- assertScriptingEnabled();const note = becca.getNoteOrThrow(req.params.noteId);try {- return { executionResult: scriptService.executeNote(note, { originEntity: note }) };+ assertScriptingEnabled();+ // A nested `transactional()` is a savepoint, so a script that throws leaves nothing it+ // wrote behind even though the route returns rather than throws.+ const executionResult = getSql().transactional(+ () => scriptService.executeNote(note, { originEntity: note }));+ return { executionResult };} catch (e) {- // Answered in parts rather than as one sentence: the cause chain does not survive the- // response, and what the caller wants out of it — what failed, and which note — would- // otherwise have to be read back out of the text on the other side.- return [ 500, describeScriptFailure(e) ];+ const [ message, stack ] = safeExtractMessageAndStackFromError(e);+ getLog().error(`Script note ${note.noteId} failed: '${message}', stack: ${stack}`);++ // The client reads the failing note from the body, as the cause chain is not serialized.+ const failure = describeScriptFailure(e);+ return [ 500, { ...failure, noteId: failure.noteId ?? note.noteId } ];}}