test_websocket_api.py 88 KB

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