WorkflowNotificationToolRow.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. import { Hourglass, MessageCircleQuestion, Workflow } from "lucide-react";
  2. import { useCallback, useEffect, useMemo, useState } from "react";
  3. import type { WorkflowNotificationMeta, WorkflowRunHole } from "@zcode/shared/zcode-protocol-v4";
  4. import { CodeBlock, CodeBlockHeader } from "@/components/ai-elements/code-block.js";
  5. import { WorkflowNotificationHoleRow } from "@/v4/WorkflowNotificationHoleRow.js";
  6. import { ToolLayout } from "@/ToolCallBlocks/ToolLayout.js";
  7. import { useZCodeIntl } from "@/i18n/IntlProvider.js";
  8. import type { Theme } from "@/useTheme.js";
  9. import { workflowRunQuestionWaitedLabel } from "@/app-shell/workflowRunQuestions.js";
  10. import { WorkflowNotificationArtifactChips } from "@/v4/WorkflowNotificationArtifactChips.js";
  11. /**
  12. * 后台 workflow 通知行。
  13. *
  14. * manifest 台账形态已否决(判为「too flowery」),改走既有工具卡语法:
  15. * 通知行与普通工具调用行视觉完全同族(ToolLayout:图标 + kindLabel + primaryText + 展开体)。
  16. * 数据契约 / 发射侧 / hydration / pendingQuestions 联查全部不动——这里只是表现层。
  17. *
  18. * 纯展示:join 结果(onOpenRun / pendingQids)由宿主从投影解析后注入,组件不自取 store,
  19. * 好让它在 renderToStaticMarkup 下可测(展开态经 forceOpen 透传给 ToolLayout)。
  20. */
  21. /** 通知行根节点的 testid 基名。 */
  22. const TID_CHAT_WORKFLOW_NOTIFICATION_ROW = "chat-workflow-notification-row";
  23. /** 折叠头部单行概要上限,照 escalate 卡:概要只是「大概问了什么」,全文在展开体里。 */
  24. const INLINE_PREVIEW_MAX_LENGTH = 160;
  25. const TERMINAL_ICON = <Workflow className="size-4 shrink-0 text-foreground-subtle" />;
  26. const ESCALATION_ICON = (
  27. <MessageCircleQuestion className="size-4 shrink-0 text-foreground-subtle" />
  28. );
  29. /** 面板正文(问题 / 结果 prose):照 escalate / submit-result 的 border-border bg-panel 惯例。 */
  30. const PANEL_CLASS =
  31. "whitespace-pre-wrap break-words rounded-lg border border-border bg-panel px-4 py-3 text-ui-base leading-5";
  32. /** 失败 error 面板:照 resolve-question outcome 的 border-destructive/40 惯例(不是行级失败装置)。 */
  33. const ERROR_PANEL_CLASS =
  34. "whitespace-pre-wrap break-words rounded-lg border border-destructive/40 bg-panel px-4 py-3 text-ui-base leading-5 text-foreground";
  35. /** 折叠成单行概要:换行折成空格,超长截断(照 escalate 卡 toInlinePreview)。 */
  36. function toInlinePreview(value: string): string | undefined {
  37. const collapsed = value.replace(/\s+/gu, " ").trim();
  38. if (collapsed.length === 0) return undefined;
  39. return collapsed.length > INLINE_PREVIEW_MAX_LENGTH
  40. ? `${collapsed.slice(0, INLINE_PREVIEW_MAX_LENGTH)}…`
  41. : collapsed;
  42. }
  43. const TERMINAL_KIND_LABEL_ID: Record<"completed" | "errored" | "stopped", string> = {
  44. completed: "chat.backgroundResult.workflow.completed",
  45. errored: "chat.backgroundResult.workflow.errored",
  46. stopped: "chat.backgroundResult.workflow.stopped",
  47. };
  48. /** stall 行的 kindLabel:run 还在跑,只是 20 分钟没有一次成功的模型请求。 */
  49. const STALL_KIND_LABEL_ID = "chat.backgroundResult.workflow.stall";
  50. const STALL_ICON = <Hourglass className="size-4 shrink-0 text-foreground-subtle" />;
  51. /** 展开体里的一个 `label: value` 事实行(stall 的等待时长 / 原因 / 并发数)。 */
  52. function factLine(label: string, value: string, key: string) {
  53. return (
  54. <p key={key} className="text-ui-sm text-foreground-subtle">
  55. <span className="text-foreground-subtlest">{label}</span> {value}
  56. </p>
  57. );
  58. }
  59. /**
  60. * 升级行 kindLabel 三态(按 pendingQuestions 在场性联查活翻转,与 manifest 同一逻辑):
  61. * pendingQids 含 qid → waiting(正在等待回答);
  62. * run 在场且 qid 缺席 → answered(问题已回答);
  63. * run 不在场(pendingQids === undefined)→ asked(中性:提出了问题)。
  64. * 不闪不 shimmer——shimmer 语义是「正在干活」,停驻问题等的是主代理。
  65. */
  66. function escalationState(
  67. pendingQids: ReadonlySet<string> | undefined,
  68. qid: string,
  69. ): "waiting" | "answered" | "asked" {
  70. if (pendingQids === undefined) return "asked";
  71. return pendingQids.has(qid) ? "waiting" : "answered";
  72. }
  73. export interface WorkflowNotificationToolRowProps {
  74. notification: WorkflowNotificationMeta;
  75. /** run 名 = originMeta.title(CLI 权威给出,不本地化)。 */
  76. runName: string;
  77. /** testid 后缀 + ToolLayout persist key,取 unit.key。 */
  78. testIdKey: string;
  79. /** CodeBlock 的应用主题(json result 走它)。 */
  80. theme: Theme;
  81. /** 预绑定的打开 run 详情回调;不可得时展开体内不渲染「打开运行详情」链接。 */
  82. onOpenRun?: () => void;
  83. /**
  84. * 预绑定的打开产物 tab 回调(宿主从 join 注入,同 `onOpenRun`)。缺席时 chips 仍然渲染,
  85. * 只是不可点——「交付了什么」是事实,「能不能打开」是能力。
  86. */
  87. onOpenArtifact?: (artifactId: string) => void;
  88. /** 升级行的在场性联查:undefined = run 不在活投影;Set 含 qid = Waiting;不含 = Answered。 */
  89. pendingQids?: ReadonlySet<string>;
  90. /** 测试/宿主强制展开(透传 ToolLayout.forceOpen);产品默认折叠。 */
  91. forceOpen?: boolean;
  92. /**
  93. * 留白行的在场性联查(docs/dynamic-workflow/transcript-and-notifications.md「The hole row's live state」):
  94. * run 投影里的 `holes`;undefined = run 不在活投影(中性词)。
  95. */
  96. holes?: readonly WorkflowRunHole[];
  97. }
  98. export function WorkflowNotificationToolRow(props: WorkflowNotificationToolRowProps) {
  99. // 留白行整个另起一件(WorkflowNotificationHoleRow.tsx):它有自己的三态与展开体,塞进下面的
  100. // 三分支只会让每个分支都多一句「不是 hole」。
  101. if (props.notification.kind === "hole") {
  102. return (
  103. <WorkflowNotificationHoleRow
  104. forceOpen={props.forceOpen ?? false}
  105. holes={props.holes}
  106. notification={props.notification}
  107. runName={props.runName}
  108. toolId={`${TID_CHAT_WORKFLOW_NOTIFICATION_ROW}-${props.testIdKey}`}
  109. {...(props.onOpenRun === undefined ? {} : { onOpenRun: props.onOpenRun })}
  110. />
  111. );
  112. }
  113. return <WorkflowNotificationBaseRow {...props} notification={props.notification} />;
  114. }
  115. function WorkflowNotificationBaseRow({
  116. notification,
  117. runName,
  118. testIdKey,
  119. theme,
  120. onOpenRun,
  121. onOpenArtifact,
  122. pendingQids,
  123. forceOpen = false,
  124. }: WorkflowNotificationToolRowProps & {
  125. notification: Exclude<WorkflowNotificationMeta, { kind: "hole" }>;
  126. }) {
  127. const { intl } = useZCodeIntl();
  128. // 等待时长要在没有事件流时也照走(停驻的 run 恰恰不发事件),按固定间隔喂新的"现在"。
  129. const [now, setNow] = useState(() => Date.now());
  130. useEffect(() => {
  131. const timer = setInterval(() => setNow(Date.now()), 30_000);
  132. return () => clearInterval(timer);
  133. }, []);
  134. const openRunLink = onOpenRun ? (
  135. <button
  136. type="button"
  137. onClick={onOpenRun}
  138. className="text-ui-sm text-foreground-subtle decoration-dotted underline-offset-2 hover:text-foreground hover:underline"
  139. >
  140. {intl.formatMessage({ id: "chat.toolCall.workflow.openRunDetails" })}
  141. </button>
  142. ) : null;
  143. const isEscalation = notification.kind === "escalation";
  144. const isStall = notification.kind === "stall";
  145. // kindLabel + primaryText + 展开体,按三类通知分别铸造。
  146. const escalationView = isEscalation ? escalationState(pendingQids, notification.qid) : undefined;
  147. // stopped 的原因词跟在 kindLabel 后。
  148. const stopReason =
  149. notification.kind === "terminal" && notification.status === "stopped"
  150. ? notification.stopReason
  151. : undefined;
  152. const kindLabel = isEscalation
  153. ? intl.formatMessage({ id: `chat.backgroundResult.workflow.${escalationView!}` })
  154. : isStall
  155. ? intl.formatMessage({ id: STALL_KIND_LABEL_ID })
  156. : stopReason !== undefined
  157. ? `${intl.formatMessage({ id: TERMINAL_KIND_LABEL_ID[notification.status] })} · ${intl.formatMessage({ id: `chat.toolCall.workflow.run.stopReason.${stopReason}` })}`
  158. : intl.formatMessage({ id: TERMINAL_KIND_LABEL_ID[notification.status] });
  159. const primaryText = useMemo(() => {
  160. if (notification.kind === "terminal" || notification.kind === "stall") {
  161. return (
  162. <span className="inline-flex min-w-0 items-center gap-2">
  163. <span aria-hidden>·</span>
  164. <span className="min-w-0 truncate">{runName}</span>
  165. </span>
  166. );
  167. }
  168. const preview = toInlinePreview(notification.question);
  169. return <span className="min-w-0 truncate">{preview ?? runName}</span>;
  170. }, [notification, runName]);
  171. // 折叠头部尾部的产物 chips。
  172. // 走 ToolLayout 的 `secondaryText` 槽,配合已有的 `hideSecondaryTextWhenOpen`——
  173. // 只在**折叠头部**展示:展开之后正文自己在说结果,chips 再挂着只是重复。
  174. const artifactChips =
  175. notification.kind === "terminal" &&
  176. notification.artifacts !== undefined &&
  177. notification.artifacts.length > 0 ? (
  178. <span className="inline-flex min-w-0 items-center gap-2">
  179. <span aria-hidden>·</span>
  180. <WorkflowNotificationArtifactChips
  181. artifacts={notification.artifacts}
  182. {...(notification.artifactsTruncated === undefined
  183. ? {}
  184. : { truncated: notification.artifactsTruncated })}
  185. {...(onOpenArtifact === undefined ? {} : { onOpenArtifact })}
  186. />
  187. </span>
  188. ) : undefined;
  189. // 展开门:终态看 artifact(errored / provider 停下的 error,否则 result),升级恒有问题正文,
  190. // stall 恒有等待事实。
  191. const hasDetails =
  192. notification.kind === "escalation" || notification.kind === "stall"
  193. ? true
  194. : notification.error !== undefined
  195. ? true
  196. : Boolean(notification.result);
  197. const waited =
  198. escalationView === "waiting" && notification.kind === "escalation"
  199. ? workflowRunQuestionWaitedLabel(notification.askedAt, now, (descriptor, values) =>
  200. intl.formatMessage(descriptor, values),
  201. )
  202. : undefined;
  203. const renderContent = useCallback(() => {
  204. if (notification.kind === "escalation") {
  205. const contextHeading = intl.formatMessage({ id: "chat.toolCall.workflow.escalate.context" });
  206. return (
  207. <div className="space-y-3">
  208. {/* 问题全文(不引用答案原文——答案在相邻 ResolveWorkflowQuestion 卡里)。 */}
  209. <p className={`${PANEL_CLASS} text-foreground`}>{notification.question}</p>
  210. {notification.context !== undefined ? (
  211. <section className="space-y-1.5">
  212. <h4 className="text-ui-sm font-medium text-foreground-subtlest">{contextHeading}</h4>
  213. <p className={`${PANEL_CLASS} text-foreground-subtle`}>{notification.context}</p>
  214. </section>
  215. ) : null}
  216. {waited ? <p className="text-ui-sm text-foreground-subtle">{waited}</p> : null}
  217. {openRunLink}
  218. </div>
  219. );
  220. }
  221. if (notification.kind === "stall") {
  222. const minutes = Math.max(1, Math.round(notification.sinceMs / 60_000));
  223. return (
  224. <div className="space-y-1" data-testid="workflow-notification-stall">
  225. <p className={`${PANEL_CLASS} text-foreground`}>
  226. {intl.formatMessage({ id: "chat.backgroundResult.workflow.stall.body" }, { minutes })}
  227. </p>
  228. {notification.reason !== undefined
  229. ? factLine(
  230. intl.formatMessage({ id: "chat.backgroundResult.workflow.stall.reason" }),
  231. notification.reason,
  232. "reason",
  233. )
  234. : null}
  235. {notification.cap !== undefined
  236. ? factLine(
  237. intl.formatMessage({ id: "chat.backgroundResult.workflow.stall.cap" }),
  238. String(notification.cap),
  239. "cap",
  240. )
  241. : null}
  242. {openRunLink}
  243. </div>
  244. );
  245. }
  246. // errored,或 stopped 而带错误明细(provider / interrupted):错误面板。
  247. if (notification.error !== undefined) {
  248. return (
  249. <div className="space-y-3">
  250. <p className={ERROR_PANEL_CLASS}>{notification.error}</p>
  251. {openRunLink}
  252. </div>
  253. );
  254. }
  255. // completed / stopped:只显示 result(prose <p> / json CodeBlock,照 submit-result 惯例)。
  256. const { result, resultForm } = notification;
  257. let resultCode = result ?? "";
  258. if (resultForm === "json") {
  259. try {
  260. resultCode = JSON.stringify(JSON.parse(resultCode), null, 2);
  261. } catch {
  262. /* 历史截断的 JSON 保留原文,不丢弃结果。 */
  263. }
  264. }
  265. return (
  266. <div className="mb-2 min-w-0 space-y-2" data-testid="workflow-notification-result">
  267. {resultForm === "json" ? (
  268. <CodeBlock
  269. appTheme={theme}
  270. code={resultCode}
  271. language="json"
  272. className="border border-border bg-card"
  273. contentClassName="max-h-80 overflow-auto"
  274. wrapLongLines
  275. >
  276. <CodeBlockHeader className="pl-3 pr-2 pt-2" language="json" />
  277. </CodeBlock>
  278. ) : (
  279. <p className="max-h-80 overflow-auto whitespace-pre-wrap break-words text-ui-base leading-relaxed text-foreground">
  280. {result}
  281. </p>
  282. )}
  283. {openRunLink}
  284. </div>
  285. );
  286. }, [notification, theme, waited, openRunLink, intl]);
  287. const toolId = `${TID_CHAT_WORKFLOW_NOTIFICATION_ROW}-${testIdKey}`;
  288. return (
  289. <div data-testid={toolId}>
  290. <ToolLayout
  291. toolId={toolId}
  292. persistOpenKey={toolId}
  293. icon={isEscalation ? ESCALATION_ICON : isStall ? STALL_ICON : TERMINAL_ICON}
  294. // 图标已由 kind 区分;showIcon 缺省即显示。
  295. canToggle={hasDetails}
  296. forceOpen={forceOpen && hasDetails}
  297. hideSecondaryTextWhenOpen
  298. kindLabel={kindLabel}
  299. primaryText={primaryText}
  300. secondaryText={artifactChips}
  301. // 关键:**不**走 ToolLayout 的 failure status 装置(那是「这次调用坏了」的语义);
  302. // 「工作流失败」由 kindLabel 说出,错误详情在展开体。也不设 isRunning(无 shimmer)。
  303. title={runName}
  304. renderContent={hasDetails ? renderContent : undefined}
  305. />
  306. </div>
  307. );
  308. }