Files
ai-agent/backend/test_plugin_footprint.py
gabrielvidalandClaude Opus 5.5 6f6774ef94 feat(plugins): the Environment dashboard leaves the core for the environment plugin
The carbon / water / energy dashboard (business/dashboards/pages/Environment.tsx,
469 lines) is now the `environment` live plugin (ai-agent-plugins). What the
core keeps for it:

- footprint.read, a new owner-only hub capability: GET
  /proxy/tools/plugins/<id>/hub/footprint?account=<scope>&range=<key> returns
  each conversation's estimated footprint (id, time, family, projects,
  co2eKg, waterL, energyKwh) filtered by the dashboards' profile scope
  (ProfileStore.selector, countsInScope's server twin) and range ("since
  subscription" read from the settings' account plans), plus the profiles
  for the page's switch. plugins/footprintdata.py is lib/footprint.ts's
  Python twin; test_plugin_footprint.py reads the TS constants so they can't
  drift. lib/footprint.ts stays (the conversation's Footprint card, guest
  Stats).
- A plugin page's init carries `scope` (the app's profile scope), so a
  dashboard plugin opens on the profile the app is on.
- /dashboards/environnement and /dashboard/environnement redirect to
  /plugins/environment/environment.

Removed: the page, its lazy export, route, nav and drawer entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 17:41:46 +01:00

183 lines
8.1 KiB
Python

