managed-renderer.tsx 18 KB

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