Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): re-point desktop attach to server.lock v2 (PRD-7903) (#3413)

omar-inkeep21a6f800fbfb
diff --git a/.changeset/desktop-attach-canonical-server.md b/.changeset/desktop-attach-canonical-server.md
new file mode 100644
index 000000000..761842bcc
--- /dev/null
+++ b/.changeset/desktop-attach-canonical-server.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+The desktop app now derives every connection to a project's server — the collab socket, the keepalive that holds off idle shutdown, and the branch-switch dialog's API calls — from the single address the server advertises in `server.lock`, instead of assuming `localhost`. A server bound to a different loopback address (such as `::1`) now keeps its keepalive and dialogs working after the desktop attaches to it. The desktop's spawned server also stops passing a redundant legacy flag; it serves the editor, content assets, and API from one process and one port, and advertises that single URL with `capabilities: ["ui"]` for every other tool to discover.
diff --git a/packages/desktop/src/main/branch-info-proxy.test.ts b/packages/desktop/src/main/branch-info-proxy.test.ts
index 5da3b2d67..1abff1f0e 100644
--- a/packages/desktop/src/main/branch-info-proxy.test.ts
+++ b/packages/desktop/src/main/branch-info-proxy.test.ts
@@ -52,6 +52,24 @@ describe('resolveProjectServerOrigin', () => {
expect(origin).toBe('http://localhost:12345');
});
+ test('prefers the lock v2 url over the port — non-default loopback binds resolve', async () => {
+ const origin = await resolveProjectServerOrigin(
+ '/tmp/p',
+ buildDeps({ readServerLock: () => ({ pid: 4242, port: 12345, url: 'http://[::1]:12345' }) }),
+ );
+ expect(origin).toBe('http://[::1]:12345');
+ });
+
+ test('a non-loopback lock url is refused by validation and falls back to the port', async () => {
+ const origin = await resolveProjectServerOrigin(
+ '/tmp/p',
+ buildDeps({
+ readServerLock: () => ({ pid: 4242, port: 12345, url: 'http://evil.example:80' }),
+ }),
+ );
+ expect(origin).toBe('http://localhost:12345');
+ });
+
test('returns null when no lock is present after the poll window', async () => {
const origin = await resolveProjectServerOrigin(
'/tmp/p',
diff --git a/packages/desktop/src/main/branch-info-proxy.ts b/packages/desktop/src/main/branch-info-proxy.ts
index 3809d0e44..bb5634ec9 100644
--- a/packages/desktop/src/main/branch-info-proxy.ts
+++ b/packages/desktop/src/main/branch-info-proxy.ts
@@ -46,6 +46,7 @@ import {
ShareTargetStatusResponseSchema,
} from '@inkeep/open-knowledge-core';
import { RUNTIME_VERSION } from '@inkeep/open-knowledge-server';
+import { lockApiOrigin } from './window-manager.ts';
// Client version metadata on every main-process /api request (v1 wire contract).
const DESKTOP_MAIN_VERSION_HEADERS = clientVersionHeaders({
@@ -56,11 +57,13 @@ const DESKTOP_MAIN_VERSION_HEADERS = clientVersionHeaders({
/**
* Bounded subset of the server-lock metadata we read here. Mirrors the
* shape consumed by `WindowManager.tryAttachExistingServer` so behavior
- * stays consistent across surfaces.
+ * stays consistent across surfaces. `url` is the lock v2 one-URL contract
+ * field; optional for pre-v2 locks.
*/
export interface ServerLockReadShape {
readonly pid: number;
readonly port: number;
+ readonly url?: string;
}
/** Dependencies injected so unit tests can substitute deterministic fakes. */
@@ -80,11 +83,12 @@ export interface BranchInfoProxyDeps {
}
/**
- * Locate the running server for `projectPath` and return its HTTP origin
- * (`http://localhost:<port>`). Polls briefly because the dispatcher may
- * call this right after `bridge.project.open`, before the utility's lock
- * file lands. Returns `null` when no live server resolves within the
- * poll window.
+ * Locate the running server for `projectPath` and return its HTTP origin —
+ * the lock v2 `url` when the holder advertises one (`lockApiOrigin`'s
+ * loopback validation applies), else `http://localhost:<port>`. Polls
+ * briefly because the dispatcher may call this right after
+ * `bridge.project.open`, before the utility's lock file lands. Returns
+ * `null` when no live server resolves within the poll window.
*
* `signal` is checked before each poll iteration so renderer-side cleanup
* (dialog dismiss, payload-keyed reset) bails the busy-wait early instead
@@ -103,7 +107,7 @@ export async function resolveProjectServerOrigin(
if (signal?.aborted) return null;
const lock = deps.readServerLock(lockDir);
if (lock && lock.port > 0 && lock.pid > 0 && deps.isProcessAlive(lock.pid)) {
- return `http://localhost:${lock.port}`;
+ return lockApiOrigin(lock);
}
if (Date.now() >= deadline) {
deps.log?.warn('[branch-info-proxy] gave up waiting for server lock', {
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index fd83f7449..b1c86f331 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -449,6 +449,7 @@ import { buildViewMenuStateDeps, EditorViewMenuStateRegistry } from './view-menu
import { applyThemeToWindow, buildNonDarwinChromeOpts } from './window-chrome.ts';
import {
type BrowserWindowLike,
+ collabUrlFromApiOrigin,
setWindowInstanceLabel,
type UtilityProcessLike,
WindowManager,
@@ -5183,7 +5184,7 @@ function registerIpcHandlers() {
const ctx = wm?.getContextForBrowserWindow(win as unknown as BrowserWindowLike);
if (!ctx) throw new Error('No project context for this window');
return {
- collabUrl: `ws://localhost:${ctx.port}/collab`,
+ collabUrl: collabUrlFromApiOrigin(ctx.apiOrigin),
apiOrigin: ctx.apiOrigin,
projectPath: ctx.projectPath,
projectName: ctx.projectName,
@@ -6467,7 +6468,7 @@ function installDockIcon(instanceLabel: string | null) {
* Two behaviors:
* 1. Any localhost response missing `Access-Control-Allow-Origin` gets
* `*` + `Allow-Methods` + `Allow-Headers` injected. Safe because the
- * server binds 127.0.0.1 only — no remote origin could ever reach it.
+ * filter below admits loopback URLs only — no remote origin is in scope.
* 2. A `405`/`404` to an `OPTIONS` preflight from such a server is rewritten
* to `204 No Content` with the CORS headers so POSTs with a JSON body
* (which trigger a preflight) don't fail before the real request fires.
@@ -6475,6 +6476,13 @@ function installDockIcon(instanceLabel: string | null) {
* Both are gated on hostname (`localhost` / `127.0.0.1`) and on `hasAcao`
* being false — we leave responses from CORS-aware servers (our current
* api-extension + any future release) untouched.
+ *
+ * The filter deliberately stays at `localhost` / `127.0.0.1` even though
+ * `lockApiOrigin` admits other loopbacks (`[::1]`, `127.0.0.x`): pre-CORS CLI
+ * servers — the only servers this injector exists for — could only ever bind
+ * those two addresses, and any server new enough to take a non-default
+ * loopback bind is new enough to emit native CORS headers. Widening the
+ * filter would guard an unreachable version-skew combination.
*/
function installLocalhostCorsInjector() {
session.defaultSession.webRequest.onHeadersReceived(
diff --git a/packages/desktop/src/main/keepalive.test.ts b/packages/desktop/src/main/keepalive.test.ts
index c2b1ae128..e5e80c6d2 100644
--- a/packages/desktop/src/main/keepalive.test.ts
+++ b/packages/desktop/src/main/keepalive.test.ts
@@ -1,6 +1,10 @@
import { describe, expect, test } from 'vitest';
import type { DesktopLogger } from './desktop-logger.ts';
-import { createDesktopKeepaliveFactory, toKeepaliveLogger } from './keepalive.ts';
+import {
+ createDesktopKeepaliveFactory,
+ resolveKeepaliveWsOrigin,
+ toKeepaliveLogger,
+} from './keepalive.ts';
import type { ServerLockMetadataLike } from './window-manager.ts';
const FAKE_LOCK: ServerLockMetadataLike = {
@@ -78,6 +82,35 @@ describe('createDesktopKeepaliveFactory', () => {
});
});
+describe('resolveKeepaliveWsOrigin', () => {
+ test('prefers the lock v2 url — a non-default loopback bind keeps its keepalive', () => {
+ expect(resolveKeepaliveWsOrigin({ ...FAKE_LOCK, url: 'http://[::1]:51234' })).toBe(
+ 'ws://[::1]:51234',
+ );
+ expect(resolveKeepaliveWsOrigin({ ...FAKE_LOCK, url: 'http://127.0.0.2:51234' })).toBe(
+ 'ws://127.0.0.2:51234',
+ );
+ });
+
+ test('pre-v2 lock (no url) falls back to ws://localhost:<port>', () => {
+ expect(resolveKeepaliveWsOrigin(FAKE_LOCK)).toBe('ws://localhost:51234');
+ });
+
+ test('a non-loopback url is refused by validation and falls back to the port', () => {
+ // The url string comes off disk — `lockApiOrigin` only honors http(s) +
+ // loopback hosts, so a tampered/foreign advertisement degrades to the
+ // legacy port dial instead of pointing the keepalive off-machine.
+ expect(resolveKeepaliveWsOrigin({ ...FAKE_LOCK, url: 'http://evil.example:80' })).toBe(
+ 'ws://localhost:51234',
+ );
+ });
+
+ test('no lock / pre-listen port sentinel resolve to undefined (back off and retry)', () => {
+ expect(resolveKeepaliveWsOrigin(null)).toBeUndefined();
+ expect(resolveKeepaliveWsOrigin({ ...FAKE_LOCK, port: 0 })).toBeUndefined();
+ });
+});
+
describe('toKeepaliveLogger', () => {
type Call = { data: Record<string, unknown>; msg: string };
diff --git a/packages/desktop/src/main/keepalive.ts b/packages/desktop/src/main/keepalive.ts
index beda502da..4f309aede 100644
--- a/packages/desktop/src/main/keepalive.ts
+++ b/packages/desktop/src/main/keepalive.ts
@@ -27,7 +27,7 @@ import {
startKeepalive,
} from '@inkeep/open-knowledge-core/keepalive';
import type { DesktopLogger } from './desktop-logger.ts';
-import type { ServerLockMetadataLike } from './window-manager.ts';
+import { lockWsOrigin, type ServerLockMetadataLike } from './window-manager.ts';
/**
* Adapt a pino-style `DesktopLogger` (`(data, msg)`) to the core
@@ -68,6 +68,21 @@ export interface CreateDesktopKeepaliveOpts {
lockDir: string;
}
+/**
+ * WS base origin for the keepalive dial, from the lock's v2 advertisement.
+ * Derives via `lockWsOrigin` (the lock's `url` when usable, `port` fallback
+ * for pre-v2 locks) — a hardcoded `ws://localhost:<port>` would miss a server
+ * bound to a non-default loopback (`::1`, `127.0.0.2`), silently dropping the
+ * keepalive and letting idle-shutdown reap the server under an open window.
+ * `undefined` (no lock yet / pre-listen port sentinel) tells the core
+ * keepalive to back off and re-resolve.
+ */
+export function resolveKeepaliveWsOrigin(lock: ServerLockMetadataLike | null): string | undefined {
+ if (!lock) return undefined;
+ if (typeof lock.port !== 'number' || lock.port <= 0) return undefined;
+ return lockWsOrigin(lock);
+}
+
/**
* Pure factory — returns a `createKeepalive` callback compatible with
* `WindowManagerDeps.createKeepalive`. Production wiring captures
@@ -79,12 +94,7 @@ export function createDesktopKeepaliveFactory(
return (opts) => {
const connectionId = randomUUID();
return startKeepalive({
- resolveWsUrl: async () => {
- const lock = deps.readServerLock(opts.lockDir);
- if (!lock) return undefined;
- if (typeof lock.port !== 'number' || lock.port <= 0) return undefined;
- return `ws://localhost:${lock.port}`;
- },
+ resolveWsUrl: async () => resolveKeepaliveWsOrigin(deps.readServerLock(opts.lockDir)),
connectionId,
pid: process.pid,
// Presence-invisibility: intentionally omit displayName, clientName,
diff --git a/packages/desktop/src/main/resolve-detached-spawn-args.test.ts b/packages/desktop/src/main/resolve-detached-spawn-args.test.ts
index 390f00696..2f71e5b49 100644
--- a/packages/desktop/src/main/resolve-detached-spawn-args.test.ts
+++ b/packages/desktop/src/main/resolve-detached-spawn-args.test.ts
@@ -178,16 +178,19 @@ describe('resolveDetachedSpawnArgs', () => {
expect(opts.cwd).toBe('/tmp/some-project');
});
- test('args invoke the bundled CLI with start + content-asset serving + the react shell dist dir', () => {
+ test('args invoke the bundled CLI with start + the react shell dist dir', () => {
const { args } = resolveDetachedSpawnArgs(makeInput());
expect(args).toEqual([
'--max-old-space-size=16384',
`${PARENT_APP}/Contents/Resources/app.asar.unpacked/dist/cli.mjs`,
'start',
- '--serve-content-assets',
'--react-shell-dist-dir',
`${PARENT_APP}/Contents/Resources/app`,
]);
+ // The spawned server is the canonical single-listener: content assets are
+ // served by default on every CLI boot path, so the sibling-era
+ // `--serve-content-assets` flag must not come back.
+ expect(args).not.toContain('--serve-content-assets');
});
// Ephemeral single-file mode (`ok <file>`): the resolver appends
@@ -205,7 +208,6 @@ describe('resolveDetachedSpawnArgs', () => {
'--max-old-space-size=16384',
`${PARENT_APP}/Contents/Resources/app.asar.unpacked/dist/cli.mjs`,
'start',
- '--serve-content-assets',
'--react-shell-dist-dir',
`${PARENT_APP}/Contents/Resources/app`,
'--single-file',
diff --git a/packages/desktop/src/main/resolve-detached-spawn-args.ts b/packages/desktop/src/main/resolve-detached-spawn-args.ts
index b9b1e6b54..386a55283 100644
--- a/packages/desktop/src/main/resolve-detached-spawn-args.ts
+++ b/packages/desktop/src/main/resolve-detached-spawn-args.ts
@@ -194,7 +194,12 @@ export function resolveDetachedSpawnArgs(
'--max-old-space-size=16384',
bundleCliMjsPath,
'start',
- '--serve-content-assets',
+ // No `--serve-content-assets`: the bundled CLI (always version-matched to
+ // this build) serves content assets on every boot path by default. The
+ // explicit shell dir stays — resolving the shell from inside app.asar is
+ // not guaranteed by the packaging layout, and the flag makes the spawned
+ // server the canonical single-listener (it advertises `url` +
+ // `capabilities: ["ui"]` in server.lock).
'--react-shell-dist-dir',
reactShellDistDir,
...(singleFile !== undefined
diff --git a/packages/desktop/src/main/terminal-window.test.ts b/packages/desktop/src/main/terminal-window.test.ts
index f5b2555de..30ca86a03 100644
--- a/packages/desktop/src/main/terminal-window.test.ts
+++ b/packages/desktop/src/main/terminal-window.test.ts
@@ -200,7 +200,7 @@ describe('createTerminalWindow', () => {
});
describe('resolveTerminalWindowProject', () => {
- test('an editor window context wins, deriving the collab URL from its port', () => {
+ test('an editor window context wins, deriving the collab URL from its apiOrigin', () => {
expect(
resolveTerminalWindowProject({
editor: {
@@ -219,6 +219,25 @@ describe('resolveTerminalWindowProject', () => {
});
});
+ test('a non-localhost apiOrigin (lock v2 url, ::1 bind) carries into the collab URL', () => {
+ expect(
+ resolveTerminalWindowProject({
+ editor: {
+ projectPath: '/Users/me/proj',
+ projectName: 'proj',
+ port: 5200,
+ apiOrigin: 'http://[::1]:5200',
+ },
+ terminal: undefined,
+ }),
+ ).toEqual({
+ projectPath: '/Users/me/proj',
+ projectName: 'proj',
+ collabUrl: 'ws://[::1]:5200/collab',
+ apiOrigin: 'http://[::1]:5200',
+ });
+ });
+
test('a focused terminal window inherits its registry context (chaining)', () => {
expect(
resolveTerminalWindowProject({
diff --git a/packages/desktop/src/main/terminal-window.ts b/packages/desktop/src/main/terminal-window.ts
index 941721663..33468fcd4 100644
--- a/packages/desktop/src/main/terminal-window.ts
+++ b/packages/desktop/src/main/terminal-window.ts
@@ -24,7 +24,7 @@ import {
type TerminalWindowContext,
unregisterTerminalWindow,
} from './terminal-window-registry.ts';
-import type { BrowserWindowLike } from './window-manager.ts';
+import { type BrowserWindowLike, collabUrlFromApiOrigin } from './window-manager.ts';
/** A created window exposing the numeric `id` the reap + registry wiring needs.
* The real Electron `BrowserWindow` always has `id`; `BrowserWindowLike` omits
@@ -131,12 +131,13 @@ interface EditorProjectContext {
/**
* Resolve the project a new terminal window inherits from the focused window.
- * An editor window's context (from `windowsByPath`) wins — its collab URL is
- * derived from the port the same way editor windows build their `--ok-collab-url`
- * argv. Otherwise a focused terminal window's registry context lets "New
- * Terminal Window" chain within the same project. Returns null when neither
- * resolves (the Navigator, no focused window, or a project-less terminal window)
- * so the new window opens project-less (home cwd).
+ * An editor window's context (from `windowsByPath`) wins — its collab URL
+ * derives from the context's `apiOrigin` (the lock v2 `url` in attach mode)
+ * via the same helper the editor's own dials use. Otherwise a focused
+ * terminal window's registry context lets "New Terminal Window" chain within
+ * the same project. Returns null when neither resolves (the Navigator, no
+ * focused window, or a project-less terminal window) so the new window opens
+ * project-less (home cwd).
*/
export function resolveTerminalWindowProject(args: {
readonly editor: EditorProjectContext | null;
@@ -146,7 +147,7 @@ export function resolveTerminalWindowProject(args: {
return {
projectPath: args.editor.projectPath,
projectName: args.editor.projectName,
- collabUrl: `ws://localhost:${args.editor.port}/collab`,
+ collabUrl: collabUrlFromApiOrigin(args.editor.apiOrigin),
apiOrigin: args.editor.apiOrigin,
};
}
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 8543813ea..ba40d997e 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -313,9 +313,37 @@ export function lockApiOrigin(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>
return `http://localhost:${lock.port}`;
}
+/**
+ * http(s) origin → ws(s) origin. The single scheme-swap primitive — every
+ * desktop WS dial (lock-shaped or already-resolved `apiOrigin` string)
+ * derives from this so `https` → `wss` can never silently diverge between
+ * surfaces. Module-private: external callers go through `lockWsOrigin` /
+ * `collabUrlFromApiOrigin`, which carry the validated-origin guarantee.
+ */
+function httpOriginToWsOrigin(origin: string): string {
+ return origin.replace(/^http/, 'ws');
+}
+
+/**
+ * WebSocket origin for a lock holder — `lockApiOrigin` with the ws(s) scheme,
+ * so the v2 `url` preference and its port fallback carry into every WS dial.
+ */
+export function lockWsOrigin(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>): string {
+ return httpOriginToWsOrigin(lockApiOrigin(lock));
+}
+
+/**
+ * `/collab` WebSocket endpoint for an already-resolved http(s) origin.
+ * Consumers holding a `ProjectContext.apiOrigin` (the lock v2 `url` in attach
+ * mode) call this instead of restating the scheme swap.
+ */
+export function collabUrlFromApiOrigin(apiOrigin: string): string {
+ return `${httpOriginToWsOrigin(apiOrigin)}/collab`;
+}
+
/** `/collab` WebSocket endpoint derived from the same origin as `lockApiOrigin`. */
export function lockCollabUrl(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>): string {
- return `${lockApiOrigin(lock).replace(/^http/, 'ws')}/collab`;
+ return collabUrlFromApiOrigin(lockApiOrigin(lock));
}
interface ProjectContext {
@@ -2719,7 +2747,14 @@ export class WindowManager {
const apiOrigin = lockApiOrigin(lock);
this.deps.log?.info(
- { projectPath, holderPid: lock.pid, port, startedAt: lock.startedAt },
+ {
+ projectPath,
+ holderPid: lock.pid,
+ port,
+ startedAt: lock.startedAt,
+ apiOrigin,
+ capabilities: lock.capabilities,
+ },
'attaching to existing OpenKnowledge server',
);
diff --git a/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts b/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts
index a43ec00be..269bd5292 100644
--- a/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts
+++ b/packages/desktop/tests/integration/ephemeral-lifecycle.test.ts
@@ -121,7 +121,8 @@ describe('ephemeral single-file lifecycle (real CLI)', () => {
// the `localhost` default; the host is irrelevant to G4 / teardown).
'--host',
'127.0.0.1',
- '--serve-content-assets',
+ // No `--serve-content-assets` — mirrors the production spawn shape;
+ // content-asset serving is the CLI default on every boot path.
'--react-shell-dist-dir',
SHELL_DIST_PATH,
'--no-color',
diff --git a/packages/desktop/tests/main/lock-api-origin-parity.test.ts b/packages/desktop/tests/main/lock-api-origin-parity.test.ts
index c1dff6b05..8fd3271be 100644
--- a/packages/desktop/tests/main/lock-api-origin-parity.test.ts
+++ b/packages/desktop/tests/main/lock-api-origin-parity.test.ts
@@ -1,6 +1,10 @@
import { lockBaseUrl } from '@inkeep/open-knowledge-server';
import { describe, expect, test } from 'vitest';
-import { lockApiOrigin, lockCollabUrl } from '../../src/main/window-manager';
+import {
+ collabUrlFromApiOrigin,
+ lockApiOrigin,
+ lockCollabUrl,
+} from '../../src/main/window-manager';
/**
* Pins the hand-maintained mirror in `window-manager.ts` to the canonical
@@ -50,5 +54,16 @@ describe('lockApiOrigin parity with the canonical lockBaseUrl', () => {
expect(lockCollabUrl({ port: 4123, url: 'http://evil.example.com:9999' })).toBe(
'ws://localhost:4123/collab',
);
+ // https must map to wss — pins the scheme swap against a future narrowing
+ // to /^http:/ that would silently break secure-loopback locks.
+ expect(lockCollabUrl({ port: 4123, url: 'https://127.0.0.1:9999' })).toBe(
+ 'wss://127.0.0.1:9999/collab',
+ );
+ });
+
+ test('an apiOrigin-string consumer derives the same collab URL as the lock-shaped helper', () => {
+ const lock = { port: 4123, url: 'https://[::1]:9999' };
+ expect(collabUrlFromApiOrigin(lockApiOrigin(lock))).toBe(lockCollabUrl(lock));
+ expect(collabUrlFromApiOrigin('http://[::1]:9999')).toBe('ws://[::1]:9999/collab');
});
});
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index a5803ca96..1e4968bea 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -793,6 +793,74 @@ describe('WindowManager', () => {
expect(env.createWindowOpts[0]?.additionalArguments).not.toContain('--ok-fresh-create=1');
});
+ // The canonical attach contract (server.lock v2): a shell-serving server
+ // advertises ONE record — `url` plus `capabilities` containing "ui" — and
+ // everything the desktop dials must derive from that record. These pins
+ // are what make it provably safe to retire the `ok ui` sibling + `ui.lock`:
+ // the desktop's attach surface consumes only server.lock.
+
+ test('attach consumes the v2 advertisement end-to-end — probe + renderer args derive from url', async () => {
+ // A ui-capable holder bound to a non-default loopback (::1). If any
+ // dial falls back to a hardcoded localhost:<port>, the attach succeeds
+ // but every subsequent connection misses the server.
+ const probed: string[] = [];
+ enableAttachProbe({
+ readServerLock: () => ({
+ ...liveLock,
+ url: 'http://[::1]:59534',
+ capabilities: ['http', 'ws', 'ui'],
+ }),
+ probeWsUpgrade: (url) => {
+ probed.push(url);
+ return Promise.resolve(true);
+ },
+ });
+ const wm = new WindowManager(env.deps);
+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
+
+ expect(ctx.ownsServer).toBe(false);
+ expect(ctx.apiOrigin).toBe('http://[::1]:59534');
+ // The WS-upgrade health probe dials the advertised origin.
+ expect(probed).toEqual(['ws://[::1]:59534/collab/__attach_probe__']);
+ // The renderer's injected args — the preload/React bundle's only view of
+ // the server — carry the same one-URL derivation.
+ const args = env.createWindowOpts[0]?.additionalArguments ?? [];
+ expect(args).toContain('--ok-api-origin=http://[::1]:59534');
+ expect(args).toContain('--ok-collab-url=ws://[::1]:59534/collab');
+ });
+
+ test('pre-v2 lock (no url) attaches with the localhost:<port> fallback end-to-end', async () => {
+ // Version-skew window: an older server's lock has no `url`. The desktop
+ // must keep attaching via the port so a stable-channel straggler server
+ // still gets a window.
+ const probed: string[] = [];
+ enableAttachProbe({
+ probeWsUpgrade: (url) => {
+ probed.push(url);
+ return Promise.resolve(true);
+ },
+ });
+ const wm = new WindowManager(env.deps);
+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
+
+ expect(ctx.apiOrigin).toBe('http://localhost:59534');
+ expect(probed).toEqual(['ws://localhost:59534/collab/__attach_probe__']);
+ const args = env.createWindowOpts[0]?.additionalArguments ?? [];
+ expect(args).toContain('--ok-api-origin=http://localhost:59534');
+ expect(args).toContain('--ok-collab-url=ws://localhost:59534/collab');
+ });
+
+ test('a non-loopback lock url is refused by validation — dials fall back to the port', async () => {
+ // The url comes off disk; only http(s) + loopback hosts are honored, so
+ // a tampered advertisement cannot point the renderer off-machine.
+ enableAttachProbe({
+ readServerLock: () => ({ ...liveLock, url: 'http://evil.example:80' }),
+ });
+ const wm = new WindowManager(env.deps);
+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/dragon' });
+ expect(ctx.apiOrigin).toBe('http://localhost:59534');
+ });
+
function driftSends(w: ReturnType<typeof makeWindow>): unknown[] {
return (w.webContents.send as ReturnType<typeof vi.fn>).mock.calls.filter(
(c: unknown[]) => c[0] === 'ok:server-version-drift',