tool-summary-spacing.fixture.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import { useState } from "react";
  2. import type { ConversationRow } from "@zcode/shared/zcode-protocol-v4";
  3. import { ConversationShareReadonlyTimeline } from "@/v4/ConversationShareReadonlyTimeline.js";
  4. import { WorkflowToolSummary } from "@/v4/WorkflowToolSummary.js";
  5. import type { WorkflowRunCardSummary } from "@/ToolCallBlocks/shared.js";
  6. import { ConsecutiveSummaryGroup } from "@/ToolCallBlocks/ToolSummaryRow.js";
  7. import { SummaryGroupBoundaryContext } from "@/v4/conversationRowContext.js";
  8. import {
  9. Reasoning,
  10. ReasoningTrigger,
  11. ReasoningContent,
  12. } from "@/components/ai-elements/reasoning.js";
  13. import type { IServiceAccessor } from "@zcode/services";
  14. import { ZCODE_AGENT_PROVIDER } from "@zcode/shared";
  15. import { ServiceProvider } from "@/hooks/useServices.js";
  16. import { TabStoreProvider } from "@/store/TabStoreProvider.js";
  17. import { useToolPresentationHostCapabilities } from "@/hooks/useToolPresentationHostCapabilities.js";
  18. import { useSubagentsContextStore } from "@/store/subagentsContextStore.js";
  19. import {
  20. useSubagentsStore,
  21. refreshLoadedSubagentsStoreForWorkspace,
  22. } from "@/store/subagentsStore.js";
  23. import { createRoot } from "react-dom/client";
  24. import { ToolPresentation } from "@/ToolCallBlocks/ToolPresentation.js";
  25. import { ToolPresentationCapabilitiesProvider } from "@/ToolCallBlocks/presentationCapabilities.js";
  26. import { TooltipProvider } from "@/components/ui/tooltip.js";
  27. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  28. import type { TaskChatToolCallTreeNode } from "@/lib/toolCallTree.js";
  29. import "@/styles.css";
  30. const params = new URLSearchParams(location.search);
  31. const theme = params.get("theme") === "dark" ? "dark" : "light";
  32. document.documentElement.className = `${theme} theme-zai-${theme}`;
  33. const tool = (
  34. id: string,
  35. kind: string,
  36. input: unknown,
  37. title: string,
  38. ): TaskChatToolCallTreeNode => ({
  39. toolCall: { toolId: id, toolName: kind, kind, input, title, status: "completed", output: "ok" },
  40. childToolCalls: [],
  41. });
  42. const rows = [
  43. tool(
  44. "node",
  45. "mcp__node_repl__js",
  46. { code: "1 + 1", title: "点击定位按钮并截图确认" },
  47. "点击定位按钮并截图确认",
  48. ),
  49. ...["in_progress", "failed", "stopped"].map((status) => ({
  50. ...tool(
  51. `node-${status}`,
  52. "mcp__node_repl__js",
  53. { code: "1 + 1", title: "检查设置页面" },
  54. "检查设置页面",
  55. ),
  56. toolCall: {
  57. ...tool(
  58. `node-${status}`,
  59. "mcp__node_repl__js",
  60. { code: "1 + 1", title: "检查设置页面" },
  61. "检查设置页面",
  62. ).toolCall,
  63. status,
  64. },
  65. })),
  66. tool("read", "Read", { file_path: "/workspace/example.ts" }, "Read file"),
  67. tool("write", "Write", { file_path: "/workspace/package.json", content: "{}" }, "Write file"),
  68. tool(
  69. "edit",
  70. "Edit",
  71. { file_path: "/workspace/src/App.tsx", old_string: "before", new_string: "after" },
  72. "Edit file",
  73. ),
  74. tool("execute", "Bash", { command: "echo done" }, "Run command"),
  75. tool("agent", "Agent", { subagent_type: "general-purpose", description: "检查布局" }, "检查布局"),
  76. ...["pending", "in_progress", "failed", "stopped"].map((status) => ({
  77. ...tool(
  78. `agent-${status}`,
  79. "Agent",
  80. { subagent_type: "general-purpose", description: "检查布局" },
  81. "检查布局",
  82. ),
  83. toolCall: {
  84. ...tool(
  85. `agent-${status}`,
  86. "Agent",
  87. { subagent_type: "general-purpose", description: "检查布局" },
  88. "检查布局",
  89. ).toolCall,
  90. status,
  91. },
  92. })),
  93. tool(
  94. "todo-spacing",
  95. "TodoWrite",
  96. {
  97. todos: [
  98. { content: "Summarize results", status: "completed", activeForm: "Summarizing results" },
  99. ],
  100. },
  101. "Summarize results",
  102. ),
  103. tool("cua-hover", "mcp__computer-use__click", { x: 10, y: 10 }, "检查页面"),
  104. tool("mcp", "mcp__example__lookup", { query: "example" }, "查询资料"),
  105. ];
  106. let configuredFixtureColor = "pink";
  107. const fixtureService = {
  108. list: async () => ({
  109. agents: [{ id: "general-purpose", name: "general-purpose", color: configuredFixtureColor }],
  110. capability: null,
  111. }),
  112. };
  113. const fixtureServices = { subagentsService: fixtureService } as unknown as IServiceAccessor;
  114. if (params.has("hostColors")) {
  115. // 同路径的其他设备缓存和全局列表不能覆盖当前服务的配置。
  116. const foreignContext = {
  117. workspacePath: "/workspace",
  118. workspaceIdentity: "other-device",
  119. provider: ZCODE_AGENT_PROVIDER,
  120. agents: [{ id: "general-purpose", name: "general-purpose", color: "green" }],
  121. capability: null,
  122. loading: false,
  123. loaded: true,
  124. error: null,
  125. };
  126. useSubagentsContextStore.setState({
  127. contexts: {
  128. first: foreignContext,
  129. second: { ...foreignContext, workspaceIdentity: "another-device" },
  130. },
  131. });
  132. useSubagentsStore.setState({ agents: foreignContext.agents });
  133. }
  134. function HostColorSample() {
  135. const capabilities = useToolPresentationHostCapabilities("/workspace");
  136. return (
  137. <ToolPresentationCapabilitiesProvider value={capabilities}>
  138. <section data-example="host-color">
  139. <ToolPresentation
  140. toolCallNode={tool(
  141. "host-agent",
  142. "Agent",
  143. { subagent_type: "general-purpose", description: "当前工作区配置" },
  144. "当前工作区配置",
  145. )}
  146. />
  147. <button
  148. onClick={async () => {
  149. configuredFixtureColor = "blue";
  150. await refreshLoadedSubagentsStoreForWorkspace({
  151. scope: "user",
  152. subagentsService: fixtureService as unknown as IServiceAccessor["subagentsService"],
  153. });
  154. }}
  155. >
  156. 刷新为蓝色配置
  157. </button>
  158. </section>
  159. </ToolPresentationCapabilitiesProvider>
  160. );
  161. }
  162. // 用真实分享 renderer 检查连续工具,数据为确定性的浏览器验收 fixture。
  163. const shareRows: ConversationRow[] = [
  164. {
  165. rowId: 1,
  166. turnId: "mixed",
  167. createdAt: 1,
  168. createdAtSeq: 1,
  169. kind: "turnHeader",
  170. origin: "backgroundResult",
  171. state: "completedSuccess",
  172. startedAt: 1,
  173. endedAt: 10,
  174. },
  175. ...(params.has("sessions")
  176. ? [
  177. "ListSessions",
  178. "ReadSession",
  179. "Reasoning",
  180. "SendToSession",
  181. "WaitSessions",
  182. "Bash",
  183. "OtherSession",
  184. "ListSessions",
  185. "ReadSession",
  186. "Agent",
  187. "ListSessions",
  188. "ReadSession",
  189. ]
  190. : params.has("changes")
  191. ? ["Write", "Edit", "Write", "Edit", "Write", "Write"]
  192. : [
  193. "Read",
  194. "Read",
  195. "Reasoning",
  196. "Bash",
  197. "Write",
  198. "Edit",
  199. "mcp__computer-use__list_apps",
  200. "mcp__computer-use__screenshot",
  201. "mcp__node_repl__js",
  202. "Agent",
  203. "CreateWorkflow",
  204. "Read",
  205. "Read",
  206. ]
  207. ).map((name, index): ConversationRow => {
  208. const base = {
  209. rowId: index + 2,
  210. turnId: "mixed",
  211. createdAt: index + 2,
  212. createdAtSeq: index + 2,
  213. };
  214. if (name === "Reasoning")
  215. return {
  216. ...base,
  217. kind: "reasoning",
  218. text: "检查文件后继续执行构建",
  219. state: "complete",
  220. durationMs: 3000,
  221. };
  222. return {
  223. ...base,
  224. kind: "toolCall",
  225. toolCallId: `mixed-${index}`,
  226. inputText: "{}",
  227. toolName: name,
  228. status: "success",
  229. ...(params.has("sessions")
  230. ? {
  231. output:
  232. name === "ListSessions"
  233. ? {
  234. text: JSON.stringify({
  235. sessions: [
  236. { session: { sessionId: "sess_one" } },
  237. { session: { sessionId: "sess_two" } },
  238. ],
  239. }),
  240. }
  241. : name === "ReadSession"
  242. ? {
  243. text: JSON.stringify({
  244. view: "messages",
  245. messages: [{ role: "assistant", text: "Session detail preserved" }],
  246. }),
  247. }
  248. : undefined,
  249. }
  250. : {}),
  251. input:
  252. params.has("sessions") && ["ReadSession", "SendToSession", "WaitSessions"].includes(name)
  253. ? name === "WaitSessions"
  254. ? { operations: [{ sessionId: "sess_one", commandId: "example" }] }
  255. : { sessionId: "sess_one" }
  256. : name === "Bash"
  257. ? { command: "echo example" }
  258. : name === "Agent"
  259. ? { subagent_type: "general-purpose", description: "检查布局" }
  260. : {
  261. file_path: params.has("changes")
  262. ? [
  263. "/workspace/src/App.tsx",
  264. "/workspace/src/App.tsx",
  265. "/workspace/src/styles.css",
  266. "/workspace/src/game.ts",
  267. "/workspace/src/lib/a.ts",
  268. "/workspace/src/lib/b.ts",
  269. ][index]
  270. : "/workspace/example.ts",
  271. content: "example",
  272. },
  273. };
  274. }),
  275. ];
  276. const bashDescription =
  277. params.get("description") === "empty"
  278. ? " "
  279. : params.get("description") === "missing"
  280. ? undefined
  281. : "检查当前项目的构建结果";
  282. function CrossGroupPreview() {
  283. const [size, setSize] = useState(3);
  284. const [boundary, setBoundary] = useState(false);
  285. const [finished, setFinished] = useState(false);
  286. const [toolFinished, setToolFinished] = useState(false);
  287. const [lateTool, setLateTool] = useState(false);
  288. const [unknownPath, setUnknownPath] = useState(false);
  289. const [failed, setFailed] = useState(false);
  290. const [earlierRunning, setEarlierRunning] = useState(false);
  291. const displayed = shareRows.slice(0, size).map((row, index): ConversationRow => {
  292. if (params.has("bash") && index === 2 && row.kind === "toolCall")
  293. row = {
  294. ...row,
  295. toolName: "Bash",
  296. input: { command: "echo bash-summary-output", description: bashDescription },
  297. output: { text: "bash-summary-output" },
  298. };
  299. if (params.get("first") === "cua" && index === 1 && row.kind === "toolCall")
  300. return { ...row, toolName: "mcp__computer-use__screenshot", input: {} };
  301. if (row.kind === "turnHeader")
  302. return {
  303. ...row,
  304. state: finished ? "completedSuccess" : "running",
  305. endedAt: finished ? 10 : undefined,
  306. };
  307. if (earlierRunning && index === 1 && row.kind === "toolCall")
  308. return { ...row, status: "running" };
  309. if (unknownPath && row.kind === "toolCall" && row.toolName === "Write")
  310. return { ...row, input: { content: "example" } };
  311. if (failed && index === size - 1 && row.kind === "toolCall")
  312. return { ...row, status: "error", error: { code: "fixture", message: "Example failure" } };
  313. if (lateTool && index === size - 1 && row.kind === "toolCall")
  314. return { ...row, status: "running" };
  315. if (index !== size - 1 || finished || toolFinished) return row;
  316. if (row.kind === "toolCall") return { ...row, status: "running" };
  317. if (row.kind === "reasoning") return { ...row, state: "streaming" };
  318. return row;
  319. });
  320. if (boundary)
  321. displayed.splice(3, 0, {
  322. rowId: 100,
  323. turnId: "mixed",
  324. createdAt: 3,
  325. createdAtSeq: 3,
  326. kind: "assistantText",
  327. text: "正文切断分组",
  328. state: "complete",
  329. });
  330. return (
  331. <main className="min-h-dvh bg-background text-foreground">
  332. {params.has("bash") && (
  333. <ZCodeIntlProvider initialLocale={params.get("locale") === "en-US" ? "en-US" : "zh-CN"}>
  334. <section data-bash-standalone>
  335. <ToolPresentation
  336. toolCallNode={tool(
  337. "bash-standalone",
  338. "Bash",
  339. { command: "echo bash-summary-output", description: bashDescription },
  340. "Bash",
  341. )}
  342. />
  343. </section>
  344. </ZCodeIntlProvider>
  345. )}
  346. <nav className="flex flex-wrap gap-4 p-4 text-ui-base">
  347. <button
  348. onClick={() => {
  349. setFinished(false);
  350. setFailed(false);
  351. setToolFinished(false);
  352. setLateTool(false);
  353. setSize((value) => Math.min(value + 1, shareRows.length));
  354. }}
  355. >
  356. Next summary
  357. </button>
  358. <button
  359. onClick={() => {
  360. setFinished(false);
  361. setFailed(false);
  362. setToolFinished(false);
  363. setLateTool(false);
  364. setSize(2);
  365. }}
  366. >
  367. Reset
  368. </button>
  369. <button onClick={() => setBoundary((value) => !value)}>Text boundary</button>
  370. <button
  371. onClick={() => {
  372. setLateTool(false);
  373. setFinished(true);
  374. }}
  375. >
  376. Finish
  377. </button>
  378. <button onClick={() => setToolFinished(true)}>Tool done</button>
  379. <button onClick={() => setEarlierRunning((value) => !value)}>Earlier running</button>
  380. <button
  381. onClick={() => {
  382. setFinished(true);
  383. setLateTool(true);
  384. }}
  385. >
  386. Late tool
  387. </button>
  388. <button onClick={() => setUnknownPath((value) => !value)}>Unknown path</button>
  389. <button
  390. onClick={() => {
  391. setFinished(true);
  392. setFailed(true);
  393. }}
  394. >
  395. Failed call
  396. </button>
  397. </nav>
  398. <ConversationShareReadonlyTimeline
  399. rows={displayed}
  400. theme={theme}
  401. locale={params.get("locale") === "en-US" ? "en-US" : "zh-CN"}
  402. />
  403. </main>
  404. );
  405. }
  406. function ScrollPreview() {
  407. const [count, setCount] = useState(20);
  408. const [extra, setExtra] = useState(false);
  409. return (
  410. <ZCodeIntlProvider initialLocale="en-US">
  411. <TooltipProvider>
  412. <main
  413. data-scroll-parent
  414. className="bg-background p-4 text-foreground text-ui-base"
  415. style={params.has("chain") ? { height: 600, overflowY: "auto" } : undefined}
  416. >
  417. <button onClick={() => setCount((value) => value + 1)}>Append</button>
  418. <button onClick={() => setExtra((value) => !value)}>Grow</button>
  419. <button onClick={() => setCount(12)}>Short</button>
  420. <SummaryGroupBoundaryContext.Provider value={{ taskRunning: true, tailRowId: count }}>
  421. <ConsecutiveSummaryGroup
  422. summary="Reading"
  423. statistics={`Read ${count} files`}
  424. contentKey={String(count)}
  425. refreshVersion={count}
  426. lastRowId={count}
  427. hasActiveItem={false}
  428. >
  429. {Array.from({ length: count }, (_, i) => (
  430. <div key={i} className="summary-hover-text" data-scroll-row>
  431. {`Read file ${i}`}
  432. {extra && i === count - 1 ? <div style={{ height: 100 }}>Details</div> : null}
  433. </div>
  434. ))}
  435. </ConsecutiveSummaryGroup>
  436. </SummaryGroupBoundaryContext.Provider>
  437. {params.has("chain") && <div style={{ height: 1000 }} />}
  438. <Reasoning defaultOpen>
  439. <ReasoningTrigger />
  440. <ReasoningContent>
  441. {Array.from({ length: count * 2 }, (_, i) => `Thought ${i}`).join("\n")}
  442. </ReasoningContent>
  443. </Reasoning>
  444. </main>
  445. </TooltipProvider>
  446. </ZCodeIntlProvider>
  447. );
  448. }
  449. if (params.has("scroll")) {
  450. createRoot(document.getElementById("root")!).render(<ScrollPreview />);
  451. } else if (params.has("share")) {
  452. createRoot(document.getElementById("root")!).render(
  453. <TooltipProvider>
  454. <CrossGroupPreview />
  455. </TooltipProvider>,
  456. );
  457. } else {
  458. createRoot(document.getElementById("root")!).render(
  459. <ZCodeIntlProvider initialLocale={params.get("locale") === "en-US" ? "en-US" : "zh-CN"}>
  460. <TooltipProvider>
  461. <ToolPresentationCapabilitiesProvider value={{ readonly: true }}>
  462. <main
  463. data-conversation-work-items
  464. className="@container/conversation min-h-screen flex flex-col gap-1 bg-background p-6 text-foreground"
  465. >
  466. <section data-example="workflow-summary-spacing">
  467. <WorkflowToolSummary
  468. toolCallId="workflow-summary-spacing"
  469. summary={{ runId: "workflow-example", agents: 2 } as WorkflowRunCardSummary}
  470. onOpen={() => undefined}
  471. />
  472. </section>
  473. <section data-example="reasoning-hover">
  474. <Reasoning duration={3}>
  475. <ReasoningTrigger />
  476. </Reasoning>
  477. </section>
  478. <section data-example="reasoning-running-hover">
  479. <Reasoning isStreaming>
  480. <ReasoningTrigger />
  481. </Reasoning>
  482. </section>
  483. {params.has("hostColors") ? (
  484. <ServiceProvider services={fixtureServices}>
  485. <TabStoreProvider>
  486. <HostColorSample />
  487. </TabStoreProvider>
  488. </ServiceProvider>
  489. ) : null}
  490. <section data-example="body-spacing">正文段落间距保持原值。</section>
  491. {rows.map((node) => (
  492. <section key={node.toolCall.toolId} data-example={node.toolCall.toolId}>
  493. <ToolPresentation toolCallNode={node} showTodoToolCalls />
  494. </section>
  495. ))}
  496. </main>
  497. </ToolPresentationCapabilitiesProvider>
  498. </TooltipProvider>
  499. </ZCodeIntlProvider>,
  500. );
  501. }