Files
ai-agent/backend/test_context_skills_bridge.py
gabrielvidalandClaude Opus 5.5 2037700317 feat(plugins): retire core Context & skills dashboard into the context-skills plugin (contextcost.read bridge, /dashboards grid)
- GET /api/dashboard → owner-only contextcost.read bridge (plugins/hubcontextcost.py)
- /dashboards becomes DashboardsHome, a card grid of the dashboard plugins' pages
- one-time carry-over of the stat-card order/bench into the plugin's layout.json
- telemetry: /dashboards is dash.home; the plugin page keeps dash.overview

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:48:04 +01:00

209 lines
9.1 KiB
Python

"""The core's half of the Context & skills dashboard since it moved into the
``context-skills`` live plugin (2026-11-28): the ``contextcost.read``
capability, its owner-only bridge (``plugins/hubcontextcost.py``), the
stat-card layout carry-over (``plugins/carryover_context.py``) and the
retired ``GET /api/dashboard``."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import unittest
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", "SERVICES_DIR": TMP / "services",
"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 carryover_context, hubcontextcost # noqa: E402
from plugins.manifest import ManifestError, requires_operator, validate_manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access # noqa: E402
PID = "context-skills"
MANIFEST = {
"schema": 1, "id": PID, "name": "Context & skills",
"actions": {"overview": {"script": "handlers/overview.py", "readOnly": True}},
"capabilities": ["contextcost.read"],
"ui": {"pages": [{"id": "context", "label": "Context & skills", "nav": "dashboards",
"icon": "gauge", "html": "ui/c.html", "feature": "dash.overview"}]},
}
FILES = {
"CLAUDE.md": {"tokens": 4000, "cost": 0.012, "estimated": 0},
".claude/skills/open-pr/SKILL.md": {"tokens": 1500, "cost": 0.0045, "estimated": 0},
".claude/skills/open-pr/scripts/pr.sh": {"tokens": 500, "cost": 0.0015, "estimated": 1},
"projects/x/.claude/skills/deploy/SKILL.md": {"tokens": 1000, "cost": 0.003, "estimated": 0},
}
SKILLS = [
{"name": "open-pr", "count": 10, "last_used": "2026-11-27T10:00:00Z"},
{"name": "deploy", "count": 2, "last_used": None},
{"name": "code-review", "count": 3, "last_used": "2026-11-20T10:00:00Z"},
]
class _Store:
def all_files(self):
return {p: dict(r) for p, r in FILES.items()}
def all_skills(self):
return [dict(r) for r in SKILLS]
def _write(root: pathlib.Path, manifest: dict) -> pathlib.Path:
(root / "handlers").mkdir(parents=True, exist_ok=True)
(root / "ui").mkdir(exist_ok=True)
(root / "plugin.json").write_text(json.dumps(manifest))
(root / "handlers" / "overview.py").write_text("import sys\nsys.stdin.read()\nprint('{}')\n")
(root / "ui" / "c.html").write_text("<p>c</p>")
return root
class ManifestTest(unittest.TestCase):
def test_capability_is_known_and_operator_approved(self):
with tempfile.TemporaryDirectory() as d:
mf = validate_manifest(_write(pathlib.Path(d) / "p", MANIFEST))
self.assertEqual(mf["capabilities"], ["contextcost.read"])
self.assertTrue(requires_operator(mf))
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(d) / "q", {**MANIFEST, "capabilities": ["contextcost.write"]}))
class BuildTest(unittest.TestCase):
def test_same_figures_as_the_old_route(self):
out = hubcontextcost.build(type("D", (), {"store": _Store()})())
t = out["totals"]
self.assertEqual((t["files"], t["tokens"], t["estimated"], t["skills"], t["invocations"]),
(4, 7000, 1, 3, 15))
self.assertAlmostEqual(t["cost"], 0.021)
by = {s["name"]: s for s in out["skills"]}
# a repo skill: its whole dir is its context; SKILL.md is linkable
self.assertEqual(by["open-pr"]["contextTokens"], 2000)
self.assertAlmostEqual(by["open-pr"]["estSpend"], 0.06)
self.assertEqual(by["open-pr"]["path"], ".claude/skills/open-pr/SKILL.md")
# a project's skill counts its context, but the repo-root link doesn't exist
self.assertEqual(by["deploy"]["contextTokens"], 1000)
self.assertIsNone(by["deploy"]["path"])
# a built-in skill: no file, no context cost
self.assertIsNone(by["code-review"]["contextCost"])
self.assertIsNone(by["code-review"]["estSpend"])
self.assertAlmostEqual(t["skillSpend"], 0.066)
self.assertEqual(out["topFiles"][0]["path"], "CLAUDE.md")
self.assertTrue(next(f for f in out["topFiles"] if f["path"].endswith("pr.sh"))["estimated"])
self.assertEqual(set(out["pricing"]), {"model", "inputPerMTok"})
class BridgeTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.tmp.name)
self.store = PluginStore(self.root / "data")
self.store.install(OWNER_UID, str(_write(self.root / "plugin", MANIFEST)), is_owner=True, approve=True)
self.deps = main.app.state.ai
self.tc = TestClient(main.app)
self.patches = [patch.object(self.deps, "plugin_store", self.store),
patch.object(self.deps, "store", _Store())]
for p in self.patches:
p.start()
def tearDown(self):
for p in self.patches:
p.stop()
self.tmp.cleanup()
def _get(self, uid=OWNER_UID, pid=PID):
return self.tc.get(f"/proxy/tools/plugins/{pid}/hub/context-cost",
headers={"Authorization": f"Bearer {access.mint_handler(uid, pid, ttl=600)}"})
def test_owner_gets_the_figures(self):
r = self._get()
self.assertEqual(r.status_code, 200, r.text)
body = r.json()
self.assertEqual(body["totals"]["skills"], 3)
self.assertEqual(len(body["topFiles"]), 4)
def test_a_guest_gets_nothing(self):
r = self._get("dom")
self.assertEqual(r.status_code, 403, r.text)
self.assertNotIn("totals", r.text)
self.assertIn("owner-only", r.text)
def test_needs_the_capability(self):
store = PluginStore(self.root / "data2")
store.install(OWNER_UID, str(_write(self.root / "p2", {**MANIFEST, "capabilities": []})),
is_owner=True, approve=True)
with patch.object(self.deps, "plugin_store", store):
r = self._get()
self.assertEqual(r.status_code, 403)
self.assertIn("contextcost.read", r.text)
def test_disabled_plugin_is_refused(self):
self.store.update(OWNER_UID, PID, enabled=False)
self.assertNotEqual(self._get().status_code, 200)
def test_no_token_no_figures(self):
r = self.tc.get(f"/proxy/tools/plugins/{PID}/hub/context-cost")
self.assertIn(r.status_code, (401, 403))
def test_old_route_is_gone(self):
paths = set(main.app.openapi()["paths"])
self.assertNotIn("/api/dashboard", paths)
self.assertIn("/proxy/tools/plugins/{pid}/hub/context-cost", paths)
# the skills catalog that shares _context_by_skill still answers
self.assertIn("/api/skills", paths)
class CarryOverTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.store = PluginStore(pathlib.Path(self.tmp.name) / "data")
def tearDown(self):
self.tmp.cleanup()
def _blob(self, orders=None, stashes=None):
return {"ai-agent-settings": json.dumps({"state": {"listOrders": orders or {},
"listStashes": stashes or {}}, "version": 7})}
def _layout(self):
p = self.store.user_data_dir(OWNER_UID, PID) / "layout.json"
return json.loads(p.read_text()) if p.exists() else None
def test_carries_order_and_bench_once(self):
ui = self._blob({"dashboard-stats": ["skills", "cost", "bogus", "skills"], "nav": ["x"]},
{"dashboard-stats": ["files", "cost"]})
self.assertTrue(carryover_context.layout(self.store, ui))
self.assertEqual(self._layout(), {"order": ["skills", "cost"], "bench": ["files"]})
# once: a later change in the blob is not carried again
ui2 = self._blob({"dashboard-stats": ["tokens"]})
self.assertFalse(carryover_context.layout(self.store, ui2))
self.assertEqual(self._layout()["order"], ["skills", "cost"])
def test_nothing_arranged_writes_nothing(self):
self.assertFalse(carryover_context.layout(self.store, self._blob()))
self.assertIsNone(self._layout())
self.assertFalse(carryover_context.layout(self.store, {}))
def test_keeps_a_layout_the_plugin_has(self):
p = self.store.user_data_dir(OWNER_UID, PID) / "layout.json"
p.write_text(json.dumps({"order": ["tokens"], "bench": []}))
carryover_context.layout(self.store, self._blob({"dashboard-stats": ["cost"]}))
self.assertEqual(self._layout()["order"], ["tokens"])
def test_bad_blob_is_harmless(self):
self.assertFalse(carryover_context.layout(self.store, {"ai-agent-settings": "{nope"}))
self.assertFalse(carryover_context.layout(None, {}))
if __name__ == "__main__":
unittest.main()