test_websocket_api.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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, TokenUsage
  15. from agent_lab.infrastructure.chat_client import OpenAICompatibleChatClient
  16. from agent_lab.infrastructure.sqlite_store import SQLiteSessionStore
  17. from agent_lab.presentation.web import create_app
  18. from agent_lab.settings import Settings
  19. def _css_rule(css: str, selector: str) -> str:
  20. start = css.index(f"{selector} {{")
  21. end = css.index("}", start)
  22. return css[start:end]
  23. class FakeRuntime:
  24. def __init__(self) -> None:
  25. self.requests: list[DebugRunRequest] = []
  26. async def run(self, request: DebugRunRequest) -> AsyncIterator[dict]:
  27. self.requests.append(request)
  28. yield {"type": "session_started"}
  29. yield {"type": "message_delta", "content": "hello"}
  30. yield {"type": "done"}
  31. class QueueAwareRuntime:
  32. def __init__(self) -> None:
  33. self.requests: list[DebugRunRequest] = []
  34. self.queues: RuntimeQueues | None = None
  35. self.task: asyncio.Task | None = None
  36. def start(self, request: DebugRunRequest) -> RuntimeQueues:
  37. self.requests.append(request)
  38. self.queues = RuntimeQueues()
  39. self.task = asyncio.create_task(self._run())
  40. return self.queues
  41. async def _run(self) -> None:
  42. assert self.queues is not None
  43. await self.queues.output.put({"type": "session_started"})
  44. message = await self.queues.input.get()
  45. await self.queues.output.put(
  46. {"type": "message_delta", "content": message.content}
  47. )
  48. await self.queues.output.put({"type": "done"})
  49. async def aclose(self) -> None:
  50. if self.task is not None and not self.task.done():
  51. self.task.cancel()
  52. await asyncio.gather(self.task, return_exceptions=True)
  53. class PersistentSessionRuntime:
  54. def __init__(self) -> None:
  55. self.requests: list[DebugRunRequest] = []
  56. self.queues: RuntimeQueues | None = None
  57. self.task: asyncio.Task | None = None
  58. def start_session(self, request: DebugRunRequest) -> RuntimeQueues:
  59. self.requests.append(request)
  60. self.queues = RuntimeQueues()
  61. self.task = asyncio.create_task(self._run(request))
  62. return self.queues
  63. async def _run(self, request: DebugRunRequest) -> None:
  64. assert self.queues is not None
  65. await self.queues.output.put({"type": "session_started"})
  66. await self._emit_turn(1, request.user_message)
  67. turn_index = 1
  68. while True:
  69. message = await self.queues.input.get()
  70. turn_index += 1
  71. await self._emit_turn(turn_index, message.content)
  72. async def _emit_turn(self, turn_index: int, content: str) -> None:
  73. assert self.queues is not None
  74. await self.queues.output.put({"type": "turn_started", "turn_index": turn_index})
  75. await self.queues.output.put({"type": "message_delta", "content": content})
  76. await self.queues.output.put(
  77. {"type": "turn_completed", "turn_index": turn_index}
  78. )
  79. async def aclose(self) -> None:
  80. if self.task is not None and not self.task.done():
  81. self.task.cancel()
  82. await asyncio.gather(self.task, return_exceptions=True)
  83. def _request_payload() -> dict:
  84. return {
  85. "user_message": "debug this",
  86. "system_prompts": ["You are a debugger."],
  87. "pre_messages": [{"role": "user", "content": "previous turn"}],
  88. "chat_agent": {
  89. "model": "fake-model",
  90. "temperature": 0.1,
  91. "max_tokens": 200,
  92. },
  93. "event_agent": {
  94. "enabled_tools": ["handoff_note"],
  95. "max_event_loops": 2,
  96. },
  97. }
  98. def _event_tool_call_from_tools(
  99. tools: list[dict],
  100. messages: list[ChatMessage],
  101. ) -> StreamItem:
  102. tool_name = tools[0]["function"]["name"]
  103. content = ""
  104. for role in ("assistant", "user"):
  105. content = next(
  106. (
  107. message.content
  108. for message in reversed(messages)
  109. if message.role == role and message.content.strip()
  110. ),
  111. "",
  112. )
  113. if content:
  114. break
  115. arguments = {
  116. "message": content,
  117. "query": content,
  118. "title": content,
  119. }
  120. return StreamItem.provider_tool_call(
  121. ToolCallEvent(
  122. id="event_agent_call_1",
  123. name=tool_name,
  124. arguments=arguments,
  125. raw_arguments=json.dumps(arguments),
  126. )
  127. )
  128. def test_agent_params_defaults_include_extra_body_and_event_agent_defaults_to_one_round():
  129. chat_params = AgentParams()
  130. event_params = EventAgentParams()
  131. assert chat_params.extra_body == {
  132. "thinking": {"type": "disabled"},
  133. "enable_search": False,
  134. "search_options": {"forced_search": False},
  135. }
  136. assert event_params.extra_body == chat_params.extra_body
  137. assert event_params.max_event_loops == 1
  138. assert event_params.system_prompt == ""
  139. def test_health_returns_ok():
  140. app = create_app(runtime_factory=FakeRuntime)
  141. client = TestClient(app)
  142. response = client.get("/health")
  143. assert response.status_code == 200
  144. assert response.json() == {"status": "ok"}
  145. def test_api_tools_returns_handoff_note_metadata():
  146. app = create_app(runtime_factory=FakeRuntime)
  147. client = TestClient(app)
  148. response = client.get("/api/tools")
  149. assert response.status_code == 200
  150. tools = response.json()
  151. assert [tool["name"] for tool in tools] == [
  152. "handoff_note",
  153. "mock_search",
  154. "mock_ticket",
  155. ]
  156. assert tools[0]["parameters"]["required"] == ["message"]
  157. def test_session_api_creates_lists_and_returns_empty_replay_data(tmp_path):
  158. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  159. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  160. client = TestClient(app)
  161. created = client.post(
  162. "/api/sessions",
  163. json={
  164. "title": "Debug session",
  165. "config": {"chat_agent": {"model": "chat-model"}},
  166. },
  167. )
  168. assert created.status_code == 200
  169. session_id = created.json()["id"]
  170. assert created.json()["title"] == "Debug session"
  171. sessions = client.get("/api/sessions")
  172. assert sessions.status_code == 200
  173. assert sessions.json()[0]["id"] == session_id
  174. assert sessions.json()[0]["turn_count"] == 0
  175. detail = client.get(f"/api/sessions/{session_id}")
  176. assert detail.status_code == 200
  177. assert detail.json()["config"]["chat_agent"]["model"] == "chat-model"
  178. assert client.get(f"/api/sessions/{session_id}/messages").json() == []
  179. assert client.get(f"/api/sessions/{session_id}/audit").json() == []
  180. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  181. assert usage == {
  182. "calls": [],
  183. "turns": [],
  184. "session": {
  185. "prompt_tokens": 0,
  186. "completion_tokens": 0,
  187. "total_tokens": 0,
  188. "cached_tokens": 0,
  189. "elapsed_ms": 0,
  190. },
  191. }
  192. def test_session_api_returns_persisted_replay_data(tmp_path):
  193. database_path = tmp_path / "agent_lab.sqlite3"
  194. settings = Settings(database_path=str(database_path))
  195. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  196. client = TestClient(app)
  197. session_id = client.post("/api/sessions", json={"title": "Replay"}).json()["id"]
  198. store = SQLiteSessionStore(database_path)
  199. store.start_turn(session_id, turn_index=1, user_message="debug this")
  200. store.append_message(
  201. session_id,
  202. turn_index=1,
  203. message=ChatMessage(role="user", content="debug this"),
  204. )
  205. store.append_message(
  206. session_id,
  207. turn_index=1,
  208. message=ChatMessage(role="assistant", content="answer"),
  209. )
  210. store.append_audit(
  211. session_id,
  212. event="chat_agent_request",
  213. details={"model": "chat-model"},
  214. turn_index=1,
  215. round_index=1,
  216. )
  217. store.append_usage(
  218. session_id,
  219. turn_index=1,
  220. round_index=1,
  221. usage=TokenUsage(prompt_tokens=1, completion_tokens=2, total_tokens=3),
  222. ttft_ms=10,
  223. elapsed_ms=20,
  224. )
  225. assert [message["content"] for message in client.get(
  226. f"/api/sessions/{session_id}/messages"
  227. ).json()] == ["debug this", "answer"]
  228. assert client.get(f"/api/sessions/{session_id}/audit").json()[0]["details"] == {
  229. "model": "chat-model"
  230. }
  231. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  232. assert usage["calls"][0]["total_tokens"] == 3
  233. assert usage["turns"][0]["total_tokens"] == 3
  234. assert usage["session"]["total_tokens"] == 3
  235. def test_default_websocket_runtime_factory_accepts_session_store(tmp_path):
  236. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  237. app = create_app(settings=settings)
  238. client = TestClient(app)
  239. with client.websocket_connect("/ws/debug") as websocket:
  240. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  241. message = websocket.receive_json()
  242. assert message["type"] == "error"
  243. assert "user_message" in message["message"]
  244. def test_websocket_debug_streams_runtime_messages():
  245. runtime = FakeRuntime()
  246. app = create_app(runtime_factory=lambda: runtime)
  247. client = TestClient(app)
  248. with client.websocket_connect("/ws/debug") as websocket:
  249. websocket.send_json(_request_payload())
  250. assert websocket.receive_json() == {"type": "session_started"}
  251. assert websocket.receive_json() == {
  252. "type": "message_delta",
  253. "content": "hello",
  254. }
  255. assert websocket.receive_json() == {"type": "done"}
  256. assert runtime.requests[0].user_message == "debug this"
  257. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  258. def test_websocket_debug_logs_session_lifecycle(caplog):
  259. runtime = FakeRuntime()
  260. app = create_app(runtime_factory=lambda: runtime)
  261. client = TestClient(app)
  262. with caplog.at_level(logging.INFO, logger="agent_lab.presentation.web"):
  263. with client.websocket_connect("/ws/debug") as websocket:
  264. websocket.send_json(_request_payload())
  265. assert websocket.receive_json() == {"type": "session_started"}
  266. assert websocket.receive_json() == {
  267. "type": "message_delta",
  268. "content": "hello",
  269. }
  270. assert websocket.receive_json() == {"type": "done"}
  271. assert "websocket session accepted" in caplog.text
  272. assert "websocket request accepted" in caplog.text
  273. assert "websocket session closed" in caplog.text
  274. def test_websocket_debug_enqueues_user_messages_during_running_session():
  275. runtime = QueueAwareRuntime()
  276. app = create_app(runtime_factory=lambda: runtime)
  277. client = TestClient(app)
  278. with client.websocket_connect("/ws/debug") as websocket:
  279. websocket.send_json(_request_payload())
  280. assert websocket.receive_json() == {"type": "session_started"}
  281. websocket.send_json({"type": "user_message", "content": "follow-up"})
  282. assert websocket.receive_json() == {
  283. "type": "message_delta",
  284. "content": "follow-up",
  285. }
  286. assert websocket.receive_json() == {"type": "done"}
  287. assert runtime.requests[0].user_message == "debug this"
  288. def test_websocket_debug_keeps_session_open_for_multiple_turns():
  289. runtime = PersistentSessionRuntime()
  290. app = create_app(runtime_factory=lambda: runtime)
  291. client = TestClient(app)
  292. with client.websocket_connect("/ws/debug") as websocket:
  293. websocket.send_json(_request_payload())
  294. assert websocket.receive_json() == {"type": "session_started"}
  295. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 1}
  296. assert websocket.receive_json() == {
  297. "type": "message_delta",
  298. "content": "debug this",
  299. }
  300. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 1}
  301. websocket.send_json({"type": "user_message", "content": "follow-up"})
  302. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 2}
  303. assert websocket.receive_json() == {
  304. "type": "message_delta",
  305. "content": "follow-up",
  306. }
  307. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 2}
  308. websocket.close()
  309. assert runtime.requests[0].user_message == "debug this"
  310. def test_websocket_debug_sends_error_for_invalid_request():
  311. app = create_app(runtime_factory=FakeRuntime)
  312. client = TestClient(app)
  313. with client.websocket_connect("/ws/debug") as websocket:
  314. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  315. message = websocket.receive_json()
  316. assert message["type"] == "error"
  317. assert "user_message" in message["message"]
  318. def test_debug_run_request_rejects_invalid_pre_message_role():
  319. payload = _request_payload()
  320. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  321. with pytest.raises(ValidationError) as exc_info:
  322. DebugRunRequest.model_validate(payload)
  323. assert "role" in str(exc_info.value)
  324. def test_debug_run_request_rejects_tool_pre_messages():
  325. payload = _request_payload()
  326. payload["pre_messages"] = [
  327. {
  328. "role": "tool",
  329. "content": "orphan result",
  330. "tool_call_id": "call_1",
  331. }
  332. ]
  333. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  334. DebugRunRequest.model_validate(payload)
  335. def test_chat_message_allows_internal_tool_replies():
  336. message = ChatMessage(
  337. role="tool",
  338. content='{"message":"handled"}',
  339. name="handoff_note",
  340. tool_call_id="call_1",
  341. )
  342. assert message.role == "tool"
  343. assert message.tool_call_id == "call_1"
  344. class HistoryCapturingChatClient:
  345. def __init__(self) -> None:
  346. self.calls = 0
  347. self.second_call_messages: list[ChatMessage] = []
  348. async def stream_chat(
  349. self,
  350. messages: list[ChatMessage],
  351. tools: list[dict],
  352. params: AgentParams,
  353. ) -> AsyncIterator[StreamItem]:
  354. if tools:
  355. yield _event_tool_call_from_tools(tools, messages)
  356. return
  357. self.calls += 1
  358. if self.calls == 1:
  359. yield StreamItem.message_delta("Need event help.")
  360. yield StreamItem.text_event(
  361. ToolCallEvent(
  362. id="call_1",
  363. name="handoff_note",
  364. arguments={},
  365. raw_arguments="{}",
  366. )
  367. )
  368. return
  369. self.second_call_messages = list(messages)
  370. yield StreamItem.message_delta("Final answer.")
  371. @pytest.mark.asyncio
  372. async def test_runtime_appends_event_summary_without_tool_reply_history():
  373. request = DebugRunRequest(
  374. user_message="debug this",
  375. system_prompts=["You are a debugger."],
  376. pre_messages=[],
  377. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  378. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  379. )
  380. client = HistoryCapturingChatClient()
  381. runtime = DebugRuntime(client)
  382. outputs = [message async for message in runtime.run(request)]
  383. assert client.calls == 2
  384. assert [message.role for message in client.second_call_messages] == [
  385. "system",
  386. "system",
  387. "user",
  388. "assistant",
  389. "user",
  390. ]
  391. assert "Available events:" in client.second_call_messages[1].content
  392. assert client.second_call_messages[3].content == "Need event help."
  393. assert not any(message.role == "tool" for message in client.second_call_messages)
  394. assert client.second_call_messages[4].content.startswith("EventAgent results:\n")
  395. assert client.second_call_messages[4].name == "event_agent"
  396. assert outputs[-1] == {"type": "done"}
  397. @pytest.mark.asyncio
  398. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  399. requests: list[httpx.Request] = []
  400. def handler(request: httpx.Request) -> httpx.Response:
  401. requests.append(request)
  402. payload = json.loads(request.content)
  403. assert payload["stream"] is True
  404. assert payload["model"] == "model-x"
  405. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  406. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  407. assert payload["tool_choice"] == {
  408. "type": "function",
  409. "function": {"name": "handoff_note"},
  410. }
  411. assert payload["temperature"] == 0.3
  412. assert payload["max_tokens"] == 50
  413. assert request.headers["authorization"] == "Bearer test-key"
  414. return httpx.Response(
  415. 200,
  416. content=(
  417. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  418. b"data: [DONE]\n\n"
  419. ),
  420. )
  421. async with httpx.AsyncClient(
  422. transport=httpx.MockTransport(handler),
  423. base_url="https://llm.test/v1",
  424. ) as http_client:
  425. client = OpenAICompatibleChatClient(
  426. api_key="test-key",
  427. base_url="https://llm.test/v1",
  428. default_model="default-model",
  429. request_timeout_seconds=5,
  430. http_client=http_client,
  431. )
  432. items = [
  433. item
  434. async for item in client.stream_chat(
  435. messages=[ChatMessage(role="user", content="hi")],
  436. tools=[
  437. {
  438. "type": "function",
  439. "function": {"name": "handoff_note", "parameters": {}},
  440. }
  441. ],
  442. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  443. )
  444. ]
  445. assert requests[0].url.path == "/v1/chat/completions"
  446. assert [item.content for item in items if item.kind == "message_delta"] == ["hi"]
  447. assert [item.raw_chunk for item in items if item.kind == "raw_chunk"] == [
  448. {"choices": [{"delta": {"content": "hi"}, "finish_reason": None}]}
  449. ]
  450. @pytest.mark.asyncio
  451. async def test_openai_chat_client_flushes_one_provider_tool_call_at_done():
  452. def handler(request: httpx.Request) -> httpx.Response:
  453. return httpx.Response(
  454. 200,
  455. content=(
  456. b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,'
  457. b'"id":"call_1","function":{"name":"mock_search",'
  458. b'"arguments":"{\\"query\\":\\""}}]},"finish_reason":null}]}\n\n'
  459. b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,'
  460. b'"function":{"arguments":"latency docs\\"}"}}]},'
  461. b'"finish_reason":null}]}\n\n'
  462. b"data: [DONE]\n\n"
  463. ),
  464. )
  465. async with httpx.AsyncClient(
  466. transport=httpx.MockTransport(handler),
  467. base_url="https://llm.test/v1",
  468. ) as http_client:
  469. client = OpenAICompatibleChatClient(
  470. api_key="",
  471. base_url="https://llm.test/v1",
  472. default_model="provider-default",
  473. request_timeout_seconds=5,
  474. http_client=http_client,
  475. )
  476. items = [
  477. item
  478. async for item in client.stream_chat(
  479. messages=[ChatMessage(role="user", content="find docs")],
  480. tools=[
  481. {
  482. "type": "function",
  483. "function": {"name": "mock_search", "parameters": {}},
  484. }
  485. ],
  486. params=AgentParams(model="provider-default"),
  487. )
  488. ]
  489. provider_calls = [
  490. item.event for item in items if item.kind == "provider_tool_call"
  491. ]
  492. assert provider_calls == [
  493. ToolCallEvent(
  494. id="call_1",
  495. name="mock_search",
  496. arguments={"query": "latency docs"},
  497. raw_arguments='{"query":"latency docs"}',
  498. )
  499. ]
  500. @pytest.mark.asyncio
  501. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  502. captured_payloads: list[dict] = []
  503. def handler(request: httpx.Request) -> httpx.Response:
  504. captured_payloads.append(json.loads(request.content))
  505. return httpx.Response(
  506. 200,
  507. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  508. )
  509. async with httpx.AsyncClient(
  510. transport=httpx.MockTransport(handler),
  511. base_url="https://llm.test/v1",
  512. ) as http_client:
  513. client = OpenAICompatibleChatClient(
  514. api_key="",
  515. base_url="https://llm.test/v1",
  516. default_model="provider-default",
  517. request_timeout_seconds=5,
  518. http_client=http_client,
  519. )
  520. [
  521. item
  522. async for item in client.stream_chat(
  523. messages=[ChatMessage(role="user", content="hi")],
  524. tools=[],
  525. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  526. )
  527. ]
  528. assert captured_payloads[0]["model"] == "provider-default"
  529. @pytest.mark.asyncio
  530. async def test_openai_chat_client_rejects_internal_tool_messages_before_network():
  531. network_called = False
  532. def handler(request: httpx.Request) -> httpx.Response:
  533. nonlocal network_called
  534. network_called = True
  535. return httpx.Response(
  536. 200,
  537. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  538. )
  539. async with httpx.AsyncClient(
  540. transport=httpx.MockTransport(handler),
  541. base_url="https://llm.test/v1",
  542. ) as http_client:
  543. client = OpenAICompatibleChatClient(
  544. api_key="",
  545. base_url="https://llm.test/v1",
  546. default_model="provider-default",
  547. request_timeout_seconds=5,
  548. http_client=http_client,
  549. )
  550. with pytest.raises(ValueError, match="tool messages are internal"):
  551. [
  552. item
  553. async for item in client.stream_chat(
  554. messages=[
  555. ChatMessage(
  556. role="tool",
  557. content="internal tool result",
  558. tool_call_id="call_1",
  559. )
  560. ],
  561. tools=[],
  562. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  563. )
  564. ]
  565. assert network_called is False
  566. def test_static_pre_message_role_selector_does_not_offer_tool():
  567. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  568. assert '<option value="tool">tool</option>' not in html
  569. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  570. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  571. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  572. assert 'id="tool-handoff-note"' not in html
  573. assert "#tool-handoff-note" not in js
  574. assert 'id="tool-list"' in html
  575. assert '"/api/tools"' in js
  576. assert "fetch" in js
  577. def test_static_workspace_snapshot_controls_are_available_outside_agent_config():
  578. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  579. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  580. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  581. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  582. sidebar_html = html[:chat_dialog_start]
  583. assert 'id="open-prompt-config"' not in html
  584. assert '<dialog id="prompt-dialog"' not in html
  585. assert 'id="workspace-snapshot-name"' in sidebar_html
  586. assert 'id="saved-workspace-snapshots"' in sidebar_html
  587. assert 'id="save-workspace-snapshot"' in sidebar_html
  588. assert 'id="load-workspace-snapshot"' in sidebar_html
  589. assert 'id="delete-workspace-snapshot"' in sidebar_html
  590. assert 'id="workspace-snapshot-name"' not in chat_dialog_html
  591. assert 'id="saved-workspace-snapshots"' not in chat_dialog_html
  592. assert 'id="save-workspace-snapshot"' not in chat_dialog_html
  593. assert 'id="system-prompts"' in chat_dialog_html
  594. assert 'id="pre-messages"' in chat_dialog_html
  595. def test_static_session_ui_controls_and_replay_panels_are_available():
  596. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  597. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  598. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  599. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  600. event_dialog_html = html[event_dialog_start:]
  601. sidebar_html = html[:chat_dialog_start]
  602. for control_id in [
  603. "session-title",
  604. "session-list",
  605. "new-session",
  606. "refresh-sessions",
  607. "load-session",
  608. "session-status",
  609. ]:
  610. assert f'id="{control_id}"' in sidebar_html
  611. assert f'id="{control_id}"' not in chat_dialog_html
  612. assert f'id="{control_id}"' not in event_dialog_html
  613. for replay_id in [
  614. "audit-replay",
  615. "audit-count",
  616. "session-usage-summary",
  617. "session-usage-turns",
  618. "session-usage-calls",
  619. ]:
  620. assert f'id="{replay_id}"' in html
  621. def test_static_chat_agent_prompt_is_a_single_sortable_list_with_event_instructions():
  622. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  623. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  624. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  625. assert 'id="chat-system-prompt"' not in html
  626. assert 'id="chat-event-prompt-preview"' not in html
  627. assert 'class="prompt-list stack"' in html
  628. assert 'class="prompt-item"' in html
  629. assert 'data-prompt-role="system"' in html
  630. assert "prompt-type" in html
  631. assert "function buildAvailableEventsPrompt(" in js
  632. assert "Available events:" in js
  633. assert "function updateEventPromptItem(" in js
  634. assert "function createSystemPrompt(" in js
  635. assert "function movePromptItem(" in js
  636. assert 'draggable = true' in js
  637. assert "dataset.promptRole" in js
  638. assert "prompt-title" in js
  639. assert "delete-system-prompt" in js
  640. assert 'prompt_kind: "event_agent_system"' in js
  641. assert "system_prompts: collectSystemPrompts()" in js
  642. assert 'system_prompt: ""' in js
  643. assert ".prompt-item" in css
  644. assert ".prompt-item.dragging" in css
  645. assert ".prompt-meta" in css
  646. assert ".prompt-type" in css
  647. assert ".prompt-actions button" in css
  648. assert "#open-prompt-config" not in js
  649. assert "promptDialog" not in js
  650. def test_static_app_script_is_versioned_and_click_binding_is_guarded():
  651. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  652. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  653. assert '<script src="/static/app.js?v=' in html
  654. assert "function bindClick(" in js
  655. assert 'bindClick("#open-chat-config-panel", openChatConfig)' in js
  656. assert 'bindClick("#open-event-config-panel", openEventConfig)' in js
  657. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  658. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  659. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  660. assert '<dialog id="chat-config-dialog"' in html
  661. assert '<dialog id="event-config-dialog"' in html
  662. assert html.count('id="open-chat-config-panel"') == 1
  663. assert html.count('id="open-event-config-panel"') == 1
  664. assert 'id="open-chat-config"' not in html
  665. assert 'id="open-event-config"' not in html
  666. assert '#open-chat-config"' not in js
  667. assert '#open-event-config"' not in js
  668. assert '#open-chat-config-panel"' in js
  669. assert '#open-event-config-panel"' in js
  670. assert 'id="close-chat-config"' in html
  671. assert 'id="close-event-config"' in html
  672. assert "chatConfigDialog.showModal()" in js
  673. assert "eventConfigDialog.showModal()" in js
  674. assert "chatConfigDialog.close()" in js
  675. assert "eventConfigDialog.close()" in js
  676. for control_id in [
  677. "model",
  678. "temperature",
  679. "max-tokens",
  680. "chat-thinking-disabled",
  681. "chat-enable-search",
  682. "chat-forced-search",
  683. "event-model",
  684. "event-temperature",
  685. "event-max-tokens",
  686. "event-system-prompt",
  687. "event-thinking-disabled",
  688. "event-enable-search",
  689. "event-forced-search",
  690. ]:
  691. assert f'id="{control_id}"' in html
  692. assert 'extra_body: buildExtraBody("chat")' in js
  693. assert 'extra_body: buildExtraBody("event")' in js
  694. assert 'system_prompt: ""' in js
  695. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  696. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  697. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  698. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  699. assert 'id="tool-count"' in html
  700. assert 'id="select-all-tools"' in html
  701. assert 'id="clear-tools"' in html
  702. assert "tool-card" in js
  703. assert "tool-description" in js
  704. assert "tool-required" in js
  705. assert "function updateToolCount()" in js
  706. def test_static_app_handles_audit_messages():
  707. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  708. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  709. assert 'message.type === "audit"' in js
  710. assert "appendAuditEntry(message)" in js
  711. assert 'appendLog("audit"' not in js
  712. assert "function renderAuditDetail(" in js
  713. assert "chat_agent_request" in js
  714. assert "event_agent_response" in js
  715. assert "chat_message_stream_started" in js
  716. assert "chat_message_stream_finished" in js
  717. assert ".audit-event" in css
  718. assert ".audit-detail" in css
  719. def test_static_audit_replay_uses_event_stream_and_detail_panel():
  720. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  721. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  722. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  723. assert '<link rel="stylesheet" href="/static/styles.css?v=' in html
  724. assert "session-switch-idle-socket" in html
  725. assert 'id="audit-dialog"' in html
  726. assert 'id="open-audit-dialog"' in html
  727. assert 'id="close-audit-dialog"' in html
  728. assert 'id="audit-summary"' in html
  729. assert 'id="audit-replay" class="audit-stream"' in html
  730. assert 'id="audit-detail"' in html
  731. assert "auditDialog.showModal()" in js
  732. assert "auditDialog.close()" in js
  733. assert "auditEntryKey(entry)" in js
  734. assert "selectAuditEntry(key)" in js
  735. assert 'meta.className = "audit-detail-meta"' in js
  736. assert 'appendMetaField(meta, "Since User Message"' in js
  737. assert "auditRelativeTime(entry)" in js
  738. assert 'const list = document.createElement("ul")' in js
  739. assert "appendKeyValueSection(auditDetail, \"Model Parameters\"" in js
  740. assert "appendRepliesSection(auditDetail, details.replies)" in js
  741. assert "appendRawChunksSection(auditDetail, \"Raw LLM Chunks\"" in js
  742. assert "appendRawModelChunksSection(auditDetail, details.raw_model_chunks)" in js
  743. assert "Enabled This Round" in js
  744. assert "Configured Events" in js
  745. assert "details.configured_events" in js
  746. assert "enabled this round" in js
  747. assert ".audit-modal" in css
  748. assert ".audit-modal-body" in css
  749. assert ".audit-modal-body section + section" in css
  750. assert ".audit-detail-title" in css
  751. assert ".detail-tags code" in css
  752. assert ".audit-detail-meta span" not in css
  753. assert ".detail-tags span" not in css
  754. assert "display: block" in _css_rule(css, ".audit-detail")
  755. assert "display: grid" not in _css_rule(css, ".audit-detail")
  756. assert "display: block" in _css_rule(css, ".audit-detail-header")
  757. assert "display: grid" not in _css_rule(css, ".audit-detail-header")
  758. assert "display: inline-flex" in _css_rule(css, ".audit-detail-meta div")
  759. assert ".audit-marker::before" in css
  760. assert ".audit-event.is-selected" in css
  761. def test_static_layout_keeps_controls_and_composer_fixed_with_scrollable_panes():
  762. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  763. assert "height: calc(100vh - 56px)" in css
  764. assert ".layout" in css and "overflow: hidden" in css
  765. assert ".controls" in css and "overflow: auto" in css
  766. assert ".workspace {\n display: grid;\n grid-template-rows: minmax(0, 1fr) auto auto;" in css
  767. assert ".workspace-body" in css and "overflow: hidden" in css
  768. assert ".messages" in css and "overflow: auto" in css
  769. assert ".audit-stream" in css and "overflow: auto" in css
  770. def test_static_app_shows_wait_state_and_immediate_user_echo():
  771. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  772. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  773. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  774. assert 'id="run-button"' in html
  775. assert 'const runButton = document.querySelector("#run-button")' in js
  776. assert 'appendLog("user", submittedMessage)' in js
  777. assert 'statusEl.textContent = "Waiting for first token"' in js
  778. assert "function startElapsedTimer()" in js
  779. assert "function stopElapsedTimer()" in js
  780. assert "function setRunState(" in js
  781. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  782. assert "hasBackendRoundStats && firstTokenAt" in js
  783. assert ".user" in css
  784. def test_static_app_reuses_websocket_for_session_turns():
  785. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  786. assert "function isSocketOpen()" in js
  787. assert "socket.send(JSON.stringify({ type: \"user_message\"" in js
  788. assert "session_id: currentSessionId || undefined" in js
  789. assert "message.session_id" in js
  790. assert 'message.type === "turn_completed"' in js
  791. assert 'message.type === "done"' in js
  792. def test_static_app_loads_session_replay_and_usage():
  793. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  794. assert "function loadSessions(" in js
  795. assert "function createSession(" in js
  796. assert "function setSessionStatus(" in js
  797. assert '"Refreshing sessions"' in js
  798. assert '"Creating session"' in js
  799. assert '"Session created"' in js
  800. assert 'sessionStatus.textContent = message' in js
  801. assert "function loadSessionReplay(" in js
  802. assert 'fetchJson("/api/sessions")' in js
  803. assert 'method: "POST"' in js
  804. assert '`/api/sessions/${sessionId}/messages`' in js
  805. assert '`/api/sessions/${sessionId}/audit`' in js
  806. assert '`/api/sessions/${sessionId}/usage`' in js
  807. assert "function renderAuditReplay(" in js
  808. assert "function renderSessionUsage(" in js
  809. assert "sessionUsageSummary" in js
  810. assert "Finish current turn before switching sessions" in js
  811. def test_static_session_switch_guard_uses_active_turn_not_open_socket():
  812. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  813. create_session = js[js.index("async function createSession()") : js.index("async function loadSelectedSession()")]
  814. load_session = js[js.index("async function loadSelectedSession()") : js.index("async function loadSessionReplay(")]
  815. assert "function hasActiveTurn()" in js
  816. assert "turnActive = isRunning" in js
  817. assert "if (hasActiveTurn())" in create_session
  818. assert "if (hasActiveTurn())" in load_session
  819. assert "if (isSocketOpen())" not in create_session
  820. assert "if (isSocketOpen())" not in load_session
  821. assert "closeSocket();" in create_session
  822. assert "closeSocket();" in load_session
  823. assert "const activeSocket = socket" in js
  824. assert "if (socket !== activeSocket)" in js
  825. def test_static_workspace_snapshot_uses_stable_storage_hooks():
  826. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  827. assert "agent-lab.workspace-snapshots.v1" in js
  828. assert "agent-lab.prompt-sets.v1" in js
  829. assert "function saveWorkspaceSnapshot()" in js
  830. assert "function loadWorkspaceSnapshot()" in js
  831. assert "function deleteWorkspaceSnapshot()" in js
  832. assert "function buildWorkspaceSnapshot()" in js
  833. assert "prompt_items: buildPromptItems()" in js
  834. assert "enabled_tools: selectedTools()" in js
  835. assert "extra_body: buildExtraBody(\"chat\")" in js
  836. assert "extra_body: buildExtraBody(\"event\")" in js
  837. def test_static_app_handles_backend_round_stats_messages():
  838. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  839. assert 'message.type === "round_stats"' in js
  840. assert "function updateRoundStats(" in js
  841. assert "#stat-ttft" in js
  842. assert "#stat-elapsed" in js
  843. @pytest.mark.asyncio
  844. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  845. captured_payloads: list[dict] = []
  846. def handler(request: httpx.Request) -> httpx.Response:
  847. captured_payloads.append(json.loads(request.content))
  848. return httpx.Response(
  849. 200,
  850. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  851. )
  852. async with httpx.AsyncClient(
  853. transport=httpx.MockTransport(handler),
  854. base_url="https://llm.test/v1",
  855. ) as http_client:
  856. client = OpenAICompatibleChatClient(
  857. api_key="",
  858. base_url="https://llm.test/v1",
  859. default_model="provider-default",
  860. request_timeout_seconds=5,
  861. include_usage=False,
  862. http_client=http_client,
  863. )
  864. [
  865. item
  866. async for item in client.stream_chat(
  867. messages=[ChatMessage(role="user", content="hi")],
  868. tools=[],
  869. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  870. )
  871. ]
  872. assert "stream_options" not in captured_payloads[0]
  873. @pytest.mark.asyncio
  874. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  875. captured_payloads: list[dict] = []
  876. def handler(request: httpx.Request) -> httpx.Response:
  877. captured_payloads.append(json.loads(request.content))
  878. return httpx.Response(
  879. 200,
  880. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  881. )
  882. async with httpx.AsyncClient(
  883. transport=httpx.MockTransport(handler),
  884. base_url="https://llm.test/v1",
  885. ) as http_client:
  886. client = OpenAICompatibleChatClient(
  887. api_key="",
  888. base_url="https://llm.test/v1",
  889. default_model="provider-default",
  890. request_timeout_seconds=5,
  891. http_client=http_client,
  892. )
  893. [
  894. item
  895. async for item in client.stream_chat(
  896. messages=[ChatMessage(role="user", content="hi")],
  897. tools=[],
  898. params=AgentParams(
  899. model="provider-default",
  900. temperature=0.3,
  901. max_tokens=50,
  902. extra_body={
  903. "thinking": {"type": "disabled"},
  904. "enable_search": False,
  905. "search_options": {"forced_search": False},
  906. },
  907. ),
  908. )
  909. ]
  910. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  911. assert captured_payloads[0]["enable_search"] is False
  912. assert captured_payloads[0]["search_options"] == {"forced_search": False}