- Add conversations.tasks hub bridge (backend/plugins/hubtasks.py) and
retire legacy /api/conversation-task-{output,stop} routes & schemas.
- Add generic plugin points: aiAgentPlugin.openDetails(slotId?),
ui.toolCards match.hasField='taskId', match.hasInput, bare, and
inThreadWhile='active', plus task fields on toolCardInit/Update.
- Remove BackgroundShellsCard, BackgroundToolWidgets, and their
visibility/i18n wiring; keep liveBackgroundWork + StatusChip in core
and migrate DETAIL_CARD_RENAMES.backgroundShells.
- Wire background-shells mock harness and tests.
271 lines
13 KiB
Python
271 lines
13 KiB
Python
"""``conversations.tasks`` (2026-11-27) — the hub bridge behind the
|
|
``background-shells`` live plugin (``plugins/hubtasks.py``), plus the manifest
|
|
points it uses (``match.hasField: "taskId"``, ``match.hasInput``,
|
|
``inThreadWhile: "active"``, ``bare: true``) and a check that the retired core
|
|
``/api/conversation-task-*`` routes are gone.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
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",
|
|
"FORMS_PATH": TMP / "f.json", "FORM_SECRETS_PATH": TMP / "fs.json",
|
|
"ASKFORM_PATH": TMP / "af.json", "FRESH_CONTEXT_PATH": TMP / "fc.json",
|
|
"UI_STATE_PATH": TMP / "ui.json", "DRAFTS_PATH": TMP / "dr.json",
|
|
"TAG_META_PATH": TMP / "tm.json", "PROJECT_MERGES_PATH": TMP / "pm.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"SECURITY_LOG_PATH": TMP / "sl.jsonl", "SECURITY_STATE_PATH": TMP / "ss.json",
|
|
"MCP_PATH": TMP / "mcp.json", "PERF_SETTINGS_PATH": TMP / "ps.json",
|
|
"REPO_PLUGINS_PATH": TMP / "rp.json", "WORKER_ENROLL_PATH": TMP / "we.json",
|
|
"UPLOADS_DIR": TMP / "uploads",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"NEW_PROJECTS_PATH": TMP / "np.json", "PROJECTS_DIR": TMP / "projects",
|
|
"SCHEDULED_PATH": TMP / "scheduled.json",
|
|
"PLUGINS_DIR": TMP / "plugins", "PLUGINS_SEED_DIR": "",
|
|
"PLUGINS_LIVE_HARNESSES_DIR": TMP / "lh", "PLUGINS_LIVE_PROVIDERS_DIR": TMP / "lp",
|
|
"INTERNAL_API_TOKEN": "tok", "SIDECAR_TOKEN": "",
|
|
"PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from plugins import hubtasks, manifest # noqa: E402
|
|
from plugins.store import OWNER_UID # noqa: E402
|
|
from toolproxy import access as tp_access # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
SID = "11111111-2222-4333-8444-999999999999"
|
|
REL = f"-home-x/{SID}.jsonl"
|
|
MON_CMD = "tail -f build.log | grep --line-buffered -E 'ERROR|done'"
|
|
|
|
|
|
def _rec(kind, uuid, content, t):
|
|
return {"type": kind, "uuid": uuid, "sessionId": SID, "timestamp": f"2026-11-27T10:00:0{t}Z",
|
|
"message": {"role": kind, "content": content,
|
|
**({"model": "claude-opus-5-5"} if kind == "assistant" else {})}}
|
|
|
|
|
|
def write_transcript() -> None:
|
|
p = TMP / "arch" / REL
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
recs = [
|
|
_rec("user", "u1", "build it", 0),
|
|
_rec("assistant", "a1", [{"type": "tool_use", "id": "toolu_b", "name": "Bash",
|
|
"input": {"command": "npm run build", "description": "Build",
|
|
"run_in_background": True}}], 1),
|
|
_rec("user", "u2", [{"type": "tool_result", "tool_use_id": "toolu_b",
|
|
"content": "Command running in background with ID: bsh1. Output is "
|
|
"being written to: /tmp/x/tasks/bsh1.output"}], 2),
|
|
_rec("assistant", "a2", [{"type": "tool_use", "id": "toolu_m", "name": "Monitor",
|
|
"input": {"command": MON_CMD, "description": "build errors",
|
|
"timeout_ms": 300000}}], 3),
|
|
_rec("user", "u3", [{"type": "tool_result", "tool_use_id": "toolu_m",
|
|
"content": "Monitor started (task bmo1, expires in 5m unless the "
|
|
"source ends first)."}], 4),
|
|
_rec("assistant", "a3", [{"type": "text", "text": "watching"}], 5),
|
|
]
|
|
p.write_text("\n".join(json.dumps(r) for r in recs) + "\n")
|
|
|
|
|
|
def _make_plugin(root: pathlib.Path, pid: str = "bg-test", caps=("conversations.tasks",)):
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
(root / "card.html").write_text("<div>ok</div>")
|
|
(root / "plugin.json").write_text(json.dumps({
|
|
"schema": 1,
|
|
"id": pid,
|
|
"name": "BG Test",
|
|
"version": "1.0.0",
|
|
"capabilities": list(caps),
|
|
"ui": {
|
|
"toolCards": [
|
|
{
|
|
"id": "mon",
|
|
"label": "Monitor",
|
|
"match": {"tool": "claude:Monitor"},
|
|
"html": "card.html",
|
|
"height": 80,
|
|
"replace": True,
|
|
"bare": True,
|
|
"inThread": True,
|
|
"inThreadWhile": "active",
|
|
},
|
|
{
|
|
"id": "out",
|
|
"label": "TaskOutput",
|
|
"match": {"tool": "shell_output", "hasInput": "task_id"},
|
|
"html": "card.html",
|
|
"height": 80,
|
|
"replace": True,
|
|
"bare": True,
|
|
},
|
|
{
|
|
"id": "strip",
|
|
"label": "BashTask",
|
|
"match": {"tool": "shell", "hasField": "taskId"},
|
|
"html": "card.html",
|
|
"height": 26,
|
|
"bare": True,
|
|
},
|
|
],
|
|
},
|
|
}))
|
|
return root
|
|
|
|
|
|
class FakeSidecar:
|
|
def __init__(self, reply=None, status=None):
|
|
self.reply, self.status, self.calls = reply, status, []
|
|
|
|
def __call__(self, deps, path, payload=None, **kw):
|
|
self.calls.append((path, payload, kw.get("worker")))
|
|
if self.status:
|
|
raise HTTPException(self.status, {"message": "nothing there", "kind": "no_output"})
|
|
return dict(self.reply or {})
|
|
|
|
|
|
class ManifestPoints(unittest.TestCase):
|
|
def test_validates_has_input_has_field_bare_and_in_thread_while(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
mf = manifest.validate_manifest(_make_plugin(pathlib.Path(td)))
|
|
self.assertEqual(mf["capabilities"], ["conversations.tasks"])
|
|
self.assertFalse(manifest.requires_operator(mf))
|
|
tcs = {t["id"]: t for t in mf["ui"]["toolCards"]}
|
|
self.assertEqual(tcs["mon"]["inThreadWhile"], "active")
|
|
self.assertTrue(tcs["mon"]["bare"])
|
|
self.assertEqual(tcs["out"]["match"]["hasInput"], "task_id")
|
|
self.assertEqual(tcs["strip"]["match"]["hasField"], "taskId")
|
|
|
|
def test_in_thread_while_requires_in_thread(self):
|
|
with tempfile.TemporaryDirectory() as td:
|
|
root = pathlib.Path(td)
|
|
(root / "c.html").write_text("<div/>")
|
|
(root / "plugin.json").write_text(json.dumps({
|
|
"schema": 1, "id": "bad", "name": "Bad", "version": "1.0.0",
|
|
"ui": {"toolCards": [{
|
|
"id": "x", "match": {"tool": "claude:Monitor"}, "html": "c.html",
|
|
"inThreadWhile": "active",
|
|
}]},
|
|
}))
|
|
with self.assertRaises(manifest.ManifestError):
|
|
manifest.validate_manifest(root)
|
|
|
|
|
|
class HubTasksBridge(unittest.TestCase):
|
|
def setUp(self):
|
|
write_transcript()
|
|
DEPS.meta_store.update(SID, {"taskStops": None, "owner": None})
|
|
self._orig = hubtasks._sidecar_call
|
|
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
with tempfile.TemporaryDirectory() as td:
|
|
src = _make_plugin(pathlib.Path(td) / "src", pid="bg-test")
|
|
DEPS.plugin_store.install(OWNER_UID, str(src), is_owner=True, approve=True)
|
|
nocap = _make_plugin(pathlib.Path(td) / "nocap", pid="bg-nocap", caps=())
|
|
DEPS.plugin_store.install(OWNER_UID, str(nocap), is_owner=True, approve=True)
|
|
self.handler_tok = tp_access.mint_handler(OWNER_UID, "bg-test", 60)
|
|
self.nocap_tok = tp_access.mint_handler(OWNER_UID, "bg-nocap", 60)
|
|
|
|
def tearDown(self):
|
|
hubtasks._sidecar_call = self._orig
|
|
for pid in ("bg-test", "bg-nocap"):
|
|
try:
|
|
DEPS.plugin_store.uninstall(OWNER_UID, pid, purge=True)
|
|
except Exception:
|
|
pass
|
|
|
|
def use(self, fake):
|
|
hubtasks._sidecar_call = fake
|
|
return fake
|
|
|
|
def _hdr(self, tok=None):
|
|
return {"Authorization": f"Bearer {tok or self.handler_tok}"}
|
|
|
|
def test_core_routes_are_retired(self):
|
|
paths = {getattr(r, "path", "") for r in main.app.routes}
|
|
self.assertNotIn("/api/conversation-task-output", paths)
|
|
self.assertNotIn("/api/conversation-task-stop", paths)
|
|
r2 = self.c.post("/api/conversation-task-stop", json={"id": REL, "taskId": "bsh1"})
|
|
self.assertIn(r2.status_code, (404, 405))
|
|
|
|
def test_lists_tasks_for_conversation(self):
|
|
r = self.c.get(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks", headers=self._hdr())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertEqual(body["sessionId"], SID)
|
|
self.assertTrue(body["canStop"])
|
|
self.assertEqual([(t["taskId"], t["kind"]) for t in body["tasks"]],
|
|
[("bsh1", "shell"), ("bmo1", "monitor")])
|
|
self.assertEqual(body["tasks"][0]["command"], "npm run build")
|
|
self.assertEqual(body["tasks"][1]["timeoutMs"], 300000)
|
|
|
|
def test_capability_is_enforced(self):
|
|
r = self.c.get(f"/proxy/tools/plugins/bg-nocap/hub/conversations/{REL}/tasks",
|
|
headers=self._hdr(self.nocap_tok))
|
|
self.assertEqual(r.status_code, 403)
|
|
|
|
def test_output_tail_is_asked_of_the_runner(self):
|
|
fake = self.use(FakeSidecar({"lines": ["compiling", "done"], "more": True,
|
|
"size": 120, "mtime": 1.0, "end": "exited with code 0"}))
|
|
r = self.c.get(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks/bsh1/output",
|
|
params={"lines": 999}, headers=self._hdr())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
body = r.json()
|
|
self.assertTrue(body["available"])
|
|
self.assertEqual(body["lines"], ["compiling", "done"])
|
|
self.assertEqual(fake.calls, [("/tasks/output",
|
|
{"sessionId": SID, "taskId": "bsh1", "lines": 200}, None)])
|
|
|
|
def test_unknown_task_is_404(self):
|
|
fake = self.use(FakeSidecar({"lines": []}))
|
|
r1 = self.c.get(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks/bother/output",
|
|
headers=self._hdr())
|
|
r2 = self.c.post(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks/bother/stop",
|
|
headers=self._hdr())
|
|
self.assertEqual(r1.status_code, 404)
|
|
self.assertEqual(r2.status_code, 404)
|
|
self.assertEqual(fake.calls, [])
|
|
|
|
def test_missing_output_file_answers_unavailable(self):
|
|
self.use(FakeSidecar(status=404))
|
|
r = self.c.get(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks/bmo1/output",
|
|
headers=self._hdr())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["available"], False)
|
|
self.assertEqual(r.json()["reason"], "nothing there")
|
|
|
|
def test_monitor_stop_sends_command_and_stamps_meta(self):
|
|
fake = self.use(FakeSidecar({"stopped": [42], "forced": []}))
|
|
r = self.c.post(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks/bmo1/stop",
|
|
headers=self._hdr())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json(), {"ok": True, "taskId": "bmo1", "forced": False})
|
|
self.assertEqual(fake.calls[0][1], {"sessionId": SID, "taskId": "bmo1",
|
|
"kind": "monitor", "command": MON_CMD})
|
|
self.assertIn("bmo1", DEPS.meta_store.peek(SID)["taskStops"])
|
|
|
|
def test_shell_stop_sends_no_command_and_shows_in_tasks(self):
|
|
fake = self.use(FakeSidecar({"stopped": [42], "forced": [42]}))
|
|
r = self.c.post(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks/bsh1/stop",
|
|
headers=self._hdr())
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertTrue(r.json()["forced"])
|
|
self.assertEqual(fake.calls[0][1], {"sessionId": SID, "taskId": "bsh1",
|
|
"kind": "shell", "command": None})
|
|
r2 = self.c.get(f"/proxy/tools/plugins/bg-test/hub/conversations/{REL}/tasks", headers=self._hdr())
|
|
self.assertIsNotNone(r2.json()["tasks"][0]["stoppedAt"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|