conversation-session-browser-use-iab-full-chain.test.ts 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. import { createServer, type Server } from "node:http";
  2. import type { AddressInfo } from "node:net";
  3. import { PlatformChannels } from "@zcode/shared";
  4. import {
  5. TID_BROWSER_RESPONSIVE_HEIGHT_INPUT,
  6. TID_BROWSER_RESPONSIVE_SCALED_FRAME,
  7. TID_BROWSER_RESPONSIVE_VIEWPORT,
  8. TID_BROWSER_RESPONSIVE_WIDTH_INPUT,
  9. TID_BROWSER_RESPONSIVE_ZOOM_OPTION,
  10. TID_BROWSER_RESPONSIVE_ZOOM_SELECT,
  11. TID_BROWSER_WEBVIEW,
  12. TID_V4_COMPOSER_INPUT,
  13. TID_V4_TIMELINE,
  14. } from "@zcode/shared/test-ids";
  15. import {
  16. clearAppData,
  17. clickTestIdByWebDriver,
  18. setInputValueByTestIdDom,
  19. waitForDefaultWorkspaceReady,
  20. } from "#e2e/helpers/desktop-app";
  21. import {
  22. getUpstreamRequestEvidence,
  23. waitForUpstreamRequest,
  24. } from "#e2e/helpers/conversation-session-network";
  25. import {
  26. assertToolCallNotFailedByToolCallId,
  27. waitForSuccessfulToolCallByToolCallId,
  28. waitForToolCallBlockByToolName,
  29. } from "#e2e/helpers/conversation-session-tool";
  30. import {
  31. getV4PaneSnapshot,
  32. prepareV4ConversationE2E,
  33. selectV4TaskById,
  34. sendV4Prompt,
  35. startNewV4Draft,
  36. waitForV4AssistantMessageContaining,
  37. waitForV4Pane,
  38. waitForV4QueueCount,
  39. waitForV4TimelineContaining,
  40. } from "#e2e/helpers/v4-conversation";
  41. const PROMPT_MARKER = "E2E_BROWSER_USE_IAB_FULL_CHAIN";
  42. const FINAL_MARKER = "E2E_BROWSER_USE_IAB_DONE";
  43. const TOOL_NAME = "mcp__node_repl__js";
  44. const BOOTSTRAP_TOOL_CALL_ID = "toolu_e2e_browser_iab_bootstrap";
  45. const ACTION_TOOL_CALL_ID = "toolu_e2e_browser_iab_action";
  46. const BOOTSTRAP_RESULT_MARKER = "E2E_BROWSER_USE_IAB_BOOTSTRAP_OK";
  47. const ACTIONABILITY_RESULT_MARKER = "E2E_BROWSER_USE_IAB_ACTIONABILITY_OK";
  48. const BOOTSTRAP_PERMISSION_TITLE = "打开 Browser Use 测试页面";
  49. const ACTION_PERMISSION_TITLE = "填写并截图 Browser Use 测试页面";
  50. const FIXTURE_TITLE = "E2E Browser Use Fixture";
  51. const SUBMITTED_TEXT = "Submitted ZCode / ZCode";
  52. const DESKTOP_ZOOM_LEVEL_CHANGED = PlatformChannels.DesktopZoomLevelChanged;
  53. const SHOT_MARKER = "E2E_BROWSER_USE_IAB_TURN_SHOT";
  54. const SHOT_FINAL_MARKER = "E2E_BROWSER_USE_IAB_SHOT_DONE";
  55. const SHOT_TOOL_CALL_ID = "toolu_e2e_browser_iab_shot_open";
  56. const SHOT_RESULT_MARKER = "E2E_BROWSER_USE_IAB_SHOT_OPEN_OK";
  57. const SHOT_PERMISSION_TITLE = "打开轮尾截图测试页面";
  58. const SHOT_FOLLOW_LIVE = "E2E_BROWSER_USE_IAB_SHOT_FOLLOW_LIVE";
  59. const SHOT_FOLLOW_COLD = "E2E_BROWSER_USE_IAB_SHOT_FOLLOW_COLD";
  60. interface BrowserSurfaceSnapshot {
  61. browserPaneVisible: boolean;
  62. responsiveHeight: number | null;
  63. responsiveScale: number | null;
  64. responsiveWidth: number | null;
  65. scaledFrame: { height: number; width: number } | null;
  66. warningCount: number;
  67. webviews: Array<{
  68. compositorScale: number | null;
  69. displayed: boolean;
  70. height: number;
  71. id: number;
  72. layoutScale: number | null;
  73. src: string;
  74. width: number;
  75. }>;
  76. zoomValue: string | null;
  77. }
  78. interface GuestSnapshot {
  79. animatedInputValue: string;
  80. coveredClicks: number;
  81. devicePixelRatio: number;
  82. exists: boolean;
  83. height: number;
  84. hiddenInputValue: string;
  85. id: number;
  86. inputValue: string;
  87. status: string;
  88. title: string;
  89. url: string;
  90. width: number;
  91. zoomFactor: number;
  92. }
  93. let fixtureServer: Server | null = null;
  94. let fixtureUrl = "";
  95. describe("Browser Use Desktop IAB 全链 E2E", () => {
  96. before(async () => {
  97. fixtureServer = createBrowserFixtureServer();
  98. fixtureUrl = await listen(fixtureServer);
  99. });
  100. after(async () => {
  101. await setDesktopZoomLevel(0).catch(() => undefined);
  102. await closeServer(fixtureServer);
  103. fixtureServer = null;
  104. await browser.electron.restoreAllMocks();
  105. await clearAppData();
  106. });
  107. it("BU-E2E-001/002/005..010: 真实 IAB、输入隔离、viewport、保活和轮尾截图", async function () {
  108. this.timeout(300000);
  109. await prepareV4ConversationE2E();
  110. const prompt = [
  111. `${PROMPT_MARKER}: control the ZCode in-app browser against the supplied local fixture.`,
  112. `E2E_BROWSER_FIXTURE_URL:${fixtureUrl}`,
  113. "Inspect the form, fill Name with ZCode, submit it, take one explicit screenshot, and report the result.",
  114. ].join(" ");
  115. await sendV4Prompt(prompt);
  116. await waitForV4TimelineContaining(PROMPT_MARKER);
  117. await waitForUpstreamRequest(
  118. {
  119. includes: [PROMPT_MARKER, "E2E_BROWSER_FIXTURE_URL:", TOOL_NAME],
  120. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  121. },
  122. "首轮请求没有暴露 Browser Use Node REPL 工具或 fixture marker",
  123. 60000,
  124. );
  125. await waitForToolCallBlockByToolName(TOOL_NAME, 90000);
  126. await waitForPermissionAndApproveOnce(BOOTSTRAP_PERMISSION_TITLE);
  127. await waitForSuccessfulToolCallByToolCallId(
  128. BOOTSTRAP_TOOL_CALL_ID,
  129. [BOOTSTRAP_RESULT_MARKER, "e2eBrowserTabId"],
  130. 90000,
  131. );
  132. await waitForUpstreamRequest(
  133. {
  134. includes: [
  135. PROMPT_MARKER,
  136. BOOTSTRAP_TOOL_CALL_ID,
  137. BOOTSTRAP_RESULT_MARKER,
  138. FIXTURE_TITLE,
  139. "Submit",
  140. ],
  141. excludes: [SUBMITTED_TEXT, "Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  142. },
  143. "Browser bootstrap/goto/domSnapshot 没有真实进入 provider continuation",
  144. 90000,
  145. );
  146. await waitForPermissionAndApproveOnce(ACTION_PERMISSION_TITLE);
  147. const actionSurface = await waitForActiveBrowserSurface();
  148. const actionWebContentsId = actionSurface.webviews[0]?.id;
  149. expect(actionWebContentsId).toBeGreaterThan(0);
  150. await waitForGuestFocusedInput(
  151. actionWebContentsId as number,
  152. "cua-name-input",
  153. ACTION_TOOL_CALL_ID,
  154. );
  155. // 修复回归:旧 CUA type 依赖 Electron 当前焦点,网页 click 与 type 间若 Composer
  156. // autofocus 抢焦,文本会串进宿主。这里主动制造该时序,Browser type 仍必须只写 guest。
  157. const composerAtFocusSteal = await focusEmptyV4Composer();
  158. expect(composerAtFocusSteal.focused).toBe(true);
  159. expect(composerAtFocusSteal.text).toBe("");
  160. await waitForSuccessfulToolCallByToolCallId(
  161. ACTION_TOOL_CALL_ID,
  162. [ACTIONABILITY_RESULT_MARKER, SUBMITTED_TEXT],
  163. 90000,
  164. );
  165. await waitForUpstreamRequest(
  166. {
  167. includes: [PROMPT_MARKER, ACTION_TOOL_CALL_ID, ACTIONABILITY_RESULT_MARKER, SUBMITTED_TEXT],
  168. excludes: ["Generate a concise title", "CRITICAL: Respond with TEXT ONLY"],
  169. },
  170. "Browser locator fill/click/screenshot 结果没有进入 provider continuation",
  171. 90000,
  172. );
  173. await waitForV4AssistantMessageContaining(FINAL_MARKER);
  174. await waitForV4Pane(
  175. (snapshot) => !snapshot.canStop && snapshot.sessionId !== "draft",
  176. "Browser Use turn 完成后没有回到 idle",
  177. 90000,
  178. );
  179. await waitForV4QueueCount(0, 90000);
  180. const chat = await getV4PaneSnapshot();
  181. expect(chat.sessionId).toBeTruthy();
  182. const taskId = chat.sessionId as string;
  183. const activeSurface = await waitForActiveBrowserSurface();
  184. expect(activeSurface.responsiveWidth).toBe(375);
  185. expect(activeSurface.responsiveHeight).toBe(667);
  186. expect(activeSurface.warningCount).toBe(0);
  187. expect(activeSurface.webviews).toHaveLength(1);
  188. const originalWebContentsId = activeSurface.webviews[0]?.id;
  189. expect(originalWebContentsId).toBeGreaterThan(0);
  190. const guest = await waitForGuestSnapshot(originalWebContentsId as number);
  191. expect(guest.url).toBe(fixtureUrl);
  192. expect(guest.title).toBe(FIXTURE_TITLE);
  193. expect(guest.inputValue).toBe("ZCode");
  194. expect(guest.animatedInputValue).toBe("ZCode");
  195. expect(guest.hiddenInputValue).toBe("");
  196. expect(guest.coveredClicks).toBe(0);
  197. expect(guest.status).toBe(SUBMITTED_TEXT);
  198. expect(guest.width).toBe(375);
  199. expect(guest.height).toBe(667);
  200. // 轮尾会释放 CDP,Retina 自然 DPR 随之恢复;DPR=1 由真实工具结果的
  201. // ACTIONABILITY_OK 条件验证,空闲阶段继续验证 CSS 尺寸与页面状态。
  202. expect((await readV4ComposerSnapshot()).text).toBe("");
  203. // 模型主动 setViewportSize 的布局收敛期不应误报;最后一个 Browser command
  204. // 刚结束时 operationUntil 仍有效,立即执行用户 resize,避免慢机跨过 active deadline。
  205. expect(activeSurface.warningCount).toBe(0);
  206. await setInputValueByTestIdDom(TID_BROWSER_RESPONSIVE_WIDTH_INPUT, "380");
  207. const warningSurface = await waitForResizeWarning();
  208. expect(warningSurface.warningCount).toBe(1);
  209. expect(warningSurface.responsiveWidth).toBe(380);
  210. const imagesBeforeSwitch = await waitForConversationImageFacts(3);
  211. expect(imagesBeforeSwitch.map((image) => image.kind)).toEqual([
  212. "explicit",
  213. "explicit",
  214. "turn-end",
  215. ]);
  216. await assertBrowserUseImageGalleryPreview();
  217. // 修复回归:切到无 tab 的 B 时 A 的 webview 必须后台保活;切回 A 时必须主动展开,
  218. // 不能沿用 B 的 collapsed 状态或创建新的 guest。
  219. await startNewV4Draft();
  220. const backgroundSurface = await readBrowserSurfaceSnapshot();
  221. expect(backgroundSurface.browserPaneVisible).toBe(false);
  222. expect(backgroundSurface.webviews.some((item) => item.id === originalWebContentsId)).toBe(true);
  223. const backgroundGuest = await waitForGuestSnapshot(originalWebContentsId as number);
  224. expect(backgroundGuest.status).toBe(SUBMITTED_TEXT);
  225. await selectV4TaskById(taskId, 30000);
  226. const restoredSurface = await waitForActiveBrowserSurface();
  227. expect(restoredSurface.webviews.some((item) => item.id === originalWebContentsId)).toBe(true);
  228. const restoredGuest = await waitForGuestSnapshot(originalWebContentsId as number);
  229. expect(restoredGuest.url).toBe(fixtureUrl);
  230. expect(restoredGuest.status).toBe(SUBMITTED_TEXT);
  231. // 越界草稿保留但不得部分应用到真实 guest。
  232. await setInputValueByTestIdDom(TID_BROWSER_RESPONSIVE_HEIGHT_INPUT, "2161");
  233. const invalidDraft = await readResponsiveDraftSnapshot();
  234. expect(invalidDraft.heightInput).toBe("2161");
  235. expect(invalidDraft.heightAriaInvalid).toBe("true");
  236. expect(invalidDraft.appliedHeight).toBe(667);
  237. const invalidGuest = await waitForGuestSnapshot(originalWebContentsId as number);
  238. expect(invalidGuest.height).toBe(667);
  239. await setInputValueByTestIdDom(TID_BROWSER_RESPONSIVE_HEIGHT_INPUT, "1200");
  240. await waitForResponsiveSize(380, 1200);
  241. const resizedGuest = await waitForGuestSnapshot(originalWebContentsId as number, {
  242. height: 1200,
  243. width: 380,
  244. });
  245. expect(resizedGuest.devicePixelRatio).toBe(1);
  246. await clickTestIdByWebDriver(TID_BROWSER_RESPONSIVE_ZOOM_SELECT);
  247. await clickTestIdByWebDriver(`${TID_BROWSER_RESPONSIVE_ZOOM_OPTION}-50`);
  248. const fiftyPercentSurface = await waitForZoomValue("50");
  249. expect(fiftyPercentSurface.responsiveScale).toBeCloseTo(0.5, 4);
  250. expect(fiftyPercentSurface.scaledFrame?.width).toBeCloseTo(190, 1);
  251. expect(fiftyPercentSurface.scaledFrame?.height).toBeCloseTo(600, 1);
  252. expect(fiftyPercentSurface.webviews[0]?.width).toBeCloseTo(190, 1);
  253. expect(fiftyPercentSurface.webviews[0]?.height).toBeCloseTo(600, 1);
  254. for (const zoomLevel of [2, -2]) {
  255. await setDesktopZoomLevel(zoomLevel);
  256. const zoomSurface = await waitForDesktopZoomSurface(zoomLevel);
  257. const zoomGuest = await waitForGuestSnapshot(originalWebContentsId as number, {
  258. height: 1200,
  259. width: 380,
  260. });
  261. expect(zoomGuest.devicePixelRatio).toBe(1);
  262. expect(zoomGuest.zoomFactor).toBeCloseTo(1, 4);
  263. expect(zoomSurface.responsiveWidth).toBe(380);
  264. expect(zoomSurface.responsiveHeight).toBe(1200);
  265. expect(zoomSurface.zoomValue?.replace("%", "")).toBe("50");
  266. expect(zoomSurface.webviews[0]?.compositorScale).toBeCloseTo(Math.pow(1.1, zoomLevel), 4);
  267. expect(zoomSurface.webviews[0]?.layoutScale).toBeCloseTo(
  268. zoomLevel < 0 ? 1 / Math.pow(1.1, zoomLevel) : 1,
  269. 4,
  270. );
  271. }
  272. await setDesktopZoomLevel(0);
  273. // cold restart 只恢复 conversation 图片事实;IAB tab 本身不承诺跨进程恢复。
  274. await browser.reloadSession();
  275. await waitForRendererAfterReloadSession();
  276. await waitForDefaultWorkspaceReady(60000);
  277. await selectV4TaskById(taskId, 60000);
  278. const imagesAfterColdRestore = await waitForConversationImageFacts(3, 60000);
  279. expect(imagesAfterColdRestore).toEqual(imagesBeforeSwitch);
  280. });
  281. // 修复回归:以前冷恢复把轮尾截图 part 变成一次工具调用加结果,冷恢复后的请求和 live 不同。
  282. // 规格见 apps/zcode-cli/docs/design/v2/model/assistant-block-order.md「测试」。
  283. it("BTA01/BTA05: 轮尾截图不进入模型历史,冷恢复前后截图这一轮的请求不变", async function () {
  284. this.timeout(240000);
  285. await prepareV4ConversationE2E();
  286. await sendV4Prompt(
  287. [
  288. `${SHOT_MARKER}: open the supplied local fixture once in the in-app browser.`,
  289. `E2E_BROWSER_FIXTURE_URL:${fixtureUrl}`,
  290. ].join(" "),
  291. );
  292. await waitForToolCallBlockByToolName(TOOL_NAME, 90000);
  293. await waitForPermissionAndApproveOnce(SHOT_PERMISSION_TITLE);
  294. await waitForSuccessfulToolCallByToolCallId(SHOT_TOOL_CALL_ID, [SHOT_RESULT_MARKER], 90000);
  295. await waitForV4AssistantMessageContaining(SHOT_FINAL_MARKER);
  296. await waitForV4Pane(
  297. (snapshot) => !snapshot.canStop && snapshot.sessionId !== "draft",
  298. "轮尾截图轮次完成后没有回到 idle",
  299. 90000,
  300. );
  301. const taskId = (await getV4PaneSnapshot()).sessionId as string;
  302. // 轮尾截图只用于展示,界面上有这一张图。
  303. const imagesBeforeRestart = await waitForConversationImageFacts(1);
  304. await sendV4Prompt(`${SHOT_FOLLOW_LIVE} 冷恢复前续发。`);
  305. await waitForV4AssistantMessageContaining(`${SHOT_FOLLOW_LIVE}_DONE`);
  306. await waitForV4Pane((snapshot) => !snapshot.canStop, "冷恢复前续发未结束", 90000);
  307. await browser.reloadSession();
  308. await waitForRendererAfterReloadSession();
  309. await waitForDefaultWorkspaceReady(60000);
  310. await selectV4TaskById(taskId, 60000);
  311. expect(await waitForConversationImageFacts(1, 60000)).toEqual(imagesBeforeRestart);
  312. await sendV4Prompt(`${SHOT_FOLLOW_COLD} 冷恢复后续发。`);
  313. await waitForV4AssistantMessageContaining(`${SHOT_FOLLOW_COLD}_DONE`);
  314. await waitForV4Pane((snapshot) => !snapshot.canStop, "冷恢复后续发未结束", 90000);
  315. const live = await shotFollowRequest(
  316. "upstream-browser-use-iab-shot-follow-live",
  317. SHOT_FOLLOW_LIVE,
  318. );
  319. const cold = await shotFollowRequest(
  320. "upstream-browser-use-iab-shot-follow-cold",
  321. SHOT_FOLLOW_COLD,
  322. );
  323. // 模型只调用过一次工具;轮尾截图不变成工具调用。
  324. expect(toolUseIds(live)).toEqual([SHOT_TOOL_CALL_ID]);
  325. expect(toolUseIds(cold)).toEqual([SHOT_TOOL_CALL_ID]);
  326. // 冷恢复后截图这一轮的消息不变。只比较 live 最后一条之前的消息:最后一条是冷恢复前续发的
  327. // user 消息,live 在内存历史里带内置浏览器上下文,存库只存用户原文,冷恢复后两者不同(旧问题,
  328. // 与轮尾截图无关)。以前截图被回放成工具调用加结果,会插在这一轮之后,前缀比较仍能发现。
  329. expect(JSON.stringify(live.messages.at(-1))).toContain(SHOT_FOLLOW_LIVE);
  330. const shotTurn = live.messages.slice(0, -1);
  331. expect(stripCacheControl(cold.messages.slice(0, shotTurn.length))).toEqual(
  332. stripCacheControl(shotTurn),
  333. );
  334. });
  335. });
  336. type ShotRequest = { messages: Array<{ role: string; content: unknown }> };
  337. async function shotFollowRequest(fixtureId: string, marker: string): Promise<ShotRequest> {
  338. const record = (await getUpstreamRequestEvidence({ includes: [marker] })).find(
  339. (entry) => entry.fixtureId === fixtureId,
  340. );
  341. expect(record?.status).toBe("complete");
  342. return record!.requestJson as ShotRequest;
  343. }
  344. function toolUseIds(request: ShotRequest): string[] {
  345. return request.messages.flatMap((message) =>
  346. Array.isArray(message.content)
  347. ? (message.content as Array<{ type?: string; id?: string }>)
  348. .filter((block) => block.type === "tool_use")
  349. .map((block) => String(block.id))
  350. : [],
  351. );
  352. }
  353. // 缓存断点随请求尾部移动,不属于内容。
  354. function stripCacheControl(value: unknown): unknown {
  355. return JSON.parse(
  356. JSON.stringify(value ?? null, (key, item: unknown) =>
  357. key === "cache_control" ? undefined : item,
  358. ),
  359. );
  360. }
  361. function createBrowserFixtureServer(): Server {
  362. return createServer((_request, response) => {
  363. response.setHeader("content-type", "text/html; charset=utf-8");
  364. response.end(`<!doctype html>
  365. <html>
  366. <head>
  367. <meta name="viewport" content="width=device-width, initial-scale=1" />
  368. <title>${FIXTURE_TITLE}</title>
  369. <style>
  370. html, body { margin: 0; min-height: 100%; background: rgb(24, 79, 132); color: white; }
  371. main { box-sizing: border-box; min-height: 100vh; padding: 32px; }
  372. label, button, [role=status] { display: block; margin-top: 16px; }
  373. .moving-input { animation: browser-e2e-jitter 120ms linear infinite alternate; }
  374. .covered-target { position: relative; width: 180px; }
  375. .covered-target button { width: 100%; }
  376. .covered-target .overlay { position: absolute; inset: 0; z-index: 2; background: rgba(255, 255, 255, 0.2); }
  377. @keyframes browser-e2e-jitter { from { transform: translateX(0); } to { transform: translateX(12px); } }
  378. </style>
  379. </head>
  380. <body>
  381. <main>
  382. <h1>${FIXTURE_TITLE}</h1>
  383. <div hidden><label>Animated Name <input id="hidden-animated-name" /></label></div>
  384. <label>Animated Name <input id="animated-name" class="moving-input" /></label>
  385. <label>CUA Name <input id="cua-name-input" /></label>
  386. <button aria-label="Duplicate" data-testid="candidate-a" type="button">Candidate A</button>
  387. <button aria-label="Duplicate" data-testid="candidate-b" type="button">Candidate B</button>
  388. <div class="covered-target">
  389. <button id="covered-button" type="button">Covered</button>
  390. <span class="overlay" aria-hidden="true"></span>
  391. </div>
  392. <button id="submit-button" type="button">Submit</button>
  393. <p role="status">Waiting</p>
  394. </main>
  395. <script>
  396. window.__e2eBrowserState = { coveredClicks: 0, submissions: 0 };
  397. document.querySelector("#covered-button").addEventListener("click", () => {
  398. window.__e2eBrowserState.coveredClicks += 1;
  399. });
  400. document.querySelector("#submit-button").addEventListener("click", () => {
  401. window.__e2eBrowserState.submissions += 1;
  402. document.querySelector("[role=status]").textContent =
  403. "Submitted " + document.querySelector("#animated-name").value +
  404. " / " + document.querySelector("#cua-name-input").value;
  405. });
  406. </script>
  407. </body>
  408. </html>`);
  409. });
  410. }
  411. async function listen(server: Server): Promise<string> {
  412. await new Promise<void>((resolve, reject) => {
  413. server.once("error", reject);
  414. server.listen(0, "127.0.0.1", () => {
  415. server.off("error", reject);
  416. resolve();
  417. });
  418. });
  419. const address = server.address() as AddressInfo | null;
  420. if (!address) throw new Error("Browser Use fixture server 没有绑定端口");
  421. return `http://127.0.0.1:${address.port}/basic`;
  422. }
  423. async function closeServer(server: Server | null) {
  424. if (!server?.listening) return;
  425. await new Promise<void>((resolve, reject) => {
  426. server.close((error) => (error ? reject(error) : resolve()));
  427. });
  428. }
  429. async function waitForActiveBrowserSurface(timeout = 60000) {
  430. let latest = await readBrowserSurfaceSnapshot();
  431. await browser.waitUntil(
  432. async () => {
  433. latest = await readBrowserSurfaceSnapshot();
  434. return (
  435. latest.browserPaneVisible &&
  436. latest.webviews.length === 1 &&
  437. latest.webviews[0]?.displayed === true &&
  438. latest.webviews[0]?.id > 0
  439. );
  440. },
  441. {
  442. timeout,
  443. timeoutMsg: `Browser pane/webview 没有进入 active: ${JSON.stringify(latest)}`,
  444. },
  445. );
  446. return latest;
  447. }
  448. async function readBrowserSurfaceSnapshot(): Promise<BrowserSurfaceSnapshot> {
  449. return browser.execute(
  450. (viewportTestId, scaledFrameTestId, webviewTestId, zoomTestId) => {
  451. const isVisible = (element: HTMLElement | null) => {
  452. if (!element) return false;
  453. const style = getComputedStyle(element);
  454. const rect = element.getBoundingClientRect();
  455. return (
  456. style.display !== "none" &&
  457. style.visibility !== "hidden" &&
  458. rect.width > 0 &&
  459. rect.height > 0
  460. );
  461. };
  462. const viewport = document.querySelector<HTMLElement>(`[data-testid="${viewportTestId}"]`);
  463. const scaledFrame = document.querySelector<HTMLElement>(
  464. `[data-testid="${scaledFrameTestId}"]`,
  465. );
  466. const zoom = document.querySelector<HTMLElement>(`[data-testid="${zoomTestId}"]`);
  467. const scaledFrameRect = scaledFrame?.getBoundingClientRect() ?? null;
  468. const webviews = Array.from(
  469. document.querySelectorAll<HTMLElement>(`[data-testid="${webviewTestId}"]`),
  470. ).map((element) => {
  471. const webview = element as HTMLElement & {
  472. getWebContentsId?: () => number;
  473. src?: string;
  474. };
  475. const rect = element.getBoundingClientRect();
  476. const readNumber = (name: string) => {
  477. const value = element.getAttribute(name);
  478. return value === null ? null : Number(value);
  479. };
  480. return {
  481. compositorScale: readNumber("data-browser-compositor-scale"),
  482. displayed: isVisible(element),
  483. height: rect.height,
  484. id: webview.getWebContentsId?.() ?? 0,
  485. layoutScale: readNumber("data-browser-layout-scale"),
  486. src: webview.src ?? element.getAttribute("src") ?? "",
  487. width: rect.width,
  488. };
  489. });
  490. return {
  491. // 修复原因:旧 TID_BROWSER_PANE 已无生产挂载点,继续拿它判断会出现
  492. // “webview 可见但 pane 不可见”的假失败。responsive viewport 是当前
  493. // Browser surface 的真实可见容器,也能区分任务切换后的 collapsed 状态。
  494. browserPaneVisible: isVisible(viewport),
  495. responsiveHeight: Number(viewport?.dataset.responsiveHeight ?? "") || null,
  496. responsiveScale: Number(viewport?.dataset.responsiveScale ?? "") || null,
  497. responsiveWidth: Number(viewport?.dataset.responsiveWidth ?? "") || null,
  498. scaledFrame: scaledFrameRect
  499. ? { height: scaledFrameRect.height, width: scaledFrameRect.width }
  500. : null,
  501. warningCount: document.querySelectorAll('[data-browser-resize-warning="visible"]').length,
  502. webviews,
  503. zoomValue: zoom?.getAttribute("data-value") ?? zoom?.textContent?.trim() ?? null,
  504. };
  505. },
  506. TID_BROWSER_RESPONSIVE_VIEWPORT,
  507. TID_BROWSER_RESPONSIVE_SCALED_FRAME,
  508. TID_BROWSER_WEBVIEW,
  509. TID_BROWSER_RESPONSIVE_ZOOM_SELECT,
  510. ) as Promise<BrowserSurfaceSnapshot>;
  511. }
  512. async function waitForGuestSnapshot(
  513. webContentsId: number,
  514. expected?: { height: number; width: number },
  515. timeout = 60000,
  516. ) {
  517. let latest: GuestSnapshot | null = null;
  518. await browser.waitUntil(
  519. async () => {
  520. latest = await readGuestSnapshot(webContentsId);
  521. return (
  522. latest.exists &&
  523. (!expected ||
  524. (Math.abs(latest.width - expected.width) <= 1 &&
  525. Math.abs(latest.height - expected.height) <= 1))
  526. );
  527. },
  528. {
  529. timeout,
  530. timeoutMsg: `guest ${webContentsId} 没有收敛: ${JSON.stringify(latest)}`,
  531. },
  532. );
  533. return latest as unknown as GuestSnapshot;
  534. }
  535. function readGuestSnapshot(webContentsId: number): Promise<GuestSnapshot> {
  536. return browser.electron.execute(async (electron, targetId) => {
  537. const guest = electron.webContents.fromId(targetId);
  538. if (!guest || guest.isDestroyed()) {
  539. return {
  540. animatedInputValue: "",
  541. coveredClicks: 0,
  542. devicePixelRatio: 0,
  543. exists: false,
  544. height: 0,
  545. hiddenInputValue: "",
  546. id: targetId,
  547. inputValue: "",
  548. status: "",
  549. title: "",
  550. url: "",
  551. width: 0,
  552. zoomFactor: 0,
  553. };
  554. }
  555. const page = (await guest.executeJavaScript(`({
  556. animatedInputValue: document.querySelector('#animated-name')?.value ?? '',
  557. coveredClicks: window.__e2eBrowserState?.coveredClicks ?? 0,
  558. devicePixelRatio: window.devicePixelRatio,
  559. height: window.innerHeight,
  560. hiddenInputValue: document.querySelector('#hidden-animated-name')?.value ?? '',
  561. inputValue: document.querySelector('#cua-name-input')?.value ?? '',
  562. status: document.querySelector('[role=status]')?.textContent ?? '',
  563. title: document.title,
  564. width: window.innerWidth
  565. })`)) as {
  566. animatedInputValue: string;
  567. coveredClicks: number;
  568. devicePixelRatio: number;
  569. height: number;
  570. hiddenInputValue: string;
  571. inputValue: string;
  572. status: string;
  573. title: string;
  574. width: number;
  575. };
  576. return {
  577. ...page,
  578. exists: true,
  579. id: targetId,
  580. url: guest.getURL(),
  581. zoomFactor: guest.getZoomFactor(),
  582. };
  583. }, webContentsId) as unknown as Promise<GuestSnapshot>;
  584. }
  585. async function waitForGuestFocusedInput(
  586. webContentsId: number,
  587. expectedId: string,
  588. toolCallId: string,
  589. timeout = 10000,
  590. ) {
  591. const deadline = Date.now() + timeout;
  592. let latest = "";
  593. while (Date.now() <= deadline) {
  594. // Bug 根因:WebdriverIO waitUntil 会把 predicate 抛出的工具错误当成重试信号,
  595. // 最后只留下焦点超时。显式轮询可让真实的 node_repl 失败立即终止用例。
  596. await assertToolCallNotFailedByToolCallId(toolCallId);
  597. latest = await browser.electron.execute((electron, targetId) => {
  598. const guest = electron.webContents.fromId(targetId);
  599. if (!guest || guest.isDestroyed()) return "";
  600. return guest.executeJavaScript("document.activeElement?.id ?? ''") as Promise<string>;
  601. }, webContentsId);
  602. if (latest === expectedId) return latest;
  603. await new Promise<void>((resolveDelay) => setTimeout(resolveDelay, 100));
  604. }
  605. throw new Error(`guest 输入焦点没有收敛到 ${expectedId}: ${latest}`);
  606. }
  607. function readV4ComposerSnapshot() {
  608. return browser.execute((inputTestId) => {
  609. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  610. const bridge = (
  611. element as
  612. | (HTMLElement & {
  613. __zcodeLexicalInputE2E?: {
  614. focus: () => void;
  615. getText: () => string;
  616. };
  617. })
  618. | null
  619. )?.__zcodeLexicalInputE2E;
  620. return {
  621. focused: Boolean(
  622. element && document.activeElement && element.contains(document.activeElement),
  623. ),
  624. text: bridge?.getText() ?? null,
  625. };
  626. }, TID_V4_COMPOSER_INPUT);
  627. }
  628. async function focusEmptyV4Composer(timeout = 10000) {
  629. let latest = await readV4ComposerSnapshot();
  630. await browser.waitUntil(
  631. async () => {
  632. latest = await browser.execute((inputTestId) => {
  633. const element = document.querySelector<HTMLElement>(`[data-testid="${inputTestId}"]`);
  634. const bridge = (
  635. element as
  636. | (HTMLElement & {
  637. __zcodeLexicalInputE2E?: {
  638. focus: () => void;
  639. getText: () => string;
  640. };
  641. })
  642. | null
  643. )?.__zcodeLexicalInputE2E;
  644. bridge?.focus();
  645. return {
  646. focused: Boolean(
  647. element && document.activeElement && element.contains(document.activeElement),
  648. ),
  649. text: bridge?.getText() ?? null,
  650. };
  651. }, TID_V4_COMPOSER_INPUT);
  652. return latest.focused && latest.text === "";
  653. },
  654. {
  655. timeout,
  656. interval: 100,
  657. timeoutMsg: `宿主 Composer 没有在空草稿下抢到焦点: ${JSON.stringify(latest)}`,
  658. },
  659. );
  660. return latest;
  661. }
  662. interface ConversationImageFact {
  663. bytes: number;
  664. hash: string;
  665. height: number;
  666. kind: "explicit" | "turn-end";
  667. mimeType: string;
  668. width: number;
  669. }
  670. async function waitForConversationImageFacts(expectedCount: number, timeout = 30000) {
  671. let latest: ConversationImageFact[] = [];
  672. let diagnostic = "not-read";
  673. try {
  674. await browser.waitUntil(
  675. async () => {
  676. const result = await browser
  677. .execute(
  678. (timelineTestId, actionTitle) => {
  679. const timeline = document.querySelector<HTMLElement>(
  680. `[data-testid="${timelineTestId}"]`,
  681. );
  682. const hash = (value: string) => {
  683. let result = 2_166_136_261;
  684. for (let index = 0; index < value.length; index += 1) {
  685. result ^= value.charCodeAt(index);
  686. result = Math.imul(result, 16_777_619);
  687. }
  688. return (result >>> 0).toString(16).padStart(8, "0");
  689. };
  690. const workGroupTrigger = Array.from(
  691. timeline?.querySelectorAll<HTMLButtonElement>('button[aria-expanded="false"]') ??
  692. [],
  693. ).find((button) => {
  694. const text = button.innerText.replace(/\u00a0/g, " ").trim();
  695. return text.startsWith("Worked for") || text.startsWith("已工作");
  696. });
  697. workGroupTrigger?.click();
  698. const actionRow = Array.from(
  699. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  700. ).find((row) =>
  701. (row.innerText.replace(/\u00a0/g, " ").trim() ?? "").includes(actionTitle),
  702. );
  703. const collapsedTrigger = Array.from(
  704. actionRow?.querySelectorAll<HTMLElement>(
  705. '[role="button"][aria-expanded="false"]',
  706. ) ?? [],
  707. ).at(-1);
  708. collapsedTrigger?.click();
  709. const images = Array.from(
  710. timeline?.querySelectorAll<HTMLImageElement>(
  711. '[data-row-id] button img[src^="data:image/"]',
  712. ) ?? [],
  713. ).map((image) => {
  714. const row = image.closest<HTMLElement>("[data-row-id]");
  715. const rowText = row?.innerText.replace(/\u00a0/g, " ").trim() ?? "";
  716. const mimeType = /^data:([^;,]+);base64,/iu.exec(image.src)?.[1] ?? "";
  717. return {
  718. bytes: image.src.length,
  719. hash: hash(image.src),
  720. height: image.naturalHeight,
  721. kind: rowText.includes(actionTitle)
  722. ? ("explicit" as const)
  723. : ("turn-end" as const),
  724. mimeType,
  725. width: image.naturalWidth,
  726. };
  727. });
  728. return {
  729. diagnostic: {
  730. actionRowFound: Boolean(actionRow),
  731. bodyImageCount: document.images.length,
  732. collapsedTriggerFound: Boolean(collapsedTrigger),
  733. imageSources: Array.from(document.images)
  734. .map((image) => image.src.slice(0, 80))
  735. .slice(-8),
  736. rowCount: timeline?.querySelectorAll("[data-row-id]").length ?? 0,
  737. timelineFound: Boolean(timeline),
  738. timelineTail: timeline?.innerText.slice(-800) ?? "",
  739. workGroupTriggerFound: Boolean(workGroupTrigger),
  740. },
  741. images,
  742. };
  743. },
  744. TID_V4_TIMELINE,
  745. ACTION_PERMISSION_TITLE,
  746. )
  747. .catch((error: unknown) => {
  748. diagnostic = `execute-error:${error instanceof Error ? error.message : String(error)}`;
  749. return null;
  750. });
  751. if (!result) return false;
  752. latest = result.images;
  753. diagnostic = JSON.stringify(result.diagnostic);
  754. return (
  755. latest.length === expectedCount &&
  756. latest.every(
  757. (image) =>
  758. image.bytes > 100 &&
  759. image.mimeType === "image/png" &&
  760. image.width > 0 &&
  761. image.height > 0,
  762. ) &&
  763. latest.filter((image) => image.kind === "explicit").length === expectedCount - 1 &&
  764. latest.filter((image) => image.kind === "turn-end").length === 1
  765. );
  766. },
  767. {
  768. timeout,
  769. timeoutMsg: `Node REPL/轮尾图片数量没有收敛到 ${expectedCount}`,
  770. },
  771. );
  772. } catch (error) {
  773. throw new Error(
  774. `Node REPL/轮尾图片数量没有收敛到 ${expectedCount}: ${JSON.stringify(latest)}; ${diagnostic}`,
  775. { cause: error },
  776. );
  777. }
  778. return latest;
  779. }
  780. async function assertBrowserUseImageGalleryPreview() {
  781. const opened = await browser.execute(
  782. (timelineTestId, actionTitle) => {
  783. const timeline = document.querySelector<HTMLElement>(`[data-testid="${timelineTestId}"]`);
  784. const actionRow = Array.from(
  785. timeline?.querySelectorAll<HTMLElement>("[data-row-id]") ?? [],
  786. ).find((row) => row.innerText.includes(actionTitle));
  787. const gallery = actionRow?.querySelector<HTMLElement>("[data-node-repl-image-gallery]");
  788. const buttons = Array.from(
  789. gallery?.querySelectorAll<HTMLButtonElement>("[data-image-thumbnail-trigger]") ?? [],
  790. );
  791. const button = buttons[1];
  792. button?.click();
  793. return {
  794. count: buttons.length,
  795. horizontalOverflow: Boolean(gallery && gallery.scrollWidth > gallery.clientWidth + 1),
  796. opened: Boolean(button),
  797. };
  798. },
  799. TID_V4_TIMELINE,
  800. ACTION_PERMISSION_TITLE,
  801. );
  802. expect(opened).toEqual({
  803. count: 2,
  804. horizontalOverflow: false,
  805. opened: true,
  806. });
  807. await browser.waitUntil(
  808. async () =>
  809. browser.execute(() =>
  810. Boolean(document.querySelector('[data-testid="node-repl-image-lightbox"]')),
  811. ),
  812. { timeout: 10000, timeoutMsg: "Node REPL 图片大图预览没有打开" },
  813. );
  814. const initialAlt = await browser.execute(
  815. () =>
  816. document
  817. .querySelector<HTMLImageElement>('[data-testid="node-repl-image-lightbox-image"]')
  818. ?.getAttribute("alt") ?? "",
  819. );
  820. expect(initialAlt).toMatch(/2$/u);
  821. await browser.keys("ArrowRight");
  822. const nextAlt = await browser.execute(
  823. () =>
  824. document
  825. .querySelector<HTMLImageElement>('[data-testid="node-repl-image-lightbox-image"]')
  826. ?.getAttribute("alt") ?? "",
  827. );
  828. expect(nextAlt).toMatch(/1$/u);
  829. await browser.keys("Escape");
  830. await browser.waitUntil(
  831. async () =>
  832. browser.execute(() => !document.querySelector('[data-testid="node-repl-image-lightbox"]')),
  833. { timeout: 10000, timeoutMsg: "Node REPL 图片大图预览没有被 Escape 关闭" },
  834. );
  835. }
  836. async function waitForResizeWarning() {
  837. let latest = await readBrowserSurfaceSnapshot();
  838. await browser.waitUntil(
  839. async () => {
  840. latest = await readBrowserSurfaceSnapshot();
  841. return latest.warningCount === 1;
  842. },
  843. {
  844. timeout: 10000,
  845. timeoutMsg: `用户 resize 后没有出现一次弱提示: ${JSON.stringify(latest)}`,
  846. },
  847. );
  848. return latest;
  849. }
  850. function readResponsiveDraftSnapshot() {
  851. return browser.execute(
  852. (heightTestId, viewportTestId) => {
  853. const input = document.querySelector<HTMLInputElement>(`[data-testid="${heightTestId}"]`);
  854. const viewport = document.querySelector<HTMLElement>(`[data-testid="${viewportTestId}"]`);
  855. return {
  856. appliedHeight: Number(viewport?.dataset.responsiveHeight ?? "") || null,
  857. heightAriaInvalid: input?.getAttribute("aria-invalid") ?? null,
  858. heightInput: input?.value ?? null,
  859. };
  860. },
  861. TID_BROWSER_RESPONSIVE_HEIGHT_INPUT,
  862. TID_BROWSER_RESPONSIVE_VIEWPORT,
  863. );
  864. }
  865. async function waitForResponsiveSize(width: number, height: number) {
  866. let latest = await readBrowserSurfaceSnapshot();
  867. await browser.waitUntil(
  868. async () => {
  869. latest = await readBrowserSurfaceSnapshot();
  870. return latest.responsiveWidth === width && latest.responsiveHeight === height;
  871. },
  872. {
  873. timeout: 30000,
  874. timeoutMsg: `responsive viewport 没有收敛到 ${width}x${height}: ${JSON.stringify(latest)}`,
  875. },
  876. );
  877. return latest;
  878. }
  879. async function waitForZoomValue(expected: string) {
  880. let latest = await readBrowserSurfaceSnapshot();
  881. await browser.waitUntil(
  882. async () => {
  883. latest = await readBrowserSurfaceSnapshot();
  884. return latest.zoomValue === expected || latest.zoomValue === `${expected}%`;
  885. },
  886. {
  887. timeout: 10000,
  888. timeoutMsg: `responsive zoom 没有切到 ${expected}: ${JSON.stringify(latest)}`,
  889. },
  890. );
  891. return latest;
  892. }
  893. async function setDesktopZoomLevel(zoomLevel: number) {
  894. const result = await browser.electron.execute(
  895. (electron, channel, nextZoomLevel) => {
  896. const candidates = electron.BrowserWindow.getAllWindows().filter(
  897. (candidate) =>
  898. !candidate.isDestroyed() &&
  899. candidate.webContents.getURL().includes("/renderer/index.html"),
  900. );
  901. // 修复原因:restoreSession 启动 URL 不再携带 initialWorkspacePath,按 URL
  902. // 查 workspace 会漏掉健康主窗口。E2E 只接受唯一 renderer BrowserWindow,
  903. // 多窗口时直接失败,避免退化成 focused-window 猜测并改错窗口。
  904. if (candidates.length !== 1) {
  905. return {
  906. applied: false,
  907. candidateUrls: candidates.map((candidate) => candidate.webContents.getURL()),
  908. };
  909. }
  910. const target = candidates[0];
  911. if (!target || target.isDestroyed()) return { applied: false, candidateUrls: [] };
  912. target.webContents.setZoomFactor(Math.pow(1.1, nextZoomLevel));
  913. target.webContents.send(channel, { zoomLevel: nextZoomLevel });
  914. target.focus();
  915. return { applied: true, candidateUrls: [target.webContents.getURL()] };
  916. },
  917. DESKTOP_ZOOM_LEVEL_CHANGED,
  918. zoomLevel,
  919. );
  920. if (!result.applied) {
  921. throw new Error(
  922. `没有找到唯一可设置 Desktop zoom=${zoomLevel} 的窗口: ${JSON.stringify(result.candidateUrls)}`,
  923. );
  924. }
  925. }
  926. async function waitForDesktopZoomSurface(zoomLevel: number) {
  927. const expected = Math.pow(1.1, zoomLevel);
  928. let latest = await readBrowserSurfaceSnapshot();
  929. await browser.waitUntil(
  930. async () => {
  931. latest = await readBrowserSurfaceSnapshot();
  932. return latest.webviews.some(
  933. (webview) =>
  934. webview.compositorScale !== null && Math.abs(webview.compositorScale - expected) < 0.0001,
  935. );
  936. },
  937. {
  938. timeout: 30000,
  939. timeoutMsg: `Desktop zoom=${zoomLevel} 没有同步到 Browser surface: ${JSON.stringify(latest)}`,
  940. },
  941. );
  942. return latest;
  943. }
  944. async function waitForRendererAfterReloadSession() {
  945. await browser.waitUntil(
  946. async () => {
  947. try {
  948. const puppeteer = await browser.getPuppeteer();
  949. const rendererTarget = puppeteer
  950. .targets()
  951. .filter((target) => {
  952. try {
  953. return new URL(target.url()).pathname.endsWith("/renderer/index.html");
  954. } catch {
  955. return false;
  956. }
  957. })
  958. .at(-1);
  959. const targetId = rendererTarget
  960. ? ((rendererTarget as unknown as { _targetId?: string })._targetId ?? null)
  961. : null;
  962. if (!targetId) return false;
  963. await browser.switchToWindow(targetId);
  964. return true;
  965. } catch {
  966. return false;
  967. }
  968. },
  969. {
  970. timeout: 30000,
  971. interval: 250,
  972. timeoutMsg: "Browser Use cold restore 后没有找到 renderer target",
  973. },
  974. );
  975. }
  976. async function waitForPermissionAndApproveOnce(expectedTitle: string) {
  977. let latest = "";
  978. const clickMatchingAllowOnce = () =>
  979. browser.execute(() => {
  980. const listboxes = Array.from(
  981. document.querySelectorAll<HTMLElement>('[role="listbox"]'),
  982. ).filter((element) => {
  983. const label = element.getAttribute("aria-label")?.trim();
  984. return label === "Permission required" || label === "需要权限";
  985. });
  986. const options = listboxes.flatMap((listbox) =>
  987. Array.from(
  988. listbox.querySelectorAll<HTMLButtonElement>(
  989. 'button[role="option"][data-permission-option-kind="allowOnce"]',
  990. ),
  991. ),
  992. );
  993. if (listboxes.length !== 1 || options.length !== 1) return false;
  994. options[0]?.click();
  995. return true;
  996. });
  997. await browser.waitUntil(
  998. async () => {
  999. const state = await browser.execute(() => {
  1000. const listboxes = Array.from(
  1001. document.querySelectorAll<HTMLElement>('[role="listbox"]'),
  1002. ).filter((element) => {
  1003. const label = element.getAttribute("aria-label")?.trim();
  1004. return label === "Permission required" || label === "需要权限";
  1005. });
  1006. const allowOnceCount = listboxes.reduce(
  1007. (count, element) =>
  1008. count +
  1009. element.querySelectorAll(
  1010. 'button[role="option"][data-permission-option-kind="allowOnce"]',
  1011. ).length,
  1012. 0,
  1013. );
  1014. return {
  1015. allowOnceCount,
  1016. count: listboxes.length,
  1017. text: listboxes
  1018. .map((element) => element.parentElement?.innerText.replace(/\u00a0/g, " ").trim() ?? "")
  1019. .join("\n"),
  1020. };
  1021. });
  1022. latest = JSON.stringify(state);
  1023. // 修复原因:V4 permission payload 只保留 toolName/summary/detail,不会把
  1024. // node_repl 输入里的模型 title 投影到 PermissionDialog。调用方已先用固定
  1025. // tool call/continuation 锁定阶段;这里要求唯一弹窗和唯一 allowOnce,避免
  1026. // 退化成“随便批准第一个”而误响应并发请求。
  1027. return state.count === 1 && state.allowOnceCount === 1;
  1028. },
  1029. {
  1030. timeout: 30000,
  1031. timeoutMsg: `Browser Use 权限请求没有出现(${expectedTitle}): ${latest}`,
  1032. },
  1033. );
  1034. expect(await clickMatchingAllowOnce()).toBe(true);
  1035. // 修复原因:首个 tool result 后下一个权限可能在 100ms polling 间隔内立即出现。
  1036. // 旧 helper 看到“仍有 listbox”会再次点击,实际把下一次 Browser 调用也批准了。
  1037. // 单次 helper 只能点击一次;调用方用下一条 provider continuation 证明本次审批已生效。
  1038. }