From 2154ce9efd8ac20bd0a605298fe553a208a9e663 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 18:55:58 +0000 Subject: [PATCH 01/36] docs(specs): local daemon design (runs survive web restarts) --- docs/specs/2026-10-29-local-daemon-design.md | 149 +++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 docs/specs/2026-10-29-local-daemon-design.md diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md new file mode 100644 index 000000000..4f03b0347 --- /dev/null +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -0,0 +1,149 @@ +# Local daemon: omp runs survive web-server restarts + +## Goal + +Restarting or redeploying the ompweb web server never interrupts an omp run, on +this machine or any linked host. That frees the web server to change and restart +often. + +Today the web server owns the local omp children (`LocalHost` spawns them over +stdio), so every restart kills them, and auto-resume restarts them with a +resume prompt. Remote hosts (`docs/specs/2026-10-28-remote-hosts-design.md`) +already keep their children alive while the link is down, but a web-server +restart still kills them as orphans. + +## Decisions + +- **The local daemon is required.** This machine is reached only through a + local `ompweb host` daemon, linked over loopback. `LocalHost`'s direct spawn + path is removed; there is one code path for every host. +- **The daemon is its own service** (systemd unit / launchd agent / Windows + service), installed next to the web service. +- **Restarts adopt live children.** A restarted web server takes over the omp + children the daemon still runs instead of killing them. +- **Dev mode links to the same daemon.** `npm run dev` links to the local + daemon and takes the link over while it runs (one link per host); production + gets it back when dev stops. + +## Non-goals + +- Changing omp. Gaps in omp's RPC that block a clean adoption are handled with + the fallbacks below and reported upstream separately. +- Keeping runs alive across a daemon restart. The daemon owns the children; + restarting it ends them, and auto-resume handles that as today. +- Multiple web servers sharing one daemon at the same time. + +## Process layout + +``` +ompweb (web service) ──link over 127.0.0.1──▶ ompweb host (daemon service) ──▶ omp children + └──link over https/tailnet──▶ ompweb host on the Mac ──▶ omp children +``` + +- **"This machine" is a linked host with the fixed id `local`.** It is shown as + "This machine", listed first, and cannot be revoked or renamed in Settings → + Hosts. +- **Session file operations** (`session-ops.ts`) run in the daemon, as they do + for remote hosts. The web server keeps no direct session-file reads for + `local`, so the two paths cannot drift. +- **Local link bootstrap.** On start, the web server makes sure a host record + `local` exists with a token, and writes the daemon's + `/omp-web/host.json` (`{url, token}`, mode 0600) with its own + loopback URL. The daemon re-reads `host.json` when its link gets 401, so a + web server that regenerated the token is picked up without restarting the + daemon. Loopback links use `http://` without `--allow-http`. + +## Adopting live children + +On `hello`, for each listed `{ch, sessionId}` that has no wrapper on the web +server: + +1. Look up `sessionId` in that host's session list to get the file and cwd. A + child whose session is unknown (never written, or deleted) is killed, as + today. +2. Create an `AgentSessionWrapper` on the existing channel with `adopted: true`. + It skips spawn, the `ready` wait and the initial protocol negotiation. +3. Re-sync the protocol: send `negotiate_protocol` again; drop partial chunked + frames until the next complete one. +4. Rebuild state: `get_state` (identity, model, streaming/compacting, queue), + `get_subagents`, `get_btw_history`. If omp reports a run in progress, mark + the wrapper running; the next frames continue it, and the committed message + shows anything streamed before the restart. +5. Register the wrapper under its session id and publish it on the `running` + channel; browsers reopening the session attach as on any stream reopen. + +**Gaps and fallbacks.** Each is checked against omp's RPC while planning; the +fallback applies when omp cannot provide what adoption needs: + +| Lost at restart | Needed from omp | Fallback | +|---|---|---| +| A pending `extension_ui_request` (ask/confirm/select/input) | a way to list or re-send pending UI requests | send `abort` and post a notice: "A question was lost when ompweb restarted; the run was stopped." | +| A pending `host_tool_call` | accepting a late `host_tool_result` by id | answer each pending call with an error result so the agent continues | +| Protocol v2 framing mid-chunk | re-negotiation on a live process | if refused, treat the child as unrecoverable: kill and resume once | + +**Adoption failure** (any of the re-sync commands time out after +`GET_STATE_TIMEOUT_MS`): the child is killed and resumed once through the +existing orphan path, so no session ends up with two writers. + +Auto-resume remains for children that really died: a daemon restart, a crash, +or an adoption failure. + +## Failure cases + +| Case | Behavior | +|---|---| +| Web server restarts, daemon fine | Runs continue; adopted on `hello`; no resume prompt. | +| Daemon restarts or upgrades | Children end; sessions that were running resume once (existing auto-resume). | +| Web and daemon on different link protocol versions | 426; "This machine" shows "needs upgrade"; new sessions there are disabled until the daemon is restarted on the new version. | +| Dev server takes the link | Production's local wrappers see the link down (offline banner). When dev stops, production redials, gets the link back and adopts every live channel, including ones dev started. | +| Daemon not installed or not running | "This machine" shows offline with "start the ompweb-host service"; new local sessions are disabled. | +| `host.json` token stale (web regenerated it) | Daemon gets 401, re-reads `host.json`, redials. It exits only if the file still holds the rejected token. | + +## Installing and upgrading + +- `ompweb systemd install` and `ompweb launchd install` install two units: the + existing web unit and `ompweb-host` (`ompweb host`), both restarting on + failure. Uninstall removes both. +- Windows (`lib/windows-service.ts`, tray): the same split, a second service + for the daemon. The tray shows both states. +- **Existing installs:** on first start after the upgrade, if no local daemon + links within 10 s, the web server shows a one-time banner with the exact + command to install the daemon service (it does not install services itself). + Until then "This machine" is offline as above. +- **Upgrades:** an upgrade replaces the package for both. The web unit restarts + as today. The daemon unit restarts only when `LINK_PROTOCOL_VERSION` + changed; otherwise the old daemon keeps running the live children and new + code takes effect at its next restart. + +### This machine's deployment + +`/opt/omp-deployment/bin/ompweb-deploy` gains a daemon unit (`ompweb-host`) +from the same release: + +- It restarts `ompweb-api` with the existing probes and rollback. +- It restarts `ompweb-host` only when the release's `LINK_PROTOCOL_VERSION` + differs from the running daemon's (read from `GET /api/hosts`). +- Rollback restores the previous release for both units. + +## Dev mode + +`npm run dev` uses the same agent dir and the same `host.json` as production, +so it links to the production daemon and takes the link over. It does nothing +special: the takeover and the return are the one-link-per-host rule. + +## Testing + +- **Unit:** adoption builds a wrapper from `hello` without spawning; the + re-sync order; each fallback in the gaps table; adoption failure kills and + resumes once; local bootstrap writes `host.json` and re-reads on 401. +- **Integration:** a real web server and a real daemon (fake omp). Start a run, + restart only the web side; the same omp pid keeps streaming, no resume prompt, + no duplicated or lost frames. Restart the daemon; the run resumes once. +- **Deploy smoke:** deploy a web-only change on this VM during a run; the run + continues. + +## Documentation + +AGENTS.md (process layout, adoption, the required daemon), README (two services, +install commands, dev mode note), DESIGN.md (the host seam no longer has a +direct path), CHANGELOG. From e32c71894999eb1e55d020fa9627ba76712940d9 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 18:59:09 +0000 Subject: [PATCH 02/36] docs: local daemon plan; spec replays pending requests instead of aborting --- docs/plans/2026-10-29-local-daemon.md | 167 +++++++++++++++++++ docs/specs/2026-10-29-local-daemon-design.md | 31 +++- 2 files changed, 190 insertions(+), 8 deletions(-) create mode 100644 docs/plans/2026-10-29-local-daemon.md diff --git a/docs/plans/2026-10-29-local-daemon.md b/docs/plans/2026-10-29-local-daemon.md new file mode 100644 index 000000000..4d2145fdc --- /dev/null +++ b/docs/plans/2026-10-29-local-daemon.md @@ -0,0 +1,167 @@ +# Local Daemon Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** omp runs survive web-server restarts: this machine is reached only through a local `ompweb host` daemon, and a restarted web server adopts the omp children it finds running. + +**Architecture:** Builds on PR #339 (`feat/remote-hosts`). The hub stops killing unknown channels on `hello` and adopts them into `AgentSessionWrapper`s rebuilt from omp's state. The daemon replays still-open blocking requests it saw on each channel. "This machine" becomes a linked host `local` over loopback, bootstrapped by the web server; main no longer spawns omp or reads session files itself. + +**Tech Stack:** Next 16 route handlers, Node 24, `node:test`, jiti; systemd/launchd/Windows service helpers in `bin/` and `lib/windows-service.ts`. + +**Spec:** `docs/specs/2026-10-29-local-daemon-design.md` (and `docs/specs/2026-10-28-remote-hosts-design.md` for the link it extends). + +## Global Constraints + +- Base branch: `feat/remote-hosts` (PR #339) until it merges, then `upstream/main`. +- No new dependencies. Daemon-loaded modules (`lib/hosts/*`, what they import) never import `next/*` or `@/`. +- `LINK_PROTOCOL_VERSION` becomes `3` (hello carries pending requests). +- Pending-request replay cap: 1 MB of raw lines per channel; over it the channel is not adoptable. +- Adoption re-sync uses the existing `GET_STATE_TIMEOUT_MS`; a timeout kills the child and resumes it once. +- The local host id is the literal `"local"`; label "This machine"; it cannot be renamed or revoked. +- Loopback links (`127.0.0.1`, `::1`, `localhost`) use `http://` without `--allow-http`. +- Copy: "start the ompweb-host service"; "This machine needs the ompweb-host service. Install it with: ". +- Client code never uses `AbortSignal.timeout/any` or `Promise.withResolvers`; every new UI string exists in all `lib/i18n/locales/*.json`. +- Line numbers below are hints; locate code by symbol. + +## Review Focus + +1. A web restart during a run that is waiting on an `ask` dialog: after adoption the dialog shows again in the browser and answering it continues the run (Task 1 + Task 3 tests). +2. A channel listed in `hello` whose session id is unknown, or whose re-sync times out: killed and resumed once, never two writers on one file (Task 3). +3. Dev server takes the local link, then stops: production adopts channels dev started, including a run dev left mid-turn (Task 3 integration test). +4. A web server that regenerated the local token: the daemon re-reads `host.json` on 401 and relinks without restarting its children (Task 4). +5. A machine with the new web server but no daemon service: "This machine" offline with the install hint, no crash, no direct spawn (Task 5 + Task 6). + +--- + +### Task 1: Daemon tracks and replays pending blocking requests (link v3) + +**Files:** +- Modify: `lib/hosts/link-protocol.ts` (version 3; hello channel `pending: string[]`), `lib/hosts/daemon.ts` +- Create: `lib/hosts/pending-requests.ts` +- Test: `lib/hosts/pending-requests.test.mjs`, `lib/hosts/daemon.test.mjs` + +**Interfaces:** +- Produces: + ```ts + export class PendingRequests { // one per channel, daemon side + constructor(limitBytes: number); + noteStdout(line: string): void; // decodes (RpcFrameDecoder) and opens/closes entries + noteStdin(line: string): void; // host_tool_result / extension_ui_response close by id + lines(): string[] | null; // raw lines of open requests in order; null when over the cap + } + // hello: channels: { ch: string; sessionId: string | null; pending: string[] | null }[] + ``` + Opened by `host_tool_call` and `extension_ui_request` with a method in `BLOCKING_UI_METHODS` (import from `lib/notification-events.ts` if it has no next/@ imports, else move the constant to a shared module). Closed by `host_tool_result`/`extension_ui_response` with the same id on stdin, or `host_tool_cancel` (`targetId`) / an `extension_ui_request` cancel frame from omp. A chunked frame's raw `rpc_chunk` lines are kept together. +- [ ] **Step 1: Failing tests** — `pending-requests.test.mjs`: an `ask` request then its `extension_ui_response` → `lines()` is `[]`; an open `host_tool_call` → `lines()` holds its raw line; a request split into three `rpc_chunk` lines → `lines()` holds all three in order; `host_tool_cancel` with `targetId` closes the call; past `limitBytes` → `null`; a non-blocking `notify` UI request is not kept. `daemon.test.mjs`: after a link drop the next `hello` carries the open request's line for its channel. +- [ ] **Step 2: Run** `node --experimental-strip-types --test lib/hosts/pending-requests.test.mjs lib/hosts/daemon.test.mjs` → FAIL. +- [ ] **Step 3: Implement**; bump `LINK_PROTOCOL_VERSION` to 3 and update `decodeUp` for the new hello field. +- [ ] **Step 4: Run** → PASS; `npm test`, `node_modules/.bin/tsc --noEmit`. +- [ ] **Step 5: Commit** `feat(hosts): the daemon replays open blocking requests on hello`. + +### Task 2: Adopted session wrapper + +**Files:** +- Modify: `lib/omp/rpc-process.ts`, `lib/rpc-manager.ts` +- Test: `lib/rpc-manager.test.mjs`, `lib/omp/rpc-process-runtime.test.mjs` + +**Interfaces:** +- Produces: + ```ts + // RpcProcessOptions gains: + adopted?: { protocolVersion: 2 }; // skip the ready wait; decoder starts at v2 and drops rpc_chunk records until a chunk with index 0 / a plain frame + export async function adoptRpcSession(input: { + host: Host; transport: RpcTransport; sessionId: string; sessionFile: string; cwd: string; replay: string[]; + }): Promise; // lib/rpc-manager.ts + ``` + `adoptRpcSession` builds the wrapper on the existing transport with no spawn, sends `negotiate_protocol` (v2), `set_subagent_subscription`, `set_ask_dialog`, `get_state` (→ `applyIdentity`, running/compacting/queue), `get_subagents`, `get_btw_history`; then feeds each `replay` line through the same path as a stdout line so `handleFrame` re-tracks dialogs and host tool calls; registers it like `startRpcSession` (registry, `onDestroy`, `onIdentityChange`) and calls `notifyRunningChange`. Any re-sync command timing out (`GET_STATE_TIMEOUT_MS`) rejects after destroying the wrapper. +- [ ] **Step 1: Failing tests** — scripted transport already past `ready`: `adoptRpcSession` resolves without waiting for `ready`, issues the commands in the order above, reports `isRunning()` when `get_state` says streaming; a replayed `ask` `extension_ui_request` appears in the wrapper's pending dialogs and reaches an attached listener; a replayed `host_tool_call` reaches a host-tool listener; a leading `rpc_chunk` continuation is dropped without a protocol error; a `get_state` timeout rejects and the transport receives a kill. +- [ ] **Step 2: Run** the two test files → FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** → PASS; `npm test`, `tsc`. +- [ ] **Step 5: Commit** `feat(rpc): adopt a live omp child into a session wrapper`. + +### Task 3: The hub adopts instead of killing + +**Files:** +- Modify: `lib/hosts/hub.ts` (`reattach`), `lib/session-resume.ts` (`resumeOnHostLink`), `lib/hosts/session-index.ts` (session lookup for adoption) +- Test: `lib/hosts/hub.test.mjs`, `lib/session-resume.test.mjs`, `lib/hosts/link-integration.test.mjs` + +**Interfaces:** +- Consumes: `adoptRpcSession` (Task 2), hello `pending` (Task 1). +- Produces: on `hello`, each listed channel with no transport and a `sessionId` found in that host's session list (fresh `listSessions`, not the cache) is adopted with its `pending` lines as `replay`. Channels with no `sessionId`, an unknown session, `pending === null`, or a failed adoption take today's orphan path (kill, `orphanExit`, resume once if it was mid-run). An adopted session is removed from the interrupted-session list so `resumeOnHostLink` never resumes it. +- [ ] **Step 1: Failing tests** — hub: a listed unknown channel for a known session is adopted (no `kill` sent, wrapper registered); unknown session → killed as today; adoption failure → killed and resumed once; `pending: null` → killed. session-resume: an adopted session gets no resume prompt. link-integration: real daemon + fake omp; start a run, recreate the hub (simulated web restart), the same child pid keeps streaming frames to a new wrapper with no gap or duplicate, and no resume prompt is written to its stdin; a run waiting on an `ask` shows the dialog again after the restart and the answer reaches omp. +- [ ] **Step 2: Run** → FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** → PASS; `npm test`, `tsc`. +- [ ] **Step 5: Commit** `feat(hosts): a restarted web server adopts live omp children`. + +### Task 4: Local link bootstrap + +**Files:** +- Modify: `lib/hosts/registry.ts` (reserved `local` record), `lib/hosts/hub.ts` (`getHost("local")` → the linked host), `lib/hosts/daemon.ts` (re-read `host.json` on 401; loopback http), `bin/omp-web-host.js`, `instrumentation.node.ts` (bootstrap at start), `app/api/hosts/route.ts` (local row from the registry, not synthesized) +- Create: `lib/hosts/local-bootstrap.ts` +- Test: `lib/hosts/local-bootstrap.test.mjs`, `lib/hosts/daemon.test.mjs`, `lib/hosts/hosts-route.test.mjs` + +**Interfaces:** +- Produces: + ```ts + export function ensureLocalHostLink(input: { url: string }): { token: string; written: boolean }; + // registry: the "local" record exists exactly once; createHost never returns id "local"; updateHost/revokeHost("local") throw + ``` + At startup the web server calls `ensureLocalHostLink({ url: "http://127.0.0.1:" })`: creates or keeps the `local` record, writes `/omp-web/host.json` (0600, temp + rename) when its url/token differ. The daemon, on 401, re-reads `host.json` once and redials with the new token; it exits only when the file still holds the rejected token. `http://` is accepted for loopback hosts without `--allow-http`. +- [ ] **Step 1: Failing tests** — bootstrap writes `host.json` with the server's loopback url and a token `hostForToken` accepts; a second call with the same url does not rewrite; registry refuses to revoke/rename `local`; daemon given a stale token gets 401, re-reads the rewritten file and links; daemon with an unchanged stale file exits 1; `http://127.0.0.1` links without `--allow-http`. +- [ ] **Step 2: Run** → FAIL. +- [ ] **Step 3: Implement.** +- [ ] **Step 4: Run** → PASS; `npm test`, `tsc`. +- [ ] **Step 5: Commit** `feat(hosts): bootstrap the local daemon link`. + +### Task 5: Main never runs omp or reads session files itself + +**Files:** +- Modify: `lib/hosts/local-host.ts` (becomes the daemon's machine implementation; main imports nothing from it), `lib/api-utils.ts`, `lib/hosts/session-index.ts`, `lib/rpc-manager.ts`, every `app/api/**` route importing `localHost`, `lib/session-resume.ts`, `lib/file-access.ts` (local roots now come from the `local` host's session list) +- Test: affected route/manager tests; add `lib/hosts/no-direct-local.test.mjs` + +**Interfaces:** +- Consumes: `getHost("local")` from Task 4. +- Produces: every main-side path that used `localHost` uses `getHost("local")`. `allowFileRoot` keeps working for `local` (local paths are main's paths) — the check becomes `host.id === "local"` instead of `host === localHost`. `no-direct-local.test.mjs` fails if any file under `app/` or `lib/` other than `lib/hosts/daemon.ts`, `lib/hosts/local-host.ts` and their tests imports `local-host` or `spawnLocalRpcTransport`. +- [ ] **Step 1: Write** `no-direct-local.test.mjs` (it fails on the current imports). +- [ ] **Step 2: Run** → FAIL listing the importing files. +- [ ] **Step 3: Migrate** each import; tests that relied on direct local behavior use the existing `link-driver.test-helper.mjs` or a fake host. +- [ ] **Step 4: Run** `npm test`, `tsc`, `npm run lint` → PASS. +- [ ] **Step 5: Commit** `refactor(hosts): this machine goes through its daemon`. + +### Task 6: Offline local host UI and install hint + +**Files:** +- Modify: `components/HostsConfig.tsx` (local row: no rename/revoke; offline hint), `components/AppShell.tsx` (one-time banner), `lib/i18n/locales/*.json` +- Test: `components/HostsConfig.test.mjs` + +**Interfaces:** +- Consumes: `hosts` channel status for `local`. +- Produces: when `local` is offline, Settings → Hosts shows "start the ompweb-host service"; when it has never linked since this web server started and 10 s have passed, AppShell shows a one-time dismissible banner "This machine needs the ompweb-host service. Install it with: ", where the command is the platform's helper from Task 7 (`ompweb systemd install` / `ompweb launchd install` / the Windows service command). +- [ ] **Step 1: Failing tests** — local row renders no Rename/Revoke; offline local row shows the hint; banner appears once after 10 s offline, not again after dismissal (localStorage key), not when local links. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS; lint. +- [ ] **Step 5: Commit** `feat(hosts): tell users to install the local daemon`. + +### Task 7: Service helpers install both units + +**Files:** +- Modify: `bin/omp-web-systemd.js`, `bin/omp-web-launchd.js`, `lib/windows-service.ts`, `bin/omp-web-tray.js` +- Test: `bin/omp-web-systemd.test.mjs`, `lib/windows-service.test.mjs`, a launchd plist test + +**Interfaces:** +- Produces: `install` writes and enables two units — the existing web unit and `ompweb-host` running ` host` with `Restart=always` (systemd) / `KeepAlive` (launchd) / a second Windows service; `uninstall` removes both; `status` reports both. The tray shows the daemon state next to the web state. +- [ ] **Step 1: Failing tests** — generated systemd units: two files, the host unit's `ExecStart` ends with ` host`; launchd: two plists with `KeepAlive`; Windows: two service definitions. +- [ ] **Step 2: Run** → FAIL. **Step 3: Implement.** **Step 4: Run** → PASS. +- [ ] **Step 5: Commit** `feat(service): install the ompweb-host daemon next to the web service`. + +### Task 8: This machine's deploy and docs + +**Files:** +- Modify (outside the repo, not under git): `/opt/omp-deployment/bin/ompweb-deploy`; create the `ompweb-host` systemd unit for this VM +- Modify: `AGENTS.md`, `README.md`, `DESIGN.md`, `CHANGELOG.md` + +- [ ] **Step 1:** Back up `/opt/omp-deployment/bin/ompweb-deploy`, then add: `ompweb-host` unit pointing at the same release; restart it only when the release's `LINK_PROTOCOL_VERSION` differs from the running daemon's (`GET /api/hosts`, local row `hostVersion`); rollback restores both units' release. +- [ ] **Step 2:** Docs per the spec's Documentation section. +- [ ] **Step 3: Deploy smoke (needs the user's go-ahead to deploy):** start a long run on this machine, deploy a web-only change, confirm the run continues with the same omp pid and no resume prompt. +- [ ] **Step 4: Commit** `docs(hosts): document the local daemon`. diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index 4f03b0347..99f4b2465 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -72,14 +72,29 @@ server: 5. Register the wrapper under its session id and publish it on the `running` channel; browsers reopening the session attach as on any stream reopen. -**Gaps and fallbacks.** Each is checked against omp's RPC while planning; the -fallback applies when omp cannot provide what adoption needs: - -| Lost at restart | Needed from omp | Fallback | -|---|---|---| -| A pending `extension_ui_request` (ask/confirm/select/input) | a way to list or re-send pending UI requests | send `abort` and post a notice: "A question was lost when ompweb restarted; the run was stopped." | -| A pending `host_tool_call` | accepting a late `host_tool_result` by id | answer each pending call with an error result so the agent continues | -| Protocol v2 framing mid-chunk | re-negotiation on a live process | if refused, treat the child as unrecoverable: kill and resume once | +**Pending requests are replayed by the daemon.** omp (checked at oh-my-pi +`3e3c488a58`) has no command that lists pending `extension_ui_request`s or +`host_tool_call`s, and neither ever times out, so a request the web server +missed would block the run forever. The daemon already sees every line, so it +keeps, per channel, the raw lines of each blocking request still open: + +- opened by a `host_tool_call` or an `extension_ui_request` whose method is in + `BLOCKING_UI_METHODS` (decoded with `RpcFrameDecoder`, so chunked frames are + kept whole); +- closed by the matching `host_tool_result` / `extension_ui_response` written to + stdin, or a `host_tool_cancel` / UI cancel from omp. + +`hello` carries them per channel (`channels[{ch, sessionId, pending: string[]}]`, +capped at 1 MB per channel; over the cap the channel is not adoptable and takes +the kill-and-resume path). The adopted wrapper feeds them through its normal +frame handling, so dialogs reappear, input-needed notifications fire, and browser +tool calls reach a tab again. This changes the hello shape, so +`LINK_PROTOCOL_VERSION` becomes 3. + +**Framing.** omp answers `negotiate_protocol` every time, and every ompweb child +is already on protocol v2, so the adopted wrapper starts its decoder at v2, +drops `rpc_chunk` records until the first record of a new frame, and sends +`negotiate_protocol` again. **Adoption failure** (any of the re-sync commands time out after `GET_STATE_TIMEOUT_MS`): the child is killed and resumed once through the From 2c63a5e917db0ed3b6b0b4eb86dd10a45ca2c5d1 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 19:02:49 +0000 Subject: [PATCH 03/36] docs: dev mode does not take the local daemon --- docs/plans/2026-10-29-local-daemon.md | 4 ++-- docs/specs/2026-10-29-local-daemon-design.md | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/plans/2026-10-29-local-daemon.md b/docs/plans/2026-10-29-local-daemon.md index 4d2145fdc..2a65f3561 100644 --- a/docs/plans/2026-10-29-local-daemon.md +++ b/docs/plans/2026-10-29-local-daemon.md @@ -27,7 +27,7 @@ 1. A web restart during a run that is waiting on an `ask` dialog: after adoption the dialog shows again in the browser and answering it continues the run (Task 1 + Task 3 tests). 2. A channel listed in `hello` whose session id is unknown, or whose re-sync times out: killed and resumed once, never two writers on one file (Task 3). -3. Dev server takes the local link, then stops: production adopts channels dev started, including a run dev left mid-turn (Task 3 integration test). +3. A dev server (`NODE_ENV=development`) starting next to production: it never rewrites `host.json`, the daemon stays linked to production, and production's runs are untouched (Task 4 test). 4. A web server that regenerated the local token: the daemon re-reads `host.json` on 401 and relinks without restarting its children (Task 4). 5. A machine with the new web server but no daemon service: "This machine" offline with the install hint, no crash, no direct spawn (Task 5 + Task 6). @@ -108,7 +108,7 @@ export function ensureLocalHostLink(input: { url: string }): { token: string; written: boolean }; // registry: the "local" record exists exactly once; createHost never returns id "local"; updateHost/revokeHost("local") throw ``` - At startup the web server calls `ensureLocalHostLink({ url: "http://127.0.0.1:" })`: creates or keeps the `local` record, writes `/omp-web/host.json` (0600, temp + rename) when its url/token differ. The daemon, on 401, re-reads `host.json` once and redials with the new token; it exits only when the file still holds the rejected token. `http://` is accepted for loopback hosts without `--allow-http`. + At startup the web server calls `ensureLocalHostLink({ url: "http://127.0.0.1:" })` — skipped when `NODE_ENV` is `development` — : creates or keeps the `local` record, writes `/omp-web/host.json` (0600, temp + rename) when its url/token differ. The port is the one the server actually listens on (read how `bin/omp-web.js` passes it to `next start`). The daemon, on 401, re-reads `host.json` once and redials with the new token; it exits only when the file still holds the rejected token. `http://` is accepted for loopback hosts without `--allow-http`. - [ ] **Step 1: Failing tests** — bootstrap writes `host.json` with the server's loopback url and a token `hostForToken` accepts; a second call with the same url does not rewrite; registry refuses to revoke/rename `local`; daemon given a stale token gets 401, re-reads the rewritten file and links; daemon with an unchanged stale file exits 1; `http://127.0.0.1` links without `--allow-http`. - [ ] **Step 2: Run** → FAIL. - [ ] **Step 3: Implement.** diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index 99f4b2465..8f670322a 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -21,9 +21,10 @@ restart still kills them as orphans. service), installed next to the web service. - **Restarts adopt live children.** A restarted web server takes over the omp children the daemon still runs instead of killing them. -- **Dev mode links to the same daemon.** `npm run dev` links to the local - daemon and takes the link over while it runs (one link per host); production - gets it back when dev stops. +- **Dev mode does not take the local daemon.** Only the production web server + writes the daemon's `host.json`; a dev server shows "This machine" offline. + (The daemon dials out, so a takeover would need it to follow every rewrite of + `host.json`, and production and dev would then pull it back and forth.) ## Non-goals @@ -110,7 +111,7 @@ or an adoption failure. | Web server restarts, daemon fine | Runs continue; adopted on `hello`; no resume prompt. | | Daemon restarts or upgrades | Children end; sessions that were running resume once (existing auto-resume). | | Web and daemon on different link protocol versions | 426; "This machine" shows "needs upgrade"; new sessions there are disabled until the daemon is restarted on the new version. | -| Dev server takes the link | Production's local wrappers see the link down (offline banner). When dev stops, production redials, gets the link back and adopts every live channel, including ones dev started. | +| Dev server running | It never writes `host.json`, so the daemon stays linked to production; dev shows "This machine" offline. | | Daemon not installed or not running | "This machine" shows offline with "start the ompweb-host service"; new local sessions are disabled. | | `host.json` token stale (web regenerated it) | Daemon gets 401, re-reads `host.json`, redials. It exits only if the file still holds the rejected token. | @@ -142,9 +143,8 @@ from the same release: ## Dev mode -`npm run dev` uses the same agent dir and the same `host.json` as production, -so it links to the production daemon and takes the link over. It does nothing -special: the takeover and the return are the one-link-per-host rule. +When `NODE_ENV` is `development`, the web server skips `ensureLocalHostLink`: +the daemon stays linked to production, and dev shows "This machine" offline. ## Testing From 8109925b1ed73062d5320c1c5975a3e67acb19a2 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 19:12:47 +0000 Subject: [PATCH 04/36] feat(hosts): the daemon replays open blocking requests on hello --- AGENTS.md | 6 +- lib/hosts/daemon.test.mjs | 21 +++++++ lib/hosts/daemon.ts | 33 +++++++--- lib/hosts/hub.test.mjs | 12 ++-- lib/hosts/hub.ts | 2 +- lib/hosts/link-protocol.test.mjs | 6 +- lib/hosts/link-protocol.ts | 22 +++++-- lib/hosts/pending-requests.test.mjs | 72 +++++++++++++++++++++ lib/hosts/pending-requests.ts | 97 +++++++++++++++++++++++++++++ lib/rpc-manager.test.mjs | 6 +- lib/session-resume.test.mjs | 2 +- 11 files changed, 253 insertions(+), 26 deletions(-) create mode 100644 lib/hosts/pending-requests.test.mjs create mode 100644 lib/hosts/pending-requests.ts diff --git a/AGENTS.md b/AGENTS.md index 43657d629..e1ae4a8b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -114,6 +114,7 @@ lib/ link-protocol.ts link messages, codec, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox` hub.ts main side: link GET/POST/blob handlers, `RemoteHost`, `getHost`, `listHosts`, orphans, `hosts` change events daemon.ts remote side: `loginHost`, `readHostLogin`, `runHostDaemon` (reconnect, buffering, op dispatch) + pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests for the hello registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget` provider-accounts.ts distinct omp accounts per provider from `omp usage` reports (Models → provider detail) @@ -266,7 +267,10 @@ bin/ buffers would cap the channels it lists): a POST with `x-omp-web-hello: 1` carries it and answers `{helloId}`, and the downlink GET names that id in `x-omp-web-hello`; main takes the hello at that GET, so it opens one - downlink once. A v1 daemon's header hello gets 426. Each side keeps unacked + downlink once. A v1 daemon's header hello gets 426. Each `hello.channels` + entry carries `pending` (link v3): the raw stdout lines of that child's + still-open `host_tool_call`s and blocking `extension_ui_request`s + (`PendingRequests`), or null past `LINK_LIMITS.pendingBytes`. Each side keeps unacked lines, resends after a reconnect and drops any `seq` it already applied. Main decodes a whole POST before applying any of it. `hello.ack === 0` means a fresh daemon: main restarts that host's uplink window. Wire shapes diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index d98f42bea..b45cf52e3 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -42,6 +42,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l const count = Math.ceil(bytes.length / 262144); for (let index = 0; index < count; index++) process.stdout.write(JSON.stringify({ type: "rpc_chunk", chunkId: id, index, count, byteLength: bytes.length, data: bytes.subarray(index * 262144, (index + 1) * 262144).toString("base64") }) + "\\n"); } + if (type === "ask") process.stdout.write('{"type":"extension_ui_request","id":"q1","method":"ask","questions":[]}\\n'); }); `); @@ -422,6 +423,26 @@ test("5xx answers are retried and the omp children keep running", async () => { assert.equal(await daemon.done, 0); }); +test("after a link drop the next hello carries each channel's open blocking requests", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + try { + await waitFor(() => server.downlink, "the downlink"); + await spawnChannel(server, "c1"); + server.send({ type: "stdin", ch: "c1", line: '{"type":"ask"}\n' }); + await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line.includes('"q1"')), "the ask request"); + const request = server.up.find((m) => m.type === "stdout" && m.line.includes('"q1"')).line; + assert.deepEqual(server.hellos[0].channels, []); + server.downlink.close(); + await waitFor(() => server.hellos.length === 2, "the relink"); + assert.deepEqual(server.hellos[1].channels, [{ ch: "c1", sessionId: null, pending: [request] }]); + } finally { + await daemon.stop(); + log.restore(); + } +}); + test("spawn reports a fallback when a new session's cwd is missing on this host", async () => { const log = captureLog(); const server = scriptedServer(); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 2fce1d1fb..7c93289fc 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -31,6 +31,7 @@ import { type UpMessage, } from "./link-protocol"; import { localHost, resolveSpawnCwdResult } from "./local-host"; +import { PendingRequests } from "./pending-requests"; import { sessionOps } from "./session-ops"; const FIRST_RETRY_MS = 1_000; @@ -46,6 +47,8 @@ interface Channel { sessionId: string | null; /** Bytes of this child's output waiting for an uplink ack. */ buffered: number; + /** Open blocking requests, replayed in the next hello. */ + pending: PendingRequests; } interface Queued { @@ -328,9 +331,12 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: // Resent after a reconnect but already applied. if (!down.applied(message.seq)) return; switch (message.type) { - case "stdin": - channels.get(message.ch)?.transport.write(message.line, () => {}); + case "stdin": { + const channel = channels.get(message.ch); + channel?.pending.noteStdin(message.line); + channel?.transport.write(message.line, () => {}); return; + } case "kill": channels.get(message.ch)?.transport.killTree(message.force); return; @@ -454,8 +460,12 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: transport.killTree(true); throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); } - channels.set(ch, { transport, sessionId: file ? readSessionHeaderSync(file)?.id ?? null : null, buffered: 0 }); - transport.onLine((line) => output(ch, { type: "stdout", ch, line })); + const pending = new PendingRequests(LINK_LIMITS.pendingBytes); + channels.set(ch, { transport, sessionId: file ? readSessionHeaderSync(file)?.id ?? null : null, buffered: 0, pending }); + transport.onLine((line) => { + pending.noteStdout(line); + output(ch, { type: "stdout", ch, line }); + }); transport.onStderr((chunk) => output(ch, { type: "stderr", ch, chunk })); transport.onExit((code, signal) => { channels.delete(ch); @@ -475,15 +485,24 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: watchdog = setTimeout(() => abort.abort(new Error("no traffic from the server")), LINK_LIMITS.offlineMs); }; try { - const hello = encodeLine({ + const ompVersion = await getOmpVersion(); + const encodeHello = (replay: boolean) => encodeLine({ type: "hello", v: LINK_PROTOCOL_VERSION, - ompVersion: await getOmpVersion(), + ompVersion, platform: process.platform, home: homedir(), ack: down.acked, - channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.sessionId })), + channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.sessionId, pending: replay ? channel.pending.lines() : null })), }); + let hello: string; + try { + hello = encodeHello(true); + } catch (error) { + if (!(error instanceof LinkLimitError)) throw error; + // Too many channels near the pending cap for one line: none replays (all take the kill-and-resume path) rather than never relinking. + hello = encodeHello(false); + } alive(); const signal = AbortSignal.any([stopSignal.signal, abort.signal]); // The hello goes in a POST body: as a GET header, proxy header buffers (nginx: 8 KB) capped the channels it lists. diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index fd4a23922..24f3533a4 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -171,7 +171,7 @@ test("a version mismatch gets 426 with both versions and marks the host needs-up test("the hello rides a POST body, so a hello listing hundreds of channels links", async () => { const { token } = createHost("Busy box"); // Far past an 8 KB proxy header buffer (the hello used to ride a GET header). - const channels = Array.from({ length: 300 }, (_, i) => ({ ch: `ch-${String(i).padStart(4, "0")}`, sessionId: null })); + const channels = Array.from({ length: 300 }, (_, i) => ({ ch: `ch-${String(i).padStart(4, "0")}`, sessionId: null, pending: [] })); assert.ok(JSON.stringify(channels).length > 8 * 1024); const offered = await linkHello(token, hello({ channels })); assert.equal(offered.status, 200); @@ -405,9 +405,9 @@ test("no uplink traffic for offlineMs marks the host offline and notifies", asyn test("onHostHello reports the channels a daemon still runs", async () => { const seen = []; const unsubscribe = hub.onHostHello((hostId, channels) => seen.push({ hostId, channels })); - const { id, down } = await linkedHost("Reattach", { channels: [{ ch: "c1", sessionId: "s1" }] }); + const { id, down } = await linkedHost("Reattach", { channels: [{ ch: "c1", sessionId: "s1", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }); unsubscribe(); - assert.deepEqual(seen, [{ hostId: id, channels: [{ ch: "c1", sessionId: "s1" }] }]); + assert.deepEqual(seen, [{ hostId: id, channels: [{ ch: "c1", sessionId: "s1", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }]); await down.cancel(); }); @@ -435,7 +435,7 @@ test("on hello a spawned child the daemon no longer lists exits as lost; a spawn test("orphanExit rejects with 503 when the host goes offline before the orphan exits", async () => { hub.linkTimings.offlineMs = 40; const sessionId = "11111111-2222-4333-8444-999999999999"; - const link = await linkedHost("Dozing", { channels: [{ ch: "old", sessionId }] }); + const link = await linkedHost("Dozing", { channels: [{ ch: "old", sessionId, pending: [] }] }); // No uplink follows the hello: the host goes offline with the orphan still listed. await assert.rejects(hub.orphanExit(link.id, sessionId), (error) => { assert.equal(error.status, 503); @@ -448,7 +448,7 @@ test("orphanExit rejects with 503 when the host goes offline before the orphan e test("on hello a listed child with no transport is an orphan: killed, and orphanExit waits for it", async () => { const sessionId = "11111111-2222-4333-8444-555555555555"; - const link = await linkedHost("Survivor", { channels: [{ ch: "old", sessionId }] }); + const link = await linkedHost("Survivor", { channels: [{ ch: "old", sessionId, pending: [] }] }); assert.deepEqual(await link.down.nextReal(), { type: "kill", seq: 1, ch: "old", force: false }); let gone = false; const waiting = hub.orphanExit(link.id, sessionId).then(() => { @@ -468,7 +468,7 @@ for (const [op, call, value] of [ ]) { test(`${op} waits for the session's orphan to exit; another session is not delayed`, async () => { const sessionId = "11111111-2222-4333-8444-666666666666"; - const link = await linkedHost(`Waiter ${op}`, { channels: [{ ch: "old", sessionId }] }); + const link = await linkedHost(`Waiter ${op}`, { channels: [{ ch: "old", sessionId, pending: [] }] }); assert.equal((await link.down.nextReal()).type, "kill"); const ops = link.remote.sessionOps; let seq = 0; diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 4033e679a..d615f3a8c 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -25,6 +25,7 @@ import { SeqWindow, SESSION_OP_PARAMS, type DownMessage, + type HelloChannel, type HostOpName, type UpMessage, } from "./link-protocol"; @@ -39,7 +40,6 @@ export const linkTimings = { opTimeoutMs: LINK_LIMITS.opTimeoutMs, }; -type HelloChannel = { ch: string; sessionId: string | null }; type Hello = Extract; type Res = Extract; /** A sequenced downlink message before the link numbers it. */ diff --git a/lib/hosts/link-protocol.test.mjs b/lib/hosts/link-protocol.test.mjs index 03688bf20..b395f6794 100644 --- a/lib/hosts/link-protocol.test.mjs +++ b/lib/hosts/link-protocol.test.mjs @@ -26,8 +26,8 @@ const UP = [ home: "/Users/me", ack: 3, channels: [ - { ch: "c1", sessionId: "s1" }, - { ch: "c2", sessionId: null }, + { ch: "c1", sessionId: "s1", pending: ['{"type":"host_tool_call","id":"t1"}'] }, + { ch: "c2", sessionId: null, pending: null }, ], }, { type: "stdout", seq: 1, ch: "c1", line: '{"type":"message_end"}' }, @@ -109,6 +109,8 @@ test("decode rejects malformed lines with LinkProtocolError", async () => { '{"type":"exit","seq":1,"ch":"c","code":"0","signal":null}', '{"type":"res","seq":1,"id":"a"}', '{"type":"res","seq":1,"id":"a","ok":false,"error":{"code":"x","message":"y"}}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"pending":[1]}]}', ]; for (const line of bad) { assert.throws(() => decodeUp(line), LinkProtocolError, line); diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 695226f6e..9c8faa803 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -2,8 +2,9 @@ // Pure: no I/O and no Next or `@/` imports, so both sides share it. import type { SessionOps } from "./session-ops"; -/** 2: the hello moved from a GET header into a POST body (a v1 daemon gets 426). */ -export const LINK_PROTOCOL_VERSION = 2; +/** 2: the hello moved from a GET header into a POST body (a v1 daemon gets 426). + * 3: hello channels carry `pending`, the raw lines of their open blocking requests. */ +export const LINK_PROTOCOL_VERSION = 3; export const LINK_LIMITS = { pingMs: 15_000, @@ -19,6 +20,8 @@ export const LINK_LIMITS = { inlineResultBytes: 1024 * 1024, opTimeoutMs: 30_000, maxLineBytes: 8 * 1024 * 1024, + /** Per channel: open blocking requests past this are not replayed (the channel is not adoptable). */ + pendingBytes: 1024 * 1024, }; /** A POST carrying this header (value `1`) is the daemon's `hello`, in its body; @@ -79,6 +82,9 @@ export type DownMessage = | { type: "ping" } | { type: "pong" }; +/** `pending`: raw stdout lines of the child's open blocking requests, or null when over `pendingBytes`. */ +export type HelloChannel = { ch: string; sessionId: string | null; pending: string[] | null }; + export type UpMessage = | { type: "hello"; @@ -87,7 +93,7 @@ export type UpMessage = platform: string; home: string; ack: number; - channels: { ch: string; sessionId: string | null }[]; + channels: HelloChannel[]; } | { type: "stdout"; seq: number; ch: string; line: string } | { type: "stderr"; seq: number; ch: string; chunk: string } @@ -154,6 +160,12 @@ function nullable(o: Obj, key: string, read: (o: Obj, key: string) => T): T | return o[key] === null ? null : read(o, key); } +function strings(o: Obj, key: string): string[] { + const v = o[key]; + if (!Array.isArray(v) || !v.every((s) => typeof s === "string")) fail(`${key} must be an array of strings`); + return v; +} + function isHostOp(name: string): name is HostOpName { return (HOST_OP_NAMES as readonly string[]).includes(name); } @@ -198,12 +210,12 @@ export function decodeDown(line: string): DownMessage { } } -function channels(o: Obj): { ch: string; sessionId: string | null }[] { +function channels(o: Obj): HelloChannel[] { const list = o.channels; if (!Array.isArray(list)) fail("channels must be an array"); return list.map((c: unknown) => { if (!isObj(c)) fail("channel must be an object"); - return { ch: str(c, "ch"), sessionId: nullable(c, "sessionId", str) }; + return { ch: str(c, "ch"), sessionId: nullable(c, "sessionId", str), pending: nullable(c, "pending", strings) }; }); } diff --git a/lib/hosts/pending-requests.test.mjs b/lib/hosts/pending-requests.test.mjs new file mode 100644 index 000000000..fcb4193f6 --- /dev/null +++ b/lib/hosts/pending-requests.test.mjs @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import { randomBytes } from "node:crypto"; +import test from "node:test"; +import { createJiti } from "jiti"; + +const jiti = createJiti(import.meta.url); +const { PendingRequests } = await jiti.import("./pending-requests.ts"); + +const line = (frame) => JSON.stringify(frame); +const LIMIT = 1024 * 1024; + +test("an ask request answered on stdin is no longer open", () => { + const pending = new PendingRequests(LIMIT); + pending.noteStdout(line({ type: "extension_ui_request", id: "q1", method: "ask", questions: [] })); + assert.equal(pending.lines().length, 1); + pending.noteStdin(line({ type: "extension_ui_response", id: "q1", answers: [] })); + assert.deepEqual(pending.lines(), []); +}); + +test("an open host_tool_call keeps its raw line until host_tool_cancel names it", () => { + const pending = new PendingRequests(LIMIT); + const call = line({ type: "host_tool_call", id: "t1", toolCallId: "c1", toolName: "browser", arguments: {} }); + pending.noteStdout(line({ type: "message_update", text: "unrelated" })); + pending.noteStdout(call); + assert.deepEqual(pending.lines(), [call]); + pending.noteStdout(line({ type: "host_tool_cancel", id: "x9", targetId: "t1" })); + assert.deepEqual(pending.lines(), []); +}); + +test("host_tool_result on stdin closes the call; omp's UI cancel closes a dialog", () => { + const pending = new PendingRequests(LIMIT); + pending.noteStdout(line({ type: "host_tool_call", id: "t1", toolCallId: "c1", toolName: "browser", arguments: {} })); + const confirm = line({ type: "extension_ui_request", id: "d1", method: "confirm", title: "t", message: "m" }); + pending.noteStdout(confirm); + pending.noteStdin(`${line({ type: "host_tool_result", id: "t1", result: { content: [] } })}\n`); + assert.deepEqual(pending.lines(), [confirm]); + pending.noteStdout(line({ type: "extension_ui_request", id: "x1", method: "cancel", targetId: "d1" })); + assert.deepEqual(pending.lines(), []); +}); + +test("a chunked request keeps all of its rpc_chunk lines in order", () => { + // RpcFrameDecoder only accepts chunked frames of at least 1 MiB in 256 KiB pieces: five lines here. + const frame = Buffer.from(line({ type: "extension_ui_request", id: "big", method: "editor", title: "t", prefill: randomBytes(600_000).toString("hex") })); + const size = 256 * 1024; + const count = Math.ceil(frame.byteLength / size); + const chunks = Array.from({ length: count }, (_, index) => line({ + type: "rpc_chunk", chunkId: "k1", index, count, byteLength: frame.byteLength, + data: frame.subarray(index * size, (index + 1) * size).toString("base64"), + })); + const pending = new PendingRequests(4 * LIMIT); + for (const chunk of chunks) pending.noteStdout(chunk); + assert.deepEqual(pending.lines(), chunks); + pending.noteStdin(line({ type: "extension_ui_response", id: "big", cancelled: true })); + assert.deepEqual(pending.lines(), []); +}); + +test("past limitBytes lines() is null until the oversized request closes", () => { + const pending = new PendingRequests(1000); + pending.noteStdout(line({ type: "extension_ui_request", id: "small", method: "input", title: "t" })); + pending.noteStdout(line({ type: "extension_ui_request", id: "big", method: "input", title: "x".repeat(2000) })); + assert.equal(pending.lines(), null); + pending.noteStdin(line({ type: "extension_ui_response", id: "big", value: "v" })); + assert.equal(pending.lines().length, 1); +}); + +test("non-blocking UI requests and garbage lines are not kept", () => { + const pending = new PendingRequests(LIMIT); + pending.noteStdout(line({ type: "extension_ui_request", id: "n1", method: "notify", message: "hi" })); + pending.noteStdout("not json host_tool_call"); + pending.noteStdout(line({ type: "rpc_chunk", chunkId: "bad" })); + assert.deepEqual(pending.lines(), []); +}); diff --git a/lib/hosts/pending-requests.ts b/lib/hosts/pending-requests.ts new file mode 100644 index 000000000..6a362278e --- /dev/null +++ b/lib/hosts/pending-requests.ts @@ -0,0 +1,97 @@ +// The blocking requests still open on one omp child, kept so the daemon's +// `hello` can replay them to a main server that missed them (omp has no +// command listing them, and they never time out). +import { BLOCKING_UI_METHODS } from "../notification-events"; +import { RpcFrameDecoder } from "../omp/rpc-frame"; +import { isRecord } from "../type-guards"; + +// A line without one of these types cannot matter: skips JSON-parsing streamed output. +const STDOUT_TYPES = /"(?:rpc_chunk|host_tool_call|host_tool_cancel|extension_ui_request)"/; +const STDIN_TYPES = /"(?:host_tool_result|extension_ui_response)"/; + +/** Raw lines, or null once they no longer fit under the cap. */ +type Kept = string[] | null; + +export class PendingRequests { + private decoder = new RpcFrameDecoder(); + private readonly open = new Map(); + /** The raw `rpc_chunk` lines of the frame being reassembled. */ + private chunk: Kept | undefined; + private bytes = 0; + + constructor(private readonly limitBytes: number) {} + + noteStdout(line: string): void { + if (this.chunk === undefined && !STDOUT_TYPES.test(line)) return; + let frame; + try { + frame = this.decoder.push(JSON.parse(line)); + } catch { + // Not JSON, or a broken chunk sequence: drop it and start clean. + this.decoder = new RpcFrameDecoder(); + this.free(this.chunk); + this.chunk = undefined; + return; + } + const kept = this.append(this.chunk ?? [], line); + if (!frame) { + this.chunk = kept; + return; + } + this.chunk = undefined; + const blocking = frame.type === "host_tool_call" + || (frame.type === "extension_ui_request" && typeof frame.method === "string" && BLOCKING_UI_METHODS.has(frame.method)); + if (blocking && typeof frame.id === "string") { + this.close(frame.id); + this.open.set(frame.id, kept); + return; + } + this.free(kept); + const cancel = frame.type === "host_tool_cancel" || (frame.type === "extension_ui_request" && frame.method === "cancel"); + if (cancel && typeof frame.targetId === "string") this.close(frame.targetId); + } + + noteStdin(line: string): void { + if (!STDIN_TYPES.test(line)) return; + let command: unknown; + try { + command = JSON.parse(line); + } catch { + return; + } + if (isRecord(command) && (command.type === "host_tool_result" || command.type === "extension_ui_response") && typeof command.id === "string") { + this.close(command.id); + } + } + + /** Raw lines of the open requests in order; null when they exceed the cap. */ + lines(): string[] | null { + const lines: string[] = []; + for (const kept of this.open.values()) { + if (!kept) return null; + lines.push(...kept); + } + return lines; + } + + private close(id: string): void { + this.free(this.open.get(id)); + this.open.delete(id); + } + + private append(kept: Kept, line: string): Kept { + if (!kept) return null; + const size = Buffer.byteLength(line); + if (this.bytes + size > this.limitBytes) { + this.free(kept); + return null; + } + this.bytes += size; + kept.push(line); + return kept; + } + + private free(kept: Kept | undefined): void { + if (kept) for (const line of kept) this.bytes -= Buffer.byteLength(line); + } +} diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 6cf6a2d64..521c39506 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -2985,7 +2985,7 @@ test("a command written before the host link dropped resolves once the link retu await until(() => hub.getHost(link.id).status() === "offline", "the host to go offline"); hub.linkTimings.offlineMs = timings.offlineMs; - await link.dial({ channels: [{ ch, sessionId: null }] }); + await link.dial({ channels: [{ ch, sessionId: null, pending: [] }] }); link.serve(ops, omp); await link.post({ type: "stdout", ch, line: respond(held) }); const state = await pending; @@ -3088,7 +3088,7 @@ test("a session the host still runs an orphan child for spawns only after the or const id = "11111111-2222-4333-8444-888888888888"; const sessionFile = `/remote/sessions/${id}.jsonl`; // This server restarted while the host kept running the session's child. - const link = await linkHost("Survivor box", { channels: [{ ch: "orphan", sessionId: id }] }); + const link = await linkHost("Survivor box", { channels: [{ ch: "orphan", sessionId: id, pending: [] }] }); let session; t.after(async () => { hub.closeHostLink(link.id); @@ -3143,7 +3143,7 @@ test("a prompt whose ack is lost to a quiet link answers host_offline and keeps // The lid opens: the daemon redials with the child still running. await link.drop(); - await link.dial({ channels: [{ ch: spawns[0].ch, sessionId: null }] }); + await link.dial({ channels: [{ ch: spawns[0].ch, sessionId: null, pending: [] }] }); link.serve(ops, omp); assert.equal((await session.send({ type: "get_state" })).sessionId, "s-lid"); assert.deepEqual(kills, [], "no kill was queued for the reconnect either"); diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index 44cc0dba1..dc15ad920 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -161,7 +161,7 @@ test("a remote entry resumes after its host's hello, exactly once", async (t) => // The orphan wait is startRpcSession's (rpc-manager.test.mjs); resume starts on hello. const link = new LinkDriver(host.id, token); - await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id }] }); + await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id, pending: [] }] }); await sleep(10); assert.deepEqual(resumed, [remote]); From b7bdc3b059f3c1c8ddd090c094afdd5b35786165 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 19:16:25 +0000 Subject: [PATCH 05/36] fix(hosts): an over-cap chunked request blocks replay; host URI requests are replayed too --- AGENTS.md | 2 +- lib/hosts/daemon.test.mjs | 9 +++++++- lib/hosts/pending-requests.test.mjs | 34 ++++++++++++++++++++++++----- lib/hosts/pending-requests.ts | 16 ++++++++------ 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e1ae4a8b0..4a17077d1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -269,7 +269,7 @@ bin/ `x-omp-web-hello`; main takes the hello at that GET, so it opens one downlink once. A v1 daemon's header hello gets 426. Each `hello.channels` entry carries `pending` (link v3): the raw stdout lines of that child's - still-open `host_tool_call`s and blocking `extension_ui_request`s + still-open `host_tool_call`s, `host_uri_request`s and blocking `extension_ui_request`s (`PendingRequests`), or null past `LINK_LIMITS.pendingBytes`. Each side keeps unacked lines, resends after a reconnect and drops any `seq` it already applied. Main decodes a whole POST before applying any of it. `hello.ack === 0` diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index b45cf52e3..260b1beba 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -423,7 +423,7 @@ test("5xx answers are retried and the omp children keep running", async () => { assert.equal(await daemon.done, 0); }); -test("after a link drop the next hello carries each channel's open blocking requests", async () => { +test("after a link drop the next hello carries each channel's open blocking requests; an answer closes them", async () => { const log = captureLog(); const server = scriptedServer(); const daemon = start(server); @@ -437,6 +437,13 @@ test("after a link drop the next hello carries each channel's open blocking requ server.downlink.close(); await waitFor(() => server.hellos.length === 2, "the relink"); assert.deepEqual(server.hellos[1].channels, [{ ch: "c1", sessionId: null, pending: [request] }]); + // The answer goes down to omp: the request is no longer open. The echo orders it before the drop. + server.send({ type: "stdin", ch: "c1", line: '{"type":"extension_ui_response","id":"q1","answers":[]}\n' }); + server.send({ type: "stdin", ch: "c1", line: '{"type":"echo"}\n' }); + await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line === '{"type":"echoed"}'), "the echo"); + server.downlink.close(); + await waitFor(() => server.hellos.length === 3, "the second relink"); + assert.deepEqual(server.hellos[2].channels, [{ ch: "c1", sessionId: null, pending: [] }]); } finally { await daemon.stop(); log.restore(); diff --git a/lib/hosts/pending-requests.test.mjs b/lib/hosts/pending-requests.test.mjs index fcb4193f6..5ff790240 100644 --- a/lib/hosts/pending-requests.test.mjs +++ b/lib/hosts/pending-requests.test.mjs @@ -38,15 +38,19 @@ test("host_tool_result on stdin closes the call; omp's UI cancel closes a dialog assert.deepEqual(pending.lines(), []); }); -test("a chunked request keeps all of its rpc_chunk lines in order", () => { - // RpcFrameDecoder only accepts chunked frames of at least 1 MiB in 256 KiB pieces: five lines here. - const frame = Buffer.from(line({ type: "extension_ui_request", id: "big", method: "editor", title: "t", prefill: randomBytes(600_000).toString("hex") })); +/** A blocking request omp would chunk: RpcFrameDecoder only accepts chunked frames of at least 1 MiB in 256 KiB pieces (five lines here). */ +function chunkedRequest(id) { + const frame = Buffer.from(line({ type: "extension_ui_request", id, method: "editor", title: "t", prefill: randomBytes(600_000).toString("hex") })); const size = 256 * 1024; const count = Math.ceil(frame.byteLength / size); - const chunks = Array.from({ length: count }, (_, index) => line({ - type: "rpc_chunk", chunkId: "k1", index, count, byteLength: frame.byteLength, + return Array.from({ length: count }, (_, index) => line({ + type: "rpc_chunk", chunkId: `k-${id}`, index, count, byteLength: frame.byteLength, data: frame.subarray(index * size, (index + 1) * size).toString("base64"), })); +} + +test("a chunked request keeps all of its rpc_chunk lines in order", () => { + const chunks = chunkedRequest("big"); const pending = new PendingRequests(4 * LIMIT); for (const chunk of chunks) pending.noteStdout(chunk); assert.deepEqual(pending.lines(), chunks); @@ -54,6 +58,26 @@ test("a chunked request keeps all of its rpc_chunk lines in order", () => { assert.deepEqual(pending.lines(), []); }); +test("a chunked request over the cap makes lines() null until it closes", () => { + const pending = new PendingRequests(LIMIT); + for (const chunk of chunkedRequest("big")) pending.noteStdout(chunk); + assert.equal(pending.lines(), null); + pending.noteStdin(line({ type: "extension_ui_response", id: "big", cancelled: true })); + assert.deepEqual(pending.lines(), []); +}); + +test("a host_uri_request stays open until host_uri_result or omp's host_uri_cancel", () => { + const pending = new PendingRequests(LIMIT); + const read = line({ type: "host_uri_request", id: "u1", operation: "read", url: "web://x" }); + pending.noteStdout(read); + pending.noteStdout(line({ type: "host_uri_request", id: "u2", operation: "write", url: "web://y", content: "c" })); + assert.equal(pending.lines().length, 2); + pending.noteStdout(line({ type: "host_uri_cancel", id: "x2", targetId: "u2" })); + assert.deepEqual(pending.lines(), [read]); + pending.noteStdin(line({ type: "host_uri_result", id: "u1", content: "body" })); + assert.deepEqual(pending.lines(), []); +}); + test("past limitBytes lines() is null until the oversized request closes", () => { const pending = new PendingRequests(1000); pending.noteStdout(line({ type: "extension_ui_request", id: "small", method: "input", title: "t" })); diff --git a/lib/hosts/pending-requests.ts b/lib/hosts/pending-requests.ts index 6a362278e..4b7b1dffa 100644 --- a/lib/hosts/pending-requests.ts +++ b/lib/hosts/pending-requests.ts @@ -6,8 +6,8 @@ import { RpcFrameDecoder } from "../omp/rpc-frame"; import { isRecord } from "../type-guards"; // A line without one of these types cannot matter: skips JSON-parsing streamed output. -const STDOUT_TYPES = /"(?:rpc_chunk|host_tool_call|host_tool_cancel|extension_ui_request)"/; -const STDIN_TYPES = /"(?:host_tool_result|extension_ui_response)"/; +const STDOUT_TYPES = /"(?:rpc_chunk|host_tool_call|host_tool_cancel|host_uri_request|host_uri_cancel|extension_ui_request)"/; +const STDIN_TYPES = /"(?:host_tool_result|host_uri_result|extension_ui_response)"/; /** Raw lines, or null once they no longer fit under the cap. */ type Kept = string[] | null; @@ -15,7 +15,7 @@ type Kept = string[] | null; export class PendingRequests { private decoder = new RpcFrameDecoder(); private readonly open = new Map(); - /** The raw `rpc_chunk` lines of the frame being reassembled. */ + /** The raw `rpc_chunk` lines of the frame being reassembled (null: over the cap); undefined between frames. */ private chunk: Kept | undefined; private bytes = 0; @@ -33,13 +33,13 @@ export class PendingRequests { this.chunk = undefined; return; } - const kept = this.append(this.chunk ?? [], line); + const kept = this.append(this.chunk === undefined ? [] : this.chunk, line); if (!frame) { this.chunk = kept; return; } this.chunk = undefined; - const blocking = frame.type === "host_tool_call" + const blocking = frame.type === "host_tool_call" || frame.type === "host_uri_request" || (frame.type === "extension_ui_request" && typeof frame.method === "string" && BLOCKING_UI_METHODS.has(frame.method)); if (blocking && typeof frame.id === "string") { this.close(frame.id); @@ -47,7 +47,8 @@ export class PendingRequests { return; } this.free(kept); - const cancel = frame.type === "host_tool_cancel" || (frame.type === "extension_ui_request" && frame.method === "cancel"); + const cancel = frame.type === "host_tool_cancel" || frame.type === "host_uri_cancel" + || (frame.type === "extension_ui_request" && frame.method === "cancel"); if (cancel && typeof frame.targetId === "string") this.close(frame.targetId); } @@ -59,7 +60,8 @@ export class PendingRequests { } catch { return; } - if (isRecord(command) && (command.type === "host_tool_result" || command.type === "extension_ui_response") && typeof command.id === "string") { + if (!isRecord(command) || typeof command.id !== "string") return; + if (command.type === "host_tool_result" || command.type === "host_uri_result" || command.type === "extension_ui_response") { this.close(command.id); } } From ee3eddc7a410554092579409e6f8d375b9ea8235 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 19:33:37 +0000 Subject: [PATCH 06/36] feat(rpc): adopt a live omp child into a session wrapper --- lib/omp/rpc-process-runtime.test.mjs | 54 ++++++++++ lib/omp/rpc-process.ts | 146 +++++++++++++++++---------- lib/rpc-manager.test.mjs | 113 +++++++++++++++++++++ lib/rpc-manager.ts | 94 +++++++++++++++-- 4 files changed, 343 insertions(+), 64 deletions(-) diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 9e0690111..44add01b0 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -285,3 +285,57 @@ test("a host resync mid chunk sequence drops the partial frame and skips the tai assert.equal(proc.isAlive, true); await proc.dispose(0); }); + +/** A child that was already running: it sends no `ready`, and `held` lines reach the first reader at once, as RemoteRpcTransport delivers them. */ +function makeAdoptedTransport(held) { + const readers = []; + const transport = { + endInputCalls: 0, + answer: () => {}, + write(line, callback) { + callback(null); + queueMicrotask(() => transport.answer(JSON.parse(line))); + }, + onLine(listener) { + readers.push(listener); + for (const line of held) listener(line); + }, + onStderr() {}, + onExit(listener) { transport.exit = listener; }, + endInput() { + transport.endInputCalls += 1; + queueMicrotask(() => transport.exit?.(0, null)); + }, + killTree() {}, + send(record) { for (const reader of readers) reader(JSON.stringify(record)); }, + }; + return transport; +} + +test("an adopted RpcProcess needs no ready, skips a chunk tail, and holds live frames until the replay", async () => { + const big = (type, id) => ({ type, id, content: "x".repeat(1024 * 1024) }); + // The web server restarted mid chunk sequence: its tail must not be a protocol error. + const tail = chunkRecords(big("message_update", "lost"), "before-restart").slice(2); + const transport = makeAdoptedTransport([...tail, { type: "agent_start" }].map((record) => JSON.stringify(record))); + const proc = new RpcProcess({ cwd: process.cwd(), transport, adopted: { protocolVersion: 2 } }); + transport.answer = (command) => transport.send({ type: "response", id: command.id, command: command.type, success: true, data: { protocolVersion: 2 } }); + assert.equal(await proc.negotiateProtocol(await proc.waitReady(1), 1_000), 2); + + const frames = []; + proc.onFrame((frame) => frames.push(frame.id ?? frame.type)); + const live = chunkRecords(big("message_update", "live"), "live"); + for (const record of live.slice(0, 2)) transport.send(record); + assert.deepEqual(frames, [], "live frames wait for the replay"); + + // The daemon's lines are older than anything live, and a half-read live sequence does not disturb them. + proc.replay([ + JSON.stringify({ type: "extension_ui_request", id: "q1", method: "ask" }), + ...chunkRecords(big("host_tool_call", "h1"), "pending").map((record) => JSON.stringify(record)), + ]); + assert.deepEqual(frames, ["q1", "h1", "agent_start"]); + for (const record of live.slice(2)) transport.send(record); + assert.deepEqual(frames, ["q1", "h1", "agent_start", "live"]); + assert.equal(transport.endInputCalls, 0, "no protocol error disposed the child"); + assert.equal(proc.isAlive, true); + await proc.dispose(0); +}); diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index 1a53a4596..b59c236db 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -4,6 +4,7 @@ import { isRecord } from "../type-guards"; import { resolveOmpBin } from "./omp-cli"; import { type RpcTransport, spawnLocalRpcTransport } from "./rpc-transport"; import { encodeRpcCommand, RpcFrameDecoder, type RpcFrameRecord, type RpcProtocolVersion } from "./rpc-frame"; +import { LINK_LIMITS } from "../hosts/link-protocol"; /** * Process + protocol layer for `omp --mode rpc-ui` (NDJSON over stdio). @@ -74,6 +75,10 @@ export interface RpcProcessOptions { onExit?: (info: { code: number | null; signal: NodeJS.Signals | null; stderrTail: string }) => void; /** Byte transport to run over. Omitted → spawn the installed omp (see spawnLocalRpcTransport). */ transport?: RpcTransport; + /** A child that outlived the server that spawned it (see adoptRpcSession): no + * ready wait, the decoder starts at this version and drops `rpc_chunk` + * records until a frame starts, and frames are held until `replay`. */ + adopted?: { protocolVersion: 2 }; /** Injectable process boundary for deterministic transport tests. */ dependencies?: { resolveOmpBin?: typeof resolveOmpBin; @@ -83,6 +88,17 @@ export interface RpcProcessOptions { const STDERR_TAIL_LIMIT = 8 * 1024; +/** A stdout line as JSON; undefined when blank or not JSON (omp guards stdout in RPC mode, but never let a stray line kill the reader). */ +function parseLine(line: string): unknown { + const trimmed = line.trim(); + if (!trimmed) return undefined; + try { + return JSON.parse(trimmed); + } catch { + return undefined; + } +} + /** Spawns the installed omp in RPC mode with the sanitized child environment. */ export function spawnOmpTransport(options: RpcProcessOptions): RpcTransport { const resolveBin = options.dependencies?.resolveOmpBin ?? resolveOmpBin; @@ -108,6 +124,9 @@ export class RpcProcess { private readonly pending = new Map(); private readonly frameListeners = new Set<(frame: RpcFrame) => void>(); private readyPromise: Promise; + private readonly resolveReady: (frame: RpcFrame) => void; + /** An adopted child's frames, held until `replay` (see RpcProcessOptions.adopted). */ + private heldFrames: RpcFrame[] | null = null; private nextId = 1; private stderrTail = ""; private exited = false; @@ -122,66 +141,35 @@ export class RpcProcess { this.cwd = options.cwd; if (options.onFrame) this.frameListeners.add(options.onFrame); - let resolveReady: (frame: RpcFrame) => void; - let rejectReady: (error: Error) => void; - this.readyPromise = new Promise((resolve, reject) => { - resolveReady = resolve; - rejectReady = reject; - }); + const ready = Promise.withResolvers(); + this.readyPromise = ready.promise; + this.resolveReady = ready.resolve; // waitReady() is optional for callers; avoid unhandled-rejection noise when // the process dies before anyone awaited readiness. this.readyPromise.catch(() => {}); const exitDeferred = Promise.withResolvers(); this.exitedPromise = exitDeferred.promise; + if (options.adopted) { + // It announced readiness and negotiated this version with the server that spawned it. + this.protocolVersion = options.adopted.protocolVersion; + this.heldFrames = []; + ready.resolve({ type: "ready", supportedProtocolVersions: [options.adopted.protocolVersion] }); + } let decoder = new RpcFrameDecoder(); - // A linked host dropped lines (resync): the half-read sequence is gone, and the next lines may be another's tail. - let midSequence = false; + // An adopted child's output can resume mid chunk sequence, and a linked host's resync drops lines + // (the half-read sequence is gone): skip to the next frame's start. + let midSequence = options.adopted !== undefined; this.transport.onResync?.(() => { decoder = new RpcFrameDecoder(); midSequence = true; }); this.transport.onLine((line) => { - const trimmed = line.trim(); - if (!trimmed) return; - let parsed: unknown; - try { - parsed = JSON.parse(trimmed); - } catch { - // omp guards stdout in RPC mode, but never let a stray line kill the reader. - return; - } + const parsed = parseLine(line); + if (parsed === undefined) return; if (midSequence && isRecord(parsed) && parsed.type === "rpc_chunk" && parsed.index !== 0) return; midSequence = false; - let frame: RpcFrameRecord; - try { - if (parsed && typeof parsed === "object" && (parsed as { type?: unknown }).type === "rpc_chunk" && this.protocolVersion !== 2) { - throw new Error("RPC chunk received before protocol negotiation"); - } - const decoded = decoder.push(parsed); - if (!decoded) return; - frame = decoded; - } catch (error) { - this.stderrTail = (this.stderrTail + `\nRPC protocol error: ${error instanceof Error ? error.message : String(error)}`).slice(-STDERR_TAIL_LIMIT); - console.warn("[omp-web] rpc-protocol-dispose", JSON.stringify({ transport: this.transport.id, protocolVersion: this.protocolVersion, errorType: error instanceof Error ? error.name : typeof error, at: new Date().toISOString() })); - void this.dispose(0); - return; - } - if (frame.type === "ready") { - resolveReady(frame); - return; - } - if (frame.type === "response") { - this.handleResponse(frame as unknown as RpcResponseFrame); - return; - } - for (const listener of this.frameListeners) { - try { - listener(frame); - } catch { - // Listener bugs must not break the protocol reader. - } - } + this.receive(parsed, decoder); }); this.transport.onStderr((chunk) => { @@ -195,7 +183,7 @@ export class RpcProcess { const exitError = new Error( `omp exited (code ${code ?? "null"}, signal ${signal ?? "none"})${this.stderrTail ? `: ${this.stderrTail.slice(-500)}` : ""}`, ); - rejectReady(exitError); + ready.reject(exitError); for (const [, entry] of this.pending) { if (entry.timer) clearTimeout(entry.timer); entry.reject(exitError); @@ -226,10 +214,10 @@ export class RpcProcess { } /** Enables bounded protocol-v2 framing when the ready frame advertises it. */ - async negotiateProtocol(ready: RpcFrame): Promise { + async negotiateProtocol(ready: RpcFrame, timeoutMs?: number): Promise { const supported = Array.isArray(ready.supportedProtocolVersions) ? ready.supportedProtocolVersions : []; if (!supported.includes(2)) return this.protocolVersion; - const response = await this.sendCommand<{ protocolVersion?: unknown }>({ type: "negotiate_protocol", protocolVersion: 2 }); + const response = await this.sendCommand<{ protocolVersion?: unknown }>({ type: "negotiate_protocol", protocolVersion: 2 }, timeoutMs); if (response?.protocolVersion !== 2) throw new Error("OMP rejected RPC protocol v2 negotiation"); this.protocolVersion = 2; return this.protocolVersion; @@ -240,6 +228,60 @@ export class RpcProcess { return () => this.frameListeners.delete(listener); } + /** Adopted child: feeds the daemon's raw lines of its still-open requests as + * if just read (they are older than anything live), then the frames held since. */ + replay(lines: string[]): void { + const held = this.heldFrames ?? []; + this.heldFrames = null; + // Its own decoder: a live chunk sequence may be half-read. + const decoder = new RpcFrameDecoder(); + for (const line of lines) { + const parsed = parseLine(line); + if (parsed !== undefined) this.receive(parsed, decoder); + } + for (const frame of held) this.dispatch(frame); + } + + private receive(parsed: unknown, decoder: RpcFrameDecoder): void { + let frame: RpcFrameRecord; + try { + if (isRecord(parsed) && parsed.type === "rpc_chunk" && this.protocolVersion !== 2) { + throw new Error("RPC chunk received before protocol negotiation"); + } + const decoded = decoder.push(parsed); + if (!decoded) return; + frame = decoded; + } catch (error) { + this.stderrTail = (this.stderrTail + `\nRPC protocol error: ${error instanceof Error ? error.message : String(error)}`).slice(-STDERR_TAIL_LIMIT); + console.warn("[omp-web] rpc-protocol-dispose", JSON.stringify({ transport: this.transport.id, protocolVersion: this.protocolVersion, errorType: error instanceof Error ? error.name : typeof error, at: new Date().toISOString() })); + void this.dispose(0); + return; + } + if (frame.type === "ready") { + this.resolveReady(frame); + return; + } + if (frame.type === "response") { + this.handleResponse(frame as unknown as RpcResponseFrame); + return; + } + this.dispatch(frame); + } + + private dispatch(frame: RpcFrame): void { + if (this.heldFrames) { + this.heldFrames.push(frame); + return; + } + for (const listener of this.frameListeners) { + try { + listener(frame); + } catch { + // Listener bugs must not break the protocol reader. + } + } + } + /** Send a command and await its response `data`. A failed response rejects * with RpcCommandError. No timeout by default — some commands (login, * long prompts via bash) legitimately take minutes, and the session wrapper @@ -323,11 +365,7 @@ export class RpcProcess { if (!entry || !id) { // Unsolicited response (or a command we already timed out) — surface to // frame listeners so nothing is silently dropped. - for (const listener of this.frameListeners) { - try { - listener(response as unknown as RpcFrame); - } catch {} - } + this.dispatch(response as unknown as RpcFrame); return; } this.pending.delete(id); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 521c39506..df7b0cbb4 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -3442,3 +3442,116 @@ test("a resume that failed while its host went offline blocks a retry until its assert.equal(spawns, 2); assert.equal(retried.session.isAlive(), true); }); + +/** + * An omp child a previous run of this server spawned: already past `ready`, so + * it never sends one. It answers every command except `silent` ones; get_state + * reports `sessionId` plus `state`. `held` lines reach the first reader at once. + */ +function adoptedTransport(sessionId, { state = {}, held = [], silent = [] } = {}) { + const transport = { + sent: [], + kills: 0, + write(line, callback) { + const command = JSON.parse(line); + transport.sent.push(command.type); + callback(null); + // Replies to dialogs and host calls are frames, not commands: nothing answers them. + if (silent.includes(command.type) || command.type.endsWith("_result") || command.type === "extension_ui_response") return; + const data = command.type === "negotiate_protocol" ? { protocolVersion: 2 } + : command.type === "get_state" ? { sessionId, sessionFile: `/nonexistent/${sessionId}.jsonl`, isStreaming: false, isCompacting: false, ...state } + : {}; + queueMicrotask(() => transport.emit(JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }))); + }, + onLine(listener) { + transport.emit = listener; + for (const line of held) listener(line); + }, + onStderr() {}, + onExit(listener) { transport.exit = listener; }, + endInput() { + transport.kills += 1; + queueMicrotask(() => transport.exit?.(0, null)); + }, + killTree() { + transport.kills += 1; + queueMicrotask(() => transport.exit?.(null, "SIGTERM")); + }, + }; + return transport; +} + +function adoptionHost(id, transport) { + const host = scriptedHost(id, transport); + host.spawnRpc = async () => { + throw new Error("adoption must not spawn"); + }; + return host; +} + +test("adoptRpcSession re-syncs a live child with no spawn and no ready wait", async (t) => { + const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad01"; + const sessionFile = `/nonexistent/${id}.jsonl`; + // This server restarted mid chunk sequence: the tail is dropped, not a protocol error. + const bytes = Buffer.from(JSON.stringify({ type: "message_update", text: "x".repeat(1024 * 1024) })); + const tail = { type: "rpc_chunk", chunkId: "lost", index: 3, count: 5, byteLength: bytes.byteLength, data: bytes.subarray(3 * 262144, 4 * 262144).toString("base64") }; + const transport = adoptedTransport(id, { state: { isStreaming: true }, held: [JSON.stringify(tail)] }); + const session = await adoptRpcSession({ host: adoptionHost("adopt-box", transport), transport, sessionId: id, sessionFile, cwd: "/w", replay: [] }); + t.after(() => session.destroyAndWait()); + + assert.deepEqual(transport.sent, ["negotiate_protocol", "set_subagent_subscription", "set_ask_dialog", "get_state", "get_subagents", "get_btw_history"]); + assert.equal(session.isRunning(), true, "omp reported a run in progress"); + assert.equal(session.sessionFile, sessionFile); + assert.equal(getRpcSession(id), session); + assert.equal(transport.kills, 0); +}); + +test("an adopted child's open requests come back: an ask for the next tab, a host tool call for an open tab", async (t) => { + const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad02"; + const transport = adoptedTransport(id); + const calls = []; + const leave = subscribeHostToolCalls((call) => calls.push(call)); + const ask = { type: "extension_ui_request", id: "q1", method: "ask", questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }; + const call = { type: "host_tool_call", id: "h1", toolName: "open_url", arguments: { url: "https://a.test" } }; + const session = await adoptRpcSession({ + host: adoptionHost("replay-box", transport), + transport, + sessionId: id, + sessionFile: `/nonexistent/${id}.jsonl`, + cwd: "/w", + replay: [JSON.stringify(ask), JSON.stringify(call)], + }); + t.after(async () => { + leave(); + await session.destroyAndWait(); + }); + + // Registered with the wrapper the restart lost: routed to the open tab, not rejected. + assert.deepEqual(calls, [{ sessionId: id, id: "h1", toolName: "open_url", arguments: { url: "https://a.test" } }]); + assert.equal(transport.sent.includes("host_tool_result"), false); + const events = []; + session.onEvent((event) => events.push(event)); + assert.deepEqual(events.map((event) => [event.type, event.id]), [["extension_ui_request", "q1"]]); + assert.equal(session.isRunning(), true, "the run waits on its user"); +}); + +test("an adoption whose get_state times out rejects and kills the child", async (t) => { + const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad03"; + const transport = adoptedTransport(id, { silent: ["get_state"] }); + const asked = Promise.withResolvers(); + const write = transport.write; + transport.write = (line, callback) => { + write(line, callback); + if (JSON.parse(line).type === "get_state") asked.resolve(); + }; + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); + const adopting = adoptRpcSession({ host: adoptionHost("wedged-adopt-box", transport), transport, sessionId: id, sessionFile: `/nonexistent/${id}.jsonl`, cwd: "/w", replay: [] }); + await asked.promise; + t.mock.timers.tick(5_000); + await assert.rejects(adopting, (error) => error.name === "RpcCommandTimeoutError" && error.command === "get_state"); + assert.ok(transport.kills > 0, "the child is killed"); + assert.equal(getRpcSession(id), undefined); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 7ef254434..a94699b74 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -4,6 +4,7 @@ import { validateAgentImages } from "./image-attachments"; import { hasVisibleAssistantContent } from "./assistant-response"; import { invalidateModelsCache } from "./models-cache"; import { RpcCommandError, RpcCommandTimeoutError, RpcProcess, type RpcFrame } from "./omp/rpc-process"; +import type { RpcTransport } from "./omp/rpc-transport"; import { editSessionHistory, isSessionEditReply, SESSION_EDIT_COMMAND, SessionEditAgentInvocationError, type SessionEditResult } from "./omp/session-edit"; import { cacheSessionPath, invalidateSessionListCache } from "./session-reader"; import { allowFileRoot } from "./file-access"; @@ -294,6 +295,8 @@ export class AgentSessionWrapper { private _alive = true; /** Host tools the web UI registered via set_host_tools (agent-callable). */ private hostToolNames: Set = new Set(); + /** Feeding an adopted child's open requests (see adopt): its host tools were registered through the wrapper a restart lost. */ + private replaying = false; /** host_tool_call ids awaiting a host_tool_result from the browser. */ private pendingHostTools: Map = new Map(); /** URI schemes the web UI registered via set_host_uri_schemes. */ @@ -577,6 +580,34 @@ export class AgentSessionWrapper { } } + /** + * Re-sync a child that outlived the server that spawned it (adoptRpcSession): + * the startup handshake minus the ready wait, every command bounded so a + * wedged child fails the adoption, then the daemon's lines of its open requests. + */ + async adopt(replay: string[]): Promise { + this.handshaking = true; + // Older omp rejects some of these, as at startup; a timeout or an exit fails the adoption. + const optional = (command: { type: string; [key: string]: unknown }) => this.proc.sendCommand(command, GET_STATE_TIMEOUT_MS).then(() => {}, (error) => { + if (!(error instanceof RpcCommandError)) throw error; + }); + try { + await this.proc.negotiateProtocol(await this.proc.waitReady(), GET_STATE_TIMEOUT_MS); + await optional({ type: "set_subagent_subscription", level: "events" }); + await optional({ type: "set_ask_dialog", enabled: true }); + this.applyIdentity(await this.getStateWithTimeout()); + // The wrapper keeps neither (a tab reads both when it attaches): a child that cannot answer them fails here instead. + await optional({ type: "get_subagents" }); + await optional({ type: "get_btw_history" }); + this.replaying = true; + this.proc.replay(replay); + this.replaying = false; + } finally { + this.handshaking = false; + this.noteActivity(); + } + } + private applyIdentity(state: RpcSessionState): void { const oldId = this._sessionId; const identityChanged = Boolean(oldId) && (state.sessionId !== oldId || (state.sessionFile && state.sessionFile !== this._sessionFile)); @@ -946,7 +977,7 @@ export class AgentSessionWrapper { // any open omp-web tab (the user switched sessions mid-run). Otherwise // reject immediately so the agent never hangs on a tool nobody will // answer. - if (id && toolName && this.hostToolNames.has(toolName)) { + if (id && toolName && (this.hostToolNames.has(toolName) || this.replaying)) { if (this.listeners.length > 0) { this.pendingHostTools.set(id, event); this.emit(event); @@ -2798,15 +2829,7 @@ export async function startRpcSession( } const realSessionId = created.sessionId; - created.onDestroy(() => { - // Drop every key (current id, original id, moved-from aliases). - for (const [key, wrapper] of registry) if (wrapper === created) registry.delete(key); - }); - created.onIdentityChange((oldId, newId, options) => { - if (!options?.keepOldId && registry.get(oldId) === created) registry.delete(oldId); - registry.set(newId, created); - }); - registry.set(realSessionId, created); + registerSession(created); // A successful respawn supersedes the crash record. clearExitedRpcSession(sessionId); if (realSessionId !== sessionId) clearExitedRpcSession(realSessionId); @@ -2816,3 +2839,54 @@ export async function startRpcSession( locks.set(sessionId, starting); return starting; } + +/** Key a ready wrapper under its real id and keep its keys current as omp moves or switches it. */ +function registerSession(created: AgentSessionWrapper): void { + const registry = getRegistry(); + created.onDestroy(() => { + // Drop every key (current id, original id, moved-from aliases). + for (const [key, wrapper] of registry) if (wrapper === created) registry.delete(key); + }); + created.onIdentityChange((oldId, newId, options) => { + if (!options?.keepOldId && registry.get(oldId) === created) registry.delete(oldId); + registry.set(newId, created); + }); + registry.set(created.sessionId, created); +} + +/** + * Take over an omp child that outlived the server that spawned it (its host + * listed it in `hello`): no spawn and no ready wait. `replay` holds the host's + * raw stdout lines of the child's still-open blocking requests. A failed + * re-sync kills the child and rejects. + */ +export async function adoptRpcSession({ host, transport, sessionId, cwd, replay }: { + host: Host; + transport: RpcTransport; + sessionId: string; + sessionFile: string; + cwd: string; + replay: string[]; +}): Promise { + const locks = getLocks(); + const holder: { wrapper?: AgentSessionWrapper } = {}; + const proc = new RpcProcess({ cwd, transport, adopted: { protocolVersion: 2 }, onExit: (info) => holder.wrapper?.handleProcessExit(info, proc) }); + // Spawn-time facts (--advisor, a cwd fallback) died with the server that spawned it. + const created = new AgentSessionWrapper(proc, cwd, cwd, false, sessionId, DISCONNECT_DESTROY_MS, host); + holder.wrapper = created; + created.start(); + const adopting = (async () => { + try { + await created.adopt(replay); + } catch (error) { + await created.destroyAndWait("adoption-failed"); + throw error; + } + registerSession(created); + notifyRunningChange(); + return { session: created, realSessionId: created.sessionId }; + })().finally(() => locks.delete(sessionId)); + // A start for this session meanwhile joins the adoption instead of spawning a second child beside it. + locks.set(sessionId, adopting); + return (await adopting).session; +} From b4fd7c0d44a3f4a3533316f0cccd9b25340cd77d Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 20:00:07 +0000 Subject: [PATCH 07/36] fix(rpc): adopted sessions hold host calls for the next tab, never rerun agent tools, and never start a second child --- lib/omp/rpc-process-runtime.test.mjs | 22 +++ lib/omp/rpc-process.ts | 28 +++- lib/rpc-manager.test.mjs | 195 +++++++++++++++++++++++++-- lib/rpc-manager.ts | 120 +++++++++++++++-- 4 files changed, 338 insertions(+), 27 deletions(-) diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 44add01b0..01840ee1a 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -339,3 +339,25 @@ test("an adopted RpcProcess needs no ready, skips a chunk tail, and holds live f assert.equal(proc.isAlive, true); await proc.dispose(0); }); + +test("an adopted RpcProcess whose output outgrows the hold cap fails its commands and its replay", async () => { + const { LINK_LIMITS } = jiti("../hosts/link-protocol.ts"); + const saved = LINK_LIMITS.channelBufferBytes; + LINK_LIMITS.channelBufferBytes = 1_000; + try { + const transport = makeAdoptedTransport([]); + const proc = new RpcProcess({ cwd: process.cwd(), transport, adopted: { protocolVersion: 2 } }); + const frames = []; + proc.onFrame((frame) => frames.push(frame)); + // The child holds this answer back while its output piles up. + const pending = proc.sendCommand({ type: "get_state" }); + transport.send({ type: "message_update", text: "x".repeat(2_000) }); + await assert.rejects(pending, /exceeded 1000 bytes/); + await assert.rejects(proc.sendCommand({ type: "get_state" }), /exceeded 1000 bytes/); + assert.throws(() => proc.replay([]), /exceeded 1000 bytes/); + assert.deepEqual(frames, [], "nothing held reaches the session"); + await proc.dispose(0); + } finally { + LINK_LIMITS.channelBufferBytes = saved; + } +}); diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index b59c236db..66ee6ed16 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -125,8 +125,11 @@ export class RpcProcess { private readonly frameListeners = new Set<(frame: RpcFrame) => void>(); private readyPromise: Promise; private readonly resolveReady: (frame: RpcFrame) => void; - /** An adopted child's frames, held until `replay` (see RpcProcessOptions.adopted). */ + /** An adopted child's frames, held until `replay` (see RpcProcessOptions.adopted), and the bytes of its lines since. */ private heldFrames: RpcFrame[] | null = null; + private heldBytes = 0; + /** Set once an adopted child's output outgrew the cap before `replay`: the adoption fails. */ + private heldOverflow: Error | null = null; private nextId = 1; private stderrTail = ""; private exited = false; @@ -165,6 +168,7 @@ export class RpcProcess { midSequence = true; }); this.transport.onLine((line) => { + if (this.heldFrames && !this.holdable(line)) return; const parsed = parseLine(line); if (parsed === undefined) return; if (midSequence && isRecord(parsed) && parsed.type === "rpc_chunk" && parsed.index !== 0) return; @@ -231,6 +235,7 @@ export class RpcProcess { /** Adopted child: feeds the daemon's raw lines of its still-open requests as * if just read (they are older than anything live), then the frames held since. */ replay(lines: string[]): void { + if (this.heldOverflow) throw this.heldOverflow; const held = this.heldFrames ?? []; this.heldFrames = null; // Its own decoder: a live chunk sequence may be half-read. @@ -242,6 +247,26 @@ export class RpcProcess { for (const frame of held) this.dispatch(frame); } + /** + * Counts an adopted child's output until `replay`, up to LINK_LIMITS.channelBufferBytes + * as RemoteRpcTransport holds it. Past that the adoption fails: its commands + * reject, `replay` throws, and the output is dropped while the wrapper kills it. + */ + private holdable(line: string): boolean { + if (this.heldOverflow) return false; + this.heldBytes += Buffer.byteLength(line); + if (this.heldBytes <= LINK_LIMITS.channelBufferBytes) return true; + const overflow = new Error(`omp's output during adoption exceeded ${LINK_LIMITS.channelBufferBytes} bytes`); + this.heldOverflow = overflow; + this.heldFrames = []; + for (const [, entry] of this.pending) { + clearTimeout(entry.timer); + entry.reject(overflow); + } + this.pending.clear(); + return false; + } + private receive(parsed: unknown, decoder: RpcFrameDecoder): void { let frame: RpcFrameRecord; try { @@ -292,6 +317,7 @@ export class RpcProcess { if (this.exited) { return Promise.reject(new Error("omp RPC process has exited")); } + if (this.heldOverflow) return Promise.reject(this.heldOverflow); const dispatchedAt = Date.now(); const id = `w${this.nextId++}`; return new Promise((resolve, reject) => { diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index df7b0cbb4..56a8591ff 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -3445,23 +3445,30 @@ test("a resume that failed while its host went offline blocks a retry until its /** * An omp child a previous run of this server spawned: already past `ready`, so - * it never sends one. It answers every command except `silent` ones; get_state - * reports `sessionId` plus `state`. `held` lines reach the first reader at once. + * it never sends one. It answers every command except `silent` ones (the test + * answers those with `answer`); get_state reports `sessionId` plus `state`. + * `held` lines reach the first reader at once. With `exitOnKill: false` a kill + * waits in the link outbox: the child exits when the test calls `exit`. */ -function adoptedTransport(sessionId, { state = {}, held = [], silent = [] } = {}) { +function adoptedTransport(sessionId, { state = {}, held = [], silent = [], exitOnKill = true } = {}) { const transport = { sent: [], + frames: [], kills: 0, write(line, callback) { const command = JSON.parse(line); transport.sent.push(command.type); + transport.frames.push(command); callback(null); // Replies to dialogs and host calls are frames, not commands: nothing answers them. if (silent.includes(command.type) || command.type.endsWith("_result") || command.type === "extension_ui_response") return; + transport.answer(command); + }, + answer(command, reply = {}) { const data = command.type === "negotiate_protocol" ? { protocolVersion: 2 } : command.type === "get_state" ? { sessionId, sessionFile: `/nonexistent/${sessionId}.jsonl`, isStreaming: false, isCompacting: false, ...state } : {}; - queueMicrotask(() => transport.emit(JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data }))); + queueMicrotask(() => transport.emit(JSON.stringify({ type: "response", id: command.id, command: command.type, success: true, data, ...reply }))); }, onLine(listener) { transport.emit = listener; @@ -3471,11 +3478,11 @@ function adoptedTransport(sessionId, { state = {}, held = [], silent = [] } = {} onExit(listener) { transport.exit = listener; }, endInput() { transport.kills += 1; - queueMicrotask(() => transport.exit?.(0, null)); + if (exitOnKill) queueMicrotask(() => transport.exit?.(0, null)); }, killTree() { transport.kills += 1; - queueMicrotask(() => transport.exit?.(null, "SIGTERM")); + if (exitOnKill) queueMicrotask(() => transport.exit?.(null, "SIGTERM")); }, }; return transport; @@ -3489,21 +3496,28 @@ function adoptionHost(id, transport) { return host; } +const hostToolResults = (transport) => transport.frames.filter((frame) => frame.type === "host_tool_result"); +/** Frames reach the transport through RpcProcess's write queue. */ +const flushWrites = () => new Promise((resolve) => setImmediate(resolve)); + test("adoptRpcSession re-syncs a live child with no spawn and no ready wait", async (t) => { - const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { adoptRpcSession, getExitedRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad01"; - const sessionFile = `/nonexistent/${id}.jsonl`; + // A crash record from before the restart. + globalThis.__ompExitedSessions ??= new Map(); + globalThis.__ompExitedSessions.set(id, { id, cwd: "/w", at: Date.now(), code: null, signal: "SIGTERM", detail: "" }); // This server restarted mid chunk sequence: the tail is dropped, not a protocol error. const bytes = Buffer.from(JSON.stringify({ type: "message_update", text: "x".repeat(1024 * 1024) })); const tail = { type: "rpc_chunk", chunkId: "lost", index: 3, count: 5, byteLength: bytes.byteLength, data: bytes.subarray(3 * 262144, 4 * 262144).toString("base64") }; const transport = adoptedTransport(id, { state: { isStreaming: true }, held: [JSON.stringify(tail)] }); - const session = await adoptRpcSession({ host: adoptionHost("adopt-box", transport), transport, sessionId: id, sessionFile, cwd: "/w", replay: [] }); + const session = await adoptRpcSession({ host: adoptionHost("adopt-box", transport), transport, sessionId: id, cwd: "/w", replay: [] }); t.after(() => session.destroyAndWait()); assert.deepEqual(transport.sent, ["negotiate_protocol", "set_subagent_subscription", "set_ask_dialog", "get_state", "get_subagents", "get_btw_history"]); assert.equal(session.isRunning(), true, "omp reported a run in progress"); - assert.equal(session.sessionFile, sessionFile); + assert.equal(session.sessionFile, `/nonexistent/${id}.jsonl`); assert.equal(getRpcSession(id), session); + assert.equal(getExitedRpcSession(id), undefined, "the run goes on: no crash record"); assert.equal(transport.kills, 0); }); @@ -3519,7 +3533,6 @@ test("an adopted child's open requests come back: an ask for the next tab, a hos host: adoptionHost("replay-box", transport), transport, sessionId: id, - sessionFile: `/nonexistent/${id}.jsonl`, cwd: "/w", replay: [JSON.stringify(ask), JSON.stringify(call)], }); @@ -3530,13 +3543,119 @@ test("an adopted child's open requests come back: an ask for the next tab, a hos // Registered with the wrapper the restart lost: routed to the open tab, not rejected. assert.deepEqual(calls, [{ sessionId: id, id: "h1", toolName: "open_url", arguments: { url: "https://a.test" } }]); - assert.equal(transport.sent.includes("host_tool_result"), false); + await flushWrites(); + assert.deepEqual(hostToolResults(transport), []); const events = []; session.onEvent((event) => events.push(event)); assert.deepEqual(events.map((event) => [event.type, event.id]), [["extension_ui_request", "q1"]]); assert.equal(session.isRunning(), true, "the run waits on its user"); }); +test("with no tab open at hello, host tool calls wait for the first tab to attach until a tab registers its tools", async (t) => { + const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad04"; + const transport = adoptedTransport(id); + const call = { type: "host_tool_call", id: "h1", toolName: "open_url", arguments: { url: "https://a.test" } }; + const session = await adoptRpcSession({ host: adoptionHost("tabless-box", transport), transport, sessionId: id, cwd: "/w", replay: [JSON.stringify(call)] }); + t.after(() => session.destroyAndWait()); + await flushWrites(); + assert.deepEqual(hostToolResults(transport), [], "not rejected for want of a tab"); + assert.equal(session.isRunning(), true); + // omp calls again before any tab is back. + transport.emit(JSON.stringify({ type: "host_tool_call", id: "h2", toolName: "read_clipboard", arguments: {} })); + await flushWrites(); + assert.deepEqual(hostToolResults(transport), []); + + const first = []; + session.onEvent((event) => first.push(event)); + assert.deepEqual(first.map((event) => [event.type, event.id]), [["host_tool_call", "h1"], ["host_tool_call", "h2"]]); + const second = []; + session.onEvent((event) => second.push(event)); + assert.deepEqual(second, [], "a call reaches one tab only"); + await session.send({ type: "host_tool_result", id: "h1", result: { content: [] } }); + await flushWrites(); + assert.deepEqual(hostToolResults(transport).map((frame) => frame.id), ["h1"]); + + // The tab registers its tools: omp now knows only those. + await session.send({ type: "set_host_tools", tools: [{ name: "open_url" }] }); + transport.emit(JSON.stringify({ type: "host_tool_call", id: "h3", toolName: "read_clipboard", arguments: {} })); + await flushWrites(); + assert.deepEqual(hostToolResults(transport).map((frame) => [frame.id, frame.isError]), [["h1", undefined], ["h3", true]]); + assert.equal(first.some((event) => event.id === "h3"), false); +}); + +test("a replayed host tool call no tab comes back for is settled after the disconnect window", async (t) => { + const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad05"; + const transport = adoptedTransport(id); + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); + const call = { type: "host_tool_call", id: "h1", toolName: "open_url", arguments: {} }; + const session = await adoptRpcSession({ host: adoptionHost("abandoned-box", transport), transport, sessionId: id, cwd: "/w", replay: [JSON.stringify(call)] }); + t.after(() => session.destroyAndWait()); + t.mock.timers.tick(119_000); + await flushWrites(); + assert.deepEqual(hostToolResults(transport), []); + // DISCONNECT_DESTROY_MS. + t.mock.timers.tick(1_000); + await flushWrites(); + assert.deepEqual(hostToolResults(transport).map((frame) => [frame.id, frame.isError, frame.result.content[0].text]), [["h1", true, "No omp-web tab reconnected to answer this host tool"]]); +}); + +test("replayed server agent tools that change things are not run twice; list_sessions is", async (t) => { + const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { until } = await import("./hosts/link-driver.test-helper.mjs"); + globalThis.__ompWebSettingsCache = undefined; + const settingsPath = join(isolatedAgentDir, "omp-web-settings.json"); + writeFileSync(settingsPath, JSON.stringify({ agentToolsEnabled: true, agentEnv: {} })); + const id = "11111111-2222-4333-8444-adadadadad06"; + const transport = adoptedTransport(id); + const replay = [ + { type: "host_tool_call", id: "n1", toolName: "new_session", arguments: { cwd: "/w" } }, + { type: "host_tool_call", id: "s1", toolName: "send_to_session", arguments: { sessionId: "other", message: "hi" } }, + { type: "host_tool_call", id: "l1", toolName: "list_sessions", arguments: {} }, + ].map((call) => JSON.stringify(call)); + const session = await adoptRpcSession({ host: adoptionHost("agent-tools-box", transport), transport, sessionId: id, cwd: "/w", replay }); + t.after(async () => { + await session.destroyAndWait(); + globalThis.__ompWebSettingsCache = undefined; + rmSync(settingsPath, { force: true }); + }); + await until(() => hostToolResults(transport).length === 3, "every replayed agent tool answered"); + const unknown = "omp-web restarted while this ran; the outcome is unknown, check with list_sessions before retrying"; + assert.deepEqual(hostToolResults(transport).map((frame) => [frame.id, frame.isError, frame.result.content[0].text === unknown]), [ + ["n1", true, true], + ["s1", true, true], + ["l1", false, false], + ]); +}); + +test("a start during adoption joins it; an adopted child is not replaced over --advisor, and a second child is refused", async (t) => { + const { adoptRpcSession, getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { until } = await import("./hosts/link-driver.test-helper.mjs"); + const id = "11111111-2222-4333-8444-adadadadad07"; + const sessionFile = `/nonexistent/${id}.jsonl`; + const transport = adoptedTransport(id, { silent: ["get_state"] }); + const host = adoptionHost("joined-box", transport); + const adopting = adoptRpcSession({ host, transport, sessionId: id, cwd: "/w", replay: [] }); + await until(() => transport.sent.includes("get_state"), "the adoption's get_state"); + // A tab opens the session meanwhile, with the advisor toggle on. + const starting = startRpcSession(id, sessionFile, "/w", undefined, true, "/w", undefined, host); + transport.answer(transport.frames.find((frame) => frame.type === "get_state")); + const session = await adopting; + t.after(() => session.destroyAndWait()); + assert.equal((await starting).session, session, "the start joined the adoption"); + + const again = await startRpcSession(id, sessionFile, "/w", undefined, true, "/w", undefined, host); + assert.equal(again.session, session, "an idle adopted child is kept: its --advisor flag is unknown"); + assert.equal(session.isAlive(), true); + + const stray = adoptedTransport(id); + await assert.rejects(adoptRpcSession({ host, transport: stray, sessionId: id, cwd: "/w", replay: [] }), /already started/); + assert.equal(stray.kills, 1, "the second child is killed"); + assert.equal(getRpcSession(id), session); + assert.equal(session.isAlive(), true); +}); + test("an adoption whose get_state times out rejects and kills the child", async (t) => { const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad03"; @@ -3548,10 +3667,60 @@ test("an adoption whose get_state times out rejects and kills the child", async if (JSON.parse(line).type === "get_state") asked.resolve(); }; t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: Date.now() }); - const adopting = adoptRpcSession({ host: adoptionHost("wedged-adopt-box", transport), transport, sessionId: id, sessionFile: `/nonexistent/${id}.jsonl`, cwd: "/w", replay: [] }); + const adopting = adoptRpcSession({ host: adoptionHost("wedged-adopt-box", transport), transport, sessionId: id, cwd: "/w", replay: [] }); await asked.promise; t.mock.timers.tick(5_000); await assert.rejects(adopting, (error) => error.name === "RpcCommandTimeoutError" && error.command === "get_state"); assert.ok(transport.kills > 0, "the child is killed"); assert.equal(getRpcSession(id), undefined); }); + +test("an adoption that failed while its host went offline blocks a start until its child exits", async (t) => { + const { adoptRpcSession, getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { until } = await import("./hosts/link-driver.test-helper.mjs"); + const id = "11111111-2222-4333-8444-adadadadad08"; + const sessionFile = `/nonexistent/${id}.jsonl`; + const transport = adoptedTransport(id, { silent: ["get_state"], exitOnKill: false }); + const host = adoptionHost("dropping-adopt-box", transport); + let spawns = 0; + let retried; + t.after(async () => { + transport.exit?.(null, "SIGTERM"); + await retried?.session.destroyAndWait(); + }); + const adopting = adoptRpcSession({ host, transport, sessionId: id, cwd: "/w", replay: [] }); + await until(() => transport.sent.includes("get_state"), "the adoption's get_state"); + host.setStatus("offline"); + transport.answer(transport.frames.find((frame) => frame.type === "get_state"), { success: false, error: "link lost" }); + await assert.rejects(adopting, /link lost/); + assert.equal(getRpcSession(id)?.isAlive(), false, "kept registered while its child may still write the file"); + + host.setStatus("online"); + host.spawnRpc = async (request) => { + spawns += 1; + return { transport: scriptedTransport(id), cwd: request.cwd, fellBack: false, launchAdvisor: false }; + }; + const retry = startRpcSession(id, sessionFile, "/w", undefined, false, "/w", undefined, host); + await new Promise((resolve) => setTimeout(resolve, 50)); + assert.equal(spawns, 0, "no second child while the adopted one may still write the session file"); + transport.exit(null, "SIGTERM"); + retried = await retry; + assert.equal(spawns, 1); + assert.equal(retried.session.isAlive(), true); +}); + +test("an adoption whose output outgrows channelBufferBytes before the replay fails and kills the child", async (t) => { + const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const { LINK_LIMITS } = await runtimeJiti.import("./hosts/link-protocol.ts"); + const saved = LINK_LIMITS.channelBufferBytes; + LINK_LIMITS.channelBufferBytes = 1_000; + t.after(() => { LINK_LIMITS.channelBufferBytes = saved; }); + const id = "11111111-2222-4333-8444-adadadadad09"; + const transport = adoptedTransport(id, { held: [JSON.stringify({ type: "message_update", text: "x".repeat(2_000) })] }); + await assert.rejects( + adoptRpcSession({ host: adoptionHost("chatty-adopt-box", transport), transport, sessionId: id, cwd: "/w", replay: [] }), + /exceeded 1000 bytes/, + ); + assert.ok(transport.kills > 0, "the child is killed"); + assert.equal(getRpcSession(id), undefined); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index a94699b74..ead823f6c 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -104,6 +104,8 @@ const AWAITING_AGENT_START_TIMEOUT_MS = 10_000; const RESTARTING_MESSAGE = "This session is restarting — retry in a moment."; const BASH_EXCLUDE_MESSAGE = "omp cannot run a shell command with its output excluded from the model context (`!!`): the RPC bash command has no exclusion option, so the output would silently enter the context anyway. Run it with a single `!` to share the output with the model, or use a terminal outside omp web."; +/** Answer to a replayed server agent tool call that changes things: it may have run before the restart. */ +const AGENT_TOOL_UNKNOWN_OUTCOME = "omp-web restarted while this ran; the outcome is unknown, check with list_sessions before retrying"; /** * Failure raised by omp-web itself (not by omp) carrying a stable snake_case @@ -295,10 +297,16 @@ export class AgentSessionWrapper { private _alive = true; /** Host tools the web UI registered via set_host_tools (agent-callable). */ private hostToolNames: Set = new Set(); - /** Feeding an adopted child's open requests (see adopt): its host tools were registered through the wrapper a restart lost. */ + /** Feeding an adopted child's open requests (see adopt): server agent tools there may already have run. */ private replaying = false; + /** Adopted, and no tab has registered host tools since: omp may call tools the + * wrapper a restart lost registered, so every call routes as registered. */ + private hostToolsUnknown = false; + private _adopted = false; /** host_tool_call ids awaiting a host_tool_result from the browser. */ private pendingHostTools: Map = new Map(); + /** Own host calls no tab has seen yet (see parkHostTool), with their deadlines. */ + private parkedHostTools = new Map>(); /** URI schemes the web UI registered via set_host_uri_schemes. */ private hostUriSchemes: Map = new Map(); /** host_uri_request ids awaiting a host_uri_result from the browser. */ @@ -587,6 +595,8 @@ export class AgentSessionWrapper { */ async adopt(replay: string[]): Promise { this.handshaking = true; + this._adopted = true; + this.hostToolsUnknown = true; // Older omp rejects some of these, as at startup; a timeout or an exit fails the adoption. const optional = (command: { type: string; [key: string]: unknown }) => this.proc.sendCommand(command, GET_STATE_TIMEOUT_MS).then(() => {}, (error) => { if (!(error instanceof RpcCommandError)) throw error; @@ -595,19 +605,29 @@ export class AgentSessionWrapper { await this.proc.negotiateProtocol(await this.proc.waitReady(), GET_STATE_TIMEOUT_MS); await optional({ type: "set_subagent_subscription", level: "events" }); await optional({ type: "set_ask_dialog", enabled: true }); + // omp's state has no shell-command flag: a `!!` command the lost server started + // leaves bashRunning false, and its result arrives as an unsolicited response. this.applyIdentity(await this.getStateWithTimeout()); // The wrapper keeps neither (a tab reads both when it attaches): a child that cannot answer them fails here instead. await optional({ type: "get_subagents" }); await optional({ type: "get_btw_history" }); this.replaying = true; - this.proc.replay(replay); - this.replaying = false; + try { + this.proc.replay(replay); + } finally { + this.replaying = false; + } } finally { this.handshaking = false; this.noteActivity(); } } + /** Taken over from a previous run of this server (see adopt): its spawn-time --advisor flag is unknown. */ + get adopted(): boolean { + return this._adopted; + } + private applyIdentity(state: RpcSessionState): void { const oldId = this._sessionId; const identityChanged = Boolean(oldId) && (state.sessionId !== oldId || (state.sessionFile && state.sessionFile !== this._sessionFile)); @@ -954,7 +974,15 @@ export class AgentSessionWrapper { // browser routing, so they work with no tab open. A disabled gate // is an explicit error, not a silent hang and not a browser call. if (id && toolName && AGENT_TOOL_NAMES.has(toolName)) { - if (loadWebServerSettings().agentToolsEnabled) { + // A replayed call may have run before the restart: only the read-only listing runs again. + if (this.replaying && toolName !== "list_sessions") { + this.proc.sendFrame({ + type: "host_tool_result", + id, + isError: true, + result: { content: [{ type: "text", text: AGENT_TOOL_UNKNOWN_OUTCOME }] }, + }); + } else if (loadWebServerSettings().agentToolsEnabled) { void this.answerServerAgentTool(event); } else { this.proc.sendFrame({ @@ -977,7 +1005,7 @@ export class AgentSessionWrapper { // any open omp-web tab (the user switched sessions mid-run). Otherwise // reject immediately so the agent never hangs on a tool nobody will // answer. - if (id && toolName && (this.hostToolNames.has(toolName) || this.replaying)) { + if (id && toolName && (this.hostToolNames.has(toolName) || this.hostToolsUnknown)) { if (this.listeners.length > 0) { this.pendingHostTools.set(id, event); this.emit(event); @@ -995,6 +1023,12 @@ export class AgentSessionWrapper { notifyRunningChange(); return; } + // Adopted with every tab gone with the old server: the next tab to attach answers it. + if (this.hostToolsUnknown) { + this.parkHostTool(id, event); + notifyRunningChange(); + return; + } } // Unregistered tool / no listener: reject (emits a notice) and do NOT // re-emit the frame — the UI must not answer a call nobody routed. @@ -1004,6 +1038,7 @@ export class AgentSessionWrapper { case "host_tool_cancel": { const targetId = typeof event.targetId === "string" ? event.targetId : ""; if (targetId && this.pendingHostTools.delete(targetId)) { + this.unparkHostTool(targetId); this.emit(event); notifyRunningChange(); return; @@ -1174,6 +1209,7 @@ export class AgentSessionWrapper { const cross = event.webCrossSession === true; if ((which === "own" && cross) || (which === "cross" && !cross)) continue; this.pendingHostTools.delete(id); + this.unparkHostTool(id); this.proc.sendFrame({ type: "host_tool_result", id, @@ -1183,6 +1219,33 @@ export class AgentSessionWrapper { } } + /** + * Hold an own host call no tab can answer yet (adopted: every tab went with + * the old server) for the next tab to attach (see onEvent). If none attaches + * within the disconnect window it is settled, so the agent never waits forever. + */ + private parkHostTool(id: string, event: UnsequencedAgentEvent): void { + this.pendingHostTools.set(id, event); + const timer = setTimeout(() => { + this.parkedHostTools.delete(id); + if (!this.pendingHostTools.delete(id)) return; + this.proc.sendFrame({ + type: "host_tool_result", + id, + isError: true, + result: { content: [{ type: "text", text: "No omp-web tab reconnected to answer this host tool" }] }, + }); + notifyRunningChange(); + }, this.disconnectDestroyMs); + timer.unref?.(); + this.parkedHostTools.set(id, timer); + } + + private unparkHostTool(id: string): void { + clearTimeout(this.parkedHostTools.get(id)); + this.parkedHostTools.delete(id); + } + /** The last other tab left: settle calls routed to other tabs. */ rejectCrossSessionHostTools(): void { this.rejectPendingHostTools("The web UI disconnected while the agent was waiting for this host tool", "cross"); @@ -1356,6 +1419,12 @@ export class AgentSessionWrapper { } listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); } + // Own host calls parked while no tab could answer go to the first tab that attaches, once. + for (const id of [...this.parkedHostTools.keys()]) { + this.unparkHostTool(id); + const event = this.pendingHostTools.get(id); + if (event) listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); + } return () => { const i = this.listeners.indexOf(listener); if (i !== -1) this.listeners.splice(i, 1); @@ -2218,11 +2287,16 @@ export class AgentSessionWrapper { : valid; this.hostToolNames = new Set(merged.map((t) => t.name as string)); await this.proc.sendCommand({ type: "set_host_tools", tools: merged }); + // omp now knows exactly these: an adopted child's lost registration is replaced. + this.hostToolsUnknown = false; return null; } case "host_tool_result": { - if (typeof command.id === "string") this.pendingHostTools.delete(command.id); + if (typeof command.id === "string") { + this.pendingHostTools.delete(command.id); + this.unparkHostTool(command.id); + } this.proc.sendFrame(command as { type: string; [key: string]: unknown }); return null; } @@ -2331,6 +2405,8 @@ export class AgentSessionWrapper { const disposed = this.proc.dispose().catch(() => {}).then(() => this.onDestroyCallback?.()); this.destroyPromise = disposed; this.pendingHostTools.clear(); + for (const timer of this.parkedHostTools.values()) clearTimeout(timer); + this.parkedHostTools.clear(); this.hostToolNames.clear(); this.pendingHostUris.clear(); this.hostUriSchemes.clear(); @@ -2734,8 +2810,9 @@ export async function startRpcSession( // replace the child so the toggle takes effect on the next prompt. Busy // children are kept (a mid-run swap would drop in-flight work) and pick // the new flag up at the next natural respawn; callers that pass no - // advisor opinion (undefined) simply reuse whatever is running. - if (advisor === undefined || existing.advisorSpawned === effectiveAdvisor || existing.isRunning() || existing.isEditingHistory()) { + // advisor opinion (undefined) simply reuse whatever is running. An adopted + // child's flag is unknown, so it is never replaced over it. + if (advisor === undefined || existing.adopted || existing.advisorSpawned === effectiveAdvisor || existing.isRunning() || existing.isEditingHistory()) { return { session: existing, realSessionId: sessionId }; } await existing.destroyAndWait(); @@ -2857,18 +2934,23 @@ function registerSession(created: AgentSessionWrapper): void { /** * Take over an omp child that outlived the server that spawned it (its host * listed it in `hello`): no spawn and no ready wait. `replay` holds the host's - * raw stdout lines of the child's still-open blocking requests. A failed - * re-sync kills the child and rejects. + * raw stdout lines of the child's still-open blocking requests. Rejects, with + * the child being killed, when this server already starts or keeps a wrapper + * for the session (never two children on one file) or when the re-sync fails. */ export async function adoptRpcSession({ host, transport, sessionId, cwd, replay }: { host: Host; transport: RpcTransport; sessionId: string; - sessionFile: string; cwd: string; replay: string[]; }): Promise { + const registry = getRegistry(); const locks = getLocks(); + if (locks.has(sessionId) || registry.has(sessionId)) { + transport.killTree(false); + throw new Error(`Session ${sessionId} is already started on this server`); + } const holder: { wrapper?: AgentSessionWrapper } = {}; const proc = new RpcProcess({ cwd, transport, adopted: { protocolVersion: 2 }, onExit: (info) => holder.wrapper?.handleProcessExit(info, proc) }); // Spawn-time facts (--advisor, a cwd fallback) died with the server that spawned it. @@ -2879,13 +2961,25 @@ export async function adoptRpcSession({ host, transport, sessionId, cwd, replay try { await created.adopt(replay); } catch (error) { - await created.destroyAndWait("adoption-failed"); + const disposing = created.destroyAndWait("adoption-failed"); + // As for a failed resume: until the child really exits, a start for this + // session waits for it (destroyAndWait returns early behind a dropped link). + registry.set(sessionId, created); + void created.destroyPromise?.then(() => { + if (registry.get(sessionId) === created) registry.delete(sessionId); + }); + await disposing; throw error; } registerSession(created); + // The run goes on: any crash record for the session is stale. + clearExitedRpcSession(sessionId); + if (created.sessionId !== sessionId) clearExitedRpcSession(created.sessionId); notifyRunningChange(); return { session: created, realSessionId: created.sessionId }; - })().finally(() => locks.delete(sessionId)); + })().finally(() => { + if (locks.get(sessionId) === adopting) locks.delete(sessionId); + }); // A start for this session meanwhile joins the adoption instead of spawning a second child beside it. locks.set(sessionId, adopting); return (await adopting).session; From ded178bb5bfb038ea2edf499603092154012d3a4 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 20:07:26 +0000 Subject: [PATCH 08/36] fix(rpc): parked host calls wait for a tab, and handshake-time agent tools run as live calls --- lib/omp/rpc-process-runtime.test.mjs | 5 +++- lib/omp/rpc-process.ts | 32 +++++++++++++---------- lib/rpc-manager.test.mjs | 38 ++++++++++++++++++++++++++++ lib/rpc-manager.ts | 20 ++++++++++++--- 4 files changed, 77 insertions(+), 18 deletions(-) diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 01840ee1a..1fda4f683 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -312,7 +312,7 @@ function makeAdoptedTransport(held) { return transport; } -test("an adopted RpcProcess needs no ready, skips a chunk tail, and holds live frames until the replay", async () => { +test("an adopted RpcProcess needs no ready, skips a chunk tail, and holds live frames until the replay is released", async () => { const big = (type, id) => ({ type, id, content: "x".repeat(1024 * 1024) }); // The web server restarted mid chunk sequence: its tail must not be a protocol error. const tail = chunkRecords(big("message_update", "lost"), "before-restart").slice(2); @@ -332,6 +332,8 @@ test("an adopted RpcProcess needs no ready, skips a chunk tail, and holds live f JSON.stringify({ type: "extension_ui_request", id: "q1", method: "ask" }), ...chunkRecords(big("host_tool_call", "h1"), "pending").map((record) => JSON.stringify(record)), ]); + assert.deepEqual(frames, ["q1", "h1"], "the replay is delivered at once; live frames are still held"); + proc.release(); assert.deepEqual(frames, ["q1", "h1", "agent_start"]); for (const record of live.slice(2)) transport.send(record); assert.deepEqual(frames, ["q1", "h1", "agent_start", "live"]); @@ -355,6 +357,7 @@ test("an adopted RpcProcess whose output outgrows the hold cap fails its command await assert.rejects(pending, /exceeded 1000 bytes/); await assert.rejects(proc.sendCommand({ type: "get_state" }), /exceeded 1000 bytes/); assert.throws(() => proc.replay([]), /exceeded 1000 bytes/); + assert.throws(() => proc.release(), /exceeded 1000 bytes/); assert.deepEqual(frames, [], "nothing held reaches the session"); await proc.dispose(0); } finally { diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index 66ee6ed16..afd052fde 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -77,7 +77,7 @@ export interface RpcProcessOptions { transport?: RpcTransport; /** A child that outlived the server that spawned it (see adoptRpcSession): no * ready wait, the decoder starts at this version and drops `rpc_chunk` - * records until a frame starts, and frames are held until `replay`. */ + * records until a frame starts, and frames are held until `release` (after `replay`). */ adopted?: { protocolVersion: 2 }; /** Injectable process boundary for deterministic transport tests. */ dependencies?: { @@ -125,10 +125,10 @@ export class RpcProcess { private readonly frameListeners = new Set<(frame: RpcFrame) => void>(); private readyPromise: Promise; private readonly resolveReady: (frame: RpcFrame) => void; - /** An adopted child's frames, held until `replay` (see RpcProcessOptions.adopted), and the bytes of its lines since. */ + /** An adopted child's frames, held until `release` (see RpcProcessOptions.adopted), and the bytes of its lines since. */ private heldFrames: RpcFrame[] | null = null; private heldBytes = 0; - /** Set once an adopted child's output outgrew the cap before `replay`: the adoption fails. */ + /** Set once an adopted child's output outgrew the cap before `release`: the adoption fails. */ private heldOverflow: Error | null = null; private nextId = 1; private stderrTail = ""; @@ -233,24 +233,29 @@ export class RpcProcess { } /** Adopted child: feeds the daemon's raw lines of its still-open requests as - * if just read (they are older than anything live), then the frames held since. */ + * if just read. They are older than anything held, which `release` delivers next. */ replay(lines: string[]): void { if (this.heldOverflow) throw this.heldOverflow; - const held = this.heldFrames ?? []; - this.heldFrames = null; // Its own decoder: a live chunk sequence may be half-read. const decoder = new RpcFrameDecoder(); for (const line of lines) { const parsed = parseLine(line); - if (parsed !== undefined) this.receive(parsed, decoder); + if (parsed !== undefined) this.receive(parsed, decoder, true); } + } + + /** Adopted child, after `replay`: delivers the frames held since and stops holding. */ + release(): void { + if (this.heldOverflow) throw this.heldOverflow; + const held = this.heldFrames ?? []; + this.heldFrames = null; for (const frame of held) this.dispatch(frame); } /** - * Counts an adopted child's output until `replay`, up to LINK_LIMITS.channelBufferBytes + * Counts an adopted child's output until `release`, up to LINK_LIMITS.channelBufferBytes * as RemoteRpcTransport holds it. Past that the adoption fails: its commands - * reject, `replay` throws, and the output is dropped while the wrapper kills it. + * reject, `replay` and `release` throw, and the output is dropped while the wrapper kills it. */ private holdable(line: string): boolean { if (this.heldOverflow) return false; @@ -267,7 +272,8 @@ export class RpcProcess { return false; } - private receive(parsed: unknown, decoder: RpcFrameDecoder): void { + /** `replayed`: a daemon line (see `replay`), delivered past the frames still held. */ + private receive(parsed: unknown, decoder: RpcFrameDecoder, replayed = false): void { let frame: RpcFrameRecord; try { if (isRecord(parsed) && parsed.type === "rpc_chunk" && this.protocolVersion !== 2) { @@ -290,11 +296,11 @@ export class RpcProcess { this.handleResponse(frame as unknown as RpcResponseFrame); return; } - this.dispatch(frame); + this.dispatch(frame, replayed); } - private dispatch(frame: RpcFrame): void { - if (this.heldFrames) { + private dispatch(frame: RpcFrame, replayed = false): void { + if (this.heldFrames && !replayed) { this.heldFrames.push(frame); return; } diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 56a8591ff..cb4ec4266 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -3629,6 +3629,44 @@ test("replayed server agent tools that change things are not run twice; list_ses ]); }); +test("an agent tool omp called during the adoption handshake is live, not replayed", async (t) => { + const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + // The gate is off: a live call gets the gate's answer, a replayed one "outcome unknown". + globalThis.__ompWebSettingsCache = undefined; + t.after(() => { globalThis.__ompWebSettingsCache = undefined; }); + const id = "11111111-2222-4333-8444-adadadadad0a"; + const live = { type: "host_tool_call", id: "live1", toolName: "new_session", arguments: { cwd: "/w" } }; + const replayed = { type: "host_tool_call", id: "r1", toolName: "new_session", arguments: { cwd: "/w" } }; + const transport = adoptedTransport(id, { held: [JSON.stringify(live)] }); + const session = await adoptRpcSession({ host: adoptionHost("handshake-tools-box", transport), transport, sessionId: id, cwd: "/w", replay: [JSON.stringify(replayed)] }); + t.after(() => session.destroyAndWait()); + await flushWrites(); + assert.deepEqual(hostToolResults(transport).map((frame) => [frame.id, frame.result.content[0].text.startsWith("omp-web restarted"), /disabled/.test(frame.result.content[0].text)]), [ + ["r1", true, false], + ["live1", false, true], + ]); +}); + +test("an internal turn waiter neither takes an adopted session's parked host calls nor settles them", async (t) => { + const { adoptRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad0b"; + const transport = adoptedTransport(id); + const call = { type: "host_tool_call", id: "h1", toolName: "open_url", arguments: {} }; + const session = await adoptRpcSession({ host: adoptionHost("waiter-box", transport), transport, sessionId: id, cwd: "/w", replay: [JSON.stringify(call)] }); + t.after(() => session.destroyAndWait()); + // An agent tool's waited delivery watches the session; no tab does. + const waiting = session.waitForTurnEnd(5_000); + transport.emit(JSON.stringify({ type: "host_tool_call", id: "h2", toolName: "open_url", arguments: {} })); + transport.emit(JSON.stringify({ type: "agent_end", isTerminal: true })); + await waiting; + await flushWrites(); + assert.deepEqual(hostToolResults(transport), [], "the waiter leaving settles nothing"); + + const tab = []; + session.onEvent((event) => tab.push(event)); + assert.deepEqual(tab.map((event) => [event.type, event.id]), [["host_tool_call", "h1"], ["host_tool_call", "h2"]]); +}); + test("a start during adoption joins it; an adopted child is not replaced over --advisor, and a second child is refused", async (t) => { const { adoptRpcSession, getRpcSession, startRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); const { until } = await import("./hosts/link-driver.test-helper.mjs"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index ead823f6c..d9dd064e7 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -307,6 +307,8 @@ export class AgentSessionWrapper { private pendingHostTools: Map = new Map(); /** Own host calls no tab has seen yet (see parkHostTool), with their deadlines. */ private parkedHostTools = new Map>(); + /** Listeners omp-web attaches itself (waitForTurnEnd), not tabs: a parked host call waits for a tab. */ + private readonly internalListeners = new WeakSet(); /** URI schemes the web UI registered via set_host_uri_schemes. */ private hostUriSchemes: Map = new Map(); /** host_uri_request ids awaiting a host_uri_result from the browser. */ @@ -617,6 +619,8 @@ export class AgentSessionWrapper { } finally { this.replaying = false; } + // Frames omp sent during the handshake are live: its agent tool calls there run normally. + this.proc.release(); } finally { this.handshaking = false; this.noteActivity(); @@ -1006,7 +1010,11 @@ export class AgentSessionWrapper { // reject immediately so the agent never hangs on a tool nobody will // answer. if (id && toolName && (this.hostToolNames.has(toolName) || this.hostToolsUnknown)) { - if (this.listeners.length > 0) { + // An adopted session's calls wait for a tab: an internal listener alone cannot answer them. + const ownTab = this.hostToolsUnknown + ? this.listeners.some((listener) => !this.internalListeners.has(listener)) + : this.listeners.length > 0; + if (ownTab) { this.pendingHostTools.set(id, event); this.emit(event); notifyRunningChange(); @@ -1208,6 +1216,8 @@ export class AgentSessionWrapper { for (const [id, event] of this.pendingHostTools) { const cross = event.webCrossSession === true; if ((which === "own" && cross) || (which === "cross" && !cross)) continue; + // No tab ever received it: its own deadline settles it (see parkHostTool). + if (which === "own" && this.parkedHostTools.has(id)) continue; this.pendingHostTools.delete(id); this.unparkHostTool(id); this.proc.sendFrame({ @@ -1407,7 +1417,9 @@ export class AgentSessionWrapper { this.idleTimer.unref?.(); } - onEvent(listener: EventListener): () => void { + /** `internal`: omp-web's own listener (waitForTurnEnd), never handed a parked host call. */ + onEvent(listener: EventListener, { internal = false }: { internal?: boolean } = {}): () => void { + if (internal) this.internalListeners.add(listener); this.listeners.push(listener); this.noteActivity(); const now = Date.now(); @@ -1420,7 +1432,7 @@ export class AgentSessionWrapper { listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); } // Own host calls parked while no tab could answer go to the first tab that attaches, once. - for (const id of [...this.parkedHostTools.keys()]) { + for (const id of internal ? [] : [...this.parkedHostTools.keys()]) { this.unparkHostTool(id); const event = this.pendingHostTools.get(id); if (event) listener({ ...event, web: { streamId: this.streamId, sequence: ++this.streamSequence } }); @@ -1469,7 +1481,7 @@ export class AgentSessionWrapper { } else if (event.type === "prompt_error") { finish(new Error(typeof event.errorMessage === "string" ? event.errorMessage : "Target session turn failed.")); } - }); + }, { internal: true }); const finish = (error: Error | null) => { if (done) return; done = true; From 8cf742933bc476ecdfb73f1211a1f35c37bfe414 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 20:41:01 +0000 Subject: [PATCH 09/36] feat(hosts): a restarted web server adopts live omp children --- lib/hosts/hub.test.mjs | 96 +++++++++++++++- lib/hosts/hub.ts | 91 ++++++++++----- lib/hosts/link-driver.test-helper.mjs | 19 ++++ lib/hosts/link-integration.test.mjs | 155 ++++++++++++++++++++++++-- lib/rpc-manager.test.mjs | 4 +- lib/session-resume.test.mjs | 34 +++++- lib/session-resume.ts | 9 +- 7 files changed, 357 insertions(+), 51 deletions(-) diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 24f3533a4..1296de8b6 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -19,6 +19,9 @@ const jiti = createJiti(import.meta.url); const hub = await jiti.import("./hub.ts"); const { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_LIMITS, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION } = await jiti.import("./link-protocol.ts"); const { createHost } = await jiti.import("./registry.ts"); +const { getRpcSession } = await jiti.import("../rpc-manager.ts"); +const { resumeOnHostLink } = await jiti.import("../session-resume.ts"); +const { LinkDriver, linkHost, listedSession, ompChild, until } = await import("./link-driver.test-helper.mjs"); const defaultTimings = { ...hub.linkTimings }; test.afterEach(() => Object.assign(hub.linkTimings, defaultTimings)); @@ -405,9 +408,9 @@ test("no uplink traffic for offlineMs marks the host offline and notifies", asyn test("onHostHello reports the channels a daemon still runs", async () => { const seen = []; const unsubscribe = hub.onHostHello((hostId, channels) => seen.push({ hostId, channels })); - const { id, down } = await linkedHost("Reattach", { channels: [{ ch: "c1", sessionId: "s1", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }); + const { id, down } = await linkedHost("Reattach", { channels: [{ ch: "c1", sessionId: null, pending: ['{"type":"host_tool_call","id":"t1"}'] }] }); unsubscribe(); - assert.deepEqual(seen, [{ hostId: id, channels: [{ ch: "c1", sessionId: "s1", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }]); + assert.deepEqual(seen, [{ hostId: id, channels: [{ ch: "c1", sessionId: null, pending: ['{"type":"host_tool_call","id":"t1"}'] }] }]); await down.cancel(); }); @@ -435,7 +438,7 @@ test("on hello a spawned child the daemon no longer lists exits as lost; a spawn test("orphanExit rejects with 503 when the host goes offline before the orphan exits", async () => { hub.linkTimings.offlineMs = 40; const sessionId = "11111111-2222-4333-8444-999999999999"; - const link = await linkedHost("Dozing", { channels: [{ ch: "old", sessionId, pending: [] }] }); + const link = await linkedHost("Dozing", { channels: [{ ch: "old", sessionId, pending: null }] }); // No uplink follows the hello: the host goes offline with the orphan still listed. await assert.rejects(hub.orphanExit(link.id, sessionId), (error) => { assert.equal(error.status, 503); @@ -446,9 +449,9 @@ test("orphanExit rejects with 503 when the host goes offline before the orphan e await link.down.cancel(); }); -test("on hello a listed child with no transport is an orphan: killed, and orphanExit waits for it", async () => { +test("on hello a listed child with no transport that cannot be adopted is an orphan: killed, and orphanExit waits for it", async () => { const sessionId = "11111111-2222-4333-8444-555555555555"; - const link = await linkedHost("Survivor", { channels: [{ ch: "old", sessionId, pending: [] }] }); + const link = await linkedHost("Survivor", { channels: [{ ch: "old", sessionId, pending: null }] }); assert.deepEqual(await link.down.nextReal(), { type: "kill", seq: 1, ch: "old", force: false }); let gone = false; const waiting = hub.orphanExit(link.id, sessionId).then(() => { @@ -461,6 +464,87 @@ test("on hello a listed child with no transport is an orphan: killed, and orphan await link.down.cancel(); }); +const ADOPTED = "11111111-2222-4333-8444-aaaaaaaaaa01"; + +test("on hello a listed child of a session its host lists is adopted: no kill, its wrapper registered", async (t) => { + const link = await linkHost("Adopter", { channels: [{ ch: "live", sessionId: ADOPTED, pending: [] }] }); + t.after(async () => { + const disposing = getRpcSession(ADOPTED)?.destroyAndWait(); + await link.post({ type: "exit", ch: "live", code: 0, signal: null }); + await disposing; + hub.closeHostLink(link.id); + }); + const seen = []; + const omp = ompChild(link, ADOPTED, { state: { isStreaming: true } }); + link.serve({ listSessions: () => [listedSession(ADOPTED)] }, (message) => { + seen.push(message); + return omp(message); + }); + await until(() => getRpcSession(ADOPTED), "the adopted session"); + const session = getRpcSession(ADOPTED); + assert.equal(session.adopted, true); + assert.equal(session.host, hub.getHost(link.id)); + assert.equal(session.isRunning(), true); + assert.deepEqual(seen.filter((message) => message.type === "kill"), []); + assert.ok(seen.some((message) => message.type === "stdin" && message.ch === "live"), "the wrapper talks to the listed channel"); + assert.equal(await hub.adoptedChild(link.id, ADOPTED), true); + // An adopted child is the live session's, no longer an orphan a start or file op waits for. + await hub.orphanExit(link.id, ADOPTED); +}); + +test("on hello a listed child of a session its host does not list is killed", async (t) => { + const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa02"; + const link = await linkHost("Forgetful", { channels: [{ ch: "stray", sessionId, pending: [] }] }); + t.after(() => hub.closeHostLink(link.id)); + const kills = []; + link.serve({ listSessions: () => [listedSession(ADOPTED)] }, (message) => { + if (message.type === "kill") kills.push(message); + }); + await until(() => kills.length > 0, "the kill"); + assert.deepEqual(kills.map(({ ch, force }) => ({ ch, force })), [{ ch: "stray", force: false }]); + assert.equal(getRpcSession(sessionId), undefined); + assert.equal(await hub.adoptedChild(link.id, sessionId), false); +}); + +test("a child listed without its replay or without a session is killed without asking for the host's sessions", async (t) => { + const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa03"; + const link = await linkHost("Overflowing", { channels: [{ ch: "big", sessionId, pending: null }, { ch: "fresh", sessionId: null, pending: [] }] }); + t.after(() => hub.closeHostLink(link.id)); + assert.deepEqual([await link.next(), await link.next()].map(({ type, ch }) => ({ type, ch })), [{ type: "kill", ch: "big" }, { type: "kill", ch: "fresh" }]); +}); + +test("a failed adoption kills the child, blocks a start until it exits, then resumes the run once", async (t) => { + const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa04"; + const { host, token } = createHost("Wedged"); + t.after(() => hub.closeHostLink(host.id)); + const entry = { id: sessionId, advisor: false, hostId: host.id }; + const resumed = []; + resumeOnHostLink([entry], async (interrupted) => { + resumed.push(interrupted); + }); + const link = new LinkDriver(host.id, token); + await link.dial({ channels: [{ ch: "wedged", sessionId, pending: [] }] }); + const kills = []; + const omp = ompChild(link, sessionId, { fail: "get_state" }); + link.serve({ listSessions: () => [listedSession(sessionId)] }, (message) => { + if (message.type === "kill") kills.push(message.ch); + return omp(message); + }); + await until(() => kills.includes("wedged"), "the kill"); + let exited = false; + const waiting = hub.orphanExit(host.id, sessionId).then(() => { + exited = true; + }); + await new Promise((resolve) => setTimeout(resolve, 20)); + assert.equal(exited, false, "no second child while this one may still write the session file"); + assert.deepEqual(resumed, []); + await link.post({ type: "exit", ch: "wedged", code: null, signal: "SIGTERM" }); + await waiting; + await until(() => resumed.length > 0, "the resume"); + assert.deepEqual(resumed, [entry]); + assert.equal(getRpcSession(sessionId), undefined); +}); + for (const [op, call, value] of [ ["archiveSession", (ops, id) => ops.archiveSession(id), { archivedPath: "/a" }], ["deleteSession", (ops, id) => ops.deleteSession(id, []), {}], @@ -468,7 +552,7 @@ for (const [op, call, value] of [ ]) { test(`${op} waits for the session's orphan to exit; another session is not delayed`, async () => { const sessionId = "11111111-2222-4333-8444-666666666666"; - const link = await linkedHost(`Waiter ${op}`, { channels: [{ ch: "old", sessionId, pending: [] }] }); + const link = await linkedHost(`Waiter ${op}`, { channels: [{ ch: "old", sessionId, pending: null }] }); assert.equal((await link.down.nextReal()).type, "kill"); const ops = link.remote.sessionOps; let seq = 0; diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index d615f3a8c..3a462ad9e 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -389,8 +389,9 @@ const ORPHAN_KILL_GRACE_MS = 5_000; * Spec Rules → Reattach. Listed channels this server has a transport for carry * on unchanged. A spawned child the daemon no longer lists died while the link * was down: its transport gets a synthesized exit, marked `lost`. Listed - * channels without a transport are orphans of a restart of this server and are - * killed; they stay registered until their `exit` (see orphanExit). + * channels without a transport are children of a previous run of this server: + * adopted (see adopt), or killed as orphans when that is not possible. Either + * way they stay registered until their `exit` (see orphanExit). */ function reattach(link: Link, listed: HelloChannel[]): void { const live = new Set(listed.map(({ ch }) => ch)); @@ -401,16 +402,45 @@ function reattach(link: Link, listed: HelloChannel[]): void { transport.lost = true; transport.deliverExit(null, null); } - for (const { ch, sessionId } of listed) { + // Asked once per hello, and fresh: a cached list may still hold a session deleted since. + let sessions: Promise | undefined; + const listSessions = () => (sessions ??= link.host.sessionOps.listSessions()); + for (const { ch, sessionId, pending } of listed) { if (link.channels.has(ch)) continue; - const orphan = new RemoteRpcTransport(link.id, ch, sessionId); - orphan.spawned = true; - orphan.orphaned = true; - link.channels.set(ch, orphan); - orphan.killTree(false); - const escalate = setTimeout(() => orphan.killTree(true), ORPHAN_KILL_GRACE_MS); - escalate.unref?.(); - orphan.onExit(() => clearTimeout(escalate)); + const child = new RemoteRpcTransport(link.id, ch, sessionId); + child.spawned = true; + link.channels.set(ch, child); + // A null `pending` lost open requests to the daemon's cap: adopted, the run would wait on them forever. + if (sessionId && pending) child.adoption = adopt(link, child, sessionId, pending, listSessions); + else killOrphan(child); + } +} + +function killOrphan(orphan: RemoteRpcTransport): void { + orphan.orphaned = true; + orphan.killTree(false); + const escalate = setTimeout(() => orphan.killTree(true), ORPHAN_KILL_GRACE_MS); + escalate.unref?.(); + orphan.onExit(() => clearTimeout(escalate)); +} + +/** Spec "Adopting live children": a session wrapper takes the child over; one + * that cannot (unknown session, failed re-sync) is killed. True when adopted. */ +async function adopt(link: Link, child: RemoteRpcTransport, sessionId: string, replay: string[], listSessions: () => Promise): Promise { + try { + // rpc-manager imports this module. Awaiting it also defers the lookup past + // openDownlink, which marks the link up (ops need it) after reattach. + const { adoptRpcSession } = await import("../rpc-manager"); + // shortcut: a start of this session during the lookup takes its lock first, so adoptRpcSession + // refuses and the child is killed and resumed; hold the start lock across the lookup if that shows up. + const session = (await listSessions()).find((entry) => entry.id === sessionId); + if (!session) throw new Error("its session is unknown"); + await adoptRpcSession({ host: link.host, transport: child, sessionId, cwd: session.cwd, replay }); + return true; + } catch (error) { + console.warn(`[omp-web] killing the omp child of session ${sessionId} on ${labelOf(link.id)}: it could not be adopted (${error instanceof Error ? error.message : String(error)})`); + killOrphan(child); + return false; } } @@ -638,14 +668,16 @@ export class RemoteRpcTransport implements RpcTransport { get id(): string { return this.ch; } - /** Set for an orphan the daemon listed in `hello` (the session it runs); null for children this server spawned. */ + /** Set for a child of a previous run the daemon listed in `hello` (the session it runs); null for children this server spawned. */ readonly sessionId: string | null; /** The daemon confirmed the spawn (or listed the channel); until then a `hello` without it is not a loss. */ spawned = false; /** The daemon stopped listing this child: it died while the link was down. Set before the synthesized exit. */ lost = false; - /** Killed on sight: a child of a previous run of this server. Its output has no reader and is dropped. */ + /** Killed: a child of a previous run of this server that it could not adopt. Its output has no reader and is dropped. */ orphaned = false; + /** A listed child being taken over (see reattach): resolves true once adopted, false once killed instead. */ + adoption: Promise | null = null; private readonly lineListeners: Array<(line: string) => void> = []; private readonly stderrListeners: Array<(chunk: string) => void> = []; private readonly exitListeners: Array<(code: number | null, signal: NodeJS.Signals | null) => void> = []; @@ -897,8 +929,8 @@ export function onHostsChange(listener: () => void): () => void { }; } -/** Fires on every accepted hello with the omp children the daemon still runs. - * Listeners run after reattach: lost channels have exited and orphans are being killed. */ +/** Fires on every accepted hello with the omp children the daemon still runs. Listeners + * run after reattach: lost channels have exited, the rest are being adopted or killed. */ export function onHostHello(listener: (hostId: string, channels: HelloChannel[]) => void): () => void { const listeners = hub().helloListeners; listeners.add(listener); @@ -907,27 +939,34 @@ export function onHostHello(listener: (hostId: string, channels: HelloChannel[]) }; } -/** Resolves once every orphan of `sessionId` the host listed in a hello has exited. +/** Whether this server adopted a child of `sessionId` the host listed in a hello; waits for an adoption still running. */ +export async function adoptedChild(hostId: string, sessionId: string): Promise { + const listed = [...(hub().links.get(hostId)?.channels.values() ?? [])].filter((child) => child.sessionId === sessionId); + return (await Promise.all(listed.map((child) => child.adoption))).includes(true); +} + +/** Resolves once every child of `sessionId` the host listed in a hello has exited or been adopted. * Rejects with 503 if the host goes offline first: waiting through an outage * would hold the session's start lock until the host redials. */ export async function orphanExit(hostId: string, sessionId: string): Promise { const link = hub().links.get(hostId); - const orphans = [...(link?.channels.values() ?? [])].filter((transport) => transport.sessionId === sessionId); - if (!link || orphans.length === 0) return; - const { promise, resolve, reject } = Promise.withResolvers(); + const listed = [...(link?.channels.values() ?? [])].filter((child) => child.sessionId === sessionId); + if (!link || listed.length === 0) return; + const { promise: offline, reject } = Promise.withResolvers(); const onStatus = (status: HostStatus) => { if (!isLinkUp(status)) reject(new HostOpError(503, "host_offline", `${labelOf(hostId)} is offline`)); }; onStatus(link.status); link.statusListeners.add(onStatus); - let running = orphans.length; - for (const orphan of orphans) { - orphan.onExit(() => { - if (--running === 0) resolve(); - }); - } + const gone = listed.map((child) => { + const { promise, resolve } = Promise.withResolvers(); + child.onExit(() => resolve()); + // An adopted child runs the live session: not an orphan to wait for. + void child.adoption?.then((adopted) => adopted && resolve()); + return promise; + }); try { - await promise; + await Promise.race([offline, Promise.all(gone)]); } finally { link.statusListeners.delete(onStatus); } diff --git a/lib/hosts/link-driver.test-helper.mjs b/lib/hosts/link-driver.test-helper.mjs index 6ded9f0e9..2f7f6e485 100644 --- a/lib/hosts/link-driver.test-helper.mjs +++ b/lib/hosts/link-driver.test-helper.mjs @@ -28,6 +28,25 @@ export async function until(predicate, what) { } } +/** A linked host's `listSessions` entry for session `id`. */ +export function listedSession(id, cwd = "/w") { + return { path: `/remote/sessions/${id}.jsonl`, id, cwd, created: "c", modified: "m", messageCount: 1, firstMessage: "hi" }; +} + +/** An omp child behind `link` that is past its ready: answers each command on its channel + * (protocol v2), get_state as session `sessionId` plus `state`; a command of type `fail` is refused. */ +export function ompChild(link, sessionId, { state = {}, fail = null } = {}) { + return async (message) => { + if (message.type !== "stdin") return; + const command = JSON.parse(message.line); + const data = command.type === "negotiate_protocol" ? { protocolVersion: 2 } + : command.type === "get_state" ? { sessionId, sessionFile: `/remote/sessions/${sessionId}.jsonl`, isStreaming: false, isCompacting: false, ...state } + : {}; + const outcome = command.type === fail ? { success: false, error: `${fail} failed` } : { success: true, data }; + await link.post({ type: "stdout", ch: message.ch, line: JSON.stringify({ type: "response", id: command.id, command: command.type, ...outcome }) }); + }; +} + export class LinkDriver { constructor(id, token) { this.id = id; diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 06cb40209..ffc910349 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -1,10 +1,11 @@ import assert from "node:assert/strict"; import { spawn, spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import { createServer } from "node:http"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test, { after, before } from "node:test"; +import { setTimeout as sleep } from "node:timers/promises"; import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; @@ -30,7 +31,9 @@ const blobRoute = await jiti.import("../../app/api/hosts/link/blob/[reqId]/route const hub = await jiti.import("./hub.ts"); const { createHost } = await jiti.import("./registry.ts"); const { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_NONCE_HEADER } = await jiti.import("./link-protocol.ts"); -const { startRpcSession } = await jiti.import("../rpc-manager.ts"); +const { AgentSessionWrapper, getRpcSession, resumeInterruptedSessions, startRpcSession } = await jiti.import("../rpc-manager.ts"); +const { RESUME_PROMPT } = await jiti.import("../session-resume.ts"); +const { saveWebServerSettings } = await jiti.import("../web-settings.ts"); // Windows cannot spawn a shebang script: run it through a .cmd launcher (which wrapWindowsScript routes via cmd.exe). function writeFakeOmp(file, source) { @@ -43,21 +46,62 @@ function writeFakeOmp(file, source) { } const FRAMES = 200; +// "slow": the first half at once, the rest one by one once the test creates slowGo. +const SLOW_HALF = 20; +const SLOW_FRAMES = 80; +const slowGo = join(scratch, "slow-go"); +// Every omp child appends {pid, kind: "start" | "stdin", ...} here. +const ompLogFile = join(scratch, "omp.log"); +const ompLog = () => (existsSync(ompLogFile) ? readFileSync(ompLogFile, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : []); const fakeOmp = join(scratch, process.platform === "win32" ? "fake-omp.cmd" : "fake-omp"); writeFakeOmp(fakeOmp, `if (process.argv.includes("--version")) { console.log("14.0.0-fake"); process.exit(0); } +const fs = require("node:fs"); const path = require("node:path"); const out = (frame) => process.stdout.write(JSON.stringify(frame) + "\\n"); -const sessionFile = path.join(${JSON.stringify(sessionsDir)}, "-project", "fake-live.jsonl"); -out({ type: "ready" }); +const log = (entry) => fs.appendFileSync(${JSON.stringify(ompLogFile)}, JSON.stringify({ pid: process.pid, ...entry }) + "\\n"); +const resumeAt = process.argv.indexOf("--resume"); +const resumed = resumeAt === -1 ? null : process.argv[resumeAt + 1]; +const sessionFile = resumed ?? path.join(${JSON.stringify(sessionsDir)}, "-project", "fake-live.jsonl"); +const sessionId = resumed ? JSON.parse(fs.readFileSync(resumed, "utf8").split("\\n")[0]).id : "remote-live"; +let streaming = false; +const update = (text) => out({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: String(text) }] } }); +const end = () => { + streaming = false; + out({ type: "agent_end", isTerminal: true, messages: [] }); +}; +log({ kind: "start", sessionId }); +out({ type: "ready", supportedProtocolVersions: [1, 2] }); require("node:readline").createInterface({ input: process.stdin }).on("line", (line) => { const command = JSON.parse(line); + log({ kind: "stdin", command }); const reply = (data) => out({ type: "response", id: command.id, command: command.type, success: true, data }); - if (command.type === "get_state") return reply({ sessionId: "remote-live", sessionFile, isStreaming: false, isCompacting: false }); + if (command.type === "negotiate_protocol") return reply({ protocolVersion: 2 }); + if (command.type === "get_state") return reply({ sessionId, sessionFile, isStreaming: streaming, isCompacting: false }); + // A dialog answer is a frame: omp sends no response to it. + if (command.type === "extension_ui_response") { + update("answered " + command.answers[0].selectedOptions[0]); + return end(); + } if (command.type !== "prompt") return reply({}); reply({ agentInvoked: true }); + streaming = true; out({ type: "agent_start" }); - for (let i = 1; i <= ${FRAMES}; i++) out({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: String(i) }] } }); - out({ type: "agent_end", isTerminal: true, messages: [] }); + if (command.message === "ask") return out({ type: "extension_ui_request", id: "q1", method: "ask", questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }); + if (command.message === "slow") { + for (let i = 1; i <= ${SLOW_HALF}; i++) update(i); + let sent = ${SLOW_HALF}; + const timer = setInterval(() => { + if (!fs.existsSync(${JSON.stringify(slowGo)})) return; + update(++sent); + if (sent === ${SLOW_FRAMES}) { + clearInterval(timer); + end(); + } + }, 25); + return; + } + for (let i = 1; i <= ${FRAMES}; i++) update(i); + end(); }); process.stdin.on("end", () => process.exit(0)); `); @@ -77,16 +121,22 @@ function writeSession(name, id, messages) { // Session ids are UUIDs; main drops list entries with any other id. const SMALL_ID = "11111111-2222-4333-8444-000000000001"; const BIG_ID = "11111111-2222-4333-8444-000000000002"; +const ASK_ID = "11111111-2222-4333-8444-000000000003"; const smallFile = writeSession("2026-01-01_small.jsonl", SMALL_ID, ["hello", "hi"]); +const askFile = writeSession("2026-01-03_ask.jsonl", ASK_ID, ["ask me", "sure"]); writeSession("2026-01-02_big.jsonl", BIG_ID, Array.from({ length: 200 }, (_, i) => `${i} ${"x".repeat(10_000)}`)); assert.ok(statSync(join(sessionsDir, "-project", "2026-01-02_big.jsonl")).size > 2_000_000); // Faults the adapter injects once each, and what it observed. const faults = { loseStdin: false, cutUplinkBeforeApply: false, cutUplinkAfterApply: false }; -const seen = { cuts: [], blobUploads: 0 }; +const seen = { cuts: [], blobUploads: 0, posting: 0 }; const server = createServer(async (req, res) => { const url = new URL(req.url, "http://127.0.0.1"); + if (req.method === "POST") { + seen.posting += 1; + res.once("close", () => { seen.posting -= 1; }); + } const chunks = []; for await (const chunk of req) chunks.push(chunk); const body = Buffer.concat(chunks); @@ -148,7 +198,21 @@ const server = createServer(async (req, res) => { let hostId; let daemon; let daemonLog = ""; -const sessions = []; + +/** A restart of the web server as the daemon sees it: the hub, the sessions and + * the resume state start over, while the daemon and its omp children run on. */ +async function restartWeb() { + // Nothing in flight: an uplink batch applied here but never acked would reach the next server again. + await waitFor(() => seen.posting === 0, "the uplink to settle"); + await sleep(50); + for (const link of globalThis.__ompHostHub.links.values()) { + clearInterval(link.pingTimer); + clearTimeout(link.offlineTimer); + } + for (const name of ["__ompHostHub", "__ompHostLists", "__ompSessions", "__ompStartLocks", "__ompExitedSessions", "__ompResumeTracker"]) globalThis[name] = undefined; + // The daemon's downlink drops with the old process: it redials the new one. + server.closeAllConnections(); +} function waitFor(predicate, what, timeoutMs = 20_000) { return new Promise((resolve, reject) => { @@ -186,7 +250,8 @@ before(async () => { }); after(async () => { - for (const session of sessions) await session.destroyAndWait(); + // This run's wrappers only: those of a server restartWeb replaced died with it. + for (const session of new Set(globalThis.__ompSessions?.values() ?? [])) await session.destroyAndWait(); if (daemon && daemon.exitCode === null) { const exited = new Promise((resolve) => daemon.once("exit", resolve)); daemon.kill("SIGTERM"); @@ -242,7 +307,6 @@ test("the host refuses session paths outside its sessions directory", async () = test("a remote session streams a reply with no frame lost or duplicated across link breaks", async () => { const remote = hub.getHost(hostId); const { session } = await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote); - sessions.push(session); assert.equal(session.host, remote); const texts = []; let ended = false; @@ -258,3 +322,72 @@ test("a remote session streams a reply with no frame lost or duplicated across l assert.deepEqual(seen.cuts, ["downlink", "uplink-before-apply", "uplink-after-apply"]); assert.deepEqual(texts, Array.from({ length: FRAMES }, (_, i) => i + 1)); }); + +test("a restarted web server adopts a running omp child: the same pid streams on with no gap or duplicate, and nothing resumes it", async (t) => { + saveWebServerSettings({ autoResumeSessions: true }); + const adopt = AgentSessionWrapper.prototype.adopt; + t.after(() => { + AgentSessionWrapper.prototype.adopt = adopt; + saveWebServerSettings({ autoResumeSessions: false }); + }); + const { session } = await startRpcSession(SMALL_ID, smallFile, projectDir, undefined, false, projectDir, undefined, hub.getHost(hostId)); + const texts = []; + session.onEvent((event) => { + if (event.type === "message_update") texts.push(Number(event.message.content[0].text)); + }); + await session.send({ type: "prompt", message: "slow" }); + await waitFor(() => texts.length === SLOW_HALF, "the first half of the run"); + const interrupted = join(mainAgentDir, `omp-web-interrupted-sessions-${process.pid}.json`); + await waitFor(() => existsSync(interrupted) && readFileSync(interrupted, "utf8").includes(SMALL_ID), "the run to be recorded for resume"); + + // Watch the next wrapper from its first frame: frames held across the restart are applied during adopt(). + const adopted = new Map(); + AgentSessionWrapper.prototype.adopt = function (replay) { + const events = []; + this.onEvent((event) => events.push(event), { internal: true }); + adopted.set(this, events); + return adopt.call(this, replay); + }; + await restartWeb(); + // As instrumentation does when the new server starts. + await resumeInterruptedSessions(); + writeFileSync(slowGo, ""); + await waitFor(() => getRpcSession(SMALL_ID), "the adoption"); + const events = adopted.get(getRpcSession(SMALL_ID)); + await waitFor(() => events.some((event) => event.type === "agent_end"), "the run to end"); + for (const event of events) if (event.type === "message_update") texts.push(Number(event.message.content[0].text)); + assert.deepEqual(texts, Array.from({ length: SLOW_FRAMES }, (_, i) => i + 1)); + + const log = ompLog(); + const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === SMALL_ID); + assert.equal(starts.length, 1, "no second child was spawned"); + const handshakes = log.filter((entry) => entry.pid === starts[0].pid && entry.command?.type === "negotiate_protocol"); + assert.equal(handshakes.length, 2, "the new server re-synced the same child"); + assert.equal(log.some((entry) => entry.command?.message === RESUME_PROMPT), false, "no resume prompt"); +}); + +test("a run waiting on an ask shows the dialog again after a web restart, and the answer reaches the same omp child", async () => { + const { session } = await startRpcSession(ASK_ID, askFile, projectDir, undefined, false, projectDir, undefined, hub.getHost(hostId)); + let asked = false; + session.onEvent((event) => { + if (event.type === "extension_ui_request" && event.id === "q1") asked = true; + }); + await session.send({ type: "prompt", message: "ask" }); + await waitFor(() => asked, "the ask"); + + await restartWeb(); + await waitFor(() => getRpcSession(ASK_ID), "the adoption"); + // A tab opening the session after the restart. + const events = []; + const adopted = getRpcSession(ASK_ID); + adopted.onEvent((event) => events.push(event)); + assert.equal(events.find((event) => event.type === "extension_ui_request" && event.id === "q1")?.method, "ask"); + await adopted.send({ type: "extension_ui_response", id: "q1", answers: [{ id: "q", selectedOptions: ["A"] }] }); + await waitFor(() => events.some((event) => event.type === "agent_end"), "the answered run to end"); + assert.ok(events.some((event) => event.type === "message_update" && event.message.content[0].text === "answered A")); + + const log = ompLog(); + const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === ASK_ID); + assert.equal(starts.length, 1, "no second child was spawned"); + assert.ok(log.some((entry) => entry.pid === starts[0].pid && entry.command?.type === "extension_ui_response" && entry.command.id === "q1")); +}); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index cb4ec4266..61119c6f0 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -3087,8 +3087,8 @@ test("a session the host still runs an orphan child for spawns only after the or const { linkHost } = await import("./hosts/link-driver.test-helper.mjs"); const id = "11111111-2222-4333-8444-888888888888"; const sessionFile = `/remote/sessions/${id}.jsonl`; - // This server restarted while the host kept running the session's child. - const link = await linkHost("Survivor box", { channels: [{ ch: "orphan", sessionId: id, pending: [] }] }); + // This server restarted while the host kept running the session's child (one it cannot adopt: no replay listed). + const link = await linkHost("Survivor box", { channels: [{ ch: "orphan", sessionId: id, pending: null }] }); let session; t.after(async () => { hub.closeHostLink(link.id); diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index dc15ad920..51e1c261f 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -6,7 +6,7 @@ import { join } from "node:path"; import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { createJiti } from "jiti"; -import { LinkDriver } from "./hosts/link-driver.test-helper.mjs"; +import { LinkDriver, listedSession, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; const jiti = createJiti(import.meta.url); /** A new omp-web process: fresh tracker, same agent dir. */ @@ -18,6 +18,7 @@ const { EXIT_GRACE_MS, markShuttingDown, recordRunningSessions, resumeOnHostLink const { saveWebServerSettings } = await jiti.import("./web-settings.ts"); const hub = await jiti.import("./hosts/hub.ts"); const { createHost } = await jiti.import("./hosts/registry.ts"); +const { getRpcSession } = await jiti.import("./rpc-manager.ts"); /** Fresh agent dir and tracker per test; the resume setting starts as given. */ function setup(t, { enabled }) { @@ -160,8 +161,9 @@ test("a remote entry resumes after its host's hello, exactly once", async (t) => assert.deepEqual(resumed, [], "waits for the host to link"); // The orphan wait is startRpcSession's (rpc-manager.test.mjs); resume starts on hello. + // With no replay listed the child cannot be adopted: it is killed and the run resumes. const link = new LinkDriver(host.id, token); - await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id, pending: [] }] }); + await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id, pending: null }] }); await sleep(10); assert.deepEqual(resumed, [remote]); @@ -170,3 +172,31 @@ test("a remote entry resumes after its host's hello, exactly once", async (t) => await sleep(10); assert.deepEqual(resumed, [remote], "a later hello resumes nothing again"); }); + +test("a remote entry whose child the server adopts on hello is not resumed", async (t) => { + let link = null; + // Before setup's cleanup: disposing the wrapper records running sessions in this test's agent dir. + t.after(async () => { + if (!link) return; + const disposing = getRpcSession(B.id)?.destroyAndWait(); + await link.post({ type: "exit", ch: "live", code: 0, signal: null }); + await disposing; + hub.closeHostLink(link.id); + }); + const { listPath } = setup(t, { enabled: true }); + const { host, token } = createHost("Adopted laptop"); + const remote = { id: B.id, advisor: false, hostId: host.id }; + writeFileSync(listPath, JSON.stringify({ sessions: [remote] })); + restart(); + const resumed = []; + resumeOnHostLink(takeInterruptedSessions(), async (entry) => { + resumed.push(entry); + }); + + link = new LinkDriver(host.id, token); + await link.dial({ channels: [{ ch: "live", sessionId: remote.id, pending: [] }] }); + link.serve({ listSessions: () => [listedSession(remote.id)] }, ompChild(link, remote.id, { state: { isStreaming: true } })); + await until(() => getRpcSession(remote.id), "the adoption"); + await sleep(10); + assert.deepEqual(resumed, [], "the run goes on in the adopted child"); +}); diff --git a/lib/session-resume.ts b/lib/session-resume.ts index bca4947c6..9fa8884f9 100644 --- a/lib/session-resume.ts +++ b/lib/session-resume.ts @@ -2,7 +2,7 @@ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, wri import { uptime } from "os"; import { resolve } from "path"; import { isLinkUp } from "./hosts/host"; -import { getHost, onHostHello } from "./hosts/hub"; +import { adoptedChild, getHost, onHostHello } from "./hosts/hub"; import { getAgentDir } from "./omp/paths"; import { isValidSessionId } from "./session-file-references-core"; import { isRecord } from "./type-guards"; @@ -200,12 +200,13 @@ export function takeInterruptedSessions(): InterruptibleSession[] { /** * Resume remote entries once their host links, once only. startRpcSession * waits for any orphan child of the session the host still runs (spec Rules - * → Reattach). A host already linked in this run said hello before this ran; - * a host revoked since is skipped. + * → Reattach). A child the server adopts on that hello runs on: its entry is + * dropped. A host already linked in this run said hello before this ran; a + * host revoked since is skipped. */ export function resumeOnHostLink(entries: InterruptibleSession[], resume: (entry: InterruptibleSession) => Promise): void { // An unhandled rejection stops the server (instrumentation.node.ts). - const start = (entry: InterruptibleSession) => void resume(entry).catch(() => {}); + const start = (entry: InterruptibleSession) => void adoptedChild(entry.hostId, entry.id).then((adopted) => adopted ? undefined : resume(entry)).catch(() => {}); const waiting = new Map(); for (const entry of entries) { const status = getHost(entry.hostId)?.status(); From fb867373e4dbcb46b0e6f035ba22b1234a86223c Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 21:04:37 +0000 Subject: [PATCH 10/36] fix(hosts): a graceful stop leaves linked children running, the daemon tracks each child's current session, and a start during adoption joins it --- lib/hosts/daemon.test.mjs | 41 ++++++++++++- lib/hosts/daemon.ts | 9 ++- lib/hosts/hub.test.mjs | 57 +++++++++++++++++- lib/hosts/hub.ts | 2 - lib/hosts/link-integration.test.mjs | 92 ++++++++++++++++++++--------- lib/hosts/pending-requests.test.mjs | 34 +++++++++-- lib/hosts/pending-requests.ts | 18 ++++-- lib/rpc-manager.test.mjs | 18 ++++++ lib/rpc-manager.ts | 21 +++++-- lib/session-resume.test.mjs | 2 + 10 files changed, 241 insertions(+), 53 deletions(-) diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index 260b1beba..affe57b9c 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -32,7 +32,9 @@ after(() => { 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:readline").createInterface({ input: process.stdin }).on("line", (line) => { - const { type } = JSON.parse(line); + const command = JSON.parse(line); + const { type } = command; + if (type === "state") process.stdout.write(JSON.stringify({ type: "response", id: "g1", command: "get_state", success: true, data: { sessionId: command.sessionId } }) + "\\n"); if (type === "flood") for (let i = 0; i < 400; i++) process.stdout.write(JSON.stringify({ type: "x", i, pad: "y".repeat(100_000) }) + "\\n"); if (type === "huge") process.stdout.write(JSON.stringify({ type: "x", pad: "y".repeat(9 * 1024 * 1024) }) + "\\n"); if (type === "echo") process.stdout.write('{"type":"echoed"}\\n'); @@ -450,6 +452,43 @@ test("after a link drop the next hello carries each channel's open blocking requ } }); +test("a channel's hello names the session its child last reported in get_state", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + const A = "11111111-2222-4333-8444-0000000000aa"; + const B = "11111111-2222-4333-8444-0000000000bb"; + const fileA = join(process.env.PI_CODING_AGENT_DIR, "sessions", "-w", "a.jsonl"); + mkdirSync(dirname(fileA), { recursive: true }); + writeFileSync(fileA, `${JSON.stringify({ type: "session", version: 3, id: A, cwd: scratch, timestamp: "2026-01-01T00:00:00.000Z" })}\n`); + const relink = async (count) => { + server.downlink.close(); + await waitFor(() => server.hellos.length === count, "the relink"); + return server.hellos[count - 1].channels.map(({ ch, sessionId }) => ({ ch, sessionId })); + }; + const reported = async (sessionId) => { + const before = server.up.filter((m) => m.type === "stdout").length; + server.send({ type: "stdin", ch: "fresh", line: `${JSON.stringify({ type: "state", sessionId })}\n` }); + await waitFor(() => server.up.filter((m) => m.type === "stdout").length > before, "the get_state response"); + }; + try { + await waitFor(() => server.downlink, "the downlink"); + server.send({ type: "req", id: "spawn-a", op: "spawn", args: { ch: "resumed", cwd: scratch, recordedCwd: null, sessionFile: fileA, advisor: false } }); + await waitFor(() => server.res("spawn-a"), "the resume"); + assert.equal(server.res("spawn-a").ok, true, JSON.stringify(server.res("spawn-a"))); + await spawnChannel(server, "fresh"); + assert.deepEqual(await relink(2), [{ ch: "resumed", sessionId: A }, { ch: "fresh", sessionId: null }]); + // A brand-new session names itself on its first get_state; a switch to another session on the next one. + await reported(A); + assert.deepEqual(await relink(3), [{ ch: "resumed", sessionId: A }, { ch: "fresh", sessionId: A }]); + await reported(B); + assert.deepEqual(await relink(4), [{ ch: "resumed", sessionId: A }, { ch: "fresh", sessionId: B }]); + } finally { + await daemon.stop(); + log.restore(); + } +}); + test("spawn reports a fallback when a new session's cwd is missing on this host", async () => { const log = captureLog(); const server = scriptedServer(); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 7c93289fc..70ccb3871 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -44,10 +44,9 @@ type Unsequenced = M extends { seq: number } ? Omit : never; interface Channel { transport: RpcTransport; - sessionId: string | null; /** Bytes of this child's output waiting for an uplink ack. */ buffered: number; - /** Open blocking requests, replayed in the next hello. */ + /** Open blocking requests and the child's current session, both in the next hello. */ pending: PendingRequests; } @@ -460,8 +459,8 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: transport.killTree(true); throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); } - const pending = new PendingRequests(LINK_LIMITS.pendingBytes); - channels.set(ch, { transport, sessionId: file ? readSessionHeaderSync(file)?.id ?? null : null, buffered: 0, pending }); + const pending = new PendingRequests(LINK_LIMITS.pendingBytes, file ? readSessionHeaderSync(file)?.id ?? null : null); + channels.set(ch, { transport, buffered: 0, pending }); transport.onLine((line) => { pending.noteStdout(line); output(ch, { type: "stdout", ch, line }); @@ -493,7 +492,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: platform: process.platform, home: homedir(), ack: down.acked, - channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.sessionId, pending: replay ? channel.pending.lines() : null })), + channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.pending.sessionId, pending: replay ? channel.pending.lines() : null })), }); let hello: string; try { diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 1296de8b6..4e14f9916 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -19,7 +19,7 @@ const jiti = createJiti(import.meta.url); const hub = await jiti.import("./hub.ts"); const { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_LIMITS, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION } = await jiti.import("./link-protocol.ts"); const { createHost } = await jiti.import("./registry.ts"); -const { getRpcSession } = await jiti.import("../rpc-manager.ts"); +const { getRpcSession, startRpcSession } = await jiti.import("../rpc-manager.ts"); const { resumeOnHostLink } = await jiti.import("../session-resume.ts"); const { LinkDriver, linkHost, listedSession, ompChild, until } = await import("./link-driver.test-helper.mjs"); @@ -466,7 +466,14 @@ test("on hello a listed child with no transport that cannot be adopted is an orp const ADOPTED = "11111111-2222-4333-8444-aaaaaaaaaa01"; +/** Adoption logs each kill and wrapper dispose; the tests assert on what reaches the daemon instead. */ +function quiet(t) { + t.mock.method(console, "warn", () => {}); + t.mock.method(console, "info", () => {}); +} + test("on hello a listed child of a session its host lists is adopted: no kill, its wrapper registered", async (t) => { + quiet(t); const link = await linkHost("Adopter", { channels: [{ ch: "live", sessionId: ADOPTED, pending: [] }] }); t.after(async () => { const disposing = getRpcSession(ADOPTED)?.destroyAndWait(); @@ -493,6 +500,7 @@ test("on hello a listed child of a session its host lists is adopted: no kill, i }); test("on hello a listed child of a session its host does not list is killed", async (t) => { + quiet(t); const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa02"; const link = await linkHost("Forgetful", { channels: [{ ch: "stray", sessionId, pending: [] }] }); t.after(() => hub.closeHostLink(link.id)); @@ -514,6 +522,7 @@ test("a child listed without its replay or without a session is killed without a }); test("a failed adoption kills the child, blocks a start until it exits, then resumes the run once", async (t) => { + quiet(t); const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa04"; const { host, token } = createHost("Wedged"); t.after(() => hub.closeHostLink(host.id)); @@ -545,6 +554,52 @@ test("a failed adoption kills the child, blocks a start until it exits, then res assert.equal(getRpcSession(sessionId), undefined); }); +test("a start while the hello's session lookup is in flight joins the adoption: no kill, no second child", async (t) => { + quiet(t); + const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa05"; + const link = await linkHost("Busy", { channels: [{ ch: "live", sessionId, pending: [] }] }); + t.after(async () => { + // The child below exits on its kill. + await getRpcSession(sessionId)?.destroyAndWait(); + hub.closeHostLink(link.id); + }); + const lookup = Promise.withResolvers(); + let looking = false; + const kills = []; + const spawns = []; + const omp = ompChild(link, sessionId); + link.serve({ + async listSessions() { + looking = true; + await lookup.promise; + return [listedSession(sessionId)]; + }, + async spawn(args) { + spawns.push(args.ch); + await link.post({ type: "stdout", ch: args.ch, line: JSON.stringify({ type: "ready", supportedProtocolVersions: [1, 2] }) }); + return { cwd: args.cwd, fellBack: false, launchAdvisor: false, autoApproveExtension: false }; + }, + sessionFileExists: () => true, + invalidateSessionLists: () => null, + }, async (message) => { + if (message.type === "kill") { + kills.push(message.ch); + return link.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }); + } + return omp(message); + }); + await until(() => looking, "the session lookup"); + // A tab sends the session a prompt meanwhile. + const starting = startRpcSession(sessionId, listedSession(sessionId).path, "/w", undefined, false, "/w", undefined, hub.getHost(link.id)); + await new Promise((resolve) => setTimeout(resolve, 20)); + lookup.resolve(); + const { session } = await starting; + assert.equal(session.adopted, true); + assert.equal(getRpcSession(sessionId), session); + assert.deepEqual(spawns, []); + assert.deepEqual(kills, []); +}); + for (const [op, call, value] of [ ["archiveSession", (ops, id) => ops.archiveSession(id), { archivedPath: "/a" }], ["deleteSession", (ops, id) => ops.deleteSession(id, []), {}], diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 3a462ad9e..23401b47b 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -431,8 +431,6 @@ async function adopt(link: Link, child: RemoteRpcTransport, sessionId: string, r // rpc-manager imports this module. Awaiting it also defers the lookup past // openDownlink, which marks the link up (ops need it) after reattach. const { adoptRpcSession } = await import("../rpc-manager"); - // shortcut: a start of this session during the lookup takes its lock first, so adoptRpcSession - // refuses and the child is killed and resumed; hold the start lock across the lookup if that shows up. const session = (await listSessions()).find((entry) => entry.id === sessionId); if (!session) throw new Error("its session is unknown"); await adoptRpcSession({ host: link.host, transport: child, sessionId, cwd: session.cwd, replay }); diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index ffc910349..1424bf657 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -46,10 +46,10 @@ function writeFakeOmp(file, source) { } const FRAMES = 200; -// "slow": the first half at once, the rest one by one once the test creates slowGo. +// "slow": the first half at once, the rest one by one once the test creates slowGo(sessionId). const SLOW_HALF = 20; const SLOW_FRAMES = 80; -const slowGo = join(scratch, "slow-go"); +const slowGo = (sessionId) => join(scratch, `go-${sessionId}`); // Every omp child appends {pid, kind: "start" | "stdin", ...} here. const ompLogFile = join(scratch, "omp.log"); const ompLog = () => (existsSync(ompLogFile) ? readFileSync(ompLogFile, "utf8").split("\n").filter(Boolean).map((line) => JSON.parse(line)) : []); @@ -61,8 +61,15 @@ const out = (frame) => process.stdout.write(JSON.stringify(frame) + "\\n"); const log = (entry) => fs.appendFileSync(${JSON.stringify(ompLogFile)}, JSON.stringify({ pid: process.pid, ...entry }) + "\\n"); const resumeAt = process.argv.indexOf("--resume"); const resumed = resumeAt === -1 ? null : process.argv[resumeAt + 1]; -const sessionFile = resumed ?? path.join(${JSON.stringify(sessionsDir)}, "-project", "fake-live.jsonl"); -const sessionId = resumed ? JSON.parse(fs.readFileSync(resumed, "utf8").split("\\n")[0]).id : "remote-live"; +// A new session is written on its first prompt, as omp does. +const sessionId = resumed ? JSON.parse(fs.readFileSync(resumed, "utf8").split("\\n")[0]).id : require("node:crypto").randomUUID(); +const sessionFile = resumed ?? path.join(${JSON.stringify(sessionsDir)}, "-project", sessionId + ".jsonl"); +const write = (message) => { + if (fs.existsSync(sessionFile)) return; + const at = new Date().toISOString(); + const lines = [{ type: "session", version: 3, id: sessionId, cwd: ${JSON.stringify(projectDir)}, timestamp: at }, { type: "message", id: "m0", parentId: null, timestamp: at, message: { role: "user", content: message } }]; + fs.writeFileSync(sessionFile, lines.map((line) => JSON.stringify(line)).join("\\n") + "\\n"); +}; let streaming = false; const update = (text) => out({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: String(text) }] } }); const end = () => { @@ -84,6 +91,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l } if (command.type !== "prompt") return reply({}); reply({ agentInvoked: true }); + write(command.message); streaming = true; out({ type: "agent_start" }); if (command.message === "ask") return out({ type: "extension_ui_request", id: "q1", method: "ask", questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }); @@ -91,7 +99,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l for (let i = 1; i <= ${SLOW_HALF}; i++) update(i); let sent = ${SLOW_HALF}; const timer = setInterval(() => { - if (!fs.existsSync(${JSON.stringify(slowGo)})) return; + if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; update(++sent); if (sent === ${SLOW_FRAMES}) { clearInterval(timer); @@ -129,7 +137,8 @@ assert.ok(statSync(join(sessionsDir, "-project", "2026-01-02_big.jsonl")).size > // Faults the adapter injects once each, and what it observed. const faults = { loseStdin: false, cutUplinkBeforeApply: false, cutUplinkAfterApply: false }; -const seen = { cuts: [], blobUploads: 0, posting: 0 }; +// `kills`: the channel of each `kill` main sent down to the daemon. +const seen = { cuts: [], blobUploads: 0, posting: 0, kills: [] }; const server = createServer(async (req, res) => { const url = new URL(req.url, "http://127.0.0.1"); @@ -190,6 +199,7 @@ const server = createServer(async (req, res) => { req.socket.destroy(); return; } + for (const [, ch] of Buffer.from(value).toString().matchAll(/"type":"kill","ch":"([^"]+)"/g)) seen.kills.push(ch); res.write(value); } res.end(); @@ -199,10 +209,14 @@ let hostId; let daemon; let daemonLog = ""; -/** A restart of the web server as the daemon sees it: the hub, the sessions and - * the resume state start over, while the daemon and its omp children run on. */ +/** A restart of the web server as the daemon sees it: the old process runs its shutdown + * handlers with the daemon's link still open, then the hub, the sessions and the resume + * state start over, while the daemon and its omp children run on. */ async function restartWeb() { + // A deploy stops the service: SIGTERM, then connections close as the process exits. + process.emit("SIGTERM"); // Nothing in flight: an uplink batch applied here but never acked would reach the next server again. + // The wait also lets anything the shutdown queued on the downlink reach the daemon. await waitFor(() => seen.posting === 0, "the uplink to settle"); await sleep(50); for (const link of globalThis.__ompHostHub.links.values()) { @@ -304,9 +318,13 @@ test("the host refuses session paths outside its sessions directory", async () = ); }); +/** The new session the streaming test starts; it stays live, idle, on the daemon. */ +let countSessionId; + test("a remote session streams a reply with no frame lost or duplicated across link breaks", async () => { const remote = hub.getHost(hostId); - const { session } = await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote); + const { session, realSessionId } = await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote); + countSessionId = realSessionId; assert.equal(session.host, remote); const texts = []; let ended = false; @@ -323,24 +341,33 @@ test("a remote session streams a reply with no frame lost or duplicated across l assert.deepEqual(texts, Array.from({ length: FRAMES }, (_, i) => i + 1)); }); -test("a restarted web server adopts a running omp child: the same pid streams on with no gap or duplicate, and nothing resumes it", async (t) => { +test("a restarted web server adopts its running omp children, resumed or new: each pid streams on with no gap or duplicate, no kill reaches the daemon, nothing resumes them", async (t) => { saveWebServerSettings({ autoResumeSessions: true }); const adopt = AgentSessionWrapper.prototype.adopt; t.after(() => { AgentSessionWrapper.prototype.adopt = adopt; saveWebServerSettings({ autoResumeSessions: false }); }); - const { session } = await startRpcSession(SMALL_ID, smallFile, projectDir, undefined, false, projectDir, undefined, hub.getHost(hostId)); - const texts = []; - session.onEvent((event) => { - if (event.type === "message_update") texts.push(Number(event.message.content[0].text)); - }); - await session.send({ type: "prompt", message: "slow" }); - await waitFor(() => texts.length === SLOW_HALF, "the first half of the run"); + const remote = hub.getHost(hostId); + // A resumed session, and a new one (no --resume) that names itself only in its get_state. + const runs = [ + await startRpcSession(SMALL_ID, smallFile, projectDir, undefined, false, projectDir, undefined, remote), + await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote), + ].map(({ session, realSessionId }) => ({ session, id: realSessionId, texts: [] })); + for (const run of runs) { + run.session.onEvent((event) => { + if (event.type === "message_update") run.texts.push(Number(event.message.content[0].text)); + }); + await run.session.send({ type: "prompt", message: "slow" }); + } + await waitFor(() => runs.every((run) => run.texts.length === SLOW_HALF), "the first half of each run"); const interrupted = join(mainAgentDir, `omp-web-interrupted-sessions-${process.pid}.json`); - await waitFor(() => existsSync(interrupted) && readFileSync(interrupted, "utf8").includes(SMALL_ID), "the run to be recorded for resume"); + await waitFor(() => existsSync(interrupted) && runs.every((run) => readFileSync(interrupted, "utf8").includes(run.id)), "the runs to be recorded for resume"); + // Live on the daemon too: the earlier test's idle new session. + const ids = [...runs.map((run) => run.id), countSessionId]; + const killsBefore = seen.kills.length; - // Watch the next wrapper from its first frame: frames held across the restart are applied during adopt(). + // Watch each next wrapper from its first frame: frames held across the restart are applied during adopt(). const adopted = new Map(); AgentSessionWrapper.prototype.adopt = function (replay) { const events = []; @@ -351,18 +378,23 @@ test("a restarted web server adopts a running omp child: the same pid streams on await restartWeb(); // As instrumentation does when the new server starts. await resumeInterruptedSessions(); - writeFileSync(slowGo, ""); - await waitFor(() => getRpcSession(SMALL_ID), "the adoption"); - const events = adopted.get(getRpcSession(SMALL_ID)); - await waitFor(() => events.some((event) => event.type === "agent_end"), "the run to end"); - for (const event of events) if (event.type === "message_update") texts.push(Number(event.message.content[0].text)); - assert.deepEqual(texts, Array.from({ length: SLOW_FRAMES }, (_, i) => i + 1)); + for (const run of runs) writeFileSync(slowGo(run.id), ""); + await waitFor(() => ids.every((id) => getRpcSession(id)), "the adoptions"); + for (const run of runs) { + const events = adopted.get(getRpcSession(run.id)); + await waitFor(() => events.some((event) => event.type === "agent_end"), "the run to end"); + for (const event of events) if (event.type === "message_update") run.texts.push(Number(event.message.content[0].text)); + assert.deepEqual(run.texts, Array.from({ length: SLOW_FRAMES }, (_, i) => i + 1), run.id); + } + assert.deepEqual(seen.kills.slice(killsBefore), [], "no kill reached the daemon"); const log = ompLog(); - const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === SMALL_ID); - assert.equal(starts.length, 1, "no second child was spawned"); - const handshakes = log.filter((entry) => entry.pid === starts[0].pid && entry.command?.type === "negotiate_protocol"); - assert.equal(handshakes.length, 2, "the new server re-synced the same child"); + for (const id of ids) { + const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === id); + assert.equal(starts.length, 1, `no second child was spawned for ${id}`); + const handshakes = log.filter((entry) => entry.pid === starts[0].pid && entry.command?.type === "negotiate_protocol"); + assert.equal(handshakes.length, 2, `the new server re-synced the same child of ${id}`); + } assert.equal(log.some((entry) => entry.command?.message === RESUME_PROMPT), false, "no resume prompt"); }); @@ -375,6 +407,7 @@ test("a run waiting on an ask shows the dialog again after a web restart, and th await session.send({ type: "prompt", message: "ask" }); await waitFor(() => asked, "the ask"); + const killsBefore = seen.kills.length; await restartWeb(); await waitFor(() => getRpcSession(ASK_ID), "the adoption"); // A tab opening the session after the restart. @@ -390,4 +423,5 @@ test("a run waiting on an ask shows the dialog again after a web restart, and th const starts = log.filter((entry) => entry.kind === "start" && entry.sessionId === ASK_ID); assert.equal(starts.length, 1, "no second child was spawned"); assert.ok(log.some((entry) => entry.pid === starts[0].pid && entry.command?.type === "extension_ui_response" && entry.command.id === "q1")); + assert.deepEqual(seen.kills.slice(killsBefore).filter((ch) => ch === getRpcSession(ASK_ID).proc.transport.ch), [], "no kill reached the asking child"); }); diff --git a/lib/hosts/pending-requests.test.mjs b/lib/hosts/pending-requests.test.mjs index 5ff790240..4bdf3a11e 100644 --- a/lib/hosts/pending-requests.test.mjs +++ b/lib/hosts/pending-requests.test.mjs @@ -38,17 +38,39 @@ test("host_tool_result on stdin closes the call; omp's UI cancel closes a dialog assert.deepEqual(pending.lines(), []); }); -/** A blocking request omp would chunk: RpcFrameDecoder only accepts chunked frames of at least 1 MiB in 256 KiB pieces (five lines here). */ -function chunkedRequest(id) { - const frame = Buffer.from(line({ type: "extension_ui_request", id, method: "editor", title: "t", prefill: randomBytes(600_000).toString("hex") })); +/** `frame` as omp chunks it: RpcFrameDecoder only accepts chunked frames of at least 1 MiB in 256 KiB pieces. */ +function chunked(frame, chunkId) { + const bytes = Buffer.from(line(frame)); const size = 256 * 1024; - const count = Math.ceil(frame.byteLength / size); + const count = Math.ceil(bytes.byteLength / size); return Array.from({ length: count }, (_, index) => line({ - type: "rpc_chunk", chunkId: `k-${id}`, index, count, byteLength: frame.byteLength, - data: frame.subarray(index * size, (index + 1) * size).toString("base64"), + type: "rpc_chunk", chunkId, index, count, byteLength: bytes.byteLength, + data: bytes.subarray(index * size, (index + 1) * size).toString("base64"), })); } +/** A blocking request omp would chunk (five lines). */ +function chunkedRequest(id) { + return chunked({ type: "extension_ui_request", id, method: "editor", title: "t", prefill: randomBytes(600_000).toString("hex") }, `k-${id}`); +} + +test("the session a successful get_state reports, plain or chunked, is the child's session from then on", () => { + const A = "11111111-2222-4333-8444-00000000000a"; + const B = "11111111-2222-4333-8444-00000000000b"; + const pending = new PendingRequests(LIMIT, A); + assert.equal(pending.sessionId, A); + pending.noteStdout(line({ type: "response", id: "1", command: "get_state", success: false, error: "busy" })); + pending.noteStdout(line({ type: "response", id: "2", command: "get_session_stats", success: true, data: { sessionId: B } })); + assert.equal(pending.sessionId, A, "only a successful get_state names the session"); + for (const chunk of chunked({ type: "response", id: "3", command: "get_state", success: true, data: { sessionId: B, pad: randomBytes(600_000).toString("hex") } }, "s3")) { + pending.noteStdout(chunk); + } + assert.equal(pending.sessionId, B); + assert.deepEqual(pending.lines(), [], "a response is not an open request"); + pending.noteStdout(line({ type: "response", id: "4", command: "get_state", success: true, data: { sessionId: "not-a-session" } })); + assert.equal(pending.sessionId, null, "an id main could not adopt names no session"); +}); + test("a chunked request keeps all of its rpc_chunk lines in order", () => { const chunks = chunkedRequest("big"); const pending = new PendingRequests(4 * LIMIT); diff --git a/lib/hosts/pending-requests.ts b/lib/hosts/pending-requests.ts index 4b7b1dffa..85d266032 100644 --- a/lib/hosts/pending-requests.ts +++ b/lib/hosts/pending-requests.ts @@ -1,12 +1,13 @@ -// The blocking requests still open on one omp child, kept so the daemon's -// `hello` can replay them to a main server that missed them (omp has no -// command listing them, and they never time out). +// What a main server that missed a child's output needs from it in the +// daemon's `hello`: the blocking requests still open on it (omp has no command +// listing them, and they never time out), and the session it runs now. import { BLOCKING_UI_METHODS } from "../notification-events"; import { RpcFrameDecoder } from "../omp/rpc-frame"; +import { isValidSessionId } from "../session-file-references-core"; import { isRecord } from "../type-guards"; // A line without one of these types cannot matter: skips JSON-parsing streamed output. -const STDOUT_TYPES = /"(?:rpc_chunk|host_tool_call|host_tool_cancel|host_uri_request|host_uri_cancel|extension_ui_request)"/; +const STDOUT_TYPES = /"(?:rpc_chunk|host_tool_call|host_tool_cancel|host_uri_request|host_uri_cancel|extension_ui_request|get_state)"/; const STDIN_TYPES = /"(?:host_tool_result|host_uri_result|extension_ui_response)"/; /** Raw lines, or null once they no longer fit under the cap. */ @@ -19,7 +20,9 @@ export class PendingRequests { private chunk: Kept | undefined; private bytes = 0; - constructor(private readonly limitBytes: number) {} + /** `sessionId`: the session the child was started on, until a successful `get_state` names + * another (a new session's first one, a switch or a fork); null for one main could not adopt. */ + constructor(private readonly limitBytes: number, public sessionId: string | null = null) {} noteStdout(line: string): void { if (this.chunk === undefined && !STDOUT_TYPES.test(line)) return; @@ -47,6 +50,11 @@ export class PendingRequests { return; } this.free(kept); + if (frame.type === "response" && frame.command === "get_state" && frame.success === true && isRecord(frame.data)) { + const { sessionId } = frame.data; + this.sessionId = typeof sessionId === "string" && isValidSessionId(sessionId) ? sessionId : null; + return; + } const cancel = frame.type === "host_tool_cancel" || frame.type === "host_uri_cancel" || (frame.type === "extension_ui_request" && frame.method === "cancel"); if (cancel && typeof frame.targetId === "string") this.close(frame.targetId); diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 61119c6f0..395989b7b 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -3694,6 +3694,24 @@ test("a start during adoption joins it; an adopted child is not replaced over -- assert.equal(session.isAlive(), true); }); +test("an adopted child that turns out to run a session another wrapper holds is killed, not registered", async (t) => { + const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const holderId = "11111111-2222-4333-8444-adadadadad0c"; + const listedId = "11111111-2222-4333-8444-adadadadad0d"; + const first = adoptedTransport(holderId); + const holder = await adoptRpcSession({ host: adoptionHost("holder-box", first), transport: first, sessionId: holderId, cwd: "/w", replay: [] }); + t.after(() => holder.destroyAndWait()); + // The host listed this child under the session it last reported; omp has switched to the holder's since. + const stale = adoptedTransport(listedId, { state: { sessionId: holderId } }); + await assert.rejects( + adoptRpcSession({ host: adoptionHost("stale-box", stale), transport: stale, sessionId: listedId, cwd: "/w", replay: [] }), + /already started/, + ); + assert.ok(stale.kills > 0, "the second writer is killed"); + assert.equal(getRpcSession(holderId), holder); + assert.equal(holder.isAlive(), true); +}); + test("an adoption whose get_state times out rejects and kills the child", async (t) => { const { adoptRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); const id = "11111111-2222-4333-8444-adadadadad03"; diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index d9dd064e7..644082464 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2491,7 +2491,12 @@ function getRegistry(): Map { const cleanup = () => { // Children dying from here on are the shutdown, not finished runs. markShuttingDown(); - globalThis.__ompSessions?.forEach((s) => s.destroy()); + // Only this process's own children. A linked host's children run on: its daemon + // keeps them when the link drops, and the next server adopts them (a kill sent + // here could still reach the daemon over a downlink that outlives this handler). + globalThis.__ompSessions?.forEach((s) => { + if (s.host === localHost) s.destroy(); + }); }; process.once("exit", cleanup); process.once("SIGINT", cleanup); @@ -2807,6 +2812,12 @@ export async function startRpcSession( const registry = getRegistry(); const locks = getLocks(); + // A child of this session the host still ran from before a restart of this + // server is being adopted or killed. Waiting here, before the registry and + // the lock, lets a start join an adopted child; a killed one must exit first: + // two children must never write one session file. + if (sessionFile && host !== localHost) await orphanExit(host.id, sessionId); + const existing = registry.get(sessionId); // Union semantics, matching the spawn below and the wrapper identity: // workspace advisor=true forces the flag on. The gate must compare this @@ -2853,9 +2864,6 @@ export async function startRpcSession( // The wrapper needs the process and the process's onExit needs the wrapper; // the holder breaks that cycle (onExit only fires once the child dies). const holder: { wrapper?: AgentSessionWrapper } = {}; - // A child of this session the host still ran from before a restart of this - // server is being killed: two children must never write one session file. - if (sessionFile && host !== localHost) await orphanExit(host.id, sessionId); const spawned = await host.spawnRpc({ cwd, recordedCwd: recordedCwd ?? null, sessionFile, toolNames, advisor: advisor === true, spawnModel }); const proc = new RpcProcess({ cwd: spawned.cwd, @@ -2972,6 +2980,11 @@ export async function adoptRpcSession({ host, transport, sessionId, cwd, replay const adopting = (async () => { try { await created.adopt(replay); + // The host names a child by the session it last reported; one that has since moved + // to a session this server already runs would be its second writer. + if (created.sessionId !== sessionId && (locks.has(created.sessionId) || registry.has(created.sessionId))) { + throw new Error(`Session ${created.sessionId} is already started on this server`); + } } catch (error) { const disposing = created.destroyAndWait("adoption-failed"); // As for a failed resume: until the child really exits, a start for this diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index 51e1c261f..ca0aa24a2 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -174,6 +174,8 @@ test("a remote entry resumes after its host's hello, exactly once", async (t) => }); test("a remote entry whose child the server adopts on hello is not resumed", async (t) => { + // The adoption's wrapper logs its dispose on cleanup. + t.mock.method(console, "info", () => {}); let link = null; // Before setup's cleanup: disposing the wrapper records running sessions in this test's agent dir. t.after(async () => { From 245a86a38cee1cf232b2b3d360a26e5fe3751174 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 21:12:48 +0000 Subject: [PATCH 11/36] fix(hosts): freeze links once the web server starts shutting down --- lib/hosts/hub.ts | 28 +++++++++- lib/hosts/link-integration.test.mjs | 81 ++++++++++++++++++++++++++--- lib/rpc-manager.ts | 9 ++-- 3 files changed, 104 insertions(+), 14 deletions(-) diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 23401b47b..dc1d2d507 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -87,6 +87,8 @@ interface HubState { links: Map; changeListeners: Set<() => void>; helloListeners: Set<(hostId: string, channels: HelloChannel[]) => void>; + /** This server is shutting down (freezeHostLinks): links neither send nor apply anything. */ + frozen: boolean; } declare global { @@ -95,7 +97,7 @@ declare global { // globalThis, like the rpc-manager registry: survives Next.js hot reload. function hub(): HubState { - globalThis.__ompHostHub ??= { links: new Map(), changeListeners: new Set(), helloListeners: new Set() }; + globalThis.__ompHostHub ??= { links: new Map(), changeListeners: new Set(), helloListeners: new Set(), frozen: false }; return globalThis.__ompHostHub; } @@ -164,8 +166,10 @@ function enqueue(link: Link, line: string): void { } } -/** Number, keep until acked, and send; returns the seq. Throws LinkLimitError before recording anything. */ +/** Number, keep until acked, and send; returns the seq. Throws LinkLimitError before recording anything. + * Dropped once frozen (0): a kill, an answer or a command from a stopping server must not reach the children. */ function sendDown(link: Link, body: Unsequenced): number { + if (hub().frozen) return 0; const seq = link.downSeq + 1; const line = encodeLine({ ...body, seq } as DownMessage); link.downSeq = seq; @@ -252,11 +256,26 @@ function currentLink(req: Request, record: HostRecord): Link | null { } const staleLink = () => json({ error: "This link was replaced; wait for the next welcome" }, 409); +// The daemon retries a 503: what it sends lands on the next server instead. +const stopping = () => json({ error: "omp-web is shutting down" }, 503); + +/** + * This server is shutting down. From here on nothing reaches a daemon (sendDown + * drops it), and no hello, uplink batch or blob upload is applied or acked: each + * daemon keeps its children's output unacked and sends it to the next server, + * which adopts the children. Without this a tab closing on the way out would + * answer omp's open host tool calls with an error, and output this server took + * but never showed would be lost to the next one. + */ +export function freezeHostLinks(): void { + hub().frozen = true; +} /** GET /api/hosts/link: the daemon's downlink, an NDJSON stream, opened with the id of the hello it POSTed. */ export async function handleLinkGet(req: Request): Promise { const record = authenticate(req); if (record instanceof Response) return record; + if (hub().frozen) return stopping(); const link = linkFor(record.id); const helloId = req.headers.get(LINK_HELLO_HEADER); const offer = link.helloOffer; @@ -446,6 +465,7 @@ async function adopt(link: Link, child: RemoteRpcTransport, sessionId: string, r export async function handleLinkPost(req: Request): Promise { const record = authenticate(req); if (record instanceof Response) return record; + if (hub().frozen) return stopping(); if (req.headers.has(LINK_HELLO_HEADER)) return handleHelloPost(req, record); // A replaced link's late POST must not reach the current daemon's uplink window. const link = currentLink(req, record); @@ -462,6 +482,7 @@ export async function handleLinkPost(req: Request): Promise { if (error instanceof RequestBodyTooLargeError) return json({ error: "Uplink batch too large" }, 413); return json({ error: "Malformed uplink batch" }, 400); } + if (hub().frozen) return stopping(); // Replaced while the body was arriving. if (link.nonce !== nonce) return staleLink(); sawDaemon(link); @@ -521,6 +542,7 @@ function settle(link: Link, message: Res): void { export async function handleLinkBlob(req: Request, reqId: string): Promise { const record = authenticate(req); if (record instanceof Response) return record; + if (hub().frozen) return stopping(); const link = currentLink(req, record); if (!link) return staleLink(); const nonce = link.nonce; @@ -535,6 +557,7 @@ export async function handleLinkBlob(req: Request, reqId: string): Promise): Promise { const link = linkFor(hostId); const label = labelOf(hostId); + if (hub().frozen) return Promise.reject(new HostOpError(503, "server_stopping", "omp-web is shutting down")); if (!link.nonce || !isLinkUp(link.status)) { return Promise.reject(new HostOpError(503, "host_offline", `${label} is offline`)); } diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 1424bf657..457b7aaf2 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -84,17 +84,31 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l const reply = (data) => out({ type: "response", id: command.id, command: command.type, success: true, data }); if (command.type === "negotiate_protocol") return reply({ protocolVersion: 2 }); if (command.type === "get_state") return reply({ sessionId, sessionFile, isStreaming: streaming, isCompacting: false }); - // A dialog answer is a frame: omp sends no response to it. + // A dialog answer and a host tool result are frames: omp sends no response to them. if (command.type === "extension_ui_response") { update("answered " + command.answers[0].selectedOptions[0]); return end(); } + if (command.type === "host_tool_result") { + update("tool " + command.result.content[0].text); + return end(); + } if (command.type !== "prompt") return reply({}); reply({ agentInvoked: true }); write(command.message); streaming = true; out({ type: "agent_start" }); if (command.message === "ask") return out({ type: "extension_ui_request", id: "q1", method: "ask", questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }); + if (command.message === "tool") { + // A host tool call, then one more frame once the test creates the go file. + out({ type: "host_tool_call", id: "h1", toolCallId: "c1", toolName: "browser_open", arguments: { url: "https://a.test" } }); + const timer = setInterval(() => { + if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; + clearInterval(timer); + update("while stopping"); + }, 25); + return; + } if (command.message === "slow") { for (let i = 1; i <= ${SLOW_HALF}; i++) update(i); let sent = ${SLOW_HALF}; @@ -130,15 +144,17 @@ function writeSession(name, id, messages) { const SMALL_ID = "11111111-2222-4333-8444-000000000001"; const BIG_ID = "11111111-2222-4333-8444-000000000002"; const ASK_ID = "11111111-2222-4333-8444-000000000003"; +const TOOL_ID = "11111111-2222-4333-8444-000000000004"; const smallFile = writeSession("2026-01-01_small.jsonl", SMALL_ID, ["hello", "hi"]); const askFile = writeSession("2026-01-03_ask.jsonl", ASK_ID, ["ask me", "sure"]); +const toolFile = writeSession("2026-01-04_tool.jsonl", TOOL_ID, ["use a tool", "ok"]); writeSession("2026-01-02_big.jsonl", BIG_ID, Array.from({ length: 200 }, (_, i) => `${i} ${"x".repeat(10_000)}`)); assert.ok(statSync(join(sessionsDir, "-project", "2026-01-02_big.jsonl")).size > 2_000_000); // Faults the adapter injects once each, and what it observed. const faults = { loseStdin: false, cutUplinkBeforeApply: false, cutUplinkAfterApply: false }; -// `kills`: the channel of each `kill` main sent down to the daemon. -const seen = { cuts: [], blobUploads: 0, posting: 0, kills: [] }; +// `kills`: the channel of each `kill` main sent down to the daemon; `refusedPosts`: uplink POSTs answered 503. +const seen = { cuts: [], blobUploads: 0, posting: 0, kills: [], refusedPosts: 0 }; const server = createServer(async (req, res) => { const url = new URL(req.url, "http://127.0.0.1"); @@ -169,6 +185,7 @@ const server = createServer(async (req, res) => { return; } response = await linkRoute.POST(request()); + if (response.status === 503) seen.refusedPosts += 1; if (faults.cutUplinkAfterApply && carriesFrames) { // Applied, but the ack never reaches the daemon: it must resend. faults.cutUplinkAfterApply = false; @@ -210,13 +227,13 @@ let daemon; let daemonLog = ""; /** A restart of the web server as the daemon sees it: the old process runs its shutdown - * handlers with the daemon's link still open, then the hub, the sessions and the resume - * state start over, while the daemon and its omp children run on. */ -async function restartWeb() { + * handlers (then `whileStopping`) with the daemon's link still open, then the hub, the + * sessions and the resume state start over, while the daemon and its omp children run on. */ +async function restartWeb({ whileStopping } = {}) { // A deploy stops the service: SIGTERM, then connections close as the process exits. process.emit("SIGTERM"); - // Nothing in flight: an uplink batch applied here but never acked would reach the next server again. - // The wait also lets anything the shutdown queued on the downlink reach the daemon. + await whileStopping?.(); + // Lets anything the stopping server sent down reach the daemon before the link drops. await waitFor(() => seen.posting === 0, "the uplink to settle"); await sleep(50); for (const link of globalThis.__ompHostHub.links.values()) { @@ -425,3 +442,51 @@ test("a run waiting on an ask shows the dialog again after a web restart, and th assert.ok(log.some((entry) => entry.pid === starts[0].pid && entry.command?.type === "extension_ui_response" && entry.command.id === "q1")); assert.deepEqual(seen.kills.slice(killsBefore).filter((ch) => ch === getRpcSession(ASK_ID).proc.transport.ch), [], "no kill reached the asking child"); }); + +test("a stopping web server sends nothing more and takes nothing in: a closing tab rejects no host tool call, and output waits for the next server", async (t) => { + const adopt = AgentSessionWrapper.prototype.adopt; + t.after(() => { + AgentSessionWrapper.prototype.adopt = adopt; + }); + const { session } = await startRpcSession(TOOL_ID, toolFile, projectDir, undefined, false, projectDir, undefined, hub.getHost(hostId)); + await session.send({ type: "set_host_tools", tools: [{ name: "browser_open", description: "Open a page", parameters: { type: "object" } }] }); + const before = []; + const leave = session.onEvent((event) => before.push(event)); + await session.send({ type: "prompt", message: "tool" }); + await waitFor(() => before.some((event) => event.type === "host_tool_call" && event.id === "h1"), "the host tool call"); + + const adopted = new Map(); + AgentSessionWrapper.prototype.adopt = function (replay) { + const events = []; + this.onEvent((event) => events.push(event), { internal: true }); + adopted.set(this, events); + return adopt.call(this, replay); + }; + const refusedBefore = seen.refusedPosts; + await restartWeb({ + async whileStopping() { + // The tab's connection closes with the server: a live server answers its open call with an error. + leave(); + // omp sends more output while the server stops. + writeFileSync(slowGo(TOOL_ID), ""); + await waitFor(() => seen.refusedPosts > refusedBefore, "an uplink POST refused while stopping"); + }, + }); + assert.equal(ompLog().some((entry) => entry.command?.type === "host_tool_result"), false, "no rejection reached omp"); + assert.equal(before.some((event) => event.type === "message_update"), false, "the stopping server applied none of it"); + + await waitFor(() => getRpcSession(TOOL_ID), "the adoption"); + const next = getRpcSession(TOOL_ID); + const events = adopted.get(next); + const stopping = () => events.filter((event) => event.type === "message_update" && event.message.content[0].text === "while stopping"); + await waitFor(() => stopping().length > 0, "the refused output to reach the next server"); + // A tab of the next server gets the still-open call and answers it. + const tab = []; + next.onEvent((event) => tab.push(event)); + assert.ok(tab.some((event) => event.type === "host_tool_call" && event.id === "h1")); + await next.send({ type: "host_tool_result", id: "h1", result: { content: [{ type: "text", text: "opened" }] } }); + await waitFor(() => tab.some((event) => event.type === "agent_end"), "the run to end"); + assert.ok(tab.some((event) => event.type === "message_update" && event.message.content[0].text === "tool opened")); + assert.equal(stopping().length, 1, "delivered once"); + assert.deepEqual(ompLog().filter((entry) => entry.command?.type === "host_tool_result").map((entry) => entry.command.result.content[0].text), ["opened"]); +}); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 644082464..5cc9c9281 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -34,7 +34,7 @@ import type { } from "./pi-types"; import type { AgentMessage, CrossSessionHostToolCall, ExitedRpcSession, ExtensionWidgetItem } from "./types"; import { isLinkUp, type Host, type HostStatus } from "./hosts/host"; -import { getHost, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; +import { freezeHostLinks, getHost, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; import { localHost } from "./hosts/local-host"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId, invalidateHostSessionList, listSessionsAllHosts, sessionSpawnTarget } from "./hosts/session-index"; @@ -2491,9 +2491,10 @@ function getRegistry(): Map { const cleanup = () => { // Children dying from here on are the shutdown, not finished runs. markShuttingDown(); - // Only this process's own children. A linked host's children run on: its daemon - // keeps them when the link drops, and the next server adopts them (a kill sent - // here could still reach the daemon over a downlink that outlives this handler). + // A linked host's children run on: nothing more reaches its daemon (no kill, no + // host tool rejection as tabs close on the way out), and the next server adopts them. + freezeHostLinks(); + // Only this process's own children are stopped. globalThis.__ompSessions?.forEach((s) => { if (s.host === localHost) s.destroy(); }); From dd202020e0f22e7d1542d476fa7aa8725a54938e Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 21:27:41 +0000 Subject: [PATCH 12/36] fix(hosts): adopt a child by its own identity and spawn cwd, so a new session's first reply survives a restart --- lib/hosts/daemon.test.mjs | 4 +- lib/hosts/daemon.ts | 6 +- lib/hosts/hub.test.mjs | 109 ++++++++++++++++++---------- lib/hosts/hub.ts | 33 +++++---- lib/hosts/link-integration.test.mjs | 33 ++++++--- lib/hosts/link-protocol.test.mjs | 9 ++- lib/hosts/link-protocol.ts | 7 +- lib/rpc-manager.test.mjs | 6 +- lib/rpc-manager.ts | 4 +- lib/session-resume.test.mjs | 8 +- 10 files changed, 134 insertions(+), 85 deletions(-) diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index affe57b9c..8d34e2910 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -438,14 +438,14 @@ test("after a link drop the next hello carries each channel's open blocking requ assert.deepEqual(server.hellos[0].channels, []); server.downlink.close(); await waitFor(() => server.hellos.length === 2, "the relink"); - assert.deepEqual(server.hellos[1].channels, [{ ch: "c1", sessionId: null, pending: [request] }]); + assert.deepEqual(server.hellos[1].channels, [{ ch: "c1", sessionId: null, cwd: scratch, pending: [request] }]); // The answer goes down to omp: the request is no longer open. The echo orders it before the drop. server.send({ type: "stdin", ch: "c1", line: '{"type":"extension_ui_response","id":"q1","answers":[]}\n' }); server.send({ type: "stdin", ch: "c1", line: '{"type":"echo"}\n' }); await waitFor(() => server.up.some((m) => m.type === "stdout" && m.line === '{"type":"echoed"}'), "the echo"); server.downlink.close(); await waitFor(() => server.hellos.length === 3, "the second relink"); - assert.deepEqual(server.hellos[2].channels, [{ ch: "c1", sessionId: null, pending: [] }]); + assert.deepEqual(server.hellos[2].channels, [{ ch: "c1", sessionId: null, cwd: scratch, pending: [] }]); } finally { await daemon.stop(); log.restore(); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 70ccb3871..c63e69f5b 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -44,6 +44,8 @@ type Unsequenced = M extends { seq: number } ? Omit : never; interface Channel { transport: RpcTransport; + /** Where the child was spawned: a restarted main adopts it there. */ + cwd: string; /** Bytes of this child's output waiting for an uplink ack. */ buffered: number; /** Open blocking requests and the child's current session, both in the next hello. */ @@ -460,7 +462,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); } const pending = new PendingRequests(LINK_LIMITS.pendingBytes, file ? readSessionHeaderSync(file)?.id ?? null : null); - channels.set(ch, { transport, buffered: 0, pending }); + channels.set(ch, { transport, cwd: spawned.cwd, buffered: 0, pending }); transport.onLine((line) => { pending.noteStdout(line); output(ch, { type: "stdout", ch, line }); @@ -492,7 +494,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: platform: process.platform, home: homedir(), ack: down.acked, - channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.pending.sessionId, pending: replay ? channel.pending.lines() : null })), + channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.pending.sessionId, cwd: channel.cwd, pending: replay ? channel.pending.lines() : null })), }); let hello: string; try { diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 4e14f9916..9039e5143 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -174,7 +174,7 @@ test("a version mismatch gets 426 with both versions and marks the host needs-up test("the hello rides a POST body, so a hello listing hundreds of channels links", async () => { const { token } = createHost("Busy box"); // Far past an 8 KB proxy header buffer (the hello used to ride a GET header). - const channels = Array.from({ length: 300 }, (_, i) => ({ ch: `ch-${String(i).padStart(4, "0")}`, sessionId: null, pending: [] })); + const channels = Array.from({ length: 300 }, (_, i) => ({ ch: `ch-${String(i).padStart(4, "0")}`, sessionId: null, cwd: "/w", pending: [] })); assert.ok(JSON.stringify(channels).length > 8 * 1024); const offered = await linkHello(token, hello({ channels })); assert.equal(offered.status, 200); @@ -408,9 +408,9 @@ test("no uplink traffic for offlineMs marks the host offline and notifies", asyn test("onHostHello reports the channels a daemon still runs", async () => { const seen = []; const unsubscribe = hub.onHostHello((hostId, channels) => seen.push({ hostId, channels })); - const { id, down } = await linkedHost("Reattach", { channels: [{ ch: "c1", sessionId: null, pending: ['{"type":"host_tool_call","id":"t1"}'] }] }); + const { id, down } = await linkedHost("Reattach", { channels: [{ ch: "c1", sessionId: null, cwd: "/w", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }); unsubscribe(); - assert.deepEqual(seen, [{ hostId: id, channels: [{ ch: "c1", sessionId: null, pending: ['{"type":"host_tool_call","id":"t1"}'] }] }]); + assert.deepEqual(seen, [{ hostId: id, channels: [{ ch: "c1", sessionId: null, cwd: "/w", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }]); await down.cancel(); }); @@ -438,7 +438,7 @@ test("on hello a spawned child the daemon no longer lists exits as lost; a spawn test("orphanExit rejects with 503 when the host goes offline before the orphan exits", async () => { hub.linkTimings.offlineMs = 40; const sessionId = "11111111-2222-4333-8444-999999999999"; - const link = await linkedHost("Dozing", { channels: [{ ch: "old", sessionId, pending: null }] }); + const link = await linkedHost("Dozing", { channels: [{ ch: "old", sessionId, cwd: "/w", pending: null }] }); // No uplink follows the hello: the host goes offline with the orphan still listed. await assert.rejects(hub.orphanExit(link.id, sessionId), (error) => { assert.equal(error.status, 503); @@ -451,7 +451,7 @@ test("orphanExit rejects with 503 when the host goes offline before the orphan e test("on hello a listed child with no transport that cannot be adopted is an orphan: killed, and orphanExit waits for it", async () => { const sessionId = "11111111-2222-4333-8444-555555555555"; - const link = await linkedHost("Survivor", { channels: [{ ch: "old", sessionId, pending: null }] }); + const link = await linkedHost("Survivor", { channels: [{ ch: "old", sessionId, cwd: "/w", pending: null }] }); assert.deepEqual(await link.down.nextReal(), { type: "kill", seq: 1, ch: "old", force: false }); let gone = false; const waiting = hub.orphanExit(link.id, sessionId).then(() => { @@ -472,9 +472,9 @@ function quiet(t) { t.mock.method(console, "info", () => {}); } -test("on hello a listed child of a session its host lists is adopted: no kill, its wrapper registered", async (t) => { +test("on hello a listed child is adopted by its own identity, in its spawn cwd: no kill, no session lookup, its wrapper registered", async (t) => { quiet(t); - const link = await linkHost("Adopter", { channels: [{ ch: "live", sessionId: ADOPTED, pending: [] }] }); + const link = await linkHost("Adopter", { channels: [{ ch: "live", sessionId: ADOPTED, cwd: "/w/project", pending: [] }] }); t.after(async () => { const disposing = getRpcSession(ADOPTED)?.destroyAndWait(); await link.post({ type: "exit", ch: "live", code: 0, signal: null }); @@ -483,7 +483,8 @@ test("on hello a listed child of a session its host lists is adopted: no kill, i }); const seen = []; const omp = ompChild(link, ADOPTED, { state: { isStreaming: true } }); - link.serve({ listSessions: () => [listedSession(ADOPTED)] }, (message) => { + // No ops: a new session is in no list before its first reply is written. + link.serve({}, (message) => { seen.push(message); return omp(message); }); @@ -491,32 +492,18 @@ test("on hello a listed child of a session its host lists is adopted: no kill, i const session = getRpcSession(ADOPTED); assert.equal(session.adopted, true); assert.equal(session.host, hub.getHost(link.id)); + assert.equal(session.cwd, "/w/project"); assert.equal(session.isRunning(), true); - assert.deepEqual(seen.filter((message) => message.type === "kill"), []); + assert.deepEqual(seen.filter((message) => message.type === "kill" || message.type === "req"), []); assert.ok(seen.some((message) => message.type === "stdin" && message.ch === "live"), "the wrapper talks to the listed channel"); assert.equal(await hub.adoptedChild(link.id, ADOPTED), true); // An adopted child is the live session's, no longer an orphan a start or file op waits for. await hub.orphanExit(link.id, ADOPTED); }); -test("on hello a listed child of a session its host does not list is killed", async (t) => { - quiet(t); - const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa02"; - const link = await linkHost("Forgetful", { channels: [{ ch: "stray", sessionId, pending: [] }] }); - t.after(() => hub.closeHostLink(link.id)); - const kills = []; - link.serve({ listSessions: () => [listedSession(ADOPTED)] }, (message) => { - if (message.type === "kill") kills.push(message); - }); - await until(() => kills.length > 0, "the kill"); - assert.deepEqual(kills.map(({ ch, force }) => ({ ch, force })), [{ ch: "stray", force: false }]); - assert.equal(getRpcSession(sessionId), undefined); - assert.equal(await hub.adoptedChild(link.id, sessionId), false); -}); - -test("a child listed without its replay or without a session is killed without asking for the host's sessions", async (t) => { +test("a child listed without its replay or without a session is killed", async (t) => { const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa03"; - const link = await linkHost("Overflowing", { channels: [{ ch: "big", sessionId, pending: null }, { ch: "fresh", sessionId: null, pending: [] }] }); + const link = await linkHost("Overflowing", { channels: [{ ch: "big", sessionId, cwd: "/w", pending: null }, { ch: "fresh", sessionId: null, cwd: "/w", pending: [] }] }); t.after(() => hub.closeHostLink(link.id)); assert.deepEqual([await link.next(), await link.next()].map(({ type, ch }) => ({ type, ch })), [{ type: "kill", ch: "big" }, { type: "kill", ch: "fresh" }]); }); @@ -532,10 +519,10 @@ test("a failed adoption kills the child, blocks a start until it exits, then res resumed.push(interrupted); }); const link = new LinkDriver(host.id, token); - await link.dial({ channels: [{ ch: "wedged", sessionId, pending: [] }] }); + await link.dial({ channels: [{ ch: "wedged", sessionId, cwd: "/w", pending: [] }] }); const kills = []; const omp = ompChild(link, sessionId, { fail: "get_state" }); - link.serve({ listSessions: () => [listedSession(sessionId)] }, (message) => { + link.serve({}, (message) => { if (message.type === "kill") kills.push(message.ch); return omp(message); }); @@ -554,26 +541,21 @@ test("a failed adoption kills the child, blocks a start until it exits, then res assert.equal(getRpcSession(sessionId), undefined); }); -test("a start while the hello's session lookup is in flight joins the adoption: no kill, no second child", async (t) => { +test("a start while the adoption re-syncs joins it: no kill, no second child", async (t) => { quiet(t); const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa05"; - const link = await linkHost("Busy", { channels: [{ ch: "live", sessionId, pending: [] }] }); + const link = await linkHost("Busy", { channels: [{ ch: "live", sessionId, cwd: "/w", pending: [] }] }); t.after(async () => { // The child below exits on its kill. await getRpcSession(sessionId)?.destroyAndWait(); hub.closeHostLink(link.id); }); - const lookup = Promise.withResolvers(); - let looking = false; + const release = Promise.withResolvers(); + let holding = false; const kills = []; const spawns = []; const omp = ompChild(link, sessionId); link.serve({ - async listSessions() { - looking = true; - await lookup.promise; - return [listedSession(sessionId)]; - }, async spawn(args) { spawns.push(args.ch); await link.post({ type: "stdout", ch: args.ch, line: JSON.stringify({ type: "ready", supportedProtocolVersions: [1, 2] }) }); @@ -586,13 +568,17 @@ test("a start while the hello's session lookup is in flight joins the adoption: kills.push(message.ch); return link.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }); } + if (message.type === "stdin" && JSON.parse(message.line).type === "get_state" && !holding) { + holding = true; + await release.promise; + } return omp(message); }); - await until(() => looking, "the session lookup"); + await until(() => holding, "the adoption's get_state"); // A tab sends the session a prompt meanwhile. const starting = startRpcSession(sessionId, listedSession(sessionId).path, "/w", undefined, false, "/w", undefined, hub.getHost(link.id)); await new Promise((resolve) => setTimeout(resolve, 20)); - lookup.resolve(); + release.resolve(); const { session } = await starting; assert.equal(session.adopted, true); assert.equal(getRpcSession(sessionId), session); @@ -600,6 +586,49 @@ test("a start while the hello's session lookup is in flight joins the adoption: assert.deepEqual(kills, []); }); +test("a start of a live adopted session does not wait on its listed child: no 503 while its host is offline", async (t) => { + quiet(t); + const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa06"; + const link = await linkHost("Napping", { channels: [{ ch: "live", sessionId, cwd: "/w", pending: [] }] }); + t.after(async () => { + // Offline: returns at once; closing the link then exits the channel. + await getRpcSession(sessionId)?.destroyAndWait(); + hub.closeHostLink(link.id); + }); + link.serve({}, ompChild(link, sessionId)); + await until(() => getRpcSession(sessionId), "the adoption"); + // The host goes quiet: offline, with its child still running there. + hub.linkTimings.offlineMs = 30; + await link.post(); + await until(() => hub.getHost(link.id).status() === "offline", "the host to go offline"); + const { session } = await startRpcSession(sessionId, listedSession(sessionId).path, "/w", undefined, undefined, "/w", undefined, hub.getHost(link.id)); + assert.equal(session, getRpcSession(sessionId)); + assert.equal(session.isAlive(), true); +}); + +test("an adoption cut short by this server's shutdown leaves the child to the next server, and says so", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); + t.mock.method(console, "info", () => {}); + const sessionId = "11111111-2222-4333-8444-aaaaaaaaaa07"; + const { host, token } = createHost("Handed over"); + hub.linkTimings.offlineMs = 50; + // The shutdown starts as the hello lands: the adoption's first command finds the links frozen. + const stop = hub.onHostHello((hostId) => { + if (hostId === host.id) hub.freezeHostLinks(); + }); + t.after(() => { + stop(); + globalThis.__ompHostHub.frozen = false; + hub.closeHostLink(host.id); + }); + const link = new LinkDriver(host.id, token); + await link.dial({ channels: [{ ch: "live", sessionId, cwd: "/w", pending: [] }] }); + assert.equal(await hub.adoptedChild(host.id, sessionId), false); + const messages = warn.mock.calls.map((call) => String(call.arguments[0])); + assert.ok(messages.some((message) => /left the omp child of session .* to the next server/.test(message)), messages.join("\n")); + assert.equal(messages.some((message) => /killing/.test(message)), false); +}); + for (const [op, call, value] of [ ["archiveSession", (ops, id) => ops.archiveSession(id), { archivedPath: "/a" }], ["deleteSession", (ops, id) => ops.deleteSession(id, []), {}], @@ -607,7 +636,7 @@ for (const [op, call, value] of [ ]) { test(`${op} waits for the session's orphan to exit; another session is not delayed`, async () => { const sessionId = "11111111-2222-4333-8444-666666666666"; - const link = await linkedHost(`Waiter ${op}`, { channels: [{ ch: "old", sessionId, pending: null }] }); + const link = await linkedHost(`Waiter ${op}`, { channels: [{ ch: "old", sessionId, cwd: "/w", pending: null }] }); assert.equal((await link.down.nextReal()).type, "kill"); const ops = link.remote.sessionOps; let seq = 0; diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index dc1d2d507..122ec0a29 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -421,16 +421,13 @@ function reattach(link: Link, listed: HelloChannel[]): void { transport.lost = true; transport.deliverExit(null, null); } - // Asked once per hello, and fresh: a cached list may still hold a session deleted since. - let sessions: Promise | undefined; - const listSessions = () => (sessions ??= link.host.sessionOps.listSessions()); - for (const { ch, sessionId, pending } of listed) { + for (const { ch, sessionId, cwd, pending } of listed) { if (link.channels.has(ch)) continue; const child = new RemoteRpcTransport(link.id, ch, sessionId); child.spawned = true; link.channels.set(ch, child); // A null `pending` lost open requests to the daemon's cap: adopted, the run would wait on them forever. - if (sessionId && pending) child.adoption = adopt(link, child, sessionId, pending, listSessions); + if (sessionId && pending) child.adoption = adopt(link, child, sessionId, cwd, pending); else killOrphan(child); } } @@ -443,20 +440,24 @@ function killOrphan(orphan: RemoteRpcTransport): void { orphan.onExit(() => clearTimeout(escalate)); } -/** Spec "Adopting live children": a session wrapper takes the child over; one - * that cannot (unknown session, failed re-sync) is killed. True when adopted. */ -async function adopt(link: Link, child: RemoteRpcTransport, sessionId: string, replay: string[], listSessions: () => Promise): Promise { +/** Spec "Adopting live children": a session wrapper takes the child over, by + * the identity the child itself reports (a new session is in no list before + * its first reply is written). One that cannot re-sync is killed. True when adopted. */ +async function adopt(link: Link, child: RemoteRpcTransport, sessionId: string, cwd: string, replay: string[]): Promise { try { - // rpc-manager imports this module. Awaiting it also defers the lookup past - // openDownlink, which marks the link up (ops need it) after reattach. + // Dynamic: rpc-manager imports this module. const { adoptRpcSession } = await import("../rpc-manager"); - const session = (await listSessions()).find((entry) => entry.id === sessionId); - if (!session) throw new Error("its session is unknown"); - await adoptRpcSession({ host: link.host, transport: child, sessionId, cwd: session.cwd, replay }); + await adoptRpcSession({ host: link.host, transport: child, sessionId, cwd, replay }); return true; } catch (error) { - console.warn(`[omp-web] killing the omp child of session ${sessionId} on ${labelOf(link.id)}: it could not be adopted (${error instanceof Error ? error.message : String(error)})`); - killOrphan(child); + const reason = error instanceof Error ? error.message : String(error); + if (hub().frozen) { + // Nothing reaches the daemon now, a kill included: the child runs on for the next server. + console.warn(`[omp-web] left the omp child of session ${sessionId} on ${labelOf(link.id)} to the next server: this one stopped while adopting it (${reason})`); + } else { + console.warn(`[omp-web] killing the omp child of session ${sessionId} on ${labelOf(link.id)}: it could not be adopted (${reason})`); + killOrphan(child); + } return false; } } @@ -719,6 +720,8 @@ export class RemoteRpcTransport implements RpcTransport { write(line: string, callback: (error?: Error | null) => void): void { if (this.exitInfo) return callback(new Error("RPC process is not running")); + // sendDown would drop it: a command waiting on it fails now instead of at its timeout. + if (hub().frozen) return callback(new Error("omp-web is shutting down")); try { // Kept in the link outbox until the daemon acks it, across reconnects. sendDown(linkFor(this.hostId), { type: "stdin", ch: this.ch, line }); diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 457b7aaf2..3b24d8b00 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -61,19 +61,27 @@ const out = (frame) => process.stdout.write(JSON.stringify(frame) + "\\n"); const log = (entry) => fs.appendFileSync(${JSON.stringify(ompLogFile)}, JSON.stringify({ pid: process.pid, ...entry }) + "\\n"); const resumeAt = process.argv.indexOf("--resume"); const resumed = resumeAt === -1 ? null : process.argv[resumeAt + 1]; -// A new session is written on its first prompt, as omp does. +// As omp does, a new session's file is written only once its first assistant message ends. const sessionId = resumed ? JSON.parse(fs.readFileSync(resumed, "utf8").split("\\n")[0]).id : require("node:crypto").randomUUID(); const sessionFile = resumed ?? path.join(${JSON.stringify(sessionsDir)}, "-project", sessionId + ".jsonl"); -const write = (message) => { - if (fs.existsSync(sessionFile)) return; - const at = new Date().toISOString(); - const lines = [{ type: "session", version: 3, id: sessionId, cwd: ${JSON.stringify(projectDir)}, timestamp: at }, { type: "message", id: "m0", parentId: null, timestamp: at, message: { role: "user", content: message } }]; - fs.writeFileSync(sessionFile, lines.map((line) => JSON.stringify(line)).join("\\n") + "\\n"); -}; +let prompt = null; let streaming = false; -const update = (text) => out({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: String(text) }] } }); +let text = ""; +const update = (next) => { + text = String(next); + out({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text }] } }); +}; const end = () => { streaming = false; + if (!fs.existsSync(sessionFile)) { + const at = new Date().toISOString(); + const lines = [ + { type: "session", version: 3, id: sessionId, cwd: ${JSON.stringify(projectDir)}, timestamp: at }, + { type: "message", id: "m0", parentId: null, timestamp: at, message: { role: "user", content: prompt } }, + { type: "message", id: "m1", parentId: "m0", timestamp: at, message: { role: "assistant", content: [{ type: "text", text }] } }, + ]; + fs.writeFileSync(sessionFile, lines.map((line) => JSON.stringify(line)).join("\\n") + "\\n"); + } out({ type: "agent_end", isTerminal: true, messages: [] }); }; log({ kind: "start", sessionId }); @@ -95,7 +103,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l } if (command.type !== "prompt") return reply({}); reply({ agentInvoked: true }); - write(command.message); + prompt = command.message; streaming = true; out({ type: "agent_start" }); if (command.message === "ask") return out({ type: "extension_ui_request", id: "q1", method: "ask", questions: [{ id: "q", question: "Pick", options: [{ label: "A" }] }] }); @@ -366,7 +374,8 @@ test("a restarted web server adopts its running omp children, resumed or new: ea saveWebServerSettings({ autoResumeSessions: false }); }); const remote = hub.getHost(hostId); - // A resumed session, and a new one (no --resume) that names itself only in its get_state. + // A resumed session, and a new one (no --resume) in its first reply: it names itself only in + // its get_state, and no session list has it until that reply ends and omp writes its file. const runs = [ await startRpcSession(SMALL_ID, smallFile, projectDir, undefined, false, projectDir, undefined, remote), await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote), @@ -380,6 +389,8 @@ test("a restarted web server adopts its running omp children, resumed or new: ea await waitFor(() => runs.every((run) => run.texts.length === SLOW_HALF), "the first half of each run"); const interrupted = join(mainAgentDir, `omp-web-interrupted-sessions-${process.pid}.json`); await waitFor(() => existsSync(interrupted) && runs.every((run) => readFileSync(interrupted, "utf8").includes(run.id)), "the runs to be recorded for resume"); + const newSessionFile = join(sessionsDir, "-project", `${runs[1].id}.jsonl`); + assert.equal(existsSync(newSessionFile), false, "the new session has no file yet"); // Live on the daemon too: the earlier test's idle new session. const ids = [...runs.map((run) => run.id), countSessionId]; const killsBefore = seen.kills.length; @@ -404,6 +415,8 @@ test("a restarted web server adopts its running omp children, resumed or new: ea assert.deepEqual(run.texts, Array.from({ length: SLOW_FRAMES }, (_, i) => i + 1), run.id); } assert.deepEqual(seen.kills.slice(killsBefore), [], "no kill reached the daemon"); + // The first reply completed in the adopted child, which then wrote the session. + assert.equal(JSON.parse(readFileSync(newSessionFile, "utf8").split("\n")[0]).id, runs[1].id); const log = ompLog(); for (const id of ids) { diff --git a/lib/hosts/link-protocol.test.mjs b/lib/hosts/link-protocol.test.mjs index b395f6794..4ed306bdb 100644 --- a/lib/hosts/link-protocol.test.mjs +++ b/lib/hosts/link-protocol.test.mjs @@ -26,8 +26,8 @@ const UP = [ home: "/Users/me", ack: 3, channels: [ - { ch: "c1", sessionId: "s1", pending: ['{"type":"host_tool_call","id":"t1"}'] }, - { ch: "c2", sessionId: null, pending: null }, + { ch: "c1", sessionId: "s1", cwd: "/Users/me/project", pending: ['{"type":"host_tool_call","id":"t1"}'] }, + { ch: "c2", sessionId: null, cwd: "/Users/me", pending: null }, ], }, { type: "stdout", seq: 1, ch: "c1", line: '{"type":"message_end"}' }, @@ -109,8 +109,9 @@ test("decode rejects malformed lines with LinkProtocolError", async () => { '{"type":"exit","seq":1,"ch":"c","code":"0","signal":null}', '{"type":"res","seq":1,"id":"a"}', '{"type":"res","seq":1,"id":"a","ok":false,"error":{"code":"x","message":"y"}}', - '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null}]}', - '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"pending":[1]}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"cwd":"/w"}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"cwd":"/w","pending":[1]}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"pending":[]}]}', ]; for (const line of bad) { assert.throws(() => decodeUp(line), LinkProtocolError, line); diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 9c8faa803..3b10cd076 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -82,8 +82,9 @@ export type DownMessage = | { type: "ping" } | { type: "pong" }; -/** `pending`: raw stdout lines of the child's open blocking requests, or null when over `pendingBytes`. */ -export type HelloChannel = { ch: string; sessionId: string | null; pending: string[] | null }; +/** `sessionId`: the session the child last reported (null before it named one); `cwd`: where the + * daemon spawned it; `pending`: raw stdout lines of its open blocking requests, or null when over `pendingBytes`. */ +export type HelloChannel = { ch: string; sessionId: string | null; cwd: string; pending: string[] | null }; export type UpMessage = | { @@ -215,7 +216,7 @@ function channels(o: Obj): HelloChannel[] { if (!Array.isArray(list)) fail("channels must be an array"); return list.map((c: unknown) => { if (!isObj(c)) fail("channel must be an object"); - return { ch: str(c, "ch"), sessionId: nullable(c, "sessionId", str), pending: nullable(c, "pending", strings) }; + return { ch: str(c, "ch"), sessionId: nullable(c, "sessionId", str), cwd: str(c, "cwd"), pending: nullable(c, "pending", strings) }; }); } diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index 395989b7b..e7b95353e 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -2985,7 +2985,7 @@ test("a command written before the host link dropped resolves once the link retu await until(() => hub.getHost(link.id).status() === "offline", "the host to go offline"); hub.linkTimings.offlineMs = timings.offlineMs; - await link.dial({ channels: [{ ch, sessionId: null, pending: [] }] }); + await link.dial({ channels: [{ ch, sessionId: null, cwd: "/w", pending: [] }] }); link.serve(ops, omp); await link.post({ type: "stdout", ch, line: respond(held) }); const state = await pending; @@ -3088,7 +3088,7 @@ test("a session the host still runs an orphan child for spawns only after the or const id = "11111111-2222-4333-8444-888888888888"; const sessionFile = `/remote/sessions/${id}.jsonl`; // This server restarted while the host kept running the session's child (one it cannot adopt: no replay listed). - const link = await linkHost("Survivor box", { channels: [{ ch: "orphan", sessionId: id, pending: null }] }); + const link = await linkHost("Survivor box", { channels: [{ ch: "orphan", sessionId: id, cwd: "/w", pending: null }] }); let session; t.after(async () => { hub.closeHostLink(link.id); @@ -3143,7 +3143,7 @@ test("a prompt whose ack is lost to a quiet link answers host_offline and keeps // The lid opens: the daemon redials with the child still running. await link.drop(); - await link.dial({ channels: [{ ch: spawns[0].ch, sessionId: null, pending: [] }] }); + await link.dial({ channels: [{ ch: spawns[0].ch, sessionId: null, cwd: "/w", pending: [] }] }); link.serve(ops, omp); assert.equal((await session.send({ type: "get_state" })).sessionId, "s-lid"); assert.deepEqual(kills, [], "no kill was queued for the reconnect either"); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index 5cc9c9281..cd5e353b2 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -2816,8 +2816,8 @@ export async function startRpcSession( // A child of this session the host still ran from before a restart of this // server is being adopted or killed. Waiting here, before the registry and // the lock, lets a start join an adopted child; a killed one must exit first: - // two children must never write one session file. - if (sessionFile && host !== localHost) await orphanExit(host.id, sessionId); + // two children must never write one session file. A live wrapper is past that. + if (sessionFile && host !== localHost && !registry.get(sessionId)?.isAlive()) await orphanExit(host.id, sessionId); const existing = registry.get(sessionId); // Union semantics, matching the spawn below and the wrapper identity: diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index ca0aa24a2..a5457c652 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -6,7 +6,7 @@ import { join } from "node:path"; import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { createJiti } from "jiti"; -import { LinkDriver, listedSession, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; +import { LinkDriver, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; const jiti = createJiti(import.meta.url); /** A new omp-web process: fresh tracker, same agent dir. */ @@ -163,7 +163,7 @@ test("a remote entry resumes after its host's hello, exactly once", async (t) => // The orphan wait is startRpcSession's (rpc-manager.test.mjs); resume starts on hello. // With no replay listed the child cannot be adopted: it is killed and the run resumes. const link = new LinkDriver(host.id, token); - await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id, pending: null }] }); + await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id, cwd: "/w", pending: null }] }); await sleep(10); assert.deepEqual(resumed, [remote]); @@ -196,8 +196,8 @@ test("a remote entry whose child the server adopts on hello is not resumed", asy }); link = new LinkDriver(host.id, token); - await link.dial({ channels: [{ ch: "live", sessionId: remote.id, pending: [] }] }); - link.serve({ listSessions: () => [listedSession(remote.id)] }, ompChild(link, remote.id, { state: { isStreaming: true } })); + await link.dial({ channels: [{ ch: "live", sessionId: remote.id, cwd: "/w", pending: [] }] }); + link.serve({}, ompChild(link, remote.id, { state: { isStreaming: true } })); await until(() => getRpcSession(remote.id), "the adoption"); await sleep(10); assert.deepEqual(resumed, [], "the run goes on in the adopted child"); From 7a0e69997da64bcfa093e74ff0b70b2097d7e51a Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 21:38:36 +0000 Subject: [PATCH 13/36] feat(hosts): bootstrap the local daemon link --- bin/omp-web-host.js | 4 +- instrumentation.node.ts | 13 ++++++ lib/hosts/daemon.test.mjs | 43 +++++++++++++++++- lib/hosts/daemon.ts | 43 +++++++++++------- lib/hosts/hosts-route.test.mjs | 18 ++++++++ lib/hosts/hub.ts | 11 +++-- lib/hosts/local-bootstrap.test.mjs | 72 ++++++++++++++++++++++++++++++ lib/hosts/local-bootstrap.ts | 24 ++++++++++ lib/hosts/registry.ts | 30 +++++++++++++ 9 files changed, 236 insertions(+), 22 deletions(-) create mode 100644 lib/hosts/local-bootstrap.test.mjs create mode 100644 lib/hosts/local-bootstrap.ts diff --git a/bin/omp-web-host.js b/bin/omp-web-host.js index 107683457..8a8247c93 100755 --- a/bin/omp-web-host.js +++ b/bin/omp-web-host.js @@ -4,7 +4,7 @@ // `ompweb host`: link this machine to a main omp-web so sessions can run here // (lib/hosts/daemon.ts). // ompweb host login --url reads the host token from stdin -// ompweb host [--allow-http] dials the saved server and keeps the link up +// ompweb host [--allow-http] dials the saved server and keeps the link up (http:// is accepted without the flag for loopback) // eslint-disable-next-line @typescript-eslint/no-require-imports require("./node-version").exitIfUnsupportedNode(); @@ -59,7 +59,7 @@ async function main(argv) { } const login = readHostLogin(); if (!login) { - console.error("This machine is not linked yet. Run `ompweb host login --url ` first."); + console.error("This machine is not linked yet. Start ompweb on this machine (it writes the link), or run `ompweb host login --url `."); return 1; } const daemon = runHostDaemon({ ...login, allowHttp: argv.includes("--allow-http") }); diff --git a/instrumentation.node.ts b/instrumentation.node.ts index 235561f8a..74a2f4876 100644 --- a/instrumentation.node.ts +++ b/instrumentation.node.ts @@ -57,6 +57,19 @@ export async function register(): Promise { } })(); + // Point the local `ompweb host` daemon at this server (production only: a dev + // server must not take the daemon from the running production one). + if (process.env.NODE_ENV !== "development") { + try { + const { ensureLocalHostLink, localLinkUrl } = await import("@/lib/hosts/local-bootstrap"); + const url = localLinkUrl(); + if (url) ensureLocalHostLink({ url }); + else console.warn("[omp-web] local daemon link skipped: OMP_WEB_PORT is not set (start through the ompweb launcher)"); + } catch (error) { + console.warn(`[omp-web] local daemon link not prepared: ${error instanceof Error ? error.message : String(error)}`); + } + } + // Resume sessions that were mid-run when omp-web last stopped (opt-in // setting). Fire-and-forget: resuming must not block boot. void (async () => { diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index 8d34e2910..997f72dfa 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -68,11 +68,12 @@ async function waitFor(predicate, what, timeoutMs = 15_000) { /** A scripted main server: one downlink at a time, uplink POSTs recorded and acked. * Like the hub, it takes the hello as a POST and refuses (409) POSTs and blob * uploads that name another link's nonce. `hellos` are the ones a downlink opened. */ -function scriptedServer({ getStatus = () => 200, helloStatus = 200 } = {}) { +function scriptedServer({ getStatus = () => 200, helloStatus = 200, validToken = null } = {}) { const server = { up: [], hellos: [], offered: null, downlink: null, uplinkDown: false, gets: 0, nonce: null, refused: [], blobs: [], postStatus: [] }; let downSeq = 0; let ack = 0; server.fetch = async (url, init = {}) => { + if (validToken && init.headers?.authorization !== `Bearer ${validToken}`) return Response.json({}, { status: 401 }); if (init.method === "POST" && init.headers[LINK_HELLO_HEADER]) { if (helloStatus !== 200) return Response.json({ error: "This link was replaced; wait for the next welcome" }, { status: helloStatus }); server.offered = { id: `hello-${server.gets + 1}`, hello: JSON.parse(String(init.body)) }; @@ -138,6 +139,11 @@ function captureLog() { return { lines, restore: () => { console.error = original; } }; } +test("an http:// loopback server links without --allow-http", () => { + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "t", allowHttp: false, fetch: async () => Response.json({}, { status: 503 }) }); + return daemon.stop(); +}); + test("an http:// server needs loopback or --allow-http", () => { assert.throws(() => runHostDaemon({ url: "http://example.com", token: "t", allowHttp: false, fetch: async () => Response.json({}, { status: 503 }) }), /https:\/\//); }); @@ -506,3 +512,38 @@ test("spawn reports a fallback when a new session's cwd is missing on this host" log.restore(); } }); + +const hostJson = join(scratch, "agent", "omp-web", "host.json"); +function writeHostJson(token) { + mkdirSync(dirname(hostJson), { recursive: true }); + writeFileSync(hostJson, JSON.stringify({ url: "http://127.0.0.1:9", token })); +} + +test("a 401 with a newer token in host.json redials with it and links", async () => { + const log = captureLog(); + const server = scriptedServer({ validToken: "new" }); + writeHostJson("new"); + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "stale", allowHttp: false, fetch: server.fetch }); + try { + await waitFor(() => server.downlink, "the downlink after the token swap"); + assert.ok(log.lines.some((line) => line.includes("new one from host.json"))); + } finally { + await daemon.stop(); + rmSync(hostJson, { force: true }); + log.restore(); + } +}); + +test("a 401 with host.json still holding the rejected token exits 1", async () => { + const log = captureLog(); + const server = scriptedServer({ validToken: "new" }); + writeHostJson("stale"); + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "stale", allowHttp: false, fetch: server.fetch }); + try { + assert.equal(await daemon.done, 1); + assert.ok(log.lines.some((line) => line.includes("revoked"))); + } finally { + rmSync(hostJson, { force: true }); + log.restore(); + } +}); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index c63e69f5b..73cf2a884 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -156,7 +156,8 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } const fetchLink = options.fetch ?? fetch; const linkUrl = `${options.url.replace(/\/+$/, "")}/api/hosts/link`; - const authorization = `Bearer ${options.token}`; + // Replaced when a 401 finds a newer token in host.json (the web server re-keyed this host). + let authorization = `Bearer ${options.token}`; const channels = new Map(); // Uplink messages stay here until main acks them; a failed POST resends them. @@ -236,6 +237,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: flushTimer = undefined; if (posting || stopped || !nonce) return; const used = nonce; + const sent = authorization; const batch: string[] = []; let size = pongOwed ? PONG_LINE.length : 0; for (const item of outbox.pending()) { @@ -251,11 +253,11 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: try { const response = await fetchLink(linkUrl, { method: "POST", - headers: { authorization, "content-type": "application/x-ndjson", [LINK_ACK_HEADER]: String(down.acked), [LINK_NONCE_HEADER]: used }, + headers: { authorization: sent, "content-type": "application/x-ndjson", [LINK_ACK_HEADER]: String(down.acked), [LINK_NONCE_HEADER]: used }, body, signal: AbortSignal.any([stopSignal.signal, AbortSignal.timeout(LINK_LIMITS.offlineMs)]), }); - if (fatal(response.status)) return; + if (fatal(response.status, sent)) return; if (response.status === 409) { // Sent on a link main has replaced: resend on the current one, now if // its welcome already arrived, else when it does. @@ -285,12 +287,21 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } } - /** 401 (revoked) and 426 (outdated) end the daemon; true when it is stopping. */ - function fatal(status: number): boolean { - if (status === 401) { - log("the server rejected this host's token (revoked?); stopping its omp sessions"); - void shutdown(1); - } else if (status === 426) { + /** 426 (outdated) ends the daemon. So does 401 (revoked) unless host.json already holds a newer token, which the daemon then dials with. + * `sent` is the authorization the request carried; true when the daemon is stopping. */ + function fatal(status: number, sent: string): boolean { + // A 401 for a token another request already replaced needs nothing more. + if (status === 401 && sent === authorization) { + const saved = readHostLogin(); + if (saved && `Bearer ${saved.token}` !== sent) { + authorization = `Bearer ${saved.token}`; + log("the server rejected this host's token; using the new one from host.json"); + } else { + log("the server rejected this host's token (revoked?); stopping its omp sessions"); + void shutdown(1); + } + } + if (status === 426) { log("the server speaks a different link protocol: upgrade omp-web on this host"); void shutdown(1); } @@ -405,13 +416,14 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: await Promise.race([welcome.promise, aborted]); } const used = nonce; + const sent = authorization; const response = await fetchLink(`${linkUrl}/blob/${encodeURIComponent(id)}`, { method: "POST", - headers: { authorization, "content-type": "application/octet-stream", [LINK_NONCE_HEADER]: used }, + headers: { authorization: sent, "content-type": "application/octet-stream", [LINK_NONCE_HEADER]: used }, body: bytes as Uint8Array, signal, }); - if (fatal(response.status)) throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); + if (fatal(response.status, sent)) throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); if (response.status === 409) { if (nonce === used) forgetLink(); continue; @@ -505,15 +517,16 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: hello = encodeHello(false); } alive(); + const sent = authorization; const signal = AbortSignal.any([stopSignal.signal, abort.signal]); // The hello goes in a POST body: as a GET header, proxy header buffers (nginx: 8 KB) capped the channels it lists. const offered = await fetchLink(linkUrl, { method: "POST", - headers: { authorization, "content-type": "application/x-ndjson", [LINK_HELLO_HEADER]: "1" }, + headers: { authorization: sent, "content-type": "application/x-ndjson", [LINK_HELLO_HEADER]: "1" }, body: hello, signal, }); - if (fatal(offered.status)) return; + if (fatal(offered.status, sent)) return; const { helloId } = (offered.ok ? await offered.json().catch(() => ({})) : {}) as { helloId?: unknown }; if (typeof helloId !== "string" || !helloId) { // A v1 main answers a nonce-less POST 409 and has no hello leg: redialing would loop forever. @@ -524,8 +537,8 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } throw new Error(`the server answered the hello with ${offered.status}`); } - const response = await fetchLink(linkUrl, { headers: { authorization, [LINK_HELLO_HEADER]: helloId }, signal }); - if (fatal(response.status)) return; + const response = await fetchLink(linkUrl, { headers: { authorization: sent, [LINK_HELLO_HEADER]: helloId }, signal }); + if (fatal(response.status, sent)) return; if (!response.ok || !response.body) throw new Error(`the server answered ${response.status}`); for await (const line of readLines(response.body)) { alive(); diff --git a/lib/hosts/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index ff1c48d5b..f6fbee353 100644 --- a/lib/hosts/hosts-route.test.mjs +++ b/lib/hosts/hosts-route.test.mjs @@ -111,3 +111,21 @@ test("an unreadable hosts.json answers 503 and is never rewritten", async () => assert.equal((await route.DELETE(new Request(`${BASE}?id=${host.id}`, { method: "DELETE" }))).status, 503); assert.equal(readFileSync(hostsFile, "utf8"), broken); }); + +test("the reserved local record is not listed twice; getHost(local) is the daemon only while one is linked", async () => { + writeFileSync(hostsFile, '{"hosts":[]}'); + const { localHost } = await jiti.import("./local-host.ts"); + const { ensureLocalHostLink } = await jiti.import("./local-bootstrap.ts"); + assert.equal(hub.getHost("local"), localHost); + const { token } = ensureLocalHostLink({ url: "http://127.0.0.1:30177" }); + assert.equal(hub.getHost("local"), localHost, "a record alone is not a link"); + assert.deepEqual((await get()).hosts.filter((h) => h.id === "local").map((h) => h.label), ["This machine"]); + + assert.equal((await linkGet(token)).status, 200); + const linked = hub.getHost("local"); + assert.notEqual(linked, localHost); + assert.equal(linked.id, "local"); + assert.equal((await get()).hosts.filter((h) => h.id === "local").length, 1); + assert.equal((await send("PATCH", { id: "local", allowAgentStart: false })).status, 400); + assert.equal((await route.DELETE(new Request(`${BASE}?id=local`, { method: "DELETE" }))).status, 400); +}); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 122ec0a29..28dac0f81 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -30,7 +30,7 @@ import { type UpMessage, } from "./link-protocol"; import { localHost } from "./local-host"; -import { HostRegistryUnreadableError, hostForToken, loadHosts, touchHost, type HostRecord } from "./registry"; +import { HostRegistryUnreadableError, hostForToken, LOCAL_HOST_ID, loadHosts, touchHost, type HostRecord } from "./registry"; import type { SessionOps } from "./session-ops"; /** Liveness and op timeouts from LINK_LIMITS; tests shorten them. */ @@ -875,9 +875,12 @@ export class RemoteHost implements Host { } } -/** "local" is this machine; other ids must be registered hosts. */ +/** "local" is this machine: the daemon linked as `local` when one is up, else the direct host (until the direct path is removed); other ids must be registered hosts. */ export function getHost(id: string): Host | null { - if (id === localHost.id) return localHost; + if (id === LOCAL_HOST_ID) { + const link = hub().links.get(id); + return link && isLinkUp(link.status) ? link.host : localHost; + } return loadHosts().some((h) => h.id === id) ? linkFor(id).host : null; } @@ -895,7 +898,7 @@ export interface LinkedHostRow { } export function listHosts(): LinkedHostRow[] { - return loadHosts().map((record) => { + return loadHosts().filter((record) => record.id !== LOCAL_HOST_ID).map((record) => { const link = hub().links.get(record.id); return { id: record.id, diff --git a/lib/hosts/local-bootstrap.test.mjs b/lib/hosts/local-bootstrap.test.mjs new file mode 100644 index 000000000..8dead9555 --- /dev/null +++ b/lib/hosts/local-bootstrap.test.mjs @@ -0,0 +1,72 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { after } from "node:test"; +import { createJiti } from "jiti"; + +const agentDir = mkdtempSync(join(tmpdir(), "omp-web-local-bootstrap-test-")); +const previous = process.env.PI_CODING_AGENT_DIR; +process.env.PI_CODING_AGENT_DIR = agentDir; +after(() => { + if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previous; + rmSync(agentDir, { recursive: true, force: true }); +}); + +const jiti = createJiti(import.meta.url); +const { ensureLocalHostLink, localLinkUrl } = await jiti.import("./local-bootstrap.ts"); +const { createHost, hostForToken, loadHosts, revokeHost, updateHost } = await jiti.import("./registry.ts"); + +const hostJson = join(agentDir, "omp-web", "host.json"); +const readLogin = () => JSON.parse(readFileSync(hostJson, "utf8")); + +test("bootstrap writes host.json (0600) with the loopback url and a token the registry accepts as local", () => { + const { token, written } = ensureLocalHostLink({ url: "http://127.0.0.1:30177" }); + assert.equal(written, true); + assert.deepEqual(readLogin(), { url: "http://127.0.0.1:30177", token }); + if (process.platform !== "win32") assert.equal(statSync(hostJson).mode & 0o777, 0o600); + assert.equal(hostForToken(token)?.id, "local"); + assert.equal(loadHosts().filter((host) => host.id === "local").length, 1); +}); + +test("a second call with the same url keeps the token and does not rewrite", () => { + const before = readLogin(); + const mtime = statSync(hostJson).mtimeMs; + const { token, written } = ensureLocalHostLink({ url: "http://127.0.0.1:30177/" }); + assert.equal(written, false); + assert.equal(token, before.token); + assert.equal(statSync(hostJson).mtimeMs, mtime); +}); + +test("a new url is written with the same token", () => { + const before = readLogin(); + const { token, written } = ensureLocalHostLink({ url: "http://127.0.0.1:40000" }); + assert.equal(written, true); + assert.deepEqual(readLogin(), { url: "http://127.0.0.1:40000", token: before.token }); + assert.equal(token, before.token); +}); + +test("a host.json token the registry does not know is replaced, keeping one local record", () => { + writeFileSync(hostJson, JSON.stringify({ url: "http://127.0.0.1:40000", token: "unknown" })); + const { token, written } = ensureLocalHostLink({ url: "http://127.0.0.1:40000" }); + assert.equal(written, true); + assert.notEqual(token, "unknown"); + assert.equal(hostForToken("unknown"), null); + assert.equal(hostForToken(token)?.id, "local"); + assert.equal(loadHosts().filter((host) => host.id === "local").length, 1); +}); + +test("the registry refuses to revoke or edit local, and createHost never makes it", () => { + assert.throws(() => revokeHost("local"), { name: "ReservedHostError" }); + assert.throws(() => updateHost("local", { label: "x" }), { name: "ReservedHostError" }); + assert.notEqual(createHost("laptop").host.id, "local"); + assert.equal(loadHosts().filter((host) => host.id === "local").length, 1); +}); + +test("the link url follows the launcher's port, and ::1 binds", () => { + assert.equal(localLinkUrl({ OMP_WEB_PORT: "30177" }), "http://127.0.0.1:30177"); + assert.equal(localLinkUrl({ OMP_WEB_PORT: "30177", OMP_WEB_HOSTNAME: "0.0.0.0" }), "http://127.0.0.1:30177"); + assert.equal(localLinkUrl({ OMP_WEB_PORT: "30177", OMP_WEB_HOSTNAME: "::1" }), "http://[::1]:30177"); + assert.equal(localLinkUrl({}), null); +}); diff --git a/lib/hosts/local-bootstrap.ts b/lib/hosts/local-bootstrap.ts new file mode 100644 index 000000000..7217c02d5 --- /dev/null +++ b/lib/hosts/local-bootstrap.ts @@ -0,0 +1,24 @@ +// The web server's side of the local daemon link: keep the `local` host record +// and the daemon's host.json in step. Pure Node: no Next or `@/` imports. +import { loginHost, readHostLogin } from "./daemon"; +import { hostForToken, LOCAL_HOST_ID, rotateLocalHostToken } from "./registry"; + +/** Where the daemon dials this server: its own loopback address on the port it listens on; null when the launcher did not say. */ +export function localLinkUrl(env: NodeJS.ProcessEnv = process.env): string | null { + const port = env.OMP_WEB_PORT; + if (!port) return null; + const v6 = env.OMP_WEB_HOSTNAME === "::1" || env.OMP_WEB_HOSTNAME === "[::1]"; + return `http://${v6 ? "[::1]" : "127.0.0.1"}:${port}`; +} + +/** Make sure the `local` record exists and host.json holds its token and `url`. + * A host.json whose token the registry still accepts is kept, so a restart does not make the daemon redial. */ +export function ensureLocalHostLink(input: { url: string }): { token: string; written: boolean } { + const url = input.url.replace(/\/+$/, ""); + const saved = readHostLogin(); + const kept = saved && hostForToken(saved.token)?.id === LOCAL_HOST_ID ? saved : null; + if (kept && kept.url === url) return { token: kept.token, written: false }; + const token = kept?.token ?? rotateLocalHostToken(); + loginHost({ url, token }); + return { token, written: true }; +} diff --git a/lib/hosts/registry.ts b/lib/hosts/registry.ts index 221a88afb..dffe90110 100644 --- a/lib/hosts/registry.ts +++ b/lib/hosts/registry.ts @@ -17,6 +17,9 @@ interface HostsFile { hosts: HostRecord[]; } +/** "This machine": the one record the web server itself creates (local-bootstrap.ts). */ +export const LOCAL_HOST_ID = "local"; + function normalizeLabel(label: string): string { const trimmed = label.trim(); if (!trimmed) throw new Error("Host label is required"); @@ -110,7 +113,16 @@ export class UnknownHostError extends Error { } } +/** `local` is created and keyed by the web server only; it cannot be renamed or revoked. */ +export class ReservedHostError extends Error { + readonly name = "ReservedHostError"; + constructor() { + super("This machine cannot be changed"); + } +} + export function updateHost(id: string, updates: { label?: string; allowAgentStart?: boolean }): HostRecord { + if (id === LOCAL_HOST_ID) throw new ReservedHostError(); const hosts = readHosts(); const host = hosts.find((h) => h.id === id); if (!host) throw new UnknownHostError(); @@ -120,7 +132,25 @@ export function updateHost(id: string, updates: { label?: string; allowAgentStar return host; } +/** Create the `local` record, or give the existing one a new token; the old token stops matching. */ +export function rotateLocalHostToken(): string { + const hosts = readHosts(); + const existing = hosts.find((h) => h.id === LOCAL_HOST_ID); + const token = randomBytes(32).toString("base64url"); + const record: HostRecord = { + id: LOCAL_HOST_ID, + label: "This machine", + tokenHash: sha256Hex(token), + createdAt: existing?.createdAt || new Date().toISOString(), + lastSeenAt: existing?.lastSeenAt ?? null, + allowAgentStart: true, + }; + saveHosts([...hosts.filter((h) => h.id !== LOCAL_HOST_ID), record]); + return token; +} + export function revokeHost(id: string): boolean { + if (id === LOCAL_HOST_ID) throw new ReservedHostError(); const hosts = readHosts(); const remaining = hosts.filter((h) => h.id !== id); if (remaining.length === hosts.length) return false; From 1544d75ff28648bffe8a3a447e139d0e0a68c63b Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 21:56:06 +0000 Subject: [PATCH 14/36] fix(hosts): the local row shows the daemon link's status, getHost(local) stays direct, and the bootstrap never takes a host.json for another server --- app/api/hosts/route.ts | 4 +- instrumentation.node.ts | 6 +-- lib/event-stream-hub.ts | 4 +- lib/hosts/daemon.test.mjs | 75 ++++++++++++++++++++++++++++-- lib/hosts/daemon.ts | 8 +++- lib/hosts/hosts-route.test.mjs | 24 +++++++--- lib/hosts/hub.ts | 34 ++++++++------ lib/hosts/local-bootstrap.test.mjs | 29 ++++++++++-- lib/hosts/local-bootstrap.ts | 29 +++++++++--- 9 files changed, 167 insertions(+), 46 deletions(-) diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index 06f7be6e5..3d5210d11 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -49,8 +49,8 @@ function requestOrigin(req: Request): string { } } -export async function GET() { - return NextResponse.json(await hostsSnapshot(), { headers: noStore }); +export function GET() { + return NextResponse.json(hostsSnapshot(), { headers: noStore }); } export async function POST(req: Request) { diff --git a/instrumentation.node.ts b/instrumentation.node.ts index 74a2f4876..1e5b996e4 100644 --- a/instrumentation.node.ts +++ b/instrumentation.node.ts @@ -62,9 +62,9 @@ export async function register(): Promise { if (process.env.NODE_ENV !== "development") { try { const { ensureLocalHostLink, localLinkUrl } = await import("@/lib/hosts/local-bootstrap"); - const url = localLinkUrl(); - if (url) ensureLocalHostLink({ url }); - else console.warn("[omp-web] local daemon link skipped: OMP_WEB_PORT is not set (start through the ompweb launcher)"); + const target = localLinkUrl(); + if ("url" in target) ensureLocalHostLink({ url: target.url }); + else console.warn(`[omp-web] local daemon link skipped: ${target.skip}`); } catch (error) { console.warn(`[omp-web] local daemon link not prepared: ${error instanceof Error ? error.message : String(error)}`); } diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 99400088c..42afa5814 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -296,8 +296,8 @@ function openHostsChannel(handle: SubscriptionHandle): SubscribeResult { let chain: Promise = Promise.resolve(); const push = () => { chain = chain - .then(async () => { - const snapshot = await hostsSnapshot(); + .then(() => { + const snapshot = hostsSnapshot(); if (handle.active) handle.send(snapshot); }) .catch(() => {}); diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index 997f72dfa..8aaf21e91 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -69,11 +69,11 @@ async function waitFor(predicate, what, timeoutMs = 15_000) { * Like the hub, it takes the hello as a POST and refuses (409) POSTs and blob * uploads that name another link's nonce. `hellos` are the ones a downlink opened. */ function scriptedServer({ getStatus = () => 200, helloStatus = 200, validToken = null } = {}) { - const server = { up: [], hellos: [], offered: null, downlink: null, uplinkDown: false, gets: 0, nonce: null, refused: [], blobs: [], postStatus: [] }; + const server = { validToken, up: [], hellos: [], offered: null, downlink: null, uplinkDown: false, gets: 0, nonce: null, refused: [], blobs: [], postStatus: [] }; let downSeq = 0; let ack = 0; server.fetch = async (url, init = {}) => { - if (validToken && init.headers?.authorization !== `Bearer ${validToken}`) return Response.json({}, { status: 401 }); + if (server.validToken && init.headers?.authorization !== `Bearer ${server.validToken}`) return Response.json({}, { status: 401 }); if (init.method === "POST" && init.headers[LINK_HELLO_HEADER]) { if (helloStatus !== 200) return Response.json({ error: "This link was replaced; wait for the next welcome" }, { status: helloStatus }); server.offered = { id: `hello-${server.gets + 1}`, hello: JSON.parse(String(init.body)) }; @@ -139,9 +139,22 @@ function captureLog() { return { lines, restore: () => { console.error = original; } }; } -test("an http:// loopback server links without --allow-http", () => { - const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "t", allowHttp: false, fetch: async () => Response.json({}, { status: 503 }) }); - return daemon.stop(); +test("an http:// loopback server links without --allow-http", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + try { + await waitFor(() => server.hellos.length === 1, "the link over http://127.0.0.1"); + } finally { + await daemon.stop(); + log.restore(); + } +}); + +test("hostnames that only look like loopback need --allow-http", () => { + for (const url of ["http://localhost.evil.com", "http://127.0.0.1.nip.io", "http://evil-localhost", "http://127.0.0.1@example.com"]) { + assert.throws(() => runHostDaemon({ url, token: "t", allowHttp: false, fetch: async () => Response.json({}, { status: 503 }) }), /https:\/\//, url); + } }); test("an http:// server needs loopback or --allow-http", () => { @@ -547,3 +560,55 @@ test("a 401 with host.json still holding the rejected token exits 1", async () = log.restore(); } }); + +test("a newer token in a host.json that names another server is not adopted", async () => { + const log = captureLog(); + const server = scriptedServer({ validToken: "new" }); + mkdirSync(dirname(hostJson), { recursive: true }); + writeFileSync(hostJson, JSON.stringify({ url: "https://elsewhere.example.com/", token: "new" })); + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "stale", allowHttp: false, fetch: server.fetch }); + try { + assert.equal(await daemon.done, 1); + } finally { + rmSync(hostJson, { force: true }); + log.restore(); + } +}); + +test("a newer token for the same url is adopted when it differs only by a trailing slash", async () => { + const log = captureLog(); + const server = scriptedServer({ validToken: "new" }); + mkdirSync(dirname(hostJson), { recursive: true }); + writeFileSync(hostJson, JSON.stringify({ url: "http://127.0.0.1:9//", token: "new" })); + const daemon = runHostDaemon({ url: "http://127.0.0.1:9/", token: "stale", allowHttp: false, fetch: server.fetch }); + try { + await waitFor(() => server.hellos.length === 1, "the link with the new token"); + } finally { + await daemon.stop(); + rmSync(hostJson, { force: true }); + log.restore(); + } +}); + +test("a blob upload refused with 401 after the web server re-keyed retries with the new token", async () => { + const log = captureLog(); + const server = scriptedServer({ validToken: "old" }); + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "old", allowHttp: false, fetch: server.fetch }); + try { + await waitFor(() => server.downlink, "the downlink"); + const hash = "b".repeat(64); + const media = join(process.env.PI_CODING_AGENT_DIR, "blobs", hash); + mkdirSync(dirname(media), { recursive: true }); + writeFileSync(media, "image-bytes"); + writeHostJson("new"); + server.validToken = "new"; + server.send({ type: "req", id: "m2", op: "readMedia", args: { hash } }); + await waitFor(() => server.res("m2"), "the result"); + assert.equal(server.res("m2").ok, true); + assert.deepEqual(server.blobs, ["m2"]); + } finally { + await daemon.stop(); + rmSync(hostJson, { force: true }); + log.restore(); + } +}); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 73cf2a884..151e61e2c 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -61,6 +61,7 @@ interface Queued { } const loginFile = () => join(getAgentDir(), "omp-web", "host.json"); +const trimUrl = (url: string) => url.replace(/\/+$/, ""); const reason = (error: unknown) => (error instanceof Error ? error.message : String(error)); const log = (message: string) => console.error(`[ompweb host] ${message}`); // 1 s doubling to 60 s; each wait varies ±20% so many hosts do not redial in step. @@ -122,7 +123,7 @@ function sessionsPath(value: unknown): string { return target; } -const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname); +export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname); async function* readLines(body: ReadableStream): AsyncGenerator { const reader = body.getReader(); @@ -293,7 +294,8 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: // A 401 for a token another request already replaced needs nothing more. if (status === 401 && sent === authorization) { const saved = readHostLogin(); - if (saved && `Bearer ${saved.token}` !== sent) { + // Only a host.json for this same server counts: one that names another server is not this daemon's link. + if (saved && trimUrl(saved.url) === trimUrl(options.url) && `Bearer ${saved.token}` !== sent) { authorization = `Bearer ${saved.token}`; log("the server rejected this host's token; using the new one from host.json"); } else { @@ -424,6 +426,8 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: signal, }); if (fatal(response.status, sent)) throw new HostOpError(503, "host_stopping", "ompweb host is stopping"); + // The token was just replaced (or this request carried a replaced one): upload again with the current one. + if (response.status === 401) continue; if (response.status === 409) { if (nonce === used) forgetLink(); continue; diff --git a/lib/hosts/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index f6fbee353..ef1ba3b33 100644 --- a/lib/hosts/hosts-route.test.mjs +++ b/lib/hosts/hosts-route.test.mjs @@ -112,20 +112,32 @@ test("an unreadable hosts.json answers 503 and is never rewritten", async () => assert.equal(readFileSync(hostsFile, "utf8"), broken); }); -test("the reserved local record is not listed twice; getHost(local) is the daemon only while one is linked", async () => { +test("the local row shows the reserved record's real link status; getHost(local) stays the direct host", async () => { writeFileSync(hostsFile, '{"hosts":[]}'); const { localHost } = await jiti.import("./local-host.ts"); const { ensureLocalHostLink } = await jiti.import("./local-bootstrap.ts"); - assert.equal(hub.getHost("local"), localHost); + const localRows = async () => (await get()).hosts.filter((h) => h.id === "local"); + + // Dev server, or before the first bootstrap: no record, no daemon. + assert.deepEqual((await localRows()).map((h) => [h.label, h.status]), [["This machine", "offline"]]); + assert.equal(hub.getLinkedHost("local"), null); + const { token } = ensureLocalHostLink({ url: "http://127.0.0.1:30177" }); - assert.equal(hub.getHost("local"), localHost, "a record alone is not a link"); - assert.deepEqual((await get()).hosts.filter((h) => h.id === "local").map((h) => h.label), ["This machine"]); + assert.deepEqual((await localRows()).map((h) => h.status), ["offline"], "a record alone is not a link"); assert.equal((await linkGet(token)).status, 200); - const linked = hub.getHost("local"); + const [row] = await localRows(); + assert.equal(row.status, "online"); + assert.equal(row.ompVersion, "14.0.0"); + assert.ok(!("allowAgentStart" in row), "the UI shows no revoke/rename controls for this machine"); + assert.equal((await get()).hosts[0].id, "local"); + assert.equal((await get()).hosts.filter((h) => h.id === "local").length, 1); + + assert.equal(hub.getHost("local"), localHost, "until the cutover, sessions run on the direct host"); + const linked = hub.getLinkedHost("local"); assert.notEqual(linked, localHost); assert.equal(linked.id, "local"); - assert.equal((await get()).hosts.filter((h) => h.id === "local").length, 1); + assert.equal((await send("PATCH", { id: "local", allowAgentStart: false })).status, 400); assert.equal((await route.DELETE(new Request(`${BASE}?id=local`, { method: "DELETE" }))).status, 400); }); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 28dac0f81..d559420d9 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -5,7 +5,6 @@ import { randomUUID } from "node:crypto"; import { readBodyWithinLimit, RequestBodyTooLargeError } from "../bounded-form-data"; import type { RpcTransport } from "../omp/rpc-transport"; -import { getOmpVersion } from "../omp/omp-cli"; import type { ProjectRegistryEntry } from "../project-registry"; import { isValidSessionId } from "../session-file-references-core"; import { isRecord } from "../type-guards"; @@ -875,12 +874,14 @@ export class RemoteHost implements Host { } } -/** "local" is this machine: the daemon linked as `local` when one is up, else the direct host (until the direct path is removed); other ids must be registered hosts. */ +/** "local" is this machine; other ids must be registered hosts. Until the direct path is removed, "local" is always the direct host, even while a daemon is linked: see `getLinkedHost`. */ export function getHost(id: string): Host | null { - if (id === LOCAL_HOST_ID) { - const link = hub().links.get(id); - return link && isLinkUp(link.status) ? link.host : localHost; - } + if (id === localHost.id) return localHost; + return getLinkedHost(id); +} + +/** The host reached over its link, for any registered id including the reserved `local`; null when no such record exists. */ +export function getLinkedHost(id: string): Host | null { return loadHosts().some((h) => h.id === id) ? linkFor(id).host : null; } @@ -917,23 +918,28 @@ export function listHosts(): LinkedHostRow[] { export interface LocalHostRow { id: "local"; label: string; - status: "online"; + status: HostStatus; ompVersion: string | null; - platform: string; + platform: string | null; lastSeenAt: null; + hostVersion: number | null; + serverVersion: number; } export type HostRow = LocalHostRow | LinkedHostRow; -/** Settings → Hosts payload (`GET /api/hosts` and the `hosts` channel): this machine first, then linked hosts. */ -export async function hostsSnapshot(): Promise<{ hosts: HostRow[] }> { +/** Settings → Hosts payload (`GET /api/hosts` and the `hosts` channel): this machine first, then linked hosts. This machine's status is its daemon link's. */ +export function hostsSnapshot(): { hosts: HostRow[] } { + const link = hub().links.get(LOCAL_HOST_ID); const local: LocalHostRow = { id: "local", - label: "This machine", - status: "online", - ompVersion: await getOmpVersion(), - platform: process.platform, + label: loadHosts().find((record) => record.id === LOCAL_HOST_ID)?.label ?? "This machine", + status: link?.status ?? "offline", + ompVersion: link?.ompVersion ?? null, + platform: link?.platform ?? null, lastSeenAt: null, + hostVersion: link?.hostVersion ?? null, + serverVersion: LINK_PROTOCOL_VERSION, }; return { hosts: [local, ...listHosts()] }; } diff --git a/lib/hosts/local-bootstrap.test.mjs b/lib/hosts/local-bootstrap.test.mjs index 8dead9555..2b42e883c 100644 --- a/lib/hosts/local-bootstrap.test.mjs +++ b/lib/hosts/local-bootstrap.test.mjs @@ -64,9 +64,28 @@ test("the registry refuses to revoke or edit local, and createHost never makes i assert.equal(loadHosts().filter((host) => host.id === "local").length, 1); }); -test("the link url follows the launcher's port, and ::1 binds", () => { - assert.equal(localLinkUrl({ OMP_WEB_PORT: "30177" }), "http://127.0.0.1:30177"); - assert.equal(localLinkUrl({ OMP_WEB_PORT: "30177", OMP_WEB_HOSTNAME: "0.0.0.0" }), "http://127.0.0.1:30177"); - assert.equal(localLinkUrl({ OMP_WEB_PORT: "30177", OMP_WEB_HOSTNAME: "::1" }), "http://[::1]:30177"); - assert.equal(localLinkUrl({}), null); +test("the link url follows the launcher's port and bind address", () => { + const url = (env) => localLinkUrl({ OMP_WEB_PORT: "30177", ...env }); + assert.deepEqual(url({}), { url: "http://127.0.0.1:30177" }); + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "127.0.0.1" }), { url: "http://127.0.0.1:30177" }); + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "0.0.0.0" }), { url: "http://127.0.0.1:30177" }); + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "::" }), { url: "http://127.0.0.1:30177" }); + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "::1" }), { url: "http://[::1]:30177" }); + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "[::1]" }), { url: "http://[::1]:30177" }); + // localhost resolves to whichever family the server bound: dial it by name. + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "localhost" }), { url: "http://localhost:30177" }); + assert.deepEqual(url({ OMP_WEB_HOSTNAME: "127.0.0.2" }), { url: "http://127.0.0.2:30177" }); +}); + +test("a bind address the daemon could only reach over plain http is skipped with the reason", () => { + assert.match(localLinkUrl({ OMP_WEB_PORT: "30177", OMP_WEB_HOSTNAME: "100.64.0.1" }).skip, /100\.64\.0\.1.*not loopback/); + assert.match(localLinkUrl({ OMP_WEB_PORT: "30177", OMP_WEB_HOSTNAME: "example.com" }).skip, /not loopback/); + assert.match(localLinkUrl({}).skip, /OMP_WEB_PORT/); +}); + +test("a host.json that points at another server is left alone", () => { + const remote = JSON.stringify({ url: "https://main.example.com", token: "remote-token" }); + writeFileSync(hostJson, remote); + assert.throws(() => ensureLocalHostLink({ url: "http://127.0.0.1:40000" }), /main\.example\.com/); + assert.equal(readFileSync(hostJson, "utf8"), remote); }); diff --git a/lib/hosts/local-bootstrap.ts b/lib/hosts/local-bootstrap.ts index 7217c02d5..3a5042b79 100644 --- a/lib/hosts/local-bootstrap.ts +++ b/lib/hosts/local-bootstrap.ts @@ -1,21 +1,36 @@ // The web server's side of the local daemon link: keep the `local` host record // and the daemon's host.json in step. Pure Node: no Next or `@/` imports. -import { loginHost, readHostLogin } from "./daemon"; +import { isLoopbackHost, loginHost, readHostLogin } from "./daemon"; import { hostForToken, LOCAL_HOST_ID, rotateLocalHostToken } from "./registry"; -/** Where the daemon dials this server: its own loopback address on the port it listens on; null when the launcher did not say. */ -export function localLinkUrl(env: NodeJS.ProcessEnv = process.env): string | null { +/** Where the daemon dials this server, or why it cannot: the daemon uses plain http only on loopback, so a bind address elsewhere gets no link. */ +export function localLinkUrl(env: NodeJS.ProcessEnv = process.env): { url: string } | { skip: string } { const port = env.OMP_WEB_PORT; - if (!port) return null; - const v6 = env.OMP_WEB_HOSTNAME === "::1" || env.OMP_WEB_HOSTNAME === "[::1]"; - return `http://${v6 ? "[::1]" : "127.0.0.1"}:${port}`; + if (!port) return { skip: "OMP_WEB_PORT is not set (start through the ompweb launcher)" }; + const bind = env.OMP_WEB_HOSTNAME || "127.0.0.1"; + // A wildcard bind also answers on 127.0.0.1; "localhost" is dialed by name, so it matches whichever family the server bound. + const host = ["0.0.0.0", "::", "[::]"].includes(bind) ? "127.0.0.1" : bind === "::1" ? "[::1]" : bind; + if (!isLoopbackHost(host)) return { skip: `OMP_WEB_HOSTNAME=${bind} is not loopback, so the local daemon cannot link to it over http` }; + return { url: `http://${host}:${port}` }; } +const linksElsewhere = (url: string) => { + try { + return !isLoopbackHost(new URL(url).hostname); + } catch { + return false; + } +}; + /** Make sure the `local` record exists and host.json holds its token and `url`. - * A host.json whose token the registry still accepts is kept, so a restart does not make the daemon redial. */ + * A host.json whose token the registry still accepts is kept, so a restart does not make the daemon redial. + * Throws instead of overwriting a host.json that links this machine's daemon to another server. */ export function ensureLocalHostLink(input: { url: string }): { token: string; written: boolean } { const url = input.url.replace(/\/+$/, ""); const saved = readHostLogin(); + if (saved && linksElsewhere(saved.url)) { + throw new Error(`host.json links this machine's daemon to ${saved.url}, not to this server; remove it to use this server for "This machine"`); + } const kept = saved && hostForToken(saved.token)?.id === LOCAL_HOST_ID ? saved : null; if (kept && kept.url === url) return { token: kept.token, written: false }; const token = kept?.token ?? rotateLocalHostToken(); From 8f2433b22ea14d1c60a69e08a871a6eeefee6b9a Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 22:34:54 +0000 Subject: [PATCH 15/36] refactor(hosts): this machine goes through its daemon --- app/api/cwd/validate/route.ts | 4 +- app/api/mcp/route.ts | 24 ++-- app/api/projects/route.ts | 25 ++-- app/api/sessions/[id]/export/route.ts | 6 +- app/api/sessions/archive/route.ts | 2 + app/api/sessions/import/route.ts | 3 + app/api/worktrees/route.ts | 3 + hooks/useAgentSession.rpc.test.mjs | 6 +- lib/agent-skill-diagnostics-route.test.mjs | 57 ++++---- lib/api-contract.test.mjs | 2 +- lib/api-utils.ts | 4 +- lib/file-access.test.mjs | 25 ++++ lib/file-access.ts | 6 +- lib/hosts/hosts-route.test.mjs | 13 +- lib/hosts/hub.test.mjs | 9 +- lib/hosts/hub.ts | 17 +-- lib/hosts/link-driver.test-helper.mjs | 42 +++++- lib/hosts/no-direct-local.test.mjs | 44 ++++++ lib/hosts/session-index.test.mjs | 48 ++++++- lib/hosts/session-index.ts | 66 +++++---- lib/omp/rpc-process-runtime.test.mjs | 4 +- lib/rpc-manager.test.mjs | 38 ++--- lib/rpc-manager.ts | 68 ++++----- lib/session-resume.test.mjs | 43 +++++- lib/session-resume.ts | 2 +- lib/session-routes.test.mjs | 154 ++++++++++----------- lib/session-watcher.ts | 8 +- 27 files changed, 442 insertions(+), 281 deletions(-) create mode 100644 lib/hosts/no-direct-local.test.mjs diff --git a/app/api/cwd/validate/route.ts b/app/api/cwd/validate/route.ts index a9f38b8cd..e4c3a3dde 100644 --- a/app/api/cwd/validate/route.ts +++ b/app/api/cwd/validate/route.ts @@ -1,7 +1,7 @@ import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { allowFileRoot } from "@/lib/file-access"; -import { localHost } from "@/lib/hosts/local-host"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; import { projectIdentityKey } from "@/lib/paths"; // POST /api/cwd/validate body: { cwd: string; hostId?: string } @@ -20,7 +20,7 @@ export async function POST(req: Request) { const result = await target.host.sessionOps.validateCwd(cwd); if (!result.ok) return opErrorResponse(result); // Browsable only on this machine: another host's paths do not exist here. - if (target.host === localHost) allowFileRoot(result.value.cwd); + if (target.host.id === LOCAL_HOST_ID) allowFileRoot(result.value.cwd); return NextResponse.json({ success: true, cwd: result.value.cwd, diff --git a/app/api/mcp/route.ts b/app/api/mcp/route.ts index 63bbd2611..279d88394 100644 --- a/app/api/mcp/route.ts +++ b/app/api/mcp/route.ts @@ -1,9 +1,10 @@ import { NextResponse } from "next/server"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; import { deleteMcpServer, parseMcpListOutput, readDiscoveredMcpServers, readMcpConfig, readUserMcpConfig, type McpLiveServer, validateMcpServer, writeMcpServer } from "@/lib/omp/mcp-config"; -import { readSessionHeader, resolveSessionPath } from "@/lib/session-reader"; import { WebRpcError, getRpcSession, startRpcSession } from "@/lib/rpc-manager"; -import { resolveSpawnCwdResult } from "@/lib/hosts/local-host"; +import { getHost } from "@/lib/hosts/hub"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; +import { sessionSpawnTarget } from "@/lib/hosts/session-index"; import { RpcCommandError } from "@/lib/omp/rpc-process"; import { parseJsonWithinLimit, RequestBodyTooLargeError } from "@/lib/bounded-form-data"; import { redactMcpServer } from "@/lib/omp/mcp-config"; @@ -92,14 +93,14 @@ export async function GET(request: Request) { try { let session = getRpcSession(sessionId); if (!session?.isAlive()) { - const sessionFile = await resolveSessionPath(sessionId); - if (!sessionFile) throw new Error("Session not found"); - const header = readSessionHeader(sessionFile); - const { cwd } = resolveSpawnCwdResult(header?.cwd); + // MCP settings are this machine's only. + const host = getHost(LOCAL_HOST_ID); + const target = await sessionSpawnTarget(sessionId, host); + if (!target) throw new Error("Session not found"); // Fresh spawn only (an alive child is reused above): apply the // caller's advisor opinion so a racing prompt doesn't inherit a // wrong-flag child for its whole turn. - ({ session } = await startRpcSession(sessionId, sessionFile, cwd, undefined, advisor, header?.cwd)); + ({ session } = await startRpcSession(sessionId, target.sessionFile, target.cwd, undefined, advisor, target.recordedCwd, undefined, host)); } liveServers = mergeMcpServers(parseMcpListOutput(await session.getMcpList()), inventory); } catch (error) { @@ -156,11 +157,10 @@ export async function PATCH(request: Request) { // Do not create a different session or apply the caller's arbitrary cwd. let session = getRpcSession(body.sessionId); if (!session?.isAlive()) { - const sessionFile = await resolveSessionPath(body.sessionId); - if (!sessionFile) throw new Error("Session not found"); - const header = readSessionHeader(sessionFile); - const { cwd } = resolveSpawnCwdResult(header?.cwd); - ({ session } = await startRpcSession(body.sessionId, sessionFile, cwd, undefined, undefined, header?.cwd)); + const host = getHost(LOCAL_HOST_ID); + const target = await sessionSpawnTarget(body.sessionId, host); + if (!target) throw new Error("Session not found"); + ({ session } = await startRpcSession(body.sessionId, target.sessionFile, target.cwd, undefined, undefined, target.recordedCwd, undefined, host)); } if (session.isRunning()) return NextResponse.json({ error: "Wait for the current run to finish before changing MCP servers." }, { status: 409 }); await session.changeMcp(body.action, typeof body.name === "string" ? body.name : undefined); diff --git a/app/api/projects/route.ts b/app/api/projects/route.ts index a4b8967cb..804f91ca0 100644 --- a/app/api/projects/route.ts +++ b/app/api/projects/route.ts @@ -1,10 +1,10 @@ import { NextResponse } from "next/server"; import { apiErrorResponse, opErrorResponse, resolveHostOrError } from "@/lib/api-utils"; import { allowFileRoot } from "@/lib/file-access"; -import { localHost } from "@/lib/hosts/local-host"; -import { listRemoteProjects } from "@/lib/hosts/session-index"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; +import { listProjectsAllHosts } from "@/lib/hosts/session-index"; import type { ProjectUpdate } from "@/lib/hosts/session-ops"; -import { isReservedLaunchArg, mergeProjects, ProjectPathError } from "@/lib/project-registry"; +import { isReservedLaunchArg, ProjectPathError } from "@/lib/project-registry"; import type { ProjectLaunchConfig } from "@/lib/types"; const MAX_EXTRA_ARGS = 32; const MAX_EXTRA_ARG_LENGTH = 256; @@ -36,20 +36,13 @@ function parseLaunchConfig(value: unknown): ProjectLaunchConfig | undefined { // sort with pins first — see lib/project-ordering.ts). export async function GET() { try { - const { sessionOps } = localHost; - const registry = { version: 1 as const, projects: await sessionOps.listProjects() }; - const sessions = await sessionOps.listSessions(); - const discovered = sessions - .map((s) => s.projectRoot ?? s.cwd) - .filter((path): path is string => Boolean(path)); - const projects = mergeProjects(registry, discovered); + const projects = await listProjectsAllHosts(); // Keep the in-memory browse allowlist warm for registered projects that // have no sessions (the in-memory list does not survive restarts, and an // empty managed project derives no root from sessions). Only this // machine's: another host's paths do not exist here. - for (const project of projects) allowFileRoot(project.path); - const local = projects.map((project) => ({ ...project, hostId: localHost.id })); - return NextResponse.json({ projects: [...local, ...await listRemoteProjects()] }); + for (const project of projects) if (project.hostId === LOCAL_HOST_ID) allowFileRoot(project.path); + return NextResponse.json({ projects }); } catch (error) { return apiErrorResponse(error); } @@ -68,7 +61,7 @@ export async function POST(req: Request) { const { host } = target; const result = await host.sessionOps.addProject(cwd, launchConfig); if (!result.ok) return opErrorResponse(result); - if (host !== localHost) return NextResponse.json({ project: { ...result.value, hostId: host.id } }); + if (host.id !== LOCAL_HOST_ID) return NextResponse.json({ project: { ...result.value, hostId: host.id } }); allowFileRoot(result.value.path); return NextResponse.json({ project: result.value }); } catch (error) { @@ -132,9 +125,9 @@ export async function PATCH(req: Request) { if (!result.ok) return opErrorResponse(result); // Only after a successful save: a failed write must not leave an orphaned // in-memory browse authorization behind. Never for another host's paths. - if (target.host === localHost) for (const root of result.value.newRoots) allowFileRoot(root); + if (target.host.id === LOCAL_HOST_ID) for (const root of result.value.newRoots) allowFileRoot(root); const { projects } = result.value; - return NextResponse.json({ projects: target.host === localHost ? projects : projects.map((project) => ({ ...project, hostId: target.host.id })) }); + return NextResponse.json({ projects: target.host.id === LOCAL_HOST_ID ? projects : projects.map((project) => ({ ...project, hostId: target.host.id })) }); } catch (error) { if (error instanceof ProjectPathError) { return NextResponse.json({ error: error.message, code: error.code }, { status: 400 }); diff --git a/app/api/sessions/[id]/export/route.ts b/app/api/sessions/[id]/export/route.ts index f7d2e44f3..eb99df227 100644 --- a/app/api/sessions/[id]/export/route.ts +++ b/app/api/sessions/[id]/export/route.ts @@ -1,6 +1,6 @@ import { apiErrorResponse, opErrorResponse, resolveSessionHostOr404 } from "@/lib/api-utils"; import { getContentDisposition } from "@/lib/content-disposition"; -import { localHost } from "@/lib/hosts/local-host"; +import { LOCAL_HOST_ID } from "@/lib/hosts/registry"; export const runtime = "nodejs"; @@ -17,8 +17,8 @@ export async function GET( if ("response" in resolved) return resolved.response; const result = await resolved.host.sessionOps.exportSession(id); if (!result.ok) return opErrorResponse(result); - // A daemon's HTML is untrusted: opened inline it would run on this origin. - const asInline = inline && resolved.host.id === localHost.id; + // Another host's HTML is untrusted: opened inline it would run on this origin. This machine's daemon is the server's own. + const asInline = inline && resolved.host.id === LOCAL_HOST_ID; return new Response(result.value.html, { headers: { "Content-Type": "text/html; charset=utf-8", diff --git a/app/api/sessions/archive/route.ts b/app/api/sessions/archive/route.ts index 3062df609..09eec963b 100644 --- a/app/api/sessions/archive/route.ts +++ b/app/api/sessions/archive/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from "next/server"; import { apiErrorResponse } from "@/lib/api-utils"; import { listArchivedSessions, restoreArchivedSession } from "@/lib/omp/archive"; +import { invalidateLocalSessionLists } from "@/lib/hosts/session-index"; import { invalidateSessionListCache } from "@/lib/session-reader"; import type { ArchivedSessionInfo } from "@/lib/types"; @@ -35,6 +36,7 @@ export async function POST(req: Request) { } const sessionId = restoreArchivedSession(body.key); invalidateSessionListCache(); + invalidateLocalSessionLists(); return NextResponse.json({ ok: true, sessionId }); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/app/api/sessions/import/route.ts b/app/api/sessions/import/route.ts index d5871fa3e..82ee4349c 100644 --- a/app/api/sessions/import/route.ts +++ b/app/api/sessions/import/route.ts @@ -4,6 +4,7 @@ import { mkdirSync, writeFileSync } from "fs"; import path from "path"; import { randomUUID } from "crypto"; import { getSessionsDir, getSessionDirNameForCwd } from "@/lib/omp/paths"; +import { invalidateLocalSessionLists } from "@/lib/hosts/session-index"; import { invalidateSessionListCache } from "@/lib/session-reader"; import { invalidateSessionFileListCache } from "@/lib/omp/session-files"; import { getAllowedFileRoots, isExistingFilePathAllowed } from "@/lib/file-access"; @@ -95,6 +96,8 @@ export async function POST(req: Request) { // mtime-keyed walk cache (the AGENTS.md-documented Windows/NTFS trap). invalidateSessionListCache(); invalidateSessionFileListCache(); + // The sidebar lists this machine's sessions through its daemon. + invalidateLocalSessionLists(); return NextResponse.json({ success: true, sessionFile }); } catch (error) { diff --git a/app/api/worktrees/route.ts b/app/api/worktrees/route.ts index 39d8ac15e..2d564cc22 100644 --- a/app/api/worktrees/route.ts +++ b/app/api/worktrees/route.ts @@ -5,6 +5,7 @@ import { join } from "path"; import { addWorktree, findCurrentWorktreePath, listWorktrees, removeWorktree, resolveProject } from "@/lib/worktree"; import { allowFileRoot, getAllowedFileRoots, isExistingFilePathAllowed, isFilePathAllowed } from "@/lib/file-access"; import { projectIdentityKey } from "@/lib/paths"; +import { invalidateLocalSessionLists } from "@/lib/hosts/session-index"; import { invalidateSessionListCache } from "@/lib/session-reader"; /** Same gate as /api/files: only session cwds / project roots / explicitly @@ -87,6 +88,7 @@ export async function POST(req: Request) { const result = await addWorktree(body.cwd, body.branch); invalidateSessionListCache(); + invalidateLocalSessionLists(); return NextResponse.json(result); } catch (error) { const message = error instanceof Error ? error.message : String(error); @@ -109,6 +111,7 @@ export async function DELETE(req: Request) { await removeWorktree(body.cwd, body.path, body.force === true); invalidateSessionListCache(); + invalidateLocalSessionLists(); return NextResponse.json({ success: true }); } catch (error) { const message = error instanceof Error ? error.message : String(error); diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 6bde8283e..33e22c9e8 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -283,6 +283,8 @@ const { useAgentSession } = await jiti.import("../hooks/useAgentSession.ts"); const { selectSessionHistory } = await jiti.import("@/lib/session-sync"); const { publishSessionsChanged } = await jiti.import("@/lib/session-change-bus"); const { AgentSessionWrapper } = await jiti.import("@/lib/rpc-manager"); +// Wrappers built directly need an online host; the daemon's machine host is one. +const { localHost } = await jiti.import("@/lib/hosts/local-host"); const { isUnknownSlashCommand, slashCommandName, runHostTool } = await jiti.import("@/hooks/useAgentSession-stream"); const { toastCalls } = await jiti.import("@/components/ui/toast"); const { MessageView } = await jiti.import("@/components/MessageView"); @@ -2123,7 +2125,7 @@ function attachNativeWrapper(t, sid) { }, sendFrame() {}, async dispose() {}, - }, process.cwd()); + }, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); world.wrappers.set(sid, wrapper); t.after(() => wrapper.destroyAndWait()); @@ -2742,7 +2744,7 @@ async function attachEditableWrapper(t, native, { holdHistory = false } = {}) { }, sendFrame() {}, async dispose() { listeners.clear(); }, - }, process.cwd()); + }, process.cwd(), null, false, "", undefined, localHost); t.after(() => wrapper.destroyAndWait()); native.onMove = () => emitNative({ type: "notice", source: "session-persistence", level: "warning", message: "Session moved to a sibling file because another process owns the original" }); wrapper.onIdentityChange((oldId, newId, options) => { diff --git a/lib/agent-skill-diagnostics-route.test.mjs b/lib/agent-skill-diagnostics-route.test.mjs index 76fcb2591..cd298b493 100644 --- a/lib/agent-skill-diagnostics-route.test.mjs +++ b/lib/agent-skill-diagnostics-route.test.mjs @@ -1,55 +1,49 @@ import assert from "node:assert/strict"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import test, { after } from "node:test"; import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; +import { linkLocalHost, listedSession, ompChild } from "./hosts/link-driver.test-helper.mjs"; -// Real POST /api/agent/[id] handler against a real saved-session file. The omp -// binary is a launcher stub that records every launch and exits at once, so a -// launch record is the observable proof that a child process was created. +// Real POST /api/agent/[id] handler for a saved session on this machine. Its +// daemon is driven by hand, so a `spawn` request is the observable proof that +// an omp child was created. const jiti = createJiti(import.meta.url, { tryNative: false, alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, }); const agentRoute = await jiti.import("../app/api/agent/[id]/route.ts"); +const hub = await jiti.import("./hosts/hub.ts"); -const SAVED_ID = "saved-skill-session"; +const SAVED_ID = "01a0e6b0-d916-7610-8343-f4a766ba0051"; const agentDir = mkdtempSync(join(tmpdir(), "omp-web-skill-diagnostics-route-")); -const projectDir = join(agentDir, "sessions", "-project"); -mkdirSync(projectDir, { recursive: true }); -writeFileSync( - join(projectDir, "2026-01-01_saved.jsonl"), - `${[ - { type: "session", version: 3, id: SAVED_ID, cwd: tmpdir(), timestamp: "2026-01-01T00:00:00.000Z" }, - { type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hello" } }, - ].map((line) => JSON.stringify(line)).join("\n")}\n`, -); - -const launchLog = join(agentDir, "omp-launches.log"); -const fakeOmp = join(agentDir, process.platform === "win32" ? "fake-omp.cmd" : "fake-omp"); -writeFileSync( - fakeOmp, - process.platform === "win32" - ? `@echo off\r\necho launched>> "${launchLog}"\r\nexit /b 1\r\n` - : `#!/bin/sh\necho launched >> '${launchLog}'\nexit 1\n`, - { mode: 0o755 }, -); - const previousAgentDir = process.env.PI_CODING_AGENT_DIR; -const previousBin = process.env.OMP_WEB_OMP_BIN; process.env.PI_CODING_AGENT_DIR = agentDir; -process.env.OMP_WEB_OMP_BIN = fakeOmp; + +const spawns = []; +const daemon = await linkLocalHost(); +const omp = ompChild(daemon, SAVED_ID); +daemon.serve({ + async spawn(args) { + spawns.push(args); + await daemon.post({ type: "stdout", ch: args.ch, line: '{"type":"ready"}' }); + return { cwd: args.cwd, fellBack: false, launchAdvisor: false, autoApproveExtension: false }; + }, + listSessions: () => [listedSession(SAVED_ID)], + sessionFileExists: () => true, + invalidateSessionLists: () => null, +}, (message) => (message.type === "kill" ? daemon.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }) : omp(message))); + after(() => { + hub.closeHostLink("local"); if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previousAgentDir; - if (previousBin === undefined) delete process.env.OMP_WEB_OMP_BIN; - else process.env.OMP_WEB_OMP_BIN = previousBin; rmSync(agentDir, { recursive: true, force: true }); }); -const launches = () => (existsSync(launchLog) ? readFileSync(launchLog, "utf8").split(/\r?\n/).filter(Boolean).length : 0); +const launches = () => spawns.length; const post = (id, body, query = "") => agentRoute.POST( new Request(`http://localhost/api/agent/${id}${query}`, { @@ -62,7 +56,7 @@ const post = (id, body, query = "") => agentRoute.POST( /** Replace the process-wide wrapper registry and clear the launch record for one test. */ function useRegistry(t, wrappers = {}) { - rmSync(launchLog, { force: true }); + spawns.length = 0; const previousSessions = globalThis.__ompSessions; const previousLocks = globalThis.__ompStartLocks; globalThis.__ompSessions = new Map(Object.entries(wrappers)); @@ -149,4 +143,5 @@ test("an ordinary command for the same saved session still starts omp", async (t assert.equal(launches(), 1, `a session-owning command resumes omp (response ${response.status}: ${text})`); assert.notEqual(response.status, 409); + await globalThis.__ompSessions.get(SAVED_ID)?.destroyAndWait(); }); diff --git a/lib/api-contract.test.mjs b/lib/api-contract.test.mjs index 9ad7bb56f..66404a02d 100644 --- a/lib/api-contract.test.mjs +++ b/lib/api-contract.test.mjs @@ -219,7 +219,7 @@ test("agent command route binds a cold set_model to the lazy spawn (#277)", asyn test("mcp listing carries the advisor opinion into fresh spawns only", async () => { const route = await readFile(new URL("../app/api/mcp/route.ts", import.meta.url), "utf8"); assert.match(route, /params\.get\("advisor"\) === "1"/); - assert.match(route, /startRpcSession\(sessionId, sessionFile, cwd, undefined, advisor/); + assert.match(route, /startRpcSession\(sessionId, target\.sessionFile, target\.cwd, undefined, advisor/); // An alive child is always reused for listing; the opinion must never // trigger a flag-mismatch replace of a live session. assert.match(route, /getRpcSession\(sessionId\)/); diff --git a/lib/api-utils.ts b/lib/api-utils.ts index 83167a5f5..cd86ecf7d 100644 --- a/lib/api-utils.ts +++ b/lib/api-utils.ts @@ -2,9 +2,9 @@ import { NextResponse } from "next/server"; import { isLinkUp, type Host } from "./hosts/host"; import { getHost } from "./hosts/hub"; import { HostOpError } from "./hosts/link-protocol"; -import { localHost } from "./hosts/local-host"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId } from "./hosts/session-index"; +import { LOCAL_HOST_ID } from "./hosts/registry"; import { WebRpcError } from "./rpc-manager"; const SESSION_NOT_FOUND = { error: "Session not found", code: "session_not_found" } as const; @@ -25,7 +25,7 @@ export function hostOfflineResponse(host: Host): NextResponse | null { /** The host a request names (`hostId`, this machine when absent): 404 when unknown, 503 while offline. */ export function resolveHostOrError(hostId: unknown): { host: Host } | { response: NextResponse } { - const host = hostId === undefined ? localHost : typeof hostId === "string" ? getHost(hostId) : null; + const host = hostId === undefined ? getHost(LOCAL_HOST_ID) : typeof hostId === "string" ? getHost(hostId) : null; if (!host) return { response: NextResponse.json({ error: "Host not found", code: "host_not_found" }, { status: 404 }) }; const offline = hostOfflineResponse(host); return offline ? { response: offline } : { host }; diff --git a/lib/file-access.test.mjs b/lib/file-access.test.mjs index 8f1875f03..94111abad 100644 --- a/lib/file-access.test.mjs +++ b/lib/file-access.test.mjs @@ -182,6 +182,31 @@ test("allows omp's config and agent roots alongside workspaces", async (t) => { clearAllowedRootsCache(); }); +test("this machine's session roots come from its daemon's session list", async (t) => { + const { getAllowedFileRoots } = await loadSubject(); + const { closeHostLink } = await jiti.import("./hosts/hub.ts"); + const { linkLocalHost, listedSession } = await import("./hosts/link-driver.test-helper.mjs"); + const previousAgentDir = process.env.PI_CODING_AGENT_DIR; + const isolated = fs.mkdtempSync(path.join(os.tmpdir(), "omp-web-file-access-")); + t.after(() => { + closeHostLink("local"); + if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR; + else process.env.PI_CODING_AGENT_DIR = previousAgentDir; + fs.rmSync(isolated, { recursive: true, force: true }); + globalThis.__ompHostLists = undefined; + clearAllowedRootsCache(); + }); + process.env.PI_CODING_AGENT_DIR = isolated; + globalThis.__ompHostLists = undefined; + clearAllowedRootsCache(); + const daemon = await linkLocalHost(); + daemon.serve({ listSessions: () => [{ ...listedSession("11111111-2222-4333-8444-555555555555", "/srv/app/pkg"), projectRoot: "/srv/app" }] }); + + const roots = await getAllowedFileRoots(); + assert.ok(roots.has("/srv/app/pkg"), "the session cwd is browsable"); + assert.ok(roots.has("/srv/app"), "its project root is browsable"); +}); + test("serves a bare workspace path through GET instead of 403-ing it", async (t) => { const { allowFileRoot } = await loadSubject(); const { GET } = await jiti.import("../app/api/files/[...path]/route.ts"); diff --git a/lib/file-access.ts b/lib/file-access.ts index 7fdccad8f..8e5e275ba 100644 --- a/lib/file-access.ts +++ b/lib/file-access.ts @@ -3,7 +3,8 @@ import { homedir } from "os"; import path from "path"; import { getAgentDir, getConfigRoot } from "./omp/paths"; import { isWindowsAbsolutePath } from "./paths"; -import { listAllSessions } from "./session-reader"; +import { hostSessions } from "./hosts/session-index"; +import { LOCAL_HOST_ID } from "./hosts/registry"; export { isWindowsAbsolutePath } from "./paths"; @@ -96,7 +97,8 @@ export async function getAllowedFileRoots(): Promise> { const now = Date.now(); const cached = globalThis.__piAllowedRootsCache; if (cached && cached.expiresAt > now) return cached.roots; - const sessions = await listAllSessions(); + // This machine's sessions, as its daemon lists them (the last list while it is offline). + const sessions = await hostSessions(LOCAL_HOST_ID); const roots = new Set(); for (const s of sessions) { if (s.cwd) roots.add(normalizeSlashes(s.cwd)); diff --git a/lib/hosts/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index ef1ba3b33..751828408 100644 --- a/lib/hosts/hosts-route.test.mjs +++ b/lib/hosts/hosts-route.test.mjs @@ -112,15 +112,14 @@ test("an unreadable hosts.json answers 503 and is never rewritten", async () => assert.equal(readFileSync(hostsFile, "utf8"), broken); }); -test("the local row shows the reserved record's real link status; getHost(local) stays the direct host", async () => { +test("the local row and getHost(local) show the reserved record's real link status", async () => { writeFileSync(hostsFile, '{"hosts":[]}'); - const { localHost } = await jiti.import("./local-host.ts"); const { ensureLocalHostLink } = await jiti.import("./local-bootstrap.ts"); const localRows = async () => (await get()).hosts.filter((h) => h.id === "local"); // Dev server, or before the first bootstrap: no record, no daemon. assert.deepEqual((await localRows()).map((h) => [h.label, h.status]), [["This machine", "offline"]]); - assert.equal(hub.getLinkedHost("local"), null); + assert.equal(hub.getHost("local").status(), "offline"); const { token } = ensureLocalHostLink({ url: "http://127.0.0.1:30177" }); assert.deepEqual((await localRows()).map((h) => h.status), ["offline"], "a record alone is not a link"); @@ -133,10 +132,10 @@ test("the local row shows the reserved record's real link status; getHost(local) assert.equal((await get()).hosts[0].id, "local"); assert.equal((await get()).hosts.filter((h) => h.id === "local").length, 1); - assert.equal(hub.getHost("local"), localHost, "until the cutover, sessions run on the direct host"); - const linked = hub.getLinkedHost("local"); - assert.notEqual(linked, localHost); - assert.equal(linked.id, "local"); + // Sessions on this machine run through the same link. + const local = hub.getHost("local"); + assert.equal(local.id, "local"); + assert.equal(local.status(), "online"); assert.equal((await send("PATCH", { id: "local", allowAgentStart: false })).status, 400); assert.equal((await route.DELETE(new Request(`${BASE}?id=local`, { method: "DELETE" }))).status, 400); diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index 9039e5143..c708d18c5 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -831,8 +831,13 @@ test("an over-limit batch gets 413; a batch cut mid-line applies nothing", async }); test("getHost resolves local, linked and unknown ids", async () => { - const { localHost } = await jiti.import("./local-host.ts"); - assert.equal(hub.getHost("local"), localHost); + // This machine is its daemon's link, also before any record exists: offline until a daemon links. + const local = hub.getHost("local"); + assert.equal(local, hub.getHost("local"), "one RemoteHost for this machine"); + assert.equal(local.id, "local"); + assert.equal(local.label, "This machine"); + assert.equal(local.status(), "offline"); + await assert.rejects(local.sessionOps.listSessions(), (error) => error.status === 503); assert.equal(hub.getHost("no-such-host"), null); const { host } = createHost("Never linked"); const remote = hub.getHost(host.id); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index d559420d9..7ed9d9344 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -28,7 +28,6 @@ import { type HostOpName, type UpMessage, } from "./link-protocol"; -import { localHost } from "./local-host"; import { HostRegistryUnreadableError, hostForToken, LOCAL_HOST_ID, loadHosts, touchHost, type HostRecord } from "./registry"; import type { SessionOps } from "./session-ops"; @@ -131,7 +130,7 @@ function linkFor(id: string): Link { } function labelOf(id: string): string { - return loadHosts().find((h) => h.id === id)?.label ?? id; + return loadHosts().find((h) => h.id === id)?.label ?? (id === LOCAL_HOST_ID ? "This machine" : id); } function notify(listeners: Iterable<(...args: A) => void>, ...args: A): void { @@ -874,15 +873,11 @@ export class RemoteHost implements Host { } } -/** "local" is this machine; other ids must be registered hosts. Until the direct path is removed, "local" is always the direct host, even while a daemon is linked: see `getLinkedHost`. */ +/** `local` is this machine, reached through its daemon link (offline while none is linked); other ids must be registered hosts. */ +export function getHost(id: typeof LOCAL_HOST_ID): Host; +export function getHost(id: string): Host | null; export function getHost(id: string): Host | null { - if (id === localHost.id) return localHost; - return getLinkedHost(id); -} - -/** The host reached over its link, for any registered id including the reserved `local`; null when no such record exists. */ -export function getLinkedHost(id: string): Host | null { - return loadHosts().some((h) => h.id === id) ? linkFor(id).host : null; + return id === LOCAL_HOST_ID || loadHosts().some((h) => h.id === id) ? linkFor(id).host : null; } export interface LinkedHostRow { @@ -933,7 +928,7 @@ export function hostsSnapshot(): { hosts: HostRow[] } { const link = hub().links.get(LOCAL_HOST_ID); const local: LocalHostRow = { id: "local", - label: loadHosts().find((record) => record.id === LOCAL_HOST_ID)?.label ?? "This machine", + label: labelOf(LOCAL_HOST_ID), status: link?.status ?? "offline", ompVersion: link?.ompVersion ?? null, platform: link?.platform ?? null, diff --git a/lib/hosts/link-driver.test-helper.mjs b/lib/hosts/link-driver.test-helper.mjs index 2f7f6e485..d7b128c0f 100644 --- a/lib/hosts/link-driver.test-helper.mjs +++ b/lib/hosts/link-driver.test-helper.mjs @@ -6,8 +6,8 @@ import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); const hub = await jiti.import("./hub.ts"); -const { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION } = await jiti.import("./link-protocol.ts"); -const { createHost } = await jiti.import("./registry.ts"); +const { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION, SESSION_OP_PARAMS } = await jiti.import("./link-protocol.ts"); +const { createHost, rotateLocalHostToken } = await jiti.import("./registry.ts"); const URL_BASE = "http://main.test/api/hosts/link"; @@ -19,6 +19,28 @@ export async function linkHost(label, { channels = [] } = {}) { return link; } +/** Link this machine's daemon: the reserved `local` record. */ +export async function linkLocalHost({ channels = [] } = {}) { + const link = new LinkDriver("local", rotateLocalHostToken()); + await link.dial({ channels }); + return link; +} + +/** Link this machine's daemon and run its real session ops on the current agent dir in this + * process, as `ompweb host` does; `ops` adds or replaces ops (spawn, say). readMedia bytes do not go as a blob. */ +export async function linkLocalDaemon(ops = {}, onMessage = undefined) { + const { localHost } = await jiti.import("./local-host.ts"); + const { sessionOps } = await jiti.import("./session-ops.ts"); + const link = await linkLocalHost(); + link.serve({ + ...Object.fromEntries(Object.entries(SESSION_OP_PARAMS).map(([op, params]) => [op, (args) => sessionOps[op](...params.map((name) => args[name]))])), + sessionFileExists: ({ path }) => localHost.sessionFileExists(path), + invalidateSessionLists: ({ path }) => localHost.invalidateSessionLists(path) ?? null, + ...ops, + }, onMessage); + return link; +} + /** Poll `predicate` until it holds; fails after 5 s instead of hanging the test. */ export async function until(predicate, what) { const deadline = Date.now() + 5_000; @@ -116,12 +138,22 @@ export class LinkDriver { return this.post({ type: "res", id: req.id, ok: true, result: value }); } - /** Answer every `req` from `ops[op](args)` until the downlink ends; other messages go to `onMessage`. */ + /** Answer every `req` from `ops[op](args)` (a throw answers failed, as the daemon does) until the downlink ends; other messages go to `onMessage`. */ serve(ops, onMessage = () => {}) { return (async () => { for (let message = await this.next(); message; message = await this.next()) { - if (message.type === "req" && ops[message.op]) await this.answer(message, await ops[message.op](message.args)); - else await onMessage(message); + if (message.type !== "req" || !ops[message.op]) { + await onMessage(message); + continue; + } + let value; + try { + value = await ops[message.op](message.args); + } catch (error) { + await this.post({ type: "res", id: message.id, ok: false, error: { status: error.status ?? 500, code: error.code ?? "host_op_failed", message: error.message } }); + continue; + } + await this.answer(message, value); } })(); } diff --git a/lib/hosts/no-direct-local.test.mjs b/lib/hosts/no-direct-local.test.mjs new file mode 100644 index 000000000..f912b0d0c --- /dev/null +++ b/lib/hosts/no-direct-local.test.mjs @@ -0,0 +1,44 @@ +// This machine is reached only through its daemon link: nothing on the web +// server's side may run omp children or read session files through LocalHost. +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; + +const ROOT = fileURLToPath(new URL("../../", import.meta.url)); + +const ALLOWED = new Set([ + "lib/hosts/daemon.ts", + "lib/hosts/local-host.ts", + // The RPC layer's default transport, used by main's utility omp (models, login), never a session. + "lib/omp/rpc-process.ts", +]); + +const IMPORT_RE = /\b(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']|\bimport\s*\(\s*["']([^"']+)["']\s*\)/g; + +function sourceFiles(dir) { + return readdirSync(join(ROOT, dir), { withFileTypes: true }).flatMap((entry) => { + const path = `${dir}/${entry.name}`; + if (entry.isDirectory()) return sourceFiles(path); + return /\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !/\.test(?:-helper)?\.[cm]?[jt]s$/.test(entry.name) ? [path] : []; + }); +} + +/** Files under app/ and lib/ that import the local-host module or spawnLocalRpcTransport. */ +function directLocalImports() { + return ["app", "lib"].flatMap(sourceFiles).filter((path) => { + if (ALLOWED.has(path)) return false; + const source = readFileSync(join(ROOT, path), "utf8"); + for (const match of source.matchAll(IMPORT_RE)) { + const specifier = match[1] ?? match[2]; + if (/(?:^|\/)local-host(?:\.ts)?$/.test(specifier)) return true; + if (match[1] && /\bspawnLocalRpcTransport\b/.test(match[0])) return true; + } + return false; + }); +} + +test("only the daemon imports local-host or spawnLocalRpcTransport", () => { + assert.deepEqual(directLocalImports(), []); +}); diff --git a/lib/hosts/session-index.test.mjs b/lib/hosts/session-index.test.mjs index 17cb8b1f9..f5375a2e3 100644 --- a/lib/hosts/session-index.test.mjs +++ b/lib/hosts/session-index.test.mjs @@ -6,7 +6,7 @@ import { join } from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; -import { linkHost, until } from "./link-driver.test-helper.mjs"; +import { linkHost, linkLocalHost, until } from "./link-driver.test-helper.mjs"; const jiti = createJiti(import.meta.url); const hub = await jiti.import("./hub.ts"); @@ -17,7 +17,7 @@ const SHARED = "11111111-2222-4333-8444-555555555555"; const OTHER = "11111111-2222-4333-8444-666666666666"; const defaultTimings = { ...hub.linkTimings }; -/** Own agent dir (so only this test's hosts are registered), optionally with one local session. */ +/** Own agent dir (so only this test's hosts are registered), optionally with one session file on this machine's disk. */ function setup(t, { localSessionId } = {}) { const agentDir = mkdtempSync(join(tmpdir(), "omp-web-session-index-")); if (localSessionId) { @@ -42,9 +42,9 @@ function setup(t, { localSessionId } = {}) { invalidateSessionListCache(); rmSync(agentDir, { recursive: true, force: true }); }); - /** Link a host that answers ops from `ops`. */ + /** Link a host that answers ops from `ops`; a null label links this machine's daemon. */ return async (label, ops) => { - const link = await linkHost(label); + const link = label === null ? await linkLocalHost() : await linkHost(label); links.push(link); link.serve(ops); return link; @@ -64,7 +64,8 @@ const entry = (id, extra = {}) => ({ }); test("an id on this machine and a remote host is listed once, as local", async (t) => { - const link = setup(t, { localSessionId: SHARED }); + const link = setup(t); + await link(null, { listSessions: () => [entry(SHARED)] }); const remote = await link("Remote", { listSessions: () => [entry(SHARED), entry(OTHER)] }); const sessions = await index.listSessionsAllHosts(); assert.deepEqual(sessions.map((s) => [s.id, s.hostId]), [[SHARED, "local"], [OTHER, remote.id]]); @@ -72,6 +73,39 @@ test("an id on this machine and a remote host is listed once, as local", async ( assert.equal((await index.hostForSessionId(OTHER)).id, remote.id); }); +test("this machine's sessions come from its daemon only, never from the files on disk", async (t) => { + const link = setup(t, { localSessionId: SHARED }); + assert.deepEqual(await index.listSessionsAllHosts(), [], "no daemon linked: nothing is read here"); + assert.equal(await index.hostForSessionId(SHARED), null); + + await link(null, { listSessions: () => [entry(SHARED, { cwd: "/srv/app" })] }); + index.invalidateHostSessionList("local"); + assert.deepEqual((await index.listSessionsAllHosts()).map((s) => [s.id, s.hostId, s.path]), [[SHARED, "local", `/remote/sessions/${SHARED}.jsonl`]]); + const host = await index.hostForSessionId(SHARED); + assert.equal(host, hub.getHost("local")); + assert.deepEqual(await index.sessionSpawnTarget(SHARED, host), { sessionFile: `/remote/sessions/${SHARED}.jsonl`, cwd: "/srv/app", recordedCwd: "/srv/app" }); +}); + +test("a change on this machine's disk drops its list on the daemon and here", async (t) => { + const link = setup(t); + let listed = [entry(SHARED)]; + const invalidated = []; + await link(null, { listSessions: () => listed, invalidateSessionLists: ({ path }) => { invalidated.push(path); return null; } }); + assert.deepEqual((await index.listSessionsAllHosts()).map((s) => s.id), [SHARED]); + listed = [entry(SHARED), entry(OTHER)]; + index.invalidateLocalSessionLists("/s/new.jsonl"); + await until(() => invalidated.length === 1, "the daemon's invalidation"); + assert.deepEqual(invalidated, ["/s/new.jsonl"]); + assert.deepEqual((await index.listSessionsAllHosts()).map((s) => s.id), [SHARED, OTHER]); +}); + +test("projects list this machine's daemon first, then linked hosts", async (t) => { + const link = setup(t); + const remote = await link("Remote", { listProjects: () => [], listSessions: () => [entry(OTHER)] }); + await link(null, { listProjects: () => [{ path: tmpdir(), addedAt: "2026-01-01T00:00:00.000Z", hidden: false }], listSessions: () => [] }); + assert.deepEqual((await index.listProjectsAllHosts()).map((p) => [p.path, p.hostId]), [[tmpdir(), "local"], ["/remote/project", remote.id]]); +}); + test("an id on two remote hosts only is listed under the first host by label", async (t) => { const link = setup(t); await link("b-mac", { listSessions: () => [entry(SHARED)] }); @@ -125,6 +159,10 @@ test("a route given an unknown hostId answers 404, a host that is not linked 503 const offline = await validate(host.id); assert.equal(offline.status, 503); assert.deepEqual(await offline.json(), { error: "Asleep is offline", code: "host_offline", hostOffline: true, delivery: "refused" }); + // No hostId is this machine: offline like any host until its daemon links. + const local = await validate(undefined); + assert.equal(local.status, 503); + assert.equal((await local.json()).error, "This machine is offline"); // A command whose link dropped after it was sent may still run there. const { apiErrorResponse } = await routeJiti.import("../../lib/api-utils.ts"); const { WebRpcError } = await routeJiti.import("../../lib/rpc-manager.ts"); diff --git a/lib/hosts/session-index.ts b/lib/hosts/session-index.ts index be9daa6d3..f75aff274 100644 --- a/lib/hosts/session-index.ts +++ b/lib/hosts/session-index.ts @@ -1,16 +1,15 @@ // Sessions and projects across hosts (spec "Routing", "Data flow"): this -// machine's lists plus each linked host's, cached per host. +// machine's lists (from its daemon) plus each linked host's, cached per host. // No `next/*` or `@/` imports. import { createHash } from "node:crypto"; import { mergeProjects, type ProjectRegistryEntry } from "../project-registry"; import { isValidSessionId } from "../session-file-references-core"; -import { readSessionHeader, resolveSessionPath } from "../session-reader"; import type { ManagedProject, SessionInfo } from "../types"; import { isLinkUp, type Host } from "./host"; import { getHost, listHosts, onHostHello } from "./hub"; -import { localHost, resolveSpawnCwdResult } from "./local-host"; +import { LOCAL_HOST_ID } from "./registry"; -/** Same TTL as the local session-list cache. */ +/** Same TTL as the daemon's own session-list cache. */ const LIST_TTL_MS = 30_000; interface HostLists { @@ -42,13 +41,14 @@ function hostLists(hostId: string): HostLists { return lists; } -/** Linked hosts in sidebar order: by label, case-insensitive. */ -function remoteHosts(): { id: string; label: string; status: string }[] { - return listHosts().sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase()) || a.id.localeCompare(b.id)); +/** Host ids in sidebar order: this machine, then linked hosts by label, case-insensitive. */ +function hostIds(): string[] { + const remote = listHosts().sort((a, b) => a.label.toLowerCase().localeCompare(b.label.toLowerCase()) || a.id.localeCompare(b.id)); + return [LOCAL_HOST_ID, ...remote.map((host) => host.id)]; } -/** One linked host's sessions, cached for LIST_TTL_MS. An unreachable or failing host keeps its last list. */ -async function hostSessions(hostId: string, refresh = false): Promise { +/** One host's sessions, cached for LIST_TTL_MS. An unreachable or failing host keeps its last list. */ +export async function hostSessions(hostId: string, refresh = false): Promise { const lists = hostLists(hostId); if (!refresh && Date.now() - lists.fetchedAt < LIST_TTL_MS) return lists.sessions; const host = getHost(hostId); @@ -73,11 +73,10 @@ async function hostSessions(hostId: string, refresh = false): Promise { - const hosts = remoteHosts(); - const [local, ...remote] = await Promise.all([localHost.sessionOps.listSessions(), ...hosts.map((host) => hostSessions(host.id))]); - const merged: SessionInfo[] = local.map((session) => ({ ...session, hostId: localHost.id })); - const seen = new Set(merged.map((session) => session.id)); - for (const sessions of remote) { + const lists = await Promise.all(hostIds().map((id) => hostSessions(id))); + const merged: SessionInfo[] = []; + const seen = new Set(); + for (const sessions of lists) { for (const session of sessions) { if (seen.has(session.id)) continue; seen.add(session.id); @@ -87,20 +86,19 @@ export async function listSessionsAllHosts(): Promise { return merged; } -async function remoteHostFor(id: string, refresh: boolean): Promise { - const hosts = remoteHosts(); - const lists = await Promise.all(hosts.map((host) => hostSessions(host.id, refresh))); +async function hostWithSession(id: string, refresh: boolean): Promise { + const ids = hostIds(); + const lists = await Promise.all(ids.map((hostId) => hostSessions(hostId, refresh))); const index = lists.findIndex((sessions) => sessions.some((session) => session.id === id)); - return index === -1 ? null : getHost(hosts[index].id); + return index === -1 ? null : getHost(ids[index]); } -/** The host holding a session: this machine first, then the linked hosts' lists, refreshed once on a miss. */ +/** The host holding a session: this machine first, then the linked hosts by label; the lists are refreshed once on a miss. */ export async function hostForSessionId(id: string): Promise { - if (await resolveSessionPath(id)) return localHost; - // Remote lists only hold valid ids: a malformed one never costs a round trip. + // Host lists only hold valid ids: a malformed one never costs a round trip. if (!isValidSessionId(id)) return null; // shortcut: every miss re-asks each linked host; throttle per host if polling for gone sessions shows up. - return (await remoteHostFor(id, false)) ?? (await remoteHostFor(id, true)); + return (await hostWithSession(id, false)) ?? (await hostWithSession(id, true)); } /** Where a session's file is and which cwd to start it in, on `host`; null when the host has no such session. */ @@ -108,12 +106,6 @@ export async function sessionSpawnTarget( id: string, host: Host, ): Promise<{ sessionFile: string; cwd: string; recordedCwd: string | undefined } | null> { - if (host === localHost) { - const sessionFile = await resolveSessionPath(id); - if (!sessionFile) return null; - const header = readSessionHeader(sessionFile); - return { sessionFile, cwd: resolveSpawnCwdResult(header?.cwd).cwd, recordedCwd: header?.cwd }; - } // The host's own list entry carries its file path and recorded cwd; the // host resolves a missing cwd on its machine when it spawns. const find = async (refresh: boolean) => (await hostSessions(host.id, refresh)).find((session) => session.id === id); @@ -121,7 +113,7 @@ export async function sessionSpawnTarget( return info ? { sessionFile: info.path, cwd: info.cwd, recordedCwd: info.cwd } : null; } -/** Drop one linked host's cached session list; it is kept as the fallback while the host is unreachable. */ +/** Drop one host's cached session list; it is kept as the fallback while the host is unreachable. */ export function invalidateHostSessionList(hostId: string): void { const lists = globalThis.__ompHostLists?.get(hostId); if (!lists) return; @@ -129,9 +121,15 @@ export function invalidateHostSessionList(hostId: string): void { lists.generation += 1; } -/** Each linked host's projects (its registry plus session-discovered ones), tagged with `hostId`. */ -export async function listRemoteProjects(): Promise { - const perHost = await Promise.all(remoteHosts().map(async ({ id }) => { +/** This machine's session files changed outside any host op (a terminal omp, an import, an archive restore): its daemon and main drop their lists. */ +export function invalidateLocalSessionLists(sessionFile?: string): void { + getHost(LOCAL_HOST_ID).invalidateSessionLists(sessionFile); + invalidateHostSessionList(LOCAL_HOST_ID); +} + +/** Each host's projects (its registry plus session-discovered ones), this machine first, tagged with `hostId`. */ +export async function listProjectsAllHosts(): Promise { + const perHost = await Promise.all(hostIds().map(async (id) => { const host = getHost(id); const lists = hostLists(id); if (host && isLinkUp(host.status())) { @@ -142,8 +140,8 @@ export async function listRemoteProjects(): Promise { } } const discovered = (await hostSessions(id)).map((session) => session.projectRoot ?? session.cwd).filter(Boolean); - // Remote paths are never resolved on this machine. - return mergeProjects({ version: 1, projects: lists.projects }, discovered, (path) => path).map((project) => ({ ...project, hostId: id })); + // Only this machine's paths resolve here; another host's are never resolved on this machine. + return mergeProjects({ version: 1, projects: lists.projects }, discovered, id === LOCAL_HOST_ID ? undefined : (path) => path).map((project) => ({ ...project, hostId: id })); })); return perHost.flat(); } diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 1fda4f683..5e658185f 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -7,6 +7,8 @@ import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); const { RpcProcess, RpcCommandTimeoutError } = jiti("./rpc-process.ts"); const { AgentSessionWrapper } = jiti("../rpc-manager.ts"); +// Wrappers built directly need an online host; the daemon's machine host is one. +const { localHost } = jiti("../hosts/local-host.ts"); /** Outbound v2 chunk records exactly as OMP emits them. */ function chunkRecords(frame, chunkId, payloadBytes = 256 * 1024) { @@ -177,7 +179,7 @@ for (const type of ["remove_queued_message", "promote_queued_message"]) { const proc = startProcess(transport); await proc.waitReady(); t.mock.timers.enable({ apis: ["setTimeout"] }); - const wrapper = new AgentSessionWrapper(proc, process.cwd()); + const wrapper = new AgentSessionWrapper(proc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); try { diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index e7b95353e..d44843d4d 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -22,6 +22,8 @@ test.after(() => { const runtimeJiti = createJiti(import.meta.url); const { AgentSessionWrapper: SnapshotWrapper, subscribeHostToolCalls } = await runtimeJiti.import("./rpc-manager.ts"); +// Wrappers built directly need an online host; the daemon's machine host is one. +const { localHost } = await runtimeJiti.import("./hosts/local-host.ts"); function snapshotSession(t, sendCommand = async () => ({}), Wrapper = SnapshotWrapper, sessionId = "", disconnectDestroyMs) { const frameListeners = new Set(); @@ -32,7 +34,7 @@ function snapshotSession(t, sendCommand = async () => ({}), Wrapper = SnapshotWr sendCommand, sendFrame(frame) { sentFrames.push(frame); }, dispose: async () => {}, - }, process.cwd(), null, false, sessionId, ...(disconnectDestroyMs === undefined ? [] : [disconnectDestroyMs])); + }, process.cwd(), null, false, sessionId, disconnectDestroyMs, localHost); wrapper.start(); t.after(() => wrapper.destroyAndWait()); return { wrapper, sentFrames, get listenerCount() { return frameListeners.size; }, emit: (event) => { for (const listener of frameListeners) listener(event); } }; @@ -222,7 +224,7 @@ test("agent startup broadcasts a session-list refresh without waiting for a repl assert.match(agentStart, /invalidateSessionLists\(\)/); assert.match(agentStart, /refreshSessionList = true/); assert.match(source, /private invalidateSessionLists\(\)/); - assert.match(source, /invalidateSessionListCache\(\)/); + assert.match(source, /this\.host\.invalidateSessionLists\(this\._sessionFile \|\| undefined\)/); assert.match(source, /notifyRunningChange\(\{ refreshSessionList \}\)/); assert.match(source, /snapshot === lastRunningSnapshot && !refreshSessionList/); }); @@ -370,7 +372,7 @@ test("missing terminal agent_end clears isPromptRunning on raw idle get_state", dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); await wrapper.send({ type: "prompt", message: "Hello" }); @@ -410,7 +412,7 @@ test("prompt ack pending does not let raw idle get_state clear promptRunning", a dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); const promptPromise = wrapper.send({ type: "prompt", message: "Hello" }); @@ -453,7 +455,7 @@ test("isTerminal:false respects 2-second grace period before raw idle can clear dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); await wrapper.send({ type: "prompt", message: "Hello" }); @@ -491,7 +493,7 @@ test("abort_and_prompt images go through the same server-side validation as prom dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); await assert.rejects( @@ -523,7 +525,7 @@ test("get_state timeout preserves the process and reports a transient status err dispose: async () => { disposed = true; }, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); await assert.rejects( @@ -591,7 +593,7 @@ test("prompt ack timeout recycles a child that accepts the frame but withholds i dispose: async () => { disposed = true; }, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.onDestroy(() => { removedFromRegistry = true; }); wrapper.start(); @@ -657,7 +659,7 @@ test("unexpected child exit is retained until a replacement session clears it", dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); await wrapper.waitUntilReady(); wrapper.expectedExitProc = fakeProc; @@ -699,7 +701,7 @@ test("a resumed session crash is retained before its initial handshake", async ( sendFrame: () => {}, dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "resume-before-ready"); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "resume-before-ready", undefined, localHost); wrapper.start(); wrapper.handleProcessExit({ code: 1, signal: null, stderrTail: "startup failed" }); @@ -737,7 +739,7 @@ async function notifyingSession(t) { sendFrame: () => {}, dispose: async () => {}, }; - const wrapper = new SnapshotWrapper(fakeProc, process.cwd()); + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); await wrapper.waitUntilReady(); t.after(async () => { @@ -929,7 +931,7 @@ test("mcp list ack timeout recycles a child that accepts the frame but withholds dispose: async () => { disposed = true; }, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); const pending = wrapper.getMcpList(); @@ -971,7 +973,7 @@ test("mcp list ack timeout clears the waiter so a retry is not blocked as busy", dispose: async () => {}, }; - const wrapper = new AgentSessionWrapper(fakeProc, process.cwd()); + const wrapper = new AgentSessionWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); const first = wrapper.getMcpList(); @@ -1312,7 +1314,7 @@ test("startup opts into the ask dialog and still starts when omp rejects the com sendFrame: () => {}, dispose: async () => {}, }; - const wrapper = new SnapshotWrapper(fakeProc, process.cwd()); + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); t.after(() => wrapper.destroyAndWait()); await wrapper.waitUntilReady(); @@ -1598,7 +1600,7 @@ test("a session stuck in its startup handshake is never reaped", async (t) => { sendFrame: () => {}, dispose: async () => {}, }; - const wrapper = new SnapshotWrapper(proc, process.cwd(), null, false, "", REAP_MS); + const wrapper = new SnapshotWrapper(proc, process.cwd(), null, false, "", REAP_MS, localHost); t.after(() => wrapper.destroyAndWait()); const inner = proc.dispose.bind(proc); proc.dispose = async () => { disposed.push(Date.now()); return inner(); }; @@ -1899,7 +1901,7 @@ test("skill diagnostics cross the wrapper only as parsed public DTOs", async (t) sendFrame: () => {}, dispose: async () => {}, }; - const wrapper = new SnapshotWrapper(fakeProc, process.cwd()); + const wrapper = new SnapshotWrapper(fakeProc, process.cwd(), null, false, "", undefined, localHost); wrapper.start(); t.after(() => wrapper.destroyAndWait()); @@ -2595,7 +2597,9 @@ test("initial spawn and reload both keep same-session editing available through t.after(() => { spawnMock.mock.restore(); syncBuiltinESMExports(); }); const isolated = createJiti(import.meta.url, { moduleCache: false, tryNative: false }); const { startRpcSession } = await isolated.import("./rpc-manager.ts"); - const { session, realSessionId } = await startRpcSession(sessionId, sessionFile, isolatedAgentDir); + // The daemon's machine host spawns the (mocked) omp in this process. + const { localHost: spawningHost } = await isolated.import("./hosts/local-host.ts"); + const { session, realSessionId } = await startRpcSession(sessionId, sessionFile, isolatedAgentDir, undefined, undefined, undefined, undefined, spawningHost); t.after(() => session.destroyAndWait()); const events = []; session.onEvent((event) => events.push(event)); diff --git a/lib/rpc-manager.ts b/lib/rpc-manager.ts index cd5e353b2..160e6235e 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1,12 +1,11 @@ import { randomUUID } from "crypto"; -import { existsSync } from "fs"; import { validateAgentImages } from "./image-attachments"; import { hasVisibleAssistantContent } from "./assistant-response"; import { invalidateModelsCache } from "./models-cache"; import { RpcCommandError, RpcCommandTimeoutError, RpcProcess, type RpcFrame } from "./omp/rpc-process"; import type { RpcTransport } from "./omp/rpc-transport"; import { editSessionHistory, isSessionEditReply, SESSION_EDIT_COMMAND, SessionEditAgentInvocationError, type SessionEditResult } from "./omp/session-edit"; -import { cacheSessionPath, invalidateSessionListCache } from "./session-reader"; +import { cacheSessionPath } from "./session-reader"; import { allowFileRoot } from "./file-access"; import { loadWebServerSettings } from "./web-settings"; import { @@ -35,7 +34,7 @@ import type { import type { AgentMessage, CrossSessionHostToolCall, ExitedRpcSession, ExtensionWidgetItem } from "./types"; import { isLinkUp, type Host, type HostStatus } from "./hosts/host"; import { freezeHostLinks, getHost, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; -import { localHost } from "./hosts/local-host"; +import { LOCAL_HOST_ID } from "./hosts/registry"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId, invalidateHostSessionList, listSessionsAllHosts, sessionSpawnTarget } from "./hosts/session-index"; import type { SessionLiveSnapshot, SessionLiveToolEvent, SessionStreamCursor } from "./session-sync"; @@ -353,7 +352,7 @@ export class AgentSessionWrapper { /** Test seam: the real value is DISCONNECT_DESTROY_MS (120s), far too long * for a unit test. 0 disables reaping for that wrapper. */ disconnectDestroyMs: number = DISCONNECT_DESTROY_MS, - host: Host = localHost, + host: Host = getHost(LOCAL_HOST_ID), launchAdvisor = false, fellBack = false, ) { @@ -654,8 +653,8 @@ export class AgentSessionWrapper { this.streaming = state.isStreaming; this.compacting = state.isCompacting; this.fastModeEnabled = state.fastModeEnabled ?? state.fastMode ?? this.fastModeEnabled; - // The local path cache resolves ids to files on this machine only. - if (this._sessionFile && this.host === localHost) cacheSessionPath(this._sessionId, this._sessionFile); + // The path cache resolves ids to files on this machine only (file authorization). + if (this._sessionFile && this.host.id === LOCAL_HOST_ID) cacheSessionPath(this._sessionId, this._sessionFile); if (moved) { this.sessionMovePending = false; if (oldId !== this._sessionId) { @@ -804,7 +803,7 @@ export class AgentSessionWrapper { : null; // Recorded before destroy(): its running-change broadcast must carry the // record so sidebars that missed the notice below still see the exit. - if (this._sessionId) getExitedMap().set(this._sessionId, { id: this._sessionId, cwd: this.cwd, ...(this.host.id === localHost.id ? {} : { hostId: this.host.id }), at: Date.now(), code, signal, detail }); + if (this._sessionId) getExitedMap().set(this._sessionId, { id: this._sessionId, cwd: this.cwd, ...(this.host.id === LOCAL_HOST_ID ? {} : { hostId: this.host.id }), at: Date.now(), code, signal, detail }); this.emit({ type: "notice", level: "error", @@ -2491,13 +2490,9 @@ function getRegistry(): Map { const cleanup = () => { // Children dying from here on are the shutdown, not finished runs. markShuttingDown(); - // A linked host's children run on: nothing more reaches its daemon (no kill, no + // Every child runs under a host daemon: nothing more reaches it (no kill, no // host tool rejection as tabs close on the way out), and the next server adopts them. freezeHostLinks(); - // Only this process's own children are stopped. - globalThis.__ompSessions?.forEach((s) => { - if (s.host === localHost) s.destroy(); - }); }; process.once("exit", cleanup); process.once("SIGINT", cleanup); @@ -2520,7 +2515,7 @@ export function getRunningRpcSessions(): RunningRpcSession[] { for (const [sessionId, session] of getRegistry()) { if (session.isRunning()) { const id = session.sessionId || sessionId; - map.set(id, { id, cwd: session.cwd, ...(session.host.id === localHost.id ? {} : { hostId: session.host.id }) }); + map.set(id, { id, cwd: session.cwd, ...(session.host.id === LOCAL_HOST_ID ? {} : { hostId: session.host.id }) }); } } return [...map.values()]; @@ -2539,7 +2534,7 @@ export function getLiveRpcSessionIds(): string[] { * reconnect sessions on demand and start them with the updated executable. */ export async function restartAllRpcSessions(): Promise { // An update changes this machine's omp only; remote runs keep going. - const sessions = [...new Set(getRegistry().values())].filter((session) => session.host.id === localHost.id); + const sessions = [...new Set(getRegistry().values())].filter((session) => session.host.id === LOCAL_HOST_ID); await Promise.all(sessions.map((session) => session.destroyAndWait())); return sessions.length; } @@ -2624,13 +2619,12 @@ export function syncInterruptibleSessions(): void { /** * Restart the sessions that were mid-run when omp-web last stopped and ask - * each to continue. Only runs when the auto-resume setting is on. A remote - * session waits for its host's next hello and its orphan child's exit. + * each to continue. Only runs when the auto-resume setting is on. Each session, + * this machine's included, waits for its host's hello: a child its daemon still + * runs is adopted there, and only a dead one resumes, after its orphan's exit. */ export async function resumeInterruptedSessions(): Promise { - const sessions = takeInterruptedSessions(); - resumeOnHostLink(sessions.filter((session) => session.hostId !== localHost.id), resumeSession); - await Promise.all(sessions.filter((session) => session.hostId === localHost.id).map(resumeSession)); + resumeOnHostLink(takeInterruptedSessions(), resumeSession); } /** Start an interrupted session again on its host and ask it to continue. Never rejects. */ @@ -2682,12 +2676,13 @@ function createAgentToolOps(): AgentToolSessionOps { async listSessions() { const running = new Set(getRunningRpcSessionIds()); const sessions = await listSessionsAllHosts(); - return sessions.map((s) => ({ id: s.id, name: s.name, cwd: s.cwd, running: running.has(s.id), hostId: s.hostId ?? localHost.id })); + return sessions.map((s) => ({ id: s.id, name: s.name, cwd: s.cwd, running: running.has(s.id), hostId: s.hostId ?? LOCAL_HOST_ID })); }, listHosts() { + const local = getHost(LOCAL_HOST_ID); return [ - { id: localHost.id, label: localHost.label, online: true, allowAgentStart: true }, + { id: local.id, label: local.label, online: isLinkUp(local.status()), allowAgentStart: true }, ...listHosts().map((h) => ({ id: h.id, label: h.label, online: isLinkUp(h.status), allowAgentStart: h.allowAgentStart })), ]; }, @@ -2756,8 +2751,8 @@ function createAgentToolOps(): AgentToolSessionOps { /** * Spawn a brand-new session on `host` in `cwd`, checked where it lives: the - * host answers with the path it will use. Registers the cwd with this - * machine's file routes, or refreshes the host's session list. + * host answers with the path it will use. Registers this machine's cwd with + * its file routes, and refreshes the host's session list. */ export async function startNewRpcSession( host: Host, @@ -2765,25 +2760,16 @@ export async function startNewRpcSession( toolNames?: string[], advisor?: boolean, ): Promise> { - let spawnCwd = cwd; - if (host === localHost) { - if (!existsSync(cwd)) return { ok: false, status: 400, code: "directory_not_found", error: `Directory does not exist: ${cwd}` }; - } else { - const validated = await host.sessionOps.validateCwd(cwd); - if (!validated.ok) return validated; - spawnCwd = validated.value.cwd; - } + const validated = await host.sessionOps.validateCwd(cwd); + if (!validated.ok) return validated; + const spawnCwd = validated.value.cwd; // Unique per call: startRpcSession coalesces concurrent callers that share a key onto one session. const tempKey = `__new__${randomUUID()}`; const started = await startRpcSession(tempKey, "", spawnCwd, toolNames, advisor, undefined, undefined, host); - if (host === localHost) { - // Without this a file request under a brand-new cwd would 403 for up to the allowed-roots cache TTL. - // Never for another host: its paths do not exist on this machine. - allowFileRoot(spawnCwd); - invalidateSessionListCache(); - } else { - invalidateHostSessionList(host.id); - } + // Without this a file request under a brand-new cwd would 403 for up to the allowed-roots cache TTL. + // Never for another host: its paths do not exist on this machine. + if (host.id === LOCAL_HOST_ID) allowFileRoot(spawnCwd); + invalidateHostSessionList(host.id); return { ok: true, value: started }; } @@ -2808,7 +2794,7 @@ export async function startRpcSession( * or a completed turn); the picker path re-binds on each cold switch, so * the user is never stuck on the unrestorable model. */ spawnModel?: string, - host: Host = localHost, + host: Host = getHost(LOCAL_HOST_ID), ): Promise<{ session: AgentSessionWrapper; realSessionId: string }> { const registry = getRegistry(); const locks = getLocks(); @@ -2817,7 +2803,7 @@ export async function startRpcSession( // server is being adopted or killed. Waiting here, before the registry and // the lock, lets a start join an adopted child; a killed one must exit first: // two children must never write one session file. A live wrapper is past that. - if (sessionFile && host !== localHost && !registry.get(sessionId)?.isAlive()) await orphanExit(host.id, sessionId); + if (sessionFile && !registry.get(sessionId)?.isAlive()) await orphanExit(host.id, sessionId); const existing = registry.get(sessionId); // Union semantics, matching the spawn below and the wrapper identity: diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index a5457c652..d4758622a 100644 --- a/lib/session-resume.test.mjs +++ b/lib/session-resume.test.mjs @@ -6,7 +6,7 @@ import { join } from "node:path"; import test from "node:test"; import { setTimeout as sleep } from "node:timers/promises"; import { createJiti } from "jiti"; -import { LinkDriver, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; +import { LinkDriver, linkLocalHost, listedSession, ompChild, until } from "./hosts/link-driver.test-helper.mjs"; const jiti = createJiti(import.meta.url); /** A new omp-web process: fresh tracker, same agent dir. */ @@ -14,11 +14,11 @@ function restart() { globalThis.__ompResumeTracker = undefined; } -const { EXIT_GRACE_MS, markShuttingDown, recordRunningSessions, resumeOnHostLink, takeInterruptedSessions } = await jiti.import("./session-resume.ts"); +const { EXIT_GRACE_MS, markShuttingDown, recordRunningSessions, RESUME_PROMPT, resumeOnHostLink, takeInterruptedSessions } = await jiti.import("./session-resume.ts"); const { saveWebServerSettings } = await jiti.import("./web-settings.ts"); const hub = await jiti.import("./hosts/hub.ts"); const { createHost } = await jiti.import("./hosts/registry.ts"); -const { getRpcSession } = await jiti.import("./rpc-manager.ts"); +const { getRpcSession, resumeInterruptedSessions } = await jiti.import("./rpc-manager.ts"); /** Fresh agent dir and tracker per test; the resume setting starts as given. */ function setup(t, { enabled }) { @@ -202,3 +202,40 @@ test("a remote entry whose child the server adopts on hello is not resumed", asy await sleep(10); assert.deepEqual(resumed, [], "the run goes on in the adopted child"); }); + +test("this machine's interrupted run waits for its daemon's hello and resumes there", async (t) => { + const spawns = []; + const prompts = []; + let link = null; + // Before setup's cleanup: disposing the wrapper records running sessions in this test's agent dir. + t.after(async () => { + await getRpcSession(A.id)?.destroyAndWait(); + hub.closeHostLink("local"); + }); + const { listPath } = setup(t, { enabled: true }); + writeFileSync(listPath, JSON.stringify({ sessions: [A] })); + restart(); + await resumeInterruptedSessions(); + await sleep(10); + assert.equal(getRpcSession(A.id), undefined, "nothing starts before this machine's daemon links"); + + // The daemon restarted too: its hello lists no child, so the run resumes on it. + link = await linkLocalHost(); + const omp = ompChild(link, A.id); + link.serve({ + async spawn(args) { + spawns.push(args); + await link.post({ type: "stdout", ch: args.ch, line: '{"type":"ready"}' }); + return { cwd: args.cwd, fellBack: false, launchAdvisor: false, autoApproveExtension: false }; + }, + listSessions: () => [listedSession(A.id)], + sessionFileExists: () => true, + invalidateSessionLists: () => null, + }, async (message) => { + if (message.type === "kill") return link.post({ type: "exit", ch: message.ch, code: null, signal: "SIGTERM" }); + if (message.type === "stdin" && JSON.parse(message.line).type === "prompt") prompts.push(JSON.parse(message.line).message); + return omp(message); + }); + await until(() => prompts.includes(RESUME_PROMPT), "the resume prompt on this machine's daemon"); + assert.deepEqual(spawns.map((spawn) => spawn.sessionFile), [listedSession(A.id).path]); +}); diff --git a/lib/session-resume.ts b/lib/session-resume.ts index 9fa8884f9..2c1911e6c 100644 --- a/lib/session-resume.ts +++ b/lib/session-resume.ts @@ -198,7 +198,7 @@ export function takeInterruptedSessions(): InterruptibleSession[] { } /** - * Resume remote entries once their host links, once only. startRpcSession + * Resume entries (this machine's too) once their host links, once only. startRpcSession * waits for any orphan child of the session the host still runs (spec Rules * → Reattach). A child the server adopts on that hello runs on: its entry is * dropped. A host already linked in this run said hello before this ran; a diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5d966ed28..90a97732c 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -4,9 +4,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import test from "node:test"; import { createJiti } from "jiti"; -import fs from "node:fs"; -import { syncBuiltinESMExports } from "node:module"; import { fileURLToPath } from "node:url"; +import { linkLocalDaemon } from "./hosts/link-driver.test-helper.mjs"; const jiti = createJiti(import.meta.url, { alias: { @@ -21,6 +20,7 @@ const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/rout const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await jiti.import("./session-reader.ts"); const { allowFileRoot, normalizeSlashes } = await jiti.import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await jiti.import("./rpc-manager.ts"); +const { closeHostLink } = await jiti.import("./hosts/hub.ts"); const getContext = (id, query = "") => contextRoute.GET( new Request(`http://localhost/api/sessions/${id}/context${query ? `?${query}` : ""}`), @@ -35,20 +35,24 @@ const getState = (id) => stateRoute.GET( // MAX_SESSION_LOAD_BYTES from lib/omp/session-files.ts (1 GiB). const MAX_SESSION_LOAD_BYTES = 1024 * 1024 * 1024; -/** Point the omp agent dir at a throwaway location for the duration of `run`. */ -async function withAgentDir(run) { +/** Point the omp agent dir at a throwaway location for the duration of `run`; + * this machine's daemon serves it from this process. */ +async function withAgentDir(run, daemonOps = {}) { const agentDir = mkdtempSync(join(tmpdir(), "omp-web-session-routes-")); const projectDir = join(agentDir, "sessions", "-project"); mkdirSync(projectDir, { recursive: true }); const previous = process.env.PI_CODING_AGENT_DIR; process.env.PI_CODING_AGENT_DIR = agentDir; - // The global session-list cache (30s TTL) and the path cache could hold - // entries from another test's agent dir; clear both so resolution sees only - // THIS dir's files. + // The global session-list cache (30s TTL), the path cache and main's per-host + // lists could hold entries from another test's agent dir; clear them so + // resolution sees only THIS dir's files. invalidateSessionListCache(); + globalThis.__ompHostLists = undefined; + await linkLocalDaemon(daemonOps); try { await run(projectDir); } finally { + closeHostLink("local"); if (previous === undefined) delete process.env.PI_CODING_AGENT_DIR; else process.env.PI_CODING_AGENT_DIR = previous; invalidateSessionListCache(); @@ -94,14 +98,14 @@ function makeOversized(filePath) { test("session route returns 413 session_file_too_large when a valid-header file exceeds the load ceiling", async () => { await withAgentDir(async (dir) => { const filePath = writeSessionFile(dir, "2026-01-01_giant.jsonl", { - id: "giant-session", + id: "0a000000-0000-4000-8000-000000000001", cwd: join(tmpdir(), "omp-web-missing-project"), timestamp: "2026-01-01T00:00:00.000Z", }, [{ type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hi" } }]); makeOversized(filePath); - const req = new Request("http://localhost/api/sessions/giant-session"); - const res = await sessionRoute.GET(req, { params: Promise.resolve({ id: "giant-session" }) }); + const req = new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000001"); + const res = await sessionRoute.GET(req, { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000001" }) }); assert.equal(res.status, 413, "valid header must not degrade to 200 with an empty transcript"); const body = await res.json(); @@ -112,14 +116,14 @@ test("session route returns 413 session_file_too_large when a valid-header file test("context route returns 413 session_file_too_large when a valid-header file exceeds the load ceiling", async () => { await withAgentDir(async (dir) => { const filePath = writeSessionFile(dir, "2026-01-01_giant.jsonl", { - id: "giant-context", + id: "0a000000-0000-4000-8000-000000000002", cwd: join(tmpdir(), "omp-web-missing-project"), timestamp: "2026-01-01T00:00:00.000Z", }, [{ type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "hi" } }]); makeOversized(filePath); - const req = new Request("http://localhost/api/sessions/giant-context/context?leafId=u1"); - const res = await contextRoute.GET(req, { params: Promise.resolve({ id: "giant-context" }) }); + const req = new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000002/context?leafId=u1"); + const res = await contextRoute.GET(req, { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000002" }) }); assert.equal(res.status, 413, "valid header must not degrade to 200 with an empty context"); const body = await res.json(); @@ -130,11 +134,11 @@ test("context route returns 413 session_file_too_large when a valid-header file test("oversized file with an INVALID header still 413s, not 404", async () => { await withAgentDir(async (dir) => { const filePath = join(dir, "2026-01-01_bad-giant.jsonl"); - writeFileSync(filePath, '{"type":"session","version":3,"id":"bad-giant","cwd":"/tmp","timestamp":"2026-01-01T00:00:00.000Z"}\n'); + writeFileSync(filePath, '{"type":"session","version":3,"id":"0a000000-0000-4000-8000-000000000003","cwd":"/tmp","timestamp":"2026-01-01T00:00:00.000Z"}\n'); makeOversized(filePath); - const req = new Request("http://localhost/api/sessions/bad-giant"); - const res = await sessionRoute.GET(req, { params: Promise.resolve({ id: "bad-giant" }) }); + const req = new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000003"); + const res = await sessionRoute.GET(req, { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000003" }) }); assert.equal(res.status, 413, "too large is reported as too large even when the header scan fails"); const body = await res.json(); @@ -145,7 +149,7 @@ test("oversized file with an INVALID header still 413s, not 404", async () => { test("session and context routes still serve a normal-size file with 200", async () => { await withAgentDir(async (dir) => { writeSessionFile(dir, "2026-01-01_small.jsonl", { - id: "small-session", + id: "0a000000-0000-4000-8000-000000000004", cwd: join(tmpdir(), "omp-web-missing-project"), timestamp: "2026-01-01T00:00:00.000Z", }, [ @@ -153,8 +157,8 @@ test("session and context routes still serve a normal-size file with 200", async { type: "message", id: "a1", parentId: "u1", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: "world" } }, ]); - const req = new Request("http://localhost/api/sessions/small-session"); - const res = await sessionRoute.GET(req, { params: Promise.resolve({ id: "small-session" }) }); + const req = new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000004"); + const res = await sessionRoute.GET(req, { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000004" }) }); assert.equal(res.status, 200); const body = await res.json(); assert.equal(body.context.messages.length, 2, "normal file still yields its transcript"); @@ -163,15 +167,15 @@ test("session and context routes still serve a normal-size file with 200", async // Branch semantics: the context for a leaf is the path TO that leaf. // `u1` is the root, so its context is just itself; `a1` (a child of u1) // is a sibling branch whose context is u1 -> a1. - const ctxReq = new Request("http://localhost/api/sessions/small-session/context?leafId=u1"); - const ctxRes = await contextRoute.GET(ctxReq, { params: Promise.resolve({ id: "small-session" }) }); + const ctxReq = new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000004/context?leafId=u1"); + const ctxRes = await contextRoute.GET(ctxReq, { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000004" }) }); assert.equal(ctxRes.status, 200); const ctxBody = await ctxRes.json(); assert.equal(ctxBody.context.messages.length, 1, "leaf u1 is the root, so its context contains only itself"); assert.deepEqual(ctxBody.context.entryIds, ["u1"]); - const branchReq = new Request("http://localhost/api/sessions/small-session/context?leafId=a1"); - const branchRes = await contextRoute.GET(branchReq, { params: Promise.resolve({ id: "small-session" }) }); + const branchReq = new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000004/context?leafId=a1"); + const branchRes = await contextRoute.GET(branchReq, { params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000004" }) }); assert.equal(branchRes.status, 200); const branchBody = await branchRes.json(); assert.equal(branchBody.context.messages.length, 2, "leaf a1's context is the full u1 -> a1 branch"); @@ -198,45 +202,45 @@ test("DELETE /api/sessions/[id] re-parents children to the grandparent and stops await withAgentDir(async (dir) => { const cwd = join(tmpdir(), "omp-web-missing-project"); const gpPath = writeSessionFile(dir, "2026-01-01_gp.jsonl", { - id: "gp-id", + id: "0a000000-0000-4000-8000-000000000005", cwd, timestamp: "2026-01-01T00:00:00.000Z", }, [{ type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "gp" } }]); const parentPath = writeSessionFile(dir, "2026-01-02_parent.jsonl", { - id: "parent-del", + id: "0a000000-0000-4000-8000-000000000006", cwd, timestamp: "2026-01-02T00:00:00.000Z", parentSession: gpPath, }, [{ type: "message", id: "u1", parentId: null, timestamp: "2026-01-02T00:00:00.000Z", message: { role: "user", content: "parent" } }]); writeSessionFile(dir, "2026-01-03_child.jsonl", { - id: "child-del", + id: "0a000000-0000-4000-8000-000000000007", cwd, timestamp: "2026-01-03T00:00:00.000Z", parentSession: parentPath, }, [{ type: "message", id: "u1", parentId: null, timestamp: "2026-01-03T00:00:00.000Z", message: { role: "user", content: "child" } }]); writeSessionFile(dir, "2026-01-04_childid.jsonl", { - id: "child-id-del", + id: "0a000000-0000-4000-8000-000000000008", cwd, timestamp: "2026-01-04T00:00:00.000Z", - parentSession: "parent-del", + parentSession: "0a000000-0000-4000-8000-000000000006", }, [{ type: "message", id: "u1", parentId: null, timestamp: "2026-01-04T00:00:00.000Z", message: { role: "user", content: "child-id" } }]); // Warm the list so id/path resolution is exercised the way the UI does. await listAllSessions(); - const res = await sessionRoute.DELETE(new Request("http://localhost/api/sessions/parent-del"), { - params: Promise.resolve({ id: "parent-del" }), + const res = await sessionRoute.DELETE(new Request("http://localhost/api/sessions/0a000000-0000-4000-8000-000000000006"), { + params: Promise.resolve({ id: "0a000000-0000-4000-8000-000000000006" }), }); assert.equal(res.status, 200); const body = await res.json(); assert.equal(body.ok, true); assert.equal(existsSync(parentPath), false, "deleted session's file must be gone"); - assert.equal(await resolveSessionPath("parent-del"), null, "deleted session must no longer resolve (stale cache would make omp create a new session on --resume)"); + assert.equal(await resolveSessionPath("0a000000-0000-4000-8000-000000000006"), null, "deleted session must no longer resolve (stale cache would make omp create a new session on --resume)"); const after = new Map((await listAllSessions()).map((s) => [s.id, s])); - assert.equal(after.get("child-del")?.parentSessionId, "gp-id", "child linked by PATH form must re-attach to the grandparent path"); - assert.equal(after.get("child-id-del")?.parentSessionId, "gp-id", "child linked by ID form must re-attach to the grandparent id"); + assert.equal(after.get("0a000000-0000-4000-8000-000000000007")?.parentSessionId, "0a000000-0000-4000-8000-000000000005", "child linked by PATH form must re-attach to the grandparent path"); + assert.equal(after.get("0a000000-0000-4000-8000-000000000008")?.parentSessionId, "0a000000-0000-4000-8000-000000000005", "child linked by ID form must re-attach to the grandparent id"); }); }); @@ -333,7 +337,7 @@ test("POST /api/sessions/import rejects unauthorized workspaces and malformed fi test("sync serves paged file-only history and preserves the legacy context shape", async () => { await withAgentDir(async (dir) => { - const id = "sync-file-only"; + const id = "0a000000-0000-4000-8000-000000000009"; writeSessionFile(dir, "2026-01-01_sync.jsonl", { id, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ { type: "message", id: "one", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "one" } }, { type: "message", id: "two", parentId: "one", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: [{ type: "thinking", thinking: "private" }, { type: "text", text: "two" }] } }, @@ -364,8 +368,8 @@ test("sync serves paged file-only history and preserves the legacy context shape test("boundary returns only the latest compaction-aware active context IDs without a native wrapper", async () => { await withAgentDir(async (dir) => { - const id = "boundary-file-only"; - const filePath = writeSessionFile(dir, "boundary-file-only.jsonl", { id, cwd: dir }, [ + const id = "0a000000-0000-4000-8000-00000000000a"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-00000000000a.jsonl", { id, cwd: dir }, [ { type: "message", id: "old", parentId: null, message: { role: "user", content: "omitted" } }, { type: "message", id: "kept", parentId: "old", message: { role: "user", content: "retained" } }, { type: "compaction", id: "summary", parentId: "kept", summary: "condensed", firstKeptEntryId: "kept", tokensBefore: 50 }, @@ -402,8 +406,8 @@ test("boundary rejects invalid modes and incompatible options before resolving a test("boundary preserves malformed-header and oversized-file errors", async () => { await withAgentDir(async (dir) => { - const id = "boundary-errors"; - const filePath = writeSessionFile(dir, "boundary-errors.jsonl", { id, cwd: dir }); + const id = "0a000000-0000-4000-8000-00000000000b"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-00000000000b.jsonl", { id, cwd: dir }); cacheSessionPath(id, filePath); makeOversized(filePath); const validHeader = await getContext(id, "boundary=1"); @@ -420,14 +424,24 @@ test("boundary preserves malformed-header and oversized-file errors", async () = }); }); -test("sync samples current live output after the history read and excludes pinned historical views", async (t) => { +test("sync samples current live output after the history read and excludes pinned historical views", async () => { + const { sessionOps } = await jiti.import("./hosts/session-ops.ts"); + let emit; + let emittedDuringRead = false; + // The history read is this machine's daemon op: output arriving while it runs must reach the response. + const readContextOp = async ({ id, leafId, options }) => { + if (!emittedDuringRead) { + emittedDuringRead = true; + queueMicrotask(() => emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "during read" }] } })); + } + return sessionOps.readContext(id, leafId, options); + }; await withAgentDir(async (dir) => { - const id = "sync-live"; - const filePath = writeSessionFile(dir, "2026-01-01_live.jsonl", { id, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ + const id = "0a000000-0000-4000-8000-00000000000c"; + writeSessionFile(dir, "2026-01-01_live.jsonl", { id, cwd: dir, timestamp: "2026-01-01T00:00:00.000Z" }, [ { type: "message", id: "old", parentId: null, timestamp: "2026-01-01T00:00:00.000Z", message: { role: "user", content: "history-read" } }, { type: "message", id: "tip", parentId: "old", timestamp: "2026-01-01T00:00:01.000Z", message: { role: "assistant", content: [] } }, ]); - let emit; const wrapper = new AgentSessionWrapper({ isAlive: true, onFrame(listener) { emit = listener; return () => {}; }, @@ -440,29 +454,8 @@ test("sync samples current live output after the history read and excludes pinne globalThis.__ompSessions.set(id, wrapper); emit({ type: "agent_start" }); emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "before read" }] } }); - // Prime only identity resolution, not the entry cache: the observed read - // must belong to this context request rather than a directory-list scan. - cacheSessionPath(id, filePath); - let emittedDuringRead = false; - const originalRead = fs.readSync; - const readMock = t.mock.method(fs, "readSync", (...args) => { - const count = originalRead(...args); - if (!emittedDuringRead && Buffer.isBuffer(args[1]) && args[1].toString("utf8", 0, count).includes("history-read")) { - emittedDuringRead = true; - queueMicrotask(() => emit({ type: "message_update", message: { role: "assistant", content: [{ type: "text", text: "during read" }] } })); - } - return count; - }); - syncBuiltinESMExports(); - t.after(() => { readMock.mock.restore(); syncBuiltinESMExports(); }); - const isolated = createJiti(import.meta.url, { - moduleCache: false, - tryNative: false, - alias: { "@/": fileURLToPath(new URL("../", import.meta.url)) }, - }); try { - const observedRoute = await isolated.import("../app/api/sessions/[id]/context/route.ts"); - const readContext = (query) => observedRoute.GET( + const readContext = (query) => contextRoute.GET( new Request(`http://localhost/api/sessions/${id}/context?${query}`), { params: Promise.resolve({ id }) }, ); @@ -482,7 +475,7 @@ test("sync samples current live output after the history read and excludes pinne await wrapper.destroyAndWait(); globalThis.__ompSessions.delete(id); } - }); + }, { readContext: readContextOp }); }); test("sync rejects malformed cursor, page bounds and mode before reading a session", async () => { @@ -506,17 +499,18 @@ test("sync rejects malformed cursor, page bounds and mode before reading a sessi test("sync preserves the too-large and malformed-file error contracts", async () => { await withAgentDir(async (dir) => { const filePath = writeSessionFile(dir, "2026-01-01_big-sync.jsonl", { - id: "big-sync", cwd: dir, timestamp: "2026-01-01T00:00:00.000Z", + id: "0a000000-0000-4000-8000-00000000000d", cwd: dir, timestamp: "2026-01-01T00:00:00.000Z", + }); + // Listed by the daemon while its header is valid; it turns malformed below. + const malformedPath = writeSessionFile(dir, "2026-01-01_malformed-sync.jsonl", { + id: "0a000000-0000-4000-8000-00000000000e", cwd: dir, timestamp: "2026-01-01T00:00:00.000Z", }); makeOversized(filePath); - const large = await getContext("big-sync", "sync=1"); + const large = await getContext("0a000000-0000-4000-8000-00000000000d", "sync=1"); assert.equal(large.status, 413); assert.equal((await large.json()).code, "session_file_too_large"); - const { cacheSessionPath } = await jiti.import("./session-reader.ts"); - const malformedPath = join(dir, "2026-01-01_malformed-sync.jsonl"); writeFileSync(malformedPath, "not a session\n"); - cacheSessionPath("malformed-sync", malformedPath); - const malformed = await getContext("malformed-sync", "sync=1"); + const malformed = await getContext("0a000000-0000-4000-8000-00000000000e", "sync=1"); assert.equal(malformed.status, 404); assert.equal((await malformed.json()).code, "session_file_malformed"); }); @@ -524,7 +518,7 @@ test("sync preserves the too-large and malformed-file error contracts", async () test("sync recovers the first live reply before persistence without erasing an established cursor", async () => { await withAgentDir(async (dir) => { - const id = "not-yet-persisted"; + const id = "0a000000-0000-4000-8000-00000000000f"; const filePath = join(dir, "2026-01-01_not-yet-persisted.jsonl"); let emit; let stateLoaded = false; @@ -575,14 +569,10 @@ test("sync recovers the first live reply before persistence without erasing an e assert.deepEqual(await emptyBoundary.json(), { entryIds: [] }, "an unpersisted live session has an empty boundary"); writeFileSync(filePath, "malformed existing file\n"); assert.equal((await getContext(id, "boundary=1")).status, 404, "an existing unresolvable file is not an empty boundary"); - const { cacheSessionPath } = await jiti.import("./session-reader.ts"); - cacheSessionPath(id, filePath); - const malformedBoundary = await getContext(id, "boundary=1"); - assert.equal(malformedBoundary.status, 404); - assert.equal((await malformedBoundary.json()).code, "session_file_malformed"); + // No host lists the bad file, so it resolves like any unknown id: never as not-yet-persisted. const malformed = await getContext(id, "sync=1"); assert.equal(malformed.status, 404); - assert.equal((await malformed.json()).code, "session_file_malformed", "an existing bad file cannot masquerade as not-yet-persisted"); + assert.equal("context" in await malformed.json(), false, "an existing bad file cannot masquerade as not-yet-persisted"); globalThis.__ompSessions.delete(id); assert.equal((await getContext("file-only-missing", "sync=1")).status, 404); assert.equal((await getContext("file-only-missing", "boundary=1")).status, 404, "without a live wrapper a missing file stays 404"); @@ -595,8 +585,8 @@ test("sync recovers the first live reply before persistence without erasing an e test("sidebar rename cannot fall back to disk while Edit owns the session", async () => { await withAgentDir(async (dir) => { - const id = "rename-during-edit"; - const filePath = writeSessionFile(dir, "rename-during-edit.jsonl", { id, cwd: dir }, [ + const id = "0a000000-0000-4000-8000-000000000010"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000010.jsonl", { id, cwd: dir }, [ { type: "message", id: "u1", parentId: null, message: { role: "user", content: "question" } }, { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, ]); @@ -669,8 +659,8 @@ test("sidebar rename cannot fall back to disk while Edit owns the session", asyn test("automatic title fallback cannot write after Edit takes over", async () => { await withAgentDir(async (dir) => { - const id = "auto-name-during-edit"; - const filePath = writeSessionFile(dir, "auto-name-during-edit.jsonl", { id, cwd: dir }, [ + const id = "0a000000-0000-4000-8000-000000000011"; + const filePath = writeSessionFile(dir, "0a000000-0000-4000-8000-000000000011.jsonl", { id, cwd: dir }, [ { type: "message", id: "u1", parentId: null, message: { role: "user", content: "Preserve this conversation" } }, { type: "message", id: "a1", parentId: "u1", message: { role: "assistant", content: [] } }, ]); diff --git a/lib/session-watcher.ts b/lib/session-watcher.ts index b36a66db7..d3cf1b4cf 100644 --- a/lib/session-watcher.ts +++ b/lib/session-watcher.ts @@ -8,6 +8,7 @@ import { listAllSessions, resolveSessionIdByPath, } from "./session-reader"; +import { invalidateLocalSessionLists } from "./hosts/session-index"; // omp owns the writes to a session's JSONL. ompweb streams RPC events only for // the sessions it spawned itself, so a session started outside the web UI — by @@ -40,6 +41,7 @@ function flush(): void { // filename was null — fs.watch coalesced the event or overflowed. We // don't know which file changed, so fall back to the full invalidation. invalidateSessionListCache(); + invalidateLocalSessionLists(); void rescanAndNotify(); return; } @@ -48,7 +50,11 @@ function flush(): void { // list's mtimes and message counts are stale) and invalidate ONLY the // changed sessions' parse caches, leaving unrelated sessions cached. invalidateSessionListMeta(); - for (const path of paths) invalidateSessionEntriesCache(path); + // The sidebar lists this machine's sessions through its daemon: its caches go stale the same way. + for (const path of paths) { + invalidateSessionEntriesCache(path); + invalidateLocalSessionLists(path); + } void Promise.all(paths.map((path) => resolveSessionIdByPath(path).catch(() => undefined))) .then((ids) => { From c277f2a5a926a65b2715fc0076526a06268b0d38 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 22:56:33 +0000 Subject: [PATCH 16/36] fix(hosts): an unlisted id is offline until this machine's daemon has listed, and a live session resolves to its own host --- app/api/sessions/[id]/context/route.ts | 23 +++---- hooks/useAgentSession.rpc.test.mjs | 19 ++++-- lib/api-utils.ts | 17 +++-- lib/hosts/link-driver.test-helper.mjs | 13 +++- lib/hosts/no-direct-local.test.mjs | 65 +++++++++++++----- lib/hosts/session-index.test.mjs | 32 ++++++++- lib/hosts/session-index.ts | 15 ++++- lib/omp/rpc-process-runtime.test.mjs | 16 ++++- lib/session-routes.test.mjs | 91 ++++++++++++++++++++++++-- 9 files changed, 240 insertions(+), 51 deletions(-) diff --git a/app/api/sessions/[id]/context/route.ts b/app/api/sessions/[id]/context/route.ts index e3f4fe372..533b0e98a 100644 --- a/app/api/sessions/[id]/context/route.ts +++ b/app/api/sessions/[id]/context/route.ts @@ -47,12 +47,21 @@ export async function GET( try { const resolved = await resolveSessionHostOr404(id); - if ("response" in resolved) { + // A live session resolves to its host even before its file exists; the host then answers 404. + const result = "response" in resolved ? resolved : await resolved.host.sessionOps.readContext(id, leafId, { + deferThinking, + deferMedia: deferToolResultImages, + includePreCompaction, + boundary: boundary === "1", + sync: sync === "1" ? { cursor, limit } : null, + }); + if ("response" in result || !result.ok) { // OMP may not create the file until the first assistant message is // committed. A live wrapper can still recover that first partial reply, // and its persisted boundary is empty (the next prompt must not 404). // Never replace previously confirmed history when its file is missing. - const session = boundary === "1" || (sync === "1" && !cursor?.lastEntryId && leafId === undefined) ? getRpcSession(id) : undefined; + const notFound = "response" in result ? result.response.status === 404 : result.status === 404; + const session = notFound && (boundary === "1" || (sync === "1" && !cursor?.lastEntryId && leafId === undefined)) ? getRpcSession(id) : undefined; if (session?.isAlive() && !(await session.host.sessionFileExists(session.sessionFile))) { if (boundary === "1") { return NextResponse.json({ entryIds: [] }, { headers: { "Cache-Control": "no-store" } }); @@ -65,16 +74,8 @@ export async function GET( }; return NextResponse.json(response, { headers: { "Cache-Control": "no-store" } }); } - return resolved.response; + return "response" in result ? result.response : opErrorResponse(result); } - const result = await resolved.host.sessionOps.readContext(id, leafId, { - deferThinking, - deferMedia: deferToolResultImages, - includePreCompaction, - boundary: boundary === "1", - sync: sync === "1" ? { cursor, limit } : null, - }); - if (!result.ok) return opErrorResponse(result); if (boundary === "1") { return NextResponse.json(result.value, { headers: { "Cache-Control": "no-store" } }); } diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 33e22c9e8..e64d586be 100644 --- a/hooks/useAgentSession.rpc.test.mjs +++ b/hooks/useAgentSession.rpc.test.mjs @@ -2,6 +2,7 @@ import "../tests/setup-dom.mjs"; import assert from "node:assert/strict"; import test, { afterEach, beforeEach } from "node:test"; import React from "react"; +import { existsSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; import { act, cleanup, fireEvent, render, renderHook, within } from "@testing-library/react/pure.js"; @@ -283,8 +284,18 @@ const { useAgentSession } = await jiti.import("../hooks/useAgentSession.ts"); const { selectSessionHistory } = await jiti.import("@/lib/session-sync"); const { publishSessionsChanged } = await jiti.import("@/lib/session-change-bus"); const { AgentSessionWrapper } = await jiti.import("@/lib/rpc-manager"); -// Wrappers built directly need an online host; the daemon's machine host is one. -const { localHost } = await jiti.import("@/lib/hosts/local-host"); +// Wrappers built directly need an online host: this machine's, as its daemon answers, minus spawning. +const onlineHost = { + id: "local", + label: "This machine", + sessionOps: {}, + status: () => "online", + onStatus: () => () => {}, + spawnRpc: async () => { throw new Error("this test never spawns"); }, + sessionFileExists: async (path) => existsSync(path), + invalidateSessionLists() {}, + autoApproveExtension: () => false, +}; const { isUnknownSlashCommand, slashCommandName, runHostTool } = await jiti.import("@/hooks/useAgentSession-stream"); const { toastCalls } = await jiti.import("@/components/ui/toast"); const { MessageView } = await jiti.import("@/components/MessageView"); @@ -2125,7 +2136,7 @@ function attachNativeWrapper(t, sid) { }, sendFrame() {}, async dispose() {}, - }, process.cwd(), null, false, "", undefined, localHost); + }, process.cwd(), null, false, "", undefined, onlineHost); wrapper.start(); world.wrappers.set(sid, wrapper); t.after(() => wrapper.destroyAndWait()); @@ -2744,7 +2755,7 @@ async function attachEditableWrapper(t, native, { holdHistory = false } = {}) { }, sendFrame() {}, async dispose() { listeners.clear(); }, - }, process.cwd(), null, false, "", undefined, localHost); + }, process.cwd(), null, false, "", undefined, onlineHost); t.after(() => wrapper.destroyAndWait()); native.onMove = () => emitNative({ type: "notice", source: "session-persistence", level: "warning", message: "Session moved to a sibling file because another process owns the original" }); wrapper.onIdentityChange((oldId, newId, options) => { diff --git a/lib/api-utils.ts b/lib/api-utils.ts index cd86ecf7d..c3f77531e 100644 --- a/lib/api-utils.ts +++ b/lib/api-utils.ts @@ -5,16 +5,25 @@ import { HostOpError } from "./hosts/link-protocol"; import type { OpResult } from "./hosts/session-ops"; import { hostForSessionId } from "./hosts/session-index"; import { LOCAL_HOST_ID } from "./hosts/registry"; -import { WebRpcError } from "./rpc-manager"; +import { getRpcSession, WebRpcError } from "./rpc-manager"; const SESSION_NOT_FOUND = { error: "Session not found", code: "session_not_found" } as const; -/** Resolve a session id to the host holding its file, or a 404 JSON response. */ +/** Resolve a session id to the host holding its file: a live session's own host first, then the + * hosts' lists. A 404 JSON response when no host has it, 503 while this machine's sessions are unknown. */ export async function resolveSessionHostOr404( id: string, ): Promise<{ host: Host } | { response: NextResponse }> { - const host = await hostForSessionId(id); - return host ? { host } : { response: NextResponse.json(SESSION_NOT_FOUND, { status: 404 }) }; + const live = getRpcSession(id); + if (live?.isAlive()) return { host: live.host }; + try { + const host = await hostForSessionId(id); + return host ? { host } : { response: NextResponse.json(SESSION_NOT_FOUND, { status: 404 }) }; + } catch (error) { + // Nothing was sent: a command the composer holds is refused, not lost. + if (error instanceof HostOpError && error.code === "host_offline") return { response: apiErrorResponse(new WebRpcError(error.message, "host_offline", "refused")) }; + throw error; + } } /** 503 `{hostOffline: true, delivery: "refused"}` while a host's link is down; null when it takes requests. */ diff --git a/lib/hosts/link-driver.test-helper.mjs b/lib/hosts/link-driver.test-helper.mjs index d7b128c0f..f675384f4 100644 --- a/lib/hosts/link-driver.test-helper.mjs +++ b/lib/hosts/link-driver.test-helper.mjs @@ -6,7 +6,8 @@ import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); const hub = await jiti.import("./hub.ts"); -const { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION, SESSION_OP_PARAMS } = await jiti.import("./link-protocol.ts"); +const { HostOpError, LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION, SESSION_OP_PARAMS } = await jiti.import("./link-protocol.ts"); +const { ProjectPathError } = await jiti.import("../project-registry.ts"); const { createHost, rotateLocalHostToken } = await jiti.import("./registry.ts"); const URL_BASE = "http://main.test/api/hosts/link"; @@ -41,6 +42,14 @@ export async function linkLocalDaemon(ops = {}, onMessage = undefined) { return link; } +/** The `res` error `ompweb host` sends for an op that threw (daemon.ts `answer`). */ +function opFailure(error) { + if (error instanceof HostOpError) return { status: error.status, code: error.code, message: error.message }; + // A rejected project path is a bad request. + if (error instanceof ProjectPathError) return { status: 400, code: error.code, message: error.message }; + return { status: 500, code: "host_op_failed", message: error instanceof Error ? error.message : String(error) }; +} + /** Poll `predicate` until it holds; fails after 5 s instead of hanging the test. */ export async function until(predicate, what) { const deadline = Date.now() + 5_000; @@ -150,7 +159,7 @@ export class LinkDriver { try { value = await ops[message.op](message.args); } catch (error) { - await this.post({ type: "res", id: message.id, ok: false, error: { status: error.status ?? 500, code: error.code ?? "host_op_failed", message: error.message } }); + await this.post({ type: "res", id: message.id, ok: false, error: opFailure(error) }); continue; } await this.answer(message, value); diff --git a/lib/hosts/no-direct-local.test.mjs b/lib/hosts/no-direct-local.test.mjs index f912b0d0c..80a653877 100644 --- a/lib/hosts/no-direct-local.test.mjs +++ b/lib/hosts/no-direct-local.test.mjs @@ -8,37 +8,68 @@ import { fileURLToPath } from "node:url"; const ROOT = fileURLToPath(new URL("../../", import.meta.url)); -const ALLOWED = new Set([ +/** Files that may reach this machine's direct spawn and file path: the daemon's side, and tests that exercise it. */ +const DIRECT_LOCAL_ALLOWED = new Set([ "lib/hosts/daemon.ts", "lib/hosts/local-host.ts", - // The RPC layer's default transport, used by main's utility omp (models, login), never a session. + // Define the spawn transports. "lib/omp/rpc-process.ts", + "lib/omp/rpc-transport.ts", + // Runs a daemon's session ops in this process. + "lib/hosts/link-driver.test-helper.mjs", + // local-host's spawn arguments and spawn path. + "lib/rpc-manager.test.mjs", + "lib/hosts/no-direct-local.test.mjs", ]); -const IMPORT_RE = /\b(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']|\bimport\s*\(\s*["']([^"']+)["']\s*\)/g; +/** `new RpcProcess` without a transport spawns omp here: main's utility omp (models, login), never a session, and RpcProcess's own tests. */ +const BARE_RPC_PROCESS_ALLOWED = new Set([ + "lib/omp/rpc-utility.ts", + "app/api/auth/login/[provider]/route.ts", + "lib/omp/rpc-process-runtime.test.mjs", + "lib/omp/session-edit.native.test.mjs", +]); + +const DIRECT_LOCAL_RE = /["'`][^"'`\n]*\blocal-host(?:\.ts)?["'`]|\b(?:spawnLocalRpcTransport|spawnOmpTransport)\b/; function sourceFiles(dir) { return readdirSync(join(ROOT, dir), { withFileTypes: true }).flatMap((entry) => { const path = `${dir}/${entry.name}`; if (entry.isDirectory()) return sourceFiles(path); - return /\.(?:[cm]?[jt]sx?)$/.test(entry.name) && !/\.test(?:-helper)?\.[cm]?[jt]s$/.test(entry.name) ? [path] : []; + return /\.(?:[cm]?[jt]sx?)$/.test(entry.name) ? [path] : []; }); } -/** Files under app/ and lib/ that import the local-host module or spawnLocalRpcTransport. */ -function directLocalImports() { - return ["app", "lib"].flatMap(sourceFiles).filter((path) => { - if (ALLOWED.has(path)) return false; - const source = readFileSync(join(ROOT, path), "utf8"); - for (const match of source.matchAll(IMPORT_RE)) { - const specifier = match[1] ?? match[2]; - if (/(?:^|\/)local-host(?:\.ts)?$/.test(specifier)) return true; - if (match[1] && /\bspawnLocalRpcTransport\b/.test(match[0])) return true; +const FILES = ["app", "bin", "components", "hooks", "lib"].flatMap(sourceFiles).map((path) => { + // Comments may name these freely. A comment opens after whitespace; `"**/*"`, `"//?/"` and `https://` are code. + const code = readFileSync(join(ROOT, path), "utf8").replace(/(^|\s)\/\*[\s\S]*?\*\//g, "$1").replace(/(^|\s)\/\/.*$/gm, "$1"); + return { path, code }; +}); + +/** True when some `new RpcProcess({...})` call passes no `transport` property. */ +function spawnsBareRpcProcess(code) { + for (const match of code.matchAll(/\bnew RpcProcess\(/g)) { + let end = match.index + match[0].length; + for (let depth = 1; end < code.length && depth > 0; end++) { + if (code[end] === "(") depth++; + else if (code[end] === ")") depth--; } - return false; - }); + // `transport: x` or shorthand `transport,` / `transport }`; `transport.spawn` is not one. + if (!/[{,]\s*transport\s*[:,}]/.test(code.slice(match.index, end))) return true; + } + return false; } -test("only the daemon imports local-host or spawnLocalRpcTransport", () => { - assert.deepEqual(directLocalImports(), []); +/** Flagged files outside `allowed`, and allowed files that no longer need the exemption. */ +function check(allowed, flags) { + const flagged = FILES.filter(({ code }) => flags(code)).map(({ path }) => path); + return { outside: flagged.filter((path) => !allowed.has(path)), stale: [...allowed].filter((path) => !flagged.includes(path)) }; +} + +test("only the daemon's side reaches local-host, spawnLocalRpcTransport or spawnOmpTransport", () => { + assert.deepEqual(check(DIRECT_LOCAL_ALLOWED, (code) => DIRECT_LOCAL_RE.test(code)), { outside: [], stale: [] }); +}); + +test("only main's utility omp builds an RpcProcess without a transport", () => { + assert.deepEqual(check(BARE_RPC_PROCESS_ALLOWED, spawnsBareRpcProcess), { outside: [], stale: [] }); }); diff --git a/lib/hosts/session-index.test.mjs b/lib/hosts/session-index.test.mjs index f5375a2e3..91edd04dc 100644 --- a/lib/hosts/session-index.test.mjs +++ b/lib/hosts/session-index.test.mjs @@ -76,7 +76,8 @@ test("an id on this machine and a remote host is listed once, as local", async ( test("this machine's sessions come from its daemon only, never from the files on disk", async (t) => { const link = setup(t, { localSessionId: SHARED }); assert.deepEqual(await index.listSessionsAllHosts(), [], "no daemon linked: nothing is read here"); - assert.equal(await index.hostForSessionId(SHARED), null); + // Unknown is not gone: a 404 would make the client drop the session. + await assert.rejects(index.hostForSessionId(SHARED), (error) => error.status === 503 && error.code === "host_offline" && error.message === "This machine is offline"); await link(null, { listSessions: () => [entry(SHARED, { cwd: "/srv/app" })] }); index.invalidateHostSessionList("local"); @@ -86,6 +87,35 @@ test("this machine's sessions come from its daemon only, never from the files on assert.deepEqual(await index.sessionSpawnTarget(SHARED, host), { sessionFile: `/remote/sessions/${SHARED}.jsonl`, cwd: "/srv/app", recordedCwd: "/srv/app" }); }); +test("an id no host lists is gone only once this machine's daemon has answered a list", async (t) => { + const link = setup(t); + let failing = true; + await link(null, { + listSessions: () => { + if (failing) throw new Error("sessions dir unreadable"); + return [entry(OTHER)]; + }, + }); + await assert.rejects(index.hostForSessionId(SHARED), (error) => error.status === 503, "linked, but its list never arrived"); + failing = false; + assert.equal(await index.hostForSessionId(SHARED), null); + assert.equal(await index.hostForSessionId("not-a-session-id"), null, "a malformed id is never anyone's"); +}); + +test("the hand-driven daemon answers a failed op as ompweb host does", async (t) => { + const link = setup(t); + const { ProjectPathError } = await jiti.import("../project-registry.ts"); + const { HostOpError } = await jiti.import("./link-protocol.ts"); + const thrown = { bad: new ProjectPathError("invalid_path", "Not a directory"), gone: new HostOpError(410, "gone", "Gone"), broken: new Error("disk on fire") }; + const remote = await link("Strict", { validateCwd: ({ path }) => { throw thrown[path]; } }); + const { sessionOps } = hub.getHost(remote.id); + const failure = async (path) => sessionOps.validateCwd(path).then(() => assert.fail("resolved"), ({ status, code, message }) => ({ status, code, message })); + // Main prefixes the host's label. + assert.deepEqual(await failure("bad"), { status: 400, code: "invalid_path", message: "Strict: Not a directory" }); + assert.deepEqual(await failure("gone"), { status: 410, code: "gone", message: "Strict: Gone" }); + assert.deepEqual(await failure("broken"), { status: 500, code: "host_op_failed", message: "Strict: disk on fire" }); +}); + test("a change on this machine's disk drops its list on the daemon and here", async (t) => { const link = setup(t); let listed = [entry(SHARED)]; diff --git a/lib/hosts/session-index.ts b/lib/hosts/session-index.ts index f75aff274..33c1fe164 100644 --- a/lib/hosts/session-index.ts +++ b/lib/hosts/session-index.ts @@ -6,6 +6,7 @@ import { mergeProjects, type ProjectRegistryEntry } from "../project-registry"; import { isValidSessionId } from "../session-file-references-core"; import type { ManagedProject, SessionInfo } from "../types"; import { isLinkUp, type Host } from "./host"; +import { HostOpError } from "./link-protocol"; import { getHost, listHosts, onHostHello } from "./hub"; import { LOCAL_HOST_ID } from "./registry"; @@ -20,6 +21,8 @@ interface HostLists { loading: { generation: number; promise: Promise } | null; /** Last registry the host returned, shown while it is unreachable. */ projects: ProjectRegistryEntry[]; + /** The host answered a list at least once; until then a missing id may still be there. */ + loaded: boolean; } declare global { @@ -35,7 +38,7 @@ function hostLists(hostId: string): HostLists { } let lists = globalThis.__ompHostLists.get(hostId); if (!lists) { - lists = { sessions: [], fetchedAt: 0, generation: 0, loading: null, projects: [] }; + lists = { sessions: [], fetchedAt: 0, generation: 0, loading: null, projects: [], loaded: false }; globalThis.__ompHostLists.set(hostId, lists); } return lists; @@ -57,6 +60,7 @@ export async function hostSessions(hostId: string, refresh = false): Promise = host.sessionOps.listSessions().then((sessions) => { const tagged = sessions.map((session) => ({ ...session, hostId })); + lists.loaded = true; if (lists.generation === generation) { lists.sessions = tagged; lists.fetchedAt = Date.now(); @@ -93,12 +97,17 @@ async function hostWithSession(id: string, refresh: boolean): Promise { // Host lists only hold valid ids: a malformed one never costs a round trip. if (!isValidSessionId(id)) return null; // shortcut: every miss re-asks each linked host; throttle per host if polling for gone sessions shows up. - return (await hostWithSession(id, false)) ?? (await hostWithSession(id, true)); + const host = (await hostWithSession(id, false)) ?? (await hostWithSession(id, true)); + if (host) return host; + const local = getHost(LOCAL_HOST_ID); + if (!isLinkUp(local.status()) || !hostLists(LOCAL_HOST_ID).loaded) throw new HostOpError(503, "host_offline", `${local.label} is offline`); + return null; } /** Where a session's file is and which cwd to start it in, on `host`; null when the host has no such session. */ diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 5e658185f..b9e6c79dc 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -7,8 +7,18 @@ import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); const { RpcProcess, RpcCommandTimeoutError } = jiti("./rpc-process.ts"); const { AgentSessionWrapper } = jiti("../rpc-manager.ts"); -// Wrappers built directly need an online host; the daemon's machine host is one. -const { localHost } = jiti("../hosts/local-host.ts"); +// Wrappers built directly need an online host; this one never spawns or reads files. +const onlineHost = { + id: "local", + label: "This machine", + sessionOps: {}, + status: () => "online", + onStatus: () => () => {}, + spawnRpc: async () => { throw new Error("this test never spawns"); }, + sessionFileExists: async () => false, + invalidateSessionLists() {}, + autoApproveExtension: () => false, +}; /** Outbound v2 chunk records exactly as OMP emits them. */ function chunkRecords(frame, chunkId, payloadBytes = 256 * 1024) { @@ -179,7 +189,7 @@ for (const type of ["remove_queued_message", "promote_queued_message"]) { const proc = startProcess(transport); await proc.waitReady(); t.mock.timers.enable({ apis: ["setTimeout"] }); - const wrapper = new AgentSessionWrapper(proc, process.cwd(), null, false, "", undefined, localHost); + const wrapper = new AgentSessionWrapper(proc, process.cwd(), null, false, "", undefined, onlineHost); wrapper.start(); try { diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 90a97732c..a35871d2a 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, truncateSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { gzipSync } from "node:zlib"; import test from "node:test"; import { createJiti } from "jiti"; import { fileURLToPath } from "node:url"; @@ -15,12 +16,15 @@ const jiti = createJiti(import.meta.url, { const sessionRoute = await jiti.import("../app/api/sessions/[id]/route.ts"); const contextRoute = await jiti.import("../app/api/sessions/[id]/context/route.ts"); const importRoute = await jiti.import("../app/api/sessions/import/route.ts"); +const archiveRoute = await jiti.import("../app/api/sessions/archive/route.ts"); +const exportRoute = await jiti.import("../app/api/sessions/[id]/export/route.ts"); const stateRoute = await jiti.import("../app/api/sessions/[id]/state/route.ts"); const autoNameRoute = await jiti.import("../app/api/sessions/[id]/auto-name/route.ts"); const { cacheSessionPath, invalidateSessionListCache, listAllSessions, resolveSessionPath } = await jiti.import("./session-reader.ts"); const { allowFileRoot, normalizeSlashes } = await jiti.import("./file-access.ts"); const { AgentSessionWrapper, WebRpcError } = await jiti.import("./rpc-manager.ts"); -const { closeHostLink } = await jiti.import("./hosts/hub.ts"); +const { closeHostLink, getHost } = await jiti.import("./hosts/hub.ts"); +const { listSessionsAllHosts } = await jiti.import("./hosts/session-index.ts"); const getContext = (id, query = "") => contextRoute.GET( new Request(`http://localhost/api/sessions/${id}/context${query ? `?${query}` : ""}`), @@ -36,7 +40,7 @@ const getState = (id) => stateRoute.GET( const MAX_SESSION_LOAD_BYTES = 1024 * 1024 * 1024; /** Point the omp agent dir at a throwaway location for the duration of `run`; - * this machine's daemon serves it from this process. */ + * this machine's daemon serves it from this process (`daemonOps` null: no daemon links). */ async function withAgentDir(run, daemonOps = {}) { const agentDir = mkdtempSync(join(tmpdir(), "omp-web-session-routes-")); const projectDir = join(agentDir, "sessions", "-project"); @@ -48,7 +52,7 @@ async function withAgentDir(run, daemonOps = {}) { // resolution sees only THIS dir's files. invalidateSessionListCache(); globalThis.__ompHostLists = undefined; - await linkLocalDaemon(daemonOps); + if (daemonOps) await linkLocalDaemon(daemonOps); try { await run(projectDir); } finally { @@ -249,6 +253,8 @@ test("POST /api/sessions/import writes a fresh-id copy and makes it visible imme const workspace = mkdtempSync(join(tmpdir(), "omp-web-import-ws-")); try { allowFileRoot(workspace); + // The sidebar's list of this machine's sessions, warm before the import. + assert.deepEqual(await listSessionsAllHosts(), []); const content = [ JSON.stringify({ type: "session", version: 3, id: "src-id", cwd: workspace, timestamp: "2026-01-01T00:00:00.000Z" }), JSON.stringify({ type: "message", id: "u1", parentId: null, timestamp: "2026-01-01T00:00:01.000Z", message: { role: "user", content: "imported hello" } }), @@ -267,9 +273,9 @@ test("POST /api/sessions/import writes a fresh-id copy and makes it visible imme // Fresh id: an imported copy must never keep the source id, or opening // / deleting the import would hit the ORIGINAL session file. - const sessions = await listAllSessions(); - const imported = sessions.find((s) => s.firstMessage === "imported hello"); - assert.ok(imported, "imported session must appear in the list right away (list invalidation)"); + const imported = (await listSessionsAllHosts()).find((s) => s.firstMessage === "imported hello"); + assert.ok(imported, "imported session must appear in the sidebar's list right away (list invalidation)"); + assert.equal(imported.hostId, "local"); assert.notEqual(imported.id, "src-id", "imported copy must get a fresh session id"); // The imported bashExecution must not carry fullOutputPath: it could @@ -287,6 +293,78 @@ test("POST /api/sessions/import writes a fresh-id copy and makes it visible imme }); }); +test("POST /api/sessions/archive restores a session into the sidebar's list right away", async () => { + await withAgentDir(async (dir) => { + const id = "0a000000-0000-4000-8000-000000000020"; + // getArchivedSessionsDir(): /archive/sessions, beside /sessions. + const archived = join(dir, "..", "..", "archive", "sessions", "-project"); + mkdirSync(archived, { recursive: true }); + const lines = [ + { type: "session", version: 3, id, cwd: dir, timestamp: "2026-01-02T00:00:00.000Z" }, + { type: "message", id: "u1", parentId: null, timestamp: "2026-01-02T00:00:01.000Z", message: { role: "user", content: "restored hello" } }, + ]; + writeFileSync(join(archived, "2026-01-02_restored.jsonl.gz"), gzipSync(Buffer.from(`${lines.map((line) => JSON.stringify(line)).join("\n")}\n`))); + assert.deepEqual(await listSessionsAllHosts(), [], "the sidebar's list, warm before the restore"); + + const res = await archiveRoute.POST(new Request("http://localhost/api/sessions/archive", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ key: "-project/2026-01-02_restored.jsonl.gz" }), + })); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { ok: true, sessionId: id }); + assert.deepEqual((await listSessionsAllHosts()).map((s) => [s.id, s.hostId]), [[id, "local"]]); + }); +}); + +test("before this machine's daemon has listed its sessions, an unknown id answers offline, not gone", async () => { + const id = "0a000000-0000-4000-8000-000000000021"; + const get = () => sessionRoute.GET(new Request(`http://localhost/api/sessions/${id}`), { params: Promise.resolve({ id }) }); + // The client keeps the transcript on 503 hostOffline; a 404 would drop it. + const offlineBody = { error: "This machine is offline", code: "host_offline", hostOffline: true, delivery: "refused" }; + await withAgentDir(async () => { + const offline = await get(); + assert.equal(offline.status, 503); + assert.deepEqual(await offline.json(), offlineBody); + }, null); + await withAgentDir(async () => { + const unlisted = await get(); + assert.equal(unlisted.status, 503, "linked, but its list never arrived"); + assert.deepEqual(await unlisted.json(), offlineBody); + }, { listSessions: () => { throw new Error("sessions dir unreadable"); } }); + await withAgentDir(async () => { + const gone = await get(); + assert.equal(gone.status, 404); + assert.equal((await gone.json()).code, "session_not_found"); + }); +}); + +test("a live session resolves to its own host before any list has it", async (t) => { + const id = "0a000000-0000-4000-8000-000000000022"; + const exported = []; + const host = { + id: "local", + label: "This machine", + status: () => "online", + sessionOps: { + async exportSession(sessionId) { + exported.push(sessionId); + return { ok: true, value: { html: "

live

", fileName: "live.html" } }; + }, + }, + }; + const previousSessions = globalThis.__ompSessions; + globalThis.__ompSessions = new Map([[id, { isAlive: () => true, host }]]); + t.after(() => { globalThis.__ompSessions = previousSessions; }); + // No daemon has listed anything: without the live session this answers 503. + await withAgentDir(async () => { + const response = await exportRoute.GET(new Request(`http://localhost/api/sessions/${id}/export`), { params: Promise.resolve({ id }) }); + assert.equal(response.status, 200); + assert.equal(await response.text(), "

live

"); + assert.deepEqual(exported, [id]); + }, null); +}); + test("POST /api/sessions/import rejects unauthorized workspaces and malformed files", async () => { await withAgentDir(async () => { const unauthorized = mkdtempSync(join(tmpdir(), "omp-web-import-denied-")); @@ -670,6 +748,7 @@ test("automatic title fallback cannot write after Edit takes over", async () => let nativeRenames = 0; const rpc = { isAlive: () => true, + host: getHost("local"), isEditingHistory: () => editing, async generateTitle() { // The generation finished without a title; another request acquired Edit. From 4dccbc1c6919c51d5bc2e6bd7bff669bf609a3e1 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 23:03:38 +0000 Subject: [PATCH 17/36] feat(hosts): rename This machine --- AGENTS.md | 2 +- app/api/hosts/route.ts | 8 ++-- components/HostsConfig.test.mjs | 43 +++++++++++++++++++- components/HostsConfig.tsx | 36 +++++++++------- components/host-status.ts | 4 +- docs/specs/2026-10-29-local-daemon-design.md | 5 ++- lib/agent-tools.test.mjs | 12 ++++++ lib/agent-tools.ts | 3 +- lib/hosts/hosts-route.test.mjs | 17 ++++++-- lib/hosts/hub.ts | 8 ++-- lib/hosts/local-bootstrap.test.mjs | 4 +- lib/hosts/registry.test.mjs | 24 ++++++++++- lib/hosts/registry.ts | 17 ++++++-- lib/i18n/locales/en.json | 2 + lib/i18n/locales/ja.json | 2 + lib/i18n/locales/zh-CN.json | 2 + 16 files changed, 150 insertions(+), 39 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 4a17077d1..86cd6fe90 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -74,7 +74,7 @@ app/api/ agent/new/route.ts POST { cwd, message, toolNames?, provider?, modelId? } agent/[id]/route.ts GET state | POST any RPC command events/route.ts GET multiplexed SSE | POST subscribe/unsubscribe channels - hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart? } | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable + hosts/route.ts GET hosts (this machine first) | POST { label } → token once + login command | PATCH { id, label?, allowAgentStart? } (`local`: label only, empty resets to "This machine") | DELETE ?id= revoke (registry first, then close the link); 503 if hosts.json is unreadable hosts/link/route.ts GET downlink (NDJSON stream) | POST uplink (NDJSON batch) — the `ompweb host` daemon; bearer-token auth, skipped by `proxy.ts` hosts/link/blob/[reqId]/route.ts POST raw bytes for a large op result (daemon → main) notifications/devices/route.ts GET VAPID key + subscribed | PUT { deviceId, prefs, subscription? } diff --git a/app/api/hosts/route.ts b/app/api/hosts/route.ts index 3d5210d11..583093187 100644 --- a/app/api/hosts/route.ts +++ b/app/api/hosts/route.ts @@ -76,8 +76,10 @@ export async function POST(req: Request) { export async function PATCH(req: Request) { const body = await readBody(req); if (!body || typeof body.id !== "string" || !body.id) return fail("id is required", 400); - if (body.id === "local") return fail("This machine cannot be edited", 400); - const label = parseLabel(body.label); + const isLocal = body.id === "local"; + if (isLocal && body.allowAgentStart !== undefined) return fail("This machine's agent-start setting cannot be changed", 400); + // An empty name resets this machine to its default name. + const label = isLocal && typeof body.label === "string" && !body.label.trim() ? "" : parseLabel(body.label); if (label === null) return fail(`label must be a non-empty string of at most ${MAX_LABEL_LENGTH} characters`, 400); const { allowAgentStart } = body; if (allowAgentStart !== undefined && typeof allowAgentStart !== "boolean") return fail("allowAgentStart must be a boolean", 400); @@ -85,7 +87,7 @@ export async function PATCH(req: Request) { try { updateHost(body.id, { label, allowAgentStart }); notifyHostsChange(); - return NextResponse.json({ host: listHosts().find((h) => h.id === body.id) }, { headers: noStore }); + return NextResponse.json({ host: hostsSnapshot().hosts.find((h) => h.id === body.id) }, { headers: noStore }); } catch (error) { return failFor(error); } diff --git a/components/HostsConfig.test.mjs b/components/HostsConfig.test.mjs index 6c9075407..4401810df 100644 --- a/components/HostsConfig.test.mjs +++ b/components/HostsConfig.test.mjs @@ -2,13 +2,22 @@ import "../tests/setup-dom.mjs"; import assert from "node:assert/strict"; import test, { afterEach } from "node:test"; import { createElement } from "react"; -import { cleanup, render, screen, waitFor } from "@testing-library/react/pure.js"; +import { act, cleanup, render, screen, waitFor } from "@testing-library/react/pure.js"; import userEvent from "@testing-library/user-event"; import { createJiti } from "jiti"; const { HostsConfig } = await createJiti(import.meta.url, { tsconfigPaths: true, fsCache: false, jsx: { runtime: "automatic" } }).import("./HostsConfig.tsx"); const originalWorker = globalThis.Worker; +// The event-stream transport keeps the first worker it was given for the whole file. +const workers = []; +class FakeWorker { + onmessage = null; + onerror = null; + posted = []; + constructor() { workers.push(this); } + postMessage(message) { this.posted.push(message); } +} afterEach(() => { cleanup(); globalThis.Worker = originalWorker; @@ -16,7 +25,7 @@ afterEach(() => { test("the one-time host token survives Escape; only Done closes it", async (t) => { // The hosts list rides the shared event-stream worker; a silent one keeps it idle. - globalThis.Worker = class { onmessage = null; onerror = null; postMessage() {} }; + globalThis.Worker = FakeWorker; t.mock.method(globalThis, "fetch", async () => Response.json({ host: { id: "h1", label: "Laptop" }, token: "tok-once", command: "ompweb host login --url https://omp.test" })); render(createElement(HostsConfig)); const user = userEvent.setup(); @@ -32,3 +41,33 @@ test("the one-time host token survives Escape; only Done closes it", async (t) = await user.click(screen.getByRole("button", { name: "Done" })); await waitFor(() => assert.equal(screen.queryByText("tok-once"), null)); }); + +test("this machine can be renamed but not revoked", async (t) => { + globalThis.Worker = FakeWorker; + const patches = []; + t.mock.method(globalThis, "fetch", async (url, init) => { + patches.push([init?.method, JSON.parse(init?.body ?? "null")]); + return Response.json({}); + }); + render(createElement(HostsConfig)); + const row = (fields) => ({ status: "online", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, ...fields }); + const hosts = [row({ id: "local", label: "" }), row({ id: "h1", label: "Laptop", allowAgentStart: false })]; + await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); + const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); + act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); + + const localRow = (await screen.findByRole("button", { name: "Rename This machine" })).closest("li"); + assert.deepEqual([...localRow.querySelectorAll("button")].map((button) => button.textContent), ["Rename"]); + assert.ok(screen.getByRole("button", { name: "Rename Laptop" }).closest("li").textContent.includes("Revoke")); + + // An empty name is allowed here: it resets to the default. + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: "Rename This machine" })); + await user.type(screen.getByPlaceholderText("This machine"), "Desk"); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => assert.deepEqual(patches, [["PATCH", { id: "local", label: "Desk" }]])); + + // With a custom name the card and its rename button use it. + act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts: [row({ id: "local", label: "Desk" })] }) } })); + await screen.findByRole("button", { name: "Rename Desk" }); +}); diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index 59871f76d..49aad6814 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -51,6 +51,7 @@ function CopyField({ label, value }: { label: string; value: string }) { function HostDialog({ dialog, onClose }: { dialog: NonNullable; onClose: () => void }) { const { t } = useI18n(); const adding = dialog.kind === "add"; + const local = dialog.kind === "rename" && dialog.host.id === "local"; const [label, setLabel] = useState(dialog.kind === "rename" ? dialog.host.label : ""); const [busy, setBusy] = useState(false); const [created, setCreated] = useState<{ token: string; command: string } | null>(null); @@ -92,11 +93,12 @@ function HostDialog({ dialog, onClose }: { dialog: NonNullable; onClose
void submit(event)} style={{ display: "flex", flexDirection: "column", gap: 12 }}>
-
@@ -127,22 +129,26 @@ function HostCard({ host, onRename, onRevoke }: { host: HostRow; onRename: () => {details &&
{details}
} - {linked && ( -
- {t("hostsConfig.allowAgentStart")} - void call("PATCH", "/api/hosts", { id: host.id, allowAgentStart }).catch(failure)} - /> - +
+ {linked && ( + <> + {t("hostsConfig.allowAgentStart")} + void call("PATCH", "/api/hosts", { id: host.id, allowAgentStart }).catch(failure)} + /> + + )} + + {linked && ( -
- )} + )} +
); } diff --git a/components/host-status.ts b/components/host-status.ts index 9c91ba6d1..b000bee96 100644 --- a/components/host-status.ts +++ b/components/host-status.ts @@ -4,9 +4,9 @@ type Translate = (key: string, vars?: Record) => string export const HOST_STATUS_COLOR = { online: "var(--status-success)", offline: "var(--text-dim)", "omp-missing": "var(--status-warning)", "needs-upgrade": "var(--status-warning)" } as const; -/** The name a host goes by in the UI: this machine is localized, linked hosts keep their label. */ +/** The name a host goes by in the UI: this machine is localized until the user names it, linked hosts keep their label. */ export function hostName(t: Translate, host: Pick): string { - return host.id === "local" ? t("hostsConfig.thisMachine") : host.label; + return host.id === "local" && !host.label ? t("hostsConfig.thisMachine") : host.label; } export function hostStatusText(t: Translate, host: HostRow): string { diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index 8f670322a..aae933516 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -42,8 +42,9 @@ ompweb (web service) ──link over 127.0.0.1──▶ ompweb host (daemon se ``` - **"This machine" is a linked host with the fixed id `local`.** It is shown as - "This machine", listed first, and cannot be revoked or renamed in Settings → - Hosts. + "This machine" until it is renamed in Settings → Hosts (an empty name resets + it; the registry keeps "" for the default), and is listed first. It cannot be + revoked, and its `allowAgentStart` is fixed. - **Session file operations** (`session-ops.ts`) run in the daemon, as they do for remote hosts. The web server keeps no direct session-file reads for `local`, so the two paths cannot drift. diff --git a/lib/agent-tools.test.mjs b/lib/agent-tools.test.mjs index 2c0233667..98e59635b 100644 --- a/lib/agent-tools.test.mjs +++ b/lib/agent-tools.test.mjs @@ -274,6 +274,18 @@ test("new_session without a host, or with local / This machine, starts here with assert.deepEqual(ops.calls.create.map((input) => input.hostId), ["local", "local", "local"]); }); +test("a renamed this machine resolves by its custom label, `local` and \"This machine\", and list_sessions names it", async () => { + const listHosts = () => [ + { id: "local", label: "Desk", online: true, allowAgentStart: true }, + { id: "h-ci", label: "ci-box", online: true, allowAgentStart: true }, + ]; + const ops = fakeOps({ listHosts }); + for (const host of ["Desk", "local", "This machine"]) await executeAgentTool("new_session", { host }, ops, ctx()); + assert.deepEqual(ops.calls.create.map((input) => input.hostId), ["local", "local", "local"]); + assert.deepEqual((await executeAgentTool("list_sessions", {}, ops, ctx())).sessions.map((s) => s.host), ["Desk"]); + await assert.rejects(() => executeAgentTool("new_session", { host: "nowhere" }, ops, ctx()), /Known hosts: Desk, ci-box/); +}); + /** A confirm that records each title and answers `answer`. */ const asking = (titles, answer = true) => async (title) => { titles.push(title); diff --git a/lib/agent-tools.ts b/lib/agent-tools.ts index d44d74411..fc2853ee2 100644 --- a/lib/agent-tools.ts +++ b/lib/agent-tools.ts @@ -299,7 +299,8 @@ function checkMessageLength(message: string, field: string): void { /** `host` matched case-insensitively against ids, then labels; a label several hosts share is refused, not guessed. */ function resolveHost(hosts: AgentToolHost[], host: string): AgentToolHost { const wanted = host.toLowerCase(); - const byId = hosts.find((h) => h.id.toLowerCase() === wanted); + // "This machine" keeps working after the user renames it. + const byId = hosts.find((h) => h.id.toLowerCase() === (wanted === "this machine" ? "local" : wanted)); const labelled = byId ? [] : hosts.filter((h) => h.label.toLowerCase() === wanted); if (labelled.length > 1) { throw new Error(`"${host}" matches more than one host (ids: ${labelled.map((h) => h.id).join(", ")}). Pass one of those ids as host.`); diff --git a/lib/hosts/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index 751828408..91adcd9ae 100644 --- a/lib/hosts/hosts-route.test.mjs +++ b/lib/hosts/hosts-route.test.mjs @@ -78,8 +78,6 @@ test("PATCH renames and toggles allowAgentStart; local cannot be edited or revok assert.equal(patched.status, 200); assert.deepEqual((await get()).hosts.filter((h) => h.id === host.id).map((h) => [h.label, h.allowAgentStart]), [["new", true]]); - assert.equal((await send("PATCH", { id: "local", label: "x" })).status, 400); - assert.equal((await route.DELETE(new Request(`${BASE}?id=local`, { method: "DELETE" }))).status, 400); assert.equal((await send("PATCH", { id: "missing", label: "x" })).status, 404); }); @@ -118,7 +116,7 @@ test("the local row and getHost(local) show the reserved record's real link stat const localRows = async () => (await get()).hosts.filter((h) => h.id === "local"); // Dev server, or before the first bootstrap: no record, no daemon. - assert.deepEqual((await localRows()).map((h) => [h.label, h.status]), [["This machine", "offline"]]); + assert.deepEqual((await localRows()).map((h) => [h.label, h.status]), [["", "offline"]], "no custom name: the UI shows the localized default"); assert.equal(hub.getHost("local").status(), "offline"); const { token } = ensureLocalHostLink({ url: "http://127.0.0.1:30177" }); @@ -139,4 +137,17 @@ test("the local row and getHost(local) show the reserved record's real link stat assert.equal((await send("PATCH", { id: "local", allowAgentStart: false })).status, 400); assert.equal((await route.DELETE(new Request(`${BASE}?id=local`, { method: "DELETE" }))).status, 400); + + // Renamed, the name reaches the row and server-side text; an empty or blank name resets it. + const renamed = await send("PATCH", { id: "local", label: " Desk " }); + assert.equal(renamed.status, 200); + assert.equal((await renamed.json()).host.label, "Desk"); + assert.deepEqual((await localRows()).map((h) => h.label), ["Desk"]); + assert.equal(hub.getHost("local").label, "Desk"); + assert.equal((await send("PATCH", { id: "local", label: "x".repeat(101) })).status, 400); + assert.equal((await send("PATCH", { id: "local", label: 5 })).status, 400); + assert.equal((await send("PATCH", { id: "local" })).status, 400); + assert.equal((await send("PATCH", { id: "local", label: " " })).status, 200); + assert.deepEqual((await localRows()).map((h) => h.label), [""]); + assert.equal(hub.getHost("local").label, "This machine"); }); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 7ed9d9344..fa92adc45 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -28,7 +28,7 @@ import { type HostOpName, type UpMessage, } from "./link-protocol"; -import { HostRegistryUnreadableError, hostForToken, LOCAL_HOST_ID, loadHosts, touchHost, type HostRecord } from "./registry"; +import { customLocalLabel, DEFAULT_LOCAL_LABEL, HostRegistryUnreadableError, hostForToken, LOCAL_HOST_ID, loadHosts, touchHost, type HostRecord } from "./registry"; import type { SessionOps } from "./session-ops"; /** Liveness and op timeouts from LINK_LIMITS; tests shorten them. */ @@ -130,7 +130,8 @@ function linkFor(id: string): Link { } function labelOf(id: string): string { - return loadHosts().find((h) => h.id === id)?.label ?? (id === LOCAL_HOST_ID ? "This machine" : id); + if (id === LOCAL_HOST_ID) return customLocalLabel() || DEFAULT_LOCAL_LABEL; + return loadHosts().find((h) => h.id === id)?.label ?? id; } function notify
(listeners: Iterable<(...args: A) => void>, ...args: A): void { @@ -912,6 +913,7 @@ export function listHosts(): LinkedHostRow[] { export interface LocalHostRow { id: "local"; + /** The user's name for this machine; "" while it goes by the localized default. */ label: string; status: HostStatus; ompVersion: string | null; @@ -928,7 +930,7 @@ export function hostsSnapshot(): { hosts: HostRow[] } { const link = hub().links.get(LOCAL_HOST_ID); const local: LocalHostRow = { id: "local", - label: labelOf(LOCAL_HOST_ID), + label: customLocalLabel(), status: link?.status ?? "offline", ompVersion: link?.ompVersion ?? null, platform: link?.platform ?? null, diff --git a/lib/hosts/local-bootstrap.test.mjs b/lib/hosts/local-bootstrap.test.mjs index 2b42e883c..fe3c8f792 100644 --- a/lib/hosts/local-bootstrap.test.mjs +++ b/lib/hosts/local-bootstrap.test.mjs @@ -57,9 +57,9 @@ test("a host.json token the registry does not know is replaced, keeping one loca assert.equal(loadHosts().filter((host) => host.id === "local").length, 1); }); -test("the registry refuses to revoke or edit local, and createHost never makes it", () => { +test("the registry refuses to revoke local or change its agent-start right, and createHost never makes it", () => { assert.throws(() => revokeHost("local"), { name: "ReservedHostError" }); - assert.throws(() => updateHost("local", { label: "x" }), { name: "ReservedHostError" }); + assert.throws(() => updateHost("local", { allowAgentStart: false }), { name: "ReservedHostError" }); assert.notEqual(createHost("laptop").host.id, "local"); assert.equal(loadHosts().filter((host) => host.id === "local").length, 1); }); diff --git a/lib/hosts/registry.test.mjs b/lib/hosts/registry.test.mjs index b84d9b445..00ba63865 100644 --- a/lib/hosts/registry.test.mjs +++ b/lib/hosts/registry.test.mjs @@ -8,7 +8,7 @@ import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); const registry = await jiti.import("./registry.ts"); -const { createHost, hostForToken, loadHosts, revokeHost, touchHost, updateHost } = registry; +const { createHost, customLocalLabel, hostForToken, loadHosts, revokeHost, rotateLocalHostToken, touchHost, updateHost } = registry; /** Point the omp agent dir at a throwaway location for the duration of `fn`. */ async function withAgentDir(fn) { @@ -126,3 +126,25 @@ test("malformed records are skipped and do not break token lookup", () => assert.equal(hostForToken(token)?.id, host.id); assert.equal(hostForToken(undefined), null); })); + +test("this machine can be renamed and reset, never revoked or given agent-start rights", () => + withAgentDir(async () => { + const token = rotateLocalHostToken(); + assert.equal(customLocalLabel(), ""); + + assert.equal(updateHost("local", { label: " Desk " }).label, "Desk"); + assert.equal(customLocalLabel(), "Desk"); + assert.equal(hostForToken(token)?.id, "local"); + assert.equal(loadHosts()[0].allowAgentStart, true); + + rotateLocalHostToken(); + assert.equal(customLocalLabel(), "Desk", "a new token keeps the name"); + + assert.throws(() => revokeHost("local"), { name: "ReservedHostError" }); + assert.throws(() => updateHost("local", { allowAgentStart: false }), { name: "ReservedHostError" }); + assert.equal(customLocalLabel(), "Desk"); + + updateHost("local", { label: " " }); + assert.equal(customLocalLabel(), ""); + assert.throws(() => updateHost(createHost("laptop").host.id, { label: " " }), { message: "Host label is required" }); + })); diff --git a/lib/hosts/registry.ts b/lib/hosts/registry.ts index dffe90110..971bc99b4 100644 --- a/lib/hosts/registry.ts +++ b/lib/hosts/registry.ts @@ -19,6 +19,14 @@ interface HostsFile { /** "This machine": the one record the web server itself creates (local-bootstrap.ts). */ export const LOCAL_HOST_ID = "local"; +/** What this machine is called until the user names it. */ +export const DEFAULT_LOCAL_LABEL = "This machine"; + +/** The name the user gave this machine; "" while it goes by the default. */ +export function customLocalLabel(): string { + const label = loadHosts().find((h) => h.id === LOCAL_HOST_ID)?.label ?? ""; + return label === DEFAULT_LOCAL_LABEL ? "" : label; +} function normalizeLabel(label: string): string { const trimmed = label.trim(); @@ -113,7 +121,7 @@ export class UnknownHostError extends Error { } } -/** `local` is created and keyed by the web server only; it cannot be renamed or revoked. */ +/** `local` is created and keyed by the web server only; it can be renamed but not revoked or given agent-start rights. */ export class ReservedHostError extends Error { readonly name = "ReservedHostError"; constructor() { @@ -122,11 +130,12 @@ export class ReservedHostError extends Error { } export function updateHost(id: string, updates: { label?: string; allowAgentStart?: boolean }): HostRecord { - if (id === LOCAL_HOST_ID) throw new ReservedHostError(); + if (id === LOCAL_HOST_ID && updates.allowAgentStart !== undefined) throw new ReservedHostError(); const hosts = readHosts(); const host = hosts.find((h) => h.id === id); if (!host) throw new UnknownHostError(); - if (updates.label !== undefined) host.label = normalizeLabel(updates.label); + // An empty name resets this machine to the default. + if (updates.label !== undefined) host.label = id === LOCAL_HOST_ID && !updates.label.trim() ? "" : normalizeLabel(updates.label); if (updates.allowAgentStart !== undefined) host.allowAgentStart = updates.allowAgentStart; saveHosts(hosts); return host; @@ -139,7 +148,7 @@ export function rotateLocalHostToken(): string { const token = randomBytes(32).toString("base64url"); const record: HostRecord = { id: LOCAL_HOST_ID, - label: "This machine", + label: existing?.label ?? "", tokenHash: sha256Hex(token), createdAt: existing?.createdAt || new Date().toISOString(), lastSeenAt: existing?.lastSeenAt ?? null, diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 33d863e65..d6532b736 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1334,6 +1334,8 @@ "hostsConfig.allowAgentStartAria": "Agents can start sessions on {name} without asking", "hostsConfig.rename": "Rename", "hostsConfig.renameTitle": "Rename host", + "hostsConfig.renameAria": "Rename {name}", + "hostsConfig.localNameHint": "Leave empty to use “This machine”.", "hostsConfig.save": "Save", "hostsConfig.saving": "Saving…", "hostsConfig.cancel": "Cancel", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 383195b8b..d32533233 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1293,6 +1293,8 @@ "hostsConfig.allowAgentStartAria": "エージェントが確認なしで {name} にセッションを開始できる", "hostsConfig.rename": "名前を変更", "hostsConfig.renameTitle": "ホスト名を変更", + "hostsConfig.renameAria": "{name} の名前を変更", + "hostsConfig.localNameHint": "空欄にすると「このマシン」に戻ります。", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", "hostsConfig.cancel": "キャンセル", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index cfc517832..48076dbd7 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1293,6 +1293,8 @@ "hostsConfig.allowAgentStartAria": "智能体可在 {name} 上无需确认即启动会话", "hostsConfig.rename": "重命名", "hostsConfig.renameTitle": "重命名主机", + "hostsConfig.renameAria": "重命名 {name}", + "hostsConfig.localNameHint": "留空则使用“本机”。", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", "hostsConfig.cancel": "取消", From 966fcdb8444979d1cde12c94a6570857fe6bf1bf Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 23:12:47 +0000 Subject: [PATCH 18/36] feat(hosts): tell users to install the local daemon --- components/AppShell.tsx | 2 + components/HostsConfig.test.mjs | 37 ++++++++++++++ components/HostsConfig.tsx | 12 +++-- components/LocalDaemonBanner.test.mjs | 74 +++++++++++++++++++++++++++ components/LocalDaemonBanner.tsx | 59 +++++++++++++++++++++ components/SessionSidebar.tsx | 2 +- components/host-status.ts | 6 +++ lib/hosts/hosts-route.test.mjs | 1 + lib/hosts/hub.ts | 3 ++ lib/i18n/locales/en.json | 3 ++ lib/i18n/locales/ja.json | 3 ++ lib/i18n/locales/zh-CN.json | 3 ++ 12 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 components/LocalDaemonBanner.test.mjs create mode 100644 components/LocalDaemonBanner.tsx diff --git a/components/AppShell.tsx b/components/AppShell.tsx index b2c2e33da..68deb1d2f 100644 --- a/components/AppShell.tsx +++ b/components/AppShell.tsx @@ -38,6 +38,7 @@ import { comparableProjectPath } from "@/lib/comparable-path"; import { LOCAL_HOST_ID, remoteHostId } from "@/lib/project-ordering"; import { isLinkUp } from "@/lib/hosts/host"; import { useHostRows } from "@/hooks/useHostRows"; +import { LocalDaemonBanner } from "./LocalDaemonBanner"; import { hostName, hostStatusText } from "./host-status"; import { clearDraft } from "@/lib/draft-store"; import { useNotifications } from "@/hooks/useNotifications"; @@ -2730,6 +2731,7 @@ export function AppShell({ appName }: { appName: string }) { )} + void proceedWithAppUpdate()} onNotNow={dismissAppUpdate} /> {archiveBrowserOpen && ( { act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts: [row({ id: "local", label: "Desk" })] }) } })); await screen.findByRole("button", { name: "Rename Desk" }); }); + +test("an offline this-machine row says to start the service, with the server's install command", async (t) => { + globalThis.Worker = FakeWorker; + t.mock.method(globalThis, "fetch", async () => Response.json({})); + render(createElement(HostsConfig)); + const row = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "darwin", ...fields }); + await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); + const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); + const send = (hosts) => act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); + + send([row({})]); + const hint = await screen.findByText(/ompweb-host service/); + assert.ok(hint.textContent.includes("ompweb launchd install"), hint.textContent); + assert.deepEqual([...hint.closest("li").querySelectorAll("button")].map((button) => button.textContent), ["Rename"]); + + send([row({ serverPlatform: "linux" })]); + assert.ok((await screen.findByText(/ompweb-host service/)).textContent.includes("ompweb systemd install")); + send([row({ serverPlatform: "win32" })]); + assert.ok((await screen.findByText(/ompweb-host service/)).textContent.includes("ompweb-tray install")); + + send([row({ status: "online", hostVersion: 3 })]); + await waitFor(() => assert.equal(screen.queryByText(/ompweb-host service/), null)); +}); + +test("the local name hint is the input's description, not part of its label", async (t) => { + globalThis.Worker = FakeWorker; + t.mock.method(globalThis, "fetch", async () => Response.json({})); + render(createElement(HostsConfig)); + const row = { id: "local", label: "", status: "online", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: 3, serverVersion: 3, serverPlatform: "linux" }; + await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); + const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); + act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts: [row] }) } })); + await userEvent.setup().click(await screen.findByRole("button", { name: "Rename This machine" })); + // The label stays just "Name": the hint is not inside it. + screen.getByRole("textbox", { name: "Name" }); + assert.equal(screen.getByRole("textbox").getAttribute("aria-describedby"), screen.getByText(/Leave empty/).id); +}); diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index 49aad6814..b30f74cb1 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -1,6 +1,6 @@ "use client"; -import { useState, type FormEvent } from "react"; +import { useId, useState, type FormEvent } from "react"; import { Copy, Pencil, Plus, Trash2 } from "lucide-react"; import { ConfirmDialog } from "@/components/ui/field"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/primitives"; @@ -10,7 +10,7 @@ import { copyText } from "@/lib/clipboard"; import type { HostRow } from "@/lib/hosts/hub"; import { useI18n } from "@/lib/i18n"; import { useHostRows } from "@/hooks/useHostRows"; -import { HOST_STATUS_COLOR, hostName, hostStatusText } from "./host-status"; +import { HOST_STATUS_COLOR, hostName, hostStatusText, localInstallCommand } from "./host-status"; type Dialogs = { kind: "add" } | { kind: "rename"; host: HostRow } | null; @@ -54,6 +54,7 @@ function HostDialog({ dialog, onClose }: { dialog: NonNullable; onClose const local = dialog.kind === "rename" && dialog.host.id === "local"; const [label, setLabel] = useState(dialog.kind === "rename" ? dialog.host.label : ""); const [busy, setBusy] = useState(false); + const hintId = useId(); const [created, setCreated] = useState<{ token: string; command: string } | null>(null); const submit = async (event: FormEvent) => { @@ -93,9 +94,9 @@ function HostDialog({ dialog, onClose }: { dialog: NonNullable; onClose void submit(event)} style={{ display: "flex", flexDirection: "column", gap: 12 }}> + {local && {t("hostsConfig.localNameHint")}}
{details &&
{details}
} + {"serverPlatform" in host && host.status === "offline" && ( +
{t("hostsConfig.localOfflineHint", { command: localInstallCommand(host.serverPlatform) })}
+ )}
{linked && ( diff --git a/components/LocalDaemonBanner.test.mjs b/components/LocalDaemonBanner.test.mjs new file mode 100644 index 000000000..6040469d0 --- /dev/null +++ b/components/LocalDaemonBanner.test.mjs @@ -0,0 +1,74 @@ +import "../tests/setup-dom.mjs"; +import assert from "node:assert/strict"; +import test, { afterEach, beforeEach } from "node:test"; +import { createElement } from "react"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react/pure.js"; +import { createJiti } from "jiti"; + +const { LocalDaemonBanner, LOCAL_DAEMON_BANNER_DISMISSED_KEY } = await createJiti(import.meta.url, { tsconfigPaths: true, fsCache: false, jsx: { runtime: "automatic" } }).import("./LocalDaemonBanner.tsx"); + +const originalWorker = globalThis.Worker; +const workers = []; +class FakeWorker { + onmessage = null; + onerror = null; + posted = []; + constructor() { workers.push(this); } + postMessage(message) { this.posted.push(message); } +} +beforeEach(() => { globalThis.Worker = FakeWorker; localStorage.clear(); }); +afterEach(() => { + cleanup(); + globalThis.Worker = originalWorker; +}); + +const local = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "linux", ...fields }); +const send = (hosts) => { + const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); + act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); +}; +const opens = () => workers[0]?.posted.filter((message) => message.op === "open").length ?? 0; +// The event-stream transport keeps its first worker, so a new mount shows up as one more open. +const mount = async () => { + const before = opens(); + render(createElement(LocalDaemonBanner)); + await waitFor(() => assert.ok(opens() > before)); +}; +const text = /needs the ompweb-host service/; + +test("the install banner appears after 10 s offline, once: dismissing it keeps it away", async (t) => { + await mount(); + t.mock.timers.enable({ apis: ["setTimeout"] }); + send([local({})]); + act(() => t.mock.timers.tick(9_999)); + assert.equal(screen.queryByText(text), null); + act(() => t.mock.timers.tick(1)); + assert.ok(screen.getByText(text).textContent.includes("This machine needs the ompweb-host service. Install it with: ompweb systemd install")); + + fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); + assert.equal(screen.queryByText(text), null); + assert.ok(localStorage.getItem(LOCAL_DAEMON_BANNER_DISMISSED_KEY)); + + cleanup(); + t.mock.timers.reset(); // waitFor needs real timers + await mount(); + t.mock.timers.enable({ apis: ["setTimeout"] }); + send([local({})]); + act(() => t.mock.timers.tick(20_000)); + assert.equal(screen.queryByText(text), null); +}); + +test("no banner when the daemon links within 10 s, or has linked before", async (t) => { + await mount(); + t.mock.timers.enable({ apis: ["setTimeout"] }); + send([local({})]); + act(() => t.mock.timers.tick(5_000)); + send([local({ status: "online", hostVersion: 3 })]); + act(() => t.mock.timers.tick(20_000)); + assert.equal(screen.queryByText(text), null); + + // A daemon that linked earlier and dropped is the offline banner's job, not an install hint. + send([local({ hostVersion: 3 })]); + act(() => t.mock.timers.tick(20_000)); + assert.equal(screen.queryByText(text), null); +}); diff --git a/components/LocalDaemonBanner.tsx b/components/LocalDaemonBanner.tsx new file mode 100644 index 000000000..2f86f66d4 --- /dev/null +++ b/components/LocalDaemonBanner.tsx @@ -0,0 +1,59 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { X } from "lucide-react"; +import { useHostRows } from "@/hooks/useHostRows"; +import { useI18n } from "@/lib/i18n"; +import { hostName, localInstallCommand } from "./host-status"; + +export const LOCAL_DAEMON_BANNER_DISMISSED_KEY = "omp-web:local-daemon-banner-dismissed"; +const GRACE_MS = 10_000; + +/** One-time hint to install the ompweb-host service: this machine has not linked since this server started and 10 s have passed. */ +export function LocalDaemonBanner() { + const { t } = useI18n(); + const { hosts } = useHostRows(); + const local = hosts?.find((host) => "serverPlatform" in host); + const missing = local?.status === "offline" && local.hostVersion === null; + const [waited, setWaited] = useState(false); + // Hidden until storage is read, so a dismissed banner never flashes. + const [dismissed, setDismissed] = useState(true); + + useEffect(() => { + try { + setDismissed(window.localStorage.getItem(LOCAL_DAEMON_BANNER_DISMISSED_KEY) === "true"); + } catch { + setDismissed(false); + } + }, []); + + useEffect(() => { + if (!missing) return; + const timer = setTimeout(() => setWaited(true), GRACE_MS); + return () => { + clearTimeout(timer); + setWaited(false); + }; + }, [missing]); + + if (!local || !missing || !waited || dismissed) return null; + const dismiss = () => { + setDismissed(true); + try { + window.localStorage.setItem(LOCAL_DAEMON_BANNER_DISMISSED_KEY, "true"); + } catch { + // Dismissed for this page view only. + } + }; + return ( +
+ {t("hostsConfig.localDaemonBanner", { host: hostName(t, local), command: localInstallCommand(local.serverPlatform) })} + +
+ ); +} diff --git a/components/SessionSidebar.tsx b/components/SessionSidebar.tsx index b7a88de30..c0ff11c9a 100644 --- a/components/SessionSidebar.tsx +++ b/components/SessionSidebar.tsx @@ -120,7 +120,7 @@ interface Props { /** The host a project or session belongs to: this machine unless it says otherwise. */ const hostOf = (item: { hostId?: string }): string => item.hostId ?? LOCAL_HOST_ID; -const THIS_MACHINE = { id: LOCAL_HOST_ID, label: "This machine" }; +const THIS_MACHINE = { id: LOCAL_HOST_ID, label: "" }; const COLLAPSED_HOSTS_STORAGE_KEY = "omp-web:collapsed-hosts"; function loadCollapsedHosts(): Set { diff --git a/components/host-status.ts b/components/host-status.ts index b000bee96..381470383 100644 --- a/components/host-status.ts +++ b/components/host-status.ts @@ -9,6 +9,12 @@ export function hostName(t: Translate, host: Pick): str return host.id === "local" && !host.label ? t("hostsConfig.thisMachine") : host.label; } +/** The command that installs the ompweb-host service on the server's platform (`LocalHostRow.serverPlatform`). */ +export function localInstallCommand(platform: string): string { + if (platform === "darwin") return "ompweb launchd install"; + return platform === "win32" ? "ompweb-tray install" : "ompweb systemd install"; +} + export function hostStatusText(t: Translate, host: HostRow): string { switch (host.status) { case "online": diff --git a/lib/hosts/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index 91adcd9ae..3619955ee 100644 --- a/lib/hosts/hosts-route.test.mjs +++ b/lib/hosts/hosts-route.test.mjs @@ -53,6 +53,7 @@ test("POST returns the token once; GET lists the host without any secret", async const { hosts } = JSON.parse(text); assert.equal(hosts[0].id, "local"); assert.ok(!("allowAgentStart" in hosts[0])); + assert.equal(hosts[0].serverPlatform, process.platform); assert.deepEqual(hosts.slice(1).map((h) => [h.id, h.status, h.allowAgentStart]), [[host.id, "offline", false]]); }); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index fa92adc45..53086757c 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -921,6 +921,8 @@ export interface LocalHostRow { lastSeenAt: null; hostVersion: number | null; serverVersion: number; + /** `process.platform` of this server: picks the daemon install command while no daemon has linked. */ + serverPlatform: string; } export type HostRow = LocalHostRow | LinkedHostRow; @@ -937,6 +939,7 @@ export function hostsSnapshot(): { hosts: HostRow[] } { lastSeenAt: null, hostVersion: link?.hostVersion ?? null, serverVersion: LINK_PROTOCOL_VERSION, + serverPlatform: process.platform, }; return { hosts: [local, ...listHosts()] }; } diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index d6532b736..3768693f2 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1336,6 +1336,9 @@ "hostsConfig.renameTitle": "Rename host", "hostsConfig.renameAria": "Rename {name}", "hostsConfig.localNameHint": "Leave empty to use “This machine”.", + "hostsConfig.localOfflineHint": "Start the ompweb-host service. To install it, run: {command}", + "hostsConfig.localDaemonBanner": "{host} needs the ompweb-host service. Install it with: {command}", + "hostsConfig.dismiss": "Dismiss", "hostsConfig.save": "Save", "hostsConfig.saving": "Saving…", "hostsConfig.cancel": "Cancel", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index d32533233..2364257a4 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1295,6 +1295,9 @@ "hostsConfig.renameTitle": "ホスト名を変更", "hostsConfig.renameAria": "{name} の名前を変更", "hostsConfig.localNameHint": "空欄にすると「このマシン」に戻ります。", + "hostsConfig.localOfflineHint": "ompweb-host サービスを起動してください。インストールするには次を実行します: {command}", + "hostsConfig.localDaemonBanner": "{host} には ompweb-host サービスが必要です。次のコマンドでインストールします: {command}", + "hostsConfig.dismiss": "閉じる", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", "hostsConfig.cancel": "キャンセル", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 48076dbd7..ed98b5401 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1295,6 +1295,9 @@ "hostsConfig.renameTitle": "重命名主机", "hostsConfig.renameAria": "重命名 {name}", "hostsConfig.localNameHint": "留空则使用“本机”。", + "hostsConfig.localOfflineHint": "请启动 ompweb-host 服务。安装方法,运行:{command}", + "hostsConfig.localDaemonBanner": "{host} 需要 ompweb-host 服务。请用以下命令安装:{command}", + "hostsConfig.dismiss": "关闭", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", "hostsConfig.cancel": "取消", From 628424ba6488ea559fce26592209dbf0fd378847 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 23:17:58 +0000 Subject: [PATCH 19/36] fix(hosts): no install hint in dev mode, 90 s banner grace, copyable command, live-region wrapper --- components/HostsConfig.test.mjs | 17 +++++---- components/HostsConfig.tsx | 11 +++--- components/LocalDaemonBanner.test.mjs | 31 ++++++++++++----- components/LocalDaemonBanner.tsx | 36 ++++++++++++-------- components/host-status.ts | 4 ++- docs/specs/2026-10-29-local-daemon-design.md | 6 ++-- lib/hosts/hub.ts | 3 ++ lib/i18n/locales/en.json | 4 +-- lib/i18n/locales/ja.json | 4 +-- lib/i18n/locales/zh-CN.json | 4 +-- 10 files changed, 77 insertions(+), 43 deletions(-) diff --git a/components/HostsConfig.test.mjs b/components/HostsConfig.test.mjs index 22517885c..6bbcd71f8 100644 --- a/components/HostsConfig.test.mjs +++ b/components/HostsConfig.test.mjs @@ -76,20 +76,25 @@ test("an offline this-machine row says to start the service, with the server's i globalThis.Worker = FakeWorker; t.mock.method(globalThis, "fetch", async () => Response.json({})); render(createElement(HostsConfig)); - const row = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "darwin", ...fields }); + const row = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "darwin", daemonManaged: true, ...fields }); await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); const send = (hosts) => act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); send([row({})]); const hint = await screen.findByText(/ompweb-host service/); - assert.ok(hint.textContent.includes("ompweb launchd install"), hint.textContent); - assert.deepEqual([...hint.closest("li").querySelectorAll("button")].map((button) => button.textContent), ["Rename"]); + assert.equal(hint.closest("li").querySelector("code").textContent, "ompweb launchd install"); + // The command is copyable; the local row still has no Revoke. + assert.deepEqual([...hint.closest("li").querySelectorAll("button")].map((button) => button.textContent), ["Copy", "Rename"]); send([row({ serverPlatform: "linux" })]); - assert.ok((await screen.findByText(/ompweb-host service/)).textContent.includes("ompweb systemd install")); + assert.equal((await screen.findByText(/ompweb-host service/)).closest("li").querySelector("code").textContent, "ompweb systemd install"); send([row({ serverPlatform: "win32" })]); - assert.ok((await screen.findByText(/ompweb-host service/)).textContent.includes("ompweb-tray install")); + assert.equal((await screen.findByText(/ompweb-host service/)).closest("li").querySelector("code").textContent, "ompweb-tray install"); + + // Dev mode: offline by design, nothing to install. + send([row({ daemonManaged: false })]); + await waitFor(() => assert.equal(screen.queryByText(/ompweb-host service/), null)); send([row({ status: "online", hostVersion: 3 })]); await waitFor(() => assert.equal(screen.queryByText(/ompweb-host service/), null)); @@ -99,7 +104,7 @@ test("the local name hint is the input's description, not part of its label", as globalThis.Worker = FakeWorker; t.mock.method(globalThis, "fetch", async () => Response.json({})); render(createElement(HostsConfig)); - const row = { id: "local", label: "", status: "online", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: 3, serverVersion: 3, serverPlatform: "linux" }; + const row = { id: "local", label: "", status: "online", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: 3, serverVersion: 3, serverPlatform: "linux", daemonManaged: true }; await waitFor(() => assert.ok(workers[0].posted.some((message) => message.op === "open" && message.channel.kind === "hosts"))); const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts: [row] }) } })); diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index b30f74cb1..a15cd21a6 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -10,7 +10,7 @@ import { copyText } from "@/lib/clipboard"; import type { HostRow } from "@/lib/hosts/hub"; import { useI18n } from "@/lib/i18n"; import { useHostRows } from "@/hooks/useHostRows"; -import { HOST_STATUS_COLOR, hostName, hostStatusText, localInstallCommand } from "./host-status"; +import { HOST_STATUS_COLOR, hostName, hostStatusText, isLocalRow, localInstallCommand } from "./host-status"; type Dialogs = { kind: "add" } | { kind: "rename"; host: HostRow } | null; @@ -27,7 +27,7 @@ async function call(method: string, url: string, body?: unknown): Promise toast.error(error instanceof Error ? error.message : String(error)); -function CopyField({ label, value }: { label: string; value: string }) { +export function CopyField({ label, value }: { label: string; value: string }) { const { t } = useI18n(); return (
@@ -129,8 +129,11 @@ function HostCard({ host, onRename, onRevoke }: { host: HostRow; onRename: () => {hostStatusText(t, host)}
{details &&
{details}
} - {"serverPlatform" in host && host.status === "offline" && ( -
{t("hostsConfig.localOfflineHint", { command: localInstallCommand(host.serverPlatform) })}
+ {isLocalRow(host) && host.daemonManaged && host.status === "offline" && ( +
+ {t("hostsConfig.localOfflineHint")} + +
)}
diff --git a/components/LocalDaemonBanner.test.mjs b/components/LocalDaemonBanner.test.mjs index 6040469d0..780489e11 100644 --- a/components/LocalDaemonBanner.test.mjs +++ b/components/LocalDaemonBanner.test.mjs @@ -22,7 +22,7 @@ afterEach(() => { globalThis.Worker = originalWorker; }); -const local = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "linux", ...fields }); +const local = (fields) => ({ id: "local", label: "", status: "offline", ompVersion: null, platform: null, lastSeenAt: null, hostVersion: null, serverVersion: 3, serverPlatform: "linux", daemonManaged: true, ...fields }); const send = (hosts) => { const { id } = workers[0].posted.findLast((message) => message.op === "open" && message.channel.kind === "hosts"); act(() => workers[0].onmessage({ data: { id, type: "message", data: JSON.stringify({ hosts }) } })); @@ -36,14 +36,15 @@ const mount = async () => { }; const text = /needs the ompweb-host service/; -test("the install banner appears after 10 s offline, once: dismissing it keeps it away", async (t) => { +test("the install banner appears after 90 s offline, once: dismissing it keeps it away", async (t) => { await mount(); t.mock.timers.enable({ apis: ["setTimeout"] }); send([local({})]); - act(() => t.mock.timers.tick(9_999)); + act(() => t.mock.timers.tick(89_999)); assert.equal(screen.queryByText(text), null); act(() => t.mock.timers.tick(1)); - assert.ok(screen.getByText(text).textContent.includes("This machine needs the ompweb-host service. Install it with: ompweb systemd install")); + assert.ok(screen.getByText(text).textContent.startsWith("This machine needs the ompweb-host service. Install it with:")); + assert.equal(screen.getByRole("status").querySelector("code").textContent, "ompweb systemd install"); fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); assert.equal(screen.queryByText(text), null); @@ -54,21 +55,33 @@ test("the install banner appears after 10 s offline, once: dismissing it keeps i await mount(); t.mock.timers.enable({ apis: ["setTimeout"] }); send([local({})]); - act(() => t.mock.timers.tick(20_000)); + act(() => t.mock.timers.tick(200_000)); assert.equal(screen.queryByText(text), null); }); -test("no banner when the daemon links within 10 s, or has linked before", async (t) => { +test("the live region stays mounted while the banner is hidden", async () => { + await mount(); + send([local({})]); + assert.ok(screen.getByRole("status")); + assert.equal(screen.getByRole("status").childElementCount, 0); +}); + +test("no banner when the daemon links within 90 s, or has linked before, or in dev mode", async (t) => { await mount(); t.mock.timers.enable({ apis: ["setTimeout"] }); send([local({})]); - act(() => t.mock.timers.tick(5_000)); + act(() => t.mock.timers.tick(30_000)); send([local({ status: "online", hostVersion: 3 })]); - act(() => t.mock.timers.tick(20_000)); + act(() => t.mock.timers.tick(200_000)); assert.equal(screen.queryByText(text), null); // A daemon that linked earlier and dropped is the offline banner's job, not an install hint. send([local({ hostVersion: 3 })]); - act(() => t.mock.timers.tick(20_000)); + act(() => t.mock.timers.tick(200_000)); + assert.equal(screen.queryByText(text), null); + + // Dev mode: this machine is offline by design. + send([local({ daemonManaged: false })]); + act(() => t.mock.timers.tick(200_000)); assert.equal(screen.queryByText(text), null); }); diff --git a/components/LocalDaemonBanner.tsx b/components/LocalDaemonBanner.tsx index 2f86f66d4..bb35276ac 100644 --- a/components/LocalDaemonBanner.tsx +++ b/components/LocalDaemonBanner.tsx @@ -4,17 +4,19 @@ import { useEffect, useState } from "react"; import { X } from "lucide-react"; import { useHostRows } from "@/hooks/useHostRows"; import { useI18n } from "@/lib/i18n"; -import { hostName, localInstallCommand } from "./host-status"; +import { CopyField } from "./HostsConfig"; +import { hostName, isLocalRow, localInstallCommand } from "./host-status"; export const LOCAL_DAEMON_BANNER_DISMISSED_KEY = "omp-web:local-daemon-banner-dismissed"; -const GRACE_MS = 10_000; +// Longer than the daemon's 60 s redial backoff cap, so a restarting daemon does not trip it. +export const LOCAL_DAEMON_GRACE_MS = 90_000; -/** One-time hint to install the ompweb-host service: this machine has not linked since this server started and 10 s have passed. */ +/** One-time hint to install the ompweb-host service: this machine has not linked since this server started and 90 s have passed. */ export function LocalDaemonBanner() { const { t } = useI18n(); const { hosts } = useHostRows(); - const local = hosts?.find((host) => "serverPlatform" in host); - const missing = local?.status === "offline" && local.hostVersion === null; + const local = hosts?.find(isLocalRow); + const missing = local?.daemonManaged === true && local.status === "offline" && local.hostVersion === null; const [waited, setWaited] = useState(false); // Hidden until storage is read, so a dismissed banner never flashes. const [dismissed, setDismissed] = useState(true); @@ -29,14 +31,13 @@ export function LocalDaemonBanner() { useEffect(() => { if (!missing) return; - const timer = setTimeout(() => setWaited(true), GRACE_MS); + const timer = setTimeout(() => setWaited(true), LOCAL_DAEMON_GRACE_MS); return () => { clearTimeout(timer); setWaited(false); }; }, [missing]); - if (!local || !missing || !waited || dismissed) return null; const dismiss = () => { setDismissed(true); try { @@ -45,15 +46,20 @@ export function LocalDaemonBanner() { // Dismissed for this page view only. } }; + // The live region stays mounted so screen readers announce the banner when it appears. return ( -
- {t("hostsConfig.localDaemonBanner", { host: hostName(t, local), command: localInstallCommand(local.serverPlatform) })} - +
+ {local && missing && waited && !dismissed && ( +
+
+ {t("hostsConfig.localDaemonBanner", { host: hostName(t, local) })} + +
+ +
+ )}
); } diff --git a/components/host-status.ts b/components/host-status.ts index 381470383..dc0f5855f 100644 --- a/components/host-status.ts +++ b/components/host-status.ts @@ -1,4 +1,4 @@ -import type { HostRow } from "@/lib/hosts/hub"; +import type { HostRow, LocalHostRow } from "@/lib/hosts/hub"; type Translate = (key: string, vars?: Record) => string; @@ -9,6 +9,8 @@ export function hostName(t: Translate, host: Pick): str return host.id === "local" && !host.label ? t("hostsConfig.thisMachine") : host.label; } +export const isLocalRow = (host: HostRow): host is LocalHostRow => host.id === "local"; + /** The command that installs the ompweb-host service on the server's platform (`LocalHostRow.serverPlatform`). */ export function localInstallCommand(platform: string): string { if (platform === "darwin") return "ompweb launchd install"; diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index aae933516..8f334edbd 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -124,8 +124,10 @@ or an adoption failure. - Windows (`lib/windows-service.ts`, tray): the same split, a second service for the daemon. The tray shows both states. - **Existing installs:** on first start after the upgrade, if no local daemon - links within 10 s, the web server shows a one-time banner with the exact - command to install the daemon service (it does not install services itself). + links within 90 s (longer than the daemon's 60 s redial backoff cap, so a + restart does not trip it), the web server shows a one-time banner with the + exact command to install the daemon service (it does not install services + itself). Not in dev mode, where this machine is offline by design. Until then "This machine" is offline as above. - **Upgrades:** an upgrade replaces the package for both. The web unit restarts as today. The daemon unit restarts only when `LINK_PROTOCOL_VERSION` diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index 53086757c..bf8ba5e46 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -923,6 +923,8 @@ export interface LocalHostRow { serverVersion: number; /** `process.platform` of this server: picks the daemon install command while no daemon has linked. */ serverPlatform: string; + /** False in `next dev`, where this machine runs sessions in-process and is offline by design: no install hints. */ + daemonManaged: boolean; } export type HostRow = LocalHostRow | LinkedHostRow; @@ -940,6 +942,7 @@ export function hostsSnapshot(): { hosts: HostRow[] } { hostVersion: link?.hostVersion ?? null, serverVersion: LINK_PROTOCOL_VERSION, serverPlatform: process.platform, + daemonManaged: process.env.NODE_ENV !== "development", }; return { hosts: [local, ...listHosts()] }; } diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 3768693f2..5cb062821 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -1336,8 +1336,8 @@ "hostsConfig.renameTitle": "Rename host", "hostsConfig.renameAria": "Rename {name}", "hostsConfig.localNameHint": "Leave empty to use “This machine”.", - "hostsConfig.localOfflineHint": "Start the ompweb-host service. To install it, run: {command}", - "hostsConfig.localDaemonBanner": "{host} needs the ompweb-host service. Install it with: {command}", + "hostsConfig.localOfflineHint": "Start the ompweb-host service. To install it, run:", + "hostsConfig.localDaemonBanner": "{host} needs the ompweb-host service. Install it with:", "hostsConfig.dismiss": "Dismiss", "hostsConfig.save": "Save", "hostsConfig.saving": "Saving…", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 2364257a4..06b91f636 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -1295,8 +1295,8 @@ "hostsConfig.renameTitle": "ホスト名を変更", "hostsConfig.renameAria": "{name} の名前を変更", "hostsConfig.localNameHint": "空欄にすると「このマシン」に戻ります。", - "hostsConfig.localOfflineHint": "ompweb-host サービスを起動してください。インストールするには次を実行します: {command}", - "hostsConfig.localDaemonBanner": "{host} には ompweb-host サービスが必要です。次のコマンドでインストールします: {command}", + "hostsConfig.localOfflineHint": "ompweb-host サービスを起動してください。インストールするには次を実行します:", + "hostsConfig.localDaemonBanner": "{host} には ompweb-host サービスが必要です。次のコマンドでインストールします:", "hostsConfig.dismiss": "閉じる", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index ed98b5401..b094bd2d0 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -1295,8 +1295,8 @@ "hostsConfig.renameTitle": "重命名主机", "hostsConfig.renameAria": "重命名 {name}", "hostsConfig.localNameHint": "留空则使用“本机”。", - "hostsConfig.localOfflineHint": "请启动 ompweb-host 服务。安装方法,运行:{command}", - "hostsConfig.localDaemonBanner": "{host} 需要 ompweb-host 服务。请用以下命令安装:{command}", + "hostsConfig.localOfflineHint": "请启动 ompweb-host 服务。安装方法,运行:", + "hostsConfig.localDaemonBanner": "{host} 需要 ompweb-host 服务。请用以下命令安装:", "hostsConfig.dismiss": "关闭", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", From 9e99a613a07f63bd85babd9defb2ecc96fe523a2 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 23:32:09 +0000 Subject: [PATCH 20/36] feat(service): install the ompweb-host daemon next to the web service --- CHANGELOG.md | 1 + README.md | 2 +- bin/linux-tray.js | 28 ++++-- bin/linux-tray.test.mjs | 7 ++ bin/omp-web-launchd.js | 133 ++++++++++++++++++----------- bin/omp-web-launchd.test.mjs | 33 +++++++ bin/omp-web-systemd.js | 129 +++++++++++++++++++--------- bin/omp-web-systemd.test.mjs | 24 ++++++ bin/omp-web-tray.js | 5 +- lib/windows-service.test.mjs | 27 ++++++ lib/windows-service.ts | 58 +++++++++++++ scripts/windows/install-tray.ps1 | 21 +++++ scripts/windows/omp-web-host.ps1 | 59 +++++++++++++ scripts/windows/omp-web-tray.ps1 | 27 ++++++ scripts/windows/uninstall-tray.ps1 | 8 ++ 15 files changed, 461 insertions(+), 101 deletions(-) create mode 100644 bin/omp-web-launchd.test.mjs create mode 100644 scripts/windows/omp-web-host.ps1 diff --git a/CHANGELOG.md b/CHANGELOG.md index 9e395eed8..8cf84dc25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Fixes & Improvements +- **The service installers set up the host daemon too.** `ompweb systemd install`, `ompweb-launchd install` and the Windows tray install now register `ompweb host` as a second unit (`ompweb-host`) next to the web service, restarting it after a 10 s delay so it can wait for the web server to write its host link on first install. `uninstall` and `status` cover both, and the tray menus show the daemon state. - **In-app updates work when ompweb runs as a systemd service.** The update worker ran inside the service's cgroup, so stopping the server killed the worker too: nothing was installed, the service could stay down (`Restart=on-failure` does not restart a clean SIGTERM exit), and every page load reopened the update dialog at "Stop ompweb-managed sessions". The worker now runs in its own transient scope (`systemd-run --scope`) and stops, updates and starts the unit through `systemctl`, starting it again if the install fails. - **An update whose worker died is reported as failed.** A running update whose worker process is gone, or whose lease has expired, now becomes a failed attempt the dialog can show and clean up, instead of waiting forever. - **The Provider Usage header stays put while its list scrolls.** Scrolling a long provider list in the sidebar also scrolled the section header (title, window toggle, refresh) out of view, on desktop and mobile. Only the list scrolls now. diff --git a/README.md b/README.md index 348a77ef9..861d40268 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ ompweb --no-open # Don't auto-open the browser ompweb --install-tray # Install Windows System Tray service & Desktop shortcuts ompweb --uninstall-tray # Uninstall Windows System Tray service & shortcuts ompweb --tray # Start background System Tray manager -ompweb systemd install # Install Linux systemd user service +ompweb systemd install # Install Linux systemd user services (web + ompweb-host daemon) ompweb --help # Show help ompweb --version # Show version ``` diff --git a/bin/linux-tray.js b/bin/linux-tray.js index f34c978cc..69c438618 100644 --- a/bin/linux-tray.js +++ b/bin/linux-tray.js @@ -272,6 +272,7 @@ const ITEM_PATH = "/StatusNotifierItem"; const MENU_PATH = "/MenuBar"; const TRAY_PATH = "/ompweb/tray"; const SERVICE_UNIT = "ompweb.service"; +const DAEMON_UNIT = "ompweb-host.service"; const AUTOSTART_FILE = path.join(os.homedir(), ".config", "autostart", "ompweb-tray.desktop"); const ICON_DIR = path.join(os.homedir(), ".local", "share", "icons", "hicolor", "scalable", "apps"); const POLL_INTERVAL_MS = 5000; @@ -450,10 +451,12 @@ function readTrayConfig(overrides = {}, env = process.env, home = os.homedir()) // Menu item table. `separator` items render as dividers; `checkmark` items // carry a toggle state; `disabled` items are inert status rows. -function buildMenuItems({ running, version, autostart, hasService, exposed, hasDialogTool }) { +// `daemon` is "running", "stopped" or "not installed" (the ompweb-host unit). +function buildMenuItems({ running, version, autostart, hasService, exposed, hasDialogTool, daemon = "not installed" }) { return [ { id: 1, label: `ompweb (v${version})`, enabled: false }, { id: 2, label: running ? " Status: Running" : " Status: Stopped", enabled: false }, + { id: 19, label: ` Daemon: ${daemon[0].toUpperCase()}${daemon.slice(1)}`, enabled: false }, { id: 3, separator: true }, { id: 4, label: "Open in Browser", action: "open" }, { id: 5, label: "Copy Web URL", action: "copy" }, @@ -665,9 +668,18 @@ function systemctlUser(args) { }; } -function serviceInstalled() { +function unitInstalled(unit) { const dir = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"); - return fs.existsSync(path.join(dir, "systemd", "user", SERVICE_UNIT)); + return fs.existsSync(path.join(dir, "systemd", "user", unit)); +} + +function serviceInstalled() { + return unitInstalled(SERVICE_UNIT); +} + +function daemonState() { + if (!unitInstalled(DAEMON_UNIT)) return "not installed"; + return systemctlUser(["is-active", DAEMON_UNIT]).stdout === "active" ? "running" : "stopped"; } function openUrl(url) { @@ -691,7 +703,7 @@ function viewLogs() { const resolved = candidateBinPath(terminal); if (!resolved) return false; const prefix = terminalPrefix(terminal).slice(1); - const child = spawn(resolved, [...prefix, `journalctl --user -u ompweb -f`], { + const child = spawn(resolved, [...prefix, `journalctl --user -u ompweb -u ompweb-host -f`], { stdio: "ignore", detached: true, env: process.env, @@ -730,6 +742,7 @@ function createTrayState(config, { log = console.log } = {}) { port: config.port, hostname: config.hostname, version: readPackageVersion(), + daemon: daemonState(), }; state.menuItems = () => @@ -740,6 +753,7 @@ function createTrayState(config, { log = console.log } = {}) { hasService: state.hasService, exposed: state.exposed, hasDialogTool: state.dialogTool !== null, + daemon: state.daemon, }); // Re-read the env file after config changes and refresh icon + menu. @@ -926,11 +940,13 @@ function createTrayState(config, { log = console.log } = {}) { } const hadService = state.hasService; state.hasService = serviceInstalled(); + const hadDaemon = state.daemon; + state.daemon = daemonState(); if (running !== wasRunning) { state.running = running; state.refreshIcon(); state.refreshMenu(); - } else if (state.hasService !== hadService) { + } else if (state.hasService !== hadService || state.daemon !== hadDaemon) { state.refreshMenu(); } }; @@ -1094,6 +1110,7 @@ async function readStatus(overrides) { trayRunning, serviceInstalled: serviceInstalled(), serviceRunning, + daemon: daemonState(), autostart, port: config.port, hostname: config.hostname, @@ -1268,6 +1285,7 @@ async function runCli(argv = process.argv.slice(2)) { console.log(`=== ompweb Linux tray status ===`); console.log(` Tray running : ${status.trayRunning ? "Yes" : "No"}`); console.log(` Service unit : ${status.serviceInstalled ? "installed" : "not installed"} (${status.serviceRunning ? "active" : "inactive"})`); + console.log(` Host daemon : ${status.daemon}`); console.log(` Autostart : ${status.autostart ? `enabled (${status.autostartFile})` : "disabled"}`); console.log(` Live URL : ${status.serviceUrl}`); } diff --git a/bin/linux-tray.test.mjs b/bin/linux-tray.test.mjs index 2e63398c1..a76deef89 100644 --- a/bin/linux-tray.test.mjs +++ b/bin/linux-tray.test.mjs @@ -108,6 +108,13 @@ test("buildMenuItems reflects running state and service availability", () => { assert.equal(itemById(noDialog, 13).enabled, false); assert.equal(itemById(noDialog, 14).enabled, false); + // The ompweb-host daemon state sits under the web status. + assert.equal(itemById(running, 19).label, " Daemon: Not installed"); + assert.equal(itemById(running, 19).enabled, false); + const withDaemon = buildMenuItems({ running: true, version: "0.4.2", autostart: false, hasService: true, exposed: false, hasDialogTool: true, daemon: "running" }); + assert.equal(itemById(withDaemon, 19).label, " Daemon: Running"); + assert.equal(withDaemon.findIndex((item) => item.id === 19), withDaemon.findIndex((item) => item.id === 2) + 1); + // Inert rows and separators. assert.equal(itemById(running, 1).enabled, false); assert.ok(itemById(running, 3).separator); diff --git a/bin/omp-web-launchd.js b/bin/omp-web-launchd.js index 906dbd9ef..cdaf9fe44 100644 --- a/bin/omp-web-launchd.js +++ b/bin/omp-web-launchd.js @@ -22,8 +22,11 @@ const path = require("node:path"); const { resolvePasswordHash } = require("./omp-web-hash-password"); const LABEL = "com.kahme247.ompweb"; +// The host daemon links this machine to an omp-web (`ompweb host`); it runs next to the web agent. +const HOST_LABEL = "com.kahme247.ompweb-host"; const HOME = os.homedir(); const PLIST = path.join(HOME, "Library", "LaunchAgents", `${LABEL}.plist`); +const HOST_PLIST = path.join(HOME, "Library", "LaunchAgents", `${HOST_LABEL}.plist`); const LOG_DIR = path.join(HOME, "Library", "Logs", "ompweb"); const DOMAIN = `gui/${process.getuid?.() ?? 0}`; @@ -61,6 +64,35 @@ function launchctl(args, { ignoreFailure = false } = {}) { return result.stdout ?? ""; } +// One launch agent; `throttleInterval` (seconds) spaces out KeepAlive restarts. +function buildPlist({ label, args, env, logName, throttleInterval }) { + const argsXml = args.map((arg) => ` ${xmlEscape(arg)}`).join("\n"); + const envXml = Object.entries(env) + .map(([key, value]) => ` ${xmlEscape(key)}${xmlEscape(value)}`) + .join("\n"); + return ` + + + + Label${label} + ProgramArguments + +${argsXml} + + EnvironmentVariables + +${envXml} + + WorkingDirectory${xmlEscape(HOME)} + RunAtLoad + KeepAlive${throttleInterval ? `\n ThrottleInterval${throttleInterval}` : ""} + StandardOutPath${xmlEscape(path.join(LOG_DIR, `${logName}.log`))} + StandardErrorPath${xmlEscape(path.join(LOG_DIR, `${logName}.err.log`))} + + +`; +} + function install(pkgArg) { const nodeBin = process.execPath; const siblingNpx = path.join(path.dirname(nodeBin), "npx"); @@ -118,73 +150,72 @@ function install(pkgArg) { ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; - const envXml = Object.entries(env) - .map(([key, value]) => ` ${xmlEscape(key)}${xmlEscape(value)}`) - .join("\n"); - - const plist = ` - - - - Label${LABEL} - ProgramArguments - - ${xmlEscape(npxBin)} - --yes - ${xmlEscape(pkg)} - - EnvironmentVariables - -${envXml} - - WorkingDirectory${xmlEscape(HOME)} - RunAtLoad - KeepAlive - StandardOutPath${xmlEscape(path.join(LOG_DIR, "ompweb.log"))} - StandardErrorPath${xmlEscape(path.join(LOG_DIR, "ompweb.err.log"))} - - -`; + const web = buildPlist({ label: LABEL, args: [npxBin, "--yes", pkg], env, logName: "ompweb" }); + // The daemon needs the same agent dir (host.json) and PATH, not the web password. + const hostEnv = { PATH: svcPath, ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}) }; + const host = buildPlist({ + label: HOST_LABEL, + args: [npxBin, "--yes", pkg, "host"], + env: hostEnv, + logName: "ompweb-host", + // host.json does not exist until the web server first starts; the daemon exits until then. + throttleInterval: 10, + }); fs.mkdirSync(LOG_DIR, { recursive: true }); fs.mkdirSync(path.dirname(PLIST), { recursive: true }); - fs.writeFileSync(PLIST, plist, { mode: 0o600 }); - fs.chmodSync(PLIST, 0o600); - - launchctl(["bootout", `${DOMAIN}/${LABEL}`], { ignoreFailure: true }); - launchctl(["bootstrap", DOMAIN, PLIST]); + for (const [file, xml, label] of [[PLIST, web, LABEL], [HOST_PLIST, host, HOST_LABEL]]) { + fs.writeFileSync(file, xml, { mode: 0o600 }); + fs.chmodSync(file, 0o600); + launchctl(["bootout", `${DOMAIN}/${label}`], { ignoreFailure: true }); + launchctl(["bootstrap", DOMAIN, file]); + } console.log(`installed: ${PLIST}`); + console.log(`installed: ${HOST_PLIST}`); console.log(`package: ${pkg} (via npx --yes)`); console.log(`url: http://${hostname}:${port}`); - console.log(`logs: ${path.join(LOG_DIR, "ompweb.log")}`); + console.log(`logs: ${path.join(LOG_DIR, "ompweb.log")}, ${path.join(LOG_DIR, "ompweb-host.log")}`); if (passwordHash) console.log("note: the password hash is stored in the plist (mode 600)"); } function uninstall() { - launchctl(["bootout", `${DOMAIN}/${LABEL}`], { ignoreFailure: true }); - fs.rmSync(PLIST, { force: true }); - console.log(`uninstalled: ${LABEL}`); + for (const [file, label] of [[PLIST, LABEL], [HOST_PLIST, HOST_LABEL]]) { + launchctl(["bootout", `${DOMAIN}/${label}`], { ignoreFailure: true }); + fs.rmSync(file, { force: true }); + console.log(`uninstalled: ${label}`); + } } function status() { - const result = spawnSync("launchctl", ["print", `${DOMAIN}/${LABEL}`], { encoding: "utf8" }); - if (result.status === 0) { - const lines = (result.stdout ?? "").split("\n").filter((line) => /\b(state|pid|last exit)\b/.test(line)); - console.log(lines.join("\n") || (result.stdout ?? "").trim()); - return; + let loaded = false; + for (const label of [LABEL, HOST_LABEL]) { + const result = spawnSync("launchctl", ["print", `${DOMAIN}/${label}`], { encoding: "utf8" }); + if (result.status === 0) { + loaded ||= label === LABEL; + const lines = (result.stdout ?? "").split("\n").filter((line) => /\b(state|pid|last exit)\b/.test(line)); + console.log(`${label}:\n${lines.join("\n") || (result.stdout ?? "").trim()}`); + } else { + console.log(`not loaded: ${label}`); + } } - console.log(`not loaded: ${LABEL}`); - process.exit(1); + // Exit status stays the web agent's: scripts that polled it before keep working. + if (!loaded) process.exit(1); } -if (process.platform !== "darwin") fail("launchd services are macOS-only"); +function main() { + if (process.platform !== "darwin") fail("launchd services are macOS-only"); -const command = process.argv[2] ?? "install"; -if (command === "install") install(process.argv[3]); -else if (command === "uninstall") uninstall(); -else if (command === "status") status(); -else { - console.error("usage: ompweb-launchd [install [package-spec]|uninstall|status]"); - process.exit(2); + const command = process.argv[2] ?? "install"; + if (command === "install") install(process.argv[3]); + else if (command === "uninstall") uninstall(); + else if (command === "status") status(); + else { + console.error("usage: ompweb-launchd [install [package-spec]|uninstall|status]"); + process.exit(2); + } } + +if (require.main === module) main(); + +module.exports = { HOST_LABEL, LABEL, buildPlist }; diff --git a/bin/omp-web-launchd.test.mjs b/bin/omp-web-launchd.test.mjs new file mode 100644 index 000000000..f59bc16ce --- /dev/null +++ b/bin/omp-web-launchd.test.mjs @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { createRequire } from "node:module"; +import test from "node:test"; + +const require = createRequire(import.meta.url); +const { HOST_LABEL, LABEL, buildPlist } = require("./omp-web-launchd.js"); + +const env = { PATH: "/usr/bin", PI_CODING_AGENT_DIR: "/Users/u/agent" }; + +test("the host daemon plist runs `ompweb host`, restarts with KeepAlive, and is throttled", () => { + const plist = buildPlist({ + label: HOST_LABEL, + args: ["/usr/local/bin/npx", "--yes", "@kahme247/ompweb@latest", "host"], + env, + logName: "ompweb-host", + throttleInterval: 10, + }); + assert.equal(HOST_LABEL, "com.kahme247.ompweb-host"); + assert.match(plist, /Label<\/key>com\.kahme247\.ompweb-host<\/string>/); + assert.match(plist, /@kahme247\/ompweb@latest<\/string>\n host<\/string>\n <\/array>/); + assert.match(plist, /KeepAlive<\/key>/); + assert.match(plist, /ThrottleInterval<\/key>10<\/integer>/); + assert.match(plist, /PI_CODING_AGENT_DIR<\/key>\/Users\/u\/agent<\/string>/); + assert.match(plist, /ompweb-host\.log<\/string>/); +}); + +test("the web plist keeps its arguments and has no throttle", () => { + const plist = buildPlist({ label: LABEL, args: ["/usr/local/bin/npx", "--yes", "pkg & co"], env, logName: "ompweb" }); + assert.match(plist, /pkg & co<\/string>\n <\/array>/); + assert.match(plist, /KeepAlive<\/key>/); + assert.doesNotMatch(plist, /ThrottleInterval/); + assert.doesNotMatch(plist, /host<\/string>/); +}); diff --git a/bin/omp-web-systemd.js b/bin/omp-web-systemd.js index 9e267d01d..88e5df84c 100644 --- a/bin/omp-web-systemd.js +++ b/bin/omp-web-systemd.js @@ -34,6 +34,11 @@ const UNIT = `${UNIT_NAME}.service`; const HOME = os.homedir(); const UNIT_DIR = path.join(HOME, ".config", "systemd", "user"); const UNIT_PATH = path.join(UNIT_DIR, UNIT); +// The host daemon links this machine to an omp-web (`ompweb host`); it runs next to the web unit. +const HOST_UNIT_NAME = "ompweb-host"; +const HOST_UNIT = `${HOST_UNIT_NAME}.service`; +const HOST_UNIT_PATH = path.join(UNIT_DIR, HOST_UNIT); +const UNITS = [UNIT, HOST_UNIT]; const ENV_PATH = getServiceEnvPath(); const DEFAULT_PORT = "30177"; const DEFAULT_HOSTNAME = "127.0.0.1"; @@ -42,12 +47,12 @@ function printHelp() { console.log(`Usage: ompweb-systemd [command] [options] Commands: - install Install the user service, create its env file, and enable it - uninstall Stop the service and remove the unit file - start Start the service - stop Stop the service - restart Restart the service - status Show service status (default when no command is given) + install Install the web and host-daemon user services, create the env file, and enable them + uninstall Stop both services and remove their unit files + start Start both services + stop Stop both services + restart Restart both services + status Show both services' status (default when no command is given) open Open the web service in the default browser help Show this help @@ -218,8 +223,10 @@ function validateHostname(value) { } // Build the unit file text. Runtime settings belong in EnvironmentFile so the -// tray or an editor can change them without reinstalling the unit. -function buildUnit({ ompwebBin, env: extraEnv = {}, home = HOME, envPath = getServiceEnvPath(home) }) { +// tray or an editor can change them without reinstalling the unit. The web and +// host units share the env file: same user, same HOME and PI_CODING_AGENT_DIR, +// so both read the same /omp-web/host.json. +function buildUnitText({ description, execArgs, restart, ompwebBin, env: extraEnv, home, envPath }) { const ompBin = extraEnv.OMP_WEB_OMP_BIN ?? null; const interpreterDir = ompBin ? launcherInterpreterDir(ompBin) : null; const pathDirs = [ @@ -238,27 +245,47 @@ function buildUnit({ ompwebBin, env: extraEnv = {}, home = HOME, envPath = getSe return `# Generated by ompweb-systemd — edits are overwritten on reinstall. [Unit] -Description=ompweb web service (oh-my-pi web UI) +Description=${description} Documentation=https://github.com/kahme247/ompweb#readme Wants=network-online.target After=network-online.target -StartLimitIntervalSec=60 -StartLimitBurst=5 - +${restart.startLimit} [Service] Type=simple WorkingDirectory=%h -ExecStart=${formatExecStart(ompwebBin)} +ExecStart=${formatExecStart(ompwebBin)}${execArgs} Environment=${environmentLine([["PATH", pathDirs.join(path.delimiter)]])} EnvironmentFile=${escapeUnitPath(envPath)} -Restart=on-failure -RestartSec=3 +Restart=${restart.policy} +RestartSec=${restart.delay} [Install] WantedBy=default.target `; } +function buildUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { + return buildUnitText({ + description: "ompweb web service (oh-my-pi web UI)", + execArgs: "", + restart: { policy: "on-failure", delay: 3, startLimit: "StartLimitIntervalSec=60\nStartLimitBurst=5\n" }, + ompwebBin, env, home, envPath, + }); +} + +// The daemon exits when host.json does not exist yet (first install: the web +// server writes it at startup) and when the server revokes or outdates its +// token. Restart=always with a 10 s delay covers all of those, and +// StartLimitIntervalSec=0 keeps systemd from giving up while it waits. +function buildHostUnit({ ompwebBin, env = {}, home = HOME, envPath = getServiceEnvPath(home) }) { + return buildUnitText({ + description: "ompweb host daemon (links this machine to an ompweb server)", + execArgs: " host", + restart: { policy: "always", delay: 10, startLimit: "StartLimitIntervalSec=0\n" }, + ompwebBin, env, home, envPath, + }); +} + function systemctl(args, { ignoreFailure = false } = {}) { const result = spawnSync("systemctl", ["--user", ...args], { encoding: "utf8" }); if (result.error) { @@ -316,12 +343,12 @@ function install(options = {}) { } const agentDir = process.env.PI_CODING_AGENT_DIR?.replace(/^~(?=\/|$)/, HOME); const envPath = getServiceEnvPath(); - const unit = buildUnit({ + const unitOptions = { ompwebBin, env: ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}, home: HOME, envPath, - }); + }; // This is intentionally created during install. It is the source of truth // read by systemd on every start/restart, and is safe to edit by hand. @@ -337,29 +364,33 @@ function install(options = {}) { ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }, envPath); - const wasActive = systemdQuery(["is-active", "--quiet", UNIT]).ok; + const wasActive = Object.fromEntries(UNITS.map((unit) => [unit, systemdQuery(["is-active", "--quiet", unit]).ok])); fs.mkdirSync(UNIT_DIR, { recursive: true }); - fs.writeFileSync(UNIT_PATH, unit, { mode: 0o600 }); - fs.chmodSync(UNIT_PATH, 0o600); + for (const [unitPath, text] of [[UNIT_PATH, buildUnit(unitOptions)], [HOST_UNIT_PATH, buildHostUnit(unitOptions)]]) { + fs.writeFileSync(unitPath, text, { mode: 0o600 }); + fs.chmodSync(unitPath, 0o600); + } systemctl(["daemon-reload"]); - if (options.autostart !== false) systemctl(["enable", "--now", UNIT]); - else systemctl(["start", UNIT], { ignoreFailure: true }); - if (wasActive) systemctl(["restart", UNIT]); + if (options.autostart !== false) systemctl(["enable", "--now", ...UNITS]); + else systemctl(["start", ...UNITS], { ignoreFailure: true }); + for (const unit of UNITS) if (wasActive[unit]) systemctl(["restart", unit]); console.log(`installed: ${UNIT_PATH}`); + console.log(`installed: ${HOST_UNIT_PATH}`); console.log(`binary: ${ompwebBin}`); console.log(`config: ${envPath} (port/hostname/password — no reinstall needed)`); console.log(`url: http://${hostname}:${port}`); - console.log(`logs: journalctl --user -u ${UNIT_NAME} -f`); + console.log(`logs: journalctl --user -u ${UNIT_NAME} -u ${HOST_UNIT_NAME} -f`); if (options.autostart === false) console.log("note: service is not enabled at login (--no-autostart)"); if (passwordHash) console.log("note: password hash is stored in the env file (mode 600)"); console.log("note: for headless servers, run: loginctl enable-linger $USER"); } function uninstall(options = {}) { - systemctl(["disable", "--now", UNIT], { ignoreFailure: true }); + systemctl(["disable", "--now", ...UNITS], { ignoreFailure: true }); fs.rmSync(UNIT_PATH, { force: true }); + fs.rmSync(HOST_UNIT_PATH, { force: true }); systemctl(["daemon-reload"], { ignoreFailure: true }); if (options.cleanConfig) { const legacyConfig = path.join(HOME, ".omp", "agent", "web-service.json"); @@ -368,45 +399,53 @@ function uninstall(options = {}) { fs.rmSync(ENV_PATH, { force: true }); console.log(`removed: ${ENV_PATH}`); } - console.log(`uninstalled: ${UNIT_NAME}`); + console.log(`uninstalled: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); } function start() { - systemctl(["start", UNIT]); - console.log(`started: ${UNIT_NAME}`); + systemctl(["start", ...UNITS]); + console.log(`started: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); } function stop() { - systemctl(["stop", UNIT]); - console.log(`stopped: ${UNIT_NAME}`); + systemctl(["stop", ...UNITS]); + console.log(`stopped: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); } function restart() { - systemctl(["restart", UNIT]); - console.log(`restarted: ${UNIT_NAME}`); + systemctl(["restart", ...UNITS]); + console.log(`restarted: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); +} + +function readUnitStatus(unit, unitPath) { + const active = systemdQuery(["is-active", unit]); + const enabled = systemdQuery(["is-enabled", unit]); + const pid = systemdQuery(["show", "--property", "MainPID", "--value", unit]); + return { + unit, + unitPath, + isInstalled: fs.existsSync(unitPath), + isActive: active.ok && active.stdout === "active", + isEnabled: enabled.ok, + pid: Number.parseInt(pid.stdout, 10) || null, + }; } function readStatus() { - const active = systemdQuery(["is-active", UNIT]); - const enabled = systemdQuery(["is-enabled", UNIT]); - const pid = systemdQuery(["show", "--property", "MainPID", "--value", UNIT]); + const web = readUnitStatus(UNIT, UNIT_PATH); const envConfig = readServiceEnv(); const configuredPort = Number.parseInt(envConfig.PORT ?? process.env.PORT ?? DEFAULT_PORT, 10); const port = Number.isInteger(configuredPort) ? configuredPort : Number(DEFAULT_PORT); const hostname = envConfig.OMP_WEB_HOSTNAME ?? process.env.OMP_WEB_HOSTNAME ?? DEFAULT_HOSTNAME; return { isLinux: process.platform === "linux", - unit: UNIT, - unitPath: UNIT_PATH, + ...web, envFile: ENV_PATH, - isInstalled: fs.existsSync(UNIT_PATH), - isActive: active.ok && active.stdout === "active", - isEnabled: enabled.ok, - pid: Number.parseInt(pid.stdout, 10) || null, + daemon: readUnitStatus(HOST_UNIT, HOST_UNIT_PATH), port, hostname, serviceUrl: `http://${hostname}:${port}`, - logCommand: `journalctl --user -u ${UNIT_NAME} -f`, + logCommand: `journalctl --user -u ${UNIT_NAME} -u ${HOST_UNIT_NAME} -f`, }; } @@ -421,6 +460,9 @@ function printStatus(asJson) { console.log(` Version : v${readPackageVersion()}`); console.log(` Active : ${status.isActive ? `Yes (pid ${status.pid})` : "No"}`); console.log(` Start at login: ${status.isEnabled ? "Enabled" : "Disabled"}`); + const { daemon } = status; + console.log(` Host daemon : ${daemon.unit} (${daemon.isInstalled ? daemon.unitPath : "not installed"})`); + console.log(` Daemon active : ${daemon.isActive ? `Yes (pid ${daemon.pid})` : "No"}`); console.log(` Live URL : ${status.serviceUrl}`); console.log(` Config : ${status.envFile}`); console.log(` Logs : ${status.logCommand}`); @@ -537,8 +579,11 @@ module.exports = { DEFAULT_HOSTNAME, DEFAULT_PORT, ENV_PATH, + HOST_UNIT, + HOST_UNIT_PATH, UNIT, UNIT_PATH, + buildHostUnit, buildUnit, escapeUnitPath, escapeUnitValue, diff --git a/bin/omp-web-systemd.test.mjs b/bin/omp-web-systemd.test.mjs index 12d552d42..c9fa77b89 100644 --- a/bin/omp-web-systemd.test.mjs +++ b/bin/omp-web-systemd.test.mjs @@ -8,6 +8,7 @@ import test from "node:test"; const require = createRequire(import.meta.url); const { + buildHostUnit, buildUnit, escapeUnitPath, escapeUnitValue, @@ -79,6 +80,26 @@ test("buildUnit points at the generated env file and keeps runtime settings out } }); +test("buildHostUnit runs `ompweb host` with the web unit's env file and never gives up restarting", () => { + const options = { + ompwebBin: "/usr/local/bin/ompweb", + env: { OMP_WEB_OMP_BIN: "/home/u/.bun/bin/omp" }, + home: "/home/u", + envPath: "/home/u/.omp/agent/web-service.env", + }; + const unit = buildHostUnit(options); + + assert.match(unit, /^ExecStart=\/usr\/local\/bin\/ompweb host$/m); + assert.match(unit, /EnvironmentFile=\/home\/u\/\.omp\/agent\/web-service\.env/); + assert.match(unit, /^Restart=always$/m); + assert.match(unit, /^RestartSec=10$/m); + // No host.json on first install makes the daemon exit; the start limit must not turn that into a permanent failure. + assert.match(unit, /^StartLimitIntervalSec=0$/m); + assert.doesNotMatch(unit, /StartLimitBurst/); + assert.match(unit, /WantedBy=default\.target/); + assert.equal(buildHostUnit({ ...options, ompwebBin: "/opt/my tools/ompweb" }).match(/^ExecStart=(.*)$/m)[1], '"/opt/my tools/ompweb" host'); +}); + test("buildUnit adds the launcher interpreter dir for Bun/npm installs of omp", () => { const dir = mkdtempSync(path.join(tmpdir(), "ompweb-systemd-bun-")); try { @@ -197,6 +218,9 @@ test("install creates the env file and unit with LAN settings", { skip: process. OMP_WEB_TRUSTED_HEADER_SHA256: "a".repeat(64), }); assert.match(readFileSync(unitPath, "utf8"), /EnvironmentFile=.*web-service\.env/); + const hostUnit = readFileSync(path.join(path.dirname(unitPath), "ompweb-host.service"), "utf8"); + assert.match(hostUnit, /^ExecStart=.*\/ompweb host$/m); + assert.match(hostUnit, /EnvironmentFile=.*web-service\.env/); assert.match(result.stdout, /config:.*web-service\.env/); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/bin/omp-web-tray.js b/bin/omp-web-tray.js index 8ca3faf71..e86ac07cb 100644 --- a/bin/omp-web-tray.js +++ b/bin/omp-web-tray.js @@ -23,8 +23,8 @@ Platform notes: for the systemd user service this tray manages Commands: - --install, install Install system tray shortcuts and background service - --uninstall, uninstall Uninstall system tray shortcuts and background service + --install, install Install system tray shortcuts, the background service and the host daemon + --uninstall, uninstall Uninstall system tray shortcuts, the background service and the host daemon --start, start Start the background system tray manager --stop, stop Stop running background system tray and server processes --restart, restart Restart running background system tray and server @@ -206,6 +206,7 @@ async function runCli(argv = process.argv.slice(2)) { console.log(` Version : v${status.version}`); console.log(` Installed : ${status.isInstalled ? "Yes" : "No"}`); console.log(` Running : ${status.isRunning ? "Yes (Tray Active)" : "No (Stopped)"}`); + console.log(` Host daemon : ${status.daemon.isInstalled ? (status.daemon.isRunning ? "Running" : "Stopped") : "Not installed"}`); console.log(` Live URL : ${status.serviceUrl}`); console.log(` Config Mode : ${status.mode} (Port: ${status.port}, Host: ${status.hostname})`); console.log(` Start with Windows: ${status.autostart ? "Enabled" : "Disabled"}`); diff --git a/lib/windows-service.test.mjs b/lib/windows-service.test.mjs index 114b7a42a..bc31a3abf 100644 --- a/lib/windows-service.test.mjs +++ b/lib/windows-service.test.mjs @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; import path from "node:path"; +import { existsSync, readFileSync } from "node:fs"; import { createJiti } from "jiti"; const jiti = createJiti(import.meta.url); @@ -13,6 +14,8 @@ const { getWebServiceLogPath, getWindowsShortcutPaths, getWebServiceStatus, + getWindowsServiceDefinitions, + getHostDaemonStatus, getAppVersion, getRepoRoot, getSystemRoot, @@ -108,6 +111,30 @@ test("getWebServiceStatus returns a complete status object", async () => { assert.equal(typeof status.serviceUrl, "string"); assert.equal(typeof status.version, "string"); assert.ok(status.serviceUrl.startsWith("http://")); + assert.equal(typeof status.daemon.isInstalled, "boolean"); + assert.equal(typeof status.daemon.isRunning, "boolean"); +}); + +test("getWindowsServiceDefinitions names the web service and the host daemon, and the installers register both", () => { + const root = path.resolve(import.meta.dirname, ".."); + const { web, host } = getWindowsServiceDefinitions(root); + assert.equal(web.name, "omp-web"); + assert.equal(host.name, "omp-web-host"); + for (const { script } of [web, host]) assert.ok(existsSync(script), script); + assert.equal(path.basename(host.script), "omp-web-host.ps1"); + const installer = readFileSync(path.join(root, "scripts", "windows", "install-tray.ps1"), "utf8"); + const uninstaller = readFileSync(path.join(root, "scripts", "windows", "uninstall-tray.ps1"), "utf8"); + for (const { name, script } of [web, host]) { + assert.ok(installer.includes(`"${name}"`), `install-tray.ps1 registers ${name}`); + assert.ok(installer.includes(path.basename(script)), `install-tray.ps1 runs ${path.basename(script)}`); + assert.ok(uninstaller.includes(`"${name}"`), `uninstall-tray.ps1 removes ${name}`); + } + assert.match(readFileSync(host.script, "utf8"), /\$LauncherJs`" host >>/); +}); + +test("getHostDaemonStatus reports no daemon off Windows", async () => { + if (process.platform === "win32") return; + assert.deepEqual(await getHostDaemonStatus(), { isInstalled: false, isRunning: false }); }); test("getRepoRoot resolves valid repository directory containing package.json", () => { diff --git a/lib/windows-service.ts b/lib/windows-service.ts index ec8d78301..e927b0554 100644 --- a/lib/windows-service.ts +++ b/lib/windows-service.ts @@ -33,6 +33,28 @@ export interface WebServiceStatus { configFile: string; serviceUrl: string; version: string; + /** The `ompweb host` daemon task that runs next to the web service. */ + daemon: HostDaemonStatus; +} + +export interface HostDaemonStatus { + isInstalled: boolean; + isRunning: boolean; +} + +export interface WindowsServiceDefinition { + /** Scheduled Task name (scripts/windows/install-tray.ps1 registers it). */ + name: string; + /** Supervisor script the task runs. */ + script: string; +} + +/** The two units `ompweb-tray install` sets up: the web service and the `ompweb host` daemon. */ +export function getWindowsServiceDefinitions(repoRoot = getRepoRoot()): { web: WindowsServiceDefinition; host: WindowsServiceDefinition } { + return { + web: { name: "omp-web", script: path.join(repoRoot, "scripts", "windows", "omp-web-service.ps1") }, + host: { name: "omp-web-host", script: path.join(repoRoot, "scripts", "windows", "omp-web-host.ps1") }, + }; } export const DEFAULT_WEB_SERVICE_CONFIG: WebServiceConfig = { @@ -244,6 +266,7 @@ const TRAY_RUNNING_TTL_MS = 3000; export function invalidateTrayRunningCache(): void { trayRunningCache = null; + hostDaemonCache = null; } export async function isTrayProcessRunning(): Promise { @@ -276,6 +299,38 @@ export async function isTrayProcessRunning(): Promise { } } +let hostDaemonCache: { status: HostDaemonStatus; expiresAt: number } | null = null; + +export async function getHostDaemonStatus(): Promise { + if (process.platform !== "win32") return { isInstalled: false, isRunning: false }; + if (hostDaemonCache && hostDaemonCache.expiresAt > Date.now()) return hostDaemonCache.status; + const env = getWindowsExecutionEnv(); + const { name } = getWindowsServiceDefinitions().host; + const isInstalled = await execFileAsync("schtasks.exe", ["/query", "/tn", name], { timeout: 3000, env, windowsHide: true }).then(() => true, () => false); + let isRunning = false; + if (isInstalled) { + try { + const { stdout } = await execFileAsync( + resolvePowerShellBin(), + [ + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-Command", + '(Get-CimInstance Win32_Process -Filter "Name LIKE \'%powershell%\' OR Name LIKE \'%pwsh%\'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -like \'*omp-web-host.ps1*\' } | Measure-Object).Count', + ], + { timeout: 4000, env, windowsHide: true }, + ); + isRunning = parseInt(stdout.trim(), 10) > 0; + } catch { + isRunning = false; + } + } + const status = { isInstalled, isRunning }; + hostDaemonCache = { status, expiresAt: Date.now() + TRAY_RUNNING_TTL_MS }; + return status; +} + export function getAppVersion(): string { return packageJson.version || "0.0.0"; } @@ -333,6 +388,7 @@ export async function getWebServiceStatus(): Promise { configFile: getWebServiceConfigPath(), serviceUrl, version: getAppVersion(), + daemon: await getHostDaemonStatus(), }; } @@ -482,6 +538,8 @@ export async function startTrayService(options: { openBrowser?: boolean } = {}): await execFileAsync("schtasks.exe", ["/query", "/tn", "omp-web"], { timeout: 3000, env: getWindowsExecutionEnv(), windowsHide: true }); // Task exists, try to run it (ONLOGON tasks can be triggered via /run even without logon trigger). await execFileAsync("schtasks.exe", ["/run", "/tn", "omp-web"], { timeout: 5000, env: getWindowsExecutionEnv(), windowsHide: true }); + // The daemon follows the web service; its supervisor exits at once when one is already running. + await execFileAsync("schtasks.exe", ["/run", "/tn", getWindowsServiceDefinitions().host.name], { timeout: 5000, env: getWindowsExecutionEnv(), windowsHide: true }).catch(() => undefined); invalidateTrayRunningCache(); // Optionally open browser if requested. if (options.openBrowser) { diff --git a/scripts/windows/install-tray.ps1 b/scripts/windows/install-tray.ps1 index c1c8a665f..06ebd374c 100644 --- a/scripts/windows/install-tray.ps1 +++ b/scripts/windows/install-tray.ps1 @@ -267,6 +267,27 @@ if (!$NoAutostart -and (Test-Path $ServicePs1)) { try { schtasks /delete /tn "omp-web" /f 2>$null | Out-Null } catch { } } +# The host daemon (`ompweb host`) runs next to the web service. It starts at logon like the web +# service; with -NoAutostart it is still registered and started, but not at logon. +$HostPs1 = Join-Path $RepoRoot "scripts\windows\omp-web-host.ps1" +if (Test-Path $HostPs1) { + try { + $hostArg = "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$HostPs1`"" + $hostAction = New-ScheduledTaskAction -Execute "powershell.exe" -Argument $hostArg + $hostTrigger = New-ScheduledTaskTrigger -AtLogOn -User "$env:USERDOMAIN\$env:USERNAME" + $hostPrincipal = New-ScheduledTaskPrincipal -UserId "$env:USERDOMAIN\$env:USERNAME" -LogonType Interactive -RunLevel Limited + # omp-web-host.ps1 restarts the daemon itself; the scheduler only has to survive battery and a missed logon. + $hostSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -ExecutionTimeLimit ([TimeSpan]::Zero) + $hostTask = @{ TaskName = "omp-web-host"; Action = $hostAction; Principal = $hostPrincipal; Settings = $hostSettings; Force = $true; ErrorAction = "Stop" } + if (!$NoAutostart) { $hostTask.Trigger = $hostTrigger } + Register-ScheduledTask @hostTask | Out-Null + Log-Message " [OK] Scheduled Task created: omp-web-host" + schtasks.exe /run /tn "omp-web-host" 2>$null | Out-Null + } catch { + Log-Message " [WARN] Failed to create the omp-web-host Scheduled Task: $($_.Exception.Message)" + } +} + # ----------------------------------------------------------------------------- # 4. Optional Immediate Launch # ----------------------------------------------------------------------------- diff --git a/scripts/windows/omp-web-host.ps1 b/scripts/windows/omp-web-host.ps1 new file mode 100644 index 000000000..3d2494834 --- /dev/null +++ b/scripts/windows/omp-web-host.ps1 @@ -0,0 +1,59 @@ +#Requires -Version 5.1 +<# +.SYNOPSIS + Headless omp-web host daemon supervisor (`ompweb host`). + Registered next to the omp-web service by install-tray.ps1 as the "omp-web-host" scheduled task. +.NOTES + `ompweb host` exits when host.json does not exist yet (first install: the web server writes it + at startup) and when the server revokes or outdates its token. This loop restarts it after a + pause, so the daemon follows the web server instead of staying down. +#> +param( + [int]$RestartDelaySeconds = 10 +) + +$RepoRoot = (Resolve-Path "$PSScriptRoot\..\..").Path +$LauncherJs = Join-Path $RepoRoot "bin\omp-web.js" + +# One daemon supervisor per logon session. +$createdNew = $false +try { $script:AppMutex = New-Object System.Threading.Mutex($true, "Local\OmpWebHostDaemon_Instance_Mutex", [ref]$createdNew) } catch { $createdNew = $true } +if (!$createdNew) { Exit 0 } + +$LogDir = Join-Path $env:USERPROFILE ".omp\agent\logs" +if (!(Test-Path $LogDir)) { New-Item -Path $LogDir -ItemType Directory -Force | Out-Null } +$LogFile = Join-Path $LogDir "omp-web-host.log" +if ((Test-Path $LogFile) -and ((Get-Item $LogFile).Length -gt 5MB)) { + Move-Item -Path $LogFile -Destination "$LogFile.old" -Force -ErrorAction SilentlyContinue +} + +function Find-NodeExecutable { + $nodeCmd = Get-Command node.exe -ErrorAction SilentlyContinue + if ($nodeCmd -and (Test-Path $nodeCmd.Source)) { return $nodeCmd.Source } + $candidates = @( + "$env:ProgramFiles\nodejs\node.exe", + "${env:ProgramFiles(x86)}\nodejs\node.exe", + "$env:LOCALAPPDATA\Programs\node\node.exe", + "$env:USERPROFILE\.bun\bin\node.exe" + ) + foreach ($c in $candidates) { if (Test-Path $c) { return $c } } + return "node.exe" +} +$NodeExe = Find-NodeExecutable + +try { + while ($true) { + # Output goes to a file through cmd, as in omp-web-service.ps1. + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = $env:ComSpec + $psi.Arguments = "/d /s /c `"`"$NodeExe`" `"$LauncherJs`" host >> `"$LogFile`" 2>&1`"" + $psi.WorkingDirectory = $RepoRoot + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $proc = [System.Diagnostics.Process]::Start($psi) + $proc.WaitForExit() + Start-Sleep -Seconds $RestartDelaySeconds + } +} finally { + if ($script:AppMutex) { try { $script:AppMutex.ReleaseMutex() } catch { }; $script:AppMutex.Dispose() } +} diff --git a/scripts/windows/omp-web-tray.ps1 b/scripts/windows/omp-web-tray.ps1 index f456cc85c..ced491ef9 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -431,6 +431,12 @@ $script:MenuItemStatus.Text = " Status: Starting (Port $EffectivePort)" $script:MenuItemStatus.Enabled = $false $contextMenu.Items.Add($script:MenuItemStatus) | Out-Null +# Item 2b: Host daemon indicator (`ompweb host`, registered as the omp-web-host task) +$script:MenuItemDaemon = New-Object System.Windows.Forms.ToolStripMenuItem +$script:MenuItemDaemon.Text = " Daemon: Checking..." +$script:MenuItemDaemon.Enabled = $false +$contextMenu.Items.Add($script:MenuItemDaemon) | Out-Null + $contextMenu.Items.Add((New-Object System.Windows.Forms.ToolStripSeparator)) | Out-Null # Item 3: Open in Browser @@ -542,6 +548,19 @@ $script:NotifyIcon.add_DoubleClick({ try { [System.Diagnostics.Process]::Start($ServerUrl) | Out-Null } catch { } }) +# "Not installed" when the omp-web-host task is absent, else Running/Stopped by its supervisor process. +function Get-HostDaemonState { + try { + schtasks.exe /query /tn "omp-web-host" 2>$null | Out-Null + if ($LASTEXITCODE -ne 0) { return "Not installed" } + $procs = Get-CimInstance Win32_Process -Filter "Name LIKE '%powershell%' OR Name LIKE '%pwsh%'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -like '*omp-web-host.ps1*' } + if (($procs | Measure-Object).Count -gt 0) { return "Running" } + return "Stopped" + } catch { return "Unknown" } +} +$script:DaemonTicks = 0 +$script:DaemonState = "Checking..." + function Update-TrayUI { $statusText = switch ($script:State) { "Running" { "Running ($EffectivePort)" } @@ -552,6 +571,7 @@ function Update-TrayUI { } $script:MenuItemStatus.Text = " Status: $statusText" + $script:MenuItemDaemon.Text = " Daemon: $($script:DaemonState)" # Limit tooltip text length (Windows NotifyIcon.Text max 63 characters) $tipText = "omp-web ($statusText)" @@ -577,6 +597,13 @@ $script:Timer.Interval = 3000 $script:Timer.add_Tick({ if ($script:IsExiting) { return } + # The daemon query shells out to schtasks and WMI: every 5th tick (15 s) is enough. + if ($script:DaemonTicks % 5 -eq 0) { + $script:DaemonState = Get-HostDaemonState + $script:MenuItemDaemon.Text = " Daemon: $($script:DaemonState)" + } + $script:DaemonTicks++ + # Check child process state if ($script:ChildProcess -and $script:ChildProcess.HasExited) { $exitCode = $script:ChildProcess.ExitCode diff --git a/scripts/windows/uninstall-tray.ps1 b/scripts/windows/uninstall-tray.ps1 index ca4a432d6..11a38536f 100644 --- a/scripts/windows/uninstall-tray.ps1 +++ b/scripts/windows/uninstall-tray.ps1 @@ -43,6 +43,14 @@ try { Log-Message " Stopping headless service process tree (PID $($p.ProcessId))..." Start-Process -FilePath $taskkillExe -ArgumentList "/PID $($p.ProcessId) /T /F" -WindowStyle Hidden -Wait -ErrorAction SilentlyContinue | Out-Null } + # Also terminate the host daemon supervisor (omp-web-host.ps1) and its `ompweb host` child + $hostProcs = Get-CimInstance Win32_Process -Filter "Name LIKE '%powershell%' OR Name LIKE '%pwsh%'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -like '*omp-web-host.ps1*' } + foreach ($p in $hostProcs) { + Log-Message " Stopping host daemon process tree (PID $($p.ProcessId))..." + Start-Process -FilePath $taskkillExe -ArgumentList "/PID $($p.ProcessId) /T /F" -WindowStyle Hidden -Wait -ErrorAction SilentlyContinue | Out-Null + } + try { schtasks /delete /tn "omp-web-host" /f 2>$null | Out-Null; Log-Message " [OK] Removed Scheduled Task: omp-web-host" } catch { } + try { Unregister-ScheduledTask -TaskName "omp-web-host" -Confirm:$false -ErrorAction SilentlyContinue | Out-Null } catch { } # Delete Scheduled Task (both schtasks and PowerShell fallback) try { schtasks /delete /tn "omp-web" /f 2>$null | Out-Null; Log-Message " [OK] Removed Scheduled Task: omp-web" } catch { } try { Unregister-ScheduledTask -TaskName "omp-web" -Confirm:$false -ErrorAction SilentlyContinue | Out-Null } catch { } From 67c56cc88426069ccad8bcc053d91e723ce07a96 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 23:40:07 +0000 Subject: [PATCH 21/36] fix(service): restart only the web unit, tolerate a missing host unit, cheaper tray daemon poll --- bin/linux-tray.js | 2 +- bin/linux-tray.test.mjs | 2 +- bin/omp-web-launchd.js | 18 +++++-- bin/omp-web-launchd.test.mjs | 8 ++- bin/omp-web-systemd.js | 40 +++++++++++---- bin/omp-web-systemd.test.mjs | 84 +++++++++++++++++++++++++++++++- lib/i18n/locales/en.json | 2 +- lib/i18n/locales/ja.json | 2 +- lib/i18n/locales/zh-CN.json | 2 +- scripts/windows/omp-web-tray.ps1 | 23 ++++++--- 10 files changed, 155 insertions(+), 28 deletions(-) diff --git a/bin/linux-tray.js b/bin/linux-tray.js index 69c438618..0547d77ab 100644 --- a/bin/linux-tray.js +++ b/bin/linux-tray.js @@ -461,7 +461,7 @@ function buildMenuItems({ running, version, autostart, hasService, exposed, hasD { id: 4, label: "Open in Browser", action: "open" }, { id: 5, label: "Copy Web URL", action: "copy" }, { id: 6, separator: true }, - { id: 7, label: running ? "Stop Server" : "Start Server", action: "toggle", enabled: hasService }, + { id: 7, label: running ? "Stop Server (omp runs keep going)" : "Start Server", action: "toggle", enabled: hasService }, { id: 8, label: "Restart Server", action: "restart", enabled: hasService }, { id: 9, separator: true }, { id: 10, label: "View Logs", action: "logs" }, diff --git a/bin/linux-tray.test.mjs b/bin/linux-tray.test.mjs index a76deef89..dd1a2a498 100644 --- a/bin/linux-tray.test.mjs +++ b/bin/linux-tray.test.mjs @@ -86,7 +86,7 @@ test("readTrayConfig falls back to defaults without a config file", () => { test("buildMenuItems reflects running state and service availability", () => { const running = buildMenuItems({ running: true, version: "0.4.2", autostart: true, hasService: true, exposed: false, hasDialogTool: true }); assert.equal(itemById(running, 2).label, " Status: Running"); - assert.equal(itemById(running, 7).label, "Stop Server"); + assert.equal(itemById(running, 7).label, "Stop Server (omp runs keep going)"); assert.equal(itemById(running, 12).label, "Expose to Network"); assert.equal(itemById(running, 12).state, 0); assert.equal(itemById(running, 16).label, "Start with Plasma"); diff --git a/bin/omp-web-launchd.js b/bin/omp-web-launchd.js index cdaf9fe44..84e79c818 100644 --- a/bin/omp-web-launchd.js +++ b/bin/omp-web-launchd.js @@ -93,6 +93,15 @@ ${envXml} `; } +// The daemon needs the web agent's PATH, omp binary and agent dir (host.json), not its password. +function buildHostEnv({ svcPath, ompBin, agentDir }) { + return { + PATH: svcPath, + ...(ompBin ? { OMP_WEB_OMP_BIN: ompBin } : {}), + ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), + }; +} + function install(pkgArg) { const nodeBin = process.execPath; const siblingNpx = path.join(path.dirname(nodeBin), "npx"); @@ -151,12 +160,10 @@ function install(pkgArg) { ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}), }; const web = buildPlist({ label: LABEL, args: [npxBin, "--yes", pkg], env, logName: "ompweb" }); - // The daemon needs the same agent dir (host.json) and PATH, not the web password. - const hostEnv = { PATH: svcPath, ...(agentDir ? { PI_CODING_AGENT_DIR: agentDir } : {}) }; const host = buildPlist({ label: HOST_LABEL, args: [npxBin, "--yes", pkg, "host"], - env: hostEnv, + env: buildHostEnv({ svcPath, ompBin, agentDir }), logName: "ompweb-host", // host.json does not exist until the web server first starts; the daemon exits until then. throttleInterval: 10, @@ -165,6 +172,9 @@ function install(pkgArg) { fs.mkdirSync(LOG_DIR, { recursive: true }); fs.mkdirSync(path.dirname(PLIST), { recursive: true }); for (const [file, xml, label] of [[PLIST, web, LABEL], [HOST_PLIST, host, HOST_LABEL]]) { + // Reloading the daemon ends every omp run on this machine: leave it alone when nothing changed. + const unchanged = label === HOST_LABEL && fs.existsSync(file) && fs.readFileSync(file, "utf8") === xml; + if (unchanged && spawnSync("launchctl", ["print", `${DOMAIN}/${label}`], { stdio: "ignore" }).status === 0) continue; fs.writeFileSync(file, xml, { mode: 0o600 }); fs.chmodSync(file, 0o600); launchctl(["bootout", `${DOMAIN}/${label}`], { ignoreFailure: true }); @@ -218,4 +228,4 @@ function main() { if (require.main === module) main(); -module.exports = { HOST_LABEL, LABEL, buildPlist }; +module.exports = { HOST_LABEL, LABEL, buildHostEnv, buildPlist }; diff --git a/bin/omp-web-launchd.test.mjs b/bin/omp-web-launchd.test.mjs index f59bc16ce..f780eeee0 100644 --- a/bin/omp-web-launchd.test.mjs +++ b/bin/omp-web-launchd.test.mjs @@ -3,7 +3,7 @@ import { createRequire } from "node:module"; import test from "node:test"; const require = createRequire(import.meta.url); -const { HOST_LABEL, LABEL, buildPlist } = require("./omp-web-launchd.js"); +const { HOST_LABEL, LABEL, buildHostEnv, buildPlist } = require("./omp-web-launchd.js"); const env = { PATH: "/usr/bin", PI_CODING_AGENT_DIR: "/Users/u/agent" }; @@ -31,3 +31,9 @@ test("the web plist keeps its arguments and has no throttle", () => { assert.doesNotMatch(plist, /ThrottleInterval/); assert.doesNotMatch(plist, /host<\/string>/); }); + +test("the host env carries PATH, the omp binary and the agent dir, but no web settings", () => { + const all = buildHostEnv({ svcPath: "/usr/bin", ompBin: "/opt/omp/bin/omp", agentDir: "/Users/u/agent" }); + assert.deepEqual(all, { PATH: "/usr/bin", OMP_WEB_OMP_BIN: "/opt/omp/bin/omp", PI_CODING_AGENT_DIR: "/Users/u/agent" }); + assert.deepEqual(buildHostEnv({ svcPath: "/usr/bin" }), { PATH: "/usr/bin" }); +}); diff --git a/bin/omp-web-systemd.js b/bin/omp-web-systemd.js index 88e5df84c..c43563036 100644 --- a/bin/omp-web-systemd.js +++ b/bin/omp-web-systemd.js @@ -51,7 +51,7 @@ Commands: uninstall Stop both services and remove their unit files start Start both services stop Stop both services - restart Restart both services + restart Restart the web service (the host daemon keeps running) status Show both services' status (default when no command is given) open Open the web service in the default browser help Show this help @@ -365,8 +365,11 @@ function install(options = {}) { }, envPath); const wasActive = Object.fromEntries(UNITS.map((unit) => [unit, systemdQuery(["is-active", "--quiet", unit]).ok])); + // Restarting the daemon ends every omp run on this machine: only do it when its unit changed. + const hostUnitText = buildHostUnit(unitOptions); + const hostUnitChanged = readFileOrNull(HOST_UNIT_PATH) !== hostUnitText; fs.mkdirSync(UNIT_DIR, { recursive: true }); - for (const [unitPath, text] of [[UNIT_PATH, buildUnit(unitOptions)], [HOST_UNIT_PATH, buildHostUnit(unitOptions)]]) { + for (const [unitPath, text] of [[UNIT_PATH, buildUnit(unitOptions)], [HOST_UNIT_PATH, hostUnitText]]) { fs.writeFileSync(unitPath, text, { mode: 0o600 }); fs.chmodSync(unitPath, 0o600); } @@ -374,7 +377,8 @@ function install(options = {}) { systemctl(["daemon-reload"]); if (options.autostart !== false) systemctl(["enable", "--now", ...UNITS]); else systemctl(["start", ...UNITS], { ignoreFailure: true }); - for (const unit of UNITS) if (wasActive[unit]) systemctl(["restart", unit]); + if (wasActive[UNIT]) systemctl(["restart", UNIT]); + if (wasActive[HOST_UNIT] && hostUnitChanged) systemctl(["restart", HOST_UNIT]); console.log(`installed: ${UNIT_PATH}`); console.log(`installed: ${HOST_UNIT_PATH}`); @@ -402,19 +406,37 @@ function uninstall(options = {}) { console.log(`uninstalled: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); } +function readFileOrNull(file) { + try { + return fs.readFileSync(file, "utf8"); + } catch { + return null; + } +} + +// Installs from before the daemon existed have no host unit: leave it out then. +function installedUnits() { + return UNITS.filter((unit) => unit === UNIT || fs.existsSync(HOST_UNIT_PATH)); +} + +const unitNames = (units) => units.map((unit) => unit.replace(/\.service$/, "")).join(", "); + function start() { - systemctl(["start", ...UNITS]); - console.log(`started: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); + const units = installedUnits(); + systemctl(["start", ...units]); + console.log(`started: ${unitNames(units)}`); } function stop() { - systemctl(["stop", ...UNITS]); - console.log(`stopped: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); + const units = installedUnits(); + systemctl(["stop", ...units]); + console.log(`stopped: ${unitNames(units)}`); } +// Web unit only: restarting the daemon would end every omp run on this machine. function restart() { - systemctl(["restart", ...UNITS]); - console.log(`restarted: ${UNIT_NAME}, ${HOST_UNIT_NAME}`); + systemctl(["restart", UNIT]); + console.log(`restarted: ${UNIT_NAME}`); } function readUnitStatus(unit, unitPath) { diff --git a/bin/omp-web-systemd.test.mjs b/bin/omp-web-systemd.test.mjs index c9fa77b89..f5ad17a42 100644 --- a/bin/omp-web-systemd.test.mjs +++ b/bin/omp-web-systemd.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { createRequire } from "node:module"; import { spawnSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; @@ -97,6 +97,9 @@ test("buildHostUnit runs `ompweb host` with the web unit's env file and never gi assert.match(unit, /^StartLimitIntervalSec=0$/m); assert.doesNotMatch(unit, /StartLimitBurst/); assert.match(unit, /WantedBy=default\.target/); + // Same PATH as the web unit, so omp resolves the same way in both. + const envLine = (text) => text.match(/^Environment=.*$/m)[0]; + assert.equal(envLine(unit), envLine(buildUnit(options))); assert.equal(buildHostUnit({ ...options, ompwebBin: "/opt/my tools/ompweb" }).match(/^ExecStart=(.*)$/m)[1], '"/opt/my tools/ompweb" host'); }); @@ -314,3 +317,82 @@ test("runCli handles help and unknown commands without systemd", async () => { assert.deepEqual((await runCli(["--help"])).exitCode, 0); assert.deepEqual((await runCli(["bogus-command"])).exitCode, 2); }); + +// Runs the CLI against a fake systemctl that logs its arguments; `hostUnit: false` mimics an install from before the daemon. +function runWithFakeSystemctl(command, { hostUnit = true, active = false, dir: sharedDir, hostFails = !hostUnit } = {}) { + // A shared dir keeps HOME and the fake ompweb path, so a repeated install generates identical units. + const dir = sharedDir ?? mkdtempSync(path.join(tmpdir(), "ompweb-systemd-cmd-")); + const home = path.join(dir, "home"); + const binDir = path.join(dir, "bin"); + const log = path.join(dir, "systemctl.log"); + const fakeOmpweb = path.join(binDir, "ompweb"); + mkdirSync(binDir, { recursive: true }); + const unitDir = path.join(home, ".config", "systemd", "user"); + mkdirSync(unitDir, { recursive: true }); + writeFileSync(path.join(unitDir, "ompweb.service"), "[Service]\n"); + if (hostUnit && !existsSync(path.join(unitDir, "ompweb-host.service"))) writeFileSync(path.join(unitDir, "ompweb-host.service"), "[Service]\n"); + writeFileSync(fakeOmpweb, "#!/bin/sh\nexit 0\n", { mode: 0o755 }); + // A missing host unit makes systemctl fail, as the real one does. + writeFileSync( + path.join(binDir, "systemctl"), + `#!/bin/sh\necho "$*" >> "${log}"\n${hostFails ? 'case "$*" in *ompweb-host*) exit 5 ;; esac\n' : ""}case "$*" in *is-active*) exit ${active ? 0 : 3} ;; *) exit 0 ;; esac\n`, + { mode: 0o755 }, + ); + const env = { ...process.env, HOME: home, PATH: binDir, OMP_WEB_SYSTEMD_BIN: fakeOmpweb, OMP_WEB_DISABLE_AUTOUPDATE: "1" }; + for (const key of ["PI_CODING_AGENT_DIR", "OMP_WEB_OMP_BIN", "OMP_WEB_PASSWORD"]) delete env[key]; + const result = spawnSync(process.execPath, [path.join(process.cwd(), "bin", "omp-web-systemd.js"), command], { env, encoding: "utf8" }); + const calls = existsSync(log) ? readFileSync(log, "utf8").trim().split("\n") : []; + rmSync(log, { force: true }); + return { result, calls, dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) }; +} + +test("restart restarts the web unit only: restarting the daemon would end every omp run", { skip: process.platform !== "linux" }, () => { + const { result, calls, cleanup } = runWithFakeSystemctl("restart"); + try { + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(calls, ["--user restart ompweb.service"]); + } finally { + cleanup(); + } +}); + +test("start and stop cover both units when the host unit exists", { skip: process.platform !== "linux" }, () => { + for (const command of ["start", "stop"]) { + const { result, calls, cleanup } = runWithFakeSystemctl(command); + try { + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(calls, [`--user ${command} ompweb.service ompweb-host.service`]); + } finally { + cleanup(); + } + } +}); + +test("start, stop and restart work on an install without the host unit", { skip: process.platform !== "linux" }, () => { + for (const command of ["start", "stop", "restart"]) { + const { result, calls, cleanup } = runWithFakeSystemctl(command, { hostUnit: false }); + try { + assert.equal(result.status, 0, result.stderr); + assert.deepEqual(calls, [`--user ${command} ompweb.service`]); + } finally { + cleanup(); + } + } +}); + +test("install restarts a running host unit only when its unit text changed", { skip: process.platform !== "linux" }, () => { + // Pre-existing install: the host unit file is absent, so the first install writes it (changed). + const first = runWithFakeSystemctl("install", { hostUnit: false, hostFails: false, active: true }); + try { + assert.equal(first.result.status, 0, first.result.stderr); + assert.ok(first.calls.includes("--user restart ompweb.service")); + assert.ok(first.calls.includes("--user restart ompweb-host.service")); + // Same install again: identical unit text, so only the web unit restarts. + const second = runWithFakeSystemctl("install", { active: true, dir: first.dir }); + assert.equal(second.result.status, 0, second.result.stderr); + assert.ok(second.calls.includes("--user restart ompweb.service")); + assert.ok(!second.calls.includes("--user restart ompweb-host.service"), second.calls.join("\n")); + } finally { + first.cleanup(); + } +}); diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 5cb062821..911f8cc9b 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -204,7 +204,7 @@ "settingsConfig.windowsServiceReinstallBtn": "Reinstall / Repair Shortcuts", "settingsConfig.windowsServiceUninstallBtn": "Uninstall Service", "settingsConfig.windowsServiceStartBtn": "Start Tray Manager", - "settingsConfig.windowsServiceStopBtn": "Stop Service", + "settingsConfig.windowsServiceStopBtn": "Stop Service (omp runs keep going)", "settingsConfig.windowsServiceRestartBtn": "Restart Service", "settingsConfig.windowsServiceDesktopShortcut": "Desktop Shortcut: {status}", "settingsConfig.windowsServiceStartupShortcut": "Startup Shortcut: {status}", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index 06b91f636..75069b6c8 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -201,7 +201,7 @@ "settingsConfig.windowsServiceReinstallBtn": "ショートカットを再インストール / 修復", "settingsConfig.windowsServiceUninstallBtn": "サービスをアンインストール", "settingsConfig.windowsServiceStartBtn": "トレイマネージャーを起動", - "settingsConfig.windowsServiceStopBtn": "サービスを停止", + "settingsConfig.windowsServiceStopBtn": "サービスを停止(omp の実行は継続)", "settingsConfig.windowsServiceRestartBtn": "サービスを再起動", "settingsConfig.windowsServiceDesktopShortcut": "デスクトップショートカット: {status}", "settingsConfig.windowsServiceStartupShortcut": "スタートアップショートカット: {status}", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index b094bd2d0..fe15446ec 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -201,7 +201,7 @@ "settingsConfig.windowsServiceReinstallBtn": "重新安装 / 修复快捷方式", "settingsConfig.windowsServiceUninstallBtn": "卸载服务", "settingsConfig.windowsServiceStartBtn": "启动托盘管理器", - "settingsConfig.windowsServiceStopBtn": "停止服务", + "settingsConfig.windowsServiceStopBtn": "停止服务(omp 运行将继续)", "settingsConfig.windowsServiceRestartBtn": "重启服务", "settingsConfig.windowsServiceDesktopShortcut": "桌面快捷方式:{status}", "settingsConfig.windowsServiceStartupShortcut": "自启快捷方式:{status}", diff --git a/scripts/windows/omp-web-tray.ps1 b/scripts/windows/omp-web-tray.ps1 index ced491ef9..4b347a4bf 100644 --- a/scripts/windows/omp-web-tray.ps1 +++ b/scripts/windows/omp-web-tray.ps1 @@ -469,7 +469,7 @@ $contextMenu.Items.Add($script:MenuItemRestart) | Out-Null # Item 6: Toggle Start/Stop Server $script:MenuItemToggle = New-Object System.Windows.Forms.ToolStripMenuItem -$script:MenuItemToggle.Text = "Stop Server" +$script:MenuItemToggle.Text = "Stop Server (omp runs keep going)" $script:MenuItemToggle.add_Click({ if ($script:State -eq "Running" -or $script:State -eq "Starting") { Stop-WebServer @@ -548,13 +548,17 @@ $script:NotifyIcon.add_DoubleClick({ try { [System.Diagnostics.Process]::Start($ServerUrl) | Out-Null } catch { } }) -# "Not installed" when the omp-web-host task is absent, else Running/Stopped by its supervisor process. +# The supervisor (omp-web-host.ps1) holds a named mutex while it runs: opening it is an in-process +# check. Only when it is not held do we shell out to schtasks to tell "Stopped" from "Not installed". function Get-HostDaemonState { try { + $held = $null + if ([System.Threading.Mutex]::TryOpenExisting("Local\OmpWebHostDaemon_Instance_Mutex", [ref]$held)) { + $held.Dispose() + return "Running" + } schtasks.exe /query /tn "omp-web-host" 2>$null | Out-Null if ($LASTEXITCODE -ne 0) { return "Not installed" } - $procs = Get-CimInstance Win32_Process -Filter "Name LIKE '%powershell%' OR Name LIKE '%pwsh%'" -ErrorAction SilentlyContinue | Where-Object { $_.ProcessId -ne $PID -and $_.CommandLine -like '*omp-web-host.ps1*' } - if (($procs | Measure-Object).Count -gt 0) { return "Running" } return "Stopped" } catch { return "Unknown" } } @@ -579,7 +583,7 @@ function Update-TrayUI { $script:NotifyIcon.Text = $tipText if ($script:State -eq "Running" -or $script:State -eq "Starting") { - $script:MenuItemToggle.Text = "Stop Server" + $script:MenuItemToggle.Text = "Stop Server (omp runs keep going)" $script:MenuItemRestart.Enabled = $true } else { $script:MenuItemToggle.Text = "Start Server" @@ -597,10 +601,13 @@ $script:Timer.Interval = 3000 $script:Timer.add_Tick({ if ($script:IsExiting) { return } - # The daemon query shells out to schtasks and WMI: every 5th tick (15 s) is enough. + # Every 5th tick (15 s) is enough for the daemon state. if ($script:DaemonTicks % 5 -eq 0) { - $script:DaemonState = Get-HostDaemonState - $script:MenuItemDaemon.Text = " Daemon: $($script:DaemonState)" + $newDaemonState = Get-HostDaemonState + if ($newDaemonState -ne $script:DaemonState) { + $script:DaemonState = $newDaemonState + Update-TrayUI + } } $script:DaemonTicks++ From 9e2fdb582902aec4f49cdb2f7a88695f5acaceb1 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Thu, 29 Oct 2026 23:49:28 +0000 Subject: [PATCH 22/36] docs(hosts): document the local daemon --- AGENTS.md | 83 +++++++++++++------- CHANGELOG.md | 1 + DESIGN.md | 28 ++++--- README.md | 57 +++++++++++--- docs/specs/2026-10-29-local-daemon-design.md | 37 ++++++--- 5 files changed, 143 insertions(+), 63 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 86cd6fe90..42668dca0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -107,16 +107,17 @@ app/api/ lib/ omp/ shared omp foundations (paths, CLI probe, RpcProcess) - hosts/ remote hosts (see "Remote hosts"); none of the daemon-loaded files may import `next/*` or `@/` + hosts/ hosts and the local daemon (see "Remote hosts"); none of the daemon-loaded files may import `next/*` or `@/` host.ts `Host` interface, `HostStatus`, `isLinkUp` - local-host.ts `localHost`: spawn + file checks on this machine; `resolveSpawnCwdResult` - session-ops.ts file-reading half of the session/project routes, run on the owning host + local-host.ts `localHost`, the daemon's side: spawn + file checks on the daemon's machine; `resolveSpawnCwdResult`. Never imported by main (`no-direct-local.test.mjs`) + local-bootstrap.ts web server side of the local link: `localLinkUrl`, `ensureLocalHostLink` (the `local` record + `host.json`) + session-ops.ts file-reading half of the session/project routes, run on the owning host's daemon (this machine's too) link-protocol.ts link messages, codec, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox` - hub.ts main side: link GET/POST/blob handlers, `RemoteHost`, `getHost`, `listHosts`, orphans, `hosts` change events - daemon.ts remote side: `loginHost`, `readHostLogin`, `runHostDaemon` (reconnect, buffering, op dispatch) - pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests for the hello - registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup - session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget` + hub.ts main side: link GET/POST/blob handlers, `RemoteHost`, `getHost`, `listHosts`, adoption of live children (`reattach`/`adopt`), orphans, `freezeHostLinks`, `hosts` change events + daemon.ts daemon side: `loginHost`, `readHostLogin`, `runHostDaemon` (reconnect, buffering, op dispatch, hello with each child's `{sessionId, cwd, pending}`) + pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests and current session id for the hello + registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup; the `local` record (`rotateLocalHostToken`, `customLocalLabel`) + session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget`, `invalidateLocalSessionLists` provider-accounts.ts distinct omp accounts per provider from `omp usage` reports (Models → provider detail) agent-client.ts typed fetch helper for /api/agent commands btw.ts /btw side-question records + pure frame/snapshot merge (order-safe) @@ -179,6 +180,7 @@ components/ ModelsConfig.tsx modal for models/auth configuration McpConfig.tsx project MCP server editor (Settings → MCP tab) HostsConfig.tsx linked hosts: add (token shown once), rename, revoke, allowAgentStart (Settings → Hosts tab) + LocalDaemonBanner.tsx production-only hint with the install command while no local daemon has linked (90 s grace) host-status.ts host name, status text and dot colour shared by Settings → Hosts and the sidebar PluginsConfig.tsx modal for installed plugins SkillsConfig.tsx modal for loaded/search/installable skills @@ -236,27 +238,33 @@ bin/ overwrites sessions the other is running. Startup claims a list only when its pid is dead or the file predates the last boot, plus the legacy unsuffixed list. Same-boot pid reuse or a zombie writer leaves that list unresumed. -- A service stop signals every process at once, so an omp child can die - before omp-web's own SIGTERM handler runs. A session whose process died - therefore stays listed for `EXIT_GRACE_MS`; the shutdown handler freezes the - list (`markShuttingDown`) so those deaths count as interrupted, while a - crash with omp-web still up is dropped after the window. +- The omp children run under the daemon, so stopping the web service does not + reach them: the next server adopts the ones still running and drops their + entries from this list (`adoptedChild`, see "Local daemon"). Only sessions + whose child died (daemon restart, crash, failed adoption) resume, after the + daemon's hello (`resumeOnHostLink`). A session whose process died stays + listed for `EXIT_GRACE_MS`; the shutdown handler freezes the list + (`markShuttingDown`) so deaths during a shutdown count as interrupted, while + a crash with omp-web still up is dropped after the window. - Only session ids are stored; paths are re-resolved on resume. - Known limit: resume does not detect a terminal `omp --resume ` started on the same session while omp-web was down; both would write the file. ### Remote hosts (`lib/hosts/`, `app/api/hosts/`, `bin/omp-web-host.js`) -- **Host seam** (`lib/hosts/host.ts`). `localHost` (`id: "local"`, `local-host.ts`) - spawns and reads files on this machine; `RemoteHost` (`getHost(id)` in - `hub.ts`) makes the same calls over the link. `startRpcSession(..., host)` +- **Host seam** (`lib/hosts/host.ts`). Every host, this machine included, is + reached over the link: `getHost(id)` (`hub.ts`) returns a `RemoteHost` whose + calls go to a daemon. `getHost("local")` is the link of this machine's own + `ompweb host` daemon (see "Local daemon"); there is no direct spawn or file path + on main. `localHost` (`id: "local"`, `local-host.ts`) is the daemon's side: it spawns + and reads files on the machine the daemon runs on. `startRpcSession(..., host)` asks `host.spawnRpc` for an `RpcTransport`; `RpcProcess`, the wrapper, the event hub, notifications, the queue and `/btw` never see where omp runs. - Session and project file reads are `host.sessionOps` (`session-ops.ts`), - addressed by session id, never by path: routes use `resolveSessionHostOr404` + Session and project file reads are `host.sessionOps` (`session-ops.ts`, run in + the daemon), addressed by session id, never by path: routes use `resolveSessionHostOr404` (`lib/api-utils.ts`) and the host resolves the file itself. New route code - must not open a session file on main for a session that may be remote. + 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 locally, `:`). + project state key on `hostProjectKey` (bare path on this machine, `:`). - **Link = two HTTP legs, both dialled by the daemon** (`/api/hosts/link`): `GET` is the downlink (long-lived NDJSON, main → daemon), `POST` the uplink (batched NDJSON, daemon → main). No WebSocket: `next start` route handlers @@ -320,17 +328,18 @@ bin/ `linkLostDuring` in `rpc-manager.ts`); a quiet or dropped link answers `host_offline` (503), queues no kill and leaves the run to `reconcileAfterGap`. A kill through a dead link only waits in the outbox. -- **Orphans and resume.** On `hello`, listed channels with no wrapper are - orphans (main restarted): they get `kill`, escalating to force after 5 s, - and stay registered until their `exit`. A cold remote spawn for a session +- **Orphans and resume.** On `hello`, listed channels with no wrapper are children + of a previous server run: they are adopted (see "Local daemon"), and killed + (`kill`, escalating to force after 5 s, registered until their `exit`) only when + adoption is impossible. A cold spawn for a session awaits `orphanExit(hostId, sessionId)` first so two children never write one file; the wait rejects 503 as soon as the link goes down. A buffer overflow on the daemon (32 MB per channel, two image-prompt echoes) drops the channel's backlog and sends `resync {ch}`; main's `RpcProcess` discards any partial chunked frame, skips leftover chunks until the next frame start, and reruns - the `get_state` reconcile. With `autoResumeSessions` on, - an interrupted remote session resumes after its host's hello - (`resumeOnHostLink`, `lib/session-resume.ts`), once, after the orphan's exit. + the `get_state` reconcile. With `autoResumeSessions` on, an interrupted + session resumes after its host's hello (`resumeOnHostLink`, + `lib/session-resume.ts`), once, after the orphan's exit. - **Proxy exclusion.** `proxy.ts` does not run for `/api/hosts/link` and its subpaths (its matcher excludes exactly those). Next buffers a proxied request body and silently truncates it past 10 MB, below the link's 16 MB uplink and @@ -369,6 +378,18 @@ bin/ settings tabs and directory browsing show "Not available on remote hosts yet". Sub-projects 2 and 3 of the spec add ops for them. +#### Local daemon (`docs/specs/2026-10-29-local-daemon-design.md`) +- **Two services.** `ompweb` (web) and `ompweb-host` (`ompweb host`, the daemon) are installed together by `ompweb systemd install`, `ompweb launchd install` and the Windows tray install; uninstall removes both, `ompweb systemd restart` restarts the web unit only. The daemon owns this machine's omp children, so a web restart, update or redeploy leaves runs going; restarting the daemon ends them (auto-resume then resumes the sessions that were running). An upgrade restarts the daemon only when `LINK_PROTOCOL_VERSION` changed (the old daemon would get 426 and exit). +- **Local link bootstrap** (`lib/hosts/local-bootstrap.ts`, called from `instrumentation.node.ts`). `localLinkUrl()` builds the daemon's URL from `OMP_WEB_PORT`/`OMP_WEB_HOSTNAME` (set by the `ompweb` launcher; wildcard binds map to `127.0.0.1`, a non-loopback bind gets no link and a console warning). `ensureLocalHostLink()` makes sure the `local` record exists (`registry.ts`, `rotateLocalHostToken`) and writes `/omp-web/host.json` (`{url, token}`, 0600). A `host.json` whose token the registry still accepts and whose url matches is left alone, so a web restart does not make the daemon redial. It throws, and startup only logs, when `host.json` points to a non-loopback server (a remote-host login on this machine): it is never overwritten. The daemon re-reads `host.json` when its link gets 401 and exits only if the file still holds the rejected token. +- **Dev mode does not take the daemon.** With `NODE_ENV=development` `ensureLocalHostLink` is skipped, so the daemon stays linked to production and the dev server shows "This machine" offline. The local row of `GET /api/hosts` carries `daemonManaged: false` there, which hides the install banner. +- **`local` is a registry record like any host**, with three exceptions: it is listed first, `PATCH` takes `label` only (`allowAgentStart` is fixed), and it cannot be revoked. Renaming "This machine" is a `PATCH /api/hosts {id: "local", label}`; an empty label resets it (`registry.ts` stores `""`; `customLocalLabel()` / `DEFAULT_LOCAL_LABEL` map it). `getHost("local")` works without the record: it is the daemon link, offline while none is linked, and "needs upgrade" on a protocol mismatch (`hostVersion` in the row is the daemon's). +- **Adoption on hello** (`reattach`/`adopt` in `hub.ts`, `adoptRpcSession` in `rpc-manager.ts`). Each listed `{ch, sessionId, cwd, pending}` channel that has no transport on this server is a child of a previous server and is taken over by a new `AgentSessionWrapper` (`adopted: true`, `RpcProcess` option `adopted`). There is no session-list lookup: the spawn `cwd` comes from the hello, and the session identity from the child's own `get_state` (`applyIdentity`), so a new session whose file is not written yet is adoptable. The daemon names each child's current session in the hello (`PendingRequests.sessionId`: the file's header id at spawn, then the last successful `get_state`). Re-sync (`AgentSessionWrapper.adopt`): `negotiate_protocol`, `set_subagent_subscription`, `set_ask_dialog`, `get_state`, `get_subagents`, `get_btw_history`, then `replay` of the `pending` lines and `release` of the frames held meanwhile. Every command is bounded by `GET_STATE_TIMEOUT_MS`. +- **The daemon replays open blocking requests** (`pending-requests.ts`): `host_tool_call`, `host_uri_request` and blocking `extension_ui_request` lines, until answered or cancelled, capped at `LINK_LIMITS.pendingBytes` per channel. An adopted wrapper feeds them through `handleFrame` (`replaying`; agent tools are not re-run), so dialogs reappear and browser tool calls wait for the next tab (`hostToolsUnknown`, `parkHostTool`). +- **A child is killed (`killOrphan`) only when it cannot be adopted:** its hello entry has no session id or lost its `pending` lines to the cap, a re-sync command times out or the child exits, its held output overflows, or its real session (after `get_state`) is already started on this server. Auto-resume (`resumeOnHostLink`) first awaits `adoptedChild()` and resumes a session only if it was not adopted. +- **Shutdown freezes the links and never kills daemon children.** The `cleanup` in `rpc-manager.ts` runs `markShuttingDown()` and `freezeHostLinks()`: from then on a link neither sends nor applies anything (no kill, no rejection of open host tool calls as tabs close; the daemon's POSTs get 503 "shutting down"). The daemon keeps the output unacked for the next server. An adoption that fails after the freeze leaves its child to the next server instead of killing it. +- **Install banner** (`components/LocalDaemonBanner.tsx`). In production, when the local row stays offline with `hostVersion === null` (no daemon has linked since this server started) for 90 s of a page view (longer than the daemon's 60 s redial backoff cap, so a restarting daemon does not trip it), it shows the platform's install command; dismissal is kept in `localStorage`. Main never installs services. +- **No direct local path.** `local-host.ts` is the daemon's; `lib/hosts/no-direct-local.test.mjs` fails when anything outside its allow-list spawns omp or imports it. The utility omp (`rpc-utility.ts`, login) is the one deliberate exception: it is not a session. + ### Session moves (omp >= 18.5 ownership) and title generation - Only the first omp process to write a session file owns it; a non-owner moves to a sibling file with a new id on its first write and emits a @@ -711,13 +732,13 @@ during the wait. disconnect cancels and cleans up too. An existing target is refused (409). ### File access allow-list -- `/api/files` is intentionally not a general filesystem browser. Allowed roots come from session cwds, their resolved project roots, `~/omp-cwd-*`, and roots explicitly added with `allowFileRoot()`. +- `/api/files` is intentionally not a general filesystem browser. Allowed roots come from this machine's session cwds and their resolved project roots (as its daemon lists them: `hostSessions("local")`, the last list while the daemon is offline), `~/omp-cwd-*`, and roots explicitly added with `allowFileRoot()`. Other hosts' paths never reach it. - `/api/cwd/validate`, `/api/default-cwd`, and `/api/worktrees` call `allowFileRoot()` when they make a new location browsable. +- The session-id → file path cache (`cacheSessionPath`, `lib/session-reader.ts`) on main is filled by main's own scans and by wrappers on the local host; it only serves the readers listed under "Session list caching". ### Session list caching — new sessions must appear immediately -- `listAllSessions()` (sidebar, command palette) is cached twice: a 30s TTL - list cache in `lib/session-reader.ts` plus an mtime-keyed directory walk in - `lib/omp/session-files.ts` (`listSessionFiles`). +- The sidebar and command palette list sessions per host: `listSessionsAllHosts()` (`lib/hosts/session-index.ts`) calls each host's `listSessions` op and caches it 30 s per host (`LIST_TTL_MS`, the daemon's own TTL). **This machine's list is its daemon's**; a host that fails or is offline keeps its last list. Nothing on main parses session files to build it. +- The daemon's `listSessions` is `listAllSessions()` (`lib/session-reader.ts`): a 30 s TTL list cache plus an mtime-keyed directory walk in `lib/omp/session-files.ts` (`listSessionFiles`), both in the daemon process. - The walk cache keys on the **sessions root** mtime. On Windows/NTFS a new `.jsonl` inside an existing project subdirectory does NOT bump the root mtime, so the walk stays stale indefinitely. @@ -725,6 +746,8 @@ during the wait. compaction, renames) must therefore ALSO clear the walk cache via `invalidateSessionFileListCache()` — never add a session-mutation path that forgets this. Regression test: `session-reader.test.mjs`. +- A mutation that main triggers calls `invalidateLocalSessionLists()`: it clears main's per-host entry and sends the daemon `invalidateSessionLists` (the daemon runs the invalidation above). A route that changes this machine's session files and does not call it leaves the sidebar stale for up to 30 s. +- **Still read on main, from this machine's own files** (main and the daemon share a machine, so these see the same sessions): transcript search (`session-content-search.ts`, `/api/sessions/search`), the session file watcher (`session-watcher.ts`), archive list/restore (`/api/sessions/archive`), import (`/api/sessions/import`), usage (`usage-db.ts`), and the bash-output, subagent-history and file-reference readers (`session-file-references.ts`, `subagent-history.ts`). They use main's own copies of `session-reader` and its caches, so they are invalidated separately (`invalidateSessionListCache()`); a new reader of session files on main for a session that may be remote is a bug. ### Chat scroll-follow - `useAgentSession` follows the conversation: the effect depends on both diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cf84dc25..da63be5d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added - **Run sessions on other machines from one ompweb.** Link a machine (for example a MacBook) with **Settings → Hosts → Add host**, then run `ompweb host login --url ` (the token is read from stdin) and `ompweb host` there. The remote machine keeps its own `omp`, agent directory and credentials; ompweb routes. The sidebar groups sessions by host, the new-session screen has a host picker, and chat, history, notifications and resume work on every host. If the link drops, the run continues on the remote machine and the chat shows an offline banner until the host reconnects. Agents can pass `host` to `new_session` (it defaults to the agent's own host), which asks for confirmation on a remote host unless the host allows it; an agent on a remote host always asks before it starts or messages a session on this machine. Explorer, Git, worktrees and the skills, plugins, agents and MCP settings are not available on remote hosts yet. +- **Restarting or redeploying ompweb no longer interrupts a run on this machine.** "This machine" now runs through a local `ompweb host` daemon, installed as a second service (`ompweb-host`) by `ompweb systemd install`, `ompweb launchd install` and the Windows tray install. The daemon keeps the omp processes; a restarted web server adopts them, with no resume prompt, and the dialogs and browser tool calls omp was waiting on come back. The daemon is required: until it is installed and linked, "This machine" shows offline (with a banner showing the install command) and new sessions there cannot start. Restarting the daemon still ends runs, and `ompweb systemd restart` leaves it alone. A `npm run dev` server does not take over the daemon. "This machine" can be renamed in **Settings → Hosts**. ### Fixes & Improvements diff --git a/DESIGN.md b/DESIGN.md index fefc58047..a3f79b23d 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -78,20 +78,25 @@ v1-capable installations. Every machine-local action of a session goes through one interface, `Host` (`lib/hosts/host.ts`): spawning `omp --mode rpc-ui`, checking that a session file exists, invalidating cached session lists, and the -file-reading operations behind the session and project routes. Two -implementations exist: - -- `LocalHost` runs on the machine that serves ompweb, using `child_process` and - direct file access. -- `RemoteHost` makes the same calls on another machine over the link described - below. +file-reading operations behind the session and project routes. The web server +has no direct path to any machine, its own included: it reaches every host +through the link described below. The implementation on the web server is +`RemoteHost`; the daemon (`ompweb host`) runs the other side, `LocalHost`, on +the machine whose omp it owns. ``` -Browser ─▶ ompweb ──┬─ LocalHost ── spawn omp --mode rpc-ui (stdio) - └─ RemoteHost ◀── link (HTTP) ── ompweb host - └─ spawn omp --mode rpc-ui +Browser ─▶ ompweb ◀── link (loopback) ── ompweb host ── spawn omp --mode rpc-ui (stdio) + ◀── link (HTTP) ── ompweb host on another machine + └─ spawn omp --mode rpc-ui ``` +"This machine" is the host with the fixed id `local`, linked to the daemon +that the service installers set up next to the web service. Because the daemon +owns the omp processes, restarting or redeploying the web server does not end +a run: the restarted server adopts the live children from the daemon's hello, +with their open blocking requests replayed. A direct spawn path would tie +every run to the web server's lifetime, which is why none exists. + The CLI boundary above holds on every machine: a remote machine runs its own installed `omp`, its own `~/.omp/agent` and its own credentials. ompweb only routes. `RpcProcess` takes its byte pipe (`RpcTransport`) from the host, so the @@ -128,7 +133,8 @@ the daemon requires `https://` except for loopback or an explicit Session browsing is implemented in pure Node against OMP JSONL files. The reader tolerates the fixed title slot and older session shapes, resolves blob references when needed, and builds the active branch context from the entry -tree. +tree. The session and project routes run it in the daemon of the session's host +(`session-ops.ts`), so the same code serves this machine and every linked one. Direct session mutation is deliberately narrow and explicit: rename/title, archive, deletion, and required branch-parent maintenance. These writes are diff --git a/README.md b/README.md index 861d40268..612977c9b 100644 --- a/README.md +++ b/README.md @@ -123,6 +123,7 @@ ompweb --install-tray # Install Windows System Tray service ompweb --uninstall-tray # Uninstall Windows System Tray service & shortcuts ompweb --tray # Start background System Tray manager ompweb systemd install # Install Linux systemd user services (web + ompweb-host daemon) +ompweb launchd install # Install the macOS launchd agents (web + ompweb-host daemon) ompweb --help # Show help ompweb --version # Show version ``` @@ -171,6 +172,31 @@ your user or system environment (for example `setx OMP_WEB_PASSWORD_HASH started with. Changing or removing the hash takes effect at the next server restart, without signing out of Windows. +### Two services: the web server and the local daemon + +ompweb runs this machine's `omp` sessions through a small daemon, `ompweb host`, +linked to the web server over loopback. The service installers (`ompweb systemd install`, +`ompweb launchd install`, `ompweb --install-tray`) install both: the web +service and `ompweb-host`. Uninstall removes both. + +- **Restarting or redeploying the web server does not interrupt runs.** The daemon + keeps the omp processes running; the restarted web server takes them over, with + no resume prompt, and dialogs or tool calls omp was waiting on reappear. +- **Restarting the daemon does end runs** (it owns the omp processes). With auto-resume + on, sessions that were running resume once. `ompweb systemd restart` restarts the + web service only; upgrades restart the daemon only when the link protocol + changed. +- **First start after an upgrade:** if no daemon has linked after about 90 seconds, + ompweb shows a banner with the install command for your platform. It never installs + services itself. Until the daemon runs, "This machine" shows offline and new + sessions on it cannot start. +- **It is a host like any other.** Rename "This machine" in **Settings → Hosts** + (clear the name to reset it); it cannot be revoked. The web server writes the + daemon's link (`~/.omp/agent/omp-web/host.json`, mode `600`) at startup, only + for a loopback bind address. +- **Development:** `npm run dev` does not take the daemon (see + [Development](#development)). + ### Run as a Windows Service (System Tray) Install ompweb as a Windows background service with a system tray icon and autostart at login: @@ -186,7 +212,7 @@ ompweb --tray # Start the tray manager ompweb --uninstall-tray ``` -Shortcuts are created on the Desktop and Start Menu. The service restarts automatically and shows the current port and status in the tray. +Shortcuts are created on the Desktop and Start Menu. The service restarts automatically and shows the current port and status in the tray. The install also registers the [local daemon](#two-services-the-web-server-and-the-local-daemon) as a second scheduled task (`ompweb host`); the tray shows both states. ### Run as a macOS Service (launchd) @@ -223,9 +249,12 @@ or equivalent access control) and HTTPS through a trusted reverse proxy or VPN. Never expose the unauthenticated web UI or send its password/session cookie over plaintext HTTP. -Logs go to `~/Library/Logs/ompweb/ompweb.log` and the plist lives at +Logs go to `~/Library/Logs/ompweb/ompweb.log` (web) and +`~/Library/Logs/ompweb/ompweb-host.log` (the +[local daemon](#two-services-the-web-server-and-the-local-daemon)). The plists live at `~/Library/LaunchAgents/com.kahme247.ompweb.plist` (mode 600; the password -hash — not the password — is stored there). +hash — not the password — is stored there) and +`~/Library/LaunchAgents/com.kahme247.ompweb-host.plist`. ### Run as a Linux Service (systemd) @@ -264,11 +293,13 @@ hostname, and password hash there and just restart the service; no reinstall needed. Install-time [environment variables](#environment-variables) are baked into that file. As a service, the browser is **not** auto-opened by default. The -unit lives at `~/.config/systemd/user/ompweb.service` and logs go to the -journal: +units live at `~/.config/systemd/user/ompweb.service` and +`~/.config/systemd/user/ompweb-host.service` (the +[local daemon](#two-services-the-web-server-and-the-local-daemon)); logs go to +the journal: ```bash -journalctl --user -u ompweb -f +journalctl --user -u ompweb -u ompweb-host -f ``` On a headless server, enable user lingering if the service must keep running @@ -348,10 +379,12 @@ Settings closes its link and the daemon stops its omp processes. Notes: -- **Service helpers:** `ompweb-launchd` and `ompweb-systemd` install the web server - only (their service runs `ompweb` with no arguments), so they cannot run - `ompweb host`. To keep the link up across logouts or reboots, run - `ompweb host` under a supervisor of your choice that restarts it after failure. +- **Service helpers:** `ompweb systemd install` and `ompweb launchd install` set up + this machine's own daemon next to its web server (see + [Two services](#two-services-the-web-server-and-the-local-daemon)). On the other + machine you only need the daemon, and the helpers would also start a web server + there, so run `ompweb host` under a supervisor of your choice that restarts it + after failure to keep the link up across logouts or reboots. The daemon exits with code `1` when the server revokes its token or when the link protocol versions differ (either side may be the newer one; upgrade ompweb on the older side), and `0` when a newer link for the same host replaces it. @@ -535,6 +568,10 @@ npm run dev The dev server runs at [http://127.0.0.1:30178](http://127.0.0.1:30178). +A dev server does not take over the local daemon: only the production web +server writes the daemon's `host.json`, so "This machine" shows offline in dev +and the daemon stays linked to your installed ompweb. + The development server allows loopback and RFC1918 private IPv4 origins (`10.0.0.0/8`, `172.16.0.0/12`, and `192.168.0.0/16`). When using a tunnel or reverse proxy with a custom hostname, set it without editing `next.config.ts`: diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index 8f334edbd..11c5bda93 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -46,8 +46,11 @@ ompweb (web service) ──link over 127.0.0.1──▶ ompweb host (daemon se it; the registry keeps "" for the default), and is listed first. It cannot be revoked, and its `allowAgentStart` is fixed. - **Session file operations** (`session-ops.ts`) run in the daemon, as they do - for remote hosts. The web server keeps no direct session-file reads for - `local`, so the two paths cannot drift. + for remote hosts: the session and project routes and the sidebar list reach + this machine's sessions through it. A few main-side readers still read this + machine's files directly because both share the machine (transcript search, + the session file watcher, archive and import, usage, bash-output and + subagent-history; listed in `AGENTS.md`). - **Local link bootstrap.** On start, the web server makes sure a host record `local` exists with a token, and writes the daemon's `/omp-web/host.json` (`{url, token}`, mode 0600) with its own @@ -57,12 +60,15 @@ ompweb (web service) ──link over 127.0.0.1──▶ ompweb host (daemon se ## Adopting live children -On `hello`, for each listed `{ch, sessionId}` that has no wrapper on the web -server: +On `hello`, for each listed `{ch, sessionId, cwd, pending}` that has no wrapper +on the web server: -1. Look up `sessionId` in that host's session list to get the file and cwd. A - child whose session is unknown (never written, or deleted) is killed, as - today. +1. Take the spawn cwd from the `hello` entry. There is no session-list lookup: + the child's own `get_state` (step 4) names its session, so a new session + whose file is not written yet is adoptable. The daemon lists each child's + current session id (the session file's header at spawn, then the last + successful `get_state`). A child with no session id, or whose open requests + exceeded the cap, is killed, as today. 2. Create an `AgentSessionWrapper` on the existing channel with `adopted: true`. It skips spawn, the `ready` wait and the initial protocol negotiation. 3. Re-sync the protocol: send `negotiate_protocol` again; drop partial chunked @@ -86,7 +92,7 @@ keeps, per channel, the raw lines of each blocking request still open: - closed by the matching `host_tool_result` / `extension_ui_response` written to stdin, or a `host_tool_cancel` / UI cancel from omp. -`hello` carries them per channel (`channels[{ch, sessionId, pending: string[]}]`, +`hello` carries them per channel (`channels[{ch, sessionId, cwd, pending: string[]}]`, capped at 1 MB per channel; over the cap the channel is not adoptable and takes the kill-and-resume path). The adopted wrapper feeds them through its normal frame handling, so dialogs reappear, input-needed notifications fire, and browser @@ -99,8 +105,11 @@ drops `rpc_chunk` records until the first record of a new frame, and sends `negotiate_protocol` again. **Adoption failure** (any of the re-sync commands time out after -`GET_STATE_TIMEOUT_MS`): the child is killed and resumed once through the -existing orphan path, so no session ends up with two writers. +`GET_STATE_TIMEOUT_MS`, the child exits or its held output overflows, or its +real session, as `get_state` names it, is already started on this server): the +child is killed and resumed once through the existing orphan path, so no +session ends up with two writers. A web server that is itself shutting down +leaves the child to the next one. Auto-resume remains for children that really died: a daemon restart, a crash, or an adoption failure. @@ -141,8 +150,12 @@ from the same release: - It restarts `ompweb-api` with the existing probes and rollback. - It restarts `ompweb-host` only when the release's `LINK_PROTOCOL_VERSION` - differs from the running daemon's (read from `GET /api/hosts`). -- Rollback restores the previous release for both units. + differs from the running daemon's. The script reads the daemon's from the + release its process was started from (`/proc//cmdline`); + `GET /api/hosts` (local row, `hostVersion`) says the same but sits behind + the web password. +- Rollback restores the previous release for both units, and restarts the + daemon only if the cutover did. ## Dev mode From 7922455d6b03ca9c9af599388ee1778030264680 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:41:39 +0000 Subject: [PATCH 23/36] fix(hosts): an adopted child's request opened during shutdown is delivered once, and a stale response settles no command A request omp opened while the old server stopped is both in the daemon's hello (replayed) and resent unacked (held): release() now skips held requests the replay delivered, which also stops a host call being parked twice. A response whose command differs from the pending one with that id (the old server's late answer: adopted ids restart at w1) surfaces as unsolicited. --- lib/hosts/link-integration.test.mjs | 62 +++++++++++++++++++++++++--- lib/omp/rpc-process-runtime.test.mjs | 33 +++++++++++++++ lib/omp/rpc-process.ts | 19 +++++++-- 3 files changed, 106 insertions(+), 8 deletions(-) diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 3b24d8b00..c14a17c91 100644 --- a/lib/hosts/link-integration.test.mjs +++ b/lib/hosts/link-integration.test.mjs @@ -117,6 +117,16 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l }, 25); return; } + if (command.message === "late") { + // An ask and an agent tool call, once the test creates the go file. + const timer = setInterval(() => { + if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) return; + clearInterval(timer); + out({ type: "extension_ui_request", id: "q2", method: "ask", questions: [{ id: "q", question: "Late", options: [{ label: "B" }] }] }); + out({ type: "host_tool_call", id: "h2", toolCallId: "c2", toolName: "send_to_session", arguments: { sessionId: ${JSON.stringify("11111111-2222-4333-8444-000000000001")}, message: "hi" } }); + }, 25); + return; + } if (command.message === "slow") { for (let i = 1; i <= ${SLOW_HALF}; i++) update(i); let sent = ${SLOW_HALF}; @@ -153,16 +163,18 @@ const SMALL_ID = "11111111-2222-4333-8444-000000000001"; const BIG_ID = "11111111-2222-4333-8444-000000000002"; const ASK_ID = "11111111-2222-4333-8444-000000000003"; const TOOL_ID = "11111111-2222-4333-8444-000000000004"; +const LATE_ID = "11111111-2222-4333-8444-000000000005"; const smallFile = writeSession("2026-01-01_small.jsonl", SMALL_ID, ["hello", "hi"]); const askFile = writeSession("2026-01-03_ask.jsonl", ASK_ID, ["ask me", "sure"]); const toolFile = writeSession("2026-01-04_tool.jsonl", TOOL_ID, ["use a tool", "ok"]); +const lateFile = writeSession("2026-01-05_late.jsonl", LATE_ID, ["late", "ok"]); writeSession("2026-01-02_big.jsonl", BIG_ID, Array.from({ length: 200 }, (_, i) => `${i} ${"x".repeat(10_000)}`)); assert.ok(statSync(join(sessionsDir, "-project", "2026-01-02_big.jsonl")).size > 2_000_000); // Faults the adapter injects once each, and what it observed. const faults = { loseStdin: false, cutUplinkBeforeApply: false, cutUplinkAfterApply: false }; -// `kills`: the channel of each `kill` main sent down to the daemon; `refusedPosts`: uplink POSTs answered 503. -const seen = { cuts: [], blobUploads: 0, posting: 0, kills: [], refusedPosts: 0 }; +// `kills`: the channel of each `kill` main sent down to the daemon; `refusedPosts`: the bodies of uplink POSTs answered 503. +const seen = { cuts: [], blobUploads: 0, posting: 0, kills: [], refusedPosts: [] }; const server = createServer(async (req, res) => { const url = new URL(req.url, "http://127.0.0.1"); @@ -193,7 +205,7 @@ const server = createServer(async (req, res) => { return; } response = await linkRoute.POST(request()); - if (response.status === 503) seen.refusedPosts += 1; + if (response.status === 503) seen.refusedPosts.push(body.toString()); if (faults.cutUplinkAfterApply && carriesFrames) { // Applied, but the ack never reaches the daemon: it must resend. faults.cutUplinkAfterApply = false; @@ -475,14 +487,14 @@ test("a stopping web server sends nothing more and takes nothing in: a closing t adopted.set(this, events); return adopt.call(this, replay); }; - const refusedBefore = seen.refusedPosts; + const refusedBefore = seen.refusedPosts.length; await restartWeb({ async whileStopping() { // The tab's connection closes with the server: a live server answers its open call with an error. leave(); // omp sends more output while the server stops. writeFileSync(slowGo(TOOL_ID), ""); - await waitFor(() => seen.refusedPosts > refusedBefore, "an uplink POST refused while stopping"); + await waitFor(() => seen.refusedPosts.length > refusedBefore, "an uplink POST refused while stopping"); }, }); assert.equal(ompLog().some((entry) => entry.command?.type === "host_tool_result"), false, "no rejection reached omp"); @@ -503,3 +515,43 @@ test("a stopping web server sends nothing more and takes nothing in: a closing t assert.equal(stopping().length, 1, "delivered once"); assert.deepEqual(ompLog().filter((entry) => entry.command?.type === "host_tool_result").map((entry) => entry.command.result.content[0].text), ["opened"]); }); + +test("a request omp opens while the web server stops reaches the next server once: one dialog, one agent tool result", async (t) => { + const adopt = AgentSessionWrapper.prototype.adopt; + t.after(() => { + AgentSessionWrapper.prototype.adopt = adopt; + }); + const { session } = await startRpcSession(LATE_ID, lateFile, projectDir, undefined, false, projectDir, undefined, hub.getHost(hostId)); + let started = false; + session.onEvent((event) => { + if (event.type === "agent_start") started = true; + }); + await session.send({ type: "prompt", message: "late" }); + await waitFor(() => started, "the run"); + + const adopted = new Map(); + AgentSessionWrapper.prototype.adopt = function (replay) { + const events = []; + this.onEvent((event) => events.push(event), { internal: true }); + adopted.set(this, events); + return adopt.call(this, replay); + }; + const refusedBefore = seen.refusedPosts.length; + await restartWeb({ + async whileStopping() { + writeFileSync(slowGo(LATE_ID), ""); + // The stopping server acks neither line: the daemon lists both in its hello and resends both. + const refused = () => seen.refusedPosts.slice(refusedBefore).join(""); + await waitFor(() => refused().includes("q2") && refused().includes("send_to_session"), "both requests refused while stopping"); + }, + }); + + await waitFor(() => getRpcSession(LATE_ID), "the adoption"); + const events = adopted.get(getRpcSession(LATE_ID)); + const results = () => ompLog().filter((entry) => entry.command?.type === "host_tool_result" && entry.command.id === "h2"); + await waitFor(() => results().length > 0, "the agent tool result"); + // Room for a second delivery to show up. + await sleep(300); + assert.equal(events.filter((event) => event.type === "extension_ui_request" && event.id === "q2").length, 1, "one dialog"); + assert.equal(results().length, 1, "one agent tool result"); +}); diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index b9e6c79dc..bd36717fa 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -354,6 +354,39 @@ test("an adopted RpcProcess needs no ready, skips a chunk tail, and holds live f await proc.dispose(0); }); +test("an adopted RpcProcess delivers a request both replayed and held once", async () => { + const requests = [ + { type: "extension_ui_request", id: "q1", method: "ask" }, + { type: "host_tool_call", id: "h1", toolName: "send_to_session" }, + { type: "host_uri_request", id: "u1", url: "x:1" }, + ]; + // Opened while the old server stopped: the daemon resends each unacked and lists it in its hello. + const transport = makeAdoptedTransport([...requests, { type: "host_tool_call", id: "h2" }].map((record) => JSON.stringify(record))); + const proc = new RpcProcess({ cwd: process.cwd(), transport, adopted: { protocolVersion: 2 } }); + const frames = []; + proc.onFrame((frame) => frames.push(frame.id)); + proc.replay(requests.map((record) => JSON.stringify(record))); + proc.release(); + assert.deepEqual(frames, ["q1", "h1", "u1", "h2"]); + await proc.dispose(0); +}); + +test("a response naming another command does not settle a command with its id", async () => { + const transport = makeAdoptedTransport([]); + const proc = new RpcProcess({ cwd: process.cwd(), transport, adopted: { protocolVersion: 2 } }); + proc.release(); + const unsolicited = []; + proc.onFrame((frame) => unsolicited.push(frame.command)); + transport.answer = (command) => { + // An adopted RpcProcess numbers from w1 again: the old server's late answer to its own w1 arrives first. + transport.send({ type: "response", id: command.id, command: "prompt", success: false, error: "stale" }); + transport.send({ type: "response", id: command.id, command: command.type, success: true, data: { sessionId: "s" } }); + }; + assert.deepEqual(await proc.sendCommand({ type: "get_state" }, 1_000), { sessionId: "s" }); + assert.deepEqual(unsolicited, ["prompt"]); + await proc.dispose(0); +}); + test("an adopted RpcProcess whose output outgrows the hold cap fails its commands and its replay", async () => { const { LINK_LIMITS } = jiti("../hosts/link-protocol.ts"); const saved = LINK_LIMITS.channelBufferBytes; diff --git a/lib/omp/rpc-process.ts b/lib/omp/rpc-process.ts index afd052fde..198a43211 100644 --- a/lib/omp/rpc-process.ts +++ b/lib/omp/rpc-process.ts @@ -99,6 +99,9 @@ function parseLine(line: string): unknown { } } +const REQUEST_TYPES = new Set(["host_tool_call", "host_uri_request", "extension_ui_request"]); +const requestId = (frame: RpcFrame) => (REQUEST_TYPES.has(frame.type) && typeof frame.id === "string" ? frame.id : null); + /** Spawns the installed omp in RPC mode with the sanitized child environment. */ export function spawnOmpTransport(options: RpcProcessOptions): RpcTransport { const resolveBin = options.dependencies?.resolveOmpBin ?? resolveOmpBin; @@ -130,6 +133,8 @@ export class RpcProcess { private heldBytes = 0; /** Set once an adopted child's output outgrew the cap before `release`: the adoption fails. */ private heldOverflow: Error | null = null; + /** Ids of the requests `replay` delivered (see `release`). */ + private readonly replayedRequests = new Set(); private nextId = 1; private stderrTail = ""; private exited = false; @@ -244,12 +249,17 @@ export class RpcProcess { } } - /** Adopted child, after `replay`: delivers the frames held since and stops holding. */ + /** Adopted child, after `replay`: delivers the frames held since and stops holding. A request + * opened while the old server stopped is in both (replayed, and resent unacked): it is delivered once. */ release(): void { if (this.heldOverflow) throw this.heldOverflow; const held = this.heldFrames ?? []; this.heldFrames = null; - for (const frame of held) this.dispatch(frame); + for (const frame of held) { + const id = requestId(frame); + if (id === null || !this.replayedRequests.has(id)) this.dispatch(frame); + } + this.replayedRequests.clear(); } /** @@ -304,6 +314,8 @@ export class RpcProcess { this.heldFrames.push(frame); return; } + const id = replayed ? requestId(frame) : null; + if (id !== null) this.replayedRequests.add(id); for (const listener of this.frameListeners) { try { listener(frame); @@ -394,7 +406,8 @@ export class RpcProcess { private handleResponse(response: RpcResponseFrame): void { const id = response.id; const entry = id ? this.pending.get(id) : undefined; - if (!entry || !id) { + // An adopted child numbers from w1 again: a late answer to the old server's command of another type is not this one's. + if (!entry || !id || (response.command && response.command !== entry.command)) { // Unsolicited response (or a command we already timed out) — surface to // frame listeners so nothing is silently dropped. this.dispatch(response as unknown as RpcFrame); From aee7baf404cdec682db02de54b9a4d007daba9d7 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:43:00 +0000 Subject: [PATCH 24/36] fix(hosts): an adopted run keeps extension auto-approve The flag came only from a spawn result, so a run adopted after a web restart stopped at every Allow tool: confirm. The daemon now reports it in hello (link v3 is unreleased) and openDownlink applies it. --- docs/specs/2026-10-29-local-daemon-design.md | 6 +++++- lib/hosts/daemon.test.mjs | 17 +++++++++++++++++ lib/hosts/daemon.ts | 1 + lib/hosts/hosts-route.test.mjs | 2 +- lib/hosts/hub.test.mjs | 8 +++++++- lib/hosts/hub.ts | 1 + lib/hosts/link-driver.test-helper.mjs | 2 +- lib/hosts/link-protocol.test.mjs | 8 +++++--- lib/hosts/link-protocol.ts | 3 +++ 9 files changed, 41 insertions(+), 7 deletions(-) diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index 11c5bda93..e79f6db41 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -96,7 +96,11 @@ keeps, per channel, the raw lines of each blocking request still open: capped at 1 MB per channel; over the cap the channel is not adoptable and takes the kill-and-resume path). The adopted wrapper feeds them through its normal frame handling, so dialogs reappear, input-needed notifications fire, and browser -tool calls reach a tab again. This changes the hello shape, so +tool calls reach a tab again. A request opened while the old server was stopping +is also resent as unacked output; the adopted wrapper delivers it once (the +replayed copy). `hello` also carries `autoApproveExtension` (the host's +`tools.approval.extension: allow`), which a spawn result reported before: an +adopted run has no spawn. This changes the hello shape, so `LINK_PROTOCOL_VERSION` becomes 3. **Framing.** omp answers `negotiate_protocol` every time, and every ompweb child diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index 8aaf21e91..f1d3bf5cc 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -151,6 +151,23 @@ test("an http:// loopback server links without --allow-http", async () => { } }); +test("the hello reports this host's extension auto-approve", async () => { + const log = captureLog(); + const config = join(process.env.PI_CODING_AGENT_DIR, "config.yml"); + mkdirSync(dirname(config), { recursive: true }); + writeFileSync(config, "tools:\n approval:\n extension: allow\n"); + const server = scriptedServer(); + const daemon = start(server); + try { + await waitFor(() => server.hellos.length === 1, "the hello"); + assert.equal(server.hellos[0].autoApproveExtension, true); + } finally { + await daemon.stop(); + rmSync(config, { force: true }); + log.restore(); + } +}); + test("hostnames that only look like loopback need --allow-http", () => { for (const url of ["http://localhost.evil.com", "http://127.0.0.1.nip.io", "http://evil-localhost", "http://127.0.0.1@example.com"]) { assert.throws(() => runHostDaemon({ url, token: "t", allowHttp: false, fetch: async () => Response.json({}, { status: 503 }) }), /https:\/\//, url); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 151e61e2c..2c31ec5c4 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -509,6 +509,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: ompVersion, platform: process.platform, home: homedir(), + autoApproveExtension: localHost.autoApproveExtension(), ack: down.acked, channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.pending.sessionId, cwd: channel.cwd, pending: replay ? channel.pending.lines() : null })), }); diff --git a/lib/hosts/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index 3619955ee..ec400398d 100644 --- a/lib/hosts/hosts-route.test.mjs +++ b/lib/hosts/hosts-route.test.mjs @@ -28,7 +28,7 @@ const get = async () => (await route.GET()).json(); /** The daemon's dial: POST the hello, then GET the downlink with its id. A refused hello is returned as is. */ async function linkGet(token) { - const hello = { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/h", ack: 0, channels: [] }; + const hello = { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/h", autoApproveExtension: false, ack: 0, channels: [] }; const offered = await hub.handleLinkPost(new Request(`${BASE}/link`, { method: "POST", headers: { authorization: `Bearer ${token}`, [LINK_HELLO_HEADER]: "1" }, diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index c708d18c5..aa704060f 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -29,7 +29,7 @@ test.afterEach(() => Object.assign(hub.linkTimings, defaultTimings)); const URL_BASE = "http://main.test/api/hosts/link"; function hello(overrides = {}) { - return { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/home/u", ack: 0, channels: [], ...overrides }; + return { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/home/u", autoApproveExtension: false, ack: 0, channels: [], ...overrides }; } /** POST a hello, as the daemon does before opening its downlink. */ @@ -686,6 +686,12 @@ test("archive and project-update results must have the fields the routes read", await link.down.cancel(); }); +test("the hello carries the host's extension auto-approve: an adopted run spawned nothing to report it", async () => { + const link = await linkedHost("Auto-approver", { autoApproveExtension: true }); + assert.equal(link.remote.autoApproveExtension(), true); + await link.down.cancel(); +}); + test("RemoteHost spawns over the link and its transport replays output sent before subscription", async () => { const link = await linkedHost("Spawner"); const { req, spawning, result, post } = await spawnOverLink(link); diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index bf8ba5e46..d05610d25 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -383,6 +383,7 @@ function openDownlink(link: Link, hello: Hello, signal: AbortSignal): Response { link.ompVersion = hello.ompVersion; link.platform = hello.platform; + link.autoApprove = hello.autoApproveExtension; sawDaemon(link); persistLastSeen(link); clearInterval(link.pingTimer); diff --git a/lib/hosts/link-driver.test-helper.mjs b/lib/hosts/link-driver.test-helper.mjs index f675384f4..5ad513859 100644 --- a/lib/hosts/link-driver.test-helper.mjs +++ b/lib/hosts/link-driver.test-helper.mjs @@ -91,7 +91,7 @@ export class LinkDriver { /** POST a hello, then GET the downlink with its id; resolves after its welcome. */ async dial({ channels = [], ack = this.ack } = {}) { - const hello = { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/home/u", ack, channels }; + const hello = { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/home/u", autoApproveExtension: false, ack, channels }; const offered = await hub.handleLinkPost(new Request(URL_BASE, { method: "POST", headers: { authorization: `Bearer ${this.token}`, [LINK_HELLO_HEADER]: "1" }, diff --git a/lib/hosts/link-protocol.test.mjs b/lib/hosts/link-protocol.test.mjs index 4ed306bdb..ecde202be 100644 --- a/lib/hosts/link-protocol.test.mjs +++ b/lib/hosts/link-protocol.test.mjs @@ -24,6 +24,7 @@ const UP = [ ompVersion: null, platform: "darwin", home: "/Users/me", + autoApproveExtension: true, ack: 3, channels: [ { ch: "c1", sessionId: "s1", cwd: "/Users/me/project", pending: ['{"type":"host_tool_call","id":"t1"}'] }, @@ -109,9 +110,10 @@ test("decode rejects malformed lines with LinkProtocolError", async () => { '{"type":"exit","seq":1,"ch":"c","code":"0","signal":null}', '{"type":"res","seq":1,"id":"a"}', '{"type":"res","seq":1,"id":"a","ok":false,"error":{"code":"x","message":"y"}}', - '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"cwd":"/w"}]}', - '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"cwd":"/w","pending":[1]}]}', - '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[{"ch":"c","sessionId":null,"pending":[]}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","autoApproveExtension":false,"ack":0,"channels":[{"ch":"c","sessionId":null,"cwd":"/w"}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","autoApproveExtension":false,"ack":0,"channels":[{"ch":"c","sessionId":null,"cwd":"/w","pending":[1]}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","autoApproveExtension":false,"ack":0,"channels":[{"ch":"c","sessionId":null,"pending":[]}]}', + '{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","ack":0,"channels":[]}', ]; for (const line of bad) { assert.throws(() => decodeUp(line), LinkProtocolError, line); diff --git a/lib/hosts/link-protocol.ts b/lib/hosts/link-protocol.ts index 3b10cd076..5a5c81957 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -93,6 +93,8 @@ export type UpMessage = ompVersion: string | null; platform: string; home: string; + /** omp's `tools.approval.extension: allow` on the host: a run adopted after a web restart had no spawn to report it. */ + autoApproveExtension: boolean; ack: number; channels: HelloChannel[]; } @@ -257,6 +259,7 @@ export function decodeUp(line: string): UpMessage { ompVersion: nullable(o, "ompVersion", str), platform: str(o, "platform"), home: str(o, "home"), + autoApproveExtension: bool(o, "autoApproveExtension"), ack: int(o, "ack"), channels: channels(o), }; From da2cd0d6be643eabdd7218a357ee3c4da0db2123 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:45:16 +0000 Subject: [PATCH 25/36] fix(hosts): load the session-edit extension from the package, not the daemon's cwd The --extension path was built from process.cwd(), which the web launcher sets to the package root but a daemon unit sets to HOME: omp failed to load the extension and history editing was unavailable. The path now comes from local-host's own location (daemon-only). --- lib/hosts/daemon.test.mjs | 18 ++++++++++++++++++ lib/hosts/local-host.ts | 5 ++++- lib/hosts/no-direct-local.test.mjs | 1 + lib/omp/session-edit.native.test.mjs | 4 +++- lib/omp/session-edit.ts | 3 --- lib/rpc-manager.test.mjs | 2 +- 6 files changed, 27 insertions(+), 6 deletions(-) diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index f1d3bf5cc..86fd8e1f1 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -1,8 +1,10 @@ import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import test, { after } from "node:test"; +import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; // The daemon in-process against a scripted server (the `fetch` option). @@ -168,6 +170,22 @@ test("the hello reports this host's extension auto-approve", async () => { } }); +test("a spawned omp loads the session-edit extension whatever the daemon's working directory", () => { + const argvFile = join(scratch, "argv.json"); + const recorder = join(scratch, process.platform === "win32" ? "argv-omp.cmd" : "argv-omp"); + writeFakeOmp(recorder, `require("node:fs").writeFileSync(${JSON.stringify(argvFile)}, JSON.stringify(process.argv));`); + const localHostFile = fileURLToPath(new URL("./local-host.ts", import.meta.url)); + // A daemon unit runs in HOME, not in the package: a fresh process, as the module resolves the path on load. + const script = `const { createJiti } = await import(${JSON.stringify(import.meta.resolve("jiti"))}); +const { localHost } = await createJiti(${JSON.stringify(localHostFile)}).import(${JSON.stringify(localHostFile)}); +await localHost.spawnRpc({ cwd: ${JSON.stringify(scratch)}, recordedCwd: null, sessionFile: "", advisor: false });`; + const child = spawnSync(process.execPath, ["--input-type=module", "-e", script], { cwd: scratch, env: { ...process.env, OMP_WEB_OMP_BIN: recorder }, encoding: "utf8" }); + assert.equal(child.status, 0, child.stderr); + const args = JSON.parse(readFileSync(argvFile, "utf8")); + const extension = args[args.indexOf("--extension") + 1]; + assert.ok(existsSync(extension), extension); +}); + test("hostnames that only look like loopback need --allow-http", () => { for (const url of ["http://localhost.evil.com", "http://127.0.0.1.nip.io", "http://evil-localhost", "http://127.0.0.1@example.com"]) { assert.throws(() => runHostDaemon({ url, token: "t", allowHttp: false, fetch: async () => Response.json({}, { status: 503 }) }), /https:\/\//, url); diff --git a/lib/hosts/local-host.ts b/lib/hosts/local-host.ts index 9391a2911..900b51b1c 100644 --- a/lib/hosts/local-host.ts +++ b/lib/hosts/local-host.ts @@ -1,9 +1,9 @@ import { existsSync, realpathSync, statSync } from "fs"; import { homedir } from "os"; +import { fileURLToPath } from "url"; import { comparableProjectPath } from "../comparable-path"; import { getAgentEnvOverrides } from "../omp/agent-env"; import { spawnOmpTransport } from "../omp/rpc-process"; -import { SESSION_EDIT_EXTENSION_PATH } from "../omp/session-edit"; import { readNativeSettings } from "../omp/settings-config"; import { isReservedLaunchArg, loadProjectRegistry } from "../project-registry"; import { invalidateSessionEntriesCache, invalidateSessionListCache, invalidateSessionListMeta } from "../session-reader"; @@ -12,6 +12,9 @@ import type { ProjectLaunchConfig } from "../types"; import type { Host } from "./host"; import { sessionOps } from "./session-ops"; +/** omp loads it for history edits (#278). Next to this module, not in the cwd: the daemon runs in HOME. */ +export const SESSION_EDIT_EXTENSION_PATH = fileURLToPath(new URL("../omp/session-edit-extension.mjs", import.meta.url)); + // omp aliases "find"->"glob" and has no "ls" tool; the web UI presets still use // the pi names (lib/tool-presets.ts), so translate before building --tools. const TOOL_NAME_ALIASES: Record = { find: "glob", search: "grep" }; diff --git a/lib/hosts/no-direct-local.test.mjs b/lib/hosts/no-direct-local.test.mjs index 80a653877..39139926d 100644 --- a/lib/hosts/no-direct-local.test.mjs +++ b/lib/hosts/no-direct-local.test.mjs @@ -19,6 +19,7 @@ const DIRECT_LOCAL_ALLOWED = new Set([ "lib/hosts/link-driver.test-helper.mjs", // local-host's spawn arguments and spawn path. "lib/rpc-manager.test.mjs", + "lib/hosts/daemon.test.mjs", "lib/hosts/no-direct-local.test.mjs", ]); diff --git a/lib/omp/session-edit.native.test.mjs b/lib/omp/session-edit.native.test.mjs index 107cb5b6b..4209126e5 100644 --- a/lib/omp/session-edit.native.test.mjs +++ b/lib/omp/session-edit.native.test.mjs @@ -6,11 +6,13 @@ import { createServer } from "node:http"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import test from "node:test"; +import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; import { SESSION_EDIT_COMMAND, SESSION_EDIT_RESPONSE_PREFIX } from "./session-edit-extension.mjs"; const jiti = createJiti(import.meta.url); -const { editSessionHistory, SESSION_EDIT_EXTENSION_PATH } = await jiti.import("./session-edit.ts"); +const { editSessionHistory } = await jiti.import("./session-edit.ts"); +const SESSION_EDIT_EXTENSION_PATH = fileURLToPath(new URL("./session-edit-extension.mjs", import.meta.url)); const { RpcProcess, RpcCommandTimeoutError } = await jiti.import("./rpc-process.ts"); const { resolveOmpBin } = await jiti.import("./omp-cli.ts"); const { buildSessionContext } = await jiti.import("../session-reader.ts"); diff --git a/lib/omp/session-edit.ts b/lib/omp/session-edit.ts index e328531ad..e55e69042 100644 --- a/lib/omp/session-edit.ts +++ b/lib/omp/session-edit.ts @@ -1,12 +1,9 @@ import { randomUUID } from "node:crypto"; -import path from "node:path"; import { RpcCommandTimeoutError, type RpcFrame, type RpcProcess } from "./rpc-process"; import type { RpcAvailableSlashCommand } from "../pi-types"; import { SESSION_EDIT_COMMAND, SESSION_EDIT_RESPONSE_PREFIX } from "./session-edit-extension.mjs"; export { SESSION_EDIT_COMMAND }; -// Next's dev/start commands and the installed launcher run in the package root. -export const SESSION_EDIT_EXTENSION_PATH = path.join(process.cwd(), "lib", "omp", "session-edit-extension.mjs"); const EDIT_TIMEOUT_MS = 15_000; export interface SessionEditResult { diff --git a/lib/rpc-manager.test.mjs b/lib/rpc-manager.test.mjs index d44843d4d..7411e9226 100644 --- a/lib/rpc-manager.test.mjs +++ b/lib/rpc-manager.test.mjs @@ -2554,7 +2554,7 @@ test("initial spawn and reload both keep same-session editing available through const sessionFile = join(isolatedAgentDir, "edit-spawn-and-reload.jsonl"); writeFileSync(sessionFile, JSON.stringify({ type: "session", version: 3, id: sessionId, cwd: isolatedAgentDir }) + "\n"); t.after(() => rmSync(sessionFile, { force: true })); - const { SESSION_EDIT_EXTENSION_PATH } = await runtimeJiti.import("./omp/session-edit.ts"); + const { SESSION_EDIT_EXTENSION_PATH } = await runtimeJiti.import("./hosts/local-host.ts"); const spawns = []; let editCount = 0; const spawnReplacement = (file, args) => { From 8cff534c5b38d6a925715aa019c8b1eaa1ca1331 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:47:07 +0000 Subject: [PATCH 26/36] refactor(hosts): host.json helpers move to host-login.ts, so the web bundle does not pull in the daemon local-bootstrap imported loginHost/readHostLogin/isLoopbackHost from daemon.ts, which drags local-host, session-ops and spawn code into the web server. The no-direct-local guard now also flags imports of daemon. --- AGENTS.md | 5 ++-- bin/omp-web-host.js | 5 ++-- lib/hosts/daemon.ts | 37 +++------------------------- lib/hosts/host-login.ts | 39 ++++++++++++++++++++++++++++++ lib/hosts/local-bootstrap.ts | 2 +- lib/hosts/no-direct-local.test.mjs | 8 +++--- 6 files changed, 54 insertions(+), 42 deletions(-) create mode 100644 lib/hosts/host-login.ts diff --git a/AGENTS.md b/AGENTS.md index 42668dca0..ce361d887 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -109,12 +109,13 @@ lib/ omp/ shared omp foundations (paths, CLI probe, RpcProcess) hosts/ hosts and the local daemon (see "Remote hosts"); none of the daemon-loaded files may import `next/*` or `@/` host.ts `Host` interface, `HostStatus`, `isLinkUp` - local-host.ts `localHost`, the daemon's side: spawn + file checks on the daemon's machine; `resolveSpawnCwdResult`. Never imported by main (`no-direct-local.test.mjs`) + local-host.ts `localHost`, the daemon's side: spawn + file checks on the daemon's machine; `resolveSpawnCwdResult`; `SESSION_EDIT_EXTENSION_PATH` (from the module's own location: the daemon runs in HOME). Never imported by main, nor is `daemon.ts` (`no-direct-local.test.mjs`) 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) link-protocol.ts link messages, codec, size limits, `HOST_OP_NAMES`, `SeqWindow`/`Outbox` hub.ts main side: link GET/POST/blob handlers, `RemoteHost`, `getHost`, `listHosts`, adoption of live children (`reattach`/`adopt`), orphans, `freezeHostLinks`, `hosts` change events - daemon.ts daemon side: `loginHost`, `readHostLogin`, `runHostDaemon` (reconnect, buffering, op dispatch, hello with each child's `{sessionId, cwd, pending}`) + daemon.ts daemon side: `runHostDaemon` (reconnect, buffering, op dispatch, hello with each child's `{sessionId, cwd, pending}`; follows a `host.json` url or token change when a dial fails; loopback redials at most 3 s apart) pending-requests.ts daemon side: `PendingRequests`, a channel's still-open blocking requests and current session id for the hello registry.ts `/omp-web/hosts.json`: create/update/revoke, token hashing and lookup; the `local` record (`rotateLocalHostToken`, `customLocalLabel`) session-index.ts sessions and projects across hosts, cached per host; `hostForSessionId`, `sessionSpawnTarget`, `invalidateLocalSessionLists` diff --git a/bin/omp-web-host.js b/bin/omp-web-host.js index 8a8247c93..49c6244b4 100755 --- a/bin/omp-web-host.js +++ b/bin/omp-web-host.js @@ -38,8 +38,8 @@ function readTokenLine() { async function main(argv) { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { createJiti } = require("jiti"); - const { loginHost, readHostLogin, runHostDaemon } = await createJiti(__filename).import("../lib/hosts/daemon.ts"); + const jiti = require("jiti").createJiti(__filename); + const { loginHost, readHostLogin } = await jiti.import("../lib/hosts/host-login.ts"); if (argv[0] === "login") { const urlIndex = argv.indexOf("--url"); @@ -62,6 +62,7 @@ async function main(argv) { console.error("This machine is not linked yet. Start ompweb on this machine (it writes the link), or run `ompweb host login --url `."); return 1; } + const { runHostDaemon } = await jiti.import("../lib/hosts/daemon.ts"); const daemon = runHostDaemon({ ...login, allowHttp: argv.includes("--allow-http") }); for (const signal of ["SIGINT", "SIGTERM"]) process.once(signal, () => void daemon.stop()); return daemon.done; diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index 2c31ec5c4..b511d40bb 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -1,16 +1,17 @@ // `ompweb host` (spec "Daemon"): links this machine to a main omp-web, runs // the omp children it asks for and answers host ops with this machine's files. // bin/omp-web-host.js loads it through jiti: no `next/*` or `@/` imports. -import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { lstatSync, realpathSync } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { getOmpVersion } from "../omp/omp-cli"; -import { getAgentDir, getSessionsDir } from "../omp/paths"; +import { getSessionsDir } from "../omp/paths"; import type { RpcTransport } from "../omp/rpc-transport"; import { readSessionHeaderSync } from "../omp/session-files"; import { ProjectPathError } from "../project-registry"; import { isRecord } from "../type-guards"; +import { isLoopbackHost, readHostLogin } from "./host-login"; import { decodeDown, encodeLine, @@ -60,42 +61,12 @@ interface Queued { ch: string | null; } -const loginFile = () => join(getAgentDir(), "omp-web", "host.json"); const trimUrl = (url: string) => url.replace(/\/+$/, ""); const reason = (error: unknown) => (error instanceof Error ? error.message : String(error)); const log = (message: string) => console.error(`[ompweb host] ${message}`); // 1 s doubling to 60 s; each wait varies ±20% so many hosts do not redial in step. const withJitter = (ms: number) => ms * (0.8 + Math.random() * 0.4); -/** Save the server URL and host token, owner-only. The token never goes through argv. */ -export function loginHost(options: { url: string; token: string }): void { - const { protocol } = new URL(options.url); - if (protocol !== "https:" && protocol !== "http:") throw new Error("The server URL must start with https:// or http://"); - const token = options.token.trim(); - if (!token) throw new Error("The host token is empty"); - const file = loginFile(); - mkdirSync(dirname(file), { recursive: true }); - // A fresh 0600 file renamed into place: the token never sits in a wider-mode file. - const temp = `${file}.${process.pid}.tmp`; - try { - writeFileSync(temp, `${JSON.stringify({ url: options.url.replace(/\/+$/, ""), token })}\n`, { mode: 0o600 }); - renameSync(temp, file); - } finally { - rmSync(temp, { force: true }); - } -} - -/** What `loginHost` saved, or null before the first login. */ -export function readHostLogin(): { url: string; token: string } | null { - try { - const saved: unknown = JSON.parse(readFileSync(loginFile(), "utf8")); - if (isRecord(saved) && typeof saved.url === "string" && typeof saved.token === "string") return { url: saved.url, token: saved.token }; - } catch { - // Missing or unreadable: not logged in. - } - return null; -} - /** realpath of the longest existing prefix; null when a component is a dangling symlink. */ function canonicalPath(path: string): string | null { try { @@ -123,8 +94,6 @@ function sessionsPath(value: unknown): string { return target; } -export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname); - async function* readLines(body: ReadableStream): AsyncGenerator { const reader = body.getReader(); const decoder = new TextDecoder(); diff --git a/lib/hosts/host-login.ts b/lib/hosts/host-login.ts new file mode 100644 index 000000000..66e06348f --- /dev/null +++ b/lib/hosts/host-login.ts @@ -0,0 +1,39 @@ +// The daemon's saved link (`/omp-web/host.json`), shared by `ompweb host` +// and the web server (local-bootstrap): no daemon or spawn code, no `next/*` or `@/` imports. +import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { getAgentDir } from "../omp/paths"; +import { isRecord } from "../type-guards"; + +const loginFile = () => join(getAgentDir(), "omp-web", "host.json"); + +export const isLoopbackHost = (hostname: string) => hostname === "localhost" || hostname === "[::1]" || /^127(\.\d{1,3}){3}$/.test(hostname); + +/** Save the server URL and host token, owner-only. The token never goes through argv. */ +export function loginHost(options: { url: string; token: string }): void { + const { protocol } = new URL(options.url); + if (protocol !== "https:" && protocol !== "http:") throw new Error("The server URL must start with https:// or http://"); + const token = options.token.trim(); + if (!token) throw new Error("The host token is empty"); + const file = loginFile(); + mkdirSync(dirname(file), { recursive: true }); + // A fresh 0600 file renamed into place: the token never sits in a wider-mode file. + const temp = `${file}.${process.pid}.tmp`; + try { + writeFileSync(temp, `${JSON.stringify({ url: options.url.replace(/\/+$/, ""), token })}\n`, { mode: 0o600 }); + renameSync(temp, file); + } finally { + rmSync(temp, { force: true }); + } +} + +/** What `loginHost` saved, or null before the first login. */ +export function readHostLogin(): { url: string; token: string } | null { + try { + const saved: unknown = JSON.parse(readFileSync(loginFile(), "utf8")); + if (isRecord(saved) && typeof saved.url === "string" && typeof saved.token === "string") return { url: saved.url, token: saved.token }; + } catch { + // Missing or unreadable: not logged in. + } + return null; +} diff --git a/lib/hosts/local-bootstrap.ts b/lib/hosts/local-bootstrap.ts index 3a5042b79..f1a4e6c45 100644 --- a/lib/hosts/local-bootstrap.ts +++ b/lib/hosts/local-bootstrap.ts @@ -1,6 +1,6 @@ // The web server's side of the local daemon link: keep the `local` host record // and the daemon's host.json in step. Pure Node: no Next or `@/` imports. -import { isLoopbackHost, loginHost, readHostLogin } from "./daemon"; +import { isLoopbackHost, loginHost, readHostLogin } from "./host-login"; import { hostForToken, LOCAL_HOST_ID, rotateLocalHostToken } from "./registry"; /** Where the daemon dials this server, or why it cannot: the daemon uses plain http only on loopback, so a bind address elsewhere gets no link. */ diff --git a/lib/hosts/no-direct-local.test.mjs b/lib/hosts/no-direct-local.test.mjs index 39139926d..e83487491 100644 --- a/lib/hosts/no-direct-local.test.mjs +++ b/lib/hosts/no-direct-local.test.mjs @@ -8,10 +8,12 @@ import { fileURLToPath } from "node:url"; const ROOT = fileURLToPath(new URL("../../", import.meta.url)); -/** Files that may reach this machine's direct spawn and file path: the daemon's side, and tests that exercise it. */ +/** Files that may reach this machine's direct spawn and file path (local-host, or daemon, which imports it): the daemon's side, and tests that exercise it. */ const DIRECT_LOCAL_ALLOWED = new Set([ "lib/hosts/daemon.ts", "lib/hosts/local-host.ts", + // `ompweb host`: runs the daemon. + "bin/omp-web-host.js", // Define the spawn transports. "lib/omp/rpc-process.ts", "lib/omp/rpc-transport.ts", @@ -31,7 +33,7 @@ const BARE_RPC_PROCESS_ALLOWED = new Set([ "lib/omp/session-edit.native.test.mjs", ]); -const DIRECT_LOCAL_RE = /["'`][^"'`\n]*\blocal-host(?:\.ts)?["'`]|\b(?:spawnLocalRpcTransport|spawnOmpTransport)\b/; +const DIRECT_LOCAL_RE = /["'`][^"'`\n]*(?:\blocal-host|\/daemon)(?:\.ts)?["'`]|\b(?:spawnLocalRpcTransport|spawnOmpTransport)\b/; function sourceFiles(dir) { return readdirSync(join(ROOT, dir), { withFileTypes: true }).flatMap((entry) => { @@ -67,7 +69,7 @@ function check(allowed, flags) { return { outside: flagged.filter((path) => !allowed.has(path)), stale: [...allowed].filter((path) => !flagged.includes(path)) }; } -test("only the daemon's side reaches local-host, spawnLocalRpcTransport or spawnOmpTransport", () => { +test("only the daemon's side reaches local-host, daemon, spawnLocalRpcTransport or spawnOmpTransport", () => { assert.deepEqual(check(DIRECT_LOCAL_ALLOWED, (code) => DIRECT_LOCAL_RE.test(code)), { outside: [], stale: [] }); }); From bb4f03c420b92efe8cfd8699e9cdc76ea3b0c04a Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:53:19 +0000 Subject: [PATCH 27/36] fix(hosts): the daemon follows a host.json url change, and redials this machine's web server at most 3 s apart After a failed dial the daemon re-reads host.json and dials the url and token it names now, if it could have started with that url (https, or http on loopback or with --allow-http). A web server restarted on another port was otherwise offline until the daemon restarted, ending every run. Loopback redials cap at 3 s instead of 60 s. --- README.md | 4 +- docs/specs/2026-10-29-local-daemon-design.md | 6 ++- lib/hosts/daemon.test.mjs | 49 +++++++++++++++++++- lib/hosts/daemon.ts | 46 ++++++++++++++---- 4 files changed, 94 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 612977c9b..326983a58 100644 --- a/README.md +++ b/README.md @@ -370,7 +370,9 @@ npx @kahme247/ompweb@latest host --allow-http ``` If the connection drops, the daemon reconnects by itself (1 s backoff doubling to -60 s). After a network drop, runs keep going on the remote machine; the chat shows +60 s; 3 s at most for the web server on the same machine). After a failed dial it +re-reads its saved link, so a web server that came back on another port is found +without restarting the daemon. After a network drop, runs keep going on the remote machine; the chat shows an offline banner and the runs reattach when the link returns. A laptop that goes to sleep (closing the lid, usually) pauses the daemon and its omp runs along with everything else on it: they resume when it wakes, and the link returns then. A diff --git a/docs/specs/2026-10-29-local-daemon-design.md b/docs/specs/2026-10-29-local-daemon-design.md index e79f6db41..0c6480e3b 100644 --- a/docs/specs/2026-10-29-local-daemon-design.md +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -56,7 +56,10 @@ ompweb (web service) ──link over 127.0.0.1──▶ ompweb host (daemon se `/omp-web/host.json` (`{url, token}`, mode 0600) with its own loopback URL. The daemon re-reads `host.json` when its link gets 401, so a web server that regenerated the token is picked up without restarting the - daemon. Loopback links use `http://` without `--allow-http`. + daemon, and after every failed dial, so a web server that came back on + another port is followed (a URL it could not have started with, such as + plain http elsewhere without `--allow-http`, is ignored). Loopback links use + `http://` without `--allow-http` and redial at most 3 s apart. ## Adopting live children @@ -128,6 +131,7 @@ or an adoption failure. | Dev server running | It never writes `host.json`, so the daemon stays linked to production; dev shows "This machine" offline. | | Daemon not installed or not running | "This machine" shows offline with "start the ompweb-host service"; new local sessions are disabled. | | `host.json` token stale (web regenerated it) | Daemon gets 401, re-reads `host.json`, redials. It exits only if the file still holds the rejected token. | +| Web server moved to another port | The dial to the old port fails; the daemon re-reads `host.json` and dials the new URL. | ## Installing and upgrading diff --git a/lib/hosts/daemon.test.mjs b/lib/hosts/daemon.test.mjs index 86fd8e1f1..3dc365b34 100644 --- a/lib/hosts/daemon.test.mjs +++ b/lib/hosts/daemon.test.mjs @@ -51,7 +51,7 @@ require("node:readline").createInterface({ input: process.stdin }).on("line", (l `); const jiti = createJiti(import.meta.url); -const { runHostDaemon } = await jiti.import("./daemon.ts"); +const { nextRedialDelay, runHostDaemon } = await jiti.import("./daemon.ts"); const { LINK_HELLO_HEADER, LINK_LIMITS, LINK_NONCE_HEADER } = await jiti.import("./link-protocol.ts"); const { RpcFrameDecoder } = await jiti.import("../omp/rpc-frame.ts"); const { RpcProcess } = await jiti.import("../omp/rpc-process.ts"); @@ -625,6 +625,53 @@ test("a newer token for the same url is adopted when it differs only by a traili } }); +/** The web server moved from port 9 to port 10: dials to port 9 fail. Each dialed port lands in `dialed`. */ +function movedServer(server, dialed) { + return (url, init) => { + const { port } = new URL(url); + dialed.push(port); + return port === "10" ? server.fetch(url, init) : Promise.reject(new TypeError("fetch failed")); + }; +} + +test("a failed dial re-reads host.json and follows its new url", async () => { + const log = captureLog(); + const server = scriptedServer(); + mkdirSync(dirname(hostJson), { recursive: true }); + writeFileSync(hostJson, JSON.stringify({ url: "http://127.0.0.1:10", token: "t" })); + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "t", allowHttp: false, fetch: movedServer(server, []) }); + try { + await waitFor(() => server.hellos.length === 1, "the link to the new url"); + } finally { + await daemon.stop(); + rmSync(hostJson, { force: true }); + log.restore(); + } +}); + +test("a host.json url the daemon could not have started with is not followed", async () => { + const log = captureLog(); + mkdirSync(dirname(hostJson), { recursive: true }); + writeFileSync(hostJson, JSON.stringify({ url: "http://example.com:10", token: "t" })); + const dialed = []; + const daemon = runHostDaemon({ url: "http://127.0.0.1:9", token: "t", allowHttp: false, fetch: movedServer(scriptedServer(), dialed) }); + try { + await waitFor(() => dialed.length >= 2, "a redial"); + assert.deepEqual([...new Set(dialed)], ["9"]); + } finally { + await daemon.stop(); + rmSync(hostJson, { force: true }); + log.restore(); + } +}); + +test("a loopback link redials at most 3 s apart; another server's waits double to 60 s", () => { + assert.equal(nextRedialDelay(2_000, "http://127.0.0.1:30178"), 3_000); + assert.equal(nextRedialDelay(2_000, "http://localhost:30178"), 3_000); + assert.equal(nextRedialDelay(2_000, "https://main.example.com"), 4_000); + assert.equal(nextRedialDelay(40_000, "https://main.example.com"), 60_000); +}); + test("a blob upload refused with 401 after the web server re-keyed retries with the new token", async () => { const log = captureLog(); const server = scriptedServer({ validToken: "old" }); diff --git a/lib/hosts/daemon.ts b/lib/hosts/daemon.ts index b511d40bb..53d76fe18 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -37,6 +37,8 @@ import { sessionOps } from "./session-ops"; const FIRST_RETRY_MS = 1_000; const MAX_RETRY_MS = 60_000; +// This machine's web server is back within seconds of a restart. +const LOOPBACK_MAX_RETRY_MS = 3_000; /** Children still running this long after SIGTERM get SIGKILL. */ const KILL_GRACE_MS = 5_000; const PONG_LINE = encodeLine({ type: "pong" }); @@ -64,9 +66,24 @@ interface Queued { const trimUrl = (url: string) => url.replace(/\/+$/, ""); const reason = (error: unknown) => (error instanceof Error ? error.message : String(error)); const log = (message: string) => console.error(`[ompweb host] ${message}`); -// 1 s doubling to 60 s; each wait varies ±20% so many hosts do not redial in step. +// Each wait varies ±20% so many hosts do not redial in step. const withJitter = (ms: number) => ms * (0.8 + Math.random() * 0.4); +/** The redial wait after `delay`: doubling to 60 s, or to 3 s for a server on this machine. */ +export function nextRedialDelay(delay: number, url: string): number { + return Math.min(delay * 2, isLoopbackHost(new URL(url).hostname) ? LOOPBACK_MAX_RETRY_MS : MAX_RETRY_MS); +} + +/** A URL the daemon dials: https, or http on loopback or with --allow-http. */ +function dialable(url: string, allowHttp: boolean): boolean { + try { + const { protocol, hostname } = new URL(url); + return protocol === "https:" || (protocol === "http:" && (allowHttp || isLoopbackHost(hostname))); + } catch { + return false; + } +} + /** realpath of the longest existing prefix; null when a component is a dangling symlink. */ function canonicalPath(path: string): string | null { try { @@ -120,13 +137,13 @@ async function* readLines(body: ReadableStream): AsyncGenerator; done: Promise } { - const { protocol, hostname } = new URL(options.url); - if (protocol !== "https:" && !(protocol === "http:" && (options.allowHttp || isLoopbackHost(hostname)))) { + if (!dialable(options.url, options.allowHttp)) { throw new Error("ompweb host needs an https:// server URL (http:// only for loopback, or with --allow-http)"); } const fetchLink = options.fetch ?? fetch; - const linkUrl = `${options.url.replace(/\/+$/, "")}/api/hosts/link`; - // Replaced when a 401 finds a newer token in host.json (the web server re-keyed this host). + // Both follow host.json: a 401 finds a newer token there (the web server re-keyed this host), a failed dial a new url or token. + let serverUrl = trimUrl(options.url); + let linkUrl = `${serverUrl}/api/hosts/link`; let authorization = `Bearer ${options.token}`; const channels = new Map(); @@ -264,7 +281,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: if (status === 401 && sent === authorization) { const saved = readHostLogin(); // Only a host.json for this same server counts: one that names another server is not this daemon's link. - if (saved && trimUrl(saved.url) === trimUrl(options.url) && `Bearer ${saved.token}` !== sent) { + if (saved && trimUrl(saved.url) === serverUrl && `Bearer ${saved.token}` !== sent) { authorization = `Bearer ${saved.token}`; log("the server rejected this host's token; using the new one from host.json"); } else { @@ -279,6 +296,18 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: return stopped; } + /** host.json names another url or token now (the web server came back on another port): dial with those. */ + function followLogin(): void { + const saved = readHostLogin(); + if (!saved || !dialable(saved.url, options.allowHttp)) return; + const url = trimUrl(saved.url); + if (url === serverUrl && `Bearer ${saved.token}` === authorization) return; + log(`host.json changed; dialing ${url}`); + serverUrl = url; + linkUrl = `${url}/api/hosts/link`; + authorization = `Bearer ${saved.token}`; + } + function forgetLink(): void { nonce = null; welcome = Promise.withResolvers(); @@ -295,7 +324,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } switch (message.type) { case "welcome": - log(`linked to ${options.url}`); + log(`linked to ${serverUrl}`); nonce = message.nonce; welcome.resolve(); // A fresh link: resend what main has not acked now, not after the old backoff. @@ -523,11 +552,12 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } catch (error) { if (stopped) return; log(`link lost (${reason(error)}); redialing`); + followLogin(); } finally { clearTimeout(watchdog); } await sleep(withJitter(redialDelay), undefined, { signal: stopSignal.signal }).catch(() => {}); - redialDelay = Math.min(redialDelay * 2, MAX_RETRY_MS); + redialDelay = nextRedialDelay(redialDelay, serverUrl); } } From d6a589e4f9305f734f47a7dd033ec9c123e5f2be Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:54:25 +0000 Subject: [PATCH 28/36] test(hosts): a stopping server takes no hello; a closed request frees its pending bytes Both guards on the hello (POST and the downlink GET) were redundant with each other and untested, as was the byte accounting that keeps answered requests from making later ones non-adoptable. --- lib/hosts/hub.test.mjs | 15 +++++++++++++++ lib/hosts/pending-requests.test.mjs | 12 ++++++++++++ 2 files changed, 27 insertions(+) diff --git a/lib/hosts/hub.test.mjs b/lib/hosts/hub.test.mjs index aa704060f..2099cf275 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -629,6 +629,21 @@ test("an adoption cut short by this server's shutdown leaves the child to the ne assert.equal(messages.some((message) => /killing/.test(message)), false); }); +test("a stopping server takes no hello: neither its POST nor the downlink GET of one offered before", async (t) => { + const { host, token } = createHost("Hello at shutdown"); + t.after(() => { + globalThis.__ompHostHub.frozen = false; + hub.closeHostLink(host.id); + }); + const offered = await linkHello(token); + assert.equal(offered.status, 200); + const { helloId } = await offered.json(); + hub.freezeHostLinks(); + assert.equal((await openDown(token, helloId)).status, 503, "the GET of an earlier hello"); + assert.equal((await linkHello(token)).status, 503, "a new hello"); + assert.equal(hub.getHost(host.id).status(), "offline", "nothing the daemon said was applied"); +}); + for (const [op, call, value] of [ ["archiveSession", (ops, id) => ops.archiveSession(id), { archivedPath: "/a" }], ["deleteSession", (ops, id) => ops.deleteSession(id, []), {}], diff --git a/lib/hosts/pending-requests.test.mjs b/lib/hosts/pending-requests.test.mjs index 4bdf3a11e..8f87b9a45 100644 --- a/lib/hosts/pending-requests.test.mjs +++ b/lib/hosts/pending-requests.test.mjs @@ -109,6 +109,18 @@ test("past limitBytes lines() is null until the oversized request closes", () => assert.equal(pending.lines().length, 1); }); +test("a closed request frees its bytes: answered traffic past limitBytes leaves later requests adoptable", () => { + const pending = new PendingRequests(1000); + // Each request takes about a third of the cap; ten of them, each answered, total three caps. + for (let i = 0; i < 10; i++) { + pending.noteStdout(line({ type: "host_tool_call", id: `t${i}`, toolName: "browser", arguments: { pad: "x".repeat(300) } })); + pending.noteStdin(line({ type: "host_tool_result", id: `t${i}`, result: { content: [] } })); + } + const open = line({ type: "host_tool_call", id: "last", toolName: "browser", arguments: { pad: "x".repeat(300) } }); + pending.noteStdout(open); + assert.deepEqual(pending.lines(), [open]); +}); + test("non-blocking UI requests and garbage lines are not kept", () => { const pending = new PendingRequests(LIMIT); pending.noteStdout(line({ type: "extension_ui_request", id: "n1", method: "notify", message: "hi" })); From 4c057ec1761a1acea7376990da4c50f5b5a4dbd8 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:54:43 +0000 Subject: [PATCH 29/36] fix(hosts): a failed adoption kills its child once adoptRpcSession already kills a child it cannot adopt (its wrapper's dispose escalates to SIGKILL); the hub's second killOrphan was redundant. --- lib/hosts/hub.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/hosts/hub.ts b/lib/hosts/hub.ts index d05610d25..bd50d7383 100644 --- a/lib/hosts/hub.ts +++ b/lib/hosts/hub.ts @@ -455,8 +455,8 @@ async function adopt(link: Link, child: RemoteRpcTransport, sessionId: string, c // Nothing reaches the daemon now, a kill included: the child runs on for the next server. console.warn(`[omp-web] left the omp child of session ${sessionId} on ${labelOf(link.id)} to the next server: this one stopped while adopting it (${reason})`); } else { + // adoptRpcSession has already killed it (its wrapper's dispose escalates to SIGKILL). console.warn(`[omp-web] killing the omp child of session ${sessionId} on ${labelOf(link.id)}: it could not be adopted (${reason})`); - killOrphan(child); } return false; } From e91435f6d07daef18053f73e11bae82b2dfd1328 Mon Sep 17 00:00:00 2001 From: Andre Brait Date: Fri, 30 Oct 2026 00:56:33 +0000 Subject: [PATCH 30/36] fix(hosts): tell a foreground ompweb to keep `ompweb host` running A terminal or npx ompweb installs no service, so nothing runs the daemon and This machine stays offline. The banner and the Settings hint now show `ompweb host` next to the service install command (all locales), and the README says so. The launcher does not start the daemon: one started by it would die with it. --- AGENTS.md | 2 +- README.md | 6 ++++++ components/HostsConfig.test.mjs | 7 ++++--- components/HostsConfig.tsx | 2 ++ components/LocalDaemonBanner.test.mjs | 4 +++- components/LocalDaemonBanner.tsx | 4 +++- docs/specs/2026-10-29-local-daemon-design.md | 10 ++++++---- lib/i18n/locales/en.json | 1 + lib/i18n/locales/ja.json | 1 + lib/i18n/locales/zh-CN.json | 1 + 10 files changed, 28 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ce361d887..0d66f7a80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -388,7 +388,7 @@ bin/ - **The daemon replays open blocking requests** (`pending-requests.ts`): `host_tool_call`, `host_uri_request` and blocking `extension_ui_request` lines, until answered or cancelled, capped at `LINK_LIMITS.pendingBytes` per channel. An adopted wrapper feeds them through `handleFrame` (`replaying`; agent tools are not re-run), so dialogs reappear and browser tool calls wait for the next tab (`hostToolsUnknown`, `parkHostTool`). - **A child is killed (`killOrphan`) only when it cannot be adopted:** its hello entry has no session id or lost its `pending` lines to the cap, a re-sync command times out or the child exits, its held output overflows, or its real session (after `get_state`) is already started on this server. Auto-resume (`resumeOnHostLink`) first awaits `adoptedChild()` and resumes a session only if it was not adopted. - **Shutdown freezes the links and never kills daemon children.** The `cleanup` in `rpc-manager.ts` runs `markShuttingDown()` and `freezeHostLinks()`: from then on a link neither sends nor applies anything (no kill, no rejection of open host tool calls as tabs close; the daemon's POSTs get 503 "shutting down"). The daemon keeps the output unacked for the next server. An adoption that fails after the freeze leaves its child to the next server instead of killing it. -- **Install banner** (`components/LocalDaemonBanner.tsx`). In production, when the local row stays offline with `hostVersion === null` (no daemon has linked since this server started) for 90 s of a page view (longer than the daemon's 60 s redial backoff cap, so a restarting daemon does not trip it), it shows the platform's install command; dismissal is kept in `localStorage`. Main never installs services. +- **Install banner** (`components/LocalDaemonBanner.tsx`). In production, when the local row stays offline with `hostVersion === null` (no daemon has linked since this server started) for 90 s of a page view (well past the daemon's redial wait, at most 3 s on loopback, so a restarting daemon does not trip it), it shows the platform's install command and, for a foreground `ompweb` (terminal or npx, no service), `ompweb host` to keep running in another terminal; Settings → Hosts shows both for an offline local row. Dismissal is kept in `localStorage`. Main never installs services or starts the daemon. - **No direct local path.** `local-host.ts` is the daemon's; `lib/hosts/no-direct-local.test.mjs` fails when anything outside its allow-list spawns omp or imports it. The utility omp (`rpc-utility.ts`, login) is the one deliberate exception: it is not a session. ### Session moves (omp >= 18.5 ownership) and title generation diff --git a/README.md b/README.md index 326983a58..e09eb0598 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,12 @@ linked to the web server over loopback. The service installers (`ompweb systemd `ompweb launchd install`, `ompweb --install-tray`) install both: the web service and `ompweb-host`. Uninstall removes both. +**Running ompweb in the foreground** (`ompweb` in a terminal, or `npx +@kahme247/ompweb@latest`) installs no service, so nothing runs the daemon: keep +`ompweb host` (with npx: `npx @kahme247/ompweb@latest host`) running in a +second terminal. Without it "This machine" stays offline. The web server writes +the daemon's link when it starts, so start the web server first. + - **Restarting or redeploying the web server does not interrupt runs.** The daemon keeps the omp processes running; the restarted web server takes them over, with no resume prompt, and dialogs or tool calls omp was waiting on reappear. diff --git a/components/HostsConfig.test.mjs b/components/HostsConfig.test.mjs index 6bbcd71f8..cb4223014 100644 --- a/components/HostsConfig.test.mjs +++ b/components/HostsConfig.test.mjs @@ -83,9 +83,10 @@ test("an offline this-machine row says to start the service, with the server's i send([row({})]); const hint = await screen.findByText(/ompweb-host service/); - assert.equal(hint.closest("li").querySelector("code").textContent, "ompweb launchd install"); - // The command is copyable; the local row still has no Revoke. - assert.deepEqual([...hint.closest("li").querySelectorAll("button")].map((button) => button.textContent), ["Copy", "Rename"]); + assert.deepEqual([...hint.closest("li").querySelectorAll("code")].map((code) => code.textContent), ["ompweb launchd install", "ompweb host"]); + assert.match(hint.closest("li").textContent, /in a terminal or with npx/); + // The commands are copyable; the local row still has no Revoke. + assert.deepEqual([...hint.closest("li").querySelectorAll("button")].map((button) => button.textContent), ["Copy", "Copy", "Rename"]); send([row({ serverPlatform: "linux" })]); assert.equal((await screen.findByText(/ompweb-host service/)).closest("li").querySelector("code").textContent, "ompweb systemd install"); diff --git a/components/HostsConfig.tsx b/components/HostsConfig.tsx index a15cd21a6..9f5518a1f 100644 --- a/components/HostsConfig.tsx +++ b/components/HostsConfig.tsx @@ -133,6 +133,8 @@ function HostCard({ host, onRename, onRevoke }: { host: HostRow; onRename: () =>
{t("hostsConfig.localOfflineHint")} + {t("hostsConfig.localForegroundHint")} +
)}
diff --git a/components/LocalDaemonBanner.test.mjs b/components/LocalDaemonBanner.test.mjs index 780489e11..7d81d8457 100644 --- a/components/LocalDaemonBanner.test.mjs +++ b/components/LocalDaemonBanner.test.mjs @@ -44,7 +44,9 @@ test("the install banner appears after 90 s offline, once: dismissing it keeps i assert.equal(screen.queryByText(text), null); act(() => t.mock.timers.tick(1)); assert.ok(screen.getByText(text).textContent.startsWith("This machine needs the ompweb-host service. Install it with:")); - assert.equal(screen.getByRole("status").querySelector("code").textContent, "ompweb systemd install"); + // A foreground ompweb (terminal or npx) has no service: it needs `ompweb host` running beside it. + assert.deepEqual([...screen.getByRole("status").querySelectorAll("code")].map((code) => code.textContent), ["ompweb systemd install", "ompweb host"]); + assert.match(screen.getByRole("status").textContent, /in a terminal or with npx/); fireEvent.click(screen.getByRole("button", { name: "Dismiss" })); assert.equal(screen.queryByText(text), null); diff --git a/components/LocalDaemonBanner.tsx b/components/LocalDaemonBanner.tsx index bb35276ac..524ac6419 100644 --- a/components/LocalDaemonBanner.tsx +++ b/components/LocalDaemonBanner.tsx @@ -8,7 +8,7 @@ import { CopyField } from "./HostsConfig"; import { hostName, isLocalRow, localInstallCommand } from "./host-status"; export const LOCAL_DAEMON_BANNER_DISMISSED_KEY = "omp-web:local-daemon-banner-dismissed"; -// Longer than the daemon's 60 s redial backoff cap, so a restarting daemon does not trip it. +// Well past the daemon's redial wait (at most 3 s on loopback), so a restarting daemon does not trip it. export const LOCAL_DAEMON_GRACE_MS = 90_000; /** One-time hint to install the ompweb-host service: this machine has not linked since this server started and 90 s have passed. */ @@ -54,6 +54,8 @@ export function LocalDaemonBanner() {
{t("hostsConfig.localDaemonBanner", { host: hostName(t, local) })} + {t("hostsConfig.localForegroundHint")} +