Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(ok): verify a foreign lock before serving it (PRD-8260) (#3830)
Andrew Mikofalvyc75a6e534f66
diff --git a/.changeset/stale-server-lock-wedge.md b/.changeset/stale-server-lock-wedge.mdnew file mode 100644index 000000000..f7e2c6de1--- /dev/null+++ b/.changeset/stale-server-lock-wedge.md@@ -0,0 +1,9 @@+---+"@inkeep/open-knowledge": patch+---++A project can no longer get permanently stuck behind a stale server lock. When a project's `server.lock` named a process that was still running but no longer serving — which happens when a second server takes over the lock and the first one is later stopped, for example by an app update relaunch — the desktop app would connect every new window to that dead address. Every document in the project then showed "Connection dropped" and stayed that way: relaunching the app reproduced it exactly, and the in-app "Restart server" button gave up with advice to restart your computer, which could never have helped. One reporter's project was unusable for three days.++When the app starts a server for a project and finds the lock held by some other process, it now checks that the other server is actually reachable before handing it to the window, instead of assuming it is ready. This is the same check the app already made when attaching to a server it did not start. If the check fails, opening the project now reports that a stopped server is holding it and offers to stop that process and retry, rather than opening onto a dead connection.++Clearing such a holder also works from both places it can be met. Previously only the "Restart server" button on an already-open window could recover, which was no help for a project too wedged to open in the first place; the "Stop Server & Retry" button on the failed-open dialog now applies the same rule. In both cases, a process that cannot be stopped but is verifiably not serving has its stale lock cleared so a fresh server can start, and a server that genuinely is serving is still left alone.diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex c53e46647..08fde9f87 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -402,6 +402,7 @@ import {import { handleRevealExternal } from './reveal-external.ts';import { attachServerExitObserver } from './server-exit-observer.ts';import { createServerExitRecorder, type ServerExitRecorder } from './server-exit-record.ts';+import { breakServerLockHeldBy } from './server-lock-break.ts';import { startFirstRunHandshake } from './share-handoff.ts';import { checkOutboundUrl, handleShellOpenExternal } from './shell-allowlist.ts';import { applyHarvestedAuthSock, harvestShellAuthSock } from './shell-env.ts';@@ -444,6 +445,7 @@ import {type UpdateChannel,windowRestoreKey,} from './state-store.ts';+import { quoteStopCommandPath } from './stop-command.ts';import { isTerminalConsented, isTerminalConsentedWithGrace } from './terminal-consent.ts';import { commitTerminalDockState } from './terminal-dock-persistence.ts';import { type TerminalReaper, wireWindowTerminalReap } from './terminal-lifecycle.ts';@@ -2091,6 +2093,17 @@ function ensureWindowManager() {// contentDir, window-manager reads the lock + verifies liveness and// connects the renderer directly instead of trying to spawn a duplicate.readServerLock: (lockDir) => readServerLock(lockDir),+ // Break a stale claim whose holder is both unkillable and not serving —+ // see `removeServerLock` in WindowManagerDeps for when that is reached.+ // Unlinked directly rather than through the server's refcounted+ // `releaseServerLock`, which only releases a lock this process owns.+ //+ // Read-compare-unlink, mirroring `process-lock.ts`'s `registerExitUnlink`:+ // the caller's verdict is about a specific holder and a health probe stands+ // between that verdict and this call, so a successor that acquired the lock+ // meanwhile must keep it. A missing or unparseable file is the desired end+ // state either way.+ removeServerLock: (lockDir, expected) => breakServerLockHeldBy(lockDir, expected),isProcessAlive: (pid) => isProcessAlive(pid),hostname: () => osHostname(),probeWsUpgrade: (url, timeoutMs) => probeWsUpgrade(url, timeoutMs),@@ -2839,6 +2852,18 @@ async function openProjectOrFallbackToNavigator(const errorMessage = (err as Error).message;const kind = (err as Error & { kind?: string }).kind;const holderPid = (err as Error & { holderPid?: number }).holderPid;+ // Which of the two refusals this is. `stale-lock-holder` covers both a+ // holder that answered nothing and a lock whose port we cannot hold a+ // connection open on, and only the second can involve a LIVE holder.+ // Both are only meaningful on `stale-lock-holder`; other kinds reach the+ // shared remedy copy below and must not read a `reason` that is not theirs.+ const isStaleLockHolder = kind === 'stale-lock-holder';+ const staleLockReason = isStaleLockHolder+ ? (err as Error & { reason?: string }).reason+ : undefined;+ const holderIsOwnChild =+ isStaleLockHolder &&+ (err as Error & { holderIsOwnChild?: boolean }).holderIsOwnChild === true;// Route through pino, not only `console.error`: a failure reported solely// to the native dialog leaves nothing in `~/.ok/logs/desktop.*.log`, so a// user who hits this can send logs that contain their successful opens and@@ -2883,6 +2908,18 @@ async function openProjectOrFallbackToNavigator(} else if (kind === 'lock-collision') {dialogTitle = 'OpenKnowledge is already running for this project';dialogBody = `${projectPath}\n\n${errorMessage}`;+ } else if (kind === 'stale-lock-holder') {+ // Distinct from `lock-collision`: that one means a real server has the+ // project and we should not fight it. On the probed arm the holder+ // answered nothing on the port it advertises, so "already running" would+ // be the wrong thing to tell someone whose project has been unopenable+ // for days. The unusable-lock arm never dialed anyone, so it must not+ // borrow that claim — its holder may be perfectly healthy.+ dialogTitle =+ staleLockReason === 'lock-not-attachable'+ ? 'This project\u2019s server lock cannot be used'+ : 'A stopped server is still holding this project';+ dialogBody = `${projectPath}\n\n${errorMessage}`;}// A spawn that timed out because a holder is in the way (fail-closed// collision — visible in the child's stderr tail), or a direct lock@@ -2890,7 +2927,10 @@ async function openProjectOrFallbackToNavigator(// retry. Everything else keeps the plain error box.const holderInTheWay =kind === 'lock-collision' ||+ kind === 'stale-lock-holder' ||(kind === 'spawn-lock-timeout' && errorMessage.includes('already running'));+ // The one arm whose holder was never dialed, so it may be a live server.+ const warnsHolderMayBeLive = staleLockReason === 'lock-not-attachable' && !holderIsOwnChild;if (holderInTheWay) {const { response } = await dialog.showMessageBox({type: 'warning',@@ -2898,9 +2938,18 @@ async function openProjectOrFallbackToNavigator(message: dialogTitle,detail:`${dialogBody}\n\n` +- `OpenKnowledge can stop the conflicting server process and retry opening the project.`,+ (warnsHolderMayBeLive+ ? `OpenKnowledge can stop that process and retry opening the project. It may still be ` ++ `running, so stop it only if you do not need it.`+ : holderIsOwnChild+ ? `OpenKnowledge already asked that server to stop during this open. It can make ` ++ `sure it is gone and try again.`+ : `OpenKnowledge can stop the conflicting server process and retry opening the project.`),buttons: ['Stop Server & Retry', 'Cancel'],- defaultId: 0,+ // Enter lands on the safe path. Everywhere else that is Stop, because+ // the holder is known inert; on the arm that just told the user their+ // process may still be running, the safe path is the other button.+ defaultId: warnsHolderMayBeLive ? 1 : 0,cancelId: 1,});if (response === 0) {@@ -2947,6 +2996,59 @@ async function openProjectOrFallbackToNavigator(: 'Could not stop the conflicting server. Quit it manually (`ok stop`) and try again.'),);}+ } else {+ // Every kind that reaches this dialog gets a decline record. The BOX is+ // scoped narrower on purpose — the collision arms self-remedy in their+ // own message text — but the record's reader is not the box's reader:+ // to an operator reading a bundle, "kind=lock-collision, then silence"+ // cannot distinguish a decline from an app quit mid-modal.+ getLogger('project').info(+ {+ projectPath,+ kind,+ ...(isStaleLockHolder ? { reason: staleLockReason, holderIsOwnChild } : {}),+ holderPid,+ },+ 'user declined the stop-and-retry remedy',+ );+ if (isStaleLockHolder) {+ // Three holder states reach here, not two. On the own-child arm this+ // method signalled that pid during the open the user just asked for,+ // so "nothing was stopped" would be wrong there — but SIGTERM is a+ // request, and the child releases the lock on receiving it, so that+ // arm must not claim the stop completed OR that the lock survived.+ //+ // Quoted because this is a command the user is told to paste: `ok stop`+ // rejoins its own argv, but never sees what the shell already ate. An+ // apostrophe in a folder name hangs at a continuation prompt, and an+ // `&` silently runs against a truncated path and reports success. The+ // quoting is per-platform and lives in its own module, because POSIX+ // single quotes are not a grouping character on `cmd.exe`.+ //+ // The target is the PROJECT PATH, never the pid: `ok stop <path>`+ // resolves the same lockDir this refusal was computed from and stops+ // it without reading `port`, while `ok stop <pid>` goes through a+ // heuristic process scan that can miss, and matches a port before a+ // pid — so on a machine where another project's port equals this+ // holder's pid it stops the wrong one.+ const stopCommandTarget = quoteStopCommandPath(projectPath, process.platform);+ dialog.showErrorBox(+ dialogTitle,+ `${dialogBody}\n\n` ++ (holderIsOwnChild+ ? `OpenKnowledge has signalled that server to stop. Open the project again. If ` ++ `this keeps happening, the server is advertising a port it cannot serve on — ` ++ `there is no way around that from here, so please send a report from ` ++ `Help > Report a bug.`+ : warnsHolderMayBeLive+ ? `Nothing was stopped. If you need that process, leave it running and open a ` ++ `different project; if you do not, run \`ok stop ${stopCommandTarget}\` and ` ++ `open the project again, or reopen and choose Stop Server & Retry.`+ : `Nothing was stopped. Run \`ok stop ${stopCommandTarget}\` and open the ` ++ `project again, or reopen and choose Stop Server & Retry to have ` ++ `OpenKnowledge do it.`),+ );+ }}openNavigator();return;diff --git a/packages/desktop/src/main/server-lock-break.ts b/packages/desktop/src/main/server-lock-break.tsnew file mode 100644index 000000000..c776c7399--- /dev/null+++ b/packages/desktop/src/main/server-lock-break.ts@@ -0,0 +1,45 @@+import { readFileSync, unlinkSync } from 'node:fs';+import { join } from 'node:path';++/**+ * Break a project's `server.lock` on behalf of a caller that has decided its+ * holder is both unkillable and not serving.+ *+ * Its own module so the desktop's window-manager wiring and the tests exercise+ * the SAME function. `index.ts` bootstraps Electron at module scope and cannot+ * be imported from Vitest, so an inline arrow there can only ever be tested by+ * hand-copying it — which pins the copy, not the code that ships.+ *+ * Read-compare-unlink, mirroring `process-lock.ts`'s `registerExitUnlink`. The+ * caller's verdict is about a specific holder and a health probe stands between+ * that verdict and this call, so a successor that acquired the lock meanwhile+ * must keep it.+ *+ * Returns whether this call removed the lock, so the caller can report what+ * actually happened rather than what it intended. Never throws: it is reached+ * only on a recovery path whose whole purpose is to un-wedge a project, and a+ * read-only directory or a held file there must degrade to "could not break it"+ * rather than replace a stuck project with a crashed one.+ */+export function breakServerLockHeldBy(lockDir: string, expected: { pid: number }): boolean {+ const lockPath = join(lockDir, 'server.lock');+ let holderPid: unknown;+ try {+ holderPid = (JSON.parse(readFileSync(lockPath, 'utf-8')) as { pid?: unknown })?.pid;+ } catch {+ // Gone or unparseable. Gone is the end state we wanted; unparseable is not a+ // claim we can confirm is the one we judged, and `runClean` already prunes+ // corrupt locks on boot. Either way, not ours to break.+ return false;+ }+ if (holderPid !== expected.pid) return false;+ try {+ unlinkSync(lockPath);+ return true;+ } catch {+ // ENOENT means someone released it between the read and here, which is the+ // end state we wanted but not a removal WE performed. Anything else is a+ // real IO failure the caller has to survive.+ return false;+ }+}diff --git a/packages/desktop/src/main/stop-command.test.ts b/packages/desktop/src/main/stop-command.test.tsnew file mode 100644index 000000000..433e3b479--- /dev/null+++ b/packages/desktop/src/main/stop-command.test.ts@@ -0,0 +1,56 @@+import { describe, expect, test } from 'vitest';+import { quoteStopCommandPath } from './stop-command.ts';++describe('quoteStopCommandPath', () => {+ // The two shapes that make an unquoted paste fail, and fail differently: an+ // apostrophe strands the user at a continuation prompt, and an ampersand+ // truncates the path, runs against the wrong lock dir, and reports success.+ describe('posix', () => {+ test.each([+ ['plain', '/Users/me/notes', "'/Users/me/notes'"],+ ['space', '/Users/me/My Notes', "'/Users/me/My Notes'"],+ ['ampersand', '/Users/me/Work & Personal', "'/Users/me/Work & Personal'"],+ ['apostrophe', "/Users/bob/Bob's Notes", "'/Users/bob/Bob'\\''s Notes'"],+ ['dollar', '/Users/me/$HOME-ish', "'/Users/me/$HOME-ish'"],+ ['backtick', '/Users/me/`whoami`', "'/Users/me/`whoami`'"],+ ])('%s', (_label, input, expected) => {+ expect(quoteStopCommandPath(input, 'darwin')).toBe(expected);+ });++ // The property the table encodes: whatever a POSIX shell does to this+ // string, the argument that reaches `ok stop` is the path we started with.+ test('linux quotes identically to darwin', () => {+ const p = "/srv/Bob's & Co/notes";+ expect(quoteStopCommandPath(p, 'linux')).toBe(quoteStopCommandPath(p, 'darwin'));+ });+ });++ describe('win32', () => {+ // Single quotes are not a grouping character in `cmd.exe`, so POSIX quoting+ // here would survive into the argument verbatim and resolve to a path that+ // does not exist — reported as "no running processes" at exit 0, on the+ // project the user is looking at, by the command the app just gave them.+ test.each([+ ['plain', 'C:\\Users\\me\\notes'],+ ['space', 'C:\\Users\\First Last\\notes'],+ ['ampersand', 'C:\\Users\\me\\Work & Personal'],+ ['apostrophe', "C:\\Users\\O'Brien\\notes"],+ ])('%s wraps in double quotes with nothing escaped', (_label, input) => {+ expect(quoteStopCommandPath(input, 'win32')).toBe(`"${input}"`);+ });++ // A drive root is a supported project location — `folder-admission.ts`+ // warns on `C:\` and admits it — and it is the reachable case where the+ // receiving parser, not the shell, mangles the argument: an odd run of+ // backslashes before the closing quote yields a literal `"` and leaves+ // quote mode on, so `"C:\"` arrives as `C:"`.+ test.each([+ ['drive root', 'C:\\', '"C:\\\\"'],+ ['trailing backslash', 'C:\\Users\\me\\notes\\', '"C:\\Users\\me\\notes\\\\"'],+ ['two trailing', 'C:\\a\\\\', '"C:\\a\\\\\\\\"'],+ ['interior only', 'C:\\a\\b', '"C:\\a\\b"'],+ ])('%s doubles only a trailing backslash run', (_label, input, expected) => {+ expect(quoteStopCommandPath(input, 'win32')).toBe(expected);+ });+ });+});diff --git a/packages/desktop/src/main/stop-command.ts b/packages/desktop/src/main/stop-command.tsnew file mode 100644index 000000000..c4b5bc77a--- /dev/null+++ b/packages/desktop/src/main/stop-command.ts@@ -0,0 +1,58 @@+/**+ * The `ok stop <path>` command string the failed-open dialog tells a user to+ * paste. Its own module because the dialog lives in `index.ts`, which+ * bootstraps Electron at import and so cannot be reached from a test.+ */++/**+ * POSIX single-quote escaping: wrap in `'…'`, embedded single quotes become+ * `'\''`. Nothing is interpreted inside single quotes, so spaces, `$`,+ * backticks, `;` and newlines are all covered by construction.+ */+function posixQuote(value: string): string {+ return `'${value.replaceAll("'", "'\\''")}'`;+}++/**+ * Windows double-quoting. `"` groups in both `cmd.exe` and PowerShell and is a+ * reserved character in Windows filenames, so there is nothing inside to+ * escape — except a trailing backslash run, which is not about the shell at+ * all. `CommandLineToArgvW` treats backslashes as special only immediately+ * before a `"`: an even run toggles quote mode, an odd run yields a literal+ * `"` and stays in it. So `"C:\"` reaches the process as the single argument+ * `C:"`. Doubling the trailing run restores the even count.+ *+ * A drive root is exactly that shape and is a supported project location —+ * `folder-admission.ts` warns on `C:\` and admits it.+ */+function windowsQuote(value: string): string {+ return `"${value.replace(/(\\+)$/, '$1$1')}"`;+}++/**+ * Quote a project path for a command the USER will paste into their own shell.+ *+ * The shell is not ours to choose, so this is a per-platform best answer rather+ * than a universally correct one: POSIX gets single quotes, which are fully+ * literal; Windows gets double quotes, which group in both of its shells.+ *+ * Two known gaps remain on Windows, and this list is the set that has been+ * looked for rather than a proof there are no others. Both need a character+ * that is legal in a Windows path AND special inside double quotes:+ *+ * - PowerShell expands `$` and a backtick inside `"…"`. Backtick-escaping them+ * would fix PowerShell and corrupt the identical path under `cmd.exe`, where+ * a backtick is an ordinary character, so there is no single string correct+ * in both shells.+ * - `cmd.exe` substitutes `%name%` inside double quotes, because quoting+ * governs space-grouping there, not `%` expansion. `%%` escapes only in a+ * batch file, not at an interactive prompt.+ *+ * Both fail toward the same place: `ok stop` resolves a path that does not+ * exist and reports no running processes at exit 0. That success-shaped no-op+ * is the outcome this module exists to stop producing, which is why the+ * reachable trailing-backslash case is fixed rather than listed here.+ */+export function quoteStopCommandPath(projectPath: string, platform: NodeJS.Platform): string {+ return platform === 'win32' ? windowsQuote(projectPath) : posixQuote(projectPath);+}diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex cd236547f..946510dde 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -73,6 +73,58 @@ const DEFAULT_SPAWN_STARTUP_DEADLINE_MS = 15_000;*/const SPAWN_WAIT_EXTENSION_FACTOR = 8;+/**+ * How many times a foreign lock is probed before a caller acts on the answer,+ * and how long it waits between tries. Shared by the detached-spawn gate and+ * the recovery that breaks a stale claim. See `probeForeignLockWithGrace`.+ */+const FOREIGN_LOCK_PROBE_ATTEMPTS = 3;+const FOREIGN_LOCK_PROBE_RETRY_MS = 500;++/**+ * Which decision a health probe is informing. The `desktop-attach-refused`+ * event predates every caller but the attach gate, so without this a bundle+ * reads a restart-recovery refusal and an attach-gate refusal as the same+ * verdict twice on one port.+ */+type ProbePhase = 'attach' | 'spawn-foreign-lock' | 'restart-recovery' | 'force-stop-recovery';++/**+ * Whether a lock's `port` is something we can actually dial.+ *+ * `lock.port` is TYPED `number` but never validated at runtime on this path:+ * `readProcessLock` checks only `pid` and then casts. So `undefined`, `Infinity`,+ * `70000`, `1.5` and even a string all reach us, and every one of them survives+ * a `port <= 0` test — `undefined <= 0` is a NaN comparison, hence `false`.+ * Each then formats into `http://localhost:undefined`-shaped garbage, the probe+ * throws, `probeAttachableLock` swallows it as "not serving", and a lock we had+ * no business touching gets unlinked. Testing dialability rather than sign is+ * what closes that.+ */+function isDialablePort(port: unknown): port is number {+ return typeof port === 'number' && Number.isInteger(port) && port > 0 && port <= 65535;+}++/** The two entry states that can meet an unkillable lock holder. */+type RecoveryCaller = 'restart' | 'force-stop';++/**+ * Pairs each recovery entry state's log event with its probe phase, so the two+ * cannot drift apart. Not the single source of the event NAME — the same+ * literals are set independently at the other log sites in these two methods;+ * this owns only the pairing.+ */+const RECOVERY_CALLERS: Record<+ RecoveryCaller,+ { event: 'desktop-server-restart' | 'desktop-force-stop-conflicting-server'; phase: ProbePhase }+> = {+ restart: { event: 'desktop-server-restart', phase: 'restart-recovery' },+ 'force-stop': {+ event: 'desktop-force-stop-conflicting-server',+ phase: 'force-stop-recovery',+ },+};+/*** Cadence (ms) of the ephemeral single-file session's server-liveness poll. An* ephemeral server is a DETACHED process whose lifetime is decoupled from its@@ -312,39 +364,85 @@ export interface ServerLockMetadataLike {draining?: boolean;}+/**+ * The loopback origin a lock's `url` field yields, or `null` when it yields+ * none. Extracted so `lockApiOrigin` and anything reasoning about whether a+ * lock is dialable at all read the SAME precedence — a second copy of this+ * check drifting from the first is how a lock with a good `url` and a garbage+ * `port` came to look unreachable.+ */+function loopbackOriginFromUrl(url: unknown): string | null {+ if (typeof url !== 'string' || url.length === 0) return null;+ let parsed: URL | null = null;+ try {+ parsed = new URL(url);+ } catch {+ return null;+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;+ // WHATWG URL keeps the brackets in `hostname` for IPv6 literals.+ const host = parsed.hostname;+ const loopback =+ host === 'localhost' || host === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);+ return loopback ? parsed.origin : null;+}++/**+ * Whether anything could be listening at what this lock names — the question+ * the BREAK path asks, because breaking without a probe is only safe when the+ * answer is no.+ *+ * Deliberately permissive about `port`. `lockApiOrigin` renders a numeric+ * STRING into `http://localhost:42117`, which is a perfectly live address, so+ * a server can be behind a lock that shape. Treating it as nothing-there would+ * destroy a claim we could have dialed.+ */+function lockMayHaveServer(lock: { port?: unknown; url?: unknown }): boolean {+ if (loopbackOriginFromUrl(lock.url) !== null) return true;+ const port = typeof lock.port === 'string' ? Number(lock.port) : lock.port;+ return isDialablePort(port);+}++/**+ * Whether we can ATTACH to what this lock names — a strictly narrower question+ * than `lockMayHaveServer`, and the reason the two exist separately.+ *+ * A numeric string can have a server behind it, but the session we would build+ * on top cannot carry it: `resolveKeepaliveWsOrigin` returns `undefined` unless+ * `port` is a positive NUMBER, so idle-shutdown reaps the server under an open+ * window. That requirement is unconditional, which is why a good `url` does not+ * rescue a bad `port` here the way it does for `lockMayHaveServer` — dialing+ * once and holding the server alive are different needs, and only the second+ * one is what attaching commits us to. Both doors into attach ask this; the+ * break path asks the looser question and probes rather than assuming dead.+ * `createEphemeralWindow` polls too and is exempt by design, not by omission —+ * its lockDir is freshly synthesized under `os.tmpdir()`, so no foreign lock+ * can ever be there to refuse.+ */+function lockIsAttachable(lock: { port?: unknown }): boolean {+ return isDialablePort(lock.port);+}+/*** Base HTTP origin to dial for a lock holder — prefers the lock's `url`- * (validated: http(s) + loopback hostname only, since the string comes off- * disk and becomes renderer arguments), falling back to `port` for locks- * written by binaries predating the field or whose `url` fails validation.+ * (validated: http(s) + loopback hostname only, since the string comes off disk+ * and becomes renderer arguments), falling back to `port` for locks written by+ * binaries predating the field or whose `url` fails validation.** Drift warning: mirrors `lockBaseUrl`/`dialableLockOrigin` in the server* package's `process-lock.ts`. This module is deliberately structurally* independent of that package (see `ServerLockMetadataLike`), so TypeScript- * cannot catch divergence — parity is pinned by- * `tests/main/lock-api-origin-parity.test.ts`. One deliberate difference:- * the canonical helper returns `null` when nothing is dialable (`port` 0,- * no usable `url`); this one returns `http://localhost:0` — safe because- * every caller reaches it with a post-listen lock (`port > 0` guaranteed),- * also pinned by the parity test.+ * cannot catch divergence — both arms are pinned by+ * `tests/main/lock-api-origin-parity.test.ts`. One deliberate difference, also+ * pinned there: the canonical helper returns `null` when nothing is dialable;+ * this one returns `http://localhost:0`, which is safe only because it is a+ * string for argv and never a reachability claim.*/-export function lockApiOrigin(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>): string {- if (typeof lock.url === 'string' && lock.url.length > 0) {- let parsed: URL | null = null;- try {- parsed = new URL(lock.url);- } catch {- parsed = null;- }- if (parsed && (parsed.protocol === 'http:' || parsed.protocol === 'https:')) {- // WHATWG URL keeps the brackets in `hostname` for IPv6 literals.- const host = parsed.hostname;- const loopback =- host === 'localhost' || host === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);- if (loopback) return parsed.origin;- }- }- return `http://localhost:${lock.port}`;+export function lockApiOrigin(lock: { port?: unknown; url?: unknown }): string {+ // Total by construction: callers that only need a string for argv always get+ // one. It is NOT a claim that the origin is reachable — the decision paths ask+ // `lockMayHaveServer` or `lockIsAttachable`, never this.+ return loopbackOriginFromUrl(lock.url) ?? `http://localhost:${lock.port}`;}/**@@ -376,7 +474,7 @@ export function collabUrlFromApiOrigin(apiOrigin: string): string {}/** `/collab` WebSocket endpoint derived from the same origin as `lockApiOrigin`. */-export function lockCollabUrl(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>): string {+export function lockCollabUrl(lock: { port?: unknown; url?: unknown }): string {return collabUrlFromApiOrigin(lockApiOrigin(lock));}@@ -824,6 +922,35 @@ export interface WindowManagerDeps {* effectively disabled and every call spawns a fresh utility.*/readServerLock?(lockDir: string): ServerLockMetadataLike | null;+ /**+ * Delete a project's `server.lock` outright, breaking a holder's claim+ * without its cooperation. Deliberately NOT the server's `releaseServerLock`,+ * which is refcounted for the OWNING process and no-ops for anyone else.+ *+ * Reached from the two recovery entry states — `restartAttachedServer` (from an+ * open window) and `forceStopConflictingServer` (from the failed-open dialog),+ * once a holder has proven BOTH unkillable (EPERM) and not serving. Both+ * halves are load-bearing: a live server's lock must never be broken, or two+ * servers end up bound to one project.+ *+ * `expected` is the holder the caller decided about, and the implementation+ * MUST re-read the file and unlink only if it still names that pid. The+ * decision takes hundreds of milliseconds (a health probe), and the holder+ * can exit and a fresh server acquire the lock inside that window — an+ * unguarded unlink would delete the newcomer's valid claim on the strength of+ * a verdict about its predecessor. `process-lock.ts`'s `registerExitUnlink`+ * is the same read-compare-unlink shape for the same reason.+ *+ * Returns whether THIS call removed the lock, so the caller logs what happened+ * rather than what it intended.+ *+ * Optional only for back-compat with tests that never reach the recovery.+ * Whether to break a lock is a fact about the HOLDER, so leaving this unwired+ * does not change that verdict — it just makes the break a no-op, and the+ * recreate that follows then fails loudly on the stale lock rather than+ * silently wiring a window to it.+ */+ removeServerLock?(lockDir: string, expected: { pid: number }): boolean;/*** Check whether a pid is alive on this host (EPERM counts as alive per the* `process.kill(pid, 0)` semantics in `isProcessAlive`). Production:@@ -1619,6 +1746,170 @@ export class WindowManager {}}+ /**+ * The one rule for an unkillable lock holder, shared by both entry states+ * that can meet one: `restartAttachedServer` (reached from an OPEN project+ * window) and `forceStopConflictingServer` (reached from the failed-open+ * dialog, when there is no window). Keeping a single rule is the point — a+ * holder that is unrecoverable from one entry state and recoverable from the+ * other is the shape that left a real project unopenable for three days.+ *+ * "Cannot be signalled" and "is serving" are separate facts. EPERM only says+ * the holder exists and is not ours to kill: an MCP-spawned server, or a pid+ * the OS has reused. Nothing else clears that lock either — `runClean` prunes+ * only dead-pid and corrupt locks, and its classifier reads EPERM as alive.+ *+ * So ask the holder — but only once it names somewhere to ask. A lock naming+ * no dialable origin at all is broken outright and breaks without a probe;+ * past that there are three outcomes, not two. A holder that has not bound+ * yet (the `port: 0` boot sentinel) is left+ * alone, because a probe that cannot succeed is not evidence of anything. A+ * holder that answers is a live server we simply do not own; refuse, and let+ * the caller surface the cross-account remedy, because breaking that lock+ * would strand a running server and put a second one on the same project. A+ * holder that answers nothing is stale in effect however alive its pid looks,+ * so break the claim and let the caller proceed.+ *+ * Returns whether the lock was broken. Scoped to `eperm` by the callers: an+ * `other` termination failure says nothing about whether the holder serves.+ */+ private async breakUnservingHolderLock(args: {+ lockDir: string;+ // Only what the decision needs: the identity to guard the unlink on, and+ // enough to address the port. Narrower than `ServerLockMetadataLike` so the+ // force-stop caller, which reads the lock raw precisely because the+ // identity-filtered reader refuses these holders, can pass what it actually+ // parsed instead of casting a partial object into a full one.+ lock: Pick<ServerLockMetadataLike, 'pid' | 'url'> & { port: unknown };+ projectPath: string;+ // ONE discriminator for one fact. The log event and the probe phase are two+ // views of "which entry state is asking", so taking them separately lets a+ // caller pair a restart event with a force-stop phase and nothing would+ // notice. Mapped once, exhaustively, below.+ caller: RecoveryCaller;+ }): Promise<boolean> {+ const { lockDir, lock, projectPath, caller } = args;+ const { event, phase } = RECOVERY_CALLERS[caller];+ // A port of 0 is the acquired-but-not-yet-bound sentinel a lock carries+ // during boot. The probe cannot succeed against it, so it would read as+ // "not serving" and break the lock of a server that is still coming up.+ //+ // This lives in the RULE, not at a caller. The whole point of this helper is+ // that both entry states decide the same way, and a guard installed at one+ // of them leaves the other free to do the damage.+ const port = lock.port;+ // Two different states hide behind "the port is not dialable", and treating+ // them alike gets one of them wrong.+ //+ // `0` is the acquired-but-not-yet-bound sentinel: a server mid-boot, which+ // will have a real port shortly. Leave it alone — it is the one case where+ // waiting is correct.+ //+ // A lock that names nowhere to dial (absent, `Infinity`, out of range, a+ // fraction) cannot denote a listening server at all, so there is nothing to+ // strand and no reason to keep the claim. Refusing here would be worse than+ // useless: nothing else prunes these, so the project would stay wedged —+ // the exact failure this whole change exists to end. A numeric STRING is+ // NOT in this set: it renders into a live address, so it goes to the probe.+ if (!lockMayHaveServer(lock)) {+ if (port === 0) {+ this.deps.log?.warn(+ {+ event,+ outcome: 'eperm-stale-lock-break-skipped',+ reason: 'booting',+ pid: lock.pid,+ projectPath,+ },+ '[window-manager] holder has not bound a port yet — leaving its lock alone',+ );+ return false;+ }+ this.deps.log?.warn(+ // Port carried raw: for a lock this shape the value IS the diagnosis.+ // A DECISION, not the result: the unlink below can still decline or+ // fail, and `-broken` is the value that means it did not.+ {+ event,+ outcome: 'eperm-stale-lock-break-decided',+ reason: 'unservable-origin',+ pid: lock.pid,+ port,+ projectPath,+ },+ '[window-manager] holder names nowhere that could serve — breaking its stale lock',+ );+ return this.unlinkHolderLock({ lockDir, lock, projectPath, event });+ }+ const dialable = { pid: lock.pid, port, url: lock.url };+ // The graced probe, not a single shot. This path is the DESTRUCTIVE one —+ // it deletes another process's claim — so it should not settle for less+ // confidence than the spawn path, which only declines to adopt. A transient+ // refusal here breaks a live server's lock; there it costs a retry.+ if (await this.probeForeignLockWithGrace(dialable, phase)) return false;+ // Identity-guarded: the verdict above is about THIS holder, and the probe+ // it rests on took long enough for that holder to exit and a fresh server+ // to take the lock.+ //+ // Reporting what HAPPENED, not what was intended. The dep is optional, its+ // identity guard can decline, and the unlink can fail on a read-only or+ // otherwise hostile `.ok` directory — claiming "broken" through any of those+ // would tell the next diagnosis the lock is gone when it is still there, the+ // same false-record failure the recovery rule one branch over avoids. It+ // also must not+ // throw: this is the recovery path for a wedged project, and replacing a+ // stuck project with a crashed app is a strictly worse outcome.+ return this.unlinkHolderLock({ lockDir, lock, projectPath, event });+ }++ /**+ * The unlink half of the rule: identity-guarded, non-throwing, and honest+ * about whether it actually removed anything. Shared by both break paths so+ * neither can drift from the other.+ */+ private unlinkHolderLock(args: {+ lockDir: string;+ lock: Pick<ServerLockMetadataLike, 'pid'> & { port?: unknown };+ projectPath: string;+ event: string;+ }): boolean {+ const { lockDir, lock, projectPath, event } = args;+ let broke = false;+ try {+ broke = this.deps.removeServerLock?.(lockDir, { pid: lock.pid }) ?? false;+ } catch (err) {+ this.deps.log?.warn(+ { event, outcome: 'eperm-stale-lock-break-failed', err, pid: lock.pid, projectPath },+ '[window-manager] could not break the stale lock',+ );+ return false;+ }+ if (!broke) {+ this.deps.log?.warn(+ { event, outcome: 'eperm-stale-lock-break-declined', pid: lock.pid, projectPath },+ // Deliberately does not name a cause: the break declines on an identity+ // mismatch, an already-gone file, or a failed unlink, and this layer+ // cannot tell which. Asserting one would be the same false-record+ // failure this path exists to avoid.+ '[window-manager] stale lock was not broken',+ );+ return false;+ }+ this.deps.log?.warn(+ {+ event,+ outcome: 'eperm-stale-lock-broken',+ pid: lock.pid,+ port: lock.port,+ projectPath,+ },+ // Neutral about WHY: the caller has already logged whether the holder+ // failed its probe or advertised a port nothing could serve.+ "[window-manager] broke the unkillable holder's stale lock",+ );+ return true;+ }+/*** Explicit-user-consent recovery: stop whatever process holds this* project's server.lock so a fresh open can proceed. Reached from the@@ -1640,9 +1931,17 @@ export class WindowManager {): Promise<{ ok: true } | { ok: false; reason: 'eperm' | 'other' }> {const lockDir = getLocalDir(resolve(projectPath));let pid: unknown;+ let rawPort: unknown;+ let rawUrl: unknown;try {- pid = (JSON.parse(readFileSync(join(lockDir, 'server.lock'), 'utf-8')) as { pid?: unknown })- ?.pid;+ const raw = JSON.parse(readFileSync(join(lockDir, 'server.lock'), 'utf-8')) as {+ pid?: unknown;+ port?: unknown;+ url?: unknown;+ };+ pid = raw?.pid;+ rawPort = raw?.port;+ rawUrl = raw?.url;} catch {// No lock / unreadable — nothing to stop; the retry will proceed.return { ok: true };@@ -1651,6 +1950,29 @@ export class WindowManager {return { ok: true };}const term = await this.terminateServerByPid(lockDir, pid);+ // The dialog behind this call is the ONLY remedy a user has while the+ // project has no window, so an EPERM dead-end here is terminal in a way the+ // restart path's is not. Same two-fact rule, same safety argument: a holder+ // that answers its port is still refused.+ //+ // The probe target is built from the RAW fields above, NOT `readServerLock`.+ // That reader applies the machine-identity filter this whole method exists+ // to bypass, and it would refuse exactly the holders EPERM implies — a+ // different account, a foreign-looking machineId, a hostname flap — leaving+ // the one no-window remedy silently inert for its most likely cohort.+ if (!term.ok && term.reason === 'eperm') {+ const broke = await this.breakUnservingHolderLock({+ lockDir,+ lock: {+ pid,+ port: rawPort,+ ...(typeof rawUrl === 'string' ? { url: rawUrl } : {}),+ },+ projectPath,+ caller: 'force-stop',+ });+ if (broke) return { ok: true };+ }this.deps.log?.info({event: 'desktop-force-stop-conflicting-server',@@ -1692,28 +2014,45 @@ export class WindowManager {if (lock && isValidLockPidLocal(lock.pid)) {const term = await this.terminateServerByPid(lockDir, lock.pid);if (!term.ok) {- this.deps.log?.warn(+ // Scoped to `eperm` — see `breakUnservingHolderLock` for the rule, and+ // why an `other` failure keeps the conservative refusal.+ const broke =+ term.reason === 'eperm' &&+ (await this.breakUnservingHolderLock({+ lockDir,+ lock,+ projectPath: resolved,+ caller: 'restart',+ }));+ if (!broke) {+ this.deps.log?.warn(+ {+ event: 'desktop-server-restart',+ outcome: term.reason,+ pid: lock.pid,+ projectPath: resolved,+ },+ '[window-manager] server restart could not terminate the attached server',+ );+ return term;+ }+ } else {+ // Only the genuine kill reports `terminated`. The lock-broken path above+ // falls through to the same recreate but terminated nothing, and saying+ // otherwise would misreport the one event a future diagnosis reads to+ // learn whether the old server actually went away.+ this.deps.log?.info({event: 'desktop-server-restart',- outcome: term.reason,+ outcome: 'terminated',+ escalated: term.escalated,pid: lock.pid,+ appRuntime: this.deps.selfRuntimeVersion ?? null,projectPath: resolved,},- '[window-manager] server restart could not terminate the attached server',+ '[window-manager] terminated attached server for restart',);- return term;}- this.deps.log?.info(- {- event: 'desktop-server-restart',- outcome: 'terminated',- escalated: term.escalated,- pid: lock.pid,- appRuntime: this.deps.selfRuntimeVersion ?? null,- projectPath: resolved,- },- '[window-manager] terminated attached server for restart',- );}// Detach the originating window from the map (so the recreate spawns a new// window instead of focusing the old) but keep it open until the new one@@ -2118,8 +2457,135 @@ export class WindowManager {childExited,});}+ // A lock our child did not write is an UNVERIFIED claim, and the readiness+ // this branch is about to declare rests on it. `pollServerLock` accepts a+ // foreign holder deliberately — a concurrent starter that won the acquire+ // is a real server worth sharing, which the losing-child path depends on —+ // but a STALE holder passes every metadata gate that acceptance rests on:+ // right host, valid pid, non-draining, real port, and (because EPERM reads+ // as alive) a liveness check it cannot fail. Only asking the port+ // separates the two, and `spawnProjectWindow`'s attach gate already asks+ // it about this very lock. Not asking here is how one field log recorded+ // both verdicts on the same port 2 ms apart — `desktop-attach-refused`+ // with `reason: 'ws-upgrade-failed'`, then this line calling it ready —+ // and the window opened onto a port answering nothing.+ //+ // Our OWN child is exempt: we watched it come up, so a probe would buy no+ // signal and cost every cold start its timeout.+ const adoptedForeignLock = lock.pid !== handle.pid;+ // Two doors lead into `attachToExistingServer`, and gating only the direct+ // one leaves the other open. `pollServerLock` admits on `lock.port > 0` —+ // a RELATIONAL compare, so `'42117' > 0` coerces true — and this branch+ // then attaches whatever it returned. A lock we cannot carry has to be+ // refused at both doors or the stricter predicate is decoration.+ const unusableLock = !lockIsAttachable(lock);+ if (unusableLock || (adoptedForeignLock && !(await this.probeForeignLockWithGrace(lock)))) {+ // Our child may still be alive here (it can lose the publish race+ // without losing the acquire), and it is `.unref()`ed, so refusing the+ // holder without reaping it leaks an orphan with no parent to reap it —+ // the same hazard the lock-timeout branch above handles, for the same+ // reason. ESRCH just means it already exited.+ const childExited = this.deps.isProcessAlive+ ? !this.deps.isProcessAlive(handle.pid)+ : undefined;+ const childExit = handle.readExit?.() ?? null;+ try {+ this.deps.killProbe(handle.pid, 'SIGTERM');+ } catch (signalErr) {+ const code = (signalErr as NodeJS.ErrnoException).code;+ if (code !== 'ESRCH') {+ this.deps.log?.warn(+ {+ event: 'desktop-spawn-orphan-sigterm-failed',+ err: signalErr,+ code,+ pid: handle.pid,+ projectPath,+ },+ '[window-manager] SIGTERM on orphan after refusing a stale lock failed',+ );+ }+ }+ this.spawnedDetachedPids.delete(canonicalKey);+ this.deps.log?.warn(+ {+ event: 'desktop-server-spawn-refused-stale-lock',+ reason: unusableLock ? 'lock-not-attachable' : 'holder-not-serving',+ pid: handle.pid,+ lockPid: lock.pid,+ port: lock.port,+ // `port` alone cannot name which shape refused this. Under pino's+ // JSON semantics `undefined` drops the key and `Infinity` becomes+ // `null`, so a bundle showing `"port": null` cannot distinguish a+ // writer that set nothing from one that computed `Infinity` — two+ // different upstream bugs. These two survive serialization.+ portType: typeof lock.port,+ rawPort: String(lock.port),+ lockDir,+ projectPath,+ },+ '[window-manager] refusing to attach the spawn to a lock we cannot use',+ );+ // Its OWN error kind, deliberately not `buildSpawnFailureError`. That+ // one narrates a deadline and the child's exit, and nothing here is a+ // deadline: `pollServerLock` returned on its first read, so reporting+ // the tier that was never served would blame a 15 s timeout that did+ // not elapse, on our own healthy child's pid, and never mention the+ // holder. It also would not reach the remedy — the failed-open dialog+ // gates Stop Server & Retry on the kind, so a refusal that wants that+ // button has to say what it actually is.+ // `||` short-circuits, so on the unusable-lock arm the holder was never+ // dialed. Reporting "is not serving" there states a probe result that+ // does not exist, and the failed-open dialog quotes this message+ // verbatim — the user would consent to stopping a process on the claim+ // it is already inert. The holder framing has to move too: `unusableLock`+ // is deliberately not exempted for our own child the way the probe is,+ // so "another process" can be our own healthy spawn.+ const holder = adoptedForeignLock+ ? `Another process (pid ${lock.pid})`+ : `The server OpenKnowledge just started (pid ${lock.pid})`;+ throw Object.assign(+ new Error(+ unusableLock+ ? `${holder} holds this project's server lock, but the lock does not name a port ` ++ `OpenKnowledge can keep a connection open on (${String(lock.port)}).`+ : `${holder} holds this project's server lock but is not serving on port ${lock.port}.`,+ ),+ {+ name: 'StaleLockHolderError',+ kind: 'stale-lock-holder' as const,+ reason: unusableLock+ ? ('lock-not-attachable' as const)+ : ('holder-not-serving' as const),+ // The unusable arm is not exempted for our own spawn the way the+ // probe is, so the holder here can be the child this method just+ // SIGTERMed. Asking the user whether they still need a process we+ // killed for them, from the request they just made, has no answer+ // they could act on — the dialog drops that clause when this is set.+ holderIsOwnChild: !adoptedForeignLock,+ holderPid: lock.pid,+ holderPort: lock.port,+ pid: handle.pid,+ childExited,+ exitCode: childExit?.code ?? null,+ exitSignal: childExit?.signal ?? null,+ },+ );+ }this.deps.log?.info(- { event: 'desktop-server-spawned-detached', pid: handle.pid, port: lock.port, lockDir },+ {+ event: 'desktop-server-spawned-detached',+ pid: handle.pid,+ // `pid` and `port` come from different sources — our child handle and+ // whoever holds the lock. Recording `lockPid` and how the claim was+ // established keeps the pair auditable: without them this record+ // cannot distinguish "our child came up" from "we adopted a+ // stranger's lock", which is precisely the confusion it caused.+ lockPid: lock.pid,+ readiness: adoptedForeignLock ? 'foreign-lock-probe-verified' : 'own-child',+ port: lock.port,+ lockDir,+ },'[window-manager] detached server ready',);// Startup waterfall: the detached server's lock is now readable — carry@@ -2366,10 +2832,10 @@ export class WindowManager {});}- // (The dev reclaim path used to deliver a "started a fresh server" notice- // here; both it and the packaged upgrade reconcile now terminate + respawn- // silently, so no server-lifecycle toast is delivered on this dev/test-only- // utility-fork branch.)+ // (No "started a fresh server" notice here: the dev reclaim path and the+ // packaged upgrade reconcile both terminate + respawn silently, so no+ // server-lifecycle toast is delivered on this dev/test-only utility-fork+ // branch.)// Defer OS-level window display until both first-paint AND chrome-theme// signals arrive — `show: false` in DEFAULT_WIN_OPTS hides the native@@ -3188,7 +3654,13 @@ export class WindowManager {// Attaching would bind the window to a dying backend — fall through to// spawn mode, whose `ok start` child waits out the drain.if (lock.draining === true) return refuse('lock-draining');- if (lock.port <= 0) return refuse('lock-port-zero');+ // A STRICTER question than the recovery rule's: not whether anything could+ // be there, but whether we could HOLD it. A numeric string passes the first+ // and fails this one. Deliberately decided on `port` alone even when the+ // `url` is perfectly good, because the keepalive reads the port and nothing+ // else; `port <= 0` would not do, since it admits `Infinity` to be formatted+ // into a probe URL nothing can answer.+ if (!lockIsAttachable(lock)) return refuse('lock-not-attachable');if (lock.kind === undefined) return refuse('legacy-lock-no-kind');if (lock.capabilities !== undefined && !lock.capabilities.includes('ws')) {return refuse('capabilities-missing-ws');@@ -3196,6 +3668,39 @@ export class WindowManager {return lock;}+ /**+ * `probeAttachableLock` with a bounded grace, for the callers whose verdict on+ * a failed probe is one-way: the detached-spawn gate fails the open, and the+ * recovery path deletes the holder's claim.+ *+ * The attach path can afford a single shot: a refusal there falls through to+ * spawning our own server, so a false negative costs a redundant spawn. The+ * detached-spawn path has already spawned, so its refusal fails the open —+ * and the lock it is judging belongs to a concurrent starter caught at its+ * youngest. The port-0 sentinel means `port > 0` implies `listen()` has+ * bound, but binding is not the same as serving `/collab`: a hung or+ * mid-wiring upgrade path is the exact symptom `probeAttachableLock` exists+ * for. One 500 ms shot at that moment would refuse healthy winners.+ *+ * Retries are cheap here because the failure they guard against is expensive+ * and one-way, and because a genuinely dead port fails fast on connection+ * refused rather than burning the timeout.+ */+ private async probeForeignLockWithGrace(+ lock: { pid: number; port?: unknown; url?: unknown },+ phase: ProbePhase = 'spawn-foreign-lock',+ ): Promise<boolean> {+ for (let attempt = 1; attempt <= FOREIGN_LOCK_PROBE_ATTEMPTS; attempt++) {+ if (await this.probeAttachableLock(lock, phase)) return true;+ if (attempt < FOREIGN_LOCK_PROBE_ATTEMPTS) {+ await new Promise<void>((resolveSleep) => {+ this.deps.setTimeout(() => resolveSleep(), FOREIGN_LOCK_PROBE_RETRY_MS);+ });+ }+ }+ return false;+ }+/*** Final defensive gate against a server that lies about WS capability or* has a hung upgrade path (the live symptom that motivated all of this:@@ -3207,7 +3712,13 @@ export class WindowManager {* the probe (thrown rejections) are treated as failures — defensive* stance, since we cannot prove the server is healthy.*/- private async probeAttachableLock(lock: ServerLockMetadataLike): Promise<boolean> {+ private async probeAttachableLock(+ // Only the fields the probe reads: the address to dial and the pid to name+ // in the refusal. Narrow so callers holding a partially-parsed lock can ask+ // without fabricating the rest.+ lock: { pid: number; port?: unknown; url?: unknown },+ phase: ProbePhase = 'attach',+ ): Promise<boolean> {const probe = this.deps.probeWsUpgrade;if (!probe) return true;const url = `${lockCollabUrl(lock)}/__attach_probe__`;@@ -3219,7 +3730,17 @@ export class WindowManager {}if (!upgradeOk) {this.deps.log?.warn(- { event: 'desktop-attach-refused', reason: 'ws-upgrade-failed', lockPid: lock.pid },+ {+ event: 'desktop-attach-refused',+ reason: 'ws-upgrade-failed',+ lockPid: lock.pid,+ // Which decision this probe was informing. The event name predates+ // the second caller, and a bundle that cannot tell an attach-gate+ // refusal from a spawn-path one reads as the same verdict twice on+ // one port — the exact confusion that made this class hard to+ // diagnose from logs in the first place.+ phase,+ },'[window-manager] refusing attach',);}diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex c9c6c3612..1ce77ea34 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -1,9 +1,10 @@-import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import { DEFAULT_SERVER_HOST } from '@inkeep/open-knowledge-core';import { beforeEach, describe, expect, test, vi } from 'vitest';+import { breakServerLockHeldBy } from '../../src/main/server-lock-break.ts';import type { ShowGateRegistry } from '../../src/main/show-gate.ts';import {type BrowserWindowLike,@@ -1195,6 +1196,379 @@ describe('WindowManager', () => {expect(env.utilities.length).toBe(0);});+ // "Cannot be signalled" and "is not serving" are separate facts, and the+ // restart path stops at the first one: `terminateServerByPid` reports+ // `{ ok: false, reason: 'eperm' }` when `killProbe` throws EPERM, and+ // `restartAttachedServer` returns that verbatim with no fallback. A lock+ // naming a holder this app cannot signal therefore makes the project+ // unopenable from inside the app even when the port behind that holder+ // answers nothing — and the dialog's Stop Server & Retry runs the same+ // ladder, so there is no user-reachable way out.+ test('restartAttachedServer breaks a stale lock whose unkillable holder serves nothing', async () => {+ // The base env's setTimeout only RECORDS timers, which would deadlock the+ // post-spawn lock poll a successful recreate has to run through.+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const STALE_PID = 870;+ const FRESH_PID = 22018;+ const staleLock = { ...liveLock, pid: STALE_PID, port: 42117 };+ const freshLock = { ...liveLock, pid: FRESH_PID, port: 60222 };+ let spawned = false;+ // The stale lock survives until our own respawn replaces it — the+ // unkillable holder is never going to release it for us.+ env.deps.readServerLock = () => (spawned ? freshLock : staleLock);+ // EPERM reads as alive (`isPidAlive`), so liveness cannot break the tie.+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // 42117 answers nothing; the freshly spawned server does.+ env.deps.probeWsUpgrade = (url) => Promise.resolve(!url.includes('42117'));+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.spawnDetachedServer = () => {+ spawned = true;+ return Promise.resolve({ pid: FRESH_PID });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ // Dead-ending on EPERM is the defect: the holder cannot be signalled AND+ // is not serving, so nothing is lost by breaking its lock.+ expect(outcome).not.toEqual({ ok: false, reason: 'eperm' });+ // …and the recreate proceeds onto the freshly spawned server.+ expect(outcome).toEqual({ ok: true });+ expect(env.windows.length).toBe(1);+ const ctx = wm.getContextForBrowserWindow(env.windows[0] as BrowserWindowLike);+ expect(ctx?.port).toBe(60222);+ // The break itself, not just its consequence. `readServerLock` is stubbed+ // to stop returning the stale record once we respawn, so the recreate+ // would succeed here even if the lock were left on disk — in production it+ // would not, because the fresh server's own acquire re-reads that file and+ // its stale detection reads an EPERM pid as alive. Asserting the call+ // keeps that step from being silently dropped.+ expect(removeServerLock).toHaveBeenCalledTimes(1);+ // The LOCK DIR, not the project root. `removeServerLock` unlinks+ // `<arg>/server.lock` and swallows ENOENT, so handing it the project root+ // silently turns this entire recovery into a no-op — and an assertion+ // that merely contains the project path accepts both.+ expect(removeServerLock.mock.calls[0]?.[0]).toMatch(/[/\\]\.ok[/\\]local$/);+ expect(removeServerLock.mock.calls[0]?.[0]).toContain('/tmp/dragon');+ // The identity guard. A health probe stands between the verdict and this+ // call, which is long enough for the judged holder to exit and a fresh+ // server to take the lock; the implementation re-reads and unlinks only+ // if it still names this pid, so the pid has to travel with the request.+ expect(removeServerLock.mock.calls[0]?.[1]).toEqual({ pid: STALE_PID });+ });++ // The break can fail for reasons that have nothing to do with the holder:+ // a read-only `.ok` directory, a file held by something else. This runs on+ // the path whose whole purpose is to un-wedge a project, so it must degrade+ // to "could not break it" — replacing a stuck project with a crashed app is+ // strictly worse. Nothing pinned this, so deleting the try/catch was+ // invisible to the suite while letting the throw escape an IPC handler.+ test('restartAttachedServer survives a removeServerLock that throws', async () => {+ // The graced probe on the break path retries through `deps.setTimeout`,+ // which the base env only records; drive it so the loop resolves.+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ env.deps.removeServerLock = vi.fn(() => {+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' });+ });+ env.deps.readServerLock = () => ({ ...liveLock, pid: 5151, port: 42117 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ const spawn = vi.fn(() => Promise.resolve({ pid: 22018 }));+ env.deps.spawnDetachedServer = spawn;+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(spawn).not.toHaveBeenCalled();+ expect(env.windows.length).toBe(0);+ });++ // A declined break is not a success. The identity guard can refuse when the+ // lock no longer names the holder we judged, and treating that as "broken"+ // would send the recreate at a lock that is still there.+ test('restartAttachedServer does not proceed when the break is declined', async () => {+ // The graced probe on the break path retries through `deps.setTimeout`,+ // which the base env only records; drive it so the loop resolves.+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => false);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => ({ ...liveLock, pid: 5152, port: 42117 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ const spawn = vi.fn(() => Promise.resolve({ pid: 22018 }));+ env.deps.spawnDetachedServer = spawn;+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(removeServerLock).toHaveBeenCalledTimes(1);+ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(spawn).not.toHaveBeenCalled();+ });++ // The grace on the DESTRUCTIVE path. A transient refusal here deletes a+ // live server's claim, which is why this path retries rather than acting on+ // one answer — but every other recovery test stubs a constant probe, so a+ // reversion to single-shot would be invisible exactly where it costs most.+ test('the break path retries the probe and stands down when a later attempt answers', async () => {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => ({ ...liveLock, pid: 5153, port: 42117 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ let probes = 0;+ // Silent twice, then answers — a holder that was merely slow.+ env.deps.probeWsUpgrade = () => {+ probes++;+ return Promise.resolve(probes >= 3);+ };+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(probes).toBe(3);+ // It answered, so it is a live server we merely cannot kill: refuse, and+ // above all do not break its lock.+ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(removeServerLock).not.toHaveBeenCalled();+ });++ // The guard belongs to the RULE, so both entry states inherit it. Port 0 is+ // the acquired-but-not-yet-bound sentinel: the probe cannot succeed against+ // it, and a probe that cannot succeed would read as "not serving" and break+ // the lock of a server that is merely still coming up.+ test('restartAttachedServer leaves the lock alone when the holder has not bound a port', async () => {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ // port 0 — acquired, still booting.+ env.deps.readServerLock = () => ({ ...liveLock, pid: 5154, port: 0 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ const probe = vi.fn(() => Promise.resolve(false));+ env.deps.probeWsUpgrade = probe;+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(removeServerLock).not.toHaveBeenCalled();+ // Not even probed: there is nothing at port 0 to ask.+ expect(probe).not.toHaveBeenCalled();+ });++ // `port` is typed `number` but never validated at runtime — `readProcessLock`+ // checks only `pid` and casts the rest — so these all arrive in production,+ // and every one survives a `port <= 0` test (`undefined <= 0` is a NaN+ // comparison, hence false).+ //+ // None of them can denote a listening server, so there is nothing to strand+ // by breaking the claim — and refusing would wedge the project forever.+ // `runClean` is not a route out for any of them: its classifier reads only+ // the pid and the file's parseability, never `port`, so a lock advertising+ // `Infinity` is `alive` to it and survives every sweep.+ test.each([+ ['absent', undefined],+ ['Infinity', Number.POSITIVE_INFINITY],+ ['out of range', 70000],+ ['non-integer', 1.5],+ ['a non-numeric string', 'not-a-port'],+ ])('restartAttachedServer breaks a lock whose port is %s', async (_label, port) => {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ let spawned = false;+ env.deps.readServerLock = () =>+ (spawned+ ? { ...liveLock, pid: 22018, port: 60222 }+ : { ...liveLock, pid: 5155, port }) as unknown as ServerLockMetadataLike;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => {+ spawned = true;+ return Promise.resolve({ pid: 22018 });+ };+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: true });+ expect(removeServerLock).toHaveBeenCalledTimes(1);+ });++ // `lockApiOrigin` resolves `url` BEFORE `port`, so an undialable port field+ // on a lock carrying a usable url is not evidence that nothing is behind+ // it. Breaking without asking would destroy a live server's claim on the+ // strength of a field we never dial.+ test('a garbage port does not authorise a break when the lock carries a usable url', async () => {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () =>+ ({+ ...liveLock,+ pid: 5156,+ port: Number.POSITIVE_INFINITY,+ url: 'http://127.0.0.1:42117',+ }) as unknown as ServerLockMetadataLike;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // The url answers: this is a live server we simply cannot kill.+ const probe = vi.fn(() => Promise.resolve(true));+ env.deps.probeWsUpgrade = probe;+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(removeServerLock).not.toHaveBeenCalled();+ // Asked, rather than assumed, and asked at the url.+ expect(probe).toHaveBeenCalled();+ expect(probe.mock.calls[0]?.[0]).toContain('42117');+ });++ // The two questions are not the same question. A numeric string cannot be+ // ATTACHED to — the keepalive is typed on a numeric port — but it renders+ // into `http://localhost:42117`, which is a live address, so a server can be+ // behind it. Breaking without asking would destroy a claim we could dial.+ test('a numeric string port is probed rather than broken, since a server can be behind it', async () => {+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () =>+ ({ ...liveLock, pid: 5158, port: '42117' }) as unknown as ServerLockMetadataLike;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // It answers: a live server we simply cannot kill.+ const probe = vi.fn(() => Promise.resolve(true));+ env.deps.probeWsUpgrade = probe;+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(removeServerLock).not.toHaveBeenCalled();+ expect(probe.mock.calls[0]?.[0]).toContain('42117');+ });++ // The scoping guard. EPERM is the one termination failure that carries+ // information about the holder: it exists and is not ours to signal. An+ // `other` failure carries none, so a dead port alongside it is not evidence+ // the lock is safe to break. Without this, dropping the `term.reason ===+ // 'eperm'` conjunct widens lock-breaking to ANY termination failure and+ // every other test stays green.+ test('restartAttachedServer does not break a lock when termination failed for a non-EPERM reason', async () => {+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => ({ ...liveLock, pid: 5150, port: 42117 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // The port answers nothing — the OTHER half of the rule is satisfied, so+ // only the reason scoping can hold the line here.+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ const spawn = vi.fn(() => Promise.resolve({ pid: 22018 }));+ env.deps.spawnDetachedServer = spawn;+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('kaboom'), { code: 'EIO' });+ });++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'other' });+ expect(removeServerLock).not.toHaveBeenCalled();+ expect(spawn).not.toHaveBeenCalled();+ expect(env.windows.length).toBe(0);+ });++ // The guard on the fix above: EPERM is not license to break a lock. When+ // the unkillable holder is genuinely serving, the eperm refusal is the only+ // correct answer — the renderer surfaces the "running under a different+ // account" remedy — because breaking that lock would strand a live server+ // and the windows connected to it behind a second one on the same project.+ test('restartAttachedServer still refuses eperm when the unkillable holder IS serving', async () => {+ const liveHolderLock = {+ ...liveLock,+ pid: 7777,+ protocolVersion: 1,+ runtimeVersion: '0.8.0',+ };+ const spawn = vi.fn(() => Promise.resolve({ pid: 22018 }));+ env.deps.readServerLock = () => liveHolderLock;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // The port answers: this server is real, just not ours to kill.+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.killProbe = vi.fn(() => {+ throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' });+ });+ env.deps.spawnDetachedServer = spawn;++ const wm = new WindowManager(env.deps);+ const outcome = await wm.restartAttachedServer('/tmp/dragon');++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ // Nothing respawned, no second window opened behind the live server.+ expect(spawn).not.toHaveBeenCalled();+ expect(env.windows.length).toBe(0);+ expect(env.utilities.length).toBe(0);+ });+test('restartAttachedServer keeps the originating window alive when the respawn fails', async () => {// Kill succeeds, but the fresh spawn never comes up — the originating// window must survive so its invoke resolves with the failure and the@@ -2288,6 +2662,391 @@ describe('WindowManager', () => {expect(env.windows.length).toBe(1);});+ // A stale lock is a different failure from a missing one. The file can+ // name a pid that is alive-or-unkillable while the port it advertises+ // serves nothing: an MCP-spawned server takes the lock, the desktop's own+ // server is later stopped by an auto-update relaunch, and the survivor's+ // lock outlives the port behind it. Every metadata gate still passes, so+ // only a health probe can tell that lock from a good one — and the attach+ // path already does exactly that. The spawn path does not, which is how+ // one field log records both verdicts on the same port 2 ms apart:+ // `desktop-attach-refused reason=ws-upgrade-failed lockPid=870`, then+ // `desktop-server-spawned-detached pid=22018 port=42117` /+ // "detached server ready". The window opens onto a port that answers+ // nothing, and every retry reproduces it.+ test('a stale lock our child never replaced is NOT declared ready (dead port)', async () => {+ enableSyncTimers();+ const STALE_PID = 870;+ const OUR_CHILD_PID = 22018;+ const staleLock: ServerLockMetadataLike = {+ ...spawnedLock,+ pid: STALE_PID,+ port: 42117,+ };+ // The holder never releases and our child never publishes its own lock,+ // so every read — the attach gate's and the spawn poll's — returns the+ // same record, and `pollServerLock` accepts it on the first iteration.+ const probed: string[] = [];+ env.deps.readServerLock = () => staleLock;+ // Alive-or-unkillable: `isPidAlive` reports EPERM as alive, so liveness+ // cannot distinguish this holder from a healthy one.+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = (url) => {+ probed.push(url);+ return Promise.resolve(false);+ };+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ const killCalls: Array<{ pid: number; signal: NodeJS.Signals | number }> = [];+ env.deps.killProbe = (pid, signal) => {+ killCalls.push({ pid, signal });+ };+ // Both tiers kept short: a correct refusal spends the rest of the+ // window re-polling for a lock that is never going to change.+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const wm = new WindowManager(env.deps);+ // Discriminated rather than a bare rejects/resolves assertion so a+ // failure names the port we wrongly attached to.+ const outcome = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' }).then(+ (ctx) => ({ kind: 'attached' as const, port: ctx.port }),+ (err) => ({+ kind: 'refused' as const,+ message: (err as Error).message,+ errKind: (err as Error & { kind?: string }).kind,+ reason: (err as Error & { reason?: string }).reason,+ holderPid: (err as Error & { holderPid?: number }).holderPid,+ }),+ );++ // Precondition, not the point: the attach gate really did probe this+ // lock, so a pass here cannot come from the lock never being examined.+ expect(probed.some((u) => u.includes('42117'))).toBe(true);+ // The point: the spawn branch must not adopt the lock the attach branch+ // just refused. Failing the spawn is an acceptable outcome — the user+ // gets the "Unable to open project" dialog and its Stop Server & Retry+ // remedy instead of a window wired to a port that answers nothing.+ expect(outcome).toMatchObject({ kind: 'refused' });+ expect(env.windows.length).toBe(0);+ // The refusal has to be diagnosable AS a stale holder, not as a+ // deadline. `buildSpawnFailureError`'s narrative would blame a timeout+ // that never elapsed on our own child's pid, and — load-bearing — the+ // failed-open dialog gates its Stop Server & Retry remedy on this kind,+ // so a refusal that does not say what it is silently loses the only way+ // out a user has while the project has no window.+ expect(outcome).toMatchObject({ errKind: 'stale-lock-holder', holderPid: STALE_PID });+ // The other half of the discriminator, and the half that carries THIS+ // scenario — a holder alive but answering nothing. Without it, collapsing+ // the ternary shows the unusable-lock copy ("it may still be running")+ // for a holder this code just proved is not serving, and the suite stays+ // green.+ expect(outcome).toMatchObject({ reason: 'holder-not-serving' });+ if (outcome.kind === 'refused') {+ expect(outcome.message).toContain('not serving on port 42117');+ }+ // The orphan reap. Our child is `.unref()`ed with no parent to collect+ // it, so refusing the holder without SIGTERMing it leaks a server+ // process for the session's lifetime.+ expect(killCalls).toContainEqual({ pid: OUR_CHILD_PID, signal: 'SIGTERM' });+ });++ // Two doors lead into `attachToExistingServer`, and the direct gate is+ // only one of them. A numeric-string port is refused there, but the+ // spawn branch then re-derives the same lock through `pollServerLock`,+ // whose readiness test is `lock.port > 0` — a RELATIONAL compare, so+ // `'42117' > 0` coerces true. The probe on that lock SUCCEEDS, because a+ // numeric string renders into a live address, so the health check that+ // catches the dead-port case cannot catch this one. Without a gate on+ // this door the session is built on a port typed as a string, and the+ // keepalive that keeps the server from reaping the project is typed on a+ // number.+ test('a numeric-string port is refused at the spawn door too, not just the attach gate', async () => {+ enableSyncTimers();+ const FOREIGN_PID = 870;+ const OUR_CHILD_PID = 22018;+ const stringPortLock = {+ ...spawnedLock,+ pid: FOREIGN_PID,+ port: '42117',+ } as unknown as ServerLockMetadataLike;+ env.deps.readServerLock = () => stringPortLock;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // Load-bearing: the holder ANSWERS. This is what separates this case+ // from the dead-port test above — health cannot be the discriminator,+ // so only the shape check can refuse it.+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ const killCalls: Array<{ pid: number; signal: NodeJS.Signals | number }> = [];+ env.deps.killProbe = (pid, signal) => {+ killCalls.push({ pid, signal });+ };+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const wm = new WindowManager(env.deps);+ const outcome = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' }).then(+ (ctx) => ({ kind: 'attached' as const, port: ctx.port }),+ (err) => ({+ kind: 'refused' as const,+ errKind: (err as Error & { kind?: string }).kind,+ reason: (err as Error & { reason?: string }).reason,+ holderIsOwnChild: (err as Error & { holderIsOwnChild?: boolean }).holderIsOwnChild,+ message: (err as Error).message,+ }),+ );++ expect(outcome).toMatchObject({+ kind: 'refused',+ errKind: 'stale-lock-holder',+ reason: 'lock-not-attachable',+ });+ // The FOREIGN direction of both discriminators, and the one carrying the+ // consequence: `holderIsOwnChild` is the second conjunct of the dialog's+ // may-still-be-running hedge AND of its safe keyboard default, so a+ // mutant pinning it true reverts both for every stranger's lock.+ // Asserting only the own-child direction leaves that green.+ expect(outcome).toMatchObject({ holderIsOwnChild: false });+ if (outcome.kind === 'refused') {+ expect(outcome.message).toContain(`Another process (pid ${FOREIGN_PID})`);+ }+ // `||` short-circuits, so the holder was never dialed on this arm. The+ // failed-open dialog quotes this message verbatim, and a user asked to+ // stop a process on the claim it is already inert would be consenting+ // under a premise nothing here established.+ expect(outcome).toMatchObject({ kind: 'refused' });+ if (outcome.kind === 'refused') {+ expect(outcome.message).not.toContain('not serving');+ }+ expect(env.windows.length).toBe(0);+ expect(killCalls).toContainEqual({ pid: OUR_CHILD_PID, signal: 'SIGTERM' });+ });++ // A url arm here would defeat the whole point of the predicate:+ // `resolveKeepaliveWsOrigin` returns `undefined`+ // unless `port` is a positive NUMBER whatever the url says, so a session+ // built on this lock loses its keepalive and idle-shutdown reaps the+ // server under an open window. A good advertisement does not make a lock+ // we can HOLD.+ test('a good loopback url does not rescue a non-numeric port at the attach gate', async () => {+ enableSyncTimers();+ const urlLock = {+ ...spawnedLock,+ pid: 870,+ url: 'http://127.0.0.1:59534',+ port: '59534',+ } as unknown as ServerLockMetadataLike;+ env.deps.readServerLock = () => urlLock;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // The advertised address answers. Only the shape can refuse this.+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: 22018 });+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const wm = new WindowManager(env.deps);+ const outcome = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' }).then(+ (ctx) => ({ kind: 'attached' as const, port: ctx.port }),+ (err) => ({+ kind: 'refused' as const,+ reason: (err as Error & { reason?: string }).reason,+ }),+ );++ expect(outcome).toMatchObject({ kind: 'refused', reason: 'lock-not-attachable' });+ expect(env.windows.length).toBe(0);+ });++ // The one shape that reaches the own-child arm of the holder framing.+ // `unusableLock` is deliberately not exempted for our own spawn the way+ // the probe is, so a lock our child wrote with a port we cannot hold a+ // connection on refuses ITS OWN child — which this method has already+ // SIGTERMed by the time the message is built. Nothing else in the suite+ // gets here (every other test of this throw is cross-pid), so without+ // this the framing reverts to "another process" unnoticed.+ test('refusing our own child names it as ours, not as another process', async () => {+ enableSyncTimers();+ const OUR_CHILD_PID = 22018;+ const ownLock = {+ ...spawnedLock,+ pid: OUR_CHILD_PID,+ port: '42117',+ } as unknown as ServerLockMetadataLike;+ env.deps.readServerLock = () => ownLock;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ const killCalls: Array<{ pid: number; signal: NodeJS.Signals | number }> = [];+ env.deps.killProbe = (pid, signal) => {+ killCalls.push({ pid, signal });+ };+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const wm = new WindowManager(env.deps);+ const outcome = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' }).then(+ () => ({ kind: 'attached' as const }),+ (err) => ({+ kind: 'refused' as const,+ message: (err as Error).message,+ holderIsOwnChild: (err as Error & { holderIsOwnChild?: boolean }).holderIsOwnChild,+ }),+ );++ expect(outcome).toMatchObject({ kind: 'refused', holderIsOwnChild: true });+ if (outcome.kind === 'refused') {+ expect(outcome.message).not.toContain('Another process');+ }+ // The same reap its same-branch siblings assert: our child is+ // `.unref()`ed with no parent to collect it, and here the holder IS+ // that child.+ expect(killCalls).toContainEqual({ pid: OUR_CHILD_PID, signal: 'SIGTERM' });+ });++ // The differential partner of the dead-port test above: the same cross-pid shape+ // with exactly one variable flipped. `pollServerLock` deliberately+ // accepts a non-draining lock held by a DIFFERENT live pid, because a+ // concurrent starter that won the acquire is a real server we should+ // share (see the losing-child test above). Any fix for the stale-lock+ // case must discriminate on the HEALTH of the advertised port, never on+ // pid identity — give that test a probe that passes and the attach returns.+ test('a healthy cross-pid lock-race winner is still attached (probe passes)', async () => {+ enableSyncTimers();+ const WINNER_PID = 870;+ const OUR_CHILD_PID = 22018;+ const winnerLock: ServerLockMetadataLike = {+ ...spawnedLock,+ pid: WINNER_PID,+ port: 42117,+ };+ // Nothing usable at the attach gate; the winner's lock lands on the+ // first poll read, by which point our child is already gone.+ let reads = 0;+ env.deps.readServerLock = () => {+ reads++;+ return reads === 1 ? null : winnerLock;+ };+ // Our child lost the acquire and exited by design; the winner is alive.+ env.deps.isProcessAlive = (pid) => pid === WINNER_PID;+ env.deps.hostname = () => 'my-host';+ // The winner is genuinely serving — the whole difference from above.+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ const spawn = vi.fn(() => Promise.resolve({ pid: OUR_CHILD_PID }));+ env.deps.spawnDetachedServer = spawn;+ env.deps.spawnLockPollDeadlineMs = 500;++ const wm = new WindowManager(env.deps);+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' });++ // Not vacuous: we went through the spawn branch's poll, not the direct+ // attach gate (which saw no lock on its single read).+ expect(spawn).toHaveBeenCalledTimes(1);+ expect(ctx.port).toBe(42117);+ expect(ctx.ownsServer).toBe(false);+ expect(env.windows.length).toBe(1);+ });++ // The STRICT differential for the stale-lock test: byte-identical setup+ // with exactly one value changed, the probe's answer. The cross-pid+ // winner test above is a useful scenario but a loose differential — it+ // also varies child liveness and the lock-read sequence, so a gate gating+ // on child liveness rather than port health passes both of them and only+ // trips over an unrelated pre-existing test. Here liveness is `() => true`+ // for everyone and the lock never changes, so the probe is the only thing+ // that can decide, and any implementation reading a different signal+ // fails one of the pair.+ test('the same stale-lock shape attaches when the probe answers (only the probe differs)', async () => {+ enableSyncTimers();+ const HOLDER_PID = 870;+ const OUR_CHILD_PID = 22018;+ const holderLock: ServerLockMetadataLike = {+ ...spawnedLock,+ pid: HOLDER_PID,+ port: 42117,+ };+ env.deps.readServerLock = () => holderLock;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const wm = new WindowManager(env.deps);+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' });++ expect(ctx.port).toBe(42117);+ expect(env.windows.length).toBe(1);+ });++ // The grace exists for a holder that is up but not yet answering, which is+ // the whole reason this path retries where the attach gate does not. With+ // a single shot this attaches to nothing and the open fails; the loop is+ // otherwise only ever exercised with a constant answer, so nothing would+ // notice it collapsing back to one attempt.+ test('a foreign holder that answers only on a later attempt is still attached', async () => {+ enableSyncTimers();+ const HOLDER_PID = 870;+ const OUR_CHILD_PID = 22018;+ const holderLock: ServerLockMetadataLike = {+ ...spawnedLock,+ pid: HOLDER_PID,+ port: 42117,+ };+ env.deps.readServerLock = () => holderLock;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ let probes = 0;+ // Refuses the first two, then comes up — a server past `listen()` whose+ // `/collab` is still wiring.+ env.deps.probeWsUpgrade = () => {+ probes++;+ return Promise.resolve(probes >= 3);+ };+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ env.deps.spawnLockPollDeadlineMs = 50;+ env.deps.spawnLockProgressDeadlineMs = 50;++ const wm = new WindowManager(env.deps);+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' });++ expect(ctx.port).toBe(42117);+ expect(probes).toBe(3);+ expect(env.windows.length).toBe(1);+ });++ // The own-child exemption is a deliberate cost decision, not an accident:+ // probing a server we just watched come up buys no signal and would put+ // the probe timeout on every cold project open. Nothing else pins it, so+ // deleting the exemption is invisible to the suite.+ test('our own child’s lock is adopted without paying for a probe', async () => {+ enableSyncTimers();+ const OUR_CHILD_PID = 44001;+ let reads = 0;+ env.deps.readServerLock = () => {+ reads++;+ return reads === 1 ? null : { ...spawnedLock, pid: OUR_CHILD_PID, port: 51234 };+ };+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ const probed: string[] = [];+ env.deps.probeWsUpgrade = (url) => {+ probed.push(url);+ return Promise.resolve(true);+ };+ env.deps.spawnDetachedServer = () => Promise.resolve({ pid: OUR_CHILD_PID });+ env.deps.spawnLockPollDeadlineMs = 500;++ const wm = new WindowManager(env.deps);+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' });++ expect(ctx.port).toBe(51234);+ expect(probed).toHaveLength(0);+ });+test('a child that exits before binding surfaces its exit code and signal', async () => {enableSyncTimers();env.deps.readServerLock = () => null;@@ -2442,7 +3201,7 @@ describe('WindowManager', () => {});describe('forceStopConflictingServer (dialog "Stop Server & Retry")', () => {- function seedRawLock(pid: number): string {+ function seedRawLock(pid: number, overrides?: { port?: number }): string {const projectPath = mkdtempSync(join(tmpdir(), 'ok-force-stop-'));const lockDir = join(projectPath, '.ok', 'local');mkdirSync(lockDir, { recursive: true });@@ -2454,7 +3213,7 @@ describe('WindowManager', () => {pid,hostname: 'some-old-hostname',machineId: 'not-this-machine',- port: 61000,+ port: overrides?.port ?? 61000,startedAt: '2026-07-07T00:00:00.000Z',worktreeRoot: projectPath,kind: 'interactive',@@ -2509,6 +3268,203 @@ describe('WindowManager', () => {expect(outcome).toEqual({ ok: false, reason: 'eperm' });});+ // This dialog is the ONLY remedy while the project has no window, so an+ // EPERM dead-end here is terminal in a way the restart path's is not: the+ // restart affordance lives on a window that, for a wedged project, never+ // opens. Both entry states have to clear an unkillable-and-not-serving+ // holder or the fix only helps projects that were already open.+ test('EPERM holder that serves nothing has its lock broken so the retry proceeds', async () => {+ // The graced probe on the break path retries through `deps.setTimeout`,+ // which the base env only records; drive it so the loop resolves.+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const projectPath = seedRawLock(64323);+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => ({ ...liveLock, pid: 64323, port: 61000 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ // 61000 answers nothing.+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ env.deps.killProbe = () => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: true });+ expect(removeServerLock).toHaveBeenCalledTimes(1);+ // Same trap as the restart path: the lock dir, not the project root.+ expect(removeServerLock.mock.calls[0]?.[0]).toBe(join(projectPath, '.ok', 'local'));+ expect(removeServerLock.mock.calls[0]?.[1]).toEqual({ pid: 64323 });+ });++ // The production `removeServerLock` wiring, exercised against a real lock+ // file rather than a spy. The window between deciding and unlinking is a+ // whole health probe wide, so a successor that acquired the lock in it+ // must keep it — an unguarded unlink would delete a valid claim on the+ // strength of a verdict about its predecessor.+ test('the guarded unlink breaks only the holder it was told about', () => {+ const projectPath = seedRawLock(70001);+ const lockDir = join(projectPath, '.ok', 'local');+ const lockPath = join(lockDir, 'server.lock');++ // A successor took the lock while we were probing the predecessor.+ expect(breakServerLockHeldBy(lockDir, { pid: 69999 })).toBe(false);+ expect(existsSync(lockPath)).toBe(true);++ // The holder we actually judged.+ expect(breakServerLockHeldBy(lockDir, { pid: 70001 })).toBe(true);+ expect(existsSync(lockPath)).toBe(false);++ // Already gone is the end state we wanted, but not a removal WE did,+ // and never an error — this runs on the path that un-wedges a project.+ expect(breakServerLockHeldBy(lockDir, { pid: 70001 })).toBe(false);++ // A corrupt lock is left for `runClean`, not broken on a guess.+ writeFileSync(lockPath, 'not json', 'utf-8');+ expect(breakServerLockHeldBy(lockDir, { pid: 70001 })).toBe(false);+ expect(existsSync(lockPath)).toBe(true);+ });++ // `seedRawLock` deliberately writes a+ // foreign hostname and machineId, because the defining feature of this+ // state is that identity checks refused the holder — that is why this+ // method reads the lock raw. Sourcing the probe target from+ // `readServerLock` instead re-imposes that filter and returns null,+ // silently making the one no-window remedy inert for exactly the cohort+ // EPERM implies: a holder under another account or a flapped hostname.+ test('EPERM recovery works on a lock whose identity fields look foreign', async () => {+ // The graced probe on the break path retries through `deps.setTimeout`,+ // which the base env only records; drive it so the loop resolves.+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const projectPath = seedRawLock(64325);+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ // The identity-filtered reader refuses this lock, as it does in the field.+ env.deps.readServerLock = () => null;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ env.deps.killProbe = () => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: true });+ expect(removeServerLock).toHaveBeenCalledTimes(1);+ expect(removeServerLock.mock.calls[0]?.[1]).toEqual({ pid: 64325 });+ });++ // Same degrade-don't-crash contract as the restart path, on the entry+ // state that has no window to fall back to.+ test('EPERM recovery survives a removeServerLock that throws', async () => {+ // The graced probe on the break path retries through `deps.setTimeout`,+ // which the base env only records; drive it so the loop resolves.+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const projectPath = seedRawLock(64326);+ env.deps.removeServerLock = vi.fn(() => {+ throw Object.assign(new Error('EACCES'), { code: 'EACCES' });+ });+ env.deps.readServerLock = () => null;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ env.deps.killProbe = () => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ });++ // Symmetry with the restart path: a declined break is not a success here+ // either, and this is the entry state with no window to fall back to.+ test('EPERM recovery does not report success when the break is declined', async () => {+ const projectPath = seedRawLock(64327);+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => false);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => null;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(false);+ env.deps.killProbe = () => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(removeServerLock).toHaveBeenCalledTimes(1);+ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ });++ // The other half of the port-0 guard. Pinning it from the restart path+ // alone proves the rule holds it, not that this caller reaches the rule.+ test('EPERM recovery leaves the lock alone when the holder has not bound a port', async () => {+ const projectPath = seedRawLock(64328, { port: 0 });+ env.deps.setTimeout = (cb: () => void, _ms: number) => {+ cb();+ return null;+ };+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => null;+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ const probe = vi.fn(() => Promise.resolve(false));+ env.deps.probeWsUpgrade = probe;+ env.deps.killProbe = () => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(removeServerLock).not.toHaveBeenCalled();+ expect(probe).not.toHaveBeenCalled();+ });++ // The guard on the test above, and the reason the rule asks two questions+ // rather than one: breaking a serving holder's lock would strand it and+ // put a second server on the same project.+ test('EPERM holder that IS serving keeps its lock and still fails', async () => {+ const projectPath = seedRawLock(64324);+ const removeServerLock = vi.fn(() => true);+ env.deps.removeServerLock = removeServerLock;+ env.deps.readServerLock = () => ({ ...liveLock, pid: 64324, port: 61000 });+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ env.deps.killProbe = () => {+ throw Object.assign(new Error('eperm'), { code: 'EPERM' });+ };++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ expect(removeServerLock).not.toHaveBeenCalled();+ });+test('never signals a hostile lock pid (0/1/self)', async () => {const killCalls: number[] = [];env.deps.killProbe = (pid) => {