Files
ai-agent/backend/plugins/usagedata.py
gabrielvidalandClaude Opus 5.5 f21db5ed56 feat(home): plugin tiles bring their own links — no core links into plan/activity pages
The owner's home-strip tiles were already the plan-usage and activity plugins'
(`provides: home.tiles`, 2026-11-26); this drops what the core still carried
for them now that /dashboards/plan and /dashboards/activity are gone:

- ProfileUsageCard: the core Meter is a guest's own Claude gauge only (always
  /settings/logins/claude — the owner's /dashboards/plan branch was
  unreachable); Stat no longer defaults to /dashboards/activity; the core
  DEFAULT_BENCH naming the activity plugin's `tokens` id is gone (the tile's
  own `defaultBench` benches it).
- PluginTile: every kind links to the tile's `to` (its plugin's page), the
  burn gauge included again (BurnGauge lost its link with plugin-links); a
  tile without `to` links nowhere instead of to "/".
- home.tiles: two fields the plugins already sent and the sanitizer dropped —
  `stashLabel` (≤ 48: the bench's name, "$ today" for "Today", as the core
  tiles had) and the burn tile's `noReading` ("no reading", not a $0 dial).
  Schema + openapi.json + generated HomeTile follow.
- French: "Plan usage dashboard" goes with its only use.
- Docs: plugins.md / CLAUDE.md / usage-calibration.md / usagedata.py no
  longer say the old paths redirect.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 18:33:32 +01:00

142 lines
6.1 KiB
Python

