conversation-session-built-in-subagent-model-overrides.test.ts 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  1. import { readFile, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { parse as parseYaml } from "yaml";
  4. import { decodeCustomModelValue, encodeCustomModelValue } from "@zcode/shared";
  5. import {
  6. TID_CHAT_MODEL_SELECT_ITEM,
  7. TID_CHAT_MODEL_SELECT_GROUP,
  8. TID_CHAT_MODEL_SELECT_TRIGGER,
  9. TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM,
  10. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  11. TID_SETTINGS_BACK_BUTTON,
  12. TID_SETTINGS_PAGE,
  13. TID_SETTINGS_SECTION_NAV,
  14. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  15. TID_SUBAGENT_ROW,
  16. TID_TASK_SETTINGS_BUTTON,
  17. TID_V4_SUBAGENT_OPEN_SIDE_PANE,
  18. testId,
  19. } from "@zcode/shared/test-ids";
  20. import {
  21. DEFAULT_WORKSPACE,
  22. clearAppData,
  23. clickTestIdByDom,
  24. readAgentsState,
  25. waitForTestIdByDom,
  26. waitForWorkspaceApp,
  27. } from "#e2e/helpers/desktop-app";
  28. import {
  29. assertUpstreamRequestCapture,
  30. assertUpstreamThoughtLevelCapture,
  31. } from "#e2e/helpers/upstream-capture";
  32. import { reloadElectronSessionSafely } from "#e2e/helpers/e2e-electron-reload";
  33. import type {
  34. E2ENetworkCaptureArtifact,
  35. E2ENetworkCaptureRecord,
  36. } from "#e2e/helpers/network-capture-proxy";
  37. import {
  38. UPSTREAM_ALTERNATE_MODEL,
  39. UPSTREAM_ALTERNATE_PROVIDER_ID,
  40. UPSTREAM_ALTERNATE_PROVIDER_NAME,
  41. UPSTREAM_MODEL,
  42. UPSTREAM_PROVIDER_ID,
  43. } from "#e2e/helpers/upstream-provider";
  44. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  45. import {
  46. restartIntoWorkspacePreservingProfile,
  47. seedPersistedModelSelection,
  48. } from "#e2e/helpers/model-provider-restart";
  49. import { waitForProviderConfigPolling } from "#e2e/helpers/provider-config-polling";
  50. import { sel } from "#e2e/helpers/selectors";
  51. import { waitForToolCallBlockByToolName } from "#e2e/helpers/conversation-session-tool";
  52. import {
  53. getV4PaneSnapshot,
  54. prepareV4ConversationE2E,
  55. selectV4TaskById,
  56. sendV4PromptAndWaitAccepted,
  57. waitForV4AssistantMessageContaining,
  58. waitForV4ConversationState,
  59. waitForV4Pane,
  60. } from "#e2e/helpers/v4-conversation";
  61. const OVERRIDE_MODEL_VALUE = encodeCustomModelValue(
  62. UPSTREAM_ALTERNATE_PROVIDER_ID,
  63. UPSTREAM_ALTERNATE_MODEL,
  64. );
  65. const PRIMARY_MODEL_VALUE = encodeCustomModelValue(UPSTREAM_PROVIDER_ID, UPSTREAM_MODEL);
  66. const CUSTOM_AGENT_NAME = "e2e-reasoning-reviewer";
  67. const CUSTOM_AGENT_PATH = join(resolveE2EStorageRoot(), "agents", `${CUSTOM_AGENT_NAME}.md`);
  68. const SUBAGENT_FORM_SELECTOR = `form:has(input[type="text"]):has(${sel(TID_CHAT_MODEL_SELECT_TRIGGER)})`;
  69. const INVALID_EFFORT = "invalid-e2e";
  70. // Bug 根因:child 与 parent 档位相同时,忽略 profile 并错误继承 parent 的回归也会通过。
  71. // 三类 child 都用 high,parent 与目标模型默认均为 max,确保继承或默认回退都会被请求断言捕获。
  72. const GENERAL_EFFORT = "high";
  73. const EXPLORE_EFFORT = "high";
  74. const CUSTOM_EFFORT = "high";
  75. const PARENT_EFFORT = "max";
  76. const GENERAL_PARENT_MARKER = "E2E_BUILT_IN_SUBAGENT_GENERAL_PARENT";
  77. const GENERAL_CHILD_MARKER = "E2E_BUILT_IN_SUBAGENT_GENERAL_CHILD";
  78. const GENERAL_CHILD_REPLY_TOKEN = "E2E_BUILT_IN_SUBAGENT_GENERAL_CHILD_OK";
  79. const GENERAL_FINAL_TOKEN = "built-in-general-subagent-model-override-done";
  80. const EXPLORE_PARENT_MARKER = "E2E_BUILT_IN_SUBAGENT_EXPLORE_PARENT";
  81. const EXPLORE_CHILD_MARKER = "E2E_BUILT_IN_SUBAGENT_EXPLORE_CHILD";
  82. const EXPLORE_CHILD_REPLY_TOKEN = "E2E_BUILT_IN_SUBAGENT_EXPLORE_CHILD_OK";
  83. const EXPLORE_FINAL_TOKEN = "built-in-explore-subagent-model-override-done";
  84. const CUSTOM_PARENT_MARKER = "E2E_CUSTOM_SUBAGENT_REASONING_PARENT";
  85. const CUSTOM_CHILD_MARKER = "E2E_CUSTOM_SUBAGENT_REASONING_CHILD";
  86. const CUSTOM_CHILD_REPLY_TOKEN = "E2E_CUSTOM_SUBAGENT_REASONING_CHILD_OK";
  87. const CUSTOM_FINAL_TOKEN = "custom-subagent-reasoning-override-done";
  88. describe("Subagent 模型与 reasoning effort 覆盖 E2E", () => {
  89. after(async () => {
  90. await browser.electron.restoreAllMocks();
  91. await clearAppData();
  92. });
  93. it("I20: Settings 保存 builtin/custom effort 后冷启动进入 child provider 请求", async function () {
  94. this.timeout(300000);
  95. await prepareV4ConversationE2E({ skipProvider: true });
  96. await setRendererLocale("en-US");
  97. await configureSubagentReasoningOverrides();
  98. await seedPersistedModelSelection({
  99. modelId: UPSTREAM_MODEL,
  100. providerId: UPSTREAM_PROVIDER_ID,
  101. reasoningLevel: PARENT_EFFORT,
  102. });
  103. // Todo 88:冷启动前模拟真实旧存储,不能只测 UI 已写好的新版结构。
  104. const state = await readAgentsState();
  105. const { builtInModelSelectionOverrides: _newSelections, ...rest } = state;
  106. await writeFile(
  107. join(resolveE2EStorageRoot(), "v2", "agents-state.json"),
  108. JSON.stringify({
  109. ...rest,
  110. builtInModelOverrides: {
  111. "general-purpose": OVERRIDE_MODEL_VALUE,
  112. Explore: OVERRIDE_MODEL_VALUE,
  113. },
  114. builtInThoughtLevelOverrides: {
  115. "general-purpose": GENERAL_EFFORT,
  116. Explore: EXPLORE_EFFORT,
  117. },
  118. }),
  119. );
  120. const customProfile = await readFile(CUSTOM_AGENT_PATH, "utf8");
  121. expect(customProfile).not.toContain("modelSelection:");
  122. await restartIntoWorkspacePreservingProfile();
  123. expect(await readFile(CUSTOM_AGENT_PATH, "utf8")).toBe(customProfile);
  124. await prepareV4ConversationE2E({ skipProvider: true });
  125. await waitForProviderConfigPolling();
  126. await runSubagentScenario({
  127. childMarker: GENERAL_CHILD_MARKER,
  128. childReplyToken: GENERAL_CHILD_REPLY_TOKEN,
  129. effort: GENERAL_EFFORT,
  130. finalToken: GENERAL_FINAL_TOKEN,
  131. parentMarker: GENERAL_PARENT_MARKER,
  132. subagentType: "general-purpose",
  133. });
  134. await assertInitialChildModelMarker("live");
  135. const sessionId = (await getV4PaneSnapshot()).sessionId;
  136. if (!sessionId || sessionId === "draft") {
  137. throw new Error(`内置 subagent 模型 case 没有真实 sessionId: ${sessionId ?? "null"}`);
  138. }
  139. await reloadAppAndRestoreV4Session(sessionId);
  140. await assertInitialChildModelMarker("cold");
  141. const exploreChildRecord = await runSubagentScenario({
  142. childMarker: EXPLORE_CHILD_MARKER,
  143. childReplyToken: EXPLORE_CHILD_REPLY_TOKEN,
  144. effort: EXPLORE_EFFORT,
  145. finalToken: EXPLORE_FINAL_TOKEN,
  146. parentMarker: EXPLORE_PARENT_MARKER,
  147. subagentType: "Explore",
  148. });
  149. expect(readToolNamesFromCapture(exploreChildRecord.requestJson)).toEqual([
  150. "Bash",
  151. "Read",
  152. "TodoWrite",
  153. "WebFetch",
  154. "RespondToCoordinator",
  155. ]);
  156. await runSubagentScenario({
  157. childMarker: CUSTOM_CHILD_MARKER,
  158. childReplyToken: CUSTOM_CHILD_REPLY_TOKEN,
  159. effort: CUSTOM_EFFORT,
  160. finalToken: CUSTOM_FINAL_TOKEN,
  161. parentMarker: CUSTOM_PARENT_MARKER,
  162. subagentType: CUSTOM_AGENT_NAME,
  163. });
  164. });
  165. });
  166. async function configureSubagentReasoningOverrides() {
  167. expect(await readAgentsState()).toMatchObject({
  168. builtInModelSelectionOverrides: {
  169. Explore: {
  170. providerId: UPSTREAM_ALTERNATE_PROVIDER_ID,
  171. modelId: UPSTREAM_ALTERNATE_MODEL,
  172. options: { reasoningLevel: INVALID_EFFORT },
  173. },
  174. "general-purpose": {
  175. providerId: UPSTREAM_PROVIDER_ID,
  176. modelId: UPSTREAM_MODEL,
  177. },
  178. },
  179. });
  180. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON, {
  181. timeout: 15000,
  182. timeoutMsg: "没有找到设置入口按钮",
  183. });
  184. await waitForTestIdByDom(TID_SETTINGS_PAGE, {
  185. timeout: 15000,
  186. timeoutMsg: "设置页没有渲染",
  187. });
  188. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "subagents"), {
  189. timeout: 15000,
  190. timeoutMsg: "设置页没有出现 subagents 分区入口",
  191. });
  192. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "general-purpose"));
  193. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, "Explore"));
  194. await waitForTestIdByDom(testId(TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER, "general-purpose"));
  195. await waitForTestIdByDom(testId(TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER, "Explore"));
  196. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME));
  197. await expectBuiltInModelValues({
  198. Explore: OVERRIDE_MODEL_VALUE,
  199. "general-purpose": PRIMARY_MODEL_VALUE,
  200. });
  201. await waitForExploreInvalidEffortError(
  202. "Select a reasoning effort supported by this model",
  203. "英文",
  204. );
  205. await setRendererLocale("zh-CN");
  206. await waitForExploreInvalidEffortError("请选择当前模型支持的推理档位", "中文");
  207. await setRendererLocale("en-US");
  208. await waitForExploreInvalidEffortError(
  209. "Select a reasoning effort supported by this model",
  210. "英文恢复",
  211. );
  212. await selectThoughtLevelInScope(sel(testId(TID_SUBAGENT_ROW, "Explore")), EXPLORE_EFFORT);
  213. await waitForAgentsState(
  214. (state) => readBuiltInReasoningLevel(state, "Explore") === EXPLORE_EFFORT,
  215. "Explore 合法 effort 没有写入 agents-state.json",
  216. );
  217. await selectModelInScope(sel(testId(TID_SUBAGENT_ROW, "general-purpose")), OVERRIDE_MODEL_VALUE);
  218. await waitForAgentsState(
  219. (state) =>
  220. readBuiltInModelValue(state, "general-purpose") === OVERRIDE_MODEL_VALUE &&
  221. readBuiltInReasoningLevel(state, "general-purpose") === "max",
  222. "general-purpose 主动切换模型后没有使用目标最高档位",
  223. );
  224. await selectThoughtLevelInScope(sel(testId(TID_SUBAGENT_ROW, "general-purpose")), GENERAL_EFFORT);
  225. await waitForAgentsState(
  226. (state) => readBuiltInReasoningLevel(state, "general-purpose") === GENERAL_EFFORT,
  227. "general-purpose effort 没有写入 agents-state.json",
  228. );
  229. expect(await readAgentsState()).toMatchObject({
  230. builtInModelSelectionOverrides: {
  231. Explore: {
  232. providerId: UPSTREAM_ALTERNATE_PROVIDER_ID,
  233. modelId: UPSTREAM_ALTERNATE_MODEL,
  234. options: { reasoningLevel: EXPLORE_EFFORT },
  235. },
  236. "general-purpose": {
  237. providerId: UPSTREAM_ALTERNATE_PROVIDER_ID,
  238. modelId: UPSTREAM_ALTERNATE_MODEL,
  239. options: { reasoningLevel: GENERAL_EFFORT },
  240. },
  241. },
  242. });
  243. await configureCustomSubagentReasoningOverride();
  244. await assertSettingsLayoutAcrossThemes();
  245. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  246. timeout: 15000,
  247. timeoutMsg: "设置页返回按钮没有出现",
  248. });
  249. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 30000);
  250. }
  251. async function setRendererLocale(locale: "en-US" | "zh-CN") {
  252. const changed = await browser.execute((nextLocale) => {
  253. const actions = (
  254. window as typeof window & {
  255. __testActions?: Record<string, unknown>;
  256. }
  257. ).__testActions;
  258. const setLocale = actions?.setLocale;
  259. if (typeof setLocale !== "function") return false;
  260. (setLocale as (value: string) => void)(nextLocale);
  261. return true;
  262. }, locale);
  263. if (!changed) {
  264. throw new Error(`I20 缺少 renderer locale test action: ${locale}`);
  265. }
  266. await browser.waitUntil(
  267. async () =>
  268. browser.execute((expectedLocale) => {
  269. const actions = (
  270. window as typeof window & {
  271. __testActions?: Record<string, unknown>;
  272. }
  273. ).__testActions;
  274. const getLocale = actions?.getLocale;
  275. return typeof getLocale === "function" && getLocale() === expectedLocale;
  276. }, locale),
  277. {
  278. timeout: 15_000,
  279. timeoutMsg: `I20 renderer locale 没有切换到 ${locale}`,
  280. },
  281. );
  282. }
  283. async function waitForExploreInvalidEffortError(expectedText: string, localeLabel: string) {
  284. await browser.waitUntil(
  285. async () =>
  286. (await $(sel(testId(TID_SUBAGENT_ROW, "Explore"))).getText()).includes(expectedText),
  287. {
  288. timeout: 15_000,
  289. timeoutMsg: `workspace catalog 就绪后 Explore 没有显示${localeLabel}无效 effort 错误`,
  290. },
  291. );
  292. }
  293. async function configureCustomSubagentReasoningOverride() {
  294. const initialMarkdown = await readFile(CUSTOM_AGENT_PATH, "utf8");
  295. expect(initialMarkdown).toContain(`model: ${OVERRIDE_MODEL_VALUE}`);
  296. expect(initialMarkdown).toContain(`thoughtLevel: ${INVALID_EFFORT}`);
  297. await openCustomAgentForm();
  298. const form = $(SUBAGENT_FORM_SELECTOR);
  299. expect(await form.getText()).toMatch(
  300. /Select a reasoning effort supported by this model|请选择当前模型支持的推理档位/u,
  301. );
  302. // 非法历史档位会禁用保存按钮;强行点击只会触发 WebDriver 拦截,不能证明产品拒绝保存。
  303. expect(await form.$('button[type="submit"]').isEnabled()).toBe(false);
  304. expect(await form.isDisplayed()).toBe(true);
  305. expect(await readFile(CUSTOM_AGENT_PATH, "utf8")).toBe(initialMarkdown);
  306. await selectThoughtLevelInScope(SUBAGENT_FORM_SELECTOR, EXPLORE_EFFORT);
  307. await saveCustomAgentForm();
  308. await waitForCustomMarkdown((content) => {
  309. const selection = readCustomAgentSelection(content);
  310. return selection?.model === OVERRIDE_MODEL_VALUE && selection.reasoningLevel === EXPLORE_EFFORT;
  311. }, "custom 合法 effort 没有写入 Markdown");
  312. await openCustomAgentForm();
  313. await selectModelInScope(SUBAGENT_FORM_SELECTOR, PRIMARY_MODEL_VALUE);
  314. await assertThoughtOptionsAndSelectInScope(
  315. SUBAGENT_FORM_SELECTOR,
  316. ["off", "low", "high", "max"],
  317. [],
  318. "high",
  319. );
  320. await saveCustomAgentForm();
  321. // Todo 88:主动切换先选最高档 max,随后用户显式改成 high 并保存。
  322. const defaultEffortMarkdown = await waitForCustomMarkdown((content) => {
  323. const selection = readCustomAgentSelection(content);
  324. return selection?.model === PRIMARY_MODEL_VALUE && selection.reasoningLevel === "high";
  325. }, "custom 重新确认默认 effort 后没有写入 Markdown");
  326. expect(defaultEffortMarkdown).toContain("thoughtLevel: high");
  327. expect(defaultEffortMarkdown).not.toContain("modelSelection:");
  328. await openCustomAgentForm();
  329. await selectModelInScope(SUBAGENT_FORM_SELECTOR, OVERRIDE_MODEL_VALUE);
  330. await assertThoughtOptionsAndSelectInScope(
  331. SUBAGENT_FORM_SELECTOR,
  332. ["off", "low", "high", "max"],
  333. [],
  334. CUSTOM_EFFORT,
  335. );
  336. await saveCustomAgentForm();
  337. const finalMarkdown = await waitForCustomMarkdown((content) => {
  338. const selection = readCustomAgentSelection(content);
  339. return selection?.model === OVERRIDE_MODEL_VALUE && selection.reasoningLevel === CUSTOM_EFFORT;
  340. }, "custom 最终 model + effort 没有写入 Markdown");
  341. expect(finalMarkdown).toContain(`thoughtLevel: ${CUSTOM_EFFORT}`);
  342. expect(finalMarkdown).not.toContain("modelSelection:");
  343. }
  344. async function openCustomAgentForm() {
  345. const rowTestId = testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME);
  346. await browser.waitUntil(
  347. async () =>
  348. browser.execute((currentRowTestId) => {
  349. const row = document.querySelector<HTMLElement>(`[data-testid="${currentRowTestId}"]`);
  350. // 保存后的刷新会保留行,但暂时移除 role 和编辑事件;存在不代表已经可编辑。
  351. if (!row || row.getAttribute("role") !== "button") return false;
  352. // 编辑入口由整行承载;行内带 title 的按钮是删除,不能按 button[title] 定位。
  353. row.click();
  354. return true;
  355. }, rowTestId),
  356. { timeout: 15000, timeoutMsg: "custom subagent 行不可编辑" },
  357. );
  358. await $(SUBAGENT_FORM_SELECTOR).waitForDisplayed({
  359. timeout: 15000,
  360. timeoutMsg: "custom subagent 编辑表单没有打开",
  361. });
  362. }
  363. async function saveCustomAgentForm() {
  364. await $(SUBAGENT_FORM_SELECTOR).$('button[type="submit"]').click();
  365. await browser.waitUntil(async () => !(await $(SUBAGENT_FORM_SELECTOR).isExisting()), {
  366. timeout: 15000,
  367. timeoutMsg: "custom subagent 保存后表单没有关闭",
  368. });
  369. await waitForTestIdByDom(testId(TID_SUBAGENT_ROW, CUSTOM_AGENT_NAME));
  370. }
  371. async function selectModelInScope(scope: string, model: string) {
  372. const decodedModel = decodeCustomModelValue(model);
  373. if (!decodedModel) {
  374. throw new Error(`E2E 仅支持选择 custom provider 模型: ${model}`);
  375. }
  376. const itemTestId = testId(TID_CHAT_MODEL_SELECT_ITEM, model);
  377. const groupTestId = testId(
  378. TID_CHAT_MODEL_SELECT_GROUP,
  379. `registry-provider:${decodedModel.providerId}`,
  380. );
  381. const trigger = $(scope).$(sel(TID_CHAT_MODEL_SELECT_TRIGGER));
  382. await trigger.waitForClickable({ timeout: 15000 });
  383. await trigger.click();
  384. try {
  385. await browser.waitUntil(
  386. () =>
  387. browser.execute(
  388. (currentItemTestId, currentGroupTestId) =>
  389. Boolean(
  390. document.querySelector(`[data-testid="${currentItemTestId}"]`) ||
  391. document.querySelector(`[data-testid="${currentGroupTestId}"]`),
  392. ),
  393. itemTestId,
  394. groupTestId,
  395. ),
  396. { timeout: 15000, timeoutMsg: `模型菜单没有出现 ${model}` },
  397. );
  398. } catch (error) {
  399. const candidates = await browser.execute(
  400. (itemPrefix, groupPrefix) =>
  401. Array.from(document.querySelectorAll<HTMLElement>("[data-testid]"))
  402. .filter((element) => {
  403. const value = element.dataset.testid ?? "";
  404. return value.startsWith(itemPrefix) || value.startsWith(groupPrefix);
  405. })
  406. .map((element) => ({
  407. testId: element.dataset.testid ?? "",
  408. text: element.innerText.replace(/\s+/gu, " ").trim(),
  409. })),
  410. testId(TID_CHAT_MODEL_SELECT_ITEM, ""),
  411. testId(TID_CHAT_MODEL_SELECT_GROUP, ""),
  412. );
  413. throw new Error(`模型菜单没有出现 ${model},当前候选: ${JSON.stringify(candidates)}`, {
  414. cause: error,
  415. });
  416. }
  417. const itemVisible = await browser.execute(
  418. (currentItemTestId) => Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  419. itemTestId,
  420. );
  421. if (!itemVisible) {
  422. await browser.execute((currentGroupTestId) => {
  423. const group = document.querySelector<HTMLElement>(`[data-testid="${currentGroupTestId}"]`);
  424. if (!group) {
  425. return;
  426. }
  427. group.focus();
  428. for (const eventName of ["pointerenter", "mouseenter", "mousemove"] as const) {
  429. group.dispatchEvent(
  430. new MouseEvent(eventName, {
  431. bubbles: true,
  432. cancelable: true,
  433. view: window,
  434. }),
  435. );
  436. }
  437. group.click();
  438. }, groupTestId);
  439. }
  440. await browser.waitUntil(
  441. () =>
  442. browser.execute(
  443. (currentItemTestId) =>
  444. Boolean(document.querySelector(`[data-testid="${currentItemTestId}"]`)),
  445. itemTestId,
  446. ),
  447. { timeout: 15000, timeoutMsg: `模型菜单没有出现 ${model}` },
  448. );
  449. await browser.execute((currentItemTestId) => {
  450. document.querySelector<HTMLElement>(`[data-testid="${currentItemTestId}"]`)?.click();
  451. }, itemTestId);
  452. await browser.waitUntil(
  453. async () => (await trigger.getAttribute("data-model-current-value")) === model,
  454. { timeout: 15000, timeoutMsg: `模型控件没有切换到 ${model}` },
  455. );
  456. }
  457. async function selectThoughtLevelInScope(scope: string, thoughtLevel: string) {
  458. let selected = false;
  459. for (let attempt = 0; attempt < 3; attempt += 1) {
  460. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  461. await trigger.waitForClickable({
  462. timeout: 15000,
  463. timeoutMsg: `reasoning effort 控件没有出现: ${scope}`,
  464. });
  465. await trigger.click();
  466. try {
  467. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  468. await item.waitForClickable({ timeout: 3000 });
  469. await item.click();
  470. selected = true;
  471. break;
  472. } catch {
  473. // Radix 菜单可能在 portal 重挂载时吞掉一次打开动作,关闭后有限重试。
  474. await browser.keys("Escape");
  475. }
  476. }
  477. if (!selected) {
  478. throw new Error(`reasoning effort 菜单没有出现 ${thoughtLevel}`);
  479. }
  480. const expectedLabels: Record<string, string[]> = {
  481. high: ["High", "高"],
  482. low: ["Low", "低"],
  483. max: ["Max", "最高"],
  484. };
  485. await browser.waitUntil(
  486. async () => {
  487. const currentTrigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  488. const label = await currentTrigger.getAttribute("aria-label");
  489. return (expectedLabels[thoughtLevel] ?? [thoughtLevel]).includes(label ?? "");
  490. },
  491. {
  492. timeout: 15000,
  493. timeoutMsg: `reasoning effort 控件没有切换到 ${thoughtLevel}`,
  494. },
  495. );
  496. }
  497. async function assertThoughtOptionsAndSelectInScope(
  498. scope: string,
  499. expected: string[],
  500. excluded: string[],
  501. thoughtLevel: string,
  502. ) {
  503. const trigger = $(scope).$(sel(TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER));
  504. await trigger.waitForClickable({ timeout: 15000 });
  505. await trigger.click();
  506. for (const level of expected) {
  507. await $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, level))).waitForDisplayed({
  508. timeout: 15000,
  509. timeoutMsg: `目标模型没有展示 reasoning effort ${level}`,
  510. });
  511. }
  512. for (const level of excluded) {
  513. expect(await $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, level))).isExisting()).toBe(
  514. false,
  515. );
  516. }
  517. const item = $(sel(testId(TID_CHAT_THOUGHT_LEVEL_SELECT_ITEM, thoughtLevel)));
  518. await item.waitForClickable({ timeout: 15000 });
  519. await item.click();
  520. }
  521. async function expectBuiltInModelValues(expected: Record<string, string>) {
  522. const values = await browser.execute(
  523. (entries, triggerPrefix) =>
  524. Object.fromEntries(
  525. entries.map(([name]) => {
  526. const element = document.querySelector<HTMLElement>(
  527. `[data-testid="${triggerPrefix}-${name}"]`,
  528. );
  529. return [name, element?.dataset.modelCurrentValue ?? null];
  530. }),
  531. ),
  532. Object.entries(expected),
  533. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  534. );
  535. expect(values).toEqual(expected);
  536. }
  537. async function waitForAgentsState(
  538. predicate: (state: Record<string, unknown>) => boolean,
  539. timeoutMsg: string,
  540. ) {
  541. await browser.waitUntil(async () => predicate(await readAgentsState()), {
  542. timeout: 15000,
  543. timeoutMsg,
  544. });
  545. }
  546. function readBuiltInSelection(state: Record<string, unknown>, agentName: string) {
  547. const map = state.builtInModelSelectionOverrides;
  548. if (!map || typeof map !== "object" || Array.isArray(map)) {
  549. return null;
  550. }
  551. const value = (map as Record<string, unknown>)[agentName];
  552. return value && typeof value === "object" && !Array.isArray(value)
  553. ? (value as Record<string, unknown>)
  554. : null;
  555. }
  556. function readBuiltInModelValue(state: Record<string, unknown>, agentName: string) {
  557. const selection = readBuiltInSelection(state, agentName);
  558. return typeof selection?.providerId === "string" && typeof selection.modelId === "string"
  559. ? encodeCustomModelValue(selection.providerId, selection.modelId)
  560. : null;
  561. }
  562. function readBuiltInReasoningLevel(state: Record<string, unknown>, agentName: string) {
  563. const options = readBuiltInSelection(state, agentName)?.options;
  564. if (!options || typeof options !== "object" || Array.isArray(options)) return null;
  565. const reasoningLevel = (options as Record<string, unknown>).reasoningLevel;
  566. return typeof reasoningLevel === "string" ? reasoningLevel : null;
  567. }
  568. async function waitForCustomMarkdown(predicate: (content: string) => boolean, timeoutMsg: string) {
  569. let latest = "";
  570. await browser.waitUntil(
  571. async () => {
  572. latest = await readFile(CUSTOM_AGENT_PATH, "utf8");
  573. return predicate(latest);
  574. },
  575. { timeout: 15000, timeoutMsg },
  576. );
  577. return latest;
  578. }
  579. function parseCustomAgentFrontmatter(content: string): Record<string, unknown> {
  580. const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u);
  581. if (!match?.[1]) {
  582. return {};
  583. }
  584. const parsed = parseYaml(match[1]) as unknown;
  585. return parsed && typeof parsed === "object" && !Array.isArray(parsed)
  586. ? (parsed as Record<string, unknown>)
  587. : {};
  588. }
  589. function readCustomAgentSelection(content: string) {
  590. const frontmatter = parseCustomAgentFrontmatter(content);
  591. const value = frontmatter.model;
  592. if (typeof value !== "string") return null;
  593. const separator = value.indexOf("/");
  594. const decoded = decodeCustomModelValue(value);
  595. const providerId = decoded?.providerId ?? value.slice(0, separator);
  596. const modelId = decoded?.modelName ?? value.slice(separator + 1);
  597. if (!providerId || !modelId) return null;
  598. return {
  599. model: encodeCustomModelValue(providerId, modelId),
  600. reasoningLevel:
  601. typeof frontmatter.thoughtLevel === "string" ? frontmatter.thoughtLevel : undefined,
  602. };
  603. }
  604. async function assertSettingsLayoutAcrossThemes() {
  605. await assertSubagentControlRowsFit();
  606. try {
  607. await setRendererViewport(390, 844);
  608. for (const theme of ["zai-light", "zai-dark"] as const) {
  609. await setSettingsTheme(theme);
  610. await assertSubagentControlRowsFit();
  611. }
  612. } finally {
  613. await clearRendererViewport();
  614. }
  615. }
  616. async function assertSubagentControlRowsFit() {
  617. const result = await browser.execute(
  618. (rowPrefix, modelPrefix, thoughtTrigger, names) =>
  619. names.map((name) => {
  620. const row = document.querySelector<HTMLElement>(`[data-testid="${rowPrefix}-${name}"]`);
  621. const model = row?.querySelector<HTMLElement>(`[data-testid="${modelPrefix}-${name}"]`);
  622. const thought = row?.querySelector<HTMLElement>(`[data-testid="${thoughtTrigger}"]`);
  623. const modelRect = model?.getBoundingClientRect();
  624. const thoughtRect = thought?.getBoundingClientRect();
  625. const overlaps = Boolean(
  626. modelRect &&
  627. thoughtRect &&
  628. modelRect.left < thoughtRect.right &&
  629. modelRect.right > thoughtRect.left &&
  630. modelRect.top < thoughtRect.bottom &&
  631. modelRect.bottom > thoughtRect.top,
  632. );
  633. return {
  634. hasModel: Boolean(modelRect),
  635. hasThought: Boolean(thoughtRect),
  636. horizontalOverflow: Boolean(row && row.scrollWidth > row.clientWidth + 1),
  637. name,
  638. overlaps,
  639. };
  640. }),
  641. TID_SUBAGENT_ROW,
  642. TID_SUBAGENT_BUILT_IN_MODEL_TRIGGER,
  643. TID_CHAT_THOUGHT_LEVEL_SELECT_TRIGGER,
  644. ["general-purpose", "Explore"],
  645. );
  646. expect(result).toEqual([
  647. {
  648. hasModel: true,
  649. hasThought: true,
  650. horizontalOverflow: false,
  651. name: "general-purpose",
  652. overlaps: false,
  653. },
  654. {
  655. hasModel: true,
  656. hasThought: true,
  657. horizontalOverflow: false,
  658. name: "Explore",
  659. overlaps: false,
  660. },
  661. ]);
  662. }
  663. async function setSettingsTheme(theme: "zai-light" | "zai-dark") {
  664. const changed = await browser.execute((nextTheme) => {
  665. const actions = (window as typeof window & { __testActions?: Record<string, unknown> })
  666. .__testActions;
  667. const setTheme = actions?.setTheme;
  668. if (typeof setTheme !== "function") {
  669. return false;
  670. }
  671. (setTheme as (value: string) => void)(nextTheme);
  672. return true;
  673. }, theme);
  674. expect(changed).toBe(true);
  675. await browser.pause(100);
  676. }
  677. async function setRendererViewport(width: number, height: number) {
  678. await sendRendererEmulationCommand("Emulation.setDeviceMetricsOverride", {
  679. deviceScaleFactor: 1,
  680. height,
  681. mobile: false,
  682. width,
  683. });
  684. await browser.waitUntil(
  685. async () => browser.execute((expectedWidth) => window.innerWidth === expectedWidth, width),
  686. { timeout: 10000, timeoutMsg: `renderer viewport 没有收敛到 ${width}px` },
  687. );
  688. }
  689. async function clearRendererViewport() {
  690. await sendRendererEmulationCommand("Emulation.clearDeviceMetricsOverride");
  691. }
  692. async function sendRendererEmulationCommand(method: string, params: Record<string, unknown> = {}) {
  693. const sent = await browser.electron.execute(
  694. async (electron, command, commandParams) => {
  695. const window = electron.BrowserWindow.getAllWindows().find(
  696. (candidate) => !candidate.isDestroyed() && candidate.isVisible(),
  697. );
  698. if (!window) return false;
  699. const devtools = window.webContents.debugger;
  700. if (!devtools.isAttached()) devtools.attach("1.3");
  701. await devtools.sendCommand(command, commandParams);
  702. return true;
  703. },
  704. method,
  705. params,
  706. );
  707. expect(sent).toBe(true);
  708. }
  709. async function assertInitialChildModelMarker(stage: "cold" | "live") {
  710. const agentBlock = await waitForToolCallBlockByToolName("Agent", 30000);
  711. const sidePaneAction = await $(`[data-testid="${agentBlock.testId}"]`).$(
  712. `[data-testid^="${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-"]`,
  713. );
  714. await sidePaneAction.waitForDisplayed({
  715. timeout: 15000,
  716. timeoutMsg: `${stage} child 没有右侧会话入口`,
  717. });
  718. const actionTestId = await sidePaneAction.getAttribute("data-testid");
  719. const childSessionId = actionTestId?.slice(`${TID_V4_SUBAGENT_OPEN_SIDE_PANE}-`.length);
  720. if (!actionTestId || !childSessionId) {
  721. throw new Error(`${stage} child 会话入口缺少 session id`);
  722. }
  723. // Bug 原因:Agent 摘要完成或冷恢复后会重挂载,首次查询得到的 WebDriver element
  724. // 可能在 click 前已经失效。每次按稳定 test id 重新定位,并以目标 child pane 可见
  725. // 作为完成条件,避免把“没有打开侧栏”误报成“冷恢复丢失模型 marker”。
  726. for (let attempt = 0; attempt < 3; attempt += 1) {
  727. await browser.execute(
  728. (blockTestId, actionId) => {
  729. document
  730. .querySelector<HTMLElement>(`[data-testid="${blockTestId}"] [data-testid="${actionId}"]`)
  731. ?.click();
  732. },
  733. agentBlock.testId,
  734. actionTestId,
  735. );
  736. try {
  737. await browser.waitUntil(
  738. () =>
  739. browser.execute(
  740. (expectedChildSessionId) =>
  741. Array.from(
  742. document.querySelectorAll<HTMLElement>(
  743. `[data-session-id="${expectedChildSessionId}"]`,
  744. ),
  745. ).some((pane) => pane.offsetParent !== null),
  746. childSessionId,
  747. ),
  748. {
  749. timeout: 10000,
  750. timeoutMsg: `${stage} child conversation 没有在右侧面板打开`,
  751. },
  752. );
  753. break;
  754. } catch (error) {
  755. if (attempt === 2) throw error;
  756. }
  757. }
  758. const expectedZh = `正在使用 ${UPSTREAM_ALTERNATE_PROVIDER_NAME}/${UPSTREAM_ALTERNATE_MODEL}`;
  759. const expectedEn = `Using ${UPSTREAM_ALTERNATE_PROVIDER_NAME}/${UPSTREAM_ALTERNATE_MODEL}`;
  760. // cold pane 默认恢复到底部;timeline 使用虚拟列表时,首轮顶部 marker 可能尚未挂载。
  761. // 断言的是持久化后的首个模型事实,因此先滚到目标 child timeline 顶部再读取 DOM。
  762. await browser.execute((expectedChildSessionId) => {
  763. const pane = Array.from(
  764. document.querySelectorAll<HTMLElement>(`[data-session-id="${expectedChildSessionId}"]`),
  765. ).find((candidate) => candidate.offsetParent !== null);
  766. pane?.querySelector<HTMLElement>('[data-v4-timeline-scroll="true"]')?.scrollTo({ top: 0 });
  767. }, childSessionId);
  768. try {
  769. await browser.waitUntil(
  770. async () => {
  771. const markers = await readVisibleModelMarkers();
  772. return markers.some(
  773. (marker) =>
  774. (marker.text === expectedZh || marker.text === expectedEn) && !marker.hasSwitchArrow,
  775. );
  776. },
  777. {
  778. timeout: 30000,
  779. timeoutMsg: `${stage} child 没有以无切换箭头的精简文案展示初始模型 ${UPSTREAM_ALTERNATE_MODEL}`,
  780. },
  781. );
  782. } catch (error) {
  783. const markers = await readVisibleModelMarkers();
  784. throw new Error(`${String(error)}; visibleModelMarkers=${JSON.stringify(markers)}`);
  785. }
  786. }
  787. async function readVisibleModelMarkers() {
  788. return browser.execute(() =>
  789. Array.from(document.querySelectorAll<HTMLElement>('[data-marker-type="modelChange"]')).map(
  790. (marker) => ({
  791. hasSwitchArrow: marker.querySelector(".lucide-arrow-right-left") !== null,
  792. sessionId: marker.closest<HTMLElement>("[data-session-id]")?.dataset.sessionId ?? null,
  793. text: (marker.innerText ?? "").trim(),
  794. }),
  795. ),
  796. );
  797. }
  798. async function reloadAppAndRestoreV4Session(sessionId: string) {
  799. // Bug 原因:raw reloadSession 只重建 WebDriver 协议 session,旧 Electron/Host/CLI
  800. // 可能仍在内存中;使用进程退出屏障才能证明 marker 来自 transcript cold hydration。
  801. await reloadElectronSessionSafely(browser);
  802. await waitForWorkspaceApp(DEFAULT_WORKSPACE, 60000);
  803. await selectV4TaskById(sessionId);
  804. await waitForV4Pane(
  805. (snapshot) => snapshot.sessionId === sessionId,
  806. `CLI cold restart 后没有恢复 session ${sessionId}`,
  807. 60000,
  808. );
  809. }
  810. async function runSubagentScenario(input: {
  811. childMarker: string;
  812. childReplyToken: string;
  813. effort: string;
  814. finalToken: string;
  815. parentMarker: string;
  816. subagentType: string;
  817. }) {
  818. const marker = `${input.parentMarker}_${Date.now()}`;
  819. const prompt =
  820. `${marker}: Use the Agent tool with subagent_type "${input.subagentType}". ` +
  821. `Ask it to reply with exactly "${input.childReplyToken}". ` +
  822. `After the subagent returns, reply with exactly "${input.finalToken}" and no other text.`;
  823. await sendV4PromptAndWaitAccepted(
  824. prompt,
  825. marker,
  826. `${input.subagentType} 首发没有被 composer 接受`,
  827. );
  828. const childRecord = await waitForChildSubagentRequestCapture(input.childMarker);
  829. assertUpstreamRequestCapture(childRecord, {
  830. expectedText: input.childMarker,
  831. model: UPSTREAM_ALTERNATE_MODEL,
  832. });
  833. assertUpstreamThoughtLevelCapture(childRecord, input.effort);
  834. const parentContinuationRecord = await waitForParentContinuationRequestCapture(
  835. input.childReplyToken,
  836. );
  837. assertUpstreamRequestCapture(parentContinuationRecord, {
  838. expectedText: input.childReplyToken,
  839. model: UPSTREAM_MODEL,
  840. });
  841. assertUpstreamThoughtLevelCapture(parentContinuationRecord, PARENT_EFFORT);
  842. await waitForV4AssistantMessageContaining(input.finalToken);
  843. await waitForV4ConversationState(
  844. (snapshot) => snapshot.state === "idle" && snapshot.queueCount === 0,
  845. `${input.subagentType} 模型覆盖 case 完成后没有回到 idle`,
  846. 90000,
  847. );
  848. const agentBlock = await waitForToolCallBlockByToolName("Agent");
  849. expect(agentBlock.status).toBe("completed");
  850. return childRecord;
  851. }
  852. async function waitForChildSubagentRequestCapture(childMarker: string) {
  853. let latestArtifact: E2ENetworkCaptureArtifact | null = null;
  854. try {
  855. await browser.waitUntil(
  856. async () => {
  857. latestArtifact = await readCaptureArtifact();
  858. return Boolean(findChildSubagentRequest(latestArtifact, childMarker));
  859. },
  860. {
  861. timeout: 30000,
  862. timeoutMsg: `没有捕获到内置 subagent child 请求: ${childMarker}`,
  863. },
  864. );
  865. } catch (error) {
  866. throw new Error(
  867. `没有捕获到内置 subagent child 请求\n${JSON.stringify(
  868. summarizeRequestsContaining(latestArtifact, childMarker),
  869. null,
  870. 2,
  871. )}`,
  872. { cause: error },
  873. );
  874. }
  875. const record = findChildSubagentRequest(latestArtifact, childMarker);
  876. if (!record) {
  877. throw new Error("内置 subagent child 请求在等待完成后仍不存在");
  878. }
  879. return record;
  880. }
  881. async function waitForParentContinuationRequestCapture(childReplyToken: string) {
  882. let latestArtifact: E2ENetworkCaptureArtifact | null = null;
  883. try {
  884. await browser.waitUntil(
  885. async () => {
  886. latestArtifact = await readCaptureArtifact();
  887. return Boolean(findParentContinuationRequest(latestArtifact, childReplyToken));
  888. },
  889. {
  890. timeout: 30000,
  891. timeoutMsg: `没有捕获到 parent continuation 请求: ${childReplyToken}`,
  892. },
  893. );
  894. } catch (error) {
  895. throw new Error(
  896. `没有捕获到 parent continuation 请求\n${JSON.stringify(
  897. summarizeRequestsContaining(latestArtifact, childReplyToken),
  898. null,
  899. 2,
  900. )}`,
  901. { cause: error },
  902. );
  903. }
  904. const record = findParentContinuationRequest(latestArtifact, childReplyToken);
  905. if (!record) {
  906. throw new Error("parent continuation 请求在等待完成后仍不存在");
  907. }
  908. return record;
  909. }
  910. async function readCaptureArtifact(): Promise<E2ENetworkCaptureArtifact | null> {
  911. const capturePath = process.env.E2E_PROVIDER_CAPTURE_PATH?.trim();
  912. if (!capturePath) {
  913. return null;
  914. }
  915. try {
  916. return JSON.parse(await readFile(capturePath, "utf-8")) as E2ENetworkCaptureArtifact;
  917. } catch (error) {
  918. if (error instanceof Error && "code" in error && error.code === "ENOENT") {
  919. return null;
  920. }
  921. throw error;
  922. }
  923. }
  924. function findChildSubagentRequest(artifact: E2ENetworkCaptureArtifact | null, childMarker: string) {
  925. return (
  926. artifact?.records.find(
  927. (record) =>
  928. isUpstreamMessageRequest(record) &&
  929. record.status === "complete" &&
  930. captureContainsText(record.requestJson, childMarker) &&
  931. readModelFromCapture(record.requestJson) === UPSTREAM_ALTERNATE_MODEL,
  932. ) ?? null
  933. );
  934. }
  935. function findParentContinuationRequest(
  936. artifact: E2ENetworkCaptureArtifact | null,
  937. childReplyToken: string,
  938. ) {
  939. return (
  940. artifact?.records.findLast(
  941. (record) =>
  942. isUpstreamMessageRequest(record) &&
  943. record.status === "complete" &&
  944. latestUserToolResultContainsText(record.requestJson, childReplyToken) &&
  945. readModelFromCapture(record.requestJson) === UPSTREAM_MODEL,
  946. ) ?? null
  947. );
  948. }
  949. function latestUserToolResultContainsText(requestJson: unknown, expectedText: string) {
  950. if (!requestJson || typeof requestJson !== "object") {
  951. return false;
  952. }
  953. const messages = (requestJson as { messages?: unknown }).messages;
  954. if (!Array.isArray(messages)) {
  955. return false;
  956. }
  957. for (let index = messages.length - 1; index >= 0; index -= 1) {
  958. const message = messages[index];
  959. if (!message || typeof message !== "object") {
  960. continue;
  961. }
  962. if ((message as { role?: unknown }).role !== "user") {
  963. continue;
  964. }
  965. const content = (message as { content?: unknown }).content;
  966. // Bug 原因:父输入本身也包含 child 回复 token,只搜整段 request 会把 compact
  967. // 或首轮请求当成 continuation;这里要求 token 真正来自最新 user/tool_result。
  968. return (
  969. Array.isArray(content) &&
  970. content.some(
  971. (part) =>
  972. part !== null &&
  973. typeof part === "object" &&
  974. (part as { type?: unknown }).type === "tool_result" &&
  975. captureContainsText(part, expectedText),
  976. )
  977. );
  978. }
  979. return false;
  980. }
  981. function summarizeRequestsContaining(
  982. artifact: E2ENetworkCaptureArtifact | null,
  983. expectedText: string,
  984. ) {
  985. return {
  986. records:
  987. artifact?.records
  988. .filter((record) => captureContainsText(record.requestJson, expectedText))
  989. .map((record) => ({
  990. model: readModelFromCapture(record.requestJson),
  991. path: record.path,
  992. status: record.status,
  993. statusCode: record.statusCode,
  994. tools: readToolNamesFromCapture(record.requestJson),
  995. })) ?? [],
  996. };
  997. }
  998. function isUpstreamMessageRequest(record: E2ENetworkCaptureRecord) {
  999. return (
  1000. record.method === "POST" &&
  1001. (record.path.includes("/messages") || record.path.includes("/chat/completions"))
  1002. );
  1003. }
  1004. function readModelFromCapture(value: unknown) {
  1005. if (!value || typeof value !== "object" || Array.isArray(value)) {
  1006. return null;
  1007. }
  1008. const model = (value as { model?: unknown }).model;
  1009. return typeof model === "string" ? model : null;
  1010. }
  1011. function readToolNamesFromCapture(value: unknown): string[] {
  1012. if (!value || typeof value !== "object" || Array.isArray(value)) {
  1013. return [];
  1014. }
  1015. const tools = (value as { tools?: unknown }).tools;
  1016. if (!Array.isArray(tools)) {
  1017. return [];
  1018. }
  1019. return tools
  1020. .map((tool) => {
  1021. if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
  1022. return null;
  1023. }
  1024. const name = (tool as { name?: unknown }).name;
  1025. return typeof name === "string" ? name : null;
  1026. })
  1027. .filter((name): name is string => Boolean(name));
  1028. }
  1029. function captureContainsText(value: unknown, expected: string): boolean {
  1030. if (typeof value === "string") {
  1031. return value.includes(expected);
  1032. }
  1033. if (Array.isArray(value)) {
  1034. return value.some((item) => captureContainsText(item, expected));
  1035. }
  1036. if (!value || typeof value !== "object") {
  1037. return false;
  1038. }
  1039. return Object.values(value).some((child) => captureContainsText(child, expected));
  1040. }