Files
ai-agent/backend/test_plugin_details_batch.py

288 lines
13 KiB
Python

"""The Details drawer's two-request load: ``ui.slots[].query`` /
``reuseFrame`` in the manifest, ``GET|POST /api/plugins/batch-read``,
``GET /api/plugins/ui-bundle`` and the cacheable ``/sandbox-frame.html?v=``."""
from __future__ import annotations
import json
import os
import pathlib
import sys
import tempfile
import time
import unittest
BACKEND = pathlib.Path(__file__).resolve().parent
if str(BACKEND) not in sys.path:
sys.path.insert(0, str(BACKEND))
_TMP = tempfile.TemporaryDirectory()
_DATA = pathlib.Path(_TMP.name)
os.environ.setdefault("DB_PATH", str(_DATA / "ai-agent.db"))
os.environ.setdefault("TRANSCRIPTS_DIR", str(_DATA / "transcripts"))
os.environ.setdefault("WORKSPACE", str(_DATA / "workspace"))
os.environ.setdefault("REPO_DIR", str(_DATA / "workspace"))
os.environ.setdefault("PLUGINS_DIR", str(_DATA / "plugins"))
os.environ.setdefault("UI_STATE_PATH", str(_DATA / "ui-state.json"))
os.environ.setdefault("USERS_PATH", str(_DATA / "users.json"))
os.environ.setdefault("AUTH_PATH", str(_DATA / "auth.json"))
os.environ.setdefault("TOOLS_TOKEN_KEY", str(_DATA / "tools.key"))
os.environ.setdefault("STATIC_DIR", str(_DATA / "static"))
os.environ.setdefault("INTERNAL_API_TOKEN", "tok")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from core import csp # noqa: E402
from plugins import batch # noqa: E402
from plugins.manifest import ManifestError, validate_manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
# Answers its payload and a value unique to each run (a cache hit repeats it).
ECHO = ("import json, sys, time\n"
"p = json.load(sys.stdin)\n"
"print(json.dumps({'payload': p.get('payload', p), 'n': time.time_ns()}))\n")
SLOW = ("import json, sys, time\n"
"json.load(sys.stdin)\n"
"time.sleep(0.6)\n"
"print(json.dumps({'n': time.time_ns()}))\n")
FAIL = "import sys\nsys.stderr.write('boom')\nsys.exit(3)\n"
def _write(root: pathlib.Path, mf: dict, files: dict[str, str] | None = None) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(mf, indent=2), encoding="utf-8")
(root / "ui").mkdir(exist_ok=True)
(root / "ui" / "s.html").write_text(f"<p>{mf['id']} slot</p>", encoding="utf-8")
for rel, content in (files or {}).items():
p = root / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(content, encoding="utf-8")
return root
def _plugin(root: pathlib.Path, pid: str, *, slot_extra: dict | None = None) -> pathlib.Path:
return _write(root / pid, {
"schema": 1, "id": pid, "name": pid.title(),
"actions": {
"read": {"script": "echo.py", "readOnly": True},
"slow": {"script": "slow.py", "readOnly": True},
"fail": {"script": "fail.py", "readOnly": True},
"write": {"script": "echo.py"},
},
"ui": {"slots": [{"id": "det", "where": "conversation.details", "html": "ui/s.html",
**(slot_extra or {})}]},
}, {"echo.py": ECHO, "slow.py": SLOW, "fail.py": FAIL})
class ManifestTest(unittest.TestCase):
def _mf(self, td, **slot):
return validate_manifest(_write(pathlib.Path(td) / "q", {
"schema": 1, "id": "q", "name": "Q",
"actions": {"read": {"script": "a.py", "readOnly": True}, "write": {"script": "a.py"}},
"ui": {"slots": [{"id": "det", "where": "conversation.details", "html": "ui/s.html", **slot}]},
}, {"a.py": "print(1)\n"}))
def test_query_and_reuse_frame(self):
with tempfile.TemporaryDirectory() as td:
sl = self._mf(td, query={"action": "read", "payload": {"conversationId": "$conversationId"}},
reuseFrame=True)["ui"]["slots"][0]
self.assertEqual(sl["query"], {"action": "read", "payload": {"conversationId": "$conversationId"}})
self.assertTrue(sl["reuseFrame"])
sl = self._mf(td, query={"action": "read"}, reuseFrame=False)["ui"]["slots"][0]
self.assertEqual(sl["query"], {"action": "read", "payload": {}})
self.assertNotIn("reuseFrame", sl)
plain = self._mf(td)["ui"]["slots"][0]
self.assertNotIn("query", plain)
self.assertNotIn("reuseFrame", plain)
def test_bad_query_or_reuse_frame_refused(self):
with tempfile.TemporaryDirectory() as td:
for bad in ({"query": {"action": "write"}}, # not readOnly
{"query": {"action": "nope"}}, # not declared
{"query": {"action": "read", "payload": {"x": "y" * 3000}}},
{"query": {"action": "read", "payload": [1]}},
{"query": "read"},
{"reuseFrame": "yes"}):
with self.assertRaises(ManifestError, msg=bad):
self._mf(td, **bad)
class _RouteBase(unittest.TestCase):
def setUp(self):
self.td = tempfile.TemporaryDirectory()
self.root = pathlib.Path(self.td.name)
self.deps = main.app.state.ai
self.orig = self.deps.plugin_store
self.store = PluginStore(self.root / "plugins-data")
self.deps.plugin_store = self.store
batch.invalidate()
self.client = TestClient(main.app)
def tearDown(self):
self.deps.plugin_store = self.orig
batch.invalidate()
self.td.cleanup()
def install(self, pid: str, **kw):
plug = _plugin(self.root, pid, **kw)
self.store.install(OWNER_UID, str(plug), is_owner=True, approve=True)
return plug
class DescriptorsTest(_RouteBase):
def test_ui_exposes_query_and_reuse_frame(self):
self.install("alpha", slot_extra={"query": {"action": "read", "payload": {"a": 1}},
"reuseFrame": True})
r = self.client.get("/api/plugins/ui", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
sl = next(s for s in r.json()["ui"]["slots"] if s["pluginId"] == "alpha")
self.assertEqual(sl["query"], {"action": "read", "payload": {"a": 1}})
self.assertTrue(sl["reuseFrame"])
class BatchReadTest(_RouteBase):
def post(self, items, **extra):
r = self.client.post("/api/plugins/batch-read", headers=OWNER_H,
json={"items": items, **extra})
self.assertEqual(r.status_code, 200, r.text)
return r.json()["results"]
def test_many_plugins_partial_failure_and_readonly(self):
self.install("alpha")
self.install("beta")
res = self.post([
{"key": "a", "pluginId": "alpha", "action": "read", "payload": {"x": 1}},
{"key": "b", "pluginId": "beta", "action": "read"},
{"key": "f", "pluginId": "alpha", "action": "fail"},
{"key": "w", "pluginId": "alpha", "action": "write"},
{"key": "u", "pluginId": "nope", "action": "read"},
{"key": "d", "pluginId": "beta", "action": "missing"},
])
self.assertTrue(res["a"]["ok"])
self.assertEqual(res["a"]["data"]["payload"], {"x": 1})
self.assertFalse(res["a"]["cached"])
self.assertTrue(res["b"]["ok"])
self.assertFalse(res["f"]["ok"])
self.assertGreaterEqual(res["f"]["status"], 400)
self.assertEqual(res["w"], {"ok": False, "status": 405, "error": "action is not read-only"})
self.assertEqual(res["u"]["status"], 404)
self.assertEqual(res["d"]["status"], 404)
def test_concurrent(self):
self.install("alpha")
self.install("beta")
self.install("gamma")
t0 = time.monotonic()
res = self.post([{"key": p, "pluginId": p, "action": "slow"} for p in ("alpha", "beta", "gamma")])
took = time.monotonic() - t0
self.assertTrue(all(v["ok"] for v in res.values()), res)
self.assertLess(took, 1.5, "the three 0.6 s reads ran one after the other")
def test_cache_fresh_and_invalidation(self):
plug = self.install("alpha")
item = {"key": "a", "pluginId": "alpha", "action": "read", "payload": {"q": 1}}
first = self.post([item])["a"]
again = self.post([item])["a"]
self.assertTrue(again["cached"])
self.assertEqual(again["data"], first["data"])
fresh = self.post([{**item, "fresh": True}])["a"]
self.assertFalse(fresh["cached"])
self.assertNotEqual(fresh["data"]["n"], first["data"]["n"])
whole = self.post([item], fresh=True)["a"]
self.assertFalse(whole["cached"])
# a reload (same manifest) drops what was kept
self.assertTrue(self.post([item])["a"]["cached"])
r = self.client.post("/api/plugins/alpha/reload", headers=OWNER_H, json={})
self.assertEqual(r.status_code, 200, r.text)
self.assertFalse(self.post([item])["a"]["cached"])
# so does a config update
self.assertTrue(self.post([item])["a"]["cached"])
r = self.client.put("/api/plugins/alpha", headers=OWNER_H, json={"enabled": True})
self.assertEqual(r.status_code, 200, r.text)
self.assertFalse(self.post([item])["a"]["cached"])
self.assertTrue(plug.is_dir())
def test_get_form(self):
self.install("alpha")
items = json.dumps([{"key": "k", "pluginId": "alpha", "action": "read", "payload": {"z": 2}}])
r = self.client.get("/api/plugins/batch-read", headers=OWNER_H, params={"items": items})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["results"]["k"]["data"]["payload"], {"z": 2})
r2 = self.client.get("/api/plugins/batch-read", headers=OWNER_H, params={"items": items})
self.assertTrue(r2.json()["results"]["k"]["cached"])
r3 = self.client.get("/api/plugins/batch-read", headers=OWNER_H,
params={"items": items, "fresh": "true"})
self.assertFalse(r3.json()["results"]["k"]["cached"])
def test_bad_bodies(self):
too_many = [{"key": str(i), "pluginId": "a", "action": "b"} for i in range(33)]
for body in ({"items": too_many}, {"items": "x"}, {"items": [{"key": "", "pluginId": "a", "action": "b"}]},
{"items": [{"key": "k", "pluginId": "a", "action": "b", "payload": [1]}]}):
r = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json=body)
self.assertEqual(r.status_code, 400, body)
r = self.client.post("/api/plugins/batch-read", headers=OWNER_H,
json={"items": [], "pad": "x" * 40000})
self.assertEqual(r.status_code, 413)
r = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json={"items": []})
self.assertEqual(r.json(), {"results": {}})
class UiBundleTest(_RouteBase):
def test_bundle_etag_304(self):
self.install("alpha")
self.install("beta")
r = self.client.get("/api/plugins/ui-bundle?where=conversation.details", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
body = r.json()
self.assertEqual(body["where"], "conversation.details")
self.assertEqual(body["docs"], {"alpha:det": "<p>alpha slot</p>", "beta:det": "<p>beta slot</p>"})
self.assertRegex(body["version"], r"^[0-9a-f]{16}$")
self.assertEqual(r.headers["etag"], f'"{body["version"]}"')
self.assertEqual(r.headers["cache-control"], "private, no-cache")
r2 = self.client.get("/api/plugins/ui-bundle?where=conversation.details",
headers={**OWNER_H, "If-None-Match": r.headers["etag"]})
self.assertEqual(r2.status_code, 304)
empty = self.client.get("/api/plugins/ui-bundle?where=home.section", headers=OWNER_H)
self.assertEqual(empty.json()["docs"], {})
self.assertNotEqual(empty.json()["version"], body["version"])
def test_unknown_where(self):
r = self.client.get("/api/plugins/ui-bundle?where=nowhere", headers=OWNER_H)
self.assertEqual(r.status_code, 400)
class SandboxFrameCacheTest(unittest.TestCase):
def setUp(self):
self.static = main.STATIC_DIR
self.made = []
for name, text in (("index.html", "<html></html>"), (csp.SANDBOX_FRAME, "<p>frame</p>")):
p = self.static / name
if not p.exists():
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
self.made.append(p)
self.client = TestClient(main.app)
def tearDown(self):
for p in self.made:
p.unlink()
def test_versioned_is_immutable(self):
v = csp.sandbox_frame_hash(self.static / csp.SANDBOX_FRAME)
self.assertRegex(v, r"^[0-9a-f]{12}$")
r = self.client.get(f"/sandbox-frame.html?v={v}")
self.assertEqual(r.status_code, 200)
self.assertEqual(r.headers["cache-control"], "public, max-age=31536000, immutable")
self.assertTrue(r.headers["content-security-policy"].startswith("sandbox "))
for url in ("/sandbox-frame.html", "/sandbox-frame.html?v=deadbeef0000"):
r = self.client.get(url)
self.assertEqual(r.headers["cache-control"], "no-cache", url)
self.assertTrue(r.headers["content-security-policy"].startswith("sandbox "))
if __name__ == "__main__":
unittest.main()