Files
ai-agent/backend/test_plugin_perf_bridge.py
gabrielvidalandClaude Opus 5.5 efa87b21cf feat(plugins): perf.read / perf.act bridges; Performance and Storage move to the performance plugin
- backend: plugins/hubperf.py — perf.read (GET hub/perf/live, history,
  conversations, commands, conversation/{sid}?series=, conversation/{sid}/storage,
  storage, storage/history, storage/writers, storage/config, settings; live and
  storage add profiles + guestNames), perf.act (POST hub/perf/kill, keep,
  settings, storage/rm, storage/scan, storage/config — the plugin's own
  handlers only), and telemetry.read's hub/telemetry/hub. Owner-only,
  operator-approved caps. backend/perf and every /api/perf/* route stay.
- frontend: the Performance and Storage pages, perfLive/perfTotals/perfViz/
  perfStorage/storageItems/storageWriters/HubCard/guestPill, hubAnalysis,
  telemetryApi, perfApi and the conversation's PerfCards/StorageCards go;
  /dashboards/performance and /dashboards/storage redirect to
  /plugins/performance/performance|storage (else the overview);
  DETAIL_CARD_RENAMES maps the six retired card ids onto the plugin's
  conv-perf / conv-storage slots; the slot update carries drawerOpen and
  prompts. The header chips, CallCost / CommandPlayback and the guest Stats
  stay core.
- docs: CLAUDE.md, docs/plugins.md; tests: test_plugin_perf_bridge.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:16:42 +01:00

199 lines
9.2 KiB
Python

"""``perf.read`` / ``perf.act`` (2026-11-26) — the performance plugin's
bridges (``plugins/hubperf.py``): operator-only, owner-only, the acts for
the plugin's own handlers only, the answers' shape on the real store, and
that the core Performance / Storage pages are gone while ``/api/perf/*``
stays."""
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", "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 hubperf # 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": "pf", "name": "Performance",
"capabilities": ["perf.read", "perf.act", "telemetry.read"]}
BASE = "/proxy/tools/plugins/pf/hub"
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 _handler(pid="pf", uid=OWNER_UID):
return {"Authorization": f"Bearer {access.mint_handler(uid, pid, ttl=600)}"}
LAB = {"Authorization": "Bearer tok"} # the owner, not a handler (the internal token)
class Caps(unittest.TestCase):
def test_operator_only_and_labelled(self):
with tempfile.TemporaryDirectory() as td:
for cap in ("perf.read", "perf.act"):
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 Reads(unittest.TestCase):
def setUp(self):
self.deps = main.app.state.ai
self.tc = TestClient(main.app)
self.td = tempfile.TemporaryDirectory()
self.store = _install(self.td.name, MF)
self.p = patch.object(self.deps, "plugin_store", self.store)
self.p.start()
def tearDown(self):
self.p.stop()
self.td.cleanup()
def test_live_carries_the_scope_switch_and_names(self):
r = self.tc.get(f"{BASE}/perf/live?account=all", headers=_handler())
self.assertEqual(r.status_code, 200, r.text)
out = r.json()
for k in ("machines", "sessions", "leftovers", "settings", "profiles", "guestNames"):
self.assertIn(k, out)
self.assertTrue(any(p["id"] for p in out["profiles"]))
def test_every_read_answers(self):
for path in ("/perf/history?range=1h", "/perf/conversations?range=24h",
"/perf/commands?range=7d&kind=program", "/perf/conversation/s1?series=10m,life,bad",
"/perf/conversation/s1/storage", "/perf/storage", "/perf/storage/writers?range=24h",
"/perf/storage/history?runner=lab&mount=/&range=7d", "/perf/settings",
"/telemetry/hub?range=7d"):
r = self.tc.get(BASE + path, headers=LAB)
self.assertEqual(r.status_code, 200, f"{path}: {r.text}")
json.dumps(r.json())
conv = self.tc.get(f"{BASE}/perf/conversation/s1?series=10m,life,bad", headers=LAB).json()
self.assertEqual(sorted(conv["series"]), ["10m", "life"])
self.assertIn("tracked", conv["perf"])
self.assertIn("profiles", self.tc.get(f"{BASE}/perf/storage", headers=LAB).json())
def test_a_bad_range_is_a_refusal(self):
r = self.tc.get(f"{BASE}/perf/history?range=9y", headers=LAB)
self.assertEqual(r.status_code, 400)
self.assertEqual(r.json()["error"]["kind"], "bad_request")
r = self.tc.get(f"{BASE}/telemetry/hub?range=9y", headers=LAB)
self.assertEqual(r.status_code, 400)
def test_owner_only(self):
guest = {"Authorization": f"Bearer {access.mint('cel', ttl=600)}"}
r = self.tc.get(f"{BASE}/perf/live", headers=guest)
self.assertIn(r.status_code, (403, 404))
class Acts(unittest.TestCase):
def setUp(self):
self.deps = main.app.state.ai
self.tc = TestClient(main.app)
self.td = tempfile.TemporaryDirectory()
self.store = _install(self.td.name, MF)
self.p = patch.object(self.deps, "plugin_store", self.store)
self.p.start()
def tearDown(self):
self.p.stop()
self.td.cleanup()
def test_kill_goes_to_the_poller_for_the_handler_only(self):
with patch.object(self.deps.perf_poller, "kill", return_value={"killed": [42]}) as kill:
r = self.tc.post(f"{BASE}/perf/kill", json={"runner": "lab", "sessionId": "s1",
"processes": [{"pid": 42, "startedAt": 1}]},
headers=_handler())
lab = self.tc.post(f"{BASE}/perf/kill", json={"runner": "lab", "sessionId": "s1"}, headers=LAB)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json(), {"killed": [42]})
self.assertEqual(kill.call_args.args, ("lab", "s1", [{"pid": 42, "startedAt": 1}]))
self.assertEqual(lab.status_code, 403)
self.assertEqual(lab.json()["error"]["kind"], "handler_only")
def test_bodies_are_checked(self):
r = self.tc.post(f"{BASE}/perf/keep", json={"runner": "lab"}, headers=_handler())
self.assertEqual(r.status_code, 400)
r = self.tc.post(f"{BASE}/perf/keep", content=b"[]", headers=_handler())
self.assertEqual(r.status_code, 400)
def test_settings_patch(self):
with patch.object(self.deps.perf_settings, "set", side_effect=lambda b: {**b, "ok": 1}) as st:
r = self.tc.post(f"{BASE}/perf/settings", json={"autoKill": False}, headers=_handler())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(st.call_args.args, ({"autoKill": False},))
def test_storage_acts_reach_the_runner(self):
with patch("workers.store.sidecar_request", return_value={"ok": True}) as sc, \
patch.object(self.deps.perf_poller, "_endpoint", return_value=("http://x", "t")), \
patch.object(self.deps.perf_poller, "refresh"):
rm = self.tc.post(f"{BASE}/perf/storage/rm", json={"runner": "lab", "path": "/tmp/x"},
headers=_handler())
bad = self.tc.post(f"{BASE}/perf/storage/rm", json={"runner": "lab", "path": "rel"},
headers=_handler())
cfg = self.tc.post(f"{BASE}/perf/storage/config", json={"runner": "lab", "nudgeAt": 0},
headers=_handler())
self.assertEqual(rm.status_code, 200, rm.text)
self.assertEqual(sc.call_args_list[0].args[2], "/storage/rm")
self.assertEqual(bad.status_code, 400)
self.assertEqual(cfg.status_code, 200, cfg.text)
self.assertIn("nudgeAt", cfg.json())
def test_act_needs_its_own_capability(self):
with tempfile.TemporaryDirectory() as td:
store = _install(td, {**MF, "id": "ro", "capabilities": ["perf.read"]})
with patch.object(self.deps, "plugin_store", store):
r = self.tc.post("/proxy/tools/plugins/ro/hub/perf/kill",
json={"runner": "lab", "sessionId": "s"}, headers=_handler("ro"))
self.assertEqual(r.status_code, 403)
class Retired(unittest.TestCase):
def test_core_pages_gone_api_kept(self):
paths = set(main.app.openapi()["paths"])
for p in ("/api/perf/live", "/api/perf/conversation/{sid}", "/api/perf/conversation/{sid}/calls",
"/api/perf/conversation/{sid}/storage", "/api/perf/storage", "/api/telemetry/hub"):
self.assertIn(p, paths)
front = pathlib.Path(__file__).resolve().parent.parent / "frontend" / "src" / "business"
if front.is_dir():
for f in ("dashboards/pages/Performance.tsx", "dashboards/pages/Storage.tsx",
"dashboards/components/HubCard.tsx", "conversations/components/PerfCards.tsx",
"conversations/components/StorageCards.tsx"):
self.assertFalse((front / f).exists(), f)
def test_guest_names(self):
class U:
def all(self):
return [{"id": "cel", "name": "Céline"}, {"id": "bo"}, {}]
self.assertEqual(hubperf.guest_names(type("D", (), {"users": U()})()), {"cel": "Céline", "bo": "bo"})
if __name__ == "__main__":
unittest.main()