Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f

### Fixed

- **In-app updates can replace an npm-global Windows install started by the tray.** The update stops the tray program in the package and any node or bun process still using that install, without ending the update itself, and runs the install from outside the package so Windows can rename it. When the tray started the server, it is started again in the logged-on session and starts the one server; otherwise the server is started directly and still told which install to serve.
- **Windows updates no longer fail when the update status is read while it is written.** Host update state, the server worker's status and upgrade plans retry their atomic replacement for a moment when a concurrent reader holds the file, as the server's own update state already did.
- **GitHub workflow watches no longer regress to stale run states.** Workflow updates retain GitHub's run timestamp and ignore older snapshots for the same or an earlier attempt, so a delayed `queued` response cannot follow a newer `in_progress` delivery.
- **Keep sidebar transcript results aligned with expandable hits on every linked host.** Each daemon now searches its own active conversations, ignoring abandoned branches and pre-compaction messages.
Expand Down
5 changes: 3 additions & 2 deletions lib/hosts/update-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -462,7 +462,8 @@ export async function stagePackage(d: HostPackageSource, staging: string): Promi
const windows = process.platform === "win32" && /\.(cmd|bat)$/i.test(command);
// `/s /c` strips one outer pair of quotes; verbatim so Node does not escape the inner ones (as Node's `shell: true`).
const line = [command, ...args].map((arg) => `"${arg.replaceAll('"', '')}"`).join(" ");
await exec(windows ? process.env.ComSpec || "cmd.exe" : command, windows ? ["/d", "/s", "/c", `"${line}"`] : args, { timeout: DOWNLOAD_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: workerEnvironment(), windowsHide: true, windowsVerbatimArguments: windows });
// Windows refuses to rename a directory that is any live process's working directory, including this install child.
await exec(windows ? process.env.ComSpec || "cmd.exe" : command, windows ? ["/d", "/s", "/c", `"${line}"`] : args, { cwd: tmpdir(), timeout: DOWNLOAD_TIMEOUT_MS, maxBuffer: 1024 * 1024, env: workerEnvironment(), windowsHide: true, windowsVerbatimArguments: windows });
const modules = join(prefix, "node_modules");
const packageDir = join(modules, "@kahme247", "ompweb");
const metadata = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
Expand Down
15 changes: 15 additions & 0 deletions lib/hosts/update-worker.windows.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
});
8 changes: 6 additions & 2 deletions lib/self-update.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -302,6 +304,8 @@ test("a commit stages and preflights the release before updating hosts, then lau
assert.ok(!descriptorText.includes("secret-hash"));
const restartEnvironment = JSON.parse(readFileSync(join(attemptDir, "launch-env.json"), "utf8"));
assert.equal(restartEnvironment.OMP_WEB_PASSWORD_HASH, "secret-hash");
assert.equal(restartEnvironment.OMP_WEB_PACKAGE_DIR, installDir);
assert.notEqual(inspections[0].launch.cwd, installDir);
assert.equal("OMP_WEB_LAUNCHER_PID" in restartEnvironment, false);
const descriptor = JSON.parse(descriptorText);
assert.equal(descriptor.installMethod, "npm");
Expand Down Expand Up @@ -514,7 +518,7 @@ test("resuming staged bytes under a different artifact approval never dispatches
function writeRecoveryJob(attemptDir, attemptId, installDir) {
writeFileSync(join(attemptDir, "job.json"), JSON.stringify({
attemptId, install: selfUpdate.resolveServerInstall(),
launch: { command: process.execPath, args: [join(installDir, "bin", "omp-web.js"), "-p", "30177", "-H", "127.0.0.1", "--no-open"], cwd: installDir },
launch: { command: process.execPath, args: [join(installDir, "bin", "omp-web.js"), "-p", "30177", "-H", "127.0.0.1", "--no-open"], cwd: realProcess.cwdOutsideInstall(installDir) },
server: { pid: DEAD_PID, identity: "old", supervisor: { kind: "foreground" } },
}));
}
Expand Down
21 changes: 12 additions & 9 deletions lib/self-update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -338,15 +338,18 @@ function serverRestart(install: ServerInstall): { launch: Omit<UpgradeLaunch, "e
const hostname = process.env.OMP_WEB_HOSTNAME;
if (!port || !hostname) throw new SelfUpdateError("self_update_unsupported", "The server's listen address is unknown, so it cannot be restarted", 409);
const listen = ["-p", port, "-H", hostname];
if (install.method === "binary") return { launch: { command: join(install.installDir, serverBinaryName()), args: [...listen, "--no-open"], cwd: process.cwd() }, viaLauncher: false };
if (process.env.OMP_WEB_LAUNCHER_PID) return { launch: { command: install.runtime, args: [join(install.installDir, "bin", "omp-web.js"), ...listen, "--no-open"], cwd: install.installDir }, viaLauncher: true };
return { launch: { command: process.execPath, args: [join(install.installDir, "server", "main.ts"), ...listen], cwd: install.installDir }, viaLauncher: false };
const cwd = cwdOutsideInstall(install.installDir);
if (install.method === "binary") return { launch: { command: join(install.installDir, serverBinaryName()), args: [...listen, "--no-open"], cwd }, viaLauncher: false };
if (process.env.OMP_WEB_LAUNCHER_PID) return { launch: { command: install.runtime, args: [join(install.installDir, "bin", "omp-web.js"), ...listen, "--no-open"], cwd }, viaLauncher: true };
return { launch: { command: process.execPath, args: [join(install.installDir, "server", "main.ts"), ...listen], cwd }, viaLauncher: false };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

/** The server's environment for its restart, with its web password hash and every setting. Written owner-only and removed by the worker; never argv. */
function restartEnvironment(): Record<string, string> {
function restartEnvironment(installDir: string): Record<string, string> {
const env: Record<string, string> = {};
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. */
Expand Down Expand Up @@ -414,12 +417,12 @@ async function workerLaunch(job: CommitJob, attemptDir: string, descriptor: stri
chmodSync(target, 0o700);
return target;
};
if (install.method === "binary") return { command: copyRuntime(process.execPath), args: ["server-update-worker", descriptor], cwd: attemptDir, env };
if (install.method === "binary") return { command: copyRuntime(process.execPath), args: ["server-update-worker", descriptor], cwd: installSpawnCwd(), env };
const bundle = await Bun.build({ entrypoints: [fileURLToPath(new URL("./server-update-worker.ts", import.meta.url))], target: "node", format: "esm", outdir: attemptDir, naming: "worker.mjs" });
if (!bundle.success) throw new Error(`Could not build the update worker: ${bundle.logs.map(String).join("; ")}`);
// A runtime inside the package (Windows locks a running .exe) would be replaced under the worker.
const runtime = insideInstall(install.installDir, install.runtime) ? copyRuntime(install.runtime) : install.runtime;
return { command: runtime, args: [join(attemptDir, "worker.mjs"), "--server-update-descriptor", descriptor], cwd: attemptDir, env };
return { command: runtime, args: [join(attemptDir, "worker.mjs"), "--server-update-descriptor", descriptor], cwd: installSpawnCwd(), env };
}

/** After the commit returned: stage and preflight the release, update the plan's other hosts, then hand over to the detached worker. */
Expand Down Expand Up @@ -470,7 +473,7 @@ async function coordinate(job: CommitJob): Promise<void> {
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) {
Expand Down Expand Up @@ -528,7 +531,7 @@ async function startSelfUpdate(attemptId: string, approval: UpgradeApproval, res
const serverUrl = links.length === 1 ? links[0].replace(/\/+$/, "") : null;
if (localHost.kind !== "separate" && !serverUrl) throw unsupported("The local host's link to this server could not be identified");
await controllable("The detached update worker cannot be started safely", () =>
launchDetachedUpgrade({ command: process.execPath, args: ["--version"], cwd: install.installDir, env: helperEnvironment() }));
launchDetachedUpgrade({ command: process.execPath, args: ["--version"], cwd: installSpawnCwd(), env: helperEnvironment() }));
// Unknown activity is not consent: only explicit Force permits interruption.
const interruptSessions = confirmed.force && localHost.kind === "shared" && local !== null && (local.sessionProcesses !== 0 || local.activeTurns !== 0);

Expand Down
Loading
Loading