Files
ai-agent/backend/test_plugin_perf_bridge.py
gabrielvidalandClaude Opus 5.5 a459352850 refactor(plugins): the header's CPU and On-disk chips move to the performance plugin
The core carried the conversation header's two perf chips (PerfChip,
StorageChip) although they belong to the performance plugin, and since
plugin-links they linked to /dashboards/performance|storage, which no
longer exist. They are now the plugin's `conversation.header` slot:

- `conversation.header` (declared since v1, never drawn) is rendered:
  HeaderPluginSlots puts each slot inline at the end of the header's meta
  line, sized both ways by resize(h, w), update {sessionId,
  conversationId, running}. SinglePluginSlot gets `startEmpty` (hidden
  until the frame first sizes itself, so a chip never shows a blank
  300 px frame while it loads) and `emptyStyle` (a 0 x 0 inline box: the
  absolute EMPTY_SLOT_STYLE would start mid-line and overflow the page);
- removed: PerfCard.tsx / StorageCard.tsx, useConversationPerf /
  useConversationStorage, fmtPct, the *Performance* eye switch (`perf`)
  and its French hint;
- perf.read already serves both reads (conversation/{sid} without series,
  conversation/{sid}/storage); a bridge test now pins the fields the
  chips draw, and the retired-files test lists the two chip files;
- docs/plugins.md and CLAUDE.md say where the chips live now.

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

234 lines
11 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 (the
header chips' two reads included), and that the core Performance / Storage
pages and the header chips are gone while ``/api/perf/*`` stays."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import time
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_header_chip_reads(self):
"""The header chips' two reads (the plugin's ``conversation.header``
slot): a tracked conversation's numbers without any series, and what
it keeps on disk — the fields the chips draw."""
from perf.poller import LAB
sid = "chip-0000-4000-8000-000000000001"
now = time.time()
snap = {"at": now, "interval": 5, "scanMs": 1,
"host": {"cpus": 8, "cpu": 50.0, "memTotal": 32 << 30, "memAvailable": 20 << 30},
"sessions": [{"sessionId": sid, "harness": "claude", "source": "hub", "rootPid": 9100,
"rootStart": 1, "startedAt": now - 60, "cpu": 42.0, "cpuSeconds": 33.0,
"rss": 700 << 20, "procs": 4, "threads": 9, "processes": []}],
"leftovers": []}
self.deps.perf_store.record(LAB, snap)
r = self.tc.get(f"{BASE}/perf/conversation/{sid}", headers=_handler())
self.assertEqual(r.status_code, 200, r.text)
out = r.json()
self.assertEqual(out["series"], {})
perf = out["perf"]
self.assertTrue(perf["tracked"])
self.assertEqual(perf["cpuSeconds"], 33.0)
self.assertEqual(perf["peakRss"], 700 << 20)
self.assertEqual(perf["peakProcs"], 4)
self.assertIn("live", perf)
d = self.tc.get(f"{BASE}/perf/conversation/{sid}/storage", headers=_handler())
self.assertEqual(d.status_code, 200, d.text)
self.assertIsInstance(d.json()["left"], int)
self.assertIsInstance(d.json()["items"], list)
guest = {"Authorization": f"Bearer {access.mint('cel', ttl=600)}"}
self.assertIn(self.tc.get(f"{BASE}/perf/conversation/{sid}", headers=guest).status_code, (403, 404))
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",
# the header chips (2026-11-27: the plugin's conversation.header slot)
"conversations/components/PerfCard.tsx",
"conversations/components/StorageCard.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()