Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Keep desktop error dialogs from wedging the app (PRD-9099) (#5930)
Andrew Mikofalvy785028621719
diff --git a/.changeset/prd-9099-error-dialog-hang.md b/.changeset/prd-9099-error-dialog-hang.mdnew file mode 100644index 000000000..d125ad3f7--- /dev/null+++ b/.changeset/prd-9099-error-dialog-hang.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge-desktop": patch+---++Error dialogs such as "Cannot open this folder" no longer hide behind other windows, the Project Navigator no longer gets stuck on "Opening…", and the app still quits while one is open.diff --git a/lint-plugins/ok-rules/README.md b/lint-plugins/ok-rules/README.mdindex ceeda73df..beb551051 100644--- a/lint-plugins/ok-rules/README.md+++ b/lint-plugins/ok-rules/README.md@@ -625,6 +625,20 @@ Included: `packages/app/src/**/*.tsx`, `packages/desktop/src/**/*.tsx`, `packageRule: [`lint-plugins/ok-rules/rules/no-demoted-dialog-confirm.mjs`](rules/no-demoted-dialog-confirm.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-demoted-dialog-confirm.fixture.tsx`](__fixtures__/no-demoted-dialog-confirm.fixture.tsx). Test: [`lint-plugins/ok-rules/tests/no-demoted-dialog-confirm.uncached.test.mjs`](tests/no-demoted-dialog-confirm.uncached.test.mjs). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.+### `no-blocking-error-box`++Desktop error reporting. No code under `packages/desktop/src` calls `showErrorBox` on Electron's `dialog`, or on anything shaped like it. Errors are shown with `showErrorDialog` from [`packages/desktop/src/main/error-dialog.ts`](../../packages/desktop/src/main/error-dialog.ts), an async `showMessageBox` attached to a parent window.++**Why.** `dialog.showErrorBox` is synchronous and takes no parent window. On Linux it runs `gtk_dialog_run`, which holds the main thread in a nested GTK loop until someone presses its button. With no parent, the window manager can stack the dialog behind the window it is reporting on, and the dialog has no taskbar entry, so nothing on screen shows it is still open. In PRD-9099 that left the Project Navigator on "Opening <folder>…" indefinitely: the `ok:project:open` reply could not leave the main process. SIGTERM was ignored as well, because both Chromium's shutdown task and the app's Node signal handler wait for the main loop. `showMessageBox` with a parent stays above that window, and the main loop keeps running while it is open.++**Scoped** (see the rule's `RULE_SCOPES` entry in [`scope.mjs`](scope.mjs)) to `packages/desktop/src/**/*.ts`, the only package that runs in Electron's main process. `**/*.test.ts` and `**/*.test-helper.ts` are excluded, because tests stub the method by name.++The rule matches a call of a non-computed `.showErrorBox` member, whatever the receiver: `dialog`, `electron.dialog`, or an injected dialog host. It does NOT catch a bare `showErrorBox(...)` identifier, a computed `dialog['showErrorBox'](...)`, or a reference taken without calling it (`const f = dialog.showErrorBox`). Those shapes have no realistic occurrence.++**Opting out.** There is no sanctioned use after `app` is ready. Before `ready`, Electron prints the error box to stderr on Linux instead of showing it, so even an early-boot error needs a different reporting path.++Rule: [`lint-plugins/ok-rules/rules/no-blocking-error-box.mjs`](rules/no-blocking-error-box.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-blocking-error-box.fixture.tsx`](__fixtures__/no-blocking-error-box.fixture.tsx). Test: [`lint-plugins/ok-rules/tests/no-blocking-error-box.uncached.test.mjs`](tests/no-blocking-error-box.uncached.test.mjs). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.+### `no-unconverted-git-pathspec`Git pathspec discipline. Fires on a hand-written `'--'` string literal in an array literal, or as a direct argument of a `.raw(...)` varargs call, anywhere under `packages/{core,server,cli,desktop}/src/**` — unless the argv's leading non-flag token is one of the five verbs whose `--` operands are not pathspecs. The array branch consults no git token of any kind; see the over-catch note below. The tail after the separator is built with `pathspecArgs(paths)` from [`packages/core/src/git-pathspec.ts`](../../packages/core/src/git-pathspec.ts), which emits the separator and the `:(literal)` conversion together.diff --git a/lint-plugins/ok-rules/__fixtures__/no-blocking-error-box.fixture.tsx b/lint-plugins/ok-rules/__fixtures__/no-blocking-error-box.fixture.tsxnew file mode 100644index 000000000..4bdf69229--- /dev/null+++ b/lint-plugins/ok-rules/__fixtures__/no-blocking-error-box.fixture.tsx@@ -0,0 +1,25 @@+type MessageBox = (options: { type: string; message: string }) => Promise<unknown>;+declare const dialog: {+ showErrorBox: (title: string, body: string) => void;+ showMessageBox: MessageBox;+};+declare const electron: { dialog: typeof dialog };+declare const host: { showErrorBox: (title: string, body: string) => void };+declare function showErrorBox(title: string, body: string): void;+declare function showErrorDialog(title: string, body: string): Promise<void>;++export function positives(): void {+ dialog.showErrorBox('p1', 'dialog module');+ electron.dialog.showErrorBox('p2', 'namespaced electron import');+ host.showErrorBox('p3', 'injected dialog host');+}++export async function negatives(): Promise<void> {+ await dialog.showMessageBox({ type: 'error', message: 'n1 async message box' });+ await showErrorDialog('n2', 'sanctioned helper');+ showErrorBox('n3', 'bare identifier, not a dialog member');+ const n4 = 'showErrorBox' as const;+ dialog[n4]('n4', 'computed member access');+ const n5 = dialog.showErrorBox;+ void n5;+}diff --git a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.jsonindex 4046ee974..3a16ad1cc 100644--- a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json+++ b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json@@ -6,6 +6,7 @@"ok/microcopy-ellipsis": "error","ok/no-app-core-barrel-import": "error","ok/no-blind-agent-host-fanout": "error",+ "ok/no-blocking-error-box": "error","ok/no-demoted-dialog-confirm": "error","ok/no-hand-rolled-branch-validation": "error","ok/no-hand-rolled-test-file-suffix": "error",diff --git a/lint-plugins/ok-rules/index.mjs b/lint-plugins/ok-rules/index.mjsindex de3aef990..e87a2ef67 100644--- a/lint-plugins/ok-rules/index.mjs+++ b/lint-plugins/ok-rules/index.mjs@@ -5,6 +5,7 @@ import { cstPmHandlerTodoStub } from './rules/cst-pm-handler-todo-stub.mjs';import { microcopyEllipsis } from './rules/microcopy-ellipsis.mjs';import { noAppCoreBarrelImport } from './rules/no-app-core-barrel-import.mjs';import { noBlindAgentHostFanout } from './rules/no-blind-agent-host-fanout.mjs';+import { noBlockingErrorBox } from './rules/no-blocking-error-box.mjs';import { noDemotedDialogConfirm } from './rules/no-demoted-dialog-confirm.mjs';import { noHandRolledBranchValidation } from './rules/no-hand-rolled-branch-validation.mjs';import { noHandRolledSpinner } from './rules/no-hand-rolled-spinner.mjs';@@ -39,6 +40,7 @@ const declared = {'microcopy-ellipsis': microcopyEllipsis,'no-app-core-barrel-import': noAppCoreBarrelImport,'no-blind-agent-host-fanout': noBlindAgentHostFanout,+ 'no-blocking-error-box': noBlockingErrorBox,'no-demoted-dialog-confirm': noDemotedDialogConfirm,'no-hand-rolled-branch-validation': noHandRolledBranchValidation,'no-hand-rolled-test-file-suffix': noHandRolledTestFileSuffix,diff --git a/lint-plugins/ok-rules/rules/no-blocking-error-box.mjs b/lint-plugins/ok-rules/rules/no-blocking-error-box.mjsnew file mode 100644index 000000000..86e9892a8--- /dev/null+++ b/lint-plugins/ok-rules/rules/no-blocking-error-box.mjs@@ -0,0 +1,27 @@+import { docsUrl } from '../docs.mjs';++const URL = docsUrl('no-blocking-error-box');++const MESSAGE = `Blocking error box. \`dialog.showErrorBox\` runs a synchronous dialog with no parent window: the main process stops until someone dismisses it, and on Linux it can fall behind the window it reports on, so the IPC reply that window waits for never arrives and SIGTERM goes unhandled. Show the error with \`showErrorDialog\` from \`packages/desktop/src/main/error-dialog.ts\`, attached to the window the user is looking at. See ${URL}`;++export const noBlockingErrorBox = {+ meta: {+ type: 'problem',+ docs: {+ description: 'Desktop code must not show a blocking, parentless dialog.showErrorBox.',+ url: URL,+ },+ },+ create(context) {+ return {+ CallExpression(node) {+ const callee = node.callee;+ if (callee?.type !== 'MemberExpression' || callee.computed) return;+ if (callee.property?.type !== 'Identifier' || callee.property.name !== 'showErrorBox') {+ return;+ }+ context.report({ node, message: MESSAGE });+ },+ };+ },+};diff --git a/lint-plugins/ok-rules/scope.mjs b/lint-plugins/ok-rules/scope.mjsindex abf1bab83..cb2885ce7 100644--- a/lint-plugins/ok-rules/scope.mjs+++ b/lint-plugins/ok-rules/scope.mjs@@ -89,6 +89,12 @@ export const RULE_SCOPES = {'!packages/md-conformance/src/class-proofs/proofs/**','lint-plugins/ok-rules/__fixtures__/class-proof-registration-discipline.fixture.tsx',],+ 'no-blocking-error-box': [+ 'packages/desktop/src/**/*.ts',+ '!**/*.test.ts',+ '!**/*.test-helper.ts',+ 'lint-plugins/ok-rules/__fixtures__/no-blocking-error-box.fixture.tsx',+ ],'require-windowshide-on-spawn': ['packages/server/src/**/*.ts','packages/cli/src/**/*.ts',diff --git a/lint-plugins/ok-rules/tests/no-blocking-error-box.uncached.test.mjs b/lint-plugins/ok-rules/tests/no-blocking-error-box.uncached.test.mjsnew file mode 100644index 000000000..ba283d389--- /dev/null+++ b/lint-plugins/ok-rules/tests/no-blocking-error-box.uncached.test.mjs@@ -0,0 +1,38 @@+import { fileURLToPath } from 'node:url';+import { describe, expect, test } from 'vitest';+import {+ lintOkRulesFixture,+ readEnabledRuleIds,+ readRegisteredRuleNames,+ readRuleScope,+} from '../../../test-support/read-ok-rules-config.test-helper.ts';++const REPO_ROOT = fileURLToPath(new URL('../../..', import.meta.url));+const RULE = 'no-blocking-error-box';+const CODE = `ok(${RULE})`;+const FIXTURE = `lint-plugins/ok-rules/__fixtures__/${RULE}.fixture.tsx`;+const DOCS = `lint-plugins/ok-rules/README.md#${RULE}`;++describe(`${RULE} oxlint rule`, () => {+ test('fires at exactly its 3 showErrorBox member calls, by its own code, and on no negative case', () => {+ const fires = lintOkRulesFixture(FIXTURE).filter((d) => d.code === CODE);+ expect(fires.map((fire) => fire.position)).toEqual(['12:3', '13:3', '14:3']);+ for (const fire of fires) {+ expect(fire.message).toContain('Blocking error box');+ expect(fire.message).toContain('showErrorDialog');+ expect(fire.message).toMatch(/https?:\/\/[^\s]+/);+ expect(fire.message).toContain(DOCS);+ }+ });++ test('rule is registered, enabled, and scoped via its RULE_SCOPES entry', async () => {+ expect(await readRegisteredRuleNames(REPO_ROOT)).toContain(RULE);+ expect(await readEnabledRuleIds(REPO_ROOT)).toContain(`ok/${RULE}`);+ });++ test('its scope table still carries every include and exclude the rule depends on', () => {+ expect(readRuleScope(REPO_ROOT, RULE).sort()).toEqual(+ ['packages/desktop/src/**/*.ts', '!**/*.test.ts', '!**/*.test-helper.ts', FIXTURE].sort(),+ );+ });+});diff --git a/oxlint.config.ts b/oxlint.config.tsindex d74643d97..59ba9a601 100644--- a/oxlint.config.ts+++ b/oxlint.config.ts@@ -54,6 +54,7 @@ export default defineConfig({'ok/microcopy-ellipsis': 'error','ok/no-app-core-barrel-import': 'error','ok/no-blind-agent-host-fanout': 'error',+ 'ok/no-blocking-error-box': 'error','ok/no-demoted-dialog-confirm': 'error','ok/no-hand-rolled-branch-validation': 'error','ok/no-hand-rolled-test-file-suffix': 'error',diff --git a/packages/app/src/lib/command-menu-parity.uncached.test.ts b/packages/app/src/lib/command-menu-parity.uncached.test.tsindex 3000e58e2..a267e68c8 100644--- a/packages/app/src/lib/command-menu-parity.uncached.test.ts+++ b/packages/app/src/lib/command-menu-parity.uncached.test.ts@@ -109,6 +109,7 @@ function makeFullDeps(): MenuDeps {appName: 'OpenKnowledge',showDevToolsMenu: true,dialog: {} as MenuDeps['dialog'],+ errorDialogParent: () => null,openNavigator: noop,openProject: () => Promise.resolve(),openEphemeralFile: () => Promise.resolve(),diff --git a/packages/desktop/src/main/dialog-helpers.test.ts b/packages/desktop/src/main/dialog-helpers.test.tsindex e80bc875c..88b91dae6 100644--- a/packages/desktop/src/main/dialog-helpers.test.ts+++ b/packages/desktop/src/main/dialog-helpers.test.ts@@ -1,3 +1,4 @@+import type { BrowserWindow } from 'electron';import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';const dialogLog = vi.hoisted(() => ({@@ -14,11 +15,26 @@ import {resolvePickedPathForIndex,} from './dialog-helpers.ts';+type PickerHost = Parameters<typeof promptForExistingFolder>[0];+type PickerOpts = Partial<Parameters<typeof promptForExistingFolder>[1]>;++function pickFolder(host: PickerHost, opts: PickerOpts = {}) {+ return promptForExistingFolder(host, { errorParent: () => null, ...opts });+}++function pickMarkdownFile(host: PickerHost, opts: PickerOpts = {}) {+ return promptForExistingMarkdownFile(host, { errorParent: () => null, ...opts });+}+const ORIGINAL_SMOKE = process.env.OK_DESKTOP_E2E_SMOKE;const ORIGINAL_PICKED = process.env.OK_DESKTOP_TEST_PICKED_PATH;+function messageBoxAcknowledged() {+ return vi.fn(async () => ({ response: 0, checkboxChecked: false }));+}+function pickerReturning(result: { canceled: boolean; filePaths: string[] }) {- return { showOpenDialog: vi.fn(async () => result), showErrorBox: vi.fn() };+ return { showOpenDialog: vi.fn(async () => result), showMessageBox: messageBoxAcknowledged() };}beforeEach(() => {@@ -40,7 +56,10 @@ describe('promptForExistingFolder', () => {test('OS picker uses openDirectory + createDirectory + showHiddenFiles (macOS: New Folder button + dot-dirs visible for `.claude/worktrees`)', async () => {const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/picked'] }));- const result = await promptForExistingFolder({ showOpenDialog, showErrorBox: vi.fn() });+ const result = await pickFolder({+ showOpenDialog,+ showMessageBox: messageBoxAcknowledged(),+ });expect(result).toBe('/picked');expect(showOpenDialog).toHaveBeenCalledWith({properties: ['openDirectory', 'createDirectory', 'showHiddenFiles'],@@ -49,8 +68,8 @@ describe('promptForExistingFolder', () => {test('a cancel returns null silently', async () => {const picker = pickerReturning({ canceled: true, filePaths: [] });- expect(await promptForExistingFolder(picker)).toBe(null);- expect(picker.showErrorBox).not.toHaveBeenCalled();+ expect(await pickFolder(picker)).toBe(null);+ expect(picker.showMessageBox).not.toHaveBeenCalled();expect(dialogLog.warn).not.toHaveBeenCalled();expect(dialogLog.info).toHaveBeenCalledWith({ outcome: 'canceled', target: 'folder' },@@ -64,24 +83,50 @@ describe('promptForExistingFolder', () => {{ label: 'a relative path', filePaths: ['notes'], shape: 'relative' },])('a non-cancel close with $label shows an error and logs it', async ({ filePaths, shape }) => {const picker = pickerReturning({ canceled: false, filePaths });- expect(await promptForExistingFolder(picker)).toBe(null);- expect(picker.showErrorBox).toHaveBeenCalledTimes(1);- expect(picker.showErrorBox.mock.calls[0]?.[0]).toContain('open that folder');+ expect(await pickFolder(picker)).toBe(null);+ expect(picker.showMessageBox).toHaveBeenCalledTimes(1);+ expect(picker.showMessageBox).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'error',+ title: expect.stringContaining('open that folder'),+ }),+ );expect(dialogLog.warn).toHaveBeenCalledWith({ outcome: 'no-selection', target: 'folder', shape, count: filePaths.length },expect.any(String),);});+ test('the no-selection error attaches to the window errorParent names', async () => {+ const picker = pickerReturning({ canceled: false, filePaths: [] });+ const parent = { isDestroyed: () => false } as unknown as BrowserWindow;+ expect(await pickFolder(picker, { errorParent: () => parent })).toBe(null);+ expect(picker.showMessageBox).toHaveBeenCalledWith(+ parent,+ expect.objectContaining({ type: 'error' }),+ );+ });++ test('a no-selection close returns without waiting for its error dialog', async () => {+ const picker = {+ showOpenDialog: vi.fn(async () => ({ canceled: false, filePaths: [] })),+ showMessageBox: vi.fn(+ () => new Promise<{ response: number; checkboxChecked: boolean }>(() => {}),+ ),+ };+ expect(await pickFolder(picker)).toBe(null);+ expect(picker.showMessageBox).toHaveBeenCalledTimes(1);+ });+test('a picker that throws is logged and rethrown', async () => {const failure = new Error('portal unavailable');const picker = {showOpenDialog: vi.fn(async () => {throw failure;}),- showErrorBox: vi.fn(),+ showMessageBox: messageBoxAcknowledged(),};- await expect(promptForExistingFolder(picker)).rejects.toBe(failure);+ await expect(pickFolder(picker)).rejects.toBe(failure);expect(dialogLog.error).toHaveBeenCalledWith(expect.objectContaining({ outcome: 'failed' }),expect.any(String),@@ -92,7 +137,7 @@ describe('promptForExistingFolder', () => {process.env.OK_DESKTOP_E2E_SMOKE = '1';process.env.OK_DESKTOP_TEST_PICKED_PATH = '/tmp/seam';const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/never/used'] }));- expect(await promptForExistingFolder({ showOpenDialog, showErrorBox: vi.fn() })).toBe(+ expect(await pickFolder({ showOpenDialog, showMessageBox: messageBoxAcknowledged() })).toBe('/tmp/seam',);expect(showOpenDialog).not.toHaveBeenCalled();@@ -101,7 +146,7 @@ describe('promptForExistingFolder', () => {test('test seam ignored when OK_DESKTOP_E2E_SMOKE missing — production safety', async () => {process.env.OK_DESKTOP_TEST_PICKED_PATH = '/tmp/should-not-fire';const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/real/pick'] }));- expect(await promptForExistingFolder({ showOpenDialog, showErrorBox: vi.fn() })).toBe(+ expect(await pickFolder({ showOpenDialog, showMessageBox: messageBoxAcknowledged() })).toBe('/real/pick',);expect(showOpenDialog).toHaveBeenCalled();@@ -111,7 +156,7 @@ describe('promptForExistingFolder', () => {process.env.OK_DESKTOP_E2E_SMOKE = '1';process.env.OK_DESKTOP_TEST_PICKED_PATH = '';const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/real/pick'] }));- expect(await promptForExistingFolder({ showOpenDialog, showErrorBox: vi.fn() })).toBe(+ expect(await pickFolder({ showOpenDialog, showMessageBox: messageBoxAcknowledged() })).toBe('/real/pick',);expect(showOpenDialog).toHaveBeenCalled();@@ -119,8 +164,8 @@ describe('promptForExistingFolder', () => {test('defaultPath threads through to showOpenDialog', async () => {const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/picked'] }));- await promptForExistingFolder(- { showOpenDialog, showErrorBox: vi.fn() },+ await pickFolder(+ { showOpenDialog, showMessageBox: messageBoxAcknowledged() },{ defaultPath: '/project/root' },);expect(showOpenDialog).toHaveBeenCalledWith({@@ -131,7 +176,7 @@ describe('promptForExistingFolder', () => {test('omits defaultPath when not provided', async () => {const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/picked'] }));- await promptForExistingFolder({ showOpenDialog, showErrorBox: vi.fn() });+ await pickFolder({ showOpenDialog, showMessageBox: messageBoxAcknowledged() });expect(showOpenDialog).toHaveBeenCalledWith({properties: ['openDirectory', 'createDirectory', 'showHiddenFiles'],});@@ -185,7 +230,10 @@ describe('promptForExistingMarkdownFile', () => {test('OS picker uses openFile + a md/mdx filter', async () => {const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/notes/x.md'] }));- const result = await promptForExistingMarkdownFile({ showOpenDialog, showErrorBox: vi.fn() });+ const result = await pickMarkdownFile({+ showOpenDialog,+ showMessageBox: messageBoxAcknowledged(),+ });expect(result).toBe('/notes/x.md');expect(showOpenDialog).toHaveBeenCalledWith({properties: ['openFile'],@@ -195,8 +243,8 @@ describe('promptForExistingMarkdownFile', () => {test('a cancel returns null silently', async () => {const picker = pickerReturning({ canceled: true, filePaths: [] });- expect(await promptForExistingMarkdownFile(picker)).toBe(null);- expect(picker.showErrorBox).not.toHaveBeenCalled();+ expect(await pickMarkdownFile(picker)).toBe(null);+ expect(picker.showMessageBox).not.toHaveBeenCalled();expect(dialogLog.info).toHaveBeenCalledWith({ outcome: 'canceled', target: 'file' },expect.any(String),@@ -209,9 +257,11 @@ describe('promptForExistingMarkdownFile', () => {{ label: 'a relative path', filePaths: ['notes.md'], shape: 'relative' },])('a non-cancel close with $label shows an error', async ({ filePaths, shape }) => {const picker = pickerReturning({ canceled: false, filePaths });- expect(await promptForExistingMarkdownFile(picker)).toBe(null);- expect(picker.showErrorBox).toHaveBeenCalledTimes(1);- expect(picker.showErrorBox.mock.calls[0]?.[0]).toContain('open that file');+ expect(await pickMarkdownFile(picker)).toBe(null);+ expect(picker.showMessageBox).toHaveBeenCalledTimes(1);+ expect(picker.showMessageBox).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'error', title: expect.stringContaining('open that file') }),+ );expect(dialogLog.warn).toHaveBeenCalledWith({ outcome: 'no-selection', target: 'file', shape, count: filePaths.length },expect.any(String),@@ -222,16 +272,19 @@ describe('promptForExistingMarkdownFile', () => {process.env.OK_DESKTOP_E2E_SMOKE = '1';process.env.OK_DESKTOP_TEST_PICKED_PATH = '/tmp/seam.md';const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/never/used.md'] }));- expect(await promptForExistingMarkdownFile({ showOpenDialog, showErrorBox: vi.fn() })).toBe(- '/tmp/seam.md',- );+ expect(+ await pickMarkdownFile({+ showOpenDialog,+ showMessageBox: messageBoxAcknowledged(),+ }),+ ).toBe('/tmp/seam.md');expect(showOpenDialog).not.toHaveBeenCalled();});test('defaultPath threads through to showOpenDialog', async () => {const showOpenDialog = vi.fn(async () => ({ canceled: false, filePaths: ['/notes/x.md'] }));- await promptForExistingMarkdownFile(- { showOpenDialog, showErrorBox: vi.fn() },+ await pickMarkdownFile(+ { showOpenDialog, showMessageBox: messageBoxAcknowledged() },{ defaultPath: '/notes' },);expect(showOpenDialog).toHaveBeenCalledWith({diff --git a/packages/desktop/src/main/dialog-helpers.ts b/packages/desktop/src/main/dialog-helpers.tsindex 798c9b644..6a4ba7f00 100644--- a/packages/desktop/src/main/dialog-helpers.ts+++ b/packages/desktop/src/main/dialog-helpers.ts@@ -1,9 +1,11 @@import { isAbsolute } from 'node:path';+import type { BrowserWindow } from 'electron';import { getLogger } from './desktop-logger.ts';+import { type ErrorDialogHost, showErrorDialog } from './error-dialog.ts';type OpenDialogOptions = Parameters<DialogLike['showOpenDialog']>[0];-interface DialogLike {+interface DialogLike extends ErrorDialogHost {showOpenDialog(opts: {properties: (| 'openDirectory'@@ -15,7 +17,6 @@ interface DialogLike {defaultPath?: string;filters?: { name: string; extensions: string[] }[];}): Promise<{ canceled: boolean; filePaths: string[] }>;- showErrorBox(title: string, content: string): void;}const NO_SELECTION_COPY = {@@ -40,6 +41,7 @@ async function runPicker(dialogModule: DialogLike,target: keyof typeof NO_SELECTION_COPY,options: OpenDialogOptions,+ errorParent: () => BrowserWindow | null,): Promise<string | null> {const log = getLogger('dialog');let result: Awaited<ReturnType<DialogLike['showOpenDialog']>>;@@ -61,7 +63,7 @@ async function runPicker('picker returned no usable path',);const copy = NO_SELECTION_COPY[target];- dialogModule.showErrorBox(copy.title, copy.body);+ void showErrorDialog(dialogModule, errorParent(), copy.title, copy.body);return null;}return picked;@@ -69,6 +71,7 @@ async function runPicker(interface PromptForPickerOpts {defaultPath?: string;+ errorParent: () => BrowserWindow | null;}export function resolvePickedPathForIndex(raw: string, callIndex: number): string | null {@@ -92,25 +95,35 @@ function readTestPickedPath(): string | null {export async function promptForExistingFolder(dialogModule: DialogLike,- opts: PromptForPickerOpts = {},+ opts: PromptForPickerOpts,): Promise<string | null> {const testSeam = readTestPickedPath();if (testSeam !== null) return testSeam;- return runPicker(dialogModule, 'folder', {- properties: ['openDirectory', 'createDirectory', 'showHiddenFiles'],- ...(opts.defaultPath !== undefined ? { defaultPath: opts.defaultPath } : {}),- });+ return runPicker(+ dialogModule,+ 'folder',+ {+ properties: ['openDirectory', 'createDirectory', 'showHiddenFiles'],+ ...(opts.defaultPath !== undefined ? { defaultPath: opts.defaultPath } : {}),+ },+ opts.errorParent,+ );}export async function promptForExistingMarkdownFile(dialogModule: DialogLike,- opts: PromptForPickerOpts = {},+ opts: PromptForPickerOpts,): Promise<string | null> {const testSeam = readTestPickedPath();if (testSeam !== null) return testSeam;- return runPicker(dialogModule, 'file', {- properties: ['openFile'],- filters: [{ name: 'Markdown', extensions: ['md', 'mdx'] }],- ...(opts.defaultPath !== undefined ? { defaultPath: opts.defaultPath } : {}),- });+ return runPicker(+ dialogModule,+ 'file',+ {+ properties: ['openFile'],+ filters: [{ name: 'Markdown', extensions: ['md', 'mdx'] }],+ ...(opts.defaultPath !== undefined ? { defaultPath: opts.defaultPath } : {}),+ },+ opts.errorParent,+ );}diff --git a/packages/desktop/src/main/error-dialog.test.ts b/packages/desktop/src/main/error-dialog.test.tsnew file mode 100644index 000000000..228a4197d--- /dev/null+++ b/packages/desktop/src/main/error-dialog.test.ts@@ -0,0 +1,189 @@+import type { BrowserWindow } from 'electron';+import { beforeEach, describe, expect, test, vi } from 'vitest';++const dialogLog = vi.hoisted(() => ({+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ debug: vi.fn(),+}));+vi.mock('./desktop-logger.ts', () => ({ getLogger: () => dialogLog }));++import { EventEmitter } from 'node:events';+import { showErrorDialog, showErrorDialogOnceVisible } from './error-dialog.ts';++function windowStub(destroyed: boolean): BrowserWindow {+ return { isDestroyed: () => destroyed } as unknown as BrowserWindow;+}++function hostResolving() {+ return { showMessageBox: vi.fn(async () => ({ response: 0, checkboxChecked: false })) };+}++const ERROR_OPTIONS = expect.objectContaining({+ type: 'error',+ title: 'Cannot open this folder',+ message: 'Cannot open this folder',+ detail: '/home/me\n\nReason: home',+ buttons: ['OK'],+});++beforeEach(() => {+ vi.clearAllMocks();+});++describe('showErrorDialog', () => {+ test('attaches the dialog to a live parent window so it stays above it', async () => {+ const host = hostResolving();+ const parent = windowStub(false);+ await showErrorDialog(host, parent, 'Cannot open this folder', '/home/me\n\nReason: home');+ expect(host.showMessageBox).toHaveBeenCalledTimes(1);+ expect(host.showMessageBox).toHaveBeenCalledWith(parent, ERROR_OPTIONS);+ });++ test.each([+ { label: 'no parent', parent: null },+ { label: 'a destroyed parent', parent: windowStub(true) },+ ])('shows an unattached dialog when there is $label', async ({ parent }) => {+ const host = hostResolving();+ await showErrorDialog(host, parent, 'Cannot open this folder', '/home/me\n\nReason: home');+ expect(host.showMessageBox).toHaveBeenCalledWith(ERROR_OPTIONS);+ });++ test('a dialog that throws while showing is logged instead of throwing', async () => {+ const failure = new Error('app not ready');+ const host = {+ showMessageBox: vi.fn(() => {+ throw failure;+ }),+ };+ await expect(showErrorDialog(host, null, 'title', 'body')).resolves.toBeUndefined();+ expect(dialogLog.error).toHaveBeenCalledWith(+ { title: 'title', err: failure },+ 'error dialog failed to show',+ );+ });++ test('a dialog that fails to show is logged instead of rejecting', async () => {+ const failure = new Error('no display');+ const host = {+ showMessageBox: vi.fn(async () => {+ throw failure;+ }),+ };+ await expect(showErrorDialog(host, null, 'title', 'body')).resolves.toBeUndefined();+ expect(dialogLog.error).toHaveBeenCalledWith(+ { title: 'title', err: failure },+ 'error dialog failed to show',+ );+ });+});++class PendingWindow extends EventEmitter {+ visible = false;+ destroyed = false;+ isVisible(): boolean {+ return this.visible;+ }+ isDestroyed(): boolean {+ return this.destroyed;+ }+ asBrowserWindow(): BrowserWindow {+ return this as unknown as BrowserWindow;+ }+}++function revealDeps() {+ const timers: Array<() => void> = [];+ return {+ timers,+ deps: {+ setTimeout: (cb: () => void) => {+ timers.push(cb);+ return timers.length;+ },+ clearTimeout: vi.fn(),+ timeoutMs: 8_000,+ },+ };+}++describe('showErrorDialogOnceVisible', () => {+ test('attaches to a window that is already visible', async () => {+ const host = hostResolving();+ const window = new PendingWindow();+ window.visible = true;+ await showErrorDialogOnceVisible(+ host,+ window.asBrowserWindow(),+ 'title',+ 'body',+ revealDeps().deps,+ );+ expect(host.showMessageBox).toHaveBeenCalledWith(+ window,+ expect.objectContaining({ title: 'title' }),+ );+ });++ test('waits for a hidden window to show, then attaches to it', async () => {+ const host = hostResolving();+ const window = new PendingWindow();+ const shown = showErrorDialogOnceVisible(+ host,+ window.asBrowserWindow(),+ 'title',+ 'body',+ revealDeps().deps,+ );+ await Promise.resolve();+ expect(host.showMessageBox).not.toHaveBeenCalled();+ window.visible = true;+ window.emit('show');+ await shown;+ expect(host.showMessageBox).toHaveBeenCalledTimes(1);+ expect(host.showMessageBox).toHaveBeenCalledWith(+ window,+ expect.objectContaining({ title: 'title' }),+ );+ });++ test('attaches to a minimized window once it is restored', async () => {+ const host = hostResolving();+ const window = new PendingWindow();+ const shown = showErrorDialogOnceVisible(+ host,+ window.asBrowserWindow(),+ 'title',+ 'body',+ revealDeps().deps,+ );+ await Promise.resolve();+ expect(host.showMessageBox).not.toHaveBeenCalled();+ window.visible = true;+ window.emit('restore');+ await shown;+ expect(host.showMessageBox).toHaveBeenCalledWith(+ window,+ expect.objectContaining({ title: 'title' }),+ );+ });++ test('shows the dialog unattached when the window is still hidden at the reveal timeout', async () => {+ const host = hostResolving();+ const window = new PendingWindow();+ const { timers, deps } = revealDeps();+ const shown = showErrorDialogOnceVisible(host, window.asBrowserWindow(), 'title', 'body', deps);+ expect(timers).toHaveLength(1);+ timers[0]?.();+ await shown;+ expect(host.showMessageBox).toHaveBeenCalledTimes(1);+ expect(host.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ title: 'title' }));+ });++ test('shows the dialog unattached when there is no window', async () => {+ const host = hostResolving();+ await showErrorDialogOnceVisible(host, null, 'title', 'body', revealDeps().deps);+ expect(host.showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ title: 'title' }));+ });+});diff --git a/packages/desktop/src/main/error-dialog.ts b/packages/desktop/src/main/error-dialog.tsnew file mode 100644index 000000000..1c79a44ac--- /dev/null+++ b/packages/desktop/src/main/error-dialog.ts@@ -0,0 +1,56 @@+import type { BrowserWindow, MessageBoxOptions, MessageBoxReturnValue } from 'electron';+import { getLogger } from './desktop-logger.ts';+import { type RestoreFocusDeps, whenWindowRevealed } from './restore-focus.ts';++export interface ErrorDialogHost {+ showMessageBox(options: MessageBoxOptions): Promise<MessageBoxReturnValue>;+ showMessageBox(window: BrowserWindow, options: MessageBoxOptions): Promise<MessageBoxReturnValue>;+}++function logShowFailure(title: string, err: unknown): void {+ getLogger('dialog').error({ title, err }, 'error dialog failed to show');+}++export function showErrorDialog(+ host: ErrorDialogHost,+ parent: BrowserWindow | null,+ title: string,+ body: string,+): Promise<void> {+ const options: MessageBoxOptions = {+ type: 'error',+ title,+ message: title,+ detail: body,+ buttons: ['OK'],+ defaultId: 0,+ noLink: true,+ };+ let shown: Promise<MessageBoxReturnValue>;+ try {+ shown =+ parent !== null && !parent.isDestroyed()+ ? host.showMessageBox(parent, options)+ : host.showMessageBox(options);+ } catch (err) {+ logShowFailure(title, err);+ return Promise.resolve();+ }+ return shown.then(+ () => undefined,+ (err: unknown) => logShowFailure(title, err),+ );+}++export function showErrorDialogOnceVisible(+ host: ErrorDialogHost,+ parent: BrowserWindow | null,+ title: string,+ body: string,+ reveal: RestoreFocusDeps,+): Promise<void> {+ if (parent === null) return showErrorDialog(host, null, title, body);+ return whenWindowRevealed(parent, reveal).then(() =>+ showErrorDialog(host, !parent.isDestroyed() && parent.isVisible() ? parent : null, title, body),+ );+}diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex a2496e32d..206a03f1b 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -285,6 +285,7 @@ import {runDriverBootSmoke,} from './driver-boot-smoke.ts';import { EMBED_HOST_PATTERNS, rewriteEmbedRequestHeaders } from './embed-referer.ts';+import { showErrorDialog, showErrorDialogOnceVisible } from './error-dialog.ts';import {defaultGitTopLevel,discoverProject,@@ -1776,11 +1777,10 @@ async function openProject();if (discovery.kind === 'rejected') {- dialog.showErrorBox(+ showErrorOverNavigator('Cannot open this folder',`${projectPath}\n\nReason: ${REJECTION_REASON_COPY[discovery.reason]}`,);- openNavigator();return false;}@@ -1843,7 +1843,7 @@ async function openProject({ projectName, resolvedPickedName },'project admission confirmation requested',);- const { response } = await dialog.showMessageBox({+ const { response } = await showMessageBoxAttached({type: 'question',buttons: ['Cancel', `Open ${projectName}`],cancelId: 0,@@ -1885,7 +1885,7 @@ async function openProject(openNavigator();navigator = navigatorWindow;if (!navigator) {- dialog.showErrorBox(+ showErrorOnFocusedWindow('Cannot open this folder',`${projectPath}\n\nFailed to open the Project Navigator.`,);@@ -2208,7 +2208,7 @@ async function openProjectOrFallbackToNavigator(holderIsOwnChild,},{- showMessageBox: (options) => dialog.showMessageBox(options),+ showMessageBox: (options) => showMessageBoxAttached(options),forceStop: (expectedHolder) => {ensureWindowManager();return wm.forceStopConflictingServer(projectPath, expectedHolder);@@ -2236,11 +2236,10 @@ async function openProjectOrFallbackToNavigator('[main] openProject retry after stopping the conflicting server failed',);flushDesktopLogger();- dialog.showErrorBox(+ showErrorOverNavigator('Unable to open project',`${projectPath}\n\n${(retryErr as Error).message}`,);- openNavigator();return false;}},@@ -2261,7 +2260,7 @@ async function openProjectOrFallbackToNavigator(if (prompt.kind !== 'not-offered') {if (prompt.kind === 'stop-failed') {flushDesktopLogger();- dialog.showErrorBox(+ showErrorOverNavigator('Unable to open project',`${projectPath}\n\n` +(prompt.reason === 'eperm'@@ -2281,7 +2280,7 @@ async function openProjectOrFallbackToNavigator(if (isStaleLockHolder && otherChannelHolder === null) {const stopCommandTarget = quoteStopCommandPath(projectPath, process.platform);flushDesktopLogger();- dialog.showErrorBox(+ showErrorOverNavigator(dialogTitle,`${dialogBody}\n\n` +(holderIsOwnChild@@ -2302,8 +2301,7 @@ async function openProjectOrFallbackToNavigator(openNavigator();return false;}- dialog.showErrorBox(dialogTitle, dialogBody);- openNavigator();+ showErrorOverNavigator(dialogTitle, dialogBody);return false;}}@@ -2317,13 +2315,10 @@ async function openEphemeralFile(filePath: string): Promise<void> {plan = prepareSingleFileOpen(filePath);} catch (err) {getLogger('project').warn({ file: filePath, err }, 'single-file open could not be prepared');- dialog.showErrorBox(+ showErrorOnFocusedWindowOrNavigator('Cannot open this file',`${filePath}\n\n${err instanceof Error ? err.message : String(err)}`,);- if (BrowserWindow.getAllWindows().length === 0) {- openNavigator();- }return;}@@ -2362,13 +2357,10 @@ async function openEphemeralFile(filePath: string): Promise<void> {{ file: plan.canonicalFilePath, err },'ephemeral single-file open failed',);- dialog.showErrorBox(+ showErrorOnFocusedWindowOrNavigator('Could not open file',`${filePath}\n\n${err instanceof Error ? err.message : String(err)}`,);- if (BrowserWindow.getAllWindows().length === 0) {- openNavigator();- }}}@@ -2433,7 +2425,7 @@ async function runMenuDispatchCommand(openNavigator();return;case 'open-folder-dialog': {- const picked = await promptForExistingFolder(dialog);+ const picked = await promptForExistingFolder(dialog, { errorParent: dialogParentWindow });if (picked) await openProjectOrFallbackToNavigator(picked, 'pick-existing');return;}@@ -2481,6 +2473,7 @@ async function runApplicationMenuRefresh(): Promise<void> {showDevToolsMenu: !app.isPackaged || DESKTOP_VARIANT.name !== 'stable',terminalCapable: isTerminalAvailable(),dialog,+ errorDialogParent: dialogParentWindow,openNavigator,openProject: async (path, entryPoint) => {await openProjectOrFallbackToNavigator(path, entryPoint);@@ -2584,8 +2577,49 @@ function desktopSelfUninstallAvailable(): boolean {return appBundlePath !== null && isSupportedApplicationsBundle(appBundlePath, osHomedir());}+function dialogParentWindow(): BrowserWindow | null {+ return (+ BrowserWindow.getFocusedWindow() ??+ BrowserWindow.getAllWindows().find((w) => !w.isDestroyed()) ??+ null+ );+}++function showErrorOnFocusedWindow(title: string, body: string): void {+ void showErrorDialog(dialog, dialogParentWindow(), title, body);+}++function showErrorOverNavigator(title: string, body: string): void {+ try {+ openNavigator();+ } catch (err) {+ getLogger('navigator').error({ err, title }, 'navigator failed to open to report an error');+ showErrorOnFocusedWindow(title, body);+ return;+ }+ void showErrorDialogOnceVisible(+ dialog,+ navigatorWindow as unknown as BrowserWindow | null,+ title,+ body,+ {+ setTimeout: (cb, ms) => setTimeout(cb, ms),+ clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+ timeoutMs: RESTORE_REVEAL_TIMEOUT_MS,+ },+ );+}++function showErrorOnFocusedWindowOrNavigator(title: string, body: string): void {+ if (BrowserWindow.getAllWindows().length === 0) {+ showErrorOverNavigator(title, body);+ } else {+ showErrorOnFocusedWindow(title, body);+ }+}+async function showMessageBoxAttached(options: MessageBoxOptions) {- const target = BrowserWindow.getFocusedWindow();+ const target = dialogParentWindow();return target ? dialog.showMessageBox(target, options) : dialog.showMessageBox(options);}@@ -3651,7 +3685,7 @@ function reconfigureMcpWiringNow(target: McpWiringDispatchTarget | undefined): b} catch (err) {const message = err instanceof Error ? err.message : String(err);console.error('[main] reconfigureMcpWiring failed', { err: message });- dialog.showErrorBox(+ showErrorOnFocusedWindow('Set up OpenKnowledge integrations failed',`OpenKnowledge couldn't re-arm the MCP consent dialog:\n\n${message}`,);@@ -4125,11 +4159,13 @@ function registerIpcHandlers() {});handle('ok:dialog:open-folder', async (_event, opts) => {- return promptForExistingFolder(dialog, opts);+ return promptForExistingFolder(dialog, { ...opts, errorParent: dialogParentWindow });});handle('ok:project:open-file-picker', async () => {- const picked = await promptForExistingMarkdownFile(dialog);+ const picked = await promptForExistingMarkdownFile(dialog, {+ errorParent: dialogParentWindow,+ });if (picked) await openEphemeralFile(picked);return undefined;});diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.tsindex c7ab88b63..46c48a6c6 100644--- a/packages/desktop/src/main/menu.ts+++ b/packages/desktop/src/main/menu.ts@@ -15,7 +15,7 @@ import {SHOW_INSTALL_SKILL,type TerminalPlacement,} from '@inkeep/open-knowledge-core';-import type { Dialog, MenuItemConstructorOptions } from 'electron';+import type { BrowserWindow, Dialog, MenuItemConstructorOptions } from 'electron';import type { EntryPoint } from '../shared/entry-point.ts';import type { EditorActiveTargetSnapshot } from '../shared/ipc-channels.ts';import { promptForExistingFolder, promptForExistingMarkdownFile } from './dialog-helpers.ts';@@ -28,6 +28,7 @@ export interface MenuDeps {showDevToolsMenu: boolean;terminalCapable: boolean;dialog: Dialog;+ errorDialogParent(): BrowserWindow | null;openNavigator(): void;openProject(projectPath: string, entryPoint: EntryPoint): Promise<void>;openEphemeralFile?(filePath: string): Promise<void>;@@ -192,7 +193,7 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {'switch-project': { click: (d) => () => d.openNavigator() },'open-folder': {click: (d) => async () => {- const picked = await promptForExistingFolder(d.dialog);+ const picked = await promptForExistingFolder(d.dialog, { errorParent: d.errorDialogParent });if (picked) {await d.openProject(picked, 'pick-existing');}@@ -200,7 +201,9 @@ const MENU_BINDINGS: Record<string, MenuCommandBinding> = {},'open-file': {click: (d) => async () => {- const picked = await promptForExistingMarkdownFile(d.dialog);+ const picked = await promptForExistingMarkdownFile(d.dialog, {+ errorParent: d.errorDialogParent,+ });if (picked) {await d.openEphemeralFile?.(picked);}diff --git a/packages/desktop/src/main/restore-focus.test.ts b/packages/desktop/src/main/restore-focus.test.tsindex 86fbf83b5..4a1ae2e19 100644--- a/packages/desktop/src/main/restore-focus.test.ts+++ b/packages/desktop/src/main/restore-focus.test.ts@@ -37,25 +37,28 @@ function makeTimers(timeoutMs = 8_000): {interface FakeWindow extends RevealableWindow {emitShow: () => void;+ emitRestore: () => 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> = [];+ const listeners = { show: [] as Array<() => void>, restore: [] as Array<() => void> };+ const emit = (event: 'show' | 'restore') => {+ visible = true;+ const snapshot = [...listeners[event]];+ listeners[event].length = 0;+ for (const l of snapshot) l();+ };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();+ once: (event, listener) => {+ listeners[event].push(listener);},+ emitShow: () => emit('show'),+ emitRestore: () => emit('restore'),destroy: () => {destroyed = true;},@@ -119,6 +122,21 @@ describe('whenWindowRevealed', () => {expect(pending()).toBe(0);});+ test('resolves when a minimized window is restored, and clears the safety timer', async () => {+ const { deps, pending } = makeTimers();+ const win = makeWindow();+ let resolved = false;+ const p = whenWindowRevealed(win, deps).then(() => {+ resolved = true;+ });+ await flush();+ expect(resolved).toBe(false);+ win.emitRestore();+ 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();diff --git a/packages/desktop/src/main/restore-focus.ts b/packages/desktop/src/main/restore-focus.tsindex 61802f349..1a8498b17 100644--- a/packages/desktop/src/main/restore-focus.ts+++ b/packages/desktop/src/main/restore-focus.ts@@ -9,7 +9,7 @@ export function shouldRevealInactiveNow(state: {export interface RevealableWindow {isDestroyed?(): boolean;isVisible?(): boolean;- once(event: 'show', listener: () => void): void;+ once(event: 'show' | 'restore', listener: () => void): void;}export interface RestoreFocusDeps {@@ -35,6 +35,7 @@ export function whenWindowRevealed(win: RevealableWindow, deps: RestoreFocusDeps};const handle = deps.setTimeout(finish, deps.timeoutMs);win.once('show', finish);+ win.once('restore', finish);});}diff --git a/packages/desktop/tests/main/menu-localization.test.ts b/packages/desktop/tests/main/menu-localization.test.tsindex 9397a0e8b..3b4e9bf72 100644--- a/packages/desktop/tests/main/menu-localization.test.ts+++ b/packages/desktop/tests/main/menu-localization.test.ts@@ -11,6 +11,7 @@ function makeDeps(overrides: Partial<MenuDeps> = {}): MenuDeps {showDevToolsMenu: true,terminalCapable: true,dialog: {} as Dialog,+ errorDialogParent: () => null,openNavigator: vi.fn(),openProject: vi.fn(async () => {}),getRecentProjects: () => [],diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.tsindex 7f4e17640..1c915c7ef 100644--- a/packages/desktop/tests/main/menu.test.ts+++ b/packages/desktop/tests/main/menu.test.ts@@ -13,6 +13,7 @@ function makeDeps(overrides: Partial<MenuDeps> = {}): MenuDeps {showDevToolsMenu: true,terminalCapable: true,dialog: {} as MenuDeps['dialog'],+ errorDialogParent: () => null,openNavigator: vi.fn(() => {}),openProject: vi.fn(() => Promise.resolve()),getRecentProjects: vi.fn(() => []),@@ -129,15 +130,15 @@ describe('buildMenuTemplate', () => {test('File → Open folder reports a picker that closes without a folder', async () => {const openProject = vi.fn(() => Promise.resolve());const showOpenDialog = vi.fn(() => Promise.resolve({ canceled: false, filePaths: [] }));- const showErrorBox = vi.fn();+ const showMessageBox = vi.fn(() => Promise.resolve({ response: 0, checkboxChecked: false }));const deps = makeDeps({openProject,- dialog: { showOpenDialog, showErrorBox } as unknown as MenuDeps['dialog'],+ dialog: { showOpenDialog, showMessageBox } as unknown as MenuDeps['dialog'],});const template = buildMenuTemplate(deps);const openFolder = findByLabel(template, 'Open folder…');await (openFolder?.click as (() => Promise<void>) | undefined)?.();- expect(showErrorBox).toHaveBeenCalledTimes(1);+ expect(showMessageBox).toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));expect(openProject).not.toHaveBeenCalled();});diff --git a/packages/desktop/tests/smoke/_helpers/platform-gate.ts b/packages/desktop/tests/smoke/_helpers/platform-gate.tsindex 8ea74a08d..4afafd82f 100644--- a/packages/desktop/tests/smoke/_helpers/platform-gate.ts+++ b/packages/desktop/tests/smoke/_helpers/platform-gate.ts@@ -34,7 +34,7 @@ export const SPEC_PLATFORM_GATES = {'external-link.e2e.ts': ['!DARWIN'],'liveness-watchdog.e2e.ts': ['!PLATFORM_SUPPORTED'],'mcp-wiring.e2e.ts': ['!PLATFORM_SUPPORTED', 'WINDOWS', "WINDOWS || TARGET.mode === 'packaged'"],- 'navigator-close-on-open.e2e.ts': ['!PLATFORM_SUPPORTED'],+ 'navigator-close-on-open.e2e.ts': ['!PLATFORM_SUPPORTED', 'WINDOWS'],'navigator-return.e2e.ts': ['!PLATFORM_SUPPORTED', 'DARWIN'],'note-window.e2e.ts': ['!PLATFORM_SUPPORTED', '!DARWIN'],'okf-rule-toggle.e2e.ts': ['!DARWIN'],diff --git a/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts b/packages/desktop/tests/smoke/navigator-close-on-open.e2e.tsindex f09eb8609..05545a427 100644--- a/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts+++ b/packages/desktop/tests/smoke/navigator-close-on-open.e2e.ts@@ -1,6 +1,7 @@+import { once } from 'node:events';import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { join, parse } from 'node:path';import type { ElectronApplication, Page } from '@playwright/test';import { _electron as electron } from '@playwright/test';import { configureDesktopGitRepositories } from '../support/git-fixture.test-helper.ts';@@ -15,6 +16,7 @@ import { findProjectEditorWindow } from './_helpers/project-editor-window';import { expect, test } from './_helpers/smoke-test';const TARGET = resolveDesktopTarget();+const WINDOWS = process.platform === 'win32';interface SeededHome {tmpHome: string;@@ -128,6 +130,68 @@ async function findFirstWindowByMode(throw new Error(`${mode} window vanished between poll resolution and read`);}+interface RecordedErrorDialog {+ title: string | undefined;+ parentWindowId: number | null;+ parentVisible: boolean | null;+}++async function recordErrorDialogs(+ app: ElectronApplication,+ { acknowledge }: { acknowledge: boolean } = { acknowledge: true },+): Promise<void> {+ await app.evaluate(({ BrowserWindow, dialog }, acknowledgeDialogs) => {+ const recorded: RecordedErrorDialog[] = [];+ Reflect.set(globalThis, '__okRecordedErrorDialogs', recorded);+ const original = dialog.showMessageBox.bind(dialog);+ const recording = (+ ...args: [Electron.MessageBoxOptions] | [Electron.BrowserWindow, Electron.MessageBoxOptions]+ ) => {+ const [first, second] = args;+ const parent = first instanceof BrowserWindow ? first : null;+ const options = (parent === null ? first : second) as Electron.MessageBoxOptions;+ if (options.type !== 'error') {+ return parent === null ? original(options) : original(parent, options);+ }+ recorded.push({+ title: options.title,+ parentWindowId: parent?.id ?? null,+ parentVisible: parent?.isVisible() ?? null,+ });+ return acknowledgeDialogs+ ? Promise.resolve({ response: 0, checkboxChecked: false })+ : new Promise<Electron.MessageBoxReturnValue>(() => {});+ };+ dialog.showMessageBox = recording as typeof dialog.showMessageBox;+ }, acknowledge);+}++async function readRecordedErrorDialogs(app: ElectronApplication): Promise<RecordedErrorDialog[]> {+ return app.evaluate(+ () => (Reflect.get(globalThis, '__okRecordedErrorDialogs') ?? []) as RecordedErrorDialog[],+ );+}++async function windowIds(app: ElectronApplication): Promise<number[]> {+ return app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().map((w) => w.id));+}++async function onlyWindowId(app: ElectronApplication): Promise<number> {+ const ids = await windowIds(app);+ expect(ids).toHaveLength(1);+ return ids[0] as number;+}++async function openFromNavigator(navigator: Page, path: string): Promise<void> {+ await navigator.evaluate(async (target) => {+ await window.okDesktop?.project.open({+ path: target,+ target: 'new-window',+ entryPoint: 'pick-existing',+ });+ }, path);+}+test.describe('Project Navigator close-on-project-open smoke', () => {test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');test.skip(!PLATFORM_SUPPORTED, PLATFORM_SKIP_REASON);@@ -241,19 +305,7 @@ test.describe('Project Navigator close-on-project-open smoke', () => {.toBe(1);const navigator = await findFirstWindowByMode(app, 'navigator');- await app.evaluate(({ dialog }) => {- const wrapped = dialog as unknown as {- __showErrorBoxCalls?: number;- __lastErrorTitle?: string;- showErrorBox: (t: string, c: string) => void;- };- wrapped.__showErrorBoxCalls = 0;- wrapped.__lastErrorTitle = undefined;- wrapped.showErrorBox = (title) => {- wrapped.__showErrorBoxCalls = (wrapped.__showErrorBoxCalls ?? 0) + 1;- wrapped.__lastErrorTitle = title;- };- });+ await recordErrorDialogs(app);await navigator.evaluate(async (path) => {await window.okDesktop?.project.open({@@ -271,17 +323,138 @@ test.describe('Project Navigator close-on-project-open smoke', () => {.toBe(0);expect(await countWindowsByMode(app, 'navigator')).toBe(1);- const dialogState = await app.evaluate(({ dialog }) => {- const wrapped = dialog as unknown as {- __showErrorBoxCalls?: number;- __lastErrorTitle?: string;- };- return {- calls: wrapped.__showErrorBoxCalls ?? 0,- title: wrapped.__lastErrorTitle,- };+ const navigatorWindowId = await onlyWindowId(app);+ expect(await readRecordedErrorDialogs(app)).toContainEqual({+ title: 'Cannot open this folder',+ parentWindowId: navigatorWindowId,+ parentVisible: true,});- expect(dialogState.calls).toBeGreaterThan(0);- expect(dialogState.title).toBe('Cannot open this folder');+ });++ test('A refusal sent from an editor attaches its dialog to the Navigator once it is visible', async ({+ captureStderrFor,+ }) => {+ const { tmpHome, projectAPath, projectBPath } =+ seedHomeWithLastOpenedProjectAndExtra('refused-editor');+ const app = await launchApp(tmpHome);+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectAPath, projectBPath] });++ await expect+ .poll(() => countWindowsByMode(app, 'editor'), {+ timeout: 30_000,+ message: 'Editor A did not appear from lastOpenedProject',+ })+ .toBe(1);+ const editor = await findFirstWindowByMode(app, 'editor');+ expect(await countWindowsByMode(app, 'navigator')).toBe(0);+ await configureDesktopGitRepositories(editor, projectAPath);+ const editorWindowIds = await windowIds(app);+ await recordErrorDialogs(app);++ await editor.evaluate(async (target) => {+ await window.okDesktop?.project.open({+ path: target,+ target: 'new-window',+ entryPoint: 'pick-existing',+ });+ }, tmpHome);++ await expect+ .poll(() => countWindowsByMode(app, 'navigator'), {+ timeout: 15_000,+ message: 'the refusal did not open the Navigator',+ })+ .toBe(1);+ const navigatorWindowIds = (await windowIds(app)).filter((id) => !editorWindowIds.includes(id));+ expect(navigatorWindowIds).toHaveLength(1);+ await expect+ .poll(() => readRecordedErrorDialogs(app), {+ timeout: 15_000,+ message: 'the refusal dialog was not shown over the Navigator',+ })+ .toEqual([+ {+ title: 'Cannot open this folder',+ parentWindowId: navigatorWindowIds[0],+ parentVisible: true,+ },+ ]);+ expect(editor.isClosed()).toBe(false);+ });++ test('Refusing the home directory or a drive root leaves the Navigator usable', async ({+ captureStderrFor,+ }) => {+ const { tmpHome, projectDir } = seedHomeWithoutLastOpenedProject('refused');+ const app = await launchApp(tmpHome);+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });++ await expect+ .poll(() => countWindowsByMode(app, 'navigator'), {+ timeout: 20_000,+ message: 'navigator window did not appear at cold boot',+ })+ .toBe(1);+ const navigator = await findFirstWindowByMode(app, 'navigator');+ const navigatorWindowId = await onlyWindowId(app);+ await recordErrorDialogs(app);++ await openFromNavigator(navigator, tmpHome);+ await openFromNavigator(navigator, parse(tmpHome).root);++ expect(await countWindowsByMode(app, 'editor')).toBe(0);+ const refusal = {+ title: 'Cannot open this folder',+ parentWindowId: navigatorWindowId,+ parentVisible: true,+ };+ expect(await readRecordedErrorDialogs(app)).toEqual([refusal, refusal]);++ await openFromNavigator(navigator, projectDir);+ await expect+ .poll(() => countWindowsByMode(app, 'editor'), {+ timeout: 30_000,+ message: 'a valid project did not open after the refusals',+ })+ .toBe(1);+ const editor = await findProjectEditorWindow(app, projectDir);+ if (!editor) throw new Error('project editor did not open');+ await configureDesktopGitRepositories(editor, projectDir);+ });++ test('The app quits on SIGTERM while the home-directory refusal is still open', async ({+ captureStderrFor,+ }) => {+ test.skip(+ WINDOWS,+ 'Windows has no SIGTERM: ChildProcess.kill terminates the process whatever the app does.',+ );+ const { tmpHome, projectDir } = seedHomeWithoutLastOpenedProject('refused-sigterm');+ const app = await launchApp(tmpHome);+ captureStderrFor(app, { home: tmpHome, cleanupDirs: [tmpHome, projectDir] });++ await expect+ .poll(() => countWindowsByMode(app, 'navigator'), {+ timeout: 20_000,+ message: 'navigator window did not appear at cold boot',+ })+ .toBe(1);+ const navigator = await findFirstWindowByMode(app, 'navigator');+ await recordErrorDialogs(app, { acknowledge: false });+ await openFromNavigator(navigator, tmpHome);+ expect(await readRecordedErrorDialogs(app)).toHaveLength(1);++ const main = app.process();+ const exited = once(main, 'exit');+ main.kill('SIGTERM');+ let timer: ReturnType<typeof setTimeout> | undefined;+ const outcome = await Promise.race([+ exited.then(() => 'exited'),+ new Promise((resolve) => {+ timer = setTimeout(() => resolve('still running'), 20_000);+ }),+ ]);+ clearTimeout(timer);+ expect(outcome).toBe('exited');});});