From 6177ce2cd72bd04b370f9677608888202d10a111 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 21:14:41 +0000 Subject: [PATCH 1/9] fix(windows): let in-app updates replace an npm-global install (fixes #513) Windows refuses to rename a package directory that a live process has as its working directory or executable. Stop the tray and leftover node/bun processes without a tree kill, and run the update outside the installation. --- CHANGELOG.md | 1 + lib/hosts/update-worker.ts | 5 +- lib/hosts/update-worker.windows.test.mjs | 15 +++ lib/self-update.test.mjs | 6 +- lib/self-update.ts | 15 +-- lib/server-update-worker.test.mjs | 33 ++++-- lib/server-update-worker.ts | 12 +- lib/upgrade-process.ts | 111 ++++++++++++++++++- lib/upgrade-process.windows-service.test.mjs | 49 ++++++++ 9 files changed, 223 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c879aa1ae..1f4af04bc 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. - **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 c74bc663a..13af361a6 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"; @@ -452,7 +452,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..4c80a31d8 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); @@ -514,7 +516,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..2d5d7daf1 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,9 +338,10 @@ function serverRestart(install: ServerInstall): { launch: Omit - 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..e85f4350f 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -442,23 +442,19 @@ 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; 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) { @@ -630,3 +626,18 @@ 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(",")); +}); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index cc576abce..42aa7ac89 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -15,7 +15,7 @@ import { assertOwnedPath, HOST_VERSION_PATTERN, hostLaunch, moveHostRelease, sha 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 { inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, restartUpgradeProcess, stopInstallLockingProcesses, stopUpgradeProcess, 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,8 @@ 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 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 +80,7 @@ export const defaultServerUpdateDeps: ServerUpdateDeps = { launch: launchDetachedUpgrade, hostControl: requestHostControl, sharedInstall: sharedHostInstallReason, + releaseLocks: stopInstallLockingProcesses, bootTimeoutMs: 120_000, hostTimeoutMs: 90_000, pollMs: 250, @@ -275,6 +278,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; @@ -405,6 +410,8 @@ 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] : [])]; + // The tray exe lives in the package and is not a descriptor pid. Stop it before it is treated as a foreign sharer, and before it can restart the server. + await deps.releaseLocks(d.installDir, [process.pid, ...owned], "tray"); const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned], owned); if (sharing) throw new Error(sharing); @@ -440,6 +447,9 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server } else if (!isProcessAlive(serverProcess.pid)) flags.serverStopped = true; throw error; } + // 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]); if (leftover) throw new Error(leftover); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 8413f630b..8d011f9a4 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,112 @@ 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 } +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 === "" || /[\s"'=]/.test(before)) && (after === "" || after === "/" || /[\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; +} +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[]): 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; + 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. 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"): Promise { + 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]); + 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); + } +} diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 379371926..8ccc114df 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -256,3 +256,52 @@ 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("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()); +}); From 7743b5df5a62f20dba9445ec2f02495b5335b0f9 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 21:20:34 +0000 Subject: [PATCH 2/9] fix(windows): bring the tray back after an npm-global update When the tray started the server, relaunch only that tray from the new install so it starts the one server. A server with no tray supervisor still restarts directly. --- CHANGELOG.md | 2 +- lib/server-update-worker.test.mjs | 18 ++++++++++ lib/server-update-worker.ts | 19 ++++++++-- lib/upgrade-process.ts | 38 +++++++++++++++++++- lib/upgrade-process.windows-service.test.mjs | 22 ++++++++++++ 5 files changed, 94 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f4af04bc..ecf2a5f2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +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. +- **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, the tray comes back from the new install and starts the server; otherwise the server is started directly. - **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/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index e85f4350f..526a15d9b 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -641,3 +641,21 @@ test("tray locks are released before the server stop, and surviving runtimes bef 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 and the server is not started beside it", 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.launch = async (launch) => { + ctx.calls.push("tray"); + ctx.launches.push(launch); + 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 })); + return process.pid; + }; + assert.equal(await run(ctx), 0); + assert.equal(ctx.calls.includes("restart server"), false); + assert.equal(ctx.launches.length, 1); + assert.equal(ctx.launches[0].command, join(ctx.installDir, "bin", "omp-web-tray.exe")); + assert.deepEqual(ctx.launches[0].args, ["-Startup"]); + assert.notEqual(ctx.launches[0].cwd, ctx.installDir); +}); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index 42aa7ac89..afb6142b5 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -15,7 +15,7 @@ import { assertOwnedPath, HOST_VERSION_PATTERN, hostLaunch, moveHostRelease, sha 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, installSpawnCwd, launchDetachedUpgrade, restartUpgradeProcess, stopInstallLockingProcesses, stopUpgradeProcess, type UpgradeLaunch, type UpgradeProcess } from "./upgrade-process"; +import { cwdOutsideInstall, findTraySupervisor, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, 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"; @@ -65,6 +65,8 @@ export interface ServerUpdateDeps { 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 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. */ @@ -81,6 +83,7 @@ export const defaultServerUpdateDeps: ServerUpdateDeps = { hostControl: requestHostControl, sharedInstall: sharedHostInstallReason, releaseLocks: stopInstallLockingProcesses, + findTray: findTraySupervisor, bootTimeoutMs: 120_000, hostTimeoutMs: 90_000, pollMs: 250, @@ -296,6 +299,8 @@ 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; const serverProcess = d.server.process; const hostProcess = d.localHost.kind === "shared" ? d.localHost.process : null; const backup = serverArtifact(d.installDir, "backup", id); @@ -312,7 +317,11 @@ 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"; + const started = choice.kind === "tray" + ? await deps.launch({ command: choice.command, args: choice.args, cwd: choice.cwd }) + : await deps.restart(serverProcess, { ...d.server.launch, env: readLaunchEnvironment(id) }); const deadline = Date.now() + deps.bootTimeoutMs; let exitedAt: number | undefined; for (;;) { @@ -382,7 +391,10 @@ 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); @@ -410,6 +422,7 @@ 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] : [])]; + tray = await deps.findTray(d.installDir, d.server.pids); // The tray exe lives in the package and is not a descriptor pid. Stop it before it is treated as a foreign sharer, and before it can restart the server. await deps.releaseLocks(d.installDir, [process.pid, ...owned], "tray"); const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned], owned); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 8d011f9a4..f5ac8073a 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1032,7 +1032,7 @@ export async function restartUpgradeProcess(plan: UpgradeProcess, launch: Upgrad return instance.pid ?? undefined; } -export interface InstallLockRow { pid: number; ppid: number; exe: string; command: string } +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[] } @@ -1140,3 +1140,39 @@ export async function stopInstallLockingProcesses(installDir: string, sparePids: 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; + const args = row.args ?? 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 }; +} + +export async function findTraySupervisor(installDir: string, serverPids: number[]): Promise { + 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); +} diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 8ccc114df..41bdd7523 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -305,3 +305,25 @@ test("update working directories stay outside the installation", async () => { 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: ["-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: ["-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" }); +}); From c930bfc223cf55f972775ac8cb220cfbe3e4fcd0 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 21:27:24 +0000 Subject: [PATCH 3/9] fix(windows): relaunch the tray in the logged-on session Win32_Process.Create is non-interactive, so a detached tray has no icon. Start it with a one-shot interactive scheduled task, and keep the direct server restart able to find its install. --- CHANGELOG.md | 2 +- lib/self-update.test.mjs | 2 ++ lib/self-update.ts | 6 ++-- lib/server-update-worker.test.mjs | 16 ++++----- lib/server-update-worker.ts | 16 ++++++--- lib/upgrade-process.ts | 36 +++++++++++++++++++- lib/upgrade-process.windows-service.test.mjs | 35 +++++++++++++++++++ 7 files changed, 96 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ecf2a5f2e..a93c92bdf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +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, the tray comes back from the new install and starts the server; otherwise the server is started directly. +- **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. - **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/self-update.test.mjs b/lib/self-update.test.mjs index 4c80a31d8..5f199dcf9 100644 --- a/lib/self-update.test.mjs +++ b/lib/self-update.test.mjs @@ -304,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"); diff --git a/lib/self-update.ts b/lib/self-update.ts index 2d5d7daf1..5cfc97421 100644 --- a/lib/self-update.ts +++ b/lib/self-update.ts @@ -345,9 +345,11 @@ 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. */ @@ -471,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) { diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index 526a15d9b..6f6eb29c6 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -173,6 +173,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); @@ -642,20 +643,17 @@ test("tray locks are released before the server stop, and surviving runtimes bef assert.ok(tray >= 0 && tray < stop && stop < all, ctx.calls.join(",")); }); -test("a tray that started the server is relaunched and the server is not started beside it", async (t) => { +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.launch = async (launch) => { - ctx.calls.push("tray"); - ctx.launches.push(launch); + ctx.deps.relaunchInteractiveTray = async (installDir, operationId) => { + tasks.push({ installDir, 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 })); - return process.pid; }; assert.equal(await run(ctx), 0); assert.equal(ctx.calls.includes("restart server"), false); - assert.equal(ctx.launches.length, 1); - assert.equal(ctx.launches[0].command, join(ctx.installDir, "bin", "omp-web-tray.exe")); - assert.deepEqual(ctx.launches[0].args, ["-Startup"]); - assert.notEqual(ctx.launches[0].cwd, ctx.installDir); + assert.equal(ctx.launches.length, 0); + assert.deepEqual(tasks, [{ installDir: ctx.installDir, operationId: ctx.id }]); }); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index afb6142b5..ae087d25a 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -15,7 +15,7 @@ import { assertOwnedPath, HOST_VERSION_PATTERN, hostLaunch, moveHostRelease, sha 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 { cwdOutsideInstall, findTraySupervisor, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, restartUpgradeProcess, serverRestartChoice, stopInstallLockingProcesses, stopUpgradeProcess, type TraySupervisor, type UpgradeLaunch, type UpgradeProcess } from "./upgrade-process"; +import { cwdOutsideInstall, 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"; @@ -67,6 +67,8 @@ export interface ServerUpdateDeps { 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; + /** 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. */ @@ -84,6 +86,7 @@ export const defaultServerUpdateDeps: ServerUpdateDeps = { sharedInstall: sharedHostInstallReason, releaseLocks: stopInstallLockingProcesses, findTray: findTraySupervisor, + relaunchInteractiveTray: launchInteractiveTray, bootTimeoutMs: 120_000, hostTimeoutMs: 90_000, pollMs: 250, @@ -319,9 +322,14 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server atomicWrite(markerPath(id, "expect.json"), JSON.stringify({ attemptId: id, version, nonce })); const choice = serverRestartChoice(tray, d.installDir, cwdOutsideInstall(d.installDir)); relaunchTray = choice.kind === "tray"; - const started = choice.kind === "tray" - ? await deps.launch({ command: choice.command, args: choice.args, cwd: choice.cwd }) - : await deps.restart(serverProcess, { ...d.server.launch, env: readLaunchEnvironment(id) }); + // 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(d.installDir, 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 (;;) { diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index f5ac8073a..0b2faf10e 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1051,7 +1051,7 @@ function mentionsInstall(text: string, root: string): boolean { if (at < 0) return false; const before = at === 0 ? "" : value[at - 1]; const after = value[at + root.length] ?? ""; - if ((before === "" || /[\s"'=]/.test(before)) && (after === "" || after === "/" || /[\s"']/.test(after))) return true; + if ((before === "" || before === "\0" || /[\s"'=]/.test(before)) && (after === "" || after === "/" || after === "\0" || /[\s"']/.test(after))) return true; from = at + root.length; } return false; @@ -1176,3 +1176,37 @@ export async function findTraySupervisor(installDir: string, serverPids: number[ 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("'", "''")}'`; + +/** A one-shot interactive task (`schtasks /IT`) that starts the new install's tray and exits, so deleting the task does not kill the tray. */ +export function interactiveTrayTask(installDir: string, operationId: string, cwd: string): InteractiveTrayTask { + 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 exe = join(installDir, "bin", "omp-web-tray.exe"); + const args = "-Startup"; + const encoded = encodePowershell(`Start-Process -LiteralPath ${psLiteral(exe)} -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(installDir: string, operationId: string): Promise { + if (process.platform !== "win32") fail("An interactive tray can only be relaunched on Windows"); + await powershell(interactiveTrayTask(installDir, operationId, cwdOutsideInstall(installDir)).script, 60000); +} diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 41bdd7523..2593a4441 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -327,3 +327,38 @@ test("a tray that started the server is relaunched alone; otherwise the server r 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("the interactive tray task is unique per operation, points at the new install, and quotes hostile paths", async () => { + const { interactiveTrayTask } = await import("./upgrade-process.ts"); + const install = "C:/Users/a b/o'mpweb"; + const cwd = "C:/Users/a b"; + const first = "11111111-1111-4111-8111-111111111111"; + const second = "22222222-2222-4222-8222-222222222222"; + const task = interactiveTrayTask(install, first, cwd); + const other = interactiveTrayTask(install, second, cwd); + assert.notEqual(task.taskName, other.taskName); + assert.match(task.taskName, new RegExp(first)); + assert.equal(task.exe, join(install, "bin", "omp-web-tray.exe")); + assert.equal(task.args, "-Startup"); + const inner = Buffer.from(task.encoded, "base64").toString("utf16le"); + assert.ok(inner.includes(task.exe.replaceAll("'", "''")), inner); + assert.match(inner, /-Startup/); + 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(install, "not-an-id", cwd), /operation id/); +}); + +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]); +}); From ba1534cd9ac9306d98dc567161b66c22d55cea3c Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 23:08:27 +0000 Subject: [PATCH 4/9] fix(windows): relaunch the selected tray command and restore a tray stopped during preparation --- lib/server-update-worker.test.mjs | 32 ++++++++++++++++++-- lib/server-update-worker.ts | 11 +++++-- lib/upgrade-process.ts | 17 ++++++----- lib/upgrade-process.windows-service.test.mjs | 27 ++++++++++++----- 4 files changed, 67 insertions(+), 20 deletions(-) diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index 6f6eb29c6..ef1f3eb95 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -647,13 +647,39 @@ test("a tray that started the server is relaunched in the interactive session an 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 (installDir, operationId) => { - tasks.push({ installDir, operationId }); + 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, [{ installDir: ctx.installDir, operationId: ctx.id }]); + 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 tray stopped before preparation fails is relaunched alone, without starting a second server", 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.sharedInstall = async () => "another process uses the install"; + ctx.deps.relaunchInteractiveTray = async (choice) => { tasks.push(choice.command); }; + assert.equal(await run(ctx), 1); + assert.deepEqual(tasks, [join(ctx.installDir, "bin", "omp-web-tray.exe")]); + assert.equal(ctx.calls.includes("stop server"), false); + assert.equal(ctx.calls.includes("restart server"), false); + assert.equal(ctx.launches.length, 0); }); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index ae087d25a..723b8a583 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -304,6 +304,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server 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); @@ -324,7 +325,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server 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(d.installDir, id); + if (choice.kind === "tray") await deps.relaunchInteractiveTray(choice, id); else { const env = readLaunchEnvironment(id); env.OMP_WEB_PACKAGE_DIR = d.installDir; @@ -408,6 +409,11 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server 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)); + // A tray stopped during preparation, before this worker stopped the server: bring back only the tray, since startServer would wait for a second server. + else if (trayStopped && !blocked) await step("The previous tray could not be restarted", async () => { + const choice = serverRestartChoice(tray, d.installDir, cwdOutsideInstall(d.installDir)); + if (choice.kind === "tray") await deps.relaunchInteractiveTray(choice, id); + }); 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); @@ -418,7 +424,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 }; }; @@ -431,6 +437,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server // 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] : [])]; tray = await deps.findTray(d.installDir, d.server.pids); + 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 is treated as a foreign sharer, and before it can restart the server. await deps.releaseLocks(d.installDir, [process.pid, ...owned], "tray"); const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned], owned); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 0b2faf10e..25009d405 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1181,14 +1181,17 @@ export interface InteractiveTrayTask { taskName: string; exe: string; args: stri const psLiteral = (value: string): string => `'${value.replaceAll("'", "''")}'`; -/** A one-shot interactive task (`schtasks /IT`) that starts the new install's tray and exits, so deleting the task does not kill the tray. */ -export function interactiveTrayTask(installDir: string, operationId: string, cwd: string): InteractiveTrayTask { +/** 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 exe = join(installDir, "bin", "omp-web-tray.exe"); - const args = "-Startup"; - const encoded = encodePowershell(`Start-Process -LiteralPath ${psLiteral(exe)} -ArgumentList ${psLiteral(args)} -WorkingDirectory ${psLiteral(cwd)}`); + 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)}`, @@ -1206,7 +1209,7 @@ export function interactiveTrayTask(installDir: string, operationId: string, cwd return { taskName, exe, args, cwd, encoded, script }; } -export async function launchInteractiveTray(installDir: string, operationId: string): Promise { +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(installDir, operationId, cwdOutsideInstall(installDir)).script, 60000); + 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 2593a4441..39c214265 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -328,26 +328,37 @@ test("a tray that started the server is relaunched alone; otherwise the server r assert.deepEqual(serverRestartChoice(null, install, cwd), { kind: "direct" }); }); -test("the interactive tray task is unique per operation, points at the new install, and quotes hostile paths", async () => { +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 install = "C:/Users/a b/o'mpweb"; + 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(install, first, cwd); - const other = interactiveTrayTask(install, second, cwd); + 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, join(install, "bin", "omp-web-tray.exe")); + assert.equal(task.exe, exe); assert.equal(task.args, "-Startup"); const inner = Buffer.from(task.encoded, "base64").toString("utf16le"); - assert.ok(inner.includes(task.exe.replaceAll("'", "''")), inner); - assert.match(inner, /-Startup/); + // 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(install, "not-an-id", cwd), /operation id/); + 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 () => { From da7641d0a3808b392b0ce5d98aeacca3dceee074 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 23:25:20 +0000 Subject: [PATCH 5/9] fix(windows): check the shared install before stopping the tray; drop argv[0] from the tray command --- lib/server-update-worker.test.mjs | 34 +++++++++++++++++--- lib/server-update-worker.ts | 26 +++++++++------ lib/upgrade-process.ts | 9 +++++- lib/upgrade-process.windows-service.test.mjs | 22 +++++++++++-- 4 files changed, 74 insertions(+), 17 deletions(-) diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index ef1f3eb95..a28cdb4cf 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -150,6 +150,7 @@ 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 }; }, + trayPids: async () => [], sharedInstall: async (dir, ignored, owned) => { ctx.sharedInstallCalls.push({ dir, ignored, owned }); return ctx.sharing; @@ -671,15 +672,38 @@ test("a PowerShell tray is relaunched with its own command and the new install's assert.deepEqual(tasks, [{ command: "powershell.exe", args: ["-File", join(ctx.installDir, "scripts", "windows", "omp-web-tray.ps1"), "-Startup"] }]); }); -test("a tray stopped before preparation fails is relaunched alone, without starting a second server", async (t) => { +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 () => 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"); +}); + +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.sharedInstall = async () => "another process uses the install"; - ctx.deps.relaunchInteractiveTray = async (choice) => { tasks.push(choice.command); }; + 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.equal(ctx.calls.includes("stop server"), false); - assert.equal(ctx.calls.includes("restart server"), false); + 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); }); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index d19c087e4..ab9254632 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 { cwdOutsideInstall, findTraySupervisor, inspectUpgradeProcess, installSpawnCwd, launchDetachedUpgrade, launchInteractiveTray, restartUpgradeProcess, serverRestartChoice, stopInstallLockingProcesses, stopUpgradeProcess, type TraySupervisor, 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"; @@ -67,6 +67,8 @@ export interface ServerUpdateDeps { 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; + /** Every tray from the install that the tray stop would end: 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. */ @@ -86,6 +88,7 @@ export const defaultServerUpdateDeps: ServerUpdateDeps = { sharedInstall: sharedHostInstallReason, releaseLocks: stopInstallLockingProcesses, findTray: findTraySupervisor, + trayPids: findInstallTrayPids, relaunchInteractiveTray: launchInteractiveTray, bootTimeoutMs: 120_000, hostTimeoutMs: 90_000, @@ -409,11 +412,14 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server 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)); - // A tray stopped during preparation, before this worker stopped the server: bring back only the tray, since startServer would wait for a second server. - else if (trayStopped && !blocked) await step("The previous tray could not be restarted", async () => { - const choice = serverRestartChoice(tray, d.installDir, cwdOutsideInstall(d.installDir)); - if (choice.kind === "tray") await deps.relaunchInteractiveTray(choice, id); - }); + // 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 startServer(d.fromVersion); + }, 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); @@ -437,11 +443,13 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server // 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] : [])]; 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]); + 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 is treated as a foreign sharer, and before it can restart the server. + // 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"); - const sharing = await deps.sharedInstall(d.installDir, [process.pid, ...owned], owned); - if (sharing) throw new Error(sharing); stage("stopping"); if (hostProcess) { diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 25009d405..50da936e0 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1153,7 +1153,8 @@ export function traySupervisor(rows: InstallLockRow[], serverPids: number[], ins for (const ancestor of ancestorsOf(rows, pid)) { const row = byPid.get(ancestor); if (!row || lockKind(row, root) !== "tray") continue; - const args = row.args ?? row.command.split("\0").filter((arg) => arg && arg !== row.exe); + // 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 }; } } @@ -1172,6 +1173,12 @@ export function serverRestartChoice(tray: TraySupervisor | null, installDir: str return { kind: "tray", command: tray.exe, args: tray.args.map((arg) => scriptArg(arg) ? join(installDir, "scripts", "windows", "omp-web-tray.ps1") : arg), cwd }; } +/** Pids of every tray from this installation that `stopInstallLockingProcesses(.., "tray")` would stop. */ +export async function findInstallTrayPids(installDir: string, sparePids: number[]): Promise { + const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0") })); + return selectInstallLockingProcesses(rows, installDir, sparePids, [process.pid]).stop.filter((hit) => hit.kind === "tray").map((hit) => hit.pid); +} + export async function findTraySupervisor(installDir: string, serverPids: number[]): Promise { 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); diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 39c214265..3887b4470 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -311,10 +311,10 @@ test("a tray that started the server is relaunched alone; otherwise the server r 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: ["-Startup"] }, + { 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: ["-OpenBrowser"] }, + { 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"] }); @@ -328,6 +328,24 @@ test("a tray that started the server is relaunched alone; otherwise the server r 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"; From f8ad2c72dee9c384a0069dcf5032ef2847b64401 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 23:29:47 +0000 Subject: [PATCH 6/9] fix(windows): stop the server's surviving children before relaunching the tray on rollback --- lib/server-update-worker.test.mjs | 18 ++++++++++++++++++ lib/server-update-worker.ts | 2 ++ lib/upgrade-process.ts | 20 ++++++++++++++++---- lib/upgrade-process.windows-service.test.mjs | 15 +++++++++++++++ 4 files changed, 51 insertions(+), 4 deletions(-) diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index a28cdb4cf..8ef9d55e6 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -707,3 +707,21 @@ test("a failure after the tray stopped, with the server still running, stops tha 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 ab9254632..1c4e07882 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -418,6 +418,8 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server 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; + // Stopping the launcher on Windows can leave its bun child holding the port. Only the server's own tree: never the host daemon or other processes. + await deps.releaseLocks(d.installDir, [process.pid], "all", d.server.pids); await startServer(d.fromVersion); }, true); if (flags.hostStopped && !blocked) await step("The previous local host could not be restarted", async () => { diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index 50da936e0..60ea3075b 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1068,6 +1068,16 @@ function ancestorsOf(rows: InstallLockRow[], pid: number): Set { } 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(); @@ -1083,7 +1093,7 @@ function lockKind(row: InstallLockRow, root: string): InstallLockHit["kind"] | n * 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[]): InstallLockSelection { +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(); @@ -1096,6 +1106,8 @@ export function selectInstallLockingProcesses(rows: InstallLockRow[], installDir 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); @@ -1128,10 +1140,10 @@ export function cwdOutsideInstall(installDir: string, home = homedir(), temporar } -/** Stops install-locking processes one by one. 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"): Promise { +/** 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 { 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]); + 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`); diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index 3887b4470..a873fc1cb 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -285,6 +285,21 @@ test("a bun or node process whose command line references the install is selecte 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 update does not select a process the worker descends from", async () => { const { selectInstallLockingProcesses } = await import("./upgrade-process.ts"); const rows = [ From cb1ffe1efc6f86c027ad7582adec6d511ca74baa Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 23:35:43 +0000 Subject: [PATCH 7/9] fix(windows): treat the tray's cmd.exe wrapper as owned in the shared-install check --- lib/server-update-worker.test.mjs | 3 ++- lib/server-update-worker.ts | 6 +++--- lib/upgrade-process.ts | 18 +++++++++++++++--- lib/upgrade-process.windows-service.test.mjs | 20 ++++++++++++++++++++ 4 files changed, 40 insertions(+), 7 deletions(-) diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index 8ef9d55e6..32e984d1e 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -676,13 +676,14 @@ test("a shared install is refused before the tray is stopped, so tray and server 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 () => trayPids; + 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) => { diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index 1c4e07882..bd0aa8edb 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -67,7 +67,7 @@ export interface ServerUpdateDeps { 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; - /** Every tray from the install that the tray stop would end: not foreign sharers, so the shared-install check can run before it stops. */ + /** 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; @@ -446,7 +446,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server const owned = [...d.server.pids, ...(hostProcess ? [hostProcess.pid] : [])]; 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]); + 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 @@ -488,7 +488,7 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server // 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]); + 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 60ea3075b..cbb620e2b 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1185,10 +1185,22 @@ export function serverRestartChoice(tray: TraySupervisor | null, installDir: str return { kind: "tray", command: tray.exe, args: tray.args.map((arg) => scriptArg(arg) ? join(installDir, "scripts", "windows", "omp-web-tray.ps1") : arg), cwd }; } -/** Pids of every tray from this installation that `stopInstallLockingProcesses(.., "tray")` would stop. */ -export async function findInstallTrayPids(installDir: string, sparePids: number[]): Promise { +/** + * 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 { const rows = (await listProcesses()).map((row) => ({ pid: row.pid, ppid: row.ppid, exe: row.exe, command: [row.exe, ...row.args].join("\0") })); - return selectInstallLockingProcesses(rows, installDir, sparePids, [process.pid]).stop.filter((hit) => hit.kind === "tray").map((hit) => hit.pid); + return selectOwnedTrayPids(rows, installDir, sparePids, serverPids); } export async function findTraySupervisor(installDir: string, serverPids: number[]): Promise { diff --git a/lib/upgrade-process.windows-service.test.mjs b/lib/upgrade-process.windows-service.test.mjs index a873fc1cb..748d081b8 100644 --- a/lib/upgrade-process.windows-service.test.mjs +++ b/lib/upgrade-process.windows-service.test.mjs @@ -300,6 +300,26 @@ test("scoped to the server launcher, a surviving bun child is selected after the 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 = [ From 5f4f41ba24682cd7032a4ec6600a258c069a5896 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Tue, 17 Nov 2026 23:56:38 +0000 Subject: [PATCH 8/9] fix(windows): reconcile the server tree on every rollback restart; fake process queries in the worker tests --- lib/server-update-worker.test.mjs | 17 +++++++++++++++++ lib/server-update-worker.ts | 11 +++++++---- lib/upgrade-process.ts | 3 +++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index 32e984d1e..c2e649272 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -150,7 +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; @@ -585,6 +588,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); diff --git a/lib/server-update-worker.ts b/lib/server-update-worker.ts index bd0aa8edb..531422d26 100644 --- a/lib/server-update-worker.ts +++ b/lib/server-update-worker.ts @@ -411,16 +411,19 @@ export async function runServerUpdateWorker(descriptorPath: string, deps: Server 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; - // Stopping the launcher on Windows can leave its bun child holding the port. Only the server's own tree: never the host daemon or other processes. - await deps.releaseLocks(d.installDir, [process.pid], "all", d.server.pids); - await startServer(d.fromVersion); + await restartPreviousServer(); }, true); if (flags.hostStopped && !blocked) await step("The previous local host could not be restarted", async () => { await deps.restart(hostProcess!, launchFor(d)); diff --git a/lib/upgrade-process.ts b/lib/upgrade-process.ts index cbb620e2b..4fc74c1c8 100644 --- a/lib/upgrade-process.ts +++ b/lib/upgrade-process.ts @@ -1142,6 +1142,7 @@ export function cwdOutsideInstall(installDir: string, home = homedir(), temporar /** 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"; @@ -1199,11 +1200,13 @@ export function selectOwnedTrayPids(rows: InstallLockRow[], installDir: string, } 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); } From 5c520baf0218bbf3157e3fa263f6b527f3a616d3 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Wed, 18 Nov 2026 00:16:27 +0000 Subject: [PATCH 9/9] test(windows): keep the real lock release in the old-binary cutover test The scenario now fakes releaseLocks; this Windows test relies on it stopping the still-running old executable before cutover. --- lib/server-update-worker.test.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/server-update-worker.test.mjs b/lib/server-update-worker.test.mjs index c2e649272..167bb3677 100644 --- a/lib/server-update-worker.test.mjs +++ b/lib/server-update-worker.test.mjs @@ -451,6 +451,7 @@ test("Windows: a stop that leaves the old binary alive is finished by stopping t const ctx = scenario(t); const { child, exited } = await startRunningExecutable(ctx, ctx.installDir); ctx.deps.sharedInstall = defaultServerUpdateDeps.sharedInstall; + 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];