test_websocket_api.py 101 KB

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