Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): PRD-8496 run OK-spawned children with the PATH the app grants its own shells (#4360)

serafin-garcia74a5ea4d5091
diff --git a/.changeset/ok-bin-on-spawned-child-path.md b/.changeset/ok-bin-on-spawned-child-path.md
new file mode 100644
index 000000000..b7241ad4f
--- /dev/null
+++ b/.changeset/ok-bin-on-spawned-child-path.md
@@ -0,0 +1,19 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+CLIs installed in `~/.ok/bin` are now found and launchable even when the shell PATH block was declined or deleted.
+
+On macOS and Linux (packaged builds, not AppImage runs), OpenKnowledge creates `~/.ok/bin` and puts its own `ok` command there whether or not you let it edit your shell startup files, and the built-in terminal already ran with that directory on its PATH. The checks that decide whether a CLI is installed did not. A tool sitting in `~/.ok/bin` therefore read as missing, so Settings offered install instructions for a command the app could already run, and the toolbar control that would have launched it stayed hidden. Slidev was the reported case. Claude, Codex, and every other terminal CLI were affected the same way.
+
+The presence checks, the Slidev launch, and the CLI launches the built-in terminal starts for you now compose their child environment through the same helper, so all three put the same OK-managed directory first on their child's PATH. All three also reassert that directory after your startup files have run, so a startup file that replaces PATH can no longer hide the installed command. The reassert skips the directory when it is already there, matching the rule the environment layer follows, so it appears once rather than twice and your own PATH ordering is left alone. Commands you type yourself in the terminal are not reasserted and keep your PATH exactly as your startup files left it.
+
+Presence checks and global Slidev launches now run the same shell mode as the built-in terminal. On macOS that is a login interactive shell, unchanged. On Linux it is an interactive shell, which is what the terminal already used and what the desktop convention expects, so a `slidev` shell function or alias defined in `~/.bashrc` is now both detected and launchable rather than detected and then failing with `command not found`.
+
+The tradeoff on Linux is that a global deck launch is no longer a login shell, so anything set only in your shell's login-only startup files (a proxy, a `JAVA_HOME`, a version manager init) no longer reaches the deck. For `bash` those are `/etc/profile`, `/etc/profile.d/`, `~/.profile` and `~/.bash_profile`, and for `zsh` they are `/etc/zprofile` and `~/.zprofile`. Move the setting to the file your shell reads for every interactive session, `~/.bashrc` for `bash` or `~/.zshrc` for `zsh`, if your deck's toolchain needs it.
+
+Global Slidev launches also disable shell job control before starting the deck, so closing a slides window reliably stops the dev server instead of leaving it running and holding its port. POSIX shells get `set +m` and `fish` gets `status job-control none`, both emitted after your startup files have run so a startup file cannot turn job control back on. A `fish` deck was already contained at fish's default job-control mode, but a `config.fish` that sets `status job-control full` took that away, and the opt-out now covers that case too.
+
+A CLI-presence check and a Slidev dev server are no longer told they are the OpenKnowledge terminal. Launching the app from inside the built-in terminal used to pass that marker down to them, which made agent skills treat a probe or a preview server as a hosted agent session. The terminal itself still carries the marker.
+
+Windows never had the reported bug: there the installer puts the CLI on your PATH itself rather than through a `~/.ok/bin` shim, so those checks already saw it. Windows does pick up two changes from the same work. The presence checks now run with the app's own bundled CLI directory ahead of the PATH they inherit, and the Slidev launch now writes its composed PATH under the variable name Windows actually uses, instead of adding a second, empty one beside it.
diff --git a/docs/content/migrate/notion.mdx b/docs/content/migrate/notion.mdx
index b1d429dc4..6711fa86f 100644
--- a/docs/content/migrate/notion.mdx
+++ b/docs/content/migrate/notion.mdx
@@ -42,12 +42,13 @@ ok migrate notion /path/to/unzipped-export --apply
```
<Callout type="info">
- The desktop app ships the `ok` CLI. The Windows installer and the Linux
- packages put it on your `PATH` on their own. On macOS it installs to
- `$HOME/.ok/bin`, and a pre-checked toggle in the first-launch dialog puts it
- on your `PATH` — if `ok` isn't found, add it from **File → Set up
- OpenKnowledge integrations…**, then open a new terminal window. If it's
- still missing, add `$HOME/.ok/bin` to your `PATH` manually.
+ The desktop app ships the `ok` CLI. The Windows installer puts it on your
+ `PATH` on its own. On macOS and Linux it installs to `$HOME/.ok/bin`, and a
+ pre-checked toggle in the first-launch dialog puts it on your `PATH` (on
+ Linux the package's install script also links `/usr/bin/ok` either way). If
+ `ok` isn't found, add it from **File → Set up OpenKnowledge
+ integrations…**, then open a new terminal window. If it's still missing,
+ add `$HOME/.ok/bin` to your `PATH` manually.
</Callout>
Every transform is **idempotent**, so re-running is safe. See the tables below for a full list of differences between the Notion export and what OpenKnowledge supports.
diff --git a/docs/content/plugins/slidev.mdx b/docs/content/plugins/slidev.mdx
index 690d210fc..b11a8b2c4 100644
--- a/docs/content/plugins/slidev.mdx
+++ b/docs/content/plugins/slidev.mdx
@@ -60,6 +60,12 @@ Edit the document and the open deck updates — Slidev watches the same file Ope
Closing a deck window stops that deck's Slidev process. Quitting OpenKnowledge stops all of them.
+## Environment for the deck process
+
+A globally installed Slidev is started through your shell on macOS and Linux, so the `PATH` and the variables your startup files set are what the deck sees. A project-local install is started directly, without a shell, so startup files do not apply to it. On Windows both are run through `cmd.exe` with AutoRun disabled, so no shell startup file reaches the deck either way.
+
+On Linux that shell is interactive but not a login shell. Variables set only in your shell's login-only startup files (a proxy, a `JAVA_HOME`, a version manager init) do not reach the deck. For `bash` those are `/etc/profile`, `/etc/profile.d/`, `~/.profile` and `~/.bash_profile`, and for `zsh` they are `/etc/zprofile` and `~/.zprofile`. Put them in the file your shell reads for every interactive session (`~/.bashrc` for `bash`, `~/.zshrc` for `zsh`) if your deck's toolchain needs them. On macOS the deck runs in a login interactive shell, so every startup file applies.
+
## Writing decks
Past the frontmatter flag it's ordinary Slidev:
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 8d24188aa..73b34ffe1 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -32,7 +32,7 @@ How the app lands depends on your platform:
- **macOS** — a signed `.dmg` you drag into `/Applications`. Because a `.dmg` app can't put a CLI on your `PATH` on its own, first launch asks, in one dialog, whether to register the MCP server with your AI editors and whether to add `ok` to your shell's `PATH` (both covered below, both with your consent).
- **Windows** — a per-user installer: the app lands under `%LOCALAPPDATA%\Programs\`, with no admin prompt. The installer itself adds the bundled `ok` CLI to your **user** `PATH` (a registry value under `HKCU\Environment`) and registers the `openknowledge://` URL scheme under `HKCU\Software\Classes` — both removed by its uninstaller. It also registers OpenKnowledge for `.md` and `.mdx` files under `HKCU\Software\Classes`, which can make it the default opener when you have not explicitly chosen one in Windows. Uninstall removes its Open With and file-handler registrations but does not restore a previous file-type default. To choose another opener, use **Settings → Apps → Default apps**. Your shell startup files are never touched.
-- **Linux** — a deb or rpm package: the app installs to `/opt/OpenKnowledge/`, and the package's post-install script symlinks `/usr/bin/ok`, `/usr/bin/open-knowledge`, and `/usr/bin/openknowledge` (plus a desktop entry that registers the `openknowledge://` scheme, and an AppArmor profile on Ubuntu 24.04+ so the Chromium sandbox keeps working). Your shell startup files are never touched.
+- **Linux** — a deb or rpm package: the app installs to `/opt/OpenKnowledge/`, and the package's post-install script symlinks `/usr/bin/ok`, `/usr/bin/open-knowledge`, and `/usr/bin/openknowledge` (plus a desktop entry that registers the `openknowledge://` scheme, and an AppArmor profile on Ubuntu 24.04+ so the Chromium sandbox keeps working). Your shell startup files are touched only with your consent, as described below.
On every platform the app writes app-level state and logs on launch. The table below shows the macOS locations; on Windows the same app-state files live under `%APPDATA%\OpenKnowledge\` and staged updates under `%LOCALAPPDATA%\@inkeepopen-knowledge-desktop-updater\`. On Linux, app state defaults to `~/.config/OpenKnowledge/` and staged updates to `~/.cache/@inkeepopen-knowledge-desktop-updater/` (or the corresponding XDG config and cache directories). The `~/.ok/` paths are the same everywhere.
@@ -56,7 +56,7 @@ On its first launch the app also opens your default browser once to `openknowled
### Shell and `PATH`
-So `ok` can work in your terminal too, the packaged app manages a `PATH` shim. **This is macOS-only, packaged-build-only, and disabled by `OK_RECLAIM_DISABLE=1`.** It never uses `sudo`, never runs an admin prompt, and never installs a login item. (Windows and Linux don't need it: the Windows installer adds the bundled CLI to your user `PATH` itself, and the Linux packages place `/usr/bin/ok` directly — neither ever edits your shell files.)
+So `ok` can work in your terminal too, the packaged app manages a `PATH` shim. **This is macOS and Linux only, packaged-build-only, and disabled by `OK_RECLAIM_DISABLE=1`.** It never uses `sudo`, never runs an admin prompt, and never installs a login item. (Windows doesn't need it: the Windows installer adds the bundled CLI to your user `PATH` itself, and never edits your shell files. OpenKnowledge no longer ships a Linux AppImage, but a build launched from one skips the shim too, because an AppImage has no fixed install location to link to.)
The first two rows below live in OpenKnowledge's own `~/.ok/` directory and are maintained automatically. The third — the only write into files OpenKnowledge doesn't own — happens **only with your consent**: the first-launch dialog has an "Add the `ok` command to your terminal" toggle (checked by default), and nothing is written to your shell config if you uncheck it.
@@ -64,7 +64,7 @@ The first two rows below live in OpenKnowledge's own `~/.ok/` directory and are
| --- | --- | --- |
| `~/.ok/bin/ok`, `~/.ok/bin/open-knowledge` | Symlinks to the CLI bundled inside the app | Outside-project (home dir) |
| `~/.ok/env.sh` | A managed shim that prepends `~/.ok/bin` to your `PATH` | Outside-project (home dir) |
-| `~/.zshrc`, `~/.bash_profile`, `~/.config/fish/conf.d/open-knowledge.fish` | A **fenced managed block** that sources `~/.ok/env.sh` — written **only if you consent** in the first-launch dialog | Outside-project (shell config) |
+| `~/.zshrc`, `~/.bash_profile`, `~/.bashrc` (Linux), `~/.config/fish/conf.d/open-knowledge.fish` | A **fenced managed block** that sources `~/.ok/env.sh` — written **only if you consent** in the first-launch dialog. The block is created in the startup file for your login shell, and maintained in any of these that already exists, except `~/.bashrc`, which is only ever touched on Linux | Outside-project (shell config) |
If you decline, only `ok` typed in an *external* terminal (Terminal, iTerm) is affected — the app's built-in terminal, the MCP server, and the "Open with AI" launches all work without it. You can add it later from **File → Set up OpenKnowledge integrations…**. Machines that already had the block from a version before the consent dialog are treated as consented: the block is left in place and maintained.
@@ -315,7 +315,7 @@ Bridge setup requires a project directory it can resolve and access, and refuses
| To skip… | Do this |
| --- | --- |
| The `postinstall` skill install (CLI) | `npm install --ignore-scripts` |
-| The shell-config `PATH` block (macOS app) | Uncheck "Add the `ok` command to your terminal" in the first-launch dialog |
+| The shell-config `PATH` block (macOS and Linux app) | Uncheck "Add the `ok` command to your terminal" in the first-launch dialog |
| All editor MCP registration in `ok init` | `ok init --no-mcp` |
| User-level (vs project) MCP writes | `ok init --scope project` |
| Committing `.ok/` to git | Off by default for a new project; `ok init --shared` commits it instead |
diff --git a/packages/app/src/components/SlidesToolbarControls.dom.test.tsx b/packages/app/src/components/SlidesToolbarControls.dom.test.tsx
index 1f0f6efd1..6a8ac0513 100644
--- a/packages/app/src/components/SlidesToolbarControls.dom.test.tsx
+++ b/packages/app/src/components/SlidesToolbarControls.dom.test.tsx
@@ -429,23 +429,26 @@ describe('SlidesToolbarControls — activation', () => {
);
});
- test('a spawn failure surfaces a message distinct from a hung or crashed boot', async () => {
- const user = userEvent.setup();
- installBridge({
- status: () => Promise.resolve({ kind: 'status', available: true, source: 'global' }),
- open: () => Promise.resolve({ kind: 'open', ok: false, reason: 'spawn-error' }),
- });
- await renderControls(makeProvider('---\nslides: true\n---\nbody\n'));
+ test.each(['spawn-error', 'port-error'] as const)(
+ '%s surfaces a message distinct from a hung or crashed boot',
+ async (reason) => {
+ const user = userEvent.setup();
+ installBridge({
+ status: () => Promise.resolve({ kind: 'status', available: true, source: 'global' }),
+ open: () => Promise.resolve({ kind: 'open', ok: false, reason }),
+ });
+ await renderControls(makeProvider('---\nslides: true\n---\nbody\n'));
- await user.click(await screen.findByTestId('slides-toolbar-action'));
+ await user.click(await screen.findByTestId('slides-toolbar-action'));
- await waitFor(() =>
- expect(toastErrorSpy).toHaveBeenCalledWith(
- "Couldn't start Slidev.",
- expect.objectContaining({ id: 'slides-opening' }),
- ),
- );
- });
+ await waitFor(() =>
+ expect(toastErrorSpy).toHaveBeenCalledWith(
+ "Couldn't start Slidev.",
+ expect.objectContaining({ id: 'slides-opening' }),
+ ),
+ );
+ },
+ );
test('an open that rejects at the IPC boundary surfaces an error and logs the cause', async () => {
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
diff --git a/packages/app/src/components/SlidesToolbarControls.tsx b/packages/app/src/components/SlidesToolbarControls.tsx
index 9e04a5843..99c867202 100644
--- a/packages/app/src/components/SlidesToolbarControls.tsx
+++ b/packages/app/src/components/SlidesToolbarControls.tsx
@@ -60,6 +60,7 @@ async function openSlidesDeck(
message = copy.unsupported;
break;
case 'spawn-error':
+ case 'port-error':
message = copy.startFailed;
retryable = true;
break;
diff --git a/packages/core/src/constants/ok-dir.test.ts b/packages/core/src/constants/ok-dir.test.ts
new file mode 100644
index 000000000..abfc57ef2
--- /dev/null
+++ b/packages/core/src/constants/ok-dir.test.ts
@@ -0,0 +1,34 @@
+import { posix } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { OK_BIN_DIRNAME, OK_DIR, posixOkManagedBinDir } from './ok-dir.ts';
+
+describe('posixOkManagedBinDir', () => {
+ test('is the OK dir plus the bin dirname, under the given home', () => {
+ expect(posixOkManagedBinDir('/Users/alice')).toBe(`/Users/alice/${OK_DIR}/${OK_BIN_DIRNAME}`);
+ expect(posixOkManagedBinDir('/Users/alice')).toBe('/Users/alice/.ok/bin');
+ });
+
+ test('normalizes trailing separators on the home it is given', () => {
+ expect(posixOkManagedBinDir('/Users/alice/')).toBe('/Users/alice/.ok/bin');
+ expect(posixOkManagedBinDir('/Users/alice///')).toBe('/Users/alice/.ok/bin');
+ });
+
+ test('collapses repeated interior separators the way posix.join would', () => {
+ expect(posixOkManagedBinDir('/Users//alice')).toBe('/Users/alice/.ok/bin');
+ expect(posixOkManagedBinDir('//Users/alice')).toBe('/Users/alice/.ok/bin');
+ });
+
+ test('leaves a backslash alone, since it is a legal character in a POSIX home', () => {
+ expect(posixOkManagedBinDir('/home/a\\b')).toBe('/home/a\\b/.ok/bin');
+ });
+
+ test('leaves a root home resolvable', () => {
+ expect(posixOkManagedBinDir('/')).toBe('/.ok/bin');
+ });
+
+ test('stays byte-identical to the posix join both call sites used before they shared it', () => {
+ for (const home of ['/Users/alice', '/Users/alice/', '/home/a\\b', '/']) {
+ expect(posixOkManagedBinDir(home)).toBe(posix.join(home, OK_DIR, OK_BIN_DIRNAME));
+ }
+ });
+});
diff --git a/packages/core/src/constants/ok-dir.ts b/packages/core/src/constants/ok-dir.ts
index b7c52dd8e..054fda883 100644
--- a/packages/core/src/constants/ok-dir.ts
+++ b/packages/core/src/constants/ok-dir.ts
@@ -5,3 +5,10 @@ export const OK_PROJECT_MARKER = '.ok/config.yml';
export const LOCAL_DIR = 'local';
export const SAVED_THEMES_DIRNAME = 'themes';
+
+export const OK_BIN_DIRNAME = 'bin';
+
+export function posixOkManagedBinDir(homeDir: string): string {
+ const base = homeDir.replace(/\/+/g, '/').replace(/\/+$/, '');
+ return `${base}/${OK_DIR}/${OK_BIN_DIRNAME}`;
+}
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index b6d5488e4..dddab86ba 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -878,6 +878,7 @@ export type SlidevOpenFailureReason =
| 'not-available'
| 'invalid-path'
| 'spawn-error'
+ | 'port-error'
| 'exited-early'
| 'cancelled'
| 'load-failed'
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fff623c11..8273f324c 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -495,7 +495,13 @@ export {
NATIVE_MENU_LABELS,
type NativeMenuLabelKey,
} from './constants/native-menu-labels.ts';
-export { LOCAL_DIR, OK_DIR, OK_PROJECT_MARKER, SAVED_THEMES_DIRNAME } from './constants/ok-dir.ts';
+export {
+ LOCAL_DIR,
+ OK_DIR,
+ OK_PROJECT_MARKER,
+ posixOkManagedBinDir,
+ SAVED_THEMES_DIRNAME,
+} from './constants/ok-dir.ts';
export {
PREVIEW_EMBED_STARTERS,
type PreviewEmbedStarter,
diff --git a/packages/desktop/src/main/claude-readiness.test.ts b/packages/desktop/src/main/claude-readiness.test.ts
new file mode 100644
index 000000000..2bf6f8cdc
--- /dev/null
+++ b/packages/desktop/src/main/claude-readiness.test.ts
@@ -0,0 +1,232 @@
+import { beforeEach, describe, expect, test, vi } from 'vitest';
+import {
+ cliProbeArgs,
+ type ProbeChild,
+ type ProbeTimers,
+ runLoginShellProbe,
+ runWindowsPathProbe,
+} from './claude-readiness.ts';
+
+const probeLog = vi.hoisted(() => {
+ const logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: () => logger,
+ };
+ return logger;
+});
+vi.mock('./desktop-logger.ts', () => ({ getLogger: () => probeLog }));
+
+function settleRecords(): Record<string, unknown>[] {
+ return [...probeLog.info.mock.calls, ...probeLog.warn.mock.calls]
+ .map(([attrs]) => attrs as Record<string, unknown>)
+ .filter((attrs) => 'outcome' in attrs);
+}
+
+function unknownSettleRecords(): Record<string, unknown>[] {
+ return probeLog.warn.mock.calls
+ .map(([attrs]) => attrs as Record<string, unknown>)
+ .filter((attrs) => attrs.outcome === 'unknown');
+}
+
+function makeFakeChild() {
+ let exitCb: ((code: number | null) => void) | null = null;
+ let errorCb: ((err: Error) => void) | null = null;
+ const child: ProbeChild = {
+ onExit: (cb) => {
+ exitCb = cb;
+ },
+ onError: (cb) => {
+ errorCb = cb;
+ },
+ kill: () => {},
+ };
+ return {
+ child,
+ emitExit: (code: number | null) => exitCb?.(code),
+ emitError: (err: Error) => errorCb?.(err),
+ };
+}
+
+function makeFakeTimers() {
+ let scheduled: (() => void) | null = null;
+ const timers: ProbeTimers = {
+ setTimer: (cb) => {
+ scheduled = cb;
+ return 'token';
+ },
+ clearTimer: () => {},
+ };
+ return { timers, fireTimeout: () => scheduled?.() };
+}
+
+const CODEX_PROBE_ARGS = cliProbeArgs('codex', process.platform);
+
+describe('probe settle observability (a not-found must be distinguishable from a real absence)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ test.each([
+ [0, 'present'],
+ [1, 'not-found'],
+ [127, 'not-found'],
+ ])(
+ 'an exit of %i settles as %s, naming the shell and the binary it probed',
+ async (code, outcome) => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers } = makeFakeTimers();
+ const probe = runLoginShellProbe(
+ () => child,
+ '/bin/zsh',
+ timers,
+ undefined,
+ CODEX_PROBE_ARGS,
+ );
+ emitExit(code);
+ expect(await probe).toBe(code);
+ expect(settleRecords()).toEqual([
+ {
+ label: 'interactive-shell',
+ shell: '/bin/zsh',
+ args: CODEX_PROBE_ARGS,
+ outcome,
+ exitCode: code,
+ },
+ ]);
+ },
+ );
+
+ test('two probes of different binaries settle as separately attributable records', async () => {
+ const claudeArgs = cliProbeArgs('claude', process.platform);
+ for (const args of [claudeArgs, CODEX_PROBE_ARGS]) {
+ const { child, emitExit } = makeFakeChild();
+ const { timers } = makeFakeTimers();
+ const probe = runLoginShellProbe(() => child, '/bin/zsh', timers, undefined, args);
+ emitExit(1);
+ await probe;
+ }
+ expect(settleRecords().map((record) => record.args)).toEqual([claudeArgs, CODEX_PROBE_ARGS]);
+ });
+
+ test('a timeout settles as unknown and records it once, even when a late exit follows', async () => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers, fireTimeout } = makeFakeTimers();
+ const probe = runLoginShellProbe(() => child, '/bin/zsh', timers, 5000, CODEX_PROBE_ARGS);
+ fireTimeout();
+ emitExit(0);
+ expect(await probe).toBe(null);
+ expect(settleRecords()).toEqual([
+ {
+ label: 'interactive-shell',
+ shell: '/bin/zsh',
+ args: CODEX_PROBE_ARGS,
+ timedOut: true,
+ timeoutMs: 5000,
+ outcome: 'unknown',
+ exitCode: null,
+ },
+ ]);
+ });
+
+ test('a child that fails to run settles as unknown, alongside the warn', async () => {
+ const { child, emitError } = makeFakeChild();
+ const { timers } = makeFakeTimers();
+ const failure = new Error('ENOENT');
+ const probe = runLoginShellProbe(() => child, '/bin/zsh', timers, undefined, CODEX_PROBE_ARGS);
+ emitError(failure);
+ expect(await probe).toBe(null);
+ expect(settleRecords()).toEqual([
+ {
+ label: 'interactive-shell',
+ shell: '/bin/zsh',
+ args: CODEX_PROBE_ARGS,
+ err: failure,
+ failurePhase: 'onError',
+ outcome: 'unknown',
+ exitCode: null,
+ },
+ ]);
+ expect(unknownSettleRecords()).toHaveLength(1);
+ expect(probeLog.warn.mock.calls).toHaveLength(1);
+ });
+
+ test('a spawn that throws settles as unknown rather than leaving no verdict at all', async () => {
+ const { timers } = makeFakeTimers();
+ const failure = new Error('EACCES');
+ const probe = runLoginShellProbe(
+ () => {
+ throw failure;
+ },
+ '/bin/zsh',
+ timers,
+ undefined,
+ CODEX_PROBE_ARGS,
+ );
+ expect(await probe).toBe(null);
+ expect(settleRecords()).toEqual([
+ {
+ label: 'interactive-shell',
+ shell: '/bin/zsh',
+ args: CODEX_PROBE_ARGS,
+ err: failure,
+ failurePhase: 'spawn',
+ outcome: 'unknown',
+ exitCode: null,
+ },
+ ]);
+ expect(unknownSettleRecords()).toHaveLength(1);
+ expect(probeLog.warn.mock.calls).toHaveLength(1);
+ });
+
+ test('an unknown outcome is recorded at warn level, unlike a routine not-found', async () => {
+ const notFound = makeFakeChild();
+ const notFoundProbe = runLoginShellProbe(
+ () => notFound.child,
+ '/bin/zsh',
+ makeFakeTimers().timers,
+ undefined,
+ CODEX_PROBE_ARGS,
+ );
+ notFound.emitExit(1);
+ await notFoundProbe;
+ expect(unknownSettleRecords()).toHaveLength(0);
+
+ const signalled = makeFakeChild();
+ const signalledProbe = runLoginShellProbe(
+ () => signalled.child,
+ '/bin/zsh',
+ makeFakeTimers().timers,
+ undefined,
+ CODEX_PROBE_ARGS,
+ );
+ signalled.emitExit(null);
+ await signalledProbe;
+ expect(unknownSettleRecords()).toHaveLength(1);
+ });
+
+ test('the where.exe probe settles under its own label, naming the binary it probed', async () => {
+ const { child, emitExit } = makeFakeChild();
+ const { timers } = makeFakeTimers();
+ const probe = runWindowsPathProbe(
+ () => child,
+ 'C:\\Windows\\System32\\where.exe',
+ 'claude',
+ timers,
+ );
+ emitExit(0);
+ expect(await probe).toBe(0);
+ const [record] = settleRecords();
+ expect(record).toEqual({
+ label: 'where.exe',
+ bin: 'claude',
+ args: ['$PATH:claude'],
+ outcome: 'present',
+ exitCode: 0,
+ });
+ });
+});
diff --git a/packages/desktop/src/main/claude-readiness.ts b/packages/desktop/src/main/claude-readiness.ts
index d8c43304b..812844dbc 100644
--- a/packages/desktop/src/main/claude-readiness.ts
+++ b/packages/desktop/src/main/claude-readiness.ts
@@ -46,41 +46,37 @@ interface InjectedProbeSpec {
function runInjectedProbe(spec: InjectedProbeSpec): Promise<number | null> {
const { spawn, file, args, timers, timeoutMs, loggerName, label, attrs } = spec;
return new Promise<number | null>((resolve) => {
+ function recordSettled(code: number | null, reason: Record<string, unknown> = {}): void {
+ const outcome = interpretClaudeProbe(code);
+ const log = getLogger(loggerName);
+ const record = { ...attrs, ...reason, label, outcome, exitCode: code };
+ const message = `${label} PATH probe settled`;
+ if (outcome === 'unknown') log.warn(record, message);
+ else log.info(record, message);
+ }
let child: ProbeChild;
try {
// oxlint-disable-next-line ok/require-windowshide-on-spawn -- injected probe seam; the production child_process adapter owns its spawn options
child = spawn(file, args);
} catch (err) {
- getLogger(loggerName).warn(
- { ...attrs, err },
- `${label} PATH probe spawn threw; presence unknown`,
- );
+ recordSettled(null, { err, failurePhase: 'spawn' });
resolve(null);
return;
}
let settled = false;
const timer = timers.setTimer(() => {
- getLogger(loggerName).warn(
- { ...attrs, timeoutMs },
- `${label} PATH probe timed out; presence unknown`,
- );
child.kill();
- finish(null);
+ finish(null, { timedOut: true, timeoutMs });
}, timeoutMs);
- function finish(code: number | null): void {
+ function finish(code: number | null, reason: Record<string, unknown> = {}): void {
if (settled) return;
settled = true;
timers.clearTimer(timer);
+ recordSettled(code, reason);
resolve(code);
}
child.onError((err) => {
- if (!settled) {
- getLogger(loggerName).warn(
- { ...attrs, err },
- `${label} PATH probe failed to run; presence unknown`,
- );
- }
- finish(null);
+ finish(null, { err, failurePhase: 'onError' });
});
child.onExit((code) => finish(code));
});
@@ -121,7 +117,7 @@ export function runWindowsPathProbe(
timeoutMs,
loggerName: 'windows-path-probe',
label: 'where.exe',
- attrs: { whereExe, bin, args },
+ attrs: { bin, args },
});
}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 1503aa16a..516d36718 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -214,8 +214,6 @@ import {
import { classifyClaudeMcpScopes } from './claude-mcp-scopes.ts';
import {
cliProbeArgs,
- type ProbeChild,
- type ProbeTimers,
probePlatformCliOnPath,
resolveClaudeReadiness,
resolveCliOnPath,
@@ -375,6 +373,7 @@ import {
removePathShimFromRcFiles,
} from './path-install.ts';
import { probeLoopbackPort } from './port-probe.ts';
+import { realProbeSpawn, realProbeTimers } from './probe-spawn.ts';
import { installStdioBrokenPipeGuard } from './process-safety-net.ts';
import {
type ProjectIntegrationsCliSurface,
@@ -3616,30 +3615,6 @@ function formatUnknownError(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
-function realProbeSpawn(file: string, spawnArgs: readonly string[]): ProbeChild {
- const child = spawn(file, [...spawnArgs], {
- stdio: 'ignore',
- shell: false,
- windowsHide: true,
- });
- return {
- onExit: (cb) => {
- child.on('exit', (code) => cb(code));
- },
- onError: (cb) => {
- child.on('error', (err) => cb(err));
- },
- kill: () => {
- child.kill('SIGKILL');
- },
- };
-}
-
-const realProbeTimers: ProbeTimers = {
- setTimer: (cb, ms) => setTimeout(cb, ms),
- clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),
-};
-
function probeWindowsPath(bin: string): Promise<number | null> {
const systemRoot = getWindowsEnvValue(process.env, 'SystemRoot') ?? 'C:\\Windows';
return runWindowsPathProbe(
diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.ts
index 174cd84ef..754f2008b 100644
--- a/packages/desktop/src/main/path-install.ts
+++ b/packages/desktop/src/main/path-install.ts
@@ -20,6 +20,7 @@ import {
type PathInstallMarker,
pathInstallMarkerPath,
} from '@inkeep/open-knowledge';
+import { posixOkManagedBinDir } from '@inkeep/open-knowledge-core';
import type { McpWiringPathInstallDescriptor } from '../shared/ipc-channels.ts';
import { classifyInstallShape } from './install-shape.ts';
@@ -148,7 +149,7 @@ function writeMarker(home: string, marker: PathInstallMarker, fs: PathInstallFsO
}
function okBin(home: string): string {
- return join(home, '.ok', 'bin');
+ return posixOkManagedBinDir(home);
}
function envShim(home: string): string {
diff --git a/packages/desktop/src/main/probe-spawn.test.ts b/packages/desktop/src/main/probe-spawn.test.ts
new file mode 100644
index 000000000..806b41d3d
--- /dev/null
+++ b/packages/desktop/src/main/probe-spawn.test.ts
@@ -0,0 +1,307 @@
+import { randomUUID } from 'node:crypto';
+import { rmSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { TERMINAL_CLI_IDS, TERMINAL_CLIS } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest';
+import {
+ createScratchHomeWithOkBin,
+ firstShellOnDisk,
+ MINIMAL_PARENT_PATH,
+} from '../../tests/support/ok-bin-scratch-home.test-helper.ts';
+import { okManagedBinDirs } from '../shared/ok-child-env.ts';
+import { buildShellEnv } from '../utility/pty-host.ts';
+import { cliProbeArgs, runLoginShellProbe } from './claude-readiness.ts';
+import {
+ okProbeSpawnEnv,
+ probeEnvVerdict,
+ probeSpawnArgs,
+ realProbeSpawn,
+ realProbeTimers,
+} from './probe-spawn.ts';
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:os')>();
+ return { ...actual, homedir: vi.fn(actual.homedir) };
+});
+
+const probeLog = vi.hoisted(() => {
+ const logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: () => logger,
+ };
+ return logger;
+});
+vi.mock('./desktop-logger.ts', () => ({ getLogger: () => probeLog }));
+
+function compositionRecords(): Record<string, unknown>[] {
+ return probeLog.info.mock.calls
+ .map(([attrs]) => attrs as Record<string, unknown>)
+ .filter((attrs) => 'verdict' in attrs);
+}
+
+const SLIDEV_BIN = 'slidev';
+const TERMINAL_CLI_BINS = TERMINAL_CLI_IDS.map((cli) => TERMINAL_CLIS[cli].bin);
+const FIXTURE_ONLY_BIN = `ok-probe-spawn-fixture-${randomUUID()}`;
+
+describe('probeSpawnArgs', () => {
+ test('reasserts the managed path in the initialized POSIX shell', () => {
+ const { args, reassert, family } = probeSpawnArgs(
+ '/bin/zsh',
+ ['-i', '-c', 'command -v codex'],
+ {
+ platform: 'linux',
+ home: "/home/o'brien",
+ },
+ );
+ expect(reassert).toBe('applied');
+ expect(family).toBe('posix');
+ expect(args.slice(0, -1)).toEqual(['-i', '-c']);
+ expect(args.at(-1)).toBe(
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: shell parameter expansion in an expected command string, not a JS template placeholder
+ "case \":$PATH:\" in *:'/home/o'\\''brien/.ok/bin':*) ;; *) PATH='/home/o'\\''brien/.ok/bin'\"${PATH:+:$PATH}\" ;; esac; export PATH; command -v codex",
+ );
+ });
+
+ test('uses the configured shell family syntax', () => {
+ const options = { platform: 'linux' as const, home: "/home/o'brien" };
+ expect(
+ probeSpawnArgs('/usr/bin/fish', ['-i', '-c', 'command -v codex'], options).args.at(-1),
+ ).toBe(
+ "if not contains '/home/o\\'brien/.ok/bin' $PATH; set -gx PATH '/home/o\\'brien/.ok/bin' $PATH; end; command -v codex",
+ );
+ });
+
+ test('delegates unknown shell families to a POSIX command shell', () => {
+ for (const shell of ['/usr/bin/nu', '/bin/tcsh']) {
+ const { args, family } = probeSpawnArgs(shell, ['-i', '-c', 'command -v codex'], {
+ platform: 'linux',
+ home: '/home/alice',
+ });
+ expect(family).toBe('fallback');
+ expect(args.at(-1)).toContain('exec /bin/sh -c');
+ expect(args.at(-1)).toContain('command -v codex');
+ }
+ });
+
+ test('leaves Windows and non-command argv unchanged', () => {
+ const windows = ['/d', '/s', '/c', 'where.exe codex'];
+ expect(
+ probeSpawnArgs('cmd.exe', windows, {
+ platform: 'win32',
+ home: 'C:\\Users\\alice',
+ cliBinDir: 'C:\\OpenKnowledge\\cli\\bin',
+ }),
+ ).toEqual({ args: windows, reassert: 'skipped-win32', family: undefined });
+ const direct = ['--version'];
+ expect(probeSpawnArgs('/bin/sh', direct, { platform: 'linux', home: '/home/alice' })).toEqual({
+ args: direct,
+ reassert: 'skipped-shape',
+ family: 'posix',
+ });
+ });
+
+ test.skipIf(process.platform === 'win32')(
+ 'warns with the shell family and the reassert reason when probe argv cannot carry a reassert',
+ () => {
+ probeLog.warn.mockClear();
+ const child = realProbeSpawn('/bin/sh', ['--version']);
+ child.onError(() => {});
+ try {
+ expect(
+ probeLog.warn,
+ 'this is the third record the shell-family convergence renamed, and the only one whose warn call no test reaches: probeSpawnArgs returning the skipped-shape shape is pinned above, its consumer was not',
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'probe-reassert-skipped',
+ shellCommandFamily: 'posix',
+ reassert: 'skipped-shape',
+ }),
+ expect.any(String),
+ );
+ } finally {
+ child.kill();
+ }
+ },
+ );
+});
+
+describe.skipIf(process.platform === 'win32')('the production CLI-presence probe adapter', () => {
+ let scratchHome: string;
+ let shell: string;
+ let previousHome: string | undefined;
+ let previousPath: string | undefined;
+ let previousZdotdir: string | undefined;
+
+ beforeAll(() => {
+ scratchHome = createScratchHomeWithOkBin({
+ prefix: 'ok-probe-spawn-',
+ bins: [SLIDEV_BIN, ...TERMINAL_CLI_BINS, FIXTURE_ONLY_BIN],
+ });
+ previousHome = process.env.HOME;
+ previousPath = process.env.PATH;
+ previousZdotdir = process.env.ZDOTDIR;
+ process.env.HOME = scratchHome;
+ process.env.PATH = MINIMAL_PARENT_PATH;
+ delete process.env.ZDOTDIR;
+ shell = firstShellOnDisk();
+ });
+
+ afterAll(() => {
+ if (previousHome === undefined) delete process.env.HOME;
+ else process.env.HOME = previousHome;
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ if (previousZdotdir !== undefined) process.env.ZDOTDIR = previousZdotdir;
+ rmSync(scratchHome, { recursive: true, force: true });
+ });
+
+ function okBinGrantedToOwnShells(): string {
+ return (
+ (buildShellEnv(process.env, { platform: process.platform }).env.PATH ?? '').split(':')[0] ??
+ ''
+ );
+ }
+
+ function probeThroughProductionAdapter(bin: string): Promise<number | null> {
+ return runLoginShellProbe(
+ realProbeSpawn,
+ shell,
+ realProbeTimers,
+ undefined,
+ cliProbeArgs(bin, process.platform),
+ );
+ }
+
+ test('leads the probe PATH with the same OK-managed bin dir the app grants its own shells', () => {
+ const env = okProbeSpawnEnv();
+ expect((env.PATH ?? '').split(':')[0]).toBe(okBinGrantedToOwnShells());
+ expect(env.PATH).not.toBe(process.env.PATH);
+ expect(env).not.toBe(process.env);
+ });
+
+ test('does not mark the probe child as the OK Desktop terminal', () => {
+ expect(okProbeSpawnEnv().OK_DESKTOP_TERMINAL).toBeUndefined();
+ });
+
+ test('resolves a ~/.ok/bin CLI that the bare app environment cannot reach', async () => {
+ expect(await probeThroughProductionAdapter(FIXTURE_ONLY_BIN)).toBe(0);
+ });
+});
+
+const WIN_CLI_BIN = 'C:\\Program Files\\Open Knowledge\\resources\\cli\\bin';
+
+describe('probeEnvVerdict', () => {
+ test('reports inherited when the app PATH already carries the OK-managed bin dir', () => {
+ expect(
+ probeEnvVerdict(
+ { PATH: '/Users/alice/.ok/bin:/usr/bin' },
+ { platform: 'darwin', home: '/Users/alice' },
+ ),
+ ).toBe('inherited');
+ });
+
+ test('reports injected when the app PATH does not, which is the reported bug precondition', () => {
+ expect(
+ probeEnvVerdict({ PATH: '/usr/bin' }, { platform: 'darwin', home: '/Users/alice' }),
+ ).toBe('injected');
+ });
+
+ test('separates "no managed dir applies" from either grant', () => {
+ expect(probeEnvVerdict({ PATH: '/usr/bin' }, { platform: 'darwin' })).toBe(
+ 'not-applicable-no-home',
+ );
+ expect(probeEnvVerdict({ Path: 'C:\\Windows' }, { platform: 'win32' })).toBe('not-applicable');
+ expect(
+ probeEnvVerdict({ Path: 'C:\\Windows' }, { platform: 'win32', cliBinDir: WIN_CLI_BIN }),
+ ).toBe('injected');
+ expect(
+ probeEnvVerdict(
+ { Path: `${WIN_CLI_BIN};C:\\Windows` },
+ { platform: 'win32', cliBinDir: WIN_CLI_BIN },
+ ),
+ ).toBe('inherited');
+ });
+
+ test('every verdict is reachable from a real okProbeSpawnEnv parent environment', () => {
+ const reached = new Set<string>();
+ for (const [parent, options] of [
+ [{ PATH: '/usr/bin' }, { platform: 'darwin' as const }],
+ [{ Path: 'C:\\Windows' }, { platform: 'win32' as const }],
+ [{ PATH: '/usr/bin' }, { platform: 'darwin' as const, home: '/Users/alice' }],
+ [
+ { PATH: '/Users/alice/.ok/bin:/usr/bin' },
+ { platform: 'darwin' as const, home: '/Users/alice' },
+ ],
+ ] as const) {
+ reached.add(probeEnvVerdict(parent, options));
+ }
+ expect(reached).toEqual(
+ new Set(['not-applicable', 'not-applicable-no-home', 'inherited', 'injected']),
+ );
+ });
+});
+
+describe('the probe env composition line', () => {
+ test('classifies an explicitly empty POSIX home as missing', () => {
+ expect(probeEnvVerdict({}, { platform: 'linux', home: '' })).toBe('not-applicable-no-home');
+ });
+
+ test.skipIf(process.platform === 'win32')(
+ 'warns when the resolved POSIX home is empty',
+ async () => {
+ vi.stubEnv('HOME', '');
+ vi.mocked(homedir).mockReturnValueOnce('');
+ try {
+ const mod = await freshProbeSpawn();
+ mod.okProbeSpawnEnv();
+ expect(probeLog.warn).toHaveBeenCalledWith(
+ expect.objectContaining({ verdict: 'not-applicable-no-home', okManagedBinDirs: [] }),
+ expect.any(String),
+ );
+ expect(probeLog.info).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ },
+ );
+
+ beforeEach(() => {
+ vi.resetModules();
+ probeLog.info.mockClear();
+ probeLog.warn.mockClear();
+ });
+
+ async function freshProbeSpawn() {
+ return await import('./probe-spawn.ts');
+ }
+
+ test('logs the composition once per run, not once per probe', async () => {
+ const mod = await freshProbeSpawn();
+ mod.okProbeSpawnEnv();
+ mod.okProbeSpawnEnv();
+ mod.okProbeSpawnEnv();
+ expect(compositionRecords()).toHaveLength(1);
+ });
+
+ test('names the verdict and the dir it resolved, at info level', async () => {
+ const mod = await freshProbeSpawn();
+ mod.okProbeSpawnEnv();
+ const [record] = compositionRecords();
+ expect(record?.verdict).toBe(
+ probeEnvVerdict(process.env, {
+ platform: process.platform,
+ home: homedir(),
+ cliBinDir: undefined,
+ }),
+ );
+ expect(record?.okManagedBinDirs).toEqual(
+ okManagedBinDirs({ platform: process.platform, home: homedir(), cliBinDir: undefined }),
+ );
+ expect(probeLog.warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/desktop/src/main/probe-spawn.ts b/packages/desktop/src/main/probe-spawn.ts
new file mode 100644
index 000000000..be17ab4c3
--- /dev/null
+++ b/packages/desktop/src/main/probe-spawn.ts
@@ -0,0 +1,153 @@
+import { spawn } from 'node:child_process';
+import {
+ composeOkChildEnv,
+ hasNoResolvableOkHome,
+ hasOkManagedBinDirsOnPath,
+ type OkManagedBinDirsOptions,
+ okChildEnvOptionsFromProcess,
+ okChildPathEntries,
+ okManagedBinDirs,
+} from '../shared/ok-child-env.ts';
+import {
+ commandWithManagedPath,
+ type ShellCommandFamily,
+ shellCommandFamily,
+} from '../shared/terminal-shell.ts';
+import type { ProbeChild, ProbeTimers } from './claude-readiness.ts';
+import { getLogger } from './desktop-logger.ts';
+
+export type ProbeReassert = 'applied' | 'skipped-shape' | 'skipped-win32';
+
+export interface ProbeSpawnArgv {
+ readonly args: readonly string[];
+ readonly reassert: ProbeReassert;
+ readonly family: ShellCommandFamily | undefined;
+}
+
+export type ProbeEnvVerdict =
+ | 'not-applicable'
+ | 'not-applicable-no-home'
+ | 'inherited'
+ | 'injected';
+
+const VERDICT_MESSAGES: Record<ProbeEnvVerdict, string> = {
+ 'not-applicable': 'no OK-managed bin dir applies to CLI-presence probe children',
+ 'not-applicable-no-home':
+ 'home directory unresolvable, so CLI-presence probe children get no OK-managed bin dir',
+ inherited: 'CLI-presence probe children inherit the OK-managed bin dir from the app PATH',
+ injected: 'CLI-presence probe children get the OK-managed bin dir added to the app PATH',
+};
+
+const VERDICT_LOG_LEVELS: Record<ProbeEnvVerdict, 'warn' | 'info'> = {
+ 'not-applicable': 'info',
+ 'not-applicable-no-home': 'warn',
+ inherited: 'info',
+ injected: 'info',
+};
+
+const REASSERT_WARNINGS: Record<ProbeReassert, string | null> = {
+ applied: null,
+ 'skipped-shape':
+ 'POSIX probe argv does not end in -c <command>, so the OK-managed bin dir was not reasserted after shell startup files ran',
+ 'skipped-win32': null,
+};
+
+export function probeEnvVerdict(
+ parentEnv: Record<string, string | undefined>,
+ options: OkManagedBinDirsOptions,
+): ProbeEnvVerdict {
+ if (okManagedBinDirs(options).length === 0) {
+ return hasNoResolvableOkHome(options) ? 'not-applicable-no-home' : 'not-applicable';
+ }
+ return hasOkManagedBinDirsOnPath(parentEnv, options) ? 'inherited' : 'injected';
+}
+
+let probeEnvCompositionLogged = false;
+
+function logProbeEnvComposition(
+ parentEnv: Record<string, string | undefined>,
+ options: OkManagedBinDirsOptions,
+ argv: ProbeSpawnArgv | undefined,
+): void {
+ if (probeEnvCompositionLogged) return;
+ probeEnvCompositionLogged = true;
+ const verdict = probeEnvVerdict(parentEnv, options);
+ const record = {
+ platform: options.platform,
+ verdict,
+ okManagedBinDirs: okManagedBinDirs(options),
+ parentPathEntryCount: okChildPathEntries(parentEnv, options).length,
+ reassert: argv?.reassert,
+ shellCommandFamily: argv?.family,
+ };
+ const log = getLogger('probe-spawn');
+ log[VERDICT_LOG_LEVELS[verdict]](record, VERDICT_MESSAGES[verdict]);
+}
+
+export function okProbeSpawnEnv(
+ options: OkManagedBinDirsOptions = okChildEnvOptionsFromProcess(),
+ argv?: ProbeSpawnArgv,
+): Record<string, string> {
+ logProbeEnvComposition(process.env, options, argv);
+ return composeOkChildEnv(process.env, options);
+}
+
+export function probeSpawnArgs(
+ shell: string,
+ spawnArgs: readonly string[],
+ options: OkManagedBinDirsOptions,
+): ProbeSpawnArgv {
+ if (options.platform === 'win32') {
+ return { args: spawnArgs, reassert: 'skipped-win32', family: undefined };
+ }
+ const family = shellCommandFamily(shell);
+ const command = spawnArgs.at(-2) === '-c' ? spawnArgs.at(-1) : undefined;
+ if (command === undefined) return { args: spawnArgs, reassert: 'skipped-shape', family };
+ return {
+ args: [
+ ...spawnArgs.slice(0, -1),
+ commandWithManagedPath(shell, command, okManagedBinDirs(options)),
+ ],
+ reassert: 'applied',
+ family,
+ };
+}
+
+export function realProbeSpawn(file: string, spawnArgs: readonly string[]): ProbeChild {
+ const options = okChildEnvOptionsFromProcess();
+ const argv = probeSpawnArgs(file, spawnArgs, options);
+ const reassertWarning = REASSERT_WARNINGS[argv.reassert];
+ if (reassertWarning !== null) {
+ getLogger('probe-spawn').warn(
+ {
+ event: 'probe-reassert-skipped',
+ platform: options.platform,
+ shellCommandFamily: argv.family,
+ reassert: argv.reassert,
+ },
+ reassertWarning,
+ );
+ }
+ const child = spawn(file, [...argv.args], {
+ stdio: 'ignore',
+ shell: false,
+ windowsHide: true,
+ env: okProbeSpawnEnv(options, argv),
+ });
+ return {
+ onExit: (cb) => {
+ child.on('exit', (code) => cb(code));
+ },
+ onError: (cb) => {
+ child.on('error', (err) => cb(err));
+ },
+ kill: () => {
+ child.kill('SIGKILL');
+ },
+ };
+}
+
+export const realProbeTimers: ProbeTimers = {
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),
+};
diff --git a/packages/desktop/src/main/slides-telemetry.test.ts b/packages/desktop/src/main/slides-telemetry.test.ts
index cda87eb5c..0954c3351 100644
--- a/packages/desktop/src/main/slides-telemetry.test.ts
+++ b/packages/desktop/src/main/slides-telemetry.test.ts
@@ -106,6 +106,7 @@ describe('recordDeckOpen — lazily-cached instrument', () => {
{ kind: 'open', ok: false, reason: 'renderer-failed' },
{ kind: 'open', ok: false, reason: 'unsupported-server' },
{ kind: 'open', ok: false, reason: 'spawn-error' },
+ { kind: 'open', ok: false, reason: 'port-error' },
];
for (const f of failures) recordDeckOpen(f);
expect(createCounterCalls).toBe(1);
@@ -116,6 +117,7 @@ describe('recordDeckOpen — lazily-cached instrument', () => {
{ value: 1, attributes: { 'ok.slides.reason': 'renderer-failed' } },
{ value: 1, attributes: { 'ok.slides.reason': 'unsupported-server' } },
{ value: 1, attributes: { 'ok.slides.reason': 'spawn-error' } },
+ { value: 1, attributes: { 'ok.slides.reason': 'port-error' } },
]);
});
});
diff --git a/packages/desktop/src/main/slidev-server.test.ts b/packages/desktop/src/main/slidev-server.test.ts
index 3b3dcea7b..2e4205e05 100644
--- a/packages/desktop/src/main/slidev-server.test.ts
+++ b/packages/desktop/src/main/slidev-server.test.ts
@@ -3,16 +3,43 @@ import { EventEmitter } from 'node:events';
import { createServer as createHttpServer, type Server } from 'node:http';
import { createServer } from 'node:net';
import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const slidevLog = vi.hoisted(() => {
+ const logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: () => logger,
+ };
+ return logger;
+});
+vi.mock('./desktop-logger.ts', () => ({ getLogger: () => slidevLog }));
+
+function slidevWarnRecords(): Record<string, unknown>[] {
+ return slidevLog.warn.mock.calls.map(([attrs]) => attrs as Record<string, unknown>);
+}
+
+import {
+ okChildEnvOptionsFromProcess,
+ okChildPathEntries,
+ okManagedBinDirs,
+} from '../shared/ok-child-env.ts';
+import { cliProbeArgs } from './claude-readiness.ts';
import { validateSpawnPath } from './path-containment.ts';
import {
adaptSlidevChild,
buildSlidevInvocation,
+ composeSlidevSpawnEnv,
findFreePort,
probeSlidevReady,
type ReadinessProbe,
type SlidevProcess,
type StartSlidevDeps,
signalSlidevChild,
+ slidevSpawnEnv,
startSlidevServer,
} from './slidev-server.ts';
@@ -168,7 +195,7 @@ describe('startSlidevServer', () => {
});
it('reports spawn-error and logs the OS error code when the spawn throws', async () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ slidevLog.warn.mockClear();
const emfile: NodeJS.ErrnoException = Object.assign(new Error('spawn EMFILE'), {
code: 'EMFILE',
});
@@ -180,16 +207,12 @@ describe('startSlidevServer', () => {
});
const result = await startSlidevServer(deps);
expect(result).toEqual({ ok: false, reason: 'spawn-error' });
- expect(warnSpy).toHaveBeenCalledTimes(1);
- expect(JSON.parse(warnSpy.mock.calls[0]?.[0] as string)).toMatchObject({
- event: 'slides-spawn-error',
- code: 'EMFILE',
- });
- warnSpy.mockRestore();
+ expect(slidevWarnRecords()).toHaveLength(1);
+ expect(slidevWarnRecords()[0]).toMatchObject({ event: 'slides-spawn-error', code: 'EMFILE' });
});
- it('reports spawn-error when a free port cannot be found', async () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ it('reports spawn-error when a free port cannot be found, under its own event', async () => {
+ slidevLog.warn.mockClear();
const proc = fakeProcess();
let spawned = false;
const { deps } = makeDeps({
@@ -202,14 +225,10 @@ describe('startSlidevServer', () => {
},
});
const result = await startSlidevServer(deps);
- expect(result).toEqual({ ok: false, reason: 'spawn-error' });
+ expect(result).toEqual({ ok: false, reason: 'port-error' });
expect(spawned).toBe(false);
- expect(warnSpy).toHaveBeenCalledTimes(1);
- expect(JSON.parse(warnSpy.mock.calls[0]?.[0] as string)).toMatchObject({
- event: 'slides-spawn-error',
- code: null,
- });
- warnSpy.mockRestore();
+ expect(slidevWarnRecords()).toHaveLength(1);
+ expect(slidevWarnRecords()[0]).toMatchObject({ event: 'slides-port-error', code: null });
});
});
@@ -227,41 +246,31 @@ describe('adaptSlidevChild', () => {
});
it('keeps a spawned process alive and tracked after a child error', () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- const child = fakeChildProcess(4321);
- const process = adaptSlidevChild(child);
- const onExit = vi.fn();
- process.onExit(onExit);
+ const child = fakeChildProcess(4321);
+ const process = adaptSlidevChild(child);
+ const onExit = vi.fn();
+ process.onExit(onExit);
- child.emit('error', new Error('late pipe error'));
+ child.emit('error', new Error('late pipe error'));
- expect(process.isAlive()).toBe(true);
- expect(process.spawnError).toBeUndefined();
- expect(onExit).not.toHaveBeenCalled();
- } finally {
- warnSpy.mockRestore();
- }
+ expect(process.isAlive()).toBe(true);
+ expect(process.spawnError).toBeUndefined();
+ expect(onExit).not.toHaveBeenCalled();
});
it('reports an error before a pid is assigned as a spawn failure', () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
- try {
- const child = fakeChildProcess(undefined);
- const process = adaptSlidevChild(child);
- const onExit = vi.fn();
- process.onExit(onExit);
- const error = Object.assign(new Error('not found'), { code: 'ENOENT' });
-
- child.emit('error', error);
- child.emit('exit', null, null);
-
- expect(process.isAlive()).toBe(false);
- expect(process.spawnError).toBe(error);
- expect(onExit).toHaveBeenCalledExactlyOnceWith(null);
- } finally {
- warnSpy.mockRestore();
- }
+ const child = fakeChildProcess(undefined);
+ const process = adaptSlidevChild(child);
+ const onExit = vi.fn();
+ process.onExit(onExit);
+ const error = Object.assign(new Error('not found'), { code: 'ENOENT' });
+
+ child.emit('error', error);
+ child.emit('exit', null, null);
+
+ expect(process.isAlive()).toBe(false);
+ expect(process.spawnError).toBe(error);
+ expect(onExit).toHaveBeenCalledExactlyOnceWith(null);
});
});
@@ -275,6 +284,8 @@ describe('buildSlidevInvocation', () => {
shell: '/bin/zsh',
},
5301,
+ 'darwin',
+ [],
);
expect(invocation).toEqual({
mode: 'direct',
@@ -292,11 +303,14 @@ describe('buildSlidevInvocation', () => {
shell: '/bin/zsh',
},
5301,
+ 'darwin',
+ [],
);
expect(invocation).toEqual({
- mode: 'login-shell',
+ mode: 'interactive-shell',
file: '/bin/zsh',
- args: ['-l', '-i', '-c', "exec slidev '/decks/talk/slides.md' --port 5301"],
+ args: ['-l', '-i', '-c', "set +m; slidev '/decks/talk/slides.md' --port 5301"],
+ family: 'posix',
});
});
@@ -309,11 +323,14 @@ describe('buildSlidevInvocation', () => {
shell: 'zsh',
},
3000,
+ 'darwin',
+ [],
);
expect(invocation).toEqual({
- mode: 'login-shell',
+ mode: 'interactive-shell',
file: 'zsh',
- args: ['-l', '-i', '-c', "exec slidev '/decks/o'\\''brien; rm -rf ~/deck.md' --port 3000"],
+ args: ['-l', '-i', '-c', "set +m; slidev '/decks/o'\\''brien; rm -rf ~/deck.md' --port 3000"],
+ family: 'posix',
});
});
});
@@ -381,21 +398,109 @@ describe('buildSlidevInvocation — platform matrix', () => {
{ source: 'project-local', projectRoot: '/proj', docPath: deck, shell: '/bin/zsh' },
4300,
'linux',
+ [],
);
expect(inv.mode).toBe('direct');
expect(inv.file).toBe('/proj/node_modules/.bin/slidev');
expect(inv.args).toEqual([deck, '--port', '4300']);
});
- it('POSIX global routes through the login shell', () => {
+ it('Linux global runs the terminal interactive shell and reasserts managed bins afterward', () => {
const inv = buildSlidevInvocation(
{ source: 'global', projectRoot: '/proj', docPath: deck, shell: '/bin/zsh' },
4300,
'linux',
+ ["/home/o'brien/.ok/bin"],
);
- expect(inv.mode).toBe('login-shell');
+ expect(inv.mode).toBe('interactive-shell');
expect(inv.file).toBe('/bin/zsh');
- expect(inv.args.slice(0, 3)).toEqual(['-l', '-i', '-c']);
+ expect(inv.args).toEqual([
+ '-i',
+ '-c',
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: shell parameter expansion in an expected command string, not a JS template placeholder
+ "case \":$PATH:\" in *:'/home/o'\\''brien/.ok/bin':*) ;; *) PATH='/home/o'\\''brien/.ok/bin'\"${PATH:+:$PATH}\" ;; esac; export PATH; set +m; slidev '/proj/decks/talk.md' --port 4300",
+ ]);
+ });
+
+ it('emits the fish job-control opt-out rather than the POSIX one, so a config.fish that set job control full cannot leak the deck out of the killable group', () => {
+ const inv = buildSlidevInvocation(
+ { source: 'global', projectRoot: '/proj', docPath: deck, shell: '/usr/bin/fish' },
+ 4300,
+ 'linux',
+ ['/managed/bin'],
+ );
+ expect(inv.args.at(-1)).not.toContain('set +m');
+ expect(
+ inv.args,
+ 'without an exact pin, any drift in the fish reassert or opt-out that is not the literal addition of `set +m` lands green here, and the containment oracle that would catch it needs a fish binary on the host',
+ ).toEqual([
+ '-i',
+ '-c',
+ "if not contains '/managed/bin' $PATH; set -gx PATH '/managed/bin' $PATH; end; status job-control none; slidev '/proj/decks/talk.md' --port 4300",
+ ]);
+ });
+
+ it('omits the POSIX job-control opt-out for an unrecognized family, which runs inside a non-interactive exec /bin/sh -c wrapper whenever a managed bin dir resolves', () => {
+ const inv = buildSlidevInvocation(
+ { source: 'global', projectRoot: '/proj', docPath: deck, shell: '/usr/bin/nu' },
+ 4300,
+ 'linux',
+ ['/managed/bin'],
+ );
+ expect(inv.args.at(-1)).not.toContain('set +m');
+ expect(inv.args.at(-1)).toContain('exec /bin/sh -c ');
+ });
+
+ it('emits no shell wrapper at all for an unrecognized family when no managed bin dir resolves, which is the boundary of the wrapper above', () => {
+ const inv = buildSlidevInvocation(
+ { source: 'global', projectRoot: '/proj', docPath: deck, shell: '/usr/bin/nu' },
+ 4300,
+ 'linux',
+ [],
+ );
+ expect(inv.args.at(-1)).not.toContain('set +m');
+ expect(inv.args.at(-1)).not.toContain('exec /bin/sh -c ');
+ });
+
+ it('emits the POSIX job-control opt-out so the deck stays in the killable process group', () => {
+ const inv = buildSlidevInvocation(
+ { source: 'global', projectRoot: '/proj', docPath: deck, shell: '/bin/bash' },
+ 4300,
+ 'linux',
+ ['/managed/bin'],
+ );
+ expect(inv.args.at(-1)).toContain('; set +m; slidev ');
+ });
+
+ it.each([
+ ['posix', '/bin/bash', 'set +m; '],
+ ['fish', '/usr/bin/fish', 'status job-control none; '],
+ ] as const)(
+ 'keeps the %s job-control opt-out when no managed bin dir resolves, because it is composed above the empty-dirs early return in commandWithManagedPath',
+ (_family, shell, optOut) => {
+ const inv = buildSlidevInvocation(
+ { source: 'global', projectRoot: '/proj', docPath: deck, shell },
+ 4300,
+ 'linux',
+ [],
+ );
+ expect(
+ inv.args.at(-1),
+ 'hasNoResolvableOkHome is a state this build reaches, so folding the opt-out into the PATH reassert would drop it for exactly the users whose managed bin dir does not resolve, and every other opt-out assertion drives a non-empty dir list',
+ ).toBe(`${optOut}slidev '/proj/decks/talk.md' --port 4300`);
+ },
+ );
+
+ it('composes its launch argv from the same shell-mode source as the presence probe', () => {
+ for (const platform of ['darwin', 'linux'] as const) {
+ const inv = buildSlidevInvocation(
+ { source: 'global', projectRoot: '/proj', docPath: deck, shell: '/bin/bash' },
+ 4300,
+ platform,
+ [],
+ );
+ expect(inv.args.slice(0, -2)).toEqual(cliProbeArgs('slidev', platform).slice(0, -2));
+ }
});
it('Windows project-local targets the .cmd shim via cmd.exe', () => {
@@ -403,6 +508,7 @@ describe('buildSlidevInvocation — platform matrix', () => {
{ source: 'project-local', projectRoot: 'C:\\proj', docPath: deck, shell: '' },
4300,
'win32',
+ [],
);
expect(inv.mode).toBe('windows-shell');
expect(inv.file).toBe('cmd.exe');
@@ -418,6 +524,7 @@ describe('buildSlidevInvocation — platform matrix', () => {
{ source: 'global', projectRoot: 'C:\\proj', docPath: deck, shell: '' },
4300,
'win32',
+ [],
);
expect(inv.mode).toBe('windows-shell');
expect(inv.file).toBe('cmd.exe');
@@ -431,6 +538,7 @@ describe('buildSlidevInvocation — platform matrix', () => {
{ source, projectRoot: 'C:\\proj', docPath: deck, shell: '' },
4300,
'win32',
+ [],
);
expect(inv.args).not.toContain('-l');
expect(inv.args).not.toContain('-i');
@@ -446,6 +554,7 @@ describe('buildSlidevInvocation — Windows command-line injection', () => {
{ source: 'global', projectRoot: 'C:\\proj', docPath: evil, shell: '' },
4300,
'win32',
+ [],
);
expect(inv.args).not.toContain(evil);
const cmdline = inv.args[3] ?? '';
@@ -488,22 +597,21 @@ describe('signalSlidevChild', () => {
});
it('logs a failed Windows tree kill without retrying a bare PID', async () => {
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ slidevLog.warn.mockClear();
const { child, kill } = fakeChild();
const killWindowsTree = vi.fn(() => Promise.reject(new Error('taskkill failed')));
await signalSlidevChild(child, 'SIGKILL', { platform: 'win32', killWindowsTree });
- expect(warnSpy).toHaveBeenCalledTimes(1);
+ expect(slidevWarnRecords()).toHaveLength(1);
expect(killWindowsTree).toHaveBeenCalledTimes(1);
expect(kill).not.toHaveBeenCalled();
- expect(JSON.parse(warnSpy.mock.calls[0]?.[0] as string)).toMatchObject({
+ expect(slidevWarnRecords()[0]).toMatchObject({
event: 'slides-tree-kill-failed',
pid: 4321,
signal: 'SIGKILL',
- message: 'taskkill failed',
+ err: new Error('taskkill failed'),
});
- warnSpy.mockRestore();
});
it('waits for the Windows tree kill to settle', async () => {
@@ -533,7 +641,7 @@ describe('signalSlidevChild', () => {
it('bounds a hanging Windows tree kill', async () => {
vi.useFakeTimers();
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ slidevLog.warn.mockClear();
try {
const { child } = fakeChild();
const signal = signalSlidevChild(child, 'SIGTERM', {
@@ -545,13 +653,127 @@ describe('signalSlidevChild', () => {
await vi.advanceTimersByTimeAsync(5_000);
await signal;
- expect(JSON.parse(warnSpy.mock.calls[0]?.[0] as string)).toMatchObject({
+ expect(slidevWarnRecords()[0]).toMatchObject({
event: 'slides-tree-kill-failed',
- message: 'taskkill timed out',
+ err: new Error('taskkill timed out'),
});
} finally {
- warnSpy.mockRestore();
vi.useRealTimers();
}
});
});
+
+describe('composeSlidevSpawnEnv', () => {
+ const alwaysDir = () => true;
+
+ it('strips the Electron and GDK markers the terminal strips, so the login shell child sees the same env', () => {
+ const env = composeSlidevSpawnEnv(
+ {
+ PATH: '/usr/bin',
+ HOME: '/home/alice',
+ OK_ELECTRON_PROTOCOL_HOST: '1',
+ OK_LOCK_KIND: 'interactive',
+ ELECTRON_RUN_AS_NODE: '1',
+ GDK_PIXBUF_MODULEDIR: '/app/lib/gdk-pixbuf',
+ GDK_PIXBUF_MODULE_FILE: '/app/lib/loaders.cache',
+ GDK_THEME: 'Adwaita',
+ },
+ { platform: 'linux', home: '/home/alice' },
+ () => false,
+ );
+ expect(env.OK_ELECTRON_PROTOCOL_HOST).toBeUndefined();
+ expect(env.OK_LOCK_KIND).toBeUndefined();
+ expect(env.ELECTRON_RUN_AS_NODE).toBeUndefined();
+ expect(env.GDK_PIXBUF_MODULEDIR).toBeUndefined();
+ expect(env.GDK_PIXBUF_MODULE_FILE).toBeUndefined();
+ expect(env.GDK_THEME).toBe('Adwaita');
+ });
+
+ it('does not mark the slidev child as the OK Desktop terminal', () => {
+ const env = composeSlidevSpawnEnv(
+ { PATH: '/usr/bin', HOME: '/home/alice' },
+ { platform: 'linux', home: '/home/alice' },
+ () => false,
+ );
+ expect(env.OK_DESKTOP_TERMINAL).toBeUndefined();
+ });
+
+ it('leads PATH with the OK-managed bin dir, ahead of the appended tool dirs', () => {
+ const env = composeSlidevSpawnEnv(
+ { PATH: '/usr/bin', HOME: '/Users/alice' },
+ { platform: 'darwin', home: '/Users/alice' },
+ alwaysDir,
+ );
+ const entries = (env.PATH ?? '').split(':');
+ expect(entries[0]).toBe('/Users/alice/.ok/bin');
+ expect(entries).toContain('/opt/homebrew/bin');
+ expect(entries.indexOf('/usr/bin')).toBeLessThan(entries.indexOf('/opt/homebrew/bin'));
+ });
+
+ it('writes through the inherited PATH key casing on win32 rather than adding a second key', () => {
+ const env = composeSlidevSpawnEnv(
+ { Path: 'C:\\Windows\\System32', HOME: 'C:\\Users\\alice' },
+ { platform: 'win32', home: 'C:\\Users\\alice', cliBinDir: 'C:\\ok\\resources\\cli\\bin' },
+ alwaysDir,
+ );
+ expect(env.PATH).toBeUndefined();
+ expect((env.Path ?? '').split(';')[0]).toBe('C:\\ok\\resources\\cli\\bin');
+ });
+});
+
+describe('missing Slidev child home', () => {
+ it.each([undefined, ''])('warns without probing root tool directories for home %s', (home) => {
+ slidevLog.warn.mockClear();
+ const isDir = vi.fn(() => true);
+ const env = composeSlidevSpawnEnv({ PATH: '/usr/bin' }, { platform: 'linux', home }, isDir);
+ expect(env.PATH).toBe('/usr/bin');
+ expect(isDir).not.toHaveBeenCalled();
+ expect(slidevLog.warn).toHaveBeenCalledWith(
+ { event: 'slides-no-ok-managed-home', platform: 'linux' },
+ expect.any(String),
+ );
+ });
+});
+
+describe('slidevSpawnEnv', () => {
+ function withParentEnv(overrides: Record<string, string>, run: () => void): void {
+ const prior = new Map(Object.keys(overrides).map((key) => [key, process.env[key]]));
+ Object.assign(process.env, overrides);
+ try {
+ run();
+ } finally {
+ for (const [key, value] of prior) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+ }
+
+ it('runs the launch through the shared composer, so the markers the terminal strips are stripped here too', () => {
+ withParentEnv(
+ {
+ OK_LOCK_KIND: 'interactive',
+ ELECTRON_RUN_AS_NODE: '1',
+ OK_ELECTRON_PROTOCOL_HOST: '1',
+ GDK_PIXBUF_MODULEDIR: '/app/lib/gdk-pixbuf',
+ },
+ () => {
+ const env = slidevSpawnEnv();
+ expect(env.OK_LOCK_KIND).toBeUndefined();
+ expect(env.ELECTRON_RUN_AS_NODE).toBeUndefined();
+ expect(env.OK_ELECTRON_PROTOCOL_HOST).toBeUndefined();
+ expect(env.GDK_PIXBUF_MODULEDIR).toBeUndefined();
+ },
+ );
+ });
+
+ it.skipIf(process.platform === 'win32')(
+ 'puts the OK-managed bin dir its own options resolve onto the launch PATH',
+ () => {
+ const options = okChildEnvOptionsFromProcess();
+ const dirs = okManagedBinDirs(options);
+ expect(dirs).toHaveLength(1);
+ expect(okChildPathEntries(slidevSpawnEnv(), options)).toContain(dirs[0]);
+ },
+ );
+});
diff --git a/packages/desktop/src/main/slidev-server.ts b/packages/desktop/src/main/slidev-server.ts
index 4b9c9b93f..fb55dc5e2 100644
--- a/packages/desktop/src/main/slidev-server.ts
+++ b/packages/desktop/src/main/slidev-server.ts
@@ -1,9 +1,24 @@
import { type ChildProcess, spawn } from 'node:child_process';
import { statSync } from 'node:fs';
import { createServer } from 'node:net';
-import { homedir } from 'node:os';
-import { delimiter } from 'node:path';
import { augmentAgentSpawnPath } from '@inkeep/open-knowledge-core';
+import {
+ composeOkChildEnv,
+ hasNoResolvableOkHome,
+ type OkManagedBinDirsOptions,
+ okChildEnvOptionsFromProcess,
+ okManagedBinDirs,
+ okPathDelimiter,
+} from '../shared/ok-child-env.ts';
+import {
+ commandWithManagedPath,
+ interactiveShellArgs,
+ quoteShellArg,
+ type ShellCommandFamily,
+ shellCommandFamily,
+} from '../shared/terminal-shell.ts';
+import { windowsPathKey } from '../shared/windows-env.ts';
+import { getLogger } from './desktop-logger.ts';
import { projectLocalSlidevBin } from './slidev-resolve.ts';
export interface SlidevProcess {
@@ -16,7 +31,12 @@ export interface SlidevProcess {
export type ReadinessProbe = { reachable: false } | { reachable: true; hasVersionMeta: boolean };
-type SlidevStartFailure = 'spawn-error' | 'exited-early' | 'timeout' | 'unsupported-server';
+type SlidevStartFailure =
+ | 'spawn-error'
+ | 'port-error'
+ | 'exited-early'
+ | 'timeout'
+ | 'unsupported-server';
export type StartSlidevResult =
| { ok: true; port: number; process: SlidevProcess }
@@ -36,6 +56,13 @@ export interface StartSlidevDeps {
const DEFAULT_TIMEOUT_MS = 20_000;
const DEFAULT_POLL_INTERVAL_MS = 250;
+function logSlidevFailure(event: string, err: unknown): void {
+ getLogger('slidev-server').warn(
+ { event, code: (err as NodeJS.ErrnoException | null)?.code ?? null, err },
+ 'slidev server failure',
+ );
+}
+
export async function startSlidevServer(deps: StartSlidevDeps): Promise<StartSlidevResult> {
const timeoutMs = deps.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const pollIntervalMs = deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
@@ -44,15 +71,14 @@ export async function startSlidevServer(deps: StartSlidevDeps): Promise<StartSli
let child: SlidevProcess;
try {
port = await deps.findFreePort();
+ } catch (err) {
+ logSlidevFailure('slides-port-error', err);
+ return { ok: false, reason: 'port-error' };
+ }
+ try {
child = deps.spawnSlidev(port);
} catch (err) {
- console.warn(
- JSON.stringify({
- event: 'slides-spawn-error',
- code: (err as NodeJS.ErrnoException | null)?.code ?? null,
- message: err instanceof Error ? err.message : String(err),
- }),
- );
+ logSlidevFailure('slides-spawn-error', err);
return { ok: false, reason: 'spawn-error' };
}
deps.onSpawned?.(child);
@@ -130,7 +156,12 @@ export type SlidevSpawnConfig = {
export type SlidevInvocation =
| { readonly mode: 'direct'; readonly file: string; readonly args: readonly string[] }
- | { readonly mode: 'login-shell'; readonly file: string; readonly args: readonly string[] }
+ | {
+ readonly mode: 'interactive-shell';
+ readonly file: string;
+ readonly args: readonly string[];
+ readonly family: ShellCommandFamily;
+ }
| {
readonly mode: 'windows-shell';
readonly file: string;
@@ -138,18 +169,21 @@ export type SlidevInvocation =
readonly verbatim: true;
};
-function shSingleQuote(value: string): string {
- return `'${value.replace(/'/g, `'\\''`)}'`;
-}
-
function cmdQuote(value: string): string {
return `"${value}"`;
}
+const JOB_CONTROL_OPT_OUT: Record<ShellCommandFamily, string> = {
+ posix: 'set +m; ',
+ fish: 'status job-control none; ',
+ fallback: '',
+};
+
export function buildSlidevInvocation(
config: SlidevSpawnConfig,
port: number,
- platform: NodeJS.Platform = process.platform,
+ platform: NodeJS.Platform,
+ managedBinDirs: readonly string[],
): SlidevInvocation {
const portArgs = ['--port', String(port)];
if (platform === 'win32') {
@@ -169,8 +203,16 @@ export function buildSlidevInvocation(
const bin = projectLocalSlidevBin(config.projectRoot, platform);
return { mode: 'direct', file: bin, args: [config.docPath, ...portArgs] };
}
- const cmdline = `exec slidev ${shSingleQuote(config.docPath)} ${portArgs.join(' ')}`;
- return { mode: 'login-shell', file: config.shell, args: ['-l', '-i', '-c', cmdline] };
+ const family = shellCommandFamily(config.shell);
+ const runSlidev = `slidev ${quoteShellArg(config.shell, config.docPath)} ${portArgs.join(' ')}`;
+ const launched = `${JOB_CONTROL_OPT_OUT[family]}${runSlidev}`;
+ const cmdline = commandWithManagedPath(config.shell, launched, managedBinDirs);
+ return {
+ mode: 'interactive-shell',
+ file: config.shell,
+ args: [...interactiveShellArgs(platform), '-c', cmdline],
+ family,
+ };
}
export interface SignalSlidevChildDeps {
@@ -225,13 +267,9 @@ export function signalSlidevChild(
settled = true;
clearTimeout(timer);
if (err !== undefined) {
- console.warn(
- JSON.stringify({
- event: 'slides-tree-kill-failed',
- pid,
- signal: sig,
- message: err instanceof Error ? err.message : String(err),
- }),
+ getLogger('slidev-server').warn(
+ { event: 'slides-tree-kill-failed', pid, signal: sig, err },
+ 'slidev server failure',
);
}
resolve();
@@ -264,17 +302,38 @@ function isDir(dir: string): boolean {
}
}
-function repairedSpawnEnv(): NodeJS.ProcessEnv {
- const env: NodeJS.ProcessEnv = { ...process.env };
- env.PATH = augmentAgentSpawnPath(env.PATH, {
- platform: process.platform,
- homeDir: homedir(),
- isDir,
- delimiter,
+export function composeSlidevSpawnEnv(
+ parentEnv: Record<string, string | undefined>,
+ options: OkManagedBinDirsOptions,
+ isDirSync: (dir: string) => boolean = isDir,
+): Record<string, string> {
+ const env = composeOkChildEnv(parentEnv, options);
+ const homeDir = options.home;
+ if (!homeDir) {
+ if (hasNoResolvableOkHome(options)) {
+ getLogger('slidev-server').warn(
+ { event: 'slides-no-ok-managed-home', platform: options.platform },
+ 'Slidev child has no resolvable home directory',
+ );
+ }
+ return env;
+ }
+ const pathKey = windowsPathKey(env);
+ env[pathKey] = augmentAgentSpawnPath(env[pathKey], {
+ platform: options.platform,
+ homeDir,
+ isDir: isDirSync,
+ delimiter: okPathDelimiter(options.platform),
});
return env;
}
+export function slidevSpawnEnv(
+ options: OkManagedBinDirsOptions = okChildEnvOptionsFromProcess(),
+): NodeJS.ProcessEnv {
+ return composeSlidevSpawnEnv(process.env, options);
+}
+
export function adaptSlidevChild(child: ChildProcess): SlidevProcess {
let alive = true;
let spawnError: NodeJS.ErrnoException | undefined;
@@ -286,13 +345,7 @@ export function adaptSlidevChild(child: ChildProcess): SlidevProcess {
alive = false;
spawnError = err;
}
- console.warn(
- JSON.stringify({
- event: 'slides-child-error',
- code: err?.code ?? null,
- message: err instanceof Error ? err.message : String(err),
- }),
- );
+ logSlidevFailure('slides-child-error', err);
});
return {
onExit: (cb) => {
@@ -319,10 +372,26 @@ export function adaptSlidevChild(child: ChildProcess): SlidevProcess {
}
export function realSpawnSlidev(config: SlidevSpawnConfig, port: number): SlidevProcess {
- const invocation = buildSlidevInvocation(config, port);
+ const options = okChildEnvOptionsFromProcess();
+ const invocation = buildSlidevInvocation(
+ config,
+ port,
+ process.platform,
+ okManagedBinDirs(options),
+ );
+ if (invocation.mode === 'interactive-shell') {
+ getLogger('slidev-server').info(
+ {
+ event: 'slides-launch-shell-resolved',
+ platform: options.platform,
+ shellCommandFamily: invocation.family,
+ },
+ 'Slidev deck launches through an interactive shell',
+ );
+ }
const child = spawn(invocation.file, [...invocation.args], {
cwd: config.projectRoot,
- env: repairedSpawnEnv(),
+ env: slidevSpawnEnv(options),
stdio: 'ignore',
shell: false,
detached: process.platform !== 'win32',
diff --git a/packages/desktop/src/shared/ok-child-env.test.ts b/packages/desktop/src/shared/ok-child-env.test.ts
new file mode 100644
index 000000000..940aa3f62
--- /dev/null
+++ b/packages/desktop/src/shared/ok-child-env.test.ts
@@ -0,0 +1,185 @@
+import { homedir } from 'node:os';
+import { describe, expect, test, vi } from 'vitest';
+import { buildShellEnv } from '../utility/pty-host.ts';
+import {
+ composeOkChildEnv,
+ okChildEnvOptions,
+ okChildHome,
+ okManagedBinDirs,
+ okPackagedCliBinDir,
+} from './ok-child-env.ts';
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:os')>();
+ return { ...actual, homedir: vi.fn(actual.homedir) };
+});
+
+const WIN_CLI_BIN = 'C:\\Program Files\\Open Knowledge\\resources\\cli\\bin';
+
+describe('okPackagedCliBinDir', () => {
+ test('is the packaged cli bin under resourcesPath on win32', () => {
+ expect(okPackagedCliBinDir('win32', 'C:\\Program Files\\Open Knowledge\\resources')).toBe(
+ WIN_CLI_BIN,
+ );
+ });
+
+ test('is undefined off win32', () => {
+ expect(
+ okPackagedCliBinDir('darwin', '/Applications/OK.app/Contents/Resources'),
+ ).toBeUndefined();
+ expect(okPackagedCliBinDir('linux', '/opt/ok/resources')).toBeUndefined();
+ });
+
+ test('is undefined when resourcesPath is absent, so it is safe outside Electron', () => {
+ expect(okPackagedCliBinDir('win32', undefined)).toBeUndefined();
+ expect(okPackagedCliBinDir('win32', '')).toBeUndefined();
+ });
+});
+
+describe('okManagedBinDirs', () => {
+ test.each([
+ ['darwin' as const, { home: '/Users/alice' }, ['/Users/alice/.ok/bin']],
+ ['linux' as const, { home: '/home/alice' }, ['/home/alice/.ok/bin']],
+ ['darwin' as const, {}, []],
+ ['win32' as const, { cliBinDir: WIN_CLI_BIN }, [WIN_CLI_BIN]],
+ ['win32' as const, { home: 'C:\\Users\\alice' }, []],
+ ])('%s %o', (platform, options, expected) => {
+ expect(okManagedBinDirs({ platform, ...options })).toEqual(expected);
+ });
+});
+
+describe('composeOkChildEnv PATH grant', () => {
+ test('prepends the OK-managed bin dir on POSIX', () => {
+ const env = composeOkChildEnv(
+ { PATH: '/usr/bin:/bin' },
+ { platform: 'darwin', home: '/Users/alice' },
+ );
+ expect(env.PATH).toBe('/Users/alice/.ok/bin:/usr/bin:/bin');
+ });
+
+ test('leaves an already-present entry where it is rather than moving it to the front', () => {
+ const env = composeOkChildEnv(
+ { PATH: '/opt/x:/Users/alice/.ok/bin:/usr/bin' },
+ { platform: 'darwin', home: '/Users/alice' },
+ );
+ expect(env.PATH).toBe('/opt/x:/Users/alice/.ok/bin:/usr/bin');
+ });
+
+ test('leaves PATH untouched when there is no home to resolve against', () => {
+ const env = composeOkChildEnv({ PATH: '/usr/bin' }, { platform: 'linux' });
+ expect(env.PATH).toBe('/usr/bin');
+ });
+
+ test('writes through the inherited PATH key casing on win32 and never adds the POSIX dir', () => {
+ const env = composeOkChildEnv(
+ { Path: 'C:\\Windows\\System32;C:\\Tools', HOME: 'C:\\Users\\alice' },
+ { platform: 'win32', home: 'C:\\Users\\alice', cliBinDir: WIN_CLI_BIN },
+ );
+ expect(env.Path).toBe(`${WIN_CLI_BIN};C:\\Windows\\System32;C:\\Tools`);
+ expect(env.PATH).toBeUndefined();
+ expect(env.Path).not.toContain('.ok');
+ });
+
+ test('dedupes case-insensitively on win32', () => {
+ const env = composeOkChildEnv(
+ { Path: `C:\\Windows;${WIN_CLI_BIN.toUpperCase()}` },
+ { platform: 'win32', cliBinDir: WIN_CLI_BIN },
+ );
+ expect(env.Path).toBe(`C:\\Windows;${WIN_CLI_BIN.toUpperCase()}`);
+ });
+
+ test('seeds PATH when the parent carries none', () => {
+ const env = composeOkChildEnv({}, { platform: 'darwin', home: '/Users/alice' });
+ expect(env.PATH).toBe('/Users/alice/.ok/bin');
+ });
+});
+
+describe('composeOkChildEnv', () => {
+ test('strips OK and Electron markers, drops undefined, and grants the OK-managed bin dir', () => {
+ const env = composeOkChildEnv(
+ {
+ PATH: '/usr/bin',
+ HOME: '/Users/x',
+ OK_ELECTRON_PROTOCOL_HOST: '1',
+ OK_LOCK_KIND: 'interactive',
+ ELECTRON_RUN_AS_NODE: '1',
+ OK_DESKTOP_TERMINAL: '1',
+ OK_HOSTED_AGENT: '1',
+ GDK_PIXBUF_MODULEDIR: '/app/lib/gdk-pixbuf',
+ GDK_PIXBUF_MODULE_FILE: '/app/lib/loaders.cache',
+ ELECTRON_TRASH: 'gio',
+ GDK_THEME: 'Adwaita',
+ MAYBE: undefined,
+ },
+ { platform: 'darwin', home: '/Users/x' },
+ );
+ expect(env).toEqual({
+ PATH: '/Users/x/.ok/bin:/usr/bin',
+ HOME: '/Users/x',
+ ELECTRON_TRASH: 'gio',
+ GDK_THEME: 'Adwaita',
+ });
+ });
+
+ test('does not mark the child as the OK Desktop terminal', () => {
+ const env = composeOkChildEnv(
+ { PATH: '/usr/bin', HOME: '/Users/x' },
+ { platform: 'darwin', home: '/Users/x' },
+ );
+ expect(Object.keys(env).some((key) => key.startsWith('OK_DESKTOP_TERMINAL'))).toBe(false);
+ });
+
+ test('drops an inherited hosted-agent marker instead of passing it to the child', () => {
+ const env = composeOkChildEnv(
+ { PATH: '/usr/bin', HOME: '/Users/x', OK_DESKTOP_TERMINAL: '1', OK_HOSTED_AGENT: '1' },
+ { platform: 'darwin', home: '/Users/x' },
+ );
+ expect(env.OK_DESKTOP_TERMINAL).toBeUndefined();
+ expect(env.OK_HOSTED_AGENT).toBeUndefined();
+ });
+});
+
+describe('okChildHome', () => {
+ test('warns when a terminal cannot grant a managed home', () => {
+ vi.mocked(homedir).mockReturnValueOnce('');
+ const logger = { warn: vi.fn() };
+ const { env } = buildShellEnv({ PATH: '/usr/bin' }, { platform: 'linux', logger });
+ expect(env.PATH).toBe('/usr/bin');
+ expect(logger.warn).toHaveBeenCalledWith({
+ event: 'pty-host-no-ok-managed-home',
+ platform: 'linux',
+ });
+ });
+
+ test('normalizes an empty resolved home to absence', () => {
+ vi.mocked(homedir).mockReturnValueOnce('');
+ expect(okChildHome({ HOME: '' })).toBeUndefined();
+ });
+
+ test('returns absence when the operating system cannot resolve home', () => {
+ vi.mocked(homedir).mockImplementationOnce(() => {
+ throw new Error('no passwd entry');
+ });
+ expect(okChildHome({})).toBeUndefined();
+ });
+
+ test('prefers the parent env HOME, which is what the terminal producer passes', () => {
+ expect(okChildHome({ HOME: '/Users/alice' })).toBe('/Users/alice');
+ });
+
+ test('falls back to the resolved home when the parent env carries none', () => {
+ expect(okChildHome({})).toBe(homedir());
+ });
+});
+
+describe('the terminal producer and the probe consumers derive the same home', () => {
+ test.each([
+ ['a parent env with HOME set', { PATH: '/usr/bin', HOME: '/Users/alice' }],
+ ['a parent env with no HOME at all', { PATH: '/usr/bin' }],
+ ])('%s yields one leading PATH entry for both sides', (_label, parentEnv) => {
+ const options = okChildEnvOptions(parentEnv, { platform: 'darwin' });
+ const consumer = composeOkChildEnv(parentEnv, options);
+ const { env: producer } = buildShellEnv(parentEnv, { platform: 'darwin' });
+ expect((producer.PATH ?? '').split(':')[0]).toBe((consumer.PATH ?? '').split(':')[0]);
+ });
+});
diff --git a/packages/desktop/src/shared/ok-child-env.ts b/packages/desktop/src/shared/ok-child-env.ts
new file mode 100644
index 000000000..02e0a5c8e
--- /dev/null
+++ b/packages/desktop/src/shared/ok-child-env.ts
@@ -0,0 +1,118 @@
+import { homedir } from 'node:os';
+import {
+ OK_DESKTOP_TERMINAL_ENV,
+ OK_HOSTED_AGENT_ENV,
+ posixOkManagedBinDir,
+} from '@inkeep/open-knowledge-core';
+import { windowsPathKey } from './windows-env.ts';
+
+const STRIPPED_ENV_MARKERS = [
+ 'OK_ELECTRON_PROTOCOL_HOST',
+ 'OK_LOCK_KIND',
+ 'ELECTRON_RUN_AS_NODE',
+ OK_DESKTOP_TERMINAL_ENV,
+ OK_HOSTED_AGENT_ENV,
+] as const;
+
+export interface OkManagedBinDirsOptions {
+ readonly platform: NodeJS.Platform;
+ readonly home?: string | undefined;
+ readonly cliBinDir?: string | undefined;
+}
+
+export function okPackagedCliBinDir(
+ platform: NodeJS.Platform,
+ resourcesPath: string | undefined,
+): string | undefined {
+ if (platform !== 'win32' || !resourcesPath) return undefined;
+ return `${resourcesPath}\\cli\\bin`;
+}
+
+export function okChildHome(parentEnv: Record<string, string | undefined>): string | undefined {
+ if (parentEnv.HOME) return parentEnv.HOME;
+ try {
+ return homedir() || undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+export function okChildEnvOptions(
+ parentEnv: Record<string, string | undefined>,
+ overrides: { platform?: NodeJS.Platform; cliBinDir?: string } = {},
+): OkManagedBinDirsOptions {
+ return {
+ platform: overrides.platform ?? process.platform,
+ home: okChildHome(parentEnv),
+ cliBinDir: overrides.cliBinDir,
+ };
+}
+
+export function okChildEnvOptionsFromProcess(): OkManagedBinDirsOptions {
+ return okChildEnvOptions(process.env, {
+ cliBinDir: okPackagedCliBinDir(process.platform, process.resourcesPath),
+ });
+}
+
+export function okManagedBinDirs(options: OkManagedBinDirsOptions): readonly string[] {
+ if (options.platform === 'win32') return options.cliBinDir ? [options.cliBinDir] : [];
+ return options.home ? [posixOkManagedBinDir(options.home)] : [];
+}
+
+export function hasNoResolvableOkHome(options: OkManagedBinDirsOptions): boolean {
+ return options.platform !== 'win32' && !options.home;
+}
+
+export function okPathDelimiter(platform: NodeJS.Platform): string {
+ return platform === 'win32' ? ';' : ':';
+}
+
+function entryMatchesDir(entry: string, dir: string, platform: NodeJS.Platform): boolean {
+ return platform === 'win32' ? entry.toLowerCase() === dir.toLowerCase() : entry === dir;
+}
+
+export function okChildPathEntries(
+ env: Record<string, string | undefined>,
+ options: OkManagedBinDirsOptions,
+): readonly string[] {
+ return (env[windowsPathKey(env)] ?? '').split(okPathDelimiter(options.platform)).filter(Boolean);
+}
+
+export function hasOkManagedBinDirsOnPath(
+ env: Record<string, string | undefined>,
+ options: OkManagedBinDirsOptions,
+): boolean {
+ const dirs = okManagedBinDirs(options);
+ if (dirs.length === 0) return false;
+ const entries = okChildPathEntries(env, options);
+ return dirs.every((dir) =>
+ entries.some((entry) => entryMatchesDir(entry, dir, options.platform)),
+ );
+}
+
+function prependOkManagedBinDirs(
+ env: Record<string, string>,
+ options: OkManagedBinDirsOptions,
+): Record<string, string> {
+ const entries = okChildPathEntries(env, options);
+ const additions = okManagedBinDirs(options).filter(
+ (dir) => !entries.some((entry) => entryMatchesDir(entry, dir, options.platform)),
+ );
+ if (additions.length === 0) return { ...env };
+ const joined = [...additions, ...entries].join(okPathDelimiter(options.platform));
+ return { ...env, [windowsPathKey(env)]: joined };
+}
+
+export function composeOkChildEnv(
+ parentEnv: Record<string, string | undefined>,
+ options: OkManagedBinDirsOptions,
+): Record<string, string> {
+ const stripped = new Set<string>(STRIPPED_ENV_MARKERS);
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(parentEnv)) {
+ if (value === undefined) continue;
+ if (stripped.has(key) || key.startsWith('GDK_PIXBUF_')) continue;
+ out[key] = value;
+ }
+ return prependOkManagedBinDirs(out, options);
+}
diff --git a/packages/desktop/src/shared/terminal-shell.test.ts b/packages/desktop/src/shared/terminal-shell.test.ts
new file mode 100644
index 000000000..f9f6c5161
--- /dev/null
+++ b/packages/desktop/src/shared/terminal-shell.test.ts
@@ -0,0 +1,63 @@
+import { spawnSync } from 'node:child_process';
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import { commandWithManagedPath } from './terminal-shell.ts';
+
+const zsh = ['/bin/zsh', '/usr/bin/zsh'].find(existsSync);
+const bash = ['/bin/bash', '/usr/bin/bash'].find(existsSync);
+
+describe.skipIf(zsh === undefined)('commandWithManagedPath', () => {
+ test('keeps startup-defined functions available in the initialized shell', () => {
+ const zdotdir = mkdtempSync(join(tmpdir(), 'ok-managed-path-zsh-'));
+ try {
+ writeFileSync(join(zdotdir, '.zshrc'), 'slidev() { exit 42; }\n');
+ const command = commandWithManagedPath(zsh ?? '/bin/zsh', 'slidev deck.md --port 4300', [
+ '/managed/bin',
+ ]);
+ const child = spawnSync(zsh ?? '/bin/zsh', ['-i', '-c', command], {
+ env: { ...process.env, ZDOTDIR: zdotdir },
+ encoding: 'utf8',
+ });
+ expect(child.status, child.stderr).toBe(42);
+ } finally {
+ rmSync(zdotdir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe.skipIf(bash === undefined)('commandWithManagedPath in Bash', () => {
+ test('launches a function accepted by the presence probe', () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-managed-path-bash-'));
+ try {
+ writeFileSync(join(home, '.bashrc'), 'slidev() { exit 43; }\n');
+ const shell = bash ?? '/bin/bash';
+ const command = commandWithManagedPath(shell, 'slidev deck.md --port 4300', ['/managed/bin']);
+ const child = spawnSync(shell, ['-i', '-c', command], {
+ env: { ...process.env, HOME: home },
+ encoding: 'utf8',
+ });
+ expect(child.status, child.stderr).toBe(43);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('commandWithManagedPath with no managed bin dir', () => {
+ test.each([
+ ['posix', '/bin/zsh'],
+ ['fish', '/usr/bin/fish'],
+ ['unrecognized', '/usr/bin/nu'],
+ ])(
+ 'returns the command untouched for a %s shell, wrapping nothing around it',
+ (_family, shell) => {
+ const command = 'slidev deck.md --port 4300';
+ expect(
+ commandWithManagedPath(shell, command, []),
+ 'there is no reassert to carry when no dir resolves, and posixReassert([], cmd) is a syntax error, so the early return is the contract rather than an optimization',
+ ).toBe(command);
+ },
+ );
+});
diff --git a/packages/desktop/src/shared/terminal-shell.ts b/packages/desktop/src/shared/terminal-shell.ts
index 471e67360..6b767b3f4 100644
--- a/packages/desktop/src/shared/terminal-shell.ts
+++ b/packages/desktop/src/shared/terminal-shell.ts
@@ -1,3 +1,57 @@
+import { shellSingleQuote } from '@inkeep/open-knowledge-core';
+
export function interactiveShellArgs(platform: NodeJS.Platform): readonly string[] {
return platform === 'linux' ? ['-i'] : ['-l', '-i'];
}
+
+function fishSingleQuote(value: string): string {
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
+}
+
+const POSIX_SHELL_NAMES = new Set(['ash', 'bash', 'dash', 'ksh', 'ksh93', 'mksh', 'sh', 'zsh']);
+
+export type ShellCommandFamily = 'posix' | 'fish' | 'fallback';
+
+export function shellCommandFamily(shell: string): ShellCommandFamily {
+ const shellName = shell.replace(/\\/g, '/').split('/').at(-1)?.toLowerCase() ?? '';
+ if (shellName === 'fish') return 'fish';
+ return POSIX_SHELL_NAMES.has(shellName) ? 'posix' : 'fallback';
+}
+
+export function quoteShellArg(shell: string, value: string): string {
+ return shellCommandFamily(shell) === 'fish' ? fishSingleQuote(value) : shellSingleQuote(value);
+}
+
+function posixReassert(managedBinDirs: readonly string[], command: string): string {
+ const guards = [...managedBinDirs]
+ .reverse()
+ .map((dir) => {
+ const quoted = shellSingleQuote(dir);
+ return `case ":$PATH:" in *:${quoted}:*) ;; *) PATH=${quoted}"\${PATH:+:$PATH}" ;; esac`;
+ })
+ .join('; ');
+ return `${guards}; export PATH; ${command}`;
+}
+
+function fishReassert(managedBinDirs: readonly string[], command: string): string {
+ const guards = [...managedBinDirs]
+ .reverse()
+ .map((dir) => {
+ const quoted = fishSingleQuote(dir);
+ return `if not contains ${quoted} $PATH; set -gx PATH ${quoted} $PATH; end`;
+ })
+ .join('; ');
+ return `${guards}; ${command}`;
+}
+
+export function commandWithManagedPath(
+ shell: string,
+ command: string,
+ managedBinDirs: readonly string[],
+): string {
+ if (managedBinDirs.length === 0) return command;
+ const family = shellCommandFamily(shell);
+ if (family === 'fish') return fishReassert(managedBinDirs, command);
+ const inner = posixReassert(managedBinDirs, command);
+ return family === 'posix' ? inner : `exec /bin/sh -c ${shellSingleQuote(inner)}`;
+}
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
index f37800e3e..270ce688b 100644
--- a/packages/desktop/src/utility/pty-host.ts
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -1,12 +1,13 @@
import { execFileSync } from 'node:child_process';
import { existsSync, readdirSync } from 'node:fs';
import { userInfo } from 'node:os';
-import { basename, delimiter, join, win32 } from 'node:path';
+import { basename, win32 } from 'node:path';
import {
composeWindowsShellLaunchArgs,
launchWithoutSupportFile,
OK_DESKTOP_TERMINAL_ENV,
resolveWindowsShellFamily,
+ shellSingleQuote,
type TerminalLaunchCommand,
type WindowsShellFamily,
WindowsShellLaunchError,
@@ -17,8 +18,19 @@ import type {
TerminalShellNoticeReason,
TerminalSupportFileNoticeReason,
} from '../shared/bridge-contract.ts';
-import { interactiveShellArgs } from '../shared/terminal-shell.ts';
-import { getWindowsEnvValue, windowsPathKey, windowsWherePathArgs } from '../shared/windows-env.ts';
+import {
+ composeOkChildEnv,
+ hasNoResolvableOkHome,
+ okChildEnvOptions,
+ okManagedBinDirs,
+ okPackagedCliBinDir,
+} from '../shared/ok-child-env.ts';
+import {
+ commandWithManagedPath,
+ interactiveShellArgs,
+ shellCommandFamily,
+} from '../shared/terminal-shell.ts';
+import { getWindowsEnvValue, windowsWherePathArgs } from '../shared/windows-env.ts';
import {
materializeSupportFileSync,
TERMINAL_SUPPORT_FILE_ESCAPE_CODE,
@@ -27,12 +39,6 @@ import {
const DARWIN_FALLBACK_SHELL = '/bin/zsh';
const KILL_ESCALATE_MS = 250;
-const STRIPPED_ENV_MARKERS = [
- 'OK_ELECTRON_PROTOCOL_HOST',
- 'OK_LOCK_KIND',
- 'ELECTRON_RUN_AS_NODE',
-] as const;
-
export interface PtyCreateMessage {
type: 'create';
ptyId: string;
@@ -497,7 +503,8 @@ export function resolveShell(
export function buildShellArgs(
platform: NodeJS.Platform,
shell: string,
- launchCommand?: string | TerminalLaunchCommand,
+ launchCommand: string | TerminalLaunchCommand | undefined,
+ managedBinDirs: readonly string[],
): string[] | string {
if (platform === 'win32') {
return typeof launchCommand === 'object'
@@ -506,43 +513,36 @@ export function buildShellArgs(
}
const interactiveArgs = [...interactiveShellArgs(platform)];
if (typeof launchCommand !== 'string' || launchCommand.length === 0) return interactiveArgs;
- const quotedShell = `'${shell.replace(/'/g, "'\\''")}'`;
+ const quotedShell = shellSingleQuote(shell);
return [
...interactiveArgs,
'-c',
- `${launchCommand}; exec ${quotedShell} ${interactiveArgs.join(' ')}`,
+ commandWithManagedPath(
+ shell,
+ `${launchCommand}; exec ${quotedShell} ${interactiveArgs.join(' ')}`,
+ managedBinDirs,
+ ),
];
}
export function buildShellEnv(
parentEnv: Record<string, string | undefined>,
- options: { platform?: NodeJS.Platform; cliBinDir?: string } = {},
-): Record<string, string> {
- const stripped = new Set<string>(STRIPPED_ENV_MARKERS);
- const out: Record<string, string> = {};
- for (const [key, value] of Object.entries(parentEnv)) {
- if (value === undefined) continue;
- if (stripped.has(key) || key.startsWith('GDK_PIXBUF_')) continue;
- out[key] = value;
- }
- const platform = options.platform ?? process.platform;
- const pathKey = windowsPathKey(out);
- if (platform === 'win32' && options.cliBinDir) {
- const entries = (out[pathKey] ?? '').split(';').filter(Boolean);
- if (!entries.some((entry) => entry.toLowerCase() === options.cliBinDir?.toLowerCase())) {
- out[pathKey] = [options.cliBinDir, ...entries].join(';');
- }
- }
- const home = out.HOME;
- if (platform !== 'win32' && home) {
- const okBin = join(home, '.ok', 'bin');
- const entries = (out[pathKey] ?? '').split(delimiter).filter(Boolean);
- if (!entries.includes(okBin)) {
- out[pathKey] = [okBin, ...entries].join(delimiter);
- }
+ options: {
+ platform?: NodeJS.Platform;
+ cliBinDir?: string;
+ logger?: { warn: (data: Record<string, unknown>) => void };
+ } = {},
+): { env: Record<string, string>; managedBinDirs: readonly string[] } {
+ const childOptions = okChildEnvOptions(parentEnv, {
+ platform: options.platform,
+ cliBinDir: options.cliBinDir,
+ });
+ if (hasNoResolvableOkHome(childOptions)) {
+ options.logger?.warn({ event: 'pty-host-no-ok-managed-home', platform: childOptions.platform });
}
+ const out = composeOkChildEnv(parentEnv, childOptions);
out[OK_DESKTOP_TERMINAL_ENV] = '1';
- return out;
+ return { env: out, managedBinDirs: okManagedBinDirs(childOptions) };
}
const CONPTY_DLL_LOAD_ERROR_PREFIXES = {
@@ -655,6 +655,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
event: 'pty-host-shell-resolved',
platform,
rung: resolution.rung,
+ shellCommandFamily: platform === 'win32' ? undefined : shellCommandFamily(resolution.shell),
});
const shell = resolution.shell;
if (platform === 'win32') {
@@ -663,7 +664,11 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
post({ type: 'shell-notice', ptyId, notice: 'shell-resolved', shellFamily });
}
}
- const shellEnv = buildShellEnv(env, { platform, cliBinDir: deps.cliBinDir });
+ const { env: shellEnv, managedBinDirs } = buildShellEnv(env, {
+ platform,
+ cliBinDir: deps.cliBinDir,
+ logger: deps.logger,
+ });
let launchCommand = message.launchCommand;
if (
platform === 'win32' &&
@@ -704,7 +709,7 @@ export function setupPtyHost(deps: SetupPtyHostDeps): PtyHostHandle {
}
let shellArgs: string[] | string;
try {
- shellArgs = buildShellArgs(platform, shell, launchCommand);
+ shellArgs = buildShellArgs(platform, shell, launchCommand, managedBinDirs);
} catch (error) {
const launchFailure = error instanceof WindowsShellLaunchError ? error.reason : null;
deps.logger?.warn({
@@ -944,14 +949,10 @@ if ((process as NodeJS.Process & { parentPort?: unknown }).parentPort) {
exitHost: (code) => process.exit(code),
flushLogger,
env: process.env,
- cliBinDir:
- process.platform === 'win32'
- ? join(
- (process as NodeJS.Process & { resourcesPath: string }).resourcesPath,
- 'cli',
- 'bin',
- )
- : undefined,
+ cliBinDir: okPackagedCliBinDir(
+ process.platform,
+ (process as NodeJS.Process & { resourcesPath?: string }).resourcesPath,
+ ),
logger: {
warn: (o) => log.warn(o, 'pty-host warning'),
info: (o) => log.info(o, 'pty-host shell resolution'),
diff --git a/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts b/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
new file mode 100644
index 000000000..afd0a0c2a
--- /dev/null
+++ b/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
@@ -0,0 +1,610 @@
+import { spawn, spawnSync } from 'node:child_process';
+import { randomUUID } from 'node:crypto';
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { TERMINAL_CLI_IDS, TERMINAL_CLIS } from '@inkeep/open-knowledge-core';
+import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
+
+const desktopLog = vi.hoisted(() => ({
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ debug: vi.fn(),
+}));
+vi.mock('../../src/main/desktop-logger.ts', () => ({ getLogger: () => desktopLog }));
+
+import {
+ cliProbeArgs,
+ type ProbeSpawn,
+ type ProbeTimers,
+ probePlatformCliOnPath,
+ resolvePlatformCliInstalledMap,
+ runLoginShellProbe,
+} from '../../src/main/claude-readiness.ts';
+import { handleSlidesStatus } from '../../src/main/ipc/slides.ts';
+import { realProbeSpawn, realProbeTimers } from '../../src/main/probe-spawn.ts';
+import {
+ buildSlidevInvocation,
+ composeSlidevSpawnEnv,
+ findFreePort,
+ realSpawnSlidev,
+ type SlidevProcess,
+} from '../../src/main/slidev-server.ts';
+import { buildShellEnv } from '../../src/utility/pty-host.ts';
+import {
+ createRecordDir,
+ createScratchHomeWithOkBin,
+ firstShellOnDisk,
+ MINIMAL_PARENT_PATH,
+ RC_WITHOUT_MANAGED_BLOCK,
+} from '../support/ok-bin-scratch-home.test-helper.ts';
+
+const SENTINEL_EXIT_CODE = 42;
+const SLIDEV_BIN = 'slidev';
+const TERMINAL_CLI_BINS = TERMINAL_CLI_IDS.map((cli) => TERMINAL_CLIS[cli].bin);
+const FIXTURE_ONLY_BIN = `ok-probe-fixture-${randomUUID()}`;
+const CHILD_PATH_RECORD = "child's-path";
+const BIN_ON_THE_BARE_PARENT_PATH = 'ls';
+const LAUNCH_EXIT_TIMEOUT_MS = 20_000;
+const LAUNCH_TIMED_OUT = -1;
+
+const WHY_THIS_PAIRS_WITH_PTY_HOST =
+ 'Pairs with "prepends ~/.ok/bin to the child PATH so ok resolves regardless of rc consent" in ' +
+ 'packages/desktop/tests/utility/pty-host.test.ts. That test pins the producer (buildShellEnv). ' +
+ 'This file pins the consumers. The asserted directory is read back out of buildShellEnv rather ' +
+ 'than written as a literal, so the two halves cannot drift apart silently.';
+
+const probeTimers: ProbeTimers = {
+ setTimer: (cb, ms) => setTimeout(cb, ms),
+ clearTimer: (token) => clearTimeout(token as ReturnType<typeof setTimeout>),
+};
+
+function bareEnvProbeSpawn(): ProbeSpawn {
+ return (file, args) => {
+ const child = spawn(file, [...args], { stdio: 'ignore', shell: false, windowsHide: true });
+ return {
+ onExit: (cb) => {
+ child.on('exit', (code) => cb(code));
+ },
+ onError: (cb) => {
+ child.on('error', (err) => cb(err));
+ },
+ kill: () => {
+ child.kill('SIGKILL');
+ },
+ };
+ };
+}
+
+function recordingProbeSpawn(inner: ProbeSpawn, probedArgv: string[][]): ProbeSpawn {
+ return (file, args) => {
+ probedArgv.push([file, ...args]);
+ return inner(file, args);
+ };
+}
+
+describe.skipIf(process.platform === 'win32')(
+ 'the CLI-presence probes and the Slidev launch run with ~/.ok/bin on their PATH',
+ () => {
+ let scratchHome: string;
+ let recordDir: string;
+ let childPathRecord: string;
+ let shell: string;
+ let previousHome: string | undefined;
+ let previousPath: string | undefined;
+ let previousZdotdir: string | undefined;
+
+ beforeAll(() => {
+ recordDir = createRecordDir();
+ childPathRecord = join(recordDir, CHILD_PATH_RECORD);
+ scratchHome = createScratchHomeWithOkBin({
+ prefix: 'ok-bin-child-path-',
+ bins: [SLIDEV_BIN, ...TERMINAL_CLI_BINS, FIXTURE_ONLY_BIN],
+ exitCode: SENTINEL_EXIT_CODE,
+ recordPath: childPathRecord,
+ });
+ previousHome = process.env.HOME;
+ previousPath = process.env.PATH;
+ previousZdotdir = process.env.ZDOTDIR;
+ process.env.HOME = scratchHome;
+ process.env.PATH = MINIMAL_PARENT_PATH;
+ delete process.env.ZDOTDIR;
+ shell = firstShellOnDisk();
+ });
+
+ afterAll(() => {
+ if (previousHome === undefined) delete process.env.HOME;
+ else process.env.HOME = previousHome;
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ if (previousZdotdir !== undefined) process.env.ZDOTDIR = previousZdotdir;
+ rmSync(scratchHome, { recursive: true, force: true });
+ rmSync(recordDir, { recursive: true, force: true });
+ });
+
+ function appGrantedShellEnv(): NodeJS.ProcessEnv {
+ return buildShellEnv(process.env, { platform: process.platform }).env;
+ }
+
+ function okBinGrantedToOwnShells(): string {
+ return (appGrantedShellEnv().PATH ?? '').split(':')[0] ?? '';
+ }
+
+ function probeThroughBareEnv(bin: string): Promise<number | null> {
+ return runLoginShellProbe(
+ bareEnvProbeSpawn(),
+ shell,
+ probeTimers,
+ undefined,
+ cliProbeArgs(bin, process.platform),
+ );
+ }
+
+ async function expectBareEnvAdapterWorks(): Promise<void> {
+ expect(
+ await probeThroughBareEnv(BIN_ON_THE_BARE_PARENT_PATH),
+ 'the bare-env probe adapter cannot resolve a binary that is on the parent PATH, so every negative result it produces is vacuous',
+ ).toBe(0);
+ }
+
+ test('the PATH OK Desktop grants its own shells leads with ~/.ok/bin', () => {
+ expect(okBinGrantedToOwnShells(), WHY_THIS_PAIRS_WITH_PTY_HOST).toBe(
+ join(scratchHome, '.ok', 'bin'),
+ );
+ });
+
+ test('a probe child inheriting the bare app environment misses a ~/.ok/bin CLI the production seam resolves', async () => {
+ expect(
+ await runLoginShellProbe(
+ realProbeSpawn,
+ shell,
+ realProbeTimers,
+ undefined,
+ cliProbeArgs(FIXTURE_ONLY_BIN, process.platform),
+ ),
+ 'the fixture bin is not a working sentinel, so the negative half below is vacuous',
+ ).toBe(0);
+ await expectBareEnvAdapterWorks();
+ expect(await probeThroughBareEnv(FIXTURE_ONLY_BIN)).not.toBe(0);
+ });
+
+ test('every CLI-presence detection site reports a ~/.ok/bin CLI present, through one probe-spawn seam', async () => {
+ const probedArgv: string[][] = [];
+ const probeSpawn = recordingProbeSpawn(realProbeSpawn, probedArgv);
+ const platform = process.platform;
+ const probePosix = (args: readonly string[]) =>
+ runLoginShellProbe(probeSpawn, shell, realProbeTimers, undefined, args);
+ const probeWindows = () => Promise.resolve(null);
+
+ const slidesStatus = await handleSlidesStatus(undefined, {
+ isExecutableFile: () => Promise.resolve(false),
+ isOnLoginPath: async (bin) => (await probePosix(cliProbeArgs(bin, platform))) === 0,
+ });
+ const claudeReadiness = await probePlatformCliOnPath({
+ platform,
+ bin: TERMINAL_CLIS.claude.bin,
+ probePosix,
+ probeWindows,
+ });
+ const codexOnPath = await probePlatformCliOnPath({
+ platform,
+ bin: TERMINAL_CLIS.codex.bin,
+ probePosix,
+ probeWindows,
+ });
+ const installedMap = await resolvePlatformCliInstalledMap({
+ platform,
+ probePosix,
+ probeWindows,
+ });
+
+ expect(slidesStatus).toEqual({ kind: 'status', available: true, source: 'global' });
+ expect(claudeReadiness).toBe(0);
+ expect(codexOnPath).toBe(0);
+ expect(installedMap).toEqual(Object.fromEntries(TERMINAL_CLI_IDS.map((cli) => [cli, true])));
+ expect(probedArgv.every(([file]) => file === shell)).toBe(true);
+ expect(new Set(probedArgv.map((argv) => argv.at(-1)))).toEqual(
+ new Set(
+ [SLIDEV_BIN, ...TERMINAL_CLI_BINS].map((bin) => cliProbeArgs(bin, platform).at(-1)),
+ ),
+ );
+ });
+
+ describe('the Slidev launch child', () => {
+ let launched: SlidevProcess | undefined;
+ let launchExitCode: number | null = LAUNCH_TIMED_OUT;
+
+ beforeAll(async () => {
+ await expectBareEnvAdapterWorks();
+ if ((await probeThroughBareEnv(SLIDEV_BIN)) === 0) {
+ throw new Error(
+ 'the scratch HOME is compromised: a slidev outside ~/.ok/bin is already reachable from the bare app environment',
+ );
+ }
+ const projectRoot = mkdtempSync(join(tmpdir(), 'ok-bin-child-path-deck-'));
+ const child = realSpawnSlidev(
+ { docPath: join(projectRoot, 'slides.md'), shell, source: 'global', projectRoot },
+ await findFreePort(),
+ );
+ launched = child;
+ launchExitCode = await new Promise<number | null>((resolve) => {
+ const timer = setTimeout(() => resolve(LAUNCH_TIMED_OUT), LAUNCH_EXIT_TIMEOUT_MS);
+ child.onExit((code) => {
+ clearTimeout(timer);
+ resolve(code);
+ });
+ });
+ }, LAUNCH_EXIT_TIMEOUT_MS + 15_000);
+
+ afterAll(async () => {
+ if (launched?.isAlive() === true) await launched.signal('SIGKILL');
+ });
+
+ test('runs the slidev installed in ~/.ok/bin', () => {
+ expect(
+ launchExitCode,
+ launchExitCode === LAUNCH_TIMED_OUT
+ ? 'the launched slidev never exited: it resolved to something other than the ~/.ok/bin sentinel'
+ : 'the launched slidev is not the ~/.ok/bin sentinel',
+ ).toBe(SENTINEL_EXIT_CODE);
+ });
+
+ test('leaves a record of the environment it actually ran with', () => {
+ expect(
+ existsSync(childPathRecord),
+ 'the launched slidev was the sentinel (it exited with the sentinel code) but wrote no record, so the PATH assertion below would report a harness failure as a PATH failure',
+ ).toBe(true);
+ });
+
+ test('runs with ~/.ok/bin on its PATH', () => {
+ const recorded = readFileSync(childPathRecord, 'utf8');
+ expect(recorded.split(':'), WHY_THIS_PAIRS_WITH_PTY_HOST).toContain(
+ okBinGrantedToOwnShells(),
+ );
+ });
+
+ test('records the shell command family on the launch record, which firstShellOnDisk always resolves to posix', () => {
+ expect(
+ desktopLog.info.mock.calls.map(([attrs]) => attrs as Record<string, unknown>),
+ 'the launch is the only one of the shell-family consumers whose record is emitted from a real spawn, so nothing else would notice if the key drifted; firstShellOnDisk only ever returns /bin/zsh, /bin/bash or /bin/sh, every one of which shellCommandFamily classifies posix',
+ ).toContainEqual(
+ expect.objectContaining({
+ event: 'slides-launch-shell-resolved',
+ platform: process.platform,
+ shellCommandFamily: 'posix',
+ }),
+ );
+ });
+ });
+ },
+);
+
+function spawnDeck(
+ shell: string,
+ command: string,
+ args: readonly string[],
+ env?: NodeJS.ProcessEnv,
+) {
+ const child = spawn(shell, [...args.slice(0, -1), command], {
+ stdio: 'ignore',
+ detached: true,
+ ...(env ? { env } : {}),
+ });
+ const shellPid = child.pid ?? 0;
+ const descendants = () =>
+ spawnSync('/bin/ps', ['-eo', 'pid,ppid,pgid'], { encoding: 'utf8' })
+ .stdout.split('\n')
+ .map((line) => line.trim().split(/\s+/).map(Number))
+ .filter((row) => row.length === 3 && row[1] === shellPid);
+ const reap = () => {
+ for (const [pid] of descendants()) {
+ try {
+ process.kill(pid ?? 0, 'SIGKILL');
+ } catch {}
+ }
+ try {
+ process.kill(-shellPid, 'SIGKILL');
+ } catch {}
+ };
+ return { shellPid, descendants, reap };
+}
+
+const FISH_SHELL_CANDIDATES = [
+ '/opt/homebrew/bin/fish',
+ '/usr/local/bin/fish',
+ '/usr/bin/fish',
+] as const;
+const FISH_SHELL = FISH_SHELL_CANDIDATES.find((bin) => existsSync(bin));
+const FISH_DECK_APPEAR_TIMEOUT_MS = 15_000;
+const FISH_DECK_REAP_TIMEOUT_MS = 5_000;
+const FISH_CONTAINMENT_TIMEOUT_MS =
+ FISH_DECK_APPEAR_TIMEOUT_MS * 2 + FISH_DECK_REAP_TIMEOUT_MS + 15_000;
+
+describe.skipIf(!existsSync('/bin/bash'))('Slidev launch process-group containment', () => {
+ test('the launched deck shares the spawned shell process group, so the group kill reaches it', async (ctx) => {
+ const deckDir = mkdtempSync(join(tmpdir(), 'ok-pgid-'));
+ try {
+ const invocation = buildSlidevInvocation(
+ {
+ source: 'global',
+ projectRoot: deckDir,
+ docPath: join(deckDir, 'slides.md'),
+ shell: '/bin/bash',
+ },
+ 4300,
+ 'linux',
+ [join(deckDir, '.ok', 'bin')],
+ );
+ const shipped = `${invocation.args.at(-1)?.replace(/slidev .*$/, '/bin/sleep 60')}; :`;
+ const mutated = shipped.replace('set +m; ', '');
+ expect(shipped).toContain('set +m; ');
+ expect(mutated).not.toContain('set +m; ');
+
+ const control = spawnDeck('/bin/bash', mutated, invocation.args, {
+ ...process.env,
+ HOME: deckDir,
+ });
+ try {
+ await vi.waitFor(() => expect(control.descendants().length).toBeGreaterThan(0), {
+ timeout: 5_000,
+ });
+ const [mutantDeck] = control.descendants();
+ if (mutantDeck?.[2] === control.shellPid) {
+ const version =
+ spawnSync('/bin/bash', ['--version'], { encoding: 'utf8' }).stdout.split('\n')[0] ?? '';
+ ctx.skip(
+ `this host's bash keeps the deck in the shell group even without 'set +m', so it cannot witness the leak: ${version}`,
+ );
+ return;
+ }
+ } finally {
+ control.reap();
+ }
+
+ const shippedRun = spawnDeck('/bin/bash', shipped, invocation.args, {
+ ...process.env,
+ HOME: deckDir,
+ });
+ try {
+ await vi.waitFor(() => expect(shippedRun.descendants().length).toBeGreaterThan(0), {
+ timeout: 5_000,
+ });
+ const [deck] = shippedRun.descendants();
+ expect(
+ deck?.[2],
+ "bash turns job control on from -i alone and then setpgid()s the deck into its own group, where signalSlidevChild's process.kill(-pid) cannot reach it",
+ ).toBe(shippedRun.shellPid);
+ const deckPid = deck?.[0] ?? 0;
+ process.kill(-shippedRun.shellPid, 'SIGKILL');
+ await vi.waitFor(
+ () => {
+ expect(() => process.kill(deckPid, 0)).toThrow();
+ },
+ { timeout: 5_000 },
+ );
+ } finally {
+ shippedRun.reap();
+ }
+ } finally {
+ rmSync(deckDir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('Slidev launch process-group containment on fish', () => {
+ test(
+ 'the fish job-control opt-out keeps the deck in the shell process group even when config.fish turned job control on',
+ async (ctx) => {
+ if (FISH_SHELL === undefined) {
+ ctx.skip(
+ `no fish binary at any of ${FISH_SHELL_CANDIDATES.join(', ')}, so fish containment is UNKNOWN on this host rather than confirmed: the bash arm above degrades this way too, and a silently absent describe would read like a pass in the run summary`,
+ );
+ return;
+ }
+ const fish = FISH_SHELL;
+ const deckDir = mkdtempSync(join(tmpdir(), 'ok-pgid-fish-'));
+ try {
+ mkdirSync(join(deckDir, '.config', 'fish'), { recursive: true });
+ writeFileSync(
+ join(deckDir, '.config', 'fish', 'config.fish'),
+ 'status job-control full\n',
+ 'utf8',
+ );
+ const invocation = buildSlidevInvocation(
+ {
+ source: 'global',
+ projectRoot: deckDir,
+ docPath: join(deckDir, 'slides.md'),
+ shell: fish,
+ },
+ 4300,
+ 'linux',
+ [join(deckDir, '.ok', 'bin')],
+ );
+ const shipped = `${invocation.args.at(-1)?.replace(/slidev .*$/, '/bin/sleep 60')}; true`;
+ const mutated = shipped.replace('status job-control none; ', '');
+ expect(shipped).toContain('status job-control none; ');
+ expect(mutated).not.toContain('status job-control none');
+ expect(
+ shipped,
+ 'fish speaks its own job-control builtin, so the POSIX opt-out would be a command-not-found in the same position',
+ ).not.toContain('set +m');
+
+ const fishEnv = {
+ ...process.env,
+ HOME: deckDir,
+ XDG_CONFIG_HOME: join(deckDir, '.config'),
+ };
+ const control = spawnDeck(fish, mutated, invocation.args, fishEnv);
+ try {
+ await vi.waitFor(() => expect(control.descendants().length).toBeGreaterThan(0), {
+ timeout: FISH_DECK_APPEAR_TIMEOUT_MS,
+ });
+ const [mutantDeck] = control.descendants();
+ if (mutantDeck?.[2] === control.shellPid) {
+ const version = spawnSync(fish, ['--version'], { encoding: 'utf8' }).stdout.trim();
+ ctx.skip(
+ `this host's fish keeps the deck in the shell group even at 'status job-control full' with the opt-out stripped, so it cannot witness the leak: ${version}`,
+ );
+ return;
+ }
+ } finally {
+ control.reap();
+ }
+
+ const shippedRun = spawnDeck(fish, shipped, invocation.args, fishEnv);
+ try {
+ await vi.waitFor(() => expect(shippedRun.descendants().length).toBeGreaterThan(0), {
+ timeout: FISH_DECK_APPEAR_TIMEOUT_MS,
+ });
+ const [deck] = shippedRun.descendants();
+ expect(
+ deck?.[2],
+ `a config.fish carrying 'status job-control full' survives into ${fish} -i -c, where it setpgid()s the deck into its own group and signalSlidevChild's process.kill(-pid) cannot reach it, so the opt-out has to land after startup files rather than in the env layer`,
+ ).toBe(shippedRun.shellPid);
+ const deckPid = deck?.[0] ?? 0;
+ process.kill(-shippedRun.shellPid, 'SIGKILL');
+ await vi.waitFor(
+ () => {
+ expect(() => process.kill(deckPid, 0)).toThrow();
+ },
+ { timeout: FISH_DECK_REAP_TIMEOUT_MS },
+ );
+ } finally {
+ shippedRun.reap();
+ }
+ } finally {
+ rmSync(deckDir, { recursive: true, force: true });
+ }
+ },
+ FISH_CONTAINMENT_TIMEOUT_MS,
+ );
+});
+
+describe.skipIf(!existsSync('/bin/bash'))('Slidev bashrc function detect-and-launch parity', () => {
+ test('a slidev function defined only in ~/.bashrc is both detected and launchable', async () => {
+ const home = createScratchHomeWithOkBin({ prefix: 'ok-bashrc-fn-', bins: [] });
+ const previousHome = process.env.HOME;
+ const previousPath = process.env.PATH;
+ try {
+ writeFileSync(join(home, '.bashrc'), `slidev() { exit ${SENTINEL_EXIT_CODE}; }\n`);
+ for (const loginOnly of ['.bash_profile', '.profile']) {
+ writeFileSync(join(home, loginOnly), RC_WITHOUT_MANAGED_BLOCK);
+ }
+ process.env.HOME = home;
+ process.env.PATH = MINIMAL_PARENT_PATH;
+ expect(
+ await runLoginShellProbe(
+ realProbeSpawn,
+ '/bin/bash',
+ realProbeTimers,
+ undefined,
+ cliProbeArgs('slidev', 'linux'),
+ ),
+ ).toBe(0);
+ const invocation = buildSlidevInvocation(
+ {
+ source: 'global',
+ projectRoot: home,
+ docPath: join(home, 'slides.md'),
+ shell: '/bin/bash',
+ },
+ 4300,
+ 'linux',
+ [],
+ );
+ const child = spawnSync(invocation.file, [...invocation.args], {
+ env: { ...process.env, HOME: home, PATH: MINIMAL_PARENT_PATH },
+ encoding: 'utf8',
+ timeout: 5_000,
+ });
+ expect(child.error).toBeUndefined();
+ expect(child.status, child.stderr).toBe(SENTINEL_EXIT_CODE);
+ } finally {
+ if (previousHome === undefined) delete process.env.HOME;
+ else process.env.HOME = previousHome;
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+describe.skipIf(process.platform === 'win32')('Slidev shell startup PATH replacement', () => {
+ test('reasserts the managed CLI path for detection and launch after shell startup', async () => {
+ const home = createScratchHomeWithOkBin({
+ prefix: 'ok-bin-login-reset-',
+ bins: ['slidev'],
+ exitCode: SENTINEL_EXIT_CODE,
+ });
+ const previousHome = process.env.HOME;
+ const previousPath = process.env.PATH;
+ try {
+ const shellDir = join(home, 'path-reset-shell');
+ mkdirSync(shellDir, { recursive: true });
+ const shell = join(shellDir, 'bash');
+ writeFileSync(
+ shell,
+ '#!/bin/sh\nfor last do :; done\nPATH=/usr/bin:/bin\nexport PATH\nexec /bin/sh -c "$last"\n',
+ );
+ chmodSync(shell, 0o755);
+ const env = composeSlidevSpawnEnv(
+ { HOME: home, PATH: MINIMAL_PARENT_PATH },
+ { platform: 'linux', home },
+ () => false,
+ );
+ const login = spawnSync(shell, ['-l', '-i', '-c', 'exec slidev'], {
+ env,
+ encoding: 'utf8',
+ timeout: 5_000,
+ });
+ expect(login.error).toBeUndefined();
+ expect(login.status).not.toBe(0);
+ process.env.HOME = home;
+ process.env.PATH = MINIMAL_PARENT_PATH;
+ expect(
+ await runLoginShellProbe(
+ realProbeSpawn,
+ shell,
+ realProbeTimers,
+ undefined,
+ cliProbeArgs('slidev', 'linux'),
+ ),
+ ).toBe(0);
+ const invocation = buildSlidevInvocation(
+ {
+ source: 'global',
+ projectRoot: home,
+ docPath: join(home, 'slides.md'),
+ shell,
+ },
+ 4300,
+ 'linux',
+ [join(home, '.ok', 'bin')],
+ );
+ expect(invocation.mode).toBe('interactive-shell');
+ const child = spawnSync(invocation.file, [...invocation.args], {
+ env,
+ encoding: 'utf8',
+ timeout: 5_000,
+ });
+ expect(child.error).toBeUndefined();
+ expect(child.status, child.stderr).toBe(SENTINEL_EXIT_CODE);
+ } finally {
+ if (previousHome === undefined) delete process.env.HOME;
+ else process.env.HOME = previousHome;
+ if (previousPath === undefined) delete process.env.PATH;
+ else process.env.PATH = previousPath;
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/desktop/tests/integration/ok-bin-probe-spawn-wiring.test.ts b/packages/desktop/tests/integration/ok-bin-probe-spawn-wiring.test.ts
new file mode 100644
index 000000000..6baab5186
--- /dev/null
+++ b/packages/desktop/tests/integration/ok-bin-probe-spawn-wiring.test.ts
@@ -0,0 +1,102 @@
+import { readFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const DESKTOP_SRC = resolve(fileURLToPath(new URL('../../src', import.meta.url)));
+const INDEX_TS = join(DESKTOP_SRC, 'main', 'index.ts');
+
+const FIX = (what: string): string =>
+ `\n[ok-bin-probe-spawn] ${what}\n\n` +
+ `OK Desktop creates and populates ~/.ok/bin unconditionally, and buildShellEnv (pty-host.ts)\n` +
+ `prepends it to every shell the app spawns for the user. That is the contract #2405 shipped, and\n` +
+ `pty-host.test.ts pins it on the producer side. The CLI-presence probe adapter is the other end\n` +
+ `of that pair: it composes a child environment for a real shell, so it owes the same PATH.\n` +
+ `Spawning it with the app process environment makes every CLI installed in ~/.ok/bin read as\n` +
+ `absent, and the false negative is silent, because a non-zero exit is indistinguishable from a\n` +
+ `genuine absence. The behavioral half of this pin is\n` +
+ `tests/integration/ok-bin-child-spawn-path.test.ts. This file covers the four call sites, which\n` +
+ `live in the Electron wiring root and cannot be imported under vitest.\n`;
+
+const INDEX_SOURCE = readFileSync(INDEX_TS, 'utf-8');
+
+const DETECTION_SITES = [
+ 'resolveTerminalClaudeReadiness',
+ 'resolveTerminalCliOnPath',
+ 'resolveTerminalCliInstalledMap',
+];
+
+function functionBody(src: string, name: string): string {
+ return new RegExp(`function ${name}\\([\\s\\S]*?\\n\\}`).exec(src)?.[0] ?? '';
+}
+
+describe('every CLI-presence detection site routes through the shared probe adapter', () => {
+ test('index.ts takes its probe adapter from probe-spawn.ts rather than defining its own', () => {
+ const imported = /import \{([^}]*)\} from '\.\/probe-spawn\.ts';/.exec(INDEX_SOURCE)?.[1] ?? '';
+ for (const name of ['realProbeSpawn', 'realProbeTimers']) {
+ expect(
+ imported,
+ FIX(
+ `index.ts does not import ${name} from ./probe-spawn.ts; a locally defined adapter can drift out of the PATH contract on its own.`,
+ ),
+ ).toContain(name);
+ }
+ });
+
+ test.each(['runLoginShellProbe', 'runWindowsPathProbe'])(
+ '%s is fed that one adapter, not a second one defined beside it',
+ (runner) => {
+ const call = new RegExp(`${runner}\\(\\s*([A-Za-z_$][\\w$]*)\\s*,`, 'g');
+ const adapters = [...INDEX_SOURCE.matchAll(call)].map((match) => match[1]);
+ expect(adapters.length, FIX(`${runner} is never called in index.ts.`)).toBeGreaterThan(0);
+ expect(
+ new Set(adapters),
+ FIX(
+ `${runner} is fed ${[...new Set(adapters)].join(', ')}; a second adapter can drift out of the PATH contract on its own.`,
+ ),
+ ).toEqual(new Set(['realProbeSpawn']));
+ },
+ );
+
+ test.each(DETECTION_SITES)(
+ '%s probes through probeLoginShellOnPath / probeWindowsPath',
+ (site) => {
+ const body = functionBody(INDEX_SOURCE, site);
+ expect(body, FIX(`${site}() was not found in index.ts.`)).not.toBe('');
+ expect(
+ body.includes('probeLoginShellOnPath'),
+ FIX(`${site}() no longer probes POSIX presence through probeLoginShellOnPath.`),
+ ).toBe(true);
+ expect(
+ body.includes('probeWindowsPath'),
+ FIX(`${site}() no longer probes Windows presence through probeWindowsPath.`),
+ ).toBe(true);
+ },
+ );
+
+ test('the slides status probe probes through probeLoginShellOnPath / probeWindowsPath', () => {
+ const wiring =
+ /isOnLoginPath:\s*async\s*\([^)]*\)\s*=>[\s\S]*?probeWindowsPath\([^)]*\)[\s\S]*?probeLoginShellOnPath\(\s*cliProbeArgs\(/g;
+ expect(
+ (INDEX_SOURCE.match(wiring) ?? []).length,
+ FIX(
+ 'the ok:slides:dispatch probes no longer resolve slidev through probeLoginShellOnPath / probeWindowsPath.',
+ ),
+ ).toBe(1);
+ });
+
+ test('probeLoginShellOnPath and probeWindowsPath are the only presence probes index.ts wires', () => {
+ const posixSites = (
+ INDEX_SOURCE.match(/probePosix:\s*\([^)]*\)\s*=>\s*probeLoginShellOnPath\(/g) ?? []
+ ).length;
+ const windowsSites = (
+ INDEX_SOURCE.match(/probeWindows:\s*\([^)]*\)\s*=>\s*probeWindowsPath\(/g) ?? []
+ ).length;
+ expect(
+ [posixSites, windowsSites],
+ FIX(
+ `index.ts wires ${posixSites} POSIX and ${windowsSites} Windows presence probes; DETECTION_SITES lists ${DETECTION_SITES.length} (${DETECTION_SITES.join(', ')}). If you ADDED a detection site, add its function name to DETECTION_SITES above so its wiring gets pinned too. If you did not add one, a site stopped routing through the shared adapter.`,
+ ),
+ ).toEqual([DETECTION_SITES.length, DETECTION_SITES.length]);
+ });
+});
diff --git a/packages/desktop/tests/main/claude-readiness.test.ts b/packages/desktop/tests/main/claude-readiness.test.ts
index 596023673..1afad87a7 100644
--- a/packages/desktop/tests/main/claude-readiness.test.ts
+++ b/packages/desktop/tests/main/claude-readiness.test.ts
@@ -301,8 +301,11 @@ describe('windows probe verdict observability (an UNKNOWN must leave a trace)',
const p = runWindowsPathProbe(() => child, 'where.exe', 'claude', timers, 5000);
fireTimeout();
expect(await p).toBe(null);
- const messages = operatorVisibleRecords().map((call) => call.map(String).join(' '));
- expect(messages.some((m) => /timed?\s*out/i.test(m))).toBe(true);
+ expect(
+ operatorVisibleRecords().some((call) =>
+ call.some((arg) => (arg as { timedOut?: unknown })?.timedOut === true),
+ ),
+ ).toBe(true);
});
test("an async where.exe 'error' emits an operator-visible record carrying the cause", async () => {
@@ -349,7 +352,15 @@ describe('windows probe verdict observability (an UNKNOWN must leave a trace)',
.find((arg): arg is Record<string, unknown> => typeof arg === 'object' && arg !== null);
expect(attrs).toBeDefined();
expect(attrs?.bin).toBe('claude');
- expect(Object.keys(attrs ?? {}).sort()).toEqual(['args', 'bin', 'timeoutMs', 'whereExe']);
+ expect(Object.keys(attrs ?? {}).sort()).toEqual([
+ 'args',
+ 'bin',
+ 'exitCode',
+ 'label',
+ 'outcome',
+ 'timedOut',
+ 'timeoutMs',
+ ]);
});
});
@@ -366,8 +377,11 @@ describe('probe verdict observability (an UNKNOWN must leave a trace)', () => {
expect(await p).toBe(null);
const records = operatorVisibleRecords();
expect(records.length).toBeGreaterThan(0);
- const messages = records.map((call) => call.map(String).join(' '));
- expect(messages.some((m) => /timed?\s*out/i.test(m))).toBe(true);
+ expect(
+ records.some((call) =>
+ call.some((arg) => (arg as { timedOut?: unknown })?.timedOut === true),
+ ),
+ ).toBe(true);
});
test("an async spawn 'error' emits an operator-visible log record carrying the cause", async () => {
diff --git a/packages/desktop/tests/support/ok-bin-scratch-home.test-helper.ts b/packages/desktop/tests/support/ok-bin-scratch-home.test-helper.ts
new file mode 100644
index 000000000..013eb6dfd
--- /dev/null
+++ b/packages/desktop/tests/support/ok-bin-scratch-home.test-helper.ts
@@ -0,0 +1,48 @@
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+
+export const MINIMAL_PARENT_PATH = ['/usr/bin', '/bin', '/usr/sbin', '/sbin'].join(':');
+
+export const RC_WITHOUT_MANAGED_BLOCK = '# user rc, with the OpenKnowledge PATH block declined\n';
+
+export const RC_FILES = ['.zshrc', '.zprofile', '.bashrc', '.bash_profile', '.profile'];
+
+export interface ScratchOkHomeOptions {
+ readonly prefix: string;
+ readonly bins: readonly string[];
+ readonly exitCode?: number;
+ readonly recordPath?: string;
+}
+
+function sentinelScript(exitCode: number, recordPath: string | undefined): string {
+ const record =
+ recordPath === undefined
+ ? ''
+ : `printf '%s' "$PATH" > '${recordPath.replace(/'/g, `'\\''`)}'\nprintf '%s' "$HOME" > '${recordPath.replace(/'/g, `'\\''`)}.home'\n`;
+ return `#!/bin/sh\n${record}exit ${exitCode}\n`;
+}
+
+export function createScratchHomeWithOkBin(options: ScratchOkHomeOptions): string {
+ const home = mkdtempSync(join(tmpdir(), options.prefix));
+ const okBin = join(home, '.ok', 'bin');
+ mkdirSync(okBin, { recursive: true });
+ const script = sentinelScript(options.exitCode ?? 0, options.recordPath);
+ for (const bin of options.bins) {
+ const path = join(okBin, bin);
+ writeFileSync(path, script);
+ chmodSync(path, 0o755);
+ }
+ for (const rc of RC_FILES) writeFileSync(join(home, rc), RC_WITHOUT_MANAGED_BLOCK);
+ return home;
+}
+
+export function createRecordDir(): string {
+ return mkdtempSync(join(tmpdir(), 'ok-bin-child-record-'));
+}
+
+export function firstShellOnDisk(): string {
+ const found = ['/bin/zsh', '/bin/bash', '/bin/sh'].find((candidate) => existsSync(candidate));
+ if (found === undefined) throw new Error('no POSIX shell on disk to exercise the probe against');
+ return found;
+}
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index 71cbd23f5..0c9d21f44 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -1,6 +1,18 @@
-import { OK_DESKTOP_TERMINAL_ENV } from '@inkeep/open-knowledge-core';
+import { homedir } from 'node:os';
+
+import {
+ OK_DESKTOP_TERMINAL_ENV,
+ OK_HOSTED_AGENT_ENV,
+ posixOkManagedBinDir,
+} from '@inkeep/open-knowledge-core';
import { TERMINAL_SHELL_NOTICE_REASONS } from '@inkeep/open-knowledge-core/desktop-bridge';
-import { describe, expect, test } from 'vitest';
+import { describe, expect, test, vi } from 'vitest';
+
+vi.mock('node:os', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:os')>();
+ return { ...actual, homedir: vi.fn(actual.homedir) };
+});
+
import { isTerminalPlatform } from '../../src/shared/terminal-platform.ts';
import {
buildShellArgs,
@@ -246,17 +258,58 @@ describe('setupPtyHost — create', () => {
});
test('bakes a launch command into a non-history `-c` spawn with an interactive exec tail', () => {
- const h = makeHarness({ env: { SHELL: '/bin/zsh', PATH: '/usr/bin' } });
+ const env = { SHELL: '/bin/zsh', PATH: '/usr/bin' };
+ const h = makeHarness({ env });
h.fire(CREATE({ launchCommand: "claude 'do the thing'" }));
+ const [managedBinDir] = buildShellEnv(env, { platform: 'darwin' }).managedBinDirs;
+ expect(managedBinDir).toBeDefined();
expect(h.spawnCalls[0]?.file).toBe('/bin/zsh');
expect(h.spawnCalls[0]?.args).toEqual([
'-l',
'-i',
'-c',
- "claude 'do the thing'; exec '/bin/zsh' -l -i",
+ `case ":$PATH:" in *:'${managedBinDir}':*) ;; *) PATH='${managedBinDir}'"\${PATH:+:$PATH}" ;; esac; export PATH; claude 'do the thing'; exec '/bin/zsh' -l -i`,
]);
});
+ test('handleCreate threads the logger, so a POSIX terminal with no home leaves a trace', () => {
+ vi.mocked(homedir).mockReturnValueOnce('');
+ const warnings: Record<string, unknown>[] = [];
+ const h = makeHarness({
+ platform: 'linux',
+ env: { SHELL: '/bin/bash', PATH: '/usr/bin' },
+ shellExists: (path) => path === '/bin/bash',
+ logger: { warn: (entry) => warnings.push(entry) },
+ });
+ h.fire(CREATE());
+ expect(
+ warnings,
+ 'buildShellEnv warns through an injected logger, so dropping `logger: deps.logger` at the handleCreate call site would silently lose the terminal-side missing-home diagnostic',
+ ).toContainEqual({ event: 'pty-host-no-ok-managed-home', platform: 'linux' });
+ });
+
+ test('records the resolved shell command family on POSIX, the platform where the question has an answer', () => {
+ const entries: Record<string, unknown>[] = [];
+ const h = makeHarness({
+ platform: 'linux',
+ env: { SHELL: '/usr/bin/fish', PATH: '/usr/bin' },
+ shellExists: (path) => path === '/usr/bin/fish',
+ logger: { warn: () => {}, info: (entry) => entries.push(entry) },
+ });
+
+ h.fire(CREATE());
+
+ expect(
+ entries,
+ 'the win32 sibling of this assertion cannot see this field (it is undefined there by construction, and toContainEqual reads an undefined-valued key as absent), so without this test the non-win32 path the field exists for is unasserted from both directions',
+ ).toContainEqual({
+ event: 'pty-host-shell-resolved',
+ platform: 'linux',
+ rung: 'env-shell',
+ shellCommandFamily: 'fish',
+ });
+ });
+
test('falls back to /bin/zsh when SHELL is unset', () => {
const h = makeHarness({ env: { PATH: '/usr/bin' } });
h.fire(CREATE());
@@ -274,15 +327,18 @@ describe('setupPtyHost — create', () => {
env: {
SHELL: '/bin/zsh',
PATH: '/usr/bin',
+ HOME: '/Users/alice',
OK_ELECTRON_PROTOCOL_HOST: '1',
OK_LOCK_KIND: 'interactive',
+ [OK_HOSTED_AGENT_ENV]: '1',
},
});
h.fire(CREATE());
const env = h.spawnCalls[0]?.options.env ?? {};
expect(env.OK_ELECTRON_PROTOCOL_HOST).toBeUndefined();
expect(env.OK_LOCK_KIND).toBeUndefined();
- expect(env.PATH).toBe('/usr/bin');
+ expect(env[OK_HOSTED_AGENT_ENV]).toBeUndefined();
+ expect(env.PATH).toBe('/Users/alice/.ok/bin:/usr/bin');
});
test('marks the shell as the OK Desktop terminal (OK_DESKTOP_TERMINAL=1)', () => {
@@ -314,11 +370,14 @@ describe('setupPtyHost — create', () => {
expect(env.PATH).toBe('/opt/x:/Users/alice/.ok/bin:/usr/bin');
});
- test('leaves PATH untouched when HOME is absent (nothing to resolve against)', () => {
+ test('falls back to the home the CLI installer used when the env carries no HOME', () => {
const h = makeHarness({ env: { SHELL: '/bin/zsh', PATH: '/usr/bin' } });
h.fire(CREATE());
const env = h.spawnCalls[0]?.options.env ?? {};
- expect(env.PATH).toBe('/usr/bin');
+ expect(
+ env.PATH,
+ 'index.ts installs the CLI under osHomedir(), not process.env.HOME, so a terminal that skipped the grant here would omit a directory that exists on disk, and would disagree with the probe children that do resolve it',
+ ).toBe(`${posixOkManagedBinDir(homedir())}:/usr/bin`);
});
});
@@ -837,7 +896,14 @@ describe('setupPtyHost — incoming message validation (asIncomingMessage guard)
launchCommand: "x 'y'",
});
expect(h.spawnCalls).toHaveLength(1);
- expect(h.spawnCalls[0]?.args).toEqual(['-l', '-i', '-c', "x 'y'; exec '/bin/zsh' -l -i"]);
+ const [managedBinDir] = buildShellEnv({}, { platform: 'darwin' }).managedBinDirs;
+ expect(managedBinDir).toBeDefined();
+ expect(h.spawnCalls[0]?.args).toEqual([
+ '-l',
+ '-i',
+ '-c',
+ `case ":$PATH:" in *:'${managedBinDir}':*) ;; *) PATH='${managedBinDir}'"\${PATH:+:$PATH}" ;; esac; export PATH; x 'y'; exec '/bin/zsh' -l -i`,
+ ]);
});
test('accepts a structured Windows launch and composes it after shell resolution', () => {
@@ -1025,14 +1091,14 @@ describe('setupPtyHost — incoming message validation (asIncomingMessage guard)
describe('buildShellArgs', () => {
test('a plain tab follows the platform interactive-shell convention', () => {
- expect(buildShellArgs('darwin', '/bin/zsh')).toEqual(['-l', '-i']);
- expect(buildShellArgs('darwin', '/bin/zsh', '')).toEqual(['-l', '-i']);
- expect(buildShellArgs('linux', '/bin/bash')).toEqual(['-i']);
- expect(buildShellArgs('linux', '/bin/bash', '')).toEqual(['-i']);
+ expect(buildShellArgs('darwin', '/bin/zsh', undefined, [])).toEqual(['-l', '-i']);
+ expect(buildShellArgs('darwin', '/bin/zsh', '', [])).toEqual(['-l', '-i']);
+ expect(buildShellArgs('linux', '/bin/bash', undefined, [])).toEqual(['-i']);
+ expect(buildShellArgs('linux', '/bin/bash', '', [])).toEqual(['-i']);
});
test('a macOS launch keeps login flags in the launcher and exec tail', () => {
- expect(buildShellArgs('darwin', '/bin/zsh', "codex 'hi'")).toEqual([
+ expect(buildShellArgs('darwin', '/bin/zsh', "codex 'hi'", [])).toEqual([
'-l',
'-i',
'-c',
@@ -1041,20 +1107,61 @@ describe('buildShellArgs', () => {
});
test('a Linux launch is interactive without forcing login semantics', () => {
- expect(buildShellArgs('linux', '/bin/bash', "codex 'hi'")).toEqual([
+ expect(buildShellArgs('linux', '/bin/bash', "codex 'hi'", [])).toEqual([
'-i',
'-c',
"codex 'hi'; exec '/bin/bash' -i",
]);
});
+ test('reasserts the managed bin dir in the launched CLI command on macOS', () => {
+ expect(buildShellArgs('darwin', '/bin/zsh', "codex 'hi'", ['/managed/bin'])).toEqual([
+ '-l',
+ '-i',
+ '-c',
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: shell parameter expansion in an expected command string, not a JS template placeholder
+ "case \":$PATH:\" in *:'/managed/bin':*) ;; *) PATH='/managed/bin'\"${PATH:+:$PATH}\" ;; esac; export PATH; codex 'hi'; exec '/bin/zsh' -l -i",
+ ]);
+ });
+
+ test('reasserts the managed bin dir in the launched CLI command on Linux', () => {
+ expect(buildShellArgs('linux', '/bin/bash', 'claude', ['/managed/bin'])).toEqual([
+ '-i',
+ '-c',
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: shell parameter expansion in an expected command string, not a JS template placeholder
+ "case \":$PATH:\" in *:'/managed/bin':*) ;; *) PATH='/managed/bin'\"${PATH:+:$PATH}\" ;; esac; export PATH; claude; exec '/bin/bash' -i",
+ ]);
+ });
+
+ test('uses fish list syntax for the reassert when the terminal shell is fish', () => {
+ expect(buildShellArgs('linux', '/usr/bin/fish', 'claude', ['/managed/bin'])).toEqual([
+ '-i',
+ '-c',
+ "if not contains '/managed/bin' $PATH; set -gx PATH '/managed/bin' $PATH; end; claude; exec '/usr/bin/fish' -i",
+ ]);
+ });
+
+ test('a host with no grantable managed dir composes exactly the pre-reassert argv', () => {
+ expect(buildShellArgs('darwin', '/bin/zsh', "codex 'hi'", [])).toEqual([
+ '-l',
+ '-i',
+ '-c',
+ "codex 'hi'; exec '/bin/zsh' -l -i",
+ ]);
+ });
+
+ test('a plain interactive tab is never reasserted, so typed commands keep the user PATH order', () => {
+ expect(buildShellArgs('darwin', '/bin/zsh', undefined, ['/managed/bin'])).toEqual(['-l', '-i']);
+ expect(buildShellArgs('linux', '/bin/bash', undefined, ['/managed/bin'])).toEqual(['-i']);
+ });
+
test('single-quotes the shell path in the exec tail (space/quote-safe)', () => {
- expect(buildShellArgs('linux', "/odd path/o'sh", "claude 'x'")).toEqual([
+ expect(buildShellArgs('linux', "/odd path/o'sh", "claude 'x'", [])).toEqual([
'-i',
'-c',
"claude 'x'; exec '/odd path/o'\\''sh' -i",
]);
- expect(buildShellArgs('darwin', "/odd path/o'sh", "claude 'x'")).toEqual([
+ expect(buildShellArgs('darwin', "/odd path/o'sh", "claude 'x'", [])).toEqual([
'-l',
'-i',
'-c',
@@ -1065,7 +1172,7 @@ describe('buildShellArgs', () => {
describe('buildShellEnv', () => {
test('strips markers, drops undefined, preserves the rest, marks the desktop terminal', () => {
- const env = buildShellEnv({
+ const { env } = buildShellEnv({
PATH: '/usr/bin',
HOME: '/Users/x',
OK_ELECTRON_PROTOCOL_HOST: '1',
@@ -1087,7 +1194,7 @@ describe('buildShellEnv', () => {
});
test('win32 prepends the packaged CLI bin using the inherited PATH key casing', () => {
- const env = buildShellEnv(
+ const { env } = buildShellEnv(
{
Path: 'C:\\Windows\\System32;C:\\Tools',
HOME: 'C:\\Users\\alice',
@@ -1394,17 +1501,26 @@ describe('resolveShell', () => {
});
test('buildShellArgs uses empty argv for every win32 shell rung', () => {
- expect(buildShellArgs('win32', 'C:\\Program Files\\PowerShell\\7\\pwsh.exe')).toEqual([]);
- expect(buildShellArgs('win32', 'C:\\Windows\\System32\\cmd.exe')).toEqual([]);
- expect(buildShellArgs('win32', 'C:\\Program Files\\Git\\bin\\bash.exe')).toEqual([]);
+ expect(
+ buildShellArgs('win32', 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', undefined, []),
+ ).toEqual([]);
+ expect(buildShellArgs('win32', 'C:\\Windows\\System32\\cmd.exe', undefined, [])).toEqual([]);
+ expect(buildShellArgs('win32', 'C:\\Program Files\\Git\\bin\\bash.exe', undefined, [])).toEqual(
+ [],
+ );
});
describe('buildShellArgs Windows launch composition', () => {
test('PowerShell uses -NoExit + EncodedCommand and preserves structured JSON', () => {
- const args = buildShellArgs('win32', 'C:\\Program Files\\PowerShell\\7\\pwsh.exe', {
- executable: 'native.exe',
- args: ['--settings', '{"nested":"a\'b"}'],
- });
+ const args = buildShellArgs(
+ 'win32',
+ 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
+ {
+ executable: 'native.exe',
+ args: ['--settings', '{"nested":"a\'b"}'],
+ },
+ [],
+ );
expect(Array.isArray(args)).toBe(true);
if (!Array.isArray(args)) throw new Error('expected PowerShell argv');
expect(args.slice(0, 2)).toEqual(['-NoExit', '-EncodedCommand']);
@@ -1415,10 +1531,15 @@ describe('buildShellArgs Windows launch composition', () => {
test('cmd uses node-pty string mode so CRT quote remarshal is bypassed', () => {
expect(
- buildShellArgs('win32', 'C:\\Windows\\System32\\cmd.exe', {
- executable: 'claude',
- args: [],
- }),
+ buildShellArgs(
+ 'win32',
+ 'C:\\Windows\\System32\\cmd.exe',
+ {
+ executable: 'claude',
+ args: [],
+ },
+ [],
+ ),
).toBe('/K claude');
});
@@ -1430,10 +1551,15 @@ describe('buildShellArgs Windows launch composition', () => {
'mcp_servers.open-knowledge.default_tools_approval_mode=approve',
"apostrophe'and space",
];
- const args = buildShellArgs('win32', shell, {
- executable: launchTokens[0] ?? '',
- args: launchTokens.slice(1),
- });
+ const args = buildShellArgs(
+ 'win32',
+ shell,
+ {
+ executable: launchTokens[0] ?? '',
+ args: launchTokens.slice(1),
+ },
+ [],
+ );
expect(Array.isArray(args)).toBe(true);
if (!Array.isArray(args)) throw new Error('expected Git Bash argv');