Files
ai-agent/backend/test_plugin_card.py
gabrielvidalandClaude Opus 5.5 1ac03d0804 feat(home): notification lines under the cards, Recent, machine strips and plugin card bits
The home view, less bloated (forms home-declutter-phone_kwmprx, its three
interactive-demo rounds):
- cards: no glyphs under the tile (home and Conversations page), no unread
  dot, no notification inside; the foot holds the account/machine pills,
  the via origin and the subagents, then the time
- CardNotifs: one line per notification under each home card, newest first,
  3 then Show N more; a tap opens it (body, link) and reads it, a swipe
  dismisses it; state per id from the ledger (notifStateIn)
- Recent replaces Finished: finished conversations read or not, by last
  activity, 10 + Show more (pages the list in); a card swipe archives
- Running grouped by machine once on two or more: a vertical strip with the
  machine's icon and name turned counterclockwise, tinted by its profile
  while online, grey asleep; the cards there drop their machine pill
- ui.card: plugins add declarative bits to the cards (tags, cost, foot,
  corner, border) from templates over the summary's fields; PlanPctChip and
  LocalEnergyChip leave core for plan-usage / provider-evox2
- list cards keep a notification's body, link, type and remote image
- Swipe: nested swipes go to the innermost one
- mock: /api/notifications/state, server mode under the mock too

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 23:44:18 +01:00

158 lines
7.3 KiB
Python

"""``ui.card[]``: what a plugin adds to the conversation cards (the plan-usage
plugin's ``≈0.4% wk``, provider-evox2's energy). The manifest key and its
refusals, the approval fingerprint of a plugin without it, the descriptors
``GET /api/plugins`` hands the app and the capability line."""
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 ( # noqa: E402
ManifestError,
capability_fingerprint,
capability_summary,
validate_manifest,
)
from plugins.store import OWNER_UID, PluginStore # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
WEEK = {
"id": "week", "place": "cost", "text": "{planPct.week|apct} wk",
"title": "≈ {planPct.week|pct2} of this account's weekly limit",
"when": "planPct.week > 0",
"vis": {"key": "planPct", "label": "Plan %", "hint": "share of the week"},
}
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")
return root
def _mf(pid: str, card) -> dict:
return {"schema": 1, "id": pid, "name": pid.title(), "ui": {"card": card}}
class CardManifestTest(unittest.TestCase):
def test_normalized(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "plan", _mf("plan", [
WEEK,
{"id": "energy", "place": "tags", "text": "{local.wh|wh}", "icon": "zap", "tone": "plain"},
{"id": "pi", "place": "border", "when": 'meta.harness == "pi"', "tone": "violet"},
{"id": "local", "place": "corner", "icon": "cpu"},
])))
week, energy, pi, local = mf["ui"]["card"]
self.assertEqual(week, {**WEEK, "tone": "muted"})
self.assertEqual(energy, {"id": "energy", "place": "tags", "text": "{local.wh|wh}",
"icon": "zap", "tone": "plain"})
self.assertEqual(pi, {"id": "pi", "place": "border", "when": 'meta.harness == "pi"', "tone": "violet"})
# corner and border default to the primary tone
self.assertEqual(local["tone"], "primary")
def test_refused(self):
bad = [
({"id": "a", "place": "header", "text": "x"}, "place must be one of"),
({"id": "a", "place": "tags", "text": "{secret.key}"}, "unknown field 'secret.key'"),
({"id": "a", "place": "tags", "text": "{cost|money}"}, "unknown format 'money'"),
({"id": "a", "place": "tags"}, "needs a text or an icon"),
({"id": "a", "place": "border", "text": "x"}, "a border bit has no text"),
({"id": "a", "place": "corner", "text": "four"}, "at most 3 characters"),
({"id": "a", "place": "tags", "text": "x" * 61}, "at most 60 characters"),
({"id": "a", "place": "tags", "text": "x", "icon": "skull"}, "icon must be one of"),
({"id": "a", "place": "tags", "text": "x", "tone": "pink"}, "tone must be one of"),
({"id": "a", "place": "tags", "text": "x", "when": "cost >> 2"}, "when must be a field"),
({"id": "a", "place": "tags", "text": "x", "when": "env.HOME"}, "when must be a field"),
({"id": "a b", "place": "tags", "text": "x"}, "id invalid"),
]
with tempfile.TemporaryDirectory() as td:
for i, (bit, 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}", [bit])))
self.assertIn(why, str(cm.exception))
with self.assertRaises(ManifestError) as cm:
validate_manifest(_write(pathlib.Path(td) / "many", _mf("many", [
{"id": f"b{i}", "place": "tags", "text": "x"} for i in range(7)])))
self.assertIn("at most 6", str(cm.exception))
def test_fingerprint_unchanged_without_card(self):
"""No ``card`` 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": {}})
mf = validate_manifest(root)
self.assertNotIn("card", mf.get("ui") or {})
fp = capability_fingerprint(mf)
raw = json.loads((root / "plugin.json").read_text())
raw["ui"]["card"] = []
(root / "plugin.json").write_text(json.dumps(raw))
self.assertEqual(capability_fingerprint(validate_manifest(root)), fp)
def test_capability_line(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "plan", _mf("plan", [WEEK])))
lines = [i["label"] for i in capability_summary(mf)]
self.assertIn("Adds `week` to the conversation cards (cost)", lines)
class CardRoutesTest(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(self):
a = _write(self.root / "plan", _mf("plan", [WEEK]))
b = _write(self.root / "evox", _mf("evox", [
{"id": "energy", "place": "tags", "text": "{local.wh|wh}", "icon": "zap", "tone": "plain"}]))
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)
card = r.json()["ui"]["card"]
# every active plugin's, in plugin order (the store's: by id)
self.assertEqual([(x["pluginId"], x["id"]) for x in card], [("evox", "energy"), ("plan", "week")])
week = card[1]
self.assertEqual(week["pluginName"], "Plan")
self.assertEqual(week["vis"]["key"], "planPct")
self.assertEqual(week["text"], "{planPct.week|apct} wk")
if __name__ == "__main__":
unittest.main()