Skip to content

The agent that grows with you

fix(gateway): keep persisted model routes consistent

fangliquanflq095d25c6122a
diff --git a/gateway/slash_commands.py b/gateway/slash_commands.py
index 4aca0b876ce..925c64b3a7d 100644
--- a/gateway/slash_commands.py
+++ b/gateway/slash_commands.py
@@ -611,6 +611,7 @@ class GatewaySlashCommandsMixin:
# single source of truth; reading it here keeps /status accurate
# without duplicating token writes into two stores.
db_total_tokens = 0
+ persisted_route: dict[str, Any] = {}
if self._session_db:
try:
title = await self._session_db.get_session_title(session_entry.session_id)
@@ -629,6 +630,14 @@ class GatewaySlashCommandsMixin:
)
except Exception:
db_total_tokens = 0
+ try:
+ route = await self._session_db.get_dominant_session_model_route(
+ session_entry.session_id
+ )
+ if isinstance(route, dict):
+ persisted_route = route
+ except Exception:
+ persisted_route = {}
# Resolve model/context for cockpit-style status. Prefer the live or
# cached agent because it carries the actual runtime route and context
@@ -651,20 +660,33 @@ class GatewaySlashCommandsMixin:
model_name = ""
provider_name = ""
base_url = ""
+ route_resolved = False
context_used = 0
context_total = 0
if status_agent is not None and status_agent is not _AGENT_PENDING_SENTINEL:
- model_name = _clean_str(getattr(status_agent, "model", ""))
- provider_name = _clean_str(getattr(status_agent, "provider", ""))
- base_url = _clean_str(getattr(status_agent, "base_url", ""))
+ live_model = _clean_str(getattr(status_agent, "model", ""))
+ live_provider = _clean_str(getattr(status_agent, "provider", ""))
+ if live_model and live_provider:
+ model_name = live_model
+ provider_name = live_provider
+ base_url = _clean_str(getattr(status_agent, "base_url", ""))
+ route_resolved = True
ctx = getattr(status_agent, "context_compressor", None)
if ctx is not None:
context_used = _int_value(getattr(ctx, "last_prompt_tokens", 0))
context_total = _int_value(getattr(ctx, "context_length", 0))
- model_name = model_name or _clean_str(session_row.get("model"))
- provider_name = provider_name or _clean_str(session_row.get("billing_provider"))
- base_url = base_url or _clean_str(session_row.get("billing_base_url"))
+ persisted_model = _clean_str(persisted_route.get("model"))
+ persisted_provider = _clean_str(persisted_route.get("billing_provider"))
+ if not route_resolved and persisted_model and persisted_provider:
+ model_name = persisted_model
+ provider_name = persisted_provider
+ base_url = _clean_str(persisted_route.get("billing_base_url"))
+ route_resolved = True
+ if not route_resolved:
+ model_name = _clean_str(session_row.get("model"))
+ provider_name = _clean_str(session_row.get("billing_provider"))
+ base_url = _clean_str(session_row.get("billing_base_url"))
context_used = context_used or _int_value(getattr(session_entry, "last_prompt_tokens", 0))
user_config: dict[str, Any] = {}
@@ -5226,10 +5248,19 @@ class GatewaySlashCommandsMixin:
try:
_entry_for_billing = await self.async_session_store.get_or_create_session(source)
persisted = await self._session_db.get_session(_entry_for_billing.session_id) or {}
+ route = await self._session_db.get_dominant_session_model_route(
+ _entry_for_billing.session_id
+ )
+ persisted_route = route if isinstance(route, dict) else {}
except Exception:
persisted = {}
- provider = provider or persisted.get("billing_provider")
- base_url = base_url or persisted.get("billing_base_url")
+ persisted_route = {}
+ if persisted_route.get("billing_provider"):
+ provider = persisted_route["billing_provider"]
+ base_url = persisted_route.get("billing_base_url")
+ else:
+ provider = persisted.get("billing_provider")
+ base_url = persisted.get("billing_base_url")
if wants_reset:
normalized_provider = str(provider or "").strip().lower()
diff --git a/hermes_state.py b/hermes_state.py
index c28f9cb0644..834a56b91f1 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -7822,6 +7822,35 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
row = cursor.fetchone()
return self._session_row_dict(row) if row else None
+ def get_dominant_session_model_route(
+ self, session_id: str
+ ) -> Optional[Dict[str, Any]]:
+ """Return the main-loop model route that served most API calls.
+
+ ``sessions`` is a legacy aggregate row and can hold model/provider fields
+ written by different route changes. ``session_model_usage`` keeps the
+ coherent per-call tuple, so persisted status and billing reads should use
+ its dominant main-loop route when one is available.
+ """
+ self.flush_token_counts()
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ """SELECT model, billing_provider, billing_base_url, billing_mode,
+ api_call_count
+ FROM session_model_usage
+ WHERE session_id = ?
+ AND task = ''
+ AND model <> 'unknown'
+ AND billing_provider <> ''
+ ORDER BY api_call_count DESC,
+ (input_tokens + output_tokens + cache_read_tokens +
+ cache_write_tokens + reasoning_tokens) DESC,
+ last_seen DESC
+ LIMIT 1""",
+ (session_id,),
+ ).fetchone()
+ return dict(row) if row else None
+
def resolve_session_id(self, session_id_or_prefix: str) -> Optional[str]:
"""Resolve an exact or uniquely prefixed session ID to the full ID.
diff --git a/tests/gateway/test_status_command.py b/tests/gateway/test_status_command.py
index 799c3aa1b1c..32a60024ccb 100644
--- a/tests/gateway/test_status_command.py
+++ b/tests/gateway/test_status_command.py
@@ -1,4 +1,4 @@
-from hermes_state import AsyncSessionDB
+from hermes_state import AsyncSessionDB, SessionDB
"""Tests for gateway /status behavior and token persistence."""
from datetime import datetime
@@ -141,6 +141,54 @@ async def test_status_command_includes_live_agent_model_and_context():
assert "**Lifetime tokens billed:** 1,250" in result
+async def test_status_command_uses_dominant_persisted_model_route(tmp_path):
+ """Persisted status must not combine a model and provider from different calls."""
+ session_entry = SessionEntry(
+ session_key=build_session_key(_make_source()),
+ session_id="sess-1",
+ created_at=datetime.now(),
+ updated_at=datetime.now(),
+ platform=Platform.TELEGRAM,
+ chat_type="dm",
+ )
+ runner = _make_runner(session_entry)
+ db = SessionDB(db_path=tmp_path / "state.db")
+ runner._session_db = AsyncSessionDB(db)
+ try:
+ db.create_session("sess-1", "telegram", model="z-ai/glm-5.2")
+ db.update_token_counts(
+ "sess-1",
+ model="z-ai/glm-5.2",
+ billing_provider="nvidia",
+ billing_base_url="https://integrate.api.nvidia.com/v1/",
+ input_tokens=480,
+ api_call_count=48,
+ )
+ db.update_token_counts(
+ "sess-1",
+ model="upstage/solar-pro4:free",
+ billing_provider="nous",
+ billing_base_url="https://inference-api.nousresearch.com/v1/",
+ input_tokens=60,
+ api_call_count=6,
+ )
+ # Reproduce the inconsistent legacy summary observed in #87227.
+ db.update_session_model("sess-1", "z-ai/glm-5.2")
+ db.update_session_billing_route(
+ "sess-1",
+ provider="nous",
+ base_url="https://inference-api.nousresearch.com/v1/",
+ )
+
+ result = await runner._handle_message(_make_event("/status"))
+
+ assert "**Model:** `z-ai/glm-5.2` (nvidia)" in result
+ assert "**Model:** `z-ai/glm-5.2` (nous)" not in result
+ finally:
+ db.close()
+
+
@pytest.mark.asyncio
async def test_agents_command_reports_active_agents_and_processes(monkeypatch):
session_key = build_session_key(_make_source())
diff --git a/tests/gateway/test_usage_command.py b/tests/gateway/test_usage_command.py
index 0e0e2ec7da1..9006dd0d6ea 100644
--- a/tests/gateway/test_usage_command.py
+++ b/tests/gateway/test_usage_command.py
@@ -162,6 +162,44 @@ class TestUsageAccountSection:
assert "πŸ“Š **Session Info**" in result
assert "πŸ“ˆ **Account limits**" in result
+ @pytest.mark.asyncio
+ async def test_usage_command_prefers_dominant_persisted_route(self, monkeypatch):
+ runner = _make_runner(SK)
+ runner._session_db = AsyncSessionDB(MagicMock())
+ runner._session_db._db.get_session.return_value = {
+ "billing_provider": "nous",
+ "billing_base_url": "https://inference-api.nousresearch.com/v1/",
+ }
+ runner._session_db._db.get_dominant_session_model_route.return_value = {
+ "model": "z-ai/glm-5.2",
+ "billing_provider": "nvidia",
+ "billing_base_url": "https://integrate.api.nvidia.com/v1/",
+ }
+ session_entry = MagicMock(session_id="sess-1")
+ runner.session_store.get_or_create_session.return_value = session_entry
+
+ calls = []
+
+ async def _fake_to_thread(fn, *args, **kwargs):
+ calls.append({"args": args, "kwargs": kwargs})
+ return fn(*args, **kwargs)
+
+ monkeypatch.setattr("gateway.run.asyncio.to_thread", _fake_to_thread)
+ monkeypatch.setattr(
+ "gateway.slash_commands.fetch_account_usage",
+ lambda provider, base_url=None, api_key=None: object(),
+ )
+ monkeypatch.setattr(
+ "gateway.slash_commands.render_account_usage_lines",
+ lambda snapshot, markdown=False: ["account limits"],
+ )
+ monkeypatch.setattr("agent.account_usage.nous_credits_lines", lambda markdown=False: [])
+
+ await runner._handle_usage_command(MagicMock())
+
+ account_call = next(c for c in calls if c["args"] == ("nvidia",))
+ assert account_call["kwargs"]["base_url"] == "https://integrate.api.nvidia.com/v1/"
+
class TestUsageReset:
"""`/usage reset [--force]` β€” banked Codex reset redemption via the gateway."""