Files
ai-agent/backend/test_plugin_widget_platform.py
gabrielvidalandClaude Opus 5.5 f21db5ed56 feat(home): plugin tiles bring their own links — no core links into plan/activity pages
The owner's home-strip tiles were already the plan-usage and activity plugins'
(`provides: home.tiles`, 2026-11-26); this drops what the core still carried
for them now that /dashboards/plan and /dashboards/activity are gone:

- ProfileUsageCard: the core Meter is a guest's own Claude gauge only (always
  /settings/logins/claude — the owner's /dashboards/plan branch was
  unreachable); Stat no longer defaults to /dashboards/activity; the core
  DEFAULT_BENCH naming the activity plugin's `tokens` id is gone (the tile's
  own `defaultBench` benches it).
- PluginTile: every kind links to the tile's `to` (its plugin's page), the
  burn gauge included again (BurnGauge lost its link with plugin-links); a
  tile without `to` links nowhere instead of to "/".
- home.tiles: two fields the plugins already sent and the sanitizer dropped —
  `stashLabel` (≤ 48: the bench's name, "$ today" for "Today", as the core
  tiles had) and the burn tile's `noReading` ("no reading", not a $0 dial).
  Schema + openapi.json + generated HomeTile follow.
- French: "Plan usage dashboard" goes with its only use.
- Docs: plugins.md / CLAUDE.md / usage-calibration.md / usagedata.py no
  longer say the old paths redirect.

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

281 lines
14 KiB
Python

