Files
ai-agent/backend/test_worker_bound.py
gabrielvidalandClaude Opus 5.5 0e68e98795 feat(scheduled): Send later leaves the core for the scheduled-conversations plugin
Generic hooks the plugin builds on: the conversations.drawer, composer.send and
app.modal slot places (openModal / modal.setResult / modal.close, ?modal=
links), runs.start taking the composer's whole payload (auto routing,
account, projects, cwd, meta.scheduled) and hub/runs/resolve, a turn's knobs
on conversations.send, push buttons answered as the notify.action event,
hub/changed (SSE plugin-data), hub/title (conversations.title), the
runs.schedule provider behind /api/scheduled, the week's budget and the
stopped-run card, providers in /api/plugins/ui, carryover.scheduled.

backend/scheduled/ and frontend/src/business/scheduled/ are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:22:49 +01:00

209 lines
11 KiB
Python

"""The owner narrowed to one of his workers (workers/bound.py) — what an MCP
connection bound to a worker is: its mode's routes, its own profile's
conversations, runs on that worker only. Also the worker's `ai-agent past`.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
import time
import unittest
import uuid
TMP = pathlib.Path(tempfile.mkdtemp())
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
"PROFILES_PATH": TMP / "profiles.json",
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
"NOTIF_READ_PATH": TMP / "nr.json",
"SCHEDULED_PATH": TMP / "scheduled.json",
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
"PROJECTS_DIR": TMP / "projects", "SECURITY_STATE_PATH": TMP / "sec.json",
"SECURITY_LOG_PATH": TMP / "sec.jsonl",
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
"PI_TRANSCRIPTS_DIR": ""}.items():
os.environ[k] = str(v)
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
import runs.routes as run_routes # noqa: E402
from plugins import schedule_bridge # noqa: E402
from conversations import past # noqa: E402
from users import access # noqa: E402
from workers import bound as worker_bound # noqa: E402
DEPS = main.app.state.ai
OWNER_H = {"X-Internal-Auth": "tok"}
NEW = "33333333-3333-4333-8333-333333333333"
class WorkerBound(unittest.TestCase):
def setUp(self):
self.w = DEPS.worker_store.put({"id": "orus", "name": "Orus Macbook",
"url": "http://w:8790", "token": "t",
"account": "work", "claudeMode": "own"})
DEPS.profile_store.assign_worker(self.w, "work")
self.mine = str(uuid.uuid4()) # ran on the Orus Mac (Work)
self.lab = str(uuid.uuid4()) # ran on the lab (Personal)
DEPS.meta_store.update(self.mine, {"worker": "orus", "account": "work"})
DEPS.meta_store.update(self.lab, {"account": "personal"})
self.c = TestClient(main.app)
def tearDown(self):
DEPS.worker_store.delete("orus")
DEPS.worker_store.delete("guestbox")
DEPS.profile_store.forget_worker("orus")
def h(self, wid="orus", mode="run"):
return {**OWNER_H, "X-AIA-As-Worker": wid, "X-AIA-As-Worker-Mode": mode}
def capture(self):
calls = []
orig = run_routes._send_message
run_routes._send_message = lambda deps, prompt, **kw: (
calls.append((prompt, kw)) or {"sessionId": NEW, "pid": 1})
self.addCleanup(setattr, run_routes, "_send_message", orig)
return calls
# ── who the call is ──────────────────────────────────────────────────────
def test_the_owner_narrowed_to_the_workers_profile(self):
c = worker_bound.worker_caller(DEPS, "orus", "run")
self.assertEqual((c.is_owner, c.via_worker, c.profile, c.worker_mode),
(True, "orus", "work", "run"))
self.assertEqual(worker_bound.worker_caller(DEPS, "orus", "all").worker_mode, "read")
self.assertTrue(access.visible(DEPS, c, self.mine))
self.assertFalse(access.visible(DEPS, c, self.lab))
self.assertFalse(access.unrestricted(c))
cards = [{"meta": {"profile": "work"}}, {"meta": {"profile": "personal"}}]
self.assertEqual(access.filter_cards(c, cards), cards[:1])
def test_unknown_or_a_guests_computer_is_refused(self):
self.assertEqual(self.c.get("/api/workers", headers=self.h("nope")).status_code, 403)
DEPS.worker_store.put({"id": "guestbox", "name": "Dom's", "owner": "dom",
"url": "http://g", "token": "t"})
self.assertFalse(worker_bound.bindable(DEPS.worker_store.get("guestbox")))
self.assertEqual(self.c.get("/api/workers", headers=self.h("guestbox")).status_code, 403)
def test_only_its_modes_routes_answer(self):
self.assertEqual(self.c.get("/api/workers", headers=self.h()).status_code, 200)
for path in ("/api/projects", "/api/skills", "/api/ask-form/forms", "/api/cron"):
self.assertEqual(self.c.get(path, headers=self.h()).status_code, 403, path)
for mode in ("read", "", "all"): # anything but run is read
r = self.c.post("/api/spawn", json={"prompt": "x"}, headers=self.h(mode=mode))
self.assertEqual(r.status_code, 403, mode)
def test_the_headers_grant_nothing_to_an_untrusted_caller(self):
r = TestClient(main.app).get("/api/conversations",
headers={"X-AIA-As-Worker": "orus",
"X-AIA-As-Worker-Mode": "run"})
self.assertIn(r.status_code, (401, 403)) # refused before the headers count
self.assertNotIn("conversations", r.json())
# ── runs stay on that worker ─────────────────────────────────────────────
def test_a_new_run_goes_to_that_worker(self):
calls = self.capture()
r = self.c.post("/api/spawn", json={"prompt": "x", "parent": self.mine}, headers=self.h())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls[-1][1]["worker"], "orus")
r = self.c.post("/api/spawn", json={"prompt": "x", "worker": "orus macbook"},
headers=self.h())
self.assertEqual((r.status_code, calls[-1][1]["worker"]), (200, "orus"))
for other in ("local", "29ef5f0d4144"):
r = self.c.post("/api/spawn", json={"prompt": "x", "worker": other}, headers=self.h())
self.assertEqual(r.status_code, 403, other)
r = self.c.post("/api/spawn", json={"prompt": "x", "newProject": True}, headers=self.h())
self.assertEqual(r.status_code, 403)
def test_a_parent_it_cant_see_is_dropped(self):
calls = self.capture()
self.c.post("/api/spawn", json={"prompt": "x", "parent": self.lab}, headers=self.h())
self.assertFalse((calls[-1][1].get("stamp") or {}).get("spawnedBy"))
def test_send_stop_title_only_where_it_ran(self):
calls = self.capture()
r = self.c.post("/api/resume", json={"sessionId": self.lab, "prompt": "x"},
headers=self.h())
self.assertEqual(r.status_code, 404) # not even visible
DEPS.meta_store.update(self.lab, {"worker": "29ef5f0d4144", "profile": "work"})
r = self.c.post("/api/resume", json={"sessionId": self.lab, "prompt": "x"},
headers=self.h())
self.assertEqual(r.status_code, 403) # Work, but another machine
r = self.c.post("/api/interrupt", json={"sessionId": self.lab}, headers=self.h())
self.assertEqual(r.status_code, 403)
r = self.c.post("/api/resume", json={"sessionId": self.mine, "prompt": "x"},
headers=self.h())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls[-1][1]["session_id"], self.mine)
r = self.c.post("/api/conversation-meta", json={"id": self.mine, "title": "Mine"},
headers=self.h())
self.assertEqual(r.status_code, 200, r.text)
r = self.c.post("/api/conversation-meta", json={"id": self.mine, "account": "personal"},
headers=self.h())
self.assertEqual(r.status_code, 403)
r = self.c.post("/api/conversation-meta", json={"id": self.lab, "archived": True},
headers=self.h())
self.assertEqual(r.status_code, 403)
def test_scheduled_turns_are_passed_on_as_that_worker(self):
"""``/api/scheduled`` is the scheduled-conversations plugin's door
(plugins/schedule_bridge.py): the plugin keeps a bound connection to
its worker's entries — the host hands it who is calling."""
plug = TMP / "fake-scheduled"
plug.mkdir(exist_ok=True)
(plug / "h.py").write_text(
"import json, os, sys\n"
"p = json.load(sys.stdin)\n"
"print(json.dumps({'items': [], 'op': p['op'], 'body': p,\n"
" 'ctx': json.loads(os.environ['AIA_USER_CONTEXT'])}))\n")
rec = {"id": "scheduled-conversations", "dir": str(plug),
"manifest": {"id": "scheduled-conversations"}}
orig = schedule_bridge._provider
schedule_bridge._provider = lambda deps: (rec, {"script": "h.py"})
self.addCleanup(setattr, schedule_bridge, "_provider", orig)
later = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(time.time() + 3600))
r = self.c.post("/api/scheduled", json={"prompt": "x", "shouldStartAt": later},
headers=self.h()).json()
self.assertEqual((r["op"], r["body"]["prompt"]), ("create", "x"))
self.assertEqual({k: r["ctx"].get(k) for k in ("viaWorker", "viaWorkerName", "workerMode")},
{"viaWorker": "orus", "viaWorkerName": "Orus Macbook", "workerMode": "run"})
# the owner himself: no worker in the context
r = self.c.post("/api/scheduled", json={"prompt": "y", "shouldStartAt": later},
headers=OWNER_H).json()
self.assertNotIn("viaWorker", r["ctx"])
# a read-only connection lists, but can't schedule
self.assertEqual(self.c.get("/api/scheduled", headers=self.h(mode="read")).status_code, 200)
self.assertEqual(self.c.post("/api/scheduled", json={"prompt": "x", "shouldStartAt": later},
headers=self.h(mode="read")).status_code, 403)
d = self.c.delete("/api/scheduled/sch_x", headers=self.h()).json()
self.assertEqual((d, ), ({"ok": True}, ))
def test_without_the_plugin_nothing_is_scheduled(self):
orig = schedule_bridge._provider
schedule_bridge._provider = lambda deps: None
self.addCleanup(setattr, schedule_bridge, "_provider", orig)
self.assertEqual(self.c.get("/api/scheduled", headers=OWNER_H).json(), {"items": []})
r = self.c.post("/api/scheduled", json={"prompt": "x", "shouldStartAt": "2030-01-01T00:00:00Z"},
headers=OWNER_H)
self.assertEqual((r.status_code, r.json()["detail"]["kind"]), (404, "no_provider"))
# ── a worker's own sessions ──────────────────────────────────────────────
def test_no_cli_switch_on_the_workers_page_any_more(self):
r = self.c.get("/api/workers", headers=OWNER_H).json()["workers"]
self.assertNotIn("cli", next(w for w in r if w["id"] == "orus"))
def test_its_past_lookup_sees_its_own_profile(self):
out = past.outbox_lookup(DEPS, {"worker": "orus", "keys": ["INS-1"]})
self.assertTrue(out.get("ok"), out)
out = past.outbox_lookup(DEPS, {"worker": "nope", "keys": ["INS-1"]})
self.assertTrue(out.get("failed"), out)
if __name__ == "__main__":
unittest.main()