Files
gabrielvidalandClaude Opus 5.5 2a3f1924f4 feat(plugins): batch 1 platform hooks for the next seven plugin extractions
Shared hooks for templates, memories, desk-phone, activity, project-env,
ship and blue-green-deploy, with no legacy module removed:

- manifest: owner-only templates.read / memories.read / projects.env /
  activity.read / ship.run (one _OPERATOR_CAPS set); provides
  memories.index, notify.audio, app.banner
- runner: AIA_TEMPLATES_DIR / AIA_MEMORIES_DIR / AIA_PROJECTS_DIR for the
  owner's runs; requester_context() carries sessionId for runAs: owner
- /api/plugins (+ ui): active provides keys (no app.banner for guests)
- hub/conversations: memories=1 (memoriesRead, model), memory=<slug>
- hub/activity (plugins/activitydata.py now holds the rollup;
  dashboards/activity.py is a shim; dashboards/timebins.py helpers)
- /api/usage/daily (owner, lab.read); Home's usage card reads it
- memories_bridge.py (plans_bridge twin), Graph prefers it
- banner.py + /api/app-banner + StatusBanner.tsx; webhook/action of the
  provider invalidates and publishes SSE banner; is_maintenance pauses
  guest-job delivery
- hubbridge: inline scaffold template list; ship/deploy, ship/audit,
  ship/scan bridges
- project.detail slot on Project.tsx; aiAgentPlugin.copy(text)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 10:14:14 +01:00

196 lines
9.6 KiB
Python

