Files
ai-agent/backend/test_worker_cli.py

160 lines
7.6 KiB
Python

"""A worker's ``ai-agent`` CLI through its outbox (workers/cli.py): the jobs
the OutboxMirror hands the hub — run here, answered in the ack when quick,
later when not — the worker's switch, and the environment the CLI runs in
(the worker and its mode as headers, the session as the parent).
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",
"UI_STATE_PATH": TMP / "ui.json", "NOTIF_READ_PATH": TMP / "nr.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)
import main # noqa: E402
from workers import cli as worker_cli # noqa: E402
from workers.outbox_mirror import OutboxMirror # noqa: E402
DEPS = main.app.state.ai
SID = "44444444-4444-4444-8444-444444444444"
FAKE_CLI = '''import os, sys, time
if sys.argv[1] == "wait":
time.sleep(float(sys.argv[2]))
print("ran", sys.argv[1:], os.environ.get("AIA_AS_WORKER"), os.environ.get("AIA_AS_WORKER_MODE"),
os.environ.get("CLAUDE_SESSION_ID"), os.environ.get("AI_AGENT_TOKEN"),
os.environ.get("AI_AGENT_OUTBOX_URL") == "")
print("err", file=sys.stderr)
sys.exit(3 if sys.argv[1] == "ls" else 0)
'''
class Jobs(unittest.TestCase):
"""The mirror's hooks: create (answered in the ack when quick), get, cancel."""
def setUp(self):
DEPS.worker_store.put({"id": "evox", "name": "EVOX2", "url": "http://w", "token": "t"})
DEPS.profile_store.assign_worker(DEPS.worker_store.get("evox"), "personal")
cli = TMP / "fake_cli.py"
cli.write_text(FAKE_CLI)
self.jobs = worker_cli.CliJobs(DEPS, cli=cli)
def tearDown(self):
DEPS.worker_store.delete("evox")
DEPS.worker_store.delete("guestbox")
DEPS.profile_store.forget_worker("evox")
def item(self, *argv, sid=SID, worker="evox"):
return {"id": "cli_" + uuid.uuid4().hex[:12], "worker": worker, "sessionId": sid,
"argv": list(argv)}
def wait_done(self, oid):
for _ in range(80):
if self.jobs.get(oid)["status"] != "running":
break
time.sleep(0.1)
return self.jobs.get(oid)
def test_a_quick_command_rides_back_in_the_ack(self):
out = self.jobs.create(self.item("ls", "--limit", "3"))
self.assertTrue(out["ok"], out)
r = out["result"]
self.assertEqual(r["rc"], 3)
# the worker, its switch, the session (the parent of what it starts),
# the host token for the loopback call, and never the outbox again
self.assertIn(f"['ls', '--limit', '3'] evox run {SID} tok True", r["stdout"])
self.assertEqual(r["stderr"], "err\n")
def test_the_mode_follows_the_switch(self):
DEPS.worker_store.patch("evox", {"cli": "read"})
out = self.jobs.create(self.item("show", "abc"))
self.assertIn("evox read", out["result"]["stdout"])
def test_a_slow_one_is_answered_later(self):
it = self.item("wait", "2.5")
out = self.jobs.create(it)
self.assertEqual((out.get("ok"), "result" in out), (True, False))
self.assertEqual(self.jobs.get(it["id"])["status"], "running")
rec = self.wait_done(it["id"])
self.assertEqual(rec["status"], "applied")
self.assertEqual(OutboxMirror.terminal("cli", rec)["result"]["rc"], 0)
# the same id again (a lost ack) is not run twice
self.assertTrue(self.jobs.create(it).get("existing"))
def test_cancel_kills_it(self):
it = self.item("wait", "30")
self.jobs.create(it)
self.jobs.cancel(it["id"])
self.assertNotEqual(self.wait_done(it["id"])["result"]["rc"], 0)
def test_what_a_worker_may_not_run(self):
# `worktrees` is a plugin's now: refused like `plugin` is, short of Full
self.assertIn("Full", self.jobs.create(self.item("worktrees", "clean"))["error"])
err = self.jobs.create(self.item("plugin", "plans", "ls"))["error"]
self.assertIn("lab's", err)
self.assertIn("Full", err) # the switch that opens the rest
DEPS.worker_store.patch("evox", {"cli": "read"})
self.assertIn("Read + run", self.jobs.create(self.item("new", "x"))["error"])
self.assertTrue(self.jobs.create(self.item("ls")).get("ok"))
DEPS.worker_store.patch("evox", {"cli": "off"})
self.assertIn("off", self.jobs.create(self.item("ls"))["error"])
self.assertTrue(self.jobs.create({"id": "nope", "worker": "evox", "argv": ["ls"]})["failed"])
def test_full_is_the_owners_own_cli(self):
DEPS.worker_store.patch("evox", {"cli": "full"})
# the lab's commands, the plugins' — and nothing narrows the calls
out = self.jobs.create(self.item("plugin", "handoff", "start", "abc", "--model", "sonnet"))
self.assertTrue(out.get("ok"), out)
self.assertIn(f"['plugin', 'handoff', 'start', 'abc', '--model', 'sonnet'] None None {SID} tok True",
out["result"]["stdout"])
self.assertTrue(self.jobs.create(self.item("inbox")).get("ok"))
# a run it starts goes to the asking machine unless it says where
here = self.jobs.create(self.item("new", "do it"))["result"]["stdout"]
self.assertIn("['new', 'do it', '--on', 'evox']", here)
there = self.jobs.create(self.item("new", "do it", "--on", "lab"))["result"]["stdout"]
self.assertIn("['new', 'do it', '--on', 'lab']", there)
eq = self.jobs.create(self.item("new", "x", "--on=lab"))["result"]["stdout"]
self.assertNotIn("evox'", eq)
# `worktrees` is the Worktrees plugin's commands: Full runs it like any
# plugin command; nothing is the lab host's alone any more
self.assertEqual(worker_cli.LAB_ONLY, ())
self.assertIn("['worktrees', 'ls']",
self.jobs.create(self.item("worktrees", "ls"))["result"]["stdout"])
def test_full_is_never_a_guests(self):
DEPS.worker_store.put({"id": "guestbox", "name": "Dom's", "url": "http://g", "token": "t",
"owner": "dom", "cli": "full"})
self.assertEqual(worker_cli.mode(DEPS.worker_store.get("guestbox")), "off")
self.assertTrue(self.jobs.create(self.item("inbox", worker="guestbox"))["failed"])
def test_a_guests_computer_never_runs_it(self):
DEPS.worker_store.put({"id": "guestbox", "name": "Dom's", "url": "http://g", "token": "t",
"owner": "dom", "cli": "run"})
self.assertEqual(worker_cli.mode(DEPS.worker_store.get("guestbox")), "off")
self.assertTrue(self.jobs.create(self.item("ls", worker="guestbox"))["failed"])
self.assertTrue(self.jobs.create(self.item("ls", worker="ghost"))["failed"])
def test_a_session_id_that_isnt_one_is_not_passed_on(self):
out = self.jobs.create(self.item("ls", sid="../../etc"))
self.assertIn("evox run None", out["result"]["stdout"])
if __name__ == "__main__":
unittest.main()