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 close-to-tray option
Elian Doran4e5f329b9be3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 7be3977082..ce7ec9fa41 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1522,7 +1522,9 @@"tray": {"title": "System Tray","enable_tray": "Tray icon",- "enable_tray_description": "Changes apply immediately, though on some platforms hiding the tray icon may require restarting Trilium."+ "enable_tray_description": "Changes apply immediately, though on some platforms hiding the tray icon may require restarting Trilium.",+ "close_to_tray": "Close to tray",+ "close_to_tray_description": "When you close the window, keep Trilium running in the system tray instead of quitting. Requires the tray icon to be enabled."},"text_editor": {"title": "Editor",diff --git a/apps/client/src/widgets/type_widgets/options/other.tsx b/apps/client/src/widgets/type_widgets/options/other.tsxindex 044657d6de..042ba4160d 100644--- a/apps/client/src/widgets/type_widgets/options/other.tsx+++ b/apps/client/src/widgets/type_widgets/options/other.tsx@@ -109,6 +109,7 @@ function SearchEngineSettings() {function TrayOptionsSettings() {const [ disableTray, setDisableTray ] = useTriliumOptionBool("disableTray");+ const [ closeToTray, setCloseToTray ] = useTriliumOptionBool("closeToTray");return (<OptionsSection title={t("tray.title")}>@@ -123,6 +124,15 @@ function TrayOptionsSettings() {utils.reloadTray();}}/>+ <OptionsRowWithToggle+ name="close-to-tray"+ label={t("tray.close_to_tray")}+ description={t("tray.close_to_tray_description")}+ currentValue={closeToTray}+ // Close-to-tray with no tray icon would hide the app with no way back.+ disabled={disableTray}+ onChange={setCloseToTray}+ /></OptionsSection>);}diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.tsindex ce35aca079..0e79e54812 100644--- a/apps/desktop/src/main.spec.ts+++ b/apps/desktop/src/main.spec.ts@@ -433,10 +433,16 @@ describe("app event handlers", () => {await activate?.();expect(h.createMainWindow).toHaveBeenCalledTimes(2);- // Existing windows → do not create another.+ // Existing windows → do not create another; instead reveal the+ // (possibly close-to-tray-hidden) last focused window.+ const show = vi.fn();+ const focus = vi.fn();h.allWindows = [{}];+ h.lastFocusedWindow = { isMinimized: () => false, restore: vi.fn(), show, focus };await activate?.();expect(h.createMainWindow).toHaveBeenCalledTimes(2);+ expect(show).toHaveBeenCalled();+ expect(focus).toHaveBeenCalled();});it("does not register activate on non-darwin even when DB is initialized", async () => {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 7999fa7f2b..1b257f00e4 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -267,6 +267,12 @@ async function onReady() {app.on("activate", async () => {if (BrowserWindow.getAllWindows().length === 0) {await windowService.createMainWindow();+ } else {+ // Close-to-tray may have hidden the window rather than destroying+ // it, so a dock-icon click must reveal the existing window.+ const win = windowService.getLastFocusedWindow();+ win?.show();+ win?.focus();}});}diff --git a/apps/desktop/src/services/tray.spec.ts b/apps/desktop/src/services/tray.spec.tsindex c37c5ffbe7..2a47a789a9 100644--- a/apps/desktop/src/services/tray.spec.ts+++ b/apps/desktop/src/services/tray.spec.ts@@ -14,6 +14,7 @@ const state = vi.hoisted(() => ({shouldUseDarkColors: false,// captured handlersappHandlers: new Map<string, Handler>(),+ appQuit: vi.fn(),ipcHandlers: new Map<string, Handler>(),nativeThemeHandlers: new Map<string, Handler>(),i18nHandlers: new Map<string, Handler>(),@@ -87,7 +88,8 @@ vi.mock("electron", () => ({on: (channel: string, fn: Handler) => state.ipcHandlers.set(channel, fn)},app: {- on: (event: string, fn: Handler) => state.appHandlers.set(event, fn)+ on: (event: string, fn: Handler) => state.appHandlers.set(event, fn),+ quit: (...args: unknown[]) => state.appQuit(...args)},BrowserWindow: {getAllWindows: () => state.browserWindowAll@@ -454,13 +456,17 @@ describe("tray", () => {await todayClick?.();expect(win.webContents.send).toHaveBeenCalledWith("openInSameTab", "today");- // "close" closes all BrowserWindow windows.+ // "close" (labelled "Quit Trilium") genuinely quits the app. It calls+ // app.quit() rather than closing windows so the close-to-tray+ // interceptor (which would otherwise hide them) is bypassed via+ // before-quit.findItem("tray.close")?.click?.(undefined as never,undefined as never,undefined as never);- expect(win.close).toHaveBeenCalled();+ expect(state.appQuit).toHaveBeenCalled();+ expect(win.close).not.toHaveBeenCalled();});it("open-new-window and new-note no-op when no focused window", () => {diff --git a/apps/desktop/src/services/tray.ts b/apps/desktop/src/services/tray.tsindex ca43fa6628..85df159ab7 100644--- a/apps/desktop/src/services/tray.ts+++ b/apps/desktop/src/services/tray.ts@@ -263,12 +263,11 @@ function updateTrayMenu() {label: t("tray.close"),type: "normal",icon: getIconPath("close"),- click: () => {- const windows = electron.BrowserWindow.getAllWindows();- windows.forEach(window => {- window.close();- });- }+ // Genuinely quit. `app.quit()` triggers `before-quit`, which clears the+ // close-to-tray interception so the windows close for real instead of+ // hiding back to the tray. Works on macOS too (where closing the last+ // window does not quit by itself).+ click: () => electron.app.quit()}]);diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.tsindex 0077d3d264..d26dcc5208 100644--- a/apps/desktop/src/services/window.spec.ts+++ b/apps/desktop/src/services/window.spec.ts@@ -17,6 +17,8 @@ const state = vi.hoisted(() => ({ipcOn: new Map<string, Handler>(),ipcHandle: new Map<string, Handler>(),ipcEmit: vi.fn(),+ // captured electron.app event handlers (e.g. before-quit)+ appOn: new Map<string, Handler>(),// captured events.subscribe callbacks keyed by event nameeventSubs: new Map<string, Handler>(),// captured BrowserWindow instances@@ -155,7 +157,9 @@ const fakeNativeImage = {const fakeApp = {setUserTasks: vi.fn(),relaunch: vi.fn(),- exit: vi.fn()+ exit: vi.fn(),+ quit: vi.fn(),+ on: vi.fn((event: string, cb: Handler) => state.appOn.set(event, cb))};const electronSurface = {@@ -268,6 +272,7 @@ beforeEach(() => {state.keyboardActions = [];state.windows = [];state.fromWebContentsResult = undefined;+ state.appOn.clear();state.registerResults = [];state.nativeImageEmpty = false;state.nativeImageThrow = false;@@ -894,4 +899,65 @@ describe("window service", () => {expect(state.log.error).toHaveBeenCalledWith(expect.stringContaining("Failed to swap"));});});++ describe("close-to-tray", () => {+ it("hides the main window instead of closing when closeToTray is enabled", async () => {+ state.optionBools = { closeToTray: true };+ await windowService.createMainWindow();+ const win = state.windows[state.windows.length - 1];++ const event = { preventDefault: vi.fn() };+ win.fire("close", event);++ expect(event.preventDefault).toHaveBeenCalled();+ expect(win.hide).toHaveBeenCalled();+ // The window must survive so it can be shown again from the tray.+ expect(windowService.getMainWindow()).toBe(win);+ });++ it("closes normally when closeToTray is disabled", async () => {+ state.optionBools = {};+ await windowService.createMainWindow();+ const win = state.windows[state.windows.length - 1];++ const event = { preventDefault: vi.fn() };+ win.fire("close", event);++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(win.hide).not.toHaveBeenCalled();+ });++ it("closes normally when the tray is disabled, even if closeToTray is on", async () => {+ state.optionBools = { closeToTray: true, disableTray: true };+ await windowService.createMainWindow();+ const win = state.windows[state.windows.length - 1];++ const event = { preventDefault: vi.fn() };+ win.fire("close", event);++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(win.hide).not.toHaveBeenCalled();+ });++ // NOTE: keep this test LAST. `before-quit` flips the module-level+ // `isQuitting` flag to `true` and nothing resets it, so any close-to-tray+ // assertion ordered after this one would see the window close for real.+ it("lets the main window close for real once a genuine quit is underway", async () => {+ setupWindowing();+ state.optionBools = { closeToTray: true };+ await windowService.createMainWindow();+ const win = state.windows[state.windows.length - 1];++ // Simulate a real quit (Cmd+Q, tray "Quit", app menu, OS shutdown).+ const beforeQuit = state.appOn.get("before-quit");+ if (!beforeQuit) throw new Error("before-quit handler not registered");+ beforeQuit();++ const event = { preventDefault: vi.fn() };+ win.fire("close", event);++ expect(event.preventDefault).not.toHaveBeenCalled();+ expect(win.hide).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.tsindex 016750b076..c0b026d7e8 100644--- a/apps/desktop/src/services/window.ts+++ b/apps/desktop/src/services/window.ts@@ -36,6 +36,11 @@ let setupWindow: BrowserWindow | null;let allWindows: BrowserWindow[] = []; // Used to store all windows, sorted by the order of focus.const loadedSpellcheckSessions = new WeakSet<Session>();+// Set to `true` once the app is genuinely quitting (via `before-quit`, which fires+// for every real quit path: Cmd+Q, the tray "Quit" item, the app menu, OS shutdown).+// The close-to-tray interceptor checks this so a true quit isn't swallowed into a hide.+let isQuitting = false;+function trackWindowFocus(win: BrowserWindow) {// We need to get the last focused window from allWindows. If the last window is closed, we return the previous window.// Therefore, we need to push the window into the allWindows array every time it gets focused.@@ -138,6 +143,15 @@ async function createMainWindow() {mainWindow.setMenuBarVisibility(false);mainWindow.loadURL(TRILIUM_APP_BASE_URL);+ // Close-to-tray: when enabled, closing the main window hides it to the tray+ // instead of quitting. Only intercepts a genuine window close (not an app+ // quit, which sets `isQuitting` first). Extra windows are unaffected.+ mainWindow.on("close", (event) => {+ if (!isQuitting && !optionService.getOptionBool("disableTray") && optionService.getOptionBool("closeToTray")) {+ event.preventDefault();+ mainWindow?.hide();+ }+ });mainWindow.on("closed", () => (mainWindow = null));configureWebContents(mainWindow.webContents, spellcheckEnabled);@@ -376,6 +390,12 @@ export function setupWindowing() {// the renderer/main security boundary.setupWebContentsSecurity();+ // Mark a genuine quit so the close-to-tray interceptor lets windows close for+ // real. Fires for every quit path (Cmd+Q, tray "Quit", app menu, OS shutdown).+ electron.app.on("before-quit", () => {+ isQuitting = true;+ });+electron.ipcMain.on("create-extra-window", (_event, arg) => {createExtraWindow(arg.extraWindowHash);});diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 1440d7f6b1..4bc905fb85 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -168,6 +168,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActidownloadImagesAutomatically: boolean;checkForUpdates: boolean;disableTray: 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;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 1cfbe706b8..3cc8b04371 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -91,6 +91,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["highlightsList","checkForUpdates","disableTray",+ "closeToTray","eraseUnusedAttachmentsAfterSeconds","eraseUnusedAttachmentsAfterTimeScale","disableTray",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 486667a68a..9802f9aa04 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -165,6 +165,7 @@ const defaultOptions: DefaultOption[] = [{ name: "highlightsList", value: '["underline","color","bgColor"]', isSynced: true },{ name: "checkForUpdates", value: "true", isSynced: true },{ name: "disableTray", value: "false", isSynced: false },+ { name: "closeToTray", 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