"""A guest's own dashboard (``GET /api/me/stats``, and the owner's view of it
on ``/api/users/{id}/stats``): their conversations only, over a period.
Money and counts come from the memoized conversation cards (a card's ``cost``
already carries its subagents), the time Claude worked from the summaries'
``activeBins`` — the 5-minute bins each run produced a turn in, subagents
included — so nothing here re-reads a transcript.
Attribution follows :func:`users.runs.activity_of`: a conversation's whole
cost lands on the day it last ran, ``usd`` on the owner's account and
``ownUsd`` on the guest's own Claude login (an estimate). Days are the
caller's local days (``tz_offset``, minutes east of UTC), like the activity
dashboard's.
The footprint (carbon, water, energy) is estimated client-side by
``lib/footprint.ts``, which is linear in tokens per model family: the rollup
hands it each conversation's tokens summed under the model it is attributed
to — the busiest one, as ``convFootprint`` does — plus the EVOX2's measured
Wh, so the page's total is the sum of the per-conversation estimates.
"""
from __future__ import annotations
import datetime
import accounts as accounts_mod
from conversations import BIN_MINUTES
from dashboards.timebins import _local_date, _local_day_and_slot
#: The periods the page offers; 0 = everything since their first conversation.
PERIODS = (7, 30, 0)
#: An all-time daily series stops a year back — the bars would be hairlines.
MAX_DAYS = 366
def _mine(meta: dict, uid: str, shared: bool) -> bool:
return meta.get("owner") == uid or (shared and uid in (meta.get("participants") or ()))
def _r(x: float) -> float:
return round(x, 4)
_TOKENS = ("input", "output", "cacheRead", "cacheWriteTokens")
def _footprint_usage(c: dict) -> tuple[str | None, dict | None]:
"""``(model, tokens)`` the footprint estimate takes for one card — the
mirror of ``convFootprint`` (``lib/costAnalysis.ts``): on a run through
the EVOX2 only the Claude models' tokens are estimated (the box's share is
measured), attributed to the first of them; otherwise every model's,
attributed to the busiest."""
local = bool(c.get("local"))
per = [(mid, (mu or {}).get("usage")) for mid, mu in (c.get("byModel") or {}).items()]
per = [(mid, u) for mid, u in per if u and (not local or "claude" in mid)]
if not per:
return None, None
model = per[0][0] if local else ((c.get("models") or [None])[0] or c.get("model") or per[0][0])
return model, {k: sum(int(u.get(k) or 0) for _, u in per) for k in _TOKENS}
def stats_of(cards: list[dict], summaries: list[tuple[str, dict]], uid: str, *,
days: int = 30, tz_offset: int = 0, project_of=None, shared: bool = False,
now: datetime.datetime | None = None) -> dict:
"""``days`` = the period (0 = all time); ``project_of(card)`` names the
project a conversation ran in, else the card's first; ``shared`` also
counts the conversations they were invited into."""
now = now or datetime.datetime.now(datetime.timezone.utc)
off_ms = int(tz_offset) * 60 * 1000
today = _local_date(now.isoformat(), off_ms)
mine = [c for c in cards if _mine(c.get("meta") or {}, uid, shared)]
sids = {c.get("sessionId") for c in mine if c.get("sessionId")}
# ── the period's first local day ────────────────────────────────────────
first_seen = min((d for c in mine
if (d := _local_date(c.get("startedAt") or c.get("endedAt"), off_ms))),
default=today)
span = days if days > 0 else (datetime.date.fromisoformat(today)
- datetime.date.fromisoformat(first_seen)).days + 1
span = max(1, min(span, MAX_DAYS))
start = (datetime.date.fromisoformat(today) - datetime.timedelta(days=span - 1)).isoformat()
daily = {d: {"date": d, "usd": 0.0, "ownUsd": 0.0, "conversations": 0, "activeMinutes": 0}
for d in ((datetime.date.fromisoformat(start) + datetime.timedelta(days=i)).isoformat()
for i in range(span))}
# ── money, conversations, projects, models — from the cards ─────────────
month = now.strftime("%Y-%m-01")
week = (now - datetime.timedelta(days=7)).strftime("%Y-%m-%dT%H:%M:%S")
totals = {"usd": 0.0, "ownUsd": 0.0, "conversations": 0}
month_spend = {"usd": 0.0, "ownUsd": 0.0}
by_project: dict[str, dict] = {}
by_model: dict[str, dict] = {}
fp_tokens: dict[str, dict] = {}
local_wh = 0.0
project_by_sid: dict[str, str] = {}
this_week = 0
for c in mine:
meta = c.get("meta") or {}
own = accounts_mod.guest_of(meta.get("account")) == uid
key = "ownUsd" if own else "usd"
cost = float(c.get("cost") or 0)
at = c.get("endedAt") or c.get("startedAt") or ""
project = ((project_of(c) if project_of else None)
or (meta.get("projects") or [None])[0])
project_by_sid[c.get("sessionId")] = project or ""
if (c.get("startedAt") or "") >= week:
this_week += 1
if at >= month:
month_spend[key] += cost
day = daily.get(_local_date(at, off_ms) or "")
if day is None:
continue
day[key] += cost
totals[key] += cost
totals["conversations"] += 1
if (d := daily.get(_local_date(c.get("startedAt"), off_ms) or "")) is not None:
d["conversations"] += 1
p = by_project.setdefault(project or "", {
"project": project, "usd": 0.0, "ownUsd": 0.0, "conversations": 0,
"activeMinutes": 0})
p[key] += cost
p["conversations"] += 1
for mid, mu in (c.get("byModel") or {}).items():
m = by_model.setdefault(mid, {"model": mid, "conversations": 0,
"usd": 0.0, "activeMinutes": 0})
m["usd"] += float((mu or {}).get("cost") or 0)
m["conversations"] += 1
fp_model, tokens = _footprint_usage(c)
if fp_model:
row = fp_tokens.setdefault(fp_model, {"model": fp_model, **dict.fromkeys(_TOKENS, 0)})
for k in _TOKENS:
row[k] += tokens[k]
local_wh += float((c.get("local") or {}).get("wh") or 0)
# ── the time Claude worked — from the summaries' active bins ───────────
# Distinct bins per day / project / model: two runs (or a run and its
# subagent) sharing a 5-minute slot are still five minutes of clock.
day_bins: dict[str, set[int]] = {}
proj_bins: dict[str, set[int]] = {}
model_bins: dict[str, set[int]] = {}
calendar: dict[str, dict] = {}
for _path, s in summaries:
sid = s.get("sessionId")
if sid not in sids or not s.get("messages"):
continue
if not s.get("isSidechain"):
if d := _local_date(s.get("startedAt") or s.get("endedAt"), off_ms):
calendar.setdefault(d, {"date": d, "conversations": 0, "activeMinutes": 0})
calendar[d]["conversations"] += 1
for mid, bins in (s.get("activeBins") or {}).items():
for b in bins:
d, _slot = _local_day_and_slot(b, off_ms)
day_bins.setdefault(d, set()).add(b)
if d in daily:
proj_bins.setdefault(project_by_sid.get(sid, ""), set()).add(b)
model_bins.setdefault(mid, set()).add(b)
for d, bins in day_bins.items():
minutes = len(bins) * BIN_MINUTES
calendar.setdefault(d, {"date": d, "conversations": 0, "activeMinutes": 0})
calendar[d]["activeMinutes"] = minutes
if d in daily:
daily[d]["activeMinutes"] = minutes
for key, bins in proj_bins.items():
if key in by_project:
by_project[key]["activeMinutes"] = len(bins) * BIN_MINUTES
for mid, bins in model_bins.items():
by_model.setdefault(mid, {"model": mid, "conversations": 0, "usd": 0.0,
"activeMinutes": 0})["activeMinutes"] = len(bins) * BIN_MINUTES
# ── shape ───────────────────────────────────────────────────────────────
day_list = list(daily.values())
for row in (*day_list, *by_project.values(), *by_model.values()):
for k in ("usd", "ownUsd"):
if k in row:
row[k] = _r(row[k])
return {
"period": {"days": days if days > 0 else 0, "start": start, "end": today},
"tzOffset": int(tz_offset),
"totals": {
"usd": _r(totals["usd"]), "ownUsd": _r(totals["ownUsd"]),
"conversations": totals["conversations"],
"activeMinutes": sum(d["activeMinutes"] for d in day_list),
"activeDays": sum(1 for d in day_list if d["activeMinutes"] or d["conversations"]),
},
"month": {"usd": _r(month_spend["usd"]), "ownUsd": _r(month_spend["ownUsd"])},
"conversations": len(mine),
"conversationsThisWeek": this_week,
"firstDay": first_seen if mine else None,
"daily": day_list,
"calendar": sorted(calendar.values(), key=lambda d: d["date"]),
"byProject": sorted(by_project.values(), key=lambda p: -(p["usd"] + p["ownUsd"])),
"byModel": sorted(by_model.values(),
key=lambda m: (-m["activeMinutes"], -m["usd"], m["model"])),
"footprint": {"tokens": sorted(fp_tokens.values(), key=lambda t: t["model"]),
"localWh": round(local_wh, 3)},
}