Skip to content

The agent that grows with you

fix(tui_gateway): resume on the route in model_config.gateway_runtime (#125942, salvage #125956)

teknium133c6ab002d1f
diff --git a/hermes_state_gateway.py b/hermes_state_gateway.py
index a15f92e6ee3..4a0a245fdc0 100644
--- a/hermes_state_gateway.py
+++ b/hermes_state_gateway.py
@@ -776,9 +776,9 @@ class SessionGatewayMixin:
def session_gateway_runtime(session_meta: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""Read the persisted runtime route off a session row dict (``model_config`` as
JSON string or parsed dict). Precedence: nested ``gateway_runtime`` (gateway sync /
- CLI ``/model``), then top-level ``provider``/``base_url``/``api_mode`` (TUI), then
- ``billing_provider`` so sessions that never ran ``/model`` still restore the
- provider that served them. Empty dict on parse failure — resume uses ambient config."""
+ CLI ``/model``), then top-level ``provider``/``base_url``/``api_mode`` (TUI), with
+ ``billing_provider`` filling a missing provider so sessions that never ran ``/model``
+ still restore the provider that served them. Empty dict on parse failure — resume uses ambient config."""
from hermes_state import _BARE_BILLING_PROVIDERS
raw = (session_meta or {}).get("model_config")
if isinstance(raw, str):
@@ -794,14 +794,14 @@ class SessionGatewayMixin:
if isinstance(runtime, dict) and runtime.get("provider"):
return {k: v for k, v in runtime.items() if v is not None}
top_level = {key: raw.get(key) for key in ("provider", "base_url", "api_mode") if raw.get(key)}
- if top_level:
- return top_level
# billing_provider is COALESCE-written on the first accounted API call — the only durable
# record for sessions that never ran /model. Bare buckets ("auto"/"custom") are not
# routable identities; filter them so resume falls back to the ambient default.
billing_provider = str((session_meta or {}).get("billing_provider") or "").strip()
if billing_provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:
- return {"provider": billing_provider}
+ top_level.setdefault("provider", billing_provider)
+ if top_level:
+ return top_level
if not isinstance(runtime, dict):
return {}
return {k: v for k, v in runtime.items() if v is not None}
diff --git a/tests/tui_gateway/test_resume_switched_provider_endpoint.py b/tests/tui_gateway/test_resume_switched_provider_endpoint.py
index 4d326eeceb8..2ac478ec90b 100644
--- a/tests/tui_gateway/test_resume_switched_provider_endpoint.py
+++ b/tests/tui_gateway/test_resume_switched_provider_endpoint.py
@@ -33,3 +33,24 @@ def test_resume_drops_previous_providers_endpoint(tmp_path, row_origin):
assert (desktop["provider"], desktop["base_url"], desktop["api_mode"]) == ("openai-codex", None, None)
assert stored_session_route(row, current_model="openai/gpt-6-luna", current_provider="nous") == (
"gpt-6-luna-900k", "openai-codex", None, None, True)
+
+
+def test_resume_honors_gateway_runtime_over_first_call_billing_provider():
+ """The messaging gateway persists the route it last ran only in ``model_config.gateway_runtime``;
+ ``billing_provider`` is frozen at the first accounted call. Desktop resume must read the nested
+ route like CLI ``--resume`` does, not recombine the current model with the stale bucket (#125942)."""
+ row = {"model": "gpt-6-sol", "billing_provider": "anthropic", "model_config": json.dumps(
+ {"gateway_runtime": {"provider": "openai-codex", "base_url": None, "api_mode": "codex_responses"}})}
+ desktop = _stored_session_runtime_overrides(row)["model_override"]
+ assert (desktop["provider"], desktop["base_url"], desktop["api_mode"]) == ("openai-codex", None, "codex_responses")
+ assert stored_session_route(row, current_model="gpt-6-sol", current_provider="anthropic")[1:4] == (
+ "openai-codex", None, "codex_responses")
+
+
+def test_resume_prefers_gateway_runtime_over_stale_top_level_keys():
+ """A gateway turn after a Desktop pick rewrites only ``gateway_runtime``, so the nested route is the
+ newest one — same precedence as ``SessionDB.session_gateway_runtime``."""
+ row = {"model": "gpt-6-sol", "model_config": json.dumps(
+ {"provider": "anthropic", **NOUS_ROUTE, "gateway_runtime": {"provider": "openai-codex", "api_mode": "codex_responses"}})}
+ desktop = _stored_session_runtime_overrides(row)["model_override"]
+ assert (desktop["provider"], desktop["base_url"], desktop["api_mode"]) == ("openai-codex", None, "codex_responses")
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 466f3becd40..4489008cb64 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1500,16 +1500,6 @@ def _resolve_startup_runtime() -> tuple[str, str | None]:
return model, None
-# Bare billing buckets are not routable provider identities; restoring one as a session provider override
-# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).
-# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default
-# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully
-# routable provider with its own API key and base_url. Sessions that used OpenRouter store
-# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom
-# endpoint), which is the wrong provider for the stored model. See #57588.
-from hermes_state import _BARE_BILLING_PROVIDERS
-
-
def _is_routable_provider(provider: str) -> bool:
with contextlib.suppress(Exception):
from hermes_cli.runtime_provider import is_routable_provider
@@ -1570,15 +1560,13 @@ def _stored_session_runtime_overrides(row: dict | None) -> dict:
if room_plumbing or (_row_follows_profile(row) and not composer_profile_matches):
return {}
overrides: dict = {}
- field = lambda k: str(model_config.get(k) or "").strip()
model = str(row.get("model") or model_config.get("model") or "").strip()
- # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which
- # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.
- provider = field("provider")
- billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()
- if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:
- provider = billing_provider
- base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")
+ # Canonical route reader shared with CLI --resume: nested ``gateway_runtime`` (the route the messaging
+ # gateway last ran) before the TUI's top-level keys, then a routable ``billing_provider`` (#125942).
+ from hermes_state import SessionDB
+ route = SessionDB.session_gateway_runtime(row)
+ provider, base_url, api_mode = (str(route.get(k) or "").strip() for k in ("provider", "base_url", "api_mode"))
+ service_tier = str(model_config.get("service_tier") or "").strip()
reasoning_config = model_config.get("reasoning_config")
from hermes_cli.runtime_provider import is_foreign_provider_endpoint
if is_foreign_provider_endpoint(provider, base_url):