managed-renderer.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. import { attachPluginUiToolResults } from "../../../ui/src/plugin-ui/adapters/pluginUiBackground.js";
  2. import { buildPluginUiSurfaceKey } from "../../../ui/src/plugin-ui/contract.js";
  3. import { subscribePage } from "../../../ui/src/plugin-ui/adapters/pluginUiPageRegistry.js";
  4. import { registerPluginUiSessionActions } from "../../../ui/src/plugin-ui/adapters/pluginUiSessionActions.js";
  5. import { useEffect, useState } from "react";
  6. import { createRoot } from "react-dom/client";
  7. import { flushSync } from "react-dom";
  8. import { ServiceProvider } from "../../../ui/src/hooks/useServices.js";
  9. import { PlatformProvider } from "../../../ui/src/hooks/usePlatform.js";
  10. import { usePluginUiHost } from "../../../ui/src/plugin-ui/adapters/usePluginUiHost.js";
  11. import { PluginUiCard } from "../../../ui/src/plugin-ui/components/PluginUiCard.js";
  12. import { PluginUiSidePaneView } from "../../../ui/src/plugin-ui/components/PluginUiSidePane.js";
  13. import { pluginUiPages } from "../../../ui/src/plugin-ui/adapters/pluginUiPageRegistry.js";
  14. import { getPluginUiWidgetState } from "../../../ui/src/plugin-ui/app/pluginUiWidgetStateStore.js";
  15. import { RowsFixture } from "./rows-renderer.js";
  16. import type {
  17. UsePluginUiHostInput,
  18. UsePluginUiHostResult,
  19. } from "../../../ui/src/plugin-ui/adapters/pluginUiHostTypes.js";
  20. const harness = (window as any).harness;
  21. const ready = Promise.withResolvers<void>();
  22. (window as any).harnessReady = ready.promise;
  23. const paused = Promise.withResolvers<void>();
  24. (window as any).fixturePaused = paused.promise;
  25. const drained = new Set<() => void>();
  26. const channels = new Map<string, Set<(value: any) => void>>();
  27. const emit = (name: string, value: unknown) => {
  28. for (const handler of channels.get(name) ?? []) handler(value);
  29. };
  30. const subscribe = (name: string, handler: (value: any) => void) => {
  31. const set = channels.get(name) ?? new Set();
  32. channels.set(name, set);
  33. set.add(handler);
  34. return {
  35. dispose: () => {
  36. set.delete(handler);
  37. for (const notify of drained) notify();
  38. },
  39. };
  40. };
  41. window.addEventListener("message", (event) => {
  42. if (event.data?.type === "fixture-notification")
  43. emit(event.data.payload.kind, event.data.payload.value);
  44. if (event.data?.type === "zcode:plugin-sandbox-ports")
  45. emit("ports", { ...event.data, port: event.ports[0] });
  46. });
  47. const proxy = (send: (method: string, p: unknown) => Promise<unknown>) =>
  48. new Proxy({}, { get: (_, method) => (p: unknown) => send(String(method), p) });
  49. const agent = {
  50. ...Object.fromEntries(
  51. [
  52. "helloConversationV4",
  53. "initializeConversationV4",
  54. "subscribeConversationV4",
  55. "unsubscribeConversationV4",
  56. "resyncConversationV4",
  57. ].map((method) => [method, (p: unknown) => harness.v4(method, p)]),
  58. ),
  59. onDynamicPluginUiToolResult: () => (handler: any) => subscribe("ui-result", handler),
  60. onDynamicConversationFrame: () => (handler: any) => subscribe("frame", handler),
  61. onDynamicLocalTtftFacts: () => (handler: any) => subscribe("ttft", handler),
  62. onAgentRuntimeRestarted: (handler: any) => subscribe("restart", handler),
  63. onAgentRuntimeLifecycle: (handler: any) => subscribe("lifecycle", handler),
  64. };
  65. const services = {
  66. zcodeAgentService: agent,
  67. zcodeTaskService: { onDynamicWorkspaceEvent: () => (handler: any) => subscribe("task", handler) },
  68. pluginUiBridgeService: proxy(harness.bridge),
  69. pluginUiSamplingService: proxy(harness.bridge),
  70. pluginUiAppToolsService: proxy(harness.appTools),
  71. };
  72. const platform = {
  73. pluginSandbox: {
  74. setExecutionActive: window.zcodePluginSandbox?.setExecutionActive,
  75. getOwnerWebContentsId: () => harness.owner(),
  76. disposeSandbox: (id: string, init: number) => harness.dispose(id, init),
  77. consumeUserGesture: async () => false,
  78. onPorts(handler: any) {
  79. const listener = subscribe("ports", handler);
  80. return () => listener.dispose();
  81. },
  82. },
  83. };
  84. let current: UsePluginUiHostResult;
  85. let renderState: (next: {
  86. inline: boolean;
  87. sidebar: boolean;
  88. sequence?: number;
  89. remote?: boolean;
  90. }) => void;
  91. let config: any;
  92. const phases: string[] = [];
  93. const deadlines = new Set<() => void>();
  94. const realSetTimeout = window.setTimeout.bind(window),
  95. realClearTimeout = window.clearTimeout.bind(window);
  96. const fakeIds = new Map<number, () => void>();
  97. let nextTimer = -1;
  98. // 只控制产品的五分钟保活期限;握手、teardown、v4 keep-warm 仍用真实完成事件/时钟。
  99. window.setTimeout = ((run: () => void, ms: number, ...args: any[]) => {
  100. if (ms !== 300_000) return realSetTimeout(run, ms, ...args);
  101. const id = nextTimer--;
  102. deadlines.add(run);
  103. fakeIds.set(id, run);
  104. return id;
  105. }) as typeof window.setTimeout;
  106. window.clearTimeout = ((id: number) => {
  107. const run = fakeIds.get(id);
  108. if (run) {
  109. deadlines.delete(run);
  110. fakeIds.delete(id);
  111. } else realClearTimeout(id);
  112. }) as typeof window.clearTimeout;
  113. function Anchor({
  114. side,
  115. enabled,
  116. sequence,
  117. remote,
  118. visible = true,
  119. }: {
  120. side: boolean;
  121. enabled: boolean;
  122. sequence?: number;
  123. remote?: boolean;
  124. visible?: boolean;
  125. }) {
  126. const input: UsePluginUiHostInput = {
  127. ...config,
  128. scope: { ...config.scope, ...(remote ? { remoteSessionId: "fixture-remote" } : {}) },
  129. theme: config.theme ?? "light",
  130. locale: config.locale ?? "en",
  131. displayMode: side ? "fullscreen" : "inline",
  132. width: config.width ?? 400,
  133. hostVersion: "managed-fixture",
  134. toolInput: sequence === undefined ? undefined : { sequence },
  135. toolResult:
  136. sequence === undefined ? undefined : { content: [], structuredContent: { sequence } },
  137. toolCallId: `feed-${sequence}`,
  138. enabled,
  139. };
  140. const host = usePluginUiHost(input);
  141. if (enabled) current = host;
  142. useEffect(() => {
  143. if (!enabled) return;
  144. phases.push(host.phase);
  145. void harness.event({ type: "phase", phase: host.phase, key: host.pageKey });
  146. if (host.phase === "running" || !host.supported) ready.resolve();
  147. if (host.phase === "error") ready.reject(new Error(host.error ?? "managed page failed"));
  148. }, [host.phase, host.pageKey, enabled]);
  149. if (config.mode.startsWith("background-cold")) return null;
  150. return side ? (
  151. <PluginUiSidePaneView
  152. visible={visible}
  153. scopeRef={config.scope.scope}
  154. host={host}
  155. loadingLabel="loading"
  156. errorLabel="failed"
  157. retryLabel="retry"
  158. />
  159. ) : (
  160. <PluginUiCard
  161. {...host}
  162. prefersBorder={false}
  163. loadingLabel="loading"
  164. errorLabel="failed"
  165. retryLabel="retry"
  166. onRetry={host.reload}
  167. />
  168. );
  169. }
  170. function Fixture() {
  171. const [state, setState] = useState({
  172. inline: config.mode !== "background-hidden" && !config.mode.startsWith("background-admission"),
  173. sidebar: config.mode === "background-hidden",
  174. sidebarVisible: true,
  175. sidebarActive: true,
  176. chatVisible: true,
  177. workspaceVisible: true,
  178. sequence: undefined as number | undefined,
  179. remote: config.mode === "remote",
  180. });
  181. renderState = (next) => setState((previous) => ({ ...previous, ...next }));
  182. return (
  183. <ServiceProvider services={services as never}>
  184. <PlatformProvider platform={platform as never}>
  185. <div
  186. id="inline-scroll"
  187. style={{
  188. position: "absolute",
  189. left: 20,
  190. top: 20,
  191. width: config.width ?? 400,
  192. height: 350,
  193. overflow: "auto",
  194. }}
  195. >
  196. <div data-sandbox-page-container="true" style={{ position: "relative" }}>
  197. <div id="inline-anchor">
  198. {state.inline && (
  199. <Anchor
  200. side={false}
  201. enabled={!state.sidebar}
  202. sequence={state.sequence}
  203. remote={state.remote}
  204. />
  205. )}
  206. </div>
  207. <div style={{ height: 1400 }} />
  208. </div>
  209. </div>
  210. <div
  211. id="sidebar-anchor"
  212. aria-hidden={!state.sidebarVisible || !state.chatVisible || !state.workspaceVisible}
  213. style={{
  214. position: "absolute",
  215. left: 500,
  216. top: 20,
  217. width: state.sidebarVisible ? 450 : 0,
  218. height: 600,
  219. display: config.mode === "background-hidden" ? "none" : undefined,
  220. overflow: "hidden",
  221. opacity: state.sidebarVisible && state.chatVisible && state.workspaceVisible ? 1 : 0,
  222. pointerEvents:
  223. state.sidebarVisible && state.chatVisible && state.workspaceVisible
  224. ? undefined
  225. : "none",
  226. }}
  227. >
  228. {/* 复现应用收起时锁宽、切标签时 forceMount 的真实布局;锚点一直连接。 */}
  229. <div style={{ width: 450, height: 600, display: state.sidebarActive ? "block" : "none" }}>
  230. {state.sidebar && (
  231. <Anchor
  232. side
  233. enabled
  234. visible={
  235. state.sidebarVisible &&
  236. state.sidebarActive &&
  237. state.chatVisible &&
  238. state.workspaceVisible
  239. }
  240. sequence={state.sequence}
  241. remote={state.remote}
  242. />
  243. )}
  244. </div>
  245. </div>
  246. <div style={{ position: "absolute", left: 500, top: 650 }}>
  247. <button
  248. id="toggle-sidebar"
  249. onClick={() =>
  250. setState((previous) => ({ ...previous, sidebarVisible: !previous.sidebarVisible }))
  251. }
  252. >
  253. Toggle sidebar
  254. </button>
  255. <button
  256. id="switch-sidebar-tab"
  257. onClick={() =>
  258. setState((previous) => ({ ...previous, sidebarActive: !previous.sidebarActive }))
  259. }
  260. >
  261. Switch tab
  262. </button>
  263. <button
  264. id="switch-main-page"
  265. onClick={() =>
  266. setState((previous) => ({ ...previous, chatVisible: !previous.chatVisible }))
  267. }
  268. >
  269. Switch page
  270. </button>
  271. <button
  272. id="switch-workspace"
  273. onClick={() =>
  274. setState((previous) => ({
  275. ...previous,
  276. workspaceVisible: !previous.workspaceVisible,
  277. }))
  278. }
  279. >
  280. Switch workspace
  281. </button>
  282. </div>
  283. </PlatformProvider>
  284. </ServiceProvider>
  285. );
  286. }
  287. const layout = () =>
  288. new Promise<void>((resolve) =>
  289. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  290. );
  291. (window as any).setAnchors = async (inline: boolean, sidebar: boolean, sequence?: number) => {
  292. flushSync(() => renderState({ inline, sidebar, sequence }));
  293. await layout();
  294. };
  295. (window as any).revealBackgroundPage = async () => {
  296. config.mode = "background";
  297. flushSync(() => renderState({ inline: false, sidebar: true }));
  298. await layout();
  299. };
  300. (window as any).setShowcasePresentation = async (
  301. theme: "light" | "dark",
  302. locale: string,
  303. width: number,
  304. ) => {
  305. Object.assign(config, { theme, locale, width });
  306. // fixture 没有应用主题样式表,提供宿主 token 以验证 reader → hostContext → 页面颜色。
  307. for (const [token, values] of Object.entries({
  308. "--color-background": ["#ffffff", "#17191c"],
  309. "--color-panel": ["#f4f5f6", "#23272c"],
  310. "--color-foreground": ["#202124", "#e6edf3"],
  311. "--color-foreground-subtle": ["#5f6368", "#adb5bd"],
  312. "--color-border": ["#dadce0", "#454b52"],
  313. }))
  314. document.documentElement.style.setProperty(token, values[theme === "dark" ? 1 : 0]!);
  315. flushSync(() => renderState({ inline: true, sidebar: false }));
  316. await layout();
  317. };
  318. (window as any).managedState = () => ({
  319. actual: {
  320. phase: pluginUiPages.get(current.pageKey)?.snapshot().phase,
  321. error: pluginUiPages.get(current.pageKey)?.snapshot().error,
  322. },
  323. phase: current.phase,
  324. supported: current.supported,
  325. handle: current.handle,
  326. key: current.pageKey,
  327. visible: pluginUiPages.get(current.pageKey)?.visible,
  328. busy: pluginUiPages.get(current.pageKey)?.busy(),
  329. widget: getPluginUiWidgetState(current.pageKey),
  330. views: document.querySelectorAll("webview").length,
  331. listeners: Object.fromEntries([...channels].map(([key, listeners]) => [key, listeners.size])),
  332. phases,
  333. });
  334. (window as any).expireOffscreen = () => {
  335. const pending = [...deadlines];
  336. deadlines.clear();
  337. for (const run of pending) run();
  338. };
  339. (window as any).removeTask = () => {
  340. // 删除任务同时撤掉呈现入口;不能让测试中仍挂载的 hook 再次请求已删除任务。
  341. flushSync(() => renderState({ inline: false, sidebar: false }));
  342. emit("task", {
  343. type: "workspace_task_list_changed",
  344. reason: "task_deleted",
  345. taskId: config.scope.sessionId,
  346. });
  347. };
  348. (window as any).runtimeUnavailable = () =>
  349. emit("lifecycle", {
  350. workspaceKey: config.scope.workspaceIdentity ?? config.scope.workspacePath,
  351. state: "unavailable",
  352. });
  353. (window as any).retryManaged = () => current.reload();
  354. (window as any).waitManagedPhase = (phase: string) => {
  355. const page = pluginUiPages.get(current.pageKey);
  356. if (!page || page.snapshot().phase === phase) return Promise.resolve();
  357. return new Promise<void>((resolve) => {
  358. const off = page.subscribe(() => {
  359. if (page.snapshot().phase === phase) {
  360. off();
  361. resolve();
  362. }
  363. });
  364. });
  365. };
  366. (window as any).suspendManaged = () => pluginUiPages.get(current.pageKey)?.suspend();
  367. (window as any).waitConnectionsReleased = () =>
  368. new Promise<void>((resolve) => {
  369. const check = () => {
  370. if ([...channels.values()].every((set) => set.size === 0)) {
  371. drained.delete(check);
  372. resolve();
  373. }
  374. };
  375. drained.add(check);
  376. check();
  377. });
  378. (window as any).clearManaged = () => pluginUiPages.clear();
  379. (window as any).setFallback = async (remote: boolean, noSandbox: boolean) => {
  380. const previous = platform.pluginSandbox;
  381. if (noSandbox) platform.pluginSandbox = undefined as never;
  382. flushSync(() => renderState({ inline: true, sidebar: false, remote }));
  383. await layout();
  384. platform.pluginSandbox = previous;
  385. return { supported: current.supported, views: document.querySelectorAll("webview").length };
  386. };
  387. void harness
  388. .config()
  389. .then(async (value: any) => {
  390. config = value;
  391. if (config.mode === "sampling") {
  392. let unregister: (() => void) | undefined;
  393. (window as any).setSamplingEnabled = (enabled: boolean) => {
  394. unregister?.();
  395. unregister = undefined;
  396. if (enabled)
  397. unregister = registerPluginUiSessionActions(config.scope, {
  398. sendFollowUp: async () => {
  399. throw new Error("Sampling must not send a conversation turn");
  400. },
  401. });
  402. };
  403. (window as any).setSamplingEnabled(true);
  404. const idleWaiters = new Set<() => void>();
  405. const settled = pluginUiPages.settled.bind(pluginUiPages);
  406. pluginUiPages.settled = (page) => {
  407. settled(page);
  408. for (const notify of idleWaiters) notify();
  409. };
  410. (window as any).waitSamplingIdle = () =>
  411. new Promise<void>((resolve) => {
  412. const notify = () => {
  413. if (!pluginUiPages.get(current.pageKey)?.busy()) {
  414. idleWaiters.delete(notify);
  415. resolve();
  416. }
  417. };
  418. idleWaiters.add(notify);
  419. notify();
  420. });
  421. }
  422. if (config.mode.startsWith("background-admission")) {
  423. // 故意不挂 Anchor/usePluginUiHost,也没有 conversation lease;只保留生产窗口接收器。
  424. const key = buildPluginUiSurfaceKey(
  425. { ...config.scope, ...config.presentation },
  426. config.scope.scope,
  427. );
  428. subscribePage(key, () => {
  429. const page = pluginUiPages.get(key);
  430. if (page) current = page.snapshot();
  431. });
  432. const off = attachPluginUiToolResults(services as never, platform as never, () => ({
  433. theme: "light",
  434. locale: "en",
  435. }));
  436. (window as any).stopBackgroundReceiver = off;
  437. ready.resolve();
  438. }
  439. if (config.mode === "web") platform.pluginSandbox = undefined as never;
  440. if (config.mode.endsWith("-minimized")) {
  441. const start = Promise.withResolvers<void>();
  442. (window as any).startFixture = start.resolve;
  443. paused.resolve();
  444. await start.promise;
  445. }
  446. createRoot(document.getElementById("root")!).render(
  447. config.mode === "rows" ? (
  448. <ServiceProvider services={services as never}>
  449. <PlatformProvider platform={platform as never}>
  450. <RowsFixture config={config} ready={ready.resolve} />
  451. </PlatformProvider>
  452. </ServiceProvider>
  453. ) : (
  454. <Fixture />
  455. ),
  456. );
  457. })
  458. .catch(ready.reject);