agenthub/backend/tests/test_api_tasks.py

100 lines
4.3 KiB
Python

"""Task dispatch on the mock driver: events, streams, failures, cancellation."""
from __future__ import annotations
from tests.conftest import BASE, mock_agent, sse_payloads, task_status, wait_for
def dispatch(client, prompt: str, agent: str = "mocky", **fields) -> dict:
body = {"prompt": prompt, "agent_id": agent, **fields}
response = client.post(f"{BASE}/tasks", json=body)
assert response.status_code == 201, response.text
return response.json()
def test_task_runs_to_completion_and_records_usage(hub):
agent = mock_agent(hub, "mocky", reply="all good")
task = dispatch(hub, "summarise the incident", agent=agent["id"], wait=True)
assert task["status"] == "completed"
assert task["result"] == "all good"
assert task["agent_name"] == "mocky"
assert task["usage"]["output_tokens"] > 0
assert task["duration_s"] is not None
def test_streamed_events_are_persisted_in_order(hub):
mock_agent(hub, "mocky")
task = dispatch(hub, "x" * 90, wait=True)
events = hub.get(f"{BASE}/tasks/{task['id']}/events").json()
kinds = [row["kind"] for row in events]
assert kinds[0] == "status"
assert kinds.count("delta") >= 3
assert events == sorted(events, key=lambda row: row["seq"])
def test_finished_task_streams_a_replay_and_stops(hub):
mock_agent(hub, "mocky", reply="done")
task = dispatch(hub, "hello", wait=True)
frames = sse_payloads(hub.get(f"{BASE}/tasks/{task['id']}/stream").text)
kinds = [frame["kind"] for frame in frames]
assert all(frame["type"] == "replay" for frame in frames)
assert kinds[0] == "status" and kinds[-2:] == ["completed", "eof"]
assert frames[-1]["kind"] == "eof" and frames[-1]["payload"]["status"] == "completed"
def test_running_task_is_visible_then_completes(hub):
mock_agent(hub, "slowpoke", reply="slow" + " " * 200, delay_s=0.05)
task = dispatch(hub, "go", agent="slowpoke")
assert task["status"] in ("queued", "running")
assert wait_for(lambda: task_status(hub, task["id"]) == "completed")
raw = hub.get(f"{BASE}/tasks/{task['id']}/raw").json()
assert raw["task"]["status"] == "completed"
assert any(frame["kind"].startswith("task.") for frame in raw["frames"])
def test_driver_failure_becomes_a_failed_task(hub):
mock_agent(hub, "broken", fail=True)
task = dispatch(hub, "anything", agent="broken", wait=True)
assert task["status"] == "failed" and task["error"]
kinds = [row["kind"] for row in hub.get(f"{BASE}/tasks/{task['id']}/events").json()]
assert "failed" in kinds
def test_cancel_stops_a_running_task(hub):
mock_agent(hub, "slowpoke", reply="long" + " " * 600, delay_s=0.05)
task = dispatch(hub, "go", agent="slowpoke")
wait_for(lambda: task_status(hub, task["id"]) == "running")
assert hub.post(f"{BASE}/tasks/{task['id']}/cancel").status_code == 200
assert wait_for(lambda: task_status(hub, task["id"]) == "cancelled")
assert hub.post(f"{BASE}/tasks/{task['id']}/cancel").status_code == 409
def test_tasks_need_a_target(hub):
mock_agent(hub, "mocky")
assert hub.post(f"{BASE}/tasks", json={"prompt": "orphan"}).status_code in (400, 422)
assert hub.post(f"{BASE}/tasks", json={"prompt": "hi", "agent_id": "ghost"}).status_code in (400, 404)
def test_task_listing_filters(hub):
mock_agent(hub, "mocky")
for index in range(3):
dispatch(hub, f"job {index}", wait=True)
assert len(hub.get(f"{BASE}/tasks?status=completed").json()) == 3
assert len(hub.get(f"{BASE}/tasks?agent_id=mocky").json()) == 3
assert hub.get(f"{BASE}/tasks?status=failed").json() == []
stats = hub.get(f"{BASE}/stats").json()
assert stats["tasks"]["by_status"]["completed"] == 3
assert stats["agents"]["total"] == 1
def test_event_cursor_returns_only_what_is_new(hub):
"""Reconnecters pass ``since=<last seq>`` and must not see a row twice."""
mock_agent(hub, "mocky")
task = dispatch(hub, "x" * 90, wait=True)
events = hub.get(f"{BASE}/tasks/{task['id']}/events").json()
cursor = events[2]["seq"]
tail = hub.get(f"{BASE}/tasks/{task['id']}/events?since={cursor}").json()
assert [row["seq"] for row in tail] == [row["seq"] for row in events if row["seq"] > cursor]
assert tail[0]["seq"] == cursor + 1 and len(tail) == len(events) - 3
assert hub.get(f"{BASE}/tasks/{task['id']}/events?since={events[-1]['seq']}").json() == []