363 lines
19 KiB
Python
363 lines
19 KiB
Python
#!/usr/bin/env python3
|
|
"""Unit tests for the Performance live plugin (stdlib only).
|
|
|
|
A fake hub (``http.server`` on 127.0.0.1) stands in for the ai-agent's
|
|
``perf.read`` / ``perf.act`` / ``telemetry.read`` bridges; each handler runs
|
|
as a subprocess with the stripped env the hub gives it. The pages and slots
|
|
are rendered in jsdom against ``fixtures.json`` when a ``node_modules`` with
|
|
jsdom is around (``AI_AGENT_DIR``/frontend, default ~/projects/ai-agent).
|
|
|
|
python3 tests/test_plugin.py
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
import urllib.parse
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
|
TESTS = ROOT / "tests"
|
|
MANIFEST = json.loads((ROOT / "plugin.json").read_text())
|
|
TOKEN = "aiah1.owner.performance.123.sig"
|
|
FIXTURES = json.loads((TESTS / "fixtures.json").read_text())
|
|
|
|
|
|
class _Hub(BaseHTTPRequestHandler):
|
|
status = 200
|
|
body: dict = {"ok": True}
|
|
seen: list = []
|
|
|
|
def _reply(self, method, body=None):
|
|
_Hub.seen.append((method, self.path, body))
|
|
if self.headers.get("Authorization") != f"Bearer {TOKEN}":
|
|
return self._send(401, {"error": {"message": "unknown token", "kind": "auth"}})
|
|
if _Hub.status != 200:
|
|
return self._send(_Hub.status, {"error": {"message": "perf.read is owner-only", "kind": "capability"}})
|
|
if not urllib.parse.urlsplit(self.path).path.startswith("/plugins/performance/hub/"):
|
|
return self._send(404, {"error": {"message": "no", "kind": "x"}})
|
|
self._send(200, _Hub.body)
|
|
|
|
def do_GET(self):
|
|
self._reply("GET")
|
|
|
|
def do_POST(self):
|
|
n = int(self.headers.get("Content-Length") or 0)
|
|
self._reply("POST", json.loads(self.rfile.read(n) or b"{}"))
|
|
|
|
def _send(self, code, body):
|
|
raw = json.dumps(body).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(raw)))
|
|
self.end_headers()
|
|
self.wfile.write(raw)
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
|
|
class TestHandlers(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.srv = ThreadingHTTPServer(("127.0.0.1", 0), _Hub)
|
|
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
|
cls.url = f"http://127.0.0.1:{cls.srv.server_address[1]}"
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.srv.shutdown()
|
|
|
|
def setUp(self):
|
|
_Hub.status, _Hub.body, _Hub.seen = 200, {"ok": True}, []
|
|
|
|
def run_action(self, name, payload=None, token=TOKEN, url=None):
|
|
script = ROOT / MANIFEST["actions"][name]["script"]
|
|
with tempfile.TemporaryDirectory() as td:
|
|
env = {"PATH": "/usr/bin:/bin", "AIA_TOOLS_URL": url or self.url, "AIA_TOOLS_TOKEN": token,
|
|
"AIA_PLUGIN_ID": "performance", "AIA_PLUGIN_DATA_DIR": td}
|
|
return subprocess.run([sys.executable, "-I", str(script)], input=json.dumps(payload or {}),
|
|
capture_output=True, text=True, env=env, timeout=30)
|
|
|
|
def last(self):
|
|
method, path, body = _Hub.seen[-1]
|
|
u = urllib.parse.urlsplit(path)
|
|
return method, u.path.removeprefix("/plugins/performance/hub/"), urllib.parse.parse_qs(u.query), body
|
|
|
|
# read
|
|
def test_live_with_scope_and_guest_pick(self):
|
|
_Hub.body = FIXTURES["live"]
|
|
p = self.run_action("read", {"view": "live", "scope": "profile:guests", "guests": ["carol", "bo", "carol"]})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout), FIXTURES["live"])
|
|
self.assertEqual(self.last()[1:3], ("perf/live", {"account": ["profile:guests,guest:carol,guest:bo"]}))
|
|
|
|
def test_every_view_has_its_route(self):
|
|
cases = [
|
|
({"view": "history", "range": "1h", "runner": "lab"}, "perf/history", {"range": ["1h"], "runner": ["lab"]}),
|
|
({"view": "conversations", "range": "all"}, "perf/conversations", {"range": ["all"]}),
|
|
({"view": "commands", "kind": "program"}, "perf/commands", {"range": ["7d"], "kind": ["program"]}),
|
|
({"view": "conversation", "sid": "abc-123", "series": ["10m", "life", "nope"]}, "perf/conversation/abc-123",
|
|
{"series": ["10m,life"]}),
|
|
({"view": "conversationStorage", "sid": "abc"}, "perf/conversation/abc/storage", {}),
|
|
({"view": "storage", "scope": "all"}, "perf/storage", {"account": ["all"]}),
|
|
({"view": "writers", "range": "30d"}, "perf/storage/writers", {"range": ["30d"]}),
|
|
({"view": "storageHistory", "runner": "lab", "mount": "/tmp"}, "perf/storage/history",
|
|
{"runner": ["lab"], "mount": ["/tmp"], "range": ["7d"]}),
|
|
({"view": "storageConfig", "runner": "fedcba987654"}, "perf/storage/config", {"runner": ["fedcba987654"]}),
|
|
({"view": "settings"}, "perf/settings", {}),
|
|
({"view": "hub", "range": "7d"}, "telemetry/hub", {"range": ["7d"]}),
|
|
]
|
|
for payload, path, query in cases:
|
|
p = self.run_action("read", payload)
|
|
self.assertEqual(p.returncode, 0, f"{payload}: {p.stderr}")
|
|
self.assertEqual(self.last()[:3], ("GET", path, query), payload)
|
|
|
|
def test_odd_input_is_dropped(self):
|
|
self.run_action("read", {"view": "history", "range": "9y", "runner": "../x", "scope": "profile:x&a=1",
|
|
"guests": ["Bad!", 3]})
|
|
self.assertEqual(self.last()[1:3], ("perf/history", {"range": ["24h"]}))
|
|
p = self.run_action("read", {"view": "conversation", "sid": "../../etc"})
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("which conversation", p.stderr)
|
|
p = self.run_action("read", {"view": "everything"})
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("unknown view", p.stderr)
|
|
|
|
def test_refusals_are_reported(self):
|
|
_Hub.status = 403
|
|
p = self.run_action("read", {"view": "live"})
|
|
self.assertNotEqual(p.returncode, 0)
|
|
self.assertIn("owner-only", p.stderr)
|
|
p = self.run_action("read", {"view": "live"}, token="nope")
|
|
self.assertIn("unknown token", p.stderr)
|
|
p = self.run_action("read", {"view": "live"}, url="http://127.0.0.1:9")
|
|
self.assertIn("didn't answer", p.stderr)
|
|
|
|
# act
|
|
def test_kill_forwards_only_its_fields(self):
|
|
_Hub.body = {"killed": [42]}
|
|
p = self.run_action("act", {"op": "kill", "runner": "lab", "sessionId": "s1", "evil": 1,
|
|
"processes": [{"pid": 42, "startedAt": 1795000000.5, "x": 2}]})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
self.assertEqual(json.loads(p.stdout), {"killed": [42]})
|
|
self.assertEqual(self.last()[0:2], ("POST", "perf/kill"))
|
|
self.assertEqual(self.last()[3], {"runner": "lab", "sessionId": "s1",
|
|
"processes": [{"pid": 42, "startedAt": 1795000000.5}]})
|
|
self.run_action("act", {"op": "kill", "runner": "lab", "sessionId": "s1"})
|
|
self.assertEqual(self.last()[3], {"runner": "lab", "sessionId": "s1"})
|
|
|
|
def test_keep_settings_and_storage(self):
|
|
self.run_action("act", {"op": "keep", "runner": "lab", "pid": 7, "startedAt": 5, "kept": False})
|
|
self.assertEqual(self.last()[1:], ("perf/keep", {}, {"runner": "lab", "pid": 7, "startedAt": 5, "kept": False}))
|
|
self.run_action("act", {"op": "settings", "autoKill": False, "autoKillHours": 12, "keepLabels": ["opencode", " "]})
|
|
self.assertEqual(self.last()[3], {"autoKill": False, "autoKillHours": 12, "keepLabels": ["opencode"]})
|
|
self.run_action("act", {"op": "storageRm", "runner": "lab", "path": "/tmp/claude-1000/x", "force": True})
|
|
self.assertEqual(self.last()[1:], ("perf/storage/rm", {}, {"runner": "lab", "path": "/tmp/claude-1000/x",
|
|
"force": True, "dry": False}))
|
|
self.run_action("act", {"op": "storageScan", "runner": "lab"})
|
|
self.assertEqual(self.last()[1:], ("perf/storage/scan", {}, {"runner": "lab"}))
|
|
self.run_action("act", {"op": "storageConfig", "runner": "lab", "autoCleanDays": 0, "nudgeAt": 0.9})
|
|
self.assertEqual(self.last()[3], {"runner": "lab", "autoCleanDays": 0, "nudgeAt": 0.9})
|
|
|
|
def test_bad_acts_never_reach_the_hub(self):
|
|
for payload, why in [({"op": "kill", "runner": "lab"}, "which conversation"),
|
|
({"op": "kill", "sessionId": "s"}, "which machine"),
|
|
({"op": "keep", "runner": "lab", "pid": True, "startedAt": 1}, "pid"),
|
|
({"op": "settings"}, "nothing to change"),
|
|
({"op": "settings", "autoKillHours": 0}, "autoKillHours"),
|
|
({"op": "storageRm", "runner": "lab", "path": "relative/x"}, "absolute path"),
|
|
({"op": "storageConfig", "runner": "lab", "nudgeAt": 2}, "nudgeAt"),
|
|
({"op": "format-disk"}, "unknown op")]:
|
|
_Hub.seen = []
|
|
p = self.run_action("act", payload)
|
|
self.assertNotEqual(p.returncode, 0, payload)
|
|
self.assertIn(why, p.stderr, payload)
|
|
self.assertEqual(_Hub.seen, [], payload)
|
|
|
|
|
|
def _node_modules() -> pathlib.Path | None:
|
|
ai = pathlib.Path(os.path.expanduser(os.environ.get("AI_AGENT_DIR", "~/projects/ai-agent")))
|
|
for d in (ai / "frontend" / "node_modules", ROOT / "node_modules"):
|
|
if (d / "jsdom").is_dir():
|
|
return d
|
|
return None
|
|
|
|
|
|
NODE_MODULES = _node_modules()
|
|
|
|
|
|
@unittest.skipUnless(NODE_MODULES and shutil.which("node"), "no node + jsdom (AI_AGENT_DIR/frontend/node_modules)")
|
|
class TestRender(unittest.TestCase):
|
|
def render(self, page, init=None, click=""):
|
|
p = subprocess.run(["node", str(TESTS / "render_harness.js"), str(ROOT / "ui" / page), str(TESTS / "fixtures.json"),
|
|
json.dumps(init or {}), click], capture_output=True, text=True, timeout=60,
|
|
env={**os.environ, "NODE_PATH": str(NODE_MODULES)})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
out = json.loads(p.stdout)
|
|
self.assertEqual(out["errors"], [], page)
|
|
return out
|
|
|
|
def test_performance_page(self):
|
|
out = self.render("performance.html", {"scope": "profile:personal"})
|
|
for text in ("Running now", "Leftover processes", "Over time", "Heaviest commands", "Per conversation",
|
|
"Is the hub answering fast?", "Where does the time go?", "How does it feel in the browser?",
|
|
"What broke in the browser?", "Ship the storage page", "Carol", "Auto-kill leftovers after",
|
|
"Its runner predates the Performance dashboard"):
|
|
self.assertIn(text, out["text"])
|
|
views = [c[2].get("view") for c in out["calls"] if c[0] == "query"]
|
|
self.assertEqual(sorted(views), ["commands", "conversations", "history", "hub", "live"])
|
|
self.assertIn("2 agents running", out["headers"][-1]["subtitle"])
|
|
|
|
def test_kill_all_asks_twice_then_acts(self):
|
|
out = self.render("performance.html", {"scope": "all"}, click="Kill all")
|
|
acts = [c[2] for c in out["calls"] if c[0] == "action"]
|
|
self.assertEqual(acts, [{"op": "kill", "runner": "lab", "sessionId": "s-old"}])
|
|
|
|
def test_storage_page(self):
|
|
out = self.render("storage.html", {"scope": "all"})
|
|
for text in ("On disk", "Biggest writers", "/tmp (RAM) is 81% full", "Clean up stale", "~/worktrees/ai-agent-x",
|
|
"merged into main", "Auto-clean the scratch dirs", "+800 MB"):
|
|
self.assertIn(text, out["text"])
|
|
self.assertEqual(sorted(c[2]["view"] for c in out["calls"] if c[0] == "query"), ["storage", "storageConfig", "writers"])
|
|
|
|
def test_conversation_slots(self):
|
|
init = {"sessionId": "s-build", "update": {"running": True, "drawerOpen": True, "prompts": [1]}}
|
|
perf = self.render("conv-perf.html", init)
|
|
for text in ("Now", "CPU time", "Over its life", "Heaviest commands", "npm run build", "Left running (1)", "Kill all"):
|
|
self.assertIn(text, perf["text"])
|
|
self.assertIs(perf["empty"], False)
|
|
self.assertEqual([c[2] for c in perf["calls"] if c[0] == "query"],
|
|
[{"view": "conversation", "sid": "s-build", "series": ["10m", "life"]}])
|
|
disk = self.render("conv-storage.html", init)
|
|
for text in ("On disk", "Keeps 2.8 GB", "net +2.8 GB", "ai-agent-x", "in RAM"):
|
|
self.assertIn(text, disk["text"])
|
|
|
|
def test_header_chips(self):
|
|
# running: live CPU · RAM, and the disk it keeps (amber past 1 GB); each opens its page
|
|
out = self.render("conv-chips.html", {"sessionId": "s-build", "update": {"running": True}}, click="148%")
|
|
self.assertIn("148% · 1.4 GB", out["text"])
|
|
self.assertIn("2.8 GB", out["text"])
|
|
self.assertIs(out["empty"], False)
|
|
self.assertEqual([c[2] for c in out["calls"] if c[0] == "query"],
|
|
[{"view": "conversation", "sid": "s-build", "series": ["10m", "life"]},
|
|
{"view": "conversationStorage", "sid": "s-build"}])
|
|
# (the harness clicks twice, for the arm-then-confirm buttons)
|
|
self.assertEqual({c[1] for c in out["calls"] if c[0] == "navigate"}, {"/plugins/performance/performance"})
|
|
disk = self.render("conv-chips.html", {"sessionId": "s-build"}, click="2.8 GB")
|
|
self.assertEqual({c[1] for c in disk["calls"] if c[0] == "navigate"}, {"/plugins/performance/storage"})
|
|
|
|
def test_header_chips_once_ended_or_untracked(self):
|
|
def run(fixtures):
|
|
p = subprocess.run(["node", str(TESTS / "render_harness.js"), str(ROOT / "ui" / "conv-chips.html"), "/dev/stdin",
|
|
json.dumps({"sessionId": "s-x", "update": {"running": False}})],
|
|
input=json.dumps(fixtures), capture_output=True, text=True, timeout=60,
|
|
env={**os.environ, "NODE_PATH": str(NODE_MODULES)})
|
|
self.assertEqual(p.returncode, 0, p.stderr)
|
|
return json.loads(p.stdout)
|
|
ended = {"conversation": {"perf": {**FIXTURES["conversation"]["perf"], "live": None}, "series": {}},
|
|
"conversationStorage": {"items": [], "left": 10 << 20}}
|
|
out = run(ended)
|
|
self.assertIn("1.9 GB · 12 min", out["text"])
|
|
self.assertNotIn("10 MB", out["text"]) # under 50 MB: no disk chip
|
|
self.assertIs(out["empty"], False)
|
|
out = run({"conversation": {"perf": {"tracked": False}, "series": {}}}) # the disk read fails
|
|
self.assertEqual(out["errors"], [])
|
|
self.assertIs(out["empty"], True)
|
|
|
|
def test_heaviest_command_jumps_to_its_call(self):
|
|
out = self.render("conv-perf.html", {"sessionId": "s-build", "update": {"running": False}}, click="npm run build")
|
|
jumps = [c[1] for c in out["calls"] if c[0] == "scrollTo"]
|
|
self.assertEqual(jumps[0], {"toolUseId": "toolu_1"})
|
|
|
|
def test_untracked_conversation_folds_away(self):
|
|
p = subprocess.run(["node", str(TESTS / "render_harness.js"), str(ROOT / "ui" / "conv-perf.html"), "/dev/stdin",
|
|
json.dumps({"sessionId": "s-x", "update": {}})],
|
|
input=json.dumps({"conversation": {"perf": {"tracked": False}, "series": {}}}),
|
|
capture_output=True, text=True, timeout=60, env={**os.environ, "NODE_PATH": str(NODE_MODULES)})
|
|
out = json.loads(p.stdout)
|
|
self.assertIs(out["empty"], True)
|
|
|
|
|
|
class TestPackage(unittest.TestCase):
|
|
def pages(self):
|
|
return {p: (ROOT / "ui" / p).read_text()
|
|
for p in ("performance.html", "storage.html", "conv-perf.html", "conv-storage.html", "conv-chips.html")}
|
|
|
|
def test_manifest(self):
|
|
self.assertEqual(MANIFEST["id"], "performance")
|
|
self.assertEqual(MANIFEST["capabilities"], ["perf.read", "perf.act", "telemetry.read"])
|
|
self.assertNotIn("managed", MANIFEST)
|
|
self.assertRegex(MANIFEST["color"], r"^#[0-9a-f]{6}$")
|
|
pages = {(p["id"], p["nav"], p["html"]) for p in MANIFEST["ui"]["pages"]}
|
|
self.assertEqual(pages, {("performance", "dashboards", "ui/performance.html"), ("storage", "dashboards", "ui/storage.html")})
|
|
# the ids core's DETAIL_CARD_RENAMES maps the retired cards onto, and the header chips
|
|
self.assertEqual([(s["id"], s["where"]) for s in MANIFEST["ui"]["slots"]],
|
|
[("conv-perf", "conversation.details"), ("conv-storage", "conversation.details"),
|
|
("conv-chips", "conversation.header")])
|
|
chips = MANIFEST["ui"]["slots"][2]
|
|
self.assertEqual(chips["vis"]["key"], "chips")
|
|
self.assertLessEqual(chips["height"], 20) # a chip in a line of text
|
|
for f in ("README.md", "icon.svg", "illustration.webp", *(a["script"] for a in MANIFEST["actions"].values()),
|
|
*(p["html"] for p in MANIFEST["ui"]["pages"]), *(s["html"] for s in MANIFEST["ui"]["slots"])):
|
|
self.assertTrue((ROOT / f).is_file(), f)
|
|
|
|
def test_reads_are_read_only_acts_are_not(self):
|
|
self.assertIs(MANIFEST["actions"]["read"].get("readOnly"), True)
|
|
self.assertNotIn("readOnly", MANIFEST["actions"]["act"])
|
|
for name, html in self.pages().items():
|
|
self.assertNotRegex(html, r'query\("act"|action\("read"\)', name)
|
|
for op in re.findall(r'op: "([a-zA-Z]+)"', html):
|
|
self.assertIn(op, ("kill", "keep", "settings", "storageRm", "storageScan", "storageConfig"), name)
|
|
|
|
def test_pages_need_no_network(self):
|
|
for name, html in self.pages().items():
|
|
self.assertNotRegex(html, r"<script[^>]+src=|<link[^>]+href=|@import|fetch\(|XMLHttpRequest|innerHTML|eval\(", name)
|
|
|
|
def test_pages_are_native_and_themed(self):
|
|
for name, html in self.pages().items():
|
|
self.assertIn("hsl(var(--", html, name)
|
|
self.assertIn("html.dark", html, name) if name != "conv-storage.html" else None
|
|
self.assertIn("onTheme", html, name)
|
|
for name in ("performance.html", "storage.html"):
|
|
html = self.pages()[name]
|
|
for token in ("setHeader", "init.scope", "aia-page", "aia-card", "aia-seg", "aia-error", "aia-empty", "api.query"):
|
|
self.assertIn(token, html, name)
|
|
self.assertNotIn("Loading", html, name)
|
|
self.assertNotRegex(html, r"<h1", name)
|
|
for name in ("conv-perf.html", "conv-storage.html"):
|
|
html = self.pages()[name]
|
|
for token in ("setEmpty", "resize", "onUpdate", "drawerOpen"):
|
|
self.assertIn(token, html, name)
|
|
chips = self.pages()["conv-chips.html"]
|
|
for token in ("setEmpty", "resize(h, w)", "onUpdate", "U.running", "navigate"):
|
|
self.assertIn(token, chips)
|
|
|
|
def test_icon_is_plain(self):
|
|
svg = (ROOT / "icon.svg").read_text()
|
|
self.assertIn('stroke="currentColor"', svg)
|
|
self.assertIn('stroke-width="1.75"', svg)
|
|
self.assertIn('viewBox="0 0 24 24"', svg)
|
|
self.assertNotRegex(svg, r"<script|\son\w+=|foreignObject|href=|data:")
|
|
|
|
def test_handlers_are_executable(self):
|
|
for a in MANIFEST["actions"].values():
|
|
self.assertTrue(os.access(ROOT / a["script"], os.X_OK), a["script"])
|
|
|
|
def test_readme_is_short(self):
|
|
lines = [x for x in (ROOT / "README.md").read_text().splitlines() if x.strip()]
|
|
self.assertLessEqual(len(lines), 12)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|