- backend: plugins/usagedata.py + hub/usage/overview and hub/usage/calibrate (owner-only, operator-approved caps); usage/ and /api/usage/* stay core. - frontend: drop PlanUsage.tsx + planViz.tsx (ArcGauge moved to its own file for Home's strip), their hooks/fetchers, viz Columns, unused billing/planUsage helpers; /dashboards/plan redirects to /plugins/plan-usage/board (else /dashboards); nav/drawer/telemetry entries updated. - docs: plugins.md, usage-calibration.md, CLAUDE.md; openapi + orval regenerated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
174 lines
8.0 KiB
Python
174 lines
8.0 KiB
Python
"""``usage.read`` / ``usage.calibrate`` (2026-11-26) — the plan-usage
|
|
plugin's bridges (``plugins/usagedata.py``): operator-only, owner-only, the
|
|
scope → accounts rule, the overview's shape, and that the core Plan usage
|
|
page is gone while ``/api/usage/*`` stays."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from types import SimpleNamespace
|
|
from unittest.mock import patch
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "INTERNAL_API_TOKEN": "tok",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import usagedata # noqa: E402
|
|
from plugins.manifest import capability_summary, requires_operator, validate_manifest # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
|
|
MF = {"schema": 1, "id": "pu", "name": "Plan usage", "capabilities": ["usage.read", "usage.calibrate"]}
|
|
|
|
|
|
def _install(td, manifest) -> PluginStore:
|
|
src = pathlib.Path(td) / "src"
|
|
src.mkdir(parents=True, exist_ok=True)
|
|
(src / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
|
|
return store
|
|
|
|
|
|
def _owner_h(pid="pu"):
|
|
return {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, pid, ttl=600)}"}
|
|
|
|
|
|
class Caps(unittest.TestCase):
|
|
def test_operator_only_and_labelled(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
for cap in ("usage.read", "usage.calibrate"):
|
|
d = pathlib.Path(td) / cap
|
|
d.mkdir()
|
|
(d / "plugin.json").write_text(json.dumps(
|
|
{"schema": 1, "id": "x", "name": "X", "capabilities": [cap]}), encoding="utf-8")
|
|
mf = validate_manifest(d)
|
|
self.assertTrue(requires_operator(mf), cap)
|
|
item = next(c for c in capability_summary(mf) if c["kind"] == "capability")
|
|
self.assertTrue(item["privileged"], cap)
|
|
self.assertNotIn("Hub capability:", item["label"], cap)
|
|
|
|
|
|
class Routes(unittest.TestCase):
|
|
def test_overview_owner_only_days_clamped(self):
|
|
deps = main.app.state.ai
|
|
tc = TestClient(main.app)
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = _install(td, MF)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch("plugins.usagedata.overview", return_value={"accounts": []}) as ov:
|
|
r = tc.get("/proxy/tools/plugins/pu/hub/usage/overview?scope=profile:work&days=999",
|
|
headers=_owner_h())
|
|
g = tc.get("/proxy/tools/plugins/pu/hub/usage/overview",
|
|
headers={"Authorization": f"Bearer {access.mint('cel', ttl=600)}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(ov.call_args.args[1:], ("profile:work", 120))
|
|
self.assertEqual(g.status_code, 403)
|
|
|
|
def test_calibrate_needs_its_own_capability(self):
|
|
deps = main.app.state.ai
|
|
tc = TestClient(main.app)
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = _install(td, MF)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch("plugins.usagedata.calibrate_now",
|
|
return_value={"calibrations": {}, "shifted": []}) as cal:
|
|
r = tc.post("/proxy/tools/plugins/pu/hub/usage/calibrate", json={"backfill": True},
|
|
headers=_owner_h())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"calibrations": {}, "shifted": []})
|
|
self.assertEqual(cal.call_args.args[1:], (True,))
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = _install(td, {**MF, "id": "ro", "capabilities": ["usage.read"]})
|
|
with patch.object(deps, "plugin_store", store):
|
|
r = tc.post("/proxy/tools/plugins/ro/hub/usage/calibrate", json={}, headers=_owner_h("ro"))
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_core_page_gone_api_kept(self):
|
|
paths = set(main.app.openapi()["paths"])
|
|
for p in ("/api/usage/limits", "/api/usage/history", "/api/usage/plans",
|
|
"/api/usage/calibration", "/api/usage/calibrate", "/api/usage/burn"):
|
|
self.assertIn(p, paths)
|
|
front = pathlib.Path(__file__).resolve().parent.parent / "frontend" / "src" / "business" / "dashboards"
|
|
if front.is_dir():
|
|
self.assertFalse((front / "pages" / "PlanUsage.tsx").exists())
|
|
self.assertFalse((front / "components" / "planViz.tsx").exists())
|
|
|
|
|
|
class _Profiles:
|
|
def __init__(self, profiles):
|
|
self._p = profiles
|
|
|
|
def list(self):
|
|
return self._p
|
|
|
|
def default(self):
|
|
return self._p[0]
|
|
|
|
def stars(self, p):
|
|
return set((p.get("accounts") or {}).values())
|
|
|
|
|
|
class Scope(unittest.TestCase):
|
|
PROFILES = [
|
|
{"id": "personal", "accounts": {"claude": "personal"}},
|
|
{"id": "work", "accounts": {"claude": "work", "opencode": "chatgpt-work"}},
|
|
{"id": "guests", "kind": "guests"},
|
|
]
|
|
PUBLIC = [{"id": i} for i in ("personal", "work", "chatgpt-work", "openrouter", "guest-cel")]
|
|
|
|
def _deps(self):
|
|
poller = SimpleNamespace(accounts=lambda: ["personal", "work", "chatgpt-work", "guest-cel"],
|
|
limits=lambda: {})
|
|
return SimpleNamespace(profile_store=_Profiles(self.PROFILES), usage_poller=poller)
|
|
|
|
def test_scopes(self):
|
|
deps = self._deps()
|
|
with patch("accounts.public", return_value=self.PUBLIC):
|
|
self.assertEqual(usagedata.scope_accounts(deps, "all"), ["personal", "work", "chatgpt-work"])
|
|
self.assertEqual(usagedata.scope_accounts(deps, "profile:work"), ["work", "chatgpt-work"])
|
|
self.assertEqual(usagedata.scope_accounts(deps, ""), ["personal"])
|
|
self.assertEqual(usagedata.scope_accounts(deps, "profile:guests"), ["personal"])
|
|
self.assertEqual(usagedata.scope_accounts(deps, "bad scope!"), ["personal"])
|
|
self.assertEqual(usagedata.scope_accounts(deps, "profile:nope"), ["personal"])
|
|
|
|
def test_subscriptions_merge_the_saved_settings(self):
|
|
blob = json.dumps({"state": {"accounts": {"personal": {"plan": "max20", "monthlyCost": 200,
|
|
"startDate": "2026-09-01"},
|
|
"work": "junk"}}})
|
|
deps = SimpleNamespace(ui_state=SimpleNamespace(get=lambda k: blob))
|
|
subs = usagedata._subscriptions(deps)
|
|
self.assertEqual(subs["personal"], {"plan": "max20", "monthlyCost": 200.0, "startDate": "2026-09-01"})
|
|
self.assertEqual(subs["work"]["plan"], "team")
|
|
none = usagedata._subscriptions(SimpleNamespace(ui_state=SimpleNamespace(get=lambda k: None)))
|
|
self.assertEqual(none["personal"]["plan"], "none")
|
|
|
|
|
|
class Overview(unittest.TestCase):
|
|
def test_shape_on_the_real_store(self):
|
|
deps = main.app.state.ai
|
|
with patch("plugins.usagedata.scope_accounts", return_value=["personal"]):
|
|
out = usagedata.overview(deps, "all", 7)
|
|
for k in ("accounts", "limits", "history", "plans", "calibration", "profiles", "days"):
|
|
self.assertIn(k, out)
|
|
self.assertEqual(out["days"], 7)
|
|
self.assertEqual([a["id"] for a in out["accounts"]], ["personal"])
|
|
self.assertIn("subscription", out["accounts"][0])
|
|
self.assertIn("daily", out["history"]["personal"])
|
|
self.assertEqual(out["calibration"]["personal"]["account"], "personal")
|
|
json.dumps(out) # the wire form
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|