Skip to content

The agent that grows with you

serve: retire desktop-owned local backends on code skew; guard every model-mutating path (#99859)

Brooklyn Nicholsoneb8a1580c65c
diff --git a/hermes_cli/web_routers/models.py b/hermes_cli/web_routers/models.py
index f7e12c0171d..52360666750 100644
--- a/hermes_cli/web_routers/models.py
+++ b/hermes_cli/web_routers/models.py
@@ -327,6 +327,14 @@ async def set_model_assignment(body: ModelAssignment, profile: Optional[str] = N
raise HTTPException(status_code=400, detail="scope must be 'main' or 'auxiliary'")
with http_failure("POST /api/model/set failed", 500, detail="Failed to save model assignment"):
+ # #99859 (R2): the options picker already refuses on code skew; the WRITE path
+ # must too — a stale process persisting a post-update model string is the
+ # invalid-model-serving failure the reporter hit.
+ skew_msg = _dashboard_code_skew_guard()
+ if skew_msg:
+ _log.warning("POST /api/model/set refused: %s", skew_msg)
+ raise HTTPException(status_code=503, detail=f"Restart required: {skew_msg}")
+
# Expensive-model warning runs BEFORE the profile scope is entered: _profile_scope
# must never be held across an await (the RLock is reentrant per-thread, so a second
# coroutine interleaving on the event-loop thread could cross-restore module globals).
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index 0bb9306832b..e19d3eb4fa5 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -1355,8 +1355,13 @@ def _on_server_started(
except (TypeError, ValueError):
grace = DEFAULT_IDLE_GRACE_S
start_idle_watchdog(server, app.state.ssh_isolated_clients, grace_s=grace)
- # A connected client keeps the idle watchdog quiet forever, and the host's updater may not
- # restart this backend, so it retires itself (between turns) when the install moves on.
+ if getattr(app.state, "ssh_isolated_clients", None) is not None or is_desktop_owned_backend():
+ # The host's updater never restarts this backend (SSH-isolated: only the remote Desktop
+ # client holds its token and owner nonce, #91668/#101626; Desktop-owned local serve:
+ # the updater defers to the app's ledger-verified restart and the backend otherwise
+ # outlives the handoff, #99859), so it retires itself (between turns) when the install
+ # moves on. The retirement fence closes admission process-wide before the exit, so a
+ # connected Desktop just sees its next request reconnect-respawn the backend on new code.
from hermes_cli.web_server_skew_exit import start_code_skew_watchdog
start_code_skew_watchdog(server)
diff --git a/tests/hermes_cli/test_code_skew.py b/tests/hermes_cli/test_code_skew.py
index 26dc799ba5d..740c9de38b6 100644
--- a/tests/hermes_cli/test_code_skew.py
+++ b/tests/hermes_cli/test_code_skew.py
@@ -143,3 +143,42 @@ class TestModelOptionsSkewGuard:
assert result == expected
assert payload_calls == [1]
+
+
+class TestModelSetSkewGuard:
+ """#99859 (R2): POST /api/model/set is the WRITE twin of the guarded picker —
+ a stale process persisting a post-update model string serves an invalid model
+ after the restart it itself needs. It must refuse with the same 503 and never
+ reach the assignment apply."""
+
+ def test_stale_model_set_returns_503_and_skips_assignment(self, monkeypatch):
+ from fastapi import HTTPException
+
+ monkeypatch.setattr(code_skew, "detect_code_skew", lambda: ("abc1234567", "def4567890"))
+
+ applied: list = []
+ monkeypatch.setattr(_rt_models, "_apply_model_assignment_sync", lambda *a, **k: applied.append(1))
+
+ body = _rt_models.ModelAssignment(scope="main", provider="nous", model="some-model")
+ with pytest.raises(HTTPException) as excinfo:
+ asyncio.run(_rt_models.set_model_assignment(body))
+
+ assert excinfo.value.status_code == 503
+ assert "restart" in str(excinfo.value.detail).lower()
+ assert applied == []
+
+ def test_fresh_model_set_proceeds(self, monkeypatch):
+ monkeypatch.setattr(code_skew, "detect_code_skew", lambda: None)
+
+ async def _to_thread(fn):
+ return fn()
+
+ monkeypatch.setattr(_rt_models.asyncio, "to_thread", _to_thread)
+ monkeypatch.setattr(_web_server_profiles, "_profile_scope", lambda profile: contextlib.nullcontext())
+ monkeypatch.setattr(_rt_models, "_prepare_main_assignment", lambda cfg, *a: {"ok": True})
+ monkeypatch.setattr(_rt_models, "_apply_model_assignment_sync",
+ lambda *a, **k: {"ok": True, "scope": "main"})
+
+ body = _rt_models.ModelAssignment(scope="main", provider="nous", model="some-model")
+ result = asyncio.run(_rt_models.set_model_assignment(body))
+ assert result["ok"] is True
diff --git a/tests/tui_gateway/test_model_rpc_skew_guard.py b/tests/tui_gateway/test_model_rpc_skew_guard.py
new file mode 100644
index 00000000000..021d4a1da11
--- /dev/null
+++ b/tests/tui_gateway/test_model_rpc_skew_guard.py
@@ -0,0 +1,66 @@
+"""#99859 (R2): the TUI gateway's model-serving JSON-RPCs refuse on code skew.
+
+The Desktop's Models page reaches the same inventory through ``model.options`` /
+``model.save_key`` that the browser dashboard reaches through the guarded
+``/api/model/options``; a backend kept alive across ``hermes update`` serves stale
+``sys.modules`` and would resolve a post-update model string against them (the
+reporter's ``agent_init_failed``). Both RPCs must answer the same "restart" error
+the gateway's ``/model`` switch already returns, and never reach the payload build.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import Mock
+
+import tui_gateway.server as server
+
+
+def _call(method: str, params: dict | None = None) -> dict:
+ return server._methods[method]("rid", params or {})
+
+
+def test_stale_model_options_refuses_instead_of_building(tmp_path, monkeypatch):
+ import gateway.code_skew as code_skew
+
+ monkeypatch.setattr(code_skew, "detect_code_skew", lambda: ("abc1234567", "def4567890"))
+ builds = []
+ monkeypatch.setattr("hermes_cli.inventory.build_model_options_payload",
+ Mock(side_effect=lambda *a, **k: builds.append(1)))
+
+ resp = _call("model.options")
+ assert resp.get("error") is not None, resp
+ assert resp["error"]["code"] == 5098
+ assert "abc1234567" in resp["error"]["message"]
+ assert "def4567890" in resp["error"]["message"]
+ assert "restart" in resp["error"]["message"].lower()
+ assert builds == []
+
+
+def test_stale_model_save_key_refuses_instead_of_writing(tmp_path, monkeypatch):
+ import gateway.code_skew as code_skew
+
+ monkeypatch.setattr(code_skew, "detect_code_skew", lambda: ("abc1234567", "def4567890"))
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+
+ resp = _call("model.save_key", {"slug": "zai", "api_key": "sk-canary"})
+ assert resp.get("error") is not None, resp
+ assert resp["error"]["code"] == 5098
+ # The stale process never touches the key store.
+ assert "sk-canary" not in (tmp_path / ".env").read_text(encoding="utf-8") if (tmp_path / ".env").exists() else True
+
+
+def test_fresh_model_options_builds_payload_unchanged(tmp_path, monkeypatch):
+ import gateway.code_skew as code_skew
+
+ monkeypatch.setattr(code_skew, "detect_code_skew", lambda: None)
+ monkeypatch.setattr(server, "_hermes_home", tmp_path)
+ monkeypatch.setattr(server, "_cfg_cache", None)
+ monkeypatch.setattr(server, "_cfg_sig", None)
+ monkeypatch.setattr(server, "_cfg_path", None)
+ expected = {"providers": []}
+ monkeypatch.setattr("hermes_cli.inventory.build_model_options_payload",
+ Mock(return_value=expected))
+
+ resp = _call("model.options")
+ assert "result" in resp, resp
+ assert resp["result"] == expected
diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.py
index a1a6bc518fc..4ebe4a1c439 100644
--- a/tui_gateway/methods_complete.py
+++ b/tui_gateway/methods_complete.py
@@ -336,10 +336,31 @@ def _session_agent(params: dict):
return session.get("agent") if session else None
+def _model_skew_err(rid) -> dict | None:
+ """#99859 (R2): refuse model-serving/holding RPCs when this process runs stale
+ code — the TUI/desktop would otherwise resolve a post-update model string against
+ stale cached modules (the reporter's agent_init_failed). Mirrors the dashboard's
+ ``_dashboard_code_skew_guard`` and the gateway's ``_model_switch_skew_guard``;
+ never a false positive (non-git installs detect nothing)."""
+ from gateway.code_skew import detect_code_skew
+
+ skew = detect_code_skew()
+ if not skew:
+ return None
+ boot_rev, disk_rev = skew
+ from agent.i18n import t
+
+ return _err(rid, 5098, t("gateway.model.error_prefix", error=t(
+ "gateway.model.err_skew", boot_rev=boot_rev, disk_rev=disk_rev)))
+
+
@method("model.options")
@_profile_scoped
@_catch(5033)
def _(rid, params: dict) -> dict:
+ skew = _model_skew_err(rid)
+ if skew is not None:
+ return skew
from hermes_cli.inventory import build_model_options_payload
# A spawned agent owns the live provider/model/base_url; empty attributes must
# NOT clobber disk config (with_overrides is truthy-only).
@@ -353,6 +374,9 @@ def _(rid, params: dict) -> dict:
@_catch(5034)
def _(rid, params: dict) -> dict:
"""Save an API key for ``slug``; return its refreshed provider row (model.options shape + ``authenticated``)."""
+ skew = _model_skew_err(rid)
+ if skew is not None:
+ return skew
from hermes_cli.auth import PROVIDER_REGISTRY
from hermes_cli.config import is_managed
slug, api_key = (params.get("slug") or "").strip(), (params.get("api_key") or "").strip()