Files

466 lines
22 KiB
Python

#!/usr/bin/env python3
"""Unit tests for the Handoff live plugin: the manifest and its files, the
backend (``handlers/handoff_lib.py``) against a fake hub — ``link`` stamping
both ends, the dialog's ``handoff`` (warm / cold / the 409s), the ``models``
shortlist, ``peek`` — the real ``Hub`` transport against a local HTTP server,
and a handler shim end to end (stdin JSON in, the ``_error`` answer out).
python3 -m pytest plugins/handoff/tests/test_plugin.py
"""
from __future__ import annotations
import json
import os
import pathlib
import subprocess
import sys
import threading
import unittest
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
sys.dont_write_bytecode = True
PLUGIN = pathlib.Path(__file__).resolve().parent.parent
HANDLERS = PLUGIN / "handlers"
sys.path.insert(0, str(HANDLERS))
import handoff_lib # noqa: E402
from handoff_lib import HandoffError, run # noqa: E402
SRC = "6fa67bc8-0000-4000-8000-000000000001"
NEW = "7a1b2c3d-0000-4000-8000-000000000002"
CID = "019a0000-0000-7000-8000-00000000c1d0"
def row(**kw):
r = {"id": CID, "sessionId": SRC, "title": "Ship the thing", "state": "finished",
"model": "claude-opus-5-5", "harness": "claude", "worker": "local", "archived": False}
r.update(kw)
return r
class FakeHub:
def __init__(self, rows=None, listed=None, models=None):
self.rows = {r["sessionId"]: r for r in (rows if rows is not None else [row()])}
self.listed = listed
self.models_resp = models or {}
self.data: dict[str, list] = {}
self.stored: dict[str, dict] = {}
self.sent: list[tuple] = []
self.runs: list[dict] = []
def conversation(self, sid):
if sid not in self.rows:
raise HandoffError("conversation not found", 404, "not_found")
return dict(self.rows[sid])
def conversations(self, days=365, limit=2000):
return list(self.listed if self.listed is not None else self.rows.values())
def set_data(self, sid, data, merge=True):
self.data.setdefault(sid, []).append((data, merge))
self.stored[sid] = {**(self.stored.get(sid) or {}), **data} if merge else dict(data)
return {"ok": True, "sessionId": sid, "data": self.stored[sid]}
def get_data(self, sid):
if sid not in self.rows and sid not in self.stored:
raise HandoffError("conversation not found", 404, "not_found")
return {"sessionId": sid, "data": self.stored.get(sid)}
def send(self, sid, prompt):
self.sent.append((sid, prompt))
return {"sessionId": sid, "delivered": "resume"}
def start_run(self, r):
self.runs.append(r)
return {"sessionId": "writer-sid-0001"}
def models(self):
return self.models_resp
class Base(unittest.TestCase):
def setUp(self):
self._ctx = os.environ.pop("AIA_USER_CONTEXT", None)
def tearDown(self):
os.environ.pop("AIA_USER_CONTEXT", None)
if self._ctx is not None:
os.environ["AIA_USER_CONTEXT"] = self._ctx
def act(self, action, payload=None, hub=None):
return run(action, payload or {}, hub or FakeHub())
def refused(self, action, payload, hub=None):
with self.assertRaises(HandoffError) as cm:
self.act(action, payload, hub)
return cm.exception
class TestManifest(unittest.TestCase):
def setUp(self):
self.m = json.loads((PLUGIN / "plugin.json").read_text())
def test_shape(self):
m = self.m
self.assertEqual((m["schema"], m["id"], m["name"]), (1, "handoff", "Handoff"))
self.assertEqual(set(m["capabilities"]), {"conversations.read", "conversations.send",
"runs.start", "models.read", "conversations.data"})
self.assertEqual(m["skill"], {"dir": "skill", "name": "handoff"})
self.assertRegex(m["color"], r"^#[0-9a-f]{6}$")
def test_actions_exist_and_are_owner_only(self):
self.assertEqual(set(self.m["actions"]), set(handoff_lib.ACTIONS))
for name, a in self.m["actions"].items():
script = PLUGIN / a["script"]
self.assertTrue(script.is_file(), script)
self.assertTrue(os.access(script, os.X_OK), script)
self.assertTrue(a.get("ownerOnly"), name)
self.assertTrue(self.m["actions"]["models"].get("readOnly"))
self.assertTrue(self.m["actions"]["peek"].get("readOnly"))
self.assertTrue(self.m["actions"]["links"].get("readOnly"))
self.assertFalse(self.m["actions"]["link"].get("readOnly"))
def test_ui_files(self):
ui = self.m["ui"]
(item,) = ui["menuItems"]
self.assertEqual((item["id"], item["where"], item["label"]), ("handoff", "conversation.menu", "Hand off…"))
places = {s["id"]: s["where"] for s in ui["slots"]}
self.assertEqual(places, {"from": "conversation.threadHeader", "to": "conversation.threadEnd"})
for s in ui["slots"]:
self.assertEqual(s["vis"]["key"], "banners")
for rel in [item["html"]] + [s["html"] for s in ui["slots"]]:
self.assertTrue((PLUGIN / rel).is_file(), rel)
def test_art_and_skill(self):
for rel in ("icon.svg", "illustration.webp", "README.md", "skill/SKILL.md", "skill/template.md",
"skill/scripts/handoff.py", "skill/scripts/hubclient.py"):
self.assertTrue((PLUGIN / rel).is_file(), rel)
wrapper = PLUGIN / "skill/scripts/handoff"
self.assertTrue(os.access(wrapper, os.X_OK))
self.assertTrue(os.access(PLUGIN / "skill/scripts/handoff.py", os.X_OK))
svg = (PLUGIN / "icon.svg").read_text()
for bad in ("<script", "foreignObject", "href=", "data:"):
self.assertNotIn(bad, svg)
class TestPrompts(unittest.TestCase):
def test_target_flags_quote(self):
self.assertEqual(handoff_lib.target_flags("qwen local", "pi", "Acme Macbook", None, "high"),
"--model 'qwen local' --harness pi --on 'Acme Macbook' --effort high")
def test_warm_prompt(self):
p = handoff_lib.warm_prompt("--model gpt", " use the staging DB ")
self.assertEqual(p, "Use the handoff skill to hand this conversation off — target: --model gpt."
"\n\nNote for the next agent: use the staging DB")
self.assertNotIn("Note", handoff_lib.warm_prompt("--model gpt", ""))
def test_cold_prompt(self):
p = handoff_lib.cold_prompt(CID, "gpt", "--model gpt", None)
self.assertTrue(p.startswith(f"Hand off conversation {CID} to gpt — write its handoff brief"))
self.assertIn(f"Use the handoff skill: run its `handoff material {CID} --model gpt`", p)
self.assertTrue(p.endswith("Your final message is the new conversation's link."))
class TestLink(Base):
def test_stamps_both_ends(self):
hub = FakeHub()
out = self.act("link", {"from": SRC, "to": NEW, "model": "gpt-6.1-sol", "harness": "PI",
"worker": "w-mac", "title": "ship the thing"}, hub)
self.assertTrue(out["ok"])
(frm, merge), = hub.data[NEW]
self.assertTrue(merge)
self.assertEqual(set(frm), {"from"})
f = frm["from"]
self.assertEqual((f["id"], f["sessionId"], f["title"], f["model"], f["harness"], f["worker"]),
(CID, SRC, "Ship the thing", "claude-opus-5-5", "claude", None))
self.assertRegex(f["at"], r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.000Z$")
(to, _), = hub.data[SRC]
t = to["to"]
self.assertEqual((t["sessionId"], t["id"], t["title"], t["model"], t["harness"], t["worker"]),
(NEW, None, "ship the thing", "gpt-6.1-sol", "pi", "w-mac"))
def test_unknown_harness_stays_null_and_lab_worker_is_none(self):
hub = FakeHub()
self.act("link", {"from": SRC, "to": NEW, "model": "gpt", "worker": "local"}, hub)
t = hub.data[SRC][0][0]["to"]
self.assertIsNone(t["harness"])
self.assertIsNone(t["worker"])
def test_source_by_conversation_id(self):
hub = FakeHub()
self.act("link", {"from": CID, "to": NEW}, hub)
self.assertIn(SRC, hub.data) # resolved to its session through the list
def test_refusals(self):
self.assertEqual(self.refused("link", {"from": "nope-not-there-0", "to": NEW}).status, 404)
self.assertEqual(self.refused("link", {"from": SRC, "to": SRC}).status, 400)
self.assertEqual(self.refused("link", {"from": SRC}).status, 400)
self.assertEqual(self.refused("link", {"from": SRC, "to": "../etc"}).status, 400)
def test_owner_only(self):
os.environ["AIA_USER_CONTEXT"] = json.dumps({"uid": "g1", "isOwner": False})
e = self.refused("link", {"from": SRC, "to": NEW})
self.assertEqual((e.status, e.kind), (403, "owner_only"))
class TestHandoff(Base):
def test_warm_sends_the_skill_turn(self):
hub = FakeHub()
out = self.act("handoff", {"sessionId": SRC, "model": "qwen local", "harness": "pi",
"effort": "high", "mode": "warm", "note": "mind the DB"}, hub)
self.assertEqual(out, {"ok": True, "mode": "warm", "sessionId": SRC})
(sid, prompt), = hub.sent
self.assertEqual(sid, SRC)
self.assertEqual(prompt, "Use the handoff skill to hand this conversation off — target: "
"--model 'qwen local' --harness pi --effort high."
"\n\nNote for the next agent: mind the DB")
self.assertEqual(hub.runs, [])
def test_warm_defaults_and_conversation_id(self):
hub = FakeHub()
self.act("handoff", {"conversationId": CID, "model": "opus"}, hub)
self.assertEqual(hub.sent[0][0], SRC)
def test_warm_needs_claude(self):
hub = FakeHub(rows=[row(harness="pi")])
e = self.refused("handoff", {"sessionId": SRC, "model": "opus", "mode": "warm"}, hub)
self.assertEqual((e.status, e.kind), (409, "handoff_warm_unavailable"))
self.assertEqual(hub.sent, [])
def test_cold_starts_a_haiku_test_writer(self):
hub = FakeHub(rows=[row(harness="pi")])
out = self.act("handoff", {"sessionId": SRC, "model": "gpt-6.1-sol", "worker": "Acme Macbook",
"mode": "cold", "note": "x"}, hub)
self.assertEqual(out, {"ok": True, "mode": "cold", "sessionId": "writer-sid-0001"})
(r,) = hub.runs
self.assertEqual((r["model"], r["harness"], r["worker"], r["test"]), ("haiku", "claude", "local", True))
self.assertEqual(r["title"], "Handoff brief: Ship the thing")
self.assertEqual(r["prompt"], handoff_lib.cold_prompt(
CID, "gpt-6.1-sol", "--model gpt-6.1-sol --on 'Acme Macbook'", "x"))
self.assertEqual(hub.sent, [])
def test_cold_needs_a_transcript(self):
hub = FakeHub(rows=[row(id=None)])
e = self.refused("handoff", {"sessionId": SRC, "model": "gpt", "mode": "cold"}, hub)
self.assertEqual((e.status, e.kind), (409, "handoff_source"))
def test_validation(self):
self.assertEqual(self.refused("handoff", {"sessionId": SRC}).status, 400)
self.assertEqual(self.refused("handoff", {"sessionId": SRC, "model": "x", "mode": "hot"}).status, 400)
self.assertEqual(self.refused("handoff", {"sessionId": SRC, "model": "x", "harness": "vim"}).status, 400)
self.assertEqual(self.refused("handoff", {"model": "x"}).status, 400)
self.assertEqual(self.refused("handoff", {"sessionId": "gone-gone-gone", "model": "x"}).status, 404)
class TestCommandPayloads(Base):
"""The manifest's ``commands`` send their arguments as the payload's keys:
``id`` for ``start`` / ``links``, ``mode`` defaulting to ``auto``."""
def test_start_takes_id_and_auto_picks_warm_for_claude(self):
hub = FakeHub()
out = self.act("handoff", {"id": SRC, "model": "gpt-6-sol", "mode": "auto"}, hub)
self.assertEqual(out["mode"], "warm")
self.assertEqual(hub.sent[0][0], SRC)
def test_auto_goes_cold_for_another_harness(self):
hub = FakeHub(rows=[row(harness="pi")])
out = self.act("handoff", {"id": SRC, "model": "opus", "mode": "auto"}, hub)
self.assertEqual(out["mode"], "cold")
self.assertEqual(hub.runs[0]["model"], "haiku")
self.assertFalse(hub.sent)
def test_links_after_a_link(self):
hub = FakeHub()
self.act("link", {"from": SRC, "to": NEW, "model": "gpt-6-sol", "title": "next"}, hub)
src = self.act("links", {"id": SRC}, hub)
self.assertIsNone(src["from"])
self.assertEqual((src["to"]["sessionId"], src["to"]["id"]), (NEW, None)) # not synced yet
new = self.act("links", {"id": NEW}, hub)
self.assertEqual((new["from"]["sessionId"], new["from"]["id"]), (SRC, CID))
self.assertIsNone(new["to"])
# Once the successor has synced, `to` carries its id and title.
hub.rows[NEW] = row(sessionId=NEW, id="019b-new", title="Continue: next", state="running")
src = self.act("links", {"id": SRC}, hub)
self.assertEqual((src["to"]["id"], src["to"]["title"], src["to"]["state"]),
("019b-new", "Continue: next", "running"))
def test_links_refusals(self):
self.assertEqual(self.refused("links", {}).status, 400)
self.assertEqual(self.refused("links", {"id": "gone-gone-gone"}).status, 404)
def test_every_command_names_a_declared_action_and_its_args_are_read(self):
m = json.loads((PLUGIN / "plugin.json").read_text())
reads = {"start": {"id", "model", "mode", "harness", "effort", "worker", "account", "note"},
"link": {"from", "to", "model", "harness", "worker", "title"},
"links": {"id"}, "models": set()}
self.assertEqual(set(m["commands"]), set(reads))
for name, c in m["commands"].items():
self.assertIn(c["action"], m["actions"], name)
self.assertEqual({a["name"] for a in c.get("args") or []}, reads[name], name)
self.assertEqual({k for k, c in m["commands"].items() if c.get("mcp")}, {"start", "link", "links"})
MODELS = {
"default": "opus",
"models": [
{"key": "opus", "id": "claude-opus-5-5", "alias": "opus", "harness": "claude", "vendor": "anthropic",
"label": "Opus 5.5"},
{"key": "sonnet", "id": "claude-sonnet-5-5", "alias": "sonnet", "harness": "claude",
"vendor": "anthropic", "label": "Sonnet 5.5"},
{"key": "opus-fast", "id": "claude-opus-5-5", "harness": "claude", "vendor": "anthropic", "fast": True},
{"key": "gpt", "id": "gpt-6.1-sol", "harness": "opencode", "vendor": "openai", "label": "GPT 6.1"},
{"key": "gpt", "id": "openai/gpt-6.1-sol", "harness": "pi", "vendor": "openai", "label": "GPT 6.1"},
{"key": "gem", "id": "gemini-4", "harness": "agy", "vendor": "google", "label": "Gemini 4",
"unavailable": "signed out"},
{"key": "qwen", "id": "qwen3.8", "harness": "pi", "vendor": "evox2", "displayName": "qwen local"},
],
"presets": {"gpt": {"harness": "opencode", "effort": "high"}},
}
class TestModels(Base):
def test_catalog_and_vendor_shortlist(self):
out = self.act("models", {}, FakeHub(models=MODELS))
keys = [c["key"] for c in out["models"]]
self.assertEqual(keys, ["opus", "sonnet", "gpt", "gem", "qwen"]) # fast twins skipped
gpt = next(c for c in out["models"] if c["key"] == "gpt")
self.assertEqual((gpt["model"], gpt["harness"], gpt["effort"]), ("gpt-6.1-sol", "opencode", "high"))
qwen = next(c for c in out["models"] if c["key"] == "qwen")
self.assertEqual(qwen["label"], "qwen local")
# one per vendor, unavailable ones out
self.assertEqual([c["key"] for c in out["shortlist"]], ["opus", "gpt", "qwen"])
self.assertEqual(out["default"], "opus")
def test_favourites_win(self):
resp = json.loads(json.dumps(MODELS))
resp["presets"] = {"sonnet": {"favorite": True}, "qwen": {"favorite": True},
"gem": {"favorite": True}}
out = self.act("models", {}, FakeHub(models=resp))
self.assertEqual([c["key"] for c in out["shortlist"]], ["sonnet", "qwen"])
def test_at_most_six(self):
resp = {"models": [{"key": f"m{i}", "id": f"m{i}", "harness": "pi", "vendor": f"v{i}"}
for i in range(9)]}
self.assertEqual(len(self.act("models", {}, FakeHub(models=resp))["shortlist"]), 6)
class TestPeek(Base):
def test_row(self):
out = self.act("peek", {"sessionId": SRC})
self.assertEqual((out["id"], out["title"], out["state"], out["harness"]),
(CID, "Ship the thing", "finished", "claude"))
def test_missing(self):
self.assertEqual(self.act("peek", {"sessionId": NEW}), {"missing": True, "sessionId": NEW})
# ── the real transport, against a local HTTP server ───────────────────────────
class _Server:
def __init__(self):
self.calls: list[tuple] = []
server = self
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def _answer(self, code, body):
raw = json.dumps(body).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
def _do(self, method):
n = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(n)) if n else None
server.calls.append((method, self.path, self.headers.get("Authorization"), body))
p = self.path
if p == f"/proxy/tools/plugins/handoff/hub/conversations/{SRC}":
return self._answer(200, row(harness="pi"))
if p.startswith("/proxy/tools/plugins/handoff/hub/conversations?"):
return self._answer(200, {"conversations": [row(harness="pi")]})
if p.endswith("/data"):
return self._answer(200, {"ok": True, "data": body["data"]})
if p.endswith("/send"):
return self._answer(403, {"error": {"message": "a guest's conversation",
"kind": "capability"}})
return self._answer(404, {"error": {"message": "conversation not found", "kind": "not_found"}})
def do_GET(self):
self._do("GET")
def do_POST(self):
self._do("POST")
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), H)
self.url = f"http://127.0.0.1:{self.httpd.server_address[1]}/proxy/tools"
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
def close(self):
self.httpd.shutdown()
self.httpd.server_close()
class TestTransport(Base):
def setUp(self):
super().setUp()
self.srv = _Server()
self.hub = handoff_lib.Hub(self.srv.url, "aiah1.tok")
def tearDown(self):
self.srv.close()
super().tearDown()
def test_link_over_http(self):
out = run("link", {"from": SRC, "to": NEW, "model": "gpt"}, self.hub)
self.assertTrue(out["ok"])
paths = [(c[0], c[1]) for c in self.srv.calls]
self.assertEqual(paths, [
("GET", f"/proxy/tools/plugins/handoff/hub/conversations/{SRC}"),
("POST", f"/proxy/tools/plugins/handoff/hub/conversations/{NEW}/data"),
("POST", f"/proxy/tools/plugins/handoff/hub/conversations/{SRC}/data"),
])
self.assertTrue(all(c[2] == "Bearer aiah1.tok" for c in self.srv.calls))
self.assertEqual(self.srv.calls[1][3]["merge"], True)
self.assertEqual(self.srv.calls[1][3]["data"]["from"]["harness"], "pi")
def test_errors_keep_status_and_kind(self):
with self.assertRaises(HandoffError) as cm:
run("handoff", {"sessionId": SRC, "model": "gpt", "mode": "cold"}, self.hub)
# pi source: cold is fine; runs → 404 from this server
self.assertEqual(cm.exception.status, 404)
with self.assertRaises(HandoffError) as cm:
run("peek", {"sessionId": "zzzzzzzz-1"}, handoff_lib.Hub(self.srv.url, ""))
self.assertEqual(cm.exception.kind, "config")
def test_peek_missing_over_http(self):
self.assertTrue(run("peek", {"sessionId": NEW}, self.hub)["missing"])
def test_shim_answers_a_structured_error(self):
env = {**os.environ, "AIA_TOOLS_URL": self.srv.url, "AIA_TOOLS_TOKEN": "aiah1.tok",
"AIA_PLUGIN_ID": "handoff", "AIA_USER_CONTEXT": json.dumps({"isOwner": True})}
p = subprocess.run([sys.executable, "-I", str(HANDLERS / "handoff.py")],
input=json.dumps({"sessionId": SRC, "model": "opus", "mode": "warm"}),
capture_output=True, text=True, env=env, timeout=30)
self.assertEqual(p.returncode, 0, p.stderr)
out = json.loads(p.stdout)
self.assertEqual(out["_error"]["status"], 409) # a pi source can't write its own
self.assertEqual(out["_error"]["kind"], "handoff_warm_unavailable")
def test_shim_success(self):
env = {**os.environ, "AIA_TOOLS_URL": self.srv.url, "AIA_TOOLS_TOKEN": "aiah1.tok",
"AIA_PLUGIN_ID": "handoff"}
p = subprocess.run([sys.executable, "-I", str(HANDLERS / "peek.py")],
input=json.dumps({"sessionId": SRC}), capture_output=True, text=True,
env=env, timeout=30)
self.assertEqual(p.returncode, 0, p.stderr)
self.assertEqual(json.loads(p.stdout)["id"], CID)
if __name__ == "__main__":
unittest.main()