test_websocket_api.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186
  1. import json
  2. import asyncio
  3. import logging
  4. import subprocess
  5. from collections.abc import AsyncIterator
  6. from pathlib import Path
  7. import httpx
  8. import pytest
  9. from fastapi.testclient import TestClient
  10. from pydantic import ValidationError
  11. from agent_lab.application.contracts import AgentParams, DebugRunRequest, EventAgentParams
  12. from agent_lab.application.queues import RuntimeQueues
  13. from agent_lab.application.runtime import DebugRuntime
  14. from agent_lab.domain.events import ToolCallEvent
  15. from agent_lab.domain.messages import ChatMessage, StreamItem, TokenUsage
  16. from agent_lab.infrastructure.chat_client import OpenAICompatibleChatClient
  17. from agent_lab.infrastructure.sqlite_store import SQLiteSessionStore
  18. from agent_lab.presentation.web import create_app
  19. from agent_lab.settings import Settings
  20. def _css_rule(css: str, selector: str) -> str:
  21. start = css.index(f"{selector} {{")
  22. end = css.index("}", start)
  23. return css[start:end]
  24. def _run_node_json(source: str) -> object:
  25. completed = subprocess.run(
  26. ["node", "--input-type=module", "-e", source],
  27. capture_output=True,
  28. text=True,
  29. check=False,
  30. )
  31. assert completed.returncode == 0, completed.stderr
  32. return json.loads(completed.stdout)
  33. def _run_load_session_replay_scenario(scenario: str) -> object:
  34. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  35. load_replay = js[
  36. js.index("async function loadSessionReplay(") :
  37. js.index("function setSessionStatus(")
  38. ]
  39. harness = """
  40. let currentSessionId = null;
  41. let sessionReplayLoadToken = 0;
  42. const sessionTitle = { value: "" };
  43. const sessionList = { value: "" };
  44. const mutations = {
  45. workspace: [],
  46. transcript: [],
  47. audit: [],
  48. usage: [],
  49. status: [],
  50. };
  51. const pending = new Map();
  52. function fetchJson(url) {
  53. let resolve;
  54. let reject;
  55. const promise = new Promise((resolvePromise, rejectPromise) => {
  56. resolve = resolvePromise;
  57. reject = rejectPromise;
  58. });
  59. pending.set(url, { resolve, reject });
  60. return promise;
  61. }
  62. function resolveReplay(sessionId) {
  63. pending.get(`/api/sessions/${sessionId}`).resolve({
  64. title: `${sessionId} title`,
  65. config: { marker: sessionId },
  66. });
  67. pending.get(`/api/sessions/${sessionId}/messages`).resolve([
  68. { content: sessionId },
  69. ]);
  70. pending.get(`/api/sessions/${sessionId}/audit`).resolve([
  71. { event: sessionId },
  72. ]);
  73. pending.get(`/api/sessions/${sessionId}/usage`).resolve({
  74. session: { marker: sessionId },
  75. });
  76. }
  77. function restoreWorkspaceSnapshot(config) {
  78. mutations.workspace.push(config.marker);
  79. }
  80. function renderReplayMessages(messages) {
  81. mutations.transcript.push(messages[0].content);
  82. }
  83. function renderAuditReplay(audit) {
  84. mutations.audit.push(audit[0].event);
  85. }
  86. function renderSessionUsage(usage) {
  87. mutations.usage.push(usage.session.marker);
  88. }
  89. function setSessionStatus(status) {
  90. mutations.status.push(status);
  91. }
  92. function isSocketOpen() {
  93. return false;
  94. }
  95. """
  96. return _run_node_json("\n".join([harness, load_replay, scenario]))
  97. class FakeRuntime:
  98. def __init__(self) -> None:
  99. self.requests: list[DebugRunRequest] = []
  100. async def run(self, request: DebugRunRequest) -> AsyncIterator[dict]:
  101. self.requests.append(request)
  102. yield {"type": "session_started"}
  103. yield {"type": "message_delta", "content": "hello"}
  104. yield {"type": "done"}
  105. class QueueAwareRuntime:
  106. def __init__(self) -> None:
  107. self.requests: list[DebugRunRequest] = []
  108. self.queues: RuntimeQueues | None = None
  109. self.task: asyncio.Task | None = None
  110. def start(self, request: DebugRunRequest) -> RuntimeQueues:
  111. self.requests.append(request)
  112. self.queues = RuntimeQueues()
  113. self.task = asyncio.create_task(self._run())
  114. return self.queues
  115. async def _run(self) -> None:
  116. assert self.queues is not None
  117. await self.queues.output.put({"type": "session_started"})
  118. message = await self.queues.input.get()
  119. await self.queues.output.put(
  120. {"type": "message_delta", "content": message.content}
  121. )
  122. await self.queues.output.put({"type": "done"})
  123. async def aclose(self) -> None:
  124. if self.task is not None and not self.task.done():
  125. self.task.cancel()
  126. await asyncio.gather(self.task, return_exceptions=True)
  127. class PersistentSessionRuntime:
  128. def __init__(self) -> None:
  129. self.requests: list[DebugRunRequest] = []
  130. self.queues: RuntimeQueues | None = None
  131. self.task: asyncio.Task | None = None
  132. def start_session(self, request: DebugRunRequest) -> RuntimeQueues:
  133. self.requests.append(request)
  134. self.queues = RuntimeQueues()
  135. self.task = asyncio.create_task(self._run(request))
  136. return self.queues
  137. async def _run(self, request: DebugRunRequest) -> None:
  138. assert self.queues is not None
  139. await self.queues.output.put({"type": "session_started"})
  140. await self._emit_turn(1, request.user_message)
  141. turn_index = 1
  142. while True:
  143. message = await self.queues.input.get()
  144. turn_index += 1
  145. await self._emit_turn(turn_index, message.content)
  146. async def _emit_turn(self, turn_index: int, content: str) -> None:
  147. assert self.queues is not None
  148. await self.queues.output.put({"type": "turn_started", "turn_index": turn_index})
  149. await self.queues.output.put({"type": "message_delta", "content": content})
  150. await self.queues.output.put(
  151. {"type": "turn_completed", "turn_index": turn_index}
  152. )
  153. async def aclose(self) -> None:
  154. if self.task is not None and not self.task.done():
  155. self.task.cancel()
  156. await asyncio.gather(self.task, return_exceptions=True)
  157. def _request_payload() -> dict:
  158. return {
  159. "user_message": "debug this",
  160. "system_prompts": ["You are a debugger."],
  161. "pre_messages": [{"role": "user", "content": "previous turn"}],
  162. "chat_agent": {
  163. "model": "fake-model",
  164. "temperature": 0.1,
  165. "max_tokens": 200,
  166. },
  167. "event_agent": {
  168. "enabled_tools": ["handoff_note"],
  169. "max_event_loops": 2,
  170. },
  171. }
  172. def _event_tool_call_from_tools(
  173. tools: list[dict],
  174. messages: list[ChatMessage],
  175. ) -> StreamItem:
  176. tool_name = tools[0]["function"]["name"]
  177. content = ""
  178. for role in ("assistant", "user"):
  179. content = next(
  180. (
  181. message.content
  182. for message in reversed(messages)
  183. if message.role == role and message.content.strip()
  184. ),
  185. "",
  186. )
  187. if content:
  188. break
  189. arguments = {
  190. "message": content,
  191. "query": content,
  192. "title": content,
  193. }
  194. return StreamItem.provider_tool_call(
  195. ToolCallEvent(
  196. id="event_agent_call_1",
  197. name=tool_name,
  198. arguments=arguments,
  199. raw_arguments=json.dumps(arguments),
  200. )
  201. )
  202. def test_agent_params_defaults_include_extra_body_and_event_agent_defaults_to_one_round():
  203. chat_params = AgentParams()
  204. event_params = EventAgentParams()
  205. assert chat_params.extra_body == {
  206. "thinking": {"type": "disabled"},
  207. "enable_search": False,
  208. "search_options": {"forced_search": False},
  209. }
  210. assert event_params.extra_body == chat_params.extra_body
  211. assert event_params.max_event_loops == 1
  212. assert event_params.max_parallel_events == 4
  213. assert event_params.batch_timeout_seconds == 15.0
  214. assert event_params.system_prompt == ""
  215. @pytest.mark.parametrize("value", [0, 17])
  216. def test_event_agent_params_rejects_out_of_range_parallelism(value: int):
  217. with pytest.raises(ValidationError, match="max_parallel_events"):
  218. EventAgentParams(max_parallel_events=value)
  219. @pytest.mark.parametrize("value", [0, -1, 121])
  220. def test_event_agent_params_rejects_invalid_batch_timeout(value: float):
  221. with pytest.raises(ValidationError, match="batch_timeout_seconds"):
  222. EventAgentParams(batch_timeout_seconds=value)
  223. def test_debug_run_request_defaults_to_dual_agent_tool_invocation_mode():
  224. request = DebugRunRequest.model_validate(_request_payload())
  225. assert request.tool_invocation_mode == "dual_agent"
  226. @pytest.mark.parametrize("mode", ["dual_agent", "chat_agent_tools"])
  227. def test_debug_run_request_accepts_supported_tool_invocation_modes(mode: str):
  228. payload = _request_payload()
  229. payload["tool_invocation_mode"] = mode
  230. request = DebugRunRequest.model_validate(payload)
  231. assert request.tool_invocation_mode == mode
  232. def test_debug_run_request_rejects_unknown_tool_invocation_mode():
  233. payload = _request_payload()
  234. payload["tool_invocation_mode"] = "unknown"
  235. with pytest.raises(ValidationError, match="tool_invocation_mode"):
  236. DebugRunRequest.model_validate(payload)
  237. def test_health_returns_ok():
  238. app = create_app(runtime_factory=FakeRuntime)
  239. client = TestClient(app)
  240. response = client.get("/health")
  241. assert response.status_code == 200
  242. assert response.json() == {"status": "ok"}
  243. def test_api_tools_returns_default_tool_catalog():
  244. app = create_app(runtime_factory=FakeRuntime)
  245. client = TestClient(app)
  246. response = client.get("/api/tools")
  247. assert response.status_code == 200
  248. tools = response.json()
  249. assert [tool["name"] for tool in tools] == [
  250. "handoff_note",
  251. "mock_search",
  252. "mock_ticket",
  253. "session.terminate",
  254. "device.volume.adjust",
  255. "calendar.schedule.create",
  256. "knowledge.web.search",
  257. ]
  258. assert tools[0]["parameters"]["required"] == ["message"]
  259. def test_session_api_creates_lists_and_returns_empty_replay_data(tmp_path):
  260. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  261. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  262. client = TestClient(app)
  263. created = client.post(
  264. "/api/sessions",
  265. json={
  266. "title": "Debug session",
  267. "config": {"chat_agent": {"model": "chat-model"}},
  268. },
  269. )
  270. assert created.status_code == 200
  271. session_id = created.json()["id"]
  272. assert created.json()["title"] == "Debug session"
  273. sessions = client.get("/api/sessions")
  274. assert sessions.status_code == 200
  275. assert sessions.json()[0]["id"] == session_id
  276. assert sessions.json()[0]["turn_count"] == 0
  277. detail = client.get(f"/api/sessions/{session_id}")
  278. assert detail.status_code == 200
  279. assert detail.json()["config"]["chat_agent"]["model"] == "chat-model"
  280. assert client.get(f"/api/sessions/{session_id}/messages").json() == []
  281. assert client.get(f"/api/sessions/{session_id}/audit").json() == []
  282. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  283. assert usage == {
  284. "calls": [],
  285. "turns": [],
  286. "session": {
  287. "prompt_tokens": 0,
  288. "completion_tokens": 0,
  289. "total_tokens": 0,
  290. "cached_tokens": 0,
  291. "elapsed_ms": 0,
  292. "call_count": 0,
  293. "fallback_count": 0,
  294. "tool_count": 0,
  295. "turn_wall_time_ms": None,
  296. },
  297. }
  298. def test_session_api_returns_persisted_replay_data(tmp_path):
  299. database_path = tmp_path / "agent_lab.sqlite3"
  300. settings = Settings(database_path=str(database_path))
  301. app = create_app(settings=settings, runtime_factory=FakeRuntime)
  302. client = TestClient(app)
  303. session_id = client.post("/api/sessions", json={"title": "Replay"}).json()["id"]
  304. store = SQLiteSessionStore(database_path)
  305. store.start_turn(session_id, turn_index=1, user_message="debug this")
  306. store.append_message(
  307. session_id,
  308. turn_index=1,
  309. message=ChatMessage(role="user", content="debug this"),
  310. )
  311. store.append_message(
  312. session_id,
  313. turn_index=1,
  314. message=ChatMessage(
  315. role="assistant",
  316. content="answer",
  317. tool_calls=[
  318. ToolCallEvent(
  319. id="call-1",
  320. name="mock_search",
  321. arguments={"query": "docs"},
  322. raw_arguments='{"query":"docs"}',
  323. )
  324. ],
  325. ),
  326. )
  327. store.append_message(
  328. session_id,
  329. turn_index=1,
  330. message=ChatMessage(
  331. role="tool",
  332. content='{"results":[]}',
  333. name="mock_search",
  334. tool_call_id="call-1",
  335. ),
  336. )
  337. store.append_audit(
  338. session_id,
  339. event="chat_agent_request",
  340. details={"model": "chat-model"},
  341. turn_index=1,
  342. round_index=1,
  343. )
  344. store.append_usage(
  345. session_id,
  346. turn_index=1,
  347. round_index=1,
  348. usage=TokenUsage(prompt_tokens=1, completion_tokens=2, total_tokens=3),
  349. ttft_ms=10,
  350. elapsed_ms=20,
  351. )
  352. messages = client.get(f"/api/sessions/{session_id}/messages").json()
  353. assert [message["content"] for message in messages] == [
  354. "debug this",
  355. "answer",
  356. '{"results":[]}',
  357. ]
  358. assert messages[0]["tool_calls"] == []
  359. assert messages[1]["tool_calls"] == [
  360. {
  361. "id": "call-1",
  362. "name": "mock_search",
  363. "arguments": {"query": "docs"},
  364. "raw_arguments": '{"query":"docs"}',
  365. }
  366. ]
  367. assert messages[2]["tool_call_id"] == "call-1"
  368. assert messages[2]["tool_calls"] == []
  369. assert client.get(f"/api/sessions/{session_id}/audit").json()[0]["details"] == {
  370. "model": "chat-model"
  371. }
  372. usage = client.get(f"/api/sessions/{session_id}/usage").json()
  373. assert usage["calls"][0]["total_tokens"] == 3
  374. assert usage["turns"][0]["total_tokens"] == 3
  375. assert usage["session"]["total_tokens"] == 3
  376. def test_default_websocket_runtime_factory_accepts_session_store(tmp_path):
  377. settings = Settings(database_path=str(tmp_path / "agent_lab.sqlite3"))
  378. app = create_app(settings=settings)
  379. client = TestClient(app)
  380. with client.websocket_connect("/ws/debug") as websocket:
  381. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  382. message = websocket.receive_json()
  383. assert message["type"] == "error"
  384. assert "user_message" in message["message"]
  385. def test_websocket_debug_streams_runtime_messages():
  386. runtime = FakeRuntime()
  387. app = create_app(runtime_factory=lambda: runtime)
  388. client = TestClient(app)
  389. with client.websocket_connect("/ws/debug") as websocket:
  390. websocket.send_json(_request_payload())
  391. assert websocket.receive_json() == {"type": "session_started"}
  392. assert websocket.receive_json() == {
  393. "type": "message_delta",
  394. "content": "hello",
  395. }
  396. assert websocket.receive_json() == {"type": "done"}
  397. assert runtime.requests[0].user_message == "debug this"
  398. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  399. def test_websocket_debug_logs_session_lifecycle(caplog):
  400. runtime = FakeRuntime()
  401. app = create_app(runtime_factory=lambda: runtime)
  402. client = TestClient(app)
  403. with caplog.at_level(logging.INFO, logger="agent_lab.presentation.web"):
  404. with client.websocket_connect("/ws/debug") as websocket:
  405. websocket.send_json(_request_payload())
  406. assert websocket.receive_json() == {"type": "session_started"}
  407. assert websocket.receive_json() == {
  408. "type": "message_delta",
  409. "content": "hello",
  410. }
  411. assert websocket.receive_json() == {"type": "done"}
  412. assert "websocket session accepted" in caplog.text
  413. assert "websocket request accepted" in caplog.text
  414. assert "websocket session closed" in caplog.text
  415. def test_websocket_debug_enqueues_user_messages_during_running_session():
  416. runtime = QueueAwareRuntime()
  417. app = create_app(runtime_factory=lambda: runtime)
  418. client = TestClient(app)
  419. with client.websocket_connect("/ws/debug") as websocket:
  420. websocket.send_json(_request_payload())
  421. assert websocket.receive_json() == {"type": "session_started"}
  422. websocket.send_json({"type": "user_message", "content": "follow-up"})
  423. assert websocket.receive_json() == {
  424. "type": "message_delta",
  425. "content": "follow-up",
  426. }
  427. assert websocket.receive_json() == {"type": "done"}
  428. assert runtime.requests[0].user_message == "debug this"
  429. def test_websocket_debug_keeps_session_open_for_multiple_turns():
  430. runtime = PersistentSessionRuntime()
  431. app = create_app(runtime_factory=lambda: runtime)
  432. client = TestClient(app)
  433. with client.websocket_connect("/ws/debug") as websocket:
  434. websocket.send_json(_request_payload())
  435. assert websocket.receive_json() == {"type": "session_started"}
  436. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 1}
  437. assert websocket.receive_json() == {
  438. "type": "message_delta",
  439. "content": "debug this",
  440. }
  441. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 1}
  442. websocket.send_json({"type": "user_message", "content": "follow-up"})
  443. assert websocket.receive_json() == {"type": "turn_started", "turn_index": 2}
  444. assert websocket.receive_json() == {
  445. "type": "message_delta",
  446. "content": "follow-up",
  447. }
  448. assert websocket.receive_json() == {"type": "turn_completed", "turn_index": 2}
  449. websocket.close()
  450. assert runtime.requests[0].user_message == "debug this"
  451. def test_websocket_debug_sends_error_for_invalid_request():
  452. app = create_app(runtime_factory=FakeRuntime)
  453. client = TestClient(app)
  454. with client.websocket_connect("/ws/debug") as websocket:
  455. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  456. message = websocket.receive_json()
  457. assert message["type"] == "error"
  458. assert "user_message" in message["message"]
  459. def test_debug_run_request_rejects_invalid_pre_message_role():
  460. payload = _request_payload()
  461. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  462. with pytest.raises(ValidationError) as exc_info:
  463. DebugRunRequest.model_validate(payload)
  464. assert "role" in str(exc_info.value)
  465. def test_debug_run_request_rejects_tool_pre_messages():
  466. payload = _request_payload()
  467. payload["pre_messages"] = [
  468. {
  469. "role": "tool",
  470. "content": "orphan result",
  471. "tool_call_id": "call_1",
  472. }
  473. ]
  474. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  475. DebugRunRequest.model_validate(payload)
  476. def test_debug_run_request_rejects_assistant_tool_calls_in_pre_messages():
  477. payload = _request_payload()
  478. payload["pre_messages"] = [
  479. {
  480. "role": "assistant",
  481. "content": "I will inspect this.",
  482. "tool_calls": [
  483. {
  484. "id": "call_1",
  485. "name": "mock_search",
  486. "arguments": {"query": "latency"},
  487. "raw_arguments": '{"query":"latency"}',
  488. }
  489. ],
  490. }
  491. ]
  492. with pytest.raises(
  493. ValidationError,
  494. match="pre_messages cannot include assistant tool calls",
  495. ):
  496. DebugRunRequest.model_validate(payload)
  497. def test_chat_message_allows_internal_tool_replies():
  498. message = ChatMessage(
  499. role="tool",
  500. content='{"message":"handled"}',
  501. name="handoff_note",
  502. tool_call_id="call_1",
  503. )
  504. assert message.role == "tool"
  505. assert message.tool_call_id == "call_1"
  506. def test_chat_message_preserves_assistant_tool_calls():
  507. message = ChatMessage(
  508. role="assistant",
  509. content="I will inspect both sources.",
  510. tool_calls=[
  511. ToolCallEvent(
  512. id="call_1",
  513. name="mock_search",
  514. arguments={"query": "latency docs"},
  515. raw_arguments='{"query":"latency docs"}',
  516. ),
  517. ToolCallEvent(
  518. id="call_2",
  519. name="handoff_note",
  520. arguments={"message": "inspect provider behavior"},
  521. raw_arguments='{"message":"inspect provider behavior"}',
  522. ),
  523. ],
  524. )
  525. assert message.model_dump()["tool_calls"] == [
  526. {
  527. "id": "call_1",
  528. "name": "mock_search",
  529. "arguments": {"query": "latency docs"},
  530. "raw_arguments": '{"query":"latency docs"}',
  531. },
  532. {
  533. "id": "call_2",
  534. "name": "handoff_note",
  535. "arguments": {"message": "inspect provider behavior"},
  536. "raw_arguments": '{"message":"inspect provider behavior"}',
  537. },
  538. ]
  539. def test_chat_message_rejects_tool_calls_on_non_assistant_role():
  540. with pytest.raises(ValidationError, match="tool_calls require assistant role"):
  541. ChatMessage(
  542. role="user",
  543. content="invalid",
  544. tool_calls=[
  545. ToolCallEvent(
  546. id="call_1",
  547. name="mock_search",
  548. arguments={},
  549. raw_arguments="{}",
  550. )
  551. ],
  552. )
  553. def test_chat_message_rejects_tool_role_without_tool_call_id():
  554. with pytest.raises(ValidationError, match="tool messages require tool_call_id"):
  555. ChatMessage(role="tool", content="orphan result")
  556. @pytest.mark.parametrize("role", ["system", "user", "assistant"])
  557. def test_chat_message_rejects_tool_call_id_on_non_tool_roles(role: str):
  558. with pytest.raises(ValidationError, match="tool_call_id requires tool role"):
  559. ChatMessage(role=role, content="invalid", tool_call_id="call_1")
  560. def test_chat_message_rejects_duplicate_assistant_tool_call_ids():
  561. with pytest.raises(ValidationError, match="duplicate assistant tool-call ID: call_1"):
  562. ChatMessage(
  563. role="assistant",
  564. content="checking twice",
  565. tool_calls=[
  566. ToolCallEvent(
  567. id="call_1",
  568. name="mock_search",
  569. arguments={"query": "first"},
  570. raw_arguments='{"query":"first"}',
  571. ),
  572. ToolCallEvent(
  573. id="call_1",
  574. name="handoff_note",
  575. arguments={"message": "second"},
  576. raw_arguments='{"message":"second"}',
  577. ),
  578. ],
  579. )
  580. class HistoryCapturingChatClient:
  581. def __init__(self) -> None:
  582. self.calls = 0
  583. self.second_call_messages: list[ChatMessage] = []
  584. async def stream_chat(
  585. self,
  586. messages: list[ChatMessage],
  587. tools: list[dict],
  588. params: AgentParams,
  589. tool_choice: dict | None = None,
  590. ) -> AsyncIterator[StreamItem]:
  591. if tools:
  592. yield _event_tool_call_from_tools(tools, messages)
  593. return
  594. self.calls += 1
  595. if self.calls == 1:
  596. yield StreamItem.message_delta("Need event help.")
  597. yield StreamItem.text_event(
  598. ToolCallEvent(
  599. id="call_1",
  600. name="handoff_note",
  601. arguments={},
  602. raw_arguments="{}",
  603. )
  604. )
  605. return
  606. self.second_call_messages = list(messages)
  607. yield StreamItem.message_delta("Final answer.")
  608. @pytest.mark.asyncio
  609. async def test_runtime_appends_event_summary_without_tool_reply_history():
  610. request = DebugRunRequest(
  611. user_message="debug this",
  612. system_prompts=["You are a debugger."],
  613. pre_messages=[],
  614. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  615. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  616. )
  617. client = HistoryCapturingChatClient()
  618. runtime = DebugRuntime(client)
  619. outputs = [message async for message in runtime.run(request)]
  620. assert client.calls == 2
  621. assert [message.role for message in client.second_call_messages] == [
  622. "system",
  623. "system",
  624. "user",
  625. "assistant",
  626. "user",
  627. ]
  628. assert "Available events:" in client.second_call_messages[1].content
  629. assert client.second_call_messages[3].content == "Need event help."
  630. assert not any(message.role == "tool" for message in client.second_call_messages)
  631. assert client.second_call_messages[4].content.startswith("EventAgent results:\n")
  632. assert client.second_call_messages[4].name == "event_agent"
  633. assert outputs[-1] == {"type": "done"}
  634. @pytest.mark.asyncio
  635. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  636. requests: list[httpx.Request] = []
  637. def handler(request: httpx.Request) -> httpx.Response:
  638. requests.append(request)
  639. payload = json.loads(request.content)
  640. assert payload["stream"] is True
  641. assert payload["model"] == "model-x"
  642. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  643. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  644. assert "tool_choice" not in payload
  645. assert payload["temperature"] == 0.3
  646. assert payload["max_tokens"] == 50
  647. assert request.headers["authorization"] == "Bearer test-key"
  648. return httpx.Response(
  649. 200,
  650. content=(
  651. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  652. b"data: [DONE]\n\n"
  653. ),
  654. )
  655. async with httpx.AsyncClient(
  656. transport=httpx.MockTransport(handler),
  657. base_url="https://llm.test/v1",
  658. ) as http_client:
  659. client = OpenAICompatibleChatClient(
  660. api_key="test-key",
  661. base_url="https://llm.test/v1",
  662. default_model="default-model",
  663. request_timeout_seconds=5,
  664. http_client=http_client,
  665. )
  666. items = [
  667. item
  668. async for item in client.stream_chat(
  669. messages=[ChatMessage(role="user", content="hi")],
  670. tools=[
  671. {
  672. "type": "function",
  673. "function": {"name": "handoff_note", "parameters": {}},
  674. }
  675. ],
  676. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  677. )
  678. ]
  679. assert requests[0].url.path == "/v1/chat/completions"
  680. assert [item.content for item in items if item.kind == "message_delta"] == ["hi"]
  681. assert [item.raw_chunk for item in items if item.kind == "raw_chunk"] == [
  682. {"choices": [{"delta": {"content": "hi"}, "finish_reason": None}]}
  683. ]
  684. @pytest.mark.asyncio
  685. async def test_openai_chat_client_serializes_explicit_tool_choice():
  686. captured_payloads: list[dict] = []
  687. forced_choice = {
  688. "type": "function",
  689. "function": {"name": "handoff_note"},
  690. }
  691. def handler(request: httpx.Request) -> httpx.Response:
  692. captured_payloads.append(json.loads(request.content))
  693. return httpx.Response(200, content=b"data: [DONE]\n\n")
  694. async with httpx.AsyncClient(
  695. transport=httpx.MockTransport(handler),
  696. base_url="https://llm.test/v1",
  697. ) as http_client:
  698. client = OpenAICompatibleChatClient(
  699. api_key="",
  700. base_url="https://llm.test/v1",
  701. default_model="provider-default",
  702. request_timeout_seconds=5,
  703. http_client=http_client,
  704. )
  705. [
  706. item
  707. async for item in client.stream_chat(
  708. messages=[ChatMessage(role="user", content="prepare handoff")],
  709. tools=[
  710. {
  711. "type": "function",
  712. "function": {"name": "handoff_note", "parameters": {}},
  713. }
  714. ],
  715. params=AgentParams(model="provider-default"),
  716. tool_choice=forced_choice,
  717. )
  718. ]
  719. assert captured_payloads[0]["tool_choice"] == forced_choice
  720. @pytest.mark.asyncio
  721. async def test_openai_chat_client_flushes_one_provider_tool_call_at_done():
  722. def handler(request: httpx.Request) -> httpx.Response:
  723. return httpx.Response(
  724. 200,
  725. content=(
  726. b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,'
  727. b'"id":"call_1","function":{"name":"mock_search",'
  728. b'"arguments":"{\\"query\\":\\""}}]},"finish_reason":null}]}\n\n'
  729. b'data: {"choices":[{"delta":{"tool_calls":[{"index":0,'
  730. b'"function":{"arguments":"latency docs\\"}"}}]},'
  731. b'"finish_reason":null}]}\n\n'
  732. b"data: [DONE]\n\n"
  733. ),
  734. )
  735. async with httpx.AsyncClient(
  736. transport=httpx.MockTransport(handler),
  737. base_url="https://llm.test/v1",
  738. ) as http_client:
  739. client = OpenAICompatibleChatClient(
  740. api_key="",
  741. base_url="https://llm.test/v1",
  742. default_model="provider-default",
  743. request_timeout_seconds=5,
  744. http_client=http_client,
  745. )
  746. items = [
  747. item
  748. async for item in client.stream_chat(
  749. messages=[ChatMessage(role="user", content="find docs")],
  750. tools=[
  751. {
  752. "type": "function",
  753. "function": {"name": "mock_search", "parameters": {}},
  754. }
  755. ],
  756. params=AgentParams(model="provider-default"),
  757. )
  758. ]
  759. provider_calls = [
  760. item.event for item in items if item.kind == "provider_tool_call"
  761. ]
  762. assert provider_calls == [
  763. ToolCallEvent(
  764. id="call_1",
  765. name="mock_search",
  766. arguments={"query": "latency docs"},
  767. raw_arguments='{"query":"latency docs"}',
  768. )
  769. ]
  770. @pytest.mark.asyncio
  771. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  772. captured_payloads: list[dict] = []
  773. def handler(request: httpx.Request) -> httpx.Response:
  774. captured_payloads.append(json.loads(request.content))
  775. return httpx.Response(
  776. 200,
  777. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  778. )
  779. async with httpx.AsyncClient(
  780. transport=httpx.MockTransport(handler),
  781. base_url="https://llm.test/v1",
  782. ) as http_client:
  783. client = OpenAICompatibleChatClient(
  784. api_key="",
  785. base_url="https://llm.test/v1",
  786. default_model="provider-default",
  787. request_timeout_seconds=5,
  788. http_client=http_client,
  789. )
  790. [
  791. item
  792. async for item in client.stream_chat(
  793. messages=[ChatMessage(role="user", content="hi")],
  794. tools=[],
  795. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  796. )
  797. ]
  798. assert captured_payloads[0]["model"] == "provider-default"
  799. @pytest.mark.asyncio
  800. async def test_openai_chat_client_serializes_provider_tool_transcript():
  801. captured_payloads: list[dict] = []
  802. def handler(request: httpx.Request) -> httpx.Response:
  803. captured_payloads.append(json.loads(request.content))
  804. return httpx.Response(
  805. 200,
  806. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  807. )
  808. async with httpx.AsyncClient(
  809. transport=httpx.MockTransport(handler),
  810. base_url="https://llm.test/v1",
  811. ) as http_client:
  812. client = OpenAICompatibleChatClient(
  813. api_key="",
  814. base_url="https://llm.test/v1",
  815. default_model="provider-default",
  816. request_timeout_seconds=5,
  817. http_client=http_client,
  818. )
  819. [
  820. item
  821. async for item in client.stream_chat(
  822. messages=[
  823. ChatMessage(role="user", content="inspect both"),
  824. ChatMessage(
  825. role="assistant",
  826. content="I will inspect both sources.",
  827. tool_calls=[
  828. ToolCallEvent(
  829. id="call_1",
  830. name="mock_search",
  831. arguments={"query": "latency docs"},
  832. raw_arguments='{"query":"latency docs"}',
  833. ),
  834. ToolCallEvent(
  835. id="call_2",
  836. name="handoff_note",
  837. arguments={"message": "inspect provider behavior"},
  838. raw_arguments='{"message":"inspect provider behavior"}',
  839. ),
  840. ],
  841. ),
  842. ChatMessage(
  843. role="tool",
  844. content='{"results":[]}',
  845. name="mock_search",
  846. tool_call_id="call_1",
  847. ),
  848. ChatMessage(
  849. role="tool",
  850. content='{"message":"handled"}',
  851. name="handoff_note",
  852. tool_call_id="call_2",
  853. ),
  854. ChatMessage(role="user", content="continue"),
  855. ],
  856. tools=[],
  857. params=AgentParams(
  858. model="provider-default",
  859. temperature=0.3,
  860. max_tokens=50,
  861. ),
  862. )
  863. ]
  864. assert captured_payloads[0]["messages"] == [
  865. {"role": "user", "content": "inspect both"},
  866. {
  867. "role": "assistant",
  868. "content": "I will inspect both sources.",
  869. "tool_calls": [
  870. {
  871. "id": "call_1",
  872. "type": "function",
  873. "function": {
  874. "name": "mock_search",
  875. "arguments": '{"query":"latency docs"}',
  876. },
  877. },
  878. {
  879. "id": "call_2",
  880. "type": "function",
  881. "function": {
  882. "name": "handoff_note",
  883. "arguments": '{"message":"inspect provider behavior"}',
  884. },
  885. },
  886. ],
  887. },
  888. {
  889. "role": "tool",
  890. "content": '{"results":[]}',
  891. "tool_call_id": "call_1",
  892. },
  893. {
  894. "role": "tool",
  895. "content": '{"message":"handled"}',
  896. "tool_call_id": "call_2",
  897. },
  898. {"role": "user", "content": "continue"},
  899. ]
  900. async def _assert_tool_transcript_rejected(
  901. messages: list[ChatMessage],
  902. error_match: str,
  903. ) -> None:
  904. network_called = False
  905. def handler(request: httpx.Request) -> httpx.Response:
  906. nonlocal network_called
  907. network_called = True
  908. return httpx.Response(200)
  909. async with httpx.AsyncClient(
  910. transport=httpx.MockTransport(handler),
  911. base_url="https://llm.test/v1",
  912. ) as http_client:
  913. client = OpenAICompatibleChatClient(
  914. api_key="",
  915. base_url="https://llm.test/v1",
  916. default_model="provider-default",
  917. request_timeout_seconds=5,
  918. http_client=http_client,
  919. )
  920. with pytest.raises(ValueError, match=error_match):
  921. [
  922. item
  923. async for item in client.stream_chat(
  924. messages=messages,
  925. tools=[],
  926. params=AgentParams(model="provider-default"),
  927. )
  928. ]
  929. assert network_called is False
  930. @pytest.mark.asyncio
  931. async def test_openai_chat_client_rejects_orphan_tool_reply_before_network():
  932. await _assert_tool_transcript_rejected(
  933. [
  934. ChatMessage(
  935. role="tool",
  936. content="orphan",
  937. tool_call_id="call_1",
  938. )
  939. ],
  940. "orphan tool reply: call_1",
  941. )
  942. @pytest.mark.asyncio
  943. async def test_openai_chat_client_rejects_mismatched_tool_call_id_before_network():
  944. await _assert_tool_transcript_rejected(
  945. [
  946. ChatMessage(
  947. role="assistant",
  948. content="",
  949. tool_calls=[
  950. ToolCallEvent(
  951. id="call_1",
  952. name="mock_search",
  953. arguments={},
  954. raw_arguments="{}",
  955. )
  956. ],
  957. ),
  958. ChatMessage(role="tool", content="wrong", tool_call_id="call_2"),
  959. ],
  960. "mismatched tool_call_id: call_2",
  961. )
  962. @pytest.mark.asyncio
  963. async def test_openai_chat_client_rejects_duplicate_tool_reply_before_network():
  964. await _assert_tool_transcript_rejected(
  965. [
  966. ChatMessage(
  967. role="assistant",
  968. content="",
  969. tool_calls=[
  970. ToolCallEvent(
  971. id="call_1",
  972. name="mock_search",
  973. arguments={},
  974. raw_arguments="{}",
  975. )
  976. ],
  977. ),
  978. ChatMessage(role="tool", content="first", tool_call_id="call_1"),
  979. ChatMessage(role="tool", content="duplicate", tool_call_id="call_1"),
  980. ],
  981. "duplicate tool reply: call_1",
  982. )
  983. @pytest.mark.asyncio
  984. async def test_openai_chat_client_rejects_non_tool_message_with_unresolved_calls():
  985. await _assert_tool_transcript_rejected(
  986. [
  987. ChatMessage(
  988. role="assistant",
  989. content="checking",
  990. tool_calls=[
  991. ToolCallEvent(
  992. id="call_1",
  993. name="mock_search",
  994. arguments={},
  995. raw_arguments="{}",
  996. ),
  997. ToolCallEvent(
  998. id="call_2",
  999. name="handoff_note",
  1000. arguments={},
  1001. raw_arguments="{}",
  1002. ),
  1003. ],
  1004. ),
  1005. ChatMessage(role="tool", content="done", tool_call_id="call_1"),
  1006. ChatMessage(role="user", content="continue too early"),
  1007. ],
  1008. "unresolved tool calls before user message: call_2",
  1009. )
  1010. @pytest.mark.asyncio
  1011. async def test_openai_chat_client_rejects_unfinished_tool_calls_at_end():
  1012. await _assert_tool_transcript_rejected(
  1013. [
  1014. ChatMessage(
  1015. role="assistant",
  1016. content="checking",
  1017. tool_calls=[
  1018. ToolCallEvent(
  1019. id="call_1",
  1020. name="mock_search",
  1021. arguments={},
  1022. raw_arguments="{}",
  1023. )
  1024. ],
  1025. )
  1026. ],
  1027. "unresolved tool calls at end: call_1",
  1028. )
  1029. @pytest.mark.asyncio
  1030. async def test_openai_chat_client_rejects_reused_tool_call_id_across_transcript():
  1031. await _assert_tool_transcript_rejected(
  1032. [
  1033. ChatMessage(
  1034. role="assistant",
  1035. content="first round",
  1036. tool_calls=[
  1037. ToolCallEvent(
  1038. id="call_1",
  1039. name="mock_search",
  1040. arguments={},
  1041. raw_arguments="{}",
  1042. )
  1043. ],
  1044. ),
  1045. ChatMessage(role="tool", content="done", tool_call_id="call_1"),
  1046. ChatMessage(
  1047. role="assistant",
  1048. content="second round",
  1049. tool_calls=[
  1050. ToolCallEvent(
  1051. id="call_1",
  1052. name="handoff_note",
  1053. arguments={},
  1054. raw_arguments="{}",
  1055. )
  1056. ],
  1057. ),
  1058. ],
  1059. "duplicate assistant tool-call ID across transcript: call_1",
  1060. )
  1061. async def _assert_tool_choice_rejected(
  1062. tools: list[dict],
  1063. tool_choice: dict,
  1064. error_match: str,
  1065. ) -> None:
  1066. network_called = False
  1067. def handler(request: httpx.Request) -> httpx.Response:
  1068. nonlocal network_called
  1069. network_called = True
  1070. return httpx.Response(200)
  1071. async with httpx.AsyncClient(
  1072. transport=httpx.MockTransport(handler),
  1073. base_url="https://llm.test/v1",
  1074. ) as http_client:
  1075. client = OpenAICompatibleChatClient(
  1076. api_key="",
  1077. base_url="https://llm.test/v1",
  1078. default_model="provider-default",
  1079. request_timeout_seconds=5,
  1080. http_client=http_client,
  1081. )
  1082. with pytest.raises(ValueError, match=error_match):
  1083. [
  1084. item
  1085. async for item in client.stream_chat(
  1086. messages=[ChatMessage(role="user", content="use a tool")],
  1087. tools=tools,
  1088. params=AgentParams(model="provider-default"),
  1089. tool_choice=tool_choice,
  1090. )
  1091. ]
  1092. assert network_called is False
  1093. @pytest.mark.asyncio
  1094. async def test_openai_chat_client_rejects_forced_choice_without_tools():
  1095. await _assert_tool_choice_rejected(
  1096. tools=[],
  1097. tool_choice={
  1098. "type": "function",
  1099. "function": {"name": "handoff_note"},
  1100. },
  1101. error_match="forced tool choice requires tools",
  1102. )
  1103. @pytest.mark.asyncio
  1104. async def test_openai_chat_client_rejects_forced_choice_for_unknown_tool():
  1105. await _assert_tool_choice_rejected(
  1106. tools=[
  1107. {
  1108. "type": "function",
  1109. "function": {"name": "mock_search", "parameters": {}},
  1110. }
  1111. ],
  1112. tool_choice={
  1113. "type": "function",
  1114. "function": {"name": "handoff_note"},
  1115. },
  1116. error_match="forced tool choice references unknown tool: handoff_note",
  1117. )
  1118. def test_static_pre_message_role_selector_does_not_offer_tool():
  1119. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1120. assert '<option value="tool">tool</option>' not in html
  1121. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  1122. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1123. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1124. assert 'id="tool-handoff-note"' not in html
  1125. assert "#tool-handoff-note" not in js
  1126. assert 'id="tool-list"' in html
  1127. assert '"/api/tools"' in js
  1128. assert "fetch" in js
  1129. def test_static_workspace_snapshot_controls_are_available_outside_agent_config():
  1130. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1131. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  1132. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  1133. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  1134. sidebar_html = html[:chat_dialog_start]
  1135. assert 'id="open-prompt-config"' not in html
  1136. assert '<dialog id="prompt-dialog"' not in html
  1137. assert 'id="workspace-snapshot-name"' in sidebar_html
  1138. assert 'id="saved-workspace-snapshots"' in sidebar_html
  1139. assert 'id="save-workspace-snapshot"' in sidebar_html
  1140. assert 'id="load-workspace-snapshot"' in sidebar_html
  1141. assert 'id="delete-workspace-snapshot"' in sidebar_html
  1142. assert 'id="workspace-snapshot-name"' not in chat_dialog_html
  1143. assert 'id="saved-workspace-snapshots"' not in chat_dialog_html
  1144. assert 'id="save-workspace-snapshot"' not in chat_dialog_html
  1145. assert 'id="system-prompts"' in chat_dialog_html
  1146. assert 'id="pre-messages"' in chat_dialog_html
  1147. def test_static_session_ui_controls_and_replay_panels_are_available():
  1148. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1149. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  1150. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  1151. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  1152. event_dialog_html = html[event_dialog_start:]
  1153. sidebar_html = html[:chat_dialog_start]
  1154. for control_id in [
  1155. "session-title",
  1156. "session-list",
  1157. "new-session",
  1158. "refresh-sessions",
  1159. "load-session",
  1160. "session-status",
  1161. ]:
  1162. assert f'id="{control_id}"' in sidebar_html
  1163. assert f'id="{control_id}"' not in chat_dialog_html
  1164. assert f'id="{control_id}"' not in event_dialog_html
  1165. for replay_id in [
  1166. "audit-replay",
  1167. "audit-count",
  1168. "session-usage-summary",
  1169. "session-usage-turns",
  1170. "session-usage-calls",
  1171. ]:
  1172. assert f'id="{replay_id}"' in html
  1173. def test_static_chat_agent_prompt_is_a_single_sortable_list_with_event_instructions():
  1174. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1175. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1176. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1177. assert 'id="chat-system-prompt"' not in html
  1178. assert 'id="chat-event-prompt-preview"' not in html
  1179. assert 'class="prompt-list stack"' in html
  1180. assert 'class="prompt-item"' in html
  1181. assert 'data-prompt-role="system"' in html
  1182. assert "prompt-type" in html
  1183. assert "function buildAvailableEventsPrompt(" in js
  1184. assert "Available events:" in js
  1185. assert "function updateEventPromptItem(" in js
  1186. assert "function createSystemPrompt(" in js
  1187. assert "function movePromptItem(" in js
  1188. assert 'draggable = true' in js
  1189. assert "dataset.promptRole" in js
  1190. assert "prompt-title" in js
  1191. assert "delete-system-prompt" in js
  1192. assert 'prompt_kind: "event_agent_system"' in js
  1193. assert "system_prompts: collectSystemPrompts()" in js
  1194. assert 'system_prompt: ""' in js
  1195. assert ".prompt-item" in css
  1196. assert ".prompt-item.dragging" in css
  1197. assert ".prompt-meta" in css
  1198. assert ".prompt-type" in css
  1199. assert ".prompt-actions button" in css
  1200. assert "#open-prompt-config" not in js
  1201. assert "promptDialog" not in js
  1202. def test_static_event_prompt_refresh_uses_unified_tool_mode_state_path():
  1203. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1204. render_tools = js[
  1205. js.index("function renderTools(") :
  1206. js.index("function formatRequiredParameters(")
  1207. ]
  1208. set_all_tools = js[
  1209. js.index("function setAllTools(") :
  1210. js.index("function updateToolCount(")
  1211. ]
  1212. restore_snapshot = js[
  1213. js.index("function restoreWorkspaceSnapshot(") :
  1214. js.index("function updateToolModeHelp(")
  1215. ]
  1216. apply_selected_tools = js[
  1217. js.index("function applySelectedTools(") :
  1218. js.index("function initializePromptList(")
  1219. ]
  1220. initialize_prompt_list = js[
  1221. js.index("function initializePromptList(") :
  1222. js.index("function buildPromptItems(")
  1223. ]
  1224. refresh_tool_mode = js[
  1225. js.index("function refreshToolModeState(") :
  1226. js.index("function updateToolModeHelp(")
  1227. ]
  1228. remove_generated_prompts = js[
  1229. js.index("function removeGeneratedEventPromptItems(") :
  1230. js.index("function ensureEventPromptItem(")
  1231. ]
  1232. assert (
  1233. 'toolInvocationMode.addEventListener("change", refreshToolModeState);'
  1234. in js
  1235. )
  1236. assert render_tools.count("refreshToolModeState();") == 3
  1237. assert "updateEventPromptItem(" not in render_tools
  1238. assert "refreshToolModeState();" in set_all_tools
  1239. assert "updateEventPromptItem(" not in set_all_tools
  1240. assert "refreshToolModeState();" in restore_snapshot
  1241. assert "refreshToolModeState();" in apply_selected_tools
  1242. assert "refreshToolModeState();" in initialize_prompt_list
  1243. assert js.count("updateEventPromptItem(") == 2
  1244. assert "removeGeneratedEventPromptItems();" in refresh_tool_mode
  1245. assert "if (!isChatAgentTools)" in refresh_tool_mode
  1246. assert "updateEventPromptItem(availableTools);" in refresh_tool_mode
  1247. assert 'querySelectorAll(".prompt-item")' in remove_generated_prompts
  1248. assert 'item.dataset.promptKind === "event_agent_system"' in remove_generated_prompts
  1249. assert "isGeneratedEventPromptContent(content)" in remove_generated_prompts
  1250. assert "item.remove();" in remove_generated_prompts
  1251. assert 'textarea.readOnly = promptItem.prompt_kind === "event_agent_system"' in js
  1252. def test_static_prompt_restore_discards_generated_event_prompt_derived_state():
  1253. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1254. ordinary = "Keep this custom prompt with an <agent_events> example."
  1255. exact_name_docs = (
  1256. "Use exact event names only, one per line. Do not include parameters."
  1257. )
  1258. assert "function isGeneratedEventPromptContent(" in js
  1259. normalization = js[
  1260. js.index("function normalizePromptItems(") :
  1261. js.index("function buildAvailableEventsPrompt(")
  1262. ]
  1263. result = _run_node_json(
  1264. "\n".join(
  1265. [
  1266. normalization,
  1267. """
  1268. const generated = [
  1269. "You may request EventAgent work using this text protocol.",
  1270. "Available events:",
  1271. "- handoff_note: Handoff a note",
  1272. "First write the user-facing reply normally. If events are needed, append this block after the visible reply:",
  1273. "<agent_events>",
  1274. "handoff_note",
  1275. "</agent_events>",
  1276. "Use exact event names only, one per line. Do not include parameters.",
  1277. ].join("\\n");
  1278. const ordinary = "Keep this custom prompt with an <agent_events> example.";
  1279. const exactNameDocs = "Use exact event names only, one per line. Do not include parameters.";
  1280. console.log(JSON.stringify({
  1281. matches: [
  1282. isGeneratedEventPromptContent(generated),
  1283. isGeneratedEventPromptContent(ordinary),
  1284. isGeneratedEventPromptContent(exactNameDocs),
  1285. ],
  1286. normalized: normalizePromptItems([
  1287. { prompt_kind: "event_agent_system", role: "system", content: generated },
  1288. generated,
  1289. ordinary,
  1290. { prompt_kind: "custom", role: "system", content: exactNameDocs },
  1291. ]),
  1292. empty: normalizePromptItems([]),
  1293. }));
  1294. """,
  1295. ]
  1296. )
  1297. )
  1298. assert result["matches"] == [True, False, False]
  1299. assert result["normalized"] == [
  1300. {"prompt_kind": "custom", "role": "system", "content": ordinary},
  1301. {"prompt_kind": "custom", "role": "system", "content": exact_name_docs},
  1302. ]
  1303. assert result["empty"] == [
  1304. {"prompt_kind": "custom", "role": "system", "content": ""}
  1305. ]
  1306. def test_static_event_prompt_is_excluded_from_chat_agent_tools_payload():
  1307. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1308. generated = "\n".join(
  1309. [
  1310. "You may request EventAgent work using this text protocol.",
  1311. "Available events:",
  1312. "- handoff_note: Handoff a note",
  1313. "<agent_events>",
  1314. "handoff_note",
  1315. "</agent_events>",
  1316. "Use exact event names only, one per line. Do not include parameters.",
  1317. ]
  1318. )
  1319. prompt_collection = js[
  1320. js.index("function buildPromptItems(") :
  1321. js.index("function normalizePromptItems(")
  1322. ]
  1323. generated_matcher = js[
  1324. js.index("function isGeneratedEventPromptContent(") :
  1325. js.index("function buildAvailableEventsPrompt(")
  1326. ]
  1327. result = _run_node_json(
  1328. "\n".join(
  1329. [
  1330. prompt_collection,
  1331. generated_matcher,
  1332. """
  1333. const generated = [
  1334. "You may request EventAgent work using this text protocol.",
  1335. "Available events:",
  1336. "- handoff_note: Handoff a note",
  1337. "<agent_events>",
  1338. "handoff_note",
  1339. "</agent_events>",
  1340. "Use exact event names only, one per line. Do not include parameters.",
  1341. ].join("\\n");
  1342. function promptItem(promptKind, content) {
  1343. return {
  1344. dataset: { promptKind, promptRole: "system" },
  1345. querySelector() {
  1346. return { value: content };
  1347. },
  1348. };
  1349. }
  1350. const systemPrompts = {
  1351. querySelectorAll() {
  1352. return [
  1353. promptItem("custom", "ordinary custom"),
  1354. promptItem("event_agent_system", generated),
  1355. promptItem("custom", generated),
  1356. ];
  1357. },
  1358. };
  1359. const toolInvocationMode = { value: "chat_agent_tools" };
  1360. const chatAgentTools = collectSystemPrompts();
  1361. toolInvocationMode.value = "dual_agent";
  1362. const dualAgent = collectSystemPrompts();
  1363. console.log(JSON.stringify({ chatAgentTools, dualAgent }));
  1364. """,
  1365. ]
  1366. )
  1367. )
  1368. assert result["chatAgentTools"] == ["ordinary custom"]
  1369. assert result["dualAgent"] == ["ordinary custom", generated, generated]
  1370. def test_static_tool_mode_disables_only_event_agent_model_settings_group():
  1371. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1372. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1373. model_settings_start = html.index('id="event-agent-model-settings"')
  1374. shared_settings_start = html.index('id="max-event-loops"')
  1375. model_settings_html = html[model_settings_start:shared_settings_start]
  1376. refresh_tool_mode = js[
  1377. js.index("function refreshToolModeState(") :
  1378. js.index("function updateToolModeHelp(")
  1379. ]
  1380. for control_id in [
  1381. "event-model",
  1382. "event-temperature",
  1383. "event-max-tokens",
  1384. "event-system-prompt",
  1385. "event-thinking-disabled",
  1386. "event-enable-search",
  1387. "event-forced-search",
  1388. ]:
  1389. assert f'id="{control_id}"' in model_settings_html
  1390. for control_id in [
  1391. "max-event-loops",
  1392. "max-parallel-events",
  1393. "batch-timeout-seconds",
  1394. ]:
  1395. assert f'id="{control_id}"' not in model_settings_html
  1396. assert 'document.querySelector("#event-agent-model-settings")' in js
  1397. assert '.querySelectorAll("input, textarea, select, button")' in refresh_tool_mode
  1398. assert "control.disabled = isChatAgentTools;" in refresh_tool_mode
  1399. def test_static_app_script_is_versioned_and_click_binding_is_guarded():
  1400. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1401. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1402. assert '<script src="/static/app.js?v=' in html
  1403. assert "function bindClick(" in js
  1404. assert 'bindClick("#open-chat-config-panel", openChatConfig)' in js
  1405. assert 'bindClick("#open-event-config-panel", openEventConfig)' in js
  1406. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  1407. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1408. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1409. assert '<dialog id="chat-config-dialog"' in html
  1410. assert '<dialog id="event-config-dialog"' in html
  1411. assert html.count('id="open-chat-config-panel"') == 1
  1412. assert html.count('id="open-event-config-panel"') == 1
  1413. assert 'id="open-chat-config"' not in html
  1414. assert 'id="open-event-config"' not in html
  1415. assert '#open-chat-config"' not in js
  1416. assert '#open-event-config"' not in js
  1417. assert '#open-chat-config-panel"' in js
  1418. assert '#open-event-config-panel"' in js
  1419. assert 'id="close-chat-config"' in html
  1420. assert 'id="close-event-config"' in html
  1421. assert "chatConfigDialog.showModal()" in js
  1422. assert "eventConfigDialog.showModal()" in js
  1423. assert "chatConfigDialog.close()" in js
  1424. assert "eventConfigDialog.close()" in js
  1425. for control_id in [
  1426. "model",
  1427. "temperature",
  1428. "max-tokens",
  1429. "chat-thinking-disabled",
  1430. "chat-enable-search",
  1431. "chat-forced-search",
  1432. "event-model",
  1433. "event-temperature",
  1434. "event-max-tokens",
  1435. "event-system-prompt",
  1436. "event-thinking-disabled",
  1437. "event-enable-search",
  1438. "event-forced-search",
  1439. ]:
  1440. assert f'id="{control_id}"' in html
  1441. assert 'extra_body: buildExtraBody("chat")' in js
  1442. assert 'extra_body: buildExtraBody("event")' in js
  1443. assert 'system_prompt: ""' in js
  1444. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  1445. def test_static_tool_mode_and_batch_controls_explain_active_configuration():
  1446. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1447. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1448. assert 'id="tool-invocation-mode"' in html
  1449. assert '<option value="dual_agent" selected>' in html
  1450. assert '<option value="chat_agent_tools">' in html
  1451. assert 'id="tool-mode-help"' in html
  1452. assert 'id="max-parallel-events"' in html
  1453. assert 'value="4"' in html
  1454. assert 'id="batch-timeout-seconds"' in html
  1455. assert 'value="15"' in html
  1456. assert "missing-argument fallback" in js
  1457. assert "EventAgent model, temperature, max tokens, system prompt, and extra body are inactive" in js
  1458. assert "enabled tools, loop budget, batch concurrency, and timeout remain active" in js
  1459. assert "function updateToolModeHelp()" in js
  1460. def test_static_tool_mode_config_roundtrips_request_snapshot_and_session_restore():
  1461. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1462. build_snapshot = js[
  1463. js.index("function buildWorkspaceSnapshot()") :
  1464. js.index("function restoreWorkspaceSnapshot(")
  1465. ]
  1466. restore_snapshot = js[
  1467. js.index("function restoreWorkspaceSnapshot(") :
  1468. js.index("function buildExtraBody(")
  1469. ]
  1470. build_request = js[
  1471. js.index("function buildRequest(") :
  1472. js.index("function selectedTools(")
  1473. ]
  1474. load_replay = js[
  1475. js.index("async function loadSessionReplay(") :
  1476. js.index("function setSessionStatus(")
  1477. ]
  1478. create_session = js[
  1479. js.index("async function createSession()") :
  1480. js.index("async function loadSelectedSession()")
  1481. ]
  1482. for source in [build_snapshot, build_request]:
  1483. assert 'tool_invocation_mode: document.querySelector("#tool-invocation-mode").value' in source
  1484. assert 'max_parallel_events: Number(document.querySelector("#max-parallel-events").value)' in source
  1485. assert 'batch_timeout_seconds: Number(document.querySelector("#batch-timeout-seconds").value)' in source
  1486. assert 'snapshot.tool_invocation_mode || "dual_agent"' in restore_snapshot
  1487. assert 'eventAgent.max_parallel_events ?? 4' in restore_snapshot
  1488. assert 'eventAgent.batch_timeout_seconds ?? 15' in restore_snapshot
  1489. assert "refreshToolModeState();" in restore_snapshot
  1490. assert '`/api/sessions/${sessionId}`' in load_replay
  1491. assert "const [session, messages, audit, usage] = await Promise.all([" in load_replay
  1492. assert "restoreWorkspaceSnapshot(session.config || {});" in load_replay
  1493. assert "config: buildWorkspaceSnapshot()" in create_session
  1494. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  1495. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1496. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1497. assert 'id="tool-count"' in html
  1498. assert 'id="select-all-tools"' in html
  1499. assert 'id="clear-tools"' in html
  1500. assert "tool-card" in js
  1501. assert "tool-description" in js
  1502. assert "tool-required" in js
  1503. assert "function updateToolCount()" in js
  1504. def test_static_app_handles_audit_messages():
  1505. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1506. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1507. assert 'message.type === "audit"' in js
  1508. assert "appendAuditEntry(message)" in js
  1509. assert 'appendLog("audit"' not in js
  1510. assert "function renderAuditDetail(" in js
  1511. assert "chat_agent_request" in js
  1512. assert "event_agent_response" in js
  1513. assert "chat_message_stream_started" in js
  1514. assert "chat_message_stream_finished" in js
  1515. assert ".audit-event" in css
  1516. assert ".audit-detail" in css
  1517. def test_static_audit_replay_uses_event_stream_and_detail_panel():
  1518. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1519. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1520. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1521. assert '<link rel="stylesheet" href="/static/styles.css?v=' in html
  1522. assert "tool-mode-session-restore" in html
  1523. assert 'id="audit-dialog"' in html
  1524. assert 'id="open-audit-dialog"' in html
  1525. assert 'id="close-audit-dialog"' in html
  1526. assert 'id="audit-summary"' in html
  1527. assert 'id="audit-replay" class="audit-stream"' in html
  1528. assert 'id="audit-detail"' in html
  1529. assert "auditDialog.showModal()" in js
  1530. assert "auditDialog.close()" in js
  1531. assert "auditEntryKey(entry)" in js
  1532. assert "selectAuditEntry(key)" in js
  1533. assert 'meta.className = "audit-detail-meta"' in js
  1534. assert 'appendMetaField(meta, "Since User Message"' in js
  1535. assert "auditRelativeTime(entry)" in js
  1536. assert 'const list = document.createElement("ul")' in js
  1537. assert "appendKeyValueSection(auditDetail, \"Model Parameters\"" in js
  1538. assert "appendRepliesSection(auditDetail, details.replies)" in js
  1539. assert "appendRawChunksSection(auditDetail, \"Raw LLM Chunks\"" in js
  1540. assert "appendRawModelChunksSection(auditDetail, details.raw_model_chunks)" in js
  1541. assert "Enabled This Round" in js
  1542. assert "Configured Events" in js
  1543. assert "details.configured_events" in js
  1544. assert "enabled this round" in js
  1545. assert ".audit-modal" in css
  1546. assert ".audit-modal-body" in css
  1547. assert ".audit-modal-body section + section" in css
  1548. assert ".audit-detail-title" in css
  1549. assert ".detail-tags code" in css
  1550. assert ".audit-detail-meta span" not in css
  1551. assert ".detail-tags span" not in css
  1552. assert "display: block" in _css_rule(css, ".audit-detail")
  1553. assert "display: grid" not in _css_rule(css, ".audit-detail")
  1554. assert "display: block" in _css_rule(css, ".audit-detail-header")
  1555. assert "display: grid" not in _css_rule(css, ".audit-detail-header")
  1556. assert "display: inline-flex" in _css_rule(css, ".audit-detail-meta div")
  1557. assert ".audit-marker::before" in css
  1558. assert ".audit-event.is-selected" in css
  1559. def test_static_layout_keeps_controls_and_composer_fixed_with_scrollable_panes():
  1560. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1561. assert "height: calc(100vh - 56px)" in css
  1562. assert ".layout" in css and "overflow: hidden" in css
  1563. assert ".controls" in css and "overflow: auto" in css
  1564. assert ".workspace {\n display: grid;\n grid-template-rows: minmax(0, 1fr) auto auto;" in css
  1565. assert ".workspace-body" in css and "overflow: hidden" in css
  1566. assert ".messages" in css and "overflow: auto" in css
  1567. assert ".audit-stream" in css and "overflow: auto" in css
  1568. def test_static_app_shows_wait_state_and_immediate_user_echo():
  1569. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  1570. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1571. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  1572. assert 'id="run-button"' in html
  1573. assert 'const runButton = document.querySelector("#run-button")' in js
  1574. assert 'appendLog("user", submittedMessage)' in js
  1575. assert 'statusEl.textContent = "Waiting for first token"' in js
  1576. assert "function startElapsedTimer()" in js
  1577. assert "function stopElapsedTimer()" in js
  1578. assert "function setRunState(" in js
  1579. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  1580. assert "hasBackendRoundStats && firstTokenAt" in js
  1581. assert ".user" in css
  1582. def test_static_app_reuses_websocket_for_session_turns():
  1583. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1584. assert "function isSocketOpen()" in js
  1585. assert "socket.send(JSON.stringify({ type: \"user_message\"" in js
  1586. assert "session_id: currentSessionId || undefined" in js
  1587. assert "message.session_id" in js
  1588. assert 'message.type === "turn_completed"' in js
  1589. assert 'message.type === "done"' in js
  1590. def test_static_app_loads_session_replay_and_usage():
  1591. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1592. create_session = js[
  1593. js.index("async function createSession()") :
  1594. js.index("async function loadSelectedSession()")
  1595. ]
  1596. load_session = js[
  1597. js.index("async function loadSelectedSession()") :
  1598. js.index("async function loadSessionReplay(")
  1599. ]
  1600. assert "function loadSessions(" in js
  1601. assert "function createSession(" in js
  1602. assert "function setSessionStatus(" in js
  1603. assert '"Refreshing sessions"' in js
  1604. assert '"Creating session"' in js
  1605. assert '"Session created"' in js
  1606. assert 'sessionStatus.textContent = message' in js
  1607. assert "function loadSessionReplay(" in js
  1608. assert 'fetchJson("/api/sessions")' in js
  1609. assert 'method: "POST"' in js
  1610. assert '`/api/sessions/${sessionId}/messages`' in js
  1611. assert '`/api/sessions/${sessionId}/audit`' in js
  1612. assert '`/api/sessions/${sessionId}/usage`' in js
  1613. assert "function renderAuditReplay(" in js
  1614. assert "function renderSessionUsage(" in js
  1615. assert "session.turn_wall_time_ms ?? session.elapsed_ms" in js
  1616. assert "turn.turn_wall_time_ms ?? turn.elapsed_ms" in js
  1617. assert "call.mode" in js
  1618. assert "call.agent" in js
  1619. assert "call.call_kind" in js
  1620. assert "call.used_fallback" in js
  1621. assert "call.tool_latency_ms" in js
  1622. assert "sessionUsageSummary" in js
  1623. assert "Finish current turn before switching sessions" in js
  1624. assert "await loadSessionReplay(session.id, { preserveStatus: true });" in create_session
  1625. assert "await loadSessionReplay(sessionId);" in load_session
  1626. def test_static_session_replay_ignores_superseded_success():
  1627. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1628. result = _run_load_session_replay_scenario(
  1629. """
  1630. currentSessionId = "old";
  1631. const oldLoad = loadSessionReplay("old");
  1632. currentSessionId = "new";
  1633. const newLoad = loadSessionReplay("new");
  1634. resolveReplay("new");
  1635. await newLoad;
  1636. resolveReplay("old");
  1637. await oldLoad;
  1638. console.log(JSON.stringify({
  1639. ...mutations,
  1640. title: sessionTitle.value,
  1641. selected: sessionList.value,
  1642. }));
  1643. """
  1644. )
  1645. assert result == {
  1646. "workspace": ["new"],
  1647. "transcript": ["new"],
  1648. "audit": ["new"],
  1649. "usage": ["new"],
  1650. "status": ["Session loaded"],
  1651. "title": "new title",
  1652. "selected": "new",
  1653. }
  1654. assert "let sessionReplayLoadToken = 0;" in js
  1655. def test_static_session_replay_ignores_superseded_failure_status():
  1656. result = _run_load_session_replay_scenario(
  1657. """
  1658. currentSessionId = "old";
  1659. const oldLoad = loadSessionReplay("old");
  1660. currentSessionId = "new";
  1661. const newLoad = loadSessionReplay("new");
  1662. resolveReplay("new");
  1663. await newLoad;
  1664. pending.get("/api/sessions/old").reject(new Error("stale failure"));
  1665. await oldLoad;
  1666. console.log(JSON.stringify(mutations.status));
  1667. """
  1668. )
  1669. assert result == ["Session loaded"]
  1670. def test_static_session_replay_rejects_stale_invocation_before_token_advance():
  1671. result = _run_load_session_replay_scenario(
  1672. """
  1673. currentSessionId = "new";
  1674. const newLoad = loadSessionReplay("new");
  1675. const tokenAfterNew = sessionReplayLoadToken;
  1676. const oldLoad = loadSessionReplay("old");
  1677. const oldResult = await Promise.race([
  1678. oldLoad.then(() => "returned"),
  1679. new Promise((resolve) => setTimeout(() => resolve("pending"), 0)),
  1680. ]);
  1681. const tokenAfterOld = sessionReplayLoadToken;
  1682. const oldFetchStarted = pending.has("/api/sessions/old");
  1683. resolveReplay("new");
  1684. await newLoad;
  1685. console.log(JSON.stringify({
  1686. oldResult,
  1687. tokenAfterNew,
  1688. tokenAfterOld,
  1689. oldFetchStarted,
  1690. mutations,
  1691. title: sessionTitle.value,
  1692. selected: sessionList.value,
  1693. }));
  1694. """
  1695. )
  1696. assert result == {
  1697. "oldResult": "returned",
  1698. "tokenAfterNew": 1,
  1699. "tokenAfterOld": 1,
  1700. "oldFetchStarted": False,
  1701. "mutations": {
  1702. "workspace": ["new"],
  1703. "transcript": ["new"],
  1704. "audit": ["new"],
  1705. "usage": ["new"],
  1706. "status": ["Session loaded"],
  1707. },
  1708. "title": "new title",
  1709. "selected": "new",
  1710. }
  1711. def test_static_replay_hides_whitespace_assistant_tool_protocol_records():
  1712. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1713. render_replay = js[
  1714. js.index("function renderReplayMessages(") :
  1715. js.index("function appendAuditEntry(")
  1716. ]
  1717. result = _run_node_json(
  1718. "\n".join(
  1719. [
  1720. """
  1721. let activeAssistant = null;
  1722. const messagesEl = {
  1723. children: [],
  1724. scrollHeight: 0,
  1725. scrollTop: 0,
  1726. set textContent(value) {
  1727. if (value === "") {
  1728. this.children = [];
  1729. }
  1730. },
  1731. append(item) {
  1732. this.children.push(item);
  1733. },
  1734. };
  1735. const document = {
  1736. createElement() {
  1737. return { className: "", textContent: "" };
  1738. },
  1739. };
  1740. function appendLog(kind, content) {
  1741. messagesEl.append({ className: `message ${kind}`, textContent: content });
  1742. }
  1743. """,
  1744. render_replay,
  1745. """
  1746. renderReplayMessages([
  1747. { role: "assistant", content: " \\n\\t", tool_calls: [{ id: "call-1" }] },
  1748. { role: "assistant", content: "visible", tool_calls: [] },
  1749. ]);
  1750. console.log(JSON.stringify(messagesEl.children.map((item) => item.textContent)));
  1751. """,
  1752. ]
  1753. )
  1754. )
  1755. assert result == ["visible"]
  1756. def test_static_session_switch_guard_uses_active_turn_not_open_socket():
  1757. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1758. create_session = js[js.index("async function createSession()") : js.index("async function loadSelectedSession()")]
  1759. load_session = js[js.index("async function loadSelectedSession()") : js.index("async function loadSessionReplay(")]
  1760. assert "function hasActiveTurn()" in js
  1761. assert "turnActive = isRunning" in js
  1762. assert "if (hasActiveTurn())" in create_session
  1763. assert "if (hasActiveTurn())" in load_session
  1764. assert "if (isSocketOpen())" not in create_session
  1765. assert "if (isSocketOpen())" not in load_session
  1766. assert "closeSocket();" in create_session
  1767. assert "closeSocket();" in load_session
  1768. assert "const activeSocket = socket" in js
  1769. assert "if (socket !== activeSocket)" in js
  1770. def test_static_workspace_snapshot_uses_stable_storage_hooks():
  1771. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1772. assert "agent-lab.workspace-snapshots.v1" in js
  1773. assert "agent-lab.prompt-sets.v1" in js
  1774. assert "function saveWorkspaceSnapshot()" in js
  1775. assert "function loadWorkspaceSnapshot()" in js
  1776. assert "function deleteWorkspaceSnapshot()" in js
  1777. assert "function buildWorkspaceSnapshot()" in js
  1778. assert "prompt_items: buildPromptItems()" in js
  1779. assert "enabled_tools: selectedTools()" in js
  1780. assert "extra_body: buildExtraBody(\"chat\")" in js
  1781. assert "extra_body: buildExtraBody(\"event\")" in js
  1782. def test_static_app_handles_backend_round_stats_messages():
  1783. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  1784. assert 'message.type === "round_stats"' in js
  1785. assert "function updateRoundStats(" in js
  1786. assert "#stat-ttft" in js
  1787. assert "#stat-elapsed" in js
  1788. @pytest.mark.asyncio
  1789. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  1790. captured_payloads: list[dict] = []
  1791. def handler(request: httpx.Request) -> httpx.Response:
  1792. captured_payloads.append(json.loads(request.content))
  1793. return httpx.Response(
  1794. 200,
  1795. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  1796. )
  1797. async with httpx.AsyncClient(
  1798. transport=httpx.MockTransport(handler),
  1799. base_url="https://llm.test/v1",
  1800. ) as http_client:
  1801. client = OpenAICompatibleChatClient(
  1802. api_key="",
  1803. base_url="https://llm.test/v1",
  1804. default_model="provider-default",
  1805. request_timeout_seconds=5,
  1806. include_usage=False,
  1807. http_client=http_client,
  1808. )
  1809. [
  1810. item
  1811. async for item in client.stream_chat(
  1812. messages=[ChatMessage(role="user", content="hi")],
  1813. tools=[],
  1814. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  1815. )
  1816. ]
  1817. assert "stream_options" not in captured_payloads[0]
  1818. @pytest.mark.asyncio
  1819. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  1820. captured_payloads: list[dict] = []
  1821. def handler(request: httpx.Request) -> httpx.Response:
  1822. captured_payloads.append(json.loads(request.content))
  1823. return httpx.Response(
  1824. 200,
  1825. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  1826. )
  1827. async with httpx.AsyncClient(
  1828. transport=httpx.MockTransport(handler),
  1829. base_url="https://llm.test/v1",
  1830. ) as http_client:
  1831. client = OpenAICompatibleChatClient(
  1832. api_key="",
  1833. base_url="https://llm.test/v1",
  1834. default_model="provider-default",
  1835. request_timeout_seconds=5,
  1836. http_client=http_client,
  1837. )
  1838. [
  1839. item
  1840. async for item in client.stream_chat(
  1841. messages=[ChatMessage(role="user", content="hi")],
  1842. tools=[],
  1843. params=AgentParams(
  1844. model="provider-default",
  1845. temperature=0.3,
  1846. max_tokens=50,
  1847. extra_body={
  1848. "thinking": {"type": "disabled"},
  1849. "enable_search": False,
  1850. "search_options": {"forced_search": False},
  1851. },
  1852. ),
  1853. )
  1854. ]
  1855. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  1856. assert captured_payloads[0]["enable_search"] is False
  1857. assert captured_payloads[0]["search_options"] == {"forced_search": False}
  1858. @pytest.mark.asyncio
  1859. @pytest.mark.parametrize(
  1860. ("reserved_key", "override_value"),
  1861. [
  1862. ("model", "overridden-model"),
  1863. ("messages", []),
  1864. ("tools", []),
  1865. (
  1866. "tool_choice",
  1867. {"type": "function", "function": {"name": "other_tool"}},
  1868. ),
  1869. ("stream", False),
  1870. ("stream_options", {"include_usage": False}),
  1871. ("temperature", 1.0),
  1872. ("max_tokens", 1),
  1873. ],
  1874. )
  1875. async def test_openai_chat_client_rejects_reserved_extra_body_fields_before_network(
  1876. reserved_key: str,
  1877. override_value: object,
  1878. ):
  1879. network_called = False
  1880. def handler(request: httpx.Request) -> httpx.Response:
  1881. nonlocal network_called
  1882. network_called = True
  1883. return httpx.Response(200)
  1884. async with httpx.AsyncClient(
  1885. transport=httpx.MockTransport(handler),
  1886. base_url="https://llm.test/v1",
  1887. ) as http_client:
  1888. client = OpenAICompatibleChatClient(
  1889. api_key="",
  1890. base_url="https://llm.test/v1",
  1891. default_model="provider-default",
  1892. request_timeout_seconds=5,
  1893. http_client=http_client,
  1894. )
  1895. with pytest.raises(
  1896. ValueError,
  1897. match=f"extra_body contains reserved field: {reserved_key}",
  1898. ):
  1899. [
  1900. item
  1901. async for item in client.stream_chat(
  1902. messages=[ChatMessage(role="user", content="hi")],
  1903. tools=[],
  1904. params=AgentParams(extra_body={reserved_key: override_value}),
  1905. )
  1906. ]
  1907. assert network_called is False