mcp-apps-host-e2e.mjs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import { verifySamplingDatabase } from "./mcp-apps-host-fixture/sampling-database.mjs";
  2. import { build } from "esbuild";
  3. import { access, mkdtemp, readFile, writeFile } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { dirname, join, resolve } from "node:path";
  6. import { fileURLToPath } from "node:url";
  7. import { spawn } from "node:child_process";
  8. import { createRequire } from "node:module";
  9. import { DatabaseSync } from "node:sqlite";
  10. const require = createRequire(import.meta.url);
  11. const desktop = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  12. const root = resolve(desktop, "../..");
  13. const output = await mkdtemp(join(tmpdir(), "zcode-mcp-host-e2e-"));
  14. const fixture = join(desktop, "scripts/mcp-apps-host-fixture");
  15. const showcaseServer = process.env.ZCODE_SHOWCASE_SERVER;
  16. if (process.argv.includes("--showcase-only")) {
  17. if (!showcaseServer)
  18. throw new Error(
  19. "Set ZCODE_SHOWCASE_SERVER to the built Showcase dist/server.mjs from zcode-plugins",
  20. );
  21. await access(showcaseServer);
  22. }
  23. const sentinel = new DatabaseSync(join(output, "plugin-sentinel.sqlite"));
  24. sentinel.exec(
  25. "CREATE TABLE fixture(value TEXT); INSERT INTO fixture VALUES ('preserve-plugin-data')",
  26. );
  27. sentinel.close();
  28. await writeFile(join(output, "plugin-sentinel.txt"), "preserve-plugin-files\n");
  29. // Agent bundle 必须来自本次源码;否则 Electron 用新代码、stdio 却测到旧 dist。
  30. if (
  31. !process.argv.includes("--retention-only") &&
  32. !process.argv.includes("--storage-only") &&
  33. !process.argv.includes("--reuse-agent-build")
  34. ) {
  35. // 新工作树没有预先生成的声明文件,先构建 Agent 的基础包。
  36. for (const name of [
  37. "shared-types",
  38. "dynamic-workflow",
  39. "contracts",
  40. "i18n",
  41. "telemetry",
  42. "dynamic-workflow-runtime",
  43. "core",
  44. "adapters",
  45. "bootstrap",
  46. "cli",
  47. ]) {
  48. await new Promise((accept, reject) => {
  49. const child = spawn(
  50. "pnpm",
  51. [
  52. "--dir",
  53. join(root, "apps/zcode-cli"),
  54. "--filter",
  55. `@zcode/${name}`,
  56. name === "cli" ? "build:desktop-agent" : "build",
  57. ],
  58. { stdio: "inherit" },
  59. );
  60. child.on("error", reject);
  61. child.on("exit", (code) =>
  62. code === 0 ? accept() : reject(new Error(`Agent fixture build failed: ${name} (${code})`)),
  63. );
  64. });
  65. }
  66. }
  67. const shared = join(root, "packages/shared/src");
  68. const sharedExports = JSON.parse(await readFile(join(shared, "../package.json"), "utf8")).exports;
  69. const alias = {
  70. "@": join(root, "packages/ui/src"),
  71. ...Object.fromEntries(
  72. Object.entries(sharedExports).map(([key, value]) => [
  73. key === "." ? "@zcode/shared" : `@zcode/shared/${key.slice(2)}`,
  74. resolve(shared, "..", value),
  75. ]),
  76. ),
  77. "@modelcontextprotocol/ext-apps": require.resolve("@modelcontextprotocol/ext-apps", {
  78. paths: [join(root, "packages/ui")],
  79. }),
  80. "@modelcontextprotocol/ext-apps/app-bridge": require.resolve(
  81. "@modelcontextprotocol/ext-apps/app-bridge",
  82. { paths: [join(root, "packages/ui")] },
  83. ),
  84. };
  85. const bundle = (entry, file, platform = "browser") =>
  86. build({
  87. entryPoints: [entry],
  88. outfile: join(output, file),
  89. bundle: true,
  90. platform,
  91. jsx: "automatic",
  92. format: platform === "node" ? "cjs" : "iife",
  93. external: ["electron"],
  94. loader: { ".png": "dataurl", ".svg": "dataurl" },
  95. plugins: [
  96. {
  97. name: "fixture-url-assets",
  98. setup(builder) {
  99. builder.onResolve({ filter: /\?raw$/ }, (args) => ({
  100. path: resolve(args.resolveDir, args.path.slice(0, -4)),
  101. namespace: "fixture-raw",
  102. }));
  103. builder.onLoad({ filter: /.*/, namespace: "fixture-raw" }, async (args) => ({
  104. contents: await readFile(args.path, "utf8"),
  105. loader: "text",
  106. }));
  107. builder.onResolve({ filter: /\?url$/ }, (args) => ({
  108. path: require.resolve(args.path.slice(0, -4), { paths: [args.resolveDir] }),
  109. namespace: "fixture-url",
  110. }));
  111. builder.onLoad({ filter: /.*/, namespace: "fixture-url" }, async (args) => ({
  112. contents: await readFile(args.path),
  113. loader: "file",
  114. }));
  115. },
  116. },
  117. ],
  118. alias,
  119. define: {
  120. "process.env.NODE_ENV": '"production"',
  121. "import.meta.env": '{"DEV":false,"PROD":true,"BASE_URL":"./"}',
  122. },
  123. logLevel: "warning",
  124. });
  125. await Promise.all([
  126. bundle(join(fixture, "main.ts"), "main.cjs", "node"),
  127. bundle(join(fixture, "chain-main.ts"), "chain-main.cjs", "node"),
  128. bundle(join(fixture, "showcase-main.ts"), "showcase-main.cjs", "node"),
  129. bundle(join(desktop, "src/renderer/src/plugin-sandbox/alias.ts"), "plugin-sandbox-alias.js"),
  130. bundle(join(fixture, "sampling-main.ts"), "sampling-main.cjs", "node"),
  131. bundle(join(fixture, "managed-empty-main.ts"), "managed-empty-main.cjs", "node"),
  132. bundle(join(fixture, "managed-main.ts"), "managed-main.cjs", "node"),
  133. bundle(join(fixture, "interaction-main.ts"), "interaction-main.cjs", "node"),
  134. bundle(join(fixture, "rows-main.ts"), "rows-main.cjs", "node"),
  135. bundle(join(fixture, "managed-renderer.tsx"), "managed.js"),
  136. bundle(join(fixture, "retention-main.ts"), "retention-main.cjs", "node"),
  137. bundle(join(fixture, "retention-renderer.ts"), "retention.js"),
  138. bundle(join(fixture, "preload.ts"), "preload.cjs", "node"),
  139. bundle(join(fixture, "renderer.ts"), "host.js"),
  140. bundle(join(fixture, "widget.tsx"), "widget.js"),
  141. bundle(join(desktop, "src/preload/pluginSandbox/index.ts"), "guest.cjs", "node"),
  142. bundle(join(desktop, "src/renderer/src/plugin-sandbox/main.ts"), "shell.js"),
  143. ]);
  144. await Promise.all([
  145. writeFile(
  146. join(output, "host.html"),
  147. '<!doctype html><body><div id="inline" style="position:absolute;left:20px;top:20px;width:400px;height:300px"></div><div id="sidebar" style="position:absolute;right:20px;top:20px;width:450px;height:600px"></div><script src="host.js"></script>',
  148. ),
  149. writeFile(
  150. join(output, "plugin-sandbox.html"),
  151. '<!doctype html><style>html,body,#root,iframe{width:100%;height:100%;margin:0;border:0}iframe{display:block}</style><div id="root"></div><script src="/assets/shell.js"></script>',
  152. ),
  153. writeFile(
  154. join(output, "widget.html"),
  155. '<!doctype html><html><head></head><body><div id="root"></div><script>' +
  156. (await readFile(join(output, "widget.js"), "utf8")).replaceAll("</script", "<\\/script") +
  157. "</script></body></html>",
  158. ),
  159. ]);
  160. const { mkdir, copyFile } = await import("node:fs/promises");
  161. await mkdir(join(output, "assets"));
  162. await copyFile(join(output, "shell.js"), join(output, "assets/shell.js"));
  163. await copyFile(join(fixture, "mcp-server.mjs"), join(output, "mcp-server.mjs"));
  164. await writeFile(
  165. join(output, "retention.html"),
  166. '<!doctype html><body><script src="retention.js"></script>',
  167. );
  168. await writeFile(
  169. join(output, "managed.html"),
  170. '<!doctype html><meta charset="utf-8"><style>.h-full{height:100%}.w-full{width:100%}.flex{display:flex}.flex-col{flex-direction:column}.flex-1{flex:1}.min-h-0{min-height:0}.overflow-y-auto{overflow-y:auto}.relative{position:relative}</style><body><div id="root"></div><script src="managed.js"></script>',
  171. );
  172. const electron = require("electron");
  173. const modes = process.argv.includes("--showcase-only")
  174. ? ["showcase"]
  175. : process.argv.includes("--sampling-only")
  176. ? ["sampling"]
  177. : process.argv.includes("--rows-only")
  178. ? ["rows"]
  179. : process.argv.includes("--managed-only")
  180. ? ["interaction", "managed", "managed-empty"]
  181. : process.argv.includes("--chain-only")
  182. ? ["chain"]
  183. : process.argv.includes("--retention-only")
  184. ? ["retention"]
  185. : process.argv.includes("--storage-only")
  186. ? ["write", "read", "empty"]
  187. : [
  188. "write",
  189. "read",
  190. "empty",
  191. "chain",
  192. "interaction",
  193. "managed",
  194. "managed-empty",
  195. "retention",
  196. "rows",
  197. "sampling",
  198. ];
  199. for (const mode of modes) {
  200. await new Promise((accept, reject) => {
  201. const env = { ...process.env };
  202. delete env.ELECTRON_RUN_AS_NODE;
  203. const child = spawn(
  204. electron,
  205. mode === "chain" ||
  206. mode === "interaction" ||
  207. mode === "managed" ||
  208. mode === "rows" ||
  209. mode === "sampling" ||
  210. mode === "showcase"
  211. ? [
  212. join(output, `${mode}-main.cjs`),
  213. output,
  214. join(output, `${mode}-profile`),
  215. process.execPath,
  216. join(root, "apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  217. showcaseServer ?? "",
  218. ]
  219. : mode === "managed-empty"
  220. ? [join(output, "managed-empty-main.cjs"), output, join(output, "managed-profile")]
  221. : mode === "retention"
  222. ? [join(output, "retention-main.cjs"), output, join(output, "retention-profile")]
  223. : [join(output, "main.cjs"), output, join(output, "profile"), mode],
  224. { env, stdio: "inherit" },
  225. );
  226. const watchdog = setTimeout(() => {
  227. child.kill("SIGKILL");
  228. reject(new Error(`Electron fixture timed out (${mode})`));
  229. }, 90_000);
  230. child.on("error", reject);
  231. child.on("exit", (code) => {
  232. clearTimeout(watchdog);
  233. if (code === 0) accept();
  234. else reject(new Error(`Electron fixture failed (${mode}): ${code}`));
  235. });
  236. });
  237. }
  238. process.stdout.write(
  239. JSON.stringify(
  240. {
  241. output,
  242. interaction: modes.includes("interaction")
  243. ? JSON.parse(await readFile(join(output, "interaction-results.json"), "utf8"))
  244. : undefined,
  245. showcase: modes.includes("showcase")
  246. ? JSON.parse(await readFile(join(output, "showcase-results.json"), "utf8"))
  247. : undefined,
  248. samplingDatabase: modes.includes("sampling") ? verifySamplingDatabase(output) : undefined,
  249. sampling: modes.includes("sampling")
  250. ? JSON.parse(await readFile(join(output, "sampling-results.json"), "utf8"))
  251. : undefined,
  252. rows: modes.includes("rows")
  253. ? JSON.parse(await readFile(join(output, "rows-results.json"), "utf8"))
  254. : undefined,
  255. managed: modes.includes("managed")
  256. ? JSON.parse(await readFile(join(output, "managed-results.json"), "utf8"))
  257. : undefined,
  258. managedStorage: modes.includes("managed-empty")
  259. ? JSON.parse(await readFile(join(output, "managed-storage-empty.json"), "utf8"))
  260. : undefined,
  261. chain: modes.includes("chain")
  262. ? JSON.parse(await readFile(join(output, "chain-results.json"), "utf8"))
  263. : undefined,
  264. retention: modes.includes("retention")
  265. ? JSON.parse(await readFile(join(output, "retention-results.json"), "utf8"))
  266. : undefined,
  267. metrics: await Promise.all(
  268. modes
  269. .filter((mode) => ["write", "read", "empty"].includes(mode))
  270. .map(async (mode) =>
  271. JSON.parse(await readFile(join(output, `metrics-${mode}.json`), "utf8")),
  272. ),
  273. ),
  274. },
  275. null,
  276. 2,
  277. ) + "\n",
  278. );