The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a failed agent build retries on the next send instead of wedging the session
emozilla386fb217f531
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex 462b480d190..089c3c0ced9 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -1199,6 +1199,30 @@ def _resolve_named_custom_runtime("source": "local-runtime","requested_provider": requested_provider,}+ # No server to serve this model. Say so and stop — falling through+ # to the generic custom path sends the request to whatever provider+ # picks it up (OpenRouter with a placeholder key), and the user's+ # "local server is off" surfaces as that provider's baffling+ # "401 Invalid API key". The switch's own state picks the message:+ # the user who turned the server off gets pointed at the switch,+ # anyone else at the setup pane.+ try:+ from hermes_cli.config import load_config as _load_cfg++ _lr_enabled = bool((_load_cfg().get("local_runtime") or {}).get("enabled"))+ except Exception: # noqa: BLE001+ _lr_enabled = False+ if _lr_enabled:+ raise ValueError(+ "The local model server isn't running. It may still be "+ "starting — try again in a moment, or check Settings → "+ "Providers → Local models."+ )+ raise ValueError(+ "The local model server is turned off. Turn it back on in "+ "Settings → Providers → Local models, or switch to another "+ "model."+ )if requested_norm and requested_norm != "custom":try:diff --git a/tests/hermes_cli/test_local_runtime.py b/tests/hermes_cli/test_local_runtime.pyindex 082c22afb9b..0603e9ec296 100644--- a/tests/hermes_cli/test_local_runtime.py+++ b/tests/hermes_cli/test_local_runtime.py@@ -394,6 +394,42 @@ def test_llamacpp_endpoint_stale_state_falls_through(tmp_path, monkeypatch):assert DEFAULT_PROBE_PORTS # (import kept honest)+def test_llamacpp_dead_server_raises_friendly_error(tmp_path, monkeypatch):+ """A llamacpp send with no server must say WHY in user terms, not fall+ through to the generic custom path (which lands on a cloud provider+ with a placeholder key and surfaces as a baffling '401 Invalid API+ key'). Message tracks the off switch: enabled = probably starting;+ disabled = the user turned it off."""+ import pytest++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))++ from hermes_cli import runtime_provider as rp++ monkeypatch.setattr(+ "hermes_cli.local_runtime.endpoint.resolve_llamacpp_endpoint",+ lambda *a, **k: None)++ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"local_runtime": {"enabled": False}})+ with pytest.raises(ValueError, match="turned off"):+ rp._resolve_named_custom_runtime(requested_provider="llamacpp")++ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"local_runtime": {"enabled": True}})+ with pytest.raises(ValueError, match="isn't running"):+ rp._resolve_named_custom_runtime(requested_provider="llamacpp")++ # An explicit base_url is the user pointing at a specific server —+ # that path keeps its own error reporting, never this one.+ result = rp._resolve_named_custom_runtime(+ requested_provider="llamacpp",+ explicit_base_url="http://127.0.0.1:9999/v1")+ assert result is None or result.get("base_url", "").startswith("http://127.0.0.1:9999")++def test_llamacpp_endpoint_starting_server_resolves(tmp_path, monkeypatch):"""The restart race: state written at spawn, server not yet healthy,supervisor child alive — resolution must return the endpoint (a@@ -649,8 +685,8 @@ def test_llamacpp_endpoint_no_wait_when_not_enabled(tmp_path, monkeypatch):def test_switch_model_explicit_llamacpp_provider(tmp_path, monkeypatch, stub_server):"""The desktop dropdown path: switch_model(explicit_provider='llamacpp')- must resolve the managed provider — not 'Unknown provider' (Jeff's- round-5 symptom). E2E through the real pipeline against a stub server."""+ must resolve the managed provider — not 'Unknown provider' (the+ desktop-review symptom). E2E through the real pipeline against a stub server."""port, handler = stub_serverhandler.models = {"data": [{"id": "stub-model-a", "owned_by": "llamacpp"}]}monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))diff --git a/tests/tui_gateway/test_failed_agent_build_retry.py b/tests/tui_gateway/test_failed_agent_build_retry.pynew file mode 100644index 00000000000..2d56849d20f--- /dev/null+++ b/tests/tui_gateway/test_failed_agent_build_retry.py@@ -0,0 +1,100 @@+"""A failed agent build must not wedge the session.++The first send with the local server off fails agent init and stores+``agent_error`` with ``agent_ready`` set. Before the fix, prompt.submit's+build kick was a no-op on that state (``agent_build_started`` stayed True),+so every later send — including the error card's Retry — replayed the stored+failure even after the server came back; only NEW sessions worked. The fix+routes prompt.submit through ``_restart_completed_failed_agent_build`` first,+which clears one completed failed generation and rebuilds with fresh+provider resolution.++These tests pin the restart helper's contract directly: it is the seam the+prompt path now calls, and its answer decides retry-vs-replay.+"""++from __future__ import annotations++import threading++from tui_gateway import server+++def failed_session(tmp_path, sid: str) -> dict:+ """A session record whose deferred agent build COMPLETED in failure."""+ ready = threading.Event()+ ready.set()+ session = {+ "agent": None,+ "agent_ready": ready,+ "agent_build_started": True,+ "agent_error": "The local model server is turned off.",+ "cwd": str(tmp_path),+ "history": [],+ "history_lock": threading.RLock(),+ "profile_home": str(tmp_path),+ "running": False,+ "session_key": sid,+ }+ server._sessions[sid] = session+ return session+++def test_restart_clears_failed_generation_and_rebuilds(tmp_path, monkeypatch):+ sid = "wedged-session"+ session = failed_session(tmp_path, sid)+ failed_ready = session["agent_ready"]++ rebuilt = []+ monkeypatch.setattr(server, "_start_agent_build",+ lambda s, sess: rebuilt.append(s))++ try:+ assert server._restart_completed_failed_agent_build(+ sid, session, failed_ready) is True++ # The failed generation is gone: error cleared, fresh unset ready+ # event, build flag dropped — the next build starts from zero.+ assert session["agent_error"] is None+ assert session["agent_ready"] is not failed_ready+ assert not session["agent_ready"].is_set()+ assert "agent_build_started" not in session+ assert rebuilt == [sid]+ finally:+ server._sessions.pop(sid, None)+++def test_restart_declines_every_non_failure_state(tmp_path, monkeypatch):+ """False (caller falls through to the normal build) when there is no+ completed failure: healthy agent, build still in flight, or no error."""+ sid = "healthy-session"+ session = failed_session(tmp_path, sid)+ monkeypatch.setattr(server, "_start_agent_build",+ lambda s, sess: None)++ try:+ # Build still in flight: ready not set.+ in_flight = threading.Event()+ session["agent_ready"] = in_flight+ assert server._restart_completed_failed_agent_build(+ sid, session, in_flight) is False++ # No error recorded.+ done = threading.Event()+ done.set()+ session["agent_ready"] = done+ session["agent_error"] = None+ assert server._restart_completed_failed_agent_build(+ sid, session, done) is False++ # Agent actually built.+ session["agent_error"] = "stale text"+ session["agent"] = object()+ assert server._restart_completed_failed_agent_build(+ sid, session, done) is False++ # No ready event at all.+ assert server._restart_completed_failed_agent_build(+ sid, session, None) is False+ finally:+ server._sessions.pop(sid, None)diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 34e38aacf9a..5faf56a63fe 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -862,7 +862,18 @@ def _(rid, params: dict) -> dict:5071,f"session storage could not be written: {exc}",)- _start_agent_build(sid, session)+ # A completed FAILED build must not wedge the session: the error frame+ # says retryable, so a new send (or the error card's Retry) rebuilds the+ # agent with fresh provider resolution instead of replaying the cached+ # failure forever. Before this, only a model switch reset the failed+ # generation — a session that failed once (local server off) kept+ # erroring after the server came back, while new sessions worked. Falls+ # through to the normal build when there is no completed failure to+ # clear.+ if not _restart_completed_failed_agent_build(+ sid, session, session.get("agent_ready")+ ):+ _start_agent_build(sid, session)def run_after_agent_ready() -> None:# Patient wait (#63078): the user's message is already the accepted