test_websocket_api.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  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.event(
  121. ToolCallEvent(
  122. id="event_agent_call_1",
  123. name=tool_name,
  124. arguments=arguments,
  125. raw_arguments=json.dumps(arguments),
  126. )
  127. )
  128. def test_agent_params_defaults_include_extra_body_and_event_agent_defaults_to_one_round():
  129. chat_params = AgentParams()
  130. event_params = EventAgentParams()
  131. assert chat_params.extra_body == {
  132. "thinking": {"type": "disabled"},
  133. "enable_search": False,
  134. "search_options": {"forced_search": False},
  135. }
  136. assert event_params.extra_body == chat_params.extra_body
  137. assert event_params.max_event_loops == 1
  138. assert event_params.system_prompt == ""
  139. def test_health_returns_ok():
  140. app = create_app(runtime_factory=FakeRuntime)
  141. client = TestClient(app)
  142. response = client.get("/health")
  143. assert response.status_code == 200
  144. assert response.json() == {"status": "ok"}
  145. def test_api_tools_returns_handoff_note_metadata():
  146. app = create_app(runtime_factory=FakeRuntime)
  147. client = TestClient(app)
  148. response = client.get("/api/tools")
  149. assert response.status_code == 200
  150. tools = response.json()
  151. assert [tool["name"] for tool in tools] == [
  152. "handoff_note",
  153. "mock_search",
  154. "mock_ticket",
  155. ]
  156. assert tools[0]["parameters"]["required"] == ["message"]
  157. def test_session_api_creates_lists_and_returns_empty_replay_data(tmp_path):
  158. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  159. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  160. client = TestClient(app)
  161. created = client.post(
  162. "/api/sessions",
  163. json={
  164. "title": "Debug session",
  165. "config": {"chat_agent": {"model": "chat-model"}},
  166. },
  167. )
  168. assert created.status_code == 200
  169. session_id = created.json()["id"]
  170. assert created.json()["title"] == "Debug session"
  171. sessions = client.get("/api/sessions")
  172. assert sessions.status_code == 200
  173. assert sessions.json()[0]["id"] == session_id
  174. assert sessions.json()[0]["turn_count"] == 0
  175. detail = client.get(f"/api/sessions/{session_id}")
  176. assert detail.status_code == 200
  177. assert detail.json()["config"]["chat_agent"]["model"] == "chat-model"
  178. assert client.get(f"/api/sessions/{session_id}/messages").json() == []
  179. assert client.get(f"/api/sessions/{session_id}/audit").json() == []
  180. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  181. assert usage == {
  182. "calls": [],
  183. "turns": [],
  184. "session": {
  185. "prompt_tokens": 0,
  186. "completion_tokens": 0,
  187. "total_tokens": 0,
  188. "cached_tokens": 0,
  189. "elapsed_ms": 0,
  190. },
  191. }
  192. def test_session_api_returns_persisted_replay_data(tmp_path):
  193. database_path = tmp_path / "agent_lab.sqlite3"
  194. settings = Settings(database_path=str(database_path))
  195. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  196. client = TestClient(app)
  197. session_id = client.post("/api/sessions", json={"title": "Replay"}).json()["id"]
  198. store = SQLiteSessionStore(database_path)
  199. store.start_turn(session_id, turn_index=1, user_message="debug this")
  200. store.append_message(
  201. session_id,
  202. turn_index=1,
  203. message=ChatMessage(role="user", content="debug this"),
  204. )
  205. store.append_message(
  206. session_id,
  207. turn_index=1,
  208. message=ChatMessage(role="assistant", content="answer"),
  209. )
  210. store.append_audit(
  211. session_id,
  212. event="chat_agent_request",
  213. details={"model": "chat-model"},
  214. turn_index=1,
  215. round_index=1,
  216. )
  217. store.append_usage(
  218. session_id,
  219. turn_index=1,
  220. round_index=1,
  221. usage=TokenUsage(prompt_tokens=1, completion_tokens=2, total_tokens=3),
  222. ttft_ms=10,
  223. elapsed_ms=20,
  224. )
  225. assert [message["content"] for message in client.get(
  226. f"/api/sessions/{session_id}/messages"
  227. ).json()] == ["debug this", "answer"]
  228. assert client.get(f"/api/sessions/{session_id}/audit").json()[0]["details"] == {
  229. "model": "chat-model"
  230. }
  231. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  232. assert usage["calls"][0]["total_tokens"] == 3
  233. assert usage["turns"][0]["total_tokens"] == 3
  234. assert usage["session"]["total_tokens"] == 3
  235. def test_default_websocket_runtime_factory_accepts_session_store(tmp_path):
  236. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  237. app = create_app(settings=settings)
  238. client = TestClient(app)
  239. with client.websocket_connect("/ws/debug") as websocket:
  240. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  241. message = websocket.receive_json()
  242. assert message["type"] == "error"
  243. assert "user_message" in message["message"]
  244. def test_websocket_debug_streams_runtime_messages():
  245. runtime = FakeRuntime()
  246. app = create_app(runtime_factory=lambda: runtime)
  247. client = TestClient(app)
  248. with client.websocket_connect("/ws/debug") as websocket:
  249. websocket.send_json(_request_payload())
  250. assert websocket.receive_json() == {"type": "session_started"}
  251. assert websocket.receive_json() == {
  252. "type": "message_delta",
  253. "content": "hello",
  254. }
  255. assert websocket.receive_json() == {"type": "done"}
  256. assert runtime.requests[0].user_message == "debug this"
  257. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  258. def test_websocket_debug_logs_session_lifecycle(caplog):
  259. runtime = FakeRuntime()
  260. app = create_app(runtime_factory=lambda: runtime)
  261. client = TestClient(app)
  262. with caplog.at_level(logging.INFO, logger="agent_lab.presentation.web"):
  263. with client.websocket_connect("/ws/debug") as websocket:
  264. websocket.send_json(_request_payload())
  265. assert websocket.receive_json() == {"type": "session_started"}
  266. assert websocket.receive_json() == {
  267. "type": "message_delta",
  268. "content": "hello",
  269. }
  270. assert websocket.receive_json() == {"type": "done"}
  271. assert "websocket session accepted" in caplog.text
  272. assert "websocket request accepted" in caplog.text
  273. assert "websocket session closed" in caplog.text
  274. def test_websocket_debug_enqueues_user_messages_during_running_session():
  275. runtime = QueueAwareRuntime()
  276. app = create_app(runtime_factory=lambda: runtime)
  277. client = TestClient(app)
  278. with client.websocket_connect("/ws/debug") as websocket:
  279. websocket.send_json(_request_payload())
  280. assert websocket.receive_json() == {"type": "session_started"}
  281. websocket.send_json({"type": "user_message", "content": "follow-up"})
  282. assert websocket.receive_json() == {
  283. "type": "message_delta",
  284. "content": "follow-up",
  285. }
  286. assert websocket.receive_json() == {"type": "done"}
  287. assert runtime.requests[0].user_message == "debug this"
  288. def test_websocket_debug_keeps_session_open_for_multiple_turns():
  289. runtime = PersistentSessionRuntime()
  290. app = create_app(runtime_factory=lambda: runtime)
  291. client = TestClient(app)
  292. with client.websocket_connect("/ws/debug") as websocket:
  293. websocket.send_json(_request_payload())
  294. assert websocket.receive_json() == {"type": "session_started"}
  295. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 1}
  296. assert websocket.receive_json() == {
  297. "type": "message_delta",
  298. "content": "debug this",
  299. }
  300. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 1}
  301. websocket.send_json({"type": "user_message", "content": "follow-up"})
  302. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 2}
  303. assert websocket.receive_json() == {
  304. "type": "message_delta",
  305. "content": "follow-up",
  306. }
  307. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 2}
  308. websocket.close()
  309. assert runtime.requests[0].user_message == "debug this"
  310. def test_websocket_debug_sends_error_for_invalid_request():
  311. app = create_app(runtime_factory=FakeRuntime)
  312. client = TestClient(app)
  313. with client.websocket_connect("/ws/debug") as websocket:
  314. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  315. message = websocket.receive_json()
  316. assert message["type"] == "error"
  317. assert "user_message" in message["message"]
  318. def test_debug_run_request_rejects_invalid_pre_message_role():
  319. payload = _request_payload()
  320. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  321. with pytest.raises(ValidationError) as exc_info:
  322. DebugRunRequest.model_validate(payload)
  323. assert "role" in str(exc_info.value)
  324. def test_debug_run_request_rejects_tool_pre_messages():
  325. payload = _request_payload()
  326. payload["pre_messages"] = [
  327. {
  328. "role": "tool",
  329. "content": "orphan result",
  330. "tool_call_id": "call_1",
  331. }
  332. ]
  333. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  334. DebugRunRequest.model_validate(payload)
  335. def test_chat_message_allows_internal_tool_replies():
  336. message = ChatMessage(
  337. role="tool",
  338. content='{"message":"handled"}',
  339. name="handoff_note",
  340. tool_call_id="call_1",
  341. )
  342. assert message.role == "tool"
  343. assert message.tool_call_id == "call_1"
  344. class HistoryCapturingChatClient:
  345. def __init__(self) -> None:
  346. self.calls = 0
  347. self.second_call_messages: list[ChatMessage] = []
  348. async def stream_chat(
  349. self,
  350. messages: list[ChatMessage],
  351. tools: list[dict],
  352. params: AgentParams,
  353. ) -> AsyncIterator[StreamItem]:
  354. if tools:
  355. yield _event_tool_call_from_tools(tools, messages)
  356. return
  357. self.calls += 1
  358. if self.calls == 1:
  359. yield StreamItem.message_delta("Need event help.")
  360. yield StreamItem.event(
  361. ToolCallEvent(
  362. id="call_1",
  363. name="handoff_note",
  364. arguments={},
  365. raw_arguments="{}",
  366. )
  367. )
  368. return
  369. self.second_call_messages = list(messages)
  370. yield StreamItem.message_delta("Final answer.")
  371. @pytest.mark.asyncio
  372. async def test_runtime_appends_event_summary_without_tool_reply_history():
  373. request = DebugRunRequest(
  374. user_message="debug this",
  375. system_prompts=["You are a debugger."],
  376. pre_messages=[],
  377. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  378. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  379. )
  380. client = HistoryCapturingChatClient()
  381. runtime = DebugRuntime(client)
  382. outputs = [message async for message in runtime.run(request)]
  383. assert client.calls == 2
  384. assert [message.role for message in client.second_call_messages] == [
  385. "system",
  386. "system",
  387. "user",
  388. "assistant",
  389. "user",
  390. ]
  391. assert "Available events:" in client.second_call_messages[1].content
  392. assert client.second_call_messages[3].content == "Need event help."
  393. assert not any(message.role == "tool" for message in client.second_call_messages)
  394. assert client.second_call_messages[4].content.startswith("EventAgent results:\n")
  395. assert client.second_call_messages[4].name == "event_agent"
  396. assert outputs[-1] == {"type": "done"}
  397. @pytest.mark.asyncio
  398. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  399. requests: list[httpx.Request] = []
  400. def handler(request: httpx.Request) -> httpx.Response:
  401. requests.append(request)
  402. payload = json.loads(request.content)
  403. assert payload["stream"] is True
  404. assert payload["model"] == "model-x"
  405. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  406. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  407. assert payload["tool_choice"] == {
  408. "type": "function",
  409. "function": {"name": "handoff_note"},
  410. }
  411. assert payload["temperature"] == 0.3
  412. assert payload["max_tokens"] == 50
  413. assert request.headers["authorization"] == "Bearer test-key"
  414. return httpx.Response(
  415. 200,
  416. content=(
  417. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  418. b"data: [DONE]\n\n"
  419. ),
  420. )
  421. async with httpx.AsyncClient(
  422. transport=httpx.MockTransport(handler),
  423. base_url="https://llm.test/v1",
  424. ) as http_client:
  425. client = OpenAICompatibleChatClient(
  426. api_key="test-key",
  427. base_url="https://llm.test/v1",
  428. default_model="default-model",
  429. request_timeout_seconds=5,
  430. http_client=http_client,
  431. )
  432. items = [
  433. item
  434. async for item in client.stream_chat(
  435. messages=[ChatMessage(role="user", content="hi")],
  436. tools=[
  437. {
  438. "type": "function",
  439. "function": {"name": "handoff_note", "parameters": {}},
  440. }
  441. ],
  442. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  443. )
  444. ]
  445. assert requests[0].url.path == "/v1/chat/completions"
  446. assert [item.content for item in items if item.kind == "message_delta"] == ["hi"]
  447. assert [item.raw_chunk for item in items if item.kind == "raw_chunk"] == [
  448. {"choices": [{"delta": {"content": "hi"}, "finish_reason": None}]}
  449. ]
  450. @pytest.mark.asyncio
  451. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  452. captured_payloads: list[dict] = []
  453. def handler(request: httpx.Request) -> httpx.Response:
  454. captured_payloads.append(json.loads(request.content))
  455. return httpx.Response(
  456. 200,
  457. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  458. )
  459. async with httpx.AsyncClient(
  460. transport=httpx.MockTransport(handler),
  461. base_url="https://llm.test/v1",
  462. ) as http_client:
  463. client = OpenAICompatibleChatClient(
  464. api_key="",
  465. base_url="https://llm.test/v1",
  466. default_model="provider-default",
  467. request_timeout_seconds=5,
  468. http_client=http_client,
  469. )
  470. [
  471. item
  472. async for item in client.stream_chat(
  473. messages=[ChatMessage(role="user", content="hi")],
  474. tools=[],
  475. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  476. )
  477. ]
  478. assert captured_payloads[0]["model"] == "provider-default"
  479. @pytest.mark.asyncio
  480. async def test_openai_chat_client_rejects_internal_tool_messages_before_network():
  481. network_called = False
  482. def handler(request: httpx.Request) -> httpx.Response:
  483. nonlocal network_called
  484. network_called = True
  485. return httpx.Response(
  486. 200,
  487. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  488. )
  489. async with httpx.AsyncClient(
  490. transport=httpx.MockTransport(handler),
  491. base_url="https://llm.test/v1",
  492. ) as http_client:
  493. client = OpenAICompatibleChatClient(
  494. api_key="",
  495. base_url="https://llm.test/v1",
  496. default_model="provider-default",
  497. request_timeout_seconds=5,
  498. http_client=http_client,
  499. )
  500. with pytest.raises(ValueError, match="tool messages are internal"):
  501. [
  502. item
  503. async for item in client.stream_chat(
  504. messages=[
  505. ChatMessage(
  506. role="tool",
  507. content="internal tool result",
  508. tool_call_id="call_1",
  509. )
  510. ],
  511. tools=[],
  512. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  513. )
  514. ]
  515. assert network_called is False
  516. def test_static_pre_message_role_selector_does_not_offer_tool():
  517. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  518. assert '<option value="tool">tool</option>' not in html
  519. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  520. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  521. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  522. assert 'id="tool-handoff-note"' not in html
  523. assert "#tool-handoff-note" not in js
  524. assert 'id="tool-list"' in html
  525. assert '"/api/tools"' in js
  526. assert "fetch" in js
  527. def test_static_workspace_snapshot_controls_are_available_outside_agent_config():
  528. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  529. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  530. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  531. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  532. sidebar_html = html[:chat_dialog_start]
  533. assert 'id="open-prompt-config"' not in html
  534. assert '<dialog id="prompt-dialog"' not in html
  535. assert 'id="workspace-snapshot-name"' in sidebar_html
  536. assert 'id="saved-workspace-snapshots"' in sidebar_html
  537. assert 'id="save-workspace-snapshot"' in sidebar_html
  538. assert 'id="load-workspace-snapshot"' in sidebar_html
  539. assert 'id="delete-workspace-snapshot"' in sidebar_html
  540. assert 'id="workspace-snapshot-name"' not in chat_dialog_html
  541. assert 'id="saved-workspace-snapshots"' not in chat_dialog_html
  542. assert 'id="save-workspace-snapshot"' not in chat_dialog_html
  543. assert 'id="system-prompts"' in chat_dialog_html
  544. assert 'id="pre-messages"' in chat_dialog_html
  545. def test_static_session_ui_controls_and_replay_panels_are_available():
  546. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  547. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  548. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  549. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  550. event_dialog_html = html[event_dialog_start:]
  551. sidebar_html = html[:chat_dialog_start]
  552. for control_id in [
  553. "session-title",
  554. "session-list",
  555. "new-session",
  556. "refresh-sessions",
  557. "load-session",
  558. "session-status",
  559. ]:
  560. assert f'id="{control_id}"' in sidebar_html
  561. assert f'id="{control_id}"' not in chat_dialog_html
  562. assert f'id="{control_id}"' not in event_dialog_html
  563. for replay_id in [
  564. "audit-replay",
  565. "audit-count",
  566. "session-usage-summary",
  567. "session-usage-turns",
  568. "session-usage-calls",
  569. ]:
  570. assert f'id="{replay_id}"' in html
  571. def test_static_chat_agent_prompt_is_a_single_sortable_list_with_event_instructions():
  572. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  573. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  574. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  575. assert 'id="chat-system-prompt"' not in html
  576. assert 'id="chat-event-prompt-preview"' not in html
  577. assert 'class="prompt-list stack"' in html
  578. assert 'class="prompt-item"' in html
  579. assert 'data-prompt-role="system"' in html
  580. assert "prompt-type" in html
  581. assert "function buildAvailableEventsPrompt(" in js
  582. assert "Available events:" in js
  583. assert "function updateEventPromptItem(" in js
  584. assert "function createSystemPrompt(" in js
  585. assert "function movePromptItem(" in js
  586. assert 'draggable = true' in js
  587. assert "dataset.promptRole" in js
  588. assert "prompt-title" in js
  589. assert "delete-system-prompt" in js
  590. assert 'prompt_kind: "event_agent_system"' in js
  591. assert "system_prompts: collectSystemPrompts()" in js
  592. assert 'system_prompt: ""' in js
  593. assert ".prompt-item" in css
  594. assert ".prompt-item.dragging" in css
  595. assert ".prompt-meta" in css
  596. assert ".prompt-type" in css
  597. assert ".prompt-actions button" in css
  598. assert "#open-prompt-config" not in js
  599. assert "promptDialog" not in js
  600. def test_static_app_script_is_versioned_and_click_binding_is_guarded():
  601. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  602. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  603. assert '<script src="/static/app.js?v=' in html
  604. assert "function bindClick(" in js
  605. assert 'bindClick("#open-chat-config-panel", openChatConfig)' in js
  606. assert 'bindClick("#open-event-config-panel", openEventConfig)' in js
  607. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  608. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  609. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  610. assert '<dialog id="chat-config-dialog"' in html
  611. assert '<dialog id="event-config-dialog"' in html
  612. assert html.count('id="open-chat-config-panel"') == 1
  613. assert html.count('id="open-event-config-panel"') == 1
  614. assert 'id="open-chat-config"' not in html
  615. assert 'id="open-event-config"' not in html
  616. assert '#open-chat-config"' not in js
  617. assert '#open-event-config"' not in js
  618. assert '#open-chat-config-panel"' in js
  619. assert '#open-event-config-panel"' in js
  620. assert 'id="close-chat-config"' in html
  621. assert 'id="close-event-config"' in html
  622. assert "chatConfigDialog.showModal()" in js
  623. assert "eventConfigDialog.showModal()" in js
  624. assert "chatConfigDialog.close()" in js
  625. assert "eventConfigDialog.close()" in js
  626. for control_id in [
  627. "model",
  628. "temperature",
  629. "max-tokens",
  630. "chat-thinking-disabled",
  631. "chat-enable-search",
  632. "chat-forced-search",
  633. "event-model",
  634. "event-temperature",
  635. "event-max-tokens",
  636. "event-system-prompt",
  637. "event-thinking-disabled",
  638. "event-enable-search",
  639. "event-forced-search",
  640. ]:
  641. assert f'id="{control_id}"' in html
  642. assert 'extra_body: buildExtraBody("chat")' in js
  643. assert 'extra_body: buildExtraBody("event")' in js
  644. assert 'system_prompt: ""' in js
  645. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  646. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  647. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  648. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  649. assert 'id="tool-count"' in html
  650. assert 'id="select-all-tools"' in html
  651. assert 'id="clear-tools"' in html
  652. assert "tool-card" in js
  653. assert "tool-description" in js
  654. assert "tool-required" in js
  655. assert "function updateToolCount()" in js
  656. def test_static_app_handles_audit_messages():
  657. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  658. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  659. assert 'message.type === "audit"' in js
  660. assert "appendAuditEntry(message)" in js
  661. assert 'appendLog("audit"' not in js
  662. assert "function renderAuditDetail(" in js
  663. assert "chat_agent_request" in js
  664. assert "event_agent_response" in js
  665. assert "chat_message_stream_started" in js
  666. assert "chat_message_stream_finished" in js
  667. assert ".audit-event" in css
  668. assert ".audit-detail" in css
  669. def test_static_audit_replay_uses_event_stream_and_detail_panel():
  670. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  671. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  672. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  673. assert '<link rel="stylesheet" href="/static/styles.css?v=' in html
  674. assert "session-switch-idle-socket" in html
  675. assert 'id="audit-dialog"' in html
  676. assert 'id="open-audit-dialog"' in html
  677. assert 'id="close-audit-dialog"' in html
  678. assert 'id="audit-summary"' in html
  679. assert 'id="audit-replay" class="audit-stream"' in html
  680. assert 'id="audit-detail"' in html
  681. assert "auditDialog.showModal()" in js
  682. assert "auditDialog.close()" in js
  683. assert "auditEntryKey(entry)" in js
  684. assert "selectAuditEntry(key)" in js
  685. assert 'meta.className = "audit-detail-meta"' in js
  686. assert 'appendMetaField(meta, "Since User Message"' in js
  687. assert "auditRelativeTime(entry)" in js
  688. assert 'const list = document.createElement("ul")' in js
  689. assert "appendKeyValueSection(auditDetail, \"Model Parameters\"" in js
  690. assert "appendRepliesSection(auditDetail, details.replies)" in js
  691. assert "appendRawChunksSection(auditDetail, \"Raw LLM Chunks\"" in js
  692. assert "appendRawModelChunksSection(auditDetail, details.raw_model_chunks)" in js
  693. assert "Enabled This Round" in js
  694. assert "Configured Events" in js
  695. assert "details.configured_events" in js
  696. assert "enabled this round" in js
  697. assert ".audit-modal" in css
  698. assert ".audit-modal-body" in css
  699. assert ".audit-modal-body section + section" in css
  700. assert ".audit-detail-title" in css
  701. assert ".detail-tags code" in css
  702. assert ".audit-detail-meta span" not in css
  703. assert ".detail-tags span" not in css
  704. assert "display: block" in _css_rule(css, ".audit-detail")
  705. assert "display: grid" not in _css_rule(css, ".audit-detail")
  706. assert "display: block" in _css_rule(css, ".audit-detail-header")
  707. assert "display: grid" not in _css_rule(css, ".audit-detail-header")
  708. assert "display: inline-flex" in _css_rule(css, ".audit-detail-meta div")
  709. assert ".audit-marker::before" in css
  710. assert ".audit-event.is-selected" in css
  711. def test_static_layout_keeps_controls_and_composer_fixed_with_scrollable_panes():
  712. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  713. assert "height: calc(100vh - 56px)" in css
  714. assert ".layout" in css and "overflow: hidden" in css
  715. assert ".controls" in css and "overflow: auto" in css
  716. assert ".workspace {\n display: grid;\n grid-template-rows: minmax(0, 1fr) auto auto;" in css
  717. assert ".workspace-body" in css and "overflow: hidden" in css
  718. assert ".messages" in css and "overflow: auto" in css
  719. assert ".audit-stream" in css and "overflow: auto" in css
  720. def test_static_app_shows_wait_state_and_immediate_user_echo():
  721. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  722. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  723. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  724. assert 'id="run-button"' in html
  725. assert 'const runButton = document.querySelector("#run-button")' in js
  726. assert 'appendLog("user", submittedMessage)' in js
  727. assert 'statusEl.textContent = "Waiting for first token"' in js
  728. assert "function startElapsedTimer()" in js
  729. assert "function stopElapsedTimer()" in js
  730. assert "function setRunState(" in js
  731. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  732. assert "hasBackendRoundStats && firstTokenAt" in js
  733. assert ".user" in css
  734. def test_static_app_reuses_websocket_for_session_turns():
  735. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  736. assert "function isSocketOpen()" in js
  737. assert "socket.send(JSON.stringify({ type: \"user_message\"" in js
  738. assert "session_id: currentSessionId || undefined" in js
  739. assert "message.session_id" in js
  740. assert 'message.type === "turn_completed"' in js
  741. assert 'message.type === "done"' in js
  742. def test_static_app_loads_session_replay_and_usage():
  743. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  744. assert "function loadSessions(" in js
  745. assert "function createSession(" in js
  746. assert "function setSessionStatus(" in js
  747. assert '"Refreshing sessions"' in js
  748. assert '"Creating session"' in js
  749. assert '"Session created"' in js
  750. assert 'sessionStatus.textContent = message' in js
  751. assert "function loadSessionReplay(" in js
  752. assert 'fetchJson("/api/sessions")' in js
  753. assert 'method: "POST"' in js
  754. assert '`/api/sessions/${sessionId}/messages`' in js
  755. assert '`/api/sessions/${sessionId}/audit`' in js
  756. assert '`/api/sessions/${sessionId}/usage`' in js
  757. assert "function renderAuditReplay(" in js
  758. assert "function renderSessionUsage(" in js
  759. assert "sessionUsageSummary" in js
  760. assert "Finish current turn before switching sessions" in js
  761. def test_static_session_switch_guard_uses_active_turn_not_open_socket():
  762. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  763. create_session = js[js.index("async function createSession()") : js.index("async function loadSelectedSession()")]
  764. load_session = js[js.index("async function loadSelectedSession()") : js.index("async function loadSessionReplay(")]
  765. assert "function hasActiveTurn()" in js
  766. assert "turnActive = isRunning" in js
  767. assert "if (hasActiveTurn())" in create_session
  768. assert "if (hasActiveTurn())" in load_session
  769. assert "if (isSocketOpen())" not in create_session
  770. assert "if (isSocketOpen())" not in load_session
  771. assert "closeSocket();" in create_session
  772. assert "closeSocket();" in load_session
  773. assert "const activeSocket = socket" in js
  774. assert "if (socket !== activeSocket)" in js
  775. def test_static_workspace_snapshot_uses_stable_storage_hooks():
  776. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  777. assert "agent-lab.workspace-snapshots.v1" in js
  778. assert "agent-lab.prompt-sets.v1" in js
  779. assert "function saveWorkspaceSnapshot()" in js
  780. assert "function loadWorkspaceSnapshot()" in js
  781. assert "function deleteWorkspaceSnapshot()" in js
  782. assert "function buildWorkspaceSnapshot()" in js
  783. assert "prompt_items: buildPromptItems()" in js
  784. assert "enabled_tools: selectedTools()" in js
  785. assert "extra_body: buildExtraBody(\"chat\")" in js
  786. assert "extra_body: buildExtraBody(\"event\")" in js
  787. def test_static_app_handles_backend_round_stats_messages():
  788. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  789. assert 'message.type === "round_stats"' in js
  790. assert "function updateRoundStats(" in js
  791. assert "#stat-ttft" in js
  792. assert "#stat-elapsed" in js
  793. @pytest.mark.asyncio
  794. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  795. captured_payloads: list[dict] = []
  796. def handler(request: httpx.Request) -> httpx.Response:
  797. captured_payloads.append(json.loads(request.content))
  798. return httpx.Response(
  799. 200,
  800. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  801. )
  802. async with httpx.AsyncClient(
  803. transport=httpx.MockTransport(handler),
  804. base_url="https://llm.test/v1",
  805. ) as http_client:
  806. client = OpenAICompatibleChatClient(
  807. api_key="",
  808. base_url="https://llm.test/v1",
  809. default_model="provider-default",
  810. request_timeout_seconds=5,
  811. include_usage=False,
  812. http_client=http_client,
  813. )
  814. [
  815. item
  816. async for item in client.stream_chat(
  817. messages=[ChatMessage(role="user", content="hi")],
  818. tools=[],
  819. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  820. )
  821. ]
  822. assert "stream_options" not in captured_payloads[0]
  823. @pytest.mark.asyncio
  824. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  825. captured_payloads: list[dict] = []
  826. def handler(request: httpx.Request) -> httpx.Response:
  827. captured_payloads.append(json.loads(request.content))
  828. return httpx.Response(
  829. 200,
  830. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  831. )
  832. async with httpx.AsyncClient(
  833. transport=httpx.MockTransport(handler),
  834. base_url="https://llm.test/v1",
  835. ) as http_client:
  836. client = OpenAICompatibleChatClient(
  837. api_key="",
  838. base_url="https://llm.test/v1",
  839. default_model="provider-default",
  840. request_timeout_seconds=5,
  841. http_client=http_client,
  842. )
  843. [
  844. item
  845. async for item in client.stream_chat(
  846. messages=[ChatMessage(role="user", content="hi")],
  847. tools=[],
  848. params=AgentParams(
  849. model="provider-default",
  850. temperature=0.3,
  851. max_tokens=50,
  852. extra_body={
  853. "thinking": {"type": "disabled"},
  854. "enable_search": False,
  855. "search_options": {"forced_search": False},
  856. },
  857. ),
  858. )
  859. ]
  860. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  861. assert captured_payloads[0]["enable_search"] is False
  862. assert captured_payloads[0]["search_options"] == {"forced_search": False}