renderer.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. import {
  2. createPluginUiHostController,
  3. type PluginUiHostController,
  4. } from "../../../ui/src/plugin-ui/app/pluginUiHostController.js";
  5. import { PluginUiPageManager } from "../../../ui/src/plugin-ui/app/pluginUiPageManager.js";
  6. import {
  7. getPluginUiWidgetState,
  8. setPluginUiWidgetState,
  9. clearPluginUiWidgetState,
  10. } from "../../../ui/src/plugin-ui/app/pluginUiWidgetStateStore.js";
  11. import type { PluginSandboxHandle, PluginSandboxPortsEvent } from "@zcode/shared/mcp-apps";
  12. import { createPluginUiMessagePortTransport } from "../../../ui/src/plugin-ui/adapters/messagePortTransport.js";
  13. import { createPluginUiPagePlane } from "../../../ui/src/plugin-ui/adapters/pluginUiPagePlane.js";
  14. const harness = (window as any).harness;
  15. // 记录生产承载层的活动 window 监听器,重复切换后必须保持恒定。
  16. const tracked = new Map<string, Set<EventListenerOrEventListenerObject>>();
  17. const add = window.addEventListener.bind(window),
  18. remove = window.removeEventListener.bind(window);
  19. (window as any).addEventListener = (
  20. type: string,
  21. listener: EventListenerOrEventListenerObject,
  22. options: any,
  23. ) => {
  24. const entries = tracked.get(type) ?? new Set();
  25. entries.add(listener);
  26. tracked.set(type, entries);
  27. add(type, listener, options);
  28. };
  29. (window as any).removeEventListener = (
  30. type: string,
  31. listener: EventListenerOrEventListenerObject,
  32. options: any,
  33. ) => {
  34. tracked.get(type)?.delete(listener);
  35. remove(type, listener, options);
  36. };
  37. let controller: PluginUiHostController;
  38. let handshakes = 0;
  39. let handle: PluginSandboxHandle;
  40. let portHandler: ((event: PluginSandboxPortsEvent) => void) | undefined;
  41. let ready = Promise.withResolvers<void>();
  42. (window as any).harnessReady = ready.promise;
  43. window.addEventListener("message", (event) => {
  44. if (event.data?.type !== "zcode:plugin-sandbox-ports" || event.ports.length !== 1) return;
  45. portHandler?.({ ...event.data, port: event.ports[0] });
  46. });
  47. const plane = createPluginUiPagePlane({
  48. onVisibility() {},
  49. onCrash() {
  50. throw new Error("fixture crashed");
  51. },
  52. });
  53. const inline = document.getElementById("inline")!;
  54. const sidebar = document.getElementById("sidebar")!;
  55. (window as any).previewPage = async (enabled: boolean) => {
  56. plane.preview(enabled ? sidebar : null);
  57. await new Promise<void>((resolve) =>
  58. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  59. );
  60. };
  61. let off: (() => void) | undefined;
  62. const deadlines = new Set<() => void>();
  63. let disposal = Promise.resolve();
  64. const page = {
  65. key: "fixture",
  66. task: "fixture",
  67. visible: true,
  68. busy: () => controller?.isBusy() ?? false,
  69. running: () => Boolean(controller && controller.phase !== "disposed"),
  70. async suspend() {
  71. if (!(await controller.tryRecycle())) return false;
  72. disposal = controller.dispose();
  73. await disposal;
  74. plane.unmount(handle.sandboxId);
  75. manager.released(page);
  76. return true;
  77. },
  78. destroy() {
  79. void controller.dispose();
  80. plane.dispose();
  81. clearPluginUiWidgetState("fixture");
  82. },
  83. };
  84. const manager = new PluginUiPageManager<typeof page>(
  85. (run, ms) => {
  86. if (ms !== 300_000) throw new Error("unexpected retention deadline");
  87. deadlines.add(run);
  88. return () => {
  89. deadlines.delete(run);
  90. };
  91. },
  92. () => {},
  93. );
  94. async function start() {
  95. await manager.reserve(page);
  96. const config = await harness.config();
  97. controller = createPluginUiHostController({
  98. bridge: config
  99. ? (new Proxy(
  100. {},
  101. { get: (_, method) => (params: unknown) => harness.bridge(method, params) },
  102. ) as any)
  103. : ({
  104. prepareSandbox: () => harness.handle(),
  105. validateInstance: async () => {},
  106. closeInstance: async () => {},
  107. recycleInstance: async () => true,
  108. } as any),
  109. platform: {
  110. getOwnerWebContentsId: () => harness.owner(),
  111. disposeSandbox: (id, init) => harness.dispose(id, init),
  112. consumeUserGesture: async () => false,
  113. onPorts(handler) {
  114. portHandler = handler;
  115. return () => {
  116. if (portHandler === handler) portHandler = undefined;
  117. };
  118. },
  119. },
  120. scope: config?.scope ?? {
  121. workspacePath: "/fixture",
  122. sessionId: "fixture",
  123. scope: { kind: "surface", surfaceId: "fixture" },
  124. },
  125. presentation: config?.presentation ?? {
  126. pluginId: "fixture",
  127. serverName: "fixture",
  128. resourceUri: "ui://fixture",
  129. },
  130. createTransport: createPluginUiMessagePortTransport,
  131. initialHostContext: { displayMode: "inline" },
  132. hostVersion: "fixture",
  133. getToolFeed: () => ({}),
  134. getWidgetState: () => getPluginUiWidgetState("fixture"),
  135. getHostCapabilities: () => ({
  136. serverTools: {},
  137. serverResources: {},
  138. experimental: { "zcode/widgetState": {} },
  139. }),
  140. onUpdateWidgetState: async (value) => {
  141. setPluginUiWidgetState("fixture", value);
  142. },
  143. onPhase(phase, detail) {
  144. if (phase === "mounted") {
  145. handle = detail!.handle!;
  146. plane.mount(handle);
  147. }
  148. if (phase === "running") {
  149. handshakes++;
  150. ready.resolve();
  151. }
  152. if (phase === "error") ready.reject(new Error(detail?.error));
  153. },
  154. onHeight() {},
  155. onOpenExternal() {},
  156. onDisplayModeRequest: (mode) => mode,
  157. });
  158. controller.start();
  159. await ready.promise;
  160. }
  161. off = plane.bind({ node: inline, kind: "inline" });
  162. void manager.add(page).then(start);
  163. (window as any).switchPage = async (side: boolean) => {
  164. const started = performance.now();
  165. const previous = off;
  166. off = plane.bind({ node: side ? sidebar : inline, kind: side ? "sidebar" : "inline" });
  167. previous?.();
  168. controller.updateHostContext({ displayMode: side ? "fullscreen" : "inline" });
  169. const dispatchMs = performance.now() - started;
  170. await new Promise<void>((resolve) =>
  171. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  172. );
  173. return {
  174. handshakes,
  175. views: document.querySelectorAll("webview").length,
  176. listeners: [...tracked.values()].reduce((sum, items) => sum + items.size, 0),
  177. dispatchMs,
  178. };
  179. };
  180. (window as any).recyclePage = async () => {
  181. off?.();
  182. off = undefined;
  183. manager.visibility(page, false);
  184. // 可控期限触发生产 manager 的五分钟回收规则,不依赖实际等待五分钟。
  185. const completed = Promise.withResolvers<void>();
  186. const suspend = page.suspend;
  187. page.suspend = async () => {
  188. const result = await suspend();
  189. completed.resolve();
  190. return result;
  191. };
  192. for (const deadline of deadlines) deadline();
  193. deadlines.clear();
  194. await completed.promise;
  195. page.suspend = suspend;
  196. return {
  197. views: document.querySelectorAll("webview").length,
  198. state: getPluginUiWidgetState("fixture"),
  199. };
  200. };
  201. (window as any).restorePage = async (retry: boolean) => {
  202. if (retry) {
  203. clearPluginUiWidgetState("fixture");
  204. await page.suspend();
  205. }
  206. ready = Promise.withResolvers<void>();
  207. off = plane.bind({ node: inline, kind: "inline" });
  208. manager.visibility(page, true);
  209. await start();
  210. return { handshakes };
  211. };
  212. (window as any).disposePage = async () => {
  213. await controller.dispose();
  214. plane.unmount(handle.sandboxId);
  215. manager.released(page);
  216. };
  217. (window as any).currentHandle = () => handle;
  218. (window as any).pageBusy = () => controller.isBusy();
  219. (window as any).savedWidget = () => getPluginUiWidgetState("fixture");
  220. (window as any).deliverFeed = (n: number) => {
  221. controller.notifyToolInput({ arguments: { sequence: n } });
  222. controller.notifyToolResult({ content: [], structuredContent: { sequence: n } });
  223. };