node-repl-browser-injection.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. import { describe, expect, it, vi } from "vitest";
  2. import { jsToolEntry, disposeNodeReplSession } from "../src/tool/handlers/node-repl.js";
  3. import type { ToolExecutionContext } from "../src/tool/types.js";
  4. import type {
  5. BrowserControlPort,
  6. BrowserCommandResult,
  7. ToolArtifactStorePort,
  8. } from "@zcode/contracts";
  9. import type { JsOutput } from "@zcode/contracts";
  10. const IAB = {
  11. id: "iab-runtime-1",
  12. generation: 1,
  13. type: "iab" as const,
  14. name: "ZCode In-app Browser",
  15. capabilities: {},
  16. };
  17. function browserPort(execute: BrowserControlPort["execute"]): BrowserControlPort {
  18. return {
  19. list: vi.fn(async () => [IAB]),
  20. execute: vi.fn(async (input) => {
  21. if (input.command.method === "newTab") {
  22. return {
  23. ok: true,
  24. tab: {
  25. tabId: "tab-1",
  26. url: "about:blank",
  27. title: "",
  28. viewport: { width: 1280, height: 720 },
  29. },
  30. elapsedMs: 1,
  31. };
  32. }
  33. return execute(input);
  34. }),
  35. };
  36. }
  37. function ctx(sessionId: string, port?: BrowserControlPort): ToolExecutionContext {
  38. return {
  39. toolCallId: "t",
  40. traceId: "tr",
  41. abortSignal: new AbortController().signal,
  42. workingDirectory: "/tmp",
  43. workspaceRoot: "/tmp",
  44. sessionId: sessionId as ToolExecutionContext["sessionId"],
  45. ...(port ? { browserControlPort: port } : {}),
  46. };
  47. }
  48. describe("node_repl browser injection", () => {
  49. it("exposes the browser.tabs.new path when browserControlPort is present", async () => {
  50. const port = browserPort(
  51. vi.fn(async (): Promise<BrowserCommandResult> => ({ ok: true, elapsedMs: 1 })),
  52. );
  53. const c = ctx("bs1", port);
  54. const out = (await jsToolEntry.handler(
  55. {
  56. code: "const browser = await agent.browsers.getDefault(); return typeof browser.tabs.new;",
  57. },
  58. c,
  59. )) as JsOutput;
  60. expect(out.error).toBeUndefined();
  61. expect(out.result).toBe("function");
  62. disposeNodeReplSession("bs1" as ToolExecutionContext["sessionId"]);
  63. });
  64. it("injects browser.documentation and agent.documentation.get as separate surfaces", async () => {
  65. const port = browserPort(
  66. vi.fn(async (): Promise<BrowserCommandResult> => ({ ok: true, elapsedMs: 1 })),
  67. );
  68. const c = {
  69. ...ctx("bs-docs", port),
  70. browserDocumentationRoot: new URL("../../browser-use-plugin/docs", import.meta.url).pathname,
  71. };
  72. const out = (await jsToolEntry.handler(
  73. {
  74. code: `const docsBrowser = await agent.browsers.get("iab"); const full = await docsBrowser.documentation(); const lookup = await agent.documentation.get("screenshots"); return JSON.stringify({full:full.includes("API manifest"),fullBytes:Buffer.byteLength(full,"utf8"),lookup:lookup.includes("# Screenshots"),legacy:typeof agent.browsers.documentation});`,
  75. },
  76. c,
  77. )) as JsOutput;
  78. const result = JSON.parse(out.result ?? "{}") as {
  79. full: boolean;
  80. fullBytes: number;
  81. lookup: boolean;
  82. legacy: string;
  83. };
  84. expect(result).toEqual({
  85. full: true,
  86. fullBytes: expect.any(Number),
  87. lookup: true,
  88. legacy: "undefined",
  89. });
  90. // 回归原因:真实 backend 的有效文档会超过旧 30 KB 预算;预算固定为 64 KiB,
  91. // 测试夹具生成的完整文档也必须能原样进入下一轮模型上下文。
  92. expect(jsToolEntry.resultBudget?.maxModelBytes).toBe(64 * 1024);
  93. expect(jsToolEntry.resultBudget?.preview?.maxBytes).toBe(64 * 1024);
  94. expect(result.fullBytes).toBeLessThanOrEqual(jsToolEntry.resultBudget?.maxModelBytes ?? 0);
  95. disposeNodeReplSession("bs-docs" as ToolExecutionContext["sessionId"]);
  96. });
  97. it("kernel reset drops old JS bindings and recovers backend-owned tabs through tabs.list", async () => {
  98. const execute = vi.fn(async (input): Promise<BrowserCommandResult> => {
  99. if (input.command.method === "list") {
  100. return {
  101. ok: true,
  102. tabs: [
  103. {
  104. tabId: "controlled-1",
  105. url: "https://example.com",
  106. title: "Example",
  107. viewport: { width: 1280, height: 720 },
  108. },
  109. ],
  110. elapsedMs: 1,
  111. };
  112. }
  113. if (input.command.method === "listUserTabs") {
  114. return { ok: true, userTabs: [], elapsedMs: 1 };
  115. }
  116. if (input.command.method === "activateTab") {
  117. return {
  118. ok: true,
  119. tab: {
  120. tabId: input.command.tabId,
  121. url: "https://example.com",
  122. title: "Example",
  123. active: true,
  124. viewport: { width: 1280, height: 720 },
  125. },
  126. elapsedMs: 1,
  127. };
  128. }
  129. return { ok: true, elapsedMs: 1 };
  130. });
  131. const c = ctx("bs-reset-recovery", browserPort(execute));
  132. await jsToolEntry.handler(
  133. {
  134. code: `globalThis.iab = await agent.browsers.get("iab"); globalThis.tab = await iab.tabs.get("controlled-1");`,
  135. },
  136. c,
  137. );
  138. // 2026-09-18:js_reset 工具已删除。dispose 后同 sessionId 再调用会重建 session,
  139. // 与旧 reset 等价,且更贴近生产——MCP 路径下每次 js 调用本来就是 fresh kernel。
  140. disposeNodeReplSession("bs-reset-recovery" as ToolExecutionContext["sessionId"]);
  141. const out = (await jsToolEntry.handler(
  142. {
  143. code: `const oldBinding = typeof tab; globalThis.iab = await agent.browsers.get("iab"); const controlled = await iab.tabs.list(); const userTabs = await iab.user.openTabs(); return JSON.stringify({oldBinding, controlled, userTabs});`,
  144. },
  145. c,
  146. )) as JsOutput;
  147. expect(JSON.parse(out.result ?? "{}")).toEqual({
  148. oldBinding: "undefined",
  149. controlled: [
  150. {
  151. id: "controlled-1",
  152. url: "https://example.com",
  153. title: "Example",
  154. viewport: { width: 1280, height: 720 },
  155. },
  156. ],
  157. userTabs: [],
  158. });
  159. disposeNodeReplSession("bs-reset-recovery" as ToolExecutionContext["sessionId"]);
  160. });
  161. it("rejects an in-flight browser result that arrives after kernel reset", async () => {
  162. let resolveLate!: (result: BrowserCommandResult) => void;
  163. let markStarted!: () => void;
  164. const started = new Promise<void>((resolve) => {
  165. markStarted = resolve;
  166. });
  167. const execute = vi.fn(async (input): Promise<BrowserCommandResult> => {
  168. if (input.command.method !== "playwright") return { ok: true, elapsedMs: 1 };
  169. markStarted();
  170. return await new Promise<BrowserCommandResult>((resolve) => {
  171. resolveLate = resolve;
  172. });
  173. });
  174. const port = browserPort(execute);
  175. const controller = new AbortController();
  176. const firstContext = {
  177. ...ctx("bs-reset-late-result", port),
  178. abortSignal: controller.signal,
  179. };
  180. const interrupted = jsToolEntry.handler(
  181. {
  182. code: `const lateBrowser = await agent.browsers.getDefault(); const lateTab = await lateBrowser.tabs.new(); await lateTab.playwright.domSnapshot();`,
  183. },
  184. firstContext,
  185. ) as Promise<JsOutput>;
  186. await started;
  187. controller.abort();
  188. expect((await interrupted).error?.name).toBe("AbortError");
  189. // 第二个 cell 保持 sink 活跃;旧 generation 的迟到结果不得把 browser meta 合并进来。
  190. const nextContext = ctx("bs-reset-late-result", port);
  191. const nextCell = jsToolEntry.handler(
  192. {
  193. code: "await new Promise(resolve => setTimeout(resolve, 30)); return 42;",
  194. timeout_ms: 100,
  195. },
  196. nextContext,
  197. ) as Promise<JsOutput>;
  198. resolveLate({
  199. ok: true,
  200. value: "late",
  201. meta: {
  202. browserUse: true,
  203. backendType: "iab",
  204. browserId: IAB.id,
  205. browserGeneration: IAB.generation,
  206. openTabIds: ["late-tab"],
  207. },
  208. elapsedMs: 20,
  209. });
  210. const next = await nextCell;
  211. expect(next.result).toBe("42");
  212. expect(next.responseMeta).toBeUndefined();
  213. disposeNodeReplSession("bs-reset-late-result" as ToolExecutionContext["sessionId"]);
  214. });
  215. it("browser.tabs.new + tab.goto triggers port.execute (navigate) and returns result", async () => {
  216. const execute = vi.fn(
  217. async (): Promise<BrowserCommandResult> => ({
  218. ok: true,
  219. state: {
  220. url: "https://x",
  221. title: "X",
  222. canGoBack: false,
  223. canGoForward: false,
  224. },
  225. elapsedMs: 2,
  226. }),
  227. );
  228. const port = browserPort(execute);
  229. const c = ctx("bs2", port);
  230. const out = (await jsToolEntry.handler(
  231. {
  232. code: `const browser = await agent.browsers.getDefault(); const b = await browser.tabs.new(); await b.goto("https://x"); return b.constructor.name;`,
  233. },
  234. c,
  235. )) as JsOutput;
  236. expect(out.error).toBeUndefined();
  237. // 至少发生了一次 navigate 调用。
  238. expect(execute).toHaveBeenCalled();
  239. const firstCall = execute.mock.calls[0][0] as {
  240. command: { method: string; url?: string };
  241. };
  242. expect(firstCall.command).toEqual({
  243. method: "navigate",
  244. url: "https://x",
  245. tabId: "tab-1",
  246. });
  247. expect(firstCall).toMatchObject({ browserId: IAB.id, sessionId: "bs2" });
  248. disposeNodeReplSession("bs2" as ToolExecutionContext["sessionId"]);
  249. });
  250. it("emits an explicit screenshot and exposes its original artifact absolute path", async () => {
  251. const port = browserPort(
  252. vi.fn(async (input): Promise<BrowserCommandResult> => {
  253. const command = (input as { command: { method: string } }).command;
  254. if (command.method === "screenshot") {
  255. return {
  256. ok: true,
  257. image: { base64: "AAAA", mimeType: "image/png" },
  258. elapsedMs: 1,
  259. };
  260. }
  261. return { ok: true, elapsedMs: 1 };
  262. }),
  263. );
  264. const writes: Uint8Array[] = [];
  265. const artifactStore: ToolArtifactStorePort = {
  266. writeToolResultArtifact: async () => {
  267. throw new Error("unexpected text artifact write");
  268. },
  269. writeToolResultBinaryArtifact: async (request) => {
  270. writes.push(request.content);
  271. return {
  272. id: "browser-shot",
  273. uri: "zcode-artifact://bs3/browser-shot",
  274. path: "/tmp/browser-shot.png",
  275. bytes: request.content.byteLength,
  276. contentType: request.contentType,
  277. createdAt: new Date("2026-07-20T00:00:00.000Z"),
  278. };
  279. },
  280. readToolResultArtifact: async () => {
  281. throw new Error("not used");
  282. },
  283. };
  284. const c = { ...ctx("bs3", port), artifactStore };
  285. const out = (await jsToolEntry.handler(
  286. {
  287. code: `const browser = await agent.browsers.getDefault(); const b = await browser.tabs.new(); nodeRepl.emitImage(await b.screenshot());`,
  288. },
  289. c,
  290. )) as JsOutput;
  291. expect(out.error).toBeUndefined();
  292. expect(out.images?.[0]?.base64).toBe("AAAA");
  293. expect(out.browserScreenshotPaths).toEqual(["/tmp/browser-shot.png"]);
  294. expect(Buffer.from(writes[0] ?? [])).toEqual(Buffer.from("AAAA", "base64"));
  295. // Canonical node_repl result order puts the emitted raster before its summary.
  296. expect(jsToolEntry.formatModelContent?.(out)).toEqual([
  297. expect.objectContaining({ type: "image", mediaType: "image/png" }),
  298. expect.objectContaining({
  299. type: "text",
  300. text: expect.stringContaining("Browser screenshot saved to: /tmp/browser-shot.png"),
  301. }),
  302. ]);
  303. disposeNodeReplSession("bs3" as ToolExecutionContext["sessionId"]);
  304. });
  305. it("DOM-first example returns snapshot text without capturing a screenshot", async () => {
  306. const execute = vi.fn(async (input): Promise<BrowserCommandResult> => {
  307. const command = (input as { command: { method: string } }).command;
  308. if (command.method === "playwright" && command.action.name === "domSnapshot") {
  309. return {
  310. ok: true,
  311. value: '- heading "百度一下" [level=1]\n- paragraph: 网页内容',
  312. elapsedMs: 1,
  313. };
  314. }
  315. return { ok: true, elapsedMs: 1 };
  316. });
  317. const c = ctx("bs-dom-first", browserPort(execute));
  318. const out = (await jsToolEntry.handler(
  319. {
  320. code: `const browser = await agent.browsers.getDefault(); const domFirstTab = await browser.tabs.new(); await domFirstTab.goto("https://www.baidu.com"); await domFirstTab.playwright.domSnapshot()`,
  321. },
  322. c,
  323. )) as JsOutput;
  324. expect(out.error).toBeUndefined();
  325. expect(out.result).toContain("百度一下");
  326. expect(out.images ?? []).toEqual([]);
  327. const methods = execute.mock.calls.map(
  328. ([input]) => (input as { command: { method: string } }).command.method,
  329. );
  330. expect(methods).toEqual(["navigate", "playwright"]);
  331. disposeNodeReplSession("bs-dom-first" as ToolExecutionContext["sessionId"]);
  332. });
  333. it("automatically forwards browser response meta without creating an image block", async () => {
  334. const port = browserPort(
  335. vi.fn(
  336. async (): Promise<BrowserCommandResult> => ({
  337. ok: true,
  338. value: '- heading "X" [level=1]',
  339. meta: {
  340. browserUse: true,
  341. backendType: "iab",
  342. browserId: IAB.id,
  343. browserGeneration: IAB.generation,
  344. openTabIds: ["tab-1"],
  345. tabId: "tab-1",
  346. currentUrl: "https://x",
  347. lifecycle: "active",
  348. },
  349. elapsedMs: 1,
  350. }),
  351. ),
  352. );
  353. const c = ctx("bs-response-meta", port);
  354. const out = (await jsToolEntry.handler(
  355. {
  356. code: "const browser = await agent.browsers.getDefault(); const metaTab = await browser.tabs.new(); await metaTab.playwright.domSnapshot()",
  357. },
  358. c,
  359. )) as JsOutput;
  360. expect(out.responseMeta).toEqual({
  361. "zcode/browserUse": true,
  362. "zcode/toolSurface": expect.objectContaining({
  363. kind: "browserUse",
  364. backend: "iab",
  365. browserId: IAB.id,
  366. }),
  367. browser_use: { url: "https://x" },
  368. "zcode/browserTurnScreenshot": {
  369. browserGeneration: IAB.generation,
  370. browserId: IAB.id,
  371. tabId: "tab-1",
  372. },
  373. });
  374. expect(out.images).toBeUndefined();
  375. disposeNodeReplSession("bs-response-meta" as ToolExecutionContext["sessionId"]);
  376. });
  377. it("keeps last side-effect openTabIds through later reads without preview screenshot meta", async () => {
  378. const port = browserPort(
  379. vi.fn(
  380. async (input): Promise<BrowserCommandResult> => ({
  381. ok: true,
  382. ...(input.command.method === "getState"
  383. ? {
  384. state: {
  385. url: "https://x",
  386. title: "X",
  387. canGoBack: false,
  388. canGoForward: false,
  389. },
  390. }
  391. : {}),
  392. meta: {
  393. browserUse: true,
  394. backendType: "iab",
  395. browserId: IAB.id,
  396. browserGeneration: IAB.generation,
  397. openTabIds: ["tab-1"],
  398. tabId: "tab-1",
  399. currentUrl: "https://x",
  400. lifecycle: "active",
  401. },
  402. elapsedMs: 1,
  403. }),
  404. ),
  405. );
  406. const c = ctx("bs-side-effect-meta", port);
  407. const out = (await jsToolEntry.handler(
  408. {
  409. code: `const sideEffectBrowser = await agent.browsers.getDefault(); const sideEffectTab = await sideEffectBrowser.tabs.new(); await sideEffectTab.goto("https://x"); await sideEffectTab.title();`,
  410. },
  411. c,
  412. )) as JsOutput;
  413. expect(out.responseMeta).toMatchObject({
  414. "zcode/toolSurface": {
  415. kind: "browserUse",
  416. backend: "iab",
  417. browserId: IAB.id,
  418. openTabIds: ["tab-1"],
  419. },
  420. });
  421. expect(
  422. (out.responseMeta?.["zcode/toolSurface"] as Record<string, unknown>)?.screenshot,
  423. ).toBeUndefined();
  424. expect(out.images).toBeUndefined();
  425. disposeNodeReplSession("bs-side-effect-meta" as ToolExecutionContext["sessionId"]);
  426. });
  427. it("does not inject agent.browsers when no browser port is injected", async () => {
  428. const c = ctx("bs4");
  429. const out = (await jsToolEntry.handler({ code: "return typeof agent;" }, c)) as JsOutput;
  430. expect(out.error).toBeUndefined();
  431. expect(out.result).toBe("undefined");
  432. disposeNodeReplSession("bs4" as ToolExecutionContext["sessionId"]);
  433. });
  434. });