Files
ai-agent/backend/test_plugin_conv_data.py
gabrielvidalandClaude Opus 5.5 61ecbdd993 feat(plugins): handoffs leave the core for the Handoff plugin
The handoff link, the conversation menu's Hand off ▸, HandoffDialog, the
Continued from / Continued in banners and POST /api/handoff move to the
handoff live plugin (ai-agent-plugins). What the core keeps is generic:

- ui.menuItems (conversation.menu): a plugin row in the conversation menu
  opening the plugin's sandboxed dialog; frame bridges close() and toast()
- slot places conversation.threadHeader / conversation.threadEnd, whose
  update carries the plugin's own meta.plugins.<id> (pluginData)
- ConversationDetail.pluginData (owner only)
- conversations.data: GET|POST hub/conversations/{sid}/data, a plugin's
  own data on a conversation (handler only, owner only, operator approval)
- runs.start takes test; hub/conversations rows carry model and harness
- carryover.handoffs moves the old meta.handoffFrom / handoffTo stamps
  into meta.plugins.handoff once

Removed: runs/handoff.py, /api/handoff, SpawnBody.handoffFrom and the
spawn's handoff origin, meta.handoffFrom/handoffTo and their resolved refs,
Handoff.tsx, the Handoffs eye switch (the plugin's vis switch replaces it).
The CLI's --handoff-from and MCP handoff_from are left alone (inert) until
the CLI/MCP plugin-commands mechanism lands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 23:20:16 +01:00

253 lines
12 KiB
Python

"""The platform points the handoff plugin was built on (2026-11-26, when
handoffs left the core): ``ui.menuItems`` (a conversation menu row opening a
sandboxed dialog), the ``conversation.threadHeader`` / ``threadEnd`` slot
places, the ``conversations.data`` bridge (a plugin's own ``meta.plugins.<id>``
on a conversation), ``runs.start``'s ``test``, the model / harness on a
``hub/conversations`` row, ``ConversationDetail.pluginData``'s owner gate and
the carry-over of the core's old handoff stamps."""
from __future__ import annotations
import json
import os
import pathlib
import tempfile
import unittest
from unittest.mock import patch
os.environ.setdefault("INTERNAL_API_TOKEN", "tok")
from fastapi.testclient import TestClient # noqa: E402
import main # noqa: E402
from plugins import carryover, hubconvdata, hubruns, manifest # noqa: E402
from plugins.store import OWNER_UID, PluginStore # noqa: E402
from toolproxy import access # noqa: E402
OWNER_H = {"X-Internal-Auth": os.environ.get("INTERNAL_API_TOKEN", "")}
SID = "aaaaaaaa-1111-4111-8111-111111111111"
NEW = "bbbbbbbb-2222-4222-8222-222222222222"
def _write(root: pathlib.Path, mf: dict, files=("ui/dialog.html", "ui/from.html")) -> pathlib.Path:
root.mkdir(parents=True, exist_ok=True)
for f in files:
(root / f).parent.mkdir(parents=True, exist_ok=True)
(root / f).write_text("<p>x</p>")
(root / "plugin.json").write_text(json.dumps({"schema": 1, "id": "hp", "name": "H", **mf}))
return root
class FakeMeta:
def __init__(self, m=None):
self.m = m or {}
self.version = 0
def peek(self, sid):
return self.m.get(sid) or {}
def items(self):
return list(self.m.items())
def update(self, sid, patch):
cur = dict(self.m.get(sid) or {})
cur.update({k: v for k, v in patch.items() if v is not None})
self.m[sid] = cur
return cur
def stamp_many(self, patches):
n = 0
for cid, p in patches.items():
cur = dict(self.m.get(cid) or {})
diff = {k: v for k, v in p.items() if v is not None and cur.get(k) != v}
if diff:
self.m[cid] = {**cur, **diff}
n += 1
return n
class TestManifest(unittest.TestCase):
def test_menu_items_and_the_thread_places(self):
with tempfile.TemporaryDirectory() as td:
mf = manifest.validate_manifest(_write(pathlib.Path(td), {
"capabilities": ["conversations.data"],
"ui": {"menuItems": [{"id": "handoff", "where": "conversation.menu",
"label": "Hand off…", "icon": "arrow-right-left",
"html": "ui/dialog.html", "title": "Hand off", "height": 360}],
"slots": [{"id": "from", "where": "conversation.threadHeader",
"html": "ui/from.html"},
{"id": "to", "where": "conversation.threadEnd",
"html": "ui/from.html"}]}}))
self.assertEqual(mf["ui"]["menuItems"], [{
"id": "handoff", "where": "conversation.menu", "label": "Hand off…",
"html": "ui/dialog.html", "icon": "arrow-right-left", "title": "Hand off",
"height": 360}])
self.assertEqual([s["where"] for s in mf["ui"]["slots"]],
["conversation.threadHeader", "conversation.threadEnd"])
self.assertTrue(manifest.requires_operator(mf))
def test_no_menu_items_leaves_the_ui_as_it_was(self):
with tempfile.TemporaryDirectory() as td:
mf = manifest.validate_manifest(_write(pathlib.Path(td), {"ui": {"slots": []}}))
self.assertNotIn("menuItems", mf["ui"])
def test_bad_menu_items(self):
for item in ({"id": "x", "where": "home.menu", "label": "L", "html": "ui/dialog.html"},
{"id": "x", "where": "conversation.menu", "label": "", "html": "ui/dialog.html"},
{"id": "x", "where": "conversation.menu", "label": "L"},
{"id": "x", "where": "conversation.menu", "label": "L", "html": "../out.html"},
{"id": "x", "where": "conversation.menu", "label": "L", "html": "ui/dialog.html",
"icon": "Bad Icon"},
{"id": "x", "where": "conversation.menu", "label": "L", "html": "ui/dialog.html",
"height": 5}):
with tempfile.TemporaryDirectory() as td, self.assertRaises(manifest.ManifestError, msg=item):
manifest.validate_manifest(_write(pathlib.Path(td), {"ui": {"menuItems": [item]}}))
class TestUiRoutes(unittest.TestCase):
def test_menu_items_are_listed_and_served(self):
tc = TestClient(main.app)
with tempfile.TemporaryDirectory() as td:
src = _write(pathlib.Path(td) / "src", {"ui": {"menuItems": [{
"id": "handoff", "where": "conversation.menu", "label": "Hand off…",
"html": "ui/dialog.html"}]}})
store = PluginStore(pathlib.Path(td) / "data")
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
with patch.object(main.app.state.ai, "plugin_store", store):
ui = tc.get("/api/plugins", headers=OWNER_H).json()["ui"]
html = tc.get("/api/plugins/hp/ui/menuItem/handoff", headers=OWNER_H)
missing = tc.get("/api/plugins/hp/ui/menuItem/nope", headers=OWNER_H)
self.assertEqual([(m["id"], m["pluginId"]) for m in ui["menuItems"]], [("handoff", "hp")])
self.assertEqual((html.status_code, html.text), (200, "<p>x</p>"))
self.assertEqual(missing.status_code, 404)
class TestConvDataBridge(unittest.TestCase):
def setUp(self):
self.tc = TestClient(main.app)
def _call(self, td, fn, caps=("conversations.data",), meta=None, token=None):
src = _write(pathlib.Path(td) / "src", {"capabilities": list(caps)}, files=())
store = PluginStore(pathlib.Path(td) / "data")
store.install(OWNER_UID, str(src), is_owner=True, approve=True)
deps = main.app.state.ai
self.meta = FakeMeta(meta if meta is not None else {SID: {"title": "src"}})
self.published = []
tok = token or access.mint_handler(OWNER_UID, "hp", ttl=600)
with patch.object(deps, "plugin_store", store), patch.object(deps, "meta_store", self.meta), \
patch.object(deps.hub, "publish", self.published.append):
return fn({"Authorization": f"Bearer {tok}"})
def test_write_merge_read_and_clear(self):
url = f"/proxy/tools/plugins/hp/hub/conversations/{SID}/data"
def go(h):
a = self.tc.post(url, headers=h, json={"data": {"to": {"sessionId": NEW}}})
b = self.tc.post(url, headers=h, json={"data": {"from": {"sessionId": "x"}}})
c = self.tc.get(url, headers=h)
d = self.tc.post(url, headers=h, json={"data": {"from": None}})
e = self.tc.post(url, headers=h, json={"data": None, "merge": False})
return a, b, c, d, e
with tempfile.TemporaryDirectory() as td:
a, b, c, d, e = self._call(td, go)
self.assertEqual(a.status_code, 200, a.text)
self.assertEqual(b.json()["data"], {"to": {"sessionId": NEW}, "from": {"sessionId": "x"}})
self.assertEqual(c.json(), {"sessionId": SID, "data": {"to": {"sessionId": NEW},
"from": {"sessionId": "x"}}})
self.assertEqual(d.json()["data"], {"to": {"sessionId": NEW}})
self.assertIsNone(e.json()["data"])
self.assertEqual(self.meta.m[SID]["plugins"], {})
self.assertEqual(self.meta.m[SID]["title"], "src") # the rest of the meta untouched
self.assertIn({"type": "meta", "id": SID}, self.published)
def test_another_plugins_data_stays(self):
def go(h):
return self.tc.post(f"/proxy/tools/plugins/hp/hub/conversations/{SID}/data",
headers=h, json={"data": {"k": 1}})
with tempfile.TemporaryDirectory() as td:
r = self._call(td, go, meta={SID: {"plugins": {"ma": {"preset": "x"}}}})
self.assertEqual(r.status_code, 200, r.text)
self.assertEqual(self.meta.m[SID]["plugins"], {"ma": {"preset": "x"}, "hp": {"k": 1}})
def test_refusals(self):
url = f"/proxy/tools/plugins/hp/hub/conversations/{SID}/data"
with tempfile.TemporaryDirectory() as td:
no_cap = self._call(td, lambda h: self.tc.get(url, headers=h), caps=())
self.assertEqual(no_cap.status_code, 403)
with tempfile.TemporaryDirectory() as td: # the owner's run token: not the handler
run = self._call(td, lambda h: self.tc.get(url, headers=h), token=access.mint(OWNER_UID))
self.assertEqual(run.status_code, 403)
with tempfile.TemporaryDirectory() as td:
unknown = self._call(td, lambda h: self.tc.get(
f"/proxy/tools/plugins/hp/hub/conversations/{NEW}/data", headers=h))
self.assertEqual(unknown.status_code, 404)
with tempfile.TemporaryDirectory() as td:
guest = self._call(td, lambda h: self.tc.post(url, headers=h, json={"data": {}}),
meta={SID: {"owner": "g1"}})
self.assertEqual(guest.status_code, 403)
with tempfile.TemporaryDirectory() as td:
big = self._call(td, lambda h: self.tc.post(url, headers=h, json={
"data": {"x": "y" * 20_000}}))
self.assertEqual(big.status_code, 400)
with tempfile.TemporaryDirectory() as td:
bad = self._call(td, lambda h: self.tc.post(url, headers=h, json={"data": [1]}))
self.assertEqual(bad.status_code, 400)
def test_merged_drops_none_and_replaces_without_merge(self):
self.assertEqual(hubconvdata.merged({"a": 1, "b": 2}, {"b": None, "c": 3}, True),
{"a": 1, "c": 3})
self.assertEqual(hubconvdata.merged({"a": 1}, {"c": 3}, False), {"c": 3})
self.assertIsNone(hubconvdata.merged({"a": 1}, {"a": None}, True))
class TestRunsStartTest(unittest.TestCase):
def test_test_is_kept_only_when_true(self):
run, _ = hubruns.norm_run({"prompt": "x", "test": True})
self.assertIs(run["test"], True)
run, _ = hubruns.norm_run({"prompt": "x", "test": "yes"})
self.assertNotIn("test", run)
def test_start_run_stamps_it(self):
seen = {}
def send(deps, prompt, **kw):
seen.update(kw)
return {"sessionId": NEW}
meta = FakeMeta()
deps = main.app.state.ai
with patch("runs.service._send_message", send), patch.object(deps, "meta_store", meta):
hubruns.start_run(deps, "hp", {"prompt": "x", "worker": "local", "test": True})
self.assertEqual(seen["stamp"], {"plugin": "hp", "origin": "plugin", "test": True})
class TestConvRow(unittest.TestCase):
def test_model_and_harness(self):
from plugins.proxyroutes import _conv_row
row = _conv_row("/x/a.jsonl", {"sessionId": SID, "contextModel": "claude-opus-5-5"},
{"harness": "pi"})
self.assertEqual((row["model"], row["harness"]), ("claude-opus-5-5", "pi"))
row = _conv_row("/x/a.jsonl", {"sessionId": SID, "model": "m"}, {})
self.assertEqual((row["model"], row["harness"]), ("m", "claude"))
class TestCarryOver(unittest.TestCase):
def test_old_stamps_become_the_plugins_data_once(self):
frm = {"id": "c1", "sessionId": SID, "title": "t", "model": "opus", "harness": "claude",
"at": "2026-11-25T10:00:00.000Z"}
to = {"id": None, "sessionId": NEW, "model": "gpt", "harness": "pi", "worker": None,
"at": "2026-11-25T10:00:00.000Z"}
meta = FakeMeta({NEW: {"handoffFrom": frm}, SID: {"handoffTo": to, "plugins": {"ma": {"k": 1}}},
"c3": {"title": "plain"},
"c4": {"handoffTo": to, "plugins": {"handoff": {"to": {"sessionId": "newer"}}}}})
self.assertEqual(carryover.handoffs(meta), 2)
self.assertEqual(meta.m[NEW]["plugins"], {"handoff": {"from": frm}})
self.assertEqual(meta.m[SID]["plugins"], {"ma": {"k": 1}, "handoff": {"to": to}})
self.assertEqual(meta.m["c4"]["plugins"]["handoff"]["to"], {"sessionId": "newer"})
self.assertEqual(carryover.handoffs(meta), 0) # once
self.assertEqual(carryover.handoffs(None), 0)
if __name__ == "__main__":
unittest.main()