ToolCallBlocks.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. import { memo, type ReactNode, useEffect, useMemo, useState } from "react";
  2. import { TID_CHAT_TOOL_CALL_BLOCK, testId } from "@zcode/shared";
  3. import { useIsOfficeMode } from "@/hooks/useInterfaceMode.js";
  4. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  5. import { mapToolStatus } from "@/lib/mapToolStatus.js";
  6. import { buildToolDisplayModel } from "@/lib/toolDisplay.js";
  7. import type { TaskChatToolCallTreeNode } from "@/lib/toolCallTree.js";
  8. import { getToolCallErrorText } from "@/lib/toolError.js";
  9. import {
  10. getCompactToolCallStatusMessageId,
  11. isCompactToolCallRunningState,
  12. } from "@/lib/toolCallSummary.js";
  13. import type { CodeViewerSource } from "@/lib/codeViewer.js";
  14. import { CuaGroupToolCallBlock } from "@/ToolCallBlocks/renderers/cua-group.js";
  15. import { resolveToolCallRenderer } from "@/ToolCallBlocks/resolveRenderer.js";
  16. import * as PluginUi from "@/plugin-ui/index.js";
  17. import { resolveToolCallIdentity } from "@/lib/toolIdentity.js";
  18. import {
  19. readRawToolCallFileSummaries,
  20. type ToolCallBlockRenderContext,
  21. } from "@/ToolCallBlocks/shared.js";
  22. import type { MessageFileLinkTarget } from "@/components/ai-elements/message.js";
  23. import type { ConversationCuaGroupEvent } from "@/v4/conversationCuaGroups.js";
  24. const NESTED_TOOLCALL_CONTAINER_CLASS =
  25. "ml-2 space-y-2 border-border border-l pl-3.5 border-border";
  26. const MAX_TOOL_ENTRANCE_ANIMATION_KEYS = 800;
  27. const TOOL_ENTRANCE_ANIMATION_CLEANUP_MS = 1000;
  28. const toolEntranceAnimationKeys = new Map<string, number>();
  29. function pruneToolEntranceAnimationKeys() {
  30. if (toolEntranceAnimationKeys.size <= MAX_TOOL_ENTRANCE_ANIMATION_KEYS) {
  31. return;
  32. }
  33. const staleKeys = Array.from(toolEntranceAnimationKeys.entries())
  34. .sort(([, left], [, right]) => left - right)
  35. .slice(0, toolEntranceAnimationKeys.size - MAX_TOOL_ENTRANCE_ANIMATION_KEYS)
  36. .map(([key]) => key);
  37. for (const key of staleKeys) {
  38. toolEntranceAnimationKeys.delete(key);
  39. }
  40. }
  41. function normalizeToolEntranceAnimationKey(key: string) {
  42. const normalizedKey = key.trim();
  43. return normalizedKey.length > 0 ? normalizedKey : null;
  44. }
  45. function hasPlayedToolEntranceAnimation(key: string) {
  46. const normalizedKey = normalizeToolEntranceAnimationKey(key);
  47. return normalizedKey === null || toolEntranceAnimationKeys.has(normalizedKey);
  48. }
  49. function recordToolEntranceAnimation(key: string) {
  50. const normalizedKey = normalizeToolEntranceAnimationKey(key);
  51. if (normalizedKey === null) {
  52. return;
  53. }
  54. toolEntranceAnimationKeys.set(normalizedKey, Date.now());
  55. pruneToolEntranceAnimationKeys();
  56. }
  57. function canPlayToolEntranceAnimation(key: string, active: boolean) {
  58. return active && !hasPlayedToolEntranceAnimation(key);
  59. }
  60. export function isAgentToolCall(toolCall: TaskChatToolCallTreeNode["toolCall"]): boolean {
  61. return resolveToolCallIdentity(toolCall).family === "agent";
  62. }
  63. function ToolCallBlockComponent({
  64. toolCallNode,
  65. depth = 0,
  66. workspacePath,
  67. theme,
  68. codePreviewSettings,
  69. showIcon = true,
  70. cuaAppIconClassName,
  71. onOpenCodeViewer,
  72. onOpenFileLink,
  73. onOpenBrowserUrl,
  74. onOpenAutomationsMain,
  75. onOpenPlanDetail,
  76. pluginUi: providedPluginUi,
  77. onOpenWorkflowRun,
  78. onResumeWorkflowRun,
  79. onOpenWorkflowActor,
  80. onOpenWorkflowWorkspace,
  81. onOpenWorkflowArtifact,
  82. workflowRun,
  83. workflowDraft,
  84. onLoadFullToolCallFields,
  85. suppressSourceLabel = false,
  86. showTodoToolCalls = true,
  87. disableSummaryContentAnimation = false,
  88. animateDiffCountOnMount = false,
  89. agentSummaryAction,
  90. authoritativeAgentType,
  91. streamingEntranceActive = false,
  92. streamingEntranceKeyPrefix = "tool",
  93. cuaGroupEvents,
  94. renderCuaAssistantMessage,
  95. renderCuaReasoning,
  96. }: {
  97. toolCallNode: TaskChatToolCallTreeNode;
  98. depth?: number;
  99. workspacePath: string;
  100. /** 应用主题(store 耦合剥离):由宿主(v4 SessionPane 等)传入,缺省按 "system" 兜底。 */
  101. theme?: ToolCallBlockRenderContext["theme"];
  102. /** 代码预览设置(store 耦合剥离):由宿主传入并保持引用稳定。 */
  103. codePreviewSettings?: ToolCallBlockRenderContext["codePreviewSettings"];
  104. showIcon?: boolean;
  105. cuaAppIconClassName?: ToolCallBlockRenderContext["cuaAppIconClassName"];
  106. onOpenCodeViewer?: (source: CodeViewerSource) => void;
  107. onOpenFileLink?: (target: MessageFileLinkTarget) => void;
  108. onOpenBrowserUrl?: (url: string) => void;
  109. onOpenAutomationsMain?: (automationId?: string) => void;
  110. onOpenPlanDetail?: ToolCallBlockRenderContext["onOpenPlanDetail"];
  111. pluginUi?: ToolCallBlockRenderContext["pluginUi"];
  112. onOpenWorkflowRun?: ToolCallBlockRenderContext["onOpenWorkflowRun"];
  113. /** 工具卡页脚的 Resume;与 workflowRun 同样不向子工具卡透传。 */
  114. onResumeWorkflowRun?: ToolCallBlockRenderContext["onResumeWorkflowRun"];
  115. /** 药丸 → 子代理 transcript;同样不向子工具卡透传。 */
  116. onOpenWorkflowActor?: ToolCallBlockRenderContext["onOpenWorkflowActor"];
  117. /** 脚本药丸 → 脚本 transcript;同样不向子工具卡透传。 */
  118. onOpenWorkflowWorkspace?: ToolCallBlockRenderContext["onOpenWorkflowWorkspace"];
  119. /** 产物药丸 → 产物 tab;同样不向子工具卡透传。 */
  120. onOpenWorkflowArtifact?: ToolCallBlockRenderContext["onOpenWorkflowArtifact"];
  121. /**
  122. * 该工具调用联接到的 workflow run 摘要(宿主按 toolCallId 从 workflowRuns 投影解析)。
  123. * 刻意**不**向子工具卡透传:摘要是按 toolCallId 联接出来的,把父卡的 run 摘要传给
  124. * 一个不同 toolCallId 的子卡,画出来的就是别人的运行态。
  125. */
  126. workflowRun?: ToolCallBlockRenderContext["workflowRun"];
  127. /** 编译反馈的草稿位置(宿主按 toolCallId 从行窗口联接);同 workflowRun,不向子工具卡透传。 */
  128. workflowDraft?: ToolCallBlockRenderContext["workflowDraft"];
  129. onLoadFullToolCallFields?: (toolId: string) => Promise<boolean | void> | boolean | void;
  130. suppressSourceLabel?: boolean;
  131. showTodoToolCalls?: boolean;
  132. disableSummaryContentAnimation?: boolean;
  133. animateDiffCountOnMount?: boolean;
  134. agentSummaryAction?: ToolCallBlockRenderContext["agentSummaryAction"];
  135. authoritativeAgentType?: ToolCallBlockRenderContext["authoritativeAgentType"];
  136. streamingEntranceActive?: boolean;
  137. streamingEntranceKeyPrefix?: string;
  138. cuaGroupEvents?: readonly ConversationCuaGroupEvent[];
  139. renderCuaAssistantMessage?: (
  140. event: Extract<ConversationCuaGroupEvent, { kind: "assistantMessage" }>,
  141. ) => ReactNode;
  142. renderCuaReasoning?: (
  143. event: Extract<ConversationCuaGroupEvent, { kind: "reasoning" }>,
  144. ) => ReactNode;
  145. }) {
  146. const inheritedPluginUi = PluginUi.usePluginUiToolBinding(toolCallNode.toolCall.toolId);
  147. const pluginUi = providedPluginUi ?? inheritedPluginUi;
  148. const { toolCall, childToolCalls } = toolCallNode;
  149. const { intl } = useZCodeIntl();
  150. const isOfficeMode = useIsOfficeMode();
  151. const toolEntranceAnimationKey = `${streamingEntranceKeyPrefix}:${toolCall.toolId}`;
  152. // tool 在流式对话中新出现时如果没有淡入,会和同一段文字的渐入节奏割裂。
  153. // 这里按 toolId 记录已经展示过的 tool,切换任务或虚拟列表重挂时不重复播放。
  154. // 记录动作放在 effect 里延迟执行,避免 React 开发态重挂把第一次动画误吞掉。
  155. const [shouldPlayEntranceAnimation, setShouldPlayEntranceAnimation] = useState(() =>
  156. canPlayToolEntranceAnimation(toolEntranceAnimationKey, streamingEntranceActive),
  157. );
  158. useEffect(() => {
  159. if (!streamingEntranceActive || shouldPlayEntranceAnimation) {
  160. return;
  161. }
  162. if (canPlayToolEntranceAnimation(toolEntranceAnimationKey, streamingEntranceActive)) {
  163. setShouldPlayEntranceAnimation(true);
  164. }
  165. }, [shouldPlayEntranceAnimation, streamingEntranceActive, toolEntranceAnimationKey]);
  166. useEffect(() => {
  167. if (!shouldPlayEntranceAnimation) {
  168. return;
  169. }
  170. const markAnimatedTimer = window.setTimeout(() => {
  171. recordToolEntranceAnimation(toolEntranceAnimationKey);
  172. }, 0);
  173. const cleanupTimer = window.setTimeout(() => {
  174. setShouldPlayEntranceAnimation(false);
  175. }, TOOL_ENTRANCE_ANIMATION_CLEANUP_MS);
  176. return () => {
  177. window.clearTimeout(markAnimatedTimer);
  178. window.clearTimeout(cleanupTimer);
  179. };
  180. }, [shouldPlayEntranceAnimation, toolEntranceAnimationKey]);
  181. // 注意:下面的 early return 必须放在所有 hook 调用之后。
  182. // 之前这里在 useMemo 之前就 `return null`,导致当某个 toolCall 的
  183. // family 在 todo 与非 todo 之间切换(或 showTodoToolCalls 变化)时,
  184. // 本组件这次渲染执行的 hook 数量和上次不一致,React 会抛出
  185. // "Rendered fewer hooks than expected" 并导致整个聊天页面白屏崩溃。
  186. // 修复方式:把 early return 下移到所有 hook 之后,保证 hook 调用顺序稳定。
  187. const identity = resolveToolCallIdentity(toolCall);
  188. const toolState = mapToolStatus(toolCall.status);
  189. const displayModel = useMemo(
  190. () => buildToolDisplayModel(toolCall, workspacePath),
  191. [toolCall, workspacePath],
  192. );
  193. const rawFileSummaries = useMemo(
  194. () =>
  195. readRawToolCallFileSummaries(toolCall.raw, {
  196. toolName: toolCall.toolName,
  197. kind: toolCall.kind,
  198. title: toolCall.title,
  199. input: toolCall.input,
  200. output: toolCall.output,
  201. raw: toolCall.raw,
  202. }),
  203. [
  204. toolCall.input,
  205. toolCall.kind,
  206. toolCall.output,
  207. toolCall.raw,
  208. toolCall.title,
  209. toolCall.toolName,
  210. ],
  211. );
  212. const isRunning = isCompactToolCallRunningState(toolState);
  213. const statusLabel = intl.formatMessage({
  214. id: getCompactToolCallStatusMessageId(toolState, toolCall.status),
  215. });
  216. const errorText = getToolCallErrorText(toolCall);
  217. const isCurrentAgentToolCall = isAgentToolCall(toolCall);
  218. const isSubAgentToolCall = !isCurrentAgentToolCall && (depth > 0 || toolCall.parentToolUseId);
  219. const sourceLabel =
  220. !suppressSourceLabel && isSubAgentToolCall
  221. ? intl.formatMessage({ id: "chat.toolCall.source.subAgent" })
  222. : undefined;
  223. // 之前为了避免“双预览”把 onOpenCodeViewer 全局置空,
  224. // 会导致 edit/read 文件摘要失去点击能力,回归为“看得到文件名但不能点”。
  225. // 这里恢复透传,保持历史交互;是否做“避免双预览”应改为更细粒度开关,而不是一刀切禁用。
  226. const toolPreviewCodeViewer: ToolCallBlockRenderContext["onOpenCodeViewer"] = onOpenCodeViewer;
  227. const childToolList = useMemo(
  228. () =>
  229. childToolCalls.length > 0 ? (
  230. <div className={NESTED_TOOLCALL_CONTAINER_CLASS}>
  231. {childToolCalls.map((childToolCallNode) => (
  232. <ToolCallBlock
  233. key={childToolCallNode.toolCall.toolId}
  234. toolCallNode={childToolCallNode}
  235. depth={depth + 1}
  236. workspacePath={workspacePath}
  237. theme={theme}
  238. codePreviewSettings={codePreviewSettings}
  239. showIcon={showIcon}
  240. onOpenCodeViewer={toolPreviewCodeViewer}
  241. onOpenFileLink={onOpenFileLink}
  242. onOpenBrowserUrl={onOpenBrowserUrl}
  243. onOpenAutomationsMain={onOpenAutomationsMain}
  244. onOpenPlanDetail={onOpenPlanDetail}
  245. onOpenWorkflowRun={onOpenWorkflowRun}
  246. onLoadFullToolCallFields={onLoadFullToolCallFields}
  247. suppressSourceLabel={suppressSourceLabel}
  248. showTodoToolCalls={showTodoToolCalls}
  249. disableSummaryContentAnimation={disableSummaryContentAnimation}
  250. animateDiffCountOnMount={animateDiffCountOnMount}
  251. streamingEntranceActive={streamingEntranceActive}
  252. streamingEntranceKeyPrefix={streamingEntranceKeyPrefix}
  253. />
  254. ))}
  255. </div>
  256. ) : null,
  257. [
  258. childToolCalls,
  259. depth,
  260. onLoadFullToolCallFields,
  261. onOpenAutomationsMain,
  262. onOpenBrowserUrl,
  263. onOpenPlanDetail,
  264. onOpenFileLink,
  265. showIcon,
  266. showTodoToolCalls,
  267. streamingEntranceActive,
  268. streamingEntranceKeyPrefix,
  269. suppressSourceLabel,
  270. theme,
  271. codePreviewSettings,
  272. toolPreviewCodeViewer,
  273. workspacePath,
  274. ],
  275. );
  276. const renderContext: ToolCallBlockRenderContext = useMemo(
  277. () => ({
  278. isOfficeMode,
  279. toolCallNode,
  280. workspacePath,
  281. theme,
  282. codePreviewSettings,
  283. displayModel,
  284. viewerSource: displayModel.viewerSource,
  285. rawFileSummaries,
  286. isRunning,
  287. statusLabel,
  288. sourceLabel,
  289. errorText,
  290. childToolList,
  291. showIcon,
  292. cuaAppIconClassName,
  293. showTodoToolCalls,
  294. disableSummaryContentAnimation,
  295. animateDiffCountOnMount,
  296. agentSummaryAction,
  297. authoritativeAgentType,
  298. onOpenCodeViewer: toolPreviewCodeViewer,
  299. onOpenFileLink,
  300. onOpenBrowserUrl,
  301. onOpenAutomationsMain,
  302. onOpenPlanDetail,
  303. pluginUi,
  304. // onOpenWorkflowRun 之前只被透传给子工具卡,从未进过 renderContext,
  305. // 于是 CreateWorkflow renderer 永远收不到它——「打开详情页」的入口不是被埋深了,
  306. // 是根本没渲染过。run 态紧凑卡就挂在这个回调上,所以它必须在这里。
  307. onOpenWorkflowRun,
  308. onResumeWorkflowRun,
  309. onOpenWorkflowActor,
  310. onOpenWorkflowWorkspace,
  311. onOpenWorkflowArtifact,
  312. workflowRun,
  313. workflowDraft,
  314. onLoadFullToolCallFields,
  315. }),
  316. [
  317. isOfficeMode,
  318. agentSummaryAction,
  319. authoritativeAgentType,
  320. childToolList,
  321. codePreviewSettings,
  322. cuaAppIconClassName,
  323. displayModel,
  324. disableSummaryContentAnimation,
  325. animateDiffCountOnMount,
  326. errorText,
  327. isRunning,
  328. onLoadFullToolCallFields,
  329. onOpenAutomationsMain,
  330. onOpenBrowserUrl,
  331. onOpenPlanDetail,
  332. pluginUi,
  333. onOpenWorkflowRun,
  334. onResumeWorkflowRun,
  335. onOpenWorkflowActor,
  336. onOpenWorkflowWorkspace,
  337. onOpenWorkflowArtifact,
  338. onOpenFileLink,
  339. rawFileSummaries,
  340. showIcon,
  341. showTodoToolCalls,
  342. sourceLabel,
  343. statusLabel,
  344. suppressSourceLabel,
  345. theme,
  346. toolCallNode,
  347. toolPreviewCodeViewer,
  348. workflowRun,
  349. workflowDraft,
  350. workspacePath,
  351. ],
  352. );
  353. const ToolCallRenderer = useMemo(() => resolveToolCallRenderer(renderContext), [renderContext]);
  354. // early return 必须在所有 hook 之后(见上方注释说明的崩溃原因)
  355. if (!showTodoToolCalls && identity.family === "todo") {
  356. return null;
  357. }
  358. return (
  359. <div
  360. className="w-full"
  361. data-testid={testId(TID_CHAT_TOOL_CALL_BLOCK, toolCall.toolId)}
  362. data-tool-call-id={toolCall.toolId}
  363. data-tool-name={toolCall.toolName ?? toolCall.kind ?? ""}
  364. data-status={toolCall.status}
  365. data-zcode-tool-stream-animate={shouldPlayEntranceAnimation ? "true" : undefined}
  366. >
  367. {toolCall.kind === "cuaGroup" ? (
  368. <CuaGroupToolCallBlock
  369. {...renderContext}
  370. events={cuaGroupEvents}
  371. renderAssistantMessage={renderCuaAssistantMessage}
  372. renderReasoning={renderCuaReasoning}
  373. />
  374. ) : (
  375. <ToolCallRenderer {...renderContext} />
  376. )}
  377. </div>
  378. );
  379. }
  380. export const ToolCallBlock = memo(ToolCallBlockComponent);
  381. ToolCallBlock.displayName = "ToolCallBlock";