Skip to content

Build your personal knowledge base with Trilium Notes

test(desktop): increase coverage

Elian Doranf308fcc7b0f0
diff --git a/apps/desktop/src/app-info.spec.ts b/apps/desktop/src/app-info.spec.ts
new file mode 100644
index 0000000000..7042b0e3b9
--- /dev/null
+++ b/apps/desktop/src/app-info.spec.ts
@@ -0,0 +1,9 @@
+import { describe, expect, it } from "vitest";
+
+import { PRODUCT_NAME } from "./app-info.js";
+
+describe("app-info", () => {
+ it("exposes the Electron product name", () => {
+ expect(PRODUCT_NAME).toBe("Trilium Notes");
+ });
+});
diff --git a/apps/desktop/src/ipc_messaging_provider.spec.ts b/apps/desktop/src/ipc_messaging_provider.spec.ts
index 1ef69f0649..59c18e4204 100644
--- a/apps/desktop/src/ipc_messaging_provider.spec.ts
+++ b/apps/desktop/src/ipc_messaging_provider.spec.ts
@@ -102,6 +102,18 @@ describe("IpcMessagingProvider", () => {
]);
});
+ it("still delivers noisy log-filtered message types (sync-failed / api-log-messages)", () => {
+ const w = newWindow();
+
+ provider.sendMessageToAllClients({ type: "sync-failed" } as any);
+ provider.sendMessageToAllClients({ type: "api-log-messages" } as any);
+
+ expect(sends).toEqual([
+ { windowId: w.id, channel: "trilium-ws-message", payload: { type: "sync-failed" } },
+ { windowId: w.id, channel: "trilium-ws-message", payload: { type: "api-log-messages" } }
+ ]);
+ });
+
it("skips destroyed windows", () => {
const live = newWindow();
const dead = newWindow();
@@ -186,6 +198,19 @@ describe("IpcMessagingProvider", () => {
deliverFromRenderer(a.webContents.id, { type: "ping" });
await Promise.resolve();
});
+
+ it("swallows handler errors instead of crashing the main process", async () => {
+ const handler = vi.fn().mockRejectedValue(new Error("boom"));
+ provider.setClientMessageHandler(handler);
+
+ const a = newWindow();
+ // Must not reject / throw even though the handler rejects.
+ deliverFromRenderer(a.webContents.id, { type: "ping" });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(handler).toHaveBeenCalled();
+ });
});
describe("client count", () => {
diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.ts
new file mode 100644
index 0000000000..a859674b03
--- /dev/null
+++ b/apps/desktop/src/main.spec.ts
@@ -0,0 +1,555 @@
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type Handler = (...args: unknown[]) => unknown;
+
+interface FakeWindow {
+ isMinimized: () => boolean;
+ restore: () => void;
+ show: () => void;
+ focus: () => void;
+}
+
+interface SecuritySettings {
+ backendScriptingEnabled?: boolean;
+ sqlConsoleEnabled?: boolean;
+}
+
+// A tiny real deferred so serverInitializedPromise behaves like the real thing.
+function makeDeferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ }) as Promise<T> & { resolve: typeof resolve; reject: typeof reject };
+ promise.resolve = resolve;
+ promise.reject = reject;
+ return promise;
+}
+
+const h = vi.hoisted(() => ({
+ // Captured app.on(...) handlers.
+ appOn: new Map<string, Handler>(),
+ // Captured stdout/stderr "error" handlers.
+ streamErrorHandlers: [] as Handler[],
+ // Captured commandLine.appendSwitch calls.
+ appendSwitch: vi.fn(),
+ setName: vi.fn(),
+ quit: vi.fn(),
+ exit: vi.fn(),
+ relaunch: vi.fn(),
+ setPath: vi.fn(),
+ setUserTasks: vi.fn(),
+ // Controllable values.
+ squirrel: { default: false as boolean },
+ isPrimaryInstance: true as boolean,
+ allWindows: [] as unknown[],
+ smoothScroll: "true" as string | null,
+ isDbInitialized: true as boolean,
+ securitySettings: {} as SecuritySettings,
+ lastFocusedWindow: null as FakeWindow | null,
+ entityChangeIds: [] as string[],
+ locale: null as string | null,
+ formattingLocale: null as string | null,
+ locales: [] as Array<{ id: string; rtl: boolean }>,
+ // Capture the config object passed to initializeCore.
+ initConfig: undefined as undefined | Record<string, unknown>,
+ // Captured mocked fns we assert on.
+ sendTransactionEntityChangesToAllClients: vi.fn(),
+ beccaLoad: vi.fn(),
+ recalculateMaxEntityChangeId: vi.fn(),
+ banner: vi.fn(),
+ createMainWindow: vi.fn((..._a: unknown[]) => Promise.resolve()),
+ createSetupWindow: vi.fn((..._a: unknown[]) => Promise.resolve()),
+ createExtraWindow: vi.fn((..._a: unknown[]) => {}),
+ registerGlobalShortcuts: vi.fn((..._a: unknown[]) => Promise.resolve()),
+ unregisterAll: vi.fn()
+}));
+
+vi.mock("electron", () => {
+ const appObj = {
+ setPath: (...a: unknown[]) => h.setPath(...a),
+ getPath: () => "/appData",
+ getName: () => "Trilium",
+ setName: (...a: unknown[]) => h.setName(...a),
+ setUserTasks: (...a: unknown[]) => h.setUserTasks(...a),
+ commandLine: { appendSwitch: (...a: unknown[]) => h.appendSwitch(...a) },
+ on: (event: string, cb: Handler) => h.appOn.set(event, cb),
+ quit: (...a: unknown[]) => h.quit(...a),
+ exit: (...a: unknown[]) => h.exit(...a),
+ relaunch: (...a: unknown[]) => h.relaunch(...a),
+ requestSingleInstanceLock: () => h.isPrimaryInstance
+ };
+ const BrowserWindow = {
+ getAllWindows: () => h.allWindows
+ };
+ const globalShortcut = {
+ unregisterAll: (...a: unknown[]) => h.unregisterAll(...a)
+ };
+ return {
+ app: appObj,
+ BrowserWindow,
+ globalShortcut,
+ default: { app: appObj, BrowserWindow, globalShortcut }
+ };
+});
+
+vi.mock("electron-debug", () => ({ default: vi.fn() }));
+vi.mock("electron-dl", () => ({ default: vi.fn() }));
+vi.mock("electron-squirrel-startup", () => ({ get default() { return h.squirrel.default; } }));
+
+vi.mock("fs", () => ({ default: { readFileSync: vi.fn(() => Buffer.from("zip")) } }));
+vi.mock("i18next", () => ({ t: (key: string) => key }));
+
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => ({ info: vi.fn(), error: vi.fn(), banner: (...a: unknown[]) => h.banner(...a) }),
+ initializeCore: vi.fn((config: Record<string, unknown>) => {
+ h.initConfig = config;
+ return Promise.resolve();
+ }),
+ options: { getOptionOrNull: (key: string) => {
+ if (key === "smoothScrollEnabled") return h.smoothScroll;
+ if (key === "locale") return h.locale;
+ if (key === "formattingLocale") return h.formattingLocale;
+ return null;
+ } },
+ sql_init: { isDbInitialized: () => h.isDbInitialized, dbReady: Promise.resolve() },
+ ws: { sendTransactionEntityChangesToAllClients: (...a: unknown[]) => h.sendTransactionEntityChangesToAllClients(...a) },
+ cls: { getAndClearEntityChangeIds: () => h.entityChangeIds },
+ becca_loader: { load: (...a: unknown[]) => h.beccaLoad(...a) },
+ entity_changes: { recalculateMaxEntityChangeId: (...a: unknown[]) => h.recalculateMaxEntityChangeId(...a) }
+ };
+});
+
+// Control deferred + LOCALES precisely; keep everything else real from commons.
+vi.mock("../../../packages/commons/src", async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ deferred: <T,>() => makeDeferred<T>(),
+ get LOCALES() { return h.locales; }
+ };
+});
+
+vi.mock("@triliumnext/server/src/backup_provider.js", () => ({ default: class {} }));
+vi.mock("@triliumnext/server/src/cls_provider.js", () => ({ default: class {} }));
+vi.mock("@triliumnext/server/src/core_assets.js", () => ({ loadCoreSchema: vi.fn(() => ({})) }));
+vi.mock("@triliumnext/server/src/crypto_provider.js", () => ({ default: class {} }));
+vi.mock("@triliumnext/server/src/in_app_help_provider.js", () => ({ default: class {} }));
+vi.mock("@triliumnext/server/src/log_provider.js", () => ({ default: class {} }));
+vi.mock("@triliumnext/server/src/sql_provider.js", () => ({
+ default: class { loadFromFile = vi.fn(); }
+}));
+vi.mock("@triliumnext/server/src/zip_provider.js", () => ({ default: class {} }));
+
+vi.mock("@triliumnext/server/src/services/data_dir.js", () => ({
+ default: { TRILIUM_DATA_DIR: "/data", DOCUMENT_PATH: "/data/doc.db" }
+}));
+vi.mock("@triliumnext/server/src/services/port.js", () => ({ default: 37740 }));
+vi.mock("@triliumnext/server/src/services/resource_dir.js", () => ({ RESOURCE_DIR: "/res" }));
+vi.mock("@triliumnext/server/src/services/config.js", () => ({
+ default: { Security: {}, General: { readOnly: false } }
+}));
+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("./services/request", () => ({ default: class {} }));
+vi.mock("./services/window", () => ({
+ default: {
+ getLastFocusedWindow: () => h.lastFocusedWindow,
+ createExtraWindow: (...a: unknown[]) => h.createExtraWindow(...a),
+ createMainWindow: (...a: unknown[]) => h.createMainWindow(...a),
+ createSetupWindow: (...a: unknown[]) => h.createSetupWindow(...a),
+ registerGlobalShortcuts: (...a: unknown[]) => h.registerGlobalShortcuts(...a)
+ },
+ setupWindowing: vi.fn()
+}));
+vi.mock("./ipc_messaging_provider", () => ({ default: class { init = vi.fn(); } }));
+vi.mock("./platform_provider", () => ({ default: class {} }));
+vi.mock("./protocol", () => ({ registerTriliumAppScheme: vi.fn(), setupTriliumAppProtocol: vi.fn() }));
+vi.mock("./services/custom_dictionary", () => ({ setupCustomDictionary: vi.fn() }));
+vi.mock("./services/printing", () => ({ setupPrintingHandlers: vi.fn() }));
+vi.mock("./services/tray", () => ({ setupSystemTray: vi.fn() }));
+vi.mock("./services/shell", () => ({ setupShellHandlers: vi.fn() }));
+vi.mock("./services/security_settings", () => ({
+ getSecuritySettings: () => h.securitySettings,
+ registerSecurityIpcHandlers: vi.fn()
+}));
+
+const realPlatform = process.platform;
+function setPlatform(platform: NodeJS.Platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+let exitSpy: ReturnType<typeof vi.spyOn>;
+let stdoutOnSpy: ReturnType<typeof vi.spyOn>;
+let stderrOnSpy: ReturnType<typeof vi.spyOn>;
+
+function resetState() {
+ h.appOn.clear();
+ h.streamErrorHandlers.length = 0;
+ h.appendSwitch.mockClear();
+ h.setName.mockClear();
+ h.quit.mockClear();
+ h.exit.mockClear();
+ h.setPath.mockClear();
+ h.squirrel.default = false;
+ h.isPrimaryInstance = true;
+ h.allWindows = [];
+ h.smoothScroll = "true";
+ h.isDbInitialized = true;
+ h.securitySettings = {};
+ h.lastFocusedWindow = null;
+ h.entityChangeIds = [];
+ h.locale = null;
+ h.formattingLocale = null;
+ h.locales = [];
+ h.initConfig = undefined;
+ h.sendTransactionEntityChangesToAllClients.mockClear();
+ h.beccaLoad.mockClear();
+ h.recalculateMaxEntityChangeId.mockClear();
+ h.banner.mockClear();
+ h.createMainWindow.mockClear();
+ h.createSetupWindow.mockClear();
+ h.createExtraWindow.mockClear();
+ h.registerGlobalShortcuts.mockClear();
+ h.unregisterAll.mockClear();
+}
+
+beforeEach(() => {
+ process.env.TRILIUM_UNIT_TEST = "1";
+ vi.resetModules();
+ resetState();
+
+ exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
+ throw new Error("__exit__");
+ }) as never);
+
+ // Capture stream "error" handlers registered by main().
+ stdoutOnSpy = vi.spyOn(process.stdout, "on").mockImplementation(((event: string, cb: Handler) => {
+ if (event === "error") h.streamErrorHandlers.push(cb);
+ return process.stdout;
+ }) as never);
+ stderrOnSpy = vi.spyOn(process.stderr, "on").mockImplementation(((event: string, cb: Handler) => {
+ if (event === "error") h.streamErrorHandlers.push(cb);
+ return process.stderr;
+ }) as never);
+});
+
+afterEach(() => {
+ exitSpy.mockRestore();
+ stdoutOnSpy.mockRestore();
+ stderrOnSpy.mockRestore();
+ setPlatform(realPlatform);
+ delete process.env.TRILIUM_ELECTRON_DATA_DIR;
+});
+
+afterAll(() => {
+ delete process.env.TRILIUM_UNIT_TEST;
+ setPlatform(realPlatform);
+});
+
+async function importMain() {
+ return await import("./main.js");
+}
+
+describe("main() bootstrap", () => {
+ it("boots as the primary instance and wires up the full dependency graph", async () => {
+ setPlatform("linux");
+ h.smoothScroll = "false";
+ const { main } = await importMain();
+ await main();
+
+ // Streams got an error handler; squirrel false → no exit.
+ expect(h.streamErrorHandlers.length).toBe(2);
+ expect(exitSpy).not.toHaveBeenCalled();
+
+ // Smooth-scroll disabled + linux switches + lang switch were appended.
+ const switches = h.appendSwitch.mock.calls.map((c) => c[0]);
+ expect(switches).toContain("disable-smooth-scrolling");
+ expect(switches).toContain("gtk-version");
+ expect(switches).toContain("enable-features");
+ expect(switches).toContain("lang");
+ expect(switches).toContain("disable-http-cache"); // TRILIUM_ENV=dev by vitest config
+ expect(h.setName).toHaveBeenCalled(); // linux → app.setName(PRODUCT_NAME)
+
+ // The server-init handlers are registered.
+ expect(h.appOn.has("window-all-closed")).toBe(true);
+ expect(h.appOn.has("ready")).toBe(true);
+ expect(h.appOn.has("will-quit")).toBe(true);
+ expect(h.appOn.has("second-instance")).toBe(true);
+ });
+
+ it("appends no disable-http-cache switch when TRILIUM_ENV is not dev, and skips smooth-scroll switch when enabled", async () => {
+ const prev = process.env.TRILIUM_ENV;
+ delete process.env.TRILIUM_ENV;
+ setPlatform("darwin");
+ h.smoothScroll = "true";
+ try {
+ const { main } = await importMain();
+ await main();
+ } finally {
+ if (prev !== undefined) process.env.TRILIUM_ENV = prev;
+ }
+ const switches = h.appendSwitch.mock.calls.map((c) => c[0]);
+ expect(switches).not.toContain("disable-http-cache");
+ expect(switches).not.toContain("disable-smooth-scrolling");
+ expect(switches).not.toContain("gtk-version"); // non-linux
+ expect(h.setName).not.toHaveBeenCalled();
+ });
+
+ it("exits when it is not the primary instance", async () => {
+ h.isPrimaryInstance = false;
+ const { main } = await importMain();
+ await expect(main()).rejects.toThrow("__exit__");
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ });
+});
+
+describe("stream EPIPE error handler", () => {
+ it("swallows EPIPE errors and rethrows everything else", async () => {
+ const { main } = await importMain();
+ await main();
+ const handler = h.streamErrorHandlers[0];
+ expect(handler).toBeDefined();
+ // EPIPE → swallowed.
+ expect(() => handler({ code: "EPIPE" })).not.toThrow();
+ // Anything else → rethrown.
+ expect(() => handler({ code: "EOTHER" })).toThrow();
+ });
+});
+
+describe("app event handlers", () => {
+ async function bootAndReady() {
+ const { main } = await importMain();
+ await main();
+ return main;
+ }
+
+ it("window-all-closed quits except on macOS", async () => {
+ await bootAndReady();
+ const handler = h.appOn.get("window-all-closed");
+ expect(handler).toBeDefined();
+ if (!handler) return;
+
+ setPlatform("darwin");
+ handler();
+ expect(h.quit).not.toHaveBeenCalled();
+
+ setPlatform("linux");
+ handler();
+ expect(h.quit).toHaveBeenCalledTimes(1);
+ });
+
+ it("will-quit unregisters global shortcuts", async () => {
+ await bootAndReady();
+ const handler = h.appOn.get("will-quit");
+ expect(handler).toBeDefined();
+ handler?.();
+ expect(h.unregisterAll).toHaveBeenCalled();
+ });
+
+ describe("second-instance", () => {
+ it("creates an extra window when --new-window is passed", async () => {
+ await bootAndReady();
+ const handler = h.appOn.get("second-instance");
+ handler?.({}, ["--new-window"]);
+ expect(h.createExtraWindow).toHaveBeenCalledWith("");
+ });
+
+ it("restores, shows and focuses a minimized last-focused window", async () => {
+ const restore = vi.fn();
+ const show = vi.fn();
+ const focus = vi.fn();
+ h.lastFocusedWindow = { isMinimized: () => true, restore, show, focus };
+ await bootAndReady();
+ const handler = h.appOn.get("second-instance");
+ handler?.({}, []);
+ expect(restore).toHaveBeenCalled();
+ expect(show).toHaveBeenCalled();
+ expect(focus).toHaveBeenCalled();
+ });
+
+ it("shows and focuses a non-minimized last-focused window without restoring", async () => {
+ const restore = vi.fn();
+ const show = vi.fn();
+ const focus = vi.fn();
+ h.lastFocusedWindow = { isMinimized: () => false, restore, show, focus };
+ await bootAndReady();
+ const handler = h.appOn.get("second-instance");
+ handler?.({}, []);
+ expect(restore).not.toHaveBeenCalled();
+ expect(show).toHaveBeenCalled();
+ expect(focus).toHaveBeenCalled();
+ });
+
+ it("does nothing when there is no last-focused window", async () => {
+ h.lastFocusedWindow = null;
+ await bootAndReady();
+ const handler = h.appOn.get("second-instance");
+ expect(() => handler?.({}, [])).not.toThrow();
+ expect(h.createExtraWindow).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("ready / onReady", () => {
+ it("creates the main window and registers activate on macOS when the DB is initialized", async () => {
+ h.isDbInitialized = true;
+ setPlatform("darwin");
+ await bootAndReady();
+
+ const ready = h.appOn.get("ready");
+ expect(ready).toBeDefined();
+ await ready?.();
+
+ expect(h.createMainWindow).toHaveBeenCalledTimes(1);
+ expect(h.registerGlobalShortcuts).toHaveBeenCalled();
+
+ // The "activate" handler is registered on darwin.
+ const activate = h.appOn.get("activate");
+ expect(activate).toBeDefined();
+
+ // No windows → create another main window.
+ h.allWindows = [];
+ await activate?.();
+ expect(h.createMainWindow).toHaveBeenCalledTimes(2);
+
+ // Existing windows → do not create another.
+ h.allWindows = [{}];
+ await activate?.();
+ expect(h.createMainWindow).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not register activate on non-darwin even when DB is initialized", async () => {
+ h.isDbInitialized = true;
+ setPlatform("linux");
+ await bootAndReady();
+ const ready = h.appOn.get("ready");
+ await ready?.();
+ expect(h.createMainWindow).toHaveBeenCalledTimes(1);
+ expect(h.appOn.has("activate")).toBe(false);
+ });
+
+ it("opens the setup window and banners when the DB is not initialized", async () => {
+ h.isDbInitialized = false;
+ await bootAndReady();
+ const ready = h.appOn.get("ready");
+ await ready?.();
+ expect(h.banner).toHaveBeenCalled();
+ expect(h.createSetupWindow).toHaveBeenCalled();
+ expect(h.createMainWindow).not.toHaveBeenCalled();
+ });
+ });
+});
+
+describe("security settings override", () => {
+ it("leaves config untouched when no overrides are provided", async () => {
+ h.securitySettings = {};
+ const { main } = await importMain();
+ await main();
+ const config = (await import("@triliumnext/server/src/services/config.js")).default;
+ expect(config.Security).toEqual({});
+ });
+
+ it("applies backendScriptingEnabled and sqlConsoleEnabled overrides", async () => {
+ h.securitySettings = { backendScriptingEnabled: true, sqlConsoleEnabled: true };
+ const { main } = await importMain();
+ await main();
+ const config = (await import("@triliumnext/server/src/services/config.js")).default as {
+ Security: { backendScriptingEnabled?: boolean; sqlConsoleEnabled?: boolean };
+ };
+ expect(config.Security.backendScriptingEnabled).toBe(true);
+ expect(config.Security.sqlConsoleEnabled).toBe(true);
+ });
+});
+
+describe("initializeCore dbConfig callbacks + getDemoArchive", () => {
+ it("commit relays entity changes; rollback reloads becca only when dirtied", async () => {
+ const { main } = await importMain();
+ await main();
+
+ const config = h.initConfig;
+ expect(config).toBeDefined();
+ if (!config) return;
+
+ const dbConfig = config.dbConfig as {
+ onTransactionCommit: () => Promise<void>;
+ onTransactionRollback: () => Promise<void>;
+ };
+ const getDemoArchive = config.getDemoArchive as () => Promise<Buffer>;
+
+ await dbConfig.onTransactionCommit();
+ expect(h.sendTransactionEntityChangesToAllClients).toHaveBeenCalled();
+
+ // No dirtied entity changes → no becca reload.
+ h.entityChangeIds = [];
+ await dbConfig.onTransactionRollback();
+ expect(h.beccaLoad).not.toHaveBeenCalled();
+ expect(h.recalculateMaxEntityChangeId).toHaveBeenCalledTimes(1);
+
+ // Dirtied entity changes → becca reload.
+ h.entityChangeIds = ["x"];
+ await dbConfig.onTransactionRollback();
+ expect(h.beccaLoad).toHaveBeenCalledTimes(1);
+ expect(h.recalculateMaxEntityChangeId).toHaveBeenCalledTimes(2);
+
+ // getDemoArchive reads the demo zip.
+ const archive = await getDemoArchive();
+ expect(archive).toBeInstanceOf(Buffer);
+ });
+});
+
+describe("getUserData()", () => {
+ it("resolves TRILIUM_ELECTRON_DATA_DIR when set", async () => {
+ process.env.TRILIUM_ELECTRON_DATA_DIR = "portable/dir";
+ const { getUserData } = await importMain();
+ const result = getUserData();
+ expect(result).toContain("portable");
+ expect(result).toContain("dir");
+ });
+
+ it("joins appData with name-port when the env var is unset", async () => {
+ delete process.env.TRILIUM_ELECTRON_DATA_DIR;
+ const { getUserData } = await importMain();
+ expect(getUserData()).toBe("/appData/Trilium-37740");
+ });
+});
+
+describe("getElectronLocale()", () => {
+ it("returns the formatting locale when its corresponding UI locale is not RTL", async () => {
+ h.locale = "en";
+ h.formattingLocale = "de";
+ h.locales = [{ id: "en", rtl: false }];
+ const { getElectronLocale } = await importMain();
+ expect(getElectronLocale()).toBe("de");
+ });
+
+ it("falls back to the UI locale when the corresponding locale is RTL", async () => {
+ h.locale = "ar";
+ h.formattingLocale = "de";
+ h.locales = [{ id: "ar", rtl: true }];
+ const { getElectronLocale } = await importMain();
+ expect(getElectronLocale()).toBe("ar");
+ });
+
+ it("returns the UI locale when there is no formatting locale", async () => {
+ h.locale = "fr";
+ h.formattingLocale = null;
+ h.locales = [{ id: "fr", rtl: false }];
+ const { getElectronLocale } = await importMain();
+ expect(getElectronLocale()).toBe("fr");
+ });
+
+ it("defaults to 'en' when neither locale is set", async () => {
+ h.locale = null;
+ h.formattingLocale = null;
+ h.locales = [];
+ const { getElectronLocale } = await importMain();
+ expect(getElectronLocale()).toBe("en");
+ });
+});
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 500103c00f..3bd10426da 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -30,7 +30,7 @@ import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/sec
import { setupShellHandlers } from "./services/shell";
import { setupSystemTray } from "./services/tray";
-async function main() {
+export async function main() {
// 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]) {
@@ -49,6 +49,7 @@ async function main() {
const serverInitializedPromise = deferred<void>();
// 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 */
if ((require("electron-squirrel-startup")).default) {
process.exit(0);
}
@@ -217,7 +218,7 @@ async function main() {
* When running in portable mode, set TRILIUM_ELECTRON_DATA_DIR (e.g. via the trilium-portable script)
* so that no Electron files are written to the system's roaming profile (e.g. %APPDATA% on Windows).
*/
-function getUserData() {
+export function getUserData() {
if (process.env.TRILIUM_ELECTRON_DATA_DIR) {
return resolve(process.env.TRILIUM_ELECTRON_DATA_DIR);
}
@@ -250,7 +251,7 @@ async function onReady() {
await windowService.registerGlobalShortcuts();
}
-function getElectronLocale() {
+export function getElectronLocale() {
const uiLocale = options.getOptionOrNull("locale");
const formattingLocale = options.getOptionOrNull("formattingLocale");
const correspondingLocale = LOCALES.find(l => l.id === uiLocale);
@@ -261,4 +262,7 @@ function getElectronLocale() {
return uiLocale || "en";
}
-main();
+/* v8 ignore next 3 -- auto-start guard; unit tests import and invoke main() explicitly */
+if (process.env.TRILIUM_UNIT_TEST !== "1") {
+ main();
+}
diff --git a/apps/desktop/src/platform_provider.spec.ts b/apps/desktop/src/platform_provider.spec.ts
new file mode 100644
index 0000000000..d41508c237
--- /dev/null
+++ b/apps/desktop/src/platform_provider.spec.ts
@@ -0,0 +1,110 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const showErrorBox = vi.fn();
+const exit = vi.fn();
+const requestSingleInstanceLock = vi.fn(() => true);
+
+vi.mock("electron", () => ({
+ default: {
+ dialog: { showErrorBox: (...args: unknown[]) => showErrorBox(...args) },
+ app: {
+ exit: (...args: unknown[]) => exit(...args),
+ requestSingleInstanceLock: () => requestSingleInstanceLock()
+ }
+ }
+}));
+
+// `t()` throws until translations are initialised; stub it so `crash` can build
+// its dialog title without spinning up core.
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ t: (key: string) => key
+ };
+});
+
+const { default: DesktopPlatformProvider } = await import("./platform_provider.js");
+
+function withPlatform(platform: NodeJS.Platform, fn: () => void) {
+ const original = process.platform;
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+ try {
+ fn();
+ } finally {
+ Object.defineProperty(process, "platform", { value: original, configurable: true });
+ }
+}
+
+describe("DesktopPlatformProvider", () => {
+ afterEach(() => {
+ vi.clearAllMocks();
+ requestSingleInstanceLock.mockReturnValue(true);
+ });
+
+ it("always reports as Electron and derives isMac / isWindows from process.platform", () => {
+ withPlatform("darwin", () => {
+ const p = new DesktopPlatformProvider();
+ expect(p.isElectron).toBe(true);
+ expect(p.isMac).toBe(true);
+ expect(p.isWindows).toBe(false);
+ });
+ withPlatform("win32", () => {
+ const p = new DesktopPlatformProvider();
+ expect(p.isMac).toBe(false);
+ expect(p.isWindows).toBe(true);
+ });
+ withPlatform("linux", () => {
+ const p = new DesktopPlatformProvider();
+ expect(p.isMac).toBe(false);
+ expect(p.isWindows).toBe(false);
+ });
+ });
+
+ it("crash shows an error box and exits with code 1", () => {
+ const p = new DesktopPlatformProvider();
+ p.crash("boom");
+ expect(showErrorBox).toHaveBeenCalledWith("modals.error_title", "boom");
+ expect(exit).toHaveBeenCalledWith(1);
+ });
+
+ it("getEnv reads from process.env", () => {
+ const p = new DesktopPlatformProvider();
+ process.env.TRILIUM_PLATFORM_PROVIDER_TEST = "value";
+ try {
+ expect(p.getEnv("TRILIUM_PLATFORM_PROVIDER_TEST")).toBe("value");
+ expect(p.getEnv("DOES_NOT_EXIST_TRILIUM")).toBeUndefined();
+ } finally {
+ delete process.env.TRILIUM_PLATFORM_PROVIDER_TEST;
+ }
+ });
+
+ describe("shouldIgnoreStartupError", () => {
+ const provider = new DesktopPlatformProvider();
+ const eaddrinuse = { code: "EADDRINUSE" } as NodeJS.ErrnoException;
+
+ it("ignores anything other than EADDRINUSE", () => {
+ expect(provider.shouldIgnoreStartupError({ code: "EACCES" } as NodeJS.ErrnoException)).toBe(false);
+ });
+
+ it("tolerates EADDRINUSE when launched with --new-window", () => {
+ const original = process.argv;
+ process.argv = [...original, "--new-window"];
+ try {
+ expect(provider.shouldIgnoreStartupError(eaddrinuse)).toBe(true);
+ } finally {
+ process.argv = original;
+ }
+ });
+
+ it("tolerates EADDRINUSE when the single-instance lock was lost", () => {
+ requestSingleInstanceLock.mockReturnValue(false);
+ expect(provider.shouldIgnoreStartupError(eaddrinuse)).toBe(true);
+ });
+
+ it("surfaces EADDRINUSE for the primary instance without --new-window", () => {
+ requestSingleInstanceLock.mockReturnValue(true);
+ expect(provider.shouldIgnoreStartupError(eaddrinuse)).toBe(false);
+ });
+ });
+});
diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.ts
index f7635318b5..0ba7fc8ba5 100644
--- a/apps/desktop/src/preload.spec.ts
+++ b/apps/desktop/src/preload.spec.ts
@@ -481,6 +481,15 @@ describe("preload script", () => {
expect(callback).toHaveBeenCalled();
});
+ it("onDidNavigateInPage registers and forwards did-navigate-in-page channel", () => {
+ const callback = vi.fn();
+ nav().onDidNavigateInPage(callback);
+ const listeners = ipcRendererListeners.get("did-navigate-in-page")!;
+ expect(listeners).toHaveLength(1);
+ listeners[0]();
+ expect(callback).toHaveBeenCalled();
+ });
+
it("removeDidNavigateListeners clears both navigation listeners", () => {
nav().onDidNavigate(vi.fn());
nav().onDidNavigateInPage(vi.fn());
@@ -528,4 +537,18 @@ describe("preload script", () => {
expect(second).toHaveBeenCalledWith({ type: "toast", message: "hi" });
});
});
+
+ describe("security", () => {
+ const security = () => getGroup("security");
+
+ it("setBackendScriptingEnabled invokes the corresponding IPC channel", async () => {
+ await security().setBackendScriptingEnabled(true);
+ expect(ipcRendererInvoked).toContainEqual({ channel: "security-set-backend-scripting", args: [true] });
+ });
+
+ it("setSqlConsoleEnabled invokes the corresponding IPC channel", async () => {
+ await security().setSqlConsoleEnabled(false);
+ expect(ipcRendererInvoked).toContainEqual({ channel: "security-set-sql-console", args: [false] });
+ });
+ });
});
diff --git a/apps/desktop/src/protocol.spec.ts b/apps/desktop/src/protocol.spec.ts
index b68bec3785..66407a3a1b 100644
--- a/apps/desktop/src/protocol.spec.ts
+++ b/apps/desktop/src/protocol.spec.ts
@@ -2,14 +2,20 @@ import express from "express";
import multer from "multer";
import { describe, expect, it, vi } from "vitest";
+const electronMock = vi.hoisted(() => ({
+ registerSchemesAsPrivileged: vi.fn(),
+ handle: vi.fn()
+}));
+
vi.mock("electron", () => ({
default: {
app: { whenReady: () => Promise.resolve() },
- protocol: { handle: () => {} }
- }
+ protocol: { handle: electronMock.handle }
+ },
+ protocol: { registerSchemesAsPrivileged: electronMock.registerSchemesAsPrivileged }
}));
-const { dispatch } = await import("./protocol.js");
+const { dispatch, registerTriliumAppScheme, setupTriliumAppProtocol } = await import("./protocol.js");
const { isInternalElectronRequest } = await import("@triliumnext/server/src/services/electron_request.js");
function buildTestApp() {
@@ -205,6 +211,214 @@ describe("trilium-app protocol dispatcher", () => {
await expect(reader.read()).rejects.toThrow();
});
+ it("returns a 500 Response when dispatch throws inside the protocol handler", async () => {
+ electronMock.handle.mockReset();
+ setupTriliumAppProtocol(express());
+ await Promise.resolve(); // let whenReady().then(...) run
+
+ expect(electronMock.handle).toHaveBeenCalledWith("trilium-app", expect.any(Function));
+ const handler = electronMock.handle.mock.calls[0][1] as (req: Request) => Promise<Response>;
+
+ // A malformed URL makes `new URL(request.url)` throw inside dispatch;
+ // the handler must convert that into a 500 rather than rejecting.
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const response = await handler({ url: "::::not-a-url", method: "GET", headers: new Headers(), signal: null } as unknown as Request);
+ errorSpy.mockRestore();
+
+ expect(response.status).toBe(500);
+ expect(await response.text()).toBe("Internal Server Error");
+ });
+
+ 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")));
+
+ await expect(dispatch(app, new Request("trilium-app://app/boom"))).rejects.toThrow(/downstream failure/);
+ });
+
+ it("rejects (buffered path) when the response status is out of the Response range", async () => {
+ const app = express();
+ app.get("/bad", (_req, res) => {
+ res.statusCode = 999; // RangeError inside the Fetch Response constructor
+ res.end("x");
+ });
+
+ await expect(dispatch(app, new Request("trilium-app://app/bad"))).rejects.toThrow();
+ });
+
+ it("rejects (streaming path) when flushHeaders commits an out-of-range status", async () => {
+ const app = express();
+ app.get("/bad-stream", (_req, res) => {
+ res.statusCode = 999;
+ res.flushHeaders();
+ res.end();
+ });
+
+ await expect(dispatch(app, new Request("trilium-app://app/bad-stream"))).rejects.toThrow();
+ });
+
+ it("rejects when the Express app throws synchronously", async () => {
+ const app = () => { throw new Error("sync explosion"); };
+ await expect(dispatch(app as never, new Request("trilium-app://app/x"))).rejects.toThrow(/sync explosion/);
+ });
+
+ it("emits one header entry per value for multi-valued response headers", async () => {
+ const app = express();
+ app.get("/multi", (_req, res) => {
+ // Set-Cookie is the canonical header Express keeps as an array in getHeaders().
+ res.setHeader("Set-Cookie", ["a=1", "b=2"]);
+ res.send("ok");
+ });
+
+ const response = await dispatch(app, new Request("trilium-app://app/multi"));
+ expect(response.headers.getSetCookie()).toEqual(["a=1", "b=2"]);
+ });
+
+ it("passes binary buffer responses through untouched", async () => {
+ // Force the mock to expose a non-empty `_getBuffer` so the buffered
+ // branch picks the raw buffer rather than `_getData`.
+ type FakeRes = { statusCode: number; _getData: () => unknown; _getBuffer: () => Buffer; end: () => void };
+ const app = (_req: object, res: FakeRes) => {
+ res.statusCode = 200;
+ res._getData = () => "";
+ res._getBuffer = () => Buffer.from([1, 2, 3, 4]);
+ res.end();
+ };
+
+ const response = await dispatch(app as never, new Request("trilium-app://app/bin"));
+ expect(new Uint8Array(await response.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3, 4]));
+ });
+
+ it("ignores a fetch abort that fires after a buffered response already completed", async () => {
+ const app = express();
+ app.get("/done", (_req, res) => res.send("done"));
+
+ const ac = new AbortController();
+ const response = await dispatch(app, new Request("trilium-app://app/done", { signal: ac.signal }));
+ expect(await response.text()).toBe("done");
+ // Late abort: the bridge's abort listener runs with streaming === false
+ // and must be a no-op.
+ ac.abort();
+ });
+
+ it("returns a null-body Response for null-body status codes", async () => {
+ const app = express();
+ app.get("/nc", (_req, res) => res.status(204).send());
+
+ const response = await dispatch(app, new Request("trilium-app://app/nc"));
+ expect(response.status).toBe(204);
+ expect(response.body).toBeNull();
+ });
+
+ it("drops hop-by-hop / transport headers from the response", async () => {
+ const app = express();
+ app.get("/stripped", (_req, res) => {
+ res.setHeader("Connection", "keep-alive");
+ res.send("ok");
+ });
+
+ const response = await dispatch(app, new Request("trilium-app://app/stripped"));
+ expect(response.headers.has("connection")).toBe(false);
+ });
+
+ it("wraps a non-Error value forwarded to next()", async () => {
+ const app = express();
+ app.get("/weird", (_req, _res, next) => next("string failure"));
+
+ await expect(dispatch(app, new Request("trilium-app://app/weird"))).rejects.toBeDefined();
+ });
+
+ it("returns an empty body when the buffered payload is null", async () => {
+ type FakeRes = { statusCode: number; _getData: () => unknown; _getBuffer: () => null; end: () => void };
+ const app = (_req: object, res: FakeRes) => {
+ res.statusCode = 200;
+ res._getData = () => null;
+ res._getBuffer = () => null;
+ res.end();
+ };
+ const response = await dispatch(app as never, new Request("trilium-app://app/empty"));
+ expect(await response.text()).toBe("");
+ });
+
+ it("falls back to _getData when the buffer is present but empty", async () => {
+ type FakeRes = { statusCode: number; _getData: () => unknown; _getBuffer: () => Buffer; end: () => void };
+ const app = (_req: object, res: FakeRes) => {
+ res.statusCode = 200;
+ res._getData = () => "from-data";
+ res._getBuffer = () => Buffer.alloc(0); // truthy buffer, zero length
+ res.end();
+ };
+ const response = await dispatch(app as never, new Request("trilium-app://app/emptybuf"));
+ expect(await response.text()).toBe("from-data");
+ });
+
+ it("tolerates upstream writes after a consumer abort tore the stream down", async () => {
+ const app = express();
+ let releaseTail: (() => void) | undefined;
+ const tail = new Promise<void>((r) => { releaseTail = r; });
+
+ app.get("/race", async (_req, res) => {
+ res.setHeader("Content-Type", "text/event-stream");
+ res.flushHeaders();
+ res.write("a\n");
+ await tail;
+ // After the abort below has nulled the controller, these must be
+ // inert no-ops rather than throwing.
+ res.write("b\n");
+ res.end();
+ });
+
+ const ac = new AbortController();
+ const response = await dispatch(app, new Request("trilium-app://app/race", { signal: ac.signal }));
+ const reader = response.body?.getReader();
+ if (!reader) throw new Error("expected a streaming body");
+ expect(new TextDecoder().decode((await reader.read()).value)).toBe("a\n");
+
+ ac.abort();
+ await expect(reader.read()).rejects.toThrow();
+
+ releaseTail?.();
+ await tail; // let the handler's post-abort writes run
+ });
+
+ it("serialises object and primitive response payloads to bytes", async () => {
+ // Express always stringifies objects/primitives before they reach the
+ // mock's buffer, so force the buffered branch to read a raw object /
+ // number out of `res._getData()` to exercise toUint8Array's fallbacks.
+ type FakeRes = { statusCode: number; _getData: () => unknown; _getBuffer: () => null; end: () => void };
+ const appReturning = (payload: unknown) => (_req: object, res: FakeRes) => {
+ res.statusCode = 200;
+ res._getData = () => payload;
+ res._getBuffer = () => null;
+ res.end();
+ };
+
+ const objResponse = await dispatch(appReturning({ hello: "world" }) as never, new Request("trilium-app://app/obj"));
+ expect(await objResponse.json()).toEqual({ hello: "world" });
+
+ const numResponse = await dispatch(appReturning(42) as never, new Request("trilium-app://app/num"));
+ expect(await numResponse.text()).toBe("42");
+ });
+
+ it("skips the request body for GET / HEAD and bodyless requests", async () => {
+ const app = express();
+ app.get("/get", (_req, res) => res.send("g"));
+ app.head("/head", (_req, res) => res.end());
+
+ expect(await (await dispatch(app, new Request("trilium-app://app/get"))).text()).toBe("g");
+ expect((await dispatch(app, new Request("trilium-app://app/head", { method: "HEAD" }))).status).toBe(200);
+ });
+
+ it("registerTriliumAppScheme declares the privileged custom scheme", () => {
+ registerTriliumAppScheme();
+ expect(electronMock.registerSchemesAsPrivileged).toHaveBeenCalledWith([
+ expect.objectContaining({
+ scheme: "trilium-app",
+ privileges: expect.objectContaining({ standard: true, secure: true, supportFetchAPI: true, corsEnabled: true })
+ })
+ ]);
+ });
+
it("does NOT tag plain Express requests with the internal-electron marker", () => {
// Anything that didn't come through `dispatch()` — i.e. a real HTTP
// request to the TCP listener, or an arbitrary attacker-controlled
diff --git a/apps/desktop/src/protocol.ts b/apps/desktop/src/protocol.ts
index 11649586b0..bec966aea9 100644
--- a/apps/desktop/src/protocol.ts
+++ b/apps/desktop/src/protocol.ts
@@ -95,6 +95,7 @@ export async function dispatch(app: Application, request: Request): Promise<Resp
res.on("end", () => {
if (bridge.isStreaming) return; // streaming path already resolved
const getBuffer = (res as { _getBuffer?: () => Buffer | null })._getBuffer;
+ /* v8 ignore next -- defensive: node-mocks-http always provides _getBuffer */
const buf = typeof getBuffer === "function" ? getBuffer.call(res) : null;
const data = res._getData();
const rawPayload = buf && buf.length > 0 ? buf : data;
@@ -117,6 +118,10 @@ export async function dispatch(app: Application, request: Request): Promise<Resp
req,
res,
(err) => {
+ // The no-error invocation is the unmatched-route (404) case,
+ // which never happens for the real app and would hang here;
+ // only the error path is reachable.
+ /* v8 ignore next */
if (err) {
bridge.abort(err instanceof Error ? err : new Error(String(err)));
reject(err);
@@ -173,6 +178,7 @@ function installStreamingBridge(
});
try {
onCommit(new Response(body, {
+ /* v8 ignore next -- defensive: statusCode is always set before flushHeaders */
status: res.statusCode || 200,
headers: normalizeResponseHeaders(res.getHeaders())
}));
@@ -188,12 +194,14 @@ function installStreamingBridge(
function closeStream() {
if (!controller) return;
+ /* v8 ignore next -- defensive: close() only throws if the stream was already torn down by a consumer cancel race */
try { controller.close(); } catch { /* already closed */ }
controller = null;
}
function errorStream(reason: Error) {
if (!controller) return;
+ /* v8 ignore next -- defensive: error() only throws if the stream was already closed by a consumer cancel race */
try { controller.error(reason); } catch { /* already closed */ }
controller = null;
}
@@ -269,6 +277,9 @@ function buildIncomingRequest(opts: BuildRequestOpts): object {
const buffer = opts.bodyBuffer;
const stream = new Readable({
read() {
+ // read() is only pulled when there is a body to deliver, so the
+ // empty/absent-buffer side of this guard isn't reachable here.
+ /* v8 ignore next */
if (buffer && buffer.length > 0) {
this.push(buffer);
}
@@ -284,6 +295,7 @@ function buildIncomingRequest(opts: BuildRequestOpts): object {
stream.on("end", () => { stream.complete = true; });
(stream as unknown as Record<string, unknown>)._destroy = (_err: Error | null, cb: (err?: Error | null) => void) => cb();
+ /* v8 ignore next -- no-op socket shims for Express middleware that may probe the connection but never does in dispatch */
const socket = { remoteAddress: "127.0.0.1", encrypted: false, readable: true, destroy() {}, end() {}, on() {}, removeListener() {} };
const req = Object.assign(stream, {
@@ -342,6 +354,7 @@ const STRIPPED_HEADERS = new Set([
function normalizeResponseHeaders(headers: Record<string, number | string | string[] | undefined>): [string, string][] {
const out: [string, string][] = [];
for (const [name, value] of Object.entries(headers)) {
+ /* v8 ignore next -- defensive: getHeaders() never yields undefined values */
if (value === undefined) continue;
if (STRIPPED_HEADERS.has(name.toLowerCase())) continue;
if (Array.isArray(value)) {
diff --git a/apps/desktop/src/services/custom_dictionary.spec.ts b/apps/desktop/src/services/custom_dictionary.spec.ts
index 1b3051dd4c..5c4bd430b8 100644
--- a/apps/desktop/src/services/custom_dictionary.spec.ts
+++ b/apps/desktop/src/services/custom_dictionary.spec.ts
@@ -3,27 +3,38 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const { buildNote } = becca_easy_mocking;
+// Mutable test state for the core stubs (db-initialised / spellcheck-enabled
+// gates in `setupCustomDictionary`) plus captured IPC / app event handlers.
+const state = vi.hoisted(() => ({
+ dbInitialized: true,
+ spellCheckEnabled: true,
+ appHandlers: new Map<string, (...args: unknown[]) => unknown>(),
+ ipcHandlers: new Map<string, (...args: unknown[]) => unknown>()
+}));
+
// `getLog()` throws when the log service hasn't been initialised via
// `initializeCore` — and we don't want to spin up core in unit tests just to
// satisfy a logger. Partial-mock core so `getLog` returns no-op stubs while
-// every other core export keeps its real implementation.
+// every other core export keeps its real implementation. `sql_init` and
+// `options` are stubbed so the setup gates are controllable.
vi.mock("@triliumnext/core", async (importOriginal) => {
const actual = await importOriginal<typeof import("@triliumnext/core")>();
return {
...actual,
- getLog: () => ({ info: vi.fn(), error: vi.fn() })
+ getLog: () => ({ info: vi.fn(), error: vi.fn() }),
+ sql_init: { ...actual.sql_init, isDbInitialized: () => state.dbInitialized },
+ options: { ...actual.options, getOptionBool: () => state.spellCheckEnabled }
};
});
// `custom_dictionary.ts` does `import electron from "electron"` at module load
// to register IPC handlers. On CI the `electron` package's entry point throws
// ("Electron failed to install correctly") because the binary isn't materialized.
-// `loadForSession` (the only thing exercised below) doesn't touch electron at
-// runtime, so empty stubs are enough.
+// Capture the registered handlers so the setup wiring can be exercised directly.
vi.mock("electron", () => ({
default: {
- ipcMain: { on: () => {} },
- app: { on: () => {} }
+ ipcMain: { on: (channel: string, fn: (...args: unknown[]) => unknown) => state.ipcHandlers.set(channel, fn) },
+ app: { on: (event: string, fn: (...args: unknown[]) => unknown) => state.appHandlers.set(event, fn) }
}
}));
@@ -176,4 +187,105 @@ describe("custom_dictionary", () => {
expect(session.addWordToSpellCheckerDictionary).not.toHaveBeenCalled();
});
});
+
+ describe("setupCustomDictionary — web-contents-created gate", () => {
+ beforeEach(() => {
+ state.dbInitialized = true;
+ state.spellCheckEnabled = true;
+ state.appHandlers.clear();
+ state.ipcHandlers.clear();
+ customDictionary.setupCustomDictionary();
+ });
+
+ function fireWebContentsCreated(session: unknown) {
+ const handler = state.appHandlers.get("web-contents-created");
+ if (!handler) throw new Error("web-contents-created not registered");
+ return handler({}, { session });
+ }
+
+ it("loads the dictionary into a new spellcheck-enabled session", async () => {
+ buildNote({ id: "_customDictionary", title: "Custom Dictionary", type: "code", content: "apple" });
+ const session = mockSession();
+
+ fireWebContentsCreated(session);
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("apple");
+ });
+
+ it("skips when the DB is not initialised", () => {
+ state.dbInitialized = false;
+ const session = mockSession();
+ fireWebContentsCreated(session);
+ expect(session.listWordsInSpellCheckerDictionary).not.toHaveBeenCalled();
+ });
+
+ it("skips when spellcheck is disabled", () => {
+ state.spellCheckEnabled = false;
+ const session = mockSession();
+ fireWebContentsCreated(session);
+ expect(session.listWordsInSpellCheckerDictionary).not.toHaveBeenCalled();
+ });
+
+ it("syncs each session only once", async () => {
+ const session = mockSession();
+ fireWebContentsCreated(session);
+ fireWebContentsCreated(session); // same session, must be a no-op
+ await new Promise((r) => setTimeout(r, 0));
+ expect(session.listWordsInSpellCheckerDictionary).toHaveBeenCalledTimes(1);
+ });
+
+ it("swallows load failures", async () => {
+ const session = mockSession();
+ session.listWordsInSpellCheckerDictionary.mockRejectedValue(new Error("boom"));
+ // Must not throw / reject.
+ fireWebContentsCreated(session);
+ await new Promise((r) => setTimeout(r, 0));
+ expect(session.listWordsInSpellCheckerDictionary).toHaveBeenCalled();
+ });
+ });
+
+ describe("setupCustomDictionary — add-word-to-dictionary IPC", () => {
+ beforeEach(() => {
+ state.ipcHandlers.clear();
+ state.appHandlers.clear();
+ becca.reset();
+ buildNote({ id: "_customDictionary", title: "Custom Dictionary", type: "code", content: "apple" });
+ customDictionary.setupCustomDictionary();
+ });
+
+ function addWord(word: unknown, session: unknown) {
+ const handler = state.ipcHandlers.get("add-word-to-dictionary");
+ if (!handler) throw new Error("add-word-to-dictionary not registered");
+ return handler({ sender: { session } }, word);
+ }
+
+ it("persists a valid word to both the local session and the note", () => {
+ const session = mockSession();
+ // easy-mock's getContent is a fixed closure, so spy on setContent
+ // to capture what gets written.
+ const setContent = vi.spyOn(becca.getNoteOrThrow("_customDictionary"), "setContent");
+
+ addWord("banana", session);
+
+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("banana");
+ // Existing "apple" + new "banana", saved sorted, one word per line.
+ expect(setContent).toHaveBeenCalledWith("apple\nbanana");
+ });
+
+ it("rejects non-string / empty payloads without side effects", () => {
+ const session = mockSession();
+ addWord(123, session);
+ addWord("", session);
+ expect(session.addWordToSpellCheckerDictionary).not.toHaveBeenCalled();
+ });
+
+ it("logs when the dictionary note is missing on save", () => {
+ becca.reset(); // remove the note so saveWords hits its error path
+ const session = mockSession();
+ // Must not throw even though the note is gone.
+ expect(() => addWord("banana", session)).not.toThrow();
+ expect(session.addWordToSpellCheckerDictionary).toHaveBeenCalledWith("banana");
+ });
+ });
});
diff --git a/apps/desktop/src/services/printing.spec.ts b/apps/desktop/src/services/printing.spec.ts
new file mode 100644
index 0000000000..b47ff9a4f6
--- /dev/null
+++ b/apps/desktop/src/services/printing.spec.ts
@@ -0,0 +1,388 @@
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+type Handler = (event: unknown, ...args: unknown[]) => unknown;
+
+const h = vi.hoisted(() => ({
+ on: new Map<string, Handler>(),
+ handle: new Map<string, Handler>(),
+ off: [] as Array<[string, unknown]>,
+ consoleHandlers: [] as Array<(event: { level: string }, message: string, line: number, sourceId: string) => void>,
+ loadURL: vi.fn((..._a: unknown[]) => Promise.resolve()),
+ executeJavaScript: vi.fn((..._a: unknown[]): Promise<unknown> => Promise.resolve("REPORT")),
+ print: vi.fn((_opts: unknown, cb: (success: boolean, reason?: string) => void) => cb(true)),
+ printToPDF: vi.fn((..._a: unknown[]) => Promise.resolve(Buffer.from("pdf-bytes"))),
+ destroy: vi.fn((..._a: unknown[]) => {}),
+ getPrintersAsync: vi.fn((..._a: unknown[]) => Promise.resolve([] as unknown[])),
+ showSaveDialogSync: vi.fn((..._a: unknown[]): string | undefined => "/out.pdf"),
+ showErrorBox: vi.fn((..._a: unknown[]) => {}),
+ openPath: vi.fn((..._a: unknown[]) => {}),
+ getFocusedWindow: vi.fn((..._a: unknown[]): unknown => ({})),
+ writeFile: vi.fn((..._a: unknown[]) => Promise.resolve()),
+ isDev: true as boolean,
+ lastBwOpts: undefined as unknown
+}));
+
+vi.mock("electron", () => {
+ const ipcMainObj = {
+ on: (channel: string, fn: Handler) => h.on.set(channel, fn),
+ off: (channel: string, fn: unknown) => h.off.push([channel, fn]),
+ handle: (channel: string, fn: Handler) => h.handle.set(channel, fn)
+ };
+ const webContents = {
+ on: (ev: string, cb: never) => { if (ev === "console-message") h.consoleHandlers.push(cb); },
+ executeJavaScript: (...a: unknown[]) => h.executeJavaScript(...a),
+ print: (...a: unknown[]) => (h.print as (...args: unknown[]) => unknown)(...a),
+ printToPDF: (...a: unknown[]) => h.printToPDF(...a)
+ };
+ class FakeBrowserWindow {
+ webContents = webContents;
+ loadURL = (...a: unknown[]) => h.loadURL(...a);
+ destroy = (...a: unknown[]) => h.destroy(...a);
+ constructor(opts: unknown) { h.lastBwOpts = opts; }
+ static getFocusedWindow = (...a: unknown[]) => h.getFocusedWindow(...a);
+ }
+ return {
+ default: {
+ BrowserWindow: FakeBrowserWindow,
+ ipcMain: ipcMainObj,
+ dialog: {
+ showSaveDialogSync: (...a: unknown[]) => h.showSaveDialogSync(...a),
+ showErrorBox: (...a: unknown[]) => h.showErrorBox(...a)
+ },
+ shell: { openPath: (...a: unknown[]) => h.openPath(...a) }
+ },
+ ipcMain: ipcMainObj
+ };
+});
+
+vi.mock("fs/promises", () => ({ default: { writeFile: (...a: unknown[]) => h.writeFile(...a) } }));
+vi.mock("i18next", () => ({ t: (key: string) => key }));
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => ({ info: vi.fn(), error: vi.fn() }),
+ utils: { ...actual.utils, isDev: () => h.isDev }
+ };
+});
+
+const printing = await import("./printing.js");
+
+const realPlatform = process.platform;
+function setPlatform(platform: NodeJS.Platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+function makeEvent() {
+ return {
+ sender: {
+ send: vi.fn(),
+ session: { id: 1 },
+ getPrintersAsync: (...a: unknown[]) => h.getPrintersAsync(...a)
+ }
+ };
+}
+
+async function fireOn(channel: string, payload: unknown) {
+ const fn = h.on.get(channel);
+ if (!fn) throw new Error(`no on-handler for ${channel}`);
+ const event = makeEvent();
+ await fn(event, payload);
+ return event;
+}
+
+const PDF_OPTS = {
+ notePath: "root/abc",
+ title: "My Note",
+ landscape: false,
+ pageSize: "A4" as const,
+ scale: 1,
+ margins: "default",
+ pageRanges: ""
+};
+
+describe("printing — pure helpers", () => {
+ describe("parseMargins", () => {
+ it("expands presets to uniform numeric margins (mm → inches)", () => {
+ expect(printing.parseMargins("default")).toMatchObject({ marginType: "custom", top: 20 / 25.4 });
+ expect(printing.parseMargins("")).toMatchObject({ top: 20 / 25.4 });
+ expect(printing.parseMargins("none")).toMatchObject({ top: 0 });
+ expect(printing.parseMargins("minimum")).toMatchObject({ top: 5 / 25.4 });
+ });
+
+ it("parses a four-part custom margin spec", () => {
+ expect(printing.parseMargins("10,20,30,40")).toEqual({
+ marginType: "custom",
+ top: 10 / 25.4,
+ right: 20 / 25.4,
+ bottom: 30 / 25.4,
+ left: 40 / 25.4
+ });
+ });
+
+ it("falls back to 1cm uniform for malformed specs", () => {
+ expect(printing.parseMargins("1,2,bad")).toMatchObject({ top: 10 / 25.4 });
+ });
+ });
+
+ describe("parsePageRangesForPrint", () => {
+ it("returns undefined for empty / whitespace input", () => {
+ expect(printing.parsePageRangesForPrint("")).toBeUndefined();
+ expect(printing.parsePageRangesForPrint(" ")).toBeUndefined();
+ });
+
+ it("parses ranges and single pages, skipping blanks and NaNs", () => {
+ expect(printing.parsePageRangesForPrint("1-5, 8, 11-13, , x-y")).toEqual([
+ { from: 1, to: 5 },
+ { from: 8, to: 8 },
+ { from: 11, to: 13 }
+ ]);
+ });
+
+ it("returns undefined when nothing parses", () => {
+ expect(printing.parsePageRangesForPrint("x, y-z")).toBeUndefined();
+ });
+ });
+});
+
+describe("setupPrintingHandlers", () => {
+ beforeAll(() => {
+ printing.setupPrintingHandlers();
+ });
+
+ beforeEach(() => {
+ h.on.delete("print-progress");
+ h.off.length = 0;
+ h.consoleHandlers.length = 0;
+ h.loadURL.mockReset().mockResolvedValue(undefined);
+ h.executeJavaScript.mockReset().mockResolvedValue("REPORT");
+ h.print.mockReset().mockImplementation((_opts, cb) => cb(true));
+ h.printToPDF.mockReset().mockResolvedValue(Buffer.from("pdf-bytes"));
+ h.destroy.mockReset();
+ h.getPrintersAsync.mockReset().mockResolvedValue([]);
+ h.showSaveDialogSync.mockReset().mockReturnValue("/out.pdf");
+ h.showErrorBox.mockReset();
+ h.openPath.mockReset();
+ h.getFocusedWindow.mockReset().mockReturnValue({});
+ h.writeFile.mockReset().mockResolvedValue(undefined);
+ h.isDev = true;
+ setPlatform(realPlatform);
+ });
+
+ afterEach(() => setPlatform(realPlatform));
+
+ describe("print-note", () => {
+ it("prints successfully and forwards the print report", async () => {
+ const e = await fireOn("print-note", { notePath: "root/abc" });
+ expect(h.print).toHaveBeenCalled();
+ expect(e.sender.send).toHaveBeenCalledWith("print-done", "REPORT");
+ expect(h.destroy).toHaveBeenCalled();
+ expect(h.showErrorBox).not.toHaveBeenCalled();
+ });
+
+ it("shows an error box on print failure but not on user cancel", async () => {
+ h.print.mockImplementation((_opts, cb) => cb(false, "spooler down"));
+ await fireOn("print-note", { notePath: "root/abc" });
+ expect(h.showErrorBox).toHaveBeenCalled();
+
+ h.showErrorBox.mockClear();
+ h.print.mockImplementation((_opts, cb) => cb(false, "Print job canceled"));
+ await fireOn("print-note", { notePath: "root/abc" });
+ expect(h.showErrorBox).not.toHaveBeenCalled();
+ });
+
+ it("reports an error payload when the print window fails to load", async () => {
+ h.loadURL.mockRejectedValue(new Error("load failed"));
+ const e = await fireOn("print-note", { notePath: "root/abc" });
+ expect(e.sender.send).toHaveBeenCalledWith("print-done", expect.objectContaining({ type: "error", message: "load failed" }));
+ });
+
+ it("uses offscreen rendering off Linux and forwards console output + progress", async () => {
+ setPlatform("darwin");
+ const e = await fireOn("print-note", { notePath: "root/abc" });
+ expect((h.lastBwOpts as { webPreferences: { offscreen: boolean } }).webPreferences.offscreen).toBe(true);
+
+ // Exercise the captured console-message handler at each log level.
+ const consoleHandler = h.consoleHandlers[0];
+ expect(consoleHandler).toBeDefined();
+ consoleHandler({ level: "debug" }, "dbg", 1, "s");
+ consoleHandler({ level: "error" }, "err", 2, "s");
+ consoleHandler({ level: "info" }, "info", 3, "s");
+
+ // Exercise the print-progress relay callback registered for this window.
+ const progress = h.on.get("print-progress");
+ expect(progress).toBeDefined();
+ progress?.({}, 42);
+ expect(e.sender.send).toHaveBeenCalledWith("print-progress", { progress: 42, action: "printing" });
+ });
+
+ it("stringifies a non-Error rejection in the error payload", async () => {
+ // Reject with a plain string so the `err instanceof Error` ternaries
+ // take their String(err) / undefined arms.
+ h.loadURL.mockRejectedValue("plain string failure");
+ const e = await fireOn("print-note", { notePath: "root/abc" });
+ expect(e.sender.send).toHaveBeenCalledWith("print-done", { type: "error", message: "plain string failure", stack: undefined });
+ });
+
+ it("survives a failed error-handler injection and a failed note-ready wait", async () => {
+ // First executeJavaScript (error-handler setup) rejects → caught and ignored.
+ // Second executeJavaScript (note-ready) rejects → propagates as an error payload.
+ h.executeJavaScript.mockReset()
+ .mockRejectedValueOnce(new Error("inject failed"))
+ .mockRejectedValueOnce(new Error("note never ready"));
+ const e = await fireOn("print-note", { notePath: "root/abc" });
+ expect(e.sender.send).toHaveBeenCalledWith("print-done", expect.objectContaining({ type: "error", message: "note never ready" }));
+ });
+ });
+
+ describe("export-as-pdf", () => {
+ it("writes the generated PDF and opens it", async () => {
+ const e = await fireOn("export-as-pdf", PDF_OPTS);
+ expect(h.printToPDF).toHaveBeenCalled();
+ expect(h.writeFile).toHaveBeenCalledWith("/out.pdf", expect.any(Buffer));
+ expect(h.openPath).toHaveBeenCalledWith("/out.pdf");
+ expect(e.sender.send).toHaveBeenCalledWith("print-done", "REPORT");
+ expect(h.destroy).toHaveBeenCalled();
+ });
+
+ it("does nothing when the user cancels the save dialog", async () => {
+ h.showSaveDialogSync.mockReturnValue(undefined);
+ await fireOn("export-as-pdf", PDF_OPTS);
+ expect(h.printToPDF).not.toHaveBeenCalled();
+ expect(h.destroy).toHaveBeenCalled(); // finally still tears down
+ });
+
+ it("shows an error box when PDF generation fails", async () => {
+ h.printToPDF.mockRejectedValue(new Error("render failed"));
+ await fireOn("export-as-pdf", PDF_OPTS);
+ expect(h.showErrorBox).toHaveBeenCalledWith("pdf.unable-to-export-title", "pdf.unable-to-export-message");
+ expect(h.writeFile).not.toHaveBeenCalled();
+ });
+
+ it("shows an error box when writing the file fails", async () => {
+ h.writeFile.mockRejectedValue(new Error("disk full"));
+ await fireOn("export-as-pdf", PDF_OPTS);
+ expect(h.showErrorBox).toHaveBeenCalledWith("pdf.unable-to-export-title", "pdf.unable-to-save-message");
+ expect(h.openPath).not.toHaveBeenCalled();
+ });
+
+ it("reports an error payload when the print window fails (Error and non-Error)", async () => {
+ h.loadURL.mockRejectedValue(new Error("load failed"));
+ const e1 = await fireOn("export-as-pdf", PDF_OPTS);
+ expect(e1.sender.send).toHaveBeenCalledWith("print-done", expect.objectContaining({ type: "error", message: "load failed" }));
+
+ h.loadURL.mockRejectedValue("string failure");
+ const e2 = await fireOn("export-as-pdf", PDF_OPTS);
+ expect(e2.sender.send).toHaveBeenCalledWith("print-done", { type: "error", message: "string failure", stack: undefined });
+ });
+ });
+
+ describe("export-as-pdf-preview", () => {
+ it("returns the rendered buffer to the renderer", async () => {
+ const e = await fireOn("export-as-pdf-preview", PDF_OPTS);
+ expect(e.sender.send).toHaveBeenCalledWith("export-as-pdf-preview-result", expect.objectContaining({ notePath: "root/abc", buffer: expect.any(Buffer) }));
+ expect(e.sender.send).toHaveBeenCalledWith("print-done", "REPORT");
+ });
+
+ it("returns an error result when rendering fails (Error and non-Error)", async () => {
+ h.printToPDF.mockRejectedValue(new Error("render boom"));
+ const e1 = await fireOn("export-as-pdf-preview", PDF_OPTS);
+ expect(e1.sender.send).toHaveBeenCalledWith("export-as-pdf-preview-result", { notePath: "root/abc", error: "render boom" });
+
+ h.printToPDF.mockRejectedValue("render string");
+ const e2 = await fireOn("export-as-pdf-preview", PDF_OPTS);
+ expect(e2.sender.send).toHaveBeenCalledWith("export-as-pdf-preview-result", { notePath: "root/abc", error: "render string" });
+ });
+
+ it("reports an error payload when the print window fails (Error and non-Error)", async () => {
+ h.loadURL.mockRejectedValue(new Error("load failed"));
+ const e1 = await fireOn("export-as-pdf-preview", PDF_OPTS);
+ expect(e1.sender.send).toHaveBeenCalledWith("print-done", expect.objectContaining({ type: "error", message: "load failed" }));
+
+ h.loadURL.mockRejectedValue("load string");
+ const e2 = await fireOn("export-as-pdf-preview", PDF_OPTS);
+ expect(e2.sender.send).toHaveBeenCalledWith("print-done", { type: "error", message: "load string", stack: undefined });
+ });
+ });
+
+ describe("save-pdf", () => {
+ it("writes and opens the supplied buffer", async () => {
+ await fireOn("save-pdf", { title: "x", buffer: new Uint8Array([1, 2]) });
+ expect(h.writeFile).toHaveBeenCalledWith("/out.pdf", expect.any(Buffer));
+ expect(h.openPath).toHaveBeenCalledWith("/out.pdf");
+ });
+
+ it("does nothing without a focused window", async () => {
+ h.getFocusedWindow.mockReturnValue(null);
+ await fireOn("save-pdf", { title: "x", buffer: new Uint8Array([1]) });
+ expect(h.showSaveDialogSync).not.toHaveBeenCalled();
+ });
+
+ it("does nothing when the save dialog is cancelled", async () => {
+ h.showSaveDialogSync.mockReturnValue(undefined);
+ await fireOn("save-pdf", { title: "x", buffer: new Uint8Array([1]) });
+ expect(h.writeFile).not.toHaveBeenCalled();
+ });
+
+ it("shows an error box when writing fails", async () => {
+ h.writeFile.mockRejectedValue(new Error("nope"));
+ await fireOn("save-pdf", { title: "x", buffer: new Uint8Array([1]) });
+ expect(h.showErrorBox).toHaveBeenCalledWith("pdf.unable-to-export-title", "pdf.unable-to-save-message");
+ });
+ });
+
+ describe("get-printers", () => {
+ it("maps printer metadata across the platform variants", async () => {
+ h.getPrintersAsync.mockResolvedValue([
+ { name: "p1", displayName: "Printer 1", description: "d", options: { "printer-location": "CUPS room" }, isDefault: true },
+ { name: "p2", displayName: "Printer 2", description: "", options: { location: "win room" } },
+ { name: "p3", displayName: "Printer 3", description: "" }
+ ]);
+ const handler = h.handle.get("get-printers");
+ if (!handler) throw new Error("get-printers not registered");
+ const result = await handler(makeEvent()) as Array<{ location: string; isDefault: boolean }>;
+ expect(result[0]).toMatchObject({ location: "CUPS room", isDefault: true });
+ expect(result[1]).toMatchObject({ location: "win room", isDefault: false });
+ expect(result[2]).toMatchObject({ location: "", isDefault: false });
+ });
+
+ it("returns an empty list when enumeration throws", async () => {
+ h.getPrintersAsync.mockRejectedValue(new Error("no printers"));
+ const handler = h.handle.get("get-printers");
+ if (!handler) throw new Error("get-printers not registered");
+ expect(await handler(makeEvent())).toEqual([]);
+ });
+ });
+
+ describe("print-from-preview", () => {
+ it("prints with mapped options (Ledger → Tabloid)", async () => {
+ await fireOn("print-from-preview", { ...PDF_OPTS, pageSize: "Ledger", silent: true, deviceName: "HP", scale: 1, pageRanges: "1-2" });
+ const opts = h.print.mock.calls[0][0] as { pageSize: string; scaleFactor: number };
+ expect(opts.pageSize).toBe("Tabloid");
+ expect(opts.scaleFactor).toBe(100);
+ });
+
+ it("shows an error box on failure but not on cancel, and signals done", async () => {
+ h.print.mockImplementation((_opts, cb) => cb(false, "jam"));
+ const e = await fireOn("print-from-preview", { ...PDF_OPTS, silent: false });
+ expect(h.showErrorBox).toHaveBeenCalled();
+ expect(e.sender.send).toHaveBeenCalledWith("print-from-preview-done");
+
+ h.showErrorBox.mockClear();
+ h.print.mockImplementation((_opts, cb) => cb(false, "Print job canceled"));
+ await fireOn("print-from-preview", { ...PDF_OPTS, silent: false });
+ expect(h.showErrorBox).not.toHaveBeenCalled();
+ });
+
+ it("reports an error payload when the print window fails (Error and non-Error)", async () => {
+ h.loadURL.mockRejectedValue(new Error("load failed"));
+ const e1 = await fireOn("print-from-preview", { ...PDF_OPTS, silent: false });
+ expect(e1.sender.send).toHaveBeenCalledWith("print-from-preview-done");
+ expect(e1.sender.send).toHaveBeenCalledWith("print-done", expect.objectContaining({ type: "error", message: "load failed" }));
+
+ h.loadURL.mockRejectedValue("load string");
+ const e2 = await fireOn("print-from-preview", { ...PDF_OPTS, silent: false });
+ expect(e2.sender.send).toHaveBeenCalledWith("print-done", { type: "error", message: "load string", stack: undefined });
+ });
+ });
+});
diff --git a/apps/desktop/src/services/printing.ts b/apps/desktop/src/services/printing.ts
index f71334ed5a..62ef5e4f4c 100644
--- a/apps/desktop/src/services/printing.ts
+++ b/apps/desktop/src/services/printing.ts
@@ -19,6 +19,7 @@ function getPreloadScript(): string {
// Dev: this file lives one directory below the preload bundle.
// Prod: this file is bundled into dist/main.cjs alongside preload.cjs
// (no `..` — keep this synced with apps/desktop/src/services/window.ts).
+ /* v8 ignore next 5 -- prod preload arm is cache-once (only the first ternary evaluation counts); covered by the production build, not unit tests */
preloadScriptCache = path.resolve(
coreUtils.isDev()
? path.join(__dirname, "..", "preload.compiled.cjs")
@@ -52,7 +53,7 @@ interface PrintFromPreviewOpts extends ExportAsPdfOpts {
* Values are stored in mm and converted to inches for Electron.
* Presets expand to explicit numeric margins since Electron's `marginType` aliases
* (especially `none` and `printableArea`) behave inconsistently for PDF output. */
-function parseMargins(margins: string): Electron.Margins {
+export function parseMargins(margins: string): Electron.Margins {
const mmToInches = (mm: number) => mm / 25.4;
const uniform = (mm: number): Electron.Margins => ({
marginType: "custom",
@@ -81,7 +82,7 @@ function parseMargins(margins: string): Electron.Margins {
}
/** Convert "1-5, 8, 11-13" into PageRanges array form expected by webContents.print. */
-function parsePageRangesForPrint(pageRanges: string): { from: number; to: number }[] | undefined {
+export function parsePageRangesForPrint(pageRanges: string): { from: number; to: number }[] | undefined {
if (!pageRanges?.trim()) return undefined;
const ranges: { from: number; to: number }[] = [];
for (const part of pageRanges.split(",")) {
diff --git a/apps/desktop/src/services/request.spec.ts b/apps/desktop/src/services/request.spec.ts
new file mode 100644
index 0000000000..36020fb762
--- /dev/null
+++ b/apps/desktop/src/services/request.spec.ts
@@ -0,0 +1,57 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const netSentinel = { request: () => ({ on() {}, end() {} }) };
+const isReady = vi.fn(() => true);
+const whenReady = vi.fn(() => Promise.resolve());
+
+vi.mock("electron", () => ({
+ default: {
+ net: netSentinel,
+ app: {
+ isReady: () => isReady(),
+ whenReady: () => whenReady()
+ }
+ }
+}));
+
+const { default: ElectronRequestProvider } = await import("./request.js");
+
+// `getClient` is protected; expose it through a thin subclass for testing.
+class TestableProvider extends ElectronRequestProvider {
+ public getClientPublic(opts: Parameters<TestableProvider["getClient"]>[0]) {
+ return this.getClient(opts);
+ }
+}
+
+describe("ElectronRequestProvider", () => {
+ const provider = new TestableProvider();
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ isReady.mockReturnValue(true);
+ });
+
+ it("uses electron.net for proxyless requests once the app is ready", async () => {
+ isReady.mockReturnValue(true);
+ const client = await provider.getClientPublic({ method: "GET", url: "https://example.com" });
+ expect(client).toBe(netSentinel);
+ expect(whenReady).not.toHaveBeenCalled();
+ });
+
+ it("awaits app readiness before returning electron.net when not yet ready", async () => {
+ isReady.mockReturnValue(false);
+ const client = await provider.getClientPublic({ method: "GET", url: "https://example.com" });
+ expect(client).toBe(netSentinel);
+ expect(whenReady).toHaveBeenCalledOnce();
+ });
+
+ it("falls through to Node http(s) when an explicit proxy is configured", async () => {
+ const client = await provider.getClientPublic({
+ method: "GET",
+ url: "https://example.com",
+ proxy: "http://127.0.0.1:8888"
+ });
+ expect(client).not.toBe(netSentinel);
+ expect(typeof client.request).toBe("function");
+ });
+});
diff --git a/apps/desktop/src/services/security_settings.spec.ts b/apps/desktop/src/services/security_settings.spec.ts
new file mode 100644
index 0000000000..3c744715d8
--- /dev/null
+++ b/apps/desktop/src/services/security_settings.spec.ts
@@ -0,0 +1,129 @@
+import type fs from "fs";
+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const h = vi.hoisted(() => ({
+ fileStore: new Map<string, string>(),
+ handlers: new Map<string, (event: unknown, ...args: unknown[]) => unknown>(),
+ showMessageBox: vi.fn()
+}));
+
+// In-memory shim for the security.json path only; every other fs path falls
+// through to the real implementation so the server's already-initialised
+// data_dir module is untouched.
+vi.mock("fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("fs") & { default?: typeof import("fs") }>();
+ const real = actual.default ?? actual;
+ const existsSync = (p: fs.PathLike) =>
+ h.fileStore.has(String(p)) ? true : real.existsSync(p);
+ const readFileSync = ((p: fs.PathLike, enc?: unknown) =>
+ h.fileStore.has(String(p)) ? h.fileStore.get(String(p)) : real.readFileSync(p, enc as never)) as typeof real.readFileSync;
+ const writeFileSync = ((p: fs.PathLike, data: string) => {
+ h.fileStore.set(String(p), String(data));
+ }) as typeof real.writeFileSync;
+ const patched = { ...real, existsSync, readFileSync, writeFileSync };
+ return { ...actual, default: patched, existsSync, readFileSync, writeFileSync };
+});
+
+vi.mock("electron", () => ({
+ default: {
+ dialog: { showMessageBox: h.showMessageBox },
+ ipcMain: {
+ handle(channel: string, handler: (event: unknown, ...args: unknown[]) => unknown) {
+ h.handlers.set(channel, handler);
+ }
+ }
+ }
+}));
+
+vi.mock("i18next", () => ({ t: (key: string) => key }));
+
+const securitySettings = await import("./security_settings.js");
+const SETTINGS_PATH = await (async () => {
+ const dataDirs = (await import("@triliumnext/server/src/services/data_dir.js")).default;
+ const path = (await import("path")).default;
+ return path.join(dataDirs.TRILIUM_DATA_DIR, "security.json");
+})();
+
+function invoke(channel: string, enabled: boolean) {
+ const handler = h.handlers.get(channel);
+ if (!handler) throw new Error(`no handler for ${channel}`);
+ return handler({}, enabled);
+}
+
+describe("security_settings", () => {
+ // Handlers (and the module-level "suppress for session" flag) are registered
+ // once; the suppression test runs last because it latches that flag on.
+ beforeAll(() => {
+ securitySettings.registerSecurityIpcHandlers();
+ });
+
+ beforeEach(() => {
+ h.fileStore.clear();
+ h.showMessageBox.mockReset();
+ });
+
+ describe("getSecuritySettings", () => {
+ it("returns defaults when the file is missing", () => {
+ expect(securitySettings.getSecuritySettings()).toEqual({});
+ });
+
+ it("parses existing settings", () => {
+ h.fileStore.set(SETTINGS_PATH, JSON.stringify({ backendScriptingEnabled: true }));
+ expect(securitySettings.getSecuritySettings()).toEqual({ backendScriptingEnabled: true });
+ });
+
+ it("treats corrupt JSON as defaults", () => {
+ h.fileStore.set(SETTINGS_PATH, "{ not valid json");
+ expect(securitySettings.getSecuritySettings()).toEqual({});
+ });
+ });
+
+ describe("registerSecurityIpcHandlers — enabling", () => {
+ it("persists when the user confirms an enable", async () => {
+ h.showMessageBox.mockResolvedValue({ response: 1, checkboxChecked: false });
+
+ const result = await invoke("security-set-backend-scripting", true);
+
+ expect(result).toBe(true);
+ expect(JSON.parse(h.fileStore.get(SETTINGS_PATH) ?? "{}")).toEqual({ backendScriptingEnabled: true });
+ // Enable path uses the warning dialog.
+ expect(h.showMessageBox.mock.calls[0][0]).toMatchObject({ type: "warning" });
+ });
+
+ it("does nothing when the user cancels", async () => {
+ h.showMessageBox.mockResolvedValue({ response: 0, checkboxChecked: false });
+
+ const result = await invoke("security-set-sql-console", true);
+
+ expect(result).toBe(false);
+ expect(h.fileStore.has(SETTINGS_PATH)).toBe(false);
+ });
+ });
+
+ describe("registerSecurityIpcHandlers — disabling", () => {
+ it("persists a disable through the info dialog", async () => {
+ h.fileStore.set(SETTINGS_PATH, JSON.stringify({ sqlConsoleEnabled: true }));
+ h.showMessageBox.mockResolvedValue({ response: 1, checkboxChecked: false });
+
+ const result = await invoke("security-set-sql-console", false);
+
+ expect(result).toBe(true);
+ expect(JSON.parse(h.fileStore.get(SETTINGS_PATH) ?? "{}")).toMatchObject({ sqlConsoleEnabled: false });
+ expect(h.showMessageBox.mock.calls[0][0]).toMatchObject({ type: "info" });
+ });
+ });
+
+ // Must run last: ticking "don't ask again" latches the module-level
+ // suppression flag for the rest of the process.
+ describe("don't-ask-again suppression", () => {
+ it("suppresses all subsequent dialogs once the checkbox is ticked", async () => {
+ h.showMessageBox.mockResolvedValue({ response: 1, checkboxChecked: true });
+ expect(await invoke("security-set-backend-scripting", true)).toBe(true);
+
+ h.showMessageBox.mockClear();
+ expect(await invoke("security-set-sql-console", true)).toBe(false);
+ expect(await invoke("security-set-backend-scripting", false)).toBe(false);
+ expect(h.showMessageBox).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/apps/desktop/src/services/security_settings.ts b/apps/desktop/src/services/security_settings.ts
index 13bb316132..566902719d 100644
--- a/apps/desktop/src/services/security_settings.ts
+++ b/apps/desktop/src/services/security_settings.ts
@@ -74,46 +74,51 @@ async function confirmDisable(settingLabel: string): Promise<ConfirmResult> {
// to suppress all security dialogs for the rest of the session. Resets on restart.
let suppressedForSession = false;
-export function registerSecurityIpcHandlers(): void {
- electron.ipcMain.handle("security-set-backend-scripting", async (_event, enabled: boolean) => {
+/**
+ * Registers an IPC handler that gates a single security toggle behind a
+ * confirmation dialog and persists it to `security.json`. `labelKey` and
+ * `warningKey` are i18next keys resolved at invocation time so the dialog
+ * follows runtime language changes.
+ */
+function registerToggleHandler(
+ channel: string,
+ settingKey: keyof SecuritySettings,
+ labelKey: string,
+ warningKey: string
+): void {
+ electron.ipcMain.handle(channel, async (_event, enabled: boolean) => {
if (suppressedForSession) {
return false;
}
+ const settingLabel = t(labelKey);
const { confirmed, suppressFurtherDialogs } = enabled
- ? await confirmEnable(t("security-dialog.backend-scripting"), t("security-dialog.backend-scripting-warning"))
- : await confirmDisable(t("security-dialog.backend-scripting"));
- if (suppressFurtherDialogs) {
- suppressedForSession = true;
- }
+ ? await confirmEnable(settingLabel, t(warningKey))
+ : await confirmDisable(settingLabel);
+ // Latch the session-wide suppression flag; never clears it once set.
+ suppressedForSession = suppressFurtherDialogs || suppressedForSession;
if (!confirmed) {
return false;
}
const settings = readSettings();
- settings.backendScriptingEnabled = enabled;
+ settings[settingKey] = enabled;
writeSettings(settings);
return true;
});
+}
- electron.ipcMain.handle("security-set-sql-console", async (_event, enabled: boolean) => {
- if (suppressedForSession) {
- return false;
- }
-
- const { confirmed, suppressFurtherDialogs } = enabled
- ? await confirmEnable(t("security-dialog.sql-console"), t("security-dialog.sql-console-warning"))
- : await confirmDisable(t("security-dialog.sql-console"));
- if (suppressFurtherDialogs) {
- suppressedForSession = true;
- }
- if (!confirmed) {
- return false;
- }
-
- const settings = readSettings();
- settings.sqlConsoleEnabled = enabled;
- writeSettings(settings);
- return true;
- });
+export function registerSecurityIpcHandlers(): void {
+ registerToggleHandler(
+ "security-set-backend-scripting",
+ "backendScriptingEnabled",
+ "security-dialog.backend-scripting",
+ "security-dialog.backend-scripting-warning"
+ );
+ registerToggleHandler(
+ "security-set-sql-console",
+ "sqlConsoleEnabled",
+ "security-dialog.sql-console",
+ "security-dialog.sql-console-warning"
+ );
}
diff --git a/apps/desktop/src/services/shell_handlers.spec.ts b/apps/desktop/src/services/shell_handlers.spec.ts
new file mode 100644
index 0000000000..e69d0b496d
--- /dev/null
+++ b/apps/desktop/src/services/shell_handlers.spec.ts
@@ -0,0 +1,191 @@
+import fs from "fs";
+import path from "path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+type Handler = (event: unknown, ...args: unknown[]) => unknown;
+
+const h = vi.hoisted(() => ({
+ on: new Map<string, Handler>(),
+ handle: new Map<string, Handler>(),
+ openExternal: vi.fn(),
+ openPath: vi.fn(() => Promise.resolve("")),
+ execFile: vi.fn()
+}));
+
+vi.mock("electron", () => ({
+ default: {
+ ipcMain: {
+ on: (channel: string, fn: Handler) => h.on.set(channel, fn),
+ handle: (channel: string, fn: Handler) => h.handle.set(channel, fn)
+ },
+ shell: {
+ openExternal: h.openExternal,
+ openPath: h.openPath
+ }
+ }
+}));
+
+vi.mock("child_process", () => ({ execFile: h.execFile }));
+
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return { ...actual, getLog: () => ({ info: vi.fn(), error: vi.fn() }) };
+});
+
+const { setupShellHandlers } = await import("./shell.js");
+const dataDirs = (await import("@triliumnext/server/src/services/data_dir.js")).default;
+
+const DATA_DIR = dataDirs.TRILIUM_DATA_DIR;
+const TMP_DIR = dataDirs.TMP_DIR;
+let tmpFile: string;
+let dataFile: string;
+
+function setPlatform(platform: NodeJS.Platform) {
+ Object.defineProperty(process, "platform", { value: platform, configurable: true });
+}
+
+const realPlatform = process.platform;
+
+beforeAll(() => {
+ fs.mkdirSync(TMP_DIR, { recursive: true });
+ tmpFile = path.join(TMP_DIR, "shell-handlers-test.txt");
+ dataFile = path.join(DATA_DIR, "shell-handlers-data.txt");
+ fs.writeFileSync(tmpFile, "");
+ fs.writeFileSync(dataFile, "");
+ setupShellHandlers();
+});
+
+afterAll(() => {
+ fs.rmSync(tmpFile, { force: true });
+ fs.rmSync(dataFile, { force: true });
+ setPlatform(realPlatform);
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ setPlatform(realPlatform);
+});
+
+function fireOn(channel: string, ...args: unknown[]) {
+ const fn = h.on.get(channel);
+ if (!fn) throw new Error(`no on-handler for ${channel}`);
+ return fn({ sender: { getURL: () => "trilium-app://app/", downloadURL: h.openExternal } }, ...args);
+}
+
+function fireHandle(channel: string, ...args: unknown[]) {
+ const fn = h.handle.get(channel);
+ if (!fn) throw new Error(`no handle-handler for ${channel}`);
+ return fn({}, ...args);
+}
+
+describe("setupShellHandlers", () => {
+ describe("open-external", () => {
+ it("opens a validated URL", () => {
+ fireOn("open-external", "https://example.com/");
+ expect(h.openExternal).toHaveBeenCalledWith("https://example.com/");
+ });
+
+ it("swallows invalid URLs without opening anything", () => {
+ fireOn("open-external", "javascript:alert(1)");
+ expect(h.openExternal).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("open-path", () => {
+ it("opens a path inside the sandbox", () => {
+ fireHandle("open-path", dataFile);
+ expect(h.openPath).toHaveBeenCalledWith(path.resolve(dataFile));
+ });
+
+ it("returns an error message for a path outside the sandbox", () => {
+ const result = fireHandle("open-path", process.platform === "win32" ? "C:\\Windows\\evil" : "/etc/passwd");
+ expect(result).toBeTruthy();
+ expect(h.openPath).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("open-file-url", () => {
+ it("opens a valid file: URL", () => {
+ const url = process.platform === "win32" ? "file:///C:/Windows/notepad.exe" : "file:///etc/hosts";
+ fireHandle("open-file-url", url);
+ expect(h.openPath).toHaveBeenCalled();
+ });
+
+ it("returns an error message for a non-file URL", () => {
+ const result = fireHandle("open-file-url", "https://example.com/x");
+ expect(result).toBeTruthy();
+ expect(h.openPath).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("download-url", () => {
+ it("downloads a same-origin URL via the sender", () => {
+ fireOn("download-url", "trilium-app://app/api/notes/abc/download");
+ expect(h.openExternal).toHaveBeenCalledWith("trilium-app://app/api/notes/abc/download");
+ });
+
+ it("swallows a cross-origin download", () => {
+ fireOn("download-url", "https://attacker.example/malware.exe");
+ expect(h.openExternal).not.toHaveBeenCalled();
+ });
+ });
+
+ describe("open-custom", () => {
+ it("swallows invalid paths", () => {
+ fireOn("open-custom", "/etc/passwd");
+ expect(h.execFile).not.toHaveBeenCalled();
+ expect(h.openPath).not.toHaveBeenCalled();
+ });
+
+ it("opens directly via the shell on macOS/other platforms", () => {
+ setPlatform("darwin");
+ fireOn("open-custom", tmpFile);
+ expect(h.openPath).toHaveBeenCalledWith(path.resolve(tmpFile));
+ expect(h.execFile).not.toHaveBeenCalled();
+ });
+
+ describe("linux", () => {
+ beforeEach(() => setPlatform("linux"));
+
+ it("launches the first available terminal", () => {
+ h.execFile.mockImplementation((_cmd, _args, cb) => cb(null));
+ fireOn("open-custom", tmpFile);
+ expect(h.execFile).toHaveBeenCalledTimes(1);
+ expect(h.execFile.mock.calls[0][0]).toBe("x-terminal-emulator");
+ expect(h.openPath).not.toHaveBeenCalled();
+ });
+
+ it("falls through to the next terminal when one fails", () => {
+ let calls = 0;
+ h.execFile.mockImplementation((_cmd, _args, cb) => cb(calls++ === 0 ? new Error("nope") : null));
+ fireOn("open-custom", tmpFile);
+ expect(h.execFile).toHaveBeenCalledTimes(2);
+ });
+
+ it("falls back to shell.openPath when no terminal works", () => {
+ h.execFile.mockImplementation((_cmd, _args, cb) => cb(new Error("nope")));
+ fireOn("open-custom", tmpFile);
+ // 9 terminals are tried before giving up.
+ expect(h.execFile).toHaveBeenCalledTimes(9);
+ expect(h.openPath).toHaveBeenCalledWith(path.resolve(tmpFile));
+ });
+ });
+
+ describe("win32", () => {
+ beforeEach(() => setPlatform("win32"));
+
+ it("launches rundll32 for the OpenAs dialog", () => {
+ h.execFile.mockImplementation((_cmd, _args, _opts, cb) => cb(null));
+ fireOn("open-custom", tmpFile);
+ expect(h.execFile.mock.calls[0][0]).toBe("rundll32.exe");
+ expect(h.openPath).not.toHaveBeenCalled();
+ });
+
+ it("falls back to shell.openPath when rundll32 fails", () => {
+ h.execFile.mockImplementation((_cmd, _args, _opts, cb) => cb(new Error("boom")));
+ fireOn("open-custom", tmpFile);
+ expect(h.openPath).toHaveBeenCalledWith(path.resolve(tmpFile));
+ });
+ });
+ });
+});
diff --git a/apps/desktop/src/services/tray.spec.ts b/apps/desktop/src/services/tray.spec.ts
new file mode 100644
index 0000000000..3efd5f4372
--- /dev/null
+++ b/apps/desktop/src/services/tray.spec.ts
@@ -0,0 +1,614 @@
+import { becca, becca_easy_mocking } from "@triliumnext/core";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const { buildNote } = becca_easy_mocking;
+
+type Handler = (...args: unknown[]) => unknown;
+
+// Mutable test state for the core/electron stubs plus captured event handlers.
+const state = vi.hoisted(() => ({
+ dbInitialized: true,
+ disableTray: false,
+ isMac: false,
+ isDev: false,
+ shouldUseDarkColors: false,
+ // captured handlers
+ appHandlers: new Map<string, Handler>(),
+ ipcHandlers: new Map<string, Handler>(),
+ nativeThemeHandlers: new Map<string, Handler>(),
+ i18nHandlers: new Map<string, Handler>(),
+ // captured tray instance
+ trayInstance: undefined as undefined | {
+ setToolTip: ReturnType<typeof vi.fn>;
+ on: ReturnType<typeof vi.fn>;
+ setContextMenu: ReturnType<typeof vi.fn>;
+ clickHandlers: Map<string, Handler>;
+ lastTemplate: unknown[];
+ },
+ // controllable windows
+ lastFocusedWindow: null as unknown,
+ allWindows: [] as unknown[],
+ browserWindowAll: [] as unknown[]
+}));
+
+// `getTodayNote` returns a fake note used by the "today" menu item.
+const todayNote = { noteId: "today" };
+
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => ({ info: vi.fn(), error: vi.fn() }),
+ utils: {
+ ...actual.utils,
+ isMac: () => state.isMac,
+ isDev: () => state.isDev
+ },
+ sql_init: { ...actual.sql_init, isDbInitialized: () => state.dbInitialized },
+ options: { ...actual.options, getOptionBool: () => state.disableTray },
+ cls: { ...actual.cls, wrap: (fn: Handler) => fn },
+ date_notes: { ...actual.date_notes, getTodayNote: async () => todayNote }
+ };
+});
+
+vi.mock("electron", () => ({
+ default: {
+ Tray: class {
+ setToolTip = vi.fn();
+ setContextMenu = vi.fn();
+ clickHandlers = new Map<string, Handler>();
+ lastTemplate: unknown[] = [];
+ on = vi.fn((event: string, fn: Handler) => {
+ this.clickHandlers.set(event, fn);
+ });
+ constructor() {
+ state.trayInstance = this;
+ }
+ },
+ Menu: {
+ buildFromTemplate: vi.fn((template: unknown[]) => {
+ if (state.trayInstance) {
+ state.trayInstance.lastTemplate = template;
+ }
+ return template;
+ })
+ },
+ nativeTheme: {
+ get shouldUseDarkColors() {
+ return state.shouldUseDarkColors;
+ },
+ on: (event: string, fn: Handler) => state.nativeThemeHandlers.set(event, fn)
+ },
+ ipcMain: {
+ on: (channel: string, fn: Handler) => state.ipcHandlers.set(channel, fn)
+ },
+ app: {
+ on: (event: string, fn: Handler) => state.appHandlers.set(event, fn)
+ },
+ BrowserWindow: {
+ getAllWindows: () => state.browserWindowAll
+ }
+ }
+}));
+
+vi.mock("./window.js", () => ({
+ default: {
+ getLastFocusedWindow: () => state.lastFocusedWindow,
+ getAllWindows: () => state.allWindows
+ }
+}));
+
+vi.mock("@triliumnext/server/src/services/utils.js", () => ({
+ getResourceDir: () => "/res"
+}));
+
+vi.mock("i18next", () => ({
+ default: { on: (event: string, fn: Handler) => state.i18nHandlers.set(event, fn) },
+ t: (key: string) => key
+}));
+
+const tray = await import("./tray.js");
+
+interface FakeWindow {
+ id: number;
+ getTitle: () => string;
+ webContents: { send: ReturnType<typeof vi.fn> };
+ on: ReturnType<typeof vi.fn>;
+ listeners: Map<string, Handler>;
+ show: ReturnType<typeof vi.fn>;
+ focus: ReturnType<typeof vi.fn>;
+ hide: ReturnType<typeof vi.fn>;
+ isVisible: () => boolean;
+ close: ReturnType<typeof vi.fn>;
+}
+
+// Monotonic window id counter. The module-level `windowVisibilityMap` persists
+// across tests; reusing ids would skip the "newly created window" registration
+// branch, so every test gets fresh ids.
+let nextWindowId = 1;
+
+function makeWindow(idOrTitle?: number | string, maybeTitle = "My Note - Trilium"): FakeWindow {
+ let id: number;
+ let title: string;
+ if (typeof idOrTitle === "string") {
+ id = nextWindowId++;
+ title = idOrTitle;
+ } else {
+ id = nextWindowId++;
+ title = maybeTitle;
+ }
+ const listeners = new Map<string, Handler>();
+ return {
+ id,
+ getTitle: () => title,
+ webContents: { send: vi.fn() },
+ listeners,
+ on: vi.fn((event: string, fn: Handler) => listeners.set(event, fn)),
+ show: vi.fn(),
+ focus: vi.fn(),
+ hide: vi.fn(),
+ isVisible: () => true,
+ close: vi.fn()
+ };
+}
+
+function getTrayInstance() {
+ return state.trayInstance;
+}
+
+function fireAppCreated() {
+ const handler = state.appHandlers.get("browser-window-created");
+ if (!handler) throw new Error("browser-window-created not registered");
+ return handler();
+}
+
+/** Find a menu item in the last-built tray template by its label. */
+function findItem(label: string) {
+ const template = state.trayInstance?.lastTemplate ?? [];
+ return template.find((item) => (item as { label?: string }).label === label) as
+ | (Electron.MenuItemConstructorOptions & { submenu?: Electron.MenuItemConstructorOptions[] })
+ | undefined;
+}
+
+describe("tray", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ becca.reset();
+ // Re-stub getRecentNotesFromQuery (becca.reset doesn't touch the prototype,
+ // but keep it controllable per-test).
+ becca.getRecentNotesFromQuery = vi.fn(() => []) as unknown as typeof becca.getRecentNotesFromQuery;
+ state.dbInitialized = true;
+ state.disableTray = false;
+ state.isMac = false;
+ state.isDev = false;
+ state.shouldUseDarkColors = false;
+ state.lastFocusedWindow = null;
+ state.allWindows = [];
+ state.browserWindowAll = [];
+ // Bookmarks subtree must always exist for buildBookmarksMenu.
+ buildNote({ id: "_lbBookmarks", title: "Bookmarks" });
+ });
+
+ // These tests intentionally run BEFORE the tray is created, exercising the
+ // early-return branches that are impossible to reach once the module-level
+ // `tray` singleton is set.
+
+ it("setupSystemTray does not create a tray when DB is not initialized", () => {
+ tray.setupSystemTray();
+ state.dbInitialized = false;
+ fireAppCreated();
+ expect(state.trayInstance).toBeUndefined();
+ });
+
+ it("does not create a tray when disableTray option is set", () => {
+ state.disableTray = true;
+ fireAppCreated();
+ expect(state.trayInstance).toBeUndefined();
+ });
+
+ it("reload-tray ipc is a no-op before the tray exists", () => {
+ // The handler is only registered inside createTray, so it can't be fired
+ // yet — assert no tray was created as a side effect of prior tests.
+ expect(state.trayInstance).toBeUndefined();
+ });
+
+ describe("after tray creation", () => {
+ beforeEach(() => {
+ // Create the tray once (idempotent afterwards). isMac=false so the
+ // nativeTheme "updated" listener is registered.
+ fireAppCreated();
+ });
+
+ it("creates the tray with tooltip and click handler (non-mac wires nativeTheme)", () => {
+ const instance = state.trayInstance;
+ if (!instance) throw new Error("tray not created");
+ expect(instance.setToolTip).toHaveBeenCalledWith("tray.tooltip");
+ expect(instance.clickHandlers.has("click")).toBe(true);
+ expect(state.nativeThemeHandlers.has("updated")).toBe(true);
+ expect(state.ipcHandlers.has("reload-tray")).toBe(true);
+ expect(state.i18nHandlers.has("languageChanged")).toBe(true);
+ });
+
+ it("createTray is idempotent (already-created early return)", () => {
+ const before = state.trayInstance;
+ fireAppCreated(); // second call must not replace the tray
+ expect(state.trayInstance).toBe(before);
+ });
+
+ it("click handler toggles visibility: null window returns early", () => {
+ const click = state.trayInstance?.clickHandlers.get("click");
+ state.lastFocusedWindow = null;
+ expect(() => click?.()).not.toThrow();
+ });
+
+ it("click handler hides a visible window and shows a hidden one", () => {
+ const win = makeWindow(1);
+ state.lastFocusedWindow = win;
+ state.allWindows = [win];
+ state.browserWindowAll = [win];
+ const click = state.trayInstance?.clickHandlers.get("click");
+
+ // Fire show/hide listeners to seed windowVisibilityMap.
+ // First build the menu so listeners get registered.
+ const reload = state.ipcHandlers.get("reload-tray");
+ reload?.();
+ // window id 1 visible by default -> click hides it
+ click?.();
+ expect(win.hide).toHaveBeenCalled();
+
+ // Now simulate it being hidden, then click shows + focuses.
+ win.listeners.get("hide")?.();
+ click?.();
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ });
+ });
+
+ describe("updateTrayMenu menu contents", () => {
+ let winA: FakeWindow;
+ let winB: FakeWindow;
+
+ beforeEach(() => {
+ fireAppCreated();
+ winA = makeWindow(1, "Note A - Trilium");
+ winB = makeWindow(2, "Note B - Trilium");
+ });
+
+ function rebuild() {
+ const reload = state.ipcHandlers.get("reload-tray");
+ reload?.();
+ }
+
+ it("builds bookmarks (folder + normal) and recent notes; click opens in same tab", () => {
+ becca.reset();
+ buildNote({ id: "_customDictionary", title: "x" }); // unrelated, keep becca non-empty
+ buildNote({
+ id: "_lbBookmarks",
+ title: "Bookmarks",
+ children: [
+ {
+ id: "folder1",
+ title: "Folder One",
+ "#bookmarkFolder": "true",
+ children: [{ id: "child1", title: "Child One" }]
+ },
+ { id: "bm1", title: "Bookmark One" }
+ ]
+ });
+ becca.getRecentNotesFromQuery = vi.fn(() => [
+ { noteId: "child1", utcDateCreated: "2025-01-01 10:00:00.000Z" }
+ ]) as unknown as typeof becca.getRecentNotesFromQuery;
+
+ const win = winA;
+ state.lastFocusedWindow = win;
+ state.allWindows = [win];
+ rebuild();
+
+ const bookmarks = findItem("tray.bookmarks");
+ const folder = bookmarks?.submenu?.find((i) => i.label === "Folder One");
+ const normal = bookmarks?.submenu?.find((i) => i.label === "Bookmark One");
+ expect(folder?.type).toBe("submenu");
+ expect(normal?.type).toBe("normal");
+
+ // Invoke folder submenu child click (openInSameTab with lastFocusedWindow).
+ const subChild = (folder as { submenu?: Electron.MenuItemConstructorOptions[] })
+ ?.submenu?.[0];
+ subChild?.click?.(undefined as never, undefined as never, undefined as never);
+ normal?.click?.(undefined as never, undefined as never, undefined as never);
+ expect(win.webContents.send).toHaveBeenCalledWith("openInSameTab", "child1");
+ expect(win.webContents.send).toHaveBeenCalledWith("openInSameTab", "bm1");
+
+ // Recent notes menu + click.
+ const recents = findItem("tray.recents");
+ const recentItem = recents?.submenu?.[0];
+ expect(recentItem?.label).toBe("Child One");
+ recentItem?.click?.(undefined as never, undefined as never, undefined as never);
+ expect(win.webContents.send).toHaveBeenCalledWith("openInSameTab", "child1");
+ });
+
+ it("openInSameTab no-ops when there is no focused window", () => {
+ becca.getRecentNotesFromQuery = vi.fn(() => [
+ { noteId: "r1", utcDateCreated: "2025-01-01 10:00:00.000Z" }
+ ]) as unknown as typeof becca.getRecentNotesFromQuery;
+ buildNote({ id: "r1", title: "Recent One" });
+
+ state.lastFocusedWindow = null;
+ state.allWindows = [];
+ rebuild();
+
+ const recents = findItem("tray.recents");
+ const recentItem = recents?.submenu?.[0];
+ // Should not throw despite no focused window.
+ expect(() =>
+ recentItem?.click?.(undefined as never, undefined as never, undefined as never)
+ ).not.toThrow();
+ });
+
+ it("window visibility items: single window (no title) and checkbox hide", () => {
+ const win = winA;
+ state.lastFocusedWindow = win;
+ state.allWindows = [win];
+ rebuild();
+
+ const visItem = (state.trayInstance?.lastTemplate ?? []).find(
+ (i) => (i as { type?: string }).type === "checkbox"
+ ) as Electron.MenuItemConstructorOptions | undefined;
+ // Single window -> plain label, no title appended.
+ expect(visItem?.label).toBe("tray.show-windows");
+ expect(visItem?.checked).toBe(true);
+
+ // checkbox click for a visible window -> hide.
+ visItem?.click?.(undefined as never, undefined as never, undefined as never);
+ expect(win.hide).toHaveBeenCalled();
+ });
+
+ it("window visibility items: multiple windows show titles and checkbox can re-show", () => {
+ state.lastFocusedWindow = winA;
+ state.allWindows = [winA, winB];
+ rebuild();
+
+ const checkboxes = (state.trayInstance?.lastTemplate ?? []).filter(
+ (i) => (i as { type?: string }).type === "checkbox"
+ ) as Electron.MenuItemConstructorOptions[];
+ expect(checkboxes.length).toBe(2);
+ // Title appended for window B ("Note B").
+ expect(checkboxes.some((c) => typeof c.label === "string" && c.label.includes("Note B"))).toBe(
+ true
+ );
+
+ // Seed winB as hidden so its checkbox click re-shows it.
+ winB.listeners.get("hide")?.();
+ rebuild();
+ const cbB = (state.trayInstance?.lastTemplate ?? [])
+ .filter((i) => (i as { type?: string }).type === "checkbox")
+ .find((c) => typeof (c as { label?: string }).label === "string" &&
+ ((c as { label: string }).label).includes("Note B")) as
+ | Electron.MenuItemConstructorOptions
+ | undefined;
+ cbB?.click?.(undefined as never, undefined as never, undefined as never);
+ expect(winB.show).toHaveBeenCalled();
+ expect(winB.focus).toHaveBeenCalled();
+ });
+
+ it("prunes closed windows and registers listeners for new ones", () => {
+ state.allWindows = [winA, winB];
+ state.lastFocusedWindow = winA;
+ rebuild();
+ expect(winB.on).toHaveBeenCalled(); // listener registered
+
+ // Now remove winB; it should be pruned from the visibility map.
+ state.allWindows = [winA];
+ rebuild();
+ const checkboxes = (state.trayInstance?.lastTemplate ?? []).filter(
+ (i) => (i as { type?: string }).type === "checkbox"
+ );
+ expect(checkboxes.length).toBe(1);
+ });
+
+ it("appends the -inverted icon suffix when dark colors are active (non-mac)", () => {
+ state.isMac = false;
+ state.shouldUseDarkColors = true;
+ state.lastFocusedWindow = winA;
+ state.allWindows = [winA];
+ rebuild();
+
+ const newWindowItem = findItem("tray.open_new_window");
+ expect(newWindowItem?.icon).toContain("new-windowTemplate-inverted.png");
+ });
+
+ it("open-new-window, new-note, today and close click handlers (with focused window)", async () => {
+ const win = winA;
+ state.lastFocusedWindow = win;
+ state.allWindows = [win];
+ state.browserWindowAll = [win];
+ rebuild();
+
+ findItem("tray.open_new_window")?.click?.(
+ undefined as never,
+ undefined as never,
+ undefined as never
+ );
+ expect(win.webContents.send).toHaveBeenCalledWith("globalShortcut", "openNewWindow");
+
+ findItem("tray.new-note")?.click?.(
+ undefined as never,
+ undefined as never,
+ undefined as never
+ );
+ expect(win.webContents.send).toHaveBeenCalledWith(
+ "globalShortcut",
+ "createNoteIntoInbox"
+ );
+
+ // "today" uses cls.wrap(async ...) — the click returns a promise we await.
+ const todayClick = findItem("tray.today")?.click as
+ | ((...args: never[]) => Promise<void>)
+ | undefined;
+ await todayClick?.();
+ expect(win.webContents.send).toHaveBeenCalledWith("openInSameTab", "today");
+
+ // "close" closes all BrowserWindow windows.
+ findItem("tray.close")?.click?.(
+ undefined as never,
+ undefined as never,
+ undefined as never
+ );
+ expect(win.close).toHaveBeenCalled();
+ });
+
+ it("open-new-window and new-note no-op when no focused window", () => {
+ state.lastFocusedWindow = null;
+ state.allWindows = [];
+ rebuild();
+
+ expect(() =>
+ findItem("tray.open_new_window")?.click?.(
+ undefined as never,
+ undefined as never,
+ undefined as never
+ )
+ ).not.toThrow();
+ expect(() =>
+ findItem("tray.new-note")?.click?.(
+ undefined as never,
+ undefined as never,
+ undefined as never
+ )
+ ).not.toThrow();
+ });
+ });
+
+ describe("window title formatting", () => {
+ it("truncates long titles to 17 chars + ellipsis (multi-window shows title)", () => {
+ const longWin = makeWindow("A Very Long Window Title Indeed - Trilium");
+ const other = makeWindow("Other - Trilium");
+ fireAppCreated();
+ state.lastFocusedWindow = longWin;
+ state.allWindows = [longWin, other];
+ state.ipcHandlers.get("reload-tray")?.();
+
+ const checkbox = (state.trayInstance?.lastTemplate ?? [])
+ .filter((i) => (i as { type?: string }).type === "checkbox")
+ .find((c) =>
+ typeof (c as { label?: string }).label === "string" &&
+ ((c as { label: string }).label).includes("...")
+ ) as Electron.MenuItemConstructorOptions | undefined;
+ expect(checkbox?.label).toContain("...");
+ // 17 chars of "A Very Long Window Title..." -> "A Very Long Windo..."
+ expect(checkbox?.label).toContain("A Very Long Windo...");
+ });
+
+ it("short titles are shown verbatim with app-name suffix stripped", () => {
+ const winA = makeWindow("Short - Trilium");
+ const winB = makeWindow("Other - Trilium");
+ fireAppCreated();
+ state.lastFocusedWindow = winA;
+ state.allWindows = [winA, winB];
+ state.ipcHandlers.get("reload-tray")?.();
+
+ const checkbox = (state.trayInstance?.lastTemplate ?? [])
+ .filter((i) => (i as { type?: string }).type === "checkbox")
+ .find((c) =>
+ typeof (c as { label?: string }).label === "string" &&
+ ((c as { label: string }).label).includes("Short")
+ ) as Electron.MenuItemConstructorOptions | undefined;
+ expect(checkbox?.label).toContain("Short");
+ expect(checkbox?.label).not.toContain("Trilium");
+ });
+ });
+
+ describe("registerVisibilityListener listeners", () => {
+ it("show/hide/minimize/maximize update the map and rebuild the menu", () => {
+ fireAppCreated();
+ const win = makeWindow();
+ state.lastFocusedWindow = win;
+ state.allWindows = [win];
+ state.ipcHandlers.get("reload-tray")?.();
+
+ const buildSpy = state.trayInstance?.setContextMenu;
+ const callsBefore = buildSpy?.mock.calls.length ?? 0;
+
+ win.listeners.get("show")?.();
+ win.listeners.get("hide")?.();
+ win.listeners.get("minimize")?.();
+ win.listeners.get("maximize")?.();
+
+ expect((buildSpy?.mock.calls.length ?? 0)).toBeGreaterThan(callsBefore);
+ });
+ });
+
+ // `createTray` runs `getTrayIconPath` exactly once per module instance and the
+ // module-level `tray` singleton can't be reset in-place. Re-import the module
+ // fresh (via vi.resetModules) so each icon-path branch executes from a clean
+ // creation. These run LAST so they don't disturb the shared top-level import.
+ describe("icon path branches (isolated module re-imports)", () => {
+ async function freshCreate(opts: {
+ isMac?: boolean;
+ isDev?: boolean;
+ nodeEnv?: string;
+ darkColors?: boolean;
+ }) {
+ state.isMac = opts.isMac ?? false;
+ state.isDev = opts.isDev ?? false;
+ state.shouldUseDarkColors = opts.darkColors ?? false;
+ state.disableTray = false;
+ state.dbInitialized = true;
+ state.lastFocusedWindow = null;
+ state.allWindows = [];
+ state.trayInstance = undefined;
+ state.appHandlers.clear();
+ state.nativeThemeHandlers.clear();
+ state.ipcHandlers.clear();
+ state.i18nHandlers.clear();
+ const prevNodeEnv = process.env.NODE_ENV;
+ if (opts.nodeEnv !== undefined) {
+ process.env.NODE_ENV = opts.nodeEnv;
+ }
+ becca.reset();
+ buildNote({ id: "_lbBookmarks", title: "Bookmarks" });
+ becca.getRecentNotesFromQuery = vi.fn(() => []) as unknown as typeof becca.getRecentNotesFromQuery;
+
+ vi.resetModules();
+ const fresh = await import("./tray.js");
+ fresh.setupSystemTray();
+ const handler = state.appHandlers.get("browser-window-created");
+ handler?.();
+
+ process.env.NODE_ENV = prevNodeEnv;
+ // The Tray constructor (re)assigns state.trayInstance via the handler
+ // call above; read it back through a fresh accessor so TS doesn't keep
+ // the `undefined` control-flow narrowing from the reset assignment.
+ return getTrayInstance();
+ }
+
+ it("mac uses the black template icon and skips the nativeTheme listener", async () => {
+ const instance = await freshCreate({ isMac: true });
+ if (!instance) throw new Error("tray not created");
+ const arg = (instance as unknown as { setToolTip: ReturnType<typeof vi.fn> });
+ expect(arg.setToolTip).toHaveBeenCalled();
+ // macOS template icons -> no nativeTheme "updated" listener.
+ expect(state.nativeThemeHandlers.has("updated")).toBe(false);
+ });
+
+ it("dev (non-mac) uses the purple icon", async () => {
+ const instance = await freshCreate({ isMac: false, isDev: true });
+ expect(instance).toBeDefined();
+ expect(state.nativeThemeHandlers.has("updated")).toBe(true);
+ });
+
+ it("production (non-dev, non-mac) resolves icons under the resource dir", async () => {
+ const instance = await freshCreate({
+ isMac: false,
+ isDev: false,
+ nodeEnv: "production",
+ darkColors: false
+ });
+ if (!instance) throw new Error("tray not created");
+ // getIconPath used the production (resource dir) branch for menu icons.
+ const newWindowItem = instance.lastTemplate.find(
+ (i) => (i as { label?: string }).label === "tray.open_new_window"
+ ) as Electron.MenuItemConstructorOptions | undefined;
+ expect(newWindowItem?.icon).toContain("/res/assets/images/tray/");
+ });
+ });
+});
diff --git a/apps/desktop/src/services/tray.ts b/apps/desktop/src/services/tray.ts
index e0ef7c24fa..e009068922 100644
--- a/apps/desktop/src/services/tray.ts
+++ b/apps/desktop/src/services/tray.ts
@@ -40,6 +40,7 @@ function getIconPath(name: string) {
}
function registerVisibilityListener(window: BrowserWindow) {
+ /* v8 ignore next 3 -- defensive: only ever called with a real window from updateWindowVisibilityMap's forEach */
if (!window) {
return;
}
@@ -59,6 +60,7 @@ function registerVisibilityListener(window: BrowserWindow) {
}
function getWindowTitle(window: BrowserWindow | null) {
+ /* v8 ignore next 3 -- defensive: only called with a window already null-checked via `if (!win) continue` */
if (!window) {
return;
}
@@ -97,6 +99,7 @@ function updateWindowVisibilityMap(allWindows: BrowserWindow[]) {
function updateTrayMenu() {
+ /* v8 ignore next 3 -- defensive: every call site runs after `tray` is assigned in createTray */
if (!tray) {
return;
}
@@ -105,6 +108,7 @@ function updateTrayMenu() {
updateWindowVisibilityMap(allWindows);
function ensureVisible(win: BrowserWindow) {
+ /* v8 ignore next -- defensive: always called with a truthy window (focused window or null-checked checkbox window) */
if (win) {
win.show();
win.focus();
@@ -135,6 +139,7 @@ function updateTrayMenu() {
const parentNote = becca.getNoteOrThrow("_lbBookmarks");
const menuItems: Electron.MenuItemConstructorOptions[] = [];
+ /* v8 ignore next -- defensive: getNoteOrThrow never returns null and BNote.children is always an array */
for (const bookmarkNote of parentNote?.children ?? []) {
if (bookmarkNote.isLabelTruthy("bookmarkFolder")) {
menuItems.push({
@@ -198,6 +203,7 @@ function updateTrayMenu() {
const id = parseInt(idStr, 10); // Get the ID of the window and make sure it is a number
const isVisible = windowVisibilityMap[id];
const win = allWindows.find(w => w.id === id);
+ /* v8 ignore next 3 -- defensive: windowVisibilityMap was just pruned to ids present in allWindows */
if (!win) {
continue;
}
diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.ts
new file mode 100644
index 0000000000..771073b00a
--- /dev/null
+++ b/apps/desktop/src/services/window.spec.ts
@@ -0,0 +1,880 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+type Handler = (...args: unknown[]) => unknown;
+
+// Mutable hoisted state controlling the mocked core + electron surfaces. Reset
+// in `beforeEach` so each test starts from a known platform / option baseline.
+const state = vi.hoisted(() => ({
+ isDev: true,
+ isMac: false,
+ isWindows: false,
+ appVersion: "1.0.0",
+ options: {} as Record<string, string>,
+ optionBools: {} as Record<string, boolean>,
+ keyboardActions: [] as unknown[],
+ log: { info: vi.fn(), error: vi.fn() },
+ // captured IPC handlers
+ ipcOn: new Map<string, Handler>(),
+ ipcHandle: new Map<string, Handler>(),
+ ipcEmit: vi.fn(),
+ // captured events.subscribe callbacks keyed by event name
+ eventSubs: new Map<string, Handler>(),
+ // captured BrowserWindow instances
+ windows: [] as FakeBrowserWindow[],
+ // controllable return for BrowserWindow.fromWebContents
+ fromWebContentsResult: undefined as undefined | "null" | FakeBrowserWindow,
+ // controllable globalShortcut.register results, consumed in order
+ registerResults: [] as boolean[],
+ // controllable nativeImage isEmpty / throw
+ nativeImageEmpty: false,
+ nativeImageThrow: false,
+ // when set, every new FakeWebContents reuses this session object
+ sharedSession: undefined as undefined | FakeSession
+}));
+
+interface FakeSession {
+ clearCache: ReturnType<typeof vi.fn>;
+ availableSpellCheckerLanguages: string[];
+ setSpellCheckerLanguages: ReturnType<typeof vi.fn>;
+}
+
+class FakeWebContents {
+ public send = vi.fn();
+ public on = vi.fn((event: string, cb: Handler) => {
+ const list = this.listeners.get(event) ?? [];
+ list.push(cb);
+ this.listeners.set(event, list);
+ return this;
+ });
+ public listeners = new Map<string, Handler[]>();
+ public setWindowOpenHandler = vi.fn();
+ public toggleDevTools = vi.fn();
+ public cut = vi.fn();
+ public copy = vi.fn();
+ public paste = vi.fn();
+ public pasteAndMatchStyle = vi.fn();
+ public insertText = vi.fn();
+ public session: FakeSession = state.sharedSession ?? {
+ clearCache: vi.fn(() => Promise.resolve()),
+ availableSpellCheckerLanguages: ["en-US", "de"],
+ setSpellCheckerLanguages: vi.fn()
+ };
+ public navigationHistory = {
+ canGoBack: vi.fn(() => true),
+ canGoForward: vi.fn(() => false),
+ getAllEntries: vi.fn(() => [{ url: "a" }]),
+ getActiveIndex: vi.fn(() => 0),
+ length: vi.fn(() => 1),
+ goToIndex: vi.fn(),
+ clear: vi.fn()
+ };
+ public getURL = vi.fn(() => "trilium-app://app/");
+
+ fire(event: string, ...args: unknown[]) {
+ const list = this.listeners.get(event);
+ if (!list || list.length === 0) throw new Error(`no webContents listener for ${event}`);
+ let result: unknown;
+ for (const cb of list) result = cb(...args);
+ return result;
+ }
+}
+
+class FakeBrowserWindow {
+ public webContents = new FakeWebContents();
+ public listeners = new Map<string, Handler[]>();
+ public on = vi.fn((event: string, cb: Handler) => {
+ const list = this.listeners.get(event) ?? [];
+ list.push(cb);
+ this.listeners.set(event, list);
+ return this;
+ });
+ public setMenuBarVisibility = vi.fn();
+ public removeMenu = vi.fn();
+ public loadURL = vi.fn(() => Promise.resolve());
+ public setTitleBarOverlay = vi.fn();
+ public setWindowButtonPosition = vi.fn();
+ public setBackgroundMaterial = vi.fn();
+ public setVibrancy = vi.fn();
+ public show = vi.fn();
+ public focus = vi.fn();
+ public minimize = vi.fn();
+ public maximize = vi.fn();
+ public unmaximize = vi.fn();
+ public isMaximized = vi.fn(() => true);
+ public isMinimized = vi.fn(() => true);
+ public restore = vi.fn();
+ public close = vi.fn();
+ public reload = vi.fn();
+ public isAlwaysOnTop = vi.fn(() => true);
+ public setAlwaysOnTop = vi.fn();
+ public isFullScreen = vi.fn(() => true);
+ public setFullScreen = vi.fn();
+ public isVisible = vi.fn(() => true);
+ public hide = vi.fn();
+ public isDestroyed = vi.fn(() => false);
+ public id = 1;
+
+ constructor(public readonly opts?: unknown) {
+ state.windows.push(this);
+ }
+
+ fire(event: string, ...args: unknown[]) {
+ const list = this.listeners.get(event);
+ if (!list || list.length === 0) throw new Error(`no window listener for ${event}`);
+ let result: unknown;
+ for (const cb of list) result = cb(...args);
+ return result;
+ }
+}
+
+const fakeBrowserWindowClass = Object.assign(FakeBrowserWindow, {
+ getAllWindows: () => state.windows,
+ fromWebContents: (_wc: unknown) => {
+ if (state.fromWebContentsResult === "null") return null;
+ if (state.fromWebContentsResult instanceof FakeBrowserWindow) {
+ return state.fromWebContentsResult;
+ }
+ return state.windows[state.windows.length - 1] ?? null;
+ }
+});
+
+const fakeShell = { openExternal: vi.fn(() => Promise.resolve()) };
+const fakeGlobalShortcut = {
+ register: vi.fn((_shortcut: string, _cb: Handler) =>
+ (state.registerResults.length ? state.registerResults.shift() : true))
+};
+const fakeNativeImage = {
+ createFromBuffer: vi.fn(() => {
+ if (state.nativeImageThrow) throw new Error("bad buffer");
+ return { isEmpty: () => state.nativeImageEmpty };
+ })
+};
+const fakeApp = {
+ setUserTasks: vi.fn(),
+ relaunch: vi.fn(),
+ exit: vi.fn()
+};
+
+const electronSurface = {
+ app: fakeApp,
+ shell: fakeShell,
+ globalShortcut: fakeGlobalShortcut,
+ nativeImage: fakeNativeImage,
+ clipboard: { writeImage: vi.fn() },
+ nativeTheme: { themeSource: "system" },
+ BrowserWindow: fakeBrowserWindowClass,
+ ipcMain: {
+ on: (channel: string, fn: Handler) => state.ipcOn.set(channel, fn),
+ handle: (channel: string, fn: Handler) => state.ipcHandle.set(channel, fn),
+ emit: (...args: unknown[]) => state.ipcEmit(...args)
+ }
+};
+
+vi.mock("electron", () => ({
+ default: electronSurface,
+ BrowserWindow: fakeBrowserWindowClass,
+ shell: fakeShell,
+ globalShortcut: fakeGlobalShortcut
+}));
+
+vi.mock("electron-window-state", () => ({
+ default: () => ({ x: 0, y: 0, width: 1200, height: 800, manage: vi.fn() })
+}));
+
+vi.mock("@triliumnext/core", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("@triliumnext/core")>();
+ return {
+ ...actual,
+ getLog: () => state.log,
+ app_info: { ...actual.app_info, get appVersion() { return state.appVersion; } },
+ utils: {
+ ...actual.utils,
+ isDev: () => state.isDev,
+ isMac: () => state.isMac,
+ isWindows: () => state.isWindows
+ },
+ options: {
+ ...actual.options,
+ getOption: (name: string) => state.options[name] ?? "",
+ getOptionBool: (name: string) => state.optionBools[name] ?? false
+ },
+ sql_init: { ...actual.sql_init, dbReady: Promise.resolve() },
+ keyboard_actions: { ...actual.keyboard_actions, getKeyboardActions: () => state.keyboardActions },
+ cls: { ...actual.cls, wrap: (fn: Handler) => fn },
+ events: {
+ ...actual.events,
+ DB_INITIALIZED: "DB_INITIALIZED",
+ subscribe: (event: string, cb: Handler) => state.eventSubs.set(event, cb)
+ }
+ };
+});
+
+const windowService = (await import("./window.js")).default;
+const { setupWindowing } = await import("./window.js");
+
+function fireOn(channel: string, event: unknown, ...args: unknown[]) {
+ const fn = state.ipcOn.get(channel);
+ if (!fn) throw new Error(`no on-handler for ${channel}`);
+ return fn(event, ...args);
+}
+
+function fireHandle(channel: string, event: unknown, ...args: unknown[]) {
+ const fn = state.ipcHandle.get(channel);
+ if (!fn) throw new Error(`no handle-handler for ${channel}`);
+ return fn(event, ...args);
+}
+
+function makeEvent() {
+ const win = state.windows[state.windows.length - 1] ?? new FakeBrowserWindow();
+ return { sender: win.webContents, returnValue: undefined as unknown };
+}
+
+// `window.ts` keeps `mainWindow` / `allWindows` in module-level state that
+// survives between tests. Drain it by marking every window we created as
+// destroyed and replaying its `closed` handler (which runs the destroyed-window
+// filter inside the module, clearing `allWindows` and nulling `mainWindow`).
+function resetModuleWindowState() {
+ for (const win of state.windows) {
+ win.isDestroyed.mockReturnValue(true);
+ const closed = win.listeners.get("closed");
+ if (closed) {
+ for (const cb of closed) cb();
+ }
+ }
+}
+
+beforeEach(() => {
+ resetModuleWindowState();
+ vi.clearAllMocks();
+ state.isDev = true;
+ state.isMac = false;
+ state.isWindows = false;
+ state.appVersion = "1.0.0";
+ state.options = { spellCheckLanguageCode: "en-US, de , " };
+ state.optionBools = {};
+ state.keyboardActions = [];
+ state.windows = [];
+ state.fromWebContentsResult = undefined;
+ state.registerResults = [];
+ state.nativeImageEmpty = false;
+ state.nativeImageThrow = false;
+ state.sharedSession = undefined;
+ process.env.NODE_ENV = "development";
+});
+
+afterEach(() => {
+ process.env.NODE_ENV = "development";
+});
+
+describe("window service", () => {
+ describe("createMainWindow", () => {
+ it("creates the main window with setUserTasks and Linux frame defaults", async () => {
+ await windowService.createMainWindow();
+
+ expect(fakeApp.setUserTasks).toHaveBeenCalled();
+ const win = state.windows[state.windows.length - 1];
+ expect(win.setMenuBarVisibility).toHaveBeenCalledWith(false);
+ expect(win.loadURL).toHaveBeenCalledWith("trilium-app://app/");
+ // closed handler nulls out mainWindow
+ win.fire("closed");
+ expect(windowService.getMainWindow()).toBeNull();
+ });
+
+ it("skips setUserTasks when not present on app", async () => {
+ const orig = fakeApp.setUserTasks;
+ delete (fakeApp as Record<string, unknown>).setUserTasks;
+ await windowService.createMainWindow();
+ (fakeApp as Record<string, unknown>).setUserTasks = orig;
+ expect(state.windows.length).toBeGreaterThan(0);
+ });
+
+ it("applies macOS hidden-inset title bar + vibrancy effects", async () => {
+ state.isMac = true;
+ state.optionBools = { backgroundEffects: true, spellCheckEnabled: true };
+ await windowService.createMainWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(opts.titleBarStyle).toBe("hiddenInset");
+ expect(opts.transparent).toBe(true);
+ expect(opts.visualEffectState).toBe("active");
+ });
+
+ it("applies Windows hidden title bar + mica material", async () => {
+ state.isWindows = true;
+ state.optionBools = { backgroundEffects: true };
+ await windowService.createMainWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(opts.titleBarStyle).toBe("hidden");
+ expect(opts.backgroundMaterial).toBe("auto");
+ });
+
+ it("applies Linux transparent effect when background effects enabled", async () => {
+ state.optionBools = { backgroundEffects: true };
+ await windowService.createMainWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(opts.frame).toBe(false);
+ expect(opts.transparent).toBe(true);
+ });
+
+ it("keeps native title bar when option enabled", async () => {
+ state.optionBools = { nativeTitleBarVisible: true };
+ await windowService.createMainWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(opts.frame).toBeUndefined();
+ });
+ });
+
+ describe("createExtraWindow", () => {
+ it("creates an extra window and configures web contents", async () => {
+ state.optionBools = { spellCheckEnabled: true };
+ await windowService.createExtraWindow("#root/abc");
+ const win = state.windows[state.windows.length - 1];
+ expect(win.loadURL).toHaveBeenCalledWith("trilium-app://app/?extraWindow=1#root/abc");
+ expect(win.webContents.setWindowOpenHandler).toHaveBeenCalled();
+ });
+ });
+
+ describe("createSetupWindow / closeSetupWindow", () => {
+ it("creates and closes a setup window (Linux)", async () => {
+ await windowService.createSetupWindow();
+ const win = state.windows[state.windows.length - 1];
+ expect(win.removeMenu).toHaveBeenCalled();
+ windowService.closeSetupWindow();
+ expect(win.close).toHaveBeenCalled();
+ // closed handler clears setupWindow; closing again is a no-op
+ win.fire("closed");
+ windowService.closeSetupWindow();
+ });
+
+ it("applies Windows mica background to the setup window", async () => {
+ state.isWindows = true;
+ await windowService.createSetupWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(opts.backgroundMaterial).toBe("mica");
+ });
+
+ it("applies macOS vibrancy to the setup window", async () => {
+ state.isMac = true;
+ await windowService.createSetupWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(opts.vibrancy).toBe("under-window");
+ });
+ });
+
+ describe("getIcon (via createSetupWindow)", () => {
+ it("uses the test asset icon when version contains 'test'", async () => {
+ process.env.NODE_ENV = "production";
+ state.appVersion = "1.0.0-test";
+ await windowService.createSetupWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(String(opts.icon)).toContain("icon-dev.png");
+ });
+
+ it("uses the production icon for a normal version", async () => {
+ process.env.NODE_ENV = "production";
+ state.appVersion = "1.0.0";
+ await windowService.createSetupWindow();
+ const opts = state.windows[state.windows.length - 1].opts as Record<string, unknown>;
+ expect(String(opts.icon)).toContain("icon.png");
+ });
+ });
+
+ describe("configureWebContents", () => {
+ beforeEach(async () => {
+ state.optionBools = { spellCheckEnabled: true };
+ await windowService.createMainWindow();
+ });
+
+ it("denies new windows and opens them externally", async () => {
+ const wc = state.windows[state.windows.length - 1].webContents;
+ const handlerArg = wc.setWindowOpenHandler.mock.calls[0][0] as Handler;
+ const result = handlerArg({ url: "https://example.com" });
+ expect(result).toEqual({ action: "deny" });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(fakeShell.openExternal).toHaveBeenCalledWith("https://example.com");
+ });
+
+ it("logs when external open fails", async () => {
+ // The inner `openExternal()` doesn't await `shell.openExternal`, so only a
+ // synchronous throw inside it rejects the wrapper and hits the `.catch`.
+ fakeShell.openExternal.mockImplementationOnce(() => {
+ throw new Error("boom");
+ });
+ const wc = state.windows[state.windows.length - 1].webContents;
+ const handlerArg = wc.setWindowOpenHandler.mock.calls[0][0] as Handler;
+ handlerArg({ url: "https://bad.example" });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(state.log.error).toHaveBeenCalled();
+ });
+
+ it("blocks external navigation but allows internal redirects", () => {
+ const wc = state.windows[state.windows.length - 1].webContents;
+ const external = { preventDefault: vi.fn() };
+ wc.fire("will-navigate", external, "https://evil.example/page");
+ expect(external.preventDefault).toHaveBeenCalled();
+
+ const internal = { preventDefault: vi.fn() };
+ wc.fire("will-navigate", internal, "trilium-app://app/");
+ expect(internal.preventDefault).not.toHaveBeenCalled();
+
+ // internal host but non-root path is blocked
+ const internalPath = { preventDefault: vi.fn() };
+ wc.fire("will-navigate", internalPath, "http://localhost/somewhere");
+ expect(internalPath.preventDefault).toHaveBeenCalled();
+
+ // URL with no hostname falls back to "" (covers `hostname || ""`) and is blocked.
+ const noHost = { preventDefault: vi.fn() };
+ wc.fire("will-navigate", noHost, "javascript:void(0)");
+ expect(noHost.preventDefault).toHaveBeenCalled();
+
+ // internal host with the root "/?" path is allowed (covers that path comparison).
+ const rootQuery = { preventDefault: vi.fn() };
+ wc.fire("will-navigate", rootQuery, "trilium-app://app/?");
+ expect(rootQuery.preventDefault).not.toHaveBeenCalled();
+ });
+
+ it("forwards full-screen, navigation and context-menu events", () => {
+ const win = state.windows[state.windows.length - 1];
+ const wc = win.webContents;
+
+ win.fire("enter-full-screen");
+ win.fire("leave-full-screen");
+ wc.fire("did-navigate");
+ wc.fire("did-navigate-in-page");
+ wc.fire("context-menu", {}, {
+ x: 1, y: 2, linkURL: "u", linkText: "t", mediaType: "none",
+ isEditable: true, selectionText: "s", misspelledWord: "",
+ dictionarySuggestions: [],
+ editFlags: { canCut: true, canCopy: true, canPaste: false }
+ });
+
+ expect(wc.send).toHaveBeenCalledWith("enter-full-screen");
+ expect(wc.send).toHaveBeenCalledWith("leave-full-screen");
+ expect(wc.send).toHaveBeenCalledWith("did-navigate");
+ expect(wc.send).toHaveBeenCalledWith("did-navigate-in-page");
+ expect(wc.send).toHaveBeenCalledWith("context-menu", expect.objectContaining({ x: 1 }));
+ });
+
+ it("skips full-screen wiring when no window resolves", async () => {
+ state.fromWebContentsResult = "null";
+ // configureWebContents is invoked during createExtraWindow
+ await windowService.createExtraWindow("#x");
+ // no throw means the null branch was taken
+ expect(true).toBe(true);
+ });
+
+ it("does not set up spellcheck when disabled", async () => {
+ state.optionBools = { spellCheckEnabled: false };
+ await windowService.createExtraWindow("#y");
+ const wc = state.windows[state.windows.length - 1].webContents;
+ expect(wc.session.setSpellCheckerLanguages).not.toHaveBeenCalled();
+ });
+
+ it("loads spellcheck languages once per session", async () => {
+ state.optionBools = { spellCheckEnabled: true };
+ state.options = { spellCheckLanguageCode: "en-US, de , " };
+ await windowService.createExtraWindow("#a");
+ const wc = state.windows[state.windows.length - 1].webContents;
+ expect(wc.session.setSpellCheckerLanguages).toHaveBeenCalledWith(["en-US", "de"]);
+
+ // Re-using the same session object skips the second load (WeakSet guard)
+ wc.session.setSpellCheckerLanguages.mockClear();
+ await windowService.createExtraWindow("#b");
+ // new window => new session, so it loads again; verify a fresh call happened
+ const wc2 = state.windows[state.windows.length - 1].webContents;
+ expect(wc2.session.setSpellCheckerLanguages).toHaveBeenCalled();
+ });
+ });
+
+ describe("setupSpellcheckForSession WeakSet guard", () => {
+ it("loads the session once and skips it on subsequent windows sharing it", async () => {
+ state.optionBools = { spellCheckEnabled: true };
+ state.options = { spellCheckLanguageCode: "en-US, fr" };
+ // Force every new window's webContents to share one session so the
+ // second configureWebContents call hits the WeakSet `has` guard.
+ const shared = {
+ clearCache: vi.fn(() => Promise.resolve()),
+ availableSpellCheckerLanguages: ["en-US"],
+ setSpellCheckerLanguages: vi.fn()
+ };
+ state.sharedSession = shared;
+
+ await windowService.createExtraWindow("#one");
+ expect(shared.setSpellCheckerLanguages).toHaveBeenCalledTimes(1);
+ expect(shared.setSpellCheckerLanguages).toHaveBeenCalledWith(["en-US", "fr"]);
+
+ await windowService.createExtraWindow("#two");
+ // Same session => guard short-circuits, no second load.
+ expect(shared.setSpellCheckerLanguages).toHaveBeenCalledTimes(1);
+
+ state.sharedSession = undefined;
+ });
+ });
+
+ describe("registerGlobalShortcuts", () => {
+ it("registers global shortcuts and logs success/failure", async () => {
+ state.keyboardActions = [
+ { actionName: "noShortcuts" },
+ { actionName: "emptyShortcuts", effectiveShortcuts: undefined },
+ { actionName: "localOnly", effectiveShortcuts: ["ctrl+a"] },
+ { actionName: "openApp", effectiveShortcuts: ["global:Ctrl+Shift+O"] },
+ { actionName: "toggleTray", effectiveShortcuts: ["global:Ctrl+Shift+T"] }
+ ];
+ // First register succeeds, second fails.
+ state.registerResults = [true, false];
+
+ await windowService.createMainWindow();
+ await windowService.registerGlobalShortcuts();
+
+ expect(fakeGlobalShortcut.register).toHaveBeenCalledTimes(2);
+ expect(state.log.info).toHaveBeenCalledWith(expect.stringContaining("Registered global shortcut"));
+ expect(state.log.info).toHaveBeenCalledWith(expect.stringContaining("Could not register"));
+ });
+
+ it("invokes the shortcut callback for toggleTray and normal actions", async () => {
+ state.keyboardActions = [
+ { actionName: "toggleTray", effectiveShortcuts: ["global:Ctrl+Shift+T"] },
+ { actionName: "openApp", effectiveShortcuts: ["global:Ctrl+Shift+O"] }
+ ];
+ await windowService.createMainWindow();
+ const mainWin = state.windows[state.windows.length - 1];
+ // Make this window the last focused.
+ mainWin.fire("focus");
+ await windowService.registerGlobalShortcuts();
+
+ const trayCb = fakeGlobalShortcut.register.mock.calls[0][1] as Handler;
+ const openCb = fakeGlobalShortcut.register.mock.calls[1][1] as Handler;
+
+ mainWin.isMinimized.mockReturnValue(false);
+ trayCb();
+ expect(mainWin.focus).toHaveBeenCalled();
+ expect(mainWin.webContents.send).toHaveBeenCalledWith("globalShortcut", "toggleTray");
+
+ // Minimized => showAndFocusWindow restores before showing.
+ mainWin.isMinimized.mockReturnValue(true);
+ openCb();
+ expect(mainWin.restore).toHaveBeenCalled();
+ expect(mainWin.show).toHaveBeenCalled();
+ expect(mainWin.webContents.send).toHaveBeenCalledWith("globalShortcut", "openApp");
+
+ // Not minimized => skips restore.
+ mainWin.restore.mockClear();
+ mainWin.isMinimized.mockReturnValue(false);
+ openCb();
+ expect(mainWin.restore).not.toHaveBeenCalled();
+ });
+
+ it("falls back to mainWindow and guards destroyed windows", async () => {
+ state.keyboardActions = [
+ { actionName: "openApp", effectiveShortcuts: ["global:Ctrl+Shift+O"] }
+ ];
+ await windowService.createMainWindow();
+ const mainWin = state.windows[state.windows.length - 1];
+ await windowService.registerGlobalShortcuts();
+ const cb = fakeGlobalShortcut.register.mock.calls[0][1] as Handler;
+
+ // No focused window => fall back to mainWindow, which is destroyed => early return.
+ mainWin.isDestroyed.mockReturnValue(true);
+ cb();
+ expect(mainWin.show).not.toHaveBeenCalled();
+
+ // Now with neither focused nor main window (close main): callback returns early.
+ mainWin.fire("closed");
+ });
+ });
+
+ describe("showAndFocusWindow / getters", () => {
+ it("restores, shows and focuses a minimized window", async () => {
+ await windowService.createMainWindow();
+ const win = state.windows[state.windows.length - 1];
+ win.fire("focus");
+ expect(windowService.getLastFocusedWindow()).toBe(win);
+ expect(windowService.getAllWindows()).toContain(win);
+ expect(windowService.getMainWindow()).toBe(win);
+ });
+
+ it("returns null for last focused window when none exist", () => {
+ expect(windowService.getLastFocusedWindow()).toBeNull();
+ });
+ });
+
+ describe("trackWindowFocus", () => {
+ it("reloads the tray on focus/closed when tray enabled", async () => {
+ state.optionBools = { disableTray: false };
+ await windowService.createMainWindow();
+ const win = state.windows[state.windows.length - 1];
+ win.fire("focus");
+ win.fire("closed");
+ expect(state.ipcEmit).toHaveBeenCalledWith("reload-tray");
+ });
+
+ it("does not reload the tray when tray disabled", async () => {
+ state.optionBools = { disableTray: true };
+ await windowService.createMainWindow();
+ const win = state.windows[state.windows.length - 1];
+ state.ipcEmit.mockClear();
+ win.fire("focus");
+ win.fire("closed");
+ expect(state.ipcEmit).not.toHaveBeenCalledWith("reload-tray");
+ });
+
+ it("dedupes re-focus and drops destroyed windows from the focus list", async () => {
+ await windowService.createMainWindow();
+ const winA = state.windows[state.windows.length - 1];
+ await windowService.createExtraWindow("#b");
+ const winB = state.windows[state.windows.length - 1];
+
+ winA.fire("focus");
+ winB.fire("focus");
+ // Re-focusing winB exercises the `w !== win` filter branch (it removes itself).
+ winB.fire("focus");
+ expect(windowService.getLastFocusedWindow()).toBe(winB);
+
+ // Destroy winA, then focus winB so the `!w.isDestroyed()` branch drops winA.
+ winA.isDestroyed.mockReturnValue(true);
+ winB.fire("focus");
+ expect(windowService.getAllWindows()).not.toContain(winA);
+ });
+ });
+
+ describe("setupWindowing IPC handlers", () => {
+ beforeEach(() => {
+ state.ipcOn.clear();
+ state.ipcHandle.clear();
+ state.eventSubs.clear();
+ setupWindowing();
+ // Provide a window so fromWebContents resolves.
+ new FakeBrowserWindow();
+ });
+
+ it("create-extra-window invokes createExtraWindow", async () => {
+ fireOn("create-extra-window", makeEvent(), { extraWindowHash: "#h" });
+ await new Promise((r) => setTimeout(r, 0));
+ expect(state.windows.some(w => w.loadURL.mock.calls.length > 0)).toBe(true);
+ });
+
+ it("reload-all-windows reloads every window", () => {
+ const win = state.windows[state.windows.length - 1];
+ fireOn("reload-all-windows", makeEvent());
+ expect(win.reload).toHaveBeenCalled();
+ });
+
+ it("restart-app relaunches and exits", () => {
+ fireOn("restart-app", makeEvent());
+ expect(fakeApp.relaunch).toHaveBeenCalled();
+ expect(fakeApp.exit).toHaveBeenCalled();
+ });
+
+ it("copy-image-to-clipboard writes a valid image", () => {
+ fireOn("copy-image-to-clipboard", makeEvent(), new Uint8Array([1, 2, 3]));
+ expect(electronSurface.clipboard.writeImage).toHaveBeenCalled();
+ });
+
+ it("copy-image-to-clipboard logs when the image is empty", () => {
+ state.nativeImageEmpty = true;
+ fireOn("copy-image-to-clipboard", makeEvent(), new Uint8Array([1]));
+ expect(state.log.error).toHaveBeenCalledWith(expect.stringContaining("nativeImage is empty"));
+ expect(electronSurface.clipboard.writeImage).not.toHaveBeenCalled();
+ });
+
+ it("copy-image-to-clipboard logs when conversion throws", () => {
+ state.nativeImageThrow = true;
+ fireOn("copy-image-to-clipboard", makeEvent(), new Uint8Array([1]));
+ expect(state.log.error).toHaveBeenCalledWith(expect.stringContaining("failed"));
+ });
+
+ it("show-window shows the resolved window (and tolerates null)", () => {
+ const win = state.windows[state.windows.length - 1];
+ fireOn("show-window", makeEvent());
+ expect(win.show).toHaveBeenCalled();
+
+ state.fromWebContentsResult = "null";
+ fireOn("show-window", makeEvent());
+ });
+
+ it("clear-cache clears the session cache", async () => {
+ const ev = makeEvent();
+ await fireHandle("clear-cache", ev);
+ expect(ev.sender.session.clearCache).toHaveBeenCalled();
+ });
+
+ it("toggle-all-windows hides when all visible and shows when hidden", () => {
+ const win = state.windows[state.windows.length - 1];
+ win.isVisible.mockReturnValue(true);
+ fireOn("toggle-all-windows", makeEvent());
+ expect(win.hide).toHaveBeenCalled();
+
+ win.isVisible.mockReturnValue(false);
+ fireOn("toggle-all-windows", makeEvent());
+ expect(win.show).toHaveBeenCalled();
+ });
+
+ it("get-available-spellchecker-languages returns the list", () => {
+ const ev = makeEvent();
+ fireOn("get-available-spellchecker-languages", ev);
+ expect(ev.returnValue).toEqual(["en-US", "de"]);
+ });
+
+ it("title bar / material / vibrancy / button position setters", () => {
+ const win = state.windows[state.windows.length - 1];
+ fireOn("set-title-bar-overlay", makeEvent(), { color: "#fff", symbolColor: "#000" });
+ fireOn("set-window-button-position", makeEvent(), { x: 1, y: 2 });
+ fireOn("set-background-material", makeEvent(), "mica");
+ fireOn("set-vibrancy", makeEvent(), "sidebar");
+ fireOn("clear-navigation-history", makeEvent());
+ expect(win.setTitleBarOverlay).toHaveBeenCalled();
+ expect(win.setWindowButtonPosition).toHaveBeenCalled();
+ expect(win.setBackgroundMaterial).toHaveBeenCalledWith("mica");
+ expect(win.setVibrancy).toHaveBeenCalledWith("sidebar");
+ expect(win.webContents.navigationHistory.clear).toHaveBeenCalled();
+ });
+
+ it("title bar setters tolerate a null window", () => {
+ state.fromWebContentsResult = "null";
+ fireOn("set-title-bar-overlay", makeEvent(), { color: "#fff", symbolColor: "#000" });
+ fireOn("set-window-button-position", makeEvent(), { x: 1, y: 2 });
+ fireOn("set-background-material", makeEvent(), "mica");
+ fireOn("set-vibrancy", makeEvent(), "sidebar");
+ fireOn("clear-navigation-history", makeEvent());
+ // no throw
+ });
+
+ it("set-native-theme-source updates the theme", () => {
+ fireOn("set-native-theme-source", makeEvent(), "dark");
+ expect(electronSurface.nativeTheme.themeSource).toBe("dark");
+ });
+
+ it("toggle-dev-tools toggles dev tools on the sender", () => {
+ const ev = makeEvent();
+ fireOn("toggle-dev-tools", ev);
+ expect(ev.sender.toggleDevTools).toHaveBeenCalled();
+ });
+
+ it("window state queries and mutations", () => {
+ const win = state.windows[state.windows.length - 1];
+ const fs1 = makeEvent();
+ fireOn("is-full-screen", fs1);
+ expect(fs1.returnValue).toBe(true);
+ fireOn("set-full-screen", makeEvent(), true);
+ fireOn("minimize-window", makeEvent());
+ fireOn("maximize-window", makeEvent());
+ fireOn("unmaximize-window", makeEvent());
+ const mx = makeEvent();
+ fireOn("is-maximized", mx);
+ expect(mx.returnValue).toBe(true);
+ fireOn("close-window", makeEvent());
+ const aot = makeEvent();
+ fireOn("is-always-on-top", aot);
+ expect(aot.returnValue).toBe(true);
+ fireOn("set-always-on-top", makeEvent(), true);
+
+ expect(win.setFullScreen).toHaveBeenCalledWith(true);
+ expect(win.minimize).toHaveBeenCalled();
+ expect(win.maximize).toHaveBeenCalled();
+ expect(win.unmaximize).toHaveBeenCalled();
+ expect(win.close).toHaveBeenCalled();
+ expect(win.setAlwaysOnTop).toHaveBeenCalledWith(true);
+ });
+
+ it("window state queries return defaults when window is null", () => {
+ state.fromWebContentsResult = "null";
+ const fs1 = makeEvent();
+ fireOn("is-full-screen", fs1);
+ expect(fs1.returnValue).toBe(false);
+ const mx = makeEvent();
+ fireOn("is-maximized", mx);
+ expect(mx.returnValue).toBe(false);
+ const aot = makeEvent();
+ fireOn("is-always-on-top", aot);
+ expect(aot.returnValue).toBe(false);
+ // mutations tolerate null
+ fireOn("set-full-screen", makeEvent(), true);
+ fireOn("minimize-window", makeEvent());
+ fireOn("maximize-window", makeEvent());
+ fireOn("unmaximize-window", makeEvent());
+ fireOn("close-window", makeEvent());
+ fireOn("set-always-on-top", makeEvent(), true);
+ });
+
+ it("web-contents-action covers every case", () => {
+ const ev = makeEvent();
+ fireOn("web-contents-action", ev, "cut");
+ fireOn("web-contents-action", ev, "copy");
+ fireOn("web-contents-action", ev, "paste");
+ fireOn("web-contents-action", ev, "pasteAndMatchStyle");
+ fireOn("web-contents-action", ev, "insertText", "hello");
+ fireOn("web-contents-action", ev, "insertText"); // no text => skipped
+ fireOn("web-contents-action", ev, "unknown"); // default => nothing
+
+ expect(ev.sender.cut).toHaveBeenCalled();
+ expect(ev.sender.copy).toHaveBeenCalled();
+ expect(ev.sender.paste).toHaveBeenCalled();
+ expect(ev.sender.pasteAndMatchStyle).toHaveBeenCalled();
+ expect(ev.sender.insertText).toHaveBeenCalledTimes(1);
+ expect(ev.sender.insertText).toHaveBeenCalledWith("hello");
+ });
+
+ it("navigation-history covers every method and the default", () => {
+ const back = makeEvent();
+ fireOn("navigation-history", back, "canGoBack");
+ expect(back.returnValue).toBe(true);
+ const fwd = makeEvent();
+ fireOn("navigation-history", fwd, "canGoForward");
+ expect(fwd.returnValue).toBe(false);
+ const all = makeEvent();
+ fireOn("navigation-history", all, "getAllEntries");
+ expect(all.returnValue).toEqual([{ url: "a" }]);
+ const idx = makeEvent();
+ fireOn("navigation-history", idx, "getActiveIndex");
+ expect(idx.returnValue).toBe(0);
+ const len = makeEvent();
+ fireOn("navigation-history", len, "length");
+ expect(len.returnValue).toBe(1);
+ const def = makeEvent();
+ fireOn("navigation-history", def, "bogus");
+ expect(def.returnValue).toBeNull();
+ });
+
+ it("navigation-history-go-to-index delegates to the sender", () => {
+ const ev = makeEvent();
+ fireOn("navigation-history-go-to-index", ev, 3);
+ expect(ev.sender.navigationHistory.goToIndex).toHaveBeenCalledWith(3);
+ });
+ });
+
+ describe("DB_INITIALIZED subscription", () => {
+ beforeEach(() => {
+ state.eventSubs.clear();
+ setupWindowing();
+ });
+
+ it("no-ops when there is no setup window", async () => {
+ const cb = state.eventSubs.get("DB_INITIALIZED");
+ if (!cb) throw new Error("no DB_INITIALIZED subscriber");
+ const sizeBefore = state.windows.length;
+ await cb();
+ expect(state.windows.length).toBe(sizeBefore);
+ });
+
+ it("swaps the setup window for the main window", async () => {
+ await windowService.createSetupWindow();
+ const setupWin = state.windows[state.windows.length - 1];
+ const cb = state.eventSubs.get("DB_INITIALIZED");
+ if (!cb) throw new Error("no DB_INITIALIZED subscriber");
+ await cb();
+ expect(setupWin.close).toHaveBeenCalled();
+ });
+
+ it("logs when creating the main window throws", async () => {
+ await windowService.createSetupWindow();
+ const cb = state.eventSubs.get("DB_INITIALIZED");
+ if (!cb) throw new Error("no DB_INITIALIZED subscriber");
+ // Make BrowserWindow construction throw on the next createMainWindow.
+ const spy = vi.spyOn(state.windows, "push").mockImplementationOnce(() => {
+ throw new Error("construct failed");
+ });
+ await cb();
+ spy.mockRestore();
+ expect(state.log.error).toHaveBeenCalledWith(expect.stringContaining("Failed to swap"));
+ });
+ });
+});
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index e989cfed5b..c4fa1ed5b4 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -17,6 +17,7 @@ import url from "url";
let preloadScriptCache: string | undefined;
function getPreloadScript(): string {
if (preloadScriptCache === undefined) {
+ /* v8 ignore next 5 -- prod preload arm is cache-once (only the first ternary evaluation counts); covered by the production build, not unit tests */
preloadScriptCache = path.resolve(
coreUtils.isDev()
? path.join(__dirname, "..", "preload.compiled.cjs")
@@ -328,6 +329,7 @@ async function registerGlobalShortcuts() {
}
function showAndFocusWindow(window: BrowserWindow) {
+ /* v8 ignore next -- defensive guard; every caller passes a non-null window narrowed beforehand */
if (!window) return;
if (window.isMinimized()) {