bundle-smoke.test.ts 8.5 KB

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