Files
ai-agent/backend/test_plugin_usage_bridge.py
gabrielvidalandClaude Opus 5.5 acda5ecc30 refactor: retire core leftovers the plugins replaced
- 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>
2026-11-27 11:53:15 +01:00

177 lines
8.1 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/plans", "/api/usage/calibrate",
"/api/usage/burn"):
self.assertIn(p, paths)
# the plan-usage plugin reads history / calibration through its bridge
for p in ("/api/usage/history", "/api/usage/calibration"):
self.assertNotIn(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()