Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(desktop): restore the active window on update relaunch (#2683)
Andrew Mikofalvy1ac39d6cc2eb
diff --git a/.changeset/restore-active-window-on-update.md b/.changeset/restore-active-window-on-update.mdnew file mode 100644index 000000000..1f6668616--- /dev/null+++ b/.changeset/restore-active-window-on-update.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Installing an update no longer lands you in the wrong window. When you relaunch to install the latest version with several project windows open, OpenKnowledge reopens all of them and now brings the window you were last working in back to the front, instead of whichever window happened to finish loading last.diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 1cf6cae9a..73ab8255f 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -292,6 +292,11 @@ import { removeGitFolder } from './remove-git-folder.ts';import { attachRendererConsoleCapture } from './renderer-console-capture.ts';import { resolveDetachedSpawnArgs } from './resolve-detached-spawn-args.ts';import { resolveShareTarget as resolveShareTargetMain } from './resolve-share-target.ts';+import {+ RESTORE_REVEAL_TIMEOUT_MS,+ type RevealableWindow,+ raiseMostRecentlyFocusedAfterRestore,+} from './restore-focus.ts';import { handleRevealExternal } from './reveal-external.ts';import { startFirstRunHandshake } from './share-handoff.ts';import { handleShellOpenExternal } from './shell-allowlist.ts';@@ -5430,29 +5435,35 @@ function bootPrimaryInstance(): void {if (decision.action === 'restore') {// Parallel opens — the snapshot is ordered least → most recently- // focused (see `pendingWindowRestore`), but each window shows only- // when its own theme gate releases, so completion order (and thus- // which window ends up focused) is nondeterministic. Raise the- // snapshot's LAST entry once every open settles AND its window is- // actually visible: `bringToFront` calls `show()`, so raising a- // still-gated window would bypass the dual-signal show gate and- // resurface the un-themed first paint.+ // focused (see `pendingWindowRestore`), but 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 must wait for EVERY restored window to reveal+ // before raising the snapshot's last entry — otherwise a sibling window+ // that shows later steals focus back (the reported "active window isn't+ // the one I was working in" after a relaunch). Waiting for all reveals+ // also keeps `bringToFront`'s `show()` from bypassing the target's own+ // gate: the target is already shown by the time we raise it.const opens = decision.projects.map((projectPath) =>openProjectOrFallbackToNavigator(projectPath, 'recents'),);- const lastActiveProject = decision.projects[decision.projects.length - 1];- void Promise.allSettled(opens).then(() => {- if (lastActiveProject === undefined) return;- const ctx = wm?.getWindowFor(lastActiveProject);- // Absent context = the open failed and fell back to the Navigator;- // nothing to raise.- if (!ctx || ctx.window.isDestroyed?.() === true) return;- const raise = () => {- if (ctx.window.isDestroyed?.() !== true) wm?.focusWindowForProject(lastActiveProject);- };- if (ctx.window.isVisible?.() === true) raise();- else (ctx.window as unknown as BrowserWindow).once('show', raise);- });+ void Promise.allSettled(opens).then(() =>+ raiseMostRecentlyFocusedAfterRestore({+ projects: decision.projects,+ getWindow: (projectPath) => {+ const ctx = wm?.getWindowFor(projectPath);+ return ctx ? (ctx.window as unknown as RevealableWindow) : undefined;+ },+ raise: (projectPath) => {+ wm?.focusWindowForProject(projectPath);+ },+ deps: {+ setTimeout: (cb, ms) => setTimeout(cb, ms),+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+ timeoutMs: RESTORE_REVEAL_TIMEOUT_MS,+ },+ }),+ );} 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.tsnew file mode 100644index 000000000..ecc4bb281--- /dev/null+++ b/packages/desktop/src/main/restore-focus.test.ts@@ -0,0 +1,203 @@+import { describe, expect, test } from 'bun:test';+import {+ type RestoreFocusDeps,+ type RevealableWindow,+ raiseMostRecentlyFocusedAfterRestore,+ whenWindowRevealed,+} from './restore-focus.ts';++/** Captured-timer harness so tests fire the safety timeout deterministically. */+function makeTimers(timeoutMs = 8_000): {+ deps: RestoreFocusDeps;+ fireAll: () => void;+ pending: () => number;+} {+ const timers = new Map<number, () => void>();+ let nextId = 1;+ return {+ deps: {+ setTimeout: (cb) => {+ const id = nextId++;+ timers.set(id, cb);+ return id;+ },+ clearTimeout: (handle) => {+ timers.delete(handle as number);+ },+ timeoutMs,+ },+ fireAll: () => {+ const snapshot = [...timers.values()];+ timers.clear();+ for (const cb of snapshot) cb();+ },+ pending: () => timers.size,+ };+}++interface FakeWindow extends RevealableWindow {+ emitShow: () => void;+ destroy: () => void;+}++function makeWindow(opts: { visible?: boolean; destroyed?: boolean } = {}): FakeWindow {+ let visible = opts.visible ?? false;+ let destroyed = opts.destroyed ?? false;+ const showListeners: Array<() => void> = [];+ return {+ isDestroyed: () => destroyed,+ isVisible: () => visible,+ once: (_event, listener) => {+ showListeners.push(listener);+ },+ emitShow: () => {+ visible = true;+ const snapshot = [...showListeners];+ showListeners.length = 0;+ for (const l of snapshot) l();+ },+ destroy: () => {+ destroyed = true;+ },+ };+}++const flush = () => Promise.resolve();++describe('whenWindowRevealed', () => {+ test('resolves immediately when already visible', async () => {+ const { deps, pending } = makeTimers();+ await whenWindowRevealed(makeWindow({ visible: true }), deps);+ // No safety timer should linger for an already-visible window.+ expect(pending()).toBe(0);+ });++ test('resolves immediately when destroyed', async () => {+ const { deps, pending } = makeTimers();+ await whenWindowRevealed(makeWindow({ destroyed: true }), deps);+ expect(pending()).toBe(0);+ });++ test('resolves on show and clears the safety timer', async () => {+ const { deps, pending } = makeTimers();+ const win = makeWindow();+ let resolved = false;+ const p = whenWindowRevealed(win, deps).then(() => {+ resolved = true;+ });+ expect(pending()).toBe(1);+ win.emitShow();+ await p;+ expect(resolved).toBe(true);+ expect(pending()).toBe(0);+ });++ test('resolves via the safety timeout when show never fires', async () => {+ const { deps, fireAll } = makeTimers();+ const win = makeWindow();+ let resolved = false;+ const p = whenWindowRevealed(win, deps).then(() => {+ resolved = true;+ });+ await flush();+ expect(resolved).toBe(false);+ fireAll();+ await p;+ expect(resolved).toBe(true);+ });+});++describe('raiseMostRecentlyFocusedAfterRestore', () => {+ test('raises the last (most recently focused) entry only after every window reveals', async () => {+ const { deps } = makeTimers();+ const winA = makeWindow();+ const winB = makeWindow();+ const wins: Record<string, FakeWindow> = { '/a': winA, '/b': winB };+ const raised: string[] = [];++ const p = raiseMostRecentlyFocusedAfterRestore({+ projects: ['/a', '/b'],+ getWindow: (path) => wins[path],+ raise: (path) => raised.push(path),+ deps,+ });++ await flush();+ // The target (/b) shows first, but /a is still gated — no raise yet.+ winB.emitShow();+ await flush();+ expect(raised).toEqual([]);++ // The last sibling reveals; now the target must win the final show().+ winA.emitShow();+ await p;+ expect(raised).toEqual(['/b']);+ });++ test('does not wait on windows that fell back to the Navigator (absent)', async () => {+ const { deps } = makeTimers();+ const winB = makeWindow();+ const wins: Record<string, FakeWindow | undefined> = { '/a': undefined, '/b': winB };+ const raised: string[] = [];++ const p = raiseMostRecentlyFocusedAfterRestore({+ projects: ['/a', '/b'],+ getWindow: (path) => wins[path],+ raise: (path) => raised.push(path),+ deps,+ });++ await flush();+ winB.emitShow();+ await p;+ expect(raised).toEqual(['/b']);+ });++ test('skips the raise when the target was destroyed mid-restore', async () => {+ const { deps } = makeTimers();+ const winB = makeWindow({ destroyed: true });+ const raised: string[] = [];++ await raiseMostRecentlyFocusedAfterRestore({+ projects: ['/b'],+ getWindow: () => winB,+ raise: (path) => raised.push(path),+ deps,+ });++ expect(raised).toEqual([]);+ });++ test('is a no-op for an empty snapshot', async () => {+ const { deps } = makeTimers();+ const raised: string[] = [];+ await raiseMostRecentlyFocusedAfterRestore({+ projects: [],+ getWindow: () => undefined,+ raise: (path) => raised.push(path),+ deps,+ });+ expect(raised).toEqual([]);+ });++ test('still raises the target when a sibling only reveals via the safety timeout', async () => {+ const { deps, fireAll } = makeTimers();+ const winA = makeWindow(); // never emits show — must time out+ const winB = makeWindow({ visible: true }); // target already visible+ const wins: Record<string, FakeWindow> = { '/a': winA, '/b': winB };+ const raised: string[] = [];++ const p = raiseMostRecentlyFocusedAfterRestore({+ projects: ['/a', '/b'],+ getWindow: (path) => wins[path],+ raise: (path) => raised.push(path),+ deps,+ });++ await flush();+ expect(raised).toEqual([]);+ fireAll();+ await p;+ expect(raised).toEqual(['/b']);+ });+});diff --git a/packages/desktop/src/main/restore-focus.ts b/packages/desktop/src/main/restore-focus.tsnew file mode 100644index 000000000..93e533d3e--- /dev/null+++ b/packages/desktop/src/main/restore-focus.ts@@ -0,0 +1,105 @@+/**+ * Post-restore focus coordination for the update-relaunch window snapshot.+ *+ * 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.+ *+ * 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.+ *+ * Electron-free by construction: `RevealableWindow` is a structural subset and+ * timers are injected, so tests exercise the ordering without a real+ * BrowserWindow.+ */++/** 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()`). */+ once(event: 'show', listener: () => void): void;+}++export interface RestoreFocusDeps {+ /** Production wires `(cb, ms) => setTimeout(cb, ms)`; tests inject a captured-timer mock. */+ setTimeout: (cb: () => void, ms: number) => unknown;+ clearTimeout: (handle: unknown) => void;+ /**+ * Safety bound so a window whose `show()` never emits `show` (a pathological+ * native failure) can't stall the raise forever. Must comfortably exceed the+ * show gate's own timeout, since a genuinely gated window emits `show` when+ * that gate force-shows it.+ */+ timeoutMs: number;+}++/**+ * Comfortably above the show gate's 5 s force-show timeout: a window still+ * waiting on its dual-signal gate emits `show` when that gate fires, so this+ * only backstops a `show()` that throws or never dispatches `show`.+ */+export const RESTORE_REVEAL_TIMEOUT_MS = 8_000;++/**+ * Resolve once a window has revealed — it is already visible, it was destroyed+ * (closed mid-restore), it fires `show`, or the safety timeout elapses.+ */+export function whenWindowRevealed(win: RevealableWindow, deps: RestoreFocusDeps): Promise<void> {+ return new Promise<void>((resolve) => {+ if (win.isDestroyed?.() === true || win.isVisible?.() === true) {+ resolve();+ return;+ }+ let settled = false;+ const finish = (): void => {+ if (settled) return;+ settled = true;+ if (handle !== undefined) deps.clearTimeout(handle);+ resolve();+ };+ const handle = deps.setTimeout(finish, deps.timeoutMs);+ win.once('show', finish);+ });+}++/**+ * After a multi-window restore, wait for every restored window to reveal, then+ * raise the most-recently-focused one (the snapshot's last entry) so it wins the+ * final `show()`. Windows that failed to open (fell back to the Navigator) or+ * were destroyed mid-restore are skipped; if the target itself is gone, nothing+ * is raised.+ *+ * @param projects Restored project paths, ordered least → most recently focused.+ */+export async function raiseMostRecentlyFocusedAfterRestore(input: {+ projects: readonly string[];+ getWindow: (projectPath: string) => RevealableWindow | undefined;+ raise: (projectPath: string) => void;+ deps: RestoreFocusDeps;+}): Promise<void> {+ const { projects, getWindow, raise, deps } = input;+ const target = projects[projects.length - 1];+ if (target === undefined) return;++ await Promise.all(+ projects.map((projectPath) => {+ const win = getWindow(projectPath);+ if (!win || win.isDestroyed?.() === true) return Promise.resolve();+ return whenWindowRevealed(win, deps);+ }),+ );++ const targetWin = getWindow(target);+ if (!targetWin || targetWin.isDestroyed?.() === true) return;+ raise(target);+}