Skip to content

Build your personal knowledge base with Trilium Notes

chore(desktop): handle Squirrel installer events without a dependency

Elian Doran56e9aff6d8bd
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 3faf057953..706aba08ef 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -35,7 +35,6 @@
"better-sqlite3": "13.0.3",
"electron-debug": "5.0.0",
"electron-dl": "5.0.0",
- "electron-squirrel-startup": "1.0.1",
"electron-window-state": "5.0.3",
"sherpa-onnx-node": "1.13.8"
},
@@ -53,7 +52,6 @@
"@triliumnext/commons": "workspace:*",
"@triliumnext/core": "workspace:*",
"@triliumnext/server": "workspace:*",
- "@types/electron-squirrel-startup": "1.0.2",
"@types/pngjs": "6.0.5",
"electron": "45.0.0",
"gifenc": "1.0.3",
diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.ts
index 177a82b865..68db2a2209 100644
--- a/apps/desktop/src/main.spec.ts
+++ b/apps/desktop/src/main.spec.ts
@@ -1,4 +1,4 @@
-import { join as pathJoin } from "node:path";
+import { join as pathJoin, resolve as pathResolve } from "node:path";
import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -50,7 +50,7 @@ const h = vi.hoisted(() => ({
setPath: vi.fn(),
setUserTasks: vi.fn(),
// Controllable values.
- squirrel: { default: false as boolean },
+ spawn: vi.fn(),
isPrimaryInstance: true as boolean,
allWindows: [] as unknown[],
smoothScroll: "true" as string | null,
@@ -133,7 +133,10 @@ vi.mock("electron", () => {
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("child_process", async (importOriginal) => ({
+ ...await importOriginal<typeof import("child_process")>(),
+ spawn: (...a: unknown[]) => h.spawn(...a)
+}));
vi.mock("fs", () => ({ default: { readFileSync: vi.fn(() => Buffer.from("zip")) } }));
vi.mock("i18next", () => ({ t: (key: string) => key }));
@@ -273,7 +276,7 @@ function resetState() {
h.quit.mockClear();
h.exit.mockClear();
h.setPath.mockClear();
- h.squirrel.default = false;
+ h.spawn.mockClear();
h.isPrimaryInstance = true;
h.allWindows = [];
h.smoothScroll = "true";
@@ -349,7 +352,7 @@ describe("main() bootstrap", () => {
const { main } = await importMain();
await main();
- // Streams got an error handler; squirrel false → no exit.
+ // Streams got an error handler; no Squirrel event → no exit.
expect(h.streamErrorHandlers.length).toBe(2);
expect(exitSpy).not.toHaveBeenCalled();
@@ -467,6 +470,48 @@ describe("main() bootstrap", () => {
expect(h.appendSwitch).toHaveBeenCalledWith("lang", "de");
});
+ it("hands a Squirrel installer event to Update.exe and exits", async () => {
+ const originalArgv = process.argv;
+ const originalExecPath = process.execPath;
+ Object.defineProperty(process, "execPath", { value: "/opt/trilium/app-1.0.0/trilium.exe", configurable: true });
+ try {
+ for (const [ event, action ] of [
+ [ "--squirrel-install", "--createShortcut=trilium.exe" ],
+ [ "--squirrel-updated", "--createShortcut=trilium.exe" ],
+ [ "--squirrel-uninstall", "--removeShortcut=trilium.exe" ]
+ ]) {
+ setPlatform("win32");
+ process.argv = [ "trilium.exe", event ];
+ h.spawn.mockClear();
+ exitSpy.mockClear();
+ const { main } = await importMain();
+ await expect(main()).rejects.toThrow("__exit__");
+ expect(h.spawn).toHaveBeenCalledWith(
+ pathResolve("/opt/trilium/Update.exe"), [ action ], { detached: true });
+ expect(exitSpy).toHaveBeenCalledWith(0);
+ vi.resetModules();
+ }
+
+ // An obsolete version exits without touching the shortcuts.
+ process.argv = [ "trilium.exe", "--squirrel-obsolete" ];
+ h.spawn.mockClear();
+ await expect((await importMain()).main()).rejects.toThrow("__exit__");
+ expect(h.spawn).not.toHaveBeenCalled();
+ vi.resetModules();
+
+ // The same flags mean nothing outside Windows.
+ setPlatform("linux");
+ process.argv = [ "trilium", "--squirrel-install" ];
+ exitSpy.mockClear();
+ await (await importMain()).main();
+ expect(h.spawn).not.toHaveBeenCalled();
+ expect(exitSpy).not.toHaveBeenCalled();
+ } finally {
+ process.argv = originalArgv;
+ Object.defineProperty(process, "execPath", { value: originalExecPath, configurable: true });
+ }
+ });
+
it("exits when it is not the primary instance", async () => {
h.isPrimaryInstance = false;
const { main } = await importMain();
diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts
index 8c8ae15152..8c6449f6c2 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -14,6 +14,7 @@ import { RESOURCE_DIR } from "@triliumnext/server/src/services/resource_dir.js";
import WebSocketMessagingProvider from "@triliumnext/server/src/services/ws_messaging_provider.js";
import BetterSqlite3Provider from "@triliumnext/server/src/sql_provider.js";
import NodejsZipProvider from "@triliumnext/server/src/zip_provider.js";
+import { spawn } from "child_process";
import { app, BrowserWindow,globalShortcut } from "electron";
import electronDebug from "electron-debug";
import electronDl from "electron-dl";
@@ -81,8 +82,7 @@ export async function main() {
setupTriliumAppProtocol(expressAppPromise);
// Prevent Trilium starting twice on first install and on uninstall for the Windows installer.
- /* v8 ignore next 3 -- squirrel uses a CJS require() that vi.mock cannot intercept, so the truthy/exit path is un-coverable in unit tests */
- if ((require("electron-squirrel-startup")).default) {
+ if (handleSquirrelEvent()) {
process.exit(0);
}
@@ -334,6 +334,36 @@ function readDbOption(provider: BetterSqlite3Provider, name: string): string | n
}
}
+/**
+ * Handles the `--squirrel-*` argument the Squirrel.Windows installer launches the app with: on
+ * install, update or uninstall, `Update.exe` (one directory above the versioned app directory)
+ * creates or removes the shortcuts. Returns `true` when the app was launched for such an event and
+ * must exit instead of starting.
+ */
+function handleSquirrelEvent() {
+ if (process.platform !== "win32") {
+ return false;
+ }
+
+ const target = path.basename(process.execPath);
+ const actions: Record<string, string | null> = {
+ "--squirrel-install": `--createShortcut=${target}`,
+ "--squirrel-updated": `--createShortcut=${target}`,
+ "--squirrel-uninstall": `--removeShortcut=${target}`,
+ "--squirrel-obsolete": null
+ };
+ const action = actions[process.argv[1] ?? ""];
+ if (action === undefined) {
+ return false;
+ }
+
+ if (action) {
+ const updateExe = path.resolve(path.dirname(process.execPath), "..", "Update.exe");
+ spawn(updateExe, [ action ], { detached: true });
+ }
+ return true;
+}
+
/**
* Returns a unique user data directory for Electron so that single instance locks between legitimately different instances such as different port or data directory can still act independently, but we are focusing the main window otherwise.
*
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0c3f28396c..594c3060eb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -428,9 +428,6 @@ importers:
electron-dl:
specifier: 5.0.0
version: 5.0.0
- electron-squirrel-startup:
- specifier: 1.0.1
- version: 1.0.1([email protected])
electron-window-state:
specifier: 5.0.3
version: 5.0.3
@@ -477,9 +474,6 @@ importers:
'@triliumnext/server':
specifier: workspace:*
version: link:../server
- '@types/electron-squirrel-startup':
- specifier: 1.0.2
- version: 1.0.2
'@types/pngjs':
specifier: 6.0.5
version: 6.0.5
@@ -4807,9 +4801,6 @@ packages:
resolution: {integrity: sha512-nv+GSx77ZtXiJzwKdsASqi+YQ5Z7vwHsTP0JY2SiQgjGckkBRKZnk8nIM+7oUZ1VCtuTz0+By4qVR7fqzp/Dfg==}
- '@types/[email protected]':
- resolution: {integrity: sha512-AzxnvBzNh8K/0SmxMmZtpJf1/IWoGXLP+pQDuUaVkPyotI8ryvAtBSqgxR/qOSvxWHYWrxkeNsJ+Ca5xOuUxJQ==}
-
resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}
@@ -7020,9 +7011,6 @@ packages:
resolution: {integrity: sha512-8TjjAh8Ec51hUi3o4TaU0mD3GMTOESi866oRNavj9A3IQJ7pmv+MJVmdZBFGw4GFT36X7bkqnuDNYvkQgvyI8Q==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-sTfFIHGku+7PsHLJ7v0dRcZNkALrV+YEozINTW8X1nM//e5O3L+rfYuvSW00lmGHnYmUjARZulD8F2V8ISI9RA==}
-
resolution: {integrity: sha512-2Gcq6inCQs/AqfHP3f5ftCzk+pqeW2VlA1LgmPqEj2hfBO8HiZRspNYkD4HzFBe4u6lGqca4BspFr6Ix4Q400g==}
@@ -15775,8 +15763,6 @@ snapshots:
'@types/[email protected]': {}
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -18638,12 +18624,6 @@ snapshots:
- dependencies:
- debug: 2.6.9([email protected])
- transitivePeerDependencies:
- - supports-color
-