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(server): keep a background failure from killing the app
Elian Dorana36d963c3904
diff --git a/apps/client/src/services/toast.ts b/apps/client/src/services/toast.tsindex 003da7daff..ed62d5937e 100644--- a/apps/client/src/services/toast.ts+++ b/apps/client/src/services/toast.ts@@ -112,6 +112,25 @@ 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.+ *+ * 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) {+ showPersistent({+ id: "unhandled-error",+ title: t("toast.unhandled-error"),+ icon: "bx bx-error-circle",+ message,+ // Raw error strings are shown verbatim, so render them monospace.+ messageMonospace: true,+ timeout: 20_000+ });+}+//#region Toast storeexport const toasts = signal<ToastOptionsWithRequiredId[]>([]);diff --git a/apps/client/src/services/ws.spec.ts b/apps/client/src/services/ws.spec.tsindex f70ca9dfeb..616baae0c2 100644--- a/apps/client/src/services/ws.spec.ts+++ b/apps/client/src/services/ws.spec.ts@@ -11,6 +11,7 @@ const toast = vi.hoisted(() => ({showPersistent: vi.fn(),closePersistent: vi.fn()}));+const showUnhandledError = vi.hoisted(() => vi.fn());const bundle = vi.hoisted(() => ({ getAndExecuteBundle: vi.fn() }));const appCtx = vi.hoisted(() => ({ triggerEvent: vi.fn() }));const frocaUpdater = vi.hoisted(() => ({ processEntityChanges: vi.fn(async () => {}) }));@@ -20,7 +21,7 @@ const utilsCtrl = vi.hoisted(() => ({}));const optionsCtrl = vi.hoisted(() => ({ is: vi.fn(() => false) }));-vi.mock("./toast.js", () => ({ default: toast }));+vi.mock("./toast.js", () => ({ default: toast, showUnhandledError }));vi.mock("./bundle.js", () => ({ default: bundle }));vi.mock("../components/app_context.js", () => ({ default: appCtx }));vi.mock("./froca_updater.js", () => ({ default: frocaUpdater }));@@ -92,6 +93,9 @@ 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.");});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 d54f07abff..affe29a5a6 100644--- a/apps/client/src/services/ws.ts+++ b/apps/client/src/services/ws.ts@@ -8,7 +8,7 @@ import frocaUpdater from "./froca_updater.js";import { t } from "./i18n.js";import options from "./options.js";import server from "./server.js";-import toastService from "./toast.js";+import toastService, { showUnhandledError } from "./toast.js";import utils, { isPreAuthScreen } from "./utils.js";type MessageHandler = (message: WebSocketMessage) => void;@@ -105,6 +105,8 @@ export async function dispatchMessage(message: WebSocketMessage) {appContext.triggerEvent("apiLogMessages", { noteId: msg.noteId, messages: msg.messages });} else if (messageType === "toast") {toastService.showMessage(msg.message, msg.timeout);+ } else if (messageType === "unhandled-error") {+ showUnhandledError(msg.message);} 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 e081e67d11..1040fa15da 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -45,7 +45,8 @@},"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"+ "scripting-error": "The script note failed to run",+ "unhandled-error": "A background task failed"},"add_link": {"add_link": "Add link",diff --git a/apps/client/src/widgets/Toast.tsx b/apps/client/src/widgets/Toast.tsxindex a2bc6f4c1e..d9a9812c8b 100644--- a/apps/client/src/widgets/Toast.tsx+++ b/apps/client/src/widgets/Toast.tsx@@ -17,12 +17,15 @@ export default function ToastContainer() {}function Toast({ id, title, timeout, progress, message, messageMonospace, icon, buttons, dismissible, wide, notes, notesHeading }: ToastOptionsWithRequiredId) {- // Autohide.+ // Autohide. The countdown restarts whenever the message changes, so a persistent toast reused for a+ // repeating event (the same id showing a newer error) stays up for its full duration from the latest+ // update rather than expiring on the first one's deadline. Progress toasts are unaffected: they carry+ // no timeout while updating, and only gain one when they settle into their final message.useEffect(() => {if (!timeout || timeout <= 0) return;const timerId = setTimeout(() => removeToastFromStore(id), timeout);return () => clearTimeout(timerId);- }, [ id, timeout ]);+ }, [ id, timeout, message ]);function dismissToast() {removeToastFromStore(id);diff --git a/apps/server/src/services/process_errors.spec.ts b/apps/server/src/services/process_errors.spec.tsnew file mode 100644index 0000000000..dd883022ad--- /dev/null+++ b/apps/server/src/services/process_errors.spec.ts@@ -0,0 +1,143 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const { getLogMock, crashMock, sendMessageToAllClientsMock } = vi.hoisted(() => ({+ getLogMock: { error: vi.fn() },+ crashMock: vi.fn(),+ sendMessageToAllClientsMock: vi.fn()+}));++vi.mock("@triliumnext/core", async () => {+ // the real extractor, so the tests cover how non-Error throws actually get rendered+ const { safeExtractMessageAndStackFromError } = await vi.importActual<typeof import("@triliumnext/core/src/services/utils/index.js")>(+ "@triliumnext/core/src/services/utils/index.js"+ );++ return {+ getLog: () => getLogMock,+ getPlatform: () => ({ crash: crashMock }),+ utils: { safeExtractMessageAndStackFromError },+ ws: { sendMessageToAllClients: sendMessageToAllClientsMock }+ };+});++import { createErrorThrottle } from "./process_errors.js";++/**+ * Both the readiness flag and the throttle are module-level state, so each case gets its own instance of+ * the module rather than inheriting whatever the previous one left behind.+ */+async function freshModule() {+ vi.resetModules();+ return await import("./process_errors.js");+}++describe("createErrorThrottle", () => {+ const options = { maxPerMessage: 3, windowMs: 60_000, maxTrackedMessages: 3 };++ it("reports up to the cap, flags the last one, then goes quiet until the window rolls over", () => {+ const throttle = createErrorThrottle(options);++ expect(throttle.check("boom", 0)).toEqual({ report: true, lastBeforeSuppression: false });+ expect(throttle.check("boom", 10)).toEqual({ report: true, lastBeforeSuppression: false });+ expect(throttle.check("boom", 20)).toEqual({ report: true, lastBeforeSuppression: true });+ expect(throttle.check("boom", 30)).toEqual({ report: false, lastBeforeSuppression: false });+ expect(throttle.check("boom", 59_999)).toEqual({ report: false, lastBeforeSuppression: false });++ // a fresh window starts once the old one has fully elapsed+ expect(throttle.check("boom", 60_000)).toEqual({ report: true, lastBeforeSuppression: false });+ });++ it("throttles each message independently and flags the last one when the cap is 1", () => {+ const throttle = createErrorThrottle(options);+ const single = createErrorThrottle({ ...options, maxPerMessage: 1 });++ throttle.check("first", 0);+ throttle.check("first", 1);+ throttle.check("first", 2);+ expect(throttle.check("first", 3).report).toBe(false);+ expect(throttle.check("second", 3).report).toBe(true);++ expect(single.check("only-once", 0)).toEqual({ report: true, lastBeforeSuppression: true });+ expect(single.check("only-once", 1).report).toBe(false);+ });++ it("drops its bookkeeping once too many distinct messages are tracked", () => {+ const throttle = createErrorThrottle(options);++ // Messages embedding entity ids are all distinct, so the table would otherwise grow without bound.+ throttle.check("Note 'a' doesn't exist.", 0);+ throttle.check("Note 'b' doesn't exist.", 0);+ throttle.check("Note 'c' doesn't exist.", 0);++ // The fourth distinct message clears the table, which also resets the earlier windows.+ expect(throttle.check("Note 'd' doesn't exist.", 0).report).toBe(true);+ expect(throttle.check("Note 'a' doesn't exist.", 0)).toEqual({ report: true, lastBeforeSuppression: false });+ });+});++describe("reportProcessError", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.spyOn(console, "error").mockImplementation(() => {});+ });++ it("crashes while the app is still starting, and only informs once it is up", async () => {+ const { markAppReady, reportProcessError, UNCAUGHT_EXCEPTION } = await freshModule();++ reportProcessError(UNCAUGHT_EXCEPTION, new Error("db is locked"));++ expect(crashMock).toHaveBeenCalledOnce();+ expect(crashMock.mock.calls[0][0]).toContain("Uncaught exception: db is locked");+ expect(sendMessageToAllClientsMock).not.toHaveBeenCalled();++ markAppReady();+ reportProcessError(UNCAUGHT_EXCEPTION, new Error("Note 'XvA0rKdu1238' doesn't exist."));++ // no second crash, and the message reaches the user without the stack trace+ expect(crashMock).toHaveBeenCalledOnce();+ expect(sendMessageToAllClientsMock).toHaveBeenCalledWith({+ type: "unhandled-error",+ message: "Note 'XvA0rKdu1238' doesn't exist."+ });+ expect(getLogMock.error).toHaveBeenCalledTimes(2);+ expect(getLogMock.error.mock.calls[1][0]).toContain("Note 'XvA0rKdu1238' doesn't exist.");+ });++ it("keeps a startup unhandled rejection non-fatal, as it has always been", async () => {+ const { reportProcessError, UNHANDLED_REJECTION } = await freshModule();++ reportProcessError(UNHANDLED_REJECTION, new Error("some floating promise"));++ // logged, but neither fatal (the app still boots) nor surfaced (nobody is connected yet)+ expect(getLogMock.error).toHaveBeenCalledOnce();+ expect(crashMock).not.toHaveBeenCalled();+ expect(sendMessageToAllClientsMock).not.toHaveBeenCalled();+ });++ it("survives a thrown non-Error and a logger that is not usable yet", async () => {+ const { markAppReady, reportProcessError, UNHANDLED_REJECTION } = await freshModule();+ markAppReady();+ getLogMock.error.mockImplementationOnce(() => {+ throw new Error("log service not initialized");+ });++ expect(() => reportProcessError(UNHANDLED_REJECTION, "just a string")).not.toThrow();++ expect(sendMessageToAllClientsMock).toHaveBeenCalledWith({+ type: "unhandled-error",+ message: "just a string"+ });+ });++ it("stops reporting a message that keeps failing, warning once that it will", async () => {+ const { markAppReady, reportProcessError, UNCAUGHT_EXCEPTION } = await freshModule();+ markAppReady();++ for (let i = 0; i < 10; i++) {+ reportProcessError(UNCAUGHT_EXCEPTION, new Error("every second"));+ }++ expect(sendMessageToAllClientsMock).toHaveBeenCalledTimes(3);+ expect(getLogMock.error.mock.calls[2][0]).toContain("will not be reported");+ });+});diff --git a/apps/server/src/services/process_errors.ts b/apps/server/src/services/process_errors.tsnew file mode 100644index 0000000000..6240568d1a--- /dev/null+++ b/apps/server/src/services/process_errors.ts@@ -0,0 +1,172 @@+import { getLog, getPlatform, utils, ws } from "@triliumnext/core";++/** Occurrences of the same message beyond this count within {@link THROTTLE_WINDOW_MS} are dropped. */+const MAX_REPORTS_PER_MESSAGE = 3;+const THROTTLE_WINDOW_MS = 60_000;+/**+ * Error messages routinely embed entity ids (`Note 'XvA0rKdu1238' doesn't exist.`), so a storm can produce+ * an unbounded number of distinct keys. Past this many tracked messages the whole table is dropped:+ * throttling is a flood guard, not an audit trail, and restarting the windows costs at most a few extra+ * log lines.+ */+const MAX_TRACKED_MESSAGES = 100;++/** A throw nothing caught. During startup it means the application never came up, so it stays fatal. */+export const UNCAUGHT_EXCEPTION = { label: "Uncaught exception", fatalDuringStartup: true };+/**+ * A rejected promise nobody awaited. Node's default is to promote these to uncaught exceptions, but+ * Trilium has always logged and carried on instead — a floating promise is usually incidental to whatever+ * the process is really doing, and the ones raised during startup have never prevented a working boot.+ * Keeping them non-fatal preserves that; the new part is only that they now reach the user once the+ * application is up.+ */+export const UNHANDLED_REJECTION = { label: "Unhandled promise rejection", fatalDuringStartup: false };++interface ProcessErrorKind {+ label: string;+ fatalDuringStartup: boolean;+}++const throttle = createErrorThrottle({+ maxPerMessage: MAX_REPORTS_PER_MESSAGE,+ windowMs: THROTTLE_WINDOW_MS,+ maxTrackedMessages: MAX_TRACKED_MESSAGES+});++let appReady = false;++/**+ * Installs the last-resort handlers for errors that escaped every other guard.+ *+ * Deferred work — a `setTimeout` callback, a floating promise — has no request to fail and no caller to+ * catch it, so without this a single throw from a background task takes the whole application down: the+ * server process dies, and Electron replaces the desktop app with a modal stack trace against minified+ * `main.cjs` offsets (see #10823). That is a wildly disproportionate outcome for work whose failure is+ * usually inconsequential, and it costs the user whatever unsaved state they had.+ *+ * Crashing therefore has to be a decision rather than the default, which is what {@link markAppReady}+ * draws the line for. Fatal errors are still fatal: they go through `platform.crash()` deliberately, from+ * a caller that knows continuing is pointless.+ *+ * Registering an `uncaughtException` listener also suppresses Electron's own handler, which bails out as+ * soon as the application has a listener of its own — so the desktop dialog stops appearing precisely+ * because we take responsibility for the error here.+ */+export function installProcessErrorHandlers() {+ process.on("uncaughtException", (error) => reportProcessError(UNCAUGHT_EXCEPTION, error));+ process.on("unhandledRejection", (reason) => reportProcessError(UNHANDLED_REJECTION, reason));+}++/**+ * Marks the point past which an escaped error is no longer fatal.+ *+ * Before this, an error means the application never became usable — a failed migration, an unreadable+ * database, a port that couldn't be bound — and limping on would only produce a broken app that misleads+ * the user about what state their data is in. After it, the application is running and serving clients,+ * so a failure in one background task is contained by definition.+ */+export function markAppReady() {+ appReady = true;+}++/**+ * Records an escaped error and decides what it costs: nothing more than a log entry and a toast once the+ * application is up, a deliberate crash while it is still starting.+ *+ * Exported for tests — production code reaches it through {@link installProcessErrorHandlers}.+ */+export function reportProcessError(kind: ProcessErrorKind, error: unknown) {+ try {+ const [message, stack] = utils.safeExtractMessageAndStackFromError(error);+ const decision = throttle.check(message, Date.now());++ if (!decision.report) {+ return;+ }++ const suppressionNotice = decision.lastBeforeSuppression+ ? ` (further occurrences of this error within ${THROTTLE_WINDOW_MS / 1000}s will not be reported)`+ : "";+ const description = `${kind.label}: ${message}${suppressionNotice}\n${stack ?? "(no stack trace available)"}`;++ logSafely(description);++ if (!appReady) {+ // No client is connected this early, so the log is the only channel available either way.+ if (kind.fatalDuringStartup) {+ getPlatform().crash(description);+ }+ 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 });+ } 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 a+ // startup failure fatal even when the reporting path itself is what broke.+ console.error("Failed to report a process-level error:", e);++ if (!appReady && kind.fatalDuringStartup) {+ process.exit(1);+ }+ }+}++function logSafely(description: string) {+ // The console line goes out first and unconditionally: it is the only channel guaranteed to exist,+ // and terminal users would otherwise see nothing.+ console.error(description);++ try {+ getLog().error(description);+ } catch {+ // The log service may not be initialized yet — an escaped error during startup is exactly when+ // that happens — and this handler must never throw.+ }+}++interface ThrottleDecision {+ /** Whether this occurrence should be logged and surfaced at all. */+ report: boolean;+ /** `true` on the last reported occurrence before the message goes quiet for the rest of its window. */+ lastBeforeSuppression: boolean;+}++/**+ * Collapses repeats of the same error message so that a task failing in a loop costs a few log lines+ * rather than an unbounded flood of them (and a toast the user cannot dismiss faster than it reappears).+ *+ * Exported for tests; pure apart from the caller-supplied clock.+ */+export function createErrorThrottle({ maxPerMessage, windowMs, maxTrackedMessages }: {+ maxPerMessage: number;+ windowMs: number;+ maxTrackedMessages: number;+}) {+ const windows = new Map<string, { count: number; startedAtMs: number }>();++ return {+ check(message: string, nowMs: number): ThrottleDecision {+ const current = windows.get(message);++ if (!current || nowMs - current.startedAtMs >= windowMs) {+ if (windows.size >= maxTrackedMessages) {+ windows.clear();+ }++ windows.set(message, { count: 1, startedAtMs: nowMs });++ return { report: true, lastBeforeSuppression: maxPerMessage <= 1 };+ }++ current.count++;++ return {+ report: current.count <= maxPerMessage,+ lastBeforeSuppression: current.count === maxPerMessage+ };+ }+ };+}diff --git a/apps/server/src/www.ts b/apps/server/src/www.tsindex 471effe834..8d51e417fe 100644--- a/apps/server/src/www.ts+++ b/apps/server/src/www.ts@@ -11,6 +11,7 @@ import { startCpuProfiler, writeCpuProfile } from "./services/cpu_profiler.js";import { registerOcrHandlers } from "./services/handlers.js";import host from "./services/host.js";import port from "./services/port.js";+import { installProcessErrorHandlers, markAppReady } from "./services/process_errors.js";import { isScriptingEnabled } from "./services/scripting_guard.js";import { getDbSize } from "./services/sql_init.js";import { isHttpAttachableMessagingProvider } from "./services/ws_messaging_provider.js";@@ -29,13 +30,7 @@ export default async function startTriliumServer(): Promise<Express> {await displayStartupMessage();// setup basic error handling even before requiring dependencies, since those can produce errors as well- process.on("unhandledRejection", (error: Error) => {- // this makes sure that stacktrace of failed promise is printed out- console.log(error);-- // but also try to log it into file- getLog().info(error);- });+ installProcessErrorHandlers();// When TRILIUM_PROFILE is set we drive the V8 CPU profiler ourselves rather than relying on Node's// --cpu-prof flag: that flag flushes its file during the normal shutdown path, which the exit() handler@@ -95,6 +90,10 @@ export default async function startTriliumServer(): Promise<Express> {registerOcrHandlers();+ // Everything the application needs in order to be usable is now up, so from here on an escaped error+ // is a contained failure rather than a broken startup, and stops being fatal.+ markAppReady();+return app;}diff --git a/packages/commons/src/lib/ws_api.ts b/packages/commons/src/lib/ws_api.tsindex eef027eb36..13cd2dfa64 100644--- a/packages/commons/src/lib/ws_api.ts+++ b/packages/commons/src/lib/ws_api.ts@@ -165,4 +165,14 @@ export type WebSocketMessage = AllTaskDefinitions | {lastSyncedPush: number;} | {type: "consistency-checks-failed"+} | {+ /**+ * An error that escaped every other handler and reached the process-level safety net — typically a+ * throw from deferred background work (a timer, a floating promise), which has no request to fail.+ * The backend keeps running; this only tells the user that something went wrong, since the failure+ * 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. */+ message: string;}