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

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