browser-manifest.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. import { readFileSync } from "node:fs";
  2. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join, resolve } from "node:path";
  5. import { describe, expect, it } from "vitest";
  6. import type { BrowserInfo } from "../src/browser-client/index.js";
  7. import {
  8. BrowserApiPolicy,
  9. createBrowserApiProxy,
  10. loadBrowserApiManifest,
  11. } from "../src/browser-client/index.js";
  12. import { loadBrowserDocumentation } from "../src/browser-client/documentation.js";
  13. import { NodeReplSession } from "../src/repl/node-repl-session.js";
  14. const docsRoot = resolve(process.cwd(), "../browser-use-plugin/docs");
  15. const skillPath = resolve(process.cwd(), "../browser-use-plugin/skills/control-browser/SKILL.md");
  16. const overviewPath = resolve(docsRoot, "overview.md");
  17. const workflowPath = resolve(docsRoot, "workflow.md");
  18. const playwrightPath = resolve(docsRoot, "playwright.md");
  19. const testerSkillPath = resolve(
  20. process.cwd(),
  21. "../browser-use-plugin/skills/web-gui-tester/SKILL.md",
  22. );
  23. const iab: BrowserInfo = {
  24. id: "iab-runtime-1",
  25. generation: 3,
  26. type: "iab",
  27. name: "IAB",
  28. capabilities: { browser: [], tab: [{ id: "dom-cua", description: "DOM" }] },
  29. apiSupportOverrides: {
  30. "BrowserUser.claimTab": true,
  31. "Tabs.finalize": true,
  32. "Tab.markDeliverable": true,
  33. "Tab.markHandoff": true,
  34. },
  35. };
  36. describe("browser capability manifest", () => {
  37. it("web GUI tester stays agnostic to the browser automation tooling available in the session", () => {
  38. const skill = readFileSync(testerSkillPath, "utf8");
  39. expect(skill).toContain("whatever browser automation tooling the session actually provides");
  40. expect(skill).toContain("This skill defines the testing methodology only");
  41. expect(skill).toContain("Cross-validate code and visuals");
  42. expect(skill).not.toContain("browser-use:control-browser");
  43. expect(skill).not.toContain("agent.browsers");
  44. expect(skill).not.toContain("tab.playwright.domSnapshot()");
  45. expect(skill).not.toContain("nodeRepl.emitImage(await tab.screenshot())");
  46. expect(skill).not.toMatch(
  47. /\bpage\.(?:click|fill|goto|screenshot|evaluate|on|context|keyboard|mouse)\b/u,
  48. );
  49. expect(skill).not.toContain("page.on(");
  50. expect(skill).toContain("Browser screenshot saved to: <absolute path>");
  51. });
  52. it("keeps included examples executable without cross-cell Browser bindings", async () => {
  53. const overview = readFileSync(overviewPath, "utf8");
  54. const workflow = readFileSync(workflowPath, "utf8");
  55. const firstWorkflowCell = /```js\r?\n([\s\S]*?)\r?\n```/u.exec(workflow)?.[1];
  56. expect(firstWorkflowCell).toBeTruthy();
  57. expect(overview).not.toContain("globalThis.browser");
  58. expect(overview).not.toContain("globalThis.tab");
  59. expect(overview).toContain("fresh kernel");
  60. expect(workflow).not.toContain("globalThis.browser");
  61. expect(workflow).not.toContain("globalThis.tab");
  62. expect(overview).not.toContain("browser.tabs.selected()");
  63. expect(workflow).toMatch(/\bconst browser = await agent\.browsers/u);
  64. if (!firstWorkflowCell) return;
  65. const browser = {
  66. tabs: {
  67. list: async () => [
  68. {
  69. id: "tab-1",
  70. title: "Example",
  71. url: "https://example.com/",
  72. viewport: { width: 1280, height: 720 },
  73. },
  74. ],
  75. },
  76. };
  77. const session = new NodeReplSession({
  78. injectedGlobals: () => ({
  79. agent: { browsers: { getDefault: async () => browser } },
  80. }),
  81. protectProtocolStdio: true,
  82. });
  83. try {
  84. const first = await session.run(firstWorkflowCell);
  85. expect(first.error).toBeUndefined();
  86. expect(first.result).toContain('"id": "tab-1"');
  87. } finally {
  88. session.dispose();
  89. }
  90. });
  91. it("browser skill keeps BrowserControl continuity while rebuilding JavaScript bindings", () => {
  92. const skill = readFileSync(skillPath, "utf8");
  93. expect(skill).toContain("mcp__node_repl__js");
  94. expect(skill).toContain("every `js` call runs in a fresh JavaScript kernel");
  95. expect(skill).toContain("Persistent BrowserControl tabs are the continuity boundary");
  96. expect(skill).not.toContain("mcp__browser_use__");
  97. expect(skill).not.toContain("context_handle");
  98. });
  99. it("preserves pre-upgrade Browser Use guidance outside the fresh-kernel substitutions", () => {
  100. const skill = readFileSync(skillPath, "utf8");
  101. const bootstrapSource = /## Bootstrap[\s\S]*?```js\r?\n([\s\S]*?)\r?\n```/u.exec(skill)?.[1];
  102. expect(skill).toContain("The tool has no `command` parameter.");
  103. expect(skill).toContain("Headless is a CDP launch mode, not a backend type.");
  104. expect(skill).toContain("Reuse the latest relevant snapshot until it becomes stale.");
  105. expect(skill).toMatch(
  106. /An internal SDK validation or a list hidden inside the same\s+cell does not count as model inspection\./u,
  107. );
  108. expect(skill).toContain("Do not navigate to the same URL again");
  109. expect(skill).toMatch(
  110. /Do not close research\/source tabs merely because the\s+turn is ending\./u,
  111. );
  112. expect(skill).toContain(
  113. "If the user asked for screenshots, include the emitted images in your final response.",
  114. );
  115. expect(bootstrapSource).toBeTruthy();
  116. expect(bootstrapSource).not.toContain("agent.browsers.getDefault()");
  117. expect(bootstrapSource).not.toContain("agent.browsers.get(");
  118. expect(bootstrapSource).not.toContain("agent.browsers.getForUrl(");
  119. });
  120. it("executes the browser skill bootstrap with the host-provided plugin root", async () => {
  121. const skill = readFileSync(skillPath, "utf8");
  122. const bootstrapSource = /## Bootstrap[\s\S]*?```js\r?\n([\s\S]*?)\r?\n```/u.exec(skill)?.[1];
  123. expect(bootstrapSource).toBeTruthy();
  124. if (!bootstrapSource) return;
  125. const pluginRoot = await mkdtemp(join(tmpdir(), "zcode-browser-skill-"));
  126. const previousPluginRoot = process.env.ZCODE_PLUGIN_ROOT;
  127. let session: NodeReplSession | undefined;
  128. try {
  129. await mkdir(join(pluginRoot, "scripts"), { recursive: true });
  130. await writeFile(
  131. join(pluginRoot, "scripts", "browser-client.mjs"),
  132. [
  133. "export async function setupBrowserRuntime({ globals }) {",
  134. " globals.agent = { browsers: { ready: true, getDefault: async () => ({}) } };",
  135. "}",
  136. ].join("\n"),
  137. "utf8",
  138. );
  139. process.env.ZCODE_PLUGIN_ROOT = pluginRoot;
  140. session = new NodeReplSession({ protectProtocolStdio: true });
  141. // 修复原因:生产 Skill 的 base directory 位于 skills/control-browser,必须证明模板只信任宿主根目录。
  142. const bootstrapResult = await session.run(bootstrapSource);
  143. expect(bootstrapResult.error).toBeUndefined();
  144. const readyResult = await session.run("globalThis.agent?.browsers?.ready");
  145. expect(readyResult.error).toBeUndefined();
  146. expect(readyResult.result).toBe("true");
  147. } finally {
  148. session?.dispose();
  149. if (previousPluginRoot === undefined) {
  150. delete process.env.ZCODE_PLUGIN_ROOT;
  151. } else {
  152. process.env.ZCODE_PLUGIN_ROOT = previousPluginRoot;
  153. }
  154. await rm(pluginRoot, { force: true, recursive: true });
  155. }
  156. });
  157. it("exposes the Playwright wait member in runtime policy and effective documentation", () => {
  158. const manifest = loadBrowserApiManifest(docsRoot);
  159. const policy = new BrowserApiPolicy(manifest, iab);
  160. const runtime = createBrowserApiProxy({ waitForTimeout: () => "ok" }, "PlaywrightAPI", policy);
  161. expect(runtime.waitForTimeout()).toBe("ok");
  162. expect("waitForTimeout" in runtime).toBe(true);
  163. const documentation = loadBrowserDocumentation(docsRoot, undefined, iab);
  164. expect(documentation).toContain("url(): Promise<string | undefined>");
  165. expect(documentation).toContain("playwright: PlaywrightAPI");
  166. expect(documentation).toContain("waitForTimeout(timeoutMs: number)");
  167. expect(documentation).toContain('waitForEvent(event: "download"');
  168. expect(documentation).toContain("Construct locators only from the latest relevant domSnapshot");
  169. expect(documentation).toContain("If the latest snapshot already contains the target");
  170. expect(documentation).toContain("execute JavaScript in the page context");
  171. expect(documentation).not.toContain("read-only evaluate");
  172. expect(documentation).not.toContain("Possible side-effect in debug-evaluate");
  173. expect(documentation).toContain("capped at 3000ms");
  174. expect(documentation).toContain("do not wait on that locator");
  175. expect(documentation).toContain("do not loop over guessed URL variants");
  176. expect(documentation).toContain("accepts a plain string or `RegExp`");
  177. expect(documentation).toContain("RegExp values created in the node_repl VM realm");
  178. expect(documentation).toContain("already-loaded page can satisfy that waiter");
  179. expect(documentation).toContain("ambient UI state, not a browser-selection instruction");
  180. expect(documentation).toContain("nodeRepl.emitImage(await tab.screenshot())");
  181. expect(documentation).toContain("Never use tab.screenshot() as the final expression");
  182. expect(documentation).not.toContain('waitForEvent(event: "filechooser"');
  183. expect(documentation).not.toContain("setFiles(files");
  184. expect(documentation).not.toContain("elementInfo(options:");
  185. expect(documentation).not.toContain("elementScreenshot(options:");
  186. expect(documentation).not.toContain("downloadMedia(options: CuaDownloadMediaOptions");
  187. expect(documentation).not.toContain("downloadMedia(options: DomDownloadMediaOptions");
  188. });
  189. it("browser skill keeps snapshot-first discovery while allowing evaluate page scripts", () => {
  190. const skill = readFileSync(skillPath, "utf8");
  191. expect(skill).toContain(
  192. "If that snapshot already contains the target, act from its facts directly",
  193. );
  194. expect(skill).toContain("do not write `evaluate()` code to rediscover related elements");
  195. expect(skill).toContain("execute JavaScript in the page context");
  196. expect(skill).not.toContain("read-only evaluate");
  197. expect(skill).not.toContain("Possible side-effect in debug-evaluate");
  198. });
  199. it("requires an explicit DOMContentLoaded wait after every new-URL goto", () => {
  200. const skill = readFileSync(skillPath, "utf8");
  201. const overview = readFileSync(overviewPath, "utf8");
  202. const workflow = readFileSync(workflowPath, "utf8");
  203. const playwright = readFileSync(playwrightPath, "utf8");
  204. const manifest = loadBrowserApiManifest(docsRoot);
  205. const documentation = loadBrowserDocumentation(docsRoot, undefined, iab);
  206. const fallbackDocumentation = loadBrowserDocumentation(undefined, undefined, iab);
  207. const requiredGuidance =
  208. 'After every successful `tab.goto(url)`, explicitly call `await tab.playwright.waitForLoadState({ state: "domcontentloaded" })` before the first title, URL, or DOM observation.';
  209. const explicitWait = 'await tab.playwright.waitForLoadState({ state: "domcontentloaded" });';
  210. expect(manifest.semantics?.navigationWait).toContain(requiredGuidance);
  211. for (const guidance of [
  212. skill,
  213. overview,
  214. workflow,
  215. playwright,
  216. documentation,
  217. fallbackDocumentation,
  218. ]) {
  219. expect(guidance).toContain(requiredGuidance);
  220. expect(guidance).toContain("3000ms");
  221. expect(guidance).not.toContain(
  222. 'tab.goto(url)` and `tab.playwright.waitForLoadState({ state: "networkidle" })',
  223. );
  224. }
  225. for (const example of [overview, workflow]) {
  226. const gotoIndex = example.indexOf('await tab.goto("https://example.com");');
  227. const waitIndex = example.indexOf(explicitWait, gotoIndex);
  228. const observationIndex = example.indexOf("await tab.playwright.domSnapshot();", waitIndex);
  229. expect(gotoIndex).toBeGreaterThanOrEqual(0);
  230. expect(waitIndex).toBeGreaterThan(gotoIndex);
  231. expect(observationIndex).toBeGreaterThan(waitIndex);
  232. }
  233. });
  234. it("browser guidance observes both tab registries in one cell before deciding a popup action effect", () => {
  235. const skill = readFileSync(skillPath, "utf8");
  236. const manifest = loadBrowserApiManifest(docsRoot);
  237. const documentation = loadBrowserDocumentation(docsRoot, undefined, iab);
  238. const fallbackDocumentation = loadBrowserDocumentation(undefined, undefined, iab);
  239. const troubleshootingDocumentation = loadBrowserDocumentation(
  240. docsRoot,
  241. "browser-troubleshooting",
  242. iab,
  243. );
  244. const tabClaimingDocumentation = loadBrowserDocumentation(docsRoot, "tab-claiming-iab", iab);
  245. expect(manifest.semantics?.actionResultObservation).toContain(
  246. "read `browser.tabs.list()` and `browser.user.openTabs()` unconditionally in the same observation cell",
  247. );
  248. for (const guidance of [skill, documentation, fallbackDocumentation]) {
  249. expect(guidance).toContain(
  250. "A snapshot-proven heading or visible text does not need a `link` or `button` role to be clicked.",
  251. );
  252. expect(guidance).toContain(
  253. "Do not replace a snapshot-proven `heading` with a guessed `link` role.",
  254. );
  255. expect(guidance).toContain("one state-changing action per observation cycle");
  256. expect(guidance).toContain("An unchanged source-tab URL does not prove the click failed.");
  257. expect(guidance).toContain(
  258. "When an action may open a popup/new tab and the source tab does not show the expected effect, read `browser.tabs.list()` and `browser.user.openTabs()` unconditionally in the same observation cell.",
  259. );
  260. expect(guidance).toContain(
  261. "Judge an action by whether its expected effect appeared, not by whether `browser.tabs.list()` is non-empty.",
  262. );
  263. expect(guidance).toContain(
  264. "An existing source tab or unrelated controlled tab is not an action effect.",
  265. );
  266. expect(guidance).toContain(
  267. "Return `{ controlledTabs, userTabs }` as that cell's final result so the model makes one decision from both lists.",
  268. );
  269. expect(guidance).toContain(
  270. "Do not return the controlled list first or decide whether to query user tabs from its contents.",
  271. );
  272. expect(guidance).not.toContain("Return each list in a dedicated JS call");
  273. expect(guidance).not.toContain("lists in separate observation calls");
  274. expect(guidance).not.toContain(
  275. "inspect `browser.tabs.list()` and then `browser.user.openTabs()` before clicking again",
  276. );
  277. }
  278. expect(fallbackDocumentation).toContain("every Browser Use call starts in a fresh kernel");
  279. expect(fallbackDocumentation).toContain("const browser = await agent.browsers.getDefault()");
  280. expect(fallbackDocumentation).not.toContain("globalThis.browser");
  281. expect(fallbackDocumentation).not.toContain("globalThis.tab");
  282. for (const guidance of [troubleshootingDocumentation, tabClaimingDocumentation]) {
  283. expect(guidance).toContain(
  284. "When an action may open a popup/new tab and the source tab does not show the expected effect, read",
  285. );
  286. expect(guidance).toContain(
  287. "`browser.tabs.list()` and `browser.user.openTabs()` unconditionally in the same observation cell.",
  288. );
  289. expect(guidance).toContain(
  290. "{ controlledTabs, userTabs }` as that cell's final result so the model makes one decision from both lists",
  291. );
  292. expect(guidance).not.toContain("separate observation");
  293. }
  294. });
  295. it("IAB effective docs include capability-gated tab lifecycle and recovery guidance", () => {
  296. const documentation = loadBrowserDocumentation(docsRoot, undefined, iab);
  297. expect(documentation).toContain("# User Tab Claiming");
  298. expect(documentation).toContain("# Tab Cleanup");
  299. expect(documentation).toContain("# Tab Lifecycle Marks");
  300. expect(documentation).toContain("# All-Tabs Cleanup Guidance");
  301. expect(documentation).toContain("browser.tabs.get(info.id)");
  302. expect(documentation).toContain("Before every logical tab operation batch");
  303. expect(documentation).toContain("dedicated JS call");
  304. expect(documentation).toContain("same-cell hidden list does not count as model inspection");
  305. expect(documentation).toContain("background session never steals the foreground UI");
  306. expect(documentation).toContain("active?: boolean");
  307. expect(documentation).toContain("viewport: BrowserViewportSize");
  308. expect(loadBrowserDocumentation(undefined, undefined, iab)).toContain(
  309. "viewport: BrowserViewportSize",
  310. );
  311. expect(documentation).toContain("validates, binds, and activates a tab");
  312. expect(documentation).toContain("omission from `keep` do not close a tab");
  313. expect(documentation).not.toContain("unlisted temporary tabs are cleaned up");
  314. expect(documentation).not.toContain("preserves only the final active agent tab");
  315. expect(documentation).not.toContain("# Browser Interaction Troubleshooting");
  316. expect(loadBrowserDocumentation(docsRoot, "browser-troubleshooting", iab)).toContain(
  317. "Do not retry the same",
  318. );
  319. expect(loadBrowserDocumentation(docsRoot, "viewport", iab)).toContain(
  320. "responsive mode uses DPR 1",
  321. );
  322. });
  323. it("non-IAB effective docs do not include IAB-only tab lifecycle documents", () => {
  324. const documentation = loadBrowserDocumentation(docsRoot, undefined, {
  325. ...iab,
  326. id: "extension-1",
  327. type: "extension",
  328. });
  329. expect(documentation).not.toContain("# User Tab Claiming");
  330. expect(documentation).not.toContain("# Tab Lifecycle Marks");
  331. expect(documentation).not.toContain("# All-Tabs Cleanup Guidance");
  332. });
  333. it("connection override can hide a common member from runtime and docs", () => {
  334. const manifest = loadBrowserApiManifest(docsRoot);
  335. const descriptor = {
  336. ...iab,
  337. apiSupportOverrides: { "PlaywrightAPI.waitForTimeout": false },
  338. };
  339. const policy = new BrowserApiPolicy(manifest, descriptor);
  340. const runtime = createBrowserApiProxy(
  341. { waitForTimeout: () => "unexpected" },
  342. "PlaywrightAPI",
  343. policy,
  344. );
  345. expect(runtime.waitForTimeout).toBeUndefined();
  346. expect("waitForTimeout" in runtime).toBe(false);
  347. expect(loadBrowserDocumentation(docsRoot, undefined, descriptor)).not.toContain(
  348. "waitForTimeout(timeoutMs: number)",
  349. );
  350. });
  351. it("hides tab lifecycle finalization from IAB and managed CDP object graphs", () => {
  352. const manifest = loadBrowserApiManifest(docsRoot);
  353. for (const type of ["iab", "cdp"] as const) {
  354. const policy = new BrowserApiPolicy(manifest, {
  355. ...iab,
  356. type,
  357. apiSupportOverrides: {},
  358. });
  359. const runtime = createBrowserApiProxy({ finalize: () => "unexpected" }, "Tab", policy);
  360. expect(policy.supports("Tab", "finalize")).toBe(false);
  361. expect(runtime.finalize).toBeUndefined();
  362. expect("finalize" in runtime).toBe(false);
  363. }
  364. });
  365. it("keeps browser and tab capability requirements isolated", () => {
  366. const manifest = loadBrowserApiManifest(docsRoot);
  367. const scopedManifest = {
  368. ...manifest,
  369. objects: {
  370. ...manifest.objects,
  371. Scoped: {
  372. members: [
  373. {
  374. name: "browserOnly",
  375. kind: "method" as const,
  376. signature: "browserOnly()",
  377. requiresCapabilities: ["browser:shared"],
  378. },
  379. {
  380. name: "tabOnly",
  381. kind: "method" as const,
  382. signature: "tabOnly()",
  383. requiresCapabilities: ["tab:shared"],
  384. },
  385. ],
  386. },
  387. },
  388. };
  389. const policy = new BrowserApiPolicy(scopedManifest, {
  390. ...iab,
  391. capabilities: { browser: [], tab: [{ id: "shared", description: "tab only" }] },
  392. });
  393. expect(policy.supports("Scoped", "browserOnly")).toBe(false);
  394. expect(policy.supports("Scoped", "tabOnly")).toBe(true);
  395. });
  396. it("keeps manifest command mappings inside the browser command contract", () => {
  397. const manifest = loadBrowserApiManifest(docsRoot);
  398. const knownCommands = new Set([
  399. "navigate",
  400. "back",
  401. "forward",
  402. "reload",
  403. "snapshot",
  404. "screenshot",
  405. "getState",
  406. "click",
  407. "type",
  408. "press",
  409. "scroll",
  410. "hover",
  411. "select",
  412. "check",
  413. "drag",
  414. "elementInfo",
  415. "evaluate",
  416. "getDialog",
  417. "handleDialog",
  418. "finalize",
  419. "close",
  420. "list",
  421. "newTab",
  422. "nameSession",
  423. "claimTab",
  424. "listUserTabs",
  425. "finalizeTabs",
  426. "markDeliverable",
  427. "markHandoff",
  428. "browserViewportSet",
  429. "browserViewportReset",
  430. "recordingStart",
  431. "recordingStatus",
  432. "recordingCancel",
  433. "playwrightWaitForTimeout",
  434. "playwright",
  435. ]);
  436. for (const object of Object.values(manifest.objects)) {
  437. for (const member of object.members) {
  438. if (member.command) expect(knownCommands.has(member.command), member.command).toBe(true);
  439. }
  440. }
  441. });
  442. it("manifest 枚举 common Playwright 全对象图", () => {
  443. const manifest = loadBrowserApiManifest(docsRoot);
  444. expect(manifest.version).toBe(11);
  445. expect(manifest.objects.PlaywrightAPI.members).toHaveLength(16);
  446. expect(manifest.objects.PlaywrightLocator.members).toHaveLength(32);
  447. expect(manifest.objects.PlaywrightFrameLocator.members).toHaveLength(7);
  448. expect(manifest.objects.PlaywrightDownload.members.map((member) => member.name)).toEqual([
  449. "path",
  450. ]);
  451. expect(manifest.objects.PlaywrightFileChooser.members.map((member) => member.name)).toEqual([
  452. "isMultiple",
  453. "setFiles",
  454. ]);
  455. });
  456. });