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(client): put the stack trace behind the background-error toast
Elian Doran071476f549ed
diff --git a/apps/client/src/services/toast.spec.ts b/apps/client/src/services/toast.spec.tsindex 9707930c21..646cc6c5f4 100644--- a/apps/client/src/services/toast.spec.ts+++ b/apps/client/src/services/toast.spec.ts@@ -9,7 +9,24 @@ vi.mock("../components/app_context.js", () => ({}}));-import toast, { removeToastFromStore, showError, showErrorForScriptNote, toasts } from "./toast.js";+const dialogInfo = vi.hoisted(() => vi.fn());+vi.mock("./dialog.js", () => ({ default: { info: dialogInfo } }));++import toast, { removeToastFromStore, showError, showErrorForScriptNote, showUnhandledError, toasts } from "./toast.js";++/** Flattens the text of a JSX tree, so a test can assert on what a dialog body actually says. */+function collectText(node: any): string {+ if (node === null || node === undefined || typeof node === "boolean") {+ return "";+ }+ if (typeof node === "string" || typeof node === "number") {+ return String(node);+ }+ if (Array.isArray(node)) {+ return node.map(collectText).join("");+ }+ return collectText(node.props?.children);+}describe("toast store", () => {beforeEach(() => {@@ -126,6 +143,38 @@ describe("toast store", () => {expect(created?.buttons).toBeUndefined();});+ it("showUnhandledError keeps the stack behind a details dialog the user can copy", async () => {+ showUnhandledError("Note 'abc' doesn't exist.", "NotFoundError: Note 'abc' doesn't exist.\n at getNoteOrThrow");++ const created = toasts.value.find(t => t.id === "unhandled-error");+ expect(created).toMatchObject({+ icon: "bx bx-error-circle",+ message: "Note 'abc' doesn't exist.",+ messageMonospace: true,+ timeout: 20000+ });++ const dismissToast = vi.fn();+ expect(created?.buttons).toHaveLength(1);+ await created?.buttons?.[0].onClick({ dismissToast });++ // The notification gets out of the way before the dialog takes over.+ expect(dismissToast).toHaveBeenCalledOnce();+ expect(dialogInfo).toHaveBeenCalledOnce();++ const [ body, options ] = dialogInfo.mock.calls[0];+ expect(collectText(body)).toContain("at getNoteOrThrow");+ expect(options).toMatchObject({ size: "lg", copyToClipboardButton: true });+ });++ it("showUnhandledError offers no details button when the error carried no stack", () => {+ showUnhandledError("Unknown Error");++ const created = toasts.value.find(t => t.id === "unhandled-error");+ expect(created?.message).toBe("Unknown Error");+ expect(created?.buttons).toBeUndefined();+ });+it("showErrorForScriptNote renders the message monospace when requested", () => {showErrorForScriptNote("scriptNote2", "api.logg is not a function", { monospace: true });diff --git a/apps/client/src/services/toast.ts b/apps/client/src/services/toast.tsxsimilarity index 80%rename from apps/client/src/services/toast.tsrename to apps/client/src/services/toast.tsxindex ed62d5937e..e8d8664767 100644--- a/apps/client/src/services/toast.ts+++ b/apps/client/src/services/toast.tsx@@ -114,19 +114,42 @@ export function showErrorForScriptNote(noteId: string, message: string, opts?: {/*** Surfaces a backend failure that no request was waiting on — a background task that threw, and would- * otherwise be visible only in the log. The backend keeps running, so this informs rather than alarms.+ * otherwise be visible only in the log. The backend keeps running, so this informs rather than alarms:+ * the message identifies what broke, and the stack trace — the part that actually makes a bug report+ * useful, and the part no user wants filling their screen — waits behind a details step, as the text+ * editor's crash notification does with its crash log.** Shown under a fixed id so that a task failing repeatedly refreshes one toast instead of stacking a* column of identical ones.*/-export function showUnhandledError(message: string) {+export function showUnhandledError(message: string, stack?: string) {showPersistent({id: "unhandled-error",- title: t("toast.unhandled-error"),+ title: t("toast.unhandled-error.title"),icon: "bx bx-error-circle",message,// Raw error strings are shown verbatim, so render them monospace.messageMonospace: true,+ buttons: stack ? [ {+ text: t("toast.unhandled-error.details-button"),+ onClick: async ({ dismissToast }) => {+ dismissToast();+ // Imported here rather than at the top of the module: toasts are pulled in by the app+ // context itself, and a static dependency on the dialog service would both close a cycle+ // through it and drag the modal machinery into everything that merely shows a toast.+ const dialog = (await import("./dialog.js")).default;++ dialog.info(<>+ <p>{t("toast.unhandled-error.details-intro")}</p>+ <h3>{t("toast.unhandled-error.details-title")}</h3>+ <pre><code>{stack}</code></pre>+ </>, {+ title: t("toast.unhandled-error.title"),+ size: "lg",+ copyToClipboardButton: true+ });+ }+ } ] : undefined,timeout: 20_000});}diff --git a/apps/client/src/services/ws.spec.ts b/apps/client/src/services/ws.spec.tsindex 616baae0c2..4f59bba1cc 100644--- a/apps/client/src/services/ws.spec.ts+++ b/apps/client/src/services/ws.spec.ts@@ -94,8 +94,8 @@ describe("dispatchMessage", () => {await ws.dispatchMessage({ type: "toast", message: "hi", timeout: 5 } as any);expect(toast.showMessage).toHaveBeenCalledWith("hi", 5);- await ws.dispatchMessage({ type: "unhandled-error", message: "Note 'abc' doesn't exist." } as any);- expect(showUnhandledError).toHaveBeenCalledWith("Note 'abc' doesn't exist.");+ await ws.dispatchMessage({ type: "unhandled-error", message: "Note 'abc' doesn't exist.", stack: "at getNoteOrThrow" } as any);+ expect(showUnhandledError).toHaveBeenCalledWith("Note 'abc' doesn't exist.", "at getNoteOrThrow");});it("execute-script resolves the origin entity from froca when an id is present", async () => {diff --git a/apps/client/src/services/ws.ts b/apps/client/src/services/ws.tsindex affe29a5a6..2bec415a17 100644--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@ -106,7 +106,7 @@ export async function dispatchMessage(message: WebSocketMessage) {} else if (messageType === "toast") {toastService.showMessage(msg.message, msg.timeout);} else if (messageType === "unhandled-error") {- showUnhandledError(msg.message);+ showUnhandledError(msg.message, msg.stack);} else if (messageType === "execute-script") {const originEntity = msg.originEntityId ? await froca.getNote(msg.originEntityId) : null;diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 1040fa15da..3f5c2969b5 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -46,7 +46,12 @@"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": "The script note failed to run",- "unhandled-error": "A background task failed"+ "unhandled-error": {+ "title": "A background task failed",+ "details-button": "View more details...",+ "details-intro": "The application is still running and your notes are unaffected. If this keeps happening, consider reporting it on GitHub by pasting the information below.",+ "details-title": "Technical information"+ }},"add_link": {"add_link": "Add link",diff --git a/apps/client/src/widgets/dialogs/info.css b/apps/client/src/widgets/dialogs/info.cssindex e1ee89affd..7f063fa169 100644--- a/apps/client/src/widgets/dialogs/info.css+++ b/apps/client/src/widgets/dialogs/info.css@@ -7,5 +7,11 @@pre {font-size: 0.75em;++ /* Crash logs and stack traces are made of long unbreakable lines — absolute paths, minified+ offsets — and a deep stack runs to dozens of them. Scroll both axes within the dialog so the+ technical detail stays a dialog instead of stretching into an unusable page. */+ max-height: 50vh;+ overflow: auto;}}diff --git a/apps/server/src/services/process_errors.spec.ts b/apps/server/src/services/process_errors.spec.tsindex dd883022ad..92a9eab483 100644--- a/apps/server/src/services/process_errors.spec.ts+++ b/apps/server/src/services/process_errors.spec.ts@@ -93,11 +93,12 @@ describe("reportProcessError", () => {markAppReady();reportProcessError(UNCAUGHT_EXCEPTION, new Error("Note 'XvA0rKdu1238' doesn't exist."));- // no second crash, and the message reaches the user without the stack trace+ // no second crash, and the failure reaches the user with the stack for a bug reportexpect(crashMock).toHaveBeenCalledOnce();expect(sendMessageToAllClientsMock).toHaveBeenCalledWith({type: "unhandled-error",- message: "Note 'XvA0rKdu1238' doesn't exist."+ message: "Note 'XvA0rKdu1238' doesn't exist.",+ stack: expect.stringContaining("Note 'XvA0rKdu1238' doesn't exist.")});expect(getLogMock.error).toHaveBeenCalledTimes(2);expect(getLogMock.error.mock.calls[1][0]).toContain("Note 'XvA0rKdu1238' doesn't exist.");@@ -123,9 +124,11 @@ describe("reportProcessError", () => {expect(() => reportProcessError(UNHANDLED_REJECTION, "just a string")).not.toThrow();+ // a thrown string carries no stack, so the client gets nothing to put behind the details stepexpect(sendMessageToAllClientsMock).toHaveBeenCalledWith({type: "unhandled-error",- message: "just a string"+ message: "just a string",+ stack: undefined});});diff --git a/apps/server/src/services/process_errors.ts b/apps/server/src/services/process_errors.tsindex 6240568d1a..e05c80c479 100644--- a/apps/server/src/services/process_errors.ts+++ b/apps/server/src/services/process_errors.ts@@ -99,9 +99,9 @@ export function reportProcessError(kind: ProcessErrorKind, error: unknown) {return;}- // Only the message reaches the UI: a stack trace against a bundled build tells the user nothing- // they can act on, and the log — which is what they attach to a bug report — already has it.- ws.sendMessageToAllClients({ type: "unhandled-error", message });+ // The stack goes along for the user to copy into a bug report; the client keeps it behind a+ // details step so the notification itself stays readable.+ ws.sendMessageToAllClients({ type: "unhandled-error", message, stack });} catch (e: unknown) {// This is the handler of last resort, so a throw from inside it has nowhere left to go and would// terminate the process with an error about the error. Fall back to the console, and keep adiff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.tsindex 13cd2dfa64..f21bac77a4 100644--- a/packages/commons/src/lib/ws_api.ts+++ b/packages/commons/src/lib/ws_api.ts@@ -173,6 +173,12 @@ export type WebSocketMessage = AllTaskDefinitions | {* would otherwise be invisible outside the log.*/type: "unhandled-error";- /** The error message alone. The stack trace stays in the backend log rather than in the UI. */+ /** The error message, shown directly in the notification. */message: string;+ /**+ * The stack trace, kept behind a "view more details" step rather than shown up front: it is what+ * makes a bug report actionable, and nothing the user is expected to read. Absent when the thrown+ * value carried no stack.+ */+ stack?: string;}