test_websocket_api.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. import json
  2. import asyncio
  3. import logging
  4. from collections.abc import AsyncIterator
  5. from pathlib import Path
  6. import httpx
  7. import pytest
  8. from fastapi.testclient import TestClient
  9. from pydantic import ValidationError
  10. from agent_lab.application.contracts import AgentParams, DebugRunRequest, EventAgentParams
  11. from agent_lab.application.queues import RuntimeQueues
  12. from agent_lab.application.runtime import DebugRuntime
  13. from agent_lab.domain.events import ToolCallEvent
  14. from agent_lab.domain.messages import ChatMessage, StreamItem
  15. from agent_lab.infrastructure.chat_client import OpenAICompatibleChatClient
  16. from agent_lab.presentation.web import create_app
  17. class FakeRuntime:
  18. def __init__(self) -> None:
  19. self.requests: list[DebugRunRequest] = []
  20. async def run(self, request: DebugRunRequest) -> AsyncIterator[dict]:
  21. self.requests.append(request)
  22. yield {"type": "session_started"}
  23. yield {"type": "message_delta", "content": "hello"}
  24. yield {"type": "done"}
  25. class QueueAwareRuntime:
  26. def __init__(self) -> None:
  27. self.requests: list[DebugRunRequest] = []
  28. self.queues: RuntimeQueues | None = None
  29. self.task: asyncio.Task | None = None
  30. def start(self, request: DebugRunRequest) -> RuntimeQueues:
  31. self.requests.append(request)
  32. self.queues = RuntimeQueues()
  33. self.task = asyncio.create_task(self._run())
  34. return self.queues
  35. async def _run(self) -> None:
  36. assert self.queues is not None
  37. await self.queues.output.put({"type": "session_started"})
  38. message = await self.queues.input.get()
  39. await self.queues.output.put(
  40. {"type": "message_delta", "content": message.content}
  41. )
  42. await self.queues.output.put({"type": "done"})
  43. async def aclose(self) -> None:
  44. if self.task is not None and not self.task.done():
  45. self.task.cancel()
  46. await asyncio.gather(self.task, return_exceptions=True)
  47. def _request_payload() -> dict:
  48. return {
  49. "user_message": "debug this",
  50. "system_prompts": ["You are a debugger."],
  51. "pre_messages": [{"role": "user", "content": "previous turn"}],
  52. "chat_agent": {
  53. "model": "fake-model",
  54. "temperature": 0.1,
  55. "max_tokens": 200,
  56. },
  57. "event_agent": {
  58. "enabled_tools": ["handoff_note"],
  59. "max_event_loops": 2,
  60. },
  61. }
  62. def test_agent_params_defaults_include_extra_body_and_event_agent_defaults_to_one_round():
  63. chat_params = AgentParams()
  64. event_params = EventAgentParams()
  65. assert chat_params.extra_body == {
  66. "thinking": {"type": "disabled"},
  67. "enable_search": False,
  68. "search_options": {"forced_search": False},
  69. }
  70. assert event_params.extra_body == chat_params.extra_body
  71. assert event_params.max_event_loops == 1
  72. assert event_params.system_prompt == ""
  73. def test_health_returns_ok():
  74. app = create_app(runtime_factory=FakeRuntime)
  75. client = TestClient(app)
  76. response = client.get("/health")
  77. assert response.status_code == 200
  78. assert response.json() == {"status": "ok"}
  79. def test_api_tools_returns_handoff_note_metadata():
  80. app = create_app(runtime_factory=FakeRuntime)
  81. client = TestClient(app)
  82. response = client.get("/api/tools")
  83. assert response.status_code == 200
  84. tools = response.json()
  85. assert [tool["name"] for tool in tools] == [
  86. "handoff_note",
  87. "mock_search",
  88. "mock_ticket",
  89. ]
  90. assert tools[0]["parameters"]["required"] == ["message"]
  91. def test_websocket_debug_streams_runtime_messages():
  92. runtime = FakeRuntime()
  93. app = create_app(runtime_factory=lambda: runtime)
  94. client = TestClient(app)
  95. with client.websocket_connect("/ws/debug") as websocket:
  96. websocket.send_json(_request_payload())
  97. assert websocket.receive_json() == {"type": "session_started"}
  98. assert websocket.receive_json() == {
  99. "type": "message_delta",
  100. "content": "hello",
  101. }
  102. assert websocket.receive_json() == {"type": "done"}
  103. assert runtime.requests[0].user_message == "debug this"
  104. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  105. def test_websocket_debug_logs_session_lifecycle(caplog):
  106. runtime = FakeRuntime()
  107. app = create_app(runtime_factory=lambda: runtime)
  108. client = TestClient(app)
  109. with caplog.at_level(logging.INFO, logger="agent_lab.presentation.web"):
  110. with client.websocket_connect("/ws/debug") as websocket:
  111. websocket.send_json(_request_payload())
  112. assert websocket.receive_json() == {"type": "session_started"}
  113. assert websocket.receive_json() == {
  114. "type": "message_delta",
  115. "content": "hello",
  116. }
  117. assert websocket.receive_json() == {"type": "done"}
  118. assert "websocket session accepted" in caplog.text
  119. assert "websocket request accepted" in caplog.text
  120. assert "websocket session closed" in caplog.text
  121. def test_websocket_debug_enqueues_user_messages_during_running_session():
  122. runtime = QueueAwareRuntime()
  123. app = create_app(runtime_factory=lambda: runtime)
  124. client = TestClient(app)
  125. with client.websocket_connect("/ws/debug") as websocket:
  126. websocket.send_json(_request_payload())
  127. assert websocket.receive_json() == {"type": "session_started"}
  128. websocket.send_json({"type": "user_message", "content": "follow-up"})
  129. assert websocket.receive_json() == {
  130. "type": "message_delta",
  131. "content": "follow-up",
  132. }
  133. assert websocket.receive_json() == {"type": "done"}
  134. assert runtime.requests[0].user_message == "debug this"
  135. def test_websocket_debug_sends_error_for_invalid_request():
  136. app = create_app(runtime_factory=FakeRuntime)
  137. client = TestClient(app)
  138. with client.websocket_connect("/ws/debug") as websocket:
  139. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  140. message = websocket.receive_json()
  141. assert message["type"] == "error"
  142. assert "user_message" in message["message"]
  143. def test_debug_run_request_rejects_invalid_pre_message_role():
  144. payload = _request_payload()
  145. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  146. with pytest.raises(ValidationError) as exc_info:
  147. DebugRunRequest.model_validate(payload)
  148. assert "role" in str(exc_info.value)
  149. def test_debug_run_request_rejects_tool_pre_messages():
  150. payload = _request_payload()
  151. payload["pre_messages"] = [
  152. {
  153. "role": "tool",
  154. "content": "orphan result",
  155. "tool_call_id": "call_1",
  156. }
  157. ]
  158. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  159. DebugRunRequest.model_validate(payload)
  160. def test_chat_message_allows_internal_tool_replies():
  161. message = ChatMessage(
  162. role="tool",
  163. content='{"message":"handled"}',
  164. name="handoff_note",
  165. tool_call_id="call_1",
  166. )
  167. assert message.role == "tool"
  168. assert message.tool_call_id == "call_1"
  169. class HistoryCapturingChatClient:
  170. def __init__(self) -> None:
  171. self.calls = 0
  172. self.second_call_messages: list[ChatMessage] = []
  173. async def stream_chat(
  174. self,
  175. messages: list[ChatMessage],
  176. tools: list[dict],
  177. params: AgentParams,
  178. ) -> AsyncIterator[StreamItem]:
  179. self.calls += 1
  180. if self.calls == 1:
  181. yield StreamItem.message_delta("Need event help.")
  182. yield StreamItem.event(
  183. ToolCallEvent(
  184. id="call_1",
  185. name="handoff_note",
  186. arguments={},
  187. raw_arguments="{}",
  188. )
  189. )
  190. return
  191. self.second_call_messages = list(messages)
  192. yield StreamItem.message_delta("Final answer.")
  193. @pytest.mark.asyncio
  194. async def test_runtime_appends_assistant_message_before_tool_reply_history():
  195. request = DebugRunRequest(
  196. user_message="debug this",
  197. system_prompts=["You are a debugger."],
  198. pre_messages=[],
  199. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  200. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  201. )
  202. client = HistoryCapturingChatClient()
  203. runtime = DebugRuntime(client)
  204. outputs = [message async for message in runtime.run(request)]
  205. assert client.calls == 2
  206. assert [message.role for message in client.second_call_messages] == [
  207. "system",
  208. "user",
  209. "assistant",
  210. "tool",
  211. ]
  212. assert client.second_call_messages[2].content == "Need event help."
  213. assert outputs[-1] == {"type": "done"}
  214. @pytest.mark.asyncio
  215. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  216. requests: list[httpx.Request] = []
  217. def handler(request: httpx.Request) -> httpx.Response:
  218. requests.append(request)
  219. payload = json.loads(request.content)
  220. assert payload["stream"] is True
  221. assert payload["model"] == "model-x"
  222. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  223. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  224. assert payload["temperature"] == 0.3
  225. assert payload["max_tokens"] == 50
  226. assert request.headers["authorization"] == "Bearer test-key"
  227. return httpx.Response(
  228. 200,
  229. content=(
  230. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  231. b"data: [DONE]\n\n"
  232. ),
  233. )
  234. async with httpx.AsyncClient(
  235. transport=httpx.MockTransport(handler),
  236. base_url="https://llm.test/v1",
  237. ) as http_client:
  238. client = OpenAICompatibleChatClient(
  239. api_key="test-key",
  240. base_url="https://llm.test/v1",
  241. default_model="default-model",
  242. request_timeout_seconds=5,
  243. http_client=http_client,
  244. )
  245. items = [
  246. item
  247. async for item in client.stream_chat(
  248. messages=[ChatMessage(role="user", content="hi")],
  249. tools=[
  250. {
  251. "type": "function",
  252. "function": {"name": "handoff_note", "parameters": {}},
  253. }
  254. ],
  255. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  256. )
  257. ]
  258. assert requests[0].url.path == "/v1/chat/completions"
  259. assert [item.content for item in items] == ["hi"]
  260. @pytest.mark.asyncio
  261. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  262. captured_payloads: list[dict] = []
  263. def handler(request: httpx.Request) -> httpx.Response:
  264. captured_payloads.append(json.loads(request.content))
  265. return httpx.Response(
  266. 200,
  267. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  268. )
  269. async with httpx.AsyncClient(
  270. transport=httpx.MockTransport(handler),
  271. base_url="https://llm.test/v1",
  272. ) as http_client:
  273. client = OpenAICompatibleChatClient(
  274. api_key="",
  275. base_url="https://llm.test/v1",
  276. default_model="provider-default",
  277. request_timeout_seconds=5,
  278. http_client=http_client,
  279. )
  280. [
  281. item
  282. async for item in client.stream_chat(
  283. messages=[ChatMessage(role="user", content="hi")],
  284. tools=[],
  285. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  286. )
  287. ]
  288. assert captured_payloads[0]["model"] == "provider-default"
  289. @pytest.mark.asyncio
  290. async def test_openai_chat_client_serializes_tool_reply_without_name():
  291. captured_payloads: list[dict] = []
  292. assistant_tool_call = {
  293. "id": "call_1",
  294. "type": "function",
  295. "function": {
  296. "name": "handoff_note",
  297. "arguments": '{"message":"inspect"}',
  298. },
  299. }
  300. def handler(request: httpx.Request) -> httpx.Response:
  301. captured_payloads.append(json.loads(request.content))
  302. return httpx.Response(
  303. 200,
  304. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  305. )
  306. async with httpx.AsyncClient(
  307. transport=httpx.MockTransport(handler),
  308. base_url="https://llm.test/v1",
  309. ) as http_client:
  310. client = OpenAICompatibleChatClient(
  311. api_key="",
  312. base_url="https://llm.test/v1",
  313. default_model="provider-default",
  314. request_timeout_seconds=5,
  315. http_client=http_client,
  316. )
  317. [
  318. item
  319. async for item in client.stream_chat(
  320. messages=[
  321. ChatMessage(
  322. role="assistant",
  323. content="",
  324. tool_calls=[assistant_tool_call],
  325. ),
  326. ChatMessage(
  327. role="tool",
  328. content="noted",
  329. name="handoff_note",
  330. tool_call_id="call_1",
  331. ),
  332. ],
  333. tools=[],
  334. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  335. )
  336. ]
  337. assert captured_payloads[0]["messages"] == [
  338. {
  339. "role": "assistant",
  340. "content": "",
  341. "tool_calls": [assistant_tool_call],
  342. },
  343. {
  344. "role": "tool",
  345. "content": "noted",
  346. "tool_call_id": "call_1",
  347. },
  348. ]
  349. @pytest.mark.asyncio
  350. async def test_openai_chat_client_rejects_tool_message_without_tool_call_id_before_network():
  351. network_called = False
  352. def handler(request: httpx.Request) -> httpx.Response:
  353. nonlocal network_called
  354. network_called = True
  355. return httpx.Response(
  356. 200,
  357. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  358. )
  359. async with httpx.AsyncClient(
  360. transport=httpx.MockTransport(handler),
  361. base_url="https://llm.test/v1",
  362. ) as http_client:
  363. client = OpenAICompatibleChatClient(
  364. api_key="",
  365. base_url="https://llm.test/v1",
  366. default_model="provider-default",
  367. request_timeout_seconds=5,
  368. http_client=http_client,
  369. )
  370. with pytest.raises(ValueError, match="tool messages require tool_call_id"):
  371. [
  372. item
  373. async for item in client.stream_chat(
  374. messages=[ChatMessage(role="tool", content="orphan tool result")],
  375. tools=[],
  376. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  377. )
  378. ]
  379. assert network_called is False
  380. def test_static_pre_message_role_selector_does_not_offer_tool():
  381. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  382. assert '<option value="tool">tool</option>' not in html
  383. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  384. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  385. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  386. assert 'id="tool-handoff-note"' not in html
  387. assert "#tool-handoff-note" not in js
  388. assert 'id="tool-list"' in html
  389. assert '"/api/tools"' in js
  390. assert "fetch" in js
  391. def test_static_prompt_workspace_controls_are_available():
  392. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  393. assert 'id="prompt-set-name"' in html
  394. assert 'id="saved-prompt-sets"' in html
  395. assert 'id="save-prompt-set"' in html
  396. assert 'id="load-prompt-set"' in html
  397. assert 'id="delete-prompt-set"' in html
  398. def test_static_prompt_workspace_is_opened_from_a_modal():
  399. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  400. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  401. assert 'id="open-prompt-config"' in html
  402. assert '<dialog id="prompt-dialog"' in html
  403. assert 'id="close-prompt-config"' in html
  404. assert "promptDialog.showModal()" in js
  405. assert "promptDialog.close()" in js
  406. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  407. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  408. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  409. for control_id in [
  410. "model",
  411. "temperature",
  412. "max-tokens",
  413. "chat-system-prompt",
  414. "chat-thinking-disabled",
  415. "chat-enable-search",
  416. "chat-forced-search",
  417. "event-model",
  418. "event-temperature",
  419. "event-max-tokens",
  420. "event-system-prompt",
  421. "event-thinking-disabled",
  422. "event-enable-search",
  423. "event-forced-search",
  424. ]:
  425. assert f'id="{control_id}"' in html
  426. assert 'extra_body: buildExtraBody("chat")' in js
  427. assert 'extra_body: buildExtraBody("event")' in js
  428. assert 'system_prompt: document.querySelector("#chat-system-prompt")' in js
  429. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  430. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  431. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  432. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  433. assert 'id="tool-count"' in html
  434. assert 'id="select-all-tools"' in html
  435. assert 'id="clear-tools"' in html
  436. assert "tool-card" in js
  437. assert "tool-description" in js
  438. assert "tool-required" in js
  439. assert "function updateToolCount()" in js
  440. def test_static_app_handles_audit_messages():
  441. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  442. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  443. assert 'message.type === "audit"' in js
  444. assert 'appendLog("audit"' in js
  445. assert ".audit" in css
  446. def test_static_app_shows_wait_state_and_immediate_user_echo():
  447. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  448. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  449. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  450. assert 'id="run-button"' in html
  451. assert 'const runButton = document.querySelector("#run-button")' in js
  452. assert 'appendLog("user", submittedMessage)' in js
  453. assert 'statusEl.textContent = "Waiting for first token"' in js
  454. assert "function startElapsedTimer()" in js
  455. assert "function stopElapsedTimer()" in js
  456. assert "function setRunState(" in js
  457. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  458. assert "hasBackendRoundStats && firstTokenAt" in js
  459. assert ".user" in css
  460. def test_static_prompt_workspace_uses_stable_storage_hooks():
  461. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  462. assert "agent-lab.prompt-sets.v1" in js
  463. assert "function savePromptSet()" in js
  464. assert "function loadPromptSet()" in js
  465. assert "function deletePromptSet()" in js
  466. def test_static_app_handles_backend_round_stats_messages():
  467. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  468. assert 'message.type === "round_stats"' in js
  469. assert "function updateRoundStats(" in js
  470. assert "#stat-ttft" in js
  471. assert "#stat-elapsed" in js
  472. @pytest.mark.asyncio
  473. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  474. captured_payloads: list[dict] = []
  475. def handler(request: httpx.Request) -> httpx.Response:
  476. captured_payloads.append(json.loads(request.content))
  477. return httpx.Response(
  478. 200,
  479. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  480. )
  481. async with httpx.AsyncClient(
  482. transport=httpx.MockTransport(handler),
  483. base_url="https://llm.test/v1",
  484. ) as http_client:
  485. client = OpenAICompatibleChatClient(
  486. api_key="",
  487. base_url="https://llm.test/v1",
  488. default_model="provider-default",
  489. request_timeout_seconds=5,
  490. include_usage=False,
  491. http_client=http_client,
  492. )
  493. [
  494. item
  495. async for item in client.stream_chat(
  496. messages=[ChatMessage(role="user", content="hi")],
  497. tools=[],
  498. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  499. )
  500. ]
  501. assert "stream_options" not in captured_payloads[0]
  502. @pytest.mark.asyncio
  503. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  504. captured_payloads: list[dict] = []
  505. def handler(request: httpx.Request) -> httpx.Response:
  506. captured_payloads.append(json.loads(request.content))
  507. return httpx.Response(
  508. 200,
  509. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  510. )
  511. async with httpx.AsyncClient(
  512. transport=httpx.MockTransport(handler),
  513. base_url="https://llm.test/v1",
  514. ) as http_client:
  515. client = OpenAICompatibleChatClient(
  516. api_key="",
  517. base_url="https://llm.test/v1",
  518. default_model="provider-default",
  519. request_timeout_seconds=5,
  520. http_client=http_client,
  521. )
  522. [
  523. item
  524. async for item in client.stream_chat(
  525. messages=[ChatMessage(role="user", content="hi")],
  526. tools=[],
  527. params=AgentParams(
  528. model="provider-default",
  529. temperature=0.3,
  530. max_tokens=50,
  531. extra_body={
  532. "thinking": {"type": "disabled"},
  533. "enable_search": False,
  534. "search_options": {"forced_search": False},
  535. },
  536. ),
  537. )
  538. ]
  539. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  540. assert captured_payloads[0]["enable_search"] is False
  541. assert captured_payloads[0]["search_options"] == {"forced_search": False}