diff --git a/AGENTS.md b/AGENTS.md index 43657d629..f04474faf 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? } @@ -107,15 +107,18 @@ 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`; `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`, orphans, `hosts` change events - daemon.ts remote side: `loginHost`, `readHostLogin`, `runHostDaemon` (reconnect, buffering, op dispatch) - 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: `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` 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) @@ -178,6 +181,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 @@ -235,27 +239,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 @@ -266,13 +276,29 @@ 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, `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` means a fresh daemon: main restarts that host's uplink window. Wire shapes and size limits live in `lib/hosts/link-protocol.ts` (one op allow-list, `HOST_OP_NAMES`, shared by both sides); the spec is `docs/specs/2026-10-28-remote-hosts-design.md`. +- **Link protocol versions** (spec "Protocol versions and compatibility"). A + released `LINK_PROTOCOL_VERSION` changes only compatibly: an added optional + field or a message type receivers skip is fine; a changed type or meaning, or + a newly required field, needs a new version. Receivers skip unknown message + types (acking their `seq`) and answer unknown ops 501 `unknown_op`, from v3 on; + a v2 daemon is strict. Main keeps supporting older + daemons, at least N-1, from `MIN_LINK_PROTOCOL_VERSION` (2) up; dropping one is + an explicit decision (a daemon on a dropped version gets 426; an update-only + mode is planned). For an older daemon main decodes its hello into today's shape + (`decodeUp`), sends only messages that version understands, and echoes its + version in `welcome` and `hostVersion`; a v2 daemon's listed children are + killed, never adopted. Upgrade order: web app first, then hosts; a daemon need + not support a newer main (it gets 426). - **One link per host, and the 409 nonce rule.** A new link with the same token replaces the old one (`replaced` is sent, the old daemon exits); two daemons must never run competing `omp --resume` children on one agent dir. Each @@ -316,17 +342,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 @@ -365,6 +392,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 the running daemon's link version is outside the new release's `[MIN_LINK_PROTOCOL_VERSION, LINK_PROTOCOL_VERSION]` range (it would get 426 and exit); a daemon inside the range keeps running. +- **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 request opened while the old server stopped is also resent unacked: `RpcProcess.release` skips held requests the replay already delivered, so it is handled once. The hello also carries `autoApproveExtension`, which an adopted run has no spawn result for. +- **A child is killed only when it cannot be adopted:** its hello entry has no session id, lost its `pending` lines to the cap, or came from a v2 hello (`killOrphan`), or 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 (`adoptRpcSession` kills it: its wrapper's dispose). 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 (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 - 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 @@ -707,13 +746,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. @@ -721,6 +760,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 9e395eed8..739937744 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,14 @@ 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. An `ompweb` run in a terminal or with npx installs no service: keep `ompweb host` running in a second terminal. Restarting the daemon still ends runs, and `ompweb systemd restart` leaves it alone. If the web server comes back on another port, the daemon follows it. A `npm run dev` server does not take over the daemon. "This machine" can be renamed in **Settings → Hosts**. ### 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. +- **Upgrade ompweb before its hosts.** The web server links a host daemon one link protocol version older than its own, so a host keeps running sessions until its `ompweb` is updated; after a web restart that daemon's live runs are resumed rather than adopted. A daemon older than that, or newer than the web server, is still asked to upgrade. - **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/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 348a77ef9..8def0093d 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,8 @@ 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 launchd install # Install the macOS launchd agents (web + ompweb-host daemon) ompweb --help # Show help ompweb --version # Show version ``` @@ -171,6 +172,37 @@ 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. + +**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. +- **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 its link protocol version + is outside the range the new release supports. +- **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 +218,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 +255,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 +299,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 @@ -339,7 +376,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 @@ -348,13 +387,16 @@ 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. - 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. +- **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 its + link protocol version is outside the range the server supports (older than the + server's oldest supported version, or newer than the server: update ompweb on + the older side), and `0` when a newer link for the same host replaces it. SIGTERM or SIGINT stops the daemon and its omp processes. A link is one-per-host, so never run two daemons with the same token. - **The server's agent directory holds the host list** (`omp-web/hosts.json`). @@ -535,6 +577,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/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/hosts/route.ts b/app/api/hosts/route.ts index 06f7be6e5..583093187 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) { @@ -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/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]/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/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/bin/linux-tray.js b/bin/linux-tray.js index f34c978cc..0547d77ab 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,15 +451,17 @@ 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" }, { 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" }, @@ -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..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"); @@ -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-host.js b/bin/omp-web-host.js index 107683457..49c6244b4 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(); @@ -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"); @@ -59,9 +59,10 @@ 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 { 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/bin/omp-web-launchd.js b/bin/omp-web-launchd.js index 906dbd9ef..84e79c818 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,44 @@ 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`))} + + +`; +} + +// 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"); @@ -118,73 +159,73 @@ 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" }); + const host = buildPlist({ + label: HOST_LABEL, + args: [npxBin, "--yes", pkg, "host"], + 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, + }); 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]]) { + // 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 }); + 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, buildHostEnv, buildPlist }; diff --git a/bin/omp-web-launchd.test.mjs b/bin/omp-web-launchd.test.mjs new file mode 100644 index 000000000..f780eeee0 --- /dev/null +++ b/bin/omp-web-launchd.test.mjs @@ -0,0 +1,39 @@ +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, buildHostEnv, 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>/); +}); + +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 9e267d01d..c43563036 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 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 @@ -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,37 @@ 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])); + // 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 }); - fs.writeFileSync(UNIT_PATH, unit, { mode: 0o600 }); - fs.chmodSync(UNIT_PATH, 0o600); + for (const [unitPath, text] of [[UNIT_PATH, buildUnit(unitOptions)], [HOST_UNIT_PATH, hostUnitText]]) { + 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 }); + 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}`); 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 +403,71 @@ 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 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", UNIT]); - console.log(`started: ${UNIT_NAME}`); + const units = installedUnits(); + systemctl(["start", ...units]); + console.log(`started: ${unitNames(units)}`); } function stop() { - systemctl(["stop", UNIT]); - console.log(`stopped: ${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", UNIT]); console.log(`restarted: ${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 +482,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 +601,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..f5ad17a42 100644 --- a/bin/omp-web-systemd.test.mjs +++ b/bin/omp-web-systemd.test.mjs @@ -1,13 +1,14 @@ 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"; const require = createRequire(import.meta.url); const { + buildHostUnit, buildUnit, escapeUnitPath, escapeUnitValue, @@ -79,6 +80,29 @@ 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/); + // 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'); +}); + 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 +221,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 }); @@ -290,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/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/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 && ( { 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,76 @@ 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" }); +}); + +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", 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.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"); + send([row({ serverPlatform: "win32" })]); + 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)); +}); + +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", 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] }) } })); + 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 59871f76d..9f5518a1f 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, 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 (
@@ -51,8 +51,10 @@ 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 hintId = useId(); const [created, setCreated] = useState<{ token: string; command: string } | null>(null); const submit = async (event: FormEvent) => { @@ -92,11 +94,12 @@ function HostDialog({ dialog, onClose }: { dialog: NonNullable; onClose
void submit(event)} style={{ display: "flex", flexDirection: "column", gap: 12 }}> + {local && {t("hostsConfig.localNameHint")}}
-
@@ -126,23 +129,35 @@ function HostCard({ host, onRename, onRevoke }: { host: HostRow; onRename: () => {hostStatusText(t, host)}
{details &&
{details}
} + {isLocalRow(host) && host.daemonManaged && host.status === "offline" && ( +
+ {t("hostsConfig.localOfflineHint")} + + {t("hostsConfig.localForegroundHint")} + +
+ )} - {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/LocalDaemonBanner.test.mjs b/components/LocalDaemonBanner.test.mjs new file mode 100644 index 000000000..7d81d8457 --- /dev/null +++ b/components/LocalDaemonBanner.test.mjs @@ -0,0 +1,89 @@ +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", 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 }) } })); +}; +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 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(89_999)); + 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:")); + // 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); + 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(200_000)); + assert.equal(screen.queryByText(text), null); +}); + +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(30_000)); + send([local({ status: "online", hostVersion: 3 })]); + 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(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 new file mode 100644 index 000000000..524ac6419 --- /dev/null +++ b/components/LocalDaemonBanner.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { X } from "lucide-react"; +import { useHostRows } from "@/hooks/useHostRows"; +import { useI18n } from "@/lib/i18n"; +import { CopyField } from "./HostsConfig"; +import { hostName, isLocalRow, localInstallCommand } from "./host-status"; + +export const LOCAL_DAEMON_BANNER_DISMISSED_KEY = "omp-web:local-daemon-banner-dismissed"; +// 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. */ +export function LocalDaemonBanner() { + const { t } = useI18n(); + const { hosts } = useHostRows(); + 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); + + useEffect(() => { + try { + setDismissed(window.localStorage.getItem(LOCAL_DAEMON_BANNER_DISMISSED_KEY) === "true"); + } catch { + setDismissed(false); + } + }, []); + + useEffect(() => { + if (!missing) return; + const timer = setTimeout(() => setWaited(true), LOCAL_DAEMON_GRACE_MS); + return () => { + clearTimeout(timer); + setWaited(false); + }; + }, [missing]); + + const dismiss = () => { + setDismissed(true); + try { + window.localStorage.setItem(LOCAL_DAEMON_BANNER_DISMISSED_KEY, "true"); + } catch { + // Dismissed for this page view only. + } + }; + // The live region stays mounted so screen readers announce the banner when it appears. + return ( +
+ {local && missing && waited && !dismissed && ( +
+
+ {t("hostsConfig.localDaemonBanner", { host: hostName(t, local) })} + + {t("hostsConfig.localForegroundHint")} + +
+ +
+ )} +
+ ); +} 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 9c91ba6d1..dc0f5855f 100644 --- a/components/host-status.ts +++ b/components/host-status.ts @@ -1,12 +1,20 @@ -import type { HostRow } from "@/lib/hosts/hub"; +import type { HostRow, LocalHostRow } from "@/lib/hosts/hub"; 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 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"; + return platform === "win32" ? "ompweb-tray install" : "ompweb systemd install"; } export function hostStatusText(t: Translate, host: HostRow): string { 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..0c59fb23e --- /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. 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). + +--- + +### 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:" })` — 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.** +- [ ] **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 running daemon's link version (`GET /api/hosts`, local row `hostVersion`) is outside the new release's `[MIN_LINK_PROTOCOL_VERSION, LINK_PROTOCOL_VERSION]` range; 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-28-remote-hosts-design.md b/docs/specs/2026-10-28-remote-hosts-design.md index 06122e1d1..dc93a8642 100644 --- a/docs/specs/2026-10-28-remote-hosts-design.md +++ b/docs/specs/2026-10-28-remote-hosts-design.md @@ -196,14 +196,21 @@ On 409 the daemon keeps the messages and sends them after the next ### Rules -- **Version.** `v` is an integer bumped on any incompatible change (2: the - hello moved from the GET header into a POST body). On a mismatch the link - request gets 426 with both versions, and so does a v1 daemon's GET carrying - its hello in the header; the daemon exits with "upgrade omp-web on this - host"; Settings → Hosts shows "needs upgrade (host vN, server vM)". A hello - POST answered 400, 404, 405 or 409 without a `helloId` comes from an older - main (v1 answers a POST without a link nonce 409): the daemon logs "the - server runs an older ompweb: upgrade it" and exits 1 instead of redialing. +- **Version.** `v` is an integer, bumped on any incompatible change (2: the + hello moved from the GET header into a POST body; 3: the hello carries + `autoApproveExtension` and each channel its `cwd` and `pending`). Main links + daemons from `MIN_LINK_PROTOCOL_VERSION` (2) up to its own + `LINK_PROTOCOL_VERSION`, and its `welcome` carries the version the link + speaks, the daemon's (see "Protocol versions and compatibility"). Any other + version, older or newer than main, gets 426 with both versions, and so does a + v1 daemon's GET carrying its hello in the header; the daemon exits, telling + which side to update ("update ompweb on this host", or "this host's ompweb is + newer than the server's: update ompweb on the server" when the 426's + `serverVersion` is below its own); Settings → Hosts shows "needs upgrade (host + vN, server vM)". A hello POST answered 400, 404, 405 or 409 without a + `helloId` comes from an older main (v1 answers a POST without a link nonce + 409): the daemon logs "the server runs an older ompweb: upgrade it" and exits + 1 instead of redialing. - **Identity.** The host is the record whose `tokenHash` matches. Nothing the daemon sends selects or changes its identity. - **One link per host.** A new link with the same token replaces the old one, @@ -239,6 +246,48 @@ On 409 the daemon keeps the messages and sends them after the next over-limit requests get 413. A single `stdout` line over 8 MB is dropped and replaced by `resync {ch}`. +### Protocol versions and compatibility + +- **A released version changes only compatibly.** Compatible means both: every + message the newer side can send is valid for an older receiver, and every + message the older side can send is valid for a newer receiver. Anything else + needs a new `LINK_PROTOCOL_VERSION`. + - Compatible: a sender starting to always include a field the receiver + already accepts as optional; adding an optional field (decoders ignore + fields they do not know); adding a message type that receivers ignore when + unknown. + - Not compatible: making a field the receiver requires optional for + senders; changing a field's type or meaning; a receiver starting to + require a field older senders may omit. + - Receivers tolerate what they do not know: an unknown message type (valid + envelope: a string `type` and, where the direction numbers messages, a + non-negative safe-integer `seq`) is skipped, its `seq` still applied and + acked so it is never resent and later messages are not blocked. A known + type arriving the wrong way (`stdout` on the downlink) is skipped and acked + the same way. Each side logs an unknown type once per link (at most 16 + distinct types, escaped and cut to 64 characters) and a wrong-way message + each time (at most 16 per link). An unknown host op in a `req` is answered `res {ok: false, error: + {status: 501, code: "unknown_op"}}`, which main surfaces as a 501 + `HostOpError` so callers can fall back. A sender must not rely on a newer + message being understood unless the version (or, later, a capability) says + so. Tolerance starts with v3: a v2 daemon is strict (an unknown type or op + makes it refuse the line), so main sends a v2 daemon only messages and ops + v2 understands. +- **Older versions stay supported** until supporting one becomes too much of a + maintenance burden; dropping one is an explicit decision (raising + `MIN_LINK_PROTOCOL_VERSION`). In practice main keeps at least version N-1. + For an older daemon main decodes its hello into today's shape and sends only + messages that version understands. A daemon on a dropped version gets 426; + an update-only mode for it is planned, separately. +- **Upgrade order: web app first, then hosts.** Main supports older daemons; a + daemon is not required to support a newer main, and one newer than main gets + 426. `hostVersion` (Settings → Hosts) is the version a linked daemon speaks, + so Settings can later show "update available" for one behind the server. +- **v2 daemons** (N-1 today): their hello has no `autoApproveExtension` (read + as false until a spawn result reports it) and no channel `cwd` or `pending`, + so their listed children are never adopted: they take the kill-and-resume + path. v2 and v3 have the same down messages, host ops and HTTP legs. + ## Host ops (this sub-project) Every op name is in one allow-list shared by both sides; the daemon rejects 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..cdd42e288 --- /dev/null +++ b/docs/specs/2026-10-29-local-daemon-design.md @@ -0,0 +1,196 @@ +# 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 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 + +- 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" 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 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 + 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, 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 + +On `hello`, for each listed `{ch, sessionId, cwd, pending}` that has no wrapper +on the web server: + +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 + 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. + +**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, 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 +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; the web server still links v2 daemons (their +children are killed and resumed, never adopted; see the remote-hosts spec, +"Protocol versions and compatibility"). + +**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 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. + +## 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). | +| Daemon one link protocol version behind the web server (N-1) | Links and runs sessions; after a web restart its live children are killed and resumed on `hello`, not adopted (a v2 hello carries no `pending`). The web server is upgraded first; the daemon catches up at its next restart. | +| Daemon on a version the web server dropped, or newer than it | 426; "This machine" shows "needs upgrade"; new sessions there are disabled until the daemon is restarted on a supported version. An update-only mode for this is planned. | +| 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 + +- `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 90 s (well past the daemon's redial wait, at most 3 s on + loopback, 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), and `ompweb host` for a foreground `ompweb` + (terminal or npx), which has no service: the user keeps it running in another + terminal. 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 the running daemon's link version + is outside the new release's `[MIN_LINK_PROTOCOL_VERSION, + LINK_PROTOCOL_VERSION]` range (it would get 426 and exit); otherwise the + running daemon keeps its 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 running daemon's link version is + outside the new release's `[MIN_LINK_PROTOCOL_VERSION, + LINK_PROTOCOL_VERSION]` range. 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 + +When `NODE_ENV` is `development`, the web server skips `ensureLocalHostLink`: +the daemon stays linked to production, and dev shows "This machine" offline. + +## 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. diff --git a/hooks/useAgentSession.rpc.test.mjs b/hooks/useAgentSession.rpc.test.mjs index 6bde8283e..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,6 +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: 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"); @@ -2123,7 +2136,7 @@ function attachNativeWrapper(t, sid) { }, sendFrame() {}, async dispose() {}, - }, process.cwd()); + }, process.cwd(), null, false, "", undefined, onlineHost); wrapper.start(); world.wrappers.set(sid, wrapper); t.after(() => wrapper.destroyAndWait()); @@ -2742,7 +2755,7 @@ async function attachEditableWrapper(t, native, { holdHistory = false } = {}) { }, sendFrame() {}, async dispose() { listeners.clear(); }, - }, process.cwd()); + }, 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/instrumentation.node.ts b/instrumentation.node.ts index 235561f8a..1e5b996e4 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 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)}`); + } + } + // 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/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/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/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..c3f77531e 100644 --- a/lib/api-utils.ts +++ b/lib/api-utils.ts @@ -2,19 +2,28 @@ 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 { WebRpcError } from "./rpc-manager"; +import { LOCAL_HOST_ID } from "./hosts/registry"; +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. */ @@ -25,7 +34,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/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/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/daemon.test.mjs b/lib/hosts/daemon.test.mjs index d98f42bea..ae1478181 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). @@ -32,7 +34,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'); @@ -42,12 +46,13 @@ 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'); }); `); const jiti = createJiti(import.meta.url); -const { runHostDaemon } = await jiti.import("./daemon.ts"); -const { LINK_HELLO_HEADER, LINK_LIMITS, LINK_NONCE_HEADER } = await jiti.import("./link-protocol.ts"); +const { nextRedialDelay, runHostDaemon } = await jiti.import("./daemon.ts"); +const { LINK_ACK_HEADER, 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"); @@ -65,11 +70,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 } = {}) { - const server = { up: [], hellos: [], offered: null, downlink: null, uplinkDown: false, gets: 0, nonce: null, refused: [], blobs: [], postStatus: [] }; +function scriptedServer({ getStatus = () => 200, helloStatus = 200, validToken = null } = {}) { + const server = { validToken, up: [], hellos: [], offered: null, downlink: null, uplinkDown: false, gets: 0, nonce: null, refused: [], blobs: [], postStatus: [], acks: [] }; let downSeq = 0; let ack = 0; server.fetch = async (url, init = {}) => { + 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)) }; @@ -78,7 +84,7 @@ function scriptedServer({ getStatus = () => 200, helloStatus = 200 } = {}) { if (!init.method || init.method === "GET") { server.gets += 1; const status = getStatus(server.gets); - if (status !== 200) return Response.json({}, { status }); + if (status !== 200) return typeof status === "object" ? status : Response.json({}, { status }); assert.equal(init.headers[LINK_HELLO_HEADER], server.offered?.id, "the GET names the hello just posted"); server.hellos.push(server.offered.hello); const body = new ReadableStream({ start(controller) { server.downlink = controller; } }); @@ -103,6 +109,7 @@ function scriptedServer({ getStatus = () => 200, helloStatus = 200 } = {}) { if (server.uplinkDown) throw new TypeError("fetch failed"); const status = server.postStatus.shift(); if (status) return Response.json({}, { status }); + server.acks.push(init.headers[LINK_ACK_HEADER]); const messages = String(init.body).split("\n").filter(Boolean).map((line) => JSON.parse(line)); server.up.push(...messages); for (const message of messages) if (Number.isInteger(message.seq)) ack = Math.max(ack, message.seq); @@ -135,11 +142,62 @@ function captureLog() { return { lines, restore: () => { console.error = original; } }; } +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("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("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); + } +}); + 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:\/\//); }); -test("ops outside the allow-list are refused and a resent downlink seq runs once", async () => { +test("an unknown op is answered 501 unknown_op and a resent downlink seq runs once", async () => { const log = captureLog(); const server = scriptedServer(); const daemon = start(server); @@ -152,7 +210,7 @@ test("ops outside the allow-list are refused and a resent downlink seq runs once server.raw(listing); await waitFor(() => server.res("r1") && server.res("r2"), "both results"); await sleep(100); - assert.deepEqual(server.res("r1").error, { status: 400, code: "invalid_request", message: "unknown host op: exec" }); + assert.deepEqual(server.res("r1").error, { status: 501, code: "unknown_op", message: "Unknown host op: exec" }); assert.equal(server.res("r2").ok, true); assert.equal(server.up.filter((m) => m.id === "r2").length, 1); } finally { @@ -162,6 +220,88 @@ test("ops outside the allow-list are refused and a resent downlink seq runs once assert.equal(await daemon.done, 0); }); +test("an unknown op gets a 501 res, not a refused line", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + try { + await waitFor(() => server.downlink, "the downlink"); + server.send({ type: "req", id: "r1", op: "exec", args: { command: "id" } }); + await waitFor(() => server.res("r1"), "the answer"); + assert.deepEqual(server.res("r1"), { type: "res", seq: server.res("r1").seq, id: "r1", ok: false, error: { status: 501, code: "unknown_op", message: "Unknown host op: exec" } }); + assert.ok(!log.lines.some((line) => line.includes("malformed")), log.lines.join("|")); + } finally { + await daemon.stop(); + log.restore(); + } +}); + +test("an unknown downlink message is skipped and acked, noted once, and later ones still run", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + try { + await waitFor(() => server.downlink, "the downlink"); + server.raw({ type: "future", seq: 1, x: 1 }); + server.raw({ type: "future", seq: 2 }); + server.raw({ type: "ping" }); + await waitFor(() => server.acks.includes("2"), "an uplink POST acking both unknown messages"); + server.raw({ type: "req", seq: 3, id: "r3", op: "listProjects", args: {} }); + await waitFor(() => server.res("r3"), "the result after the unknown messages"); + assert.equal(server.res("r3").ok, true); + assert.equal(log.lines.filter((line) => line.includes('"future"')).length, 1); + } finally { + await daemon.stop(); + log.restore(); + } + assert.equal(await daemon.done, 0); +}); + +test("unknown-message notes are capped per link, escaped, and start again on a new link", async () => { + const log = captureLog(); + const server = scriptedServer(); + const daemon = start(server); + try { + await waitFor(() => server.downlink, "the downlink"); + for (let i = 0; i < 20; i++) server.send({ type: `t${i}` }); + server.send({ type: "evil\n\u001b[31m" + "x".repeat(100_000) }); + server.send({ type: "stdout", ch: "c", line: "x" }); + server.send({ type: "stdout", ch: "c", line: "x" }); + server.send({ type: "req", id: "r1", op: "listProjects", args: {} }); + await waitFor(() => server.res("r1"), "the result after the flood"); + const notes = log.lines.filter((line) => /ignored an unknown|is not valid from/.test(line)); + assert.equal(notes.filter((line) => line.includes("ignored an unknown")).length, 16); + assert.equal(notes.filter((line) => line.includes('"stdout" is not valid from the server')).length, 2); + assert.ok(notes.every((line) => !/[\n\u001b]/.test(line) && line.length < 200)); + // A new link: the same type is noted again. + const before = log.lines.filter((line) => line.includes('"t0"')).length; + server.downlink.close(); + await waitFor(() => server.hellos.length === 2, "the redial"); + server.send({ type: "t0" }); + server.send({ type: "req", id: "r2", op: "listProjects", args: {} }); + await waitFor(() => server.res("r2"), "the result on the new link"); + assert.equal(log.lines.filter((line) => line.includes('"t0"')).length, before + 1); + } finally { + await daemon.stop(); + log.restore(); + } +}); + +test("a 426 names which side to update", async () => { + const log = captureLog(); + try { + const newer = start(scriptedServer({ getStatus: () => Response.json({ serverVersion: 2, hostVersion: 3 }, { status: 426 }) })); + assert.equal(await newer.done, 1); + assert.ok(log.lines.some((line) => line.includes("this host's ompweb is newer than the server's: update ompweb on the server")), log.lines.join("|")); + log.lines.length = 0; + const older = start(scriptedServer({ getStatus: () => Response.json({ serverVersion: 9, hostVersion: 3 }, { status: 426 }) })); + assert.equal(await older.done, 1); + assert.ok(log.lines.some((line) => line.includes("update ompweb on this host")), log.lines.join("|")); + } finally { + log.restore(); + } +}); + test("output beyond the channel buffer while the uplink is down is dropped, then resync", async () => { const log = captureLog(); const server = scriptedServer(); @@ -332,7 +472,7 @@ test("426 exits 1 asking for an upgrade; replaced exits 0", async () => { try { const outdated = start(scriptedServer({ getStatus: () => 426 })); assert.equal(await outdated.done, 1); - assert.ok(log.lines.some((line) => line.includes("upgrade omp-web on this host"))); + assert.ok(log.lines.some((line) => line.includes("update ompweb on this host"))); const server = scriptedServer(); const replaced = start(server); @@ -422,6 +562,70 @@ 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; an answer closes them", 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, 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, cwd: scratch, pending: [] }]); + } finally { + await daemon.stop(); + log.restore(); + } +}); + +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(); @@ -439,3 +643,137 @@ 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(); + } +}); + +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(); + } +}); + +/** 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" }); + 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 2fce1d1fb..138afd1f0 100644 --- a/lib/hosts/daemon.ts +++ b/lib/hosts/daemon.ts @@ -1,21 +1,22 @@ // `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, - HOST_OP_NAMES, HostOpError, + isHostOp, LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_LIMITS, @@ -27,14 +28,18 @@ import { SeqWindow, SESSION_OP_PARAMS, type DownMessage, - type HostOpName, + type UnknownMessage, + UnknownMessageLog, 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; 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" }); @@ -43,9 +48,12 @@ type Unsequenced = M extends { seq: number } ? Omit : never; interface Channel { transport: RpcTransport; - sessionId: string | null; + /** 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. */ + pending: PendingRequests; } interface Queued { @@ -56,39 +64,25 @@ 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. +// 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 }); - } +/** 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); } -/** What `loginHost` saved, or null before the first login. */ -export function readHostLogin(): { url: string; token: string } | null { +/** A URL the daemon dials: https, or http on loopback or with --allow-http. */ +function dialable(url: string, allowHttp: boolean): boolean { 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 }; + const { protocol, hostname } = new URL(url); + return protocol === "https:" || (protocol === "http:" && (allowHttp || isLoopbackHost(hostname))); } catch { - // Missing or unreadable: not logged in. + return false; } - return null; } /** realpath of the longest existing prefix; null when a component is a dangling symlink. */ @@ -118,8 +112,6 @@ function sessionsPath(value: unknown): string { return target; } -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(); @@ -146,13 +138,14 @@ 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`; - const authorization = `Bearer ${options.token}`; + // 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(); // Uplink messages stay here until main acks them; a failed POST resends them. @@ -232,6 +225,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()) { @@ -247,11 +241,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 (await fatal(response, 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. @@ -281,25 +275,57 @@ 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) { - log("the server speaks a different link protocol: upgrade omp-web on this host"); + /** 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. */ + async function fatal(response: Response, sent: string): Promise { + const { status } = response; + // A 401 for a token another request already replaced needs nothing more. + 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) === 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 { + log("the server rejected this host's token (revoked?); stopping its omp sessions"); + void shutdown(1); + } + } + if (status === 426) { + // The 426 body carries the server's newest version: below this daemon's, the server is the outdated side. + const { serverVersion } = (await response.json().catch(() => ({}))) as { serverVersion?: unknown }; + log( + typeof serverVersion === "number" && serverVersion < LINK_PROTOCOL_VERSION + ? "this host's ompweb is newer than the server's: update ompweb on the server" + : "the server speaks a different link protocol: update ompweb on this host", + ); void shutdown(1); } 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(); } + /** What this link has already logged about messages it skipped. */ + const unknownLog = new UnknownMessageLog("server"); + function handleDown(line: string): void { - let message: DownMessage; + let message: DownMessage | UnknownMessage; try { message = decodeDown(line); } catch (error) { @@ -309,7 +335,8 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } switch (message.type) { case "welcome": - log(`linked to ${options.url}`); + log(`linked to ${serverUrl}`); + unknownLog.reset(); nonce = message.nonce; welcome.resolve(); // A fresh link: resend what main has not acked now, not after the old backoff. @@ -324,13 +351,24 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: return; case "pong": return; + case "unknown": + // A newer main's message, or one only the daemon sends: skipped, but its seq is applied so it is acked and never resent. + if (message.seq !== null) down.applied(message.seq); + { + const note = unknownLog.note(message); + if (note) log(note); + } + return; } // 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; @@ -344,7 +382,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } } - /** A line that does not decode (an op outside HOST_OP_NAMES, say) is never run. */ + /** A line that does not decode (a known type with a bad field, say) is never run. */ function refuse(line: string, why: string): void { let raw: unknown; try { @@ -362,7 +400,7 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: log(`ignored a malformed link message: ${why}`); } - async function answer(id: string, op: HostOpName, args: unknown): Promise { + async function answer(id: string, op: string, args: unknown): Promise { try { const result = await runOp(op, args); const media = op === "readMedia" && isRecord(result) && result.ok === true && result.value instanceof Uint8Array ? result.value : null; @@ -398,13 +436,16 @@ 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 (await fatal(response, 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; @@ -414,9 +455,9 @@ export function runHostDaemon(options: { url: string; token: string; allowHttp: } } - async function runOp(op: HostOpName, args: unknown): Promise { - // decodeDown already refuses unknown names; checked again where ops run. - if (!(HOST_OP_NAMES as readonly string[]).includes(op)) throw new HostOpError(400, "unknown_op", `Unknown host op: ${String(op)}`); + async function runOp(op: string, args: unknown): Promise { + // An older daemon than main: callers fall back on the 501. + if (!isHostOp(op)) throw new HostOpError(501, "unknown_op", `Unknown host op: ${op}`); if (!isRecord(args)) throw new HostOpError(400, "invalid_request", "Host op arguments must be an object"); switch (op) { case "spawn": @@ -454,8 +495,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, file ? readSessionHeaderSync(file)?.id ?? null : null); + channels.set(ch, { transport, cwd: spawned.cwd, 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,25 +520,36 @@ 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(), + autoApproveExtension: localHost.autoApproveExtension(), ack: down.acked, - channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.sessionId })), + channels: [...channels].map(([ch, channel]) => ({ ch, sessionId: channel.pending.sessionId, cwd: channel.cwd, 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 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 (await fatal(offered, 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. @@ -504,8 +560,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 (await fatal(response, sent)) return; if (!response.ok || !response.body) throw new Error(`the server answered ${response.status}`); for await (const line of readLines(response.body)) { alive(); @@ -516,11 +572,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); } } 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/hosts-route.test.mjs b/lib/hosts/hosts-route.test.mjs index ff1c48d5b..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" }, @@ -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]]); }); @@ -78,8 +79,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); }); @@ -111,3 +110,45 @@ 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 local row and getHost(local) show the reserved record's real link status", async () => { + writeFileSync(hostsFile, '{"hosts":[]}'); + 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]), [["", "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" }); + assert.deepEqual((await localRows()).map((h) => h.status), ["offline"], "a record alone is not a link"); + + assert.equal((await linkGet(token)).status, 200); + 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); + + // 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); + + // 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.test.mjs b/lib/hosts/hub.test.mjs index fd4a23922..759dd004f 100644 --- a/lib/hosts/hub.test.mjs +++ b/lib/hosts/hub.test.mjs @@ -17,8 +17,11 @@ after(() => { 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 { LINK_ACK_HEADER, LINK_HELLO_HEADER, LINK_LIMITS, LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION, MIN_LINK_PROTOCOL_VERSION } = await jiti.import("./link-protocol.ts"); const { createHost } = await jiti.import("./registry.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"); const defaultTimings = { ...hub.linkTimings }; test.afterEach(() => Object.assign(hub.linkTimings, defaultTimings)); @@ -26,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. */ @@ -171,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 })); + 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); @@ -208,6 +211,60 @@ test("a v1 daemon, whose GET carries the hello itself, gets 426 instead of redia assert.equal(hub.listHosts().find((h) => h.id === host.id).status, "needs-upgrade"); }); +test("a daemon older than MIN_LINK_PROTOCOL_VERSION gets 426 on its hello POST", async () => { + const { host, token } = createHost("Too old"); + const response = await linkGet(token, hello({ v: MIN_LINK_PROTOCOL_VERSION - 1 })); + assert.equal(response.status, 426); + assert.deepEqual(await response.json(), { error: "Link protocol version mismatch", hostVersion: MIN_LINK_PROTOCOL_VERSION - 1, serverVersion: LINK_PROTOCOL_VERSION }); + assert.equal(hub.listHosts().find((h) => h.id === host.id).status, "needs-upgrade"); +}); + +/** What a v2 daemon's hello lacks: no extension auto-approve, and its channels carry no cwd or pending. */ +const V2_HELLO = { v: 2, autoApproveExtension: undefined }; + +test("a v2 daemon links one protocol version back and its spawned session takes a prompt", async (t) => { + const sessionId = "11111111-2222-4333-8444-bbbbbbbbbb01"; + const link = await linkHost("v2 box", { hello: V2_HELLO }); + t.after(async () => { + await getRpcSession(sessionId)?.destroyAndWait(); + hub.closeHostLink(link.id); + }); + // The link speaks v2: its welcome says so, and Settings can offer the update. + assert.equal(link.welcome.v, 2); + const listed = hub.listHosts().find((h) => h.id === link.id); + assert.equal(listed.status, "online"); + assert.equal(listed.hostVersion, 2); + const remote = hub.getHost(link.id); + assert.equal(remote.autoApproveExtension(), false); + const prompts = []; + const omp = ompChild(link, sessionId); + link.serve({ + async spawn(args) { + 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") 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); + }); + const { session } = await startRpcSession(sessionId, listedSession(sessionId).path, "/w", undefined, false, "/w", undefined, remote); + assert.equal(session.host, remote); + await session.send({ type: "prompt", message: "hi" }); + assert.deepEqual(prompts, ["hi"]); +}); + +test("a v2 daemon's listed children are killed, not adopted: its hello cannot replay their open requests", async (t) => { + const sessionId = "11111111-2222-4333-8444-bbbbbbbbbb02"; + const link = await linkHost("v2 survivor", { hello: V2_HELLO, channels: [{ ch: "old", sessionId }] }); + t.after(() => hub.closeHostLink(link.id)); + assert.deepEqual(await link.next(), { type: "kill", seq: 1, ch: "old", force: false }); + assert.equal(await hub.adoptedChild(link.id, sessionId), false); + assert.equal(getRpcSession(sessionId), undefined); +}); + test("hello without omp marks the host omp-missing and spawnRpc rejects", async () => { const { id, remote, down } = await linkedHost("No omp", { ompVersion: null }); const listed = hub.listHosts().find((h) => h.id === id); @@ -405,9 +462,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: null, cwd: "/w", 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: null, cwd: "/w", pending: ['{"type":"host_tool_call","id":"t1"}'] }] }]); await down.cancel(); }); @@ -435,7 +492,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, 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); @@ -446,9 +503,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 }] }); + 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(() => { @@ -461,6 +518,186 @@ 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"; + +/** 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 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, cwd: "/w/project", 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 } }); + // No ops: a new session is in no list before its first reply is written. + link.serve({}, (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.cwd, "/w/project"); + assert.equal(session.isRunning(), true); + 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("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, 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" }]); +}); + +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)); + 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, cwd: "/w", pending: [] }] }); + const kills = []; + const omp = ompChild(link, sessionId, { fail: "get_state" }); + link.serve({}, (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); +}); + +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, cwd: "/w", pending: [] }] }); + t.after(async () => { + // The child below exits on its kill. + await getRpcSession(sessionId)?.destroyAndWait(); + hub.closeHostLink(link.id); + }); + const release = Promise.withResolvers(); + let holding = false; + const kills = []; + const spawns = []; + const omp = ompChild(link, sessionId); + link.serve({ + 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" }); + } + if (message.type === "stdin" && JSON.parse(message.line).type === "get_state" && !holding) { + holding = true; + await release.promise; + } + return omp(message); + }); + 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)); + release.resolve(); + const { session } = await starting; + assert.equal(session.adopted, true); + assert.equal(getRpcSession(sessionId), session); + assert.deepEqual(spawns, []); + 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); +}); + +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, []), {}], @@ -468,7 +705,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, cwd: "/w", pending: null }] }); assert.equal((await link.down.nextReal()).type, "kill"); const ops = link.remote.sessionOps; let seq = 0; @@ -518,6 +755,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); @@ -662,9 +905,88 @@ test("an over-limit batch gets 413; a batch cut mid-line applies nothing", async await link.down.cancel(); }); +test("unknown uplink messages are acked and skipped, warning once per type; the known ones in the batch apply", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); + const link = await linkedHost("Newer daemon"); + const listing = link.remote.sessionOps.listSessions(); + const req = await link.down.nextReal(); + const response = await linkPost(link, [ + { type: "future", seq: 1, x: 1 }, + { type: "future", seq: 2 }, + { type: "res", seq: 3, id: req.id, ok: true, result: [] }, + { type: "other", seq: 4 }, + ], req.seq); + assert.equal(response.status, 200); + assert.deepEqual(await response.json(), { ack: 4 }); + assert.deepEqual(await listing, []); + assert.deepEqual(warn.mock.calls.map((call) => String(call.arguments[0]).match(/"(\w+)"/)?.[1]), ["future", "other"]); + await link.down.cancel(); +}); + +test("an unknown type is warned about again on a new link of the same host", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); + const a = await linkedHost("Redialing daemon"); + await linkPost(a, [{ type: "future", seq: 1 }]); + await linkPost(a, [{ type: "future", seq: 2 }]); + assert.equal(warn.mock.calls.length, 1); + const b = { token: a.token, ...(await openLink(a.token, { ack: 0 })) }; + await linkPost(b, [{ type: "future", seq: 1 }]); + assert.equal(warn.mock.calls.length, 2, "the new link starts a new set"); + await b.down.cancel(); +}); + +test("unknown-type warnings are capped per link and escaped", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); + const link = await linkedHost("Chatty daemon"); + const types = Array.from({ length: 20 }, (_, i) => `t${i}`); + const hostile = "evil\n\u001b[31m" + "x".repeat(100_000); + const response = await linkPost(link, [...types, hostile].map((type, i) => ({ type, seq: i + 1 }))); + assert.deepEqual(await response.json(), { ack: 21 }, "every seq is still applied"); + const lines = warn.mock.calls.map((call) => String(call.arguments[0])); + assert.equal(lines.length, 16); + assert.ok(lines.every((line) => !/[\n\u001b]/.test(line) && line.length < 200)); + await link.down.cancel(); +}); + +test("a daemon message that only the server may send is logged each time, skipped and acked", async (t) => { + const warn = t.mock.method(console, "warn", () => {}); + const link = await linkedHost("Confused daemon"); + const response = await linkPost(link, [ + { type: "stdin", seq: 1, ch: "c", line: "x" }, + { type: "stdin", seq: 2, ch: "c", line: "x" }, + ]); + assert.deepEqual(await response.json(), { ack: 2 }); + const lines = warn.mock.calls.map((call) => String(call.arguments[0])); + assert.equal(lines.length, 2); + assert.ok(lines.every((line) => line.includes('"stdin" is not valid from the daemon')), lines.join("|")); + await link.down.cancel(); +}); + +test("an uplink seq outside the safe integers refuses the batch", async () => { + const link = await linkedHost("Jumping daemon"); + assert.equal((await linkPost(link, [{ type: "future", seq: 1e300 }])).status, 400); + assert.equal((await linkPost(link, [{ type: "stdout", seq: -1, ch: "none", line: "x" }])).status, 400); + assert.deepEqual(await (await linkPost(link, [{ type: "stdout", seq: 1, ch: "none", line: "x" }])).json(), { ack: 1 }); + await link.down.cancel(); +}); + +test("a daemon's unknown_op answer surfaces as a 501 HostOpError", async () => { + const link = await linkedHost("Older daemon"); + const listing = link.remote.sessionOps.listSessions(); + const req = await link.down.nextReal(); + await linkPost(link, [{ type: "res", seq: 1, id: req.id, ok: false, error: { status: 501, code: "unknown_op", message: "Unknown host op: listSessions" } }], req.seq); + await assert.rejects(listing, (error) => error.name === "HostOpError" && error.status === 501 && error.code === "unknown_op"); + await link.down.cancel(); +}); + 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 4033e679a..a02df157f 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"; @@ -21,15 +20,18 @@ import { LINK_NONCE_HEADER, LINK_PROTOCOL_VERSION, LinkLimitError, + MIN_LINK_PROTOCOL_VERSION, Outbox, SeqWindow, SESSION_OP_PARAMS, type DownMessage, + type HelloChannel, type HostOpName, + type UnknownMessage, + UnknownMessageLog, type UpMessage, } from "./link-protocol"; -import { localHost } from "./local-host"; -import { HostRegistryUnreadableError, hostForToken, 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. */ @@ -39,7 +41,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. */ @@ -76,6 +77,8 @@ interface Link { downSeq: number; outbox: Outbox<{ seq: number; line: string }>; up: SeqWindow; + /** What this link has already logged about messages it skipped. */ + unknownLog: UnknownMessageLog; pending: Map; channels: Map; pingTimer: NodeJS.Timeout | undefined; @@ -87,6 +90,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 +100,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; } @@ -118,6 +123,7 @@ function linkFor(id: string): Link { downSeq: 0, outbox: new Outbox(), up: new SeqWindow(), + unknownLog: new UnknownMessageLog("daemon"), pending: new Map(), channels: new Map(), pingTimer: undefined, @@ -130,6 +136,7 @@ function linkFor(id: string): Link { } function labelOf(id: string): string { + if (id === LOCAL_HOST_ID) return customLocalLabel() || DEFAULT_LOCAL_LABEL; return loadHosts().find((h) => h.id === id)?.label ?? id; } @@ -164,8 +171,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 +261,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; @@ -278,10 +302,11 @@ function legacyHelloVersion(link: Link, header: string | null): Response | null } } -/** 426 for a daemon on another protocol version. Compared before decoding: another version may shape its hello differently. */ +/** 426 for a daemon outside MIN_LINK_PROTOCOL_VERSION..LINK_PROTOCOL_VERSION (a newer one too: the web app upgrades first). + * Compared before decoding: another version may shape its hello differently. */ function versionMismatch(link: Link, raw: unknown): Response | null { const version = isRecord(raw) ? raw.v : undefined; - if (version === LINK_PROTOCOL_VERSION) return null; + if (typeof version === "number" && version >= MIN_LINK_PROTOCOL_VERSION && version <= LINK_PROTOCOL_VERSION && Number.isInteger(version)) return null; const hostVersion = typeof version === "number" && Number.isInteger(version) ? version : null; // A stray old daemon with this token must not take down the healthy link. if (!link.stream) { @@ -311,7 +336,7 @@ async function handleHelloPost(req: Request, record: HostRecord): Promise ch)); @@ -401,16 +430,44 @@ function reattach(link: Link, listed: HelloChannel[]): void { transport.lost = true; transport.deliverExit(null, null); } - for (const { ch, sessionId } of listed) { + for (const { ch, sessionId, cwd, 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, cwd, pending); + 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, 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 { + // Dynamic: rpc-manager imports this module. + const { adoptRpcSession } = await import("../rpc-manager"); + await adoptRpcSession({ host: link.host, transport: child, sessionId, cwd, replay }); + return true; + } catch (error) { + 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 { + // 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})`); + } + return false; } } @@ -418,6 +475,7 @@ function reattach(link: Link, listed: HelloChannel[]): void { 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); @@ -425,7 +483,7 @@ export async function handleLinkPost(req: Request): Promise { const nonce = link.nonce; const ack = req.headers.get(LINK_ACK_HEADER); if (ack === null || !/^\d+$/.test(ack)) return json({ error: "Missing ack" }, 400); - let messages: UpMessage[]; + let messages: (UpMessage | UnknownMessage)[]; try { const bytes = await readBodyWithinLimit(req, LINK_LIMITS.uplinkBytes); // Decode the whole batch first: a batch cut mid-line applies nothing. @@ -434,6 +492,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); @@ -442,9 +501,16 @@ export async function handleLinkPost(req: Request): Promise { return json({ ack: link.up.acked }); } -function applyUp(link: Link, message: UpMessage): void { +function applyUp(link: Link, message: UpMessage | UnknownMessage): void { if (message.type === "ping") return enqueue(link, encodeLine({ type: "pong" })); if (message.type === "pong" || message.type === "hello") return; + if (message.type === "unknown") { + // A newer daemon's message, or one only the server sends: skipped, but its seq is applied so it is acked and never resent. + if (message.seq !== null) link.up.applied(message.seq); + const note = link.unknownLog.note(message); + if (note) console.warn(`[omp-web] ${labelOf(link.id)}: ${note}`); + return; + } // Already applied before a resend. if (!link.up.applied(message.seq)) return; switch (message.type) { @@ -493,6 +559,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; @@ -507,6 +574,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`)); } @@ -638,14 +707,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> = []; @@ -665,6 +736,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 }); @@ -818,10 +891,11 @@ export class RemoteHost implements Host { } } -/** "local" is this machine; other ids must be registered hosts. */ +/** `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 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 { @@ -838,7 +912,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, @@ -856,24 +930,36 @@ 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: "online"; + status: HostStatus; ompVersion: string | null; - platform: string; + platform: string | null; lastSeenAt: null; + hostVersion: number | null; + 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; -/** 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: customLocalLabel(), + status: link?.status ?? "offline", + ompVersion: link?.ompVersion ?? null, + platform: link?.platform ?? null, lastSeenAt: null, + hostVersion: link?.hostVersion ?? null, + serverVersion: LINK_PROTOCOL_VERSION, + serverPlatform: process.platform, + daemonManaged: process.env.NODE_ENV !== "development", }; return { hosts: [local, ...listHosts()] }; } @@ -897,8 +983,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 +993,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..99533d5a1 100644 --- a/lib/hosts/link-driver.test-helper.mjs +++ b/lib/hosts/link-driver.test-helper.mjs @@ -6,19 +6,50 @@ 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 { 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"; -/** Register a host and link it. `channels`: the hello's still-running children. */ -export async function linkHost(label, { channels = [] } = {}) { +/** Register a host and link it. `channels`: the hello's still-running children; `hello`: fields to override (an older protocol's, say). */ +export async function linkHost(label, { channels = [], hello = {} } = {}) { const { host, token } = createHost(label); const link = new LinkDriver(host.id, token); + await link.dial({ channels, hello }); + 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; +} + +/** 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; @@ -28,6 +59,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; @@ -39,9 +89,9 @@ export class LinkDriver { this.buffer = ""; } - /** 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 }; + /** POST a hello (`hello` overrides its fields), then GET the downlink with its id; resolves after its welcome, kept as `welcome`. */ + async dial({ channels = [], ack = this.ack, hello: overrides = {} } = {}) { + const hello = { type: "hello", v: LINK_PROTOCOL_VERSION, ompVersion: "14.0.0", platform: "linux", home: "/home/u", autoApproveExtension: false, ack, channels, ...overrides }; const offered = await hub.handleLinkPost(new Request(URL_BASE, { method: "POST", headers: { authorization: `Bearer ${this.token}`, [LINK_HELLO_HEADER]: "1" }, @@ -56,6 +106,7 @@ export class LinkDriver { this.buffer = ""; const welcome = await this.next(); assert.equal(welcome.type, "welcome"); + this.welcome = welcome; this.nonce = welcome.nonce; } @@ -97,12 +148,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: opFailure(error) }); + continue; + } + await this.answer(message, value); } })(); } diff --git a/lib/hosts/link-integration.test.mjs b/lib/hosts/link-integration.test.mjs index 06cb40209..c14a17c91 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,102 @@ function writeFakeOmp(file, source) { } const FRAMES = 200; +// "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 = (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)) : []); 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]; +// 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"); +let prompt = null; +let streaming = false; +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 }); +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 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 }); + prompt = command.message; + 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 === "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 === "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}; + const timer = setInterval(() => { + if (!fs.existsSync(path.join(${JSON.stringify(scratch)}, "go-" + sessionId))) 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 +161,27 @@ 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 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 }; -const seen = { cuts: [], blobUploads: 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"); + 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); @@ -110,6 +205,7 @@ const server = createServer(async (req, res) => { return; } response = await linkRoute.POST(request()); + 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; @@ -140,6 +236,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(); @@ -148,7 +245,25 @@ 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 old process runs its shutdown + * 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"); + 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()) { + 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 +301,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"); @@ -239,10 +355,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); - sessions.push(session); + const { session, realSessionId } = await startRpcSession("", "", projectDir, undefined, false, null, undefined, remote); + countSessionId = realSessionId; assert.equal(session.host, remote); const texts = []; let ended = false; @@ -258,3 +377,181 @@ 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 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 remote = hub.getHost(hostId); + // 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), + ].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) && 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; + + // 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 = []; + 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(); + 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"); + // 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) { + 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"); +}); + +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"); + + const killsBefore = seen.kills.length; + 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")); + 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.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.length > 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"]); +}); + +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/hosts/link-protocol.test.mjs b/lib/hosts/link-protocol.test.mjs index 03688bf20..8626604dc 100644 --- a/lib/hosts/link-protocol.test.mjs +++ b/lib/hosts/link-protocol.test.mjs @@ -24,10 +24,11 @@ const UP = [ ompVersion: null, platform: "darwin", home: "/Users/me", + autoApproveExtension: true, ack: 3, channels: [ - { ch: "c1", sessionId: "s1" }, - { ch: "c2", sessionId: 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"}' }, @@ -64,6 +65,14 @@ test("round-trips every up message kind", async () => { } }); +test("a v2 hello decodes into today's shape: no extension auto-approve, and no channel is adoptable", async () => { + const { decodeUp } = await load(); + const v2 = { type: "hello", v: 2, ompVersion: "14.0.0", platform: "linux", home: "/h", ack: 0, channels: [{ ch: "c1", sessionId: "s1" }] }; + assert.deepEqual(decodeUp(JSON.stringify(v2)), { ...v2, autoApproveExtension: false, channels: [{ ch: "c1", sessionId: "s1", cwd: "", pending: null }] }); + // From v3 on the fields are required. + assert.throws(() => decodeUp(JSON.stringify({ ...v2, v: 3 }))); +}); + test("decodeUp returns an inline res exactly as sent", async () => { const { decodeUp } = await load(); assert.deepEqual(decodeUp('{"type":"res","seq":1,"id":"a","ok":true,"result":1}'), { @@ -75,26 +84,84 @@ test("decodeUp returns an inline res exactly as sent", async () => { }); }); -test("decodeDown accepts every host op name and rejects anything else", async () => { - const { HOST_OP_NAMES, encodeLine, decodeDown, LinkProtocolError } = await load(); +test("decodeDown accepts every host op name and passes an unknown one on for the daemon to answer", async () => { + const { HOST_OP_NAMES, encodeLine, decodeDown } = await load(); assert.equal(HOST_OP_NAMES.length, 20); for (const op of HOST_OP_NAMES) { const message = { type: "req", seq: 1, id: "x", op, args: null }; assert.deepEqual(decodeDown(encodeLine(message)), message); } - assert.throws( - () => decodeDown(encodeLine({ type: "req", seq: 1, id: "x", op: "exec", args: null })), - LinkProtocolError, - ); + const unknownOp = { type: "req", seq: 1, id: "x", op: "exec", args: null }; + assert.deepEqual(decodeDown(encodeLine(unknownOp)), unknownOp); +}); + +test("decode turns an unknown message type into an unknown message and still checks the envelope", async () => { + const { decodeDown, decodeUp, LinkProtocolError } = await load(); + assert.deepEqual(decodeDown('{"type":"future","seq":4,"x":1}'), { type: "unknown", messageType: "future", seq: 4, wrongDirection: false }); + assert.deepEqual(decodeUp('{"type":"future","seq":5}'), { type: "unknown", messageType: "future", seq: 5, wrongDirection: false }); + assert.deepEqual(decodeUp('{"type":"future"}'), { type: "unknown", messageType: "future", seq: null, wrongDirection: false }); + for (const line of ['{"seq":1}', '{"type":7,"seq":1}', '{"type":"future","seq":"1"}', '{"type":"future","seq":1.5}']) { + assert.throws(() => decodeUp(line), LinkProtocolError, line); + assert.throws(() => decodeDown(line), LinkProtocolError, line); + } + // A known type keeps its strict validation. + assert.throws(() => decodeUp('{"type":"stdout","seq":1}'), LinkProtocolError); +}); + +test("a known type from the other direction is an unknown message marked wrongDirection", async () => { + const { decodeDown, decodeUp } = await load(); + assert.deepEqual(decodeDown('{"type":"stdout","seq":1,"ch":"c","line":"x"}'), { type: "unknown", messageType: "stdout", seq: 1, wrongDirection: true }); + assert.deepEqual(decodeUp('{"type":"stdin","seq":1,"ch":"c","line":"x"}'), { type: "unknown", messageType: "stdin", seq: 1, wrongDirection: true }); + assert.deepEqual(decodeUp('{"type":"welcome","v":3,"hostId":"h","nonce":"n"}'), { type: "unknown", messageType: "welcome", seq: null, wrongDirection: true }); }); -test("decode rejects messages travelling in the other direction", async () => { +test("every seq and ack must be a safe non-negative integer, so one line cannot jump the window", async () => { const { decodeDown, decodeUp, LinkProtocolError } = await load(); - assert.throws( - () => decodeDown('{"type":"stdout","seq":1,"ch":"c","line":"x"}'), - LinkProtocolError, - ); - assert.throws(() => decodeUp('{"type":"stdin","seq":1,"ch":"c","line":"x"}'), LinkProtocolError); + const hello = (ack) => `{"type":"hello","v":3,"ompVersion":null,"platform":"linux","home":"/h","autoApproveExtension":false,"ack":${ack},"channels":[]}`; + for (const seq of ["1e300", "-1", "9007199254740992"]) { + for (const line of [`{"type":"future","seq":${seq}}`, `{"type":"stdout","seq":${seq},"ch":"c","line":"x"}`, `{"type":"stdin","seq":${seq},"ch":"c","line":"x"}`]) { + assert.throws(() => decodeUp(line), LinkProtocolError, line); + assert.throws(() => decodeDown(line), LinkProtocolError, line); + } + assert.throws(() => decodeUp(hello(seq)), LinkProtocolError, `hello ack ${seq}`); + } + assert.equal(decodeUp(hello(0)).ack, 0); + assert.equal(decodeUp('{"type":"future","seq":9007199254740991}').seq, Number.MAX_SAFE_INTEGER); +}); + +test("decodeDown refuses a req whose op is not a string or whose args are missing", async () => { + const { decodeDown, LinkProtocolError } = await load(); + for (const line of ['{"type":"req","seq":1,"id":"x","op":7,"args":{}}', '{"type":"req","seq":1,"id":"x","args":{}}', '{"type":"req","seq":1,"id":"x","op":"listSessions"}']) { + assert.throws(() => decodeDown(line), LinkProtocolError, line); + } +}); + +test("UnknownMessageLog notes each unknown type once, at most 16 types, escaped and truncated", async () => { + const { UnknownMessageLog, UNKNOWN_LOG_CAP } = await load(); + assert.equal(UNKNOWN_LOG_CAP, 16); + const unknown = (messageType, wrongDirection = false) => ({ type: "unknown", messageType, seq: 1, wrongDirection }); + const log = new UnknownMessageLog("daemon"); + const first = log.note(unknown("future")); + assert.match(first, /"future"/); + assert.equal(log.note(unknown("future")), null, "once per type"); + for (let i = 1; i < UNKNOWN_LOG_CAP; i++) assert.ok(log.note(unknown(`t${i}`)), `type ${i}`); + assert.equal(log.note(unknown("one-too-many")), null, "past the cap nothing is logged"); + log.reset(); + assert.ok(log.note(unknown("future")), "a new link notes it again"); + + const hostile = new UnknownMessageLog("daemon").note(unknown("a\nb\u001b[31m" + "x".repeat(7 * MB))); + assert.ok(hostile.length < 200, `${hostile.length} chars`); + assert.ok(!/[\n\u001b]/.test(hostile), "control characters are escaped"); + assert.ok(hostile.includes("\\n") && hostile.includes("\\u001b")); +}); + +test("UnknownMessageLog names the sender of a message that travelled the wrong way, every time, up to 16", async () => { + const { UnknownMessageLog, UNKNOWN_LOG_CAP } = await load(); + const wrong = { type: "unknown", messageType: "stdout", seq: 1, wrongDirection: true }; + const log = new UnknownMessageLog("daemon"); + for (let i = 0; i < UNKNOWN_LOG_CAP; i++) assert.equal(log.note(wrong), '"stdout" is not valid from the daemon'); + assert.equal(log.note(wrong), null); + assert.equal(new UnknownMessageLog("server").note({ ...wrong, messageType: "stdin" }), '"stdin" is not valid from the server'); }); test("decode rejects malformed lines with LinkProtocolError", async () => { @@ -109,6 +176,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","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 695226f6e..00c561c63 100644 --- a/lib/hosts/link-protocol.ts +++ b/lib/hosts/link-protocol.ts @@ -2,8 +2,12 @@ // 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. + * Rules for changing it: docs/specs/2026-10-28-remote-hosts-design.md, "Protocol versions and compatibility". */ +export const LINK_PROTOCOL_VERSION = 3; +/** The oldest daemon protocol the server still links (older ones get 426). Dropping one is an explicit decision. */ +export const MIN_LINK_PROTOCOL_VERSION = 2; export const LINK_LIMITS = { pingMs: 15_000, @@ -19,6 +23,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; @@ -74,11 +80,16 @@ export type DownMessage = | { type: "welcome"; v: number; hostId: string; nonce: string } | { type: "stdin"; seq: number; ch: string; line: string } | { type: "kill"; seq: number; ch: string; force: boolean } - | { type: "req"; seq: number; id: string; op: HostOpName; args: unknown } + /** `op` is whatever the sender named: the daemon answers one it does not know with 501 `unknown_op`. */ + | { type: "req"; seq: number; id: string; op: string; args: unknown } | { type: "replaced"; seq: number } | { type: "ping" } | { type: "pong" }; +/** `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 = | { type: "hello"; @@ -86,8 +97,10 @@ 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: { ch: string; sessionId: string | null }[]; + channels: HelloChannel[]; } | { type: "stdout"; seq: number; ch: string; line: string } | { type: "stderr"; seq: number; ch: string; chunk: string } @@ -104,6 +117,10 @@ export type UpMessage = | { type: "ping" } | { type: "pong" }; +/** A message this side cannot decode by type (a newer peer's), or one that only the other side may send + * (`wrongDirection`): receivers skip it, but ack its `seq` (null when it carries none) so it is never resent. */ +export type UnknownMessage = { type: "unknown"; messageType: string; seq: number | null; wrongDirection: boolean }; + export class LinkProtocolError extends Error { readonly name = "LinkProtocolError"; } @@ -138,6 +155,13 @@ function str(o: Obj, key: string): string { return v; } +/** A `seq` or `ack`: a safe non-negative integer, so one line cannot push a window out of reach of every later message. */ +function seqNum(o: Obj, key: string): number { + const v = o[key]; + if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0) fail(`${key} must be a non-negative safe integer`); + return v; +} + function int(o: Obj, key: string): number { const v = o[key]; if (typeof v !== "number" || !Number.isInteger(v)) fail(`${key} must be an integer`); @@ -154,10 +178,60 @@ function nullable(o: Obj, key: string, read: (o: Obj, key: string) => T): T | return o[key] === null ? null : read(o, key); } -function isHostOp(name: string): name is HostOpName { +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; +} + +export function isHostOp(name: string): name is HostOpName { return (HOST_OP_NAMES as readonly string[]).includes(name); } +const DOWN_TYPES: readonly string[] = ["welcome", "stdin", "kill", "req", "replaced", "ping", "pong"]; +const UP_TYPES: readonly string[] = ["hello", "stdout", "stderr", "exit", "resync", "res", "ping", "pong"]; + +/** `otherDirection`: the types only the other direction decodes; one of those arrived on the wrong way. */ +function unknownMessage(o: Obj, otherDirection: readonly string[]): UnknownMessage { + const messageType = str(o, "type"); + return { type: "unknown", messageType, seq: "seq" in o ? seqNum(o, "seq") : null, wrongDirection: otherDirection.includes(messageType) }; +} + +/** Distinct unknown types, and wrong-direction messages, one link may make a side log. */ +export const UNKNOWN_LOG_CAP = 16; + +/** What one side logs about the messages it skips, per link: an unknown type once, a wrong-direction message every + * time, each within UNKNOWN_LOG_CAP, so a peer cannot flood the log. The type is escaped and cut to 64 characters. */ +export class UnknownMessageLog { + private readonly types = new Set(); + private misdirected = 0; + private readonly from: "daemon" | "server"; + + /** `from`: who sends the messages this log sees. */ + constructor(from: "daemon" | "server") { + this.from = from; + } + + /** The text to log for `message`, or null when there is nothing to log. */ + note(message: UnknownMessage): string | null { + const type = JSON.stringify(message.messageType.slice(0, 64)); + if (message.wrongDirection) { + if (this.misdirected >= UNKNOWN_LOG_CAP) return null; + this.misdirected += 1; + return `${type} is not valid from the ${this.from}`; + } + if (this.types.has(type) || this.types.size >= UNKNOWN_LOG_CAP) return null; + this.types.add(type); + return `ignored an unknown link message type ${type}`; + } + + /** A new link starts again. */ + reset(): void { + this.types.clear(); + this.misdirected = 0; + } +} + function parseLine(line: string): Obj { if (encoder.encode(line).byteLength > LINK_LIMITS.maxLineBytes) { throw new LinkLimitError(`link line exceeds ${LINK_LIMITS.maxLineBytes} bytes`); @@ -172,43 +246,42 @@ function parseLine(line: string): Obj { return value; } -export function decodeDown(line: string): DownMessage { +export function decodeDown(line: string): DownMessage | UnknownMessage { const o = parseLine(line); switch (o.type) { case "welcome": return { type: "welcome", v: int(o, "v"), hostId: str(o, "hostId"), nonce: str(o, "nonce") }; case "stdin": - return { type: "stdin", seq: int(o, "seq"), ch: str(o, "ch"), line: str(o, "line") }; + return { type: "stdin", seq: seqNum(o, "seq"), ch: str(o, "ch"), line: str(o, "line") }; case "kill": - return { type: "kill", seq: int(o, "seq"), ch: str(o, "ch"), force: bool(o, "force") }; - case "req": { - const op = str(o, "op"); - if (!isHostOp(op)) fail(`unknown host op: ${op}`); - if (!("args" in o)) fail("args must be present"); - return { type: "req", seq: int(o, "seq"), id: str(o, "id"), op, args: o.args }; - } + return { type: "kill", seq: seqNum(o, "seq"), ch: str(o, "ch"), force: bool(o, "force") }; + case "req": + return { type: "req", seq: seqNum(o, "seq"), id: str(o, "id"), op: str(o, "op"), args: "args" in o ? o.args : fail("args must be present") }; case "replaced": - return { type: "replaced", seq: int(o, "seq") }; + return { type: "replaced", seq: seqNum(o, "seq") }; case "ping": return { type: "ping" }; case "pong": return { type: "pong" }; default: - return fail(`unknown down message type: ${String(o.type)}`); + return unknownMessage(o, UP_TYPES); } } -function channels(o: Obj): { ch: string; sessionId: string | null }[] { +/** A v2 hello's channels carry no `cwd` or `pending`: decoded with `pending: null`, which reattach kills instead of adopting. */ +function channels(o: Obj, v2: boolean): 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) }; + const ch = str(c, "ch"); + const sessionId = nullable(c, "sessionId", str); + return v2 ? { ch, sessionId, cwd: "", pending: null } : { ch, sessionId, cwd: str(c, "cwd"), pending: nullable(c, "pending", strings) }; }); } function res(o: Obj): UpMessage { - const seq = int(o, "seq"); + const seq = seqNum(o, "seq"); const id = str(o, "id"); if (o.ok === true) { const blob = o.blob; @@ -234,33 +307,37 @@ function res(o: Obj): UpMessage { return fail("ok must be true or false"); } -export function decodeUp(line: string): UpMessage { +export function decodeUp(line: string): UpMessage | UnknownMessage { const o = parseLine(line); switch (o.type) { - case "hello": + case "hello": { + const v = int(o, "v"); return { type: "hello", - v: int(o, "v"), + v, ompVersion: nullable(o, "ompVersion", str), platform: str(o, "platform"), home: str(o, "home"), - ack: int(o, "ack"), - channels: channels(o), + // A v2 hello does not say: off until a spawn result reports it. + autoApproveExtension: v === 2 ? false : bool(o, "autoApproveExtension"), + ack: seqNum(o, "ack"), + channels: channels(o, v === 2), }; + } case "stdout": - return { type: "stdout", seq: int(o, "seq"), ch: str(o, "ch"), line: str(o, "line") }; + return { type: "stdout", seq: seqNum(o, "seq"), ch: str(o, "ch"), line: str(o, "line") }; case "stderr": - return { type: "stderr", seq: int(o, "seq"), ch: str(o, "ch"), chunk: str(o, "chunk") }; + return { type: "stderr", seq: seqNum(o, "seq"), ch: str(o, "ch"), chunk: str(o, "chunk") }; case "exit": return { type: "exit", - seq: int(o, "seq"), + seq: seqNum(o, "seq"), ch: str(o, "ch"), code: nullable(o, "code", int), signal: nullable(o, "signal", str), }; case "resync": - return { type: "resync", seq: int(o, "seq"), ch: str(o, "ch") }; + return { type: "resync", seq: seqNum(o, "seq"), ch: str(o, "ch") }; case "res": return res(o); case "ping": @@ -268,7 +345,7 @@ export function decodeUp(line: string): UpMessage { case "pong": return { type: "pong" }; default: - return fail(`unknown up message type: ${String(o.type)}`); + return unknownMessage(o, DOWN_TYPES); } } diff --git a/lib/hosts/local-bootstrap.test.mjs b/lib/hosts/local-bootstrap.test.mjs new file mode 100644 index 000000000..fe3c8f792 --- /dev/null +++ b/lib/hosts/local-bootstrap.test.mjs @@ -0,0 +1,91 @@ +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 local or change its agent-start right, and createHost never makes it", () => { + assert.throws(() => revokeHost("local"), { 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); +}); + +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 new file mode 100644 index 000000000..f1a4e6c45 --- /dev/null +++ b/lib/hosts/local-bootstrap.ts @@ -0,0 +1,39 @@ +// 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 "./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. */ +export function localLinkUrl(env: NodeJS.ProcessEnv = process.env): { url: string } | { skip: string } { + const port = env.OMP_WEB_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. + * 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(); + loginHost({ url, token }); + return { token, written: true }; +} 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 new file mode 100644 index 000000000..e83487491 --- /dev/null +++ b/lib/hosts/no-direct-local.test.mjs @@ -0,0 +1,78 @@ +// 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)); + +/** 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", + // 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/daemon.test.mjs", + "lib/hosts/no-direct-local.test.mjs", +]); + +/** `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|\/daemon)(?:\.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) ? [path] : []; + }); +} + +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--; + } + // `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; +} + +/** 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, daemon, 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/pending-requests.test.mjs b/lib/hosts/pending-requests.test.mjs new file mode 100644 index 000000000..8f87b9a45 --- /dev/null +++ b/lib/hosts/pending-requests.test.mjs @@ -0,0 +1,130 @@ +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(), []); +}); + +/** `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(bytes.byteLength / size); + return Array.from({ length: count }, (_, index) => line({ + 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); + 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("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" })); + 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("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" })); + 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..85d266032 --- /dev/null +++ b/lib/hosts/pending-requests.ts @@ -0,0 +1,107 @@ +// 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|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. */ +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 (null: over the cap); undefined between frames. */ + private chunk: Kept | undefined; + private bytes = 0; + + /** `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; + 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 === undefined ? [] : this.chunk, line); + if (!frame) { + this.chunk = kept; + return; + } + this.chunk = undefined; + 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); + this.open.set(frame.id, kept); + 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); + } + + noteStdin(line: string): void { + if (!STDIN_TYPES.test(line)) return; + let command: unknown; + try { + command = JSON.parse(line); + } catch { + return; + } + 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); + } + } + + /** 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/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 221a88afb..971bc99b4 100644 --- a/lib/hosts/registry.ts +++ b/lib/hosts/registry.ts @@ -17,6 +17,17 @@ interface HostsFile { hosts: HostRecord[]; } +/** "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(); if (!trimmed) throw new Error("Host label is required"); @@ -110,17 +121,45 @@ export class UnknownHostError extends Error { } } +/** `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() { + super("This machine cannot be changed"); + } +} + export function updateHost(id: string, updates: { label?: string; allowAgentStart?: boolean }): HostRecord { + 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; } +/** 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: existing?.label ?? "", + 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; diff --git a/lib/hosts/session-index.test.mjs b/lib/hosts/session-index.test.mjs index 17cb8b1f9..91edd04dc 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,69 @@ 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"); + // 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"); + 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("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)]; + 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 +189,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..33c1fe164 100644 --- a/lib/hosts/session-index.ts +++ b/lib/hosts/session-index.ts @@ -1,16 +1,16 @@ // 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 { HostOpError } from "./link-protocol"; 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 { @@ -21,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 { @@ -36,19 +38,20 @@ 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; } -/** 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); @@ -57,6 +60,7 @@ 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(); @@ -73,11 +77,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 +90,24 @@ 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. + * Rejects 503 while this machine's daemon is offline or has never listed its sessions: its sessions are unknown then, not gone. */ 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)); + 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. */ @@ -108,12 +115,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 +122,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 +130,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 +149,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/i18n/locales/en.json b/lib/i18n/locales/en.json index 33d863e65..100ad63ad 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}", @@ -1334,6 +1334,12 @@ "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.localOfflineHint": "Start the ompweb-host service. To install it, run:", + "hostsConfig.localDaemonBanner": "{host} needs the ompweb-host service. Install it with:", + "hostsConfig.localForegroundHint": "Running ompweb in a terminal or with npx instead? Keep this running in another terminal (with npx: npx @kahme247/ompweb@latest host):", + "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 383195b8b..9974090bf 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}", @@ -1293,6 +1293,12 @@ "hostsConfig.allowAgentStartAria": "エージェントが確認なしで {name} にセッションを開始できる", "hostsConfig.rename": "名前を変更", "hostsConfig.renameTitle": "ホスト名を変更", + "hostsConfig.renameAria": "{name} の名前を変更", + "hostsConfig.localNameHint": "空欄にすると「このマシン」に戻ります。", + "hostsConfig.localOfflineHint": "ompweb-host サービスを起動してください。インストールするには次を実行します:", + "hostsConfig.localDaemonBanner": "{host} には ompweb-host サービスが必要です。次のコマンドでインストールします:", + "hostsConfig.localForegroundHint": "ターミナルや npx で ompweb を起動している場合は、代わりに別のターミナルでこれを実行したままにしてください(npx の場合: npx @kahme247/ompweb@latest host):", + "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 cfc517832..0724a782b 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}", @@ -1293,6 +1293,12 @@ "hostsConfig.allowAgentStartAria": "智能体可在 {name} 上无需确认即启动会话", "hostsConfig.rename": "重命名", "hostsConfig.renameTitle": "重命名主机", + "hostsConfig.renameAria": "重命名 {name}", + "hostsConfig.localNameHint": "留空则使用“本机”。", + "hostsConfig.localOfflineHint": "请启动 ompweb-host 服务。安装方法,运行:", + "hostsConfig.localDaemonBanner": "{host} 需要 ompweb-host 服务。请用以下命令安装:", + "hostsConfig.localForegroundHint": "如果是在终端中或用 npx 运行 ompweb,请改为在另一个终端中保持运行以下命令(npx:npx @kahme247/ompweb@latest host):", + "hostsConfig.dismiss": "关闭", "hostsConfig.save": "保存", "hostsConfig.saving": "保存中…", "hostsConfig.cancel": "取消", diff --git a/lib/omp/rpc-process-runtime.test.mjs b/lib/omp/rpc-process-runtime.test.mjs index 9e0690111..bd36717fa 100644 --- a/lib/omp/rpc-process-runtime.test.mjs +++ b/lib/omp/rpc-process-runtime.test.mjs @@ -7,6 +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; 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) { @@ -177,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()); + const wrapper = new AgentSessionWrapper(proc, process.cwd(), null, false, "", undefined, onlineHost); wrapper.start(); try { @@ -285,3 +297,115 @@ 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 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); + 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"], "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"]); + assert.equal(transport.endInputCalls, 0, "no protocol error disposed the child"); + assert.equal(proc.isAlive, true); + 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; + 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.throws(() => proc.release(), /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 1a53a4596..198a43211 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 `release` (after `replay`). */ + adopted?: { protocolVersion: 2 }; /** Injectable process boundary for deterministic transport tests. */ dependencies?: { resolveOmpBin?: typeof resolveOmpBin; @@ -83,6 +88,20 @@ 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; + } +} + +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; @@ -108,6 +127,14 @@ 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 `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 `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; @@ -122,66 +149,36 @@ 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; - } + 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; 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 +192,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 +223,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 +237,94 @@ 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 held, which `release` delivers next. */ + replay(lines: string[]): void { + if (this.heldOverflow) throw this.heldOverflow; + // 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, true); + } + } + + /** 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) { + const id = requestId(frame); + if (id === null || !this.replayedRequests.has(id)) this.dispatch(frame); + } + this.replayedRequests.clear(); + } + + /** + * 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` and `release` throw, 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; + } + + /** `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) { + 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, replayed); + } + + private dispatch(frame: RpcFrame, replayed = false): void { + if (this.heldFrames && !replayed) { + 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); + } 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 @@ -250,6 +335,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) => { @@ -320,14 +406,11 @@ 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. - 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/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 6cf6a2d64..7411e9226 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()); @@ -2552,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) => { @@ -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)); @@ -2985,7 +2989,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, cwd: "/w", pending: [] }] }); link.serve(ops, omp); await link.post({ type: "stdout", ch, line: respond(held) }); const state = await pending; @@ -3087,8 +3091,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 }] }); + // 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, cwd: "/w", pending: null }] }); let session; t.after(async () => { hub.closeHostLink(link.id); @@ -3143,7 +3147,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, 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"); @@ -3442,3 +3446,341 @@ 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 (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 = [], 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, ...reply }))); + }, + onLine(listener) { + transport.emit = listener; + for (const line of held) listener(line); + }, + onStderr() {}, + onExit(listener) { transport.exit = listener; }, + endInput() { + transport.kills += 1; + if (exitOnKill) queueMicrotask(() => transport.exit?.(0, null)); + }, + killTree() { + transport.kills += 1; + if (exitOnKill) 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; +} + +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, getExitedRpcSession, getRpcSession } = await runtimeJiti.import("./rpc-manager.ts"); + const id = "11111111-2222-4333-8444-adadadadad01"; + // 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, 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, `/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); +}); + +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, + 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" } }]); + 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("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"); + 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 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"; + 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, 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 7ef254434..160e6235e 100644 --- a/lib/rpc-manager.ts +++ b/lib/rpc-manager.ts @@ -1,11 +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 { @@ -33,8 +33,8 @@ 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 { localHost } from "./hosts/local-host"; +import { freezeHostLinks, getHost, lastUplinkAt, listHosts, orphanExit } from "./hosts/hub"; +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"; @@ -103,6 +103,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 @@ -294,8 +296,18 @@ 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): 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>(); + /** 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. */ @@ -340,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, ) { @@ -577,6 +589,48 @@ 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; + 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; + }); + 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 }); + // 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; + try { + this.proc.replay(replay); + } 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(); + } + } + + /** 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)); @@ -599,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) { @@ -749,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", @@ -923,7 +977,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({ @@ -946,8 +1008,12 @@ 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 (this.listeners.length > 0) { + if (id && toolName && (this.hostToolNames.has(toolName) || this.hostToolsUnknown)) { + // 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(); @@ -964,6 +1030,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. @@ -973,6 +1045,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; @@ -1142,7 +1215,10 @@ 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({ type: "host_tool_result", id, @@ -1152,6 +1228,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"); @@ -1313,7 +1416,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(); @@ -1325,6 +1430,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 internal ? [] : [...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); @@ -1369,7 +1480,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; @@ -2187,11 +2298,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; } @@ -2300,6 +2416,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(); @@ -2372,7 +2490,9 @@ function getRegistry(): Map { const cleanup = () => { // Children dying from here on are the shutdown, not finished runs. markShuttingDown(); - globalThis.__ompSessions?.forEach((s) => s.destroy()); + // 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(); }; process.once("exit", cleanup); process.once("SIGINT", cleanup); @@ -2395,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()]; @@ -2414,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; } @@ -2499,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. */ @@ -2557,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 })), ]; }, @@ -2631,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, @@ -2640,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 }; } @@ -2683,11 +2794,17 @@ 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(); + // 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. A live wrapper is past that. + 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: // workspace advisor=true forces the flag on. The gate must compare this @@ -2703,8 +2820,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(); @@ -2733,9 +2851,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, @@ -2798,15 +2913,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 +2923,76 @@ 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. 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; + 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. + 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); + // 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 + // 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(() => { + 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; +} diff --git a/lib/session-resume.test.mjs b/lib/session-resume.test.mjs index 44cc0dba1..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 } 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,10 +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, resumeInterruptedSessions } = 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 }] }); + await link.dial({ channels: [{ ch: "orphan", sessionId: remote.id, cwd: "/w", pending: null }] }); await sleep(10); assert.deepEqual(resumed, [remote]); @@ -170,3 +172,70 @@ 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) => { + // 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 () => { + 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, 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"); +}); + +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 bca4947c6..2c1911e6c 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"; @@ -198,14 +198,15 @@ 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 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(); diff --git a/lib/session-routes.test.mjs b/lib/session-routes.test.mjs index 5d966ed28..a35871d2a 100644 --- a/lib/session-routes.test.mjs +++ b/lib/session-routes.test.mjs @@ -2,11 +2,11 @@ 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 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: { @@ -16,11 +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, 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}` : ""}`), @@ -35,20 +39,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 (`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"); 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; + if (daemonOps) 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 +102,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 +120,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 +138,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 +153,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 +161,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 +171,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 +206,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"); }); }); @@ -245,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" } }), @@ -263,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 @@ -283,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-")); @@ -333,7 +415,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 +446,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 +484,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 +502,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 +532,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 +553,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 +577,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 +596,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 +647,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 +663,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 +737,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: [] } }, ]); @@ -680,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. 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) => { 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..4b347a4bf 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 @@ -463,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 @@ -542,6 +548,23 @@ $script:NotifyIcon.add_DoubleClick({ try { [System.Diagnostics.Process]::Start($ServerUrl) | Out-Null } catch { } }) +# 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" } + return "Stopped" + } catch { return "Unknown" } +} +$script:DaemonTicks = 0 +$script:DaemonState = "Checking..." + function Update-TrayUI { $statusText = switch ($script:State) { "Running" { "Running ($EffectivePort)" } @@ -552,6 +575,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)" @@ -559,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" @@ -577,6 +601,16 @@ $script:Timer.Interval = 3000 $script:Timer.add_Tick({ if ($script:IsExiting) { return } + # Every 5th tick (15 s) is enough for the daemon state. + if ($script:DaemonTicks % 5 -eq 0) { + $newDaemonState = Get-HostDaemonState + if ($newDaemonState -ne $script:DaemonState) { + $script:DaemonState = $newDaemonState + Update-TrayUI + } + } + $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 { }