Files
ai-agent/backend/test_worker_cli.py
gabrielvidalandClaude Opus 5.5 e425f10358 feat(workers): the ai-agent CLI back on workers, through the outbox — any harness
On 2026-11-28 an agy run on the EVOX2 (2ca176fc) had no way to start a
conversation: since 2026-11-18 a worker's CLI kept only `past`, and the
hub's MCP — its stand-in — existed in Claude Code only. It shelled out to
three `claude -p --model haiku` relays to call start_conversation, which
named the worker EVOX2 (refused), had no parent to report to and polled
wait_for_conversation for 10+ minutes. Another agy run (25c32ca5) gave up
delegating. Gabriel's call: the CLI back on workers, the MCP stays.

The 2026-11-16 path, on today's code:
- cli/ai_agent.py: on a worker (AI_AGENT_OUTBOX_URL) the WORKER_COMMANDS
  go into the outbox as a `cli` item {argv, sessionId}; what the hub's run
  printed comes back (≈ 2–4 s, a `wait` when the run ends). The hub's run
  sends X-AIA-As-Worker + X-AIA-As-Worker-Mode.
- backend/workers/cli.py: CliJobs runs the same CLI in a clean env (host
  token, AIA_AS_WORKER, its switch as the mode, CLAUDE_SESSION_ID = the
  sending session → the parent of what it starts: children nest and report
  back). The narrowing is workers/bound.py worker_caller — the same caller
  as a worker-bound MCP connection, worker.read / worker.run scopes.
- The per-worker switch: workers.json `cli` off | read | run (unset = run,
  a guest's computer always off), PATCH /api/workers/{id} {cli}, Machines →
  the worker → Details → "ai-agent CLI".
- sidecar/outbox.py: the `cli` kind (results dropped 10 min after they end);
  outbox_mirror answers it; worker/install.sh writes the `ai-agent` terminal
  shim again.
- The conv-ref hook names the CLI on a worker; `past`'s lookup follows the
  switch. The bound MCP connection stays, optional.
- Docs: CLAUDE.md, docs/mcp.md, worker/README.md.

Tests: test_worker_cli.py (new), test_worker_bound.py, test_worker_routing.py,
sidecar test_outbox.py, cli test_ai_agent.py / test_conv_ref.py; the whole
backend per module matches main (test_typed_plugins' git-clone case fails on
both). A live local hub answered every worker command through the gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 12:57:34 +01:00

130 lines
5.7 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):
self.assertIn("lab's", self.jobs.create(self.item("worktrees", "clean", "--yes"))["error"])
self.assertIn("lab's", self.jobs.create(self.item("plugin", "plans", "ls"))["error"])
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_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()