Skip to content
2 changes: 2 additions & 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

### Added

- **Windows hosts can be pool workers and accept local maintenance controls.** `ompweb host status`, `drain` and `resume` now work on Windows through a named pipe with a random name and a per-start token, kept in `<agent dir>/omp-web/host-control.json`; requests without the current token are refused. Windows hosts also report CPU busy time and available memory, so pools can place sessions on them. Windows reports no load average, so CPU pressure there comes from busy time alone.
- **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive.
- **Several web apps can share one host daemon and the same live sessions.** Link additional servers with `ompweb host login --add --url <server>` (token from stdin). Prompts, tool progress, results and dialogs stay synchronized, and restarting one web app leaves the other connected to the same omp process. Link protocol v7 moves session startup, idle cleanup and interrupted-run recovery into the host; older links remain supported without sharing their processes. Schedule the first daemon upgrade while its host is quiescent.
- **Sidebar marks sessions with an unsent draft.** A session whose composer still holds text or attachments shows a small pencil beside its title, so a half-written message is easy to find again. The mark follows this browser tab's drafts.
Expand Down Expand Up @@ -60,6 +61,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f
- **Copied uploads start retention at the send time on Windows too.** When a hard link cannot be used or its timestamp cannot be changed, the host writes a fresh exclusive copy instead of inheriting an old staging timestamp. Failed copies remain retryable without replacing unrelated files.
- **Windows servers can manage pools of Unix workers.** Pool configuration and clone paths use the worker's path rules, not the web server's OS. Creation journals retain their synced-file, atomic-rename commit on Windows without requiring unsupported directory fsync.
- **Session HTML export supports Windows OMP launchers.** Export uses the same `.cmd` and `.bat` handling as RPC sessions and version checks.
- **Git status and pool preparation work under Windows short paths.** A workspace opened through an 8.3 short name (such as `C:\Users\RUNNER~1`) or with backslashes no longer loses its Git changes, and pooled preparation no longer rejects its own clone as "not an independent repository". Repository roots are located relative to the workspace instead of comparing Git's spelling of the path with the caller's.
- **Newly sent uploads survive an overlapping retention sweep.** The host refreshes the staged file's timestamp before making its hard link visible, for attachments and Files-panel uploads alike, so cleanup cannot mistake a just-sent file for an expired one. A Files-panel overwrite of an expired file can no longer be deleted by a sweep that inspected the file it replaced.
- **Windows upload cleanup respects each daemon's retention policy.** Shared temporary roots now keep each daemon's attachments in its own subfolder, so a seven-day policy cannot delete another daemon's “Never” uploads, even with copied session UUIDs. Existing flat fallback files remain readable and are left untouched because their owner is unknown.
- **Credential copies and config `.env` files stay private without blocking independent uploads.** The file viewer and upload preflight/overwrite deny editor swaps and backups such as `.agent.db.swp`, `agent.db~`, `.models.yml.swp` and `models.yml-backup` only directly in omp's actual agent directories (including profiles). `.env` and `.env.*` are also denied at genuine default/profile config roots and agent directories, including their symlinked real targets. Same-named session uploads, workspace files and package assets remain readable and replaceable.
Expand Down
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,13 @@ executable/entrypoint identity and maintenance state without credentials.
`ompweb host drain` synchronously checks children (idle included), preparations,
uploads/controls, pending operations and reliable results, and closes new-work admission
only when idle. A busy refusal never kills work or changes admission.
`ompweb host resume` reopens the live daemon. Controls use a private Unix socket inside
the existing daemon, not TCP or a separate service. A disconnected deployer cannot release
a live drain. Ordinary standalone Windows hosts remain unchanged; local controls are Unix-only.
`ompweb host resume` reopens the live daemon. Controls run inside the existing daemon, not
TCP or a separate service: a private Unix socket on Linux and macOS, and on Windows a named
pipe with a random name and a per-start token. Windows keeps both in
`<agent dir>/omp-web/host-control.json`, which only the daemon's user can read through the
agent directory; a request without the current token is refused. A disconnected deployer
cannot release a live drain. Windows hosts report CPU and memory capacity too, so they can be
pool workers.
Disable central member admission before worker rollout; native drain is the final race-free guard.

Worker service cutovers can additionally start drained through `OMP_WEB_HOST_DRAINED=1`
Expand Down
36 changes: 25 additions & 11 deletions bin/omp-web-host.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -195,22 +195,36 @@ test("CLI startup failure cleans its endpoint without dialing or needing credent
assert.equal(existsSync(hostControlPath(f.agentDir)), false);
});

