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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(subscriptions): show accurate Codex and Grok usage and Google login
rubenluetke10-beepf8db5b599e77
diff --git a/jarvis/agent_usage.py b/jarvis/agent_usage.pyindex ed7cf1222f..5c7eb374f1 100644--- a/jarvis/agent_usage.py+++ b/jarvis/agent_usage.py@@ -49,6 +49,7 @@ from typing import Anyfrom loguru import loggerfrom jarvis.agent_accounts import AgentAccount+from jarvis.core.http_pool import SyncHttpClientPool#: 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@@ -204,6 +205,7 @@ class AccountUsage:_CACHE = _Cache()+_HTTP_POOL = SyncHttpClientPool(timeout_s=HTTP_TIMEOUT_S)# ------------------------------------------------------------------ helpers@@ -306,12 +308,7 @@ def _http_get_json(url: str, headers: dict[str, str]) -> Any | None:if blocked_until is not None and time.time() < blocked_until:return Nonetry:- 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)+ response = _HTTP_POOL.client().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_Slogger.debug("Agent usage: {} could not be reached ({})", url, type(exc).__name__)@@ -575,6 +572,10 @@ def _codex_rate_limit_windows(rate_limits: Any) -> tuple[UsageWindow, ...]:"""if not isinstance(rate_limits, dict):return ()+ # Spark and other separately metered models are not the account's Codex+ # allowance. Their often-empty windows must never replace its weekly bar.+ if rate_limits.get("limit_id") not in (None, "codex"):+ return ()windows: list[UsageWindow] = []for slot in ("primary", "secondary"):block = rate_limits.get(slot)@@ -660,6 +661,10 @@ def _codex_last_rate_limits(path: Path) -> tuple[dict[str, Any], float] | None:limits = payload.get("rate_limits") if isinstance(payload, dict) else Noneif not isinstance(limits, dict):continue+ if limits.get("limit_id") not in (None, "codex"):+ continue+ if not _codex_rate_limit_windows(limits):+ continuestamp = record.get("timestamp") if isinstance(record, dict) else Noneas_of = path.stat().st_mtimeif isinstance(stamp, str):@@ -740,11 +745,14 @@ def _codex_usage(account: AgentAccount) -> AccountUsage:# 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.+ readings: list[tuple[dict[str, Any], float]] = []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+ if found is not None:+ readings.append(found)+ # A transcript can be touched long after its last usage event (titles,+ # resumes, sync). Compare the event timestamps, not file modification order.+ for rate_limits, as_of in sorted(readings, key=lambda item: item[1], reverse=True):windows = _codex_rate_limit_windows(rate_limits)if windows:return AccountUsage(@@ -771,6 +779,59 @@ def _codex_usage(account: AgentAccount) -> AccountUsage:# ------------------------------------------------------------------ generic+def _grok_build_usage(account: AgentAccount) -> AccountUsage:+ """Read the same included-credit snapshot as Grok Build's /usage view.++ Wire source: xai-grok-shell/src/extensions/billing.rs and+ agent/remote_config/endpoint.rs in xai-org/grok-build.+ """+ from jarvis.grok_build_auth import _auth_record, _derive_auth++ auth = _read_json_file(account.config_dir / "auth.json") or {}+ connected, mode = _derive_auth(auth)+ if not connected or mode != "subscription":+ return AccountUsage(account.id, account.platform, "signed_out")+ token = _auth_record(auth).get("key")+ payload = None+ if isinstance(token, str) and token:+ payload = _http_get_json(+ "https://cli-chat-proxy.grok.com/v1/billing?format=credits",+ {"Authorization": f"Bearer {token}", "X-XAI-Token-Auth": "xai-grok-cli"},+ )+ config = payload.get("config") if isinstance(payload, dict) else None+ if isinstance(config, dict):+ percent = _clamp_percent(config.get("creditUsagePercent"))+ period = config.get("currentPeriod")+ period = period if isinstance(period, dict) else {}+ minutes = {+ "USAGE_PERIOD_TYPE_WEEKLY": WEEKLY_WINDOW_MINUTES,+ "USAGE_PERIOD_TYPE_MONTHLY": MONTHLY_WINDOW_MINUTES,+ }.get(period.get("type"))+ if percent is not None:+ return AccountUsage(+ account.id,+ account.platform,+ "ok",+ windows=(+ UsageWindow(+ kind=_kind_for_window(minutes),+ percent=percent,+ severity=_severity(percent),+ resets_at=_iso_or_none(period.get("end") or config.get("billingPeriodEnd")),+ window_minutes=minutes,+ ),+ ),+ source="live",+ as_of=time.time(),+ )+ return AccountUsage(+ account.id,+ account.platform,+ "unavailable",+ message="Grok Build usage could not be read. Reconnect if the login expired.",+ )++def _generic_usage(account: AgentAccount) -> AccountUsage:"""The answer for a CLI this build has no usage reader for.@@ -798,6 +859,7 @@ def _generic_usage(account: AgentAccount) -> AccountUsage:_READERS: dict[str, Any] = {"claude": _claude_usage,"codex": _codex_usage,+ "grok-build": _grok_build_usage,}diff --git a/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsx b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsxindex 7de2b4cd4a..380ba386f4 100644--- a/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsx+++ b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.test.tsx@@ -50,6 +50,12 @@ function usage(overrides: Partial<AccountUsage> = {}): AccountUsage {}describe("AccountUsageMeters", () => {+ it("distinguishes 46 percent used from 54 percent remaining", () => {+ render(<AccountUsageMeters now={NOW} usage={usage({ windows: [window_({ percent: 46 })] })} />);+ expect(screen.getByText("46% used")).toBeTruthy();+ expect(screen.getByText("54% remaining")).toBeTruthy();+ expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBe("46");+ });it("draws every window, including a scoped one beside the overall week", () => {render(<AccountUsageMetersdiff --git a/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsx b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsxindex b28dbd878f..5cab11423e 100644--- a/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsx+++ b/jarvis/ui/web/frontend/src/components/AccountUsageMeters.tsx@@ -134,9 +134,12 @@ function Meter({ window: usageWindow, now }: { window: UsageWindow; now: numberPERCENT_CLASS[severity],)}>- {Math.round(percent)}%+ {Math.round(percent)}% {t("agent_accounts.usage.used")}</span></div>+ <p className="text-right text-micro tabular-nums text-muted-foreground">+ {Math.round(100 - percent)}% {t("agent_accounts.usage.remaining")}+ </p><divrole="progressbar"aria-label={label}diff --git a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsxindex 0f1696de5c..d4ca98867e 100644--- a/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/AgentAccountsPanel.tsx@@ -58,6 +58,7 @@ import {submitLoginFlowCode,} from "@/lib/agentAccountsApi";import { AccountUsageMeters } from "./AccountUsageMeters";+import { AntigravitySubscriptionCard } from "./AntigravitySubscriptionCard";import { robustCopy, robustPaste } from "@/lib/clipboard";import { openExternalUrl } from "@/lib/openExternal";import { useEventStore } from "@/store/events";@@ -93,6 +94,7 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelPropsconst [usage, setUsage] = useState<Record<string, AccountUsage>>({});const [usageTtl, setUsageTtl] = useState(60);const [refreshing, setRefreshing] = useState(false);+ const [subscriptionRefresh, setSubscriptionRefresh] = useState(0);// Assumed true until a 404 proves otherwise, so the meters appear on the// first successful read instead of after a round trip spent proving support.const [usageAvailable, setUsageAvailable] = useState(true);@@ -173,12 +175,13 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelPropsconst refreshUsage = useCallback(async () => {setRefreshing(true);+ setSubscriptionRefresh((value) => value + 1);try {- await loadUsage(true);+ await Promise.all([reload(), loadUsage(true)]);} finally {setRefreshing(false);}- }, [loadUsage]);+ }, [loadUsage, reload]);/** Run one account action, keeping the list and any error message honest. */const run = useCallback(@@ -256,6 +259,7 @@ export function AgentAccountsPanel({ onActivate, note }: AgentAccountsPanelPropsnow={now}/>))}+ <AntigravitySubscriptionCard refresh={subscriptionRefresh} /></div></div>);diff --git a/jarvis/ui/web/frontend/src/components/AntigravitySubscriptionCard.test.tsx b/jarvis/ui/web/frontend/src/components/AntigravitySubscriptionCard.test.tsxnew file mode 100644index 0000000000..9646ddb3ea--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/AntigravitySubscriptionCard.test.tsx@@ -0,0 +1,27 @@+import { afterEach, expect, test, vi } from "vitest";+import { cleanup, render, screen, waitFor } from "@testing-library/react";+import { AntigravitySubscriptionCard } from "./AntigravitySubscriptionCard";++afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++test("the connected Google subscription is visible without a switchable account directory", async () => {+ const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => ({+ installed: true, connected: true, mode: "oauth-personal", message: "Connected via Google subscription",+ }) });+ vi.stubGlobal("fetch", fetch);+ const view = render(<AntigravitySubscriptionCard refresh={0} />);+ expect(await screen.findByText("Connected via Google subscription")).toBeTruthy();+ expect(screen.getByRole("region", { name: "Antigravity" })).toBeTruthy();+ expect(screen.queryByRole("progressbar")).toBeNull();+ view.rerender(<AntigravitySubscriptionCard refresh={1} />);+ await waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));+});++test("an API-key connection is not presented as a Google subscription", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, json: async () => ({+ installed: true, connected: true, mode: "api_key", message: "API key configured",+ }) }));+ render(<AntigravitySubscriptionCard refresh={0} />);+ expect(await screen.findByText("not signed in")).toBeTruthy();+ expect(screen.queryByText("API key configured")).toBeNull();+});diff --git a/jarvis/ui/web/frontend/src/components/AntigravitySubscriptionCard.tsx b/jarvis/ui/web/frontend/src/components/AntigravitySubscriptionCard.tsxnew file mode 100644index 0000000000..3b62367716--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/AntigravitySubscriptionCard.tsx@@ -0,0 +1,37 @@+import { useEffect, useState } from "react";+import { KeyRound } from "lucide-react";+import type { AntigravityStatus } from "@/hooks/useProviders";+import { useT } from "@/i18n";++/** A connected Google login is a subscription even without multi-account support. */+export function AntigravitySubscriptionCard({ refresh }: { refresh: number }) {+ const t = useT();+ const [status, setStatus] = useState<AntigravityStatus | null>(null);+ const [failed, setFailed] = useState(false);+ useEffect(() => {+ const controller = new AbortController();+ void fetch("/api/antigravity/status", { cache: "no-store", signal: controller.signal })+ .then(async (response) => {+ if (!response.ok) throw new Error("Antigravity status unavailable");+ const next = await response.json() as AntigravityStatus;+ if (!controller.signal.aborted) { setStatus(next); setFailed(false); }+ })+ .catch(() => {+ // Render the failed read; never present a previous login as current.+ if (!controller.signal.aborted) { setStatus(null); setFailed(true); }+ });+ return () => controller.abort();+ }, [refresh]);+ const connected = status?.installed && status.connected && status.mode === "oauth-personal";+ return <section aria-label="Antigravity" className="flex flex-col gap-3 rounded-2xl border border-border bg-card p-4">+ <h4 className="text-sm font-semibold">Antigravity</h4>+ <div className="space-y-2 rounded-xl border border-border px-3 py-2">+ <p className="flex items-start gap-2 text-xs text-muted-foreground">+ <KeyRound className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />+ {status ? connected || status.mode !== "api_key" ? status.message : t("agent_accounts.not_signed_in") : t(failed ? "agent_accounts.usage.state.unavailable" : "agent_accounts.loading")}+ </p>+ <p className="text-micro text-muted-foreground">{t("agent_accounts.single_google_login")}</p>+ <p className="text-micro text-muted-foreground">{t("agent_accounts.usage.state.unsupported")}</p>+ </div>+ </section>;+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b15b0836fd..165f9a4f91 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -4192,6 +4192,8 @@}},"agent_accounts": {+ "not_signed_in": "nicht angemeldet",+ "single_google_login": "Nutzt das unter API Keys verbundene Google-Abo. Weitere Google-Anmeldungen lassen sich hier noch nicht wechseln.","title": "Deine Abos","hint": "mehrere Logins pro CLI","description": "Du hast mehr als ein Abo für dasselbe Coding-CLI? Trag hier jedes ein und wechsle, ohne dich abzumelden — jeder Login bleibt parallel gültig. Der Haken markiert das Konto, mit dem NEUE Terminals starten; bereits laufende Terminals behalten das Konto, mit dem sie gestartet wurden.",@@ -4221,9 +4223,11 @@"other": "Limit"},"state": {- "unsupported": "Dieser Zugang hat kein Plan-Limit, das angezeigt werden kann.",+ "unsupported": "Für diesen Anbieter sind hier keine Verbrauchsdaten verfügbar.","unavailable": "Der Verbrauch ist gerade nicht lesbar — er erscheint von selbst wieder."- }+ },+ "used": "verbraucht",+ "remaining": "übrig"},"flow": {"starting": "Anmeldung wird gestartet…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex a1790b284a..5b75d6efb8 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -4225,6 +4225,8 @@}},"agent_accounts": {+ "not_signed_in": "not signed in",+ "single_google_login": "Uses the Google subscription connected under API Keys. Additional Google logins cannot be switched here yet.","title": "Your subscriptions","hint": "several logins per CLI","description": "Hold more than one plan for the same coding CLI? Register each one here and switch without signing out — every login stays valid side by side. The tick marks the account NEW terminals open on; terminals that are already running keep the account they were started with.",@@ -4241,6 +4243,8 @@"remove": "Remove","usage": {"title": "Plan usage",+ "used": "used",+ "remaining": "remaining","refresh": "Refresh","live": "live","cached": "from cache",@@ -4254,7 +4258,7 @@"other": "Limit"},"state": {- "unsupported": "This seat has no plan limit to show.",+ "unsupported": "Plan usage is not available for this provider here.","unavailable": "Usage is not readable right now — it comes back on its own."}},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex d214275403..8f29d28561 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -4192,6 +4192,8 @@}},"agent_accounts": {+ "not_signed_in": "sin sesión iniciada",+ "single_google_login": "Utiliza la suscripción de Google conectada en API Keys. Todavía no se puede alternar entre otras cuentas de Google aquí.","title": "Tus suscripciones","hint": "varios inicios de sesión por CLI","description": "¿Tienes más de un plan para la misma CLI de programación? Registra cada uno aquí y cambia sin cerrar sesión: todos los accesos siguen siendo válidos a la vez. La marca indica la cuenta con la que se abren los terminales NUEVOS; los terminales en curso conservan la cuenta con la que se iniciaron.",@@ -4221,9 +4223,11 @@"other": "Límite"},"state": {- "unsupported": "Esta cuenta no tiene un límite de plan que mostrar.",+ "unsupported": "Los datos de uso de este proveedor no están disponibles aquí.","unavailable": "El uso no se puede leer ahora mismo — volverá por sí solo."- }+ },+ "used": "utilizado",+ "remaining": "restante"},"flow": {"starting": "Iniciando el inicio de sesión…",diff --git a/tests/unit/test_agent_usage.py b/tests/unit/test_agent_usage.pyindex b032bf8a3b..f5d85b06bc 100644--- a/tests/unit/test_agent_usage.py+++ b/tests/unit/test_agent_usage.py@@ -19,7 +19,6 @@ usage meter can be confidently wrong, which is worse than having none at all:from __future__ import annotationsimport json-import sysfrom pathlib import Pathimport pytest@@ -420,14 +419,14 @@ def test_an_unreachable_host_is_left_alone_but_an_http_error_is_retried(return _Response()- monkeypatch.setitem(sys.modules, "httpx", _Unreachable())+ monkeypatch.setattr(agent_usage._HTTP_POOL, "client", lambda: _Unreachable())assert agent_usage._http_get_json("https://example.invalid/u", {}) is Noneassert agent_usage._http_get_json("https://example.invalid/u", {}) is Noneassert attempts == ["https://example.invalid/u"], "the second probe must be skipped"attempts.clear()agent_usage.clear_cache()- monkeypatch.setitem(sys.modules, "httpx", _Rejecting())+ monkeypatch.setattr(agent_usage._HTTP_POOL, "client", lambda: _Rejecting())assert agent_usage._http_get_json("https://example.invalid/v", {}) is Noneassert agent_usage._http_get_json("https://example.invalid/v", {}) is Noneassert len(attempts) == 2, "a rejected request must still be retried"@@ -439,3 +438,112 @@ def test_an_over_consumed_window_is_clamped_to_full_rather_than_dropped() -> Nonassert agent_usage._clamp_percent(-5) == 0.0assert agent_usage._clamp_percent("nope") is Noneassert agent_usage._clamp_percent(True) is None+++def test_codex_spark_never_replaces_the_main_weekly_allowance(tmp_path: Path) -> None:+ _codex_signed_in(tmp_path)+ sessions = tmp_path / "sessions"+ sessions.mkdir()++ def event(stamp, limit_id, percent):+ return json.dumps(+ {+ "timestamp": stamp,+ "payload": {+ "rate_limits": {+ "limit_id": limit_id,+ "plan_type": "pro",+ "primary": {"used_percent": percent, "window_minutes": 10080},+ }+ },+ }+ )++ # The same stream can report the main allowance followed by a Spark update.+ (sessions / "rollout-main.jsonl").write_text(+ event("2026-09-10T12:00:00Z", "codex", 46)+ + "\n"+ + event("2026-09-10T12:01:00Z", "codex_bengalfox", 0),+ encoding="utf-8",+ )+ # A newly touched transcript is not necessarily the freshest measurement.+ (sessions / "rollout-old.jsonl").write_text(+ event("2026-09-09T12:00:00Z", "codex", 20), encoding="utf-8"+ )+ usage = agent_usage.read_usage(_account("codex", tmp_path))+ assert usage.status == "ok" and usage.source == "cached"+ assert [(w.kind, w.percent) for w in usage.windows] == [("weekly", 46)]+++def test_codex_spark_only_is_unavailable_not_an_empty_main_budget(tmp_path: Path) -> None:+ _codex_signed_in(tmp_path)+ sessions = tmp_path / "sessions"+ sessions.mkdir()+ (sessions / "rollout-spark.jsonl").write_text(+ json.dumps(+ {+ "payload": {+ "rate_limits": {+ "limit_id": "codex_bengalfox",+ "primary": {"used_percent": 0, "window_minutes": 10080},+ }+ }+ }+ ),+ encoding="utf-8",+ )+ assert agent_usage.read_usage(_account("codex", tmp_path)).status == "unavailable"++[email protected]("percent", [0, 54, 100])+def test_grok_build_reads_live_credit_usage_for_its_own_account(tmp_path, monkeypatch, percent):+ scope = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"+ (tmp_path / "auth.json").write_text(+ json.dumps(+ {+ scope: {+ "auth_mode": "oidc",+ "key": "grok-test-bearer",+ }+ }+ ),+ encoding="utf-8",+ )++ def get(url, headers):+ assert url == "https://cli-chat-proxy.grok.com/v1/billing?format=credits"+ assert headers["Authorization"] == "Bearer grok-test-bearer"+ return {+ "config": {+ "creditUsagePercent": percent,+ "currentPeriod": {+ "type": "USAGE_PERIOD_TYPE_WEEKLY",+ "end": "2026-09-14T12:59:05Z",+ },+ }+ }++ monkeypatch.setattr(agent_usage, "_http_get_json", get)+ usage = agent_usage.read_usage(_account("grok-build", tmp_path))+ assert usage.status == "ok" and usage.source == "live"+ assert usage.windows[0].kind == "weekly" and usage.windows[0].percent == percent+ assert usage.windows[0].resets_at is not None+ assert "grok-test-bearer" not in json.dumps(usage.to_dict())+++def test_grok_missing_usage_does_not_invent_zero(tmp_path, monkeypatch):+ scope = "https://auth.x.ai::b1a00492-073a-47ea-816f-4c329264a828"+ (tmp_path / "auth.json").write_text(+ json.dumps(+ {+ scope: {+ "auth_mode": "oidc",+ "key": "grok-test-bearer",+ }+ }+ ),+ encoding="utf-8",+ )+ monkeypatch.setattr(agent_usage, "_http_get_json", lambda *args: {"config": {}})+ usage = agent_usage.read_usage(_account("grok-build", tmp_path))+ assert usage.status == "unavailable" and usage.windows == ()