Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): serve the UI from the project server by default (PRD-7859) (#3361)
omar-inkeepb5ad64264e5b
diff --git a/.changeset/wave3-ui-default-flip.md b/.changeset/wave3-ui-default-flip.mdnew file mode 100644index 000000000..4b365aa67--- /dev/null+++ b/.changeset/wave3-ui-default-flip.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": minor+---++`ok start` now serves the editor UI from the project server by default — one process, one port, one URL for the editor, `/api/*`, `/mcp`, and `/collab`. The separate `ok ui` sibling process is no longer spawned; `ok ui` keeps working as a deprecated fallback for older desktop builds and will be removed in a later release. Running `ok start` against a project whose server is already up now reports the running server's URL and exits cleanly instead of failing with a lock error, and interactive starts open the editor in your browser automatically (suppress with `--no-open-browser`). New flags: `--bind` replaces `--host` (which keeps working as an alias), `--idle-shutdown <duration|off>` controls the idle window, and `--only server` / `--only ui --server-url <url>` let operators run one module at a time. Desktop and agent tooling discover the editor through `server.lock`'s `url` plus `capabilities: ["ui"]` — the single attach record for every surface.diff --git a/docs/content/get-started/quickstart.mdx b/docs/content/get-started/quickstart.mdxindex 8a20118b7..10905eeb5 100644--- a/docs/content/get-started/quickstart.mdx+++ b/docs/content/get-started/quickstart.mdx@@ -127,7 +127,7 @@ mkdir my-knowledge-base && cd my-knowledge-baseok init# Serve the editor and open it in your browser.-ok start --open+ok start```<Callout type="info">diff --git a/docs/content/migrate/notion.mdx b/docs/content/migrate/notion.mdxindex edb28aef8..325755289 100644--- a/docs/content/migrate/notion.mdx+++ b/docs/content/migrate/notion.mdx@@ -73,7 +73,7 @@ Open OpenKnowledge, choose **Open folder on disk**, select the unzipped export f### Linux, Windows, Intel Mac-`cd` into the unzipped folder and run `ok init && ok start --open`.+`cd` into the unzipped folder and run `ok init && ok start`.## What exports cleanlydiff --git a/docs/content/migrate/obsidian.mdx b/docs/content/migrate/obsidian.mdxindex 4898975d3..e0c7bf7e0 100644--- a/docs/content/migrate/obsidian.mdx+++ b/docs/content/migrate/obsidian.mdx@@ -18,7 +18,7 @@ Open OpenKnowledge, choose **Open folder on disk**, and select your existing vau### Linux, Windows, Intel Mac-Install the [ok CLI](/docs/reference/cli), `cd` into your vault, and run `ok init && ok start --open`.+Install the [ok CLI](/docs/reference/cli), `cd` into your vault, and run `ok init && ok start`.<Callout type="info">Want to know exactly what these commands write to your machine — in your vault, your home directory, and your editors' configs? See [What OpenKnowledge writes to your system](/docs/reference/what-open-knowledge-writes).diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex cafcdbd8b..9d91e47f4 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -40,10 +40,14 @@ In a sub-folder of a git repo, `ok init` sets the project up at the git root —Once you have initialized your project, launch the app in your browser:```bash-ok start --open+ok start```-`ok start` also takes `-p/--port` and `-H/--host` to pick the address, and `--mode app` to hand off to the desktop app instead of running a server in the terminal (macOS with the desktop app installed; can't be combined with `--open`).+One server on one port serves everything — the editor, the API, the MCP endpoint, and real-time collaboration — and the editor opens in your browser automatically (pass `--no-open-browser` to skip that). Running `ok start` again while a server is already up prints the running server's URL and exits.++`ok start` also takes `-p/--port` and `--bind` to pick the address, `--idle-shutdown` (`off` or a duration like `30m`) to control when an unused server exits, `--only server` to run without the editor UI, and `--mode app` to hand off to the desktop app instead of running a server in the terminal (macOS with the desktop app installed).++Idle shutdown is on by default at 30 minutes — a server with no connected clients exits so it doesn't linger. If you keep a session open for a long time without interacting, pass `--idle-shutdown off` (or a longer duration) to keep it running.For a complete list of every file OpenKnowledge creates or changes — during install, at runtime, and in the desktop app — see [What OpenKnowledge writes to your system](/docs/reference/what-open-knowledge-writes).diff --git a/docs/content/reference/configuration.mdx b/docs/content/reference/configuration.mdxindex 1e755662a..53fa75811 100644--- a/docs/content/reference/configuration.mdx+++ b/docs/content/reference/configuration.mdx@@ -134,7 +134,7 @@ Hovering a link in the editor shows a preview card. For **internal links** (otheFor **external links**, a card shows the destination's site name, page title, description, and favicon. It is **on by default**; turn it off per machine in Settings.<Callout type="info">- **Desktop app:** external link previews are not yet available in the packaged desktop app (its `file://` renderer is rejected by the preview route's anti-proxy gate), so this default applies to the browser and `ok ui` surfaces. Internal document-to-document previews work everywhere.+ **Desktop app:** external link previews are not yet available in the packaged desktop app (its `file://` renderer is rejected by the preview route's anti-proxy gate), so this default applies to the browser (`ok start`) surface. Internal document-to-document previews work everywhere.</Callout><Callout type="warn">diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 95d6ef194..654f93dd9 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -99,7 +99,7 @@ The app runs a collaboration server for the open project. It writes runtime stat| Path | What it is | Scope || --- | --- | --- |-| `.ok/local/server.lock`, `.ok/local/ui.lock` | Advertise the running server's and web UI's ports | In-project, gitignored |+| `.ok/local/server.lock` (and `.ok/local/ui.lock` on the legacy `--ui-port` path) | Advertise the running server's URL; `ok start` now serves the UI from the same server, so `ui.lock` is written only by the deprecated sibling path | In-project, gitignored || `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored || `.ok/local/sync-state.json`, `.ok/local/conflicts.json` | GitHub-sync engine state | In-project, gitignored || `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the UI sibling's error log | In-project, gitignored |@@ -212,7 +212,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a| Path | What it is | Scope || --- | --- | --- |-| `.ok/local/server.lock`, `.ok/local/ui.lock` | Advertise the running server's and web UI's ports | In-project, gitignored |+| `.ok/local/server.lock` (and `.ok/local/ui.lock` on the legacy `--ui-port` path) | Advertise the running server's URL; `ok start` now serves the UI from the same server, so `ui.lock` is written only by the deprecated sibling path | In-project, gitignored || `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored || `.ok/local/sync-state.json`, `.ok/local/conflicts.json` | GitHub-sync engine state | In-project, gitignored || `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the UI sibling's error log | In-project, gitignored |diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsindex 87d216fcd..dd2081fc4 100644--- a/packages/cli/src/cli.ts+++ b/packages/cli/src/cli.ts@@ -256,7 +256,8 @@ program.addCommand(lintCommand(() => resolvedConfig));// the running project server; CLI sibling of the `audit` MCP toolprogram.addCommand(auditCommand(() => resolvedConfig));-// ui command — serves the React editor (sibling of `start`).+// ui command — deprecated sibling UI server; kept functional for the Desktop+// version-skew window (plain `ok start` now serves the UI itself).const ui = uiCommand(() => resolvedConfig);program.addCommand(ui);diff --git a/packages/cli/src/commands/single-file-open.ts b/packages/cli/src/commands/single-file-open.tsindex e6f9fb587..867d0b323 100644--- a/packages/cli/src/commands/single-file-open.ts+++ b/packages/cli/src/commands/single-file-open.ts@@ -13,9 +13,7 @@* a tab, and removes the temp projectDir on teardown.*/-import { existsSync } from 'node:fs';import { rm } from 'node:fs/promises';-import { resolve } from 'node:path';import {encodeDocName,prepareSingleFileOpen,@@ -120,21 +118,6 @@ export async function runSingleFileOpen(return 0;}-/**- * Resolve the bundled React shell `dist` directory — published `dist/public`- * first, then the monorepo `app/dist`. Mirrors `ok ui`'s resolution so dev and- * published builds agree.- */-function resolveReactShellDistDir(): string | undefined {- const cliDir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;- const candidates = [- resolve(cliDir, 'public'), // npm install: dist/public/- resolve(cliDir, '../../app/dist'), // monorepo dev from src/- resolve(cliDir, '../../../app/dist'), // monorepo dev from dist/- ];- return candidates.find((p) => existsSync(p));-}-/*** Browser fallback: boot an ephemeral single-file server in this process* (serving the React shell single-origin via `--react-shell-dist-dir`, so there@@ -149,10 +132,10 @@ async function runSingleFileBrowserOpen(): Promise<void> {const { createEphemeralProjectDir } = await import('@inkeep/open-knowledge-server');const { loadConfig } = await import('../index.ts');- const { bootStartServer, resolveHost } = await import('./start.ts');+ const { bootStartServer, resolveBundledReactShellDir, resolveHost } = await import('./start.ts');const { openBrowser } = await import('../utils/open-browser.ts');- const reactShellDistDir = resolveReactShellDistDir();+ const reactShellDistDir = resolveBundledReactShellDir();if (!reactShellDistDir) {process.stderr.write('OpenKnowledge UI assets were not found. Reinstall @inkeep/open-knowledge, or build the app (`bun run build`) in a monorepo checkout.\n',diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.tsindex d2570a102..49c9e8060 100644--- a/packages/cli/src/commands/start.test.ts+++ b/packages/cli/src/commands/start.test.ts@@ -18,13 +18,21 @@ import {connectUiSibling,decideUiSpawn,deriveServerProcessTitle,+ formatServerReuseNotice,formatShutdownNotice,+ isLoopbackHost,isServerLockCollision,OkDirMissingError,+ parseIdleShutdownFlag,+ parseOnlyModule,+ resolveBundledReactShellDir,resolveCollabPort,resolveHost,+ resolveServerReuse,resolveStartConsoleLevel,+ resolveStartShellDir,shouldConnectToExistingServer,+ shouldOpenBrowser,spawnOkUi,startCommand,teardownUiSibling,@@ -36,7 +44,7 @@ import {import { closeHttpServers, startUiServer, type UiServerHandle } from './ui.ts';describe('resolveHost', () => {- test('returns --host flag when present (highest priority)', () => {+ test('returns --host flag when --bind is absent (second priority, after --bind)', () => {expect(resolveHost({ host: '0.0.0.0' }, { HOST: '127.0.0.2' })).toBe('0.0.0.0');});@@ -939,6 +947,25 @@ describe('bootStartServer (integration)', () => {expect(body.detail).toContain('/');});+ test('idleThresholdMs: null (--idle-shutdown off) threads through and boots (not the 30-min default)', async () => {+ // Load-bearing distinction: bootStartServer uses an explicit `=== undefined`+ // check, not `??`, so `null` disables idle shutdown rather than falling back+ // to DEFAULT_IDLE_THRESHOLD_MS. A refactor to `?? DEFAULT` would silently+ // re-enable the 30-min timer under `--idle-shutdown off`. Boot succeeding+ // with `null` proves the value is accepted and threaded to bootServer,+ // whose own `idleShutdownMs: null` contract disables the timer.+ booted = await bootStartServer({+ config: makeTestConfig(),+ cwd: tmpDir,+ host: TEST_HOST,+ skipAutoInit: true,+ skipUiAutoSpawn: true,+ idleThresholdMs: null,+ });+ expect(booted.port).toBeGreaterThan(0);+ await booted.ready;+ });+test('GET /assets/anything also returns the same pointer (no static fallthrough)', async () => {// Pre-split the SPA fell through to dist/public/. Post-split there is no// static handler in `ok start` at all — every non-/api path returns the@@ -2120,6 +2147,7 @@ describe('tryDescribeLockCollision', () => {class ServerLockCollisionError extends Error {}return {ServerLockCollisionError,+ resolveLockDir: (projectDir: string) => join(projectDir, '.ok', 'local'),readServerLock: () => {if (opts.throwOnRead) throw new Error('synthetic read failure');return opts.meta;@@ -2134,12 +2162,12 @@ describe('tryDescribeLockCollision', () => {expect(result).toBeNull();});- test("kind='interactive' → desktop-running message", () => {+ test("kind='interactive' → generic message (covers terminal AND desktop holders)", () => {const fm = fakeServerModule({ meta: { kind: 'interactive', pid: 42, port: 3000 } });const err = new fm.ServerLockCollisionError();const result = tryDescribeLockCollision(err, '/tmp/proj', fm);- expect(result).toContain('desktop is currently running');- expect(result).toContain('--cwd');+ expect(result).toContain('already running');+ expect(result).not.toContain('desktop');});test("kind='mcp-spawned' → MCP idle-shutdown message", () => {@@ -2229,3 +2257,452 @@ describe('withEphemeralTempDirReap', () => {expect(removed).toEqual(['/tmp/ok-ephemeral-throw']);});});++describe('resolveHost — --bind precedence', () => {+ test('--bind wins over the deprecated --host alias and env', () => {+ expect(resolveHost({ bind: ['0.0.0.0'], host: '127.0.0.2' }, { HOST: '127.0.0.3' })).toBe(+ '0.0.0.0',+ );+ });++ test('empty bind list falls through to --host', () => {+ expect(resolveHost({ bind: [], host: '127.0.0.2' }, {})).toBe('127.0.0.2');+ });+});++describe('parseOnlyModule', () => {+ test('accepts ui and server', () => {+ expect(parseOnlyModule('ui')).toBe('ui');+ expect(parseOnlyModule('server')).toBe('server');+ });++ test('rejects anything else', () => {+ expect(() => parseOnlyModule('api')).toThrow(/--only must be/);+ });+});++describe('resolveBundledReactShellDir (candidate-path probe)', () => {+ test('returns the first candidate that exists', () => {+ // Injected existsFn accepts any path — asserts the probe returns the FIRST+ // hit (the published `dist/public` slot is tried before the monorepo paths).+ const dir = resolveBundledReactShellDir(() => true);+ expect(dir).not.toBeUndefined();+ expect(dir?.endsWith('public')).toBe(true);+ });++ test('returns undefined when no candidate exists (→ API/MCP-only degrade)', () => {+ expect(resolveBundledReactShellDir(() => false)).toBeUndefined();+ });+});++describe('resolveStartShellDir (the Wave 3 default-flip decision)', () => {+ const bundled = () => '/bundled/dist';+ const noBundle = () => undefined;++ test('default: resolves the bundled shell — the flip', () => {+ expect(+ resolveStartShellDir({+ explicitDir: undefined,+ only: undefined,+ uiPortSet: false,+ remoteEnabled: false,+ findBundledDir: bundled,+ }),+ ).toEqual({ dir: '/bundled/dist', missingBundle: false });+ });++ test('explicit --react-shell-dist-dir always wins', () => {+ expect(+ resolveStartShellDir({+ explicitDir: '/explicit',+ only: undefined,+ uiPortSet: true,+ remoteEnabled: false,+ findBundledDir: noBundle,+ }).dir,+ ).toBe('/explicit');+ });++ test('--only server opts out of the UI module entirely', () => {+ expect(+ resolveStartShellDir({+ explicitDir: undefined,+ only: 'server',+ uiPortSet: false,+ remoteEnabled: false,+ findBundledDir: bundled,+ }),+ ).toEqual({ dir: undefined, missingBundle: false });+ });++ test('--ui-port keeps the legacy sibling model (worktree-preview recipe)', () => {+ expect(+ resolveStartShellDir({+ explicitDir: undefined,+ only: undefined,+ uiPortSet: true,+ remoteEnabled: false,+ findBundledDir: bundled,+ }),+ ).toEqual({ dir: undefined, missingBundle: false });+ });++ test('remote overrides the --ui-port opt-out — one tunnel covers everything', () => {+ expect(+ resolveStartShellDir({+ explicitDir: undefined,+ only: undefined,+ uiPortSet: true,+ remoteEnabled: true,+ findBundledDir: bundled,+ }).dir,+ ).toBe('/bundled/dist');+ });++ test('missing bundle degrades (API/MCP-only) and is flagged for the warning', () => {+ expect(+ resolveStartShellDir({+ explicitDir: undefined,+ only: undefined,+ uiPortSet: false,+ remoteEnabled: false,+ findBundledDir: noBundle,+ }),+ ).toEqual({ dir: undefined, missingBundle: true });+ });+});++describe('isLoopbackHost', () => {+ test('loopback shapes', () => {+ expect(isLoopbackHost('127.0.0.1')).toBe(true);+ expect(isLoopbackHost('127.1.2.3')).toBe(true);+ expect(isLoopbackHost('localhost')).toBe(true);+ expect(isLoopbackHost('::1')).toBe(true);+ expect(isLoopbackHost('[::1]')).toBe(true);+ });++ test('non-loopback shapes', () => {+ expect(isLoopbackHost('0.0.0.0')).toBe(false);+ expect(isLoopbackHost('::')).toBe(false);+ expect(isLoopbackHost('192.168.1.5')).toBe(false);+ });+});++describe('shouldOpenBrowser (interactive-loopback default open)', () => {+ const base = {+ openBrowser: true,+ legacyOpen: false,+ host: '127.0.0.1',+ isTTY: true,+ remoteEnabled: false,+ ephemeral: false,+ only: undefined,+ servesUi: true,+ } as const;++ test('interactive loopback start serving the UI opens by default', () => {+ expect(shouldOpenBrowser({ ...base })).toBe(true);+ });++ test('--no-open-browser suppresses', () => {+ expect(shouldOpenBrowser({ ...base, openBrowser: false })).toBe(false);+ });++ test('deprecated --open force-opens even without a TTY (pre-flip contract)', () => {+ expect(shouldOpenBrowser({ ...base, legacyOpen: true, isTTY: false })).toBe(true);+ });++ test('no TTY (spawned/CI) stays quiet', () => {+ expect(shouldOpenBrowser({ ...base, isTTY: false })).toBe(false);+ });++ test('non-loopback bind stays quiet', () => {+ expect(shouldOpenBrowser({ ...base, host: '0.0.0.0' })).toBe(false);+ });++ test('remote mode stays quiet', () => {+ expect(shouldOpenBrowser({ ...base, remoteEnabled: true })).toBe(false);+ });++ test('ephemeral single-file stays quiet (owns its own open flow)', () => {+ expect(shouldOpenBrowser({ ...base, ephemeral: true })).toBe(false);+ });++ test('--only server stays quiet', () => {+ expect(shouldOpenBrowser({ ...base, only: 'server' })).toBe(false);+ });++ test('a start that ended up serving no shell stays quiet', () => {+ expect(shouldOpenBrowser({ ...base, servesUi: false })).toBe(false);+ });++ // Guard-ordering regressions: --open must not override the "nothing to open"+ // or "explicit no" suppressions (only the TTY / loopback gates).+ test('--open does NOT open a dead tab at a shell-less --only server', () => {+ expect(shouldOpenBrowser({ ...base, legacyOpen: true, only: 'server', servesUi: false })).toBe(+ false,+ );+ });++ test('--open does NOT open when no shell was served', () => {+ expect(shouldOpenBrowser({ ...base, legacyOpen: true, servesUi: false })).toBe(false);+ });++ test('--no-open-browser wins over --open (explicit no)', () => {+ expect(shouldOpenBrowser({ ...base, legacyOpen: true, openBrowser: false })).toBe(false);+ });+});++describe('resolveServerReuse (spawn-or-reuse)', () => {+ const immediate = { now: () => 0, sleep: async () => {}, timeoutMs: 1000, pollIntervalMs: 10 };++ test('ui-capable holder: reports the lock v2 url (the canonical one-URL contract)', async () => {+ const info = await resolveServerReuse({+ ...immediate,+ readServerLock: () => ({+ pid: 42,+ port: 24_550,+ url: 'http://127.0.0.1:24550',+ kind: 'interactive',+ capabilities: ['http', 'ws', 'ui'],+ }),+ readUiLock: () => null,+ });+ expect(info).toEqual({+ url: 'http://127.0.0.1:24550',+ kind: 'interactive',+ pid: 42,+ servesUi: true,+ });+ });++ test('sibling topology (no ui capability): reports the live ui.lock advertisement', async () => {+ const info = await resolveServerReuse({+ ...immediate,+ readServerLock: () => ({+ pid: 42,+ port: 24_550,+ url: 'http://127.0.0.1:24550',+ capabilities: ['http', 'ws'],+ }),+ readUiLock: () => ({ pid: 43, port: 39_847 }),+ });+ expect(info?.url).toBe('http://localhost:39847');+ expect(info?.servesUi).toBe(false);+ });++ test('sibling topology: prefers the ui.lock url when present (IPv6 bind, not localhost)', async () => {+ const info = await resolveServerReuse({+ ...immediate,+ readServerLock: () => ({ pid: 42, port: 24_550, capabilities: ['http', 'ws'] }),+ readUiLock: () => ({ pid: 43, port: 39_847, url: 'http://[::1]:39847' }),+ });+ expect(info?.url).toBe('http://[::1]:39847');+ expect(info?.servesUi).toBe(false);+ });++ test('no ui anywhere: falls back to the server address', async () => {+ const info = await resolveServerReuse({+ ...immediate,+ readServerLock: () => ({ pid: 42, port: 24_550 }),+ readUiLock: () => null,+ });+ expect(info?.url).toBe('http://127.0.0.1:24550');+ });++ test('polls through the pre-listen port-0 sentinel to the bound port', async () => {+ let clock = 0;+ let reads = 0;+ const info = await resolveServerReuse({+ readServerLock: () => {+ reads += 1;+ return reads < 3+ ? { pid: 42, port: 0 }+ : {+ pid: 42,+ port: 24_550,+ url: 'http://127.0.0.1:24550',+ capabilities: ['http', 'ws', 'ui'],+ };+ },+ readUiLock: () => null,+ now: () => clock,+ sleep: async (ms) => {+ clock += ms;+ },+ timeoutMs: 1000,+ pollIntervalMs: 10,+ });+ expect(info?.url).toBe('http://127.0.0.1:24550');+ });++ test('draining holder yields null (caller falls back to the error path)', async () => {+ const info = await resolveServerReuse({+ ...immediate,+ readServerLock: () => ({ pid: 42, port: 24_550, draining: true }),+ readUiLock: () => null,+ });+ expect(info).toBeNull();+ });++ test('sentinel that never binds times out to null', async () => {+ let clock = 0;+ const info = await resolveServerReuse({+ readServerLock: () => ({ pid: 42, port: 0 }),+ readUiLock: () => null,+ now: () => clock,+ sleep: async (ms) => {+ clock += ms;+ },+ timeoutMs: 100,+ pollIntervalMs: 10,+ });+ expect(info).toBeNull();+ });++ test('missing lock yields null', async () => {+ const info = await resolveServerReuse({+ ...immediate,+ readServerLock: () => null,+ readUiLock: () => null,+ });+ expect(info).toBeNull();+ });+});++describe('formatServerReuseNotice', () => {+ test("kind='interactive' gets the neutral copy — it covers terminal AND desktop holders", () => {+ const lines = formatServerReuseNotice({+ url: 'http://127.0.0.1:1',+ kind: 'interactive',+ pid: 7,+ servesUi: true,+ });+ expect(lines[0]).toContain('already running');+ expect(lines[0]).not.toContain('desktop');+ expect(lines.join('\n')).toContain('http://127.0.0.1:1');+ });++ test('names the mcp-spawned holder and the generic holder', () => {+ expect(+ formatServerReuseNotice({ url: 'u', kind: 'mcp-spawned', pid: 7, servesUi: true })[0],+ ).toContain('MCP-spawned');+ expect(formatServerReuseNotice({ url: 'u', pid: 7, servesUi: false })[0]).toContain(+ 'already running',+ );+ });+});++describe('parseIdleShutdownFlag (--idle-shutdown, Table 3 semantics)', () => {+ test("'off' disables idle shutdown (null)", () => {+ expect(parseIdleShutdownFlag('off')).toBeNull();+ });++ test('parses s/m/h durations to ms', () => {+ expect(parseIdleShutdownFlag('90s')).toBe(90_000);+ expect(parseIdleShutdownFlag('30m')).toBe(1_800_000);+ expect(parseIdleShutdownFlag('2h')).toBe(7_200_000);+ });++ test('rejects unitless, zero-led, and unknown-unit values', () => {+ for (const bad of ['30', '0s', '05m', '1d', 'forever', '']) {+ expect(() => parseIdleShutdownFlag(bad)).toThrow(/--idle-shutdown/);+ }+ });+});++describe('startCommand — flag-conflict guards (exit 2)', () => {+ function quietCommand() {+ const cmd = startCommand(() => makeTestConfig());+ cmd.exitOverride();+ cmd.configureOutput({ writeOut: () => {}, writeErr: () => {} });+ return cmd;+ }++ /**+ * Parse argv against the real `startCommand` action with process.exit ++ * stderr stubbed, returning the captured exit code and stderr. Each guard+ * exits before any server boot, so no teardown is needed.+ */+ async function captureGuard(+ argv: string[],+ ): Promise<{ code: number | undefined; stderr: string }> {+ const cmd = quietCommand();+ let code: number | undefined;+ let stderr = '';+ const originalExit = process.exit;+ const originalWrite = process.stderr.write.bind(process.stderr);+ process.exit = ((c?: number) => {+ code = c;+ throw new Error('exit-stub');+ }) as never;+ process.stderr.write = ((chunk: unknown) => {+ stderr += String(chunk);+ return true;+ }) as never;+ try {+ await cmd.parseAsync(argv, { from: 'user' });+ } catch (err) {+ if ((err as Error).message !== 'exit-stub') throw err;+ } finally {+ process.exit = originalExit;+ process.stderr.write = originalWrite;+ }+ return { code, stderr };+ }++ test('multiple --bind addresses exit 2', async () => {+ const { code, stderr } = await captureGuard(['--bind', '127.0.0.1', '--bind', '10.0.0.1']);+ expect(code).toBe(2);+ expect(stderr).toContain('--bind');+ });++ test('--server-url without --only ui exits 2', async () => {+ const { code, stderr } = await captureGuard(['--server-url', 'http://127.0.0.1:24550']);+ expect(code).toBe(2);+ expect(stderr).toContain('--server-url');+ });++ test('--only ui without --server-url exits 2', async () => {+ const { code, stderr } = await captureGuard(['--only', 'ui']);+ expect(code).toBe(2);+ expect(stderr).toContain('--server-url');+ });++ test('--only server + --react-shell-dist-dir exits 2', async () => {+ const { code, stderr } = await captureGuard([+ '--only',+ 'server',+ '--react-shell-dist-dir',+ '/tmp/shell',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('--react-shell-dist-dir');+ });++ test('--only ui + --mode app exits 2 (would silently drop --mode app)', async () => {+ const { code, stderr } = await captureGuard([+ '--only',+ 'ui',+ '--server-url',+ 'http://127.0.0.1:24550',+ '--mode',+ 'app',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('--mode app');+ });++ test('--only ui + --remote exits 2 (would silently drop --remote)', async () => {+ const { code, stderr } = await captureGuard([+ '--only',+ 'ui',+ '--server-url',+ 'http://127.0.0.1:24550',+ '--remote',+ 'https://tunnel.example.com',+ ]);+ expect(code).toBe(2);+ expect(stderr).toContain('--remote');+ });+});diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex 48dd1f03e..0f851b90e 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -1,14 +1,22 @@/**- * `open-knowledge start` — collab server only (Hocuspocus + /api/*).+ * `open-knowledge start` — the OpenKnowledge project server.*- * Lifecycle split:- * - `ok start` owns the WebSocket (/collab) + HTTP API (/api/*) and advertises- * its port via `server.lock`. Static React assets are served by `ok ui`.- * - On startup we auto-spawn `ok ui` as a detached sibling when `ui.lock` is- * absent or stale. A pre-existing live UI is left alone.- * - Idle-shutdown counts WebSocket upgrades at `/collab` only; it is blind- * to DirectConnections by design. When the threshold fires we SIGTERM the- * UI sibling before releasing our own lock.+ * One listener, one origin: by default the server serves the React shell on+ * `/` alongside `/api/*`, `/mcp`, `/collab`, and content assets, and+ * advertises the one URL via `server.lock` (`url` + `capabilities: ["ui"]` —+ * the Desktop attach contract). A second `ok start` against a live server+ * reports that URL and exits 0 (spawn-or-reuse) instead of colliding.+ *+ * The legacy two-process model (`ok ui` sibling serving the shell and+ * proxying `/api` + `/collab`, advertised via `ui.lock`) survives on two+ * paths only, for the Desktop version-skew window:+ * - `--ui-port` (the worktree-preview recipe) keeps the sibling model.+ * - `ok ui` remains functional as a deprecated fallback.+ * Idle-shutdown SIGTERMs a spawned sibling before releasing our own lock.+ *+ * `--only server` suppresses the UI module entirely; `--only ui` (with+ * `--server-url`) runs just the shell-serving proxy — explicit operator+ * module selection against the same composition, never a separate topology.** The Commander action is a thin wrapper around `bootStartServer` — that* boot function returns a `BootedStartServer` handle (`{httpServer, destroy,@@ -39,11 +47,11 @@ import {type PinoLogger,prepareSingleFileOpen,} from '@inkeep/open-knowledge-server';-import { Command, InvalidArgumentError } from 'commander';+import { Command, InvalidArgumentError, Option } from 'commander';import { makeLazyEmbeddingsKeyStore } from '../auth/embeddings-key-store.ts';import { detectGh } from '../auth/gh-detect.ts';import { makeLazyProbeTokenStore } from '../auth/token-store.ts';-import { OK_DIR, PACKAGE_VERSION } from '../constants.ts';+import { PACKAGE_VERSION } from '../constants.ts';import { probeOwnManagedEditorMcpEntry } from './acp-harness-probe.ts';import {createRealDetectDeps,@@ -57,15 +65,139 @@ import { resolveSelfSpawn } from './self-spawn.ts';const DEFAULT_IDLE_THRESHOLD_MS = 30 * 60 * 1000;/**- * Resolve server bind host with `--host` flag > `HOST` env > application- * default precedence. Pure helper — no side effects, no `process.env` access- * inside (env passed in) so tests can pin all three branches.+ * Resolve server bind host with `--bind` flag > deprecated `--host` alias >+ * `HOST` env > application default precedence. Pure helper — no side effects,+ * no `process.env` access inside (env passed in) so tests can pin all+ * branches. `--bind` is declared repeatable (the config surface reserves a+ * bind LIST); the action layer rejects >1 value until multi-bind lands, so+ * only the first element is consulted here.*/export function resolveHost(- opts: { host?: string },+ opts: { host?: string; bind?: string[] },env: { HOST?: string | undefined; [key: string]: string | undefined },): string {- return opts.host ?? env.HOST ?? DEFAULT_SERVER_HOST;+ return opts.bind?.[0] ?? opts.host ?? env.HOST ?? DEFAULT_SERVER_HOST;+}++/** Modules selectable via `--only` — explicit operator module selection. */+export type OnlyModule = 'ui' | 'server';++/**+ * Validator for Commander's `--only` parser. Throws `InvalidArgumentError`+ * for anything outside the documented enum, which Commander converts into a+ * non-zero exit + usage.+ */+export function parseOnlyModule(value: string): OnlyModule {+ if (value === 'ui' || value === 'server') return value;+ throw new InvalidArgumentError("--only must be 'ui' or 'server'");+}++/**+ * Resolve the bundled React shell `dist` directory — published `dist/public`+ * first, then the monorepo `app/dist`. One resolver shared by plain+ * `ok start`, remote mode, and the ephemeral single-file browser fallback so+ * dev and published builds can never disagree on where the shell lives.+ */+export function resolveBundledReactShellDir(+ existsFn: (path: string) => boolean = fsExistsSync,+): string | undefined {+ const cliDir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;+ return [+ pathResolve(cliDir, 'public'), // npm install: dist/public/ (bundled)+ pathResolve(cliDir, '../../app/dist'), // monorepo dev from src/+ pathResolve(cliDir, '../../../app/dist'), // monorepo dev from dist/+ ].find((p) => existsFn(p));+}++/**+ * Decide which React-shell directory the composed server serves — the Wave 3+ * default-flip decision, pure so every branch is unit-tested:+ *+ * - an explicit `--react-shell-dist-dir` always wins;+ * - `--only server` opts out of the UI module entirely;+ * - `--ui-port` (the worktree-preview recipe) keeps the legacy sibling model+ * until its retirement — EXCEPT under `--remote`, which always serves the+ * shell on the tunneled port;+ * - otherwise the bundled shell is resolved and served by default. A missing+ * bundle (source checkout without an app build) degrades to API/MCP-only —+ * the `ok ui` sibling would be serving the same missing bundle, so falling+ * back to it could never help.+ */+export function resolveStartShellDir(input: {+ explicitDir: string | undefined;+ only: OnlyModule | undefined;+ uiPortSet: boolean;+ remoteEnabled: boolean;+ findBundledDir: () => string | undefined;+}): { dir: string | undefined; missingBundle: boolean } {+ if (input.explicitDir !== undefined) return { dir: input.explicitDir, missingBundle: false };+ if (input.only === 'server') return { dir: undefined, missingBundle: false };+ if (input.uiPortSet && !input.remoteEnabled) return { dir: undefined, missingBundle: false };+ const dir = input.findBundledDir();+ return { dir, missingBundle: dir === undefined };+}++/**+ * Validator for `--idle-shutdown <dur|off>`: `off`, or a strict `<n>(s|m|h)`+ * duration. Returns milliseconds, or `null` for `off` (idle shutdown+ * disabled). The grammar mirrors the forthcoming `server.idleShutdown` config+ * leaf so the flag and the key resolve durations identically.+ */+export function parseIdleShutdownFlag(value: string): number | null {+ if (value === 'off') return null;+ const match = /^([1-9]\d*)(s|m|h)$/.exec(value);+ if (match === null) {+ throw new InvalidArgumentError("--idle-shutdown must be 'off' or a duration like 90s, 30m, 2h");+ }+ const amount = Number(match[1]);+ switch (match[2]) {+ case 's':+ return amount * 1000;+ case 'm':+ return amount * 60_000;+ default:+ return amount * 3_600_000;+ }+}++/** Loopback-shaped bind hosts — the family the browser-open default keys on. */+export function isLoopbackHost(host: string): boolean {+ return host === 'localhost' || host === '::1' || host === '[::1]' || host.startsWith('127.');+}++/**+ * Should this start open the browser? Interactive loopback starts open by+ * default (suppress with `--no-open-browser`); everything non-interactive or+ * non-local stays quiet. Pure so the whole decision table is unit-tested:+ *+ * Guard order matters. The "nothing to open" and "explicit no" checks run+ * BEFORE the deprecated `--open` force-open, so `--open` can override the TTY+ * and loopback gates (its pre-flip contract) but can never pop a dead tab at+ * a shell-less server or fight an explicit `--no-open-browser`:+ *+ * - `--no-open-browser` always suppresses, even against `--open`;+ * - remote mode, ephemeral single-file (owns its own open flow), `--only+ * server`, and a start that ended up serving no shell never open;+ * - `--open` (deprecated) then forces open, preserving its pre-flip contract+ * for scripts that relied on it in non-TTY contexts;+ * - otherwise: open iff the bind is loopback AND stdout is a TTY (a spawned+ * or CI invocation must not pop a browser).+ */+export function shouldOpenBrowser(input: {+ openBrowser: boolean;+ legacyOpen: boolean;+ host: string;+ isTTY: boolean;+ remoteEnabled: boolean;+ ephemeral: boolean;+ only: OnlyModule | undefined;+ servesUi: boolean;+}): boolean {+ if (!input.openBrowser) return false;+ if (input.remoteEnabled || input.ephemeral || input.only === 'server') return false;+ if (!input.servesUi) return false;+ if (input.legacyOpen) return true;+ return isLoopbackHost(input.host) && input.isTTY;}/**@@ -691,8 +823,9 @@ interface BootStartServerOptions {skipUiAutoSpawn?: boolean;/** Override for `spawnOkUi`'s underlying spawn — passed through to it. */spawn?: typeof NativeSpawn;- /** Override idle-shutdown threshold; default 30 min. Tests use small values. */- idleThresholdMs?: number;+ /** Override idle-shutdown threshold; default 30 min. `null` disables idle+ * shutdown entirely (`--idle-shutdown off`). Tests use small values. */+ idleThresholdMs?: number | null;/*** Override the process-exit call fired after an idle-shutdown teardown* completes (see `withIdleShutdownProcessExit`). Default `process.exit`.@@ -855,7 +988,10 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Booconst { config, cwd, host } = opts;const skipAutoInit = opts.skipAutoInit ?? false;const skipUiAutoSpawn = opts.skipUiAutoSpawn ?? false;- const idleThresholdMs = opts.idleThresholdMs ?? DEFAULT_IDLE_THRESHOLD_MS;+ // Explicit undefined check (not `??`): `null` means "idle shutdown OFF"+ // (`--idle-shutdown off`) and must not fall back to the 30-min default.+ const idleThresholdMs =+ opts.idleThresholdMs === undefined ? DEFAULT_IDLE_THRESHOLD_MS : opts.idleThresholdMs;const { existsSync, mkdirSync } = await import('node:fs');const { basename, dirname } = await import('node:path');@@ -1020,10 +1156,11 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo}};- // When --react-shell-dist-dir is set, the server itself serves the React- // shell — the `ok ui` sibling is redundant and auto-suppressed. This is- // the desktop-spawn-mode shape (single-origin renderer); terminal-launched- // `ok start` keeps the historical two-process model.+ // The server serves the React shell whenever it has a dist dir, which is+ // the default for plain `ok start` — so the single-origin composition is+ // the norm and the `ok ui` sibling is auto-suppressed. A sibling is spawned+ // only on the legacy two-process paths that reach here without a shell dir+ // (the `--ui-port` worktree-preview recipe).const attachUiSibling = opts.reactShellDistDir === undefined;// Push-permission probe auth wiring — LAZY token store. Keyring init is@@ -1128,9 +1265,10 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Booreturn withIdleShutdownProcessExit(reaped, { log, exit: opts.idleExit });},log,- // Content assets serve by default (bootServer default-on); the React- // shell stays a desktop-spawn opt-in so terminal `ok start` retains the- // two-process shell model (`ok ui` sibling).+ // Content assets serve by default (bootServer default-on). The React+ // shell dir is passed through when present — the default for plain+ // `ok start` — so the one-listener composition is the norm; it is absent+ // only on the legacy `--ui-port` sibling path....(opts.serveContentAssets !== undefined? { serveContentAssets: opts.serveContentAssets }: {}),@@ -1201,8 +1339,32 @@ interface StartCommandOptions {* the main checkout and a fresh worktree. Absent → today's behavior.*/uiPort?: string | number;+ /** From repeatable `--bind <address>`. First value wins today; >1 rejected at the action layer. */+ bind?: string[];+ /** From the deprecated `-H, --host` alias of `--bind`. */host?: string;+ /** From deprecated `--open`: force-open the browser (pre-flip contract, honored even non-TTY). */open?: boolean;+ /**+ * From `--no-open-browser` (Commander negation: absent → `true`). Interactive+ * loopback starts open the browser by default; this is the suppression+ * direction — see `shouldOpenBrowser` for the full decision table.+ */+ openBrowser?: boolean;+ /**+ * From `--only <ui|server>`: explicit module selection. `'server'` boots the+ * project server with no UI module (no shell, no sibling); `'ui'` is handled+ * in the action (delegates to the UI proxy with `--server-url`) and never+ * reaches `runStartCommand`.+ */+ only?: OnlyModule;+ /** From `--server-url <url>`: where the `--only ui` split-mode UI finds its project server. */+ serverUrl?: string;+ /**+ * From `--idle-shutdown <dur|off>` (already parsed by `parseIdleShutdownFlag`):+ * idle-shutdown threshold in ms, or `null` for `off`. Absent → 30-min default.+ */+ idleShutdown?: number | null;/** From `--mode`: undefined (default → browser) | 'browser' | 'app'. */mode?: StartMode;/**@@ -1418,25 +1580,27 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)}}- // Remote mode serves the SPA from the same remote port (`/` = UI, `/mcp` =- // MCP) so one tunnel covers both. Resolve the bundled shell the way `ok ui`- // does; an explicit --react-shell-dist-dir still wins. Missing shell (rare:- // source checkout without an app build) degrades to MCP/API-only with a- // warning rather than failing the start. Passing reactShellDistDir also- // suppresses the `ok ui` sibling spawn — one UI, one port, in remote mode.- let reactShellDistDir = opts.reactShellDistDir;- if (remoteEnabled && reactShellDistDir === undefined) {- const cliDir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;- reactShellDistDir = [- pathResolve(cliDir, 'public'), // npm install: dist/public/ (bundled)- pathResolve(cliDir, '../../app/dist'), // monorepo dev from src/- pathResolve(cliDir, '../../../app/dist'), // monorepo dev from dist/- ].find((p) => fsExistsSync(p));- if (reactShellDistDir === undefined) {- console.warn(- 'remote access: bundled web UI not found — serving /mcp and /api only over the tunnel.',- );- }+ // The default composition serves the SPA from the server's own port (`/` =+ // UI, `/api`, `/mcp`, `/collab` — one listener, one origin), which also+ // auto-suppresses the `ok ui` sibling. `resolveStartShellDir` holds the+ // decision table (explicit dir wins; `--only server` and the `--ui-port`+ // worktree-preview recipe opt out; remote always serves the shell so one+ // tunnel covers everything). A missing bundle degrades to API/MCP-only with+ // a warning rather than failing the start.+ const shell = resolveStartShellDir({+ explicitDir: opts.reactShellDistDir,+ only: opts.only,+ uiPortSet: requestedUiPort !== undefined,+ remoteEnabled,+ findBundledDir: resolveBundledReactShellDir,+ });+ const reactShellDistDir = shell.dir;+ if (shell.missingBundle) {+ console.warn(+ remoteEnabled+ ? 'remote access: bundled web UI not found — serving /mcp and /api only over the tunnel.'+ : 'bundled web UI not found — serving /api and /mcp only. Reinstall @inkeep/open-knowledge, or build packages/app in a source checkout.',+ );}let booted: BootedStartServer;@@ -1451,6 +1615,11 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)? { serveContentAssets: opts.serveContentAssets }: {}),...(reactShellDistDir ? { reactShellDistDir } : {}),+ // No sibling spawn when the UI module is off (`--only server`) or the+ // bundle is missing — a spawned `ok ui` would be serving the same+ // missing bundle, and the warning above already promised API/MCP-only.+ ...(opts.only === 'server' || shell.missingBundle ? { skipUiAutoSpawn: true } : {}),+ ...(opts.idleShutdown !== undefined ? { idleThresholdMs: opts.idleShutdown } : {}),...(opts.singleFile ? { singleFile: opts.singleFile } : {}),...(opts.projectDir ? { projectDir: opts.projectDir } : {}),...(remoteEnabled ? { enableRemote: true } : {}),@@ -1505,6 +1674,46 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)return;}+ // Spawn-or-reuse: a plain `ok start` that collided with a live server+ // reads the holder's advertisement, reports its URL, and exits 0 — a+ // second start attaches to the running composition instead of failing.+ // Falls through to the tailored/generic error path (exit 1) only when the+ // lock can't be resolved to a usable address within the poll window.+ if (requestedUiPort === undefined && isServerLockCollision(err, serverModule)) {+ const lockDir = serverModule.resolveLockDir(cwd);+ // A lock read can throw mid-poll (EMFILE, a JSON rewrite caught in+ // flight). Contain it so a transient disk error degrades to the tailored+ // collision message below rather than escaping as a raw stack trace.+ let reuse: ServerReuseInfo | null = null;+ try {+ reuse = await resolveServerReuse({+ readServerLock: () => serverModule.readServerLock(lockDir),+ readUiLock: () => serverModule.readUiLock(lockDir),+ now: Date.now,+ sleep: (ms) => wait(ms),+ timeoutMs: 3000,+ pollIntervalMs: 50,+ });+ } catch (reuseErr) {+ // Fall through to tryDescribeLockCollision / the generic error path —+ // but leave a trace: a lock read that throws mid-poll (EMFILE burst,+ // JSON caught mid-rewrite) would otherwise make "already running" or+ // the collision message appear with the underlying disk fault+ // invisible. stderr keeps stdout clean for scripts.+ process.stderr.write(+ `[start] spawn-or-reuse: lock poll failed (${reuseErr instanceof Error ? reuseErr.message : String(reuseErr)}) — falling back to the collision message\n`,+ );+ }+ if (reuse !== null) {+ const [headline, ...rest] = formatServerReuseNotice(reuse);+ console.log(accent(headline));+ for (const line of rest) {+ console.log(dim(line));+ }+ process.exit(0);+ }+ }+// On server.lock collision, READ the existing lock to give a// holder-specific message ("desktop is running on this project")// instead of the generic "Failed to start." Failure to read@@ -1581,18 +1790,21 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)void shutdown('SIGTERM');});- const apiUrl = `http://${host}:${booted.port}`;+ // Bracket a bare IPv6 literal for the authority (`::1` → `[::1]`); an+ // unbracketed IPv6 host produces a malformed `http://::1:PORT` that the+ // browser-open default would now actually navigate to (--bind ::1 on a TTY).+ const urlHost = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;+ const apiUrl = `http://${urlHost}:${booted.port}`;const networkUrl =host === '0.0.0.0' || host === '::' ? `http://0.0.0.0:${booted.port}` : undefined;- // The user-facing URL is the `ok ui` sibling, not the collab/API port.- // Use `resolvedUiPort` — bootStartServer polls `ui.lock` end-to-end so- // this reflects the port the child actually bound (kernel-allocated,- // not a hardcoded default). When the UI sibling did not bind in time- // (or spawn was skipped) we fall back to the API URL so the user still- // has an actionable URL.+ // On the default one-listener path the server serves the shell itself, so+ // `resolvedUiPort` is null and `localUrl` IS `apiUrl` — the editor URL, not+ // a degraded fallback. `resolvedUiPort` is non-null only on the legacy+ // `--ui-port` sibling path, where bootStartServer polls `ui.lock`+ // end-to-end for the port the sibling actually bound.const uiPort = booted.resolvedUiPort;- const localUrl = uiPort !== null && uiPort > 0 ? `http://${host}:${uiPort}` : apiUrl;+ const localUrl = uiPort !== null && uiPort > 0 ? `http://${urlHost}:${uiPort}` : apiUrl;console.log(renderBanner({@@ -1621,7 +1833,20 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)console.log();}- if (opts.open) {+ // Interactive loopback starts open the browser by default now that the+ // banner URL is the full editor (suppress with --no-open-browser; the+ // deprecated --open force-opens). Decision table: `shouldOpenBrowser`.+ const openDecision = shouldOpenBrowser({+ openBrowser: opts.openBrowser !== false,+ legacyOpen: opts.open === true,+ host,+ isTTY: process.stdout.isTTY === true,+ remoteEnabled,+ ephemeral: opts.singleFile !== undefined,+ only: opts.only,+ servesUi: reactShellDistDir !== undefined,+ });+ if (openDecision) {const { openBrowser } = await import('../utils/open-browser.ts');openBrowser(localUrl);}@@ -1633,6 +1858,104 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)});}+/** What a reused (already-running) server advertises — see `resolveServerReuse`. */+export interface ServerReuseInfo {+ /** The browser-facing URL of the running composition. */+ url: string;+ /** Lock holder's `kind` (`interactive` = any direct boot, terminal or desktop; `mcp-spawned`). */+ kind?: string | undefined;+ pid: number;+ /** True when the running server itself serves the React shell (lock v2 `capabilities` includes `"ui"`). */+ servesUi: boolean;+}++interface ResolveServerReuseDeps {+ readServerLock: () => {+ pid: number;+ port: number;+ url?: string;+ kind?: string;+ draining?: boolean;+ capabilities?: string[];+ } | null;+ readUiLock: () => { pid: number; port: number; url?: string } | null;+ now: () => number;+ sleep: (ms: number) => Promise<void>;+ timeoutMs: number;+ pollIntervalMs: number;+}++/**+ * Spawn-or-reuse resolution: a second `ok start` that lost the server.lock+ * acquisition reads the live holder's advertisement and reports it instead of+ * failing. Returns the holder's browser-facing URL, or `null` when the lock+ * can't be resolved to a usable address (caller falls back to the error path).+ *+ * Polls through the pre-listen window (`port: 0` sentinel) so racing a+ * predecessor that is still binding reports its real address rather than+ * failing on the sentinel. URL preference order:+ *+ * 1. lock v2 `url` when the holder advertises the `ui` capability — the+ * canonical one-URL contract (the same record Desktop attaches through);+ * 2. a live `ui.lock` advertisement — the sibling topology (an older server+ * or `--only server`), where the browser-facing origin is the UI process;+ * 3. the server's own `url`/port — API+MCP only, but still the right address.+ *+ * All time + IO deps injected (precedent #13b) so tests drive every branch+ * with a virtual clock and no filesystem.+ */+export async function resolveServerReuse(+ deps: ResolveServerReuseDeps,+): Promise<ServerReuseInfo | null> {+ const deadline = deps.now() + deps.timeoutMs;+ let lock = deps.readServerLock();+ while (lock !== null && lock.draining !== true && lock.port <= 0 && deps.now() < deadline) {+ await deps.sleep(deps.pollIntervalMs);+ lock = deps.readServerLock();+ }+ if (lock === null || lock.draining === true || lock.port <= 0) return null;+ if (lock.capabilities?.includes('ui') === true && lock.url !== undefined) {+ return { url: lock.url, kind: lock.kind, pid: lock.pid, servesUi: true };+ }+ const uiLock = deps.readUiLock();+ if (uiLock !== null && uiLock.port > 0) {+ // Prefer the ui.lock's own advertised url (symmetric with the server.lock+ // branch above) — a UI bound to `::1` on a host where `localhost` resolves+ // to `127.0.0.1` would otherwise be reported at the wrong address.+ return {+ url: uiLock.url ?? `http://localhost:${uiLock.port}`,+ kind: lock.kind,+ pid: lock.pid,+ servesUi: false,+ };+ }+ return {+ url: lock.url ?? `http://${DEFAULT_SERVER_HOST}:${lock.port}`,+ kind: lock.kind,+ pid: lock.pid,+ servesUi: false,+ };+}++/**+ * The reuse notice a second `ok start` prints before exiting 0. Pure so the+ * copy (and the holder-kind variants) are unit-tested. `kind: 'interactive'`+ * covers BOTH terminal `ok start` and desktop-spawned servers (every direct+ * boot stamps it), so it gets the neutral copy — only `mcp-spawned` is a+ * genuinely distinguishable holder.+ */+export function formatServerReuseNotice(info: ServerReuseInfo): string[] {+ const holder =+ info.kind === 'mcp-spawned'+ ? 'An MCP-spawned OpenKnowledge server is already running on this project'+ : 'OpenKnowledge is already running on this project';+ return [+ `${holder} (pid ${info.pid}).`,+ ` ${info.url}`,+ 'Leaving it running — run `ok stop` first if you want a fresh server.',+ ];+}+/*** True when `err` is the typed server-lock collision `bootStartServer` throws* because a live process already holds this folder's `server.lock`. Used by the@@ -1665,14 +1988,15 @@ export function tryDescribeLockCollision(if (lockErr === undefined || !(err instanceof lockErr)) return null;try {- const lockDir = join(cwd, OK_DIR);- const meta = serverModule.readServerLock(lockDir);+ // `.ok/local/` — the same anchor the server writes (join(cwd, OK_DIR)+ // pointed one level too shallow and always fell back to the generic copy).+ const meta = serverModule.readServerLock(serverModule.resolveLockDir(cwd));if (!meta) {return 'OpenKnowledge server is already running on this project — check `ok status` or `ok stop`.';}- if (meta.kind === 'interactive') {- return 'OpenKnowledge desktop is currently running on this project. Quit it or use --cwd to point elsewhere.';- }+ // NOTE: `kind: 'interactive'` covers both terminal and desktop servers,+ // so it takes the generic fallthrough below — a "desktop is running"+ // claim here would be wrong for every terminal-started holder.if (meta.kind === 'mcp-spawned') {return 'An MCP-spawned server holds this lock; it should release on idle-shutdown (~30 min). Or run `ok stop`.';}@@ -1686,15 +2010,43 @@ export function tryDescribeLockCollision(export function startCommand(getConfig: () => Config): Command {const cmd = new Command('start')- .description('Start the knowledge base collab server')+ .description('Start the OpenKnowledge server (UI + API + MCP + collab on one port)').option('-p, --port <port>', 'Server port', undefined).option('--ui-port <port>','Pin the ok ui sibling to <port> and connect (not exit) if a server already runs here — the worktree-preview recipe path',parseUiPort,)- .option('-H, --host <host>', 'Server host', undefined)- .option('--open', 'Open browser after start')+ .option(+ '--bind <address>',+ 'Bind address (repeatable; default 127.0.0.1 — loopback only)',+ (value: string, prev: string[] | undefined) => [...(prev ?? []), value],+ )+ // Deprecated alias of --bind — kept working for the skew window, hidden+ // from --help so new scripts reach for the locked name.+ .addOption(new Option('-H, --host <host>', 'Deprecated alias of --bind').hideHelp())+ .option(+ '--no-open-browser',+ 'Do not open the browser after start (interactive loopback starts open it by default)',+ )+ // Deprecated: pre-flip opt-in, now the default for interactive loopback+ // starts. Kept as a force-open for scripts that relied on it (it opens+ // even without a TTY). Hidden from --help.+ .addOption(new Option('--open', 'Deprecated: force-open the browser after start').hideHelp())+ .option(+ '--only <module>',+ "Serve one module: 'server' (API + MCP only, no shell or browser) or 'ui' (shell + proxy only; requires --server-url)",+ parseOnlyModule,+ )+ .option(+ '--server-url <url>',+ 'Project-server URL the --only ui process proxies to (e.g. http://127.0.0.1:24550)',+ )+ .option(+ '--idle-shutdown <duration>',+ "Shut the server down after this long with no connected clients ('off', or a duration like 90s, 30m, 2h; default 30m)",+ parseIdleShutdownFlag,+ ).option('--mode <mode>', "Force dispatch mode: 'browser' or 'app'", parseStartMode).option('--serve-content-assets',@@ -1719,6 +2071,65 @@ export function startCommand(getConfig: () => Config): Command {.action(async (opts: StartCommandOptions) => {const config = getConfig();+ // `--bind` is declared repeatable because the config surface reserves a+ // bind LIST, but multi-bind isn't implemented yet — reject loudly+ // rather than silently binding only the first address.+ if (opts.bind !== undefined && opts.bind.length > 1) {+ process.stderr.write(+ 'error: multiple --bind addresses are not supported yet — pass a single address\n',+ );+ process.exit(2);+ }++ // `--server-url` only means something to the --only ui proxy.+ if (opts.serverUrl !== undefined && opts.only !== 'ui') {+ process.stderr.write("error: option '--server-url' requires '--only ui'\n");+ process.exit(2);+ }++ // `--only server` promises "no UI module" — an explicit shell dir+ // contradicts it. Fail loud rather than pick a winner silently.+ if (opts.only === 'server' && opts.reactShellDistDir !== undefined) {+ process.stderr.write(+ "error: option '--only server' cannot be combined with '--react-shell-dist-dir'\n",+ );+ process.exit(2);+ }++ // `--only ui`: run just the shell-serving proxy against an explicit+ // upstream — the operator split-mode replacement for bare `ok ui`+ // (which discovers its upstream via server.lock instead).+ if (opts.only === 'ui') {+ if (opts.serverUrl === undefined) {+ process.stderr.write(+ "error: '--only ui' requires '--server-url <url>' (where the project server runs)\n",+ );+ process.exit(2);+ }+ // `--only ui` runs the proxy in-process and returns below, before the+ // --mode app handoff and before runStartCommand reads --remote — so+ // either combination would silently drop a flag. Reject loudly.+ if (opts.mode === 'app') {+ process.stderr.write("error: option '--only ui' cannot be combined with '--mode app'\n");+ process.exit(2);+ }+ if (opts.remote !== undefined && opts.remote !== false) {+ process.stderr.write("error: option '--only ui' cannot be combined with '--remote'\n");+ process.exit(2);+ }+ const { runUiCommand } = await import('./ui.ts');+ await runUiCommand(config, {+ ...(opts.port !== undefined ? { port: String(opts.port) } : {}),+ ...(opts.bind?.[0] !== undefined+ ? { host: opts.bind[0] }+ : opts.host !== undefined+ ? { host: opts.host }+ : {}),+ upstreamUrl: opts.serverUrl,+ });+ return;+ }+// `--mode=app` shortcuts the server boot and hands off to the// desktop app. Mutually exclusive with --open (which opens a// browser tab against the local server, which app mode does not@@ -1742,7 +2153,12 @@ export function startCommand(getConfig: () => Config): Command {const ignored: string[] = [];if (opts.port !== undefined) ignored.push('--port');if (opts.uiPort !== undefined) ignored.push('--ui-port');+ if (opts.bind !== undefined) ignored.push('--bind');if (opts.host !== undefined) ignored.push('--host');+ if (opts.only !== undefined) ignored.push('--only');+ if (opts.serverUrl !== undefined) ignored.push('--server-url');+ if (opts.idleShutdown !== undefined) ignored.push('--idle-shutdown');+ if (opts.openBrowser === false) ignored.push('--no-open-browser');if (ignored.length > 0) {// Debug-level surface; reuse the existing program log-level// gate (--log-level=debug). Inline check to avoid a logger dep.diff --git a/packages/cli/src/commands/status.test.ts b/packages/cli/src/commands/status.test.tsindex c0ac288ad..7dbee3188 100644--- a/packages/cli/src/commands/status.test.ts+++ b/packages/cli/src/commands/status.test.ts@@ -2,7 +2,7 @@ import { describe, expect, test } from 'vitest';import type { LockState } from './lock-state.ts';import { buildStatusReport, renderStatusText, runStatus } from './status.ts';-function alive(pid: number, port: number, host = 'host'): LockState {+function alive(pid: number, port: number, host = 'host', capabilities?: string[]): LockState {return {status: 'alive',lockPath: `/tmp/fake-${pid}.lock`,@@ -12,6 +12,7 @@ function alive(pid: number, port: number, host = 'host'): LockState {hostname: host,startedAt: '2026-04-16T00:00:00Z',worktreeRoot: '/x',+ ...(capabilities !== undefined ? { capabilities } : {}),},};}@@ -88,6 +89,24 @@ describe('buildStatusReport', () => {expect(r.server.alive).toBe('unknown');expect(r.server.host).toBe('other-box');});++ test('single-listener default: ui.lock missing but server advertises `ui` → ui served by server', () => {+ // The Wave 3 flip writes only server.lock (capabilities incl. `ui`); a+ // "not running" ui row would be a false negative. Synthesize it instead.+ const r = buildStatusReport(alive(100, 3001, 'host', ['http', 'ws', 'ui']), missing());+ expect(r.ui.state).toBe('alive');+ expect(r.ui.alive).toBe(true);+ expect(r.ui.servedByServer).toBe(true);+ expect(r.ui.pid).toBe(100);+ expect(r.ui.port).toBe(3001);+ });++ test('server without the `ui` capability leaves a missing ui.lock as not-running', () => {+ // `--only server`: no UI anywhere, so the ui row must stay honest.+ const r = buildStatusReport(alive(100, 3001, 'host', ['http', 'ws']), missing());+ expect(r.ui.state).toBe('missing');+ expect(r.ui.servedByServer).toBeUndefined();+ });});describe('renderStatusText', () => {@@ -98,6 +117,14 @@ describe('renderStatusText', () => {expect(out).toContain('started=2026-04-16T00:00:00Z');});+ test('ui served by server renders "served by server", not "not running"', () => {+ const out = renderStatusText(+ buildStatusReport(alive(100, 3001, 'host', ['http', 'ws', 'ui']), missing()),+ );+ expect(out).toContain('served by server pid=100 port=3001');+ expect(out).not.toContain('ui not running');+ });+test('missing entries render "not running"', () => {const out = renderStatusText(buildStatusReport(missing(), missing()));expect(out).toContain('not running');diff --git a/packages/cli/src/commands/status.ts b/packages/cli/src/commands/status.tsindex a9819078c..14604cb5d 100644--- a/packages/cli/src/commands/status.ts+++ b/packages/cli/src/commands/status.ts@@ -20,6 +20,10 @@ interface StatusEntry {/** Resolved `alive` verdict — `true` for local-live locks, `false` for* `missing` / `dead-pid` / `corrupt`, `'unknown'` for foreign-host. */alive: boolean | 'unknown';+ /** UI only: the UI is served by the project server itself (single-listener+ * default — server.lock advertises the `ui` capability and no ui.lock+ * exists), rather than by a separate `ok ui` sibling. */+ servedByServer?: boolean;}interface StatusReport {@@ -28,10 +32,30 @@ interface StatusReport {}export function buildStatusReport(server: LockState, ui: LockState): StatusReport {- return {- server: summarize('server', server),- ui: summarize('ui', ui),- };+ const serverEntry = summarize('server', server);+ let uiEntry = summarize('ui', ui);+ // Single-listener default (Wave 3 flip): plain `ok start` serves the UI from+ // the project server and writes NO ui.lock. Without this, the ui row would+ // read "not running" while the editor is fully up at the server's port — a+ // false negative for anyone scripting against `ok status`. Synthesize the ui+ // state from server.lock's `ui` capability instead.+ if (+ uiEntry.state === 'missing' &&+ server.status === 'alive' &&+ server.lock.capabilities?.includes('ui') === true+ ) {+ uiEntry = {+ name: 'ui',+ state: 'alive',+ pid: server.lock.pid,+ port: server.lock.port,+ startedAt: server.lock.startedAt,+ host: server.lock.hostname,+ alive: true,+ servedByServer: true,+ };+ }+ return { server: serverEntry, ui: uiEntry };}function summarize(name: 'server' | 'ui', state: LockState): StatusEntry {@@ -92,6 +116,9 @@ function renderEntry(entry: StatusEntry): string {return `${label} stale (dead pid=${entry.pid}) — run \`ok clean\``;}// alive+ if (entry.servedByServer === true) {+ return `${label} served by server pid=${entry.pid} port=${entry.port}`;+ }return `${label} alive pid=${entry.pid} port=${entry.port} started=${entry.startedAt}`;}diff --git a/packages/cli/src/commands/ui.test.ts b/packages/cli/src/commands/ui.test.tsindex 35704570d..e509f3410 100644--- a/packages/cli/src/commands/ui.test.ts+++ b/packages/cli/src/commands/ui.test.ts@@ -29,6 +29,7 @@ import {DEFAULT_UI_PORT,DEFAULT_UI_SAFETY_NET_MS,isNonInteractiveContext,+ parseUpstreamUrl,resolveRequestedPort,resolveUiLockCollision,startUiServer,@@ -399,6 +400,43 @@ describe('startUiServer', () => {expect(headers.get('cache-control')).toBe('no-store');});+ test('explicit upstreamUrl (split mode) proxies /api to that upstream with NO server.lock', async () => {+ // `ok start --only ui --server-url <url>`: the operator owns the wiring, so+ // /api routes to the explicit upstream via `resolveUpstream`, not server.lock+ // discovery. No server.lock is acquired here — discovery would find nothing,+ // so a proxied 200 proves the explicit upstream path is the one taken.+ let sawApi = false;+ const upstream = await startDualLoopbackUpstream((req, res) => {+ if (req.url?.startsWith('/api/')) {+ sawApi = true;+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ via: 'explicit-upstream' }));+ return;+ }+ res.statusCode = 404;+ res.end();+ });+ try {+ handle = await startUiServer({+ config: config(),+ cwd: tmpDir,+ port: 0,+ host: '127.0.0.1',+ upstreamUrl: `http://127.0.0.1:${upstream.port}`,+ });+ const { status, body } = await get(handle.port, '/api/pages');+ expect(status).toBe(200);+ expect(JSON.parse(body).via).toBe('explicit-upstream');+ expect(sawApi).toBe(true);+ // /api/config advertises a collabUrl because an upstream is resolvable,+ // even though no server.lock exists.+ const cfg = JSON.parse((await get(handle.port, '/api/config')).body);+ expect(cfg.collabUrl).toBe(`ws://127.0.0.1:${handle.port}/collab`);+ } finally {+ await upstream.close();+ }+ });+test('HEAD /api/config returns 200 with no body', async () => {handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });const res = await fetch(`http://127.0.0.1:${handle.port}/api/config`, { method: 'HEAD' });@@ -1292,3 +1330,42 @@ describe('isNonInteractiveContext — PRD-6704 keepalive gate', () => {expect(isNonInteractiveContext(makeProc({ isTTY: true, port: '' }))).toBe(false);});});++describe('parseUpstreamUrl (--server-url for the split-mode UI)', () => {+ test('parses host and explicit port', () => {+ expect(parseUpstreamUrl('http://127.0.0.1:24550')).toEqual({ host: '127.0.0.1', port: 24550 });+ });++ test('defaults the port to 80 when absent', () => {+ expect(parseUpstreamUrl('http://ok-server.internal')).toEqual({+ host: 'ok-server.internal',+ port: 80,+ });+ });++ test('strips IPv6 brackets from hostname (url.hostname, not url.host)', () => {+ // WHATWG `url.hostname` de-brackets IPv6 (`::1`), which is what+ // node:http.request expects; `url.host` would retain `[::1]` and fail to+ // dial. Pins the hostname-vs-host choice against a future refactor.+ expect(parseUpstreamUrl('http://[::1]:24550')).toEqual({ host: '::1', port: 24550 });+ });++ test('drops any path component — the proxy dials host:port only', () => {+ // Documents the behavior: `--server-url http://host:port/api` proxies to+ // the bare root, NOT the /api subpath. If path-prefixed upstreams ever+ // need support, this is the test that must change with the parser.+ expect(parseUpstreamUrl('http://127.0.0.1:24550/api')).toEqual({+ host: '127.0.0.1',+ port: 24550,+ });+ });++ test('rejects non-http schemes — the proxy speaks plain HTTP', () => {+ expect(() => parseUpstreamUrl('https://kb.example.com')).toThrow(/must be http:/);+ expect(() => parseUpstreamUrl('ws://127.0.0.1:1')).toThrow(/must be http:/);+ });++ test('rejects unparseable input with the fix in the message', () => {+ expect(() => parseUpstreamUrl('not a url')).toThrow(/expected e\.g\./);+ });+});diff --git a/packages/cli/src/commands/ui.ts b/packages/cli/src/commands/ui.tsindex 381be3514..6dfdb164e 100644--- a/packages/cli/src/commands/ui.ts+++ b/packages/cli/src/commands/ui.ts@@ -1,6 +1,14 @@/*** `open-knowledge ui` — serves the React editor UI as a sibling to `ok start`.*+ * DEPRECATED as a user-facing command: plain `ok start` now serves the shell+ * from the project server on one port. This command remains functional for+ * the Desktop version-skew window (older desktop builds attach through it and+ * `ui.lock`) and as the engine behind `ok start --only ui --server-url` (the+ * explicit split-mode, which passes `upstreamUrl` instead of discovering the+ * upstream via `server.lock`). Do not remove until the Desktop attach+ * re-point has shipped in a stable release.+ ** Default port `DEFAULT_UI_PORT` (39847 — quirky, IANA-unassigned, unlikely to* 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@@ -149,6 +157,41 @@ interface StartUiServerOptions {* controlled tmp dist — but also lets an embedder point at a custom build.*/assetDir?: string;+ /**+ * Explicit upstream project-server URL (`ok start --only ui --server-url`).+ * When set, `/api/*` proxying and `/collab` upgrade forwarding dial this+ * address instead of discovering the upstream via `server.lock` — the+ * split-mode contract where the operator owns the wiring. `http:` only (the+ * proxy speaks plain `node:http`; TLS termination belongs to the operator's+ * ingress, in front of both halves).+ */+ upstreamUrl?: string;+}++/**+ * Parse `--server-url` into the host/port pair the proxy dials. Exported for+ * tests. Rejects non-`http:` schemes: the split-mode proxy is plain+ * `node:http`, and a TLS upstream would silently downgrade.+ *+ * IPv6: `url.hostname` KEEPS the brackets (`[::1]`), but `node:http`'s `host`+ * option wants the bare address (`::1`) — so strip them here, or the proxy+ * would fail to dial an IPv6 upstream.+ */+export function parseUpstreamUrl(raw: string): { host: string; port: number } {+ let url: URL;+ try {+ url = new URL(raw);+ } catch {+ throw new Error(`Invalid --server-url '${raw}' — expected e.g. http://127.0.0.1:24550`);+ }+ if (url.protocol !== 'http:') {+ throw new Error(+ `--server-url must be http: (got '${url.protocol}//') — the UI proxy speaks plain HTTP; terminate TLS at your ingress`,+ );+ }+ const port = url.port !== '' ? Number(url.port) : 80;+ const host = url.hostname.replace(/^\[(.+)\]$/, '$1');+ return { host, port };}/**@@ -240,6 +283,22 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe}): null;+ // Upstream resolution — one closure shared by the `/api` proxy, the+ // `/collab` upgrade forwarder, and `/api/config`. An explicit+ // `--server-url` (split mode) wins; otherwise discover the project server+ // via `server.lock` on every call so a later `ok start` shows up without a+ // UI restart.+ const explicitUpstream =+ opts.upstreamUrl !== undefined ? parseUpstreamUrl(opts.upstreamUrl) : null;+ const resolveUpstream = (): { host: string; port: number } | null => {+ if (explicitUpstream !== null) return explicitUpstream;+ const lock = readServerLock(lockDir);+ if (!lock || lock.port <= 0) return null;+ // Dial the data server on the same numeric IPv4 loopback it binds — see+ // DEFAULT_SERVER_HOST's JSDoc for why not `localhost`.+ return { host: DEFAULT_SERVER_HOST, port: lock.port };+ };+// Resolved port — filled in after listen(). /api/config reads from this so// the advertised `port` matches what the kernel actually bound (matters// when opts.port is 0).@@ -289,7 +348,6 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe// `useCollabUrl` hook, default ~2s cadence while unresolved) never lets// the 12h timer fire mid-session.apiConfigNudge?.();- const lock = readServerLock(lockDir);// Advertise the collab WebSocket on the **same origin** the shell// loaded from — `ok ui` forwards `/collab` upgrades to the collab// server in its `on('upgrade')` handler below. Same-origin avoids the@@ -299,7 +357,7 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe// `req.headers.host` is guaranteed present and loopback-shaped; the// `?? <localhost>` fallback is defense-in-depth only.const sameOriginHost = req.headers.host ?? `localhost:${resolvedPort}`;- const collabUrl = lock && lock.port > 0 ? `ws://${sameOriginHost}/collab` : null;+ const collabUrl = resolveUpstream() !== null ? `ws://${sameOriginHost}/collab` : null;const body = JSON.stringify({ collabUrl, previewUrl: null, port: resolvedPort });res.setHeader('Content-Type', 'application/json');res.setHeader('Cache-Control', 'no-store');@@ -326,8 +384,8 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServe// "Start `ok start`" title instead of a generic HTTP-503 fallback.if (url?.startsWith('/api/')) {apiConfigNudge?.();- const lock = readServerLock(lockDir);- if (!lock || lock.port <= 0) {+ const upstream = resolveUpstream();+ if (upstream === null) {emitProblem(res,503,@@ -338,10 +396,8 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServereturn;}proxyRequest(req, res, {- // Dial the data server on the same numeric IPv4 loopback it binds — see- // DEFAULT_SERVER_HOST's JSDoc for why not `localhost`.- upstreamHost: DEFAULT_SERVER_HOST,- upstreamPort: lock.port,+ upstreamHost: upstream.host,+ upstreamPort: upstream.port,});return;}@@ -422,8 +478,8 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServeclientSocket.destroy();return;}- const lock = readServerLock(lockDir);- if (!lock || lock.port <= 0) {+ const upstream = resolveUpstream();+ if (upstream === null) {console.warn(JSON.stringify({event: 'ok-ui-upgrade-no-collab-lock',@@ -434,16 +490,7 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServeclientSocket.destroy();return;}- // Dial the data server on the same numeric IPv4 loopback it binds — see- // DEFAULT_SERVER_HOST's JSDoc for why not `localhost`.- proxyUpgrade(- req,- clientSocket,- head,- DEFAULT_SERVER_HOST,- lock.port,- upgradeSocketsForShutdown,- );+ proxyUpgrade(req, clientSocket, head, upstream.host, upstream.port, upgradeSocketsForShutdown);};const drainUpgradeSockets = (): void => {for (const sock of upgradeSocketsForShutdown) {@@ -788,9 +835,174 @@ export async function resolveUiLockCollision(return { mode: 'proxy', handle, upstreamPort };}+export interface RunUiCommandOptions {+ port?: string;+ host?: string;+ /** Explicit upstream (`ok start --only ui --server-url`) — see `StartUiServerOptions.upstreamUrl`. */+ upstreamUrl?: string;+}++/**+ * Body of the `ui` command — exported so `ok start --only ui` (the split-mode+ * replacement) can run the same server without going through Commander or the+ * deprecation notice.+ */+export async function runUiCommand(config: Config, opts: RunUiCommandOptions): Promise<void> {+ const { dim } = await import('../ui/colors.ts');+ const { UiLockCollisionError } = await import('@inkeep/open-knowledge-server');+ const { resolveLockDir } = await import('@inkeep/open-knowledge-server');+ // Undefined `host` triggers the default two-socket loopback mode in+ // startUiServer. Callers who pass `-H` get single-socket bind as-is.+ const host = opts.host;++ // Validate `--server-url` up front for a clean argument-error exit rather+ // than a stack trace out of startUiServer.+ if (opts.upstreamUrl !== undefined) {+ try {+ parseUpstreamUrl(opts.upstreamUrl);+ } catch (err) {+ console.error(err instanceof Error ? err.message : String(err));+ process.exit(2);+ }+ }++ let resolved: ResolvedRequestedPort;+ try {+ resolved = resolveRequestedPort(opts.port, process.env.PORT);+ } catch (err) {+ // Exit 2 (usage error) to match the `--server-url` validation above and+ // `ok start`'s argument-error convention — uniform now that `ok start+ // --only ui` routes its `--port` through this same path.+ console.error(err instanceof Error ? err.message : String(err));+ process.exit(2);+ }+ const requestedPort = resolved.port;++ try {+ const handle = await startUiServer({+ config,+ cwd: process.cwd(),+ port: requestedPort,+ fallbackToKernel: resolved.fallbackToKernel,+ host,+ ...(opts.upstreamUrl !== undefined ? { upstreamUrl: opts.upstreamUrl } : {}),+ });+ // Display a clickable URL in the log. Two-socket loopback mode+ // (host === undefined) and wildcard binds don't have a single+ // canonical host string, so default to `localhost` — it resolves+ // to whichever loopback family the browser prefers and both are+ // bound.+ const displayHost =+ host === undefined || host === '::' || host === '0.0.0.0' ? 'localhost' : host;+ console.log(`${dim('[ui]')} listening on http://${displayHost}:${handle.port}`);++ let shuttingDown = false;+ const shutdown = (signal: NodeJS.Signals) => {+ if (shuttingDown) return;+ shuttingDown = true;+ console.log(dim(`\n[ui] Shutting down (${signal})`));+ // Release the lock LAST, inside a finally, so a+ // mid-shutdown throw still removes the lockfile. Inverting this+ // (lock first, socket close second) re-introduces the stale-lock+ // + EADDRINUSE race the zero-ceremony design set out to eliminate.+ // Matches the shutdown pattern in `packages/server/src/server-factory.ts`.+ handle.detachSafetyNet();+ const finish = () => {+ try {+ handle.release();+ } finally {+ process.exit(process.exitCode ?? 0);+ }+ };+ // Drain upgrade-detached WebSocket sockets first — closeHttpServers+ // awaits `httpServer.close()` which does NOT track upgrade-detached+ // sockets, so a long-lived `/collab` WS would otherwise stall the+ // shutdown right up to the 2s hard-deadline.+ handle.drainUpgradeSockets();+ // Close every bound server (two in the default two-socket mode)+ // before releasing the lock. If any .close() throws synchronously+ // we still fall through to finish() via the catch.+ closeHttpServers(handle.httpServers).then(finish, finish);+ // Hard-deadline fallback — if close() hangs on an in-flight request,+ // we still release the lock and exit rather than stranding a stale+ // lockfile forever.+ setTimeout(finish, 2000).unref();+ };+ process.once('SIGINT', () => shutdown('SIGINT'));+ process.once('SIGTERM', () => shutdown('SIGTERM'));+ return;+ } catch (err) {+ if (!(err instanceof UiLockCollisionError)) throw err;++ // Lock anchor is the project root (cwd), not contentDir — see+ // server-factory.ts. The collision-recovery path must read the+ // lock from the same place the running UI server wrote it.+ const lockDir = resolveLockDir(process.cwd());+ // The proxy + collision code paths expect a concrete host string.+ // When the caller didn't pass `-H`, fall back to `localhost` — the+ // proxy only matters when a SECOND `ok ui` races against a live+ // lock, and that proxy's single-socket+ // loopback is acceptable (unlike the primary server, which does+ // two-socket for collision-fail-loud).+ const proxyHost = host ?? 'localhost';+ let result: UiCollisionResult;+ try {+ result = await resolveUiLockCollision({+ requestedPort,+ host: proxyHost,+ lockDir,+ });+ } catch (collisionErr) {+ console.error(collisionErr instanceof Error ? collisionErr.message : String(collisionErr));+ process.exit(1);+ }++ if (result.mode === 'already-running') {+ console.log(`UI already running at http://${proxyHost}:${result.port}`);+ // Non-interactive callers (no TTY, or PORT env set) get a keepalive+ // instead of exit(0): Claude Code Desktop's preview pane spawns+ // `ok ui` as a subprocess with PORT set, treats subprocess exit+ // as "preview crashed", and tears down the pane. The keepalive+ // makes the subprocess stay attached to the already-running UI+ // until the pane sends SIGTERM. Interactive TTY users still get+ // a clean exit so they're not stuck staring at a hung command.+ if (isNonInteractiveContext(process)) {+ const idleResolve = new Promise<void>((resolve) => {+ const shutdown = (signal: NodeJS.Signals): void => {+ console.log(dim(`\n[ui-keepalive] Shutting down (${signal})`));+ resolve();+ };+ process.once('SIGINT', () => shutdown('SIGINT'));+ process.once('SIGTERM', () => shutdown('SIGTERM'));+ });+ await idleResolve;+ return;+ }+ process.exit(0);+ }++ console.log(+ `UI running at http://${proxyHost}:${result.upstreamPort}; acting as HTTP proxy on port ${result.handle.port}`,+ );++ let shuttingDown = false;+ const shutdown = (signal: NodeJS.Signals) => {+ if (shuttingDown) return;+ shuttingDown = true;+ console.log(dim(`\n[ui-proxy] Shutting down (${signal})`));+ result.handle.close().finally(() => process.exit(process.exitCode ?? 0));+ setTimeout(() => process.exit(process.exitCode ?? 0), 2000).unref();+ };+ process.once('SIGINT', () => shutdown('SIGINT'));+ process.once('SIGTERM', () => shutdown('SIGTERM'));+ }+}+export function uiCommand(getConfig: () => Config): Command {return new Command('ui')- .description('Serve the OpenKnowledge React editor UI')+ .description(+ 'Deprecated: serve the React editor UI as a sibling process (plain `ok start` now serves the UI itself)',+ ).option('-p, --port <port>',`UI port (default: $PORT env or ${DEFAULT_UI_PORT}, kernel-allocated fallback if busy)`,@@ -800,143 +1012,17 @@ export function uiCommand(getConfig: () => Config): Command {'UI host. Default: two-socket loopback bind (`[::1]` + `127.0.0.1`) so cross-family collisions fail loud. Pass an explicit host (e.g. `127.0.0.1`, `0.0.0.0`) to bind a single socket on that host.',).action(async (opts: { port?: string; host?: string }) => {- const { dim } = await import('../ui/colors.ts');- const { UiLockCollisionError } = await import('@inkeep/open-knowledge-server');- const { resolveLockDir } = await import('@inkeep/open-knowledge-server');- const config = getConfig();- // Undefined `host` triggers the default two-socket loopback mode in- // startUiServer. Callers who pass `-H` get single-socket bind as-is.- const host = opts.host;-- let resolved: ResolvedRequestedPort;- try {- resolved = resolveRequestedPort(opts.port, process.env.PORT);- } catch (err) {- console.error(err instanceof Error ? err.message : String(err));- process.exitCode = 1;- return;- }- const requestedPort = resolved.port;-- try {- const handle = await startUiServer({- config,- cwd: process.cwd(),- port: requestedPort,- fallbackToKernel: resolved.fallbackToKernel,- host,- });- // Display a clickable URL in the log. Two-socket loopback mode- // (host === undefined) and wildcard binds don't have a single- // canonical host string, so default to `localhost` — it resolves- // to whichever loopback family the browser prefers and both are- // bound.- const displayHost =- host === undefined || host === '::' || host === '0.0.0.0' ? 'localhost' : host;- console.log(`${dim('[ui]')} listening on http://${displayHost}:${handle.port}`);-- let shuttingDown = false;- const shutdown = (signal: NodeJS.Signals) => {- if (shuttingDown) return;- shuttingDown = true;- console.log(dim(`\n[ui] Shutting down (${signal})`));- // Release the lock LAST, inside a finally, so a- // mid-shutdown throw still removes the lockfile. Inverting this- // (lock first, socket close second) re-introduces the stale-lock- // + EADDRINUSE race the zero-ceremony design set out to eliminate.- // Matches the shutdown pattern in `packages/server/src/server-factory.ts`.- handle.detachSafetyNet();- const finish = () => {- try {- handle.release();- } finally {- process.exit(process.exitCode ?? 0);- }- };- // Drain upgrade-detached WebSocket sockets first — closeHttpServers- // awaits `httpServer.close()` which does NOT track upgrade-detached- // sockets, so a long-lived `/collab` WS would otherwise stall the- // shutdown right up to the 2s hard-deadline.- handle.drainUpgradeSockets();- // Close every bound server (two in the default two-socket mode)- // before releasing the lock. If any .close() throws synchronously- // we still fall through to finish() via the catch.- closeHttpServers(handle.httpServers).then(finish, finish);- // Hard-deadline fallback — if close() hangs on an in-flight request,- // we still release the lock and exit rather than stranding a stale- // lockfile forever.- setTimeout(finish, 2000).unref();- };- process.once('SIGINT', () => shutdown('SIGINT'));- process.once('SIGTERM', () => shutdown('SIGTERM'));- return;- } catch (err) {- if (!(err instanceof UiLockCollisionError)) throw err;-- // Lock anchor is the project root (cwd), not contentDir — see- // server-factory.ts. The collision-recovery path must read the- // lock from the same place the running UI server wrote it.- const lockDir = resolveLockDir(process.cwd());- // The proxy + collision code paths expect a concrete host string.- // When the caller didn't pass `-H`, fall back to `localhost` — the- // proxy only matters when a SECOND `ok ui` races against a live- // lock, and that proxy's single-socket- // loopback is acceptable (unlike the primary server, which does- // two-socket for collision-fail-loud).- const proxyHost = host ?? 'localhost';- let result: UiCollisionResult;- try {- result = await resolveUiLockCollision({- requestedPort,- host: proxyHost,- lockDir,- });- } catch (collisionErr) {- console.error(- collisionErr instanceof Error ? collisionErr.message : String(collisionErr),- );- process.exit(1);- }-- if (result.mode === 'already-running') {- console.log(`UI already running at http://${proxyHost}:${result.port}`);- // Non-interactive callers (no TTY, or PORT env set) get a keepalive- // instead of exit(0): Claude Code Desktop's preview pane spawns- // `ok ui` as a subprocess with PORT set, treats subprocess exit- // as "preview crashed", and tears down the pane. The keepalive- // makes the subprocess stay attached to the already-running UI- // until the pane sends SIGTERM. Interactive TTY users still get- // a clean exit so they're not stuck staring at a hung command.- if (isNonInteractiveContext(process)) {- const idleResolve = new Promise<void>((resolve) => {- const shutdown = (signal: NodeJS.Signals): void => {- console.log(dim(`\n[ui-keepalive] Shutting down (${signal})`));- resolve();- };- process.once('SIGINT', () => shutdown('SIGINT'));- process.once('SIGTERM', () => shutdown('SIGTERM'));- });- await idleResolve;- return;- }- process.exit(0);- }-- console.log(- `UI running at http://${proxyHost}:${result.upstreamPort}; acting as HTTP proxy on port ${result.handle.port}`,- );-- let shuttingDown = false;- const shutdown = (signal: NodeJS.Signals) => {- if (shuttingDown) return;- shuttingDown = true;- console.log(dim(`\n[ui-proxy] Shutting down (${signal})`));- result.handle.close().finally(() => process.exit(process.exitCode ?? 0));- setTimeout(() => process.exit(process.exitCode ?? 0), 2000).unref();- };- process.once('SIGINT', () => shutdown('SIGINT'));- process.once('SIGTERM', () => shutdown('SIGTERM'));- }+ // Deprecation notice on stderr — stdout stays parseable for callers+ // that scrape the "listening on" line, and Desktop preview panes that+ // spawn `ok ui` keep working untouched (removal is a later release,+ // after the Desktop attach re-point ships).+ const { warning } = await import('../ui/colors.ts');+ console.error(+ warning(+ '[ui] Deprecated: use `ok start` instead — it now serves the editor UI on one port. `ok ui` remains for older desktop builds and will be removed in a future release.',+ ),+ );+ await runUiCommand(getConfig(), opts);});}diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex 6fa698f55..7a8667969 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -307,7 +307,8 @@ export interface BootServerOptions* behind the default-off discipline.** Sirv is configured with `single: true` (SPA fallback to `index.html`),- * `gzip: true`, and `immutable: true`. Unlike `ok ui`'s static handler,+ * `gzip: true`, `dev: true`, and `etag: true` (see the call site for why+ * live-disk lookup over a boot-time map). Unlike `ok ui`'s static handler,* `extensions: []` is NOT set here: that flag suppresses sirv's* directory-index resolution that `single: true` rides on for `/` and* bare deep-links. `ok ui` keeps it because its handler shares URL@@ -846,9 +847,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {}}- // React-shell serving — Electron utility opt-in.+ // React-shell serving — the default for plain `ok start`, and the Electron+ // utility path.// - `single: true` — SPA fallback to `index.html` for unknown routes- // - `gzip: true` + `immutable: true` — standard hashed-asset perf flags+ // - `gzip: true` — standard hashed-asset perf flag// Mounted in `mountMcpAndApi` AFTER `/mcp`, `/api/*`, the WS upgrade, and// `contentAssetMiddleware` — so existing surfaces keep priority and the// React shell is purely a fallback for non-data routes.@@ -863,11 +865,27 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// behavior to work for unknown routes, which `extensions: []`// suppresses (it disables sirv's directory-index resolution path// that `single: true` rides on for `/` and bare deep-links).+ // `dev: true` resolves each request against live disk instead of a+ // boot-time file map — same rationale as `ok ui`'s shell handler: an+ // in-place rebuild or `npm i -g` upgrade that rewrites the dist while this+ // server is running must degrade to a 404/refresh, not stream from a+ // boot-time map entry whose file is gone (observed: unhandled ENOENT from+ // the stale map crashed the whole server). `etag: true` restores 304+ // revalidation that dev mode otherwise drops; `immutable` is inert under+ // `dev` (sirv only emits Cache-Control with `maxAge`).+ //+ // Dotfiles: sirv's dev lookup (`viaLocal`) has NO dotfile filter — that+ // guard runs only in the boot-time cache path — so a `dotfiles: false`+ // option here would be inert. This is safe ONLY because the shell dist is+ // build output with no dotfiles; do not point this middleware at a tree+ // that could contain them without adding an explicit dotfile reject in+ // front. (`ok ui`'s shell handler carries the same constraint.)const reactShellMiddleware = opts.reactShellDistDir? sirv(opts.reactShellDistDir, {single: true,gzip: true,- immutable: true,+ etag: true,+ dev: true,}): undefined;diff --git a/packages/server/src/desktop-attach-contract.test.ts b/packages/server/src/desktop-attach-contract.test.tsindex 0d9c4a17d..53398ba89 100644--- a/packages/server/src/desktop-attach-contract.test.ts+++ b/packages/server/src/desktop-attach-contract.test.ts@@ -4,6 +4,7 @@ import { hostname, tmpdir } from 'node:os';import { resolve } from 'node:path';import { describe, expect, test, vi } from 'vitest';import { bootCompositionRig, parseProblem } from './composition-rig.test-helper.ts';+import { readServerLock } from './server-lock.ts';import { acquireUiLock, readUiLock, releaseUiLock, updateUiLockPort } from './ui-lock.ts';/**@@ -167,3 +168,70 @@ describe('ui.lock — the Desktop attach advertisement', () => {}}, 30_000);});++/**+ * The canonical attach contract that replaces the ui.lock flow above: a+ * server that serves the React shell advertises ONE record — `server.lock`'s+ * `url` plus `capabilities` containing `"ui"`. Claude Desktop's pre-declared+ * entrypoint (and the MCP preview tools via `resolveUiInfo`) dial that URL+ * directly; every surface (`/`, `/api/*`, `/mcp`, `/collab`) lives at the one+ * origin. The ui.lock behaviors above stay pinned for the version-skew+ * window; readers must prefer this record whenever the `ui` capability is+ * present.+ */+describe('server.lock v2 — the canonical Claude Desktop attach contract', () => {+ test('a shell-serving server advertises url + the ui capability, and that url serves the shell', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-v2-'));+ try {+ const projectDir = mkdtempSync(resolve(tmp, 'proj-'));+ const shellDistDir = mkdtempSync(resolve(tmp, 'dist-'));+ writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');++ const booted = await bootCompositionRig(projectDir, { reactShellDistDir: shellDistDir });+ try {+ await booted.ready;++ // The advertisement: one URL, the ui capability, a bound port.+ const lock = readServerLock(resolve(projectDir, '.ok', 'local'));+ expect(lock).not.toBeNull();+ expect(lock?.port).toBe(booted.port);+ expect(lock?.url).toBe(`http://127.0.0.1:${booted.port}`);+ expect(lock?.capabilities).toContain('ui');+ expect(lock?.capabilities).toContain('http');+ expect(lock?.capabilities).toContain('ws');++ // Attach exactly as a pre-registered Desktop pane does: dial the+ // advertised URL cold and expect the SPA shell.+ const shellRes = await fetch(`${lock?.url}/`);+ expect(shellRes.status).toBe(200);+ expect(await shellRes.text()).toContain('shell');++ // Route precedence at the same origin: /api stays a data surface+ // (problem+json), never the SPA fallback.+ const apiRes = await fetch(`${lock?.url}/api/definitely-not-a-route`);+ expect(apiRes.headers.get('content-type')).toContain('json');+ } finally {+ await booted.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);++ test('a server not serving the shell advertises no ui capability', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-v2-noui-'));+ try {+ const booted = await bootCompositionRig(tmp);+ try {+ await booted.ready;+ const lock = readServerLock(resolve(tmp, '.ok', 'local'));+ expect(lock).not.toBeNull();+ expect(lock?.capabilities).toEqual(['http', 'ws']);+ } finally {+ await booted.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.tsindex dc360fc90..e710975a0 100644--- a/packages/server/src/mcp/tools/get-preview-url.test.ts+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts@@ -308,6 +308,36 @@ describe('preview_url tool — no UI running', () => {expect(result.content[0]?.text).toContain('`ok ui`');expect(result.content[0]?.text).not.toContain('`ok start`');});++ test('--only server (capabilities omit ui): permanent hint, no "Retry" (UI never binds on its own)', async () => {+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));+ // A live server advertising http+ws but NOT ui — the `--only server` shape.+ bindTestServerLock(cwd, 4321, ['http', 'ws']);+ const handler = captureRegistration(cwd);+ const result = await handler({ document: 'specs/foo/SPEC' });+ expect(result.structuredContent?.running).toBe(false);+ expect(result.content[0]?.text).toContain('no preview UI is mounted');+ expect(result.content[0]?.text).toContain('--only server');+ // Steer to the non-deprecated Wave 3 split-mode command, not `ok ui`.+ expect(result.content[0]?.text).toContain('--only ui --server-url');+ expect(result.content[0]?.text).not.toContain('`ok ui`');+ // The whole point: "retry" would loop forever against a UI-less server.+ expect(result.content[0]?.text).not.toContain('Retry');+ });++ test('ui-capable server.lock resolves directly (single-listener): running, own origin, no ui.lock needed', async () => {+ const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));+ // The default flip: a server advertising `ui` IS the preview surface at its+ // own origin — resolveUiInfo returns it without any separate ui.lock. This+ // is why the permanent "no UI mounted" hint keys on the ABSENCE of the ui+ // capability, not merely on a missing ui.lock.+ bindTestServerLock(cwd, 4321, ['http', 'ws', 'ui']);+ const handler = captureRegistration(cwd);+ const result = await handler({ document: 'specs/foo/SPEC' });+ expect(result.structuredContent?.running).toBe(true);+ expect(result.structuredContent?.url).toBe('http://localhost:4321/#/specs/foo/SPEC');+ expect(result.content[0]?.text).not.toContain('no preview UI is mounted');+ });});describe('preview_url tool — backend demand-ensure', () => {diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.tsindex 0a654d5ad..c69bfd9fb 100644--- a/packages/server/src/mcp/tools/get-preview-url.ts+++ b/packages/server/src/mcp/tools/get-preview-url.ts@@ -203,14 +203,29 @@ const OutputSchema = outputSchemaWithText({});/**- * Recovery hints for the two distinguishable no-UI states. The server-running- * variant advises `ok ui` (the server exists; only the UI is missing — bare- * `ok start` would exit with an already-running collision there). The- * no-server variant advises `ok start`, which brings up server + UI sibling- * together; `ok ui` alone in that state produces a backend-less UI shell.+ * Recovery hints for the three distinguishable no-UI states.+ *+ * `NO_UI_SERVER_RUNNING_MESSAGE` is the TRANSIENT case: a live pre-v2 / legacy+ * sibling-topology server whose `ok ui` sibling hasn't bound its `ui.lock`+ * yet. "Retry" is the right first move (it's binding), and `ok ui` is the tool+ * that topology uses — advising `ok start` here would be wrong, since under+ * spawn-or-reuse a second `ok start` just reports the running server's URL and+ * exits 0 without adding a UI. (Post-flip note: bare `ok start` no longer+ * collides — it reuses — but that doesn't make it a way to attach a UI.)+ *+ * `NO_SERVER_MESSAGE` advises `ok start`, which brings up the server serving+ * the UI on one port.*/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) or open the project in OK Electron.';+// Permanent-state sibling of the message above: the live server advertises NO+// `ui` capability (started `--only server`, or a degraded API-only boot), so a+// UI will never bind on its own — "retry" would loop forever. Steer to the+// Wave 3 way to attach a UI to a running server: `ok start --only ui+// --server-url` (NOT deprecated `ok ui`; NOT bare `ok start`, which would just+// reuse the headless server without adding a UI).+const NO_UI_NONE_MOUNTED_MESSAGE =+ 'The OK server is running but no preview UI is mounted (e.g. it was started with `--only server`). Add one against it: `ok start --only ui --server-url <server-url>`, 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), or open the project in OK Electron.';const AUTOSTART_DISABLED_NOTE = ' Auto-start is disabled (OK_MCP_AUTOSTART=0).';@@ -244,6 +259,28 @@ function noSingleFileSessionMessage(file: string): string {return `No Open Knowledge session is serving ${file} yet. On a host with a terminal, \`ok open ${file}\` starts one; otherwise open ${file} in the OK Desktop app. Then retry.`;}+/**+ * True only when a live lock EXPLICITLY advertises capabilities that omit+ * `ui` — the `--only server` (and degraded API-only) state, where no UI will+ * ever bind on its own. A ui-capable lock whose `ui.lock` is still binding, and+ * a pre-v2 lock with no `capabilities` field at all, both return false so they+ * keep the transient "retry" hint (an extra poll is harmless; wrongly sending a+ * user to `ok ui` seconds before the UI binds is not). Mirrors `isServerLive`'s+ * fail-observable error handling.+ */+function serverExplicitlyLacksUi(lockDir: string): boolean {+ try {+ const lock = readServerLock(lockDir);+ if (lock === null || lock.port <= 0 || !isProcessAlive(lock.pid)) return false;+ return Array.isArray(lock.capabilities) && !lock.capabilities.includes('ui');+ } catch (err) {+ process.stderr.write(+ `[preview-url] readServerLock failed at ${lockDir} while checking ui capability: ${err instanceof Error ? err.message : String(err)}\n`,+ );+ return false;+ }+}+/** Live server check — same lock+liveness criteria the MCP shim uses. */function isServerLive(lockDir: string): boolean {try {@@ -451,9 +488,14 @@ export function register(server: ServerInstance, deps: GetPreviewUrlDeps): void}if (baseUrl === null) {- const hint = isServerLive(lockDir)- ? NO_UI_SERVER_RUNNING_MESSAGE- : `${NO_SERVER_MESSAGE}${autoStartDisabled ? AUTOSTART_DISABLED_NOTE : ''}`;+ // Three-way: no server at all → NO_SERVER; a live server that will+ // never mount a UI (`--only server`) → the permanent message; a live+ // ui-capable server whose UI hasn't bound yet → the transient "retry".+ const hint = !isServerLive(lockDir)+ ? `${NO_SERVER_MESSAGE}${autoStartDisabled ? AUTOSTART_DISABLED_NOTE : ''}`+ : serverExplicitlyLacksUi(lockDir)+ ? NO_UI_NONE_MOUNTED_MESSAGE+ : NO_UI_SERVER_RUNNING_MESSAGE;return textPlusStructured(`${hostedAgentSteer}${hint}`, {url: null,baseUrl: null,diff --git a/packages/server/src/mcp/tools/preview-url-test-helpers.ts b/packages/server/src/mcp/tools/preview-url-test-helpers.tsindex aa4f165b4..56772d2b8 100644--- a/packages/server/src/mcp/tools/preview-url-test-helpers.ts+++ b/packages/server/src/mcp/tools/preview-url-test-helpers.ts@@ -52,8 +52,16 @@ export function bindTestUiLock(cwd: string, port = TEST_UI_PORT): string {* duration of the test. Used by tests exercising `preview_url`'s* backend-ensure branches, which key off `server.lock` state.*/-export function bindTestServerLock(cwd: string, port = 4321): void {+export function bindTestServerLock(cwd: string, port = 4321, capabilities?: string[]): void {const lockDir = resolve(cwd, OK_DIR, LOCAL_DIR);- acquireServerLock(lockDir, { port: 0, worktreeRoot: cwd });+ // `capabilities` survives the port update — `updateServerLockPort` reads the+ // acquired metadata and rewrites only port/url. Pass `['http','ws']` to model+ // an `--only server` boot (no `ui`), or `['http','ws','ui']` for a shell-+ // serving server whose `ui.lock` hasn't bound yet.+ acquireServerLock(lockDir, {+ port: 0,+ worktreeRoot: cwd,+ ...(capabilities !== undefined ? { capabilities } : {}),+ });updateServerLockPort(lockDir, port);}