Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): preview via Claude Desktop in-app browser (#2588)

tim-inkeepbd0757e49339
diff --git a/.changeset/remove-launch-json-pane-arming.md b/.changeset/remove-launch-json-pane-arming.md
new file mode 100644
index 000000000..6800f25e7
--- /dev/null
+++ b/.changeset/remove-launch-json-pane-arming.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": minor
+"@inkeep/open-knowledge-core": minor
+"@inkeep/open-knowledge-server": minor
+"@inkeep/open-knowledge-app": minor
+"@inkeep/open-knowledge-desktop": minor
+---
+
+Remove the launch.json preview machinery and the pane-target arming subsystem. Claude Code Desktop's in-app Browser pane now opens the preview URL directly (`preview_start({url})` + `navigate({url})`), so OK no longer scaffolds `.claude/launch.json`.
+
+Breaking for consumers: the `@inkeep/open-knowledge` package drops the `scaffoldLaunchJson`, `LAUNCH_UI_CHAIN_*`, and `LaunchJsonResult` exports; the `preview_url` MCP tool drops the `armPaneTarget` param; and the `/api/config` response drops the `paneTarget` field. The `ok start` repair sweep now removes any pre-existing `open-knowledge-ui` launch.json entry instead of rewriting it.
diff --git a/docs/content/reference/mcp.mdx b/docs/content/reference/mcp.mdx
index c7bbb959b..1ba60b719 100644
--- a/docs/content/reference/mcp.mdx
+++ b/docs/content/reference/mcp.mdx
@@ -21,7 +21,7 @@ The surface is **19 tools**. The four write verbs — `write`, `edit`, `delete`,
| `skills` | Find and read agent skills. Omit `name` to list every skill across Project + Global (rows carry `installed` + `hosts`); pass `name` to read one (addressed by `name`+`scope`, never by path); pass `name` + `file` to read one bundle file's text — the read path for `references/` and `scripts/` content |
| `config` | Read the effective merged config (`config({ key: "appearance.theme" })` for a sub-tree; omit `key` for the whole config) |
| `palette` | Markdown-native authoring forms, themed `html preview` embed starters, and theme tokens. Pass `components` for the canonical components' full JSX prop schemas |
-| `preview_url` | Resolve the browser-reachable preview URL. Targets a `document`, `folder`, or `skill` in the current project, or — via `file`, an absolute path — a markdown file outside it (resolved through the session serving that file). Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL. `armPaneTarget` briefly arms the target so a host preview pane opens on it |
+| `preview_url` | Resolve the browser-reachable preview URL. Targets a `document`, `folder`, or `skill` in the current project, or — via `file`, an absolute path — a markdown file outside it (resolved through the session serving that file). Per-response `previewUrl` fields elsewhere are route-only (`/#/<doc>`); call this when you need the full openable URL |
| `share_link` | Build a GitHub-substrate share URL for a doc or folder to send to a teammate (`kind` disambiguates; `path: ""` with `kind: "folder"` shares the content root). Responses carry a `freshness` verdict — `current`, `stale` (unpushed changes), or `absent` (never pushed), omitted when the probe can't run — and prepend a matching warning to relay with the link. Read-only against `.git/`; never publishes |
| `write` | Create or overwrite a `document`, `folder`, `template`, `skill`, or `asset`. For a document: `{ path, content }`, or `{ path, template }` to instantiate from a folder template. `position` selects `replace` (full rewrite; the only mode that touches frontmatter), `append`, or `prepend`. `extension` selects `.md` (default) or `.mdx` for a new document; an existing doc keeps its extension (the MCP cannot change it). An `asset` takes exactly one of `content` (base64, for small files) or `source` (a local path the server reads, for large files) |
| `edit` | Modify a `document` (body find/replace **or** a frontmatter merge-patch), a `folder` (frontmatter merge-patch), a `template`, or a `skill`. Body edits take `{ path, find, replace, occurrence? }`; `occurrence` selects which match (1 = first) |
@@ -73,6 +73,6 @@ To detect conflict state proactively without waiting for a 409, call `conflicts(
## Preview links
-Read and write tools return a `previewUrl` for any doc they touched, but **those are route-only** (`/#/<doc>` with no host:port), meant to identify the doc, not to be opened as-is. Hosts that want to open the editor (Claude Code Desktop's `preview_start`, terminal `open <url>`) call `preview_url` to resolve the full URL once per session.
+Read and write tools return a `previewUrl` for any doc they touched, but **those are route-only** (`/#/<doc>` with no host:port), meant to identify the doc, not to be opened as-is. Hosts that want to open the editor (Claude Code Desktop's `preview_start({url})`, terminal `open <url>`) call `preview_url` to resolve the full URL once per session.
`preview_url` always carries an `autoOpen` boolean (top-level on its response) reflecting the user's [`appearance.preview.autoOpen`](/docs/reference/configuration) preference. The write tools (`write`, `edit`) carry the same boolean on the `warning` object, which fires only when no browser is attached to the preview. In the common case (a browser is attached), the write response has no `warning` and no `autoOpen` field. Agents honor `autoOpen` before navigating: `true` (default) follows the host-capability routing in the bundled skill; `false` means the user is managing their own preview window, so the agent surfaces the URL on request but does not open or refresh anything. The value is resolved fresh on every tool call, so a mid-session toggle propagates within 0–1 calls, with no client restart.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 732914964..aa13141e8 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -87,7 +87,6 @@ When you initialize or open a project, the app scaffolds the same project files
| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](/docs/integrations/pi) (which has no MCP support) to the project | In-project, committed |
| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`, `.pi/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for the same five editors | In-project, committed |
| `.ok/skill-targets.json` | Committed list of which editors receive skills, written when you customize the targets | In-project, committed |
-| `.claude/launch.json` | Configures Claude Code's preview pane to open the editor (on a local UI port, `39848`) | In-project, committed |
| `~/.claude.json`, `~/Library/Application Support/Claude/claude_desktop_config.json`, `~/.cursor/mcp.json`, `~/.codex/config.toml`, `~/.config/opencode/opencode.json`, `~/.openclaw/openclaw.json`, `~/.gemini/config/mcp_config.json`, `~/.lmstudio/mcp.json`, `~/.hermes/config.yaml` | User-level `open-knowledge` MCP registration, one per detected editor, so it's available in every project (`~/.openclaw/openclaw.json` only when `~/.openclaw/` exists; `~/.gemini/config/mcp_config.json` is Antigravity's shared IDE + `agy` config, only when `~/.gemini/` exists; `~/.lmstudio/mcp.json` and `~/.hermes/config.yaml` only when those apps are installed) | Outside-project (editor config) |
### While a project is open
@@ -109,7 +108,7 @@ The app runs a collaboration server for the open project. It writes runtime stat
Diagnostic logs and telemetry are **on by default but local-only** — credential-bearing attributes are redacted (`[REDACTED]`) before anything is written, the files rotate at the size caps above, and nothing leaves the machine until you explicitly run `ok diagnose bundle`. Turn the local sink off with `telemetry.localSink.enabled: false`; see [Configuration](/docs/reference/configuration).
-On each launch and project open, the app also runs **repair sweeps**: it rewrites *existing* `open-knowledge` MCP entries (in the editor configs above), `.claude/launch.json`, and the OpenKnowledge skill bundles (`open-knowledge-discovery` and `open-knowledge-write-skill`, in `~/.agents/skills/` and each detected editor's `~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) to the current canonical form — a no-op when nothing has drifted. It **never adds** an MCP entry to an editor that doesn't already have one; and when you turn on skill management for a project, it also adopts your existing editor skills into `.ok/skills/`. Same `OK_RECLAIM_DISABLE=1` opt-out.
+On each launch and project open, the app also runs **repair sweeps**: it rewrites *existing* `open-knowledge` MCP entries (in the editor configs above) and the OpenKnowledge skill bundles (`open-knowledge-discovery` and `open-knowledge-write-skill`, in `~/.agents/skills/` and each detected editor's `~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/`) to the current canonical form — a no-op when nothing has drifted. It also removes any stale `open-knowledge-ui` entry left in `.claude/launch.json` by an older OK version. It **never adds** an MCP entry to an editor that doesn't already have one; and when you turn on skill management for a project, it also adopts your existing editor skills into `.ok/skills/`. Same `OK_RECLAIM_DISABLE=1` opt-out.
### Home directory and credentials (`~/.ok/`)
@@ -165,7 +164,6 @@ The `postinstall` step is **non-fatal** (install always succeeds even if it fail
| `.pi/extensions/open-knowledge.ts` | Managed bridge extension connecting [Pi](/docs/integrations/pi) (which has no MCP support) to the project | In-project, committed |
| `.claude/skills/`, `.cursor/skills/`, `.codex/skills/`, `.opencode/skills/`, `.pi/skills/` | Project-local "rich" OpenKnowledge skill (`SKILL.md`) for the same five editors | In-project, committed |
| `.ok/skill-targets.json` | Committed list of which editors receive skills, written when you customize the targets | In-project, committed |
-| `.claude/launch.json` | Configures Claude Code's preview pane to open the editor (on a local UI port, `39848`) | In-project, committed |
With `--scope user` or `both` (the default), `ok init` also registers the `open-knowledge` MCP server in each detected editor's **user-level** config, so it's available in every project:
@@ -217,8 +215,8 @@ On each boot, `ok start` also runs **repair sweeps**: it re-checks a few things
| What it re-checks | Where | Scope |
| --- | --- | --- |
| Existing `open-knowledge` MCP entries | The same editor configs `ok init` writes — **both** user-level (`~/.claude.json`, `~/.cursor/mcp.json`, …) and project-level | Outside-project (editor config) **and** in-project |
-| `.claude/launch.json` | Your project | In-project, committed |
| OpenKnowledge skill bundles (`open-knowledge-discovery`, `open-knowledge-write-skill`) | Project (`.claude/skills/…`) and user-global — `~/.agents/skills/` plus each detected editor's `~/.claude/skills/`, `~/.cursor/skills/`, `~/.codex/skills/`, `~/.opencode/skills/` | In-project **and** outside-project (home dir) |
+| Stale `open-knowledge-ui` entry in `.claude/launch.json` | Project | Removed if present — OK no longer writes launch.json |
Disable all three with `OK_RECLAIM_DISABLE=1`.
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
index 79f66121c..651c8c5bd 100644
--- a/packages/app/src/App.dom.test.tsx
+++ b/packages/app/src/App.dom.test.tsx
@@ -29,7 +29,6 @@ let fetchApiConfigMock = mock(() =>
collabUrl: null,
previewUrl: null,
port: 0,
- paneTarget: null,
singleFile: false,
},
}),
@@ -261,7 +260,6 @@ describe('App runtime wiring', () => {
collabUrl: null,
previewUrl: null,
port: 0,
- paneTarget: null,
singleFile: false,
},
}),
@@ -365,74 +363,6 @@ describe('App runtime wiring', () => {
expect(resolveNavigationTargetMock).not.toHaveBeenCalled();
});
- test('base-open pane target applies a well-formed config route once and consumes it', async () => {
- fetchApiConfigMock = mock(() =>
- Promise.resolve({
- status: 'ok' as const,
- config: {
- collabUrl: null,
- previewUrl: null,
- port: 0,
- paneTarget: '#/docs/pane-target',
- singleFile: false,
- },
- }),
- );
-
- renderApp();
-
- await waitFor(() => {
- expect(window.location.hash).toBe('#/docs/pane-target');
- });
- expect(fetchApiConfigMock).toHaveBeenCalledTimes(1);
- expect(globalThis.fetch).toHaveBeenCalledWith('/api/config', { method: 'DELETE' });
- });
-
- test('base-open pane target ignores malformed and direct-navigation routes', async () => {
- fetchApiConfigMock = mock(() =>
- Promise.resolve({
- status: 'ok' as const,
- config: {
- collabUrl: null,
- previewUrl: null,
- port: 0,
- paneTarget: 'https://example.invalid/docs/readme',
- singleFile: false,
- },
- }),
- );
-
- renderApp();
-
- await waitFor(() => {
- expect(fetchApiConfigMock).toHaveBeenCalledTimes(1);
- });
- expect(window.location.hash).toBe('');
- expect(globalThis.fetch).not.toHaveBeenCalled();
-
- cleanup();
- fetchApiConfigMock = mock(() =>
- Promise.resolve({
- status: 'ok' as const,
- config: {
- collabUrl: null,
- previewUrl: null,
- port: 0,
- paneTarget: '#/docs/pane-target',
- singleFile: false,
- },
- }),
- );
- setHash('#/docs/already-open');
-
- renderApp();
-
- await waitFor(() => {
- expect(fetchApiConfigMock).not.toHaveBeenCalled();
- });
- expect(window.location.hash).toBe('#/docs/already-open');
- });
-
test('active doc and folder targets are pushed to the desktop bridge', async () => {
const bridge = createBridge();
activeTarget = { kind: 'doc', target: 'docs/readme', docName: 'docs/readme' };
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 654ff07bc..7ad2518e8 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -31,7 +31,6 @@ import {
} from '@/editor/DocumentContext';
import { parseEditorTabId } from '@/editor/editor-tabs';
import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';
-import { fetchApiConfig } from '@/lib/api-config';
import { ConfigProvider } from '@/lib/config-provider';
import {
assetPathFromHash,
@@ -248,52 +247,6 @@ function NavigationHandler() {
return null;
}
-/**
- * One-shot base-open deep-link: when the UI opens at its base (no doc / asset /
- * dialog in the hash — e.g. the Claude pane's `preview_start`), apply an armed
- * pane target from `/api/config` so the pane lands on the agent's intended
- * doc/folder instead of an empty splash. Fires once at mount; navigates only if
- * the page is still at base when the fetch resolves (so it never overrides a
- * deep link the user opened directly or navigated to meanwhile). When no target
- * is armed (or it expired), it does nothing and the normal root view shows.
- */
-function PaneTargetLanding() {
- // No `didRun` ref: a ref set synchronously persists across React Strict
- // Mode's dev double-invoke, which would make the first run's cleanup cancel
- // the fetch and the second run early-return — so the effect would silently do
- // nothing in dev. The `cancelled` flag + the `atBase` re-check already make
- // re-running safe and idempotent (it only navigates from a base hash).
- useEffect(() => {
- const atBase = (hash: string) =>
- !isAuxiliaryDialogHash(hash) &&
- !assetPathFromHash(hash) &&
- !docNameFromHash(hash) &&
- (hash === '' || hash === '#' || hash === '#/');
- if (!atBase(window.location.hash)) return;
- const controller = new AbortController();
- void fetchApiConfig(controller.signal)
- .then((result) => {
- if (controller.signal.aborted || result.status !== 'ok') return;
- const target = result.config.paneTarget;
- // Only apply a well-formed in-app route fragment, and only if we're still
- // at base (the user hasn't navigated during the fetch).
- if (!target?.startsWith('#/')) return;
- if (!atBase(window.location.hash)) return;
- window.location.hash = target;
- // Consume the one-shot target so a reload within its TTL doesn't yank
- // back here. Fire-and-forget — re-navigation is the only cost if it
- // fails, and the server-side TTL caps that anyway.
- void fetch('/api/config', { method: 'DELETE' }).catch(() => {});
- })
- // fetchApiConfig rethrows AbortError on unmount — expected, swallow it.
- .catch(() => {});
- // Aborting on unmount cancels the inflight request, not just its handler —
- // symmetric with the rest of the app's /api/config consumers.
- return () => controller.abort();
- }, []);
- return null;
-}
-
/**
* Mounts `InstallInClaudeDesktopDialog` at the App root and opens it when
* `window.location.hash === '#install-claude-desktop'`. Docs and in-app CTAs
@@ -533,7 +486,6 @@ function AppBody() {
<PageListProvider>
<SystemDocSubscriber />
<NavigationHandler />
- <PaneTargetLanding />
<ActiveTargetBridgePush />
<NewItemShortcutHandler />
{/* Settings is unavailable in single-file mode (config editing is
diff --git a/packages/app/src/components/ConfigSharingInfoTooltip.tsx b/packages/app/src/components/ConfigSharingInfoTooltip.tsx
index bd9d9e52d..f49265d94 100644
--- a/packages/app/src/components/ConfigSharingInfoTooltip.tsx
+++ b/packages/app/src/components/ConfigSharingInfoTooltip.tsx
@@ -28,7 +28,7 @@ export function ConfigSharingInfoTooltip() {
<p className="leading-relaxed wrap-break-word">
<Trans>
Setup files include: <code>.ok/</code>, AI-tool MCP configs (<code>.mcp.json</code>{' '}
- and per-tool files), project skills, and <code>.claude/launch.json</code>.
+ and per-tool files), project skills.
<br />
<strong className="font-semibold">Shared</strong> commits them to git, so anyone who
clones the repo gets the same setup. <br />
diff --git a/packages/app/src/components/ConsentDialogBody.tsx b/packages/app/src/components/ConsentDialogBody.tsx
index d9eb88a80..25b23fbcb 100644
--- a/packages/app/src/components/ConsentDialogBody.tsx
+++ b/packages/app/src/components/ConsentDialogBody.tsx
@@ -391,10 +391,7 @@ function ConsentDialogForm({ payload, store, toast }: ConsentDialogFormProps) {
<Trans>Connect to AI tools</Trans>
</legend>
<p className="text-1sm text-muted-foreground">
- <Trans>
- Writes a project-MCP config for each selected tool; Claude also gets{' '}
- <code>.claude/launch.json</code>.
- </Trans>
+ <Trans>Writes a project-MCP config for each selected tool.</Trans>
</p>
{payload.editorOptions.map((editor) => {
const checkboxId = `consent-editor-${editor.id}-cb`;
diff --git a/packages/app/src/lib/api-config.test.ts b/packages/app/src/lib/api-config.test.ts
index f8fcc15e2..73166de71 100644
--- a/packages/app/src/lib/api-config.test.ts
+++ b/packages/app/src/lib/api-config.test.ts
@@ -36,7 +36,6 @@ describe('fetchApiConfig', () => {
collabUrl: 'ws://localhost:52000/collab',
previewUrl: 'http://localhost:3000/',
port: 3000,
- paneTarget: null,
singleFile: false,
},
});
@@ -52,7 +51,7 @@ describe('fetchApiConfig', () => {
const result = await fetchApiConfig();
expect(result).toEqual({
status: 'ok',
- config: { collabUrl: null, previewUrl: null, port: 0, paneTarget: null, singleFile: false },
+ config: { collabUrl: null, previewUrl: null, port: 0, singleFile: false },
});
});
@@ -67,33 +66,7 @@ describe('fetchApiConfig', () => {
const result = await fetchApiConfig();
expect(result).toEqual({
status: 'ok',
- config: { collabUrl: null, previewUrl: null, port: 0, paneTarget: null, singleFile: true },
- });
- });
-
- it('parses an armed paneTarget route fragment', async () => {
- stubFetch(
- async () =>
- new Response(
- JSON.stringify({
- collabUrl: null,
- previewUrl: null,
- port: 0,
- paneTarget: '#/specs/foo/',
- }),
- { status: 200 },
- ),
- );
- const result = await fetchApiConfig();
- expect(result).toEqual({
- status: 'ok',
- config: {
- collabUrl: null,
- previewUrl: null,
- port: 0,
- paneTarget: '#/specs/foo/',
- singleFile: false,
- },
+ config: { collabUrl: null, previewUrl: null, port: 0, singleFile: true },
});
});
@@ -139,7 +112,7 @@ describe('fetchApiConfig', () => {
const result = await fetchApiConfig();
expect(result).toEqual({
status: 'ok',
- config: { collabUrl: null, previewUrl: null, port: 0, paneTarget: null, singleFile: false },
+ config: { collabUrl: null, previewUrl: null, port: 0, singleFile: false },
});
});
diff --git a/packages/app/src/lib/api-config.ts b/packages/app/src/lib/api-config.ts
index d4fbfba12..dac8edf5a 100644
--- a/packages/app/src/lib/api-config.ts
+++ b/packages/app/src/lib/api-config.ts
@@ -25,13 +25,6 @@ interface ApiConfig {
collabUrl: string | null;
previewUrl: string | null;
port: number;
- /**
- * Armed pane-target route fragment (`#/<doc>` or `#/<folder>/`), TTL-bounded
- * server-side. Present only when an agent armed an explicit deep-link target
- * via `preview_url({ armPaneTarget: true })`; the app applies it once on a
- * base-open. `null` when unarmed or expired.
- */
- paneTarget: string | null;
/**
* `true` when served by a no-project ephemeral single-file server (`ok <file>`).
* The browser fallback reads this to drop project chrome (the desktop reads the
@@ -79,7 +72,6 @@ export async function fetchApiConfig(signal?: AbortSignal): Promise<FetchApiConf
collabUrl: typeof obj.collabUrl === 'string' ? obj.collabUrl : null,
previewUrl: typeof obj.previewUrl === 'string' ? obj.previewUrl : null,
port: typeof obj.port === 'number' ? obj.port : 0,
- paneTarget: typeof obj.paneTarget === 'string' ? obj.paneTarget : null,
singleFile: obj.singleFile === true,
},
};
diff --git a/packages/app/src/lib/single-file-mode.dom.test.tsx b/packages/app/src/lib/single-file-mode.dom.test.tsx
index 5dba0a52d..641ac40ce 100644
--- a/packages/app/src/lib/single-file-mode.dom.test.tsx
+++ b/packages/app/src/lib/single-file-mode.dom.test.tsx
@@ -68,7 +68,6 @@ describe('SingleFileModeProvider — browser /api/config channel', () => {
collabUrl: null,
previewUrl: null,
port: 0,
- paneTarget: null,
singleFile: true,
}),
{
@@ -94,7 +93,6 @@ describe('SingleFileModeProvider — browser /api/config channel', () => {
collabUrl: null,
previewUrl: null,
port: 0,
- paneTarget: null,
singleFile: false,
}),
{
diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.json
index cbc7201dd..e19aa5a6b 100644
--- a/packages/app/src/locales/en/messages.json
+++ b/packages/app/src/locales/en/messages.json
@@ -69,9 +69,6 @@
],
"0jD-Gn": ["A team knowledge base, a personal wiki, project docs..."],
"0kTAXe": ["Open source: ", ["mirrorSrc"]],
- "0njBIq": [
- "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills, and <2>.claude/launch.json</2>.<3/><4>Shared</4> commits them to git, so anyone who clones the repo gets the same setup. <5/><6>Local only</6> keeps them out of git (via <7>.git/info/exclude</7>)."
- ],
"0rwwOn": ["By tag"],
"0s8-e8": [
"Select, enter, or leave block components and fallback source blocks from keyboard boundaries."
@@ -1175,6 +1172,7 @@
"\" could not be cleared in time. Reload to retry."
],
"ScwcF2": ["A project already exists at this location. Pick a different parent folder."],
+ "SfxQX8": ["Writes a project-MCP config for each selected tool."],
"SgKLfA": ["Not connected to GitHub."],
"Sh3Qkg": ["No matching branches."],
"SiUUCS": ["Next match"],
@@ -1637,9 +1635,6 @@
"ePK91l": ["Edit"],
"eQkgKV": ["Installed"],
"eQxm13": ["Failed to update attachment location — ", ["detail"]],
- "eSu2Xn": [
- "Writes a project-MCP config for each selected tool; Claude also gets <0>.claude/launch.json</0>."
- ],
"eTL5y9": ["Show selection preview"],
"eTsJYJ": ["description"],
"eVPynQ": ["Open <0><1>", ["verificationUri"], "</1><2/></0> and enter this code:"],
@@ -1824,6 +1819,9 @@
"ircigK": ["Blank project"],
"irrm_E": ["Remove selection"],
"isRobC": ["New"],
+ "itxlnr": [
+ "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills.<2/><3>Shared</3> commits them to git, so anyone who clones the repo gets the same setup. <4/><5>Local only</5> keeps them out of git (via <6>.git/info/exclude</6>)."
+ ],
"iuTKci": ["No edits yet."],
"iycx_A": ["Pushing"],
"j9Vqvc": ["inherited"],
diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.po
index d8542c1fc..8345733c4 100644
--- a/packages/app/src/locales/en/messages.po
+++ b/packages/app/src/locales/en/messages.po
@@ -6286,8 +6286,8 @@ msgid "Setup"
msgstr "Setup"
#: src/components/ConfigSharingInfoTooltip.tsx
-msgid "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills, and <2>.claude/launch.json</2>.<3/><4>Shared</4> commits them to git, so anyone who clones the repo gets the same setup. <5/><6>Local only</6> keeps them out of git (via <7>.git/info/exclude</7>)."
-msgstr "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills, and <2>.claude/launch.json</2>.<3/><4>Shared</4> commits them to git, so anyone who clones the repo gets the same setup. <5/><6>Local only</6> keeps them out of git (via <7>.git/info/exclude</7>)."
+msgid "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills.<2/><3>Shared</3> commits them to git, so anyone who clones the repo gets the same setup. <4/><5>Local only</5> keeps them out of git (via <6>.git/info/exclude</6>)."
+msgstr "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills.<2/><3>Shared</3> commits them to git, so anyone who clones the repo gets the same setup. <4/><5>Local only</5> keeps them out of git (via <6>.git/info/exclude</6>)."
#: src/components/ConsentDialogBody.tsx
msgid "Setup OpenKnowledge in this folder?"
@@ -7870,8 +7870,8 @@ msgid "Wrap long lines in the markdown source editor."
msgstr "Wrap long lines in the markdown source editor."
#: src/components/ConsentDialogBody.tsx
-msgid "Writes a project-MCP config for each selected tool; Claude also gets <0>.claude/launch.json</0>."
-msgstr "Writes a project-MCP config for each selected tool; Claude also gets <0>.claude/launch.json</0>."
+msgid "Writes a project-MCP config for each selected tool."
+msgstr "Writes a project-MCP config for each selected tool."
#: src/components/ActivityPanelFileRow.tsx
msgid "writing"
diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.json
index 3f1a3d573..b684027b8 100644
--- a/packages/app/src/locales/pseudo/messages.json
+++ b/packages/app/src/locales/pseudo/messages.json
@@ -69,9 +69,6 @@
],
"0jD-Gn": ["À ţēàḿ ķńōŵĺēďĝē ƀàśē, à ƥēŕśōńàĺ ŵĩķĩ, ƥŕōĴēćţ ďōćś..."],
"0kTAXe": ["Ōƥēń śōũŕćē: ", ["mirrorSrc"]],
- "0njBIq": [
- "Śēţũƥ ƒĩĺēś ĩńćĺũďē: <0>.ōķ/</0>, ÀĨ-ţōōĺ ḾĆƤ ćōńƒĩĝś (<1>.ḿćƥ.Ĵśōń</1> àńď ƥēŕ-ţōōĺ ƒĩĺēś), ƥŕōĴēćţ śķĩĺĺś, àńď <2>.ćĺàũďē/ĺàũńćĥ.Ĵśōń</2>.<3/><4>Śĥàŕēď</4> ćōḿḿĩţś ţĥēḿ ţō ĝĩţ, śō àńŷōńē ŵĥō ćĺōńēś ţĥē ŕēƥō ĝēţś ţĥē śàḿē śēţũƥ. <5/><6>Ĺōćàĺ ōńĺŷ</6> ķēēƥś ţĥēḿ ōũţ ōƒ ĝĩţ (vĩà <7>.ĝĩţ/ĩńƒō/ēxćĺũďē</7>)."
- ],
"0rwwOn": ["ßŷ ţàĝ"],
"0s8-e8": [
"Śēĺēćţ, ēńţēŕ, ōŕ ĺēàvē ƀĺōćķ ćōḿƥōńēńţś àńď ƒàĺĺƀàćķ śōũŕćē ƀĺōćķś ƒŕōḿ ķēŷƀōàŕď ƀōũńďàŕĩēś."
@@ -1175,6 +1172,7 @@
"\" ćōũĺď ńōţ ƀē ćĺēàŕēď ĩń ţĩḿē. Ŕēĺōàď ţō ŕēţŕŷ."
],
"ScwcF2": ["À ƥŕōĴēćţ àĺŕēàďŷ ēxĩśţś àţ ţĥĩś ĺōćàţĩōń. Ƥĩćķ à ďĩƒƒēŕēńţ ƥàŕēńţ ƒōĺďēŕ."],
+ "SfxQX8": ["Ŵŕĩţēś à ƥŕōĴēćţ-ḾĆƤ ćōńƒĩĝ ƒōŕ ēàćĥ śēĺēćţēď ţōōĺ."],
"SgKLfA": ["Ńōţ ćōńńēćţēď ţō ĜĩţĤũƀ."],
"Sh3Qkg": ["Ńō ḿàţćĥĩńĝ ƀŕàńćĥēś."],
"SiUUCS": ["Ńēxţ ḿàţćĥ"],
@@ -1637,9 +1635,6 @@
"ePK91l": ["Ēďĩţ"],
"eQkgKV": ["Ĩńśţàĺĺēď"],
"eQxm13": ["Ƒàĩĺēď ţō ũƥďàţē àţţàćĥḿēńţ ĺōćàţĩōń — ", ["detail"]],
- "eSu2Xn": [
- "Ŵŕĩţēś à ƥŕōĴēćţ-ḾĆƤ ćōńƒĩĝ ƒōŕ ēàćĥ śēĺēćţēď ţōōĺ; Ćĺàũďē àĺśō ĝēţś <0>.ćĺàũďē/ĺàũńćĥ.Ĵśōń</0>."
- ],
"eTL5y9": ["Śĥōŵ śēĺēćţĩōń ƥŕēvĩēŵ"],
"eTsJYJ": ["ďēśćŕĩƥţĩōń"],
"eVPynQ": ["Ōƥēń <0><1>", ["verificationUri"], "</1><2/></0> àńď ēńţēŕ ţĥĩś ćōďē:"],
@@ -1824,6 +1819,9 @@
"ircigK": ["ßĺàńķ ƥŕōĴēćţ"],
"irrm_E": ["Ŕēḿōvē śēĺēćţĩōń"],
"isRobC": ["Ńēŵ"],
+ "itxlnr": [
+ "Śēţũƥ ƒĩĺēś ĩńćĺũďē: <0>.ōķ/</0>, ÀĨ-ţōōĺ ḾĆƤ ćōńƒĩĝś (<1>.ḿćƥ.Ĵśōń</1> àńď ƥēŕ-ţōōĺ ƒĩĺēś), ƥŕōĴēćţ śķĩĺĺś.<2/><3>Śĥàŕēď</3> ćōḿḿĩţś ţĥēḿ ţō ĝĩţ, śō àńŷōńē ŵĥō ćĺōńēś ţĥē ŕēƥō ĝēţś ţĥē śàḿē śēţũƥ. <4/><5>Ĺōćàĺ ōńĺŷ</5> ķēēƥś ţĥēḿ ōũţ ōƒ ĝĩţ (vĩà <6>.ĝĩţ/ĩńƒō/ēxćĺũďē</6>)."
+ ],
"iuTKci": ["Ńō ēďĩţś ŷēţ."],
"iycx_A": ["Ƥũśĥĩńĝ"],
"j9Vqvc": ["ĩńĥēŕĩţēď"],
diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.po
index 9c077caa5..e6c6f7321 100644
--- a/packages/app/src/locales/pseudo/messages.po
+++ b/packages/app/src/locales/pseudo/messages.po
@@ -6281,7 +6281,7 @@ msgid "Setup"
msgstr ""
#: src/components/ConfigSharingInfoTooltip.tsx
-msgid "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills, and <2>.claude/launch.json</2>.<3/><4>Shared</4> commits them to git, so anyone who clones the repo gets the same setup. <5/><6>Local only</6> keeps them out of git (via <7>.git/info/exclude</7>)."
+msgid "Setup files include: <0>.ok/</0>, AI-tool MCP configs (<1>.mcp.json</1> and per-tool files), project skills.<2/><3>Shared</3> commits them to git, so anyone who clones the repo gets the same setup. <4/><5>Local only</5> keeps them out of git (via <6>.git/info/exclude</6>)."
msgstr ""
#: src/components/ConsentDialogBody.tsx
@@ -7865,7 +7865,7 @@ msgid "Wrap long lines in the markdown source editor."
msgstr ""
#: src/components/ConsentDialogBody.tsx
-msgid "Writes a project-MCP config for each selected tool; Claude also gets <0>.claude/launch.json</0>."
+msgid "Writes a project-MCP config for each selected tool."
msgstr ""
#: src/components/ActivityPanelFileRow.tsx
diff --git a/packages/app/src/server/api-config-handler.test.ts b/packages/app/src/server/api-config-handler.test.ts
index 6bb9ae334..087554488 100644
--- a/packages/app/src/server/api-config-handler.test.ts
+++ b/packages/app/src/server/api-config-handler.test.ts
@@ -13,7 +13,6 @@ describe('computeDevApiConfigResponse', () => {
collabUrl: 'ws://localhost:5173/collab',
previewUrl: null,
port: 5173,
- paneTarget: null,
singleFile: false,
});
});
diff --git a/packages/app/src/server/api-config-handler.ts b/packages/app/src/server/api-config-handler.ts
index 018aaaa3b..5ef4d3293 100644
--- a/packages/app/src/server/api-config-handler.ts
+++ b/packages/app/src/server/api-config-handler.ts
@@ -24,12 +24,9 @@ interface DevApiConfigResponse {
* Returns `null` for methods other than GET/HEAD — callers should fall
* through so the catch-all returns a 404 JSON.
*
- * Body shape: `{ collabUrl, previewUrl, port, paneTarget }` — matches `ok ui`.
+ * Body shape: `{ collabUrl, previewUrl, port }` — matches `ok ui`.
* `collabUrl` is null when `port <= 0` (server not yet bound); callers
* should not invoke this before the dev server has emitted 'listening'.
- * `paneTarget` is always null in dev — the armed-pane-target store is an
- * `ok ui` concern (the Claude pane opens against `ok ui`, not `bun run dev`),
- * but the field rides the dev response too so the dev/prod shape stays identical.
*/
export function computeDevApiConfigResponse(
method: string | undefined,
@@ -40,7 +37,7 @@ export function computeDevApiConfigResponse(
const collabUrl = port > 0 ? `ws://localhost:${port}/collab` : null;
return {
status: 200,
- body: JSON.stringify({ collabUrl, previewUrl: null, port, paneTarget: null, singleFile }),
+ body: JSON.stringify({ collabUrl, previewUrl: null, port, singleFile }),
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
diff --git a/packages/app/tests/integration/attribution-sweep-coverage.test.ts b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
index 01b2024c6..fec26542e 100644
--- a/packages/app/tests/integration/attribution-sweep-coverage.test.ts
+++ b/packages/app/tests/integration/attribution-sweep-coverage.test.ts
@@ -193,8 +193,7 @@ const EXEMPT_HANDLERS = new Set([
// GET /api/server-info — identity-free readonly endpoint surfacing the
// per-process serverInstanceId for CRDT restart-recovery defense.
'handleServerInfo',
- // `/api/config` — collab-bootstrap payload. GET reads server-lock + armed
- // pane-target; DELETE clears the local pane-target TTL file. No Y.Doc
+ // `/api/config` — collab-bootstrap payload. GET reads server-lock. No Y.Doc
// mutation and no agent content, so identity threading is exempt — same
// rationale as `handleServerInfo`.
'handleApiConfig',
diff --git a/packages/app/tests/integration/conflict-gate-coverage.test.ts b/packages/app/tests/integration/conflict-gate-coverage.test.ts
index f294dda45..75761ffa7 100644
--- a/packages/app/tests/integration/conflict-gate-coverage.test.ts
+++ b/packages/app/tests/integration/conflict-gate-coverage.test.ts
@@ -112,9 +112,8 @@ const EXEMPT_HANDLERS = new Set([
// conflict gate does not apply.
'handleClientLogs',
'handleWorkspace',
- // `/api/config` — collab-bootstrap payload. GET reads server-lock + armed
- // pane-target; DELETE clears the local pane-target TTL file. Neither targets
- // a Y.Doc, so the per-doc conflict gate does not apply.
+ // `/api/config` — collab-bootstrap payload. GET reads server-lock. Does not
+ // target a Y.Doc, so the per-doc conflict gate does not apply.
'handleApiConfig',
'handleRescueList',
'handleSyncStatus',
diff --git a/packages/cli/src/commands/editors.ts b/packages/cli/src/commands/editors.ts
index 8486fbf77..3d82a4044 100644
--- a/packages/cli/src/commands/editors.ts
+++ b/packages/cli/src/commands/editors.ts
@@ -348,7 +348,7 @@ export function isEntryUpToDate(entry: unknown): boolean {
return false;
}
-export function resolveDevCliDistPath(entryPath: string = process.argv[1]): string {
+function resolveDevCliDistPath(entryPath: string = process.argv[1]): string {
if (!entryPath) {
throw new Error(
'Cannot infer the local CLI entry for --dev-mcp because process.argv[1] is empty.',
diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts
index c67466a6f..40c7562b1 100644
--- a/packages/cli/src/commands/init.test.ts
+++ b/packages/cli/src/commands/init.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
-import { execFileSync, spawnSync } from 'node:child_process';
+import { execFileSync } from 'node:child_process';
import {
existsSync,
lstatSync,
@@ -51,9 +51,6 @@ import {
formatInitResult,
formatSharingOutcome,
initCommand,
- LAUNCH_UI_CHAIN_SENTINEL,
- LAUNCH_UI_CHAIN_V1,
- LAUNCH_UI_WIN_CHAIN_SENTINEL,
MANAGED_FILE_BUILDERS,
readExistingMcpEntry,
resolveInitSkillEnablement,
@@ -61,11 +58,9 @@ import {
resolveRequestedContentDir,
resolveSharingMode,
runInit,
- scaffoldLaunchJson,
writeEditorMcpConfig,
writeUserMcpConfigs,
} from './init.ts';
-import { LAUNCH_JSON_PORT } from './ui.ts';
// The native TOML addon is absent when its napi `.node` wasn't built (a turbo cache
// miss, or local dev without a build) — the engine then falls back to smol-toml. A
@@ -76,75 +71,6 @@ import { LAUNCH_JSON_PORT } from './ui.ts';
// forced `() => null` engine tests.
const NATIVE_TOML_AVAILABLE = createTomlConfigEngine().backend === 'native';
-describe('LAUNCH_UI_CHAIN_V1 (published launch.json recipe shell chain)', () => {
- it('is syntactically valid POSIX sh (sh -n)', () => {
- // The recipe runs on every user machine after `ok init` / desktop reclaim,
- // so a shell syntax error would silently break the preview everywhere.
- // `sh -n` parses without executing — hermetic, ~ms.
- const result = spawnSync('sh', ['-n', '-c', LAUNCH_UI_CHAIN_V1], { encoding: 'utf-8' });
- expect(result.status).toBe(0);
- expect(result.stderr).toBe('');
- });
-
- // The argv-forwarding tests below EXECUTE the chain via `/bin/sh -l -c`. The
- // recipe is macOS-only (it resolves an `OpenKnowledge.app` bundle), and the
- // execution semantics depend on the macOS `/bin/sh` (bash). On a Linux CI
- // runner `/bin/sh` is dash and the bundle-probe path differs, so the chain
- // falls through to its `npx @latest` network branch and the assertion is
- // meaningless. Gate execution on darwin (dev macs + macOS CI lanes); the
- // platform-agnostic `sh -n` syntax check above still runs everywhere.
- const itDarwin = it.skipIf(process.platform !== 'darwin');
-
- // Stub the user-bundle resolution target ($HOME/Applications/.../ok.sh) with a
- // script that echoes its argv, so the chain's FIRST exec branch fires and we
- // can observe exactly what it forwards. Returns the stubbed HOME.
- function withStubbedBundle(): { home: string; cleanup: () => void } {
- const home = join(tmpdir(), `ok-ui-chain-${Date.now()}-${Math.random().toString(36).slice(2)}`);
- const binDir = join(
- home,
- 'Applications',
- 'OpenKnowledge.app',
- 'Contents',
- 'Resources',
- 'cli',
- 'bin',
- );
- mkdirSync(binDir, { recursive: true });
- const stub = join(binDir, 'ok.sh');
- writeFileSync(stub, '#!/bin/sh\necho "STUB:$*"\n');
- spawnSync('chmod', ['+x', stub]);
- return { home, cleanup: () => rmSync(home, { recursive: true, force: true }) };
- }
-
- itDarwin('forwards the pane PORT as `start --ui-port <PORT>`', () => {
- const { home, cleanup } = withStubbedBundle();
- try {
- const out = spawnSync('sh', ['-l', '-c', LAUNCH_UI_CHAIN_V1], {
- encoding: 'utf-8',
- env: { ...process.env, HOME: home, PORT: '40123' },
- });
- expect(out.stdout.trim()).toBe('STUB:start --ui-port 40123');
- } finally {
- cleanup();
- }
- });
-
- itDarwin(
- 'defaults --ui-port to LAUNCH_JSON_PORT when PORT is unset (main stays connect-armed)',
- () => {
- const { home, cleanup } = withStubbedBundle();
- try {
- const env = { ...process.env, HOME: home };
- delete (env as { PORT?: string }).PORT;
- const out = spawnSync('sh', ['-l', '-c', LAUNCH_UI_CHAIN_V1], { encoding: 'utf-8', env });
- expect(out.stdout.trim()).toBe(`STUB:start --ui-port ${LAUNCH_JSON_PORT}`);
- } finally {
- cleanup();
- }
- },
- );
-});
-
describe('runInit', () => {
let testDir: string;
let fakeHome: string;
@@ -177,34 +103,6 @@ describe('runInit', () => {
OK_LOG_FILE: '/tmp/ok-mcp.log',
},
});
- // The recipe is now a `# ok-ui-v1` `/bin/sh` chain running `ok start` (not
- // bare `ok ui`) so the opened folder gets its own collab server. Assert the
- // chain shape rather than a brittle byte-for-byte string. Dev mode pins the
- // chain's `exec` to the local CLI dist (`dist/cli.mjs`).
- const assertChainEntry = (
- entry: {
- name: string;
- runtimeExecutable: string;
- runtimeArgs: string[];
- port: number;
- autoPort: boolean;
- },
- opts: { devDist?: string } = {},
- ) => {
- expect(entry.name).toBe('open-knowledge-ui');
- expect(entry.runtimeExecutable).toBe('/bin/sh');
- expect(entry.runtimeArgs.slice(0, 2)).toEqual(['-l', '-c']);
- const chain = entry.runtimeArgs[2];
- expect(chain).toContain(LAUNCH_UI_CHAIN_SENTINEL);
- expect(chain).toContain('start');
- expect(chain).toContain('--ui-port');
- if (opts.devDist !== undefined) {
- expect(chain).toContain(`exec node "${opts.devDist}" start`);
- }
- expect(entry.port).toBe(LAUNCH_JSON_PORT);
- expect(entry.autoPort).toBe(true);
- };
- const devDistPath = () => join(devRepoRoot(), 'packages', 'cli', 'dist', 'cli.mjs');
/**
* Stubbed installUserSkill used by every test unless overridden. Prevents
* the real `npx skills` subprocess from firing in the test suite, keeping
@@ -941,221 +839,12 @@ describe('runInit', () => {
expect(output).toContain('.mcp.json');
expect(output).toContain('.cursor/mcp.json');
});
-
- it('renders launch.json beside the Claude MCP entry, not in the legacy warning block', async () => {
- mkdirSync(dirname(cursorConfigPath()), { recursive: true });
- mkdirSync(join(testDir, '.cursor'), { recursive: true });
- writeFileSync(join(testDir, '.mcp.json'), JSON.stringify({ mcpServers: {} }, null, 2));
- writeFileSync(
- join(testDir, '.cursor', 'mcp.json'),
- JSON.stringify({ mcpServers: {} }, null, 2),
- );
-
- const result = await runInitForTest({ editors: ['claude', 'cursor'] });
- const output = formatInitResult(result, testDir);
-
- const claudeIndex = output.indexOf('Claude');
- const launchJsonIndex = output.indexOf('launch.json');
- const legacyIndex = output.indexOf('Project MCP configs found:');
-
- expect(output).toContain('app preview server');
- expect(claudeIndex).toBeGreaterThanOrEqual(0);
- expect(launchJsonIndex).toBeGreaterThan(claudeIndex);
- expect(legacyIndex).toBeGreaterThan(launchJsonIndex);
- });
});
// -----------------------------------------------------------------------
// Claude launch.json scaffolding
// -----------------------------------------------------------------------
- describe('launch.json scaffolding', () => {
- it('writes a fresh .claude/launch.json pointing at open-knowledge ui', async () => {
- const result = await runInitForTest();
-
- expect(result.launchJson).toBeDefined();
- expect(result.launchJson?.action).toBe('created');
-
- const configPath = join(testDir, '.claude', 'launch.json');
- expect(existsSync(configPath)).toBe(true);
- const parsed = JSON.parse(readFileSync(configPath, 'utf-8'));
-
- expect(parsed.configurations).toHaveLength(1);
- assertChainEntry(parsed.configurations[0]);
- });
-
- it('overwrites a stale open-knowledge-ui entry by default', async () => {
- const configPath = join(testDir, '.claude', 'launch.json');
- mkdirSync(join(testDir, '.claude'), { recursive: true });
- writeFileSync(
- configPath,
- JSON.stringify(
- {
- version: '0.0.1',
- configurations: [
- {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['open-knowledge', 'start'],
- port: 3000,
- },
- ],
- },
- null,
- 2,
- ),
- );
-
- const result = await runInitForTest();
- expect(result.launchJson?.action).toBe('merged');
-
- const parsed = JSON.parse(readFileSync(configPath, 'utf-8'));
- assertChainEntry(parsed.configurations[0]);
- });
-
- it('writes a local dev launch target when --dev-mcp is enabled', async () => {
- enableDevMcp();
- const result = await runInitForTest({ devMcp: true });
-
- expect(result.launchJson?.action).toBe('created');
-
- const parsed = JSON.parse(readFileSync(join(testDir, '.claude', 'launch.json'), 'utf-8'));
- expect(parsed.configurations).toHaveLength(1);
- assertChainEntry(parsed.configurations[0], { devDist: devDistPath() });
- });
-
- it('rewrites an up-to-date open-knowledge-ui entry', async () => {
- const configPath = join(testDir, '.claude', 'launch.json');
- mkdirSync(join(testDir, '.claude'), { recursive: true });
- writeFileSync(
- configPath,
- JSON.stringify(
- {
- version: '0.0.1',
- configurations: [
- {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['@inkeep/open-knowledge', 'ui'],
- port: LAUNCH_JSON_PORT,
- autoPort: true,
- },
- ],
- },
- null,
- 2,
- ),
- );
-
- const result = await runInitForTest();
- expect(result.launchJson?.action).toBe('merged');
- });
-
- it('overwrites the published launch target in dev mode', async () => {
- const configPath = join(testDir, '.claude', 'launch.json');
- mkdirSync(join(testDir, '.claude'), { recursive: true });
- writeFileSync(
- configPath,
- JSON.stringify(
- {
- version: '0.0.1',
- configurations: [
- {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['@inkeep/open-knowledge', 'ui'],
- port: LAUNCH_JSON_PORT,
- autoPort: true,
- },
- ],
- },
- null,
- 2,
- ),
- );
-
- enableDevMcp();
- const result = await runInitForTest({ devMcp: true });
- expect(result.launchJson?.action).toBe('merged');
-
- const parsed = JSON.parse(readFileSync(configPath, 'utf-8'));
- assertChainEntry(parsed.configurations[0], { devDist: devDistPath() });
- });
-
- it('merges the new entry into an existing launch.json with other configurations', async () => {
- const configPath = join(testDir, '.claude', 'launch.json');
- mkdirSync(join(testDir, '.claude'), { recursive: true });
- writeFileSync(
- configPath,
- JSON.stringify(
- {
- version: '0.0.1',
- configurations: [
- {
- name: 'some-other-server',
- runtimeExecutable: 'node',
- runtimeArgs: ['./server.js'],
- },
- ],
- },
- null,
- 2,
- ),
- );
-
- const result = await runInitForTest();
- expect(result.launchJson?.action).toBe('created');
-
- const parsed = JSON.parse(readFileSync(configPath, 'utf-8'));
- expect(parsed.configurations).toHaveLength(2);
- const ok = parsed.configurations.find(
- (c: { name: string }) => c.name === 'open-knowledge-ui',
- );
- assertChainEntry(ok);
- expect(ok.port).toBe(LAUNCH_JSON_PORT);
- expect(ok.autoPort).toBe(true);
- });
-
- it('does NOT scaffold launch.json when Claude is not among selected editors', async () => {
- const result = await runInitForTest({ editors: ['cursor'] });
- expect(result.launchJson).toBeUndefined();
- expect(existsSync(join(testDir, '.claude', 'launch.json'))).toBe(false);
- });
-
- it('emits the powershell `# ok-ui-win-v1` chain on Windows', () => {
- // Windows has no `/bin/sh`, so the preview pane cannot launch the posix
- // chain. `platformName` is injected (rather than spoofing the ambient
- // `process.platform`) since a machine always writes its own platform's
- // shape; the option exists purely to pin either shape under test.
- const result = scaffoldLaunchJson(testDir, { platformName: 'win32' });
- expect(result.action).toBe('created');
-
- const parsed = JSON.parse(readFileSync(join(testDir, '.claude', 'launch.json'), 'utf-8'));
- expect(parsed.configurations).toHaveLength(1);
- const entry = parsed.configurations[0];
- expect(entry.name).toBe('open-knowledge-ui');
- expect(entry.runtimeExecutable).toBe('powershell');
- expect(entry.runtimeArgs.slice(0, 3)).toEqual(['-NoProfile', '-NonInteractive', '-Command']);
- const chain = entry.runtimeArgs[3];
- expect(chain).toContain(LAUNCH_UI_WIN_CHAIN_SENTINEL);
- expect(chain).toContain('start --ui-port');
- expect(chain).not.toContain('/bin/sh');
- // The body must carry zero double-quote characters: it travels as one
- // argv element through the host's Windows argument-quoting layer, and any
- // `"` would be mangled there.
- expect(chain).not.toContain('"');
- expect(entry.port).toBe(LAUNCH_JSON_PORT);
- expect(entry.autoPort).toBe(true);
- });
-
- it('emits the posix `/bin/sh` chain when the platform is macOS', () => {
- const result = scaffoldLaunchJson(testDir, { platformName: 'darwin' });
- expect(result.action).toBe('created');
- const parsed = JSON.parse(readFileSync(join(testDir, '.claude', 'launch.json'), 'utf-8'));
- assertChainEntry(parsed.configurations[0]);
- });
- });
-
// -----------------------------------------------------------------------
// Zero project-root file writes
// -----------------------------------------------------------------------
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index de668baab..c84b3a829 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -12,14 +12,7 @@
* Missing editor config roots are skipped so init does not create new user-home
* directories for tools that are not installed.
*/
-import {
- existsSync,
- mkdirSync,
- readFileSync,
- realpathSync,
- statSync,
- writeFileSync,
-} from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
import { inspect } from 'node:util';
@@ -89,11 +82,9 @@ import {
type EditorId,
type EditorMcpTarget,
type McpInstallOptions,
- resolveDevCliDistPath,
resolveEditorTargets,
} from './editors.ts';
import { existingFileMode, isCrlfDominant } from './jsonc-surgical.ts';
-import { LAUNCH_JSON_PORT } from './ui.ts';
// ---------------------------------------------------------------------------
// Config I/O — generic across all editors
@@ -612,7 +603,7 @@ async function promptSharingMode(
): Promise<'shared' | 'local-only'> {
return select<'shared' | 'local-only'>({
message:
- 'How do you want to handle OpenKnowledge config files (.ok/, .mcp.json, project skills, launch.json)?',
+ 'How do you want to handle OpenKnowledge config files (.ok/, .mcp.json, project skills)?',
default: defaultMode,
choices: [
{
@@ -849,8 +840,6 @@ interface InitCommandResult {
skillInstall?: InstallUserSkillResult | 'declined';
/** Content preview result (undefined if preview failed or was not run). */
preview?: PreviewResult;
- /** Claude launch.json result (undefined when Claude is not a selected editor). */
- launchJson?: LaunchJsonResult;
/** `true` if `ensureProjectGit` ran `git init` during this invocation. */
didGitInit: boolean;
/** `true` if a project-root `.gitignore` was seeded during this invocation.
@@ -936,272 +925,15 @@ export type SharingOutcome =
};
// ---------------------------------------------------------------------------
-// Claude launch.json scaffolding
+// Claude launch.json — OK no longer scaffolds one. Claude Code Desktop's
+// in-app Browser pane opens the preview URL directly (`preview_start({url})`
+// + `navigate({url})`), and `preview_url` autostarts the OK UI. The config
+// name survives only so `ok deinit` and the `ok start` repair sweep can
+// remove any pre-existing entry from a shared `.claude/launch.json`.
// ---------------------------------------------------------------------------
-const LAUNCH_JSON_VERSION = '0.0.1';
export const LAUNCH_CONFIG_NAME = 'open-knowledge-ui';
-/**
- * Canonical published-mode `runtimeArgs` for the `open-knowledge-ui` launch
- * config. Pinned to `@latest` so Claude Code Desktop's preview-pane spawn
- * can't be silently downgraded by npm's engine-aware sort in
- * `npm-pick-manifest`; `-y` suppresses the install-confirm prompt under the
- * non-TTY preview spawn. Single source of truth — `scaffoldLaunchJson`
- * writes this shape and `repair-launch-json.ts` classifies against it.
- */
-export const LAUNCH_JSON_CANONICAL_ARGS: readonly string[] = [
- '-y',
- '@inkeep/open-knowledge@latest',
- 'ui',
-];
-
-/**
- * Version sentinel for the published-mode launch.json recipe. The first line
- * of the chain doubles as a shell comment and the stamp `classifyLaunchJsonEntry`
- * matches on. Bump the suffix (`v2`, …) on any structurally-different chain so
- * the repair sweep recognizes stale text and rewrites it forward.
- */
-export const LAUNCH_UI_CHAIN_SENTINEL = '# ok-ui-v1';
-
-/**
- * Published-mode `.claude/launch.json` recipe — the preview pane spawns this
- * to bring the worktree's editor up. Mirrors the proven `# ok-mcp-v1` chain
- * (editors.ts) — resolves the Desktop bundle first (user → system Applications),
- * then npx, then version-manager `npx` paths — but runs **`ok start`**, not
- * bare `ok ui`, so the folder gets its OWN collab server (the worktree fix).
- * `ok start` connects-instead-of-erroring on a live lock (`--ui-port` path), so
- * one committed recipe is safe on both the main checkout and a fresh worktree.
- *
- * Port handling: the pane passes its watched port via `PORT` env. We capture it
- * as `UIPORT`, defaulting to the launch.json `port` (`LAUNCH_JSON_PORT`) when
- * `PORT` is somehow absent — the pane probes that same port, so the default
- * matches what it watches. `unset PORT` so the collab server kernel-allocates
- * instead of fighting its UI sibling for the env port (`ok start` also drops
- * env-`PORT` for the collab when `--ui-port` is set, belt-and-braces). We ALWAYS
- * pass `--ui-port` — that is what arms `ok start`'s connect-instead-of-exit-1
- * fallback, so a missing `PORT` can never leave the main checkout running a bare
- * `ok start` that exits 1 and breaks the preview pane. Ports are numeric;
- * `"$UIPORT"` is quoted for safety.
- *
- * Portable + public-safe: no machine-specific absolute path is baked in; the
- * bundle is resolved at spawn time. Same chain ships in the git-committed
- * scaffold and the per-open desktop reclaim (which force-writes this shape).
- */
-export const LAUNCH_UI_CHAIN_V1 = `${LAUNCH_UI_CHAIN_SENTINEL}
-UIPORT="\${PORT:-${LAUNCH_JSON_PORT}}"
-unset PORT
-USER_BUNDLE="$HOME/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
-[ -f "$USER_BUNDLE" ] && [ -x "$USER_BUNDLE" ] && exec "$USER_BUNDLE" start --ui-port "$UIPORT"
-BUNDLE="/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh"
-[ -f "$BUNDLE" ] && [ -x "$BUNDLE" ] && exec "$BUNDLE" start --ui-port "$UIPORT"
-command -v npx >/dev/null 2>&1 && exec npx -y @inkeep/open-knowledge@latest start --ui-port "$UIPORT"
-for d in "$HOME/.nvm/versions/node"/*/bin "$HOME/.fnm/node-versions"/*/installation/bin "$HOME/.asdf/installs/nodejs"/*/bin /opt/homebrew/bin /usr/local/bin "$HOME/.local/bin" "$HOME/.volta/bin"; do
- [ -f "$d/npx" ] && [ -x "$d/npx" ] && exec "$d/npx" -y @inkeep/open-knowledge@latest start --ui-port "$UIPORT"
-done
-echo "OpenKnowledge: install OK Desktop or Node.js 24+, then restart your editor" >&2
-exit 127`;
-
-/**
- * Version sentinel for the Windows published-mode launch.json recipe — the
- * PowerShell sibling of `LAUNCH_UI_CHAIN_SENTINEL`. First line of the chain,
- * doubling as a PowerShell comment. Bump the suffix (`win-v2`, …) on any
- * structurally-different chain so the repair sweep rewrites stale text forward.
- */
-export const LAUNCH_UI_WIN_CHAIN_SENTINEL = '# ok-ui-win-v1';
-
-/**
- * Windows published-mode `.claude/launch.json` recipe — the PowerShell member
- * of the two-shape canonical set (Unix sibling: `LAUNCH_UI_CHAIN_V1`). Claude
- * Code Desktop's preview pane spawns this to bring the folder's editor up on
- * Windows, where `/bin/sh` does not exist. Mirrors the proven `# ok-mcp-win-v1`
- * chain (`CHAIN_WIN_V1` in editors.ts) — resolves the npm-global `ok.cmd` shim
- * first, then `npx.cmd` from PATH, then explicit version-manager/installer
- * dirs — but runs `ok start --ui-port`, not `ok mcp`, so the opened folder
- * gets its OWN collab server (the worktree fix). No OK Desktop bundle branches:
- * OK Desktop does not ship on Windows, so `npm i -g @inkeep/open-knowledge` is
- * the primary install persona, and the pinned global shim outranks `npx
- * @latest` so the launched UI resolves to the SAME installed version as the
- * user's hand-run `ok`.
- *
- * Port handling mirrors the Unix chain: capture the pane's watched `PORT` env
- * into `$UIPORT`, defaulting to `LAUNCH_JSON_PORT` (the same port the pane
- * probes) when `PORT` is absent, then clear `PORT` so the auto-spawned collab
- * server kernel-allocates instead of fighting its UI sibling for the env port.
- * `--ui-port` is always passed — that arms `ok start`'s
- * connect-instead-of-exit-1 fallback so one committed recipe is safe on both
- * the main checkout and a fresh worktree.
- *
- * Each PowerShell detail is load-bearing exactly as documented on `CHAIN_WIN_V1`:
- * `powershell` (5.1, preinstalled everywhere) not `cmd`/`pwsh`; `-NoProfile
- * -NonInteractive` for a deterministic, fail-loud spawn; zero double-quote
- * characters in the body (single-quoted literals + `Join-Path` only) so the
- * script survives the host's argument-quoting layer as one argv element;
- * `.cmd` shims only (a `.ps1` re-enters execution policy); `exit
- * $LASTEXITCODE` after each invocation (PowerShell has no `exec`); null-guarded
- * env probes (`Join-Path` on an unset var throws); and the PATHEXT guard on
- * line 2 — Electron hosts spawn with a PATHEXT that omits `.CMD`, which makes
- * `& <path>\ok.cmd` a SILENT no-op, so the guard prepends the standard
- * executable extensions.
- */
-export const LAUNCH_UI_WIN_CHAIN_V1 = `${LAUNCH_UI_WIN_CHAIN_SENTINEL}
-if ($env:PATHEXT -notmatch 'CMD') { $env:PATHEXT = '.COM;.EXE;.BAT;.CMD;' + $env:PATHEXT }
-$UIPORT = if ($env:PORT) { $env:PORT } else { '${LAUNCH_JSON_PORT}' }
-Remove-Item Env:PORT -ErrorAction SilentlyContinue
-if ($env:APPDATA) {
- $shim = Join-Path $env:APPDATA 'npm\\ok.cmd'
- if (Test-Path -LiteralPath $shim -PathType Leaf) { & $shim start --ui-port $UIPORT; exit $LASTEXITCODE }
-}
-$ok = Get-Command ok.cmd -CommandType Application -ErrorAction SilentlyContinue
-if ($ok) { & $ok.Source start --ui-port $UIPORT; exit $LASTEXITCODE }
-$npx = Get-Command npx.cmd -CommandType Application -ErrorAction SilentlyContinue
-if ($npx) { & $npx.Source -y '@inkeep/open-knowledge@latest' start --ui-port $UIPORT; exit $LASTEXITCODE }
-$dirs = @()
-if ($env:ProgramFiles) { $dirs += Join-Path $env:ProgramFiles 'nodejs' }
-if ($env:NVM_SYMLINK) { $dirs += $env:NVM_SYMLINK }
-if ($env:LOCALAPPDATA) {
- $dirs += Join-Path $env:LOCALAPPDATA 'fnm\\aliases\\default'
- $dirs += Join-Path $env:LOCALAPPDATA 'Volta\\bin'
- $dirs += Join-Path $env:LOCALAPPDATA 'pnpm'
-}
-if ($env:USERPROFILE) { $dirs += Join-Path $env:USERPROFILE 'scoop\\shims' }
-foreach ($d in $dirs) {
- $probe = Join-Path $d 'npx.cmd'
- if (Test-Path -LiteralPath $probe -PathType Leaf) { & $probe -y '@inkeep/open-knowledge@latest' start --ui-port $UIPORT; exit $LASTEXITCODE }
-}
-[Console]::Error.WriteLine('OpenKnowledge: install Node.js 24+ (npm i -g @inkeep/open-knowledge), then restart your editor')
-exit 127`;
-
-type LaunchJsonAction = 'created' | 'merged' | 'failed';
-
-export interface LaunchJsonResult {
- action: LaunchJsonAction;
- configPath: string;
- error?: string;
-}
-
-/**
- * Scaffold or merge a `.claude/launch.json` entry so that Claude's
- * built-in preview browser can start the OpenKnowledge dev server via
- * `preview_start("open-knowledge-ui")`.
- *
- * `runtimeArgs` launches `open-knowledge ui` (not `open-knowledge start`) —
- * the UI sibling-process is what the preview pane renders; collab runs in a
- * separate `open-knowledge start` process auto-spawned by `ok ui` via the
- * MCP stdio path.
- *
- * - File missing → create with the OK entry
- * - File exists, no OK → merge the entry into configurations
- * - File exists, has OK → replace with current defaults
- */
-export function scaffoldLaunchJson(
- cwd: string,
- installOptions: McpInstallOptions = {},
-): LaunchJsonResult {
- const configPath = join(cwd, '.claude', 'launch.json');
- // `port` deliberately differs from `DEFAULT_UI_PORT` so Claude's spawn of the
- // UI sibling (with `PORT=LAUNCH_JSON_PORT` env) goes through the lock-collision
- // proxy branch rather than the same-port "already-running" exit-0 branch (which
- // empirically fails Claude's preview pane). `autoPort: true` is the additional
- // fallback when `LAUNCH_JSON_PORT` itself is occupied — Claude picks a free
- // port, passes via `PORT`, still routes through the proxy branch. Full pairing
- // rationale on `LAUNCH_JSON_PORT` in `ui.ts`.
- //
- // The recipe runs `ok start` (not bare `ok ui`) so the opened folder —
- // crucially, a worktree — gets its OWN collab server, not just a UI. `ok
- // start` connects-instead-of-erroring on a live lock (the `--ui-port` path),
- // so the same committed recipe is correct on both the main checkout and a
- // fresh worktree. The published recipe uses the local platform's interpreter:
- // a `/bin/sh` chain (`# ok-ui-v1`) on macOS/Linux, a `powershell` chain
- // (`# ok-ui-win-v1`) on Windows, since `/bin/sh` does not exist there and the
- // preview pane could not otherwise launch the UI. Dev mode stays `/bin/sh`
- // (monorepo development is Unix-only) and pins the chain's exec to the local
- // CLI dist. Every shape carries its platform's sentinel so the repair sweep
- // recognizes them.
- //
- // `resolveDevCliDistPath()` is resolved LAZILY (dev branch only) — it throws
- // when the repo root can't be inferred, which is the normal case for the
- // published recipe + the desktop reclaim, so it must never run in that path.
- const buildDevChain = () => `${LAUNCH_UI_CHAIN_SENTINEL}
-UIPORT="\${PORT:-${LAUNCH_JSON_PORT}}"
-unset PORT
-exec node "${resolveDevCliDistPath()}" start --ui-port "$UIPORT"`;
- // Writers never set `platformName`; a machine always emits its own platform's
- // shape. Tests inject it to pin either shape on any host.
- const platformName = installOptions.platformName ?? process.platform;
- const entry: {
- name: string;
- runtimeExecutable: string;
- runtimeArgs: string[];
- port: number;
- autoPort: true;
- } =
- installOptions.mode === 'dev'
- ? {
- name: LAUNCH_CONFIG_NAME,
- runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', buildDevChain()],
- port: LAUNCH_JSON_PORT,
- autoPort: true,
- }
- : platformName === 'win32'
- ? {
- name: LAUNCH_CONFIG_NAME,
- runtimeExecutable: 'powershell',
- runtimeArgs: ['-NoProfile', '-NonInteractive', '-Command', LAUNCH_UI_WIN_CHAIN_V1],
- port: LAUNCH_JSON_PORT,
- autoPort: true,
- }
- : {
- name: LAUNCH_CONFIG_NAME,
- runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', LAUNCH_UI_CHAIN_V1],
- port: LAUNCH_JSON_PORT,
- autoPort: true,
- };
-
- try {
- assertProjectPathSafe(configPath, cwd);
- if (!existsSync(configPath)) {
- mkdirSync(dirname(configPath), { recursive: true });
- const content = { version: LAUNCH_JSON_VERSION, configurations: [entry] };
- writeFileSync(configPath, `${JSON.stringify(content, null, 2)}\n`, 'utf-8');
- return { action: 'created', configPath };
- }
-
- const raw = readFileSync(configPath, 'utf-8').trim();
- const parsed = raw ? JSON.parse(raw) : {};
- if (!isObject(parsed)) {
- return { action: 'failed', configPath, error: 'launch.json root is not an object' };
- }
-
- const configs: unknown[] = Array.isArray(parsed.configurations) ? parsed.configurations : [];
- const existingIdx = configs.findIndex(
- (c) => isObject(c) && (c as Record<string, unknown>).name === LAUNCH_CONFIG_NAME,
- );
-
- if (existingIdx >= 0) {
- configs[existingIdx] = entry;
- } else {
- configs.push(entry);
- }
-
- const updated = {
- ...parsed,
- version: parsed.version ?? LAUNCH_JSON_VERSION,
- configurations: configs,
- };
- writeFileSync(configPath, `${JSON.stringify(updated, null, 2)}\n`, 'utf-8');
- return { action: existingIdx >= 0 ? 'merged' : 'created', configPath };
- } catch (err) {
- return {
- action: 'failed',
- configPath,
- error: err instanceof Error ? err.message : String(err),
- };
- }
-}
-
// ---------------------------------------------------------------------------
// Per-editor write logic
// ---------------------------------------------------------------------------
@@ -1595,7 +1327,6 @@ export interface UserMcpConfigsOptions {
* - `ensureProjectGit` — would `git init` wherever `cwd` is (packaged Electron
* apps have `process.cwd() === '/'` by default)
* - `initContent` — scaffolds `.ok/` in a project
- * - `scaffoldLaunchJson` — writes `.claude/launch.json`
* - `upsertRootInstructions` — mutates `AGENTS.md` / `CLAUDE.md`
* - `collectLegacyProjectConfig` — scans for `.mcp.json` / `.cursor/mcp.json`
*
@@ -2036,15 +1767,6 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
// Suppress paths we just wrote during project-scope install.
.filter((result) => !writtenProjectPaths.has(result.path));
- // 3. Scaffold .claude/launch.json when Claude is a selected editor.
- // hasClaude checks availableTargets (existence of ~/.claude/), not the full
- // targets list, so scope=project writes .mcp.json but skips launch.json when
- // ~/.claude/ is absent (e.g. CI). This is intentional: launch.json targets a
- // running editor instance, not a committed project artifact.
- const hasClaude = availableTargets.some((target) => target.id === 'claude');
- const launchJson =
- hasClaude && !skipMcp ? scaffoldLaunchJson(projectRoot, installOptions) : undefined;
-
// `ok init` does not write to root AGENTS.md / CLAUDE.md. Behavioral
// guidance ships via (1) per-tool MCP tool descriptions and (2) the
// user-global Agent Skill installed via `installUserSkill` from
@@ -2126,7 +1848,6 @@ export async function runInit(options: InitCommandOptions = {}): Promise<InitCom
editors: editorResults,
projectSkills: projectSkillResults,
legacyProjectConfigs,
- launchJson,
skillInstall,
didGitInit: gitResult.didInit,
rootGitignoreCreated,
@@ -2278,20 +1999,6 @@ export function formatInitResult(result: InitCommandResult, cwd: string): string
result.editors.length > 0 && result.editors.every((e) => e.action === 'skipped-flag');
const allSkippedMissing =
result.editors.length > 0 && result.editors.every((e) => e.action === 'skipped-missing');
- const formatLaunchJsonSummary = (launchJson: LaunchJsonResult): string => {
- const displayPath = launchJson.configPath.startsWith(cwd)
- ? relative(cwd, launchJson.configPath)
- : launchJson.configPath;
- switch (launchJson.action) {
- case 'created':
- return ` app preview server ${displayPath} configured for Claude Code Desktop embedded browser`;
- case 'merged':
- return ` app preview server ${displayPath} updated for Claude Code Desktop embedded browser`;
- case 'failed':
- return ` app preview server ${displayPath} FAILED: ${launchJson.error}`;
- }
- };
-
// Auto-git-init disclosure — surfaced when ensureProjectGit ran
// `git init` during this invocation. Silent when the project already had
// `.git/`.
@@ -2394,9 +2101,6 @@ export function formatInitResult(result: InitCommandResult, cwd: string): string
void _exhaustive;
}
}
- if (editor.editorId === 'claude' && result.launchJson) {
- lines.push(formatLaunchJsonSummary(result.launchJson));
- }
}
if (result.projectScopeUnsupportedLabels && result.projectScopeUnsupportedLabels.length > 0) {
const names = result.projectScopeUnsupportedLabels.join(', ');
diff --git a/packages/cli/src/commands/repair-launch-json.test.ts b/packages/cli/src/commands/repair-launch-json.test.ts
index b2933bca8..384ae00f4 100644
--- a/packages/cli/src/commands/repair-launch-json.test.ts
+++ b/packages/cli/src/commands/repair-launch-json.test.ts
@@ -1,242 +1,14 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
-import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
-import { LAUNCH_UI_CHAIN_SENTINEL, LAUNCH_UI_CHAIN_V1, LAUNCH_UI_WIN_CHAIN_V1 } from './init.ts';
-import {
- classifyLaunchJsonEntry,
- type LaunchJsonRepairLogEvent,
- repairLaunchJson,
-} from './repair-launch-json.ts';
+import { type LaunchJsonRepairLogEvent, repairLaunchJson } from './repair-launch-json.ts';
-// Current canonical recipe — the `# ok-ui-v1` `/bin/sh` chain that runs
-// `ok start` (not bare `ok ui`), so a worktree gets its own collab server.
-const CANONICAL_ENTRY = {
- name: 'open-knowledge-ui',
- runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', LAUNCH_UI_CHAIN_V1],
- port: 50219,
- autoPort: true,
-};
-
-// Published shape (`npx @latest ui`). Launched a bare UI with no collab
-// server — now a `legacy-bare` form that migrates forward to the chain.
-const LEGACY_AT_LATEST_ENTRY = {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['-y', '@inkeep/open-knowledge@latest', 'ui'],
- port: 50219,
- autoPort: true,
-};
-
-const LEGACY_BARE_ENTRY = {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['@inkeep/open-knowledge', 'ui'],
- port: 50219,
- autoPort: true,
-};
-
-const LEGACY_BARE_WITH_Y_ENTRY = {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['-y', '@inkeep/open-knowledge', 'ui'],
- port: 50219,
- autoPort: true,
-};
-
-// Current canonical Windows recipe — the `# ok-ui-win-v1` `powershell` chain a
-// Windows `ok init` commits. A macOS/Linux checkout that reads this shared file
-// MUST classify it canonical, or the two platforms' startup repair sweeps would
-// rewrite the committed entry back and forth forever.
-const CANONICAL_WIN_ENTRY = {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'powershell',
- runtimeArgs: ['-NoProfile', '-NonInteractive', '-Command', LAUNCH_UI_WIN_CHAIN_V1],
- port: 50219,
- autoPort: true,
-};
-
-/** Assert a rewritten entry is the current canonical chain shape. */
-function expectCanonicalChain(entry: { runtimeExecutable: string; runtimeArgs: string[] }): void {
- expect(entry.runtimeExecutable).toBe('/bin/sh');
- expect(entry.runtimeArgs.slice(0, 2)).toEqual(['-l', '-c']);
- expect(entry.runtimeArgs[2]).toContain(LAUNCH_UI_CHAIN_SENTINEL);
- expect(entry.runtimeArgs[2]).toContain('start');
-}
-
-describe('classifyLaunchJsonEntry', () => {
- it('returns "canonical" for the current ok-start `# ok-ui-v1` chain', () => {
- expect(classifyLaunchJsonEntry(CANONICAL_ENTRY)).toBe('canonical');
- });
-
- it('returns "canonical" for the current Windows `# ok-ui-win-v1` powershell chain', () => {
- expect(classifyLaunchJsonEntry(CANONICAL_WIN_ENTRY)).toBe('canonical');
- });
-
- it('recognizes BOTH platform canonicals regardless of the host platform (no ping-pong)', () => {
- // The load-bearing mutual-recognition invariant: a macOS user and a Windows
- // user sharing one committed `.claude/launch.json` must both see the other's
- // committed shape as canonical, so neither startup repair sweep rewrites it.
- // `classifyLaunchJsonEntry` is platform-independent by construction — assert
- // it on every host, spoofing `process.platform` both ways to prove it never
- // consults the ambient platform.
- const originalPlatform = process.platform;
- try {
- for (const spoofed of ['darwin', 'linux', 'win32'] as const) {
- Object.defineProperty(process, 'platform', { value: spoofed, configurable: true });
- expect(classifyLaunchJsonEntry(CANONICAL_ENTRY)).toBe('canonical');
- expect(classifyLaunchJsonEntry(CANONICAL_WIN_ENTRY)).toBe('canonical');
- }
- } finally {
- Object.defineProperty(process, 'platform', {
- value: originalPlatform,
- configurable: true,
- });
- }
- });
-
- it('returns "legacy-bare" for an older `# ok-ui-win-vN` powershell chain we no longer ship', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'powershell',
- runtimeArgs: ['-NoProfile', '-NonInteractive', '-Command', '# ok-ui-win-v0\nok start'],
- }),
- ).toBe('legacy-bare');
- });
-
- it('returns "preserved" for a foreign powershell command without our sentinel', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'powershell',
- runtimeArgs: ['-NoProfile', '-Command', 'Start-Process my-own-launcher'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "legacy-bare" for the pre-D5 published `npx @latest ui` shape', () => {
- expect(classifyLaunchJsonEntry(LEGACY_AT_LATEST_ENTRY)).toBe('legacy-bare');
- });
-
- it('returns "legacy-bare" for an older `# ok-ui-vN` chain we no longer ship', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', '# ok-ui-v0\nexec ok ui'],
- }),
- ).toBe('legacy-bare');
- });
-
- it('returns "preserved" for a foreign /bin/sh command without our sentinel', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-c', 'my-own-launcher --flag'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "legacy-bare" for the unpinned 2-arg npx shape', () => {
- expect(classifyLaunchJsonEntry(LEGACY_BARE_ENTRY)).toBe('legacy-bare');
- });
-
- it('returns "legacy-bare" for the unpinned -y 3-arg npx shape', () => {
- expect(classifyLaunchJsonEntry(LEGACY_BARE_WITH_Y_ENTRY)).toBe('legacy-bare');
- });
-
- it('returns "preserved" when the package is pinned to @beta', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['-y', '@inkeep/open-knowledge@beta', 'ui'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" when the package is pinned to a concrete version', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['-y', '@inkeep/[email protected]', 'ui'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" when the bare @latest spec omits the -y flag', () => {
- // Forward-migration only — entries that already pin @latest but happen
- // to lack `-y` are user-curated; leave them. Mirrors the MCP classifier.
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['@inkeep/open-knowledge@latest', 'ui'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" for dev-mode (runtimeExecutable=node, dist path)', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'node',
- runtimeArgs: ['/path/to/packages/cli/dist/cli.mjs', 'ui'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" for an arbitrary custom command', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'my-wrapper',
- runtimeArgs: ['ui'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" for legacy bare shape with extra trailing args', () => {
- // Foreign-customized — e.g. someone appended `--port 9999`. Don't touch.
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['@inkeep/open-knowledge', 'ui', '--port', '9999'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" for entries with non-array runtimeArgs', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: 'ui',
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" for entries with non-string runtimeExecutable', () => {
- expect(
- classifyLaunchJsonEntry({
- name: 'open-knowledge-ui',
- runtimeExecutable: 42,
- runtimeArgs: ['@inkeep/open-knowledge', 'ui'],
- }),
- ).toBe('preserved');
- });
-
- it('returns "preserved" for empty entries', () => {
- expect(classifyLaunchJsonEntry({})).toBe('preserved');
- });
-});
-
-describe('repairLaunchJson', () => {
+// OK no longer scaffolds `.claude/launch.json`; the `ok start` repair sweep now
+// REMOVES any `open-knowledge-ui` entry a prior OK version left behind. The
+// surgical removal itself is covered in launch-json-removal.test.ts; here we
+// pin the sweep wrapper's outcomes, its structured event, and the reclaim gate.
+describe('repairLaunchJson (remove sweep)', () => {
let testDir: string;
let projectDir: string;
let logEvents: LaunchJsonRepairLogEvent[];
@@ -266,293 +38,66 @@ describe('repairLaunchJson', () => {
return path;
}
- it('rewrites a legacy bare entry forward to the canonical @latest shape', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [LEGACY_BARE_ENTRY],
- });
+ const OK_ENTRY = {
+ name: 'open-knowledge-ui',
+ runtimeExecutable: '/bin/sh',
+ runtimeArgs: ['-l', '-c', '# ok-ui-v1\nexec ok start'],
+ port: 39848,
+ };
+ const FOREIGN = {
+ name: 'some-other-tool',
+ runtimeExecutable: 'node',
+ runtimeArgs: ['./server.js'],
+ };
+
+ it("removes OK's entry, preserving co-located configurations", () => {
+ const configPath = writeLaunchJson({ version: '0.0.1', configurations: [FOREIGN, OK_ENTRY] });
const result = repairLaunchJson({ projectDir, logger });
- expect(result.outcome.outcome).toBe('repaired');
+ expect(result.outcome.outcome).toBe('removed');
expect(result.outcome.configPath).toBe(configPath);
expect(result.repairedCount).toBe(1);
const written = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(written.configurations).toHaveLength(1);
- expectCanonicalChain(written.configurations[0]);
- expect(written.configurations[0].name).toBe('open-knowledge-ui');
-
- expect(logEvents).toContainEqual({
- event: 'launch-json-repair-applied',
- configPath,
- });
- });
-
- it('rewrites the -y legacy variant forward', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [LEGACY_BARE_WITH_Y_ENTRY],
- });
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('repaired');
- const written = JSON.parse(readFileSync(configPath, 'utf-8'));
- expectCanonicalChain(written.configurations[0]);
- });
-
- it('leaves an already-canonical entry untouched (outcome=canonical, no rewrite)', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [CANONICAL_ENTRY],
- });
- const before = readFileSync(configPath, 'utf-8');
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('canonical');
- expect(result.repairedCount).toBe(0);
- expect(readFileSync(configPath, 'utf-8')).toBe(before);
- expect(logEvents.filter((e) => e.event === 'launch-json-repair-applied')).toHaveLength(0);
- });
-
- it('leaves a Windows-committed canonical entry untouched on this host (no ping-pong)', () => {
- // The sweep-level guarantee behind the classifier's mutual recognition: a
- // `.claude/launch.json` committed by a Windows teammate must survive an
- // `ok start` repair sweep on macOS/Linux with zero rewrite, and vice versa.
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [CANONICAL_WIN_ENTRY],
- });
- const before = readFileSync(configPath, 'utf-8');
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('canonical');
- expect(result.repairedCount).toBe(0);
- expect(readFileSync(configPath, 'utf-8')).toBe(before);
- expect(logEvents.filter((e) => e.event === 'launch-json-repair-applied')).toHaveLength(0);
+ expect(written.configurations[0]).toEqual(FOREIGN);
+ expect(logEvents).toContainEqual({ event: 'launch-json-repair-removed', configPath });
});
- it('preserves a @beta-pinned entry (user intent)', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [
- {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'npx',
- runtimeArgs: ['-y', '@inkeep/open-knowledge@beta', 'ui'],
- port: 50219,
- autoPort: true,
- },
- ],
- });
- const before = readFileSync(configPath, 'utf-8');
+ it("removes the whole file when OK's entry was the only configuration", () => {
+ const configPath = writeLaunchJson({ version: '0.0.1', configurations: [OK_ENTRY] });
const result = repairLaunchJson({ projectDir, logger });
- expect(result.outcome.outcome).toBe('preserved');
- expect(readFileSync(configPath, 'utf-8')).toBe(before);
- });
-
- it('preserves a dev-mode entry (runtimeExecutable=node)', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [
- {
- name: 'open-knowledge-ui',
- runtimeExecutable: 'node',
- runtimeArgs: ['/some/dist/cli.mjs', 'ui'],
- port: 50219,
- autoPort: true,
- },
- ],
- });
- const before = readFileSync(configPath, 'utf-8');
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('preserved');
- expect(readFileSync(configPath, 'utf-8')).toBe(before);
- });
-
- it('preserves co-located non-OK configurations when rewriting', () => {
- // Real launch.json files often have other dev tooling configs alongside.
- // The repair sweep must rewrite only our entry and leave the rest intact.
- const foreignConfig = {
- name: 'some-other-tool',
- runtimeExecutable: 'node',
- runtimeArgs: ['./server.js'],
- port: 9001,
- };
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [foreignConfig, LEGACY_BARE_ENTRY],
- });
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('repaired');
- const written = JSON.parse(readFileSync(configPath, 'utf-8'));
- expect(written.configurations).toHaveLength(2);
- expect(
- written.configurations.find((c: { name: string }) => c.name === 'some-other-tool'),
- ).toEqual(foreignConfig);
- const okEntry = written.configurations.find(
- (c: { name: string }) => c.name === 'open-knowledge-ui',
- );
- expectCanonicalChain(okEntry);
+ expect(result.outcome.outcome).toBe('removed-file');
+ expect(result.repairedCount).toBe(1);
+ expect(existsSync(configPath)).toBe(false);
});
- it('reports no-file when .claude/launch.json does not exist', () => {
+ it('reports not-present when no launch.json exists, and does not create one', () => {
const result = repairLaunchJson({ projectDir, logger });
- expect(result.outcome.outcome).toBe('no-file');
+ expect(result.outcome.outcome).toBe('not-present');
expect(result.outcome.configPath).toBe(join(projectDir, '.claude', 'launch.json'));
expect(result.repairedCount).toBe(0);
- expect(logEvents).toHaveLength(0);
- });
-
- it('does not create launch.json when it was absent', () => {
- // Negative-coverage: a sweep that does nothing must not silently scaffold.
- repairLaunchJson({ projectDir, logger });
expect(existsSync(join(projectDir, '.claude', 'launch.json'))).toBe(false);
+ expect(logEvents).toHaveLength(0);
});
- it('reports no-entry when launch.json exists but has no open-knowledge-ui config', () => {
- writeLaunchJson({
- version: '0.0.1',
- configurations: [
- { name: 'some-other-tool', runtimeExecutable: 'node', runtimeArgs: ['./server.js'] },
- ],
- });
+ it('reports not-present when launch.json has no open-knowledge-ui entry', () => {
+ const configPath = writeLaunchJson({ version: '0.0.1', configurations: [FOREIGN] });
+ const before = readFileSync(configPath, 'utf-8');
const result = repairLaunchJson({ projectDir, logger });
- expect(result.outcome.outcome).toBe('no-entry');
+ expect(result.outcome.outcome).toBe('not-present');
expect(result.repairedCount).toBe(0);
+ expect(readFileSync(configPath, 'utf-8')).toBe(before);
});
- it('reports no-entry when configurations is missing entirely', () => {
- writeLaunchJson({ version: '0.0.1' });
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('no-entry');
- });
-
- it('reports read-failed and emits the structured event on malformed JSON', () => {
- const dir = join(projectDir, '.claude');
- mkdirSync(dir, { recursive: true });
- const path = join(dir, 'launch.json');
- writeFileSync(path, '{ not valid json');
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('read-failed');
- expect(typeof result.outcome.error).toBe('string');
- expect(result.outcome.error?.length ?? 0).toBeGreaterThan(0);
-
- const readFailed = logEvents.find((e) => e.event === 'launch-json-repair-read-failed');
- expect(readFailed).toBeDefined();
- expect(readFailed?.configPath).toBe(path);
- expect(typeof readFailed?.error).toBe('string');
- });
-
- it('reports read-failed and emits the structured event on non-object root', () => {
- // Symmetric with the JSON-parse-error branch — both surface
- // structurally-broken files via the same `launch-json-repair-read-failed`
- // event so operators tailing stderr see them, not just unparseable JSON.
- const dir = join(projectDir, '.claude');
- mkdirSync(dir, { recursive: true });
- const path = join(dir, 'launch.json');
- writeFileSync(path, JSON.stringify([{ name: 'open-knowledge-ui' }]));
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('read-failed');
- expect(result.outcome.error).toBe('launch.json root is not an object');
-
- const readFailed = logEvents.find((e) => e.event === 'launch-json-repair-read-failed');
- expect(readFailed).toBeDefined();
- expect(readFailed?.configPath).toBe(path);
- expect(readFailed?.error).toBe('launch.json root is not an object');
- });
-
- it('emits a single stderr JSON line per repair when no logger is injected', () => {
- writeLaunchJson({ version: '0.0.1', configurations: [LEGACY_BARE_ENTRY] });
-
- const writes: string[] = [];
- const origWrite = process.stderr.write.bind(process.stderr);
- process.stderr.write = ((chunk: string | Uint8Array) => {
- writes.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8'));
- return true;
- }) as typeof process.stderr.write;
-
- try {
- repairLaunchJson({ projectDir });
- } finally {
- process.stderr.write = origWrite;
- }
-
- const appliedLines = writes.filter((w) => w.includes('"launch-json-repair-applied"'));
- expect(appliedLines.length).toBe(1);
- const parsed = JSON.parse(appliedLines[0].trim());
- expect(parsed.event).toBe('launch-json-repair-applied');
- expect(parsed.configPath).toContain('launch.json');
- });
-
- it('reports write-failed and emits the structured event when the file is unwritable', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [LEGACY_BARE_ENTRY],
- });
- chmodSync(configPath, 0o444);
- try {
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('write-failed');
- expect(typeof result.outcome.error).toBe('string');
- expect(result.outcome.error?.length ?? 0).toBeGreaterThan(0);
- expect(result.repairedCount).toBe(0);
-
- const writeFailed = logEvents.find((e) => e.event === 'launch-json-repair-write-failed');
- expect(writeFailed).toBeDefined();
- expect(writeFailed?.configPath).toBe(configPath);
- expect(typeof writeFailed?.error).toBe('string');
- } finally {
- // Restore writeability so afterEach's rmSync doesn't trip on a
- // read-only file inside the test scratch tree.
- chmodSync(configPath, 0o644);
- }
- });
-
- it('rewrites only the first matching entry when somehow duplicated', () => {
- // Defensive — `scaffoldLaunchJson` uses findIndex which targets the first
- // match, so a hypothetical duplicate-named launch.json (manual edit, merge
- // conflict resolved by appending) gets the first entry repaired. Pinning
- // this behavior so the helper's findIndex contract can't drift to findLast.
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [LEGACY_BARE_ENTRY, { ...LEGACY_BARE_ENTRY, port: 99999 }],
- });
-
- const result = repairLaunchJson({ projectDir, logger });
-
- expect(result.outcome.outcome).toBe('repaired');
- const written = JSON.parse(readFileSync(configPath, 'utf-8'));
- expect(written.configurations).toHaveLength(2);
- expectCanonicalChain(written.configurations[0]);
- // Second duplicate is left alone (findIndex returns first match only).
- expect(written.configurations[1].runtimeArgs).toEqual(['@inkeep/open-knowledge', 'ui']);
- });
-
- it('AC-C3: OK_RECLAIM_DISABLE=1 short-circuits with a structured event and no rewrite', () => {
- const configPath = writeLaunchJson({
- version: '0.0.1',
- configurations: [LEGACY_BARE_ENTRY],
- });
+ it('OK_RECLAIM_DISABLE=1 short-circuits with a structured event and no removal', () => {
+ const configPath = writeLaunchJson({ version: '0.0.1', configurations: [OK_ENTRY] });
const before = readFileSync(configPath, 'utf-8');
const result = repairLaunchJson({ projectDir, logger, reclaimDisableEnv: '1' });
@@ -567,7 +112,6 @@ describe('repairLaunchJson', () => {
});
it('skipped-reclaim-disabled fires even when no launch.json exists', () => {
- // Distinct from no-file because the env gate runs before the existsSync check.
const result = repairLaunchJson({ projectDir, logger, reclaimDisableEnv: '1' });
expect(result.outcome.outcome).toBe('skipped-reclaim-disabled');
expect(logEvents).toEqual([
diff --git a/packages/cli/src/commands/repair-launch-json.ts b/packages/cli/src/commands/repair-launch-json.ts
index 00fe24838..a3aafea11 100644
--- a/packages/cli/src/commands/repair-launch-json.ts
+++ b/packages/cli/src/commands/repair-launch-json.ts
@@ -1,144 +1,31 @@
/**
- * Startup sweep that rewrites stale OK-managed `.claude/launch.json` entries
- * forward to today's canonical published shape.
+ * Startup sweep that REMOVES OK's own `.claude/launch.json` entry.
*
- * Sibling of `repair-mcp-configs.ts`. Targets the single project-scoped
- * `.claude/launch.json` rather than the fan-out of editor host configs:
- * Claude Code Desktop's preview pane is the only consumer of this file
- * (read via `preview_start("open-knowledge-ui")`), so there is no user-
- * scope analogue and no per-editor iteration.
- *
- * Runs from `bootStartServer` (CLI `ok start`), alongside `repairMcpConfigs`.
- * Reads the existing `open-knowledge-ui` configuration entry, classifies it,
- * and re-invokes `scaffoldLaunchJson` only when the entry matches a legacy
- * bare-npx shape — anything else (version pin, dev mode, foreign customized
- * shape) is left untouched.
- *
- * Fail-soft. File read/write failures emit a structured event via the
- * injected logger and do not propagate.
+ * OK no longer scaffolds a launch.json — Claude Code Desktop's in-app Browser
+ * pane opens the preview URL directly. This sweep, run from `bootStartServer`
+ * (CLI `ok start`) alongside `repairMcpConfigs`, surgically removes any
+ * `open-knowledge-ui` entry a prior OK version left in a (possibly shared)
+ * `.claude/launch.json`, preserving every other configuration. Fail-soft: IO
+ * failures inside `removeOwnLaunchEntry` surface as its executor's `failed`
+ * op; the reclaim gate short-circuits with a structured event.
*/
-import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
-import { isObject } from '../utils/is-object.ts';
-import {
- LAUNCH_CONFIG_NAME,
- LAUNCH_JSON_CANONICAL_ARGS,
- LAUNCH_UI_CHAIN_SENTINEL,
- LAUNCH_UI_WIN_CHAIN_SENTINEL,
- type LaunchJsonResult,
- scaffoldLaunchJson,
-} from './init.ts';
-
-// Legacy npx-`ui` forms that `ok init` wrote before the recipe switched to
-// the `# ok-ui-v1` `ok start` chain. All three launched a bare UI with no
-// collab server — the exact worktree-hang the chain fixes — so they migrate
-// forward. Includes the prior published `@latest ui` form (LAUNCH_JSON_CANONICAL_ARGS)
-// and the two pre-`@latest` bare forms (which additionally triggered npm's
-// engine-aware downgrade in `npm-pick-manifest`). Any OTHER npx shape (`@beta`,
-// `@0.4.0`, a custom subcommand) is a deliberate user pin and is left alone.
-const LEGACY_NPX_UI_FORMS: ReadonlyArray<readonly string[]> = [
- ['@inkeep/open-knowledge', 'ui'],
- ['-y', '@inkeep/open-knowledge', 'ui'],
- LAUNCH_JSON_CANONICAL_ARGS,
-];
-
-export type LaunchJsonEntryClassification = 'canonical' | 'legacy-bare' | 'preserved';
-
-/**
- * Pure classifier for an existing launch.json configuration entry. Exported
- * for direct unit testing. Unlike MCP config repair, launch.json has no
- * namespace-ownership semantics, so custom command shapes are preserved.
- *
- * - `canonical` — the current `# ok-ui-v1` `/bin/sh` chain (macOS/Linux) OR the
- * current `# ok-ui-win-v1` `powershell` chain (Windows); no repair. BOTH
- * platforms' canonical shapes are recognized regardless of the CURRENT host
- * platform: a committed `.claude/launch.json` written on one platform must
- * classify as canonical on the other, or a macOS user and a Windows user
- * sharing the repo would have their startup repair sweeps rewrite the shared
- * file back and forth forever. Writers always EMIT the local platform's shape;
- * this predicate only decides "leave it alone".
- * - `legacy-bare` — an earlier npx-`ui` shape (any of `LEGACY_NPX_UI_FORMS`)
- * OR an older `# ok-ui-vN` / `# ok-ui-win-vN` chain we own but no longer ship;
- * rewriting forward to the current chain unwedges the worktree-no-collab-server
- * hang (and, for the bare-npx forms, npm's engine-aware stale-release downgrade).
- * - `preserved` — anything else: version-pinned npx, a foreign `/bin/sh` or
- * `powershell` command, `node /path/cli.mjs` dev mode, custom command,
- * foreign-customized args, or any shape we don't recognize. Left alone —
- * preserving user intent matters more than aggressive normalization.
- */
-export function classifyLaunchJsonEntry(
- entry: Record<string, unknown>,
-): LaunchJsonEntryClassification {
- // The `/bin/sh` chain shapes (published + dev) carry a `# ok-ui-vN` sentinel
- // in `args[2]`. The current sentinel → canonical; an older one we own →
- // migrate forward. A `/bin/sh` entry WITHOUT an ok-ui sentinel is a user's
- // own command → preserved.
- if (entry.runtimeExecutable === '/bin/sh' && Array.isArray(entry.runtimeArgs)) {
- const chain = entry.runtimeArgs[2];
- if (typeof chain === 'string') {
- if (chain.includes(LAUNCH_UI_CHAIN_SENTINEL)) return 'canonical';
- if (/# ok-ui-v\d+/.test(chain)) return 'legacy-bare';
- }
- return 'preserved';
- }
- // Windows `powershell` chain — the same sentinel logic on `args[3]` (the
- // `-Command` payload sits after `-NoProfile -NonInteractive -Command`). This
- // branch is platform-independent by design (see the mutual-recognition note
- // above): a Unix host must still see a Windows-committed entry as canonical.
- if (entry.runtimeExecutable === 'powershell' && Array.isArray(entry.runtimeArgs)) {
- const chain = entry.runtimeArgs[3];
- if (typeof chain === 'string') {
- if (chain.includes(LAUNCH_UI_WIN_CHAIN_SENTINEL)) return 'canonical';
- if (/# ok-ui-win-v\d+/.test(chain)) return 'legacy-bare';
- }
- return 'preserved';
- }
- if (entry.runtimeExecutable === 'npx' && Array.isArray(entry.runtimeArgs)) {
- for (const form of LEGACY_NPX_UI_FORMS) {
- if (argsExactlyMatch(entry.runtimeArgs, form)) return 'legacy-bare';
- }
- }
- return 'preserved';
-}
-
-// Keep semantics in sync with `argsExactlyMatch` in `repair-mcp-configs.ts` —
-// both classifiers depend on byte-exact argv matching for their canonical /
-// legacy-bare predicates. If you need to change matching here (e.g.
-// case-insensitive or order-insensitive), update the sibling in lockstep.
-function argsExactlyMatch(actual: readonly unknown[], expected: readonly string[]): boolean {
- if (actual.length !== expected.length) return false;
- for (let i = 0; i < expected.length; i++) {
- if (actual[i] !== expected[i]) return false;
- }
- return true;
-}
+import { removeOwnLaunchEntry } from './launch-json-removal.ts';
export interface LaunchJsonRepairOutcome {
configPath: string;
/**
- * - `no-file` — `.claude/launch.json` does not exist (no `ok init`
- * against Claude yet, or user removed it). Distinct from
- * `no-entry` so diagnostics can tell "never wired up" apart from
- * "user removed our entry."
- * - `no-entry` — file exists but contains no configuration named
- * `open-knowledge-ui`; user-curated state, do not recreate.
- * - `read-failed` — file exists but couldn't be parsed (malformed JSON,
- * non-object root, configurations not an array). Surfaced for
- * diagnostics; treated as a no-op to avoid stomping on a file the
- * user is mid-edit.
- * - `canonical` / `preserved` — entry exists and is in a shape we
- * should not rewrite (see classifier docs).
- * - `repaired` — legacy bare-npx entry rewritten forward to canonical.
- * - `write-failed` — repair attempted but the file write failed
- * (permissions, disk full, etc.).
+ * - `removed` / `removed-file` — OK's entry (or the whole OK-only file) was
+ * removed from a pre-existing `.claude/launch.json`.
+ * - `not-present` — no file, or no OK entry; nothing to clean up.
+ * - `declined` — file exists but is malformed; left untouched.
+ * - `skipped-reclaim-disabled` — `OK_RECLAIM_DISABLE=1` short-circuited.
*/
outcome:
- | 'no-file'
- | 'no-entry'
- | 'read-failed'
- | 'canonical'
- | 'preserved'
- | 'repaired'
+ | 'removed'
+ | 'removed-file'
+ | 'not-present'
+ | 'declined'
| 'write-failed'
| 'skipped-reclaim-disabled';
error?: string;
@@ -146,41 +33,29 @@ export interface LaunchJsonRepairOutcome {
export interface LaunchJsonRepairResult {
outcome: LaunchJsonRepairOutcome;
+ /** 1 when an entry (or the OK-only file) was removed, else 0. */
repairedCount: 0 | 1;
}
export interface LaunchJsonRepairLogEvent {
event: string;
- /** Present on per-file events; absent on the sweep-level skip event. */
configPath?: string;
- error?: string;
reason?: string;
}
export interface LaunchJsonRepairContext {
/** Absolute path to the project root. The sweep targets `<projectDir>/.claude/launch.json`. */
projectDir: string;
- /** Sink for the structured per-file event. Default: stderr JSON-lines. */
+ /** Sink for the structured event. Default: stderr JSON-lines. */
logger?: (event: LaunchJsonRepairLogEvent) => void;
- /**
- * Value of `process.env.OK_RECLAIM_DISABLE` — '1' short-circuits the sweep
- * with a structured `launch-json-repair-skipped` event. Mirrors the env
- * gate in the sibling MCP sweep and the new CLI `repairSkills` sweep.
- */
+ /** `process.env.OK_RECLAIM_DISABLE` — '1' short-circuits with a skip event. */
reclaimDisableEnv?: string | null;
}
/**
- * Sweep `<projectDir>/.claude/launch.json` and rewrite a legacy bare-npx
- * `open-knowledge-ui` entry forward to today's canonical shape. Single-file
- * sweep — there is no fan-out and no user-scope analogue (launch.json is
- * project-local by Claude's design).
- *
- * Fail-soft. IO failures are captured in the returned outcome and emitted as
- * a structured event via the injected logger — neither propagates. The
- * default logger (`process.stderr.write`) does not throw; a caller that
- * injects a logger which CAN throw should defend at the call site, the same
- * way `bootStartServer` wraps the MCP repair sweep with an outer try/catch.
+ * Remove OK's `open-knowledge-ui` entry from `<projectDir>/.claude/launch.json`
+ * if present. Single-file sweep; no fan-out and no user-scope analogue.
+ * Fail-soft — never throws.
*/
export function repairLaunchJson(ctx: LaunchJsonRepairContext): LaunchJsonRepairResult {
const logger = ctx.logger ?? defaultLogger;
@@ -188,78 +63,22 @@ export function repairLaunchJson(ctx: LaunchJsonRepairContext): LaunchJsonRepair
if (ctx.reclaimDisableEnv === '1') {
logger({ event: 'launch-json-repair-skipped', reason: 'reclaim-disabled' });
- return {
- outcome: { configPath, outcome: 'skipped-reclaim-disabled' },
- repairedCount: 0,
- };
- }
-
- if (!existsSync(configPath)) {
- return { outcome: { configPath, outcome: 'no-file' }, repairedCount: 0 };
+ return { outcome: { configPath, outcome: 'skipped-reclaim-disabled' }, repairedCount: 0 };
}
- // Read-and-classify pass. We deliberately don't reuse `scaffoldLaunchJson`'s
- // read path: that helper conflates read with write and would auto-create
- // the entry on a malformed root, which is not what we want here. Repair
- // is forward-migration of existing entries only — never proactive creation.
- let parsed: unknown;
+ let result: ReturnType<typeof removeOwnLaunchEntry>;
try {
- const raw = readFileSync(configPath, 'utf-8').trim();
- parsed = raw ? JSON.parse(raw) : {};
+ result = removeOwnLaunchEntry(ctx.projectDir);
} catch (err) {
+ // removeOwnLaunchEntry propagates a final write/unlink IO failure; keep the
+ // startup sweep fail-soft so `ok start` never crashes on a read-only file.
const error = err instanceof Error ? err.message : String(err);
- logger({ event: 'launch-json-repair-read-failed', configPath, error });
- return { outcome: { configPath, outcome: 'read-failed', error }, repairedCount: 0 };
- }
-
- if (!isObject(parsed)) {
- // Symmetric with the JSON parse-error path above: emit the structured
- // event before returning `read-failed` so operators tailing stderr
- // JSON-lines see structurally-broken files surface, not just unparseable
- // ones.
- const error = 'launch.json root is not an object';
- logger({ event: 'launch-json-repair-read-failed', configPath, error });
- return {
- outcome: { configPath, outcome: 'read-failed', error },
- repairedCount: 0,
- };
- }
-
- const configs = parsed.configurations;
- if (!Array.isArray(configs)) {
- return { outcome: { configPath, outcome: 'no-entry' }, repairedCount: 0 };
- }
-
- const existing = configs.find(
- (c): c is Record<string, unknown> =>
- isObject(c) && (c as Record<string, unknown>).name === LAUNCH_CONFIG_NAME,
- );
- if (!existing) {
- return { outcome: { configPath, outcome: 'no-entry' }, repairedCount: 0 };
- }
-
- const classification = classifyLaunchJsonEntry(existing);
- if (classification === 'canonical') {
- return { outcome: { configPath, outcome: 'canonical' }, repairedCount: 0 };
- }
- if (classification === 'preserved') {
- return { outcome: { configPath, outcome: 'preserved' }, repairedCount: 0 };
- }
-
- // legacy-bare → rewrite via the canonical write path. `scaffoldLaunchJson`
- // owns the merge-and-replace semantics: it locates the entry by `name`,
- // replaces it with today's published-mode shape, and preserves any other
- // configurations alongside. `mode: 'published'` is correct here — the
- // sweep only fires from `bootStartServer` in production, never dev.
- const writeResult: LaunchJsonResult = scaffoldLaunchJson(ctx.projectDir, { mode: 'published' });
- if (writeResult.action === 'failed') {
- const error = writeResult.error ?? 'unknown write failure';
- logger({ event: 'launch-json-repair-write-failed', configPath, error });
+ logger({ event: 'launch-json-repair-write-failed', configPath });
return { outcome: { configPath, outcome: 'write-failed', error }, repairedCount: 0 };
}
-
- logger({ event: 'launch-json-repair-applied', configPath });
- return { outcome: { configPath, outcome: 'repaired' }, repairedCount: 1 };
+ const removed = result.kind === 'removed' || result.kind === 'removed-file';
+ if (removed) logger({ event: 'launch-json-repair-removed', configPath });
+ return { outcome: { configPath, outcome: result.kind }, repairedCount: removed ? 1 : 0 };
}
function defaultLogger(event: LaunchJsonRepairLogEvent): void {
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 9554c2484..add4d2876 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -265,9 +265,9 @@ interface ConnectUiSiblingOptions {
* Connect fallback. When `ok start --ui-port P` finds the collab
* server.lock already held by a live process — the main checkout (server
* always running), or a lost TOCTOU race against a concurrent start — we must
- * NOT exit 1, because the same committed `launch.json` recipe rides into both
- * the main checkout and every worktree, and a non-zero exit reads to the
- * preview pane as "preview crashed." Instead we "connect": run `ok ui --port P`
+ * NOT exit 1, because `ok start --ui-port P` is run identically in the main
+ * checkout and every worktree, and a non-zero exit would break a caller that
+ * expects connect-on-collision. Instead we "connect": run `ok ui --port P`
* in this folder, exactly reproducing what the prior bare-`ok ui` recipe did.
*
* On main that `ok ui --port P` hits the existing UI's `ui.lock` and enters
@@ -866,10 +866,9 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo
log.warn({ err }, '[start] mcp-config repair sweep failed; continuing');
}
- // Sibling sweep for `.claude/launch.json` — same silent-downgrade class
- // as the MCP sweep above. The bare-npx form pre-dating the `@latest`
- // pin would otherwise route Claude Code Desktop's preview-pane spawn
- // through npm's engine-aware sort and silently land on a stale release.
+ // Sibling sweep for `.claude/launch.json` — OK no longer scaffolds one,
+ // so this removes any stale `open-knowledge-ui` entry a prior OK version
+ // left behind (co-located user configs are preserved).
try {
const repair =
opts.repairLaunchJsonFn ?? (await import('./repair-launch-json.ts')).repairLaunchJson;
diff --git a/packages/cli/src/commands/ui.test.ts b/packages/cli/src/commands/ui.test.ts
index d772b4a77..8ce3ebcaf 100644
--- a/packages/cli/src/commands/ui.test.ts
+++ b/packages/cli/src/commands/ui.test.ts
@@ -18,10 +18,8 @@ import { resolve } from 'node:path';
import { ProblemDetailsSchema, type Scheduler } from '@inkeep/open-knowledge-core';
import {
acquireServerLock,
- armPaneTarget,
ConfigSchema,
getLocalDir,
- readArmedPaneTarget,
readUiLock,
type UiLockMetadata,
updateServerLockPort,
@@ -364,45 +362,9 @@ describe('startUiServer', () => {
expect(parsed.collabUrl).toBeNull();
expect(parsed.previewUrl).toBeNull();
expect(parsed.port).toBe(handle.port);
- // No target armed → paneTarget rides the body as null (shape parity).
- expect(parsed.paneTarget).toBeNull();
});
- test('/api/config returns an armed paneTarget; DELETE consumes it', async () => {
- armPaneTarget(lockDir, '#/specs/foo/SPEC');
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const first = JSON.parse((await get(handle.port, '/api/config')).body);
- expect(first.paneTarget).toBe('#/specs/foo/SPEC');
-
- // DELETE clears the armed target (one-shot consume on apply).
- const del = await fetch(`http://127.0.0.1:${handle.port}/api/config`, { method: 'DELETE' });
- expect(del.status).toBe(204);
- expect(readArmedPaneTarget(lockDir)).toBeNull();
-
- const second = JSON.parse((await get(handle.port, '/api/config')).body);
- expect(second.paneTarget).toBeNull();
- });
-
- test('base-open GET / 302-redirects to an armed pane target and consumes it', async () => {
- armPaneTarget(lockDir, '#/specs/foo/SPEC');
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
-
- // First base-open: redirect straight to the armed doc route (manual so we
- // can inspect the 302 instead of following it).
- const res = await fetch(`http://127.0.0.1:${handle.port}/`, { redirect: 'manual' });
- expect(res.status).toBe(302);
- expect(res.headers.get('location')).toBe('/#/specs/foo/SPEC');
- expect(res.headers.get('cache-control')).toBe('no-store');
-
- // Consumed on emit — the target is gone, so the follow-up GET / (which the
- // browser sends with the fragment stripped) does NOT redirect again. This is
- // what breaks the fragment-redirect loop.
- expect(readArmedPaneTarget(lockDir)).toBeNull();
- const follow = await fetch(`http://127.0.0.1:${handle.port}/`, { redirect: 'manual' });
- expect(follow.status).not.toBe(302);
- });
-
- test('base-open GET / does not redirect when no pane target is armed', async () => {
+ test('base-open GET / serves the SPA shell at root', async () => {
const dist = seedDist(tmpDir, 'noredir');
handle = await startUiServer({
config: config(),
diff --git a/packages/cli/src/commands/ui.ts b/packages/cli/src/commands/ui.ts
index 493755ef3..2da11c5b0 100644
--- a/packages/cli/src/commands/ui.ts
+++ b/packages/cli/src/commands/ui.ts
@@ -2,18 +2,12 @@
* `open-knowledge ui` — serves the React editor UI as a sibling to `ok start`.
*
* Default port `DEFAULT_UI_PORT` (39847 — quirky, IANA-unassigned, unlikely to
- * collide with other dev servers); `PORT` env (set by Claude via
- * `launch.json` + `autoPort:true`) and `--port` flag override. When the
+ * collide with other dev servers); `PORT` env and `--port` flag override. When the
* default port is busy, the bind layer falls back to kernel-allocation
* (port 0) so multi-project concurrency stays mechanical rather than
* aspirational — guarding against silent cross-project collisions.
* The user-facing URL is always sourced from `ui.lock.port`.
*
- * Claude's `launch.json` uses a distinct port `LAUNCH_JSON_PORT`
- * (39848) — see that constant's docstring for why the two must differ
- * (the lock-collision proxy bridges them; the same-port "already-running"
- * exit-0 path empirically fails Claude's preview pane).
- *
* Acquires `<lockDir>/ui.lock` so MCP tools can advertise preview URLs
* pointing at this process.
*
@@ -72,26 +66,6 @@ export const DEFAULT_UI_SAFETY_NET_MS = 12 * 60 * 60 * 1000;
*/
export const DEFAULT_UI_PORT = 39847;
-/**
- * Port written into `.claude/launch.json`'s `port` field — what Claude
- * Code's preview pane uses as its probe / spawn target. **Must differ
- * from `DEFAULT_UI_PORT`** so the lock-collision handler enters proxy
- * mode (`requestedPort ≠ lockPort` → bind + forward) rather than the
- * "already-running" exit-0 path. The exit-0 path empirically fails
- * Claude's preview pane (the subprocess exits before the pane can
- * attach), so the design relies on the proxy bridge:
- *
- * `ok start` → spawns `ok ui` → binds 39847 → writes `ui.lock`
- * Claude preview → spawns `ok ui` with `PORT=39848`
- * → new `ok ui` sees lock collision, `requestedPort(39848) ≠ lockPort(39847)`
- * → proxy mode: binds 39848, forwards to 39847
- * Preview pane → `http://localhost:39848` → proxy → real UI
- *
- * Picked adjacent to `DEFAULT_UI_PORT` (39848 vs 39847) so the pairing
- * is mnemonic; both are quirky/IANA-unassigned.
- */
-export const LAUNCH_JSON_PORT = 39848;
-
export interface UiServerHandle {
/**
* All bound HTTP servers. In two-socket-loopback mode (default) this has
@@ -187,10 +161,8 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe
const { resolve } = await import('node:path');
const {
acquireUiLock,
- clearArmedPaneTarget,
createAssetServeMiddleware,
createContentFilter,
- readArmedPaneTarget,
readServerLock,
releaseUiLock,
updateUiLockPort,
@@ -284,34 +256,6 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe
const requestHandler = (req: import('node:http').IncomingMessage, res: ServerResponse) => {
const url = req.url?.split('?')[0];
- // Claude-pane deep-link redirect (Claude Code Desktop flow only).
- // `preview_start` opens the pane at the UI root with no way to pass a target
- // doc, so the agent arms one via `preview_url({ armPaneTarget })`, which
- // writes a TTL-bounded hash route here. On the base-open we 302 straight to
- // that route so the pane lands ON the doc instead of rendering root and then
- // client-navigating. Inert for every other host: nothing else arms a target,
- // so `readArmedPaneTarget` returns null and we fall through to serve root.
- //
- // The target is a hash fragment (`#/doc`) the server never sees on the
- // follow-up request, so a naive 302 would loop (GET / → 302 → GET / → 302 …).
- // Consuming the target as we emit the redirect breaks the loop — the second
- // GET / finds nothing armed and serves the SPA — and also stops an in-TTL
- // reload of a deep link from being yanked back to the armed doc.
- // `PaneTargetLanding` in the app remains a client-side backstop.
- if (req.method === 'GET' && (url === '/' || url === '')) {
- const armed = readArmedPaneTarget(lockDir);
- // CRLF guard: never let a stray newline in the route split the response
- // into injected headers (the route is built from a doc/folder name).
- if (armed && !/[\r\n]/.test(armed)) {
- clearArmedPaneTarget(lockDir);
- res.statusCode = 302;
- res.setHeader('Location', `/${armed}`);
- res.setHeader('Cache-Control', 'no-store');
- res.end();
- return;
- }
- }
-
// Bare `/` and the empty path: rewrite to `/index.html` so sirv serves
// the SPA shell. The static handler is configured with `extensions: []`
// (a security choice — without it, `/foo` would transparently serve
@@ -337,19 +281,6 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe
if (rejectIfNotLoopbackApi(req, res)) return;
}
- // DELETE /api/config — one-shot consume of the armed pane target. The app
- // calls this AFTER it has applied the target on a base-open, so a reload
- // within the TTL doesn't re-navigate. Consume-on-apply (not on read) keeps
- // the GET non-destructive — other /api/config readers (the collab-URL hook)
- // must not race-consume the target before the lander applies it.
- if (url === '/api/config' && req.method === 'DELETE') {
- clearArmedPaneTarget(lockDir);
- res.setHeader('Cache-Control', 'no-store');
- res.statusCode = 204;
- res.end();
- return;
- }
-
// GET /api/config — zero-ceremony bootstrap for the React app. Reads the
// collab server.lock on demand so a later `ok start` shows up without
// requiring a UI restart.
@@ -369,10 +300,7 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe
// `?? <localhost>` fallback is defense-in-depth only.
const sameOriginHost = req.headers.host ?? `localhost:${resolvedPort}`;
const collabUrl = lock && lock.port > 0 ? `ws://${sameOriginHost}/collab` : null;
- // Armed pane-target override (route fragment, TTL-bounded). The app reads
- // this on a base-open to deep-link the Claude pane; null when unarmed/stale.
- const paneTarget = readArmedPaneTarget(lockDir);
- const body = JSON.stringify({ collabUrl, previewUrl: null, port: resolvedPort, paneTarget });
+ const body = JSON.stringify({ collabUrl, previewUrl: null, port: resolvedPort });
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
// `nosniff` — defense in depth against a misconfigured intermediate or
@@ -768,10 +696,8 @@ function resolveRequestedPort(
// port 0 (kernel-allocated) when the default is busy, preserving the
// multi-project bind guarantee against silent cross-family collisions.
// MCP preview URLs dereference `ui.lock.port` so no client contract
- // breaks. Claude's `launch.json` uses a DIFFERENT port
- // (`LAUNCH_JSON_PORT` = 39848) as its probe target; the lock-collision
- // proxy in this same file bridges that port to whatever port the real
- // `ok ui` is bound on.
+ // breaks; the lock-collision proxy in this same file bridges a second
+ // `ok ui` bound on a different port to whatever port the real UI holds.
return { port: DEFAULT_UI_PORT, fallbackToKernel: true };
}
@@ -1017,8 +943,7 @@ export { resolveRequestedPort };
/**
* "Non-interactive" gate for the `already-running` collision path. When the
* caller has no TTY (e.g. spawned by a parent process) OR is invoked with a
- * `PORT` env (Claude Code Desktop's `.claude/launch.json` template sets
- * `PORT=39848` + `autoPort:true`), `process.exit(0)` is wrong — the preview
+ * `PORT` env, `process.exit(0)` is wrong — the preview
* pane treats subprocess exit as "preview crashed" and tears down. Instead,
* the action handler stays attached as a keepalive until SIGTERM.
*
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 100f27c35..5cf1c39e0 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -33,13 +33,9 @@ export {
detectInstalledEditors,
type EditorMcpResult,
LAUNCH_CONFIG_NAME,
- LAUNCH_UI_CHAIN_SENTINEL,
- LAUNCH_UI_CHAIN_V1,
- type LaunchJsonResult,
type McpDeclineReason,
type McpEntryClassification,
readExistingMcpEntry,
- scaffoldLaunchJson,
type UserMcpConfigsOptions,
writeEditorMcpConfig,
writeUserMcpConfigs,
diff --git a/packages/cli/src/integrations/project-integration-writers.ts b/packages/cli/src/integrations/project-integration-writers.ts
index 703784ddd..390576de7 100644
--- a/packages/cli/src/integrations/project-integration-writers.ts
+++ b/packages/cli/src/integrations/project-integration-writers.ts
@@ -11,8 +11,8 @@
* NOT run this orchestrator.
*
* Abstraction boundary: per-editor project-local integrations ONLY. The
- * `.ok/` scaffold, the user-global skill (`installUserSkill`), `launch.json`,
- * and git remain `ok init`'s own composition AROUND this orchestrator.
+ * `.ok/` scaffold, the user-global skill (`installUserSkill`), and git
+ * remain `ok init`'s own composition AROUND this orchestrator.
*
* Adding a new project-local concern = appending one writer to the default
* set; no caller changes.
diff --git a/packages/cli/src/integrations/write-project-ai-integrations.test.ts b/packages/cli/src/integrations/write-project-ai-integrations.test.ts
index 0a8a32d98..52f04babd 100644
--- a/packages/cli/src/integrations/write-project-ai-integrations.test.ts
+++ b/packages/cli/src/integrations/write-project-ai-integrations.test.ts
@@ -1,13 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import {
- existsSync,
- mkdirSync,
- mkdtempSync,
- readFileSync,
- realpathSync,
- rmSync,
- writeFileSync,
-} from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { ALL_EDITOR_IDS } from '../commands/editors.ts';
@@ -78,7 +70,6 @@ describe('writeProjectAiIntegrations — installs MCP config AND the project ski
const result = writeProjectAiIntegrations(projectDir, []);
expect(result.integrations).toEqual([]);
- expect(result.claudeLaunchJson).toBeUndefined();
});
test('never throws — a hostile target surfaces as action "failed", not an exception', () => {
@@ -102,23 +93,3 @@ describe('writeProjectAiIntegrations — installs MCP config AND the project ski
expect(claudeWritten).toBe(true);
});
});
-
-describe('writeProjectAiIntegrations — Claude launch.json', () => {
- test('selecting "claude" scaffolds .claude/launch.json', () => {
- const result = writeProjectAiIntegrations(projectDir, ['claude']);
-
- expect(result.claudeLaunchJson?.action).toBe('created');
- expect(result.claudeLaunchJson?.configPath).toBe(join(projectDir, '.claude', 'launch.json'));
- expect(existsSync(join(projectDir, '.claude', 'launch.json'))).toBe(true);
-
- const launch = JSON.parse(readFileSync(join(projectDir, '.claude', 'launch.json'), 'utf-8'));
- expect(launch.configurations[0].name).toBe('open-knowledge-ui');
- });
-
- test('NOT selecting "claude" leaves launch.json absent and claudeLaunchJson undefined', () => {
- const result = writeProjectAiIntegrations(projectDir, ['cursor', 'codex']);
-
- expect(result.claudeLaunchJson).toBeUndefined();
- expect(existsSync(join(projectDir, '.claude', 'launch.json'))).toBe(false);
- });
-});
diff --git a/packages/cli/src/integrations/write-project-ai-integrations.ts b/packages/cli/src/integrations/write-project-ai-integrations.ts
index ff9e99683..432b730b0 100644
--- a/packages/cli/src/integrations/write-project-ai-integrations.ts
+++ b/packages/cli/src/integrations/write-project-ai-integrations.ts
@@ -9,18 +9,11 @@
* but keeps its own scope/detection-aware loop — it does not run this
* orchestrator.
*
- * `writeProjectAiIntegrations` adds the one desktop-specific concern the
- * per-editor orchestrator does not own: scaffolding `<projectDir>/.claude/
- * launch.json` when `'claude'` is selected (the CLI's `runInit` does the
- * equivalent). `launch.json` is a single per-project file, not a per-editor
- * integration, so it stays here rather than inside a writer.
- *
* Never throws — every per-(editor × integration) failure is captured in
* its `IntegrationWriteOutcome` as `action: 'failed'`.
*/
import type { EditorId, McpInstallOptions } from '../commands/editors.ts';
-import { type LaunchJsonResult, scaffoldLaunchJson } from '../commands/init.ts';
import {
applyProjectIntegrations,
type IntegrationWriteOutcome,
@@ -30,9 +23,6 @@ export interface ProjectAiIntegrationsResult {
/** Per-(editor × integration) outcomes — MCP config and the project-local
* runtime skill for every selected editor. */
readonly integrations: IntegrationWriteOutcome[];
- /** Result of `<projectDir>/.claude/launch.json` scaffolding; present iff
- * `'claude'` was in `selectedEditorIds`. */
- readonly claudeLaunchJson?: LaunchJsonResult;
}
export function writeProjectAiIntegrations(
@@ -41,8 +31,5 @@ export function writeProjectAiIntegrations(
installOptions: McpInstallOptions = {},
): ProjectAiIntegrationsResult {
const integrations = applyProjectIntegrations(projectDir, selectedEditorIds, installOptions);
- const claudeLaunchJson = selectedEditorIds.includes('claude')
- ? scaffoldLaunchJson(projectDir, installOptions)
- : undefined;
- return { integrations, claudeLaunchJson };
+ return { integrations };
}
diff --git a/packages/core/src/schemas/api/_envelope.ts b/packages/core/src/schemas/api/_envelope.ts
index 899d5951f..2159f6782 100644
--- a/packages/core/src/schemas/api/_envelope.ts
+++ b/packages/core/src/schemas/api/_envelope.ts
@@ -131,9 +131,7 @@ export type PrincipalSuccess = z.infer<typeof PrincipalSuccessSchema>;
* collab server is bound / the Host header is absent (the client then falls
* back to a same-origin WS URL). `previewUrl` is always `null` on the wire
* (the route-only preview URL is computed client-side). `port` is the bound
- * server port (0 when unknown). `paneTarget` is the armed deep-link route
- * fragment (`#/<doc>` / `#/<folder>/`), TTL-bounded server-side, or `null`
- * when unarmed/expired.
+ * server port (0 when unknown).
*
* `.loose()` preserves unknown fields for forward-compat, matching the other
* bare-object success schemas in this file (no `ok: true` discriminator).
@@ -143,7 +141,6 @@ export const ApiConfigSuccessSchema = z
collabUrl: z.string().nullable(),
previewUrl: z.string().nullable(),
port: z.number(),
- paneTarget: z.string().nullable(),
/**
* `true` when this server is a no-project ephemeral single-file session
* (`ok <file>`). The React shell reads it to drop the project chrome
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 2a6827251..5d4a0693c 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -230,7 +230,6 @@ import {
} from './ipc-handlers.ts';
import { logIpcError } from './ipc-log.ts';
import { createDesktopKeepaliveFactory, toKeepaliveLogger } from './keepalive.ts';
-import { checkAndRepairLaunchJsonOnProjectOpen } from './launch-json-wiring.ts';
import {
checkAndRepairMcpWiringOnStartup,
type McpStartupRepairResult,
@@ -1433,18 +1432,6 @@ async function openProject(
const warningsCount = validation.warnings.length;
const resolvedProjectDir = discovery.projectDir;
- void checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: resolvedProjectDir,
- executablePath: app.getPath('exe'),
- isPackaged: app.isPackaged,
- platform: process.platform,
- forceEnv: process.env.OK_M6B_FORCE ?? null,
- reclaimDisableEnv: process.env.OK_RECLAIM_DISABLE ?? null,
- }).catch((err) => {
- console.warn('[main] launch.json reclaim failed', {
- err: err instanceof Error ? err.message : String(err),
- });
- });
void checkAndRepairProjectMcpOnProjectOpen({
projectDir: resolvedProjectDir,
executablePath: app.getPath('exe'),
diff --git a/packages/desktop/src/main/launch-json-wiring.test.ts b/packages/desktop/src/main/launch-json-wiring.test.ts
deleted file mode 100644
index 0fd708c4f..000000000
--- a/packages/desktop/src/main/launch-json-wiring.test.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
-import { tmpdir } from 'node:os';
-import { join } from 'node:path';
-import { LAUNCH_UI_CHAIN_V1 } from '@inkeep/open-knowledge';
-import { checkAndRepairLaunchJsonOnProjectOpen } from './launch-json-wiring.ts';
-
-const EXE = '/Applications/OpenKnowledge.app/Contents/MacOS/OpenKnowledge';
-// Current canonical recipe — the `# ok-ui-v1` `/bin/sh` chain that runs
-// `ok start`, the exact shape `scaffoldLaunchJson('published')` writes.
-const CANONICAL_UI = {
- runtimeExecutable: '/bin/sh',
- runtimeArgs: ['-l', '-c', LAUNCH_UI_CHAIN_V1],
- port: 39848,
- autoPort: true,
-};
-
-function project() {
- return mkdtempSync(join(tmpdir(), 'ok-launch-json-'));
-}
-
-describe('checkAndRepairLaunchJsonOnProjectOpen — force-write posture', () => {
- test('no file → creates fresh launch.json with the OK entry', async () => {
- const dir = project();
- const events: Array<Record<string, unknown>> = [];
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- logger: { event: (e) => events.push(e) },
- });
- expect(result.status).toBe('created');
- const path = join(dir, '.claude', 'launch.json');
- expect(existsSync(path)).toBe(true);
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
- expect(parsed.configurations[0]).toMatchObject({
- name: 'open-knowledge-ui',
- ...CANONICAL_UI,
- });
- expect(events.some((e) => e.event === 'launch-json-wiring-repair-created')).toBe(true);
- });
-
- test('blank file → rewritten with the OK entry (no error)', async () => {
- const dir = project();
- mkdirSync(join(dir, '.claude'));
- const path = join(dir, '.claude', 'launch.json');
- writeFileSync(path, '');
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- });
- // scaffoldLaunchJson treats blank as {} and creates a fresh configurations
- // array — surfaced as 'created' because the entry didn't exist beforehand.
- expect(result.status).toBe('created');
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
- expect(parsed.configurations[0].name).toBe('open-knowledge-ui');
- expect(parsed.configurations[0]).toMatchObject(CANONICAL_UI);
- });
-
- test('already-canonical file → still merged (idempotent, no on-disk diff)', async () => {
- const dir = project();
- mkdirSync(join(dir, '.claude'));
- const path = join(dir, '.claude', 'launch.json');
- // Seed with the exact shape scaffoldLaunchJson writes (incl. its
- // `LAUNCH_JSON_PORT` constant) so the second-write byte diff is zero.
- writeFileSync(
- path,
- `${JSON.stringify(
- {
- version: '0.2.0',
- configurations: [
- {
- name: 'open-knowledge-ui',
- ...CANONICAL_UI,
- },
- ],
- },
- null,
- 2,
- )}\n`,
- );
- const before = readFileSync(path, 'utf8');
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- });
- expect(result.status).toBe('merged');
- expect(readFileSync(path, 'utf8')).toBe(before);
- });
-
- test('file without OK entry → entry added, siblings preserved', async () => {
- const dir = project();
- mkdirSync(join(dir, '.claude'));
- const path = join(dir, '.claude', 'launch.json');
- writeFileSync(
- path,
- JSON.stringify({ configurations: [{ name: 'other', runtimeExecutable: 'node' }] }),
- );
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- });
- // scaffoldLaunchJson's contract: action='created' when the OK entry didn't
- // exist before, action='merged' when an OK entry was already present and
- // got replaced. So new-entry-into-existing-file is 'created', not 'merged'.
- expect(result.status).toBe('created');
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
- expect(parsed.configurations).toHaveLength(2);
- expect(parsed.configurations[0].name).toBe('other');
- expect(parsed.configurations[1]).toMatchObject({
- name: 'open-knowledge-ui',
- ...CANONICAL_UI,
- });
- });
-
- test('stale OK entry → rewritten to canonical ok-start chain; siblings preserved', async () => {
- const dir = project();
- mkdirSync(join(dir, '.claude'));
- const path = join(dir, '.claude', 'launch.json');
- writeFileSync(
- path,
- JSON.stringify(
- {
- version: '0.0.1',
- configurations: [
- { name: 'other', runtimeExecutable: 'node' },
- {
- name: 'open-knowledge-ui',
- runtimeExecutable: '/Applications/OpenKnowledge.app/Contents/Resources/cli/bin/ok.sh',
- runtimeArgs: ['ui'],
- },
- ],
- },
- null,
- 2,
- ),
- );
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- });
- expect(result.status).toBe('merged');
- const parsed = JSON.parse(readFileSync(path, 'utf8'));
- expect(parsed.configurations[0].name).toBe('other');
- expect(parsed.configurations[1]).toMatchObject({
- name: 'open-knowledge-ui',
- ...CANONICAL_UI,
- });
- });
-
- test('corrupt JSON → failed (no backup-and-rewrite for launch.json — siblings outweigh recovery)', async () => {
- const dir = project();
- mkdirSync(join(dir, '.claude'));
- writeFileSync(join(dir, '.claude', 'launch.json'), '{ invalid json');
- const events: Array<Record<string, unknown>> = [];
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- logger: { event: (e) => events.push(e) },
- });
- expect(result.status).toBe('failed');
- expect(events.some((e) => e.event === 'launch-json-wiring-repair-write-failed')).toBe(true);
- });
-
- test('non-object root → failed', async () => {
- const dir = project();
- mkdirSync(join(dir, '.claude'));
- writeFileSync(join(dir, '.claude', 'launch.json'), '[1, 2, 3]');
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- });
- expect(result.status).toBe('failed');
- });
-
- test('skipped on non-darwin', async () => {
- const dir = project();
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'linux',
- });
- expect(result.status).toBe('skipped');
- });
-
- test('skipped in dev-mode without OK_M6B_FORCE', async () => {
- const dir = project();
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: false,
- platform: 'darwin',
- });
- expect(result.status).toBe('skipped');
- expect(existsSync(join(dir, '.claude', 'launch.json'))).toBe(false);
- });
-
- test('OK_RECLAIM_DISABLE=1 short-circuits', async () => {
- const dir = project();
- const result = await checkAndRepairLaunchJsonOnProjectOpen({
- projectDir: dir,
- executablePath: EXE,
- isPackaged: true,
- platform: 'darwin',
- reclaimDisableEnv: '1',
- });
- expect(result.status).toBe('skipped');
- expect(existsSync(join(dir, '.claude', 'launch.json'))).toBe(false);
- });
-});
diff --git a/packages/desktop/src/main/launch-json-wiring.ts b/packages/desktop/src/main/launch-json-wiring.ts
deleted file mode 100644
index a2bab4ebf..000000000
--- a/packages/desktop/src/main/launch-json-wiring.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import { join } from 'node:path';
-import { scaffoldLaunchJson } from '@inkeep/open-knowledge';
-
-interface LaunchJsonWiringLogger {
- event(payload: { event: string; [key: string]: unknown }): void;
-}
-
-const DEFAULT_LOGGER: LaunchJsonWiringLogger = {
- event: (payload) => console.warn(JSON.stringify(payload)),
-};
-
-type LaunchJsonRepairResult =
- | { status: 'skipped'; reason: string }
- | { status: 'created'; configPath: string }
- | { status: 'merged'; configPath: string }
- | { status: 'failed'; configPath: string; error: string };
-
-interface CheckAndRepairLaunchJsonOpts {
- projectDir: string;
- executablePath: string;
- isPackaged: boolean;
- platform: 'darwin' | 'win32' | 'linux' | string;
- forceEnv?: string | null | undefined;
- reclaimDisableEnv?: string | null | undefined;
- logger?: LaunchJsonWiringLogger;
-}
-
-/**
- * Force-write the canonical `.claude/launch.json` `open-knowledge-ui`
- * configuration on every project open. Mirrors the user-level SKILL
- * force-write posture — no namespace-ownership classification, no
- * healthy-current short-circuit. `scaffoldLaunchJson` does the right thing
- * in each case it can reach:
- *
- * - File missing → creates `.claude/launch.json` with our entry only.
- * - File parses, no `open-knowledge-ui` entry → merges our entry into
- * `configurations[]` (preserves siblings the user defined).
- * - File parses, `open-knowledge-ui` entry exists → replaces it with the
- * current bundled shape.
- * - File exists but is blank/whitespace → `scaffoldLaunchJson` treats it
- * as `{}` and writes a fresh file with our entry.
- * - File exists but contains malformed JSON → `scaffoldLaunchJson`
- * returns `'failed'`; we surface that as `status: 'failed'`. We do
- * NOT backup-and-rewrite here — preserving siblings the user authored
- * into a broken file outweighs the recovery-on-corrupt case. (Pure
- * OK-managed files like SKILL.md and `.mcp.json` *do* get the
- * backup-and-rewrite treatment; launch.json doesn't because it's a
- * shared user-authored surface.)
- *
- * Idempotent: running twice in succession produces no diff on disk
- * because `scaffoldLaunchJson` writes byte-identical output on the second
- * call. CRDT-style force-write is fine here.
- */
-export async function checkAndRepairLaunchJsonOnProjectOpen(
- opts: CheckAndRepairLaunchJsonOpts,
-): Promise<LaunchJsonRepairResult> {
- const {
- projectDir,
- executablePath,
- isPackaged,
- platform,
- forceEnv,
- reclaimDisableEnv,
- logger = DEFAULT_LOGGER,
- } = opts;
- const configPath = join(projectDir, '.claude', 'launch.json');
- if (reclaimDisableEnv === '1') return { status: 'skipped', reason: 'reclaim-disabled' };
- if (platform !== 'darwin') return { status: 'skipped', reason: 'platform' };
- if (!isPackaged && forceEnv !== '1') return { status: 'skipped', reason: 'dev-mode' };
- if (!/\.app\/Contents\/MacOS\/[^/]+$/.test(executablePath)) {
- return { status: 'skipped', reason: 'bad-executable-path' };
- }
-
- logger.event({ event: 'launch-json-wiring-repair-check-started', configPath });
- const result = scaffoldLaunchJson(projectDir, { mode: 'published' });
- if (result.action === 'failed') {
- logger.event({
- event: 'launch-json-wiring-repair-write-failed',
- configPath,
- error: result.error ?? 'unknown',
- });
- return { status: 'failed', configPath, error: result.error ?? 'unknown' };
- }
- logger.event({
- event:
- result.action === 'created'
- ? 'launch-json-wiring-repair-created'
- : 'launch-json-wiring-repair-merged',
- configPath,
- });
- return { status: result.action, configPath };
-}
diff --git a/packages/desktop/src/main/worktree-setup-inherit.test.ts b/packages/desktop/src/main/worktree-setup-inherit.test.ts
index 1c402bb6f..ad0d7db26 100644
--- a/packages/desktop/src/main/worktree-setup-inherit.test.ts
+++ b/packages/desktop/src/main/worktree-setup-inherit.test.ts
@@ -169,8 +169,9 @@ describe('seedWorktreeProjectSetup', () => {
expect(existsSync(wtMcp)).toBe(true);
expect(readFileSync(wtMcp, 'utf-8')).toContain('# ok-mcp');
expect(existsSync(wtCursor)).toBe(true);
- // Claude also gets its launcher entry (path-independent chain).
- expect(existsSync(join(wt, '.claude', 'launch.json'))).toBe(true);
+ // OK no longer scaffolds .claude/launch.json (Claude Desktop's Browser
+ // pane opens the preview URL directly).
+ expect(existsSync(join(wt, '.claude', 'launch.json'))).toBe(false);
// Codex was NOT wired at the root → not written to the worktree.
expect(existsSync(join(wt, '.codex', 'config.toml'))).toBe(false);
});
diff --git a/packages/desktop/src/main/worktree-setup-inherit.ts b/packages/desktop/src/main/worktree-setup-inherit.ts
index 05c86e6c6..d38c123a9 100644
--- a/packages/desktop/src/main/worktree-setup-inherit.ts
+++ b/packages/desktop/src/main/worktree-setup-inherit.ts
@@ -35,7 +35,7 @@
* 2. `writeProjectAiIntegrations(worktree, editors)` — the SAME writer the
* consent / create-new flows use. `editors` is the set the ROOT has wired,
* detected from each editor's project MCP config carrying the OK sentinel.
- * The published MCP entries and `.claude/launch.json` recipe are the
+ * The published MCP entries are the
* resilient `/bin/sh` chain — project-path-INDEPENDENT (they resolve the
* runtime at spawn time and derive the project from cwd), so writing them
* under the worktree path IS the path adaptation.
diff --git a/packages/server/assets/skills/discovery/SKILL.md b/packages/server/assets/skills/discovery/SKILL.md
index f6aeaae95..bb4dafc7f 100644
--- a/packages/server/assets/skills/discovery/SKILL.md
+++ b/packages/server/assets/skills/discovery/SKILL.md
@@ -92,7 +92,7 @@ When asked to open or preview such a file, **decide by the viewing surface you
actually have** — check the tool, not the host name. Only open a browser when
you genuinely have one; never pop a browser tab on a host that has none.
-- **You have an in-app / built-in browser** (Cursor, Codex, and similar) — this
+- **You have an in-app / built-in browser** (Claude Code Desktop's Browser pane, Cursor, Codex, and similar) — this
is the default: call the **`preview_url` MCP tool** with `file` set to the
absolute path (it finds, or boots on demand, the session and returns a full
`url`), then **immediately open that `url` in your in-app browser**. "Open it"
@@ -101,12 +101,7 @@ you genuinely have one; never pop a browser tab on a host that has none.
(`ok open` prefers the Desktop app). Get the URL from `preview_url` only —
never hunt for it via `ok ps` / `ok status` / `ok ui` / `ok start` or a guessed
port.
-- **You have a Claude Code Desktop preview *pane* but no general browser** — the
- pane is project-only: it shows in-project docs via `preview_start`, but it
- **cannot host a file from outside the project**. For such a file run
- `ok open /abs/path/to/file.md` (the Desktop app) instead; don't try to force
- the file into the pane.
-- **No in-app browser and no pane** (a pure-stdio CLI) — run
+- **No in-app browser** (a pure-stdio CLI) — run
`ok open /abs/path/to/file.md`: it opens the Desktop app when installed, else a
browser, and boots the session itself. Don't force a browser tab the user
didn't ask for; `ok open` is the right default here. If `ok` isn't on PATH,
diff --git a/packages/server/assets/skills/project/SKILL.md b/packages/server/assets/skills/project/SKILL.md
index b84f58b8e..34b37887a 100644
--- a/packages/server/assets/skills/project/SKILL.md
+++ b/packages/server/assets/skills/project/SKILL.md
@@ -19,7 +19,7 @@ OpenKnowledge (OK) is a markdown-CRDT collaboration platform exposed via MCP. Th
1. **Reads:** `exec("cat …")` for one doc, `exec("ls -A …")` for a directory (folder defaults + template menu), `exec("grep …")` for literal, `search` for ranked retrieval. Native `Read` / `Grep` only on source code (`.ts` / `.py` / …), never on in-scope `.md` / `.mdx`.
2. **Writes:** `write({ document: { path, content } })` for a new or full-replace doc; `edit({ document: { path, find, replace } })` for a body find/replace; `edit({ document: { path, frontmatter } })` for a frontmatter merge-patch (`null` deletes a key). `delete({ document })` removes, `move({ from, to })` moves/renames. Body find/replace is body-only. Pass a one-line `summary` (≤80 chars, user-facing outcome) on every content write.
-3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Before opening anything, pick where to focus, stop at first match: **`OK_DESKTOP_TERMINAL` set** (check your env — `echo "$OK_DESKTOP_TERMINAL"`) → OK Desktop's own terminal → `ok open <name>` (switches this window) · have `preview_*` → Claude Code Desktop pane · have a URL-navigation/browser tool → Cursor/Codex → `preview_url` then navigate it · else plain CLI → `ok open <name>`. `ok open <name>` opens a **doc or folder** (auto-detected — no `--folder`); add `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism — don't hand it to a browser just because you saw it. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.
+3. **Preview / open a doc — determine your ONE surface FIRST (once per session).** Before opening anything, pick where to focus, stop at first match: **`OK_DESKTOP_TERMINAL` set** (check your env — `echo "$OK_DESKTOP_TERMINAL"`) → OK Desktop's own terminal → `ok open <name>` (switches this window) · have an in-app browser (Claude Code Desktop's Browser pane, Cursor, Codex) → `preview_url` then open/navigate it to the doc (Claude Desktop: `preview_start({url})` to open, `navigate({url})` to move) · else plain CLI → `ok open <name>`. `ok open <name>` opens a **doc or folder** (auto-detected — no `--folder`); add `--skill <name>` for a skill. The `previewUrl` field is a route id, **not** your open mechanism — don't hand it to a browser just because you saw it. Don't `preview_screenshot` to confirm edits. Full Step-0 procedure + per-surface how-to: `references/preview.md`.
4. **Workflow guides:** `workflow({ kind: 'ingest' | 'research' | 'consolidate' | 'discover' })` returns a procedural guide, not data. Use it when the work fits the layer.
5. **Direct questions:** a plain business question ("which customers…", "what did we decide about…") routes to `search` / `exec` + a cited chat answer — no "research" keyword needed. Persist only when durable + multi-doc + not already covered, and *offer* first. See `references/corpus-qa.md`.
6. **Authoring or improving a skill** ("write/make a skill", "improve this skill", "turn this into a skill"): STOP and invoke the **`open-knowledge-write-skill`** skill — it owns scope choice (project vs global), the SKILL.md contract, evaluation, and install; don't improvise from this skill. Author through the `skill` target (`write({ skill })`), never a raw `.ok/skills/…` document. **Never read, diff, or edit the installed projections under `.claude/skills/` · `.cursor/skills/` · `.codex/skills/` · `.opencode/skills/` · `.pi/skills/` · `.agents/skills/`** — `install` generates them and overwrites them on the next sync; they are NOT source of truth.
diff --git a/packages/server/assets/skills/project/references/anti-patterns.md b/packages/server/assets/skills/project/references/anti-patterns.md
index 13ad00033..bfffc5301 100644
--- a/packages/server/assets/skills/project/references/anti-patterns.md
+++ b/packages/server/assets/skills/project/references/anti-patterns.md
@@ -12,8 +12,8 @@
| Explore a markdown-heavy dir | `Agent(Explore): "..."` | Do `exec`-based exploration yourself |
| Answer a direct business question from the corpus | answer in chat and move on (it evaporates), OR save every answer as a new doc | answer with citations; *offer* to persist only when durable + multi-doc + not already covered (`references/corpus-qa.md`) |
| Wait for the server to tell you to open preview | Skip the session-start preview open and wait for the `attach-preview-once` hint | Open the preview browser at session start; the hint is a fallback when you didn't |
-| Ignore the attach hint | Skip the `warning: { action: "attach-preview-once" }` hint in write-tool responses | Open the preview when the hint fires (`preview_start`, or `preview_url`); otherwise do nothing |
-| Make the Claude Code Desktop preview work | Read / diagnose / edit `.claude/launch.json` (host-managed config) | Call `preview_start("open-knowledge-ui")` and nothing else; the OK lock-collision proxy bridges any port mismatch transparently |
+| Ignore the attach hint | Skip the `warning: { action: "attach-preview-once" }` hint in write-tool responses | Open the preview when the hint fires (`preview_url` → navigate your in-app browser); otherwise do nothing |
+| Make the Claude Code Desktop preview work | Read / diagnose / edit `.claude/launch.json` (host-managed config) | Open the Browser pane with `preview_start({url})` (from `preview_url`; auto-starts the UI), then `navigate({url})` to move between docs; don't hand-edit host preview config — the OK lock-collision proxy bridges any port mismatch transparently |
| Open a doc/folder/skill in the app from a CLI | Print the `previewUrl` / `openknowledge://` string for the user to click | Run `ok open <name>` (doc or folder, auto-detected; `--skill <name>` for a skill) — deep-links into OK Desktop, browser fallback |
| Reference another doc | `` `[text](./page.md)` `` (backticked) or HTML `<a>` | `[text](./page.md)` (raw markdown) |
| Embed an image | `<img src="...">` (HTML), a `localhost:<port>` / `preview_url` server URL, or hot-linked external URL | Fetch + save locally + doc-relative `![meaningful alt](./assets/images/path)` |
diff --git a/packages/server/assets/skills/project/references/preview.md b/packages/server/assets/skills/project/references/preview.md
index ea242fea5..a0548d71b 100644
--- a/packages/server/assets/skills/project/references/preview.md
+++ b/packages/server/assets/skills/project/references/preview.md
@@ -22,15 +22,14 @@ The user watches your edits land in a live browser preview. Open it once at sess
Your host doesn't change mid-session, so determine this **once**, the first time you're asked to open/show/preview a doc, and use that one surface for the rest of the session. Run the checks **top-to-bottom and stop at the first match** — earlier rungs win:
1. **Is `OK_DESKTOP_TERMINAL` set in your environment?** You're a shell agent — actually check it (`echo "$OK_DESKTOP_TERMINAL"`, or read your env), don't assume. **Set → you're inside the OK Desktop app's own terminal.** Open a doc or folder with `ok open <name>` (auto-detected; `--skill <name>` for a skill) — it switches THIS window to the target. **Never resolve a preview URL here.** (This rung is the one agents miss most — check the env first, before anything else.)
-2. **Do you have `preview_*` tools** (`preview_start` / `preview_eval`)? → **Claude Code Desktop** → drive its pane (rung details below).
-3. **Do you have any URL-navigation / in-app browser tool** (Cursor `Navigate`, Codex `@Browser`, or `browser` / `open_url` / `view_url` / …)? → **Cursor / Codex desktop** → `preview_url` once, then navigate that browser to the `url`.
-4. **None of the above** → you're a **plain CLI** (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, Pi, any shell agent) → `ok open <name>` for a doc or folder (auto-detected; `--skill <name>` for a skill); deep-links a separate OK Desktop window, system browser only if no desktop.
+2. **Do you have any URL-navigation / in-app browser tool** (Claude Code Desktop's **Browser pane**, Cursor's `Navigate`, Codex's `@Browser`, or `browser` / `open_url` / `view_url` / …)? → **Claude Code Desktop / Cursor / Codex desktop** → `preview_url` once, then open/navigate that browser to the `url` (per-surface how-to below — Claude Desktop opens the pane with `preview_start({ url })` then `navigate({ url })` to move; Cursor/Codex navigate directly).
+3. **None of the above** → you're a **plain CLI** (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, Pi, any shell agent) → `ok open <name>` for a doc or folder (auto-detected; `--skill <name>` for a skill); deep-links a separate OK Desktop window, system browser only if no desktop.
Decide once; then every "open / show / preview this doc" this session uses that surface's mechanism. **The `previewUrl` field in tool responses is a route id, not your open mechanism** — seeing it is not a reason to hand it to a browser. The rest of this section is the per-surface "how" for whichever rung you landed on.
**OK ships first-class preview support for three apps — Claude Code Desktop, Cursor, and the Codex desktop app — plus any CLI (Claude Code CLI, Codex CLI, Cursor CLI, OpenCode, Pi, …) on a separate `ok open` track (below). Make the preview seamless in each.** Match on the tool you actually have (capability, not host name): if a tool can navigate to a URL, it counts as an in-app browser; if nothing can, you're a CLI → `ok open`. The three apps map to:
-- **Claude Code Desktop — you have `preview_*` tools** (e.g. `preview_start` + `preview_eval`) → **First open of the session:** to land directly on a doc, arm it first with `preview_url({ armPaneTarget: true, document })` (or `folder`), then `preview_start("open-knowledge-ui")` — `ok ui` redirects the base-open straight to the armed route, so the pane opens on the doc, not root. Plain `preview_start` (no arm) opens at root. **Moving between docs once the pane is open: do it in one `preview_eval` step — set `window.location.hash` to the target's route fragment from the response `previewUrl`, the part from `#` on (e.g. `window.location.hash = '#/specs/foo/SPEC'`).** That drives the SPA router directly. Arm + `preview_start` only redirects a *fresh* open; it can't move an already-open pane (`preview_start` reuses the live process without reloading), so use `preview_eval` there. Don't read or edit `.claude/launch.json` — host-managed; the OK lock-collision proxy handles the UI-already-running case. If `preview_start` fails, report it; don't "fix" `launch.json`.
+- **Claude Code Desktop — you have the in-app `Browser` pane** (Cmd+Shift+B; driven by the `Claude_Browser` tool set — `preview_start`, `navigate`, `read_page`, `computer`, …). Two steps, both fed by `preview_url`: **(1) open the pane** with `preview_start({ url })` passing the `preview_url` result — `preview_start` opens a browser tab directly at that URL (`preview_start({ url })`), and the deep `url` already carries the doc's hash route so it lands on the doc, no arming. **(2) move to another doc** once the pane is open with `navigate({ url })` passing the new target's `preview_url`. A cold `navigate` fails (`No preview is open`) — `preview_start` must open the pane first; and `navigate` (not `preview_eval` hash-poking) is the move verb. `preview_url` auto-starts the OK UI so the `url` resolves before you open. Don't hand-edit host preview config.
- **Cursor / Codex desktop — no `preview_*` tool, but you have an in-app / built-in browser tool** → call `preview_url` once for the **exact** target (`document` for a doc, `folder` for a folder) and navigate your **in-app browser** straight to the returned `url`. Open that deep URL directly — never the root then navigate; omit both args only for the root. Drive the tool your host gives you:
- **Cursor** → its built-in **Browser** tool, the **`Navigate`** action (`browser_navigate`, via Cursor's own `cursor-ide-browser`). Navigate it to the `url` yourself — don't print the URL or shell out to the system browser. (A *surfaced* link in Cursor follows its "Browser Tab" vs "Google Chrome" picker and may open the system browser; you calling `Navigate` avoids that. A third-party MCP like OK cannot push a URL into the pane — only the agent's own `Navigate` can.)
- **Codex desktop app** → its in-app **Browser** plugin (`@Browser`); drive it to the `url` (Codex navigates via `tab.goto`).
@@ -51,12 +50,12 @@ Decide once; then every "open / show / preview this doc" this session uses that
1. You opened/navigated earlier this session → don't reopen.
2. Write response has `previewUrl` (non-null route) and NO `warning` → a browser is attached somewhere; do nothing.
-3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; navigate one-shot (`preview_start`, or `preview_url` → in-app browser).
+3. `warning: { action: "attach-preview-once", previewUrl, message }` → UI reachable, no browser attached; open one-shot (`preview_url` → your host's open verb: `preview_start({ url })` on Claude Desktop; `navigate` / `Navigate` / `@Browser` on Cursor/Codex).
4. `warning: { action: "start-ui", previewUrl: null, message }` → no UI running anywhere. Surface the message verbatim — recovery options are in the in-band copy. Don't loop on retries.
Warnings fire at most once per session in the fresh-start case.
-**Re-point at the end of a multi-doc workflow; don't claim a doc is on screen unless you put it there.** The one-shot attach (signal 3) opens the preview *once* — later writes do NOT move the pane; it stays on the doc you last navigated to. When a turn touches several docs, finish by navigating the preview to the doc the user should land on, using your host's move mechanism (`preview_eval` setting `window.location.hash` from the response `previewUrl`, or `preview_url` → in-app browser; honor `autoOpen`). Until you have navigated there *this* turn, don't tell the user a doc is "open" / "on screen" — at most, say the preview may still be on the doc you opened earlier.
+**Re-point at the end of a multi-doc workflow; don't claim a doc is on screen unless you put it there.** The one-shot attach (signal 3) opens the preview *once* — later writes do NOT move the pane; it stays on the doc you last navigated to. When a turn touches several docs, finish by navigating the preview to the doc the user should land on, using your host's move mechanism (`preview_url` → navigate your in-app browser; honor `autoOpen`). Until you have navigated there *this* turn, don't tell the user a doc is "open" / "on screen" — at most, say the preview may still be on the doc you opened earlier.
**`previewUrl: null` only means "no UI reachable" on the two attach-warning tools: `write` / `edit`.** Workflow tools return prose and don't carry `previewUrl`. `delete` / `move` emit `previousPreviewUrl` (different field, for closing stale tabs) and don't fire attach warnings. `preview_url` auto-starts the backend on demand (same `OK_MCP_AUTOSTART` gate as writes; a cold first call can take seconds) and reports `running: false` + `url: null` only when no UI could be reached — its hint names the right command.
@@ -66,4 +65,4 @@ OK Electron and `ok ui` share `ui.lock`; when a second UI binds a different port
**The preview is read-only for the agent — it is the user's view, not a surface you read back.** You cannot click or type to drive edits — the CRDT flow is one-way (agent → MCP → CRDT → preview).
-**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK's preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed. (Navigating the pane with `preview_eval` by setting `window.location.hash` is fine — that drives the view, it is not a read-back verification loop.)
+**No screenshots to confirm edits, no generic verification loop.** Do NOT take `preview_screenshot` (host tool, not OK MCP) after a write, and do not run a generic snapshot/eval/screenshot verification loop — OK's preview is a read-only, one-way mirror, so the CRDT tool response *is* the confirmation that an edit landed. Screenshot only when debugging a visual rendering issue or when the user explicitly asks to see the preview — never to confirm an edit landed. (Navigating your in-app browser to a `preview_url` route is fine — that drives the view, it is not a read-back verification loop.)
diff --git a/packages/server/src/api-config.test.ts b/packages/server/src/api-config.test.ts
index 545e92046..add55ac8c 100644
--- a/packages/server/src/api-config.test.ts
+++ b/packages/server/src/api-config.test.ts
@@ -1,12 +1,11 @@
import { describe, expect, test } from 'bun:test';
-import { existsSync, mkdtempSync, rmSync } from 'node:fs';
+import { mkdtempSync, rmSync } from 'node:fs';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { tmpdir } from 'node:os';
-import { join, resolve } from 'node:path';
+import { join } from 'node:path';
import { Readable } from 'node:stream';
import { createApiExtension } from './api-extension.ts';
import { getLocalDir } from './config/paths.ts';
-import { armPaneTarget } from './pane-target.ts';
import { acquireServerLock } from './server-lock.ts';
interface CapturedResponse {
@@ -89,29 +88,15 @@ describe('GET /api/config (desktop / worktree collab server)', () => {
collabUrl: string | null;
previewUrl: string | null;
port: number;
- paneTarget: string | null;
};
expect(body.collabUrl).toBe('ws://localhost:7777/collab');
expect(body.previewUrl).toBeNull();
- expect(body.paneTarget).toBeNull();
expect(typeof body.port).toBe('number');
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
- test('surfaces an armed pane target', async () => {
- const dir = mkdtempSync(join(tmpdir(), 'ok-config-'));
- try {
- armPaneTarget(getLocalDir(dir), '#/bim-brain/articles/');
- const result = await call(buildExtension(dir), 'GET', '/api/config');
- const body = JSON.parse(result.body) as { paneTarget: string | null };
- expect(body.paneTarget).toBe('#/bim-brain/articles/');
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
-
test('reports the bound server port from server.lock', async () => {
const dir = mkdtempSync(join(tmpdir(), 'ok-config-'));
try {
@@ -152,52 +137,11 @@ describe('GET /api/config (desktop / worktree collab server)', () => {
}
});
- test('degrades to a null pane target / zero port when projectDir is unconfigured', async () => {
+ test('degrades to a zero port when projectDir is unconfigured', async () => {
const result = await call(buildExtension(undefined), 'GET', '/api/config');
expect(result.status).toBe(200);
- const body = JSON.parse(result.body) as { port: number; paneTarget: string | null };
+ const body = JSON.parse(result.body) as { port: number };
expect(body.port).toBe(0);
- expect(body.paneTarget).toBeNull();
- });
-});
-
-describe('DELETE /api/config one-shot consume', () => {
- test('clears the armed pane target so a later GET no longer surfaces it', async () => {
- const dir = mkdtempSync(join(tmpdir(), 'ok-config-'));
- try {
- const localDir = getLocalDir(dir);
- armPaneTarget(localDir, '#/specs/foo/SPEC');
- expect(existsSync(resolve(localDir, 'pane-target.json'))).toBe(true);
-
- const del = await call(buildExtension(dir), 'DELETE', '/api/config');
- expect(del.status).toBe(204);
- expect(del.body).toBe('');
- expect(existsSync(resolve(localDir, 'pane-target.json'))).toBe(false);
-
- const after = await call(buildExtension(dir), 'GET', '/api/config');
- const body = JSON.parse(after.body) as { paneTarget: string | null };
- expect(body.paneTarget).toBeNull();
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
-
- test('DELETE from a non-loopback Host is rejected and does not clear the arm (DNS-rebind gate)', async () => {
- const dir = mkdtempSync(join(tmpdir(), 'ok-config-'));
- try {
- const localDir = getLocalDir(dir);
- armPaneTarget(localDir, '#/specs/foo/SPEC');
-
- const del = await call(buildExtension(dir), 'DELETE', '/api/config', {
- host: 'evil.example.com',
- });
- expect(del.status).toBe(403);
- // The arm must survive a rejected DELETE — a DNS-rebound page must not
- // be able to clear local TTL state.
- expect(existsSync(resolve(localDir, 'pane-target.json'))).toBe(true);
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
});
});
@@ -207,7 +151,7 @@ describe('/api/config rejects unsupported methods', () => {
try {
const result = await call(buildExtension(dir), 'POST', '/api/config');
expect(result.status).toBe(405);
- expect(result.headers.allow).toBe('GET, HEAD, DELETE');
+ expect(result.headers.allow).toBe('GET, HEAD');
} finally {
rmSync(dir, { recursive: true, force: true });
}
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 6a3e8186b..4bf8e0c2a 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -321,7 +321,6 @@ import {
type FrontmatterMetadata,
parseFrontmatterMetadata,
} from './page-identity.ts';
-import { clearArmedPaneTarget, readArmedPaneTarget } from './pane-target.ts';
import type { RecentlyRemovedDocs } from './recently-removed-docs.ts';
import { readServerLock } from './server-lock.ts';
import {
@@ -17200,49 +17199,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// `/api/config` — collab-bootstrap payload for the React shell. In the
// desktop / worktree-as-project-server topology this collab server is what
// serves the SPA, so the shell fetches `/api/config` here rather than from a
- // separate `ok ui` front. The JSON shape matches `ok ui` (api-config.ts +
- // PaneTargetLanding consume them identically): GET returns
- // `{collabUrl, previewUrl, port, paneTarget}`; DELETE one-shot-consumes the
- // armed pane target (consume-on-apply, so a reload within the TTL doesn't
- // re-navigate). `paneTargetLockDir` is the project's `.ok/local/` — the same
- // anchor the server lock uses; null when projectDir is unconfigured (some
- // test harnesses), which degrades pane-target deep-link to presence-driven
- // while leaving collabUrl bootstrap intact.
- //
- // GET stays open like the other read-only bootstrap endpoints
+ // separate `ok ui` front. The JSON shape matches `ok ui` (api-config.ts
+ // consumes it identically): GET returns `{collabUrl, previewUrl, port}`. GET
+ // stays open like the other read-only bootstrap endpoints
// (document/pages/backlinks) — it carries no PII and only reflects the
- // client's own Host back to itself. DELETE mutates filesystem state
- // (unlinks `pane-target.json`), so it is NOT registered in `MUTATING_ROUTES`
- // (that set is URL-keyed and would gate GET too); instead it carries its own
- // inline loopback + Host-header gate below, matching the file's convention
- // that state-mutating paths pass the DNS-rebinding defense.
- const paneTargetLockDir = projectDir ? getLocalDir(projectDir) : null;
+ // client's own Host back to itself. `lockDir` is the project's
+ // `.ok/local/` (the server-lock anchor); null when projectDir is unconfigured
+ // (some test harnesses), leaving collabUrl bootstrap intact.
+ const lockDir = projectDir ? getLocalDir(projectDir) : null;
async function handleApiConfig(req: IncomingMessage, res: ServerResponse): Promise<void> {
- if (req.method === 'DELETE') {
- // DNS-rebinding defense for the only mutating verb on this route. Mirror
- // the `onRequest` MUTATING_ROUTES gate: a present-but-non-loopback TCP
- // peer or a Host header naming a non-loopback origin is refused. A
- // missing socket is test-context (mocked IncomingMessage) and skips the
- // peer check, same as the shared gate.
- const peerAddress = req.socket?.remoteAddress;
- if (peerAddress !== undefined && !isLoopbackAddress(peerAddress)) {
- errorResponse(res, 403, 'urn:ok:error:loopback-required', 'Loopback required.', {
- handler: 'api-config',
- });
- return;
- }
- if (!isAllowedWorkspaceHostHeader(req.headers.host)) {
- errorResponse(res, 403, 'urn:ok:error:host-not-allowed', 'Host header not allowed.', {
- handler: 'api-config',
- });
- return;
- }
- if (paneTargetLockDir) clearArmedPaneTarget(paneTargetLockDir);
- res.setHeader('Cache-Control', 'no-store');
- res.statusCode = 204;
- res.end();
- return;
- }
if (req.method === 'GET' || req.method === 'HEAD') {
try {
// Same-origin collab WS: the shell loaded from this server, so
@@ -17258,11 +17223,10 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
// Host, so the null path is a malformed-request floor, not a normal case.
const host = req.headers.host;
const collabUrl = host ? `ws://${host}/collab` : null;
- const port = paneTargetLockDir ? (readServerLock(paneTargetLockDir)?.port ?? 0) : 0;
- const paneTarget = paneTargetLockDir ? readArmedPaneTarget(paneTargetLockDir) : null;
+ const port = lockDir ? (readServerLock(lockDir)?.port ?? 0) : 0;
// `singleFile` tells the React shell to drop project chrome for an
// ephemeral single-file session (`ok <file>`).
- const payload = { collabUrl, previewUrl: null, port, paneTarget, singleFile: ephemeral };
+ const payload = { collabUrl, previewUrl: null, port, singleFile: ephemeral };
// HEAD carries the same headers but no body; `successResponse` always
// writes a body, so the no-body verb stays a manual emit.
if (req.method === 'HEAD') {
@@ -17287,7 +17251,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
}
errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {
handler: 'api-config',
- extraHeaders: { Allow: 'GET, HEAD, DELETE' },
+ extraHeaders: { Allow: 'GET, HEAD' },
});
}
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index dc589f1ed..bf5296ca9 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -305,12 +305,6 @@ export {
MissingOkConfigError,
type MissingOkConfigKind,
} from './missing-ok-config-error.ts';
-export {
- armPaneTarget,
- clearArmedPaneTarget,
- PANE_TARGET_TTL_MS,
- readArmedPaneTarget,
-} from './pane-target.ts';
// perf-measurement.ts's HTTP route (installPerfMeasurementHttpRoute) is
// DEV-only test instrumentation for the cap-graduation sweep harness, gated
// behind NODE_ENV + OK_PERF_SERVER_MEMORY_ENABLED. It is intentionally NOT
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index b7e90208d..35799fef6 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -15,10 +15,8 @@ import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { AutoStartDisabledError } from '../../autostart.ts';
-import { resolveLockDir } from '../../config/paths.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { OffCwdResolverDeps } from '../../off-cwd-resolver.ts';
-import { readArmedPaneTarget } from '../../pane-target.ts';
import { register } from './get-preview-url.ts';
import { bindTestServerLock, bindTestUiLock } from './preview-url-test-helpers.ts';
import type { ServerInstance } from './shared.ts';
@@ -39,7 +37,6 @@ type ToolHandler = (args: {
folder?: string;
skill?: { name: string; scope?: 'project' | 'global' };
file?: string;
- armPaneTarget?: boolean;
cwd?: string;
}) => Promise<ToolResult>;
@@ -105,39 +102,6 @@ describe('preview_url tool — UI running', () => {
expect(result.structuredContent?.url).toBe(`${uiBase}/#/My%20Notes/sub/`);
});
- test('armPaneTarget writes the doc route as a readable armed target', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
- const handler = captureRegistration(cwd);
- await handler({ document: 'specs/foo/SPEC', armPaneTarget: true });
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/specs/foo/SPEC');
- });
-
- test('without armPaneTarget: arms nothing (read-only)', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
- const handler = captureRegistration(cwd);
- await handler({ document: 'specs/foo/SPEC' });
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
- });
-
- test('armPaneTarget with no docName/folder: arms nothing + surfaces a note', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
- const handler = captureRegistration(cwd);
- const result = await handler({ armPaneTarget: true });
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
- expect(result.content[0]?.text).toContain('nothing was armed');
- });
-
- test('armPaneTarget with a folder arms the folder route', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
- const handler = captureRegistration(cwd);
- await handler({ folder: 'specs/foo', armPaneTarget: true });
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/specs/foo/');
- });
-
describe('isDesktopTerminal steer (OK Desktop built-in terminal)', () => {
test('document: response leads with `ok open <doc>` and tells the agent not to navigate the URL', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
@@ -244,8 +208,6 @@ describe('preview_url tool — UI running', () => {
const result = await handler({ document: 'specs/foo/SPEC', folder: 'specs/foo' });
expect(result.isError).toBe(true);
expect(result.content[0]?.text).toContain('mutually exclusive');
- // Nothing armed even if both + arm were passed.
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
});
test('without docName: returns the UI root URL', async () => {
@@ -286,14 +248,6 @@ describe('preview_url tool — skill target', () => {
expect(result.structuredContent?.url).toBe(`${uiBase}/#/__skill__/global/run%20tests`);
});
- test('armPaneTarget with a skill arms the skill route', async () => {
- const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
- const handler = captureRegistration(cwd);
- await handler({ skill: { name: 'trip-log' }, armPaneTarget: true });
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/__skill__/project/trip-log');
- });
-
test('skill + document together is rejected (mutually exclusive)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
bindTestUiLock(cwd);
@@ -301,7 +255,6 @@ describe('preview_url tool — skill target', () => {
const result = await handler({ skill: { name: 'trip-log' }, document: 'specs/foo/SPEC' });
expect(result.isError).toBe(true);
expect(result.content[0]?.text).toContain('mutually exclusive');
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBeNull();
});
});
@@ -434,16 +387,15 @@ describe('preview_url tool — backend demand-ensure', () => {
expect(result.content[0]?.text).not.toContain('`ok start`');
});
- test('ensure failure does not lose a requested pane-target arm', async () => {
+ test('spawn failure during demand-ensure surfaces isError', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const handler = captureRegistration(cwd, BASE_CONFIG, {
serverUrl: async () => {
throw new Error('spawn failed: ENOENT');
},
});
- const result = await handler({ document: 'specs/foo/SPEC', armPaneTarget: true });
+ const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.isError).toBe(true);
- expect(readArmedPaneTarget(resolveLockDir(cwd))).toBe('#/specs/foo/SPEC');
});
});
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index c837ef157..65b6d7fb7 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -11,9 +11,10 @@
*
* Use it for hosts that open the URL themselves: an agent with an in-app
* browser navigates that browser to the returned `url`; a stdio host with no
- * browser tool can `open <url>` as a last resort. Hosts with a preview pane
- * (Claude Code Desktop) use `preview_start("open-knowledge-ui")` instead; the
- * Claude Code CLI uses `ok open <doc>` to open in the OK Desktop app.
+ * browser tool can `open <url>` as a last resort. Claude Code Desktop opens
+ * its in-app Browser pane with `preview_start({url})`, then `navigate({url})`
+ * to move; the Claude Code CLI uses `ok open <doc>` to open in the OK Desktop
+ * app.
*
* Opening a preview counts as demand for a backend: when the registration
* threads `serverUrl` (the global stdio MCP does), the handler runs the same
@@ -23,15 +24,11 @@
* Registrations without server authority (no `serverUrl` in deps) answer
* from disk alone, as before.
*
- * Read-mostly EXCEPT when `armPaneTarget: true` — that flag writes a
- * TTL-bounded pane-target file under `.ok/local/` (hence
- * `readOnlyHint: false`) — and except for the demand-spawn above. Idempotent:
- * re-arming the same target is a no-op-equivalent overwrite, and repeated
- * calls converge on the same running backend.
+ * Read-only EXCEPT for the demand-spawn above (`readOnlyHint: false`).
+ * Idempotent: repeated calls converge on the same running backend.
*
- * Input: `{ document?, folder?, armPaneTarget?, cwd? }` — `document` XOR `folder`
- * selects the deep-link route (else the UI root); `armPaneTarget` arms it
- * for a later Claude-pane base-open.
+ * Input: `{ document?, folder?, cwd? }` — `document` XOR `folder`
+ * selects the deep-link route (else the UI root).
* Output: `structuredContent: { url, baseUrl, running, autoOpen }` + a text body.
*/
@@ -46,7 +43,6 @@ import {
type OffCwdResolverDeps,
resolveOffCwdTarget,
} from '../../off-cwd-resolver.ts';
-import { armPaneTarget } from '../../pane-target.ts';
import { isProcessAlive } from '../../process-alive.ts';
import { readServerLock } from '../../server-lock.ts';
import {
@@ -71,7 +67,7 @@ const DESCRIPTION = [
'',
'Per-response `previewUrl` fields on read/write tools are ROUTE-ONLY (`/#/<doc>`, no host:port) — they identify which doc to preview, not a URL to open by itself. Call this tool to get the full, openable URL.',
'',
- 'This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Hosts with a preview pane (Claude Code Desktop) call `preview_start("open-knowledge-ui")` instead; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.',
+ 'This is THE way to open a doc OR a loose file in a browser, and the only way to force a browser when the OK Desktop app is installed (the `ok open` CLI prefers Desktop). Use it when YOUR host opens the URL itself: navigate your in-app / embedded browser to the returned `url`, or — only on a stdio host with no browser tool — `open` it in the system browser. Do not hunt for the URL via `ok ps`/`ok status` or by guessing a port — this tool returns it. Claude Code Desktop opens its in-app Browser pane with `preview_start({url})` then `navigate({url})` to move; a pure stdio CLI with no browser uses `ok open <doc>` to open in the OK Desktop app.',
'',
'Returns `{ url: null, baseUrl: null, running: false, autoOpen }` + a recovery hint only when no UI could be reached (auto-start disabled via `OK_MCP_AUTOSTART=0`, no spawn authority in this registration, or the UI did not bind in time) — the hint names the right command for the actual state.',
'',
@@ -82,7 +78,6 @@ const DESCRIPTION = [
'- `folder` (optional) — Folder path in the current project (e.g. `specs/foo`); returns the `…/#/<folder>/` route. Mutually exclusive with `document`.',
'- `skill` (optional) — A skill to open in the editor: `{ name, scope? }` (scope `project` default). Returns the `…/#/__skill__/<scope>/<name>` route. Mutually exclusive with `document`/`folder`/`file`.',
'- `file` (optional) — Absolute path to a single markdown file, including one outside any project. Resolves to the running single-file / worktree session serving it. Mutually exclusive with `document`/`folder`/`skill`; `cwd` is ignored when set.',
- '- `armPaneTarget` (optional) — When true with a `document`/`folder`/`skill`, writes a small TTL-bounded (~30s) state file under `.ok/local/` so a later Claude-pane base-open lands on that target. Independent of server state; omit it and the call writes nothing.',
'- `cwd` (optional) — Project root (see `cwd` description below).',
].join('\n');
@@ -171,12 +166,6 @@ const InputSchema = {
.describe(
'Absolute path to a single markdown file to open, including one OUTSIDE any Open Knowledge project. Resolves to the running single-file (or worktree) session whose content directory contains it and returns that session’s `url`. Mutually exclusive with `document` / `folder` / `skill`. When `file` is set, `cwd` is ignored.',
),
- armPaneTarget: z
- .boolean()
- .optional()
- .describe(
- 'When true with a `document` or `folder`, arm that target so a subsequent Claude-pane base-open (`preview_start`) lands there instead of the presence-driven default. TTL-bounded (~30s) so a stale arm cannot hijack a later open.',
- ),
cwd: z.string().optional().describe(ROUTED_CWD_DESCRIPTION),
} as const;
@@ -216,9 +205,9 @@ const OutputSchema = outputSchemaWithText({
* together; `ok ui` alone in that state produces a backend-less UI shell.
*/
const NO_UI_SERVER_RUNNING_MESSAGE =
- 'The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or start one: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
+ 'The OK server is running but no UI has bound for this project yet. Retry in a few seconds, or start one: `ok ui` (terminal) or open the project in OK Electron.';
const NO_SERVER_MESSAGE =
- 'No OpenKnowledge server is running for this project. Start it with `ok start` (also starts the preview UI), use `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
+ 'No OpenKnowledge server is running for this project. Start it with `ok start` (also starts the preview UI), or open the project in OK Electron.';
const AUTOSTART_DISABLED_NOTE = ' Auto-start is disabled (OK_MCP_AUTOSTART=0).';
/**
* Resolve `appearance.preview.autoOpen` for the out-of-project `file` branch.
@@ -286,8 +275,7 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
inputSchema: InputSchema,
outputSchema: OutputSchema,
annotations: {
- // NOT read-only: `armPaneTarget: true` writes a pane-target file under
- // `.ok/local/`, and the demand-ensure path can spawn `ok start`.
+ // NOT read-only: the demand-ensure path can spawn `ok start`.
readOnlyHint: false,
idempotentHint: true,
},
@@ -297,7 +285,6 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
folder?: string;
skill?: { name: string; scope?: 'project' | 'global' };
file?: string;
- armPaneTarget?: boolean;
cwd?: string;
}) => {
// `document` / `folder` / `skill` / `file` are documented mutually
@@ -410,30 +397,6 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
? `You're in the OK Desktop terminal — run \`${okOpenCommand}\` to focus this in the OK Desktop window. Don't navigate the URL below or open a browser; it's for reference only.\n\n`
: '';
- // Arm an explicit pane target so a subsequent Claude-pane base-open lands
- // here (TTL-bounded). Independent of whether a UI is currently running —
- // armed BEFORE the backend-ensure below so a pane open that races the
- // spawn still lands on the requested target. Best-effort: arming writes
- // to `.ok/local/`, which can fail (read-only mount, EACCES, ENOSPC); the
- // resolved URL below is valid regardless, so a failed arm must not sink
- // the whole tool call.
- if (args.armPaneTarget && routeFragment) {
- try {
- armPaneTarget(lockDir, routeFragment);
- } catch {
- // Swallow: arming is best-effort and the URL below is valid regardless.
- // When OTel is enabled the failure shows up as the fs.* span armPaneTarget
- // emits; with OTel off (the default) it is intentionally silent.
- }
- }
-
- // Arming with no resolvable target is a silent no-op an agent tends to
- // retry blindly — call it out in the text body so the mistake is visible.
- const armNote =
- args.armPaneTarget && !routeFragment
- ? ' (note: armPaneTarget was set but no document/folder/skill was given, so nothing was armed)'
- : '';
-
// Demand-ensure: when this registration has server authority, run the
// same backend-ensure the server-backed tools use. A live `server.lock`
// resolves immediately (lock read, no HTTP); otherwise the resolver
@@ -485,7 +448,7 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
const hint = isServerLive(lockDir)
? NO_UI_SERVER_RUNNING_MESSAGE
: `${NO_SERVER_MESSAGE}${autoStartDisabled ? AUTOSTART_DISABLED_NOTE : ''}`;
- return textPlusStructured(`${desktopTerminalSteer}${hint}${armNote}`, {
+ return textPlusStructured(`${desktopTerminalSteer}${hint}`, {
url: null,
baseUrl: null,
running: false,
@@ -497,7 +460,7 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void
// baseUrl is non-null here (the lock is bound) — compose base + route.
const url = routeFragment ? `${baseUrl}/${routeFragment}` : baseUrl;
- return textPlusStructured(`${desktopTerminalSteer}Preview URL: ${url}${armNote}`, {
+ return textPlusStructured(`${desktopTerminalSteer}Preview URL: ${url}`, {
url,
baseUrl,
running: true,
diff --git a/packages/server/src/mcp/tools/preview-url.ts b/packages/server/src/mcp/tools/preview-url.ts
index f4667feb9..452232570 100644
--- a/packages/server/src/mcp/tools/preview-url.ts
+++ b/packages/server/src/mcp/tools/preview-url.ts
@@ -96,8 +96,7 @@ export function encodeSkillRoute(scope: string, name: string): string {
* hint fires at most once per session in the fresh-start case.
* - `start-ui` — `previewUrl` is null; no UI is running anywhere for this
* project. Agent advises the user to start one (`ok ui`
- * from a terminal, `preview_start("open-knowledge-ui")` in Claude
- * Code Desktop, or just open the project in OK Electron).
+ * from a terminal, `ok start`, or open the project in OK Electron).
*
* Both pin the same `previewUrl` field so a single agent-side branch can
* read either: if non-null → open; if null → tell user to start a UI.
@@ -126,9 +125,9 @@ type PreviewAttachWarning =
};
const START_UI_MESSAGE =
- 'No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `preview_start("open-knowledge-ui")` (Claude Code Desktop), or open the project in OK Electron.';
+ 'No UI is running for this project. Start one to see the preview: `ok ui` (terminal), `ok start`, or open the project in OK Electron.';
const ATTACH_PREVIEW_ONCE_MESSAGE =
- "No browser is attached to the preview. Open it in your host's surface: `preview_start` (Claude Code Desktop pane), or `preview_url` then navigate your in-app browser to the url (Cursor's `Navigate` / Codex desktop `@Browser`); on the Claude Code CLI, `ok open <doc>`.";
+ "No browser is attached to the preview. Open it in your host's surface: `preview_url`, then drive your in-app browser (Claude Code Desktop: `preview_start({url})` to open the pane, then `navigate({url})` to move; Cursor: `Navigate`; Codex desktop: `@Browser`); on a stdio CLI with no browser, `ok open <doc>`.";
/**
* Build the per-response warning emitted when the server reports zero
diff --git a/packages/server/src/pane-target.test.ts b/packages/server/src/pane-target.test.ts
deleted file mode 100644
index dd1d800c3..000000000
--- a/packages/server/src/pane-target.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { mkdtemp, rm } from 'node:fs/promises';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import {
- armPaneTarget,
- clearArmedPaneTarget,
- PANE_TARGET_TTL_MS,
- readArmedPaneTarget,
-} from './pane-target';
-
-let tmpDir: string;
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-pane-target-'));
-});
-afterEach(async () => {
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-describe('pane-target store', () => {
- test('arm then read within TTL returns the route', () => {
- armPaneTarget(tmpDir, '#/specs/foo/SPEC', 1_000);
- expect(readArmedPaneTarget(tmpDir, 1_000 + 5_000)).toBe('#/specs/foo/SPEC');
- });
-
- test('an arm older than the TTL is ignored (no stale hijack)', () => {
- armPaneTarget(tmpDir, '#/specs/foo/SPEC', 1_000);
- expect(readArmedPaneTarget(tmpDir, 1_000 + PANE_TARGET_TTL_MS + 1)).toBeNull();
- });
-
- test('no arm → null', () => {
- expect(readArmedPaneTarget(tmpDir, 1_000)).toBeNull();
- });
-
- test('last arm wins', () => {
- armPaneTarget(tmpDir, '#/a', 1_000);
- armPaneTarget(tmpDir, '#/b/', 1_100);
- expect(readArmedPaneTarget(tmpDir, 1_200)).toBe('#/b/');
- });
-
- test('a malformed route (not `#/`) is rejected at the write boundary', () => {
- expect(armPaneTarget(tmpDir, 'https://evil.example', 1_000)).toBe(false);
- expect(readArmedPaneTarget(tmpDir, 1_000)).toBeNull();
- // A valid arm still works afterward (the rejection wrote nothing).
- expect(armPaneTarget(tmpDir, '#/ok', 1_000)).toBe(true);
- expect(readArmedPaneTarget(tmpDir, 1_000)).toBe('#/ok');
- });
-
- test('clear consumes the armed target (no re-navigate within TTL)', () => {
- armPaneTarget(tmpDir, '#/specs/foo/SPEC', 1_000);
- clearArmedPaneTarget(tmpDir);
- // Within the TTL, but the target is gone — a reload must not re-navigate.
- expect(readArmedPaneTarget(tmpDir, 1_000 + 5_000)).toBeNull();
- });
-
- test('clear with no arm is a no-op (does not throw)', () => {
- expect(() => clearArmedPaneTarget(tmpDir)).not.toThrow();
- });
-});
diff --git a/packages/server/src/pane-target.ts b/packages/server/src/pane-target.ts
deleted file mode 100644
index 0118398f5..000000000
--- a/packages/server/src/pane-target.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-/**
- * Armed pane-target store for the Claude-pane deep-link override.
- *
- * `preview_start` opens the UI at its base (no hash). By default the app lands
- * presence-driven (the doc the calling agent is on). An agent can OVERRIDE that
- * by arming an explicit target via `preview_url({ armPaneTarget: true })` —
- * which writes the target route here, TTL-bounded so a stale arm cannot hijack
- * a later base-open. The UI server's `/api/config` reads it back on base-open.
- *
- * The stored `route` is a hash fragment (`#/<doc>` or `#/<folder>/`), so the app
- * can apply it to `window.location.hash` directly. State lives in `.ok/local/`
- * (gitignored, per-machine) — never content, never committed.
- */
-
-import { existsSync, readFileSync } from 'node:fs';
-import { resolve } from 'node:path';
-import { tracedMkdirSync, tracedUnlinkSync, tracedWriteFileSync } from './fs-traced.ts';
-
-const PANE_TARGET_FILE = 'pane-target.json';
-
-/** How long an armed target stays valid (ms). A later base-open past this is presence-driven. */
-export const PANE_TARGET_TTL_MS = 30_000;
-
-interface PaneTargetState {
- /** Hash fragment to navigate to, e.g. `#/specs/foo/SPEC` or `#/specs/foo/`. */
- route: string;
- /** Epoch ms the target was armed; used for the TTL bound. */
- armedAtMs: number;
-}
-
-/**
- * Arm an explicit pane target (hash fragment). Overwrites any prior arm.
- * `localDir` is the project's `.ok/local/` directory (the lock dir) — the same
- * path both the arming tool and the UI server's `/api/config` resolve to.
- *
- * Enforces the in-app route shape (`#/…`) at the WRITE boundary so every reader
- * inherits the guarantee; a malformed route is a no-op (never persisted).
- * Returns whether the target was armed.
- */
-export function armPaneTarget(
- localDir: string,
- route: string,
- nowMs: number = Date.now(),
-): boolean {
- if (!route.startsWith('#/')) return false;
- tracedMkdirSync(localDir, { recursive: true });
- const state: PaneTargetState = { route, armedAtMs: nowMs };
- tracedWriteFileSync(resolve(localDir, PANE_TARGET_FILE), JSON.stringify(state));
- return true;
-}
-
-/**
- * Read the armed pane target, or `null` if none is armed or it has expired.
- * Expiry is deliberate: an arm older than the TTL must not hijack a base-open
- * the user triggered for an unrelated reason.
- */
-export function readArmedPaneTarget(
- localDir: string,
- nowMs: number = Date.now(),
- ttlMs: number = PANE_TARGET_TTL_MS,
-): string | null {
- const path = resolve(localDir, PANE_TARGET_FILE);
- if (!existsSync(path)) return null;
- try {
- const state = JSON.parse(readFileSync(path, 'utf-8')) as Partial<PaneTargetState>;
- if (typeof state.route !== 'string' || typeof state.armedAtMs !== 'number') return null;
- if (nowMs - state.armedAtMs > ttlMs) return null;
- return state.route;
- } catch (err) {
- // ENOENT (deleted between existsSync and read) and JSON parse errors are
- // benign races — stay silent. Persistent permission / IO errors, though,
- // would break every pane-target deep-link with no signal; surface those so
- // "preview_start never navigates" is diagnosable.
- const code = (err as { code?: string }).code;
- if (code === 'EACCES' || code === 'EPERM' || code === 'EIO') {
- process.stderr.write(
- `[pane-target] readArmedPaneTarget failed at ${path}: ${err instanceof Error ? err.message : String(err)}\n`,
- );
- }
- return null;
- }
-}
-
-/**
- * Clear any armed pane target. The app calls this AFTER it has applied the
- * target on a base-open, so a reload within the TTL doesn't re-navigate to a
- * target the user already saw (and may have navigated away from). Clearing on
- * apply rather than on read keeps the read non-destructive — `/api/config` is
- * fetched by several consumers (e.g. the collab-URL hook) and only the one that
- * actually applied the target should consume it. Best-effort: a missing file or
- * unlink failure is a no-op (the TTL bound already caps a stale arm's lifetime).
- */
-export function clearArmedPaneTarget(localDir: string): void {
- const path = resolve(localDir, PANE_TARGET_FILE);
- if (!existsSync(path)) return;
- try {
- tracedUnlinkSync(path);
- } catch {
- // Already gone or unwritable — nothing to clear.
- }
-}