Manifest: four new slot places (home.section, conversation.pinned, conversation.threadFooter, conversation.gizmos); optional ui.slots[] keys label / defaultStashed / vis / events and ui.toolCards[] match.hasField / vis / events, written only when set (approval fingerprints unchanged); provides "home.tiles". Backend: plugins/home_tiles.py + GET /api/plugins/home-tiles (app.read, sanitized arc/burn/stat/sparkline/bar tiles, 5 s cache dropped on plugin mutations); hub bridges hub/usage/home (usage.read) and hub/activity/daily (activity.read); limits/burn payloads factored out of usage/routes.py; HomeTilesResponse schema + regenerated openapi/orval. Frontend: PluginSandboxFrame gains a live update channel (no reload, replayed to late onUpdate), setEmpty / resize(h, w), forwarded SSE events (lib/sseTap) and host RPCs scrollTo / openMediaViewer / openPreview / mediaUrl (host-side fetch → blob URL). PluginSlots: usePluginSlots, SinglePluginSlot (zero-layout empty state, stays mounted), vis gating. Tool cards: hasField, vis, rich init + live update; a call an inThread plugin card claims makes the core widget stand down. Visibility popover: dynamic plugin:<pid>:<key> switches under "Plugins". Details drawer: one HoldEditable card per conversation.details slot with the compact live snapshot, DETAIL_CARD_RENAMES onto the plugin keys and claimed core cards hidden. Home: plugin tiles merged into the usage strip by id, home.section slots. Conversation: pinned / threadFooter / gizmos slots (core PinnedMovies / GenProgressStrip / DeployGizmo yield when claimed), thread bridge + conversation contexts, app-level PluginHostBridges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
245 lines
9.7 KiB
Python
245 lines
9.7 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/daily", responses=_r(schemas.DailyUsageResponse))
|
||
@_json_in_worker
|
||
def usage_daily(deps: State, caller: CallerDep, days: int = 7, tzOffset: int = 0,
|
||
account: str = ""):
|
||
"""The last ``days`` (1–90) local days: ``{date, cost, tokens,
|
||
conversations}`` each, in the ``?account=`` profile scope — the slim twin
|
||
of the Activity rollup's ``days`` (``plugins/activitydata.py``) for Home's
|
||
usage card. Owner only."""
|
||
_owner(caller)
|
||
return daily_usage(deps, days, tzOffset, account or None)
|
||
|
||
|
||
@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/history", responses=_r(schemas.UsageHistory))
|
||
@_json_in_worker
|
||
def usage_history(deps: State, caller: CallerDep, account: str = "personal",
|
||
days: int = 14):
|
||
"""Raw % series, hourly meters and per-day observed / predicted /
|
||
untracked % for one account over the last ``days`` (≤ 120)."""
|
||
_owner(caller)
|
||
return calibrate.history(deps, _account(account), max(1, min(days, 120)))
|
||
|
||
|
||
@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}
|
||
|
||
|
||
@router.get("/api/usage/calibration", responses=_r(schemas.CalibrationHistory))
|
||
def usage_calibration(deps: State, caller: CallerDep, account: str = "personal"):
|
||
"""Every stored fit of an account (oldest first) and the one in force."""
|
||
_owner(caller)
|
||
acct = _account(account)
|
||
return {"account": acct, "current": calibrate.current(deps, acct),
|
||
"history": deps.usage_store.calibrations(acct)}
|
||
|
||
|
||
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}
|