managed-environment.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 === "session/lifecycle/changed") {
  82. for (const win of windows) {
  83. if (
  84. !win.isDestroyed() &&
  85. scopes.get(win.webContents.id)?.sessionId === event.params.sessionId
  86. )
  87. win.webContents.send("fixture-notification", {
  88. kind: "session-lifecycle",
  89. value: event.params,
  90. });
  91. }
  92. return;
  93. }
  94. if (event.method === "v4/plugin-ui/tool-result") {
  95. for (const win of windows) {
  96. if (win.isDestroyed()) continue;
  97. const scope = scopes.get(win.webContents.id);
  98. if (scope?.sessionId === event.params.sessionId)
  99. win.webContents.send("fixture-notification", {
  100. kind: "ui-result",
  101. value: {
  102. ...event.params,
  103. workspacePath: scope.workspace.workspacePath,
  104. },
  105. });
  106. }
  107. return;
  108. }
  109. if (event.method !== "v4/conversation/frame") return;
  110. for (const win of windows) {
  111. if (
  112. !win.isDestroyed() &&
  113. event.params.topic === `conversation/${scopes.get(win.webContents.id)?.sessionId}`
  114. )
  115. win.webContents.send("fixture-notification", { kind: "frame", value: event.params });
  116. }
  117. });
  118. ipcMain.handle("fixture-config", (event) => {
  119. const scope = scopes.get(event.sender.id);
  120. return {
  121. mode: modes.get(event.sender.id),
  122. scope: {
  123. ...scope.workspace,
  124. sessionId: scope.sessionId,
  125. scope: { kind: "surface", surfaceId: scope.surface ?? "same" },
  126. },
  127. presentation: {
  128. pluginId: scope.pluginId,
  129. serverName: scope.serverName,
  130. resourceUri: scope.resourceUri ?? "ui://fixture",
  131. },
  132. };
  133. });
  134. ipcMain.handle("fixture-event", (event, value) =>
  135. events.emit({ ...value, owner: event.sender.id }),
  136. );
  137. ipcMain.handle("fixture-bridge", async (event, method, params) => {
  138. const scope = scopes.get(event.sender.id);
  139. assert.equal(params.sessionId, scope.sessionId);
  140. assert.equal(params.serverName, scope.serverName);
  141. events.emit({ type: "bridge-arrived", method, owner: event.sender.id });
  142. const result = await ({ ...bridge, ...sampling } as any)[method](params);
  143. events.emit({ type: "bridge", method, owner: event.sender.id });
  144. await gates.get(`return:${method}`);
  145. return result;
  146. });
  147. ipcMain.handle("fixture-app-tools", async (event, method, params) => {
  148. const methods: Record<string, string> = {
  149. registerAppTools: "mcp/uiRegisterAppTools",
  150. unregisterAppTools: "mcp/uiUnregisterAppTools",
  151. claimAppToolCall: "mcp/uiClaimAppToolCall",
  152. resolveAppToolCall: "mcp/uiResolveAppToolCall",
  153. };
  154. assert.ok(methods[method]);
  155. events.emit({ type: "app-tools-arrived", method, owner: event.sender.id, params });
  156. await gates.get(method);
  157. const result = await agent.call(methods[method]!, { ...wire(params), scopeId: params.scopeId });
  158. events.emit({ type: method, owner: event.sender.id, params, result });
  159. return result;
  160. });
  161. ipcMain.handle("fixture-v4", async (event, method, params) => {
  162. const scope = scopes.get(event.sender.id);
  163. const connectionId = `managed-${event.sender.id}`;
  164. if (method === "helloConversationV4")
  165. return {
  166. kind: "hello",
  167. protocolVersion: V4_WIRE_PROTOCOL_VERSION,
  168. connectionId,
  169. clientMode: "desktop-continuous",
  170. deliveryProfile: "continuous",
  171. serverTime: Date.now(),
  172. capabilities: {
  173. nativeDialogs: true,
  174. localTerminal: true,
  175. binaryFrames: false,
  176. compression: "none",
  177. independentPlanState: true,
  178. },
  179. auth: {},
  180. };
  181. if (method === "initializeConversationV4") return;
  182. if (method === "getSessionLifecycle")
  183. return agent.call("session/lifecycle/getState", { sessionId: params.sessionId });
  184. if (method === "subscribeConversationV4") {
  185. const result = await agent.call("v4/conversation/subscribe", {
  186. connectionId,
  187. clientMode: "desktop-continuous",
  188. workspace: scope.workspace,
  189. topic: `conversation/${params.sessionId}`,
  190. ...(params.visibility ? { visibility: params.visibility } : {}),
  191. });
  192. events.emit({ type: "subscribed", owner: event.sender.id });
  193. return result;
  194. }
  195. if (method === "unsubscribeConversationV4") {
  196. const result = await agent.call("v4/conversation/unsubscribe", {
  197. connectionId,
  198. topic: `conversation/${params.sessionId}`,
  199. subscriptionId: params.subscriptionId,
  200. });
  201. events.emit({ type: "unsubscribed", owner: event.sender.id });
  202. return result;
  203. }
  204. if (method === "resyncConversationV4")
  205. return agent.call("v4/conversation/resync", { connectionId, ...params });
  206. throw new Error(`Unexpected managed service call ${method}`);
  207. });
  208. async function createWindow(scope: any, mode = "local") {
  209. const win = new BrowserWindow({
  210. show: mode.startsWith("background"),
  211. width: 1000,
  212. height: 700,
  213. webPreferences: {
  214. preload: join(root, "preload.cjs"),
  215. webviewTag: true,
  216. backgroundThrottling: mode.startsWith("background"),
  217. },
  218. });
  219. windows.push(win);
  220. modes.set(win.webContents.id, mode);
  221. scopes.set(win.webContents.id, scope);
  222. win.webContents.on("console-message", (e) => process.stderr.write(`${e.message}\n`));
  223. const pending: string[] = [];
  224. win.webContents.on("will-attach-webview", (event, webPreferences, params) => {
  225. const result = native.configureGuest({
  226. webPreferences,
  227. params,
  228. ownerWebContentsId: win.webContents.id,
  229. });
  230. if (!result.ok) event.preventDefault();
  231. else pending.push(result.sandboxId);
  232. });
  233. win.webContents.on("did-attach-webview", (_event, guest) => {
  234. guests.set(win.webContents.id, guest);
  235. native.attachGuest({ guest, hostWebContents: win.webContents, sandboxId: pending.shift()! });
  236. });
  237. await win.loadFile(join(root, "managed.html"));
  238. if (mode.endsWith("-minimized")) {
  239. // 已加载的宿主窗口先最小化,再发起首个插件请求,覆盖真实后台创建时序。
  240. await win.webContents.executeJavaScript("window.fixturePaused");
  241. win.minimize();
  242. await win.webContents
  243. .executeJavaScript(`document.hidden || new Promise(resolve=>document.addEventListener('visibilitychange',function changed(){
  244. if(document.hidden){document.removeEventListener('visibilitychange',changed);resolve()}
  245. }))`);
  246. await win.webContents.executeJavaScript("window.startFixture()");
  247. }
  248. await win.webContents.executeJavaScript("window.harnessReady");
  249. if (mode !== "local" && mode !== "sampling") return win;
  250. await evaluateGuest(
  251. guests.get(win.webContents.id)!,
  252. scope.resourceUri ? "window.showcaseReady" : "window.fixtureReady",
  253. );
  254. await events.wait((e) => e.type === "subscribed" && e.owner === win.webContents.id);
  255. return win;
  256. }
  257. return {
  258. gates,
  259. model,
  260. agent,
  261. events,
  262. windows,
  263. scopes,
  264. handles,
  265. guests,
  266. native,
  267. wire,
  268. bridge,
  269. createWindow,
  270. evalPage: (win: BrowserWindow, code: string) =>
  271. evaluateGuest(guests.get(win.webContents.id)!, code),
  272. countGuests: () =>
  273. webContents.getAllWebContents().filter((c) => c.getType() === "webview").length,
  274. async close() {
  275. for (const win of windows) if (!win.isDestroyed()) win.destroy();
  276. await agent.close();
  277. await model.close();
  278. },
  279. };
  280. }