test("CLI controls explicitly reject Windows while ordinary host startup stays available", { skip: process.platform !== "win32" && "Windows-only control-command contract" }, async (t) => {
const scratch = mkdtempSync(join(tmpdir(), "omp-web-host-control-win-"));
t.after(() => rmSync(scratch, { recursive: true, force: true }));
const env = { ...process.env, HOME: scratch, USERPROFILE: scratch, PI_CODING_AGENT_DIR: join(scratch, "agent") };
for (const command of ["status", "drain", "resume"]) {
const result = await hostCommand(env, command);
assert.equal(result.code, 1);
assert.match(result.stderr, /Windows.*unsupported|not supported.*Windows|Unix.only/i);
test("Windows: status/drain/resume reach the real daemon over its pipe; a duplicate is refused and a crash leaves no live control", { skip: process.platform !== "win32" && "Windows named-pipe CLI control" }, async (t) => {
const f = controlFixture(t);
const daemon = launchHost(t, f.env);
let status = await controlReady(f.env);
assert.equal(status.pid, daemon.child.pid);
assert.equal(status.drained, false);
for (const [command, drained] of [["drain", true], ["status", true], ["resume", false]]) {
const answer = await hostCommand(f.env, command);
assert.equal(answer.code, 0, answer.stderr);
assert.equal(JSON.parse(answer.stdout).drained, drained);
}
const duplicate = await hostCommand(f.env);
assert.equal(duplicate.code, 1, duplicate.stderr);
assert.match(duplicate.stderr, /already running/);
// Windows terminates without running handlers: the descriptor stays, but nothing answers on its pipe.
daemon.child.kill();
await daemon.closed;
assert.equal((await hostCommand(f.env, "status")).code, 1, "status must not start a replacement daemon");
const restarted = launchHost(t, f.env);
status = await controlReady(f.env);
assert.equal(status.pid, restarted.child.pid, "a stale descriptor is replaced by the next daemon");
});

test("worker maintenance startup is drained before linking and can be explicitly resumed", unixControl, async (t) => {
test("worker maintenance startup is drained before linking and can be explicitly resumed", async (t) => {
const f = controlFixture(t);
const daemon = launchHost(t, { ...f.env, OMP_WEB_HOST_DRAINED: "1" });
const { hostControlPath } = await import("../lib/hosts/host-control.ts");
t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true }));
if (process.platform !== "win32") {
const { hostControlPath } = await import("../lib/hosts/host-control.ts");
t.after(() => rmSync(join(hostControlPath(f.agentDir), ".."), { recursive: true, force: true }));
}
const status = await controlReady(f.env);
assert.equal(status.pid, daemon.child.pid);
assert.equal(status.drained, true);
Expand Down
5 changes: 3 additions & 2 deletions lib/agent-tools.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import test from "node:test";
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
import { join, posix } from "node:path";
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";

Expand Down Expand Up @@ -434,7 +434,8 @@ async function placementFixture(t, { workerAllows = true, fallback = false, hold
invalidateSessionLists: () => null,
preparePoolProject: ({ input }) => {
preparations.push({ hostId: link.id, ...input });
return { ok: true, value: { cwd: join(dirname(input.cloneRoot), `.${basename(input.cloneRoot)}_worktrees`, "session", input.creationId), projectRoot: input.cloneRoot, baseCommit: "a".repeat(40) } };
// A simulated POSIX worker: its paths follow POSIX rules whatever OS runs this test.
return { ok: true, value: { cwd: posix.join(posix.dirname(input.cloneRoot), `.${posix.basename(input.cloneRoot)}_worktrees`, "session", input.creationId), projectRoot: input.cloneRoot, baseCommit: "a".repeat(40) } };
},
addProject: () => ({ ok: true, value: {} }),
updateProject: () => ({ ok: true, value: { projects: [], newRoots: [] } }),
Expand Down
3 changes: 2 additions & 1 deletion lib/git-changes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ async function git(cwd: string, args: string[], maxBuffer = GIT_STATUS_MAX_BUFFE
return (await pending).stdout;
}

/** The toplevel in `cwd`'s own spelling: Git's --show-toplevel can differ in separators, 8.3 names and symlinks. */
async function findRepositoryRoot(cwd: string): Promise<string | null> {
try {
return (await git(cwd, ["rev-parse", "--show-toplevel"])).trim() || null;
return path.resolve(cwd, (await git(cwd, ["rev-parse", "--show-cdup"])).trim());
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
} catch {
return null;
}
Expand Down
42 changes: 42 additions & 0 deletions lib/hosts/capacity.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -331,3 +331,45 @@ test("the sampler combines leaf and ancestor limits using each ancestor's own me
},
]);
});

test("Windows samples OS CPU times and available memory without /proc, cgroups or a load average", () => {
const cpu = (busy, idle) => ({ times: { user: busy - 10, nice: 0, sys: 6, irq: 4, idle } });
const steps = [
{ cpus: [cpu(100, 900), cpu(100, 900)], free: 8 * GiB },
{ cpus: [cpu(160, 940), cpu(140, 960)], free: 6 * GiB, activeSessions: 1 },
{ cpus: [], free: 6 * GiB },
{ cpus: [cpu(200, 1000), cpu(200, 1000)], free: 5 * GiB },
{ cpus: [cpu(230, 1070), cpu(230, 1070)], free: 5 * GiB, activeSessions: 4 },
];
const script = `
const os = require("node:os");
const fs = require("node:fs");
const { syncBuiltinESMExports } = require("node:module");
const steps = ${JSON.stringify(steps)};
let step;
Object.defineProperty(process, "platform", { value: "win32" });
const readFileSync = fs.readFileSync;
fs.readFileSync = (path, ...args) => {
if (typeof path === "string" && (path.startsWith("/proc/") || path.startsWith("/sys/"))) throw new Error("Windows must not read " + path);
return readFileSync(path, ...args);
};
os.cpus = () => step.cpus;
os.freemem = () => step.free;
os.availableParallelism = () => 2;
os.loadavg = () => { throw new Error("Windows has no load average"); };
syncBuiltinESMExports();
const { sampleHostCapacity } = await import(${JSON.stringify(new URL("./capacity.ts", import.meta.url).href)});
const samples = [];
for (step of steps) samples.push(sampleHostCapacity(step.activeSessions ?? 0));
console.log(JSON.stringify(samples));
`;
const child = spawnSync(process.execPath, ["--eval", script], { encoding: "utf8", timeout: 10_000 });
assert.equal(child.status, 0, child.stderr || child.error?.message);
assert.deepEqual(JSON.parse(child.stdout), [
null,
{ effectiveCpus: 2, load1: 0, busyFraction: 0.5, stealFraction: 0, availableMemoryBytes: 6 * GiB, activeSessions: 1 },
null,
null,
{ effectiveCpus: 2, load1: 0, busyFraction: 0.3, stealFraction: 0, availableMemoryBytes: 5 * GiB, activeSessions: 4 },
]);
});
22 changes: 21 additions & 1 deletion lib/hosts/capacity.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { readFileSync } from "node:fs";
import { availableParallelism, loadavg } from "node:os";
import { availableParallelism, cpus, freemem, loadavg } from "node:os";
import { posix } from "node:path";

export interface HostCapacity {
Expand Down Expand Up @@ -163,8 +163,28 @@ function readOptional(path: string): string | undefined {

let previousCounters: CpuCounters | null = null;

/** Windows has no /proc or cgroups: Node reads per-CPU times and available physical memory from the OS.
* shortcut: Job Object CPU/memory limits are not applied; read them if Windows workers ever run inside a job. */
function windowsSample(): { current: CpuCounters; resources: EffectiveResources } | null {
let busy = 0, idle = 0;
for (const { times } of cpus()) {
busy += times.user + times.nice + times.sys + times.irq;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
idle += times.idle;
}
const available = freemem();
if (!Number.isSafeInteger(busy) || !Number.isSafeInteger(idle) || busy + idle <= 0 || !Number.isSafeInteger(available)) return null;
return { current: { busy, idle, steal: 0 }, resources: { effectiveCpus: availableParallelism(), availableMemoryBytes: available } };
}

/** Samples shared host counters; callers supply active turns, not saved sessions. */
export function sampleHostCapacity(activeSessions: number): HostCapacity | null {
if (process.platform === "win32") {
const sample = windowsSample();
// Windows reports no load average; busyFraction carries the CPU pressure there.
const capacity = sample ? capacityFromInterval(previousCounters, sample.current, sample.resources, 0, activeSessions) : null;
previousCounters = sample?.current ?? null;
return capacity;
}
if (process.platform !== "linux") return null;
try {
const current = parseProcStat(readFileSync("/proc/stat", "utf8"));
Expand Down
3 changes: 2 additions & 1 deletion lib/hosts/files-owner.integration.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,8 @@ async function startDaemon(machine, token) {
await until(() => hub.getHost(machine.hostId)?.status() === "online", `${machine.name} daemon to link`, 20000);
}
async function stopDaemon(machine) {
if (!machine.process || machine.process.exitCode !== null) return;
// Windows kill() terminates without a handler: exitCode stays null and signalCode is set.
if (!machine.process || machine.process.exitCode !== null || machine.process.signalCode !== null) return;
const exited = new Promise((resolve) => machine.process.once("exit", resolve));
machine.process.kill("SIGTERM");
await exited;
Expand Down
3 changes: 1 addition & 2 deletions lib/hosts/host-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ async function main(argv: string[]): Promise<number> {
// Login/logout need none of the daemon, which jiti would otherwise transpile on every run.
const { runHostDaemon } = await import("./daemon");
let daemon: HostDaemon | undefined;
// Windows ordinary standalone hosts retain their existing startup path.
const endpoint = process.platform === "win32" ? null : await createHostControlServer((command) => {
const endpoint = await createHostControlServer((command) => {
if (!daemon) throw new Error("The host daemon is starting");
return daemon.control(command);
});
Expand Down
Loading
Loading