Skip to content

The agent that grows with you

fix(tui): bind session.usage account fetch to the session profile scope

aydnOktayfd7b4f4f39ce
diff --git a/tests/tui_gateway/test_session_usage_account_lines.py b/tests/tui_gateway/test_session_usage_account_lines.py
index e9d19461e78..048d97275da 100644
--- a/tests/tui_gateway/test_session_usage_account_lines.py
+++ b/tests/tui_gateway/test_session_usage_account_lines.py
@@ -48,3 +48,95 @@ def test_session_usage_rpc_ships_account_lines_for_the_live_route():
# Fetched against the session's own route, not a default endpoint.
assert seen == [("openai-codex", "https://chatgpt.example/backend-api", "tok")]
assert result["account_lines"]
+
+
+def test_session_usage_binds_session_profile_scope_for_account_lines():
+ """#132422: multi-profile hosting — account fetch must run inside the session profile scope."""
+ from tui_gateway import server
+
+ agent = SimpleNamespace(provider="anthropic", base_url=None, api_key=None)
+ session = {
+ "agent": agent,
+ "profile_home": "/tmp/hermes-profiles/coder",
+ "history": [],
+ "running": False,
+ "session_key": "sess-scoped",
+ }
+ sid = "sid-usage-scoped"
+ server._sessions[sid] = session
+ scoped: list[str] = []
+
+ class _Scope:
+ def __enter__(self):
+ scoped.append("enter")
+ return self
+
+ def __exit__(self, *exc):
+ scoped.append("exit")
+ return False
+
+ def _scope(sess, **kwargs):
+ assert sess is session
+ return _Scope()
+
+ def _fetch(provider, *, base_url=None, api_key=None):
+ assert "enter" in scoped and "exit" not in scoped
+ return _codex_snapshot()
+
+ try:
+ with (
+ patch.object(server, "_get_usage", return_value={"calls": 0, "input": 0, "output": 0, "total": 0}),
+ patch.object(server, "_session_profile_runtime_scope", _scope),
+ patch("agent.account_usage.fetch_account_usage", _fetch),
+ patch("agent.account_usage.nous_credits_lines", lambda **kw: []),
+ ):
+ r = server._methods["session.usage"]("r1", {"session_id": sid})
+ finally:
+ server._sessions.pop(sid, None)
+
+ assert "error" not in r, r
+ assert scoped == ["enter", "exit"]
+ assert r["result"]["account_lines"]
+
+
+def test_session_usage_pre_agent_uses_scoped_config_provider():
+ """#132422: before the first turn, provider comes from the session profile's config."""
+ from tui_gateway import server
+
+ session = {
+ "agent": None,
+ "profile_home": "/tmp/hermes-profiles/coder",
+ "history": [],
+ "running": False,
+ "session_key": "sess-pre",
+ }
+ sid = "sid-usage-pre"
+ server._sessions[sid] = session
+ fetch_calls: list[str] = []
+
+ class _Scope:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ return False
+
+ def _fetch(provider, *, base_url=None, api_key=None):
+ fetch_calls.append(provider)
+ return _codex_snapshot()
+
+ try:
+ with (
+ patch.object(server, "_get_usage", return_value={}),
+ patch.object(server, "_session_profile_runtime_scope", lambda sess, **kw: _Scope()),
+ patch.object(server, "_config_model_target", lambda: ("claude-opus", "anthropic")),
+ patch("agent.account_usage.fetch_account_usage", _fetch),
+ patch("agent.account_usage.nous_credits_lines", lambda **kw: []),
+ ):
+ r = server._methods["session.usage"]("r1", {"session_id": sid})
+ finally:
+ server._sessions.pop(sid, None)
+
+ assert "error" not in r, r
+ assert fetch_calls == ["anthropic"]
+ assert r["result"]["account_lines"]
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index f642cd9782b..10167250e1f 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1465,14 +1465,22 @@ def _(rid, params: dict, session: dict) -> dict:
def _account_usage_lines(session: dict) -> list[str]:
"""Rendered account-limit lines for the session's route: the live agent's provider/endpoint when
- built, else the configured ``model.provider`` (on-disk credentials suffice, e.g. Codex OAuth)."""
+ built, else the configured ``model.provider`` (on-disk credentials suffice, e.g. Codex OAuth).
+
+ Must run under the session's profile secret/config scope (#132422): multi-profile hosting
+ leaves ``os.environ`` / ``get_secret()`` on the launch profile, so an unscoped Anthropic OAuth
+ fetch raises ``UnscopedSecretError`` and the Desktop usage feed silently omits ``account_lines``.
+ Inside the scope, ``_config_model_target()`` also resolves the *session* profile's provider
+ when the agent is not built yet (pre-first-turn).
+ """
from agent.account_usage import fetch_account_usage, render_account_usage_lines
agent = session.get("agent")
- provider = getattr(agent, "provider", None) or _config_model_target()[1]
- if not provider:
- return []
- snapshot = fetch_account_usage(
- provider, base_url=getattr(agent, "base_url", None), api_key=getattr(agent, "api_key", None))
+ with _session_profile_runtime_scope(session):
+ provider = getattr(agent, "provider", None) or _config_model_target()[1]
+ if not provider:
+ return []
+ snapshot = fetch_account_usage(
+ provider, base_url=getattr(agent, "base_url", None), api_key=getattr(agent, "api_key", None))
return render_account_usage_lines(snapshot)