test_websocket_api.py 60 KB

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