Skip to content

Build your personal knowledge base with Trilium Notes

fix(desktop): restore hidden windows before reveal

Amp76fe349fe6da
diff --git a/apps/desktop/src/main.spec.ts b/apps/desktop/src/main.spec.ts
index bea3dcaa43..917ea15240 100644
--- a/apps/desktop/src/main.spec.ts
+++ b/apps/desktop/src/main.spec.ts
@@ -75,6 +75,7 @@ const h = vi.hoisted(() => ({
createMainWindow: vi.fn((..._a: unknown[]) => Promise.resolve()),
createSetupWindow: vi.fn((..._a: unknown[]) => Promise.resolve()),
createExtraWindow: vi.fn((..._a: unknown[]) => {}),
+ showAndFocusWindow: vi.fn((..._a: unknown[]) => {}),
registerGlobalShortcuts: vi.fn((..._a: unknown[]) => Promise.resolve()),
setupAutoLaunch: vi.fn(),
applyLaunchOnStartup: vi.fn(),
@@ -222,6 +223,7 @@ vi.mock("./services/window", () => ({
createExtraWindow: (...a: unknown[]) => h.createExtraWindow(...a),
createMainWindow: (...a: unknown[]) => h.createMainWindow(...a),
createSetupWindow: (...a: unknown[]) => h.createSetupWindow(...a),
+ showAndFocusWindow: (...a: unknown[]) => h.showAndFocusWindow(...a),
registerGlobalShortcuts: (...a: unknown[]) => h.registerGlobalShortcuts(...a)
},
setupWindowing: vi.fn()
@@ -293,7 +295,11 @@ function resetState() {
h.createMainWindow.mockClear();
h.createSetupWindow.mockClear();
h.createExtraWindow.mockClear();
+ h.showAndFocusWindow.mockClear();
h.registerGlobalShortcuts.mockClear();
+ h.wasLaunchedHidden.mockReset();
+ h.wasLaunchedHidden.mockReturnValue(false);
+ h.disableTray = false;
h.unregisterAll.mockClear();
h.startServer = () => Promise.resolve({});
}
@@ -551,38 +557,43 @@ describe("app event handlers", () => {
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 };
+ it("reveals the last-focused window", async () => {
+ const targetWindow = {
+ isMinimized: () => true,
+ restore: vi.fn(),
+ show: vi.fn(),
+ focus: vi.fn()
+ };
+ h.lastFocusedWindow = targetWindow;
await bootAndReady();
const handler = h.appOn.get("second-instance");
handler?.({}, []);
- expect(restore).toHaveBeenCalled();
- expect(show).toHaveBeenCalled();
- expect(focus).toHaveBeenCalled();
+ expect(h.showAndFocusWindow).toHaveBeenCalledWith(targetWindow);
});
- 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 };
+ it("falls back to the main window when a hidden start has no focus history", async () => {
+ const targetWindow = {
+ isMinimized: () => false,
+ restore: vi.fn(),
+ show: vi.fn(),
+ focus: vi.fn()
+ };
+ h.lastFocusedWindow = null;
+ h.mainWindow = targetWindow;
await bootAndReady();
const handler = h.appOn.get("second-instance");
handler?.({}, []);
- expect(restore).not.toHaveBeenCalled();
- expect(show).toHaveBeenCalled();
- expect(focus).toHaveBeenCalled();
+ expect(h.showAndFocusWindow).toHaveBeenCalledWith(targetWindow);
});
- it("does nothing when there is no last-focused window", async () => {
+ it("does nothing when there is no existing window", async () => {
h.lastFocusedWindow = null;
+ h.mainWindow = null;
await bootAndReady();
const handler = h.appOn.get("second-instance");
expect(() => handler?.({}, [])).not.toThrow();
expect(h.createExtraWindow).not.toHaveBeenCalled();
+ expect(h.showAndFocusWindow).not.toHaveBeenCalled();
});
});
@@ -613,23 +624,44 @@ describe("app event handlers", () => {
// 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 };
+ const lastFocusedWindow = {
+ isMinimized: () => false,
+ restore: vi.fn(),
+ show: vi.fn(),
+ focus: vi.fn()
+ };
+ h.lastFocusedWindow = lastFocusedWindow;
await activate?.();
expect(h.createMainWindow).toHaveBeenCalledTimes(2);
- expect(show).toHaveBeenCalled();
- expect(focus).toHaveBeenCalled();
+ expect(h.showAndFocusWindow).toHaveBeenCalledWith(lastFocusedWindow);
// Hidden-on-autostart window was never focused → fall back to the main window.
- const mainShow = vi.fn();
- const mainFocus = vi.fn();
h.lastFocusedWindow = null;
- h.mainWindow = { isMinimized: () => false, restore: vi.fn(), show: mainShow, focus: mainFocus };
+ const mainWindow = {
+ isMinimized: () => false,
+ restore: vi.fn(),
+ show: vi.fn(),
+ focus: vi.fn()
+ };
+ h.mainWindow = mainWindow;
await activate?.();
- expect(mainShow).toHaveBeenCalled();
- expect(mainFocus).toHaveBeenCalled();
+ expect(h.showAndFocusWindow).toHaveBeenLastCalledWith(mainWindow);
+ });
+
+ it("starts hidden only when the tray can reveal the window", async () => {
+ h.wasLaunchedHidden.mockReturnValue(true);
+ await bootAndReady();
+ await h.appOn.get("ready")?.();
+ expect(h.createMainWindow).toHaveBeenCalledWith(true);
+ });
+
+ it("starts visible when the tray is disabled", async () => {
+ h.wasLaunchedHidden.mockReturnValue(true);
+ h.disableTray = true;
+ await bootAndReady();
+ await h.appOn.get("ready")?.();
+ expect(h.createMainWindow).toHaveBeenCalledWith(false);
});
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.ts
index c55601cced..cfda4b1f84 100644
--- a/apps/desktop/src/main.ts
+++ b/apps/desktop/src/main.ts
@@ -149,15 +149,15 @@ export async function main() {
});
app.on("second-instance", (event, commandLine) => {
- const lastFocusedWindow = windowService.getLastFocusedWindow();
if (commandLine.includes("--new-window")) {
windowService.createExtraWindow("");
- } else if (lastFocusedWindow) {
- if (lastFocusedWindow.isMinimized()) {
- lastFocusedWindow.restore();
+ } else {
+ // A window that started hidden has no focus history, so use the main window.
+ const targetWindow = windowService.getLastFocusedWindow()
+ ?? windowService.getMainWindow();
+ if (targetWindow) {
+ windowService.showAndFocusWindow(targetWindow);
}
- lastFocusedWindow.show();
- lastFocusedWindow.focus();
}
});
@@ -379,8 +379,9 @@ async function onReady() {
// window that was never focused, so fall back to the main window
// to reveal it on a dock-icon click.
const win = windowService.getLastFocusedWindow() ?? windowService.getMainWindow();
- win?.show();
- win?.focus();
+ if (win) {
+ windowService.showAndFocusWindow(win);
+ }
}
});
}
diff --git a/apps/desktop/src/services/tray.spec.ts b/apps/desktop/src/services/tray.spec.ts
index d0130cadba..ea4fbcee90 100644
--- a/apps/desktop/src/services/tray.spec.ts
+++ b/apps/desktop/src/services/tray.spec.ts
@@ -32,7 +32,8 @@ const state = vi.hoisted(() => ({
lastFocusedWindow: null as unknown,
mainWindow: null as unknown,
allWindows: [] as unknown[],
- browserWindowAll: [] as unknown[]
+ browserWindowAll: [] as unknown[],
+ showAndFocusWindow: vi.fn()
}));
// `getTodayNote` returns a fake note used by the "today" menu item.
@@ -103,7 +104,8 @@ vi.mock("./window.js", () => ({
default: {
getLastFocusedWindow: () => state.lastFocusedWindow,
getMainWindow: () => state.mainWindow,
- getAllWindows: () => state.allWindows
+ getAllWindows: () => state.allWindows,
+ showAndFocusWindow: (...args: unknown[]) => state.showAndFocusWindow(...args)
}
}));
@@ -272,8 +274,7 @@ describe("tray", () => {
// Now simulate it being hidden, then click shows + focuses.
win.listeners.get("hide")?.();
click?.();
- expect(win.show).toHaveBeenCalled();
- expect(win.focus).toHaveBeenCalled();
+ expect(state.showAndFocusWindow).toHaveBeenCalledWith(win);
});
it("click handler summons a window started hidden (no focus history)", () => {
@@ -291,8 +292,7 @@ describe("tray", () => {
state.ipcHandlers.get("reload-tray")?.();
state.trayInstance?.clickHandlers.get("click")?.();
- expect(win.show).toHaveBeenCalled();
- expect(win.focus).toHaveBeenCalled();
+ expect(state.showAndFocusWindow).toHaveBeenCalledWith(win);
expect(win.hide).not.toHaveBeenCalled();
});
});
@@ -419,8 +419,7 @@ describe("tray", () => {
| Electron.MenuItemConstructorOptions
| undefined;
cbB?.click?.(undefined as never, undefined as never, undefined as never);
- expect(winB.show).toHaveBeenCalled();
- expect(winB.focus).toHaveBeenCalled();
+ expect(state.showAndFocusWindow).toHaveBeenCalledWith(winB);
});
it("prunes closed windows and registers listeners for new ones", () => {
diff --git a/apps/desktop/src/services/tray.ts b/apps/desktop/src/services/tray.ts
index 5013afee54..d153efdbe3 100644
--- a/apps/desktop/src/services/tray.ts
+++ b/apps/desktop/src/services/tray.ts
@@ -113,8 +113,7 @@ function updateTrayMenu() {
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();
+ windowService.showAndFocusWindow(win);
}
}
@@ -290,8 +289,7 @@ function changeVisibility() {
if (windowVisibilityMap[targetWindow.id]) {
targetWindow.hide();
} else {
- targetWindow.show();
- targetWindow.focus();
+ windowService.showAndFocusWindow(targetWindow);
}
}
diff --git a/apps/desktop/src/services/window.spec.ts b/apps/desktop/src/services/window.spec.ts
index d45193a517..f4ad58bb6b 100644
--- a/apps/desktop/src/services/window.spec.ts
+++ b/apps/desktop/src/services/window.spec.ts
@@ -389,14 +389,26 @@ describe("window service", () => {
expect(opts.frame).toBeUndefined();
});
- it("defers window-state restoration for a hidden start until the window is shown", async () => {
+ it("restores hidden state before reveal and does not manage a window that stays hidden", async () => {
+ await windowService.createMainWindow(true);
+ const closedWindow = state.windows[state.windows.length - 1];
+
+ closedWindow.fire("closed");
+ expect(state.windowStateManage).not.toHaveBeenCalled();
+
await windowService.createMainWindow(true);
const hiddenWindow = state.windows[state.windows.length - 1];
expect((hiddenWindow.opts as Record<string, unknown>).show).toBe(false);
expect(state.windowStateManage).not.toHaveBeenCalled();
- hiddenWindow.fire("show");
+ windowService.showAndFocusWindow(hiddenWindow as never);
+ expect(state.windowStateManage).toHaveBeenCalledOnce();
expect(state.windowStateManage).toHaveBeenCalledWith(hiddenWindow);
+ expect(state.windowStateManage.mock.invocationCallOrder[0])
+ .toBeLessThan(hiddenWindow.show.mock.invocationCallOrder[0]);
+
+ hiddenWindow.fire("show");
+ expect(state.windowStateManage).toHaveBeenCalledOnce();
await windowService.createMainWindow();
const visibleWindow = state.windows[state.windows.length - 1];
@@ -404,6 +416,27 @@ describe("window service", () => {
expect(state.windowStateManage).toHaveBeenLastCalledWith(visibleWindow);
});
+ it("uses the show event as a one-time fallback", async () => {
+ await windowService.createMainWindow(true);
+ const hiddenWindow = state.windows[state.windows.length - 1];
+
+ hiddenWindow.fire("show");
+ hiddenWindow.fire("show");
+
+ expect(state.windowStateManage).toHaveBeenCalledOnce();
+ expect(state.windowStateManage).toHaveBeenCalledWith(hiddenWindow);
+ });
+
+ it("manages state once when restoration emits show synchronously", async () => {
+ await windowService.createMainWindow(true);
+ const hiddenWindow = state.windows[state.windows.length - 1];
+ state.windowStateManage.mockImplementationOnce(() => hiddenWindow.fire("show"));
+
+ windowService.showAndFocusWindow(hiddenWindow as never);
+
+ expect(state.windowStateManage).toHaveBeenCalledOnce();
+ });
+
it("marks startup metrics for creation, first paint, and load finish", async () => {
await windowService.createMainWindow();
const win = state.windows[state.windows.length - 1];
@@ -717,6 +750,18 @@ describe("window service", () => {
it("restores, shows and focuses a minimized window", async () => {
await windowService.createMainWindow();
const win = state.windows[state.windows.length - 1];
+ win.isMinimized.mockReturnValue(true);
+
+ windowService.showAndFocusWindow(win as never);
+
+ expect(win.restore).toHaveBeenCalled();
+ expect(win.show).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ expect(win.restore.mock.invocationCallOrder[0])
+ .toBeLessThan(win.show.mock.invocationCallOrder[0]);
+ expect(win.show.mock.invocationCallOrder[0])
+ .toBeLessThan(win.focus.mock.invocationCallOrder[0]);
+
win.fire("focus");
expect(windowService.getLastFocusedWindow()).toBe(win);
expect(windowService.getAllWindows()).toContain(win);
@@ -821,6 +866,7 @@ describe("window service", () => {
const win = state.windows[state.windows.length - 1];
fireOn("show-window", makeEvent());
expect(win.show).toHaveBeenCalled();
+ expect(win.focus).not.toHaveBeenCalled();
state.fromWebContentsResult = "null";
fireOn("show-window", makeEvent());
@@ -841,6 +887,7 @@ describe("window service", () => {
win.isVisible.mockReturnValue(false);
fireOn("toggle-all-windows", makeEvent());
expect(win.show).toHaveBeenCalled();
+ expect(win.focus).not.toHaveBeenCalled();
});
it("get-available-spellchecker-languages returns the list", () => {
diff --git a/apps/desktop/src/services/window.ts b/apps/desktop/src/services/window.ts
index 126b8368fe..752b57cf73 100644
--- a/apps/desktop/src/services/window.ts
+++ b/apps/desktop/src/services/window.ts
@@ -38,6 +38,7 @@ let setupWindow: BrowserWindow | null;
let allWindows: BrowserWindow[] = []; // Used to store all windows, sorted by the order of focus.
const loadedSpellcheckSessions = new WeakSet<Session>();
const exportRevealSessions = new WeakSet<Session>();
+const deferredWindowStateManagers = new WeakMap<BrowserWindow, () => void>();
// 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).
@@ -156,7 +157,14 @@ async function createMainWindow(startHidden = false) {
if (startHidden) {
const hiddenWindow = mainWindow;
- hiddenWindow.once("show", () => mainWindowState.manage(hiddenWindow));
+ const manageWindowState = () => {
+ if (deferredWindowStateManagers.delete(hiddenWindow)) {
+ mainWindowState.manage(hiddenWindow);
+ }
+ };
+ deferredWindowStateManagers.set(hiddenWindow, manageWindowState);
+ // This event is a fallback for a reveal that does not use showWindow().
+ hiddenWindow.once("show", manageWindowState);
} else {
mainWindowState.manage(mainWindow);
}
@@ -446,6 +454,13 @@ async function registerGlobalShortcuts() {
}
}
+function showWindow(window: BrowserWindow) {
+ // electron-window-state can reveal a hidden maximized window while it restores state.
+ // Restore immediately before an intentional reveal so the window starts hidden.
+ deferredWindowStateManagers.get(window)?.();
+ window.show();
+}
+
function showAndFocusWindow(window: BrowserWindow) {
/* v8 ignore next -- defensive guard; every caller passes a non-null window narrowed beforehand */
if (!window) return;
@@ -454,7 +469,7 @@ function showAndFocusWindow(window: BrowserWindow) {
window.restore();
}
- window.show();
+ showWindow(window);
window.focus();
}
@@ -524,7 +539,10 @@ export function setupWindowing() {
electron.ipcMain.handle("read-clipboard-text", () => electron.clipboard.readText());
electron.ipcMain.on("show-window", (event) => {
- electron.BrowserWindow.fromWebContents(event.sender)?.show();
+ const window = electron.BrowserWindow.fromWebContents(event.sender);
+ if (window) {
+ showWindow(window);
+ }
});
electron.ipcMain.handle("clear-cache", async (event) => {
@@ -534,9 +552,12 @@ export function setupWindowing() {
electron.ipcMain.on("toggle-all-windows", () => {
const windows = electron.BrowserWindow.getAllWindows();
const isVisible = windows.every((w) => w.isVisible());
- const action = isVisible ? "hide" : "show";
for (const win of windows) {
- win[action]();
+ if (isVisible) {
+ win.hide();
+ } else {
+ showWindow(win);
+ }
}
});
@@ -671,6 +692,7 @@ export default {
createSetupWindow,
closeSetupWindow,
registerGlobalShortcuts,
+ showAndFocusWindow,
getMainWindow,
getLastFocusedWindow,
getAllWindows