Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(open-knowledge): WYSIWYG external links open in-app window instead of OS browser (#617) (#2624)

Nick Gomezf5dd24bd74bc
diff --git a/.changeset/external-link-desktop-bridge.md b/.changeset/external-link-desktop-bridge.md
new file mode 100644
index 000000000..cdf131254
--- /dev/null
+++ b/.changeset/external-link-desktop-bridge.md
@@ -0,0 +1,12 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+External links now reliably open in your OS default browser on desktop.
+Clicking an http(s) link in the visual editor, source mode, or a wiki-link
+chip previously could open another Open Knowledge window rendering the page
+— most visibly in windows created after a server restart. Link clicks now
+route straight through the desktop bridge, and the window-level safety net
+is attached to every editor window (including the server-restart recreate
+path), so external URLs land in your browser everywhere. Web behavior is
+unchanged (links still open in a new tab).
diff --git a/packages/app/src/components/GraphPanel.tsx b/packages/app/src/components/GraphPanel.tsx
index 8ef386007..69fad6c14 100644
--- a/packages/app/src/components/GraphPanel.tsx
+++ b/packages/app/src/components/GraphPanel.tsx
@@ -400,6 +400,8 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
actionLabel: t`Open link`,
secondaryLabel: selectedNode.url,
onAction: () => {
+ // openExternalUrl gates unsafe schemes internally (a node URL can
+ // carry any authored scheme), then routes to the OS browser / new tab.
openExternalUrl(selectedNode.url);
setIsExpanded(false);
},
diff --git a/packages/app/src/components/GraphView.tsx b/packages/app/src/components/GraphView.tsx
index a6fe53867..f3376b84a 100644
--- a/packages/app/src/components/GraphView.tsx
+++ b/packages/app/src/components/GraphView.tsx
@@ -414,6 +414,8 @@ function applyGraphNodeClick({
const action = resolveGraphNodeClickAction(node, docClickBehavior);
if (action.kind === 'external') {
+ // openExternalUrl gates unsafe schemes internally (a graph node URL can
+ // carry any authored scheme), then routes to the OS browser / new tab.
openExternalUrl(action.url);
return;
}
@@ -1191,6 +1193,8 @@ export function GraphView({
showPointerCursor={(obj) => Boolean(obj && 'kind' in obj)}
onNodeClick={(node: NodeObject<GraphNode>) => {
if (node.kind === 'external') {
+ // openExternalUrl gates unsafe schemes internally (a node URL can
+ // carry any authored scheme), then routes to the OS browser / new tab.
openExternalUrl(node.url);
return;
}
diff --git a/packages/app/src/editor/extensions/internal-link.external-open.test.ts b/packages/app/src/editor/extensions/internal-link.external-open.test.ts
new file mode 100644
index 000000000..86bfa4951
--- /dev/null
+++ b/packages/app/src/editor/extensions/internal-link.external-open.test.ts
@@ -0,0 +1,175 @@
+/**
+ * RED regression tests for inkeep/open-knowledge#617 — WYSIWYG external-link
+ * chips must reach the OS default browser, not a child OpenKnowledge window.
+ *
+ * Contract under test: activating an external (`http(s)://`) link chip routes
+ * through the desktop bridge (`window.okDesktop.shell.openExternal`) when it is
+ * present, exactly as the graph view does (`openExternalUrl` in
+ * `lib/external-link.ts`), and falls back to `window.open` only on web (no
+ * bridge). Today `internal-link.ts`'s `handlePrimary` `case 'external'` calls
+ * `openHashHrefInNewTab` → `window.open(url, '_blank', …)` UNCONDITIONALLY: on
+ * the Electron desktop that `window.open` becomes a new in-app BrowserWindow
+ * that renders the page (the bug), because it relies on a main-process
+ * `setWindowOpenHandler` net that isn't attached on every window.
+ *
+ * Seam: the REAL `handlePrimary` closure is reached the way the InteractionLayer
+ * reaches it in production — via the layer registration the chip installs
+ * (`getInteractionLayer(editor).getRegistration(id).handlePrimary(...)`). No
+ * mock of the routing decision: a real Editor with the real `InternalLink`
+ * extension classifies a real external link mark and runs the real branch. The
+ * only doubles are the two external boundaries the decision targets —
+ * `window.okDesktop.shell.openExternal` (Electron preload bridge) and
+ * `window.open` (browser new-window API).
+ *
+ * Substrate: jsdom via the shared walk-currency harness (`installDomGlobals`),
+ * the same per-file DOM install the other headless editor-plugin suites use.
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { Editor } from '@tiptap/core';
+import { TextSelection } from '@tiptap/pm/state';
+import StarterKit from '@tiptap/starter-kit';
+import { getInteractionLayer } from '../interaction-layer-host';
+import { installDomGlobals } from '../walk-currency-test-harness';
+import { InternalLink } from './internal-link';
+import { markIdentityKey } from './mark-identity';
+
+let restoreDomGlobals: (() => void) | null = null;
+
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+});
+
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
+
+type OpenExternalBridge = { shell?: { openExternal?: (url: string) => Promise<void> } };
+
+interface OpenExternalWindow {
+ okDesktop?: OpenExternalBridge;
+ open: (url?: string, target?: string, features?: string) => unknown;
+}
+
+function testWindow(): OpenExternalWindow {
+ return globalThis.window as unknown as OpenExternalWindow;
+}
+
+const liveEditors = new Set<Editor>();
+
+afterEach(() => {
+ for (const editor of liveEditors) editor.destroy();
+ liveEditors.clear();
+ // Drop the injected bridge; restore the jsdom stub `window.open` so a leaked
+ // reference from one case can't satisfy another's assertion.
+ const w = testWindow();
+ delete w.okDesktop;
+});
+
+/**
+ * Mount a real editor whose sole `link` mark is the production `InternalLink`
+ * extension (we do NOT use the `mountLightEditor` rig here: it bundles
+ * `LinkFidelity`, and `InternalLink` extends `LinkFidelity`, so both would
+ * define a `link` mark and collide). Returns an `activate` that invokes the
+ * real chip primary-action closure through the InteractionLayer registration —
+ * the same entry point the layer's click / Enter handler calls.
+ */
+function mountWithExternalLink(url: string): {
+ editor: Editor;
+ activate: (newTab: boolean) => boolean | undefined;
+} {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content: `<p><a href="${url}">go</a></p>`,
+ extensions: [
+ StarterKit.configure({ link: false }),
+ InternalLink.configure({ docName: 'notes/test' }),
+ ],
+ });
+ liveEditors.add(editor);
+
+ // Force one view update so `markIdentityPlugin`'s view lifecycle fires
+ // `onRegister` → `layer.register(...)`. `state.init` already populated `byId`,
+ // but the registration (which carries `handlePrimary`) lands on the first
+ // `update`. A selection-only transaction (`docChanged === false`) triggers it
+ // without mutating the doc.
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1)));
+
+ const idState = markIdentityKey.getState(editor.state);
+ const nodeId = [...(idState?.byId.keys() ?? [])][0];
+ if (nodeId === undefined) {
+ throw new Error('setup: no link mark id — external link was not parsed into a link mark');
+ }
+ const layer = getInteractionLayer(editor);
+ const registration = layer.getRegistration(nodeId);
+ if (!registration?.handlePrimary) {
+ throw new Error('setup: chip did not register a handlePrimary hook with the InteractionLayer');
+ }
+ return {
+ editor,
+ activate: (newTab) => registration.handlePrimary?.({ nodeId, type: 'link', newTab }),
+ };
+}
+
+describe('WYSIWYG external-link activation — desktop (bridge present)', () => {
+ test('bare click routes to the OS browser via okDesktop.shell.openExternal, NOT window.open', () => {
+ const url = 'https://youtube.com/watch?v=abc';
+ const openExternal = mock(async (_url: string) => {});
+ const openWindow = mock(() => null);
+ const w = testWindow();
+ w.okDesktop = { shell: { openExternal } };
+ w.open = openWindow as unknown as OpenExternalWindow['open'];
+
+ const { activate } = mountWithExternalLink(url);
+ const handled = activate(false);
+
+ expect(handled).toBe(true);
+ // RED today: `case 'external'` calls `window.open` unconditionally, so the
+ // desktop bridge is never reached.
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(openExternal).toHaveBeenCalledWith(url);
+ // RED today: the bug IS that a new in-app window opens.
+ expect(openWindow).not.toHaveBeenCalled();
+ });
+
+ test('Cmd/Ctrl+click (new-tab gesture) also reaches the OS browser, NOT a child window', () => {
+ // External URLs must land in the OS browser on EVERY activation — bare or
+ // modifier-click. The modifier path must not fall back to window.open.
+ const url = 'https://example.com/path';
+ const openExternal = mock(async (_url: string) => {});
+ const openWindow = mock(() => null);
+ const w = testWindow();
+ w.okDesktop = { shell: { openExternal } };
+ w.open = openWindow as unknown as OpenExternalWindow['open'];
+
+ const { activate } = mountWithExternalLink(url);
+ activate(true);
+
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(openExternal).toHaveBeenCalledWith(url);
+ expect(openWindow).not.toHaveBeenCalled();
+ });
+});
+
+describe('WYSIWYG external-link activation — web (no bridge)', () => {
+ // Regression pin (green today AND after the fix): on web there is no desktop
+ // bridge, so external links keep the `window.open` new-tab behavior. Guards
+ // the fix from regressing the web path to a no-op.
+ test('bare click falls back to window.open with the new-tab + noopener features', () => {
+ const url = 'https://example.com/web';
+ const openWindow = mock(() => null);
+ const w = testWindow();
+ delete w.okDesktop;
+ w.open = openWindow as unknown as OpenExternalWindow['open'];
+
+ const { activate } = mountWithExternalLink(url);
+ const handled = activate(false);
+
+ expect(handled).toBe(true);
+ expect(openWindow).toHaveBeenCalledTimes(1);
+ expect(openWindow).toHaveBeenCalledWith(url, '_blank', 'noopener,noreferrer');
+ });
+});
diff --git a/packages/app/src/editor/extensions/internal-link.ts b/packages/app/src/editor/extensions/internal-link.ts
index 7ea2238f7..bbe6423c8 100644
--- a/packages/app/src/editor/extensions/internal-link.ts
+++ b/packages/app/src/editor/extensions/internal-link.ts
@@ -43,10 +43,10 @@ import {
} from '@inkeep/open-knowledge-core';
import { type Editor, mergeAttributes } from '@tiptap/core';
import { createElement } from 'react';
+import { openExternalUrl } from '@/lib/external-link';
import { resolveLinkTargetIntent } from '../../components/link-target-intent';
import {
activateAssetLink,
- openHashHrefInNewTab,
openInternalHashHrefInNewTab,
toInternalHashHref,
} from '../internal-link-helpers';
@@ -219,15 +219,18 @@ export const InternalLink = LinkFidelity.extend<InternalLinkOptions>({
}
return true;
case 'external':
- // Refuse javascript:/data:/etc via scheme allowlist.
- // Fall through if unsafe so the PropPanel surfaces the URL for
- // the author to edit. External links ALWAYS open in a new tab —
- // bare-click on cross-origin content shouldn't navigate away
- // from the editor (both branches end up calling
- // `openHashHrefInNewTab`, just routed for symmetry with the
- // doc/anchor branches above).
+ // External links route through the desktop bridge
+ // (`openExternalUrl`) so a click reaches the OS default browser
+ // instead of Electron's default new-window (which renders the page
+ // in an in-app child BrowserWindow). Symmetric with the graph view;
+ // on web it falls back to `window.open(url, '_blank', …)`.
+ //
+ // `openExternalUrl` refuses unsafe schemes internally, so this gate
+ // is for CONTROL FLOW, not security: an unsafe href returns false so
+ // the chip's primary handler falls through and the PropPanel surfaces
+ // the URL for the author to edit (rather than silently no-opening).
if (!isSafeNavigationUrl(target.url)) return false;
- openHashHrefInNewTab(target.url);
+ openExternalUrl(target.url);
return true;
default:
return assertNeverLinkTarget(target);
diff --git a/packages/app/src/editor/extensions/wiki-link.external-open.test.ts b/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
new file mode 100644
index 000000000..e3bede9cf
--- /dev/null
+++ b/packages/app/src/editor/extensions/wiki-link.external-open.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Regression pins for inkeep/open-knowledge#617 — the WYSIWYG `[[wikilink]]`
+ * external branch must reach the OS default browser, symmetric with the
+ * markdown-link chip (`internal-link.external-open.test.ts`).
+ *
+ * Contract: activating a `[[https://…]]` chip routes through the desktop bridge
+ * (`window.okDesktop.shell.openExternal`) when present, and falls back to
+ * `window.open` on web (no bridge). The routing code is real — a mounted Editor
+ * with the production `WikiLink` NodeView classifies a real external wiki-link
+ * target and runs the real `handlePrimary` external branch, reached the way the
+ * InteractionLayer reaches it in production
+ * (`getRegistration(nodeId).handlePrimary(...)`). The only doubles are the two
+ * external boundaries the decision targets (`okDesktop.shell.openExternal`,
+ * `window.open`).
+ */
+
+import { afterAll, afterEach, beforeAll, describe, expect, mock, test } from 'bun:test';
+import { Editor } from '@tiptap/core';
+import { TextSelection } from '@tiptap/pm/state';
+import StarterKit from '@tiptap/starter-kit';
+import { getInteractionLayer } from '../interaction-layer-host';
+import { installDomGlobals } from '../walk-currency-test-harness';
+import { WikiLink } from './wiki-link';
+
+let restoreDomGlobals: (() => void) | null = null;
+
+beforeAll(() => {
+ restoreDomGlobals = installDomGlobals();
+});
+
+afterAll(() => {
+ restoreDomGlobals?.();
+ restoreDomGlobals = null;
+});
+
+type OpenExternalBridge = { shell?: { openExternal?: (url: string) => Promise<void> } };
+
+interface OpenExternalWindow {
+ okDesktop?: OpenExternalBridge;
+ open: (url?: string, target?: string, features?: string) => unknown;
+}
+
+function testWindow(): OpenExternalWindow {
+ return globalThis.window as unknown as OpenExternalWindow;
+}
+
+const liveEditors = new Set<Editor>();
+
+afterEach(() => {
+ for (const editor of liveEditors) editor.destroy();
+ liveEditors.clear();
+ delete testWindow().okDesktop;
+});
+
+/**
+ * Mount a real editor with the production `WikiLink` NodeView holding a single
+ * external `[[url]]` chip, and return an `activate` that invokes the real chip
+ * primary-action closure through the InteractionLayer registration.
+ */
+function mountWithExternalWikiLink(url: string): {
+ editor: Editor;
+ activate: (newTab: boolean) => boolean | undefined;
+} {
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const editor = new Editor({
+ element: host,
+ content: `<p><span data-wiki-link data-target="${url}"></span></p>`,
+ extensions: [StarterKit, WikiLink.configure({ docName: 'notes/test' })],
+ });
+ liveEditors.add(editor);
+
+ // Force a view update so the NodeView's InteractionLayer registration settles.
+ // Position 1 is inside the paragraph's inline content (before the atom chip).
+ editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 1)));
+
+ const chip = host.querySelector('[data-node-id]');
+ const nodeId = chip?.getAttribute('data-node-id') ?? undefined;
+ if (nodeId === undefined) {
+ throw new Error(
+ 'setup: no wiki-link chip — external target was not parsed into a wikiLink node',
+ );
+ }
+ const registration = getInteractionLayer(editor).getRegistration(nodeId);
+ if (!registration?.handlePrimary) {
+ throw new Error('setup: wiki-link chip did not register a handlePrimary hook');
+ }
+ return {
+ editor,
+ activate: (newTab) => registration.handlePrimary?.({ nodeId, type: 'wikiLink', newTab }),
+ };
+}
+
+describe('WYSIWYG wiki-link external activation — desktop (bridge present)', () => {
+ test('bare click routes to the OS browser via okDesktop.shell.openExternal, NOT window.open', () => {
+ const url = 'https://youtube.com/watch?v=abc';
+ const openExternal = mock(async (_url: string) => {});
+ const openWindow = mock(() => null);
+ const w = testWindow();
+ w.okDesktop = { shell: { openExternal } };
+ w.open = openWindow as unknown as OpenExternalWindow['open'];
+
+ const { activate } = mountWithExternalWikiLink(url);
+ const handled = activate(false);
+
+ expect(handled).toBe(true);
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(openExternal).toHaveBeenCalledWith(url);
+ expect(openWindow).not.toHaveBeenCalled();
+ });
+});
+
+describe('WYSIWYG wiki-link external activation — web (no bridge)', () => {
+ test('bare click falls back to window.open with the new-tab + noopener features', () => {
+ const url = 'https://example.com/web';
+ const openWindow = mock(() => null);
+ const w = testWindow();
+ delete w.okDesktop;
+ w.open = openWindow as unknown as OpenExternalWindow['open'];
+
+ const { activate } = mountWithExternalWikiLink(url);
+ const handled = activate(false);
+
+ expect(handled).toBe(true);
+ expect(openWindow).toHaveBeenCalledTimes(1);
+ expect(openWindow).toHaveBeenCalledWith(url, '_blank', 'noopener,noreferrer');
+ });
+});
diff --git a/packages/app/src/editor/extensions/wiki-link.ts b/packages/app/src/editor/extensions/wiki-link.ts
index 7af3ae9d2..9608299ef 100644
--- a/packages/app/src/editor/extensions/wiki-link.ts
+++ b/packages/app/src/editor/extensions/wiki-link.ts
@@ -19,6 +19,7 @@
*/
import { WikiLink as BaseWikiLink, classifyWikiLinkTarget } from '@inkeep/open-knowledge-core';
import { createElement } from 'react';
+import { openExternalUrl } from '@/lib/external-link';
import { resolveLinkTargetIntent } from '../../components/link-target-intent';
import { type ResolvedPageIcon, resolvePageIcon } from '../../components/page-header-utils';
import { hashFromAssetPath } from '../../lib/doc-hash';
@@ -306,10 +307,13 @@ export const WikiLink = BaseWikiLink.extend<{ docName: string }>({
}
return true;
}
- // external — refuse unsafe schemes. Always
- // open in a new tab regardless of bare-click vs Cmd-click.
+ // external — route through the desktop bridge so a click reaches the
+ // OS default browser instead of an in-app child window (web falls back
+ // to window.open). openExternalUrl gates unsafe schemes internally; this
+ // gate is for control flow — an unsafe href returns false so the chip
+ // falls through to its edit affordance instead of silently no-opening.
if (!isSafeNavigationUrl(classified.url)) return false;
- openHashHrefInNewTab(classified.url);
+ openExternalUrl(classified.url);
return true;
};
layer.register({
diff --git a/packages/app/src/editor/internal-link-helpers.test.ts b/packages/app/src/editor/internal-link-helpers.test.ts
index 8e93b3bfc..ea4112a5d 100644
--- a/packages/app/src/editor/internal-link-helpers.test.ts
+++ b/packages/app/src/editor/internal-link-helpers.test.ts
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, mock } from 'bun:test';
import {
activateAssetLink,
handleChipLinkClick,
+ navigateToMarkdownTarget,
toInternalHashHref,
} from './internal-link-helpers';
@@ -135,6 +136,70 @@ describe('activateAssetLink', () => {
});
});
+/**
+ * External-link routing for the source-mode markdown-link path
+ * (`md-link-source.ts` → `navigateToMarkdownTarget`). Mirrors the WYSIWYG
+ * `internal-link.external-open.test.ts` contract: on desktop the external
+ * branch routes through the bridge (`okDesktop.shell.openExternal`), on web it
+ * falls back to `window.open`, and an unsafe scheme is refused (the branch was
+ * migrated off `openHashHrefInNewTab`, whose internal scheme gate is replaced
+ * by an explicit `isSafeNavigationUrl` guard).
+ */
+describe('navigateToMarkdownTarget — external routing', () => {
+ afterEach(() => {
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: originalWindow,
+ writable: true,
+ });
+ });
+
+ function stubWindow(overrides: { okDesktop?: unknown; open?: unknown }): void {
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: { location: { hash: '' }, open: overrides.open, okDesktop: overrides.okDesktop },
+ writable: true,
+ });
+ }
+
+ it('desktop (bridge present): routes through okDesktop.shell.openExternal, NOT window.open', () => {
+ const openExternal = mock(async (_url: string) => {});
+ const openWindow = mock(() => null);
+ stubWindow({ okDesktop: { shell: { openExternal } }, open: openWindow });
+
+ navigateToMarkdownTarget({ kind: 'external', url: 'https://example.com/watch' });
+
+ expect(openExternal).toHaveBeenCalledTimes(1);
+ expect(openExternal).toHaveBeenCalledWith('https://example.com/watch');
+ expect(openWindow).not.toHaveBeenCalled();
+ });
+
+ it('web (no bridge): falls back to window.open with the new-tab + noopener features', () => {
+ const openWindow = mock(() => null);
+ stubWindow({ okDesktop: undefined, open: openWindow });
+
+ navigateToMarkdownTarget({ kind: 'external', url: 'https://example.com/web' });
+
+ expect(openWindow).toHaveBeenCalledTimes(1);
+ expect(openWindow).toHaveBeenCalledWith(
+ 'https://example.com/web',
+ '_blank',
+ 'noopener,noreferrer',
+ );
+ });
+
+ it('unsafe scheme is refused: neither the bridge nor window.open fires', () => {
+ const openExternal = mock(async (_url: string) => {});
+ const openWindow = mock(() => null);
+ stubWindow({ okDesktop: { shell: { openExternal } }, open: openWindow });
+
+ navigateToMarkdownTarget({ kind: 'external', url: 'javascript:alert(1)' });
+
+ expect(openExternal).not.toHaveBeenCalled();
+ expect(openWindow).not.toHaveBeenCalled();
+ });
+});
+
describe('toInternalHashHref', () => {
it('builds standard fragment anchors for document sections', () => {
expect(toInternalHashHref({ docName: 'docs/guide', anchor: 'install' })).toBe(
diff --git a/packages/app/src/editor/internal-link-helpers.ts b/packages/app/src/editor/internal-link-helpers.ts
index f5fd9ede1..5a3dae666 100644
--- a/packages/app/src/editor/internal-link-helpers.ts
+++ b/packages/app/src/editor/internal-link-helpers.ts
@@ -5,6 +5,7 @@ import {
type DocLinkTarget,
} from '@inkeep/open-knowledge-core';
import { hashFromAssetPath, hashFromDocName } from '../lib/doc-hash';
+import { openExternalUrl } from '../lib/external-link';
import { dispatchAssetClick } from './asset-dispatch';
import { isSafeNavigationUrl } from './safe-navigation-url';
@@ -180,6 +181,15 @@ export function navigateToMarkdownTarget(
return;
}
+ if (target.kind === 'external') {
+ // Route through the desktop bridge so the OS default browser opens the URL
+ // (web falls back to window.open) — symmetric with the WYSIWYG link chip.
+ // openExternalUrl gates unsafe schemes internally now, so no guard here.
+ openExternalUrl(target.url);
+ return;
+ }
+
+ // asset — open the in-app asset preview / OS target in a new tab.
openHashHrefInNewTab(target.url);
}
diff --git a/packages/app/src/editor/plugins/wiki-link-source.ts b/packages/app/src/editor/plugins/wiki-link-source.ts
index 24fd92879..511e21d2a 100644
--- a/packages/app/src/editor/plugins/wiki-link-source.ts
+++ b/packages/app/src/editor/plugins/wiki-link-source.ts
@@ -24,6 +24,7 @@ import {
type ViewUpdate,
} from '@codemirror/view';
import { classifyWikiLinkTarget, type HeadingEntry } from '@inkeep/open-knowledge-core';
+import { openExternalUrl } from '@/lib/external-link';
import { hashFromAssetPath, hashFromDocName } from '../../lib/doc-hash';
import { resolveWikiLinkAssetTarget } from '../extensions/wiki-link-helpers';
import {
@@ -35,11 +36,7 @@ import {
type PageItem,
type WikiLinkContext,
} from '../extensions/wiki-link-suggestion';
-import {
- openHashHrefInNewTab,
- openInternalHashHrefInNewTab,
- shouldOpenInNewTab,
-} from '../internal-link-helpers';
+import { openInternalHashHrefInNewTab, shouldOpenInNewTab } from '../internal-link-helpers';
// ── Data fetching (module-level TTL cache wrapping shared fetchers) ──────────
//
@@ -230,11 +227,13 @@ const wikiLinkClickHandler = EditorView.domEventHandlers({
if (!classified) return false;
event.preventDefault();
if (classified.kind === 'external') {
- // classifyWikiLinkTarget admits any URI scheme via isExternalHref,
- // so a raw window.open of an authored URL would execute
- // javascript:/data:/etc. payloads in the viewer's origin.
- // openHashHrefInNewTab gates the scheme via isSafeNavigationUrl.
- openHashHrefInNewTab(classified.url);
+ // Route through the desktop bridge so the OS default browser opens
+ // the URL (web falls back to window.open) — symmetric with the
+ // WYSIWYG wiki-link chip. classifyWikiLinkTarget admits any URI
+ // scheme via isExternalHref; openExternalUrl refuses unsafe
+ // schemes internally, so an authored javascript:/data: href is
+ // dropped there (the event is already consumed via preventDefault).
+ openExternalUrl(classified.url);
} else if (classified.kind === 'asset') {
const assetPath =
resolveWikiLinkAssetTarget(
diff --git a/packages/app/src/lib/external-link.test.ts b/packages/app/src/lib/external-link.test.ts
index 7ccf1d68d..91f66165f 100644
--- a/packages/app/src/lib/external-link.test.ts
+++ b/packages/app/src/lib/external-link.test.ts
@@ -43,3 +43,19 @@ describe('openExternalUrl — web host (no bridge)', () => {
expect(openWindow).toHaveBeenCalledWith('https://example.com', '_blank', 'noopener,noreferrer');
});
});
+
+describe('openExternalUrl — structural scheme gate (internal)', () => {
+ test('an unsafe scheme is refused on the web path — never reaches window.open', () => {
+ const openWindow = mock(() => null);
+ // biome-ignore lint/suspicious/noExplicitAny: exercising the security gate with a hostile scheme
+ openExternalUrl('javascript:alert(1)' as any, { okDesktop: undefined, openWindow });
+ expect(openWindow).not.toHaveBeenCalled();
+ });
+
+ test('an unsafe scheme is refused on the desktop path — never reaches the bridge', () => {
+ const openExternal = mock(() => Promise.resolve());
+ // biome-ignore lint/suspicious/noExplicitAny: exercising the security gate with a hostile scheme
+ openExternalUrl('javascript:alert(1)' as any, { okDesktop: { shell: { openExternal } } });
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/lib/external-link.ts b/packages/app/src/lib/external-link.ts
index 64c87e8ef..53251c618 100644
--- a/packages/app/src/lib/external-link.ts
+++ b/packages/app/src/lib/external-link.ts
@@ -1,3 +1,5 @@
+import { isSafeNavigationUrl } from '@/editor/safe-navigation-url';
+
/**
* In Electron, `<a target="_blank">` opens the URL in an in-app
* BrowserWindow. Wire this onto BOTH `onClick` and `onAuxClick` so
@@ -9,7 +11,12 @@ export function dispatchExternalLinkClick(e: { preventDefault: () => void }, url
const openExternal = window.okDesktop?.shell?.openExternal;
if (!openExternal) return;
e.preventDefault();
- void openExternal(url);
+ // Same catch discipline as openExternalUrl: the bridge rejects schemes
+ // outside the main-process allowlist; swallow + warn so a rejected open
+ // can't surface as an unhandled rejection.
+ void openExternal(url).catch((err: unknown) => {
+ console.warn('[external-link] openExternal failed', url, err);
+ });
}
/**
@@ -37,11 +44,28 @@ interface OpenExternalUrlDeps {
* `window.open(url, '_blank', 'noopener,noreferrer')` new-tab behavior.
*/
export function openExternalUrl(url: string, deps: OpenExternalUrlDeps = {}): void {
+ // Structural security gate (defense-in-depth): refuse `javascript:`/`data:`/
+ // `vbscript:` etc. here so no caller can route an unsafe scheme to
+ // `window.open` (web fallback) by forgetting the check. Callers that need
+ // the boolean to drive control flow (e.g. a link chip that falls through to
+ // its edit panel) still call `isSafeNavigationUrl` themselves; this makes the
+ // invariant hold regardless. Relative `#/…` hash routes are not external and
+ // never reach here.
+ if (!isSafeNavigationUrl(url)) {
+ console.warn('[external-link] blocked non-safe scheme', url);
+ return;
+ }
const globalBridge = typeof window !== 'undefined' ? window.okDesktop : undefined;
const okDesktop = 'okDesktop' in deps ? deps.okDesktop : globalBridge;
const openExternal = okDesktop?.shell?.openExternal;
if (openExternal) {
- void openExternal(url);
+ // Fire-and-forget, but catch: the desktop bridge REJECTS schemes outside
+ // the main-process outbound allowlist (e.g. an authored `tel:` link passes
+ // the renderer's isSafeNavigationUrl gate but is not in ALLOWED_SCHEMES).
+ // Swallow + warn so a rejected open can't surface as an unhandled rejection.
+ void openExternal(url).catch((err: unknown) => {
+ console.warn('[external-link] openExternal failed', url, err);
+ });
return;
}
const globalOpen = typeof window !== 'undefined' ? window.open.bind(window) : undefined;
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 4e1777d11..faea42d0c 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -134,7 +134,6 @@ import { buildAboutPanelOptions } from './about-panel.ts';
import { appendOkIgnoreSync } from './append-okignore.ts';
import { openAssetSafely, revealAssetSafely } from './asset-allowlist.ts';
import { popAssetMenu } from './asset-menu.ts';
-import { attachAssetSafetyNet } from './asset-safety-net.ts';
import {
bootAutoUpdater,
channelFromVersion,
@@ -1369,6 +1368,25 @@ function ensureWindowManager() {
markWindowCreated: () => startupWaterfall.mark('windowCreated'),
markLoadUrlResolved: () => startupWaterfall.mark('loadUrlResolved'),
},
+ // External-link safety net, attached by the window factory to EVERY editor
+ // window (see WindowManager.attachSafetyNet). `openExternal` is
+ // window-independent; `openAsset` is parameterized by the window's project
+ // path so containment resolves against the right root. Grouped so the two
+ // delegates are wired together or not at all.
+ safetyNet: {
+ openExternal: handleShellOpenExternal({
+ openExternal: (url) => shell.openExternal(url),
+ }),
+ openAsset: (projectPath, relPath) =>
+ openAssetSafely(
+ {
+ projectPath,
+ platform: process.platform,
+ openPath: (canonical) => shell.openPath(canonical),
+ },
+ relPath,
+ ),
+ },
});
}
@@ -1832,21 +1850,9 @@ async function openProject(
},
'project window created',
);
- attachAssetSafetyNet(ctx.window.webContents, {
- editorOrigin: ctx.apiOrigin,
- openAsset: (relPath) =>
- openAssetSafely(
- {
- projectPath: ctx.projectPath,
- platform: process.platform,
- openPath: (canonical) => shell.openPath(canonical),
- },
- relPath,
- ),
- openExternal: handleShellOpenExternal({
- openExternal: (url) => shell.openExternal(url),
- }),
- });
+ // The external-link / asset safety net is attached by the window factory
+ // (WindowManager.attachSafetyNet) on every editor window, so no per-call-site
+ // wiring is needed here.
// Toast dispatch on did-finish-load so the renderer's sonner subscriber is
// mounted. `prefers-reduced-motion: reduce` is honored sonner-side.
if (toastPayload !== null) {
@@ -2027,25 +2033,9 @@ async function openEphemeralFile(filePath: string): Promise<void> {
{ file: plan.canonicalFilePath, apiOrigin: ctx.apiOrigin },
'ephemeral single-file window created',
);
- // The asset-safety-net root is the file's REAL parent (`ctx.projectPath` ===
- // `plan.contentDir`), NOT the throwaway temp projectDir — so `![[sibling]]`
- // `![](path)` assets are allowlisted against the directory they
- // actually live in.
- attachAssetSafetyNet(ctx.window.webContents, {
- editorOrigin: ctx.apiOrigin,
- openAsset: (relPath) =>
- openAssetSafely(
- {
- projectPath: ctx.projectPath,
- platform: process.platform,
- openPath: (canonical) => shell.openPath(canonical),
- },
- relPath,
- ),
- openExternal: handleShellOpenExternal({
- openExternal: (url) => shell.openExternal(url),
- }),
- });
+ // The external-link / asset safety net is attached by the window factory
+ // (WindowManager.attachSafetyNet) — for ephemeral windows the asset root is
+ // the file's real parent (`opts.contentDir`), wired there.
tryCloseNavigator(navigatorWindow, { projectPath: plan.contentDir });
refreshApplicationMenu();
} catch (err) {
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 14891d3a4..e700ea91d 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -36,6 +36,8 @@ import type { KeepaliveHandle } from '@inkeep/open-knowledge-core/keepalive';
import { getLocalDir } from '@inkeep/open-knowledge-server';
import type { OkServerRestartOutcome } from '../shared/bridge-contract.ts';
import { registerPendingDelivery } from '../shared/ipc-send.ts';
+import type { AssetOpenResult } from './asset-allowlist.ts';
+import { attachAssetSafetyNet } from './asset-safety-net.ts';
import type { ShowGateRegistry } from './show-gate.ts';
import type { ShareDeepLinkBranchSwitchPayload } from './url-scheme.ts';
import { classifyServerVersion } from './version-drift.ts';
@@ -688,6 +690,27 @@ export interface WindowManagerDeps {
/** Mark the moment `loadURL`/`loadFile` resolved. */
markLoadUrlResolved?(): void;
};
+ /**
+ * External-link safety-net delegates, grouped so the net is all-or-nothing.
+ * `attachSafetyNet` needs BOTH to function, so a partial wiring (one delegate
+ * but not the other) is unrepresentable rather than silently producing
+ * net-less windows — the #617 failure class must not resurface at the wiring
+ * layer. Absent in the unit harnesses that don't exercise the net; present in
+ * production (wired once in `index.ts`) and the factory-net tests.
+ */
+ safetyNet?: {
+ /**
+ * OS-browser delegate. Window-independent — `index.ts` wires
+ * `handleShellOpenExternal({ openExternal: url => shell.openExternal(url) })`.
+ */
+ openExternal: (url: string) => Promise<void>;
+ /**
+ * Project-scoped asset opener for the in-app-asset branch. Parameterized by
+ * `projectPath` because each window's containment root differs — `index.ts`
+ * wires `(projectPath, relPath) => openAssetSafely({ projectPath, platform, openPath }, relPath)`.
+ */
+ openAsset: (projectPath: string, relPath: string) => Promise<AssetOpenResult>;
+ };
}
/**
@@ -1311,6 +1334,35 @@ export class WindowManager {
});
}
+ /**
+ * Attach the external-link safety net to a freshly-created editor window, so
+ * EVERY factory path (spawn + ephemeral + attach, including the
+ * restart → recreate window) denies a `window.open(externalUrl)` and delegates
+ * it to the OS browser. The single enforcement point keeps the three factories
+ * from drifting — previously the net was wired per-call-site in `index.ts`, so
+ * a window created by any other path came up net-less.
+ *
+ * `setWindowOpenHandler` must be registered BEFORE the window's `loadURL`, so
+ * every caller invokes this immediately after `createWindow`.
+ *
+ * Guarded on the grouped `safetyNet` dep: unit harnesses that don't exercise
+ * the net omit it (their webContents fake has no `setWindowOpenHandler`), so
+ * the net stays off for them; production + the factory-net tests wire it.
+ */
+ private attachSafetyNet(
+ webContents: BrowserWindowLike['webContents'],
+ editorOrigin: string,
+ assetRoot: string,
+ ): void {
+ const net = this.deps.safetyNet;
+ if (!net) return;
+ attachAssetSafetyNet(webContents, {
+ editorOrigin,
+ openExternal: net.openExternal,
+ openAsset: (relPath) => net.openAsset(assetRoot, relPath),
+ });
+ }
+
async createProjectWindow(opts: CreateProjectWindowOpts): Promise<ProjectContext> {
const projectPath = resolve(opts.projectPath);
const canonicalKey = this.canonicalizeKey(projectPath);
@@ -1682,6 +1734,7 @@ export class WindowManager {
projectPath,
});
this.deps.startup?.markWindowCreated?.();
+ this.attachSafetyNet(window.webContents, apiOrigin, projectPath);
// Deep-link gate — register `dom-ready` listener BEFORE awaiting `loadURL`.
// A synchronous send from url-scheme.ts's routeUrl would work today only
@@ -1986,6 +2039,10 @@ export class WindowManager {
],
title: formatEditorTitle(projectName),
});
+ // Asset root is the file's real parent (`opts.contentDir`), NOT the throwaway
+ // temp projectDir — so `![[sibling]]` assets are allowlisted against the
+ // directory they actually live in.
+ this.attachSafetyNet(window.webContents, apiOrigin, opts.contentDir);
const disposeShowGate = this.deps.showGate.register(window, { kind: 'editor' });
@@ -2319,6 +2376,7 @@ export class WindowManager {
projectPath,
});
this.deps.startup?.markWindowCreated?.();
+ this.attachSafetyNet(window.webContents, apiOrigin, projectPath);
// Deep-link gate — same pattern as the spawn path. Register the
// `dom-ready` listener BEFORE `await loadURL` so the one-shot event
diff --git a/packages/desktop/tests/main/window-manager-safety-net.test.ts b/packages/desktop/tests/main/window-manager-safety-net.test.ts
new file mode 100644
index 000000000..c3820bc25
--- /dev/null
+++ b/packages/desktop/tests/main/window-manager-safety-net.test.ts
@@ -0,0 +1,322 @@
+/**
+ * Regression tests for inkeep/open-knowledge#617 — the external-link safety net
+ * is attached by the WINDOW FACTORY, so every editor window OpenKnowledge
+ * creates denies an external `window.open` and delegates it to the OS browser.
+ *
+ * Before the factory owned this, `attachAssetSafetyNet` was wired per-call-site
+ * in `index.ts` at only two window-creation sites, so windows created by any
+ * other path — notably the server-restart → recreate window — came up net-less:
+ * a WYSIWYG external-link click's `window.open` fell through to Electron's
+ * default and a child BrowserWindow rendered the page.
+ *
+ * Contract pinned here: a window created by the WindowManager factory — via the
+ * utility-fork spawn path, the bare attach-to-existing path, the ephemeral
+ * single-file path, AND the restart → recreate path — has a
+ * `setWindowOpenHandler` registered on its webContents that returns
+ * `{ action: 'deny' }` for an external `https:` URL and delegates that URL to
+ * `openExternal`.
+ *
+ * Seam: real `WindowManager` over the established `BrowserWindowLike` /
+ * `UtilityProcessLike` structural fakes (no Electron). The window fake's
+ * webContents captures the window-open handler so the test invokes it exactly
+ * as Electron would on a new-window request. `openExternal` is the one injected
+ * boundary (the OS-browser delegate) — asserting the captured handler routes an
+ * external URL to it is the real "reaches the OS browser" behavior, not a mock
+ * of the factory's own logic.
+ */
+
+import { describe, expect, mock, test } from 'bun:test';
+import { getLocalDir } from '@inkeep/open-knowledge-server';
+import type { AssetOpenResult } from '../../src/main/asset-allowlist.ts';
+import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
+import {
+ type BrowserWindowLike,
+ type ServerLockMetadataLike,
+ type UtilityProcessLike,
+ WindowManager,
+ type WindowManagerDeps,
+} from '../../src/main/window-manager.ts';
+
+// ---------------------------------------------------------------------------
+// Structural fakes — mirror packages/desktop/tests/main/window-manager.test.ts,
+// with the addition of a webContents that captures the safety-net handlers.
+// ---------------------------------------------------------------------------
+
+interface MockUtility extends UtilityProcessLike {
+ fire: (msg: unknown) => void;
+ fireExit: (code: number | null) => void;
+}
+
+function makeUtility(pid: number): MockUtility {
+ let messageHandler: ((m: unknown) => void) | null = null;
+ let exitHandler: ((c: number | null) => void) | null = null;
+ return {
+ pid,
+ postMessage: mock(() => {}),
+ on: mock((event: 'message' | 'exit', cb: (msg: unknown) => void) => {
+ if (event === 'message') messageHandler = cb;
+ else if (event === 'exit') exitHandler = cb as (c: number | null) => void;
+ }) as UtilityProcessLike['on'],
+ once: mock(() => {}),
+ removeListener: mock(() => {}),
+ kill: mock(() => true),
+ fire: (msg) => messageHandler?.(msg),
+ fireExit: (code) => exitHandler?.(code),
+ };
+}
+
+type WindowOpenHandler = (details: { url: string }) => { action: 'allow' | 'deny' };
+type WillNavigateHandler = (event: { preventDefault: () => void }, url: string) => void;
+
+type SafetyNetWindow = BrowserWindowLike & {
+ fireClose: () => void;
+ /** The handler the factory installs via `webContents.setWindowOpenHandler`, or
+ * null when the factory never attached the safety net. */
+ windowOpenHandler: WindowOpenHandler | null;
+ willNavigateHandler: WillNavigateHandler | null;
+};
+
+function makeWindow(): SafetyNetWindow {
+ const closeHandlers: Array<() => void> = [];
+ let destroyed = false;
+ let visible = false;
+ const win: SafetyNetWindow = {
+ focus: mock(() => {}),
+ show: mock(() => {
+ visible = true;
+ }),
+ restore: mock(() => {}),
+ isMinimized: mock(() => false),
+ moveTop: mock(() => {}),
+ isFocused: mock(() => false),
+ isDestroyed: mock(() => destroyed),
+ isVisible: mock(() => visible),
+ on: mock((_event: 'closed', cb: () => void) => {
+ closeHandlers.push(cb);
+ }) as BrowserWindowLike['on'],
+ once: mock((_event: 'ready-to-show', _cb: () => void) => {}) as BrowserWindowLike['once'],
+ close: mock(() => {
+ destroyed = true;
+ for (const h of closeHandlers) h();
+ }),
+ destroy: mock(() => {
+ destroyed = true;
+ for (const h of closeHandlers) h();
+ }),
+ webContents: {
+ send: mock(() => {}),
+ once: mock(() => {}),
+ executeJavaScript: mock(() => Promise.resolve(undefined)),
+ setWindowOpenHandler: mock((handler: WindowOpenHandler) => {
+ win.windowOpenHandler = handler;
+ }),
+ on: mock((event: 'will-navigate', handler: WillNavigateHandler) => {
+ if (event === 'will-navigate') win.willNavigateHandler = handler;
+ }),
+ } as unknown as BrowserWindowLike['webContents'],
+ loadFile: mock(() => Promise.resolve()),
+ loadURL: mock(() => Promise.resolve()),
+ fireClose: () => {
+ for (const h of closeHandlers) h();
+ },
+ windowOpenHandler: null,
+ willNavigateHandler: null,
+ };
+ return win;
+}
+
+interface TestEnv {
+ utilities: MockUtility[];
+ windows: SafetyNetWindow[];
+ openExternal: ReturnType<typeof mock>;
+ openAsset: ReturnType<typeof mock>;
+ deps: WindowManagerDeps;
+}
+
+function buildEnv(): TestEnv {
+ const utilities: MockUtility[] = [];
+ const windows: SafetyNetWindow[] = [];
+ const showGate: ShowGateRegistry = {
+ register: () => () => {},
+ fireThemeApplied: () => {},
+ };
+ let pidCounter = 20000;
+ // The two boundary delegates the safety net needs. `openAsset` is 2-arg
+ // (`projectPath`, `relPath`) — matching `WindowManagerDeps.safetyNet.openAsset`
+ // and the `attachSafetyNet` call `net.openAsset(assetRoot, relPath)`.
+ const openExternal = mock(async (_url: string): Promise<void> => {});
+ const openAsset = mock(
+ async (_projectPath: string, _relPath: string): Promise<AssetOpenResult> => ({ ok: true }),
+ );
+ const deps: WindowManagerDeps = {
+ createWindow: () => {
+ const w = makeWindow();
+ windows.push(w);
+ return w;
+ },
+ forkUtility: () => {
+ const u = makeUtility(++pidCounter);
+ utilities.push(u);
+ return u;
+ },
+ utilityEntryPath: '/fake/utility-entry.js',
+ rendererEntryPath: '/fake/renderer/index.html',
+ appVersion: '9.9.9-test',
+ setTimeout: () => null,
+ killProbe: mock(() => {}),
+ showGate,
+ // The ephemeral / detached-spawn deps are wired PER-TEST (createEphemeral
+ // and restart only). Leaving them off the base keeps the spawn test on the
+ // utility-fork path: `createProjectWindow` picks the detached-spawn path the
+ // moment `spawnDetachedServer` is present.
+ safetyNet: { openExternal, openAsset },
+ };
+ return { utilities, windows, openExternal, openAsset, deps };
+}
+
+/**
+ * Wire the ephemeral single-file (`ok <file>`) deps onto an env so
+ * `createEphemeralWindow` reaches its `attachSafetyNet` call without real
+ * Electron/spawn: `spawnDetachedServer` publishes a lock, the port poll reads it
+ * back via `readServerLock`.
+ */
+function withEphemeralDeps(env: TestEnv): void {
+ const ephemeralLocks = new Map<string, ServerLockMetadataLike>();
+ let pid = 42000;
+ env.deps.spawnLockPollDeadlineMs = 5_000;
+ env.deps.createEphemeralProjectDir = () => '/tmp/ok-ephemeral-net';
+ env.deps.removeDir = async () => {};
+ env.deps.isProcessAlive = () => true;
+ env.deps.readServerLock = (lockDir) => ephemeralLocks.get(lockDir) ?? null;
+ env.deps.spawnDetachedServer = async (opts) => {
+ const spawnedPid = ++pid;
+ if (opts.projectDir !== undefined) {
+ ephemeralLocks.set(getLocalDir(opts.projectDir), {
+ pid: spawnedPid,
+ hostname: 'testhost',
+ port: 52999,
+ startedAt: '2026-06-05T00:00:00.000Z',
+ worktreeRoot: opts.projectDir,
+ kind: 'interactive',
+ capabilities: ['ws'],
+ });
+ }
+ return { pid: spawnedPid };
+ };
+}
+
+const EXTERNAL_URL = 'https://example.com/watch';
+
+/**
+ * The invariant: `webContents.setWindowOpenHandler` was installed, and the
+ * installed handler denies an external new-window request AND delegates it to
+ * `openExternal` (the OS browser). Extracted so every factory path asserts it
+ * identically.
+ */
+async function expectExternalSafetyNet(
+ window: SafetyNetWindow,
+ openExternal: ReturnType<typeof mock>,
+): Promise<void> {
+ // The factory installed a window-open handler on the created window.
+ expect(window.windowOpenHandler).not.toBeNull();
+ const handler = window.windowOpenHandler;
+ if (!handler) throw new Error('unreachable — asserted non-null above');
+
+ const result = handler({ url: EXTERNAL_URL });
+ // An external new-window request must NOT open a child OpenKnowledge window.
+ expect(result).toEqual({ action: 'deny' });
+
+ // openExternal fires async inside the handler; let the microtask settle.
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(openExternal).toHaveBeenCalledWith(EXTERNAL_URL);
+}
+
+describe('WindowManager factory attaches the external-link safety net', () => {
+ test('createProjectWindow (spawn path) installs a deny+delegate window-open handler', async () => {
+ const env = buildEnv();
+ const wm = new WindowManager(env.deps);
+ const promise = wm.createProjectWindow({ projectPath: '/tmp/spawned-proj' });
+ env.utilities[0]?.fire({ type: 'ready', port: 51234, apiOrigin: 'http://localhost:51234' });
+ await promise;
+
+ expect(env.windows.length).toBe(1);
+ const created = env.windows[0];
+ if (!created) throw new Error('no window created');
+ await expectExternalSafetyNet(created, env.openExternal);
+ });
+
+ test('createEphemeralWindow (single-file path) installs a deny+delegate window-open handler', async () => {
+ const env = buildEnv();
+ withEphemeralDeps(env);
+ const wm = new WindowManager(env.deps);
+ await wm.createEphemeralWindow({
+ canonicalFilePath: '/Users/me/notes/todo.md',
+ contentDir: '/Users/me/notes',
+ docName: 'todo',
+ });
+
+ expect(env.windows.length).toBe(1);
+ const created = env.windows[0];
+ if (!created) throw new Error('no ephemeral window created');
+ await expectExternalSafetyNet(created, env.openExternal);
+ });
+
+ test('restartAttachedServer: both the initial attach and the recreated window install the net', async () => {
+ // Mirror the production restart path: attach mode → detached spawn (not the
+ // dev utility-fork), since drift/restart only occur in attach mode.
+ const env = buildEnv();
+ env.deps.selfProtocolVersion = 1;
+ env.deps.selfRuntimeVersion = '0.8.2';
+
+ const liveLock: ServerLockMetadataLike = {
+ pid: 65792,
+ hostname: 'my-host',
+ port: 59534,
+ startedAt: '2026-04-17T20:23:20.713Z',
+ worktreeRoot: '/tmp/dragon',
+ kind: 'interactive',
+ capabilities: ['http', 'ws'],
+ };
+ let killed = false;
+ let spawned = false;
+ const oldLock = { ...liveLock, pid: 5555, protocolVersion: 1, runtimeVersion: '0.8.0' };
+ const freshLock = {
+ ...liveLock,
+ pid: 6666,
+ port: 60000,
+ protocolVersion: 1,
+ runtimeVersion: '0.8.2',
+ };
+ env.deps.readServerLock = () => (spawned ? freshLock : killed ? null : oldLock);
+ env.deps.isProcessAlive = (pid) => (pid === 5555 ? !killed : true);
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.killProbe = mock((_pid: number, signal: number | NodeJS.Signals) => {
+ if (signal === 'SIGTERM') killed = true;
+ });
+ env.deps.spawnDetachedServer = async () => {
+ spawned = true;
+ return { pid: 6666 };
+ };
+
+ const wm = new WindowManager(env.deps);
+ const attached = await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
+ expect(attached.ownsServer).toBe(false);
+ expect(env.windows.length).toBe(1);
+ // The initial attach (createProjectWindow → attachToExistingServer, the bare
+ // attach-to-existing factory path) also installs the net.
+ const attachedWindow = env.windows[0];
+ if (!attachedWindow) throw new Error('no attach window');
+ await expectExternalSafetyNet(attachedWindow, env.openExternal);
+
+ const outcome = await wm.restartAttachedServer('/tmp/dragon');
+ expect(outcome).toEqual({ ok: true });
+ // A fresh window was recreated for the respawned server — it is the one that
+ // must carry the net (the whole point of #617).
+ expect(env.windows.length).toBe(2);
+ const recreated = env.windows[1];
+ if (!recreated) throw new Error('no recreated window');
+ await expectExternalSafetyNet(recreated, env.openExternal);
+ });
+});