test_websocket_api.py 57 KB

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