browser-client.test.ts 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  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([
  342. { tabId: "t-1", url: "https://shop.example.com/cart" },
  343. ]);
  344. const tab = await facade.open("https://example.com");
  345. expect(tab.id).toBe("t-new");
  346. expect(calls).toEqual([
  347. { method: "list" },
  348. { method: "newTab" },
  349. { method: "navigate", url: "https://example.com", tabId: "t-new" },
  350. ]);
  351. });
  352. it("creates a new tab when nothing matches and ignores unusable tab urls", async () => {
  353. const { calls, facade } = reuseFacade([
  354. { tabId: "t-1", url: "https://a.com" },
  355. { tabId: "t-2", url: "::not-a-url::" },
  356. { tabId: "t-3" },
  357. ]);
  358. const tab = await facade.open("https://b.com");
  359. expect(tab.id).toBe("t-new");
  360. expect(calls).toEqual([
  361. { method: "list" },
  362. { method: "newTab" },
  363. { method: "navigate", url: "https://b.com", tabId: "t-new" },
  364. ]);
  365. });
  366. it("falls back to a new tab when listing fails", async () => {
  367. const calls: BrowserCommand[] = [];
  368. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  369. calls.push(command);
  370. if (command.method === "list") {
  371. return {
  372. ok: false,
  373. elapsedMs: 1,
  374. error: { code: "backend_unavailable", message: "backend gone" },
  375. } satisfies BrowserCommandResult;
  376. }
  377. if (command.method === "newTab") {
  378. return {
  379. ok: true,
  380. tab: {
  381. tabId: "t-new",
  382. url: "about:blank",
  383. title: "",
  384. viewport: { width: 1280, height: 720 },
  385. },
  386. elapsedMs: 1,
  387. } satisfies BrowserCommandResult;
  388. }
  389. return { ok: true, elapsedMs: 1 } satisfies BrowserCommandResult;
  390. });
  391. const tab = await createFacade(execute).open("https://example.com");
  392. expect(tab.id).toBe("t-new");
  393. expect(calls).toEqual([
  394. { method: "list" },
  395. { method: "newTab" },
  396. { method: "navigate", url: "https://example.com", tabId: "t-new" },
  397. ]);
  398. });
  399. it("creates a tab without listing when url is omitted", async () => {
  400. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://a.com" }]);
  401. const tab = await facade.open();
  402. expect(tab.id).toBe("t-new");
  403. expect(calls).toEqual([{ method: "newTab" }]);
  404. });
  405. it("skips reuse when reuseTab is false", async () => {
  406. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://example.com/docs" }]);
  407. const tab = await facade.open("https://example.com/docs", { reuseTab: false });
  408. expect(tab.id).toBe("t-new");
  409. expect(calls).toEqual([
  410. { method: "newTab" },
  411. { method: "navigate", url: "https://example.com/docs", tabId: "t-new" },
  412. ]);
  413. });
  414. it("prefers the active tab among equal-rank matches", async () => {
  415. const { calls, facade } = reuseFacade([
  416. { tabId: "t-1", url: "https://a.com/one" },
  417. { tabId: "t-2", url: "https://a.com/two", active: true },
  418. ]);
  419. const tab = await facade.open("https://a.com/three");
  420. expect(tab.id).toBe("t-2");
  421. expect(calls).toEqual([
  422. { method: "list" },
  423. { method: "activateTab", tabId: "t-2" },
  424. { method: "navigate", url: "https://a.com/three", tabId: "t-2" },
  425. ]);
  426. });
  427. it("falls back to the newest tab among equal-rank matches without an active one", async () => {
  428. const { calls, facade } = reuseFacade([
  429. { tabId: "t-1", url: "https://a.com/one" },
  430. { tabId: "t-2", url: "https://a.com/two" },
  431. ]);
  432. const tab = await facade.open("https://a.com/three");
  433. expect(tab.id).toBe("t-2");
  434. expect(calls).toEqual([
  435. { method: "list" },
  436. { method: "activateTab", tabId: "t-2" },
  437. { method: "navigate", url: "https://a.com/three", tabId: "t-2" },
  438. ]);
  439. });
  440. it("open() stays visible through the runtime proxy (manifest hideUnknown surface)", async () => {
  441. // 修复原因:SKILL.md 教模型调 agent.browsers.open(url),但 REPL 注入的是
  442. // asRuntimeObject() 的 hideUnknown 代理——open 不在 Browsers manifest 声明里
  443. // 时会被隐藏成 undefined,文档指引直接踩空。必须走真实代理路径验证。
  444. const { calls, facade } = reuseFacade([{ tabId: "t-1", url: "https://example.com/docs" }]);
  445. const runtime = facade.asRuntimeObject();
  446. const tab = await runtime.open("https://example.com/docs");
  447. expect(tab.id).toBe("t-1");
  448. expect(calls).toEqual([
  449. { method: "list" },
  450. { method: "activateTab", tabId: "t-1" },
  451. { method: "navigate", url: "https://example.com/docs", tabId: "t-1" },
  452. ]);
  453. });
  454. });
  455. it("browser.tabs list/selected/get/new map controlled tabs", async () => {
  456. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  457. if (command.method === "list") {
  458. return {
  459. ok: true,
  460. tabs: [
  461. {
  462. tabId: "t-1",
  463. url: "https://a.com",
  464. title: "A",
  465. viewport: { width: 1024, height: 768 },
  466. },
  467. {
  468. tabId: "t-2",
  469. url: "https://b.com",
  470. title: "B",
  471. active: true,
  472. viewport: { width: 1280, height: 720 },
  473. },
  474. ],
  475. elapsedMs: 1,
  476. };
  477. }
  478. if (command.method === "newTab") {
  479. return {
  480. ok: true,
  481. tab: {
  482. tabId: "t-3",
  483. url: "about:blank",
  484. title: "",
  485. active: true,
  486. viewport: { width: 1280, height: 720 },
  487. },
  488. elapsedMs: 1,
  489. };
  490. }
  491. if (command.method === "activateTab") {
  492. return {
  493. ok: true,
  494. tab: {
  495. tabId: command.tabId,
  496. url: "https://a.com",
  497. title: "A",
  498. active: true,
  499. viewport: { width: 1024, height: 768 },
  500. },
  501. elapsedMs: 1,
  502. };
  503. }
  504. return { ok: true, elapsedMs: 1 };
  505. });
  506. const browser = await createFacade(execute).getDefault();
  507. const tabs = await browser.tabs.list();
  508. expect(execute).toHaveBeenCalledWith({ method: "list" });
  509. expect(tabs[0]).toEqual({
  510. id: "t-1",
  511. url: "https://a.com",
  512. title: "A",
  513. viewport: { width: 1024, height: 768 },
  514. });
  515. expect(tabs[1]).toMatchObject({ id: "t-2", active: true });
  516. await expect(browser.tabs.selected()).resolves.toMatchObject({ tabId: "t-2" });
  517. await expect(browser.tabs.get("t-1")).resolves.toMatchObject({ tabId: "t-1" });
  518. expect(execute.mock.calls.slice(-2).map(([command]) => command)).toEqual([
  519. { method: "list" },
  520. { method: "activateTab", tabId: "t-1" },
  521. ]);
  522. await expect(browser.tabs.get("t-9")).rejects.toMatchObject({
  523. code: "backend_unavailable",
  524. });
  525. await expect(browser.tabs.new()).resolves.toMatchObject({ tabId: "t-3" });
  526. });
  527. it("对齐 BrowserUser claim、live tab state、capability collection 和 tabs.finalize", async () => {
  528. const commands: BrowserCommand[] = [];
  529. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  530. commands.push(command);
  531. if (command.method === "listUserTabs") {
  532. return {
  533. ok: true,
  534. userTabs: [{ id: "user-1", url: "https://user.example", title: "User" }],
  535. elapsedMs: 1,
  536. };
  537. }
  538. if (command.method === "claimTab") {
  539. return {
  540. ok: true,
  541. tab: {
  542. tabId: "user-1",
  543. url: "https://user.example",
  544. title: "User",
  545. viewport: { width: 1024, height: 768 },
  546. },
  547. elapsedMs: 1,
  548. };
  549. }
  550. if (command.method === "getState") {
  551. return {
  552. ok: true,
  553. state: {
  554. url: "https://user.example/live",
  555. title: "Live title",
  556. canGoBack: false,
  557. canGoForward: false,
  558. },
  559. elapsedMs: 1,
  560. };
  561. }
  562. if (command.method === "browserVisibilityGet") {
  563. return { ok: true, value: true, elapsedMs: 1 };
  564. }
  565. return { ok: true, elapsedMs: 1 };
  566. });
  567. const info: BrowserInfo = {
  568. ...IAB_INFO,
  569. apiSupportOverrides: {
  570. "BrowserUser.claimTab": true,
  571. "Tabs.finalize": true,
  572. "Tab.markDeliverable": true,
  573. "Tab.markHandoff": true,
  574. },
  575. capabilities: {
  576. browser: [{ id: "visibility", description: "Visibility" }],
  577. tab: [{ id: "pageAssets", description: "Assets" }],
  578. },
  579. };
  580. const browser = await createFacade(execute, [info]).getDefault();
  581. await expect(browser.capabilities.list()).resolves.toEqual([
  582. { id: "visibility", description: "Visibility" },
  583. ]);
  584. const visibility = await browser.capabilities.get("visibility");
  585. await visibility.set(true);
  586. await expect(visibility.get()).resolves.toBe(true);
  587. const userTab = (await browser.user.openTabs())[0]!;
  588. const tab = await browser.user.claimTab(userTab);
  589. expect(tab.viewportSize()).toEqual({ width: 1024, height: 768 });
  590. await tab.setViewportSize({ width: 1280, height: 720 });
  591. expect(tab.viewportSize()).toEqual({ width: 1280, height: 720 });
  592. await expect(tab.setViewportSize({ width: 319, height: 720 })).rejects.toThrow(
  593. "setViewportSize requires integer width 320..3840 and height 320..2160",
  594. );
  595. await expect(tab.url()).resolves.toBe("https://user.example/live");
  596. await expect(tab.title()).resolves.toBe("Live title");
  597. await expect(tab.capabilities.list()).resolves.toEqual([
  598. { id: "pageAssets", description: "Assets" },
  599. ]);
  600. await browser.tabs.finalize({ keep: [{ tab, status: "deliverable" }] });
  601. expect(commands).toContainEqual({
  602. method: "finalizeTabs",
  603. keep: [{ tabId: "user-1", status: "deliverable" }],
  604. });
  605. expect(commands).toContainEqual({ method: "browserVisibilitySet", visible: true });
  606. expect(commands).toContainEqual({
  607. method: "browserViewportSet",
  608. tabId: "user-1",
  609. width: 1280,
  610. height: 720,
  611. });
  612. });
  613. it("current()/listTabs() keep compatibility shortcuts", async () => {
  614. const execute = vi.fn(async (command: BrowserCommand): Promise<BrowserCommandResult> => {
  615. if (command.method === "list") {
  616. return {
  617. ok: true,
  618. tabs: [
  619. {
  620. tabId: "t-1",
  621. url: "https://a.com",
  622. title: "A",
  623. viewport: { width: 1024, height: 768 },
  624. },
  625. {
  626. tabId: "t-2",
  627. url: "https://b.com",
  628. title: "B",
  629. active: true,
  630. viewport: { width: 1280, height: 720 },
  631. },
  632. ],
  633. elapsedMs: 1,
  634. };
  635. }
  636. return { ok: true, elapsedMs: 1 };
  637. });
  638. const browsers = createFacade(execute);
  639. await expect(browsers.current()).resolves.toMatchObject({ tabId: "t-2" });
  640. await expect(browsers.listTabs()).resolves.toHaveLength(2);
  641. });
  642. it("direct methods return payloads and raw methods preserve BrowserCommandResult", async () => {
  643. const { execute, calls } = fakeExecute();
  644. const tab = createFacade(execute).tab("t-1");
  645. const snapshot = await tab.snapshot({ maxElements: 50 });
  646. expect(snapshot.elements[0].ref).toBe("e1");
  647. expect(snapshot.dom?.[0]).toMatchObject({ tag: "h1", text: "Example" });
  648. expect(calls.at(-1)).toMatchObject({ method: "snapshot", maxElements: 50, tabId: "t-1" });
  649. const bytes = await tab.screenshot();
  650. expect([...bytes]).toEqual([1, 2, 3]);
  651. expect(calls.at(-1)).toMatchObject({ method: "screenshot", tabId: "t-1" });
  652. const rawShot = await tab.raw.screenshot();
  653. expect(rawShot.image?.base64).toBe("AQID");
  654. await tab.click("e1", { button: "right", doubleClick: true });
  655. expect(calls.at(-1)).toMatchObject({
  656. method: "click",
  657. ref: "e1",
  658. button: "right",
  659. doubleClick: true,
  660. });
  661. await tab.type("hello", { ref: "e2" });
  662. expect(calls.at(-1)).toMatchObject({ method: "type", text: "hello", ref: "e2" });
  663. await tab.press("Enter", { modifiers: ["Meta"] });
  664. expect(calls.at(-1)).toMatchObject({ method: "press", key: "Enter", modifiers: ["Meta"] });
  665. await tab.scroll({ y: 300 });
  666. expect(calls.at(-1)).toMatchObject({ method: "scroll", y: 300 });
  667. });
  668. it("exposes async WebView recording start/status/cancel without a persistent JS kernel", async () => {
  669. const { execute, calls } = fakeExecute();
  670. const tab = createFacade(execute).tab("t-1");
  671. const started = await tab.recording.start({
  672. viewport: { width: 1280, height: 720 },
  673. actions: [
  674. { type: "wait", durationMs: 500 },
  675. { type: "click", selector: "#start" },
  676. ],
  677. });
  678. expect(started).toMatchObject({ id: "recording-1", status: "running" });
  679. expect(calls.at(-1)).toMatchObject({
  680. method: "recordingStart",
  681. tabId: "t-1",
  682. options: { viewport: { width: 1280, height: 720 } },
  683. });
  684. const completed = await tab.recording.status(started.id, {
  685. outputPath: "recordings/demo.webm",
  686. });
  687. expect(completed).toMatchObject({
  688. id: "recording-1",
  689. status: "completed",
  690. artifact: { path: "recordings/demo.webm", mimeType: "video/webm" },
  691. });
  692. expect(calls.at(-1)).toEqual({
  693. method: "recordingStatus",
  694. recordingId: "recording-1",
  695. outputPath: "recordings/demo.webm",
  696. tabId: "t-1",
  697. });
  698. await tab.recording.cancel(started.id);
  699. expect(calls.at(-1)).toEqual({
  700. method: "recordingCancel",
  701. recordingId: "recording-1",
  702. tabId: "t-1",
  703. });
  704. });
  705. it("throws BrowserCommandError on ok:false", async () => {
  706. const execute = vi.fn(
  707. async (): Promise<BrowserCommandResult> => ({
  708. ok: false,
  709. elapsedMs: 1,
  710. error: { code: "ref_not_found", message: "stale ref" },
  711. }),
  712. );
  713. const tab = createFacade(execute).tab("t-1");
  714. await expect(tab.click("old")).rejects.toBeInstanceOf(BrowserCommandError);
  715. await expect(tab.click("old")).rejects.toMatchObject({ code: "ref_not_found" });
  716. });
  717. it("locator 错误包装只保留一次原始 message,并附带 selector context", async () => {
  718. const execute = vi.fn(
  719. async (): Promise<BrowserCommandResult> => ({
  720. ok: false,
  721. elapsedMs: 3_000,
  722. error: { code: "timeout", message: "Timeout waiting for locator placeholder" },
  723. }),
  724. );
  725. const tab = createFacade(execute).tab("t-1");
  726. let caught: Error | undefined;
  727. try {
  728. await tab.playwright.getByPlaceholder("搜索").fill("zcode");
  729. } catch (error) {
  730. caught = error as Error;
  731. }
  732. expect(caught).toBeDefined();
  733. expect(caught?.message).toBe(
  734. 'Timeout waiting for locator placeholder\nlocator.fill failed for selector internal:attr=[placeholder="搜索"i]',
  735. );
  736. expect(caught?.stack?.match(/Timeout waiting for locator placeholder/g)).toHaveLength(1);
  737. expect(caught?.cause).toBeInstanceOf(BrowserCommandError);
  738. });
  739. it("additional methods construct expected commands", async () => {
  740. const { execute, calls } = fakeExecute();
  741. const tab = createFacade(execute).tab("t-9");
  742. await tab.hover("e1");
  743. expect(calls.at(-1)).toEqual({ method: "hover", ref: "e1", tabId: "t-9" });
  744. await tab.hover({ x: 10, y: 20 });
  745. expect(calls.at(-1)).toEqual({ method: "hover", x: 10, y: 20, tabId: "t-9" });
  746. await tab.select("e2", ["a", "b"]);
  747. expect(calls.at(-1)).toEqual({ method: "select", ref: "e2", values: ["a", "b"], tabId: "t-9" });
  748. await tab.check("e3", false);
  749. expect(calls.at(-1)).toEqual({ method: "check", ref: "e3", checked: false, tabId: "t-9" });
  750. await tab.drag("e4", { x: 3, y: 4 }, { modifiers: ["Shift"] });
  751. expect(calls.at(-1)).toEqual({
  752. method: "drag",
  753. fromRef: "e4",
  754. to: { x: 3, y: 4 },
  755. modifiers: ["Shift"],
  756. tabId: "t-9",
  757. });
  758. await tab.close();
  759. expect(calls.at(-1)).toEqual({ method: "close", tabId: "t-9" });
  760. await expect(tab.elementInfo(5, 6)).resolves.toMatchObject({ ref: "e1" });
  761. await expect(tab.evaluate("document.title")).resolves.toBe("value");
  762. await expect(tab.getDialog()).resolves.toBeNull();
  763. await tab.handleDialog(true, "answer");
  764. expect(calls.at(-1)).toEqual({
  765. method: "handleDialog",
  766. accept: true,
  767. promptText: "answer",
  768. tabId: "t-9",
  769. });
  770. expect((tab as unknown as { waitForTimeout?: unknown }).waitForTimeout).toBeUndefined();
  771. await tab.playwright.waitForTimeout(0);
  772. expect(calls.at(-1)).toEqual({
  773. method: "playwrightWaitForTimeout",
  774. timeoutMs: 0,
  775. tabId: "t-9",
  776. });
  777. });
  778. it("playwright.waitForTimeout 在 client 侧拒绝负数和非整数", async () => {
  779. const { execute } = fakeExecute();
  780. const tab = createFacade(execute).tab("t-1");
  781. await expect(tab.playwright.waitForTimeout(-1)).rejects.toThrow(
  782. "playwright.waitForTimeout requires a non-negative integer",
  783. );
  784. await expect(tab.playwright.waitForTimeout(1.5)).rejects.toThrow(
  785. "playwright.waitForTimeout requires a non-negative integer",
  786. );
  787. expect(execute).not.toHaveBeenCalled();
  788. });
  789. it("完整暴露 Playwright/Locator/FrameLocator 公共对象图", () => {
  790. expect(
  791. Object.getOwnPropertyNames(PlaywrightAPI.prototype).filter((name) => name !== "constructor"),
  792. ).toEqual(
  793. expect.arrayContaining([
  794. "domSnapshot",
  795. "elementInfo",
  796. "elementScreenshot",
  797. "evaluate",
  798. "expectNavigation",
  799. "frameLocator",
  800. "getByLabel",
  801. "getByPlaceholder",
  802. "getByRole",
  803. "getByTestId",
  804. "getByText",
  805. "locator",
  806. "waitForEvent",
  807. "waitForLoadState",
  808. "waitForTimeout",
  809. "waitForURL",
  810. ]),
  811. );
  812. expect(
  813. Object.getOwnPropertyNames(PlaywrightLocator.prototype).filter(
  814. (name) => !name.startsWith("_") && name !== "constructor",
  815. ),
  816. ).toEqual(
  817. expect.arrayContaining([
  818. "all",
  819. "allTextContents",
  820. "and",
  821. "check",
  822. "click",
  823. "count",
  824. "dblclick",
  825. "downloadMedia",
  826. "evaluate",
  827. "fill",
  828. "filter",
  829. "first",
  830. "getAttribute",
  831. "getByLabel",
  832. "getByPlaceholder",
  833. "getByRole",
  834. "getByTestId",
  835. "getByText",
  836. "innerText",
  837. "isEnabled",
  838. "isVisible",
  839. "last",
  840. "locator",
  841. "nth",
  842. "or",
  843. "press",
  844. "selectOption",
  845. "setChecked",
  846. "textContent",
  847. "type",
  848. "uncheck",
  849. "waitFor",
  850. ]),
  851. );
  852. expect(
  853. Object.getOwnPropertyNames(PlaywrightFrameLocator.prototype).filter(
  854. (name) => name !== "constructor",
  855. ),
  856. ).toEqual(
  857. expect.arrayContaining([
  858. "frameLocator",
  859. "getByLabel",
  860. "getByPlaceholder",
  861. "getByRole",
  862. "getByTestId",
  863. "getByText",
  864. "locator",
  865. ]),
  866. );
  867. });
  868. it("locator builder 惰性组合 selector,终结操作才发 command", async () => {
  869. const { execute, calls } = fakeExecute();
  870. const tab = createFacade(execute).tab("t-9");
  871. const locator = tab.playwright
  872. .getByRole("button", { name: "Save" })
  873. .filter({ hasText: "now", visible: true })
  874. .nth(1);
  875. expect(calls).toHaveLength(0);
  876. await expect(locator.count()).resolves.toBe(2);
  877. expect(calls.at(-1)).toEqual({
  878. method: "playwright",
  879. action: {
  880. name: "locator",
  881. operation: "count",
  882. selector:
  883. 'internal:role=button[name="Save"i] >> internal:has-text="now"i >> visible=true >> nth=1',
  884. },
  885. tabId: "t-9",
  886. });
  887. await locator.fill("saved", { timeoutMs: 1000 });
  888. expect(calls.at(-1)).toMatchObject({
  889. method: "playwright",
  890. action: {
  891. name: "locator",
  892. operation: "fill",
  893. replace: true,
  894. value: "saved",
  895. timeoutMs: 1000,
  896. },
  897. });
  898. });
  899. it("RegExp matcher 支持 node_repl VM 创建的跨 Realm 值", async () => {
  900. const { execute, calls } = fakeExecute();
  901. const tab = createFacade(execute).tab("t-cross-realm");
  902. const crossRealmName = runInNewContext("/维生素 C/i") as RegExp;
  903. await tab.playwright.getByRole("heading", { name: crossRealmName }).count();
  904. expect(calls.at(-1)).toMatchObject({
  905. method: "playwright",
  906. action: {
  907. name: "locator",
  908. operation: "count",
  909. selector: "internal:role=heading[name=/维生素 C/i]",
  910. },
  911. tabId: "t-cross-realm",
  912. });
  913. });
  914. it("page waits/evaluate/DOM helpers/download 映射为 direct-return 语义", async () => {
  915. const { execute, calls } = fakeExecute();
  916. const tab = createFacade(execute).tab("t-1");
  917. await expect(
  918. tab.playwright.evaluate((arg: { value: string }) => arg.value, { value: "x" }),
  919. ).resolves.toBe("evaluated");
  920. await expect(tab.playwright.domSnapshot()).resolves.toContain('- heading "Example"');
  921. await expect(tab.playwright.elementInfo({ x: 10, y: 20 })).resolves.toMatchObject([
  922. { tagName: "button" },
  923. ]);
  924. await expect(tab.playwright.elementScreenshot({ x: 10, y: 20 })).resolves.toEqual(
  925. new Uint8Array([1, 2, 3]),
  926. );
  927. await tab.playwright.waitForURL("https://example.com", { waitUntil: "load", timeoutMs: 500 });
  928. expect(calls.at(-1)).toMatchObject({
  929. method: "playwright",
  930. action: { name: "waitForURL", url: "https://example.com", waitUntil: "load", timeoutMs: 500 },
  931. });
  932. const download = await tab.playwright.waitForEvent("download");
  933. await expect(download.path()).resolves.toBe("/tmp/file.txt");
  934. });
  935. it("and/or/filter 拒绝跨 tab locator,expectNavigation 先 wait 后 action", async () => {
  936. const { execute, calls } = fakeExecute();
  937. const browsers = createFacade(execute);
  938. const left = browsers.tab("a").playwright.locator("button");
  939. const right = browsers.tab("b").playwright.locator("button");
  940. expect(() => left.and(right)).toThrow("Locators must belong to the same tab");
  941. const tab = browsers.tab("a");
  942. await tab.playwright.expectNavigation(() => tab.playwright.locator("a").click(), {
  943. url: "https://example.com",
  944. });
  945. const last = calls.slice(-2);
  946. expect(last[0]).toMatchObject({ method: "playwright", action: { name: "waitForURL" } });
  947. expect(last[1]).toMatchObject({
  948. method: "playwright",
  949. action: { name: "locator", operation: "click" },
  950. });
  951. });
  952. it("cua/dom_cua escape hatches use direct-return semantics", async () => {
  953. const { execute, calls } = fakeExecute();
  954. const tab = createFacade(execute).tab("t-1");
  955. await tab.cua.click({ x: 1, y: 2, button: 3 });
  956. expect(calls.at(-1)).toMatchObject({ method: "click", x: 1, y: 2, button: "right" });
  957. expect(() => tab.cua.click({ x: 1, y: 2, button: 4 })).toThrow(
  958. "Unsupported CUA mouse button: 4",
  959. );
  960. await tab.cua.double_click({ x: 3, y: 4 });
  961. expect(calls.at(-1)).toMatchObject({ method: "click", x: 3, y: 4, doubleClick: true });
  962. await tab.cua.move({ x: 5, y: 6, keys: ["Shift"] });
  963. expect(calls.at(-1)).toMatchObject({
  964. method: "hover",
  965. x: 5,
  966. y: 6,
  967. modifiers: ["Shift"],
  968. });
  969. await tab.cua.scroll({
  970. x: 5,
  971. y: 6,
  972. scrollX: 0,
  973. scrollY: 100,
  974. keypress: ["Control"],
  975. });
  976. expect(calls.at(-1)).toMatchObject({
  977. method: "cuaScroll",
  978. x: 5,
  979. y: 6,
  980. scrollX: 0,
  981. scrollY: 100,
  982. modifiers: ["Control"],
  983. });
  984. await tab.cua.drag({
  985. path: [
  986. { x: 1, y: 1 },
  987. { x: 4, y: 7 },
  988. { x: 9, y: 9 },
  989. ],
  990. });
  991. expect(calls.at(-1)).toMatchObject({
  992. method: "cuaDrag",
  993. path: [
  994. { x: 1, y: 1 },
  995. { x: 4, y: 7 },
  996. { x: 9, y: 9 },
  997. ],
  998. });
  999. await tab.cua.keypress({ keys: ["ControlOrMeta", "A"] });
  1000. expect(calls.at(-1)).toMatchObject({
  1001. method: "cuaKeypress",
  1002. keys: ["ControlOrMeta", "A"],
  1003. });
  1004. await tab.cua.type({ text: "hi" });
  1005. expect(calls.at(-1)).toMatchObject({ method: "type", text: "hi" });
  1006. await expect(tab.dom_cua.get_visible_dom()).resolves.toMatchObject({
  1007. url: "https://example.com",
  1008. });
  1009. await tab.dom_cua.click({ node_id: "n1" });
  1010. expect(calls.at(-1)).toMatchObject({ method: "click", ref: "n1" });
  1011. await tab.dom_cua.scroll({ node_id: "n1", x: 3, y: 40 });
  1012. expect(calls.at(-1)).toMatchObject({
  1013. method: "domCuaScroll",
  1014. nodeId: "n1",
  1015. scrollX: 3,
  1016. scrollY: 40,
  1017. });
  1018. const strictTab = (await createFacade(execute).getDefault()).default;
  1019. expect("downloadMedia" in strictTab.cua).toBe(false);
  1020. expect("downloadMedia" in strictTab.dom_cua).toBe(false);
  1021. });
  1022. it("browser.documentation() and agent.documentation.get() load plugin docs", async () => {
  1023. const { execute } = fakeExecute();
  1024. const browsers = createFacade(execute, [IAB_INFO], {
  1025. documentationRoot: resolve(process.cwd(), "../browser-use-plugin/docs"),
  1026. });
  1027. const doc = await (await browsers.getDefault()).documentation();
  1028. for (const kw of [
  1029. "# Selected Browser",
  1030. "- Name: ZCode In-app Browser",
  1031. "- Type: iab",
  1032. "- ID: iab-runtime-1",
  1033. "API manifest",
  1034. 'agent.browsers.get("iab")',
  1035. "Tabs",
  1036. "BrowserCommandError",
  1037. "setViewportSize(viewportSize: { width: number; height: number })",
  1038. "viewportSize(): { width: number; height: number } | null",
  1039. "waitForTimeout(timeoutMs: number)",
  1040. "Never guess a label, accessible name, placeholder, selector, URL pattern",
  1041. "If the latest snapshot already contains the target",
  1042. "execute JavaScript in the page context",
  1043. "If `count() === 0`",
  1044. "at most 3000ms",
  1045. "do not loop over guessed URL variants",
  1046. "ambient UI state, not a browser-selection instruction",
  1047. ]) {
  1048. expect(doc).toContain(kw);
  1049. }
  1050. expect(doc).toContain("Recreate this browser wrapper in every fresh Browser Use call");
  1051. expect(doc).not.toContain("Reuse this browser binding across later turns");
  1052. expect(doc).not.toContain("# Screenshots");
  1053. expect(doc).toContain("nodeRepl.emitImage(await tab.screenshot())");
  1054. expect(doc).toContain("Never use tab.screenshot() as the final expression");
  1055. const globals: Record<string, unknown> = {};
  1056. setupBrowserRuntime({
  1057. globals,
  1058. transport: {
  1059. list: async () => [IAB_INFO],
  1060. execute: async () => ({ ok: true, elapsedMs: 0 }),
  1061. },
  1062. documentationRoot: resolve(process.cwd(), "../browser-use-plugin/docs"),
  1063. });
  1064. const screenshots = await (
  1065. globals.agent as { documentation: { get(name: string): Promise<string> } }
  1066. ).documentation.get("screenshots");
  1067. expect(screenshots).toContain("# Screenshots");
  1068. expect(screenshots).toContain("nodeRepl.emitImage(await tab.screenshot())");
  1069. expect(screenshots).toContain("Never use `await tab.screenshot()` as the final expression");
  1070. await expect(
  1071. (
  1072. globals.agent as { documentation: { get(name: string): Promise<string> } }
  1073. ).documentation.get("missing-guide"),
  1074. ).rejects.toThrow(/not found/i);
  1075. });
  1076. it("rejects a cached browser object once the runtime binding is stale", async () => {
  1077. const { execute } = fakeExecute();
  1078. let stale = false;
  1079. const assertAvailable = () => {
  1080. if (stale) throw new Error("Browser runtime binding is stale after kernel reset");
  1081. };
  1082. const browsers = createFacade(execute, [IAB_INFO], {
  1083. assertAvailable,
  1084. documentationRoot: resolve(process.cwd(), "../browser-use-plugin/docs"),
  1085. });
  1086. const iab = await browsers.get("iab");
  1087. await expect(iab.documentation()).resolves.toContain("# Selected Browser");
  1088. stale = true;
  1089. await expect(iab.documentation()).rejects.toThrow("stale");
  1090. await expect(iab.capabilities.list()).rejects.toThrow("stale");
  1091. await expect(iab.tabs.list()).rejects.toThrow("stale");
  1092. stale = false;
  1093. await expect(iab.documentation()).resolves.toContain("# Selected Browser");
  1094. });
  1095. it("exposes the PlaywrightAPI wait path without inventing a root Tab alias", async () => {
  1096. const { execute } = fakeExecute();
  1097. const tab = createFacade(execute).tab("t-1");
  1098. expect(typeof tab.playwright.waitForTimeout).toBe("function");
  1099. expect((tab as unknown as { waitForTimeout?: unknown }).waitForTimeout).toBeUndefined();
  1100. expect("waitForTimeout" in tab).toBe(false);
  1101. expect(
  1102. (tab.playwright as unknown as { setObjectWrapper?: unknown }).setObjectWrapper,
  1103. ).toBeUndefined();
  1104. const locator = tab.playwright.locator("button") as unknown as {
  1105. action?: unknown;
  1106. selector?: unknown;
  1107. };
  1108. expect(locator.action).toBeUndefined();
  1109. expect(locator.selector).toBeUndefined();
  1110. });
  1111. it("setupBrowserRuntime injects agent.browsers into globals", () => {
  1112. const { execute } = fakeExecute();
  1113. const globals: Record<string, unknown> = {};
  1114. setupBrowserRuntime({
  1115. globals,
  1116. transport: {
  1117. list: async () => [IAB_INFO],
  1118. execute: async (_browserId, _browserGeneration, command) => execute(command),
  1119. },
  1120. });
  1121. const agent = globals.agent as { browsers: BrowsersFacade };
  1122. expect(agent.browsers).toBeInstanceOf(BrowsersFacade);
  1123. expect(typeof agent.browsers.list).toBe("function");
  1124. // 设计反转(2026-08-24):open() 从「兼容入口、刻意隐藏」改为默认导航入口
  1125. // (同站复用 + 激活 + 原地跳转),必须在 hideUnknown 代理表面可见。
  1126. expect(typeof (agent.browsers as unknown as { open?: unknown }).open).toBe("function");
  1127. });
  1128. });