Files
ai-agent/cli/test_ai_agent.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

804 lines
42 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The `ai-agent` CLI (ai_agent.py): what it sends to the hub and what it prints.
``python3 -m unittest test_ai_agent`` from ``cli/``."""
import io
import json
import os
import unittest
from contextlib import redirect_stderr, redirect_stdout
from unittest import mock
import ai_agent
SID = "aaaaaaaa-1111-4111-8111-111111111111"
PARENT = "bbbbbbbb-2222-4222-8222-222222222222"
CID = f"-home-x/{SID}.jsonl"
def card(state="finished", ended="2099-01-01T00:00:00.000Z", sid=SID, **meta):
return {"id": f"-home-x/{sid}.jsonl", "sessionId": sid, "title": "T", "cost": 0.5,
"endedAt": ended, "meta": {"state": state, **meta}}
THREAD = [{"role": "user", "kind": "text", "text": "do it", "mi": 0},
{"role": "assistant", "kind": "tool_use", "name": "Bash", "input": {"command": "ls"}},
{"role": "assistant", "kind": "text", "text": "done: 42", "mi": 1}]
class Fake:
"""A scripted hub: ``routes`` maps "METHOD path" to a value or a list
(popped per call, the last one sticks)."""
def __init__(self, routes):
self.routes = routes
self.calls = []
def __call__(self, method, path, body=None, query=None, timeout=30):
self.calls.append((method, path, body, query))
r = self.routes[f"{method} {path}"]
if isinstance(r, list):
r = r.pop(0) if len(r) > 1 else r[0]
if isinstance(r, Exception):
raise r
return r
class TestAiAgent(unittest.TestCase):
def run_cli(self, argv, routes, env=None):
fake = Fake(routes)
out, err = io.StringIO(), io.StringIO()
env = {"CLAUDE_SESSION_ID": PARENT, "AI_AGENT_OUTBOX_URL": "", **(env or {})}
with mock.patch.dict(os.environ, env, clear=False), \
mock.patch.object(ai_agent.Hub, "call", fake), \
mock.patch.object(ai_agent.time, "sleep", lambda s: None), \
redirect_stdout(out), redirect_stderr(err):
rc = ai_agent.main(argv)
return rc, fake.calls, out.getvalue(), err.getvalue()
def test_new_is_recorded_as_this_conversations_child(self):
rc, calls, out, _ = self.run_cli(
["new", "fix it", "--on", "mac", "--model", "sonnet", "--project", "zipgo"],
{"GET /api/models": {"models": []}, "POST /api/spawn": {"sessionId": SID}})
self.assertEqual(rc, 0)
_, path, body, _ = calls[-1]
self.assertEqual(body["parent"], PARENT)
self.assertEqual((body["worker"], body["model"], body["projects"]), ("mac", "sonnet", ["zipgo"]))
self.assertTrue(out.startswith(SID))
def test_detach_sends_no_parent(self):
_, calls, _, _ = self.run_cli(["new", "x", "--detach"], {"POST /api/spawn": {"sessionId": SID}})
self.assertNotIn("parent", calls[0][2])
def test_a_child_reports_back_unless_told_not_to(self):
_, calls, out, _ = self.run_cli(["new", "x"], {"POST /api/spawn": {"sessionId": SID}})
self.assertNotIn("report", calls[0][2]) # the hub's default: it reports
self.assertIn("reports back", out)
_, calls, out, _ = self.run_cli(["new", "x", "--no-report"],
{"POST /api/spawn": {"sessionId": SID}})
self.assertIs(calls[0][2]["report"], False)
self.assertNotIn("reports back", out)
_, _, out, _ = self.run_cli(["new", "x", "--detach"], {"POST /api/spawn": {"sessionId": SID}})
self.assertNotIn("reports back", out)
def test_send_names_its_own_session_as_the_parent(self):
kid = card("finished", spawnedBy={"sessionId": PARENT, "depth": 1})
_, calls, out, _ = self.run_cli(["send", SID, "and the tests?"], {
"GET /api/conversations": {"conversations": [kid]},
"POST /api/resume": {"sessionId": SID}})
body = [c[2] for c in calls if c[1] == "/api/resume"][0]
self.assertEqual(body["parent"], PARENT)
self.assertIn("reports back", out)
# Someone else's conversation: sent all the same, no report promised.
_, _, out, _ = self.run_cli(["send", SID, "hi"], {
"GET /api/conversations": {"conversations": [card("finished")]},
"POST /api/resume": {"sessionId": SID}})
self.assertNotIn("reports back", out)
def test_wait_polls_as_the_waiter(self):
"""Each poll names this session: a child of ours read here is claimed,
so the hub doesn't report it back as well."""
_, calls, _, _ = self.run_cli(["wait", SID], {
"GET /api/conversations": {"conversations": [card("finished")]},
"GET /api/conversation": {"thread": THREAD}})
polls = [c[3] for c in calls if c[1] == "/api/conversations"]
self.assertTrue(polls and all(q.get("waiter") == PARENT for q in polls[1:]))
def test_test_flag_marks_the_run(self):
_, calls, _, _ = self.run_cli(["new", "x", "--test"], {"POST /api/spawn": {"sessionId": SID}})
self.assertIs(calls[0][2]["test"], True)
_, calls, _, _ = self.run_cli(["new", "x"], {"POST /api/spawn": {"sessionId": SID}})
self.assertNotIn("test", calls[0][2])
def test_a_dash_prompt_is_read_from_stdin(self):
with mock.patch.object(ai_agent.sys, "stdin", io.StringIO("a long brief\n")):
_, calls, _, _ = self.run_cli(["new", "-", "--detach"],
{"POST /api/spawn": {"sessionId": SID}})
self.assertEqual(calls[0][2]["prompt"], "a long brief\n")
def test_new_from_a_terminal_guesses_no_parent(self):
"""No session of our own: the cwd's newest transcript is someone
else's conversation, never this one's parent."""
with mock.patch("notify.newest_transcript_for_cwd",
return_value=ai_agent.Path(f"/x/{PARENT}.jsonl")):
_, calls, _, _ = self.run_cli(
["new", "x"], {"POST /api/spawn": {"sessionId": SID}},
env={"CLAUDE_SESSION_ID": "", "NOTIFY_SESSION_RESOLVER": ""})
self.assertNotIn("parent", calls[0][2])
def test_wait_on_a_new_id_waits_for_its_card(self):
"""`new` then `wait <sid>` straight away: the card isn't indexed yet."""
rc, _, out, _ = self.run_cli(["wait", SID], {
"GET /api/conversations": [{"conversations": []}, # resolve: not yet
{"conversations": []},
{"conversations": [card("running")]},
{"conversations": [card("finished")]}],
"GET /api/conversation-summary": ai_agent.HubError(404, "not found"),
"GET /api/conversation": {"thread": THREAD}})
self.assertEqual(rc, 0)
self.assertIn("done: 42", out)
def test_wait_on_a_conversation_uid_waits_on_its_session(self):
"""A conversation's own id is UUID-shaped like a session id, but no
session has it: it resolves to the session that is then polled."""
uid = "019a4f2e-7c11-7a3b-9c2d-0e1f2a3b4c5d"
rc, calls, out, _ = self.run_cli(["wait", uid], {
"GET /api/conversations": [{"conversations": []}, # no such session
{"conversations": [card("finished")]}],
"GET /api/conversation-summary": {**card(), "id": uid},
"GET /api/conversation": {"thread": THREAD}})
self.assertEqual(rc, 0)
self.assertIn("done: 42", out)
polls = [c[3]["sessions"] for c in calls if c[1] == "/api/conversations"]
self.assertEqual(polls, [uid, SID])
def test_new_wait_prints_the_final_answer(self):
rc, _, out, _ = self.run_cli(["new", "x", "--wait"], {
"POST /api/spawn": {"sessionId": SID},
"GET /api/conversations": [{"conversations": []},
{"conversations": [card("running")]},
{"conversations": [card("finished")]}],
"GET /api/conversation": {"thread": THREAD}})
self.assertEqual(rc, 0)
self.assertIn("done: 42", out)
self.assertIn(f"/conversation/{CID}", out)
def test_a_clipped_answer_is_fetched_whole(self):
whole = "head " * 2000 + "THE END"
thread = THREAD[:2] + [{"role": "assistant", "kind": "text", "text": whole[:8000], "mi": 1,
"clipped": {"text": len(whole)}, "clipId": 3}]
rc, calls, out, _ = self.run_cli(["wait", SID], {
"GET /api/conversations": {"conversations": [card("finished")]},
"GET /api/conversation": {"thread": thread},
"GET /api/conversation-full-text": {"clipId": 3, "fields": {"text": whole}}})
self.assertEqual(rc, 0)
self.assertIn("THE END", out)
asked = [c[3] for c in calls if c[1] == "/api/conversation-full-text"]
self.assertEqual([a["clip"] for a in asked], [3])
def test_wait_ignores_a_finished_stamp_older_than_the_send(self):
rc, calls, out, _ = self.run_cli(["send", SID, "more", "--wait"], {
"GET /api/conversations": [{"conversations": [card()]}, # resolve
{"conversations": [card("finished", ended="2000-01-01T00:00:00.000Z")]},
{"conversations": [card("finished")]}],
"POST /api/resume": {"sessionId": SID},
"GET /api/conversation": {"thread": THREAD}})
self.assertEqual(rc, 0)
polls = [c for c in calls if c[1] == "/api/conversations"]
self.assertEqual(len(polls), 3)
def test_wait_times_out_with_exit_4(self):
with mock.patch.object(ai_agent.time, "monotonic", side_effect=[0, 0, 10_000, 10_000]):
rc, _, _, err = self.run_cli(["wait", SID, "--timeout", "5"], {
"GET /api/conversations": {"conversations": [card("running")]}})
self.assertEqual(rc, 4)
self.assertIn("still running", err)
def test_a_prefix_resolves_through_the_list(self):
rc, calls, out, _ = self.run_cli(["show", "aaaaaaaa"], {
"GET /api/conversations": {"conversations": [card(), card(sid=PARENT)]},
"GET /api/conversation": {"thread": THREAD}})
self.assertEqual(rc, 0)
self.assertEqual(calls[0][3]["limit"], 300)
self.assertIn("## Last answer\n\ndone: 42", out)
def test_an_ambiguous_prefix_is_refused(self):
twin = "aaaaaaaa-3333-4333-8333-333333333333"
rc, _, _, err = self.run_cli(["stop", "aaaaaaaa"], {
"GET /api/conversations": {"conversations": [card(), card(sid=twin)]}})
self.assertEqual(rc, 1)
self.assertIn("matches 2", err)
def test_a_viewer_link_is_an_id(self):
rc, calls, _, _ = self.run_cli(
["stop", f"https://ai-agent.lab.gabvdl.xyz/conversation/{CID}?m=3"],
{"GET /api/conversations": {"conversations": [card("running")]},
"POST /api/interrupt": {"ok": True, "sessionId": SID}})
self.assertEqual(rc, 0)
self.assertEqual(calls[0][3]["sessions"], SID)
self.assertEqual(calls[1][2], {"sessionId": SID})
def test_show_full_numbers_messages_for_fork(self):
_, _, out, _ = self.run_cli(["show", SID, "--full", "--tools"], {
"GET /api/conversations": {"conversations": [card()]},
"GET /api/conversation": {"thread": THREAD}})
self.assertIn("## You [0]", out)
self.assertIn("→ shell: ls", out) # an older hub's `Bash`, printed by its neutral name
self.assertIn("## Claude [1]", out)
def test_children_filters_on_spawned_by(self):
kid = card(sid=SID, spawnedBy={"sessionId": PARENT, "depth": 1})
other = card(sid="cccccccc-4444-4444-8444-444444444444")
_, _, out, _ = self.run_cli(["ls", "--children"], {
"GET /api/conversations": {"conversations": [kid, other]}})
self.assertIn("aaaaaaaa", out)
self.assertNotIn("cccccccc", out)
def test_hub_errors_are_one_line(self):
def boom(*a, **k):
raise ai_agent.HubError(409, "4 children already running (max 4)")
with mock.patch.object(ai_agent.Hub, "call", boom):
err = io.StringIO()
with redirect_stderr(err), mock.patch.dict(os.environ, {"AI_AGENT_OUTBOX_URL": ""}):
rc = ai_agent.main(["new", "x"])
self.assertEqual(rc, 1)
self.assertIn("ai-agent: 4 children already running (max 4) (HTTP 409)", err.getvalue())
def test_send_later_left_for_the_plugin(self):
"""``later`` / ``scheduled`` / ``unschedule`` are the Scheduled
conversations plugin's commands since 2026-11-28: the core only says
where they went, calling nothing."""
for argv, hint in ((["later", "x", "--in", "2h", "--to", "."], "add"),
(["scheduled", "--all"], "ls"), (["unschedule", "sch_1"], "cancel")):
rc, calls, out, err = self.run_cli(argv, {})
self.assertEqual((rc, calls, out), (2, [], ""), argv)
self.assertIn(f"ai-agent plugin scheduled-conversations {hint}", err)
def test_a_conversation_uid_or_its_link_resolves(self):
"""A conversation's own id is a UUIDv7, shaped like a session id: no
session has it, so the hub's summary endpoint answers."""
uid = "019a4f2e-7c11-7a3b-9c2d-0e1f2a3b4c5d"
for ref in (uid, f"https://ai-agent.lab.gabvdl.xyz/conversation/{uid}#m4"):
routes = {"GET /api/conversations": {"conversations": []},
"GET /api/conversation-summary": {**card(), "id": uid},
"POST /api/conversation-meta": {"ok": True}}
_, calls, _, _ = self.run_cli(["archive", ref], routes)
self.assertEqual(calls[1][1:4:2], ("/api/conversation-summary", {"id": uid}))
self.assertEqual(calls[2][2], {"id": SID, "archived": True})
def test_archive_and_title_go_through_conversation_meta(self):
routes = {"GET /api/conversations": {"conversations": [card()]},
"POST /api/conversation-meta": {"ok": True}}
_, calls, _, _ = self.run_cli(["archive", SID], dict(routes))
self.assertEqual(calls[1][2], {"id": SID, "archived": True})
_, calls, _, _ = self.run_cli(["title", SID, "Zipgo flags fix"], dict(routes))
self.assertEqual(calls[1][2], {"id": SID, "title": "Zipgo flags fix", "titleSource": "agent"})
def test_inbox_lists_what_waits_oldest_first(self):
rc, _, out, _ = self.run_cli(["inbox"], {
"GET /api/ask-form/forms": {"forms": [{"id": "f_1", "title": "Pick a layout",
"createdAt": "2026-10-30T10:00:00Z", "sessionId": SID}]},
"GET /api/inbox/waiting": {"items": []},
"GET /api/notify-log": {"notifications": [
{"kind": "ask", "id": "ask_1", "status": "pending", "body": "Deploy now?",
"expiresAt": "2099-01-01T00:00:00Z", "at": "2026-10-29T10:00:00Z"},
{"kind": "ask", "id": "ask_2", "status": "pending", "body": "Lapsed",
"expiresAt": "2000-01-01T00:00:00Z", "at": "2026-10-28T10:00:00Z"}]},
"GET /api/notifications/unread": {"notifications": [], "total": 0}})
self.assertEqual(rc, 0)
self.assertLess(out.index("Deploy now?"), out.index("Pick a layout"))
self.assertNotIn("Lapsed", out)
MODELS = {"models": [
{"id": "claude-opus-5-5", "alias": "opus", "label": "opus", "harness": "claude"},
{"id": "qwen/qwen3.8-27b", "label": "qwen 3.8", "displayName": "Qwen 3.8 27B (OpenRouter)",
"harness": "pi", "provider": "openrouter"},
{"id": "ggml-org/qwen3.8-27b", "label": "qwen 3.8 local",
"displayName": "Qwen 3.8 27B (EVOX2 LM Studio, local)", "harness": "pi", "provider": "evox2"},
{"id": "gpt-6-sol", "label": "gpt-6-sol", "harness": "opencode"}]}
def test_budget_prints_what_is_free_after_the_crons(self):
b = {"account": "personal", "window": "seven_day", "pct": 48.0,
"resetsAt": 1793556000, "hoursLeft": 19.2, "plan": {"label": "Max 20×"},
"rate": {"unitsPerPct": 56.25, "usdPerPct": 27.6, "source": "carried"},
"left": {"pct": 52.0, "units": 2925.0, "usd": 1435.0},
"upcoming": {"pct": 0.02, "units": 1.2, "items": [
{"kind": "cron", "id": "radar", "name": "Radar", "runs": 1,
"next": 1793516400, "unitsPerRun": 0.34, "sampled": 8, "units": 0.34}]},
"free": {"pct": 51.98, "units": 2923.8, "usd": 1434.0},
"pace": {"last6h": 0.4, "last24h": 0.3, "projected": 55.7, "needed": 2.71},
"families": {"opus": {"tokensPerPct": 86e6, "freeTokens": 4.47e9,
"unitsPerHour": 33.0, "rateRuns": 53, "streams": 4.6},
"fable": {"tokensPerPct": 19e6, "freeTokens": 0.99e9,
"unitsPerHour": 80.0, "rateRuns": 0, "streams": 1.9}}}
rc, calls, out, _ = self.run_cli(["budget"], {"GET /api/usage/budget": b})
self.assertEqual(rc, 0)
self.assertEqual(calls[0][3], {"account": "personal"})
self.assertIn("week 48% ", out)
self.assertIn("Radar", out)
self.assertIn("free 52.0%", out)
self.assertIn("4.5 Gtok opus", out)
self.assertIn("2.71%/h uses it all", out)
self.assertIn("4.6 opus (33 u/h)", out)
self.assertIn("1.9 fable (80 u/h, default)", out)
def test_a_model_picks_its_harness(self):
for want, model, harness in (("qwen", "qwen/qwen3.8-27b", "pi"),
("qwen local", "ggml-org/qwen3.8-27b", "pi"),
("gpt-6-sol", "gpt-6-sol", "opencode"),
("opus", "opus", "claude"),
("vendor/unlisted", "vendor/unlisted", None)):
_, calls, _, _ = self.run_cli(["new", "x", "--model", want], {
"GET /api/models": self.MODELS, "POST /api/spawn": {"sessionId": SID}})
body = calls[-1][2]
self.assertEqual((body["model"], body.get("harness")), (model, harness), want)
def test_a_word_skips_a_model_that_cannot_run_now(self):
rows = [dict(m) for m in self.MODELS["models"]]
rows[1]["unavailable"] = "OpenRouter key refused: API key expired."
_, calls, _, _ = self.run_cli(["new", "x", "--model", "qwen"], {
"GET /api/models": {"models": rows}, "POST /api/spawn": {"sessionId": SID}})
self.assertEqual(calls[-1][2]["model"], "ggml-org/qwen3.8-27b")
# Named exactly, the pick stands (the run will show the key's error).
_, calls, _, err = self.run_cli(["new", "x", "--model", "qwen/qwen3.8-27b"], {
"GET /api/models": {"models": rows}, "POST /api/spawn": {"sessionId": SID}})
self.assertEqual(calls[-1][2]["model"], "qwen/qwen3.8-27b")
self.assertIn("API key expired", err)
def test_send_never_switches_harness(self):
_, calls, _, _ = self.run_cli(["send", SID, "x", "--model", "qwen"], {
"GET /api/conversations": {"conversations": [card()]},
"GET /api/models": self.MODELS, "POST /api/resume": {"sessionId": SID}})
self.assertNotIn("harness", calls[-1][2])
def test_only_the_labs_own_checkout_is_refused_on_a_worker_itself(self):
# what a worker may run is its switch on the hub (off · read · run ·
# full), which this machine doesn't know: every other command goes
# to the hub, which answers or refuses
rc, calls, _, err = self.run_cli(["worktrees", "ls"], {},
env={"AI_AGENT_OUTBOX_URL": "http://w:8790"})
self.assertEqual((rc, calls), (2, []))
self.assertIn("the lab's own checkout", err)
self.assertNotIn("inbox", ai_agent.WORKER_NEVER)
self.assertNotIn("plugin", ai_agent.WORKER_NEVER)
def test_a_worker_command_names_its_worker_to_the_hub(self):
seen = {}
class Resp(io.BytesIO):
headers = {}
status = 200
def __enter__(self):
return self
def __exit__(self, *a):
return False
def urlopen(req, timeout=0):
seen.update({k.lower(): v for k, v in req.header_items()})
return Resp(b'{"conversations": []}')
with mock.patch.object(ai_agent, "AS_WORKER", "w1"), \
mock.patch.object(ai_agent, "AS_WORKER_MODE", "read"), \
mock.patch.object(ai_agent.urllib.request, "urlopen", urlopen):
ai_agent.Hub().get("/api/conversations")
self.assertEqual((seen.get("x-aia-as-worker"), seen.get("x-aia-as-worker-mode")),
("w1", "read"))
# ── a live plugin's own commands (plugin.json `commands`) ───────────────
CATALOGUE = {"commands": [
{"plugin": "memories", "pluginName": "Memories", "name": "ls", "summary": "Every memory",
"action": "index", "readOnly": True, "args": [],
"output": {"rows": "memories", "columns": ["slug", "type", "description"]},
"mcp": True, "tool": "plugin_memories_ls"},
{"plugin": "memories", "pluginName": "Memories", "name": "show", "summary": "One memory",
"action": "get", "readOnly": True,
"args": [{"name": "slug", "type": "string", "required": True, "positional": True},
{"name": "conversations", "type": "boolean", "required": False,
"positional": False, "default": False}],
"output": {"text": "content"}, "mcp": True, "tool": "plugin_memories_show"},
{"plugin": "plans", "pluginName": "Plans", "name": "set-status", "summary": "Set a status",
"action": "set_status", "readOnly": False,
"args": [{"name": "slug", "type": "string", "required": True, "positional": True},
{"name": "status", "type": "string", "required": True, "positional": True,
"enum": ["proposed", "done"]}],
"output": None, "mcp": False, "tool": None},
]}
IDX = "GET /api/plugins/memories/actions/index"
GET = "GET /api/plugins/memories/actions/get"
SCHED = {"commands": [
{"plugin": "scheduled-conversations", "pluginName": "Scheduled conversations",
"name": "add", "summary": "Schedule", "action": "create", "readOnly": False,
"args": [{"name": "prompt", "type": "string", "required": True, "positional": True},
{"name": "in", "type": "string", "required": False, "positional": False},
{"name": "to", "type": "string", "required": False, "positional": False,
"conversation": True}],
"output": None, "mcp": True, "tool": "plugin_scheduled-conversations_add"}]}
CREATE = "POST /api/plugins/scheduled-conversations/actions/create"
def test_a_conversation_arg_dot_is_this_run(self):
rc, calls, _, _ = self.run_cli(
["plugin", "scheduled-conversations", "add", "check the deploy", "--in", "2h", "--to", "."],
{"GET /api/plugins/commands": self.SCHED, self.CREATE: {"id": "sch_1"}})
self.assertEqual(rc, 0)
self.assertEqual(calls[-1][2], {"prompt": "check the deploy", "in": "2h", "to": PARENT})
def test_a_conversation_arg_resolves_any_spelling(self):
rc, calls, _, _ = self.run_cli(
["plugin", "scheduled-conversations", "add", "x", "--in", "2h",
"--to", f"https://ai-agent.lab.gabvdl.xyz/conversation/{SID}"],
{"GET /api/plugins/commands": self.SCHED,
"GET /api/conversations": {"conversations": [{"sessionId": SID, "id": "c1"}]},
self.CREATE: {"id": "sch_1"}})
self.assertEqual(rc, 0)
self.assertEqual(calls[-1][2]["to"], SID)
def test_a_conversation_arg_dot_needs_a_session(self):
rc, calls, _, err = self.run_cli(
["plugin", "scheduled-conversations", "add", "x", "--to", "."],
{"GET /api/plugins/commands": self.SCHED}, env={"CLAUDE_SESSION_ID": ""})
self.assertEqual(rc, 1)
self.assertNotIn(self.CREATE.split(" ", 1)[1], [c[1] for c in calls])
self.assertIn("no session id", err)
def test_a_plugin_command_reads_its_action_by_get(self):
rows = {"memories": [{"slug": "m1", "type": "user", "description": "Who Gabriel is"}]}
rc, calls, out, _ = self.run_cli(["plugin", "memories", "ls"], {
"GET /api/plugins/commands": self.CATALOGUE, self.IDX: rows})
self.assertEqual(rc, 0)
self.assertIn("m1", out)
self.assertIn("Who Gabriel is", out)
self.assertEqual([c[:2] for c in calls],
[("GET", "/api/plugins/commands"), ("GET", "/api/plugins/memories/actions/index")])
self.assertEqual(calls[1][3], {"payload": ""})
def test_a_plugin_commands_args_and_defaults_make_the_payload(self):
routes = {"GET /api/plugins/commands": self.CATALOGUE,
self.GET: {"slug": "m1", "content": "# Who", "readIn": []}}
rc, calls, out, _ = self.run_cli(["plugin", "memories", "show", "m1"], routes)
self.assertEqual((rc, out.strip()), (0, "# Who"))
self.assertEqual(json.loads(calls[1][3]["payload"]), {"slug": "m1", "conversations": False})
rc, calls, out, _ = self.run_cli(["plugin", "memories", "show", "m1", "--conversations",
"--json"], routes)
self.assertEqual(json.loads(out)["readIn"], [])
self.assertEqual(json.loads(calls[1][3]["payload"]), {"slug": "m1", "conversations": True})
def test_a_writing_plugin_command_posts(self):
rc, calls, _, _ = self.run_cli(["plugin", "plans", "set-status", "p1", "done"], {
"GET /api/plugins/commands": self.CATALOGUE,
"POST /api/plugins/plans/actions/set_status": {"ok": True}})
self.assertEqual(rc, 0)
self.assertEqual(calls[1][:3], ("POST", "/api/plugins/plans/actions/set_status",
{"slug": "p1", "status": "done"}))
def test_a_plugin_command_of_a_plugin_thats_off_says_so(self):
rc, _, _, err = self.run_cli(["plugin", "memories", "ls"], {
"GET /api/plugins/commands": self.CATALOGUE,
self.IDX: ai_agent.HubError(404, "plugin 'memories' not active")})
self.assertEqual(rc, 1)
self.assertIn("Memories plugin isn't installed", err)
rc, _, _, err = self.run_cli(["plugin", "nope", "ls"], {"GET /api/plugins/commands": self.CATALOGUE})
self.assertEqual(rc, 1)
self.assertIn("ai-agent plugin commands", err)
def test_a_plugin_id_as_a_core_command_points_to_its_commands(self):
rc, calls, _, err = self.run_cli(["memories"], {"GET /api/plugins/commands": self.CATALOGUE})
self.assertEqual(rc, 2)
self.assertIn("ai-agent plugin memories <command>", err)
self.assertIn("ls, show", err)
def test_plugin_commands_lists_every_command(self):
rc, _, out, _ = self.run_cli(["plugin", "commands"], {"GET /api/plugins/commands": self.CATALOGUE})
self.assertEqual(rc, 0)
self.assertIn("memories show SLUG [--conversations]", out)
self.assertIn("(MCP plugin_memories_ls)", out)
self.assertIn("plans set-status SLUG STATUS", out)
def test_plugin_call_reaches_any_action_raw(self):
rc, calls, out, _ = self.run_cli(
["plugin", "call", "movies", "op", "--payload", '{"op": "status", "id": 7}'],
{"POST /api/plugins/movies/actions/op": {"stage": "available"}})
self.assertEqual(rc, 0)
self.assertEqual(calls[0][:3], ("POST", "/api/plugins/movies/actions/op", {"op": "status", "id": 7}))
self.assertEqual(json.loads(out), {"stage": "available"})
rc, calls, _, _ = self.run_cli(["plugin", "call", "movies", "status", "--get"],
{"GET /api/plugins/movies/actions/status": {}})
self.assertEqual((rc, calls[0][3]), (0, {"payload": ""}))
def test_services_points_at_the_plugin(self):
rc, calls, out, err = self.run_cli(["services"], {})
self.assertEqual((rc, calls, out), (2, [], ""))
self.assertIn("ai-agent plugin services", err)
def test_the_management_verbs_stay_core(self):
rc, calls, out, _ = self.run_cli(["plugin", "ls"], {"GET /api/plugins": {"installed": []}})
self.assertEqual((rc, calls[0][:2]), (0, ("GET", "/api/plugins")))
# ── a guest's session (the guard's broker sets AIA_AS_SESSION) ──────────
def run_guest(self, argv, routes):
with mock.patch.object(ai_agent, "AS_SESSION", PARENT):
return self.run_cli(argv, routes)
def test_a_guest_session_gets_only_its_commands(self):
for argv in (["worktrees"], ["agents"], ["later", "x", "--in", "1h"],
["usage"], ["services"]):
rc, calls, _, err = self.run_guest(argv, {})
self.assertEqual((rc, calls), (2, []), argv)
self.assertIn("not open to a guest's session", err)
def test_inside_a_guests_run_the_cli_never_runs(self):
"""AIA_GUEST is set in every process of a guest's run, where loopback
would make this CLI the owner: it refuses whatever spelling reached it
(a path, quotes, `sh -c`, Monitor, a pi job with no guard) — also with
an AIA_AS_SESSION the run set itself. The broker's own env has no
AIA_GUEST, so brokered calls are untouched."""
for as_session in ("", PARENT):
with mock.patch.object(ai_agent, "IN_GUEST_RUN", True), \
mock.patch.object(ai_agent, "AS_SESSION", as_session):
for argv in (["ls"], ["new", "x", "--cwd", "~/homelab"], ["projects"]):
rc, calls, out, err = self.run_cli(argv, {})
self.assertEqual((rc, calls, out), (2, [], ""), argv)
self.assertIn("the hub runs this CLI for you", err)
def test_the_guest_flag_is_read_from_the_environment(self):
import subprocess
import sys
here = os.path.dirname(os.path.abspath(ai_agent.__file__))
env = {"PATH": "/usr/bin:/bin", "HOME": "/nonexistent",
"AI_AGENT_URL": "http://127.0.0.1:9"} # nothing listens there
p = subprocess.run([sys.executable, "-I", "-B", os.path.join(here, "ai_agent.py"), "ls"],
env={**env, "AIA_GUEST": "dom"}, capture_output=True, text=True,
timeout=30)
self.assertEqual(p.returncode, 2)
self.assertIn("not run", p.stderr)
# without it the CLI goes on to call the hub (and fails to reach this one)
p = subprocess.run([sys.executable, "-I", "-B", os.path.join(here, "ai_agent.py"), "ls"],
env=env, capture_output=True, text=True, timeout=30)
self.assertNotIn("the hub runs this CLI for you", p.stderr)
def test_a_guest_wait_is_one_slice(self):
with mock.patch.object(ai_agent, "GUEST_MAX_WAIT_S", 1):
rc, _, _, err = self.run_guest(["wait", SID, "--timeout", "3600"], {
"GET /api/conversations": {"conversations": [card("running")]}})
self.assertEqual(rc, 4)
self.assertIn("still running after 1s", err)
def test_a_guest_budget_is_their_month(self):
rc, calls, out, _ = self.run_guest(["budget"], {"GET /api/me": {
"budgetUsd": 20, "spentUsd": 5.5, "models": ["sonnet"],
"claude": {"connected": False}}})
self.assertEqual((rc, calls[0][1]), (0, "/api/me"))
self.assertIn("$5.50 of $20.00 · $14.50 left", out)
def test_a_guest_inbox_skips_the_owners_unread(self):
rc, calls, out, _ = self.run_guest(["inbox"], {
"GET /api/ask-form/forms": {"forms": []},
"GET /api/inbox/waiting": {"items": []},
"GET /api/notify-log": {"notifications": []}})
self.assertEqual(rc, 0)
self.assertNotIn("/api/notifications/unread", [c[1] for c in calls])
def test_every_call_carries_the_session_and_takes_the_guest_links(self):
seen = {}
class Resp(io.BytesIO):
headers = {"X-AIA-View-Url": "https://claude.example.test/"}
def __enter__(self):
return self
def __exit__(self, *a):
return False
def urlopen(req, timeout=None):
seen.update(req.header_items())
return Resp(b'{"projects": []}')
with mock.patch.object(ai_agent, "AS_SESSION", PARENT), \
mock.patch.object(ai_agent, "VIEW_URL", "https://admin"), \
mock.patch.object(ai_agent.urllib.request, "urlopen", urlopen):
ai_agent.Hub().get("/api/projects")
self.assertEqual(ai_agent.view_url("c/x.jsonl"),
"https://claude.example.test/conversation/c/x.jsonl")
self.assertEqual(seen.get("X-aia-as-session"), PARENT)
PAST = {"subjects": [{"key": "linear:INS-1", "kind": "linear", "id": "INS-1", "label": "INS-1",
"sources": ["#7"], "more": 0,
"running": [{"id": "p/r.jsonl", "sessionId": "r" * 8, "title": "Busy",
"startedAt": None, "url": "https://v/conversation/p/r.jsonl"}],
"past": [{"id": "p/a.jsonl", "sessionId": "a" * 8, "title": "Fix INS-1",
"endedAt": "2026-11-02T10:00:00Z", "state": "finished",
"url": "https://v/conversation/p/a.jsonl",
"excerpt": "PR #7 is up for INS-1"}]}],
"skipped": [], "maxAgeDays": 30}
class FakeTransport:
"""The worker's outbox: what was queued, and the states a poll walks
through (the last one repeats)."""
calls = []
states = []
cancelled = []
def submit(self, kind, payload):
FakeTransport.calls.append((kind, payload))
return 202, {"queued": True, "id": payload["id"]}
def status(self, oid, wait_s=0):
st = FakeTransport.states
return 200, {"id": oid, **(st.pop(0) if len(st) > 1 else st[0])}
def cancel(self, oid):
FakeTransport.cancelled.append(oid)
return 200, {}
def srow(sid, ended, text, worker=None, projects=(), title="T"):
return {"id": f"-home-x/{sid}.jsonl", "sessionId": sid, "title": title, "endedAt": ended,
"worker": worker, "projects": list(projects),
"msgs": [{"i": 0, "role": "user", "text": text}]}
OLD = "cccccccc-3333-4333-8333-333333333333"
NEW = "dddddddd-4444-4444-8444-444444444444"
INDEX = {"conversations": [
srow(OLD, "2026-10-01T00:00:00Z", "edge split raspy1 raspy2 raspy2 raspy2", projects=["raspy2"]),
srow(NEW, "2026-11-20T00:00:00Z", "the edge split, once more", worker="w1", projects=["coredns@x"]),
]}
WORKERS = {"workers": [{"id": "w1", "name": "Orus Macbook"}]}
class TestSearch(unittest.TestCase):
run_cli = TestAiAgent.run_cli
routes = {"GET /api/search-index": INDEX, "GET /api/workers": WORKERS}
def test_newest_first_with_the_machine(self):
rc, _, out, err = self.run_cli(["search", "edge", "split"], self.routes)
self.assertEqual(rc, 0)
first, second = [l for l in out.splitlines() if not l.startswith(" ")]
self.assertTrue(first.startswith(NEW[:8]) and "Orus Macbook" in first) # not by hit count
self.assertTrue(second.startswith(OLD[:8]) and " lab " in second)
self.assertIn("ai-agent show ID", err)
def test_an_or_fallback_when_nobody_has_every_word(self):
rc, _, out, err = self.run_cli(["search", "raspy2", "pihole"], self.routes)
self.assertIn("no conversation has all of", err)
self.assertIn("(1/2 words)", out)
self.assertIn(OLD[:8], out)
def test_project_and_since(self):
_, _, out, _ = self.run_cli(["search", "edge", "--project", "coredns"], self.routes)
self.assertNotIn(OLD[:8], out)
self.assertIn(NEW[:8], out)
_, _, out, _ = self.run_cli(["search", "edge", "--since", "2026-11-01"], self.routes)
self.assertEqual([l[:8] for l in out.splitlines() if not l.startswith(" ")], [NEW[:8]])
self.assertTrue(ai_agent._since("7d").startswith("20"))
def test_past_reads_a_conversation_prefix_as_that_conversation(self):
uid = "01a1e40a-9907-7a32-81d4-6bfc5a8f6240"
rc, calls, _, _ = self.run_cli(["past", "aaaaaaaa", "INS-1"], {
"GET /api/conversations": {"conversations": [dict(card(), id=uid)]},
"GET /api/past-conversations": PAST})
self.assertEqual(calls[-1][3]["keys"], f"{uid},INS-1")
def printed(stdout="", stderr="", rc=0):
return {"rc": rc, "stdout": stdout, "stderr": stderr}
class TestPast(unittest.TestCase):
run_cli = TestAiAgent.run_cli
def test_on_the_lab_it_asks_the_hub(self):
rc, calls, out, _ = self.run_cli(["past", "INS-1", "#7"],
{"GET /api/past-conversations": PAST})
self.assertEqual(rc, 0)
self.assertEqual(calls[-1][3], {"keys": "INS-1,#7", "session": PARENT})
self.assertIn("RUNNING NOW", out)
self.assertIn("PR #7 is up for INS-1", out)
def test_on_a_worker_it_goes_through_the_outbox(self):
FakeTransport.calls = []
FakeTransport.states = [{"status": "applied", "hub": {"ok": True, "result": printed(
'{"subjects": [{"key": "linear:INS-1"}]}\n')}}]
with mock.patch.object(ai_agent, "Transport", FakeTransport):
rc, calls, out, _ = self.run_cli(["past", "INS-1", "--json"], {},
env={"AI_AGENT_OUTBOX_URL": "http://w:8790"})
self.assertEqual(rc, 0)
self.assertEqual(calls, []) # never the hub
(kind, payload), = FakeTransport.calls
self.assertEqual((kind, payload["sessionId"], payload["argv"]),
("cli", PARENT, ["past", "INS-1", "--json"]))
self.assertTrue(payload["id"].startswith("cli_"))
self.assertIn('"linear:INS-1"', out)
class ToolNames(unittest.TestCase):
"""A hub's tool names before and since parser v45 print alike."""
def test_old_and_neutral_names_print_the_same(self):
for old, new in (("Bash", "shell"), ("TaskCreate", "todo"), ("Agent", "agent"),
("LS", "list_dir"), ("TaskOutput", "shell_output")):
self.assertEqual(ai_agent.tool_name(old), new)
self.assertEqual(ai_agent.tool_name(new), new)
for kept in ("claude:CronCreate", "mcp__linear__get_issue", "CronCreate"):
self.assertEqual(ai_agent.tool_name(kept), kept)
self.assertEqual(ai_agent.tool_name(None), "tool")
note = ai_agent._tool_note({"kind": "tool_use", "name": "shell", "input": {"command": "ls"}})
self.assertEqual(note, " → shell: ls")
class TestOnAWorker(unittest.TestCase):
"""A session on a worker: its command goes into the outbox as a ``cli``
item, the hub runs it, what it printed comes back — never a hub call."""
run_cli = TestAiAgent.run_cli
ENV = {"AI_AGENT_OUTBOX_URL": "http://w:8790"}
def setUp(self):
FakeTransport.calls, FakeTransport.cancelled = [], []
p = mock.patch.object(ai_agent, "Transport", FakeTransport)
p.start()
self.addCleanup(p.stop)
def test_what_the_hub_printed_is_printed_here(self):
FakeTransport.states = [{"status": "applied", "hub": {"ok": True, "result": printed(
"abc12345 running Fix it\n", "warn\n", 0)}}]
rc, calls, out, err = self.run_cli(["ls", "--limit", "3"], {}, env=self.ENV)
self.assertEqual((rc, calls, out, err), (0, [], "abc12345 running Fix it\n", "warn\n"))
def test_a_long_command_answers_later_with_its_exit_code(self):
FakeTransport.states = [{"status": "sent", "hub": {"ok": True}},
{"status": "applied", "result": printed("", "still running\n", 4)}]
rc, _, _, err = self.run_cli(["wait", SID, "--timeout", "30"], {}, env=self.ENV)
self.assertEqual(rc, 4)
self.assertIn("still running", err)
def test_a_refusal_is_an_error(self):
FakeTransport.states = [{"status": "failed", "hub": {
"failed": True, "error": "the ai-agent CLI is off for Orus"}}]
rc, _, _, err = self.run_cli(["new", "x"], {}, env=self.ENV)
self.assertEqual(rc, 1)
self.assertIn("is off for Orus", err)
def test_a_cwd_is_sent_as_this_machines_absolute_path(self):
FakeTransport.states = [{"status": "applied", "hub": {"result": printed(SID + "\n")}}]
self.run_cli(["new", "x", "--cwd", "~/code/app"], {}, env=self.ENV)
argv = FakeTransport.calls[0][1]["argv"]
self.assertEqual(argv[-2:], ["--cwd", os.path.expanduser("~/code/app")])
def test_dot_names_this_session(self):
FakeTransport.states = [{"status": "applied", "hub": {"result": printed()}}]
self.run_cli(["ls", "--children", "."], {}, env=self.ENV)
self.assertEqual(FakeTransport.calls[0][1]["sessionId"], PARENT)
def test_a_restarted_hub_says_to_run_it_again(self):
FakeTransport.states = [{"status": "sent"}, {"status": "expired"}]
rc, _, _, err = self.run_cli(["show", SID], {}, env=self.ENV)
self.assertEqual(rc, 1)
self.assertIn("run it again", err)
def test_the_hubs_own_run_of_it_is_not_sent_back_to_the_outbox(self):
# The hub runs the CLI with AIA_AS_WORKER and no outbox: a plain call.
with mock.patch.object(ai_agent, "AS_WORKER", "w1"), \
mock.patch.object(ai_agent, "AS_WORKER_MODE", "run"):
rc, calls, _, _ = self.run_cli(["ls"], {"GET /api/conversations": {"conversations": []}},
env={"AI_AGENT_OUTBOX_URL": ""})
self.assertEqual((rc, [c[1] for c in calls], FakeTransport.calls),
(0, ["/api/conversations"], []))
if __name__ == "__main__":
unittest.main()
class CronMoved(unittest.TestCase):
"""``ai-agent cron`` is the Cron jobs plugin's since 2026-11-28: the core
command only says where it went."""
def test_it_points_at_the_plugin(self):
err = io.StringIO()
a = ai_agent.build_parser().parse_args(["cron", "edit", "cel-recap", "--mail-html", "x"])
with redirect_stderr(err):
self.assertEqual(ai_agent.cmd_cron(a), 2)
self.assertIn("ai-agent plugin cron-jobs", err.getvalue())