Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(agent-accounts): show how much of each subscription is left

rubenluetke10-beepb75e15fb1f7e
diff --git a/jarvis/agent_usage.py b/jarvis/agent_usage.py
new file mode 100644
index 0000000000..ed7cf1222f
--- /dev/null
+++ b/jarvis/agent_usage.py
@@ -0,0 +1,879 @@
+"""How much of each connected subscription is already spent.
+
+A user who holds several seats of the same coding CLI
+(:mod:`jarvis.agent_accounts`) can switch which one the next terminal opens
+against — but until now the one number that decides WHICH seat to pick was
+invisible here. The plan limits (Claude's rolling 5-hour window and its 7-day
+window, Codex's weekly window) were only ever readable by starting the CLI and
+typing its own status command, once per seat, in a pane that then had to be
+thrown away. This module answers the same question for every registered seat at
+once, without opening anything.
+
+**Per account, never "this machine".** The reader is handed ONE account
+directory and reports on exactly that login, the same narrow question
+:func:`jarvis.agent_accounts.describe` asks. A cross-directory search would be
+actively misleading here: it would paint one seat's remaining budget onto a
+neighbouring row, and the whole point of the feature is deciding between rows.
+
+**Live first, cached second, and it always says which.** Both CLIs cache their
+last known limits on disk, and that cache is genuinely useful — it survives an
+expired token and needs no network. It is also, for an idle seat, arbitrarily
+old: a weekly window that reads 40% may have been written four days ago. So a
+reading carries its ``source`` and its ``as_of``, and the UI states them.
+Presenting a stale number as a live one is the single worst outcome here,
+because it is the number the user is about to make a decision on.
+
+**Nothing is ever spawned and no token ever leaves.** Usage is one small HTTPS
+GET against the provider the account is already signed in to, plus a few file
+reads. The bearer is read from the account's own credential file, used for that
+one request, and never returned, never logged, never written anywhere.
+
+Cross-platform by construction: ``pathlib`` throughout, no OS branch, and every
+failure path — no network, no login, an unknown CLI, a provider that changed its
+payload — degrades to an honest "not available" with a reason rather than to a
+confident wrong percentage.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import threading
+import time
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+from jarvis.agent_accounts import AgentAccount
+
+#: How long a reading is reused before the provider is asked again. The panel
+#: polls, several seats are read at once, and a plan percentage simply does not
+#: move fast enough to justify a request per render. Deliberately short enough
+#: that a user watching a running agent still sees the number climb.
+USAGE_TTL_S: float = 60.0
+
+#: One provider request must never hold the panel. Six seconds is far past a
+#: healthy response and far short of the point where the user assumes a hang;
+#: a timeout degrades to the on-disk snapshot, which is the whole reason it
+#: exists.
+HTTP_TIMEOUT_S: float = 6.0
+
+#: Newest session transcripts scanned when Codex has no live answer. A busy
+#: CODEX_HOME holds thousands; the limits in all but the newest few are strictly
+#: older, so scanning further is pure I/O for a worse number.
+MAX_ROLLOUT_FILES: int = 12
+
+#: Bytes read from the END of a transcript. The rate-limit record is written on
+#: every turn, so the last one is always near the tail — reading a 200 MB
+#: transcript to find a line 300 bytes from its end is how a "cheap" status read
+#: becomes a disk stall.
+ROLLOUT_TAIL_BYTES: int = 512 * 1024
+
+#: Where a percentage stops being routine. Shared by every provider so two rows
+#: at the same percentage can never be coloured differently — Claude states its
+#: own severity, Codex states none, and inventing a second scale for the second
+#: provider is how that inconsistency would arrive.
+WARNING_PERCENT: float = 80.0
+CRITICAL_PERCENT: float = 95.0
+
+#: Windows shorter than this count as the rolling "session" limit rather than a
+#: weekly one. Claude's is 5 hours, Codex's short window is 5 hours; anything up
+#: to a day is unambiguously the short one.
+SESSION_WINDOW_MAX_MINUTES: int = 24 * 60
+
+#: A 7-day window, in minutes. Codex reports windows numerically, so this is
+#: what "weekly" is compared against, with a day of slack either side.
+WEEKLY_WINDOW_MINUTES: int = 7 * 24 * 60
+
+#: A 30-day window, in minutes. Measured, not assumed: a ChatGPT seat on this
+#: machine reports a 43200-minute window, and without a name for it the panel
+#: would have labelled a real monthly budget "other".
+MONTHLY_WINDOW_MINUTES: int = 30 * 24 * 60
+
+
+class _Cache:
+ """TTL cache of readings, keyed by account id and its directory.
+
+ The directory is part of the key on purpose: an account that is deleted and
+ re-added under the same label gets a new directory, and serving the previous
+ one's percentages for a minute would be a wrong answer that looks right.
+ """
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._entries: dict[tuple[str, str], tuple[float, AccountUsage]] = {}
+
+ def get(self, account: AgentAccount, ttl: float) -> AccountUsage | None:
+ key = (account.id, os.path.normcase(str(account.config_dir)))
+ with self._lock:
+ hit = self._entries.get(key)
+ if hit is None:
+ return None
+ stored_at, usage = hit
+ return usage if (time.time() - stored_at) < ttl else None
+
+ def put(self, account: AgentAccount, usage: AccountUsage) -> None:
+ key = (account.id, os.path.normcase(str(account.config_dir)))
+ with self._lock:
+ self._entries[key] = (time.time(), usage)
+
+ def clear(self) -> None:
+ with self._lock:
+ self._entries.clear()
+
+
+@dataclass(frozen=True, slots=True)
+class UsageWindow:
+ """One plan limit, normalised across providers.
+
+ ``kind`` is the vocabulary the UI translates against and is deliberately
+ small and closed: ``session`` (the rolling short window), ``weekly``,
+ ``weekly_scoped`` (a weekly budget restricted to one model or surface), and
+ ``other`` for anything a provider adds that this build has no name for. An
+ unrecognised limit is still SHOWN — with its provider label — because a
+ limit the user is being throttled by must never be the one the panel hides.
+ """
+
+ kind: str
+ percent: float
+ severity: str # "normal" | "warning" | "critical"
+ #: ISO-8601 UTC. Providers disagree (Claude sends a timestamp, Codex an
+ #: epoch), so both are converted here rather than in the browser.
+ resets_at: str | None = None
+ #: Length of the window, when the provider states it. Lets the UI write
+ #: "5 h" without inferring it from the kind.
+ window_minutes: int | None = None
+ #: What the budget is restricted to, e.g. a model name. Only ever set for
+ #: ``weekly_scoped``; the UI appends it to the translated label.
+ scope_label: str | None = None
+ #: The provider's own wording, kept for ``other`` kinds where this build has
+ #: no translation to offer.
+ raw_label: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "kind": self.kind,
+ "percent": self.percent,
+ "severity": self.severity,
+ "resets_at": self.resets_at,
+ "window_minutes": self.window_minutes,
+ "scope_label": self.scope_label,
+ "raw_label": self.raw_label,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class AccountUsage:
+ """Everything the panel needs to draw one account's remaining budget.
+
+ ``status`` separates the four outcomes that must not look alike:
+ ``ok`` (windows carry real numbers), ``signed_out`` (nothing to measure —
+ the row already says so), ``unsupported`` (this CLI publishes no usage this
+ build can read) and ``unavailable`` (it should have worked and did not,
+ with ``message`` naming why).
+ """
+
+ account_id: str
+ platform: str
+ status: str
+ windows: tuple[UsageWindow, ...] = ()
+ #: "live" | "cached" — which of the two paths produced these numbers.
+ source: str = "live"
+ #: Epoch seconds the numbers were true at. For a cached reading this is the
+ #: provider's own timestamp, which is the entire reason it is reported.
+ as_of: float | None = None
+ message: str = ""
+ #: Display-only plan name, e.g. "Max 20x". Never used for a decision.
+ plan: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "account_id": self.account_id,
+ "platform": self.platform,
+ "status": self.status,
+ "windows": [w.to_dict() for w in self.windows],
+ "source": self.source,
+ "as_of": self.as_of,
+ "message": self.message,
+ "plan": self.plan,
+ }
+
+
+_CACHE = _Cache()
+
+
+# ------------------------------------------------------------------ helpers
+
+
+def clear_cache() -> None:
+ """Drop every cached reading and any unreachable-host cooldown."""
+ _CACHE.clear()
+ _UNREACHABLE_UNTIL.clear()
+
+
+def _severity(percent: float) -> str:
+ """One scale for every provider — see :data:`WARNING_PERCENT`."""
+ if percent >= CRITICAL_PERCENT:
+ return "critical"
+ if percent >= WARNING_PERCENT:
+ return "warning"
+ return "normal"
+
+
+def _clamp_percent(value: Any) -> float | None:
+ """A usable 0-100 percentage, or ``None`` for anything that is not one.
+
+ Clamped rather than rejected at the top end: a provider that reports 103%
+ for an over-consumed window means "full", and refusing to draw that bar
+ would hide the one state the user most needs to see.
+ """
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ number = float(value)
+ if number != number or number in (float("inf"), float("-inf")): # NaN / inf
+ return None
+ return max(0.0, min(100.0, number))
+
+
+def _iso_from_epoch(value: Any) -> str | None:
+ """Codex's epoch-seconds reset time as ISO-8601 UTC."""
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ return None
+ if value <= 0:
+ return None
+ try:
+ return datetime.fromtimestamp(float(value), tz=UTC).isoformat()
+ except (OSError, OverflowError, ValueError) as exc:
+ # A nonsense timestamp costs the countdown, never the percentage.
+ logger.debug("Agent usage: unusable reset epoch {!r} ({})", value, exc)
+ return None
+
+
+def _iso_or_none(value: Any) -> str | None:
+ """Claude's already-ISO reset time, validated rather than trusted."""
+ if not isinstance(value, str) or not value.strip():
+ return None
+ text = value.strip()
+ try:
+ datetime.fromisoformat(text.replace("Z", "+00:00"))
+ except ValueError as exc:
+ logger.debug("Agent usage: unusable reset timestamp {!r} ({})", text, exc)
+ return None
+ return text
+
+
+def _kind_for_window(window_minutes: int | None) -> str:
+ """Name a provider's numeric window in the shared vocabulary."""
+ if window_minutes is None or window_minutes <= 0:
+ return "other"
+ if window_minutes <= SESSION_WINDOW_MAX_MINUTES:
+ return "session"
+ if abs(window_minutes - WEEKLY_WINDOW_MINUTES) <= 24 * 60:
+ return "weekly"
+ if abs(window_minutes - MONTHLY_WINDOW_MINUTES) <= 3 * 24 * 60:
+ return "monthly"
+ return "other"
+
+
+#: How long a host that could not be REACHED at all is left alone.
+#:
+#: Only unreachability triggers it, never an HTTP error. The distinction is the
+#: whole value: an offline machine pays the full timeout on every poll — six
+#: seconds a minute, per seat, forever — while a 403 answers instantly and
+#: costs nothing worth avoiding. Cooling down on status codes as well would
+#: keep a seat on cached numbers for minutes after a one-off server hiccup, and
+#: freshness is what this feature is for.
+_UNREACHABLE_COOLDOWN_S: float = 180.0
+
+#: ``{url: epoch until which it is not worth trying}``. Process-local and
+#: deliberately unsynchronised: a duplicate probe during a race costs one
+#: request, and a lock here would serialise every seat's read.
+_UNREACHABLE_UNTIL: dict[str, float] = {}
+
+
+def _http_get_json(url: str, headers: dict[str, str]) -> Any | None:
+ """One short GET, or ``None`` for every failure. Never raises, never logs a token.
+
+ The import is local because this module is reached from status paths that
+ must stay cheap on a host with no network at all; ``httpx`` is a real
+ dependency, but paying its import to read a cached percentage is waste.
+ """
+ blocked_until = _UNREACHABLE_UNTIL.get(url)
+ if blocked_until is not None and time.time() < blocked_until:
+ return None
+ try:
+ import httpx
+ except ImportError as exc: # pragma: no cover - httpx is a hard dependency
+ logger.debug("Agent usage: httpx is unavailable ({})", exc)
+ return None
+ try:
+ response = httpx.get(url, headers=headers, timeout=HTTP_TIMEOUT_S)
+ except Exception as exc: # noqa: BLE001 - every transport failure is "no live answer"
+ _UNREACHABLE_UNTIL[url] = time.time() + _UNREACHABLE_COOLDOWN_S
+ logger.debug("Agent usage: {} could not be reached ({})", url, type(exc).__name__)
+ return None
+ _UNREACHABLE_UNTIL.pop(url, None)
+ if response.status_code != 200:
+ logger.debug("Agent usage: {} answered {}", url, response.status_code)
+ return None
+ try:
+ return response.json()
+ except ValueError as exc:
+ logger.debug("Agent usage: {} did not answer with JSON ({})", url, exc)
+ return None
+
+
+def _read_json_file(path: Path) -> Any | None:
+ """A JSON file as plain Python values, or ``None`` when it is not usable."""
+ try:
+ raw = path.read_text(encoding="utf-8-sig")
+ except OSError:
+ # Absent is the normal state for a seat that has never been used.
+ return None
+ try:
+ return json.loads(raw)
+ except ValueError as exc:
+ logger.debug("Agent usage: {} is not valid JSON ({})", path.name, exc)
+ return None
+
+
+# ------------------------------------------------------------------- claude
+
+
+#: The endpoint Claude Code itself reads its usage from. An OAuth bearer is the
+#: only credential it accepts, which is exactly what a signed-in seat holds.
+_CLAUDE_USAGE_URL = "https://api.anthropic.com/api/oauth/usage"
+
+#: Required by the OAuth surface; without it the bearer is rejected as if it
+#: were an API key.
+_CLAUDE_OAUTH_BETA = "oauth-2025-04-20"
+
+#: Rate-limit tiers as the account file spells them, mapped to what the plan is
+#: called on the invoice. Unknown tiers fall through to a tidied version of the
+#: raw string rather than to nothing — a new plan name must still show up.
+_CLAUDE_PLAN_NAMES: dict[str, str] = {
+ "default_claude_max_20x": "Max 20x",
+ "default_claude_max_5x": "Max 5x",
+ "default_claude_pro": "Pro",
+ "default_claude_team": "Team",
+ "default_claude_enterprise": "Enterprise",
+}
+
+#: How long each Claude window is. The endpoint states the reset time but not
+#: the length, and the UI needs the length to write "5 h" beside the bar.
+_CLAUDE_WINDOW_MINUTES: dict[str, int] = {
+ "session": 5 * 60,
+ "weekly": WEEKLY_WINDOW_MINUTES,
+ "weekly_scoped": WEEKLY_WINDOW_MINUTES,
+}
+
+#: The named per-window fields, in display order, used only when the payload
+#: carries no ``limits`` array. Older builds of the endpoint answered with these
+#: alone, and a seat on one must still show its two headline numbers.
+_CLAUDE_LEGACY_WINDOWS: tuple[tuple[str, str, int | None], ...] = (
+ ("five_hour", "session", 5 * 60),
+ ("seven_day", "weekly", WEEKLY_WINDOW_MINUTES),
+)
+
+
+def _claude_plan_name(claude_json: Any) -> str | None:
+ account = claude_json.get("oauthAccount") if isinstance(claude_json, dict) else None
+ tier = account.get("organizationRateLimitTier") if isinstance(account, dict) else None
+ if not isinstance(tier, str) or not tier.strip():
+ return None
+ known = _CLAUDE_PLAN_NAMES.get(tier.strip())
+ if known:
+ return known
+ # An unmapped tier is still worth showing; strip the prefix every tier
+ # carries so a new one reads as "Max 50x" rather than as a database key.
+ cleaned = tier.strip().removeprefix("default_claude_").replace("_", " ").strip()
+ return cleaned.title() if cleaned else None
+
+
+def _claude_scope_label(scope: Any) -> str | None:
+ """What a scoped weekly budget is restricted to, e.g. the model name."""
+ if not isinstance(scope, dict):
+ return None
+ model = scope.get("model")
+ if isinstance(model, dict):
+ name = model.get("display_name") or model.get("id")
+ if isinstance(name, str) and name.strip():
+ return name.strip()
+ surface = scope.get("surface")
+ if isinstance(surface, str) and surface.strip():
+ return surface.strip()
+ return None
+
+
+def _claude_windows(utilization: Any) -> tuple[UsageWindow, ...]:
+ """Normalise one Anthropic usage payload into windows.
+
+ Reads the ``limits`` array when it is there and the named fields when it is
+ not. The array is preferred because it is self-describing: it carries the
+ per-model weekly budgets that have no named field at all, so a seat
+ throttled on one model while its overall week sits at 40% shows BOTH, which
+ is the difference between "you have plenty left" and the truth.
+ """
+ if not isinstance(utilization, dict):
+ return ()
+
+ entries = utilization.get("limits")
+ windows: list[UsageWindow] = []
+ if isinstance(entries, list):
+ for entry in entries:
+ if not isinstance(entry, dict):
+ continue
+ percent = _clamp_percent(entry.get("percent"))
+ if percent is None:
+ continue
+ group = entry.get("group")
+ kind_raw = entry.get("kind")
+ scope_label = _claude_scope_label(entry.get("scope"))
+ if kind_raw == "session" or group == "session":
+ kind = "session"
+ elif scope_label:
+ kind = "weekly_scoped"
+ elif group == "weekly":
+ kind = "weekly"
+ else:
+ kind = "other"
+ severity = entry.get("severity")
+ windows.append(
+ UsageWindow(
+ kind=kind,
+ percent=percent,
+ # The provider's own severity wins where it is stated: it
+ # knows about grace periods and soft caps that a bare
+ # percentage does not express.
+ severity=(
+ severity
+ if severity in ("normal", "warning", "critical")
+ else _severity(percent)
+ ),
+ resets_at=_iso_or_none(entry.get("resets_at")),
+ window_minutes=_CLAUDE_WINDOW_MINUTES.get(kind),
+ scope_label=scope_label,
+ raw_label=kind_raw if isinstance(kind_raw, str) else None,
+ )
+ )
+ if windows:
+ return tuple(windows)
+
+ for field, kind, window_minutes in _CLAUDE_LEGACY_WINDOWS:
+ block = utilization.get(field)
+ if not isinstance(block, dict):
+ continue
+ percent = _clamp_percent(block.get("utilization"))
+ if percent is None:
+ continue
+ windows.append(
+ UsageWindow(
+ kind=kind,
+ percent=percent,
+ severity=_severity(percent),
+ resets_at=_iso_or_none(block.get("resets_at")),
+ window_minutes=window_minutes,
+ )
+ )
+ return tuple(windows)
+
+
+def _claude_usage(account: AgentAccount) -> AccountUsage:
+ """Usage for ONE Claude seat: the live endpoint, else its own disk cache."""
+ from jarvis.claude_credentials import claude_login_in
+
+ claude_json = _read_json_file(account.config_dir / ".claude.json")
+ plan = _claude_plan_name(claude_json)
+ login = claude_login_in(account.config_dir)
+
+ if login.status == "valid" and login.access_token:
+ payload = _http_get_json(
+ _CLAUDE_USAGE_URL,
+ {
+ "Authorization": f"Bearer {login.access_token}",
+ "anthropic-beta": _CLAUDE_OAUTH_BETA,
+ "Accept": "application/json",
+ },
+ )
+ windows = _claude_windows(payload)
+ if windows:
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="ok",
+ windows=windows,
+ source="live",
+ as_of=time.time(),
+ plan=plan,
+ )
+
+ # Claude Code writes its last reading here, so an expired bearer, a
+ # firewalled host or a changed endpoint still produces the numbers the CLI
+ # itself last saw — labelled with the provider's own timestamp so nobody
+ # mistakes a four-day-old weekly figure for a live one.
+ cached = claude_json.get("cachedUsageUtilization") if isinstance(claude_json, dict) else None
+ if isinstance(cached, dict):
+ windows = _claude_windows(cached.get("utilization"))
+ fetched_ms = cached.get("fetchedAtMs")
+ if windows:
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="ok",
+ windows=windows,
+ source="cached",
+ as_of=(
+ float(fetched_ms) / 1000.0
+ if isinstance(fetched_ms, (int, float)) and not isinstance(fetched_ms, bool)
+ else None
+ ),
+ plan=plan,
+ )
+
+ if login.status == "absent":
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="signed_out",
+ message="Sign in to this seat to see how much of its plan is left.",
+ plan=plan,
+ )
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="unavailable",
+ message=(
+ "Usage could not be read for this seat. It appears again by itself "
+ "once a terminal has run on this account, or when the connection is back."
+ ),
+ plan=plan,
+ )
+
+
+# -------------------------------------------------------------------- codex
+
+
+#: Where a ChatGPT-backed Codex seat publishes its remaining budget. Tried
+#: first and allowed to fail: the transcript fallback below is the path this
+#: build has actually measured, so a 404 here costs freshness, never the
+#: feature.
+_CODEX_USAGE_URLS: tuple[str, ...] = ("https://chatgpt.com/backend-api/codex/usage",)
+
+
+def _codex_rate_limit_windows(rate_limits: Any) -> tuple[UsageWindow, ...]:
+ """Normalise Codex's ``primary``/``secondary`` pair into windows.
+
+ Which of the two is the short window and which is the weekly one is NOT
+ fixed — it depends on the plan, and hardcoding "primary is weekly" was
+ tempting because it is true for the account this was written against. The
+ window length decides instead, so a plan whose windows are the other way
+ round labels them correctly.
+ """
+ if not isinstance(rate_limits, dict):
+ return ()
+ windows: list[UsageWindow] = []
+ for slot in ("primary", "secondary"):
+ block = rate_limits.get(slot)
+ if not isinstance(block, dict):
+ continue
+ percent = _clamp_percent(block.get("used_percent"))
+ if percent is None:
+ continue
+ raw_minutes = block.get("window_minutes")
+ window_minutes = (
+ int(raw_minutes)
+ if isinstance(raw_minutes, (int, float)) and not isinstance(raw_minutes, bool)
+ else None
+ )
+ resets = _iso_from_epoch(block.get("resets_at"))
+ if resets is None:
+ # Older Codex builds state a countdown instead of a timestamp.
+ seconds = block.get("resets_in_seconds")
+ if isinstance(seconds, (int, float)) and not isinstance(seconds, bool):
+ resets = _iso_from_epoch(time.time() + float(seconds))
+ windows.append(
+ UsageWindow(
+ kind=_kind_for_window(window_minutes),
+ percent=percent,
+ severity=_severity(percent),
+ resets_at=resets,
+ window_minutes=window_minutes,
+ )
+ )
+ windows.sort(key=lambda w: w.window_minutes or 0)
+ return tuple(windows)
+
+
+def _codex_rollout_files(codex_home: Path) -> list[Path]:
+ """The newest session transcripts, newest first, bounded by count.
+
+ ``os.scandir`` rather than ``rglob`` because a long-lived CODEX_HOME holds
+ one file per session in a date tree, and stat-ing every one of thousands to
+ sort them is the expensive part of this whole module.
+ """
+ sessions = codex_home / "sessions"
+ found: list[tuple[float, Path]] = []
+ stack: list[Path] = [sessions]
+ while stack:
+ directory = stack.pop()
+ try:
+ with os.scandir(directory) as entries:
+ for entry in entries:
+ try:
+ if entry.is_dir():
+ stack.append(Path(entry.path))
+ elif entry.name.startswith("rollout-") and entry.name.endswith(".jsonl"):
+ found.append((entry.stat().st_mtime, Path(entry.path)))
+ except OSError: # noqa: PERF203 - one unreadable entry is simply skipped
+ continue
+ except OSError:
+ # An absent sessions tree means this seat has never run. Not a fault.
+ continue
+ found.sort(key=lambda pair: pair[0], reverse=True)
+ return [path for _mtime, path in found[:MAX_ROLLOUT_FILES]]
+
+
+def _codex_last_rate_limits(path: Path) -> tuple[dict[str, Any], float] | None:
+ """The final rate-limit record in one transcript, plus its timestamp."""
+ try:
+ size = path.stat().st_size
+ with path.open("rb") as handle:
+ if size > ROLLOUT_TAIL_BYTES:
+ handle.seek(size - ROLLOUT_TAIL_BYTES)
+ handle.readline() # Drop the partial line the seek landed in.
+ tail = handle.read().decode("utf-8", "replace")
+ except OSError as exc:
+ logger.debug("Agent usage: {} could not be read ({})", path.name, exc)
+ return None
+ for line in reversed(tail.splitlines()):
+ if '"rate_limits"' not in line:
+ continue
+ try:
+ record = json.loads(line)
+ except ValueError: # noqa: PERF203 - a truncated line is simply not the answer
+ continue
+ payload = record.get("payload") if isinstance(record, dict) else None
+ limits = payload.get("rate_limits") if isinstance(payload, dict) else None
+ if not isinstance(limits, dict):
+ continue
+ stamp = record.get("timestamp") if isinstance(record, dict) else None
+ as_of = path.stat().st_mtime
+ if isinstance(stamp, str):
+ try:
+ as_of = datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ # Keep the file's mtime — it is a worse answer, not a wrong one.
+ pass
+ return limits, as_of
+ return None
+
+
+def _codex_plan_name(rate_limits: Any) -> str | None:
+ if not isinstance(rate_limits, dict):
+ return None
+ for field in ("plan_type", "limit_name"):
+ value = rate_limits.get(field)
+ if isinstance(value, str) and value.strip():
+ return value.strip().replace("_", " ").title()
+ return None
+
+
+def _codex_usage(account: AgentAccount) -> AccountUsage:
+ """Usage for ONE Codex seat: the live endpoint, else its own transcripts."""
+ from jarvis.codex_auth import codex_login_in
+
+ connected, mode, _email = codex_login_in(account.config_dir)
+ if not connected:
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="signed_out",
+ message="Sign in to this seat to see how much of its plan is left.",
+ )
+ if mode == "api_key":
+ # An API key is billed per call and has no plan window to spend down.
+ # Drawing an empty 0% bar next to it would invent a limit that does not
+ # exist; saying so is the honest answer.
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="unsupported",
+ message="This seat bills per request through an API key — it has no plan limit.",
+ )
+
+ auth = _read_json_file(account.config_dir / "auth.json")
+ tokens = auth.get("tokens") if isinstance(auth, dict) else None
+ token = tokens.get("access_token") if isinstance(tokens, dict) else None
+ account_ref = None
+ if isinstance(tokens, dict):
+ account_ref = tokens.get("account_id")
+ if not account_ref and isinstance(auth, dict):
+ account_ref = auth.get("account_id")
+
+ if isinstance(token, str) and token:
+ for url in _CODEX_USAGE_URLS:
+ payload = _http_get_json(
+ url,
+ {
+ "Authorization": f"Bearer {token}",
+ "chatgpt-account-id": str(account_ref or ""),
+ "Accept": "application/json",
+ },
+ )
+ source = payload.get("rate_limits") if isinstance(payload, dict) else None
+ windows = _codex_rate_limit_windows(source if source is not None else payload)
+ if windows:
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="ok",
+ windows=windows,
+ source="live",
+ as_of=time.time(),
+ plan=_codex_plan_name(source if source is not None else payload),
+ )
+
+ # Codex writes the limits the server returned into its session transcript on
+ # every turn, so the newest transcript holds the freshest reading this
+ # machine has ever seen — which for a seat used today is minutes old.
+ for path in _codex_rollout_files(account.config_dir):
+ found = _codex_last_rate_limits(path)
+ if found is None:
+ continue
+ rate_limits, as_of = found
+ windows = _codex_rate_limit_windows(rate_limits)
+ if windows:
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="ok",
+ windows=windows,
+ source="cached",
+ as_of=as_of,
+ plan=_codex_plan_name(rate_limits),
+ )
+
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="unavailable",
+ message=(
+ "No usage recorded for this seat yet — it appears once a terminal "
+ "has run on this account."
+ ),
+ )
+
+
+# ------------------------------------------------------------------ generic
+
+
+def _generic_usage(account: AgentAccount) -> AccountUsage:
+ """The answer for a CLI this build has no usage reader for.
+
+ Falling through to another provider's reader is what an ``if claude / else
+ codex`` pair quietly does to every third CLI, and here it would be worse
+ than a wrong dot: it would draw a plausible progress bar from a file that
+ belongs to a different product. An honest "not available" is the only safe
+ answer, and switching seats is unaffected by it.
+ """
+ from jarvis.workspace.agents import get_agent
+
+ entry = get_agent(account.platform)
+ name = entry.display_name if entry is not None else account.platform
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="unsupported",
+ message=f"{name} does not publish plan usage that Jarvis can read.",
+ )
+
+
+#: Which reader answers for which CLI. A mapping rather than a chain of ``if``s
+#: so that adding a provider is one entry, and so that the absence of an entry
+#: is a visible fact rather than an accidental fallthrough into a neighbour.
+_READERS: dict[str, Any] = {
+ "claude": _claude_usage,
+ "codex": _codex_usage,
+}
+
+
+def supports_usage(platform: str) -> bool:
+ """Whether this build can read plan usage for *platform* at all."""
+ return platform in _READERS
+
+
+def read_usage(account: AgentAccount) -> AccountUsage:
+ """Usage for one account, reading the provider directly. Never raises.
+
+ Uncached: callers that render a list want :func:`collect`, which adds the
+ TTL and reads several seats at once.
+ """
+ reader = _READERS.get(account.platform, _generic_usage)
+ try:
+ return reader(account)
+ except Exception as exc: # noqa: BLE001 - a status read must never break the panel
+ logger.warning(
+ "Agent usage: {} could not be read for {!r}: {}: {}",
+ account.platform,
+ account.label,
+ type(exc).__name__,
+ exc,
+ )
+ return AccountUsage(
+ account_id=account.id,
+ platform=account.platform,
+ status="unavailable",
+ message="Usage could not be read for this seat.",
+ )
+
+
+def collect(
+ accounts: list[AgentAccount],
+ *,
+ refresh: bool = False,
+ ttl: float = USAGE_TTL_S,
+) -> dict[str, AccountUsage]:
+ """Usage for many accounts at once, keyed by account id.
+
+ Read in PARALLEL, which is the difference between a panel that updates and
+ one that stalls: each seat costs one network round trip, and four seats read
+ one after another is four timeouts stacked end to end on a host with no
+ connection. Cached seats never reach the pool at all.
+ """
+ results: dict[str, AccountUsage] = {}
+ pending: list[AgentAccount] = []
+ for account in accounts:
+ hit = None if refresh else _CACHE.get(account, ttl)
+ if hit is None:
+ pending.append(account)
+ else:
+ results[account.id] = hit
+
+ if pending:
+ with ThreadPoolExecutor(
+ max_workers=min(8, len(pending)), thread_name_prefix="agent-usage"
+ ) as pool:
+ fresh = list(pool.map(read_usage, pending))
+ for account, usage in zip(pending, fresh, strict=True):
+ _CACHE.put(account, usage)
+ results[account.id] = usage
+ return results
+
+
+__all__ = [
+ "CRITICAL_PERCENT",
+ "HTTP_TIMEOUT_S",
+ "MAX_ROLLOUT_FILES",
+ "USAGE_TTL_S",
+ "WARNING_PERCENT",
+ "AccountUsage",
+ "UsageWindow",
+ "clear_cache",
+ "collect",
+ "read_usage",
+ "supports_usage",
+]
diff --git a/jarvis/ui/web/agent_accounts_routes.py b/jarvis/ui/web/agent_accounts_routes.py
index 815583ff65..b4f86e98e6 100644
--- a/jarvis/ui/web/agent_accounts_routes.py
+++ b/jarvis/ui/web/agent_accounts_routes.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import asyncio
import logging
+import time
from typing import Any
from fastapi import APIRouter, HTTPException
@@ -109,6 +110,39 @@ async def list_accounts() -> dict[str, Any]:
return await asyncio.to_thread(_collect)
+def _usage(refresh: bool) -> dict[str, Any]:
+ """Plan usage for every registered account, keyed by account id."""
+ from jarvis import agent_usage
+
+ accounts = agent_accounts.all_accounts()
+ readings = agent_usage.collect(accounts, refresh=refresh)
+ return {
+ "accounts": [readings[a.id].to_dict() for a in accounts if a.id in readings],
+ # Told to the UI rather than agreed by convention, so the poll interval
+ # follows the server's cache instead of a second number that has to be
+ # kept in step with it by hand.
+ "ttl_seconds": agent_usage.USAGE_TTL_S,
+ "generated_at": time.time(),
+ }
+
+
[email protected]("/usage", summary="Plan usage of every connected subscription")
+async def usage(refresh: bool = False) -> dict[str, Any]:
+ """How much of each seat's plan is already spent, and when it resets.
+
+ One reading per account: the rolling short window, the weekly one, and any
+ per-model budget the provider scopes separately. Each reading says whether
+ it came from the provider just now (``source: "live"``) or from what the CLI
+ last wrote to disk (``source: "cached"``, with ``as_of``) — a stale weekly
+ figure presented as a live one is the one failure this endpoint must not
+ have, because it is the number a user picks a subscription on.
+
+ ``refresh=true`` bypasses the short server-side cache. Off the event loop:
+ every account is a network round trip, and they run in parallel.
+ """
+ return await asyncio.to_thread(_usage, refresh)
+
+
@router.post("", summary="Add another subscription")
async def create_account(req: AccountCreateRequest) -> dict[str, Any]:
"""Register a subscription and mint its (still empty) config directory.
diff --git a/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsx b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsx
new file mode 100644
index 0000000000..7de2b4cd4a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsx
@@ -0,0 +1,156 @@
+/**
+ * The meters that say how much of a subscription's plan is gone.
+ *
+ * What these pin down is the difference between a useful meter and a harmful
+ * one. A percentage next to a seat is a number the user makes a decision on, so
+ * the failures worth a test are the ones where it is confidently wrong or
+ * quietly missing:
+ *
+ * * a reading that came off disk must never be presented as a live one;
+ * * a per-model weekly budget must be drawn NEXT TO the overall week, because
+ * 55% overall beside 99% on one model is exactly when "plenty left" is wrong;
+ * * a limit this build has no name for must still be drawn, not hidden;
+ * * a seat with no login must not repeat what the row above already says.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { cleanup, render, screen } from "@testing-library/react";
+
+import { AccountUsageMeters } from "./AccountUsageMeters";
+import type { AccountUsage, UsageWindow } from "@/lib/agentAccountsApi";
+
+afterEach(cleanup);
+
+const NOW = Date.UTC(2026, 7, 13, 11, 0, 0);
+
+function window_(overrides: Partial<UsageWindow>): UsageWindow {
+ return {
+ kind: "weekly",
+ percent: 40,
+ severity: "normal",
+ resets_at: null,
+ window_minutes: 10080,
+ scope_label: null,
+ raw_label: null,
+ ...overrides,
+ };
+}
+
+function usage(overrides: Partial<AccountUsage> = {}): AccountUsage {
+ return {
+ account_id: "claude:seat",
+ platform: "claude",
+ status: "ok",
+ windows: [window_({})],
+ source: "live",
+ as_of: NOW / 1000,
+ message: "",
+ plan: null,
+ ...overrides,
+ };
+}
+
+describe("AccountUsageMeters", () => {
+ it("draws every window, including a scoped one beside the overall week", () => {
+ render(
+ <AccountUsageMeters
+ now={NOW}
+ usage={usage({
+ plan: "Max 20x",
+ windows: [
+ window_({ kind: "session", percent: 2, window_minutes: 300 }),
+ window_({ kind: "weekly", percent: 55 }),
+ window_({
+ kind: "weekly_scoped",
+ percent: 99,
+ severity: "critical",
+ scope_label: "Fable",
+ }),
+ ],
+ })}
+ />,
+ );
+
+ const bars = screen.getAllByRole("progressbar");
+ expect(bars).toHaveLength(3);
+ expect(bars.map((bar) => bar.getAttribute("aria-valuenow"))).toEqual(["2", "55", "99"]);
+ // The scoped budget names WHAT it is scoped to — a second unlabelled
+ // "Weekly" bar at 99% would read as a contradiction of the first.
+ expect(screen.getByText(/Fable/)).toBeTruthy();
+ expect(screen.getByText("Max 20x")).toBeTruthy();
+ });
+
+ it("says a disk reading is not a live one", () => {
+ render(
+ <AccountUsageMeters
+ now={NOW}
+ // Four hours old — a perfectly ordinary age for an idle seat, and
+ // exactly the case where showing it as "live" would mislead.
+ usage={usage({ source: "cached", as_of: NOW / 1000 - 4 * 3600 })}
+ />,
+ );
+ expect(screen.queryByText("live")).toBeNull();
+ expect(screen.getByText(/4 h/)).toBeTruthy();
+ });
+
+ it("counts down to the reset and never counts up from a passed one", () => {
+ const { rerender } = render(
+ <AccountUsageMeters
+ now={NOW}
+ usage={usage({
+ windows: [window_({ resets_at: new Date(NOW + 2.5 * 3600 * 1000).toISOString() })],
+ })}
+ />,
+ );
+ expect(screen.getByText(/2 h 30 min/)).toBeTruthy();
+
+ // A reset in the past means the window already rolled over. "in -3 h" is
+ // nonsense, so the countdown disappears rather than turning negative.
+ rerender(
+ <AccountUsageMeters
+ now={NOW}
+ usage={usage({
+ windows: [window_({ resets_at: new Date(NOW - 3 * 3600 * 1000).toISOString() })],
+ })}
+ />,
+ );
+ expect(screen.queryByText(/-/)).toBeNull();
+ });
+
+ it("still draws a limit this build has no name for", () => {
+ render(
+ <AccountUsageMeters
+ now={NOW}
+ usage={usage({
+ windows: [
+ window_({ kind: "other", percent: 62, window_minutes: 4320, raw_label: "burst" }),
+ ],
+ })}
+ />,
+ );
+ // Hiding an unrecognised limit is the one failure that costs the user the
+ // information they came for — the limit throttling them right now.
+ expect(screen.getAllByRole("progressbar")).toHaveLength(1);
+ expect(screen.getByText(/3 d/)).toBeTruthy();
+ });
+
+ it("stays silent for a seat that is not signed in", () => {
+ const { container } = render(
+ <AccountUsageMeters now={NOW} usage={usage({ status: "signed_out", windows: [] })} />,
+ );
+ // The row above already says "Not signed in yet" in plain words.
+ expect(container.textContent).toBe("");
+ });
+
+ it("explains an unreadable seat instead of drawing an empty bar", () => {
+ render(
+ <AccountUsageMeters now={NOW} usage={usage({ status: "unavailable", windows: [] })} />,
+ );
+ expect(screen.queryAllByRole("progressbar")).toHaveLength(0);
+ expect(screen.getByText(/not readable/i)).toBeTruthy();
+ });
+
+ it("renders nothing at all while the reading is still in flight", () => {
+ const { container } = render(<AccountUsageMeters now={NOW} usage={undefined} />);
+ expect(container.textContent).toBe("");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsx b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsx
new file mode 100644
index 0000000000..2d5b832d62
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsx
@@ -0,0 +1,231 @@
+/**
+ * How much of one subscription's plan is already spent.
+ *
+ * The number that decides WHICH seat to open a terminal on used to be invisible
+ * here: it required starting the CLI and typing its own status command, once
+ * per seat, in a pane that was then thrown away. These meters put the same
+ * figures next to the row you switch with.
+ *
+ * Three deliberate choices, each one a thing that would otherwise mislead:
+ *
+ * 1. **A stale reading never looks live.** A percentage can come from the
+ * provider just now or from what the CLI last wrote to disk, and for an idle
+ * seat the second can be days old. The freshness is stated on every block
+ * rather than left to be assumed — this is the number a decision is made on.
+ * 2. **A scoped limit is shown beside the overall one.** A week that reads 55%
+ * while one model's own weekly budget sits at 99% is the case where "plenty
+ * left" is the wrong conclusion, so both bars are drawn.
+ * 3. **Severity comes from the backend, not from the bar's own arithmetic.**
+ * The provider knows about grace periods and soft caps that a bare
+ * percentage does not express, so the colour follows what it said.
+ *
+ * `now` is a prop rather than a timer per meter: one clock in the panel means
+ * every countdown on screen agrees, and a card with four seats does not run
+ * twelve intervals.
+ */
+
+import { Gauge } from "lucide-react";
+
+import { useT } from "@/i18n";
+import type { AccountUsage, UsageWindow } from "@/lib/agentAccountsApi";
+import { cn } from "@/lib/utils";
+
+/**
+ * Bar colour per severity.
+ *
+ * `bg-primary` and `bg-destructive` are theme tokens, so they follow light and
+ * dark mode on their own. The middle step is a fixed orange on purpose: the
+ * brand accent IS amber, so a token-based "warning" would be nearly the same
+ * hue as "normal" and the one transition that has to be noticed would be the
+ * one you cannot see.
+ */
+const BAR_CLASS: Record<string, string> = {
+ normal: "bg-primary",
+ warning: "bg-orange-500",
+ critical: "bg-destructive",
+};
+
+const PERCENT_CLASS: Record<string, string> = {
+ normal: "text-foreground",
+ warning: "text-orange-500",
+ critical: "text-destructive",
+};
+
+/** Minutes as a short human duration — "5 h", "45 min", "7 d". */
+function windowLabel(minutes: number): string {
+ if (minutes < 60) return `${minutes} min`;
+ if (minutes < 60 * 24) return `${Math.round(minutes / 60)} h`;
+ return `${Math.round(minutes / (60 * 24))} d`;
+}
+
+/**
+ * A span of milliseconds as a short countdown — "2 h 14 min", "18 min", "3 d".
+ *
+ * Deliberately two units at most. "1 d 4 h 12 min 9 s" is not more useful for
+ * deciding whether to keep working on this seat, and it wraps the line.
+ */
+function durationLabel(ms: number): string {
+ const totalMinutes = Math.max(0, Math.round(ms / 60000));
+ if (totalMinutes < 60) return `${totalMinutes} min`;
+ const hours = Math.floor(totalMinutes / 60);
+ const minutes = totalMinutes % 60;
+ if (hours < 24) return minutes ? `${hours} h ${minutes} min` : `${hours} h`;
+ const days = Math.floor(hours / 24);
+ const restHours = hours % 24;
+ return restHours ? `${days} d ${restHours} h` : `${days} d`;
+}
+
+/** What to call one window, in the user's language. */
+function useWindowLabel(): (window: UsageWindow) => string {
+ const t = useT();
+ return (window) => {
+ if (window.kind === "weekly_scoped") {
+ const base = t("agent_accounts.usage.kind.weekly");
+ return window.scope_label ? `${base} · ${window.scope_label}` : base;
+ }
+ if (window.kind === "session") {
+ // The short window is 5 hours on both CLIs today, so the translation says
+ // so. If a provider ever ships a different one, the measured length wins
+ // over the wording rather than the label quietly becoming a lie.
+ if (window.window_minutes && window.window_minutes !== 300) {
+ return `${windowLabel(window.window_minutes)} · ${t("agent_accounts.usage.kind.rolling")}`;
+ }
+ return t("agent_accounts.usage.kind.session");
+ }
+ if (window.kind === "weekly") return t("agent_accounts.usage.kind.weekly");
+ if (window.kind === "monthly") return t("agent_accounts.usage.kind.monthly");
+ if (window.window_minutes) {
+ return `${windowLabel(window.window_minutes)} · ${t("agent_accounts.usage.kind.rolling")}`;
+ }
+ return window.raw_label || t("agent_accounts.usage.kind.other");
+ };
+}
+
+function Meter({ window: usageWindow, now }: { window: UsageWindow; now: number }) {
+ const t = useT();
+ const label = useWindowLabel()(usageWindow);
+ const severity = usageWindow.severity in BAR_CLASS ? usageWindow.severity : "normal";
+ const percent = Math.max(0, Math.min(100, usageWindow.percent));
+ const resetsInMs = usageWindow.resets_at
+ ? new Date(usageWindow.resets_at).getTime() - now
+ : null;
+ // A reset that has already passed means the window rolled over and the
+ // reading predates it. Showing "in -3 h" would be nonsense; showing nothing
+ // lets the freshness line carry the story.
+ const countdown =
+ resetsInMs !== null && Number.isFinite(resetsInMs) && resetsInMs > 0
+ ? `${t("agent_accounts.usage.resets_in")} ${durationLabel(resetsInMs)}`
+ : null;
+
+ return (
+ <div className="space-y-1">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="min-w-0 truncate text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
+ {label}
+ {countdown && (
+ <span className="ml-1.5 normal-case tracking-normal opacity-80">
+ · {countdown}
+ </span>
+ )}
+ </span>
+ <span
+ className={cn(
+ "shrink-0 text-[11px] font-semibold tabular-nums",
+ PERCENT_CLASS[severity],
+ )}
+ >
+ {Math.round(percent)}%
+ </span>
+ </div>
+ <div
+ role="progressbar"
+ aria-label={label}
+ aria-valuenow={Math.round(percent)}
+ aria-valuemin={0}
+ aria-valuemax={100}
+ className="h-1.5 w-full overflow-hidden rounded-full bg-foreground/10"
+ >
+ <div
+ className={cn("h-full rounded-full transition-all duration-500", BAR_CLASS[severity])}
+ style={{ width: `${Math.max(percent, percent > 0 ? 2 : 0)}%` }}
+ />
+ </div>
+ </div>
+ );
+}
+
+export function AccountUsageMeters({
+ usage,
+ now,
+}: {
+ usage: AccountUsage | undefined;
+ now: number;
+}) {
+ const t = useT();
+ if (!usage) return null;
+
+ // A seat with no login already says so on the row above in plain words.
+ // Repeating it as a usage state would be the same sentence twice.
+ if (usage.status === "signed_out") return null;
+
+ if (usage.status !== "ok" || usage.windows.length === 0) {
+ return (
+ <p className="pl-6 text-[10px] leading-relaxed text-muted-foreground">
+ {usage.status === "unsupported"
+ ? t("agent_accounts.usage.state.unsupported")
+ : t("agent_accounts.usage.state.unavailable")}
+ </p>
+ );
+ }
+
+ const live = usage.source === "live";
+ const ageMs = usage.as_of ? now - usage.as_of * 1000 : null;
+
+ return (
+ <div className="ml-6 space-y-2 rounded-xl border border-border/60 bg-background/40 px-3 py-2.5">
+ <div className="flex items-center gap-1.5">
+ <Gauge className="h-3 w-3 shrink-0 text-muted-foreground" />
+ <span className="text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
+ {t("agent_accounts.usage.title")}
+ </span>
+ {usage.plan && (
+ <span className="shrink-0 rounded-full border border-border bg-secondary/60 px-1.5 py-px text-[9px] font-medium text-muted-foreground">
+ {usage.plan}
+ </span>
+ )}
+ <span
+ className="ml-auto flex shrink-0 items-center gap-1 text-[9px] text-muted-foreground"
+ // The whole point of this line: a cached weekly figure for an idle
+ // seat can be days old, and it is the number a subscription is picked
+ // on. The exact timestamp is one hover away.
+ title={usage.as_of ? new Date(usage.as_of * 1000).toLocaleString() : undefined}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ "h-1.5 w-1.5 rounded-full",
+ live ? "bg-emerald-500" : "bg-muted-foreground/50",
+ )}
+ />
+ {live
+ ? t("agent_accounts.usage.live")
+ : ageMs !== null && ageMs > 0
+ ? `${t("agent_accounts.usage.as_of")} ${durationLabel(ageMs)}`
+ : t("agent_accounts.usage.cached")}
+ </span>
+ </div>
+
+ <div className="space-y-1.5">
+ {usage.windows.map((window, index) => (
+ <Meter
+ key={`${window.kind}:${window.scope_label ?? ""}:${index}`}
+ window={window}
+ now={now}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+export default AccountUsageMeters;
diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx
index 4280220967..8a1984b622 100644
--- a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx
@@ -31,6 +31,7 @@ import {
LogIn,
Pencil,
Plus,
+ RefreshCw,
Trash2,
Users,
X,
@@ -39,6 +40,7 @@ import {
import { useT } from "@/i18n";
import {
type AccountPlatform,
+ type AccountUsage,
type AgentAccount,
type AgentAccountsResponse,
type LoginFlowState,
@@ -46,6 +48,7 @@ import {
createAgentAccount,
deleteAgentAccount,
fetchAgentAccounts,
+ fetchAgentUsage,
getLoginFlow,
groupFor,
loginAgentAccount,
@@ -54,6 +57,7 @@ import {
startLoginFlow,
submitLoginFlowCode,
} from "@/lib/agentAccountsApi";
+import { AccountUsageMeters } from "./AccountUsageMeters";
import { robustCopy, robustPaste } from "@/lib/clipboard";
import { openExternalUrl } from "@/lib/openExternal";
import { useEventStore } from "@/store/events";
@@ -86,6 +90,13 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelProps
const [data, setData] = useState<AgentAccountsResponse | null>(null);
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState<string | null>(null);
+ const [usage, setUsage] = useState<Record<string, AccountUsage>>({});
+ const [usageTtl, setUsageTtl] = useState(60);
+ const [refreshing, setRefreshing] = useState(false);
+ // One clock for every countdown on screen. Per-meter timers would drift
+ // against each other and a card with four seats would run a dozen intervals
+ // to render the same minute.
+ const [now, setNow] = useState(() => Date.now());
const reload = useCallback(async () => {
try {
@@ -100,6 +111,59 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelProps
void reload();
}, [reload]);
+ /**
+ * Usage is fetched SEPARATELY from the account list, and that separation is
+ * the point: the list is a handful of local file reads and must stay instant,
+ * while a reading costs one network round trip per seat. Folding them into
+ * one request would make opening this panel as slow as the slowest provider.
+ */
+ const loadUsage = useCallback(async (force = false) => {
+ try {
+ const body = await fetchAgentUsage(force);
+ const next: Record<string, AccountUsage> = {};
+ for (const entry of body.accounts ?? []) next[entry.account_id] = entry;
+ setUsage(next);
+ if (body.ttl_seconds > 0) setUsageTtl(body.ttl_seconds);
+ setNow(Date.now());
+ } catch {
+ // Usage sits on top of the switcher, so a failed read keeps the previous
+ // numbers (each already labelled with its own age) and never costs the
+ // account list — which is the part the user came here to operate.
+ }
+ }, []);
+
+ // Re-read whenever the set of accounts changes, which is what makes a fresh
+ // sign-in show its plan straight away instead of after the next interval.
+ const accountKey = (data?.platforms ?? [])
+ .flatMap((group) => group.accounts.map((account) => account.id))
+ .join(",");
+ useEffect(() => {
+ if (accountKey) void loadUsage();
+ }, [accountKey, loadUsage]);
+
+ // Poll on the server's own cache lifetime rather than on a second number
+ // kept in step by hand. Floored so a short server TTL cannot turn this into
+ // a request loop.
+ useEffect(() => {
+ const period = Math.max(30, usageTtl) * 1000;
+ const timer = setInterval(() => void loadUsage(), period);
+ return () => clearInterval(timer);
+ }, [loadUsage, usageTtl]);
+
+ useEffect(() => {
+ const timer = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(timer);
+ }, []);
+
+ const refreshUsage = useCallback(async () => {
+ setRefreshing(true);
+ try {
+ await loadUsage(true);
+ } finally {
+ setRefreshing(false);
+ }
+ }, [loadUsage]);
+
/** Run one account action, keeping the list and any error message honest. */
const run = useCallback(
async (key: string, action: () => Promise<AgentAccountsResponse | void>) => {
@@ -128,6 +192,17 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelProps
<span className="text-[11px] text-muted-foreground">
· {t("agent_accounts.hint")}
</span>
+ <button
+ type="button"
+ onClick={() => void refreshUsage()}
+ disabled={refreshing}
+ aria-label={t("agent_accounts.usage.refresh")}
+ title={t("agent_accounts.usage.refresh")}
+ className="ml-auto inline-flex shrink-0 items-center gap-1 rounded-lg border border-border px-2 py-1 text-[10px] text-muted-foreground transition-colors hover:border-primary/40 hover:text-foreground disabled:opacity-50"
+ >
+ <RefreshCw className={cn("h-3 w-3", refreshing && "animate-spin")} />
+ {t("agent_accounts.usage.refresh")}
+ </button>
</div>
<p className="px-1 text-[11px] leading-relaxed text-muted-foreground">
{t("agent_accounts.description")}
@@ -159,6 +234,8 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelProps
busy={busy}
run={run}
activate={onActivate ?? setActiveAgentAccount}
+ usage={usage}
+ now={now}
/>
))}
</div>
@@ -172,12 +249,16 @@ function PlatformCard({
busy,
run,
activate,
+ usage,
+ now,
}: {
platform: AccountPlatform;
group: ReturnType<typeof groupFor>;
busy: string | null;
run: (key: string, action: () => Promise<AgentAccountsResponse | void>) => Promise<void>;
activate: Activate;
+ usage: Record<string, AccountUsage>;
+ now: number;
}) {
const t = useT();
const [adding, setAdding] = useState(false);
@@ -216,6 +297,8 @@ function PlatformCard({
busy={busy}
run={run}
activate={activate}
+ usage={usage[account.id]}
+ now={now}
/>
))}
{accounts.length === 0 && (
@@ -275,12 +358,16 @@ function AccountRow({
busy,
run,
activate,
+ usage,
+ now,
}: {
account: AgentAccount;
active: boolean;
busy: string | null;
run: (key: string, action: () => Promise<AgentAccountsResponse | void>) => Promise<void>;
activate: Activate;
+ usage: AccountUsage | undefined;
+ now: number;
}) {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
@@ -476,6 +563,11 @@ function AccountRow({
</p>
)}
+ {/* How much of THIS seat's plan is gone — the number the choice above is
+ actually made on, which until now could only be read by opening a
+ pane and asking the CLI itself. */}
+ <AccountUsageMeters usage={usage} now={now} />
+
{flow && (
<LoginFlowBox
flow={flow}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 005e138f5c..04e64022d6 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -3969,6 +3969,25 @@
"sign_in": "Anmelden",
"rename": "Umbenennen",
"remove": "Entfernen",
+ "usage": {
+ "title": "Plan-Verbrauch",
+ "refresh": "Aktualisieren",
+ "live": "live",
+ "cached": "aus dem Zwischenspeicher",
+ "as_of": "Stand vor",
+ "resets_in": "zurückgesetzt in",
+ "kind": {
+ "session": "5-Stunden-Limit",
+ "weekly": "Wochen-Limit",
+ "monthly": "Monats-Limit",
+ "rolling": "Limit",
+ "other": "Limit"
+ },
+ "state": {
+ "unsupported": "Dieser Zugang hat kein Plan-Limit, das angezeigt werden kann.",
+ "unavailable": "Der Verbrauch ist gerade nicht lesbar — er erscheint von selbst wieder."
+ }
+ },
"flow": {
"starting": "Anmeldung wird gestartet…",
"waiting_browser": "Warte darauf, dass die Anmeldung im Browser abgeschlossen wird…",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index b58cc8b255..93ff4c76c0 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -3969,6 +3969,25 @@
"sign_in": "Sign in",
"rename": "Rename",
"remove": "Remove",
+ "usage": {
+ "title": "Plan usage",
+ "refresh": "Refresh",
+ "live": "live",
+ "cached": "from cache",
+ "as_of": "as of",
+ "resets_in": "resets in",
+ "kind": {
+ "session": "5-hour limit",
+ "weekly": "Weekly limit",
+ "monthly": "Monthly limit",
+ "rolling": "limit",
+ "other": "Limit"
+ },
+ "state": {
+ "unsupported": "This seat has no plan limit to show.",
+ "unavailable": "Usage is not readable right now — it comes back on its own."
+ }
+ },
"flow": {
"starting": "Starting the sign-in…",
"waiting_browser": "Waiting for the sign-in to finish in the browser…",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index c75b9713c7..8faefabb61 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -3969,6 +3969,25 @@
"sign_in": "Iniciar sesión",
"rename": "Renombrar",
"remove": "Eliminar",
+ "usage": {
+ "title": "Uso del plan",
+ "refresh": "Actualizar",
+ "live": "en vivo",
+ "cached": "desde la caché",
+ "as_of": "hace",
+ "resets_in": "se reinicia en",
+ "kind": {
+ "session": "Límite de 5 horas",
+ "weekly": "Límite semanal",
+ "monthly": "Límite mensual",
+ "rolling": "límite",
+ "other": "Límite"
+ },
+ "state": {
+ "unsupported": "Esta cuenta no tiene un límite de plan que mostrar.",
+ "unavailable": "El uso no se puede leer ahora mismo — volverá por sí solo."
+ }
+ },
"flow": {
"starting": "Iniciando el inicio de sesión…",
"waiting_browser": "Esperando a que el inicio de sesión termine en el navegador…",
diff --git a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts
index 2e3b400633..6ed40ac09a 100644
--- a/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentAccountsApi.ts
@@ -59,6 +59,75 @@ export interface AgentAccountsResponse {
platforms: AccountPlatformGroup[];
}
+/**
+ * One plan limit of one subscription, already normalised by the backend.
+ *
+ * `kind` is a small closed vocabulary the UI translates against — `session`,
+ * `weekly`, `weekly_scoped`, `monthly`, `other`. A provider that invents a
+ * limit this build has no name for arrives as `other` and is still DRAWN, using
+ * `raw_label`: the limit a user is actually being throttled by must never be
+ * the one the panel decides to hide.
+ */
+export interface UsageWindow {
+ kind: string;
+ /** 0-100, already clamped. */
+ percent: number;
+ /** "normal" | "warning" | "critical" */
+ severity: string;
+ /** ISO-8601 UTC, or null when the provider states no reset time. */
+ resets_at: string | null;
+ window_minutes: number | null;
+ /** What a scoped budget is restricted to, e.g. a model name. */
+ scope_label: string | null;
+ raw_label: string | null;
+}
+
+/**
+ * How much of one subscription's plan is spent.
+ *
+ * `source` and `as_of` are not decoration. A reading can come from the provider
+ * just now (`live`) or from what the CLI last wrote to disk (`cached`), and a
+ * cached weekly figure for an idle seat can be days old. Since this is the
+ * number a user picks a subscription on, the UI states which one it is showing
+ * rather than letting a stale percentage pass for a live one.
+ */
+export interface AccountUsage {
+ account_id: string;
+ platform: AccountPlatform;
+ /** "ok" | "signed_out" | "unsupported" | "unavailable" */
+ status: string;
+ windows: UsageWindow[];
+ /** "live" | "cached" */
+ source: string;
+ /** Epoch SECONDS the numbers were true at. */
+ as_of: number | null;
+ message: string;
+ /** Display-only plan name, e.g. "Max 20x". */
+ plan: string | null;
+}
+
+export interface AgentUsageResponse {
+ accounts: AccountUsage[];
+ /** The server's own cache lifetime — the poll interval follows it. */
+ ttl_seconds: number;
+ generated_at: number;
+}
+
+/**
+ * Plan usage for every registered subscription.
+ *
+ * `refresh` bypasses the server's short cache; it backs the manual refresh
+ * button, so a user who just closed a heavy session can see the new number
+ * without waiting out the interval.
+ */
+export async function fetchAgentUsage(refresh = false): Promise<AgentUsageResponse> {
+ const res = await fetch(`/api/agent-accounts/usage${refresh ? "?refresh=true" : ""}`, {
+ cache: "no-store",
+ });
+ if (!res.ok) throw new Error(await detail(res));
+ return (await res.json()) as AgentUsageResponse;
+}
+
async function detail(res: Response): Promise<string> {
try {
const body = (await res.json()) as { detail?: string };
diff --git a/tests/unit/test_agent_usage.py b/tests/unit/test_agent_usage.py
new file mode 100644
index 0000000000..b032bf8a3b
--- /dev/null
+++ b/tests/unit/test_agent_usage.py
@@ -0,0 +1,441 @@
+"""Reading how much of each subscription's plan is already spent.
+
+What these pin down is not "does the JSON parse" but the handful of ways a
+usage meter can be confidently wrong, which is worse than having none at all:
+
+* a CACHED reading must never be reported as a live one — it is the number a
+ user picks a subscription on, and for an idle seat it can be days old;
+* a per-model weekly budget must survive alongside the overall weekly one,
+ because 55% overall next to 99% on one model is the case where "plenty left"
+ is the wrong conclusion;
+* which of Codex's two windows is the short one is decided by its LENGTH, not
+ by the slot it arrives in;
+* a CLI with no reader must get an honest "unsupported", never a neighbouring
+ provider's numbers;
+* nothing here ever reaches the network in a test, and nothing ever returns a
+ token.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from jarvis import agent_usage
+from jarvis.agent_accounts import AgentAccount
+
+#: Captured before any fixture runs. The autouse ``_no_network`` fixture below
+#: replaces the module attribute, so a test that wants to exercise the REAL
+#: transport helper cannot read it back off the module — it would get the stub.
+_REAL_HTTP_GET_JSON = agent_usage._http_get_json
+
+
[email protected](autouse=True)
+def _no_cache_between_tests() -> None:
+ agent_usage.clear_cache()
+
+
[email protected](autouse=True)
+def _no_network(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every live probe fails unless a test opts in.
+
+ A unit test that quietly reaches the real provider is a test that passes on
+ the maintainer's machine and hangs in CI, so the default is "no answer" and
+ the disk fallbacks are what get exercised.
+ """
+ monkeypatch.setattr(agent_usage, "_http_get_json", lambda url, headers: None)
+
+
+def _account(platform: str, config_dir: Path, *, builtin: bool = False) -> AgentAccount:
+ return AgentAccount(
+ id=f"{platform}:test",
+ platform=platform,
+ label="Test seat",
+ config_dir=config_dir,
+ builtin=builtin,
+ )
+
+
+# ----------------------------------------------------------------- claude
+
+
+CLAUDE_LIMITS_PAYLOAD = {
+ "five_hour": {"utilization": 2.0, "resets_at": "2026-08-13T13:20:00+00:00"},
+ "seven_day": {"utilization": 74.0, "resets_at": "2026-08-14T06:00:00+00:00"},
+ "limits": [
+ {
+ "kind": "session",
+ "group": "session",
+ "percent": 2,
+ "severity": "normal",
+ "resets_at": "2026-08-13T13:20:00+00:00",
+ "scope": None,
+ },
+ {
+ "kind": "weekly_all",
+ "group": "weekly",
+ "percent": 74,
+ "severity": "normal",
+ "resets_at": "2026-08-14T06:00:00+00:00",
+ "scope": None,
+ },
+ {
+ "kind": "weekly_scoped",
+ "group": "weekly",
+ "percent": 100,
+ "severity": "critical",
+ "resets_at": "2026-08-14T06:00:00+00:00",
+ "scope": {"model": {"id": None, "display_name": "Fable"}, "surface": None},
+ },
+ ],
+}
+
+
+def test_claude_keeps_the_scoped_weekly_budget_next_to_the_overall_one() -> None:
+ """A model at 100% must not be hidden behind an overall week at 74%."""
+ windows = agent_usage._claude_windows(CLAUDE_LIMITS_PAYLOAD)
+ kinds = [w.kind for w in windows]
+ assert kinds == ["session", "weekly", "weekly_scoped"]
+ scoped = windows[2]
+ assert scoped.percent == 100
+ assert scoped.severity == "critical"
+ assert scoped.scope_label == "Fable"
+
+
+def test_claude_uses_the_providers_own_severity_not_its_own_arithmetic() -> None:
+ """74% is 'normal' because the provider said so, not because 74 < 80."""
+ payload = {
+ "limits": [
+ {"kind": "weekly_all", "group": "weekly", "percent": 12, "severity": "critical"},
+ ]
+ }
+ (window,) = agent_usage._claude_windows(payload)
+ assert window.severity == "critical"
+
+
+def test_claude_falls_back_to_the_named_fields_when_there_is_no_limits_array() -> None:
+ """An older payload shape still shows both headline numbers."""
+ payload = {
+ "five_hour": {"utilization": 10.0, "resets_at": "2026-08-13T13:20:00+00:00"},
+ "seven_day": {"utilization": 90.0, "resets_at": "2026-08-14T06:00:00+00:00"},
+ }
+ windows = agent_usage._claude_windows(payload)
+ assert [w.kind for w in windows] == ["session", "weekly"]
+ assert windows[0].window_minutes == 300
+ assert windows[1].window_minutes == 10080
+ # No severity is stated in this shape, so the shared scale decides.
+ assert windows[1].severity == "warning"
+
+
+def test_claude_reports_a_disk_reading_as_cached_with_the_providers_timestamp(
+ tmp_path: Path,
+) -> None:
+ """The whole honesty contract: an old number must not look like a live one."""
+ (tmp_path / ".claude.json").write_text(
+ json.dumps(
+ {
+ "oauthAccount": {"organizationRateLimitTier": "default_claude_max_20x"},
+ "cachedUsageUtilization": {
+ "fetchedAtMs": 1786557552405,
+ "utilization": CLAUDE_LIMITS_PAYLOAD,
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+ usage = agent_usage.read_usage(_account("claude", tmp_path))
+ assert usage.status == "ok"
+ assert usage.source == "cached"
+ assert usage.as_of == pytest.approx(1786557552.405)
+ assert usage.plan == "Max 20x"
+ assert len(usage.windows) == 3
+
+
+def test_claude_without_any_login_says_signed_out_rather_than_zero_percent(
+ tmp_path: Path,
+) -> None:
+ """An empty seat must not draw a reassuring 0% bar."""
+ usage = agent_usage.read_usage(_account("claude", tmp_path))
+ assert usage.status == "signed_out"
+ assert usage.windows == ()
+
+
+def test_an_unmapped_plan_tier_is_still_shown_readably(tmp_path: Path) -> None:
+ (tmp_path / ".claude.json").write_text(
+ json.dumps({"oauthAccount": {"organizationRateLimitTier": "default_claude_max_50x"}}),
+ encoding="utf-8",
+ )
+ usage = agent_usage.read_usage(_account("claude", tmp_path))
+ assert usage.plan == "Max 50X"
+
+
+# ------------------------------------------------------------------ codex
+
+
+def _codex_signed_in(config_dir: Path) -> None:
+ (config_dir / "auth.json").write_text(
+ json.dumps({"tokens": {"access_token": "not-a-real-token", "account_id": "acct"}}),
+ encoding="utf-8",
+ )
+
+
+def test_codex_names_its_windows_by_length_not_by_slot() -> None:
+ """'primary' is not always the weekly one — the window length decides."""
+ windows = agent_usage._codex_rate_limit_windows(
+ {
+ "primary": {"used_percent": 40.0, "window_minutes": 10080, "resets_at": 1786977114},
+ "secondary": {"used_percent": 8.0, "window_minutes": 300, "resets_at": 1786900000},
+ }
+ )
+ # Sorted shortest window first, which is also the display order.
+ assert [w.kind for w in windows] == ["session", "weekly"]
+ assert windows[0].percent == 8.0
+ assert windows[1].percent == 40.0
+ assert windows[0].resets_at is not None and windows[0].resets_at.endswith("+00:00")
+
+
+def test_codex_recognises_a_thirty_day_window_as_monthly() -> None:
+ """Measured on a real seat: 43200 minutes must not read as 'other'."""
+ (window,) = agent_usage._codex_rate_limit_windows(
+ {"primary": {"used_percent": 70.0, "window_minutes": 43200, "resets_at": 1789000000}}
+ )
+ assert window.kind == "monthly"
+
+
+def test_codex_reads_the_newest_rate_limits_out_of_a_session_transcript(
+ tmp_path: Path,
+) -> None:
+ """The disk fallback that carries this feature when the endpoint cannot."""
+ _codex_signed_in(tmp_path)
+ sessions = tmp_path / "sessions" / "2026" / "08" / "13"
+ sessions.mkdir(parents=True)
+ rollout = sessions / "rollout-2026-08-13T10-00-00-abc.jsonl"
+ lines = [
+ json.dumps({"timestamp": "2026-08-13T09:00:00.000Z", "type": "event_msg", "payload": {}}),
+ json.dumps(
+ {
+ "timestamp": "2026-08-13T09:30:00.000Z",
+ "type": "event_msg",
+ "payload": {
+ "type": "token_count",
+ "rate_limits": {
+ "primary": {"used_percent": 11.0, "window_minutes": 10080},
+ },
+ },
+ }
+ ),
+ json.dumps(
+ {
+ "timestamp": "2026-08-13T10:00:00.000Z",
+ "type": "event_msg",
+ "payload": {
+ "type": "token_count",
+ "rate_limits": {
+ "plan_type": "plus",
+ "primary": {"used_percent": 23.0, "window_minutes": 10080},
+ },
+ },
+ }
+ ),
+ ]
+ rollout.write_text("\n".join(lines) + "\n", encoding="utf-8")
+
+ usage = agent_usage.read_usage(_account("codex", tmp_path))
+ assert usage.status == "ok"
+ assert usage.source == "cached"
+ assert usage.plan == "Plus"
+ # The LAST record wins — an earlier one in the same file is strictly older.
+ assert [w.percent for w in usage.windows] == [23.0]
+
+
+def test_codex_finds_the_record_in_a_transcript_larger_than_the_tail_window(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Only the tail is read, so the seek must not cut the answer off."""
+ monkeypatch.setattr(agent_usage, "ROLLOUT_TAIL_BYTES", 2048)
+ _codex_signed_in(tmp_path)
+ sessions = tmp_path / "sessions"
+ sessions.mkdir(parents=True)
+ rollout = sessions / "rollout-big.jsonl"
+ padding = [json.dumps({"type": "noise", "payload": {"blob": "x" * 200}}) for _ in range(200)]
+ answer = json.dumps(
+ {
+ "timestamp": "2026-08-13T10:00:00.000Z",
+ "payload": {"rate_limits": {"primary": {"used_percent": 5.0, "window_minutes": 300}}},
+ }
+ )
+ rollout.write_text("\n".join([*padding, answer]) + "\n", encoding="utf-8")
+
+ usage = agent_usage.read_usage(_account("codex", tmp_path))
+ assert usage.status == "ok"
+ assert [w.kind for w in usage.windows] == ["session"]
+
+
+def test_codex_on_an_api_key_says_there_is_no_plan_limit(tmp_path: Path) -> None:
+ """Per-request billing has no window to spend down — an empty bar would lie."""
+ (tmp_path / "auth.json").write_text(json.dumps({"OPENAI_API_KEY": "sk-test"}), encoding="utf-8")
+ usage = agent_usage.read_usage(_account("codex", tmp_path))
+ assert usage.status == "unsupported"
+
+
+def test_codex_signed_in_but_never_used_is_unavailable_not_zero(tmp_path: Path) -> None:
+ _codex_signed_in(tmp_path)
+ usage = agent_usage.read_usage(_account("codex", tmp_path))
+ assert usage.status == "unavailable"
+ assert usage.windows == ()
+
+
+# ---------------------------------------------------------------- generic
+
+
+def test_an_unknown_cli_gets_an_honest_answer_not_a_neighbours_numbers(
+ tmp_path: Path,
+) -> None:
+ """The failure an `if claude / else codex` pair would produce silently."""
+ (tmp_path / ".claude.json").write_text(
+ json.dumps({"cachedUsageUtilization": {"utilization": CLAUDE_LIMITS_PAYLOAD}}),
+ encoding="utf-8",
+ )
+ usage = agent_usage.read_usage(_account("some-new-cli", tmp_path))
+ assert usage.status == "unsupported"
+ assert usage.windows == ()
+
+
+def test_supports_usage_reports_only_the_clis_with_a_real_reader() -> None:
+ assert agent_usage.supports_usage("claude") is True
+ assert agent_usage.supports_usage("codex") is True
+ assert agent_usage.supports_usage("some-new-cli") is False
+
+
+# ------------------------------------------------------------- collect/cache
+
+
+def test_collect_serves_the_cache_until_the_ttl_expires(tmp_path: Path) -> None:
+ """The panel polls; a percentage does not move fast enough to re-ask each time."""
+ calls: list[str] = []
+ account = _account("claude", tmp_path)
+
+ def counting_reader(acc: AgentAccount) -> agent_usage.AccountUsage:
+ calls.append(acc.id)
+ return agent_usage.AccountUsage(account_id=acc.id, platform=acc.platform, status="ok")
+
+ original = agent_usage._READERS["claude"]
+ agent_usage._READERS["claude"] = counting_reader
+ try:
+ agent_usage.collect([account])
+ agent_usage.collect([account])
+ assert calls == [account.id]
+ # A forced refresh is what the manual button does, and it must bypass it.
+ agent_usage.collect([account], refresh=True)
+ assert len(calls) == 2
+ # A zero TTL means "never reuse", which is how the tests above stay honest.
+ agent_usage.collect([account], ttl=0)
+ assert len(calls) == 3
+ finally:
+ agent_usage._READERS["claude"] = original
+
+
+def test_a_reader_that_raises_costs_one_row_not_the_panel(tmp_path: Path) -> None:
+ account = _account("claude", tmp_path)
+
+ def exploding_reader(_acc: AgentAccount) -> agent_usage.AccountUsage:
+ raise RuntimeError("provider changed everything")
+
+ original = agent_usage._READERS["claude"]
+ agent_usage._READERS["claude"] = exploding_reader
+ try:
+ usage = agent_usage.read_usage(account)
+ finally:
+ agent_usage._READERS["claude"] = original
+ assert usage.status == "unavailable"
+
+
+def test_no_reading_ever_carries_a_credential(tmp_path: Path) -> None:
+ """The wire shape is display-only by construction."""
+ (tmp_path / ".claude.json").write_text(
+ json.dumps({"cachedUsageUtilization": {"utilization": CLAUDE_LIMITS_PAYLOAD}}),
+ encoding="utf-8",
+ )
+ (tmp_path / ".credentials.json").write_text(
+ json.dumps(
+ {
+ "claudeAiOauth": {
+ "accessToken": "sk-ant-oat-secret",
+ "refreshToken": "refresh-secret",
+ "expiresAt": 1,
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+ payload = json.dumps(agent_usage.read_usage(_account("claude", tmp_path)).to_dict())
+ assert "secret" not in payload
+ assert "sk-ant" not in payload
+
+
+# ------------------------------------------------------------------ shared
+
+
+ ("percent", "expected"),
+ [(0.0, "normal"), (79.9, "normal"), (80.0, "warning"), (94.9, "warning"), (95.0, "critical")],
+)
+def test_one_severity_scale_serves_every_provider(percent: float, expected: str) -> None:
+ """Two rows at the same percentage must never be coloured differently."""
+ assert agent_usage._severity(percent) == expected
+
+
+def test_an_unreachable_host_is_left_alone_but_an_http_error_is_retried(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """An offline machine must not pay a six-second timeout on every poll.
+
+ The asymmetry is the point: being unreachable is expensive and stays true
+ for a while, so it earns a cooldown. An HTTP status answers instantly, so
+ retrying it costs nothing — and cooling THAT down would keep a seat on
+ cached numbers for minutes after a one-off server hiccup.
+ """
+ monkeypatch.setattr(agent_usage, "_http_get_json", _REAL_HTTP_GET_JSON)
+ agent_usage.clear_cache()
+
+ attempts: list[str] = []
+
+ class _Unreachable:
+ def get(self, url: str, **_kw: object) -> object:
+ attempts.append(url)
+ raise OSError("no route to host")
+
+ class _Rejecting:
+ def get(self, url: str, **_kw: object) -> object:
+ attempts.append(url)
+
+ class _Response:
+ status_code = 403
+
+ def json(self) -> object:
+ return {}
+
+ return _Response()
+
+ monkeypatch.setitem(sys.modules, "httpx", _Unreachable())
+ assert agent_usage._http_get_json("https://example.invalid/u", {}) is None
+ assert agent_usage._http_get_json("https://example.invalid/u", {}) is None
+ assert attempts == ["https://example.invalid/u"], "the second probe must be skipped"
+
+ attempts.clear()
+ agent_usage.clear_cache()
+ monkeypatch.setitem(sys.modules, "httpx", _Rejecting())
+ assert agent_usage._http_get_json("https://example.invalid/v", {}) is None
+ assert agent_usage._http_get_json("https://example.invalid/v", {}) is None
+ assert len(attempts) == 2, "a rejected request must still be retried"
+
+
+def test_an_over_consumed_window_is_clamped_to_full_rather_than_dropped() -> None:
+ """103% means 'full'; refusing to draw it would hide the worst state."""
+ assert agent_usage._clamp_percent(103) == 100.0
+ assert agent_usage._clamp_percent(-5) == 0.0
+ assert agent_usage._clamp_percent("nope") is None
+ assert agent_usage._clamp_percent(True) is None