mcp-apps-host-e2e.mjs 12 KB

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