test_websocket_api.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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_agent_params_defaults_include_extra_body_and_event_agent_defaults_to_one_round():
  62. chat_params = AgentParams()
  63. event_params = EventAgentParams()
  64. assert chat_params.extra_body == {
  65. "thinking": {"type": "disabled"},
  66. "enable_search": False,
  67. "search_options": {"forced_search": False},
  68. }
  69. assert event_params.extra_body == chat_params.extra_body
  70. assert event_params.max_event_loops == 1
  71. assert event_params.system_prompt == ""
  72. def test_health_returns_ok():
  73. app = create_app(runtime_factory=FakeRuntime)
  74. client = TestClient(app)
  75. response = client.get("/health")
  76. assert response.status_code == 200
  77. assert response.json() == {"status": "ok"}
  78. def test_api_tools_returns_handoff_note_metadata():
  79. app = create_app(runtime_factory=FakeRuntime)
  80. client = TestClient(app)
  81. response = client.get("/api/tools")
  82. assert response.status_code == 200
  83. tools = response.json()
  84. assert [tool["name"] for tool in tools] == [
  85. "handoff_note",
  86. "mock_search",
  87. "mock_ticket",
  88. ]
  89. assert tools[0]["parameters"]["required"] == ["message"]
  90. def test_websocket_debug_streams_runtime_messages():
  91. runtime = FakeRuntime()
  92. app = create_app(runtime_factory=lambda: runtime)
  93. client = TestClient(app)
  94. with client.websocket_connect("/ws/debug") as websocket:
  95. websocket.send_json(_request_payload())
  96. assert websocket.receive_json() == {"type": "session_started"}
  97. assert websocket.receive_json() == {
  98. "type": "message_delta",
  99. "content": "hello",
  100. }
  101. assert websocket.receive_json() == {"type": "done"}
  102. assert runtime.requests[0].user_message == "debug this"
  103. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  104. def test_websocket_debug_enqueues_user_messages_during_running_session():
  105. runtime = QueueAwareRuntime()
  106. app = create_app(runtime_factory=lambda: runtime)
  107. client = TestClient(app)
  108. with client.websocket_connect("/ws/debug") as websocket:
  109. websocket.send_json(_request_payload())
  110. assert websocket.receive_json() == {"type": "session_started"}
  111. websocket.send_json({"type": "user_message", "content": "follow-up"})
  112. assert websocket.receive_json() == {
  113. "type": "message_delta",
  114. "content": "follow-up",
  115. }
  116. assert websocket.receive_json() == {"type": "done"}
  117. assert runtime.requests[0].user_message == "debug this"
  118. def test_websocket_debug_sends_error_for_invalid_request():
  119. app = create_app(runtime_factory=FakeRuntime)
  120. client = TestClient(app)
  121. with client.websocket_connect("/ws/debug") as websocket:
  122. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  123. message = websocket.receive_json()
  124. assert message["type"] == "error"
  125. assert "user_message" in message["message"]
  126. def test_debug_run_request_rejects_invalid_pre_message_role():
  127. payload = _request_payload()
  128. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  129. with pytest.raises(ValidationError) as exc_info:
  130. DebugRunRequest.model_validate(payload)
  131. assert "role" in str(exc_info.value)
  132. def test_debug_run_request_rejects_tool_pre_messages():
  133. payload = _request_payload()
  134. payload["pre_messages"] = [
  135. {
  136. "role": "tool",
  137. "content": "orphan result",
  138. "tool_call_id": "call_1",
  139. }
  140. ]
  141. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  142. DebugRunRequest.model_validate(payload)
  143. def test_chat_message_allows_internal_tool_replies():
  144. message = ChatMessage(
  145. role="tool",
  146. content='{"message":"handled"}',
  147. name="handoff_note",
  148. tool_call_id="call_1",
  149. )
  150. assert message.role == "tool"
  151. assert message.tool_call_id == "call_1"
  152. class HistoryCapturingChatClient:
  153. def __init__(self) -> None:
  154. self.calls = 0
  155. self.second_call_messages: list[ChatMessage] = []
  156. async def stream_chat(
  157. self,
  158. messages: list[ChatMessage],
  159. tools: list[dict],
  160. params: AgentParams,
  161. ) -> AsyncIterator[StreamItem]:
  162. self.calls += 1
  163. if self.calls == 1:
  164. yield StreamItem.message_delta("Need event help.")
  165. yield StreamItem.event(
  166. ToolCallEvent(
  167. id="call_1",
  168. name="handoff_note",
  169. arguments={},
  170. raw_arguments="{}",
  171. )
  172. )
  173. return
  174. self.second_call_messages = list(messages)
  175. yield StreamItem.message_delta("Final answer.")
  176. @pytest.mark.asyncio
  177. async def test_runtime_appends_assistant_message_before_tool_reply_history():
  178. request = DebugRunRequest(
  179. user_message="debug this",
  180. system_prompts=["You are a debugger."],
  181. pre_messages=[],
  182. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  183. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  184. )
  185. client = HistoryCapturingChatClient()
  186. runtime = DebugRuntime(client)
  187. outputs = [message async for message in runtime.run(request)]
  188. assert client.calls == 2
  189. assert [message.role for message in client.second_call_messages] == [
  190. "system",
  191. "user",
  192. "assistant",
  193. "tool",
  194. ]
  195. assert client.second_call_messages[2].content == "Need event help."
  196. assert outputs[-1] == {"type": "done"}
  197. @pytest.mark.asyncio
  198. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  199. requests: list[httpx.Request] = []
  200. def handler(request: httpx.Request) -> httpx.Response:
  201. requests.append(request)
  202. payload = json.loads(request.content)
  203. assert payload["stream"] is True
  204. assert payload["model"] == "model-x"
  205. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  206. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  207. assert payload["temperature"] == 0.3
  208. assert payload["max_tokens"] == 50
  209. assert request.headers["authorization"] == "Bearer test-key"
  210. return httpx.Response(
  211. 200,
  212. content=(
  213. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  214. b"data: [DONE]\n\n"
  215. ),
  216. )
  217. async with httpx.AsyncClient(
  218. transport=httpx.MockTransport(handler),
  219. base_url="https://llm.test/v1",
  220. ) as http_client:
  221. client = OpenAICompatibleChatClient(
  222. api_key="test-key",
  223. base_url="https://llm.test/v1",
  224. default_model="default-model",
  225. request_timeout_seconds=5,
  226. http_client=http_client,
  227. )
  228. items = [
  229. item
  230. async for item in client.stream_chat(
  231. messages=[ChatMessage(role="user", content="hi")],
  232. tools=[
  233. {
  234. "type": "function",
  235. "function": {"name": "handoff_note", "parameters": {}},
  236. }
  237. ],
  238. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  239. )
  240. ]
  241. assert requests[0].url.path == "/v1/chat/completions"
  242. assert [item.content for item in items] == ["hi"]
  243. @pytest.mark.asyncio
  244. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  245. captured_payloads: list[dict] = []
  246. def handler(request: httpx.Request) -> httpx.Response:
  247. captured_payloads.append(json.loads(request.content))
  248. return httpx.Response(
  249. 200,
  250. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  251. )
  252. async with httpx.AsyncClient(
  253. transport=httpx.MockTransport(handler),
  254. base_url="https://llm.test/v1",
  255. ) as http_client:
  256. client = OpenAICompatibleChatClient(
  257. api_key="",
  258. base_url="https://llm.test/v1",
  259. default_model="provider-default",
  260. request_timeout_seconds=5,
  261. http_client=http_client,
  262. )
  263. [
  264. item
  265. async for item in client.stream_chat(
  266. messages=[ChatMessage(role="user", content="hi")],
  267. tools=[],
  268. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  269. )
  270. ]
  271. assert captured_payloads[0]["model"] == "provider-default"
  272. @pytest.mark.asyncio
  273. async def test_openai_chat_client_serializes_tool_reply_without_name():
  274. captured_payloads: list[dict] = []
  275. assistant_tool_call = {
  276. "id": "call_1",
  277. "type": "function",
  278. "function": {
  279. "name": "handoff_note",
  280. "arguments": '{"message":"inspect"}',
  281. },
  282. }
  283. def handler(request: httpx.Request) -> httpx.Response:
  284. captured_payloads.append(json.loads(request.content))
  285. return httpx.Response(
  286. 200,
  287. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  288. )
  289. async with httpx.AsyncClient(
  290. transport=httpx.MockTransport(handler),
  291. base_url="https://llm.test/v1",
  292. ) as http_client:
  293. client = OpenAICompatibleChatClient(
  294. api_key="",
  295. base_url="https://llm.test/v1",
  296. default_model="provider-default",
  297. request_timeout_seconds=5,
  298. http_client=http_client,
  299. )
  300. [
  301. item
  302. async for item in client.stream_chat(
  303. messages=[
  304. ChatMessage(
  305. role="assistant",
  306. content="",
  307. tool_calls=[assistant_tool_call],
  308. ),
  309. ChatMessage(
  310. role="tool",
  311. content="noted",
  312. name="handoff_note",
  313. tool_call_id="call_1",
  314. ),
  315. ],
  316. tools=[],
  317. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  318. )
  319. ]
  320. assert captured_payloads[0]["messages"] == [
  321. {
  322. "role": "assistant",
  323. "content": "",
  324. "tool_calls": [assistant_tool_call],
  325. },
  326. {
  327. "role": "tool",
  328. "content": "noted",
  329. "tool_call_id": "call_1",
  330. },
  331. ]
  332. @pytest.mark.asyncio
  333. async def test_openai_chat_client_rejects_tool_message_without_tool_call_id_before_network():
  334. network_called = False
  335. def handler(request: httpx.Request) -> httpx.Response:
  336. nonlocal network_called
  337. network_called = True
  338. return httpx.Response(
  339. 200,
  340. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  341. )
  342. async with httpx.AsyncClient(
  343. transport=httpx.MockTransport(handler),
  344. base_url="https://llm.test/v1",
  345. ) as http_client:
  346. client = OpenAICompatibleChatClient(
  347. api_key="",
  348. base_url="https://llm.test/v1",
  349. default_model="provider-default",
  350. request_timeout_seconds=5,
  351. http_client=http_client,
  352. )
  353. with pytest.raises(ValueError, match="tool messages require tool_call_id"):
  354. [
  355. item
  356. async for item in client.stream_chat(
  357. messages=[ChatMessage(role="tool", content="orphan tool result")],
  358. tools=[],
  359. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  360. )
  361. ]
  362. assert network_called is False
  363. def test_static_pre_message_role_selector_does_not_offer_tool():
  364. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  365. assert '<option value="tool">tool</option>' not in html
  366. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  367. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  368. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  369. assert 'id="tool-handoff-note"' not in html
  370. assert "#tool-handoff-note" not in js
  371. assert 'id="tool-list"' in html
  372. assert '"/api/tools"' in js
  373. assert "fetch" in js
  374. def test_static_prompt_workspace_controls_are_available():
  375. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  376. assert 'id="prompt-set-name"' in html
  377. assert 'id="saved-prompt-sets"' in html
  378. assert 'id="save-prompt-set"' in html
  379. assert 'id="load-prompt-set"' in html
  380. assert 'id="delete-prompt-set"' in html
  381. def test_static_prompt_workspace_uses_stable_storage_hooks():
  382. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  383. assert "agent-lab.prompt-sets.v1" in js
  384. assert "function savePromptSet()" in js
  385. assert "function loadPromptSet()" in js
  386. assert "function deletePromptSet()" in js
  387. def test_static_app_handles_backend_round_stats_messages():
  388. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  389. assert 'message.type === "round_stats"' in js
  390. assert "function updateRoundStats(" in js
  391. assert "#stat-ttft" in js
  392. assert "#stat-elapsed" in js
  393. @pytest.mark.asyncio
  394. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  395. captured_payloads: list[dict] = []
  396. def handler(request: httpx.Request) -> httpx.Response:
  397. captured_payloads.append(json.loads(request.content))
  398. return httpx.Response(
  399. 200,
  400. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  401. )
  402. async with httpx.AsyncClient(
  403. transport=httpx.MockTransport(handler),
  404. base_url="https://llm.test/v1",
  405. ) as http_client:
  406. client = OpenAICompatibleChatClient(
  407. api_key="",
  408. base_url="https://llm.test/v1",
  409. default_model="provider-default",
  410. request_timeout_seconds=5,
  411. include_usage=False,
  412. http_client=http_client,
  413. )
  414. [
  415. item
  416. async for item in client.stream_chat(
  417. messages=[ChatMessage(role="user", content="hi")],
  418. tools=[],
  419. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  420. )
  421. ]
  422. assert "stream_options" not in captured_payloads[0]
  423. @pytest.mark.asyncio
  424. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  425. captured_payloads: list[dict] = []
  426. def handler(request: httpx.Request) -> httpx.Response:
  427. captured_payloads.append(json.loads(request.content))
  428. return httpx.Response(
  429. 200,
  430. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  431. )
  432. async with httpx.AsyncClient(
  433. transport=httpx.MockTransport(handler),
  434. base_url="https://llm.test/v1",
  435. ) as http_client:
  436. client = OpenAICompatibleChatClient(
  437. api_key="",
  438. base_url="https://llm.test/v1",
  439. default_model="provider-default",
  440. request_timeout_seconds=5,
  441. http_client=http_client,
  442. )
  443. [
  444. item
  445. async for item in client.stream_chat(
  446. messages=[ChatMessage(role="user", content="hi")],
  447. tools=[],
  448. params=AgentParams(
  449. model="provider-default",
  450. temperature=0.3,
  451. max_tokens=50,
  452. extra_body={
  453. "thinking": {"type": "disabled"},
  454. "enable_search": False,
  455. "search_options": {"forced_search": False},
  456. },
  457. ),
  458. )
  459. ]
  460. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  461. assert captured_payloads[0]["enable_search"] is False
  462. assert captured_payloads[0]["search_options"] == {"forced_search": False}