Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(desktop): add launch-on-startup option
Elian Doran77ced83f5ae9
diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.tsindex 17c1a11832..352a682e38 100644--- a/apps/client/src/services/utils.ts+++ b/apps/client/src/services/utils.ts@@ -36,6 +36,15 @@ function reloadTray() {window.electronApi?.tray.reloadTray();}+/**+ * Re-applies the OS autostart entry after the `launchOnStartup` option changes.+ *+ * On any other platform than Electron, nothing happens.+ */+function reapplyLaunchOnStartup() {+ window.electronApi?.autoLaunch.reapply();+}+function parseDate(str: string) {try {return new Date(Date.parse(str));@@ -864,6 +873,7 @@ export default {reloadFrontendApp,restartDesktopApp,reloadTray,+ reapplyLaunchOnStartup,parseDate,formatDateISO,formatDateTime,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ce7ec9fa41..8690e68bb5 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1519,6 +1519,11 @@"custom_url_placeholder": "Search engine URL","save_button": "Save"},+ "startup": {+ "title": "Startup",+ "launch_on_startup": "Launch on startup",+ "launch_on_startup_description": "Open Trilium automatically when you log into your computer."+ },"tray": {"title": "System Tray","enable_tray": "Tray icon",diff --git a/apps/client/src/widgets/type_widgets/options/other.tsx b/apps/client/src/widgets/type_widgets/options/other.tsxindex 042ba4160d..e7c9874337 100644--- a/apps/client/src/widgets/type_widgets/options/other.tsx+++ b/apps/client/src/widgets/type_widgets/options/other.tsx@@ -21,6 +21,7 @@ export default function OtherSettings() {<SearchSettings />{isElectron() && <><SearchEngineSettings />+ <StartupSettings /><TrayOptionsSettings /></>}<NoteErasureTimeout />@@ -107,6 +108,26 @@ function SearchEngineSettings() {);}+function StartupSettings() {+ const [ launchOnStartup, setLaunchOnStartup ] = useTriliumOptionBool("launchOnStartup");++ return (+ <OptionsSection title={t("startup.title")}>+ <OptionsRowWithToggle+ name="launch-on-startup"+ label={t("startup.launch_on_startup")}+ description={t("startup.launch_on_startup_description")}+ currentValue={launchOnStartup}+ onChange={async enabled => {+ await setLaunchOnStartup(enabled);+ // Apply the change immediately so the user doesn't have to restart the app.+ utils.reapplyLaunchOnStartup();+ }}+ />+ </OptionsSection>+ );+}+function TrayOptionsSettings() {const [ disableTray, setDisableTray ] = useTriliumOptionBool("disableTray");const [ closeToTray, setCloseToTray ] = useTriliumOptionBool("closeToTray");diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex 0e79e54812..9d19b84878 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -63,6 +63,8 @@ const h = vi.hoisted(() => ({createSetupWindow: vi.fn((..._a: unknown[]) => Promise.resolve()),createExtraWindow: vi.fn((..._a: unknown[]) => {}),registerGlobalShortcuts: vi.fn((..._a: unknown[]) => Promise.resolve()),+ setupAutoLaunch: vi.fn(),+ applyLaunchOnStartup: vi.fn(),unregisterAll: vi.fn(),// Controllable server start so tests can simulate a slow/hanging server.startServer: (() => Promise.resolve({})) as () => Promise<unknown>@@ -177,6 +179,10 @@ vi.mock("./protocol", () => ({ registerTriliumAppScheme: vi.fn(), setupTriliumApvi.mock("./services/custom_dictionary", () => ({ setupCustomDictionary: vi.fn() }));vi.mock("./services/printing", () => ({ setupPrintingHandlers: vi.fn() }));vi.mock("./services/tray", () => ({ setupSystemTray: vi.fn() }));+vi.mock("./services/auto_launch", () => ({+ setupAutoLaunch: (...a: unknown[]) => h.setupAutoLaunch(...a),+ applyLaunchOnStartup: (...a: unknown[]) => h.applyLaunchOnStartup(...a)+}));vi.mock("./services/shell", () => ({ setupShellHandlers: vi.fn() }));vi.mock("./services/security_settings", () => ({getSecuritySettings: () => h.securitySettings,@@ -423,6 +429,9 @@ describe("app event handlers", () => {expect(h.createMainWindow).toHaveBeenCalledTimes(1);expect(h.registerGlobalShortcuts).toHaveBeenCalled();+ // The autostart entry is reconciled with the stored option on a DB-ready boot.+ expect(h.setupAutoLaunch).toHaveBeenCalled();+ expect(h.applyLaunchOnStartup).toHaveBeenCalled();// The "activate" handler is registered on darwin.const activate = h.appOn.get("activate");diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 1b257f00e4..bff0b031ab 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -25,6 +25,7 @@ import { PRODUCT_NAME } from "./app-info";import IpcMessagingProvider from "./ipc_messaging_provider";import DesktopPlatformProvider from "./platform_provider";import { registerTriliumAppScheme, setupTriliumAppProtocol } from "./protocol";+import { applyLaunchOnStartup, setupAutoLaunch } from "./services/auto_launch";import { setupCustomDictionary } from "./services/custom_dictionary";import { setupPrintingHandlers } from "./services/printing";import { getSecuritySettings, registerSecurityIpcHandlers } from "./services/security_settings";@@ -119,6 +120,7 @@ export async function main() {setupWindowing();setupSystemTray();+ setupAutoLaunch();setupCustomDictionary();setupShellHandlers();setupPrintingHandlers();@@ -263,6 +265,11 @@ async function onReady() {await windowService.createMainWindow();+ // Repair the OS autostart entry so it matches the stored option (it can+ // drift if the user toggled it elsewhere). Options are loaded now that the+ // DB is ready.+ applyLaunchOnStartup();+if (process.platform === "darwin") {app.on("activate", async () => {if (BrowserWindow.getAllWindows().length === 0) {diff --git a/apps/desktop/src/preload.spec.ts b/apps/desktop/src/preload.spec.tsindex b3b25ea072..c53ab5667a 100644--- a/apps/desktop/src/preload.spec.ts+++ b/apps/desktop/src/preload.spec.ts@@ -380,6 +380,15 @@ describe("preload script", () => {});});+ describe("autoLaunch", () => {+ const autoLaunch = () => getGroup("autoLaunch");++ it("reapply sends correct IPC message", () => {+ autoLaunch().reapply();+ expect(ipcRendererSent).toContainEqual({ channel: "reapply-launch-on-startup", args: [] });+ });+ });+describe("printing", () => {const printing = () => getGroup("printing");diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.tsindex 7e7a63bf4b..0dd6a525ec 100644--- a/apps/desktop/src/preload.ts+++ b/apps/desktop/src/preload.ts@@ -161,6 +161,12 @@ contextBridge.exposeInMainWorld("electronApi", {}},+ autoLaunch: {+ reapply() {+ ipcRenderer.send("reapply-launch-on-startup");+ }+ },+printing: {sendPrintProgress(progress: number) {ipcRenderer.send("print-progress", progress);diff --git a/apps/desktop/src/services/auto_launch.spec.ts b/apps/desktop/src/services/auto_launch.spec.tsnew file mode 100644index 0000000000..3f7c520ddb--- /dev/null+++ b/apps/desktop/src/services/auto_launch.spec.ts@@ -0,0 +1,153 @@+import path from "path";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++type Handler = (...args: unknown[]) => unknown;++const state = vi.hoisted(() => ({+ launchOnStartup: false,+ appName: "Trilium Notes",+ setLoginItemSettings: vi.fn(),+ setLoginItemThrows: false,+ ipcOn: new Map<string, Handler>(),+ mkdirSync: vi.fn(),+ writeFileSync: vi.fn(),+ rmSync: vi.fn(),+ log: { info: vi.fn(), error: vi.fn() }+}));++vi.mock("electron", () => ({+ default: {+ app: {+ setLoginItemSettings: (...a: unknown[]) => {+ if (state.setLoginItemThrows) throw new Error("boom");+ return state.setLoginItemSettings(...a);+ },+ getName: () => state.appName+ },+ ipcMain: {+ on: (channel: string, fn: Handler) => state.ipcOn.set(channel, fn)+ }+ }+}));++vi.mock("fs", () => ({+ default: {+ mkdirSync: (...a: unknown[]) => state.mkdirSync(...a),+ writeFileSync: (...a: unknown[]) => state.writeFileSync(...a),+ rmSync: (...a: unknown[]) => state.rmSync(...a)+ }+}));++vi.mock("os", () => ({ default: { homedir: () => "/home/user" } }));++vi.mock("@triliumnext/core", () => ({+ getLog: () => state.log,+ options: { getOptionBool: (name: string) => (name === "launchOnStartup" ? state.launchOnStartup : false) },+ utils: { safeExtractMessageAndStackFromError: (e: unknown) => String(e) }+}));++const { applyLaunchOnStartup, setupAutoLaunch } = await import("./auto_launch.js");++// Built with the same path.join as the module so the assertions hold on every OS.+const AUTOSTART_DIR = path.join("/home/user", ".config", "autostart");+const DESKTOP_FILE = path.join(AUTOSTART_DIR, "trilium.desktop");++const ORIGINAL_PLATFORM = process.platform;+const ORIGINAL_EXECPATH = process.execPath;++function setPlatform(p: NodeJS.Platform) {+ Object.defineProperty(process, "platform", { value: p, configurable: true });+}++function setExecPath(p: string) {+ Object.defineProperty(process, "execPath", { value: p, configurable: true });+}++beforeEach(() => {+ vi.clearAllMocks();+ state.launchOnStartup = false;+ state.setLoginItemThrows = false;+ state.ipcOn.clear();+ delete process.env.APPIMAGE;+});++afterEach(() => {+ setPlatform(ORIGINAL_PLATFORM);+ setExecPath(ORIGINAL_EXECPATH);+ delete process.env.APPIMAGE;+});++describe("auto_launch", () => {+ it("enables the OS login item on Windows/macOS when the option is on", () => {+ setPlatform("win32");+ state.launchOnStartup = true;+ applyLaunchOnStartup();+ expect(state.setLoginItemSettings).toHaveBeenCalledWith({ openAtLogin: true });+ });++ it("disables the OS login item when the option is off", () => {+ setPlatform("darwin");+ state.launchOnStartup = false;+ applyLaunchOnStartup();+ expect(state.setLoginItemSettings).toHaveBeenCalledWith({ openAtLogin: false });+ });++ it("writes a .desktop autostart file on Linux when enabled", () => {+ setPlatform("linux");+ setExecPath("/opt/trilium/trilium");+ state.launchOnStartup = true;++ applyLaunchOnStartup();++ expect(state.mkdirSync).toHaveBeenCalledWith(AUTOSTART_DIR, { recursive: true });+ const [file, content] = state.writeFileSync.mock.calls[0] as [string, string];+ expect(file).toBe(DESKTOP_FILE);+ expect(content).toContain("[Desktop Entry]");+ expect(content).toContain('Exec="/opt/trilium/trilium"');+ expect(content).toContain("Name=Trilium Notes");+ // Linux must not touch the (no-op) Electron login-item API.+ expect(state.setLoginItemSettings).not.toHaveBeenCalled();+ });++ it("prefers APPIMAGE over execPath for the Linux Exec line", () => {+ setPlatform("linux");+ setExecPath("/tmp/electron");+ process.env.APPIMAGE = "/home/user/Apps/Trilium.AppImage";+ state.launchOnStartup = true;++ applyLaunchOnStartup();++ const [, content] = state.writeFileSync.mock.calls[0] as [string, string];+ expect(content).toContain('Exec="/home/user/Apps/Trilium.AppImage"');+ });++ it("removes the .desktop file on Linux when disabled", () => {+ setPlatform("linux");+ state.launchOnStartup = false;++ applyLaunchOnStartup();++ expect(state.rmSync).toHaveBeenCalledWith(DESKTOP_FILE, { force: true });+ expect(state.writeFileSync).not.toHaveBeenCalled();+ });++ it("logs and does not throw when applying fails", () => {+ setPlatform("win32");+ state.setLoginItemThrows = true;++ expect(() => applyLaunchOnStartup()).not.toThrow();+ expect(state.log.error).toHaveBeenCalledWith(expect.stringContaining("Failed to apply launch-on-startup"));+ });++ it("setupAutoLaunch registers the reapply IPC, which applies the current setting", () => {+ setPlatform("win32");+ setupAutoLaunch();++ const handler = state.ipcOn.get("reapply-launch-on-startup");+ expect(handler).toBeDefined();++ state.launchOnStartup = true;+ handler?.();+ expect(state.setLoginItemSettings).toHaveBeenCalledWith({ openAtLogin: true });+ });+});diff --git a/apps/desktop/src/services/auto_launch.ts b/apps/desktop/src/services/auto_launch.tsnew file mode 100644index 0000000000..ba403c0dfb--- /dev/null+++ b/apps/desktop/src/services/auto_launch.ts@@ -0,0 +1,65 @@+import { getLog, options as optionService, utils as coreUtils } from "@triliumnext/core";+import electron from "electron";+import fs from "fs";+import os from "os";+import path from "path";++// Electron's app.setLoginItemSettings() covers macOS and Windows but is a no-op on+// Linux, where autostart is instead a freedesktop ".desktop" file dropped into the+// per-user autostart directory. We therefore branch on the platform.+const LINUX_AUTOSTART_DIR = path.join(os.homedir(), ".config", "autostart");+const LINUX_DESKTOP_FILE = path.join(LINUX_AUTOSTART_DIR, "trilium.desktop");++/**+ * Reconciles the OS autostart entry with the current `launchOnStartup` option.+ * Safe to call repeatedly (it's idempotent) and on every startup, so the OS state+ * is repaired if it drifts from the stored option. Failures are logged rather than+ * thrown so a permission error (e.g. a read-only autostart dir on Linux) can't take+ * down app startup.+ */+export function applyLaunchOnStartup() {+ try {+ const enabled = optionService.getOptionBool("launchOnStartup");++ if (process.platform === "linux") {+ applyLinuxAutostart(enabled);+ } else {+ // macOS + Windows: handled natively by Electron.+ electron.app.setLoginItemSettings({ openAtLogin: enabled });+ }+ } catch (e) {+ getLog().error(`Failed to apply launch-on-startup setting: ${coreUtils.safeExtractMessageAndStackFromError(e)}`);+ }+}++/**+ * Registers the IPC the renderer sends after the `launchOnStartup` option changes,+ * so the autostart entry updates immediately without an app restart.+ */+export function setupAutoLaunch() {+ electron.ipcMain.on("reapply-launch-on-startup", applyLaunchOnStartup);+}++function applyLinuxAutostart(enabled: boolean) {+ if (enabled) {+ fs.mkdirSync(LINUX_AUTOSTART_DIR, { recursive: true });+ fs.writeFileSync(LINUX_DESKTOP_FILE, buildLinuxDesktopEntry());+ } else {+ fs.rmSync(LINUX_DESKTOP_FILE, { force: true });+ }+}++function buildLinuxDesktopEntry() {+ // When packaged as an AppImage, APPIMAGE points at the bundle to relaunch;+ // otherwise fall back to the running executable.+ const exec = process.env.APPIMAGE ?? process.execPath;+ return [+ "[Desktop Entry]",+ "Type=Application",+ `Name=${electron.app.getName()}`,+ `Exec="${exec}"`,+ "Terminal=false",+ "X-GNOME-Autostart-enabled=true",+ ""+ ].join("\n");+}diff --git a/packages/commons/src/lib/electron_api_interface.ts b/packages/commons/src/lib/electron_api_interface.tsindex a03b83b12c..d23a0dd7fa 100644--- a/packages/commons/src/lib/electron_api_interface.ts+++ b/packages/commons/src/lib/electron_api_interface.ts@@ -348,6 +348,12 @@ export interface ElectronTrayApi {reloadTray(): void;}+/** Autostart / launch-on-login controls. */+export interface ElectronAutoLaunchApi {+ /** Re-applies the OS autostart entry after the `launchOnStartup` option changes. */+ reapply(): void;+}+/*** Printing and PDF export flow. Trilium drives Electron's printing pipeline* through a small state machine that the main process owns, with progress and@@ -492,6 +498,8 @@ export interface ElectronApi {spellcheck: ElectronSpellcheckApi;/** System tray menu controls. */tray: ElectronTrayApi;+ /** Autostart / launch-on-login controls. */+ autoLaunch: ElectronAutoLaunchApi;/** Printing and PDF export pipeline. */printing: ElectronPrintingApi;/** Read/write access to Chromium's back/forward navigation history. */diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 4bc905fb85..79b160acfa 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -170,6 +170,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActidisableTray: boolean;/** When closing the window on desktop, hide it to the system tray instead of quitting. Requires the tray icon to be enabled. */closeToTray: boolean;+ /** Whether the desktop app is launched automatically when the user logs into their computer. */+ launchOnStartup: boolean;editedNotesOpenInRibbon: boolean;codeBlockWordWrap: boolean;codeBlockTabWidth: number;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex 3cc8b04371..4de56564b6 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -92,6 +92,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["checkForUpdates","disableTray","closeToTray",+ "launchOnStartup","eraseUnusedAttachmentsAfterSeconds","eraseUnusedAttachmentsAfterTimeScale","disableTray",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 9802f9aa04..ae5a7e139d 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -166,6 +166,7 @@ const defaultOptions: DefaultOption[] = [{ name: "checkForUpdates", value: "true", isSynced: true },{ name: "disableTray", value: "false", isSynced: false },{ name: "closeToTray", value: "false", isSynced: false },+ { name: "launchOnStartup", value: "false", isSynced: false },{ name: "eraseUnusedAttachmentsAfterSeconds", value: "2592000", isSynced: true }, // default 30 days{ name: "eraseUnusedAttachmentsAfterTimeScale", value: "86400", isSynced: true }, // default 86400 seconds = Day{ name: "logRetentionDays", value: "90", isSynced: false }, // default 90 days