mcp-apps-host-e2e.mjs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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, "background-main.ts"), "background-main.cjs", "node"),
  134. bundle(join(fixture, "interaction-main.ts"), "interaction-main.cjs", "node"),
  135. bundle(join(fixture, "rows-main.ts"), "rows-main.cjs", "node"),
  136. bundle(join(fixture, "managed-renderer.tsx"), "managed.js"),
  137. bundle(join(fixture, "retention-main.ts"), "retention-main.cjs", "node"),
  138. bundle(join(fixture, "retention-renderer.ts"), "retention.js"),
  139. bundle(join(fixture, "preload.ts"), "preload.cjs", "node"),
  140. bundle(join(fixture, "renderer.ts"), "host.js"),
  141. bundle(join(fixture, "widget.tsx"), "widget.js"),
  142. bundle(join(desktop, "src/preload/pluginSandbox/index.ts"), "guest.cjs", "node"),
  143. bundle(join(desktop, "src/renderer/src/plugin-sandbox/main.ts"), "shell.js"),
  144. ]);
  145. await Promise.all([
  146. writeFile(
  147. join(output, "host.html"),
  148. '<!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>',
  149. ),
  150. writeFile(
  151. join(output, "plugin-sandbox.html"),
  152. '<!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>',
  153. ),
  154. writeFile(
  155. join(output, "widget.html"),
  156. '<!doctype html><html><head></head><body><div id="root"></div><script>' +
  157. (await readFile(join(output, "widget.js"), "utf8")).replaceAll("</script", "<\\/script") +
  158. "</script></body></html>",
  159. ),
  160. ]);
  161. const { mkdir, copyFile } = await import("node:fs/promises");
  162. await mkdir(join(output, "assets"));
  163. await copyFile(join(output, "shell.js"), join(output, "assets/shell.js"));
  164. await copyFile(join(fixture, "mcp-server.mjs"), join(output, "mcp-server.mjs"));
  165. await writeFile(
  166. join(output, "retention.html"),
  167. '<!doctype html><body><script src="retention.js"></script>',
  168. );
  169. await writeFile(
  170. join(output, "managed.html"),
  171. '<!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>',
  172. );
  173. const electron = require("electron");
  174. const modes =
  175. process.argv.includes("--background-only") ||
  176. process.argv.includes("--photocraft-background-only")
  177. ? ["background"]
  178. : process.argv.includes("--showcase-only")
  179. ? ["showcase"]
  180. : process.argv.includes("--sampling-only")
  181. ? ["sampling"]
  182. : process.argv.includes("--rows-only")
  183. ? ["rows"]
  184. : process.argv.includes("--managed-only")
  185. ? ["interaction", "managed", "managed-empty"]
  186. : process.argv.includes("--chain-only")
  187. ? ["chain"]
  188. : process.argv.includes("--retention-only")
  189. ? ["retention"]
  190. : process.argv.includes("--storage-only")
  191. ? ["write", "read", "empty"]
  192. : [
  193. "write",
  194. "read",
  195. "empty",
  196. "chain",
  197. "interaction",
  198. "managed",
  199. "managed-empty",
  200. "retention",
  201. "rows",
  202. "sampling",
  203. "background",
  204. ];
  205. for (const mode of modes) {
  206. await new Promise((accept, reject) => {
  207. const env = { ...process.env };
  208. if (process.argv.includes("--photocraft-background-only")) {
  209. if (!env.ZCODE_PHOTOCRAFT_SERVER)
  210. throw new Error("Set ZCODE_PHOTOCRAFT_SERVER to the built PhotoCraft dist/server.mjs");
  211. env.ZCODE_PHOTOCRAFT_ONLY = "1";
  212. }
  213. delete env.ELECTRON_RUN_AS_NODE;
  214. const child = spawn(
  215. electron,
  216. mode === "background" ||
  217. mode === "chain" ||
  218. mode === "interaction" ||
  219. mode === "managed" ||
  220. mode === "rows" ||
  221. mode === "sampling" ||
  222. mode === "showcase"
  223. ? [
  224. join(output, `${mode}-main.cjs`),
  225. output,
  226. join(output, `${mode}-profile`),
  227. process.execPath,
  228. join(root, "apps/zcode-cli/packages/cli/dist/zcode.cjs"),
  229. showcaseServer ?? "",
  230. ]
  231. : mode === "managed-empty"
  232. ? [join(output, "managed-empty-main.cjs"), output, join(output, "managed-profile")]
  233. : mode === "retention"
  234. ? [join(output, "retention-main.cjs"), output, join(output, "retention-profile")]
  235. : [join(output, "main.cjs"), output, join(output, "profile"), mode],
  236. { env, stdio: "inherit" },
  237. );
  238. const watchdog = setTimeout(
  239. () => {
  240. child.kill("SIGKILL");
  241. reject(new Error(`Electron fixture timed out (${mode})`));
  242. },
  243. mode === "background" ? (process.env.ZCODE_PHOTOCRAFT_SERVER ? 300_000 : 180_000) : 90_000,
  244. );
  245. child.on("error", reject);
  246. child.on("exit", (code) => {
  247. clearTimeout(watchdog);
  248. if (code === 0) accept();
  249. else reject(new Error(`Electron fixture failed (${mode}): ${code}`));
  250. });
  251. });
  252. }
  253. process.stdout.write(
  254. JSON.stringify(
  255. {
  256. output,
  257. background: modes.includes("background")
  258. ? JSON.parse(await readFile(join(output, "background-results.json"), "utf8"))
  259. : undefined,
  260. interaction: modes.includes("interaction")
  261. ? JSON.parse(await readFile(join(output, "interaction-results.json"), "utf8"))
  262. : undefined,
  263. showcase: modes.includes("showcase")
  264. ? JSON.parse(await readFile(join(output, "showcase-results.json"), "utf8"))
  265. : undefined,
  266. samplingDatabase: modes.includes("sampling") ? verifySamplingDatabase(output) : undefined,
  267. sampling: modes.includes("sampling")
  268. ? JSON.parse(await readFile(join(output, "sampling-results.json"), "utf8"))
  269. : undefined,
  270. rows: modes.includes("rows")
  271. ? JSON.parse(await readFile(join(output, "rows-results.json"), "utf8"))
  272. : undefined,
  273. managed: modes.includes("managed")
  274. ? JSON.parse(await readFile(join(output, "managed-results.json"), "utf8"))
  275. : undefined,
  276. managedStorage: modes.includes("managed-empty")
  277. ? JSON.parse(await readFile(join(output, "managed-storage-empty.json"), "utf8"))
  278. : undefined,
  279. chain: modes.includes("chain")
  280. ? JSON.parse(await readFile(join(output, "chain-results.json"), "utf8"))
  281. : undefined,
  282. retention: modes.includes("retention")
  283. ? JSON.parse(await readFile(join(output, "retention-results.json"), "utf8"))
  284. : undefined,
  285. metrics: await Promise.all(
  286. modes
  287. .filter((mode) => ["write", "read", "empty"].includes(mode))
  288. .map(async (mode) =>
  289. JSON.parse(await readFile(join(output, `metrics-${mode}.json`), "utf8")),
  290. ),
  291. ),
  292. },
  293. null,
  294. 2,
  295. ) + "\n",
  296. );