315 lines
15 KiB
Python
315 lines
15 KiB
Python
"""The ``graph.read`` capability (plugins/graphdata.py) and the ``fill`` page
|
|
flag — what the Graph plugin needs since the dashboard left the core
|
|
(2026-11-25)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
from fastapi.testclient import TestClient
|
|
|
|
import main
|
|
from plugins import graphdata
|
|
from plugins.manifest import (ManifestError, capability_fingerprint, capability_summary,
|
|
requires_operator, validate_manifest)
|
|
from plugins.store import OWNER_UID, PluginStore
|
|
from toolproxy import access
|
|
|
|
|
|
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" / "g.html").write_text("<p>g</p>", encoding="utf-8")
|
|
(root / "handlers").mkdir(exist_ok=True)
|
|
(root / "handlers" / "g.py").write_text("print('{}')\n", encoding="utf-8")
|
|
return root
|
|
|
|
|
|
MANIFEST = {
|
|
"schema": 1, "id": "gr", "name": "Graph",
|
|
"ui": {"pages": [{"id": "graph", "label": "Graph", "nav": "dashboards",
|
|
"html": "ui/g.html", "fill": True}]},
|
|
"actions": {"graph": {"script": "handlers/g.py"}},
|
|
"capabilities": ["graph.read"],
|
|
}
|
|
|
|
|
|
class TestManifest(unittest.TestCase):
|
|
def test_graph_read_is_a_privileged_operator_capability(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "gr", MANIFEST))
|
|
self.assertEqual(mf["capabilities"], ["graph.read"])
|
|
self.assertTrue(requires_operator(mf))
|
|
cap = [c for c in capability_summary(mf) if c["kind"] == "capability"]
|
|
self.assertTrue(cap[0]["privileged"])
|
|
|
|
def test_fill_is_kept_only_when_set(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = validate_manifest(_write(pathlib.Path(td) / "a", MANIFEST))
|
|
self.assertIs(mf["ui"]["pages"][0]["fill"], True)
|
|
plain = json.loads(json.dumps(MANIFEST))
|
|
del plain["ui"]["pages"][0]["fill"]
|
|
mf2 = validate_manifest(_write(pathlib.Path(td) / "b", plain))
|
|
# No key at all: an installed page's fingerprint must not move.
|
|
self.assertNotIn("fill", mf2["ui"]["pages"][0])
|
|
self.assertNotEqual(capability_fingerprint(mf), capability_fingerprint(mf2))
|
|
|
|
def test_unknown_capability_still_refused(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
bad = dict(MANIFEST, capabilities=["graph.write"])
|
|
with self.assertRaises(ManifestError):
|
|
validate_manifest(_write(pathlib.Path(td) / "gr", bad))
|
|
|
|
|
|
class _UiState:
|
|
def __init__(self, values: dict[str, dict]):
|
|
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 TestLegacyPrefs(unittest.TestCase):
|
|
def test_reads_the_old_filters_and_physics_switch(self):
|
|
deps = type("D", (), {})()
|
|
deps.ui_state = _UiState({
|
|
"ai-agent-graph-filters": {"hidden": ["conversation", "subagent", "plan", "bogus"]},
|
|
"ai-agent-visibility": {"hidden": ["cost", "graphPhysics"]},
|
|
})
|
|
self.assertEqual(graphdata.legacy_prefs(deps),
|
|
{"hidden": ["conversation", "subagent", "plan"], "physics": False})
|
|
|
|
def test_defaults_when_nothing_was_saved(self):
|
|
deps = type("D", (), {})()
|
|
deps.ui_state = _UiState({})
|
|
self.assertEqual(graphdata.legacy_prefs(deps), {"hidden": [], "physics": True})
|
|
|
|
|
|
def _lists():
|
|
"""The list endpoints, as their bodies (no @_json_in_worker), and the
|
|
plans and memories the `plans` and `memories` plugins hand their bridges."""
|
|
return {
|
|
"projects.routes.projects_list": lambda deps, caller: {"projects": [{"dir": "brain", "name": "Brain", "costs": {}}]},
|
|
"plugins.services_bridge.list_services": lambda deps: [{"dir": "mail", "name": ""}],
|
|
"conversations.routes.conversations_list": lambda deps, caller, limit, archived: {"conversations": [
|
|
{"id": "019a-c1", "sessionId": "s1", "title": "auto", "meta": {"title": "Fix search", "state": "running",
|
|
"projects": ["brain"], "services": [], "account": "personal"}, "cost": 3.2},
|
|
{"id": "019a-c2", "sessionId": "", "title": "Untagged", "meta": {}},
|
|
]},
|
|
"plugins.plans_bridge.list_plans": lambda deps: [{"slug": "p1", "title": "", "sessionId": "s1",
|
|
"conversationIds": ["s9", None], "projects": ["brain"]}],
|
|
"plugins.memories_bridge.list_memories": lambda deps: [{"slug": "m1", "name": "M", "links": ["m2"],
|
|
"originSessionId": "s1", "content": "secret text"}],
|
|
"conversations.routes.subagents_list": lambda deps, caller: {"subagents": [
|
|
{"id": "019a-a1", "parentId": "019a-c1", "rootId": "019a-c1", "description": "Explore code",
|
|
"state": "running", "cost": 1}]},
|
|
}
|
|
|
|
|
|
class TestBridge(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app)
|
|
|
|
def _with_plugin(self, td, manifest=MANIFEST):
|
|
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_build_keeps_only_what_the_graph_draws(self):
|
|
patches = [patch(k, v) for k, v in _lists().items()]
|
|
deps = main.app.state.ai
|
|
for p in patches:
|
|
p.start()
|
|
try:
|
|
with patch.object(deps, "ui_state", _UiState({})):
|
|
out = graphdata.build(deps)
|
|
finally:
|
|
for p in patches:
|
|
p.stop()
|
|
self.assertEqual(out["projects"], [{"dir": "brain", "name": "Brain"}])
|
|
self.assertEqual(out["services"], [{"dir": "mail", "name": "mail"}])
|
|
self.assertEqual(out["conversations"][0], {"id": "019a-c1", "sessionId": "s1", "title": "Fix search",
|
|
"running": True, "projects": ["brain"], "services": []})
|
|
self.assertEqual(out["conversations"][1]["title"], "Untagged")
|
|
self.assertEqual(out["plans"][0]["sessions"], ["s1", "s9"])
|
|
self.assertEqual(out["plans"][0]["title"], "p1")
|
|
self.assertEqual(out["memories"], [{"slug": "m1", "name": "M", "links": ["m2"], "projects": [],
|
|
"services": [], "originSessionId": "s1"}])
|
|
self.assertEqual(out["subagents"][0]["label"], "Explore code")
|
|
self.assertTrue(out["subagents"][0]["running"])
|
|
self.assertEqual(out["prefs"], {"hidden": [], "physics": True})
|
|
|
|
def test_every_list_route_can_be_called(self):
|
|
"""Each list route's required parameters are ones the bridge passes —
|
|
a route that grows one (services_list took ``deps``) must not 500
|
|
the bridge again. Checked on the real functions, not stubs."""
|
|
import inspect
|
|
|
|
from conversations.routes import conversations_list, subagents_list
|
|
from projects.routes import projects_list
|
|
passed = {"deps", "caller", "limit", "archived"}
|
|
for fn in (projects_list, conversations_list, subagents_list):
|
|
sig = inspect.signature(graphdata._unwrap(fn))
|
|
required = {n for n, prm in sig.parameters.items()
|
|
if prm.default is inspect.Parameter.empty}
|
|
self.assertLessEqual(required, passed, fn.__name__)
|
|
|
|
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, "gr", ttl=600)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch("plugins.graphdata.build", return_value={"conversations": [], "prefs": {}}):
|
|
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["conversations"], [])
|
|
|
|
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.graphdata.build") as build:
|
|
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 403)
|
|
build.assert_not_called()
|
|
|
|
def test_needs_the_capability(self):
|
|
deps = main.app.state.ai
|
|
with tempfile.TemporaryDirectory() as td:
|
|
store = self._with_plugin(td, dict(MANIFEST, capabilities=[]))
|
|
tok = access.mint_handler(OWNER_UID, "gr", ttl=600)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch("plugins.graphdata.build") as build:
|
|
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph",
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
self.assertEqual(r.status_code, 403)
|
|
self.assertIn("graph.read", r.json()["error"]["message"])
|
|
build.assert_not_called()
|
|
|
|
|
|
|
|
def _card(cid, sid, ended, *keys):
|
|
rs = [{"kind": k.split(":", 1)[0], "id": k.split(":", 1)[1], "label": k} for k in keys]
|
|
return {"id": cid, "sessionId": sid, "title": cid.upper(), "endedAt": ended,
|
|
"meta": {"state": "finished", "resources": rs}}
|
|
|
|
|
|
class _Registry:
|
|
version = 1
|
|
|
|
def descriptors(self):
|
|
return [{"id": "pr", "label": "Pull request", "icon": "git-pull-request", "color": "sky",
|
|
"stateTones": {"open": "emerald"}, "clickAction": "open", "priority": 1,
|
|
"hueRole": None, "pluginId": "github"},
|
|
{"id": "slack", "label": "Slack thread", "icon": "slack", "color": "fuchsia",
|
|
"stateTones": None, "clickAction": "open", "priority": 2, "hueRole": None,
|
|
"pluginId": "slack"}]
|
|
|
|
|
|
class TestRelated(unittest.TestCase):
|
|
"""``graph.read``'s ``hub/graph/related`` — the Details drawer's *Related
|
|
conversations* card, the core's until 2026-11-27 (plugins/graphdata.related)."""
|
|
|
|
def setUp(self):
|
|
from conversations import related as related_mod
|
|
self.cards = [
|
|
_card("019a-a", "sa", "2026-10-10", "linear:INS-1", "pr:o/r#1", "branch:main"),
|
|
_card("019a-b", "sb", "2026-10-11", "pr:o/r#1"),
|
|
_card("019a-c", "sc", "2026-10-09", "linear:INS-1", "pr:o/r#1"),
|
|
_card("019a-d", "sd", "2026-10-12", "branch:main"),
|
|
]
|
|
v = type("V", (), {"summaries_version": 1, "version": 1})()
|
|
self.deps = type("D", (), {"store": v, "meta_store": v, "profile_store": v})()
|
|
related_mod._index_memo.clear()
|
|
self.addCleanup(related_mod._index_memo.clear)
|
|
for target, new in (("conversations.catalog._conversation_cards", lambda deps, full: self.cards),
|
|
("conversations.routes._public_id", lambda deps, i: {"sa": "019a-a"}.get(i, i)),
|
|
("plugins.resources.registry", lambda deps: _Registry())):
|
|
p = patch(target, new)
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
|
|
def test_most_shared_first_with_the_kinds_looks(self):
|
|
out = graphdata.related(self.deps, "sa") # a session id names its conversation
|
|
self.assertEqual(out["id"], "019a-a")
|
|
self.assertEqual([r["id"] for r in out["related"]], ["019a-c", "019a-b"])
|
|
self.assertEqual(out["related"][0]["sessionId"], "sc")
|
|
self.assertEqual(out["related"][0]["title"], "019A-C")
|
|
self.assertEqual(out["related"][0]["state"], "finished")
|
|
self.assertEqual({s["kind"] for s in out["related"][0]["shared"]}, {"linear", "pr"})
|
|
# Only the kinds it shares, and only what a pill draws; linear has no
|
|
# active plugin here (the card's own fallback), the trunk relates nothing.
|
|
self.assertEqual(out["kinds"], {"pr": {"label": "Pull request", "icon": "git-pull-request",
|
|
"color": "sky"}})
|
|
|
|
def test_an_unknown_conversation_relates_nothing(self):
|
|
self.assertEqual(graphdata.related(self.deps, "019a-zzz"),
|
|
{"id": "019a-zzz", "related": [], "kinds": {}})
|
|
|
|
|
|
class TestRelatedBridge(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tc = TestClient(main.app)
|
|
|
|
def _get(self, td, tok, manifest=MANIFEST, **params):
|
|
deps = main.app.state.ai
|
|
store = PluginStore(pathlib.Path(td) / "data")
|
|
store.install(OWNER_UID, str(_write(pathlib.Path(td) / "src", manifest)),
|
|
is_owner=True, approve=True)
|
|
with patch.object(deps, "plugin_store", store), \
|
|
patch("plugins.graphdata.related",
|
|
side_effect=lambda d, i: {"id": i, "related": [], "kinds": {}}) as rel:
|
|
r = self.tc.get("/proxy/tools/plugins/gr/hub/graph/related", params=params,
|
|
headers={"Authorization": f"Bearer {tok}"})
|
|
return r, rel
|
|
|
|
def test_owner_reads_it(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
r, rel = self._get(td, access.mint_handler(OWNER_UID, "gr", ttl=600), id=" 019a-a ")
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"id": "019a-a", "related": [], "kinds": {}})
|
|
self.assertEqual(rel.call_args.args[1], "019a-a")
|
|
|
|
def test_needs_an_id(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
r, rel = self._get(td, access.mint_handler(OWNER_UID, "gr", ttl=600))
|
|
self.assertEqual(r.status_code, 400)
|
|
rel.assert_not_called()
|
|
|
|
def test_a_guest_never_does(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
r, rel = self._get(td, access.mint("cel", ttl=600), id="019a-a")
|
|
self.assertEqual(r.status_code, 403)
|
|
rel.assert_not_called()
|
|
|
|
def test_needs_the_capability(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
r, rel = self._get(td, access.mint_handler(OWNER_UID, "gr", ttl=600),
|
|
dict(MANIFEST, capabilities=[]), id="019a-a")
|
|
self.assertEqual(r.status_code, 403)
|
|
self.assertIn("graph.read", r.json()["error"]["message"])
|
|
rel.assert_not_called()
|
|
|
|
def test_the_core_card_and_route_are_gone(self):
|
|
self.assertNotIn("/api/conversations/{id}/related", main.app.openapi()["paths"])
|
|
front = pathlib.Path(__file__).resolve().parent.parent / "frontend" / "src"
|
|
if front.is_dir():
|
|
self.assertFalse((front / "business" / "conversations" / "components"
|
|
/ "RelatedConversations.tsx").exists())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|