Files
ai-agent/backend/test_plugin_fences.py
gabrielvidalandClaude Opus 5.5 c04e8f64dd feat(plugins): ui.fences — a plugin draws a fenced block of an agent's message
A ```chart block (any language a live plugin claims) in an assistant
message renders as the plugin's sandboxed frame, init {fence, code,
sessionId, conversationId, lang}; first user: the Charts plugin.

- manifest: ui.fences[] {id, lang, html, height, label, vis}; code
  languages and notify reserved; only written when set (fingerprints of
  installed plugins unchanged);
- GET /api/plugins → ui.fences (one plugin per language), the document at
  /api/plugins/{id}/ui/fence/{fenceId}, a capability line;
- Markdown.tsx: the pre renderer asks FenceRendererProvider (fenceOf reads
  the language, the code and whether the closing fence is in yet);
- PluginFences.tsx: PluginFenceScope around assistant messages only, a
  placeholder while the block is being typed, behind Rich widgets + the
  fence's own vis switch (Plugins in the eye popover);
- mock: the Charts plugin's card + fence and a conv-charts conversation;
- docs/plugins.md: "Fenced blocks in messages".

Tests: test_plugin_fences.py (5), MarkdownFences.test.tsx (5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:24:28 +01:00

158 lines
7.4 KiB
Python

"""``ui.fences[]``: a fenced block of an agent's message drawn by a plugin
(```chart → the Charts plugin's frame). The manifest key, the reserved
languages, the approval fingerprint of a plugin without it, the descriptors
``GET /api/plugins`` hands the app and the document ``/ui/fence/<id>`` serves."""
from __future__ import annotations
import json
import os
import pathlib
import sys
import tempfile
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("INTERNAL_API_TOKEN", "tok")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins.manifest import ManifestError, capability_fingerprint, validate_manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
CHART_HTML = "<p>chart frame</p>"
def _write(root: pathlib.Path, mf: dict) -> 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" / "chart.html").write_text(CHART_HTML, encoding="utf-8")
return root
def _mf(pid: str, fences) -> dict:
return {"schema": 1, "id": pid, "name": pid.title(), "ui": {"fences": fences}}
class FenceManifestTest(unittest.TestCase):
def test_normalized(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "charts", _mf("charts", [
{"id": "chart", "lang": "chart", "html": "ui/chart.html", "height": 300,
"label": "Chart", "vis": {"key": "charts", "label": "Charts", "hint": "```chart blocks"}},
{"id": "kpi", "lang": "chart-kpi", "html": "ui/chart.html"},
])))
chart, kpi = mf["ui"]["fences"]
self.assertEqual(chart, {"id": "chart", "lang": "chart", "label": "Chart", "html": "ui/chart.html",
"height": 300, "vis": {"key": "charts", "label": "Charts",
"hint": "```chart blocks"}})
self.assertEqual(kpi["height"], 240)
self.assertEqual(kpi["label"], "kpi")
self.assertNotIn("vis", kpi)
def test_refused(self):
bad = [
({"id": "a", "lang": "python", "html": "ui/chart.html"}, "code language"),
({"id": "a", "lang": "notify", "html": "ui/chart.html"}, "closing notify"),
({"id": "a", "lang": "Chart", "html": "ui/chart.html"}, "lowercase"),
({"id": "a", "lang": "c", "html": "ui/chart.html"}, "lowercase"),
({"id": "a", "lang": "chart", "html": "../x.html"}, "html"),
({"id": "a", "lang": "chart", "html": "ui/chart.html", "height": 5}, "height"),
({"id": "a b", "lang": "chart", "html": "ui/chart.html"}, "id invalid"),
]
with tempfile.TemporaryDirectory() as td:
for i, (fence, why) in enumerate(bad):
with self.subTest(why=why), self.assertRaises(ManifestError) as cm:
validate_manifest(_write(pathlib.Path(td) / f"p{i}", _mf(f"p{i}", [fence])))
self.assertIn(why, str(cm.exception))
with self.assertRaises(ManifestError) as cm:
validate_manifest(_write(pathlib.Path(td) / "dup", _mf("dup", [
{"id": "a", "lang": "chart", "html": "ui/chart.html"},
{"id": "b", "lang": "chart", "html": "ui/chart.html"},
])))
self.assertIn("declared twice", str(cm.exception))
def test_fingerprint_unchanged_without_fences(self):
"""No ``fences`` key in a normalized ``ui`` that declares none: the
approval fingerprint of every installed plugin stays put."""
with tempfile.TemporaryDirectory() as td:
root = _write(pathlib.Path(td) / "e", {
"schema": 1, "id": "e", "name": "E",
"ui": {"toolCards": [{"id": "t", "match": {"tool": "shell"}, "html": "ui/chart.html"}]},
})
mf = validate_manifest(root)
self.assertNotIn("fences", mf["ui"])
self.assertEqual(set(mf["ui"]), {"pages", "toolCards", "slots"})
fp = capability_fingerprint(mf)
raw = json.loads((root / "plugin.json").read_text())
raw["ui"]["fences"] = []
(root / "plugin.json").write_text(json.dumps(raw))
self.assertEqual(capability_fingerprint(validate_manifest(root)), fp)
class FenceRoutesTest(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
self.client = TestClient(main.app)
def tearDown(self):
self.deps.plugin_store = self.orig
self.td.cleanup()
def test_descriptors_and_document(self):
a = _write(self.root / "charts", _mf("charts", [
{"id": "chart", "lang": "chart", "html": "ui/chart.html", "height": 320}]))
b = _write(self.root / "other", _mf("other", [
{"id": "mine", "lang": "chart", "html": "ui/chart.html"},
{"id": "map", "lang": "geomap", "html": "ui/chart.html"}]))
self.store.install(OWNER_UID, str(a), is_owner=True)
self.store.install(OWNER_UID, str(b), is_owner=True)
r = self.client.get("/api/plugins", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
fences = r.json()["ui"]["fences"]
# One plugin per language: the first active one keeps ```chart.
by_lang = {f["lang"]: f for f in fences}
self.assertEqual(sorted(by_lang), ["chart", "geomap"])
self.assertEqual(by_lang["chart"]["pluginId"], "charts")
self.assertEqual(by_lang["chart"]["height"], 320)
self.assertEqual(by_lang["geomap"]["pluginId"], "other")
self.assertNotIn("html", by_lang["chart"])
doc = self.client.get("/api/plugins/charts/ui/fence/chart", headers=OWNER_H)
self.assertEqual(doc.status_code, 200, doc.text)
self.assertEqual(doc.text, CHART_HTML)
self.assertEqual(self.client.get("/api/plugins/charts/ui/fence/nope", headers=OWNER_H).status_code, 404)
def test_capability_line(self):
a = _write(self.root / "charts", _mf("charts", [
{"id": "chart", "lang": "chart", "html": "ui/chart.html"}]))
from plugins.manifest import capability_summary
lines = [i["label"] for i in capability_summary(validate_manifest(a))]
self.assertIn("Draws ```chart blocks in agents' messages (sandboxed)", lines)
if __name__ == "__main__":
unittest.main()