"""The ``footprint.read`` capability (plugins/footprintdata.py) — what the
Environment plugin draws since the dashboard left the core (2026-11-25)."""
from __future__ import annotations
import json
import pathlib
import re
import tempfile
import unittest
from unittest.mock import patch
from fastapi.testclient import TestClient
import main
from plugins import footprintdata as fd
from plugins.manifest import capability_summary, requires_operator, validate_manifest
from plugins.store import OWNER_UID, PluginStore
from toolproxy import access
FRONT = pathlib.Path(__file__).resolve().parent.parent / "frontend" / "src"
def _write(root: pathlib.Path, manifest: dict) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
(root / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
(root / "ui").mkdir(exist_ok=True)
(root / "ui" / "e.html").write_text("<p>e</p>", encoding="utf-8")
(root / "handlers").mkdir(exist_ok=True)
(root / "handlers" / "e.py").write_text("print('{}')\n", encoding="utf-8")
return root
MANIFEST = {
"schema": 1, "id": "env", "name": "Environment",
"ui": {"pages": [{"id": "environment", "label": "Environment", "nav": "dashboards",
"html": "ui/e.html"}]},
"actions": {"footprint": {"script": "handlers/e.py"}},
"capabilities": ["footprint.read"],
}
class TestTwin(unittest.TestCase):
"""The Python estimate is lib/footprint.ts's: read the TS constants."""
def setUp(self):
self.ts = (FRONT / "lib" / "footprint.ts").read_text(encoding="utf-8")
def _const(self, name):
m = re.search(rf"const {name} = ([0-9.+ ]+);", self.ts)
self.assertIsNotNone(m, name)
return eval(m.group(1)) # noqa: S307 — digits, dots and + only
def test_factors_match(self):
for fam, (i, o) in fd.FACTORS.items():
m = re.search(rf"{fam}: \{{ input: (\d+), output: (\d+) \}}", self.ts)
self.assertIsNotNone(m, fam)
self.assertEqual((int(m.group(1)), int(m.group(2))), (i, o), fam)
self.assertEqual(len(re.findall(r"^\s+\w+: \{ input: \d+, output: \d+ \},", self.ts, re.M)),
len(fd.FACTORS))
def test_constants_match(self):
self.assertAlmostEqual(self._const("CACHE_READ_FACTOR"), fd.CACHE_READ_FACTOR)
self.assertAlmostEqual(self._const("CARBON_INTENSITY_KG_PER_KWH"), fd.CARBON_INTENSITY_KG_PER_KWH)
self.assertAlmostEqual(self._const("WUE_L_PER_KWH"), fd.WUE_L_PER_KWH)
self.assertAlmostEqual(self._const("FR_GRID_KG_PER_KWH"), fd.FR_GRID_KG_PER_KWH)
self.assertAlmostEqual(self._const("OFFSITE_WUE_L_PER_KWH"), fd.OFFSITE_WUE_L_PER_KWH)
def test_default_subscriptions_match_settings(self):
ts = (FRONT / "settings.ts").read_text(encoding="utf-8")
for k, v in fd.DEFAULT_SUBSCRIPTIONS.items():
m = re.search(rf'"?{re.escape(k)}"?: \{{ plan: "(\w+)", monthlyCost: [\d.]+, startDate: "([\d-]*)" \}}', ts)
self.assertIsNotNone(m, k)
self.assertEqual((m.group(1), m.group(2)), (v["plan"], v["startDate"]), k)
class TestEstimate(unittest.TestCase):
def test_opus_tokens(self):
fp = fd.conv_footprint({"models": ["claude-opus-5-5"],
"usage": {"input": 1e6, "output": 1e6, "cacheRead": 1e6, "cacheWriteTokens": 0}})
g = 1e6 * 78 / 1e6 + 0.08e6 * 78 / 1e6 + 1e6 * 1652 / 1e6
self.assertAlmostEqual(fp["co2eKg"], g / 1000)
self.assertAlmostEqual(fp["energyKwh"], g / 1000 / 0.287)
def test_local_only_is_measured(self):
fp = fd.conv_footprint({"model": "qwen", "local": {"wh": 100}, "byModel": {"qwen": {"usage": {"output": 9}}}})
self.assertAlmostEqual(fp["energyKwh"], 0.1)
self.assertAlmostEqual(fp["co2eKg"], 0.1 * 0.0461)
def test_nothing_is_none(self):
self.assertIsNone(fd.conv_footprint({"model": "x"}))
def test_family(self):
self.assertEqual(fd.model_family("claude-sonnet-5-5"), "sonnet")
self.assertEqual(fd.model_family("gpt-6-sol"), "opus")
class _UiState:
def __init__(self, values):
self.values = values
def get(self, key):
v = self.values.get(key)
return json.dumps({"state": v, "version": 0}) if v is not None else None
class TestBuild(unittest.TestCase):
CARDS = [
{"id": "c1", "endedAt": "2026-11-20T10:00:00Z", "models": ["claude-opus-5-5"],
"usage": {"input": 1000, "output": 1000}, "meta": {"account": "personal", "profile": "personal",
"projects": ["brain"]}},
{"id": "c2", "endedAt": "2026-10-01T10:00:00Z", "models": ["claude-sonnet-5-5"],
"usage": {"input": 1000, "output": 1000}, "meta": {"account": "personal", "profile": "personal"}},
{"id": "c3", "endedAt": "2026-11-20T10:00:00Z", "models": ["gpt"], "meta": {"account": "work",
"profile": "work"}},
]
def _build(self, account, rk, settings=None):
deps = main.app.state.ai
with patch.object(deps, "ui_state", _UiState({"ai-agent-settings": settings or {}})), \
patch("plugins.footprintdata._cards", return_value=self.CARDS):
return fd.build(deps, account, rk, now=1795000000.0)
def test_scope_and_range(self):
out = self._build("all", "all")
self.assertEqual([r["id"] for r in out["conversations"]], ["c1", "c2"]) # c3 has no usage
self.assertEqual(out["conversations"][0]["projects"], ["brain"])
self.assertTrue(out["profiles"])
def test_subscription_range(self):
out = self._build("all", "sub", {"accounts": {"personal": {"plan": "max20", "startDate": "2026-10-31"}}})
# earliest configured seat: work's default 2026-09-01
self.assertEqual(out["subscriptionStart"], "2026-09-01")
out = self._build("personal", "sub", {"accounts": {"personal": {"plan": "max20", "startDate": "2026-10-31"}}})
self.assertEqual(out["subscriptionStart"], "2026-10-31")
self.assertEqual([r["id"] for r in out["conversations"]], ["c1"])
def test_unknown_range_reads_sub(self):
self.assertEqual(self._build("all", "bogus")["range"], "sub")
class TestBridge(unittest.TestCase):
def setUp(self):
self.tc = TestClient(main.app)
def _with_plugin(self, td):
store = PluginStore(pathlib.Path(td) / "data")
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", MANIFEST)), is_owner=True, approve=True)
return store
def test_privileged(self):
with tempfile.TemporaryDirectory() as td:
mf = validate_manifest(_write(pathlib.Path(td) / "env", MANIFEST))
self.assertTrue(requires_operator(mf))
self.assertTrue([c for c in capability_summary(mf) if c["kind"] == "capability"][0]["privileged"])
def test_owner_reads_it(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = self._with_plugin(td)
tok = access.mint_handler(OWNER_UID, "env", ttl=600)
with patch.object(deps, "plugin_store", store), \
patch("plugins.footprintdata.build", return_value={"conversations": []}) as b:
r = self.tc.get("/proxy/tools/plugins/env/hub/footprint?account=profile:work&range=7d",
headers={"Authorization": f"Bearer {tok}"})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(b.call_args.args[1:], ("profile:work", "7d"))
def test_a_guest_never_does(self):
deps = main.app.state.ai
with tempfile.TemporaryDirectory() as td:
store = self._with_plugin(td)
tok = access.mint("cel", ttl=600)
with patch.object(deps, "plugin_store", store), patch("plugins.footprintdata.build") as b:
r = self.tc.get("/proxy/tools/plugins/env/hub/footprint",
headers={"Authorization": f"Bearer {tok}"})
self.assertEqual(r.status_code, 403)
b.assert_not_called()
if __name__ == "__main__":
unittest.main()