diff --git a/AGENTS.md b/AGENTS.md index 7ea44cfe6..91e6d4197 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -142,6 +142,8 @@ lib/ local-bootstrap.ts web server side of the local link: `localLinkUrl`, `ensureLocalHostLink` (the `local` record + `host.json`) host-login.ts `host.json` (`loginHost`, `readHostLogin`) and `isLoopbackHost`, shared by the daemon and local-bootstrap session-ops.ts file-reading half of the session/project routes, run on the owning host's daemon (this machine's too) + session-ownership.ts daemon side of the `sessionOwnership` op: `ChannelTable` first (ours), then one bounded process scan (foreign), then the transcript tail (activity only); `unknown` for a failed or switched-off inspection, never `none` + omp-processes.ts the process scan behind that op: Windows CIM / POSIX `ps` parsing, own-user and own-child filtering, `--resume`/`--restore`/`-r` values and unique id-prefix matching, a 10 s cached snapshot with a liveness re-check uploads.ts daemon side of composer uploads: `StagedUploads` (staging dir `/omp-web/uploads/`, offset writes, 24 h sweep, attach into the session's `local/uploads/`), `sanitizeUploadName` upload-retention.ts daemon side of sent-upload retention: `UploadRetention` (op `setUploadRetention`, `/omp-web/upload-retention.json`, sweep at start and every 24 h), `sweepSentUploads`; `upload-retention-sync.ts` is main's side (`startUploadRetentionSync` on every hello, `pushUploadRetention` when the setting changes) link-protocol.ts link messages, codec, binary blob frames, close codes, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox`, `LinkSender`/`PartJoiner` (pieces, fair sending) @@ -377,6 +379,34 @@ The table is static imports, not a runtime glob, so `bun build --compile` (`scri must not open a session file on main for a session that may be remote or local. `SessionInfo.hostId` and `ManagedProject.hostId` carry the host; sidebar and project state key on `hostProjectKey` (bare path on this machine, `:`). +- **Session ownership is a daemon op** (`sessionOwnership {ids}` -> + one `{id, owner, running?, source?, lastActivityAt?}` per id in request order, + ≤ 256 ids; `docs/specs/2026-11-05-session-ownership-design.md`). It lives in the + daemon because only there the three facts meet: `ChannelTable` (ours), + a process scan in the children's PID namespace and uid (foreign), and the + transcript on the machine that owns the file (activity). `owner` is + `daemon`/`foreign`/`none`/`unknown`; a failed, switched-off or unsupported + inspection is `unknown`, never `none`, and then reports no `running` fact. + Ownership and activity are separate: an idle foreign writer still owns the + file, and a fresh transcript without a process is an activity hint only. + Every requested id goes to the scan (a file that does not resolve must not + turn a named writer into `none`), and a scan hit is re-checked against the OS + because the snapshot is cached for 10 s. `--resume`, `--restore` and `-r` are + recognised, including a unique id prefix; only an omp row can own a session, + and the entry point must be anchored — `argv[0]`, or the program a known + launcher runs (`cmd[.exe] /c …`, `sh|bash -c …`, `node|bun …`, after + `env`/`nice`/`nohup`) — so a token that merely appears as an argument + (`grep -r lib/omp`, `cp -r …/omp`, `--exclude-dir=omp`) cannot + claim one, and on Windows a `.cmd`/node shim row counts too. A quoted + command string is re-split and walked the same way, so `sh -c "omp …"` counts + while `sh -c "grep -r lib/omp"` does not; a quoted program path with + spaces (`"C:\Program Files\omp\omp.cmd"`) is still recognised. The POSIX scan + asks `ps` for `-ww`, which lifts the width to procps's 131 072-column cap + instead of the screen width, because `args` is its last column and a clipped + command line would read as naming no session. + The daemon's own children are excluded by transport pid plus a bounded + ppid-chain walk. Detection is advisory, not an atomic lock: a writer can start + between the inspection and a later spawn. - **Link = one WebSocket per host per web server, dialled by the daemon** (`/api/hosts/link`; design `docs/specs/2026-10-31-websocket-link-design.md`). **Text frames** carry the messages (hub → daemon one per frame; daemon → hub newline-separated diff --git a/CHANGELOG.md b/CHANGELOG.md index 33fc53506..381d61a03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added +- **Session ownership is answered where the children run.** A new `sessionOwnership` host op reports, per session, whether this host's daemon runs it, a foreign `omp --resume` process holds it, nobody does, or inspection was impossible (`unknown`). It exists because only the daemon knows its own children (`ChannelTable`), shares the PID namespace and uid of the process scan, and owns the session files; a web-server-side scan silently fails open. Ownership and activity are separate answers: an idle foreign writer still owns the file, and a fresh transcript without a process is an activity hint, never proof of a writer. One bounded process scan answers up to 256 ids per request (larger lists are paged), a failed or switched-off scan is `unknown` and never `none`, and the op never spawns, kills or writes. Every requested id is scanned even when its file does not resolve, so a session a foreign `omp` created since the last list scan is never reported as nobody's; `--resume`, `--restore` and `-r` are recognised (including a unique id prefix), and only an omp row can own a session: its entry point must be anchored at `argv[0]` or after a known launcher (`cmd /c`, `sh -c`, `node`, `env`/`nice`), so `grep -r lib/omp` and `cp -r …/omp` cannot block a send, not even one quote level down (`sh -c "grep -r lib/omp"`) — while a quoted install path with spaces (`"C:\Program Files\omp\omp.cmd"`) still counts. On Windows there is no `process.getuid` and another user's process owner is unreadable unelevated, so the scan keeps every row and narrows by process identity instead: `omp.exe`/`omp`, or a command line naming an omp entry, which also covers a `.cmd`/node shim launcher — a same-machine `omp` of any account counts as a possible owner, the documented process-identity limit. Detection is advisory: it is not an atomic native ownership lock, so a writer can still start between the inspection and a spawn. This is the first of five slices; the command gate, the wire/UI wiring, explicit force and the outbox behaviour follow. - **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 ` (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. diff --git a/docs/specs/2026-10-28-remote-hosts-design.md b/docs/specs/2026-10-28-remote-hosts-design.md index 30167bf0e..71ae325c1 100644 --- a/docs/specs/2026-10-28-remote-hosts-design.md +++ b/docs/specs/2026-10-28-remote-hosts-design.md @@ -469,6 +469,7 @@ parts of those routes stay on main. | `sessionFileExists {path}` / `invalidateSessionLists {path}` | `AgentSessionWrapper` | | `uploadStart {id, name, size, type, attempt}` / `uploadAbort {id}` / `uploadAttach {id, sessionFile, sessionId}` | new in v6: composer uploads (`docs/specs/2026-11-02-file-uploads-design.md`, U3, U5) | | `setUploadRetention {days}` | compatible addition (the link version is unchanged; older daemons answer 501 `unknown_op`, which main ignores): days to keep sent uploads, `null` = for ever; sent on every hello and when the web setting changes (`docs/specs/2026-11-02-file-uploads-design.md`, U6) | +| `sessionOwnership {ids}` | compatible addition (the link version is unchanged; older daemons answer 501 `unknown_op`, which main reads as `unknown`): who holds each session's writer lease on that host — `{id, owner: "daemon"\|"foreign"\|"none"\|"unknown", running?, source?: "process"\|"transcript", lastActivityAt?}` per id, in request order, at most 256 ids per request (main pages a larger list). It lives in the daemon because only there the three facts meet: `ChannelTable` is the authority for "ours" (a spawning, adopted, idle or running child), the process scan runs in the same PID namespace and as the same uid as the children, and the transcript tail is read on the machine that owns the file. Read-only: it never spawns, kills or writes. A failed, switched-off or unsupported inspection answers `unknown`, never `none`, and reports no `running` fact. Ownership is separate from activity: a live foreign `omp` owns the file even while idle (`running: false`), and a fresh transcript without positive owner evidence is an activity hint only (`owner: "none"`, `source: "transcript"`). One bounded process scan answers a whole batch. On POSIX, rows of another uid are dropped; Windows has no `process.getuid` and cannot read another user's process owner unelevated, so the scan narrows by process name instead and a same-machine `omp` of any account counts as a possible owner — the documented process-identity limit. The inspection is not an atomic native ownership lock: a writer can start between it and a later spawn, so a copy can still occur without the user's confirmation (`docs/specs/2026-11-05-session-ownership-design.md`) | Op timeout: 30 s of silence (each result byte frame that arrives restarts it), then 504 naming the host; `uploadAttach` gets 10 minutes (a 2 GiB copy across file systems). diff --git a/docs/specs/2026-11-05-session-ownership-design.md b/docs/specs/2026-11-05-session-ownership-design.md new file mode 100644 index 000000000..1fef838b4 --- /dev/null +++ b/docs/specs/2026-11-05-session-ownership-design.md @@ -0,0 +1,176 @@ +# Session ownership: one writer per session + +Status: slice 1 of 5 implemented (the daemon op and its detector). The command +gate, the wire/UI wiring, explicit force and the outbox behaviour follow. + +## The problem + +omp ≥ 18.5 grants exactly one writer per session. The lease lives in a named +mutex (Windows) or an abstract socket (POSIX) — deliberately not a file, so +omp-web cannot read it. A second `--resume` does not fail: omp silently moves +the conversation to a fresh sibling file on its first write. A chat driven by a +terminal `omp`, by another omp-web server or by a run that was open a moment ago +therefore looked idle, and sending to it forked the conversation into a copy. + +## Where detection lives, and why + +The web server cannot answer this question. Under the shared-daemon model the +daemon owns every session file and every child process, including this machine's; +a scan on the web server runs in another PID namespace, as another uid and on +another filesystem, so it silently fails open. Detection is therefore a host op: + +``` +sessionOwnership { ids: string[] } -> SessionOwnership[] (one entry per id, request order, <= 256) +SessionOwnership = { id, owner: "daemon" | "foreign" | "none" | "unknown", + running?: boolean, source?: "process" | "transcript", lastActivityAt?: number } +``` + +It is a `SessionOps` op, not a `Host` method: id-only, it flows through +`remoteSessionOps`/`validResult` and gets the 501 fallback for older daemons for +free. It never spawns, kills or writes. + +Three facts meet only in the daemon (`lib/hosts/session-ownership.ts`): + +1. **`ChannelTable` is the authority for "ours".** A channel's aliases, launch + files, `spawning` map and `lifecycle` cover a child that is spawning, adopted, + idle between turns or mid-turn — exactly the cases a main-side reconstruction + from `isSessionStarting`, a listed-child set and a crash map kept getting + wrong. A spawn still connecting is ours too: `spawning` is keyed by the + session identity or the launch file. +2. **The process scan runs where the children run.** Same PID namespace, same + uid, so `process.getuid()` filtering is exact and the daemon's own children + are excluded by transport pid plus a bounded ppid-chain walk (the Windows + `cmd.exe /c omp.cmd` wrapper puts the real `omp` one hop below the pid). +3. **The transcript tail is read on the machine that owns the file.** + +## Contract corrections this slice honours + +**Unknown is explicit.** `owner: "unknown"` covers a failed scan, a switched-off +scan (`OMP_WEB_FOREIGN_SCAN=0`) and an older daemon's 501. Main distinguishes a +successful negative answer from an unsupported or failed inspection +(`lib/session-ownership.ts`), answers `unknown` for every id of a failed page and +never turns any failure into `none`. With `owner: "unknown"` no `running` fact is +reported: `false` would be a claim the inspection cannot establish. + +**Ownership is separate from activity.** A live foreign `omp` owns the file even +while idle between turns (`owner: "foreign"`, `running: false`). A fresh +transcript without positive owner evidence is an activity hint, not proof of a +live writer (`owner: "none"`, `running: true`, `source: "transcript"`); it never +blocks a send by itself. Activity is reported only from evidence that can carry +it: a tail window that parsed no complete record (one multi-MiB tool result fills +the 64 KiB window) says nothing about the transcript's end, so `running` is +omitted rather than reported `false`. A scan hit is re-checked against the OS +(`process.kill(pid, 0)`), because the snapshot is cached for 10 s and a terminal +`omp` closed a second ago would otherwise read as a live writer. Daemon-owned +identity comes from `ChannelTable` alone — +there is no main-side `host.pid` record, no recovery-file inference and no second +detector. + +**Batching.** One bounded process scan answers a whole request; the transcript +tail is read only for ids whose file changed inside the 60 s activity window. +Main pages a list longer than 256 ids (`LINK_LIMITS.ownershipIds`) instead of +silently skipping the rest, and a failed page does not stop the remaining pages. +Resolving an id whose path is not cached costs the same one `listAllSessions()` +scan the session list route pays (measured ~2.3 s cold, ~1 ms warm), so the first +request after a list-cache expiry is slower than the rest; the 256-id bound +bounds the reply, not that scan. It is shared with the list route through the +same cache, so it is paid once, not per id. + +**Validation at the host boundary.** The daemon rejects a non-array, an empty +array, a non-string id and more than 256 ids with 400 `invalid_request`; the +detector's own guard uses the same status and code, so one condition has one +answer. Main's +`validResult` rejects a daemon reply whose length, identity or order differs from +the request, or whose `owner`/`running`/`source`/`lastActivityAt` has the wrong +type, as 502 `host_bad_result`. + +**Windows process identity.** `process.getuid` does not exist on Windows, and +reading another user's process owner needs `PROCESS_QUERY_INFORMATION`, which an +unelevated daemon lacks. The Windows scan therefore keeps every row — a +same-machine `omp` of any account counts as a possible owner — and narrows by +process identity instead: a row counts only when its image is `omp.exe`/`omp` or +its command line names an omp entry (`omp.cmd`, `omp.bat`, `omp.js`, a path below +`@oh-my-pi`). That last rule is what makes a shim-launched omp visible: a `.cmd` +launcher (which `wrapWindowsScript` supports) runs omp as a `node.exe` process +below `cmd.exe`, so an image-name-only filter missed it entirely. This is the +documented limit, not an other-user exclusion; POSIX drops other-uid rows and a +kept and a dropped row are both asserted (`lib/hosts/session-ownership.test.mjs`). + +**Resume flags.** omp 18.12 documents `-r, --resume=` ("by ID prefix, +path, or picker if omitted") and `--restore=`, which resumes "as --resume +does, then goes on with what its last process left unfinished" — the flag a user +reaches for after a crash, exactly when a second writer appears. All three are +recognised, with `=`, a space or (`-r`) the attached form, and a *unique* id +prefix is matched as omp would resolve it (an ambiguous or shorter-than-four +prefix claims nothing). A resume argument is only evidence on an omp row: +`-r` is also `grep -r`, `rm -r` and `tar -r`, and a POSIX scan lists every +process of the user. + +**The omp entry point is anchored, not searched for.** A row counts as omp when +the entry point is `argv[0]` — `omp`, `omp.exe`, `omp.cmd`, `omp.bat`, `omp.js`, +`omp.cjs`, `omp.mjs`, or a shim's JS entry below `@oh-my-pi` — or when it is the +program a known launcher runs: `cmd[.exe] /c …`, `sh|bash|dash|zsh -c …`, +`node|bun …`, optionally behind `env`/`nice`/`nohup`/`command`/`exec`/`time` +(with `VAR=value` assignments and value-taking flags such as `nice -n 5` +skipped). A quoted command string is re-split and walked the same way, so +`sh -c "omp --resume "` counts. A quoted program path with spaces is the +program, not a word of the string: `cmd.exe /c "C:\Program Files\omp\omp.cmd" +--resume ` counts, and so does the whole-string form `cmd.exe /d /s /c +"C:\Program Files\omp\omp.cmd --resume "`. A token that merely appears later +is an argument of *that* program, so `grep -r lib/omp`, `cp -r …/omp`, +`grep -r --exclude-dir=omp .`, `omp-web` and a path below `…/omp/` claim +nothing — including one quote level down, where the string is one token: `sh -c +"grep -r lib/omp"` and `cmd.exe /c "grep -r C:\src\omp"` claim +nothing either. Matching "somewhere on the line" was the earlier rule, and it +made an ordinary background `grep -r` a foreign owner — which slice 2 would turn +into a refused send. Matching a *basename* against the whole quoted string was +the same mistake one level down: it read the string's last word as the program. + +One ambiguity survives, because `ps` and CIM drop the quoting that separated a +program path with spaces from its arguments: a path-rooted command whose *last* +argument is a relative path ending in `omp` (`sh -c "/usr/bin/less lib/omp"`) +reads like the real `"/opt/my tools/omp"`. It costs a false foreign owner, never +a false `none`, and needs the program path to be absolute and the argument to be +the first non-flag token, so it is left as a documented limit rather than +guessed at. + +**The POSIX scan asks `ps` for `-ww`.** `ps -eo pid=,ppid=,uid=,args=` clips +`args` — the last column — to the screen width, and `COLUMNS` overrides the pipe +default when a daemon inherits it (tmux panes, some CI wrappers). A clipped +command line loses the `--resume` value and the row reads as naming no session, +the false `none` this slice exists to prevent, so the scan passes `-ww`; a +command-line option wins over the environment, so no env plumbing is needed. +`-ww` is not literally unlimited: procps caps the width at `OUTBUF_SIZE` +(131 072 columns). That is far above the 8 KiB command-line prefix this parser +keeps, so no line it reads is clipped. + +**Every requested id is scanned.** An id whose file does not resolve — a session +a foreign `omp` created after the 30 s list cache was warmed, or a file outside +the sessions tree — still goes to the scan with no path. Dropping such ids made a +live foreign writer answer a definite `none`, the one answer a caller may send +into. + +**Detection is not a lock.** The inspection is read-only and not atomic with a +later spawn: a writer can start between the two, so a `--resume` can still move a +conversation into a copy without the user's confirmation. The op reduces the +window; it does not promise to close it. Callers must not describe it as a lock. + +## Later slices + +2. Command gate: `409 session_owned_elsewhere` with `{ elsewhere }` on the cold + path of `runAgentCommand`, before upload attachment; a live wrapper is never + gated. `session_running_elsewhere` keeps its current meaning (the daemon's + link-compatibility collision in `daemon-channels.ts` `collision()`) and is not + reused. +3. Wire/UI: `elsewhereSessions` on the `running` frame and `GET /api/sessions` + (additive, part of the ETag), a sidebar indicator distinct from the running + spinner, a chat banner. First discovery comes from the normal session-list + refresh, not only the 10 s tick that clears an existing badge; external + presence never feeds local completion/unread transitions. +4. Explicit force: `?force=1` over HTTP and `force: true` on the browser link, + preserving the original submission (images, finished uploads, recovered + drafts, receipt/run ownership) through the 409 and the confirmation. Force + bypasses only this advisory check, never host permissions or lifecycle fences. +5. Outbox: `session_owned_elsewhere` is a final, not-sent refusal + (`may_have_been_sent = 0`, no automatic retry), so a background retry can + never fork a conversation. diff --git a/lib/hosts/daemon-channels.test.mjs b/lib/hosts/daemon-channels.test.mjs index f41636ae4..1f269244d 100644 --- a/lib/hosts/daemon-channels.test.mjs +++ b/lib/hosts/daemon-channels.test.mjs @@ -29,7 +29,10 @@ function harness(rejectNegotiation = false, launchAdvisor = false) { onLine(fn) { listeners.line = fn; return () => {}; }, onStderr(fn) { listeners.stderr = fn; return () => {}; }, onExit(fn) { exits.push(fn); return () => {}; }, }; - const child = { transport, writes, kills: [], holdExit: false, exit(force = false) { for (const exit of exits) exit(0, force ? "SIGKILL" : null); }, emit(frame) { listeners.line?.(JSON.stringify(frame)); } }; children.push(child); + const child = { transport, writes, kills: [], holdExit: false, exit(force = false) { for (const exit of exits) exit(0, force ? "SIGKILL" : null); }, emit(frame) { listeners.line?.(JSON.stringify(frame)); } }; + // A real transport's id is its child's pid (see `spawnLocalRpcTransport`), which `childPids()` reports. + transport.id = String(4000 + children.length); + children.push(child); setTimeout(() => child.emit({ type: "ready", supportedProtocolVersions: [1, 2] }), 0); return { transport, cwd: request.cwd, fellBack: false, launchAdvisor }; } }); @@ -460,3 +463,46 @@ test("a resumed session stays recorded as running between omp's reply and agent_ assert.deepEqual(h.table.running(), [], "a finished resumed run is no longer recorded"); await h.table.stop(); }); + +test("ownership answers for a spawning, adopted, idle and running child, and never for a foreign session", async () => { + const h = harness(); + // Spawning: the spawn promise is in flight, keyed by the session identity, before any channel exists. + const opening = h.table.open(h.a, { sessionId: SAVED, launch }); + const spawning = h.table.ownership(SAVED); + assert.deepEqual(spawning, { owned: true, running: true }, "a child being spawned is already ours"); + assert.deepEqual(h.table.ownership("33333333-3333-4333-8333-333333333333"), { owned: false }); + const opened = await opening; + h.table.release(h.a, opened.ch); + const child = h.children[0]; + // Adopted and idle between turns: still ours, and not running. The launch file comes along, so the detector can + // report `lastActivityAt` for a session this daemon owns. + assert.deepEqual(h.table.ownership(SAVED), { owned: true, running: false, sessionFile: launch.sessionFile }); + // Mid-turn: ours and running. + child.emit({ type: "agent_start" }); + assert.deepEqual(h.table.ownership(SAVED), { owned: true, running: true, sessionFile: launch.sessionFile }); + child.emit({ type: "agent_end" }); + // `agent_end` alone leaves the run unsettled (omp has not settled it yet): still activity. + assert.deepEqual(h.table.ownership(SAVED), { owned: true, running: true, sessionFile: launch.sessionFile }); + child.emit({ type: "session_settled" }); + assert.deepEqual(h.table.ownership(SAVED), { owned: true, running: false, sessionFile: launch.sessionFile }); + // A session known only by its launch file (a new session whose get_state has not named it yet). + assert.deepEqual(h.table.ownership("44444444-4444-4444-8444-444444444444", launch.sessionFile), { owned: true, running: false, sessionFile: launch.sessionFile }); + // A session this daemon does not run at all. + assert.deepEqual(h.table.ownership("44444444-4444-4444-8444-444444444444", "/tmp/other.jsonl"), { owned: false }); + // The transport's pid is reported for the foreign scan to exclude: `childPids()` is the wiring the daemon's + // `sessionOwnership` handler passes as `excludePids`, and returning `[]` would let this daemon's own child read as a + // foreign writer. + assert.deepEqual(h.table.childPids(), [4000]); + child.exit(); + assert.deepEqual(h.table.childPids(), [], "an exited child is no longer excluded"); + await h.table.stop(); +}); + +test("a legacy channel's activity is unknown, not idle", async () => { + const h = harness(); + const spawned = await h.table.spawnLegacy(h.a, { ...launch, ch: "legacy" }); + assert.ok(spawned); + // A legacy channel has no ChannelLifecycle: `running` must be absent so a caller cannot read `false` as a fact. + assert.deepEqual(h.table.ownership(SAVED), { owned: true, sessionFile: launch.sessionFile }); + await h.table.stop(); +}); diff --git a/lib/hosts/daemon-channels.ts b/lib/hosts/daemon-channels.ts index 404eb61e9..950c58474 100644 --- a/lib/hosts/daemon-channels.ts +++ b/lib/hosts/daemon-channels.ts @@ -10,6 +10,7 @@ import { HISTORY_MUTATING_COMMANDS, HostOpError, LINK_LIMITS, MESSAGE_COMMANDS, import { PendingRequests } from "./pending-requests"; import { StreamSnapshot } from "./stream-snapshot"; import { ChannelLifecycle } from "./channel-lifecycle"; +import { comparableProjectPath } from "../comparable-path"; import { SharedRequests } from "./shared-requests"; import { RESUME_PROMPT, type HostResumeEntry } from "./host-resume"; @@ -513,6 +514,47 @@ export class ChannelTable { return [...this.channels.values()].filter(channel => link.version >= 7 ? channel.legacy === null || channel.legacy === link.id : channel.legacy === link.id) .map(channel => ({ ch: channel.ch, sessionId: channel.pending.sessionId, cwd: channel.cwd, pending: replay ? this.pendingFor(channel, link) : null })); } + /** + * Whether a child of this daemon runs (or is being spawned for) a session, and whether it is mid-turn. The authority + * for "ours": `sessionOwnership` (lib/hosts/session-ownership.ts) asks this before it looks at any process, so a + * spawning, adopted, idle or running child is never reported as a foreign writer. `sessionFile` covers a channel that + * knows the session only by its launch file (a new session whose `get_state` has not named it yet). + */ + ownership(id: string, sessionFile?: string | null): { owned: boolean; running?: boolean; sessionFile?: string } { + const key = sessionFile ? comparableProjectPath(sessionFile) : ""; + for (const channel of this.channels.values()) { + if (channel.exited) continue; + const named = channel.aliases.has(id) || channel.pending.sessionId === id + || (key !== "" && [...channel.files].some((file) => comparableProjectPath(file) === key)); + if (!named) continue; + // `isRunning` is "a run is executing (or was started and has not settled)"; `resuming` covers the window between + // omp accepting the resume prompt and its `agent_start`. An idle child between turns is not running. + // A legacy channel has no lifecycle, so its activity is unknown rather than idle. + const running = channel.lifecycle ? channel.lifecycle.isRunning || channel.resuming === true : undefined; + // The launch file (or the one `get_state` named) lets the detector report `lastActivityAt` for our own child too. + const knownFile = channel.launch.sessionFile || [...channel.files][0]; + return { owned: true, ...(running === undefined ? {} : { running }), ...(knownFile ? { sessionFile: knownFile } : {}) }; + } + // A spawn still connecting has no channel yet, but its child is already ours. `spawning` is keyed by the identity + // (session id) or the launch file, which is exactly what a caller asking about this session has. + for (const spawnKey of this.spawning.keys()) { + if (spawnKey === id) return { owned: true, running: true }; + if (key !== "" && comparableProjectPath(spawnKey) === key) return { owned: true, running: true, sessionFile: spawnKey }; + } + return { owned: false }; + } + + /** Pids of this daemon's children, so a process scan never counts one as a foreign writer. */ + childPids(): number[] { + const pids: number[] = []; + for (const channel of this.channels.values()) { + if (channel.exited) continue; + const id = channel.transport.id; + if (id !== undefined && /^\d+$/.test(id)) pids.push(Number(id)); + } + return pids; + } + running(): HostResumeEntry[] { return [...this.channels.values()].filter(channel => (channel.lifecycle?.isRunning || channel.resuming) && channel.pending.sessionId && channel.launch.sessionFile && !channel.sessionMovePending) .map(channel => ({ sessionId: channel.pending.sessionId!, launch: channel.launch })); diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index c79b15a5c..ffa731527 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -46,6 +46,7 @@ const ECHOES_BYTES = ["start", "end"].reduce((sum, id) => sum + Math.ceil(Buffer writeFakeOmp(fakeOmp, `if (process.argv.includes("--version")) { console.log("14.0.0-fake"); process.exit(0); } require("node:fs").writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); +require("node:fs").writeFileSync(${JSON.stringify(pidFile + ".ppid")}, String(process.ppid)); require("node:readline").createInterface({ input: process.stdin }).on("line", (line) => { const command = JSON.parse(line); const { type } = command; @@ -109,6 +110,7 @@ const { nextRedialDelay, runHostDaemon } = await import("./daemon.ts"); const { decodeBlobFrame, LINK_LIMITS, PartJoiner } = await import("./link-protocol.ts"); const { RpcFrameDecoder } = await import("../omp/rpc-frame.ts"); const { RpcProcess } = await import("../omp/rpc-process.ts"); +const { setOmpProcessScanRunner } = await import("./omp-processes.ts"); const decoder = new TextDecoder(); const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); @@ -1411,3 +1413,86 @@ test("a resend skips a channel's lines dropped by an overflow after the welcome" log.restore(); } }); + +/** A process row in the shape the platform's scan parses: Windows CIM JSON, else `ps -eo pid=,ppid=,uid=,args=` lines. + * The daemon picks the parser by `process.platform`, so the fixture must speak that platform's format to be a real + * end-to-end check on both Windows and the ubuntu-latest CI runner. */ +function processListFor(rows) { + if (process.platform === "win32") { + return JSON.stringify(rows.map(({ pid, ppid = 1, commandLine, name = "omp.exe" }) => ({ ProcessId: pid, ParentProcessId: ppid, Name: name, CommandLine: commandLine }))); + } + const uid = typeof process.getuid === "function" ? process.getuid() : 0; + return rows.map(({ pid, ppid = 1, commandLine }) => `${pid} ${ppid} ${uid} ${commandLine}`).join("\n"); +} + +test("sessionOwnership answers over the real link: a daemon child is daemon-owned, a foreign process is foreign, and the batch bound holds", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + const A = "11111111-2222-4333-8444-0000000000c1"; + const B = "11111111-2222-4333-8444-0000000000c2"; + const C = "11111111-2222-4333-8444-0000000000c3"; + const D = "11111111-2222-4333-8444-0000000000c4"; + const dir = join(process.env.PI_CODING_AGENT_DIR, "sessions", "-w"); + mkdirSync(dir, { recursive: true }); + const fileOf = (id) => join(dir, `${id}.jsonl`); + for (const id of [A, B, C]) { + writeFileSync(fileOf(id), `${JSON.stringify({ type: "session", version: 3, id, cwd: scratch, timestamp: "2026-01-01T00:00:00.000Z" })}\n`); + } + // D has no file at all: it must still be matched by a process that names its id, never answered as a definite `none`. + let childPid = 0; + let childParentPid = 0; + setOmpProcessScanRunner(async () => processListFor([ + // The daemon's own spawned child, carrying the pid and parent pid the fake omp reported. Its row names another + // session's file — the shape a child leaves behind after a session move, when `ChannelTable` no longer maps that + // file — so only the pid/ppid-chain exclusion keeps it from reading as a foreign writer. `childPids()` returning + // `[]` would make B `foreign` here. + { pid: childPid, ppid: childParentPid, commandLine: `omp --resume ${fileOf(B)}` }, + // A live foreign `omp --resume` on C. + { pid: 4242, ppid: 1, commandLine: `omp --resume ${fileOf(C)}` }, + // A terminal `omp --restore` naming D's id, whose file does not resolve on this daemon. + { pid: 4243, ppid: 1, commandLine: `omp --restore ${D}` }, + ])); + try { + await waitFor(() => server.hellos.length === 1, "the hello"); + // The pid file is shared by every test in this file: drop a previous child's, or the wait below reads a stale pid. + rmSync(pidFile, { force: true }); + rmSync(`${pidFile}.ppid`, { force: true }); + // A is this daemon's own child: spawn it on its session file. + server.send({ type: "req", id: "spawn-a", op: "spawn", args: { ch: "own", cwd: scratch, recordedCwd: null, sessionFile: fileOf(A), advisor: false } }); + await waitFor(() => server.res("spawn-a"), "the spawn"); + assert.equal(server.res("spawn-a").ok, true, JSON.stringify(server.res("spawn-a"))); + await waitFor(() => existsSync(pidFile) && existsSync(`${pidFile}.ppid`), "the child"); + childPid = Number(readFileSync(pidFile, "utf8")); + childParentPid = Number(readFileSync(`${pidFile}.ppid`, "utf8")); + assert.ok(childPid > 0 && childParentPid > 0, "the fake omp reported its pid and parent pid"); + + server.send({ type: "req", id: "own-1", op: "sessionOwnership", args: { ids: [A, B, C, D] } }); + await waitFor(() => server.res("own-1"), "the ownership answer"); + const answer = server.res("own-1"); + assert.equal(answer.ok, true, JSON.stringify(answer)); + assert.deepEqual(answer.result.value.map(({ id, owner }) => [id, owner]), [[A, "daemon"], [B, "none"], [C, "foreign"], [D, "foreign"]], + "request order; the daemon's child is ours, its child pid is excluded even for another file, the terminal omp is foreign, and an id without a file is still matched by the process that names it"); + // A legacy `spawn` channel has no lifecycle, so its activity is unknown rather than idle: ownership is the fact. + assert.equal("running" in answer.result.value[0], false, "a legacy channel reports ownership without an activity fact"); + assert.equal(answer.result.value[2].running, false, "an idle foreign writer owns the file without running"); + assert.equal(typeof answer.result.value[2].lastActivityAt, "number"); + assert.equal(answer.result.value[3].source, "process", "the --restore process is the evidence for D"); + + // The batch bound is enforced at the host boundary, not silently truncated. + server.send({ type: "req", id: "own-big", op: "sessionOwnership", args: { ids: Array.from({ length: LINK_LIMITS.ownershipIds + 1 }, () => A) } }); + await waitFor(() => server.res("own-big"), "the rejected batch"); + assert.equal(server.res("own-big").ok, false); + assert.equal(server.res("own-big").error.status, 400); + server.send({ type: "req", id: "own-empty", op: "sessionOwnership", args: { ids: [] } }); + await waitFor(() => server.res("own-empty"), "the rejected empty batch"); + assert.equal(server.res("own-empty").error.status, 400); + server.send({ type: "req", id: "own-bad", op: "sessionOwnership", args: { ids: ["not-a-session"] } }); + await waitFor(() => server.res("own-bad"), "the rejected id"); + assert.equal(server.res("own-bad").error.status, 400); + } finally { + setOmpProcessScanRunner(null); + await daemon.stop(); + log.restore(); + } +}); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 7f6fa94af..ea2e9a1dc 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -15,6 +15,7 @@ import type { SpawnRequest } from "./host"; import { encodeLine, HostOpError, isHostOp, LINK_LIMITS, SESSION_OP_PARAMS, type DownMessage, type OpenChannelRequest, type UnknownMessage } from "./link-protocol"; import { localHost, resolveSpawnCwdResult } from "./local-host"; import { sessionOps } from "./session-ops"; +import { detectSessionOwnership } from "./session-ownership"; import packageJson from "../../package.json"; import { checkHostUpdates, configureHostUpdateSafety, getHostUpdateOperation, HostUpdateError, startHostUpdate } from "./updates"; import type { HostUpdateCompatibility, HostUpdateOperation } from "./update-types"; @@ -281,6 +282,18 @@ export function runHostDaemon(options: DaemonOptions): { stop(): Promise; case "uploadAbort": requireUploadOwner(link, args.id); return uploads.abort(args.id); case "uploadAttach": requireUploadOwner(link, args.id); return uploads.attach(args.id, sessionsPath(args.sessionFile), args.sessionId); case "setUploadRetention": return uploadRetention.set(args.days); + case "sessionOwnership": { + // The daemon is the only place where the three facts meet: its ChannelTable (which child is ours), the process + // scan in this PID namespace and as this uid, and the transcript on the machine that owns the file. + const ids = args.ids; + if (!Array.isArray(ids) || ids.length === 0 || ids.length > LINK_LIMITS.ownershipIds || !ids.every(id => typeof id === "string" && isValidSessionId(id))) { + throw new HostOpError(400, "invalid_request", "sessionOwnership takes a non-empty array of at most " + LINK_LIMITS.ownershipIds + " session ids"); + } + return detectSessionOwnership(ids, { + channel: (id, file) => channels.ownership(id, file), + excludePids: () => channels.childPids(), + }); + } default: { const run = sessionOps[op] as (...params: unknown[]) => Promise; const result = await run.apply(sessionOps, SESSION_OP_PARAMS[op].map(name => args[name])); diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 42fe23b69..5fef06920 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -1726,3 +1726,51 @@ test("a hub state kept from before linkSamples existed (bun --hot) gets one inst state.linkSamples = linkSamples; } }); + +test("sessionOwnership answers in request order and rejects a daemon reply that reorders, truncates or invents ids", async () => { + const link = await linkedHost("Ownership box"); + const first = "11111111-2222-4333-8444-0000000000a1"; + const second = "11111111-2222-4333-8444-0000000000a2"; + const answer = [ + { id: first, owner: "foreign", running: false, source: "process", lastActivityAt: 1 }, + { id: second, owner: "unknown" }, + ]; + // Each uplink message needs the next seq: a repeat is dropped as already applied. + let up = 0; + const reply = async (value) => { + const req = await link.down.nextReal(); + assert.equal(req.op, "sessionOwnership"); + assert.deepEqual(req.args, { ids: [first, second] }); + up += 1; + linkPost(link, [{ type: "res", seq: up, id: req.id, ok: true, result: { ok: true, value } }], req.seq); + return req; + }; + + const asking = link.remote.sessionOps.sessionOwnership([first, second]); + await reply(answer); + assert.deepEqual(await asking, { ok: true, value: answer }); + + // A reply that answers another id, drops one, reorders or invents an owner is a boundary failure, not data. + for (const value of [ + [answer[1], answer[0]], + [answer[0]], + [answer[0], { ...answer[1], id: "11111111-2222-4333-8444-0000000000a3" }], + [answer[0], { id: second, owner: "somebody" }], + [answer[0], { id: second, owner: "none", running: "no" }], + ]) { + const rejected = link.remote.sessionOps.sessionOwnership([first, second]); + await reply(value); + await assert.rejects(rejected, (error) => error.status === 502 && error.code === "host_bad_result"); + } + await link.down.cancel(); +}); + +test("an older daemon's 501 for sessionOwnership reaches the caller as a host op error, not as an answer", async () => { + const link = await linkedHost("Old daemon"); + const id = "11111111-2222-4333-8444-0000000000b1"; + const asking = link.remote.sessionOps.sessionOwnership([id]); + const req = await link.down.nextReal(); + await linkPost(link, [{ type: "res", seq: 1, id: req.id, ok: false, error: { status: 501, code: "unknown_op", message: "Unknown host op: sessionOwnership" } }], req.seq); + await assert.rejects(asking, (error) => error.status === 501 && error.code === "unknown_op"); + await link.down.cancel(); +}); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 8bdb14cc5..875c14a15 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -1005,6 +1005,19 @@ function validResult(op: keyof SessionOps, result: unknown, args: unknown[]): bo } case "archiveSession": return isRecord(value) && typeof value.archivedPath === "string"; + case "sessionOwnership": { + // One entry per requested id, in request order: a daemon that answers a + // different set, order or shape would let a caller read one session's + // owner as another's. Everything below the id is optional by contract. + const ids = Array.isArray(args[0]) ? args[0] : null; + if (!ids || !Array.isArray(value) || value.length !== ids.length) return false; + return value.every((entry, index) => isRecord(entry) + && entry.id === ids[index] + && (entry.owner === "daemon" || entry.owner === "foreign" || entry.owner === "none" || entry.owner === "unknown") + && (entry.running === undefined || typeof entry.running === "boolean") + && (entry.source === undefined || entry.source === "process" || entry.source === "transcript") + && optionalNumber(entry.lastActivityAt)); + } // The route reads `projects` and iterates `newRoots`. case "updateProject": return isRecord(value) && Array.isArray(value.projects) && value.projects.every((project) => projectEntry(project) !== null) diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 589252b99..d68da208e 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -46,6 +46,9 @@ export const LINK_LIMITS = { pendingBytes: 1024 * 1024, /** A shared channel's `ready` wait (the legacy wrapper's allowance); an open waits for it plus opTimeoutMs. */ channelReadyMs: 120_000, + /** The most session ids one `sessionOwnership` request may carry: the reply is one entry per id, so the bound keeps a + * single op's answer small and its one process scan bounded. A caller with more ids pages through them. */ + ownershipIds: 256, /** Link head-of-line samples (metric "link"): each side writes or reports them at this count, else after statsFlushMs. * Also the most one `stats` message may carry, which bounds it to about 40 KB. */ statsSamples: 256, @@ -95,6 +98,7 @@ export const SESSION_OP_PARAMS: { readonly [K in keyof SessionOps]: readonly str updateProject: ["updates"], hideProject: ["path"], validateCwd: ["path"], + sessionOwnership: ["ids"], }; /** Every op a daemon answers. Older daemons refuse newer ops with unknown_op; upload ops require v6, `setUploadRetention` diff --git a/lib/hosts/omp-processes.test.mjs b/lib/hosts/omp-processes.test.mjs new file mode 100644 index 000000000..b63b83ec9 --- /dev/null +++ b/lib/hosts/omp-processes.test.mjs @@ -0,0 +1,220 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const { + isOmpProcess, + listOmpProcesses, + parsePosixProcessList, + parseWindowsProcessList, + resetOmpProcessCache, + resumeArguments, + sessionIdsNamedByProcesses, +} = await import("./omp-processes.ts"); + +const A = "11111111-2222-4333-8444-0000000000a1"; +const B = "22222222-3333-4444-8555-0000000000b2"; + +/** The values a command line's resume flags carry, without the flag names. */ +const values = (commandLine) => resumeArguments(commandLine).map((argument) => argument.value); + +test("every documented resume flag is recognised: --resume, --restore, -r, with = or a space", () => { + for (const commandLine of [ + `omp --resume ${A}`, + `omp --resume=${A}`, + `omp -r ${A}`, + `omp -r=${A}`, + `omp -r${A}`, + `omp --restore ${A}`, + `omp --restore=${A}`, + ]) { + assert.deepEqual(values(commandLine), [A], commandLine); + } + // A path value, quoted as Windows reports it and bare as `ps` reports it. + assert.deepEqual(values('omp --resume "C:\\Users\\x\\sessions\\2026-01-01_abc.jsonl"'), ["C:\\Users\\x\\sessions\\2026-01-01_abc.jsonl"]); + assert.deepEqual(values("omp --resume /home/x/.omp/sessions/p/2026-01-01_abc.jsonl"), ["/home/x/.omp/sessions/p/2026-01-01_abc.jsonl"]); + // Not a resume flag: a longer flag that merely starts with the marker, and a marker inside another token. + assert.deepEqual(values("omp --resume-mode fast"), []); + assert.deepEqual(values("omp --no-resume x"), []); + assert.deepEqual(values("omp --restore-all x"), []); + assert.deepEqual(values("omp --model -r"), []); +}); + +test("a resume flag with no value, or one that is the next flag, carries nothing", () => { + assert.deepEqual(values("omp --resume"), []); + assert.deepEqual(values("omp --resume --model x"), []); + assert.deepEqual(values("omp -r --model x"), []); +}); + +test("only an omp process can own a session: grep -r and rm -r are not writers", () => { + const rows = parsePosixProcessList([ + `200 1 1000 /usr/bin/grep -r ${A} /tmp`, + `201 1 1000 rm -r ${A}`, + `202 1 1000 omp --resume ${A}`, + ].join("\n")); + assert.deepEqual(rows.map(isOmpProcess), [false, false, true]); + // The non-omp rows alone must name nothing: a set that also contains the omp row cannot tell the two apart. + assert.deepEqual([...sessionIdsNamedByProcesses(rows.slice(0, 2), [{ id: A }])], [], "grep -r and rm -r are not writers"); + assert.deepEqual([...sessionIdsNamedByProcesses(rows, [{ id: A }])], [A], "the omp row names the session"); +}); + +test("the omp entry is anchored at argv[0] or after a launcher, never a token that merely appears later", () => { + // Each of these names a session id *and* the token `omp` somewhere, but the program is grep/cp: the id is an + // argument of that program, not a resume target. These are the shapes that made a background `grep -r` refuse a send. + const impostors = [ + `grep -r 1111 lib/omp`, + `grep -r 1111 /home/me/omp`, + `grep -r 1111 --exclude-dir=omp .`, + `cp -r 1111 /home/me/omp`, + `omp-web --resume ${A}`, + `C:\\bin\\fake-omp.cmd --resume ${A}`, + `/home/me/omp/foo --resume ${A}`, + `node C:\\app\\server.js --resume ${A}`, + `grep -r omp lib/`, + ]; + for (const commandLine of impostors) { + assert.equal(isOmpProcess({ pid: 200, commandLine }), false, commandLine); + assert.deepEqual([...sessionIdsNamedByProcesses([{ pid: 200, commandLine }], [{ id: A }])], [], commandLine); + } + // The accepted shapes: the image itself, and the program a known launcher runs. + const owners = [ + `omp --resume ${A}`, + `omp.exe --resume ${A}`, + `/usr/local/bin/omp --resume ${A}`, + `cmd.exe /c C:\\bin\\omp.cmd --resume ${A}`, + `cmd.exe /d /s /c "C:\\bin\\omp.cmd --resume ${A}"`, + `node C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\@oh-my-pi\\cli.js --resume ${A}`, + `sh -c "omp --resume ${A}"`, + `bash -lc "omp --resume ${A}"`, + `env FOO=1 nice -n 5 omp --resume ${A}`, + ]; + for (const commandLine of owners) { + assert.equal(isOmpProcess({ pid: 200, commandLine }), true, commandLine); + assert.deepEqual([...sessionIdsNamedByProcesses([{ pid: 200, commandLine }], [{ id: A }])], [A], commandLine); + } + // `grep -r` with the *full* id is the reviewer's original counterexample: the token is an argument, and a full id + // needs no prefix rule to match, so only the anchoring keeps it out. + const full = `grep -r ${A} lib/omp`; + assert.equal(isOmpProcess({ pid: 200, commandLine: full }), false); + assert.deepEqual([...sessionIdsNamedByProcesses([{ pid: 200, commandLine: full }], [{ id: A }])], []); +}); + +test("the POSIX scan asks ps for -ww, so a clipped args column cannot hide a resume value", async () => { + // `args` is the last `ps` column: with `COLUMNS` exported (tmux, some CI wrappers) a long command line is clipped and + // the row reads as naming no session — the false `none` this scan exists to prevent. `-ww` overrides the environment. + resetOmpProcessCache(); + const calls = []; + const scan = await listOmpProcesses({ + platform: "linux", + uid: 1000, + psBin: "/bin/ps", + run: async (file, args) => { + calls.push({ file, args }); + return `200 1 1000 omp --resume ${A}\n`; + }, + }); + assert.equal(scan.ok, true); + assert.equal(calls.length, 1); + assert.equal(calls[0].file, "/bin/ps"); + assert.ok(calls[0].args.includes("-ww"), `ps must be asked for -ww, got ${JSON.stringify(calls[0].args)}`); + assert.deepEqual(calls[0].args.filter((arg) => arg.startsWith("-eo")), ["-eo"], "the column spec is unchanged"); +}); + +test("a shim-launched omp on Windows is recognised by its command line, not only by its image name", () => { + const rows = parseWindowsProcessList(JSON.stringify([ + { ProcessId: 300, ParentProcessId: 1, Name: "cmd.exe", CommandLine: "cmd.exe /c C:\\bin\\omp.cmd --resume " + A }, + { ProcessId: 301, ParentProcessId: 300, Name: "node.exe", CommandLine: "node C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\@oh-my-pi\\cli.js --resume " + A }, + { ProcessId: 302, ParentProcessId: 1, Name: "node.exe", CommandLine: "node C:\\app\\server.js --resume " + A }, + { ProcessId: 303, ParentProcessId: 1, Name: "omp.exe", CommandLine: "omp.exe --resume " + A }, + ])); + assert.deepEqual(rows.map(isOmpProcess), [true, true, false, true]); + assert.deepEqual([...sessionIdsNamedByProcesses([rows[2]], [{ id: A }])], [], "an unrelated node process naming --resume is not omp"); + assert.deepEqual([...sessionIdsNamedByProcesses(rows, [{ id: A }])], [A]); +}); + +test("a launcher's quoted command string is walked as a command line, not basename-matched as a whole", () => { + // `sh -c ""` keeps the whole string as one token. Matching a basename against that token read its + // *last* word as the program: `grep -r lib/omp` ends in `omp`, so a background grep became a foreign owner. + const impostors = [ + `sh -c "grep -r ${A} lib/omp"`, + `bash -c "grep -r ${A} lib/omp"`, + `bash -lc "grep -r ${A} src/omp"`, + `sh -c "grep -r ${A} /home/me/omp"`, + `cmd.exe /c "grep -r ${A} C:\\src\\omp"`, + `sh -c "grep -r 1111 lib/omp"`, + `zsh -c "tar -r ${A} /backup/omp"`, + `bash -c "cp -r ${A} /home/me/omp"`, + `sh -c "grep -r ${A} node_modules/@oh-my-pi/cli"`, + // A path-rooted program whose *argument* ends in `omp` is the same mistake: the program is the first path, and a + // later argument is not a continuation of it. + `sh -c "/bin/cat /home/me/omp"`, + `sh -c "/usr/bin/grep -r ${A} /home/me/omp"`, + `sh -c "/bin/cp ${A} /home/me/omp"`, + `sh -c "/bin/echo omp"`, + ]; + for (const commandLine of impostors) { + assert.equal(isOmpProcess({ pid: 200, commandLine }), false, commandLine); + assert.deepEqual([...sessionIdsNamedByProcesses([{ pid: 200, commandLine }], [{ id: A }])], [], commandLine); + } + // The real shapes that carry a program path with spaces must still be recognised: the quoted path is the program, + // and the flags after it are its arguments. + const owners = [ + `sh -c "omp --resume ${A}"`, + `sh -c "/usr/local/bin/omp --resume ${A}"`, + `sh -c "./omp --resume ${A}"`, + `sh -c "C:\\bin\\omp.cmd --resume ${A}"`, + `cmd.exe /c "C:\\Program Files\\omp\\omp.cmd" --resume ${A}`, + `cmd.exe /d /s /c "C:\\Program Files\\omp\\omp.cmd --resume ${A}"`, + `sh -c "C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\@oh-my-pi\\cli.js --resume ${A}"`, + `sh -c "/opt/my tools/omp --resume ${A}"`, + `sh -c "/usr/bin/env FOO=1 omp --resume ${A}"`, + ]; + for (const commandLine of owners) { + assert.equal(isOmpProcess({ pid: 200, commandLine }), true, commandLine); + assert.deepEqual([...sessionIdsNamedByProcesses([{ pid: 200, commandLine }], [{ id: A }])], [A], commandLine); + } +}); + +test("the Windows scan keeps a quoted grep out and a quoted program path in, through the CIM rows", () => { + // CIM reports the command line with its quoting intact, so the shell wrapper's command string arrives as one token + // here too: the same discrimination must hold on the path the daemon actually reads on Windows. + const rows = parseWindowsProcessList(JSON.stringify([ + { ProcessId: 400, ParentProcessId: 1, Name: "cmd.exe", CommandLine: `cmd.exe /c "grep -r ${A} C:\\src\\omp"` }, + { ProcessId: 401, ParentProcessId: 1, Name: "cmd.exe", CommandLine: `cmd.exe /c "C:\\Program Files\\omp\\omp.cmd" --resume ${A}` }, + { ProcessId: 402, ParentProcessId: 1, Name: "cmd.exe", CommandLine: `cmd.exe /d /s /c "C:\\Program Files\\omp\\omp.cmd --resume ${A}"` }, + { ProcessId: 403, ParentProcessId: 1, Name: "sh.exe", CommandLine: `sh -c "grep -r ${A} lib/omp"` }, + ])); + assert.deepEqual(rows.map(isOmpProcess), [false, true, true, false]); + assert.deepEqual([...sessionIdsNamedByProcesses([rows[0], rows[3]], [{ id: A }])], [], "a quoted grep names no session"); + assert.deepEqual([...sessionIdsNamedByProcesses(rows, [{ id: A }])], [A], "the spaced install path still owns it"); +}); + +test("a unique id prefix names the session; an ambiguous or too-short prefix does not", () => { + const C = "11111111-9999-4333-8444-0000000000c3"; + const candidates = [{ id: A }, { id: B }, { id: C }]; + const named = (value) => [...sessionIdsNamedByProcesses([{ pid: 200, commandLine: `omp --resume ${value}` }], candidates)]; + assert.deepEqual(named("11111111-2222"), [A], "a unique prefix is how omp's --resume takes an id"); + assert.deepEqual(named("11111111"), [], "an ambiguous prefix leaves omp to pick: no session is claimed"); + assert.deepEqual(named("11"), [], "too short to attribute a writer"); + assert.deepEqual(named("22222222"), [B]); + // A path that merely starts with the prefix is not a prefix match. + assert.deepEqual(named("/tmp/11111111"), []); +}); + +test("a value that names a session file still matches by path and by basename", () => { + const file = "/home/x/.omp/sessions/p/2026-01-01_abc.jsonl"; + const named = sessionIdsNamedByProcesses([{ pid: 200, commandLine: `omp --resume ${file}` }], [{ id: A, sessionFile: file }]); + assert.deepEqual([...named], [A]); + // A copy of the file elsewhere still matches by basename, as before. + const copied = sessionIdsNamedByProcesses([{ pid: 200, commandLine: "omp --resume /other/place/2026-01-01_abc.jsonl" }], [{ id: A, sessionFile: file }]); + assert.deepEqual([...copied], [A]); +}); + +test("a dead row is skipped; a live second writer on the same file still owns it", () => { + const processes = [ + { pid: 200, commandLine: `omp --resume ${A}` }, + { pid: 201, commandLine: `omp --resume ${A}` }, + ]; + // The first row is a cached scan entry for a process that already exited. + assert.deepEqual([...sessionIdsNamedByProcesses(processes, [{ id: A }], { isAlive: (pid) => pid === 201 })], [A]); + assert.deepEqual([...sessionIdsNamedByProcesses(processes, [{ id: A }], { isAlive: () => false })], []); +}); diff --git a/lib/hosts/omp-processes.ts b/lib/hosts/omp-processes.ts new file mode 100644 index 000000000..7e3743816 --- /dev/null +++ b/lib/hosts/omp-processes.ts @@ -0,0 +1,724 @@ +import { execFile } from "child_process"; +import { existsSync } from "fs"; +import { comparableProjectPath } from "../comparable-path"; +import { getWindowsExecutionEnv, resolvePowerShellBin } from "../windows-service"; + +/** + * Which live omp processes exist on this machine, and which session each one was opened on. + * + * This runs where the children run: inside `ompweb host`. omp ≥ 18.5 keeps a + * process-owned OS lease per session (a named mutex on Windows, an abstract + * socket on Linux) — deliberately not a file, so omp-web cannot read it. The + * command line is the portable, version-independent evidence instead: both + * omp-web (`buildSessionSpawnArgs`) and the terminal (`omp --resume `) + * name the session they were started on, and a live process with that argument + * holds the lease. + * + * Scanning spawns a process (PowerShell cold start on Windows is expensive), so + * results are cached for `FOREIGN_SCAN_TTL_MS`, concurrent callers share one + * in-flight scan, and a failure is reported as "unknown" (`ok: false`) rather + * than "no processes". `OMP_WEB_FOREIGN_SCAN=0` turns the scan off + * (`enabled: false`). Both mean a caller cannot claim that nobody runs a + * session. + * + * Only processes of this daemon's own OS user are trusted on POSIX. A command + * line is unauthenticated evidence — any local process could print + * `--resume ` — so another user's process would be a free "this session + * runs elsewhere" for as long as it lives. `ps` reports the uid and every other + * user's row is dropped. Windows cannot read another user's process owner + * without PROCESS_QUERY_INFORMATION, which an unelevated daemon does not have, + * and `process.getuid` is unavailable there: the scan keeps every row + * (`sameUserProcesses(rows, null)`) and narrows by process identity instead — + * `omp.exe`/`omp`, or a command line naming an omp entry (`isOmpProcess`), which + * also covers a `.cmd`/node shim launcher. That is the documented + * process-identity limit — on Windows a same-machine process named `omp` that + * names a session counts as a possible owner whatever account started it. + * + * A resume argument is only evidence on an omp row: `-r` is also `grep -r` and + * `rm -r`, and a POSIX scan lists every process of the user. The flags are the + * ones omp documents (`--resume`, `--restore`, `-r`), including a unique id + * prefix, which is how omp's `--resume` takes an id. + * + * The daemon's own children are excluded by pid, never by uid: `ChannelTable` + * knows their transport pids, and a Windows `cmd.exe /c omp.cmd` wrapper puts + * the real `omp` one hop below that pid (see `sessionIdsNamedByProcesses`). + */ + +export interface OmpProcessInfo { + pid: number; + /** The process that started it, where the OS reports one. */ + ppid?: number; + commandLine: string; + /** The executable name where the OS reports one (Windows CIM `Name`); undefined from `ps`, which reports only the + * command line. */ + name?: string; + /** Owning uid where the OS reports one (POSIX); undefined on Windows. */ + uid?: number; + /** Resume arguments, computed once per scan (see `listOmpProcesses`). */ + resumeTargets?: ResumeArgument[]; +} + +/** How long one process scan is reused. Cheap enough to hide in a request, + * short enough that a stale process list cannot block for long. */ +const FOREIGN_SCAN_TTL_MS = 10_000; +/** Hard bound on one scan; a slow PowerShell must not stall an inspection. */ +const FOREIGN_SCAN_TIMEOUT_MS = 1_500; + +/** One command line can be ~2 MB (Linux ARG_MAX). Nothing that identifies a + * session lives past this prefix, and parsing must stay bounded. */ +const MAX_COMMAND_LINE_CHARS = 8 * 1024; +/** Work caps per command line: a process has one `--resume`, and a session + * path with spaces has a handful of tokens — never thousands of prefixes. */ +const MAX_RESUME_OCCURRENCES = 8; +const MAX_BARE_JOIN_TOKENS = 8; +/** How far up a ppid chain an own-child check looks. The deepest real case is + * `cmd.exe` → `omp` on Windows; the rest is headroom for a launcher script. */ +const MAX_ANCESTOR_DEPTH = 8; +/** The shortest session-id prefix a `--resume` value may be: omp accepts a + * unique prefix, and four characters keep `rm -r 1111` from matching a whole + * batch of unrelated ids. */ +const MIN_PREFIX_CHARS = 4; +/** How many argv tokens an entry-point search may walk. Real shapes are + * `env VAR=x nice -n 5 cmd.exe /c omp.cmd` — a handful; a hostile line of + * thousands of flags must not turn this into a long parse. */ +const MAX_LAUNCHER_DEPTH = 8; + +export type ProcessScanRunner = (file: string, args: string[]) => Promise; + +export interface OmpProcessScanOptions { + /** Injectable process boundary (tests, hosts without PowerShell). */ + run?: ProcessScanRunner; + platform?: NodeJS.Platform; + now?: () => number; + /** + * Effective uid of this daemon process; a POSIX process of another user is + * never trusted as a session owner. Defaults to `process.getuid()`, and + * `null` (Windows, or an OS without uids) keeps every scanned process. + */ + uid?: number | null; + /** + * The absolute `ps` a POSIX scan runs. Defaults to the first of + * `/bin/ps`/`/usr/bin/ps` that exists; `null` forces the "no absolute ps" + * failure, so a test can exercise the POSIX parse on Windows. + */ + psBin?: string | null; +} + +export interface OmpProcessScan { + processes: OmpProcessInfo[]; + /** False when the scan failed or timed out: "unknown", not "none". */ + ok: boolean; + /** False when `OMP_WEB_FOREIGN_SCAN=0` switched the scan off: also "unknown". */ + enabled: boolean; +} + +function foreignScanEnabled(env: NodeJS.ProcessEnv = process.env): boolean { + return env.OMP_WEB_FOREIGN_SCAN !== "0"; +} + +const defaultRunner: ProcessScanRunner = (file, args) => { + const { promise, resolve, reject } = Promise.withResolvers(); + execFile( + file, + args, + { timeout: FOREIGN_SCAN_TIMEOUT_MS, windowsHide: true, maxBuffer: 4 * 1024 * 1024, env: getWindowsExecutionEnv() }, + (error, stdout) => { + // A timeout leaves partial stdout unusable: report failure. + if (error) reject(error); + else resolve(stdout); + }, + ); + return promise; +}; + +/** The scan child must run the system `ps` from a fixed absolute path, never a + * project-local binary: a repository could ship one named `ps`, and it would + * run with our env. No known absolute path means no scan at all — reported as + * `ok: false` ("unknown") instead of falling back to PATH. */ +function resolvePosixPsBin(): string | null { + for (const candidate of ["/bin/ps", "/usr/bin/ps"]) { + if (existsSync(candidate)) return candidate; + } + return null; +} + +function capCommandLine(commandLine: string): string { + return commandLine.length > MAX_COMMAND_LINE_CHARS ? commandLine.slice(0, MAX_COMMAND_LINE_CHARS) : commandLine; +} + +/** `Get-CimInstance ... | ConvertTo-Json` — one JSON object or an array. */ +export function parseWindowsProcessList(raw: string): OmpProcessInfo[] { + const text = raw.trim(); + if (!text) return []; + let parsed: unknown; + try { + parsed = JSON.parse(text); + } catch { + return []; + } + const rows = Array.isArray(parsed) ? parsed : [parsed]; + const processes: OmpProcessInfo[] = []; + for (const row of rows) { + if (!row || typeof row !== "object") continue; + const record = row as { ProcessId?: unknown; ParentProcessId?: unknown; CommandLine?: unknown; Name?: unknown }; + const pid = typeof record.ProcessId === "number" ? record.ProcessId : Number(record.ProcessId); + const commandLine = typeof record.CommandLine === "string" ? capCommandLine(record.CommandLine) : ""; + if (!Number.isInteger(pid) || pid <= 0) continue; + const parent = typeof record.ParentProcessId === "number" ? record.ParentProcessId : Number(record.ParentProcessId); + const name = typeof record.Name === "string" && record.Name !== "" ? record.Name : undefined; + processes.push({ + pid, + ...(Number.isInteger(parent) && parent > 0 ? { ppid: parent } : {}), + commandLine, + ...(name === undefined ? {} : { name }), + }); + } + return processes; +} + +/** `ps -eo pid=,ppid=,uid=,args=` — one `pid ppid uid command line` per line. */ +export function parsePosixProcessList(raw: string): OmpProcessInfo[] { + const processes: OmpProcessInfo[] = []; + for (const line of raw.split(/\r?\n/)) { + const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(.*)$/.exec(line); + if (!match) continue; + const pid = Number(match[1]); + const ppid = Number(match[2]); + const uid = Number(match[3]); + if (!Number.isInteger(pid) || pid <= 0 || !Number.isSafeInteger(uid)) continue; + processes.push({ pid, ppid, uid, commandLine: capCommandLine(match[4].trim()) }); + } + return processes; +} + +/** Whether a pid still exists. `EPERM` means "exists, not ours" and counts as alive. */ +export type ProcessLivenessProbe = (pid: number) => boolean; + +const defaultLivenessProbe: ProcessLivenessProbe = (pid) => { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return (error as NodeJS.ErrnoException)?.code !== "ESRCH"; + } +}; + +interface OmpProcessScanState { + cache: { at: number; platform: NodeJS.Platform; runner: ProcessScanRunner; uid: number | null; processes: OmpProcessInfo[] } | null; + /** One scan at a time, process-wide. */ + inFlight: Promise | null; + injectedRunner: ProcessScanRunner | null; + livenessProbe: ProcessLivenessProbe | null; +} + +declare global { + var __ompProcessScanState: OmpProcessScanState | undefined; +} + +/** + * Kept on `globalThis` so `bun --hot` re-evaluation and every module that + * imports this file share one cache, one single-flight promise and one test + * seam — a module-local copy would let a burst of requests spawn one PowerShell + * each, which is exactly what the single-flight promise exists to prevent. + */ +function scanState(): OmpProcessScanState { + const state = globalThis.__ompProcessScanState ??= { cache: null, inFlight: null, injectedRunner: null, livenessProbe: null }; + // A state object created by an older module version lacks fields added later. + state.cache ??= null; + state.inFlight ??= null; + state.injectedRunner ??= null; + state.livenessProbe ??= null; + return state; +} + +/** Drop the cached scan (tests: the next call must observe the OS again). */ +export function resetOmpProcessCache(): void { + scanState().cache = null; +} + +export function setOmpProcessScanRunner(runner: ProcessScanRunner | null): void { + const state = scanState(); + state.injectedRunner = runner; + state.cache = null; + // An injected scan names the test's pids, which the real OS probe would + // reject as dead: a fake process table implies fake liveness. A caller that + // wants a specific answer passes `isProcessAlive`. + state.livenessProbe = runner ? () => true : null; +} + +/** + * Whether this pid is still running right now. A scan is cached for + * {@link FOREIGN_SCAN_TTL_MS}, so a process that exited inside that window is + * still listed: an owner hit must be confirmed against the OS before it may + * count, or a terminal `omp` closed seconds ago reads as a live writer. + */ +export function isProcessAlive(pid: number): boolean { + if (!Number.isInteger(pid) || pid <= 0) return false; + return (scanState().livenessProbe ?? defaultLivenessProbe)(pid); +} + +/** + * Drop processes of other OS users: `ps -e` lists everyone, and a command line + * of another user is no evidence that they hold this session (any local + * process could print `--resume ` and block sending). A `null` uid means + * the OS does not report one (Windows) and keeps every process. + */ +export function sameUserProcesses(processes: OmpProcessInfo[], uid: number | null): OmpProcessInfo[] { + return uid === null ? processes : processes.filter((process) => process.uid === uid); +} + +/** The image names that *are* omp, compared on the basename. */ +const OMP_IMAGE_NAMES: Record = { + omp: true, + "omp.exe": true, + "omp.cmd": true, + "omp.bat": true, + "omp.js": true, + "omp.cjs": true, + "omp.mjs": true, +}; + +/** Launchers that run another program as their first non-flag argument: + * `cmd.exe /c omp.cmd …`, `sh -c "omp --resume x"`, `node …\cli.js …`. */ +const LAUNCHER_NAMES: Record = { + cmd: true, + "cmd.exe": true, + sh: true, + bash: true, + dash: true, + zsh: true, + node: true, + "node.exe": true, + bun: true, + "bun.exe": true, +}; +/** Prefix commands that run another program as their first non-flag argument + * (`env FOO=1 omp …`, `nice -n 5 omp …`). */ +const WRAPPER_NAMES: Record = { + env: true, + nice: true, + nohup: true, + command: true, + exec: true, + time: true, +}; + +/** Launchers that take a whole command string as one argument (`-c`/`/c`). */ +const COMMAND_STRING_LAUNCHERS: Record = { + cmd: true, + "cmd.exe": true, + sh: true, + bash: true, + dash: true, + zsh: true, +}; + +/** Split a command line into argv, honouring both quote styles. `ps` loses the + * original quoting, so this is the best available reconstruction: a quoted + * run stays one token, everything else splits on whitespace. */ +function splitCommandLine(commandLine: string): string[] { + const tokens: string[] = []; + let current = ""; + let quote: '"' | "'" | null = null; + for (const char of capCommandLine(commandLine)) { + if (quote) { + if (char === quote) quote = null; + else current += char; + continue; + } + if (char === '"' || char === "'") { + quote = char; + continue; + } + if (/\s/.test(char)) { + if (current) tokens.push(current); + current = ""; + continue; + } + current += char; + } + if (current) tokens.push(current); + return tokens; +} + +/** Whether `token` names an omp entry point: the image itself (`omp`, + * `omp.exe`, `omp.cmd`, `omp.bat`, `omp.js`) or a shim's JS entry below + * `@oh-my-pi`. The comparison is on the basename, so `omp-web`, + * `fake-omp.cmd` and `…/omp/foo` do not match. */ +function isOmpEntryToken(token: string): boolean { + const base = basenameAny(token).toLowerCase(); + if (OMP_IMAGE_NAMES[base]) return true; + return /[\\/]@?oh-my-pi[\\/]/i.test(token); +} + +/** + * Whether the row can be an omp process at all. A resume argument is only + * evidence when the process carrying it is omp: `-r` is also `grep -r`, `rm -r` + * and `tar -r`, and a POSIX scan lists every process of the user. + * + * The entry point must be *anchored*, never "somewhere on the line". It is + * `argv[0]`, or the first non-flag argument after a known launcher + * (`cmd[.exe] /c …`, `sh|bash -c …`, `node|bun …`), or after a prefix command + * (`env FOO=1 …`, `nice -n 5 …`). A token that merely appears later — a grep + * pattern, an `--exclude-dir=omp`, a path below `…/omp/` — is an argument of + * that program, not an omp entry, so `grep -r lib/omp` cannot claim a + * session. + * + * Windows additionally recognises the shim shapes (`cmd.exe /c omp.cmd …`, + * `node …\@oh-my-pi\…\cli.js …`), which the old name filter missed. + */ +export function isOmpProcess(process: OmpProcessInfo): boolean { + const name = process.name?.toLowerCase(); + if (name === "omp" || name === "omp.exe") return true; + return commandLineRunsOmp(process.commandLine); +} + +/** Launcher/wrapper flags that consume the *next* token as their value + * (`nice -n 5`, `env -u NAME`, `time -f FORMAT`), so the value is not + * mistaken for the program. Attached forms (`-n5`, `--adjustment=5`) are + * single tokens and need no entry. */ +const FLAGS_WITH_VALUE: Record = { + "-n": true, + "--adjustment": true, + "-u": true, + "--unset": true, + "-C": true, + "--chdir": true, + "-S": true, + "-f": true, + "--format": true, + "-o": true, + "--output": true, +}; + +/** Skip the tokens a launcher/wrapper puts before the program it runs: its + * flags (`cmd.exe /d /s /c`, `nice -n`), the values of value-taking flags, and + * `env`'s `VAR=value` assignments. A POSIX absolute path is not a flag, so the + * cmd-style test is a bare `/x` or `/xy` only. */ +function skipLaunchPrefix(argv: string[], start: number): number { + let index = start; + while (index < argv.length) { + const token = argv[index]!; + if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)) index += 1; + else if (FLAGS_WITH_VALUE[token]) index += 2; + else if (token.startsWith("-") || /^\/[A-Za-z]{1,2}$/.test(token)) index += 1; + else break; + } + return index; +} + +/** A path root: an absolute POSIX path, a drive or UNC path, or `./`/`../`. */ +const PATH_START_RE = /^(?:[A-Za-z]:[\\/]|\\\\|\/|\.{1,2}[\\/])/; +/** A token that can continue a path across a space (`Program Files`), as + * opposed to a flag (`--resume`), a new path (`/home/me/omp`) or `VAR=value`. */ +const PATH_CONTINUATION_RE = /^[^-\s\\/][^=]*$/; + +/** + * Whether a launcher's command string *names an omp entry as its program*. + * + * The string arrives unquoted from {@link splitCommandLine}, so a command with + * arguments is one token (`sh -c "omp --resume "` → `omp --resume `). + * Only a string that starts with a path can carry a program name with spaces + * in it (`"C:\Program Files\omp\omp.cmd" --resume `): there the program is + * the path prefix, and its name must follow a separator — a bare word after a + * space (`/bin/echo omp`) is an argument of that program, not the program. + * The prefix stops at the first token that cannot continue a path, so a later + * argument (`/bin/cat /home/me/omp`) is never read as the program. A string + * that starts with a bare word is a command line whose program is its first + * token — walking it is {@link commandLineRunsOmp}'s job, and applying basename + * matching to the whole string is what made `sh -c "grep -r lib/omp"` a + * foreign owner. + */ +function isOmpEntryCommandString(commandString: string): boolean { + if (!/\s/.test(commandString)) return isOmpEntryToken(commandString); + if (!PATH_START_RE.test(commandString)) return false; + const parts = commandString.split(/\s+/); + let prefix = parts[0]!; + for (let index = 1; index < parts.length; index += 1) { + const part = parts[index]!; + if (!PATH_CONTINUATION_RE.test(part)) break; + prefix = `${prefix} ${part}`; + } + return isOmpEntryToken(prefix); +} + +/** Walk `argv` from the front: an omp entry at the head, or as the program a + * known launcher/wrapper runs. Bounded by {@link MAX_LAUNCHER_DEPTH} per + * command string, and by it again across a nested `sh -c "…"`. */ +function commandLineRunsOmp(commandLine: string, depth = 0): boolean { + if (depth >= MAX_LAUNCHER_DEPTH) return false; + const argv = splitCommandLine(commandLine); + let index = 0; + for (let step = 0; step < MAX_LAUNCHER_DEPTH; step += 1) { + index = skipLaunchPrefix(argv, index); + const token = argv[index]; + if (token === undefined) return false; + index += 1; + if (isOmpEntryToken(token)) return true; + const base = basenameAny(token).toLowerCase(); + if (!LAUNCHER_NAMES[base] && !WRAPPER_NAMES[base]) return false; + // `sh -c ""` / `cmd.exe /c `: the program + // is inside the next token, which splitCommandLine already unquoted into + // one token — so recurse on it instead of reading it as a program name. + if (COMMAND_STRING_LAUNCHERS[base]) { + index = skipLaunchPrefix(argv, index); + const commandString = argv[index]; + if (commandString === undefined) return false; + return isOmpEntryCommandString(commandString) || commandLineRunsOmp(commandString, depth + 1); + } + } + return false; +} + +async function runScan(platform: NodeJS.Platform, run: ProcessScanRunner, uid: number | null, psBin: string | null | undefined): Promise { + let processes: OmpProcessInfo[]; + if (platform === "win32") { + // Ownership could be narrowed to this user with a `GetOwner` call per + // process, but that needs PROCESS_QUERY_INFORMATION, which an unelevated + // daemon lacks for another user's process — the query would cost a CIM + // round trip per process and still answer "unknown". The name filter below + // stays the cheap narrowing. `node.exe`/`cmd.exe` are listed because a + // `.cmd` shim (which `wrapWindowsScript` supports) runs omp as a node + // process below cmd.exe; `isOmpProcess` keeps only rows whose command line + // names an omp entry, so the wider query costs one JSON parse, not trust. + const command = + "Get-CimInstance Win32_Process -Filter \"Name='omp.exe' OR Name='omp' OR Name='node.exe' OR Name='cmd.exe'\" -ErrorAction SilentlyContinue | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Compress"; + processes = parseWindowsProcessList(await run(resolvePowerShellBin(), ["-NoProfile", "-NonInteractive", "-Command", command])); + } else { + // No absolute `ps`: report "unknown" (the caller keeps a known owner) + // rather than resolving some binary from PATH. + const resolved = psBin === undefined ? resolvePosixPsBin() : psBin; + if (!resolved) throw new Error("no absolute ps binary"); + // `-ww`: procps caps the width at OUTBUF_SIZE (131 072 columns) instead of + // the screen width. `args` is the last column, so a narrow terminal + // (`COLUMNS` exported in a tmux pane or CI wrapper) clips the `--resume` + // value and the row reads as naming no session — the exact false `none` + // this scan exists to prevent. An explicit option wins over the + // environment (procps `choose_dimensions`), so no env plumbing. The cap is + // far above MAX_COMMAND_LINE_CHARS, so no line this parser keeps is + // clipped. + processes = sameUserProcesses(parsePosixProcessList(await run(resolved, ["-ww", "-eo", "pid=,ppid=,uid=,args="])), uid); + } + // Parse the resume arguments once per process: one snapshot answers a whole + // batch of session ids. + for (const process of processes) process.resumeTargets = resumeArguments(process.commandLine); + return processes; +} + +export async function listOmpProcesses(options: OmpProcessScanOptions = {}): Promise { + const platform = options.platform ?? process.platform; + const uid = options.uid === undefined + ? (typeof process.getuid === "function" ? process.getuid() : null) + : options.uid; + const now = options.now?.() ?? Date.now(); + if (!foreignScanEnabled()) return { processes: [], ok: true, enabled: false }; + const state = scanState(); + const run = options.run ?? state.injectedRunner ?? defaultRunner; + // The runner is part of the cache key: a scan produced by another boundary + // (a swapped test seam) must never answer for this one. The uid is too: the + // filter runs inside the scan. + if (state.cache && state.cache.runner === run && state.cache.platform === platform && state.cache.uid === uid && now - state.cache.at < FOREIGN_SCAN_TTL_MS) { + return { processes: state.cache.processes, ok: true, enabled: true }; + } + const scan = async (): Promise => { + try { + const processes = await runScan(platform, run, uid, options.psBin); + state.cache = { at: now, platform, runner: run, uid, processes }; + return { processes, ok: true, enabled: true }; + } catch { + // No process list is a soft "unknown", never a reason to claim absence — + // and the failure is not cached, so the next caller retries instead of + // inheriting an answer that may clear a live owner. + return { processes: [], ok: false, enabled: true }; + } + }; + // A per-call runner is a one-off boundary; it never joins the shared scan. + if (options.run) return scan(); + if (state.inFlight) return state.inFlight; + const started = scan().finally(() => { + state.inFlight = null; + }); + state.inFlight = started; + return started; +} + +function basenameAny(value: string): string { + const normalized = value.replace(/\\/g, "/"); + const index = normalized.lastIndexOf("/"); + return index >= 0 ? normalized.slice(index + 1) : value; +} + +/** + * The flags omp documents for opening an existing session (`omp --help`): + * `-r, --resume=` and `--restore=`, which resumes "as --resume + * does, then goes on with what its last process left unfinished". `--restore` + * is what a user reaches for after a crash — exactly when a second writer + * appears — so it must count as a resume argument too. + */ +const RESUME_MARKERS = ["--resume", "--restore", "-r"] as const; + +/** One resume argument: the value it carried. The flag itself is not kept — + * every caller asks only which session a row names, and the flag never + * changes that answer. */ +export interface ResumeArgument { + value: string; +} + +/** + * Values a resume flag may carry: the exact token, or — on POSIX, where `ps` + * loses the quoting — the space-joined tokens that follow it. Work stays + * bounded (`MAX_RESUME_OCCURRENCES` occurrences, `MAX_BARE_JOIN_TOKENS` joins + * each), so a hostile command line cannot turn this into a quadratic parse. + */ +export function resumeArguments(commandLine: string): ResumeArgument[] { + const text = capCommandLine(commandLine); + const values: ResumeArgument[] = []; + let occurrences = 0; + for (const marker of RESUME_MARKERS) { + let searchFrom = 0; + while (occurrences < MAX_RESUME_OCCURRENCES) { + const index = text.indexOf(marker, searchFrom); + if (index < 0) break; + searchFrom = index + marker.length; + // The marker must start an argument, not sit inside another token: + // `-r` occurs inside `--resume`/`--restore`, and `--resumeX` is a + // different flag. + if (index > 0 && !/\s/.test(text[index - 1])) continue; + let cursor = index + marker.length; + if (text[cursor] === "=") cursor += 1; + else if (cursor < text.length && !/\s/.test(text[cursor])) { + // `-r` is omp's attached short-flag form; a long flag needs `=` + // or whitespace, so `--resumeX` is a different flag. + if (marker !== "-r") continue; + } else while (cursor < text.length && /\s/.test(text[cursor])) cursor += 1; + if (cursor >= text.length) continue; + occurrences += 1; + const quote = text[cursor]; + if (quote === '"' || quote === "'") { + const end = text.indexOf(quote, cursor + 1); + values.push({ value: end > cursor + 1 ? text.slice(cursor + 1, end) : text.slice(cursor + 1) }); + continue; + } + // Unquoted: the token itself plus the joins with the tokens after it. A + // path with spaces arrives quoted from Windows and unquoted from `ps`; + // joining stops at the next flag. + const tokens: string[] = []; + while (cursor < text.length && tokens.length < MAX_BARE_JOIN_TOKENS) { + let end = cursor; + while (end < text.length && !/\s/.test(text[end])) end += 1; + // A token inside a quoted command string (`sh -c "omp --resume "`) + // carries that string's closing quote; a session id or path never ends + // in one, so it is not part of the value. + const token = text.slice(cursor, end).replace(/["']+$/, ""); + if (token.startsWith("-")) break; + tokens.push(token); + values.push({ value: tokens.join(" ") }); + while (end < text.length && /\s/.test(text[end])) end += 1; + cursor = end; + } + } + } + return values.filter((argument) => argument.value.length > 0); +} + +/** The session id a `--resume` value may carry: the value itself, or the + * trailing `` of `.jsonl` / `_.jsonl`. */ +function sessionIdFromResumeValue(value: string): string { + const base = basenameAny(value); + if (!base.endsWith(".jsonl")) return value; + const stem = base.slice(0, -".jsonl".length); + const underscore = stem.lastIndexOf("_"); + return underscore >= 0 ? stem.slice(underscore + 1) : stem; +} + +/** + * omp's `--resume` takes "a session (by ID prefix, path, or picker if + * omitted)", so `omp --resume 11111111` names a session whose id starts with + * that prefix. Only a *unique* prefix is evidence: an ambiguous one leaves omp + * to pick, so claiming either session would be a guess. The value must look + * like a bare id prefix (hex and dashes, no path separator) and be at least + * {@link MIN_PREFIX_CHARS} long, or `-r /tmp/1111` would match by accident. + */ +function uniquePrefixHit(ids: ReadonlySet, value: string): string | null { + if (value.length < MIN_PREFIX_CHARS || /[\\/]/.test(value) || !/^[0-9a-f][0-9a-f-]*$/i.test(value)) return null; + let hit: string | null = null; + for (const id of ids) { + if (!id.startsWith(value)) continue; + if (hit !== null) return null; // ambiguous: omp would have to pick + hit = id; + } + return hit; +} + +/** True when `process` is this daemon's own child: its pid is known, or its + * parent chain reaches a known pid within {@link MAX_ANCESTOR_DEPTH}. The one + * hop that matters in practice is the Windows `cmd.exe /c omp.cmd` wrapper, + * whose pid is the transport id while the real `omp` sits below it. */ +function isOwnChild(process: OmpProcessInfo, byPid: Map, exclude: Set): boolean { + if (exclude.has(process.pid)) return true; + let parent = process.ppid; + for (let depth = 0; depth < MAX_ANCESTOR_DEPTH && parent !== undefined && parent > 0; depth += 1) { + if (exclude.has(parent)) return true; + parent = byPid.get(parent)?.ppid; + } + return false; +} + +export interface NamedByProcessesOptions { + /** Pids of this daemon's own children (a transport's id is its child's pid). */ + excludePids?: readonly number[]; + /** Confirm a hit against the OS: a cached scan still lists a process that + * exited inside its TTL. Omitted = trust the scan. */ + isAlive?: ProcessLivenessProbe; +} + +/** + * Which of `candidates` a scanned process names on its command line, in one + * pass over the snapshot (one bounded scan answers a whole batch of ids). + * + * The daemon's own children are dropped first: they name the session file they + * were started on, and they are ours, not a foreign writer. A hit is confirmed + * with `isAlive` when the caller acts on it; a dead row is skipped and the + * search continues, because a second, live `--resume` on the same file is the + * real owner. + */ +export function sessionIdsNamedByProcesses( + processes: OmpProcessInfo[], + candidates: Iterable<{ id: string; sessionFile?: string }>, + options: NamedByProcessesOptions = {}, +): Set { + const byId = new Map(); + const byPath = new Map(); + const byBase = new Map(); + const ids = new Set(); + for (const candidate of candidates) { + byId.set(candidate.id, candidate.id); + ids.add(candidate.id); + if (!candidate.sessionFile) continue; + byPath.set(comparableProjectPath(candidate.sessionFile), candidate.id); + byBase.set(basenameAny(candidate.sessionFile), candidate.id); + } + const byPid = new Map(); + for (const process of processes) byPid.set(process.pid, process); + const exclude = new Set(options.excludePids ?? []); + const named = new Set(); + for (const process of processes) { + // `-r` is also `grep -r`, `rm -r` and `tar -r`, and a POSIX scan lists + // every process of the user: only an omp row may own a session. + if (!isOmpProcess(process)) continue; + const values = process.resumeTargets ?? resumeArguments(process.commandLine); + if (values.length === 0) continue; + if (exclude.size > 0 && isOwnChild(process, byPid, exclude)) continue; + let live: boolean | null = null; + for (const { value } of values) { + const pathHit = byPath.get(comparableProjectPath(value)); + const base = basenameAny(value); + const hit = pathHit ?? byBase.get(base) ?? byId.get(sessionIdFromResumeValue(value)) ?? uniquePrefixHit(ids, value); + if (!hit) continue; + // Probe only on a hit (a syscall per candidate), once per process. + live ??= options.isAlive ? options.isAlive(process.pid) : true; + if (live) named.add(hit); + } + } + return named; +} diff --git a/lib/hosts/session-ops.ts b/lib/hosts/session-ops.ts index e10a942e6..8786df092 100644 --- a/lib/hosts/session-ops.ts +++ b/lib/hosts/session-ops.ts @@ -58,8 +58,9 @@ import type { SessionHistoryCursor } from "../session-sync"; import { extractSubagentHistory, readCompletionArtifact, readSubagentTranscriptPage, resolveSubagentArtifact, subagentTranscriptPath } from "../subagent-history"; import { SUBAGENT_ID_RE } from "../subagent-types"; import { isRecord } from "../type-guards"; -import type { ArchivedSessionInfo, ManagedProject, ProjectLaunchConfig, SessionContext, SessionInfo, SessionTitleSource } from "../types"; +import type { ArchivedSessionInfo, ManagedProject, ProjectLaunchConfig, SessionContext, SessionInfo, SessionOwnership, SessionTitleSource } from "../types"; import { resolveProject } from "../worktree"; +import { detectSessionOwnership } from "./session-ownership"; export type OpResult = { ok: true; value: T } | { ok: false; status: number; code: string; error: string }; @@ -129,6 +130,10 @@ export interface SessionOps { updateProject(updates: ProjectUpdate[]): Promise>; hideProject(path: string): Promise>; validateCwd(path: string): Promise>; + /** Who holds each session's writer lease on this host (lib/hosts/session-ownership.ts): one entry per id, in request + * order, at most `LINK_LIMITS.ownershipIds`. Read-only; never spawns, kills or writes. An inspection that fails, is + * switched off or is unavailable answers `owner: "unknown"`, never `"none"`. */ + sessionOwnership(ids: string[]): Promise>; } const execFileAsync = promisify(execFile); @@ -782,4 +787,9 @@ export const sessionOps: SessionOps = { const project = await resolveProject(normalizedCwd); return ok({ cwd: normalizedCwd, projectRoot: project.projectRoot, projectKey: projectIdentityKey(project.projectRoot) }); }, + + // The plain file-side answer, for a caller inside the daemon process that has no ChannelTable at hand: the scan + // excludes this process's own descendants by ppid chain, so a child it spawned never reads as foreign. The daemon's + // op dispatch adds the exact transport pids on top (daemon.ts). + sessionOwnership: (ids) => detectSessionOwnership(ids, { excludePids: () => [process.pid] }), }; diff --git a/lib/hosts/session-ownership.test.mjs b/lib/hosts/session-ownership.test.mjs new file mode 100644 index 000000000..4c200e2d0 --- /dev/null +++ b/lib/hosts/session-ownership.test.mjs @@ -0,0 +1,299 @@ +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; + +const { detectSessionOwnership, readSessionTailState, OWNERSHIP_ACTIVE_WINDOW_MS } = await import("./session-ownership.ts"); +const { listOmpProcesses, parsePosixProcessList, resetOmpProcessCache, sameUserProcesses } = await import("./omp-processes.ts"); +const { invalidateSessionListCache } = await import("../session-reader.ts"); + +// The uid a fixture must use: the one this process runs as, never a literal. On Windows `process.getuid` does not exist, +// and the scan keeps every row (the documented process-identity limit). +const RUNNING_UID = typeof process.getuid === "function" ? process.getuid() : null; + +const scratch = mkdtempSync(join(tmpdir(), "omp-web-ownership-")); +after(() => rmSync(scratch, { recursive: true, force: true })); + +let fixture = 0; +/** A throwaway agent dir with one session file; `records` are the JSONL lines after the header. */ +function withSession(run, { records = [], ageMs = 0 } = {}) { + fixture += 1; + const id = `00000000-0000-4000-8000-${String(fixture).padStart(12, "0")}`; + const agentDir = join(scratch, `agent-${fixture}`); + const projectDir = join(agentDir, "sessions", "-project"); + mkdirSync(projectDir, { recursive: true }); + const file = join(projectDir, "2026-01-01_fixture.jsonl"); + const lines = [ + { type: "session", version: 3, id, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" }, + ...records, + ]; + writeFileSync(file, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`); + if (ageMs > 0) { + const at = new Date(Date.now() - ageMs); + utimesSync(file, at, at); + } + const previous = process.env.PI_CODING_AGENT_DIR; + process.env.PI_CODING_AGENT_DIR = agentDir; + invalidateSessionListCache(); + return Promise.resolve(run({ id, file })).finally(() => { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + invalidateSessionListCache(); + }); +} + +/** A process row as `ps` reports it, owned by the running uid unless one is given. */ +function row(pid, { ppid = 1, commandLine = "", uid = RUNNING_UID } = {}) { + return uid === null ? { pid, ppid, commandLine } : { pid, ppid, commandLine, uid }; +} + +/** A scan answer; `processes` are already parsed rows (resume targets are computed by the caller's scan). */ +function scanOf(processes, { ok = true, enabled = true } = {}) { + return async () => ({ processes, ok, enabled }); +} + +/** A fixture's pids do not exist on this machine: the ownership check confirms a scan hit against the OS, so a test + * that wants a live writer says so explicitly. */ +const alive = () => true; + +const midTurn = [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "do it" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", provider: "t", model: "m", content: [{ type: "toolCall", id: "c1", name: "read", arguments: {} }] } }, +]; +const settled = [ + { type: "message", id: "u1", parentId: null, message: { role: "user", content: "do it" } }, + { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", provider: "t", model: "m", content: [{ type: "text", text: "done" }], stopReason: "end" } }, +]; +const exitRecord = { type: "custom", customType: "session_exit", id: "x1", parentId: "a1" }; + +test("a live foreign omp owns the file while idle; the tail only says whether it is mid-turn", () => withSession(async ({ id, file }) => { + const processes = [row(200, { commandLine: `omp --resume ${file}` })]; + const running = await detectSessionOwnership([id], { scan: scanOf(processes), isAlive: alive }); + assert.equal(running.ok, true); + assert.deepEqual(running.value, [{ id, owner: "foreign", running: true, source: "process", lastActivityAt: running.value[0].lastActivityAt }]); + + // The same live process, but the transcript settled: ownership stays, activity does not. + const idle = await detectSessionOwnership([id], { scan: scanOf(processes), isAlive: alive, now: () => Date.now() + 1 }); + assert.equal(idle.value[0].owner, "foreign"); + // A trailing session_exit closes the turn even while the process lives. + writeFileSync(file, `${JSON.stringify({ type: "session", version: 3, id, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" })}\n${[...settled, exitRecord].map((line) => JSON.stringify(line)).join("\n")}\n`); + const exited = await detectSessionOwnership([id], { scan: scanOf(processes), isAlive: alive }); + assert.equal(exited.value[0].owner, "foreign", "an idle writer still owns the file"); + assert.equal(exited.value[0].running, false); +}, { records: midTurn })); + +test("a stale or closed transcript is not an owner and not activity", () => withSession(async ({ id, file }) => { + const stale = await detectSessionOwnership([id], { scan: scanOf([]), now: () => Date.now() + OWNERSHIP_ACTIVE_WINDOW_MS + 1 }); + assert.deepEqual(stale.value, [{ id, owner: "none", running: false, lastActivityAt: stale.value[0].lastActivityAt }], "no source: the tail contributed nothing"); + + // Fresh but closed by omp: no process, trailing exit -> nothing runs it. + writeFileSync(file, `${JSON.stringify({ type: "session", version: 3, id, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" })}\n${[...settled, exitRecord].map((line) => JSON.stringify(line)).join("\n")}\n`); + const closed = await detectSessionOwnership([id], { scan: scanOf([]) }); + assert.equal(closed.value[0].owner, "none"); + assert.equal(closed.value[0].running, false); +})); + +test("a fresh transcript without a process is an activity hint, never an owner", () => withSession(async ({ id }) => { + const result = await detectSessionOwnership([id], { scan: scanOf([]) }); + assert.equal(result.value[0].owner, "none", "activity is not ownership: a send must not be blocked by it"); + assert.equal(result.value[0].running, true); + assert.equal(result.value[0].source, "transcript"); +}, { records: midTurn })); + +test("a file that exists but cannot be read leaves activity unknown, not false", () => withSession(async ({ id }) => { + const result = await detectSessionOwnership([id], { scan: scanOf([]), tail: () => null }); + assert.equal(result.value[0].owner, "none", "a successful scan still answers ownership"); + assert.equal("running" in result.value[0], false, "an unreadable tail cannot make `running: false` a fact"); + assert.equal(result.value[0].source, undefined); + assert.equal(typeof result.value[0].lastActivityAt, "number", "the stat still says when it was written"); +}, { records: midTurn })); + +test("a failed or switched-off scan is unknown, never none, and claims no activity", () => withSession(async ({ id }) => { + for (const scan of [scanOf([], { ok: false }), scanOf([], { enabled: false })]) { + const result = await detectSessionOwnership([id], { scan }); + assert.equal(result.value[0].owner, "unknown"); + assert.equal("running" in result.value[0], false, "activity is unknown too, not false"); + assert.equal(result.value[0].source, undefined); + } +}, { records: midTurn })); + +test("the daemon's own children are ours: spawning, adopted, idle and running", () => withSession(async ({ id }) => { + let scans = 0; + const scan = async () => { scans += 1; throw new Error("a daemon-owned session must not need a process scan"); }; + for (const running of [true, false, undefined]) { + const result = await detectSessionOwnership([id], { channel: () => ({ owned: true, running }), scan }); + assert.equal(result.value[0].owner, "daemon"); + assert.equal(result.value[0].source, "process"); + if (running === undefined) assert.equal("running" in result.value[0], false, "a channel that cannot say leaves activity unknown"); + else assert.equal(result.value[0].running, running); + } + assert.equal(scans, 0); +}, { records: midTurn })); + +test("own children are excluded from the foreign scan by transport pid and by the Windows cmd.exe parent chain", () => withSession(async ({ id, file }) => { + // 100 is a child of this daemon (its transport id); 101 is the real omp below a cmd.exe wrapper, one hop further. + const own = [row(100, { ppid: 999, commandLine: `cmd.exe /c omp.cmd --resume ${file}` }), row(101, { ppid: 100, commandLine: `omp --resume ${file}` })]; + const ours = await detectSessionOwnership([id], { scan: scanOf(own), excludePids: () => [100], isAlive: alive }); + assert.equal(ours.value[0].owner, "none", "the daemon's own child never reads as a foreign writer"); + + // A process outside that tree that names the same file is the foreign writer. + const foreign = await detectSessionOwnership([id], { scan: scanOf([...own, row(200, { ppid: 1, commandLine: `omp --resume ${file}` })]), excludePids: () => [100], isAlive: alive }); + assert.equal(foreign.value[0].owner, "foreign"); +})); + +test("one bounded scan answers the whole batch, in request order", () => withSession(async ({ id, file }) => { + let scans = 0; + const other = "11111111-2222-4333-8444-555555555555"; + const result = await detectSessionOwnership([other, id, other], { + scan: async () => { scans += 1; return { processes: [row(200, { commandLine: `omp --resume ${file}` })], ok: true, enabled: true }; }, + isAlive: alive, + }); + assert.equal(scans, 1, "one ps/PowerShell call per host, not one per id"); + assert.deepEqual(result.value.map((entry) => [entry.id, entry.owner]), [[other, "none"], [id, "foreign"], [other, "none"]]); +})); + +test("the batch is bounded and validated at the host boundary", () => withSession(async ({ id }) => { + assert.equal((await detectSessionOwnership("nope", { scan: scanOf([]) })).status, 400); + assert.equal((await detectSessionOwnership(["", id], { scan: scanOf([]) })).status, 400); + // An empty batch is a caller bug, not an empty answer: the spec promises 400. + const empty = await detectSessionOwnership([], { scan: scanOf([]) }); + assert.equal(empty.status, 400); + const tooMany = Array.from({ length: 257 }, () => id); + const rejected = await detectSessionOwnership(tooMany, { scan: scanOf([]) }); + assert.equal(rejected.ok, false); + // One code for one condition, matching the dispatch's 400 `invalid_request`. + assert.equal(rejected.code, "invalid_request"); + const full = await detectSessionOwnership(Array.from({ length: 256 }, () => id), { scan: scanOf([]) }); + assert.equal(full.ok, true); + assert.equal(full.value.length, 256); +})); + +test("both platform scan shapes parse and filter: POSIX drops another uid, Windows keeps every row and narrows by name", async () => { + // The POSIX shape is exercised on every host (the daemon picks the parser by platform, so a Windows-only run would + // otherwise never reach `parsePosixProcessList`). The uid is this process's own, never a literal. + const uid = typeof process.getuid === "function" ? process.getuid() : 1000; + const other = uid + 1; + const posixRaw = [ + `${200} ${1} ${uid} omp --resume a`, + `${201} ${1} ${other} omp --resume b`, + `${202} ${1} ${uid} /usr/bin/grep -r a /tmp`, + ].join("\n"); + const parsed = parsePosixProcessList(posixRaw); + assert.deepEqual(parsed.map((process) => process.pid), [200, 201, 202], "every row parsed, including the other user's"); + assert.deepEqual(sameUserProcesses(parsed, uid).map((process) => process.pid), [200, 202], "the other user's row is dropped"); + // Through the real scan boundary: the injected runner's rows are filtered by the uid the daemon passes. + resetOmpProcessCache(); + const posixScan = await listOmpProcesses({ platform: "linux", uid, psBin: "/bin/ps", run: async () => posixRaw }); + assert.equal(posixScan.ok, true); + assert.deepEqual(posixScan.processes.map((process) => process.pid), [200, 202]); + + // No absolute `ps` is "unknown", never a fallback to PATH. + resetOmpProcessCache(); + const noPs = await listOmpProcesses({ platform: "linux", uid, psBin: null, run: async () => posixRaw }); + assert.deepEqual(noPs, { processes: [], ok: false, enabled: true }); + + // The Windows shape: `process.getuid` does not exist there, so the scan keeps every row — the documented + // process-identity limit — and narrows by process name instead. + resetOmpProcessCache(); + const windowsRaw = JSON.stringify([ + { ProcessId: 300, ParentProcessId: 1, Name: "omp.exe", CommandLine: "omp.exe --resume a" }, + { ProcessId: 301, ParentProcessId: 1, Name: "node.exe", CommandLine: "node C:\\Users\\x\\AppData\\Roaming\\npm\\node_modules\\@oh-my-pi\\cli.js --resume b" }, + { ProcessId: 302, ParentProcessId: 1, Name: "cmd.exe", CommandLine: "cmd.exe /c C:\\bin\\omp.cmd --resume c" }, + ]); + const windowsScan = await listOmpProcesses({ platform: "win32", uid: null, run: async () => windowsRaw }); + assert.equal(windowsScan.ok, true); + assert.deepEqual(windowsScan.processes.map((process) => process.pid), [300, 301, 302], "no uid filter on Windows: every row is kept"); + assert.deepEqual(windowsScan.processes.map((process) => process.name), ["omp.exe", "node.exe", "cmd.exe"]); +}); + +test("a scan that cannot run is unknown, and the next call retries instead of caching the failure", async () => { + resetOmpProcessCache(); + let calls = 0; + // win32: the scan runs the injected runner instead of resolving an absolute `ps` first. + const failing = await listOmpProcesses({ platform: "win32", run: async () => { calls += 1; throw new Error("PowerShell missing"); } }); + assert.deepEqual(failing, { processes: [], ok: false, enabled: true }); + assert.equal(calls, 1); + // Nothing was cached: the next caller asks again, and this one succeeds. + const recovered = await listOmpProcesses({ platform: "win32", run: async () => { calls += 1; return JSON.stringify({ ProcessId: 200, ParentProcessId: 1, CommandLine: "omp --resume x" }); } }); + assert.equal(calls, 2); + assert.equal(recovered.ok, true); + assert.deepEqual(recovered.processes.map((process) => process.pid), [200]); +}); + +test("OMP_WEB_FOREIGN_SCAN=0 reports the scan as switched off, which the detector answers as unknown", () => withSession(async ({ id }) => { + const previous = process.env.OMP_WEB_FOREIGN_SCAN; + process.env.OMP_WEB_FOREIGN_SCAN = "0"; + try { + const scan = await listOmpProcesses(); + assert.deepEqual(scan, { processes: [], ok: true, enabled: false }); + const result = await detectSessionOwnership([id], { scan: async () => scan }); + assert.equal(result.value[0].owner, "unknown"); + } finally { + if (previous === undefined) delete process.env.OMP_WEB_FOREIGN_SCAN; + else process.env.OMP_WEB_FOREIGN_SCAN = previous; + } +})); + +test("a stale scan row is not an owner: the liveness probe is what discards a process that already exited", () => withSession(async ({ id, file }) => { + // A scan is cached for 10 s, so it still lists a terminal `omp` that exited a moment ago. The default probe (no + // `isAlive` injected) must discard it, or a closed session stays blocked for the rest of the TTL. + const processes = [row(2147483000, { commandLine: `omp --resume ${file}` })]; + const stale = await detectSessionOwnership([id], { scan: scanOf(processes) }); + assert.equal(stale.value[0].owner, "none", "a dead pid in a cached scan is not a live writer"); + // The same row with a live pid (this process) is the writer: the probe, not the row, decides. + const live = await detectSessionOwnership([id], { scan: scanOf([row(process.pid, { commandLine: `omp --resume ${file}` })]) }); + assert.equal(live.value[0].owner, "foreign"); +}, { records: midTurn })); + +test("a tail window that parsed no complete record leaves activity unknown, not idle", () => withSession(async ({ id, file }) => { + // One 200 KiB record fills the 64 KiB window: the partial first line is dropped and nothing parses. The transcript's + // end is not in the window, so `running: false` would be a fact the inspection cannot establish. + const header = { type: "session", version: 3, id, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" }; + const huge = { type: "message", id: "t1", parentId: "a1", message: { role: "toolResult", toolCallId: "c1", content: "x".repeat(200 * 1024) } }; + writeFileSync(file, `${JSON.stringify(header)}\n${JSON.stringify(huge)}\n`); + const tail = readSessionTailState(file); + assert.equal(tail?.records, 0, "the window holds one oversized record and parses nothing"); + const result = await detectSessionOwnership([id], { scan: scanOf([]) }); + assert.equal(result.value[0].owner, "none"); + assert.equal("running" in result.value[0], false, "an unparsed window cannot say the turn ended"); + assert.equal(result.value[0].source, undefined); +}, { records: midTurn })); + +test("an id whose file does not resolve is still matched by the process that names it", () => withSession(async ({ id }) => { + // The stale-list-cache case: a foreign `omp` created this session after the 30 s list cache was warmed, so + // `resolveSessionPath` returns null. Before the scan saw only resolved files, this answered a definite `none`. + const fresh = "99999999-8888-4777-8666-555555555555"; + const { listAllSessions } = await import("../session-reader.ts"); + await listAllSessions(); + assert.equal(await (await import("../session-reader.ts")).resolveSessionPath(fresh), null, "the id has no resolvable file"); + const result = await detectSessionOwnership([id, fresh], { + scan: scanOf([row(200, { commandLine: `omp --resume ${fresh}` })]), + isAlive: alive, + }); + assert.deepEqual(result.value.map((entry) => [entry.id, entry.owner]), [[id, "none"], [fresh, "foreign"]], + "an unresolvable file must never turn a named writer into `none`"); +})); + +test("a daemon-owned session reports last activity from its channel's file", () => withSession(async ({ id, file }) => { + const result = await detectSessionOwnership([id], { + channel: () => ({ owned: true, running: false, sessionFile: file }), + scan: async () => { throw new Error("a daemon-owned session must not need a process scan"); }, + }); + assert.equal(result.value[0].owner, "daemon"); + assert.equal(typeof result.value[0].lastActivityAt, "number", "the contract promises last activity whenever it can be read"); + // A channel that knows no file (a legacy spawn before get_state) still answers ownership without activity. + const unknownFile = await detectSessionOwnership([id], { channel: () => ({ owned: true }) }); + assert.equal("lastActivityAt" in unknownFile.value[0], false); +})); + +test("the tail reads a trailing session_exit as closed and a running tool as active", () => withSession(async ({ file }) => { + const active = readSessionTailState(file); + assert.equal(active?.looksActive, true); + assert.equal(active?.hasTrailingExit, false); + writeFileSync(file, `${JSON.stringify({ type: "session", version: 3, id: "x", cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" })}\n${[...settled, exitRecord].map((line) => JSON.stringify(line)).join("\n")}\n`); + const closed = readSessionTailState(file); + assert.equal(closed?.looksActive, false); + assert.equal(closed?.hasTrailingExit, true); + assert.equal(Number.isInteger(closed?.mtimeMs), true, "epoch ms are integers: a fractional mtime breaks typed clients"); +}, { records: midTurn })); diff --git a/lib/hosts/session-ownership.ts b/lib/hosts/session-ownership.ts new file mode 100644 index 000000000..141de584d --- /dev/null +++ b/lib/hosts/session-ownership.ts @@ -0,0 +1,268 @@ +// Who holds a session's writer lease on this machine, answered where the children run. +// +// omp ≥ 18.5 lets exactly one process write a session: its lease lives in a +// named mutex / abstract socket (no file to read). A second writer does not +// fail, it silently moves the conversation to a fresh sibling file on its first +// write ("open-elsewhere"), which looked like a brand-new chat. +// +// Three facts meet only in the daemon, so this runs there: +// 1. `ChannelTable` is the authority for "ours": spawning, adopted, idle +// between turns and mid-turn children are all its channels. +// 2. The process scan runs in the same PID namespace and as the same uid as +// the children, so it excludes the daemon's own children exactly (transport +// pids plus a bounded ppid-chain walk for the Windows `cmd.exe` wrapper). +// 3. The transcript tail is read on the machine that owns the file. +// +// Ownership and activity are separate answers: a live foreign `omp` owns the +// file even while it is idle between turns (`running: false`), and a fresh +// transcript without positive owner evidence is an activity hint, not proof of +// a live writer (`owner: "none"`, `running: true`, `source: "transcript"`). +// A failed or switched-off scan is `unknown`, never `none`: a caller must be +// able to tell "nobody runs it" from "could not inspect". The op never spawns, +// kills or writes, and it is not an atomic native ownership lock — a writer can +// start between this inspection and a later spawn. +import { closeSync, openSync, readSync, statSync } from "node:fs"; +import { looksLikeRunningTurn } from "../chat-transcript-plan"; +import { parseJsonlLenient } from "../omp/session-files"; +import { resolveSessionPath } from "../session-reader"; +import { isRecord } from "../type-guards"; +import type { AgentMessage, SessionOwnership } from "../types"; +import { LINK_LIMITS } from "./link-protocol"; +import { + isProcessAlive, + listOmpProcesses, + sessionIdsNamedByProcesses, + type OmpProcessScan, + type ProcessLivenessProbe, +} from "./omp-processes"; +import type { OpResult } from "./session-ops"; + +/** + * Mirror of `EXTERNAL_RUN_STALE_MS` (hooks/useAgentSession-stream.ts): a tail + * that stopped growing for this long is not a live run any more. The hook + * constant cannot be imported here — that module is browser-side. + */ +export const OWNERSHIP_ACTIVE_WINDOW_MS = 60_000; + +const TAIL_BYTES = 64 * 1024; + +export interface SessionTailState { + /** The last record is omp's own `session_exit` (the writer closed the file). */ + hasTrailingExit: boolean; + /** The tail looks mid-turn (tool call without result, or a running tool). */ + looksActive: boolean; + mtimeMs: number; + /** How many complete records the window parsed. Zero means the window is one + * oversized record (a multi-MiB tool result fills it), so `looksActive` is + * not a fact about the transcript's end. */ + records: number; +} + +/** True for the records omp writes while a tool call is executing. */ +const LIVE_TOOL_RECORDS: Record = { + tool_execution_start: true, + tool_execution_update: true, +}; + +/** + * Read the last ≤64 KiB of a session file and describe its end. Backward-safe + * against a half-written last line (parsed leniently, skipped) and against the + * window starting mid-line (first partial line dropped). Returns null when the + * file cannot be read. + */ +export function readSessionTailState(filePath: string): SessionTailState | null { + let size: number; + let mtimeMs: number; + try { + const stat = statSync(filePath); + if (!stat.isFile()) return null; + size = stat.size; + // Integer epoch ms: mtimeMs is fractional on Windows, and a typed client + // that decodes `Long` rejects the whole frame on a fractional value. + mtimeMs = Math.round(stat.mtimeMs); + } catch { + return null; + } + if (size === 0) return { hasTrailingExit: false, looksActive: false, mtimeMs, records: 0 }; + + const length = Math.min(TAIL_BYTES, size); + let text: string; + try { + const fd = openSync(filePath, "r"); + try { + const buffer = Buffer.allocUnsafe(length); + const read = readSync(fd, buffer, 0, length, size - length); + text = buffer.subarray(0, read).toString("utf8"); + } finally { + closeSync(fd); + } + } catch { + return null; + } + if (length < size) { + // The window starts mid-record; drop that truncated first line. + const newline = text.indexOf("\n"); + text = newline >= 0 ? text.slice(newline + 1) : ""; + } + + const records = parseJsonlLenient>(text); + const tail = records.at(-1); + const tailType = isRecord(tail) && typeof tail.type === "string" ? tail.type : undefined; + const hasTrailingExit = tailType === "custom" && tail?.customType === "session_exit"; + + let looksActive: boolean; + if (hasTrailingExit) { + looksActive = false; + } else if (tailType === "custom" && typeof tail?.customType === "string" && LIVE_TOOL_RECORDS[tail.customType] === true) { + // A tool is executing right now; the agent has not settled yet. + looksActive = true; + } else { + // Judge by the last message in the window: a trailing tool result or an + // assistant tool call means the turn continues. + const messages: AgentMessage[] = []; + for (const record of records) { + if (!isRecord(record) || record.type !== "message") continue; + const message: unknown = record.message; + if (isRecord(message) && typeof message.role === "string") { + // Parsed JSONL entry: the record shape is omp's, validated just enough + // for `looksLikeRunningTurn` (role + content + stopReason). + messages.push(message as unknown as AgentMessage); + } + } + looksActive = messages.length > 0 && looksLikeRunningTurn(messages); + } + + return { hasTrailingExit, looksActive, mtimeMs, records: records.length }; +} + +/** What this daemon's ChannelTable says about one session. */ +export interface DaemonChannelState { + /** A child of this daemon runs (or is being spawned for) the session. */ + owned: boolean; + /** That child is mid-turn (or still starting): activity, not ownership. Absent when the channel's lifecycle is not + * tracked (a legacy channel), because then activity is unknown rather than idle. */ + running?: boolean; + /** The channel's launch file, when it knows one, so `lastActivityAt` is answered for a daemon-owned session too. */ + sessionFile?: string; +} + +export interface SessionOwnershipChecks { + /** `ChannelTable.ownership`: the authority for "ours". `sessionFile` is the resolved file, for a channel that knows + * the session only by its launch file. */ + channel?(id: string, sessionFile?: string | null): DaemonChannelState; + /** Pids of this daemon's children, so the foreign scan never counts them. */ + excludePids?(): readonly number[]; + /** One process snapshot for the whole batch (tests, or a caller that already scanned). */ + scan?(): Promise; + /** Confirm a scan hit against the OS; defaults to `omp-processes.isProcessAlive`. */ + isAlive?: ProcessLivenessProbe; + /** Read a session file's tail; defaults to `readSessionTailState`. A null answer means the file could not be read. */ + tail?: (file: string) => SessionTailState | null; + now?: () => number; +} + +const fail = (status: number, code: string, error: string): OpResult => ({ ok: false, status, code, error }); + +/** + * Answer `sessionOwnership` for a batch of ids: one entry per requested id, in + * request order. One bounded process scan covers the whole batch; the + * transcript tail is read only for ids whose file changed inside the activity + * window, because a silent old file cannot contribute activity. + */ +export async function detectSessionOwnership( + ids: string[], + checks: SessionOwnershipChecks = {}, +): Promise> { + if (!Array.isArray(ids) || ids.length === 0 || ids.length > LINK_LIMITS.ownershipIds || !ids.every((id) => typeof id === "string" && id.length > 0)) { + return fail(400, "invalid_request", `sessionOwnership takes a non-empty array of at most ${LINK_LIMITS.ownershipIds} session ids`); + } + const now = checks.now?.() ?? Date.now(); + const channels = new Map(); + const files = new Map(); + const unique = [...new Set(ids)]; + await Promise.all(unique.map(async (id) => { + // A daemon-owned session needs no list scan: its channel already knows the launch file, and `lastActivityAt` is + // part of the contract for every owner ("when it could be read"). + const byId = checks.channel?.(id); + if (byId?.owned) { + channels.set(id, byId); + files.set(id, byId.sessionFile ?? null); + return; + } + // Only ids this daemon does not own need their file resolved: the scan and the tail read it. + const file = await resolveSessionPath(id).catch(() => null); + files.set(id, file); + const byFile = checks.channel?.(id, file); + if (byFile?.owned) channels.set(id, byFile); + })); + + const scanned = channels.size === unique.length ? null : await (checks.scan?.() ?? listOmpProcesses()); + // Every requested id goes to the scan, with its file when one resolved: an + // id whose file did not resolve (a stale list cache, a relocated file) must + // still match a `--resume ` process, or a live foreign writer would be + // reported as a definite `none` — the one answer a caller may send into. + const named = scanned?.ok && scanned.enabled + ? sessionIdsNamedByProcesses( + scanned.processes, + unique.map((id) => ({ id, ...(files.get(id) ? { sessionFile: files.get(id) ?? undefined } : {}) })), + { excludePids: checks.excludePids?.() ?? [], isAlive: checks.isAlive ?? isProcessAlive }, + ) + : new Set(); + + const entries: SessionOwnership[] = []; + for (const id of ids) { + const channel = channels.get(id); + const file = files.get(id) ?? null; + let mtimeMs: number | null = null; + try { + const stat = file ? statSync(file) : null; + mtimeMs = stat?.isFile() ? Math.round(stat.mtimeMs) : null; + } catch { + mtimeMs = null; + } + const lastActivityAt = mtimeMs === null ? {} : { lastActivityAt: mtimeMs }; + if (channel) { + // The daemon's own child: spawning, adopted, idle between turns or mid-turn. `running` is activity alone, and + // omitted when the channel cannot say. + entries.push({ + id, + owner: "daemon", + source: "process", + ...(channel.running === undefined ? {} : { running: channel.running }), + ...lastActivityAt, + }); + continue; + } + if (scanned === null || !scanned.ok || !scanned.enabled) { + // Unsupported, failed or switched-off inspection: the caller must not + // read this as "nobody runs it", and must not read `running: false` as a + // fact either — activity is reported only from a successful inspection. + entries.push({ id, owner: "unknown", ...lastActivityAt }); + continue; + } + // Only a file written inside the window can say anything about activity; + // an idle owner keeps ownership regardless (see `owner` below). A file + // that exists but cannot be read leaves activity unknown: `running` is + // then absent instead of a `false` the inspection cannot establish. + const readTail = checks.tail ?? readSessionTailState; + const tail = file && mtimeMs !== null && now - mtimeMs < OWNERSHIP_ACTIVE_WINDOW_MS ? readTail(file) : null; + // A window that parsed no complete record (one oversized tool result fills + // it) says nothing about the transcript's end: activity is unknown, not idle. + const tailSaysSomething = tail !== null && tail.records > 0; + // Only a file that was read and is older than the window proves idleness. + // With no file to read (an id that does not resolve) activity is unknown too. + const activity = tailSaysSomething + ? { running: !tail.hasTrailingExit && tail.looksActive } + : mtimeMs !== null && now - mtimeMs >= OWNERSHIP_ACTIVE_WINDOW_MS ? { running: false } : {}; + if (named.has(id)) { + // A live `omp --resume` outside the daemon: ownership is the process, so + // an idle one still owns the file (`running` only says "mid-turn"). + entries.push({ id, owner: "foreign", source: "process", ...activity, ...lastActivityAt }); + continue; + } + // No positive owner evidence. A fresh tail is an activity hint only: it + // never turns into an owner, so it can never block a send by itself. + entries.push({ id, owner: "none", ...(tailSaysSomething ? { source: "transcript" as const } : {}), ...activity, ...lastActivityAt }); + } + return { ok: true, value: entries }; +} diff --git a/lib/session-ownership.test.mjs b/lib/session-ownership.test.mjs new file mode 100644 index 000000000..935df86e6 --- /dev/null +++ b/lib/session-ownership.test.mjs @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +const { sessionOwnershipOn } = await import("./session-ownership.ts"); +const { HostOpError, LINK_LIMITS } = await import("./hosts/link-protocol.ts"); + +/** A host whose session op answers through `answer(ids)`; a throw simulates a link failure. */ +function fakeHost(id, answer, label = "Build box") { + const calls = []; + return { + calls, + host: { + id, + label, + sessionOps: { + async sessionOwnership(ids) { + calls.push(ids); + return answer(ids); + }, + }, + }, + }; +} + +const ok = (ids) => ({ ok: true, value: ids.map((sessionId) => ({ id: sessionId, owner: "none" })) }); + +test("an older daemon's 501 becomes unknown for every id, logged once per host", async () => { + const warnings = []; + const original = console.warn; + console.warn = (line) => warnings.push(String(line)); + try { + const { host, calls } = fakeHost("old", async () => { + throw new HostOpError(501, "unknown_op", "Unknown host op: sessionOwnership"); + }); + const ids = ["a", "b"]; + assert.deepEqual(await sessionOwnershipOn(host, ids), [{ id: "a", owner: "unknown" }, { id: "b", owner: "unknown" }]); + await sessionOwnershipOn(host, ids); + assert.equal(calls.length, 2, "each refresh asks again: the daemon may have been updated"); + assert.equal(warnings.length, 1, "the compatibility state is logged once, not on every refresh"); + assert.match(warnings[0], /older daemon/); + } finally { + console.warn = original; + } +}); + +test("an offline host, a timeout and a malformed reply are all unknown, never none", async () => { + for (const failure of [ + new HostOpError(503, "host_offline", "Build box is offline"), + new HostOpError(504, "host_timeout", "Build box did not answer sessionOwnership in time"), + new HostOpError(502, "host_bad_result", "Build box sent an invalid sessionOwnership result"), + ]) { + const { host } = fakeHost("down", async () => { throw failure; }); + assert.deepEqual(await sessionOwnershipOn(host, ["a"]), [{ id: "a", owner: "unknown" }], failure.code); + } + // A daemon that answers an OpResult failure (rather than throwing) is the same: not evidence of absence. + const { host } = fakeHost("failed", async () => ({ ok: false, status: 500, code: "host_op_failed", error: "boom" })); + assert.deepEqual(await sessionOwnershipOn(host, ["a"]), [{ id: "a", owner: "unknown" }]); +}); + +test("more than 256 ids are paged, so no id is silently skipped", async () => { + const { host, calls } = fakeHost("big", async (ids) => ok(ids)); + const ids = Array.from({ length: LINK_LIMITS.ownershipIds * 2 + 7 }, (_, index) => `s${index}`); + const answer = await sessionOwnershipOn(host, ids); + assert.equal(answer.length, ids.length); + assert.deepEqual(answer.map((entry) => entry.id), ids, "request order across pages"); + assert.deepEqual(calls.map((page) => page.length), [LINK_LIMITS.ownershipIds, LINK_LIMITS.ownershipIds, 7]); +}); + +test("a failed page answers unknown for its ids and the remaining pages are still asked", async () => { + let page = 0; + const { host, calls } = fakeHost("flaky", async (ids) => { + page += 1; + if (page === 1) throw new HostOpError(504, "host_timeout", "slow"); + return ok(ids); + }); + const ids = Array.from({ length: LINK_LIMITS.ownershipIds + 3 }, (_, index) => `s${index}`); + const answer = await sessionOwnershipOn(host, ids); + assert.equal(calls.length, 2, "the second page was still asked"); + assert.deepEqual(answer.slice(0, LINK_LIMITS.ownershipIds).map((entry) => entry.owner), Array(LINK_LIMITS.ownershipIds).fill("unknown")); + assert.deepEqual(answer.slice(LINK_LIMITS.ownershipIds).map((entry) => entry.owner), ["none", "none", "none"]); +}); + +test("a duplicate id is asked once and answered once", async () => { + const { host, calls } = fakeHost("dup", async (ids) => ok(ids)); + const answer = await sessionOwnershipOn(host, ["a", "a", "b"]); + assert.deepEqual(calls, [["a", "b"]]); + assert.deepEqual(answer.map((entry) => entry.id), ["a", "b"]); +}); + +test("both wire shapes of one failure classify the same: a daemon 500 is unknown, a 400 propagates", async () => { + // Thrown and returned failures of the same status must not disagree: a 500 + // is an inspection that could not answer, a 4xx is a caller bug. + for (const status of [500, 501, 502, 503, 504, 429]) { + const thrown = fakeHost("thrown", async () => { throw new HostOpError(status, "host_op_failed", "boom"); }); + assert.deepEqual(await sessionOwnershipOn(thrown.host, ["a"]), [{ id: "a", owner: "unknown" }], `thrown ${status}`); + const returned = fakeHost("returned", async () => ({ ok: false, status, code: "host_op_failed", error: "boom" })); + assert.deepEqual(await sessionOwnershipOn(returned.host, ["a"]), [{ id: "a", owner: "unknown" }], `returned ${status}`); + } + for (const status of [400, 404]) { + const thrown = fakeHost("thrown-bad", async () => { throw new HostOpError(status, "invalid_request", "bad request"); }); + await assert.rejects(sessionOwnershipOn(thrown.host, ["a"]), (error) => error.status === status); + const returned = fakeHost("returned-bad", async () => ({ ok: false, status, code: "invalid_request", error: "bad request" })); + await assert.rejects(sessionOwnershipOn(returned.host, ["a"]), (error) => error.status === status); + } +}); + +test("a caller bug (400) is not swallowed as an unknown answer", async () => { + const { host } = fakeHost("bad", async () => { throw new HostOpError(400, "invalid_request", "Invalid session ids"); }); + await assert.rejects(sessionOwnershipOn(host, ["a"]), (error) => error.status === 400); +}); diff --git a/lib/session-ownership.ts b/lib/session-ownership.ts new file mode 100644 index 000000000..383389596 --- /dev/null +++ b/lib/session-ownership.ts @@ -0,0 +1,60 @@ +// Main's side of the `sessionOwnership` host op: one canonical ownership answer, no second detector. +// +// The daemon answers for its own machine (lib/hosts/session-ownership.ts); this module only asks, pages and normalizes. +// It never scans processes or reads transcripts here: the web server does not share the daemon's PID namespace, uid or +// filesystem, and a main-side scan is exactly the false "nobody runs it" the op replaced. +// +// A failed inspection is `unknown`, never `none`. An older daemon answers 501 `unknown_op`, an offline host 503, a slow +// one 504, a malformed reply 502; a caller must be able to tell "nobody runs it" from "could not inspect", so none of +// these ever becomes a negative answer. The 501 is logged once per host, because it is a compatibility state that +// persists until the daemon is updated, not a per-request error. +import type { Host } from "./hosts/host"; +import { HostOpError, LINK_LIMITS } from "./hosts/link-protocol"; +import type { SessionOwnership } from "./types"; + +/** Hosts whose daemon answered 501 for the op: logged once, not on every refresh. */ +const unsupportedLogged = new Set(); + +/** + * Whether a status means the *request* was wrong (a caller bug that must + * propagate) rather than the inspection being unable to answer. One rule for + * both wire shapes: a thrown `HostOpError` and an `OpResult` failure with the + * same status classify identically, so a daemon 500 cannot propagate in one + * shape and become `unknown` in the other. + */ +function callerBug(status: number): boolean { + return status >= 400 && status < 500 && status !== 408 && status !== 429; +} + +/** + * Who holds each of `ids` on `host`, in request order. More than + * `LINK_LIMITS.ownershipIds` ids are paged, so a large session list is fully + * covered instead of silently truncated; a page that fails answers `unknown` + * for its ids and does not stop the remaining pages. + */ +export async function sessionOwnershipOn(host: Host, ids: string[]): Promise { + const unique = [...new Set(ids)]; + const out: SessionOwnership[] = []; + for (let start = 0; start < unique.length; start += LINK_LIMITS.ownershipIds) { + const page = unique.slice(start, start + LINK_LIMITS.ownershipIds); + try { + const result = await host.sessionOps.sessionOwnership(page); + if (result.ok) { + // The host boundary already checked identity, order and length; keep the daemon's answer as is. + out.push(...result.value); + } else if (callerBug(result.status)) { + throw new HostOpError(result.status, result.code, result.error); + } else { + out.push(...page.map((id) => ({ id, owner: "unknown" as const }))); + } + } catch (error) { + if (error instanceof HostOpError && callerBug(error.status)) throw error; + if (error instanceof HostOpError && error.status === 501 && !unsupportedLogged.has(host.id)) { + unsupportedLogged.add(host.id); + console.warn(`[omp-web] ${host.label} does not answer sessionOwnership yet (older daemon); session ownership there is unknown until it is updated`); + } + out.push(...page.map((id) => ({ id, owner: "unknown" as const }))); + } + } + return out; +} diff --git a/lib/types.ts b/lib/types.ts index 658ad3aeb..9469ce7f4 100644 --- a/lib/types.ts +++ b/lib/types.ts @@ -461,6 +461,24 @@ export interface SessionInfo { hostId?: string; } +/** Who holds a session's writer lease on one host, as the `sessionOwnership` host op reports it + * (lib/hosts/session-ownership.ts). */ +export interface SessionOwnership { + id: string; + /** `daemon`: this host's daemon runs or starts the session (its ChannelTable is the authority, so a spawning, adopted + * or idle child counts). `foreign`: a live `omp --resume` process outside the daemon. `none`: a successful inspection + * found no writer. `unknown`: the inspection failed, is switched off or is unsupported — never a claim that nobody + * runs it. */ + owner: "daemon" | "foreign" | "none" | "unknown"; + /** A run is executing (or starting) right now. Absent when activity is unknown: with `owner: "unknown"` and no + * readable tail, `false` would be a fact the inspection cannot establish. */ + running?: boolean; + /** Evidence behind `running`: a process, or the transcript tail alone (an activity hint, never proof of a writer). */ + source?: "process" | "transcript"; + /** Epoch ms of the session file's last write, when it could be read. */ + lastActivityAt?: number; +} + /** Metadata for a gzip-compressed session in OMP's archive tree. */ export interface ArchivedSessionInfo { key: string;