managed-renderer.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import { registerPluginUiSessionActions } from "../../../ui/src/plugin-ui/adapters/pluginUiSessionActions.js";
  2. import { useEffect, useState } from "react";
  3. import { createRoot } from "react-dom/client";
  4. import { flushSync } from "react-dom";
  5. import { ServiceProvider } from "../../../ui/src/hooks/useServices.js";
  6. import { PlatformProvider } from "../../../ui/src/hooks/usePlatform.js";
  7. import { usePluginUiHost } from "../../../ui/src/plugin-ui/adapters/usePluginUiHost.js";
  8. import { PluginUiCard } from "../../../ui/src/plugin-ui/components/PluginUiCard.js";
  9. import { PluginUiSidePaneView } from "../../../ui/src/plugin-ui/components/PluginUiSidePane.js";
  10. import { pluginUiPages } from "../../../ui/src/plugin-ui/adapters/pluginUiPageRegistry.js";
  11. import { getPluginUiWidgetState } from "../../../ui/src/plugin-ui/app/pluginUiWidgetStateStore.js";
  12. import { RowsFixture } from "./rows-renderer.js";
  13. import type {
  14. UsePluginUiHostInput,
  15. UsePluginUiHostResult,
  16. } from "../../../ui/src/plugin-ui/adapters/pluginUiHostTypes.js";
  17. const harness = (window as any).harness;
  18. const ready = Promise.withResolvers<void>();
  19. (window as any).harnessReady = ready.promise;
  20. const drained = new Set<() => void>();
  21. const channels = new Map<string, Set<(value: any) => void>>();
  22. const emit = (name: string, value: unknown) => {
  23. for (const handler of channels.get(name) ?? []) handler(value);
  24. };
  25. const subscribe = (name: string, handler: (value: any) => void) => {
  26. const set = channels.get(name) ?? new Set();
  27. channels.set(name, set);
  28. set.add(handler);
  29. return {
  30. dispose: () => {
  31. set.delete(handler);
  32. for (const notify of drained) notify();
  33. },
  34. };
  35. };
  36. window.addEventListener("message", (event) => {
  37. if (event.data?.type === "fixture-notification")
  38. emit(event.data.payload.kind, event.data.payload.value);
  39. if (event.data?.type === "zcode:plugin-sandbox-ports")
  40. emit("ports", { ...event.data, port: event.ports[0] });
  41. });
  42. const proxy = (send: (method: string, p: unknown) => Promise<unknown>) =>
  43. new Proxy({}, { get: (_, method) => (p: unknown) => send(String(method), p) });
  44. const agent = {
  45. ...Object.fromEntries(
  46. [
  47. "helloConversationV4",
  48. "initializeConversationV4",
  49. "subscribeConversationV4",
  50. "unsubscribeConversationV4",
  51. "resyncConversationV4",
  52. ].map((method) => [method, (p: unknown) => harness.v4(method, p)]),
  53. ),
  54. onDynamicConversationFrame: () => (handler: any) => subscribe("frame", handler),
  55. onDynamicLocalTtftFacts: () => (handler: any) => subscribe("ttft", handler),
  56. onAgentRuntimeRestarted: (handler: any) => subscribe("restart", handler),
  57. onAgentRuntimeLifecycle: (handler: any) => subscribe("lifecycle", handler),
  58. };
  59. const services = {
  60. zcodeAgentService: agent,
  61. zcodeTaskService: { onDynamicWorkspaceEvent: () => (handler: any) => subscribe("task", handler) },
  62. pluginUiBridgeService: proxy(harness.bridge),
  63. pluginUiSamplingService: proxy(harness.bridge),
  64. pluginUiAppToolsService: proxy(harness.appTools),
  65. };
  66. const platform = {
  67. pluginSandbox: {
  68. getOwnerWebContentsId: () => harness.owner(),
  69. disposeSandbox: (id: string, init: number) => harness.dispose(id, init),
  70. consumeUserGesture: async () => false,
  71. onPorts(handler: any) {
  72. const listener = subscribe("ports", handler);
  73. return () => listener.dispose();
  74. },
  75. },
  76. };
  77. let current: UsePluginUiHostResult;
  78. let renderState: (next: {
  79. inline: boolean;
  80. sidebar: boolean;
  81. sequence?: number;
  82. remote?: boolean;
  83. }) => void;
  84. let config: any;
  85. const phases: string[] = [];
  86. const deadlines = new Set<() => void>();
  87. const realSetTimeout = window.setTimeout.bind(window),
  88. realClearTimeout = window.clearTimeout.bind(window);
  89. const fakeIds = new Map<number, () => void>();
  90. let nextTimer = -1;
  91. // 只控制产品的五分钟保活期限;握手、teardown、v4 keep-warm 仍用真实完成事件/时钟。
  92. window.setTimeout = ((run: () => void, ms: number, ...args: any[]) => {
  93. if (ms !== 300_000) return realSetTimeout(run, ms, ...args);
  94. const id = nextTimer--;
  95. deadlines.add(run);
  96. fakeIds.set(id, run);
  97. return id;
  98. }) as typeof window.setTimeout;
  99. window.clearTimeout = ((id: number) => {
  100. const run = fakeIds.get(id);
  101. if (run) {
  102. deadlines.delete(run);
  103. fakeIds.delete(id);
  104. } else realClearTimeout(id);
  105. }) as typeof window.clearTimeout;
  106. function Anchor({
  107. side,
  108. enabled,
  109. sequence,
  110. remote,
  111. }: {
  112. side: boolean;
  113. enabled: boolean;
  114. sequence?: number;
  115. remote?: boolean;
  116. }) {
  117. const input: UsePluginUiHostInput = {
  118. ...config,
  119. scope: { ...config.scope, ...(remote ? { remoteSessionId: "fixture-remote" } : {}) },
  120. theme: config.theme ?? "light",
  121. locale: config.locale ?? "en",
  122. displayMode: side ? "fullscreen" : "inline",
  123. width: config.width ?? 400,
  124. hostVersion: "managed-fixture",
  125. toolInput: sequence === undefined ? undefined : { sequence },
  126. toolResult:
  127. sequence === undefined ? undefined : { content: [], structuredContent: { sequence } },
  128. toolCallId: `feed-${sequence}`,
  129. enabled,
  130. };
  131. const host = usePluginUiHost(input);
  132. if (enabled) current = host;
  133. useEffect(() => {
  134. if (!enabled) return;
  135. phases.push(host.phase);
  136. void harness.event({ type: "phase", phase: host.phase, key: host.pageKey });
  137. if (host.phase === "running" || !host.supported) ready.resolve();
  138. if (host.phase === "error") ready.reject(new Error(host.error ?? "managed page failed"));
  139. }, [host.phase, host.pageKey, enabled]);
  140. return side ? (
  141. <PluginUiSidePaneView
  142. scopeRef={config.scope.scope}
  143. host={host}
  144. loadingLabel="loading"
  145. errorLabel="failed"
  146. retryLabel="retry"
  147. />
  148. ) : (
  149. <PluginUiCard
  150. {...host}
  151. prefersBorder={false}
  152. loadingLabel="loading"
  153. errorLabel="failed"
  154. retryLabel="retry"
  155. onRetry={host.reload}
  156. />
  157. );
  158. }
  159. function Fixture() {
  160. const [state, setState] = useState({
  161. inline: true,
  162. sidebar: false,
  163. sequence: undefined as number | undefined,
  164. remote: config.mode === "remote",
  165. });
  166. renderState = (next) => setState((previous) => ({ ...previous, ...next }));
  167. return (
  168. <ServiceProvider services={services as never}>
  169. <PlatformProvider platform={platform as never}>
  170. <div
  171. id="inline-scroll"
  172. style={{
  173. position: "absolute",
  174. left: 20,
  175. top: 20,
  176. width: config.width ?? 400,
  177. height: 350,
  178. overflow: "auto",
  179. }}
  180. >
  181. <div data-sandbox-page-container="true" style={{ position: "relative" }}>
  182. <div id="inline-anchor">
  183. {state.inline && (
  184. <Anchor
  185. side={false}
  186. enabled={!state.sidebar}
  187. sequence={state.sequence}
  188. remote={state.remote}
  189. />
  190. )}
  191. </div>
  192. <div style={{ height: 1400 }} />
  193. </div>
  194. </div>
  195. <div
  196. id="sidebar-anchor"
  197. style={{ position: "absolute", left: 500, top: 20, width: 450, height: 600 }}
  198. >
  199. {state.sidebar && <Anchor side enabled sequence={state.sequence} remote={state.remote} />}
  200. </div>
  201. </PlatformProvider>
  202. </ServiceProvider>
  203. );
  204. }
  205. const layout = () =>
  206. new Promise<void>((resolve) =>
  207. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  208. );
  209. (window as any).setAnchors = async (inline: boolean, sidebar: boolean, sequence?: number) => {
  210. flushSync(() => renderState({ inline, sidebar, sequence }));
  211. await layout();
  212. };
  213. (window as any).setShowcasePresentation = async (
  214. theme: "light" | "dark",
  215. locale: string,
  216. width: number,
  217. ) => {
  218. Object.assign(config, { theme, locale, width });
  219. // fixture 没有应用主题样式表,提供宿主 token 以验证 reader → hostContext → 页面颜色。
  220. for (const [token, values] of Object.entries({
  221. "--color-background": ["#ffffff", "#17191c"],
  222. "--color-panel": ["#f4f5f6", "#23272c"],
  223. "--color-foreground": ["#202124", "#e6edf3"],
  224. "--color-foreground-subtle": ["#5f6368", "#adb5bd"],
  225. "--color-border": ["#dadce0", "#454b52"],
  226. }))
  227. document.documentElement.style.setProperty(token, values[theme === "dark" ? 1 : 0]!);
  228. flushSync(() => renderState({ inline: true, sidebar: false }));
  229. await layout();
  230. };
  231. (window as any).managedState = () => ({
  232. actual: {
  233. phase: pluginUiPages.get(current.pageKey)?.snapshot().phase,
  234. error: pluginUiPages.get(current.pageKey)?.snapshot().error,
  235. },
  236. phase: current.phase,
  237. supported: current.supported,
  238. handle: current.handle,
  239. key: current.pageKey,
  240. visible: pluginUiPages.get(current.pageKey)?.visible,
  241. busy: pluginUiPages.get(current.pageKey)?.busy(),
  242. widget: getPluginUiWidgetState(current.pageKey),
  243. views: document.querySelectorAll("webview").length,
  244. listeners: Object.fromEntries([...channels].map(([key, listeners]) => [key, listeners.size])),
  245. phases,
  246. });
  247. (window as any).expireOffscreen = () => {
  248. const pending = [...deadlines];
  249. deadlines.clear();
  250. for (const run of pending) run();
  251. };
  252. (window as any).removeTask = () =>
  253. emit("task", {
  254. type: "workspace_task_list_changed",
  255. reason: "task_deleted",
  256. taskId: config.scope.sessionId,
  257. });
  258. (window as any).runtimeUnavailable = () =>
  259. emit("lifecycle", {
  260. workspaceKey: config.scope.workspaceIdentity ?? config.scope.workspacePath,
  261. state: "unavailable",
  262. });
  263. (window as any).retryManaged = () => current.reload();
  264. (window as any).waitManagedPhase = (phase: string) => {
  265. const page = pluginUiPages.get(current.pageKey);
  266. if (!page || page.snapshot().phase === phase) return Promise.resolve();
  267. return new Promise<void>((resolve) => {
  268. const off = page.subscribe(() => {
  269. if (page.snapshot().phase === phase) {
  270. off();
  271. resolve();
  272. }
  273. });
  274. });
  275. };
  276. (window as any).suspendManaged = () => pluginUiPages.get(current.pageKey)?.suspend();
  277. (window as any).waitConnectionsReleased = () =>
  278. new Promise<void>((resolve) => {
  279. const check = () => {
  280. if ([...channels.values()].every((set) => set.size === 0)) {
  281. drained.delete(check);
  282. resolve();
  283. }
  284. };
  285. drained.add(check);
  286. check();
  287. });
  288. (window as any).clearManaged = () => pluginUiPages.clear();
  289. (window as any).setFallback = async (remote: boolean, noSandbox: boolean) => {
  290. const previous = platform.pluginSandbox;
  291. if (noSandbox) platform.pluginSandbox = undefined as never;
  292. flushSync(() => renderState({ inline: true, sidebar: false, remote }));
  293. await layout();
  294. platform.pluginSandbox = previous;
  295. return { supported: current.supported, views: document.querySelectorAll("webview").length };
  296. };
  297. void harness
  298. .config()
  299. .then((value: any) => {
  300. config = value;
  301. if (config.mode === "sampling") {
  302. let unregister: (() => void) | undefined;
  303. (window as any).setSamplingEnabled = (enabled: boolean) => {
  304. unregister?.();
  305. unregister = undefined;
  306. if (enabled)
  307. unregister = registerPluginUiSessionActions(config.scope, {
  308. sendFollowUp: async () => {
  309. throw new Error("Sampling must not send a conversation turn");
  310. },
  311. });
  312. };
  313. (window as any).setSamplingEnabled(true);
  314. const idleWaiters = new Set<() => void>();
  315. const settled = pluginUiPages.settled.bind(pluginUiPages);
  316. pluginUiPages.settled = (page) => {
  317. settled(page);
  318. for (const notify of idleWaiters) notify();
  319. };
  320. (window as any).waitSamplingIdle = () =>
  321. new Promise<void>((resolve) => {
  322. const notify = () => {
  323. if (!pluginUiPages.get(current.pageKey)?.busy()) {
  324. idleWaiters.delete(notify);
  325. resolve();
  326. }
  327. };
  328. idleWaiters.add(notify);
  329. notify();
  330. });
  331. }
  332. if (config.mode === "web") platform.pluginSandbox = undefined as never;
  333. createRoot(document.getElementById("root")!).render(
  334. config.mode === "rows" ? (
  335. <ServiceProvider services={services as never}>
  336. <PlatformProvider platform={platform as never}>
  337. <RowsFixture config={config} ready={ready.resolve} />
  338. </PlatformProvider>
  339. </ServiceProvider>
  340. ) : (
  341. <Fixture />
  342. ),
  343. );
  344. })
  345. .catch(ready.reject);