workflowObservationToolCards.test.ts 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. // @vitest-environment jsdom
  2. //
  3. // 观察类工作流工具卡的渲染与分流测试(spec: docs/dynamic-workflow/launch.md
  4. // 「工具卡 display」、docs/dynamic-workflow/authoring.md「EvalWorkflowSnippet」、docs/dynamic-workflow/launch.md「`SaveWorkflow`」「结果卡 display
  5. // 增补」)。三个工具此前没有登记进已知工具表,全部掉进 raw JSON 兜底卡——本文件钉住
  6. // 「按名分流 + display 驱动 + 无 display 时文本兜底(绝不是 JSON dump)」三件事。
  7. import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
  8. import { createElement } from "react";
  9. import { afterEach, describe, expect, it, vi } from "vitest";
  10. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  11. import enUS from "@/i18n/locales/en-US.js";
  12. import zhCN from "@/i18n/locales/zh-CN.js";
  13. import { resolveToolCallRenderer } from "@/ToolCallBlocks/resolveRenderer.js";
  14. import { EvalWorkflowSnippetToolCallBlock } from "@/ToolCallBlocks/renderers/eval-workflow-snippet.js";
  15. import { GetWorkflowRunToolCallBlock } from "@/ToolCallBlocks/renderers/get-workflow-run.js";
  16. import { ListWorkflowRunsToolCallBlock } from "@/ToolCallBlocks/renderers/list-workflow-runs.js";
  17. import { ResumeWorkflowRunToolCallBlock } from "@/ToolCallBlocks/renderers/resume-workflow-run.js";
  18. import type { ToolCallBlockRenderContext } from "@/ToolCallBlocks/shared.js";
  19. vi.mock("@/components/ui/code-viewer.js", () => ({
  20. CodeViewer: ({ code, language }: { code: string; language: string }) =>
  21. createElement("pre", { "data-language": language }, code),
  22. }));
  23. vi.mock("@/components/ai-elements/code-block.js", () => ({
  24. CodeBlockHeader: () => null,
  25. CodeBlockCopyButton: () => null,
  26. CodeBlock: ({
  27. code,
  28. language,
  29. contentClassName,
  30. }: {
  31. code: string;
  32. language?: string;
  33. contentClassName?: string;
  34. children?: React.ReactNode;
  35. }) =>
  36. createElement(
  37. "pre",
  38. { "data-testid": "code-block", "data-language": language, className: contentClassName },
  39. code,
  40. ),
  41. }));
  42. const GET_RUN_DISPLAY = {
  43. kind: "get_workflow_run",
  44. runId: "wf_demo",
  45. label: "nightly-sync",
  46. status: "running",
  47. usage: {
  48. spentTokens: 12_345,
  49. nodesObserved: 7,
  50. nodesRunning: 2,
  51. nodesCompleted: 4,
  52. nodesFailed: 1,
  53. },
  54. actors: [
  55. { siteId: "agent#1", ordinal: 1, name: "scout" },
  56. { siteId: "agent#2", ordinal: 2 },
  57. ],
  58. logTail: [
  59. { sequence: 1, message: "started" },
  60. { sequence: 2, message: "fan-out complete" },
  61. ],
  62. };
  63. // ── 情势截面(spec: docs/dynamic-workflow/launch.md「`GetWorkflowRun`」「Their cards」)──
  64. //
  65. // 所有年龄都对快照时刻 `generatedAt` 算,所以这些常量写成「相对 G 的偏移」而不是绝对时刻:
  66. // 测试不需要 fake timers,卡上的读数也不该随运行时刻变化。
  67. const G = 1_800_000_000_000;
  68. const GET_RUN_SITUATION_DISPLAY = {
  69. kind: "get_workflow_run",
  70. runId: "wf_situation",
  71. label: "nightly-sync",
  72. status: "running",
  73. summary:
  74. "Running for 15m 00s, in phase 2 of 3 (judge), 5 steps settled, 2 running (1 executing, 1 parked), last progress 40s ago.",
  75. generatedAt: G,
  76. usage: {
  77. spentTokens: 12_345,
  78. nodesObserved: 7,
  79. nodesRunning: 2,
  80. nodesCompleted: 4,
  81. nodesFailed: 1,
  82. },
  83. phases: [
  84. {
  85. name: "collect",
  86. state: "done",
  87. rounds: 1,
  88. nodesSettled: 3,
  89. nodesRunning: 0,
  90. enteredAt: G - 900_000,
  91. exitedAt: G - 600_000,
  92. },
  93. {
  94. name: "judge",
  95. state: "current",
  96. rounds: 2,
  97. nodesSettled: 2,
  98. nodesRunning: 2,
  99. enteredAt: G - 600_000,
  100. },
  101. { name: "report", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  102. ],
  103. subagents: [
  104. {
  105. siteId: "agent#1",
  106. ordinal: 1,
  107. name: "scout",
  108. state: "executing",
  109. phaseName: "judge",
  110. instructionsHead: "Check the release notes for regressions",
  111. startedAt: G - 310_000,
  112. turn: 3,
  113. toolCalls: 7,
  114. lastTool: { name: "Bash", target: "pnpm test", at: G - 20_000 },
  115. stepsSettled: 2,
  116. stepsFailed: 0,
  117. tokens: 4_200,
  118. },
  119. {
  120. siteId: "agent#2",
  121. ordinal: 2,
  122. state: "parked",
  123. phaseName: "judge",
  124. parkedOn: "q_7",
  125. stepsSettled: 1,
  126. stepsFailed: 0,
  127. tokens: 900,
  128. },
  129. {
  130. siteId: "agent#3",
  131. ordinal: 3,
  132. name: "drafter",
  133. state: "waiting",
  134. phaseName: "judge",
  135. waitCause: "backoff",
  136. retryAfterMs: 45_000,
  137. waitSince: G - 65_000,
  138. stepsSettled: 0,
  139. stepsFailed: 0,
  140. tokens: 0,
  141. },
  142. ],
  143. health: {
  144. lastProgressAt: G - 40_000,
  145. concurrency: { effective: 2, cap: 4, reason: "rate_limited", since: G - 130_000 },
  146. consecutiveFailures: 2,
  147. cachedSteps: 3,
  148. pendingQuestionsKnown: true,
  149. },
  150. actors: [],
  151. logTail: [{ sequence: 9, message: "fan-out complete", at: G - 95_000 }],
  152. };
  153. const GET_RUN_COMPLETED_SITUATION_DISPLAY = {
  154. ...GET_RUN_SITUATION_DISPLAY,
  155. runId: "wf_done",
  156. status: "completed",
  157. summary: "Completed 3m 20s ago across 2 phases, 6 steps settled, deliverable: Release report.",
  158. result: "all checks passed",
  159. phases: [
  160. {
  161. name: "collect",
  162. state: "done",
  163. rounds: 1,
  164. nodesSettled: 3,
  165. nodesRunning: 0,
  166. enteredAt: G - 900_000,
  167. exitedAt: G - 600_000,
  168. },
  169. {
  170. name: "judge",
  171. state: "done",
  172. rounds: 1,
  173. nodesSettled: 3,
  174. nodesRunning: 0,
  175. enteredAt: G - 600_000,
  176. exitedAt: G - 200_000,
  177. },
  178. ],
  179. subagents: [
  180. {
  181. siteId: "agent#1",
  182. ordinal: 1,
  183. name: "scout",
  184. state: "done",
  185. phaseName: "judge",
  186. stepsSettled: 6,
  187. stepsFailed: 1,
  188. tokens: 8_800,
  189. },
  190. ],
  191. health: {
  192. lastProgressAt: G - 200_000,
  193. consecutiveFailures: 0,
  194. cachedSteps: 0,
  195. pendingQuestionsKnown: true,
  196. },
  197. logTail: [],
  198. };
  199. const GET_RUN_INTERRUPTED_SITUATION_DISPLAY = {
  200. kind: "get_workflow_run",
  201. runId: "wf_interrupted",
  202. label: "nightly-sync",
  203. status: "stopped",
  204. stopReason: "interrupted",
  205. summary: "Stopped 2h 15m ago in phase judge, 1 step settled, 1 still marked running.",
  206. generatedAt: G,
  207. usage: {
  208. spentTokens: 3_000,
  209. nodesObserved: 2,
  210. nodesRunning: 1,
  211. nodesCompleted: 1,
  212. nodesFailed: 0,
  213. },
  214. phases: [
  215. {
  216. name: "judge",
  217. state: "unfinished",
  218. rounds: 1,
  219. nodesSettled: 1,
  220. nodesRunning: 1,
  221. enteredAt: G - 8_100_000,
  222. },
  223. ],
  224. subagents: [
  225. {
  226. siteId: "agent#1",
  227. ordinal: 1,
  228. name: "scout",
  229. state: "unfinished",
  230. phaseName: "judge",
  231. startedAt: G - 8_000_000,
  232. turn: 2,
  233. stepsSettled: 1,
  234. stepsFailed: 1,
  235. tokens: 1_500,
  236. },
  237. ],
  238. health: {
  239. lastProgressAt: G - 8_000_000,
  240. consecutiveFailures: 0,
  241. cachedSteps: 0,
  242. leftoverRunning: 1,
  243. pendingQuestionsKnown: true,
  244. },
  245. actors: [],
  246. logTail: [],
  247. truncated: true,
  248. };
  249. /** 这个会话不持有的活 run:停驻的问题只活在提问进程里,卡必须把「看不见」说出口。 */
  250. const GET_RUN_UNKNOWN_QUESTIONS_DISPLAY = {
  251. kind: "get_workflow_run",
  252. runId: "wf_foreign",
  253. label: "nightly-sync",
  254. status: "running",
  255. possiblyInterrupted: true,
  256. summary: "Running, 0 steps settled, pending questions unknown to this session.",
  257. generatedAt: G,
  258. usage: {
  259. spentTokens: 0,
  260. nodesObserved: 0,
  261. nodesRunning: 0,
  262. nodesCompleted: 0,
  263. nodesFailed: 0,
  264. },
  265. subagents: [],
  266. health: {
  267. consecutiveFailures: 0,
  268. cachedSteps: 0,
  269. pendingQuestionsKnown: false,
  270. },
  271. actors: [],
  272. logTail: [],
  273. };
  274. const LIST_RUNS_DISPLAY = {
  275. kind: "list_workflow_runs",
  276. runs: [
  277. {
  278. runId: "wf_a",
  279. label: "alpha",
  280. labelSource: "name",
  281. status: "completed",
  282. ownedByThisSession: true,
  283. createdAt: 1,
  284. updatedAt: 2,
  285. spentTokens: 10,
  286. },
  287. {
  288. runId: "wf_b",
  289. label: "// derive",
  290. labelSource: "script",
  291. status: "stopped",
  292. ownedByThisSession: false,
  293. possiblyInterrupted: true,
  294. createdAt: 3,
  295. updatedAt: 4,
  296. spentTokens: 20,
  297. },
  298. ],
  299. truncated: true,
  300. };
  301. const SNIPPET_DISPLAY = {
  302. kind: "eval_workflow_snippet",
  303. ok: false,
  304. diagnostics: [
  305. { code: 2322, column: 10, line: 3, message: "Type 'string' is not assignable to 'number'." },
  306. ],
  307. logs: ["glob matched 3 files"],
  308. response: "3",
  309. durationMs: 1_250,
  310. };
  311. function buildContext(
  312. toolCall: Record<string, unknown>,
  313. overrides: Partial<ToolCallBlockRenderContext> = {},
  314. ): ToolCallBlockRenderContext {
  315. return {
  316. toolCallNode: { toolCall, childToolCalls: [] },
  317. workspacePath: "/workspace",
  318. displayModel: {
  319. inlinePreview: { type: "none" },
  320. planResult: null,
  321. viewerSource: null,
  322. viewerLabelId: "codeViewer.viewCode",
  323. showSummaryFileLink: false,
  324. showInput: false,
  325. showOutput: false,
  326. showKind: false,
  327. },
  328. viewerSource: null,
  329. rawFileSummaries: [],
  330. isRunning: false,
  331. statusLabel: "",
  332. childToolList: null,
  333. showIcon: true,
  334. forceOpen: true,
  335. canToggle: false,
  336. ...overrides,
  337. } as ToolCallBlockRenderContext;
  338. }
  339. function renderCard(
  340. component: (context: ToolCallBlockRenderContext) => unknown,
  341. context: ToolCallBlockRenderContext,
  342. locale: "en-US" | "zh-CN" = "en-US",
  343. ) {
  344. return render(
  345. createElement(
  346. ZCodeIntlProvider,
  347. { initialLocale: locale },
  348. createElement(component as never, context),
  349. ),
  350. );
  351. }
  352. function buildToolCall(overrides: Record<string, unknown> = {}) {
  353. return {
  354. toolId: "tool-obs-1",
  355. status: "completed",
  356. input: {},
  357. ...overrides,
  358. };
  359. }
  360. afterEach(cleanup);
  361. describe("resolveToolCallRenderer observation dispatch", () => {
  362. it("routes the three observation tools by name, ahead of any family fallback", () => {
  363. for (const [toolName, expected] of [
  364. ["GetWorkflowRun", GetWorkflowRunToolCallBlock],
  365. ["ListWorkflowRuns", ListWorkflowRunsToolCallBlock],
  366. ["EvalWorkflowSnippet", EvalWorkflowSnippetToolCallBlock],
  367. ["ResumeWorkflowRun", ResumeWorkflowRunToolCallBlock],
  368. ] as const) {
  369. const renderer = resolveToolCallRenderer(
  370. buildContext(buildToolCall({ toolName, kind: toolName, title: toolName })),
  371. );
  372. expect(renderer).toBe(expected);
  373. }
  374. });
  375. it("matches snake_case wire spellings too", () => {
  376. for (const [toolName, expected] of [
  377. ["get_workflow_run", GetWorkflowRunToolCallBlock],
  378. ["list_workflow_runs", ListWorkflowRunsToolCallBlock],
  379. ["eval_workflow_snippet", EvalWorkflowSnippetToolCallBlock],
  380. ["resume_workflow_run", ResumeWorkflowRunToolCallBlock],
  381. ] as const) {
  382. const renderer = resolveToolCallRenderer(
  383. buildContext(buildToolCall({ toolName, kind: toolName, title: toolName })),
  384. );
  385. expect(renderer).toBe(expected);
  386. }
  387. });
  388. });
  389. describe("GetWorkflowRunToolCallBlock", () => {
  390. it("renders the structured card from display payload", () => {
  391. const context = buildContext(
  392. buildToolCall({
  393. toolId: "tool-get-run",
  394. toolName: "GetWorkflowRun",
  395. kind: "GetWorkflowRun",
  396. title: "GetWorkflowRun",
  397. input: { run_id: "wf_demo" },
  398. raw: { display: GET_RUN_DISPLAY },
  399. }),
  400. );
  401. renderCard(GetWorkflowRunToolCallBlock, context);
  402. // 折叠行:kindLabel + label + 步数(settled 5 = completed 4 + failed 1,observed 7)+ 状态词。
  403. expect(screen.getAllByText("Workflow status").length).toBeGreaterThan(0);
  404. expect(screen.getAllByText("nightly-sync").length).toBeGreaterThan(0);
  405. expect(screen.getAllByText("5/7 steps").length).toBeGreaterThan(0);
  406. expect(screen.getAllByText("Running").length).toBeGreaterThan(0);
  407. // 展开卡体:用量(只有已花 token,没有上限)/ Actors / 日志。
  408. expect(screen.queryByText("Usage")).toBeNull();
  409. expect(screen.getByText("12.3k tokens")).toBeTruthy();
  410. expect(screen.getByText("2 running nodes")).toBeTruthy();
  411. expect(screen.queryByText("scout")).toBeNull();
  412. // 日志面板把多条 join 成一个 <pre>,用子串匹配。
  413. expect(screen.getByText(/fan-out complete/)).toBeTruthy();
  414. });
  415. it("renders the completed run result as prose", () => {
  416. const context = buildContext(
  417. buildToolCall({
  418. toolName: "GetWorkflowRun",
  419. kind: "GetWorkflowRun",
  420. title: "GetWorkflowRun",
  421. raw: {
  422. display: {
  423. ...GET_RUN_DISPLAY,
  424. status: "completed",
  425. result: "all checks passed",
  426. },
  427. },
  428. }),
  429. );
  430. renderCard(GetWorkflowRunToolCallBlock, context);
  431. expect(screen.getByText("all checks passed")).toBeTruthy();
  432. expect(screen.queryByText("Result")).toBeNull();
  433. });
  434. it("查询中即使带旧 display 也不展开", () => {
  435. renderCard(
  436. GetWorkflowRunToolCallBlock,
  437. buildContext(buildToolCall({ raw: { display: GET_RUN_DISPLAY } }), { isRunning: true }),
  438. );
  439. expect(screen.queryByTestId("workflow-status-body")).toBeNull();
  440. });
  441. it("查询失败只显示查询错误,不显示旧 run 数据", () => {
  442. renderCard(
  443. GetWorkflowRunToolCallBlock,
  444. buildContext(buildToolCall({ status: "failed", raw: { display: GET_RUN_DISPLAY } }), {
  445. errorText: "lookup denied",
  446. }),
  447. );
  448. expect(screen.getByText("lookup denied")).toBeTruthy();
  449. expect(screen.queryByText(/fan-out complete/)).toBeNull();
  450. });
  451. it("run 失败保持查询成功样式且优先显示错误", () => {
  452. renderCard(
  453. GetWorkflowRunToolCallBlock,
  454. buildContext(
  455. buildToolCall({
  456. raw: {
  457. display: {
  458. ...GET_RUN_DISPLAY,
  459. status: "errored",
  460. error: { code: "RUN_ERROR", message: "actor failed" },
  461. },
  462. },
  463. }),
  464. ),
  465. );
  466. expect(screen.getByTestId("workflow-status-body").textContent).toMatch(
  467. /^RUN_ERROR: actor failed/,
  468. );
  469. expect(screen.queryByText("Usage")).toBeNull();
  470. });
  471. it("falls back to the text projection without display — never a raw JSON dump", () => {
  472. const toolCall = buildToolCall({
  473. toolName: "GetWorkflowRun",
  474. kind: "GetWorkflowRun",
  475. title: "GetWorkflowRun",
  476. output: "<run_id>wf_demo</run_id><status>running</status>",
  477. });
  478. renderCard(GetWorkflowRunToolCallBlock, buildContext(toolCall));
  479. expect(screen.getAllByText(/wf_demo/).length).toBeGreaterThan(0);
  480. // raw JSON dump 兜底卡会把整个 toolCall stringify 进 DOM——这里必须不存在。
  481. expect(screen.queryByText(/"toolId"/)).toBeNull();
  482. });
  483. it("shows the fetching kind label while running (zh + en)", () => {
  484. for (const [locale, expected] of [
  485. ["zh-CN", "正在获取工作流状态"],
  486. ["en-US", "Checking workflow status"],
  487. ] as const) {
  488. cleanup();
  489. renderCard(
  490. GetWorkflowRunToolCallBlock,
  491. buildContext(
  492. buildToolCall({
  493. toolName: "GetWorkflowRun",
  494. kind: "GetWorkflowRun",
  495. title: "GetWorkflowRun",
  496. input: { run_id: "wf_demo" },
  497. }),
  498. { isRunning: true, forceOpen: false },
  499. ),
  500. locale,
  501. );
  502. expect(screen.getAllByText(expected).length).toBeGreaterThan(0);
  503. }
  504. });
  505. });
  506. // 情势截面上卡(spec: docs/dynamic-workflow/launch.md「`GetWorkflowRun`」「Their cards」):
  507. // 摘要句 / 阶段轨 / 花名册 / 健康行 / 日志年龄,以及两处「把不知道说出口」。
  508. describe("GetWorkflowRunToolCallBlock situation report", () => {
  509. function renderRun(display: Record<string, unknown>, locale: "en-US" | "zh-CN" = "en-US") {
  510. renderCard(
  511. GetWorkflowRunToolCallBlock,
  512. buildContext(
  513. buildToolCall({
  514. toolId: "tool-situation",
  515. toolName: "GetWorkflowRun",
  516. kind: "GetWorkflowRun",
  517. title: "GetWorkflowRun",
  518. raw: { display },
  519. }),
  520. ),
  521. locale,
  522. );
  523. }
  524. it("running: summary on both the collapsed line and the body", () => {
  525. renderRun(GET_RUN_SITUATION_DISPLAY);
  526. expect(screen.getByTestId("workflow-run-summary-line").textContent).toBe(
  527. GET_RUN_SITUATION_DISPLAY.summary,
  528. );
  529. expect(screen.getByTestId("workflow-run-summary").textContent).toBe(
  530. GET_RUN_SITUATION_DISPLAY.summary,
  531. );
  532. // 有摘要就让它占住折叠行,步数让位(步数仍在展开的用量行里)。
  533. expect(screen.getAllByText("5/7 steps").length).toBe(1);
  534. });
  535. it("running: phase rows carry state word, rounds, counts and duration", () => {
  536. renderRun(GET_RUN_SITUATION_DISPLAY);
  537. const phases = screen.getByTestId("workflow-run-phases");
  538. expect(phases.textContent).toContain("1.collectdone");
  539. expect(phases.textContent).toContain("1 round");
  540. expect(phases.textContent).toContain("3 settled");
  541. // 已离开的阶段写实际时长;当前阶段写「到现在为止」,两者都对 generatedAt 算。
  542. expect(phases.textContent).toContain("5m 00s");
  543. expect(phases.textContent).toContain("2.judgecurrent");
  544. expect(phases.textContent).toContain("2 rounds");
  545. expect(phases.textContent).toContain("2 running");
  546. expect(phases.textContent).toContain("10m 00s so far");
  547. // `ahead` 的行只有序号、名字和状态词:它还没发生过,没有 0 可写。
  548. expect(phases.textContent).toContain("3.reportahead");
  549. expect(phases.textContent).not.toContain("0 settled");
  550. });
  551. it("running: roster rows mirror the model text per state", () => {
  552. renderRun(GET_RUN_SITUATION_DISPLAY);
  553. const roster = screen.getByTestId("workflow-run-subagents");
  554. // 在跑的行:地址、相位词、阶段、这一步的年龄、轮次、工具调用数、最后一个工具及其年龄、token。
  555. expect(roster.textContent).toContain("scout");
  556. expect(roster.textContent).toContain("agent#1@1");
  557. expect(roster.textContent).toContain("executing");
  558. expect(roster.textContent).toContain("phase judge");
  559. expect(roster.textContent).toContain("5m 10s on this step");
  560. expect(roster.textContent).toContain("turn 3");
  561. expect(roster.textContent).toContain("7 tool calls");
  562. expect(roster.textContent).toContain("last Bash pnpm test 20s ago");
  563. expect(roster.textContent).toContain("4.2k tokens");
  564. // 缩进的任务行:作者自己写的指令头。
  565. expect(screen.getByText("task: Check the release notes for regressions")).toBeTruthy();
  566. // 停驻的行:只有问题 id,没有等待时长(卡面载荷不带提问时刻,绝不编一个)。
  567. expect(roster.textContent).toContain("agent#2@2");
  568. expect(roster.textContent).toContain("parked");
  569. expect(roster.textContent).toContain("on question q_7");
  570. // 退避的行:等了多久贴着原因,还要等多久收尾。
  571. expect(roster.textContent).toContain("drafter");
  572. expect(roster.textContent).toContain("in backoff");
  573. expect(roster.textContent).toContain("for 1m 05s");
  574. expect(roster.textContent).toContain("retry in 45s");
  575. // token 为 0 的行不写「0 tokens」(前置的 \D 是为了不把 "900 tokens" 误当命中)。
  576. expect(roster.textContent).not.toMatch(/(?:^|\D)0 tokens/u);
  577. });
  578. it("running: health readings and log ages are relative to generatedAt", () => {
  579. renderRun(GET_RUN_SITUATION_DISPLAY);
  580. const health = screen.getByTestId("workflow-run-health");
  581. expect(health.textContent).toContain("last progress 40s ago");
  582. expect(health.textContent).toContain("concurrency 2/4");
  583. expect(health.textContent).toContain("rate limited");
  584. expect(health.textContent).toContain("since 2m 10s ago");
  585. expect(health.textContent).toContain("not stalled");
  586. expect(health.textContent).toContain("2 consecutive failures");
  587. expect(health.textContent).toContain("3 cached steps");
  588. expect(screen.queryByTestId("workflow-run-leftover")).toBeNull();
  589. // 日志行按 journal 时刻前缀年龄(同一把尺,同一个基准)。
  590. expect(screen.getByText(/1m 35s ago\s+fan-out complete/u)).toBeTruthy();
  591. });
  592. it("running: zh-CN uses the run pane vocabulary", () => {
  593. renderRun(GET_RUN_SITUATION_DISPLAY, "zh-CN");
  594. const roster = screen.getByTestId("workflow-run-subagents");
  595. expect(roster.textContent).toContain("执行中");
  596. expect(roster.textContent).toContain("停驻");
  597. expect(roster.textContent).toContain("退避中");
  598. expect(roster.textContent).toContain("已等 1m 05s");
  599. expect(roster.textContent).toContain("45s 后重试");
  600. expect(screen.getByTestId("workflow-run-health").textContent).toContain("最近进展 40s 前");
  601. expect(screen.getByTestId("workflow-run-phases").textContent).toContain("进行中");
  602. });
  603. it("completed: result stays first, phases and roster still render", () => {
  604. renderRun(GET_RUN_COMPLETED_SITUATION_DISPLAY);
  605. const body = screen.getByTestId("workflow-status-body");
  606. // 摘要是导语,结果紧跟其后(终态卡先给结果,这是原有行为)。
  607. expect(body.textContent?.startsWith(GET_RUN_COMPLETED_SITUATION_DISPLAY.summary)).toBe(true);
  608. expect(screen.getByText("all checks passed")).toBeTruthy();
  609. expect(screen.getByTestId("workflow-run-phases").textContent).toContain("2.judgedone");
  610. const roster = screen.getByTestId("workflow-run-subagents");
  611. expect(roster.textContent).toContain("6 steps");
  612. expect(roster.textContent).toContain("1 failed");
  613. // 终态 run 不说 stalled,健康行也不写为 0 的读数。
  614. const health = screen.getByTestId("workflow-run-health");
  615. expect(health.textContent).not.toContain("stalled");
  616. expect(health.textContent).not.toContain("0 cached steps");
  617. });
  618. it("interrupted: leftover note, unfinished wording and the truncated footnote", () => {
  619. renderRun(GET_RUN_INTERRUPTED_SITUATION_DISPLAY);
  620. expect(screen.getByTestId("workflow-run-leftover").textContent).toBe(
  621. "The step below marked running is a leftover of the exited process, not live work.",
  622. );
  623. const phases = screen.getByTestId("workflow-run-phases");
  624. // 终态 run 里的「还在跑」是没结算,不是在动;也不写「到现在为止」的时长。
  625. expect(phases.textContent).toContain("1 unfinished");
  626. expect(phases.textContent).not.toContain("so far");
  627. const roster = screen.getByTestId("workflow-run-subagents");
  628. expect(roster.textContent).toContain("unfinished");
  629. expect(roster.textContent).toContain("was in flight at the stop");
  630. expect(screen.getByText("Some rows were left off this card.")).toBeTruthy();
  631. });
  632. it("says out loud that this session cannot see the pending questions", () => {
  633. renderRun(GET_RUN_UNKNOWN_QUESTIONS_DISPLAY);
  634. expect(screen.getByTestId("workflow-run-questions-unknown").textContent).toContain(
  635. "cannot see this run's pending questions",
  636. );
  637. // 空花名册什么也不画;没有阶段就没有阶段轨。
  638. expect(screen.queryByTestId("workflow-run-subagents")).toBeNull();
  639. expect(screen.queryByTestId("workflow-run-phases")).toBeNull();
  640. });
  641. it("renders a pre-situation payload exactly as before", () => {
  642. renderRun(GET_RUN_DISPLAY);
  643. // 情势五件缺席 → 折叠行回到步数,卡体没有摘要 / 阶段轨 / 花名册 / 健康行。
  644. expect(screen.getAllByText("5/7 steps").length).toBeGreaterThan(0);
  645. expect(screen.queryByTestId("workflow-run-summary-line")).toBeNull();
  646. expect(screen.queryByTestId("workflow-run-summary")).toBeNull();
  647. expect(screen.queryByTestId("workflow-run-phases")).toBeNull();
  648. expect(screen.queryByTestId("workflow-run-subagents")).toBeNull();
  649. expect(screen.queryByTestId("workflow-run-health")).toBeNull();
  650. // 没有 journal 时刻的日志行不带年龄前缀:日志面板逐字还是那两行。
  651. expect(screen.getByTestId("workflow-status-body").querySelector("pre")?.textContent).toBe(
  652. "started\nfan-out complete",
  653. );
  654. });
  655. });
  656. describe("ListWorkflowRunsToolCallBlock", () => {
  657. it("renders rows with status word, session tag, interrupted hint and truncated footnote", () => {
  658. const context = buildContext(
  659. buildToolCall({
  660. toolName: "ListWorkflowRuns",
  661. kind: "ListWorkflowRuns",
  662. title: "ListWorkflowRuns",
  663. raw: { display: LIST_RUNS_DISPLAY },
  664. }),
  665. );
  666. renderCard(ListWorkflowRunsToolCallBlock, context);
  667. expect(screen.getAllByText("2 runs").length).toBeGreaterThan(0);
  668. expect(screen.getAllByText("alpha").length).toBeGreaterThan(0);
  669. expect(screen.getAllByText("Completed").length).toBeGreaterThan(0);
  670. expect(screen.getAllByText("Stopped").length).toBeGreaterThan(0);
  671. expect(screen.getByText("this session")).toBeTruthy();
  672. expect(screen.getByText("possibly interrupted")).toBeTruthy();
  673. expect(screen.getByText("Showing the most recent runs only")).toBeTruthy();
  674. });
  675. it("renders the empty state from an empty display list", () => {
  676. const context = buildContext(
  677. buildToolCall({
  678. toolName: "ListWorkflowRuns",
  679. kind: "ListWorkflowRuns",
  680. title: "ListWorkflowRuns",
  681. raw: { display: { kind: "list_workflow_runs", runs: [] } },
  682. }),
  683. { forceOpen: true },
  684. );
  685. renderCard(ListWorkflowRunsToolCallBlock, context);
  686. expect(screen.getAllByText("No workflow runs yet").length).toBeGreaterThan(0);
  687. });
  688. });
  689. describe("EvalWorkflowSnippetToolCallBlock", () => {
  690. it("完成展开只显示返回值,没有标题、日志或代码", () => {
  691. renderCard(
  692. EvalWorkflowSnippetToolCallBlock,
  693. buildContext(
  694. buildToolCall({
  695. input: { code: "return 7;" },
  696. raw: { display: { ...SNIPPET_DISPLAY, ok: true, diagnostics: [], response: "7" } },
  697. }),
  698. ),
  699. );
  700. const body = screen.getByTestId("workflow-snippet-body");
  701. expect(body.textContent).toBe("7");
  702. expect(body.querySelector("pre")?.className).toContain("max-h-80");
  703. expect(body.querySelector("pre")?.getAttribute("data-language")).toBe("json");
  704. expect(body.querySelector("h4, summary")).toBeNull();
  705. expect(screen.queryByTestId("snippet-logs")).toBeNull();
  706. expect(screen.queryByTestId("snippet-code")).toBeNull();
  707. });
  708. it("完成无返回值时,即使有代码和日志也没有展开入口", () => {
  709. renderCard(
  710. EvalWorkflowSnippetToolCallBlock,
  711. buildContext(
  712. buildToolCall({
  713. input: { code: "return;" },
  714. raw: {
  715. display: {
  716. ...SNIPPET_DISPLAY,
  717. ok: true,
  718. diagnostics: [],
  719. logs: [],
  720. response: "The snippet completed in 1250ms.\nIt returned no value.",
  721. },
  722. },
  723. }),
  724. { forceOpen: false },
  725. ),
  726. );
  727. expect(screen.queryByTestId("workflow-snippet-body")).toBeNull();
  728. expect(document.querySelector("[aria-expanded]")).toBeNull();
  729. });
  730. it("进行中计时递增且无结果占位;终态使用固定耗时", () => {
  731. vi.useFakeTimers();
  732. vi.setSystemTime(1000);
  733. try {
  734. renderCard(
  735. EvalWorkflowSnippetToolCallBlock,
  736. buildContext(buildToolCall({ startedAt: 1000, input: { code: "return 1;" } }), {
  737. isRunning: true,
  738. }),
  739. );
  740. // 进行中按整秒走、每秒一格(修订 2026-09-12:与面板里其他计时同一粒度,毫秒尾数肉眼读不了,
  741. // 而 100ms 一次 setState 是聊天区里最频繁的待处理更新——嵌套更新计数的种子)。
  742. expect(screen.getByText("0s")).toBeTruthy();
  743. act(() => vi.advanceTimersByTime(300));
  744. expect(screen.getByText("0s")).toBeTruthy();
  745. expect(screen.queryByText(/\dms$/)).toBeNull();
  746. act(() => vi.advanceTimersByTime(700));
  747. expect(screen.getByText("1s")).toBeTruthy();
  748. act(() => vi.advanceTimersByTime(1000));
  749. expect(screen.getByText("2s")).toBeTruthy();
  750. expect(screen.queryByTestId("snippet-result")).toBeNull();
  751. expect(screen.queryByTestId("snippet-logs")).toBeNull();
  752. expect(screen.getByTestId("workflow-snippet-body").textContent).toBe("return 1;");
  753. cleanup();
  754. renderCard(
  755. EvalWorkflowSnippetToolCallBlock,
  756. buildContext(
  757. buildToolCall({
  758. raw: {
  759. display: {
  760. ...SNIPPET_DISPLAY,
  761. ok: true,
  762. diagnostics: [],
  763. logs: [],
  764. response: "1",
  765. durationMs: 427,
  766. },
  767. },
  768. }),
  769. ),
  770. );
  771. // 终态定格在工具结果的精确毫秒。
  772. act(() => vi.advanceTimersByTime(1000));
  773. expect(screen.getByText("427ms")).toBeTruthy();
  774. expect(screen.queryByText("1427ms")).toBeNull();
  775. expect(screen.queryByText(/^\ds$/)).toBeNull();
  776. } finally {
  777. cleanup();
  778. vi.useRealTimers();
  779. }
  780. });
  781. it("renders code, shared diagnostics, logs and response from display", () => {
  782. const context = buildContext(
  783. buildToolCall({
  784. toolName: "EvalWorkflowSnippet",
  785. kind: "EvalWorkflowSnippet",
  786. title: "EvalWorkflowSnippet",
  787. input: { code: 'const n = (await files.glob("*.ts")).length; return n;' },
  788. raw: { display: SNIPPET_DISPLAY },
  789. }),
  790. );
  791. renderCard(EvalWorkflowSnippetToolCallBlock, context);
  792. // 诊断走共享的编译反馈卡(与 CreateWorkflow 同一形状,docs/dynamic-workflow/presentation.md「Compiler feedback」)。
  793. expect(screen.getByText("Compiler feedback")).toBeTruthy();
  794. expect(screen.getByText("L3:C10")).toBeTruthy();
  795. expect(screen.getByText(/Type 'string' is not assignable/)).toBeTruthy();
  796. // 代码 / 日志 / 返回值分区。
  797. fireEvent.click(screen.getByText("Code"));
  798. expect(screen.getAllByText(/files\.glob/).length).toBeGreaterThan(0);
  799. expect(screen.getByText("glob matched 3 files")).toBeTruthy();
  800. expect(screen.queryByText("Return value")).toBeNull();
  801. // 折叠行:时长(1_250ms → "1.3s",toFixed(1) 四舍五入)与 response 预览。
  802. expect(screen.queryByText("1250ms")).toBeNull();
  803. });
  804. it("keeps the completed summary free of PASS and result preview", () => {
  805. const context = buildContext(
  806. buildToolCall({
  807. toolName: "EvalWorkflowSnippet",
  808. kind: "EvalWorkflowSnippet",
  809. title: "EvalWorkflowSnippet",
  810. input: { code: "return 1;" },
  811. raw: {
  812. display: { ...SNIPPET_DISPLAY, ok: true, diagnostics: [], response: "1" },
  813. },
  814. }),
  815. { forceOpen: false },
  816. );
  817. renderCard(EvalWorkflowSnippetToolCallBlock, context);
  818. expect(screen.queryByText("PASS")).toBeNull();
  819. expect(screen.getByText("1250ms")).toBeTruthy();
  820. expect(screen.queryByText("1")).toBeNull();
  821. });
  822. it("falls back to response text without display", () => {
  823. const context = buildContext(
  824. buildToolCall({
  825. toolName: "EvalWorkflowSnippet",
  826. kind: "EvalWorkflowSnippet",
  827. title: "EvalWorkflowSnippet",
  828. input: { code: "return 1;" },
  829. output: "The snippet returned 1.",
  830. }),
  831. );
  832. renderCard(EvalWorkflowSnippetToolCallBlock, context);
  833. expect(screen.getAllByText("The snippet returned 1.").length).toBeGreaterThan(0);
  834. expect(screen.queryByText(/"toolId"/)).toBeNull();
  835. });
  836. });
  837. describe("observation card i18n key parity", () => {
  838. const PREFIXES = [
  839. "chat.toolCall.workflow.getRun.",
  840. "chat.toolCall.workflow.listRuns.",
  841. "chat.toolCall.workflow.snippet.",
  842. ] as const;
  843. it("zh-CN and en-US define identical key sets for the new namespaces", () => {
  844. for (const prefix of PREFIXES) {
  845. const zhKeys = Object.keys(zhCN)
  846. .filter((key) => key.startsWith(prefix))
  847. .sort();
  848. const enKeys = Object.keys(enUS)
  849. .filter((key) => key.startsWith(prefix))
  850. .sort();
  851. expect(zhKeys.length).toBeGreaterThan(0);
  852. expect(enKeys).toEqual(zhKeys);
  853. }
  854. });
  855. });
  856. // spec:docs/dynamic-workflow/presentation.md「The run card」。
  857. // 恢复卡三件事:display 驱动(runId + 状态点词 + 本地化说明)、双语、无 display 文本兜底。
  858. const RESUME_DISPLAY = {
  859. kind: "resume_workflow_run",
  860. runId: "dwfrun_resumed",
  861. } as const;
  862. function buildResumeToolCall(overrides: Record<string, unknown> = {}) {
  863. return buildToolCall({
  864. toolId: "tool-resume-run",
  865. toolName: "ResumeWorkflowRun",
  866. raw: { display: RESUME_DISPLAY },
  867. ...overrides,
  868. });
  869. }
  870. describe("ResumeWorkflowRunToolCallBlock", () => {
  871. it("renders the structured resume card from display payload", () => {
  872. renderCard(ResumeWorkflowRunToolCallBlock, buildContext(buildResumeToolCall()));
  873. expect(screen.getByText("Workflow run resumed")).toBeTruthy();
  874. expect(screen.getByText("dwfrun_resumed")).toBeTruthy();
  875. expect(screen.getByText("Running in background")).toBeTruthy();
  876. // 展开说明在场(replay / 重新派发 / 完成通知)。
  877. expect(screen.getByText(/replayed from the journal/u)).toBeTruthy();
  878. });
  879. it("renders the zh-CN card", () => {
  880. renderCard(ResumeWorkflowRunToolCallBlock, buildContext(buildResumeToolCall()), "zh-CN");
  881. expect(screen.getByText("工作流实例已恢复")).toBeTruthy();
  882. expect(screen.getByText("后台运行中")).toBeTruthy();
  883. expect(screen.getByText(/从 journal 重放/u)).toBeTruthy();
  884. });
  885. it("falls back to bounded text output when display is absent", () => {
  886. renderCard(
  887. ResumeWorkflowRunToolCallBlock,
  888. buildContext(
  889. buildResumeToolCall({
  890. raw: undefined,
  891. output: "The workflow run dwfrun_resumed has been resumed.",
  892. }),
  893. ),
  894. );
  895. expect(screen.getByText(/has been resumed/u)).toBeTruthy();
  896. // 文本兜底不是 JSON dump。
  897. expect(screen.queryByText(/\{"/u)).toBeNull();
  898. });
  899. });
  900. // run 态紧凑可点卡(spec「ResumeWorkflowRun 工具卡 display」二轮):联接命中后复用
  901. // CreateWorkflow 的紧凑卡(WorkflowRunCompactCard),标签换「已恢复」,整卡点击打开侧栏。
  902. describe("ResumeWorkflowRunToolCallBlock run-state compact card", () => {
  903. const RESUME_RUN_SUMMARY = {
  904. runId: "dwfrun_resumed",
  905. status: "running" as const,
  906. nodesSettled: 2,
  907. nodesTotal: 5,
  908. };
  909. it("renders the shared compact card with resumed wording and live status", () => {
  910. const onOpenWorkflowRun = vi.fn();
  911. renderCard(
  912. ResumeWorkflowRunToolCallBlock,
  913. buildContext(buildResumeToolCall(), {
  914. workflowRun: RESUME_RUN_SUMMARY,
  915. onOpenWorkflowRun,
  916. }),
  917. );
  918. const card = screen.getByTestId("workflow-run-card");
  919. expect(card).toBeTruthy();
  920. expect(card.getAttribute("data-workflow-run-id")).toBe("dwfrun_resumed");
  921. // 标签是「已恢复」而不是 create 卡的「已启动」;runId 与实时状态/步数在场。
  922. expect(screen.getByText("Workflow run resumed")).toBeTruthy();
  923. expect(screen.getByText("dwfrun_resumed")).toBeTruthy();
  924. expect(screen.getByText("Running")).toBeTruthy();
  925. expect(screen.getByText("2/5 steps")).toBeTruthy();
  926. });
  927. it("opens the side panel run view when the card is clicked", () => {
  928. const onOpenWorkflowRun = vi.fn();
  929. renderCard(
  930. ResumeWorkflowRunToolCallBlock,
  931. buildContext(buildResumeToolCall(), {
  932. workflowRun: RESUME_RUN_SUMMARY,
  933. onOpenWorkflowRun,
  934. }),
  935. );
  936. fireEvent.click(screen.getByTestId("workflow-run-card"));
  937. expect(onOpenWorkflowRun).toHaveBeenCalledTimes(1);
  938. });
  939. it("renders zh-CN wording on the compact card", () => {
  940. renderCard(
  941. ResumeWorkflowRunToolCallBlock,
  942. buildContext(buildResumeToolCall(), { workflowRun: RESUME_RUN_SUMMARY }),
  943. "zh-CN",
  944. );
  945. expect(screen.getByText("工作流实例已恢复")).toBeTruthy();
  946. expect(screen.getByText("运行中")).toBeTruthy();
  947. expect(screen.getByText("2/5 步")).toBeTruthy();
  948. });
  949. });