Skip to content

The agent that grows with you

fix(tui-gateway): session.usage RPC ships provider account limits (account_lines)

teknium1604d8803a1f2
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 d65d8dd3279..4af0adada1b 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
@@ -546,6 +546,29 @@ describe('renderRpcResult', () => {
'Resets: 2026-08-01'
])
})
+
+ it('appends account_lines before 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')).toEqual([
+ 'Usage: 1 calls Β· 10 in / 20 out Β· 30 total',
+ 'πŸ“ˆ Account limits',
+ 'Provider: openai-codex (Plus)',
+ 'Weekly: 12% used',
+ 'Nous credits: 8,420 remaining',
+ 'Resets: 2026-08-01'
+ ])
+ })
})
describe('agents.list', () => {
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 57ca8e42931..59485978afa 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
@@ -523,7 +523,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, credits_lines? }
+ * - `session.usage`: { calls, input, output, total, account_lines?, credits_lines? }
* - `session.steer`: { status: 'queued' | 'rejected', text }
* - `process.stop`: { killed: boolean }
* - `agents.list`: { processes: [{ session_id, command, status, uptime }] }
@@ -582,7 +582,7 @@ export function renderRpcResult(response: unknown, name: string): string {
return r.output
}
- // session.usage β€” { calls, input, output, total, credits_lines? }
+ // session.usage β€” { calls, input, output, total, account_lines?, 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)
@@ -593,10 +593,13 @@ export function renderRpcResult(response: unknown, name: string): string {
`Usage: ${calls.toLocaleString()} calls Β· ${input.toLocaleString()} in / ${output.toLocaleString()} out Β· ${total.toLocaleString()} total`
]
- if (Array.isArray(r.credits_lines)) {
- for (const credit of r.credits_lines) {
- if (typeof credit === 'string' && credit.trim()) {
- lines.push(credit.trim())
+ // 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())
+ }
}
}
}
diff --git a/tests/tui_gateway/test_session_usage_account_lines.py b/tests/tui_gateway/test_session_usage_account_lines.py
new file mode 100644
index 00000000000..e651dfafeae
--- /dev/null
+++ b/tests/tui_gateway/test_session_usage_account_lines.py
@@ -0,0 +1,51 @@
+"""``session.usage`` RPC (Desktop usage feed) carries the provider account-limits block.
+
+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.
+"""
+from datetime import datetime, timezone
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow
+
+
+def _codex_snapshot() -> AccountUsageSnapshot:
+ return AccountUsageSnapshot(
+ provider="openai-codex", source="usage_api", fetched_at=datetime.now(timezone.utc), plan="Plus",
+ windows=(AccountUsageWindow(label="Weekly", used_percent=12.0),),
+ )
+
+
+def test_session_usage_rpc_ships_account_lines_for_the_live_route():
+ 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 "Provider: openai-codex (Plus)" in result["account_lines"]
+ assert any(line.startswith("Weekly") and "12%" in line for line in result["account_lines"])
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 45c054dd9f5..5932ceb160d 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1207,9 +1207,27 @@ 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)
+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)."""
+ 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))
+ return render_account_usage_lines(snapshot)
+
+
@_session_method("session.context_breakdown")
def _(rid, params: dict, session: dict) -> dict:
if (agent := session.get("agent")) is None: