Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Add packaged macOS desktop uninstall flow (#2517)

mike-inkeepd33922fc282a
diff --git a/.changeset/deinit-projection-symlinks.md b/.changeset/deinit-projection-symlinks.md
new file mode 100644
index 000000000..783d4aa40
--- /dev/null
+++ b/.changeset/deinit-projection-symlinks.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+`ok deinit` (and the per-project sweep in `ok uninstall`) now removes OK-installed skill projection symlinks (pack and authored skills under `.claude/skills/`, `.cursor/skills/`, etc.) instead of refusing them with "Refusing to write through a symbolic link" — removal unlinks the link itself and never touches its target. Dangling projection symlinks are cleaned up too; the refusal for symlinked ancestors that escape the project is unchanged.
diff --git a/.changeset/desktop-self-uninstall.md b/.changeset/desktop-self-uninstall.md
new file mode 100644
index 000000000..6add38f51
--- /dev/null
+++ b/.changeset/desktop-self-uninstall.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge-desktop": patch
+---
+
+Add a packaged macOS menu flow to uninstall OpenKnowledge, with a per-project picker for optionally deinitializing recent/open/running projects before removing the global footprint. After cleanup — including when cleanup reports failures, in which case the error dialog embeds the cleanup log inline — a final dialog walks the user through the one remaining manual step, then reveals OpenKnowledge.app in Finder so it can be dragged to the Trash and quits.
diff --git a/packages/cli/src/commands/removal-plan.test.ts b/packages/cli/src/commands/removal-plan.test.ts
index 1fd4a49e2..909bbc55a 100644
--- a/packages/cli/src/commands/removal-plan.test.ts
+++ b/packages/cli/src/commands/removal-plan.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from 'bun:test';
import {
chmodSync,
existsSync,
+ lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
@@ -253,6 +254,93 @@ describe('runRemoval — project path containment guard', () => {
rmSync(home, { recursive: true, force: true });
}
});
+
+ // OK installs pack/authored skill projections AS symlinks
+ // (`.claude/skills/<name> -> ../../.ok/skills/<name>`); deinit must remove
+ // the link itself, not refuse it as a write-through hazard.
+ test('removes an OK skill-projection symlink, leaving the link target intact', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-projlink-'));
+ try {
+ const projectRoot = join(home, 'proj');
+ write(join(projectRoot, '.ok', 'skills', 'pack-kb', 'SKILL.md'), '# pack\n');
+ mkdirSync(join(projectRoot, '.claude', 'skills'), { recursive: true });
+ symlinkSync(
+ join('..', '..', '.ok', 'skills', 'pack-kb'),
+ join(projectRoot, '.claude', 'skills', 'pack-kb'),
+ );
+
+ const op = {
+ kind: 'remove-path' as const,
+ group: 'test',
+ label: 'Remove .claude/skills/pack-kb/',
+ path: join(projectRoot, '.claude', 'skills', 'pack-kb'),
+ containWithin: projectRoot,
+ };
+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());
+ expect(outcome.failed).toHaveLength(0);
+ expect(outcome.removed).toHaveLength(1);
+ expect(
+ lstatSync(join(projectRoot, '.claude', 'skills', 'pack-kb'), { throwIfNoEntry: false }),
+ ).toBeUndefined();
+ // The projection source behind the link is untouched.
+ expect(existsSync(join(projectRoot, '.ok', 'skills', 'pack-kb', 'SKILL.md'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('removes a DANGLING projection symlink instead of reporting not-present', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-danglink-'));
+ try {
+ const projectRoot = join(home, 'proj');
+ mkdirSync(join(projectRoot, '.claude', 'skills'), { recursive: true });
+ symlinkSync(
+ join('..', '..', '.ok', 'skills', 'already-swept'),
+ join(projectRoot, '.claude', 'skills', 'already-swept'),
+ );
+
+ const op = {
+ kind: 'remove-path' as const,
+ group: 'test',
+ label: 'Remove .claude/skills/already-swept/',
+ path: join(projectRoot, '.claude', 'skills', 'already-swept'),
+ containWithin: projectRoot,
+ };
+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());
+ expect(outcome.removed).toHaveLength(1);
+ expect(
+ lstatSync(join(projectRoot, '.claude', 'skills', 'already-swept'), {
+ throwIfNoEntry: false,
+ }),
+ ).toBeUndefined();
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('a leaf symlink pointing outside the project is unlinked; its target survives', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'ok-leafout-'));
+ try {
+ const projectRoot = join(home, 'proj');
+ const outside = join(home, 'outside-secret');
+ write(join(outside, 'keep.txt'), 'do not delete');
+ mkdirSync(join(projectRoot, '.claude', 'skills'), { recursive: true });
+ symlinkSync(outside, join(projectRoot, '.claude', 'skills', 'planted'));
+
+ const op = {
+ kind: 'remove-path' as const,
+ group: 'test',
+ label: 'Remove .claude/skills/planted/',
+ path: join(projectRoot, '.claude', 'skills', 'planted'),
+ containWithin: projectRoot,
+ };
+ const outcome = await runRemoval({ scope: 'deinit', ops: [op] }, stubDeps());
+ expect(outcome.removed).toHaveLength(1);
+ expect(existsSync(join(outside, 'keep.txt'))).toBe(true);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
});
describe('runRemoval — uninstall end to end', () => {
diff --git a/packages/cli/src/commands/removal-plan.ts b/packages/cli/src/commands/removal-plan.ts
index 0bde0cfd5..691f6d2dd 100644
--- a/packages/cli/src/commands/removal-plan.ts
+++ b/packages/cli/src/commands/removal-plan.ts
@@ -16,7 +16,7 @@
* `~/.ok/logs`) survives until the end.
*/
-import { existsSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';
+import { existsSync, lstatSync, readdirSync, readFileSync, rmSync, unlinkSync } from 'node:fs';
import { basename, join, relative, sep } from 'node:path';
import { atomicWriteFileSync } from '@inkeep/open-knowledge-core/server';
// `resolveShadowDir` (resolves `<gitdir>/ok/`, worktree-aware; throws on a
@@ -39,7 +39,7 @@ import {
stripManagedPathBlock,
} from '../integrations/path-shim.ts';
import { userGlobalSkillBundleTargets } from '../integrations/skill-teardown.ts';
-import { assertProjectPathSafe } from '../integrations/write-project-skill.ts';
+import { assertProjectRemovalSafe } from '../integrations/write-project-skill.ts';
import {
getExcludedOkPaths,
getOkArtifactPaths,
@@ -93,11 +93,13 @@ export type RemovalOp =
requireOurState?: boolean;
/**
* Assert `path` is contained within this project root before removing
- * (via `assertProjectPathSafe`) — set for project-scoped removals so a
- * planted symlink (a `.claude -> /etc` in a cloned repo) or a poisoned
- * skill name in `installed-skills.json` can't route the `rmSync` outside
- * the project. Unset for out-of-project targets (`~/.ok`, `~/Library`,
- * the shadow repo — which legitimately lives outside a linked worktree).
+ * (via `assertProjectRemovalSafe`) — set for project-scoped removals so
+ * a planted ancestor symlink (a `.claude -> /etc` in a cloned repo) or a
+ * poisoned skill name in `installed-skills.json` can't route the `rmSync`
+ * outside the project. A symlink at `path` itself is fine (OK's skill
+ * projections are symlinks; removal unlinks the link, not its target).
+ * Unset for out-of-project targets (`~/.ok`, `~/Library`, the shadow
+ * repo — which legitimately lives outside a linked worktree).
*/
containWithin?: string;
};
@@ -626,13 +628,29 @@ function executeRemovePath(op: Extract<RemovalOp, { kind: 'remove-path' }>): Rem
if (op.requireOurState && !stateDirIsOurs(op.path)) {
return { op, status: 'skipped', detail: 'not verified as OpenKnowledge — left untouched' };
}
- // For project-scoped removals, refuse to rmSync through a symlink that escapes
- // the project (a planted `.claude -> /etc`, or a poisoned skill name). Throws
- // on escape → caught by the per-op try/catch as `failed` (the safe direction).
+ // For project-scoped removals, refuse to rmSync through a symlinked ANCESTOR
+ // that escapes the project (a planted `.claude -> /etc`). Throws on escape →
+ // caught by the per-op try/catch as `failed` (the safe direction). A symlink
+ // AT the path is allowed: OK installs skill projections as symlinks, and
+ // removal unlinks the link itself without touching its target.
if (op.containWithin) {
- assertProjectPathSafe(op.path, op.containWithin);
+ assertProjectRemovalSafe(op.path, op.containWithin);
+ }
+ // lstat, not existsSync: existsSync follows the leaf, so a DANGLING
+ // projection symlink (target already swept) would read as absent and the
+ // orphan link would be left behind.
+ let leafStat: ReturnType<typeof lstatSync> | undefined;
+ try {
+ leafStat = lstatSync(op.path);
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
+ }
+ if (!leafStat) return { op, status: 'not-present' };
+
+ if (leafStat.isSymbolicLink()) {
+ unlinkSync(op.path);
+ return { op, status: 'removed' };
}
- if (!existsSync(op.path)) return { op, status: 'not-present' };
if (op.preserve && op.preserve.length > 0) {
// Remove every child EXCEPT the preserved names, leaving the dir itself
diff --git a/packages/cli/src/integrations/remove-project-skill.test.ts b/packages/cli/src/integrations/remove-project-skill.test.ts
index 8740bba64..83b38dd99 100644
--- a/packages/cli/src/integrations/remove-project-skill.test.ts
+++ b/packages/cli/src/integrations/remove-project-skill.test.ts
@@ -81,6 +81,25 @@ describe('removeProjectSkill', () => {
}
});
+ test('removes a skill dir that is itself a symlink, leaving the link target intact', () => {
+ // A projection-style install: the managed dir is a symlink into `.ok/skills`.
+ const skillPath = CLAUDE.projectSkillPath?.(dir);
+ if (!skillPath) throw new Error('claude has no projectSkillPath');
+ const skillDir = dirname(skillPath);
+ const source = join(dir, '.ok', 'skills', 'open-knowledge');
+ mkdirSync(source, { recursive: true });
+ writeFileSync(join(source, 'SKILL.md'), '# open-knowledge\n');
+ mkdirSync(dirname(skillDir), { recursive: true });
+ symlinkSync(source, skillDir, 'dir');
+
+ const result = removeProjectSkill(CLAUDE, dir);
+
+ expect(result.action).toBe('removed');
+ expect(existsSync(skillDir)).toBe(false);
+ // Only the link was removed; the projection source survives.
+ expect(existsSync(join(source, 'SKILL.md'))).toBe(true);
+ });
+
test('reports skipped-unsupported for an editor with no project skill path', () => {
const noSkill = EDITOR_TARGETS['claude-desktop'];
expect(noSkill.projectSkillPath).toBeUndefined();
diff --git a/packages/cli/src/integrations/write-project-skill.ts b/packages/cli/src/integrations/write-project-skill.ts
index 82113eef5..cc498bfe3 100644
--- a/packages/cli/src/integrations/write-project-skill.ts
+++ b/packages/cli/src/integrations/write-project-skill.ts
@@ -38,13 +38,6 @@ import type { EditorId, EditorMcpTarget } from '../commands/editors.ts';
* with `~/.cursor/mcp.json` (and friends) symlinked to a managed location.
*/
export function assertProjectPathSafe(targetPath: string, cwd: string): void {
- let realCwd: string;
- try {
- realCwd = realpathSync(cwd);
- } catch {
- realCwd = resolve(cwd);
- }
-
let leafStat: ReturnType<typeof lstatSync> | undefined;
try {
leafStat = lstatSync(targetPath);
@@ -58,6 +51,30 @@ export function assertProjectPathSafe(targetPath: string, cwd: string): void {
);
}
+ assertProjectAncestorsContained(targetPath, cwd);
+}
+
+/**
+ * The removal-side counterpart of `assertProjectPathSafe`. A symlink AT the
+ * target path is fine here — removal unlinks the link itself and never touches
+ * what it points to, and OK's own skill projections are installed as symlinks
+ * (see `projectSkill` in `@inkeep/open-knowledge-server`), so refusing leaf
+ * symlinks would strand OK's own footprint on `ok deinit`. The ancestor check
+ * still applies: a symlinked parent (`.claude -> /etc`) would route a recursive
+ * removal outside the project tree.
+ */
+export function assertProjectRemovalSafe(targetPath: string, cwd: string): void {
+ assertProjectAncestorsContained(targetPath, cwd);
+}
+
+function assertProjectAncestorsContained(targetPath: string, cwd: string): void {
+ let realCwd: string;
+ try {
+ realCwd = realpathSync(cwd);
+ } catch {
+ realCwd = resolve(cwd);
+ }
+
let cursor = dirname(targetPath);
while (cursor.length > 1 && cursor !== sep) {
let cursorRealpath: string;
@@ -155,9 +172,10 @@ export interface ProjectSkillRemoveResult {
* whole-directory. The presence of the managed `SKILL.md` at
* `projectSkillPath` is the ownership marker: a directory at the managed path
* WITHOUT it is not something OK authored and is left untouched
- * (`not-present`). The same symlink-escape guard the write path uses runs
- * before the `rmSync`, so a symlinked ancestor (`.claude -> /etc`) can never
- * route the recursive removal outside the project tree.
+ * (`not-present`). The removal-side guard runs before the `rmSync`, so a
+ * symlinked ancestor (`.claude -> /etc`) can never route the recursive
+ * removal outside the project tree — while a symlink AT the path (a skill
+ * projection) is still removable.
*/
export function removeProjectSkill(target: EditorMcpTarget, cwd: string): ProjectSkillRemoveResult {
const skillPath = target.projectSkillPath?.(cwd);
@@ -181,8 +199,9 @@ export function removeProjectSkill(target: EditorMcpTarget, cwd: string): Projec
path: skillPath,
};
}
- // Refuse before `rmSync` runs, exactly as the write path does.
- assertProjectPathSafe(targetDir, cwd);
+ // Refuse escaping ancestors before `rmSync` runs; a leaf symlink is fine
+ // to unlink on the removal side.
+ assertProjectRemovalSafe(targetDir, cwd);
rmSync(targetDir, { recursive: true, force: true });
return {
editorId: target.id,
diff --git a/packages/desktop/src/main/auto-updater.ts b/packages/desktop/src/main/auto-updater.ts
index 7ce00f28b..8562cb7df 100644
--- a/packages/desktop/src/main/auto-updater.ts
+++ b/packages/desktop/src/main/auto-updater.ts
@@ -286,6 +286,12 @@ export interface StartAutoUpdaterHandle {
* so a project opened shortly after an update still shows the card.
*/
getActiveWhatsNew(): { version: string; releaseUrl: string } | null;
+ /**
+ * Uninstall path: prevent a staged update from auto-installing on the quit
+ * that hands control to the detached uninstall helper. Otherwise Squirrel.Mac
+ * can swap/relaunch the bundle while the helper is trying to trash it.
+ */
+ suppressAutoInstallOnQuit(): void;
}
interface Logger {
@@ -1628,6 +1634,10 @@ export function startAutoUpdater(opts: StartAutoUpdaterOpts): StartAutoUpdaterHa
}
return { version: activeWhatsNew.version, releaseUrl: activeWhatsNew.releaseUrl };
},
+ suppressAutoInstallOnQuit(): void {
+ updater.autoInstallOnAppQuit = false;
+ logger.info('autoInstallOnAppQuit suppressed for uninstall');
+ },
destroy(): void {
if (timerHandle) {
clock.clearTimeout(timerHandle);
diff --git a/packages/desktop/src/main/desktop-uninstall.ts b/packages/desktop/src/main/desktop-uninstall.ts
new file mode 100644
index 000000000..e2bd430bb
--- /dev/null
+++ b/packages/desktop/src/main/desktop-uninstall.ts
@@ -0,0 +1,889 @@
+/**
+ * Desktop self-uninstall orchestration.
+ *
+ * The running Electron process must not delete its own `.app` bundle. Instead
+ * main shows the confirmation UI, runs the bundled CLI cleanup while displaying
+ * progress (`ok deinit` for explicitly selected projects, then
+ * `ok uninstall --yes` for the global footprint), and finally reveals
+ * OpenKnowledge.app in Finder so the user can drag it to the Trash.
+ *
+ * Electron-free + dependency-injected so the path predicates and generated
+ * helper script are unit-testable without an Electron runtime.
+ */
+
+import { spawn as spawnChild } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { basename, dirname, join, resolve } from 'node:path';
+
+const APP_BUNDLE_FROM_EXEC_RE = /^(.*\.app)\/Contents\/MacOS\/[^/]+$/;
+const SUPPORTED_APP_BUNDLE_NAME = 'OpenKnowledge.app';
+
+export interface DesktopUninstallProjectCandidate {
+ path: string;
+ open: boolean;
+ recent: boolean;
+ running: boolean;
+}
+
+export interface CollectDesktopUninstallProjectCandidatesInput {
+ recentProjects: ReadonlyArray<{ path: string }>;
+ openProjectPaths: readonly string[];
+ /** Server lock dirs (`<project>/.ok/local`) discovered before the app quits. */
+ lockDirs: readonly string[];
+ exists?: (path: string) => boolean;
+}
+
+export interface DesktopUninstallCleanupInput {
+ cliPath: string;
+ projectPaths: readonly string[];
+ logPath: string;
+}
+
+interface SpawnedCleanupChildLike {
+ once(event: 'error', listener: (err: Error) => void): void;
+ once(
+ event: 'close',
+ listener: (code: number | null, signal: NodeJS.Signals | null) => void,
+ ): void;
+}
+
+interface RunDesktopUninstallCleanupDeps {
+ spawn?: (command: string, args: readonly string[], options: object) => SpawnedCleanupChildLike;
+}
+
+export type RunDesktopUninstallCleanupResult =
+ | { ok: true }
+ | { ok: false; error: string; exitCode?: number | null };
+
+/** Resolve `/Applications/OpenKnowledge.app` from Electron's main execPath. */
+export function resolveAppBundleFromExecPath(
+ execPath: string,
+ platform: NodeJS.Platform = process.platform,
+): string | null {
+ if (platform !== 'darwin') return null;
+ const match = execPath.match(APP_BUNDLE_FROM_EXEC_RE);
+ return match?.[1] ?? null;
+}
+
+/**
+ * True only for the two install locations we are willing to remove from inside
+ * the app: `/Applications/OpenKnowledge.app` and `~/Applications/OpenKnowledge.app`.
+ * This intentionally refuses DMG-mounted, Downloads, dev, and renamed bundles.
+ */
+export function isSupportedApplicationsBundle(
+ bundlePath: string,
+ home: string = homedir(),
+): boolean {
+ const app = resolve(bundlePath);
+ return (
+ app === join('/Applications', SUPPORTED_APP_BUNDLE_NAME) ||
+ app === join(resolve(home), 'Applications', SUPPORTED_APP_BUNDLE_NAME)
+ );
+}
+
+function projectRootFromLockDir(lockDir: string): string {
+ return resolve(lockDir, '..', '..');
+}
+
+function addCandidate(
+ candidates: Map<string, DesktopUninstallProjectCandidate>,
+ path: string,
+ flags: Partial<Pick<DesktopUninstallProjectCandidate, 'open' | 'recent' | 'running'>>,
+): void {
+ const resolved = resolve(path);
+ const existing = candidates.get(resolved);
+ if (existing) {
+ candidates.set(resolved, { ...existing, ...flags });
+ return;
+ }
+ candidates.set(resolved, {
+ path: resolved,
+ open: flags.open ?? false,
+ recent: flags.recent ?? false,
+ running: flags.running ?? false,
+ });
+}
+
+/**
+ * Desktop equivalent of `ok uninstall`'s project-candidate discovery, without
+ * any prompt: open windows first, then recents, then running lock dirs. The
+ * caller decides whether to include these projects; default UX leaves them out.
+ */
+export function collectDesktopUninstallProjectCandidates(
+ input: CollectDesktopUninstallProjectCandidatesInput,
+): DesktopUninstallProjectCandidate[] {
+ const exists = input.exists ?? existsSync;
+ const candidates = new Map<string, DesktopUninstallProjectCandidate>();
+
+ for (const path of input.openProjectPaths) addCandidate(candidates, path, { open: true });
+ for (const row of input.recentProjects) addCandidate(candidates, row.path, { recent: true });
+ for (const lockDir of input.lockDirs) {
+ addCandidate(candidates, projectRootFromLockDir(lockDir), { running: true });
+ }
+
+ return [...candidates.values()].filter((candidate) => exists(join(candidate.path, '.ok')));
+}
+
+function desktopUninstallProjectSourceTags(candidate: DesktopUninstallProjectCandidate): string[] {
+ return [
+ candidate.open ? 'open' : null,
+ candidate.running ? 'running' : null,
+ candidate.recent ? 'recent' : null,
+ ].filter((tag): tag is string => tag !== null);
+}
+
+export function formatDesktopUninstallProjectList(
+ candidates: readonly DesktopUninstallProjectCandidate[],
+ maxRows = 8,
+): string {
+ if (candidates.length === 0) return 'No recent, open, or running OpenKnowledge projects found.';
+
+ const rows = candidates.slice(0, maxRows).map((candidate) => {
+ const tags = desktopUninstallProjectSourceTags(candidate);
+ return `• ${candidate.path}${tags.length > 0 ? ` (${tags.join(', ')})` : ''}`;
+ });
+ if (candidates.length > maxRows) {
+ rows.push(`• …and ${candidates.length - maxRows} more`);
+ }
+ return rows.join('\n');
+}
+
+function htmlEscape(value: string): string {
+ return value.replace(/[&<>"']/g, (ch) => {
+ switch (ch) {
+ case '&':
+ return '&amp;';
+ case '<':
+ return '&lt;';
+ case '>':
+ return '&gt;';
+ case '"':
+ return '&quot;';
+ case "'":
+ return '&#39;';
+ default:
+ return ch;
+ }
+ });
+}
+
+function buildDesktopUninstallProjectRows(
+ candidates: readonly DesktopUninstallProjectCandidate[],
+): string {
+ if (candidates.length === 0) {
+ return '<div class="empty-list">No recent, open, or running OpenKnowledge projects were found.</div>';
+ }
+
+ return candidates
+ .map((candidate, index) => {
+ const name = basename(candidate.path) || candidate.path;
+ const tags = desktopUninstallProjectSourceTags(candidate)
+ .map((tag) => `<span class="tag">${htmlEscape(tag)}</span>`)
+ .join('');
+ return `<label class="project-row">
+ <input type="checkbox" data-index="${index}" aria-label="Remove OpenKnowledge from ${htmlEscape(candidate.path)}" />
+ <span class="project-main">
+ <span class="project-name">${htmlEscape(name)}</span>
+ <span class="project-path">${htmlEscape(candidate.path)}</span>
+ </span>
+ <span class="project-tags" aria-label="Project sources">${tags}</span>
+</label>`;
+ })
+ .join('\n');
+}
+
+const DESKTOP_UNINSTALL_PICKER_SCHEME = 'ok-desktop-uninstall:';
+
+/**
+ * Inline, sandbox-friendly picker HTML. Main owns the candidate paths; the page
+ * returns only selected candidate indexes through a main-intercepted private
+ * navigation URL, not renderer-supplied paths.
+ */
+export function buildDesktopUninstallProjectPickerHtml(
+ candidates: readonly DesktopUninstallProjectCandidate[],
+): string {
+ const projectCount = candidates.length;
+ const projectWord = projectCount === 1 ? 'project' : 'projects';
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:;"
+/>
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Uninstall OpenKnowledge</title>
+<style>
+ :root { color-scheme: light dark; }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; }
+ body {
+ margin: 0;
+ font: 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ color: CanvasText;
+ background: Canvas;
+ }
+ .dialog {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ min-height: 0;
+ }
+ .header {
+ padding: 22px 24px 14px;
+ border-bottom: 1px solid color-mix(in srgb, CanvasText 14%, transparent);
+ }
+ h1 {
+ margin: 0 0 10px;
+ font-size: 20px;
+ font-weight: 650;
+ letter-spacing: -0.01em;
+ }
+ p { margin: 0 0 8px; line-height: 1.42; }
+ .muted { color: color-mix(in srgb, CanvasText 68%, transparent); }
+ .controls {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin-top: 14px;
+ }
+ .controls strong { font-weight: 600; }
+ .control-buttons { display: flex; gap: 8px; flex-wrap: wrap; }
+ button {
+ appearance: none;
+ border: 1px solid color-mix(in srgb, CanvasText 22%, transparent);
+ border-radius: 7px;
+ background: color-mix(in srgb, Canvas 88%, CanvasText 12%);
+ color: CanvasText;
+ padding: 6px 11px;
+ font: inherit;
+ cursor: default;
+ }
+ button:hover { background: color-mix(in srgb, Canvas 82%, CanvasText 18%); }
+ button:focus-visible { outline: 3px solid Highlight; outline-offset: 2px; }
+ .list-region {
+ flex: 1;
+ min-height: 0;
+ padding: 14px 24px;
+ }
+ .scroll-hint {
+ margin: 0 0 8px;
+ color: color-mix(in srgb, CanvasText 62%, transparent);
+ font-size: 13px;
+ }
+ .project-list {
+ height: calc(100% - 24px);
+ min-height: 180px;
+ overflow-y: scroll;
+ scrollbar-gutter: stable;
+ border: 1px solid color-mix(in srgb, CanvasText 16%, transparent);
+ border-radius: 10px;
+ background: color-mix(in srgb, Canvas 96%, CanvasText 4%);
+ }
+ .project-list::-webkit-scrollbar { width: 12px; height: 12px; }
+ .project-list::-webkit-scrollbar-track { background: color-mix(in srgb, Canvas 88%, CanvasText 12%); border-radius: 999px; }
+ .project-list::-webkit-scrollbar-thumb { background: color-mix(in srgb, CanvasText 36%, transparent); border: 3px solid transparent; border-radius: 999px; background-clip: content-box; }
+ .project-row {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ gap: 10px;
+ align-items: start;
+ padding: 10px 12px;
+ border-bottom: 1px solid color-mix(in srgb, CanvasText 10%, transparent);
+ }
+ .project-row:last-child { border-bottom: 0; }
+ .project-row:hover { background: color-mix(in srgb, Highlight 12%, transparent); }
+ .project-row input { margin: 2px 0 0; }
+ .project-main { min-width: 0; }
+ .project-name {
+ display: block;
+ font-weight: 600;
+ line-height: 1.25;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .project-path {
+ display: block;
+ margin-top: 3px;
+ color: color-mix(in srgb, CanvasText 64%, transparent);
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 12.5px;
+ line-height: 1.35;
+ overflow-wrap: anywhere;
+ user-select: text;
+ }
+ .project-tags { display: flex; justify-content: flex-end; gap: 4px; flex-wrap: wrap; max-width: 190px; }
+ .tag {
+ border: 1px solid color-mix(in srgb, CanvasText 15%, transparent);
+ border-radius: 999px;
+ padding: 2px 6px;
+ color: color-mix(in srgb, CanvasText 72%, transparent);
+ background: color-mix(in srgb, Canvas 90%, CanvasText 10%);
+ font-size: 12px;
+ line-height: 1.2;
+ }
+ .empty-list { padding: 18px; color: color-mix(in srgb, CanvasText 62%, transparent); }
+ .footer {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 14px;
+ padding: 14px 24px 18px;
+ border-top: 1px solid color-mix(in srgb, CanvasText 14%, transparent);
+ }
+ .selected-count { color: color-mix(in srgb, CanvasText 68%, transparent); font-size: 13px; }
+ .footer-buttons { display: flex; gap: 10px; }
+ .danger {
+ border-color: color-mix(in srgb, #d70015 58%, CanvasText 12%);
+ background: color-mix(in srgb, #d70015 82%, black 18%);
+ color: white;
+ font-weight: 600;
+ }
+ .danger:hover { background: color-mix(in srgb, #d70015 74%, black 26%); }
+ @media (max-width: 640px) {
+ .project-row { grid-template-columns: auto minmax(0, 1fr); }
+ .project-tags { grid-column: 2; justify-content: flex-start; max-width: none; }
+ .footer { align-items: stretch; flex-direction: column; }
+ .footer-buttons { justify-content: flex-end; }
+ }
+</style>
+</head>
+<body>
+ <main class="dialog" role="dialog" aria-labelledby="title" aria-describedby="description">
+ <section class="header">
+ <h1 id="title">Uninstall OpenKnowledge?</h1>
+ <p id="description">This removes OpenKnowledge’s settings and integrations from your Mac. Your markdown content and authored skills are kept.</p>
+ <p class="muted">Optionally select projects to also remove OpenKnowledge from. None are selected by default.</p>
+ <div class="controls">
+ <strong>${projectCount} detected ${projectWord}</strong>
+ <div class="control-buttons" aria-label="Project selection controls">
+ <button id="select-all" type="button">Select all</button>
+ <button id="select-none" type="button">Select none</button>
+ </div>
+ </div>
+ </section>
+ <section class="list-region" aria-label="Detected OpenKnowledge projects">
+ <p class="scroll-hint">Scrollable list — review all ${projectCount} ${projectWord} before uninstalling.</p>
+ <div class="project-list" id="project-list">
+${buildDesktopUninstallProjectRows(candidates)}
+ </div>
+ </section>
+ <section class="footer">
+ <div class="selected-count" id="selected-count">0 projects selected.</div>
+ <div class="footer-buttons">
+ <button id="cancel" type="button" autofocus>Cancel</button>
+ <button id="confirm" class="danger" type="button">Uninstall OpenKnowledge</button>
+ </div>
+ </section>
+ </main>
+<script>
+(() => {
+ const boxes = Array.from(document.querySelectorAll('input[type="checkbox"][data-index]'));
+ const selectedCount = document.getElementById('selected-count');
+ const selectedIndexes = () => boxes
+ .filter((box) => box.checked)
+ .map((box) => Number(box.dataset.index))
+ .filter((index) => Number.isInteger(index));
+ const finish = (action, indexes = []) => {
+ window.location.href = 'ok-desktop-uninstall://' + action + '?indexes=' + encodeURIComponent(indexes.join(','));
+ };
+ const update = () => {
+ const count = selectedIndexes().length;
+ const noun = count === 1 ? 'project' : 'projects';
+ selectedCount.textContent = count + ' ' + noun + ' selected.';
+ };
+ const selectAll = () => { boxes.forEach((box) => { box.checked = true; }); update(); };
+ const selectNone = () => { boxes.forEach((box) => { box.checked = false; }); update(); };
+ const cancel = () => finish('cancel');
+ boxes.forEach((box) => box.addEventListener('change', update));
+ document.getElementById('select-all').addEventListener('click', selectAll);
+ document.getElementById('select-none').addEventListener('click', selectNone);
+ document.getElementById('cancel').addEventListener('click', cancel);
+ document.getElementById('confirm').addEventListener('click', () => {
+ finish('confirm', selectedIndexes());
+ });
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') cancel();
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'a') {
+ event.preventDefault();
+ selectAll();
+ }
+ });
+ update();
+})();
+</script>
+</body>
+</html>`;
+}
+
+export function parseDesktopUninstallProjectPickerUrl(url: string): unknown | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== DESKTOP_UNINSTALL_PICKER_SCHEME) return null;
+
+ if (parsed.hostname === 'cancel') return { action: 'cancel' };
+ if (parsed.hostname !== 'confirm') return null;
+
+ const indexesRaw = parsed.searchParams.get('indexes') ?? '';
+ const selectedIndexes = indexesRaw
+ .split(',')
+ .filter((part) => /^\d+$/.test(part))
+ .map((part) => Number.parseInt(part, 10));
+ return { action: 'confirm', selectedIndexes };
+}
+
+export function resolveDesktopUninstallProjectSelection(
+ candidates: readonly DesktopUninstallProjectCandidate[],
+ raw: unknown,
+): DesktopUninstallProjectCandidate[] | null {
+ if (raw == null || typeof raw !== 'object') return null;
+ const record = raw as Record<string, unknown>;
+ if (record.action !== 'confirm') return null;
+
+ const rawIndexes = Array.isArray(record.selectedIndexes) ? record.selectedIndexes : [];
+ const selected = new Set<number>();
+ for (const value of rawIndexes) {
+ if (Number.isInteger(value) && value >= 0 && value < candidates.length) {
+ selected.add(value);
+ }
+ }
+ return candidates.filter((_, index) => selected.has(index));
+}
+
+export function buildDesktopUninstallProgressHtml(): string {
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; style-src 'unsafe-inline';"
+/>
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>Uninstalling OpenKnowledge</title>
+<style>
+ :root { color-scheme: light dark; }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0;
+ min-height: 100vh;
+ display: grid;
+ place-items: center;
+ font: 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ color: CanvasText;
+ background: Canvas;
+ }
+ .wrap { text-align: center; padding: 28px; max-width: 360px; }
+ .spinner {
+ width: 34px;
+ height: 34px;
+ margin: 0 auto 18px;
+ border: 3px solid color-mix(in srgb, CanvasText 18%, transparent);
+ border-top-color: Highlight;
+ border-radius: 50%;
+ animation: spin 0.9s linear infinite;
+ }
+ h1 { margin: 0 0 8px; font-size: 18px; font-weight: 650; }
+ p { margin: 0; line-height: 1.42; color: color-mix(in srgb, CanvasText 68%, transparent); }
+ @keyframes spin { to { transform: rotate(360deg); } }
+</style>
+</head>
+<body>
+ <main class="wrap" role="status" aria-live="polite">
+ <div class="spinner" aria-hidden="true"></div>
+ <h1>Removing OpenKnowledge files…</h1>
+ <p>This may take a moment. Your markdown content is kept.</p>
+ </main>
+</body>
+</html>`;
+}
+
+export function defaultDesktopUninstallLogPath(
+ home: string = homedir(),
+ now: Date = new Date(),
+): string {
+ const stamp = now.toISOString().replace(/[:.]/g, '-');
+ return join(home, 'Library', 'Logs', 'OpenKnowledge', `uninstall-${stamp}.log`);
+}
+
+/** Keeps the failure dialog a readable height; the full log stays on disk. */
+const UNINSTALL_LOG_DISPLAY_MAX_CHARS = 4000;
+
+/**
+ * The cleanup log's tail, sized for a native message-box `detail`, or null
+ * when the log is missing/unreadable/empty (the dialog then falls back to the
+ * path-only hint). Tail, not head: the per-item failure lines and the
+ * `deinit=…/global=…` summary land at the end.
+ */
+export function readDesktopUninstallLogForDisplay(
+ logPath: string,
+ deps: { readFile?: (path: string) => string } = {},
+): string | null {
+ const readFile = deps.readFile ?? ((path: string) => readFileSync(path, 'utf-8'));
+ try {
+ const text = readFile(logPath).trim();
+ if (text.length === 0) return null;
+ if (text.length <= UNINSTALL_LOG_DISPLAY_MAX_CHARS) return text;
+ return `… (earlier lines omitted — full log on disk)\n${text.slice(-UNINSTALL_LOG_DISPLAY_MAX_CHARS)}`;
+ } catch {
+ return null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Notice dialogs (styled replacements for native message boxes)
+// ---------------------------------------------------------------------------
+
+/**
+ * A simple message dialog rendered as an inline HTML window. Native
+ * `dialog.showMessageBox` renders `detail` at macOS's fixed small font, which
+ * is what pushed these off NSAlert.
+ */
+export interface DesktopUninstallNoticeSpec {
+ title: string;
+ paragraphs: string[];
+ /** Small muted line under the body (e.g. the cleanup log path). */
+ footnote?: string;
+ /** Monospace scrollable block (the cleanup log). */
+ log?: string;
+ confirmLabel: string;
+ /** When present the notice is a two-button question; closing means Cancel. */
+ cancelLabel?: string;
+ /** Style the confirm button as destructive. */
+ danger?: boolean;
+}
+
+/** Confirmation shown when no projects were found (the picker otherwise confirms). */
+export function desktopUninstallConfirmNotice(): DesktopUninstallNoticeSpec {
+ return {
+ title: 'Uninstall OpenKnowledge?',
+ paragraphs: [
+ 'This removes OpenKnowledge’s settings and integrations from your Mac. Your markdown content and authored skills are kept.',
+ 'When cleanup finishes, OpenKnowledge will help you remove the app itself, then quit.',
+ ],
+ confirmLabel: 'Uninstall OpenKnowledge',
+ cancelLabel: 'Cancel',
+ danger: true,
+ };
+}
+
+export function desktopUninstallCompletionNotice(opts: {
+ projectCount: number;
+ logPath: string;
+}): DesktopUninstallNoticeSpec {
+ const paragraphs = ['Your markdown content and authored skills were kept.'];
+ if (opts.projectCount > 0) {
+ paragraphs.push(
+ `OpenKnowledge was also removed from ${opts.projectCount} project${opts.projectCount === 1 ? '' : 's'}.`,
+ );
+ }
+ paragraphs.push(
+ 'One step left: move OpenKnowledge.app to the Trash.',
+ 'Click Continue to show the app in Finder. OpenKnowledge will then quit.',
+ );
+ return {
+ title: 'OpenKnowledge files were removed',
+ paragraphs,
+ footnote: `Cleanup log: ${opts.logPath}`,
+ confirmLabel: 'Continue',
+ };
+}
+
+export function desktopUninstallFailureNotice(opts: {
+ error: string;
+ logPath: string;
+ logText: string | null;
+}): DesktopUninstallNoticeSpec {
+ if (opts.logText === null) {
+ return {
+ title: 'Cleanup didn’t finish',
+ paragraphs: ['Some files may not have been removed.', opts.error],
+ footnote: `Cleanup log (if present): ${opts.logPath}`,
+ confirmLabel: 'Continue',
+ };
+ }
+ // With the log visible, the raw exit-code error line adds nothing.
+ return {
+ title: 'Cleanup didn’t finish',
+ paragraphs: ['Some files may not have been removed — details below.'],
+ log: opts.logText,
+ footnote: `Also saved to ${opts.logPath}`,
+ confirmLabel: 'Continue',
+ };
+}
+
+/** Failure-path follow-up; the success notice folds this step in. */
+export function desktopUninstallFinalStepNotice(): DesktopUninstallNoticeSpec {
+ return {
+ title: 'One more step',
+ paragraphs: [
+ 'Move OpenKnowledge.app to the Trash to finish.',
+ 'Click Continue to show the app in Finder. OpenKnowledge will then quit.',
+ ],
+ confirmLabel: 'Continue',
+ };
+}
+
+export function parseDesktopUninstallNoticeUrl(url: string): 'confirm' | 'cancel' | null {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return null;
+ }
+ if (parsed.protocol !== DESKTOP_UNINSTALL_PICKER_SCHEME) return null;
+ if (parsed.hostname === 'notice-confirm') return 'confirm';
+ if (parsed.hostname === 'notice-cancel') return 'cancel';
+ return null;
+}
+
+export function buildDesktopUninstallNoticeHtml(spec: DesktopUninstallNoticeSpec): string {
+ const paragraphs = spec.paragraphs.map((text) => `<p>${htmlEscape(text)}</p>`).join('\n');
+ const logBlock = spec.log === undefined ? '' : `<pre class="log">${htmlEscape(spec.log)}</pre>`;
+ const footnote =
+ spec.footnote === undefined ? '' : `<p class="footnote">${htmlEscape(spec.footnote)}</p>`;
+ const cancelButton =
+ spec.cancelLabel === undefined
+ ? ''
+ : `<button id="cancel" type="button" autofocus>${htmlEscape(spec.cancelLabel)}</button>`;
+ // Two-button notices keep focus on Cancel (destructive-safe default, matching
+ // NSAlert's cancel-default convention); single-button notices focus Continue.
+ const confirmAutofocus = spec.cancelLabel === undefined ? ' autofocus' : '';
+ const confirmClass = spec.danger ? 'danger' : 'primary';
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta
+ http-equiv="Content-Security-Policy"
+ content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline';"
+/>
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<title>${htmlEscape(spec.title)}</title>
+<style>
+ :root { color-scheme: light dark; }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; }
+ body {
+ margin: 0;
+ font: 14px -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ color: CanvasText;
+ background: Canvas;
+ }
+ .dialog {
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ min-height: 0;
+ padding: 22px 24px 18px;
+ }
+ h1 {
+ margin: 0 0 12px;
+ font-size: 20px;
+ font-weight: 650;
+ letter-spacing: -0.01em;
+ }
+ .body { flex: 1; min-height: 0; display: flex; flex-direction: column; }
+ p { margin: 0 0 10px; line-height: 1.45; }
+ .log {
+ flex: 1;
+ min-height: 80px;
+ margin: 2px 0 10px;
+ padding: 10px 12px;
+ overflow: auto;
+ border: 1px solid color-mix(in srgb, CanvasText 16%, transparent);
+ border-radius: 8px;
+ background: color-mix(in srgb, Canvas 96%, CanvasText 4%);
+ font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ user-select: text;
+ }
+ .footnote {
+ margin: 0;
+ color: color-mix(in srgb, CanvasText 62%, transparent);
+ font-size: 12.5px;
+ overflow-wrap: anywhere;
+ user-select: text;
+ }
+ .buttons { display: flex; justify-content: flex-end; gap: 10px; padding-top: 14px; }
+ button {
+ appearance: none;
+ border: 1px solid color-mix(in srgb, CanvasText 22%, transparent);
+ border-radius: 7px;
+ background: color-mix(in srgb, Canvas 88%, CanvasText 12%);
+ color: CanvasText;
+ padding: 7px 14px;
+ font: inherit;
+ cursor: default;
+ }
+ button:hover { background: color-mix(in srgb, Canvas 82%, CanvasText 18%); }
+ button:focus-visible { outline: 3px solid Highlight; outline-offset: 2px; }
+ /* Chromium's Highlight keyword is the pale selection blue — too light for a
+ filled button — so the primary uses the concrete macOS system blues. */
+ .primary {
+ border-color: transparent;
+ background: #007aff;
+ color: white;
+ font-weight: 600;
+ }
+ .primary:hover { background: color-mix(in srgb, #007aff 86%, black 14%); }
+ @media (prefers-color-scheme: dark) {
+ .primary { background: #0a84ff; }
+ .primary:hover { background: color-mix(in srgb, #0a84ff 86%, black 14%); }
+ }
+ .danger {
+ border-color: color-mix(in srgb, #d70015 58%, CanvasText 12%);
+ background: color-mix(in srgb, #d70015 82%, black 18%);
+ color: white;
+ font-weight: 600;
+ }
+ .danger:hover { background: color-mix(in srgb, #d70015 74%, black 26%); }
+</style>
+</head>
+<body>
+ <main class="dialog" role="alertdialog" aria-labelledby="title" aria-describedby="body">
+ <h1 id="title">${htmlEscape(spec.title)}</h1>
+ <div class="body" id="body">
+${paragraphs}
+${logBlock}
+${footnote}
+ </div>
+ <div class="buttons">
+ ${cancelButton}
+ <button id="confirm" class="${confirmClass}" type="button"${confirmAutofocus}>${htmlEscape(spec.confirmLabel)}</button>
+ </div>
+ </main>
+<script>
+(() => {
+ const hasCancel = ${spec.cancelLabel === undefined ? 'false' : 'true'};
+ const finish = (action) => {
+ window.location.href = 'ok-desktop-uninstall://notice-' + action;
+ };
+ document.getElementById('confirm').addEventListener('click', () => finish('confirm'));
+ if (hasCancel) {
+ document.getElementById('cancel').addEventListener('click', () => finish('cancel'));
+ }
+ document.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') finish(hasCancel ? 'cancel' : 'confirm');
+ });
+})();
+</script>
+</body>
+</html>`;
+}
+
+function shellQuote(value: string): string {
+ return `'${value.split("'").join("'\\''")}'`;
+}
+
+export function buildDesktopUninstallCleanupScript(input: DesktopUninstallCleanupInput): string {
+ const projectArgs = input.projectPaths.map(shellQuote).join(' ');
+ const projectBlock =
+ input.projectPaths.length === 0
+ ? 'echo "No project deinit paths selected."\nDEINIT_EXIT=0'
+ : `DEINIT_EXIT=0
+set -- ${projectArgs}
+for project in "$@"; do
+ if [ -d "$project/.ok" ]; then
+ echo "Deinitializing project: $project"
+ "$OK_CLI" deinit --yes "$project"
+ code=$?
+ if [ "$code" -ne 0 ]; then
+ echo "Project deinit failed ($code): $project"
+ DEINIT_EXIT=1
+ fi
+ else
+ echo "Skipping project without .ok: $project"
+ fi
+done`;
+
+ return `#!/bin/sh
+# Generated by OpenKnowledge Desktop. Intentionally no set -e: every cleanup
+# stage should run, and failures are captured in LOG for manual follow-up.
+OK_CLI=${shellQuote(input.cliPath)}
+LOG=${shellQuote(input.logPath)}
+LOG_DIR=${shellQuote(dirname(input.logPath))}
+EXIT_CODE=0
+
+mkdir -p "$LOG_DIR"
+{
+ echo "OpenKnowledge uninstall cleanup started at $(date -u +%Y-%m-%dT%H:%M:%SZ)"
+ echo "Log: $LOG"
+
+ GLOBAL_EXIT=0
+ DEINIT_EXIT=0
+ if [ -x "$OK_CLI" ]; then
+${projectBlock
+ .split('\n')
+ .map((line) => ` ${line}`)
+ .join('\n')}
+ echo "Removing global OpenKnowledge footprint."
+ "$OK_CLI" uninstall --yes
+ GLOBAL_EXIT=$?
+ if [ "$GLOBAL_EXIT" -ne 0 ]; then
+ echo "Global uninstall failed with exit code $GLOBAL_EXIT."
+ fi
+ else
+ echo "Bundled CLI missing or not executable: $OK_CLI"
+ GLOBAL_EXIT=69
+ fi
+
+ if [ "$DEINIT_EXIT" -ne 0 ] || [ "$GLOBAL_EXIT" -ne 0 ]; then
+ EXIT_CODE=1
+ fi
+
+ echo "OpenKnowledge uninstall cleanup finished at $(date -u +%Y-%m-%dT%H:%M:%SZ)"
+ echo "deinit=$DEINIT_EXIT global=$GLOBAL_EXIT"
+} >> "$LOG" 2>&1
+exit "$EXIT_CODE"
+`;
+}
+
+export function runDesktopUninstallCleanup(
+ input: DesktopUninstallCleanupInput,
+ deps: RunDesktopUninstallCleanupDeps = {},
+): Promise<RunDesktopUninstallCleanupResult> {
+ const spawn = deps.spawn ?? spawnChild;
+ return new Promise((resolveResult) => {
+ let settled = false;
+ const finish = (result: RunDesktopUninstallCleanupResult): void => {
+ if (settled) return;
+ settled = true;
+ resolveResult(result);
+ };
+
+ try {
+ const child = spawn('/bin/sh', ['-c', buildDesktopUninstallCleanupScript(input)], {
+ // Never inherit a cwd inside the app bundle; keeping the bundle idle
+ // lets the user move it to Trash after cleanup and app quit.
+ cwd: '/',
+ detached: false,
+ stdio: 'ignore',
+ });
+ child.once('error', (err) => finish({ ok: false, error: err.message }));
+ child.once('close', (code, signal) => {
+ if (code === 0) {
+ finish({ ok: true });
+ return;
+ }
+ const error =
+ signal != null
+ ? `cleanup process exited after signal ${signal}`
+ : `cleanup process exited with code ${code ?? 'unknown'}`;
+ finish({ ok: false, error, exitCode: code });
+ });
+ } catch (err) {
+ finish({ ok: false, error: err instanceof Error ? err.message : String(err) });
+ }
+ });
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index af994fec3..dfd56b87d 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -79,6 +79,7 @@ import {
BUNDLE_SKILL_NAME,
classifyFsPath,
createEphemeralProjectDir,
+ discoverLockDirs,
ensureProjectGit,
findEnclosingGitRoot,
findEnclosingProjectRoot,
@@ -100,7 +101,7 @@ import {
writeBundleDecision,
writeTargetVersion,
} from '@inkeep/open-knowledge-server';
-import type { BrowserWindowConstructorOptions } from 'electron';
+import type { BrowserWindowConstructorOptions, MessageBoxOptions } from 'electron';
import {
app,
BrowserWindow,
@@ -173,6 +174,26 @@ import {
} from './create-new-project.ts';
import { createDebugIpc, type DebugIpcHandle } from './debug-ipc.ts';
import { flushDesktopLogger, getLogger, getRootDesktopLogger } from './desktop-logger.ts';
+import {
+ buildDesktopUninstallNoticeHtml,
+ buildDesktopUninstallProgressHtml,
+ buildDesktopUninstallProjectPickerHtml,
+ collectDesktopUninstallProjectCandidates,
+ type DesktopUninstallNoticeSpec,
+ type DesktopUninstallProjectCandidate,
+ defaultDesktopUninstallLogPath,
+ desktopUninstallCompletionNotice,
+ desktopUninstallConfirmNotice,
+ desktopUninstallFailureNotice,
+ desktopUninstallFinalStepNotice,
+ isSupportedApplicationsBundle,
+ parseDesktopUninstallNoticeUrl,
+ parseDesktopUninstallProjectPickerUrl,
+ readDesktopUninstallLogForDisplay,
+ resolveAppBundleFromExecPath,
+ resolveDesktopUninstallProjectSelection,
+ runDesktopUninstallCleanup,
+} from './desktop-uninstall.ts';
import { promptForExistingFolder } from './dialog-helpers.ts';
import {
type DriverUtilityLike,
@@ -2093,6 +2114,15 @@ async function runApplicationMenuRefresh(): Promise<void> {
});
}
: undefined,
+ onUninstall: desktopSelfUninstallAvailable()
+ ? () =>
+ void startDesktopSelfUninstallFlow().catch((err) => {
+ getLogger('lifecycle').error(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'desktop self-uninstall flow failed',
+ );
+ })
+ : undefined,
// File menu state-aware items. activeTarget drives enable/disable;
// per-item handlers fire `ok:menu-action` to the focused renderer which
// already knows the current scope (sidebar selection + editor
@@ -2152,6 +2182,308 @@ async function runApplicationMenuRefresh(): Promise<void> {
});
}
+function desktopSelfUninstallAvailable(): boolean {
+ if (process.platform !== 'darwin' || !app.isPackaged) return false;
+ const appBundlePath = resolveAppBundleFromExecPath(process.execPath, process.platform);
+ return appBundlePath !== null && isSupportedApplicationsBundle(appBundlePath, osHomedir());
+}
+
+async function showMessageBoxAttached(options: MessageBoxOptions) {
+ const target = BrowserWindow.getFocusedWindow();
+ return target ? dialog.showMessageBox(target, options) : dialog.showMessageBox(options);
+}
+
+/**
+ * Show a `DesktopUninstallNoticeSpec` in a styled utility window and resolve
+ * true on confirm. Closing the window without a button press means Cancel for
+ * a two-button notice; a single-button notice proceeds either way (there is
+ * nothing else to choose, and the flow must still quit).
+ */
+async function showDesktopUninstallNotice(
+ spec: DesktopUninstallNoticeSpec,
+ options: { width?: number; height?: number; resizable?: boolean } = {},
+): Promise<boolean> {
+ const parent = BrowserWindow.getFocusedWindow();
+ const closeMeansConfirm = spec.cancelLabel === undefined;
+ return new Promise((resolveNotice) => {
+ const win = createDesktopUninstallUtilityWindow({
+ parent,
+ width: options.width ?? 480,
+ height: options.height ?? 300,
+ title: spec.title,
+ modal: parent != null,
+ resizable: options.resizable ?? false,
+ });
+
+ let settled = false;
+ const finish = (confirmed: boolean) => {
+ if (settled) return;
+ settled = true;
+ resolveNotice(confirmed);
+ if (!win.isDestroyed()) win.destroy();
+ };
+
+ win.webContents.on('will-navigate', (event, url) => {
+ const action = parseDesktopUninstallNoticeUrl(url);
+ if (action !== null) {
+ event.preventDefault();
+ finish(action === 'confirm');
+ return;
+ }
+ if (!url.startsWith('data:text/html')) event.preventDefault();
+ });
+
+ win.on('close', (event) => {
+ if (settled) return;
+ event.preventDefault();
+ finish(closeMeansConfirm);
+ });
+ win.on('closed', () => {
+ if (settled) return;
+ settled = true;
+ resolveNotice(closeMeansConfirm);
+ });
+ win.once('ready-to-show', () => {
+ if (!win.isDestroyed()) win.show();
+ });
+
+ void win
+ .loadURL(
+ `data:text/html;charset=utf-8,${encodeURIComponent(buildDesktopUninstallNoticeHtml(spec))}`,
+ )
+ .catch((err) => {
+ getLogger('lifecycle').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'desktop uninstall notice failed to load',
+ );
+ finish(closeMeansConfirm);
+ });
+ });
+}
+
+function createDesktopUninstallUtilityWindow(options: {
+ parent: BrowserWindow | null;
+ width: number;
+ height: number;
+ minWidth?: number;
+ minHeight?: number;
+ title: string;
+ modal?: boolean;
+ resizable?: boolean;
+}): BrowserWindow {
+ const win = new BrowserWindow({
+ width: options.width,
+ height: options.height,
+ minWidth: options.minWidth,
+ minHeight: options.minHeight,
+ parent: options.parent ?? undefined,
+ modal: options.modal ?? options.parent != null,
+ resizable: options.resizable ?? true,
+ minimizable: false,
+ maximizable: false,
+ show: false,
+ title: options.title,
+ fullscreenable: false,
+ webPreferences: {
+ ...DEFAULT_WIN_OPTS.webPreferences,
+ },
+ });
+ win.setMenu(null);
+ win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
+ return win;
+}
+
+async function showDesktopUninstallProjectPicker(
+ candidates: readonly DesktopUninstallProjectCandidate[],
+): Promise<DesktopUninstallProjectCandidate[] | null> {
+ const parent = BrowserWindow.getFocusedWindow();
+ const workArea = (
+ parent ? screen.getDisplayMatching(parent.getBounds()) : screen.getPrimaryDisplay()
+ ).workArea;
+ const width = Math.max(560, Math.min(820, workArea.width - 80));
+ const height = Math.max(460, Math.min(680, workArea.height - 80));
+
+ return new Promise((resolveSelection) => {
+ const win = createDesktopUninstallUtilityWindow({
+ parent,
+ width,
+ height,
+ minWidth: 560,
+ minHeight: 420,
+ title: 'Uninstall OpenKnowledge',
+ });
+
+ let settled = false;
+ const finish = (raw: unknown) => {
+ if (settled) return;
+ settled = true;
+ resolveSelection(resolveDesktopUninstallProjectSelection(candidates, raw));
+ if (!win.isDestroyed()) win.destroy();
+ };
+
+ win.webContents.on('will-navigate', (event, url) => {
+ const pickerResult = parseDesktopUninstallProjectPickerUrl(url);
+ if (pickerResult !== null) {
+ event.preventDefault();
+ finish(pickerResult);
+ return;
+ }
+ if (!url.startsWith('data:text/html')) event.preventDefault();
+ });
+
+ win.on('close', (event) => {
+ if (settled) return;
+ event.preventDefault();
+ finish({ action: 'cancel' });
+ });
+ win.on('closed', () => {
+ if (settled) return;
+ settled = true;
+ resolveSelection(null);
+ });
+ win.once('ready-to-show', () => {
+ if (!win.isDestroyed()) win.show();
+ });
+
+ void win
+ .loadURL(
+ `data:text/html;charset=utf-8,${encodeURIComponent(
+ buildDesktopUninstallProjectPickerHtml(candidates),
+ )}`,
+ )
+ .catch((err) => {
+ getLogger('lifecycle').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'desktop uninstall project picker failed to load',
+ );
+ finish({ action: 'cancel' });
+ });
+ });
+}
+
+async function withDesktopUninstallProgress<T>(work: () => Promise<T>): Promise<T> {
+ const parent = BrowserWindow.getFocusedWindow();
+ const win = createDesktopUninstallUtilityWindow({
+ parent,
+ width: 420,
+ height: 220,
+ title: 'Uninstalling OpenKnowledge',
+ modal: parent != null,
+ resizable: false,
+ });
+ win.webContents.on('will-navigate', (event, url) => {
+ if (!url.startsWith('data:text/html')) event.preventDefault();
+ });
+ const preventClose = (event: { preventDefault(): void }) => event.preventDefault();
+ win.on('close', preventClose);
+ win.once('ready-to-show', () => {
+ if (!win.isDestroyed()) win.show();
+ });
+
+ try {
+ // The progress window is cosmetic — a failed load must neither skip the
+ // cleanup nor (being outside the finally) leak the close-prevented window.
+ try {
+ await win.loadURL(
+ `data:text/html;charset=utf-8,${encodeURIComponent(buildDesktopUninstallProgressHtml())}`,
+ );
+ } catch (err) {
+ getLogger('lifecycle').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'desktop uninstall progress window failed to load',
+ );
+ }
+ return await work();
+ } finally {
+ if (!win.isDestroyed()) {
+ win.removeListener('close', preventClose);
+ win.destroy();
+ }
+ }
+}
+
+async function startDesktopSelfUninstallFlow(): Promise<void> {
+ const appBundlePath = resolveAppBundleFromExecPath(process.execPath, process.platform);
+ if (appBundlePath === null || !isSupportedApplicationsBundle(appBundlePath, osHomedir())) {
+ await showMessageBoxAttached({
+ type: 'error',
+ message: 'OpenKnowledge cannot uninstall itself from this location.',
+ detail:
+ 'Self-uninstall only works when OpenKnowledge.app is in Applications. Move this copy to the Trash manually.',
+ });
+ return;
+ }
+
+ let lockDirs: string[] = [];
+ try {
+ lockDirs = await discoverLockDirs();
+ } catch (err) {
+ getLogger('lifecycle').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'desktop self-uninstall could not discover running project locks',
+ );
+ }
+
+ const projectCandidates = collectDesktopUninstallProjectCandidates({
+ recentProjects: appState.recentProjects,
+ openProjectPaths: wm?.getOpenProjectPaths() ?? [],
+ lockDirs,
+ });
+ let projectPaths: string[] = [];
+ if (projectCandidates.length > 0) {
+ const selectedProjects = await showDesktopUninstallProjectPicker(projectCandidates);
+ if (selectedProjects === null) return;
+ projectPaths = selectedProjects.map((candidate) => candidate.path);
+ } else {
+ const confirmed = await showDesktopUninstallNotice(desktopUninstallConfirmNotice(), {
+ height: 280,
+ });
+ if (!confirmed) return;
+ }
+
+ const includeProjects = projectPaths.length > 0;
+ const logPath = defaultDesktopUninstallLogPath(osHomedir());
+ const cleanup = await withDesktopUninstallProgress(() =>
+ runDesktopUninstallCleanup({
+ cliPath: wrapperPathInBundle(process.execPath),
+ projectPaths,
+ logPath,
+ }),
+ );
+ if (!cleanup.ok) {
+ // Cleanup ran but reported problems (a refused path, a failed deinit…).
+ // Surface the log inline so the user doesn't have to hunt for the file,
+ // then continue to the remove-the-app step — the user asked to uninstall,
+ // and the log spells out anything that needs manual follow-up.
+ getLogger('lifecycle').warn(
+ { includeProjects, projectCount: projectPaths.length, logPath, error: cleanup.error },
+ 'desktop self-uninstall cleanup reported failures',
+ );
+ await showDesktopUninstallNotice(
+ desktopUninstallFailureNotice({
+ error: cleanup.error,
+ logPath,
+ logText: readDesktopUninstallLogForDisplay(logPath),
+ }),
+ { width: 560, height: 520, resizable: true },
+ );
+ await showDesktopUninstallNotice(desktopUninstallFinalStepNotice(), { height: 240 });
+ } else {
+ getLogger('lifecycle').info(
+ { includeProjects, projectCount: projectPaths.length, logPath },
+ 'desktop self-uninstall cleanup finished',
+ );
+ await showDesktopUninstallNotice(
+ desktopUninstallCompletionNotice({ projectCount: projectPaths.length, logPath }),
+ { height: 320 },
+ );
+ }
+
+ shell.showItemInFolder(appBundlePath);
+ autoUpdaterHandle?.suppressAutoInstallOnQuit();
+ app.quit();
+}
+
/**
* Dispatch an `OkMenuAction` to the focused renderer window. Mirrors the
* `openInstallSkillDialog` / `openSettings` pattern — falls back to the first
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 2cd6646bd..5296af60e 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -110,6 +110,12 @@ export interface MenuDeps {
* tooltip explaining why is more confusing than absence in dev mode.
*/
onCheckForUpdates?(): void;
+ /**
+ * macOS App menu → Uninstall OpenKnowledge… click handler. Optional so the
+ * row is hidden in dev, non-packaged, non-macOS, or unsupported install
+ * locations; the handler owns the destructive confirmation dialog.
+ */
+ onUninstall?(): void;
/**
* Active editor target snapshot — drives the macOS File menu's
* state-aware item-management section. Renderer pushes this via
@@ -363,6 +369,15 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
{ role: 'hideOthers' as const },
{ role: 'unhide' as const },
{ type: 'separator' as const },
+ ...(deps.onUninstall
+ ? ([
+ {
+ label: 'Uninstall OpenKnowledge…',
+ click: () => deps.onUninstall?.(),
+ },
+ { type: 'separator' as const },
+ ] satisfies MenuItemConstructorOptions[])
+ : []),
{ role: 'quit' as const },
],
},
diff --git a/packages/desktop/tests/integration/auto-updater.test.ts b/packages/desktop/tests/integration/auto-updater.test.ts
index 96286fbd6..c73a75515 100644
--- a/packages/desktop/tests/integration/auto-updater.test.ts
+++ b/packages/desktop/tests/integration/auto-updater.test.ts
@@ -325,6 +325,13 @@ describe('startAutoUpdater — initial configuration (parent §8.10 LOCKED)', ()
expect(rig.updater.channel).toBe('latest');
});
+ test('suppressAutoInstallOnQuit disables install-on-quit for self-uninstall', () => {
+ const { rig, handle } = makeRig();
+ expect(rig.updater.autoInstallOnAppQuit).toBe(true);
+ handle.suppressAutoInstallOnQuit();
+ expect(rig.updater.autoInstallOnAppQuit).toBe(false);
+ });
+
// smoke plumbing regression. Added when manual `bun run dev` revealed that
// `OK_UPDATER_FEED_URL` was documented in the PR body but never actually
// wired into main — feedUrl would be set but setFeedURL was never called,
diff --git a/packages/desktop/tests/main/desktop-uninstall.test.ts b/packages/desktop/tests/main/desktop-uninstall.test.ts
new file mode 100644
index 000000000..9ee3f0a82
--- /dev/null
+++ b/packages/desktop/tests/main/desktop-uninstall.test.ts
@@ -0,0 +1,334 @@
+import { describe, expect, mock, test } from 'bun:test';
+import { join } from 'node:path';
+import {
+ buildDesktopUninstallCleanupScript,
+ buildDesktopUninstallNoticeHtml,
+ buildDesktopUninstallProgressHtml,
+ buildDesktopUninstallProjectPickerHtml,
+ collectDesktopUninstallProjectCandidates,
+ defaultDesktopUninstallLogPath,
+ desktopUninstallCompletionNotice,
+ desktopUninstallConfirmNotice,
+ desktopUninstallFailureNotice,
+ desktopUninstallFinalStepNotice,
+ formatDesktopUninstallProjectList,
+ isSupportedApplicationsBundle,
+ parseDesktopUninstallNoticeUrl,
+ parseDesktopUninstallProjectPickerUrl,
+ readDesktopUninstallLogForDisplay,
+ resolveAppBundleFromExecPath,
+ resolveDesktopUninstallProjectSelection,
+ runDesktopUninstallCleanup,
+} from '../../src/main/desktop-uninstall.ts';
+
+describe('desktop self-uninstall helpers', () => {
+ test('resolves only packaged macOS .app exec paths', () => {
+ expect(
+ resolveAppBundleFromExecPath(
+ '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',
+ 'darwin',
+ ),
+ ).toBe('/Applications/OpenKnowledge.app');
+ expect(
+ resolveAppBundleFromExecPath(
+ '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge',
+ 'linux',
+ ),
+ ).toBeNull();
+ expect(resolveAppBundleFromExecPath('/usr/bin/node', 'darwin')).toBeNull();
+ });
+
+ test('allows only the canonical Applications install locations', () => {
+ expect(isSupportedApplicationsBundle('/Applications/OpenKnowledge.app', '/Users/alice')).toBe(
+ true,
+ );
+ expect(
+ isSupportedApplicationsBundle('/Users/alice/Applications/OpenKnowledge.app', '/Users/alice'),
+ ).toBe(true);
+ expect(
+ isSupportedApplicationsBundle('/Volumes/OpenKnowledge/OpenKnowledge.app', '/Users/alice'),
+ ).toBe(false);
+ expect(
+ isSupportedApplicationsBundle('/Applications/OpenKnowledge Beta.app', '/Users/alice'),
+ ).toBe(false);
+ });
+
+ test('collects open, recent, and running project candidates with .ok markers only', () => {
+ const candidates = collectDesktopUninstallProjectCandidates({
+ openProjectPaths: ['/work/open', '/work/dupe'],
+ recentProjects: [{ path: '/work/recent' }, { path: '/work/dupe' }, { path: '/work/missing' }],
+ lockDirs: ['/work/running/.ok/local', '/work/dupe/.ok/local'],
+ exists: (path) => !path.includes('missing') && path.endsWith(join('.ok')),
+ });
+
+ expect(candidates).toEqual([
+ { path: '/work/open', open: true, recent: false, running: false },
+ { path: '/work/dupe', open: true, recent: true, running: true },
+ { path: '/work/recent', open: false, recent: true, running: false },
+ { path: '/work/running', open: false, recent: false, running: true },
+ ]);
+ });
+
+ test('formats a bounded candidate list with source tags', () => {
+ const formatted = formatDesktopUninstallProjectList(
+ [
+ { path: '/work/a', open: true, recent: false, running: true },
+ { path: '/work/b', open: false, recent: true, running: false },
+ ],
+ 1,
+ );
+ expect(formatted).toBe('• /work/a (open, running)\n• …and 1 more');
+ });
+
+ test('builds a scrollable project picker with every candidate and bulk controls', () => {
+ const html = buildDesktopUninstallProjectPickerHtml([
+ { path: '/work/a', open: true, recent: false, running: true },
+ { path: '/work/<unsafe>&b', open: false, recent: true, running: false },
+ ]);
+
+ expect(html).toContain('Select all');
+ expect(html).toContain('Select none');
+ expect(html).toContain('ok-desktop-uninstall://');
+ expect(html).toContain('overflow-y: scroll');
+ expect(html).toContain('Scrollable list — review all 2 projects');
+ expect(html).toContain('/work/a');
+ expect(html).toContain('/work/&lt;unsafe&gt;&amp;b');
+ expect(html).not.toContain('…and');
+ // The drag-to-Trash instruction belongs to the post-cleanup dialog only.
+ expect(html).not.toContain('Trash');
+ });
+
+ test('builds a progress page with a loading indicator', () => {
+ const html = buildDesktopUninstallProgressHtml();
+ expect(html).toContain('Removing OpenKnowledge files…');
+ expect(html).toContain('class="spinner"');
+ expect(html).toContain('role="status"');
+ });
+
+ test('parses the private picker navigation URL into selected indexes', () => {
+ expect(
+ parseDesktopUninstallProjectPickerUrl('ok-desktop-uninstall://confirm?indexes=2%2C0%2Cbad'),
+ ).toEqual({ action: 'confirm', selectedIndexes: [2, 0] });
+ // Empty selection — the default, most common confirm (global-only uninstall).
+ expect(
+ parseDesktopUninstallProjectPickerUrl('ok-desktop-uninstall://confirm?indexes='),
+ ).toEqual({ action: 'confirm', selectedIndexes: [] });
+ expect(parseDesktopUninstallProjectPickerUrl('ok-desktop-uninstall://cancel')).toEqual({
+ action: 'cancel',
+ });
+ expect(
+ parseDesktopUninstallProjectPickerUrl('https://example.test/confirm?indexes=0'),
+ ).toBeNull();
+ });
+
+ test('resolves project picker output by candidate index only', () => {
+ const candidates = [
+ { path: '/work/a', open: true, recent: false, running: false },
+ { path: '/work/b', open: false, recent: true, running: false },
+ { path: '/work/c', open: false, recent: false, running: true },
+ ];
+
+ expect(
+ resolveDesktopUninstallProjectSelection(candidates, {
+ action: 'confirm',
+ selectedIndexes: [2, 0, 2, 99, -1, '1'],
+ selectedPaths: ['/work/b'],
+ }),
+ ).toEqual([candidates[0], candidates[2]]);
+ expect(
+ resolveDesktopUninstallProjectSelection(candidates, {
+ action: 'confirm',
+ selectedIndexes: [],
+ }),
+ ).toEqual([]);
+ expect(resolveDesktopUninstallProjectSelection(candidates, { action: 'cancel' })).toBeNull();
+ });
+
+ test('builds a cleanup script that deinitializes selected projects before global uninstall', () => {
+ const script = buildDesktopUninstallCleanupScript({
+ cliPath: "/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok's.sh",
+ projectPaths: ['/work/a', "/work/quote's"],
+ logPath: '/Users/alice/Library/Logs/OpenKnowledge/uninstall.log',
+ });
+
+ expect(script).toContain("set -- '/work/a' '/work/quote'\\''s'");
+ expect(script).toContain('"$OK_CLI" deinit --yes "$project"');
+ expect(script).toContain('"$OK_CLI" uninstall --yes');
+ expect(script).not.toContain('osascript');
+ expect(script).not.toContain('Finder');
+ expect(script).toContain(
+ "OK_CLI='/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok'\\''s.sh'",
+ );
+ });
+
+ test('a zero-project cleanup script skips deinit but still uninstalls globally', () => {
+ const script = buildDesktopUninstallCleanupScript({
+ cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',
+ projectPaths: [],
+ logPath: '/Users/alice/Library/Logs/OpenKnowledge/uninstall.log',
+ });
+
+ expect(script).toContain('No project deinit paths selected.');
+ expect(script).not.toContain('deinit --yes');
+ expect(script).toContain('"$OK_CLI" uninstall --yes');
+ });
+
+ test('default log path lives outside app data and is timestamped safely', () => {
+ expect(
+ defaultDesktopUninstallLogPath('/Users/alice', new Date('2026-07-08T01:02:03.004Z')),
+ ).toBe('/Users/alice/Library/Logs/OpenKnowledge/uninstall-2026-07-08T01-02-03-004Z.log');
+ });
+
+ test('reads the cleanup log for display, tail-truncating oversized logs', () => {
+ expect(readDesktopUninstallLogForDisplay('/log', { readFile: () => 'cleanup output\n' })).toBe(
+ 'cleanup output',
+ );
+ expect(readDesktopUninstallLogForDisplay('/log', { readFile: () => ' \n' })).toBeNull();
+ expect(
+ readDesktopUninstallLogForDisplay('/log', {
+ readFile: () => {
+ throw new Error('ENOENT');
+ },
+ }),
+ ).toBeNull();
+
+ const truncated = readDesktopUninstallLogForDisplay('/log', {
+ readFile: () => `start-marker${'x'.repeat(8000)}end-marker`,
+ });
+ expect(truncated).toStartWith('… (earlier lines omitted — full log on disk)\n');
+ expect(truncated).toEndWith('end-marker');
+ expect(truncated).not.toContain('start-marker');
+ });
+
+ test('failure notice embeds the log and still names the saved file', () => {
+ const notice = desktopUninstallFailureNotice({
+ error: 'cleanup process exited with code 1',
+ logPath: '/Users/alice/Library/Logs/OpenKnowledge/uninstall.log',
+ logText: 'Could not remove:\n ✗ Remove .claude/skills/pack/',
+ });
+ expect(notice.log).toContain('✗ Remove .claude/skills/pack/');
+ expect(notice.footnote).toContain('/Users/alice/Library/Logs/OpenKnowledge/uninstall.log');
+
+ // Unreadable log → the raw error + a path-only hint, no log block.
+ const noLog = desktopUninstallFailureNotice({
+ error: 'cleanup process exited with code 1',
+ logPath: '/log',
+ logText: null,
+ });
+ expect(noLog.log).toBeUndefined();
+ expect(noLog.paragraphs).toContain('cleanup process exited with code 1');
+ expect(noLog.footnote).toContain('/log');
+ });
+
+ test('notice copy stays terse and routes trash guidance post-cleanup', () => {
+ const confirm = desktopUninstallConfirmNotice();
+ expect(confirm.cancelLabel).toBe('Cancel');
+ expect(confirm.danger).toBe(true);
+ expect(confirm.paragraphs.join(' ')).not.toContain('Trash');
+
+ const done = desktopUninstallCompletionNotice({ projectCount: 0, logPath: '/log' });
+ expect(done.paragraphs.join(' ')).toContain('move OpenKnowledge.app to the Trash');
+ // Projects were off by default — silence beats "No projects were deinitialized."
+ expect(done.paragraphs.join(' ')).not.toContain('project');
+ expect(done.footnote).toBe('Cleanup log: /log');
+ expect(
+ desktopUninstallCompletionNotice({ projectCount: 2, logPath: '/log' }).paragraphs.join(' '),
+ ).toContain('removed from 2 projects');
+
+ expect(desktopUninstallFinalStepNotice().paragraphs.join(' ')).toContain('Trash');
+ });
+
+ test('notice html escapes content and finishes through the private scheme', () => {
+ const html = buildDesktopUninstallNoticeHtml({
+ title: 'T<itle>',
+ paragraphs: ['a&b'],
+ footnote: 'saved <here>',
+ log: 'line <1>',
+ confirmLabel: 'Continue',
+ });
+ expect(html).toContain('T&lt;itle&gt;');
+ expect(html).toContain('a&amp;b');
+ expect(html).toContain('saved &lt;here&gt;');
+ expect(html).toContain('line &lt;1&gt;');
+ expect(html).toContain("'ok-desktop-uninstall://notice-' + action");
+ expect(html).not.toContain('id="cancel"');
+
+ const twoButton = buildDesktopUninstallNoticeHtml(desktopUninstallConfirmNotice());
+ expect(twoButton).toContain('id="cancel"');
+ expect(twoButton).toContain('class="danger"');
+ });
+
+ test('parses notice URLs, rejecting foreign schemes and hosts', () => {
+ expect(parseDesktopUninstallNoticeUrl('ok-desktop-uninstall://notice-confirm')).toBe('confirm');
+ expect(parseDesktopUninstallNoticeUrl('ok-desktop-uninstall://notice-cancel')).toBe('cancel');
+ expect(parseDesktopUninstallNoticeUrl('ok-desktop-uninstall://confirm?indexes=0')).toBeNull();
+ expect(parseDesktopUninstallNoticeUrl('https://example.test/notice-confirm')).toBeNull();
+ });
+
+ test('runDesktopUninstallCleanup spawns an attached shell and resolves on close', async () => {
+ const listeners = new Map<string, (...args: unknown[]) => void>();
+ const child = {
+ once: mock((event: string, listener: (...args: unknown[]) => void) => {
+ listeners.set(event, listener);
+ }),
+ };
+ const spawn = mock(() => child);
+ const resultPromise = runDesktopUninstallCleanup(
+ {
+ cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',
+ projectPaths: [],
+ logPath: '/tmp/ok-uninstall.log',
+ },
+ { spawn },
+ );
+
+ expect(spawn).toHaveBeenCalledTimes(1);
+ expect(spawn.mock.calls[0]?.[0]).toBe('/bin/sh');
+ expect(spawn.mock.calls[0]?.[1]).toEqual(['-c', expect.any(String)]);
+ expect(spawn.mock.calls[0]?.[2]).toMatchObject({ cwd: '/', detached: false, stdio: 'ignore' });
+ listeners.get('close')?.(0, null);
+ await expect(resultPromise).resolves.toEqual({ ok: true });
+ });
+
+ test('runDesktopUninstallCleanup surfaces spawn errors, exit codes, and signals', async () => {
+ const input = {
+ cliPath: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',
+ projectPaths: [],
+ logPath: '/tmp/ok-uninstall.log',
+ };
+ const run = (fire: (listeners: Map<string, (...args: unknown[]) => void>) => void) => {
+ const listeners = new Map<string, (...args: unknown[]) => void>();
+ const child = {
+ once: (event: string, listener: (...args: unknown[]) => void) => {
+ listeners.set(event, listener);
+ },
+ };
+ const result = runDesktopUninstallCleanup(input, { spawn: () => child });
+ fire(listeners);
+ return result;
+ };
+
+ await expect(run((l) => l.get('error')?.(new Error('spawn EACCES')))).resolves.toEqual({
+ ok: false,
+ error: 'spawn EACCES',
+ });
+ await expect(run((l) => l.get('close')?.(1, null))).resolves.toEqual({
+ ok: false,
+ error: 'cleanup process exited with code 1',
+ exitCode: 1,
+ });
+ await expect(run((l) => l.get('close')?.(null, 'SIGKILL'))).resolves.toEqual({
+ ok: false,
+ error: 'cleanup process exited after signal SIGKILL',
+ exitCode: null,
+ });
+ // A synchronous spawn throw settles too (no hung uninstall flow).
+ await expect(
+ runDesktopUninstallCleanup(input, {
+ spawn: () => {
+ throw new Error('shell missing');
+ },
+ }),
+ ).resolves.toEqual({ ok: false, error: 'shell missing' });
+ });
+});
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 4d954398d..d60521e8e 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -380,6 +380,43 @@ describe('buildMenuTemplate', () => {
});
});
+ describe('Uninstall OpenKnowledge… menu item', () => {
+ test('omitted entirely when onUninstall dep is undefined', () => {
+ const template = buildMenuTemplate(makeDeps());
+ expect(findByLabel(template, 'Uninstall OpenKnowledge…')).toBeUndefined();
+ });
+
+ if (process.platform === 'darwin') {
+ test('macOS: appears in the App menu before Quit when wired', () => {
+ const onUninstall = mock(() => {});
+ const deps = makeDeps({ onUninstall });
+ const template = buildMenuTemplate(deps);
+ const appMenu = template.find((t) => t.label === deps.appName);
+ const sub = appMenu?.submenu as MenuItemConstructorOptions[] | undefined;
+ if (!sub) throw new Error('App submenu missing');
+ const uninstallIdx = sub.findIndex((i) => i.label === 'Uninstall OpenKnowledge…');
+ const quitIdx = sub.findIndex((i) => i.role === 'quit');
+ expect(uninstallIdx).toBeGreaterThanOrEqual(0);
+ expect(uninstallIdx).toBeLessThan(quitIdx);
+ });
+ }
+
+ test('click dispatches deps.onUninstall()', () => {
+ const onUninstall = mock(() => {});
+ const item = findByLabel(
+ buildMenuTemplate(makeDeps({ onUninstall })),
+ 'Uninstall OpenKnowledge…',
+ );
+ if (process.platform !== 'darwin') {
+ expect(item).toBeUndefined();
+ return;
+ }
+ if (!item || typeof item.click !== 'function') throw new Error('uninstall click missing');
+ (item.click as () => void)();
+ expect(onUninstall).toHaveBeenCalledTimes(1);
+ });
+ });
+
test('File close item follows the current test host branch', () => {
// `buildMenuTemplate` reads `process.platform` directly — we can assert
// the consistent cross-shape pairing rather than stubbing the platform.