chain-main.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { app, BrowserWindow, ipcMain, protocol, webContents, type WebContents } from "electron";
  2. import assert from "node:assert/strict";
  3. import { writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import {
  6. installPluginSandboxHost,
  7. PLUGIN_SANDBOX_PRIVILEGED_SCHEME,
  8. } from "../../src/main/pluginSandbox/index.js";
  9. import { createPluginUiBridgeService } from "../../../services/src/plugin-ui-bridge/pluginUiBridgeService.js";
  10. import { startAgent } from "./agent.js";
  11. import { checkCombinations } from "./chain-combinations.js";
  12. import { evaluateGuest } from "./guest-evaluation.js";
  13. const [root, profile, node, cli] = process.argv.slice(2) as [string, string, string, string];
  14. app.setPath("userData", profile);
  15. protocol.registerSchemesAsPrivileged([PLUGIN_SANDBOX_PRIVILEGED_SCHEME]);
  16. app.on("window-all-closed", () => {});
  17. app
  18. .whenReady()
  19. .then(async () => {
  20. const agent = await startAgent(root, node, cli);
  21. const checks: { name: string; ms: number }[] = [];
  22. const windows: BrowserWindow[] = [];
  23. const guests = new Map<number, WebContents>();
  24. const scopes = new Map<number, any>();
  25. const handles = new Map<number, any>();
  26. const calls: any[] = [];
  27. const host = installPluginSandboxHost({
  28. rendererDir: root,
  29. aliasDir: root,
  30. preloadPath: join(root, "guest.cjs"),
  31. });
  32. const wire = (params: any) => {
  33. const {
  34. workspacePath,
  35. workspaceIdentity,
  36. scopeId: _scope,
  37. resourceUri: _uri,
  38. ownerWebContentsId: _owner,
  39. csp: _csp,
  40. prefersBorder: _border,
  41. ...rest
  42. } = params;
  43. return {
  44. ...rest,
  45. workspace: {
  46. workspacePath,
  47. workspaceKey: workspaceIdentity?.trim() || workspacePath,
  48. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  49. },
  50. };
  51. };
  52. const bridge = createPluginUiBridgeService({
  53. openInstance: (p) =>
  54. agent.call("mcp/uiOpenInstance", {
  55. workspace: wire(p).workspace,
  56. sessionId: p.sessionId,
  57. pluginId: p.pluginId,
  58. serverName: p.serverName,
  59. resourceUri: p.resourceUri,
  60. scopeId: p.scopeId,
  61. ownerWebContentsId: p.ownerWebContentsId,
  62. }),
  63. validateInstance: (p) => agent.call("mcp/uiValidateInstance", wire(p)),
  64. closeInstance: (p) => agent.call("mcp/uiCloseInstance", wire(p)),
  65. recycleInstance: async (p) =>
  66. (await agent.call("mcp/uiCloseInstance", { ...wire(p), onlyIfIdle: true })).closed,
  67. readMcpResource: (p) => agent.call("mcp/readResource", wire(p)),
  68. callMcpToolForUi: (p) => {
  69. calls.push(p);
  70. return agent.call("mcp/uiCallTool", wire(p));
  71. },
  72. cancelMcpToolCallForUi: (p) => agent.call("mcp/uiCancelCall", wire(p)),
  73. readMcpResourceForUi: (p) => agent.call("mcp/uiReadResource", wire(p)),
  74. listMcpResourcesForUi: (p) => agent.call("mcp/uiListResources", wire(p)),
  75. registerSandbox: async (input) => {
  76. const handle = host.registerFromHost(input);
  77. handles.set(input.ownerWebContentsId, handle);
  78. return handle;
  79. },
  80. });
  81. ipcMain.handle("fixture-config", (event) => {
  82. const scope = scopes.get(event.sender.id)!;
  83. return {
  84. scope: {
  85. workspacePath: scope.workspace.workspacePath,
  86. ...(scope.workspace.workspaceIdentity
  87. ? { workspaceIdentity: scope.workspace.workspaceIdentity }
  88. : {}),
  89. sessionId: scope.sessionId,
  90. scope: { kind: "surface", surfaceId: "same" },
  91. },
  92. presentation: {
  93. pluginId: scope.pluginId,
  94. serverName: scope.serverName,
  95. resourceUri: "ui://fixture",
  96. },
  97. };
  98. });
  99. ipcMain.handle("fixture-bridge", async (event, method, params) => {
  100. const scope = scopes.get(event.sender.id);
  101. assert.equal(params.sessionId, scope.sessionId);
  102. assert.equal(params.serverName, scope.serverName);
  103. if (method === "prepareSandbox") {
  104. // 同一逻辑页面并发初始化经过生产 bridge,必须只有一次 MCP read 与 Main register。
  105. const [a, b] = await Promise.all([
  106. bridge.prepareSandbox(params),
  107. bridge.prepareSandbox(params),
  108. ]);
  109. assert.deepEqual(a, b);
  110. return a;
  111. }
  112. const fn = (bridge as any)[method];
  113. assert.equal(typeof fn, "function");
  114. return fn(params);
  115. });
  116. async function createWindow(scope: any) {
  117. const win = new BrowserWindow({
  118. show: false,
  119. width: 1000,
  120. height: 700,
  121. webPreferences: {
  122. preload: join(root, "preload.cjs"),
  123. webviewTag: true,
  124. backgroundThrottling: false,
  125. },
  126. });
  127. windows.push(win);
  128. scopes.set(win.webContents.id, scope);
  129. const pending: string[] = [];
  130. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  131. const result = host.configureGuest({
  132. webPreferences,
  133. params,
  134. ownerWebContentsId: win.webContents.id,
  135. });
  136. if (!result.ok) event.preventDefault();
  137. else pending.push(result.sandboxId);
  138. });
  139. win.webContents.on("did-attach-webview", (_event, guest) => {
  140. guests.set(win.webContents.id, guest);
  141. host.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! });
  142. });
  143. await win.loadFile(join(root, "host.html"));
  144. await win.webContents.executeJavaScript("window.harnessReady");
  145. await evaluateGuest(guests.get(win.webContents.id)!, "window.fixtureReady");
  146. return win;
  147. }
  148. async function closeWindow(win: BrowserWindow) {
  149. if (win.isDestroyed()) return;
  150. const guest = guests.get(win.webContents.id);
  151. const closed =
  152. guest && !guest.isDestroyed()
  153. ? new Promise<void>((resolve) => guest.once("destroyed", resolve))
  154. : Promise.resolve();
  155. win.destroy();
  156. await closed;
  157. }
  158. const evalPage = (win: BrowserWindow, code: string) =>
  159. evaluateGuest(guests.get(win.webContents.id)!, code);
  160. async function check(name: string, run: () => Promise<void>) {
  161. const start = performance.now();
  162. await run();
  163. checks.push({ name, ms: performance.now() - start });
  164. process.stdout.write(`PASS ${name}\n`);
  165. }
  166. const approval = (key: string) =>
  167. agent.approvals.wait((request) => request.params.input?.key === key);
  168. const executed = (key: string) =>
  169. agent.events.history.filter((event) => event.type === "executed" && event.key === key).length;
  170. const scope = await agent.session(join(root, "workspace-a"), "source-a");
  171. const win = await createWindow(scope);
  172. try {
  173. await check("concurrent prepare reads once and mounts one guest", async () => {
  174. assert.equal(
  175. agent.events.history.filter(
  176. (event) => event.type === "read" && event.source === "source-a",
  177. ).length,
  178. 1,
  179. );
  180. assert.equal(
  181. webContents.getAllWebContents().filter((contents) => contents.getType() === "webview")
  182. .length,
  183. 1,
  184. );
  185. });
  186. await check(
  187. "app-only tool approval and untruncated raw result without conversation turn",
  188. async () => {
  189. const result = evalPage(win, "window.callTool('raw')");
  190. await agent.respond(await approval("raw"), "allow");
  191. const response = await result;
  192. assert.equal(response.result.content[0].text.length, 40_000);
  193. assert.deepEqual(response.result.structuredContent, { key: "raw", source: "source-a" });
  194. assert.deepEqual(response.result._meta, { fixture: true });
  195. assert.equal(executed("raw"), 1);
  196. const snapshot = await agent.call("session/read", { sessionId: scope.sessionId });
  197. assert.equal(snapshot.messages.length, 0);
  198. },
  199. );
  200. await check("denied approval never reaches MCP tool", async () => {
  201. const result = evalPage(win, "window.callTool('denied')");
  202. await agent.respond(await approval("denied"), "deny");
  203. assert.ok((await result).error);
  204. assert.equal(executed("denied"), 0);
  205. });
  206. await check(
  207. "cancellation before admission and after success never replays a call",
  208. async () => {
  209. const instance = handles.get(win.webContents.id).instance;
  210. const binding = { ...scope, instance, callId: "cancel-before-admission" };
  211. assert.equal((await agent.call("mcp/uiCancelCall", binding)).cancelled, false);
  212. await assert.rejects(() =>
  213. agent.call("mcp/uiCallTool", {
  214. ...binding,
  215. toolName: "edit",
  216. arguments: { key: "before-admission" },
  217. }),
  218. );
  219. assert.equal(executed("before-admission"), 0);
  220. const completed = calls.find((call) => call.arguments.key === "raw");
  221. await assert.rejects(() => agent.call("mcp/uiCallTool", wire(completed)));
  222. const { toolName: _tool, arguments: _args, ...cancel } = completed;
  223. assert.equal((await bridge.cancelToolCall(cancel)).cancelled, false);
  224. assert.equal(executed("raw"), 1);
  225. },
  226. );
  227. await check("SDK cancellation reaches real MCP process and rejects late result", async () => {
  228. const result = evalPage(win, "window.callTool('cancelled',true)");
  229. await agent.respond(await approval("cancelled"), "allow");
  230. await agent.events.wait((event) => event.type === "executed" && event.key === "cancelled");
  231. await evalPage(win, "window.cancelTool('cancelled')");
  232. await agent.events.wait((event) => event.type === "cancelled" && event.key === "cancelled");
  233. assert.ok((await result).error);
  234. agent.release("source-a", "cancelled");
  235. await agent.events.wait((event) => event.type === "released" && event.key === "cancelled");
  236. assert.equal(executed("cancelled"), 1);
  237. });
  238. await check("duplicate callId executes once and cancellation is idempotent", async () => {
  239. const result = evalPage(win, "window.callTool('duplicate',true)");
  240. await agent.respond(await approval("duplicate"), "allow");
  241. await agent.events.wait((event) => event.type === "executed" && event.key === "duplicate");
  242. const binding = calls.find((call) => call.arguments.key === "duplicate");
  243. await assert.rejects(() => agent.call("mcp/uiCallTool", wire(binding)));
  244. const { toolName: _tool, arguments: _args, ...cancel } = binding;
  245. assert.equal((await bridge.cancelToolCall(cancel)).cancelled, true);
  246. assert.equal((await bridge.cancelToolCall(cancel)).cancelled, false);
  247. assert.ok((await result).error);
  248. assert.equal(executed("duplicate"), 1);
  249. });
  250. await check(
  251. "pending approval pins instance and late approval cannot run closed generation",
  252. async () => {
  253. const pending = evalPage(win, "window.callTool('late-approval')").catch(() => ({
  254. closed: true,
  255. }));
  256. const request = await approval("late-approval");
  257. const old = handles.get(win.webContents.id);
  258. const binding = {
  259. workspacePath: scope.workspace.workspacePath,
  260. sessionId: scope.sessionId,
  261. pluginId: scope.pluginId,
  262. serverName: scope.serverName,
  263. instance: old.instance,
  264. };
  265. assert.equal(await bridge.recycleInstance(binding), false);
  266. await win.webContents.executeJavaScript("window.disposePage()");
  267. await win.webContents.executeJavaScript("window.restorePage(false)");
  268. await evalPage(win, "window.fixtureReady");
  269. assert.notEqual(handles.get(win.webContents.id).instance.token, old.instance.token);
  270. await agent.respond(request, "allow");
  271. await pending;
  272. assert.equal(executed("late-approval"), 0);
  273. // 旧 dispose 到达新登记之后,也不能拆掉替换页面。
  274. await win.webContents.executeJavaScript(
  275. `window.harness.dispose(${JSON.stringify(old.sandboxId)},${old.initId})`,
  276. );
  277. const result = evalPage(win, "window.callTool('new-approval')");
  278. await agent.respond(await approval("new-approval"), "deny");
  279. assert.ok((await result).error);
  280. assert.equal(executed("new-approval"), 0);
  281. assert.ok(!guests.get(win.webContents.id)!.isDestroyed());
  282. },
  283. );
  284. await check(
  285. "same surface in different windows keeps independent guest and widget snapshot",
  286. async () => {
  287. const second = await createWindow(scope);
  288. assert.notEqual(
  289. guests.get(win.webContents.id)!.id,
  290. guests.get(second.webContents.id)!.id,
  291. );
  292. assert.notEqual(
  293. handles.get(win.webContents.id).instance.token,
  294. handles.get(second.webContents.id).instance.token,
  295. );
  296. await evalPage(win, "window.saveWidget({window:1})");
  297. assert.equal(await evalPage(second, "window.readWidget()"), null);
  298. await evalPage(win, "window.storageRoundTrip(true)");
  299. assert.deepEqual(await evalPage(second, "window.storageRoundTrip(false)"), {
  300. local: "42",
  301. indexed: 42,
  302. });
  303. await closeWindow(second);
  304. assert.ok(!guests.get(win.webContents.id)!.isDestroyed());
  305. },
  306. );
  307. await check(
  308. "same surface across server and workspace identities isolates browser storage",
  309. async () => {
  310. for (const [workspace, server, identity] of [
  311. ["workspace-a", "other"],
  312. ["workspace-b", "fixture"],
  313. ["workspace-a", "fixture", "fixture-other-workspace"],
  314. ]) {
  315. // 连接命令、参数、资源、surface 完全相同,每次只改变一个身份维度。
  316. const otherScope = await agent.session(
  317. join(root, workspace!),
  318. "source-a",
  319. server!,
  320. identity,
  321. );
  322. const other = await createWindow(otherScope);
  323. assert.notEqual(
  324. handles.get(win.webContents.id).partition,
  325. handles.get(other.webContents.id).partition,
  326. );
  327. assert.deepEqual(await evalPage(other, "window.storageRoundTrip(false)"), {
  328. local: null,
  329. indexed: null,
  330. });
  331. await closeWindow(other);
  332. await agent.call("session/close", { sessionId: otherScope.sessionId });
  333. }
  334. },
  335. );
  336. await checkCombinations({
  337. agent,
  338. win,
  339. scope,
  340. handles,
  341. guests,
  342. calls,
  343. bridge,
  344. wire,
  345. evalPage,
  346. createWindow,
  347. closeWindow,
  348. check,
  349. });
  350. await check("connection revoked during approval rejects late allow", async () => {
  351. const result = evalPage(win, "window.callTool('disconnect')");
  352. const request = await approval("disconnect");
  353. agent.disconnect("source-a");
  354. assert.ok((await result).error);
  355. await agent.respond(request, "allow");
  356. assert.equal(executed("disconnect"), 0);
  357. await assert.rejects(() =>
  358. agent.call("mcp/uiValidateInstance", {
  359. ...scope,
  360. instance: handles.get(win.webContents.id).instance,
  361. }),
  362. );
  363. });
  364. for (const window of windows) if (!window.isDestroyed()) await closeWindow(window);
  365. assert.equal(
  366. webContents.getAllWebContents().filter((contents) => contents.getType() === "webview")
  367. .length,
  368. 0,
  369. );
  370. await writeFile(
  371. join(root, "chain-results.json"),
  372. JSON.stringify(
  373. {
  374. checks,
  375. executions: agent.events.history.filter((event) => event.type === "executed"),
  376. remainingGuests: 0,
  377. },
  378. null,
  379. 2,
  380. ),
  381. );
  382. } finally {
  383. for (const window of windows) if (!window.isDestroyed()) await closeWindow(window);
  384. await agent.close();
  385. }
  386. app.exit(0);
  387. })
  388. .catch((error) => {
  389. process.stderr.write(String(error.stack ?? error) + "\n");
  390. app.exit(1);
  391. });