createWorkflowToolCallBlock.test.ts 96 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302
  1. // @vitest-environment jsdom
  2. // 启动前 ToolLayout 与旧宿主运行卡的渲染回归;v4 run 摘要另由 workflowToolSummary 测试覆盖。
  3. import { act, cleanup, fireEvent, render, within } from "@testing-library/react";
  4. import { createElement, type ReactNode } from "react";
  5. import { renderToStaticMarkup } from "react-dom/server";
  6. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  7. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  8. import type { WorkflowDraftPosition, WorkflowRunCardSummary } from "@/ToolCallBlocks/shared.js";
  9. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  10. vi.mock("@/components/ai-elements/code-block.js", () => ({
  11. CodeBlockHeader: () => null,
  12. CodeBlock: ({
  13. code,
  14. contentClassName,
  15. showLineNumbers,
  16. markedLines,
  17. }: {
  18. code: string;
  19. children?: ReactNode;
  20. contentClassName?: string;
  21. showLineNumbers?: boolean;
  22. markedLines?: readonly number[];
  23. }) =>
  24. createElement(
  25. "pre",
  26. {
  27. "data-testid": "code-block",
  28. className: contentClassName,
  29. "data-show-line-numbers": showLineNumbers === true ? "true" : undefined,
  30. "data-marked-lines": markedLines === undefined ? undefined : markedLines.join(","),
  31. },
  32. code,
  33. ),
  34. }));
  35. // ControlHintTooltip 依赖应用根部的 TooltipProvider;测试里按既有惯例替换为透传桩。
  36. vi.mock("@/ControlHintTooltip.js", () => ({
  37. ControlHintTooltip: ({ children }: { children?: ReactNode }) => children,
  38. }));
  39. // 接线用例要把整行渲染出来;行不碰 workspace 服务,给一个空实现免去搭一整份 Provider。
  40. vi.mock("@/hooks/useWorkspaceServices.js", () => ({
  41. useWorkspaceServices: () => ({}),
  42. }));
  43. // eslint-disable-next-line import/first -- 必须在 code-block mock 之后再引入被测 renderer。
  44. import {
  45. CreateWorkflowToolCallBlock,
  46. readWorkflowKindMessageId,
  47. } from "../src/ToolCallBlocks/renderers/create-workflow.js";
  48. // eslint-disable-next-line import/first -- 同上;反馈提示的纯函数与 renderer 同一读取规则。
  49. import { formatWorkflowFeedbackTooltip } from "../src/ToolCallBlocks/renderers/createWorkflowDisplay.js";
  50. // eslint-disable-next-line import/first -- 同上;卡片与确认窗共用的入参读取规则。
  51. import {
  52. readWorkflowAmendScriptInherited,
  53. readWorkflowRetuneCall,
  54. } from "../src/ToolCallBlocks/renderers/createWorkflowInput.js";
  55. // eslint-disable-next-line import/first -- 同上;接线层(行 → 宿主请求)只在这一节用到。
  56. import { ConversationRowView } from "@/v4/ConversationRowView.js";
  57. // eslint-disable-next-line import/first -- 同上。
  58. import { PlatformProvider } from "@/hooks/usePlatform.js";
  59. type ToolCallOverrides = {
  60. /** 工具名(kind / title 同值);缺省 CreateWorkflow,修订行传 AmendWorkflow。 */
  61. kind?: string;
  62. input?: unknown;
  63. output?: unknown;
  64. raw?: unknown;
  65. status?: string;
  66. snapshotRefs?: readonly { field: string; previewBytes: number; fullBytes: number }[];
  67. };
  68. type ContextOverrides = {
  69. isRunning?: boolean;
  70. statusLabel?: string;
  71. errorText?: string;
  72. onOpenWorkflowRun?: (request: { workflowName?: string }) => void;
  73. onResumeWorkflowRun?: (request: { workflowName?: string }) => void;
  74. onOpenWorkflowActor?: (request: {
  75. runId: string;
  76. actorSessionId: string;
  77. siteId: string;
  78. ordinal: number;
  79. actorName?: string;
  80. }) => void;
  81. onLoadFullToolCallFields?: (toolId: string) => void;
  82. onOpenWorkflowArtifact?: (artifactId: string) => void;
  83. onOpenWorkflowWorkspace?: (request: { phaseId: string; workflowName?: string }) => void;
  84. workflowRun?: WorkflowRunCardSummary;
  85. workflowDraft?: WorkflowDraftPosition;
  86. forceOpen?: boolean;
  87. canToggle?: boolean;
  88. };
  89. function createBlock(
  90. toolCall: ToolCallOverrides,
  91. contextOverrides: ContextOverrides = {},
  92. locale: "en-US" | "zh-CN" = "en-US",
  93. ) {
  94. return createElement(
  95. ZCodeIntlProvider,
  96. { initialLocale: locale },
  97. createElement(CreateWorkflowToolCallBlock, {
  98. toolCallNode: {
  99. toolCall: {
  100. toolId: "tool-create-workflow",
  101. kind: toolCall.kind ?? "CreateWorkflow",
  102. title: toolCall.kind ?? "CreateWorkflow",
  103. input: toolCall.input,
  104. output: toolCall.output,
  105. status: toolCall.status ?? "completed",
  106. raw: toolCall.raw,
  107. snapshotRefs: toolCall.snapshotRefs,
  108. },
  109. childToolCalls: [],
  110. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 测试上下文只填 renderer 读取的字段。
  111. } as any,
  112. workspacePath: "/workspace",
  113. displayModel: {
  114. inlinePreview: { type: "none" },
  115. planResult: null,
  116. viewerSource: null,
  117. viewerLabelId: "codeViewer.viewCode",
  118. showSummaryFileLink: false,
  119. showInput: false,
  120. showOutput: true,
  121. showKind: false,
  122. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 同上。
  123. } as any,
  124. viewerSource: null,
  125. rawFileSummaries: [],
  126. isRunning: contextOverrides.isRunning ?? false,
  127. statusLabel: contextOverrides.statusLabel ?? "Completed",
  128. errorText: contextOverrides.errorText,
  129. childToolList: null,
  130. forceOpen: contextOverrides.forceOpen ?? true,
  131. canToggle: contextOverrides.canToggle ?? true,
  132. showIcon: true,
  133. onOpenWorkflowRun: contextOverrides.onOpenWorkflowRun,
  134. onResumeWorkflowRun: contextOverrides.onResumeWorkflowRun,
  135. onOpenWorkflowActor: contextOverrides.onOpenWorkflowActor,
  136. onOpenWorkflowArtifact: contextOverrides.onOpenWorkflowArtifact,
  137. onOpenWorkflowWorkspace: contextOverrides.onOpenWorkflowWorkspace,
  138. onLoadFullToolCallFields: contextOverrides.onLoadFullToolCallFields,
  139. workflowRun: contextOverrides.workflowRun,
  140. workflowDraft: contextOverrides.workflowDraft,
  141. }),
  142. );
  143. }
  144. function renderBlock(
  145. toolCall: ToolCallOverrides,
  146. contextOverrides: ContextOverrides = {},
  147. locale: "en-US" | "zh-CN" = "en-US",
  148. ): string {
  149. return renderToStaticMarkup(createBlock(toolCall, contextOverrides, locale));
  150. }
  151. function renderBlockDom(
  152. toolCall: ToolCallOverrides,
  153. contextOverrides: ContextOverrides = {},
  154. locale: "en-US" | "zh-CN" = "en-US",
  155. ) {
  156. return render(createBlock(toolCall, contextOverrides, locale));
  157. }
  158. // 本仓 vitest 没开 globals,@testing-library 的自动 cleanup 不会注册;不显式清理,
  159. // 上一条用例的 DOM 会留下来。
  160. afterEach(() => {
  161. cleanup();
  162. });
  163. const OK_DISPLAY = {
  164. kind: "create_workflow",
  165. ok: true,
  166. errorCount: 0,
  167. diagnostics: [],
  168. };
  169. // ── 图夹具:plan → verify,verify 回到 plan ─────────────────────────────────────
  170. const LOOP_GRAPH = {
  171. steps: [
  172. {
  173. id: "ask#1",
  174. kind: "ask",
  175. label: "plan",
  176. line: 2,
  177. column: 21,
  178. lane: "actor#1",
  179. phase: "phase#a",
  180. },
  181. {
  182. id: "ask#2",
  183. kind: "ask",
  184. label: "verify",
  185. line: 5,
  186. column: 21,
  187. lane: "actor#2",
  188. phase: "phase#b",
  189. },
  190. ],
  191. lanes: [
  192. { id: "actor#1", name: "planner", line: 1, column: 11 },
  193. { id: "actor#2", name: "checker", line: 4, column: 11 },
  194. ],
  195. participants: [
  196. { id: "phase#a:actor#1", phase: "phase#a", lane: "actor#1", steps: ["ask#1"] },
  197. { id: "phase#b:actor#2", phase: "phase#b", lane: "actor#2", steps: ["ask#2"] },
  198. ],
  199. handoffs: [],
  200. phases: [
  201. { id: "phase#a", name: "plan", line: 1 },
  202. { id: "phase#b", name: "verify", line: 4 },
  203. ],
  204. phaseEdges: [
  205. { from: "phase#a", to: "phase#b" },
  206. { from: "phase#b", to: "phase#a", back: true },
  207. ],
  208. exits: ["phase#b"],
  209. };
  210. const FLAT_GRAPH = {
  211. steps: [{ id: "ask#1", kind: "ask", label: "a", line: 1, column: 21, lane: "actor#1" }],
  212. lanes: [{ id: "actor#1", name: "a", line: 1, column: 11 }],
  213. participants: [{ id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#1"] }],
  214. handoffs: [],
  215. sink: ["ask#1"],
  216. };
  217. const LOOP_TOOL_CALL: ToolCallOverrides = {
  218. input: { name: "Research pipeline", script: 'phase("plan");\nconst p = agent("planner");' },
  219. raw: { display: { ...OK_DISPLAY, causalityGraph: LOOP_GRAPH } },
  220. };
  221. function runState(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  222. return {
  223. runId: "dwfrun-42",
  224. toolCallId: "tool-create-workflow",
  225. status: "running",
  226. usage: { spentTokens: 1_234, nodesUsed: 2 },
  227. actors: [
  228. { siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "completed" },
  229. { siteId: "actor#2", ordinal: 1, name: "Bob", sessionId: "s-2", status: "running" },
  230. ],
  231. nodes: [
  232. {
  233. siteId: "ask#1",
  234. ordinal: 1,
  235. phase: "settled",
  236. outcome: "ok",
  237. actorSiteId: "actor#1",
  238. actorOrdinal: 1,
  239. },
  240. { siteId: "ask#2", ordinal: 1, phase: "executing", actorSiteId: "actor#2", actorOrdinal: 1 },
  241. ] as WorkflowRunState["nodes"],
  242. lastEventSequence: 7,
  243. ...overrides,
  244. };
  245. }
  246. function joined(
  247. overrides: Partial<WorkflowRunState> = {},
  248. extra: Partial<WorkflowRunCardSummary> = {},
  249. ) {
  250. const run = runState(overrides);
  251. const settled = run.nodes.filter((node) => node.phase === "settled").length;
  252. return {
  253. runId: run.runId,
  254. status: run.status,
  255. ...(run.stopReason === undefined ? {} : { stopReason: run.stopReason }),
  256. nodesSettled: settled,
  257. nodesTotal: run.nodes.length,
  258. run,
  259. ...extra,
  260. } satisfies WorkflowRunCardSummary;
  261. }
  262. describe("CreateWorkflowToolCallBlock 静态形态(编过、未联接 run)", () => {
  263. it("表头:种类词 + 名字,右侧空环灯「compiled」+ 等宽计数;卡体是时间线,脚本折叠", () => {
  264. const view = renderBlockDom(LOOP_TOOL_CALL);
  265. const card = view.getByTestId("workflow-card");
  266. expect(card.getAttribute("data-workflow-card-state")).toBe("static");
  267. expect(view.getByTestId("workflow-card-kind").textContent).toBe("Workflow");
  268. expect(view.getByTestId("workflow-card-name").textContent).toBe("Research pipeline");
  269. expect(view.getByTestId("workflow-card-static-status").textContent).toBe("compiled");
  270. expect(view.getByTestId("workflow-card-detail").textContent).toBe("2 phases · 2 agents");
  271. const stations = view.getAllByTestId("workflow-timeline-station");
  272. expect(stations.map((station) => station.textContent)).toEqual([
  273. expect.stringContaining("plan"),
  274. expect.stringContaining("verify"),
  275. ]);
  276. expect(view.getAllByTestId("workflow-agent-pill").map((pill) => pill.textContent)).toEqual([
  277. expect.stringContaining("planner"),
  278. expect.stringContaining("checker"),
  279. ]);
  280. // 相邻的边是淡墨轨道段;回边是弧。
  281. expect(view.getByTestId("workflow-timeline-rail").getAttribute("data-rail-ink")).toBe("faint");
  282. const arc = view.getByTestId("workflow-timeline-arc");
  283. expect(arc.getAttribute("data-arc-from")).toBe("1");
  284. expect(arc.getAttribute("data-arc-to")).toBe("0");
  285. // 最低一道的弧也要有一段像样的下落:圆角之后的竖段向下且不短于箭头(回归:16px 的道高让最后
  286. // 一段向上走了一像素,`marker-end` 跟着朝上,箭头就不见了)。
  287. const d = arc.querySelector("path")!.getAttribute("d")!;
  288. const verticals = [...d.matchAll(/V(-?[\d.]+)/gu)].map((match) => Number(match[1]));
  289. const corner = Number(
  290. /Q[^ ]+ [^,]+,([\d.]+)$/u.exec(d.slice(0, d.lastIndexOf("V")).trimEnd())?.[1],
  291. );
  292. expect(verticals).toHaveLength(2);
  293. expect(verticals[1]! - corner).toBeGreaterThanOrEqual(8);
  294. // 没有汇点、没有「may terminate」。
  295. expect(card.textContent).not.toContain("terminate");
  296. // 脚本原文只能在这里读:默认收起,点开才进 DOM。
  297. expect(view.queryByTestId("code-block")).toBeNull();
  298. fireEvent.click(view.getByTestId("workflow-card-script-toggle"));
  299. expect(view.getByTestId("code-block").textContent).toContain('phase("plan")');
  300. });
  301. it("无标记脚本:一个隐式站「Workflow」,药丸是那条车道的作者原名", () => {
  302. const view = renderBlockDom({
  303. input: { script: "x" },
  304. raw: { display: { ...OK_DISPLAY, causalityGraph: FLAT_GRAPH } },
  305. });
  306. expect(view.getByTestId("workflow-timeline-station").textContent).toContain("Workflow");
  307. expect(view.getByTestId("workflow-agent-pill").textContent).toContain("a");
  308. expect(view.getByTestId("workflow-card-detail").textContent).toBe("1 phase · 1 agent");
  309. });
  310. it("没有图(或零 step 的图)时不画时间线,脚本折叠仍在", () => {
  311. const html = renderBlock({ input: { script: "const x = 1;" }, raw: { display: OK_DISPLAY } });
  312. expect(html).not.toContain("workflow-timeline");
  313. expect(html).toContain("workflow-card-script-toggle");
  314. expect(html).not.toContain("workflow-card-detail");
  315. const empty = renderBlock({
  316. input: { script: "x" },
  317. raw: {
  318. display: {
  319. ...OK_DISPLAY,
  320. causalityGraph: { steps: [], lanes: [], participants: [], handoffs: [] },
  321. },
  322. },
  323. });
  324. expect(empty).not.toContain("workflow-timeline");
  325. });
  326. it("联接不到 run 时没有页脚、没有 run 属性;回调在而 run 摘要不在时仍是静态卡", () => {
  327. const view = renderBlockDom(LOOP_TOOL_CALL, { onOpenWorkflowRun: () => {} });
  328. const card = view.getByTestId("workflow-card");
  329. expect(card.getAttribute("data-workflow-run-id")).toBeNull();
  330. expect(view.queryByTestId("workflow-card-footer")).toBeNull();
  331. expect(view.queryByTestId("workflow-card-status")).toBeNull();
  332. expect(html(view)).not.toContain("Workflow started");
  333. });
  334. it("六个阶段完整进入时间线", () => {
  335. const phases = ["a", "b", "c", "d", "e", "f"].map((name, i) => ({
  336. id: `phase#${name}`,
  337. name,
  338. line: i + 1,
  339. }));
  340. const steps = phases.map((phase, i) => ({
  341. id: `ask#${i + 1}`,
  342. kind: "ask",
  343. label: phase.name,
  344. lane: "actor#1",
  345. phase: phase.id,
  346. }));
  347. const view = renderBlockDom({
  348. input: { script: "x" },
  349. raw: {
  350. display: {
  351. ...OK_DISPLAY,
  352. causalityGraph: {
  353. steps,
  354. lanes: [{ id: "actor#1", name: "worker" }],
  355. participants: steps.map((step) => ({
  356. id: `${step.phase}:actor#1`,
  357. phase: step.phase,
  358. lane: "actor#1",
  359. steps: [step.id],
  360. })),
  361. handoffs: [],
  362. phases,
  363. phaseEdges: phases.slice(1).map((phase, i) => ({ from: phases[i]!.id, to: phase.id })),
  364. exits: ["phase#f"],
  365. },
  366. },
  367. },
  368. });
  369. expect(view.getAllByTestId("workflow-timeline-station")).toHaveLength(6);
  370. });
  371. it("shows the graph truncation note when steps were omitted", () => {
  372. const view = renderBlockDom({
  373. input: { script: "x" },
  374. raw: { display: { ...OK_DISPLAY, causalityGraph: { ...FLAT_GRAPH, truncated: true } } },
  375. });
  376. expect(view.container.textContent).toContain("some participants were omitted");
  377. });
  378. it("falls back to the plain output text when no display payload exists", () => {
  379. const markup = renderBlock({
  380. input: { script: "export const meta = {};" },
  381. output: { diagnostics: [], ok: true, response: "The workflow script compiled cleanly." },
  382. raw: {},
  383. });
  384. expect(markup).toContain("The workflow script compiled cleanly.");
  385. expect(markup).toContain("workflow-card-script-toggle");
  386. // 无 display 时不应出现结构化反馈卡、compiled 词或待修正计数。
  387. expect(markup).not.toContain("Compiler feedback");
  388. expect(markup).not.toContain("workflow-draft-lamp");
  389. expect(markup).not.toContain("workflow-card-static-status");
  390. expect(markup).not.toContain("&quot;ok&quot;");
  391. });
  392. it("does not crash and shows a hint when input.script is missing", () => {
  393. const markup = renderBlock({ input: { name: "No script here" }, raw: {} });
  394. expect(markup).toContain("No workflow script provided.");
  395. expect(markup).not.toContain("code-block");
  396. });
  397. it("saved 来源显示保存的工作流名称", () => {
  398. const view = renderBlockDom({
  399. input: {
  400. name: "Fan-out review",
  401. script: "x",
  402. saved: {
  403. name: "fan-out-review",
  404. scope: "project",
  405. path: "/workspace/.zcode/workflows/fan-out-review.dwf.ts",
  406. },
  407. },
  408. raw: { display: { ...OK_DISPLAY, causalityGraph: FLAT_GRAPH } },
  409. });
  410. const savedLine = view.container.querySelector('[data-workflow-card-saved-source="true"]')!;
  411. expect(savedLine.textContent).toContain("fan-out-review");
  412. });
  413. });
  414. function html(view: ReturnType<typeof render>): string {
  415. return view.container.innerHTML;
  416. }
  417. // ── 编译反馈(docs/dynamic-workflow/presentation.md「Compiler feedback」)──────────────────
  418. // 编不过不是失败:什么都没跑,反馈交回了模型。行只用 ToolLayout 已有的槽位说这件事,全程不用 destructive。
  419. describe("CreateWorkflowToolCallBlock 编译反馈", () => {
  420. const FEEDBACK_DISPLAY = {
  421. kind: "create_workflow",
  422. ok: false,
  423. errorCount: 2,
  424. diagnostics: [
  425. { line: 3, column: 5, code: 2304, message: "Cannot find name 'agent'." },
  426. {
  427. line: 8,
  428. column: 1,
  429. code: 9003,
  430. message: "world.run's first argument must be a compile-time string literal.",
  431. },
  432. ],
  433. };
  434. const FEEDBACK_CALL: ToolCallOverrides = {
  435. input: { name: "Release notes digest", script: "const x: number = 'nope';" },
  436. output: { diagnostics: [], ok: false, response: "The workflow script has errors:" },
  437. raw: { display: FEEDBACK_DISPLAY },
  438. };
  439. const LATEST: WorkflowDraftPosition = { ordinal: 2, superseded: false };
  440. it("行:「Workflow draft」+ 名字 + 稿号 + 警示色空环灯 +「2 to fix · not run」;不是工作流卡", () => {
  441. const view = renderBlockDom(FEEDBACK_CALL, { workflowDraft: LATEST, forceOpen: false });
  442. const row = view.getByRole("button");
  443. expect(row.getAttribute("aria-expanded")).toBe("false");
  444. expect(row.querySelector(".tool-summary-kind-label")?.textContent).toBe("Workflow draft");
  445. expect(row.textContent).toContain("Release notes digest");
  446. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 2");
  447. expect(view.getByTestId("workflow-draft-status").textContent).toBe("2 to fix · not run");
  448. const lamp = view.getByTestId("workflow-draft-lamp");
  449. expect(lamp.getAttribute("data-draft-lamp")).toBe("open");
  450. expect(lamp.className).toContain("border-warning");
  451. expect(view.queryByTestId("workflow-card")).toBeNull();
  452. expect(view.queryByTestId("workflow-timeline")).toBeNull();
  453. });
  454. it("有更新的一稿:灯褪成中性,稿号与词不变", () => {
  455. const view = renderBlockDom(FEEDBACK_CALL, {
  456. workflowDraft: { ordinal: 1, superseded: true },
  457. forceOpen: false,
  458. });
  459. const lamp = view.getByTestId("workflow-draft-lamp");
  460. expect(lamp.getAttribute("data-draft-lamp")).toBe("settled");
  461. expect(lamp.className).toContain("border-foreground-subtlest");
  462. expect(lamp.className).not.toContain("border-warning");
  463. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 1");
  464. expect(view.getByTestId("workflow-draft-status").textContent).toBe("2 to fix · not run");
  465. });
  466. it("宿主没有稿号联接:不编号,灯保持警示色", () => {
  467. const view = renderBlockDom(FEEDBACK_CALL, { forceOpen: false });
  468. expect(view.queryByTestId("workflow-draft-ordinal")).toBeNull();
  469. expect(view.getByTestId("workflow-draft-lamp").getAttribute("data-draft-lamp")).toBe("open");
  470. });
  471. it("展开脚本带行号与问题行,反馈显示标题、计数、说明及逐条位置", () => {
  472. const view = renderBlockDom(FEEDBACK_CALL, { workflowDraft: LATEST, forceOpen: true });
  473. // 展开后稿号仍在行上(不随展开隐藏)。
  474. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 2");
  475. const code = view.getByTestId("code-block");
  476. expect(code.getAttribute("data-show-line-numbers")).toBe("true");
  477. expect(code.getAttribute("data-marked-lines")).toBe("3,8");
  478. const card = view.getByTestId("workflow-compiler-feedback");
  479. expect(within(card).getByTestId("workflow-compiler-feedback-title").textContent).toBe(
  480. "Compiler feedback",
  481. );
  482. expect(within(card).getByTestId("workflow-compiler-feedback-count").textContent).toBe(
  483. "2 notes",
  484. );
  485. expect(within(card).getByTestId("workflow-compiler-feedback-lede").textContent).toBe(
  486. "Typecheck did not pass, so nothing ran. The feedback went back to the model to revise and resubmit.",
  487. );
  488. const lines = within(card).getAllByTestId("workflow-compiler-feedback-line");
  489. expect(lines).toHaveLength(2);
  490. expect(lines[0]!.textContent).toContain("L3:C5");
  491. expect(lines[0]!.textContent).toContain("Cannot find name");
  492. expect(lines[0]!.textContent).toContain("TS2304");
  493. // 分析器自有规则不是 TypeScript 码。
  494. expect(lines[1]!.textContent).toContain("rule 9003");
  495. expect(lines[1]!.textContent).not.toContain("TS9003");
  496. });
  497. it("单条反馈用单数;条数读 errorCount 而不是截断后的行数", () => {
  498. const one = renderBlockDom(
  499. {
  500. ...FEEDBACK_CALL,
  501. raw: {
  502. display: {
  503. ...FEEDBACK_DISPLAY,
  504. errorCount: 1,
  505. diagnostics: [FEEDBACK_DISPLAY.diagnostics[0]],
  506. },
  507. },
  508. },
  509. { forceOpen: true },
  510. );
  511. expect(one.getByTestId("workflow-compiler-feedback-count").textContent).toBe("1 note");
  512. expect(one.getByTestId("workflow-draft-status").textContent).toBe("1 to fix · not run");
  513. cleanup();
  514. const many = renderBlockDom(
  515. {
  516. ...FEEDBACK_CALL,
  517. raw: { display: { ...FEEDBACK_DISPLAY, errorCount: 150, truncated: true } },
  518. },
  519. { forceOpen: true },
  520. );
  521. expect(many.getByTestId("workflow-compiler-feedback-count").textContent).toBe("150 notes");
  522. expect(many.container.textContent).toContain("Some diagnostics were omitted.");
  523. });
  524. it("保存的来源编不过:那句话点名文件,而不是这次调用", () => {
  525. const view = renderBlockDom(
  526. {
  527. ...FEEDBACK_CALL,
  528. input: {
  529. name: "Release notes digest",
  530. script: "const x: number = 'nope';",
  531. saved: {
  532. name: "release-notes",
  533. scope: "project",
  534. path: ".zcode/workflows/release-notes.ts",
  535. },
  536. },
  537. },
  538. { forceOpen: true },
  539. );
  540. expect(view.getByTestId("workflow-compiler-feedback-lede").textContent).toBe(
  541. "The saved workflow file did not pass typecheck, so nothing ran. The feedback went back to the model to fix the file or save a corrected version.",
  542. );
  543. });
  544. it("zh-CN:「工作流草稿 · 第 1 稿 · 2 处待修正 · 未运行」与「编译反馈 · 2 条 · 规则 9003」", () => {
  545. const view = renderBlockDom(
  546. FEEDBACK_CALL,
  547. { workflowDraft: { ordinal: 1, superseded: false }, forceOpen: true },
  548. "zh-CN",
  549. );
  550. expect(view.container.querySelector(".tool-summary-kind-label")?.textContent).toBe(
  551. "工作流草稿",
  552. );
  553. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("第 1 稿");
  554. expect(view.getByTestId("workflow-draft-status").textContent).toBe("2 处待修正 · 未运行");
  555. expect(view.getByTestId("workflow-compiler-feedback-title").textContent).toBe("编译反馈");
  556. expect(view.getByTestId("workflow-compiler-feedback-count").textContent).toBe("2 条");
  557. expect(view.getByTestId("workflow-compiler-feedback-lede").textContent).toBe(
  558. "类型检查未通过,脚本未运行;反馈已交回模型,由它修改后重新提交。",
  559. );
  560. expect(view.container.textContent).toContain("规则 9003");
  561. });
  562. it("提示:先说那一句话,再逐条列出位置与消息", () => {
  563. expect(formatWorkflowFeedbackTooltip("Nothing ran.", FEEDBACK_DISPLAY.diagnostics)).toBe(
  564. "Nothing ran.\nL3:C5 Cannot find name 'agent'.\nL8:C1 world.run's first argument must be a compile-time string literal.",
  565. );
  566. expect(formatWorkflowFeedbackTooltip("Nothing ran.", [])).toBe("Nothing ran.");
  567. });
  568. it("失败但没有 display(被拒、工具报错):仍是「Workflow」+ 工具状态词,没有灯与稿号", () => {
  569. const view = renderBlockDom(
  570. {
  571. input: { name: "Release notes digest", script: "x" },
  572. output: "run_not_found: no such run",
  573. status: "failed",
  574. },
  575. { statusLabel: "Failed", workflowDraft: LATEST, forceOpen: false },
  576. );
  577. expect(view.container.querySelector(".tool-summary-kind-label")?.textContent).toBe("Workflow");
  578. expect(view.container.textContent).toContain("Failed");
  579. expect(view.queryByTestId("workflow-draft-lamp")).toBeNull();
  580. expect(view.queryByTestId("workflow-draft-ordinal")).toBeNull();
  581. });
  582. it("编不过时即使宿主联接到了 run 也留在反馈行", () => {
  583. const markup = renderBlock(
  584. {
  585. input: { script: "x" },
  586. raw: {
  587. display: {
  588. kind: "create_workflow",
  589. ok: false,
  590. errorCount: 1,
  591. diagnostics: [{ line: 1, column: 1, code: 2304, message: "boom" }],
  592. },
  593. },
  594. },
  595. { workflowRun: joined() },
  596. );
  597. expect(markup).toContain("Compiler feedback");
  598. expect(markup).not.toContain('data-testid="workflow-card"');
  599. expect(markup).not.toContain("Workflow running");
  600. });
  601. });
  602. describe("CreateWorkflowToolCallBlock 启动前 ToolLayout", () => {
  603. const DRAFT =
  604. 'phase("plan");\nconst planner = agent("planner");\nawait world.run("pnpm test");\nphase("ver';
  605. // 草稿由笔逐字写出(追记「书写效果」):断言最终形态前先让笔写完。
  606. beforeEach(() => {
  607. vi.useFakeTimers();
  608. });
  609. afterEach(() => {
  610. vi.useRealTimers();
  611. });
  612. // 笔每写一字都是 setState → effect 再排下一枚定时器;一次 advance 只走一步,所以按步长逐段推进。
  613. const settle = () => {
  614. for (let i = 0; i < 120; i += 1) {
  615. act(() => {
  616. vi.advanceTimersByTime(24);
  617. });
  618. }
  619. };
  620. it("编写中:行不可展开(forceOpen 也不展开),草稿阶段线常驻行下,站随笔写出、没有药丸", () => {
  621. const view = renderBlockDom(
  622. {
  623. input: { name: "Research pipeline", script: DRAFT },
  624. raw: { v4Status: "inputStreaming" },
  625. status: "running",
  626. },
  627. { isRunning: true, forceOpen: true },
  628. );
  629. expect(view.container.textContent).toContain("Writing workflow");
  630. expect(view.container.textContent).toContain("Research pipeline");
  631. expect(view.container.querySelector(".tool-summary-kind-label")).toBeTruthy();
  632. expect(view.container.querySelector("[aria-expanded]")).toBeNull();
  633. expect(view.queryByTestId("workflow-card")).toBeNull();
  634. expect(view.queryByTestId("code-block")).toBeNull();
  635. // 笔刚落下:第一站已揭示但一个字还没写,光标稳住(正在写);第二站还不在轨道上。
  636. expect(view.getByTestId("workflow-draft-timeline")).toBeTruthy();
  637. expect(view.getAllByTestId("workflow-timeline-station")).toHaveLength(1);
  638. expect(view.getByTestId("workflow-timeline-caret").getAttribute("data-pen")).toBe("writing");
  639. settle();
  640. const stations = view.getAllByTestId("workflow-timeline-station");
  641. expect(stations.map((station) => station.textContent)).toEqual(["plan", "ver"]);
  642. // 笔追上了流:光标在最后一站的名字后面闪烁。
  643. const caret = view.getByTestId("workflow-timeline-caret");
  644. expect(stations[1]!.contains(caret)).toBe(true);
  645. expect(caret.getAttribute("data-pen")).toBe("idle");
  646. // 草稿只有阶段线:没有药丸、没有弧;阶段线不是展开内容,行上仍没有展开入口。
  647. expect(view.queryByTestId("workflow-agent-pill")).toBeNull();
  648. expect(view.queryByTestId("workflow-timeline-arc")).toBeNull();
  649. expect(view.container.querySelector("[aria-expanded]")).toBeNull();
  650. });
  651. it("display 一到,草稿站与光标离场:卡换成分析器的站与药丸(不变式 10)", () => {
  652. const view = renderBlockDom(
  653. {
  654. input: { name: "Research pipeline", script: DRAFT },
  655. raw: { v4Status: "inputStreaming" },
  656. status: "running",
  657. },
  658. { isRunning: true },
  659. );
  660. settle();
  661. expect(view.getAllByTestId("workflow-timeline-station")).toHaveLength(2);
  662. view.rerender(createBlock(LOOP_TOOL_CALL));
  663. expect(view.queryByTestId("workflow-draft-timeline")).toBeNull();
  664. expect(view.queryByTestId("workflow-timeline-caret")).toBeNull();
  665. const stations = view.getAllByTestId("workflow-timeline-station");
  666. expect(stations.map((station) => station.textContent)).toEqual([
  667. expect.stringContaining("plan"),
  668. expect.stringContaining("verify"),
  669. ]);
  670. expect(view.getAllByTestId("workflow-agent-pill")).toHaveLength(2);
  671. expect(view.getByTestId("workflow-timeline-arc")).toBeTruthy();
  672. });
  673. it("编写中脚本还没到一个字:只有行,没有阶段线块", () => {
  674. const view = renderBlockDom(
  675. {
  676. input: { name: "Research pipeline" },
  677. raw: { v4Status: "inputStreaming" },
  678. status: "running",
  679. },
  680. { isRunning: true },
  681. );
  682. expect(view.container.textContent).toContain("Writing workflow");
  683. expect(view.queryByTestId("workflow-draft-timeline")).toBeNull();
  684. expect(view.queryByTestId("workflow-timeline-station")).toBeNull();
  685. });
  686. it.each(["en-US", "zh-CN"] as const)("等待确认可展开脚本、再次收起:%s", (locale) => {
  687. const view = renderBlockDom(
  688. {
  689. ...LOOP_TOOL_CALL,
  690. raw: { ...(LOOP_TOOL_CALL.raw as object), v4Status: "pendingApproval" },
  691. status: "running",
  692. },
  693. { isRunning: true, forceOpen: false },
  694. locale,
  695. );
  696. expect(view.container.querySelector(".tool-summary-kind-label")).toBeTruthy();
  697. expect(view.queryByTestId("workflow-card")).toBeNull();
  698. const trigger = view.getByRole("button");
  699. expect(trigger.getAttribute("aria-expanded")).toBe("false");
  700. expect(view.queryByTestId("code-block")).toBeNull();
  701. fireEvent.keyDown(trigger, { key: "Enter" });
  702. expect(trigger.getAttribute("aria-expanded")).toBe("true");
  703. expect(view.getByTestId("code-block").textContent).toContain("agent");
  704. fireEvent.click(trigger);
  705. expect(trigger.getAttribute("aria-expanded")).toBe("false");
  706. });
  707. });
  708. // ── 联接到 run:图整个留在聊天区,灯、药丸、墨迹随投影 ─────────────────────────────
  709. describe("CreateWorkflowToolCallBlock 运行态", () => {
  710. it("表头:种类词「Workflow running」、灯 + 状态词、步数细节;没有紧凑卡", () => {
  711. const view = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  712. const card = view.getByTestId("workflow-card");
  713. expect(card.getAttribute("data-workflow-card-state")).toBe("running");
  714. expect(card.getAttribute("data-workflow-run-id")).toBe("dwfrun-42");
  715. expect(view.getByTestId("workflow-card-kind").textContent).toBe("Workflow running");
  716. expect(view.getByTestId("workflow-card-status").textContent).toBe("Running");
  717. expect(view.getByTestId("workflow-card-detail").textContent).toBe("2 phases · 1 agent working");
  718. expect(view.queryByTestId("workflow-run-card")).toBeNull();
  719. expect(view.queryByTestId("workflow-card-static-status")).toBeNull();
  720. });
  721. it("站与药丸读投影:站灯、运行时名、状态标记;行进边是进入运行站的那一段", () => {
  722. const view = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  723. const stations = view.getAllByTestId("workflow-timeline-station");
  724. expect(stations.map((station) => station.getAttribute("data-station-status"))).toEqual([
  725. "done",
  726. "running",
  727. ]);
  728. expect(stations[0]!.textContent).toContain("1/1");
  729. const pills = view.getAllByTestId("workflow-agent-pill");
  730. expect(pills.map((pill) => pill.textContent)).toEqual([
  731. expect.stringContaining("Ada"),
  732. expect.stringContaining("Bob"),
  733. ]);
  734. expect(pills.map((pill) => pill.getAttribute("data-agent-status"))).toEqual([
  735. "done",
  736. "running",
  737. ]);
  738. // 状态不只靠颜色:标记带可读文字。
  739. expect(
  740. pills[1]!.querySelector('[data-testid="workflow-pill-status"]')?.getAttribute("aria-label"),
  741. ).toBe("running");
  742. expect(view.getByTestId("workflow-timeline-rail").getAttribute("data-rail-ink")).toBe("march");
  743. expect(view.getByTestId("workflow-timeline-arc").getAttribute("data-arc-ink")).toBe("faint");
  744. });
  745. it("运行态没有页脚:卡上只说阶段与子代理,都在表头;步数、token、轮次不上卡(2026-09-09)", () => {
  746. const view = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  747. expect(view.queryByTestId("workflow-card-footer")).toBeNull();
  748. const card = view.getByTestId("workflow-card").textContent ?? "";
  749. expect(view.getByTestId("workflow-card-detail").textContent).toBe("2 phases · 1 agent working");
  750. expect(card).not.toContain("steps");
  751. expect(card).not.toContain("tokens");
  752. expect(view.container.querySelector("progress")).toBeNull();
  753. });
  754. it("第二轮:回边浓墨并成为行进边,站头显示 ⟳ 2;表头不数轮次,仍只说阶段与子代理", () => {
  755. const view = renderBlockDom(LOOP_TOOL_CALL, {
  756. workflowRun: joined({
  757. actors: [
  758. { siteId: "actor#1", ordinal: 2, name: "Ada", sessionId: "s-1b", status: "running" },
  759. { siteId: "actor#2", ordinal: 1, name: "Bob", sessionId: "s-2", status: "completed" },
  760. ],
  761. nodes: [
  762. {
  763. siteId: "ask#1",
  764. ordinal: 1,
  765. phase: "settled",
  766. outcome: "ok",
  767. actorSiteId: "actor#1",
  768. actorOrdinal: 1,
  769. },
  770. {
  771. siteId: "ask#2",
  772. ordinal: 1,
  773. phase: "settled",
  774. outcome: "ok",
  775. actorSiteId: "actor#2",
  776. actorOrdinal: 1,
  777. },
  778. {
  779. siteId: "ask#1",
  780. ordinal: 2,
  781. phase: "executing",
  782. actorSiteId: "actor#1",
  783. actorOrdinal: 2,
  784. },
  785. ] as WorkflowRunState["nodes"],
  786. }),
  787. });
  788. expect(view.getByTestId("workflow-timeline-arc").getAttribute("data-arc-ink")).toBe("march");
  789. expect(view.getByTestId("workflow-timeline-rail").getAttribute("data-rail-ink")).toBe("strong");
  790. const rounds = view.getAllByTestId("workflow-timeline-rounds");
  791. expect(rounds[0]!.textContent).toContain("2");
  792. expect(view.getByTestId("workflow-card-detail").textContent).toBe("2 phases · 1 agent working");
  793. expect(view.queryByTestId("workflow-card-footer")).toBeNull();
  794. });
  795. it("已完成:墨迹 = 轨迹,表头换成终态计数(阶段数 · 子代理数);没有页脚", () => {
  796. const onOpenWorkflowArtifact = vi.fn();
  797. const view = renderBlockDom(LOOP_TOOL_CALL, {
  798. onOpenWorkflowArtifact,
  799. workflowRun: joined({
  800. status: "completed",
  801. actors: [
  802. { siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "completed" },
  803. { siteId: "actor#2", ordinal: 1, name: "Bob", sessionId: "s-2", status: "completed" },
  804. ],
  805. nodes: [
  806. { siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" },
  807. { siteId: "ask#2", ordinal: 1, phase: "settled", outcome: "ok" },
  808. ] as WorkflowRunState["nodes"],
  809. reports: [
  810. { id: "r1", kind: "text", title: "Summary", text: "done" },
  811. ] as WorkflowRunState["reports"],
  812. artifacts: [
  813. { id: "book", kind: "file", title: "Audit report", version: 2 },
  814. ] as WorkflowRunState["artifacts"],
  815. }),
  816. });
  817. expect(view.getByTestId("workflow-card-kind").textContent).toBe("Workflow completed");
  818. expect(view.getByTestId("workflow-card-status").textContent).toBe("Completed");
  819. expect(view.getByTestId("workflow-timeline-rail").getAttribute("data-rail-ink")).toBe("strong");
  820. expect(view.getByTestId("workflow-timeline-arc").getAttribute("data-arc-ink")).toBe("faint");
  821. expect(view.getByTestId("workflow-card-header").querySelector(".animate-pulse")).toBeNull();
  822. expect(view.queryByTestId("workflow-card-footer")).toBeNull();
  823. expect(view.getByTestId("workflow-card-detail").textContent).toBe("2 phases · 2 agents");
  824. const card = view.getByTestId("workflow-card").textContent ?? "";
  825. expect(card).not.toContain("steps");
  826. expect(card).not.toContain("tokens");
  827. // 产物只在产物条上出现(不再有「1 artifact」计数);「results」在屏幕上仍没有落点。
  828. expect(card).not.toContain("artifact");
  829. expect(card).not.toContain("result");
  830. expect(card).not.toContain("working");
  831. // 时间线下挂产物条:一枚可点的药丸,尾槽里是 v2。
  832. const strip = view.getByTestId("workflow-card-artifacts");
  833. const pills = within(strip).getAllByTestId("workflow-card-artifact");
  834. expect(pills).toHaveLength(1);
  835. expect(pills[0]?.tagName).toBe("BUTTON");
  836. expect(pills[0]?.getAttribute("data-artifact-open")).toBe("true");
  837. expect(within(strip).getByTestId("workflow-run-artifact-version").textContent).toBe("v2");
  838. fireEvent.click(pills[0]!);
  839. expect(onOpenWorkflowArtifact).toHaveBeenCalledWith("book");
  840. });
  841. it("宿主没注入产物打开能力时药丸禁用,产物条仍在场", () => {
  842. const view = renderBlockDom(LOOP_TOOL_CALL, {
  843. workflowRun: joined({
  844. status: "completed",
  845. artifacts: [
  846. { id: "book", kind: "file", title: "Audit report", version: 1 },
  847. ] as WorkflowRunState["artifacts"],
  848. }),
  849. });
  850. const pill = view.getByTestId("workflow-card-artifact") as HTMLButtonElement;
  851. expect(pill.disabled).toBe(true);
  852. expect(pill.getAttribute("data-artifact-open")).toBeNull();
  853. expect(view.queryByTestId("workflow-run-artifact-version")).toBeNull();
  854. });
  855. it("⤢ 打开详情页:只在宿主给了回调时在场,请求带展示名;点站头走同一条路", () => {
  856. const onOpenWorkflowRun = vi.fn();
  857. const view = renderBlockDom(LOOP_TOOL_CALL, { onOpenWorkflowRun, workflowRun: joined() });
  858. fireEvent.click(view.getByTestId("workflow-card-open-details"));
  859. expect(onOpenWorkflowRun).toHaveBeenCalledWith({ workflowName: "Research pipeline" });
  860. fireEvent.click(view.getAllByTestId("workflow-timeline-station")[1]!.querySelector("button")!);
  861. expect(onOpenWorkflowRun).toHaveBeenCalledTimes(2);
  862. cleanup();
  863. // 没有回调时站头不是控件(span,不是禁用的 button):禁用按钮会吞掉点击,轮尾摘要的整块开关
  864. // 就收不到(追记「点击语法修订」)。
  865. const gated = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  866. expect(gated.queryByTestId("workflow-card-open-details")).toBeNull();
  867. const station = gated.getAllByTestId("workflow-timeline-station")[0]!;
  868. expect(station.querySelector("button")).toBeNull();
  869. expect(station.querySelector('[data-testid="workflow-timeline-station-head"]')).not.toBeNull();
  870. });
  871. it("展示名缺席时请求里不带 workflowName", () => {
  872. const onOpenWorkflowRun = vi.fn();
  873. const view = renderBlockDom(
  874. { ...LOOP_TOOL_CALL, input: { script: "x" } },
  875. { onOpenWorkflowRun, workflowRun: joined() },
  876. );
  877. expect(view.getByTestId("workflow-card-name").textContent).toBe("Workflow script");
  878. fireEvent.click(view.getByTestId("workflow-card-open-details"));
  879. expect(onOpenWorkflowRun).toHaveBeenCalledWith({});
  880. });
  881. it("运行中折叠:卡体与页脚都收起;表头的灯与细节仍然在场", () => {
  882. const view = renderBlockDom(LOOP_TOOL_CALL, {
  883. forceOpen: false,
  884. canToggle: true,
  885. workflowRun: joined(),
  886. });
  887. expect(view.getByTestId("workflow-card-body")).toBeTruthy();
  888. fireEvent.click(view.getByTestId("workflow-card-toggle"));
  889. expect(view.queryByTestId("workflow-card-body")).toBeNull();
  890. expect(view.queryByTestId("workflow-card-footer")).toBeNull();
  891. expect(view.getByTestId("workflow-card-status").textContent).toBe("Running");
  892. expect(view.getByTestId("workflow-card-detail").textContent).toBe("2 phases · 1 agent working");
  893. fireEvent.click(view.getByTestId("workflow-card-toggle"));
  894. expect(view.getByTestId("workflow-card-body")).toBeTruthy();
  895. });
  896. it("forceOpen / canToggle=false 时没有折叠按钮", () => {
  897. const view = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  898. expect(view.queryByTestId("workflow-card-toggle")).toBeNull();
  899. cleanup();
  900. const locked = renderBlockDom(LOOP_TOOL_CALL, {
  901. forceOpen: false,
  902. canToggle: false,
  903. workflowRun: joined(),
  904. });
  905. expect(locked.queryByTestId("workflow-card-toggle")).toBeNull();
  906. expect(locked.getByTestId("workflow-card-body")).toBeTruthy();
  907. });
  908. it("联接到 run 后脚本折叠离开卡面:脚本原文去详情页的 Script 区读", () => {
  909. const view = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  910. expect(view.queryByTestId("workflow-card-script-toggle")).toBeNull();
  911. expect(view.queryByTestId("code-block")).toBeNull();
  912. });
  913. it("卡后面仍然挂着快照字段提示", () => {
  914. const view = renderBlockDom(
  915. {
  916. ...LOOP_TOOL_CALL,
  917. snapshotRefs: [{ field: "input", previewBytes: 100, fullBytes: 5_000 }],
  918. },
  919. { onLoadFullToolCallFields: () => {}, workflowRun: joined() },
  920. );
  921. expect(view.getByTestId("workflow-card")).toBeTruthy();
  922. expect(view.container.textContent).toContain("Load full tool data");
  923. });
  924. it("zh-CN 下卡面全部本地化", () => {
  925. const view = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() }, "zh-CN");
  926. const card = view.getByTestId("workflow-card");
  927. expect(view.getByTestId("workflow-card-kind").textContent).toBe("工作流运行中");
  928. expect(view.getByTestId("workflow-card-status").textContent).toBe("运行中");
  929. expect(card.textContent).toContain("2 个阶段 · 1 个子代理工作中");
  930. expect(card.textContent).toContain("1 个子代理工作中");
  931. expect(card.textContent).not.toContain("Workflow running");
  932. expect(card.textContent).not.toContain("steps");
  933. });
  934. });
  935. // ── 药丸 → 子代理 transcript(docs/dynamic-workflow/presentation.md「The pill」)──
  936. describe("CreateWorkflowToolCallBlock 药丸点击", () => {
  937. it("带会话的药丸是按钮:点一下交出实例身份(run、会话、站点、序号、运行时名)", () => {
  938. const onOpenWorkflowActor = vi.fn();
  939. const view = renderBlockDom(LOOP_TOOL_CALL, { onOpenWorkflowActor, workflowRun: joined() });
  940. const pills = view.getAllByTestId("workflow-agent-pill");
  941. expect(pills.map((pill) => pill.tagName)).toEqual(["BUTTON", "BUTTON"]);
  942. expect(pills[1]!.getAttribute("aria-label")).toBe("Open the transcript of Bob");
  943. // ↗ 的在场就是「可打开」的可见证据。
  944. expect(view.getAllByTestId("workflow-timeline-pill-open")).toHaveLength(2);
  945. fireEvent.click(pills[1]!);
  946. expect(onOpenWorkflowActor).toHaveBeenCalledWith({
  947. runId: "dwfrun-42",
  948. actorSessionId: "s-2",
  949. siteId: "actor#2",
  950. ordinal: 1,
  951. actorName: "Bob",
  952. });
  953. });
  954. it("能力门控:没有回调、或没有 run 时药丸不是按钮;活的 run 里没有会话的药丸也是按钮", () => {
  955. const noCallback = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: joined() });
  956. expect(
  957. noCallback.getAllByTestId("workflow-agent-pill").every((pill) => pill.tagName === "SPAN"),
  958. ).toBe(true);
  959. expect(noCallback.queryByTestId("workflow-timeline-pill-open")).toBeNull();
  960. cleanup();
  961. // 还没启动的子代理(追记「点击语法修订」):与活药丸同一套悬停与点击,交出槽位——车道 +
  962. // 将来的序号——不带会话 id;宿主开的是占位 tab。
  963. const onOpenWorkflowActor = vi.fn();
  964. const noSession = renderBlockDom(LOOP_TOOL_CALL, {
  965. onOpenWorkflowActor,
  966. workflowRun: joined({
  967. actors: [
  968. { siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "completed" },
  969. ],
  970. }),
  971. });
  972. const pills = noSession.getAllByTestId("workflow-agent-pill");
  973. expect(pills.map((pill) => pill.tagName)).toEqual(["BUTTON", "BUTTON"]);
  974. expect(pills[1]!.getAttribute("aria-label")).toBe("Open the transcript of checker");
  975. fireEvent.click(pills[1]!);
  976. expect(onOpenWorkflowActor).toHaveBeenCalledWith({
  977. runId: "dwfrun-42",
  978. siteId: "actor#2",
  979. ordinal: 1,
  980. actorName: "checker",
  981. });
  982. cleanup();
  983. const static_ = renderBlockDom(LOOP_TOOL_CALL, { onOpenWorkflowActor });
  984. expect(
  985. static_.getAllByTestId("workflow-agent-pill").every((pill) => pill.tagName === "SPAN"),
  986. ).toBe(true);
  987. expect(static_.getAllByTestId("workflow-agent-pill")[0]!.getAttribute("title")).toBe("planner");
  988. });
  989. it("点药丸不触发站头(各自的路径互不串线)", () => {
  990. const onOpenWorkflowActor = vi.fn();
  991. const onOpenWorkflowRun = vi.fn();
  992. const view = renderBlockDom(LOOP_TOOL_CALL, {
  993. onOpenWorkflowActor,
  994. onOpenWorkflowRun,
  995. workflowRun: joined(),
  996. });
  997. fireEvent.click(view.getAllByTestId("workflow-agent-pill")[0]!);
  998. expect(onOpenWorkflowActor).toHaveBeenCalledTimes(1);
  999. expect(onOpenWorkflowRun).not.toHaveBeenCalled();
  1000. });
  1001. });
  1002. // 脚本药丸(docs/dynamic-workflow/transcript-and-notifications.md「Opening the tab」):与子代理药丸同一套打开语法,
  1003. // 交出的不是槽位而是这一站的阶段 id——脚本 transcript 一个 run 只有一份,落点才按站。
  1004. describe("CreateWorkflowToolCallBlock 脚本药丸", () => {
  1005. const WORKSPACE_GRAPH = {
  1006. ...LOOP_GRAPH,
  1007. steps: [
  1008. ...LOOP_GRAPH.steps,
  1009. {
  1010. id: "world-read#1",
  1011. kind: "world-read",
  1012. label: "run tests",
  1013. line: 6,
  1014. column: 3,
  1015. lane: "workspace",
  1016. phase: "phase#b",
  1017. },
  1018. ],
  1019. lanes: [...LOOP_GRAPH.lanes, { id: "workspace" }],
  1020. participants: [
  1021. ...LOOP_GRAPH.participants,
  1022. { id: "phase#b:workspace", phase: "phase#b", lane: "workspace", steps: ["world-read#1"] },
  1023. ],
  1024. };
  1025. const WORKSPACE_TOOL_CALL: ToolCallOverrides = {
  1026. ...LOOP_TOOL_CALL,
  1027. raw: { display: { ...OK_DISPLAY, causalityGraph: WORKSPACE_GRAPH } },
  1028. };
  1029. const workspacePill = (view: ReturnType<typeof renderBlockDom>) =>
  1030. view
  1031. .getAllByTestId("workflow-agent-pill")
  1032. .find((pill) => pill.textContent?.includes("Script"))!;
  1033. it("活的 run 里脚本药丸是按钮:点一下交出这一站的阶段 id 与展示名", () => {
  1034. const onOpenWorkflowWorkspace = vi.fn();
  1035. const onOpenWorkflowActor = vi.fn();
  1036. const view = renderBlockDom(WORKSPACE_TOOL_CALL, {
  1037. onOpenWorkflowWorkspace,
  1038. onOpenWorkflowActor,
  1039. workflowRun: joined(),
  1040. });
  1041. const pill = workspacePill(view);
  1042. expect(pill.tagName).toBe("BUTTON");
  1043. expect(pill.getAttribute("aria-label")).toBe("Open the script's steps at verify");
  1044. expect(view.getAllByTestId("workflow-timeline-workspace-open")).toHaveLength(1);
  1045. fireEvent.click(pill);
  1046. expect(onOpenWorkflowWorkspace).toHaveBeenCalledWith({
  1047. phaseId: "phase#b",
  1048. workflowName: "Research pipeline",
  1049. });
  1050. // 与子代理那条路互不串线。
  1051. expect(onOpenWorkflowActor).not.toHaveBeenCalled();
  1052. });
  1053. it("能力门控:没有回调、或没有 run 时脚本药丸是 span;子代理回调在场也不借用", () => {
  1054. const noCallback = renderBlockDom(WORKSPACE_TOOL_CALL, {
  1055. onOpenWorkflowActor: vi.fn(),
  1056. workflowRun: joined(),
  1057. });
  1058. expect(workspacePill(noCallback).tagName).toBe("SPAN");
  1059. expect(noCallback.queryByTestId("workflow-timeline-workspace-open")).toBeNull();
  1060. cleanup();
  1061. const noRun = renderBlockDom(WORKSPACE_TOOL_CALL, { onOpenWorkflowWorkspace: vi.fn() });
  1062. expect(workspacePill(noRun).tagName).toBe("SPAN");
  1063. expect(noRun.queryByTestId("workflow-timeline-workspace-open")).toBeNull();
  1064. });
  1065. });
  1066. describe("CreateWorkflowToolCallBlock 失败态与 Resume", () => {
  1067. const failed = () =>
  1068. joined(
  1069. {
  1070. status: "errored",
  1071. error: { code: "actor_failed", message: "boom" } as WorkflowRunState["error"],
  1072. actors: [
  1073. { siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "completed" },
  1074. { siteId: "actor#2", ordinal: 1, name: "Bob", sessionId: "s-2", status: "completed" },
  1075. ],
  1076. nodes: [
  1077. { siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" },
  1078. { siteId: "ask#2", ordinal: 1, phase: "settled", outcome: "failed" },
  1079. ] as WorkflowRunState["nodes"],
  1080. },
  1081. { resumable: true },
  1082. );
  1083. it("出错:表头「Workflow errored」,失败的站与药丸带失败标记,页脚有 Resume", () => {
  1084. const onResumeWorkflowRun = vi.fn();
  1085. const view = renderBlockDom(LOOP_TOOL_CALL, { onResumeWorkflowRun, workflowRun: failed() });
  1086. expect(view.getByTestId("workflow-card-kind").textContent).toBe("Workflow errored");
  1087. expect(view.getByTestId("workflow-card-status").textContent).toBe("Errored");
  1088. expect(
  1089. view.getAllByTestId("workflow-timeline-station")[1]!.getAttribute("data-station-status"),
  1090. ).toBe("failed");
  1091. expect(view.getAllByTestId("workflow-agent-pill")[1]!.getAttribute("data-agent-status")).toBe(
  1092. "failed",
  1093. );
  1094. const resume = view.getByTestId("workflow-card-resume");
  1095. expect(view.getByTestId("workflow-card-footer").contains(resume)).toBe(true);
  1096. fireEvent.click(resume);
  1097. expect(onResumeWorkflowRun).toHaveBeenCalledWith({ workflowName: "Research pipeline" });
  1098. });
  1099. it("Resume 是能力门控:没有回调、或摘要不说可恢复,都没有按钮", () => {
  1100. const noCallback = renderBlockDom(LOOP_TOOL_CALL, { workflowRun: failed() });
  1101. expect(noCallback.queryByTestId("workflow-card-resume")).toBeNull();
  1102. cleanup();
  1103. const { resumable: _off, ...notResumable } = failed();
  1104. const notOffered = renderBlockDom(LOOP_TOOL_CALL, {
  1105. onResumeWorkflowRun: vi.fn(),
  1106. workflowRun: notResumable,
  1107. });
  1108. expect(notOffered.queryByTestId("workflow-card-resume")).toBeNull();
  1109. cleanup();
  1110. const running = renderBlockDom(LOOP_TOOL_CALL, {
  1111. onResumeWorkflowRun: vi.fn(),
  1112. workflowRun: joined(),
  1113. });
  1114. expect(running.queryByTestId("workflow-card-resume")).toBeNull();
  1115. });
  1116. it("折叠的失败卡仍然留下页脚:Resume 必须够得着", () => {
  1117. const view = renderBlockDom(LOOP_TOOL_CALL, {
  1118. canToggle: true,
  1119. forceOpen: false,
  1120. onResumeWorkflowRun: vi.fn(),
  1121. workflowRun: failed(),
  1122. });
  1123. fireEvent.click(view.getByTestId("workflow-card-toggle"));
  1124. expect(view.queryByTestId("workflow-card-body")).toBeNull();
  1125. expect(view.getByTestId("workflow-card-resume")).toBeTruthy();
  1126. });
  1127. it("停止:种类词「Workflow stopped」+ 原因词,联接摘要标 resumable 时同样有 Resume", () => {
  1128. const view = renderBlockDom(LOOP_TOOL_CALL, {
  1129. onResumeWorkflowRun: vi.fn(),
  1130. workflowRun: joined({ status: "stopped", stopReason: "user" }, { resumable: true }),
  1131. });
  1132. expect(view.getByTestId("workflow-card-kind").textContent).toBe("Workflow stopped");
  1133. expect(view.getByTestId("workflow-card-status-reason").textContent).toContain("by you");
  1134. // 状态行的第三个词:停下的 run 还能接着跑。动词从「取消」改成「停止」之后,后果由这里说。
  1135. expect(view.getByTestId("workflow-card-status-resumable").textContent).toContain("resumable");
  1136. expect(view.getByTestId("workflow-card-resume")).toBeTruthy();
  1137. });
  1138. it("摘要不带 resumable 时状态行没有第三个词(UI 绝不按 status 推导)", () => {
  1139. const view = renderBlockDom(LOOP_TOOL_CALL, {
  1140. workflowRun: joined({ status: "stopped", stopReason: "user" }),
  1141. });
  1142. expect(view.getByTestId("workflow-card-status-reason").textContent).toContain("by you");
  1143. expect(view.queryByTestId("workflow-card-status-resumable")).toBeNull();
  1144. });
  1145. });
  1146. // ── kind 文案的相位化 ─────────────────────────────────────────────────────────────
  1147. // ToolLayout 只在失败态渲染 statusLabel,所以非失败态 kindLabel 是卡上唯一说明「在干什么」
  1148. // 的文字;而「校验」只在 running 相为真(脚本在 prepareApproval 里早于弹窗就被 analyze 过)。
  1149. // 相位读适配器挂在 raw 上的 v4 原状态,两层都钉:纯函数与实际渲染出来的那句话。
  1150. describe("readWorkflowKindMessageId", () => {
  1151. it("终态一律是「工作流」,不看 v4 状态", () => {
  1152. expect(readWorkflowKindMessageId({ v4Status: "success" }, false)).toBe(
  1153. "chat.toolCall.workflow.ran",
  1154. );
  1155. expect(readWorkflowKindMessageId({ v4Status: "inputStreaming" }, false)).toBe(
  1156. "chat.toolCall.workflow.ran",
  1157. );
  1158. expect(readWorkflowKindMessageId(undefined, false)).toBe("chat.toolCall.workflow.ran");
  1159. });
  1160. it("inputStreaming 是「正在编写」——模型还在写脚本,没人在校验", () => {
  1161. expect(readWorkflowKindMessageId({ v4Status: "inputStreaming" }, true)).toBe(
  1162. "chat.toolCall.workflow.writing",
  1163. );
  1164. });
  1165. it("pendingApproval 是「待确认」——球在用户手上", () => {
  1166. expect(readWorkflowKindMessageId({ v4Status: "pendingApproval" }, true)).toBe(
  1167. "chat.toolCall.workflow.awaitingConfirmation",
  1168. );
  1169. });
  1170. it("running 相才是「正在校验」,语义收窄到这一相", () => {
  1171. expect(readWorkflowKindMessageId({ v4Status: "running" }, true)).toBe(
  1172. "chat.toolCall.workflow.running",
  1173. );
  1174. });
  1175. it("v4Status 缺席(非 v4 宿主 / 老快照)时逐字保持今天的行为", () => {
  1176. // 新相位只在有权威状态时生效;没有状态就不猜,回落 isRunning → 校验。
  1177. expect(readWorkflowKindMessageId(undefined, true)).toBe("chat.toolCall.workflow.running");
  1178. expect(readWorkflowKindMessageId({}, true)).toBe("chat.toolCall.workflow.running");
  1179. expect(readWorkflowKindMessageId({ display: OK_DISPLAY }, true)).toBe(
  1180. "chat.toolCall.workflow.running",
  1181. );
  1182. // raw 不是普通对象(数组 / 字符串 / null)同样回落,不崩。
  1183. expect(readWorkflowKindMessageId([], true)).toBe("chat.toolCall.workflow.running");
  1184. expect(readWorkflowKindMessageId("running", true)).toBe("chat.toolCall.workflow.running");
  1185. expect(readWorkflowKindMessageId(null, true)).toBe("chat.toolCall.workflow.running");
  1186. // 认不出的状态字符串也走同一条回落。
  1187. expect(readWorkflowKindMessageId({ v4Status: "queued" }, true)).toBe(
  1188. "chat.toolCall.workflow.running",
  1189. );
  1190. });
  1191. });
  1192. describe("CreateWorkflowToolCallBlock kind 文案分相", () => {
  1193. const IN_FLIGHT_INPUT = { name: "Fan-out review", script: "const x = 1;" };
  1194. it("inputStreaming:卡上写「正在编写工作流」,不写校验", () => {
  1195. const html = renderBlock(
  1196. { input: IN_FLIGHT_INPUT, raw: { v4Status: "inputStreaming" }, status: "running" },
  1197. { isRunning: true },
  1198. );
  1199. expect(html).toContain("Writing workflow");
  1200. expect(html).not.toContain("Validating workflow");
  1201. });
  1202. it("pendingApproval:卡上写「工作流待确认」", () => {
  1203. const html = renderBlock(
  1204. { input: IN_FLIGHT_INPUT, raw: { v4Status: "pendingApproval" }, status: "running" },
  1205. { isRunning: true },
  1206. );
  1207. expect(html).toContain("Awaiting workflow confirmation");
  1208. expect(html).not.toContain("Validating workflow");
  1209. });
  1210. it("running:仍然是「正在校验工作流」", () => {
  1211. const html = renderBlock(
  1212. { input: IN_FLIGHT_INPUT, raw: { v4Status: "running" }, status: "running" },
  1213. { isRunning: true },
  1214. );
  1215. expect(html).toContain("Validating workflow");
  1216. expect(html).not.toContain("Writing workflow");
  1217. });
  1218. it("v4Status 缺席时卡面逐字保持今天的行为", () => {
  1219. const html = renderBlock(
  1220. { input: IN_FLIGHT_INPUT, raw: {}, status: "running" },
  1221. { isRunning: true },
  1222. );
  1223. expect(html).toContain("Validating workflow");
  1224. expect(html).not.toContain("Writing workflow");
  1225. expect(html).not.toContain("Awaiting workflow confirmation");
  1226. });
  1227. it("终态不带任何相位词:只写「工作流」", () => {
  1228. const html = renderBlock({
  1229. input: IN_FLIGHT_INPUT,
  1230. raw: { display: OK_DISPLAY, v4Status: "success" },
  1231. });
  1232. expect(html).not.toContain("Writing workflow");
  1233. expect(html).not.toContain("Awaiting workflow confirmation");
  1234. expect(html).not.toContain("Validating workflow");
  1235. });
  1236. it("zh-CN 下相位文案同样本地化", () => {
  1237. const writing = renderBlock(
  1238. { input: IN_FLIGHT_INPUT, raw: { v4Status: "inputStreaming" }, status: "running" },
  1239. { isRunning: true },
  1240. "zh-CN",
  1241. );
  1242. expect(writing).toContain("正在编写工作流");
  1243. expect(writing).not.toContain("正在校验工作流");
  1244. const awaiting = renderBlock(
  1245. { input: IN_FLIGHT_INPUT, raw: { v4Status: "pendingApproval" }, status: "running" },
  1246. { isRunning: true },
  1247. "zh-CN",
  1248. );
  1249. expect(awaiting).toContain("工作流待确认");
  1250. const validating = renderBlock(
  1251. { input: IN_FLIGHT_INPUT, raw: { v4Status: "running" }, status: "running" },
  1252. { isRunning: true },
  1253. "zh-CN",
  1254. );
  1255. expect(validating).toContain("正在校验工作流");
  1256. });
  1257. it("第 2 稿起编写中的种类词是「Revising workflow」、细节槽带稿号;第 1 稿照旧不编号", () => {
  1258. const revising = renderBlockDom(
  1259. { input: IN_FLIGHT_INPUT, raw: { v4Status: "inputStreaming" }, status: "running" },
  1260. { isRunning: true, workflowDraft: { ordinal: 2, superseded: false } },
  1261. );
  1262. expect(revising.container.textContent).toContain("Revising workflow");
  1263. expect(revising.container.textContent).not.toContain("Writing workflow");
  1264. expect(revising.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 2");
  1265. expect(revising.queryByTestId("workflow-draft-lamp")).toBeNull();
  1266. cleanup();
  1267. const first = renderBlockDom(
  1268. { input: IN_FLIGHT_INPUT, raw: { v4Status: "inputStreaming" }, status: "running" },
  1269. { isRunning: true, workflowDraft: { ordinal: 1, superseded: false } },
  1270. );
  1271. expect(first.container.textContent).toContain("Writing workflow");
  1272. expect(first.queryByTestId("workflow-draft-ordinal")).toBeNull();
  1273. });
  1274. it("待确认与校验中:第 2 稿起同样带稿号,种类词不变", () => {
  1275. const awaiting = renderBlockDom(
  1276. { input: IN_FLIGHT_INPUT, raw: { v4Status: "pendingApproval" }, status: "running" },
  1277. { isRunning: true, workflowDraft: { ordinal: 2, superseded: false } },
  1278. );
  1279. expect(awaiting.container.textContent).toContain("Awaiting workflow confirmation");
  1280. expect(awaiting.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 2");
  1281. cleanup();
  1282. const validating = renderBlockDom(
  1283. { input: IN_FLIGHT_INPUT, raw: { v4Status: "running" }, status: "running" },
  1284. { isRunning: true, workflowDraft: { ordinal: 3, superseded: false } },
  1285. );
  1286. expect(validating.getByTestId("workflow-card-kind").textContent).toBe("Validating workflow");
  1287. expect(validating.getByTestId("workflow-card-detail").textContent).toBe("draft 3");
  1288. cleanup();
  1289. // 编过、没启动的静态卡不是在途行:不带稿号。
  1290. const settled = renderBlockDom(LOOP_TOOL_CALL, {
  1291. workflowDraft: { ordinal: 2, superseded: false },
  1292. });
  1293. expect(settled.getByTestId("workflow-card-detail").textContent).not.toContain("draft");
  1294. });
  1295. it("zh-CN:第 2 稿起写「正在修改工作流」与「第 2 稿」", () => {
  1296. const view = renderBlockDom(
  1297. { input: IN_FLIGHT_INPUT, raw: { v4Status: "inputStreaming" }, status: "running" },
  1298. { isRunning: true, workflowDraft: { ordinal: 2, superseded: false } },
  1299. "zh-CN",
  1300. );
  1301. expect(view.container.textContent).toContain("正在修改工作流");
  1302. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("第 2 稿");
  1303. });
  1304. });
  1305. // ── 五枚药丸与一扇门(docs/dynamic-workflow/presentation.md「Past six participants」)──
  1306. // 一站过了六个参与者:五枚钉住的药丸 + 一行「还有 n 个」;点那一行或站头开 run 详情、落到这一站。
  1307. describe("CreateWorkflowToolCallBlock 名册站", () => {
  1308. type FanStatus = "done" | "running" | "failed" | "pending";
  1309. // 真实的 fan-out 是一条车道跑出 N 个实例(`agent(\`reviewer-${i}\`)` 在循环里):静态图上是一张
  1310. // `many` 卡,run 一来按实例拆成 N 枚药丸(liveParticipantView)。display 的车道上限是 32,
  1311. // 所以名册的大数只能从这里来。
  1312. const FANOUT_GRAPH = {
  1313. steps: [
  1314. {
  1315. id: "ask#1",
  1316. kind: "ask",
  1317. label: "review",
  1318. line: 3,
  1319. column: 21,
  1320. lane: "actor#1",
  1321. phase: "phase#a",
  1322. },
  1323. ],
  1324. lanes: [{ id: "actor#1", namePattern: { head: "reviewer-" }, line: 2, column: 11 }],
  1325. participants: [
  1326. { id: "phase#a:actor#1", phase: "phase#a", lane: "actor#1", steps: ["ask#1"], many: true },
  1327. ],
  1328. handoffs: [],
  1329. phases: [{ id: "phase#a", name: "review", line: 1 }],
  1330. phaseEdges: [],
  1331. exits: ["phase#a"],
  1332. };
  1333. function fanoutToolCall(_n: number): ToolCallOverrides {
  1334. return {
  1335. input: { name: "bug-scan", script: 'phase("review");' },
  1336. raw: { display: { ...OK_DISPLAY, causalityGraph: FANOUT_GRAPH } },
  1337. };
  1338. }
  1339. function fanoutRun(
  1340. n: number,
  1341. statusOf: (index: number) => FanStatus,
  1342. unlistedByPhase?: WorkflowRunState["unlistedByPhase"],
  1343. ) {
  1344. const actors: WorkflowRunState["actors"] = [];
  1345. const nodes: WorkflowRunState["nodes"] = [];
  1346. for (let i = 1; i <= n; i += 1) {
  1347. const status = statusOf(i);
  1348. actors.push({
  1349. siteId: "actor#1",
  1350. ordinal: i,
  1351. name: `reviewer-${i}`,
  1352. sessionId: `s-${i}`,
  1353. status: status === "running" ? "running" : status === "pending" ? "waiting" : "completed",
  1354. });
  1355. if (status === "pending") continue;
  1356. nodes.push({
  1357. siteId: "ask#1",
  1358. ordinal: i,
  1359. actorSiteId: "actor#1",
  1360. actorOrdinal: i,
  1361. ...(status === "running"
  1362. ? { phase: "executing" }
  1363. : { phase: "settled", outcome: status === "failed" ? "failed" : "ok" }),
  1364. } as WorkflowRunState["nodes"][number]);
  1365. }
  1366. return joined({
  1367. actors,
  1368. nodes,
  1369. usage: { spentTokens: 10, nodesUsed: nodes.length },
  1370. ...(unlistedByPhase === undefined ? {} : { truncated: true, unlistedByPhase }),
  1371. });
  1372. }
  1373. const mid = (i: number): FanStatus =>
  1374. i === 4 ? "failed" : i === 6 ? "running" : i === 7 ? "pending" : "done";
  1375. it("七个参与者按运行、失败和参与顺序钉住五枚,其余两位汇总", () => {
  1376. const view = renderBlockDom(fanoutToolCall(7), { workflowRun: fanoutRun(7, mid) });
  1377. const column = view.getByTestId("workflow-timeline-pills");
  1378. expect(column.getAttribute("data-station-roster")).toBe("true");
  1379. const pills = within(column).getAllByTestId("workflow-agent-pill");
  1380. expect(pills.map((pill) => pill.textContent)).toEqual([
  1381. "reviewer-6",
  1382. "reviewer-4",
  1383. "reviewer-1",
  1384. "reviewer-2",
  1385. "reviewer-3",
  1386. ]);
  1387. expect(pills.map((pill) => pill.getAttribute("data-agent-status"))).toEqual([
  1388. "running",
  1389. "failed",
  1390. "done",
  1391. "done",
  1392. "done",
  1393. ]);
  1394. const row = within(column).getByTestId("workflow-roster-more-row");
  1395. expect(row.getAttribute("data-more-count")).toBe("2");
  1396. expect(row.textContent).toBe("2 more");
  1397. expect(row.getAttribute("title")).toBe("2 more subagents · list everyone in the run pane");
  1398. // 叠上的脸按注意力序:pending 的 7 在 done 的 5 前面。
  1399. const faces = within(row)
  1400. .getByTestId("workflow-more-deck")
  1401. .querySelectorAll("[data-face-state]");
  1402. expect([...faces].map((face) => face.getAttribute("data-face-state"))).toEqual([
  1403. "waiting",
  1404. "content",
  1405. ]);
  1406. expect(within(row).queryByTestId("workflow-more-failed")).toBeNull();
  1407. // 表头照旧。
  1408. expect(view.getByTestId("workflow-card-detail").textContent).toContain("1 agent working");
  1409. });
  1410. // 表外的那些(docs/dynamic-workflow/presentation.md「Past six participants」):被归约淘汰的
  1411. // 子代理没有药丸也没有脸,但阈值、人数与红 ✕ 都算它们。
  1412. it("四枚药丸加三百个被淘汰的就是名册:药丸四枚、那一行说「还有 300 个」、红 ✕ 含表外失败的", () => {
  1413. const view = renderBlockDom(fanoutToolCall(4), {
  1414. workflowRun: fanoutRun(4, () => "running", [
  1415. { phaseName: "review", actors: 300, actorsSettled: 100, actorsFailed: 2, settled: 300 },
  1416. ]),
  1417. });
  1418. const column = view.getByTestId("workflow-timeline-pills");
  1419. expect(column.getAttribute("data-station-roster")).toBe("true");
  1420. expect(within(column).getAllByTestId("workflow-agent-pill")).toHaveLength(4);
  1421. const row = within(column).getByTestId("workflow-roster-more-row");
  1422. expect(row.getAttribute("data-more-count")).toBe("300");
  1423. expect(row.textContent).toContain("300 more");
  1424. expect(within(row).getByTestId("workflow-more-failed").textContent).toBe("2");
  1425. // 表外的没有脸:叠上一张都不该有。
  1426. expect(
  1427. within(row).getByTestId("workflow-more-deck").querySelectorAll("[data-face-state]"),
  1428. ).toHaveLength(0);
  1429. });
  1430. it("六个参与者仍是药丸列:没有名册", () => {
  1431. const view = renderBlockDom(fanoutToolCall(6), { workflowRun: fanoutRun(6, mid) });
  1432. const column = view.getByTestId("workflow-timeline-pills");
  1433. expect(column.getAttribute("data-station-roster")).toBeNull();
  1434. expect(within(column).getAllByTestId("workflow-agent-pill")).toHaveLength(6);
  1435. expect(view.queryByTestId("workflow-roster-more-row")).toBeNull();
  1436. });
  1437. it("失败多于五个:五枚红药丸之后那一行说藏了几个 failed", () => {
  1438. const view = renderBlockDom(fanoutToolCall(9), {
  1439. workflowRun: fanoutRun(9, (i) => (i <= 6 ? "failed" : "done")),
  1440. });
  1441. const column = view.getByTestId("workflow-timeline-pills");
  1442. const pills = within(column).getAllByTestId("workflow-agent-pill");
  1443. expect(pills.every((pill) => pill.getAttribute("data-agent-status") === "failed")).toBe(true);
  1444. const row = within(column).getByTestId("workflow-roster-more-row");
  1445. expect(row.getAttribute("data-more-count")).toBe("4");
  1446. expect(within(row).getByTestId("workflow-more-failed").textContent).toBe("1");
  1447. const faces = within(row)
  1448. .getByTestId("workflow-more-deck")
  1449. .querySelectorAll("[data-face-state]");
  1450. expect([...faces].map((face) => face.getAttribute("data-face-state"))).toEqual([
  1451. "sad",
  1452. "content",
  1453. "content",
  1454. ]);
  1455. });
  1456. it("那一行与站头交出站 id:开 run 详情、落到这一站;没有回调时那一行是静态的", () => {
  1457. const onOpenWorkflowRun = vi.fn();
  1458. const view = renderBlockDom(fanoutToolCall(60), {
  1459. onOpenWorkflowRun,
  1460. workflowRun: fanoutRun(60, () => "done"),
  1461. });
  1462. const row = view.getByTestId("workflow-roster-more-row");
  1463. expect(row.tagName).toBe("BUTTON");
  1464. expect(row.getAttribute("data-more-count")).toBe("55");
  1465. fireEvent.click(row);
  1466. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  1467. workflowName: "bug-scan",
  1468. phaseId: "phase#a",
  1469. });
  1470. // 站头(有回调时是按钮,title = 站名)同一条路。
  1471. fireEvent.click(view.getByTitle("review"));
  1472. expect(onOpenWorkflowRun).toHaveBeenCalledTimes(2);
  1473. expect(onOpenWorkflowRun).toHaveBeenLastCalledWith({
  1474. workflowName: "bug-scan",
  1475. phaseId: "phase#a",
  1476. });
  1477. cleanup();
  1478. const inert = renderBlockDom(fanoutToolCall(60), { workflowRun: fanoutRun(60, () => "done") });
  1479. expect(inert.getByTestId("workflow-roster-more-row").tagName).toBe("SPAN");
  1480. });
  1481. it("静态卡(无 run):`many` 卡还是一枚药丸;字面量基数的成员卡过了阈值是五枚 + 静态的「还有 3 个」", () => {
  1482. expect(renderBlock(fanoutToolCall(8))).not.toContain("data-station-roster");
  1483. const members = {
  1484. ...FANOUT_GRAPH,
  1485. participants: Array.from({ length: 8 }, (_, i) => ({
  1486. id: `phase#a:actor#1[${i}]`,
  1487. phase: "phase#a",
  1488. lane: "actor#1",
  1489. steps: ["ask#1"],
  1490. member: { index: i, of: 8 },
  1491. })),
  1492. };
  1493. const html = renderBlock({
  1494. input: { name: "bug-scan", script: 'phase("review");' },
  1495. raw: { display: { ...OK_DISPLAY, causalityGraph: members } },
  1496. });
  1497. expect(html).toContain('data-station-roster="true"');
  1498. expect(html).toContain('data-more-count="3"');
  1499. expect(html).toContain('<span aria-label="3 more subagents · list everyone in the run pane"');
  1500. });
  1501. it("zh-CN:「还有 n 个」与整句 title", () => {
  1502. const view = renderBlockDom(
  1503. fanoutToolCall(60),
  1504. { workflowRun: fanoutRun(60, () => "done") },
  1505. "zh-CN",
  1506. );
  1507. const row = view.getByTestId("workflow-roster-more-row");
  1508. expect(row.textContent).toBe("还有 55 个");
  1509. expect(row.getAttribute("title")).toBe("还有 55 个子代理 · 在运行侧栏里列出全部");
  1510. });
  1511. });
  1512. // ── AmendWorkflow 行(docs/dynamic-workflow/presentation.md「The tool row」第二张表)──
  1513. // 同一个渲染器换修订词汇:编写中「正在调整工作流」、待确认「等待调整确认」、编不过 / 静态卡
  1514. // 「工作流调整」;卡体多一行「调整 run X」。display 仍是 create_workflow,图与草稿笔一份实现。
  1515. describe("CreateWorkflowToolCallBlock as AmendWorkflow", () => {
  1516. const DRAFT = 'phase("plan");\nconst planner = agent("planner");\nphase("ver';
  1517. const AMEND_INPUT = { name: "Research pipeline", script: DRAFT, run_id: "dwfrun-prev" };
  1518. it.each([
  1519. ["en-US", "Amending workflow"],
  1520. ["zh-CN", "正在调整工作流"],
  1521. ] as const)("writing: %s", (locale, word) => {
  1522. const view = renderBlockDom(
  1523. {
  1524. kind: "AmendWorkflow",
  1525. input: AMEND_INPUT,
  1526. raw: { v4Status: "inputStreaming" },
  1527. status: "running",
  1528. },
  1529. { isRunning: true },
  1530. locale,
  1531. );
  1532. expect(view.container.textContent).toContain(word);
  1533. expect(view.container.textContent).not.toContain("Writing workflow");
  1534. // 草稿笔照旧:站从半截脚本里扫出来。
  1535. expect(view.getByTestId("workflow-draft-timeline")).toBeTruthy();
  1536. });
  1537. it.each([
  1538. ["en-US", "Awaiting amendment confirmation"],
  1539. ["zh-CN", "等待调整确认"],
  1540. ] as const)("awaiting confirmation: %s", (locale, word) => {
  1541. const view = renderBlockDom(
  1542. {
  1543. kind: "AmendWorkflow",
  1544. ...LOOP_TOOL_CALL,
  1545. input: { ...(LOOP_TOOL_CALL.input as object), run_id: "dwfrun-prev" },
  1546. raw: { ...(LOOP_TOOL_CALL.raw as object), v4Status: "pendingApproval" },
  1547. status: "running",
  1548. },
  1549. { isRunning: true },
  1550. locale,
  1551. );
  1552. expect(view.container.textContent).toContain(word);
  1553. });
  1554. it.each([
  1555. ["en-US", "Workflow amendment", "Amends run"],
  1556. ["zh-CN", "工作流调整", "调整 run"],
  1557. ] as const)("static card: kind word and the lineage row: %s", (locale, word, amends) => {
  1558. const view = renderBlockDom(
  1559. {
  1560. kind: "AmendWorkflow",
  1561. ...LOOP_TOOL_CALL,
  1562. input: { ...(LOOP_TOOL_CALL.input as object), run_id: "dwfrun-prev" },
  1563. },
  1564. {},
  1565. locale,
  1566. );
  1567. expect(view.getByTestId("workflow-card-kind").textContent).toBe(word);
  1568. const lineage = view.container.querySelector('[data-workflow-card-amends="true"]');
  1569. expect(lineage?.textContent).toContain(amends);
  1570. expect(lineage?.textContent).toContain("dwfrun-prev");
  1571. });
  1572. it("compile errors: the feedback row says「Amendment draft」, not the create word", () => {
  1573. const view = renderBlockDom({
  1574. kind: "AmendWorkflow",
  1575. input: AMEND_INPUT,
  1576. raw: {
  1577. display: {
  1578. kind: "create_workflow",
  1579. ok: false,
  1580. errorCount: 1,
  1581. diagnostics: [{ line: 1, column: 1, code: 2322, message: "Type error" }],
  1582. },
  1583. },
  1584. status: "failed",
  1585. });
  1586. expect(view.container.querySelector(".tool-summary-kind-label")?.textContent).toBe(
  1587. "Amendment draft",
  1588. );
  1589. expect(view.container.textContent).not.toContain("Amending workflow");
  1590. expect(view.container.textContent).not.toContain("Workflow draft");
  1591. });
  1592. it("from draft 2 on the streaming amend row says「Revising amendment」", () => {
  1593. const view = renderBlockDom(
  1594. {
  1595. kind: "AmendWorkflow",
  1596. input: AMEND_INPUT,
  1597. raw: { v4Status: "inputStreaming" },
  1598. status: "running",
  1599. },
  1600. { isRunning: true, workflowDraft: { ordinal: 2, superseded: false } },
  1601. );
  1602. expect(view.container.textContent).toContain("Revising amendment");
  1603. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 2");
  1604. });
  1605. // 省略 script 的修订(docs/dynamic-workflow/presentation.md「The tool row」):行上的入参是模型发出的
  1606. // 那一份,脚本是之后才回填的,所以卡上没有脚本可折叠。lineage 行说「脚本不变」,「未提供脚本」的
  1607. // 提示不出现——缺脚本正是这次调用的用意,不是故障。
  1608. const SETTINGS_ONLY_INPUT = { run_id: "dwfrun-prev", max_concurrency: 2 };
  1609. it.each([
  1610. ["en-US", "Amends run", "script unchanged"],
  1611. ["zh-CN", "调整 run", "脚本不变"],
  1612. ] as const)("static card of an amend that kept the script: %s", (locale, amends, unchanged) => {
  1613. const view = renderBlockDom(
  1614. { kind: "AmendWorkflow", input: SETTINGS_ONLY_INPUT, raw: LOOP_TOOL_CALL.raw },
  1615. {},
  1616. locale,
  1617. );
  1618. const lineage = view.container.querySelector('[data-workflow-card-amends="true"]');
  1619. expect(lineage?.textContent).toContain(amends);
  1620. expect(lineage?.textContent).toContain("dwfrun-prev");
  1621. expect(lineage?.textContent).toContain(unchanged);
  1622. expect(lineage?.getAttribute("data-workflow-card-amends-script-inherited")).toBe("true");
  1623. // 图照常画(display 来自回填后的脚本),但没有脚本折叠、也没有「未提供脚本」。
  1624. expect(view.getByTestId("workflow-timeline")).toBeTruthy();
  1625. expect(view.queryByTestId("workflow-card-script-toggle")).toBeNull();
  1626. expect(view.container.textContent).not.toContain("No workflow script provided.");
  1627. });
  1628. it("an amend that kept the script and has no display still shows no 'no script' notice", () => {
  1629. const view = renderBlockDom({ kind: "AmendWorkflow", input: SETTINGS_ONLY_INPUT, raw: {} });
  1630. expect(view.container.textContent).not.toContain("No workflow script provided.");
  1631. const lineage = view.container.querySelector('[data-workflow-card-amends="true"]');
  1632. expect(lineage?.textContent).toContain("script unchanged");
  1633. });
  1634. it("a static amend card that passed a script says nothing about the script", () => {
  1635. const view = renderBlockDom({
  1636. kind: "AmendWorkflow",
  1637. ...LOOP_TOOL_CALL,
  1638. input: { ...(LOOP_TOOL_CALL.input as object), run_id: "dwfrun-prev" },
  1639. });
  1640. const lineage = view.container.querySelector('[data-workflow-card-amends="true"]');
  1641. expect(lineage?.textContent).not.toContain("script unchanged");
  1642. expect(lineage?.getAttribute("data-workflow-card-amends-script-inherited")).toBeNull();
  1643. expect(view.getByTestId("workflow-card-script-toggle")).toBeTruthy();
  1644. });
  1645. it("an input trimmed to a snapshot preview is not read as a kept script", () => {
  1646. // 首屏快照把大入参裁成预览时,缺的是字节而不是脚本:不能把一个传了脚本的修订说成「脚本不变」。
  1647. const view = renderBlockDom({
  1648. kind: "AmendWorkflow",
  1649. input: { run_id: "dwfrun-prev" },
  1650. raw: LOOP_TOOL_CALL.raw,
  1651. snapshotRefs: [{ field: "input", previewBytes: 64, fullBytes: 40_000 }],
  1652. });
  1653. const lineage = view.container.querySelector('[data-workflow-card-amends="true"]');
  1654. expect(lineage?.textContent).toContain("dwfrun-prev");
  1655. expect(lineage?.textContent).not.toContain("script unchanged");
  1656. });
  1657. it("while the input streams nothing is said: the script may still be on its way", () => {
  1658. const view = renderBlockDom(
  1659. {
  1660. kind: "AmendWorkflow",
  1661. input: { run_id: "dwfrun-prev" },
  1662. raw: { v4Status: "inputStreaming" },
  1663. status: "running",
  1664. },
  1665. { isRunning: true },
  1666. );
  1667. expect(view.container.textContent).toContain("Amending workflow");
  1668. expect(view.container.textContent).not.toContain("script unchanged");
  1669. });
  1670. it("readWorkflowAmendScriptInherited: the resolved flag, or a finished input with neither script source", () => {
  1671. // 确认窗:CLI 回填过的入参带脚本,flag 说话。
  1672. expect(
  1673. readWorkflowAmendScriptInherited({
  1674. run_id: "r",
  1675. script: "x",
  1676. predecessor: { status: "completed", script_inherited: true },
  1677. }),
  1678. ).toBe(true);
  1679. // 聊天卡:模型发出的入参里没有脚本。
  1680. expect(readWorkflowAmendScriptInherited({ run_id: "r", max_concurrency: 2 })).toBe(true);
  1681. // 给了脚本、flag 不在:不是沿用。
  1682. expect(
  1683. readWorkflowAmendScriptInherited({
  1684. run_id: "r",
  1685. script: "x",
  1686. predecessor: { status: "completed" },
  1687. }),
  1688. ).toBe(false);
  1689. // `path` 修订(docs/dynamic-workflow/launch.md「Script files」的常态)同样不带 `script`,但它交上来的
  1690. // 是一份**改过的**脚本:说「脚本不变」就是对用户撒谎。
  1691. expect(
  1692. readWorkflowAmendScriptInherited({ run_id: "r", path: ".zcode/workflow-drafts/x.dwf.ts" }),
  1693. ).toBe(false);
  1694. // 沿用脚本且前驱的文件仍可记:回填的入参同时带 `path` 与 flag,flag 说了算。
  1695. expect(
  1696. readWorkflowAmendScriptInherited({
  1697. run_id: "r",
  1698. script: "x",
  1699. path: "/abs/.zcode/workflow-drafts/x.dwf.ts",
  1700. predecessor: { status: "completed", script_inherited: true },
  1701. }),
  1702. ).toBe(true);
  1703. // 非记录的入参(快照被裁掉、形状不明)什么都不断言。
  1704. expect(readWorkflowAmendScriptInherited(undefined)).toBe(false);
  1705. expect(readWorkflowAmendScriptInherited("{}")).toBe(false);
  1706. });
  1707. it("a CreateWorkflow row never grows a lineage row", () => {
  1708. const view = renderBlockDom(LOOP_TOOL_CALL);
  1709. expect(view.container.querySelector('[data-workflow-card-amends="true"]')).toBeNull();
  1710. });
  1711. it("readWorkflowKindMessageId switches to the amend vocabulary", () => {
  1712. expect(readWorkflowKindMessageId({ v4Status: "inputStreaming" }, true, true)).toBe(
  1713. "chat.toolCall.workflow.amend.writing",
  1714. );
  1715. expect(readWorkflowKindMessageId({ v4Status: "pendingApproval" }, true, true)).toBe(
  1716. "chat.toolCall.workflow.amend.awaitingConfirmation",
  1717. );
  1718. // 校验中与创建同一个词。
  1719. expect(readWorkflowKindMessageId({ v4Status: "running" }, true, true)).toBe(
  1720. "chat.toolCall.workflow.running",
  1721. );
  1722. expect(readWorkflowKindMessageId(undefined, false, true)).toBe(
  1723. "chat.toolCall.workflow.amend.ran",
  1724. );
  1725. });
  1726. // ── 就地生效的修订(docs/dynamic-workflow/concurrency.md)────────────────────────────
  1727. // 只改并发上限、run 又在飞时这次调用不编译、不铸新 run,结果连 display 都没有——整行退成设置行
  1728. // 是接线层(ConversationRowView)按入参形状裁的,见本文件末尾那一节。这里只钉渲染器这一侧:
  1729. // 在途的那几个词不能说「校验」,因为这种调用什么都不编译。
  1730. it("只改并发上限的调用在途时不说「正在校验」,从头到尾说「正在调整工作流」", () => {
  1731. expect(readWorkflowKindMessageId({ v4Status: "running" }, true, true, true)).toBe(
  1732. "chat.toolCall.workflow.amend.writing",
  1733. );
  1734. expect(readWorkflowKindMessageId({ v4Status: "inputStreaming" }, true, true, true)).toBe(
  1735. "chat.toolCall.workflow.amend.writing",
  1736. );
  1737. // 带脚本的修订不受影响:校验是真发生的。
  1738. expect(readWorkflowKindMessageId({ v4Status: "running" }, true, true, false)).toBe(
  1739. "chat.toolCall.workflow.running",
  1740. );
  1741. });
  1742. it.each([
  1743. [
  1744. { run_id: "r", max_concurrency: 4 },
  1745. { runId: "r", requested: 4 },
  1746. ],
  1747. [
  1748. { run_id: "r", max_concurrency: null },
  1749. { runId: "r", requested: null },
  1750. ],
  1751. // 带了脚本来源:这次修订要编译,不是就地生效的形状。
  1752. [{ run_id: "r", max_concurrency: 4, script: "phase('a')" }, undefined],
  1753. [{ run_id: "r", max_concurrency: 4, path: ".zcode/workflow-drafts/x.dwf.ts" }, undefined],
  1754. // 还改了模型或名字:那要换一条 run,不是就地生效。
  1755. [{ run_id: "r", max_concurrency: 4, subagent_model: "zhipu/glm-5.3" }, undefined],
  1756. [{ run_id: "r", max_concurrency: 4, name: "Research pipeline" }, undefined],
  1757. // 只有 run_id(脚本可能还在路上):不作判断。
  1758. [{ run_id: "r" }, undefined],
  1759. [{ max_concurrency: 4 }, undefined],
  1760. ["{}", undefined],
  1761. ])("readWorkflowRetuneCall %#", (input, expected) => {
  1762. expect(readWorkflowRetuneCall(input)).toEqual(expected);
  1763. });
  1764. it("在途的只改并发上限调用:行上说「正在调整工作流」,不说校验", () => {
  1765. const view = renderBlockDom(
  1766. {
  1767. kind: "AmendWorkflow",
  1768. input: { run_id: "dwfrun-prev", max_concurrency: 4 },
  1769. raw: { v4Status: "running" },
  1770. status: "running",
  1771. },
  1772. { isRunning: true },
  1773. );
  1774. expect(view.container.textContent).toContain("Amending workflow");
  1775. expect(view.container.textContent).not.toContain("Validating workflow");
  1776. });
  1777. });
  1778. // ── 接线(docs/dynamic-workflow/authoring.md「How the user sees them」)──
  1779. // 上面钉的是药丸把**产物 id** 交给上一层;这里钉 `ConversationRowView` 把 id 变成什么样的打开
  1780. // 请求。走到这张卡的是**没有被轮尾摘要接管**的那条路(联接到 run 但工具调用本身报错),联接到
  1781. // run 且成功的行只画一条 `WorkflowToolSummary`,卡在轮尾。
  1782. describe("ConversationRowView 把工具卡的产物药丸变成打开请求", () => {
  1783. const RUN = {
  1784. runId: "run-7",
  1785. toolCallId: "tool-5",
  1786. status: "completed",
  1787. usage: { spentTokens: 12, nodesUsed: 1 },
  1788. actors: [{ siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "completed" }],
  1789. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" }],
  1790. artifacts: [
  1791. { id: "book", kind: "file", title: "Audit report", version: 2, contentType: "text/html" },
  1792. { id: "perf", kind: "chart", title: "Round timings", version: 1 },
  1793. ],
  1794. lastEventSequence: 3,
  1795. } as unknown as WorkflowRunState;
  1796. function renderRow(onOpenWorkflowArtifact: (request: unknown) => void) {
  1797. // 代码块桩会吃掉 matchMedia 的读者,但正文渲染器仍会问一次;jsdom 没有它。
  1798. Object.defineProperty(window, "matchMedia", {
  1799. configurable: true,
  1800. writable: true,
  1801. value: vi.fn(() => ({
  1802. matches: false,
  1803. addEventListener: vi.fn(),
  1804. removeEventListener: vi.fn(),
  1805. addListener: vi.fn(),
  1806. removeListener: vi.fn(),
  1807. })),
  1808. });
  1809. return render(
  1810. createElement(
  1811. ZCodeIntlProvider,
  1812. { initialLocale: "en-US" },
  1813. createElement(
  1814. PlatformProvider,
  1815. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 这条路径不碰平台服务。
  1816. { platform: {} as any },
  1817. createElement(ConversationRowView, {
  1818. row: {
  1819. rowId: 5,
  1820. turnId: "turn-1",
  1821. createdAt: 1_700_000_000_005,
  1822. createdAtSeq: 5,
  1823. kind: "toolCall",
  1824. toolCallId: "tool-5",
  1825. toolName: "CreateWorkflow",
  1826. // 成功的发起行被轮尾摘要接管,画不出这张卡;报错的行才落回完整工具卡。
  1827. status: "error",
  1828. input: { name: "implement-verify", script: "phase('a')" },
  1829. inputText: "{}",
  1830. output: {
  1831. text: "ok",
  1832. display: {
  1833. kind: "create_workflow",
  1834. ok: true,
  1835. errorCount: 0,
  1836. diagnostics: [],
  1837. causalityGraph: {
  1838. steps: [
  1839. {
  1840. id: "ask#1",
  1841. kind: "ask",
  1842. label: "plan",
  1843. line: 2,
  1844. column: 21,
  1845. lane: "actor#1",
  1846. },
  1847. ],
  1848. lanes: [{ id: "actor#1", name: "planner", line: 1, column: 11 }],
  1849. participants: [
  1850. {
  1851. id: "unphased:actor#1",
  1852. phase: "unphased",
  1853. lane: "actor#1",
  1854. steps: ["ask#1"],
  1855. },
  1856. ],
  1857. handoffs: [],
  1858. },
  1859. },
  1860. },
  1861. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 只填 renderer 读取的字段。
  1862. } as any,
  1863. context: {
  1864. workspacePath: "/workspace",
  1865. theme: "system",
  1866. sessionId: "parent-a",
  1867. onOpenWorkflowArtifact,
  1868. workflowRunByToolCallId: new Map([
  1869. [
  1870. "tool-5",
  1871. {
  1872. runId: "run-7",
  1873. toolCallId: "tool-5",
  1874. status: "completed",
  1875. nodesSettled: 1,
  1876. nodesTotal: 1,
  1877. run: RUN,
  1878. },
  1879. ],
  1880. ]),
  1881. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 同上。
  1882. } as any,
  1883. }),
  1884. ),
  1885. ),
  1886. );
  1887. }
  1888. it("带上展示名与 contentType(宿主据它把 html 产物直接开成浏览器 tab)", () => {
  1889. const spy = vi.fn();
  1890. const view = renderRow(spy);
  1891. fireEvent.click(view.getAllByTestId("workflow-card-artifact")[0]!);
  1892. expect(spy).toHaveBeenCalledWith({
  1893. parentSessionId: "parent-a",
  1894. runId: "run-7",
  1895. artifactId: "book",
  1896. title: "Audit report",
  1897. contentType: "text/html",
  1898. });
  1899. });
  1900. // 就地生效的修订行(docs/dynamic-workflow/concurrency.md):结果没有 display、也没有铸新 run,
  1901. // 所以判据全在入参形状上。默认并发从被调整那条 run 的投影读(run.concurrencyCeiling)。
  1902. function renderRetuneRow(
  1903. input: unknown,
  1904. options: {
  1905. ceiling?: number;
  1906. onOpenWorkflowRun?: (request: unknown) => void;
  1907. /** 退回真修订的那一条:编译过,所以有 display。 */
  1908. display?: unknown;
  1909. /** 同上:它铸了一条新 run,按**本行的** toolCallId 联接得上。 */
  1910. joinedByToolCallId?: boolean;
  1911. status?: string;
  1912. } = {},
  1913. ) {
  1914. Object.defineProperty(window, "matchMedia", {
  1915. configurable: true,
  1916. writable: true,
  1917. value: vi.fn(() => ({
  1918. matches: false,
  1919. addEventListener: vi.fn(),
  1920. removeEventListener: vi.fn(),
  1921. addListener: vi.fn(),
  1922. removeListener: vi.fn(),
  1923. })),
  1924. });
  1925. return render(
  1926. createElement(
  1927. ZCodeIntlProvider,
  1928. { initialLocale: "en-US" },
  1929. createElement(
  1930. PlatformProvider,
  1931. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 这条路径不碰平台服务。
  1932. { platform: {} as any },
  1933. createElement(ConversationRowView, {
  1934. row: {
  1935. rowId: 9,
  1936. turnId: "turn-1",
  1937. createdAt: 1_700_000_000_009,
  1938. createdAtSeq: 9,
  1939. kind: "toolCall",
  1940. toolCallId: "tool-9",
  1941. toolName: "AmendWorkflow",
  1942. status: options.status ?? "success",
  1943. input,
  1944. inputText: "{}",
  1945. // 就地生效的结果只有一句话:没有 display。
  1946. output: {
  1947. text: "Applied to the running run run-7; at most 4 subagents run at once.",
  1948. ...(options.display === undefined ? {} : { display: options.display }),
  1949. },
  1950. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 只填 renderer 读取的字段。
  1951. } as any,
  1952. context: {
  1953. workspacePath: "/workspace",
  1954. theme: "system",
  1955. sessionId: "parent-a",
  1956. onOpenWorkflowRun: options.onOpenWorkflowRun,
  1957. // 本行的 toolCallId 查不到任何 run(它没铸新 run);那条 run 按 runId 才在。
  1958. workflowRunByToolCallId: options.joinedByToolCallId
  1959. ? new Map([
  1960. [
  1961. "tool-9",
  1962. {
  1963. runId: "run-8",
  1964. toolCallId: "tool-9",
  1965. status: "running",
  1966. nodesSettled: 0,
  1967. nodesTotal: 1,
  1968. },
  1969. ],
  1970. ])
  1971. : new Map(),
  1972. workflowRunByRunId: new Map([
  1973. [
  1974. "run-7",
  1975. {
  1976. runId: "run-7",
  1977. toolCallId: "tool-5",
  1978. status: "running",
  1979. nodesSettled: 0,
  1980. nodesTotal: 1,
  1981. ...(options.ceiling === undefined
  1982. ? {}
  1983. : { run: { runId: "run-7", concurrencyCeiling: options.ceiling } }),
  1984. },
  1985. ],
  1986. ]),
  1987. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 同上。
  1988. } as any,
  1989. }),
  1990. ),
  1991. ),
  1992. );
  1993. }
  1994. it("就地生效的修订行退成设置行:点它开那条 run,带发起行的 toolCallId", () => {
  1995. const onOpenWorkflowRun = vi.fn();
  1996. const view = renderRetuneRow(
  1997. { run_id: "run-7", max_concurrency: 4 },
  1998. { ceiling: 13, onOpenWorkflowRun },
  1999. );
  2000. // 卡没了,只剩那一行;「已通过校验」「脚本不变」一个字都不在。
  2001. expect(view.queryByTestId("workflow-card")).toBeNull();
  2002. const row = view.getByTestId("workflow-retune-row");
  2003. expect(row.textContent).toContain("Settings changed");
  2004. expect(row.textContent).toContain("at most 4 at once");
  2005. for (const gone of ["compiled", "Amends run", "script unchanged"]) {
  2006. expect(view.container.textContent).not.toContain(gone);
  2007. }
  2008. fireEvent.click(row);
  2009. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  2010. parentSessionId: "parent-a",
  2011. toolCallId: "tool-5",
  2012. runId: "run-7",
  2013. });
  2014. });
  2015. // 默认并发 D(run.concurrencyCeiling)是起点不是上限:请求值正好等于 D 与 null 都是「解除本 run
  2016. // 自己的界」,高于或低于 D 的数照念。
  2017. it.each([
  2018. ["请求高于默认", { run_id: "run-7", max_concurrency: 40 }, 13, "at most 40 at once"],
  2019. ["请求正好是默认", { run_id: "run-7", max_concurrency: 13 }, 13, "limit back to the default"],
  2020. [
  2021. "解除上限(null)",
  2022. { run_id: "run-7", max_concurrency: null },
  2023. 13,
  2024. "limit back to the default",
  2025. ],
  2026. ["请求低于默认", { run_id: "run-7", max_concurrency: 4 }, 13, "at most 4 at once"],
  2027. // 默认未知(那条 run 已被淘汰出投影):只能照念请求值。
  2028. ["默认未知", { run_id: "run-7", max_concurrency: 4 }, undefined, "at most 4 at once"],
  2029. ])("%s", (_case, input, ceiling, text) => {
  2030. const view = renderRetuneRow(input, ceiling === undefined ? {} : { ceiling });
  2031. expect(view.getByTestId("workflow-retune-row").textContent).toContain(text);
  2032. });
  2033. it("宿主没给打开回调(只读面):还是那一行,只是点不动", () => {
  2034. const view = renderRetuneRow({ run_id: "run-7", max_concurrency: 4 }, { ceiling: 13 });
  2035. expect(view.getByTestId("workflow-retune-row").tagName).not.toBe("BUTTON");
  2036. });
  2037. // run 已结算时同一个调用退回一次**真修订**:它编译过(有 display)、也铸出一条按本行 toolCallId
  2038. // 联接得上的 run。两条判据各自都足以把它挡在设置行之外——这里各钉一条。
  2039. it("退回真修订(有 display、有按 toolCallId 联接的 run):照旧走运行摘要,不退成设置行", () => {
  2040. const view = renderRetuneRow(
  2041. { run_id: "run-7", max_concurrency: 4 },
  2042. {
  2043. ceiling: 13,
  2044. joinedByToolCallId: true,
  2045. display: { kind: "create_workflow", ok: true, errorCount: 0, diagnostics: [] },
  2046. },
  2047. );
  2048. expect(view.queryByTestId("workflow-retune-row")).toBeNull();
  2049. });
  2050. it("只有 display(还没联接到 run)也不退成设置行:编译过就不是就地生效", () => {
  2051. const view = renderRetuneRow(
  2052. { run_id: "run-7", max_concurrency: 4 },
  2053. {
  2054. ceiling: 13,
  2055. display: { kind: "create_workflow", ok: true, errorCount: 0, diagnostics: [] },
  2056. },
  2057. );
  2058. expect(view.queryByTestId("workflow-retune-row")).toBeNull();
  2059. expect(view.queryByTestId("workflow-card")).not.toBeNull();
  2060. });
  2061. it("工具报错(拒绝也是 tool error):照旧走错误渲染", () => {
  2062. const view = renderRetuneRow({ run_id: "run-7", max_concurrency: 4 }, { status: "error" });
  2063. expect(view.queryByTestId("workflow-retune-row")).toBeNull();
  2064. });
  2065. it("活投影那份摘要上没有 contentType 的那一枚不编一个出来(它也从不带 sourcePath)", () => {
  2066. const spy = vi.fn();
  2067. const view = renderRow(spy);
  2068. fireEvent.click(view.getAllByTestId("workflow-card-artifact")[1]!);
  2069. expect(spy).toHaveBeenCalledWith({
  2070. parentSessionId: "parent-a",
  2071. runId: "run-7",
  2072. artifactId: "perf",
  2073. title: "Round timings",
  2074. });
  2075. });
  2076. });
  2077. // ── 接线:行上下文的稿号联接表 → 编译反馈行(docs/dynamic-workflow/presentation.md「Compiler feedback」)──
  2078. // 稿号由宿主从行窗口一遍建成(`workflowDraftJoin.ts`);这里钉 `ConversationRowView` 按 toolCallId 把
  2079. // 这一行自己的位置交给卡片,而不是让卡片自己去翻行窗口。
  2080. describe("ConversationRowView 把稿号交给编译反馈行", () => {
  2081. function renderFeedbackRow(context: Record<string, unknown>) {
  2082. Object.defineProperty(window, "matchMedia", {
  2083. configurable: true,
  2084. writable: true,
  2085. value: vi.fn(() => ({
  2086. matches: false,
  2087. addEventListener: vi.fn(),
  2088. removeEventListener: vi.fn(),
  2089. addListener: vi.fn(),
  2090. removeListener: vi.fn(),
  2091. })),
  2092. });
  2093. return render(
  2094. createElement(
  2095. ZCodeIntlProvider,
  2096. { initialLocale: "en-US" },
  2097. createElement(
  2098. PlatformProvider,
  2099. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 这条路径不碰平台服务。
  2100. { platform: {} as any },
  2101. createElement(ConversationRowView, {
  2102. row: {
  2103. rowId: 9,
  2104. turnId: "turn-1",
  2105. createdAt: 1_700_000_000_009,
  2106. createdAtSeq: 9,
  2107. kind: "toolCall",
  2108. toolCallId: "tool-9",
  2109. toolName: "CreateWorkflow",
  2110. status: "success",
  2111. input: { name: "Release notes digest", script: "const x: number = 'nope';" },
  2112. inputText: "{}",
  2113. output: {
  2114. text: "The workflow script has errors:",
  2115. display: {
  2116. kind: "create_workflow",
  2117. ok: false,
  2118. errorCount: 1,
  2119. diagnostics: [{ line: 1, column: 7, code: 2322, message: "Type error" }],
  2120. },
  2121. },
  2122. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 只填 renderer 读取的字段。
  2123. } as any,
  2124. context: {
  2125. workspacePath: "/workspace",
  2126. theme: "system",
  2127. sessionId: "parent-a",
  2128. ...context,
  2129. // eslint-disable-next-line @typescript-eslint/no-explicit-any -- 同上。
  2130. } as any,
  2131. }),
  2132. ),
  2133. ),
  2134. );
  2135. }
  2136. it("联接表里有这一行:稿号与被替代的灯随行上下文到达卡片", () => {
  2137. const view = renderFeedbackRow({
  2138. workflowDraftByToolCallId: new Map([["tool-9", { ordinal: 3, superseded: true }]]),
  2139. });
  2140. expect(view.getByTestId("workflow-draft-ordinal").textContent).toBe("draft 3");
  2141. expect(view.getByTestId("workflow-draft-lamp").getAttribute("data-draft-lamp")).toBe("settled");
  2142. });
  2143. it("联接表缺席(只读分享等宿主):不编号,灯保持警示色", () => {
  2144. const view = renderFeedbackRow({});
  2145. expect(view.queryByTestId("workflow-draft-ordinal")).toBeNull();
  2146. expect(view.getByTestId("workflow-draft-lamp").getAttribute("data-draft-lamp")).toBe("open");
  2147. });
  2148. });