retention-renderer.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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 { createPluginUiMessagePortTransport } from "../../../ui/src/plugin-ui/adapters/messagePortTransport.js";
  7. import { createPluginUiPagePlane } from "../../../ui/src/plugin-ui/adapters/pluginUiPagePlane.js";
  8. import type { PluginSandboxHandle, PluginSandboxPortsEvent } from "@zcode/shared/mcp-apps";
  9. const harness = (window as any).harness;
  10. const ports = new Set<(event: PluginSandboxPortsEvent) => void>();
  11. window.addEventListener("message", (event) => {
  12. if (event.data?.type === "zcode:plugin-sandbox-ports" && event.ports.length === 1)
  13. for (const receive of ports) receive({ ...event.data, port: event.ports[0] });
  14. });
  15. let now = 0;
  16. const timers = new Map<() => void, number>();
  17. const snapshots = new Map<string, unknown>();
  18. const pending = new Set<Promise<unknown>>();
  19. const released: string[] = [];
  20. const track = (promise: Promise<unknown>) => {
  21. pending.add(promise);
  22. void promise.then(
  23. () => pending.delete(promise),
  24. () => pending.delete(promise),
  25. );
  26. return promise;
  27. };
  28. const owner = new PluginUiPageManager<Page>(
  29. (run, ms) => {
  30. timers.set(run, now + ms);
  31. return () => {
  32. timers.delete(run);
  33. };
  34. },
  35. (task) => {
  36. for (const key of snapshots.keys()) if (key.startsWith(task + "/")) snapshots.delete(key);
  37. },
  38. );
  39. type Page = {
  40. key: string;
  41. task: string;
  42. visible: boolean;
  43. busy(): boolean;
  44. running(): boolean;
  45. suspend(): Promise<boolean>;
  46. destroy(): void;
  47. setBusy(value: boolean): void;
  48. handle?: PluginSandboxHandle;
  49. };
  50. const pages = new Map<string, Page>();
  51. async function addPage(key: string, task: string, visible = true) {
  52. let busy = false;
  53. let running = false;
  54. let controller: PluginUiHostController;
  55. let handle: PluginSandboxHandle | undefined;
  56. const anchor = document.createElement("div");
  57. anchor.style.cssText = `position:absolute;left:${(pages.size % 8) * 120}px;top:${Math.floor(pages.size / 8) * 95}px;width:115px;height:90px;`;
  58. document.body.append(anchor);
  59. const plane = createPluginUiPagePlane({
  60. onVisibility() {},
  61. onCrash() {
  62. throw Error("retention guest crashed");
  63. },
  64. });
  65. const off = plane.bind({ node: anchor, kind: "inline" });
  66. const page: Page = {
  67. key,
  68. task,
  69. visible,
  70. busy: () => busy,
  71. running: () => running,
  72. setBusy(value) {
  73. busy = value;
  74. owner.settled(page);
  75. },
  76. suspend() {
  77. const result = (async () => {
  78. if (!running) return true;
  79. if (busy) return false;
  80. running = false;
  81. await controller.dispose();
  82. plane.unmount(handle!.sandboxId);
  83. owner.released(page);
  84. released.push(key);
  85. return true;
  86. })();
  87. track(result);
  88. return result;
  89. },
  90. destroy() {
  91. busy = false;
  92. track(
  93. page.suspend().then(() => {
  94. plane.dispose();
  95. off();
  96. anchor.remove();
  97. pages.delete(key);
  98. }),
  99. );
  100. },
  101. };
  102. await owner.add(page);
  103. pages.set(key, page);
  104. try {
  105. await owner.reserve(page);
  106. } catch (error) {
  107. plane.dispose();
  108. off();
  109. anchor.remove();
  110. return { error: String(error) };
  111. }
  112. const ready = Promise.withResolvers<void>();
  113. controller = createPluginUiHostController({
  114. scope: {
  115. workspacePath: "/retention",
  116. sessionId: task,
  117. scope: { kind: "surface", surfaceId: key },
  118. },
  119. presentation: { pluginId: "fixture", serverName: "fixture", resourceUri: "ui://fixture" },
  120. bridge: {
  121. prepareSandbox: () => harness.bridge("register", { key, task }),
  122. validateInstance: async () => {},
  123. closeInstance: async () => {},
  124. recycleInstance: async () => !busy,
  125. } as any,
  126. platform: {
  127. getOwnerWebContentsId: () => harness.owner(),
  128. disposeSandbox: (id, init) => harness.dispose(id, init),
  129. consumeUserGesture: async () => false,
  130. onPorts(receive) {
  131. ports.add(receive);
  132. return () => {
  133. ports.delete(receive);
  134. };
  135. },
  136. },
  137. createTransport: createPluginUiMessagePortTransport,
  138. initialHostContext: { displayMode: "inline" },
  139. hostVersion: "fixture",
  140. getToolFeed: () => ({}),
  141. getWidgetState: () => snapshots.get(task + "/" + key),
  142. getHostCapabilities: () => ({}),
  143. onPhase(phase, detail) {
  144. if (phase === "mounted") {
  145. handle = detail!.handle!;
  146. page.handle = handle;
  147. plane.mount(handle);
  148. }
  149. if (phase === "running") {
  150. running = true;
  151. ready.resolve();
  152. }
  153. if (phase === "error") ready.reject(Error(detail?.error));
  154. },
  155. onHeight() {},
  156. onOpenExternal() {},
  157. onDisplayModeRequest: (mode) => mode,
  158. });
  159. controller.start();
  160. await ready.promise;
  161. snapshots.set(task + "/" + key, { saved: key });
  162. return { sandboxId: handle!.sandboxId };
  163. }
  164. async function drain() {
  165. while (pending.size) await Promise.all(pending);
  166. }
  167. (window as any).retention = {
  168. addPage,
  169. counts: () => ({
  170. pages: pages.size,
  171. views: document.querySelectorAll("webview").length,
  172. ports: ports.size,
  173. snapshots: snapshots.size,
  174. timers: timers.size,
  175. released: [...released],
  176. }),
  177. visibility: (key: string, value: boolean) => owner.visibility(pages.get(key)!, value),
  178. busy: (key: string, value: boolean) => pages.get(key)!.setBusy(value),
  179. async advance(ms: number) {
  180. now += ms;
  181. for (const [run, deadline] of timers)
  182. if (deadline <= now) {
  183. timers.delete(run);
  184. run();
  185. }
  186. await drain();
  187. },
  188. async clear() {
  189. owner.clear();
  190. await drain();
  191. },
  192. };
  193. (window as any).harnessReady = Promise.resolve();