"""The widget-to-plugin platform: the new slot places, the optional
``ui.slots[]`` / ``ui.toolCards[]`` keys (label, defaultStashed, vis, events,
match.hasField), ``provides: home.tiles`` + ``GET /api/plugins/home-tiles``
and the two read-only hub bridges a ``home.tiles`` handler reads."""
from __future__ import annotations
import json
import os
import pathlib
import sys
import tempfile
import types
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 import home_tiles # 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", "")}
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("<p>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
class ManifestTest(unittest.TestCase):
def test_new_places_and_optional_slot_keys(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "a", {
"schema": 1, "id": "a", "name": "A",
"ui": {"slots": [
{"id": "home", "where": "home.section", "html": "ui/s.html"},
{"id": "pin", "where": "conversation.pinned", "html": "ui/s.html"},
{"id": "foot", "where": "conversation.threadFooter", "html": "ui/s.html"},
{"id": "giz", "where": "conversation.gizmos", "html": "ui/s.html", "height": 32},
{"id": "det", "where": "conversation.details", "html": "ui/s.html",
"label": "Estimated footprint", "defaultStashed": True,
"vis": {"key": "footprint", "label": "Footprint", "hint": "carbon"},
"events": ["askform", "meta", "askform"]},
]},
}))
slots = {s["id"]: s for s in mf["ui"]["slots"]}
self.assertEqual(slots["home"], {"id": "home", "where": "home.section",
"html": "ui/s.html", "height": 120})
d = slots["det"]
self.assertEqual(d["label"], "Estimated footprint")
self.assertTrue(d["defaultStashed"])
self.assertEqual(d["vis"], {"key": "footprint", "label": "Footprint", "hint": "carbon"})
self.assertEqual(d["events"], ["askform", "meta"])
def test_bad_optional_keys_refused(self):
with tempfile.TemporaryDirectory() as td:
for bad in ({"label": "x" * 49}, {"vis": {"key": "bad key"}}, {"events": ["nope"]},
{"defaultStashed": "yes"}):
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / "b", {
"schema": 1, "id": "b", "name": "B",
"ui": {"slots": [{"id": "s", "where": "conversation.details",
"html": "ui/s.html", **bad}]},
}))
def test_tool_card_has_field_vis_events(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "c", {
"schema": 1, "id": "c", "name": "C",
"ui": {"toolCards": [
{"id": "deploy", "match": {"tool": "shell", "hasField": "deploy"},
"html": "ui/s.html", "inThread": True,
"vis": {"key": "deployCards", "label": "Deploy cards", "hint": "", "defaultOff": True},
"events": ["transcript"]},
{"id": "plain", "match": {"tool": "shell"}, "html": "ui/s.html"},
]},
}))
dep, plain = mf["ui"]["toolCards"]
self.assertEqual(dep["match"]["hasField"], "deploy")
self.assertTrue(dep["vis"]["defaultOff"])
self.assertEqual(dep["events"], ["transcript"])
self.assertNotIn("hasField", plain["match"])
self.assertNotIn("vis", plain)
self.assertNotIn("events", plain)
with self.assertRaises(ManifestError):
validate_manifest(_write(pathlib.Path(td) / "d", {
"schema": 1, "id": "d", "name": "D",
"ui": {"toolCards": [{"id": "x", "match": {"tool": "shell", "hasField": "nope"},
"html": "ui/s.html"}]},
}))
def test_fingerprint_unchanged_without_new_keys(self):
"""A manifest that sets none of the new keys normalizes exactly as
before: no new key in its ``ui`` (the approval fingerprint)."""
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "e", {
"schema": 1, "id": "e", "name": "E",
"ui": {"slots": [{"id": "s", "where": "conversation.details", "html": "ui/s.html"}],
"toolCards": [{"id": "t", "match": {"tool": "shell"}, "html": "ui/s.html"}]},
}))
self.assertEqual(set(mf["ui"]["slots"][0]), {"id", "where", "html", "height"})
self.assertEqual(set(mf["ui"]["toolCards"][0]), {"id", "label", "match", "html", "height"})
self.assertEqual(set(mf["ui"]["toolCards"][0]["match"]), {"tool", "commandRegex"})
fp = capability_fingerprint(mf)
self.assertEqual(fp, capability_fingerprint(json.loads(json.dumps(mf))))
def test_home_tiles_provides(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "f", {
"schema": 1, "id": "f", "name": "F",
"actions": {"tiles": {"script": "t.py"}},
"provides": {"home.tiles": "tiles"},
}, {"t.py": "print('{}')\n"}))
self.assertEqual(mf["provides"], {"home.tiles": "tiles"})
def test_provider_plugin_may_declare_slots(self):
"""The EVOX2 provider plugin ships ``conversation.details`` /
``conversation.threadFooter`` slots."""
evox = pathlib.Path.home() / "projects" / "ai-agent-plugins" / "plugins" / "provider-evox2"
if not (evox / "plugin.json").exists():
self.skipTest("ai-agent-plugins checkout not here")
with tempfile.TemporaryDirectory() as td:
import shutil
dst = pathlib.Path(td) / "provider-evox2"
shutil.copytree(evox, dst, ignore=shutil.ignore_patterns("node_modules", ".git"))
raw = json.loads((dst / "plugin.json").read_text())
raw.setdefault("ui", {})["slots"] = [
{"id": "conv-local-energy", "where": "conversation.details", "html": "ui/s.html",
"label": "EVOX2 time"},
{"id": "gen-progress", "where": "conversation.threadFooter", "html": "ui/s.html"},
]
(dst / "ui").mkdir(exist_ok=True)
(dst / "ui" / "s.html").write_text("<p/>")
(dst / "plugin.json").write_text(json.dumps(raw))
mf = validate_manifest(dst)
self.assertEqual(mf["kind"], "provider")
self.assertEqual([s["id"] for s in mf["ui"]["slots"]], ["conv-local-energy", "gen-progress"])
class HomeTilesCleanTest(unittest.TestCase):
def test_kinds_sanitized(self):
got = home_tiles.clean_tiles("plan-usage", {"tiles": [
{"id": "h5:personal", "kind": "arc", "label": "5-hour", "pct": 42.5,
"resetsAt": 1764200000, "to": "/plugins/plan-usage/board", "junk": 1},
{"id": "burn:personal", "kind": "burn", "label": "Burn", "usdPerHour": 3.2,
"neededUsdPerHour": 4.0, "windowMinutes": 60, "to": "/plugins/plan-usage/board",
"noReading": True},
{"id": "today", "kind": "stat", "label": "Today", "valueUsd": 12.5,
"stashLabel": " $ today ", "noReading": True},
{"id": "spark", "kind": "sparkline", "label": "7 days", "isCost": True,
"days": [{"date": "2026-11-25", "value": 3}, {"date": "bad", "value": 1}]},
{"id": "budget:cel", "kind": "bar", "label": "Cel", "value": 5, "max": 10, "text": "$5 / $10"},
{"id": "bad kind", "kind": "arc", "label": "x"},
{"id": "x", "kind": "pie", "label": "x"},
{"id": "y", "kind": "arc", "label": "y", "to": "//evil.com"},
{"id": "z", "kind": "stat", "label": "z"},
]})
ids = [t["id"] for t in got]
self.assertEqual(ids, ["h5:personal", "burn:personal", "today", "spark", "budget:cel", "y"])
self.assertNotIn("junk", got[0])
self.assertEqual(got[0]["to"], "/plugins/plan-usage/board")
self.assertNotIn("to", got[-1])
self.assertEqual(len(got[3]["days"]), 1)
self.assertEqual(got[0]["pluginId"], "plan-usage")
# The burn tile keeps its link and its "no reading"; the bench name
# is trimmed; noReading is a burn field only.
self.assertEqual(got[1]["to"], "/plugins/plan-usage/board")
self.assertIs(got[1]["noReading"], True)
self.assertEqual(got[2]["stashLabel"], "$ today")
self.assertNotIn("noReading", got[2])
self.assertNotIn("stashLabel", got[0])
def test_stash_label_cut_and_typed(self):
got = home_tiles.clean_tiles("activity", {"tiles": [
{"id": "a", "kind": "stat", "label": "A", "value": "1", "stashLabel": "x" * 80},
{"id": "b", "kind": "stat", "label": "B", "value": "2", "stashLabel": 7},
{"id": "c", "kind": "burn", "label": "C", "usdPerHour": 0, "noReading": "yes"},
]})
self.assertEqual(len(got[0]["stashLabel"]), 48)
self.assertNotIn("stashLabel", got[1])
self.assertNotIn("noReading", got[2])
class HomeTilesRouteTest(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
home_tiles.invalidate()
self.client = TestClient(main.app)
def tearDown(self):
self.deps.plugin_store = self.orig
home_tiles.invalidate()
self.td.cleanup()
def test_route_runs_provider_and_dedups(self):
script = ("import json, sys\n"
"p = json.load(sys.stdin)\n"
"print(json.dumps({'tiles': ["
"{'id': 'today', 'kind': 'stat', 'label': 'Today', 'value': p.get('payload', p).get('profileScope', '?')},"
"{'id': 'today', 'kind': 'stat', 'label': 'dup', 'value': '2'}]}))\n")
plug = _write(self.root / "tiles", {
"schema": 1, "id": "tiles", "name": "Tiles",
"actions": {"home_tiles": {"script": "t.py"}},
"provides": {"home.tiles": "home_tiles"},
}, {"t.py": script})
self.store.install(OWNER_UID, str(plug), is_owner=True)
r = self.client.get("/api/plugins/home-tiles?profileScope=work&scope=profile:work", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
tiles = r.json()["tiles"]
self.assertEqual(len(tiles), 1)
self.assertEqual(tiles[0]["id"], "today")
self.assertEqual(tiles[0]["pluginId"], "tiles")
def test_route_empty_without_provider(self):
r = self.client.get("/api/plugins/home-tiles", headers=OWNER_H)
self.assertEqual(r.status_code, 200)
self.assertEqual(r.json(), {"tiles": []})
def test_bridges_owner_only_and_capability(self):
from unittest.mock import patch
from toolproxy import access
plug = _write(self.root / "br", {
"schema": 1, "id": "br", "name": "Br",
"capabilities": ["usage.read", "activity.read"],
})
self.store.install(OWNER_UID, str(plug), is_owner=True, approve=True)
owner = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'br', ttl=600)}"}
guest = {"Authorization": f"Bearer {access.mint('cel', ttl=600)}"}
with patch("usage.routes.daily_usage", return_value={"days": []}) as du:
r = self.client.get("/proxy/tools/plugins/br/hub/activity/daily?days=999&scope=profile:work&tzOffset=60",
headers=owner)
g = self.client.get("/proxy/tools/plugins/br/hub/activity/daily", headers=guest)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json(), {"days": []})
self.assertEqual(du.call_args.args[1:], (90, 60, "profile:work"))
self.assertEqual(g.status_code, 403)
r = self.client.get("/proxy/tools/plugins/br/hub/usage/home?profileScope=work&composerHarness=claude",
headers=owner)
self.assertEqual(r.status_code, 200, r.text)
body = r.json()
for k in ("limits", "burn", "accounts", "profiles"):
self.assertIn(k, body)
self.assertIn("accounts", body["limits"])
self.assertEqual(body["composerHarness"], "claude")
self.assertEqual(self.client.get("/proxy/tools/plugins/br/hub/usage/home", headers=guest).status_code, 403)
if __name__ == "__main__":
unittest.main()