Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

PRD-8106 Make ok open cross-platform and spawn-safe (#3636)

mike-inkeep7e470fd84507
diff --git a/.changeset/cross-platform-open-launcher.md b/.changeset/cross-platform-open-launcher.md
new file mode 100644
index 000000000..11a505247
--- /dev/null
+++ b/.changeset/cross-platform-open-launcher.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Make `ok open` and `ok <file>` use platform-native launchers on macOS, Windows, and Linux, and report launcher failures instead of exiting successfully.
diff --git a/packages/cli/src/commands/open.test.ts b/packages/cli/src/commands/open.test.ts
index fed2eddde..0bde31119 100644
--- a/packages/cli/src/commands/open.test.ts
+++ b/packages/cli/src/commands/open.test.ts
@@ -16,7 +16,10 @@ 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: (t) => opened.push(t),
+ openTarget: async (t) => {
+ opened.push(t);
+ return { ok: true };
+ },
log: (m) => logs.push(m),
error: (m) => errors.push(m),
...overrides,
@@ -25,131 +28,147 @@ function makeDeps(overrides: Partial<OpenDeps> = {}): {
}
describe('runOpen', () => {
- test('doc with a desktop bundle → openknowledge:// deep link, exit 0', () => {
+ test('doc with a desktop bundle → openknowledge:// deep link, exit 0', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
- const code = runOpen('bim-brain/log', { project: '/abs/proj' }, deps);
+ const code = await runOpen('bim-brain/log', { project: '/abs/proj' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['openknowledge://open?project=%2Fabs%2Fproj&doc=bim-brain%2Flog']);
});
- test('doc, no bundle but UI running → browser route, exit 0', () => {
+ test('doc, no bundle but UI running → browser route, exit 0', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => null,
resolveBaseUrl: () => 'http://localhost:5173',
});
- const code = runOpen('specs/foo/SPEC', { project: '/p' }, deps);
+ const code = await runOpen('specs/foo/SPEC', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['http://localhost:5173/#/specs/foo/SPEC']);
});
- test('doc, neither desktop nor UI → error, exit 1, nothing opened', () => {
+ test('launcher failure returns exit 1 without printing a success message', async () => {
+ const { deps, logs, errors } = makeDeps({
+ detectBundlePath: () => null,
+ resolveBaseUrl: () => 'http://localhost:5173',
+ openTarget: async () => ({ ok: false, reason: 'not-installed' }),
+ });
+
+ const code = await runOpen('specs/foo/SPEC', { project: '/p' }, deps);
+
+ expect(code).toBe(1);
+ expect(logs).toHaveLength(0);
+ expect(errors).toHaveLength(1);
+ expect(errors[0]).toContain('Could not open http://localhost:5173/#/specs/foo/SPEC');
+ expect(errors[0]).toContain('is not installed or cannot be executed');
+ });
+
+ test('doc, neither desktop nor UI → error, exit 1, nothing opened', async () => {
const { deps, opened, errors } = makeDeps();
- const code = runOpen('foo', { project: '/p' }, deps);
+ const code = await runOpen('foo', { project: '/p' }, deps);
expect(code).toBe(1);
expect(opened).toEqual([]);
expect(errors).toHaveLength(1);
});
- test('folder with a desktop bundle → folder= deep link, exit 0', () => {
+ test('folder with a desktop bundle → folder= deep link, exit 0', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
- const code = runOpen('specs/foo/', { project: '/p' }, deps);
+ const code = await runOpen('specs/foo/', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['openknowledge://open?project=%2Fp&folder=specs%2Ffoo']);
});
- test('folder, no bundle but UI running → browser folder route, exit 0', () => {
+ test('folder, no bundle but UI running → browser folder route, exit 0', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => null,
resolveBaseUrl: () => 'http://localhost:5173',
});
- const code = runOpen('specs/foo/', { project: '/p' }, deps);
+ const code = await runOpen('specs/foo/', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['http://localhost:5173/#/specs/foo/']);
});
- test('auto-detects a folder from disk (no trailing slash needed)', () => {
+ test('auto-detects a folder from disk (no trailing slash needed)', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
classifyName: () => 'folder',
});
- const code = runOpen('specs/foo', { project: '/p' }, deps);
+ const code = await runOpen('specs/foo', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['openknowledge://open?project=%2Fp&folder=specs%2Ffoo']);
});
- test('trailing slash infers folder intent even when disk classify says doc', () => {
+ test('trailing slash infers folder intent even when disk classify says doc', async () => {
const { deps, opened } = makeDeps({
resolveBaseUrl: () => 'http://localhost:5173',
classifyName: () => 'doc',
});
- const code = runOpen('specs/foo/', {}, deps);
+ const code = await runOpen('specs/foo/', {}, deps);
expect(code).toBe(0);
expect(opened).toEqual(['http://localhost:5173/#/specs/foo/']);
});
- test('skill with a desktop bundle → rides doc=__skill__/<scope>/<name> deep link', () => {
+ test('skill with a desktop bundle → rides doc=__skill__/<scope>/<name> deep link', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
- const code = runOpen('trip-log', { skill: true, project: '/p' }, deps);
+ const code = await runOpen('trip-log', { skill: true, project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual([
'openknowledge://open?project=%2Fp&doc=__skill__%2Fproject%2Ftrip-log',
]);
});
- test('skill --scope global, no bundle but UI running → browser skill route', () => {
+ test('skill --scope global, no bundle but UI running → browser skill route', async () => {
const { deps, opened } = makeDeps({ resolveBaseUrl: () => 'http://localhost:5173' });
- const code = runOpen('trip-log', { skill: true, scope: 'global', project: '/p' }, deps);
+ const code = await runOpen('trip-log', { skill: true, scope: 'global', project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['http://localhost:5173/#/__skill__/global/trip-log']);
});
- test('skill with an invalid --scope → error, exit 1', () => {
+ test('skill with an invalid --scope → error, exit 1', async () => {
const { deps, errors } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
- const code = runOpen('trip-log', { skill: true, scope: 'nonsense', project: '/p' }, deps);
+ const code = await runOpen('trip-log', { skill: true, scope: 'nonsense', project: '/p' }, deps);
expect(code).toBe(1);
expect(errors).toHaveLength(1);
});
- test('skill, neither desktop nor UI → error, exit 1, nothing opened', () => {
+ test('skill, neither desktop nor UI → error, exit 1, nothing opened', async () => {
const { deps, opened, errors } = makeDeps();
- const code = runOpen('trip-log', { skill: true, project: '/p' }, deps);
+ const code = await runOpen('trip-log', { skill: true, project: '/p' }, deps);
expect(code).toBe(1);
expect(opened).toEqual([]);
expect(errors).toHaveLength(1);
});
- test('skill name with a traversal/unsafe segment → error before any open', () => {
+ test('skill name with a traversal/unsafe segment → error before any open', async () => {
// The unsafe-name guard runs before the skill branch, so a malicious skill
// name can't slip into the synthetic `__skill__/<scope>/<name>` target.
const { deps, opened, errors } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
for (const bad of ['../../etc', '/abs', 'a\\b']) {
- const code = runOpen(bad, { skill: true, project: '/p' }, deps);
+ const code = await runOpen(bad, { skill: true, project: '/p' }, deps);
expect(code).toBe(1);
}
expect(opened).toEqual([]);
expect(errors.length).toBeGreaterThanOrEqual(3);
});
- test('folder with no UI running → error, exit 1', () => {
+ test('folder with no UI running → error, exit 1', async () => {
const { deps, errors } = makeDeps({ resolveBaseUrl: () => null });
- const code = runOpen('specs/foo/', { project: '/p' }, deps);
+ const code = await runOpen('specs/foo/', { project: '/p' }, deps);
expect(code).toBe(1);
expect(errors).toHaveLength(1);
});
- test('empty target (bare slash) → error, exit 1', () => {
+ test('empty target (bare slash) → error, exit 1', async () => {
const { deps, errors } = makeDeps();
- const code = runOpen('/', {}, deps);
+ const code = await runOpen('/', {}, deps);
expect(code).toBe(1);
expect(errors).toHaveLength(1);
});
@@ -159,19 +178,19 @@ describe('runOpen', () => {
['nested ..', 'a/../b'],
['leading slash', '/abs/doc'],
['backslash', 'a\\b'],
- ])('rejects names the desktop parser would drop (%s) instead of false success', (_label, name) => {
+ ])('rejects names the desktop parser would drop (%s) instead of false success', async (_label, name) => {
const { deps, opened, errors } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
- const code = runOpen(name, { project: '/p' }, deps);
+ const code = await runOpen(name, { project: '/p' }, deps);
expect(code).toBe(1);
expect(opened).toEqual([]);
expect(errors).toHaveLength(1);
});
- test('rejects unsafe folder names too', () => {
+ test('rejects unsafe folder names too', async () => {
const { deps, opened, errors } = makeDeps({ resolveBaseUrl: () => 'http://localhost:5173' });
- const code = runOpen('specs/..', { project: '/p' }, deps);
+ const code = await runOpen('specs/..', { project: '/p' }, deps);
expect(code).toBe(1);
expect(opened).toEqual([]);
expect(errors).toHaveLength(1);
@@ -180,18 +199,18 @@ describe('runOpen', () => {
// The deep-link path (encodeURIComponent) and the browser-route path
// (encodeDocName, per-segment) intentionally diverge on `/`: the deep link
// encodes it to %2F, the browser route preserves it as a path separator.
- test('doc deep link encodes the whole name including the slash (%2F)', () => {
+ test('doc deep link encodes the whole name including the slash (%2F)', async () => {
const { deps, opened } = makeDeps({
detectBundlePath: () => '/Applications/OpenKnowledge.app',
});
- const code = runOpen('notes/My Doc#1', { project: '/p' }, deps);
+ const code = await runOpen('notes/My Doc#1', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['openknowledge://open?project=%2Fp&doc=notes%2FMy%20Doc%231']);
});
- test('browser route encodes per-segment, preserving the slash', () => {
+ test('browser route encodes per-segment, preserving the slash', async () => {
const { deps, opened } = makeDeps({ resolveBaseUrl: () => 'http://localhost:5173' });
- const code = runOpen('notes/My Doc#1', { project: '/p' }, deps);
+ const code = await runOpen('notes/My Doc#1', { project: '/p' }, deps);
expect(code).toBe(0);
expect(opened).toEqual(['http://localhost:5173/#/notes/My%20Doc%231']);
});
diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts
index 3c070ec65..427a259a2 100644
--- a/packages/cli/src/commands/open.ts
+++ b/packages/cli/src/commands/open.ts
@@ -23,9 +23,9 @@
* is needed — the renderer resolves it via `docNameFromHash`.)
*
* Desktop presence comes from `detectDesktop().bundlePath`, populated whenever a
- * bundle is installed on macOS and `OK_FORCE_BROWSER` is unset — including
+ * desktop executable is installed and `OK_FORCE_BROWSER` is unset — including
* non-TTY/headless invocations (an agent shelling out). The verb spawns its own
- * `open "<url>"` (LaunchServices) rather than `launchDesktop`.
+ * platform-native URL handler rather than `launchDesktop`.
*/
import { statSync } from 'node:fs';
import { join, resolve } from 'node:path';
@@ -38,7 +38,8 @@ import {
resolveUiInfo,
} from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
-import { spawnDetachedScrubbed } from '../utils/detached-spawn.ts';
+import type { SpawnDetachedScrubbedOutcome } from '../utils/detached-spawn.ts';
+import { openTargetFailureMessage, openTarget as openTargetReal } from '../utils/open-target.ts';
import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';
export interface OpenOptions {
@@ -66,7 +67,7 @@ export interface OpenDeps {
*/
classifyName: (projectDir: string, name: string) => 'doc' | 'folder';
/** Hand a URL or `openknowledge://` deep link to the OS to open. */
- openTarget: (target: string) => void;
+ openTarget: (target: string) => Promise<SpawnDetachedScrubbedOutcome>;
log: (message: string) => void;
error: (message: string) => void;
}
@@ -101,9 +102,7 @@ export function createRealOpenDeps(
return 'doc';
}
},
- openTarget: (target) => {
- spawnDetachedScrubbed('open', [target]);
- },
+ openTarget: openTargetReal,
log: (message) => process.stdout.write(`${message}\n`),
error: (message) => process.stderr.write(`${message}\n`),
};
@@ -123,17 +122,18 @@ function noTargetError(deps: OpenDeps): number {
return 1;
}
-/** Build + open an `openknowledge://open` deep link to the desktop app. */
-function openDesktopDeepLink(
- projectDir: string,
- param: 'doc' | 'folder',
+async function openAndReport(
target: string,
+ successMessage: string,
deps: OpenDeps,
-): void {
- const deepLink = `openknowledge://open?project=${encodeURIComponent(
- projectDir,
- )}&${param}=${encodeURIComponent(target)}`;
- deps.openTarget(deepLink);
+): Promise<number> {
+ const outcome = await deps.openTarget(target);
+ if (!outcome.ok) {
+ deps.error(`Could not open ${target}: ${openTargetFailureMessage(outcome.reason, target)}.`);
+ return 1;
+ }
+ deps.log(successMessage);
+ return 0;
}
/**
@@ -143,7 +143,7 @@ function openDesktopDeepLink(
* Does not check that a doc exists — "open `<doc>`" on a not-yet-created doc
* lands on the renderer route, which resolves missing targets.
*/
-export function runOpen(name: string, options: OpenOptions, deps: OpenDeps): number {
+export async function runOpen(name: string, options: OpenOptions, deps: OpenDeps): Promise<number> {
const projectDir = resolve(options.project ?? process.cwd());
const cleanName = name.replace(/\/+$/, '');
@@ -180,16 +180,23 @@ export function runOpen(name: string, options: OpenOptions, deps: OpenDeps): num
// the synthetic name needs no pre-encoding here.
const bundlePath = deps.detectBundlePath();
if (bundlePath) {
- openDesktopDeepLink(projectDir, 'doc', `__skill__/${scope}/${cleanName}`, deps);
- deps.log(`Opening skill ${cleanName} (${scope}) in the OpenKnowledge desktop app.`);
- return 0;
+ const deepLink = `openknowledge://open?project=${encodeURIComponent(
+ projectDir,
+ )}&doc=${encodeURIComponent(`__skill__/${scope}/${cleanName}`)}`;
+ return openAndReport(
+ deepLink,
+ `Opening skill ${cleanName} (${scope}) in the OpenKnowledge desktop app.`,
+ deps,
+ );
}
const baseUrl = deps.resolveBaseUrl(projectDir);
if (baseUrl) {
const url = `${baseUrl}/#/${encodeSkillRoute(scope, cleanName)}`;
- deps.openTarget(url);
- deps.log(`Opening skill ${cleanName} (${scope}) in your browser: ${url}`);
- return 0;
+ return openAndReport(
+ url,
+ `Opening skill ${cleanName} (${scope}) in your browser: ${url}`,
+ deps,
+ );
}
return noTargetError(deps);
}
@@ -200,32 +207,34 @@ export function runOpen(name: string, options: OpenOptions, deps: OpenDeps): num
const bundlePath = deps.detectBundlePath();
if (isFolder) {
if (bundlePath) {
- openDesktopDeepLink(projectDir, 'folder', cleanName, deps);
- deps.log(`Opening folder ${cleanName} in the OpenKnowledge desktop app.`);
- return 0;
+ const deepLink = `openknowledge://open?project=${encodeURIComponent(
+ projectDir,
+ )}&folder=${encodeURIComponent(cleanName)}`;
+ return openAndReport(
+ deepLink,
+ `Opening folder ${cleanName} in the OpenKnowledge desktop app.`,
+ deps,
+ );
}
const baseUrl = deps.resolveBaseUrl(projectDir);
if (baseUrl) {
const url = `${baseUrl}/#/${encodeFolderRoute(cleanName)}`;
- deps.openTarget(url);
- deps.log(`Opening folder ${cleanName} in your browser: ${url}`);
- return 0;
+ return openAndReport(url, `Opening folder ${cleanName} in your browser: ${url}`, deps);
}
return noTargetError(deps);
}
// Doc.
if (bundlePath) {
- openDesktopDeepLink(projectDir, 'doc', cleanName, deps);
- deps.log(`Opening ${cleanName} in the OpenKnowledge desktop app.`);
- return 0;
+ const deepLink = `openknowledge://open?project=${encodeURIComponent(
+ projectDir,
+ )}&doc=${encodeURIComponent(cleanName)}`;
+ return openAndReport(deepLink, `Opening ${cleanName} in the OpenKnowledge desktop app.`, deps);
}
const baseUrl = deps.resolveBaseUrl(projectDir);
if (baseUrl) {
const url = `${baseUrl}/#/${encodeDocName(cleanName)}`;
- deps.openTarget(url);
- deps.log(`Opening ${cleanName} in your browser: ${url}`);
- return 0;
+ return openAndReport(url, `Opening ${cleanName} in your browser: ${url}`, deps);
}
return noTargetError(deps);
}
@@ -247,7 +256,7 @@ export function openCommand(): Command {
'project',
)
.option('--project <dir>', 'Project root (defaults to the current directory)')
- .action((name: string, options: OpenOptions) => {
- process.exitCode = runOpen(name, options, createRealOpenDeps());
+ .action(async (name: string, options: OpenOptions) => {
+ process.exitCode = await runOpen(name, options, createRealOpenDeps());
});
}
diff --git a/packages/cli/src/commands/single-file-open.test.ts b/packages/cli/src/commands/single-file-open.test.ts
index 61c50a031..c3efd3507 100644
--- a/packages/cli/src/commands/single-file-open.test.ts
+++ b/packages/cli/src/commands/single-file-open.test.ts
@@ -31,14 +31,23 @@ function makeDeps(
return overrides.plan;
},
detectBundlePath: overrides.detectBundlePath ?? (() => null),
- openTarget: (t) => rec.openTargets.push(t),
- runProjectOpen: (docName, projectRoot) => {
- rec.projectOpens.push({ docName, projectRoot });
- return 0;
- },
- runBrowserOpen: async (plan) => {
- rec.browserOpens.push(plan);
- },
+ openTarget:
+ overrides.openTarget ??
+ (async (t) => {
+ rec.openTargets.push(t);
+ return { ok: true };
+ }),
+ runProjectOpen:
+ overrides.runProjectOpen ??
+ (async (docName, projectRoot) => {
+ rec.projectOpens.push({ docName, projectRoot });
+ return 0;
+ }),
+ runBrowserOpen:
+ overrides.runBrowserOpen ??
+ (async (plan) => {
+ rec.browserOpens.push(plan);
+ }),
log: (m) => rec.logs.push(m),
error: (m) => rec.errors.push(m),
};
@@ -82,6 +91,21 @@ describe('runSingleFileOpen', () => {
expect(rec.browserOpens).toHaveLength(0);
});
+ test('ephemeral mode reports launcher failures as exit code 1', async () => {
+ const { deps, rec } = makeDeps({
+ plan: ephemeralPlan,
+ detectBundlePath: () => '/Applications/OpenKnowledge.app',
+ openTarget: async () => ({ ok: false, reason: 'not-installed' }),
+ });
+
+ const code = await runSingleFileOpen('/Users/me/notes/todo.md', deps);
+
+ expect(code).toBe(1);
+ expect(rec.logs).toHaveLength(0);
+ expect(rec.errors).toHaveLength(1);
+ expect(rec.errors[0]).toContain('is not installed or cannot be executed');
+ });
+
test('ephemeral mode with no desktop bundle falls back to the browser session', async () => {
const { deps, rec } = makeDeps({ plan: ephemeralPlan, detectBundlePath: () => null });
await runSingleFileOpen('/Users/me/notes/todo.md', deps);
diff --git a/packages/cli/src/commands/single-file-open.ts b/packages/cli/src/commands/single-file-open.ts
index 867d0b323..985e6f8d2 100644
--- a/packages/cli/src/commands/single-file-open.ts
+++ b/packages/cli/src/commands/single-file-open.ts
@@ -22,7 +22,8 @@ import {
SingleFileNotMarkdownError,
type SingleFileOpenPlan,
} from '@inkeep/open-knowledge-server';
-import { spawnDetachedScrubbed } from '../utils/detached-spawn.ts';
+import type { SpawnDetachedScrubbedOutcome } from '../utils/detached-spawn.ts';
+import { openTargetFailureMessage, openTarget as openTargetReal } from '../utils/open-target.ts';
import { createRealDetectDeps, type DetectResult, detectDesktop } from './desktop-dispatch.ts';
import { createRealOpenDeps, runOpen } from './open.ts';
@@ -41,9 +42,9 @@ export interface SingleFileOpenDeps {
/** 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) => void;
+ openTarget: (target: string) => Promise<SpawnDetachedScrubbedOutcome>;
/** Reuse `ok open`'s project-mode deep-link/browser path. Returns exit code. */
- runProjectOpen: (docName: string, projectRoot: string) => number;
+ runProjectOpen: (docName: string, projectRoot: string) => Promise<number>;
/** Browser fallback — boot an ephemeral single-file server + open a tab. */
runBrowserOpen: (plan: Extract<SingleFileOpenPlan, { mode: 'ephemeral' }>) => Promise<void>;
log: (message: string) => void;
@@ -56,9 +57,7 @@ export function createRealSingleFileOpenDeps(
return {
prepare: prepareSingleFileOpen,
detectBundlePath: () => detect().bundlePath ?? null,
- openTarget: (target) => {
- spawnDetachedScrubbed('open', [target]);
- },
+ openTarget: openTargetReal,
runProjectOpen: (docName, projectRoot) =>
runOpen(docName, { project: projectRoot }, createRealOpenDeps()),
runBrowserOpen: (plan) => runSingleFileBrowserOpen(plan),
@@ -96,7 +95,7 @@ export async function runSingleFileOpen(
if (plan.mode === 'project') {
// Reuse the existing `ok open` project-doc path (desktop deep-link →
// browser fallback). Mostly unchanged behavior.
- return deps.runProjectOpen(plan.docName, plan.projectRoot);
+ return await deps.runProjectOpen(plan.docName, plan.projectRoot);
}
// No-project ephemeral mode. Desktop owns the server lifecycle (deterministic
@@ -106,7 +105,16 @@ export async function runSingleFileOpen(
const bundlePath = deps.detectBundlePath();
if (bundlePath) {
const deepLink = `openknowledge://open?file=${encodeURIComponent(plan.canonicalFilePath)}`;
- deps.openTarget(deepLink);
+ const outcome = await deps.openTarget(deepLink);
+ if (!outcome.ok) {
+ deps.error(
+ `Could not open the OpenKnowledge desktop app: ${openTargetFailureMessage(
+ outcome.reason,
+ deepLink,
+ )}.`,
+ );
+ return 1;
+ }
deps.log(`Opening ${plan.singleDocRelPath} in the OpenKnowledge desktop app.`);
return 0;
}
diff --git a/packages/cli/src/utils/detached-spawn.test.ts b/packages/cli/src/utils/detached-spawn.test.ts
index 882d77bf0..e61055ede 100644
--- a/packages/cli/src/utils/detached-spawn.test.ts
+++ b/packages/cli/src/utils/detached-spawn.test.ts
@@ -1,6 +1,7 @@
-import type { SpawnOptions } from 'node:child_process';
+import type { ChildProcess, SpawnOptions } from 'node:child_process';
+import { EventEmitter } from 'node:events';
import { describe, expect, test } from 'vitest';
-import { spawnDetachedScrubbed } from './detached-spawn.ts';
+import { spawnDetachedScrubbed, spawnDetachedScrubbedAndWait } from './detached-spawn.ts';
describe('spawnDetachedScrubbed', () => {
interface Captured {
@@ -64,4 +65,33 @@ describe('spawnDetachedScrubbed', () => {
else process.env.ELECTRON_RUN_AS_NODE = prevValue;
}
});
+
+ test('a real ENOENT spawn resolves as not-installed instead of crashing Node', async () => {
+ const outcome = await spawnDetachedScrubbedAndWait(
+ '/nonexistent/ok-launcher-that-does-not-exist',
+ [],
+ );
+
+ expect(outcome).toEqual({ ok: false, reason: 'not-installed' });
+ });
+
+ test('unrefs a child even when neither process signal arrives before timeout', async () => {
+ let unrefCalled = false;
+ const spawn = (() => {
+ const child = new EventEmitter() as ChildProcess;
+ child.unref = () => {
+ unrefCalled = true;
+ return child;
+ };
+ return child;
+ }) as typeof import('node:child_process').spawn;
+
+ const outcome = await spawnDetachedScrubbedAndWait('launcher', [], {
+ spawn,
+ timeoutMs: 1,
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'timeout' });
+ expect(unrefCalled).toBe(true);
+ });
});
diff --git a/packages/cli/src/utils/detached-spawn.ts b/packages/cli/src/utils/detached-spawn.ts
index 962f7051a..f88ec959a 100644
--- a/packages/cli/src/utils/detached-spawn.ts
+++ b/packages/cli/src/utils/detached-spawn.ts
@@ -37,6 +37,31 @@ export interface SpawnDetachedScrubbedOptions {
env?: NodeJS.ProcessEnv;
}
+export interface SpawnDetachedScrubbedAndWaitOptions extends SpawnDetachedScrubbedOptions {
+ /** Deadline for receiving the child process's first `spawn` or `error` signal. */
+ timeoutMs?: number;
+}
+
+export type SpawnDetachedScrubbedOutcome =
+ | { ok: true }
+ | { ok: false; reason: 'not-installed' | 'timeout' | 'spawn-error' };
+
+function classifySpawnError(err: unknown): SpawnDetachedScrubbedOutcome {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return code === 'ENOENT' || code === 'EACCES' || code === 'EPERM'
+ ? { ok: false, reason: 'not-installed' }
+ : { ok: false, reason: 'spawn-error' };
+}
+
+function detachedSpawnOptions(env: NodeJS.ProcessEnv): Parameters<typeof nativeSpawn>[2] {
+ return withHiddenWindowsConsole({
+ detached: true,
+ stdio: 'ignore' as const,
+ shell: false,
+ env: scrubElectronRunAsNode(env),
+ });
+}
+
/**
* Spawn `command` detached (own process group, no stdio ties, `unref()`ed so
* the CLI's event loop can drain) with `ELECTRON_RUN_AS_NODE` scrubbed from
@@ -49,15 +74,53 @@ export function spawnDetachedScrubbed(
opts: SpawnDetachedScrubbedOptions = {},
): ChildProcess {
const spawnFn = opts.spawn ?? nativeSpawn;
- const child = spawnFn(
- command,
- [...args],
- withHiddenWindowsConsole({
- detached: true,
- stdio: 'ignore' as const,
- env: scrubElectronRunAsNode(opts.env ?? process.env),
- }),
- );
+ const child = spawnFn(command, [...args], detachedSpawnOptions(opts.env ?? process.env));
child.unref();
return child;
}
+
+/**
+ * Spawn with the same detached + scrubbed contract, but wait for Node's first
+ * process signal before reporting success. OS process creation is an external
+ * trust boundary: synchronous throws and asynchronous `error` events are both
+ * converted to a typed result so callers cannot print success before the
+ * launcher has actually started.
+ */
+export function spawnDetachedScrubbedAndWait(
+ command: string,
+ args: readonly string[],
+ opts: SpawnDetachedScrubbedAndWaitOptions = {},
+): Promise<SpawnDetachedScrubbedOutcome> {
+ const spawnFn = opts.spawn ?? nativeSpawn;
+ const timeoutMs = opts.timeoutMs ?? 2_000;
+
+ return new Promise((resolve) => {
+ let settled = false;
+ const settle = (outcome: SpawnDetachedScrubbedOutcome): void => {
+ if (settled) return;
+ settled = true;
+ resolve(outcome);
+ };
+ const timer = setTimeout(() => settle({ ok: false, reason: 'timeout' }), timeoutMs);
+
+ try {
+ const child = spawnFn(command, [...args], detachedSpawnOptions(opts.env ?? process.env));
+ child.once('error', (err) => {
+ clearTimeout(timer);
+ settle(classifySpawnError(err));
+ });
+ child.once('spawn', () => {
+ clearTimeout(timer);
+ settle({ ok: true });
+ });
+ try {
+ child.unref();
+ } catch {
+ // The child may have exited before its first process signal.
+ }
+ } catch (err) {
+ clearTimeout(timer);
+ settle(classifySpawnError(err));
+ }
+ });
+}
diff --git a/packages/cli/src/utils/open-target.test.ts b/packages/cli/src/utils/open-target.test.ts
new file mode 100644
index 000000000..7d949d73a
--- /dev/null
+++ b/packages/cli/src/utils/open-target.test.ts
@@ -0,0 +1,99 @@
+import type { ChildProcess, SpawnOptions } from 'node:child_process';
+import { EventEmitter } from 'node:events';
+import { describe, expect, test, vi } from 'vitest';
+import { openTarget } from './open-target.ts';
+
+interface SpawnCapture {
+ command?: string;
+ args?: readonly string[];
+ options?: SpawnOptions;
+}
+
+function makeSpawn(
+ capture: SpawnCapture,
+ signal: { type: 'spawn' } | { type: 'error'; error: NodeJS.ErrnoException },
+) {
+ return ((command: string, args: readonly string[], options: SpawnOptions) => {
+ capture.command = command;
+ capture.args = args;
+ capture.options = options;
+
+ const child = new EventEmitter() as ChildProcess;
+ child.unref = vi.fn(() => child);
+ queueMicrotask(() =>
+ child.emit(signal.type, signal.type === 'error' ? signal.error : undefined),
+ );
+ return child;
+ }) as typeof import('node:child_process').spawn;
+}
+
+describe('openTarget', () => {
+ test('macOS dispatches through LaunchServices', async () => {
+ const capture: SpawnCapture = {};
+ const target = 'openknowledge://open?project=%2FUsers%2Fme%2Fnotes&doc=specs%2Flaunch';
+
+ const outcome = await openTarget(target, {
+ platform: 'darwin',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('/usr/bin/open');
+ expect(capture.args).toEqual([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';
+
+ const outcome = await openTarget(target, {
+ platform: 'win32',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('rundll32.exe');
+ expect(capture.args).toEqual(['url.dll,FileProtocolHandler', target]);
+ expect(capture.options?.shell).toBe(false);
+ });
+
+ test('Windows preserves browser URL fragments through Explorer', async () => {
+ const capture: SpawnCapture = {};
+ const target = 'http://localhost:5173/#/specs/launch?mode=source&line=12';
+
+ const outcome = await openTarget(target, {
+ platform: 'win32',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('explorer.exe');
+ expect(capture.args).toEqual([target]);
+ expect(capture.options?.shell).toBe(false);
+ });
+
+ test('Linux dispatches through xdg-open', async () => {
+ const capture: SpawnCapture = {};
+ const target = 'https://localhost:5173/#/specs/foo';
+
+ const outcome = await openTarget(target, {
+ platform: 'linux',
+ spawn: makeSpawn(capture, { type: 'spawn' }),
+ });
+
+ expect(outcome).toEqual({ ok: true });
+ expect(capture.command).toBe('xdg-open');
+ expect(capture.args).toEqual([target]);
+ });
+
+ test('launcher spawn failures return a non-success outcome', async () => {
+ const error = Object.assign(new Error('spawn xdg-open ENOENT'), { code: 'ENOENT' });
+
+ const outcome = await openTarget('https://localhost:5173', {
+ platform: 'linux',
+ spawn: makeSpawn({}, { type: 'error', error }),
+ });
+
+ expect(outcome).toEqual({ ok: false, reason: 'not-installed' });
+ });
+});
diff --git a/packages/cli/src/utils/open-target.ts b/packages/cli/src/utils/open-target.ts
new file mode 100644
index 000000000..536a7a2bf
--- /dev/null
+++ b/packages/cli/src/utils/open-target.ts
@@ -0,0 +1,63 @@
+/**
+ * Hand an HTTP(S) URL or custom-scheme deep link to the platform's registered
+ * handler, and report whether the launcher process started successfully.
+ */
+import type { spawn as NativeSpawn } from 'node:child_process';
+import {
+ type SpawnDetachedScrubbedOutcome,
+ spawnDetachedScrubbedAndWait,
+} from './detached-spawn.ts';
+
+export interface OpenTargetOptions {
+ platform?: NodeJS.Platform;
+ spawn?: typeof NativeSpawn;
+ env?: NodeJS.ProcessEnv;
+ timeoutMs?: number;
+}
+
+interface OpenInvocation {
+ command: string;
+ args: readonly string[];
+}
+
+function resolveOpenInvocation(target: string, platform: NodeJS.Platform): OpenInvocation {
+ if (platform === 'darwin') return { command: '/usr/bin/open', args: [target] };
+ if (platform === 'win32') {
+ if (target.startsWith('http://') || target.startsWith('https://')) {
+ return { command: 'explorer.exe', args: [target] };
+ }
+ return {
+ command: 'rundll32.exe',
+ args: ['url.dll,FileProtocolHandler', target],
+ };
+ }
+ return { command: 'xdg-open', args: [target] };
+}
+
+export function openTarget(
+ target: string,
+ options: OpenTargetOptions = {},
+): Promise<SpawnDetachedScrubbedOutcome> {
+ const invocation = resolveOpenInvocation(target, options.platform ?? process.platform);
+ return spawnDetachedScrubbedAndWait(invocation.command, invocation.args, {
+ spawn: options.spawn,
+ env: options.env,
+ timeoutMs: options.timeoutMs,
+ });
+}
+
+export function openTargetFailureMessage(
+ reason: Exclude<SpawnDetachedScrubbedOutcome, { ok: true }>['reason'],
+ target: string,
+ platform: NodeJS.Platform = process.platform,
+): string {
+ const launcher = resolveOpenInvocation(target, platform).command;
+ switch (reason) {
+ case 'not-installed':
+ return `${launcher} is not installed or cannot be executed`;
+ case 'timeout':
+ return `${launcher} did not start in time`;
+ case 'spawn-error':
+ return `${launcher} could not be started`;
+ }
+}