Files
ai-agent/backend/test_worker_bound.py
gabrielvidalandClaude Opus 5.5 aee457cdbf Merge origin/main into hub-mcp-plugin
main moved cron jobs into the cron-jobs plugin (#37) and retired the core
Send later doors for the scheduled-conversations plugin's commands (#36),
both touching the core MCP files this branch moves into the hub-mcp plugin.

- The MCP stays out of core: backend/mcpserver/, cli/mcp_tools.py,
  cli/mcp_server.py, their tests and business/aiApps/ stay deleted (main's
  edits to them — no schedule group, no cron / schedule tools — are the
  plugin's to apply).
- Cron and Send later follow main: backend/cron/routes.py gone (its
  by-name worker pick is runs.start's at fire time now), no ai-agent
  later / scheduled / unschedule — so a worker's narrowed CLI drops them
  from its command lists (workers/cli.py) and schedules nothing; Full
  reaches the plugin's commands.
- authz: neither runs.schedule nor mcp.connect.
- Settings: neither Scheduled jobs nor AI apps in the registry; both old
  addresses redirect to their plugin's page.
- Regenerated openapi.json, src/generated, rolesCatalog.json,
  matrix.golden.txt and telemetry features.json.
- cli/test_library_surface.py: parse_when left with `ai-agent later`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 19:14:16 +01:00

211 lines
11 KiB
Python

"""The owner narrowed to one of his workers (workers/bound.py) — what an MCP
connection bound to a worker is, and what a worker's `ai-agent` CLI runs as
(workers/cli.py, test_worker_cli.py): its mode's routes, its own profile's
conversations, runs on that worker only. Also the worker's `ai-agent past`
lookup and the CLI switch.
Imports ``main`` against throwaway paths (no startup event → no threads)."""
import os
import pathlib
import tempfile
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 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"
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 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_a_bound_connection_schedules_nothing(self):
"""Send later is the scheduled-conversations plugin's alone since
2026-11-28: the core's ``/api/scheduled`` door is gone, and a bound
connection — run or read — holds no ``plugins.use``, so the plugin's
actions (its commands, its MCP tools) refuse it."""
for h in (self.h(), self.h(mode="read")):
r = self.c.post("/api/plugins/scheduled-conversations/actions/create",
json={"prompt": "x", "in": "2h"}, headers=h)
self.assertEqual(r.status_code, 403, r.text)
r = self.c.get("/api/plugins/commands", headers=h)
self.assertEqual(r.status_code, 403, r.text)
self.assertTrue(_no_door(self.c.get("/api/scheduled", headers=OWNER_H)))
self.assertIn(self.c.post("/api/scheduled", json={"prompt": "x"},
headers=OWNER_H).status_code, (404, 405))
# ── a worker's own sessions ──────────────────────────────────────────────
def test_the_cli_switch_on_the_workers_page(self):
# back on 2026-11-28 (workers/cli.py): unset = Read + run here
r = self.c.get("/api/workers", headers=OWNER_H).json()["workers"]
self.assertEqual(next(w for w in r if w["id"] == "orus")["cli"], "run")
r = self.c.patch("/api/workers/orus", json={"cli": "read"}, headers=OWNER_H)
self.assertEqual((r.status_code, r.json()["cli"]), (200, "read"))
r = self.c.patch("/api/workers/orus", json={"cli": "all"}, headers=OWNER_H)
self.assertEqual(r.status_code, 400)
def test_its_past_lookup_sees_its_own_profile_and_follows_the_switch(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)
DEPS.worker_store.patch("orus", {"cli": "off"})
out = past.outbox_lookup(DEPS, {"worker": "orus", "keys": ["INS-1"]})
self.assertTrue(out.get("failed"), out)
DEPS.worker_store.patch("orus", {"cli": "read"})
self.assertTrue(past.outbox_lookup(DEPS, {"worker": "orus", "keys": ["INS-1"]}).get("ok"))
def test_a_run_started_by_its_name_goes_there(self):
calls = self.capture()
r = self.c.post("/api/spawn", json={"prompt": "x", "worker": "orus macbook"},
headers=self.h())
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(calls[-1][1]["worker"], "orus")
if __name__ == "__main__":
unittest.main()