- 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>
229 lines
8.4 KiB
Python
229 lines
8.4 KiB
Python
"""``footprint.read`` — each conversation's estimated carbon, water and energy,
|
|
for the Environment plugin (the dashboard left the core on 2026-11-25).
|
|
|
|
The estimate is ``frontend/src/lib/footprint.ts``'s, which the app still uses
|
|
for a conversation's Footprint card and a guest's Stats: per-family gCO2e per
|
|
million tokens (``claude-carbon``, fitted to Jegham et al. 2025), cache reads
|
|
at 0.08 of an input token, energy backed out at 0.287 kgCO2e/kWh, water at
|
|
3.322 L/kWh — and a local (EVOX2) run's *measured* Wh at France's mix.
|
|
``test_plugin_footprint.py`` reads the TypeScript constants and checks these
|
|
match, so the two can't drift.
|
|
|
|
Filtering is the hub's, not the page's: ``?account=`` is the dashboards'
|
|
profile scope (``ProfileStore.selector``, the server twin of the app's
|
|
``countsInScope``), ``?range=`` the range picker's keys. Owner only.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
import json
|
|
from typing import Any
|
|
|
|
# gCO2e per million tokens, per Claude family (lib/footprint.ts FACTORS).
|
|
FACTORS: dict[str, tuple[float, float]] = {
|
|
"sonnet": (39, 826),
|
|
"opus": (78, 1652),
|
|
"haiku": (20, 413),
|
|
"fable": (20, 413),
|
|
}
|
|
CACHE_READ_FACTOR = 0.08
|
|
CARBON_INTENSITY_KG_PER_KWH = 0.287
|
|
WUE_L_PER_KWH = 0.18 + 3.142
|
|
FR_GRID_KG_PER_KWH = 0.0461
|
|
OFFSITE_WUE_L_PER_KWH = 3.142
|
|
|
|
# settings.ts DEFAULT_ACCOUNT_SETTINGS' start dates — what "Since
|
|
# subscription" falls back to for an account the settings never saved.
|
|
DEFAULT_SUBSCRIPTIONS: dict[str, dict[str, str]] = {
|
|
"personal": {"plan": "none", "startDate": ""},
|
|
"work": {"plan": "team", "startDate": "2026-09-01"},
|
|
"chatgpt-work": {"plan": "enterprise", "startDate": "2026-10-18"},
|
|
"google-personal": {"plan": "pro", "startDate": "2026-11-22"},
|
|
}
|
|
|
|
RANGE_DAYS = {"24h": 1, "7d": 7, "30d": 30, "90d": 90}
|
|
RANGES = ("24h", "7d", "30d", "90d", "sub", "all")
|
|
|
|
|
|
def model_family(model: str | None) -> str:
|
|
"""lib/analytics.ts ``modelFamily``: every id that isn't Sonnet / Haiku /
|
|
Fable reads as Opus."""
|
|
m = (model or "").lower()
|
|
if "sonnet" in m:
|
|
return "sonnet"
|
|
if "haiku" in m:
|
|
return "haiku"
|
|
if "fable" in m or "mythos" in m:
|
|
return "fable"
|
|
return "opus"
|
|
|
|
|
|
def _num(v) -> float:
|
|
return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0.0
|
|
|
|
|
|
def estimate(usage: dict, family: str | None) -> dict | None:
|
|
f = FACTORS.get(family or "")
|
|
if not f:
|
|
return None
|
|
inp = _num(usage.get("input")) + _num(usage.get("cacheWriteTokens"))
|
|
cache = _num(usage.get("cacheRead")) * CACHE_READ_FACTOR
|
|
grams = ((inp + cache) * f[0] + _num(usage.get("output")) * f[1]) / 1e6
|
|
co2 = grams / 1000
|
|
kwh = co2 / CARBON_INTENSITY_KG_PER_KWH
|
|
return {"co2eKg": co2, "waterL": kwh * WUE_L_PER_KWH, "energyKwh": kwh}
|
|
|
|
|
|
def local_footprint(wh) -> dict | None:
|
|
wh = _num(wh)
|
|
if not wh:
|
|
return None
|
|
kwh = wh / 1000
|
|
return {"co2eKg": kwh * FR_GRID_KG_PER_KWH, "waterL": kwh * OFFSITE_WUE_L_PER_KWH, "energyKwh": kwh}
|
|
|
|
|
|
def _usage_by_model(c: dict) -> list[tuple[str, dict]]:
|
|
"""The per-model split when the card
|
|
has one, else the whole usage on its busiest model."""
|
|
bm = c.get("byModel") if isinstance(c.get("byModel"), dict) else {}
|
|
split = [(m, v["usage"]) for m, v in bm.items() if isinstance(v, dict) and isinstance(v.get("usage"), dict)]
|
|
if split:
|
|
return split
|
|
if isinstance(c.get("usage"), dict):
|
|
return [((c.get("models") or [None])[0] or c.get("model") or "", c["usage"])]
|
|
return []
|
|
|
|
|
|
def conv_family(c: dict) -> str:
|
|
return model_family((c.get("models") or [None])[0] or c.get("model"))
|
|
|
|
|
|
def conv_footprint(c: dict) -> dict | None:
|
|
"""One card's footprint: its Claude tokens' estimate (only the Claude
|
|
models' on a run through the EVOX2) plus the box's measured share."""
|
|
local = c.get("local") if isinstance(c.get("local"), dict) else None
|
|
per = [(m, u) for m, u in _usage_by_model(c) if local is None or "claude" in (m or "")]
|
|
wh = (local or {}).get("wh")
|
|
if not per:
|
|
return local_footprint(wh)
|
|
if local is not None:
|
|
u = {k: sum(_num(x.get(k)) for _, x in per) for k in ("input", "output", "cacheRead", "cacheWriteTokens")}
|
|
fam = model_family(per[0][0])
|
|
else:
|
|
u = c.get("usage") or {}
|
|
fam = conv_family(c)
|
|
claude = estimate(u, fam)
|
|
loc = local_footprint(wh)
|
|
if not claude or not loc:
|
|
return claude or loc
|
|
return {k: claude[k] + loc[k] for k in claude}
|
|
|
|
|
|
def _ui(deps, key: str) -> dict[str, Any]:
|
|
try:
|
|
raw = deps.ui_state.get(key)
|
|
state = (json.loads(raw) or {}).get("state") if raw else None
|
|
return state if isinstance(state, dict) else {}
|
|
except (ValueError, TypeError, AttributeError):
|
|
return {}
|
|
|
|
|
|
def subscription_start(deps, scope: str) -> str | None:
|
|
"""lib/analytics.ts ``subscriptionStart`` for a scope: the earliest start
|
|
date of the scope's seats that have a plan and a start date (the app's
|
|
Settings → Logins → Plan & cost), None when none has."""
|
|
saved = _ui(deps, "ai-agent-settings").get("accounts") or {}
|
|
accts = {k: dict(v) for k, v in DEFAULT_SUBSCRIPTIONS.items()}
|
|
for k, v in saved.items() if isinstance(saved, dict) else []:
|
|
if isinstance(v, dict):
|
|
accts[k] = {**accts.get(k, {}), **v}
|
|
s = (scope or "all").strip().lower()
|
|
if s == "all":
|
|
seats = set(accts)
|
|
elif s.startswith("profile:"):
|
|
pid = s.split(":", 1)[1]
|
|
prof = deps.profile_store.get(pid)
|
|
seats = deps.profile_store.stars(prof) if prof and pid != "guests" else set()
|
|
else:
|
|
seats = {x for x in s.split(",") if x}
|
|
starts = sorted(a.get("startDate") for k, a in accts.items()
|
|
if k in seats and a.get("plan", "none") != "none" and a.get("startDate"))
|
|
return starts[0] if starts else None
|
|
|
|
|
|
def _ts(c: dict) -> float | None:
|
|
raw = c.get("endedAt") or c.get("startedAt")
|
|
if not isinstance(raw, str) or not raw:
|
|
return None
|
|
try:
|
|
d = dt.datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
|
except ValueError:
|
|
return None
|
|
if d.tzinfo is None:
|
|
d = d.replace(tzinfo=dt.timezone.utc)
|
|
return d.timestamp()
|
|
|
|
|
|
def _cards(deps) -> list[dict]:
|
|
from plugins.graphdata import _call
|
|
from conversations.routes import conversations_list
|
|
return _call(conversations_list, deps, limit=0, archived="all", full=True)["conversations"]
|
|
|
|
|
|
def profiles(deps) -> list[dict]:
|
|
"""The scope switch's segments: every profile (the Guests one once on)."""
|
|
out = []
|
|
for p in deps.profile_store.list():
|
|
if p.get("kind") == "guests" and p.get("enabled") is False:
|
|
continue
|
|
out.append({"id": p["id"], "label": p.get("label") or p["id"],
|
|
"color": p.get("color") or "", "icon": p.get("icon") or ""})
|
|
return out
|
|
|
|
|
|
def build(deps, account: str | None = None, range_key: str | None = None,
|
|
now: float | None = None) -> dict[str, Any]:
|
|
from profiles.store import guest_owner
|
|
|
|
scope = (account or "").strip().lower() or f"profile:{deps.profile_store.default()['id']}"
|
|
rk = range_key if range_key in RANGES else "sub"
|
|
now = now if now is not None else dt.datetime.now(dt.timezone.utc).timestamp()
|
|
since: float | None = None
|
|
sub = subscription_start(deps, scope)
|
|
if rk in RANGE_DAYS:
|
|
since = now - RANGE_DAYS[rk] * 86400
|
|
elif rk == "sub" and sub:
|
|
try:
|
|
since = dt.datetime.fromisoformat(sub).replace(tzinfo=dt.timezone.utc).timestamp()
|
|
except ValueError:
|
|
since = None
|
|
sel = deps.profile_store.selector(scope)
|
|
rows = []
|
|
for c in _cards(deps):
|
|
m = c.get("meta") or {}
|
|
acct = m.get("account")
|
|
if not sel(acct, m.get("profile"), guest_owner(m, acct)):
|
|
continue
|
|
t = _ts(c)
|
|
if since is not None and (t is None or t < since):
|
|
continue
|
|
fp = conv_footprint(c)
|
|
if fp is None:
|
|
continue
|
|
rows.append({
|
|
"id": c.get("id"),
|
|
"t": int(t * 1000) if t is not None else None,
|
|
"family": conv_family(c),
|
|
"projects": [p for p in (m.get("projects") or []) if isinstance(p, str)],
|
|
**{k: round(v, 9) for k, v in fp.items()},
|
|
})
|
|
return {
|
|
"scope": scope,
|
|
"range": rk,
|
|
"since": int(since * 1000) if since is not None else None,
|
|
"subscriptionStart": sub,
|
|
"profiles": profiles(deps),
|
|
"conversations": rows,
|
|
}
|