Skip to content

Build your personal knowledge base with Trilium Notes

perf(desktop): create the main window without waiting for the server to start

Elian Doranb6db6bee04b3
diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.ts
index a859674b03..64520bef64 100644
--- a/apps/desktop/src/main.spec.ts
+++ b/apps/desktop/src/main.spec.ts
@@ -14,7 +14,7 @@ interface SecuritySettings {
sqlConsoleEnabled?: boolean;
}
-// A tiny real deferred so serverInitializedPromise behaves like the real thing.
+// A tiny real deferred so the core/server init promises behave like the real thing.
function makeDeferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void;
let reject!: (reason?: unknown) => void;
@@ -63,7 +63,9 @@ const h = vi.hoisted(() => ({
createSetupWindow: vi.fn((..._a: unknown[]) => Promise.resolve()),
createExtraWindow: vi.fn((..._a: unknown[]) => {}),
registerGlobalShortcuts: vi.fn((..._a: unknown[]) => Promise.resolve()),
- unregisterAll: vi.fn()
+ unregisterAll: vi.fn(),
+ // Controllable server start so tests can simulate a slow/hanging server.
+ startServer: (() => Promise.resolve({})) as () => Promise<unknown>
}));
vi.mock("electron", () => {
@@ -156,7 +158,7 @@ vi.mock("@triliumnext/server/src/services/config.js", () => ({
vi.mock("@triliumnext/server/src/services/export/zip/factory.js", () => ({ serverZipExportProviderFactory: vi.fn() }));
vi.mock("@triliumnext/server/src/services/i18n.js", () => ({ initializeTranslations: vi.fn() }));
vi.mock("@triliumnext/server/src/services/image_provider.js", () => ({ serverImageProvider: {} }));
-vi.mock("@triliumnext/server/src/www.js", () => ({ default: vi.fn(() => Promise.resolve({})) }));
+vi.mock("@triliumnext/server/src/www.js", () => ({ default: vi.fn(() => h.startServer()) }));
vi.mock("./services/request", () => ({ default: class {} }));
vi.mock("./services/window", () => ({
@@ -219,6 +221,7 @@ function resetState() {
h.createExtraWindow.mockClear();
h.registerGlobalShortcuts.mockClear();
h.unregisterAll.mockClear();
+ h.startServer = () => Promise.resolve({});
}
beforeEach(() => {
@@ -444,6 +447,23 @@ describe("app event handlers", () => {
expect(h.createSetupWindow).toHaveBeenCalled();
expect(h.createMainWindow).not.toHaveBeenCalled();
});
+
+ it("creates the main window while the server is still starting", async () => {
+ h.isDbInitialized = true;
+ // The server never finishes starting; the window is gated on core
+ // initialization only, so it must still be created.
+ h.startServer = () => new Promise(() => {});
+ const { main } = await importMain();
+ void main(); // intentionally not awaited — it only settles once the server starts
+
+ // The ready handler is registered synchronously; awaiting it blocks
+ // only on core initialization, which completes despite the hung server.
+ const ready = h.appOn.get("ready");
+ expect(ready).toBeDefined();
+ await ready?.();
+
+ expect(h.createMainWindow).toHaveBeenCalledTimes(1);
+ });
});
});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 3bd10426da..0edaf843e3 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -15,6 +15,7 @@ import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";
import { app, BrowserWindow,globalShortcut } from "electron";
import electronDebug from "electron-debug";
import electronDl from "electron-dl";
+import type { Application } from "express";
import fs from "fs";
import { t } from "i18next";
import path, { join, resolve } from "path";
@@ -46,7 +47,17 @@ export async function main() {
const userDataPath = getUserData();
app.setPath("userData", userDataPath);
- const serverInitializedPromise = deferred<void>();
+ // Resolved once initializeCore() has finished — the DB is open and options
+ // and translations are readable. That is all window creation needs, so it
+ // (not full server startup) gates onReady(): the renderer spins up
+ // concurrently with the Express app being built.
+ const coreInitializedPromise = deferred<void>();
+
+ // Resolved with the Express app once the server has finished building. The
+ // trilium-app:// protocol handler awaits this per request, so renderer
+ // requests that arrive before the server is up simply wait.
+ const expressAppPromise = deferred<Application>();
+ setupTriliumAppProtocol(expressAppPromise);
// Prevent Trilium starting twice on first install and on uninstall for the Windows installer.
/* v8 ignore next 3 -- squirrel uses a CJS require() that vi.mock cannot intercept, so the truthy/exit path is un-coverable in unit tests */
@@ -97,7 +108,7 @@ export async function main() {
});
app.on("ready", async () => {
- await serverInitializedPromise;
+ await coreInitializedPromise;
console.log("Starting Electron...");
await onReady();
});
@@ -202,14 +213,13 @@ export async function main() {
dataDirectory: path.resolve(dataDirs.TRILIUM_DATA_DIR)
}
});
+ coreInitializedPromise.resolve();
const startTriliumServer = (await import("@triliumnext/server/src/www.js")).default;
const expressApp = await startTriliumServer();
console.log("Server loaded");
- setupTriliumAppProtocol(expressApp);
-
- serverInitializedPromise.resolve();
+ expressAppPromise.resolve(expressApp);
}
/**
diff --git a/apps/desktop/src/protocol.spec.ts b/apps/desktop/src/protocol.spec.ts
index ea5052e75b..ba882fe1a5 100644
--- a/apps/desktop/src/protocol.spec.ts
+++ b/apps/desktop/src/protocol.spec.ts
@@ -231,6 +231,29 @@ describe("trilium-app protocol dispatcher", () => {
expect(await response.text()).toBe("Internal Server Error");
});
+ it("holds requests until a promised Express app resolves", async () => {
+ electronMock.handle.mockReset();
+ let resolveApp: (app: ReturnType<typeof buildTestApp>) => void = () => {};
+ setupTriliumAppProtocol(new Promise((res) => { resolveApp = res; }));
+ await Promise.resolve(); // let whenReady().then(...) run
+
+ const handler = electronMock.handle.mock.calls[0][1] as (req: Request) => Promise<Response>;
+ const responsePromise = handler(new Request("trilium-app://app/echo-json", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ hello: "world" })
+ }));
+
+ // The request must wait for the app instead of failing or settling early.
+ const settledEarly = await Promise.race([responsePromise.then(() => true), Promise.resolve(false)]);
+ expect(settledEarly).toBe(false);
+
+ resolveApp(buildTestApp());
+ const response = await responsePromise;
+ expect(response.status).toBe(200);
+ expect(await response.json()).toEqual({ echo: { hello: "world" } });
+ });
+
it("rejects when Express forwards an unhandled error to next()", async () => {
const app = express();
app.get("/boom", (_req, _res, next) => next(new Error("downstream failure")));
diff --git a/apps/desktop/src/protocol.ts b/apps/desktop/src/protocol.ts
index 6d486731b8..0025468373 100644
--- a/apps/desktop/src/protocol.ts
+++ b/apps/desktop/src/protocol.ts
@@ -12,8 +12,8 @@ import { isTriliumAppShellUrl, TRILIUM_APP_ORIGIN, TRILIUM_APP_SCHEME } from "./
* Registers the `trilium-app://` custom scheme as privileged so the renderer
* can load the UI from `trilium-app://app/` with a proper origin & cookie jar,
* fetch support, and CORS. The actual request handler is installed by
- * `setupTriliumAppProtocol` below, once the Express app has been built and
- * `app.ready` has fired.
+ * `setupTriliumAppProtocol` below, once `app.ready` has fired (the Express
+ * app may still be building at that point — requests wait for it).
*
* **Must be called before `app.ready`.** Electron only honours
* `registerSchemesAsPrivileged` if it runs synchronously during startup;
@@ -47,8 +47,13 @@ export function registerTriliumAppScheme() {
* `Readable` for the request and a node-mocks-http response, then dispatch
* through the Express app so the real session, CSRF, body-parser, multer and
* error middleware all run.
+ *
+ * Accepts a promise of the Express app so the handler can be installed before
+ * the server has finished building — windows can then be created (and the
+ * renderer can spin up) concurrently with server startup; requests that
+ * arrive early simply wait inside the handler until the app resolves.
*/
-export function setupTriliumAppProtocol(app: Application) {
+export function setupTriliumAppProtocol(app: Application | Promise<Application>) {
electron.app.whenReady().then(() => {
installFrameOriginGuard();
electron.protocol.handle(TRILIUM_APP_SCHEME, async (request) => {
@@ -58,7 +63,7 @@ export function setupTriliumAppProtocol(app: Application) {
return new Response("Forbidden", { status: 403 });
}
try {
- return await dispatch(app, request);
+ return await dispatch(await app, request);
} catch (err) {
console.error(`[trilium-app] dispatch failed for ${request.method} ${request.url}:`, err);
return new Response("Internal Server Error", { status: 500 });