Files
gabrielvidalandClaude Opus 5.5 acda5ecc30 refactor: retire core leftovers the plugins replaced
- frontend: drop the dead Conversations dashboard code (costAnalysis,
  DashboardFilters, ConversationsDashboard), the unused analytics /
  footprint / pricing helpers, the orphan api.ts comment and the dead
  mocks (perf dashboard, storage dashboard, telemetry hub/usage,
  usage daily/history/calibration); their French strings
- backend: drop look.parse_action (the conversation-labels plugin has its
  own) and UsersStore.emails() (no caller)
- routes: drop GET /api/usage/daily|history|calibration,
  GET /api/telemetry/usage, GET /api/goals, POST /api/goal-work — the
  plugin bridges call daily_usage, calibrate.history, views.usage,
  goals_list and goal_work directly; authz table + golden matrix updated;
  openapi.json re-dumped, src/generated regenerated
- FALLBACK_ACCOUNTS: one neutral Claude seat instead of a stale copy of
  the providers' profiles (the full list moves to mock/accounts.ts)
- notify CLI: no local PRICES estimate — the line is
  "Claude Code · 78k tokens · 8m" and the hub's restate_cost puts the
  run's exact list price in (an older CLI's $ line is still restated)
- CLAUDE.md / docs / docstrings: scheduled/, templates/, sidecar
  *_usage.py, the clarifier (now the plugin's agents[] + prefs),
  runs/extras.py, sidecar/routes_chrome.py

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

214 lines
8.4 KiB
Python

"""Plan usage: live /usage %, its history, the plan each account is on and
the calibration (usage/)."""
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
import accounts as accounts_mod
import schemas
from core.http import _json_in_worker, _r
from core.state import State
from users.caller import CallerDep
from . import billing, budget, burn, calibrate, plans, service
router = APIRouter()
def _owner(caller) -> None:
if not caller.is_owner:
raise HTTPException(403, "owner only")
def _account(account: str) -> str:
if account not in accounts_mod.ids():
raise HTTPException(400, f"unknown account {account!r}")
return account
@router.get("/api/usage/limits", responses=_r(schemas.UsageLimitsResponse))
def usage_limits(deps: State, caller: CallerDep):
"""The latest /usage % per account, with the rate in force — and each
guest's own Claude login's (``guest-<uid>``, the reading only)."""
_owner(caller)
return limits_payload(deps)
def limits_payload(deps) -> dict:
"""``GET /api/usage/limits``'s body (also the ``usage.read`` bridge's
``hub/usage/home``)."""
out = {}
for acct, lim in deps.usage_poller.limits().items():
a = accounts_mod.get(acct) or {}
if service.guest(acct):
# A guest's own plan (the Guests profile's strip): the reading
# alone — no calibration or plan of the owner's to show.
out[acct] = {**lim, "label": a.get("label")}
continue
seg = plans.current(deps.usage_store, acct)
out[acct] = {**lim, "label": a.get("label"), "weekTarget": a.get("weekTarget"),
"calibration": calibrate.current(deps, acct),
"plan": plans.public(seg),
"billing": _billing(deps, acct, a, seg)}
return {"accounts": out}
def _billing(deps, acct: str, a: dict, seg: dict | None) -> dict | None:
"""The billing cycle of a Claude plan Gabriel pays for (usage/billing.py)
— not the work seat's, whose bill is Orus's."""
if a.get("excludeFromTotals") or a.get("harness", "claude") != "claude":
return None
health = getattr(deps, "account_health", None)
row = health.live_rows().get(acct) if health is not None else None
try:
return billing.billing(deps.usage_store, acct, row, seg)
except Exception:
return None
def daily_usage(deps, days: int = 7, tz_offset: int = 0, account: str | None = None) -> dict:
"""The last ``days`` local days' spend, tokens and top-level conversation
count (a run's day is the one it started on — the Activity rollup's
rule), oldest first, zero-filled. No 5-minute bins: Home's usage card."""
import datetime
from conversations.cards import _summaries_for
from dashboards.timebins import _local_date, local_today
n = max(1, min(90, int(days)))
off_ms = max(-960, min(960, int(tz_offset))) * 60 * 1000
today = datetime.date.fromisoformat(local_today(off_ms))
order = [(today - datetime.timedelta(days=n - 1 - i)).isoformat() for i in range(n)]
out = {d: {"date": d, "cost": 0.0, "tokens": 0, "conversations": 0} for d in order}
first = order[0]
for _path, s in _summaries_for(deps, account or None):
if not s.get("messages"):
continue
started = s.get("startedAt") or s.get("endedAt")
# A cheap pre-filter: ISO strings sort, and a day of offset is the most
# a local date can move.
if not started or started[:10] < (datetime.date.fromisoformat(first)
- datetime.timedelta(days=1)).isoformat():
continue
row = out.get(_local_date(started, off_ms) or "")
if row is None:
continue
row["cost"] += float(s.get("cost") or 0.0)
row["tokens"] += int(s.get("tokens") or 0)
if not s.get("isSidechain"):
row["conversations"] += 1
return {"days": [out[d] for d in order]}
@router.get("/api/usage/plans", responses=_r(schemas.PlanHistory))
def usage_plans(deps: State, caller: CallerDep, account: str = "personal"):
"""The plans (tier + limit windows) an account has been on, oldest first —
read off its login and its rate-limits.json (usage/plans.py)."""
_owner(caller)
acct = _account(account)
hist = plans.history(deps.usage_store, acct)
return {"account": acct, "current": hist[-1] if hist else None, "history": hist}
class PlanBody(BaseModel):
account: str
since: float
tier: str | None = None
# fit names (week, h5); unset = the windows of the plan in force then
windows: list[str] | None = None
# delete the segment starting at ``since`` instead
delete: bool = False
@router.post("/api/usage/plans", responses=_r(schemas.PlanHistory))
def usage_plans_edit(deps: State, caller: CallerDep, body: PlanBody):
"""Correct an account's plan history by hand: record that it went on
``tier`` at ``since`` (a past the tracker couldn't see), or ``delete`` a
segment. Refits nothing by itself — POST /api/usage/calibrate does."""
_owner(caller)
acct = _account(body.account)
if body.delete:
if not deps.usage_store.delete_plan(acct, body.since):
raise HTTPException(404, "no plan segment starts there")
else:
prev = plans.at(deps.usage_store, acct, body.since) or {}
win = plans.ordered(body.windows or prev.get("windows") or accounts_mod.plan_windows(acct))
if not win:
raise HTTPException(400, "a plan needs at least one window (week, h5)")
deps.usage_store.add_plan({"account": acct, "since": body.since,
"tier": body.tier or prev.get("tier"), "windows": win,
"source": "manual", "data": {"reason": "recorded by hand"}})
deps.hub.publish({"type": "usage"})
return usage_plans(deps, caller, acct)
@router.get("/api/usage/budget", responses=_r(schemas.UsageBudget))
@_json_in_worker
def usage_budget(deps: State, caller: CallerDep, account: str = "personal"):
"""What is left of the account's week before it resets: the free %, units,
$ and tokens per model once the crons and scheduled conversations due
before the reset are paid for, the pace, and how many nonstop runs would
use it all (usage/budget.py)."""
_owner(caller)
return budget.budget(deps, _account(account))
@router.get("/api/usage/burn", responses=_r(schemas.UsageBurnResponse))
@_json_in_worker
def usage_burn(deps: State, caller: CallerDep):
"""How fast each account with a week target spends its week right now
(the last 60 min, list $ / plan units / % per hour) against the pace that
reaches the target at the reset — the home page's burn-rate tile
(usage/burn.py)."""
_owner(caller)
return burn_payload(deps)
def burn_payload(deps) -> dict:
"""``GET /api/usage/burn``'s body (also ``hub/usage/home``)."""
out = {}
for acct in accounts_mod.ids():
if service.guest(acct):
continue
b = burn.burn(deps, acct)
if b is not None:
out[acct] = b
return {"accounts": out}
class CalibrateBody(BaseModel):
backfill: bool = False
@router.post("/api/usage/calibrate", responses=_r(schemas.CalibrateResult))
def usage_calibrate(deps: State, caller: CallerDep, body: CalibrateBody | None = None):
"""Fit every account now (``backfill``: also the weekly fits over the whole
history, for the $/% over time chart)."""
_owner(caller)
if body and body.backfill:
for acct in service.metered(deps):
calibrate.backfill(deps, acct)
cals, shifted = service.calibrate_all(deps)
return {"calibrations": cals, "shifted": shifted}
class ImportBody(BaseModel):
account: str
source: str = "ha"
# [{t, window, pct, resetsAt?}]
points: list[dict]
@router.post("/api/usage/import", responses=_r(schemas.UsageImportResult))
def usage_import(deps: State, caller: CallerDep, body: ImportBody):
"""Backfill historical % points (scripts/usage-backfill-ha.py)."""
_owner(caller)
acct = _account(body.account)
rows = [(acct, str(p["window"]), float(p["t"]), float(p["pct"]),
p.get("resetsAt"), body.source) for p in body.points
if p.get("window") and p.get("t") is not None and p.get("pct") is not None]
n = deps.usage_store.add_points(rows)
if n:
deps.hub.publish({"type": "usage"})
return {"imported": n}