test_websocket_api.py 55 KB

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