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
feat(toast): clean up the script-error toast message
Elian Doran289a4b7cf400
diff --git a/apps/client/src/services/bundle.spec.ts b/apps/client/src/services/bundle.spec.tsindex 668e89889e..a23840ccbb 100644--- a/apps/client/src/services/bundle.spec.ts+++ b/apps/client/src/services/bundle.spec.ts@@ -44,7 +44,7 @@ describe("executeBundle / executeBundleWithoutErrorHandling", () => {it("executeBundle swallows errors and reports them via showErrorForScriptNote + logError", async () => {const id = buildNote({ title: "Throwing note" }).noteId;- const spy = vi.spyOn(toast, "showErrorForScriptNote").mockResolvedValue(undefined);+ const spy = vi.spyOn(toast, "showErrorForScriptNote").mockReturnValue(undefined);const bundle: Bundle = {script: `throw new Error("kaboom");`,html: "",@@ -122,7 +122,7 @@ describe("WidgetsByParent", () => {let errorSpy: ReturnType<typeof vi.spyOn>;beforeEach(() => {- errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockResolvedValue(undefined);+ errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockReturnValue(undefined);errorSpy.mockClear();});@@ -270,7 +270,7 @@ describe("getWidgetBundlesByParent (default export)", () => {it("reports a per-bundle error when executing a single bundle throws", async () => {const id = buildNote({ title: "Bad widget note" }).noteId;- const errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockResolvedValue(undefined);+ const errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockReturnValue(undefined);// executeBundleWithoutErrorHandling needs the note to resolve in froca; force the per-bundle// try/catch by making add() throw on a widget that has neither parent nor parentWidget while// also having a falsy _noteId is not enough — instead throw during execution by referencing@@ -331,7 +331,7 @@ function getBundle(script: string) {`try {`,`${script}`,`;`,- `} catch (e) { throw new Error(\"Load of script note \\\"Client\\\" (${id}) failed with: \" + e.message); }`,+ `} catch (e) { throw new Error(\"Load of script note \\\"Client\\\" (${id}) failed with: \" + e.message, { cause: e }); }`,`for (const exportKey in exports) module.exports[exportKey] = exports[exportKey];`,`return module.exports;`,`}).call({}, {}, apiContext.modules['${id}'], apiContext.require([]), apiContext.apis['${id}']));`,diff --git a/apps/client/src/services/bundle.ts b/apps/client/src/services/bundle.tsindex 8a9a9b65da..23400fe2c4 100644--- a/apps/client/src/services/bundle.ts+++ b/apps/client/src/services/bundle.ts@@ -50,7 +50,7 @@ export async function executeBundle(bundle: Bundle, originEntity?: Entity | nulltry {return await executeBundleWithoutErrorHandling(bundle, originEntity, $container);} catch (e: unknown) {- showErrorForScriptNote(bundle.noteId, t("toast.bundle-error.message", { message: getErrorMessage(e) }));+ showErrorForScriptNote(bundle.noteId, rootCauseMessage(e), { monospace: true });logError("Widget initialization failed: ", e);}}@@ -145,7 +145,7 @@ async function getWidgetBundlesByParent() {}} catch (e: any) {const noteId = bundle.noteId;- showErrorForScriptNote(noteId, t("toast.bundle-error.message", { message: e.message }));+ showErrorForScriptNote(noteId, rootCauseMessage(e), { monospace: true });logError("Widget initialization failed: ", e);continue;@@ -169,3 +169,19 @@ export default {executeStartupBundles,getWidgetBundlesByParent};++/**+ * The script bundler wraps each script note's thrown errors as+ * `Load of script note "<title>" (<noteId>) failed with: <inner>` and attaches the original error+ * as the `cause` (see the bundle template in trilium-core's `script.ts`). That prefix is useful in+ * backend logs but redundant in the UI, where the failing note is already shown as a reference link,+ * so we surface the underlying error instead — walking the `cause` chain to the bottom also unwraps+ * the nested errors produced when a `require()`d module fails.+ */+function rootCauseMessage(e: unknown): string {+ let error = e;+ while (error instanceof Error && error.cause !== undefined) {+ error = error.cause;+ }+ return error instanceof Error ? error.message : String(error);+}diff --git a/apps/client/src/services/toast.spec.ts b/apps/client/src/services/toast.spec.tsindex 284164452d..d07772d8f3 100644--- a/apps/client/src/services/toast.spec.ts+++ b/apps/client/src/services/toast.spec.ts@@ -1,7 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { buildNote } from "../test/easy-froca";-const openInNewTab = vi.fn();vi.mock("../components/app_context.js", () => ({default: {@@ -114,37 +112,27 @@ describe("toast store", () => {expect(toasts.value).toHaveLength(0);});- it("showErrorForScriptNote shows the script note as a reference link with a generic error icon", async () => {- const note = buildNote({ title: "My Script" });-- await showErrorForScriptNote(note.noteId, "it failed");+ it("showErrorForScriptNote shows the script note as a reference link with a generic error icon", () => {+ showErrorForScriptNote("scriptNote1", "it failed");- const created = toasts.value.find(t => t.id === `custom-widget-failure-${note.noteId}`);+ const created = toasts.value.find(t => t.id === "custom-widget-failure-scriptNote1");expect(created).toMatchObject({icon: "bx bx-error-circle",message: "it failed",timeout: 15000,// The script note is attached as a reference link instead of a bespoke open-note button.- noteIds: [ note.noteId ]+ noteIds: [ "scriptNote1" ]});expect(created?.buttons).toBeUndefined();});- it("showErrorForScriptNote still renders when the note cannot be found", async () => {- const froca = (await import("./froca.js")).default;- const original = froca.getNote;- froca.getNote = vi.fn(async () => null) as typeof froca.getNote;-- try {- await showErrorForScriptNote("missing-note", "nope");- const created = toasts.value.find(t => t.id === "custom-widget-failure-missing-note");- expect(created).toMatchObject({- icon: "bx bx-error-circle",- message: "nope",- noteIds: [ "missing-note" ]- });- } finally {- froca.getNote = original;- }+ it("showErrorForScriptNote renders the message monospace when requested", () => {+ showErrorForScriptNote("scriptNote2", "api.logg is not a function", { monospace: true });++ const created = toasts.value.find(t => t.id === "custom-widget-failure-scriptNote2");+ expect(created).toMatchObject({+ message: "api.logg is not a function",+ messageMonospace: true+ });});});diff --git a/apps/client/src/services/toast.ts b/apps/client/src/services/toast.tsindex eb24e11973..b9a7b9e949 100644--- a/apps/client/src/services/toast.ts+++ b/apps/client/src/services/toast.ts@@ -1,6 +1,5 @@import { signal } from "@preact/signals";-import froca from "./froca.js";import { t } from "./i18n.js";import utils, { randomString } from "./utils.js";@@ -9,6 +8,8 @@ export interface ToastOptions {icon: string;title?: string;message: string;+ /** When `true`, the {@link message} is rendered in a monospace font — e.g. a raw error string. */+ messageMonospace?: boolean;timeout?: number;progress?: number;/**@@ -86,14 +87,14 @@ function showErrorTitleAndMessage(title: string, message: string, timeout = 1000});}-export async function showErrorForScriptNote(noteId: string, message: string) {- const note = await froca.getNote(noteId, true);-+export function showErrorForScriptNote(noteId: string, message: string, opts?: { monospace?: boolean }) {showPersistent({id: `custom-widget-failure-${noteId}`,- title: t("toast.scripting-error", { title: note?.title ?? "" }),+ title: t("toast.scripting-error"),icon: "bx bx-error-circle",message,+ // Raw error strings are shown verbatim, so render them monospace.+ messageMonospace: opts?.monospace,// The script note is shown as a reference link (icon + title, click to navigate) rather// than a bespoke "open note" button; ctrl/middle-click still opens it in a new tab.noteIds: [ noteId ],diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex de032a85e1..9082daed1d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -45,7 +45,7 @@},"widget-missing-parent": "Custom widget does not have mandatory '{{property}}' property defined.\n\nIf this script is meant to be run without a UI element, use '#run=frontendStartup' instead.","open-script-note": "Open script note",- "scripting-error": "Custom script error: {{title}}"+ "scripting-error": "The script note failed to run"},"add_link": {"add_link": "Add link",diff --git a/apps/client/src/widgets/Toast.css b/apps/client/src/widgets/Toast.cssindex 684b09270a..c23965f93d 100644--- a/apps/client/src/widgets/Toast.css+++ b/apps/client/src/widgets/Toast.css@@ -35,6 +35,12 @@overflow: hidden;}+.toast-body.monospace {+ font-family: var(--monospace-font-family);+ font-size: var(--monospace-font-size);+ overflow-wrap: anywhere;+}+.toast.no-title .toast-main-row {display: flex;flex-direction: row;diff --git a/apps/client/src/widgets/Toast.tsx b/apps/client/src/widgets/Toast.tsxindex 4fd61bf1b1..6247733c64 100644--- a/apps/client/src/widgets/Toast.tsx+++ b/apps/client/src/widgets/Toast.tsx@@ -16,7 +16,7 @@ export default function ToastContainer() {);}-function Toast({ id, title, timeout, progress, message, icon, buttons, dismissible, wide, noteIds, notesHeading }: ToastOptionsWithRequiredId) {+function Toast({ id, title, timeout, progress, message, messageMonospace, icon, buttons, dismissible, wide, noteIds, notesHeading }: ToastOptionsWithRequiredId) {// Autohide.useEffect(() => {if (!timeout || timeout <= 0) return;@@ -53,12 +53,12 @@ function Toast({ id, title, timeout, progress, message, icon, buttons, dismissib</strong>{closeButton}</div>- <div className="toast-body">{message}</div>+ <div className={clsx("toast-body", messageMonospace && "monospace")}>{message}</div></>) : (<div class="toast-main-row"><div class="toast-icon">{toastIcon}</div>- <div className="toast-body">{message}</div>+ <div className={clsx("toast-body", messageMonospace && "monospace")}>{message}</div>{closeButton && <div class="toast-close">{closeButton}</div>}</div>)}diff --git a/packages/trilium-core/src/services/script.ts b/packages/trilium-core/src/services/script.tsindex ceb97cb59e..5421209bd6 100644--- a/packages/trilium-core/src/services/script.ts+++ b/packages/trilium-core/src/services/script.ts@@ -247,7 +247,7 @@ apiContext.modules['${note.noteId}'] = { exports: {} };${root ? "return " : ""}${isFrontend ? "await" : ""} ((${isFrontend ? "async" : ""} function(exports, module, require, api${modules.length > 0 ? ", " : ""}${modules.map((child) => sanitizeVariableName(child.title)).join(", ")}) {try {${overrideContent || scriptContent};-} catch (e) { throw new Error("Load of script note \\"${note.title}\\" (${note.noteId}) failed with: " + e.message); }+} catch (e) { throw new Error("Load of script note \\"${note.title}\\" (${note.noteId}) failed with: " + e.message, { cause: e }); }for (const exportKey in exports) module.exports[exportKey] = exports[exportKey];return module.exports;}).call({}, {}, apiContext.modules['${note.noteId}'], apiContext.require(${JSON.stringify(moduleNoteIds)}), apiContext.apis['${note.noteId}']${modules.length > 0 ? ", " : ""}${modules.map((mod) => `apiContext.modules['${mod.noteId}'].exports`).join(", ")}));