managed-renderer.tsx 18 KB

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