287 lines
13 KiB
Python
287 lines
13 KiB
Python
"""The core's half of the Services catalogue since it moved fully into the
|
|
``services`` live plugin (2026-11-28): the ``services.index`` provider and its
|
|
bridge (``plugins/services_bridge.py``), ``GET /api/plugins/services-index``,
|
|
the ``services.read`` env, the plugin's hub bridges (``hub/services/commits``
|
|
and ``hub/conversations?service=``) and the manifest's ``nav: "projects"`` /
|
|
``tag: "service"``."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from types import SimpleNamespace
|
|
from unittest.mock import patch
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t", "WORKSPACE": TMP, "REPO_DIR": TMP,
|
|
"META_PATH": TMP / "meta.json", "USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"PROJECTS_DIR": TMP / "projects", "SERVICES_DIR": TMP / "services",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ.setdefault(k, str(v))
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
import servicesdir # noqa: E402
|
|
from plugins import services_bridge # noqa: E402
|
|
from plugins.manifest import (ManifestError, capability_summary, requires_operator, # noqa: E402
|
|
validate_manifest)
|
|
from plugins.runner import run_script # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from toolproxy import access # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
INDEX = r'''
|
|
import json, os, sys
|
|
sys.stdin.read()
|
|
print(json.dumps({"services": [
|
|
{"dir": "web", "name": "Web", "description": "The site", "urls": ["https://web.example"],
|
|
"containerCount": 2, "containers": ["a", "b"], "auth": "auth", "profiles": ["dev"],
|
|
"goal": {"done": 1, "total": 3}, "updatedAt": "2026-11-27T10:00:00Z", "evil": "<nope>",
|
|
"hasCompose": 1, "routerCount": True},
|
|
{"dir": "api", "auth": "weird", "goal": {"done": "x"}},
|
|
{"dir": "web", "name": "dupe"},
|
|
{"name": "no dir"},
|
|
"junk",
|
|
]}))
|
|
'''
|
|
ENV = r'''
|
|
import json, os, sys
|
|
sys.stdin.read()
|
|
print(json.dumps({"dir": os.environ.get("AIA_SERVICES_DIR")}))
|
|
'''
|
|
BROKEN = "import sys\nsys.stdin.read()\nraise SystemExit(3)\n"
|
|
|
|
MANIFEST = {
|
|
"schema": 1, "id": "services", "name": "Services",
|
|
"actions": {"index": {"script": "handlers/index.py"}, "env": {"script": "handlers/env.py"}},
|
|
"provides": {"services.index": "index"},
|
|
"capabilities": ["services.read", "conversations.read"],
|
|
"ui": {"pages": [{"id": "services", "label": "Services", "nav": "projects", "icon": "server",
|
|
"html": "ui/s.html", "subpath": True, "tag": "service"}]},
|
|
}
|
|
|
|
|
|
def _write(root: pathlib.Path, manifest: dict, index: str = INDEX) -> pathlib.Path:
|
|
(root / "handlers").mkdir(parents=True, exist_ok=True)
|
|
(root / "ui").mkdir(exist_ok=True)
|
|
(root / "plugin.json").write_text(json.dumps(manifest))
|
|
(root / "handlers" / "index.py").write_text(index)
|
|
(root / "handlers" / "env.py").write_text(ENV)
|
|
(root / "ui" / "s.html").write_text("<p>s</p>")
|
|
return root
|
|
|
|
|
|
class ManifestTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.tmp.name)
|
|
|
|
def tearDown(self):
|
|
self.tmp.cleanup()
|
|
|
|
def test_services_index_projects_nav_and_service_tag(self):
|
|
mf = validate_manifest(_write(self.root / "p", MANIFEST))
|
|
self.assertEqual(mf["provides"], {"services.index": "index"})
|
|
page = mf["ui"]["pages"][0]
|
|
self.assertEqual((page["nav"], page["tag"], page["subpath"]), ("projects", "service", True))
|
|
self.assertTrue(requires_operator(mf))
|
|
self.assertIn("provides", {c["kind"] for c in capability_summary(mf)})
|
|
|
|
def test_retired_keys_are_refused(self):
|
|
bad = [
|
|
{**MANIFEST, "provides": {"service.cards": "index"}},
|
|
{**MANIFEST, "provides": {"services.index": "nope"}},
|
|
{**MANIFEST, "ui": {"slots": [{"id": "s", "where": "service.detail", "html": "ui/s.html"}]}},
|
|
{**MANIFEST, "ui": {"pages": [{**MANIFEST["ui"]["pages"][0], "tag": "project"}]}},
|
|
]
|
|
for i, mf in enumerate(bad):
|
|
with self.assertRaises(ManifestError, msg=str(i)):
|
|
validate_manifest(_write(self.root / f"r{i}", mf))
|
|
|
|
|
|
class BridgeTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.tmp.name)
|
|
self.svc = self.root / "services"
|
|
(self.svc / "web").mkdir(parents=True)
|
|
self.store = PluginStore(self.root / "data")
|
|
self.deps = SimpleNamespace(plugin_store=self.store, users=SimpleNamespace(get=lambda u: None))
|
|
services_bridge.invalidate()
|
|
self.p = patch.object(servicesdir, "SERVICES_DIR", self.svc.resolve())
|
|
self.p.start()
|
|
|
|
def tearDown(self):
|
|
self.p.stop()
|
|
services_bridge.invalidate()
|
|
self.tmp.cleanup()
|
|
|
|
def _install(self, index: str = INDEX):
|
|
self.store.install(OWNER_UID, str(_write(self.root / "plugin", MANIFEST, index)),
|
|
is_owner=True, approve=True)
|
|
|
|
def test_no_plugin_no_services(self):
|
|
self.assertFalse(services_bridge.has_provider(self.deps))
|
|
self.assertEqual(services_bridge.list_services(self.deps), [])
|
|
|
|
def test_list_is_sanitized(self):
|
|
self._install()
|
|
self.assertTrue(services_bridge.has_provider(self.deps))
|
|
rows = services_bridge.list_services(self.deps)
|
|
self.assertEqual([r["dir"] for r in rows], ["web", "api"])
|
|
web, api = rows
|
|
self.assertEqual(web["urls"], ["https://web.example"])
|
|
self.assertEqual(web["goal"], {"done": 1, "total": 3})
|
|
self.assertEqual(web["auth"], "auth")
|
|
self.assertIs(web["hasCompose"], True)
|
|
self.assertNotIn("routerCount", web) # a bool is no count
|
|
self.assertNotIn("evil", web)
|
|
self.assertEqual((api["name"], api["description"], api["goal"]), ("api", "", None))
|
|
self.assertNotIn("auth", api)
|
|
|
|
def test_cached_and_copied(self):
|
|
self._install()
|
|
first = services_bridge.list_services(self.deps)
|
|
first[0]["name"] = "mutated"
|
|
with patch("plugins.runner.run_script") as run:
|
|
again = services_bridge.list_services(self.deps)
|
|
run.assert_not_called()
|
|
self.assertEqual(again[0]["name"], "Web")
|
|
|
|
def test_disabled_or_broken_plugin(self):
|
|
self._install(BROKEN)
|
|
self.assertEqual(services_bridge.list_services(self.deps), [])
|
|
self.store.update(OWNER_UID, "services", enabled=False)
|
|
self.assertFalse(services_bridge.has_provider(self.deps))
|
|
self.assertEqual(services_bridge.list_services(self.deps), [])
|
|
|
|
def test_services_dir_only_for_the_owner(self):
|
|
self._install()
|
|
rec = self.store.get_raw(OWNER_UID, "services")
|
|
out = run_script(self.deps, self.store, OWNER_UID, rec, "handlers/env.py")
|
|
self.assertEqual(out["dir"], str(self.svc.resolve()))
|
|
out = run_script(self.deps, self.store, "dom", rec, "handlers/env.py")
|
|
self.assertIsNone(out["dir"])
|
|
|
|
|
|
class _History:
|
|
def get(self, name):
|
|
if name == "web":
|
|
return {"ts": 1, "iso": "2026-11-27T10:00:00Z",
|
|
"commits": [{"hash": "abc", "date": "2026-11-27T10:00:00Z", "subject": "fix web"}]}
|
|
return None
|
|
|
|
|
|
class _Store:
|
|
def __init__(self, rows):
|
|
self.rows = rows
|
|
|
|
def all_summaries(self):
|
|
return list(self.rows)
|
|
|
|
|
|
class _Meta:
|
|
def __init__(self, metas):
|
|
self.metas = metas
|
|
|
|
def peek(self, sid):
|
|
return self.metas.get(sid)
|
|
|
|
|
|
class HubRoutesTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.tmp = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.tmp.name)
|
|
self.svc = self.root / "services"
|
|
for d in ("web", "api", ".hidden"):
|
|
(self.svc / d).mkdir(parents=True)
|
|
self.store = PluginStore(self.root / "data")
|
|
self.store.install(OWNER_UID, str(_write(self.root / "plugin", MANIFEST)),
|
|
is_owner=True, approve=True)
|
|
self.deps = main.app.state.ai
|
|
self.tc = TestClient(main.app)
|
|
services_bridge.invalidate()
|
|
self.patches = [patch.object(self.deps, "plugin_store", self.store),
|
|
patch.object(servicesdir, "SERVICES_DIR", self.svc.resolve()),
|
|
patch.object(servicesdir, "HISTORY", _History())]
|
|
for p in self.patches:
|
|
p.start()
|
|
|
|
def tearDown(self):
|
|
for p in self.patches:
|
|
p.stop()
|
|
services_bridge.invalidate()
|
|
self.tmp.cleanup()
|
|
|
|
def _h(self, uid=OWNER_UID):
|
|
return {"Authorization": f"Bearer {access.mint_handler(uid, 'services', ttl=600)}"}
|
|
|
|
def test_commits_of_every_service(self):
|
|
r = self.tc.get("/proxy/tools/plugins/services/hub/services/commits", headers=self._h())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()["services"]
|
|
self.assertEqual(sorted(body), ["api", "web"])
|
|
self.assertEqual(body["web"]["updatedAt"], "2026-11-27T10:00:00Z")
|
|
self.assertEqual(body["web"]["commits"][0]["subject"], "fix web")
|
|
self.assertEqual(body["api"], {"updatedAt": None, "commits": []})
|
|
|
|
def test_commits_of_one_service(self):
|
|
r = self.tc.get("/proxy/tools/plugins/services/hub/services/commits?slug=web", headers=self._h())
|
|
self.assertEqual(r.json()["commits"][0]["hash"], "abc")
|
|
for bad in ("../etc", ".hidden", "nope"):
|
|
r = self.tc.get("/proxy/tools/plugins/services/hub/services/commits",
|
|
params={"slug": bad}, headers=self._h())
|
|
self.assertEqual(r.status_code, 404, bad)
|
|
|
|
def test_commits_needs_services_read(self):
|
|
store = PluginStore(self.root / "data2")
|
|
store.install(OWNER_UID, str(_write(self.root / "p2", {**MANIFEST, "capabilities": ["conversations.read"]})),
|
|
is_owner=True, approve=True)
|
|
with patch.object(self.deps, "plugin_store", store):
|
|
r = self.tc.get("/proxy/tools/plugins/services/hub/services/commits", headers=self._h())
|
|
self.assertEqual(r.status_code, 403)
|
|
self.assertIn("services.read", r.text)
|
|
|
|
def test_conversations_by_service(self):
|
|
rows = [("/t/a.jsonl", {"sessionId": "s1", "endedAt": "2020-01-01T00:00:00", "servicesAuto": ["web"],
|
|
"costUsd": 1.5, "models": ["claude-opus-5-5"]}),
|
|
("/t/b.jsonl", {"sessionId": "s2", "endedAt": "2020-01-02T00:00:00", "servicesAuto": ["api"]}),
|
|
("/t/c.jsonl", {"sessionId": "s3", "endedAt": "2020-01-03T00:00:00"}),
|
|
("/t/d.jsonl", {"sessionId": "s4", "endedAt": "2020-01-04T00:00:00", "servicesAuto": ["web"]})]
|
|
metas = {"s3": {"services": ["web"], "title": "Tagged by hand"}, "s4": {"owner": "dom"}}
|
|
with patch.object(self.deps, "store", _Store(rows)), patch.object(self.deps, "meta_store", _Meta(metas)):
|
|
r = self.tc.get("/proxy/tools/plugins/services/hub/conversations?service=web&metrics=1",
|
|
headers=self._h())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
convs = r.json()["conversations"]
|
|
# The whole archive (2020 is far outside the 30-day window), the
|
|
# owner's only (s4 is a guest's), meta tags beat servicesAuto.
|
|
self.assertEqual([c["sessionId"] for c in convs], ["s3", "s1"])
|
|
self.assertEqual(convs[1]["services"], ["web"])
|
|
self.assertEqual(convs[1]["costUsd"], 1.5)
|
|
self.assertEqual(convs[1]["model"], "claude-opus-5-5")
|
|
plain = self.tc.get("/proxy/tools/plugins/services/hub/conversations?sids=s2",
|
|
headers=self._h()).json()["conversations"]
|
|
self.assertEqual(plain[0]["services"], ["api"])
|
|
|
|
def test_services_index_route(self):
|
|
r = self.tc.get("/api/plugins/services-index", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual([s["dir"] for s in r.json()["services"]], ["web", "api"])
|
|
self.store.update(OWNER_UID, "services", enabled=False)
|
|
self.assertEqual(self.tc.get("/api/plugins/services-index", headers=OWNER_H).json(),
|
|
{"services": []})
|
|
|
|
def test_old_routes_are_gone(self):
|
|
paths = set(main.app.openapi()["paths"])
|
|
self.assertIn("/api/plugins/services-index", paths)
|
|
self.assertFalse(paths & {"/api/services", "/api/service"})
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|