Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
PRD-8785 Store Linux PATH markers under XDG config (#7458)
Andrew Mikofalvy44c8a90438e9
diff --git a/.changeset/linux-path-marker.md b/.changeset/linux-path-marker.mdnew file mode 100644index 000000000..24f17ac6b--- /dev/null+++ b/.changeset/linux-path-marker.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+"@inkeep/open-knowledge-core": patch+"@inkeep/open-knowledge-desktop": patch+---++Linux no longer creates a macOS-style Library folder when setting up the command-line tools, and existing setup choices are preserved.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 4c453e9e8..4346b5f2b 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -50,6 +50,8 @@ How the app lands depends on your platform:On every platform the app writes app-level state and logs on launch. The table below shows the macOS locations; Beta substitutes `OpenKnowledge Beta` for the app-data directory and uses its own updater cache. On Windows, Stable app state lives under `%APPDATA%\OpenKnowledge\` and Beta under `%APPDATA%\OpenKnowledge Beta\`. On Linux, the corresponding defaults are `~/.config/OpenKnowledge/` and `~/.config/OpenKnowledge Beta/` (or the matching XDG directories). Stable keeps its command-line shortcuts under `~/.ok/` and Beta keeps its own under `~/.ok-beta/`. When Beta sets up its `PATH` shim, it removes the `~/.ok/variants/beta/` folder that earlier Beta builds used.+On Linux, Stable keeps its `PATH` marker at `$XDG_CONFIG_HOME/OpenKnowledge/path-install.json` (default `~/.config/OpenKnowledge/path-install.json`). On startup after upgrading, it migrates a valid legacy marker from `~/Library/Application Support/OpenKnowledge/path-install.json` when the new marker is absent, preserving the recorded setup choices and removing only empty legacy folders.+| Path | What it is | Scope || --- | --- | --- || `~/Library/Application Support/OpenKnowledge/state.json` | Recent projects, window/view state, update channel, and your automatic-updates preference | Outside-project (home dir) |diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.tsindex 0cffe1069..93bc0ce9a 100644--- a/packages/cli/src/commands/removal-plan.test.ts+++ b/packages/cli/src/commands/removal-plan.test.ts@@ -507,13 +507,32 @@ describe('runRemoval — uninstall end to end', () => {}});- test('idempotent — a second run is a clean no-op (nothing removed, nothing failed)', async () => {+ test('idempotent — a second run is a clean no-op (nothing removed, nothing failed)', async ({+ onTestFinished,+ }) => {const home = mkdtempSync(join(tmpdir(), 'ok-uninst-'));+ const ambientConfig = mkdtempSync(join(tmpdir(), 'ok-uninst-ambient-'));+ const platform = process.platform;+ onTestFinished(() => {+ Object.defineProperty(process, 'platform', { value: platform });+ vi.unstubAllEnvs();+ });try {+ Object.defineProperty(process, 'platform', { value: 'linux' });+ vi.stubEnv('XDG_CONFIG_HOME', ambientConfig);+ vi.stubEnv('OK_CHANNEL', 'stable');+ write(+ join(ambientConfig, 'OpenKnowledge', 'path-install.json'),+ JSON.stringify(markerFor(ambientConfig)),+ );seedHome(home);const input = baseInput(home);await runRemoval(buildUninstallPlan(input), stubDeps());- const secondInput: UninstallPlanInput = { ...input, marker: readPathInstallMarker(home) };+ const secondInput: UninstallPlanInput = {+ ...input,+ marker: readPathInstallMarker(home, undefined, 'darwin', {}),+ };+ expect(secondInput.marker).toBeNull();const second = await runRemoval(buildUninstallPlan(secondInput),stubDeps({@@ -523,8 +542,10 @@ describe('runRemoval — uninstall end to end', () => {);expect(second.failed).toHaveLength(0);expect(second.removed).toHaveLength(0);+ expect(existsSync(join(ambientConfig, '.local', 'bin', 'ok'))).toBe(true);} finally {rmSync(home, { recursive: true, force: true });+ rmSync(ambientConfig, { recursive: true, force: true });}});});diff --git a/packages/cli/src/commands/uninstall.ts b/packages/cli/src/commands/uninstall.tsindex 09efaffa6..d3e0e3458 100644--- a/packages/cli/src/commands/uninstall.ts+++ b/packages/cli/src/commands/uninstall.ts@@ -348,7 +348,7 @@ export async function runUninstall(opts: UninstallOptions = {}): Promise<Uninstaconst detectInstall = opts.deps?.detectInstallMethods ?? detectInstallMethods;const lockDirs = await discoverLocks();- const marker = readPathInstallMarker(home);+ const marker = readPathInstallMarker(home, undefined, platform, env);const recentDeinitProjectRoots = await resolveRecents({home,platform,diff --git a/packages/cli/src/integrations/path-shim.test.ts b/packages/cli/src/integrations/path-shim.test.tsindex de0fe42e2..dec16766b 100644--- a/packages/cli/src/integrations/path-shim.test.ts+++ b/packages/cli/src/integrations/path-shim.test.ts@@ -1,6 +1,6 @@import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';-import { join } from 'node:path';+import { dirname, join } from 'node:path';import { pathShimBlockLabel, pathShimFishConfFileName } from '@inkeep/open-knowledge-core';import { afterEach, describe, expect, test, vi } from 'vitest';import {@@ -49,7 +49,7 @@ describe('readPathInstallMarker', () => {test('reads a valid v1 marker', () => {const home = mkdtempSync(join(tmpdir(), 'ok-marker-'));try {- const markerPath = pathInstallMarkerPath(home);+ const markerPath = pathInstallMarkerPath(home, 'darwin', {});const dir = markerPath.slice(0, markerPath.lastIndexOf('/'));mkdirSync(dir, { recursive: true });writeFileSync(@@ -67,7 +67,7 @@ describe('readPathInstallMarker', () => {extraSymlinks: [],}),);- const marker = readPathInstallMarker(home);+ const marker = readPathInstallMarker(home, undefined, 'darwin', {});expect(marker?.version).toBe(1);expect(marker?.rcFiles).toEqual([join(home, '.zshrc')]);} finally {@@ -78,14 +78,14 @@ describe('readPathInstallMarker', () => {test('returns null for an absent, malformed, or wrong-version marker', () => {const home = mkdtempSync(join(tmpdir(), 'ok-marker-'));try {- expect(readPathInstallMarker(home)).toBeNull();- const markerPath = pathInstallMarkerPath(home);+ expect(readPathInstallMarker(home, undefined, 'darwin', {})).toBeNull();+ const markerPath = pathInstallMarkerPath(home, 'darwin', {});const dir = markerPath.slice(0, markerPath.lastIndexOf('/'));mkdirSync(dir, { recursive: true });writeFileSync(markerPath, 'not json');- expect(readPathInstallMarker(home)).toBeNull();+ expect(readPathInstallMarker(home, undefined, 'darwin', {})).toBeNull();writeFileSync(markerPath, JSON.stringify({ version: 2 }));- expect(readPathInstallMarker(home)).toBeNull();+ expect(readPathInstallMarker(home, undefined, 'darwin', {})).toBeNull();} finally {rmSync(home, { recursive: true, force: true });}@@ -121,7 +121,7 @@ describe('path shim per channel', () => {test('Stable keeps its Application Support marker and strips only the Stable block', () => {vi.stubEnv('OK_CHANNEL', 'stable');- expect(pathInstallMarkerPath('/home/me')).toBe(+ expect(pathInstallMarkerPath('/home/me', 'darwin')).toBe(join('/home/me', 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json'),);const { text } = stripManagedPathBlock(`${block()}${BETA_BLOCK}`);@@ -130,7 +130,7 @@ describe('path shim per channel', () => {test('Beta reads its marker under ~/.ok-beta and strips only the Beta block', () => {vi.stubEnv('OK_CHANNEL', 'beta');- expect(pathInstallMarkerPath('/home/me')).toBe(+ expect(pathInstallMarkerPath('/home/me', 'darwin')).toBe(join('/home/me', '.ok-beta', 'path-install.json'),);const { text, changed } = stripManagedPathBlock(`${block()}${BETA_BLOCK}`);@@ -153,3 +153,49 @@ describe('path shim per channel', () => {expect(pathShimFishConfName()).toBe('open-knowledge.fish');});});++describe('Linux uninstall marker discovery', () => {+ test.each(['current', 'legacy'])(+ 'reads the %s marker without Desktop starting first',+ (location) => {+ const home = mkdtempSync(join(tmpdir(), 'ok-linux-marker-read-'));+ try {+ const env = { XDG_CONFIG_HOME: join(home, 'settings') };+ const path =+ location === 'current'+ ? pathInstallMarkerPath(home, 'linux', env)+ : join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json');+ const marker = { version: 1, rcFiles: [join(home, 'custom.rc')], extraSymlinks: [] };+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, JSON.stringify(marker));+ expect(readPathInstallMarker(home, undefined, 'linux', env)).toEqual(marker);+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ },+ );++ test('prefers the current marker over legacy state, including a current unknown version', () => {+ const home = mkdtempSync(join(tmpdir(), 'ok-linux-marker-priority-'));+ try {+ const env = { XDG_CONFIG_HOME: join(home, 'settings') };+ const current = pathInstallMarkerPath(home, 'linux', env);+ const legacy = join(+ home,+ 'Library',+ 'Application Support',+ 'OpenKnowledge',+ 'path-install.json',+ );+ mkdirSync(dirname(current), { recursive: true });+ mkdirSync(dirname(legacy), { recursive: true });+ writeFileSync(legacy, JSON.stringify({ version: 1, rcFiles: ['legacy'] }));+ writeFileSync(current, JSON.stringify({ version: 1, rcFiles: ['current'] }));+ expect(readPathInstallMarker(home, undefined, 'linux', env)?.rcFiles).toEqual(['current']);+ writeFileSync(current, JSON.stringify({ version: 2 }));+ expect(readPathInstallMarker(home, undefined, 'linux', env)).toBeNull();+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/packages/cli/src/integrations/path-shim.ts b/packages/cli/src/integrations/path-shim.tsindex 7e2544567..a6472f67d 100644--- a/packages/cli/src/integrations/path-shim.ts+++ b/packages/cli/src/integrations/path-shim.ts@@ -47,8 +47,12 @@ export interface PathInstallMarker {consent?: PathInstallConsent;}-export function pathInstallMarkerPath(home: string): string {- return pathShimMarkerPath(resolveDesktopProductName(), home);+export function pathInstallMarkerPath(+ home: string,+ platform: string = process.platform,+ env: Record<string, string | undefined> = process.env,+): string {+ return pathShimMarkerPath(resolveDesktopProductName(), home, platform, env.XDG_CONFIG_HOME);}export function pathShimFishConfName(): string {@@ -79,9 +83,18 @@ const defaultFsOps: PathShimFsOps = {export function readPathInstallMarker(home: string,fs: PathShimFsOps = defaultFsOps,+ platform: string = process.platform,+ env: Record<string, string | undefined> = process.env,): PathInstallMarker | null {- const path = pathInstallMarkerPath(home);- if (!fs.existsSync(path)) return null;+ const channel = resolveDesktopProductName();+ const current = pathInstallMarkerPath(home, platform, env);+ const legacy = pathShimMarkerPath(channel, home);+ const path = fs.existsSync(current)+ ? current+ : channel === 'stable' && platform === 'linux' && fs.existsSync(legacy)+ ? legacy+ : null;+ if (path === null) return null;try {const parsed = JSON.parse(fs.readFileSync(path, 'utf8')) as PathInstallMarker;return parsed?.version === 1 ? parsed : null;diff --git a/packages/core/src/constants/path-shim-layout.test.ts b/packages/core/src/constants/path-shim-layout.test.tsindex c486e98aa..dc16d6ad6 100644--- a/packages/core/src/constants/path-shim-layout.test.ts+++ b/packages/core/src/constants/path-shim-layout.test.ts@@ -26,3 +26,28 @@ describe('path shim layout', () => {expect(pathShimFishConfFileName('beta')).toBe('open-knowledge-beta.fish');});});++describe('Stable Linux marker layout', () => {+ test.each([+ [undefined, '/home/a/.config/OpenKnowledge/path-install.json'],+ ['', '/home/a/.config/OpenKnowledge/path-install.json'],+ ['relative', '/home/a/.config/OpenKnowledge/path-install.json'],+ ['../relative', '/home/a/.config/OpenKnowledge/path-install.json'],+ ['/settings', '/settings/OpenKnowledge/path-install.json'],+ ['/settings/', '/settings/OpenKnowledge/path-install.json'],+ ])('uses the Linux config directory for XDG_CONFIG_HOME=%s', (xdg, expected) => {+ expect(pathShimMarkerPath('stable', '/home/a', 'linux', xdg)).toBe(expected);+ });++ test('leaves macOS and isolated channels unchanged', () => {+ expect(pathShimMarkerPath('stable', '/Users/a', 'darwin', '/settings')).toBe(+ '/Users/a/Library/Application Support/OpenKnowledge/path-install.json',+ );+ expect(pathShimMarkerPath('beta', '/home/a', 'linux', '/settings')).toBe(+ '/home/a/.ok-beta/path-install.json',+ );+ expect(pathShimMarkerPath('dev', '/home/a', 'linux', '/settings')).toBe(+ '/home/a/.ok-dev/path-install.json',+ );+ });+});diff --git a/packages/core/src/constants/path-shim-layout.ts b/packages/core/src/constants/path-shim-layout.tsindex c97b64067..f4b927a69 100644--- a/packages/core/src/constants/path-shim-layout.ts+++ b/packages/core/src/constants/path-shim-layout.ts@@ -13,8 +13,19 @@ export function pathShimBinDir(channel: DesktopProductName, home: string): strinreturn posixOkManagedBinDir(home, pathShimHomeDirName(channel));}-export function pathShimMarkerPath(channel: DesktopProductName, home: string): string {+export function pathShimMarkerPath(+ channel: DesktopProductName,+ home: string,+ platform = 'darwin',+ xdgConfigHome?: string,+): string {if (channel === 'stable') {+ if (platform === 'linux') {+ const configHome = xdgConfigHome?.startsWith('/')+ ? xdgConfigHome+ : `${posixHome(home)}/.config`;+ return `${posixHome(configHome)}/OpenKnowledge/path-install.json`;+ }return `${posixHome(home)}/Library/Application Support/OpenKnowledge/path-install.json`;}return `${posixHome(home)}/${pathShimHomeDirName(channel)}/path-install.json`;diff --git a/packages/desktop/src/main/path-install-beta.test.ts b/packages/desktop/src/main/path-install-beta.test.tsindex 5ae99ffc7..483b31b78 100644--- a/packages/desktop/src/main/path-install-beta.test.ts+++ b/packages/desktop/src/main/path-install-beta.test.ts@@ -141,6 +141,8 @@ type FsOps = NonNullable<Parameters<typeof ensureCliOnPath>[0]['fs']>;function fsWith(overrides: Partial<FsOps>): FsOps {return {+ copyFileSync: (source, destination, flags) => nodeFs.copyFileSync(source, destination, flags),+ rmdirSync: (path) => nodeFs.rmdirSync(path),existsSync: (path) => nodeFs.existsSync(path),readFileSync: (path, encoding) => nodeFs.readFileSync(path, encoding),writeFileSync: (path, content) => nodeFs.writeFileSync(path, content),diff --git a/packages/desktop/src/main/path-install-linux.test.ts b/packages/desktop/src/main/path-install-linux.test.tsnew file mode 100644index 000000000..d93bf0bf8--- /dev/null+++ b/packages/desktop/src/main/path-install-linux.test.ts@@ -0,0 +1,168 @@+import * as fs from 'node:fs';+import { dirname, join } from 'node:path';+import { afterAll, describe, expect, test } from 'vitest';+import { createTempDirFactory } from '../../../../test-support/temp-dir.test-helper.ts';+import {+ computePathInstallDescriptor,+ ensureCliOnPath,+ isPathShimInstalled,+ pathInstallMarkerPath,+ removePathShimFromRcFiles,+} from './path-install.ts';++const makeTempDir = createTempDirFactory(afterAll);+const DECLINED = { status: 'declined', at: '2026-07-02T00:00:00.000Z' } as const;+const GRANTED = { status: 'granted', at: '2026-07-02T00:00:00.000Z' } as const;+type Options = Parameters<typeof ensureCliOnPath>[0];++function linuxOptions(home: string, xdg?: string): Options {+ return {+ executablePath: '/opt/OpenKnowledge/openknowledge',+ isPackaged: true,+ platform: 'linux',+ home,+ bundleVersion: '0.5.0-test',+ env: { HOME: home, SHELL: '/bin/bash', XDG_CONFIG_HOME: xdg },+ spawn: async () => ({ code: 0, stdout: '/usr/bin:/bin', stderr: '' }),+ logger: { event: () => {} },+ };+}++async function seedLegacy(home: string) {+ const options = linuxOptions(home);+ expect((await ensureCliOnPath(options)).status).toBe('installed-silent');+ const current = join(home, '.config', 'OpenKnowledge', 'path-install.json');+ const legacy = join(home, 'Library', 'Application Support', 'OpenKnowledge', 'path-install.json');+ const marker = {+ ...JSON.parse(fs.readFileSync(current, 'utf8')),+ consent: DECLINED,+ rcOptOuts: [join(home, '.bashrc')],+ futureField: 'preserved',+ };+ const bytes = `${JSON.stringify(marker, null, 2)}\n`;+ fs.writeFileSync(current, bytes);+ fs.mkdirSync(dirname(legacy), { recursive: true });+ fs.renameSync(current, legacy);+ return { options, current, legacy, marker, bytes };+}++describe('Stable Linux PATH markers', () => {+ test.each(['unset', 'empty', 'custom'])(+ 'stores the marker under XDG with %s configuration',+ async (mode) => {+ const home = makeTempDir('ok-linux-marker-');+ const xdg = mode === 'custom' ? join(home, 'settings') : mode === 'empty' ? '' : undefined;+ const options = linuxOptions(home, xdg);+ const expected = join(xdg || join(home, '.config'), 'OpenKnowledge', 'path-install.json');+ expect(pathInstallMarkerPath(home, 'linux', options.env)).toBe(expected);+ expect((await ensureCliOnPath(options)).status).toBe('installed-silent');+ expect(JSON.parse(fs.readFileSync(expected, 'utf8')).version).toBe(1);+ expect(fs.existsSync(join(home, 'Library'))).toBe(false);+ expect((await ensureCliOnPath(options)).status).toBe('healthy-current');+ },+ );++ test('migrates legacy bytes once without changing consent, opt-outs or unknown fields', async () => {+ const home = makeTempDir('ok-linux-migrate-');+ const { options, current, legacy, bytes } = await seedLegacy(home);+ expect((await ensureCliOnPath(options)).status).toBe('healthy-current');+ expect(fs.readFileSync(current, 'utf8')).toBe(bytes);+ expect(fs.existsSync(legacy)).toBe(false);+ expect(fs.existsSync(join(home, 'Library'))).toBe(false);+ expect(fs.existsSync(join(home, '.bashrc'))).toBe(false);+ expect((await ensureCliOnPath(options)).status).toBe('healthy-current');+ expect(fs.readFileSync(current, 'utf8')).toBe(bytes);+ });++ test('keeps nonempty legacy directories and their unrelated files', async () => {+ const home = makeTempDir('ok-linux-preserve-');+ const { options, current, legacy, bytes } = await seedLegacy(home);+ const unrelated = join(dirname(legacy), 'keep.txt');+ fs.writeFileSync(unrelated, 'not managed by OpenKnowledge');+ expect((await ensureCliOnPath(options)).status).toBe('healthy-current');+ expect(fs.readFileSync(current, 'utf8')).toBe(bytes);+ expect(fs.existsSync(legacy)).toBe(false);+ expect(fs.readFileSync(unrelated, 'utf8')).toBe('not managed by OpenKnowledge');+ });++ test('does not overwrite an existing current marker', async () => {+ const home = makeTempDir('ok-linux-current-');+ const { options, current, legacy, marker, bytes } = await seedLegacy(home);+ const currentBytes = JSON.stringify({ ...marker, futureField: 'current-wins' });+ fs.writeFileSync(current, currentBytes);+ expect((await ensureCliOnPath(options)).status).toBe('healthy-current');+ expect(fs.readFileSync(current, 'utf8')).toBe(currentBytes);+ expect(fs.readFileSync(legacy, 'utf8')).toBe(bytes);+ });++ test('does not overwrite a current marker created between lookup and copy', async () => {+ const home = makeTempDir('ok-linux-race-');+ const { options, current, legacy, marker, bytes } = await seedLegacy(home);+ const currentBytes = JSON.stringify({ ...marker, futureField: 'other-writer' });+ const result = await ensureCliOnPath({+ ...options,+ fs: {+ ...fs,+ copyFileSync: (source, destination, flags) => {+ fs.writeFileSync(destination, currentBytes);+ fs.copyFileSync(source, destination, flags);+ },+ },+ });+ expect(result.status).toBe('healthy-current');+ expect(fs.readFileSync(current, 'utf8')).toBe(currentBytes);+ expect(fs.readFileSync(legacy, 'utf8')).toBe(bytes);+ });++ test('continues with the migrated marker when legacy cleanup is denied', async () => {+ const home = makeTempDir('ok-linux-unlink-denied-');+ const { options, current, legacy, bytes } = await seedLegacy(home);+ const events: unknown[] = [];+ let unlinkAttempts = 0;+ const opts = {+ ...options,+ fs: {+ ...fs,+ unlinkSync: (path: string) => {+ if (path === legacy) {+ unlinkAttempts += 1;+ throw Object.assign(new Error('legacy cleanup denied'), { code: 'EACCES' });+ }+ fs.unlinkSync(path);+ },+ },+ logger: { event: (event: unknown) => events.push(event) },+ };+ expect((await ensureCliOnPath(opts)).status).toBe('healthy-current');+ expect(fs.readFileSync(current, 'utf8')).toBe(bytes);+ expect(fs.readFileSync(legacy, 'utf8')).toBe(bytes);+ expect(events).toContainEqual(+ expect.objectContaining({ event: 'path-install-legacy-marker-retained', path: legacy }),+ );+ expect((await ensureCliOnPath(opts)).status).toBe('healthy-current');+ expect(unlinkAttempts).toBe(1);+ });++ test('retains the legacy marker when the destination cannot be created', async () => {+ const home = makeTempDir('ok-linux-migrate-fail-');+ const { options, current, legacy, bytes } = await seedLegacy(home);+ fs.rmdirSync(dirname(current));+ fs.writeFileSync(dirname(current), 'existing file');+ expect((await ensureCliOnPath(options)).status).toBe('failed-all');+ expect(fs.readFileSync(legacy, 'utf8')).toBe(bytes);+ expect(fs.readFileSync(dirname(current), 'utf8')).toBe('existing file');+ });++ test('Settings reads and updates the same custom-XDG marker as startup', async () => {+ const home = makeTempDir('ok-linux-settings-');+ const options = { ...linuxOptions(home, join(home, 'settings')), consentDecision: GRANTED };+ expect((await ensureCliOnPath(options)).status).toBe('installed');+ expect(computePathInstallDescriptor(options).alreadyInstalled).toBe(true);+ expect(isPathShimInstalled(options)).toBe(true);+ expect(removePathShimFromRcFiles(options).status).toBe('removed');+ expect(isPathShimInstalled(options)).toBe(false);+ const path = pathInstallMarkerPath(home, 'linux', options.env);+ expect(JSON.parse(fs.readFileSync(path, 'utf8')).consent.status).toBe('declined');+ expect(fs.existsSync(join(home, 'Library'))).toBe(false);+ });+});diff --git a/packages/desktop/src/main/path-install.test.ts b/packages/desktop/src/main/path-install.test.tsindex a602c228f..5a9086c45 100644--- a/packages/desktop/src/main/path-install.test.ts+++ b/packages/desktop/src/main/path-install.test.ts@@ -18,7 +18,7 @@ import {type EnsureCliOnPathResult,ensureCliOnPath,isPathShimInstalled,- pathInstallMarkerPath,+ pathInstallMarkerPath as markerPathForPlatform,removePathShimFromRcFiles,} from './path-install.ts';@@ -49,6 +49,10 @@ function baseOpts(h: string, overrides: Partial<EnsureOpts> = {}): EnsureOpts {};}+function pathInstallMarkerPath(h: string): string {+ return markerPathForPlatform(h, 'darwin', {});+}+function readMarkerFile(h: string): Record<string, unknown> {return JSON.parse(readFileSync(pathInstallMarkerPath(h), 'utf8'));}@@ -381,6 +385,8 @@ describe('ensureCliOnPath', () => {'/opt/OpenKnowledge/resources/cli/bin/ok.sh',);expect(readFileSync(join(h, '.bashrc'), 'utf8')).toContain('.ok/env.sh');+ expect(existsSync(join(h, '.config', 'OpenKnowledge', 'path-install.json'))).toBe(true);+ expect(existsSync(join(h, 'Library'))).toBe(false);});test('returns failed-all instead of throwing when an fs operation fails', async () => {@@ -389,6 +395,8 @@ describe('ensureCliOnPath', () => {const result = await ensureCliOnPath(baseOpts(h, {fs: {+ copyFileSync: () => {},+ rmdirSync: () => {},existsSync: () => false,readFileSync: () => '',writeFileSync: () => {},@@ -443,9 +451,9 @@ describe('ensureCliOnPath', () => {const marker = readMarkerFile(h);expect(marker.rcFiles).toEqual([fishConf, join(h, '.zshrc')]);- expect(removePathShimFromRcFiles({ home: h, env: { SHELL: '/bin/zsh' } }).status).toBe(- 'removed',- );+ expect(+ removePathShimFromRcFiles({ platform: 'darwin', home: h, env: { SHELL: '/bin/zsh' } }).status,+ ).toBe('removed');expect(existsSync(fishConf)).toBe(false);});@@ -565,9 +573,9 @@ describe('computePathInstallDescriptor', () => {expect(readFileSync(fishConf, 'utf8')).toBe(legacyBlock);expect(readMarkerFile(h).rcFiles as string[]).not.toContain(fishConf);- expect(removePathShimFromRcFiles({ home: h, env: { SHELL: '/bin/zsh' } }).status).toBe(- 'removed',- );+ expect(+ removePathShimFromRcFiles({ platform: 'darwin', home: h, env: { SHELL: '/bin/zsh' } }).status,+ ).toBe('removed');expect(existsSync(fishConf)).toBe(false);});@@ -652,9 +660,9 @@ describe('isPathShimInstalled / removePathShimFromRcFiles — the Settings → AwriteFileSync(join(h, '.config', 'fish', 'config.fish'), '# user fish config\n');await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));const env = { SHELL: '/bin/zsh' };- expect(isPathShimInstalled({ home: h, env })).toBe(true);+ expect(isPathShimInstalled({ platform: 'darwin', home: h, env })).toBe(true);- const result = removePathShimFromRcFiles({ home: h, env });+ const result = removePathShimFromRcFiles({ platform: 'darwin', home: h, env });expect(result.status).toBe('removed');expect(readFileSync(join(h, '.zshrc'), 'utf8')).not.toContain('# >>> open-knowledge cli >>>');expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('export FOO=1');@@ -663,14 +671,18 @@ describe('isPathShimInstalled / removePathShimFromRcFiles — the Settings → Aexpect(marker.rcFiles).toEqual([]);expect((marker.consent as { status: string }).status).toBe('declined');expect(marker.rcOptOuts).toEqual([]);- expect(isPathShimInstalled({ home: h, env })).toBe(false);+ expect(isPathShimInstalled({ platform: 'darwin', home: h, env })).toBe(false);});test('startup after a Settings removal never re-appends; a Settings re-install does', async () => {const h = home();writeFileSync(join(h, '.zshrc'), 'export FOO=1\n');await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));- removePathShimFromRcFiles({ home: h, platform: 'darwin', env: { SHELL: '/bin/zsh' } });+ removePathShimFromRcFiles({+ home: h,+ platform: 'darwin',+ env: { SHELL: '/bin/zsh' },+ });await ensureCliOnPath(baseOpts(h));expect(readFileSync(join(h, '.zshrc'), 'utf8')).not.toContain('# >>> open-knowledge cli >>>');@@ -678,9 +690,13 @@ describe('isPathShimInstalled / removePathShimFromRcFiles — the Settings → Aconst regrant = await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));expect(regrant.status).toBe('installed');expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('# >>> open-knowledge cli >>>');- expect(isPathShimInstalled({ home: h, platform: 'darwin', env: { SHELL: '/bin/zsh' } })).toBe(- true,- );+ expect(+ isPathShimInstalled({+ home: h,+ platform: 'darwin',+ env: { SHELL: '/bin/zsh' },+ }),+ ).toBe(true);});test('re-grant works even when the probe shell inherits a stale PATH containing ~/.ok/bin', async () => {@@ -692,23 +708,35 @@ describe('isPathShimInstalled / removePathShimFromRcFiles — the Settings → Astderr: '',});await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED, spawn: stalePathSpawn }));- removePathShimFromRcFiles({ home: h, platform: 'darwin', env: { SHELL: '/bin/zsh' } });+ removePathShimFromRcFiles({+ home: h,+ platform: 'darwin',+ env: { SHELL: '/bin/zsh' },+ });const regrant = await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED, spawn: stalePathSpawn }),);expect(regrant.status).toBe('installed');expect(readFileSync(join(h, '.zshrc'), 'utf8')).toContain('# >>> open-knowledge cli >>>');- expect(isPathShimInstalled({ home: h, platform: 'darwin', env: { SHELL: '/bin/zsh' } })).toBe(- true,- );+ expect(+ isPathShimInstalled({+ home: h,+ platform: 'darwin',+ env: { SHELL: '/bin/zsh' },+ }),+ ).toBe(true);});test('a wedged granted-but-blockless marker heals on the next explicit grant', async () => {const h = home();writeFileSync(join(h, '.zshrc'), 'export FOO=1\n');await ensureCliOnPath(baseOpts(h, { consentDecision: GRANTED }));- removePathShimFromRcFiles({ home: h, platform: 'darwin', env: { SHELL: '/bin/zsh' } });+ removePathShimFromRcFiles({+ home: h,+ platform: 'darwin',+ env: { SHELL: '/bin/zsh' },+ });const marker = readMarkerFile(h);writeFileSync(pathInstallMarkerPath(h),diff --git a/packages/desktop/src/main/path-install.ts b/packages/desktop/src/main/path-install.tsindex 470949e2f..0bf243e39 100644--- a/packages/desktop/src/main/path-install.ts+++ b/packages/desktop/src/main/path-install.ts@@ -1,11 +1,14 @@import { spawn as nodeSpawn } from 'node:child_process';import {+ constants as fsConstants,+ copyFileSync as fsCopyFileSync,existsSync as fsExistsSync,lstatSync as fsLstatSync,mkdirSync as fsMkdirSync,readFileSync as fsReadFileSync,readlinkSync as fsReadlinkSync,renameSync as fsRenameSync,+ rmdirSync as fsRmdirSync,rmSync as fsRmSync,symlinkSync as fsSymlinkSync,unlinkSync as fsUnlinkSync,@@ -44,14 +47,26 @@ const BLOCK_RE = new RegExp('m',);-export function pathInstallMarkerPath(home: string): string {- return pathShimMarkerPath(CHANNEL, home);+export function pathInstallMarkerPath(+ home: string,+ platform: string = process.platform,+ env: Record<string, string | undefined> = process.env,+): string {+ return pathShimMarkerPath(CHANNEL, home, platform, env.XDG_CONFIG_HOME);}-function legacyMarkerPath(home: string, fs: PathInstallFsOps): string | null {- if (LEGACY_CLI_HOME_PREFIX === null) return null;- const path = join(home, LEGACY_CLI_HOME_PREFIX, 'path-install.json');- return fs.existsSync(path) ? path : null;+function legacyMarkerPath(+ home: string,+ fs: PathInstallFsOps,+ platform: string = process.platform,+): string | null {+ const path =+ CHANNEL === 'stable' && platform === 'linux'+ ? pathShimMarkerPath(CHANNEL, home)+ : LEGACY_CLI_HOME_PREFIX === null+ ? null+ : join(home, LEGACY_CLI_HOME_PREFIX, 'path-install.json');+ return path !== null && fs.existsSync(path) ? path : null;}function removeLegacyCliHome(home: string, fs: PathInstallFsOps, logger: PathInstallLogger): void {@@ -70,7 +85,15 @@ function removeLegacyCliHome(home: string, fs: PathInstallFsOps, logger: PathIns}}+interface PathMarkerLocation {+ home: string;+ platform?: string;+ env?: Record<string, string | undefined>;+}+interface PathInstallFsOps {+ copyFileSync(source: string, destination: string, flags: number): void;+ rmdirSync(path: string): void;existsSync(path: string): boolean;readFileSync(path: string, encoding: 'utf8'): string;writeFileSync(path: string, content: string): void;@@ -84,6 +107,8 @@ interface PathInstallFsOps {}const defaultFsOps: PathInstallFsOps = {+ copyFileSync: (source, destination, flags) => fsCopyFileSync(source, destination, flags),+ rmdirSync: (path) => fsRmdirSync(path),existsSync: (path) => fsExistsSync(path),readFileSync: (path, encoding) => fsReadFileSync(path, encoding),writeFileSync: (path, content) => fsWriteFileSync(path, content),@@ -156,12 +181,13 @@ interface EnsureCliOnPathOpts {}function readMarker(- home: string,+ location: PathMarkerLocation,fs: PathInstallFsOps,logger: PathInstallLogger,): PathInstallMarker | null {- const current = pathInstallMarkerPath(home);- const path = fs.existsSync(current) ? current : legacyMarkerPath(home, fs);+ const { home, platform, env } = location;+ const current = pathInstallMarkerPath(home, platform, env);+ const path = fs.existsSync(current) ? current : legacyMarkerPath(home, fs, platform);if (path === null) return null;try {const parsed = JSON.parse(fs.readFileSync(path, 'utf8')) as PathInstallMarker;@@ -187,12 +213,63 @@ function readMarker(}}-function writeMarker(home: string, marker: PathInstallMarker, fs: PathInstallFsOps): void {- const path = pathInstallMarkerPath(home);+function writeMarker(+ location: PathMarkerLocation,+ marker: PathInstallMarker,+ fs: PathInstallFsOps,+): void {+ const path = pathInstallMarkerPath(location.home, location.platform, location.env);fs.mkdirSync(dirname(path), { recursive: true });fs.writeFileSync(path, `${JSON.stringify(marker, null, 2)}\n`);}+function migrateLinuxMarker(+ location: PathMarkerLocation,+ fs: PathInstallFsOps,+ logger: PathInstallLogger,+): void {+ if (CHANNEL !== 'stable' || location.platform !== 'linux') return;+ const { home, platform, env } = location;+ const current = pathInstallMarkerPath(home, platform, env);+ if (fs.existsSync(current)) return;+ const legacy = legacyMarkerPath(home, fs, platform);+ if (legacy === null || readMarker(location, fs, logger) === null) return;+ fs.mkdirSync(dirname(current), { recursive: true });+ try {+ fs.copyFileSync(legacy, current, fsConstants.COPYFILE_EXCL);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return;+ throw error;+ }+ try {+ fs.unlinkSync(legacy);+ } catch (error) {+ logger.event({+ event: 'path-install-legacy-marker-retained',+ path: legacy,+ error: error instanceof Error ? error.message : String(error),+ });+ return;+ }+ for (const directory of [+ join(home, 'Library', 'Application Support', 'OpenKnowledge'),+ join(home, 'Library', 'Application Support'),+ join(home, 'Library'),+ ]) {+ try {+ fs.rmdirSync(directory);+ } catch (error) {+ logger.event({+ event: 'path-install-legacy-marker-directory-retained',+ path: directory,+ error: error instanceof Error ? error.message : String(error),+ });+ break;+ }+ }+ logger.event({ event: 'path-install-marker-migrated' });+}+function okBin(home: string): string {return pathShimBinDir(CHANNEL, home);}@@ -479,8 +556,16 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensureif (shape.kind === 'unsupported') return { status: 'skipped', reason: 'bad-executable-path' };const wrapper = shape.wrapperPath;- const prior = readMarker(home, fs, logger);- const priorIsLegacy = prior !== null && !fs.existsSync(pathInstallMarkerPath(home));+ try {+ migrateLinuxMarker(opts, fs, logger);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ logger.event({ event: 'path-install-marker-migration-failed', error: message });+ return { status: 'failed-all', error: message };+ }+ const prior = readMarker(opts, fs, logger);+ const priorIsLegacy =+ prior !== null && !fs.existsSync(pathInstallMarkerPath(home, platform, opts.env));const explicitDecision = opts.consentDecision !== undefined;if (prior &&@@ -494,7 +579,7 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<Ensureconsent: { status: 'granted', at: (opts.now?.() ?? new Date()).toISOString() },};try {- writeMarker(home, marker, fs);+ writeMarker(opts, marker, fs);} catch (err) {logger.event({event: 'path-install-consent-stamp-failed',@@ -595,7 +680,7 @@ export async function ensureCliOnPath(opts: EnsureCliOnPathOpts): Promise<EnsureextraSymlinks: cleanup.remaining,...(consent ? { consent } : {}),};- writeMarker(home, marker, fs);+ writeMarker(opts, marker, fs);removeLegacyCliHome(home, fs, logger);if (consent && consent.status !== prior?.consent?.status) {logger.event({@@ -641,7 +726,7 @@ export function computePathInstallDescriptor(opts: {logger?: PathInstallLogger;}): McpWiringPathInstallDescriptor {const { home, fs = defaultFsOps, logger = DEFAULT_LOGGER } = opts;- const marker = readMarker(home, fs, logger);+ const marker = readMarker(opts, fs, logger);const rcOptOuts = marker?.rcOptOuts ?? [];const targets = rcTargets(home, (opts.env ?? process.env).SHELL, fs, opts.platform).filter((target) => !rcOptOuts.includes(target.path),@@ -666,7 +751,7 @@ export function isPathShimInstalled(opts: {logger?: PathInstallLogger;}): boolean {const { home, fs = defaultFsOps, logger = DEFAULT_LOGGER } = opts;- const marker = readMarker(home, fs, logger);+ const marker = readMarker(opts, fs, logger);const candidates = new Set<string>([...rcTargets(home, (opts.env ?? process.env).SHELL, fs, opts.platform).map((target) => target.path,@@ -690,7 +775,7 @@ export function removePathShimFromRcFiles(opts: {now?: () => Date;}): RemovePathShimResult {const { home, fs = defaultFsOps, logger = DEFAULT_LOGGER } = opts;- const marker = readMarker(home, fs, logger);+ const marker = readMarker(opts, fs, logger);const okOwnedFishConf = join(home, '.config', 'fish', 'conf.d', FISH_CONF_NAME);const candidates = new Set<string>([...rcTargets(home, (opts.env ?? process.env).SHELL, fs, opts.platform).map(@@ -718,7 +803,7 @@ export function removePathShimFromRcFiles(opts: {const consentAlreadyDeclined = marker?.consent?.status === 'declined';if (marker && (strippedFiles.length > 0 || !consentAlreadyDeclined)) {writeMarker(- home,+ opts,{...marker,rcFiles: [],