"""``usage.read`` / ``usage.calibrate`` — the Plan usage dashboard's data,
read by the ``plan-usage`` live plugin (since 2026-11-26 it replaced core's
``/dashboards/plan`` page; its own is ``/plugins/plan-usage/board``).
Everything stays in ``usage/`` (the poller, the store, the calibration maths,
``/api/usage/*`` — Home's burn tile, the composer's rings, ``ai-agent usage``
and the rate-shift pushes still read it); this only bundles one scope's worth
of it into one answer, so the page loads in a single call:
- ``accounts`` — the accounts the scope shows (``/api/accounts``' rows, with
the live plan's windows and tier), in that order, plus ``subscription``:
the plan, monthly price and start date set in Settings → Logins (the
owner's ui-state, ``settings.accounts``) when one is;
- ``limits`` — ``/api/usage/limits``' entry per shown account;
- ``history`` / ``plans`` / ``calibration`` — ``/api/usage/history`` (``days``),
``/api/usage/plans`` and ``/api/usage/calibration`` per shown account;
- ``profiles`` — the scope switch's segments.
Which accounts a scope shows mirrors the old page (``scopeIds``): ``all`` =
every account, a ``profile:<id>`` = that profile's ★ seats; the Guests
profile = the default profile's seats (what guests' lab runs bill). Accounts
with neither a /usage source nor a reading (OpenRouter, the EVOX2) are left
out: they have no plan to show.
"""
from __future__ import annotations
import json
import re
from typing import Any
SCOPE_RE = re.compile(r"(all|profile:[a-z0-9_-]{1,40})?")
SETTINGS_KEY = "ai-agent-settings"
# Settings → Logins' defaults (frontend/src/settings.ts DEFAULT_ACCOUNT_SETTINGS),
# for an owner who never saved the page.
DEFAULT_SUBSCRIPTIONS = {
"personal": {"plan": "none", "monthlyCost": 0, "startDate": ""},
"work": {"plan": "team", "monthlyCost": 200, "startDate": "2026-09-01"},
"chatgpt-work": {"plan": "enterprise", "monthlyCost": 125, "startDate": "2026-10-18"},
"google-personal": {"plan": "pro", "monthlyCost": 20, "startDate": "2026-11-22"},
}
def _subscriptions(deps) -> dict[str, dict]:
out = {k: dict(v) for k, v in DEFAULT_SUBSCRIPTIONS.items()}
try:
blob = json.loads(deps.ui_state.get(SETTINGS_KEY) or "null")
except (TypeError, ValueError, AttributeError):
blob = None
saved = ((blob or {}).get("state") or {}).get("accounts") if isinstance(blob, dict) else None
if isinstance(saved, dict):
for acct, a in saved.items():
if not isinstance(a, dict):
continue
row = out.setdefault(str(acct), {"plan": "none", "monthlyCost": 0, "startDate": ""})
if isinstance(a.get("plan"), str):
row["plan"] = a["plan"]
if isinstance(a.get("monthlyCost"), (int, float)):
row["monthlyCost"] = float(a["monthlyCost"])
if isinstance(a.get("startDate"), str):
row["startDate"] = a["startDate"]
return out
def scope_accounts(deps, scope: str) -> list[str]:
"""The account ids a scope shows, in ``/api/accounts`` order."""
import accounts as accounts_mod
from usage import service
order = [a["id"] for a in accounts_mod.public() if not service.guest(a["id"])]
scope = (scope or "").strip().lower()
if not SCOPE_RE.fullmatch(scope) or not scope:
scope = f"profile:{deps.profile_store.default()['id']}"
if scope == "all":
wanted = set(order)
else:
pid = scope.split(":", 1)[1]
prof = next((p for p in deps.profile_store.list() if p["id"] == pid), None)
if prof is None or prof.get("kind") == "guests":
prof = deps.profile_store.default()
wanted = set(deps.profile_store.stars(prof))
metered = set(service.metered(deps)) | set(deps.usage_poller.limits())
return [a for a in order if a in wanted and a in metered]
def overview(deps, scope: str = "", days: int = 14) -> dict[str, Any]:
"""The ``hub/usage/overview`` answer (module docstring). Owner only."""
import accounts as accounts_mod
from plugins.footprintdata import profiles
from usage import calibrate, plans
from usage.routes import usage_limits
days = max(1, min(int(days), 120))
shown = scope_accounts(deps, scope)
subs = _subscriptions(deps)
class _Owner: # usage_limits' own owner check
is_owner = True
all_limits = usage_limits(deps, _Owner()).get("accounts") or {}
rows = {a["id"]: a for a in accounts_mod.public()}
out_accounts, limits, history, plan_hist, cal_hist = [], {}, {}, {}, {}
for acct in shown:
row = dict(rows.get(acct) or {"id": acct, "label": acct})
seg = plans.public(plans.current(deps.usage_store, acct))
if seg:
row["planWindows"] = seg["windows"] or row.get("planWindows")
row["planLabel"] = seg["label"] if seg["tier"] else None
row["planTier"] = seg["tier"]
sub = subs.get(acct)
row["subscription"] = sub if sub and sub.get("plan") != "none" and sub.get("startDate") else None
out_accounts.append(row)
limits[acct] = all_limits.get(acct)
history[acct] = calibrate.history(deps, acct, days)
ph = plans.history(deps.usage_store, acct)
plan_hist[acct] = {"account": acct, "current": ph[-1] if ph else None, "history": ph}
cal_hist[acct] = {"account": acct, "current": calibrate.current(deps, acct),
"history": deps.usage_store.calibrations(acct)}
return {
"scope": scope or None,
"days": days,
"accounts": out_accounts,
"limits": limits,
"history": history,
"plans": plan_hist,
"calibration": cal_hist,
"profiles": profiles(deps),
}
def calibrate_now(deps, backfill: bool = False) -> dict[str, Any]:
"""``POST /api/usage/calibrate``'s work: fit every metered account now
(``backfill``: the weekly fits over the whole history first)."""
from usage import calibrate, service
if backfill:
for acct in service.metered(deps):
calibrate.backfill(deps, acct)
cals, shifted = service.calibrate_all(deps)
deps.hub.publish({"type": "usage"})
return {"calibrations": cals, "shifted": shifted}