test_websocket_api.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import json
  2. import asyncio
  3. from collections.abc import AsyncIterator
  4. from pathlib import Path
  5. import httpx
  6. import pytest
  7. from fastapi.testclient import TestClient
  8. from pydantic import ValidationError
  9. from agent_lab.application.contracts import AgentParams, DebugRunRequest, EventAgentParams
  10. from agent_lab.application.queues import RuntimeQueues
  11. from agent_lab.application.runtime import DebugRuntime
  12. from agent_lab.domain.events import ToolCallEvent
  13. from agent_lab.domain.messages import ChatMessage, StreamItem
  14. from agent_lab.infrastructure.chat_client import OpenAICompatibleChatClient
  15. from agent_lab.presentation.web import create_app
  16. class FakeRuntime:
  17. def __init__(self) -> None:
  18. self.requests: list[DebugRunRequest] = []
  19. async def run(self, request: DebugRunRequest) -> AsyncIterator[dict]:
  20. self.requests.append(request)
  21. yield {"type": "session_started"}
  22. yield {"type": "message_delta", "content": "hello"}
  23. yield {"type": "done"}
  24. class QueueAwareRuntime:
  25. def __init__(self) -> None:
  26. self.requests: list[DebugRunRequest] = []
  27. self.queues: RuntimeQueues | None = None
  28. self.task: asyncio.Task | None = None
  29. def start(self, request: DebugRunRequest) -> RuntimeQueues:
  30. self.requests.append(request)
  31. self.queues = RuntimeQueues()
  32. self.task = asyncio.create_task(self._run())
  33. return self.queues
  34. async def _run(self) -> None:
  35. assert self.queues is not None
  36. await self.queues.output.put({"type": "session_started"})
  37. message = await self.queues.input.get()
  38. await self.queues.output.put(
  39. {"type": "message_delta", "content": message.content}
  40. )
  41. await self.queues.output.put({"type": "done"})
  42. async def aclose(self) -> None:
  43. if self.task is not None and not self.task.done():
  44. self.task.cancel()
  45. await asyncio.gather(self.task, return_exceptions=True)
  46. def _request_payload() -> dict:
  47. return {
  48. "user_message": "debug this",
  49. "system_prompts": ["You are a debugger."],
  50. "pre_messages": [{"role": "user", "content": "previous turn"}],
  51. "chat_agent": {
  52. "model": "fake-model",
  53. "temperature": 0.1,
  54. "max_tokens": 200,
  55. },
  56. "event_agent": {
  57. "enabled_tools": ["handoff_note"],
  58. "max_event_loops": 2,
  59. },
  60. }
  61. def test_health_returns_ok():
  62. app = create_app(runtime_factory=FakeRuntime)
  63. client = TestClient(app)
  64. response = client.get("/health")
  65. assert response.status_code == 200
  66. assert response.json() == {"status": "ok"}
  67. def test_api_tools_returns_handoff_note_metadata():
  68. app = create_app(runtime_factory=FakeRuntime)
  69. client = TestClient(app)
  70. response = client.get("/api/tools")
  71. assert response.status_code == 200
  72. assert response.json() == [
  73. {
  74. "name": "handoff_note",
  75. "description": "Send a note to the event agent.",
  76. "parameters": {
  77. "type": "object",
  78. "properties": {
  79. "message": {"type": "string"},
  80. },
  81. "required": ["message"],
  82. },
  83. }
  84. ]
  85. def test_websocket_debug_streams_runtime_messages():
  86. runtime = FakeRuntime()
  87. app = create_app(runtime_factory=lambda: runtime)
  88. client = TestClient(app)
  89. with client.websocket_connect("/ws/debug") as websocket:
  90. websocket.send_json(_request_payload())
  91. assert websocket.receive_json() == {"type": "session_started"}
  92. assert websocket.receive_json() == {
  93. "type": "message_delta",
  94. "content": "hello",
  95. }
  96. assert websocket.receive_json() == {"type": "done"}
  97. assert runtime.requests[0].user_message == "debug this"
  98. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  99. def test_websocket_debug_enqueues_user_messages_during_running_session():
  100. runtime = QueueAwareRuntime()
  101. app = create_app(runtime_factory=lambda: runtime)
  102. client = TestClient(app)
  103. with client.websocket_connect("/ws/debug") as websocket:
  104. websocket.send_json(_request_payload())
  105. assert websocket.receive_json() == {"type": "session_started"}
  106. websocket.send_json({"type": "user_message", "content": "follow-up"})
  107. assert websocket.receive_json() == {
  108. "type": "message_delta",
  109. "content": "follow-up",
  110. }
  111. assert websocket.receive_json() == {"type": "done"}
  112. assert runtime.requests[0].user_message == "debug this"
  113. def test_websocket_debug_sends_error_for_invalid_request():
  114. app = create_app(runtime_factory=FakeRuntime)
  115. client = TestClient(app)
  116. with client.websocket_connect("/ws/debug") as websocket:
  117. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  118. message = websocket.receive_json()
  119. assert message["type"] == "error"
  120. assert "user_message" in message["message"]
  121. def test_debug_run_request_rejects_invalid_pre_message_role():
  122. payload = _request_payload()
  123. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  124. with pytest.raises(ValidationError) as exc_info:
  125. DebugRunRequest.model_validate(payload)
  126. assert "role" in str(exc_info.value)
  127. def test_debug_run_request_rejects_tool_pre_messages():
  128. payload = _request_payload()
  129. payload["pre_messages"] = [
  130. {
  131. "role": "tool",
  132. "content": "orphan result",
  133. "tool_call_id": "call_1",
  134. }
  135. ]
  136. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  137. DebugRunRequest.model_validate(payload)
  138. def test_chat_message_allows_internal_tool_replies():
  139. message = ChatMessage(
  140. role="tool",
  141. content='{"message":"handled"}',
  142. name="handoff_note",
  143. tool_call_id="call_1",
  144. )
  145. assert message.role == "tool"
  146. assert message.tool_call_id == "call_1"
  147. class HistoryCapturingChatClient:
  148. def __init__(self) -> None:
  149. self.calls = 0
  150. self.second_call_messages: list[ChatMessage] = []
  151. async def stream_chat(
  152. self,
  153. messages: list[ChatMessage],
  154. tools: list[dict],
  155. params: AgentParams,
  156. ) -> AsyncIterator[StreamItem]:
  157. self.calls += 1
  158. if self.calls == 1:
  159. yield StreamItem.message_delta("Need event help.")
  160. yield StreamItem.event(
  161. ToolCallEvent(
  162. id="call_1",
  163. name="handoff_note",
  164. arguments={},
  165. raw_arguments="{}",
  166. )
  167. )
  168. return
  169. self.second_call_messages = list(messages)
  170. yield StreamItem.message_delta("Final answer.")
  171. @pytest.mark.asyncio
  172. async def test_runtime_appends_assistant_message_before_tool_reply_history():
  173. request = DebugRunRequest(
  174. user_message="debug this",
  175. system_prompts=["You are a debugger."],
  176. pre_messages=[],
  177. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  178. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  179. )
  180. client = HistoryCapturingChatClient()
  181. runtime = DebugRuntime(client)
  182. outputs = [message async for message in runtime.run(request)]
  183. assert client.calls == 2
  184. assert [message.role for message in client.second_call_messages] == [
  185. "system",
  186. "user",
  187. "assistant",
  188. "tool",
  189. ]
  190. assert client.second_call_messages[2].content == "Need event help."
  191. assert outputs[-1] == {"type": "done"}
  192. @pytest.mark.asyncio
  193. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  194. requests: list[httpx.Request] = []
  195. def handler(request: httpx.Request) -> httpx.Response:
  196. requests.append(request)
  197. payload = json.loads(request.content)
  198. assert payload["stream"] is True
  199. assert payload["model"] == "model-x"
  200. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  201. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  202. assert payload["temperature"] == 0.3
  203. assert payload["max_tokens"] == 50
  204. assert request.headers["authorization"] == "Bearer test-key"
  205. return httpx.Response(
  206. 200,
  207. content=(
  208. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  209. b"data: [DONE]\n\n"
  210. ),
  211. )
  212. async with httpx.AsyncClient(
  213. transport=httpx.MockTransport(handler),
  214. base_url="https://llm.test/v1",
  215. ) as http_client:
  216. client = OpenAICompatibleChatClient(
  217. api_key="test-key",
  218. base_url="https://llm.test/v1",
  219. default_model="default-model",
  220. request_timeout_seconds=5,
  221. http_client=http_client,
  222. )
  223. items = [
  224. item
  225. async for item in client.stream_chat(
  226. messages=[ChatMessage(role="user", content="hi")],
  227. tools=[
  228. {
  229. "type": "function",
  230. "function": {"name": "handoff_note", "parameters": {}},
  231. }
  232. ],
  233. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  234. )
  235. ]
  236. assert requests[0].url.path == "/v1/chat/completions"
  237. assert [item.content for item in items] == ["hi"]
  238. @pytest.mark.asyncio
  239. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  240. captured_payloads: list[dict] = []
  241. def handler(request: httpx.Request) -> httpx.Response:
  242. captured_payloads.append(json.loads(request.content))
  243. return httpx.Response(
  244. 200,
  245. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  246. )
  247. async with httpx.AsyncClient(
  248. transport=httpx.MockTransport(handler),
  249. base_url="https://llm.test/v1",
  250. ) as http_client:
  251. client = OpenAICompatibleChatClient(
  252. api_key="",
  253. base_url="https://llm.test/v1",
  254. default_model="provider-default",
  255. request_timeout_seconds=5,
  256. http_client=http_client,
  257. )
  258. [
  259. item
  260. async for item in client.stream_chat(
  261. messages=[ChatMessage(role="user", content="hi")],
  262. tools=[],
  263. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  264. )
  265. ]
  266. assert captured_payloads[0]["model"] == "provider-default"
  267. @pytest.mark.asyncio
  268. async def test_openai_chat_client_serializes_tool_reply_without_name():
  269. captured_payloads: list[dict] = []
  270. assistant_tool_call = {
  271. "id": "call_1",
  272. "type": "function",
  273. "function": {
  274. "name": "handoff_note",
  275. "arguments": '{"message":"inspect"}',
  276. },
  277. }
  278. def handler(request: httpx.Request) -> httpx.Response:
  279. captured_payloads.append(json.loads(request.content))
  280. return httpx.Response(
  281. 200,
  282. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  283. )
  284. async with httpx.AsyncClient(
  285. transport=httpx.MockTransport(handler),
  286. base_url="https://llm.test/v1",
  287. ) as http_client:
  288. client = OpenAICompatibleChatClient(
  289. api_key="",
  290. base_url="https://llm.test/v1",
  291. default_model="provider-default",
  292. request_timeout_seconds=5,
  293. http_client=http_client,
  294. )
  295. [
  296. item
  297. async for item in client.stream_chat(
  298. messages=[
  299. ChatMessage(
  300. role="assistant",
  301. content="",
  302. tool_calls=[assistant_tool_call],
  303. ),
  304. ChatMessage(
  305. role="tool",
  306. content="noted",
  307. name="handoff_note",
  308. tool_call_id="call_1",
  309. ),
  310. ],
  311. tools=[],
  312. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  313. )
  314. ]
  315. assert captured_payloads[0]["messages"] == [
  316. {
  317. "role": "assistant",
  318. "content": "",
  319. "tool_calls": [assistant_tool_call],
  320. },
  321. {
  322. "role": "tool",
  323. "content": "noted",
  324. "tool_call_id": "call_1",
  325. },
  326. ]
  327. @pytest.mark.asyncio
  328. async def test_openai_chat_client_rejects_tool_message_without_tool_call_id_before_network():
  329. network_called = False
  330. def handler(request: httpx.Request) -> httpx.Response:
  331. nonlocal network_called
  332. network_called = True
  333. return httpx.Response(
  334. 200,
  335. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  336. )
  337. async with httpx.AsyncClient(
  338. transport=httpx.MockTransport(handler),
  339. base_url="https://llm.test/v1",
  340. ) as http_client:
  341. client = OpenAICompatibleChatClient(
  342. api_key="",
  343. base_url="https://llm.test/v1",
  344. default_model="provider-default",
  345. request_timeout_seconds=5,
  346. http_client=http_client,
  347. )
  348. with pytest.raises(ValueError, match="tool messages require tool_call_id"):
  349. [
  350. item
  351. async for item in client.stream_chat(
  352. messages=[ChatMessage(role="tool", content="orphan tool result")],
  353. tools=[],
  354. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  355. )
  356. ]
  357. assert network_called is False
  358. def test_static_pre_message_role_selector_does_not_offer_tool():
  359. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  360. assert '<option value="tool">tool</option>' not in html
  361. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  362. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  363. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  364. assert 'id="tool-handoff-note"' not in html
  365. assert "#tool-handoff-note" not in js
  366. assert 'id="tool-list"' in html
  367. assert '"/api/tools"' in js
  368. assert "fetch" in js
  369. def test_static_prompt_workspace_controls_are_available():
  370. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  371. assert 'id="prompt-set-name"' in html
  372. assert 'id="saved-prompt-sets"' in html
  373. assert 'id="save-prompt-set"' in html
  374. assert 'id="load-prompt-set"' in html
  375. assert 'id="delete-prompt-set"' in html
  376. def test_static_prompt_workspace_uses_stable_storage_hooks():
  377. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  378. assert "agent-lab.prompt-sets.v1" in js
  379. assert "function savePromptSet()" in js
  380. assert "function loadPromptSet()" in js
  381. assert "function deletePromptSet()" in js
  382. def test_static_app_handles_backend_round_stats_messages():
  383. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  384. assert 'message.type === "round_stats"' in js
  385. assert "function updateRoundStats(" in js
  386. assert "#stat-ttft" in js
  387. assert "#stat-elapsed" in js
  388. @pytest.mark.asyncio
  389. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  390. captured_payloads: list[dict] = []
  391. def handler(request: httpx.Request) -> httpx.Response:
  392. captured_payloads.append(json.loads(request.content))
  393. return httpx.Response(
  394. 200,
  395. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  396. )
  397. async with httpx.AsyncClient(
  398. transport=httpx.MockTransport(handler),
  399. base_url="https://llm.test/v1",
  400. ) as http_client:
  401. client = OpenAICompatibleChatClient(
  402. api_key="",
  403. base_url="https://llm.test/v1",
  404. default_model="provider-default",
  405. request_timeout_seconds=5,
  406. include_usage=False,
  407. http_client=http_client,
  408. )
  409. [
  410. item
  411. async for item in client.stream_chat(
  412. messages=[ChatMessage(role="user", content="hi")],
  413. tools=[],
  414. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  415. )
  416. ]
  417. assert "stream_options" not in captured_payloads[0]