test_websocket_api.py 56 KB

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