Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): stop the consent dialog inventing editor installs (PRD-8007) (#3631)
tim-inkeep9026b09aaa68
diff --git a/.changeset/consent-no-phantom-editor-dirs.md b/.changeset/consent-no-phantom-editor-dirs.mdnew file mode 100644index 000000000..e0ff6d489--- /dev/null+++ b/.changeset/consent-no-phantom-editor-dirs.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Connecting an editor in Settings → AI tools no longer creates a config directory for a tool you don't have installed. For Cursor, Codex, Copilot, OpenCode and Claude Desktop, that directory is also how Open Knowledge decides the tool is installed, so switching one on used to make the app report the editor as present everywhere from then on, permanently and with no way to undo it. Those rows now say the tool wasn't found and point at their setup guide instead. Claude Code is unaffected, since its config file sits next to its detection folder rather than inside it.diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.tsindex 429a9f9ec..c9ee3c832 100644--- a/packages/cli/src/commands/init.test.ts+++ b/packages/cli/src/commands/init.test.ts@@ -28,6 +28,7 @@ import {resolveClaudeCodeConfigPath,resolveClaudeDesktopConfigPath,resolveCodexConfigPath,+ resolveCopilotConfigPath,resolveCursorConfigPath,resolveLmStudioConfigPath,resolveOpenCodeConfigPath,@@ -2456,6 +2457,11 @@ describe('writeUserMcpConfigs', () => {});it('writes the canonical chain shape for every selected editor', async () => {+ // Cursor's config dir doubles as its detection probe, so the consent write+ // is gated on the tool really being present. Model a machine+ // that HAS Cursor — otherwise this asserts the phantom-dir bug.+ mkdirSync(dirname(resolveCursorConfigPath({ home: fakeHome })), { recursive: true });+const results: EditorMcpResult[] = await writeUserMcpConfigs({editors: ['claude', 'cursor'],home: fakeHome,@@ -3350,3 +3356,115 @@ describe('resolveInitSkillEnablement — --skills / --no-skills flag parsing', (expect(sorted('bogus')).toEqual([]);});});++/**+ * The consent bypass must not create the directory that detection later reads+ * back as proof the editor is installed.+ */+describe('consent bypass never fabricates its own detection evidence (PRD-8007)', () => {+ let fakeHome: string;+ let testDir: string;+ const originalPlatform = process.platform;+ const originalHome = process.env.HOME;++ beforeEach(() => {+ testDir = resolve(+ tmpdir(),+ `mcp-fabricated-detection-${Date.now()}-${Math.random().toString(36).slice(2)}`,+ );+ mkdirSync(testDir, { recursive: true });+ fakeHome = join(testDir, 'fakehome');+ mkdirSync(fakeHome, { recursive: true });+ process.env.HOME = fakeHome;+ Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true });+ });++ afterEach(() => {+ Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true });+ if (originalHome === undefined) delete process.env.HOME;+ else process.env.HOME = originalHome;+ rmSync(testDir, { recursive: true, force: true });+ });++ // The five editors whose `detectPath` IS `dirname(configPath)`. Writing their+ // config creates the probe dir, which is what made detection self-fulfilling.+ const SELF_PROBING = [+ ['cursor', resolveCursorConfigPath],+ ['codex', resolveCodexConfigPath],+ ['claude-desktop', resolveClaudeDesktopConfigPath],+ ['opencode', resolveOpenCodeConfigPath],+ ['copilot', resolveCopilotConfigPath],+ ] as const;++ for (const [editorId, resolvePath] of SELF_PROBING) {+ it(`${editorId}: an explicit tick on an absent tool writes nothing`, () => {+ const configPath = resolvePath({ home: fakeHome });+ expect(existsSync(dirname(configPath))).toBe(false);++ const result = writeEditorMcpConfig(+ EDITOR_TARGETS[editorId],+ '',+ { skipAvailabilityCheck: true },+ fakeHome,+ );++ expect(result.action).toBe('skipped-missing');+ // The actual regression: no directory, so no phantom detection.+ expect(existsSync(dirname(configPath))).toBe(false);+ expect(detectInstalledEditors('', fakeHome)).not.toContain(editorId);+ });++ it(`${editorId}: the tick is still honoured once the tool is really there`, () => {+ const configPath = resolvePath({ home: fakeHome });+ mkdirSync(dirname(configPath), { recursive: true });++ const result = writeEditorMcpConfig(+ EDITOR_TARGETS[editorId],+ '',+ { skipAvailabilityCheck: true },+ fakeHome,+ );++ expect(result.action).toBe('written');+ expect(existsSync(configPath)).toBe(true);+ });+ }++ it('Claude Code keeps the bypass — its config sits beside the probe, not inside it', () => {+ const configPath = resolveClaudeCodeConfigPath({ home: fakeHome });+ // `~/.claude` absent, yet the config is `~/.claude.json`: writing it cannot+ // manufacture the probe, so an explicit tick must still be honoured.+ expect(existsSync(join(fakeHome, '.claude'))).toBe(false);++ const result = writeEditorMcpConfig(+ EDITOR_TARGETS.claude,+ '',+ { skipAvailabilityCheck: true },+ fakeHome,+ );++ expect(result.action).toBe('written');+ expect(existsSync(configPath)).toBe(true);+ expect(existsSync(join(fakeHome, '.claude'))).toBe(false);+ });++ it('the whole consent write leaves an empty home empty apart from Claude Code', async () => {+ const results: EditorMcpResult[] = await writeUserMcpConfigs({+ editors: ['claude', 'cursor', 'codex', 'claude-desktop', 'opencode', 'copilot'],+ home: fakeHome,+ });++ expect(results.filter((r) => r.action === 'written').map((r) => r.editorId)).toEqual([+ 'claude',+ ]);+ expect(+ results+ .filter((r) => r.action === 'skipped-missing')+ .map((r) => r.editorId)+ .sort(),+ ).toEqual(['claude-desktop', 'codex', 'copilot', 'cursor', 'opencode']);+ // Detection afterwards reports only what was genuinely present.+ expect(detectInstalledEditors('', fakeHome)).not.toContain('cursor');+ expect(detectInstalledEditors('', fakeHome)).not.toContain('codex');+ });+});diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex f0c589675..e0f19bb36 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -15,7 +15,7 @@*/import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';import { homedir } from 'node:os';-import { dirname, isAbsolute, join, relative, resolve } from 'node:path';+import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';import { inspect } from 'node:util';import {type McpLauncherDeclineReason,@@ -1012,6 +1012,38 @@ function isEditorTargetAvailable(target: EditorMcpTarget, cwd: string, home?: st}}+/**+ * True when writing this editor's config would CREATE the very directory+ * `isEditorTargetAvailable` probes — so the write manufactures the evidence+ * every later detection pass reads back.+ *+ * `mkdirSync(dirname(configPath), { recursive: true })` below is what does it.+ * Five editors sit in this shape because their `detectPath` is literally+ * `dirname(configPath)`: Claude Desktop, Cursor, Codex, Copilot, OpenCode. Tick+ * one in the consent dialog on a machine without it and `~/.cursor` appears,+ * after which `detectInstalledEditors` reports Cursor installed forever.+ *+ * Claude Code is NOT in this shape — it probes `~/.claude` while its config is+ * `~/.claude.json`, so the write lands beside the probe rather than inside it,+ * and an explicit tick stays honoured. Derived from the target rather than+ * listed by id so a new editor cannot be added into the trap silently.+ */+function writeWouldFabricateDetection(+ target: EditorMcpTarget,+ cwd: string,+ home?: string,+): boolean {+ try {+ const configDir = resolve(dirname(target.configPath(cwd, home)));+ const probePath = resolve(target.detectPath?.(cwd, home) ?? configDir);+ // Equal: the probe dir IS the config dir. Ancestor: the probe is a parent+ // of the config dir, which `recursive: true` creates on the way down.+ return probePath === configDir || configDir.startsWith(probePath + sep);+ } catch {+ return false;+ }+}+/*** Per-editor MCP config writer. Exported so `@inkeep/open-knowledge`* consumers — specifically Electron main's first-launch consent flow via@@ -1022,6 +1054,15 @@ function isEditorTargetAvailable(target: EditorMcpTarget, cwd: string, home?: st* empty config dirs for editors they haven't installed; the consent flow* bypasses the check because the user explicitly toggled the editor* checkbox in the dialog.+ *+ * The bypass does NOT extend to editors whose config dir doubles as their+ * detection probe — see `writeWouldFabricateDetection`. Those resolve to+ * `skipped-missing`, which BOTH consumers of this outcome handle:+ * the first-launch consent flow ignores it (only `failed` surfaces an error),+ * and Settings → AI tools maps it to an explicit "not found on this machine"+ * message in `integrations-settings.ts`'s `setEditor`. Settings is the+ * reachable path — its rows keep a live checkbox regardless of detection,+ * whereas the consent dialog only ever offers detected editors.*/export function writeEditorMcpConfig(target: EditorMcpTarget,@@ -1052,13 +1093,18 @@ export function writeEditorMcpConfig(// (configPathOverride set) — the project directory always exists by// definition.//- // `offerOnlyWhenDetected` editors (OpenClaw, Antigravity) are the exception:- // their config root must exist even under the consent bypass, so we never- // create a config for a global tool that isn't installed. Project-scope writes- // stay exempt — neither has a project config, so `configPathOverride` never- // applies to them.+ // Two exceptions keep the bypass from creating a home for a tool that isn't+ // installed. `offerOnlyWhenDetected` editors declare it explicitly (four+ // today — OpenClaw, Antigravity, LM Studio, Hermes — but read the flag, not+ // this list). `writeWouldFabricateDetection` catches the rest structurally:+ // when the config dir IS the probe dir, writing it would make OK detect a tool+ // purely because OK wrote there. Both leave Claude Code's tick honoured —+ // its config sits beside its probe, not inside it. Project-scope+ // writes stay exempt: `configPathOverride` short-circuits before either.const enforceAvailability =- !installOptions.skipAvailabilityCheck || target.offerOnlyWhenDetected === true;+ !installOptions.skipAvailabilityCheck ||+ target.offerOnlyWhenDetected === true ||+ writeWouldFabricateDetection(target, cwd, home);if (!configPathOverride && enforceAvailability && !isEditorTargetAvailable(target, cwd, home)) {return {editorId: target.id,@@ -1402,6 +1448,11 @@ export interface UserMcpConfigsOptions {* Bypasses `isEditorTargetAvailable` via `skipAvailabilityCheck: true` — the* user explicitly toggled the editor checkbox; their click IS the consent,* so skip-on-missing would silently drop their selection.+ *+ * Consent is consent to WIRE a tool, never to invent one: the bypass stops at+ * editors whose config dir is also their detection probe, where writing would+ * make OK detect a tool it only detects because it wrote there. Those come+ * back `skipped-missing` instead.*/export async function writeUserMcpConfigs(opts: UserMcpConfigsOptions): Promise<EditorMcpResult[]> {// Filter out `scope: 'project'` targets (Pi) defensively: they have nodiff --git a/packages/desktop/src/main/integrations-settings.test.ts b/packages/desktop/src/main/integrations-settings.test.tsindex 71334815a..950732da0 100644--- a/packages/desktop/src/main/integrations-settings.test.ts+++ b/packages/desktop/src/main/integrations-settings.test.ts@@ -73,7 +73,7 @@ interface CliOverrides {classifications?: Partial<Record<McpWiringEditorId, ReturnType<IntegrationsCliSurface['classifyExistingMcpEntry']>>>;- writeAction?: 'written' | 'overwritten' | 'failed' | 'declined';+ writeAction?: 'written' | 'overwritten' | 'failed' | 'declined' | 'skipped-missing';writeError?: string;removeKind?: 'removed' | 'not-present' | 'left-foreign' | 'declined';detected?: McpWiringEditorId[];@@ -405,6 +405,23 @@ describe('ok:integrations:dispatch — set editor', () => {if (!result.ok) expect(result.error).toContain("Couldn't safely edit Cursor's config");});+ test('an undetected self-probing editor says the tool is missing, not that OK failed', async () => {+ // Cursor's config dir doubles as its detection probe, so the CLI refuses+ // the write rather than creating the dir OK would later read back as+ // "installed". Settings rows keep a live checkbox regardless of detection,+ // so this outcome is reachable here — and before it was handled it fell to+ // the generic branch and blamed OK for a tool the user never installed.+ const { set } = setup({ cli: makeCli({ writeAction: 'skipped-missing' }) });+ const result = await set({ component: { kind: 'editor', id: 'cursor' }, enabled: true });+ expect(result.ok).toBe(false);+ if (!result.ok) {+ expect(result.error).toContain("Cursor wasn't found on this machine");+ expect(result.error).not.toContain("Couldn't add OpenKnowledge");+ // No dangling empty parenthetical — `skipped-missing` carries no `error`.+ expect(result.error).not.toContain('()');+ }+ });+test('a failed write surfaces its error', async () => {const { set } = setup({ cli: makeCli({ writeAction: 'failed', writeError: 'EROFS' }) });const result = await set({ component: { kind: 'editor', id: 'claude' }, enabled: true });diff --git a/packages/desktop/src/main/integrations-settings.ts b/packages/desktop/src/main/integrations-settings.tsindex 8ec72a2a8..432fdc9f2 100644--- a/packages/desktop/src/main/integrations-settings.ts+++ b/packages/desktop/src/main/integrations-settings.ts@@ -372,6 +372,17 @@ export function registerIntegrationsSettings(ok: false,error: `Couldn't safely edit ${label}'s config — it was left unchanged.`,};+ case 'skipped-missing':+ // The editor's config dir doubles as its detection probe, so writing+ // would create the very directory OK later reads back as "installed"+ // — the write is refused rather than fabricating that evidence. Every+ // row here keeps a live checkbox regardless of detection, so this is+ // reachable by design; say the tool is missing rather than blaming OK+ // for a failure. The row's own `How to set up` link covers what next.+ return {+ ok: false,+ error: `${label} wasn't found on this machine. Install it first, then connect it here.`,+ };default:return {ok: false,