Skip to content

The agent that grows with you

fix(desktop): Windows SSH host locks let a superseded backend retire

John Paul Soliva2646293a20bf
diff --git a/hermes_cli/windows_ssh_runtime.py b/hermes_cli/windows_ssh_runtime.py
index 3580c3c0c28..6d21303a020 100644
--- a/hermes_cli/windows_ssh_runtime.py
+++ b/hermes_cli/windows_ssh_runtime.py
@@ -276,12 +276,20 @@ def read_lock(ownership_id: str) -> dict[str, Any] | None:
return parsed if isinstance(parsed, dict) else None
+def _lock_record(ownership_id: str, payload: dict[str, Any]) -> bytes:
+ # The backend's owner watchdog only trusts a lock whose logPath ends in /<ownershipId>/<nonce>.log
+ # (dashboard_procs._valid_lockfile_payload); without it a superseded Windows backend never retires.
+ record = {**payload, "logPath": _log_path(ownership_id, str(payload.get("spawnNonce"))).as_posix()}
+ data = json.dumps(record, separators=(",", ":")).encode()
+ if len(data) > _MAX_JSON:
+ raise ValueError("lock payload is too large")
+ return data
+
+
def write_lock(ownership_id: str, payload: dict[str, Any]) -> None:
win32file = _win32().win32file
directory = _ensure_scope(ownership_id)
- data = json.dumps(payload, separators=(",", ":")).encode()
- if len(data) > _MAX_JSON:
- raise ValueError("lock payload is too large")
+ data = _lock_record(ownership_id, payload)
temporary = directory / f".{os.urandom(8).hex()}.lock.tmp"
_write_new(temporary, data)
win32file.MoveFileEx(str(temporary), str(_lock_path(ownership_id)),
diff --git a/tests/hermes_cli/test_web_server_owner_exit.py b/tests/hermes_cli/test_web_server_owner_exit.py
index 8c42b5c0cfe..0404d5a606f 100644
--- a/tests/hermes_cli/test_web_server_owner_exit.py
+++ b/tests/hermes_cli/test_web_server_owner_exit.py
@@ -80,3 +80,22 @@ def test_superseded_backend_retires_through_the_fence_only_when_idle():
busy = _Fence(idle=False)
assert _run(busy, [NEW, NEW, NEW]).should_exit is False # an in-flight turn keeps it up
assert busy.committed is False
+
+
+def test_lock_written_by_the_windows_ssh_runtime_lets_the_superseded_backend_retire(tmp_path, monkeypatch):
+ """A Windows SSH host's lock comes from windows_ssh_runtime.write_lock, fed the Desktop's record
+ (no logPath). The owner watchdog must accept it, or Windows hosts keep stacking backends."""
+ from pathlib import PureWindowsPath
+
+ from hermes_cli import windows_ssh_runtime
+
+ # The runtime's root is a WindowsPath on that host; pass it as data instead of faking the OS.
+ monkeypatch.setattr(windows_ssh_runtime, "_root",
+ lambda: PureWindowsPath(r"C:\Users\u\.hermes\desktop-ssh"))
+ desktop_record = {k: v for k, v in _lock(NEW).items() if k != "logPath"}
+ desktop_record.update(creationTimeNs="133700000000000000", hermesPath=r"C:\Hermes\hermes.exe")
+ lock_path = tmp_path / "desktop-ssh" / OID / "backend.lock.json"
+ lock_path.parent.mkdir(parents=True)
+ lock_path.write_bytes(windows_ssh_runtime._lock_record(OID, desktop_record))
+
+ assert should_retire_superseded(lock=read_valid_backend_lock(lock_path), my_nonce=ME, age_s=600.0)
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 65d6c3e0b12..f7076f7c7a6 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -3102,7 +3102,7 @@ dashboard:
- `trusted_proxies` — IP addresses or bounded CIDR networks allowed to supply `X-Forwarded-Proto` and `X-Forwarded-For`. Loopback remains trusted automatically. Configure this when the TLS reverse proxy connects from another container or host. Prefer the proxy's exact IP; use a small dedicated network only when its address is dynamic. Wildcards and `/0` networks are rejected.
- `oauth` / `basic_auth` / `drain_auth` — auth provider config read by the bundled dashboard-auth plugins. The drain secret itself is **not** set here; it's provisioned via the `HERMES_DASHBOARD_DRAIN_SECRET` env var. See [Web Dashboard](./features/web-dashboard.md) for full auth setup.
- `ws_ping_interval` / `ws_ping_timeout` — WebSocket keepalive tuning for non-loopback binds (loopback connections never ping). Raise these on high-latency links (Tailscale, distant SSH tunnels) where the 20 s defaults can manufacture spurious 1006 disconnects.
-- `ssh_isolated_idle_grace_s` (default `900`) — a Desktop-owned `hermes serve --isolated` backend reached over SSH is detached from the SSH session on purpose, so a laptop that sleeps mid-connection cannot tear it down; each dark-wake reconnect used to leave another backend holding `state.db`. The backend now retires itself once no client WebSocket has been connected for this long and no agent turn is running (a turn keeps it alive; an unreadable turn state keeps it alive too). Set high if you rely on a detached backend finishing long work after the laptop sleeps. Such backends also send a slow WebSocket ping (60 s, 10 min timeout) so a half-open tunnel is noticed.
+- `ssh_isolated_idle_grace_s` (default `900`) — a Desktop-owned `hermes serve --isolated` backend reached over SSH is detached from the SSH session on purpose, so a laptop that sleeps mid-connection cannot tear it down; each dark-wake reconnect used to leave another backend holding `state.db`. The backend now retires itself once no client WebSocket has been connected for this long and no agent turn is running (a turn keeps it alive; an unreadable turn state keeps it alive too). Set high if you rely on a detached backend finishing long work after the laptop sleeps. Such backends also send a slow WebSocket ping (60 s, 10 min timeout) so a half-open tunnel is noticed. Independently of this grace, a backend retires (between turns) once the Desktop's ownership lock on the remote host names a newer spawn of the same connection, so a reconnect storm cannot stack detached backends; this covers POSIX and native Windows SSH hosts.
- `ws_orphan_reap_grace_s` — how long a WS-detached session waits before the orphan reaper collects it. Raise alongside the keepalive values if clients reconnect slowly. Periodic session maintenance also completes cleanup for closed sockets and re-arms a missing orphan timer, so a detached chat cannot keep its ownership lease solely because its initial cleanup or timer was lost. Reconnecting cancels that timer; active delegated work and healthy running turns remain protected by the normal orphan-reaper checks. (`HERMES_TUI_WS_ORPHAN_REAP_GRACE_S` remains as an internal override.)
- `ws_orphan_activity_stale_s` (default `600`) — how long a detached **running** turn's activity clock (the same clock the `agent.turn_liveness` watchdog samples: API waits, stream tokens, tool heartbeats) must be idle before the orphan reaper interrupts it. A client-absent turn that is still actively producing keeps running to completion detached — closing the laptop, backgrounding the mobile app, or a desktop update no longer cancels healthy long turns; only a genuinely wedged turn is interrupted. Set `0` to interrupt at the grace window regardless of activity (old behavior).
- `startup_orphan_sweep` (default `true`) — the WS-orphan reap timer above is in-process, so a gateway restart (update, crash, systemd) before it fires leaves the session row open forever — phantom "active" work in `/resume` and dashboards. On every gateway boot — both the stdio TUI (`entry.main`) and the desktop/dashboard WebSocket sidecar (`handle_ws`) — rows with source `tui` / `desktop` / `subagent` / `unknown` (a row the token-accounting guard had to materialize itself) whose start time **and** newest message are both older than the session TTL (`HERMES_TUI_SESSION_TTL_S`, default 6 hours) are closed with `end_reason: startup_orphan_reap`. Messaging-platform sessions (Telegram, Discord, …) are never touched, live in-memory sessions (a client that already resumed) are excluded, and swept sessions remain resumable.