Files
ai-agent/backend/test_guest_usage.py
gabrielvidalandClaude Opus 5.5 604bc1dee6 feat(usage): usage widgets follow the picked model's provider; Fable weekly limit
- sidecar: read the lab's own Claude logins through /api/oauth/usage too
  (oauth-usage.json beside the status line's file) and keep the reply's
  weekly_scoped limits as seven_day_<model> (Fable)
- hub: take only the per-model windows from that read and merge them per
  window with the status line's snapshot; alert label 'Fable weekly'
- home usage strip follows the composer's pick (lib/composerPick): Claude ->
  week + Fable week (no empty 5-hour tile), Gemini -> agy 5h + week
- composer rings: Fable week ring while a Fable model is picked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 11:05:08 +01:00

112 lines
5.0 KiB
Python

"""A guest's own Claude login's /usage % (sidecar/claude_usage.py → the
usage poller): pulled from the host sidecar, served to that guest alone
(``/api/me/usage``), shown to the owner as a reading only, and never
calibrated or tracked as one of the owner's plans.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import time
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", "USAGE_STATE_DIRS": "",
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "claude.example.test",
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
import runs.sidecar_client as sidecar_client # noqa: E402
from core.routes import _GUEST_PASS # noqa: E402
from usage import service # noqa: E402
from users.caller import SESSION_COOKIE # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
def body(week: float, h5: float | None = None, at: float | None = None) -> dict:
rl = {"seven_day": {"used_percentage": week, "resets_at": time.time() + 86400}}
if h5 is not None:
rl["five_hour"] = {"used_percentage": h5, "resets_at": time.time() + 3600}
return {"updated_at": at or time.time(), "rate_limits": rl}
class GuestUsage(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={})
self.claire = DEPS.users.create("claire@example.com", "Claire", projects={})
DEPS.users.set_claude("dom", {"account": "guest-dom", "email": "d@x.test",
"connectedAt": "2026-11-07T10:00:00Z"})
served = {"/claude/usage": {"accounts": {
"guest-dom": body(49, 7), "guest-claire": body(12),
"personal": body(99)}}} # a lab login: only its per-model windows
orig = sidecar_client._sidecar_get
sidecar_client._sidecar_get = lambda path, timeout=25: served.get(path)
self.addCleanup(setattr, sidecar_client, "_sidecar_get", orig)
poller = DEPS.usage_poller
self.addCleanup(setattr, poller, "dirs", poller.dirs)
poller.dirs = {}
poller._remote.clear()
poller.latest.clear()
poller._last.clear()
poller.poll_once()
def guest(self, uid="dom"):
c = TestClient(main.app, base_url="https://claude.example.test")
c.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(uid))
return c
def test_the_sidecar_readings_are_recorded(self):
self.assertEqual(set(DEPS.usage_poller.accounts()), {"guest-dom", "guest-claire"})
self.assertEqual(DEPS.usage_store.last_point("guest-dom", "seven_day")[1], 49)
# theirs, not the owner's plans
self.assertEqual(service.metered(DEPS), [])
def test_a_guest_reads_their_own_only(self):
r = self.guest().get("/api/me/usage")
self.assertEqual(r.status_code, 200, r.text)
accts = r.json()["accounts"]
self.assertEqual(list(accts), ["guest-dom"])
w = accts["guest-dom"]["windows"]
self.assertEqual((w["seven_day"]["pct"], w["five_hour"]["pct"]), (49, 7))
self.assertFalse(accts["guest-dom"]["stale"])
# a reading on disk but no login connected in the app: nothing
self.assertEqual(self.guest("claire").get("/api/me/usage").json(), {"accounts": {}})
# the owner's route stays the owner's, and the owner has no "me" usage
self.assertEqual(self.guest().get("/api/usage/limits").status_code, 403)
self.assertEqual(TestClient(main.app).get("/api/me/usage", headers=OWNER_H)
.status_code, 404)
def test_the_owner_sees_the_reading_alone(self):
r = TestClient(main.app).get("/api/usage/limits", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
row = r.json()["accounts"]["guest-dom"]
self.assertEqual(row["windows"]["seven_day"]["pct"], 49)
self.assertEqual(row["label"], "dom (own Claude)")
self.assertNotIn("calibration", row)
self.assertNotIn("plan", row)
def test_guests_hear_the_usage_ping(self):
self.assertIn("usage", _GUEST_PASS)
if __name__ == "__main__":
unittest.main()