663 lines
30 KiB
Python
663 lines
30 KiB
Python
"""Tests for backend plugin batching, parallelism, bootstrap & ETag optimizations."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import concurrent.futures
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import types
|
|
import unittest
|
|
from unittest.mock import patch
|
|
|
|
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)
|
|
for _k, _v in {
|
|
"DB_PATH": _DATA / "ai-agent.db",
|
|
"TRANSCRIPTS_DIR": _DATA / "transcripts",
|
|
"ARCHIVE_DIR": _DATA / "archive",
|
|
"WORKSPACE": _DATA / "workspace",
|
|
"REPO_DIR": _DATA / "workspace",
|
|
"PLUGINS_DIR": _DATA / "plugins",
|
|
"PLUGINS_LIVE_HARNESSES_DIR": _DATA / "live-harnesses",
|
|
"PLUGINS_LIVE_PROVIDERS_DIR": _DATA / "live-providers",
|
|
"META_PATH": _DATA / "meta.json",
|
|
"UI_STATE_PATH": _DATA / "ui-state.json",
|
|
"USERS_PATH": _DATA / "users.json",
|
|
"AUTH_PATH": _DATA / "auth.json",
|
|
"ROLES_PATH": _DATA / "roles.json",
|
|
"TOOLS_TOKEN_KEY": _DATA / "tools.key",
|
|
"STATIC_DIR": _DATA / "static",
|
|
"ASKFORM_PATH": _DATA / "askform.json",
|
|
"DRAFTS_PATH": _DATA / "drafts.json",
|
|
"TAG_META_PATH": _DATA / "tag-meta.json",
|
|
"WORKERS_PATH": _DATA / "workers.json",
|
|
"PROFILES_PATH": _DATA / "profiles.json",
|
|
"NOTIFY_PATH": _DATA / "notify.json",
|
|
"NOTIF_READ_PATH": _DATA / "notif-read.json",
|
|
"SECURITY_LOG_PATH": _DATA / "security.jsonl",
|
|
"SECURITY_STATE_PATH": _DATA / "security.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": _DATA / "worker-transcripts",
|
|
"PERF_SETTINGS_PATH": _DATA / "perf-settings.json",
|
|
"REPO_PLUGINS_PATH": _DATA / "repo-plugins.json",
|
|
"OWNER_SESSIONS_PATH": _DATA / "owner-sessions.json",
|
|
"OWNER_PASSKEYS_PATH": _DATA / "owner-passkeys.json",
|
|
"WEBPUSH_PATH": _DATA / "webpush.json",
|
|
"VAPID_KEY_PATH": _DATA / "vapid.pem",
|
|
"ACCOUNT_HEALTH_PATH": _DATA / "account-health.json",
|
|
"UPLOADS_DIR": _DATA / "uploads",
|
|
"RUN_QUEUE_PATH": _DATA / "run-queue.json",
|
|
"PROJECT_MERGES_PATH": _DATA / "project-merges.json",
|
|
"CRON_PATH": _DATA / "cron.json",
|
|
"FORMS_PATH": _DATA / "forms.json",
|
|
"FORM_SECRETS_PATH": _DATA / "form-secrets.json",
|
|
"INTERNAL_API_TOKEN": "tok",
|
|
"GUEST_HOSTS": "guest.example.test",
|
|
"SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": "",
|
|
}.items():
|
|
os.environ.setdefault(_k, str(_v))
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import banner, batch, home_tiles, keymap, shortcuts, waiting # noqa: E402
|
|
from plugins.store import OWNER_UID, PluginStore # noqa: E402
|
|
from users.caller import SESSION_COOKIE # noqa: E402
|
|
|
|
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
|
|
|
|
ECHO = (
|
|
"import json, sys, time\n"
|
|
"p = json.load(sys.stdin)\n"
|
|
"print(json.dumps({'payload': p.get('payload', p), 'n': time.time_ns()}))\n"
|
|
)
|
|
FAIL = "import sys\nsys.stderr.write('boom')\nsys.exit(3)\n"
|
|
|
|
|
|
def _write_plugin(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")
|
|
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 _RouteBase(unittest.TestCase):
|
|
def setUp(self):
|
|
self.td = tempfile.TemporaryDirectory()
|
|
self.root = pathlib.Path(self.td.name)
|
|
self.deps = main.app.state.ai
|
|
self.orig_store = self.deps.plugin_store
|
|
self.store = PluginStore(self.root / "plugins-data")
|
|
self.deps.plugin_store = self.store
|
|
for mod in (batch, home_tiles, waiting, shortcuts, keymap, banner):
|
|
mod.invalidate()
|
|
for u in self.deps.users.all():
|
|
self.deps.users.delete(u["id"])
|
|
self.client = TestClient(main.app, base_url="http://127.0.0.1:8096", client=("127.0.0.1", 5000))
|
|
|
|
def tearDown(self):
|
|
self.deps.plugin_store = self.orig_store
|
|
for mod in (batch, home_tiles, waiting, shortcuts, keymap, banner):
|
|
mod.invalidate()
|
|
for u in self.deps.users.all():
|
|
self.deps.users.delete(u["id"])
|
|
self.td.cleanup()
|
|
|
|
def install(self, pid: str, mf: dict, files: dict[str, str] | None = None) -> pathlib.Path:
|
|
plug = _write_plugin(self.root / pid, {"schema": 1, "id": pid, "name": pid.title(), **mf}, files)
|
|
self.store.install(OWNER_UID, str(plug), is_owner=True, approve=True)
|
|
return plug
|
|
|
|
def guest_client(self, uid_email: str = "alice@example.test", name: str = "Alice") -> tuple[dict, TestClient]:
|
|
u = self.deps.users.create(uid_email, name)
|
|
g = TestClient(main.app, base_url="https://guest.example.test")
|
|
g.cookies.set(SESSION_COOKIE, self.deps.auth.open_session(u["id"]))
|
|
return u, g
|
|
|
|
|
|
class UiBundleExtendedTest(_RouteBase):
|
|
def test_multi_where_kinds_and_etag_304(self):
|
|
commits_dir = self.install("commits", {
|
|
"ui": {
|
|
"slots": [
|
|
{"id": "det", "where": "conversation.details", "html": "ui/det.html"},
|
|
{"id": "hdr", "where": "conversation.header", "html": "ui/hdr.html"},
|
|
{"id": "send-secret", "where": "composer.send", "html": "ui/send.html"},
|
|
{"id": "send-guest", "where": "composer.send", "html": "ui/sendg.html", "guestAllowed": True},
|
|
],
|
|
"toolCards": [{"id": "commit-card", "match": {"tool": "shell"}, "html": "ui/tc.html"}],
|
|
},
|
|
"managed": {"defaultForGuests": True},
|
|
}, {
|
|
"ui/det.html": "<p>details</p>",
|
|
"ui/hdr.html": "<p>header</p>",
|
|
"ui/send.html": "<p>owner send</p>",
|
|
"ui/sendg.html": "<p>guest send</p>",
|
|
"ui/tc.html": "<p>commit card</p>",
|
|
})
|
|
self.install("charts", {
|
|
"ui": {"fences": [{"id": "chart-fence", "lang": "chart", "html": "ui/chart.html"}]},
|
|
}, {"ui/chart.html": "<p>chart</p>"})
|
|
self.install("media-viewer", {
|
|
"ui": {"filePreviews": [{"id": "card", "html": "ui/prev.html", "fileTypes": ["pdf"]}]},
|
|
}, {"ui/prev.html": "<p>preview</p>"})
|
|
self.install("pets", {
|
|
"ui": {"overlays": [{"id": "conversation", "where": "conversation", "html": "ui/ov.html"}]},
|
|
}, {"ui/ov.html": "<p>pet</p>"})
|
|
|
|
# Multi-where returns all requested slots using legacy "<pid>:<slotId>" keys
|
|
r = self.client.get(
|
|
"/api/plugins/ui-bundle?where=conversation.details,conversation.header",
|
|
headers=OWNER_H,
|
|
)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertEqual(body["where"], "conversation.details,conversation.header")
|
|
self.assertEqual(body["docs"], {"commits:det": "<p>details</p>", "commits:hdr": "<p>header</p>"})
|
|
self.assertEqual(r.headers["cache-control"], "private, no-cache")
|
|
|
|
# Kinds-only query
|
|
rk = self.client.get(
|
|
"/api/plugins/ui-bundle?kinds=toolCard,fence,preview,overlay",
|
|
headers=OWNER_H,
|
|
)
|
|
self.assertEqual(rk.status_code, 200, rk.text)
|
|
kbody = rk.json()
|
|
self.assertEqual(kbody["kinds"], "toolCard,fence,preview,overlay")
|
|
self.assertEqual(kbody["docs"], {
|
|
"toolCard:commits:commit-card": "<p>commit card</p>",
|
|
"fence:charts:chart-fence": "<p>chart</p>",
|
|
"preview:media-viewer:card": "<p>preview</p>",
|
|
"overlay:pets:conversation": "<p>pet</p>",
|
|
})
|
|
|
|
# Combined where + kinds + 304 on ETag
|
|
rc = self.client.get(
|
|
"/api/plugins/ui-bundle?where=conversation.details&kinds=fence,overlay",
|
|
headers=OWNER_H,
|
|
)
|
|
self.assertEqual(rc.status_code, 200, rc.text)
|
|
self.assertEqual(rc.json()["docs"], {
|
|
"commits:det": "<p>details</p>",
|
|
"fence:charts:chart-fence": "<p>chart</p>",
|
|
"overlay:pets:conversation": "<p>pet</p>",
|
|
})
|
|
etag = rc.headers["etag"]
|
|
r304 = self.client.get(
|
|
"/api/plugins/ui-bundle?where=conversation.details&kinds=fence,overlay",
|
|
headers={**OWNER_H, "If-None-Match": etag},
|
|
)
|
|
self.assertEqual(r304.status_code, 304)
|
|
self.assertEqual(r304.headers["etag"], etag)
|
|
|
|
# Updating a file on disk changes ETag & returns updated content
|
|
det_file = commits_dir / "ui" / "det.html"
|
|
det_file.write_text("<p>details v2 updated</p>", encoding="utf-8")
|
|
os.utime(det_file, ns=(time.time_ns() + 1_000_000, time.time_ns() + 1_000_000))
|
|
r_upd = self.client.get(
|
|
"/api/plugins/ui-bundle?where=conversation.details&kinds=fence,overlay",
|
|
headers={**OWNER_H, "If-None-Match": etag},
|
|
)
|
|
self.assertEqual(r_upd.status_code, 200)
|
|
self.assertNotEqual(r_upd.headers["etag"], etag)
|
|
self.assertEqual(r_upd.json()["docs"]["commits:det"], "<p>details v2 updated</p>")
|
|
|
|
# Guest only receives guestAllowed composer.send slots
|
|
_, guest = self.guest_client()
|
|
rg = guest.get("/api/plugins/ui-bundle?where=composer.send")
|
|
self.assertEqual(rg.status_code, 200, rg.text)
|
|
self.assertEqual(rg.json()["docs"], {"commits:send-guest": "<p>guest send</p>"})
|
|
|
|
def test_validation_errors(self):
|
|
for qs in ("", "?where=&kinds=", "?where=conversation.details,bad", "?kinds=fence,page", "?kinds=slot"):
|
|
r = self.client.get(f"/api/plugins/ui-bundle{qs}", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 400, qs)
|
|
|
|
|
|
class ReadCacheSharedTest(_RouteBase):
|
|
def test_concurrency_and_ms_field(self):
|
|
self.assertEqual(batch.BATCH_CONCURRENCY, 8)
|
|
self.install("alpha", {
|
|
"actions": {"read": {"script": "echo.py", "readOnly": True}},
|
|
}, {"echo.py": ECHO})
|
|
r = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json={
|
|
"items": [{"key": "a", "pluginId": "alpha", "action": "read", "payload": {"k": 1}}],
|
|
})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
item = r.json()["results"]["a"]
|
|
self.assertTrue(item["ok"])
|
|
self.assertFalse(item["cached"])
|
|
self.assertIsInstance(item["ms"], int)
|
|
self.assertGreaterEqual(item["ms"], 0)
|
|
r2 = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json={
|
|
"items": [{"key": "a", "pluginId": "alpha", "action": "read", "payload": {"k": 1}}],
|
|
})
|
|
item2 = r2.json()["results"]["a"]
|
|
self.assertTrue(item2["cached"])
|
|
self.assertIsInstance(item2["ms"], int)
|
|
self.assertEqual(item2["data"], item["data"])
|
|
|
|
def test_single_readonly_shares_cache_and_write_invalidates(self):
|
|
self.install("alpha", {
|
|
"actions": {
|
|
"read": {"script": "echo.py", "readOnly": True},
|
|
"fail": {"script": "fail.py", "readOnly": True},
|
|
"write": {"script": "echo.py"},
|
|
},
|
|
}, {"echo.py": ECHO, "fail.py": FAIL})
|
|
|
|
# 1. Single GET populates ReadCache -> batch-read hits cache
|
|
r1 = self.client.get(
|
|
"/api/plugins/alpha/actions/read",
|
|
headers=OWNER_H,
|
|
params={"payload": json.dumps({"x": 10})},
|
|
)
|
|
self.assertEqual(r1.status_code, 200, r1.text)
|
|
d1 = r1.json()
|
|
rb = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json={
|
|
"items": [{"key": "k", "pluginId": "alpha", "action": "read", "payload": {"x": 10}}],
|
|
})
|
|
self.assertEqual(rb.status_code, 200)
|
|
res_b = rb.json()["results"]["k"]
|
|
self.assertTrue(res_b["cached"])
|
|
self.assertEqual(res_b["data"], d1)
|
|
|
|
# 2. batch-read populates ReadCache -> single GET and POST(readOnly) hit cache
|
|
rb2 = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json={
|
|
"items": [{"key": "k2", "pluginId": "alpha", "action": "read", "payload": {"y": 20}}],
|
|
})
|
|
d2 = rb2.json()["results"]["k2"]["data"]
|
|
r2_get = self.client.get(
|
|
"/api/plugins/alpha/actions/read",
|
|
headers=OWNER_H,
|
|
params={"payload": json.dumps({"y": 20})},
|
|
)
|
|
self.assertEqual(r2_get.json(), d2)
|
|
r2_post = self.client.post(
|
|
"/api/plugins/alpha/actions/read",
|
|
headers=OWNER_H,
|
|
json={"y": 20},
|
|
)
|
|
self.assertEqual(r2_post.json(), d2)
|
|
|
|
# 3. Non-readOnly POST invalidates ReadCache for plugin
|
|
rw = self.client.post("/api/plugins/alpha/actions/write", headers=OWNER_H, json={"mutate": True})
|
|
self.assertEqual(rw.status_code, 200)
|
|
r_after = self.client.get(
|
|
"/api/plugins/alpha/actions/read",
|
|
headers=OWNER_H,
|
|
params={"payload": json.dumps({"y": 20})},
|
|
)
|
|
self.assertNotEqual(r_after.json()["n"], d2["n"])
|
|
rb_after = self.client.post("/api/plugins/batch-read", headers=OWNER_H, json={
|
|
"items": [{"key": "k2", "pluginId": "alpha", "action": "read", "payload": {"y": 20}}],
|
|
})
|
|
self.assertTrue(rb_after.json()["results"]["k2"]["cached"])
|
|
self.assertEqual(rb_after.json()["results"]["k2"]["data"], r_after.json())
|
|
|
|
# 4. ActionError and 405 error handling preserved
|
|
r_fail = self.client.get("/api/plugins/alpha/actions/fail", headers=OWNER_H)
|
|
self.assertGreaterEqual(r_fail.status_code, 400)
|
|
self.assertIn("message", r_fail.json()["detail"])
|
|
self.assertEqual(self.client.get("/api/plugins/alpha/actions/write", headers=OWNER_H).status_code, 405)
|
|
|
|
|
|
class UiAndDocEtagTest(_RouteBase):
|
|
def test_plugins_ui_readonly_actions_and_etag_304(self):
|
|
self.install("alpha", {
|
|
"managed": {"defaultForGuests": True},
|
|
"actions": {
|
|
"zeta": {"script": "echo.py", "readOnly": True},
|
|
"alpha": {"script": "echo.py", "readOnly": True},
|
|
"secret_ro": {"script": "echo.py", "readOnly": True, "ownerOnly": True},
|
|
"http_ro": {"script": "echo.py", "readOnly": True},
|
|
"mutate": {"script": "echo.py"},
|
|
},
|
|
"endpoints": [{"id": "ep", "path": "/x/alpha/ep", "methods": ["GET"], "action": "http_ro"}],
|
|
}, {"echo.py": ECHO})
|
|
self.install("writeonly", {
|
|
"managed": {"defaultForGuests": True},
|
|
"actions": {"mutate": {"script": "echo.py"}},
|
|
}, {"echo.py": ECHO})
|
|
self.install("owner-ro-only", {
|
|
"managed": {"defaultForGuests": True},
|
|
"actions": {"admin_read": {"script": "echo.py", "readOnly": True, "ownerOnly": True}},
|
|
}, {"echo.py": ECHO})
|
|
|
|
r = self.client.get("/api/plugins/ui", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.headers["cache-control"], "private, no-cache")
|
|
etag = r.headers["etag"]
|
|
self.assertRegex(etag, r'^"[0-9a-f]{16}"$')
|
|
ro = r.json()["readOnlyActions"]
|
|
self.assertEqual(ro, {
|
|
"alpha": ["alpha", "secret_ro", "zeta"],
|
|
"owner-ro-only": ["admin_read"],
|
|
})
|
|
self.assertNotIn("writeonly", ro)
|
|
|
|
# 304 on matching If-None-Match
|
|
r304 = self.client.get("/api/plugins/ui", headers={**OWNER_H, "If-None-Match": etag})
|
|
self.assertEqual(r304.status_code, 304)
|
|
self.assertEqual(r304.headers["etag"], etag)
|
|
self.assertEqual(r304.headers["cache-control"], "private, no-cache")
|
|
|
|
# Guest omits ownerOnly readOnly actions (and omits plugins left with none)
|
|
_, guest = self.guest_client()
|
|
rg = guest.get("/api/plugins/ui")
|
|
self.assertEqual(rg.status_code, 200, rg.text)
|
|
self.assertEqual(rg.json()["readOnlyActions"], {"alpha": ["alpha", "zeta"]})
|
|
rg304 = guest.get("/api/plugins/ui", headers={"If-None-Match": rg.headers["etag"]})
|
|
self.assertEqual(rg304.status_code, 304)
|
|
|
|
# Toggling a plugin changes ETag
|
|
self.store.update(OWNER_UID, "writeonly", enabled=False)
|
|
r_changed = self.client.get("/api/plugins/ui", headers={**OWNER_H, "If-None-Match": etag})
|
|
self.assertEqual(r_changed.status_code, 200)
|
|
self.assertNotEqual(r_changed.headers["etag"], etag)
|
|
|
|
def test_plugin_ui_html_etag_304(self):
|
|
pdir = self.install("viewer", {
|
|
"ui": {
|
|
"slots": [{"id": "s1", "where": "conversation.details", "html": "ui/s1.html"}],
|
|
"fences": [{"id": "f1", "lang": "mermaid2", "html": "ui/f1.html"}],
|
|
},
|
|
}, {"ui/s1.html": "<p>slot v1</p>", "ui/f1.html": "<p>fence v1</p>"})
|
|
|
|
r = self.client.get("/api/plugins/viewer/ui/slot/s1", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.text, "<p>slot v1</p>")
|
|
self.assertEqual(r.headers["cache-control"], "private, no-cache")
|
|
etag = r.headers["etag"]
|
|
self.assertRegex(etag, r'^"[0-9a-f]{16}"$')
|
|
|
|
r304 = self.client.get(
|
|
"/api/plugins/viewer/ui/slot/s1",
|
|
headers={**OWNER_H, "If-None-Match": etag},
|
|
)
|
|
self.assertEqual(r304.status_code, 304)
|
|
self.assertEqual(r304.headers["etag"], etag)
|
|
self.assertEqual(r304.headers["cache-control"], "private, no-cache")
|
|
|
|
# Different sub_id/kind has different ETag
|
|
rf = self.client.get("/api/plugins/viewer/ui/fence/f1", headers=OWNER_H)
|
|
self.assertEqual(rf.status_code, 200)
|
|
self.assertNotEqual(rf.headers["etag"], etag)
|
|
|
|
# Updating file changes ETag & serves new body
|
|
s1_path = pdir / "ui" / "s1.html"
|
|
s1_path.write_text("<p>slot v2 updated</p>", encoding="utf-8")
|
|
os.utime(s1_path, ns=(time.time_ns() + 1_000_000, time.time_ns() + 1_000_000))
|
|
r_upd = self.client.get(
|
|
"/api/plugins/viewer/ui/slot/s1",
|
|
headers={**OWNER_H, "If-None-Match": etag},
|
|
)
|
|
self.assertEqual(r_upd.status_code, 200)
|
|
self.assertEqual(r_upd.text, "<p>slot v2 updated</p>")
|
|
self.assertNotEqual(r_upd.headers["etag"], etag)
|
|
|
|
|
|
class ParallelProvidersTest(_RouteBase):
|
|
def _slow_script(self, delay: float, body: dict) -> str:
|
|
return (
|
|
"import json, sys, time\n"
|
|
"sys.stdin.read()\n"
|
|
f"time.sleep({delay})\n"
|
|
f"print(json.dumps({json.dumps(body)}))\n"
|
|
)
|
|
|
|
def test_home_tiles_parallel_and_order_and_no_pool_for_single_or_cached(self):
|
|
self.install("p1", {
|
|
"actions": {"tiles": {"script": "t.py"}},
|
|
"provides": {"home.tiles": "tiles"},
|
|
}, {"t.py": self._slow_script(0.35, {"tiles": [
|
|
{"id": "shared", "kind": "stat", "label": "From P1", "value": "1"},
|
|
{"id": "only1", "kind": "stat", "label": "Only1", "value": "1"},
|
|
]})})
|
|
self.install("p2", {
|
|
"actions": {"tiles": {"script": "t.py"}},
|
|
"provides": {"home.tiles": "tiles"},
|
|
}, {"t.py": self._slow_script(0.35, {"tiles": [
|
|
{"id": "shared", "kind": "stat", "label": "From P2", "value": "2"},
|
|
{"id": "only2", "kind": "stat", "label": "Only2", "value": "2"},
|
|
]})})
|
|
|
|
caller = types.SimpleNamespace(is_owner=True, id="owner")
|
|
t0 = time.monotonic()
|
|
tiles = home_tiles.tiles_for(self.deps, caller)
|
|
took = time.monotonic() - t0
|
|
self.assertLess(took, 0.62, f"expected parallel execution, took {took:.3f}s")
|
|
# Deterministic ordering: p1 before p2, p1 wins on duplicate 'shared'
|
|
self.assertEqual([(t["id"], t["label"]) for t in tiles], [
|
|
("shared", "From P1"),
|
|
("only1", "Only1"),
|
|
("only2", "Only2"),
|
|
])
|
|
|
|
# Cache hit avoids ThreadPoolExecutor
|
|
with patch.object(concurrent.futures, "ThreadPoolExecutor", side_effect=AssertionError("pool spawned")):
|
|
cached = home_tiles.tiles_for(self.deps, caller)
|
|
self.assertEqual(cached, tiles)
|
|
|
|
# Single cold miss avoids ThreadPoolExecutor
|
|
home_tiles.invalidate("p1")
|
|
with patch.object(concurrent.futures, "ThreadPoolExecutor", side_effect=AssertionError("pool spawned")):
|
|
tiles_single = home_tiles.tiles_for(self.deps, caller)
|
|
self.assertEqual(tiles_single, tiles)
|
|
|
|
def test_waiting_and_composer_modes_parallel(self):
|
|
self.install("w1", {
|
|
"actions": {
|
|
"wait": {"script": "w.py"},
|
|
"mode": {"script": "m.py"},
|
|
},
|
|
"provides": {"inbox.waiting": "wait", "composer.mode": "mode"},
|
|
}, {
|
|
"w.py": self._slow_script(0.35, {"items": [
|
|
{"id": "dup", "title": "First", "at": "2026-12-01T10:00:00Z"},
|
|
{"id": "a", "title": "Item A", "at": "2026-12-01T09:00:00Z"},
|
|
]}),
|
|
"m.py": self._slow_script(0.35, {"modes": [
|
|
{"id": "shared-mode", "label": "M1"},
|
|
{"id": "mode-a", "label": "Mode A"},
|
|
]}),
|
|
})
|
|
self.install("w2", {
|
|
"actions": {
|
|
"wait": {"script": "w.py"},
|
|
"mode": {"script": "m.py"},
|
|
},
|
|
"provides": {"inbox.waiting": "wait", "composer.mode": "mode"},
|
|
}, {
|
|
"w.py": self._slow_script(0.35, {"items": [
|
|
{"id": "dup", "title": "Second", "at": "2026-12-01T11:00:00Z"},
|
|
{"id": "b", "title": "Item B", "at": "2026-12-01T12:00:00Z"},
|
|
]}),
|
|
"m.py": self._slow_script(0.35, {"modes": [
|
|
{"id": "shared-mode", "label": "M2"},
|
|
{"id": "mode-b", "label": "Mode B"},
|
|
]}),
|
|
})
|
|
|
|
caller = types.SimpleNamespace(is_owner=True, id="owner")
|
|
t0 = time.monotonic()
|
|
items = waiting.waiting_for(self.deps, caller)
|
|
took_w = time.monotonic() - t0
|
|
self.assertLess(took_w, 0.62, f"waiting took {took_w:.3f}s")
|
|
# w1 wins on 'dup', sorted by 'at' descending
|
|
self.assertEqual([(i["id"], i["title"]) for i in items], [
|
|
("b", "Item B"),
|
|
("dup", "First"),
|
|
("a", "Item A"),
|
|
])
|
|
|
|
t0 = time.monotonic()
|
|
modes = waiting.composer_modes_for(self.deps, caller)
|
|
took_m = time.monotonic() - t0
|
|
self.assertLess(took_m, 0.62, f"modes took {took_m:.3f}s")
|
|
self.assertEqual([(m["id"], m["label"]) for m in modes], [
|
|
("shared-mode", "M1"),
|
|
("mode-a", "Mode A"),
|
|
("mode-b", "Mode B"),
|
|
])
|
|
|
|
# Warm SWR cache avoids ThreadPoolExecutor
|
|
with patch.object(concurrent.futures, "ThreadPoolExecutor", side_effect=AssertionError("pool spawned")):
|
|
self.assertEqual(waiting.composer_modes_for(self.deps, caller), modes)
|
|
|
|
# Single cold miss avoids ThreadPoolExecutor
|
|
waiting.invalidate("w1")
|
|
with patch.object(concurrent.futures, "ThreadPoolExecutor", side_effect=AssertionError("pool spawned")):
|
|
self.assertEqual(waiting.composer_modes_for(self.deps, caller), modes)
|
|
|
|
def test_shortcuts_parallel_and_deterministic_and_single_skips_pool(self):
|
|
self.install("s1", {
|
|
"actions": {"sc": {"script": "s.py"}},
|
|
"provides": {"composer.shortcuts": "sc"},
|
|
}, {"s.py": self._slow_script(0.35, {"shortcuts": [
|
|
{"id": "alpha", "label": "Alpha S1", "guideline": "g1"},
|
|
{"id": "dup", "label": "Dup S1", "guideline": "gd1"},
|
|
]})})
|
|
self.install("s2", {
|
|
"actions": {"sc": {"script": "s.py"}},
|
|
"provides": {"composer.shortcuts": "sc"},
|
|
}, {"s.py": self._slow_script(0.35, {
|
|
"position": "first",
|
|
"shortcuts": [
|
|
{"id": "first", "label": "First S2", "guideline": "gf"},
|
|
{"id": "dup", "label": "Dup S2", "guideline": "gd2"},
|
|
],
|
|
})})
|
|
|
|
caller = types.SimpleNamespace(is_owner=True, id="owner")
|
|
t0 = time.monotonic()
|
|
got = shortcuts.shortcuts_for(self.deps, caller)
|
|
took = time.monotonic() - t0
|
|
self.assertLess(took, 0.62, f"shortcuts took {took:.3f}s")
|
|
# s2 has position=first, so its items lead and win on 'dup'
|
|
self.assertEqual([(s["id"], s["label"]) for s in got], [
|
|
("first", "First S2"),
|
|
("dup", "Dup S2"),
|
|
("alpha", "Alpha S1"),
|
|
])
|
|
|
|
with patch.object(concurrent.futures, "ThreadPoolExecutor", side_effect=AssertionError("pool spawned")):
|
|
self.assertEqual(shortcuts.shortcuts_for(self.deps, caller), got)
|
|
|
|
shortcuts.invalidate("s1")
|
|
with patch.object(concurrent.futures, "ThreadPoolExecutor", side_effect=AssertionError("pool spawned")):
|
|
self.assertEqual(shortcuts.shortcuts_for(self.deps, caller), got)
|
|
|
|
|
|
class BootstrapTest(_RouteBase):
|
|
def test_owner_vs_guest_and_banner_attachment(self):
|
|
self.install("sc", {
|
|
"managed": {"defaultForGuests": True},
|
|
"actions": {"sc": {"script": "sc.py"}},
|
|
"provides": {"composer.shortcuts": "sc"},
|
|
}, {"sc.py": "import json; print(json.dumps({'shortcuts': [{'id': 'c1', 'label': 'C1', 'guideline': 'g'}]}))\n"})
|
|
self.install("md", {
|
|
"managed": {"defaultForGuests": True},
|
|
"actions": {"md": {"script": "md.py"}},
|
|
"provides": {"composer.mode": "md"},
|
|
}, {"md.py": "import json; print(json.dumps({'modes': [{'id': 'm1', 'label': 'Mode 1'}]}))\n"})
|
|
self.install("kb", {
|
|
"managed": {"defaultForGuests": True},
|
|
"actions": {"kb": {"script": "kb.py"}},
|
|
"provides": {"app.keymap": "kb"},
|
|
}, {"kb.py": "import json; print(json.dumps({'enabled': True, 'bindings': [{'command': 'go.home', 'keys': ['g h']}]}))\n"})
|
|
self.install("bn", {
|
|
"actions": {"bn": {"script": "bn.py"}},
|
|
"provides": {"app.banner": "bn"},
|
|
}, {"bn.py": "import json; print(json.dumps({'active': True, 'title': 'Deploy', 'status': 'running', 'sessionId': 'sid-1'}))\n"})
|
|
|
|
from core import config
|
|
from conversations import ids
|
|
root = str(config.TRANSCRIPTS_DIR)
|
|
rel = "-home-x/sid-1.jsonl"
|
|
fake_summaries = [(f"{root}/{rel}", {"sessionId": "sid-1", "title": "Ship fix", "endedAt": "2026-12-01T12:00:00Z"})]
|
|
with patch.object(self.deps.store, "all_summaries", return_value=fake_summaries), \
|
|
patch.object(self.deps.meta_store, "peek", return_value={}):
|
|
r = self.client.get("/api/plugins/bootstrap", headers=OWNER_H)
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
data = r.json()
|
|
self.assertEqual([s["id"] for s in data["shortcuts"]], ["c1"])
|
|
self.assertEqual([m["id"] for m in data["modes"]], ["m1"])
|
|
self.assertEqual(data["keymap"], {"enabled": True, "pluginId": "kb", "bindings": [{"command": "go.home", "keys": ["g h"]}]})
|
|
self.assertEqual(data["banner"]["title"], "Deploy")
|
|
self.assertEqual(data["banner"]["convTitle"], "Ship fix")
|
|
self.assertEqual(data["banner"]["conversationId"], ids.uid_for_rel(rel))
|
|
self.assertEqual(data["banner"]["convUrl"], f"/conversation/{data['banner']['conversationId']}")
|
|
|
|
# Guest receives shortcuts/modes/keymap, banner is None, banner.status not called
|
|
_, guest = self.guest_client()
|
|
with patch.object(banner, "status", side_effect=AssertionError("guest must not read banner")):
|
|
rg = guest.get("/api/plugins/bootstrap")
|
|
self.assertEqual(rg.status_code, 200, rg.text)
|
|
gdata = rg.json()
|
|
self.assertEqual([s["id"] for s in gdata["shortcuts"]], ["c1"])
|
|
self.assertEqual([m["id"] for m in gdata["modes"]], ["m1"])
|
|
self.assertTrue(gdata["keymap"]["enabled"])
|
|
self.assertIsNone(gdata["banner"])
|
|
|
|
# Anonymous caller is rejected
|
|
anon = TestClient(main.app, base_url="https://guest.example.test")
|
|
self.assertEqual(anon.get("/api/plugins/bootstrap").status_code, 401)
|
|
|
|
def test_concurrent_execution_and_fault_tolerance(self):
|
|
def slow_shortcuts(deps, caller):
|
|
time.sleep(0.3)
|
|
return [{"id": "s1", "label": "S1", "guideline": "g", "pluginId": "sc"}]
|
|
|
|
def slow_modes(deps, caller):
|
|
time.sleep(0.3)
|
|
return [{"id": "m1", "label": "M1", "pluginId": "md"}]
|
|
|
|
def slow_keymap(deps, caller):
|
|
time.sleep(0.3)
|
|
return {"enabled": True, "bindings": [], "pluginId": "kb"}
|
|
|
|
def slow_banner(deps, caller):
|
|
time.sleep(0.3)
|
|
return {"active": True, "title": "OK", "status": "info"}
|
|
|
|
with patch.object(shortcuts, "shortcuts_for", side_effect=slow_shortcuts), \
|
|
patch.object(waiting, "composer_modes_for", side_effect=slow_modes), \
|
|
patch.object(keymap, "keymap_for", side_effect=slow_keymap), \
|
|
patch.object(banner, "status_for", side_effect=slow_banner):
|
|
t0 = time.monotonic()
|
|
r = self.client.get("/api/plugins/bootstrap", headers=OWNER_H)
|
|
took = time.monotonic() - t0
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertLess(took, 0.65, f"bootstrap was sequential ({took:.3f}s)")
|
|
self.assertEqual(r.json()["banner"]["title"], "OK")
|
|
|
|
# Fault tolerance: individual failures return safe defaults without failing others
|
|
with patch.object(shortcuts, "shortcuts_for", side_effect=RuntimeError("sc boom")), \
|
|
patch.object(waiting, "composer_modes_for", return_value=[{"id": "ok-mode"}]), \
|
|
patch.object(keymap, "keymap_for", side_effect=RuntimeError("kb boom")), \
|
|
patch.object(banner, "status_for", side_effect=RuntimeError("bn boom")):
|
|
r_err = self.client.get("/api/plugins/bootstrap", headers=OWNER_H)
|
|
self.assertEqual(r_err.status_code, 200, r_err.text)
|
|
self.assertEqual(r_err.json(), {
|
|
"shortcuts": [],
|
|
"modes": [{"id": "ok-mode"}],
|
|
"keymap": {"enabled": False, "bindings": [], "pluginId": None},
|
|
"banner": None,
|
|
})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|