GET /api/conversation-task-output (conversations.read) and POST /api/conversation-task-stop (runs.start + can_send(stop)), only for a Bash or Monitor card of that conversation; a Monitor's command comes off its own card. A stop is stamped on the meta (taskStops) so the card says "stopped by you". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
149 lines
7.0 KiB
Python
149 lines
7.0 KiB
Python
"""The Background shells card's two routes (runs/bgtasks.py): a task's output
|
|
tail and a stop, both sent to the session's runner — only for a task the
|
|
conversation itself started, a Monitor's command taken off its own card, and
|
|
a stop stamped on the meta (``taskStops``).
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
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", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"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",
|
|
"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 runs import bgtasks # 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-24T10: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")
|
|
|
|
|
|
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 Routes(unittest.TestCase):
|
|
def setUp(self):
|
|
write_transcript()
|
|
DEPS.meta_store.update(SID, {"taskStops": None})
|
|
self._orig = bgtasks._sidecar_call
|
|
self.c = TestClient(main.app, headers={"x-internal-auth": "tok"})
|
|
|
|
def tearDown(self):
|
|
bgtasks._sidecar_call = self._orig
|
|
|
|
def use(self, fake):
|
|
bgtasks._sidecar_call = fake
|
|
return fake
|
|
|
|
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("/api/conversation-task-output", params={"id": REL, "task": "bsh1", "lines": 999})
|
|
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_a_task_the_conversation_did_not_start_is_a_404(self):
|
|
fake = self.use(FakeSidecar({"lines": []}))
|
|
r = self.c.get("/api/conversation-task-output", params={"id": REL, "task": "bother"})
|
|
self.assertEqual(r.status_code, 404)
|
|
r = self.c.post("/api/conversation-task-stop", json={"id": REL, "taskId": "bother"})
|
|
self.assertEqual(r.status_code, 404)
|
|
self.assertEqual(fake.calls, [])
|
|
|
|
def test_a_missing_output_file_answers_unavailable(self):
|
|
self.use(FakeSidecar(status=404))
|
|
r = self.c.get("/api/conversation-task-output", params={"id": REL, "task": "bmo1"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["available"], False)
|
|
self.assertEqual(r.json()["reason"], "nothing there")
|
|
|
|
def test_a_monitor_stop_sends_its_own_command_and_stamps_the_meta(self):
|
|
fake = self.use(FakeSidecar({"stopped": [42], "forced": []}))
|
|
r = self.c.post("/api/conversation-task-stop", json={"id": REL, "taskId": "bmo1"})
|
|
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_a_shell_stop_sends_no_command(self):
|
|
fake = self.use(FakeSidecar({"stopped": [42], "forced": [42]}))
|
|
r = self.c.post("/api/conversation-task-stop", json={"id": REL, "taskId": "bsh1"})
|
|
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})
|
|
|
|
def test_the_stop_shows_on_the_conversation_meta(self):
|
|
self.use(FakeSidecar({"stopped": [42]}))
|
|
self.c.post("/api/conversation-task-stop", json={"id": REL, "taskId": "bsh1"})
|
|
r = self.c.get("/api/conversation", params={"id": REL})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertIn("bsh1", r.json()["meta"]["taskStops"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|