browser-client.test.ts 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. import { describe, expect, it, vi } from "vitest";
  2. import { resolve } from "node:path";
  3. import { runInNewContext } from "node:vm";
  4. import {
  5. BrowserCommandError,
  6. BrowsersFacade,
  7. PlaywrightAPI,
  8. PlaywrightFrameLocator,
  9. PlaywrightLocator,
  10. Tab,
  11. type BrowserInfo,
  12. setupBrowserRuntime,
  13. } from "../src/browser-client/index.js";
  14. import type { BrowserCommand, BrowserCommandResult } from "@zcode/contracts";
  15. const IAB_INFO: BrowserInfo = {
  16. id: "iab-runtime-1",
  17. generation: 1,
  18. type: "iab",
  19. name: "ZCode In-app Browser",
  20. capabilities: { browser: [], tab: [] },
  21. };
  22. function createFacade(
  23. execute: (command: BrowserCommand) => Promise<BrowserCommandResult>,
  24. infos: BrowserInfo[] = [IAB_INFO],
  25. options: { documentationRoot?: string; assertAvailable?: () => void } = {},
  26. ): BrowsersFacade {
  27. return new BrowsersFacade(
  28. {
  29. list: async () => infos,
  30. execute: async (_browserId, _browserGeneration, command) => execute(command),
  31. },
  32. options,
  33. );
  34. }
  35. function fakeExecute() {
  36. const calls: BrowserCommand[] = [];
  37. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  38. calls.push(command);
  39. if (command.method === "list") {
  40. return { ok: true, tabs: [], elapsedMs: 1 } satisfies BrowserCommandResult;
  41. }
  42. if (command.method === "newTab") {
  43. return {
  44. ok: true,
  45. tab: {
  46. tabId: "t-new",
  47. url: "about:blank",
  48. title: "",
  49. viewport: { width: 1280, height: 720 },
  50. },
  51. elapsedMs: 1,
  52. };
  53. }
  54. if (command.method === "screenshot") {
  55. return { ok: true, image: { base64: "AQID", mimeType: "image/png" }, elapsedMs: 1 };
  56. }
  57. if (command.method === "snapshot") {
  58. return {
  59. ok: true,
  60. snapshot: {
  61. url: "https://example.com",
  62. title: "E",
  63. truncated: false,
  64. elements: [{ ref: "e1", tag: "button", text: "Go" }],
  65. dom: [
  66. { tag: "h1", depth: 1, inViewport: true, text: "Example" },
  67. { tag: "button", depth: 2, inViewport: true, ref: "e1", name: "Go" },
  68. ],
  69. domTruncated: false,
  70. },
  71. elapsedMs: 1,
  72. };
  73. }
  74. if (command.method === "getState" || command.method === "navigate") {
  75. return {
  76. ok: true,
  77. state: { url: "https://example.com", title: "E", canGoBack: false, canGoForward: false },
  78. elapsedMs: 1,
  79. };
  80. }
  81. if (command.method === "evaluate") {
  82. return { ok: true, value: "value", elapsedMs: 1 };
  83. }
  84. if (command.method === "getDialog") {
  85. return { ok: true, dialog: null, elapsedMs: 1 };
  86. }
  87. if (command.method === "recordingStart") {
  88. return {
  89. ok: true,
  90. recording: {
  91. id: "recording-1",
  92. status: "running",
  93. phase: "capturing",
  94. progress: 0.1,
  95. startedAt: 1,
  96. updatedAt: 1,
  97. },
  98. elapsedMs: 1,
  99. };
  100. }
  101. if (command.method === "recordingStatus") {
  102. return {
  103. ok: true,
  104. recording: {
  105. id: command.recordingId,
  106. status: "completed",
  107. phase: "completed",
  108. progress: 1,
  109. startedAt: 1,
  110. updatedAt: 2,
  111. artifact: {
  112. path: command.outputPath ?? "/tmp/browser-recording.webm",
  113. mimeType: "video/webm",
  114. width: 1280,
  115. height: 720,
  116. fps: 25,
  117. durationMs: 1_000,
  118. frameCount: 25,
  119. },
  120. },
  121. elapsedMs: 1,
  122. };
  123. }
  124. if (command.method === "recordingCancel") {
  125. return {
  126. ok: true,
  127. recording: {
  128. id: command.recordingId,
  129. status: "cancelled",
  130. phase: "cancelled",
  131. progress: 0.1,
  132. startedAt: 1,
  133. updatedAt: 2,
  134. },
  135. elapsedMs: 1,
  136. };
  137. }
  138. if (command.method === "elementInfo") {
  139. return {
  140. ok: true,
  141. element: { ref: "e1", tag: "button", text: "Go" },
  142. elapsedMs: 1,
  143. };
  144. }
  145. if (command.method === "playwright") {
  146. const { action } = command;
  147. if (action.name === "elementScreenshot") {
  148. return { ok: true, image: { base64: "AQID", mimeType: "image/png" }, elapsedMs: 1 };
  149. }
  150. if (action.name === "elementInfo") {
  151. return {
  152. ok: true,
  153. value: [
  154. {
  155. tagName: "button",
  156. preview: "<button>Go</button>",
  157. selector: { candidates: ["button"] },
  158. },
  159. ],
  160. elapsedMs: 1,
  161. };
  162. }
  163. if (action.name === "domSnapshot") {
  164. return { ok: true, value: '- heading "Example" [level=1]', elapsedMs: 1 };
  165. }
  166. if (action.name === "waitForEvent") {
  167. return { ok: true, value: { id: "download-1" }, elapsedMs: 1 };
  168. }
  169. if (action.name === "downloadPath") {
  170. return { ok: true, value: "/tmp/file.txt", elapsedMs: 1 };
  171. }
  172. if (action.name === "evaluate") {
  173. return { ok: true, value: "evaluated", elapsedMs: 1 };
  174. }
  175. if (action.name === "locator") {
  176. const values: Record<string, unknown> = {
  177. count: 2,
  178. allTextContents: ["one", "two"],
  179. textContent: "one",
  180. innerText: "One",
  181. getAttribute: "button",
  182. isVisible: true,
  183. isEnabled: true,
  184. evaluate: "locator-evaluated",
  185. };
  186. return { ok: true, value: values[action.operation], elapsedMs: 1 };
  187. }
  188. return { ok: true, elapsedMs: 1 };
  189. }
  190. return { ok: true, elapsedMs: 1 };
  191. });
  192. return { execute, calls };
  193. }
  194. /** open() 复用路径的可编程 mock:list/activateTab/newTab/navigate 全部记录命令序列。 */
  195. function reuseFacade(tabs: Array<{ tabId: string; url?: string; active?: boolean }>) {
  196. const calls: BrowserCommand[] = [];
  197. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  198. calls.push(command);
  199. if (command.method === "list") {
  200. return {
  201. ok: true,
  202. tabs: tabs.map((tab) => ({
  203. tabId: tab.tabId,
  204. url: tab.url,
  205. title: tab.tabId,
  206. active: tab.active,
  207. viewport: { width: 1280, height: 720 },
  208. })),
  209. elapsedMs: 1,
  210. } satisfies BrowserCommandResult;
  211. }
  212. if (command.method === "activateTab") {
  213. const found = tabs.find((tab) => tab.tabId === command.tabId);
  214. return {
  215. ok: true,
  216. tab: {
  217. tabId: command.tabId,
  218. url: found?.url ?? "about:blank",
  219. title: command.tabId,
  220. active: true,
  221. viewport: { width: 1280, height: 720 },
  222. },
  223. elapsedMs: 1,
  224. } satisfies BrowserCommandResult;
  225. }
  226. if (command.method === "newTab") {
  227. return {
  228. ok: true,
  229. tab: {
  230. tabId: "t-new",
  231. url: "about:blank",
  232. title: "",
  233. viewport: { width: 1280, height: 720 },
  234. },
  235. elapsedMs: 1,
  236. } satisfies BrowserCommandResult;
  237. }
  238. if (command.method === "navigate") {
  239. return {
  240. ok: true,
  241. state: {
  242. url: command.url,
  243. title: "",
  244. canGoBack: false,
  245. canGoForward: false,
  246. },
  247. elapsedMs: 1,
  248. } satisfies BrowserCommandResult;
  249. }
  250. return { ok: true, elapsedMs: 1 } satisfies BrowserCommandResult;
  251. });
  252. return { calls, facade: createFacade(execute) };
  253. }
  254. describe("browser-client facade", () => {
  255. it("list()/get()/getDefault() expose the iab backend model", async () => {
  256. const { execute } = fakeExecute();
  257. const browsers = createFacade(execute);
  258. await expect(browsers.list()).resolves.toEqual([
  259. {
  260. id: "iab-runtime-1",
  261. type: "iab",
  262. name: "ZCode In-app Browser",
  263. capabilities: { browser: [], tab: [] },
  264. },
  265. ]);
  266. const byType = await browsers.get("iab");
  267. await expect(browsers.get("iab-runtime-1")).resolves.toBe(byType);
  268. await expect(browsers.getDefault()).resolves.toBe(byType);
  269. await expect(browsers.getForUrl("https://example.com")).resolves.toBe(byType);
  270. await expect(browsers.get("chrome")).rejects.toMatchObject({ code: "backend_unavailable" });
  271. });
  272. it("routes commands by runtime browser id and never synthesizes unavailable backends", async () => {
  273. const extension: BrowserInfo = {
  274. id: "extension-profile-1",
  275. generation: 2,
  276. type: "extension",
  277. name: "Chrome",
  278. capabilities: {},
  279. };
  280. const execute = vi.fn(
  281. async (_browserId: string, _browserGeneration: number, command: BrowserCommand) => {
  282. if (command.method === "list") {
  283. return { ok: true, tabs: [], elapsedMs: 1 } satisfies BrowserCommandResult;
  284. }
  285. return { ok: true, elapsedMs: 1 } satisfies BrowserCommandResult;
  286. },
  287. );
  288. const browsers = new BrowsersFacade({
  289. list: async () => [extension, IAB_INFO],
  290. execute,
  291. });
  292. const chrome = await browsers.get("extension");
  293. await chrome.default.goto("https://example.com");
  294. expect(execute).toHaveBeenLastCalledWith(extension.id, extension.generation, {
  295. method: "navigate",
  296. url: "https://example.com",
  297. });
  298. await expect(browsers.getDefault()).resolves.toMatchObject({ browserId: IAB_INFO.id });
  299. await expect(browsers.getForUrl("http://localhost:3000")).resolves.toMatchObject({
  300. browserId: IAB_INFO.id,
  301. });
  302. const empty = new BrowsersFacade({ list: async () => [], execute });
  303. await expect(empty.getDefault()).rejects.toMatchObject({ code: "backend_unavailable" });
  304. });
  305. it("open(url) navigates with direct-return SDK semantics", async () => {
  306. const { execute, calls } = fakeExecute();
  307. const tab = await createFacade(execute).open("https://example.com");
  308. expect(tab).toBeInstanceOf(Tab);
  309. // 无已有 tab 可复用时,open() 仍走 newTab + navigate 的直返语义。
  310. expect(calls).toEqual([
  311. { method: "list" },
  312. { method: "newTab" },
  313. { method: "navigate", url: "https://example.com", tabId: "t-new" },
  314. ]);
  315. });
  316. describe("open(url) tab reuse", () => {
  317. it("reuses an exact URL match by activating it and navigating in place", async () => {
  318. const { calls, facade } = reuseFacade([
  319. { tabId: "t-1", url: "https://example.com/docs#old-section" },
  320. ]);
  321. const tab = await facade.open("https://example.com/docs");
  322. expect(tab).toBeInstanceOf(Tab);
  323. expect(tab.id).toBe("t-1");
  324. expect(calls).toEqual([
  325. { method: "list" },
  326. { method: "activateTab", tabId: "t-1" },
  327. { method: "navigate", url: "https://example.com/docs", tabId: "t-1" },
  328. ]);
  329. });
  330. it("reuses a same-hostname tab when no closer match exists", async () => {
  331. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://a.com/list" }]);
  332. const tab = await facade.open("https://a.com/detail");
  333. expect(tab.id).toBe("t-1");
  334. expect(calls).toEqual([
  335. { method: "list" },
  336. { method: "activateTab", tabId: "t-1" },
  337. { method: "navigate", url: "https://a.com/detail", tabId: "t-1" },
  338. ]);
  339. });
  340. it("does not reuse a parent/child-host tab", async () => {
  341. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://shop.example.com/cart" }]);
  342. const tab = await facade.open("https://example.com");
  343. expect(tab.id).toBe("t-new");
  344. expect(calls).toEqual([
  345. { method: "list" },
  346. { method: "newTab" },
  347. { method: "navigate", url: "https://example.com", tabId: "t-new" },
  348. ]);
  349. });
  350. it("creates a new tab when nothing matches and ignores unusable tab urls", async () => {
  351. const { calls, facade } = reuseFacade([
  352. { tabId: "t-1", url: "https://a.com" },
  353. { tabId: "t-2", url: "::not-a-url::" },
  354. { tabId: "t-3" },
  355. ]);
  356. const tab = await facade.open("https://b.com");
  357. expect(tab.id).toBe("t-new");
  358. expect(calls).toEqual([
  359. { method: "list" },
  360. { method: "newTab" },
  361. { method: "navigate", url: "https://b.com", tabId: "t-new" },
  362. ]);
  363. });
  364. it("falls back to a new tab when listing fails", async () => {
  365. const calls: BrowserCommand[] = [];
  366. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  367. calls.push(command);
  368. if (command.method === "list") {
  369. return {
  370. ok: false,
  371. elapsedMs: 1,
  372. error: { code: "backend_unavailable", message: "backend gone" },
  373. } satisfies BrowserCommandResult;
  374. }
  375. if (command.method === "newTab") {
  376. return {
  377. ok: true,
  378. tab: { tabId: "t-new", url: "about:blank", title: "", viewport: { width: 1280, height: 720 } },
  379. elapsedMs: 1,
  380. } satisfies BrowserCommandResult;
  381. }
  382. return { ok: true, elapsedMs: 1 } satisfies BrowserCommandResult;
  383. });
  384. const tab = await createFacade(execute).open("https://example.com");
  385. expect(tab.id).toBe("t-new");
  386. expect(calls).toEqual([
  387. { method: "list" },
  388. { method: "newTab" },
  389. { method: "navigate", url: "https://example.com", tabId: "t-new" },
  390. ]);
  391. });
  392. it("creates a tab without listing when url is omitted", async () => {
  393. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://a.com" }]);
  394. const tab = await facade.open();
  395. expect(tab.id).toBe("t-new");
  396. expect(calls).toEqual([{ method: "newTab" }]);
  397. });
  398. it("skips reuse when reuseTab is false", async () => {
  399. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://example.com/docs" }]);
  400. const tab = await facade.open("https://example.com/docs", { reuseTab: false });
  401. expect(tab.id).toBe("t-new");
  402. expect(calls).toEqual([
  403. { method: "newTab" },
  404. { method: "navigate", url: "https://example.com/docs", tabId: "t-new" },
  405. ]);
  406. });
  407. it("prefers the active tab among equal-rank matches", async () => {
  408. const { calls, facade } = reuseFacade([
  409. { tabId: "t-1", url: "https://a.com/one" },
  410. { tabId: "t-2", url: "https://a.com/two", active: true },
  411. ]);
  412. const tab = await facade.open("https://a.com/three");
  413. expect(tab.id).toBe("t-2");
  414. expect(calls).toEqual([
  415. { method: "list" },
  416. { method: "activateTab", tabId: "t-2" },
  417. { method: "navigate", url: "https://a.com/three", tabId: "t-2" },
  418. ]);
  419. });
  420. it("falls back to the newest tab among equal-rank matches without an active one", async () => {
  421. const { calls, facade } = reuseFacade([
  422. { tabId: "t-1", url: "https://a.com/one" },
  423. { tabId: "t-2", url: "https://a.com/two" },
  424. ]);
  425. const tab = await facade.open("https://a.com/three");
  426. expect(tab.id).toBe("t-2");
  427. expect(calls).toEqual([
  428. { method: "list" },
  429. { method: "activateTab", tabId: "t-2" },
  430. { method: "navigate", url: "https://a.com/three", tabId: "t-2" },
  431. ]);
  432. });
  433. it("open() stays visible through the runtime proxy (manifest hideUnknown surface)", async () => {
  434. // 修复原因:SKILL.md 教模型调 agent.browsers.open(url),但 REPL 注入的是
  435. // asRuntimeObject() 的 hideUnknown 代理——open 不在 Browsers manifest 声明里
  436. // 时会被隐藏成 undefined,文档指引直接踩空。必须走真实代理路径验证。
  437. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://example.com/docs" }]);
  438. const runtime = facade.asRuntimeObject();
  439. expect(typeof runtime.open).toBe("function");
  440. const tab = await runtime.open("https://example.com/docs");
  441. expect(tab.id).toBe("t-1");
  442. expect(calls).toEqual([
  443. { method: "list" },
  444. { method: "activateTab", tabId: "t-1" },
  445. { method: "navigate", url: "https://example.com/docs", tabId: "t-1" },
  446. ]);
  447. });
  448. });
  449. it("browser.tabs list/selected/get/new map controlled tabs", async () => {
  450. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  451. if (command.method === "list") {
  452. return {
  453. ok: true,
  454. tabs: [
  455. {
  456. tabId: "t-1",
  457. url: "https://a.com",
  458. title: "A",
  459. viewport: { width: 1024, height: 768 },
  460. },
  461. {
  462. tabId: "t-2",
  463. url: "https://b.com",
  464. title: "B",
  465. active: true,
  466. viewport: { width: 1280, height: 720 },
  467. },
  468. ],
  469. elapsedMs: 1,
  470. };
  471. }
  472. if (command.method === "newTab") {
  473. return {
  474. ok: true,
  475. tab: {
  476. tabId: "t-3",
  477. url: "about:blank",
  478. title: "",
  479. active: true,
  480. viewport: { width: 1280, height: 720 },
  481. },
  482. elapsedMs: 1,
  483. };
  484. }
  485. if (command.method === "activateTab") {
  486. return {
  487. ok: true,
  488. tab: {
  489. tabId: command.tabId,
  490. url: "https://a.com",
  491. title: "A",
  492. active: true,
  493. viewport: { width: 1024, height: 768 },
  494. },
  495. elapsedMs: 1,
  496. };
  497. }
  498. return { ok: true, elapsedMs: 1 };
  499. });
  500. const browser = await createFacade(execute).getDefault();
  501. const tabs = await browser.tabs.list();
  502. expect(execute).toHaveBeenCalledWith({ method: "list" });
  503. expect(tabs[0]).toEqual({
  504. id: "t-1",
  505. url: "https://a.com",
  506. title: "A",
  507. viewport: { width: 1024, height: 768 },
  508. });
  509. expect(tabs[1]).toMatchObject({ id: "t-2", active: true });
  510. await expect(browser.tabs.selected()).resolves.toMatchObject({ tabId: "t-2" });
  511. await expect(browser.tabs.get("t-1")).resolves.toMatchObject({ tabId: "t-1" });
  512. expect(execute.mock.calls.slice(-2).map(([command]) => command)).toEqual([
  513. { method: "list" },
  514. { method: "activateTab", tabId: "t-1" },
  515. ]);
  516. await expect(browser.tabs.get("t-9")).rejects.toMatchObject({
  517. code: "backend_unavailable",
  518. });
  519. await expect(browser.tabs.new()).resolves.toMatchObject({ tabId: "t-3" });
  520. });
  521. it("对齐 BrowserUser claim、live tab state、capability collection 和 tabs.finalize", async () => {
  522. const commands: BrowserCommand[] = [];
  523. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  524. commands.push(command);
  525. if (command.method === "listUserTabs") {
  526. return {
  527. ok: true,
  528. userTabs: [{ id: "user-1", url: "https://user.example", title: "User" }],
  529. elapsedMs: 1,
  530. };
  531. }
  532. if (command.method === "claimTab") {
  533. return {
  534. ok: true,
  535. tab: {
  536. tabId: "user-1",
  537. url: "https://user.example",
  538. title: "User",
  539. viewport: { width: 1024, height: 768 },
  540. },
  541. elapsedMs: 1,
  542. };
  543. }
  544. if (command.method === "getState") {
  545. return {
  546. ok: true,
  547. state: {
  548. url: "https://user.example/live",
  549. title: "Live title",
  550. canGoBack: false,
  551. canGoForward: false,
  552. },
  553. elapsedMs: 1,
  554. };
  555. }
  556. if (command.method === "browserVisibilityGet") {
  557. return { ok: true, value: true, elapsedMs: 1 };
  558. }
  559. return { ok: true, elapsedMs: 1 };
  560. });
  561. const info: BrowserInfo = {
  562. ...IAB_INFO,
  563. apiSupportOverrides: {
  564. "BrowserUser.claimTab": true,
  565. "Tabs.finalize": true,
  566. "Tab.markDeliverable": true,
  567. "Tab.markHandoff": true,
  568. },
  569. capabilities: {
  570. browser: [{ id: "visibility", description: "Visibility" }],
  571. tab: [{ id: "pageAssets", description: "Assets" }],
  572. },
  573. };
  574. const browser = await createFacade(execute, [info]).getDefault();
  575. await expect(browser.capabilities.list()).resolves.toEqual([
  576. { id: "visibility", description: "Visibility" },
  577. ]);
  578. const visibility = await browser.capabilities.get("visibility");
  579. await visibility.set(true);
  580. await expect(visibility.get()).resolves.toBe(true);
  581. const userTab = (await browser.user.openTabs())[0]!;
  582. const tab = await browser.user.claimTab(userTab);
  583. expect(tab.viewportSize()).toEqual({ width: 1024, height: 768 });
  584. await tab.setViewportSize({ width: 1280, height: 720 });
  585. expect(tab.viewportSize()).toEqual({ width: 1280, height: 720 });
  586. await expect(tab.setViewportSize({ width: 319, height: 720 })).rejects.toThrow(
  587. "setViewportSize requires integer width 320..3840 and height 320..2160",
  588. );
  589. await expect(tab.url()).resolves.toBe("https://user.example/live");
  590. await expect(tab.title()).resolves.toBe("Live title");
  591. await expect(tab.capabilities.list()).resolves.toEqual([
  592. { id: "pageAssets", description: "Assets" },
  593. ]);
  594. await browser.tabs.finalize({ keep: [{ tab, status: "deliverable" }] });
  595. expect(commands).toContainEqual({
  596. method: "finalizeTabs",
  597. keep: [{ tabId: "user-1", status: "deliverable" }],
  598. });
  599. expect(commands).toContainEqual({ method: "browserVisibilitySet", visible: true });
  600. expect(commands).toContainEqual({
  601. method: "browserViewportSet",
  602. tabId: "user-1",
  603. width: 1280,
  604. height: 720,
  605. });
  606. });
  607. it("current()/listTabs()/tab(id) keep compatibility shortcuts", async () => {
  608. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  609. if (command.method === "list") {
  610. return {
  611. ok: true,
  612. tabs: [
  613. {
  614. tabId: "t-1",
  615. url: "https://a.com",
  616. title: "A",
  617. viewport: { width: 1024, height: 768 },
  618. },
  619. {
  620. tabId: "t-2",
  621. url: "https://b.com",
  622. title: "B",
  623. active: true,
  624. viewport: { width: 1280, height: 720 },
  625. },
  626. ],
  627. elapsedMs: 1,
  628. };
  629. }
  630. return { ok: true, elapsedMs: 1 };
  631. });
  632. const browsers = createFacade(execute);
  633. await expect(browsers.current()).resolves.toMatchObject({ tabId: "t-2" });
  634. await expect(browsers.listTabs()).resolves.toHaveLength(2);
  635. expect(browsers.tab("t-9").tabId).toBe("t-9");
  636. });
  637. it("direct methods return payloads and raw methods preserve BrowserCommandResult", async () => {
  638. const { execute, calls } = fakeExecute();
  639. const tab = createFacade(execute).tab("t-1");
  640. const snapshot = await tab.snapshot({ maxElements: 50 });
  641. expect(snapshot.elements[0].ref).toBe("e1");
  642. expect(snapshot.dom?.[0]).toMatchObject({ tag: "h1", text: "Example" });
  643. expect(calls.at(-1)).toMatchObject({ method: "snapshot", maxElements: 50, tabId: "t-1" });
  644. const bytes = await tab.screenshot();
  645. expect([...bytes]).toEqual([1, 2, 3]);
  646. expect(calls.at(-1)).toMatchObject({ method: "screenshot", tabId: "t-1" });
  647. const rawShot = await tab.raw.screenshot();
  648. expect(rawShot.image?.base64).toBe("AQID");
  649. await tab.click("e1", { button: "right", doubleClick: true });
  650. expect(calls.at(-1)).toMatchObject({
  651. method: "click",
  652. ref: "e1",
  653. button: "right",
  654. doubleClick: true,
  655. });
  656. await tab.type("hello", { ref: "e2" });
  657. expect(calls.at(-1)).toMatchObject({ method: "type", text: "hello", ref: "e2" });
  658. await tab.press("Enter", { modifiers: ["Meta"] });
  659. expect(calls.at(-1)).toMatchObject({ method: "press", key: "Enter", modifiers: ["Meta"] });
  660. await tab.scroll({ y: 300 });
  661. expect(calls.at(-1)).toMatchObject({ method: "scroll", y: 300 });
  662. });
  663. it("exposes async WebView recording start/status/cancel without a persistent JS kernel", async () => {
  664. const { execute, calls } = fakeExecute();
  665. const tab = createFacade(execute).tab("t-1");
  666. const started = await tab.recording.start({
  667. viewport: { width: 1280, height: 720 },
  668. actions: [
  669. { type: "wait", durationMs: 500 },
  670. { type: "click", selector: "#start" },
  671. ],
  672. });
  673. expect(started).toMatchObject({ id: "recording-1", status: "running" });
  674. expect(calls.at(-1)).toMatchObject({
  675. method: "recordingStart",
  676. tabId: "t-1",
  677. options: { viewport: { width: 1280, height: 720 } },
  678. });
  679. const completed = await tab.recording.status(started.id, {
  680. outputPath: "recordings/demo.webm",
  681. });
  682. expect(completed).toMatchObject({
  683. id: "recording-1",
  684. status: "completed",
  685. artifact: { path: "recordings/demo.webm", mimeType: "video/webm" },
  686. });
  687. expect(calls.at(-1)).toEqual({
  688. method: "recordingStatus",
  689. recordingId: "recording-1",
  690. outputPath: "recordings/demo.webm",
  691. tabId: "t-1",
  692. });
  693. await tab.recording.cancel(started.id);
  694. expect(calls.at(-1)).toEqual({
  695. method: "recordingCancel",
  696. recordingId: "recording-1",
  697. tabId: "t-1",
  698. });
  699. });
  700. it("throws BrowserCommandError on ok:false", async () => {
  701. const execute = vi.fn(
  702. async (): Promise<BrowserCommandResult> => ({
  703. ok: false,
  704. elapsedMs: 1,
  705. error: { code: "ref_not_found", message: "stale ref" },
  706. }),
  707. );
  708. const tab = createFacade(execute).tab("t-1");
  709. await expect(tab.click("old")).rejects.toBeInstanceOf(BrowserCommandError);
  710. await expect(tab.click("old")).rejects.toMatchObject({ code: "ref_not_found" });
  711. });
  712. it("locator 错误包装只保留一次原始 message,并附带 selector context", async () => {
  713. const execute = vi.fn(
  714. async (): Promise<BrowserCommandResult> => ({
  715. ok: false,
  716. elapsedMs: 3_000,
  717. error: { code: "timeout", message: "Timeout waiting for locator placeholder" },
  718. }),
  719. );
  720. const tab = createFacade(execute).tab("t-1");
  721. let caught: Error | undefined;
  722. try {
  723. await tab.playwright.getByPlaceholder("搜索").fill("zcode");
  724. } catch (error) {
  725. caught = error as Error;
  726. }
  727. expect(caught).toBeDefined();
  728. expect(caught?.message).toBe(
  729. 'Timeout waiting for locator placeholder\nlocator.fill failed for selector internal:attr=[placeholder="搜索"i]',
  730. );
  731. expect(caught?.stack?.match(/Timeout waiting for locator placeholder/g)).toHaveLength(1);
  732. expect(caught?.cause).toBeInstanceOf(BrowserCommandError);
  733. });
  734. it("additional methods construct expected commands", async () => {
  735. const { execute, calls } = fakeExecute();
  736. const tab = createFacade(execute).tab("t-9");
  737. await tab.hover("e1");
  738. expect(calls.at(-1)).toEqual({ method: "hover", ref: "e1", tabId: "t-9" });
  739. await tab.hover({ x: 10, y: 20 });
  740. expect(calls.at(-1)).toEqual({ method: "hover", x: 10, y: 20, tabId: "t-9" });
  741. await tab.select("e2", ["a", "b"]);
  742. expect(calls.at(-1)).toEqual({ method: "select", ref: "e2", values: ["a", "b"], tabId: "t-9" });
  743. await tab.check("e3", false);
  744. expect(calls.at(-1)).toEqual({ method: "check", ref: "e3", checked: false, tabId: "t-9" });
  745. await tab.drag("e4", { x: 3, y: 4 }, { modifiers: ["Shift"] });
  746. expect(calls.at(-1)).toEqual({
  747. method: "drag",
  748. fromRef: "e4",
  749. to: { x: 3, y: 4 },
  750. modifiers: ["Shift"],
  751. tabId: "t-9",
  752. });
  753. await tab.close();
  754. expect(calls.at(-1)).toEqual({ method: "close", tabId: "t-9" });
  755. await expect(tab.elementInfo(5, 6)).resolves.toMatchObject({ ref: "e1" });
  756. await expect(tab.evaluate("document.title")).resolves.toBe("value");
  757. await expect(tab.getDialog()).resolves.toBeNull();
  758. await tab.handleDialog(true, "answer");
  759. expect(calls.at(-1)).toEqual({
  760. method: "handleDialog",
  761. accept: true,
  762. promptText: "answer",
  763. tabId: "t-9",
  764. });
  765. expect((tab as unknown as { waitForTimeout?: unknown }).waitForTimeout).toBeUndefined();
  766. await tab.playwright.waitForTimeout(0);
  767. expect(calls.at(-1)).toEqual({
  768. method: "playwrightWaitForTimeout",
  769. timeoutMs: 0,
  770. tabId: "t-9",
  771. });
  772. });
  773. it("playwright.waitForTimeout 在 client 侧拒绝负数和非整数", async () => {
  774. const { execute } = fakeExecute();
  775. const tab = createFacade(execute).tab("t-1");
  776. await expect(tab.playwright.waitForTimeout(-1)).rejects.toThrow(
  777. "playwright.waitForTimeout requires a non-negative integer",
  778. );
  779. await expect(tab.playwright.waitForTimeout(1.5)).rejects.toThrow(
  780. "playwright.waitForTimeout requires a non-negative integer",
  781. );
  782. expect(execute).not.toHaveBeenCalled();
  783. });
  784. it("完整暴露 Playwright/Locator/FrameLocator 公共对象图", () => {
  785. expect(
  786. Object.getOwnPropertyNames(PlaywrightAPI.prototype).filter((name) => name !== "constructor"),
  787. ).toEqual(
  788. expect.arrayContaining([
  789. "domSnapshot",
  790. "elementInfo",
  791. "elementScreenshot",
  792. "evaluate",
  793. "expectNavigation",
  794. "frameLocator",
  795. "getByLabel",
  796. "getByPlaceholder",
  797. "getByRole",
  798. "getByTestId",
  799. "getByText",
  800. "locator",
  801. "waitForEvent",
  802. "waitForLoadState",
  803. "waitForTimeout",
  804. "waitForURL",
  805. ]),
  806. );
  807. expect(
  808. Object.getOwnPropertyNames(PlaywrightLocator.prototype).filter(
  809. (name) => !name.startsWith("_") && name !== "constructor",
  810. ),
  811. ).toEqual(
  812. expect.arrayContaining([
  813. "all",
  814. "allTextContents",
  815. "and",
  816. "check",
  817. "click",
  818. "count",
  819. "dblclick",
  820. "downloadMedia",
  821. "evaluate",
  822. "fill",
  823. "filter",
  824. "first",
  825. "getAttribute",
  826. "getByLabel",
  827. "getByPlaceholder",
  828. "getByRole",
  829. "getByTestId",
  830. "getByText",
  831. "innerText",
  832. "isEnabled",
  833. "isVisible",
  834. "last",
  835. "locator",
  836. "nth",
  837. "or",
  838. "press",
  839. "selectOption",
  840. "setChecked",
  841. "textContent",
  842. "type",
  843. "uncheck",
  844. "waitFor",
  845. ]),
  846. );
  847. expect(
  848. Object.getOwnPropertyNames(PlaywrightFrameLocator.prototype).filter(
  849. (name) => name !== "constructor",
  850. ),
  851. ).toEqual(
  852. expect.arrayContaining([
  853. "frameLocator",
  854. "getByLabel",
  855. "getByPlaceholder",
  856. "getByRole",
  857. "getByTestId",
  858. "getByText",
  859. "locator",
  860. ]),
  861. );
  862. });
  863. it("locator builder 惰性组合 selector,终结操作才发 command", async () => {
  864. const { execute, calls } = fakeExecute();
  865. const tab = createFacade(execute).tab("t-9");
  866. const locator = tab.playwright
  867. .getByRole("button", { name: "Save" })
  868. .filter({ hasText: "now", visible: true })
  869. .nth(1);
  870. expect(calls).toHaveLength(0);
  871. await expect(locator.count()).resolves.toBe(2);
  872. expect(calls.at(-1)).toEqual({
  873. method: "playwright",
  874. action: {
  875. name: "locator",
  876. operation: "count",
  877. selector:
  878. 'internal:role=button[name="Save"i] >> internal:has-text="now"i >> visible=true >> nth=1',
  879. },
  880. tabId: "t-9",
  881. });
  882. await locator.fill("saved", { timeoutMs: 1000 });
  883. expect(calls.at(-1)).toMatchObject({
  884. method: "playwright",
  885. action: {
  886. name: "locator",
  887. operation: "fill",
  888. replace: true,
  889. value: "saved",
  890. timeoutMs: 1000,
  891. },
  892. });
  893. });
  894. it("RegExp matcher 支持 node_repl VM 创建的跨 Realm 值", async () => {
  895. const { execute, calls } = fakeExecute();
  896. const tab = createFacade(execute).tab("t-cross-realm");
  897. const crossRealmName = runInNewContext("/维生素 C/i") as RegExp;
  898. await tab.playwright.getByRole("heading", { name: crossRealmName }).count();
  899. expect(calls.at(-1)).toMatchObject({
  900. method: "playwright",
  901. action: {
  902. name: "locator",
  903. operation: "count",
  904. selector: "internal:role=heading[name=/维生素 C/i]",
  905. },
  906. tabId: "t-cross-realm",
  907. });
  908. });
  909. it("page waits/evaluate/DOM helpers/download 映射为 direct-return 语义", async () => {
  910. const { execute, calls } = fakeExecute();
  911. const tab = createFacade(execute).tab("t-1");
  912. await expect(
  913. tab.playwright.evaluate((arg: { value: string }) => arg.value, { value: "x" }),
  914. ).resolves.toBe("evaluated");
  915. await expect(tab.playwright.domSnapshot()).resolves.toContain('- heading "Example"');
  916. await expect(tab.playwright.elementInfo({ x: 10, y: 20 })).resolves.toMatchObject([
  917. { tagName: "button" },
  918. ]);
  919. await expect(tab.playwright.elementScreenshot({ x: 10, y: 20 })).resolves.toEqual(
  920. new Uint8Array([1, 2, 3]),
  921. );
  922. await tab.playwright.waitForURL("https://example.com", { waitUntil: "load", timeoutMs: 500 });
  923. expect(calls.at(-1)).toMatchObject({
  924. method: "playwright",
  925. action: { name: "waitForURL", url: "https://example.com", waitUntil: "load", timeoutMs: 500 },
  926. });
  927. const download = await tab.playwright.waitForEvent("download");
  928. await expect(download.path()).resolves.toBe("/tmp/file.txt");
  929. });
  930. it("and/or/filter 拒绝跨 tab locator,expectNavigation 先 wait 后 action", async () => {
  931. const { execute, calls } = fakeExecute();
  932. const browsers = createFacade(execute);
  933. const left = browsers.tab("a").playwright.locator("button");
  934. const right = browsers.tab("b").playwright.locator("button");
  935. expect(() => left.and(right)).toThrow("Locators must belong to the same tab");
  936. const tab = browsers.tab("a");
  937. await tab.playwright.expectNavigation(() => tab.playwright.locator("a").click(), {
  938. url: "https://example.com",
  939. });
  940. const last = calls.slice(-2);
  941. expect(last[0]).toMatchObject({ method: "playwright", action: { name: "waitForURL" } });
  942. expect(last[1]).toMatchObject({
  943. method: "playwright",
  944. action: { name: "locator", operation: "click" },
  945. });
  946. });
  947. it("cua/dom_cua escape hatches use direct-return semantics", async () => {
  948. const { execute, calls } = fakeExecute();
  949. const tab = createFacade(execute).tab("t-1");
  950. await tab.cua.click({ x: 1, y: 2, button: 3 });
  951. expect(calls.at(-1)).toMatchObject({ method: "click", x: 1, y: 2, button: "right" });
  952. expect(() => tab.cua.click({ x: 1, y: 2, button: 4 })).toThrow(
  953. "Unsupported CUA mouse button: 4",
  954. );
  955. await tab.cua.double_click({ x: 3, y: 4 });
  956. expect(calls.at(-1)).toMatchObject({ method: "click", x: 3, y: 4, doubleClick: true });
  957. await tab.cua.move({ x: 5, y: 6, keys: ["Shift"] });
  958. expect(calls.at(-1)).toMatchObject({
  959. method: "hover",
  960. x: 5,
  961. y: 6,
  962. modifiers: ["Shift"],
  963. });
  964. await tab.cua.scroll({
  965. x: 5,
  966. y: 6,
  967. scrollX: 0,
  968. scrollY: 100,
  969. keypress: ["Control"],
  970. });
  971. expect(calls.at(-1)).toMatchObject({
  972. method: "cuaScroll",
  973. x: 5,
  974. y: 6,
  975. scrollX: 0,
  976. scrollY: 100,
  977. modifiers: ["Control"],
  978. });
  979. await tab.cua.drag({
  980. path: [
  981. { x: 1, y: 1 },
  982. { x: 4, y: 7 },
  983. { x: 9, y: 9 },
  984. ],
  985. });
  986. expect(calls.at(-1)).toMatchObject({
  987. method: "cuaDrag",
  988. path: [
  989. { x: 1, y: 1 },
  990. { x: 4, y: 7 },
  991. { x: 9, y: 9 },
  992. ],
  993. });
  994. await tab.cua.keypress({ keys: ["ControlOrMeta", "A"] });
  995. expect(calls.at(-1)).toMatchObject({
  996. method: "cuaKeypress",
  997. keys: ["ControlOrMeta", "A"],
  998. });
  999. await tab.cua.type({ text: "hi" });
  1000. expect(calls.at(-1)).toMatchObject({ method: "type", text: "hi" });
  1001. await expect(tab.dom_cua.get_visible_dom()).resolves.toMatchObject({
  1002. url: "https://example.com",
  1003. });
  1004. await tab.dom_cua.click({ node_id: "n1" });
  1005. expect(calls.at(-1)).toMatchObject({ method: "click", ref: "n1" });
  1006. await tab.dom_cua.scroll({ node_id: "n1", x: 3, y: 40 });
  1007. expect(calls.at(-1)).toMatchObject({
  1008. method: "domCuaScroll",
  1009. nodeId: "n1",
  1010. scrollX: 3,
  1011. scrollY: 40,
  1012. });
  1013. const strictTab = (await createFacade(execute).getDefault()).default;
  1014. expect("downloadMedia" in strictTab.cua).toBe(false);
  1015. expect("downloadMedia" in strictTab.dom_cua).toBe(false);
  1016. });
  1017. it("browser.documentation() and agent.documentation.get() load plugin docs", async () => {
  1018. const { execute } = fakeExecute();
  1019. const browsers = createFacade(execute, [IAB_INFO], {
  1020. documentationRoot: resolve(process.cwd(), "../browser-use-plugin/docs"),
  1021. });
  1022. const doc = await (await browsers.getDefault()).documentation();
  1023. for (const kw of [
  1024. "# Selected Browser",
  1025. "- Name: ZCode In-app Browser",
  1026. "- Type: iab",
  1027. "- ID: iab-runtime-1",
  1028. "API manifest",
  1029. 'agent.browsers.get("iab")',
  1030. "Tabs",
  1031. "BrowserCommandError",
  1032. "setViewportSize(viewportSize: { width: number; height: number })",
  1033. "viewportSize(): { width: number; height: number } | null",
  1034. "waitForTimeout(timeoutMs: number)",
  1035. "Never guess a label, accessible name, placeholder, selector, URL pattern",
  1036. "If the latest snapshot already contains the target",
  1037. "execute JavaScript in the page context",
  1038. "If `count() === 0`",
  1039. "at most 3000ms",
  1040. "do not loop over guessed URL variants",
  1041. "ambient UI state, not a browser-selection instruction",
  1042. ]) {
  1043. expect(doc).toContain(kw);
  1044. }
  1045. expect(doc).toContain("Recreate this browser wrapper in every fresh Browser Use call");
  1046. expect(doc).not.toContain("Reuse this browser binding across later turns");
  1047. expect(doc).not.toContain("# Screenshots");
  1048. expect(doc).toContain("nodeRepl.emitImage(await tab.screenshot())");
  1049. expect(doc).toContain("Never use tab.screenshot() as the final expression");
  1050. const globals: Record<string, unknown> = {};
  1051. setupBrowserRuntime({
  1052. globals,
  1053. transport: {
  1054. list: async () => [IAB_INFO],
  1055. execute: async () => ({ ok: true, elapsedMs: 0 }),
  1056. },
  1057. documentationRoot: resolve(process.cwd(), "../browser-use-plugin/docs"),
  1058. });
  1059. const screenshots = await (
  1060. globals.agent as { documentation: { get(name: string): Promise<string> } }
  1061. ).documentation.get("screenshots");
  1062. expect(screenshots).toContain("# Screenshots");
  1063. expect(screenshots).toContain("nodeRepl.emitImage(await tab.screenshot())");
  1064. expect(screenshots).toContain("Never use `await tab.screenshot()` as the final expression");
  1065. await expect(
  1066. (
  1067. globals.agent as { documentation: { get(name: string): Promise<string> } }
  1068. ).documentation.get("missing-guide"),
  1069. ).rejects.toThrow(/not found/i);
  1070. });
  1071. it("rejects a cached browser object once the runtime binding is stale", async () => {
  1072. const { execute } = fakeExecute();
  1073. let stale = false;
  1074. const assertAvailable = () => {
  1075. if (stale) throw new Error("Browser runtime binding is stale after kernel reset");
  1076. };
  1077. const browsers = createFacade(execute, [IAB_INFO], {
  1078. assertAvailable,
  1079. documentationRoot: resolve(process.cwd(), "../browser-use-plugin/docs"),
  1080. });
  1081. const iab = await browsers.get("iab");
  1082. await expect(iab.documentation()).resolves.toContain("# Selected Browser");
  1083. stale = true;
  1084. await expect(iab.documentation()).rejects.toThrow("stale");
  1085. await expect(iab.capabilities.list()).rejects.toThrow("stale");
  1086. await expect(iab.tabs.list()).rejects.toThrow("stale");
  1087. stale = false;
  1088. await expect(iab.documentation()).resolves.toContain("# Selected Browser");
  1089. });
  1090. it("exposes the PlaywrightAPI wait path without inventing a root Tab alias", async () => {
  1091. const { execute } = fakeExecute();
  1092. const tab = createFacade(execute).tab("t-1");
  1093. expect(typeof tab.playwright.waitForTimeout).toBe("function");
  1094. expect((tab as unknown as { waitForTimeout?: unknown }).waitForTimeout).toBeUndefined();
  1095. expect("waitForTimeout" in tab).toBe(false);
  1096. expect(
  1097. (tab.playwright as unknown as { setObjectWrapper?: unknown }).setObjectWrapper,
  1098. ).toBeUndefined();
  1099. const locator = tab.playwright.locator("button") as unknown as {
  1100. action?: unknown;
  1101. selector?: unknown;
  1102. };
  1103. expect(locator.action).toBeUndefined();
  1104. expect(locator.selector).toBeUndefined();
  1105. });
  1106. it("setupBrowserRuntime injects agent.browsers into globals", () => {
  1107. const { execute } = fakeExecute();
  1108. const globals: Record<string, unknown> = {};
  1109. setupBrowserRuntime({
  1110. globals,
  1111. transport: {
  1112. list: async () => [IAB_INFO],
  1113. execute: async (_browserId, _browserGeneration, command) => execute(command),
  1114. },
  1115. });
  1116. const agent = globals.agent as { browsers: BrowsersFacade };
  1117. expect(agent.browsers).toBeInstanceOf(BrowsersFacade);
  1118. expect(typeof agent.browsers.list).toBe("function");
  1119. // 设计反转(2026-08-24):open() 从「兼容入口、刻意隐藏」改为默认导航入口
  1120. // (同站复用 + 激活 + 原地跳转),必须在 hideUnknown 代理表面可见。
  1121. expect(typeof (agent.browsers as unknown as { open?: unknown }).open).toBe("function");
  1122. });
  1123. });