Files
ai-agent/backend/test_plugin_schedule.py

346 lines
18 KiB
Python

"""The platform hooks scheduled conversations moved onto when they left the
core (2026-11-26, the ``scheduled-conversations`` plugin): the new slot
places and their keys, the ``notify.action`` event and the push buttons it
answers, the composer's whole payload on ``runs.start`` and ``hub/runs/
resolve``, a turn's knobs on ``conversations.send``, ``hub/changed`` (SSE
``plugin-data``), ``hub/title``, ``ui.providers``, the carry-over of
``/data/scheduled.json`` and the ``runs.schedule`` reader (the budget; the
``/api/scheduled`` door went on 2026-11-28)."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import unittest
from unittest.mock import patch
os.environ.setdefault("INTERNAL_API_TOKEN", "tok")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from core.routes import _guest_filter # noqa: E402
from plugins import carryover, hubruns, manifest, schedule_bridge # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access # noqa: E402
from users.caller import Caller # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ["INTERNAL_API_TOKEN"]}
CAPS = ["runs.start", "conversations.send", "notify.send", "conversations.title"]
SID = "11111111-2222-4333-8444-aaaaaaaaaaaa"
def _plugin(root: pathlib.Path, **extra) -> pathlib.Path:
src = root / "src"
(src / "ui").mkdir(parents=True)
(src / "handlers").mkdir()
for f in ("drawer", "send", "edit"):
(src / "ui" / f"{f}.html").write_text("<p>x</p>")
(src / "handlers" / "h.py").write_text("import json; print(json.dumps({'count': 2}))\n")
mf = {"schema": 1, "id": "sc", "name": "S", "capabilities": CAPS,
"actions": {"count": {"script": "handlers/h.py", "readOnly": True},
"schedule": {"script": "handlers/h.py"}},
"provides": {"runs.schedule": "schedule"},
"events": [{"id": "taps", "on": ["notify.action"], "action": "schedule"}],
"ui": {"slots": [
{"id": "drawer", "where": "conversations.drawer", "html": "ui/drawer.html",
"label": "Scheduled", "icon": "calendar-clock", "badge": "count"},
{"id": "send", "where": "composer.send", "html": "ui/send.html",
"label": "Send later…", "icon": "calendar-clock"},
{"id": "edit", "where": "app.modal", "html": "ui/edit.html"}]}}
for k, v in extra.items():
mf[k] = v
(src / "plugin.json").write_text(json.dumps(mf))
return src
def _no_door(r) -> bool:
"""No ``/api/scheduled`` route: a 404/405, or a GET falling through to
the SPA shell (never the old ``{"items": …}`` answer)."""
if r.status_code in (404, 405):
return True
try:
body = r.json()
except ValueError:
return True
return not (isinstance(body, dict) and "items" in body)
class FakeMeta:
def __init__(self, m=None):
self.m = m or {}
def peek(self, sid):
return self.m.get(sid) or {}
def update(self, sid, patch):
self.m.setdefault(sid, {}).update(patch)
class TestManifest(unittest.TestCase):
def test_the_new_places_and_keys(self):
with tempfile.TemporaryDirectory() as td:
mf = manifest.validate_manifest(_plugin(pathlib.Path(td)))
slots = {s["id"]: s for s in mf["ui"]["slots"]}
self.assertEqual((slots["drawer"]["icon"], slots["drawer"]["badge"]), ("calendar-clock", "count"))
self.assertEqual(slots["send"]["where"], "composer.send")
self.assertNotIn("icon", slots["edit"])
self.assertEqual(mf["provides"], {"runs.schedule": "schedule"})
self.assertEqual(mf["events"][0]["on"], ["notify.action"])
self.assertTrue(manifest.requires_operator(mf)) # runs.start, conversations.title
labels = " ".join(i["label"] for i in manifest.capability_summary(mf))
self.assertIn("Schedules conversations for later", labels)
def test_refusals(self):
bad = [
# a badge must be a read-only action, on the drawer only
{"id": "d", "where": "conversations.drawer", "html": "ui/drawer.html", "badge": "schedule"},
{"id": "e", "where": "app.modal", "html": "ui/edit.html", "badge": "count"},
# an icon is a lucide name, on a host-drawn control only
{"id": "s", "where": "composer.send", "html": "ui/send.html", "icon": "<svg>"},
{"id": "p", "where": "project.detail", "html": "ui/edit.html", "icon": "clock"},
]
for sl in bad:
with tempfile.TemporaryDirectory() as td:
src = _plugin(pathlib.Path(td), ui={"slots": [sl]})
with self.assertRaises(manifest.ManifestError, msg=sl):
manifest.validate_manifest(src)
def test_a_plugin_without_the_new_keys_keeps_its_fingerprint(self):
with tempfile.TemporaryDirectory() as td:
src = _plugin(pathlib.Path(td), ui={"slots": [
{"id": "x", "where": "project.detail", "html": "ui/edit.html"}]})
mf = manifest.validate_manifest(src)
self.assertEqual(set(mf["ui"]["slots"][0]), {"id", "where", "html", "height"})
class TestNormRun(unittest.TestCase):
def test_the_composer_payload(self):
run, why = hubruns.norm_run({
"prompt": "x", "worker": "auto", "profile": "work", "account": "work",
"projects": ["ai-agent", "ai-agent"], "cwd": "/workspace/projects/ai-agent",
"newProject": True, "title": "T",
"scheduled": {"id": "sch_0123456789ab", "scheduledAt": "2026-11-26T10:00:00Z",
"shouldStartAt": "2026-11-27T02:00:00Z", "manual": True, "x": 1}})
self.assertIsNone(why)
self.assertEqual((run["worker"], run["profile"], run["account"]), ("auto", "work", "work"))
self.assertEqual(run["projects"], ["ai-agent"])
self.assertEqual(run["scheduled"], {"id": "sch_0123456789ab", "scheduledAt": "2026-11-26T10:00:00Z",
"shouldStartAt": "2026-11-27T02:00:00Z", "manual": True})
def test_refusals(self):
for body in ({"prompt": "x", "projects": "a"}, {"prompt": "x", "projects": ["../x"]},
{"prompt": "x", "cwd": "relative"}, {"prompt": "x", "cwd": "/a\nb"},
{"prompt": "x", "account": "a b"}, {"prompt": "x", "profile": "../p"},
{"prompt": "x", "scheduled": {"id": "a b"}},
{"prompt": "x", "scheduled": {"id": "s", "shouldStartAt": "tomorrow"}}):
run, why = hubruns.norm_run(body)
self.assertIsNone(run, body)
self.assertTrue(why)
class TestBridges(unittest.TestCase):
def setUp(self):
self.tc = TestClient(main.app)
self.td = tempfile.TemporaryDirectory()
self.addCleanup(self.td.cleanup)
root = pathlib.Path(self.td.name)
self.store = PluginStore(root / "data")
self.store.install(OWNER_UID, str(_plugin(root)), is_owner=True, approve=True)
deps = main.app.state.ai
self.meta = FakeMeta({SID: {"worker": "orus", "title": "The conversation"}})
self.events: list[dict] = []
for p in (patch.object(deps, "plugin_store", self.store),
patch.object(deps, "meta_store", self.meta),
patch.object(deps.hub, "publish", self.events.append)):
p.start()
self.addCleanup(p.stop)
self.h = {"Authorization": f"Bearer {access.mint_handler(OWNER_UID, 'sc', ttl=600)}"}
def test_runs_start_takes_the_composer_payload(self):
sent = {}
def send(deps, prompt, **kw):
sent.update(kw)
self.meta.update("s-new", {"worker": "orus", "account": "work"})
return {"sessionId": "s-new"}
with patch("runs.service._send_message", send), patch("accounts.valid", lambda a: a):
r = self.tc.post("/proxy/tools/plugins/sc/hub/runs", headers=self.h, json={
"prompt": "x", "worker": "auto", "profile": "work", "account": "work",
"projects": ["ai-agent"], "title": "Nightly",
"scheduled": {"id": "sch_1", "shouldStartAt": "2026-11-27T02:00:00Z"}})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual((r.json()["worker"], r.json()["account"]), ("orus", "work"))
# auto = routed when it starts: no worker, the profile it was sent from
self.assertEqual((sent["worker"], sent["profile"], sent["account"], sent["projects"]),
(None, "work", "work", ["ai-agent"]))
self.assertEqual(sent["stamp"]["scheduled"], {"id": "sch_1", "shouldStartAt": "2026-11-27T02:00:00Z"})
self.assertEqual(sent["stamp"]["title"], "Nightly")
def test_a_pinned_runner_keeps_its_pin(self):
sent = {}
with patch("runs.service._send_message", lambda deps, p, **kw: sent.update(kw) or {"sessionId": "s2"}):
self.tc.post("/proxy/tools/plugins/sc/hub/runs", headers=self.h,
json={"prompt": "x", "worker": "orus", "profile": "work"})
self.assertEqual((sent["worker"], sent["profile"]), ("orus", None))
def test_an_unknown_account_is_refused(self):
with patch("accounts.valid", lambda a: None):
r = self.tc.post("/proxy/tools/plugins/sc/hub/runs", headers=self.h,
json={"prompt": "x", "account": "nope"})
self.assertEqual((r.status_code, r.json()["error"]["kind"]), (400, "account"))
def test_a_turn_takes_its_knobs(self):
sent = {}
with patch("runs.service._send_message", lambda deps, p, **kw: sent.update(kw) or {"sessionId": SID}):
r = self.tc.post(f"/proxy/tools/plugins/sc/hub/conversations/{SID}/send", headers=self.h,
json={"prompt": "go", "model": "opus", "harness": "claude",
"effort": "HIGH", "thinking": True, "cwd": "/workspace/x"})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual({k: sent[k] for k in ("model", "harness", "effort", "thinking", "cwd", "session_id")},
{"model": "opus", "harness": "claude", "effort": "high", "thinking": True,
"cwd": "/workspace/x", "session_id": SID})
def test_resolve(self):
def route(deps, harness, account, worker, profile, *, check_online=True, model=None):
if worker == "gone":
from fastapi import HTTPException
raise HTTPException(400, {"message": "no such worker", "kind": "worker"})
if check_online and worker is None:
from fastapi import HTTPException
raise HTTPException(409, {"message": "all down", "kind": "worker_offline"})
return (worker, account or "personal")
with patch("runs.service.route_new_run", route), patch("accounts.valid", lambda a: None if a == "x" else a), \
patch("conversations.catalog._conv_ids_by_session", lambda deps: {SID: "cid-1"}):
r = self.tc.post("/proxy/tools/plugins/sc/hub/runs/resolve", headers=self.h, json={
"runners": [{"key": "a", "worker": "orus"},
{"key": "b", "mode": "now"}, # all down → the default
{"key": "c", "worker": "gone"},
{"key": "d", "account": "x"}],
"sessions": [SID, "not a sid"], "workers": True})
self.assertEqual(r.status_code, 200, r.text)
out = r.json()
self.assertEqual(out["runners"]["a"], {"worker": "orus", "account": "personal", "labOnly": False})
self.assertEqual(out["runners"]["b"]["worker"], "local")
self.assertEqual(out["runners"]["c"]["error"]["kind"], "worker")
self.assertEqual(out["runners"]["d"]["error"]["status"], 400)
self.assertEqual(list(out["sessions"]), [SID])
s = out["sessions"][SID]
self.assertEqual((s["conversationId"], s["title"], s["worker"]), ("cid-1", "The conversation", "orus"))
self.assertEqual(out["workers"]["local"]["name"], "Lab")
def test_push_buttons_come_back_as_an_event(self):
r = self.tc.post("/proxy/tools/plugins/sc/hub/notify", headers=self.h, json={
"title": "⏰ Didn't start", "message": "why", "url": "/?modal=sc:edit&id=sch_1",
"actions": ["Retry"], "spoken": "It didn't start."})
self.assertEqual(r.status_code, 200, r.text)
nid = r.json()["id"]
deps = main.app.state.ai
n = deps.notify_store.get(nid)
self.assertEqual(n["actions"], [{"action": f"{nid}__0", "title": "Retry"}])
self.assertTrue(n["url"].endswith("/?modal=sc:edit&id=sch_1") and n["url"].startswith("http"))
self.assertEqual(n["spoken"], "It didn't start.")
seen = []
with patch("plugins.scheduler.dispatch_event", lambda d, ev, payload, **kw: seen.append((ev, payload))):
a = self.tc.post(f"/api/notify/{nid}/action", json={"index": 0}, headers=OWNER_H)
self.assertEqual(a.status_code, 200, a.text)
self.assertEqual(seen, [("notify.action", {"notifyId": nid, "index": 0, "title": "Retry"})])
# The first tap wins: the same push tapped on another device (the
# phone after the desk) goes nowhere.
with patch("plugins.scheduler.dispatch_event", lambda d, ev, payload, **kw: seen.append((ev, payload))):
again = self.tc.post(f"/api/notify/{nid}/action", json={"index": 0}, headers=OWNER_H)
self.assertEqual((again.status_code, again.json()["status"], len(seen)), (200, "acted", 1))
bad = self.tc.post("/proxy/tools/plugins/sc/hub/notify", headers=self.h,
json={"title": "x", "actions": ["a", "b", "c", "d"]})
self.assertEqual(bad.status_code, 400)
def test_push_buttons_reach_the_browsers_and_a_tap_clears_them(self):
pushed, cleared = [], []
with patch("users.deliver.push", lambda deps, uid, t, m, u, extra=None: pushed.append(extra) or []):
r = self.tc.post("/proxy/tools/plugins/sc/hub/notify", headers=self.h, json={
"title": "Merge & deploy 1 PR?", "message": "• ai-agent #41",
"actions": ["Merge & deploy", "Later", "Drop"]})
nid = r.json()["id"]
# the owner's web push draws the buttons (push-sw.js), by title
self.assertEqual((pushed[-1]["kind"], pushed[-1]["id"], pushed[-1]["actions"]),
("notify", nid, ["Merge & deploy", "Later", "Drop"]))
with patch("plugins.scheduler.dispatch_event", lambda *a, **kw: None), \
patch("users.deliver.clear", lambda deps, sid, tag, kind="ask", **kw: cleared.append(tag)):
a = self.tc.post(f"/api/notify/{nid}/action", json={"index": 0}, headers=OWNER_H)
self.assertEqual((a.status_code, a.json()["actionTitle"]), (200, "Merge & deploy"))
self.assertEqual(cleared, [nid]) # off the other devices
# a plain push carries no buttons to the browsers
with patch("users.deliver.push", lambda deps, uid, t, m, u, extra=None: pushed.append(extra) or []):
self.tc.post("/proxy/tools/plugins/sc/hub/notify", headers=self.h, json={"title": "plain"})
self.assertNotIn("actions", pushed[-1])
def test_changed_tells_the_frames(self):
r = self.tc.post("/proxy/tools/plugins/sc/hub/changed", headers=self.h)
self.assertEqual(r.status_code, 200, r.text)
self.assertIn({"type": "plugin-data", "id": "sc", "uid": OWNER_UID}, self.events)
def test_title(self):
with patch("plugins.labels_bridge.title", lambda deps, text, kind, ref, acct: {"title": text[:5], "summary": None}):
r = self.tc.post("/proxy/tools/plugins/sc/hub/title", headers=self.h, json={"text": "Audit things"})
self.assertEqual(r.json(), {"title": "Audit", "summary": None})
with patch("plugins.labels_bridge.title", lambda *a: None):
r = self.tc.post("/proxy/tools/plugins/sc/hub/title", headers=self.h, json={"text": "x"})
self.assertEqual(r.json(), {})
def test_providers_name_the_plugin_and_its_action(self):
r = self.tc.get("/api/plugins/ui", headers=OWNER_H)
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(r.json()["providers"]["runs.schedule"], {"pluginId": "sc", "action": "schedule"})
def test_budget_reads_upcoming_once_in_a_while(self):
calls = []
def run(deps, store, uid, rec, script, *, payload=None, **kw):
calls.append(payload)
return {"items": [{"id": "sch_1", "shouldStartAt": "2030-01-01T00:00:00Z"}]}
schedule_bridge.drop_cache()
with patch("plugins.runner.run_script", run):
a = schedule_bridge.upcoming(main.app.state.ai)
b = schedule_bridge.upcoming(main.app.state.ai)
schedule_bridge.drop_cache()
self.assertEqual(a, b)
self.assertEqual(calls, [{"op": "upcoming"}])
def test_the_core_door_is_gone(self):
"""The CLI and the MCP reach the plugin through its own commands."""
for m, path in (("GET", "/api/scheduled"), ("POST", "/api/scheduled"),
("POST", "/api/scheduled/sch_1/start"), ("DELETE", "/api/scheduled/sch_1")):
r = self.tc.request(m, path, headers=OWNER_H, json={} if m == "POST" else None)
self.assertTrue(_no_door(r), f"{m} {path}: {r.status_code} {r.text[:80]}")
class TestGuestStream(unittest.TestCase):
def test_plugin_data_reaches_its_installer_only(self):
dom = Caller(id="g-dom", role="guest", name="Dom")
flt = _guest_filter(main.app.state.ai, dom)
self.assertEqual(flt({"type": "plugin-data", "id": "x", "uid": "g-dom"}),
{"type": "plugin-data", "id": "x"})
self.assertIsNone(flt({"type": "plugin-data", "id": "x", "uid": OWNER_UID}))
class TestCarryOver(unittest.TestCase):
def test_the_old_file_becomes_the_plugins(self):
with tempfile.TemporaryDirectory() as td:
root = pathlib.Path(td)
store = PluginStore(root / "data")
old = root / "scheduled.json"
old.write_text(json.dumps({"sch_1": {"id": "sch_1", "status": "scheduled"}}))
self.assertTrue(carryover.scheduled(store, str(old)))
dst = store.shared_data_dir("scheduled-conversations") / "scheduled.json"
self.assertEqual(json.loads(dst.read_text())["sch_1"]["status"], "scheduled")
self.assertFalse(old.exists())
self.assertTrue((root / "scheduled.json.migrated").exists())
self.assertFalse(carryover.scheduled(store, str(old))) # once
if __name__ == "__main__":
unittest.main()