diff --git a/CHANGELOG.md b/CHANGELOG.md index ec584eb19..caaea23d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixed +- **In-app updates can replace an npm-global Windows install started by the tray.** The update stops the tray program in the package and any node or bun process still using that install, without ending the update itself, and runs the install from outside the package so Windows can rename it. When the tray started the server, it is started again in the logged-on session and starts the one server; otherwise the server is started directly and still told which install to serve. - **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did. - **GitHub workflow watches no longer regress to stale run states.** Workflow updates retain GitHub's run timestamp and ignore older snapshots for the same or an earlier attempt, so a delayed `queued` response cannot follow a newer `in_progress` delivery. - **Keep sidebar transcript results aligned with expandable hits on every linked host.** Each daemon now searches its own active conversations, ignoring abandoned branches and pre-compaction messages. diff --git a/lib/hosts/update-worker.ts b/lib/hosts/update-worker.ts index a81810383..f5d944c46 100644 --- a/lib/hosts/update-worker.ts +++ b/lib/hosts/update-worker.ts @@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto"; import { execFile } from "node:child_process"; import { chmodSync, closeSync, createReadStream, createWriteStream, existsSync, fstatSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync } from "node:fs"; -import { homedir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { createGunzip, inflateRawSync } from "node:zlib"; import { pipeline } from "node:stream/promises"; @@ -462,7 +462,8 @@ export async function stagePackage(d: HostPackageSource, staging: string): Promi const windows = process.platform === "win32" && /\.(cmd|bat)$/i.test(command); // `/s /c` strips one outer pair of quotes; verbatim so Node does not escape the inner ones (as Node's `shell: true`). const line = [command, ...args].map((arg) => `"${arg.replaceAll('"', '')}"`).join(" "); - await exec(windows ? process.env.ComSpec || "cmd.exe" : command, windows ? ["/d", "/s", "/c", `"${line}"`] : args, { timeout: DOWNLOAD_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: workerEnvironment(), windowsHide: true, windowsVerbatimArguments: windows }); + // Windows refuses to rename a directory that is any live process's working directory, including this install child. + await exec(windows ? process.env.ComSpec || "cmd.exe" : command, windows ? ["/d", "/s", "/c", `"${line}"`] : args, { cwd: tmpdir(), timeout: DOWNLOAD_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: workerEnvironment(), windowsHide: true, windowsVerbatimArguments: windows }); const modules = join(prefix, "node_modules"); const packageDir = join(modules, "@kahme247", "ompweb"); const metadata = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8")); diff --git a/lib/hosts/update-worker.windows.test.mjs b/lib/hosts/update-worker.windows.test.mjs index 48d192741..2a4de4606 100644 --- a/lib/hosts/update-worker.windows.test.mjs +++ b/lib/hosts/update-worker.windows.test.mjs @@ -44,3 +44,18 @@ test("a slow Windows process inventory allows private installs but still refuses assert.equal(reason !== null, fixture.refused, String(fixture.output)); } }); + +test("the package install child does not inherit the installation as its working directory", async (t) => { + let cwd; + const execFile = () => { throw new Error("not promisified"); }; + execFile[promisify.custom] = (_command, _args, options) => { + cwd = options?.cwd; + return Promise.reject(new Error("stop after cwd")); + }; + await mockBuiltin(t, "node:child_process", { execFile }); + const { stagePackage } = await import("./update-worker.ts?fresh=install-cwd"); + const staging = mkdtempSync(join(tmpdir(), "stage-cwd-")); + t.after(() => rmSync(staging, { recursive: true, force: true })); + await assert.rejects(() => stagePackage({ version: "9.9.9", installMethod: "npm", managerPath: process.execPath }, staging), /stop after cwd/); + assert.equal(cwd, tmpdir()); +}); diff --git a/lib/self-update.test.mjs b/lib/self-update.test.mjs index 510906a7c..5f199dcf9 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -286,13 +286,15 @@ test("a commit stages and preflights the release before updating hosts, then lau // The launcher is the supervised process: its pid is inspected, and the restart goes through it with the listen address. assert.equal(inspections[0].pid, process.ppid); assert.deepEqual(inspections[0].launch.args.slice(1), ["-p", "30177", "-H", "127.0.0.1", "--no-open"]); - assert.equal(inspections[0].launch.cwd, installDir); + assert.equal(inspections[0].launch.cwd, realProcess.cwdOutsideInstall(installDir)); + assert.notEqual(inspections[0].launch.cwd, installDir); const [launch] = launches; const root = resolveSelfUpdateTempRoot(); const attemptDir = join(root, "attempts", attemptId); assert.equal(launch.command, process.execPath); assert.deepEqual(launch.args, [join(attemptDir, "worker.mjs"), "--server-update-descriptor", join(attemptDir, "descriptor.json")]); + assert.equal(launch.cwd, realProcess.installSpawnCwd()); assert.ok(existsSync(launch.args[0]), "the Node bundle of the worker is built before the cutover"); // Neither the web password hash nor launcher plumbing reaches the helper: it runs npm, candidate preflights and a daemon. assert.equal(launch.env.OMP_WEB_PASSWORD_HASH, undefined); @@ -302,6 +304,8 @@ test("a commit stages and preflights the release before updating hosts, then lau assert.ok(!descriptorText.includes("secret-hash")); const restartEnvironment = JSON.parse(readFileSync(join(attemptDir, "launch-env.json"), "utf8")); assert.equal(restartEnvironment.OMP_WEB_PASSWORD_HASH, "secret-hash"); + assert.equal(restartEnvironment.OMP_WEB_PACKAGE_DIR, installDir); + assert.notEqual(inspections[0].launch.cwd, installDir); assert.equal("OMP_WEB_LAUNCHER_PID" in restartEnvironment, false); const descriptor = JSON.parse(descriptorText); assert.equal(descriptor.installMethod, "npm"); @@ -514,7 +518,7 @@ test("resuming staged bytes under a different artifact approval never dispatches function writeRecoveryJob(attemptDir, attemptId, installDir) { writeFileSync(join(attemptDir, "job.json"), JSON.stringify({ attemptId, install: selfUpdate.resolveServerInstall(), - launch: { command: process.execPath, args: [join(installDir, "bin", "omp-web.js"), "-p", "30177", "-H", "127.0.0.1", "--no-open"], cwd: installDir }, + launch: { command: process.execPath, args: [join(installDir, "bin", "omp-web.js"), "-p", "30177", "-H", "127.0.0.1", "--no-open"], cwd: realProcess.cwdOutsideInstall(installDir) }, server: { pid: DEAD_PID, identity: "old", supervisor: { kind: "foreground" } }, })); } diff --git a/lib/self-update.ts b/lib/self-update.ts index df1eaa9d8..5cfc97421 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -17,7 +17,7 @@ import { atomicWrite, attemptsDir, ensureSecureRoot, isActiveLease, LEASE_MS, leasePath, markerPath, patchStatus, readStateJson, removeSecureEmptyDirectory, removeSecureFile, renewLease, resolveSelfUpdateTempRoot, secureDirectory, secureRegularFile, SelfUpdateError, statusPath, type SelfUpdateStatus, type StoredStatus, } from "./self-update-state"; -import { type UpgradeLaunch, assertUpgradeProcessControl, inspectUpgradeProcess, launchDetachedUpgrade, secureUpgradeDirectory } from "./upgrade-process"; +import { type UpgradeLaunch, assertUpgradeProcessControl, cwdOutsideInstall, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, secureUpgradeDirectory } from "./upgrade-process"; import { approveUpgradePlan, getApprovedReleasePin, getUpgradePlan, prepareUpgradePlan, removeUpgradePlan, upgradePlannedHosts } from "./upgrade-plan"; import type { UpgradeApproval, UpgradePlan } from "./upgrade-types"; import { DISABLE_AUTOUPDATE_ENV_VAR, isUpdateDisabled } from "./update-policy"; @@ -338,15 +338,18 @@ function serverRestart(install: ServerInstall): { launch: Omit { +function restartEnvironment(installDir: string): Record { const env: Record = {}; for (const [name, value] of Object.entries(process.env)) if (value !== undefined && !PLUMBING_ENV.includes(name.toUpperCase())) env[name] = value; + // Direct `server/main.ts` has no launcher to name the install, and its cwd is outside it. + env.OMP_WEB_PACKAGE_DIR = installDir; return env; } /** The helper's environment: no web secrets (it runs npm, candidate preflights and a daemon), no launcher plumbing. */ @@ -414,12 +417,12 @@ async function workerLaunch(job: CommitJob, attemptDir: string, descriptor: stri chmodSync(target, 0o700); return target; }; - if (install.method === "binary") return { command: copyRuntime(process.execPath), args: ["server-update-worker", descriptor], cwd: attemptDir, env }; + if (install.method === "binary") return { command: copyRuntime(process.execPath), args: ["server-update-worker", descriptor], cwd: installSpawnCwd(), env }; const bundle = await Bun.build({ entrypoints: [fileURLToPath(new URL("./server-update-worker.ts", import.meta.url))], target: "node", format: "esm", outdir: attemptDir, naming: "worker.mjs" }); if (!bundle.success) throw new Error(`Could not build the update worker: ${bundle.logs.map(String).join("; ")}`); // A runtime inside the package (Windows locks a running .exe) would be replaced under the worker. const runtime = insideInstall(install.installDir, install.runtime) ? copyRuntime(install.runtime) : install.runtime; - return { command: runtime, args: [join(attemptDir, "worker.mjs"), "--server-update-descriptor", descriptor], cwd: attemptDir, env }; + return { command: runtime, args: [join(attemptDir, "worker.mjs"), "--server-update-descriptor", descriptor], cwd: installSpawnCwd(), env }; } /** After the commit returned: stage and preflight the release, update the plan's other hosts, then hand over to the detached worker. */ @@ -470,7 +473,7 @@ async function coordinate(job: CommitJob): Promise { interruptSessions: job.interruptSessions, }; atomicWrite(join(attemptDir, "descriptor.json"), JSON.stringify(descriptor)); - atomicWrite(join(attemptDir, "launch-env.json"), JSON.stringify(restartEnvironment())); + atomicWrite(join(attemptDir, "launch-env.json"), JSON.stringify(restartEnvironment(install.installDir))); const pid = await launchDetachedUpgrade(await workerLaunch(job, attemptDir, join(attemptDir, "descriptor.json"))); patchStatus(attemptId, { ...(pid === undefined ? {} : { workerPid: pid }), coordinatorPid: undefined }); } catch (error) { @@ -528,7 +531,7 @@ async function startSelfUpdate(attemptId: string, approval: UpgradeApproval, res const serverUrl = links.length === 1 ? links[0].replace(/\/+$/, "") : null; if (localHost.kind !== "separate" && !serverUrl) throw unsupported("The local host's link to this server could not be identified"); await controllable("The detached update worker cannot be started safely", () => - launchDetachedUpgrade({ command: process.execPath, args: ["--version"], cwd: install.installDir, env: helperEnvironment() })); + launchDetachedUpgrade({ command: process.execPath, args: ["--version"], cwd: installSpawnCwd(), env: helperEnvironment() })); // Unknown activity is not consent: only explicit Force permits interruption. const interruptSessions = confirmed.force && localHost.kind === "shared" && local !== null && (local.sessionProcesses !== 0 || local.activeTurns !== 0); diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index d730f7f40..167bb3677 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -150,6 +150,10 @@ function scenario(t, { method = "npm", localHost = { kind: "absent" }, hostArgs const entrypoint = method === "binary" ? join(installDir, "ompweb") : join(installDir, "bin", "omp-web-host.js"); return { pid: host.pid, version: host.version, protocol: 1, linked: host.linked, linkedServers: host.linkedServers, drained: host.drained, executable: method === "binary" ? entrypoint : process.execPath, entrypoint }; }, + // No tray and no process table: the real lookups are PowerShell/CIM queries on Windows that cost seconds each. + findTray: async () => null, + trayPids: async () => [], + releaseLocks: async () => {}, sharedInstall: async (dir, ignored, owned) => { ctx.sharedInstallCalls.push({ dir, ignored, owned }); return ctx.sharing; @@ -173,6 +177,7 @@ test("a package update replaces the installation, restarts it on the new release assert.deepEqual(ctx.calls.filter((call) => call.startsWith("stop") || call.startsWith("restart")), ["stop server", "restart server"]); // The restarted process gets the server's own environment (the web password hash), which never sat in the descriptor. assert.equal(ctx.restarts[0].launch.env.OMP_WEB_PASSWORD_HASH, "secret-hash"); + assert.equal(ctx.restarts[0].launch.env.OMP_WEB_PACKAGE_DIR, ctx.installDir); assert.ok(!readFileSync(ctx.descriptorPath, "utf8").includes("secret-hash")); assert.equal(existsSync(ctx.attemptFile("launch-env.json")), false); assert.equal(existsSync(serverArtifact(ctx.installDir, "backup", ctx.id)), false); @@ -442,23 +447,20 @@ test("Windows: an exclusive directory handle refuses replacement until released" assert.equal(installedVersion(backup), OLD); }); -test("Windows: a stop that leaves the old binary alive refuses cutover without a duplicate restart", { skip: process.platform !== "win32", timeout: 60_000 }, async (t) => { +test("Windows: a stop that leaves the old binary alive is finished by stopping that executable before cutover", { skip: process.platform !== "win32", timeout: 60_000 }, async (t) => { const ctx = scenario(t); - const { child } = await startRunningExecutable(ctx, ctx.installDir); - // The production inventory, unlike the scripted lifecycle, must detect the old executable after the alleged stop. + const { child, exited } = await startRunningExecutable(ctx, ctx.installDir); ctx.deps.sharedInstall = defaultServerUpdateDeps.sharedInstall; - ctx.deps.restart = defaultServerUpdateDeps.restart; + ctx.deps.releaseLocks = defaultServerUpdateDeps.releaseLocks; const identity = await (await import("./process-identity.ts")).processStartIdentity(child.pid); Object.assign(ctx.descriptor.server.process, { pid: child.pid, identity, current: { pid: child.pid, identity } }); ctx.descriptor.server.pids = [child.pid]; writeFileSync(ctx.descriptorPath, JSON.stringify(ctx.descriptor), { mode: 0o600 }); - assert.equal(await run(ctx), 1); - assert.equal(installedVersion(ctx.installDir), OLD); - assert.equal(child.exitCode, null); - assert.equal(ctx.status().state, "failed"); - assert.deepEqual(ctx.restarts, []); - assert.match(ctx.status().error, /shared with another running process/); - assert.equal(ctx.plan().state, "recovery-required"); + assert.equal(await run(ctx), 0); + assert.equal(installedVersion(ctx.installDir), NEW); + await exited; + assert.notEqual(child.exitCode, null); + assert.equal(ctx.status().state, "succeeded"); }); async function livePid(t) { @@ -587,6 +589,20 @@ test("a delayed server stop is reconciled and the previous server restarts durin assert.equal(ctx.plan().state, "failed"); }); +test("a delayed server stop reconciles the server's surviving children before the previous server restarts", async (t) => { + const ctx = scenario(t); + const stop = ctx.deps.stop; + let attempts = 0; + ctx.deps.stop = async (proc) => { + if (proc.role === "server" && ++attempts === 1) throw Object.assign(new Error("Shutdown is still pending"), { code: "stop_pending" }); + return stop(proc); + }; + ctx.deps.releaseLocks = async (_dir, _spare, phase, trees) => { ctx.calls.push(`locks ${phase}${trees ? ` ${trees.join(",")}` : ""}`); }; + assert.equal(await run(ctx), 1); + const scoped = ctx.calls.indexOf("locks all 4242"); + assert.ok(scoped >= 0 && scoped < ctx.calls.indexOf("restart server"), ctx.calls.join(",")); +}); + test("a detached descriptor cannot replace the staged candidate's approved artifact identity", async (t) => { const ctx = scenario(t); const changed = structuredClone(ctx.descriptor); @@ -630,3 +646,101 @@ test("a new host without a specific-server link proof is rolled back, not finali assert.equal(ctx.host.version, OLD); assert.equal(ctx.plan().state, "failed"); }); + +test("tray locks are released before the server stop, and surviving runtimes before the swap", async (t) => { + const ctx = scenario(t); + ctx.deps.releaseLocks = async (_dir, spare, phase) => { + ctx.calls.push(`locks ${phase}`); + assert.ok(spare.includes(process.pid)); + if (phase === "tray") assert.ok(spare.includes(4242)); + else assert.deepEqual(spare, [process.pid]); + }; + assert.equal(await run(ctx), 0); + const tray = ctx.calls.indexOf("locks tray"); + const stop = ctx.calls.indexOf("stop server"); + const all = ctx.calls.indexOf("locks all"); + assert.ok(tray >= 0 && tray < stop && stop < all, ctx.calls.join(",")); +}); + +test("a tray that started the server is relaunched in the interactive session and the server is not started beside it", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const tasks = []; + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "omp-web-tray.exe"), args: ["-Startup"] }); + ctx.deps.relaunchInteractiveTray = async (choice, operationId) => { + tasks.push({ command: choice.command, args: choice.args, operationId }); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 0); + assert.equal(ctx.calls.includes("restart server"), false); + assert.equal(ctx.launches.length, 0); + assert.deepEqual(tasks, [{ command: join(ctx.installDir, "bin", "omp-web-tray.exe"), args: ["-Startup"], operationId: ctx.id }]); +}); + +test("a PowerShell tray is relaunched with its own command and the new install's script", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const tasks = []; + ctx.deps.findTray = async () => ({ exe: "powershell.exe", args: ["-File", join(ctx.installDir, "scripts", "windows", "omp-web-tray.ps1"), "-Startup"] }); + ctx.deps.relaunchInteractiveTray = async (choice) => { + tasks.push({ command: choice.command, args: choice.args }); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 0); + assert.deepEqual(tasks, [{ command: "powershell.exe", args: ["-File", join(ctx.installDir, "scripts", "windows", "omp-web-tray.ps1"), "-Startup"] }]); +}); + +test("a shared install is refused before the tray is stopped, so tray and server keep running", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const trayPids = [555]; + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "omp-web-tray.exe"), args: ["-Startup"] }); + ctx.deps.trayPids = async (_dir, _spare, serverPids) => { ctx.trayPidsServers = serverPids; return trayPids; }; + ctx.deps.releaseLocks = async (_dir, _spare, phase) => { ctx.calls.push(`locks ${phase}`); }; + ctx.deps.relaunchInteractiveTray = async () => { ctx.calls.push("relaunch tray"); }; + ctx.sharing = "another process uses the install"; + assert.equal(await run(ctx), 1); + assert.deepEqual(ctx.calls, []); + assert.ok(ctx.sharedInstallCalls[0].ignored.includes(555), "the tray itself is not a foreign sharer"); + assert.deepEqual(ctx.trayPidsServers, [4242], "the tray wrapper is verified against the server's launcher pids"); +}); + +test("a failure after the tray stopped, with the server still running, stops that server and relaunches the tray that starts it", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + const tasks = []; + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "omp-web-tray.exe"), args: ["-Startup"] }); + ctx.deps.releaseLocks = async (_dir, _spare, phase) => { + ctx.calls.push(`locks ${phase}`); + if (ctx.calls.filter((call) => call === "locks tray").length === 1) throw new Error("the tray stop failed midway"); + }; + ctx.deps.relaunchInteractiveTray = async (choice) => { + ctx.calls.push("relaunch tray"); + tasks.push(choice.command); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 1); + assert.deepEqual(tasks, [join(ctx.installDir, "bin", "omp-web-tray.exe")]); + assert.ok(ctx.calls.indexOf("stop server") > ctx.calls.indexOf("locks tray"), ctx.calls.join(",")); + assert.ok(ctx.calls.indexOf("relaunch tray") > ctx.calls.indexOf("stop server"), ctx.calls.join(",")); + assert.equal(ctx.calls.includes("restart server"), false, "the tray starts the one server, not the worker"); + assert.equal(ctx.launches.length, 0); + assert.equal(installedVersion(ctx.installDir), OLD); +}); + +test("rolling back a tray-only stop reconciles the server's surviving children before the tray starts", async (t) => { + const ctx = scenario(t, { localHost: { kind: "separate" } }); + ctx.deps.findTray = async () => ({ exe: join(ctx.installDir, "bin", "omp-web-tray.exe"), args: ["-Startup"] }); + ctx.deps.releaseLocks = async (_dir, _spare, phase, trees) => { + ctx.calls.push(`locks ${phase}${trees ? ` ${trees.join(",")}` : ""}`); + if (ctx.calls.filter((call) => call === "locks tray").length === 1) throw new Error("the tray stop failed midway"); + }; + ctx.deps.relaunchInteractiveTray = async () => { + ctx.calls.push("relaunch tray"); + const expectation = state.readStateJson(state.markerPath(ctx.id, "expect.json")); + state.atomicWrite(state.markerPath(ctx.id, "boot.json"), JSON.stringify({ attemptId: ctx.id, version: expectation.version, nonce: expectation.nonce, pid: process.pid })); + }; + assert.equal(await run(ctx), 1); + const stop = ctx.calls.indexOf("stop server"); + const scoped = ctx.calls.indexOf("locks all 4242"); + assert.ok(stop >= 0 && scoped > stop && ctx.calls.indexOf("relaunch tray") > scoped, ctx.calls.join(",")); +}); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index 1357275f1..531422d26 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -15,7 +15,7 @@ import { assertOwnedPath, HOST_VERSION_PATTERN, hostLaunch, moveHostRelease, rep import { getAgentDir } from "./omp/paths"; import { isProcessAlive } from "./process-identity"; import { atomicWrite, attemptPath, isActiveLease, leasePath, markerPath, patchStatus, readStateJson, removeSecureFile, renewLease, secureRegularFile, statusPath, type SelfUpdateStage, type StoredStatus } from "./self-update-state"; -import { inspectUpgradeProcess, launchDetachedUpgrade, restartUpgradeProcess, stopUpgradeProcess, type UpgradeLaunch, type UpgradeProcess } from "./upgrade-process"; +import { cwdOutsideInstall, findInstallTrayPids, findTraySupervisor, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, launchInteractiveTray, restartUpgradeProcess, serverRestartChoice, stopInstallLockingProcesses, stopUpgradeProcess, type TraySupervisor, type UpgradeLaunch, type UpgradeProcess } from "./upgrade-process"; import { isRecord } from "./type-guards"; import type { UpgradeParticipant, UpgradePlan } from "./upgrade-types"; import type { ApprovedReleasePin } from "./hosts/update-types"; @@ -63,6 +63,14 @@ export interface ServerUpdateDeps { launch: typeof launchDetachedUpgrade; hostControl: typeof requestHostControl; sharedInstall: typeof sharedHostInstallReason; + /** Stops processes that lock the install directory. `tray` first, so a tray cannot restart the server; `all` after the descriptor stop. */ + releaseLocks: typeof stopInstallLockingProcesses; + /** The tray that started the server, captured before it is stopped. Null when the server had no tray supervisor. */ + findTray: typeof findTraySupervisor; + /** The trays the tray stop would end, and the cmd.exe wrapper between a tray and the server launcher: not foreign sharers, so the shared-install check can run before it stops. */ + trayPids: typeof findInstallTrayPids; + /** Starts the tray in the logged-on session. Not the detached helper: that one is non-interactive. */ + relaunchInteractiveTray: typeof launchInteractiveTray; /** The new server has this long to report ready after it starts. */ bootTimeoutMs: number; /** The host has this long to answer its control endpoint linked, at the expected version. */ @@ -78,6 +86,10 @@ export const defaultServerUpdateDeps: ServerUpdateDeps = { launch: launchDetachedUpgrade, hostControl: requestHostControl, sharedInstall: sharedHostInstallReason, + releaseLocks: stopInstallLockingProcesses, + findTray: findTraySupervisor, + trayPids: findInstallTrayPids, + relaunchInteractiveTray: launchInteractiveTray, bootTimeoutMs: 120_000, hostTimeoutMs: 90_000, pollMs: 250, @@ -275,6 +287,8 @@ export function reportPlan(attemptId: string, participantId: string | null, stat /** Runs one update attempt; the exit code. The terminal result is always in status.json (and the plan), never only in the exit code. */ export async function runServerUpdateWorker(descriptorPath: string, deps: ServerUpdateDeps = defaultServerUpdateDeps): Promise { + // Windows refuses to rename a directory that is a live process's working directory. + if (process.argv[2] === "--server-update-descriptor" || process.argv[2] === "server-update-worker") process.chdir(installSpawnCwd()); // The terminal that started the update may close before it ends. process.on("SIGHUP", () => undefined); let d: ServerUpdateDescriptor; @@ -291,6 +305,9 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server catch (error) { if ((error as NodeJS.ErrnoException).code === "EEXIST") return 1; throw error; } const flags = { hostDrainPending: false, hostDrained: false, hostStopped: false, serverStopped: false, swapped: false, restarted: false }; + let tray: TraySupervisor | null = null; + let relaunchTray = false; + let trayStopped = false; const serverProcess = d.server.process; const hostProcess = d.localHost.kind === "shared" ? d.localHost.process : null; const backup = serverArtifact(d.installDir, "backup", id); @@ -307,7 +324,16 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server const nonce = randomUUID(); removeSecureFile(markerPath(id, "boot.json")); atomicWrite(markerPath(id, "expect.json"), JSON.stringify({ attemptId: id, version, nonce })); - const started = await deps.restart(serverProcess, { ...d.server.launch, env: readLaunchEnvironment(id) }); + const choice = serverRestartChoice(tray, d.installDir, cwdOutsideInstall(d.installDir)); + relaunchTray = choice.kind === "tray"; + // The tray must run in the logged-on session. The detached helper is only for a server that had no tray. + let started: number | undefined; + if (choice.kind === "tray") await deps.relaunchInteractiveTray(choice, id); + else { + const env = readLaunchEnvironment(id); + env.OMP_WEB_PACKAGE_DIR = d.installDir; + started = await deps.restart(serverProcess, { ...d.server.launch, env }); + } const deadline = Date.now() + deps.bootTimeoutMs; let exitedAt: number | undefined; for (;;) { @@ -377,12 +403,28 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server }; if (flags.restarted) { await step("The failed new host could not be stopped, so the previous installation was left in place", stopHostFromInstall, true); - if (!blocked) await step("The failed new server could not be stopped, so the previous installation was left in place", () => deps.stop(serverProcess), true); + if (!blocked) await step("The failed new server could not be stopped, so the previous installation was left in place", async () => { + if (relaunchTray) await deps.releaseLocks(d.installDir, [process.pid], "all"); + else await deps.stop(serverProcess); + }, true); } if (flags.swapped && !blocked) { await step("The previous installation could not be restored", () => restoreInstallDirectory(d.installDir, backup, failed).then(() => { flags.swapped = false; }), true); } - if (flags.serverStopped && !blocked) await step(`The previous server ${d.fromVersion} could not be restarted`, () => startServer(d.fromVersion)); + // Stopping the launcher on Windows can leave its bun child holding the port. Reconcile only the server's own tree: never the host daemon or other processes. + const restartPreviousServer = async (): Promise => { + await deps.releaseLocks(d.installDir, [process.pid], "all", d.server.pids); + await startServer(d.fromVersion); + }; + if (flags.serverStopped && !blocked) await step(`The previous server ${d.fromVersion} could not be restarted`, restartPreviousServer); + // The tray was stopped during preparation while the server kept running. A relaunched tray always starts its own server and would hit the occupied + // port, so stop our server (identity-checked) and let the tray start the one server; recovery is reported only after it is ready. + else if (trayStopped && !blocked) await step(`The previous tray and server ${d.fromVersion} could not be restarted`, async () => { + await deps.releaseLocks(d.installDir, [process.pid], "tray"); // a partial stop may have left it running: never two supervisors + await deps.stop(serverProcess); + flags.serverStopped = true; + await restartPreviousServer(); + }, true); if (flags.hostStopped && !blocked) await step("The previous local host could not be restarted", async () => { await deps.restart(hostProcess!, launchFor(d)); await awaitHost(d.fromVersion, hostProcess!.pid, true); @@ -393,7 +435,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server if (status.drained) await deps.hostControl("resume"); flags.hostDrainPending = false; }); - const touched = flags.serverStopped || flags.hostStopped || flags.swapped || flags.restarted || flags.hostDrained; + const touched = flags.serverStopped || flags.hostStopped || flags.swapped || flags.restarted || flags.hostDrained || trayStopped; const detail = notes.length ? `; ${notes.join("; ")}` : touched ? "; the previous release was restored" : ""; return { message: `${message(primary)}${detail}`.slice(0, 1500), recovered: notes.length === 0 }; }; @@ -405,8 +447,14 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server await verifyStagedRelease(d); // Nothing stops while an unknown process still runs from the installation: the server's tree and the shared host (and its sessions) are expected. const owned = [...d.server.pids, ...(hostProcess ? [hostProcess.pid] : [])]; - const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned], owned); + tray = await deps.findTray(d.installDir, d.server.pids); + // Check before the tray stops: no refusal may leave a stopped tray beside a running server. The trays are ours to stop, not sharers. + const trays = await deps.trayPids(d.installDir, [process.pid, ...owned], d.server.pids); + const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned, ...trays], owned); if (sharing) throw new Error(sharing); + trayStopped = tray !== null; // set before the stop: a release that fails midway may already have stopped it + // The tray exe lives in the package and is not a descriptor pid. Stop it before it can restart the server. + await deps.releaseLocks(d.installDir, [process.pid, ...owned], "tray"); stage("stopping"); if (hostProcess) { @@ -440,7 +488,10 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server } else if (!isProcessAlive(serverProcess.pid)) flags.serverStopped = true; throw error; } - const leftover = await deps.sharedInstall(d.installDir, [process.pid]); + // shortcut: a scheduled task can restart the host during the rename; hold that task across the swap if that race shows up. + // TerminateProcess stops only the descriptor pid, so a bun child whose command line references the install is still running. + await deps.releaseLocks(d.installDir, [process.pid], "all"); + const leftover = await deps.sharedInstall(d.installDir, [process.pid, ...trays]); // the tray's cmd.exe wrapper may still be exiting if (leftover) throw new Error(leftover); stage("installing"); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 8413f630b..4fc74c1c8 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -2,7 +2,7 @@ import { execFile, spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { existsSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, realpathSync, rmSync, statSync, writeFileSync, type Stats } from "node:fs"; -import { tmpdir } from "node:os"; +import { homedir, tmpdir } from "node:os"; import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { setTimeout as pause } from "node:timers/promises"; import { promisify } from "node:util"; @@ -1031,3 +1031,219 @@ export async function restartUpgradeProcess(plan: UpgradeProcess, launch: Upgrad plan.current = instance; return instance.pid ?? undefined; } + +export interface InstallLockRow { pid: number; ppid: number; exe: string; command: string; args?: string[] } +export interface InstallLockHit { pid: number; kind: "tray" | "runtime" } +export interface InstallLockSelection { stop: InstallLockHit[]; blocked: InstallLockHit[] } + +function slash(value: string): string { return value.replaceAll("\\", "/"); } +/** A path prefix safe to search for. A drive root or `/` would match every process. */ +function installKey(installDir: string): string | null { + const root = slash(installDir).replace(/\/+$/, "").toLowerCase(); + if (root.length < 3 || root === "/" || /^[a-z]:$/.test(root)) return null; + return root; +} +function mentionsInstall(text: string, root: string): boolean { + const value = slash(text).toLowerCase(); + let from = 0; + while (from < value.length) { + const at = value.indexOf(root, from); + if (at < 0) return false; + const before = at === 0 ? "" : value[at - 1]; + const after = value[at + root.length] ?? ""; + if ((before === "" || before === "\0" || /[\s"'=]/.test(before)) && (after === "" || after === "/" || after === "\0" || /[\s"']/.test(after))) return true; + from = at + root.length; + } + return false; +} +function ancestorsOf(rows: InstallLockRow[], pid: number): Set { + const byPid = new Map(rows.map((row) => [row.pid, row])); + const found = new Set(); + let current = byPid.get(pid); + for (let hops = 0; current && hops < 32; hops++) { + const parent = byPid.get(current.ppid); + if (!parent || parent.pid === current.pid || found.has(parent.pid)) break; + found.add(parent.pid); + current = parent; + } + return found; +} +/** Every ancestor pid of `pid`, including one that has no row any more. */ +function ancestorPids(rows: InstallLockRow[], pid: number): number[] { + const byPid = new Map(rows.map((row) => [row.pid, row])); + const found: number[] = []; + for (let current = byPid.get(pid), hops = 0; current && hops < 32 && !found.includes(current.ppid); hops++) { + found.push(current.ppid); + current = byPid.get(current.ppid); + } + return found; +} +function lockKind(row: InstallLockRow, root: string): InstallLockHit["kind"] | null { + const path = slash(row.exe || row.command.split("\0").find(Boolean) || ""); + const name = path.slice(path.lastIndexOf("/") + 1).toLowerCase(); + const image = Boolean(row.exe) && mentionsInstall(row.exe, root); + const trayScript = (name === "powershell.exe" || name === "pwsh.exe") && /omp-web-tray\.(?:ps1|exe)/i.test(slash(row.command)) && mentionsInstall(row.command, root); + if ((name === "omp-web-tray.exe" && (image || mentionsInstall(row.command, root))) || trayScript) return "tray"; + if (image || (/^(node|bun)(\.exe)?$/.test(name) && mentionsInstall(row.command, root))) return "runtime"; + return null; +} + +/** + * Processes that keep an npm install from being renamed: the tray executable in the package (web-service.json has no + * pid for it), and node/bun whose image or command line references the install. `sparePids` are not selected. + * `protectPids` are the update worker: an ancestor of one is `blocked`, never stopped — stopping it would kill the worker. + */ +export function selectInstallLockingProcesses(rows: InstallLockRow[], installDir: string, sparePids: number[], protectPids: number[], onlyTreesOf?: number[]): InstallLockSelection { + const root = installKey(installDir); + const spare = new Set(sparePids); + const protectedAncestors = new Set(); + for (const pid of protectPids) for (const ancestor of ancestorsOf(rows, pid)) protectedAncestors.add(ancestor); + const trays: InstallLockHit[] = []; + const rest: InstallLockHit[] = []; + const blocked: InstallLockHit[] = []; + if (!root) return { stop: [], blocked }; + for (const row of rows) { + if (!Number.isSafeInteger(row.pid) || row.pid <= 1 || spare.has(row.pid)) continue; + const kind = lockKind(row, root); + if (!kind) continue; + // A stopped launcher is absent from the table but its survivors keep its pid as ppid (Windows does not reparent), so the chain may end at a pid that is gone. + if (onlyTreesOf && !onlyTreesOf.includes(row.pid) && !ancestorPids(rows, row.pid).some((pid) => onlyTreesOf.includes(pid))) continue; + const hit = { pid: row.pid, kind }; + if (protectedAncestors.has(row.pid)) blocked.push(hit); + else if (kind === "tray") trays.push(hit); + else rest.push(hit); + } + return { stop: [...trays, ...rest], blocked }; +} + +/** Where `npm install` / the update worker must run. A cwd inside the install makes Windows refuse the rename (EBUSY). */ +export function installSpawnCwd(temporary = tmpdir(), installDir?: string): string { + if (!temporary || !isAbsolute(temporary)) fail("The temporary directory is empty; refusing to run the update inside its installation"); + const root = installDir ? installKey(installDir) : null; + const value = slash(temporary).replace(/\/+$/, "").toLowerCase(); + if (root && (value === root || value.startsWith(`${root}/`))) fail("The temporary directory is inside the installation; refusing to use it as the update working directory"); + return temporary; +} + +/** A directory a restarted server may use. Never the installation: that cwd locks the next rename. */ +export function cwdOutsideInstall(installDir: string, home = homedir(), temporary = tmpdir()): string { + const root = installKey(installDir); + const outside = (candidate: string) => { + if (!candidate || !isAbsolute(candidate)) return false; + if (!root) return true; + const value = slash(candidate).replace(/\/+$/, "").toLowerCase(); + return value !== root && !value.startsWith(`${root}/`); + }; + if (outside(home)) return home; + if (outside(temporary)) return temporary; + return fail("No working directory outside the installation; refusing to start a process that would lock the next update"); +} + + +/** Stops install-locking processes one by one; `onlyTreesOf` limits that to those pids and their descendants. Never `taskkill /T`: a tree kill ends a worker that still descends from the target. */ +export async function stopInstallLockingProcesses(installDir: string, sparePids: number[], phase: "tray" | "all", onlyTreesOf?: number[]): Promise { + if (phase === "tray" && process.platform !== "win32") return; + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0") })); + const selection = selectInstallLockingProcesses(rows, installDir, sparePids, [process.pid], onlyTreesOf); + const inPhase = (hit: InstallLockHit) => phase === "all" || hit.kind === "tray"; + const blocked = selection.blocked.filter(inPhase); + if (blocked.length) fail(`Refusing to stop process ${blocked.map((hit) => hit.pid).join(", ")}: the update worker descends from it, and stopping it would end the update`); + for (const hit of selection.stop.filter(inPhase)) { + await signalProcess(hit.pid, "SIGTERM"); + await waitStopped(hit.pid); + } +} + +export interface TraySupervisor { exe: string; args: string[] } +export type ServerRestartChoice = { kind: "tray"; command: string; args: string[]; cwd: string } | { kind: "direct" } + +/** The tray that started one of `serverPids`, if its image or script is this install. Any other tray is not the supervisor. */ +export function traySupervisor(rows: InstallLockRow[], serverPids: number[], installDir: string): TraySupervisor | null { + const root = installKey(installDir); + if (!root) return null; + const byPid = new Map(rows.map((row) => [row.pid, row])); + for (const pid of serverPids) { + for (const ancestor of ancestorsOf(rows, pid)) { + const row = byPid.get(ancestor); + if (!row || lockKind(row, root) !== "tray") continue; + // A parsed command line starts with the executable (argv[0]); it is the command, not an argument to forward. + const args = row.args ? row.args.slice(1) : row.command.split("\0").filter((arg) => arg && arg !== row.exe); + return { exe: row.exe, args }; + } + } + return null; +} + +/** Tray-supervised: start only the tray from the new install (it starts the server). Otherwise the worker starts the server. */ +export function serverRestartChoice(tray: TraySupervisor | null, installDir: string, cwd: string): ServerRestartChoice { + if (!tray) return { kind: "direct" }; + const name = slash(tray.exe).split("/").pop()?.toLowerCase() ?? ""; + const exeArg = (arg: string) => /omp-web-tray\.exe$/i.test(slash(arg)); + const scriptArg = (arg: string) => /omp-web-tray\.ps1$/i.test(slash(arg)); + if (name === "omp-web-tray.exe" || tray.args.some(exeArg)) { + return { kind: "tray", command: join(installDir, "bin", "omp-web-tray.exe"), args: tray.args.filter((arg) => !exeArg(arg)), cwd }; + } + return { kind: "tray", command: tray.exe, args: tray.args.map((arg) => scriptArg(arg) ? join(installDir, "scripts", "windows", "omp-web-tray.ps1") : arg), cwd }; +} + +/** + * Pids the update stops or expects: every tray from this installation that `stopInstallLockingProcesses(.., "tray")` would stop, and + * the `cmd.exe` the tray starts the server through (tray → cmd.exe → launcher → bun), which only the descriptor's `serverPids` verify. + * Any other `cmd.exe`, even one referencing the install, is not owned. + */ +export function selectOwnedTrayPids(rows: InstallLockRow[], installDir: string, sparePids: number[], serverPids: number[]): number[] { + const trays = selectInstallLockingProcesses(rows, installDir, sparePids, [process.pid]).stop.filter((hit) => hit.kind === "tray").map((hit) => hit.pid); + const wrappers = rows.filter((row) => + slash(row.exe).split("/").pop()?.toLowerCase() === "cmd.exe" && trays.includes(row.ppid) + && serverPids.some((pid) => ancestorPids(rows, pid).includes(row.pid))).map((row) => row.pid); + return [...trays, ...wrappers]; +} + +export async function findInstallTrayPids(installDir: string, sparePids: number[], serverPids: number[]): Promise { + if (process.platform !== "win32") return []; // the tray is a Windows program; elsewhere there is nothing to find + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0") })); + return selectOwnedTrayPids(rows, installDir, sparePids, serverPids); +} + +export async function findTraySupervisor(installDir: string, serverPids: number[]): Promise { + if (process.platform !== "win32") return null; + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0"), args: row.args })); + return traySupervisor(rows, serverPids, installDir); +} + +export interface InteractiveTrayTask { taskName: string; exe: string; args: string; cwd: string; encoded: string; script: string } + +const psLiteral = (value: string): string => `'${value.replaceAll("'", "''")}'`; + +/** CommandLineToArgvW's inverse for one argument: quote only when it holds whitespace or a quote. */ +const winArg = (arg: string): string => /[\s"]|^$/.test(arg) ? `"${arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1")}"` : arg; + +/** A one-shot interactive task (`schtasks /IT`) that starts the selected tray command and exits, so deleting the task does not kill the tray. */ +export function interactiveTrayTask(choice: Pick, "command" | "args" | "cwd">, operationId: string): InteractiveTrayTask { + const { command: exe, cwd } = choice; + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(operationId)) fail("Invalid tray relaunch operation id"); + if (!cwd || cwd.includes("\0")) fail("The tray working directory is empty"); + const taskName = `ompweb-tray-${operationId}`; + const args = choice.args.map(winArg).join(" "); + const encoded = encodePowershell(`Start-Process -FilePath ${psLiteral(exe)}${args ? ` -ArgumentList ${psLiteral(args)}` : ""} -WorkingDirectory ${psLiteral(cwd)}`); + const script = [ + `$name = ${psString(taskName)}`, + `$cwd = ${psString(cwd)}`, + `$arg = ${psString(`-NoProfile -WindowStyle Hidden -EncodedCommand ${encoded}`)}`, + // LogonType Interactive is schtasks /IT: the starter runs in the logged-on session, not the non-interactive WMI session. + `$action = New-ScheduledTaskAction -Execute 'powershell.exe' -Argument $arg -WorkingDirectory $cwd`, + `$principal = New-ScheduledTaskPrincipal -UserId ([Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited`, + `$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 1)`, + `Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Settings $settings -Force | Out-Null`, + `try {`, + ` Start-ScheduledTask -TaskName $name`, + ` for ($i = 0; $i -lt 50; $i++) { if ((Get-ScheduledTask -TaskName $name).State -ne 'Running') { break }; Start-Sleep -Milliseconds 100 }`, + `} finally { Unregister-ScheduledTask -TaskName $name -Confirm:$false -ErrorAction SilentlyContinue }`, + ].join("\n"); + return { taskName, exe, args, cwd, encoded, script }; +} + +export async function launchInteractiveTray(choice: Parameters[0], operationId: string): Promise { + if (process.platform !== "win32") fail("An interactive tray can only be relaunched on Windows"); + await powershell(interactiveTrayTask(choice, operationId).script, 60000); +} diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 379371926..748d081b8 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -256,3 +256,173 @@ test("a helper launched under a service survives the service being stopped, with await sleep(1000); } }); + +const INSTALL = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + +test("a tray exe inside the package is selected without a pid in web-service.json", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const rows = [ + { pid: 10, ppid: 1, exe: `${INSTALL}/bin/omp-web-tray.exe`, command: "-Startup" }, + { pid: 11, ppid: 1, exe: "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe", command: `powershell -File "${INSTALL}\\scripts\\windows\\omp-web-tray.ps1" -Startup` }, + { pid: 12, ppid: 1, exe: "C:/Program Files/Code/Code.exe", command: `code ${INSTALL}` }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [], [99]); + assert.deepEqual(selected.blocked, []); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [10, 11]); + assert.ok(selected.stop.every((hit) => hit.kind === "tray")); +}); + +test("a bun or node process whose command line references the install is selected even when it is not a descriptor pid", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const rows = [ + { pid: 20, ppid: 10, exe: "C:/Program Files/nodejs/node.exe", command: `"${INSTALL}\\bin\\omp-web.js" -p 30177` }, + { pid: 30, ppid: 20, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\server\\main.ts` }, + { pid: 31, ppid: 1, exe: "C:/Program Files/bun/bun.exe", command: `bun ${INSTALL}-other/server/main.ts` }, + { pid: 99, ppid: 4, exe: "C:/Temp/runtime.exe", command: "C:/Temp/worker.mjs" }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [99], [99]); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [20, 30]); + assert.ok(selected.stop.every((hit) => hit.kind === "runtime")); +}); + +test("scoped to the server launcher, a surviving bun child is selected after the launcher is gone; the host daemon and unrelated processes are not", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + // Launcher 20 was stopped (absent from the table); Windows keeps its child's ppid, so the chain ends at a pid that no longer exists. + const rows = [ + { pid: 30, ppid: 20, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\server\\main.ts` }, + { pid: 31, ppid: 30, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\server\\worker.ts` }, + { pid: 40, ppid: 1, exe: "C:/Program Files/nodejs/node.exe", command: `"${INSTALL}\\bin\\omp-web-host.js"` }, + { pid: 41, ppid: 40, exe: `${INSTALL}/node_modules/bun/bin/bun.exe`, command: `${INSTALL}\\runner.ts` }, + { pid: 50, ppid: 1, exe: "C:/Program Files/bun/bun.exe", command: `bun ${INSTALL}\\other.ts` }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [99], [99], [20]); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [30, 31]); + assert.deepEqual(selectInstallLockingProcesses(rows, INSTALL, [99], [99]).stop.map((hit) => hit.pid), [30, 31, 40, 41, 50]); +}); + +test("the tray's cmd.exe wrapper between the tray and the launcher is owned; an unrelated cmd.exe referencing the install is not", async () => { + const { selectOwnedTrayPids } = await import("./upgrade-process.ts"); + const row = (pid, ppid, exe, args) => ({ pid, ppid, exe, command: [exe, ...args].join("\0"), args }); + const cmd = "C:/Windows/System32/cmd.exe"; + const bun = `${INSTALL}/node_modules/bun/bin/bun.exe`; + const rows = [ + row(10, 1, `${INSTALL}/bin/omp-web-tray.exe`, [`${INSTALL}/bin/omp-web-tray.exe`, "-Startup"]), + row(15, 10, cmd, [cmd, "/d", "/s", "/c", `"node.exe ${INSTALL}\\bin\\omp-web.js"`]), + row(20, 15, "C:/Program Files/nodejs/node.exe", ["node.exe", `${INSTALL}\\bin\\omp-web.js`]), + row(30, 20, bun, [bun, `${INSTALL}\\server\\main.ts`]), + // Not between the tray and the launcher: a user's shell, one under another parent, and a wrapper of an unrelated process. + row(60, 1, cmd, [cmd, "/k", `cd ${INSTALL}`]), + row(61, 10, cmd, [cmd, "/c", `echo ${INSTALL}`]), + row(62, 61, "C:/Program Files/nodejs/node.exe", ["node.exe", "other.js"]), + ]; + assert.deepEqual(selectOwnedTrayPids(rows, INSTALL, [99], [20, 30]).sort((a, b) => a - b), [10, 15]); + assert.deepEqual(selectOwnedTrayPids(rows, INSTALL, [99], [62]).sort((a, b) => a - b), [10, 61], "only the wrapper above the given server pids is owned"); + assert.deepEqual(selectOwnedTrayPids(rows.filter((r) => r.pid !== 10), INSTALL, [99], [20, 30]), [], "a cmd.exe with no tray above it is not owned"); +}); + +test("the update does not select a process the worker descends from", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const rows = [ + { pid: 10, ppid: 1, exe: `${INSTALL}/bin/omp-web-tray.exe`, command: `${INSTALL}\\bin\\omp-web-tray.exe -Startup` }, + { pid: 99, ppid: 10, exe: "C:/Temp/runtime.exe", command: "C:/Temp/worker.mjs" }, + ]; + const selected = selectInstallLockingProcesses(rows, INSTALL, [99], [99]); + assert.deepEqual(selected.stop, []); + assert.deepEqual(selected.blocked, [{ pid: 10, kind: "tray" }]); +}); + +test("update working directories stay outside the installation", async () => { + const { installSpawnCwd, cwdOutsideInstall } = await import("./upgrade-process.ts"); + const { homedir, tmpdir } = await import("node:os"); + assert.equal(installSpawnCwd(), tmpdir()); + assert.equal(cwdOutsideInstall(INSTALL), homedir()); + assert.notEqual(cwdOutsideInstall(INSTALL), INSTALL); + assert.throws(() => installSpawnCwd("/tmp/ompweb-install", "/tmp/ompweb-install"), /inside the installation/); + assert.equal(cwdOutsideInstall(homedir(), homedir(), tmpdir()), tmpdir()); +}); + +test("a tray that started the server is relaunched alone; otherwise the server restarts directly", async () => { + const { traySupervisor, serverRestartChoice } = await import("./upgrade-process.ts"); + const install = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + const cwd = "C:/Users/x"; + const rows = [ + { pid: 10, ppid: 1, exe: `${install}/bin/omp-web-tray.exe`, command: "", args: [`${install}/bin/omp-web-tray.exe`, "-Startup"] }, + { pid: 20, ppid: 10, exe: "C:/Program Files/nodejs/node.exe", command: "", args: [`${install}/bin/omp-web.js`] }, + { pid: 30, ppid: 20, exe: `${install}/node_modules/bun/bin/bun.exe`, command: "", args: [`${install}/server/main.ts`] }, + { pid: 40, ppid: 1, exe: `${install}/bin/omp-web-tray.exe`, command: "", args: [`${install}/bin/omp-web-tray.exe`, "-OpenBrowser"] }, + ]; + const tray = traySupervisor(rows, [20, 30], install); + assert.deepEqual(tray, { exe: `${install}/bin/omp-web-tray.exe`, args: ["-Startup"] }); + const choice = serverRestartChoice(tray, install, cwd); + assert.equal(choice.kind, "tray"); + if (choice.kind !== "tray") return; + assert.equal(choice.command, join(install, "bin", "omp-web-tray.exe")); + assert.deepEqual(choice.args, ["-Startup"]); + assert.equal(choice.cwd, cwd); + assert.equal(traySupervisor(rows, [99], install), null, "a tray that did not start this server is not its supervisor"); + assert.deepEqual(serverRestartChoice(null, install, cwd), { kind: "direct" }); +}); + +test("a PowerShell tray supervisor keeps its flags and script but not its own executable (argv[0])", async () => { + const { traySupervisor, serverRestartChoice } = await import("./upgrade-process.ts"); + const install = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + const script = `${install}/scripts/windows/omp-web-tray.ps1`; + // Production rows: args is the parsed command line (executable first) and command joins exe and args. + const row = (pid, ppid, exe, args) => ({ pid, ppid, exe, command: [exe, ...args].join("\0"), args }); + const pwshArgs = ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-NoProfile", "-File", script, "-Startup"]; + const rows = [ + row(10, 1, "C:/Program Files/PowerShell/7/pwsh.exe", pwshArgs), + row(20, 10, "C:/Program Files/nodejs/node.exe", ["C:/Program Files/nodejs/node.exe", `${install}/bin/omp-web.js`]), + ]; + const tray = traySupervisor(rows, [20], install); + assert.deepEqual(tray, { exe: "C:/Program Files/PowerShell/7/pwsh.exe", args: ["-NoProfile", "-File", script, "-Startup"] }); + const choice = serverRestartChoice(tray, install, "C:/Users/x"); + assert.equal(choice.kind === "tray" && choice.command, "C:/Program Files/PowerShell/7/pwsh.exe"); + assert.deepEqual(choice.kind === "tray" && choice.args, ["-NoProfile", "-File", join(install, "scripts", "windows", "omp-web-tray.ps1"), "-Startup"]); +}); + +test("the interactive tray task is unique per operation, runs the selected command, and quotes hostile paths", async () => { + const { interactiveTrayTask } = await import("./upgrade-process.ts"); + const exe = "C:/Users/a b/o'mpweb/bin/omp-web-tray.exe"; + const cwd = "C:/Users/a b"; + const first = "11111111-1111-4111-8111-111111111111"; + const second = "22222222-2222-4222-8222-222222222222"; + const task = interactiveTrayTask({ command: exe, args: ["-Startup"], cwd }, first); + const other = interactiveTrayTask({ command: exe, args: ["-Startup"], cwd }, second); + assert.notEqual(task.taskName, other.taskName); + assert.match(task.taskName, new RegExp(first)); + assert.equal(task.exe, exe); + assert.equal(task.args, "-Startup"); + const inner = Buffer.from(task.encoded, "base64").toString("utf16le"); + // Windows PowerShell 5.1 Start-Process has -FilePath but no -LiteralPath. + assert.equal(inner, `Start-Process -FilePath '${exe.replaceAll("'", "''")}' -ArgumentList '-Startup' -WorkingDirectory '${cwd}'`); + assert.match(task.script, /LogonType Interactive/); + assert.match(task.script, /Unregister-ScheduledTask/); + assert.equal(task.script.includes("a b"), false, "a spaced path is not spliced into the registration script"); + assert.equal(task.script.includes("o'mpweb"), false, "a quoted path is not spliced into the registration script"); + assert.throws(() => interactiveTrayTask({ command: exe, args: [], cwd }, "not-an-id"), /operation id/); +}); + +test("the interactive tray task starts a PowerShell tray with its script and arguments, not the exe", async () => { + const { interactiveTrayTask } = await import("./upgrade-process.ts"); + const script = "C:/Users/a b/npm/ompweb/scripts/windows/omp-web-tray.ps1"; + const task = interactiveTrayTask({ command: "powershell.exe", args: ["-NoProfile", "-File", script, "-Startup"], cwd: "C:/Users/a b" }, "11111111-1111-4111-8111-111111111111"); + assert.equal(task.exe, "powershell.exe"); + assert.equal(task.args, `-NoProfile -File "${script}" -Startup`); + const inner = Buffer.from(task.encoded, "base64").toString("utf16le"); + assert.ok(inner.startsWith("Start-Process -FilePath 'powershell.exe' -ArgumentList '"), inner); + assert.equal(inner.includes("omp-web-tray.exe"), false); +}); + +test("a NUL-joined command line still matches an install path in its own argument", async () => { + const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); + const install = "C:/Users/x/AppData/Roaming/npm/node_modules/@kahme247/ompweb"; + const node = "C:/Program Files/nodejs/node.exe"; + const powershell = "C:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe"; + const rows = [ + { pid: 20, ppid: 1, exe: node, command: [node, `${install}/bin/omp-web.js`, "-p", "30177"].join("\0") }, + { pid: 11, ppid: 1, exe: powershell, command: [powershell, "-File", `${install}/scripts/windows/omp-web-tray.ps1`, "-Startup"].join("\0") }, + ]; + const selected = selectInstallLockingProcesses(rows, install, [], [99]); + assert.deepEqual(selected.stop.map((hit) => hit.pid), [11, 20]); +});