Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): relaunch restore stops stealing focus (PRD-7799) (#3237)

Andrew Mikofalvy896d38001a12
diff --git a/.changeset/relaunch-restore-keeps-your-foreground-app.md b/.changeset/relaunch-restore-keeps-your-foreground-app.md
new file mode 100644
index 000000000..288495a84
--- /dev/null
+++ b/.changeset/relaunch-restore-keeps-your-foreground-app.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Relaunching with several projects open no longer drags you back to OpenKnowledge over and over. Restoring a multi-window session used to reveal each window with a focusing show, and on macOS that pulls the whole app forward, so a restore of seven projects (which materializes over several seconds while each project's server starts) would background whatever you had switched to once per window, then take focus one final time at the end. Now the app comes forward once, as it always did, and from then on stays out of your way: if you switch to something else while the rest of the session is still loading, the remaining windows open quietly behind you and the app does not pull you back. The window you were last working in is still the one waiting for you when you return.
diff --git a/packages/desktop/src/main/boot-restore-decision.ts b/packages/desktop/src/main/boot-restore-decision.ts
index b4e04108d..08bf12e4d 100644
--- a/packages/desktop/src/main/boot-restore-decision.ts
+++ b/packages/desktop/src/main/boot-restore-decision.ts
@@ -12,7 +12,7 @@ export interface BootRestoreInput {
* opens NO default window — restoring the previous project / Navigator
* alongside the URL-driven window both clutters the launch and races it for
* focus (the reported "two windows, one is the splash"). Ranked below the
- * update-relaunch restore (which must never be dropped) and above
+ * clean-exit window-restore snapshot (which must never be dropped) and above
* `lastOpenedProject` / Navigator.
*/
urlLaunch: boolean;
@@ -24,13 +24,15 @@ export type BootRestoreDecision =
| { clearSnapshot: boolean; action: 'navigator' }
| { clearSnapshot: boolean; action: 'none' };
-// Pure boot-restore decision. A non-null `pendingRestore` means an update
-// relaunch happened, so the snapshot is always consumed (`clearSnapshot`) even
-// when Option suppresses the actual restore. A non-null-but-empty/all-missing
-// snapshot opens the Navigator and deliberately does NOT fall through to
+// Pure boot-restore decision. A non-null `pendingRestore` means the previous
+// run exited cleanly and snapshotted its window set — every clean exit writes
+// one (normal quit, "Relaunch now" update, and install-on-quit alike), not just
+// update relaunches. It is always consumed (`clearSnapshot`) even when Option
+// suppresses the actual restore. A non-null-but-empty/all-missing snapshot
+// opens the Navigator and deliberately does NOT fall through to
// `lastOpenedProject` — the relaunch is honored as "nothing was open" rather
-// than reopening a stale project. A null snapshot is the normal cold-boot path
-// that restores `lastOpenedProject`. When a single-file deep-link claims the
+// than reopening a stale project. A null snapshot is the cold-boot path that
+// restores `lastOpenedProject`. When a single-file deep-link claims the
// launch (`urlLaunch`), open no default window — the URL flush owns it.
export function bootRestoreDecision(input: BootRestoreInput): BootRestoreDecision {
const { pendingRestore, lastOpenedProject, optionHeld, pathExists, urlLaunch } = input;
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 7c99fe1e4..5db2570d5 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -334,6 +334,7 @@ import {
RESTORE_REVEAL_TIMEOUT_MS,
type RevealableWindow,
raiseMostRecentlyFocusedAfterRestore,
+ shouldRevealInactiveNow,
} from './restore-focus.ts';
import { handleRevealExternal } from './reveal-external.ts';
import { createServerExitRecorder, type ServerExitRecorder } from './server-exit-record.ts';
@@ -1029,6 +1030,67 @@ function ingestRendererStartupMarks(marks: RendererMarks): void {
if (firstWindowShown && startupWaterfall.canEmit) emitStartupWaterfall();
}
+/**
+ * True while a boot-restore is opening its window set, cleared once the
+ * post-restore raise has run. Feeds {@link shouldRevealInactiveNow} alongside
+ * {@link appHasEverBeenActive} and {@link appIsActive} — all three terms are
+ * load-bearing and that function documents why.
+ *
+ * Its own job is to scope the quiet reveal to a restore and defer the whole
+ * foreground question to a single decision at the end: the raise in the restore
+ * branch.
+ */
+let restoreRevealInactive = false;
+
+/**
+ * Whether OpenKnowledge is the foreground application right now, tracked from
+ * the app-level activation events. Read at the end of a restore to decide
+ * whether the raise may take foreground.
+ */
+let appIsActive = false;
+
+/**
+ * Whether the app has been frontmost at least once this run. The
+ * anti-self-suppression term of {@link shouldRevealInactiveNow}; removing it
+ * is a worse bug than the one it guards against, for the reasons documented
+ * there.
+ */
+let appHasEverBeenActive = false;
+
+/**
+ * True when a deep link opened a window while a restore was still in flight.
+ *
+ * Suppresses the post-restore raise entirely. Without it the raise, which waits
+ * for every reveal to settle, would land after the deep-link window and put the
+ * previously-focused restore target on top of the thing the user just asked
+ * for. Ordering only, not a reveal concern: the deep-link window is already
+ * visible and frontmost by then.
+ */
+let deepLinkClaimedWindowDuringRestore = false;
+
+/**
+ * Stop suppressing activation for subsequent window reveals. Called once the
+ * restore's own foreground decision has been made.
+ */
+function endRestoreQuietReveal(): void {
+ restoreRevealInactive = false;
+}
+
+/**
+ * Hand the restore's foreground claim to a deep link that arrived mid-restore.
+ *
+ * Explicit user intent outranks restore politeness, in both directions: the
+ * requested window reveals with a focusing `show()` rather than quietly, AND
+ * the restore's trailing raise stands down instead of burying it. Every seam
+ * that opens or surfaces a window on behalf of an `openknowledge://` URL calls
+ * this — project opens, single-file opens, and shares that resolve to the
+ * Navigator, which reaches the same show gate as any other window.
+ */
+function yieldRestoreToDeepLink(): void {
+ endRestoreQuietReveal();
+ deepLinkClaimedWindowDuringRestore = true;
+}
+
const showGate: ShowGateRegistry = createShowGateRegistry({
log: {
warn: (obj, msg) => {
@@ -1039,6 +1101,12 @@ const showGate: ShowGateRegistry = createShowGateRegistry({
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
// Startup waterfall: first shown window stamps `windowShown` + emits.
onShown: () => onFirstWindowShown(),
+ shouldRevealInactive: () =>
+ shouldRevealInactiveNow({
+ restoreInProgress: restoreRevealInactive,
+ appHasEverBeenActive,
+ appIsActive,
+ }),
});
/**
@@ -6316,6 +6384,28 @@ function bootPrimaryInstance(): void {
}
});
+ // Foreground-state mirror for the post-restore raise. Registered here, before
+ // `whenReady`, so the launch activation itself is observed — reading this
+ // later must never mistake "not yet initialized" for "user walked away".
+ //
+ // Both events are `@platform darwin`, so off darwin these flags stay false
+ // for the whole run. Every window then reveals with `show()`
+ // (`shouldRevealInactiveNow` needs `appHasEverBeenActive`), which is the
+ // pre-existing posture. The raise is NOT identical there: `shouldActivate`
+ // reads false unconditionally, so it always takes the `activate: false`
+ // branch and skips `win.show?.()` on the target. That is inert rather than
+ // equivalent — the target is already visible by then, and `moveTop()` +
+ // `focus()` reach the same end state — and `activateApp` is a no-op off macOS
+ // regardless. Two independent guards; don't drop either on the assumption the
+ // other covers it.
+ app.on('did-become-active', () => {
+ appIsActive = true;
+ appHasEverBeenActive = true;
+ });
+ app.on('did-resign-active', () => {
+ appIsActive = false;
+ });
+
// URL-scheme handler — register BEFORE `whenReady` so macOS cold-start
// `open-url` Apple Events are caught even if they fire before the ready hook.
// Listener registration is synchronous; the actual routing defers URLs into a
@@ -6337,9 +6427,18 @@ function bootPrimaryInstance(): void {
},
focusWindowForProject: (projectPath) => {
if (!wm) return null;
+ // The warm seam: the project already has a window, so this surfaces it
+ // rather than opening one. It still needs the yield — `bringToFront`
+ // brings the window forward, but without this the restore's trailing
+ // raise would put the restore target straight back on top of it.
+ yieldRestoreToDeepLink();
return wm.focusWindowForProject(projectPath) as unknown as object | null;
},
openProject: async (projectPath, opts) => {
+ // A deep link asked for this window, so it must come forward even if a
+ // restore is still revealing its own windows quietly — and the restore's
+ // trailing raise must not then bury it.
+ yieldRestoreToDeepLink();
// Use the Navigator-fallback path: on failure (bad path, git-init error,
// stale lock) the user sees a dialog and is returned to the Navigator
// rather than a silent "link doesn't work." Success path returns the
@@ -6370,7 +6469,15 @@ function bootPrimaryInstance(): void {
// `openknowledge://open?file=<abs>` — the desktop side of `ok <file>`.
// `openEphemeralFile` re-derives the plan and routes project-vs-
// ephemeral itself, so the url-scheme layer just hands off the path.
- openEphemeralFile: (filePath) => openEphemeralFile(filePath),
+ openEphemeralFile: (filePath) => {
+ // Same rule as `openProject` above, and it must live HERE rather than
+ // inside `openEphemeralFile`: the boot restore calls that function for
+ // its own file-kind entries, and yielding there would unmute the rest of
+ // the restore. The deep-link boundary also covers the branch where the
+ // file collapses onto a project.
+ yieldRestoreToDeepLink();
+ return openEphemeralFile(filePath);
+ },
sendDeepLink: (win, payload) => {
const w = win as BrowserWindowLike;
sendToRenderer(w.webContents, 'ok:deep-link', payload);
@@ -6462,6 +6569,11 @@ function bootPrimaryInstance(): void {
checkShareTargetExists: (projectPath, kind, path) =>
checkTargetExistsImpl(projectPath, kind, path),
routeShareToNavigator: (payload) => {
+ // Third deep-link seam. A share that resolves to the Navigator (target
+ // missing, or a non-OK branch match) opens a window through the same show
+ // gate as any other, so mid-restore it would otherwise reveal quietly and
+ // sit behind the user's foreground app — for a link they just clicked.
+ yieldRestoreToDeepLink();
// `openNavigator(payload)` handles both cold-create (cold path:
// `createNavigatorWindow` registers `once('dom-ready', ...)` BEFORE
// `loadFile`/`loadURL`) and warm-focus (warm path: `isLoading()`
@@ -6698,14 +6810,14 @@ function bootPrimaryInstance(): void {
applyHarvestedAuthSock(process.env, await authSockHarvest, shellEnvLogger);
// Every project open spawns a NEW editor window. Boot restore order:
- // 1. An update relaunch left a `pendingWindowRestore` snapshot — open
- // EVERY project that was open before the relaunch, not just the
- // last one. The snapshot is consumed unconditionally (cleared to
- // null + persisted) before any window opens, so a crash mid-restore
- // can't loop it. A non-null-but-empty/all-missing snapshot opens
- // the Navigator and deliberately does NOT fall through to
- // `lastOpenedProject` — the relaunch is honored as "nothing was
- // open" rather than reopening a stale project.
+ // 1. A clean exit left a `pendingWindowRestore` snapshot — open EVERY
+ // project that was open before, not just the last one. The snapshot
+ // is consumed unconditionally (cleared to null + persisted) before
+ // any window opens, so a crash mid-restore can't loop it. A
+ // non-null-but-empty/all-missing snapshot opens the Navigator and
+ // deliberately does NOT fall through to `lastOpenedProject` — the
+ // relaunch is honored as "nothing was open" rather than reopening a
+ // stale project.
// 2. Otherwise restore `lastOpenedProject` into one editor window.
// 3. Holding Option (`--navigator`) or having nothing to restore
// opens the Navigator instead.
@@ -6800,13 +6912,19 @@ function bootPrimaryInstance(): void {
}
});
- // Parallel opens — each window's OS-level `show()` is deferred behind
- // its own dual-signal show gate, which releases in nondeterministic
- // order. `show()` steals key-window focus on macOS, so the raise waits
- // for EVERY restored window to reveal before raising the last (most
- // recently focused) entry — otherwise a sibling that shows later steals
- // focus back. Waiting for all reveals also keeps `bringToFront`'s
- // `show()` from bypassing the target's own gate.
+ // Reveal every restored window WITHOUT foregrounding the app, so the N
+ // reveals spread across the restore can't repeatedly yank a user who
+ // switched away while waiting. Cleared once the raise below has made
+ // the single foreground decision for the whole restore.
+ restoreRevealInactive = true;
+
+ // Parallel opens — each window's OS-level reveal is deferred behind its
+ // own dual-signal show gate, which releases in nondeterministic order,
+ // and every reveal lands above its predecessors in the window stack. So
+ // the raise waits for EVERY restored window to reveal before raising
+ // the last (most recently focused) entry — otherwise a sibling that
+ // reveals later would bury it. Waiting for all reveals also keeps
+ // `bringToFront`'s own reveal from bypassing the target's gate.
const opens = orderedKeys.map((key) => {
const action = actionByKey.get(key);
if (action === undefined) return Promise.resolve();
@@ -6814,26 +6932,56 @@ function bootPrimaryInstance(): void {
? openProjectOrFallbackToNavigator(action.projectPath, 'recents')
: openEphemeralFile(action.filePath);
});
- void Promise.allSettled(opens).then(() =>
- raiseMostRecentlyFocusedAfterRestore({
- windowKeys: orderedKeys,
- // `getWindowFor` / `focusWindowForProject` canonicalize their input,
- // so a loose-file key (canonical file path) resolves its ephemeral
- // window just as a project key resolves its project window.
- getWindow: (key) => {
- const ctx = wm?.getWindowFor(key);
- return ctx ? (ctx.window as unknown as RevealableWindow) : undefined;
- },
- raise: (key) => {
- wm?.focusWindowForProject(key);
- },
- deps: {
- setTimeout: (cb, ms) => setTimeout(cb, ms),
- clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
- timeoutMs: RESTORE_REVEAL_TIMEOUT_MS,
- },
- }),
- );
+ void Promise.allSettled(opens)
+ .then(() => {
+ // A deep link that arrived mid-restore already put the window the
+ // user asked for in front. Raising the restore target now would
+ // bury it, so the restore yields its ordering claim entirely.
+ if (deepLinkClaimedWindowDuringRestore) return undefined;
+ return raiseMostRecentlyFocusedAfterRestore({
+ windowKeys: orderedKeys,
+ // `getWindowFor` / `focusWindowForProject` canonicalize their input,
+ // so a loose-file key (canonical file path) resolves its ephemeral
+ // window just as a project key resolves its project window.
+ getWindow: (key) => {
+ const ctx = wm?.getWindowFor(key);
+ return ctx ? (ctx.window as unknown as RevealableWindow) : undefined;
+ },
+ raise: (key, opts) => {
+ wm?.focusWindowForProject(key, opts);
+ },
+ // The one foreground decision for the whole restore, taken after
+ // every window has revealed: come forward only if OpenKnowledge
+ // is still the app the user is in. If they moved on during the
+ // restore, the target window is ordered correctly but the
+ // foreground app is left alone.
+ shouldActivate: () => appIsActive,
+ deps: {
+ setTimeout: (cb, ms) => setTimeout(cb, ms),
+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
+ timeoutMs: RESTORE_REVEAL_TIMEOUT_MS,
+ },
+ });
+ })
+ .catch((err: unknown) => {
+ // Every window is already revealed by this point, so a throw here
+ // costs ordering, not visibility. Logged rather than swallowed so a
+ // future regression in the raise is diagnosable instead of showing
+ // up only as "the wrong window was in front".
+ getLogger('startup').warn(
+ {
+ event: 'restore-raise-failed',
+ // Which window should have ended up in front, and how many were
+ // in the restore — enough to reconstruct the case from a log
+ // alone, without a reproduction.
+ targetKey: orderedKeys[orderedKeys.length - 1],
+ windowCount: orderedKeys.length,
+ err,
+ },
+ 'post-restore raise threw — windows are up but foreground order may be wrong',
+ );
+ })
+ .finally(endRestoreQuietReveal);
} else if (decision.action === 'lastOpened') {
void openProjectOrFallbackToNavigator(decision.project, 'recents');
} else if (decision.action === 'navigator') {
diff --git a/packages/desktop/src/main/restore-focus.test.ts b/packages/desktop/src/main/restore-focus.test.ts
index 885c3db4e..5175d18e5 100644
--- a/packages/desktop/src/main/restore-focus.test.ts
+++ b/packages/desktop/src/main/restore-focus.test.ts
@@ -3,6 +3,7 @@ import {
type RestoreFocusDeps,
type RevealableWindow,
raiseMostRecentlyFocusedAfterRestore,
+ shouldRevealInactiveNow,
whenWindowRevealed,
} from './restore-focus.ts';
@@ -64,6 +65,43 @@ function makeWindow(opts: { visible?: boolean; destroyed?: boolean } = {}): Fake
const flush = () => Promise.resolve();
+describe('shouldRevealInactiveNow', () => {
+ // Full truth table. All three terms are load-bearing, and only one row is
+ // true — pinning every combination is what makes a dropped term fail here
+ // rather than in a user's window stack.
+ test.each([
+ { restoreInProgress: false, appHasEverBeenActive: false, appIsActive: false, expected: false },
+ { restoreInProgress: false, appHasEverBeenActive: false, appIsActive: true, expected: false },
+ { restoreInProgress: false, appHasEverBeenActive: true, appIsActive: false, expected: false },
+ { restoreInProgress: false, appHasEverBeenActive: true, appIsActive: true, expected: false },
+ { restoreInProgress: true, appHasEverBeenActive: false, appIsActive: false, expected: false },
+ { restoreInProgress: true, appHasEverBeenActive: false, appIsActive: true, expected: false },
+ { restoreInProgress: true, appHasEverBeenActive: true, appIsActive: false, expected: true },
+ { restoreInProgress: true, appHasEverBeenActive: true, appIsActive: true, expected: false },
+ ])('restore=$restoreInProgress everActive=$appHasEverBeenActive active=$appIsActive → $expected', ({
+ expected,
+ ...state
+ }) => {
+ expect(shouldRevealInactiveNow(state)).toBe(expected);
+ });
+
+ test('a restore that has never been frontmost reveals normally, not quietly', () => {
+ // The anti-self-suppression row, called out because it is the one that
+ // reads redundant. `showInactive()` never activates the app, so if the
+ // first restored window also revealed quietly the app would never become
+ // active, never observe a departure, and never come forward — a user who
+ // clicked Relaunch and waited would get their session back behind whatever
+ // macOS promoted when OpenKnowledge quit.
+ expect(
+ shouldRevealInactiveNow({
+ restoreInProgress: true,
+ appHasEverBeenActive: false,
+ appIsActive: false,
+ }),
+ ).toBe(false);
+ });
+});
+
describe('whenWindowRevealed', () => {
test('resolves immediately when already visible', async () => {
const { deps, pending } = makeTimers();
@@ -223,3 +261,73 @@ describe('raiseMostRecentlyFocusedAfterRestore', () => {
expect(raised).toEqual(['/notes/todo.md']);
});
});
+
+describe('raiseMostRecentlyFocusedAfterRestore — foreground decision', () => {
+ /** Run a two-window restore to completion, returning the raise's opts. */
+ async function runRestore(
+ shouldActivate?: () => boolean,
+ ): Promise<Array<{ key: string; activate: boolean }>> {
+ const { deps } = makeTimers();
+ const a = makeWindow();
+ const b = makeWindow();
+ const wins: Record<string, FakeWindow> = { '/a': a, '/b': b };
+ const calls: Array<{ key: string; activate: boolean }> = [];
+
+ const p = raiseMostRecentlyFocusedAfterRestore({
+ windowKeys: ['/a', '/b'],
+ getWindow: (key) => wins[key],
+ raise: (key, opts) => calls.push({ key, activate: opts.activate }),
+ shouldActivate,
+ deps,
+ });
+
+ await flush();
+ a.emitShow();
+ b.emitShow();
+ await p;
+ return calls;
+ }
+
+ test('activates when the predicate says the user is still here', async () => {
+ expect(await runRestore(() => true)).toEqual([{ key: '/b', activate: true }]);
+ });
+
+ test('declines to activate when the user has moved to another app', async () => {
+ // The reported bug: a restore that finishes after the user gave up waiting
+ // must not drag them back out of whatever they switched to.
+ expect(await runRestore(() => false)).toEqual([{ key: '/b', activate: false }]);
+ });
+
+ test('omitted predicate activates, preserving the previous behavior', async () => {
+ expect(await runRestore()).toEqual([{ key: '/b', activate: true }]);
+ });
+
+ test('reads the predicate after every reveal settles, not when the restore starts', async () => {
+ // This ordering is the whole point: a restore can run for many seconds, and
+ // the user leaving DURING it is exactly the case being fixed. Sampling the
+ // answer up front would activate anyway and reproduce the bug.
+ const { deps } = makeTimers();
+ const a = makeWindow();
+ const b = makeWindow();
+ const wins: Record<string, FakeWindow> = { '/a': a, '/b': b };
+ const calls: Array<{ key: string; activate: boolean }> = [];
+ let userPresent = true;
+
+ const p = raiseMostRecentlyFocusedAfterRestore({
+ windowKeys: ['/a', '/b'],
+ getWindow: (key) => wins[key],
+ raise: (key, opts) => calls.push({ key, activate: opts.activate }),
+ shouldActivate: () => userPresent,
+ deps,
+ });
+
+ await flush();
+ a.emitShow();
+ // The user walks away while the last window is still coming up.
+ userPresent = false;
+ b.emitShow();
+ await p;
+
+ expect(calls).toEqual([{ key: '/b', activate: false }]);
+ });
+});
diff --git a/packages/desktop/src/main/restore-focus.ts b/packages/desktop/src/main/restore-focus.ts
index 77ebf15ce..32add867d 100644
--- a/packages/desktop/src/main/restore-focus.ts
+++ b/packages/desktop/src/main/restore-focus.ts
@@ -1,32 +1,74 @@
/**
- * Post-restore focus coordination for the update-relaunch window snapshot.
+ * Focus posture for the clean-exit window-restore snapshot — how the restored
+ * windows reveal, and whether the raise that follows takes foreground.
*
- * A multi-window update-relaunch restores every project that was open, opening
- * each in its own window. The OS-level `BrowserWindow.show()` for each window is
- * deferred behind its own dual-signal show gate (see `show-gate.ts`), which
- * releases in nondeterministic order. `show()` steals key-window focus on macOS,
- * so whichever window's gate releases LAST would end up frontmost — not the
- * window the user was working in.
+ * A multi-window restore reopens every project that was open, each in its own
+ * window. Each window's OS-level reveal is deferred behind its own dual-signal
+ * show gate (see `show-gate.ts`), and those gates release in nondeterministic
+ * order — every reveal lands above its predecessors in the window stack, so
+ * whichever one releases LAST would end up frontmost. That is rarely the window
+ * the user was working in.
*
* The restore snapshot is ordered least → most recently focused (see
* `sortByFocusSequence`), so its last entry is the window to land in. Raising
- * that window right after the open promises settle is not enough: those promises
- * resolve after `loadURL`, well before the deferred `show()` calls, so a sibling
- * window that shows later steals focus back. This module waits until EVERY
- * restored window has revealed, then raises the target so its `show()`/`focus()`
- * is the last one to win. Waiting for all reveals also guarantees the target is
- * already shown before the raise, so `bringToFront` never bypasses its own gate.
+ * that window as soon as the open promises settle is not enough: those promises
+ * resolve after `loadURL`, well before the deferred reveals, so a sibling
+ * revealing later would bury the target again. This module waits until EVERY
+ * restored window has revealed, then raises the target so it is the last one to
+ * win. Waiting for all reveals also guarantees the target is already shown
+ * before the raise, so `bringToFront` never bypasses its own gate.
*
* Electron-free by construction: `RevealableWindow` is a structural subset and
* timers are injected, so tests exercise the ordering without a real
* BrowserWindow.
*/
+/**
+ * Whether a window revealing at this instant should appear without pulling the
+ * app to the foreground. Canonical statement of the three-term rule; the
+ * show gate's `shouldRevealInactive` predicate is this function.
+ *
+ * `restoreInProgress` scopes the whole rule to a restore. A restore of N
+ * projects reveals N windows over several seconds (each waits on its own server
+ * to bind), and on macOS a plain `show()` activates the app — so unscoped, each
+ * reveal drags a user who switched away while waiting back out of whatever they
+ * moved to.
+ *
+ * `appHasEverBeenActive` is what keeps the rule from suppressing itself. macOS
+ * reports activation only as a consequence of something taking focus, so a
+ * launch whose windows all reveal via `showInactive()` never becomes active:
+ * `appIsActive` would sit false for the whole run, unable to tell "the user
+ * walked away" from "we were never in front to begin with". Requiring a prior
+ * activation lets the FIRST restored window reveal normally, which costs the one
+ * activation a user who asked for a relaunch expects anyway and makes departure
+ * observable for every window after it. Dropping this term reads like a
+ * simplification and is a worse bug — the app would never come forward at all,
+ * so a user who waited gets their session back silently behind another app.
+ *
+ * `appIsActive` then silences every remaining reveal the moment the user does
+ * move elsewhere.
+ */
+export function shouldRevealInactiveNow(state: {
+ /** A boot restore is opening its window set and has not yet made its raise. */
+ restoreInProgress: boolean;
+ /** The app has been frontmost at least once this run. */
+ appHasEverBeenActive: boolean;
+ /** The app is frontmost right now. */
+ appIsActive: boolean;
+}): boolean {
+ return state.restoreInProgress && state.appHasEverBeenActive && !state.appIsActive;
+}
+
/** Structural subset of BrowserWindow used to observe reveal state. */
export interface RevealableWindow {
isDestroyed?(): boolean;
isVisible?(): boolean;
- /** Fires when the window is shown (Electron emits `show` on `show()`). */
+ /**
+ * Fires when the window is shown. Electron emits `show` for BOTH `show()` and
+ * `showInactive()` (macOS raises it off the window's occlusion-state change),
+ * so a quietly-revealed window still settles this wait rather than stalling it
+ * until the safety timeout.
+ */
once(event: 'show', listener: () => void): void;
}
@@ -79,6 +121,13 @@ export function whenWindowRevealed(win: RevealableWindow, deps: RestoreFocusDeps
* were destroyed mid-restore are skipped; if the target itself is gone, nothing
* is raised.
*
+ * Whether that raise also pulls the app to the foreground is decided by
+ * `shouldActivate`, called AFTER every reveal has settled. Evaluating it that
+ * late is the point: a restore can take many seconds, and the user may well
+ * have given up waiting and switched to another app in the meantime. Asking at
+ * raise time captures the whole restore window, so the app claims foreground
+ * only if the user actually stayed.
+ *
* @param windowKeys Restore keys — a project path OR a loose-file's canonical
* file path — ordered least → most recently focused. `getWindow` / `raise`
* resolve either kind (the WM lookups canonicalize their input).
@@ -86,10 +135,16 @@ export function whenWindowRevealed(win: RevealableWindow, deps: RestoreFocusDeps
export async function raiseMostRecentlyFocusedAfterRestore(input: {
windowKeys: readonly string[];
getWindow: (key: string) => RevealableWindow | undefined;
- raise: (key: string) => void;
+ raise: (key: string, opts: { activate: boolean }) => void;
+ /**
+ * `true` → the raise may foreground the app; `false` → order the window
+ * within the app but leave the user's current app alone. Omitted → always
+ * activate, preserving the behavior from before this was configurable.
+ */
+ shouldActivate?: () => boolean;
deps: RestoreFocusDeps;
}): Promise<void> {
- const { windowKeys, getWindow, raise, deps } = input;
+ const { windowKeys, getWindow, raise, shouldActivate, deps } = input;
const target = windowKeys[windowKeys.length - 1];
if (target === undefined) return;
@@ -103,5 +158,5 @@ export async function raiseMostRecentlyFocusedAfterRestore(input: {
const targetWin = getWindow(target);
if (!targetWin || targetWin.isDestroyed?.() === true) return;
- raise(target);
+ raise(target, { activate: shouldActivate === undefined || shouldActivate() });
}
diff --git a/packages/desktop/src/main/show-gate.ts b/packages/desktop/src/main/show-gate.ts
index 110403d04..77d5713e5 100644
--- a/packages/desktop/src/main/show-gate.ts
+++ b/packages/desktop/src/main/show-gate.ts
@@ -59,6 +59,23 @@ interface ShowGateRegistryDeps {
* never the window. Optional; omitted in tests that don't assert show timing.
*/
onShown?: (kind: WindowKind) => void;
+ /**
+ * Consulted at the instant a window reveals: `true` reveals via
+ * `showInactive()` instead of `show()`.
+ *
+ * On macOS `show()` activates the whole application, so a session restore
+ * that reveals N windows over several seconds drags the user back out of
+ * whatever they switched to, once per window. Revealing inactive makes the
+ * windows appear without touching the foreground app; a single deliberate
+ * activation afterwards (the post-restore raise) decides whether
+ * OpenKnowledge comes forward at all.
+ *
+ * A predicate rather than a per-`register` flag because reveal happens
+ * asynchronously, long after registration, and the answer depends on
+ * conditions at reveal time. Omitted → always `show()`, preserving the
+ * pre-existing behavior for every caller that doesn't opt in.
+ */
+ shouldRevealInactive?: () => boolean;
}
export interface ShowGateRegistry {
@@ -108,6 +125,31 @@ export function createShowGateRegistry(deps: ShowGateRegistryDeps): ShowGateRegi
state.timerHandle = undefined;
}
+ /**
+ * Reveal a window, honoring the inactive-reveal predicate. A throwing
+ * predicate must not strand the window hidden — "no window at all" is the
+ * one outcome strictly worse than revealing with the wrong focus posture —
+ * so a throw degrades to the plain `show()` that predates this option.
+ * `showInactive` is optional on the structural type, so a mock (or any
+ * future window-like) that lacks it also degrades to `show()`.
+ */
+ function revealWindow(window: BrowserWindowLike, kind: WindowKind): void {
+ let inactive = false;
+ try {
+ inactive = deps.shouldRevealInactive?.() === true;
+ } catch (err) {
+ deps.log?.warn(
+ { event: 'show-gate-reveal-predicate-failed', windowKind: kind, err },
+ 'shouldRevealInactive threw — falling back to a focusing show()',
+ );
+ }
+ if (inactive && window.showInactive !== undefined) {
+ window.showInactive();
+ return;
+ }
+ window.show?.();
+ }
+
function safeShow(window: BrowserWindowLike, state: PerWindowGateState): void {
// Mirror of `reduced-transparency-handler.ts`'s per-call try/catch. The
// isDestroyed/isVisible guards above handle the common shutdown race;
@@ -117,7 +159,7 @@ export function createShowGateRegistry(deps: ShowGateRegistryDeps): ShowGateRegi
// so a throw doesn't leave the gate in a state that lies about visibility.
// states.delete() runs in both branches so the Map entry never leaks.
try {
- window.show?.();
+ revealWindow(window, state.kind);
state.shown = true;
// Startup waterfall: the window is now visible. Fire AFTER `state.shown`
// flips so a throw from `show()` doesn't emit a false windowShown mark.
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 8134ddbc9..d05dd8931 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -131,6 +131,16 @@ export interface BrowserWindowLike {
* mocks omit it; `?.show()` callers no-op silently when missing.
*/
show?(): void;
+ /**
+ * Display the OS-level window WITHOUT taking focus. On macOS a plain
+ * `show()` activates the whole app — it pulls OpenKnowledge in front of
+ * whatever the user switched to — whereas `showInactive()` reveals the
+ * window and leaves the foreground app alone. That difference is what keeps
+ * a multi-window session restore from yanking the user back once per
+ * window. Optional in the structural type because some test mocks omit it;
+ * callers fall back to `show()`.
+ */
+ showInactive?(): void;
restore?(): void;
isMinimized?(): boolean;
/**
@@ -925,10 +935,20 @@ export class WindowManager {
* canonicalization `createProjectWindow` applies — so a deep-link URL
* carrying a realpath matches a window opened via a symlinked path.
*/
- focusWindowForProject(projectPath: string): BrowserWindowLike | null {
+ focusWindowForProject(
+ projectPath: string,
+ opts?: { activate?: boolean },
+ ): BrowserWindowLike | null {
const ctx = this.windowsByPath.get(this.canonicalizeKey(projectPath));
if (!ctx) return null;
- this.bringToFront(ctx.window);
+ // Same destroyed-window gate every other `bringToFront` caller applies. A
+ // map entry outlives its native window by the gap between `closed` firing
+ // and the utility `exit` that clears the entry, and calling into a
+ // destroyed BrowserWindow throws. Reporting it as "no window" sends deep
+ // links down their cold path, which is the right answer for one that is
+ // gone.
+ if (ctx.window.isDestroyed?.() === true) return null;
+ this.bringToFront(ctx.window, opts);
return ctx.window;
}
@@ -944,14 +964,32 @@ export class WindowManager {
* already has it. Single source of truth for all focus-an-existing-window
* paths (deep-link warm path + the createProjectWindow / ephemeral dedup
* branches).
- */
- private bringToFront(win: BrowserWindowLike): void {
+ *
+ * `opts.activate: false` performs the same raise WITHOUT pulling the app to
+ * the foreground — for callers that want a window ordered correctly but must
+ * not take the user out of whatever app they are currently in (the
+ * post-restore raise, when the user walked away mid-restore). Measured on
+ * macOS: `show()` activates the app, while `showInactive()`, `moveTop()`,
+ * and `focus()` do not. So the non-activating path swaps the reveal and drops
+ * the app-level steal, but keeps `moveTop()` + `focus()` — the window still
+ * becomes the one OpenKnowledge surfaces when the user returns on their own.
+ */
+ private bringToFront(win: BrowserWindowLike, opts?: { activate?: boolean }): void {
+ const activate = opts?.activate ?? true;
if (win.isMinimized?.()) win.restore?.();
- win.show?.();
+ if (activate) {
+ win.show?.();
+ } else if (win.isVisible?.() !== true) {
+ // Reveal a still-hidden window without foregrounding the app. `show()` is
+ // the fallback only when `showInactive` is absent (test mocks) — a
+ // window the caller asked for must never stay invisible.
+ if (win.showInactive !== undefined) win.showInactive();
+ else win.show?.();
+ }
const alreadyFrontmost = win.isFocused?.() === true;
win.moveTop?.();
win.focus();
- if (!alreadyFrontmost) this.deps.activateApp?.();
+ if (activate && !alreadyFrontmost) this.deps.activateApp?.();
}
/**
diff --git a/packages/desktop/tests/main/show-gate.test.ts b/packages/desktop/tests/main/show-gate.test.ts
index a92efb876..fa81ccb78 100644
--- a/packages/desktop/tests/main/show-gate.test.ts
+++ b/packages/desktop/tests/main/show-gate.test.ts
@@ -26,6 +26,7 @@ interface CapturedTimer {
interface MockWindow extends BrowserWindowLike {
show: ReturnType<typeof vi.fn>;
+ showInactive: ReturnType<typeof vi.fn>;
fireReadyToShow: () => void;
markDestroyed: () => void;
markVisible: () => void;
@@ -38,8 +39,12 @@ function makeWindow(): MockWindow {
const show = vi.fn(() => {
visible = true;
});
+ const showInactive = vi.fn(() => {
+ visible = true;
+ });
return {
show,
+ showInactive,
isDestroyed: vi.fn(() => destroyed),
isVisible: vi.fn(() => visible),
on: vi.fn(() => {}) as BrowserWindowLike['on'],
@@ -74,7 +79,7 @@ interface TestEnv {
registry: ShowGateRegistry;
}
-function buildEnv(opts?: { timeoutMs?: number }): TestEnv {
+function buildEnv(opts?: { timeoutMs?: number; shouldRevealInactive?: () => boolean }): TestEnv {
const timers: CapturedTimer[] = [];
const cleared: unknown[] = [];
const warns: Array<{ obj: object; msg: string }> = [];
@@ -93,6 +98,7 @@ function buildEnv(opts?: { timeoutMs?: number }): TestEnv {
cleared.push(handle);
},
timeoutMs: opts?.timeoutMs,
+ shouldRevealInactive: opts?.shouldRevealInactive,
});
return { timers, cleared, warns, registry };
}
@@ -486,3 +492,101 @@ describe('createShowGateRegistry — show() throws past the destroyed-window gua
expect(timeout).toBeDefined();
});
});
+
+describe('createShowGateRegistry — inactive reveal', () => {
+ /** Drive a registered window through both gate signals so it reveals. */
+ function reveal(registry: ShowGateRegistry, win: MockWindow): void {
+ registry.register(win, { kind: 'editor' });
+ win.fireReadyToShow();
+ registry.fireThemeApplied(win);
+ }
+
+ test('predicate false → reveals with a focusing show()', () => {
+ const env = buildEnv({ shouldRevealInactive: () => false });
+ const win = makeWindow();
+ reveal(env.registry, win);
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(win.showInactive).not.toHaveBeenCalled();
+ });
+
+ test('predicate omitted → reveals with a focusing show()', () => {
+ const env = buildEnv();
+ const win = makeWindow();
+ reveal(env.registry, win);
+ expect(win.show).toHaveBeenCalledTimes(1);
+ expect(win.showInactive).not.toHaveBeenCalled();
+ });
+
+ test('predicate true → reveals via showInactive(), never show()', () => {
+ const env = buildEnv({ shouldRevealInactive: () => true });
+ const win = makeWindow();
+ reveal(env.registry, win);
+ expect(win.showInactive).toHaveBeenCalledTimes(1);
+ expect(win.show).not.toHaveBeenCalled();
+ expect(win.isVisible?.()).toBe(true);
+ });
+
+ test('predicate is read at reveal time, not at registration time', () => {
+ // Registration happens before `loadURL`; the reveal lands seconds later. A
+ // restore that finishes between the two must not leave a later window
+ // revealing under the stale answer.
+ let inactive = true;
+ const env = buildEnv({ shouldRevealInactive: () => inactive });
+ const early = makeWindow();
+ const late = makeWindow();
+ env.registry.register(early, { kind: 'editor' });
+ env.registry.register(late, { kind: 'editor' });
+
+ early.fireReadyToShow();
+ env.registry.fireThemeApplied(early);
+ expect(early.showInactive).toHaveBeenCalledTimes(1);
+
+ inactive = false;
+ late.fireReadyToShow();
+ env.registry.fireThemeApplied(late);
+ expect(late.show).toHaveBeenCalledTimes(1);
+ expect(late.showInactive).not.toHaveBeenCalled();
+ });
+
+ test('the timeout fallback honors the predicate too', () => {
+ // A window whose second signal never arrives is force-shown by the safety
+ // timeout. That path must not become a foreground steal either.
+ const env = buildEnv({ shouldRevealInactive: () => true });
+ const win = makeWindow();
+ env.registry.register(win, { kind: 'editor' });
+ win.fireReadyToShow();
+ env.timers[0]?.cb();
+ expect(win.showInactive).toHaveBeenCalledTimes(1);
+ expect(win.show).not.toHaveBeenCalled();
+ });
+
+ test('a throwing predicate degrades to show() and warns rather than stranding the window', () => {
+ // No window at all is strictly worse than a window with the wrong focus
+ // posture, so the predicate must never be able to block a reveal.
+ const env = buildEnv({
+ shouldRevealInactive: () => {
+ throw new Error('predicate exploded');
+ },
+ });
+ const win = makeWindow();
+ env.registry.register(win, { kind: 'navigator' });
+ win.fireReadyToShow();
+ env.registry.fireThemeApplied(win);
+ expect(win.show).toHaveBeenCalledTimes(1);
+ const warn = env.warns.find(
+ (w) => (w.obj as { event?: unknown }).event === 'show-gate-reveal-predicate-failed',
+ );
+ // Carries the same windowKind its sibling warns do — a navigator, editor,
+ // or terminal revealing with the wrong posture are different user impacts.
+ expect(warn?.obj).toMatchObject({ windowKind: 'navigator' });
+ });
+
+ test('a window without showInactive still reveals when the predicate is true', () => {
+ const env = buildEnv({ shouldRevealInactive: () => true });
+ const win = makeWindow();
+ // Model a window-like that predates the inactive-reveal capability.
+ (win as { showInactive?: unknown }).showInactive = undefined;
+ reveal(env.registry, win);
+ expect(win.show).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index 13ddf955a..90caef2a2 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -70,6 +70,11 @@ function makeWindow(opts?: { minimized?: boolean; focused?: boolean }): BrowserW
show: vi.fn(() => {
visible = true;
}),
+ // Reveals like `show` but never foregrounds the app — the distinction the
+ // non-activating raise depends on.
+ showInactive: vi.fn(() => {
+ visible = true;
+ }),
restore: vi.fn(() => {
minimized = false;
}),
@@ -2087,6 +2092,103 @@ describe('WindowManager.focusWindowForProject (M4 URL-scheme warm-start)', () =>
expect(env.activateApp).toHaveBeenCalled();
});
+ test('reports a destroyed window as no window rather than calling into it', async () => {
+ // A map entry outlives its native window between `closed` and the utility
+ // `exit` that clears it. Surfacing that entry would throw; reporting "no
+ // window" instead sends a deep link down its cold path, which is correct
+ // for a window that is gone.
+ const w = makeWindow();
+ env.deps.createWindow = () => {
+ env.createWindowOpts.push({ additionalArguments: [], title: '' });
+ env.windows.push(w);
+ return w;
+ };
+ const wm = new WindowManager(env.deps);
+ const p = wm.createProjectWindow({ projectPath: '/tmp/gone-proj' });
+ env.utilities[0]?.fire({ type: 'ready', port: 51223, apiOrigin: 'http://localhost:51223' });
+ await p;
+ w.markDestroyed();
+ w.focus.mockClear();
+ w.show.mockClear();
+
+ expect(wm.focusWindowForProject('/tmp/gone-proj')).toBeNull();
+ expect(w.focus).not.toHaveBeenCalled();
+ expect(w.show).not.toHaveBeenCalled();
+ expect(env.activateApp).not.toHaveBeenCalled();
+ });
+
+ test('activate:false raises without foregrounding the app', async () => {
+ // The post-restore raise when the user walked away mid-restore: order the
+ // window correctly inside OpenKnowledge, but leave whatever app they are
+ // actually using in front. `show()` would activate the app on macOS, so the
+ // reveal must go through `showInactive()` and the app-level steal must not
+ // fire at all.
+ const wm = new WindowManager(env.deps);
+ const p = wm.createProjectWindow({ projectPath: '/tmp/quiet-proj' });
+ env.utilities[0]?.fire({ type: 'ready', port: 51220, apiOrigin: 'http://localhost:51220' });
+ const ctx = await p;
+ const win = ctx.window as unknown as ReturnType<typeof makeWindow>;
+ win.show.mockClear();
+ win.showInactive.mockClear();
+
+ wm.focusWindowForProject('/tmp/quiet-proj', { activate: false });
+
+ expect(env.activateApp).not.toHaveBeenCalled();
+ expect(win.show).not.toHaveBeenCalled();
+ // Asserted, not just described: the reveal is the whole point of the
+ // branch, so a regression that dropped it must fail here.
+ expect(win.showInactive).toHaveBeenCalledTimes(1);
+ // Still ordered + made key within the app, so returning to OpenKnowledge
+ // lands on this window rather than an arbitrary sibling.
+ expect(win.moveTop).toHaveBeenCalled();
+ expect(win.focus).toHaveBeenCalled();
+ });
+
+ test('activate:false leaves an already-visible window alone rather than re-revealing', async () => {
+ // Every restored window has already revealed by the time the raise runs, so
+ // the common case must not call a reveal primitive at all.
+ const w = makeWindow();
+ env.deps.createWindow = () => {
+ env.createWindowOpts.push({ additionalArguments: [], title: '' });
+ env.windows.push(w);
+ return w;
+ };
+ const wm = new WindowManager(env.deps);
+ const p = wm.createProjectWindow({ projectPath: '/tmp/visible-proj' });
+ env.utilities[0]?.fire({ type: 'ready', port: 51221, apiOrigin: 'http://localhost:51221' });
+ await p;
+ w.show();
+ w.show.mockClear();
+ w.showInactive.mockClear();
+
+ wm.focusWindowForProject('/tmp/visible-proj', { activate: false });
+
+ expect(w.show).not.toHaveBeenCalled();
+ expect(w.showInactive).not.toHaveBeenCalled();
+ expect(env.activateApp).not.toHaveBeenCalled();
+ });
+
+ test('activate:false reveals a still-hidden window via showInactive', async () => {
+ const w = makeWindow();
+ env.deps.createWindow = () => {
+ env.createWindowOpts.push({ additionalArguments: [], title: '' });
+ env.windows.push(w);
+ return w;
+ };
+ const wm = new WindowManager(env.deps);
+ const p = wm.createProjectWindow({ projectPath: '/tmp/hidden-proj' });
+ env.utilities[0]?.fire({ type: 'ready', port: 51222, apiOrigin: 'http://localhost:51222' });
+ await p;
+ w.show.mockClear();
+ w.showInactive.mockClear();
+
+ wm.focusWindowForProject('/tmp/hidden-proj', { activate: false });
+
+ expect(w.showInactive).toHaveBeenCalled();
+ expect(w.show).not.toHaveBeenCalled();
+ expect(env.activateApp).not.toHaveBeenCalled();
+ });
+
test('skips the app-level focus steal when the window is already frontmost', async () => {
// A window that reports isFocused() === true models the OK Desktop
// built-in terminal focusing a doc in its own already-active window —