From e7109697ba01f8306c79af7be83e02bdc13a3759 Mon Sep 17 00:00:00 2001 From: n3wr1ch <40690535+n3wr1ch@users.noreply.github.com> Date: Sat, 22 Aug 2026 21:14:11 +0900 Subject: [PATCH 1/3] fix(update): recover npm 12 self-updates --- bin/ocx.mjs | 156 +++++++++++++++------------ src/update/transactional-install.mjs | 9 +- tests/update-stop-first.test.ts | 19 ++++ tests/update-transactional.test.ts | 17 +++ 4 files changed, 133 insertions(+), 68 deletions(-) diff --git a/bin/ocx.mjs b/bin/ocx.mjs index a8f5a2455c2..bfe202dce0f 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -227,11 +227,83 @@ function runNpmSelfUpdate() { } catch { /* keep default */ } } + const launcher = fileURLToPath(import.meta.url); + + function startProxyDirectly() { + const env = { ...process.env }; + delete env.OCX_SERVICE; + const child = spawn(process.execPath, [launcher, "start", "--port", String(bakePort)], { + detached: true, + stdio: "ignore", + windowsHide: true, + env, + }); + child.unref(); + console.log(`Proxy starting on port ${bakePort}.`); + } + + function refreshBackgroundServiceOrStartDirect() { + const prevBake = process.env.OCX_BAKE_PORT; + process.env.OCX_BAKE_PORT = String(bakePort); + try { + let svc = spawnSync(process.execPath, serviceRefreshArgs(), { stdio: "inherit", windowsHide: true }); + // `serviceWasInstalled` is inferred from service-state.json alone, which can be + // STALE — present while the registration is gone. Repair refuses that case by + // design, and its thrown Error is indistinguishable from any other failure at + // this layer (plain Error, inherited stdio, generic exit status). So ask for + // structured state instead of parsing the failure: install only when the + // diagnostic says the service is genuinely absent. Installing after ANY repair + // failure would resurrect the elevation prompt this change exists to avoid, and + // could re-register a service the user just uninstalled. + if (svc.status !== 0 && readServiceInstalledFromStatus(launcher) === false) { + console.log("No registered service found — installing it instead."); + svc = spawnSync(process.execPath, serviceInstallArgs(), { stdio: "inherit", windowsHide: true }); + } + let needDirectStart = svc.status !== 0; + if (!needDirectStart) { + // Exit 0 can still leave stale/missing assets that never bring the proxy + // back — match the GUI/CLI fallthrough so /healthz is not left dead. + try { + const st = spawnSync(process.execPath, [launcher, "status", "--json"], { + encoding: "utf8", + timeout: 20_000, + windowsHide: true, + }); + if (st.status === 0 && typeof st.stdout === "string" && st.stdout.trim()) { + const parsed = JSON.parse(st.stdout); + const proxyUp = parsed?.proxy?.running === true || parsed?.proxy?.health?.ok === true; + const viable = parsed?.startup?.serviceViable === true; + if (!proxyUp && !viable) needDirectStart = true; + } else { + // status failed or empty — fail closed to direct start (match CLI). + needDirectStart = true; + } + } catch { + needDirectStart = true; + } + } + if (needDirectStart) { + // A repair needs no elevation, but it can still fail — or exit 0 while leaving + // a non-viable manager. Fall back to a direct detached proxy start so the + // update never leaves the user without a running proxy. + console.warn( + svc.status === 0 + ? "opencodex: service refresh left a non-viable manager — starting the proxy directly instead." + : "opencodex: service refresh failed — starting the proxy directly instead.", + ); + console.warn(" Run 'ocx service repair' to see why the background service could not restart."); + startProxyDirectly(); + } + } finally { + if (prevBake === undefined) delete process.env.OCX_BAKE_PORT; + else process.env.OCX_BAKE_PORT = prevBake; + } + } + // Never replace package files under a live proxy — stop it first (full `ocx stop` // semantics: graceful drain, service stop, native Codex restore). Gate on the service // and the runtime-port record too: a service-managed or orphaned proxy can be live // while ocx.pid is stale/missing. - const launcher = fileURLToPath(import.meta.url); if (trayBeforeUpdate.stopBeforeReplacement) { console.log("⏹ Handing off the Windows tray before updating..."); try { @@ -249,6 +321,17 @@ function runNpmSelfUpdate() { } const hasRuntimeState = existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json")); + + function recoverStoppedRuntimeAfterFailure() { + if (serviceWasInstalled) { + console.warn("opencodex: update failed after stopping the proxy — restoring the previous background service."); + refreshBackgroundServiceOrStartDirect(); + } else if (hasRuntimeState) { + console.warn("opencodex: update failed after stopping the proxy — restarting the previous version directly."); + startProxyDirectly(); + } + } + if (serviceWasInstalled || hasRuntimeState) { console.log("⏹ Stopping the running proxy before updating..."); const stopRes = spawnSync(process.execPath, [launcher, "stop"], { stdio: "inherit", windowsHide: true }); @@ -309,7 +392,8 @@ function runNpmSelfUpdate() { // it recreates the #1849 destruction path. Report and stop; the boot probe and the // recovery marker cover the swap-window states. console.error(`opencodex: transactional update failed unexpectedly (${error?.message ?? error}). ` + - "The live install was not knowingly modified; run 'ocx update' again or reinstall with npm install -g."); + `The live install was not knowingly modified; run 'ocx update' again or reinstall with ` + + `npm install -g --allow-scripts=bun ${PKG}@${tag}.`); res = { status: 1 }; } if (res.status === 0) { @@ -329,77 +413,15 @@ function runNpmSelfUpdate() { // launcher so the new files write the baked paths and the service restarts. if (serviceWasInstalled) { console.log("Refreshing the background service with the updated files..."); - const prevBake = process.env.OCX_BAKE_PORT; - process.env.OCX_BAKE_PORT = String(bakePort); - try { - let svc = spawnSync(process.execPath, serviceRefreshArgs(), { stdio: "inherit", windowsHide: true }); - // `serviceWasInstalled` is inferred from service-state.json alone, which can be - // STALE — present while the registration is gone. Repair refuses that case by - // design, and its thrown Error is indistinguishable from any other failure at - // this layer (plain Error, inherited stdio, generic exit status). So ask for - // structured state instead of parsing the failure: install only when the - // diagnostic says the service is genuinely absent. Installing after ANY repair - // failure would resurrect the elevation prompt this change exists to avoid, and - // could re-register a service the user just uninstalled. - if (svc.status !== 0 && readServiceInstalledFromStatus(launcher) === false) { - console.log("No registered service found — installing it instead."); - svc = spawnSync(process.execPath, serviceInstallArgs(), { stdio: "inherit", windowsHide: true }); - } - let needDirectStart = svc.status !== 0; - if (!needDirectStart) { - // Exit 0 can still leave stale/missing assets that never bring the proxy - // back — match the GUI/CLI fallthrough so /healthz is not left dead. - try { - const st = spawnSync(process.execPath, [launcher, "status", "--json"], { - encoding: "utf8", - timeout: 20_000, - windowsHide: true, - }); - if (st.status === 0 && typeof st.stdout === "string" && st.stdout.trim()) { - const parsed = JSON.parse(st.stdout); - const proxyUp = parsed?.proxy?.running === true || parsed?.proxy?.health?.ok === true; - const viable = parsed?.startup?.serviceViable === true; - if (!proxyUp && !viable) needDirectStart = true; - } else { - // status failed or empty — fail closed to direct start (match CLI). - needDirectStart = true; - } - } catch { - needDirectStart = true; - } - } - if (needDirectStart) { - // A repair needs no elevation, but it can still fail — or exit 0 while leaving - // a non-viable manager. Fall back to a direct detached proxy start so the - // update never leaves the user without a running proxy. - console.warn( - svc.status === 0 - ? "opencodex: service refresh left a non-viable manager — starting the proxy directly instead." - : "opencodex: service refresh failed — starting the proxy directly instead.", - ); - console.warn(" Run 'ocx service repair' to see why the background service could not restart."); - const env = { ...process.env }; - delete env.OCX_SERVICE; - const child = spawn(process.execPath, [launcher, "start", "--port", String(bakePort)], { - detached: true, - stdio: "ignore", - windowsHide: true, - env, - }); - child.unref(); - console.log(`Proxy starting on port ${bakePort}.`); - } - } finally { - if (prevBake === undefined) delete process.env.OCX_BAKE_PORT; - else process.env.OCX_BAKE_PORT = prevBake; - } + refreshBackgroundServiceOrStartDirect(); } else { console.log("Restart the proxy: ocx start"); } process.exit(0); } if (trayBeforeUpdate.restoreOnFailure) runTrayLifecycle(launcher, "start"); - console.error(`\nUpdate failed (npm exit ${res.status ?? "?"}). Try manually: npm install -g ${PKG}@${tag}`); + recoverStoppedRuntimeAfterFailure(); + console.error(`\nUpdate failed (npm exit ${res.status ?? "?"}). Try manually: npm install -g --allow-scripts=bun ${PKG}@${tag}`); process.exit(1); } diff --git a/src/update/transactional-install.mjs b/src/update/transactional-install.mjs index 1ecad741d33..9b61c9fe330 100644 --- a/src/update/transactional-install.mjs +++ b/src/update/transactional-install.mjs @@ -176,7 +176,14 @@ export function transactionalNpmUpdate({ } const spec = pkgName + "@" + (targetVersion || tag); log("Staging " + spec + " into " + stageRoot); - const install = runNpm(["install", "-g", "--prefix", stageRoot, "--no-audit", "--no-fund", spec]); + // npm 12 blocks lifecycle scripts by default. Bun's postinstall copies the selected + // @oven/bun-* executable into bun/bin, so a successful npm exit without this narrow + // approval leaves the staged tree intentionally incomplete. Allow only the package + // whose executable the manifest verifies below; never broaden this to all scripts. + const install = runNpm([ + "install", "-g", "--prefix", stageRoot, + "--allow-scripts=bun", "--no-audit", "--no-fund", spec, + ]); if (install.status !== 0) { try { rmSync(stageRoot, { recursive: true, force: true }); } catch { /* best effort */ } return { ok: false, phase: "stage", error: "npm staging install failed (" + (install.status ?? "?") + ")" }; diff --git a/tests/update-stop-first.test.ts b/tests/update-stop-first.test.ts index 9895161bb3f..e42c85bf2e6 100644 --- a/tests/update-stop-first.test.ts +++ b/tests/update-stop-first.test.ts @@ -105,6 +105,25 @@ describe("update stops the running proxy before replacing files", () => { expect(updateSource).toContain("runtimeTrusted"); }); + test("npm launcher restores the stopped runtime before reporting an update failure", () => { + const helperAt = launcherSource.indexOf("function recoverStoppedRuntimeAfterFailure()"); + const callAt = launcherSource.indexOf("recoverStoppedRuntimeAfterFailure();"); + const failureAt = launcherSource.indexOf("Update failed (npm exit"); + const exitAt = launcherSource.indexOf("process.exit(1);", failureAt); + + expect(helperAt).toBeGreaterThan(-1); + expect(callAt).toBeGreaterThan(helperAt); + expect(callAt).toBeLessThan(failureAt); + expect(failureAt).toBeLessThan(exitAt); + + const helper = launcherSource.slice(helperAt, callAt); + expect(helper).toContain("serviceWasInstalled"); + expect(helper).toContain("hasRuntimeState"); + expect(helper).toContain("refreshBackgroundServiceOrStartDirect()"); + expect(helper).toContain("startProxyDirectly()"); + expect(launcherSource).toContain(`Try manually: npm install -g --allow-scripts=bun \${PKG}@\${tag}`); + }); + test("both update paths surface a skipped history restore after the stop", () => { // A codex-history-backup-*.json surviving `ocx stop` means the native-history restore // was skipped (locked state DB) — users must be told or their threads silently stay diff --git a/tests/update-transactional.test.ts b/tests/update-transactional.test.ts index 58782161959..8d471280eba 100644 --- a/tests/update-transactional.test.ts +++ b/tests/update-transactional.test.ts @@ -82,6 +82,23 @@ describe("#1942 transactional update", () => { expect(liveVersion(result.backup!)).toBe("1.0.0"); }); + test("global staging explicitly allows only Bun's required install script", () => { + let installArgs: string[] = []; + const stage = stagingNpm("2.0.0"); + const result = transactionalNpmUpdate({ + packageDir, pkgName: PKG, targetVersion: "2.0.0", tag: "latest", + runNpm: (args: string[]) => { + installArgs = args; + return stage(args); + }, + }); + + expect(result.ok).toBe(true); + expect(installArgs).toContain("--allow-scripts=bun"); + expect(installArgs).not.toContain("--dangerously-allow-all-scripts"); + expect(installArgs).not.toContain("--ignore-scripts"); + }); + test("stage install failure leaves live untouched (D4 row 1)", () => { const result = transactionalNpmUpdate({ packageDir, pkgName: PKG, targetVersion: "2.0.0", tag: "latest", From f2fca7573253e2024c81bcc00b129c0c1627544b Mon Sep 17 00:00:00 2001 From: n3wr1ch <40690535+n3wr1ch@users.noreply.github.com> Date: Sat, 22 Aug 2026 22:22:11 +0900 Subject: [PATCH 2/3] test(update): exercise npm failure recovery --- tests/update-stop-first.test.ts | 127 +++++++++++++++++++++++++++----- 1 file changed, 107 insertions(+), 20 deletions(-) diff --git a/tests/update-stop-first.test.ts b/tests/update-stop-first.test.ts index e42c85bf2e6..6480cca3891 100644 --- a/tests/update-stop-first.test.ts +++ b/tests/update-stop-first.test.ts @@ -1,8 +1,38 @@ import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; -import { join } from "node:path"; +import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; import { runNpmCachePreflight } from "../src/update/npm-cache-preflight.mjs"; +const repoRoot = join(import.meta.dir, ".."); + +function freePort(): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + const server = createServer(); + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + const port = typeof address === "object" && address ? address.port : 0; + server.close(() => port ? resolve(port) : reject(new Error("no free port"))); + }); + return promise; +} + +async function waitForProxy(port: number): Promise { + const deadline = Date.now() + 15_000; + while (Date.now() < deadline) { + try { + const response = await fetch(`http://127.0.0.1:${port}/healthz`, { + signal: AbortSignal.timeout(500), + }); + if (response.ok) return true; + } catch { /* detached proxy is still starting */ } + // The detached process exposes readiness only over HTTP; fake timers cannot advance it. + await Bun.sleep(100); + } + return false; +} const updateSource = readFileSync(join(import.meta.dir, "..", "src", "update", "index.ts"), "utf8"); const launcherSource = readFileSync(join(import.meta.dir, "..", "bin", "ocx.mjs"), "utf8"); const serverSource = readFileSync(join(import.meta.dir, "..", "src", "server", "index.ts"), "utf8"); @@ -105,24 +135,81 @@ describe("update stops the running proxy before replacing files", () => { expect(updateSource).toContain("runtimeTrusted"); }); - test("npm launcher restores the stopped runtime before reporting an update failure", () => { - const helperAt = launcherSource.indexOf("function recoverStoppedRuntimeAfterFailure()"); - const callAt = launcherSource.indexOf("recoverStoppedRuntimeAfterFailure();"); - const failureAt = launcherSource.indexOf("Update failed (npm exit"); - const exitAt = launcherSource.indexOf("process.exit(1);", failureAt); - - expect(helperAt).toBeGreaterThan(-1); - expect(callAt).toBeGreaterThan(helperAt); - expect(callAt).toBeLessThan(failureAt); - expect(failureAt).toBeLessThan(exitAt); - - const helper = launcherSource.slice(helperAt, callAt); - expect(helper).toContain("serviceWasInstalled"); - expect(helper).toContain("hasRuntimeState"); - expect(helper).toContain("refreshBackgroundServiceOrStartDirect()"); - expect(helper).toContain("startProxyDirectly()"); - expect(launcherSource).toContain(`Try manually: npm install -g --allow-scripts=bun \${PKG}@\${tag}`); - }); + test.skipIf(process.platform === "win32")( + "npm launcher restarts the stopped runtime after a staged update failure", + async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-update-recovery-")); + const packageRoot = join(root, "node_modules", "@bitkyc08", "opencodex"); + const launcher = join(packageRoot, "bin", "ocx.mjs"); + const opencodexHome = join(root, "opencodex-home"); + const fakeBin = join(root, "fake-bin"); + const fakeNpm = join(fakeBin, "npm"); + const cache = join(root, "npm-cache"); + const port = await freePort(); + + mkdirSync(dirname(launcher), { recursive: true }); + mkdirSync(join(packageRoot, "node_modules"), { recursive: true }); + mkdirSync(opencodexHome, { recursive: true }); + mkdirSync(fakeBin, { recursive: true }); + mkdirSync(cache, { recursive: true }); + copyFileSync(join(repoRoot, "bin", "ocx.mjs"), launcher); + chmodSync(launcher, 0o755); + symlinkSync(join(repoRoot, "src"), join(packageRoot, "src"), "dir"); + symlinkSync(join(repoRoot, "node_modules", "bun"), join(packageRoot, "node_modules", "bun"), "dir"); + writeFileSync(join(packageRoot, "package.json"), JSON.stringify({ + name: "@bitkyc08/opencodex", + version: "1.0.0", + type: "module", + })); + writeFileSync(join(opencodexHome, "config.json"), JSON.stringify({ port })); + writeFileSync(join(opencodexHome, "runtime-port.json"), JSON.stringify({ port, pid: 999_999_999 })); + writeFileSync(fakeNpm, `#!/bin/sh +case "$1" in + view) printf '2.0.0\\n' ;; + config) printf '%s\\n' "$OCX_FAKE_NPM_CACHE" ;; + install) exit 1 ;; + *) exit 1 ;; +esac +`); + chmodSync(fakeNpm, 0o755); + + const env = { + ...process.env, + HOME: root, + USERPROFILE: root, + OPENCODEX_HOME: opencodexHome, + OCX_FAKE_NPM_CACHE: cache, + PATH: `${fakeBin}:${process.env.PATH ?? ""}`, + }; + + try { + const result = Bun.spawnSync(["node", launcher, "update"], { + cwd: root, + env, + stdout: "pipe", + stderr: "pipe", + timeout: 30_000, + }); + const output = result.stdout.toString() + result.stderr.toString(); + + expect(result.exitCode).toBe(1); + expect(output).toContain("Stopping the running proxy before updating"); + expect(output).toContain("restarting the previous version directly"); + expect(output).toContain(`Proxy starting on port ${port}.`); + expect(await waitForProxy(port)).toBe(true); + } finally { + Bun.spawnSync(["node", launcher, "stop"], { + cwd: root, + env, + stdout: "ignore", + stderr: "ignore", + timeout: 30_000, + }); + rmSync(root, { recursive: true, force: true }); + } + }, + 60_000, + ); test("both update paths surface a skipped history restore after the stop", () => { // A codex-history-backup-*.json surviving `ocx stop` means the native-history restore From a43ab638856bd019d8595ede2a9b5b51a4922897 Mon Sep 17 00:00:00 2001 From: n3wr1ch <40690535+n3wr1ch@users.noreply.github.com> Date: Sat, 22 Aug 2026 22:36:38 +0900 Subject: [PATCH 3/3] fix(update): harden direct recovery reporting --- bin/ocx.mjs | 9 +++- tests/update-stop-first.test.ts | 90 +++++++++++++++++++-------------- 2 files changed, 61 insertions(+), 38 deletions(-) diff --git a/bin/ocx.mjs b/bin/ocx.mjs index bfe202dce0f..3f00b585385 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -230,16 +230,23 @@ function runNpmSelfUpdate() { const launcher = fileURLToPath(import.meta.url); function startProxyDirectly() { + if (!existsSync(launcher)) { + console.error("opencodex: cannot restart the proxy because the launcher is missing; reinstall opencodex manually."); + return; + } const env = { ...process.env }; delete env.OCX_SERVICE; + console.log(`Attempting to restart the proxy on port ${bakePort}.`); const child = spawn(process.execPath, [launcher, "start", "--port", String(bakePort)], { detached: true, stdio: "ignore", windowsHide: true, env, }); + child.on("error", error => { + console.error(`opencodex: direct proxy restart failed: ${error.message}`); + }); child.unref(); - console.log(`Proxy starting on port ${bakePort}.`); } function refreshBackgroundServiceOrStartDirect() { diff --git a/tests/update-stop-first.test.ts b/tests/update-stop-first.test.ts index 6480cca3891..78fa26e71a2 100644 --- a/tests/update-stop-first.test.ts +++ b/tests/update-stop-first.test.ts @@ -1,9 +1,10 @@ import { describe, expect, test } from "bun:test"; -import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { createServer } from "node:net"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { runNpmCachePreflight } from "../src/update/npm-cache-preflight.mjs"; +import { killProxy } from "../src/lib/process-control"; const repoRoot = join(import.meta.dir, ".."); @@ -145,34 +146,7 @@ describe("update stops the running proxy before replacing files", () => { const fakeBin = join(root, "fake-bin"); const fakeNpm = join(fakeBin, "npm"); const cache = join(root, "npm-cache"); - const port = await freePort(); - - mkdirSync(dirname(launcher), { recursive: true }); - mkdirSync(join(packageRoot, "node_modules"), { recursive: true }); - mkdirSync(opencodexHome, { recursive: true }); - mkdirSync(fakeBin, { recursive: true }); - mkdirSync(cache, { recursive: true }); - copyFileSync(join(repoRoot, "bin", "ocx.mjs"), launcher); - chmodSync(launcher, 0o755); - symlinkSync(join(repoRoot, "src"), join(packageRoot, "src"), "dir"); - symlinkSync(join(repoRoot, "node_modules", "bun"), join(packageRoot, "node_modules", "bun"), "dir"); - writeFileSync(join(packageRoot, "package.json"), JSON.stringify({ - name: "@bitkyc08/opencodex", - version: "1.0.0", - type: "module", - })); - writeFileSync(join(opencodexHome, "config.json"), JSON.stringify({ port })); - writeFileSync(join(opencodexHome, "runtime-port.json"), JSON.stringify({ port, pid: 999_999_999 })); - writeFileSync(fakeNpm, `#!/bin/sh -case "$1" in - view) printf '2.0.0\\n' ;; - config) printf '%s\\n' "$OCX_FAKE_NPM_CACHE" ;; - install) exit 1 ;; - *) exit 1 ;; -esac -`); - chmodSync(fakeNpm, 0o755); - + const bundledBun = join(repoRoot, "node_modules", "bun"); const env = { ...process.env, HOME: root, @@ -181,8 +155,37 @@ esac OCX_FAKE_NPM_CACHE: cache, PATH: `${fakeBin}:${process.env.PATH ?? ""}`, }; + let recoveredPid: number | undefined; try { + const port = await freePort(); + expect(existsSync(bundledBun)).toBe(true); + mkdirSync(dirname(launcher), { recursive: true }); + mkdirSync(join(packageRoot, "node_modules"), { recursive: true }); + mkdirSync(opencodexHome, { recursive: true }); + mkdirSync(fakeBin, { recursive: true }); + mkdirSync(cache, { recursive: true }); + copyFileSync(join(repoRoot, "bin", "ocx.mjs"), launcher); + chmodSync(launcher, 0o755); + symlinkSync(join(repoRoot, "src"), join(packageRoot, "src"), "dir"); + symlinkSync(bundledBun, join(packageRoot, "node_modules", "bun"), "dir"); + writeFileSync(join(packageRoot, "package.json"), JSON.stringify({ + name: "@bitkyc08/opencodex", + version: "1.0.0", + type: "module", + })); + writeFileSync(join(opencodexHome, "config.json"), JSON.stringify({ port })); + writeFileSync(join(opencodexHome, "runtime-port.json"), JSON.stringify({ port, pid: 999_999_999 })); + writeFileSync(fakeNpm, `#!/bin/sh +case "$1" in + view) printf '2.0.0\\n' ;; + config) printf '%s\\n' "$OCX_FAKE_NPM_CACHE" ;; + install) exit 1 ;; + *) exit 1 ;; +esac +`); + chmodSync(fakeNpm, 0o755); + const result = Bun.spawnSync(["node", launcher, "update"], { cwd: root, env, @@ -195,16 +198,29 @@ esac expect(result.exitCode).toBe(1); expect(output).toContain("Stopping the running proxy before updating"); expect(output).toContain("restarting the previous version directly"); - expect(output).toContain(`Proxy starting on port ${port}.`); + expect(output).toContain(`Attempting to restart the proxy on port ${port}.`); expect(await waitForProxy(port)).toBe(true); + const runtime = JSON.parse(readFileSync(join(opencodexHome, "runtime-port.json"), "utf8")); + expect(runtime.pid).toBeGreaterThan(0); + recoveredPid = runtime.pid; } finally { - Bun.spawnSync(["node", launcher, "stop"], { - cwd: root, - env, - stdout: "ignore", - stderr: "ignore", - timeout: 30_000, - }); + const stopped = existsSync(launcher) + ? Bun.spawnSync(["node", launcher, "stop"], { + cwd: root, + env, + stdout: "ignore", + stderr: "ignore", + timeout: 30_000, + }) + : null; + if (stopped?.exitCode !== 0) { + if (!recoveredPid) { + try { + recoveredPid = JSON.parse(readFileSync(join(opencodexHome, "runtime-port.json"), "utf8")).pid; + } catch { /* the proxy never wrote runtime state */ } + } + if (Number.isSafeInteger(recoveredPid) && recoveredPid! > 0) killProxy(recoveredPid!); + } rmSync(root, { recursive: true, force: true }); } },