Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(desktop): consent gate for the shell-PATH install (rc-file edits) (#2405)

mike-inkeep55e537f0621a
diff --git a/.changeset/shell-path-install-consent.md b/.changeset/shell-path-install-consent.md
new file mode 100644
index 000000000..ac28f3e6d
--- /dev/null
+++ b/.changeset/shell-path-install-consent.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The macOS app now asks before editing your shell startup files. Putting `ok` on your `PATH` used to happen silently on first launch — a managed block appended to `~/.zshrc` / `~/.bash_profile` / fish's `conf.d`. That write is now a pre-checked "Add the `ok` command to your terminal" toggle in the first-launch dialog, and nothing touches your shell config if you uncheck it. Declining only affects `ok` typed in an external terminal: the app's built-in terminal now has `ok` available regardless, and MCP wiring and "Open with AI" launches never depended on it. Decisions are recorded in `path-install.json`; machines that already have the managed block are treated as consented (no re-prompt, block left in place), deleting the block still opts out permanently, and a declined install can be re-run any time from **File → Set up OpenKnowledge integrations…** (the renamed "Configure AI tool integrations…" item).
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 6209993bf..d61eb3ae0 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -28,12 +28,12 @@ OpenKnowledge installs one of two ways, and the footprint differs a little betwe
### Installing and launching the app
-The macOS app ships as a signed `.dmg` you drag into `/Applications`. On launch it writes app-level state and logs, and — because a `.dmg` app can't put a CLI on your `PATH` on its own — first launch also sets up a `PATH` shim and, with your consent, registers the MCP server (both covered below).
+The macOS app ships as a signed `.dmg` you drag into `/Applications`. On launch it writes app-level state and logs, and — 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).
| Path | What it is | Scope |
| --- | --- | --- |
| `~/Library/Application Support/OpenKnowledge/state.json` | Recent projects, window/view state, update channel | Outside-project (home dir) |
-| `~/Library/Application Support/OpenKnowledge/path-install.json` | Records the `PATH`/shell changes it made, so they can be reverted | Outside-project (home dir) |
+| `~/Library/Application Support/OpenKnowledge/path-install.json` | Records the `PATH`/shell changes it made and your `PATH`-consent choice, so they can be reverted | Outside-project (home dir) |
| `~/.ok/logs/desktop.<date>.log` | Desktop app + renderer log | Outside-project (home dir) |
| `~/.ok/mcp-status.json` | Records your first-launch MCP-setup consent choice | Outside-project (home dir) |
| `~/Library/Caches/OpenKnowledge-updater/` | Staged auto-update downloads (electron-updater) | Outside-project (home dir) |
@@ -42,13 +42,17 @@ The app registers the `openknowledge://` URL scheme (for deep links) and checks
### Shell and `PATH`
-So `ok` works 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.
+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.
+
+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.
| Path | What it is | Scope |
| --- | --- | --- |
| `~/.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` | Outside-project (shell config) |
+| `~/.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) |
+
+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.
The managed block is clearly fenced so you can see and remove it:
@@ -215,6 +219,7 @@ Disable all three with `OK_RECLAIM_DISABLE=1`.
| 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 |
| 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 | `ok init --local-only` (or choose "local only" when prompted) |
diff --git a/packages/app/src/components/McpConsentDialog.dom.test.tsx b/packages/app/src/components/McpConsentDialog.dom.test.tsx
index 9354aec91..555ccce4d 100644
--- a/packages/app/src/components/McpConsentDialog.dom.test.tsx
+++ b/packages/app/src/components/McpConsentDialog.dom.test.tsx
@@ -18,6 +18,16 @@ const payload: OkMcpWiringShowPayload = {
{ id: 'cursor', label: 'Cursor', detected: true, willReplace: false },
{ id: 'codex', label: 'Codex', detected: false, willReplace: false },
],
+ pathInstall: {
+ shellDetected: true,
+ rcFilesToTouch: ['~/.zshrc', '~/.config/fish/conf.d/open-knowledge.fish'],
+ alreadyInstalled: false,
+ },
+};
+
+const noneDetectedPayload: OkMcpWiringShowPayload = {
+ detectedEditors: [{ id: 'codex', label: 'Codex', detected: false, willReplace: false }],
+ pathInstall: payload.pathInstall,
};
function deferredResult() {
@@ -28,23 +38,30 @@ function deferredResult() {
return { promise, resolve };
}
+interface RecordedConfirm {
+ editorIds: readonly string[];
+ pathInstall: boolean | undefined;
+}
+
function makeHarness({
confirmResult = async () => ({ ok: true as const }),
skipResult = async () => ({ ok: true as const }),
+ snapshot = payload,
}: {
confirmResult?: (editorIds: readonly string[]) => Promise<OkMcpWiringResult>;
skipResult?: () => Promise<OkMcpWiringResult>;
+ snapshot?: OkMcpWiringShowPayload;
} = {}) {
- const confirmCalls: readonly string[][] = [];
+ const confirmCalls: RecordedConfirm[] = [];
const skipCalls: string[] = [];
const toastErrors: string[] = [];
const store: McpConsentStore = {
- confirm: async (editorIds) => {
- (confirmCalls as string[][]).push([...editorIds]);
- return confirmResult(editorIds);
+ confirm: async (request) => {
+ confirmCalls.push({ editorIds: [...request.editorIds], pathInstall: request.pathInstall });
+ return confirmResult(request.editorIds);
},
dismiss: () => {},
- getSnapshot: () => payload,
+ getSnapshot: () => snapshot,
install: () => undefined,
skip: async () => {
skipCalls.push('skip');
@@ -55,12 +72,14 @@ function makeHarness({
const toast: ToastImpl = {
error: (message) => toastErrors.push(message),
};
- return { confirmCalls, skipCalls, store, toast, toastErrors };
+ return { confirmCalls, skipCalls, store, toast, toastErrors, snapshot };
}
async function renderDialog(harness = makeHarness()) {
const { McpConsentDialogBody } = await import('./McpConsentDialogBody');
- render(<McpConsentDialogBody payload={payload} store={harness.store} toast={harness.toast} />);
+ render(
+ <McpConsentDialogBody payload={harness.snapshot} store={harness.store} toast={harness.toast} />,
+ );
return harness;
}
@@ -113,15 +132,15 @@ describe('McpConsentDialog runtime behavior', () => {
expect(skip.disabled).toBe(false);
expect(add.textContent).toBe('Add');
- expect(harness.confirmCalls).toEqual([['claude', 'cursor']]);
+ expect(harness.confirmCalls).toEqual([{ editorIds: ['claude', 'cursor'], pathInstall: true }]);
expect(harness.toastErrors).toEqual(['Could not write Claude config']);
await userEvent.click(add);
second.resolve({ ok: false, error: 'Still unwritable' });
await waitFor(() => {
expect(harness.confirmCalls).toEqual([
- ['claude', 'cursor'],
- ['claude', 'cursor'],
+ { editorIds: ['claude', 'cursor'], pathInstall: true },
+ { editorIds: ['claude', 'cursor'], pathInstall: true },
]);
});
});
@@ -158,3 +177,112 @@ describe('McpConsentDialog runtime behavior', () => {
});
});
});
+
+describe('McpConsentDialog PATH consent row', () => {
+ afterEach(() => cleanup());
+
+ test('PATH section is pinned outside the scrollable editor list', async () => {
+ await renderDialog();
+
+ const pathCheckbox = screen.getByTestId('mcp-consent-path-checkbox');
+ expect(pathCheckbox.closest('[class*="overflow-y-auto"]')).toBeNull();
+ const editorCheckbox = screen.getByTestId('mcp-consent-checkbox-claude');
+ expect(editorCheckbox.closest('[class*="overflow-y-auto"]')).not.toBeNull();
+ });
+
+ test('renders pre-checked with the rc-file disclosure; warning appears only when unchecked', async () => {
+ await renderDialog();
+
+ const checkbox = screen.getByTestId('mcp-consent-path-checkbox');
+ expect(checkbox.getAttribute('aria-checked')).toBe('true');
+ expect(checkbox.hasAttribute('disabled')).toBe(false);
+ expect(screen.getByTestId('mcp-consent-path-status').textContent).toBe(
+ 'Adds a managed block to ~/.zshrc, ~/.config/fish/conf.d/open-knowledge.fish',
+ );
+ expect(screen.queryByTestId('mcp-consent-path-warning')).toBeNull();
+
+ await userEvent.click(checkbox);
+ expect(checkbox.getAttribute('aria-checked')).toBe('false');
+ expect(screen.getByTestId('mcp-consent-path-warning').textContent).toContain(
+ 'external terminals',
+ );
+ });
+
+ test('unchecking the toggle sends pathInstall:false on Add', async () => {
+ const harness = await renderDialog();
+
+ await userEvent.click(screen.getByTestId('mcp-consent-path-checkbox'));
+ await userEvent.click(screen.getByTestId('mcp-consent-add'));
+
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([
+ { editorIds: ['claude', 'cursor'], pathInstall: false },
+ ]);
+ });
+ });
+
+ test('FR8: zero editors selected + PATH checked keeps Add enabled and confirms PATH-only', async () => {
+ const harness = await renderDialog(makeHarness({ snapshot: noneDetectedPayload }));
+
+ const add = screen.getByTestId('mcp-consent-add') as HTMLButtonElement;
+ expect(add.disabled).toBe(false);
+
+ await userEvent.click(add);
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([{ editorIds: [], pathInstall: true }]);
+ });
+ });
+
+ test('FR8: zero editors + PATH unchecked disables Add', async () => {
+ await renderDialog(makeHarness({ snapshot: noneDetectedPayload }));
+
+ await userEvent.click(screen.getByTestId('mcp-consent-path-checkbox'));
+ const add = screen.getByTestId('mcp-consent-add') as HTMLButtonElement;
+ expect(add.disabled).toBe(true);
+ });
+
+ test('alreadyInstalled renders an informational row and solicits no decision', async () => {
+ const harness = await renderDialog(
+ makeHarness({
+ snapshot: {
+ ...payload,
+ pathInstall: { ...payload.pathInstall, alreadyInstalled: true },
+ },
+ }),
+ );
+
+ const checkbox = screen.getByTestId('mcp-consent-path-checkbox');
+ expect(checkbox.getAttribute('aria-checked')).toBe('true');
+ expect(checkbox.hasAttribute('disabled')).toBe(true);
+ expect(screen.getByTestId('mcp-consent-path-status').textContent).toBe(
+ 'Already set up — ok is available in your terminal',
+ );
+
+ await userEvent.click(screen.getByTestId('mcp-consent-add'));
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([
+ { editorIds: ['claude', 'cursor'], pathInstall: undefined },
+ ]);
+ });
+ });
+
+ test('shellDetected:false hides the row entirely and sends no PATH decision', async () => {
+ const harness = await renderDialog(
+ makeHarness({
+ snapshot: {
+ ...payload,
+ pathInstall: { shellDetected: false, rcFilesToTouch: [], alreadyInstalled: false },
+ },
+ }),
+ );
+
+ expect(screen.queryByTestId('mcp-consent-path-checkbox')).toBeNull();
+
+ await userEvent.click(screen.getByTestId('mcp-consent-add'));
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([
+ { editorIds: ['claude', 'cursor'], pathInstall: undefined },
+ ]);
+ });
+ });
+});
diff --git a/packages/app/src/components/McpConsentDialog.test.ts b/packages/app/src/components/McpConsentDialog.test.ts
index 28a7d6b90..8f5496ab0 100644
--- a/packages/app/src/components/McpConsentDialog.test.ts
+++ b/packages/app/src/components/McpConsentDialog.test.ts
@@ -3,6 +3,7 @@ import type { OkMcpWiringEditorId, OkMcpWiringShowPayload } from '@/lib/desktop-
import { McpConsentDialog } from './McpConsentDialog';
import {
computeInitialSelection,
+ isPathRowActionable,
selectedIdsOrdered,
type ToastImpl,
toggleSelectedId,
@@ -101,6 +102,34 @@ describe('selectedIdsOrdered', () => {
});
});
+describe('isPathRowActionable', () => {
+ test('actionable only when an rc file is touchable AND nothing is installed yet', () => {
+ expect(
+ isPathRowActionable({
+ shellDetected: true,
+ rcFilesToTouch: ['~/.zshrc'],
+ alreadyInstalled: false,
+ }),
+ ).toBe(true);
+ });
+
+ test('hidden row (no touchable rc files) solicits no decision', () => {
+ expect(
+ isPathRowActionable({ shellDetected: false, rcFilesToTouch: [], alreadyInstalled: false }),
+ ).toBe(false);
+ });
+
+ test('informational row (already installed / consent granted) solicits no decision', () => {
+ expect(
+ isPathRowActionable({
+ shellDetected: true,
+ rcFilesToTouch: ['~/.zshrc'],
+ alreadyInstalled: true,
+ }),
+ ).toBe(false);
+ });
+});
+
describe('McpConsentDialog module shape', () => {
test('exports the component + the three pure helpers + ToastImpl type', () => {
expect(typeof McpConsentDialog).toBe('function');
diff --git a/packages/app/src/components/McpConsentDialogBody.tsx b/packages/app/src/components/McpConsentDialogBody.tsx
index 78115f787..c37c11a00 100644
--- a/packages/app/src/components/McpConsentDialogBody.tsx
+++ b/packages/app/src/components/McpConsentDialogBody.tsx
@@ -17,6 +17,11 @@ import type { OkMcpWiringEditorId, OkMcpWiringShowPayload } from '@/lib/desktop-
import { type McpConsentStore, mcpConsentStore } from '@/lib/mcp-consent-store';
type EditorDetection = OkMcpWiringShowPayload['detectedEditors'][number];
+type PathInstallDescriptor = OkMcpWiringShowPayload['pathInstall'];
+
+export function isPathRowActionable(pathInstall: PathInstallDescriptor): boolean {
+ return pathInstall.shellDetected && !pathInstall.alreadyInstalled;
+}
export function computeInitialSelection(
detectedEditors: readonly EditorDetection[],
@@ -81,9 +86,12 @@ interface McpConsentDialogFormProps {
function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormProps) {
const { t } = useLingui();
const detectedEditors = payload.detectedEditors;
+ const pathInstall = payload.pathInstall;
+ const pathActionable = isPathRowActionable(pathInstall);
const [selection, setSelection] = useState<ReadonlySet<OkMcpWiringEditorId>>(() =>
computeInitialSelection(detectedEditors),
);
+ const [pathChecked, setPathChecked] = useState(true);
const [busy, setBusy] = useState(false);
const idPrefix = useId();
@@ -93,7 +101,10 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
async function onAdd() {
setBusy(true);
- const result = await store.confirm(selectedIdsOrdered(selection, detectedEditors));
+ const result = await store.confirm({
+ editorIds: selectedIdsOrdered(selection, detectedEditors),
+ pathInstall: pathActionable ? pathChecked : undefined,
+ });
if (!result.ok) {
toast.error(result.error);
setBusy(false);
@@ -140,7 +151,81 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
</DialogDescription>
</DialogHeader>
+ {/*
+ * Shell-PATH consent section — its own pinned block ABOVE the
+ * scrollable editor list (DialogBody is the overflow container; a
+ * row inside it sits below the fold on machines with many editors).
+ * Distinct from the per-editor MCP checkboxes because the two
+ * decisions are independent (MCP runs over npx / the bundle
+ * wrapper, never bare `ok`). Hidden when no rc file is touchable;
+ * informational when a managed block is already on disk or consent
+ * was already granted.
+ */}
+ {pathInstall.shellDetected && (
+ <div className="flex flex-col gap-1.5">
+ <span className="text-xs font-medium text-muted-foreground">
+ <Trans comment="Section label above the shell-PATH toggle in the first-launch dialog">
+ Terminal
+ </Trans>
+ </span>
+ <div className="overflow-hidden rounded-md border border-border bg-card/50">
+ <Label
+ htmlFor={`${idPrefix}-path`}
+ className={
+ pathActionable
+ ? 'flex cursor-pointer items-start gap-2.5 px-3 py-2.5 font-normal hover:bg-accent'
+ : 'flex items-start gap-2.5 px-3 py-2.5 font-normal'
+ }
+ >
+ <Checkbox
+ id={`${idPrefix}-path`}
+ checked={pathActionable ? pathChecked : true}
+ disabled={busy || !pathActionable}
+ onCheckedChange={() => setPathChecked((prev) => !prev)}
+ className="mt-0.5"
+ data-testid="mcp-consent-path-checkbox"
+ />
+ <span className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="text-sm font-medium text-foreground">
+ <Trans comment="Toggle in the first-launch dialog that adds the ok CLI to the user's shell PATH">
+ Add the <code>ok</code> command to your terminal
+ </Trans>
+ </span>
+ <span
+ className="text-xs text-muted-foreground"
+ data-testid="mcp-consent-path-status"
+ >
+ {pathActionable
+ ? t`Adds a managed block to ${pathInstall.rcFilesToTouch.join(', ')}`
+ : t`Already set up — ok is available in your terminal`}
+ </span>
+ {pathActionable && !pathChecked && (
+ <span
+ className="text-xs text-amber-600 dark:text-amber-400"
+ data-testid="mcp-consent-path-warning"
+ >
+ <Trans comment="Warning shown when the user unchecks the PATH toggle — only external terminals degrade">
+ <code>ok</code> won't run in external terminals until you add it later from
+ the File menu. OpenKnowledge's built-in terminal and AI tools keep working.
+ </Trans>
+ </span>
+ )}
+ </span>
+ </Label>
+ </div>
+ </div>
+ )}
+
<DialogBody>
+ {/* Group label only when the Terminal section renders above —
+ with a single group there is nothing to distinguish. */}
+ {pathInstall.shellDetected && (
+ <div className="mb-1.5 text-xs font-medium text-muted-foreground">
+ <Trans comment="Section label above the editor checkbox list in the first-launch dialog">
+ AI tools
+ </Trans>
+ </div>
+ )}
<ul className="rounded-md border border-border bg-card/50 divide-y divide-border overflow-hidden">
{detectedEditors.map((editor) => {
const checked = selection.has(editor.id);
@@ -194,7 +279,7 @@ function McpConsentDialogForm({ payload, store, toast }: McpConsentDialogFormPro
</Button>
<Button
onClick={() => void onAdd()}
- disabled={busy || selection.size === 0}
+ disabled={busy || (selection.size === 0 && !(pathActionable && pathChecked))}
data-testid="mcp-consent-add"
>
{busy ? (
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index ab82a7495..2898b49af 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -276,7 +276,10 @@ export type OkMcpWiringEditorId = EditorId;
/** Payload passed to `mcpWiring.onShow` subscribers. `willReplace: true`
* signals the editor has an existing OK-managed MCP entry (canonical npx,
* `-y` variant, or prior cliPath shape) that Add would overwrite (Pass 1
- * Major #8). */
+ * Major #8). `pathInstall` drives the dialog's shell-PATH toggle row:
+ * `shellDetected: false` hides the row; `alreadyInstalled: true` renders
+ * it informational (block already on disk or consent already granted);
+ * `rcFilesToTouch` names the tildified shell files a grant would edit. */
export interface OkMcpWiringShowPayload {
readonly detectedEditors: readonly {
readonly id: OkMcpWiringEditorId;
@@ -284,6 +287,20 @@ export interface OkMcpWiringShowPayload {
readonly detected: boolean;
readonly willReplace: boolean;
}[];
+ readonly pathInstall: {
+ readonly shellDetected: boolean;
+ readonly rcFilesToTouch: readonly string[];
+ readonly alreadyInstalled: boolean;
+ };
+}
+
+/** Confirm payload for `mcpWiring.confirm`. `pathInstall` is the PATH
+ * toggle, tri-state: `true` → append the managed rc block; `false` →
+ * record declined, touch nothing; absent → no PATH decision was solicited
+ * (row hidden or informational). */
+export interface OkMcpWiringConfirmRequest {
+ readonly editorIds: readonly OkMcpWiringEditorId[];
+ readonly pathInstall?: boolean;
}
export type OkMcpWiringResult = { ok: true } | { ok: false; error: string };
@@ -674,7 +691,7 @@ export interface OkDesktopBridge {
mcpWiring: {
onShow(cb: (payload: OkMcpWiringShowPayload) => void): OkUnsubscribe;
signalReady(): void;
- confirm(editorIds: readonly OkMcpWiringEditorId[]): Promise<OkMcpWiringResult>;
+ confirm(request: OkMcpWiringConfirmRequest): Promise<OkMcpWiringResult>;
skip(): Promise<OkMcpWiringResult>;
};
onboarding: {
diff --git a/packages/app/src/lib/mcp-consent-store.test.ts b/packages/app/src/lib/mcp-consent-store.test.ts
index 521020ab3..7c694c5fa 100644
--- a/packages/app/src/lib/mcp-consent-store.test.ts
+++ b/packages/app/src/lib/mcp-consent-store.test.ts
@@ -64,6 +64,7 @@ const sampleShowPayload: OkMcpWiringShowPayload = {
{ id: 'claude', label: 'Claude', detected: true, willReplace: false },
{ id: 'cursor', label: 'Cursor', detected: false, willReplace: false },
],
+ pathInstall: { shellDetected: true, rcFilesToTouch: ['~/.zshrc'], alreadyInstalled: false },
};
describe('createMcpConsentStore — install', () => {
@@ -132,21 +133,21 @@ describe('createMcpConsentStore — onShow propagation', () => {
describe('createMcpConsentStore — confirm', () => {
test('no-op + error result when bridge is not attached', async () => {
const store = createMcpConsentStore();
- const result = await store.confirm([]);
+ const result = await store.confirm({ editorIds: [] });
expect(result).toEqual({ ok: false, error: 'Not attached to desktop bridge' });
});
- test('invokes bridge.confirm with the editorIds payload', async () => {
+ test('passes the confirm request (editors + PATH toggle) through to the bridge', async () => {
const store = createMcpConsentStore();
const bridge = makeBridge();
store.install({ bridge });
bridge.fireShow(sampleShowPayload);
const editorIds: OkMcpWiringEditorId[] = ['claude', 'cursor'];
- const result = await store.confirm(editorIds);
+ const result = await store.confirm({ editorIds, pathInstall: false });
expect(result).toEqual({ ok: true });
- expect(bridge.mcpWiring.confirm.mock.calls[0]).toEqual([editorIds]);
+ expect(bridge.mcpWiring.confirm.mock.calls[0]).toEqual([{ editorIds, pathInstall: false }]);
});
test('clears snapshot on success', async () => {
@@ -156,7 +157,7 @@ describe('createMcpConsentStore — confirm', () => {
bridge.fireShow(sampleShowPayload);
expect(store.getSnapshot()).not.toBeNull();
- await store.confirm(['claude']);
+ await store.confirm({ editorIds: ['claude'], pathInstall: true });
expect(store.getSnapshot()).toBeNull();
});
@@ -166,7 +167,7 @@ describe('createMcpConsentStore — confirm', () => {
store.install({ bridge });
bridge.fireShow(sampleShowPayload);
- const result = await store.confirm(['claude']);
+ const result = await store.confirm({ editorIds: ['claude'] });
expect(result).toEqual({ ok: false, error: 'confirm-boom' });
expect(store.getSnapshot()).toEqual(sampleShowPayload);
});
@@ -177,7 +178,7 @@ describe('createMcpConsentStore — confirm', () => {
store.install({ bridge });
bridge.fireShow(sampleShowPayload);
- const result = await store.confirm([]);
+ const result = await store.confirm({ editorIds: [] });
expect(result).toEqual({ ok: false, error: 'no editors selected' });
expect(store.getSnapshot()).toEqual(sampleShowPayload);
});
diff --git a/packages/app/src/lib/mcp-consent-store.ts b/packages/app/src/lib/mcp-consent-store.ts
index e763e0421..b21840e29 100644
--- a/packages/app/src/lib/mcp-consent-store.ts
+++ b/packages/app/src/lib/mcp-consent-store.ts
@@ -1,6 +1,6 @@
import type {
OkDesktopBridge,
- OkMcpWiringEditorId,
+ OkMcpWiringConfirmRequest,
OkMcpWiringResult,
OkMcpWiringShowPayload,
} from '@/lib/desktop-bridge-types';
@@ -9,7 +9,7 @@ export interface McpConsentStore {
install(opts: { bridge: OkDesktopBridge | undefined }): (() => void) | undefined;
getSnapshot(): OkMcpWiringShowPayload | null;
subscribe(listener: () => void): () => void;
- confirm(editorIds: readonly OkMcpWiringEditorId[]): Promise<OkMcpWiringResult>;
+ confirm(request: OkMcpWiringConfirmRequest): Promise<OkMcpWiringResult>;
skip(): Promise<OkMcpWiringResult>;
dismiss(): void;
}
@@ -62,11 +62,11 @@ export function createMcpConsentStore(): McpConsentStore {
};
},
- async confirm(editorIds): Promise<OkMcpWiringResult> {
+ async confirm(request): Promise<OkMcpWiringResult> {
const b = bridge;
if (!b) return { ok: false, error: 'Not attached to desktop bridge' };
try {
- const result = await b.mcpWiring.confirm(editorIds);
+ const result = await b.mcpWiring.confirm(request);
if (result.ok) clearCurrent();
return result;
} catch (err) {
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index 96f936943..95b75ffc1 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -33,6 +33,7 @@
"0-31GV": ["Removing"],
"02P3hL": ["Upload failed: ", ["message"]],
"04RA0-": ["Failed to enable sync — ", ["detail"]],
+ "04XyCH": ["Adds a managed block to ", ["0"]],
"05n5wS": ["Doc mention suggestions"],
"06SZfb": ["Template \"", ["trimmedTitle"], "\" created"],
"07eGJB": ["Couldn't move skill: ", ["0"]],
@@ -321,6 +322,9 @@
"7Ongq0": ["Condense my AGENTS.md file to less than 40k characters"],
"7OwvEL": ["Show HTML preview"],
"7PNNNs": ["This sends content off your machine"],
+ "7PXYaF": [
+ "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
+ ],
"7PzzBU": ["User"],
"7YRrJ9": [
"Available in the OpenKnowledge desktop app. From a terminal, use<0> ok config-sharing status</0> / <1>share</1> / <2>unshare</2>."
@@ -640,6 +644,7 @@
"FnMkli": ["Sync disabled — you don't have permission to push"],
"FqTpiN": ["Bird wiki"],
"Fqr8BP": ["Multi-page PDF viewer with toolbar controls (thumbnails, page nav, zoom)."],
+ "Fsx78O": ["Add the <0>ok</0> command to your terminal"],
"FvMSms": ["Renaming changes the file on disk and the id agents use to pick this template."],
"FvpFSZ": ["Reveal in Finder, ", ["hint"]],
"Fxf4jq": ["Description (optional)"],
@@ -1058,6 +1063,7 @@
"RlCInP": ["Slash commands"],
"RlLl3G": ["Actions for ", ["0"]],
"RmBY0A": ["No git remote"],
+ "RnrnTe": ["Already set up — ok is available in your terminal"],
"RobAKV": ["Update the destination and optional section anchor."],
"Rq1vFD": ["Tree view options"],
"RrAIZx": ["What config sharing covers"],
@@ -1439,6 +1445,7 @@
"cn1sLi": ["Couldn't connect OpenKnowledge tools to Claude Code. Please try again."],
"cnGeoo": ["Delete"],
"cqQyPB": ["Folder name"],
+ "crqzW5": ["AI tools"],
"cs4mps": ["Config sharing"],
"csDS2L": ["Available"],
"ct2kv5": ["No headings in ", ["pageTarget"]],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index 1c3a9a4d2..73ae38f35 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -448,6 +448,11 @@ msgstr "<0>Mirror anchor not found.</0> No <1>{mirrorSourceTag}</1> exists in <2
msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."
msgstr "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."
+#. Warning shown when the user unchecks the PATH toggle — only external terminals degrade
+#: src/components/McpConsentDialogBody.tsx
+msgid "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
+msgstr "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
+
#: src/components/PageHeaderWidgets.tsx
msgid "📝 or assets/icon.png"
msgstr "📝 or assets/icon.png"
@@ -641,10 +646,20 @@ msgstr "Add tab"
msgid "Add tag"
msgstr "Add tag"
+#. Toggle in the first-launch dialog that adds the ok CLI to the user's shell PATH
+#: src/components/McpConsentDialogBody.tsx
+msgid "Add the <0>ok</0> command to your terminal"
+msgstr "Add the <0>ok</0> command to your terminal"
+
#: src/lib/keyboard-shortcuts.ts
msgid "Add the next matching source selection."
msgstr "Add the next matching source selection."
+#. placeholder {0}: pathInstall.rcFilesToTouch.join(', ')
+#: src/components/McpConsentDialogBody.tsx
+msgid "Adds a managed block to {0}"
+msgstr "Adds a managed block to {0}"
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
msgstr "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
@@ -670,6 +685,11 @@ msgstr "Agent activity"
msgid "Agent configuration file"
msgstr "Agent configuration file"
+#. Section label above the editor checkbox list in the first-launch dialog
+#: src/components/McpConsentDialogBody.tsx
+msgid "AI tools"
+msgstr "AI tools"
+
#: src/components/FolderOverview.tsx
msgid "All files"
msgstr "All files"
@@ -694,6 +714,10 @@ msgstr "Already have a git repository? Add it with <0>git remote add origin <url
msgid "Already open"
msgstr "Already open"
+#: src/components/McpConsentDialogBody.tsx
+msgid "Already set up — ok is available in your terminal"
+msgstr "Already set up — ok is available in your terminal"
+
#: src/components/DocumentErrorBoundary.tsx
msgid "An unexpected error occurred."
msgstr "An unexpected error occurred."
@@ -6416,11 +6440,13 @@ msgstr "Templates"
msgid "Templates available"
msgstr "Templates available"
+#. Section label above the shell-PATH toggle in the first-launch dialog
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/TerminalSection.tsx
#: src/components/TerminalNewChatButton.tsx
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 975b7a6bd..e858ceee0 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -33,6 +33,7 @@
"0-31GV": ["Ŕēḿōvĩńĝ"],
"02P3hL": ["Ũƥĺōàď ƒàĩĺēď: ", ["message"]],
"04RA0-": ["Ƒàĩĺēď ţō ēńàƀĺē śŷńć — ", ["detail"]],
+ "04XyCH": ["Àďďś à ḿàńàĝēď ƀĺōćķ ţō ", ["0"]],
"05n5wS": ["Ďōć ḿēńţĩōń śũĝĝēśţĩōńś"],
"06SZfb": ["Ţēḿƥĺàţē \"", ["trimmedTitle"], "\" ćŕēàţēď"],
"07eGJB": ["Ćōũĺďń'ţ ḿōvē śķĩĺĺ: ", ["0"]],
@@ -321,6 +322,9 @@
"7Ongq0": ["Ćōńďēńśē ḿŷ ÀĜĒŃŢŚ.ḿď ƒĩĺē ţō ĺēśś ţĥàń 40ķ ćĥàŕàćţēŕś"],
"7OwvEL": ["Śĥōŵ ĤŢḾĹ ƥŕēvĩēŵ"],
"7PNNNs": ["Ţĥĩś śēńďś ćōńţēńţ ōƒƒ ŷōũŕ ḿàćĥĩńē"],
+ "7PXYaF": [
+ "<0>ōķ</0> ŵōń'ţ ŕũń ĩń ēxţēŕńàĺ ţēŕḿĩńàĺś ũńţĩĺ ŷōũ àďď ĩţ ĺàţēŕ ƒŕōḿ ţĥē Ƒĩĺē ḿēńũ. ŌƥēńĶńōŵĺēďĝē'ś ƀũĩĺţ-ĩń ţēŕḿĩńàĺ àńď ÀĨ ţōōĺś ķēēƥ ŵōŕķĩńĝ."
+ ],
"7PzzBU": ["Ũśēŕ"],
"7YRrJ9": [
"Àvàĩĺàƀĺē ĩń ţĥē ŌƥēńĶńōŵĺēďĝē ďēśķţōƥ àƥƥ. Ƒŕōḿ à ţēŕḿĩńàĺ, ũśē<0> ōķ ćōńƒĩĝ-śĥàŕĩńĝ śţàţũś</0> / <1>śĥàŕē</1> / <2>ũńśĥàŕē</2>."
@@ -640,6 +644,7 @@
"FnMkli": ["Śŷńć ďĩśàƀĺēď — ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ"],
"FqTpiN": ["ßĩŕď ŵĩķĩ"],
"Fqr8BP": ["Ḿũĺţĩ-ƥàĝē ƤĎƑ vĩēŵēŕ ŵĩţĥ ţōōĺƀàŕ ćōńţŕōĺś (ţĥũḿƀńàĩĺś, ƥàĝē ńàv, źōōḿ)."],
+ "Fsx78O": ["Àďď ţĥē <0>ōķ</0> ćōḿḿàńď ţō ŷōũŕ ţēŕḿĩńàĺ"],
"FvMSms": ["Ŕēńàḿĩńĝ ćĥàńĝēś ţĥē ƒĩĺē ōń ďĩśķ àńď ţĥē ĩď àĝēńţś ũśē ţō ƥĩćķ ţĥĩś ţēḿƥĺàţē."],
"FvpFSZ": ["Ŕēvēàĺ ĩń Ƒĩńďēŕ, ", ["hint"]],
"Fxf4jq": ["Ďēśćŕĩƥţĩōń (ōƥţĩōńàĺ)"],
@@ -1058,6 +1063,7 @@
"RlCInP": ["Śĺàśĥ ćōḿḿàńďś"],
"RlLl3G": ["Àćţĩōńś ƒōŕ ", ["0"]],
"RmBY0A": ["Ńō ĝĩţ ŕēḿōţē"],
+ "RnrnTe": ["Àĺŕēàďŷ śēţ ũƥ — ōķ ĩś àvàĩĺàƀĺē ĩń ŷōũŕ ţēŕḿĩńàĺ"],
"RobAKV": ["Ũƥďàţē ţĥē ďēśţĩńàţĩōń àńď ōƥţĩōńàĺ śēćţĩōń àńćĥōŕ."],
"Rq1vFD": ["Ţŕēē vĩēŵ ōƥţĩōńś"],
"RrAIZx": ["Ŵĥàţ ćōńƒĩĝ śĥàŕĩńĝ ćōvēŕś"],
@@ -1439,6 +1445,7 @@
"cn1sLi": ["Ćōũĺďń'ţ ćōńńēćţ ŌƥēńĶńōŵĺēďĝē ţōōĺś ţō Ćĺàũďē Ćōďē. Ƥĺēàśē ţŕŷ àĝàĩń."],
"cnGeoo": ["Ďēĺēţē"],
"cqQyPB": ["Ƒōĺďēŕ ńàḿē"],
+ "crqzW5": ["ÀĨ ţōōĺś"],
"cs4mps": ["Ćōńƒĩĝ śĥàŕĩńĝ"],
"csDS2L": ["Àvàĩĺàƀĺē"],
"ct2kv5": ["Ńō ĥēàďĩńĝś ĩń ", ["pageTarget"]],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index b399dd444..f4f9757df 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -443,6 +443,11 @@ msgstr ""
msgid "<0>Mirror source removed.</0> The doc <1>{src}</1> is no longer available."
msgstr ""
+#. Warning shown when the user unchecks the PATH toggle — only external terminals degrade
+#: src/components/McpConsentDialogBody.tsx
+msgid "<0>ok</0> won't run in external terminals until you add it later from the File menu. OpenKnowledge's built-in terminal and AI tools keep working."
+msgstr ""
+
#: src/components/PageHeaderWidgets.tsx
msgid "📝 or assets/icon.png"
msgstr ""
@@ -636,10 +641,20 @@ msgstr ""
msgid "Add tag"
msgstr ""
+#. Toggle in the first-launch dialog that adds the ok CLI to the user's shell PATH
+#: src/components/McpConsentDialogBody.tsx
+msgid "Add the <0>ok</0> command to your terminal"
+msgstr ""
+
#: src/lib/keyboard-shortcuts.ts
msgid "Add the next matching source selection."
msgstr ""
+#. placeholder {0}: pathInstall.rcFilesToTouch.join(', ')
+#: src/components/McpConsentDialogBody.tsx
+msgid "Adds a managed block to {0}"
+msgstr ""
+
#: src/components/InstallInClaudeDesktopDialog.tsx
msgid "Adds the OpenKnowledge skill to the <0>Claude Desktop App</0> so it's available in Chat and Cowork sessions."
msgstr ""
@@ -665,6 +680,11 @@ msgstr ""
msgid "Agent configuration file"
msgstr ""
+#. Section label above the editor checkbox list in the first-launch dialog
+#: src/components/McpConsentDialogBody.tsx
+msgid "AI tools"
+msgstr ""
+
#: src/components/FolderOverview.tsx
msgid "All files"
msgstr ""
@@ -689,6 +709,10 @@ msgstr ""
msgid "Already open"
msgstr ""
+#: src/components/McpConsentDialogBody.tsx
+msgid "Already set up — ok is available in your terminal"
+msgstr ""
+
#: src/components/DocumentErrorBoundary.tsx
msgid "An unexpected error occurred."
msgstr ""
@@ -6411,11 +6435,13 @@ msgstr ""
msgid "Templates available"
msgstr ""
+#. Section label above the shell-PATH toggle in the first-launch dialog
#: src/components/empty-state/CreatePromptComposer.tsx
#: src/components/handoff/AgentSplitButton.tsx
#: src/components/handoff/OpenInAgentContextSubmenu.tsx
#: src/components/handoff/OpenInAgentEmptySpaceSubmenu.tsx
#: src/components/handoff/OpenInAgentMenu.tsx
+#: src/components/McpConsentDialogBody.tsx
#: src/components/settings/SettingsDialogShell.tsx
#: src/components/settings/TerminalSection.tsx
#: src/components/TerminalNewChatButton.tsx
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 565e6bd1a..c132eca55 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -65,6 +65,7 @@ export {
PATH_SHIM_BLOCK_RE,
PATH_SHIM_END,
type PathDiscovery,
+ type PathInstallConsent,
type PathInstallMarker,
pathInstallMarkerPath,
} from './integrations/path-shim.ts';
diff --git a/packages/cli/src/integrations/path-shim.ts b/packages/cli/src/integrations/path-shim.ts
index b0d3f0ab4..eef808dd1 100644
--- a/packages/cli/src/integrations/path-shim.ts
+++ b/packages/cli/src/integrations/path-shim.ts
@@ -18,6 +18,11 @@ export interface PathDiscovery {
okBinAlreadyOnPath: boolean;
}
+export interface PathInstallConsent {
+ status: 'granted' | 'declined';
+ at: string;
+}
+
export interface PathInstallMarker {
version: 1;
installedAt: string;
@@ -36,6 +41,7 @@ export interface PathInstallMarker {
createdAt: string;
kind: 'created' | 'refreshed-our-own';
}>;
+ consent?: PathInstallConsent;
}
/** Absolute path to the PATH-install manifest (macOS layout — the shim is
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 5a5675ffc..a91c06fa8 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -183,6 +183,16 @@ interface OkMcpWiringShowPayload {
readonly detected: boolean;
readonly willReplace: boolean;
}[];
+ readonly pathInstall: {
+ readonly shellDetected: boolean;
+ readonly rcFilesToTouch: readonly string[];
+ readonly alreadyInstalled: boolean;
+ };
+}
+
+interface OkMcpWiringConfirmRequest {
+ readonly editorIds: readonly OkMcpWiringEditorId[];
+ readonly pathInstall?: boolean;
}
type OkMcpWiringResult = { ok: true } | { ok: false; error: string };
@@ -670,7 +680,10 @@ export interface OkDesktopBridge {
mcpWiring: {
onShow(cb: (payload: OkMcpWiringShowPayload) => void): OkUnsubscribe;
signalReady(): void;
- confirm(editorIds: readonly OkMcpWiringEditorId[]): Promise<OkMcpWiringResult>;
+ /** User clicked Add. `editorIds` is the subset the user checked;
+ * `pathInstall` is the PATH toggle (tri-state — see
+ * `OkMcpWiringConfirmRequest`). */
+ confirm(request: OkMcpWiringConfirmRequest): Promise<OkMcpWiringResult>;
skip(): Promise<OkMcpWiringResult>;
};
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index b63eb947c..41cc11150 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -185,7 +185,12 @@ import {
recordFirstRunShareHandoff,
recordOnboardingFlow,
} from './onboarding-telemetry.ts';
-import { computePathLeg, type EnsureCliOnPathResult, ensureCliOnPath } from './path-install.ts';
+import {
+ computePathInstallDescriptor,
+ computePathLeg,
+ type EnsureCliOnPathResult,
+ ensureCliOnPath,
+} from './path-install.ts';
import { installStdioBrokenPipeGuard } from './process-safety-net.ts';
import {
checkAndRepairProjectMcpOnProjectOpen,
@@ -1342,7 +1347,7 @@ async function runApplicationMenuRefresh(): Promise<void> {
const message = err instanceof Error ? err.message : String(err);
console.error('[main] reconfigureMcpWiring failed', { err: message });
dialog.showErrorBox(
- 'Configure AI Tool Integrations failed',
+ 'Set up OpenKnowledge integrations failed',
`OpenKnowledge couldn't re-arm the MCP consent dialog:\n\n${message}`,
);
}
@@ -1457,6 +1462,24 @@ interface ArmMcpWiringOpts {
immediateDispatchTarget?: McpWiringDispatchTarget;
}
+const pathInstallLogger = {
+ event: (payload: { event: string; [key: string]: unknown }) =>
+ getLogger('path-install').info(payload, payload.event),
+};
+
+function buildEnsureCliOnPathOpts() {
+ return {
+ executablePath: app.getPath('exe'),
+ isPackaged: app.isPackaged,
+ platform: process.platform,
+ forceEnv: process.env.OK_M6B_FORCE ?? null,
+ reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
+ home: osHomedir(),
+ bundleVersion: app.getVersion(),
+ logger: pathInstallLogger,
+ };
+}
+
function createMcpWiringOpts(opts: ArmMcpWiringOpts = {}) {
return {
isPackaged: app.isPackaged,
@@ -1465,6 +1488,24 @@ function createMcpWiringOpts(opts: ArmMcpWiringOpts = {}) {
platform: process.platform,
ipcMain,
cli: createMcpWiringCliSurface(),
+ pathInstall: {
+ computeDescriptor: () =>
+ computePathInstallDescriptor({
+ home: osHomedir(),
+ env: process.env,
+ logger: pathInstallLogger,
+ }),
+ applyConsent: async (status: 'granted' | 'declined') => {
+ const result = await ensureCliOnPath({
+ ...buildEnsureCliOnPathOpts(),
+ consentDecision: { status, at: new Date().toISOString() },
+ });
+ if (result.status === 'failed-all') {
+ return { ok: false as const, error: result.error };
+ }
+ return { ok: true as const };
+ },
+ },
forceEnv: process.env.OK_M6B_FORCE ?? null,
reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
forceShow: opts.forceShow ?? false,
@@ -2861,18 +2902,7 @@ function bootPrimaryInstance(): void {
mcpWiringHandle = armMcpWiring();
void Promise.allSettled([
checkAndRepairMcpWiringOnStartup(createMcpWiringOpts()),
- ensureCliOnPath({
- executablePath: app.getPath('exe'),
- isPackaged: app.isPackaged,
- platform: process.platform,
- forceEnv: process.env.OK_M6B_FORCE ?? null,
- reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
- home: osHomedir(),
- bundleVersion: app.getVersion(),
- logger: {
- event: (payload) => getLogger('path-install').info(payload, payload.event),
- },
- }),
+ ensureCliOnPath(buildEnsureCliOnPathOpts()),
])
.then(([mcpSettled, pathSettled]) => {
if (mcpSettled.status === 'rejected') {
diff --git a/packages/desktop/src/main/mcp-wiring.test.ts b/packages/desktop/src/main/mcp-wiring.test.ts
index cd7c1c437..3fefe8662 100644
--- a/packages/desktop/src/main/mcp-wiring.test.ts
+++ b/packages/desktop/src/main/mcp-wiring.test.ts
@@ -30,6 +30,7 @@ import {
type McpWiringCliSurface,
type McpWiringDispatchTarget,
type McpWiringFsOps,
+ type McpWiringPathInstallSurface,
readMcpStatusMarker,
runMcpWiringOnFirstLaunch,
writeMcpStatusMarker,
@@ -591,6 +592,29 @@ function buildFirstLaunchCli(): { cli: McpWiringCliSurface; writes: McpWiringEdi
const SILENT_LOGGER = { info() {}, warn() {}, error() {}, event() {} };
+const STUB_PATH_DESCRIPTOR = {
+ shellDetected: true,
+ rcFilesToTouch: ['~/.zshrc'],
+ alreadyInstalled: false,
+} as const;
+
+/** PATH-install stub that records `applyConsent` calls and lets tests
+ * script the per-call outcome. */
+function stubPathInstall(
+ overrides: Partial<McpWiringPathInstallSurface> = {},
+): McpWiringPathInstallSurface & { consentCalls: Array<'granted' | 'declined'> } {
+ const consentCalls: Array<'granted' | 'declined'> = [];
+ return {
+ consentCalls,
+ computeDescriptor: () => ({ ...STUB_PATH_DESCRIPTOR, rcFilesToTouch: ['~/.zshrc'] }),
+ applyConsent: async (status) => {
+ consentCalls.push(status);
+ return { ok: true as const };
+ },
+ ...overrides,
+ };
+}
+
function buildWiringOpts(overrides: Partial<WiringOpts> = {}): WiringOpts {
const { cli } = buildFirstLaunchCli();
return {
@@ -600,6 +624,7 @@ function buildWiringOpts(overrides: Partial<WiringOpts> = {}): WiringOpts {
platform: 'darwin',
ipcMain: stubIpcMain(),
cli,
+ pathInstall: stubPathInstall(),
fs: memoryFs(),
logger: SILENT_LOGGER,
...overrides,
@@ -622,6 +647,11 @@ describe('runMcpWiringOnFirstLaunch — mid-session immediate dispatch', () => {
channel: 'ok:mcp-wiring:show',
payload: {
detectedEditors: [{ id: 'claude', label: 'claude', detected: true, willReplace: false }],
+ pathInstall: {
+ shellDetected: true,
+ rcFilesToTouch: ['~/.zshrc'],
+ alreadyInstalled: false,
+ },
},
},
]);
@@ -807,3 +837,152 @@ describe('runMcpWiringOnFirstLaunch — mid-session immediate dispatch', () => {
expect(wc.sent.map((s) => s.channel)).toEqual(['ok:mcp-wiring:show']);
});
});
+
+describe('runMcpWiringOnFirstLaunch — PATH consent leg', () => {
+ test('confirm with pathInstall:true applies granted consent and writes the marker', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const pathInstall = stubPathInstall();
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({ ipcMain, fs, pathInstall, immediateDispatchTarget: wc }),
+ );
+
+ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');
+ const result = await confirm?.(
+ { sender: { id: 11 } },
+ { editorIds: ['claude'], pathInstall: true },
+ );
+ expect(result).toEqual({ ok: true });
+ expect(pathInstall.consentCalls).toEqual(['granted']);
+ expect(readMcpStatusMarker('/home/u', fs)).toMatchObject({ configured: true });
+ });
+
+ test('confirm with pathInstall:false records the decline (and still wires editors)', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const pathInstall = stubPathInstall();
+ const { cli, writes } = buildFirstLaunchCli();
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({ ipcMain, cli, fs, pathInstall, immediateDispatchTarget: wc }),
+ );
+
+ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');
+ const result = await confirm?.(
+ { sender: { id: 11 } },
+ { editorIds: ['claude'], pathInstall: false },
+ );
+ expect(result).toEqual({ ok: true });
+ expect(pathInstall.consentCalls).toEqual(['declined']);
+ expect(writes).toEqual([['claude' as McpWiringEditorId]]);
+ expect(readMcpStatusMarker('/home/u', fs)).toMatchObject({ configured: true });
+ });
+
+ test('confirm without pathInstall leaves the PATH surface untouched (no decision solicited)', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const pathInstall = stubPathInstall();
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({ ipcMain, fs, pathInstall, immediateDispatchTarget: wc }),
+ );
+
+ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');
+ const result = await confirm?.({ sender: { id: 11 } }, { editorIds: ['claude'] });
+ expect(result).toEqual({ ok: true });
+ expect(pathInstall.consentCalls).toEqual([]);
+ expect(readMcpStatusMarker('/home/u', fs)).toMatchObject({ configured: true });
+ });
+
+ test('a failed PATH leg defers the marker and allows a same-boot retry (deferred-marker mirror)', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const events: Array<Record<string, unknown>> = [];
+ const outcomes = [
+ { ok: false as const, error: 'EACCES: /home/u/.zshrc' },
+ { ok: true as const },
+ ];
+ const consentCalls: Array<'granted' | 'declined'> = [];
+ const pathInstall: McpWiringPathInstallSurface = {
+ computeDescriptor: () => ({ ...STUB_PATH_DESCRIPTOR, rcFilesToTouch: ['~/.zshrc'] }),
+ applyConsent: async (status) => {
+ consentCalls.push(status);
+ return outcomes.shift() ?? { ok: true as const };
+ },
+ };
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({
+ ipcMain,
+ fs,
+ pathInstall,
+ immediateDispatchTarget: wc,
+ logger: { info() {}, warn() {}, error() {}, event: (e) => events.push(e) },
+ }),
+ );
+
+ const confirm = ipcMain.handlers.get('ok:mcp-wiring:confirm');
+ const first = (await confirm?.(
+ { sender: { id: 11 } },
+ { editorIds: ['claude'], pathInstall: true },
+ )) as { ok: boolean; error?: string };
+ expect(first.ok).toBe(false);
+ expect(first.error).toContain('PATH');
+ expect(readMcpStatusMarker('/home/u', fs)).toBeNull();
+ expect(events.find((e) => e.event === 'mcp-wiring-path-consent-failed')).toMatchObject({
+ decision: 'granted',
+ });
+
+ const second = await confirm?.(
+ { sender: { id: 11 } },
+ { editorIds: ['claude'], pathInstall: true },
+ );
+ expect(second).toEqual({ ok: true });
+ expect(consentCalls).toEqual(['granted', 'granted']);
+ expect(readMcpStatusMarker('/home/u', fs)).toMatchObject({ configured: true });
+ });
+
+ test('a throwing descriptor degrades to a hidden PATH row instead of killing the dialog', () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const events: Array<Record<string, unknown>> = [];
+ const pathInstall = stubPathInstall({
+ computeDescriptor: () => {
+ throw new Error('marker unreadable');
+ },
+ });
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({
+ ipcMain,
+ pathInstall,
+ immediateDispatchTarget: wc,
+ logger: { info() {}, warn() {}, error() {}, event: (e) => events.push(e) },
+ }),
+ );
+
+ expect(wc.sent).toHaveLength(1);
+ expect((wc.sent[0]?.payload as { pathInstall: unknown }).pathInstall).toEqual({
+ shellDetected: false,
+ rcFilesToTouch: [],
+ alreadyInstalled: false,
+ });
+ expect(events.some((e) => e.event === 'mcp-wiring-path-descriptor-failed')).toBe(true);
+ });
+
+ test('skip never touches the PATH surface', async () => {
+ const ipcMain = stubIpcMain();
+ const wc = fakeWebContents(11);
+ const fs = memoryFs();
+ const pathInstall = stubPathInstall();
+ runMcpWiringOnFirstLaunch(
+ buildWiringOpts({ ipcMain, fs, pathInstall, immediateDispatchTarget: wc }),
+ );
+
+ const skip = ipcMain.handlers.get('ok:mcp-wiring:skip');
+ const result = await skip?.({ sender: { id: 11 } });
+ expect(result).toEqual({ ok: true });
+ expect(pathInstall.consentCalls).toEqual([]);
+ expect(readMcpStatusMarker('/home/u', fs)).toMatchObject({ configured: false });
+ });
+});
diff --git a/packages/desktop/src/main/mcp-wiring.ts b/packages/desktop/src/main/mcp-wiring.ts
index 12519825b..f35848aa5 100644
--- a/packages/desktop/src/main/mcp-wiring.ts
+++ b/packages/desktop/src/main/mcp-wiring.ts
@@ -21,6 +21,7 @@ import type {
McpWiringConfirmResult,
McpWiringEditorDetection,
McpWiringEditorId,
+ McpWiringPathInstallDescriptor,
McpWiringSkipResult,
} from '../shared/ipc-channels.ts';
import { createHandler } from '../shared/ipc-handler.ts';
@@ -190,6 +191,15 @@ export interface McpWiringCliSurface {
editorTargets: Record<McpWiringEditorId, EditorMcpTarget>;
}
+export interface McpWiringPathInstallSurface {
+ /** Arming-time descriptor for the dialog's PATH row. Read-only — must not
+ * write. Failures are tolerated (row degrades to hidden). */
+ computeDescriptor(): McpWiringPathInstallDescriptor;
+ applyConsent(
+ status: 'granted' | 'declined',
+ ): Promise<{ ok: true } | { ok: false; error: string }>;
+}
+
interface McpWiringLogger {
info(msg: string, ctx?: object): void;
warn(msg: string, ctx?: object): void;
@@ -220,6 +230,10 @@ interface RunMcpWiringOpts {
logger?: McpWiringLogger;
}
+export interface RunMcpWiringFirstLaunchOpts extends RunMcpWiringOpts {
+ pathInstall: McpWiringPathInstallSurface;
+}
+
export interface RunMcpWiringHandle {
destroy(): void;
readonly armed: boolean;
@@ -368,7 +382,7 @@ export function checkAndRepairMcpWiringOnStartup(
});
}
-export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringOpts): RunMcpWiringHandle {
+export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringFirstLaunchOpts): RunMcpWiringHandle {
const {
isPackaged,
executablePath,
@@ -376,6 +390,7 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringOpts): RunMcpWiringH
platform,
ipcMain,
cli,
+ pathInstall,
forceEnv,
reclaimDisableEnv,
forceShow = false,
@@ -447,6 +462,16 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringOpts): RunMcpWiringH
return inertHandle;
}
+ let pathDescriptor: McpWiringPathInstallDescriptor;
+ try {
+ pathDescriptor = pathInstall.computeDescriptor();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ logger.error('path-install descriptor failed — PATH row hidden for this boot', { message });
+ logger.event({ event: 'mcp-wiring-path-descriptor-failed', error: message });
+ pathDescriptor = { shellDetected: false, rcFilesToTouch: [], alreadyInstalled: false };
+ }
+
let handled = false;
let capturedSenderId: number | null = null;
@@ -546,6 +571,44 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringOpts): RunMcpWiringH
};
}
+ const pathDecision =
+ request?.pathInstall === true
+ ? ('granted' as const)
+ : request?.pathInstall === false
+ ? ('declined' as const)
+ : null;
+ if (pathDecision !== null) {
+ let pathResult: { ok: true } | { ok: false; error: string };
+ try {
+ pathResult = await pathInstall.applyConsent(pathDecision);
+ } catch (err) {
+ pathResult = { ok: false, error: err instanceof Error ? err.message : String(err) };
+ }
+ if (!pathResult.ok) {
+ logger.event({
+ event: 'mcp-wiring-path-consent-failed',
+ decision: pathDecision,
+ error: pathResult.error,
+ });
+ logIpcError({
+ event: 'ipc.error',
+ channel: 'ok:mcp-wiring:confirm',
+ reason: 'path-consent-failed',
+ handler: 'mcpWiringConfirm',
+ cause: { decision: pathDecision, error: pathResult.error },
+ });
+ handled = false;
+ return {
+ ok: false,
+ error:
+ pathDecision === 'granted'
+ ? `Couldn't add ok to your PATH (${pathResult.error}). The dialog will reappear on next launch so you can retry.`
+ : `Couldn't record your PATH preference (${pathResult.error}). The dialog will reappear on next launch so you can retry.`,
+ };
+ }
+ logger.info('path consent applied', { decision: pathDecision });
+ }
+
const configuredEditors = results
.filter((r) => r.action === 'written' || r.action === 'overwritten')
.map((r) => r.editorId);
@@ -630,6 +693,7 @@ export function runMcpWiringOnFirstLaunch(opts: RunMcpWiringOpts): RunMcpWiringH
try {
sendToRenderer(target, 'ok:mcp-wiring:show', {
detectedEditors: detections,
+ pathInstall: pathDescriptor,
});
logger.info('dispatched show to renderer', {
detectedCount: detections.length,
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 1329524d4..2abad5ce5 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -232,7 +232,7 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
...(deps.reconfigureMcpWiring
? ([
{
- label: 'Configure AI tool integrations…',
+ label: 'Set up OpenKnowledge integrations…',
click: () => {
void deps.reconfigureMcpWiring?.();
},
diff --git a/packages/desktop/src/main/path-install.test.ts b/packages/desktop/src/main/path-install.test.ts
index 97ee46ebd..e094e7922 100644
--- a/packages/desktop/src/main/path-install.test.ts
+++ b/packages/desktop/src/main/path-install.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test';
import {
+ existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
@@ -12,6 +13,7 @@ import {
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import {
+ computePathInstallDescriptor,
computePathLeg,
type EnsureCliOnPathResult,
ensureCliOnPath,
@@ -21,85 +23,207 @@ import {
const EXE = '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';
const WRAPPER = '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';
+const GRANTED = { status: 'granted', at: '2026-07-02T00:00:00.000Z' } as const;
+const DECLINED = { status: 'declined', at: '2026-07-02T00:00:00.000Z' } as const;
+
function home() {
return mkdtempSync(join(tmpdir(), 'ok-path-install-'));
}
-describe('ensureCliOnPath', () => {
- test('installs canonical ~/.ok/bin links, env shim, zsh rc block, and marker without admin prompt', async () => {
+type EnsureOpts = Parameters<typeof ensureCliOnPath>[0];
+
+/** Baseline opts: fresh packaged darwin launch; `~/.ok/bin` NOT yet on the
+ * discovered interactive PATH (the typical fresh machine, so the
+ * `canSkipRc` fast-path stays out of the way unless a test opts in). */
+function baseOpts(h: string, overrides: Partial<EnsureOpts> = {}): EnsureOpts {
+ return {
+ executablePath: EXE,
+ isPackaged: true,
+ platform: 'darwin',
+ home: h,
+ bundleVersion: '0.5.0-test',
+ env: { HOME: h, SHELL: '/bin/zsh' },
+ spawn: async () => ({ code: 0, stdout: '/usr/bin:/bin', stderr: '' }),
+ ...overrides,
+ };
+}
+
+function readMarkerFile(h: string): Record<string, unknown> {
+ return JSON.parse(readFileSync(pathInstallMarkerPath(h), 'utf8'));
+}
+
+describe('ensureCliOnPath — consent gate (rc files are never written without a consent signal)', () => {
+ test('fresh launch without a decision: OK-owned steps land, no rc file is touched', async () => {
const h = home();
- const result = await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),
- });
- expect(result.status).toBe('installed');
- if (result.status === 'installed') expect(result.summary).toContain('~/.zshrc');
+ const result = await ensureCliOnPath(baseOpts(h));
+ expect(result.status).toBe('installed-silent');
expect(readlinkSync(join(h, '.ok', 'bin', 'ok'))).toBe(WRAPPER);
expect(readlinkSync(join(h, '.ok', 'bin', 'open-knowledge'))).toBe(WRAPPER);
expect(readFileSync(join(h, '.ok', 'env.sh'), 'utf8')).toContain(
'export PATH="$' + '{HOME}/.ok/bin:$' + '{PATH}"',
);
+ expect(existsSync(join(h, '.zshrc'))).toBe(false);
+ expect(existsSync(join(h, '.bash_profile'))).toBe(false);
+ expect(existsSync(join(h, '.config', 'fish', 'conf.d', 'open-knowledge.fish'))).toBe(false);
+ const marker = readMarkerFile(h);
+ expect(marker.rcFiles).toEqual([]);
+ expect(marker.consent).toBeUndefined();
+ });
+
+ test('an existing .zshrc stays byte-identical across undecided launches', async () => {
+ const h = home();
+ writeFileSync(join(h, '.zshrc'), 'export FOO=1\n');
+ await ensureCliOnPath(baseOpts(h));
+ await ensureCliOnPath(baseOpts(h));
+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).toBe('export FOO=1\n');
+ });
+
+ test('granted decision appends the managed block, records consent, and discloses the file', async () => {
+ const h = home();
+ const events: Array<Record<string, unknown>> = [];
+ const result = await ensureCliOnPath(
+ baseOpts(h, { consentDecision: GRANTED, logger: { event: (e) => events.push(e) } }),
+ );
+ expect(result.status).toBe('installed');
+ if (result.status === 'installed') expect(result.summary).toContain('~/.zshrc');
const zshrc = readFileSync(join(h, '.zshrc'), 'utf8');
expect(zshrc).toContain('# >>> open-knowledge cli >>>');
expect(zshrc).toContain('Delete this whole block to opt out');
- expect(JSON.parse(readFileSync(pathInstallMarkerPath(h), 'utf8')).bundleWrapperPath).toBe(
- WRAPPER,
+ const marker = readMarkerFile(h);
+ expect(marker.consent).toEqual({ status: 'granted', at: GRANTED.at });
+ const granted = events.find((e) => e.event === 'path-install-consent-granted');
+ expect(granted).toMatchObject({ source: 'dialog' });
+ });
+
+ test('startup → dialog grant → next startup: the confirm path flips a healthy-but-blockless marker', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h));
+ const granted = await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ expect(granted.status).toBe('installed');
+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('# >>> open-knowledge cli >>>');
+ const relaunch = await ensureCliOnPath(baseOpts(h));
+ expect(relaunch.status).toBe('healthy-current');
+ });
+
+ test('declined decision records the choice and startup never appends afterwards', async () => {
+ const h = home();
+ const events: Array<Record<string, unknown>> = [];
+ const declined = await ensureCliOnPath(
+ baseOpts(h, { consentDecision: DECLINED, logger: { event: (e) => events.push(e) } }),
);
+ expect(declined.status).toBe('installed-silent');
+ expect(existsSync(join(h, '.zshrc'))).toBe(false);
+ expect(readMarkerFile(h).consent).toEqual({ status: 'declined', at: DECLINED.at });
+ expect(events.find((e) => e.event === 'path-install-consent-declined')).toMatchObject({
+ source: 'dialog',
+ });
+ const relaunch = await ensureCliOnPath(baseOpts(h));
+ expect(relaunch.status).toBe('healthy-current');
+ expect(existsSync(join(h, '.zshrc'))).toBe(false);
});
- test('healthy marker fast-path respects disk source of truth', async () => {
+ test('granted consent covers a NEW rc target on the next full install pass', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ writeFileSync(join(h, '.bash_profile'), 'export BAR=1\n');
+ const fastPath = await ensureCliOnPath(baseOpts(h));
+ expect(fastPath.status).toBe('healthy-current');
+ expect(readFileSync(join(h, '.bash_profile'), 'utf8')).toBe('export BAR=1\n');
+
+ const newExe = '/Users/someone/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';
+ const result = await ensureCliOnPath(baseOpts(h, { executablePath: newExe }));
+ expect(result.status).toBe('installed');
+ if (result.status === 'installed') expect(result.summary).toContain('~/.bash_profile');
+ expect(readFileSync(join(h, '.bash_profile'), 'utf8')).toContain(
+ '# >>> open-knowledge cli >>>',
+ );
+ });
+
+ test('grandfather via healthy fast-path: pre-consent marker + healthy block ⇒ consent stamped, no rc write', async () => {
const h = home();
- await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ const markerPath = pathInstallMarkerPath(h);
+ const preConsent = readMarkerFile(h);
+ delete preConsent.consent;
+ writeFileSync(markerPath, JSON.stringify(preConsent, null, 2));
+ const zshrcBefore = readFileSync(join(h, '.zshrc'), 'utf8');
+
+ const events: Array<Record<string, unknown>> = [];
+ const result = await ensureCliOnPath(baseOpts(h, { logger: { event: (e) => events.push(e) } }));
+ expect(result.status).toBe('healthy-current');
+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).toBe(zshrcBefore);
+ const marker = readMarkerFile(h);
+ expect((marker.consent as { status: string }).status).toBe('granted');
+ expect(events.find((e) => e.event === 'path-install-consent-granted')).toMatchObject({
+ source: 'grandfather',
});
- const healthy = await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),
+ });
+
+ test('grandfather via full pass: dotfile-synced block with no marker ⇒ treated as consented', async () => {
+ const h = home();
+ writeFileSync(
+ join(h, '.zshrc'),
+ '# >>> open-knowledge cli >>>\nstale contents\n# <<< open-knowledge cli <<<\n',
+ );
+ const events: Array<Record<string, unknown>> = [];
+ const result = await ensureCliOnPath(baseOpts(h, { logger: { event: (e) => events.push(e) } }));
+ expect(result.status).toBe('installed');
+ expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('$HOME/.ok/env.sh');
+ expect((readMarkerFile(h).consent as { status: string }).status).toBe('granted');
+ expect(events.find((e) => e.event === 'path-install-consent-granted')).toMatchObject({
+ source: 'grandfather',
});
+ });
+
+ test('a malformed consent field is tolerated and repaired from on-disk evidence', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ const markerPath = pathInstallMarkerPath(h);
+ const corrupt = readMarkerFile(h);
+ corrupt.consent = { status: 'maybe' };
+ writeFileSync(markerPath, JSON.stringify(corrupt, null, 2));
+ const events: Array<Record<string, unknown>> = [];
+ const result = await ensureCliOnPath(baseOpts(h, { logger: { event: (e) => events.push(e) } }));
+ expect(events.some((e) => e.event === 'path-install-marker-consent-invalid')).toBe(true);
+ expect(result.status).toBe('healthy-current');
+ expect((readMarkerFile(h).consent as { status: string }).status).toBe('granted');
+ });
+
+ test('a marker carrying unknown future fields still fast-paths (additive round-trip)', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ const markerPath = pathInstallMarkerPath(h);
+ const marker = readMarkerFile(h);
+ marker.futureField = 'from-a-newer-build';
+ writeFileSync(markerPath, JSON.stringify(marker, null, 2));
+ const result = await ensureCliOnPath(baseOpts(h));
+ expect(result.status).toBe('healthy-current');
+ });
+});
+
+describe('ensureCliOnPath', () => {
+ test('healthy marker fast-path respects disk source of truth', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h));
+ const healthy = await ensureCliOnPath(baseOpts(h));
expect(healthy.status).toBe('healthy-current');
unlinkSync(join(h, '.ok', 'bin', 'ok'));
- const repaired = await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),
- });
+ const repaired = await ensureCliOnPath(baseOpts(h));
expect(repaired.status).toBe('installed-silent');
expect(readlinkSync(join(h, '.ok', 'bin', 'ok'))).toBe(WRAPPER);
+ expect(existsSync(join(h, '.zshrc'))).toBe(false);
});
test('honors removal of the managed block — records opt-out, never re-adds, summary discloses', async () => {
const h = home();
- const run = () =>
- ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),
- });
- const first = await run();
+ const run = (overrides: Partial<EnsureOpts> = {}) =>
+ ensureCliOnPath(
+ baseOpts(h, {
+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),
+ ...overrides,
+ }),
+ );
+ const first = await run({ consentDecision: GRANTED });
expect(first.status).toBe('installed');
expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('# >>> open-knowledge cli >>>');
if (first.status === 'installed') expect(first.summary).toContain('~/.zshrc');
@@ -109,7 +233,7 @@ describe('ensureCliOnPath', () => {
expect(second.status).toBe('installed');
expect(readFileSync(join(h, '.zshrc'), 'utf8')).not.toContain('# >>> open-knowledge cli >>>');
if (second.status === 'installed') expect(second.summary).toContain("won't be re-added");
- const marker = JSON.parse(readFileSync(pathInstallMarkerPath(h), 'utf8'));
+ const marker = readMarkerFile(h);
expect(marker.rcOptOuts).toEqual([join(h, '.zshrc')]);
const third = await run();
@@ -122,15 +246,12 @@ describe('ensureCliOnPath', () => {
const bin = join(h, 'bin');
mkdirSync(bin);
writeFileSync(join(h, '.zshrc'), 'export FOO=1');
- const result = await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${bin}:/usr/bin`, stderr: '' }),
- });
+ const result = await ensureCliOnPath(
+ baseOpts(h, {
+ consentDecision: GRANTED,
+ spawn: async () => ({ code: 0, stdout: `${bin}:/usr/bin`, stderr: '' }),
+ }),
+ );
expect(result.status).toBe('installed');
expect(() => lstatSync(join(bin, 'ok'))).toThrow();
expect(() => lstatSync(join(bin, 'open-knowledge'))).toThrow();
@@ -172,36 +293,26 @@ describe('ensureCliOnPath', () => {
}),
);
const events: Array<Record<string, unknown>> = [];
- const result = await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),
- logger: { event: (e) => events.push(e) },
- });
+ const result = await ensureCliOnPath(
+ baseOpts(h, {
+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),
+ logger: { event: (e) => events.push(e) },
+ }),
+ );
expect(result.status).toBe('installed');
if (result.status === 'installed') expect(result.summary).toContain('leftover ok symlink');
expect(() => lstatSync(join(bin, 'ok'))).toThrow();
expect(readlinkSync(join(bin, 'open-knowledge'))).toBe('/elsewhere/ok.sh');
- const marker = JSON.parse(readFileSync(markerPath, 'utf8'));
+ const marker = readMarkerFile(h);
expect(marker.extraSymlinks).toEqual([]);
expect(events.some((e) => e.event === 'path-install-extra-symlink-removed')).toBe(true);
});
test('skips outside packaged darwin bundle contexts', async () => {
const h = home();
- const base = {
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
+ const base = baseOpts(h, {
spawn: async () => ({ code: 0, stdout: '', stderr: '' }),
- };
+ });
expect(await ensureCliOnPath({ ...base, reclaimDisableEnv: '1' })).toEqual({
status: 'skipped',
reason: 'reclaim-disabled',
@@ -223,48 +334,35 @@ describe('ensureCliOnPath', () => {
test('returns failed-all instead of throwing when an fs operation fails', async () => {
const h = home();
const enoent = () => Object.assign(new Error('ENOENT'), { code: 'ENOENT' });
- const result = await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),
- fs: {
- existsSync: () => false,
- readFileSync: () => '',
- writeFileSync: () => {},
- mkdirSync: () => {
- throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
+ const result = await ensureCliOnPath(
+ baseOpts(h, {
+ fs: {
+ existsSync: () => false,
+ readFileSync: () => '',
+ writeFileSync: () => {},
+ mkdirSync: () => {
+ throw Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' });
+ },
+ unlinkSync: () => {},
+ symlinkSync: () => {},
+ renameSync: () => {},
+ readlinkSync: () => {
+ throw enoent();
+ },
+ lstatSync: () => {
+ throw enoent();
+ },
},
- unlinkSync: () => {},
- symlinkSync: () => {},
- renameSync: () => {},
- readlinkSync: () => {
- throw enoent();
- },
- lstatSync: () => {
- throw enoent();
- },
- },
- logger: { event: () => {} },
- });
+ logger: { event: () => {} },
+ }),
+ );
expect(result.status).toBe('failed-all');
if (result.status === 'failed-all') expect(result.error).toContain('EACCES');
});
test('fish conf.d block uses fish syntax, not POSIX export', async () => {
const h = home();
- await ensureCliOnPath({
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),
- });
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
const fish = readFileSync(join(h, '.config', 'fish', 'conf.d', 'open-knowledge.fish'), 'utf8');
expect(fish).toContain('# >>> open-knowledge cli >>>');
expect(fish).toContain('set -gx PATH');
@@ -273,26 +371,73 @@ describe('ensureCliOnPath', () => {
test('app update repoints canonical symlinks to the new bundle wrapper', async () => {
const h = home();
- const opts = (exe: string) => ({
- executablePath: exe,
- isPackaged: true,
- platform: 'darwin',
- home: h,
- bundleVersion: '0.5.0-test',
- env: { HOME: h, SHELL: '/bin/zsh' },
- spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin`, stderr: '' }),
- });
- await ensureCliOnPath(opts(EXE));
+ await ensureCliOnPath(baseOpts(h));
const newExe = '/Users/someone/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';
const newWrapper =
'/Users/someone/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh';
- const result = await ensureCliOnPath(opts(newExe));
+ const result = await ensureCliOnPath(baseOpts(h, { executablePath: newExe }));
expect(result.status).toBe('installed-silent');
expect(readlinkSync(join(h, '.ok', 'bin', 'ok'))).toBe(newWrapper);
expect(readlinkSync(join(h, '.ok', 'bin', 'open-knowledge'))).toBe(newWrapper);
});
});
+describe('computePathInstallDescriptor', () => {
+ test('fresh zsh machine: touchable rc files listed tildified, nothing installed yet', () => {
+ const h = home();
+ const descriptor = computePathInstallDescriptor({ home: h, env: { SHELL: '/bin/zsh' } });
+ expect(descriptor).toEqual({
+ shellDetected: true,
+ rcFilesToTouch: ['~/.zshrc', '~/.config/fish/conf.d/open-knowledge.fish'],
+ alreadyInstalled: false,
+ });
+ });
+
+ test('an existing .bash_profile joins the touch list; a non-zsh shell skips .zshrc creation', () => {
+ const h = home();
+ writeFileSync(join(h, '.bash_profile'), 'export BAR=1\n');
+ const descriptor = computePathInstallDescriptor({ home: h, env: { SHELL: '/bin/bash' } });
+ expect(descriptor.rcFilesToTouch).toEqual([
+ '~/.bash_profile',
+ '~/.config/fish/conf.d/open-knowledge.fish',
+ ]);
+ });
+
+ test('a healthy managed block flips alreadyInstalled', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ const descriptor = computePathInstallDescriptor({ home: h, env: { SHELL: '/bin/zsh' } });
+ expect(descriptor.alreadyInstalled).toBe(true);
+ expect(descriptor.shellDetected).toBe(true);
+ });
+
+ test('granted consent without a block (user manages PATH themselves) still reads alreadyInstalled', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h));
+ await ensureCliOnPath(
+ baseOpts(h, {
+ consentDecision: GRANTED,
+ spawn: async () => ({ code: 0, stdout: `${h}/.ok/bin:/usr/bin`, stderr: '' }),
+ }),
+ );
+ expect(existsSync(join(h, '.zshrc'))).toBe(false);
+ const descriptor = computePathInstallDescriptor({ home: h, env: { SHELL: '/bin/zsh' } });
+ expect(descriptor.alreadyInstalled).toBe(true);
+ });
+
+ test('opted-out rc files never re-enter the touch list; all-opted-out hides the row', async () => {
+ const h = home();
+ await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));
+ writeFileSync(join(h, '.zshrc'), 'export FOO=1\n');
+ unlinkSync(join(h, '.config', 'fish', 'conf.d', 'open-knowledge.fish'));
+ await ensureCliOnPath(baseOpts(h));
+ const descriptor = computePathInstallDescriptor({ home: h, env: { SHELL: '/bin/zsh' } });
+ expect(descriptor.rcFilesToTouch).not.toContain('~/.zshrc');
+ expect(descriptor.rcFilesToTouch).not.toContain('~/.config/fish/conf.d/open-knowledge.fish');
+ expect(descriptor.shellDetected).toBe(false);
+ });
+});
+
describe('computePathLeg', () => {
const marker = {} as Extract<EnsureCliOnPathResult, { status: 'installed' }>['marker'];
diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.ts
index 778870c0b..e664b82b9 100644
--- a/packages/desktop/src/main/path-install.ts
+++ b/packages/desktop/src/main/path-install.ts
@@ -16,9 +16,11 @@ import {
PATH_SHIM_BLOCK_RE as BLOCK_RE,
PATH_SHIM_END as END,
type PathDiscovery,
+ type PathInstallConsent,
type PathInstallMarker,
pathInstallMarkerPath,
} from '@inkeep/open-knowledge';
+import type { McpWiringPathInstallDescriptor } from '../shared/ipc-channels.ts';
import { wrapperPathInBundle } from './bundle-paths.ts';
export { pathInstallMarkerPath };
@@ -107,6 +109,7 @@ interface EnsureCliOnPathOpts {
) => Promise<{ code: number | null; stdout: string; stderr: string; timedOut?: boolean }>;
logger?: PathInstallLogger;
now?: () => Date;
+ consentDecision?: PathInstallConsent;
}
function readMarker(
@@ -122,6 +125,14 @@ function readMarker(
logger.event({ event: 'path-install-marker-version-unknown', foundVersion: parsed?.version });
return null;
}
+ if (
+ parsed.consent !== undefined &&
+ parsed.consent?.status !== 'granted' &&
+ parsed.consent?.status !== 'declined'
+ ) {
+ logger.event({ event: 'path-install-marker-consent-invalid' });
+ return { ...parsed, consent: undefined };
+ }
return parsed;
} catch (err) {
logger.event({
@@ -194,6 +205,10 @@ function rcBlockHealthy(path: string, fs: PathInstallFsOps): boolean {
return text.includes(BEGIN) && text.includes(END);
}
+function tildify(path: string, home: string): string {
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
+}
+
function linkPointsTo(
path: string,
target: string,
@@ -393,7 +408,30 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
const wrapper = wrapperPathInBundle(executablePath);
const prior = readMarker(home, fs, logger);
- if (prior && markerHealthy(prior, home, wrapper, fs, logger)) {
+ const consentUnchanged =
+ opts.consentDecision === undefined || prior?.consent?.status === opts.consentDecision.status;
+ if (prior && consentUnchanged && markerHealthy(prior, home, wrapper, fs, logger)) {
+ if (!prior.consent && prior.rcFiles.length > 0) {
+ const marker: PathInstallMarker = {
+ ...prior,
+ consent: { status: 'granted', at: (opts.now?.() ?? new Date()).toISOString() },
+ };
+ try {
+ writeMarker(home, marker, fs);
+ } catch (err) {
+ logger.event({
+ event: 'path-install-consent-stamp-failed',
+ error: err instanceof Error ? err.message : String(err),
+ });
+ return { status: 'healthy-current', marker: prior };
+ }
+ logger.event({
+ event: 'path-install-consent-granted',
+ source: 'grandfather',
+ rcFileCount: prior.rcFiles.length,
+ });
+ return { status: 'healthy-current', marker };
+ }
logger.event({ event: 'path-install-healthy-current', binDir: prior.binDir });
return { status: 'healthy-current', marker: prior };
}
@@ -440,23 +478,34 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
prior != null &&
discovery?.okBinAlreadyOnPath === true &&
activePriorRcFiles.every((file) => rcBlockHealthy(file, fs));
+ const nowIso = (opts.now?.() ?? new Date()).toISOString();
+ const grandfatherEvidence =
+ activePriorRcFiles.some((file) => rcBlockHealthy(file, fs)) ||
+ targets.some((target) => rcBlockHealthy(target.path, fs));
+ const consent: PathInstallConsent | undefined =
+ opts.consentDecision ??
+ prior?.consent ??
+ (grandfatherEvidence ? { status: 'granted', at: nowIso } : undefined);
+ const rcConsented = consent?.status === 'granted';
phase = 'upsertRcBlocks';
const rcFiles: string[] = [];
const changedRcFiles: string[] = [];
if (canSkipRc && prior) {
rcFiles.push(...activePriorRcFiles);
- } else {
+ } else if (rcConsented) {
for (const target of targets) {
if (upsertBlock(target.path, target.content, fs)) changedRcFiles.push(target.path);
rcFiles.push(target.path);
}
+ } else {
+ rcFiles.push(...activePriorRcFiles.filter((file) => rcBlockHealthy(file, fs)));
}
phase = 'cleanupExtraSymlinks';
const cleanup = removeRecordedExtraSymlinks(prior?.extraSymlinks ?? [], fs, logger);
phase = 'writeMarker';
const marker: PathInstallMarker = {
version: 1,
- installedAt: (opts.now?.() ?? new Date()).toISOString(),
+ installedAt: nowIso,
bundleVersion,
bundleWrapperPath: wrapper,
binDir: okBin(home),
@@ -465,20 +514,30 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
rcOptOuts,
pathDiscovery: discovery,
extraSymlinks: cleanup.remaining,
+ ...(consent ? { consent } : {}),
};
writeMarker(home, marker, fs);
+ if (consent && consent.status !== prior?.consent?.status) {
+ logger.event({
+ event:
+ consent.status === 'granted'
+ ? 'path-install-consent-granted'
+ : 'path-install-consent-declined',
+ source: opts.consentDecision ? 'dialog' : 'grandfather',
+ rcTargetCount: targets.length,
+ });
+ }
logger.event({ event: 'path-install-symlink-success', binDir: marker.binDir });
if (changedRcFiles.length > 0)
logger.event({ event: 'path-install-rc-append-success', rcFiles: changedRcFiles });
- const tildify = (p: string) => (p.startsWith(`${home}/`) ? `~${p.slice(home.length)}` : p);
const parts: string[] = [];
if (changedRcFiles.length > 0)
parts.push(
- `Added ok to your PATH — managed block in ${changedRcFiles.map(tildify).join(', ')}.`,
+ `Added ok to your PATH — managed block in ${changedRcFiles.map((p) => tildify(p, home)).join(', ')}.`,
);
if (newOptOuts.length > 0)
parts.push(
- `You removed the OpenKnowledge block from ${newOptOuts.map(tildify).join(', ')} — it won't be re-added.`,
+ `You removed the OpenKnowledge block from ${newOptOuts.map((p) => tildify(p, home)).join(', ')} — it won't be re-added.`,
);
if (cleanup.removedCount > 0)
parts.push(
@@ -493,3 +552,27 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensure
return { status: 'failed-all', error };
}
}
+
+export function computePathInstallDescriptor(opts: {
+ home: string;
+ env?: Record<string, string | undefined>;
+ fs?: PathInstallFsOps;
+ logger?: PathInstallLogger;
+}): McpWiringPathInstallDescriptor {
+ const { home, fs = defaultFsOps, logger = DEFAULT_LOGGER } = opts;
+ const marker = readMarker(home, fs, logger);
+ const rcOptOuts = marker?.rcOptOuts ?? [];
+ const targets = rcTargets(home, (opts.env ?? process.env).SHELL, fs).filter(
+ (target) => !rcOptOuts.includes(target.path),
+ );
+ const candidates = new Set<string>([
+ ...targets.map((target) => target.path),
+ ...(marker?.rcFiles ?? []),
+ ]);
+ const blockPresent = [...candidates].some((path) => rcBlockHealthy(path, fs));
+ return {
+ shellDetected: targets.length > 0,
+ rcFilesToTouch: targets.map((target) => tildify(target.path, home)),
+ alreadyInstalled: blockPresent || marker?.consent?.status === 'granted',
+ };
+}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 0926a7f50..7ec28c105 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -408,7 +408,11 @@ const bridge: OkDesktopBridge = {
signalReady: () => {
invoke('ok:mcp-wiring:renderer-ready').catch(() => {});
},
- confirm: (editorIds) => invoke('ok:mcp-wiring:confirm', { editorIds }),
+ confirm: (request) =>
+ invoke('ok:mcp-wiring:confirm', {
+ editorIds: request.editorIds,
+ pathInstall: request.pathInstall,
+ }),
skip: () => invoke('ok:mcp-wiring:skip'),
},
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 5b4d97b0a..176a4709c 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -190,7 +190,11 @@ type OkMcpWiringEditorId = EditorId;
/** Payload passed to `onShow` subscribers. Mirrors ok:mcp-wiring:show.
* `willReplace: true` signals the editor has an existing OK-managed entry
- * that Add would overwrite — per-editor disclosure. */
+ * that Add would overwrite — per-editor disclosure. `pathInstall` drives
+ * the dialog's shell-PATH toggle row: `shellDetected: false` hides the
+ * row; `alreadyInstalled: true` renders it informational (block already on
+ * disk or consent already granted); `rcFilesToTouch` names the tildified
+ * shell files a grant would edit. */
export interface OkMcpWiringShowPayload {
readonly detectedEditors: readonly {
readonly id: OkMcpWiringEditorId;
@@ -198,6 +202,20 @@ export interface OkMcpWiringShowPayload {
readonly detected: boolean;
readonly willReplace: boolean;
}[];
+ readonly pathInstall: {
+ readonly shellDetected: boolean;
+ readonly rcFilesToTouch: readonly string[];
+ readonly alreadyInstalled: boolean;
+ };
+}
+
+/** Confirm payload for `mcpWiring.confirm`. `pathInstall` is the PATH
+ * toggle, tri-state: `true` → append the managed rc block; `false` →
+ * record declined, touch nothing; absent → no PATH decision was solicited
+ * (row hidden or informational). */
+export interface OkMcpWiringConfirmRequest {
+ readonly editorIds: readonly OkMcpWiringEditorId[];
+ readonly pathInstall?: boolean;
}
type OkMcpWiringResult = { ok: true } | { ok: false; error: string };
@@ -664,7 +682,10 @@ export interface OkDesktopBridge {
mcpWiring: {
onShow(cb: (payload: OkMcpWiringShowPayload) => void): OkUnsubscribe;
signalReady(): void;
- confirm(editorIds: readonly OkMcpWiringEditorId[]): Promise<OkMcpWiringResult>;
+ /** User clicked Add. `editorIds` is the subset the user checked;
+ * `pathInstall` is the PATH toggle (tri-state — see
+ * `OkMcpWiringConfirmRequest`). */
+ confirm(request: OkMcpWiringConfirmRequest): Promise<OkMcpWiringResult>;
skip(): Promise<OkMcpWiringResult>;
};
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index 7b279ce00..ae6452f31 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -228,10 +228,29 @@ export interface McpWiringEditorDetection {
readonly willReplace: boolean;
}
+/** PATH-install leg of the first-launch consent dialog. Computed read-only
+ * at arming time from the path-install marker + rc targets.
+ * `rcFilesToTouch` names the shell files a grant would edit (tildified for
+ * display; recorded opt-outs excluded). `shellDetected: false` — no
+ * touchable rc files — hides the PATH row. `alreadyInstalled` renders the
+ * row as informational: a managed block is already on disk or consent was
+ * already granted, so there is no new decision to solicit. */
+export interface McpWiringPathInstallDescriptor {
+ readonly shellDetected: boolean;
+ readonly rcFilesToTouch: readonly string[];
+ readonly alreadyInstalled: boolean;
+}
+
/** Confirm payload from renderer → main. Editors the user checked when they
- * clicked "Add". Subset of `McpWiringEditorId`. */
+ * clicked "Add". Subset of `McpWiringEditorId`.
+ *
+ * `pathInstall` is the PATH toggle, tri-state: `true` → append the managed
+ * rc block (consent granted); `false` → record declined, touch no rc file;
+ * absent → the dialog solicited no PATH decision (row hidden or
+ * informational) — the path-install marker is left untouched. */
export interface McpWiringConfirmRequest {
readonly editorIds: readonly McpWiringEditorId[];
+ readonly pathInstall?: boolean;
}
/** Confirm / skip response shape. `ok:false` surfaces when (a)
diff --git a/packages/desktop/src/shared/ipc-events.ts b/packages/desktop/src/shared/ipc-events.ts
index 447f07cbf..03e66cd99 100644
--- a/packages/desktop/src/shared/ipc-events.ts
+++ b/packages/desktop/src/shared/ipc-events.ts
@@ -10,7 +10,11 @@ import type {
OkServerVersionDriftInfo,
OkShareReceivedPayload,
} from './bridge-contract.ts';
-import type { McpWiringEditorDetection, OnboardingShowPayload } from './ipc-channels.ts';
+import type {
+ McpWiringEditorDetection,
+ McpWiringPathInstallDescriptor,
+ OnboardingShowPayload,
+} from './ipc-channels.ts';
export interface EventChannels {
'ok:project:switching': { payload: { projectPath: string } };
@@ -35,7 +39,10 @@ export interface EventChannels {
};
'ok:share:received': { payload: OkShareReceivedPayload };
'ok:mcp-wiring:show': {
- payload: { detectedEditors: readonly McpWiringEditorDetection[] };
+ payload: {
+ detectedEditors: readonly McpWiringEditorDetection[];
+ pathInstall: McpWiringPathInstallDescriptor;
+ };
};
'ok:onboarding:show': {
payload: OnboardingShowPayload;
diff --git a/packages/desktop/src/utility/pty-host.ts b/packages/desktop/src/utility/pty-host.ts
index a36ed1c76..dc984d794 100644
--- a/packages/desktop/src/utility/pty-host.ts
+++ b/packages/desktop/src/utility/pty-host.ts
@@ -1,3 +1,5 @@
+import { delimiter, join } from 'node:path';
+
const DARWIN_FALLBACK_SHELL = '/bin/zsh';
const STRIPPED_ENV_MARKERS = ['OK_ELECTRON_PROTOCOL_HOST', 'OK_LOCK_KIND'] as const;
@@ -152,6 +154,14 @@ export function buildShellEnv(
if (stripped.has(key)) continue;
out[key] = value;
}
+ const home = out.HOME;
+ if (home) {
+ const okBin = join(home, '.ok', 'bin');
+ const entries = (out.PATH ?? '').split(delimiter).filter(Boolean);
+ if (!entries.includes(okBin)) {
+ out.PATH = [okBin, ...entries].join(delimiter);
+ }
+ }
out.OK_DESKTOP_TERMINAL = '1';
return out;
}
diff --git a/packages/desktop/tests/utility/pty-host.test.ts b/packages/desktop/tests/utility/pty-host.test.ts
index c869c5f3f..06d793749 100644
--- a/packages/desktop/tests/utility/pty-host.test.ts
+++ b/packages/desktop/tests/utility/pty-host.test.ts
@@ -181,6 +181,35 @@ describe('setupPtyHost — create', () => {
const env = h.spawnCalls[0]?.options.env ?? {};
expect(env.OK_DESKTOP_TERMINAL).toBe('1');
});
+
+ test('prepends ~/.ok/bin to the child PATH so `ok` resolves regardless of rc consent', () => {
+ const h = makeHarness({
+ env: { SHELL: '/bin/zsh', PATH: '/usr/bin:/bin', HOME: '/Users/alice' },
+ });
+ h.fire(CREATE());
+ const env = h.spawnCalls[0]?.options.env ?? {};
+ expect(env.PATH).toBe('/Users/alice/.ok/bin:/usr/bin:/bin');
+ });
+
+ test('does not duplicate ~/.ok/bin when the parent PATH already carries it', () => {
+ const h = makeHarness({
+ env: {
+ SHELL: '/bin/zsh',
+ PATH: '/opt/x:/Users/alice/.ok/bin:/usr/bin',
+ HOME: '/Users/alice',
+ },
+ });
+ h.fire(CREATE());
+ const env = h.spawnCalls[0]?.options.env ?? {};
+ expect(env.PATH).toBe('/opt/x:/Users/alice/.ok/bin:/usr/bin');
+ });
+
+ test('leaves PATH untouched when HOME is absent (nothing to resolve against)', () => {
+ 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');
+ });
});
describe('setupPtyHost — streaming', () => {
@@ -573,7 +602,11 @@ describe('buildShellEnv', () => {
OK_LOCK_KIND: 'interactive',
MAYBE: undefined,
});
- expect(env).toEqual({ PATH: '/usr/bin', HOME: '/Users/x', OK_DESKTOP_TERMINAL: '1' });
+ expect(env).toEqual({
+ PATH: '/Users/x/.ok/bin:/usr/bin',
+ HOME: '/Users/x',
+ OK_DESKTOP_TERMINAL: '1',
+ });
});
});