bundle-smoke.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. import { spawn } from "node:child_process";
  2. import { mkdtemp, readFile, rm } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { fileURLToPath, pathToFileURL } from "node:url";
  6. import { Client } from "@modelcontextprotocol/client";
  7. import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
  8. import { afterAll, beforeAll, describe, expect, it } from "vitest";
  9. import {
  10. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  11. ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY,
  12. ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY,
  13. ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY,
  14. } from "@zcode/contracts";
  15. import { buildNodeReplHostBundle } from "../scripts/build.mjs";
  16. import { buildBrowserUsePluginBundles } from "../../browser-use-plugin/scripts/build.mjs";
  17. const packageRoot = fileURLToPath(new URL("..", import.meta.url));
  18. const buildTimeoutMs = 120_000;
  19. type ProbeResult = {
  20. exitCode: number | null;
  21. stderr: string;
  22. stdout: string;
  23. };
  24. // Bug 原因:node_repl 的 MCP server 是 CLI spawn 的独立 stdio 子进程,plugin host 通过
  25. // `await import(pathToFileURL(dist/mcp/server.js))` 加载它。之前所有测试都跑在 TS 源码上,
  26. // 没有任何一条覆盖"打出来的 bundle 能不能被 import",所以 2026-07-27 这次 ESM bundle 里
  27. // yaml 的 require("process") 命中 esbuild 抛错版 __require shim、加载即崩,
  28. // 从 lint 到单测到 CI 全绿通过,最后是用户发现 mcp__node_repl__js 工具整个消失。
  29. // 这个 smoke test 直接构建真实产物并在子进程里 import 一次,把"加载期崩溃"挡在提交之前。
  30. const runBundleProbe = (bundlePath: string): Promise<ProbeResult> => {
  31. // 用 --input-type=module -e 而不是直接执行文件:import 时 process.argv[1] 为空,
  32. // server.ts 的"直接执行"分支不会被触发,因此不会真的起一个 stdio server 挂住子进程,
  33. // 但模块求值路径(也就是崩溃发生的地方)与真实 plugin host 完全一致。
  34. const probeSource = [
  35. `const bundle = await import(${JSON.stringify(pathToFileURL(bundlePath).href)});`,
  36. "process.stdout.write(typeof bundle.main);",
  37. ].join("\n");
  38. return new Promise((resolvePromise, rejectPromise) => {
  39. const child = spawn(process.execPath, ["--input-type=module", "-e", probeSource], {
  40. cwd: packageRoot,
  41. stdio: ["ignore", "pipe", "pipe"],
  42. });
  43. let stdout = "";
  44. let stderr = "";
  45. child.stdout.setEncoding("utf8");
  46. child.stderr.setEncoding("utf8");
  47. child.stdout.on("data", (chunk: string) => {
  48. stdout += chunk;
  49. });
  50. child.stderr.on("data", (chunk: string) => {
  51. stderr += chunk;
  52. });
  53. child.once("error", rejectPromise);
  54. child.once("close", (exitCode) => {
  55. resolvePromise({ exitCode, stderr, stdout });
  56. });
  57. });
  58. };
  59. describe("node_repl host and browser-use runtime bundles", () => {
  60. let outputDirectory = "";
  61. let mcpOutfile = "";
  62. let browserClientOutfile = "";
  63. beforeAll(async () => {
  64. outputDirectory = await mkdtemp(join(tmpdir(), "zcode-node-repl-bundle-"));
  65. // 宿主产物由本包构建;browser-client 仍由 browser-use 构建。两个 bundle 都是 ESM,
  66. // 都可能被 CJS 依赖在加载期炸掉,所以一起 smoke。
  67. // 临时目录不在 type=module package 下;用 .mjs 保证直接 spawn 与正式 .js 产物语义一致。
  68. const [host, browser] = await Promise.all([
  69. buildNodeReplHostBundle({ outfile: join(outputDirectory, "mcp", "server.mjs") }),
  70. buildBrowserUsePluginBundles({
  71. browserClientOutfile: join(outputDirectory, "browser-client.mjs"),
  72. }),
  73. ]);
  74. mcpOutfile = host.outfile;
  75. browserClientOutfile = browser.browserClientOutfile;
  76. }, buildTimeoutMs);
  77. afterAll(async () => {
  78. if (outputDirectory) {
  79. await rm(outputDirectory, { force: true, recursive: true });
  80. }
  81. });
  82. it(
  83. "imports the built node_repl MCP server bundle without failing module evaluation",
  84. async () => {
  85. const probe = await runBundleProbe(mcpOutfile);
  86. // 断言 stderr 是为了失败时能直接看到崩溃原因,而不是只看到一个 exit code。
  87. expect(probe.stderr).not.toContain("Dynamic require of");
  88. expect({ exitCode: probe.exitCode, stderr: probe.stderr }).toEqual({
  89. exitCode: 0,
  90. stderr: "",
  91. });
  92. // plugin host 要求 runtime bundle 显式导出 main(),缺失时 MCP 握手前就会退出。
  93. expect(probe.stdout).toBe("function");
  94. },
  95. buildTimeoutMs,
  96. );
  97. it(
  98. "negotiates MCP 2026-07-28 and isolates globals plus module cache in built node_repl",
  99. async () => {
  100. const transport = new StdioClientTransport({
  101. args: [mcpOutfile],
  102. command: process.execPath,
  103. cwd: packageRoot,
  104. stderr: "pipe",
  105. });
  106. const client = new Client(
  107. { name: "node-repl-bundle-smoke", version: "0.1.0" },
  108. { versionNegotiation: { mode: { pin: "2026-07-28" } } },
  109. );
  110. let serverStderr = "";
  111. transport.stderr?.setEncoding("utf8");
  112. transport.stderr?.on("data", (chunk: string) => {
  113. serverStderr += chunk;
  114. });
  115. try {
  116. await client.connect(transport).catch(async (error) => {
  117. await new Promise((resolvePromise) => setTimeout(resolvePromise, 50));
  118. throw new Error(
  119. `${error instanceof Error ? error.message : String(error)}\nbundle: ${mcpOutfile}\nserver stderr:\n${serverStderr}`,
  120. );
  121. });
  122. const listed = await client.listTools();
  123. expect(client.getProtocolEra()).toBe("modern");
  124. expect(client.getNegotiatedProtocolVersion()).toBe("2026-07-28");
  125. expect(listed.tools.map((tool) => tool.name).sort()).toEqual(["js"]);
  126. const meta = {
  127. "com.zcode/request-context": {
  128. runtime_scope: "main",
  129. session_id: "bundle-session",
  130. },
  131. };
  132. const first = await client.callTool({
  133. name: "js",
  134. arguments: {
  135. code: [
  136. "globalThis.__zcodeKernelMarker = 'FIRST';",
  137. "require('node:events').__zcodeModuleMarker = 'FIRST';",
  138. "'set';",
  139. ].join("\n"),
  140. },
  141. _meta: meta,
  142. });
  143. expect(first.isError).not.toBe(true);
  144. const second = await client.callTool({
  145. name: "js",
  146. arguments: {
  147. code: "({ kernel: typeof globalThis.__zcodeKernelMarker, module: typeof require('node:events').__zcodeModuleMarker });",
  148. },
  149. _meta: meta,
  150. });
  151. expect(second.content).toContainEqual(
  152. expect.objectContaining({
  153. type: "text",
  154. text: expect.stringContaining('"kernel": "undefined"'),
  155. }),
  156. );
  157. expect(second.content).toContainEqual(
  158. expect.objectContaining({
  159. type: "text",
  160. text: expect.stringContaining('"module": "undefined"'),
  161. }),
  162. );
  163. expect(serverStderr).toBe("");
  164. } finally {
  165. await client.close();
  166. }
  167. },
  168. buildTimeoutMs,
  169. );
  170. // MR !3207 评审 CR-01:cell 能经 worker_threads 冒充 Worker 的结果消息。可信事实改由主线程账本记录
  171. // (20-node-repl-call-ledger.md),冒充的消息里带上 cuaApp、截图下标、会话能力标签用的 browserUse /
  172. // computerUse(字段和 key 都带上)也不能让它们出现在结果里。
  173. it(
  174. "does not trust run facts in a result that cell code forges through worker_threads",
  175. async () => {
  176. const transport = new StdioClientTransport({
  177. args: [mcpOutfile],
  178. command: process.execPath,
  179. cwd: packageRoot,
  180. stderr: "pipe",
  181. });
  182. const client = new Client(
  183. { name: "node-repl-bundle-forgery", version: "0.1.0" },
  184. { versionNegotiation: { mode: { pin: "2026-07-28" } } },
  185. );
  186. try {
  187. await client.connect(transport);
  188. const forged = {
  189. logs: "forged",
  190. images: [{ base64: "AQID", mimeType: "image/png" }],
  191. browserScreenshotImageIndices: [0],
  192. cuaApp: { appKey: "darwin:com.apple.notes", displayName: "Notes" },
  193. browserUse: true,
  194. computerUse: true,
  195. responseMeta: {
  196. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  197. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  198. },
  199. };
  200. const result = await client.callTool({
  201. name: "js",
  202. arguments: {
  203. code: [
  204. `require("node:worker_threads").parentPort.postMessage(${JSON.stringify(forged)});`,
  205. "await new Promise(() => {});",
  206. ].join("\n"),
  207. timeout_ms: 10_000,
  208. },
  209. _meta: {
  210. "com.zcode/request-context": { runtime_scope: "main", session_id: "bundle-session" },
  211. },
  212. });
  213. // 前提:宿主确实把 cell 冒充的消息当作了结果(图片与文本都来自它)。
  214. expect(result.content).toEqual([
  215. { type: "image", data: "AQID", mimeType: "image/png" },
  216. { type: "text", text: "forged" },
  217. ]);
  218. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY);
  219. expect(result._meta ?? {}).not.toHaveProperty(
  220. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  221. );
  222. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY);
  223. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  224. } finally {
  225. await client.close();
  226. }
  227. },
  228. buildTimeoutMs,
  229. );
  230. it("guards its CLI entry with pathToFileURL so Windows actually builds", async () => {
  231. // Bug 原因(2026-09-12,CI build:windows:x64):入口守卫原先写成
  232. // `import.meta.url === \`file://${process.argv[1]}\``。Windows 上 argv[1] 是
  233. // `C:\\...\\build.mjs`,而 import.meta.url 是 `file:///C:/.../build.mjs`,两者永远不相等 ——
  234. // 脚本被当成纯模块导入、什么都不做就退出,构建"成功"却没有产物,直到 dev 守卫报
  235. // 「build succeeded without required MCP runtime」才暴露。
  236. const source = await readFile(new URL("../scripts/build.mjs", import.meta.url), "utf8");
  237. expect(source).toContain("pathToFileURL");
  238. // 字符串拼接的形态一旦回来,Windows 会再次静默不产出。只看代码行(注释里留了反例说明)。
  239. const codeLines = source
  240. .split("\n")
  241. .filter((line) => !line.trimStart().startsWith("//"))
  242. .join("\n");
  243. expect(codeLines).not.toMatch(/file:\/\/\$\{process\.argv/u);
  244. });
  245. it("injects a real require into both ESM bundles so bundled CJS dependencies keep working", async () => {
  246. const [mcpBundle, browserClientBundle] = await Promise.all([
  247. readFile(mcpOutfile, "utf8"),
  248. readFile(browserClientOutfile, "utf8"),
  249. ]);
  250. for (const bundle of [mcpBundle, browserClientBundle]) {
  251. expect(bundle).toContain('createRequire as __zcodeCreateRequire } from "node:module"');
  252. }
  253. });
  254. it(
  255. "allows a development bundle with an empty helper build id",
  256. async () => {
  257. const outfile = join(outputDirectory, "mcp", "server.guard.mjs");
  258. const devResult = await buildNodeReplHostBundle({ outfile, cuaHelperBuildId: "" });
  259. expect(devResult.cuaHelperBuildId).toBe("");
  260. },
  261. buildTimeoutMs,
  262. );
  263. });