test_websocket_api.py 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625
  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_debug_run_request_defaults_to_dual_agent_tool_invocation_mode():
  140. request = DebugRunRequest.model_validate(_request_payload())
  141. assert request.tool_invocation_mode == "dual_agent"
  142. @pytest.mark.parametrize("mode", ["dual_agent", "chat_agent_tools"])
  143. def test_debug_run_request_accepts_supported_tool_invocation_modes(mode: str):
  144. payload = _request_payload()
  145. payload["tool_invocation_mode"] = mode
  146. request = DebugRunRequest.model_validate(payload)
  147. assert request.tool_invocation_mode == mode
  148. def test_debug_run_request_rejects_unknown_tool_invocation_mode():
  149. payload = _request_payload()
  150. payload["tool_invocation_mode"] = "unknown"
  151. with pytest.raises(ValidationError, match="tool_invocation_mode"):
  152. DebugRunRequest.model_validate(payload)
  153. def test_health_returns_ok():
  154. app = create_app(runtime_factory=FakeRuntime)
  155. client = TestClient(app)
  156. response = client.get("/health")
  157. assert response.status_code == 200
  158. assert response.json() == {"status": "ok"}
  159. def test_api_tools_returns_default_tool_catalog():
  160. app = create_app(runtime_factory=FakeRuntime)
  161. client = TestClient(app)
  162. response = client.get("/api/tools")
  163. assert response.status_code == 200
  164. tools = response.json()
  165. assert [tool["name"] for tool in tools] == [
  166. "handoff_note",
  167. "mock_search",
  168. "mock_ticket",
  169. "session.terminate",
  170. "device.volume.adjust",
  171. "calendar.schedule.create",
  172. "knowledge.web.search",
  173. ]
  174. assert tools[0]["parameters"]["required"] == ["message"]
  175. def test_session_api_creates_lists_and_returns_empty_replay_data(tmp_path):
  176. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  177. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  178. client = TestClient(app)
  179. created = client.post(
  180. "/api/sessions",
  181. json={
  182. "title": "Debug session",
  183. "config": {"chat_agent": {"model": "chat-model"}},
  184. },
  185. )
  186. assert created.status_code == 200
  187. session_id = created.json()["id"]
  188. assert created.json()["title"] == "Debug session"
  189. sessions = client.get("/api/sessions")
  190. assert sessions.status_code == 200
  191. assert sessions.json()[0]["id"] == session_id
  192. assert sessions.json()[0]["turn_count"] == 0
  193. detail = client.get(f"/api/sessions/{session_id}")
  194. assert detail.status_code == 200
  195. assert detail.json()["config"]["chat_agent"]["model"] == "chat-model"
  196. assert client.get(f"/api/sessions/{session_id}/messages").json() == []
  197. assert client.get(f"/api/sessions/{session_id}/audit").json() == []
  198. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  199. assert usage == {
  200. "calls": [],
  201. "turns": [],
  202. "session": {
  203. "prompt_tokens": 0,
  204. "completion_tokens": 0,
  205. "total_tokens": 0,
  206. "cached_tokens": 0,
  207. "elapsed_ms": 0,
  208. },
  209. }
  210. def test_session_api_returns_persisted_replay_data(tmp_path):
  211. database_path = tmp_path / "agent_lab.sqlite3"
  212. settings = Settings(database_path=str(database_path))
  213. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  214. client = TestClient(app)
  215. session_id = client.post("/api/sessions", json={"title": "Replay"}).json()["id"]
  216. store = SQLiteSessionStore(database_path)
  217. store.start_turn(session_id, turn_index=1, user_message="debug this")
  218. store.append_message(
  219. session_id,
  220. turn_index=1,
  221. message=ChatMessage(role="user", content="debug this"),
  222. )
  223. store.append_message(
  224. session_id,
  225. turn_index=1,
  226. message=ChatMessage(role="assistant", content="answer"),
  227. )
  228. store.append_audit(
  229. session_id,
  230. event="chat_agent_request",
  231. details={"model": "chat-model"},
  232. turn_index=1,
  233. round_index=1,
  234. )
  235. store.append_usage(
  236. session_id,
  237. turn_index=1,
  238. round_index=1,
  239. usage=TokenUsage(prompt_tokens=1, completion_tokens=2, total_tokens=3),
  240. ttft_ms=10,
  241. elapsed_ms=20,
  242. )
  243. assert [message["content"] for message in client.get(
  244. f"/api/sessions/{session_id}/messages"
  245. ).json()] == ["debug this", "answer"]
  246. assert client.get(f"/api/sessions/{session_id}/audit").json()[0]["details"] == {
  247. "model": "chat-model"
  248. }
  249. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  250. assert usage["calls"][0]["total_tokens"] == 3
  251. assert usage["turns"][0]["total_tokens"] == 3
  252. assert usage["session"]["total_tokens"] == 3
  253. def test_default_websocket_runtime_factory_accepts_session_store(tmp_path):
  254. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  255. app = create_app(settings=settings)
  256. client = TestClient(app)
  257. with client.websocket_connect("/ws/debug") as websocket:
  258. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  259. message = websocket.receive_json()
  260. assert message["type"] == "error"
  261. assert "user_message" in message["message"]
  262. def test_websocket_debug_streams_runtime_messages():
  263. runtime = FakeRuntime()
  264. app = create_app(runtime_factory=lambda: runtime)
  265. client = TestClient(app)
  266. with client.websocket_connect("/ws/debug") as websocket:
  267. websocket.send_json(_request_payload())
  268. assert websocket.receive_json() == {"type": "session_started"}
  269. assert websocket.receive_json() == {
  270. "type": "message_delta",
  271. "content": "hello",
  272. }
  273. assert websocket.receive_json() == {"type": "done"}
  274. assert runtime.requests[0].user_message == "debug this"
  275. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  276. def test_websocket_debug_logs_session_lifecycle(caplog):
  277. runtime = FakeRuntime()
  278. app = create_app(runtime_factory=lambda: runtime)
  279. client = TestClient(app)
  280. with caplog.at_level(logging.INFO, logger="agent_lab.presentation.web"):
  281. with client.websocket_connect("/ws/debug") as websocket:
  282. websocket.send_json(_request_payload())
  283. assert websocket.receive_json() == {"type": "session_started"}
  284. assert websocket.receive_json() == {
  285. "type": "message_delta",
  286. "content": "hello",
  287. }
  288. assert websocket.receive_json() == {"type": "done"}
  289. assert "websocket session accepted" in caplog.text
  290. assert "websocket request accepted" in caplog.text
  291. assert "websocket session closed" in caplog.text
  292. def test_websocket_debug_enqueues_user_messages_during_running_session():
  293. runtime = QueueAwareRuntime()
  294. app = create_app(runtime_factory=lambda: runtime)
  295. client = TestClient(app)
  296. with client.websocket_connect("/ws/debug") as websocket:
  297. websocket.send_json(_request_payload())
  298. assert websocket.receive_json() == {"type": "session_started"}
  299. websocket.send_json({"type": "user_message", "content": "follow-up"})
  300. assert websocket.receive_json() == {
  301. "type": "message_delta",
  302. "content": "follow-up",
  303. }
  304. assert websocket.receive_json() == {"type": "done"}
  305. assert runtime.requests[0].user_message == "debug this"
  306. def test_websocket_debug_keeps_session_open_for_multiple_turns():
  307. runtime = PersistentSessionRuntime()
  308. app = create_app(runtime_factory=lambda: runtime)
  309. client = TestClient(app)
  310. with client.websocket_connect("/ws/debug") as websocket:
  311. websocket.send_json(_request_payload())
  312. assert websocket.receive_json() == {"type": "session_started"}
  313. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 1}
  314. assert websocket.receive_json() == {
  315. "type": "message_delta",
  316. "content": "debug this",
  317. }
  318. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 1}
  319. websocket.send_json({"type": "user_message", "content": "follow-up"})
  320. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 2}
  321. assert websocket.receive_json() == {
  322. "type": "message_delta",
  323. "content": "follow-up",
  324. }
  325. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 2}
  326. websocket.close()
  327. assert runtime.requests[0].user_message == "debug this"
  328. def test_websocket_debug_sends_error_for_invalid_request():
  329. app = create_app(runtime_factory=FakeRuntime)
  330. client = TestClient(app)
  331. with client.websocket_connect("/ws/debug") as websocket:
  332. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  333. message = websocket.receive_json()
  334. assert message["type"] == "error"
  335. assert "user_message" in message["message"]
  336. def test_debug_run_request_rejects_invalid_pre_message_role():
  337. payload = _request_payload()
  338. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  339. with pytest.raises(ValidationError) as exc_info:
  340. DebugRunRequest.model_validate(payload)
  341. assert "role" in str(exc_info.value)
  342. def test_debug_run_request_rejects_tool_pre_messages():
  343. payload = _request_payload()
  344. payload["pre_messages"] = [
  345. {
  346. "role": "tool",
  347. "content": "orphan result",
  348. "tool_call_id": "call_1",
  349. }
  350. ]
  351. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  352. DebugRunRequest.model_validate(payload)
  353. def test_debug_run_request_rejects_assistant_tool_calls_in_pre_messages():
  354. payload = _request_payload()
  355. payload["pre_messages"] = [
  356. {
  357. "role": "assistant",
  358. "content": "I will inspect this.",
  359. "tool_calls": [
  360. {
  361. "id": "call_1",
  362. "name": "mock_search",
  363. "arguments": {"query": "latency"},
  364. "raw_arguments": '{"query":"latency"}',
  365. }
  366. ],
  367. }
  368. ]
  369. with pytest.raises(
  370. ValidationError,
  371. match="pre_messages cannot include assistant tool calls",
  372. ):
  373. DebugRunRequest.model_validate(payload)
  374. def test_chat_message_allows_internal_tool_replies():
  375. message = ChatMessage(
  376. role="tool",
  377. content='{"message":"handled"}',
  378. name="handoff_note",
  379. tool_call_id="call_1",
  380. )
  381. assert message.role == "tool"
  382. assert message.tool_call_id == "call_1"
  383. def test_chat_message_preserves_assistant_tool_calls():
  384. message = ChatMessage(
  385. role="assistant",
  386. content="I will inspect both sources.",
  387. tool_calls=[
  388. ToolCallEvent(
  389. id="call_1",
  390. name="mock_search",
  391. arguments={"query": "latency docs"},
  392. raw_arguments='{"query":"latency docs"}',
  393. ),
  394. ToolCallEvent(
  395. id="call_2",
  396. name="handoff_note",
  397. arguments={"message": "inspect provider behavior"},
  398. raw_arguments='{"message":"inspect provider behavior"}',
  399. ),
  400. ],
  401. )
  402. assert message.model_dump()["tool_calls"] == [
  403. {
  404. "id": "call_1",
  405. "name": "mock_search",
  406. "arguments": {"query": "latency docs"},
  407. "raw_arguments": '{"query":"latency docs"}',
  408. },
  409. {
  410. "id": "call_2",
  411. "name": "handoff_note",
  412. "arguments": {"message": "inspect provider behavior"},
  413. "raw_arguments": '{"message":"inspect provider behavior"}',
  414. },
  415. ]
  416. def test_chat_message_rejects_tool_calls_on_non_assistant_role():
  417. with pytest.raises(ValidationError, match="tool_calls require assistant role"):
  418. ChatMessage(
  419. role="user",
  420. content="invalid",
  421. tool_calls=[
  422. ToolCallEvent(
  423. id="call_1",
  424. name="mock_search",
  425. arguments={},
  426. raw_arguments="{}",
  427. )
  428. ],
  429. )
  430. def test_chat_message_rejects_tool_role_without_tool_call_id():
  431. with pytest.raises(ValidationError, match="tool messages require tool_call_id"):
  432. ChatMessage(role="tool", content="orphan result")
  433. @pytest.mark.parametrize("role", ["system", "user", "assistant"])
  434. def test_chat_message_rejects_tool_call_id_on_non_tool_roles(role: str):
  435. with pytest.raises(ValidationError, match="tool_call_id requires tool role"):
  436. ChatMessage(role=role, content="invalid", tool_call_id="call_1")
  437. def test_chat_message_rejects_duplicate_assistant_tool_call_ids():
  438. with pytest.raises(ValidationError, match="duplicate assistant tool-call ID: call_1"):
  439. ChatMessage(
  440. role="assistant",
  441. content="checking twice",
  442. tool_calls=[
  443. ToolCallEvent(
  444. id="call_1",
  445. name="mock_search",
  446. arguments={"query": "first"},
  447. raw_arguments='{"query":"first"}',
  448. ),
  449. ToolCallEvent(
  450. id="call_1",
  451. name="handoff_note",
  452. arguments={"message": "second"},
  453. raw_arguments='{"message":"second"}',
  454. ),
  455. ],
  456. )
  457. class HistoryCapturingChatClient:
  458. def __init__(self) -> None:
  459. self.calls = 0
  460. self.second_call_messages: list[ChatMessage] = []
  461. async def stream_chat(
  462. self,
  463. messages: list[ChatMessage],
  464. tools: list[dict],
  465. params: AgentParams,
  466. tool_choice: dict | None = None,
  467. ) -> AsyncIterator[StreamItem]:
  468. if tools:
  469. yield _event_tool_call_from_tools(tools, messages)
  470. return
  471. self.calls += 1
  472. if self.calls == 1:
  473. yield StreamItem.message_delta("Need event help.")
  474. yield StreamItem.text_event(
  475. ToolCallEvent(
  476. id="call_1",
  477. name="handoff_note",
  478. arguments={},
  479. raw_arguments="{}",
  480. )
  481. )
  482. return
  483. self.second_call_messages = list(messages)
  484. yield StreamItem.message_delta("Final answer.")
  485. @pytest.mark.asyncio
  486. async def test_runtime_appends_event_summary_without_tool_reply_history():
  487. request = DebugRunRequest(
  488. user_message="debug this",
  489. system_prompts=["You are a debugger."],
  490. pre_messages=[],
  491. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  492. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  493. )
  494. client = HistoryCapturingChatClient()
  495. runtime = DebugRuntime(client)
  496. outputs = [message async for message in runtime.run(request)]
  497. assert client.calls == 2
  498. assert [message.role for message in client.second_call_messages] == [
  499. "system",
  500. "system",
  501. "user",
  502. "assistant",
  503. "user",
  504. ]
  505. assert "Available events:" in client.second_call_messages[1].content
  506. assert client.second_call_messages[3].content == "Need event help."
  507. assert not any(message.role == "tool" for message in client.second_call_messages)
  508. assert client.second_call_messages[4].content.startswith("EventAgent results:\n")
  509. assert client.second_call_messages[4].name == "event_agent"
  510. assert outputs[-1] == {"type": "done"}
  511. @pytest.mark.asyncio
  512. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  513. requests: list[httpx.Request] = []
  514. def handler(request: httpx.Request) -> httpx.Response:
  515. requests.append(request)
  516. payload = json.loads(request.content)
  517. assert payload["stream"] is True
  518. assert payload["model"] == "model-x"
  519. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  520. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  521. assert "tool_choice" not in payload
  522. assert payload["temperature"] == 0.3
  523. assert payload["max_tokens"] == 50
  524. assert request.headers["authorization"] == "Bearer test-key"
  525. return httpx.Response(
  526. 200,
  527. content=(
  528. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  529. b"data: [DONE]\n\n"
  530. ),
  531. )
  532. async with httpx.AsyncClient(
  533. transport=httpx.MockTransport(handler),
  534. base_url="https://llm.test/v1",
  535. ) as http_client:
  536. client = OpenAICompatibleChatClient(
  537. api_key="test-key",
  538. base_url="https://llm.test/v1",
  539. default_model="default-model",
  540. request_timeout_seconds=5,
  541. http_client=http_client,
  542. )
  543. items = [
  544. item
  545. async for item in client.stream_chat(
  546. messages=[ChatMessage(role="user", content="hi")],
  547. tools=[
  548. {
  549. "type": "function",
  550. "function": {"name": "handoff_note", "parameters": {}},
  551. }
  552. ],
  553. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  554. )
  555. ]
  556. assert requests[0].url.path == "/v1/chat/completions"
  557. assert [item.content for item in items if item.kind == "message_delta"] == ["hi"]
  558. assert [item.raw_chunk for item in items if item.kind == "raw_chunk"] == [
  559. {"choices": [{"delta": {"content": "hi"}, "finish_reason": None}]}
  560. ]
  561. @pytest.mark.asyncio
  562. async def test_openai_chat_client_serializes_explicit_tool_choice():
  563. captured_payloads: list[dict] = []
  564. forced_choice = {
  565. "type": "function",
  566. "function": {"name": "handoff_note"},
  567. }
  568. def handler(request: httpx.Request) -> httpx.Response:
  569. captured_payloads.append(json.loads(request.content))
  570. return httpx.Response(200, content=b"data: [DONE]\n\n")
  571. async with httpx.AsyncClient(
  572. transport=httpx.MockTransport(handler),
  573. base_url="https://llm.test/v1",
  574. ) as http_client:
  575. client = OpenAICompatibleChatClient(
  576. api_key="",
  577. base_url="https://llm.test/v1",
  578. default_model="provider-default",
  579. request_timeout_seconds=5,
  580. http_client=http_client,
  581. )
  582. [
  583. item
  584. async for item in client.stream_chat(
  585. messages=[ChatMessage(role="user", content="prepare handoff")],
  586. tools=[
  587. {
  588. "type": "function",
  589. "function": {"name": "handoff_note", "parameters": {}},
  590. }
  591. ],
  592. params=AgentParams(model="provider-default"),
  593. tool_choice=forced_choice,
  594. )
  595. ]
  596. assert captured_payloads[0]["tool_choice"] == forced_choice
  597. @pytest.mark.asyncio
  598. async def test_openai_chat_client_flushes_one_provider_tool_call_at_done():
  599. def handler(request: httpx.Request) -> httpx.Response:
  600. return httpx.Response(
  601. 200,
  602. content=(
  603. b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,'
  604. b'"id":"call_1","function":{"name":"mock_search",'
  605. b'"arguments":"{\\"query\\":\\""}}]},"finish_reason":null}]}\n\n'
  606. b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,'
  607. b'"function":{"arguments":"latency docs\\"}"}}]},'
  608. b'"finish_reason":null}]}\n\n'
  609. b"data: [DONE]\n\n"
  610. ),
  611. )
  612. async with httpx.AsyncClient(
  613. transport=httpx.MockTransport(handler),
  614. base_url="https://llm.test/v1",
  615. ) as http_client:
  616. client = OpenAICompatibleChatClient(
  617. api_key="",
  618. base_url="https://llm.test/v1",
  619. default_model="provider-default",
  620. request_timeout_seconds=5,
  621. http_client=http_client,
  622. )
  623. items = [
  624. item
  625. async for item in client.stream_chat(
  626. messages=[ChatMessage(role="user", content="find docs")],
  627. tools=[
  628. {
  629. "type": "function",
  630. "function": {"name": "mock_search", "parameters": {}},
  631. }
  632. ],
  633. params=AgentParams(model="provider-default"),
  634. )
  635. ]
  636. provider_calls = [
  637. item.event for item in items if item.kind == "provider_tool_call"
  638. ]
  639. assert provider_calls == [
  640. ToolCallEvent(
  641. id="call_1",
  642. name="mock_search",
  643. arguments={"query": "latency docs"},
  644. raw_arguments='{"query":"latency docs"}',
  645. )
  646. ]
  647. @pytest.mark.asyncio
  648. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  649. captured_payloads: list[dict] = []
  650. def handler(request: httpx.Request) -> httpx.Response:
  651. captured_payloads.append(json.loads(request.content))
  652. return httpx.Response(
  653. 200,
  654. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  655. )
  656. async with httpx.AsyncClient(
  657. transport=httpx.MockTransport(handler),
  658. base_url="https://llm.test/v1",
  659. ) as http_client:
  660. client = OpenAICompatibleChatClient(
  661. api_key="",
  662. base_url="https://llm.test/v1",
  663. default_model="provider-default",
  664. request_timeout_seconds=5,
  665. http_client=http_client,
  666. )
  667. [
  668. item
  669. async for item in client.stream_chat(
  670. messages=[ChatMessage(role="user", content="hi")],
  671. tools=[],
  672. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  673. )
  674. ]
  675. assert captured_payloads[0]["model"] == "provider-default"
  676. @pytest.mark.asyncio
  677. async def test_openai_chat_client_serializes_provider_tool_transcript():
  678. captured_payloads: list[dict] = []
  679. def handler(request: httpx.Request) -> httpx.Response:
  680. captured_payloads.append(json.loads(request.content))
  681. return httpx.Response(
  682. 200,
  683. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  684. )
  685. async with httpx.AsyncClient(
  686. transport=httpx.MockTransport(handler),
  687. base_url="https://llm.test/v1",
  688. ) as http_client:
  689. client = OpenAICompatibleChatClient(
  690. api_key="",
  691. base_url="https://llm.test/v1",
  692. default_model="provider-default",
  693. request_timeout_seconds=5,
  694. http_client=http_client,
  695. )
  696. [
  697. item
  698. async for item in client.stream_chat(
  699. messages=[
  700. ChatMessage(role="user", content="inspect both"),
  701. ChatMessage(
  702. role="assistant",
  703. content="I will inspect both sources.",
  704. tool_calls=[
  705. ToolCallEvent(
  706. id="call_1",
  707. name="mock_search",
  708. arguments={"query": "latency docs"},
  709. raw_arguments='{"query":"latency docs"}',
  710. ),
  711. ToolCallEvent(
  712. id="call_2",
  713. name="handoff_note",
  714. arguments={"message": "inspect provider behavior"},
  715. raw_arguments='{"message":"inspect provider behavior"}',
  716. ),
  717. ],
  718. ),
  719. ChatMessage(
  720. role="tool",
  721. content='{"results":[]}',
  722. name="mock_search",
  723. tool_call_id="call_1",
  724. ),
  725. ChatMessage(
  726. role="tool",
  727. content='{"message":"handled"}',
  728. name="handoff_note",
  729. tool_call_id="call_2",
  730. ),
  731. ChatMessage(role="user", content="continue"),
  732. ],
  733. tools=[],
  734. params=AgentParams(
  735. model="provider-default",
  736. temperature=0.3,
  737. max_tokens=50,
  738. ),
  739. )
  740. ]
  741. assert captured_payloads[0]["messages"] == [
  742. {"role": "user", "content": "inspect both"},
  743. {
  744. "role": "assistant",
  745. "content": "I will inspect both sources.",
  746. "tool_calls": [
  747. {
  748. "id": "call_1",
  749. "type": "function",
  750. "function": {
  751. "name": "mock_search",
  752. "arguments": '{"query":"latency docs"}',
  753. },
  754. },
  755. {
  756. "id": "call_2",
  757. "type": "function",
  758. "function": {
  759. "name": "handoff_note",
  760. "arguments": '{"message":"inspect provider behavior"}',
  761. },
  762. },
  763. ],
  764. },
  765. {
  766. "role": "tool",
  767. "content": '{"results":[]}',
  768. "tool_call_id": "call_1",
  769. },
  770. {
  771. "role": "tool",
  772. "content": '{"message":"handled"}',
  773. "tool_call_id": "call_2",
  774. },
  775. {"role": "user", "content": "continue"},
  776. ]
  777. async def _assert_tool_transcript_rejected(
  778. messages: list[ChatMessage],
  779. error_match: str,
  780. ) -> None:
  781. network_called = False
  782. def handler(request: httpx.Request) -> httpx.Response:
  783. nonlocal network_called
  784. network_called = True
  785. return httpx.Response(200)
  786. async with httpx.AsyncClient(
  787. transport=httpx.MockTransport(handler),
  788. base_url="https://llm.test/v1",
  789. ) as http_client:
  790. client = OpenAICompatibleChatClient(
  791. api_key="",
  792. base_url="https://llm.test/v1",
  793. default_model="provider-default",
  794. request_timeout_seconds=5,
  795. http_client=http_client,
  796. )
  797. with pytest.raises(ValueError, match=error_match):
  798. [
  799. item
  800. async for item in client.stream_chat(
  801. messages=messages,
  802. tools=[],
  803. params=AgentParams(model="provider-default"),
  804. )
  805. ]
  806. assert network_called is False
  807. @pytest.mark.asyncio
  808. async def test_openai_chat_client_rejects_orphan_tool_reply_before_network():
  809. await _assert_tool_transcript_rejected(
  810. [
  811. ChatMessage(
  812. role="tool",
  813. content="orphan",
  814. tool_call_id="call_1",
  815. )
  816. ],
  817. "orphan tool reply: call_1",
  818. )
  819. @pytest.mark.asyncio
  820. async def test_openai_chat_client_rejects_mismatched_tool_call_id_before_network():
  821. await _assert_tool_transcript_rejected(
  822. [
  823. ChatMessage(
  824. role="assistant",
  825. content="",
  826. tool_calls=[
  827. ToolCallEvent(
  828. id="call_1",
  829. name="mock_search",
  830. arguments={},
  831. raw_arguments="{}",
  832. )
  833. ],
  834. ),
  835. ChatMessage(role="tool", content="wrong", tool_call_id="call_2"),
  836. ],
  837. "mismatched tool_call_id: call_2",
  838. )
  839. @pytest.mark.asyncio
  840. async def test_openai_chat_client_rejects_duplicate_tool_reply_before_network():
  841. await _assert_tool_transcript_rejected(
  842. [
  843. ChatMessage(
  844. role="assistant",
  845. content="",
  846. tool_calls=[
  847. ToolCallEvent(
  848. id="call_1",
  849. name="mock_search",
  850. arguments={},
  851. raw_arguments="{}",
  852. )
  853. ],
  854. ),
  855. ChatMessage(role="tool", content="first", tool_call_id="call_1"),
  856. ChatMessage(role="tool", content="duplicate", tool_call_id="call_1"),
  857. ],
  858. "duplicate tool reply: call_1",
  859. )
  860. @pytest.mark.asyncio
  861. async def test_openai_chat_client_rejects_non_tool_message_with_unresolved_calls():
  862. await _assert_tool_transcript_rejected(
  863. [
  864. ChatMessage(
  865. role="assistant",
  866. content="checking",
  867. tool_calls=[
  868. ToolCallEvent(
  869. id="call_1",
  870. name="mock_search",
  871. arguments={},
  872. raw_arguments="{}",
  873. ),
  874. ToolCallEvent(
  875. id="call_2",
  876. name="handoff_note",
  877. arguments={},
  878. raw_arguments="{}",
  879. ),
  880. ],
  881. ),
  882. ChatMessage(role="tool", content="done", tool_call_id="call_1"),
  883. ChatMessage(role="user", content="continue too early"),
  884. ],
  885. "unresolved tool calls before user message: call_2",
  886. )
  887. @pytest.mark.asyncio
  888. async def test_openai_chat_client_rejects_unfinished_tool_calls_at_end():
  889. await _assert_tool_transcript_rejected(
  890. [
  891. ChatMessage(
  892. role="assistant",
  893. content="checking",
  894. tool_calls=[
  895. ToolCallEvent(
  896. id="call_1",
  897. name="mock_search",
  898. arguments={},
  899. raw_arguments="{}",
  900. )
  901. ],
  902. )
  903. ],
  904. "unresolved tool calls at end: call_1",
  905. )
  906. @pytest.mark.asyncio
  907. async def test_openai_chat_client_rejects_reused_tool_call_id_across_transcript():
  908. await _assert_tool_transcript_rejected(
  909. [
  910. ChatMessage(
  911. role="assistant",
  912. content="first round",
  913. tool_calls=[
  914. ToolCallEvent(
  915. id="call_1",
  916. name="mock_search",
  917. arguments={},
  918. raw_arguments="{}",
  919. )
  920. ],
  921. ),
  922. ChatMessage(role="tool", content="done", tool_call_id="call_1"),
  923. ChatMessage(
  924. role="assistant",
  925. content="second round",
  926. tool_calls=[
  927. ToolCallEvent(
  928. id="call_1",
  929. name="handoff_note",
  930. arguments={},
  931. raw_arguments="{}",
  932. )
  933. ],
  934. ),
  935. ],
  936. "duplicate assistant tool-call ID across transcript: call_1",
  937. )
  938. async def _assert_tool_choice_rejected(
  939. tools: list[dict],
  940. tool_choice: dict,
  941. error_match: str,
  942. ) -> None:
  943. network_called = False
  944. def handler(request: httpx.Request) -> httpx.Response:
  945. nonlocal network_called
  946. network_called = True
  947. return httpx.Response(200)
  948. async with httpx.AsyncClient(
  949. transport=httpx.MockTransport(handler),
  950. base_url="https://llm.test/v1",
  951. ) as http_client:
  952. client = OpenAICompatibleChatClient(
  953. api_key="",
  954. base_url="https://llm.test/v1",
  955. default_model="provider-default",
  956. request_timeout_seconds=5,
  957. http_client=http_client,
  958. )
  959. with pytest.raises(ValueError, match=error_match):
  960. [
  961. item
  962. async for item in client.stream_chat(
  963. messages=[ChatMessage(role="user", content="use a tool")],
  964. tools=tools,
  965. params=AgentParams(model="provider-default"),
  966. tool_choice=tool_choice,
  967. )
  968. ]
  969. assert network_called is False
  970. @pytest.mark.asyncio
  971. async def test_openai_chat_client_rejects_forced_choice_without_tools():
  972. await _assert_tool_choice_rejected(
  973. tools=[],
  974. tool_choice={
  975. "type": "function",
  976. "function": {"name": "handoff_note"},
  977. },
  978. error_match="forced tool choice requires tools",
  979. )
  980. @pytest.mark.asyncio
  981. async def test_openai_chat_client_rejects_forced_choice_for_unknown_tool():
  982. await _assert_tool_choice_rejected(
  983. tools=[
  984. {
  985. "type": "function",
  986. "function": {"name": "mock_search", "parameters": {}},
  987. }
  988. ],
  989. tool_choice={
  990. "type": "function",
  991. "function": {"name": "handoff_note"},
  992. },
  993. error_match="forced tool choice references unknown tool: handoff_note",
  994. )
  995. def test_static_pre_message_role_selector_does_not_offer_tool():
  996. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  997. assert '<option value="tool">tool</option>' not in html
  998. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  999. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1000. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1001. assert 'id="tool-handoff-note"' not in html
  1002. assert "#tool-handoff-note" not in js
  1003. assert 'id="tool-list"' in html
  1004. assert '"/api/tools"' in js
  1005. assert "fetch" in js
  1006. def test_static_workspace_snapshot_controls_are_available_outside_agent_config():
  1007. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1008. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  1009. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  1010. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  1011. sidebar_html = html[:chat_dialog_start]
  1012. assert 'id="open-prompt-config"' not in html
  1013. assert '<dialog id="prompt-dialog"' not in html
  1014. assert 'id="workspace-snapshot-name"' in sidebar_html
  1015. assert 'id="saved-workspace-snapshots"' in sidebar_html
  1016. assert 'id="save-workspace-snapshot"' in sidebar_html
  1017. assert 'id="load-workspace-snapshot"' in sidebar_html
  1018. assert 'id="delete-workspace-snapshot"' in sidebar_html
  1019. assert 'id="workspace-snapshot-name"' not in chat_dialog_html
  1020. assert 'id="saved-workspace-snapshots"' not in chat_dialog_html
  1021. assert 'id="save-workspace-snapshot"' not in chat_dialog_html
  1022. assert 'id="system-prompts"' in chat_dialog_html
  1023. assert 'id="pre-messages"' in chat_dialog_html
  1024. def test_static_session_ui_controls_and_replay_panels_are_available():
  1025. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1026. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  1027. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  1028. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  1029. event_dialog_html = html[event_dialog_start:]
  1030. sidebar_html = html[:chat_dialog_start]
  1031. for control_id in [
  1032. "session-title",
  1033. "session-list",
  1034. "new-session",
  1035. "refresh-sessions",
  1036. "load-session",
  1037. "session-status",
  1038. ]:
  1039. assert f'id="{control_id}"' in sidebar_html
  1040. assert f'id="{control_id}"' not in chat_dialog_html
  1041. assert f'id="{control_id}"' not in event_dialog_html
  1042. for replay_id in [
  1043. "audit-replay",
  1044. "audit-count",
  1045. "session-usage-summary",
  1046. "session-usage-turns",
  1047. "session-usage-calls",
  1048. ]:
  1049. assert f'id="{replay_id}"' in html
  1050. def test_static_chat_agent_prompt_is_a_single_sortable_list_with_event_instructions():
  1051. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1052. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1053. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1054. assert 'id="chat-system-prompt"' not in html
  1055. assert 'id="chat-event-prompt-preview"' not in html
  1056. assert 'class="prompt-list stack"' in html
  1057. assert 'class="prompt-item"' in html
  1058. assert 'data-prompt-role="system"' in html
  1059. assert "prompt-type" in html
  1060. assert "function buildAvailableEventsPrompt(" in js
  1061. assert "Available events:" in js
  1062. assert "function updateEventPromptItem(" in js
  1063. assert "function createSystemPrompt(" in js
  1064. assert "function movePromptItem(" in js
  1065. assert 'draggable = true' in js
  1066. assert "dataset.promptRole" in js
  1067. assert "prompt-title" in js
  1068. assert "delete-system-prompt" in js
  1069. assert 'prompt_kind: "event_agent_system"' in js
  1070. assert "system_prompts: collectSystemPrompts()" in js
  1071. assert 'system_prompt: ""' in js
  1072. assert ".prompt-item" in css
  1073. assert ".prompt-item.dragging" in css
  1074. assert ".prompt-meta" in css
  1075. assert ".prompt-type" in css
  1076. assert ".prompt-actions button" in css
  1077. assert "#open-prompt-config" not in js
  1078. assert "promptDialog" not in js
  1079. def test_static_app_script_is_versioned_and_click_binding_is_guarded():
  1080. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1081. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1082. assert '<script src="/static/app.js?v=' in html
  1083. assert "function bindClick(" in js
  1084. assert 'bindClick("#open-chat-config-panel", openChatConfig)' in js
  1085. assert 'bindClick("#open-event-config-panel", openEventConfig)' in js
  1086. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  1087. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1088. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1089. assert '<dialog id="chat-config-dialog"' in html
  1090. assert '<dialog id="event-config-dialog"' in html
  1091. assert html.count('id="open-chat-config-panel"') == 1
  1092. assert html.count('id="open-event-config-panel"') == 1
  1093. assert 'id="open-chat-config"' not in html
  1094. assert 'id="open-event-config"' not in html
  1095. assert '#open-chat-config"' not in js
  1096. assert '#open-event-config"' not in js
  1097. assert '#open-chat-config-panel"' in js
  1098. assert '#open-event-config-panel"' in js
  1099. assert 'id="close-chat-config"' in html
  1100. assert 'id="close-event-config"' in html
  1101. assert "chatConfigDialog.showModal()" in js
  1102. assert "eventConfigDialog.showModal()" in js
  1103. assert "chatConfigDialog.close()" in js
  1104. assert "eventConfigDialog.close()" in js
  1105. for control_id in [
  1106. "model",
  1107. "temperature",
  1108. "max-tokens",
  1109. "chat-thinking-disabled",
  1110. "chat-enable-search",
  1111. "chat-forced-search",
  1112. "event-model",
  1113. "event-temperature",
  1114. "event-max-tokens",
  1115. "event-system-prompt",
  1116. "event-thinking-disabled",
  1117. "event-enable-search",
  1118. "event-forced-search",
  1119. ]:
  1120. assert f'id="{control_id}"' in html
  1121. assert 'extra_body: buildExtraBody("chat")' in js
  1122. assert 'extra_body: buildExtraBody("event")' in js
  1123. assert 'system_prompt: ""' in js
  1124. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  1125. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  1126. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1127. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1128. assert 'id="tool-count"' in html
  1129. assert 'id="select-all-tools"' in html
  1130. assert 'id="clear-tools"' in html
  1131. assert "tool-card" in js
  1132. assert "tool-description" in js
  1133. assert "tool-required" in js
  1134. assert "function updateToolCount()" in js
  1135. def test_static_app_handles_audit_messages():
  1136. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1137. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1138. assert 'message.type === "audit"' in js
  1139. assert "appendAuditEntry(message)" in js
  1140. assert 'appendLog("audit"' not in js
  1141. assert "function renderAuditDetail(" in js
  1142. assert "chat_agent_request" in js
  1143. assert "event_agent_response" in js
  1144. assert "chat_message_stream_started" in js
  1145. assert "chat_message_stream_finished" in js
  1146. assert ".audit-event" in css
  1147. assert ".audit-detail" in css
  1148. def test_static_audit_replay_uses_event_stream_and_detail_panel():
  1149. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1150. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1151. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1152. assert '<link rel="stylesheet" href="/static/styles.css?v=' in html
  1153. assert "session-switch-idle-socket" in html
  1154. assert 'id="audit-dialog"' in html
  1155. assert 'id="open-audit-dialog"' in html
  1156. assert 'id="close-audit-dialog"' in html
  1157. assert 'id="audit-summary"' in html
  1158. assert 'id="audit-replay" class="audit-stream"' in html
  1159. assert 'id="audit-detail"' in html
  1160. assert "auditDialog.showModal()" in js
  1161. assert "auditDialog.close()" in js
  1162. assert "auditEntryKey(entry)" in js
  1163. assert "selectAuditEntry(key)" in js
  1164. assert 'meta.className = "audit-detail-meta"' in js
  1165. assert 'appendMetaField(meta, "Since User Message"' in js
  1166. assert "auditRelativeTime(entry)" in js
  1167. assert 'const list = document.createElement("ul")' in js
  1168. assert "appendKeyValueSection(auditDetail, \"Model Parameters\"" in js
  1169. assert "appendRepliesSection(auditDetail, details.replies)" in js
  1170. assert "appendRawChunksSection(auditDetail, \"Raw LLM Chunks\"" in js
  1171. assert "appendRawModelChunksSection(auditDetail, details.raw_model_chunks)" in js
  1172. assert "Enabled This Round" in js
  1173. assert "Configured Events" in js
  1174. assert "details.configured_events" in js
  1175. assert "enabled this round" in js
  1176. assert ".audit-modal" in css
  1177. assert ".audit-modal-body" in css
  1178. assert ".audit-modal-body section + section" in css
  1179. assert ".audit-detail-title" in css
  1180. assert ".detail-tags code" in css
  1181. assert ".audit-detail-meta span" not in css
  1182. assert ".detail-tags span" not in css
  1183. assert "display: block" in _css_rule(css, ".audit-detail")
  1184. assert "display: grid" not in _css_rule(css, ".audit-detail")
  1185. assert "display: block" in _css_rule(css, ".audit-detail-header")
  1186. assert "display: grid" not in _css_rule(css, ".audit-detail-header")
  1187. assert "display: inline-flex" in _css_rule(css, ".audit-detail-meta div")
  1188. assert ".audit-marker::before" in css
  1189. assert ".audit-event.is-selected" in css
  1190. def test_static_layout_keeps_controls_and_composer_fixed_with_scrollable_panes():
  1191. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1192. assert "height: calc(100vh - 56px)" in css
  1193. assert ".layout" in css and "overflow: hidden" in css
  1194. assert ".controls" in css and "overflow: auto" in css
  1195. assert ".workspace {\n display: grid;\n grid-template-rows: minmax(0, 1fr) auto auto;" in css
  1196. assert ".workspace-body" in css and "overflow: hidden" in css
  1197. assert ".messages" in css and "overflow: auto" in css
  1198. assert ".audit-stream" in css and "overflow: auto" in css
  1199. def test_static_app_shows_wait_state_and_immediate_user_echo():
  1200. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1201. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1202. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1203. assert 'id="run-button"' in html
  1204. assert 'const runButton = document.querySelector("#run-button")' in js
  1205. assert 'appendLog("user", submittedMessage)' in js
  1206. assert 'statusEl.textContent = "Waiting for first token"' in js
  1207. assert "function startElapsedTimer()" in js
  1208. assert "function stopElapsedTimer()" in js
  1209. assert "function setRunState(" in js
  1210. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  1211. assert "hasBackendRoundStats && firstTokenAt" in js
  1212. assert ".user" in css
  1213. def test_static_app_reuses_websocket_for_session_turns():
  1214. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1215. assert "function isSocketOpen()" in js
  1216. assert "socket.send(JSON.stringify({ type: \"user_message\"" in js
  1217. assert "session_id: currentSessionId || undefined" in js
  1218. assert "message.session_id" in js
  1219. assert 'message.type === "turn_completed"' in js
  1220. assert 'message.type === "done"' in js
  1221. def test_static_app_loads_session_replay_and_usage():
  1222. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1223. assert "function loadSessions(" in js
  1224. assert "function createSession(" in js
  1225. assert "function setSessionStatus(" in js
  1226. assert '"Refreshing sessions"' in js
  1227. assert '"Creating session"' in js
  1228. assert '"Session created"' in js
  1229. assert 'sessionStatus.textContent = message' in js
  1230. assert "function loadSessionReplay(" in js
  1231. assert 'fetchJson("/api/sessions")' in js
  1232. assert 'method: "POST"' in js
  1233. assert '`/api/sessions/${sessionId}/messages`' in js
  1234. assert '`/api/sessions/${sessionId}/audit`' in js
  1235. assert '`/api/sessions/${sessionId}/usage`' in js
  1236. assert "function renderAuditReplay(" in js
  1237. assert "function renderSessionUsage(" in js
  1238. assert "sessionUsageSummary" in js
  1239. assert "Finish current turn before switching sessions" in js
  1240. def test_static_session_switch_guard_uses_active_turn_not_open_socket():
  1241. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1242. create_session = js[js.index("async function createSession()") : js.index("async function loadSelectedSession()")]
  1243. load_session = js[js.index("async function loadSelectedSession()") : js.index("async function loadSessionReplay(")]
  1244. assert "function hasActiveTurn()" in js
  1245. assert "turnActive = isRunning" in js
  1246. assert "if (hasActiveTurn())" in create_session
  1247. assert "if (hasActiveTurn())" in load_session
  1248. assert "if (isSocketOpen())" not in create_session
  1249. assert "if (isSocketOpen())" not in load_session
  1250. assert "closeSocket();" in create_session
  1251. assert "closeSocket();" in load_session
  1252. assert "const activeSocket = socket" in js
  1253. assert "if (socket !== activeSocket)" in js
  1254. def test_static_workspace_snapshot_uses_stable_storage_hooks():
  1255. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1256. assert "agent-lab.workspace-snapshots.v1" in js
  1257. assert "agent-lab.prompt-sets.v1" in js
  1258. assert "function saveWorkspaceSnapshot()" in js
  1259. assert "function loadWorkspaceSnapshot()" in js
  1260. assert "function deleteWorkspaceSnapshot()" in js
  1261. assert "function buildWorkspaceSnapshot()" in js
  1262. assert "prompt_items: buildPromptItems()" in js
  1263. assert "enabled_tools: selectedTools()" in js
  1264. assert "extra_body: buildExtraBody(\"chat\")" in js
  1265. assert "extra_body: buildExtraBody(\"event\")" in js
  1266. def test_static_app_handles_backend_round_stats_messages():
  1267. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1268. assert 'message.type === "round_stats"' in js
  1269. assert "function updateRoundStats(" in js
  1270. assert "#stat-ttft" in js
  1271. assert "#stat-elapsed" in js
  1272. @pytest.mark.asyncio
  1273. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  1274. captured_payloads: list[dict] = []
  1275. def handler(request: httpx.Request) -> httpx.Response:
  1276. captured_payloads.append(json.loads(request.content))
  1277. return httpx.Response(
  1278. 200,
  1279. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  1280. )
  1281. async with httpx.AsyncClient(
  1282. transport=httpx.MockTransport(handler),
  1283. base_url="https://llm.test/v1",
  1284. ) as http_client:
  1285. client = OpenAICompatibleChatClient(
  1286. api_key="",
  1287. base_url="https://llm.test/v1",
  1288. default_model="provider-default",
  1289. request_timeout_seconds=5,
  1290. include_usage=False,
  1291. http_client=http_client,
  1292. )
  1293. [
  1294. item
  1295. async for item in client.stream_chat(
  1296. messages=[ChatMessage(role="user", content="hi")],
  1297. tools=[],
  1298. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  1299. )
  1300. ]
  1301. assert "stream_options" not in captured_payloads[0]
  1302. @pytest.mark.asyncio
  1303. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  1304. captured_payloads: list[dict] = []
  1305. def handler(request: httpx.Request) -> httpx.Response:
  1306. captured_payloads.append(json.loads(request.content))
  1307. return httpx.Response(
  1308. 200,
  1309. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  1310. )
  1311. async with httpx.AsyncClient(
  1312. transport=httpx.MockTransport(handler),
  1313. base_url="https://llm.test/v1",
  1314. ) as http_client:
  1315. client = OpenAICompatibleChatClient(
  1316. api_key="",
  1317. base_url="https://llm.test/v1",
  1318. default_model="provider-default",
  1319. request_timeout_seconds=5,
  1320. http_client=http_client,
  1321. )
  1322. [
  1323. item
  1324. async for item in client.stream_chat(
  1325. messages=[ChatMessage(role="user", content="hi")],
  1326. tools=[],
  1327. params=AgentParams(
  1328. model="provider-default",
  1329. temperature=0.3,
  1330. max_tokens=50,
  1331. extra_body={
  1332. "thinking": {"type": "disabled"},
  1333. "enable_search": False,
  1334. "search_options": {"forced_search": False},
  1335. },
  1336. ),
  1337. )
  1338. ]
  1339. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  1340. assert captured_payloads[0]["enable_search"] is False
  1341. assert captured_payloads[0]["search_options"] == {"forced_search": False}
  1342. @pytest.mark.asyncio
  1343. @pytest.mark.parametrize(
  1344. ("reserved_key", "override_value"),
  1345. [
  1346. ("model", "overridden-model"),
  1347. ("messages", []),
  1348. ("tools", []),
  1349. (
  1350. "tool_choice",
  1351. {"type": "function", "function": {"name": "other_tool"}},
  1352. ),
  1353. ("stream", False),
  1354. ("stream_options", {"include_usage": False}),
  1355. ("temperature", 1.0),
  1356. ("max_tokens", 1),
  1357. ],
  1358. )
  1359. async def test_openai_chat_client_rejects_reserved_extra_body_fields_before_network(
  1360. reserved_key: str,
  1361. override_value: object,
  1362. ):
  1363. network_called = False
  1364. def handler(request: httpx.Request) -> httpx.Response:
  1365. nonlocal network_called
  1366. network_called = True
  1367. return httpx.Response(200)
  1368. async with httpx.AsyncClient(
  1369. transport=httpx.MockTransport(handler),
  1370. base_url="https://llm.test/v1",
  1371. ) as http_client:
  1372. client = OpenAICompatibleChatClient(
  1373. api_key="",
  1374. base_url="https://llm.test/v1",
  1375. default_model="provider-default",
  1376. request_timeout_seconds=5,
  1377. http_client=http_client,
  1378. )
  1379. with pytest.raises(
  1380. ValueError,
  1381. match=f"extra_body contains reserved field: {reserved_key}",
  1382. ):
  1383. [
  1384. item
  1385. async for item in client.stream_chat(
  1386. messages=[ChatMessage(role="user", content="hi")],
  1387. tools=[],
  1388. params=AgentParams(extra_body={reserved_key: override_value}),
  1389. )
  1390. ]
  1391. assert network_called is False