Skip to content

Build your personal knowledge base with Trilium Notes

feat(standalone): show an error overlay instead of a white screen on fatal startup failure

Elian Doran654d04d6f141
diff --git a/apps/standalone/src/error-overlay.spec.ts b/apps/standalone/src/error-overlay.spec.ts
new file mode 100644
index 0000000000..4c9f5e3ea4
--- /dev/null
+++ b/apps/standalone/src/error-overlay.spec.ts
@@ -0,0 +1,78 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+async function freshOverlay(): Promise<typeof import("./error-overlay.js")> {
+ // The module carries a "first failure wins" flag, so each test needs a
+ // fresh copy to start from a clean slate.
+ vi.resetModules();
+ return import("./error-overlay.js");
+}
+
+beforeEach(() => {
+ document.body.innerHTML = "";
+ document.body.style.display = "";
+});
+
+afterEach(() => {
+ document.getElementById("trilium-error-overlay")?.remove();
+});
+
+describe("showErrorOverlay", () => {
+ it("renders the title, message, detail and a reload button, and reveals the body", async () => {
+ const { showErrorOverlay } = await freshOverlay();
+ document.body.style.display = "none";
+
+ showErrorOverlay("Trilium couldn't start", "MIME type wrong", "at worker.js:1");
+
+ const overlay = document.getElementById("trilium-error-overlay");
+ expect(overlay).not.toBeNull();
+ expect(overlay?.textContent).toContain("Trilium couldn't start");
+ expect(overlay?.textContent).toContain("MIME type wrong");
+ expect(overlay?.querySelector("pre")?.textContent).toBe("at worker.js:1");
+ expect(overlay?.querySelector("button")?.textContent).toBe("Reload");
+ // The pre-client shell may hide the body; the overlay must un-hide it.
+ expect(document.body.style.display).toBe("block");
+ });
+
+ it("omits the detail block when no detail is given", async () => {
+ const { showErrorOverlay } = await freshOverlay();
+ showErrorOverlay("Title", "Message");
+ expect(document.getElementById("trilium-error-overlay")?.querySelector("pre")).toBeNull();
+ });
+
+ it("shows only the first failure — a hung worker can report twice", async () => {
+ const { showErrorOverlay } = await freshOverlay();
+ showErrorOverlay("First", "the informative one");
+ showErrorOverlay("Second", "the noise after");
+
+ const overlays = document.querySelectorAll("#trilium-error-overlay");
+ expect(overlays).toHaveLength(1);
+ expect(overlays[0]?.textContent).toContain("the informative one");
+ expect(overlays[0]?.textContent).not.toContain("the noise after");
+ });
+
+ it("inserts message text rather than interpreting it as markup", async () => {
+ const { showErrorOverlay } = await freshOverlay();
+ showErrorOverlay("Title", "<img src=x onerror=alert(1)>");
+ const overlay = document.getElementById("trilium-error-overlay");
+ expect(overlay?.querySelector("img")).toBeNull();
+ expect(overlay?.textContent).toContain("<img src=x onerror=alert(1)>");
+ });
+
+ it("reloads the page when the button is clicked", async () => {
+ const { showErrorOverlay } = await freshOverlay();
+ const reload = vi.fn();
+ // happy-dom's location.reload is not configurable to spy directly, so
+ // replace the whole accessor for the duration of the test.
+ const original = window.location;
+ Object.defineProperty(window, "location", {
+ value: { ...original, reload },
+ configurable: true
+ });
+
+ showErrorOverlay("Title", "Message");
+ document.getElementById("trilium-error-overlay")?.querySelector("button")?.click();
+ expect(reload).toHaveBeenCalled();
+
+ Object.defineProperty(window, "location", { value: original, configurable: true });
+ });
+});
diff --git a/apps/standalone/src/error-overlay.ts b/apps/standalone/src/error-overlay.ts
new file mode 100644
index 0000000000..13cf33499d
--- /dev/null
+++ b/apps/standalone/src/error-overlay.ts
@@ -0,0 +1,107 @@
+/**
+ * Full-screen error overlay for fatal standalone startup failures.
+ *
+ * The SQLite worker initialises asynchronously, so a failure there surfaces as a
+ * `WORKER_ERROR` message or the worker's `onerror` event — long after main.ts's
+ * bootstrap try/catch has already returned. With nowhere to show it, the page
+ * just sits on a blank white screen. This renders the failure straight into the
+ * DOM from wherever it is caught instead.
+ *
+ * Deliberately framework-free and self-contained (inline styles, no imports): it
+ * has to render in exactly the cases where the client bundle never came up, so
+ * it must not depend on anything the failure might have taken down with it.
+ */
+
+const OVERLAY_ID = "trilium-error-overlay";
+
+/** First failure wins — a hung worker can emit both `onerror` and `WORKER_ERROR`,
+ * and the first message is the one that names the actual cause. */
+let shown = false;
+
+export function showErrorOverlay(title: string, message: string, detail?: string): void {
+ if (shown) {
+ return;
+ }
+ shown = true;
+
+ // The pre-client shell may still be hiding the body; reveal it so the
+ // overlay is actually visible (mirrors main.ts's bootstrap catch).
+ document.body.style.display = "block";
+
+ // Defensive: never stack two overlays if one was somehow left behind.
+ document.getElementById(OVERLAY_ID)?.remove();
+
+ const overlay = document.createElement("div");
+ overlay.id = OVERLAY_ID;
+ overlay.setAttribute("role", "alert");
+ overlay.style.cssText = [
+ "position: fixed",
+ "inset: 0",
+ "z-index: 2147483647",
+ "display: flex",
+ "align-items: center",
+ "justify-content: center",
+ "padding: 24px",
+ "background: rgba(15, 18, 20, 0.72)",
+ "font-family: system-ui, -apple-system, sans-serif"
+ ].join(";");
+
+ const card = document.createElement("div");
+ card.style.cssText = [
+ "max-width: 560px",
+ "width: 100%",
+ "max-height: 100%",
+ "overflow: auto",
+ "background: #ffffff",
+ "color: #1a1a1a",
+ "border-radius: 10px",
+ "box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35)",
+ "padding: 28px"
+ ].join(";");
+
+ const heading = document.createElement("h1");
+ heading.textContent = title;
+ heading.style.cssText = "margin: 0 0 12px; font-size: 20px; color: #c0392b;";
+
+ const body = document.createElement("p");
+ body.textContent = message;
+ body.style.cssText = "margin: 0 0 20px; font-size: 15px; line-height: 1.5; white-space: pre-wrap; word-break: break-word;";
+
+ card.append(heading, body);
+
+ if (detail) {
+ const pre = document.createElement("pre");
+ pre.textContent = detail;
+ pre.style.cssText = [
+ "margin: 0 0 20px",
+ "padding: 12px",
+ "background: #f4f5f6",
+ "border-radius: 6px",
+ "font-size: 12px",
+ "line-height: 1.45",
+ "max-height: 220px",
+ "overflow: auto",
+ "white-space: pre-wrap",
+ "word-break: break-word"
+ ].join(";");
+ card.append(pre);
+ }
+
+ const reload = document.createElement("button");
+ reload.type = "button";
+ reload.textContent = "Reload";
+ reload.style.cssText = [
+ "padding: 10px 22px",
+ "background: #1976d2",
+ "color: #ffffff",
+ "border: none",
+ "border-radius: 6px",
+ "font-size: 15px",
+ "cursor: pointer"
+ ].join(";");
+ reload.addEventListener("click", () => location.reload());
+ card.append(reload);
+
+ overlay.append(card);
+ document.body.append(overlay);
+}
diff --git a/apps/standalone/src/local-bridge.spec.ts b/apps/standalone/src/local-bridge.spec.ts
index 73ce794f68..7418f878d0 100644
--- a/apps/standalone/src/local-bridge.spec.ts
+++ b/apps/standalone/src/local-bridge.spec.ts
@@ -55,6 +55,7 @@ function lastWorker(): MockWorker {
afterEach(() => {
delete (navigator as unknown as NavServiceWorker).serviceWorker;
+ document.getElementById("trilium-error-overlay")?.remove();
vi.restoreAllMocks();
});
@@ -79,15 +80,13 @@ describe("startLocalServerWorker", () => {
});
describe("worker message handling", () => {
- it("shows a dialog on FATAL_ERROR", async () => {
- const alertSpy = vi.fn();
- vi.stubGlobal("alert", alertSpy);
+ it("shows an error overlay on FATAL_ERROR", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const bridge = await freshBridge();
bridge.startLocalServerWorker();
lastWorker().onmessage?.({ data: { type: "FATAL_ERROR", message: "boom" } });
- expect(alertSpy).toHaveBeenCalledWith("boom");
- vi.unstubAllGlobals();
+ const overlay = document.getElementById("trilium-error-overlay");
+ expect(overlay?.textContent).toContain("boom");
});
it("dispatches a window event for WS_MESSAGE", async () => {
@@ -134,16 +133,25 @@ describe("worker message handling", () => {
await vi.waitFor(() => expect(worker.postMessage).toHaveBeenCalledWith(expect.objectContaining({ type: "HTTP_RESPONSE", id: "3", error: "plain rejection" })));
});
- it("rejects pending requests on WORKER_ERROR and on worker onerror", async () => {
+ it("shows an overlay and rejects pending requests on WORKER_ERROR", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const bridge = await freshBridge();
bridge.startLocalServerWorker();
- const worker = lastWorker();
- // WORKER_ERROR path
- worker.onmessage?.({ data: { type: "WORKER_ERROR", error: { message: "crash" } } });
- // onerror path
- expect(() => worker.onerror?.({ message: "fatal" })).not.toThrow();
+ lastWorker().onmessage?.({ data: { type: "WORKER_ERROR", error: { message: "crash", stack: "at boom" } } });
+
+ const overlay = document.getElementById("trilium-error-overlay");
+ expect(overlay?.textContent).toContain("crash");
+ expect(overlay?.textContent).toContain("at boom");
+ });
+
+ it("shows an overlay on worker onerror without throwing", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ const bridge = await freshBridge();
+ bridge.startLocalServerWorker();
+
+ expect(() => lastWorker().onerror?.({ message: "fatal" })).not.toThrow();
+ expect(document.getElementById("trilium-error-overlay")?.textContent).toContain("fatal");
});
it("ignores messages without a recognized type", async () => {
diff --git a/apps/standalone/src/local-bridge.ts b/apps/standalone/src/local-bridge.ts
index 8ccc38ca14..6354b59814 100644
--- a/apps/standalone/src/local-bridge.ts
+++ b/apps/standalone/src/local-bridge.ts
@@ -1,5 +1,6 @@
import type { StandaloneRestoreProgress, StandaloneRestoreResult } from "@triliumnext/commons";
+import { showErrorOverlay } from "./error-overlay.js";
import { isLeader } from "./leader_election.js";
import LocalServerWorker from "./local-server-worker?worker";
let localWorker: Worker | null = null;
@@ -161,10 +162,6 @@ export function registerNativeHttpHandler(handler: NativeHttpHandler) {
nativeHttpHandler = handler;
}
-function showFatalErrorDialog(message: string) {
- alert(message);
-}
-
export function startLocalServerWorker() {
if (localWorker) return localWorker;
localWorker = new LocalServerWorker();
@@ -177,6 +174,10 @@ export function startLocalServerWorker() {
// Handle worker errors during initialization
localWorker.onerror = (event) => {
console.error("[LocalBridge] Worker error:", event);
+ showErrorOverlay(
+ "Trilium couldn't start",
+ event.message || "The database worker failed to start. See the console for details."
+ );
// Reject all pending requests
for (const [, resolver] of pending) {
resolver.reject(new Error(`Worker error: ${event.message}`));
@@ -199,16 +200,25 @@ export function startLocalServerWorker() {
return;
}
- // Handle fatal platform crashes (shown as a dialog to the user)
+ // Handle fatal platform crashes (shown as an overlay to the user)
if (msg?.type === "FATAL_ERROR") {
console.error("[LocalBridge] Fatal error:", msg.message);
- showFatalErrorDialog(msg.message);
+ showErrorOverlay("Trilium crashed", msg.message);
return;
}
- // Handle worker error reports
+ // Handle worker error reports. These are uncaught errors and unhandled
+ // rejections in the worker; an initialization failure in particular
+ // never resolves a request (it just hangs), so this message is the only
+ // signal the user would otherwise get — surface it instead of a blank
+ // screen.
if (msg?.type === "WORKER_ERROR") {
console.error("[LocalBridge] Worker reported error:", msg.error);
+ showErrorOverlay(
+ "Trilium couldn't start",
+ msg.error?.message || "The database worker reported an error.",
+ msg.error?.stack
+ );
// Reject all pending requests with the error
for (const [, resolver] of pending) {
resolver.reject(new Error(msg.error?.message || "Unknown worker error"));
diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.ts
index 5923bc8c4b..e55434ba3d 100644
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@ -1,3 +1,4 @@
+import { showErrorOverlay } from "./error-overlay.js";
import { installIosInterceptors } from "./ios-interceptors.js";
import { claimLeadership } from "./leader_election.js";
import { announceLeadership, attachServiceWorkerBridge, registerNativeHttpHandler, restoreBackup, startLocalServerWorker } from "./local-bridge.js";
@@ -85,17 +86,10 @@ async function bootstrap() {
}
console.error("[Bootstrap] Fatal error:", err);
- document.body.innerHTML = `
- <div style="padding: 40px; max-width: 600px; margin: 0 auto; font-family: system-ui, sans-serif;">
- <h1 style="color: #d32f2f;">Failed to Initialize</h1>
- <p>The application failed to start. Please check the browser console for details.</p>
- <pre style="background: #f5f5f5; padding: 16px; border-radius: 4px; overflow: auto; white-space: pre-wrap; word-wrap: break-word;">${err instanceof Error ? err.message : String(err)}</pre>
- <button onclick="location.reload()" style="padding: 12px 24px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px;">
- Reload Page
- </button>
- </div>
- `;
- document.body.style.display = "block";
+ showErrorOverlay(
+ "Failed to Initialize",
+ err instanceof Error ? err.message : String(err)
+ );
}
}