Skip to content

The agent that grows with you

fix(desktop): /usage shows provider account limits before the first message

Tekniumd37c1202632f
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.test.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.test.ts
index ec180750861..d9f29e8a7db 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.test.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.test.ts
@@ -471,26 +471,19 @@ describe('renderRpcResult', () => {
)
})
- it('appends account_lines before credits_lines when present', () => {
+ it('appends credits_lines when present', () => {
const body = renderRpcResult(
{
calls: 1,
input: 10,
output: 20,
total: 30,
- account_lines: ['πŸ“ˆ Account limits', 'Provider: openai-codex (Plus)', 'Weekly: 12% used'],
credits_lines: ['Nous credits: 8,420 remaining', 'Resets: 2026-08-01']
},
'usage'
)
- expect(body.split('\n').slice(1)).toEqual([
- 'πŸ“ˆ Account limits',
- 'Provider: openai-codex (Plus)',
- 'Weekly: 12% used',
- 'Nous credits: 8,420 remaining',
- 'Resets: 2026-08-01'
- ])
+ expect(body.split('\n').slice(1)).toEqual(['Nous credits: 8,420 remaining', 'Resets: 2026-08-01'])
})
})
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
index 96fbd313108..ced001ba777 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/utils.ts
@@ -537,7 +537,7 @@ export function slashStatusText(command: string, output: string): string {
* because it needs transcript replacement)
* - `session.status`: { output: "<multi-line plain text>" }
* - `session.save`: { file: "<absolute path>" }
- * - `session.usage`: { calls, input, output, total, account_lines?, credits_lines? }
+ * - `session.usage`: { calls, input, output, total, credits_lines? }
* - `session.steer`: { status: 'queued' | 'rejected', text }
* - `process.stop`: { killed: boolean }
* - `agents.list`: { processes: [{ session_id, command, status, uptime }] }
@@ -596,7 +596,7 @@ export function renderRpcResult(response: unknown, name: string): string {
return r.output
}
- // session.usage β€” { calls, input, output, total, account_lines?, credits_lines? }
+ // session.usage β€” { calls, input, output, total, credits_lines? }
if ('total' in r || 'input' in r || 'output' in r || 'calls' in r) {
const calls = Number(r.calls ?? 0)
const input = Number(r.input ?? 0)
@@ -607,13 +607,10 @@ export function renderRpcResult(response: unknown, name: string): string {
`Usage: ${calls.toLocaleString()} calls Β· ${input.toLocaleString()} in / ${output.toLocaleString()} out Β· ${total.toLocaleString()} total`
]
- // Provider account limits (e.g. Codex quota windows) first, then Nous credits β€” same order as CLI /usage.
- for (const extra of [r.account_lines, r.credits_lines]) {
- if (Array.isArray(extra)) {
- for (const line of extra) {
- if (typeof line === 'string' && line.trim()) {
- lines.push(line.trim())
- }
+ if (Array.isArray(r.credits_lines)) {
+ for (const line of r.credits_lines) {
+ if (typeof line === 'string' && line.trim()) {
+ lines.push(line.trim())
}
}
}
diff --git a/tests/tui_gateway/test_session_usage_account_lines.py b/tests/tui_gateway/test_session_usage_account_lines.py
index 06065460013..ad966ff60da 100644
--- a/tests/tui_gateway/test_session_usage_account_lines.py
+++ b/tests/tui_gateway/test_session_usage_account_lines.py
@@ -1,99 +1,50 @@
-"""``session.usage`` RPC (Desktop usage feed) carries the provider account-limits block.
+"""Desktop/TUI ``/usage`` (``slash.exec``) shows provider account limits before the first turn.
-The CLI/TUI slash worker and gateway ``/usage`` render Codex quota windows via
-``render_account_usage_lines``; the Desktop feed reads ``session.usage`` instead, so the RPC
-must ship the same lines (``account_lines``) or that surface silently omits them.
+Account limits need only the session profile's configured provider and its credentials, never a
+built agent, and the fetch must run inside that profile's secret scope: on a multiplexed backend a
+second profile's key is unreadable outside it (#132422).
"""
-from datetime import datetime, timezone, UTC
-from types import SimpleNamespace
+from datetime import UTC, datetime
from unittest.mock import patch
from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow
-def _codex_snapshot() -> AccountUsageSnapshot:
+def _snapshot() -> AccountUsageSnapshot:
return AccountUsageSnapshot(
- provider="openai-codex", source="usage_api", fetched_at=datetime.now(UTC), plan="Plus",
- windows=(AccountUsageWindow(label="Weekly", used_percent=12.0),),
+ provider="openrouter", source="usage_api", fetched_at=datetime.now(UTC),
+ windows=(AccountUsageWindow(label="API key quota", used_percent=2.0),),
)
-def test_session_usage_rpc_ships_account_lines_for_the_live_route():
+def test_usage_slash_shows_account_limits_before_first_turn_inside_session_scope():
from tui_gateway import server
- agent = SimpleNamespace(provider="openai-codex", base_url="https://chatgpt.example/backend-api",
- api_key="tok", model="gpt-5.3-codex")
- session = {"agent": agent, "history": [], "running": False, "session_key": "sess-usage"}
- sid = "sid-usage-account"
- server._sessions[sid] = session
- seen: list[tuple] = []
-
- def _fetch(provider, *, base_url=None, api_key=None):
- seen.append((provider, base_url, api_key))
- return _codex_snapshot()
-
- try:
- with (
- patch.object(server, "_get_usage", return_value={"calls": 1, "input": 10, "output": 20, "total": 30}),
- 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
- result = r["result"]
- assert result["total"] == 30 and "credits_lines" not in result
- # 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": "/nonexistent/hermes-profiles/coder",
- "history": [],
- "running": False,
- "session_key": "sess-scoped",
- }
- sid = "sid-usage-scoped"
- server._sessions[sid] = session
+ session = {"agent": None, "profile_home": "/nonexistent/hermes-profiles/coder", "history": [],
+ "running": False, "session_key": "sess-usage"}
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 scoped == ["enter"], scoped # the profile's key is only readable inside its scope
+ return _snapshot()
+
+ with (
+ patch.object(server, "_session_usage_snapshot", return_value={}),
+ patch.object(server, "_session_profile_runtime_scope", lambda sess, **kw: _Scope()),
+ patch.object(server, "_config_model_target", lambda: ("openai/gpt-5-mini", "openrouter")),
+ patch("agent.account_usage.fetch_account_usage", _fetch),
+ patch("agent.account_usage.nous_credits_lines", lambda **kw: []),
+ ):
+ out = server._live_slash_command_output("sid-usage", session, "usage", "")
- assert "error" not in r, r
assert scoped == ["enter", "exit"]
- assert r["result"]["account_lines"]
+ assert "Account limits" in out and "openrouter" in out, out
+ assert "send a message first" not in out
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 1444dc67a62..8643ff6b6d6 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1455,11 +1455,6 @@ def _(rid, params: dict, session: dict) -> dict:
from agent.account_usage import nous_credits_lines
if credits := nous_credits_lines():
usage["credits_lines"] = credits
- # Provider account limits (e.g. Codex quota windows) β€” the same block the CLI and gateway /usage
- # render, so the Desktop usage feed is not the one surface that omits them. Fail-open.
- with contextlib.suppress(Exception):
- if account := _account_usage_lines(session):
- usage["account_lines"] = account
return _ok(rid, usage)
diff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.py
index 5b0bb0ad9fd..ef507c92a1c 100644
--- a/tui_gateway/methods_slash.py
+++ b/tui_gateway/methods_slash.py
@@ -131,11 +131,28 @@ def _format_live_refine_output(sid: str, session: Optional[dict], arg: str) -> s
)
+def _usage_account_blocks(session: dict) -> list[str]:
+ """Provider limits then Nous credits, as CLI/messaging /usage show them; both need no agent."""
+ lines: list[str] = []
+ with contextlib.suppress(Exception):
+ lines += _account_usage_lines(session)
+ with contextlib.suppress(Exception):
+ from agent.account_usage import nous_credits_lines
+ lines += nous_credits_lines()
+ return lines
+
+
def _format_live_usage_output(sid: str, session: dict, arg: str) -> str:
+ extra = _usage_account_blocks(session)
+ tokens = _format_live_usage_tokens(session)
+ return "\n\n".join(filter(None, [tokens, "\n".join(extra)])) or _NO_AGENT_USAGE
+
+
+def _format_live_usage_tokens(session: dict) -> str:
agent = session.get("agent")
usage = _session_usage_snapshot(session)
if agent is None and not usage:
- return _NO_AGENT_USAGE
+ return ""
if session.get("_metadata_message_count") is not None:
message_count = int(session.get("_metadata_message_count") or 0)
else: