Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): self-heal openknowledge:// protocol handler on macOS (#3976)

Andrew Mikofalvy2a043f582a51
diff --git a/.changeset/desktop-protocol-handler-self-heal.md b/.changeset/desktop-protocol-handler-self-heal.md
new file mode 100644
index 000000000..05cd163f1
--- /dev/null
+++ b/.changeset/desktop-protocol-handler-self-heal.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Fixed `openknowledge://` deep links (used by `ok open`, `ok <file>`, and shared links) sometimes opening a blank, unbranded Electron window instead of the OpenKnowledge desktop app.
+
+This happened when a development build of the desktop app had run on the machine at some point and registered itself as the handler for `openknowledge://` links, then exited without cleanly unregistering — for example, if the process was killed rather than quit normally, or its checkout was later deleted. macOS kept routing links to that no-longer-valid registration instead of the installed app. The desktop app now re-claims its link handling every time it starts, the same way it already did on Windows and Linux, so a stale registration from an old development run gets corrected automatically the next time you open the app.
+
+On macOS, `ok open` and `ok <file>` no longer depend on that registration being correct in the first place: when a desktop install is found, they open it by its exact file-system location rather than asking macOS to figure out who owns `openknowledge://` links, so they keep working even if a stale registration exists and the app hasn't been opened yet to repair it. Windows and Linux still resolve the link through the OS's own registration and rely on the per-boot repair above; making them equally independent of that resolution is tracked as a follow-up.
+
+Also worth knowing if you're developing the desktop app itself: a development instance still claims `openknowledge://` machine-wide on macOS while it's running (needed so `open openknowledge://...` reaches the dev build during local testing), and now competes with the packaged app's own per-boot repair for the same registration — whichever one started most recently wins. A browser-clicked link between an unclean dev-mode exit and the next time you launch the installed app by hand may briefly reach the wrong place; opening the installed app once corrects it.
diff --git a/packages/cli/src/commands/open.test.ts b/packages/cli/src/commands/open.test.ts
index e76f3379d..7882f8099 100644
--- a/packages/cli/src/commands/open.test.ts
+++ b/packages/cli/src/commands/open.test.ts
@@ -1,13 +1,16 @@
import { describe, expect, test } from 'vitest';
+import type { OpenTargetOptions } from '../utils/open-target.ts';
import { createRealOpenDeps, type OpenDeps, runOpen } from './open.ts';
function makeDeps(overrides: Partial<OpenDeps> = {}): {
deps: OpenDeps;
opened: string[];
+ openedOptions: Array<Pick<OpenTargetOptions, 'desktopBundlePath'> | undefined>;
logs: string[];
errors: string[];
} {
const opened: string[] = [];
+ const openedOptions: Array<Pick<OpenTargetOptions, 'desktopBundlePath'> | undefined> = [];
const logs: string[] = [];
const errors: string[] = [];
const deps: OpenDeps = {
@@ -16,8 +19,9 @@ function makeDeps(overrides: Partial<OpenDeps> = {}): {
// Default: nothing is a folder on disk, so tests opt into folder routing via
// an explicit override, `--folder`, or a trailing slash.
classifyName: () => 'doc',
- openTarget: async (t) => {
+ openTarget: async (t, options) => {
opened.push(t);
+ openedOptions.push(options);
return { ok: true };
},
findAncestorProject: () => null,
@@ -27,7 +31,7 @@ function makeDeps(overrides: Partial<OpenDeps> = {}): {
error: (m) => errors.push(m),
...overrides,
};
- return { deps, opened, logs, errors };
+ return { deps, opened, openedOptions, logs, errors };
}
describe('runOpen', () => {
@@ -40,6 +44,18 @@ describe('runOpen', () => {
expect(opened).toEqual(['openknowledge://open?project=%2Fabs%2Fproj&doc=bim-brain%2Flog']);
});
+ test('doc with a desktop bundle threads the verified bundle path to openTarget', async () => {
+ // The dispatcher (open-target.ts) names this exact bundle directly on
+ // darwin instead of resolving the openknowledge:// scheme through Launch
+ // Services — this is what makes that safe: it's the same path
+ // detectBundlePath() just confirmed exists, not a re-derived identity.
+ const { deps, openedOptions } = makeDeps({
+ detectBundlePath: () => '/Applications/OpenKnowledge.app',
+ });
+ await runOpen('bim-brain/log', { project: '/abs/proj' }, deps);
+ expect(openedOptions).toEqual([{ desktopBundlePath: '/Applications/OpenKnowledge.app' }]);
+ });
+
test('doc, no bundle but UI running → browser route, exit 0', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => null,
@@ -76,12 +92,13 @@ describe('runOpen', () => {
});
test('folder with a desktop bundle → folder= deep link, exit 0', async () => {
- const { deps, opened } = makeDeps({
+ const { deps, opened, openedOptions } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
const code = await runOpen('specs/foo/', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['openknowledge://open?project=%2Fp&folder=specs%2Ffoo']);
+ expect(openedOptions).toEqual([{ desktopBundlePath: '/Applications/OpenKnowledge.app' }]);
});
test('folder, no bundle but UI running → browser folder route, exit 0', async () => {
@@ -115,7 +132,7 @@ describe('runOpen', () => {
});
test('skill with a desktop bundle → rides doc=__skill__/<scope>/<name> deep link', async () => {
- const { deps, opened } = makeDeps({
+ const { deps, opened, openedOptions } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
const code = await runOpen('trip-log', { skill: true, project: '/p' }, deps);
@@ -123,6 +140,7 @@ describe('runOpen', () => {
expect(opened).toEqual([
'openknowledge://open?project=%2Fp&doc=__skill__%2Fproject%2Ftrip-log',
]);
+ expect(openedOptions).toEqual([{ desktopBundlePath: '/Applications/OpenKnowledge.app' }]);
});
test('skill --scope global, no bundle but UI running → browser skill route', async () => {
diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts
index 78a6eb349..c6381fc6c 100644
--- a/packages/cli/src/commands/open.ts
+++ b/packages/cli/src/commands/open.ts
@@ -40,7 +40,11 @@ import {
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import type { SpawnDetachedScrubbedOutcome } from '../utils/detached-spawn.ts';
-import { openTargetFailureMessage, openTarget as openTargetReal } from '../utils/open-target.ts';
+import {
+ type OpenTargetOptions,
+ openTargetFailureMessage,
+ openTarget as openTargetReal,
+} from '../utils/open-target.ts';
import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';
export interface OpenOptions {
@@ -67,8 +71,15 @@ export interface OpenDeps {
* This is what lets `ok open <name>` route correctly without `--folder`.
*/
classifyName: (projectDir: string, name: string) => 'doc' | 'folder';
- /** Hand a URL or `openknowledge://` deep link to the OS to open. */
- openTarget: (target: string) => Promise<SpawnDetachedScrubbedOutcome>;
+ /**
+ * Hand a URL or `openknowledge://` deep link to the OS to open.
+ * `desktopBundlePath` should be the same value `detectBundlePath()` just
+ * returned for this call — see `open-target.ts`'s `desktopBundlePath`.
+ */
+ openTarget: (
+ target: string,
+ options?: Pick<OpenTargetOptions, 'desktopBundlePath'>,
+ ) => Promise<SpawnDetachedScrubbedOutcome>;
/**
* Nearest project root STRICTLY above `projectDir`, or null. Drives the
* nested-project disclosure — a resolved root that sits inside another
@@ -159,6 +170,11 @@ function noTargetError(deps: OpenDeps): number {
* whether the directory is a project root, and calling it a "project" when it
* is only a cwd fallback is the same class of confidently-wrong output this
* surface exists to prevent.
+ *
+ * `desktopBundlePath` is the verified bundle path when `target` is a desktop
+ * deep link (omitted for a browser-fallback URL, where it has no effect) —
+ * threaded through so darwin dispatch can name the bundle directly instead of
+ * resolving the scheme (see `open-target.ts`).
*/
async function openAndReport(
target: string,
@@ -166,8 +182,9 @@ async function openAndReport(
projectDir: string,
isProject: boolean,
deps: OpenDeps,
+ desktopBundlePath?: string,
): Promise<number> {
- const outcome = await deps.openTarget(target);
+ const outcome = await deps.openTarget(target, desktopBundlePath ? { desktopBundlePath } : {});
if (!outcome.ok) {
deps.error(`Could not open ${target}: ${openTargetFailureMessage(outcome.reason, target)}.`);
return 1;
@@ -266,6 +283,7 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDeps
projectDir,
isProject,
deps,
+ bundlePath,
);
}
const baseUrl = deps.resolveBaseUrl(projectDir);
@@ -297,6 +315,7 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDeps
projectDir,
isProject,
deps,
+ bundlePath,
);
}
const baseUrl = deps.resolveBaseUrl(projectDir);
@@ -324,6 +343,7 @@ export async function runOpen(name: string, options: OpenOptions, deps: OpenDeps
projectDir,
isProject,
deps,
+ bundlePath,
);
}
const baseUrl = deps.resolveBaseUrl(projectDir);
diff --git a/packages/cli/src/commands/single-file-open.test.ts b/packages/cli/src/commands/single-file-open.test.ts
index c1fa7d894..5caf3a6dc 100644
--- a/packages/cli/src/commands/single-file-open.test.ts
+++ b/packages/cli/src/commands/single-file-open.test.ts
@@ -6,11 +6,13 @@ import {
SingleFileProjectOverrideError,
} from '@inkeep/open-knowledge-server';
import { describe, expect, test } from 'vitest';
+import type { OpenTargetOptions } from '../utils/open-target.ts';
import { runSingleFileOpen, type SingleFileOpenDeps } from './single-file-open.ts';
interface Recorder {
prepareOptions: Array<PrepareSingleFileOpenOptions | undefined>;
openTargets: string[];
+ openTargetOptions: Array<Pick<OpenTargetOptions, 'desktopBundlePath'> | undefined>;
projectOpens: Array<{ docName: string; projectRoot: string }>;
browserOpens: Array<Extract<SingleFileOpenPlan, { mode: 'ephemeral' }>>;
logs: string[];
@@ -23,6 +25,7 @@ function makeDeps(
const rec: Recorder = {
prepareOptions: [],
openTargets: [],
+ openTargetOptions: [],
projectOpens: [],
browserOpens: [],
logs: [],
@@ -38,8 +41,9 @@ function makeDeps(
detectBundlePath: overrides.detectBundlePath ?? (() => null),
openTarget:
overrides.openTarget ??
- (async (t) => {
+ (async (t, options) => {
rec.openTargets.push(t);
+ rec.openTargetOptions.push(options);
return { ok: true };
}),
runProjectOpen:
@@ -93,6 +97,12 @@ describe('runSingleFileOpen', () => {
expect(rec.openTargets).toEqual([
`openknowledge://open?file=${encodeURIComponent('/Users/me/notes/todo.md')}`,
]);
+ // The dispatcher (open-target.ts) names this exact bundle directly on
+ // darwin instead of resolving the openknowledge:// scheme through Launch
+ // Services — verified path threaded through, not re-derived.
+ expect(rec.openTargetOptions).toEqual([
+ { desktopBundlePath: '/Applications/OpenKnowledge.app' },
+ ]);
expect(rec.browserOpens).toHaveLength(0);
});
diff --git a/packages/cli/src/commands/single-file-open.ts b/packages/cli/src/commands/single-file-open.ts
index dd3e12200..c19eaf958 100644
--- a/packages/cli/src/commands/single-file-open.ts
+++ b/packages/cli/src/commands/single-file-open.ts
@@ -25,7 +25,11 @@ import {
SingleFileProjectOverrideError,
} from '@inkeep/open-knowledge-server';
import type { SpawnDetachedScrubbedOutcome } from '../utils/detached-spawn.ts';
-import { openTargetFailureMessage, openTarget as openTargetReal } from '../utils/open-target.ts';
+import {
+ type OpenTargetOptions,
+ openTargetFailureMessage,
+ openTarget as openTargetReal,
+} from '../utils/open-target.ts';
import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';
import { createRealOpenDeps, runOpen } from './open.ts';
@@ -43,8 +47,15 @@ export interface SingleFileOpenDeps {
prepare: (filePath: string, options?: PrepareSingleFileOpenOptions) => SingleFileOpenPlan;
/** Absolute desktop bundle path when one is installed, else null. */
detectBundlePath: () => string | null;
- /** Hand a URL / `openknowledge://` deep link to the OS to open. */
- openTarget: (target: string) => Promise<SpawnDetachedScrubbedOutcome>;
+ /**
+ * Hand a URL / `openknowledge://` deep link to the OS to open.
+ * `desktopBundlePath` should be the same value `detectBundlePath()` just
+ * returned — see `open-target.ts`'s `desktopBundlePath`.
+ */
+ openTarget: (
+ target: string,
+ options?: Pick<OpenTargetOptions, 'desktopBundlePath'>,
+ ) => Promise<SpawnDetachedScrubbedOutcome>;
/** Reuse `ok open`'s project-mode deep-link/browser path. Returns exit code. */
runProjectOpen: (docName: string, projectRoot: string) => Promise<number>;
/** Browser fallback — boot an ephemeral single-file server + open a tab. */
@@ -114,7 +125,7 @@ export async function runSingleFileOpen(
const bundlePath = deps.detectBundlePath();
if (bundlePath) {
const deepLink = `openknowledge://open?file=${encodeURIComponent(plan.canonicalFilePath)}`;
- const outcome = await deps.openTarget(deepLink);
+ const outcome = await deps.openTarget(deepLink, { desktopBundlePath: bundlePath });
if (!outcome.ok) {
deps.error(
`Could not open the OpenKnowledge desktop app: ${openTargetFailureMessage(
diff --git a/packages/cli/src/utils/open-target.test.ts b/packages/cli/src/utils/open-target.test.ts
index 7d949d73a..b9b8b7a6a 100644
--- a/packages/cli/src/utils/open-target.test.ts
+++ b/packages/cli/src/utils/open-target.test.ts
@@ -28,7 +28,34 @@ function makeSpawn(
}
describe('openTarget', () => {
- test('macOS dispatches through LaunchServices', async () => {
+ test('macOS with a verified bundle path names it directly, not scheme resolution', async () => {
+ // Scheme resolution is exactly what a stale Launch Services binding
+ // hijacks (a dev-mode instance that never unregistered — see desktop's
+ // url-scheme.ts). `-a <path>` sidesteps scheme resolution entirely — see
+ // open-target.ts's darwin branch for the in-repo precedent this leans on.
+ const capture: SpawnCapture = {};
+ const target = 'openknowledge://open?project=%2FUsers%2Fme%2Fnotes&doc=specs%2Flaunch';
+ const desktopBundlePath = '/Applications/OpenKnowledge.app';
+
+ const outcome = await openTarget(target, {
+ platform: 'darwin',
+ desktopBundlePath,
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('/usr/bin/open');
+ expect(capture.args).toEqual(['-a', desktopBundlePath, target]);
+ });
+
+ test('macOS falls back to plain scheme resolution when no bundle path is given', async () => {
+ // An ungated caller (no confirmed bundle path) degrades to plain scheme
+ // resolution rather than a broken dispatch. It never routes through
+ // bundle-ID (`-b`) resolution — a different Launch Services index this
+ // dispatch has no reason to trust more than scheme resolution — but that
+ // is a statement about this dispatch, not about every `-b` caller in the
+ // package (desktop-dispatch.ts's bare launch, no target argument, is
+ // unaffected either way).
const capture: SpawnCapture = {};
const target = 'openknowledge://open?project=%2FUsers%2Fme%2Fnotes&doc=specs%2Flaunch';
@@ -42,6 +69,36 @@ describe('openTarget', () => {
expect(capture.args).toEqual([target]);
});
+ test('macOS dispatches non-openknowledge URLs (browser fallback) through plain LaunchServices even with a bundle path', async () => {
+ const capture: SpawnCapture = {};
+ const target = 'http://localhost:5173/#/specs/launch';
+
+ const outcome = await openTarget(target, {
+ platform: 'darwin',
+ desktopBundlePath: '/Applications/OpenKnowledge.app',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('/usr/bin/open');
+ expect(capture.args).toEqual([target]);
+ });
+
+ test('Windows ignores a desktopBundlePath — the option is darwin-only', async () => {
+ const capture: SpawnCapture = {};
+ const target = 'openknowledge://open?project=C%3A%5CUsers%5Cme%5Cnotes&doc=specs%2Flaunch';
+
+ const outcome = await openTarget(target, {
+ platform: 'win32',
+ desktopBundlePath: '/Applications/OpenKnowledge.app',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('rundll32.exe');
+ expect(capture.args).toEqual(['url.dll,FileProtocolHandler', target]);
+ });
+
test('Windows opens the complete URL without cmd.exe parsing ampersands', async () => {
const capture: SpawnCapture = {};
const target = 'openknowledge://open?project=C%3A%5CUsers%5Cme%5Cnotes&doc=specs%2Flaunch';
@@ -72,6 +129,21 @@ describe('openTarget', () => {
expect(capture.options?.shell).toBe(false);
});
+ test('Linux ignores a desktopBundlePath — the option is darwin-only', async () => {
+ const capture: SpawnCapture = {};
+ const target = 'openknowledge://open?project=%2FUsers%2Fme%2Fnotes&doc=specs%2Flaunch';
+
+ const outcome = await openTarget(target, {
+ platform: 'linux',
+ desktopBundlePath: '/Applications/OpenKnowledge.app',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('xdg-open');
+ expect(capture.args).toEqual([target]);
+ });
+
test('Linux dispatches through xdg-open', async () => {
const capture: SpawnCapture = {};
const target = 'https://localhost:5173/#/specs/foo';
diff --git a/packages/cli/src/utils/open-target.ts b/packages/cli/src/utils/open-target.ts
index 536a7a2bf..2ae658dea 100644
--- a/packages/cli/src/utils/open-target.ts
+++ b/packages/cli/src/utils/open-target.ts
@@ -13,6 +13,15 @@ export interface OpenTargetOptions {
spawn?: typeof NativeSpawn;
env?: NodeJS.ProcessEnv;
timeoutMs?: number;
+ /**
+ * Verified desktop install path from `detectBundlePath()` — the macOS
+ * `.app` bundle; an executable path off darwin, where this option is
+ * unused. When present and `target` is an `openknowledge://` deep link,
+ * darwin dispatch names this exact bundle (`open -a <path> <url>`) instead
+ * of resolving the scheme through Launch Services. See darwin's branch in
+ * `resolveOpenInvocation` below for why.
+ */
+ desktopBundlePath?: string;
}
interface OpenInvocation {
@@ -20,8 +29,29 @@ interface OpenInvocation {
args: readonly string[];
}
-function resolveOpenInvocation(target: string, platform: NodeJS.Platform): OpenInvocation {
- if (platform === 'darwin') return { command: '/usr/bin/open', args: [target] };
+function resolveOpenInvocation(
+ target: string,
+ platform: NodeJS.Platform,
+ desktopBundlePath?: string,
+): OpenInvocation {
+ if (platform === 'darwin') {
+ // Plain scheme resolution is vulnerable to a stale Launch Services
+ // binding (see desktop's `url-scheme.ts` for the mechanism). When the
+ // caller already holds a verified bundle path — an FS probe of the
+ // executable inside it, not a Launch Services lookup — name it directly
+ // with `-a` instead: this repo already relies on `open -a <bundle>
+ // <target>` to cold-launch the app with a target and have it delivered
+ // (packages/desktop/tests/smoke/cold-single-file-launch.e2e.ts's
+ // `launchViaLaunchServices`, called with an `openknowledge://share?…`
+ // target). This is distinct from bundle-ID (`-b`) resolution, a different
+ // Launch Services index this dispatch has no reason to trust more than
+ // plain scheme resolution — desktop-dispatch.ts's bare `-b` launch (no
+ // target argument) is a separate, unaffected case.
+ if (desktopBundlePath && target.startsWith('openknowledge://')) {
+ return { command: '/usr/bin/open', args: ['-a', desktopBundlePath, target] };
+ }
+ return { command: '/usr/bin/open', args: [target] };
+ }
if (platform === 'win32') {
if (target.startsWith('http://') || target.startsWith('https://')) {
return { command: 'explorer.exe', args: [target] };
@@ -38,7 +68,11 @@ export function openTarget(
target: string,
options: OpenTargetOptions = {},
): Promise<SpawnDetachedScrubbedOutcome> {
- const invocation = resolveOpenInvocation(target, options.platform ?? process.platform);
+ const invocation = resolveOpenInvocation(
+ target,
+ options.platform ?? process.platform,
+ options.desktopBundlePath,
+ );
return spawnDetachedScrubbedAndWait(invocation.command, invocation.args, {
spawn: options.spawn,
env: options.env,
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index afef5cef8..b179eb8ef 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -8396,8 +8396,9 @@ function bootPrimaryInstance(): void {
},
getInitialArgv: () => process.argv,
log: {
- warn: (obj, msg) => console.warn(msg, obj),
- info: (obj, msg) => console.info(msg, obj),
+ warn: (obj, msg) => getLogger('url-scheme').warn(obj, msg),
+ info: (obj, msg) => getLogger('url-scheme').info(obj, msg),
+ error: (obj, msg) => getLogger('url-scheme').error(obj, msg),
},
});
diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.ts
index 4e5aa0d82..d0e903aae 100644
--- a/packages/desktop/src/main/url-scheme.ts
+++ b/packages/desktop/src/main/url-scheme.ts
@@ -795,8 +795,9 @@ interface ProtocolHandlerDeps {
now?: () => number;
/** Optional structured logger. */
log?: {
- warn(obj: object, msg: string): void;
- info?(obj: object, msg: string): void;
+ warn(obj: Record<string, unknown>, msg: string): void;
+ info?(obj: Record<string, unknown>, msg: string): void;
+ error(obj: Record<string, unknown>, msg: string): void;
};
}
@@ -942,7 +943,9 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// Electron.app shell, not this app, so Launch Services has no binding.
// `setAsDefaultProtocolClient` writes a runtime binding so `open
// openknowledge://...` targets the dev instance during development. Packaged
- // builds rely on `CFBundleURLTypes` from electron-builder.yml.
+ // builds additionally self-heal their own binding on every boot below —
+ // `CFBundleURLTypes` from electron-builder.yml is the installer-time
+ // baseline, not a permanently-authoritative claim.
if (!deps.app.isPackaged) {
try {
// Per Electron docs `setAsDefaultProtocolClient` is non-throwing and
@@ -960,11 +963,16 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
// Unregister on dev-exit so a stale Launch Services binding doesn't
// route subsequent `open openknowledge://...` to a moved/deleted
// worktree — a developer-UX footgun when switching between checkouts.
- // Hard exits (SIGKILL) skip `before-quit`, so the guarantee is
- // best-effort: the next successful dev-exit re-registers cleanly.
- // Packaged builds skip this entirely — their `CFBundleURLTypes`
- // binding is installed by the OS at DMG install time and owned by
- // Launch Services, not by us.
+ // (On macOS, Electron's `removeAsDefaultProtocolClient` doesn't clear
+ // the binding outright — per `shell/browser/browser_mac.mm` (Electron
+ // v43.x) it hands the scheme to the first other bundle ID Launch
+ // Services finds registered for it, falling back to `None` —
+ // harmless here since the packaged app, if installed, is exactly
+ // what should reclaim it.) Hard exits (SIGKILL) skip `before-quit`,
+ // so the guarantee is best-effort: the next successful dev-exit
+ // re-registers cleanly. Packaged builds don't rely on this at all —
+ // see the packaged self-heal branch below, which re-asserts the
+ // binding at every boot rather than depending on a clean dev exit.
deps.app.on('before-quit', () => {
try {
deps.app.removeAsDefaultProtocolClient('openknowledge');
@@ -979,27 +987,40 @@ export function registerProtocolHandler(deps: ProtocolHandlerDeps): ProtocolHand
} catch (err) {
deps.log?.warn({ err }, '[url-scheme] setAsDefaultProtocolClient failed');
}
- } else if (platform !== 'darwin') {
- // Packaged Windows/Linux self-heal (windows-linux-port deep-link posture).
- // Unlike macOS (where LaunchServices owns the CFBundleURLTypes binding
- // installed with the .app), Windows resolves the scheme from
+ } else {
+ // Packaged self-heal, every platform. Windows resolves the scheme from
// HKCU\Software\Classes and Linux from the .desktop database — both
// user-mutable and installer-dependent (the NSIS include writes the
// registry keys; deb's .desktop carries the MimeType; AppImage has no
- // install step at all, see appimage-integration.ts). Re-asserting at
- // every boot repairs a stale binding after the install moves, another
- // app steals the scheme, or the installer-time registration was lost.
- // No before-quit removal here — a packaged install keeps its binding.
+ // install step at all, see appimage-integration.ts). macOS's
+ // CFBundleURLTypes binding from the DMG install is NOT immune to the same
+ // class of drift: a dev-mode instance's runtime `setAsDefaultProtocolClient`
+ // call (above) writes a user-level Launch Services override that outranks
+ // the installed binding and survives indefinitely whenever that dev
+ // process exits without a clean `before-quit` (SIGKILL, a deleted
+ // worktree, a killed agent session) — the `before-quit` removal is
+ // documented above as best-effort, not guaranteed. A stale claim doesn't
+ // just break deep-linking: Launch Services routes `openknowledge://` to
+ // whatever bundle ID it has on file, which can be Electron's own
+ // `default_app.asar` placeholder if a stray dev instance's runtime
+ // override is still in effect — opening a bare, unbuilt Electron window
+ // instead of this app. Re-asserting at every boot repairs a stale binding
+ // after the install moves, another app/build steals the scheme, or the
+ // installer-time registration was lost. No before-quit removal here — a
+ // packaged install keeps its binding.
try {
const ok = deps.app.setAsDefaultProtocolClient('openknowledge');
if (!ok) {
- deps.log?.warn(
+ // Packaged is the only line of defense for real users (no dev-exit
+ // unregister to fall back on), so a failed self-heal here — unlike the
+ // dev-mode warn above — is escalated to error.
+ deps.log?.error(
{},
'[url-scheme] packaged setAsDefaultProtocolClient returned false — openknowledge:// links may not reach this install',
);
}
} catch (err) {
- deps.log?.warn({ err }, '[url-scheme] packaged setAsDefaultProtocolClient failed');
+ deps.log?.error({ err }, '[url-scheme] packaged setAsDefaultProtocolClient failed');
}
}
diff --git a/packages/desktop/tests/main/url-scheme-handler.test.ts b/packages/desktop/tests/main/url-scheme-handler.test.ts
index a565cbcf2..28d0ac134 100644
--- a/packages/desktop/tests/main/url-scheme-handler.test.ts
+++ b/packages/desktop/tests/main/url-scheme-handler.test.ts
@@ -125,7 +125,10 @@ interface TestEnv {
sendDeepLink: AnyMock;
getAnyReadyWindow: AnyMock;
timers: Array<{ cb: () => void; ms: number }>;
- warnLog: Array<{ obj: object; msg: string }>;
+ log: NonNullable<Parameters<typeof registerProtocolHandler>[0]['log']>;
+ warnLog: Array<{ obj: Record<string, unknown>; msg: string }>;
+ infoLog: Array<{ obj: Record<string, unknown>; msg: string }>;
+ errorLog: Array<{ obj: Record<string, unknown>; msg: string }>;
existingWindows: Map<string, FakeWindowHandle>;
readyWindow: FakeWindowHandle | null;
}
@@ -134,7 +137,14 @@ function makeEnv(opts?: { isPackaged?: boolean }): TestEnv {
const existingWindows = new Map<string, FakeWindowHandle>();
let readyWindow: FakeWindowHandle | null = null;
const timers: Array<{ cb: () => void; ms: number }> = [];
- const warnLog: Array<{ obj: object; msg: string }> = [];
+ const warnLog: Array<{ obj: Record<string, unknown>; msg: string }> = [];
+ const infoLog: Array<{ obj: Record<string, unknown>; msg: string }> = [];
+ const errorLog: Array<{ obj: Record<string, unknown>; msg: string }> = [];
+ const log: NonNullable<Parameters<typeof registerProtocolHandler>[0]['log']> = {
+ warn: (obj, msg) => warnLog.push({ obj, msg }),
+ info: (obj, msg) => infoLog.push({ obj, msg }),
+ error: (obj, msg) => errorLog.push({ obj, msg }),
+ };
return {
app: makeFakeApp(opts),
focusWindowForProject: vi.fn((p: string) => existingWindows.get(p) ?? null),
@@ -153,7 +163,10 @@ function makeEnv(opts?: { isPackaged?: boolean }): TestEnv {
sendDeepLink: vi.fn(() => {}),
getAnyReadyWindow: vi.fn(() => readyWindow),
timers,
+ log,
warnLog,
+ infoLog,
+ errorLog,
existingWindows,
get readyWindow() {
return readyWindow;
@@ -192,29 +205,16 @@ describe('registerProtocolHandler — setAsDefaultProtocolClient', () => {
expect(env.app.setAsDefaultProtocolClient).toHaveBeenCalledWith('openknowledge');
});
- test('does NOT call setAsDefaultProtocolClient in packaged darwin builds', () => {
- // macOS packaged installs rely on the CFBundleURLTypes binding owned by
- // LaunchServices — pin platform explicitly: the CI test host is Linux,
- // where packaged builds DO self-heal (next test).
- const env = makeEnv({ isPackaged: true });
- registerProtocolHandler({
- app: env.app,
- focusWindowForProject: env.focusWindowForProject,
- openProject: env.openProject,
- sendDeepLink: env.sendDeepLink,
- getAnyReadyWindow: env.getAnyReadyWindow,
- setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- platform: 'darwin',
- });
- expect(env.app.setAsDefaultProtocolClient).not.toHaveBeenCalled();
- });
-
- for (const platform of ['win32', 'linux'] as const) {
+ for (const platform of ['darwin', 'win32', 'linux'] as const) {
test(`packaged ${platform} builds self-heal the scheme binding per boot`, () => {
- // Windows resolves openknowledge:// from HKCU\Software\Classes and
- // Linux from the .desktop database — both user-mutable and
- // installer-dependent, so packaged builds re-assert at every boot
- // (windows-linux-port deep-link posture). No before-quit removal.
+ // A packaged install's installer-time binding (CFBundleURLTypes on
+ // macOS, HKCU\Software\Classes on Windows, the .desktop database on
+ // Linux) is not permanently authoritative on any platform — all three
+ // are user-mutable, and on macOS specifically a dev-mode instance's
+ // runtime `setAsDefaultProtocolClient` call can leave a stale
+ // user-level override in place indefinitely if that dev process never
+ // hits `before-quit` (SIGKILL, a deleted worktree). Packaged builds
+ // re-assert at every boot on every platform. No before-quit removal.
const env = makeEnv({ isPackaged: true });
registerProtocolHandler({
app: env.app,
@@ -236,7 +236,6 @@ describe('registerProtocolHandler — setAsDefaultProtocolClient', () => {
// at "dev deep-links not working" without a breadcrumb.
const env = makeEnv({ isPackaged: false });
env.app.setAsDefaultProtocolClient = vi.fn(() => false);
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
focusWindowForProject: env.focusWindowForProject,
@@ -244,10 +243,55 @@ describe('registerProtocolHandler — setAsDefaultProtocolClient', () => {
sendDeepLink: env.sendDeepLink,
getAnyReadyWindow: env.getAnyReadyWindow,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
+ });
+ expect(env.warnLog).toHaveLength(1);
+ expect(env.warnLog[0]?.msg).toContain('returned false');
+ });
+
+ test('escalates a failed packaged self-heal to error, not warn', () => {
+ // Packaged is the only line of defense for real users — no dev-exit
+ // unregister to fall back on — so a failed self-heal here must not land
+ // at the same severity as the dev-mode case above.
+ const env = makeEnv({ isPackaged: true });
+ env.app.setAsDefaultProtocolClient = vi.fn(() => false);
+ registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ log: env.log,
+ // Pin a platform so the assertion can't vary with the host OS. The
+ // packaged branch has no platform gate — the three-platform loop above
+ // covers that — and darwin's settle grace is armed inside
+ // `whenReady().then()`, which this synchronous test never resolves.
+ platform: 'darwin',
});
- expect(warnLog).toHaveLength(1);
- expect(warnLog[0]?.msg).toContain('returned false');
+ expect(env.warnLog).toHaveLength(0);
+ expect(env.errorLog).toHaveLength(1);
+ expect(env.errorLog[0]?.msg).toContain('packaged setAsDefaultProtocolClient returned false');
+ });
+
+ test('escalates a throwing packaged self-heal to error, not warn', () => {
+ const env = makeEnv({ isPackaged: true });
+ env.app.setAsDefaultProtocolClient = vi.fn(() => {
+ throw new Error('Launch Services unavailable');
+ });
+ registerProtocolHandler({
+ app: env.app,
+ focusWindowForProject: env.focusWindowForProject,
+ openProject: env.openProject,
+ sendDeepLink: env.sendDeepLink,
+ getAnyReadyWindow: env.getAnyReadyWindow,
+ setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
+ log: env.log,
+ platform: 'darwin',
+ });
+ expect(env.warnLog).toHaveLength(0);
+ expect(env.errorLog).toHaveLength(1);
+ expect(env.errorLog[0]?.msg).toContain('packaged setAsDefaultProtocolClient failed');
});
});
@@ -279,8 +323,10 @@ describe('registerProtocolHandler — before-quit Launch Services cleanup', () =
getAnyReadyWindow: env.getAnyReadyWindow,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
});
- // Packaged builds don't touch Launch Services at runtime — the binding
- // comes from the DMG's Info.plist (electron-builder). Nothing to remove.
+ // Packaged builds DO touch Launch Services at runtime (the self-heal
+ // re-assert on every boot — see the loop above), but they never remove
+ // the binding on quit: unlike a dev instance, a packaged install should
+ // keep claiming the scheme after it exits. Nothing to remove here.
expect(() => env.app.fireBeforeQuit()).toThrow(/before-quit listener not registered/);
expect(env.app.removeAsDefaultProtocolClient).not.toHaveBeenCalled();
});
@@ -308,7 +354,6 @@ describe('registerProtocolHandler — before-quit Launch Services cleanup', () =
env.app.removeAsDefaultProtocolClient = vi.fn(() => {
throw new Error('launch services refused');
});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
focusWindowForProject: env.focusWindowForProject,
@@ -316,11 +361,13 @@ describe('registerProtocolHandler — before-quit Launch Services cleanup', () =
sendDeepLink: env.sendDeepLink,
getAnyReadyWindow: env.getAnyReadyWindow,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
// Must NOT bubble up past the listener — app quit would be aborted.
expect(() => env.app.fireBeforeQuit()).not.toThrow();
- expect(warnLog.some((e) => e.msg.includes('removeAsDefaultProtocolClient failed'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('removeAsDefaultProtocolClient failed'))).toBe(
+ true,
+ );
});
});
@@ -609,7 +656,6 @@ describe('registerProtocolHandler — queue-then-flush', () => {
});
test('silent-drops malformed URLs with a single warn log line', async () => {
- const warnLog: Array<{ obj: object; msg: string }> = [];
env.readyWindow = { id: 'pre-existing' };
registerProtocolHandler({
app: env.app,
@@ -618,9 +664,7 @@ describe('registerProtocolHandler — queue-then-flush', () => {
sendDeepLink: env.sendDeepLink,
getAnyReadyWindow: env.getAnyReadyWindow,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: {
- warn: (obj, msg) => warnLog.push({ obj, msg }),
- },
+ log: env.log,
});
env.app.fireOpenUrl('openknowledge://open?doc=a.md'); // missing project
env.app.resolveReady();
@@ -628,8 +672,8 @@ describe('registerProtocolHandler — queue-then-flush', () => {
expect(env.openProject).not.toHaveBeenCalled();
expect(env.sendDeepLink).not.toHaveBeenCalled();
- expect(warnLog).toHaveLength(1);
- expect(warnLog[0]?.msg).toContain('dropped malformed URL');
+ expect(env.warnLog).toHaveLength(1);
+ expect(env.warnLog[0]?.msg).toContain('dropped malformed URL');
});
test('focuses existing window when project is already open (warm same-project)', async () => {
@@ -1047,7 +1091,6 @@ describe('registerProtocolHandler — share-flow routing', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const warnLog: Array<{ obj: object; msg: string }> = [];
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
@@ -1059,7 +1102,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
sendShareDeepLink,
getFocusedWindow: () => focusedWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1068,7 +1111,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
await flushPromises();
expect(sendShareDeepLink).toHaveBeenCalledWith(focusedWin, { kind: 'unsupported-version' });
- expect(warnLog).toContainEqual({
+ expect(env.warnLog).toContainEqual({
obj: {
source: 'universal-link',
result: 'unsupported-version',
@@ -1085,7 +1128,6 @@ describe('registerProtocolHandler — share-flow routing', () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const warnLog: Array<{ obj: object; msg: string }> = [];
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
registerProtocolHandler({
@@ -1097,7 +1139,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
sendShareDeepLink,
getFocusedWindow: () => focusedWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1106,7 +1148,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
await flushPromises();
expect(sendShareDeepLink).toHaveBeenCalledWith(focusedWin, { kind: 'invalid' });
- expect(warnLog).toContainEqual({
+ expect(env.warnLog).toContainEqual({
obj: {
source: 'universal-link',
result: 'invalid',
@@ -1116,14 +1158,13 @@ describe('registerProtocolHandler — share-flow routing', () => {
},
msg: '[receive] action=url-parse',
});
- expect(JSON.stringify(warnLog)).not.toContain('!!!not-base64!!!');
+ expect(JSON.stringify([...env.warnLog, ...env.errorLog])).not.toContain('!!!not-base64!!!');
});
test('malformed share-shaped and lookalike authority inputs keep logs scrubbed', async () => {
const env = makeEnv();
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
- const warnLog: Array<{ obj: object; msg: string }> = [];
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
const secret = 'SECRET-MALFORMED-SHARE';
@@ -1136,7 +1177,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
sendShareDeepLink,
getFocusedWindow: () => focusedWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1156,12 +1197,12 @@ describe('registerProtocolHandler — share-flow routing', () => {
expect(sendShareDeepLink).toHaveBeenNthCalledWith(3, focusedWin, { kind: 'invalid' });
expect(sendShareDeepLink).toHaveBeenNthCalledWith(4, focusedWin, { kind: 'invalid' });
expect(sendShareDeepLink).toHaveBeenNthCalledWith(5, focusedWin, { kind: 'invalid' });
- expect(JSON.stringify(warnLog)).not.toContain(secret);
- expect(warnLog.filter(({ msg }) => msg === '[url-scheme] dropped malformed URL')).toEqual([
+ expect(JSON.stringify([...env.warnLog, ...env.errorLog])).not.toContain(secret);
+ expect(env.warnLog.filter(({ msg }) => msg === '[url-scheme] dropped malformed URL')).toEqual([
{ obj: {}, msg: '[url-scheme] dropped malformed URL' },
{ obj: {}, msg: '[url-scheme] dropped malformed URL' },
]);
- expect(warnLog).toContainEqual({
+ expect(env.warnLog).toContainEqual({
obj: {
source: 'universal-link',
result: 'invalid',
@@ -1171,7 +1212,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
},
msg: '[receive] action=url-parse',
});
- expect(warnLog).toContainEqual({
+ expect(env.warnLog).toContainEqual({
obj: {
source: 'custom-scheme',
result: 'invalid',
@@ -1186,8 +1227,6 @@ describe('registerProtocolHandler — share-flow routing', () => {
test('logs a bounded v2 success classification without token, URL, or target path', async () => {
const env = makeEnv();
env.readyWindow = { id: 'ready' };
- const warnLog: Array<{ obj: object; msg: string }> = [];
- const infoLog: Array<{ obj: object; msg: string }> = [];
const fixtureEntry = shareFixture.validShares.find(
(entry) => entry.id === 'v2-one-segment-document',
);
@@ -1202,10 +1241,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
resolveShareTarget: async () => ({ kind: 'miss' }),
routeShareToNavigator: () => {},
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: {
- warn: (obj, msg) => warnLog.push({ obj, msg }),
- info: (obj, msg) => infoLog.push({ obj, msg }),
- },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1214,7 +1250,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
await flushPromises();
// A successful parse logs at info, off the warn channel operators alert on.
- expect(infoLog).toContainEqual({
+ expect(env.infoLog).toContainEqual({
obj: {
source: 'universal-link',
result: 'ok',
@@ -1224,7 +1260,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
},
msg: '[receive] action=url-parse',
});
- const serialized = JSON.stringify([...warnLog, ...infoLog]);
+ const serialized = JSON.stringify([...env.warnLog, ...env.infoLog, ...env.errorLog]);
expect(serialized).not.toContain(fixtureEntry.token);
expect(serialized).not.toContain(fixtureEntry.sharedUrl);
expect(serialized).not.toContain(fixtureEntry.target.docPath);
@@ -1237,7 +1273,6 @@ describe('registerProtocolHandler — share-flow routing', () => {
const env = makeEnv();
env.readyWindow = { id: 'ready' };
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -1249,7 +1284,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
// resolveShareTarget intentionally omitted.
getFocusedWindow: () => null,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1260,7 +1295,7 @@ describe('registerProtocolHandler — share-flow routing', () => {
expect(sendShareDeepLink).not.toHaveBeenCalled();
expect(env.openProject).not.toHaveBeenCalled();
- expect(warnLog.some((e) => e.msg.includes('resolveShareTarget dep missing'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('resolveShareTarget dep missing'))).toBe(true);
});
test('open-action URLs continue routing through the legacy path (regression check)', async () => {
@@ -1594,7 +1629,6 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
reason: 'main-checkout',
}),
);
- const warnLog: Array<{ obj: object; msg: string }> = [];
// sendShareDeepLink intentionally omitted (dep unwired). Production always
// wires it; this pins the defense-in-depth observability: the open window
@@ -1608,7 +1642,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
resolveShareTarget,
getFocusedWindow: () => editorWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1617,7 +1651,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
await flushPromises();
await flushPromises();
- expect(warnLog.some((e) => e.msg.includes('sendShareDeepLink dep missing'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('sendShareDeepLink dep missing'))).toBe(true);
// Falls through to openProject so the window is at least focused.
expect(env.openProject).toHaveBeenCalledWith(
'/Users/me/playbooks',
@@ -1947,7 +1981,6 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
});
const sendShareDeepLink = vi.fn((_w: FakeWindowHandle, _p: ShareDeepLinkPayload) => {});
const routeShareToNavigator = vi.fn((_p: ShareNavigatorPayload) => {});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -1960,7 +1993,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
routeShareToNavigator,
getFocusedWindow: () => env.readyWindow,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -1977,7 +2010,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
share: expectedSharePayload(),
});
expect(env.openProject).not.toHaveBeenCalled();
- expect(warnLog.some((e) => e.msg.includes('resolveShareTarget rejected'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('resolveShareTarget rejected'))).toBe(true);
});
test('branch-match-non-ok with no routeShareToNavigator dep surfaces warn + no dispatch', async () => {
@@ -1994,7 +2027,6 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
anchorRecent: null,
}),
);
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -2006,7 +2038,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
// routeShareToNavigator intentionally omitted
getFocusedWindow: () => env.readyWindow,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -2016,7 +2048,7 @@ describe('registerProtocolHandler — resolved share routing (US-003)', () => {
await flushPromises();
expect(env.openProject).not.toHaveBeenCalled();
- expect(warnLog.some((e) => e.msg.includes('launcher-consent dropped'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('launcher-consent dropped'))).toBe(true);
});
test('share URL via second-instance argv reaches resolution', async () => {
@@ -2242,7 +2274,6 @@ describe('registerProtocolHandler — screen-flow routing', () => {
test('missing openScreen dep surfaces a warn + no dispatch', async () => {
const env = makeEnv();
env.readyWindow = { id: 'ready' };
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -2253,7 +2284,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
getFocusedWindow: () => null,
// openScreen intentionally omitted — handler must silent-drop with a warn.
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -2261,7 +2292,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
env.app.fireOpenUrl('openknowledge://screen?name=settings');
await flushPromises();
- expect(warnLog.some((e) => e.msg.includes('openScreen dep missing'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('openScreen dep missing'))).toBe(true);
expect(env.openProject).not.toHaveBeenCalled();
expect(env.sendDeepLink).not.toHaveBeenCalled();
});
@@ -2270,7 +2301,6 @@ describe('registerProtocolHandler — screen-flow routing', () => {
const env = makeEnv();
env.readyWindow = { id: 'ready' };
const openScreen = vi.fn((_win: FakeWindowHandle, _screen: ScreenTarget) => {});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -2282,7 +2312,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
openScreen,
getFocusedWindow: () => null,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -2291,7 +2321,7 @@ describe('registerProtocolHandler — screen-flow routing', () => {
await flushPromises();
expect(openScreen).not.toHaveBeenCalled();
- expect(warnLog.some((e) => e.msg.includes('no target window'))).toBe(true);
+ expect(env.warnLog.some((e) => e.msg.includes('no target window'))).toBe(true);
});
});
@@ -2422,7 +2452,6 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -2433,7 +2462,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
sendShareDeepLink,
getFocusedWindow: () => focusedWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -2447,7 +2476,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
expect(sendShareDeepLink).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
- expect(warnLog.some((e) => e.msg.includes('continue-activity-received'))).toBe(false);
+ expect(env.warnLog.some((e) => e.msg.includes('continue-activity-received'))).toBe(false);
});
test('ignores activities whose webpageURL is on a non-AASA host', async () => {
@@ -2458,7 +2487,6 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -2469,7 +2497,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
sendShareDeepLink,
getFocusedWindow: () => focusedWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -2481,7 +2509,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
expect(sendShareDeepLink).not.toHaveBeenCalled();
expect(event.preventDefault).not.toHaveBeenCalled();
- expect(warnLog.some((e) => e.msg.includes('continue-activity-received'))).toBe(false);
+ expect(env.warnLog.some((e) => e.msg.includes('continue-activity-received'))).toBe(false);
});
test('ignores activities with no webpageURL on either details or userInfo', async () => {
@@ -2543,7 +2571,6 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
const focusedWin: FakeWindowHandle = { id: 'focused' };
env.readyWindow = focusedWin;
const sendShareDeepLink = vi.fn((_win: FakeWindowHandle, _payload: ShareDeepLinkPayload) => {});
- const warnLog: Array<{ obj: object; msg: string }> = [];
registerProtocolHandler({
app: env.app,
@@ -2554,7 +2581,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
sendShareDeepLink,
getFocusedWindow: () => focusedWin,
setTimeout: (cb, ms) => env.timers.push({ cb, ms }),
- log: { warn: (obj, msg) => warnLog.push({ obj, msg }) },
+ log: env.log,
});
env.app.resolveReady();
await flushPromises();
@@ -2565,7 +2592,7 @@ describe('registerProtocolHandler — continue-activity Handoff path', () => {
});
await flushPromises();
- const entry = warnLog.find((e) => e.msg.includes('continue-activity-received'));
+ const entry = env.warnLog.find((e) => e.msg.includes('continue-activity-received'));
expect(entry).toBeDefined();
expect(entry?.obj).toMatchObject({
type: 'NSUserActivityTypeBrowsingWeb',
diff --git a/packages/desktop/tests/smoke/deep-link.e2e.ts b/packages/desktop/tests/smoke/deep-link.e2e.ts
index 2af49c785..9ad276681 100644
--- a/packages/desktop/tests/smoke/deep-link.e2e.ts
+++ b/packages/desktop/tests/smoke/deep-link.e2e.ts
@@ -13,10 +13,8 @@
* real user click. That's what this test uses.
*
* True cold-start Apple-Event simulation (launching a not-yet-running app
- * via `open(1)` and asserting the queue-then-flush path delivers the URL)
- * is a deferred gap — it requires a signed/notarized DMG so macOS Launch
- * Services binds the scheme to this specific app bundle, rather than the
- * generic Electron shell.
+ * via `open(1)` and asserting the queue-then-flush path delivers the URL) is
+ * covered separately, in the packaged tier — see `cold-single-file-launch.e2e.ts`.
*
* Skip conditions:
* - Not on macOS (`process.platform !== 'darwin'`) — the `open` command