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(desktop): record startup timing metrics to a file
Elian Doran3f9b8ad5c741
diff --git a/.gitignore b/.gitignoreindex 244291c7c4..2bbc2611e1 100644--- a/.gitignore+++ b/.gitignore@@ -27,6 +27,7 @@ node_modulesnpm-debug.logyarn-error.logtestem.log+startup-metrics.log/typings# System Filesdiff --git a/apps/client/src/desktop.ts b/apps/client/src/desktop.tsindex 129ea53556..6b2dd7ac4b 100644--- a/apps/client/src/desktop.ts+++ b/apps/client/src/desktop.ts@@ -21,7 +21,7 @@ bundleService.getWidgetBundlesByParent().then(async (widgetBundles) => {const DesktopLayout = (await import("./layouts/desktop_layout.js")).default;appContext.setLayout(new DesktopLayout(widgetBundles));- appContext.start().catch((e) => {+ appContext.start().then(reportFullRenderStartupMetric).catch((e) => {toastService.showPersistent({id: "critical-error",title: t("toast.critical-error.title"),@@ -68,6 +68,21 @@ function initOnElectron() {api.navigation.clearNavigationHistory();}+/**+ * Tells the Electron main process that the client finished its initial render+ * (layout widgets attached, froca loaded, tab restoration started) so it gets+ * logged against the other startup metrics. The double requestAnimationFrame+ * defers the report until the browser has painted a frame of the rendered+ * layout, rather than measuring DOM construction only. No-op outside Electron.+ */+function reportFullRenderStartupMetric() {+ requestAnimationFrame(() => {+ requestAnimationFrame(() => {+ window.electronApi?.window.reportStartupMetric("client-full-render");+ });+ });+}+function initFullScreenDetection(win: ElectronWindowApi) {win.onEnterFullScreen(() => document.body.classList.add("full-screen"));win.onLeaveFullScreen(() => document.body.classList.remove("full-screen"));diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex 64520bef64..948497d26c 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -182,6 +182,10 @@ vi.mock("./services/security_settings", () => ({getSecuritySettings: () => h.securitySettings,registerSecurityIpcHandlers: vi.fn()}));+vi.mock("./services/startup_metrics", () => ({+ markStartupMetric: vi.fn(),+ setupStartupMetricsIpc: vi.fn()+}));const realPlatform = process.platform;function setPlatform(platform: NodeJS.Platform) {@@ -286,6 +290,13 @@ describe("main() bootstrap", () => {expect(h.appOn.has("ready")).toBe(true);expect(h.appOn.has("will-quit")).toBe(true);expect(h.appOn.has("second-instance")).toBe(true);++ // Startup instrumentation is wired up and the boot phases are marked.+ const { markStartupMetric, setupStartupMetricsIpc } = await import("./services/startup_metrics.js");+ expect(setupStartupMetricsIpc).toHaveBeenCalled();+ for (const phase of ["main-process-start", "database-opened", "core-initialized", "server-started"]) {+ expect(markStartupMetric).toHaveBeenCalledWith(phase);+ }});it("appends no disable-http-cache switch when TRILIUM_ENV is not dev, and skips smooth-scroll switch when enabled", async () => {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 0edaf843e3..fcb5a5ba1a 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -29,9 +29,12 @@ import { setupCustomDictionary } from "./services/custom_dictionary";import { setupPrintingHandlers } from "./services/printing";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";import { setupShellHandlers } from "./services/shell";+import { markStartupMetric, setupStartupMetricsIpc } from "./services/startup_metrics";import { setupSystemTray } from "./services/tray";export async function main() {+ markStartupMetric("main-process-start");+// Ignore EPIPE errors on stdout/stderr — these occur when the parent process// pipe breaks (e.g. after system suspend with Snap packaging).for (const stream of [process.stdout, process.stderr]) {@@ -108,6 +111,7 @@ export async function main() {});app.on("ready", async () => {+ markStartupMetric("electron-ready");await coreInitializedPromise;console.log("Starting Electron...");await onReady();@@ -119,6 +123,7 @@ export async function main() {setupShellHandlers();setupPrintingHandlers();registerSecurityIpcHandlers();+ setupStartupMetricsIpc();app.on("will-quit", () => {globalShortcut.unregisterAll();@@ -162,6 +167,7 @@ export async function main() {const dbProvider = new BetterSqlite3Provider();dbProvider.loadFromFile(DOCUMENT_PATH, config.General.readOnly);+ markStartupMetric("database-opened");// The IPC provider just registers an `ipcMain.on` listener; no TCP socket// or session parser needed, so we can init it here (before startTriliumServer)@@ -213,11 +219,12 @@ export async function main() {dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)}});+ markStartupMetric("core-initialized");coreInitializedPromise.resolve();const startTriliumServer = (await import("@triliumnext/server/src/www.js")).default;const expressApp = await startTriliumServer();- console.log("Server loaded");+ markStartupMetric("server-started");expressAppPromise.resolve(expressApp);}diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex e5e7dbdc31..b3b25ea072 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -223,6 +223,14 @@ describe("preload script", () => {expect(ipcRendererSent).toContainEqual({ channel: "show-window", args: [] });});+ it("reportStartupMetric sends correct IPC message", () => {+ win().reportStartupMetric("client-full-render");+ expect(ipcRendererSent).toContainEqual({+ channel: "report-startup-metric",+ args: ["client-full-render"]+ });+ });+it("clearCache invokes correct IPC channel", async () => {await win().clearCache();expect(ipcRendererInvoked).toContainEqual({ channel: "clear-cache", args: [] });diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 1cdaef96cb..7e7a63bf4b 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -1,4 +1,4 @@-import type { ElectronApi, ElectronContextMenuParams } from "@triliumnext/commons";+import type { ElectronApi, ElectronContextMenuParams, RendererStartupMetric } from "@triliumnext/commons";import { contextBridge, ipcRenderer, webFrame } from "electron";contextBridge.exposeInMainWorld("electronApi", {@@ -86,6 +86,9 @@ contextBridge.exposeInMainWorld("electronApi", {showWindow() {ipcRenderer.send("show-window");},+ reportStartupMetric(metric: RendererStartupMetric) {+ ipcRenderer.send("report-startup-metric", metric);+ },// Background effectssetBackgroundMaterial(material: string) {diff --git a/apps/desktop/src/services/startup_metrics.spec.ts b/apps/desktop/src/services/startup_metrics.spec.tsnew file mode 100644index 0000000000..8712ce7af1--- /dev/null+++ b/apps/desktop/src/services/startup_metrics.spec.ts@@ -0,0 +1,87 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++type Handler = (...args: unknown[]) => void;++const h = vi.hoisted(() => ({+ ipcOn: new Map<string, Handler>(),+ writeFileSync: vi.fn(),+ writeShouldThrow: false+}));++vi.mock("electron", () => ({+ ipcMain: {+ on: (channel: string, fn: Handler) => h.ipcOn.set(channel, fn)+ }+}));++vi.mock("fs", () => ({+ default: {+ writeFileSync: (...args: unknown[]) => {+ if (h.writeShouldThrow) {+ throw new Error("disk full");+ }+ h.writeFileSync(...args);+ }+ }+}));++describe("startup metrics", () => {+ let metrics: typeof import("./startup_metrics.js");++ beforeEach(async () => {+ h.ipcOn.clear();+ h.writeFileSync.mockClear();+ h.writeShouldThrow = false;+ vi.resetModules();+ metrics = await import("./startup_metrics.js");+ });++ it("records a metric relative to the baseline and rewrites the metrics file", () => {+ metrics.markStartupMetric("test-phase");++ const elapsed = metrics.getStartupMetrics().get("test-phase");+ expect(elapsed).toBeGreaterThanOrEqual(0);+ expect(h.writeFileSync).toHaveBeenCalledTimes(1);+ expect(h.writeFileSync).toHaveBeenCalledWith(+ "startup-metrics.log",+ expect.stringContaining("test-phase:")+ );++ // Re-marking keeps the first measurement and does not rewrite the file.+ metrics.markStartupMetric("test-phase");+ expect(metrics.getStartupMetrics().get("test-phase")).toBe(elapsed);+ expect(h.writeFileSync).toHaveBeenCalledTimes(1);++ // A second metric rewrites the file with the complete set, each line+ // showing the delta to the previous metric plus the cumulative time.+ metrics.markStartupMetric("second-phase");+ const content = h.writeFileSync.mock.calls[1]?.[1];+ expect(content).toContain("test-phase:");+ expect(content).toMatch(/second-phase: \+\d+ms \(\d+ms since process creation\)/);+ });++ it("keeps the metric available even when the file write fails", () => {+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});+ h.writeShouldThrow = true;++ metrics.markStartupMetric("test-phase");++ expect(metrics.getStartupMetrics().has("test-phase")).toBe(true);+ expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("startup-metrics.log"));+ });++ it("accepts allowlisted renderer metrics over IPC and rejects everything else", () => {+ metrics.setupStartupMetricsIpc();+ const handler = h.ipcOn.get("report-startup-metric");+ expect(handler).toBeDefined();+ if (!handler) return;++ handler({}, "not-a-known-metric");+ handler({}, 42);+ handler({}, undefined);+ expect(metrics.getStartupMetrics().size).toBe(0);++ handler({}, "client-full-render");+ expect(metrics.getStartupMetrics().has("client-full-render")).toBe(true);+ });+});diff --git a/apps/desktop/src/services/startup_metrics.ts b/apps/desktop/src/services/startup_metrics.tsnew file mode 100644index 0000000000..2bcbe370d0--- /dev/null+++ b/apps/desktop/src/services/startup_metrics.ts@@ -0,0 +1,72 @@+import type { RendererStartupMetric } from "@triliumnext/commons";+import { ipcMain } from "electron";+import fs from "fs";++/**+ * Startup timing instrumentation for the desktop app.+ *+ * Every mark is measured as the time elapsed since the OS created the Electron+ * main process (`process.getCreationTime()`), so the numbers include Chromium+ * bootstrap and the parse/evaluation of the main bundle — not just the parts+ * Trilium controls. Falls back to the load time of this module in the rare+ * case the OS does not report a creation time.+ *+ * The metrics are written to {@link STARTUP_METRICS_FILE} (rewritten on every+ * mark, so the file always holds the complete picture of the current launch)+ * to keep them out of the regular log stream.+ *+ * Only the first occurrence of each metric is recorded: window reloads, extra+ * windows, and repeated phase marks do not overwrite the startup measurement.+ */++const STARTUP_METRICS_FILE = "startup-metrics.log";++const baselineEpochMs: number = process.getCreationTime?.() ?? Date.now();++const recordedMetrics = new Map<string, number>();++/** Metric names the renderer is allowed to report via `report-startup-metric` IPC. */+const RENDERER_STARTUP_METRICS: ReadonlySet<string> = new Set<RendererStartupMetric>(["client-full-render"]);++/** Records the given startup milestone as "now", unless it was already recorded. */+export function markStartupMetric(name: string) {+ if (recordedMetrics.has(name)) {+ return;+ }++ recordedMetrics.set(name, Math.round(Date.now() - baselineEpochMs));++ // One line per metric: the duration of the phase (delta to the previous+ // metric), with the cumulative time since process creation in parentheses.+ let previousElapsedMs = 0;+ const lines = [...recordedMetrics].map(([metric, elapsedMs]) => {+ const line = `${metric}: +${elapsedMs - previousElapsedMs}ms (${elapsedMs}ms since process creation)`;+ previousElapsedMs = elapsedMs;+ return line;+ });+ try {+ fs.writeFileSync(STARTUP_METRICS_FILE, `${lines.join("\n")}\n`);+ } catch (e) {+ // Instrumentation must never break startup; the metric stays available+ // via getStartupMetrics().+ console.error(`Could not write ${STARTUP_METRICS_FILE}: ${e}`);+ }+}++/** The metrics recorded so far, as elapsed milliseconds since process creation. */+export function getStartupMetrics(): ReadonlyMap<string, number> {+ return recordedMetrics;+}++/**+ * Registers the IPC channel through which the renderer reports its own startup+ * milestones (`window.electronApi.window.reportStartupMetric`). The renderer is+ * untrusted, so only allowlisted metric names are accepted.+ */+export function setupStartupMetricsIpc() {+ ipcMain.on("report-startup-metric", (_event, metric: unknown) => {+ if (typeof metric === "string" && RENDERER_STARTUP_METRICS.has(metric)) {+ markStartupMetric(metric);+ }+ });+}diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.tsindex 1f75967472..0077d3d264 100644--- a/apps/desktop/src/services/window.spec.ts+++ b/apps/desktop/src/services/window.spec.ts@@ -46,6 +46,7 @@ class FakeWebContents {this.listeners.set(event, list);return this;});+ public once = vi.fn((event: string, cb: Handler) => this.on(event, cb));public listeners = new Map<string, Handler[]>();public toggleDevTools = vi.fn();public isDevToolsOpened = vi.fn(() => false);@@ -89,6 +90,7 @@ class FakeBrowserWindow {this.listeners.set(event, list);return this;});+ public once = vi.fn((event: string, cb: Handler) => this.on(event, cb));public setMenuBarVisibility = vi.fn();public removeMenu = vi.fn();public loadURL = vi.fn(() => Promise.resolve());@@ -187,6 +189,10 @@ vi.mock("electron-window-state", () => ({// windowing tests focused and free of the extra electron app/session surface.vi.mock("./web_contents_security", () => ({ setupWebContentsSecurity: vi.fn() }));+// Startup timing has its own suite (startup_metrics.spec.ts); here we only+// verify that window creation marks the right milestones.+vi.mock("./startup_metrics", () => ({ markStartupMetric: vi.fn() }));+vi.mock("@triliumnext/core", async (importOriginal) => {const actual = await importOriginal<typeof import("@triliumnext/core")>();return {@@ -217,6 +223,7 @@ vi.mock("@triliumnext/core", async (importOriginal) => {const windowService = (await import("./window.js")).default;const { setupWindowing } = await import("./window.js");+const { markStartupMetric } = await import("./startup_metrics.js");function fireOn(channel: string, event: unknown, ...args: unknown[]) {const fn = state.ipcOn.get(channel);@@ -327,6 +334,19 @@ describe("window service", () => {const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;expect(opts.frame).toBeUndefined();});++ it("marks startup metrics for creation, first paint, and load finish", async () => {+ await windowService.createMainWindow();+ const win = state.windows[state.windows.length - 1];++ expect(markStartupMetric).toHaveBeenCalledWith("main-window-created");++ win.fire("ready-to-show");+ expect(markStartupMetric).toHaveBeenCalledWith("main-window-first-paint");++ win.webContents.fire("did-finish-load");+ expect(markStartupMetric).toHaveBeenCalledWith("main-window-load-finished");+ });});describe("createExtraWindow", () => {diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.tsindex a6ce58db9e..016750b076 100644--- a/apps/desktop/src/services/window.ts+++ b/apps/desktop/src/services/window.ts@@ -3,6 +3,7 @@ import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";import { type BrowserWindow, type BrowserWindowConstructorOptions, default as electron, type Session, type WebContents } from "electron";import path from "path";+import { markStartupMetric } from "./startup_metrics.js";import { TRILIUM_APP_BASE_URL } from "./trilium_app_origin.js";import { setupWebContentsSecurity } from "./web_contents_security.js";@@ -127,6 +128,12 @@ async function createMainWindow() {...getWindowExtraOpts()});+ markStartupMetric("main-window-created");+ // First time the renderer has produced a frame of the page — the closest+ // main-process signal to "the window displays something".+ mainWindow.once("ready-to-show", () => markStartupMetric("main-window-first-paint"));+ mainWindow.webContents.once("did-finish-load", () => markStartupMetric("main-window-load-finished"));+mainWindowState.manage(mainWindow);mainWindow.setMenuBarVisibility(false);diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex 82ac40dac2..a03b83b12c 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -35,6 +35,16 @@ export interface ElectronContextMenuParams {};}+/**+ * Startup milestones the renderer may report to the main process for startup+ * timing instrumentation (see `apps/desktop/src/services/startup_metrics.ts`).+ *+ * - `client-full-render` — the client finished its initial render: the layout+ * widgets are attached to the DOM, the froca note cache is loaded, and a+ * frame of the rendered layout has been painted.+ */+export type RendererStartupMetric = "client-full-render";+/*** Window-level controls: zoom, theme, title bar, full screen, lifecycle, and* a handful of main → renderer event subscriptions.@@ -171,6 +181,14 @@ export interface ElectronWindowApi {/** Brings the main window to the foreground, restoring it if minimized. */showWindow(): void;+ /**+ * Reports a renderer startup milestone to the main process, which records+ * it relative to OS process creation alongside the main-process startup+ * metrics. Only the first report of each metric is recorded; later reports+ * (e.g. after a window reload or from extra windows) are ignored.+ */+ reportStartupMetric(metric: RendererStartupMetric): void;+// #endregion// #region Main → renderer events