Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): retire ui.lock and bump protocolVersion to 2 (PRD-7952) (#3668)

omar-inkeepb5dd037cf459
diff --git a/.changeset/retire-ui-lock-protocol-v2.md b/.changeset/retire-ui-lock-protocol-v2.md
new file mode 100644
index 000000000..549856530
--- /dev/null
+++ b/.changeset/retire-ui-lock-protocol-v2.md
@@ -0,0 +1,11 @@
+---
+'@inkeep/open-knowledge': minor
+---
+
+Retire the `ui.lock` sibling advertisement and bump the cross-process protocol to v2.
+
+A server that serves the editor now advertises the UI through a single record — its own `server.lock` carrying a `ui` capability — instead of writing a separate `ui.lock`. Preview-URL resolution, the clone→open redirect, and `ok status` / `ps` / `stop` / `clean` all read that one record. For one release of upgrade goodwill, `ok stop` still SIGTERMs a lingering pre-migration `ok ui` holder and `ok clean` still prunes a leftover `ui.lock`.
+
+The split-mode `ok start --only ui --server-url` proxy is removed: plain `ok start` serves the editor, API, and MCP on one port. `ok start --only server` stays for headless and container use.
+
+The cross-process protocol version is now 2 — the deliberate break that marks this release incompatible with older peers. A previous-stable desktop attaching to a v2 server classifies the mismatch and surfaces the version-drift prompt (with a restart action) through the existing desktop attach-drift check, instead of silently running on against an incompatible server.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index 355662a98..7f87aac8d 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -107,10 +107,10 @@ The app runs a collaboration server for the open project. It writes runtime stat
| Path | What it is | Scope |
| --- | --- | --- |
-| `.ok/local/server.lock` (and `.ok/local/ui.lock`, a compatibility advertisement) | Advertise the running server's URL; `ui.lock` is kept for older readers and the deprecated `--only ui` split mode, and retires in a future release | In-project, gitignored |
+| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server) | 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 |
+| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
@@ -222,10 +222,10 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a
| Path | What it is | Scope |
| --- | --- | --- |
-| `.ok/local/server.lock` (and `.ok/local/ui.lock`, a compatibility advertisement) | Advertise the running server's URL; `ui.lock` is kept for older readers and the deprecated `--only ui` split mode, and retires in a future release | In-project, gitignored |
+| `.ok/local/server.lock` | Advertise the running server's URL and capabilities (the `ui` capability marks a UI-serving server) | 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 |
+| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
diff --git a/packages/app/src/lib/client-fetch.test.ts b/packages/app/src/lib/client-fetch.test.ts
index 52e3050d7..7c9345132 100644
--- a/packages/app/src/lib/client-fetch.test.ts
+++ b/packages/app/src/lib/client-fetch.test.ts
@@ -82,7 +82,7 @@ describe('installClientFetchWrapper', () => {
installClientFetchWrapper();
await window.fetch('/api/documents');
expect(calls[0]?.input).toBe('/api/documents');
- expect(header(calls[0], PROTOCOL)).toBe('1');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
expect(header(calls[0], KIND)).toBe('web');
expect(typeof header(calls[0], RUNTIME)).toBe('string');
});
@@ -92,7 +92,7 @@ describe('installClientFetchWrapper', () => {
installClientFetchWrapper({ apiOrigin: 'http://localhost:59534' });
await window.fetch('/api/document?docName=foo&cache=bust');
expect(calls[0]?.input).toBe('http://localhost:59534/api/document?docName=foo&cache=bust');
- expect(header(calls[0], PROTOCOL)).toBe('1');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
expect(header(calls[0], KIND)).toBe('web');
});
@@ -103,7 +103,7 @@ describe('installClientFetchWrapper', () => {
installClientFetchWrapper({ apiOrigin: 'http://localhost:59534' });
await window.fetch('http://localhost:59534/api/install-skill', { method: 'POST' });
expect(calls[0]?.input).toBe('http://localhost:59534/api/install-skill');
- expect(header(calls[0], PROTOCOL)).toBe('1');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
expect(header(calls[0], KIND)).toBe('web');
});
@@ -183,6 +183,6 @@ describe('installClientFetchWrapper', () => {
expect(window.fetch).toBe(firstWrapper);
await window.fetch('/api/documents');
expect(calls[0]?.input).toBe('http://localhost:59534/api/documents');
- expect(header(calls[0], PROTOCOL)).toBe('1');
+ expect(header(calls[0], PROTOCOL)).toBe('2');
});
});
diff --git a/packages/app/src/lib/client-version.test.ts b/packages/app/src/lib/client-version.test.ts
index 4f73ec420..f18853d6b 100644
--- a/packages/app/src/lib/client-version.test.ts
+++ b/packages/app/src/lib/client-version.test.ts
@@ -13,7 +13,7 @@ import {
describe('browser client-version reader', () => {
test('headers carry kind=web and the resolved runtime', () => {
expect(browserClientVersionHeaders()).toEqual({
- 'x-ok-client-protocol': '1',
+ 'x-ok-client-protocol': '2',
'x-ok-client-runtime': BROWSER_RUNTIME_VERSION,
'x-ok-client-kind': 'web',
});
@@ -22,7 +22,7 @@ describe('browser client-version reader', () => {
test('token fields carry kind=web with a numeric protocol', () => {
const fields = browserClientVersionTokenFields();
expect(fields).toEqual({
- clientProtocolVersion: 1,
+ clientProtocolVersion: 2,
clientRuntimeVersion: BROWSER_RUNTIME_VERSION,
clientKind: 'web',
});
diff --git a/packages/cli/package.json b/packages/cli/package.json
index cb4ab4045..9cc6a4087 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -71,7 +71,6 @@
"picocolors": "^1.1.1",
"pino": "^10.3.1",
"simple-git": "^3.36.0",
- "sirv": "^3.0.1",
"smol-toml": "^1.6.1",
"yaml": "^2.7.1",
"yazl": "^3.3.1",
diff --git a/packages/cli/src/commands/clean.ts b/packages/cli/src/commands/clean.ts
index d86e8ea6b..9fc6c7c8d 100644
--- a/packages/cli/src/commands/clean.ts
+++ b/packages/cli/src/commands/clean.ts
@@ -12,7 +12,7 @@
import { unlinkSync } from 'node:fs';
import { type Config, resolveLockDir } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
-import { inspectLock, type LockState } from './lock-state.ts';
+import { inspectLegacyUiLock, inspectLock, type LockState } from './lock-state.ts';
interface PruneTarget {
name: 'server' | 'ui';
@@ -52,7 +52,13 @@ interface CleanOutcome {
}
export function runClean(deps: RunCleanDeps): CleanOutcome {
- const inspect = deps.inspect ?? ((name) => inspectLock(deps.lockDir, name));
+ // The `ui` slot is the one-release legacy reap: prune a leftover pre-migration
+ // `ui.lock` (dead-pid / corrupt) for upgrade goodwill. The current binary
+ // writes no `ui.lock`, so `server` is the only slot it can create.
+ const inspect =
+ deps.inspect ??
+ ((name) =>
+ name === 'ui' ? inspectLegacyUiLock(deps.lockDir) : inspectLock(deps.lockDir, name));
const unlink = deps.unlink ?? ((path) => unlinkSync(path));
const log = deps.log ?? ((msg) => console.log(msg));
const error = deps.error ?? ((msg) => console.error(msg));
diff --git a/packages/cli/src/commands/diagnose-health-checks/server-lock.ts b/packages/cli/src/commands/diagnose-health-checks/server-lock.ts
index bf9077678..2cfb723ad 100644
--- a/packages/cli/src/commands/diagnose-health-checks/server-lock.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/server-lock.ts
@@ -14,7 +14,7 @@ import { inspectLock, type LockState } from '../lock-state.ts';
import type { CheckContext, CheckDefinition, CheckResult } from './types.ts';
interface ServerLockCheckDeps {
- inspect?: (lockDir: string, name: 'server' | 'ui') => LockState;
+ inspect?: (lockDir: string, name: 'server') => LockState;
}
export function makeServerLockCheck(deps: ServerLockCheckDeps = {}): CheckDefinition {
diff --git a/packages/cli/src/commands/diagnose.test.ts b/packages/cli/src/commands/diagnose.test.ts
index f6c3c3b36..1f4d23831 100644
--- a/packages/cli/src/commands/diagnose.test.ts
+++ b/packages/cli/src/commands/diagnose.test.ts
@@ -36,7 +36,7 @@ function makeServerLock(pid: number, worktreeRoot: string, port = 5173): LockSta
function makeBaseDeps(outDir: string) {
return {
discover: async () => [],
- inspect: (_: string, __: 'server' | 'ui'): LockState => ({ status: 'missing', lockPath: '' }),
+ inspect: (_: string, __: 'server'): LockState => ({ status: 'missing', lockPath: '' }),
resolveCommand: (_: number) => '/usr/local/bin/node /tmp/cli.ts start',
resolveUsage: (_: number) => ({ cpuPercent: 1.2, memPercent: 0.4 }),
collectLsofFn: (_: number) => 'COMMAND PID USER FD TYPE DEVICE SIZE NAME\n',
diff --git a/packages/cli/src/commands/diagnose.ts b/packages/cli/src/commands/diagnose.ts
index 732b70741..d63996568 100644
--- a/packages/cli/src/commands/diagnose.ts
+++ b/packages/cli/src/commands/diagnose.ts
@@ -281,7 +281,7 @@ function summarizeProfile(profileJson: string): string {
interface DiagnoseProcessDeps {
discover?: () => Promise<string[]>;
- inspect?: (lockDir: string, name: 'server' | 'ui') => LockState;
+ inspect?: (lockDir: string, name: 'server') => LockState;
resolveCommand?: (pid: number) => string | null;
resolveUsage?: (pid: number) => ProcessUsage | null;
collectLsofFn?: (pid: number) => string | null;
diff --git a/packages/cli/src/commands/lock-state.test.ts b/packages/cli/src/commands/lock-state.test.ts
index 1aec06653..6a76576d8 100644
--- a/packages/cli/src/commands/lock-state.test.ts
+++ b/packages/cli/src/commands/lock-state.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
-import { inspectLock } from './lock-state.ts';
+import { inspectLegacyUiLock, inspectLock } from './lock-state.ts';
function freshLockDir(): string {
const dir = mkdtempSync(join(tmpdir(), 'ok-lock-state-'));
@@ -21,8 +21,13 @@ describe('inspectLock', () => {
test('corrupt JSON', () => {
const dir = freshLockDir();
writeFileSync(join(dir, 'ui.lock'), 'not-json{{{', 'utf-8');
- const result = inspectLock(dir, 'ui');
+ // `inspectLegacyUiLock` is the one-release reap's only `ui.lock` reader.
+ // Reading it here proves LEGACY_UI_LOCK_FILENAME + the path join resolve to
+ // `ui.lock` (a wrong filename would classify it 'missing', silently
+ // skipping the reap in `ok stop` / `ok clean`).
+ const result = inspectLegacyUiLock(dir);
expect(result.status).toBe('corrupt');
+ expect(result.lockPath.endsWith('/ui.lock')).toBe(true);
});
test('valid JSON but missing pid is treated as corrupt', () => {
@@ -80,6 +85,56 @@ describe('inspectLock', () => {
}
});
+ test('matching machineId classifies alive even when hostname has drifted', () => {
+ // machineId is the identity signal (the production path — every current
+ // binary stamps it): a lock carrying THIS machine's stable id is `alive`
+ // even when the recorded hostname has since drifted.
+ const dir = freshLockDir();
+ writeFileSync(
+ join(dir, 'server.lock'),
+ JSON.stringify({
+ pid: 4242,
+ hostname: 'drifted-bonjour-name',
+ machineId: 'machine-A',
+ port: 3000,
+ startedAt: '2026-04-16T00:00:00Z',
+ worktreeRoot: '/x',
+ }),
+ 'utf-8',
+ );
+ const result = inspectLock(dir, 'server', {
+ machineId: 'machine-A',
+ host: 'current-hostname',
+ isAlive: () => true,
+ });
+ expect(result.status).toBe('alive');
+ });
+
+ test('foreign machineId with a live PID classifies foreign-host (machineId beats a matching hostname)', () => {
+ // A live lock stamped with a DIFFERENT machine's id is genuine cross-machine
+ // drift → foreign-host, even though the hostname matches — machineId takes
+ // precedence over the pre-machineId hostname fallback.
+ const dir = freshLockDir();
+ writeFileSync(
+ join(dir, 'server.lock'),
+ JSON.stringify({
+ pid: 4243,
+ hostname: 'current-hostname',
+ machineId: 'machine-B',
+ port: 3000,
+ startedAt: '2026-04-16T00:00:00Z',
+ worktreeRoot: '/x',
+ }),
+ 'utf-8',
+ );
+ const result = inspectLock(dir, 'server', {
+ machineId: 'machine-A',
+ host: 'current-hostname',
+ isAlive: () => true,
+ });
+ expect(result.status).toBe('foreign-host');
+ });
+
test('dead pid on same host', () => {
const dir = freshLockDir();
writeFileSync(
@@ -93,7 +148,7 @@ describe('inspectLock', () => {
}),
'utf-8',
);
- const result = inspectLock(dir, 'ui', { isAlive: () => false });
+ const result = inspectLegacyUiLock(dir, { isAlive: () => false });
expect(result.status).toBe('dead-pid');
if (result.status === 'dead-pid') {
expect(result.lock.pid).toBe(999999);
diff --git a/packages/cli/src/commands/lock-state.ts b/packages/cli/src/commands/lock-state.ts
index f849a6de6..00a3ea47c 100644
--- a/packages/cli/src/commands/lock-state.ts
+++ b/packages/cli/src/commands/lock-state.ts
@@ -10,6 +10,7 @@
import { existsSync, readFileSync } from 'node:fs';
import { hostname } from 'node:os';
+import { join } from 'node:path';
import {
getMachineId,
isProcessAlive,
@@ -35,12 +36,8 @@ interface InspectLockOptions {
machineId?: string;
}
-export function inspectLock(
- lockDir: string,
- lockName: LockName,
- opts: InspectLockOptions = {},
-): LockState {
- const lockPath = lockFilePath(lockDir, lockName);
+/** Classify a lock file at an explicit path — never mutates the filesystem. */
+function inspectLockPath(lockPath: string, opts: InspectLockOptions): LockState {
if (!existsSync(lockPath)) return { status: 'missing', lockPath };
let parsed: unknown;
@@ -88,3 +85,26 @@ export function inspectLock(
}
return { status: 'alive', lockPath, lock };
}
+
+export function inspectLock(
+ lockDir: string,
+ lockName: LockName,
+ opts: InspectLockOptions = {},
+): LockState {
+ return inspectLockPath(lockFilePath(lockDir, lockName), opts);
+}
+
+/** Filename of the retired UI lock — only the legacy reap below reads it. */
+const LEGACY_UI_LOCK_FILENAME = 'ui.lock';
+
+/**
+ * One-release legacy-reap carve-out: peek a leftover `ui.lock` written by a
+ * pre-migration `ok ui` holder. The current binary never writes `ui.lock`
+ * (`LockName` narrowed to `'server'`), so this is the only remaining reader —
+ * `ok stop` SIGTERMs a live legacy holder and `ok clean` prunes a stale one for
+ * one release of upgrade goodwill. Reads the filename directly (not via the
+ * `LockName` surface) to stay isolated from the live lock. Delete with the reap.
+ */
+export function inspectLegacyUiLock(lockDir: string, opts: InspectLockOptions = {}): LockState {
+ return inspectLockPath(join(lockDir, LEGACY_UI_LOCK_FILENAME), opts);
+}
diff --git a/packages/cli/src/commands/ps.test.ts b/packages/cli/src/commands/ps.test.ts
index 596d5f42d..d27d5a964 100644
--- a/packages/cli/src/commands/ps.test.ts
+++ b/packages/cli/src/commands/ps.test.ts
@@ -23,6 +23,7 @@ function makeAliveServer(overrides?: {
pid?: number;
startedAt?: string;
hostname?: string;
+ capabilities?: string[];
}): LockState {
return {
status: 'alive',
@@ -33,6 +34,7 @@ function makeAliveServer(overrides?: {
port: overrides?.port ?? 5173,
startedAt: overrides?.startedAt ?? '2026-05-05T08:00:00.000Z',
worktreeRoot: overrides?.worktreeRoot ?? '/tmp/notes',
+ ...(overrides?.capabilities !== undefined ? { capabilities: overrides.capabilities } : {}),
},
};
}
@@ -126,14 +128,14 @@ describe('runPs default (alive + foreign-host)', () => {
const lockDirs = ['/tmp/notes/.ok', '/tmp/old-project/.ok'];
const lockMap: Record<string, Record<string, LockState>> = {
- '/tmp/notes/.ok': { server: aliveServerState, ui: missingLock },
- '/tmp/old-project/.ok': { server: deadServerState, ui: missingLock },
+ '/tmp/notes/.ok': { server: aliveServerState },
+ '/tmp/old-project/.ok': { server: deadServerState },
};
const lines: string[] = [];
await runPs({
discover: async () => lockDirs,
- inspect: (lockDir, name) => lockMap[lockDir]?.[name] ?? missingLock,
+ inspect: (lockDir) => lockMap[lockDir]?.server ?? missingLock,
log: (msg) => lines.push(msg),
});
@@ -148,7 +150,7 @@ describe('runPs default (alive + foreign-host)', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/shared/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? foreignServerState : missingLock),
+ inspect: () => foreignServerState,
log: (msg) => lines.push(msg),
});
@@ -163,7 +165,7 @@ describe('runPs default (alive + foreign-host)', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/old-project/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? deadServerState : missingLock),
+ inspect: () => deadServerState,
log: (msg) => lines.push(msg),
});
@@ -195,14 +197,14 @@ describe('runPs --all', () => {
const lockDirs = ['/tmp/notes/.ok', '/tmp/old-project/.ok'];
const lockMap: Record<string, Record<string, LockState>> = {
- '/tmp/notes/.ok': { server: aliveServerState, ui: missingLock },
- '/tmp/old-project/.ok': { server: deadServerState, ui: missingLock },
+ '/tmp/notes/.ok': { server: aliveServerState },
+ '/tmp/old-project/.ok': { server: deadServerState },
};
const lines: string[] = [];
await runPs({
discover: async () => lockDirs,
- inspect: (lockDir, name) => lockMap[lockDir]?.[name] ?? missingLock,
+ inspect: (lockDir) => lockMap[lockDir]?.server ?? missingLock,
all: true,
log: (msg) => lines.push(msg),
});
@@ -220,7 +222,7 @@ describe('runPs --all', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/shared/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? foreignServerState : missingLock),
+ inspect: () => foreignServerState,
all: true,
log: (msg) => lines.push(msg),
});
@@ -274,7 +276,7 @@ describe('runPs desktop labeling', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServerState : missingLock),
+ inspect: () => aliveServerState,
resolveCommand: () => ELECTRON_UTILITY_COMMAND,
log: (msg) => lines.push(msg),
});
@@ -293,7 +295,7 @@ describe('runPs desktop labeling', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/vault/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? foreignServerState : missingLock),
+ inspect: () => foreignServerState,
resolveCommand: () => ELECTRON_UTILITY_COMMAND,
log: (msg) => lines.push(msg),
});
@@ -310,7 +312,7 @@ describe('runPs desktop labeling', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServerState : missingLock),
+ inspect: () => aliveServerState,
resolveCommand: () =>
'/usr/local/bin/node /opt/open-knowledge/packages/cli/dist/cli.mjs start',
log: (msg) => lines.push(msg),
@@ -327,7 +329,7 @@ describe('runPs desktop labeling', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServerState : missingLock),
+ inspect: () => aliveServerState,
resolveCommand: () => ELECTRON_UTILITY_COMMAND,
json: true,
log: (msg) => lines.push(msg),
@@ -348,7 +350,7 @@ describe('runPs desktop labeling', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? deadServerState : missingLock),
+ inspect: () => deadServerState,
resolveCommand: () => ELECTRON_UTILITY_COMMAND,
all: true, // dead-pid hidden by default
log: (msg) => lines.push(msg),
@@ -371,14 +373,14 @@ describe('runPs --json', () => {
const lockDirs = ['/tmp/notes/.ok', '/tmp/old-project/.ok'];
const lockMap: Record<string, Record<string, LockState>> = {
- '/tmp/notes/.ok': { server: aliveServerState, ui: missingLock },
- '/tmp/old-project/.ok': { server: deadServerState, ui: missingLock },
+ '/tmp/notes/.ok': { server: aliveServerState },
+ '/tmp/old-project/.ok': { server: deadServerState },
};
const lines: string[] = [];
await runPs({
discover: async () => lockDirs,
- inspect: (lockDir, name) => lockMap[lockDir]?.[name] ?? missingLock,
+ inspect: (lockDir) => lockMap[lockDir]?.server ?? missingLock,
json: true,
log: (msg) => lines.push(msg),
});
@@ -394,23 +396,18 @@ describe('runPs --json', () => {
});
test('json output shape has required fields', async () => {
- const aliveServerState = makeAliveServer({ worktreeRoot: '/tmp/notes', port: 5173 });
- const aliveUiState: LockState = {
- status: 'alive',
- lockPath: '/tmp/notes/.ok/ui.lock',
- lock: {
- pid: 23456,
- hostname: 'test-host',
- port: 3001,
- startedAt: '2026-05-05T08:01:00.000Z',
- worktreeRoot: '/tmp/notes',
- },
- };
+ // Single-listener: the server advertises `ui`, so the ui row is derived from
+ // server.lock and mirrors the server's own pid/port/usage.
+ const aliveServerState = makeAliveServer({
+ worktreeRoot: '/tmp/notes',
+ port: 5173,
+ capabilities: ['http', 'ws', 'ui'],
+ });
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServerState : aliveUiState),
+ inspect: () => aliveServerState,
resolveCommand: () => '/usr/local/bin/node /tmp/open-knowledge/packages/cli/src/cli.ts start',
resolveUsage: (pid) =>
pid === 12345 ? { cpuPercent: 1.2, memPercent: 3.4 } : { cpuPercent: 5.6, memPercent: 7.8 },
@@ -451,11 +448,13 @@ describe('runPs --json', () => {
expect(entry.server.status).toBe('alive');
expect(entry.server.pid).toBe(12345);
expect(typeof entry.server.startedAt).toBe('string');
+ // ui mirrors the server (single-listener) — same port/pid/usage.
expect(entry.ui).not.toBeNull();
- expect(entry.ui?.port).toBe(3001);
+ expect(entry.ui?.port).toBe(5173);
+ expect(entry.ui?.pid).toBe(12345);
expect(entry.server.usage).toEqual({ cpuPercent: 1.2, memPercent: 3.4 });
expect(entry.ui?.status).toBe('alive');
- expect(entry.ui?.usage).toEqual({ cpuPercent: 5.6, memPercent: 7.8 });
+ expect(entry.ui?.usage).toEqual({ cpuPercent: 1.2, memPercent: 3.4 });
expect(entry.hostname).toBe('test-host');
expect(typeof entry.lockPath).toBe('string');
expect(entry.binary).toBe('/tmp/open-knowledge/packages/cli/src/cli.ts');
@@ -466,13 +465,16 @@ describe('runPs --json', () => {
expect(entry.displayStatus).toBe('running');
});
- test('ui is null when ui lock is missing', async () => {
- const aliveServerState = makeAliveServer({ worktreeRoot: '/tmp/notes' });
+ test('ui is null when server.lock explicitly omits the ui capability (--only server)', async () => {
+ const aliveServerState = makeAliveServer({
+ worktreeRoot: '/tmp/notes',
+ capabilities: ['http', 'ws'],
+ });
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServerState : missingLock),
+ inspect: () => aliveServerState,
json: true,
log: (msg) => lines.push(msg),
});
@@ -482,20 +484,24 @@ describe('runPs --json', () => {
expect(parsed[0]?.ui).toBeNull();
});
- test('ui is null when ui lock is corrupt', async () => {
- const aliveServerState = makeAliveServer({ worktreeRoot: '/tmp/notes' });
+ test('ui reflects the server optimistically when server.lock omits `capabilities` (pre-v2)', async () => {
+ // A pre-capabilities server.lock is indeterminate; `lockAdvertisesUi` treats
+ // it as ui-capable (matching preview_url / status), so the ui row is present
+ // — never a divergence where ps hides a UI that preview_url would navigate to.
+ const aliveServerState = makeAliveServer({ worktreeRoot: '/tmp/notes', port: 5173 });
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServerState : corruptLock),
+ inspect: () => aliveServerState,
json: true,
log: (msg) => lines.push(msg),
});
const output = lines.join('\n');
- const parsed = JSON.parse(output) as Array<{ ui: null | object }>;
- expect(parsed[0]?.ui).toBeNull();
+ const parsed = JSON.parse(output) as Array<{ ui: { port: number } | null }>;
+ expect(parsed[0]?.ui).not.toBeNull();
+ expect(parsed[0]?.ui?.port).toBe(5173);
});
});
@@ -510,7 +516,7 @@ describe('PORTS column', () => {
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/starting/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? startingServer : missingLock),
+ inspect: () => startingServer,
log: (msg) => lines.push(msg),
});
@@ -518,194 +524,42 @@ describe('PORTS column', () => {
expect(output).toContain('(starting)');
});
- test('missing ui shows — in PORTS', async () => {
- const aliveServer = makeAliveServer({ worktreeRoot: '/tmp/notes', port: 5173 });
-
- const lines: string[] = [];
- await runPs({
- discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServer : missingLock),
- log: (msg) => lines.push(msg),
+ test('server without the ui capability shows — in PORTS', async () => {
+ const aliveServer = makeAliveServer({
+ worktreeRoot: '/tmp/notes',
+ port: 5173,
+ capabilities: ['http', 'ws'],
});
- const output = lines.join('\n');
- expect(output).toContain('5173 / —');
- });
-
- test('alive ui shows port in PORTS', async () => {
- const aliveServer = makeAliveServer({ worktreeRoot: '/tmp/notes', port: 5173 });
- const aliveUi: LockState = {
- status: 'alive',
- lockPath: '/tmp/notes/.ok/ui.lock',
- lock: {
- pid: 23456,
- hostname: 'test-host',
- port: 3001,
- startedAt: '2026-05-05T08:01:00.000Z',
- worktreeRoot: '/tmp/notes',
- },
- };
-
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServer : aliveUi),
+ inspect: () => aliveServer,
log: (msg) => lines.push(msg),
});
const output = lines.join('\n');
- expect(output).toContain('5173 / 3001');
- });
-
- test('foreign-host ui shows port in PORTS (post inspectLock-reorder)', async () => {
- // After the inspectLock liveness-first reorder, foreign-host means the PID
- // is alive locally — hostname drift, not a remote server. Hiding the port
- // (the previous behavior) made orphan UIs invisible.
- const aliveServer = makeAliveServer({ worktreeRoot: '/tmp/notes', port: 5173 });
- const foreignUi: LockState = {
- status: 'foreign-host',
- lockPath: '/tmp/notes/.ok/ui.lock',
- lock: {
- pid: 23456,
- hostname: 'old-bonjour-name',
- port: 3001,
- startedAt: '2026-05-05T08:01:00.000Z',
- worktreeRoot: '/tmp/notes',
- },
- };
-
- const lines: string[] = [];
- await runPs({
- discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServer : foreignUi),
- log: (msg) => lines.push(msg),
- });
-
- const output = lines.join('\n');
- expect(output).toContain('5173 / 3001');
- });
-});
-
-// ---------------------------------------------------------------------------
-// ui-orphan label
-// ---------------------------------------------------------------------------
-
-describe('ui-orphan label', () => {
- function makeAliveUi(overrides?: { pid?: number; port?: number }): LockState {
- return {
- status: 'alive',
- lockPath: '/tmp/notes/.ok/ui.lock',
- lock: {
- pid: overrides?.pid ?? 23456,
- hostname: 'test-host',
- port: overrides?.port ?? 3001,
- startedAt: '2026-05-05T08:01:00.000Z',
- worktreeRoot: '/tmp/notes',
- },
- };
- }
- function makeForeignUi(overrides?: { pid?: number; port?: number }): LockState {
- return {
- status: 'foreign-host',
- lockPath: '/tmp/notes/.ok/ui.lock',
- lock: {
- pid: overrides?.pid ?? 23456,
- hostname: 'old-bonjour-name',
- port: overrides?.port ?? 3001,
- startedAt: '2026-05-05T08:01:00.000Z',
- worktreeRoot: '/tmp/notes',
- },
- };
- }
-
- test('dead server + alive ui → "ui-orphan", visible by default', async () => {
- const deadServer = makeDeadServer({ worktreeRoot: '/tmp/notes' });
-
- const lines: string[] = [];
- await runPs({
- discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? deadServer : makeAliveUi()),
- log: (msg) => lines.push(msg),
- });
-
- const output = lines.join('\n');
- expect(output).toContain('/tmp/notes');
- expect(output).toContain('ui-orphan');
- expect(output).not.toMatch(/\bstale\b/);
- });
-
- test('dead server + foreign-host ui (live PID) also → "ui-orphan"', async () => {
- const deadServer = makeDeadServer({ worktreeRoot: '/tmp/notes' });
-
- const lines: string[] = [];
- await runPs({
- discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? deadServer : makeForeignUi()),
- log: (msg) => lines.push(msg),
- });
-
- expect(lines.join('\n')).toContain('ui-orphan');
- });
-
- test('dead server + dead ui → "stale" (not orphan)', async () => {
- const deadServer = makeDeadServer({ worktreeRoot: '/tmp/notes' });
- const deadUi: LockState = {
- status: 'dead-pid',
- lockPath: '/tmp/notes/.ok/ui.lock',
- lock: {
- pid: 999,
- hostname: 'test-host',
- port: 3001,
- startedAt: '2026-05-05T08:01:00.000Z',
- worktreeRoot: '/tmp/notes',
- },
- };
-
- const lines: string[] = [];
- await runPs({
- discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? deadServer : deadUi),
- all: true, // stale needs --all to show at all
- log: (msg) => lines.push(msg),
- });
-
- const output = lines.join('\n');
- expect(output).toContain('stale');
- expect(output).not.toContain('ui-orphan');
+ expect(output).toContain('5173 / —');
});
- test('alive server + alive ui → "running" (orphan only when server dead)', async () => {
- const aliveServer = makeAliveServer({ worktreeRoot: '/tmp/notes' });
-
- const lines: string[] = [];
- await runPs({
- discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? aliveServer : makeAliveUi()),
- log: (msg) => lines.push(msg),
+ test('ui-capable server shows the shared port in PORTS (single-listener)', async () => {
+ // The UI is served by the server itself, so the ui column mirrors the
+ // server port rather than a separate sibling port.
+ const aliveServer = makeAliveServer({
+ worktreeRoot: '/tmp/notes',
+ port: 5173,
+ capabilities: ['http', 'ws', 'ui'],
});
- const output = lines.join('\n');
- expect(output).toContain('running');
- expect(output).not.toContain('ui-orphan');
- });
-
- test('ui-orphan row shows live UI PID, not dead server PID', async () => {
- // Footer hint says `ok stop <pid>`; pointing at the dead server PID
- // would be a dead end. Show the UI PID so copy-paste works.
- const deadServer = makeDeadServer({ worktreeRoot: '/tmp/notes', pid: 44444 });
- const aliveUi = makeAliveUi({ pid: 23456 });
-
const lines: string[] = [];
await runPs({
discover: async () => ['/tmp/notes/.ok'],
- inspect: (_lockDir, name) => (name === 'server' ? deadServer : aliveUi),
+ inspect: () => aliveServer,
log: (msg) => lines.push(msg),
});
const output = lines.join('\n');
- expect(output).toContain('ui-orphan');
- expect(output).toContain('23456'); // UI PID
- expect(output).not.toContain('44444'); // dead server PID
+ expect(output).toContain('5173 / 5173');
});
});
diff --git a/packages/cli/src/commands/ps.ts b/packages/cli/src/commands/ps.ts
index b97e44829..2847e2986 100644
--- a/packages/cli/src/commands/ps.ts
+++ b/packages/cli/src/commands/ps.ts
@@ -7,6 +7,7 @@
* is ignored.
*/
+import { lockAdvertisesUi } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import pc from 'picocolors';
import {
@@ -96,35 +97,42 @@ export function timeAgo(isoString: string, now = Date.now()): string {
// ---------------------------------------------------------------------------
/**
- * Build a PsEntry from two inspected lock states.
+ * Build a PsEntry from the inspected server lock state.
* Returns null when the server lock is `missing` or `corrupt` (discard entry).
*/
function buildEntry(
_lockDir: string,
serverState: LockState,
- uiState: LockState,
command: string | null,
serverUsage: ProcessUsage | null,
- uiUsage: ProcessUsage | null,
): PsEntry | null {
- // Discard entries where server lock is missing or corrupt
+ // Discard entries where server lock is missing or corrupt. This intentionally
+ // hides a lone pre-migration `ui.lock` holder (a lockDir with no `server.lock`):
+ // `ok ps` shows current-topology processes only. Such an orphan stays reap-able
+ // — `process-scan`'s discovery keeps the `ui.lock` disjunct so `ok stop <pid>`,
+ // `ok stop all`, and `ok clean` still reach it (all deleted together in the
+ // reap-removal follow-up).
if (serverState.status === 'missing' || serverState.status === 'corrupt') {
return null;
}
const serverLock = serverState.lock;
- let ui: PsEntry['ui'] = null;
- if (uiState.status !== 'missing' && uiState.status !== 'corrupt') {
- const uiLock = uiState.lock;
- ui = {
- port: uiLock.port,
- status: uiState.status,
- pid: uiLock.pid,
- startedAt: uiLock.startedAt,
- usage: uiUsage,
- };
- }
+ // Single-listener topology: the UI is the server process itself. The ui row
+ // exists only when server.lock advertises the `ui` capability (via the shared
+ // `lockAdvertisesUi` predicate — a pre-v2 server missing `capabilities` counts
+ // as ui-capable, matching preview_url), and then it mirrors the server's own
+ // pid/port/usage. A `--only server` boot has none.
+ const ui: PsEntry['ui'] =
+ serverState.status === 'alive' && lockAdvertisesUi(serverLock)
+ ? {
+ port: serverLock.port,
+ status: serverState.status,
+ pid: serverLock.pid,
+ startedAt: serverLock.startedAt,
+ usage: serverUsage,
+ }
+ : null;
return {
directory: serverLock.worktreeRoot,
@@ -148,27 +156,15 @@ function buildEntry(
// Text rendering
// ---------------------------------------------------------------------------
-type DisplayStatus = 'running' | 'desktop' | 'foreign' | 'stale' | 'ui-orphan';
-
-/**
- * True when the UI lock points at a process that's actually live. After the
- * `inspectLock` reorder, `foreign-host` means specifically "different
- * hostname AND PID exists locally" — so it counts as live alongside `alive`.
- */
-function isUiLive(entry: PsEntry): boolean {
- if (entry.ui == null) return false;
- return entry.ui.status === 'alive' || entry.ui.status === 'foreign-host';
-}
+type DisplayStatus = 'running' | 'desktop' | 'foreign' | 'stale';
/**
- * Collapse server/UI lock states into the single label rendered in STATUS.
+ * Collapse the server lock state into the single label rendered in STATUS.
*
* - `desktop` overrides `running` / `foreign` when the process command
* identifies an Electron utility (see `isDesktopCommand`).
- * - `ui-orphan` triggers when the server is `dead-pid` but the UI sidekick
- * is alive (or `foreign-host`-with-live-PID). Surfaces the lifecycle hole
- * where `ok ui` survives an ungraceful server crash without shutting down.
- * - `stale` covers the fully-dead case (`dead-pid` server, no live UI).
+ * - `stale` covers the dead case (`dead-pid` server). Single-listener topology
+ * has no independent UI process, so there is no `ui-orphan` state to surface.
*/
function displayStatus(entry: PsEntry): DisplayStatus {
const serverStatus = entry.server.status;
@@ -176,17 +172,11 @@ function displayStatus(entry: PsEntry): DisplayStatus {
if (entry.isDesktop) return 'desktop';
return serverStatus === 'alive' ? 'running' : 'foreign';
}
- if (serverStatus === 'dead-pid' && isUiLive(entry)) return 'ui-orphan';
return 'stale';
}
/** Statuses shown in default (non-`--all`) text output. */
-const DEFAULT_VISIBLE: ReadonlySet<DisplayStatus> = new Set([
- 'running',
- 'desktop',
- 'foreign',
- 'ui-orphan',
-]);
+const DEFAULT_VISIBLE: ReadonlySet<DisplayStatus> = new Set(['running', 'desktop', 'foreign']);
function colorStatus(label: DisplayStatus): string {
switch (label) {
@@ -196,8 +186,6 @@ function colorStatus(label: DisplayStatus): string {
return pc.blue(label);
case 'foreign':
return pc.cyan(label);
- case 'ui-orphan':
- return pc.magenta(label);
case 'stale':
return pc.yellow(label);
}
@@ -213,15 +201,13 @@ function formatCombinedUsage(entry: PsEntry): string {
}
/**
- * Format the PORTS column: `server / ui`. UI port shows `—` only when the UI
- * lock is missing/corrupt (entry.ui null) or the UI process is dead. After the
- * `inspectLock` reorder, `foreign-host` UIs have a live local PID listening
- * on that port — show it. Hiding it (the prior behavior) made orphan UIs
- * invisible because hostname drift forces them into `foreign-host`.
+ * Format the PORTS column: `server / ui`. The UI port shows `—` when no UI is
+ * mounted (entry.ui null — a `--only server` boot, or a non-live server);
+ * otherwise it mirrors the server port (single-listener topology).
*/
function formatPorts(entry: PsEntry): string {
const serverPort = entry.server.port === 0 ? '(starting)' : String(entry.server.port);
- const uiPort = entry.ui == null || entry.ui.status === 'dead-pid' ? '—' : String(entry.ui.port);
+ const uiPort = entry.ui == null ? '—' : String(entry.ui.port);
return `${serverPort} / ${uiPort}`;
}
@@ -245,18 +231,12 @@ export function renderTable(entries: PsEntry[]): string {
'BINARY',
];
const rows = entries.map((e) => {
- const status = displayStatus(e);
- // For ui-orphan, the prominent PID column points at the live UI (which
- // `ok stop <pid>` can act on) instead of the dead server PID. The footer
- // hint reads "ok stop <pid|...>"; pointing it at a dead PID would be a
- // dead end. Server PID is still in JSON output for tooling.
- const pid = status === 'ui-orphan' && e.ui != null ? e.ui.pid : e.server.pid;
return [
e.directory,
formatPorts(e),
formatCombinedUsage(e),
- status,
- String(pid),
+ displayStatus(e),
+ String(e.server.pid),
timeAgo(e.server.startedAt),
e.binary ?? '—',
];
@@ -305,7 +285,7 @@ export function renderTable(entries: PsEntry[]): string {
interface RunPsDeps {
discover?: () => Promise<string[]>;
- inspect?: (lockDir: string, name: 'server' | 'ui') => LockState;
+ inspect?: (lockDir: string, name: 'server') => LockState;
resolveCommand?: (pid: number) => string | null;
resolveUsage?: (pid: number) => ProcessUsage | null;
json?: boolean;
@@ -325,7 +305,6 @@ export async function runPs(deps: RunPsDeps = {}): Promise<void> {
const entries: PsEntry[] = [];
for (const lockDir of lockDirs) {
const serverState = inspect(lockDir, 'server');
- const uiState = inspect(lockDir, 'ui');
const command =
serverState.status === 'missing' || serverState.status === 'corrupt'
? null
@@ -334,11 +313,7 @@ export async function runPs(deps: RunPsDeps = {}): Promise<void> {
serverState.status === 'missing' || serverState.status === 'corrupt'
? null
: resolveUsage(serverState.lock.pid);
- const uiUsage =
- uiState.status === 'missing' || uiState.status === 'corrupt'
- ? null
- : resolveUsage(uiState.lock.pid);
- const entry = buildEntry(lockDir, serverState, uiState, command, serverUsage, uiUsage);
+ const entry = buildEntry(lockDir, serverState, command, serverUsage);
if (entry != null) {
entries.push(entry);
}
diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.ts
index 6ed06199a..9bfcd678e 100644
--- a/packages/cli/src/commands/start.test.ts
+++ b/packages/cli/src/commands/start.test.ts
@@ -1452,12 +1452,12 @@ describe('resolveHost — --bind precedence', () => {
});
describe('parseOnlyModule', () => {
- test('accepts ui and server', () => {
- expect(parseOnlyModule('ui')).toBe('ui');
+ test('accepts server', () => {
expect(parseOnlyModule('server')).toBe('server');
});
- test('rejects anything else', () => {
+ test('rejects ui (retired with ui.lock) and anything else', () => {
+ expect(() => parseOnlyModule('ui')).toThrow(/--only must be/);
expect(() => parseOnlyModule('api')).toThrow(/--only must be/);
});
});
@@ -1623,7 +1623,6 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
kind: 'interactive',
capabilities: ['http', 'ws', 'ui'],
}),
- readUiLock: () => null,
});
expect(info).toEqual({
url: 'http://127.0.0.1:24550',
@@ -1633,7 +1632,10 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
});
});
- test('sibling topology (no ui capability): reports the live ui.lock advertisement', async () => {
+ test('explicit no-ui holder (--only server): reports the server address, servesUi false', async () => {
+ // With ui.lock retired, a live server that explicitly omits the `ui`
+ // capability has no separate UI advertisement to prefer — the reuse notice
+ // reports the server's own address and marks servesUi false.
const info = await resolveServerReuse({
...immediate,
readServerLock: () => ({
@@ -1642,19 +1644,8 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
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?.url).toBe('http://127.0.0.1:24550');
expect(info?.servesUi).toBe(false);
});
@@ -1662,7 +1653,6 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
const info = await resolveServerReuse({
...immediate,
readServerLock: () => ({ pid: 42, port: 24_550 }),
- readUiLock: () => null,
});
expect(info?.url).toBe('http://127.0.0.1:24550');
});
@@ -1682,7 +1672,6 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
capabilities: ['http', 'ws', 'ui'],
};
},
- readUiLock: () => null,
now: () => clock,
sleep: async (ms) => {
clock += ms;
@@ -1697,7 +1686,6 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
const info = await resolveServerReuse({
...immediate,
readServerLock: () => ({ pid: 42, port: 24_550, draining: true }),
- readUiLock: () => null,
});
expect(info).toBeNull();
});
@@ -1706,7 +1694,6 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
let clock = 0;
const info = await resolveServerReuse({
readServerLock: () => ({ pid: 42, port: 0 }),
- readUiLock: () => null,
now: () => clock,
sleep: async (ms) => {
clock += ms;
@@ -1721,7 +1708,6 @@ describe('resolveServerReuse (spawn-or-reuse)', () => {
const info = await resolveServerReuse({
...immediate,
readServerLock: () => null,
- readUiLock: () => null,
});
expect(info).toBeNull();
});
@@ -1875,18 +1861,6 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {
// multi-address bind is now real (guard dropped in start.ts; behavior
// covered by the multi-bind boot tests in boot.test.ts).
- 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',
@@ -1898,32 +1872,6 @@ describe('startCommand — flag-conflict guards (exit 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');
- });
-
test('--single-file + --remote exits 2 (no consented root to expose)', async () => {
const { code, stderr } = await captureGuard([
'--single-file',
@@ -2015,17 +1963,6 @@ describe('startCommand — flag-conflict guards (exit 2)', () => {
expect(output).toContain('must be https');
});
- test('--only ui prints the deprecation notice even on the missing --server-url refusal', async () => {
- // Same contract as the --remote notice: the operator learns the
- // successor spelling (`ok start`) from the same run that errors, exactly
- // once, on stderr.
- const { code, output } = await captureRemoteRefusal(['--only', 'ui']);
- expect(code).toBe(2);
- expect(output).toContain("'--only ui' requires '--server-url");
- expect(output.split('`--only ui` is deprecated').length - 1).toBe(1);
- expect(output).toContain('ok start');
- });
-
// The rename notices share the --remote ordering contract: they print
// BEFORE the env layer parses, so pairing the deprecated spelling with a
// malformed env var proves the notice survives a refusal path without
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index a13e4c73d..bd1011ec6 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -10,9 +10,9 @@
* The legacy two-process model (an `ok ui` sibling serving the shell and
* proxying `/api` + `/collab`, advertised via `ui.lock`) is gone: the `ok ui`
* command and the sibling auto-spawn were removed once the Desktop attach
- * re-point shipped stable. `--only server` suppresses the UI module entirely;
- * `--only ui` (with `--server-url`) runs just the shell-serving proxy — a
- * deprecated split-mode that retires together with ui.lock.
+ * re-point shipped stable, and the deprecated `--only ui` / `--server-url`
+ * split-mode proxy retired with `ui.lock`. `--only server` (headless API + MCP,
+ * no UI module) is the one `--only` value that remains.
*
* The Commander action is a thin wrapper around `bootStartServer` — that
* boot function returns a `BootedStartServer` handle (`{httpServer, destroy,
@@ -42,6 +42,7 @@ import {
type BootedServer,
type Config,
isProjectRoot,
+ lockAdvertisesUi,
type PinoLogger,
prepareSingleFileOpen,
} from '@inkeep/open-knowledge-server';
@@ -77,16 +78,17 @@ export function resolveHost(
}
/** Modules selectable via `--only` — explicit operator module selection. */
-export type OnlyModule = 'ui' | 'server';
+export type OnlyModule = 'server';
/**
* Validator for Commander's `--only` parser. Throws `InvalidArgumentError`
* for anything outside the documented enum, which Commander converts into a
- * non-zero exit + usage.
+ * non-zero exit + usage. `'ui'` (the split-mode proxy) was retired with
+ * `ui.lock`; only `'server'` (headless API + MCP) remains.
*/
export function parseOnlyModule(value: string): OnlyModule {
- if (value === 'ui' || value === 'server') return value;
- throw new InvalidArgumentError("--only must be 'ui' or 'server'");
+ if (value === 'server') return value;
+ throw new InvalidArgumentError("--only must be 'server'");
}
/**
@@ -941,14 +943,10 @@ interface StartCommandOptions {
*/
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`.
+ * From `--only server`: boot the project server with no UI module (no shell,
+ * no browser) — the headless / container profile.
*/
only?: OnlyModule;
- /** From `--server-url <url>`: where the `--only ui` split-mode UI finds its project server. */
- serverUrl?: string;
/**
* From `--idle-shutdown <dur|off>`, validated by `parseIdleShutdownFlag`: the
* duration string (`'off'` | `'90s'` | `'30m'` | …), or absent when the flag
@@ -1395,7 +1393,6 @@ export async function runStartCommand(config: Config, opts: StartCommandOptions)
try {
reuse = await resolveServerReuse({
readServerLock: () => serverModule.readServerLock(lockDir),
- readUiLock: () => serverModule.readUiLock(lockDir),
now: Date.now,
sleep: (ms) => wait(ms),
timeoutMs: 3000,
@@ -1555,7 +1552,6 @@ interface ResolveServerReuseDeps {
draining?: boolean;
capabilities?: string[];
} | null;
- readUiLock: () => { pid: number; port: number; url?: string } | null;
now: () => number;
sleep: (ms: number) => Promise<void>;
timeoutMs: number;
@@ -1574,9 +1570,8 @@ interface ResolveServerReuseDeps {
*
* 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.
+ * 2. the server's own `url`/port — API+MCP only (a `--only server` boot), but
+ * still the right address.
*
* All time + IO deps injected (precedent #13b) so tests drive every branch
* with a virtual clock and no filesystem.
@@ -1591,21 +1586,9 @@ export async function resolveServerReuse(
lock = deps.readServerLock();
}
if (lock === null || lock.draining === true || lock.port <= 0) return null;
- if (lock.capabilities?.includes('ui') === true && lock.url !== undefined) {
+ if (lockAdvertisesUi(lock) && 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,
@@ -1707,13 +1690,9 @@ export function startCommand(getConfig: () => Config): Command {
.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)",
+ "Serve one module: 'server' (API + MCP only, no shell or browser)",
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)",
@@ -1750,12 +1729,6 @@ export function startCommand(getConfig: () => Config): Command {
.action(async (opts: StartCommandOptions) => {
const config = getConfig();
- // `--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);
- }
-
// `--external-url` and its deprecated `--public-url` spelling are the
// same flag under two names — combining them would make one silently
// win. Fail loud; pass one.
@@ -1801,53 +1774,6 @@ export function startCommand(getConfig: () => Config): Command {
process.exit(2);
}
- // `--only ui`: run just the shell-serving proxy against an explicit
- // upstream — the operator split-mode replacement for the removed
- // `ok ui` (which discovered its upstream via server.lock instead).
- if (opts.only === 'ui') {
- // Deprecation notice FIRST, before any refusal below — the operator
- // should learn the successor spelling from the same run that errors
- // (mirrors the --remote notice ordering). Stderr so stdout stays
- // parseable for callers that scrape the "listening on" line. The
- // split-mode proxy retires together with ui.lock in a later release.
- {
- const { warning } = await import('../ui/colors.ts');
- console.error(
- warning(
- '[start] `--only ui` is deprecated — plain `ok start` serves the editor UI, API, and MCP on one port. The split-mode proxy will be removed in a future release.',
- ),
- );
- }
- 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
@@ -1873,7 +1799,6 @@ export function startCommand(getConfig: () => Config): Command {
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 (opts.externalUrl !== undefined) ignored.push('--external-url');
diff --git a/packages/cli/src/commands/status.test.ts b/packages/cli/src/commands/status.test.ts
index 7dbee3188..403dfa16b 100644
--- a/packages/cli/src/commands/status.test.ts
+++ b/packages/cli/src/commands/status.test.ts
@@ -50,8 +50,8 @@ function foreign(): LockState {
}
describe('buildStatusReport', () => {
- test('alive on both', () => {
- const r = buildStatusReport(alive(100, 3001), alive(200, 3000));
+ test('alive server advertising ui → both rows alive', () => {
+ const r = buildStatusReport(alive(100, 3001, 'host', ['http', 'ws', 'ui']));
expect(r.server).toEqual({
name: 'server',
state: 'alive',
@@ -65,35 +65,35 @@ describe('buildStatusReport', () => {
});
test('missing → alive: false', () => {
- const r = buildStatusReport(missing(), missing());
+ const r = buildStatusReport(missing());
expect(r.server.alive).toBe(false);
expect(r.server.state).toBe('missing');
expect(r.server.pid).toBeUndefined();
});
test('dead-pid → alive: false, reports pid', () => {
- const r = buildStatusReport(dead(999), missing());
+ const r = buildStatusReport(dead(999));
expect(r.server.alive).toBe(false);
expect(r.server.state).toBe('dead-pid');
expect(r.server.pid).toBe(999);
});
test('corrupt → alive: false, no pid surfaced', () => {
- const r = buildStatusReport(corrupt(), missing());
+ const r = buildStatusReport(corrupt());
expect(r.server.state).toBe('corrupt');
expect(r.server.pid).toBeUndefined();
});
test('foreign-host → alive: unknown', () => {
- const r = buildStatusReport(foreign(), missing());
+ const r = buildStatusReport(foreign());
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());
+ test('single-listener default: server advertises `ui` → ui served by server', () => {
+ // Single-listener writes only server.lock (capabilities incl. `ui`); a
+ // "not running" ui row would be a false negative. Derive it from capability.
+ const r = buildStatusReport(alive(100, 3001, 'host', ['http', 'ws', 'ui']));
expect(r.ui.state).toBe('alive');
expect(r.ui.alive).toBe(true);
expect(r.ui.servedByServer).toBe(true);
@@ -101,9 +101,9 @@ describe('buildStatusReport', () => {
expect(r.ui.port).toBe(3001);
});
- test('server without the `ui` capability leaves a missing ui.lock as not-running', () => {
+ test('server without the `ui` capability leaves the ui row not-running', () => {
// `--only server`: no UI anywhere, so the ui row must stay honest.
- const r = buildStatusReport(alive(100, 3001, 'host', ['http', 'ws']), missing());
+ const r = buildStatusReport(alive(100, 3001, 'host', ['http', 'ws']));
expect(r.ui.state).toBe('missing');
expect(r.ui.servedByServer).toBeUndefined();
});
@@ -111,27 +111,24 @@ describe('buildStatusReport', () => {
describe('renderStatusText', () => {
test('alive entries include pid + port + startedAt', () => {
- const out = renderStatusText(buildStatusReport(alive(100, 3001), alive(200, 3000)));
+ const out = renderStatusText(buildStatusReport(alive(100, 3001, 'host', ['http', 'ws', 'ui'])));
expect(out).toContain('pid=100 port=3001');
- expect(out).toContain('pid=200 port=3000');
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()),
- );
+ const out = renderStatusText(buildStatusReport(alive(100, 3001, 'host', ['http', 'ws', 'ui'])));
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()));
+ const out = renderStatusText(buildStatusReport(missing()));
expect(out).toContain('not running');
});
test('stale entries suggest ok clean', () => {
- const out = renderStatusText(buildStatusReport(dead(999), missing()));
+ const out = renderStatusText(buildStatusReport(dead(999)));
expect(out).toContain('stale');
expect(out).toContain('pid=999');
expect(out).toContain('ok clean');
@@ -143,7 +140,7 @@ describe('runStatus', () => {
const logs: string[] = [];
runStatus({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? alive(100, 3001) : alive(200, 3000)),
+ inspect: () => alive(100, 3001, 'host', ['http', 'ws', 'ui']),
log: (msg) => logs.push(msg),
});
expect(logs).toHaveLength(1);
@@ -155,21 +152,31 @@ describe('runStatus', () => {
runStatus({
lockDir: '/tmp/x',
json: true,
- inspect: (name) => (name === 'server' ? alive(100, 3001) : missing()),
+ inspect: () => alive(100, 3001, 'host', ['http', 'ws']),
log: (msg) => logs.push(msg),
});
expect(logs).toHaveLength(1);
const parsed = JSON.parse(logs[0] ?? '');
expect(parsed.server.state).toBe('alive');
expect(parsed.server.pid).toBe(100);
+ // server.lock EXPLICITLY omits `ui` (--only server) → the ui row stays not-running.
expect(parsed.ui.state).toBe('missing');
});
+ test('pre-v2 server.lock without `capabilities` → ui row optimistically served-by-server', () => {
+ // A missing `capabilities` field is indeterminate; the shared
+ // `lockAdvertisesUi` predicate treats it as ui-capable, so status agrees
+ // with preview_url / the redirect rather than falsely reporting "not running".
+ const report = buildStatusReport(alive(100, 3001));
+ expect(report.ui.state).toBe('alive');
+ expect(report.ui.servedByServer).toBe(true);
+ });
+
test('never sets non-zero exit code even with all dead/corrupt', () => {
const before = process.exitCode;
runStatus({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? dead(999) : corrupt()),
+ inspect: () => dead(999),
log: () => {},
});
expect(process.exitCode).toBe(before);
diff --git a/packages/cli/src/commands/status.ts b/packages/cli/src/commands/status.ts
index 14604cb5d..972697fcb 100644
--- a/packages/cli/src/commands/status.ts
+++ b/packages/cli/src/commands/status.ts
@@ -6,7 +6,7 @@
* command. Prints formatted text by default, JSON with `--json`.
*/
-import { type Config, resolveLockDir } from '@inkeep/open-knowledge-server';
+import { type Config, lockAdvertisesUi, resolveLockDir } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
import { inspectLock, type LockState } from './lock-state.ts';
@@ -31,30 +31,27 @@ interface StatusReport {
ui: StatusEntry;
}
-export function buildStatusReport(server: LockState, ui: LockState): StatusReport {
+export function buildStatusReport(server: LockState): StatusReport {
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,
- };
- }
+ // Single-listener topology: plain `ok start` serves the UI from the project
+ // server and writes NO ui.lock, so the ui row is derived entirely from
+ // server.lock's `ui` capability via the shared `lockAdvertisesUi` predicate
+ // (a missing `capabilities` field on a pre-v2 server is treated as ui-capable,
+ // matching preview_url / the redirect). A bare `--only server` boot advertises
+ // no `ui`, so its ui row is correctly empty.
+ const uiEntry: StatusEntry =
+ server.status === 'alive' && lockAdvertisesUi(server.lock)
+ ? {
+ name: 'ui',
+ state: 'alive',
+ pid: server.lock.pid,
+ port: server.lock.port,
+ startedAt: server.lock.startedAt,
+ host: server.lock.hostname,
+ alive: true,
+ servedByServer: true,
+ }
+ : { name: 'ui', state: 'missing', alive: false };
return { server: serverEntry, ui: uiEntry };
}
@@ -125,14 +122,14 @@ function renderEntry(entry: StatusEntry): string {
interface RunStatusDeps {
lockDir: string;
json?: boolean;
- inspect?: (name: 'server' | 'ui') => LockState;
+ inspect?: () => LockState;
log?: (msg: string) => void;
}
export function runStatus(deps: RunStatusDeps): StatusReport {
- const inspect = deps.inspect ?? ((name) => inspectLock(deps.lockDir, name));
+ const inspect = deps.inspect ?? (() => inspectLock(deps.lockDir, 'server'));
const log = deps.log ?? ((msg) => console.log(msg));
- const report = buildStatusReport(inspect('server'), inspect('ui'));
+ const report = buildStatusReport(inspect());
if (deps.json) {
log(JSON.stringify(report, null, 2));
} else {
diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.ts
index 9bdebf89f..a032a8ce4 100644
--- a/packages/cli/src/commands/stop.ts
+++ b/packages/cli/src/commands/stop.ts
@@ -1,6 +1,7 @@
/**
- * `open-knowledge stop` — SIGTERM live server + ui processes; leave stale
- * locks untouched (they belong to `ok clean`).
+ * `open-knowledge stop` — SIGTERM the live server (plus a lingering legacy
+ * `ok ui` holder, a one-release reap); leave stale locks untouched (they belong
+ * to `ok clean`).
*
* Single-responsibility split from lock pruning. Exits 0 when there's
* nothing live; exits 1 only when a SIGTERM fails (EPERM, etc).
@@ -11,7 +12,7 @@ import { type Config, isProcessAlive, resolveLockDir } from '@inkeep/open-knowle
import { Command } from 'commander';
import { getInvocationCwd } from '../project-anchor.ts';
import { discoverLockDirs } from '../utils/process-scan.ts';
-import { inspectLock, type LockState } from './lock-state.ts';
+import { inspectLegacyUiLock, inspectLock, type LockState } from './lock-state.ts';
import { runPs } from './ps.ts';
interface StopTargetPlan {
@@ -80,7 +81,13 @@ interface StopOutcome {
* `failed.length > 0` into `process.exitCode = 1`.
*/
export function runStop(deps: RunStopDeps): StopOutcome {
- const inspect = deps.inspect ?? ((name) => inspectLock(deps.lockDir, name));
+ // The `ui` slot is the one-release legacy reap: `inspectLegacyUiLock` peeks a
+ // leftover pre-migration `ok ui` holder so a live one still gets SIGTERM'd.
+ // The current binary writes no `ui.lock`, so `server` is the only live slot.
+ const inspect =
+ deps.inspect ??
+ ((name) =>
+ name === 'ui' ? inspectLegacyUiLock(deps.lockDir) : inspectLock(deps.lockDir, name));
const kill = deps.kill ?? ((pid, signal) => process.kill(pid, signal));
const log = deps.log ?? ((msg) => console.log(msg));
const error = deps.error ?? ((msg) => console.error(msg));
@@ -147,7 +154,7 @@ async function findLockDirByNumber(
let pidMatch: string | null = null;
for (const lockDir of lockDirs) {
const server = inspectLock(lockDir, 'server');
- const ui = inspectLock(lockDir, 'ui');
+ const ui = inspectLegacyUiLock(lockDir);
if (isStoppableState(server, isAlive) && server.lock.port === n) return lockDir;
if (isStoppableState(ui, isAlive) && ui.lock.port === n) return lockDir;
if (pidMatch === null) {
@@ -212,7 +219,7 @@ export function stopCommand(getConfig: () => Config): Command {
// Skip lockDirs with nothing stoppable to avoid noisy "no processes" messages.
// `foreign-host` with a locally-live PID counts (hostname drift).
const server = inspectLock(lockDir, 'server');
- const ui = inspectLock(lockDir, 'ui');
+ const ui = inspectLegacyUiLock(lockDir);
if (!isStoppableState(server, isProcessAlive) && !isStoppableState(ui, isProcessAlive))
continue;
executeStop(lockDir);
diff --git a/packages/cli/src/commands/sync.test.ts b/packages/cli/src/commands/sync.test.ts
index 34fed4c65..d1a9d1038 100644
--- a/packages/cli/src/commands/sync.test.ts
+++ b/packages/cli/src/commands/sync.test.ts
@@ -51,7 +51,7 @@ describe('runSync — client version headers (AC-5)', () => {
await runSync({ json: true, op: 'sync' }, {} as Config, dir);
- expect(headerOf(seen, 'x-ok-client-protocol')).toBe('1');
+ expect(headerOf(seen, 'x-ok-client-protocol')).toBe('2');
expect(headerOf(seen, 'x-ok-client-kind')).toBe('cli');
expect(headerOf(seen, 'x-ok-client-runtime')).toBe(RUNTIME_VERSION);
// The original content-type is preserved alongside the version headers.
diff --git a/packages/cli/src/commands/ui-problem.ts b/packages/cli/src/commands/ui-problem.ts
deleted file mode 100644
index 277a37be7..000000000
--- a/packages/cli/src/commands/ui-problem.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-/**
- * RFC 9457 problem+json emitter shared by `ok ui`'s in-process responses
- * (`ui.ts` collab-server-not-running 503; `ui-proxy.ts` loopback / Host /
- * Origin gate 403s). Static-asset / SPA-fallthrough 404s do NOT use this
- * emitter — they go through `notFoundStatic` in `ui.ts` (a plain 404, not the
- * API envelope). Mirrors `errorResponse(...)` in
- * `packages/server/src/http/error-response.ts` so client-side
- * `ProblemDetailsSchema.safeParse` flows match across both processes.
- *
- * **Intentional divergences from `errorResponse(...)`** — documented so
- * future readers don't try to "consolidate":
- *
- * - **No `apiErrorCounter()` increment.** The CLI process has no OTel
- * SDK initialization (CLI lacks the server's telemetry infra entirely).
- * Adding a counter call here would be a no-op at best; at worst it
- * would lazy-initialize a meter the rest of the CLI doesn't use.
- * - **No Pino `log.error()` call.** CLI uses different logging
- * conventions (console + structured warn-style for events asserted in
- * tests). The server's `getLogger()` is a Pino instance not present
- * in the CLI runtime.
- * - **Adds `Cache-Control: no-store`** that the server helper doesn't.
- * `ok ui` is a dev-mode preview server; clients should never cache its
- * 5xx/4xx fallthroughs (e.g., on collab-server restart). The main
- * server's responses are routed through Vite/asset middleware that
- * handles caching policy at a different layer.
- * - **No pre-stringify try/catch around `JSON.stringify(body)`.** The
- * server helper guards against circular references / unserializable
- * extensions in `options.extensions` (RFC 9457 §3.2 open-shape
- * extension members). `emitProblem` accepts no extension members; the
- * body is built exclusively from primitives (`type`, `title: string`,
- * `status: number`, `instance: string`, `detail?: string`) so the
- * stringify call has no surface for circularity. Adding the guard
- * would be over-engineering for a path that cannot fail given the
- * closed signature.
- *
- * Beyond those four divergences, the wire shape, header set, schema
- * validation behavior (`safeParse` + hardcoded fallback on schema-validation
- * failure), `headersSent` guard, and URN closed-enum discipline are identical
- * to `errorResponse(...)`.
- */
-import { randomUUID } from 'node:crypto';
-import type { ServerResponse } from 'node:http';
-import {
- type ProblemDetails,
- ProblemDetailsSchema,
- type ProblemType,
-} from '@inkeep/open-knowledge-core';
-import type { HttpErrorStatus } from '@inkeep/open-knowledge-server';
-
-export function emitProblem(
- res: ServerResponse,
- status: HttpErrorStatus,
- type: ProblemType,
- title: string,
- detail?: string,
-): void {
- // RFC 9457 §3.1.6 — `instance` is a URI reference. Mirrors
- // `errorResponse` in `packages/server/src/http/error-response.ts` which
- // emits `urn:uuid:<uuid>` for the same reason.
- const instance = `urn:uuid:${randomUUID()}`;
- // Defense-in-depth: mirror the four canonical wire emitters
- // (`errorResponse`, `successResponse`, `createStreamingErrorWriter`,
- // and this helper) on the same three-way guard
- // `headersSent || writableEnded || destroyed`. If the listener ever
- // runs after a partial response, after the response was ended, or
- // after a TCP RST destroyed the socket, this suppresses the double-
- // emit instead of crashing the `ok ui` process. Loud via console.error
- // since CLI lacks Pino.
- if (res.headersSent || res.writableEnded || res.destroyed) {
- // `console.error` (not `.warn`) for severity parity with the
- // server's `errorResponse()` which routes this same class through
- // `log.error` — double-write after headers are sent IS a programming
- // bug, not a routine warning. CLI lacks Pino, so console.error is
- // the local equivalent for "ops should care."
- console.error('[ok ui] emitProblem called after headers sent — suppressed', {
- type,
- status,
- instance,
- });
- return;
- }
- const body: ProblemDetails = {
- type,
- title,
- status,
- instance,
- ...(detail !== undefined ? { detail } : {}),
- };
- // Defense-in-depth: `safeParse` mirrors `errorResponse`'s pass-1 hardening.
- // The bare `http.createServer` listener has no try/catch — a throwing
- // `.parse()` (schema tightening, hardcoded title violating `min(1)`, etc.)
- // would crash the `ok ui` process. On validation failure, log to stderr
- // (CLI has no Pino) and emit a hardcoded fallback so the client still gets
- // a typed problem+json response.
- const validated = ProblemDetailsSchema.safeParse(body);
- if (!validated.success) {
- console.error('[ok ui] emitProblem produced an invalid ProblemDetails body:', {
- issues: validated.error.issues,
- originalStatus: status,
- body,
- });
- // Override status to 500 so the fallback's `type: internal-server-error`
- // and the HTTP status agree. Mirrors `errorResponse` (`error-response.ts`):
- // a malformed envelope IS a server bug; emitting `internal-server-error`
- // at the caller's original 4xx status would surface a contradiction
- // (e.g., HTTP 404 with body `{type: internal-server-error, status: 404}`).
- // Original status preserved in the warn log for ops triage.
- const fallbackStatus = 500 as const;
- res.writeHead(fallbackStatus, {
- 'Content-Type': 'application/problem+json',
- 'X-Content-Type-Options': 'nosniff',
- 'Cache-Control': 'no-store',
- });
- res.end(
- JSON.stringify({
- type: 'urn:ok:error:internal-server-error' satisfies ProblemType,
- title: 'Internal server error.',
- status: fallbackStatus,
- instance,
- }),
- );
- return;
- }
- res.writeHead(status, {
- 'Content-Type': 'application/problem+json',
- 'X-Content-Type-Options': 'nosniff',
- 'Cache-Control': 'no-store',
- });
- res.end(JSON.stringify(body));
-}
diff --git a/packages/cli/src/commands/ui-proxy.test.ts b/packages/cli/src/commands/ui-proxy.test.ts
deleted file mode 100644
index eee153ddc..000000000
--- a/packages/cli/src/commands/ui-proxy.test.ts
+++ /dev/null
@@ -1,306 +0,0 @@
-import {
- createServer as createHttpServer,
- type Server as HttpServer,
- request as httpRequest,
- type IncomingMessage,
-} from 'node:http';
-import { afterEach, describe, expect, test } from 'vitest';
-import { type ProxyServerHandle, startProxyServer } from './ui-proxy.ts';
-
-/** Send a request with arbitrary Host / Origin headers. We can't use `fetch`
- * because some runtimes silently rewrite Host. */
-async function rawRequest(opts: {
- port: number;
- path: string;
- method?: string;
- host?: string;
- origin?: string;
-}): Promise<{ status: number; body: string }> {
- return new Promise((done, fail) => {
- const req = httpRequest(
- {
- // Connect to the loopback literal startProxyServer binds — dialing
- // the bound literal removes any name-resolution ambiguity.
- host: '127.0.0.1',
- port: opts.port,
- path: opts.path,
- method: opts.method ?? 'GET',
- headers: {
- host: opts.host ?? `127.0.0.1:${opts.port}`,
- ...(opts.origin !== undefined ? { origin: opts.origin } : {}),
- },
- },
- (res: IncomingMessage) => {
- const chunks: Buffer[] = [];
- res.on('data', (c) => chunks.push(c as Buffer));
- res.on('end', () => {
- done({
- status: res.statusCode ?? 0,
- body: Buffer.concat(chunks).toString('utf-8'),
- });
- });
- },
- );
- req.on('error', fail);
- req.end();
- });
-}
-
-type UpstreamHandle = { httpServer: HttpServer; port: number; close: () => Promise<void> };
-
-async function startUpstream(
- handler: (
- req: import('node:http').IncomingMessage,
- res: import('node:http').ServerResponse,
- ) => void,
-): Promise<UpstreamHandle> {
- const server = createHttpServer(handler);
- await new Promise<void>((done, fail) => {
- const onError = (err: Error) => fail(err);
- server.once('error', onError);
- server.listen(0, '127.0.0.1', () => {
- server.off('error', onError);
- done();
- });
- });
- const addr = server.address();
- const port = typeof addr === 'object' && addr !== null ? addr.port : 0;
- return {
- httpServer: server,
- port,
- close: () => new Promise<void>((done) => server.close(() => done())),
- };
-}
-
-let proxy: ProxyServerHandle | null = null;
-let upstream: UpstreamHandle | null = null;
-
-afterEach(async () => {
- if (proxy) {
- await proxy.close();
- proxy = null;
- }
- if (upstream) {
- await upstream.close();
- upstream = null;
- }
-});
-
-describe('startProxyServer', () => {
- test('forwards GET and preserves status + body', async () => {
- upstream = await startUpstream((req, res) => {
- expect(req.method).toBe('GET');
- expect(req.url).toBe('/hello');
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('hello world');
- });
-
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const response = await fetch(`http://127.0.0.1:${proxy.port}/hello`);
- expect(response.status).toBe(200);
- expect(await response.text()).toBe('hello world');
- expect(response.headers.get('content-type')).toContain('text/plain');
- });
-
- test('forwards POST with body bytes intact', async () => {
- const payload = 'x'.repeat(64 * 1024); // 64 KiB to shake out stream handling
- upstream = await startUpstream(async (req, res) => {
- expect(req.method).toBe('POST');
- const chunks: Buffer[] = [];
- for await (const chunk of req) chunks.push(chunk as Buffer);
- const got = Buffer.concat(chunks).toString('utf-8');
- expect(got).toBe(payload);
- res.writeHead(201, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ received: got.length }));
- });
-
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const response = await fetch(`http://127.0.0.1:${proxy.port}/echo`, {
- method: 'POST',
- body: payload,
- headers: { 'Content-Type': 'text/plain' },
- });
- expect(response.status).toBe(201);
- const body = (await response.json()) as { received: number };
- expect(body.received).toBe(payload.length);
- });
-
- test('preserves upstream 404 + headers', async () => {
- upstream = await startUpstream((_req, res) => {
- res.writeHead(404, { 'X-Custom': 'not-found', 'Content-Type': 'text/plain' });
- res.end('nope');
- });
-
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const response = await fetch(`http://127.0.0.1:${proxy.port}/missing`);
- expect(response.status).toBe(404);
- expect(response.headers.get('x-custom')).toBe('not-found');
- expect(await response.text()).toBe('nope');
- });
-
- test('HEAD returns status + headers without body', async () => {
- upstream = await startUpstream((req, res) => {
- expect(req.method).toBe('HEAD');
- res.writeHead(200, { 'X-Meta': 'yes' });
- res.end();
- });
-
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const response = await fetch(`http://127.0.0.1:${proxy.port}/head`, { method: 'HEAD' });
- expect(response.status).toBe(200);
- expect(response.headers.get('x-meta')).toBe('yes');
- expect(await response.text()).toBe('');
- });
-
- test('returns 502 when upstream refuses connection', async () => {
- // Pick a port unlikely to be bound: start + immediately stop an upstream
- // so we know the port is free but nobody listens anymore.
- upstream = await startUpstream((_req, res) => res.end('ignored'));
- const deadPort = upstream.port;
- await upstream.close();
- upstream = null;
-
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: deadPort,
- });
-
- const response = await fetch(`http://127.0.0.1:${proxy.port}/whatever`);
- expect(response.status).toBe(502);
- expect(response.headers.get('content-type')).toBe('application/problem+json');
- const body = (await response.json()) as { type: string; title: string; status: number };
- expect(body.type).toBe('urn:ok:error:collab-server-not-running');
- expect(body.status).toBe(502);
- });
-
- test('close() shuts down the listener', async () => {
- upstream = await startUpstream((_req, res) => res.end('ok'));
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
- const port = proxy.port;
- await proxy.close();
- proxy = null;
-
- await expect(fetch(`http://127.0.0.1:${port}/`)).rejects.toThrow();
- });
-
- test('rejects requests with non-loopback Host header (DNS-rebind defense)', async () => {
- let upstreamHits = 0;
- upstream = await startUpstream((_req, res) => {
- upstreamHits++;
- res.end('upstream reached');
- });
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const res = await rawRequest({
- port: proxy.port,
- path: '/api/agent-write-md',
- method: 'POST',
- host: 'attacker.com:1234',
- });
- expect(res.status).toBe(403);
- const body = JSON.parse(res.body) as { type: string; title: string; status: number };
- expect(body.type).toBe('urn:ok:error:host-not-allowed');
- expect(body.status).toBe(403);
- expect(upstreamHits).toBe(0);
- });
-
- test('rejects requests with non-loopback Origin', async () => {
- let upstreamHits = 0;
- upstream = await startUpstream((_req, res) => {
- upstreamHits++;
- res.end('upstream reached');
- });
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const res = await rawRequest({
- port: proxy.port,
- path: '/api/agent-write-md',
- origin: 'http://attacker.com',
- });
- expect(res.status).toBe(403);
- const body = JSON.parse(res.body) as { type: string; title: string; status: number };
- expect(body.type).toBe('urn:ok:error:invalid-origin');
- expect(body.status).toBe(403);
- expect(upstreamHits).toBe(0);
- });
-
- test('accepts loopback Origin and forwards', async () => {
- upstream = await startUpstream((_req, res) => {
- res.writeHead(200);
- res.end('ok');
- });
- proxy = await startProxyServer({
- listenPort: 0,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
-
- const res = await rawRequest({
- port: proxy.port,
- path: '/api/anything',
- origin: 'http://127.0.0.1:5173',
- });
- expect(res.status).toBe(200);
- });
-
- test('listens on the requested port when nonzero', async () => {
- upstream = await startUpstream((_req, res) => res.end('ok'));
-
- // Grab a kernel-allocated port via a throwaway server, then close it so
- // the proxy can bind that same port on purpose.
- const pickerSrv = createHttpServer();
- await new Promise<void>((done) => pickerSrv.listen(0, '127.0.0.1', () => done()));
- const requested = (pickerSrv.address() as { port: number }).port;
- await new Promise<void>((done) => pickerSrv.close(() => done()));
-
- proxy = await startProxyServer({
- listenPort: requested,
- host: '127.0.0.1',
- upstreamHost: '127.0.0.1',
- upstreamPort: upstream.port,
- });
- expect(proxy.port).toBe(requested);
- });
-});
diff --git a/packages/cli/src/commands/ui-proxy.ts b/packages/cli/src/commands/ui-proxy.ts
deleted file mode 100644
index ca250f7bb..000000000
--- a/packages/cli/src/commands/ui-proxy.ts
+++ /dev/null
@@ -1,511 +0,0 @@
-/**
- * Minimal reverse HTTP proxy for `ok ui` lock-collision fallback and for
- * forwarding `ok ui`'s `/api/*` traffic to the collab server.
- *
- * Two modes:
- * 1. **Standalone** — `startProxyServer(opts)` spins up an HTTP listener that
- * forwards every request to an upstream host:port. Used for Claude
- * Code's `autoPort:true` lock-collision scenario (the listener holds the
- * autoPort-resolved port; requests get forwarded to the lock-holder's
- * port).
- * 2. **Embedded** — `proxyRequest(req, res, opts)` is called directly from
- * an existing `http.Server` request handler to forward a single request
- * to an upstream. Used by `ok ui` so that React's same-origin REST
- * calls (`/api/pages`, `/api/backlinks`, etc.) transparently reach the
- * collab server on a different port without per-caller URL rewriting.
- *
- * Uses only `node:http` — no new 3P dependency.
- */
-import type {
- Server as HttpServer,
- IncomingHttpHeaders,
- IncomingMessage,
- ServerResponse,
-} from 'node:http';
-import { createServer as createHttpServer, request as httpRequest } from 'node:http';
-import { connect as netConnect } from 'node:net';
-import type { Duplex } from 'node:stream';
-import {
- isAllowedApiOrigin,
- isAllowedWorkspaceHostHeader,
- isLoopbackAddress,
-} from '@inkeep/open-knowledge-server';
-import { emitProblem } from './ui-problem.ts';
-
-export interface ProxyServerHandle {
- httpServer: HttpServer;
- port: number;
- close: () => Promise<void>;
-}
-
-interface StartProxyOptions {
- listenPort: number;
- host: string;
- upstreamHost: string;
- upstreamPort: number;
- /** Per-request upstream timeout in milliseconds. Default 10_000. Upstream
- * hang past this deadline produces a 504 Gateway Timeout. Set to 0 to
- * disable (not recommended — Node's default is no timeout). */
- upstreamTimeoutMs?: number;
-}
-
-/** Default: 10s. Long enough for legitimate slow loads, short enough that a
- * hung upstream doesn't keep browser connections open indefinitely. */
-const DEFAULT_UPSTREAM_TIMEOUT_MS = 10_000;
-
-/**
- * Reject requests to the proxy that did not arrive over a loopback peer with a
- * loopback Host header and (when present) a loopback Origin. This proxy
- * rewrites the upstream Host header to `localhost:<port>` and the upstream
- * sees the proxy's own loopback peer address — without this gate, a request
- * that arrived over a non-loopback bind, a DNS-rebound hostname, or a
- * cross-origin browser context would launder all three signals before the
- * collab server's own gate (api-extension.ts) could see them.
- *
- * Returns `true` when the request was rejected and the response already
- * written; the caller must return without further work. Returns `false` when
- * the request is safe to forward.
- */
-export function rejectIfNotLoopbackApi(req: IncomingMessage, res: ServerResponse): boolean {
- const peerAddress = req.socket?.remoteAddress;
- if (peerAddress !== undefined && !isLoopbackAddress(peerAddress)) {
- emitProblem(
- res,
- 403,
- 'urn:ok:error:loopback-required',
- 'Request must originate from a loopback address.',
- );
- return true;
- }
- if (!isAllowedWorkspaceHostHeader(req.headers.host)) {
- emitProblem(
- res,
- 403,
- 'urn:ok:error:host-not-allowed',
- 'Host header is not in the loopback allowlist.',
- );
- return true;
- }
- const origin = req.headers.origin;
- if (origin !== undefined && !isAllowedApiOrigin(origin)) {
- emitProblem(
- res,
- 403,
- 'urn:ok:error:invalid-origin',
- 'Origin header is not in the loopback allowlist.',
- );
- return true;
- }
- return false;
-}
-
-/** Per-request client-side deadline — prevents a malicious/local slow-loris peer
- * from pinning the proxy socket indefinitely. 30s leaves ample margin over the
- * upstream timeout above so we never time out a healthy request. */
-const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
-
-/**
- * Upgrade-flow analogue of `rejectIfNotLoopbackApi`. The HTTP/1.1 upgrade
- * exchange has no `ServerResponse` to write a structured error into, so on
- * rejection we destroy the raw socket — the client surfaces this as a failed
- * WebSocket handshake. Same three-gate defense (peer + Host + Origin).
- *
- * Returns `true` when the upgrade was rejected; the caller must return.
- */
-export function rejectUpgradeIfNotLoopback(req: IncomingMessage, clientSocket: Duplex): boolean {
- const peerAddress = req.socket?.remoteAddress;
- if (peerAddress !== undefined && !isLoopbackAddress(peerAddress)) {
- clientSocket.destroy();
- return true;
- }
- if (!isAllowedWorkspaceHostHeader(req.headers.host)) {
- clientSocket.destroy();
- return true;
- }
- const origin = req.headers.origin;
- if (typeof origin === 'string' && !isAllowedApiOrigin(origin)) {
- clientSocket.destroy();
- return true;
- }
- return false;
-}
-
-/**
- * Forward an HTTP/1.1 upgrade (e.g. WebSocket) to an upstream and bridge the
- * two sockets once the upstream responds with `101 Switching Protocols`.
- *
- * Uses a raw TCP connection rather than `http.request({ headers: { upgrade
- * ... } })`. Node's HTTP client agent can interfere with the upgrade flow
- * (and Bun's compatibility layer is even less reliable for this case);
- * reconstructing the request bytes ourselves keeps the forward path
- * deterministic across runtimes.
- *
- * Caller is responsible for the loopback / origin gate (see
- * `rejectUpgradeIfNotLoopback`). `clientSocket` is the inbound socket Node
- * detached on the upgrade event. `head` is any prefix bytes Node captured
- * between the request line and the event firing (usually empty for WS).
- *
- * The pair of sockets is added to `upgradeSockets` so a parent server's
- * shutdown can tear them down promptly — `httpServer.close()` does not
- * track sockets detached by upgrade.
- */
-export function proxyUpgrade(
- req: IncomingMessage,
- clientSocket: Duplex,
- head: Buffer,
- upstreamHost: string,
- upstreamPort: number,
- upgradeSockets: Set<Duplex>,
-): void {
- upgradeSockets.add(clientSocket);
- clientSocket.once('close', () => upgradeSockets.delete(clientSocket));
-
- // Connect timeout — matches the HTTP path's `DEFAULT_UPSTREAM_TIMEOUT_MS`
- // (10s) so a Hocuspocus that accepts TCP but never responds doesn't pin a
- // socket pair indefinitely. Cleared in the `connect` callback below so the
- // bridge isn't subject to an idle-activity timeout once it's live.
- const upstreamSocket = netConnect({
- host: upstreamHost,
- port: upstreamPort,
- timeout: DEFAULT_UPSTREAM_TIMEOUT_MS,
- });
- upgradeSockets.add(upstreamSocket);
- upstreamSocket.once('close', () => upgradeSockets.delete(upstreamSocket));
-
- let cleaned = false;
- const cleanup = (reason?: { event: string; err?: unknown }): void => {
- if (cleaned) return;
- cleaned = true;
- if (reason !== undefined) {
- const err = reason.err;
- console.warn(
- JSON.stringify({
- event: reason.event,
- upstreamHost,
- upstreamPort,
- url: req.url,
- code: err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined,
- message: err instanceof Error ? err.message : undefined,
- }),
- );
- }
- try {
- upstreamSocket.destroy();
- } catch {
- // best-effort
- }
- try {
- clientSocket.destroy();
- } catch {
- // best-effort
- }
- };
-
- upstreamSocket.once('connect', () => {
- // Bridge is live — drop the connect timeout so long-running WS sessions
- // aren't capped by it. (Hocuspocus connections are intentionally
- // long-lived; an activity-based timeout would need its own design.)
- upstreamSocket.setTimeout(0);
-
- // Reconstruct the upgrade request: request line + headers + CRLF CRLF.
- // `req.headers` arrives lowercase-keyed (per Node parser); HTTP header
- // names are case-insensitive so verbatim serialisation is fine.
- const lines: string[] = [
- `${req.method ?? 'GET'} ${req.url ?? '/'} HTTP/1.1`,
- `host: ${upstreamHost}:${upstreamPort}`,
- ];
- for (const [name, value] of Object.entries(req.headers)) {
- if (name.toLowerCase() === 'host') continue;
- if (value === undefined) continue;
- if (Array.isArray(value)) {
- for (const v of value) lines.push(`${name}: ${v}`);
- } else {
- lines.push(`${name}: ${value}`);
- }
- }
- try {
- upstreamSocket.write(`${lines.join('\r\n')}\r\n\r\n`);
- if (head.length > 0) upstreamSocket.write(head);
- } catch (err) {
- cleanup({ event: 'proxy-upgrade-handshake-write-failed', err });
- return;
- }
-
- // Bidirectional forwarding via manual `data` handlers — `stream.pipe`
- // semantics on upgrade-detached sockets are inconsistent under Bun
- // (spurious `end` events before any payload flows). Manual forwarding
- // sidesteps that.
- upstreamSocket.on('data', (chunk: Buffer) => {
- if (clientSocket.writable) clientSocket.write(chunk);
- });
- clientSocket.on('data', (chunk: Buffer) => {
- if (upstreamSocket.writable) upstreamSocket.write(chunk);
- });
- });
-
- upstreamSocket.once('timeout', () => {
- cleanup({ event: 'proxy-upgrade-upstream-connect-timeout' });
- });
-
- // `on('error')` rather than `once('error')` — `cleanup` is idempotent via
- // the `cleaned` flag, and a stray write-after-destroy in the `data`
- // forwarders can fire a second `error` we must still catch (an
- // unhandled-error event would throw at the process level). `close` is the
- // authoritative full-teardown signal; `end` is intentionally NOT listened
- // for because under Bun 1.3 a freshly-connected `net.Socket` can emit a
- // spurious `end` before any payload flows.
- upstreamSocket.on('error', (err) => cleanup({ event: 'proxy-upgrade-upstream-error', err }));
- clientSocket.on('error', (err) => cleanup({ event: 'proxy-upgrade-client-error', err }));
- upstreamSocket.once('close', () => cleanup());
- clientSocket.once('close', () => cleanup());
-}
-
-/**
- * Hop-by-hop headers per RFC 7230 §6.1 — these MUST NOT be forwarded by a
- * proxy. Additionally we drop `Cookie` / `Set-Cookie` because `ok ui` does
- * not set cookies and there is no legitimate reason for localhost peers to
- * flow cookies through our reverse proxy.
- *
- * `Upgrade` is stripped on the plain-HTTP request path only. WebSocket
- * upgrades are routed through `proxyUpgrade` above, which preserves
- * `Connection` / `Upgrade` / `Sec-WebSocket-*` verbatim so the upstream can
- * complete the handshake.
- */
-const HOP_BY_HOP_HEADERS: readonly string[] = [
- 'connection',
- 'keep-alive',
- 'proxy-authenticate',
- 'proxy-authorization',
- 'te',
- 'trailer',
- 'transfer-encoding',
- 'upgrade',
- 'cookie',
- 'set-cookie',
-];
-
-export async function startProxyServer(opts: StartProxyOptions): Promise<ProxyServerHandle> {
- const timeoutMs = opts.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS;
- // Track upgrade-pipe sockets so `close()` can drain them. `httpServer.close()`
- // does not track sockets detached by an upgrade event; without explicit
- // draining a long-lived WS would hold the close-callback open indefinitely.
- const upgradeSockets = new Set<Duplex>();
- const httpServer: HttpServer = createHttpServer((req, res) => {
- // Standalone proxy mode (lock-collision fallback) forwards every URL — not
- // just /api/*. Apply the gate to every request because we have no way to
- // distinguish state-mutating from read-only paths without parsing every
- // upstream's route table; loopback is the only sound default.
- if (rejectIfNotLoopbackApi(req, res)) return;
- forwardRequest(req, res, opts.upstreamHost, opts.upstreamPort, timeoutMs);
- });
-
- // WebSocket upgrades — forward to the same upstream the HTTP path goes to.
- // Without this, browsers loaded from this proxy port that try to open a WS
- // here (the same-origin case: Electron utility upstream
- // serves the shell + Hocuspocus on a single port) get their connection
- // dropped — the kernel resets the socket because Node has no listener for
- // the `upgrade` event. The upstream then handles the upgrade natively
- // (Hocuspocus is wired into its HTTP server in both `ok ui` and the
- // Electron utility paths).
- httpServer.on('upgrade', (req, clientSocket, head) => {
- if (rejectUpgradeIfNotLoopback(req, clientSocket)) return;
- proxyUpgrade(req, clientSocket, head, opts.upstreamHost, opts.upstreamPort, upgradeSockets);
- });
-
- await new Promise<void>((done, fail) => {
- const onError = (err: Error) => fail(err);
- httpServer.once('error', onError);
- httpServer.listen(opts.listenPort, opts.host, () => {
- httpServer.off('error', onError);
- done();
- });
- });
-
- const addr = httpServer.address();
- const port = typeof addr === 'object' && addr !== null ? addr.port : opts.listenPort;
-
- return {
- httpServer,
- port,
- close: () =>
- new Promise<void>((done) => {
- // `httpServer.close(cb)` only invokes the callback once every existing
- // connection has finished — including idle HTTP keep-alive sockets
- // left over from prior `fetch()` calls. Without evicting those, the
- // promise hangs until the OS times out the socket (~10s+), which
- // shows up as flaky test-suite `afterEach` timeouts. Destroy live
- // upgrade pipes first (they own their own sockets post-upgrade and
- // wouldn't be tracked by `closeIdleConnections`), then close idle
- // keep-alives.
- for (const sock of upgradeSockets) {
- try {
- sock.destroy();
- } catch {
- // best-effort — the socket may already be torn down.
- }
- }
- upgradeSockets.clear();
- httpServer.close(() => done());
- httpServer.closeIdleConnections();
- }),
- };
-}
-
-interface ProxyRequestOptions {
- upstreamHost: string;
- upstreamPort: number;
- /** Per-request upstream timeout in ms. Default 10_000. 0 disables. */
- upstreamTimeoutMs?: number;
-}
-
-/**
- * Forward a single incoming request to an upstream. Shared between
- * `startProxyServer` (which wires it as the request handler) and embedded
- * callers like `ok ui` that thread a targeted `/api/*` proxy into their
- * existing request router without running a second HTTP listener.
- *
- * Handles: header forwarding (minus Host), request-body piping, response
- * status/headers/body piping, 504 on upstream timeout, 502 on upstream
- * error, and client-abort propagation so no upstream sockets leak.
- */
-export function proxyRequest(
- req: IncomingMessage,
- res: ServerResponse,
- opts: ProxyRequestOptions,
-): void {
- forwardRequest(
- req,
- res,
- opts.upstreamHost,
- opts.upstreamPort,
- opts.upstreamTimeoutMs ?? DEFAULT_UPSTREAM_TIMEOUT_MS,
- );
-}
-
-function forwardRequest(
- req: IncomingMessage,
- res: ServerResponse,
- upstreamHost: string,
- upstreamPort: number,
- upstreamTimeoutMs: number,
-): void {
- // Strip hop-by-hop headers (RFC 7230 §6.1) + Cookie / Set-Cookie. Drop the
- // inbound Host header so we can rewrite it to the upstream authority —
- // keeping the browser's Host would surface the proxy port in upstream logs
- // and confuse vhost-routing upstreams.
- const headers: IncomingHttpHeaders = { ...req.headers };
- delete headers.host;
- for (const name of HOP_BY_HOP_HEADERS) {
- delete headers[name];
- }
-
- // Per-request deadline — destroy the upstream + response on elapse so a
- // slow-loris client or hung upstream can't pin sockets past DEFAULT_REQUEST_TIMEOUT_MS.
- req.setTimeout(DEFAULT_REQUEST_TIMEOUT_MS, () => {
- if (!res.headersSent) {
- try {
- emitProblem(
- res,
- 408,
- 'urn:ok:error:request-timeout',
- 'Proxy request exceeded the per-request deadline.',
- `Slow-loris-class: client did not finish within ${DEFAULT_REQUEST_TIMEOUT_MS / 1000}s.`,
- );
- } catch {
- // already closed
- }
- } else {
- try {
- res.end();
- } catch {
- // already closed
- }
- }
- try {
- req.socket?.destroy();
- } catch {
- // best-effort
- }
- });
-
- const upstreamReq = httpRequest(
- {
- host: upstreamHost,
- port: upstreamPort,
- method: req.method,
- path: req.url,
- headers: { ...headers, host: `${upstreamHost}:${upstreamPort}` },
- },
- (upstreamRes) => {
- // Strip hop-by-hop headers + Set-Cookie on the response path too —
- // same rationale as the inbound direction.
- const resHeaders = { ...upstreamRes.headers };
- for (const name of HOP_BY_HOP_HEADERS) {
- delete resHeaders[name];
- }
- res.writeHead(upstreamRes.statusCode ?? 502, resHeaders);
- upstreamRes.pipe(res);
- upstreamRes.once('error', () => {
- try {
- res.end();
- } catch {
- // Already closed — nothing to do.
- }
- });
- },
- );
-
- // Bounded upstream timeout — without this a hung `ok ui` (GC pause, deadlock,
- // anything non-crashing) leaves browsers waiting indefinitely. On deadline we
- // destroy the upstream socket and respond 504 ourselves (headers-not-sent path
- // is the common case; if upstream already started streaming, we just end).
- if (upstreamTimeoutMs > 0) {
- upstreamReq.setTimeout(upstreamTimeoutMs, () => {
- if (!res.headersSent) {
- emitProblem(
- res,
- 504,
- 'urn:ok:error:gateway-timeout',
- 'Upstream did not respond before the gateway deadline.',
- `Upstream timeout: ${upstreamTimeoutMs / 1000}s elapsed without a response.`,
- );
- } else {
- try {
- res.end();
- } catch {
- // Already closed.
- }
- }
- upstreamReq.destroy();
- });
- }
-
- upstreamReq.on('error', () => {
- if (!res.headersSent) {
- // 502 Bad Gateway → reuse `collab-server-not-running` since the
- // proxy's upstream IS the collab server (`ok start`); a connection
- // error here means the upstream socket couldn't be established or
- // dropped mid-request.
- emitProblem(
- res,
- 502,
- 'urn:ok:error:collab-server-not-running',
- 'Collab server is unreachable.',
- 'Upstream connection failed or dropped before a response was received.',
- );
- } else {
- try {
- res.end();
- } catch {
- // Already closed.
- }
- }
- });
-
- // Propagate client aborts so we don't leak an upstream socket.
- req.on('error', () => {
- upstreamReq.destroy();
- });
-
- req.pipe(upstreamReq);
-}
diff --git a/packages/cli/src/commands/ui.test.ts b/packages/cli/src/commands/ui.test.ts
deleted file mode 100644
index e92cd817e..000000000
--- a/packages/cli/src/commands/ui.test.ts
+++ /dev/null
@@ -1,1403 +0,0 @@
-import {
- existsSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- symlinkSync,
- writeFileSync,
-} from 'node:fs';
-import { mkdtemp, rm } from 'node:fs/promises';
-import {
- createServer as createHttpServer,
- request as httpRequest,
- type IncomingMessage,
-} from 'node:http';
-import { tmpdir } from 'node:os';
-import { resolve } from 'node:path';
-import { ProblemDetailsSchema, type Scheduler } from '@inkeep/open-knowledge-core';
-import {
- acquireServerLock,
- ConfigSchema,
- getLocalDir,
- readUiLock,
- type UiLockMetadata,
- updateServerLockPort,
-} from '@inkeep/open-knowledge-server';
-import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import {
- closeHttpServers,
- DEFAULT_UI_PORT,
- DEFAULT_UI_SAFETY_NET_MS,
- isNonInteractiveContext,
- parseUpstreamUrl,
- resolveRequestedPort,
- resolveUiLockCollision,
- startUiServer,
- type UiServerHandle,
-} from './ui.ts';
-
-interface ManualScheduler extends Scheduler {
- advanceTime(ms: number): void;
- pendingCount(): number;
-}
-
-function createManualScheduler(): ManualScheduler {
- type Entry = { id: number; cb: () => void; dueAt: number };
- const queue: Entry[] = [];
- let now = 0;
- let nextId = 1;
- return {
- setTimeout: (cb, ms) => {
- const id = nextId++;
- queue.push({ id, cb, dueAt: now + ms });
- return id as unknown as ReturnType<typeof globalThis.setTimeout>;
- },
- clearTimeout: (handle) => {
- const id = handle as unknown as number;
- const idx = queue.findIndex((e) => e.id === id);
- if (idx >= 0) queue.splice(idx, 1);
- },
- now: () => now,
- advanceTime(ms) {
- now += ms;
- for (let pass = 0; pass < 100; pass++) {
- const due = queue.filter((e) => e.dueAt <= now);
- if (due.length === 0) return;
- for (const e of due) {
- const idx = queue.indexOf(e);
- if (idx >= 0) queue.splice(idx, 1);
- e.cb();
- }
- }
- },
- pendingCount: () => queue.length,
- };
-}
-
-let tmpDir: string;
-let lockDir: string;
-let handle: UiServerHandle | null = null;
-
-beforeEach(async () => {
- tmpDir = await mkdtemp(resolve(tmpdir(), 'ok-ui-cmd-test-'));
- lockDir = getLocalDir(tmpDir);
-});
-
-afterEach(async () => {
- if (handle) {
- handle.release();
- await closeHttpServers(handle.httpServers);
- handle = null;
- }
- await rm(tmpDir, { recursive: true, force: true });
-});
-
-function config() {
- return ConfigSchema.parse({});
-}
-
-async function get(port: number, path: string) {
- const res = await fetch(`http://127.0.0.1:${port}${path}`);
- const body = await res.text();
- return { status: res.status, body, headers: res.headers };
-}
-
-/**
- * Write a minimal Vite-shaped SPA dist (index.html referencing a hashed
- * bundle, plus the bundle) under `<dir>/dist` and return that path. Used as an
- * explicit `assetDir` so the SPA static-serving tests don't depend on a real
- * `bun run build` having produced `packages/app/dist`.
- */
-function seedDist(dir: string, hash: string): string {
- const dist = resolve(dir, 'dist');
- mkdirSync(resolve(dist, 'assets'), { recursive: true });
- writeFileSync(
- resolve(dist, 'index.html'),
- `<!doctype html><html><head><script type="module" src="/assets/app-${hash}.js"></script></head><body><div id="root"></div></body></html>`,
- );
- writeFileSync(resolve(dist, 'assets', `app-${hash}.js`), `console.log(${JSON.stringify(hash)});`);
- return dist;
-}
-
-/**
- * Send a request with arbitrary Host / Origin headers. We can't use `fetch`
- * for these tests because some runtimes silently rewrite Host. `http.request`
- * lets us put whatever bytes we want on the wire.
- */
-async function rawRequest(opts: {
- port: number;
- path: string;
- method?: string;
- host?: string;
- origin?: string;
- body?: string;
- contentType?: string;
-}): Promise<{ status: number; body: string; headers: Record<string, string | string[]> }> {
- return new Promise((done, fail) => {
- const req = httpRequest(
- {
- // Connect to the loopback literal these rigs bind ('127.0.0.1') —
- // dialing the bound literal removes any name-resolution ambiguity.
- host: '127.0.0.1',
- port: opts.port,
- path: opts.path,
- method: opts.method ?? 'GET',
- headers: {
- host: opts.host ?? `127.0.0.1:${opts.port}`,
- ...(opts.origin !== undefined ? { origin: opts.origin } : {}),
- ...(opts.contentType ? { 'content-type': opts.contentType } : {}),
- ...(opts.body !== undefined
- ? { 'content-length': String(Buffer.byteLength(opts.body)) }
- : {}),
- },
- },
- (res: IncomingMessage) => {
- const chunks: Buffer[] = [];
- res.on('data', (c) => chunks.push(c as Buffer));
- res.on('end', () => {
- done({
- status: res.statusCode ?? 0,
- body: Buffer.concat(chunks).toString('utf-8'),
- headers: res.headers as Record<string, string | string[]>,
- });
- });
- },
- );
- req.on('error', fail);
- if (opts.body !== undefined) req.write(opts.body);
- req.end();
- });
-}
-
-type UpstreamSurrogate = { port: number; close: () => Promise<void> };
-
-/**
- * Surrogate collab upstream owning BOTH loopback slots of its port. The
- * lock-based /api proxy dials `127.0.0.1` (matching `ok start`'s numeric
- * default bind), while resolveUiLockCollision's proxy mode may still dial a
- * hostname — owning both slots keeps the other family's slot un-squattable
- * regardless, the interception class rig-loopback-exclusivity pins. Mirror
- * production startUiServer's two-socket loopback default: bind [::1] on a
- * kernel port, then 127.0.0.1 on the same port.
- */
-async function startDualLoopbackUpstream(
- handler: Parameters<typeof createHttpServer>[1],
-): Promise<UpstreamSurrogate> {
- const v6 = createHttpServer(handler);
- await new Promise<void>((done, fail) => {
- v6.once('error', fail);
- v6.listen(0, '::1', () => {
- v6.off('error', fail);
- done();
- });
- });
- const port = (v6.address() as { port: number }).port;
- const v4 = createHttpServer(handler);
- try {
- await new Promise<void>((done, fail) => {
- v4.once('error', fail);
- v4.listen(port, '127.0.0.1', () => {
- v4.off('error', fail);
- done();
- });
- });
- } catch (err) {
- await new Promise<void>((r) => v6.close(() => r()));
- throw err;
- }
- return {
- port,
- close: async () => {
- await Promise.all([
- new Promise<void>((r) => v6.close(() => r())),
- new Promise<void>((r) => v4.close(() => r())),
- ]);
- },
- };
-}
-
-describe('resolveRequestedPort', () => {
- test('default is DEFAULT_UI_PORT with kernel-allocated fallback', () => {
- expect(resolveRequestedPort(undefined, undefined)).toEqual({
- port: DEFAULT_UI_PORT,
- fallbackToKernel: true,
- });
- });
- test('--port wins over PORT env and is operator-explicit (no fallback)', () => {
- expect(resolveRequestedPort('4000', '5000')).toEqual({
- port: 4000,
- fallbackToKernel: false,
- });
- });
- test('PORT env used when --port absent and is operator-explicit (no fallback)', () => {
- expect(resolveRequestedPort(undefined, '5555')).toEqual({
- port: 5555,
- fallbackToKernel: false,
- });
- });
- test('empty PORT env falls back to DEFAULT_UI_PORT with kernel-allocated fallback', () => {
- expect(resolveRequestedPort(undefined, '')).toEqual({
- port: DEFAULT_UI_PORT,
- fallbackToKernel: true,
- });
- });
- test('invalid --port throws', () => {
- expect(() => resolveRequestedPort('nope', undefined)).toThrow();
- });
- test('invalid PORT env throws', () => {
- expect(() => resolveRequestedPort(undefined, 'nope')).toThrow();
- });
- test('port=0 (kernel-allocated) is accepted; explicit caller, no auto-fallback', () => {
- expect(resolveRequestedPort('0', undefined)).toEqual({
- port: 0,
- fallbackToKernel: false,
- });
- });
-});
-
-describe('startUiServer', () => {
- test('binds requested port and writes ui.lock with resolved port', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- expect(handle.port).toBeGreaterThan(0);
-
- const lockPath = resolve(lockDir, 'ui.lock');
- expect(existsSync(lockPath)).toBe(true);
- const lock = JSON.parse(readFileSync(lockPath, 'utf-8'));
- expect(lock.pid).toBe(process.pid);
- expect(lock.port).toBe(handle.port);
- });
-
- test('falls back to kernel-allocation when requested port is busy and fallbackToKernel=true', async () => {
- // Stand up a blocker on a kernel-allocated port (pinned to 127.0.0.1 so
- // there's no DNS-resolution ambiguity vs. 'localhost' which can map to
- // either IPv4 or IPv6 on different macOS configs). startUiServer is then
- // asked to bind that same port on the same host. With
- // `fallbackToKernel: true`, the bind layer catches EADDRINUSE and retries
- // with port 0; handle.port should be a different, kernel-assigned port.
- const { createServer } = await import('node:http');
- const blocker = createServer(() => {});
- await new Promise<void>((done, fail) => {
- blocker.once('error', fail);
- blocker.listen(0, '127.0.0.1', () => done());
- });
- const blockedPort = (blocker.address() as { port: number }).port;
- try {
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: blockedPort,
- fallbackToKernel: true,
- host: '127.0.0.1',
- });
- expect(handle.port).toBeGreaterThan(0);
- expect(handle.port).not.toBe(blockedPort);
- const lock = JSON.parse(readFileSync(resolve(lockDir, 'ui.lock'), 'utf-8'));
- expect(lock.port).toBe(handle.port);
- } finally {
- await new Promise<void>((done) => blocker.close(() => done()));
- }
- });
-
- test('propagates EADDRINUSE when requested port is busy and fallbackToKernel is falsy', async () => {
- // Operator-explicit ports never silently move — caller asked for THIS
- // port and gets the EADDRINUSE if it's busy.
- const { createServer } = await import('node:http');
- const blocker = createServer(() => {});
- await new Promise<void>((done, fail) => {
- blocker.once('error', fail);
- blocker.listen(0, '127.0.0.1', () => done());
- });
- const blockedPort = (blocker.address() as { port: number }).port;
- try {
- await expect(
- startUiServer({
- config: config(),
- cwd: tmpDir,
- port: blockedPort,
- host: '127.0.0.1',
- }),
- ).rejects.toMatchObject({ code: 'EADDRINUSE' });
- } finally {
- await new Promise<void>((done) => blocker.close(() => done()));
- }
- });
-
- test('two-socket loopback default: IPv6 binds then IPv4 EADDRINUSE triggers full retry', async () => {
- // Production-default path: host undefined → bindTargets = ['::1', '127.0.0.1'].
- // We block only 127.0.0.1:<port>, so the IPv6 bind on [::1] succeeds first,
- // then the IPv4 bind on the same port fails EADDRINUSE. With
- // `fallbackToKernel: true`, tearDownPartialBinds() must close the
- // already-bound [::1] server and runBindLoop(0) must re-bind both
- // families on a fresh kernel-allocated port.
- const { createServer } = await import('node:http');
- const blocker = createServer(() => {});
- await new Promise<void>((done, fail) => {
- blocker.once('error', fail);
- blocker.listen(0, '127.0.0.1', () => done());
- });
- const blockedPort = (blocker.address() as { port: number }).port;
- try {
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: blockedPort,
- fallbackToKernel: true,
- // host omitted → exercises the two-socket default
- });
- expect(handle.port).toBeGreaterThan(0);
- expect(handle.port).not.toBe(blockedPort);
- expect(handle.httpServers).toHaveLength(2);
- const lock = JSON.parse(readFileSync(resolve(lockDir, 'ui.lock'), 'utf-8'));
- expect(lock.port).toBe(handle.port);
- } finally {
- await new Promise<void>((done) => blocker.close(() => done()));
- }
- });
-
- test('/api/config returns collabUrl=null when server.lock is absent', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, body, headers } = await get(handle.port, '/api/config');
- expect(status).toBe(200);
- expect(headers.get('content-type')).toContain('application/json');
- const parsed = JSON.parse(body);
- expect(parsed.collabUrl).toBeNull();
- expect(parsed.previewUrl).toBeNull();
- expect(parsed.port).toBe(handle.port);
- });
-
- test('base-open GET / serves the SPA shell at root', async () => {
- const dist = seedDist(tmpDir, 'noredir');
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- assetDir: dist,
- });
- const res = await fetch(`http://127.0.0.1:${handle.port}/`, { redirect: 'manual' });
- expect(res.status).toBe(200);
- expect(await res.text()).toContain('id="root"');
- });
-
- test('/api/config returns same-origin collabUrl when server.lock has live port', async () => {
- // Collab port goes in `server.lock`, but the advertised `collabUrl`
- // points at the REQUEST's host (same-origin) so the shell's WS attempt
- // lands back on `ok ui`, which then forwards `/collab` upgrades to the
- // collab port internally. Sandboxed in-app preview panes (Claude Code,
- // etc.) only get one URL/port; same-origin keeps them on it.
- acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateServerLockPort(lockDir, 54321);
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { body } = await get(handle.port, '/api/config');
- const parsed = JSON.parse(body);
- expect(parsed.collabUrl).toBe(`ws://127.0.0.1:${handle.port}/collab`);
- });
-
- test('/api/config has no-store cache-control', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { headers } = await get(handle.port, '/api/config');
- 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' });
- expect(res.status).toBe(200);
- const body = await res.text();
- expect(body).toBe('');
- });
-
- test('unknown path returns 404 when no static assets present (tmp dir has no dist)', async () => {
- // startUiServer looks in ../../app/dist — in the worktree this DOES exist,
- // so we can't assert 404 absolutely. Instead assert the path is handled
- // (either 404 or SPA fallback 200) without crashing.
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status } = await get(handle.port, '/does-not-exist');
- expect([200, 404]).toContain(status);
- });
-
- test('GET / serves the SPA shell (rewrites to /index.html)', async () => {
- // Regression: sirv's `single: true` SPA fallback was silently disabled by
- // `extensions: []` (set so `/foo` doesn't transparently serve `/foo.html`).
- // The request handler now rewrites `/` and `''` to `/index.html` before
- // any middleware so the entry path always loads the SPA shell.
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const root = await get(handle.port, '/');
- const indexHtml = await get(handle.port, '/index.html');
- // Either both succeed (worktree has dist/) or both 404 (no dist), but
- // they MUST agree — `/` must not 404 while `/index.html` succeeds.
- expect(root.status).toBe(indexHtml.status);
- });
-
- test('release() removes the ui.lock', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const lockPath = resolve(lockDir, 'ui.lock');
- expect(existsSync(lockPath)).toBe(true);
-
- handle.release();
- expect(existsSync(lockPath)).toBe(false);
- expect(readUiLock(lockDir)).toBeNull();
-
- // Keep afterEach happy — server is still up, just lock removed.
- if (handle) await closeHttpServers(handle.httpServers);
- handle = null;
- });
-
- test('D-033: two-socket loopback — second bind via 127.0.0.1 fails loud with EADDRINUSE', async () => {
- // Default mode (host undefined) binds BOTH [::1] and 127.0.0.1. A second
- // bind to the same port on either family must fail — proving the
- // silent cross-family collision (one process on [::1]:3000 + another
- // on 127.0.0.1:3000) can no longer happen. `::` with ipv6Only:false
- // does NOT provide this property on macOS;
- // only explicit two-socket binding does.
- const h = await startUiServer({ config: config(), cwd: tmpDir, port: 0 });
- handle = h;
- expect(h.port).toBeGreaterThan(0);
- expect(h.httpServers.length).toBe(2);
-
- const collider = createHttpServer(() => {});
- let errorCode: string | undefined;
- await new Promise<void>((done) => {
- collider.once('error', (err: NodeJS.ErrnoException) => {
- errorCode = err.code;
- done();
- });
- collider.listen(h.port, '127.0.0.1', () => {
- // If listen succeeds, the IPv4 loopback side isn't bound.
- collider.close(() => done());
- });
- });
- expect(errorCode).toBe('EADDRINUSE');
- });
-
- test('D-033: two-socket loopback — second bind via [::1] also fails loud', async () => {
- const h = await startUiServer({ config: config(), cwd: tmpDir, port: 0 });
- handle = h;
- const collider = createHttpServer(() => {});
- let errorCode: string | undefined;
- await new Promise<void>((done) => {
- collider.once('error', (err: NodeJS.ErrnoException) => {
- errorCode = err.code;
- done();
- });
- collider.listen(h.port, '::1', () => {
- collider.close(() => done());
- });
- });
- expect(errorCode).toBe('EADDRINUSE');
- });
-
- test('D-033: two-socket loopback serves both families end-to-end', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0 });
- // Both families should answer on the same port.
- const v4 = await fetch(`http://127.0.0.1:${handle.port}/api/config`);
- expect(v4.status).toBe(200);
- const v6 = await fetch(`http://[::1]:${handle.port}/api/config`);
- expect(v6.status).toBe(200);
- });
-
- test('D-033 / G4: two projects with kernel-allocated port 0 get distinct ports', async () => {
- // Two `ok ui` instances in different contentDirs must each acquire a
- // unique kernel-allocated port. This is the mechanical property the
- // default (hardcoded 3000) did not provide.
- const otherTmpDir = await mkdtemp(resolve(tmpdir(), 'ok-ui-cmd-test-'));
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0 });
- const secondHandle = await startUiServer({
- config: config(),
- cwd: otherTmpDir,
- port: 0,
- });
- try {
- expect(handle.port).toBeGreaterThan(0);
- expect(secondHandle.port).toBeGreaterThan(0);
- expect(handle.port).not.toBe(secondHandle.port);
- // Both reachable end-to-end.
- const a = await fetch(`http://127.0.0.1:${handle.port}/api/config`);
- const b = await fetch(`http://127.0.0.1:${secondHandle.port}/api/config`);
- expect(a.status).toBe(200);
- expect(b.status).toBe(200);
- } finally {
- secondHandle.release();
- await closeHttpServers(secondHandle.httpServers);
- await rm(otherTmpDir, { recursive: true, force: true });
- }
- });
-
- test('GET /api/pages is proxied to the collab server when server.lock is live', async () => {
- // Stand up a surrogate collab server that answers /api/pages with a known
- // JSON body. The real ok start / Hocuspocus HTTP stack isn't needed for
- // this contract — we only care that the UI forwards upstream and pipes
- // the response back verbatim.
- const upstream = await startDualLoopbackUpstream((req, res) => {
- if (req.url === '/api/pages') {
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true, source: 'collab', pages: [] }));
- } else {
- res.writeHead(404);
- res.end();
- }
- });
- const upstreamPort = upstream.port;
-
- // Pretend ok start wrote its lock at that port.
- acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateServerLockPort(lockDir, upstreamPort);
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- try {
- const { status, body, headers } = await get(handle.port, '/api/pages');
- expect(status).toBe(200);
- expect(headers.get('content-type')).toContain('application/json');
- const parsed = JSON.parse(body);
- expect(parsed).toEqual({ ok: true, source: 'collab', pages: [] });
- } finally {
- await upstream.close();
- }
- });
-
- test('GET /api/anything returns RFC 9457 problem+json 503 when server.lock is absent', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, body, headers } = await get(handle.port, '/api/pages');
- expect(status).toBe(503);
- expect(headers.get('content-type')).toContain('application/problem+json');
- expect(headers.get('x-content-type-options')).toBe('nosniff');
- expect(headers.get('cache-control')).toBe('no-store');
- const parsed = ProblemDetailsSchema.parse(JSON.parse(body));
- expect(parsed.type).toBe('urn:ok:error:collab-server-not-running');
- expect(parsed.title).toContain('Collab server not running');
- expect(parsed.status).toBe(503);
- expect(parsed.instance).toMatch(
- /^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
- );
- expect(parsed.detail).toContain('/api/pages');
- });
-
- test('POST /api/create-page forwards method + body to the collab server', async () => {
- const receivedRequests: Array<{ method: string; body: string; contentType: string }> = [];
- const upstream = await startDualLoopbackUpstream((req, res) => {
- if (req.url === '/api/create-page' && req.method === 'POST') {
- let body = '';
- req.setEncoding('utf-8');
- req.on('data', (chunk) => {
- body += chunk;
- });
- req.on('end', () => {
- receivedRequests.push({
- method: req.method ?? '',
- body,
- contentType: String(req.headers['content-type'] ?? ''),
- });
- res.writeHead(201, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- } else {
- res.writeHead(404);
- res.end();
- }
- });
- const upstreamPort = upstream.port;
- acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateServerLockPort(lockDir, upstreamPort);
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- try {
- const res = await fetch(`http://127.0.0.1:${handle.port}/api/create-page`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ docName: 'notes/test', content: '# hi' }),
- });
- expect(res.status).toBe(201);
- const parsed = (await res.json()) as { ok: boolean };
- expect(parsed.ok).toBe(true);
- expect(receivedRequests).toHaveLength(1);
- expect(receivedRequests[0]?.method).toBe('POST');
- expect(receivedRequests[0]?.contentType).toContain('application/json');
- const sent = JSON.parse(receivedRequests[0]?.body ?? '{}');
- expect(sent).toEqual({ docName: 'notes/test', content: '# hi' });
- } finally {
- await upstream.close();
- }
- });
-
- test('/api/* proxy returns 502 when upstream connection fails', async () => {
- // Point server.lock at a port nothing listens on — simulates the collab
- // server crashing between lock write and our proxy attempt.
- const probe = createHttpServer();
- await new Promise<void>((done) => probe.listen(0, '127.0.0.1', () => done()));
- const deadPort = (probe.address() as { port: number }).port;
- await new Promise<void>((done) => probe.close(() => done()));
-
- acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateServerLockPort(lockDir, deadPort);
-
- 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/pages`);
- expect(res.status).toBe(502);
- });
-
- test('bind failure on an invalid host releases the lock (does not leak)', async () => {
- let caught: unknown;
- try {
- await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- // Reserved IP that cannot bind — forces listen() to reject.
- host: '240.0.0.1',
- });
- } catch (err) {
- caught = err;
- }
- expect(caught).toBeDefined();
- // Lock acquired pre-listen must be released on bind failure.
- expect(readUiLock(lockDir)).toBeNull();
- });
-
- test('starts when the content root contains a broken symlink', async () => {
- symlinkSync(resolve(tmpDir, 'missing-target'), resolve(tmpDir, 'broken-link'));
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status } = await get(handle.port, '/api/config');
- expect(status).toBe(200);
- });
-
- test('asset serve: missing asset-extension URL returns 404 (not SPA index.html)', async () => {
- // Closes the dogfood bug: `/missing.m4v` against a contentDir where the
- // file does not exist used to fall through to the SPA static handler
- // (which returns index.html as text/html for unknown URLs under
- // `single: true`). The asset-serve middleware's fail-closed 404 guard
- // catches asset-extension paths before they reach the SPA fallback.
- const fs = await import('node:fs');
- const seedFile = resolve(tmpDir, 'doc.md');
- fs.writeFileSync(seedFile, '# seed', 'utf-8');
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, headers } = await get(handle.port, '/missing.m4v');
- expect(status).toBe(404);
- // Should NOT be served as text/html (the SPA fallback's mime type).
- expect(headers.get('content-type') ?? '').not.toMatch(/^text\/html/);
- });
-
- test('asset serve: existing inline-renderable asset gets Content-Disposition: inline', async () => {
- const fs = await import('node:fs');
- const seedDoc = resolve(tmpDir, 'doc.md');
- fs.writeFileSync(seedDoc, '# seed', 'utf-8');
- const seedAsset = resolve(tmpDir, 'photo.png');
- fs.writeFileSync(seedAsset, 'fake-png', 'binary');
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, headers } = await get(handle.port, '/photo.png');
- expect(status).toBe(200);
- expect(headers.get('content-disposition')).toBe('inline');
- expect(headers.get('x-content-type-options')).toBe('nosniff');
- });
-
- test('SPA-bundle assets under /assets/ serve from dist/ (regression: woff2 fonts)', async () => {
- // Regression: the asset-serve middleware's fail-closed branch refuses
- // to fall through for ASSET_EXTENSIONS (woff/woff2/png/svg/…) when the
- // file is absent under contentDir. That stranded every Vite-bundled
- // hashed asset (`/assets/inter-latin-wght-normal-*.woff2` etc.) because
- // they live in `packages/app/dist/assets/`, not in contentDir — fonts
- // 404'd and the editor fell back to system-ui. Fix: try the static
- // handler first for `/assets/` so the SPA bundle wins, with
- // fall-through preserved for user uploads under contentDir/assets/.
- const distAssets = resolve(import.meta.dirname, '../../../app/dist/assets');
- if (!existsSync(distAssets)) return; // No built app — skip in CI without `bun run build`.
- const fontFile = readdirSync(distAssets).find((name) => name.endsWith('.woff2'));
- if (!fontFile) return; // Build emitted no fonts — nothing to assert.
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, headers } = await get(handle.port, `/assets/${fontFile}`);
- expect(status).toBe(200);
- // Sirv serves with the file's MIME, not the content middleware's
- // `attachment` disposition. Absence of CD here proves the request
- // bypassed the content middleware as intended.
- expect(headers.get('content-disposition')).toBeNull();
- });
-
- test('SPA bundle: a hashed asset added AFTER boot serves without restart (stale-build fix)', async () => {
- // The blank-screen bug: a long-running `ok ui` served a fresh index.html
- // but 404'd the new hashed bundles it referenced, because the production
- // `sirv` cached its file listing at boot. `dev: true` resolves per-request
- // against live disk, so an in-place rebuild is picked up without a restart.
- const distDir = seedDist(tmpDir, 'AAAA');
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- assetDir: distDir,
- });
-
- expect((await get(handle.port, '/assets/app-AAAA.js')).status).toBe(200);
-
- // Simulate an in-place rebuild: a new content-hashed bundle lands and
- // index.html is rewritten to reference it. The production boot map would
- // 404 `app-BBBB.js`; live resolution must serve it.
- writeFileSync(resolve(distDir, 'assets', 'app-BBBB.js'), 'console.log("BBBB");');
- writeFileSync(
- resolve(distDir, 'index.html'),
- '<!doctype html><html><head><script type="module" src="/assets/app-BBBB.js"></script></head><body><div id="root"></div></body></html>',
- );
-
- const after = await get(handle.port, '/assets/app-BBBB.js');
- expect(after.status).toBe(200);
-
- // index.html itself must also be served fresh (same `dev: true` handler) —
- // a fresh shell pointing at 404ing bundles is the blank-screen symptom.
- const htmlAfter = await get(handle.port, '/index.html');
- expect(htmlAfter.body).toContain('app-BBBB.js');
- });
-
- test('SPA bundle: a missing /assets/*.js returns a plain 404, not the API problem+json', async () => {
- // the `/assets/` fall-through used to terminate in `notFound`
- // (RFC 9457 problem+json), so a missing bundle returned the API error
- // envelope — which sent debugging toward a phantom routing bug. A static
- // miss must be a plain 404 (and never the SPA shell).
- const distDir = seedDist(tmpDir, 'AAAA');
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- assetDir: distDir,
- });
-
- const res = await get(handle.port, '/assets/app-DOESNOTEXIST.js');
- expect(res.status).toBe(404);
- const contentType = res.headers.get('content-type') ?? '';
- expect(contentType).not.toContain('application/problem+json'); // not the API envelope
- expect(contentType).not.toMatch(/^text\/html/); // not the SPA shell
- expect(res.body).toBe(''); // plain, empty static 404
- expect(res.headers.get('x-content-type-options')).toBe('nosniff');
- });
-
- test('SPA bundle: an unchanged asset revalidates with 304 via If-None-Match (etag)', async () => {
- // `etag: true` recovers the transfer savings the inert `immutable` flag
- // never delivered: dev mode otherwise sends `no-store` and re-streams.
- const distDir = seedDist(tmpDir, 'AAAA');
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- assetDir: distDir,
- });
-
- const first = await fetch(`http://127.0.0.1:${handle.port}/assets/app-AAAA.js`);
- expect(first.status).toBe(200);
- const etag = first.headers.get('etag');
- expect(etag).toBeTruthy();
- // `etag` mode revalidates rather than `no-store` — pins the improvement
- // (dev mode without etag would send `no-store` and re-stream every load).
- expect(first.headers.get('cache-control') ?? '').not.toBe('no-store');
-
- const second = await fetch(`http://127.0.0.1:${handle.port}/assets/app-AAAA.js`, {
- headers: { 'If-None-Match': etag as string },
- });
- expect(second.status).toBe(304);
- });
-
- test('SPA-bundle /assets/ falls through to content middleware when sirv misses', async () => {
- // The `/assets/` path-prefix bypass tries the static handler first,
- // but if sirv has no matching file (with `extensions: []` + a path
- // that has an extension), it calls `next()` instead of returning the
- // SPA shell. The fall-through then routes to the content middleware
- // so user uploads at `<contentDir>/assets/foo.png` still serve.
- const fs = await import('node:fs');
- const assetsDir = resolve(tmpDir, 'assets');
- mkdirSync(assetsDir, { recursive: true });
- fs.writeFileSync(resolve(tmpDir, 'doc.md'), '# seed', 'utf-8');
- fs.writeFileSync(resolve(assetsDir, 'user-upload.png'), 'fake-png', 'binary');
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, headers } = await get(handle.port, '/assets/user-upload.png');
- expect(status).toBe(200);
- // Content middleware's signature headers — proves the fall-through fired.
- expect(headers.get('content-disposition')).toBe('inline');
- expect(headers.get('x-content-type-options')).toBe('nosniff');
- });
-
- test('asset serve: content .html is served only inside a sandbox CSP (stored-XSS defense)', async () => {
- // Content html IS served from contentDir (so author-created HTML resolves +
- // opens) but ONLY under the sandbox CSP: any embedded script runs in a unique
- // opaque origin, and `connect-src 'none'` blocks it from reaching OK's
- // loopback API or exfiltrating. The serve layer never hands html a same-origin
- // document — the sandbox CSP is the stored-XSS defense (supersedes the prior
- // "not served at all" posture).
- const fs = await import('node:fs');
- const seedDoc = resolve(tmpDir, 'doc.md');
- fs.writeFileSync(seedDoc, '# seed', 'utf-8');
- const seedHtml = resolve(tmpDir, 'viewer.html');
- fs.writeFileSync(seedHtml, '<h1>viewer</h1><script>alert(1)</script>', 'utf-8');
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, headers } = await get(handle.port, '/viewer.html');
- expect(status).toBe(200);
- expect(headers.get('content-disposition')).toBe('inline');
- expect(headers.get('content-security-policy')).toBe(
- "sandbox allow-scripts; connect-src 'none'",
- );
- expect(headers.get('x-content-type-options')).toBe('nosniff');
- });
-
- test('asset serve: SPA app shell (/index.html miss) is NOT sandboxed', async () => {
- // A `.html` miss in contentDir falls through to the SPA static handler. The
- // sandbox CSP/disposition headers the asset middleware set before the miss
- // was known must be stripped — otherwise the editor shell loads under
- // `sandbox …` (opaque origin → API/WS/storage break).
- const dist = seedDist(tmpDir, 'noshell');
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- assetDir: dist,
- });
- const { status, headers } = await get(handle.port, '/index.html');
- expect(status).toBe(200);
- expect(headers.get('content-security-policy')).toBeNull();
- expect(headers.get('content-disposition')).toBeNull();
- });
-
- test('/api/* gate rejects requests with non-loopback Host header (DNS-rebind defense)', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const res = await rawRequest({
- port: handle.port,
- path: '/api/config',
- host: 'attacker.com:1234',
- });
- expect(res.status).toBe(403);
- expect(String(res.headers['content-type'] ?? '')).toContain('application/problem+json');
- const body = JSON.parse(res.body) as { type: string; title: string; status: number };
- expect(body.type).toBe('urn:ok:error:host-not-allowed');
- expect(body.status).toBe(403);
- });
-
- test('/api/* gate rejects requests with non-loopback Origin (CSRF defense)', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const res = await rawRequest({
- port: handle.port,
- path: '/api/config',
- origin: 'http://attacker.com',
- });
- expect(res.status).toBe(403);
- const body = JSON.parse(res.body) as { type: string; title: string; status: number };
- expect(body.type).toBe('urn:ok:error:invalid-origin');
- });
-
- test('/api/* gate accepts loopback Origin (legitimate Vite dev server)', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const res = await rawRequest({
- port: handle.port,
- path: '/api/config',
- origin: 'http://localhost:5173',
- });
- expect(res.status).toBe(200);
- });
-
- test('/api/* gate accepts Origin: null (Electron packaged renderer)', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const res = await rawRequest({
- port: handle.port,
- path: '/api/config',
- origin: 'null',
- });
- expect(res.status).toBe(200);
- });
-
- test('/api/* proxy gate rejects DNS-rebind Host even when collab server is up', async () => {
- let upstreamHits = 0;
- const upstream = await startDualLoopbackUpstream((_req, res) => {
- upstreamHits++;
- res.writeHead(200, { 'Content-Type': 'application/json' });
- res.end(JSON.stringify({ ok: true }));
- });
- const upstreamPort = upstream.port;
- acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateServerLockPort(lockDir, upstreamPort);
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- try {
- const res = await rawRequest({
- port: handle.port,
- path: '/api/agent-write-md',
- method: 'POST',
- host: 'attacker.com:1234',
- contentType: 'application/json',
- body: JSON.stringify({ docName: 'malicious', content: 'pwn' }),
- });
- expect(res.status).toBe(403);
- const body = JSON.parse(res.body) as { type: string; title: string; status: number };
- expect(body.type).toBe('urn:ok:error:host-not-allowed');
- expect(upstreamHits).toBe(0);
- } finally {
- await upstream.close();
- }
- });
-
- test('content-asset paths are Host-gated; SPA paths stay ungated', async () => {
- // Flipped pin (read-posture hardening): an asset-extension URL is a
- // content-serve attempt, so the in-middleware gate refuses a rebound
- // Host BEFORE the disk lookup (403 host-not-allowed, not the miss 404).
- // Extension-less SPA paths still serve regardless of Host — the shell is
- // public bundle code, and a browser navigating via different loopback
- // hostnames legitimately varies its Host.
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const gated = await rawRequest({
- port: handle.port,
- path: '/missing.png',
- host: 'attacker.com:1234',
- });
- expect(gated.status).toBe(403);
- expect((JSON.parse(gated.body) as { type: string }).type).toBe('urn:ok:error:host-not-allowed');
-
- const spa = await rawRequest({
- port: handle.port,
- path: '/some/deep-link',
- host: 'attacker.com:1234',
- });
- expect(spa.status).not.toBe(403);
- });
-
- test('shell root (GET / -> /index.html) is gated under a rebound Host; serves over loopback', async () => {
- // `ok ui` rewrites `GET /` (and `/index.html`) to an html-extension
- // content-serve attempt BEFORE this middleware, and `.html` is an
- // ASSET_EXTENSIONS member — so the shell root goes through the
- // content-serve gate here (asset-serve-middleware policy item 0). `ok ui`
- // is loopback-only (its `/api` gate is loopback-only too), so a rebound
- // Host at the root is refused; a loopback Host serves the SPA shell.
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- for (const path of ['/', '/index.html']) {
- const gated = await rawRequest({ port: handle.port, path, host: 'attacker.com:1234' });
- expect(gated.status, path).toBe(403);
- expect((JSON.parse(gated.body) as { type: string }).type).toBe(
- 'urn:ok:error:host-not-allowed',
- );
- }
- const loopback = await rawRequest({
- port: handle.port,
- path: '/',
- host: `127.0.0.1:${handle.port}`,
- });
- expect(loopback.status).toBe(200);
- expect(loopback.body).toContain('<!doctype html>');
- });
-
- test('asset serve: non-inline admitted asset gets Content-Disposition: attachment', async () => {
- const fs = await import('node:fs');
- const seedDoc = resolve(tmpDir, 'doc.md');
- fs.writeFileSync(seedDoc, '# seed', 'utf-8');
- // PDF is in ASSET_EXTENSIONS but in INLINE_RENDERABLE — pick a non-inline
- // admitted extension instead. ZIP is in ASSET_EXTENSIONS but not in
- // INLINE_RENDERABLE_EXTENSIONS, so it gets attachment.
- const seedZip = resolve(tmpDir, 'archive.zip');
- fs.writeFileSync(seedZip, 'fake-zip-bytes', 'binary');
-
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const { status, headers } = await get(handle.port, '/archive.zip');
- expect(status).toBe(200);
- expect(headers.get('content-disposition')).toBe('attachment');
- expect(headers.get('x-content-type-options')).toBe('nosniff');
- });
-});
-
-describe('startUiServer — D-025 12h safety-net', () => {
- test('default safety-net is 12 hours', () => {
- expect(DEFAULT_UI_SAFETY_NET_MS).toBe(12 * 60 * 60 * 1000);
- });
-
- test('schedules a safety-net timer with the configured interval', async () => {
- const scheduler = createManualScheduler();
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- safetyNetMs: 60_000,
- scheduler,
- });
- expect(scheduler.pendingCount()).toBe(1);
- });
-
- test('safety-net fires after the configured interval — closes server, releases lock, invokes onSafetyNet', async () => {
- const scheduler = createManualScheduler();
- let onSafetyNetFired = 0;
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- safetyNetMs: 60_000,
- scheduler,
- onSafetyNet: () => {
- onSafetyNetFired++;
- },
- });
- const port = handle.port;
- const lockPath = resolve(lockDir, 'ui.lock');
- expect(existsSync(lockPath)).toBe(true);
-
- // Advance past the safety-net deadline — the timer's callback runs
- // synchronously inside advanceTime, including releaseUiLock and
- // httpServer.close() (close() returns immediately; the actual socket
- // close completes async).
- scheduler.advanceTime(60_000);
- expect(onSafetyNetFired).toBe(1);
- expect(existsSync(lockPath)).toBe(false);
- expect(readUiLock(lockDir)).toBeNull();
-
- // Wait for the close to complete on the event loop — fetch should fail
- // (or get ECONNREFUSED) once the listener is gone.
- if (handle) await closeHttpServers(handle.httpServers);
- let connectError: unknown = null;
- try {
- await fetch(`http://127.0.0.1:${port}/api/config`);
- } catch (err) {
- connectError = err;
- }
- expect(connectError).not.toBeNull();
- handle = null; // afterEach already cleaned up.
- });
-
- test('release() before fire cancels the safety-net timer', async () => {
- const scheduler = createManualScheduler();
- let onSafetyNetFired = 0;
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- safetyNetMs: 60_000,
- scheduler,
- onSafetyNet: () => {
- onSafetyNetFired++;
- },
- });
- expect(scheduler.pendingCount()).toBe(1);
-
- handle.release();
- expect(scheduler.pendingCount()).toBe(0);
-
- // Even if we advance well past the deadline, the cancelled callback
- // never fires.
- scheduler.advanceTime(60_000 * 100);
- expect(onSafetyNetFired).toBe(0);
- });
-
- test('detachSafetyNet() cancels the timer without releasing the lock', async () => {
- const scheduler = createManualScheduler();
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- safetyNetMs: 60_000,
- scheduler,
- });
- const lockPath = resolve(lockDir, 'ui.lock');
- expect(existsSync(lockPath)).toBe(true);
-
- handle.detachSafetyNet();
- expect(scheduler.pendingCount()).toBe(0);
- // Lock is still held — only the timer was cancelled.
- expect(existsSync(lockPath)).toBe(true);
- });
-
- test('release() is idempotent — second call is a no-op', async () => {
- handle = await startUiServer({ config: config(), cwd: tmpDir, port: 0, host: '127.0.0.1' });
- const lockPath = resolve(lockDir, 'ui.lock');
-
- handle.release();
- expect(existsSync(lockPath)).toBe(false);
- // Second call must not throw and must not affect anything else.
- handle.release();
- expect(existsSync(lockPath)).toBe(false);
-
- // Keep afterEach happy — server still up, just lock gone.
- if (handle) await closeHttpServers(handle.httpServers);
- handle = null;
- });
-
- test('safetyNetMs=0 disables the safety-net entirely (no timer scheduled)', async () => {
- const scheduler = createManualScheduler();
- handle = await startUiServer({
- config: config(),
- cwd: tmpDir,
- port: 0,
- host: '127.0.0.1',
- safetyNetMs: 0,
- scheduler,
- });
- expect(scheduler.pendingCount()).toBe(0);
- });
-});
-
-describe('resolveUiLockCollision', () => {
- function fakeLock(port: number): UiLockMetadata {
- return {
- pid: process.pid,
- hostname: 'localhost',
- port,
- startedAt: new Date().toISOString(),
- worktreeRoot: tmpDir,
- };
- }
-
- test('same port as holder → already-running', async () => {
- const result = await resolveUiLockCollision({
- requestedPort: 3000,
- host: '127.0.0.1',
- lockDir,
- readLock: () => fakeLock(3000),
- });
- expect(result.mode).toBe('already-running');
- if (result.mode === 'already-running') expect(result.port).toBe(3000);
- });
-
- test('throws when lock disappeared mid-handle', async () => {
- await expect(
- resolveUiLockCollision({
- requestedPort: 3000,
- host: '127.0.0.1',
- lockDir,
- readLock: () => null,
- }),
- ).rejects.toThrow(/disappeared/);
- });
-
- test('different port + live upstream → proxy mode forwards correctly', async () => {
- // Stand up a real upstream so the proxy has something to forward to.
- const upstream = await startDualLoopbackUpstream((_req, res) => {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.end('upstream ok');
- });
- const upstreamPort = upstream.port;
-
- const result = await resolveUiLockCollision({
- requestedPort: 0, // kernel-allocated so we don't conflict with anything
- host: '127.0.0.1',
- lockDir,
- readLock: () => fakeLock(upstreamPort),
- });
-
- expect(result.mode).toBe('proxy');
- if (result.mode !== 'proxy') throw new Error('unreachable');
- expect(result.upstreamPort).toBe(upstreamPort);
-
- try {
- const response = await fetch(`http://127.0.0.1:${result.handle.port}/`);
- expect(response.status).toBe(200);
- expect(await response.text()).toBe('upstream ok');
- } finally {
- await result.handle.close();
- await upstream.close();
- }
- });
-
- test('proxy returns 502 when upstream dies', async () => {
- // Probe an ephemeral port and close so upstreamPort points at nothing.
- const probe = createHttpServer();
- await new Promise<void>((done) => probe.listen(0, '127.0.0.1', () => done()));
- const deadPort = (probe.address() as { port: number }).port;
- await new Promise<void>((done) => probe.close(() => done()));
-
- const result = await resolveUiLockCollision({
- requestedPort: 0,
- host: '127.0.0.1',
- lockDir,
- readLock: () => fakeLock(deadPort),
- });
- if (result.mode !== 'proxy') throw new Error('unreachable');
-
- try {
- const response = await fetch(`http://127.0.0.1:${result.handle.port}/`);
- expect(response.status).toBe(502);
- } finally {
- await result.handle.close();
- }
- });
-
- test('lock port=0 that becomes live within deadline → proxy mode', async () => {
- const upstream = await startDualLoopbackUpstream((_req, res) => res.end('late upstream'));
- const upstreamPort = upstream.port;
-
- let calls = 0;
- const readLock = () => {
- calls++;
- return calls < 3 ? fakeLock(0) : fakeLock(upstreamPort);
- };
-
- const result = await resolveUiLockCollision({
- requestedPort: 0,
- host: '127.0.0.1',
- lockDir,
- readLock,
- pollIntervalMs: 10,
- pollDeadlineMs: 2000,
- });
-
- expect(result.mode).toBe('proxy');
- if (result.mode !== 'proxy') throw new Error('unreachable');
- expect(result.upstreamPort).toBe(upstreamPort);
-
- await result.handle.close();
- await upstream.close();
- });
-
- test('lock port=0 that stays 0 → throws timeout error', async () => {
- await expect(
- resolveUiLockCollision({
- requestedPort: 3000,
- host: '127.0.0.1',
- lockDir,
- readLock: () => fakeLock(0),
- pollIntervalMs: 5,
- pollDeadlineMs: 25,
- }),
- ).rejects.toThrow(/did not bind within 2s/);
- });
-
- test('lock port=0 that resolves equal to requested port → already-running', async () => {
- let calls = 0;
- const readLock = () => {
- calls++;
- return calls < 3 ? fakeLock(0) : fakeLock(4321);
- };
-
- const result = await resolveUiLockCollision({
- requestedPort: 4321,
- host: '127.0.0.1',
- lockDir,
- readLock,
- pollIntervalMs: 5,
- pollDeadlineMs: 500,
- });
-
- expect(result.mode).toBe('already-running');
- if (result.mode === 'already-running') expect(result.port).toBe(4321);
- });
-});
-
-describe('isNonInteractiveContext — PRD-6704 keepalive gate', () => {
- // The `already-running` collision branch in `ok ui`'s action handler must
- // NOT call process.exit(0) when running non-interactively. Claude Code
- // Desktop spawns `ok ui` as a subprocess with PORT set + autoPort:true and
- // treats subprocess exit as "preview crashed", tearing down the pane.
- // isNonInteractiveContext is the predicate that gates exit vs keepalive.
-
- function makeProc(opts: {
- isTTY: boolean;
- port?: string;
- }): Pick<NodeJS.Process, 'stdout' | 'env'> {
- const env = (opts.port === undefined ? {} : { PORT: opts.port }) as NodeJS.ProcessEnv;
- return {
- stdout: { isTTY: opts.isTTY } as NodeJS.Process['stdout'],
- env,
- };
- }
-
- test('no TTY + no PORT env → non-interactive (subprocess case)', () => {
- expect(isNonInteractiveContext(makeProc({ isTTY: false }))).toBe(true);
- });
-
- test('no TTY + PORT env → non-interactive', () => {
- expect(isNonInteractiveContext(makeProc({ isTTY: false, port: '39848' }))).toBe(true);
- });
-
- test('TTY + PORT env → non-interactive (Claude Code Desktop pattern)', () => {
- // Claude Code Desktop's .claude/launch.json sets PORT=39848 +
- // autoPort:true. Even if the spawn happened to inherit a TTY, the
- // presence of PORT signals "spawned by an automated host" — exit(0)
- // would crash the preview pane.
- expect(isNonInteractiveContext(makeProc({ isTTY: true, port: '39848' }))).toBe(true);
- });
-
- test('TTY + no PORT env → interactive (operator at a terminal)', () => {
- // The one case where process.exit(0) is the right call — the operator
- // ran `ok ui` from their shell and just wants the "already running"
- // message + a clean exit.
- expect(isNonInteractiveContext(makeProc({ isTTY: true }))).toBe(false);
- });
-
- test('TTY + empty PORT env string is treated as no PORT (defense-in-depth)', () => {
- 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.ts
deleted file mode 100644
index 06d645380..000000000
--- a/packages/cli/src/commands/ui.ts
+++ /dev/null
@@ -1,1032 +0,0 @@
-/**
- * Sibling UI server — the engine behind `ok start --only ui --server-url`
- * (the deprecated explicit split-mode, which passes `upstreamUrl` instead of
- * discovering the upstream via `server.lock`).
- *
- * The `ok ui` command that used to front this engine has been removed: plain
- * `ok start` serves the shell from the project server on one port, and the
- * Desktop attaches via server.lock v2. This module retires together with
- * `--only ui` and `ui.lock` in the follow-up removal wave.
- *
- * 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
- * (port 0) so multi-project concurrency stays mechanical rather than
- * aspirational — guarding against silent cross-project collisions.
- * The user-facing URL is always sourced from `ui.lock.port`.
- *
- * Acquires `<lockDir>/ui.lock` so MCP tools can advertise preview URLs
- * pointing at this process.
- *
- * Exposes `GET /api/config` with `{collabUrl, previewUrl, port}`, derived
- * from the `ok start` lockfile. The React app reads it on mount to bootstrap
- * HocuspocusProvider.
- *
- * Static-asset serving — app bundle from `dist/public` (published CLI) or
- * `packages/app/dist` (monorepo dev), plus filter-aware content serving over
- * `contentDir`. `ok ui` is the sole server of the React bundle; `ok start`
- * no longer serves static assets.
- *
- * Lock-collision handling: when another `ok ui` already holds `ui.lock`,
- * `resolveUiLockCollision` decides between three modes — silent exit (same
- * port), reverse HTTP proxy (different port with live upstream), or timeout
- * (upstream still binding). The proxy uses only `node:http` (see
- * `ui-proxy.ts`).
- *
- * Safety-net self-shutdown: a 12-hour timer self-terminates the UI if the
- * parent `ok start` ever crashes silently without sending SIGTERM
- * (idle-shutdown sends SIGTERM as its final pre-exit step, but a hard crash
- * doesn't get there). The default 12h is comfortably longer than any
- * legitimate uninterrupted editing session, and short enough that a
- * forgotten UI doesn't linger overnight. Cancelled by `handle.release()`.
- */
-import type { Server as HttpServer, ServerResponse } from 'node:http';
-import {
- ASSET_EXTENSIONS,
- DEFAULT_SERVER_HOST,
- defaultScheduler,
- EXECUTABLE_BLOCKLIST_EXTENSIONS,
- INLINE_RENDERABLE_EXTENSIONS,
- type Scheduler,
-} from '@inkeep/open-knowledge-core';
-import type { Config } from '@inkeep/open-knowledge-server';
-import { emitProblem } from './ui-problem.ts';
-import {
- type ProxyServerHandle,
- proxyRequest,
- proxyUpgrade,
- rejectIfNotLoopbackApi,
- rejectUpgradeIfNotLoopback,
- startProxyServer,
-} from './ui-proxy.ts';
-
-/** 12 hours — default safety-net interval. */
-export const DEFAULT_UI_SAFETY_NET_MS = 12 * 60 * 60 * 1000;
-
-/**
- * Default UI port — what `ok ui` actually binds. Picked to be quirky and
- * IANA-unassigned so it almost never collides with another local dev
- * server. The bind layer falls back to kernel-allocation (port 0) on
- * `EADDRINUSE`, so a collision degrades to "preview pane misses, banner
- * URL still works" rather than a hard failure.
- */
-export const DEFAULT_UI_PORT = 39847;
-
-export interface UiServerHandle {
- /**
- * All bound HTTP servers. In two-socket-loopback mode (default) this has
- * length 2 — one IPv6 loopback (`[::1]`), one IPv4 loopback (`127.0.0.1`).
- * When a caller passes an explicit `host`, length is 1. Callers that want
- * to close the listener must close ALL servers; use the exported
- * `closeHttpServers` helper.
- */
- httpServers: HttpServer[];
- port: number;
- /** Release the lock + cancel the safety-net timer. Idempotent. */
- release: () => void;
- /** Cancel only the safety-net timer (release() also calls this). Idempotent. */
- detachSafetyNet: () => void;
- /** Reset the safety-net timer as if activity just occurred. Called on every
- * `/api/config` hit so an actively-used UI doesn't disconnect at 12h. */
- nudgeSafetyNet: () => void;
- /** Destroy any upgrade-detached WebSocket sockets (`/collab` forwarding
- * pairs). Called from shutdown paths before `closeHttpServers` so the
- * servers' close-callbacks can fire promptly — `httpServer.close()` does
- * not track upgrade-detached sockets and would otherwise wait on them
- * forever. Idempotent. */
- drainUpgradeSockets: () => void;
-}
-
-/**
- * Close every HTTP server in a `UiServerHandle` and resolve when all have
- * fully released their listening sockets. Use instead of touching
- * `handle.httpServers` directly so the two-socket lifecycle is centralized.
- */
-export async function closeHttpServers(servers: HttpServer[]): Promise<void> {
- await Promise.all(
- servers.map(
- (s) =>
- new Promise<void>((done) => {
- s.close(() => done());
- }),
- ),
- );
-}
-
-interface StartUiServerOptions {
- config: Config;
- cwd: string;
- port: number;
- /**
- * When `true` and the requested `port` is in use (`EADDRINUSE`), the bind
- * layer retries once with port 0 (kernel-allocation). Set by the action
- * handler when the port came from `DEFAULT_UI_PORT` rather than an
- * explicit `--port` flag or `PORT` env value — operator-explicit ports
- * never silently move. Preserves the multi-project bind guarantee when
- * the default is busy.
- */
- fallbackToKernel?: boolean;
- /**
- * Bind host. Undefined (default) triggers two-socket loopback mode: the
- * server is bound twice on the same port — once on `[::1]` (IPv6 loopback)
- * and once on `127.0.0.1` (IPv4 loopback). Any subsequent bind attempt on
- * the same port from either family fails loud with EADDRINUSE.
- *
- * Passing an explicit host (e.g. `'127.0.0.1'`, `'::1'`, `'0.0.0.0'`, `'::'`)
- * degrades to single-socket binding on that host. Tests and operator
- * overrides can still target a specific family.
- */
- host?: string;
- /** Override the 12h safety-net interval. Tests pass a small value. */
- safetyNetMs?: number;
- /** Scheduler override for tests (precedent #13b — implicit time-coupling is a smell). */
- scheduler?: Scheduler;
- /**
- * Optional callback invoked by the safety-net timer right before it tears
- * down the http listener + lock. Tests use this to assert the safety-net
- * actually fired (rather than coincidentally being shut down by something
- * else). Production use case: future hook for metrics / logging.
- */
- onSafetyNet?: () => void;
- /**
- * Override the directory the SPA bundle is served from. Defaults to the
- * published `dist/public` (or the monorepo `app/dist`) resolved from this
- * module's location. Explicit override is primarily a test seam — serve a
- * 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 };
-}
-
-/**
- * Boot the UI server. Exposed for tests so they can drive the HTTP surface
- * without having to go through Commander.
- */
-export async function startUiServer(opts: StartUiServerOptions): Promise<UiServerHandle> {
- const { existsSync } = await import('node:fs');
- const { createServer: createHttpServer } = await import('node:http');
- const { resolve } = await import('node:path');
- const {
- acquireUiLock,
- buildIngressPolicy,
- createAssetServeMiddleware,
- createContentFilter,
- readServerLock,
- releaseUiLock,
- updateUiLockPort,
- } = await import('@inkeep/open-knowledge-server');
- const { default: sirv } = await import('sirv');
- const { resolveContentDir, resolveLockDir } = await import('@inkeep/open-knowledge-server');
-
- const contentDir = resolveContentDir(opts.config, opts.cwd);
- // Lock anchor is the project root (cwd), not contentDir — must match
- // `server-factory.ts`'s `<projectDir>/.ok/local/server.lock` so the UI
- // server can be discovered alongside the data server when `content.dir`
- // is a sub-folder (git-root-promotion case).
- const lockDir = resolveLockDir(opts.cwd);
-
- // Acquire lock before any side effects. `port: 0` is the sentinel while
- // the server is binding; `updateUiLockPort` rewrites after `listen()`.
- acquireUiLock(lockDir, { port: 0, worktreeRoot: opts.cwd });
-
- // Locate the built React app. Priority: published dist/public (bundled CLI)
- // first, then monorepo dev paths.
- const cliDir = import.meta.dirname ?? new URL('.', import.meta.url).pathname;
- const assetPaths = [
- resolve(cliDir, 'public'), // npm install: dist/public/ (bundled)
- resolve(cliDir, '../../app/dist'), // monorepo dev from src/
- resolve(cliDir, '../../../app/dist'), // monorepo dev from dist/
- ];
- // Explicit override (test seam / embedder) wins; otherwise resolve the
- // published or monorepo build location.
- const assetDir = opts.assetDir ?? assetPaths.find((p) => existsSync(p));
- // `dev: true` resolves each request against live disk instead of a boot-time
- // file map, so an in-place rebuild (or in-place `npm i -g` upgrade) that
- // writes new content-hashed bundles is served without a restart. The
- // production-mode boot map otherwise 404s bundles that already exist on disk
- // while still streaming a fresh index.html that references them — the
- // blank-screen bug. `etag: true` adds If-None-Match revalidation (304 on
- // unchanged hashed files); `dev` mode sends `no-store` without it. A prior
- // `immutable: true` was inert here — sirv only emits Cache-Control when
- // `maxAge` is set, which it never was.
- const staticHandler = assetDir
- ? sirv(assetDir, { single: true, gzip: true, etag: true, dev: true, extensions: [] })
- : null;
-
- // Filter-aware content asset serving — shared `createAssetServeMiddleware`
- // applies the same Content-Disposition policy + 404 fail-closed guard the
- // dev-plugin path uses, so dev and prod cannot diverge on serve semantics.
- //
- // Use `dev: true` so sirv resolves files lazily instead of recursively
- // crawling the entire content root at boot. Repo-root content dirs often
- // include huge trees (`node_modules`, build artifacts) and can contain
- // broken links from package-manager swaps; eager traversal makes UI boot
- // fail before it has served a single request.
- //
- // `dotfiles: false` still keeps `.ok/` out of reach.
- // `extensions: []` disables sirv's default `['html', 'htm']` fallback —
- // without this, a request to `/docs/evil` transparently resolves
- // `docs/evil.html` and serves it as `text/html`, bypassing the
- // Content-Disposition dispatch (which matches on the requested URL's
- // extension). Refusing extension inference confines lookup to the
- // literal requested URL.
- //
- // The asset-serve middleware itself only fires when `contentSirv` is
- // present; if `contentDir` is missing we skip filter construction and
- // route everything through the SPA static handler (matches the
- // pre-middleware behavior for missing-contentDir setups).
- const assetServeMiddleware = existsSync(contentDir)
- ? createAssetServeMiddleware({
- contentFilter: createContentFilter({
- projectDir: opts.cwd,
- contentDir,
- }),
- contentSirv: sirv(contentDir, { dotfiles: false, dev: true, extensions: [] }),
- inlineExtensions: INLINE_RENDERABLE_EXTENSIONS,
- assetExtensions: ASSET_EXTENSIONS,
- blocklistExtensions: EXECUTABLE_BLOCKLIST_EXTENSIONS,
- // Loopback-only, matching this surface's `/api` gate. `ok ui`'s API
- // gate is `rejectIfNotLoopbackApi` (loopback-shaped Host only, never
- // policy-aware), so the content-serve gate must admit no wider a set —
- // otherwise a config-declared `externalUrl` would serve content assets
- // to a Host that every `/api` call on the same surface 403s, a
- // half-broken app. `ok ui` is a loopback sidecar; the data server
- // (`ok start`) is the exposable surface and builds the real policy.
- // Mirrors the Vite dev plugin's loopback-only default.
- ingressPolicy: buildIngressPolicy({}),
- })
- : 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).
- let resolvedPort = opts.port;
-
- // Forward-reference for the safety-net nudge (set below after the timer is
- // armed). The HTTP handler closes over this indirection so it picks up the
- // live callback once the timer is in place.
- let apiConfigNudge: (() => void) | null = null;
-
- // Request handler — the same function services every bound server (both
- // [::1] and 127.0.0.1 in two-socket-loopback mode, or the single socket
- // when a caller passes an explicit host).
- const requestHandler = (req: import('node:http').IncomingMessage, res: ServerResponse) => {
- const url = req.url?.split('?')[0];
-
- // Bare `/` and the empty path: rewrite to `/index.html` so sirv serves
- // the SPA shell. The static handler is configured with `extensions: []`
- // (a security choice — without it, `/foo` would transparently serve
- // `/foo.html` and bypass the Content-Disposition dispatch which keys
- // off the requested URL's extension). That suppression also disables
- // sirv's implicit directory-index resolution, so `/` ends up as a 404
- // even though `single: true` is set. The cleanest fix is to rewrite
- // the entry path explicitly here, before any middleware runs, rather
- // than re-enabling extension inference globally.
- if (url === '/' || url === '') {
- req.url = '/index.html';
- }
-
- // Loopback gate for the /api/* surface. The proxy below rewrites the Host
- // header to `localhost:<upstream-port>` and the upstream sees the proxy's
- // own loopback peer address — so the upstream's DNS-rebinding + loopback
- // checks are trivially satisfied for anything that reaches the proxy. We
- // re-apply the same gate here at the proxy front so a non-loopback peer,
- // attacker-controlled Host (DNS-rebind), or non-loopback Origin can never
- // forward through. Mirrors `api-extension.ts` so the proxy doesn't fall
- // behind the upstream as new defenses land there.
- if (url?.startsWith('/api/')) {
- if (rejectIfNotLoopbackApi(req, res)) return;
- }
-
- // GET /api/config — zero-ceremony bootstrap for the React app. Reads the
- // collab server.lock on demand so a later `ok start` shows up without
- // requiring a UI restart.
- if (url === '/api/config' && (req.method === 'GET' || req.method === 'HEAD')) {
- // Nudge the safety-net so an actively-polling client (the React
- // `useCollabUrl` hook, default ~2s cadence while unresolved) never lets
- // the 12h timer fire mid-session.
- apiConfigNudge?.();
- // 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
- // cross-port WS attempt that gets refused by sandboxed in-app preview
- // panes (e.g. Claude Code's preview browser locked to one URL). The
- // `/api/config` route already passed `rejectIfNotLoopbackApi` above, so
- // `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 = 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');
- // `nosniff` — defense in depth against a misconfigured intermediate or
- // browser that would otherwise content-sniff the response body.
- res.setHeader('X-Content-Type-Options', 'nosniff');
- res.statusCode = 200;
- if (req.method === 'HEAD') {
- res.end();
- } else {
- res.end(body);
- }
- return;
- }
-
- // All other /api/* requests: transparently proxy to the collab server
- // (`ok start`). The React app makes same-origin `fetch('/api/pages')`,
- // `/api/backlinks`, `/api/history`, etc.; post-lifecycle-split those
- // endpoints only exist on `ok start`, NOT `ok ui`. Without this proxy
- // the React app fetches would receive the SPA-fallback HTML and fail to
- // JSON.parse. When the collab server is absent (no server.lock
- // or port=0), we emit RFC 9457 problem+json so client-side
- // `ProblemDetailsSchema.safeParse` flows surface the actionable
- // "Start `ok start`" title instead of a generic HTTP-503 fallback.
- if (url?.startsWith('/api/')) {
- apiConfigNudge?.();
- const upstream = resolveUpstream();
- if (upstream === null) {
- emitProblem(
- res,
- 503,
- 'urn:ok:error:collab-server-not-running',
- 'Collab server not running. Start `ok start` or run `ok status`.',
- `Path: ${url}`,
- );
- return;
- }
- proxyRequest(req, res, {
- upstreamHost: upstream.host,
- upstreamPort: upstream.port,
- });
- return;
- }
-
- // SPA-bundle assets live under `/assets/` (Vite's `build.assetsDir`
- // default). Try the static handler first for that prefix so hashed
- // bundle files — fonts (.woff2), sprite sheets (.svg), bundled images
- // — are served from `dist/.../assets/` instead of getting intercepted
- // by `createAssetServeMiddleware`. The middleware's fail-closed branch
- // refuses to fall through for known asset extensions when contentSirv
- // misses, which would 404 every SPA-bundled woff2/png/svg whose name
- // doesn't happen to also exist under `<contentDir>/assets/`.
- //
- // Fall through to the content middleware when sirv misses — `single:
- // true` + `extensions: []` means a missing file WITH an extension
- // calls `next()` (instead of returning the SPA shell), so user
- // uploads at `<contentDir>/assets/foo.png` still serve.
- //
- // `/excalidraw-assets/` follows the same shell-first rule for the
- // vendored Excalidraw font tree (mirrors `mcp-mount.ts`) — keep the
- // two branches aligned; splitting them out would let one drift.
- if (staticHandler && (url?.startsWith('/assets/') || url?.startsWith('/excalidraw-assets/'))) {
- staticHandler(req, res, () => {
- if (assetServeMiddleware) {
- assetServeMiddleware(req, res, () => notFoundStatic(res));
- } else {
- notFoundStatic(res);
- }
- });
- return;
- }
-
- // Content files (markdown + assets) served via the shared asset-serve
- // middleware — same Content-Disposition policy (inline / attachment) +
- // fail-closed 404 guard that the dev plugin uses. Falls through to the
- // SPA static handler when the content filter excludes the path or sirv
- // doesn't recognize it.
- if (assetServeMiddleware) {
- assetServeMiddleware(req, res, () => {
- if (staticHandler) {
- staticHandler(req, res);
- } else {
- notFoundStatic(res);
- }
- });
- return;
- }
-
- // SPA fallback.
- if (staticHandler) {
- staticHandler(req, res);
- return;
- }
-
- notFoundStatic(res);
- };
-
- // HTTP/1.1 upgrade handler — forwards `/collab` WebSocket upgrades to the
- // collab server (`ok start`) so the React shell can talk to Hocuspocus on
- // the SAME origin it loaded from. Without this, the shell's WS attempt
- // would have to dial a different port (the collab one) — which works in
- // a regular browser tab but is refused by sandboxed in-app preview panes
- // (e.g. Claude Code's preview browser locked to one URL).
- //
- // Tracked socket pairs are drained explicitly on shutdown via
- // `drainUpgradeSockets` below — `httpServer.close()` waits on its
- // connection set but does not include upgrade-detached sockets under all
- // runtimes, so without the drain a long-lived WS can keep `release()`
- // from completing (then no `process.exit`-class fallback ever fires).
- const upgradeSocketsForShutdown = new Set<import('node:stream').Duplex>();
- const handleUpgrade = (
- req: import('node:http').IncomingMessage,
- clientSocket: import('node:stream').Duplex,
- head: Buffer,
- ): void => {
- if (rejectUpgradeIfNotLoopback(req, clientSocket)) return;
- const url = req.url?.split('?')[0] ?? '';
- // Hocuspocus mounts on `/collab` and `/collab/keepalive` only; tighter
- // than `startsWith('/collab')` so `/collabsy` and similar near-prefixes
- // don't accidentally tunnel through to the collab server.
- if (url !== '/collab' && !url.startsWith('/collab/')) {
- clientSocket.destroy();
- return;
- }
- const upstream = resolveUpstream();
- if (upstream === null) {
- console.warn(
- JSON.stringify({
- event: 'ok-ui-upgrade-no-collab-lock',
- url,
- reason: 'server.lock missing or port unbound — is `ok start` running?',
- }),
- );
- clientSocket.destroy();
- return;
- }
- proxyUpgrade(req, clientSocket, head, upstream.host, upstream.port, upgradeSocketsForShutdown);
- };
- const drainUpgradeSockets = (): void => {
- for (const sock of upgradeSocketsForShutdown) {
- try {
- sock.destroy();
- } catch {
- // best-effort — already destroyed sockets are no-ops.
- }
- }
- upgradeSocketsForShutdown.clear();
- };
-
- // BIND STRATEGY
- //
- // When `opts.host` is undefined (default), we bind two separate HTTP
- // servers on the same port: one on `[::1]` (IPv6 loopback), one on
- // `127.0.0.1` (IPv4 loopback). This is "two-socket loopback" mode.
- //
- // Why not `::` + `ipv6Only:false`? That
- // doesn't enforce EADDRINUSE on macOS — a second `127.0.0.1` bind
- // succeeds even when the IPv6 wildcard is already claimed. The only way
- // to get cross-family collision-
- // fail-loud on macOS is to bind both families explicitly.
- //
- // When `opts.host` is set (e.g. `-H 127.0.0.1`), we degrade to a
- // single-socket bind so callers opting into a specific family get
- // exactly that behavior.
- //
- // Sequencing: bind IPv6 first (the kernel assigns the port when
- // `opts.port === 0`), then bind IPv4 at the resolved port. If the
- // IPv4 bind fails (EADDRINUSE, EACCES, etc.), close the IPv6 server
- // and release the lock before propagating the error.
- const bindTargets: string[] = opts.host === undefined ? ['::1', '127.0.0.1'] : [opts.host];
- const httpServers: HttpServer[] = [];
- let boundPort = opts.port;
-
- // Bind loop with optional fallback. The first iteration uses the requested
- // port; if that fails with EADDRINUSE and `fallbackToKernel: true`, we
- // close any partial binds, reset `boundPort` to 0, and retry once. After
- // a successful first listen the kernel-resolved port is pinned for any
- // subsequent loopback families, so the IPv4 bind never re-triggers the
- // fallback (preserves the two-socket-loopback EADDRINUSE-fail-loud
- // invariant for any port the kernel actually assigned us).
- const isEAddrInUse = (err: unknown): boolean =>
- err instanceof Error && (err as NodeJS.ErrnoException).code === 'EADDRINUSE';
-
- const tearDownPartialBinds = async (): Promise<void> => {
- await Promise.all(
- httpServers.splice(0).map(
- (s) =>
- new Promise<void>((done) => {
- try {
- s.close(() => done());
- } catch {
- done();
- }
- }),
- ),
- );
- };
-
- const runBindLoop = async (initialPort: number): Promise<void> => {
- boundPort = initialPort;
- for (const host of bindTargets) {
- const server = createHttpServer(requestHandler);
- server.on('upgrade', handleUpgrade);
- httpServers.push(server);
- await new Promise<void>((done, fail) => {
- const onError = (err: Error) => fail(err);
- server.once('error', onError);
- server.listen(boundPort, host, () => {
- server.off('error', onError);
- const addr = server.address();
- if (typeof addr === 'object' && addr !== null) {
- // Pin the resolved port so the next bind in the loop uses the
- // same port (matters when opts.port was 0).
- boundPort = addr.port;
- }
- done();
- });
- });
- }
- };
-
- try {
- try {
- await runBindLoop(opts.port);
- } catch (err) {
- if (opts.fallbackToKernel === true && isEAddrInUse(err)) {
- // Default-port collision: tear down whichever bind half-completed
- // and retry once with kernel-allocation. Operator-explicit ports
- // (no fallback flag set) propagate the error as before. The
- // resolveRequestedPort contract guarantees fallbackToKernel is
- // only true when opts.port came from DEFAULT_UI_PORT (> 0), so
- // there is no "port=0 fell back to port=0" infinite-loop risk.
- await tearDownPartialBinds();
- await runBindLoop(0);
- } else {
- throw err;
- }
- }
- } catch (err) {
- // Any partial binds need to be torn down before we propagate.
- await tearDownPartialBinds();
- try {
- releaseUiLock(lockDir);
- } catch {
- // Release is best-effort; the primary failure is more informative.
- }
- throw err;
- }
-
- const realPort = boundPort;
- resolvedPort = realPort;
- // `localhost` (not numeric loopback): the bind loop covers both loopback
- // families, and this origin is browser-facing — matching what pre-`url`
- // preview readers derived from `port`.
- updateUiLockPort(lockDir, realPort, `http://localhost:${realPort}`);
-
- // Schedule the safety-net self-shutdown. The timer is cancelled by
- // `release()` (the canonical "I'm shutting down" signal) so an
- // operator-driven SIGTERM never trips it. Each `/api/config` hit nudges
- // the deadline forward so an actively-used UI never fires the safety-net.
- const scheduler = opts.scheduler ?? defaultScheduler;
- const safetyNetMs = opts.safetyNetMs ?? DEFAULT_UI_SAFETY_NET_MS;
- let safetyNetHandle: ReturnType<typeof scheduler.setTimeout> | null = null;
- let safetyNetCancelled = false;
- let lockReleased = false;
-
- const detachSafetyNet = (): void => {
- if (safetyNetCancelled) return;
- safetyNetCancelled = true;
- if (safetyNetHandle !== null) {
- scheduler.clearTimeout(safetyNetHandle);
- safetyNetHandle = null;
- }
- };
-
- const release = (): void => {
- detachSafetyNet();
- if (lockReleased) return;
- lockReleased = true;
- try {
- releaseUiLock(lockDir);
- } catch {
- // Release is best-effort — another cleanup may have raced us.
- }
- };
-
- const armSafetyNet = (): void => {
- if (safetyNetCancelled || safetyNetMs <= 0) return;
- if (safetyNetHandle !== null) {
- scheduler.clearTimeout(safetyNetHandle);
- safetyNetHandle = null;
- }
- safetyNetHandle = scheduler.setTimeout(() => {
- safetyNetHandle = null;
- // Ensure callbacks see safetyNetCancelled === false at this point —
- // we treat the fire as authoritative shutdown intent.
- console.warn(`[ui] safety-net (${safetyNetMs}ms) reached — shutting down (D-025 backstop)`);
- try {
- opts.onSafetyNet?.();
- } catch {
- // best-effort observer
- }
- // Drain upgrade-detached sockets first — `server.close()` does not
- // track them and would otherwise wait on them indefinitely.
- drainUpgradeSockets();
- // Close every bound HTTP server (two-socket loopback mode has two).
- for (const server of httpServers) {
- try {
- server.close();
- } catch {
- // best-effort
- }
- }
- release();
- }, safetyNetMs);
- };
-
- const nudgeSafetyNet = (): void => {
- if (safetyNetCancelled || safetyNetMs <= 0) return;
- armSafetyNet();
- };
-
- // Expose the nudge to the HTTP handler so every /api/config request resets
- // the timer. Without this an actively-used UI disconnects at 12h — the
- // safety-net is meant to catch orphaned siblings, not healthy ones.
- apiConfigNudge = nudgeSafetyNet;
-
- armSafetyNet();
-
- return {
- httpServers,
- port: realPort,
- release,
- detachSafetyNet,
- nudgeSafetyNet,
- drainUpgradeSockets,
- };
-}
-
-// Plain static 404 for SPA-bundle / asset fall-throughs. Distinct from the
-// RFC 9457 problem+json envelope (`emitProblem`), which is reserved for the
-// `/api/*` surface: a missing `/assets/*.js` is a static miss, and emitting
-// the API error envelope there sent a real debugging session chasing a phantom
-// routing bug. Mirrors the asset-serve middleware's own fall-through 404
-// (empty body + nosniff).
-function notFoundStatic(res: ServerResponse): void {
- // Three-way guard mirrors `emitProblem` — a TCP RST can destroy the socket
- // before headers are sent (`headersSent` false but `destroyed` true).
- if (res.headersSent || res.writableEnded || res.destroyed) return;
- res.setHeader('X-Content-Type-Options', 'nosniff');
- // `no-store`: a 404 is heuristically cacheable (RFC 9111 §4.2.2), and a
- // cached miss on a bundle URL would re-create the blank screen during the
- // mid-rebuild window this fix targets. Matches the old `emitProblem` path.
- res.setHeader('Cache-Control', 'no-store');
- res.statusCode = 404;
- res.end();
-}
-
-/**
- * Result of port resolution. `fallbackToKernel` is true only when the port
- * came from `DEFAULT_UI_PORT` (i.e. no `--port` flag and no `PORT` env) —
- * operator-explicit ports never silently move on `EADDRINUSE`.
- */
-interface ResolvedRequestedPort {
- port: number;
- fallbackToKernel: boolean;
-}
-
-function resolveRequestedPort(
- optsPort: string | undefined,
- envPort: string | undefined,
-): ResolvedRequestedPort {
- if (optsPort !== undefined) {
- const parsed = Number.parseInt(optsPort, 10);
- if (Number.isNaN(parsed) || parsed < 0 || parsed > 65535) {
- throw new Error(`Invalid --port value '${optsPort}'`);
- }
- return { port: parsed, fallbackToKernel: false };
- }
- if (envPort !== undefined && envPort !== '') {
- const parsed = Number.parseInt(envPort, 10);
- if (Number.isNaN(parsed) || parsed < 0 || parsed > 65535) {
- throw new Error(`Invalid PORT env value '${envPort}'`);
- }
- return { port: parsed, fallbackToKernel: false };
- }
- // Default port `DEFAULT_UI_PORT` (39847) with bind-with-fallback to
- // kernel-allocation. Picked to be quirky and IANA-unassigned so the
- // common-case collision rate is ~zero; the bind layer falls back to
- // port 0 (kernel-allocated) when the default is busy, preserving the
- // multi-project bind guarantee against silent cross-family collisions.
- // MCP preview URLs dereference `ui.lock.port` so no client contract
- // breaks; the lock-collision proxy in this same file bridges a second
- // `ok ui` bound on a different port to whatever port the real UI holds.
- return { port: DEFAULT_UI_PORT, fallbackToKernel: true };
-}
-
-/**
- * Decide what to do when another `ok ui` already holds `ui.lock`.
- *
- * - Same requested port as the lock holder → "already running"; caller
- * logs and exits 0 (no proxy; duplicate attempt).
- * - Different requested port, lock port > 0 → reverse HTTP proxy on the
- * requested port forwarding to the lock holder.
- * - Different requested port, lock port == 0 → poll the lock for up to
- * `pollDeadlineMs` (default 2000); throw if still 0 at deadline.
- * - Lock disappears during resolution → throw so the caller can retry
- * acquiring cleanly.
- *
- * No side effects beyond starting the proxy server on the "proxy" branch.
- * Tests verify each branch directly without driving Commander.
- */
-type UiCollisionResult =
- | { mode: 'already-running'; port: number }
- | { mode: 'proxy'; handle: ProxyServerHandle; upstreamPort: number };
-
-interface ResolveUiLockCollisionOptions {
- requestedPort: number;
- host: string;
- lockDir: string;
- /** Override for tests. Defaults to `readUiLock` from the server package. */
- readLock?: () =>
- | import('@inkeep/open-knowledge-server').UiLockMetadata
- | null
- | Promise<import('@inkeep/open-knowledge-server').UiLockMetadata | null>;
- pollIntervalMs?: number;
- pollDeadlineMs?: number;
-}
-
-export async function resolveUiLockCollision(
- opts: ResolveUiLockCollisionOptions,
-): Promise<UiCollisionResult> {
- const readLock =
- opts.readLock ??
- (async () => {
- const { readUiLock } = await import('@inkeep/open-knowledge-server');
- return readUiLock(opts.lockDir);
- });
-
- const initial = await readLock();
- if (!initial) {
- throw new Error(
- 'UI lock collision reported but the lock disappeared before handling — retry acquiring.',
- );
- }
-
- if (initial.port === opts.requestedPort && initial.port > 0) {
- return { mode: 'already-running', port: initial.port };
- }
-
- let upstreamPort = initial.port;
- if (upstreamPort === 0) {
- const deadline = Date.now() + (opts.pollDeadlineMs ?? 2000);
- const intervalMs = opts.pollIntervalMs ?? 100;
- while (Date.now() < deadline) {
- await new Promise<void>((done) => {
- setTimeout(done, intervalMs);
- });
- const lock = await readLock();
- if (lock && lock.port > 0) {
- upstreamPort = lock.port;
- break;
- }
- }
- if (upstreamPort === 0) {
- throw new Error('UI did not bind within 2s; run `ok clean`');
- }
- if (upstreamPort === opts.requestedPort) {
- return { mode: 'already-running', port: upstreamPort };
- }
- }
-
- const handle = await startProxyServer({
- listenPort: opts.requestedPort,
- host: opts.host,
- upstreamHost: 'localhost',
- upstreamPort,
- });
- 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'));
- }
-}
-
-// Exported for tests.
-export { resolveRequestedPort };
-
-/**
- * "Non-interactive" gate for the `already-running` collision path. When the
- * caller has no TTY (e.g. spawned by a parent process) OR is invoked with a
- * `PORT` env, `process.exit(0)` is wrong — the preview
- * pane treats subprocess exit as "preview crashed" and tears down. Instead,
- * the action handler stays attached as a keepalive until SIGTERM.
- *
- * Interactive TTY callers still get a clean exit so they aren't stuck
- * staring at a hung command.
- *
- * Type-shaped against `NodeJS.Process` so tests can pass a minimal fake.
- */
-export function isNonInteractiveContext(proc: Pick<NodeJS.Process, 'stdout' | 'env'>): boolean {
- const hasTty = proc.stdout.isTTY === true;
- const hasPortEnv = typeof proc.env.PORT === 'string' && proc.env.PORT !== '';
- return !hasTty || hasPortEnv;
-}
diff --git a/packages/cli/src/loopback-bind-discipline.test.ts b/packages/cli/src/loopback-bind-discipline.test.ts
index fcf3c6258..e84808a39 100644
--- a/packages/cli/src/loopback-bind-discipline.test.ts
+++ b/packages/cli/src/loopback-bind-discipline.test.ts
@@ -134,8 +134,7 @@ describe('loopback bind discipline (cli test sources)', () => {
test('there are test files to scan (sanity)', () => {
expect(files.length).toBeGreaterThan(0);
- expect(files.some((f) => f.path.endsWith('commands/ui.test.ts'))).toBe(true);
- expect(files.some((f) => f.path.endsWith('commands/ui-proxy.test.ts'))).toBe(true);
+ expect(files.some((f) => f.path.endsWith('commands/start.test.ts'))).toBe(true);
});
test('every .listen( call binds an explicit loopback host literal', () => {
diff --git a/packages/cli/src/mcp/bridge-e2e.test.ts b/packages/cli/src/mcp/bridge-e2e.test.ts
index 1e45b0571..59c36a148 100644
--- a/packages/cli/src/mcp/bridge-e2e.test.ts
+++ b/packages/cli/src/mcp/bridge-e2e.test.ts
@@ -245,7 +245,7 @@ test('stdio shim forwards connectionId via x-ok-connection-id header through rea
// the same real-transport path carries client version metadata on
// every /mcp request, alongside the connection-id header.
expect(capturedVersionHeaders[0]).toEqual({
- protocol: '1',
+ protocol: '2',
runtime: RUNTIME_VERSION,
kind: 'mcp',
});
diff --git a/packages/cli/src/tsdown-bundle-coverage.test.ts b/packages/cli/src/tsdown-bundle-coverage.test.ts
index 95a3520bd..1e49ae134 100644
--- a/packages/cli/src/tsdown-bundle-coverage.test.ts
+++ b/packages/cli/src/tsdown-bundle-coverage.test.ts
@@ -137,3 +137,34 @@ describe('tsdown alwaysBundle covers the file-type transitive closure', () => {
});
}
});
+
+/**
+ * Server/core-inlined transitive deps that are NOT cli `package.json` deps but
+ * enter the bundle through the inlined `@inkeep/open-knowledge-server` / `-core`
+ * source. The declared-deps loop above cannot see them, so a
+ * reconcile-against-`package.json` pass could silently drop their `alwaysBundle`
+ * entry and crash a packaged DMG with ERR_MODULE_NOT_FOUND. Provenance:
+ * - `sirv` — server `boot.ts` react-shell mount (dropped from
+ * cli/package.json with the `--only ui` proxy; the others were always
+ * transitive)
+ * - `just-bash` — server `bash/index.ts`
+ * - `shell-quote` — server `bash/parse-command.ts`
+ * - `picomatch` — core `markdown/lint/applies-to.ts`
+ */
+describe('tsdown alwaysBundle covers server/core-inlined transitive deps', () => {
+ const serverInlinedClosure = ['sirv', 'just-bash', 'shell-quote', 'picomatch'];
+
+ for (const dep of serverInlinedClosure) {
+ test(`alwaysBundle covers transitive dep '${dep}'`, () => {
+ const escaped = dep.replace(/[\\^$*+?.()|[\]{}-]/g, '\\$&').replace(/\//g, '\\\\?/');
+ const pattern = new RegExp(`\\^${escaped}\\(`);
+ expect(
+ pattern.test(alwaysBundleBlock),
+ `Add /^${dep}(\\/|$)/ to packages/cli/tsdown.config.ts \`alwaysBundle\`. ` +
+ `It is a pure-JS transitive dep inlined via @inkeep/open-knowledge-server ` +
+ `/ -core (NOT a cli package.json dep); externalized, it leaves a bare ` +
+ `\`import '${dep}'\` that crashes the packaged app with ERR_MODULE_NOT_FOUND.`,
+ ).toBe(true);
+ });
+ }
+});
diff --git a/packages/cli/tests/integration/_helpers/lock-worker.ts b/packages/cli/tests/integration/_helpers/lock-worker.ts
index aa1c08a0b..781d22b99 100644
--- a/packages/cli/tests/integration/_helpers/lock-worker.ts
+++ b/packages/cli/tests/integration/_helpers/lock-worker.ts
@@ -3,44 +3,40 @@
* Lock-holder worker — used by `multi-project-locks.test.ts` to exercise
* cross-process lock isolation.
*
- * Acquires `<lockDir>/server.lock` AND `<lockDir>/ui.lock` with this worker's
- * own pid, advertises its (pid, server-port, ui-port) on stdout, then waits
- * for SIGTERM/SIGINT to release and exit cleanly.
+ * Acquires `<lockDir>/server.lock` with this worker's own pid, advertises its
+ * (pid, server-port) on stdout, then waits for SIGTERM/SIGINT to release and
+ * exit cleanly.
*
* Usage (invoked by the test, never directly):
- * bun run lock-worker.ts <lockDir> <serverPort> <uiPort>
+ * node --import tsx lock-worker.ts <lockDir> <serverPort>
*
* Output (one line, then waits):
- * READY {"pid":12345,"serverPort":52001,"uiPort":3001}
+ * READY {"pid":12345,"serverPort":52001}
*/
import { acquireProcessLock } from '@inkeep/open-knowledge-server';
-const [, , lockDirArg, serverPortArg, uiPortArg] = process.argv;
+const [, , lockDirArg, serverPortArg] = process.argv;
-if (!lockDirArg || !serverPortArg || !uiPortArg) {
+if (!lockDirArg || !serverPortArg) {
process.stderr.write(
- 'lock-worker: usage: bun run lock-worker.ts <lockDir> <serverPort> <uiPort>\n',
+ 'lock-worker: usage: node --import tsx lock-worker.ts <lockDir> <serverPort>\n',
);
process.exit(64); // EX_USAGE
}
const serverPort = Number.parseInt(serverPortArg, 10);
-const uiPort = Number.parseInt(uiPortArg, 10);
-if (!Number.isFinite(serverPort) || !Number.isFinite(uiPort)) {
- process.stderr.write(`lock-worker: invalid port arg(s): ${serverPortArg} ${uiPortArg}\n`);
+if (!Number.isFinite(serverPort)) {
+ process.stderr.write(`lock-worker: invalid port arg: ${serverPortArg}\n`);
process.exit(64);
}
-const metadata = { worktreeRoot: lockDirArg, startedAt: new Date().toISOString() };
+const metadata = { port: 0, worktreeRoot: lockDirArg, startedAt: new Date().toISOString() };
let serverHandle: ReturnType<typeof acquireProcessLock> | null = null;
-let uiHandle: ReturnType<typeof acquireProcessLock> | null = null;
try {
serverHandle = acquireProcessLock({ lockName: 'server', lockDir: lockDirArg, metadata });
- uiHandle = acquireProcessLock({ lockName: 'ui', lockDir: lockDirArg, metadata });
serverHandle.updatePort(serverPort);
- uiHandle.updatePort(uiPort);
} catch (err) {
process.stderr.write(
`lock-worker(${process.pid}): acquire failed: ${err instanceof Error ? err.message : String(err)}\n`,
@@ -48,10 +44,10 @@ try {
process.exit(1);
}
-// Print the READY line so the parent can correlate this worker's pid + ports
-// with the on-disk lock files. Flush stdout explicitly — Bun buffers by
-// default and the parent reads line-by-line.
-const ready = JSON.stringify({ pid: process.pid, serverPort, uiPort });
+// Print the READY line so the parent can correlate this worker's pid + port
+// with the on-disk lock file. Flush stdout explicitly — the parent reads
+// line-by-line.
+const ready = JSON.stringify({ pid: process.pid, serverPort });
process.stdout.write(`READY ${ready}\n`);
let shuttingDown = false;
@@ -63,11 +59,6 @@ function shutdown(signal: NodeJS.Signals): void {
} catch {
// best-effort
}
- try {
- uiHandle?.release();
- } catch {
- // best-effort
- }
// Use 0 (not 128 + signo) — the parent test treats clean exit as success.
process.exit(signal === 'SIGINT' ? 130 : 0);
}
@@ -75,7 +66,7 @@ function shutdown(signal: NodeJS.Signals): void {
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
-// Keep the event loop alive — without this, Bun would exit immediately
+// Keep the event loop alive — without this the process would exit immediately
// after the synchronous setup since there are no pending I/O callbacks.
const keepAlive = setInterval(() => {}, 1 << 30);
// Clear on shutdown via signal handlers; in clean exit path we never reach
diff --git a/packages/cli/tests/integration/multi-project-locks.test.ts b/packages/cli/tests/integration/multi-project-locks.test.ts
index 40c2fb910..cae87ef00 100644
--- a/packages/cli/tests/integration/multi-project-locks.test.ts
+++ b/packages/cli/tests/integration/multi-project-locks.test.ts
@@ -8,9 +8,8 @@
* these are real properties of the primitive even though same-pid
* acquires never trip the collision branch.
* 2. **Cross-process (real):** spawn N independent worker processes
- * (each with its OWN pid) holding their own server.lock + ui.lock.
- * configuration that exercises the live-foreign-pid collision path:
- * 5 concurrent spawns across 5 content dirs.
+ * (each with its OWN pid) holding their own server.lock. Exercises the
+ * live-foreign-pid collision path: concurrent spawns across content dirs.
*/
import { type ChildProcess, spawn as nativeSpawn } from 'node:child_process';
@@ -29,23 +28,19 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
interface ProjectHandles {
lockDir: string;
server: ProcessLockHandle;
- ui: ProcessLockHandle;
}
function makeProject(root: string, slug: string): ProjectHandles {
const lockDir = join(root, slug, '.ok', LOCAL_DIR);
mkdirSync(lockDir, { recursive: true });
- const metadata = { worktreeRoot: join(root, slug), startedAt: new Date().toISOString() };
+ const metadata = { port: 0, worktreeRoot: join(root, slug), startedAt: new Date().toISOString() };
const server = acquireProcessLock({ lockName: 'server', lockDir, metadata });
- const ui = acquireProcessLock({ lockName: 'ui', lockDir, metadata });
- // Simulate the real `listen()` port advertisement — ok start gets a kernel
- // port, ok ui default 3000 + offset so ports across projects don't collide
- // by coincidence.
+ // Simulate the real `listen()` port advertisement — a distinct port per
+ // project so ports across projects don't collide by coincidence.
const suffix = slug.slice(-1);
const num = Number.parseInt(suffix, 10);
server.updatePort(52000 + num);
- ui.updatePort(3000 + num);
- return { lockDir, server, ui };
+ return { lockDir, server };
}
describe('multi-project lock isolation (A1)', () => {
@@ -63,39 +58,34 @@ describe('multi-project lock isolation (A1)', () => {
rmSync(testRoot, { recursive: true, force: true });
});
- it('three concurrent projects produce six distinct live locks with unique ports', () => {
+ it('three concurrent projects produce three distinct live locks with unique ports', () => {
const p1 = makeProject(testRoot, 'project-1');
const p2 = makeProject(testRoot, 'project-2');
const p3 = makeProject(testRoot, 'project-3');
try {
- // All six lock files exist on disk
+ // All three lock files exist on disk
for (const p of [p1, p2, p3]) {
expect(existsSync(join(p.lockDir, 'server.lock'))).toBe(true);
- expect(existsSync(join(p.lockDir, 'ui.lock'))).toBe(true);
}
// Reads return the right project's metadata
const s1 = readProcessLock({ lockDir: p1.lockDir, lockName: 'server' });
const s2 = readProcessLock({ lockDir: p2.lockDir, lockName: 'server' });
const s3 = readProcessLock({ lockDir: p3.lockDir, lockName: 'server' });
- const u1 = readProcessLock({ lockDir: p1.lockDir, lockName: 'ui' });
- const u2 = readProcessLock({ lockDir: p2.lockDir, lockName: 'ui' });
- const u3 = readProcessLock({ lockDir: p3.lockDir, lockName: 'ui' });
- for (const lock of [s1, s2, s3, u1, u2, u3]) {
+ for (const lock of [s1, s2, s3]) {
expect(lock).not.toBeNull();
expect(lock?.pid).toBe(process.pid);
}
- // Ports are all distinct across the six locks
- const ports = [s1, s2, s3, u1, u2, u3].map((l) => l?.port ?? 0);
+ // Ports are all distinct across the three locks
+ const ports = [s1, s2, s3].map((l) => l?.port ?? 0);
const uniquePorts = new Set(ports);
- expect(uniquePorts.size).toBe(6);
+ expect(uniquePorts.size).toBe(3);
} finally {
for (const p of [p1, p2, p3]) {
p.server.release();
- p.ui.release();
}
}
});
@@ -106,21 +96,17 @@ describe('multi-project lock isolation (A1)', () => {
try {
p1.server.release();
- p1.ui.release();
expect(existsSync(join(p1.lockDir, 'server.lock'))).toBe(false);
- expect(existsSync(join(p1.lockDir, 'ui.lock'))).toBe(false);
// Project 2 unaffected
expect(existsSync(join(p2.lockDir, 'server.lock'))).toBe(true);
- expect(existsSync(join(p2.lockDir, 'ui.lock'))).toBe(true);
const s2 = readProcessLock({ lockDir: p2.lockDir, lockName: 'server' });
expect(s2?.pid).toBe(process.pid);
expect(s2?.port).toBeGreaterThan(0);
} finally {
p2.server.release();
- p2.ui.release();
}
});
@@ -133,21 +119,17 @@ describe('multi-project lock isolation (A1)', () => {
for (let round = 0; round < 3; round++) {
for (let i = 0; i < projects.length; i++) {
projects[i].server.updatePort(60000 + i * 10 + round);
- projects[i].ui.updatePort(40000 + i * 10 + round);
}
}
// Final port for each project should be its last write, not another's.
for (let i = 0; i < projects.length; i++) {
const s = readProcessLock({ lockDir: projects[i].lockDir, lockName: 'server' });
- const u = readProcessLock({ lockDir: projects[i].lockDir, lockName: 'ui' });
expect(s?.port).toBe(60000 + i * 10 + 2);
- expect(u?.port).toBe(40000 + i * 10 + 2);
}
} finally {
for (const p of projects) {
p.server.release();
- p.ui.release();
}
}
});
@@ -159,8 +141,8 @@ describe('multi-project lock isolation (A1)', () => {
const LOCK_WORKER_PATH = resolve(__dirname, '_helpers', 'lock-worker.ts');
// `node --import tsx` startup competes with the repository's fully parallel
-// package matrix. The isolated path is ~2s, but five seconds is below the
-// observed scheduler budget under that supported topology.
+// package matrix. The isolated path is ~2s, but the timeout below is generous
+// against the observed scheduler budget under that supported topology.
const WORKER_READY_TIMEOUT_MS = 20_000;
const WORKER_EXIT_TIMEOUT_MS = 3_000;
@@ -169,30 +151,24 @@ interface WorkerHandle {
pid: number;
lockDir: string;
serverPort: number;
- uiPort: number;
}
interface WorkerReadyPayload {
pid: number;
serverPort: number;
- uiPort: number;
}
/**
- * Spawn the lock-worker as a real node child process. The worker acquires both
- * locks for `lockDir`, prints a `READY {...}` line on stdout, then idles
+ * Spawn the lock-worker as a real node child process. The worker acquires the
+ * server.lock for `lockDir`, prints a `READY {...}` line on stdout, then idles
* waiting for SIGTERM. We resolve when the READY line lands, so the parent
* test sees a fully-acquired lock state before it asserts.
*/
-function spawnLockWorker(
- lockDir: string,
- serverPort: number,
- uiPort: number,
-): Promise<WorkerHandle> {
+function spawnLockWorker(lockDir: string, serverPort: number): Promise<WorkerHandle> {
return new Promise((resolveSpawn, reject) => {
const proc = nativeSpawn(
'node',
- ['--import', 'tsx', LOCK_WORKER_PATH, lockDir, String(serverPort), String(uiPort)],
+ ['--import', 'tsx', LOCK_WORKER_PATH, lockDir, String(serverPort)],
{ stdio: ['ignore', 'pipe', 'pipe'] },
);
if (proc.pid === undefined || !proc.stdout || !proc.stderr) {
@@ -224,7 +200,6 @@ function spawnLockWorker(
pid: payload.pid,
lockDir,
serverPort: payload.serverPort,
- uiPort: payload.uiPort,
});
} catch (err) {
clearTimeout(timeoutHandle);
@@ -289,8 +264,9 @@ function stopLockWorker(handle: WorkerHandle): Promise<void> {
});
}
-// Skip-on-CI gate (oven-sh/bun#11892): cross-process lock workers spawn `bun` children;
-// incomplete teardown on Linux GHA can keep the runner alive past `bun test` summary.
+// Skip-on-CI gate (oven-sh/bun#11892): cross-process lock workers spawn child
+// processes; incomplete teardown on Linux GHA can keep the runner alive past
+// the test summary.
(process.env.CI ? describe.skip : describe)(
'multi-project lock isolation — cross-process (A1)',
() => {
@@ -312,17 +288,15 @@ function stopLockWorker(handle: WorkerHandle): Promise<void> {
rmSync(testRoot, { recursive: true, force: true });
});
- it('three concurrent worker processes each hold their own server+ui locks (no cross-contamination)', async () => {
+ it('three concurrent worker processes each hold their own server lock (no cross-contamination)', async () => {
const lockDirs = [1, 2, 3].map((i) => {
const lockDir = join(testRoot, `project-${i}`, '.ok', LOCAL_DIR);
mkdirSync(lockDir, { recursive: true });
- return { i, lockDir, serverPort: 52100 + i, uiPort: 3100 + i };
+ return { i, lockDir, serverPort: 52100 + i };
});
const spawnResults = await Promise.allSettled(
- lockDirs.map(({ lockDir, serverPort, uiPort }) =>
- spawnLockWorker(lockDir, serverPort, uiPort),
- ),
+ lockDirs.map(({ lockDir, serverPort }) => spawnLockWorker(lockDir, serverPort)),
);
workers = spawnResults.flatMap((result) =>
result.status === 'fulfilled' ? [result.value] : [],
@@ -352,28 +326,23 @@ function stopLockWorker(handle: WorkerHandle): Promise<void> {
// lock during concurrent acquisition.
for (const w of workers) {
const serverLockPath = join(w.lockDir, 'server.lock');
- const uiLockPath = join(w.lockDir, 'ui.lock');
expect(existsSync(serverLockPath)).toBe(true);
- expect(existsSync(uiLockPath)).toBe(true);
const serverLock = JSON.parse(readFileSync(serverLockPath, 'utf-8'));
- const uiLock = JSON.parse(readFileSync(uiLockPath, 'utf-8'));
expect(serverLock.pid).toBe(w.pid);
expect(serverLock.port).toBe(w.serverPort);
- expect(uiLock.pid).toBe(w.pid);
- expect(uiLock.port).toBe(w.uiPort);
}
- // 6 distinct ports (3 server + 3 ui) — no collision across the fleet.
- const allPorts = workers.flatMap((w) => [w.serverPort, w.uiPort]);
- expect(new Set(allPorts).size).toBe(6);
+ // 3 distinct ports — no collision across the fleet.
+ const allPorts = workers.map((w) => w.serverPort);
+ expect(new Set(allPorts).size).toBe(3);
});
it('a fourth worker against an already-held lockDir collides on the live foreign pid (US-001 collision branch)', async () => {
const lockDir = join(testRoot, 'shared-project', '.ok', LOCAL_DIR);
mkdirSync(lockDir, { recursive: true });
- const holder = await spawnLockWorker(lockDir, 52200, 3200);
+ const holder = await spawnLockWorker(lockDir, 52200);
workers.push(holder);
// A second worker against the SAME lockDir must fail to acquire — the
@@ -381,7 +350,7 @@ function stopLockWorker(handle: WorkerHandle): Promise<void> {
// ProcessLockCollisionError. The worker exits non-zero; we await that.
const colliderProc = nativeSpawn(
'node',
- ['--import', 'tsx', LOCK_WORKER_PATH, lockDir, '52201', '3201'],
+ ['--import', 'tsx', LOCK_WORKER_PATH, lockDir, '52201'],
{
stdio: ['ignore', 'pipe', 'pipe'],
},
diff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.ts
index 0002b43b6..9960d2035 100644
--- a/packages/cli/tsdown.config.ts
+++ b/packages/cli/tsdown.config.ts
@@ -71,6 +71,11 @@ const alwaysBundlePureJsDeps = [
/^pino(\/|$)/,
/^shell-quote(\/|$)/,
/^simple-git(\/|$)/,
+ // sirv is inlined TRANSITIVELY via @inkeep/open-knowledge-server (boot.ts's
+ // react-shell mount) — it is NOT a cli package.json dep (dropped with the
+ // `--only ui` proxy). Do not remove this entry when reconciling `alwaysBundle`
+ // against cli deps; the server-inlined-closure guard in
+ // tsdown-bundle-coverage.test.ts pins it.
/^sirv(\/|$)/,
/^smol-toml(\/|$)/,
/^strtok3(\/|$)/,
diff --git a/packages/core/src/protocol-version.ts b/packages/core/src/protocol-version.ts
index 7f2db668c..c4f4c869c 100644
--- a/packages/core/src/protocol-version.ts
+++ b/packages/core/src/protocol-version.ts
@@ -15,4 +15,4 @@
* on). Additive-only changes (new optional fields, new endpoints, new WS frame
* types old readers can ignore) do NOT bump.
*/
-export const PROTOCOL_VERSION = 1 as const;
+export const PROTOCOL_VERSION = 2 as const;
diff --git a/packages/desktop/src/main/branch-info-proxy.test.ts b/packages/desktop/src/main/branch-info-proxy.test.ts
index 1abff1f0e..c50b890f2 100644
--- a/packages/desktop/src/main/branch-info-proxy.test.ts
+++ b/packages/desktop/src/main/branch-info-proxy.test.ts
@@ -202,7 +202,7 @@ describe('proxyFetchBranchInfo', () => {
{ projectPath: '/tmp/p', branch: 'main', kind: 'doc', path: 'a.md' },
buildDeps({ fetch: fetchMock }),
);
- expect(headerOf(seen, 'x-ok-client-protocol')).toBe('1');
+ expect(headerOf(seen, 'x-ok-client-protocol')).toBe('2');
expect(headerOf(seen, 'x-ok-client-kind')).toBe('desktop-main');
expect(headerOf(seen, 'x-ok-client-runtime')).toBe(RUNTIME_VERSION);
});
diff --git a/packages/desktop/src/utility/server-entry.ts b/packages/desktop/src/utility/server-entry.ts
index 488c79c51..a2dcd9c4a 100644
--- a/packages/desktop/src/utility/server-entry.ts
+++ b/packages/desktop/src/utility/server-entry.ts
@@ -441,11 +441,9 @@ export function setupUtility(deps: SetupUtilityDeps): UtilityHandle {
};
// Compare on `name` (not instanceof) because `bootServer` is
// dynamically imported and the class identity may differ across
- // module-realm boundaries. Includes `UiLockCollisionError` so a
- // standalone `ok ui` already serving the same project surfaces
- // the same lock-collision UX as `ServerLockCollisionError`.
+ // module-realm boundaries.
const errName = err && typeof err === 'object' ? (err as Error).name : '';
- if (errName === 'ServerLockCollisionError' || errName === 'UiLockCollisionError') {
+ if (errName === 'ServerLockCollisionError') {
const existing = (err as { existing?: UtilityErrorMessage['existingLock'] }).existing;
if (existing) {
errMsg.kind = 'lock-collision';
diff --git a/packages/server/src/asset-serve-middleware.ts b/packages/server/src/asset-serve-middleware.ts
index 181778885..1fba64a56 100644
--- a/packages/server/src/asset-serve-middleware.ts
+++ b/packages/server/src/asset-serve-middleware.ts
@@ -5,7 +5,7 @@
* Both surfaces consume this single implementation:
* - `bun run dev` Vite plugin (combines Vite + collab + asset serving
* on one port) — `packages/app/src/server/hocuspocus-plugin.ts`.
- * - `ok ui` production server — `packages/cli/src/commands/ui.ts`.
+ * - the single-listener `ok start` server — `packages/server/src/boot.ts`.
*
* Extracted as a pure factory so it can be unit-tested without spinning
* up an HTTP server. The consumer supplies the real `contentFilter` +
diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.ts
index e55ba0284..af72b9533 100644
--- a/packages/server/src/boot.test.ts
+++ b/packages/server/src/boot.test.ts
@@ -17,7 +17,7 @@ const describeEvenOnCI = _bunDescribe;
import { execFile } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
-import { hostname, tmpdir } from 'node:os';
+import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { promisify } from 'node:util';
import { emitToleranceFire, OK_DIR, resolveServerRuntimeConfig } from '@inkeep/open-knowledge-core';
@@ -358,16 +358,12 @@ describe('bootServer — idle-shutdown runs full destroy', () => {
});
});
-describe('bootServer — reactShellDistDir + ui.lock advertisement', () => {
- // `ui.lock` is treated as advertisement, NOT mutex. When --react-shell-dist-dir
- // is set, bootServer TRIES to write `ui.lock` so external agent-harness
- // preview-URL consumers can discover the bound port. If a live holder
- // already owns the lock (a co-existing `ok ui` sibling, a prior-session
- // detached server), we YIELD: their port is already a valid preview URL.
- // Stale locks (dead pid) are pruned automatically by acquireProcessLock.
- // Only the writer releases on destroy.
+describe('bootServer — reactShellDistDir + server.lock ui advertisement', () => {
+ // Single-listener topology: a server serving the React shell advertises it by
+ // stamping the `ui` capability into its own `server.lock` — there is no
+ // separate `ui.lock`. preview-URL consumers key off that capability.
- test('writes ui.lock with the bound port when --react-shell-dist-dir is set and no live holder exists', async () => {
+ test('server.lock advertises the ui capability when --react-shell-dist-dir is set', async () => {
const projectDir = mkdtempSync(resolve(tmpDir, 'fake-repo-shell-'));
await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
seedOkScaffold(projectDir);
@@ -388,67 +384,24 @@ describe('bootServer — reactShellDistDir + ui.lock advertisement', () => {
});
try {
await booted.ready;
- const uiLockPath = resolve(projectDir, '.ok', 'local', 'ui.lock');
- expect(existsSync(uiLockPath)).toBe(true);
- const raw = await import('node:fs/promises').then((m) => m.readFile(uiLockPath, 'utf-8'));
- const parsed = JSON.parse(raw) as { port: number; pid: number };
- expect(parsed.port).toBeGreaterThan(0);
+ const serverLockPath = resolve(projectDir, '.ok', 'local', 'server.lock');
+ const raw = await import('node:fs/promises').then((m) => m.readFile(serverLockPath, 'utf-8'));
+ const parsed = JSON.parse(raw) as { port: number; pid: number; capabilities?: string[] };
+ expect(parsed.capabilities).toContain('ui');
expect(parsed.port).toBe(booted.port);
expect(parsed.pid).toBe(process.pid);
+ // No separate ui.lock is written in single-listener topology.
+ expect(existsSync(resolve(projectDir, '.ok', 'local', 'ui.lock'))).toBe(false);
} finally {
await booted.destroy();
}
});
- test('does NOT write ui.lock when reactShellDistDir is omitted (CLI default)', async () => {
+ test('server.lock omits the ui capability when reactShellDistDir is absent (CLI default)', async () => {
const projectDir = mkdtempSync(resolve(tmpDir, 'fake-repo-no-shell-'));
await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
seedOkScaffold(projectDir);
- const booted = await bootServer({
- host: '127.0.0.1',
- config: TEST_CONFIG,
- contentDir: projectDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- });
- try {
- await booted.ready;
- const uiLockPath = resolve(projectDir, '.ok', 'local', 'ui.lock');
- expect(existsSync(uiLockPath)).toBe(false);
- } finally {
- await booted.destroy();
- }
- });
-
- test('yields to a live holder of ui.lock — no UiLockCollisionError, lock unchanged, boot succeeds', async () => {
- const projectDir = mkdtempSync(resolve(tmpDir, 'fake-repo-yield-'));
- await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
- seedOkScaffold(projectDir);
-
- const shellDistDir = mkdtempSync(resolve(tmpDir, 'fake-shell-dist-yield-'));
- writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');
-
- // Seed a ui.lock pointing at our parent shell's pid — a different live
- // process — to simulate a co-existing `ok ui` peer. process.ppid is
- // guaranteed alive while this test runs, and is NOT process.pid (which
- // would otherwise trigger acquireProcessLock's same-pid idempotent
- // rewrite path instead of the live-collision path).
- const lockDir = resolve(projectDir, '.ok', 'local');
- mkdirSync(lockDir, { recursive: true });
- const peerSnapshot = {
- pid: process.ppid,
- hostname: hostname(),
- port: 65432,
- startedAt: new Date().toISOString(),
- worktreeRoot: projectDir,
- protocolVersion: 1,
- runtimeVersion: '0.0.0-test-peer',
- };
- writeFileSync(resolve(lockDir, 'ui.lock'), JSON.stringify(peerSnapshot), 'utf-8');
-
const booted = await bootServer({
host: '127.0.0.1',
config: TEST_CONFIG,
@@ -458,153 +411,15 @@ describe('bootServer — reactShellDistDir + ui.lock advertisement', () => {
quiet: true,
gitEnabled: false,
idleShutdownMs: null,
- reactShellDistDir: shellDistDir,
});
try {
await booted.ready;
- expect(booted.port).toBeGreaterThan(0);
- // ui.lock was NOT overwritten — peer's advertisement survives.
- // (process-lock's same-pid idempotent rewrite would normally overwrite,
- // but the peer's startedAt and runtimeVersion are distinct sentinels
- // we can verify.)
- const stillRaw = await import('node:fs/promises').then((m) =>
- m.readFile(resolve(lockDir, 'ui.lock'), 'utf-8'),
- );
- const still = JSON.parse(stillRaw) as typeof peerSnapshot;
- expect(still.port).toBe(65432);
- expect(still.runtimeVersion).toBe('0.0.0-test-peer');
+ const serverLockPath = resolve(projectDir, '.ok', 'local', 'server.lock');
+ const raw = await import('node:fs/promises').then((m) => m.readFile(serverLockPath, 'utf-8'));
+ const parsed = JSON.parse(raw) as { capabilities?: string[] };
+ expect(parsed.capabilities ?? []).not.toContain('ui');
} finally {
await booted.destroy();
- // Yield-on-collision means bootServer must NOT release the peer's
- // ui.lock on destroy — the advertisement must survive past our quit.
- const lockStillExists = existsSync(resolve(lockDir, 'ui.lock'));
- expect(lockStillExists).toBe(true);
- }
- });
-
- test('prunes a stale ui.lock (dead pid) and writes its own', async () => {
- const projectDir = mkdtempSync(resolve(tmpDir, 'fake-repo-prune-'));
- await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
- seedOkScaffold(projectDir);
-
- const shellDistDir = mkdtempSync(resolve(tmpDir, 'fake-shell-dist-prune-'));
- writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');
-
- // Stale lock — spawn a throwaway child, await its exit, then reuse
- // its pid. Guarantees a structurally-dead pid by the time the test
- // reads it (Linux `pid_max` defaults to 4M so picking a literal like
- // 999999 isn't guaranteed dead, especially on long-running CI runners
- // with pid recycling). The kernel doesn't immediately recycle this
- // pid; isProcessAlive() returns false → acquireProcessLock prunes.
- const stalePid = await new Promise<number>((res, rej) => {
- const cp = execFile('true', (err) => {
- if (err) rej(err);
- else res(cp.pid ?? 0);
- });
- });
- expect(stalePid).toBeGreaterThan(0);
- const lockDir = resolve(projectDir, '.ok', 'local');
- mkdirSync(lockDir, { recursive: true });
- writeFileSync(
- resolve(lockDir, 'ui.lock'),
- JSON.stringify({
- pid: stalePid,
- hostname: hostname(),
- port: 11111,
- startedAt: new Date().toISOString(),
- worktreeRoot: projectDir,
- protocolVersion: 1,
- runtimeVersion: '0.0.0-stale',
- }),
- 'utf-8',
- );
-
- const booted = await bootServer({
- host: '127.0.0.1',
- config: TEST_CONFIG,
- projectDir,
- contentDir: projectDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- reactShellDistDir: shellDistDir,
- });
- try {
- await booted.ready;
- const raw = await import('node:fs/promises').then((m) =>
- m.readFile(resolve(lockDir, 'ui.lock'), 'utf-8'),
- );
- const parsed = JSON.parse(raw) as { pid: number; port: number };
- // Our pid replaced the stale entry.
- expect(parsed.pid).toBe(process.pid);
- expect(parsed.port).toBe(booted.port);
- } finally {
- await booted.destroy();
- // We owned the lock (acquired by replacing the stale entry), so destroy
- // releases our claim — but the file survives marked draining until the
- // process actually exits (unlink is deferred to the exit handler).
- const postDestroy = JSON.parse(
- await import('node:fs/promises').then((m) =>
- m.readFile(resolve(lockDir, 'ui.lock'), 'utf-8'),
- ),
- ) as { pid: number; draining?: boolean };
- expect(postDestroy.pid).toBe(process.pid);
- expect(postDestroy.draining).toBe(true);
- }
- });
-
- test('destroy() releases ui.lock so a later boot can advertise', async () => {
- const projectDir = mkdtempSync(resolve(tmpDir, 'fake-repo-release-'));
- await execFileAsync('git', ['init', '--initial-branch=main', projectDir]);
- seedOkScaffold(projectDir);
-
- const shellDistDir = mkdtempSync(resolve(tmpDir, 'fake-shell-dist-release-'));
- writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');
-
- const booted1 = await bootServer({
- host: '127.0.0.1',
- config: TEST_CONFIG,
- projectDir,
- contentDir: projectDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- reactShellDistDir: shellDistDir,
- });
- await booted1.ready;
- const uiLockPath = resolve(projectDir, '.ok', 'local', 'ui.lock');
- expect(existsSync(uiLockPath)).toBe(true);
- await booted1.destroy();
- // Draining until process exit — not unlinked at destroy time.
- const drained = JSON.parse(readFileSync(uiLockPath, 'utf-8')) as { draining?: boolean };
- expect(drained.draining).toBe(true);
-
- // A second boot for the same project acquires cleanly (same-pid
- // idempotent rewrite clears the draining flag).
- const booted2 = await bootServer({
- host: '127.0.0.1',
- config: TEST_CONFIG,
- projectDir,
- contentDir: projectDir,
- port: 0,
- quiet: true,
- gitEnabled: false,
- idleShutdownMs: null,
- reactShellDistDir: shellDistDir,
- });
- try {
- await booted2.ready;
- expect(existsSync(uiLockPath)).toBe(true);
- const reacquired = JSON.parse(readFileSync(uiLockPath, 'utf-8')) as {
- pid: number;
- draining?: boolean;
- };
- expect(reacquired.pid).toBe(process.pid);
- expect(reacquired.draining).toBeUndefined();
- } finally {
- await booted2.destroy();
}
});
});
@@ -718,18 +533,20 @@ describe('bootServer — reactShellDistDir end-to-end HTTP shape', () => {
expect(apiRes.status).toBe(404);
expect(apiRes.headers.get('content-type')).toBe('application/problem+json');
- // 6. ui.lock advertises the bound port — agent-harness preview-browser
- // flows read this file to find a clickable URL. Lock-write happens
- // AFTER listen() resolves, so the port stored is the actual port the
- // server is reachable on (no port=0 sentinel leaking to consumers).
- // Yield-to-live-holder semantics mean this assertion only holds when
- // no live peer was holding the lock — for a clean test environment
- // this is always true.
- const uiLockPath = resolve(projectDir, '.ok', 'local', 'ui.lock');
- expect(existsSync(uiLockPath)).toBe(true);
- const lockRaw = await import('node:fs/promises').then((m) => m.readFile(uiLockPath, 'utf-8'));
- const parsed = JSON.parse(lockRaw) as { port: number };
+ // 6. server.lock advertises the bound port + the `ui` capability —
+ // agent-harness preview-browser flows read this file to find a clickable
+ // URL. Lock-write happens AFTER listen() resolves, so the port stored is
+ // the actual port the server is reachable on (no port=0 sentinel leaking
+ // to consumers). Single-listener: the shell is served by this process, so
+ // its own server.lock is the advertisement — no separate ui.lock.
+ const serverLockPath = resolve(projectDir, '.ok', 'local', 'server.lock');
+ expect(existsSync(serverLockPath)).toBe(true);
+ const lockRaw = await import('node:fs/promises').then((m) =>
+ m.readFile(serverLockPath, 'utf-8'),
+ );
+ const parsed = JSON.parse(lockRaw) as { port: number; capabilities?: string[] };
expect(parsed.port).toBe(booted.port);
+ expect(parsed.capabilities).toContain('ui');
} finally {
await booted.destroy();
}
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 56606fda3..68aab7add 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -84,24 +84,6 @@ import {
initToleranceTelemetryWriter,
teardownToleranceTelemetryWriter,
} from './tolerance-telemetry-writer.ts';
-// `ui.lock` is advertisement, NOT mutex. When a process serves the React shell
-// for a contentDir, it tries to write `ui.lock` so external consumers (agent
-// harnesses opening a preview browser via `preview-url.ts`, MCP tools
-// surfacing a clickable URL) can discover the bound port. If a live holder
-// already owns the lock — a co-existing `ok ui` sibling, a prior-session
-// detached `ok start --react-shell-dist-dir` that survived a desktop quit —
-// we YIELD: their port is already reachable and serves the same React shell
-// against the same data backend, so the advertisement is already fulfilled.
-// Stale locks (dead pid) are pruned automatically by `acquireProcessLock`.
-// Only the writer releases on destroy — a desktop quit must not take down a
-// peer's advertisement. Ownership is tracked locally via `ownsUiLock` below.
-import {
- acquireUiLock,
- markUiLockDraining,
- releaseUiLock,
- UiLockCollisionError,
- updateUiLockPort,
-} from './ui-lock.ts';
/**
* Names of per-machine runtime files that pre-date the `.ok/local/` move.
@@ -803,9 +785,9 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
authStreamHeartbeatMs: opts.authStreamHeartbeatMs,
onAgentWrite: opts.onAgentWrite,
lockKind,
- // `"ui"` iff THIS process serves the React shell — the accuracy contract
- // that lets `preview_url` distinguish "no UI mounted" (an API-only
- // profile) from "UI served by a sibling" (which advertises via ui.lock).
+ // `"ui"` iff THIS process serves the React shell — the single-listener
+ // advertisement `preview_url` and the clone→open redirect read to
+ // distinguish a UI-serving server from an API-only (`--only server`) one.
capabilities: opts.reactShellDistDir ? ['http', 'ws', 'ui'] : ['http', 'ws'],
skipStateManifestCheck: opts.skipStateManifestCheck,
detectGh: opts.detectGh,
@@ -849,7 +831,7 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
// This is NOT where user-facing "issued" links come from, so keeping it
// loopback does not regress preview/share URLs: `preview_url` and the
// per-response `previewUrl` route resolve their browser base from
- // `server.lock` / `ui.lock` (this same listener origin by the one-URL
+ // `server.lock` (this same listener origin by the one-URL
// contract below, never from this value), and `share_link` builds its public
// `https://openknowledge.ai/d/...` URL from the git remote. `externalUrl`
// still governs ingress admission (CORS/Host) via `ingressPolicy`; it just
@@ -904,55 +886,6 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
})
: undefined;
- // When serving the React shell, try to advertise via `ui.lock` so external
- // preview-URL consumers find our port. If a live holder already owns the
- // lock (a co-existing `ok ui` sibling, a prior-session orphan), we yield
- // and proceed without owning the lock — their port already satisfies the
- // discovery contract. Stale-lock pruning is automatic inside
- // `acquireProcessLock`; we only catch the live-collision case here.
- let ownsUiLock = false;
- if (opts.reactShellDistDir) {
- try {
- acquireUiLock(lockDir, {
- port: 0,
- worktreeRoot: opts.projectDir ?? opts.contentDir,
- });
- ownsUiLock = true;
- } catch (err) {
- if (err instanceof UiLockCollisionError) {
- // Co-exist with the live holder. Their advertisement is sufficient
- // for agent harness preview-browser flows. Logged at info so
- // operators can grep for the yield in the wild without confusion.
- // `pid` is THIS server's pid (the yielder); `existingPid` is the
- // peer holding the lock — operators need both for incident
- // correlation when one of them later misbehaves.
- log.info(
- {
- event: 'ui-lock-yielded-to-live-holder',
- pid: process.pid,
- existingPid: err.existing.pid,
- existingPort: err.existing.port,
- lockDir,
- },
- 'ui.lock already held by a live process — yielding (advertisement is fulfilled)',
- );
- } else {
- // Any other failure (filesystem, permissions, corrupt-and-unrecoverable
- // lock) — surface it; the React shell would still serve, but losing
- // the discovery channel silently is the worse failure mode.
- await destroyHocuspocus().catch(() => {
- /* best-effort — surface the original error */
- });
- // Boot failed but this process may keep living (Electron utility
- // surfaces the error over IPC). destroyHocuspocus defers its unlink
- // to process exit, which would strand a live-pid draining lock that
- // blocks every future start — release it for real here.
- releaseServerLock(lockDir);
- throw err;
- }
- }
- }
-
// React-shell serving — the default for plain `ok start`, and the Electron
// utility path.
// - `single: true` — SPA fallback to `index.html` for unknown routes
@@ -1139,20 +1072,13 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
const listenAddresses = [...new Set(effectiveBindAddresses)];
const primaryAddress = listenAddresses[0];
const cleanupAfterListenFailure = async (): Promise<void> => {
- // Listen failed after locks were acquired. Release ui.lock only if we
- // own it (we yielded to a live holder, that holder keeps advertising);
- // destroyHocuspocus releases server.lock either way.
- if (ownsUiLock) {
- try {
- releaseUiLock(lockDir);
- } catch (releaseErr) {
- log.warn({ err: releaseErr }, 'releaseUiLock failed during listen-error cleanup');
- }
- }
+ // Listen failed after the server.lock was acquired; destroyHocuspocus
+ // releases it (immediately, below, since the process may keep living
+ // after a failed boot).
await destroyHocuspocus().catch((teardownErr) => {
// Best-effort — the original listen error is what we ultimately throw,
// but a teardown failure here can strand resources, so record it rather
- // than swallow it silently (mirrors the releaseUiLock warn above).
+ // than swallow it silently.
log.warn({ err: teardownErr }, 'destroyHocuspocus failed during listen-error cleanup');
});
// The process may keep living after a failed boot, so the
@@ -1239,12 +1165,6 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
// the self-call base structurally identical rather than two literals in sync.
const boundBaseUrl = internalBaseUrl();
updateServerLockPort(lockDir, realPort, boundBaseUrl);
- if (ownsUiLock) {
- // Flip the sentinel port=0 to the bound port so preview-URL consumers see
- // a reachable URL. Only writes if we still own the lock (paranoia in
- // case an out-of-band release happened between acquire and listen).
- updateUiLockPort(lockDir, realPort, boundBaseUrl);
- }
let destroyed = false;
const withDestroyTimeout = async (name: string, work: () => Promise<void>): Promise<void> => {
@@ -1286,9 +1206,8 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
// draining mark. Idempotent with the mark inside `destroyHocuspocus`.
try {
markServerLockDraining(lockDir);
- if (ownsUiLock) markUiLockDraining(lockDir);
} catch (err) {
- log.warn({ err, step: 'markLocksDraining' }, 'bootServer destroy step failed');
+ log.warn({ err, step: 'markServerLockDraining' }, 'bootServer destroy step failed');
}
try {
@@ -1351,16 +1270,6 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
}),
);
await runStep('destroyHocuspocus', () => destroyHocuspocus());
- if (ownsUiLock) {
- // Release ONLY if we own it. If we yielded at boot to a live holder,
- // that holder's advertisement must survive our destroy — taking down
- // ui.lock on quit-without-ownership would silently break their
- // preview-URL discovery. Unlink deferred to process exit for the same
- // reason as server.lock: lock-gone must mean process-gone.
- await runStep('releaseUiLock', async () =>
- releaseUiLock(lockDir, { deferUnlinkToExit: true }),
- );
- }
// Flush pending spans/metrics so the teardown sequence itself is
// observable. shutdownTelemetry is idempotent and has its own timeout.
await runStep('shutdownTelemetry', () => shutdownTelemetry());
diff --git a/packages/server/src/config/paths.ts b/packages/server/src/config/paths.ts
index 6a7da5e97..9f28393b4 100644
--- a/packages/server/src/config/paths.ts
+++ b/packages/server/src/config/paths.ts
@@ -27,12 +27,12 @@ export function resolveContentDir(config: Config, cwd: string): string {
* writes `<projectDir>/.ok/local/server.lock` regardless of whether
* `content.dir` is `.` or a sub-folder (the git-root-promotion case where
* one repo presents one `.ok/`). CLI commands that read the lock
- * (`ok stop`, `ok status`, `ok mcp`, `ok ui`, `ok clean`, `ok sync`) and
- * MCP tool handlers must call `getLocalDir(projectDir)` — anchoring on
- * contentDir would look in the wrong tree when `content.dir != '.'`.
+ * (`ok stop`, `ok status`, `ok mcp`, `ok clean`, `ok sync`) and MCP tool
+ * handlers must call `getLocalDir(projectDir)` — anchoring on contentDir
+ * would look in the wrong tree when `content.dir != '.'`.
*
* Single resolution helper for every server-side site that builds
- * `resolve(projectDir, '.ok')` inline. Routes for `server.lock`, `ui.lock`,
+ * `resolve(projectDir, '.ok')` inline. Routes for `server.lock`,
* `state.json`, `principal.json`, `sync-state.json`, `conflicts.json`,
* `last-spawn-error.log`, `cache/<branch>/...`, and `tmp/upload-<uuid>` all
* resolve under here.
diff --git a/packages/server/src/desktop-attach-contract.test.ts b/packages/server/src/desktop-attach-contract.test.ts
index 8f48a7839..0bca64c5f 100644
--- a/packages/server/src/desktop-attach-contract.test.ts
+++ b/packages/server/src/desktop-attach-contract.test.ts
@@ -1,155 +1,60 @@
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
-import { hostname, tmpdir } from 'node:os';
+import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
-import { describe, expect, test, vi } from 'vitest';
+import { describe, expect, test } 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';
+import {
+ acquireServerLock,
+ readServerLock,
+ releaseServerLock,
+ updateServerLockPort,
+} from './server-lock.ts';
/**
- * The Claude Desktop attach contract, as it exists today. Sandboxed agent
- * panes (Claude Desktop's embedded browser) cannot be handed an arbitrary
- * URL out of band — they attach by asking the stdio MCP for a preview URL,
- * and that answer is derived entirely from `ui.lock`:
+ * The Claude Desktop attach contract. Sandboxed agent panes (Claude Desktop's
+ * embedded browser) cannot be handed an arbitrary URL out of band — they
+ * attach by asking the stdio MCP for a preview URL, and that answer is derived
+ * from `server.lock`: a shell-serving server advertises ONE record — its `url`
+ * plus `capabilities` containing `"ui"`, dialed directly. (The retired
+ * sibling `ui.lock` and its yield-to-live-holder flow are gone; the single
+ * listener serves every surface — `/`, `/api/*`, `/mcp`, `/collab` — at that
+ * one origin.)
*
- * <projectDir>/.ok/local/ui.lock → http://localhost:<ui.lock.port>
+ * The contract the readers (preview-url tools, `off-cwd-resolver`, the
+ * clone→open redirect) rely on:
*
- * The contract the remaining readers (preview-url tools, the `--only ui`
- * split-mode collision resolver, `off-cwd-resolver`) rely on:
- *
- * 1. FIELDS — every real lock carries pid, hostname, port, startedAt,
- * worktreeRoot, protocolVersion, runtimeVersion. The optional
- * kind/parentPid/capabilities fields are NOT written by today's
- * writers; nothing may start requiring them without changing writers.
+ * 1. ADVERTISEMENT — a shell-serving server.lock carries `url` +
+ * `capabilities` containing `"ui"`, and that url serves the SPA shell.
* 2. PORT SENTINEL — the lock exists with port 0 from acquire (pre-listen)
- * until updateUiLockPort stamps the bound port. Readers must treat
+ * until updateServerLockPort stamps the bound port. Readers must treat
* port 0 as "starting" (poll), never as an address.
- * 3. YIELD — a booting server that finds a live holder does not collide:
- * it proceeds without owning the lock, leaves the peer's advertisement
- * untouched (including on its own destroy), and emits a structured
- * yield event.
- * 4. DISCOVERY HINT — a data server not serving the shell tells humans in
- * its 404 body how to get the editor (restart with plain `ok start`).
- *
- * The ui.lock removal wave must keep (or deliberately re-pin) all four
- * observable behaviors and migrate every remaining reader in the same
- * release: the preview-pane flow is downstream of `ui.lock` until then, not
- * of which process serves the shell.
+ * 3. DISCOVERY HINT — a data server not serving the shell (no `ui`
+ * capability) tells humans in its 404 body how to get the editor
+ * (restart with plain `ok start`).
*/
-describe('ui.lock — the Desktop attach advertisement', () => {
- test('the real writer advertises exactly the documented field set', async () => {
- const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-fields-'));
- 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;
- const raw = readFileSync(resolve(projectDir, '.ok', 'local', 'ui.lock'), 'utf-8');
- const lock = JSON.parse(raw) as Record<string, unknown>;
-
- expect(lock.pid).toBe(process.pid);
- expect(lock.port).toBe(booted.port);
- expect(lock.hostname).toBe(hostname());
- expect(typeof lock.startedAt).toBe('string');
- expect(Number.isNaN(Date.parse(lock.startedAt as string))).toBe(false);
- expect(lock.worktreeRoot).toBe(projectDir);
- expect(typeof lock.protocolVersion).toBe('number');
- expect(typeof lock.runtimeVersion).toBe('string');
-
- // Optional fields the writers do not populate today. A reader that
- // starts gating on these (e.g. a desktop attach check on `kind`)
- // would silently reject every real lock.
- expect('kind' in lock).toBe(false);
- expect('parentPid' in lock).toBe(false);
- expect('capabilities' in lock).toBe(false);
- } finally {
- await booted.destroy();
- }
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- }, 30_000);
-
- test('port sentinel: acquire writes 0, updateUiLockPort stamps the bound port, release unlinks', async () => {
+describe('server.lock — the Desktop attach advertisement', () => {
+ test('port sentinel: acquire writes 0, updateServerLockPort stamps the bound port, release unlinks', async () => {
const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-sentinel-'));
try {
const lockDir = resolve(tmp, '.ok', 'local');
mkdirSync(lockDir, { recursive: true });
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmp });
- expect(readUiLock(lockDir)?.port).toBe(0);
+ acquireServerLock(lockDir, { port: 0, worktreeRoot: tmp });
+ expect(readServerLock(lockDir)?.port).toBe(0);
- updateUiLockPort(lockDir, 24_680);
- expect(readUiLock(lockDir)?.port).toBe(24_680);
+ updateServerLockPort(lockDir, 24_680);
+ expect(readServerLock(lockDir)?.port).toBe(24_680);
- releaseUiLock(lockDir);
- expect(readUiLock(lockDir)).toBeNull();
+ releaseServerLock(lockDir);
+ expect(readServerLock(lockDir)).toBeNull();
} finally {
await rm(tmp, { recursive: true, force: true });
}
});
- test('yield-to-live-holder emits the structured event operators grep for', async () => {
- const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-yield-'));
- try {
- const projectDir = mkdtempSync(resolve(tmp, 'proj-'));
- const shellDistDir = mkdtempSync(resolve(tmp, 'dist-'));
- writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');
-
- // A live peer: process.ppid is alive for the duration of the test and
- // is not process.pid (which would take the same-pid rewrite path).
- const lockDir = resolve(projectDir, '.ok', 'local');
- mkdirSync(lockDir, { recursive: true });
- writeFileSync(
- resolve(lockDir, 'ui.lock'),
- JSON.stringify({
- pid: process.ppid,
- hostname: hostname(),
- port: 65_432,
- startedAt: new Date().toISOString(),
- worktreeRoot: projectDir,
- protocolVersion: 1,
- runtimeVersion: '0.0.0-test-peer',
- }),
- 'utf-8',
- );
-
- const calls: Array<Record<string, unknown>> = [];
- const capture = (obj: unknown) => {
- if (typeof obj === 'object' && obj !== null) calls.push(obj as Record<string, unknown>);
- };
- const log = {
- info: vi.fn(capture),
- warn: vi.fn(capture),
- error: vi.fn(capture),
- debug: vi.fn(capture),
- child: () => log,
- };
-
- const booted = await bootCompositionRig(projectDir, {
- reactShellDistDir: shellDistDir,
- log: log as never,
- });
- try {
- await booted.ready;
- const yielded = calls.find((c) => c.event === 'ui-lock-yielded-to-live-holder');
- expect(yielded).toBeDefined();
- expect(yielded?.existingPid).toBe(process.ppid);
- expect(yielded?.existingPort).toBe(65_432);
- } finally {
- await booted.destroy();
- }
- } finally {
- await rm(tmp, { recursive: true, force: true });
- }
- }, 30_000);
-
- test('a data server without the shell 404s with the no-UI restart hint', async () => {
+ test('a data server without the shell 404s with the no-UI restart hint and omits the ui capability', async () => {
const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-hint-'));
try {
const booted = await bootCompositionRig(tmp);
@@ -160,6 +65,10 @@ describe('ui.lock — the Desktop attach advertisement', () => {
const body = parseProblem(await res.text());
expect(body.detail).toContain('running without the web UI');
expect(body.detail).toContain('ok start');
+ // No shell served → server.lock advertises no `ui` capability (and no
+ // separate ui.lock is ever written).
+ const lock = readServerLock(resolve(tmp, '.ok', 'local'));
+ expect(lock?.capabilities ?? []).not.toContain('ui');
expect(existsSync(resolve(tmp, '.ok', 'local', 'ui.lock'))).toBe(false);
} finally {
await booted.destroy();
@@ -171,14 +80,11 @@ describe('ui.lock — the Desktop attach advertisement', () => {
});
/**
- * 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.
+ * The canonical attach contract: 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.
*/
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 () => {
diff --git a/packages/server/src/ensure-single-file-session.ts b/packages/server/src/ensure-single-file-session.ts
index 9ba8a1001..b1a0adf78 100644
--- a/packages/server/src/ensure-single-file-session.ts
+++ b/packages/server/src/ensure-single-file-session.ts
@@ -3,8 +3,8 @@
*
* When the MCP `preview_url` file branch finds no running session serving a
* loose file, it calls `ensureSingleFileSession` to start one and wait until it
- * registers (writes a discoverable `ui.lock`), so the caller can then resolve
- * its URL via off-cwd discovery.
+ * registers (writes a discoverable `server.lock`), so the caller can then
+ * resolve its URL via off-cwd discovery.
*
* Lifecycle: the session runs in a DETACHED `ok <file>` subprocess (headless,
* `OK_SINGLE_FILE_NO_OPEN=1`) — NOT inside this MCP process — so it survives the
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index b915fe241..a0eb77175 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -472,6 +472,7 @@ export { serializeError } from './serialize-error.ts';
export { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';
export {
acquireServerLock,
+ lockAdvertisesUi,
markServerLockDraining,
readServerLock,
releaseServerLock,
@@ -626,12 +627,4 @@ export {
teardownToleranceTelemetryWriter,
} from './tolerance-telemetry-writer.ts';
export { trustSystemCertificates } from './trust-system-ca.ts';
-export {
- acquireUiLock,
- readUiLock,
- releaseUiLock,
- UiLockCollisionError,
- type UiLockMetadata,
- updateUiLockPort,
-} from './ui-lock.ts';
export { PROTOCOL_VERSION, RUNTIME_VERSION, STATE_SCHEMA_VERSION } from './version-constants.ts';
diff --git a/packages/server/src/init-project.ts b/packages/server/src/init-project.ts
index 0d4dc3a33..ae77460cc 100644
--- a/packages/server/src/init-project.ts
+++ b/packages/server/src/init-project.ts
@@ -256,7 +256,6 @@ worktrees/
principal.json
state.json
server.lock
-ui.lock
sync-state.json
last-spawn-error.log
`;
diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.ts
index e1152c82b..b447afe83 100644
--- a/packages/server/src/mcp-mount.ts
+++ b/packages/server/src/mcp-mount.ts
@@ -187,7 +187,7 @@ export interface MountMcpAndApiHandle {
* runtimes (notably the packaged Electron/Node build), so without this drain
* a single live `/collab` or `/collab/keepalive` client stalls both close
* steps for the full destroy-step timeout each. Mirrors the upgrade-socket
- * drain in `cli/src/commands/ui.ts` / `ui-proxy.ts`.
+ * drain in the server's own `bootServer` destroy sequence.
*/
shutdown: () => Promise<void>;
}
@@ -410,8 +410,7 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandl
// `<contentDir>/assets/` — `js`/`css` aren't asset extensions so they
// already fall through, which is why only fonts/images regressed. Try the
// shell first for this prefix; fall through to the content middleware on a
- // miss so user uploads at `<contentDir>/assets/*` still serve. Mirrors
- // the split-mode UI proxy's `/assets/`-first branch in `commands/ui.ts`.
+ // miss so user uploads at `<contentDir>/assets/*` still serve.
//
// `/excalidraw-assets/` carries the vendored Excalidraw font tree from
// `packages/app/scripts/copy-excalidraw-assets.mjs`, which the editor
diff --git a/packages/server/src/mcp/tools/exec.test.ts b/packages/server/src/mcp/tools/exec.test.ts
index 1d730f95a..5580090e8 100644
--- a/packages/server/src/mcp/tools/exec.test.ts
+++ b/packages/server/src/mcp/tools/exec.test.ts
@@ -16,7 +16,7 @@ import {
RESULT_BODY_BUDGET_BYTES,
WIRE_BODY_COPIES,
} from './exec.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
+import { bindTestUiServerLock } from './preview-url-test-helpers.ts';
describe('exec DESCRIPTION — STOP-rule anchoring (SPEC 2026-04-22 FR4 / US-007 / QA-009)', () => {
test('total length fits Claude per-tool 2 KB cap', () => {
@@ -676,7 +676,7 @@ describe('exec — per-row route-only previewUrl (FR-2.2)', () => {
const project = await bootstrap();
// Bind the UI lock so the resolver treats the route as reachable; the
// resolved previewUrl is route-only and carries no host:port.
- bindTestUiLock(project);
+ bindTestUiServerLock(project);
const contentDir = resolve(project, 'articles');
mkdirSync(contentDir, { recursive: true });
writeFileSync(resolve(contentDir, 'auth.md'), '---\ntitle: Auth\n---\nBody');
diff --git a/packages/server/src/mcp/tools/get-preview-url.test.ts b/packages/server/src/mcp/tools/get-preview-url.test.ts
index 51c28911e..9eaf03edc 100644
--- a/packages/server/src/mcp/tools/get-preview-url.test.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.test.ts
@@ -3,11 +3,11 @@
*
* `preview_url` is the one tool that hands an agent the browser-reachable
* preview URL — per-response `previewUrl` fields are route-only. Branches:
- * - UI running (`ui.lock` bound) → composed full URL.
+ * - UI running (ui-capable `server.lock` bound) → composed full URL.
* - No UI + registration has server authority → backend demand-ensure
- * (auto-spawn via the `serverUrl` resolver), bounded `ui.lock` wait.
+ * (auto-spawn via the `serverUrl` resolver), bounded UI-bind wait.
* - Still no UI → `{ url: null, running: false }` + a state-accurate
- * recovery hint (`ok start` vs `ok ui` by `server.lock` liveness).
+ * recovery hint keyed on `server.lock` liveness + ui capability.
*/
import { mkdtempSync } from 'node:fs';
@@ -15,10 +15,12 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
import { AutoStartDisabledError } from '../../autostart.ts';
+import { resolveLockDir } from '../../config/paths.ts';
import { type Config, ConfigSchema } from '../../config/schema.ts';
import type { OffCwdResolverDeps } from '../../off-cwd-resolver.ts';
+import { markServerLockDraining } from '../../server-lock.ts';
import { register } from './get-preview-url.ts';
-import { bindTestServerLock, bindTestUiLock } from './preview-url-test-helpers.ts';
+import { bindTestServerLock, bindTestUiServerLock } from './preview-url-test-helpers.ts';
import type { ServerInstance } from './shared.ts';
const BASE_CONFIG: Config = ConfigSchema.parse({});
@@ -75,7 +77,7 @@ function captureRegistration(
describe('preview_url tool — UI running', () => {
test('with document: composes baseUrl + the doc route', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.isError).toBeUndefined();
@@ -88,7 +90,7 @@ describe('preview_url tool — UI running', () => {
test('with folder: composes the folder route with a trailing slash', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ folder: 'specs/foo' });
expect(result.structuredContent?.url).toBe(`${uiBase}/#/specs/foo/`);
@@ -96,7 +98,7 @@ describe('preview_url tool — UI running', () => {
test('folder route tolerates surrounding slashes and per-segment encodes', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ folder: '/My Notes/sub/' });
expect(result.structuredContent?.url).toBe(`${uiBase}/#/My%20Notes/sub/`);
@@ -105,7 +107,7 @@ describe('preview_url tool — UI running', () => {
describe('isHostedAgent steer (desktop terminal or in-app agent panel)', () => {
test('document: response leads with `ok open <doc>` and tells the agent not to navigate the URL', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ document: 'specs/foo/SPEC' });
const text = result.content[0]?.text ?? '';
@@ -122,7 +124,7 @@ describe('preview_url tool — UI running', () => {
// close it explicitly.
test('document: steer tells the agent not to paste the URL into its reply', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.content[0]?.text ?? '').toContain('paste the URL into your reply');
@@ -130,7 +132,7 @@ describe('preview_url tool — UI running', () => {
test('folder: steers to `ok open <folder>`', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ folder: 'specs/foo' });
expect(result.content[0]?.text ?? '').toContain('ok open specs/foo');
@@ -139,7 +141,7 @@ describe('preview_url tool — UI running', () => {
test('skill default scope (project): steers to `ok open <name> --skill` (no --scope)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ skill: { name: 'trip-log' } });
expect(result.content[0]?.text ?? '').toContain('ok open trip-log --skill');
@@ -149,7 +151,7 @@ describe('preview_url tool — UI running', () => {
test('skill --scope global: steers to `ok open <name> --skill --scope global`', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ skill: { name: 'trip-log', scope: 'global' } });
expect(result.content[0]?.text ?? '').toContain('ok open trip-log --skill --scope global');
@@ -160,7 +162,7 @@ describe('preview_url tool — UI running', () => {
test('no target (root): no steer — nothing to `ok open`', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({});
expect(result.content[0]?.text ?? '').not.toContain('ok open');
@@ -168,7 +170,7 @@ describe('preview_url tool — UI running', () => {
test('NOT a hosted agent (default): no steer — plain Preview URL', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.content[0]?.text ?? '').not.toContain('ok open');
@@ -178,7 +180,7 @@ describe('preview_url tool — UI running', () => {
test('hosted agent + no UI running: steer + okOpenCommand still fire (ok open does not need the UI)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- // No bindTestUiLock / bindTestServerLock — nothing is running.
+ // No bindTestUiServerLock / bindTestServerLock — nothing is running.
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.structuredContent?.running).toBe(false);
@@ -191,7 +193,7 @@ describe('preview_url tool — UI running', () => {
test('document with a space: okOpenCommand shell-quotes the path', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ document: 'notes/My Doc' });
expect(result.structuredContent?.okOpenCommand).toBe("ok open 'notes/My Doc'");
@@ -199,7 +201,7 @@ describe('preview_url tool — UI running', () => {
test('document with an embedded single quote: okOpenCommand POSIX-escapes it', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ document: "Q&A/what's new" });
// POSIX single-quote escape: close-quote, escaped-quote, reopen → '\''
@@ -208,7 +210,7 @@ describe('preview_url tool — UI running', () => {
test('hosted agent + no UI + folder: okOpenCommand still fires', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- // No bindTestUiLock — nothing running.
+ // No bindTestUiServerLock — nothing running.
const handler = captureRegistration(cwd, BASE_CONFIG, { isHostedAgent: true });
const result = await handler({ folder: 'specs/foo' });
expect(result.structuredContent?.running).toBe(false);
@@ -218,7 +220,7 @@ describe('preview_url tool — UI running', () => {
test('docName + folder together is rejected (mutually exclusive)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ document: 'specs/foo/SPEC', folder: 'specs/foo' });
expect(result.isError).toBe(true);
@@ -227,7 +229,7 @@ describe('preview_url tool — UI running', () => {
test('without docName: returns the UI root URL', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({});
expect(result.isError).toBeUndefined();
@@ -239,7 +241,7 @@ describe('preview_url tool — UI running', () => {
test('per-segment encodes docName when composing the URL', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ document: 'notes/My Doc' });
expect(result.structuredContent?.url).toBe(`${uiBase}/#/notes/My%20Doc`);
@@ -249,7 +251,7 @@ describe('preview_url tool — UI running', () => {
describe('preview_url tool — skill target', () => {
test('with skill: composes the __skill__ route (default project scope)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ skill: { name: 'trip-log' } });
expect(result.structuredContent?.url).toBe(`${uiBase}/#/__skill__/project/trip-log`);
@@ -257,7 +259,7 @@ describe('preview_url tool — skill target', () => {
test('with skill + explicit global scope and a spaced name', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ skill: { name: 'run tests', scope: 'global' } });
expect(result.structuredContent?.url).toBe(`${uiBase}/#/__skill__/global/run%20tests`);
@@ -265,7 +267,7 @@ describe('preview_url tool — skill target', () => {
test('skill + document together is rejected (mutually exclusive)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd);
const result = await handler({ skill: { name: 'trip-log' }, document: 'specs/foo/SPEC' });
expect(result.isError).toBe(true);
@@ -298,9 +300,16 @@ describe('preview_url tool — no UI running', () => {
expect(result.structuredContent?.autoOpen).toBe(true);
});
- test('server alive but no UI: transient retry hint, no spawn advice', async () => {
+ test('draining ui-capable server: transient retry hint, no spawn advice', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestServerLock(cwd);
+ // Single-listener teardown: the pid is still alive and the port still bound
+ // (isServerLive), but the lock is draining so no UI is reachable. The right
+ // hint is the transient "retry" — a fresh holder may bind shortly — not the
+ // permanent no-ui-mounted or no-server advice. This is the only remaining
+ // way to reach the transient hint now that a live ui-capable lock always
+ // resolves to a URL (server-liveness and UI-availability are one signal).
+ bindTestServerLock(cwd, 4321, ['http', 'ws', 'ui']);
+ markServerLockDraining(resolveLockDir(cwd));
const handler = captureRegistration(cwd);
const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.structuredContent?.running).toBe(false);
@@ -341,19 +350,17 @@ describe('preview_url tool — no UI running', () => {
});
describe('preview_url tool — backend demand-ensure', () => {
- test('cold project: ensure spawns the backend and the call returns a live URL once ui.lock binds', async () => {
+ test('cold project: ensure spawns the backend and the call returns a live URL', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
let resolverCalls = 0;
let uiBase = '';
const handler = captureRegistration(cwd, BASE_CONFIG, {
serverUrl: async () => {
resolverCalls += 1;
- bindTestServerLock(cwd);
- // The real spawn's `ok ui` sibling binds asynchronously — model the
- // lag so the test exercises the bounded wait, not a lucky fast path.
- setTimeout(() => {
- uiBase = bindTestUiLock(cwd);
- }, 30);
+ // Single-listener spawn: `ok start` brings up one ui-capable server that
+ // serves the shell at its own origin — no separate ui.lock to wait on,
+ // so the ui-capable server.lock resolves directly.
+ uiBase = bindTestUiServerLock(cwd, 4321);
return 'http://localhost:4321';
},
uiBindWait: { timeoutMs: 1500, pollIntervalMs: 10 },
@@ -367,7 +374,7 @@ describe('preview_url tool — backend demand-ensure', () => {
test('resolver runs on every call, even with a live UI (orphan-heal contract)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- const uiBase = bindTestUiLock(cwd);
+ const uiBase = bindTestUiServerLock(cwd);
let resolverCalls = 0;
const handler = captureRegistration(cwd, BASE_CONFIG, {
serverUrl: async () => {
@@ -413,11 +420,15 @@ describe('preview_url tool — backend demand-ensure', () => {
expect(result.content[0]?.text).toContain('did not start within');
});
- test('fresh spawn whose UI never binds: server-running hint after the bounded wait', async () => {
+ test('fresh spawn that comes up draining: server-running retry hint after the bounded wait', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
const handler = captureRegistration(cwd, BASE_CONFIG, {
serverUrl: async () => {
- bindTestServerLock(cwd);
+ // The spawned server is already tearing down (draining): live pid + bound
+ // port, but no reachable UI. The bounded wait polls, never resolves, and
+ // falls through to the transient "retry" hint (a fresh holder may bind).
+ bindTestServerLock(cwd, 4321, ['http', 'ws', 'ui']);
+ markServerLockDraining(resolveLockDir(cwd));
return 'http://localhost:4321';
},
uiBindWait: { timeoutMs: 60, pollIntervalMs: 10 },
@@ -447,7 +458,7 @@ describe('preview_url tool — backend demand-ensure', () => {
describe('preview_url tool — autoOpen field', () => {
test('echoes resolved autoOpen=false when the user has disabled it', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
const handler = captureRegistration(cwd, CONFIG_AUTOOPEN_OFF);
const result = await handler({ document: 'specs/foo/SPEC' });
expect(result.isError).toBeUndefined();
@@ -465,7 +476,7 @@ describe('preview_url tool — autoOpen field', () => {
test('reads config fresh per call (resolver invoked on every invocation)', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-get-preview-url-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
let currentAutoOpen = true;
const configResolver = async (): Promise<Config> =>
ConfigSchema.parse({ appearance: { preview: { autoOpen: currentAutoOpen } } });
diff --git a/packages/server/src/mcp/tools/get-preview-url.ts b/packages/server/src/mcp/tools/get-preview-url.ts
index 55a023de6..0cf280187 100644
--- a/packages/server/src/mcp/tools/get-preview-url.ts
+++ b/packages/server/src/mcp/tools/get-preview-url.ts
@@ -44,7 +44,7 @@ import {
resolveOffCwdTarget,
} from '../../off-cwd-resolver.ts';
import { isProcessAlive } from '../../process-alive.ts';
-import { readServerLock } from '../../server-lock.ts';
+import { lockAdvertisesUi, readServerLock } from '../../server-lock.ts';
import {
awaitUiBaseUrl,
encodeDocName,
@@ -101,12 +101,12 @@ interface GetPreviewUrlDeps {
/**
* Hocuspocus URL (or per-call resolver). When present, a preview request
* is treated as demand for a backend: the resolver's auto-spawn path
- * brings up `ok start` before `ui.lock` is read. Absent in registration
- * contexts without server authority — the tool then answers from disk
- * alone.
+ * brings up `ok start` before the UI advertisement is read. Absent in
+ * registration contexts without server authority — the tool then answers
+ * from disk alone.
*/
serverUrl?: ServerUrlOrResolver;
- /** Cold-spawn `ui.lock` wait overrides — tests only. */
+ /** Cold-spawn UI-bind wait overrides — tests only. */
uiBindWait?: { timeoutMs?: number; pollIntervalMs?: number };
/**
* Off-cwd resolver deps for the `file` branch (find the running session that
@@ -129,8 +129,7 @@ interface GetPreviewUrlDeps {
/**
* How long to wait for a freshly spawned backend's UI advertisement to bind
* before reporting no-UI — the window between `server.lock` appearing and the
- * listener binding its real port (+ the legacy sibling window on locks from
- * older binaries).
+ * listener binding its real port.
*/
const UI_BIND_WAIT_TIMEOUT_MS = 3000;
const UI_BIND_WAIT_POLL_MS = 100;
@@ -259,17 +258,18 @@ function noSingleFileSessionMessage(file: string): string {
/**
* 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.
+ * ever bind on its own. A ui-capable lock whose listener is still binding, and
+ * a pre-v2 lock with no `capabilities` field at all, both return false (via the
+ * shared `lockAdvertisesUi` predicate) so they keep the transient "retry" hint
+ * (an extra poll is harmless; wrongly telling a user no UI will mount seconds
+ * before it 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');
+ return !lockAdvertisesUi(lock);
} catch (err) {
process.stderr.write(
`[preview-url] readServerLock failed at ${lockDir} while checking ui capability: ${err instanceof Error ? err.message : String(err)}\n`,
diff --git a/packages/server/src/mcp/tools/history.test.ts b/packages/server/src/mcp/tools/history.test.ts
index b74ea9c0c..5a5dc6ce6 100644
--- a/packages/server/src/mcp/tools/history.test.ts
+++ b/packages/server/src/mcp/tools/history.test.ts
@@ -7,7 +7,7 @@ import {
expect,
test,
} from 'vitest';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
+import { bindTestUiServerLock } from './preview-url-test-helpers.ts';
// Skip-on-CI gate (oven-sh/bun#11892): simple-git fixture pattern in MCP
// test setup spawns git children that Bun fails to reap on ubuntu-latest
@@ -112,7 +112,7 @@ describe('history — previewUrl emission', () => {
test('emits route-only previewUrl + source alongside entries when resolver resolves', async () => {
// Bind the UI lock so the route resolves; `previewUrl` is route-only
// and carries no host:port.
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps());
diff --git a/packages/server/src/mcp/tools/index.ts b/packages/server/src/mcp/tools/index.ts
index dd3665eb7..1843921d8 100644
--- a/packages/server/src/mcp/tools/index.ts
+++ b/packages/server/src/mcp/tools/index.ts
@@ -271,7 +271,7 @@ export function registerAllTools(server: ServerInstance, opts: RegisterAllToolsO
// preview base/port reaches an agent. Per-response `previewUrl` fields are
// route-only; hosts that open the URL themselves call this tool. Takes
// `serverUrl` for its backend-ensure (a preview request is demand for a
- // backend), though it never makes HTTP calls itself — `ui.lock` stays the
+ // backend), though it never makes HTTP calls itself — `server.lock` stays the
// URL source.
registerPreviewUrl(registrationServer, {
config: opts.config,
diff --git a/packages/server/src/mcp/tools/links.test.ts b/packages/server/src/mcp/tools/links.test.ts
index 9c94fe04e..1ae3d418b 100644
--- a/packages/server/src/mcp/tools/links.test.ts
+++ b/packages/server/src/mcp/tools/links.test.ts
@@ -13,7 +13,7 @@ import {
import { type Config, ConfigSchema } from '../../config/schema.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import { DESCRIPTION, type LinksDeps, register } from './links.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
+import { bindTestUiServerLock } from './preview-url-test-helpers.ts';
import type { ServerInstance } from './shared.ts';
import { HOCUSPOCUS_NOT_RUNNING_ERROR } from './shared.ts';
@@ -209,7 +209,7 @@ describe('links — kind=backlinks', () => {
test('hits /api/backlinks with normalized docName and enriches rows with route-only previewUrl', async () => {
// Bind the UI lock so the resolver treats routes as reachable; the
// resolved previewUrl is route-only and carries no host:port.
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'backlinks', document: 'target.md' });
@@ -249,7 +249,7 @@ describe('links — kind=backlinks', () => {
describe('links — kind=forward', () => {
test('doc entries get previewUrl; external entries get null previewUrl', async () => {
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'forward', document: 'source' });
@@ -299,7 +299,7 @@ describe('links — kind=dead', () => {
});
test('target + source rows get previewUrl + previewUrlSource when resolver resolves', async () => {
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'dead' });
@@ -335,7 +335,7 @@ describe('links — kind=orphans', () => {
});
test('enriches orphan rows with previewUrl', async () => {
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'orphans' });
@@ -361,7 +361,7 @@ describe('links — kind=hubs', () => {
});
test('enriches hub rows with previewUrl', async () => {
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'hubs' });
@@ -396,7 +396,7 @@ describe('links — kind=suggest', () => {
});
test('emits previewUrl + previewUrlSource when resolver resolves', async () => {
- bindTestUiLock(tmpDir);
+ bindTestUiServerLock(tmpDir);
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl, tmpDir));
const result = await getTool().handler({ kind: 'suggest', document: 'project-alpha' });
diff --git a/packages/server/src/mcp/tools/preview-url-test-helpers.ts b/packages/server/src/mcp/tools/preview-url-test-helpers.ts
index 56772d2b8..f29cff6eb 100644
--- a/packages/server/src/mcp/tools/preview-url-test-helpers.ts
+++ b/packages/server/src/mcp/tools/preview-url-test-helpers.ts
@@ -3,21 +3,21 @@
*
* Most MCP-tool tests want to assert "this tool emitted a previewUrl that
* routes through the running UI." The resolver's only browser-reachable
- * source today is the `ui.lock` file (the `env`/`config` sources were
- * removed alongside `preview.baseUrl`). This module bundles the three
- * lines of lock setup + the URL prefix into one call so each test doesn't
- * repeat the mechanics — and so a port change touches one place, not 60+.
+ * source is a live `server.lock` advertising the `ui` capability (the
+ * `env`/`config` sources were removed alongside `preview.baseUrl`, and the
+ * sibling `ui.lock` was retired with the single-listener topology). This
+ * module bundles the lock setup + the URL prefix into one call so each test
+ * doesn't repeat the mechanics — and so a port change touches one place.
*
- * Not a `*.test.ts` file by design — `bun test` won't auto-discover it.
+ * Not a `*.test.ts` file by design — the runner won't auto-discover it.
*/
import { resolve } from 'node:path';
import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';
import { acquireServerLock, updateServerLockPort } from '../../server-lock.ts';
-import { acquireUiLock, updateUiLockPort } from '../../ui-lock.ts';
/**
- * Default port for the test UI lock. Vite's dev-server default — picking
+ * Default port for the test UI server. Vite's dev-server default — picking
* a familiar number makes failing-test output read naturally. The
* specific value doesn't matter: the resolver returns whatever the
* lock's port is, and assertions reference the same constant via the
@@ -26,23 +26,20 @@ import { acquireUiLock, updateUiLockPort } from '../../ui-lock.ts';
const TEST_UI_PORT = 5173;
/**
- * Acquire a `ui.lock` rooted at `cwd/.ok/local/` and bind it to
+ * Seed a ui-capable `server.lock` rooted at `cwd/.ok/local/` and bind it to
* `TEST_UI_PORT`. Returns the URL prefix the resolver will emit
- * (`http://localhost:<port>` — no trailing slash, no hash) so call
- * sites can build their expected URLs as `${uiBase}/#/<docName>`
- * without re-hardcoding the port number.
+ * (`http://localhost:<port>` — no trailing slash, no hash) so call sites can
+ * build their expected URLs as `${uiBase}/#/<docName>` without re-hardcoding
+ * the port number.
*
- * The `cwd` argument is whatever directory the tool's `resolveCwd`
- * resolves to — usually the test's per-test tmpDir. The resolver
- * anchors `resolveLockDir` at the project root (cwd), not contentDir
- * (see `server-factory.ts`), so this helper's `<cwd>/.ok/local/` is
- * the exact path the resolver will look at — independent of whatever
- * `config.content.dir` happens to be.
+ * The `cwd` argument is whatever directory the tool's `resolveCwd` resolves to
+ * — usually the test's per-test tmpDir. The resolver anchors `resolveLockDir`
+ * at the project root (cwd), not contentDir (see `server-factory.ts`), so this
+ * helper's `<cwd>/.ok/local/` is the exact path the resolver will look at —
+ * independent of whatever `config.content.dir` happens to be.
*/
-export function bindTestUiLock(cwd: string, port = TEST_UI_PORT): string {
- const lockDir = resolve(cwd, OK_DIR, LOCAL_DIR);
- acquireUiLock(lockDir, { port: 0, worktreeRoot: cwd });
- updateUiLockPort(lockDir, port);
+export function bindTestUiServerLock(cwd: string, port = TEST_UI_PORT): string {
+ bindTestServerLock(cwd, port, ['http', 'ws', 'ui']);
return `http://localhost:${port}`;
}
@@ -57,7 +54,7 @@ export function bindTestServerLock(cwd: string, port = 4321, capabilities?: stri
// `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.
+ // serving single-listener server.
acquireServerLock(lockDir, {
port: 0,
worktreeRoot: cwd,
diff --git a/packages/server/src/mcp/tools/preview-url.test.ts b/packages/server/src/mcp/tools/preview-url.test.ts
index 1a88e1453..9c40a9f38 100644
--- a/packages/server/src/mcp/tools/preview-url.test.ts
+++ b/packages/server/src/mcp/tools/preview-url.test.ts
@@ -16,7 +16,6 @@ import {
markServerLockDraining,
updateServerLockPort,
} from '../../server-lock.ts';
-import { acquireUiLock, markUiLockDraining, updateUiLockPort } from '../../ui-lock.ts';
import {
encodeSkillRoute,
resolvePreviewUrl,
@@ -36,13 +35,26 @@ afterEach(async () => {
await rm(tmpDir, { recursive: true, force: true });
});
+/**
+ * Seed a live, ui-capable `server.lock` bound to `port` — the reachability
+ * signal the preview resolver keys off in the single-listener topology (the
+ * retired `ui.lock` no longer participates).
+ */
+function seedUiServer(port = 5173, url?: string): void {
+ acquireServerLock(lockDir, {
+ port: 0,
+ worktreeRoot: tmpDir,
+ capabilities: ['http', 'ws', 'ui'],
+ });
+ updateServerLockPort(lockDir, port, url);
+}
+
describe('resolvePreviewUrl — lock edges', () => {
- test('lock returns route-only url when ui.lock is bound', () => {
+ test('lock returns route-only url when a ui-capable server.lock is bound', () => {
// `previewUrl` is route-only — no scheme/host/port. The lock
// is read only for reachability; a bound lock means the route is
// navigable in a running UI.
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
+ seedUiServer(5173);
const result = resolvePreviewUrl('docs/a', { lockDir });
expect(result).toEqual({ url: '/#/docs/a', source: 'lock' });
});
@@ -51,7 +63,11 @@ describe('resolvePreviewUrl — lock edges', () => {
// The deployed-wiki `config` fallback was removed alongside the
// `preview.baseUrl` schema field, so an unbound lock leaves nothing
// for the resolver to return.
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
+ acquireServerLock(lockDir, {
+ port: 0,
+ worktreeRoot: tmpDir,
+ capabilities: ['http', 'ws', 'ui'],
+ });
const result = resolvePreviewUrl('docs/a', { lockDir });
expect(result).toBeNull();
});
@@ -59,8 +75,7 @@ describe('resolvePreviewUrl — lock edges', () => {
test('route is identical regardless of the lock port', () => {
// Route-only: the port no longer rides the resolved url. Any bound
// port produces the same `/#/<doc>` route.
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 4242);
+ seedUiServer(4242);
const result = resolvePreviewUrl('docs/a', { lockDir });
expect(result?.url).toBe('/#/docs/a');
});
@@ -78,8 +93,7 @@ describe('resolvePreviewUrl — lock edges', () => {
const prior = process.env.OK_ELECTRON_PROTOCOL_HOST;
try {
process.env.OK_ELECTRON_PROTOCOL_HOST = '1';
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
+ seedUiServer(5173);
const result = resolvePreviewUrl('docs/a', { lockDir });
expect(result?.source).toBe('lock');
expect(result?.url.startsWith('/#/')).toBe(true);
@@ -92,9 +106,8 @@ describe('resolvePreviewUrl — lock edges', () => {
});
describe('resolveSkillPreviewUrl', () => {
- test('returns the route-only __skill__ url when ui.lock is bound', () => {
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
+ test('returns the route-only __skill__ url when a ui-capable server.lock is bound', () => {
+ seedUiServer(5173);
expect(resolveSkillPreviewUrl('global', 'trip-log', { lockDir })).toEqual({
url: '/#/__skill__/global/trip-log',
source: 'lock',
@@ -102,8 +115,7 @@ describe('resolveSkillPreviewUrl', () => {
});
test('encodes the skill name per-segment and defaults nothing (scope passed in)', () => {
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
+ seedUiServer(5173);
expect(resolveSkillPreviewUrl('project', 'run tests', { lockDir })?.url).toBe(
'/#/__skill__/project/run%20tests',
);
@@ -120,8 +132,7 @@ describe('resolveSkillPreviewUrl', () => {
describe('resolvePreviewUrl — docName encoding (via lock branch)', () => {
beforeEach(() => {
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
+ seedUiServer(5173);
});
test('simple nested path', () => {
@@ -161,8 +172,7 @@ describe('resolvePreviewUrl — round-trip via docNameFromHash', () => {
}
beforeEach(() => {
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
+ seedUiServer(5173);
});
test.each([
@@ -194,8 +204,8 @@ describe('resolvePreviewUrl — round-trip via docNameFromHash', () => {
});
});
-describe('resolveUiInfo — surface-aware source chain', () => {
- test('prefers a server.lock advertising the ui surface (single-listener topology)', () => {
+describe('resolveUiInfo — server.lock source', () => {
+ test('a server.lock advertising the ui surface yields its dialable origin', () => {
acquireServerLock(lockDir, {
port: 0,
worktreeRoot: tmpDir,
@@ -205,59 +215,41 @@ describe('resolveUiInfo — surface-aware source chain', () => {
expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://127.0.0.1:6060' });
});
- test('server.lock without the ui surface falls through to ui.lock (sibling topology)', () => {
- acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir, capabilities: ['http', 'ws'] });
- updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173, 'http://localhost:5173');
- expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://localhost:5173' });
- });
-
- test('pre-url ui.lock falls back to a port-derived localhost origin', () => {
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173);
- expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://localhost:5173' });
+ test('a server.lock with no capabilities field is treated as ui-capable (optimistic)', () => {
+ // Mirrors resolveUiRedirectPort: a missing `capabilities` field is
+ // indeterminate, and both twins treat it optimistically via lockAdvertisesUi.
+ acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir });
+ updateServerLockPort(lockDir, 6061, 'http://127.0.0.1:6061');
+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://127.0.0.1:6061' });
});
- test('no lock at all yields a null base', () => {
+ test('a server.lock that explicitly omits the ui surface yields a null base', () => {
+ acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir, capabilities: ['http', 'ws'] });
+ updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');
expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });
});
- test('a draining holder is never returned from either branch (single-listener teardown)', () => {
- // Single-listener teardown marks BOTH locks draining on the same
- // process. The server.lock draining guard must not be defeated by
- // falling through to that same dying process's ui.lock.
+ test('a ui-capable server.lock with no dialable origin (pre-bind, port 0) yields a null base', () => {
acquireServerLock(lockDir, {
port: 0,
worktreeRoot: tmpDir,
capabilities: ['http', 'ws', 'ui'],
});
- updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 6060, 'http://localhost:6060');
- markServerLockDraining(lockDir);
- markUiLockDraining(lockDir);
expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });
});
- test('server.lock with ui capability but no dialable origin (pre-bind) falls through to ui.lock', () => {
- // The window between acquireServerLock and updateServerLockPort: port 0,
- // no url, but the ui capability already declared. The null-origin case
- // must fall through to the ui.lock branch, not answer "no UI".
+ test('a draining ui-capable server.lock is never returned', () => {
acquireServerLock(lockDir, {
port: 0,
worktreeRoot: tmpDir,
capabilities: ['http', 'ws', 'ui'],
});
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173, 'http://localhost:5173');
- expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://localhost:5173' });
+ updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');
+ markServerLockDraining(lockDir);
+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });
});
- test('a draining ui.lock alone is not returned either', () => {
- acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });
- updateUiLockPort(lockDir, 5173, 'http://localhost:5173');
- markUiLockDraining(lockDir);
+ test('no lock at all yields a null base', () => {
expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });
});
});
diff --git a/packages/server/src/mcp/tools/preview-url.ts b/packages/server/src/mcp/tools/preview-url.ts
index d38d51893..da77f53c1 100644
--- a/packages/server/src/mcp/tools/preview-url.ts
+++ b/packages/server/src/mcp/tools/preview-url.ts
@@ -2,7 +2,7 @@
* Resolve the per-doc preview ROUTE for a given wiki docName.
*
* `resolvePreviewUrl` returns a route only (`/#/{docName}`) — no scheme,
- * host, or port. It still reads `ui.lock` for reachability: a non-null
+ * host, or port. It still reads `server.lock` for reachability: a non-null
* result means a UI is running for the project (the route is navigable);
* `null` means no UI is running anywhere. The route rides on every read +
* write tool response so the attach-preview-once warning flow keys off it.
@@ -18,8 +18,9 @@
* Route shape: `/#/{docName}` with per-segment encodeURIComponent. Matches
* the hash-route parser in `packages/app/src/lib/doc-hash.ts`.
*
- * Both CLI (`ok ui`) and OK Electron write `ui.lock`, so the lock branch
- * fires universally whenever any UI is running for the project. The
+ * A single-listener server (`ok start`, the desktop utility process) writes
+ * one `server.lock` advertising the `ui` capability, so the lock branch fires
+ * universally whenever any UI is running for the project. The
* `openknowledge://` URL scheme stays load-bearing for OS-level deep-linking
* (URL-scheme handler, dock drag, sidebar pills) — but is no longer emitted
* as an MCP `previewUrl`, because external agent in-app browsers (Claude
@@ -33,8 +34,7 @@
*/
import { resolveLockDir } from '../../config/paths.ts';
import { lockBaseUrl } from '../../process-lock.ts';
-import { readServerLock } from '../../server-lock.ts';
-import { readUiLock } from '../../ui-lock.ts';
+import { lockAdvertisesUi, readServerLock } from '../../server-lock.ts';
import type { ConfigOrResolver } from './shared.ts';
export const PREVIEW_URL_SOURCES = ['lock'] as const;
@@ -195,8 +195,8 @@ export async function resolvePreviewUrlForTool(
/**
* Browser-reachable UI info — resolved on demand by the `preview_url`
* tool, NOT emitted on per-response payloads. `baseUrl` is the
- * browser-reachable origin of the `ok ui` process; null when the UI lock is
- * absent / stale / unbound.
+ * browser-reachable origin of the running server; null when the server.lock
+ * is absent / stale / unbound / not ui-capable.
*/
export interface UiInfo {
baseUrl: string | null;
@@ -211,15 +211,15 @@ export interface UiInfo {
* emit a `ui` block, so the base does not ride per-response payloads.
*/
export function resolveUiInfo(ctx: PreviewUrlContext): UiInfo {
- // Single-listener topology first: a server.lock advertising the `ui`
- // surface means THIS process serves the React shell at its own origin —
- // no ui.lock involved. A server.lock without `ui` is not "no UI": in the
- // sibling topology (`ok start` + `ok ui`) the UI advertises via ui.lock,
- // so fall through to it. Only when neither lock yields a base is the
- // answer a definitive "no UI running".
+ // Single-listener topology: a live, non-draining server.lock that advertises
+ // the `ui` surface serves the React shell at its own origin. `lockAdvertisesUi`
+ // is the shared predicate that keeps this decision in lockstep with
+ // `resolveUiRedirectPort` and `serverExplicitlyLacksUi` — a missing
+ // `capabilities` field is indeterminate and treated as ui-capable. No
+ // server.lock, a draining one, or one that explicitly omits `ui` → no UI.
try {
const serverLock = readServerLock(ctx.lockDir);
- if (serverLock && serverLock.draining !== true && serverLock.capabilities?.includes('ui')) {
+ if (serverLock && serverLock.draining !== true && lockAdvertisesUi(serverLock)) {
const baseUrl = lockBaseUrl(serverLock);
if (baseUrl !== null) return { baseUrl };
}
@@ -228,29 +228,14 @@ export function resolveUiInfo(ctx: PreviewUrlContext): UiInfo {
`[preview-url] readServerLock failed at ${ctx.lockDir} while resolving ui info: ${err instanceof Error ? err.message : String(err)}\n`,
);
}
- try {
- const lock = readUiLock(ctx.lockDir);
- // Draining check on THIS branch too, not just server.lock above:
- // single-listener teardown marks BOTH locks draining on the same
- // process, so without it the server.lock guard is defeated by falling
- // through to the same dying process's ui.lock.
- if (lock && lock.draining !== true) {
- const baseUrl = lockBaseUrl(lock);
- if (baseUrl !== null) return { baseUrl };
- }
- } catch (err) {
- process.stderr.write(
- `[preview-url] readUiLock failed at ${ctx.lockDir} while resolving ui info: ${err instanceof Error ? err.message : String(err)}\n`,
- );
- }
return { baseUrl: null };
}
/**
* Poll `resolveUiInfo` until a UI origin binds or the deadline passes. Used
- * by `preview_url` right after a fresh backend spawn: the locks exist at
- * port 0 from acquire (pre-listen) until the server binds and stamps the
- * real port, so the ui-capable origin lags the locks' appearance by up to a
+ * by `preview_url` right after a fresh backend spawn: the server.lock exists
+ * at port 0 from acquire (pre-listen) until the server binds and stamps the
+ * real port, so the ui-capable origin lags the lock's appearance by up to a
* few seconds on a cold start.
*/
export async function awaitUiBaseUrl(
@@ -303,7 +288,7 @@ export function docNameFromPath(path: string): string {
/**
* Resolve the route-only preview URL (`/#/{docName}`) for a docName. Returns
- * `null` when no UI is running for the project (`ui.lock` absent / unbound).
+ * `null` when no UI is running for the project (no ui-capable `server.lock`).
*
* The returned `url` is a ROUTE — no scheme, host, or port. The lock is read
* only for reachability (a non-null result means the route is navigable in a
@@ -335,10 +320,9 @@ export function resolveSkillPreviewUrl(
* Shared reachability gate for the route resolvers: returns the route verbatim
* (no scheme/host/port) when a running UI is reachable, else `null`.
*
- * Same two-source chain as `resolveUiInfo`: a server.lock advertising the
- * `ui` surface (single-listener topology), else ui.lock (CLI `ok ui` + OK
- * Electron sibling topology) — the universal signal that a navigable React
- * app exists.
+ * Same signal as `resolveUiInfo`: a live, non-draining server.lock advertising
+ * the `ui` surface (single-listener topology) — the universal marker that a
+ * navigable React app exists for the project.
*/
function previewForRoute(hash: string, ctx: PreviewUrlContext): PreviewUrlResult | null {
const { baseUrl } = resolveUiInfo(ctx);
diff --git a/packages/server/src/mcp/tools/search.test.ts b/packages/server/src/mcp/tools/search.test.ts
index f05421be8..52bf32d8c 100644
--- a/packages/server/src/mcp/tools/search.test.ts
+++ b/packages/server/src/mcp/tools/search.test.ts
@@ -11,7 +11,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { type Config, ConfigSchema } from '../../config/schema.ts';
-import { bindTestUiLock } from './preview-url-test-helpers.ts';
+import { bindTestUiServerLock } from './preview-url-test-helpers.ts';
import { DESCRIPTION, register } from './search.ts';
import type { ServerInstance } from './shared.ts';
@@ -404,7 +404,7 @@ describe('search MCP tool — happy path', () => {
describe('search MCP tool — route-only previewUrl + no ui block (PRD-6735)', () => {
test('result rows carry route-only previewUrl; structured output has no ui block', async () => {
const cwd = mkdtempSync(join(tmpdir(), 'ok-search-preview-'));
- bindTestUiLock(cwd);
+ bindTestUiServerLock(cwd);
mockFetchOk({
ok: true,
query: 'agent presence',
diff --git a/packages/server/src/mcp/tools/share-link.test.ts b/packages/server/src/mcp/tools/share-link.test.ts
index 1bff61a8e..93bb551eb 100644
--- a/packages/server/src/mcp/tools/share-link.test.ts
+++ b/packages/server/src/mcp/tools/share-link.test.ts
@@ -16,11 +16,12 @@
*/
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
-import { hostname, tmpdir } from 'node:os';
+import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'vitest';
import type { z } from 'zod';
import { type Config, ConfigSchema } from '../../config/schema.ts';
+import { acquireServerLock, updateServerLockPort } from '../../server-lock.ts';
import { type FetchTestServer, startFetchTestServer } from './fetch-test-server.test-helper.ts';
import { register, type ShareLinkDeps } from './share-link.ts';
import type { ServerInstance } from './shared.ts';
@@ -142,28 +143,22 @@ function makeDeps(serverUrl: string | undefined, config: Config = BASE_CONFIG):
}
/**
- * Write a live `ui.lock` under `<tmpDir>/.ok/local/` so the preview-url
- * resolver's reachability gate fires (a non-null `previewUrl` means "a UI is
- * running"). Uses THIS process's pid + hostname so `readUiLock`'s
- * `isProcessAlive` + same-host checks both pass. Without this, every success
+ * Seed a live, ui-capable `server.lock` under `<tmpDir>/.ok/local/` so the
+ * preview-url resolver's reachability gate fires (a non-null `previewUrl`
+ * means "a UI is running"). `acquireServerLock` stamps THIS process's pid +
+ * machine identity so the liveness checks pass. Without this, every success
* case resolves `previewUrl: null` (no UI), so the lock is what lets us assert
* the concrete doc/folder route shapes.
*/
-async function writeUiLock(): Promise<void> {
+async function seedUiServer(): Promise<void> {
const lockDir = resolve(tmpDir, '.ok', 'local');
await mkdir(lockDir, { recursive: true });
- await writeFile(
- resolve(lockDir, 'ui.lock'),
- JSON.stringify({
- pid: process.pid,
- hostname: hostname(),
- port: 5173,
- startedAt: new Date().toISOString(),
- worktreeRoot: tmpDir,
- protocolVersion: 1,
- runtimeVersion: '0.0.0-test',
- }),
- );
+ acquireServerLock(lockDir, {
+ port: 0,
+ worktreeRoot: tmpDir,
+ capabilities: ['http', 'ws', 'ui'],
+ });
+ updateServerLockPort(lockDir, 5173, 'http://localhost:5173');
}
describe('share_link — registration + preconditions', () => {
@@ -432,7 +427,7 @@ describe('share_link — happy path', () => {
test('doc success previewUrl is the doc route `/#/<doc>` when a UI is running', async () => {
await writeFile(resolve(tmpDir, 'meeting.md'), '# meeting');
- await writeUiLock();
+ await seedUiServer();
mockResponse = { status: 200, body: successBody() };
const { server, getTool } = createFakeServer();
register(server, makeDeps(baseUrl));
@@ -447,7 +442,7 @@ describe('share_link — happy path', () => {
test('folder success previewUrl is the trailing-slash folder route when a UI is running', async () => {
await mkdir(resolve(tmpDir, 'guides'), { recursive: true });
- await writeUiLock();
+ await seedUiServer();
mockResponse = {
status: 200,
body: {
@@ -469,7 +464,7 @@ describe('share_link — happy path', () => {
});
test('content-root folder success previewUrl is the root route `/#/`', async () => {
- await writeUiLock();
+ await seedUiServer();
mockResponse = {
status: 200,
body: {
@@ -492,7 +487,7 @@ describe('share_link — happy path', () => {
test('nested folder previewUrl encodes per segment with trailing slash', async () => {
await mkdir(resolve(tmpDir, 'docs', 'api guide'), { recursive: true });
- await writeUiLock();
+ await seedUiServer();
mockResponse = {
status: 200,
body: {
diff --git a/packages/server/src/mcp/tools/share-link.ts b/packages/server/src/mcp/tools/share-link.ts
index 87a905013..ad312f583 100644
--- a/packages/server/src/mcp/tools/share-link.ts
+++ b/packages/server/src/mcp/tools/share-link.ts
@@ -473,7 +473,7 @@ export function register(server: ServerInstance, deps: ShareLinkDeps): void {
// Preview hint is route-only and symmetric across kinds: a doc previews
// at `/#/<doc>`, a folder at `/#/<folderPath>/` (`/#/` for the
// content-root sentinel — mirrors the app's `hashFromFolderPath` in
- // `packages/app/src/lib/doc-hash.ts`). Both share the SAME `ui.lock`
+ // `packages/app/src/lib/doc-hash.ts`). Both share the SAME `server.lock`
// reachability gate (a UI must be running for the route to be navigable),
// so `resolvePreviewUrlForTool` resolves the gate + `'lock'` source for
// both; the folder branch then rewrites the route shape to the
diff --git a/packages/server/src/off-cwd-resolver.ts b/packages/server/src/off-cwd-resolver.ts
index 3270c3035..14e5116d7 100644
--- a/packages/server/src/off-cwd-resolver.ts
+++ b/packages/server/src/off-cwd-resolver.ts
@@ -27,7 +27,7 @@ import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core
import { isProcessAlive } from './process-alive.ts';
import { lockBaseUrl } from './process-lock.ts';
import { discoverLockDirs } from './process-scan.ts';
-import { readUiLock } from './ui-lock.ts';
+import { lockAdvertisesUi, readServerLock } from './server-lock.ts';
/** A running server discovered off-cwd, with the fields the rule needs. */
export interface OffCwdCandidate {
@@ -106,9 +106,10 @@ export function projectDirOfLockDir(lockDir: string): string {
/**
* Production deps: discover via `discoverLockDirs`; inspect each lock dir by
* re-deriving its contentDir from `.ok/config.yml` (the lock records projectDir,
- * not contentDir), reading `ui.lock` for the port, and liveness-gating on the
- * pid. contentDir is realpath'd so the prefix match lines up with a realpath'd
- * target (both sides canonical — the symlink discipline used everywhere).
+ * not contentDir), reading `server.lock` for the port, and liveness-gating on
+ * the pid. contentDir is realpath'd so the prefix match lines up with a
+ * realpath'd target (both sides canonical — the symlink discipline used
+ * everywhere).
*/
export function createOffCwdResolverDeps(): OffCwdResolverDeps {
return {
@@ -135,13 +136,15 @@ export function createOffCwdResolverDeps(): OffCwdResolverDeps {
);
return null;
}
- const lock = readUiLock(lockDir);
- // Liveness and URL derivation share one source of truth: a candidate
- // is alive only when it has a non-draining, dialable origin — the same
- // coupling as the shim's liveBaseUrlFromLock. The draining check
- // matters because single-listener teardown marks BOTH locks draining
- // while the pid is still alive.
- const resolvedBase = lock ? lockBaseUrl(lock) : null;
+ const lock = readServerLock(lockDir);
+ // Liveness and URL derivation share one source of truth: a candidate is
+ // alive only when its server.lock is non-draining, ui-capable, and has a
+ // dialable origin. `lockAdvertisesUi` keeps an `--only server` holder
+ // (no navigable UI) out of redirect/off-cwd resolution — the same "no UI"
+ // boundary resolveUiInfo enforces. The draining check matters because
+ // single-listener teardown marks the lock draining while the pid is
+ // still alive.
+ const resolvedBase = lock != null && lockAdvertisesUi(lock) ? lockBaseUrl(lock) : null;
const baseUrl = resolvedBase ?? `http://localhost:${lock?.port ?? 0}`;
const alive =
lock != null && lock.draining !== true && resolvedBase !== null && isProcessAlive(lock.pid);
diff --git a/packages/server/src/process-lock.test.ts b/packages/server/src/process-lock.test.ts
index 6b3882846..6dca9f79c 100644
--- a/packages/server/src/process-lock.test.ts
+++ b/packages/server/src/process-lock.test.ts
@@ -21,7 +21,7 @@ import {
} from './process-lock';
import { PROTOCOL_VERSION, RUNTIME_VERSION } from './version-constants';
-const LOCK_NAME: LockName = 'ui';
+const LOCK_NAME: LockName = 'server';
/**
* Pick a PID that is alive on this host AND passes `isValidLockPid` (≥ 2,
@@ -70,7 +70,7 @@ describe('acquireProcessLock', () => {
expect(handle.lockPath).toBe(lockPath);
expect(existsSync(lockPath)).toBe(true);
- expect(lockPath.endsWith('ui.lock')).toBe(true);
+ expect(lockPath.endsWith('server.lock')).toBe(true);
const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));
expect(md.pid).toBe(process.pid);
@@ -100,23 +100,6 @@ describe('acquireProcessLock', () => {
expect(md.port).toBe(0);
});
- test('writes distinct files for different lockNames in the same lockDir', () => {
- acquireProcessLock({
- lockName: 'server',
- lockDir,
- metadata: { port: 1111, worktreeRoot: '/wt' },
- });
- acquireProcessLock({ lockName: 'ui', lockDir, metadata: { port: 2222, worktreeRoot: '/wt' } });
-
- expect(existsSync(lockFilePath(lockDir, 'server'))).toBe(true);
- expect(existsSync(lockFilePath(lockDir, 'ui'))).toBe(true);
-
- const serverMd = JSON.parse(readFileSync(lockFilePath(lockDir, 'server'), 'utf-8'));
- const uiMd = JSON.parse(readFileSync(lockFilePath(lockDir, 'ui'), 'utf-8'));
- expect(serverMd.port).toBe(1111);
- expect(uiMd.port).toBe(2222);
- });
-
test('replaces stale lock from dead process', () => {
acquireProcessLock({
lockName: LOCK_NAME,
@@ -568,14 +551,15 @@ describe('readProcessLock', () => {
expect(readProcessLock({ lockName: LOCK_NAME, lockDir })).toBeNull();
});
- test('reads only the named lock (does not cross-contaminate)', () => {
+ test('reads are scoped to (lockName, lockDir) — a sibling lockDir reads null', () => {
acquireProcessLock({
lockName: 'server',
lockDir,
metadata: { port: 1111, worktreeRoot: '/wt' },
});
expect(readProcessLock({ lockName: 'server', lockDir })?.port).toBe(1111);
- expect(readProcessLock({ lockName: 'ui', lockDir })).toBeNull();
+ // A different lockDir with no lock reads null — the read never leaks across dirs.
+ expect(readProcessLock({ lockName: 'server', lockDir: `${lockDir}/other` })).toBeNull();
});
});
diff --git a/packages/server/src/process-lock.ts b/packages/server/src/process-lock.ts
index 0e55160b3..c92b12829 100644
--- a/packages/server/src/process-lock.ts
+++ b/packages/server/src/process-lock.ts
@@ -12,7 +12,7 @@
* (containers): discovery fields ride on the mutex, not the reverse.
* Acquisition happens before listen; nothing here may weaken that ordering.
*
- * Used by both `server-lock.ts` (server.lock) and `ui-lock.ts` (ui.lock).
+ * Used by `server-lock.ts` (server.lock).
*/
import {
@@ -35,7 +35,10 @@ import { PROTOCOL_VERSION, RUNTIME_VERSION } from './version-constants.ts';
const log = getLogger('process-lock');
-export type LockName = 'server' | 'ui';
+// The `ui` member retired with `ui.lock` (single-listener topology); the UI is
+// advertised via the `ui` capability on `server.lock`. Kept as a named type
+// (rather than the bare literal) for call-site clarity and future expansion.
+export type LockName = 'server';
/**
* Who started this server. `interactive` means a user-facing CLI/Electron
@@ -58,11 +61,9 @@ export interface ProcessLockMetadata {
/**
* HTTP/WebSocket port. 0 means "starting — port not yet bound".
*
- * DEPRECATED as a dial target in favor of `url` — kept written through the
- * ui.lock-retirement compatibility window so binaries predating `url` keep
- * discovering. New readers go through `lockBaseUrl` (prefer `url`, fall
- * back to `port`). Retirement rides the `protocolVersion` 1→2 bump at the
- * ui.lock-removal wave, NOT before.
+ * Legacy dial fallback in favor of `url` — still written so binaries
+ * predating `url` keep discovering. New readers go through `lockBaseUrl`
+ * (prefer `url`, fall back to `port`).
*/
port: number;
/**
@@ -111,16 +112,15 @@ export interface ProcessLockMetadata {
*/
parentPid?: number;
/**
- * Protocol/feature surfaces this server exposes. On server.lock, writers
- * that also emit `url` MUST list mounted surfaces accurately — in
- * particular `"ui"` is present iff the process itself serves the React
- * shell, so `preview_url` can distinguish "no UI mounted" from "UI served
- * elsewhere". Baseline for any `bootServer` boot is `["http", "ws"]`. On
- * server.locks without `url` (older writers) the array is best-effort
- * hints only: absence of `"ui"` is indeterminate and readers keep the
- * ui.lock fallback. On ui.lock the accuracy requirement does not apply —
- * that file's very existence is the UI signal, no reader consults its
- * `capabilities`, and the sibling retires with the ui.lock-removal wave.
+ * Protocol/feature surfaces this server exposes. Writers that also emit
+ * `url` MUST list mounted surfaces accurately — in particular `"ui"` is
+ * present iff the process itself serves the React shell, so `preview_url`
+ * and the clone→open redirect can distinguish a UI-serving server from an
+ * API-only (`--only server`) one. Baseline for any `bootServer` boot is
+ * `["http", "ws"]`. On locks without `url` (older writers) the array is
+ * best-effort hints only: absence of `"ui"` is indeterminate, so the shared
+ * `lockAdvertisesUi` predicate treats a missing `capabilities` field
+ * optimistically (see `server-lock.ts`).
*/
capabilities?: string[];
/**
diff --git a/packages/server/src/process-scan.ts b/packages/server/src/process-scan.ts
index 12c938f79..b197f66ee 100644
--- a/packages/server/src/process-scan.ts
+++ b/packages/server/src/process-scan.ts
@@ -308,6 +308,9 @@ function parseListeningPids(output: string): number[] {
* i.e. `<contentDir>/.ok/local`).
*/
function hasLockFile(lockDir: string): boolean {
+ // The `ui.lock` disjunct is the one-release legacy-reap carve-out: a lingering
+ // pre-migration `ok ui` holder with no companion `server.lock` must stay
+ // discoverable so `ok stop all` / `ok clean` can reach it. Drops with the reap.
return existsSync(join(lockDir, 'server.lock')) || existsSync(join(lockDir, 'ui.lock'));
}
diff --git a/packages/server/src/server-lock.ts b/packages/server/src/server-lock.ts
index ec3763b12..7f3e7ba09 100644
--- a/packages/server/src/server-lock.ts
+++ b/packages/server/src/server-lock.ts
@@ -8,10 +8,9 @@
*
* `lockDir` is `<contentDir>/.ok/local` by convention.
*
- * Sibling of `shadow-lock.ts` (guards a shadow repo) and `ui-lock.ts`
- * (guards the UI process). All three share `process-lock.ts` for the lock
- * acquisition/release/port-update plumbing and `process-alive.ts` for
- * liveness checks.
+ * Sibling of `shadow-lock.ts` (guards a shadow repo). Both share
+ * `process-lock.ts` for the lock acquisition/release/port-update plumbing and
+ * `process-alive.ts` for liveness checks.
*/
import {
@@ -66,6 +65,29 @@ export function readServerLock(lockDir: string): ServerLockMetadata | null {
return readProcessLock({ lockName: 'server', lockDir });
}
+/**
+ * Does a server.lock advertise a navigable UI surface? The single source of
+ * truth for the UI-capability decision, shared by every resolution + display
+ * surface so none can disagree on the "no UI" boundary now that `ui.lock` no
+ * longer backstops the sibling topology:
+ * - server package: `resolveUiInfo` (preview-url.ts), `resolveUiRedirectPort`
+ * (ui-redirect-port.ts), `serverExplicitlyLacksUi` (get-preview-url.ts),
+ * and `createOffCwdResolverDeps.inspect` (off-cwd-resolver.ts);
+ * - CLI (imported via the package export): `ok status`, `ok ps`, and
+ * `resolveServerReuse` (start.ts).
+ *
+ * A missing `capabilities` field (older writer) is indeterminate and treated
+ * as ui-capable: wrongly refusing a healthy server is worse than an optimistic
+ * navigate. An explicit array WITHOUT `ui` (`--only server`, or a degraded
+ * API-only boot) is a definitive no.
+ *
+ * Capability only — liveness / draining / port are the caller's concern, since
+ * each surface needs a different shape (a base URL, a port, a hint selector).
+ */
+export function lockAdvertisesUi(lock: Pick<ServerLockMetadata, 'capabilities'>): boolean {
+ return !Array.isArray(lock.capabilities) || lock.capabilities.includes('ui');
+}
+
export function releaseServerLock(lockDir: string, opts?: { deferUnlinkToExit?: boolean }): void {
releaseProcessLock({ lockName: 'server', lockDir, ...opts });
}
diff --git a/packages/server/src/ui-lock.ts b/packages/server/src/ui-lock.ts
deleted file mode 100644
index e8cf7a13b..000000000
--- a/packages/server/src/ui-lock.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-/**
- * UI-level process lock — exclusive per-project UI process ownership.
- *
- * Thin adapter around `acquireProcessLock` in `process-lock.ts`. Only one
- * `ok ui` process may own a given contentDir at a time. The lock file at
- * `<lockDir>/ui.lock` contains JSON metadata used for stale detection and
- * for MCP tool preview-url discovery (see `preview-url.ts`).
- *
- * `lockDir` is `<contentDir>/.ok` by convention.
- *
- * Sibling of `server-lock.ts` (guards the Hocuspocus collab server) and
- * `shadow-lock.ts` (guards the shadow repo). All three share
- * `process-lock.ts` for the acquisition/release/port-update plumbing.
- */
-
-import {
- acquireProcessLock,
- type LockKind,
- markProcessLockDraining,
- ProcessLockCollisionError,
- type ProcessLockMetadata,
- readProcessLock,
- releaseProcessLock,
- updateProcessLockPort,
-} from './process-lock.ts';
-
-export type UiLockMetadata = ProcessLockMetadata;
-
-export class UiLockCollisionError extends ProcessLockCollisionError {
- constructor(existing: UiLockMetadata, lockPath: string) {
- super(existing, lockPath, 'ui');
- this.name = 'UiLockCollisionError';
- }
-}
-
-export function acquireUiLock(
- lockDir: string,
- init: {
- port: number;
- url?: string;
- worktreeRoot: string;
- kind?: LockKind;
- parentPid?: number;
- capabilities?: string[];
- },
-): string {
- try {
- const handle = acquireProcessLock({ lockName: 'ui', lockDir, metadata: init });
- return handle.lockPath;
- } catch (err) {
- if (err instanceof ProcessLockCollisionError && err.lockName === 'ui') {
- throw new UiLockCollisionError(err.existing, err.lockPath);
- }
- throw err;
- }
-}
-
-export function updateUiLockPort(lockDir: string, port: number, url?: string): void {
- updateProcessLockPort({ lockName: 'ui', lockDir, port, url });
-}
-
-export function readUiLock(lockDir: string): UiLockMetadata | null {
- return readProcessLock({ lockName: 'ui', lockDir });
-}
-
-export function releaseUiLock(lockDir: string, opts?: { deferUnlinkToExit?: boolean }): void {
- releaseProcessLock({ lockName: 'ui', lockDir, ...opts });
-}
-
-/** Mark our ui.lock draining — teardown began; unlink happens at exit. */
-export function markUiLockDraining(lockDir: string): void {
- markProcessLockDraining({ lockName: 'ui', lockDir });
-}
diff --git a/packages/server/src/ui-redirect-port.test.ts b/packages/server/src/ui-redirect-port.test.ts
index 4936ac37b..0a181b74b 100644
--- a/packages/server/src/ui-redirect-port.test.ts
+++ b/packages/server/src/ui-redirect-port.test.ts
@@ -8,10 +8,9 @@ import {
releaseServerLock,
updateServerLockPort,
} from './server-lock.ts';
-import { acquireUiLock, markUiLockDraining, releaseUiLock, updateUiLockPort } from './ui-lock.ts';
import { resolveUiRedirectPort } from './ui-redirect-port.ts';
-describe('resolveUiRedirectPort — clone-redirect two-source chain', () => {
+describe('resolveUiRedirectPort — clone-redirect server.lock chain', () => {
const dirs: string[] = [];
function makeLockDir(): string {
@@ -26,7 +25,7 @@ describe('resolveUiRedirectPort — clone-redirect two-source chain', () => {
}
});
- test('ui-capable server.lock resolves to the server port (single-listener default)', () => {
+ test('ui-capable server.lock resolves to the server port (single-listener)', () => {
const lockDir = makeLockDir();
acquireServerLock(lockDir, {
port: 0,
@@ -41,25 +40,7 @@ describe('resolveUiRedirectPort — clone-redirect two-source chain', () => {
}
});
- test('explicit no-ui server.lock + live ui.lock resolves to the sibling port (split-mode pair)', () => {
- const lockDir = makeLockDir();
- acquireServerLock(lockDir, {
- port: 0,
- worktreeRoot: lockDir,
- capabilities: ['http', 'ws'],
- });
- updateServerLockPort(lockDir, 45002, 'http://127.0.0.1:45002');
- acquireUiLock(lockDir, { port: 0, worktreeRoot: lockDir });
- updateUiLockPort(lockDir, 45003, 'http://localhost:45003');
- try {
- expect(resolveUiRedirectPort(lockDir)).toBe(45003);
- } finally {
- releaseUiLock(lockDir);
- releaseServerLock(lockDir);
- }
- });
-
- test('explicit no-ui server.lock with no sibling is a definitive no-ui', () => {
+ test('explicit no-ui server.lock is a definitive no-ui', () => {
const lockDir = makeLockDir();
acquireServerLock(lockDir, {
port: 0,
@@ -74,17 +55,6 @@ describe('resolveUiRedirectPort — clone-redirect two-source chain', () => {
}
});
- test('lone ui.lock (split UI against a remote upstream) resolves to the UI port', () => {
- const lockDir = makeLockDir();
- acquireUiLock(lockDir, { port: 0, worktreeRoot: lockDir });
- updateUiLockPort(lockDir, 45005, 'http://localhost:45005');
- try {
- expect(resolveUiRedirectPort(lockDir)).toBe(45005);
- } finally {
- releaseUiLock(lockDir);
- }
- });
-
test('server.lock with NO capabilities field is treated as ui-capable (indeterminate → optimistic)', () => {
const lockDir = makeLockDir();
acquireServerLock(lockDir, { port: 0, worktreeRoot: lockDir });
@@ -110,7 +80,7 @@ describe('resolveUiRedirectPort — clone-redirect two-source chain', () => {
}
});
- test('no locks at all resolves to null', () => {
+ test('no lock at all resolves to null', () => {
expect(resolveUiRedirectPort(makeLockDir())).toBeNull();
});
@@ -129,16 +99,4 @@ describe('resolveUiRedirectPort — clone-redirect two-source chain', () => {
releaseServerLock(lockDir);
}
});
-
- test('a DRAINING ui.lock is not a redirect target — falls through to null', () => {
- const lockDir = makeLockDir();
- acquireUiLock(lockDir, { port: 0, worktreeRoot: lockDir });
- updateUiLockPort(lockDir, 45008, 'http://localhost:45008');
- markUiLockDraining(lockDir);
- try {
- expect(resolveUiRedirectPort(lockDir)).toBeNull();
- } finally {
- releaseUiLock(lockDir);
- }
- });
});
diff --git a/packages/server/src/ui-redirect-port.ts b/packages/server/src/ui-redirect-port.ts
index 0380d9de6..5b162ca60 100644
--- a/packages/server/src/ui-redirect-port.ts
+++ b/packages/server/src/ui-redirect-port.ts
@@ -1,43 +1,23 @@
/**
* Redirect-target resolution for flows that need a browser-navigable UI port
* for a project directory (the clone → open redirect in `api-extension.ts`).
- * Mirrors `resolveUiInfo` in `mcp/tools/preview-url.ts` — the canonical
- * two-source chain; the two surfaces must agree on what "no UI" means for as
- * long as `ui.lock` remains supported:
+ * Twin of `resolveUiInfo` in `mcp/tools/preview-url.ts` — the two surfaces must
+ * agree on what "no UI" means, so both route the capability decision through
+ * the shared `lockAdvertisesUi` predicate:
*
- * 1. a live, non-draining `server.lock` advertising the `ui` capability →
- * that server's port (single-listener topology);
- * 2. else a live, non-draining `ui.lock` with a bound port → that port —
- * the `--only ui --server-url` split-mode proxy, OK Electron's
- * advertisement, or a legacy sibling from an older binary;
- * 3. else a live server.lock whose `capabilities` EXPLICITLY omit `ui` →
- * `'no-ui'` — definitive: no UI is serving and none will bind on its
- * own;
- * 4. else `null` — nothing usable is live.
- *
- * A server.lock with no `capabilities` field (older writer) is treated as
- * ui-capable in step 1 — absence is indeterminate, and an optimistic
- * redirect beats wrongly refusing a healthy server (mirrors
- * `serverExplicitlyLacksUi` in `mcp/tools/get-preview-url.ts`).
- *
- * Step 2 retires with the ui.lock removal wave; until then, dropping it
- * would report "no UI" against a live split-mode pair while a UI is in
- * fact serving.
+ * 1. a live, non-draining `server.lock` advertising the `ui` capability (or
+ * omitting the `capabilities` field — indeterminate, treated
+ * optimistically) → that server's port (single-listener topology);
+ * 2. else a live, non-draining `server.lock` whose `capabilities` EXPLICITLY
+ * omit `ui` → `'no-ui'` — definitive: no UI is serving and none will bind
+ * on its own;
+ * 3. else `null` — nothing usable is live.
*/
-import { readServerLock } from './server-lock.ts';
-import { readUiLock } from './ui-lock.ts';
+import { lockAdvertisesUi, readServerLock } from './server-lock.ts';
export function resolveUiRedirectPort(lockDir: string): number | 'no-ui' | null {
const server = readServerLock(lockDir);
- const serverLive = server !== null && server.port > 0 && server.draining !== true;
- // Two ways step 1 admits a lock: no `capabilities` field at all (older
- // writer — indeterminate, be optimistic), or an explicit `ui` entry.
- if (serverLive && (!Array.isArray(server.capabilities) || server.capabilities.includes('ui'))) {
- return server.port;
- }
- const ui = readUiLock(lockDir);
- if (ui !== null && ui.port > 0 && ui.draining !== true) return ui.port;
- if (serverLive) return 'no-ui';
- return null;
+ if (server === null || server.port <= 0 || server.draining === true) return null;
+ return lockAdvertisesUi(server) ? server.port : 'no-ui';
}
diff --git a/packages/server/src/ui-surface-agreement.test.ts b/packages/server/src/ui-surface-agreement.test.ts
new file mode 100644
index 000000000..2ec97812d
--- /dev/null
+++ b/packages/server/src/ui-surface-agreement.test.ts
@@ -0,0 +1,128 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { resolveUiInfo } from './mcp/tools/preview-url.ts';
+import {
+ acquireServerLock,
+ markServerLockDraining,
+ releaseServerLock,
+ updateServerLockPort,
+} from './server-lock.ts';
+import { resolveUiRedirectPort } from './ui-redirect-port.ts';
+
+/**
+ * Guardrail: `resolveUiInfo` (preview-url.ts) and `resolveUiRedirectPort`
+ * (ui-redirect-port.ts) are twins that MUST agree on the "no UI" boundary —
+ * both route the capability decision through the shared `lockAdvertisesUi`
+ * predicate. This table drives BOTH over the same `server.lock` states and
+ * asserts they classify UI-present identically (and, when present, surface the
+ * same port). A divergence here is the exact class of bug the shared predicate
+ * exists to prevent once `ui.lock` no longer backstops either surface.
+ *
+ * The OTHER `lockAdvertisesUi` consumers are exercised where their own
+ * liveness/shape logic lives, so no surface reintroduces the divergence:
+ * - `serverExplicitlyLacksUi` (get-preview-url.ts) — the LIVE-lock inverse;
+ * pinned by get-preview-url.test.ts's `--only server` + draining hints.
+ * - `createOffCwdResolverDeps.inspect` (off-cwd-resolver.ts) — off-cwd-resolver.test.ts.
+ * - CLI `ok status` / `ok ps` / `resolveServerReuse` — all import the exported
+ * predicate; the missing-`capabilities` optimism is pinned by status.test.ts
+ * and ps.test.ts so a pre-v2 server never shows "no UI" while preview_url
+ * would navigate to it.
+ */
+describe('resolveUiInfo ⇔ resolveUiRedirectPort agreement', () => {
+ const dirs: string[] = [];
+
+ function makeLockDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-ui-agree-'));
+ dirs.push(dir);
+ return dir;
+ }
+
+ afterEach(() => {
+ for (const dir of dirs.splice(0)) {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ type Seed = (lockDir: string) => void;
+ const cases: Array<{ name: string; seed: Seed; uiPresent: boolean }> = [
+ {
+ name: 'ui-capable live server.lock',
+ seed: (d) => {
+ acquireServerLock(d, { port: 0, worktreeRoot: d, capabilities: ['http', 'ws', 'ui'] });
+ updateServerLockPort(d, 46001, 'http://127.0.0.1:46001');
+ },
+ uiPresent: true,
+ },
+ {
+ name: 'no-capabilities live server.lock (optimistic)',
+ seed: (d) => {
+ acquireServerLock(d, { port: 0, worktreeRoot: d });
+ updateServerLockPort(d, 46002, 'http://127.0.0.1:46002');
+ },
+ uiPresent: true,
+ },
+ {
+ name: 'explicit no-ui live server.lock',
+ seed: (d) => {
+ acquireServerLock(d, { port: 0, worktreeRoot: d, capabilities: ['http', 'ws'] });
+ updateServerLockPort(d, 46003, 'http://127.0.0.1:46003');
+ },
+ uiPresent: false,
+ },
+ {
+ name: 'draining ui-capable server.lock',
+ seed: (d) => {
+ acquireServerLock(d, { port: 0, worktreeRoot: d, capabilities: ['http', 'ws', 'ui'] });
+ updateServerLockPort(d, 46004, 'http://127.0.0.1:46004');
+ markServerLockDraining(d);
+ },
+ uiPresent: false,
+ },
+ {
+ name: 'explicit no-ui + draining server.lock',
+ seed: (d) => {
+ acquireServerLock(d, { port: 0, worktreeRoot: d, capabilities: ['http', 'ws'] });
+ updateServerLockPort(d, 46005, 'http://127.0.0.1:46005');
+ markServerLockDraining(d);
+ },
+ uiPresent: false,
+ },
+ {
+ name: 'unbound (port 0) ui-capable server.lock',
+ seed: (d) => {
+ acquireServerLock(d, { port: 0, worktreeRoot: d, capabilities: ['http', 'ws', 'ui'] });
+ },
+ uiPresent: false,
+ },
+ {
+ name: 'no lock at all',
+ seed: () => undefined,
+ uiPresent: false,
+ },
+ ];
+
+ for (const c of cases) {
+ test(`${c.name}: twins agree UI-present=${c.uiPresent}`, () => {
+ const lockDir = makeLockDir();
+ c.seed(lockDir);
+ try {
+ const base = resolveUiInfo({ lockDir }).baseUrl;
+ const redirect = resolveUiRedirectPort(lockDir);
+ const infoPresent = base !== null;
+ const redirectPresent = typeof redirect === 'number';
+ // The two twins must classify UI-present identically...
+ expect(infoPresent).toBe(redirectPresent);
+ // ...and match the expected outcome for the state.
+ expect(infoPresent).toBe(c.uiPresent);
+ // When a UI is present, both surface the same port.
+ if (c.uiPresent) {
+ expect(base).toContain(`:${redirect}`);
+ }
+ } finally {
+ releaseServerLock(lockDir);
+ }
+ });
+ }
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 694da5371..908099f3e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -829,9 +829,6 @@ importers:
simple-git:
specifier: ^3.36.0
version: 3.36.0
- sirv:
- specifier: ^3.0.1
- version: 3.0.2
smol-toml:
specifier: ^1.6.1
version: 1.7.0