managed-environment.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. import { BrowserWindow, ipcMain, webContents, type WebContents } from "electron";
  2. import assert from "node:assert/strict";
  3. import { join } from "node:path";
  4. import { V4_WIRE_PROTOCOL_VERSION } from "@zcode/shared/zcode-protocol-v4";
  5. import { installPluginSandboxHost } from "../../src/main/pluginSandbox/index.js";
  6. import { createPluginUiBridgeService } from "../../../services/src/plugin-ui-bridge/pluginUiBridgeService.js";
  7. import { createPluginUiSamplingService } from "../../../services/src/plugin-ui-bridge/pluginUiSamplingService.js";
  8. import { Events, startAgent } from "./agent.js";
  9. import { startModel } from "./model.js";
  10. import { evaluateGuest } from "./guest-evaluation.js";
  11. export async function managedEnvironment(root: string, node: string, cli: string) {
  12. const model = await startModel(root, cli);
  13. const agent = await startAgent(root, node, cli, model.env);
  14. const events = new Events<any>();
  15. const windows: BrowserWindow[] = [];
  16. const modes = new Map<number, string>();
  17. const scopes = new Map<number, any>();
  18. const gates = new Map<string, Promise<void>>();
  19. const handles = new Map<number, any>();
  20. const guests = new Map<number, WebContents>();
  21. const native = installPluginSandboxHost({
  22. rendererDir: root,
  23. aliasDir: root,
  24. preloadPath: join(root, "guest.cjs"),
  25. logger: { warn: (message) => process.stderr.write(`${message}\n`) },
  26. });
  27. const wire = (p: any) => {
  28. const {
  29. workspacePath,
  30. workspaceIdentity,
  31. scopeId: _scope,
  32. resourceUri: _uri,
  33. ownerWebContentsId: _owner,
  34. csp: _csp,
  35. prefersBorder: _border,
  36. ...rest
  37. } = p;
  38. return {
  39. ...rest,
  40. workspace: {
  41. workspacePath,
  42. workspaceKey: workspaceIdentity?.trim() || workspacePath,
  43. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  44. },
  45. };
  46. };
  47. const sampling = createPluginUiSamplingService({
  48. sample: (p) => agent.call("mcp/uiSampling", wire(p)),
  49. cancelSampling: (p) => agent.call("mcp/uiCancelSampling", wire(p)),
  50. });
  51. const bridge = createPluginUiBridgeService({
  52. openInstance: (p) =>
  53. agent.call("mcp/uiOpenInstance", {
  54. ...wire(p),
  55. resourceUri: p.resourceUri,
  56. scopeId: p.scopeId,
  57. ownerWebContentsId: p.ownerWebContentsId,
  58. }),
  59. validateInstance: (p) => agent.call("mcp/uiValidateInstance", wire(p)),
  60. closeInstance: (p) => agent.call("mcp/uiCloseInstance", wire(p)),
  61. recycleInstance: async (p) =>
  62. (await agent.call("mcp/uiCloseInstance", { ...wire(p), onlyIfIdle: true })).closed,
  63. readMcpResource: (p) => agent.call("mcp/readResource", wire(p)),
  64. callMcpToolForUi: (p) => agent.call("mcp/uiCallTool", wire(p)),
  65. cancelMcpToolCallForUi: (p) => agent.call("mcp/uiCancelCall", wire(p)),
  66. readMcpResourceForUi: (p) => agent.call("mcp/uiReadResource", wire(p)),
  67. listMcpResourcesForUi: (p) => agent.call("mcp/uiListResources", wire(p)),
  68. listMcpResourceTemplatesForUi: (p) => agent.call("mcp/uiListResourceTemplates", wire(p)),
  69. subscribeMcpResourceForUi: (p) =>
  70. agent.call("mcp/uiSubscribeResource", { ...wire(p), scopeId: p.scopeId }),
  71. unsubscribeMcpResourceForUi: (p) =>
  72. agent.call("mcp/uiUnsubscribeResource", { ...wire(p), scopeId: p.scopeId }),
  73. registerSandbox: async (p) => {
  74. const handle = native.registerFromHost(p);
  75. handles.set(p.ownerWebContentsId, handle);
  76. events.emit({ type: "registered", owner: p.ownerWebContentsId, handle });
  77. return handle;
  78. },
  79. });
  80. agent.client.onNotification((event) => {
  81. if (event.method === "v4/plugin-ui/tool-result") {
  82. for (const win of windows) {
  83. if (win.isDestroyed()) continue;
  84. const scope = scopes.get(win.webContents.id);
  85. if (scope?.sessionId === event.params.sessionId)
  86. win.webContents.send("fixture-notification", {
  87. kind: "ui-result",
  88. value: {
  89. ...event.params,
  90. workspacePath: scope.workspace.workspacePath,
  91. },
  92. });
  93. }
  94. return;
  95. }
  96. if (event.method !== "v4/conversation/frame") return;
  97. for (const win of windows) {
  98. if (
  99. !win.isDestroyed() &&
  100. event.params.topic === `conversation/${scopes.get(win.webContents.id)?.sessionId}`
  101. )
  102. win.webContents.send("fixture-notification", { kind: "frame", value: event.params });
  103. }
  104. });
  105. ipcMain.handle("fixture-config", (event) => {
  106. const scope = scopes.get(event.sender.id);
  107. return {
  108. mode: modes.get(event.sender.id),
  109. scope: {
  110. ...scope.workspace,
  111. sessionId: scope.sessionId,
  112. scope: { kind: "surface", surfaceId: scope.surface ?? "same" },
  113. },
  114. presentation: {
  115. pluginId: scope.pluginId,
  116. serverName: scope.serverName,
  117. resourceUri: scope.resourceUri ?? "ui://fixture",
  118. },
  119. };
  120. });
  121. ipcMain.handle("fixture-event", (event, value) =>
  122. events.emit({ ...value, owner: event.sender.id }),
  123. );
  124. ipcMain.handle("fixture-bridge", async (event, method, params) => {
  125. const scope = scopes.get(event.sender.id);
  126. assert.equal(params.sessionId, scope.sessionId);
  127. assert.equal(params.serverName, scope.serverName);
  128. events.emit({ type: "bridge-arrived", method, owner: event.sender.id });
  129. const result = await ({ ...bridge, ...sampling } as any)[method](params);
  130. events.emit({ type: "bridge", method, owner: event.sender.id });
  131. await gates.get(`return:${method}`);
  132. return result;
  133. });
  134. ipcMain.handle("fixture-app-tools", async (event, method, params) => {
  135. const methods: Record<string, string> = {
  136. registerAppTools: "mcp/uiRegisterAppTools",
  137. unregisterAppTools: "mcp/uiUnregisterAppTools",
  138. claimAppToolCall: "mcp/uiClaimAppToolCall",
  139. resolveAppToolCall: "mcp/uiResolveAppToolCall",
  140. };
  141. assert.ok(methods[method]);
  142. events.emit({ type: "app-tools-arrived", method, owner: event.sender.id, params });
  143. await gates.get(method);
  144. const result = await agent.call(methods[method]!, { ...wire(params), scopeId: params.scopeId });
  145. events.emit({ type: method, owner: event.sender.id, params, result });
  146. return result;
  147. });
  148. ipcMain.handle("fixture-v4", async (event, method, params) => {
  149. const scope = scopes.get(event.sender.id);
  150. const connectionId = `managed-${event.sender.id}`;
  151. if (method === "helloConversationV4")
  152. return {
  153. kind: "hello",
  154. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  155. connectionId,
  156. clientMode: "desktop-continuous",
  157. deliveryProfile: "continuous",
  158. serverTime: Date.now(),
  159. capabilities: {
  160. nativeDialogs: true,
  161. localTerminal: true,
  162. binaryFrames: false,
  163. compression: "none",
  164. independentPlanState: true,
  165. },
  166. auth: {},
  167. };
  168. if (method === "initializeConversationV4") return;
  169. if (method === "subscribeConversationV4") {
  170. const result = await agent.call("v4/conversation/subscribe", {
  171. connectionId,
  172. clientMode: "desktop-continuous",
  173. workspace: scope.workspace,
  174. topic: `conversation/${params.sessionId}`,
  175. ...(params.visibility ? { visibility: params.visibility } : {}),
  176. });
  177. events.emit({ type: "subscribed", owner: event.sender.id });
  178. return result;
  179. }
  180. if (method === "unsubscribeConversationV4") {
  181. const result = await agent.call("v4/conversation/unsubscribe", {
  182. connectionId,
  183. topic: `conversation/${params.sessionId}`,
  184. subscriptionId: params.subscriptionId,
  185. });
  186. events.emit({ type: "unsubscribed", owner: event.sender.id });
  187. return result;
  188. }
  189. if (method === "resyncConversationV4")
  190. return agent.call("v4/conversation/resync", { connectionId, ...params });
  191. throw new Error(`Unexpected managed service call ${method}`);
  192. });
  193. async function createWindow(scope: any, mode = "local") {
  194. const win = new BrowserWindow({
  195. show: mode.startsWith("background"),
  196. width: 1000,
  197. height: 700,
  198. webPreferences: {
  199. preload: join(root, "preload.cjs"),
  200. webviewTag: true,
  201. backgroundThrottling: mode.startsWith("background"),
  202. },
  203. });
  204. windows.push(win);
  205. modes.set(win.webContents.id, mode);
  206. scopes.set(win.webContents.id, scope);
  207. win.webContents.on("console-message", (e) => process.stderr.write(`${e.message}\n`));
  208. const pending: string[] = [];
  209. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  210. const result = native.configureGuest({
  211. webPreferences,
  212. params,
  213. ownerWebContentsId: win.webContents.id,
  214. });
  215. if (!result.ok) event.preventDefault();
  216. else pending.push(result.sandboxId);
  217. });
  218. win.webContents.on("did-attach-webview", (_event, guest) => {
  219. guests.set(win.webContents.id, guest);
  220. native.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! });
  221. });
  222. await win.loadFile(join(root, "managed.html"));
  223. if (mode.endsWith("-minimized")) {
  224. // 已加载的宿主窗口先最小化,再发起首个插件请求,覆盖真实后台创建时序。
  225. await win.webContents.executeJavaScript("window.fixturePaused");
  226. win.minimize();
  227. await win.webContents
  228. .executeJavaScript(`document.hidden || new Promise(resolve=>document.addEventListener('visibilitychange',function changed(){
  229. if(document.hidden){document.removeEventListener('visibilitychange',changed);resolve()}
  230. }))`);
  231. await win.webContents.executeJavaScript("window.startFixture()");
  232. }
  233. await win.webContents.executeJavaScript("window.harnessReady");
  234. if (mode !== "local" && mode !== "sampling") return win;
  235. await evaluateGuest(
  236. guests.get(win.webContents.id)!,
  237. scope.resourceUri ? "window.showcaseReady" : "window.fixtureReady",
  238. );
  239. await events.wait((e) => e.type === "subscribed" && e.owner === win.webContents.id);
  240. return win;
  241. }
  242. return {
  243. gates,
  244. model,
  245. agent,
  246. events,
  247. windows,
  248. scopes,
  249. handles,
  250. guests,
  251. native,
  252. wire,
  253. bridge,
  254. createWindow,
  255. evalPage: (win: BrowserWindow, code: string) =>
  256. evaluateGuest(guests.get(win.webContents.id)!, code),
  257. countGuests: () =>
  258. webContents.getAllWebContents().filter((c) => c.getType() === "webview").length,
  259. async close() {
  260. for (const win of windows) if (!win.isDestroyed()) win.destroy();
  261. await agent.close();
  262. await model.close();
  263. },
  264. };
  265. }