Files
ai-agent/sidecar/test_outbox.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

216 lines
9.2 KiB
Python

"""The outbox: a run queues, the hub collects + answers, the run's wait returns."""
import threading
import time
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
import outbox
HUB = "hub-t0ken"
RUN = "run-t0ken"
def _hub_auth(h):
if h != f"Bearer {HUB}":
raise HTTPException(401, "unauthorized")
@pytest.fixture()
def box(tmp_path):
return outbox.Outbox(tmp_path / "outbox.json")
@pytest.fixture()
def app(box):
a = FastAPI()
a.include_router(outbox.make_router(box, _hub_auth, lambda: RUN))
return a
@pytest.fixture()
def run(app):
return TestClient(app, headers={"Authorization": f"Bearer {RUN}"})
@pytest.fixture()
def hub(app):
return TestClient(app, headers={"Authorization": f"Bearer {HUB}"})
ASK = {"id": "ask_0123456789ab", "question": "Ship?", "options": ["Yes", "No"]}
def test_run_token_is_minted_once_and_private(tmp_path):
t1 = outbox.run_token(tmp_path)
t2 = outbox.run_token(tmp_path)
assert t1 == t2 and len(t1) >= 32
assert oct((tmp_path / "outbox-token").stat().st_mode & 0o777) == "0o600"
def test_put_needs_run_token_and_a_cli_id(run, app):
anon = TestClient(app)
assert anon.post("/outbox", json={"kind": "ask", "payload": ASK}).status_code == 401
r = run.post("/outbox", json={"kind": "ask", "payload": {"id": "nope"}})
assert r.status_code == 400
r = run.post("/outbox", json={"kind": "ask", "payload": ASK})
assert r.status_code == 202 and r.json() == {"queued": True, "id": ASK["id"],
"status": "queued"}
# the same id can't be queued twice
assert run.post("/outbox", json={"kind": "ask", "payload": ASK}).status_code == 400
def test_hub_collects_acks_and_answers(run, hub, box):
run.post("/outbox", json={"kind": "ask", "payload": ASK})
# the run can't list the queue, the hub can
assert run.get("/outbox").status_code == 401
items = hub.get("/outbox").json()["items"]
assert [i["id"] for i in items] == [ASK["id"]] and items[0]["status"] == "queued"
hub.post(f"/outbox/{ASK['id']}/ack", json={"hub": {"ok": True, "id": ASK["id"]}})
it = run.get(f"/outbox/{ASK['id']}").json()
assert it["status"] == "sent" and it["hub"]["ok"] is True
# still listed (open) so the hub keeps checking for the answer
assert hub.get("/outbox").json()["count"] == 1
r = hub.post(f"/outbox/{ASK['id']}/answer",
json={"status": "answered", "answer": "Yes", "answerIndex": 0})
assert r.json()["status"] == "answered"
it = run.get(f"/outbox/{ASK['id']}").json()
assert (it["status"], it["answer"], it["answerIndex"]) == ("answered", "Yes", 0)
assert hub.get("/outbox").json()["count"] == 0 # done — off the list
assert box.get(ASK["id"])["endedAt"]
def test_wait_returns_the_instant_the_answer_lands(box):
box.put("ask", ASK)
box.ack(ASK["id"], {"ok": True})
got = {}
def waiter():
got["it"] = box.wait(ASK["id"], 10)
th = threading.Thread(target=waiter)
t0 = time.monotonic()
th.start()
time.sleep(0.2)
box.answer(ASK["id"], {"status": "answered", "answer": "No", "answerIndex": 1})
th.join(5)
assert got["it"]["answer"] == "No" and time.monotonic() - t0 < 3
def test_failed_ack_ends_the_item(run, hub):
run.post("/outbox", json={"kind": "form", "payload": {"id": "frm_0123456789ab",
"title": "", "fields": []}})
hub.post("/outbox/frm_0123456789ab/ack", json={"hub": {"failed": True,
"error": "need a title"}})
it = run.get("/outbox/frm_0123456789ab").json()
assert it["status"] == "failed" and it["hub"]["error"] == "need a title"
assert hub.get("/outbox").json()["count"] == 0
def test_cancel_before_and_after_collection(run, hub):
a, b = dict(ASK, id="ask_aaaaaaaaaaaa"), dict(ASK, id="ask_bbbbbbbbbbbb")
run.post("/outbox", json={"kind": "ask", "payload": a})
run.post("/outbox", json={"kind": "ask", "payload": b})
# a: cancelled while still queued → simply gone from the hub's view
assert run.post(f"/outbox/{a['id']}/cancel").json()["status"] == "cancelled"
assert [i["id"] for i in hub.get("/outbox").json()["items"]] == [b["id"]]
# b: collected, then cancelled → the hub is told once, then it's off the list
hub.post(f"/outbox/{b['id']}/ack", json={"hub": {"ok": True}})
run.post(f"/outbox/{b['id']}/cancel")
items = hub.get("/outbox").json()["items"]
assert items and items[0]["id"] == b["id"] and items[0]["cancelRequested"] is True
hub.post(f"/outbox/{b['id']}/ack", json={"hub": {"cancelled": True}})
assert hub.get("/outbox").json()["count"] == 0
def test_persists_across_a_restart(tmp_path):
b1 = outbox.Outbox(tmp_path / "o.json")
b1.put("notify", {"id": "ntf_0123456789ab", "title": "t", "message": "m"})
b2 = outbox.Outbox(tmp_path / "o.json")
assert b2.get("ntf_0123456789ab")["status"] == "queued"
assert [i["id"] for i in b2.pending()] == ["ntf_0123456789ab"]
def test_form_secret_is_readable_by_the_run_only(run, hub, box):
fid = "frm_0123456789ab"
run.post("/outbox", json={"kind": "form", "payload": {"id": fid, "title": "T",
"fields": []}})
hub.post(f"/outbox/{fid}/ack", json={"hub": {"ok": True, "id": fid}})
hub.post(f"/outbox/{fid}/answer", json={
"status": "submitted", "answers": {"tok": {"secret": True, "chars": 3}},
"secrets": {"tok": "abc"}})
# `notify wait` reads the item: the answers' placeholder, never the value
it = run.get(f"/outbox/{fid}").json()
assert it["answers"] == {"tok": {"secret": True, "chars": 3}}
assert "abc" not in str(it)
# only the run's token reads it — not the hub's, not an anonymous caller
assert hub.post(f"/outbox/{fid}/secret", json={"key": "tok"}).status_code == 401
r = run.post(f"/outbox/{fid}/secret", json={"key": "tok"})
assert r.status_code == 200 and r.json()["value"] == "abc"
assert run.post(f"/outbox/{fid}/secret", json={"key": "nope"}).status_code == 410
# forget drops it; expiry too
run.post(f"/outbox/{fid}/secret", json={"key": "tok", "forget": True})
assert run.post(f"/outbox/{fid}/secret", json={"key": "tok"}).status_code == 410
box.answer(fid, {"status": "submitted", "secrets": {"tok": "abc"}})
box._find(fid)["secretsExpire"] = time.time() - 1
assert box.secret(fid, "tok") is None and "secrets" not in box.get(fid)
assert "abc" not in box.path.read_text()
def test_askform_event_is_one_shot(box, hub):
"""An `ask-form serve` event (askform.py) is applied on collection: the
ack ends it, nothing waits on it."""
it = box.put("askform", {"id": "afe_0123456789ab", "event": "created",
"form": {"id": "project-setup_k3f9q2"}})
assert it["status"] == "queued"
assert [i["id"] for i in box.pending()] == ["afe_0123456789ab"]
hub.post("/outbox/afe_0123456789ab/ack", json={"hub": {"ok": True}})
assert box.get("afe_0123456789ab")["status"] == "applied"
assert box.pending() == []
with pytest.raises(ValueError):
box.put("askform", {"id": "ntf_0123456789ab"}) # the wrong prefix
with pytest.raises(ValueError):
box.put("notify", {"id": "afe_0123456789ab"})
CLI = {"id": "cli_0123456789ab", "sessionId": "s", "argv": ["ls", "--limit", "3"]}
def test_a_cli_command_answered_in_the_ack_ends_there(run, hub, box):
"""`ai-agent ls` on a worker: the hub ran it at once — what it printed is
the ack's ``result``, which ends the item."""
run.post("/outbox", json={"kind": "cli", "payload": CLI})
out = {"rc": 0, "stdout": "abc Fix it\n", "stderr": ""}
hub.post(f"/outbox/{CLI['id']}/ack", json={"hub": {"ok": True, "result": out}})
it = run.get(f"/outbox/{CLI['id']}").json()
assert it["status"] == "applied" and it["hub"]["result"] == out
assert hub.get("/outbox").json()["count"] == 0
with pytest.raises(ValueError):
box.put("cli", {"id": "lkp_0123456789ab", "argv": ["ls"]}) # the wrong prefix
def test_a_long_cli_command_is_answered_later(run, hub):
"""`ai-agent wait` on a worker: acked while it runs on the hub, its output
is the answer's ``result`` — which wakes the CLI's long-poll."""
run.post("/outbox", json={"kind": "cli", "payload": CLI})
hub.post(f"/outbox/{CLI['id']}/ack", json={"hub": {"ok": True, "id": CLI["id"]}})
assert run.get(f"/outbox/{CLI['id']}").json()["status"] == "sent"
assert hub.get("/outbox").json()["count"] == 1 # the hub keeps checking
out = {"rc": 4, "stdout": "", "stderr": "still running"}
hub.post(f"/outbox/{CLI['id']}/answer", json={"status": "applied", "result": out})
it = run.get(f"/outbox/{CLI['id']}").json()
assert (it["status"], it["result"]) == ("applied", out)
def test_a_read_cli_result_is_dropped_after_a_while(box):
box.put("cli", dict(CLI))
box.ack(CLI["id"], {"ok": True, "result": {"rc": 0, "stdout": "x" * 1000, "stderr": ""}})
box._find(CLI["id"])["collectedAt"] = "2000-01-01T00:00:00Z"
box._gc()
it = box.get(CLI["id"])
assert it["status"] == "applied" and "result" not in it["hub"]
assert "argv" not in it["payload"]