rows-renderer.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import { useCallback, useEffect, useMemo, useState } from "react";
  2. import { flushSync } from "react-dom";
  3. import type { ToolCallRow } from "@zcode/shared/zcode-protocol-v4";
  4. import { ZCodeIntlProvider } from "../../../ui/src/i18n/IntlProvider.js";
  5. import { TabStoreProvider } from "../../../ui/src/store/TabStoreProvider.js";
  6. import { ConversationTimeline } from "../../../ui/src/v4/ConversationTimeline.js";
  7. import { DEFAULT_CODE_PREVIEW_SETTINGS } from "../../../ui/src/lib/codePreviewSettings.js";
  8. import {
  9. PluginUiSessionProvider,
  10. PluginUiWorkspaceProvider,
  11. PluginUiSidePane,
  12. buildPluginUiSidePaneTabId,
  13. } from "../../../ui/src/plugin-ui/index.js";
  14. import { setPluginUiManualPin } from "../../../ui/src/plugin-ui/app/pluginUiDisclosureStore.js";
  15. import {
  16. pluginUiPages,
  17. subscribePage,
  18. } from "../../../ui/src/plugin-ui/adapters/pluginUiPageRegistry.js";
  19. import { buildPluginUiSurfaceKey } from "../../../ui/src/plugin-ui/contract.js";
  20. export interface RowCase {
  21. id: number;
  22. status?: ToolCallRow["status"];
  23. isError?: boolean;
  24. fullscreen?: boolean;
  25. widget?: boolean;
  26. }
  27. const layout = () =>
  28. new Promise<void>((resolve) =>
  29. requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
  30. );
  31. /** 使用真实时间线和工具行,不直接挂 PluginUiCard;避免绕过展示资格/替代/折叠策略。 */
  32. export function RowsFixture({ config, ready }: { config: any; ready: () => void }) {
  33. const [cases, setCases] = useState<RowCase[]>([]);
  34. const [mounted, setMounted] = useState(true);
  35. const [tab, setTab] = useState<any>(null);
  36. const [opens, setOpens] = useState(0);
  37. const open = useCallback((request: any) => {
  38. setOpens((n) => n + 1);
  39. setTab({ ...request, id: buildPluginUiSidePaneTabId(request), type: "plugin-ui" });
  40. }, []);
  41. const rows = useMemo<ToolCallRow[]>(
  42. () =>
  43. cases.map((c) => ({
  44. kind: "toolCall",
  45. rowId: c.id,
  46. turnId: "fixture-turn",
  47. createdAt: c.id,
  48. createdAtSeq: c.id,
  49. toolCallId: `row-${c.id}`,
  50. toolName: "mcp__fixture__edit",
  51. status: c.status ?? "success",
  52. inputText: JSON.stringify({ sequence: c.id }),
  53. output: { text: c.isError ? `fixture-error-${c.id}` : `fixture-success-${c.id}` },
  54. ...(c.status === "error"
  55. ? { error: { code: "fixture", message: `transport-error-${c.id}` } }
  56. : {}),
  57. display: {
  58. kind: "mcp_tool",
  59. serverName: config.presentation.serverName,
  60. toolName: "edit",
  61. ui: {
  62. pluginId: config.presentation.pluginId,
  63. resourceUri: config.presentation.resourceUri,
  64. ...(c.widget
  65. ? { widgetMeta: JSON.stringify({ "openai/widgetSessionId": "same" }) }
  66. : { surface: "same" }),
  67. ...(c.isError ? { isError: true } : {}),
  68. preferredDisplayMode: c.fullscreen ? "fullscreen" : "inline",
  69. showInline: true,
  70. structuredContent: JSON.stringify({ sequence: c.id }),
  71. },
  72. },
  73. })),
  74. [cases, config],
  75. );
  76. const rowContext = useMemo(
  77. () => ({
  78. ...config.scope,
  79. theme: "light" as const,
  80. codePreviewSettings: DEFAULT_CODE_PREVIEW_SETTINGS,
  81. }),
  82. [config],
  83. );
  84. useEffect(() => {
  85. (window as any).setRows = async (next: RowCase[], pin = false) => {
  86. if (pin)
  87. for (const c of next) setPluginUiManualPin(config.scope.sessionId, `row-${c.id}`, true);
  88. flushSync(() => setCases(next));
  89. await layout();
  90. };
  91. (window as any).mountRows = async (value: boolean) => {
  92. flushSync(() => setMounted(value));
  93. await layout();
  94. };
  95. (window as any).rowsState = () => ({
  96. cards: document.querySelectorAll('[data-tool-call-id] [data-testid="plugin-ui-card"]').length,
  97. placeholders: document.querySelectorAll('[data-testid="plugin-ui-side-pane-placeholder"]')
  98. .length,
  99. opens,
  100. sidebar: tab !== null,
  101. views: document.querySelectorAll("webview").length,
  102. owners: [
  103. ...document.querySelectorAll(
  104. '[data-tool-call-id] [data-testid="plugin-ui-card"], [data-testid="plugin-ui-side-pane-placeholder"]',
  105. ),
  106. ].map((e) => e.closest("[data-tool-call-id]")?.getAttribute("data-tool-call-id")),
  107. });
  108. (window as any).waitRowsRunning = () =>
  109. new Promise<void>((resolve, reject) => {
  110. const key = buildPluginUiSurfaceKey(
  111. { ...config.scope, ...config.presentation },
  112. config.scope.scope,
  113. );
  114. let off = () => {};
  115. const check = () => {
  116. const snapshot = pluginUiPages.get(key)?.snapshot();
  117. if (snapshot?.phase === "running") {
  118. off();
  119. resolve();
  120. }
  121. if (snapshot?.phase === "error") {
  122. off();
  123. reject(new Error(snapshot.error ?? "page failed"));
  124. }
  125. };
  126. off = subscribePage(key, check);
  127. check();
  128. });
  129. (window as any).rowPageVisible = () =>
  130. pluginUiPages.get(
  131. buildPluginUiSurfaceKey({ ...config.scope, ...config.presentation }, config.scope.scope),
  132. )?.visible === true;
  133. ready();
  134. }, [config, opens, tab, ready]);
  135. return (
  136. <ZCodeIntlProvider initialLocale="en-US">
  137. <TabStoreProvider>
  138. <PluginUiWorkspaceProvider onOpenSidePane={open}>
  139. <PluginUiSessionProvider
  140. {...config.scope}
  141. readOnly
  142. sendText={async () => {}}
  143. uploadAttachment={async () => {
  144. throw new Error("not used");
  145. }}
  146. >
  147. <div style={{ position: "absolute", left: 10, top: 10, width: 460, height: 650 }}>
  148. {mounted && (
  149. <ConversationTimeline
  150. rows={rows}
  151. totalCount={rows.length}
  152. sessionKey={config.scope.sessionId}
  153. rowContext={rowContext}
  154. hideTurnNavigator
  155. />
  156. )}
  157. </div>
  158. {tab && (
  159. <div style={{ position: "absolute", left: 500, top: 10, width: 450, height: 650 }}>
  160. <button id="close-sidebar" onClick={() => setTab(null)}>
  161. Close sidebar
  162. </button>
  163. <PluginUiSidePane tab={tab} visible onCloseTab={() => setTab(null)} />
  164. </div>
  165. )}
  166. </PluginUiSessionProvider>
  167. </PluginUiWorkspaceProvider>
  168. </TabStoreProvider>
  169. </ZCodeIntlProvider>
  170. );
  171. }