dashboards/guest.py rolls up the conversations a guest started over a
7-day / 30-day / all-time period: this month vs their budget (their own
Claude apart), conversations, the time Claude worked (distinct 5-minute
activeBins, subagents included), a calendar of the days anything ran,
spend per day / project / model, and the tokens + EVOX2 Wh the client
turns into a carbon / water / energy footprint. From the memoized cards
and the summaries, never a transcript.
GET /api/me/stats is a guest route (404 for the owner); the owner reads
the same payload for any guest on /api/users/{id}/stats.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
8.3 KiB
Python
179 lines
8.3 KiB
Python
"""A guest's own dashboard (dashboards/guest.py): the period, the money split,
|
|
the active time from the summaries' bins, and who may read it.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import datetime
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects" / "film").mkdir(parents=True)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from conversations import BIN_MINUTES # noqa: E402
|
|
from dashboards.guest import stats_of # noqa: E402
|
|
from users.caller import SESSION_COOKIE # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
NOW = datetime.datetime(2026, 10, 20, 12, 0, tzinfo=datetime.timezone.utc)
|
|
BIN_MS = BIN_MINUTES * 60 * 1000
|
|
|
|
|
|
def iso(days_ago: float) -> str:
|
|
return (NOW - datetime.timedelta(days=days_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
def bin_at(days_ago: float, plus: int = 0) -> int:
|
|
return int((NOW - datetime.timedelta(days=days_ago)).timestamp() * 1000) // BIN_MS + plus
|
|
|
|
|
|
def card(sid, at, cost=1.0, **meta):
|
|
return {"id": f"p/{sid}.jsonl", "sessionId": sid, "title": sid, "cost": cost,
|
|
"startedAt": at, "endedAt": at,
|
|
"byModel": {"claude-sonnet-5-5": {"cost": cost}},
|
|
"meta": {"owner": "dom", **meta}}
|
|
|
|
|
|
def summary(sid, at, bins, sidechain=False, model="claude-sonnet-5-5"):
|
|
return (f"p/{sid}{'-sub' if sidechain else ''}.jsonl",
|
|
{"sessionId": sid, "messages": 3, "startedAt": at, "isSidechain": sidechain,
|
|
"activeBins": {model: bins}})
|
|
|
|
|
|
CARDS = [
|
|
card("a", iso(0), projects=["film"]),
|
|
card("b", iso(2), cost=2.0, account="guest-dom", projects=["film"]),
|
|
card("c", iso(20), cost=4.0),
|
|
card("d", iso(0), cost=8.0, owner="claire"),
|
|
card("e", iso(1), cost=16.0, owner="claire", participants=["dom"]),
|
|
]
|
|
SUMMARIES = [
|
|
summary("a", iso(0), [bin_at(0), bin_at(0, 1)]),
|
|
# a subagent sharing a slot with its parent: still one slot of clock
|
|
summary("a", iso(0), [bin_at(0, 1), bin_at(0, 2)], sidechain=True, model="claude-haiku-5-5"),
|
|
summary("b", iso(2), [bin_at(2)]),
|
|
summary("c", iso(20), [bin_at(20)]),
|
|
summary("d", iso(0), [bin_at(0, 5)]),
|
|
]
|
|
|
|
|
|
class Rollup(unittest.TestCase):
|
|
def test_week(self):
|
|
s = stats_of(CARDS, SUMMARIES, "dom", days=7, now=NOW)
|
|
self.assertEqual(s["period"], {"days": 7, "start": "2026-10-14", "end": "2026-10-20"})
|
|
self.assertEqual(len(s["daily"]), 7)
|
|
t = s["totals"]
|
|
self.assertEqual((t["usd"], t["ownUsd"], t["conversations"]), (1.0, 2.0, 2))
|
|
# a: 3 distinct slots (parent + subagent overlap), b: 1
|
|
self.assertEqual(t["activeMinutes"], 4 * BIN_MINUTES)
|
|
self.assertEqual(t["activeDays"], 2)
|
|
self.assertEqual(s["daily"][-1]["activeMinutes"], 3 * BIN_MINUTES)
|
|
self.assertEqual(s["daily"][-1]["conversations"], 1)
|
|
# the month is the budget's (UTC, from Oct 1st): c ran in September
|
|
self.assertEqual(s["month"], {"usd": 1.0, "ownUsd": 2.0})
|
|
self.assertEqual((s["conversations"], s["conversationsThisWeek"]), (3, 2))
|
|
self.assertEqual([p["project"] for p in s["byProject"]], ["film"])
|
|
self.assertEqual(s["byProject"][0]["activeMinutes"], 4 * BIN_MINUTES)
|
|
models = {m["model"]: m for m in s["byModel"]}
|
|
self.assertEqual(models["claude-sonnet-5-5"]["activeMinutes"], 3 * BIN_MINUTES)
|
|
self.assertEqual(models["claude-haiku-5-5"]["activeMinutes"], 2 * BIN_MINUTES)
|
|
self.assertEqual(models["claude-sonnet-5-5"]["usd"], 3.0)
|
|
# the calendar is all time, conversations only (the subagent isn't one)
|
|
self.assertEqual({d["date"]: d["conversations"] for d in s["calendar"]},
|
|
{"2026-09-30": 1, "2026-10-18": 1, "2026-10-20": 1})
|
|
# the footprint's input: tokens under the busiest model, the box's Wh
|
|
self.assertEqual(s["footprint"], {"tokens": [], "localWh": 0.0})
|
|
|
|
def test_footprint_tokens(self):
|
|
u = {"input": 10, "output": 5, "cacheRead": 100, "cacheWriteTokens": 1, "cacheWriteUnits": 0}
|
|
cloud = {**card("f", iso(0)), "models": ["claude-opus-5-5", "claude-haiku-5-5"],
|
|
"byModel": {"claude-haiku-5-5": {"cost": 1, "usage": u},
|
|
"claude-opus-5-5": {"cost": 1, "usage": u}}}
|
|
local = {**card("g", iso(0)), "models": ["qwen3.8-27b"], "local": {"wh": 12.5},
|
|
"byModel": {"qwen3.8-27b": {"cost": 0, "usage": u},
|
|
"claude-haiku-5-5": {"cost": 1, "usage": u}}}
|
|
s = stats_of([cloud, local], [], "dom", days=7, now=NOW)
|
|
self.assertEqual(s["footprint"], {"localWh": 12.5, "tokens": [
|
|
{"model": "claude-haiku-5-5", "input": 10, "output": 5, "cacheRead": 100, "cacheWriteTokens": 1},
|
|
{"model": "claude-opus-5-5", "input": 20, "output": 10, "cacheRead": 200, "cacheWriteTokens": 2},
|
|
]})
|
|
|
|
def test_all_time_starts_on_their_first_day(self):
|
|
s = stats_of(CARDS, SUMMARIES, "dom", days=0, now=NOW)
|
|
self.assertEqual((s["period"]["start"], len(s["daily"])), ("2026-09-30", 21))
|
|
self.assertEqual(s["totals"]["usd"], 5.0)
|
|
self.assertEqual(s["firstDay"], "2026-09-30")
|
|
|
|
def test_shared_conversations_on_request(self):
|
|
s = stats_of(CARDS, SUMMARIES, "dom", days=7, now=NOW, shared=True)
|
|
self.assertEqual(s["totals"]["usd"], 17.0)
|
|
self.assertEqual(s["conversations"], 4)
|
|
|
|
def test_local_days(self):
|
|
# 23:30 UTC on Oct 19 is Oct 20 in Paris (+120)
|
|
late = "2026-10-19T23:30:00Z"
|
|
s = stats_of([card("x", late)], [], "dom", days=7, tz_offset=120, now=NOW)
|
|
self.assertEqual(s["daily"][-1]["usd"], 1.0)
|
|
s = stats_of([card("x", late)], [], "dom", days=7, now=NOW)
|
|
self.assertEqual(s["daily"][-2]["usd"], 1.0)
|
|
|
|
def test_nothing_yet(self):
|
|
s = stats_of([], [], "dom", days=0, now=NOW)
|
|
self.assertEqual((len(s["daily"]), s["firstDay"], s["totals"]["usd"]), (1, None, 0))
|
|
|
|
|
|
class Routes(unittest.TestCase):
|
|
def setUp(self):
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
self.dom = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"})
|
|
import conversations.catalog as catalog
|
|
orig = catalog._conversation_cards
|
|
catalog._conversation_cards = lambda deps, full: CARDS
|
|
self.addCleanup(setattr, catalog, "_conversation_cards", orig)
|
|
|
|
def guest(self):
|
|
c = TestClient(main.app, base_url="https://claude.example.test")
|
|
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(self.dom["id"]))
|
|
return c
|
|
|
|
def test_guest_reads_their_own(self):
|
|
r = self.guest().get("/api/me/stats?days=0&tzOffset=60")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual((r.json()["conversations"], r.json()["tzOffset"]), (3, 60))
|
|
self.assertEqual(self.guest().get("/api/me/stats?days=12").status_code, 400)
|
|
# never someone else's: the owner's route is the owner's
|
|
self.assertEqual(self.guest().get("/api/users/dom/stats").status_code, 403)
|
|
|
|
def test_owner_reads_a_guests(self):
|
|
c = TestClient(main.app)
|
|
r = c.get("/api/users/dom/stats?days=7", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["conversations"], 3)
|
|
self.assertEqual(c.get("/api/users/nobody/stats", headers=OWNER_H).status_code, 404)
|
|
self.assertEqual(c.get("/api/me/stats", headers=OWNER_H).status_code, 404)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|