agenthub/backend/tests/test_driver_nanobot_ws.py

256 lines
10 KiB
Python

"""nanobot WebSocket driver contract, locked against a scripted nanobot peer.
The peer below speaks the channel protocol the official WebUI uses — ``ready``
on connect, ``{"type":"message",…}`` inbound, ``delta`` / ``reasoning_delta`` /
``message``(kind=tool_hint) / ``stream_end`` / ``turn_end`` outbound — so if the
driver drifts away from nanobot's wire format, these tests fail instead of the
console quietly showing empty answers.
"""
from __future__ import annotations
import asyncio
import json
import threading
from typing import Any
from urllib.parse import parse_qs, urlsplit
import pytest
try: # websockets >= 15 exposes the asyncio server under this path
from websockets.asyncio.server import serve as ws_serve
except ImportError: # pragma: no cover - older websockets
from websockets import serve as ws_serve # type: ignore[attr-defined,no-redef]
from agenthub.adapters.base import AgentTarget, DriverError, Invocation
from agenthub.adapters.nanobot_ws import NanobotWsDriver, chat_id_for
from tests.conftest import BASE, add_agent, task_status, wait_for
DEFAULT_CHAT_ID = "3ab1c2d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
class FakeNanobotChannel:
"""Scripted stand-in for ``nanobot gateway``'s WebSocket channel."""
def __init__(self, *, answer: str = "hello") -> None:
self.answer = answer
self.port = 0
self.connections: list[str] = []
self.messages: list[dict[str, Any]] = []
self._loop: asyncio.AbstractEventLoop | None = None
self._thread: threading.Thread | None = None
self._ready = threading.Event()
def __enter__(self) -> "FakeNanobotChannel":
def run() -> None:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
self._loop.run_until_complete(self._serve())
self._loop.run_forever()
self._thread = threading.Thread(target=run, daemon=True)
self._thread.start()
assert self._ready.wait(5), "fake channel never bound"
return self
def __exit__(self, *exc: object) -> None:
assert self._loop is not None and self._thread is not None
self._loop.call_soon_threadsafe(self._loop.stop)
self._thread.join(5)
@property
def url(self) -> str:
return f"http://127.0.0.1:{self.port}"
async def _serve(self) -> None:
server = await ws_serve(self._handle, "127.0.0.1", 0)
self.port = server.sockets[0].getsockname()[1]
self._ready.set()
async def _handle(self, ws: Any) -> None:
self.connections.append(ws.request.path)
await ws.send(json.dumps({"event": "ready", "chat_id": DEFAULT_CHAT_ID, "client_id": "agenthub"}))
async for raw in ws:
frame = json.loads(raw)
if not isinstance(frame, dict) or frame.get("type") != "message":
continue
self.messages.append(frame)
for reply in self._script(str(frame.get("content") or ""), str(frame.get("chat_id") or "")):
await ws.send(json.dumps(reply, ensure_ascii=False))
def _script(self, content: str, chat_id: str) -> list[dict[str, Any]]:
if "boom" in content:
return [{"event": "error", "chat_id": chat_id, "detail": "access_denied"}]
if "fail" in content:
return [
{
"event": "turn_end",
"chat_id": chat_id,
"outcome": "failed",
"failure_kind": "model",
"failure_message": "quota exceeded",
}
]
return [
{"event": "reasoning_delta", "chat_id": chat_id, "text": "thinking ", "stream_id": "r1"},
{"event": "reasoning_end", "chat_id": chat_id, "stream_id": "r1"},
{
"event": "message",
"chat_id": chat_id,
"kind": "tool_hint",
"text": "running shell",
"tool_events": [{"name": "shell", "status": "ok"}],
},
{"event": "delta", "chat_id": chat_id, "text": self.answer[:2], "stream_id": "s1"},
{"event": "stream_end", "chat_id": chat_id, "text": self.answer, "stream_id": "s1"},
{
"event": "turn_end",
"chat_id": chat_id,
"usage": {"input_tokens": 21, "output_tokens": 4},
"latency_ms": 42,
},
]
def target(url: str, *, model: str = "", **config: Any) -> AgentTarget:
return AgentTarget(
id="agt-1",
name="nano-1",
driver="nanobot_ws",
connection_mode="direct",
base_url=url,
model=model,
auth={"token": "tok-1"},
config=config,
)
async def ask(driver: NanobotWsDriver, where: AgentTarget, prompt: str = "ship it", session: str = "session-42"):
events: list[tuple[str, dict]] = []
async def emit(kind: str, payload: dict) -> None:
events.append((kind, payload))
invocation = Invocation(task_id="task-1", prompt=prompt, target=where, session_key=session)
try:
return await driver.invoke(invocation, emit), events
finally:
await driver.close()
def test_invoke_speaks_the_webui_wire_protocol():
with FakeNanobotChannel(answer="hello nanobot") as channel:
result, events = asyncio.run(ask(NanobotWsDriver(), target(channel.url)))
assert result.text == "hello nanobot"
assert result.usage == {"input_tokens": 21, "output_tokens": 4}
assert result.meta["chat_id"] == "agenthub-session-42"
assert result.meta["latency_ms"] == 42
kinds = [kind for kind, _ in events]
assert kinds == ["status", "reasoning", "tool", "tool", "delta"]
assert events[1][1]["text"] == "thinking "
assert events[4][1]["text"] == "he" # deltas keep streaming, stream_end is authoritative
sent = channel.messages[0]
assert sent["chat_id"] == "agenthub-session-42"
assert sent["content"] == "ship it"
def test_the_socket_is_authenticated_the_way_nanobot_expects():
with FakeNanobotChannel() as channel:
asyncio.run(ask(NanobotWsDriver(), target(channel.url)))
path = channel.connections[0]
query = parse_qs(urlsplit(path).query)
assert query["client_id"] == ["agenthub-nano-1"]
assert query["token"] == ["tok-1"]
def test_hub_context_is_folded_into_the_single_content_field():
where = target("http://127.0.0.1:1")
invocation = Invocation(
task_id="t",
prompt="write the brief",
target=where,
context={"instructions": "you are the writer"},
)
from agenthub.adapters.nanobot_ws import _content
assert _content(invocation) == "# Instructions\nyou are the writer\n\nwrite the brief"
def test_error_and_failed_turns_become_driver_errors():
with FakeNanobotChannel() as channel:
with pytest.raises(DriverError) as rejected:
asyncio.run(ask(NanobotWsDriver(), target(channel.url), prompt="boom"))
assert "access_denied" in str(rejected.value)
with FakeNanobotChannel() as channel:
with pytest.raises(DriverError) as failed:
asyncio.run(ask(NanobotWsDriver(), target(channel.url), prompt="fail"))
assert "quota exceeded" in str(failed.value)
def test_probe_handshakes_and_describe_reports_the_transport():
with FakeNanobotChannel() as channel:
driver = NanobotWsDriver()
health = asyncio.run(driver.probe(target(channel.url)))
assert health["ok"] is True
assert health["websocket"] == f"ws://127.0.0.1:{channel.port}/"
capabilities = asyncio.run(driver.describe(target(channel.url, model="qwen3.6-plus")))
assert capabilities["streaming"] is True and capabilities["reasoning"] is True
assert capabilities["models"] == ["qwen3.6-plus"]
def test_an_unreachable_channel_is_retryable_and_cancel_is_not_claimed():
with pytest.raises(DriverError) as unreachable:
asyncio.run(NanobotWsDriver().probe(target("http://127.0.0.1:1")))
assert unreachable.value.retryable is True
assert "cannot reach nanobot WebSocket channel" in str(unreachable.value)
# nanobot's channel protocol has no abort envelope; the hub must not pretend it does.
assert asyncio.run(NanobotWsDriver().cancel(target("http://127.0.0.1:1"), "inv-1")) is False
def test_a_url_without_a_scheme_or_with_a_v1_suffix_still_resolves():
driver = NanobotWsDriver()
assert driver._base_ws_url(target("http://127.0.0.1:8900/v1")) == "ws://127.0.0.1:8900/"
assert driver._base_ws_url(target("http://127.0.0.1:8900/v1", path="/ws")) == "ws://127.0.0.1:8900/ws"
assert driver._base_ws_url(target("", ws_url="http://192.168.1.9:8765/")) == "ws://192.168.1.9:8765/"
with pytest.raises(DriverError):
driver._base_ws_url(target(""))
def test_chat_ids_are_stable_valid_and_isolated():
assert chat_id_for("session-42") == "agenthub-session-42"
assert chat_id_for("run:9") == "agenthub-run:9"
# a session key with spaces or absurd length must still produce a legal chat id
hashed = chat_id_for("a session with spaces")
assert hashed.startswith("agenthub-") and len(hashed) <= 64
assert hashed == chat_id_for("a session with spaces")
assert chat_id_for("x" * 200) != chat_id_for("y" * 200)
def test_a_nanobot_ws_agent_serves_a_real_hub_task(hub):
client = hub
with FakeNanobotChannel(answer="from the channel") as channel:
agent = add_agent(
client,
"nano-ws",
driver="nanobot_ws",
base_url=channel.url,
auth={"token": "tok-1"},
config={"ws_url": channel.url},
)
assert agent["driver"] == "nanobot_ws"
created = client.post(
f"{BASE}/tasks",
json={"agent_id": "nano-ws", "prompt": "hello", "session_key": "console-1"},
)
assert created.status_code == 201, created.text
task_id = created.json()["id"]
wait_for(lambda: task_status(client, task_id) == "completed")
detail = client.get(f"{BASE}/tasks/{task_id}").json()
assert detail["result"] == "from the channel"
events = client.get(f"{BASE}/tasks/{task_id}/events").json()
kinds = [event["kind"] for event in events]
assert "reasoning" in kinds and "tool" in kinds and "delta" in kinds
assert channel.messages[0]["chat_id"] == "agenthub-console-1"