workflowRunSidePane.test.ts 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260
  1. // @vitest-environment jsdom
  2. // dwf run 详情页(docs/dynamic-workflow/presentation.md「The run pane」):状态头 / 用量行 / Cancel /
  3. // 结果与失败面板 / 待答问题 / 产物 / 空态,双语言。
  4. //
  5. // 2026-09-04 用户指令:Results(`report` 条目)、事件日志、Script 三节已从面板撤走(技术细节,
  6. // 不给用户看),对应的用例整段删除;journal 的读面没有变化,只是这块面板不再显示它们。
  7. //
  8. // 纯规则(Cancel 可用性、结果判定、事件摘要)在 workflowRunPanel.test.ts 里穷举;
  9. // 这里只钉「那些结果真的接到了 DOM 上」以及交互(点击 Cancel 发出哪条命令)。
  10. import { createElement, type ReactNode } from "react";
  11. import { act, cleanup, fireEvent, render, waitFor, within } from "@testing-library/react";
  12. import { beforeEach, describe, expect, it, vi } from "vitest";
  13. import { TID_WORKFLOW_ARTIFACTS_SECTION, TID_WORKFLOW_ARTIFACT_CARD } from "@zcode/shared";
  14. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  15. import type { WorkflowRunSidePaneTab } from "@/lib/workspaceSidePane.js";
  16. vi.mock("@/logger.js", () => ({
  17. logger: { debug: vi.fn(), warn: vi.fn() },
  18. }));
  19. // 提示只渲染 children(不改 DOM 形状),但把 title / description 记下来:Stop 钮的第二行
  20. // 「停下的运行可以恢复」只活在提示里。
  21. const tooltips = vi.hoisted(() => ({
  22. calls: [] as Array<{ title: unknown; description?: string }>,
  23. }));
  24. vi.mock("@/ControlHintTooltip.js", () => ({
  25. ControlHintTooltip: ({
  26. children,
  27. title,
  28. description,
  29. }: {
  30. children?: ReactNode;
  31. title?: unknown;
  32. description?: string;
  33. }) => {
  34. tooltips.calls.push({ title, ...(description === undefined ? {} : { description }) });
  35. return children;
  36. },
  37. }));
  38. const sendCommand = vi.fn(async () => ({ status: "accepted" }) as never);
  39. const release = vi.fn();
  40. // layer 必须是**稳定引用**:组件的租约 effect 以 layer 为依赖,每次渲染换一个新对象
  41. // 会让 acquire → setLease → 重渲染 → 新 layer 无限循环(生产里 useV4Conversation
  42. // 返回的是 useMemo 过的 bundle,本来就稳定)。
  43. const layer = { acquire: vi.fn(() => ({ release })) };
  44. const workflowRunsQuery = vi.fn<() => Promise<{ runs: unknown[] }>>(async () => ({ runs: [] }));
  45. // 产物(docs/dynamic-workflow/authoring.md):清单走 journal 查询,看板条目走取数查询。
  46. // 两条都在这里桩掉——面板挂载时无条件问一次清单(活投影不带 spec 与版本历史)。
  47. const workflowRunArtifactsQuery = vi.fn<() => Promise<{ artifacts: unknown[] }>>(async () => ({
  48. artifacts: [],
  49. }));
  50. const workflowRunArtifactDataQuery = vi.fn<() => Promise<{ items: unknown[]; hasMore: boolean }>>(
  51. async () => ({ items: [], hasMore: false }),
  52. );
  53. const conversation = {
  54. layer,
  55. sendCommand,
  56. workflowRuns: workflowRunsQuery,
  57. workflowRunArtifacts: workflowRunArtifactsQuery,
  58. workflowRunArtifactData: workflowRunArtifactDataQuery,
  59. };
  60. vi.mock("@/v4/V4ConversationContext.js", () => ({
  61. V4PaneConversationProvider: ({ children }: { children: ReactNode }) => children,
  62. useV4Conversation: () => conversation,
  63. }));
  64. let snapshot: unknown = null;
  65. vi.mock("@/v4/useConversationProjection.js", () => ({
  66. useConversationProjection: () => ({ snapshot }),
  67. }));
  68. // 「配置」弹层的模型清单(docs/dynamic-workflow/presentation.md「The settings popover」):面板本身不读它,
  69. // 只有弹层打开时才订阅;给一份空清单即可(字段本身在 workflowRunSettingsPopover.test.ts 里钉)。
  70. vi.mock("@/hooks/useModelSelectionView.js", () => ({
  71. useModelSelectionView: () => ({
  72. state: { status: "ready", view: { revision: 1, providers: [] } },
  73. reload: vi.fn(),
  74. }),
  75. }));
  76. // eslint-disable-next-line import/first -- 必须在全部 mock 之后再引入被测组件。
  77. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  78. // eslint-disable-next-line import/first
  79. import { WorkflowRunSidePane } from "@/app-shell/WorkflowRunSidePane.js";
  80. // eslint-disable-next-line import/first
  81. import { useDynamicWorkflowAvailabilityStore } from "@/store/dynamicWorkflowAvailabilityStore.js";
  82. /** 灰度快照(docs/dynamic-workflow/launch.md「Gray release」):默认命中,面板与改动前一致。 */
  83. function setDynamicWorkflowEnabled(enabled: boolean): void {
  84. useDynamicWorkflowAvailabilityStore.setState({
  85. status: "ready",
  86. enabled,
  87. config: { mode: enabled ? "alwaysOn" : "disabled", enabled, source: "remote" },
  88. });
  89. }
  90. const tab: WorkflowRunSidePaneTab = {
  91. id: "workflow-run:%2Fworkspace:parent-a:dwfrun-1",
  92. type: "workflow-run",
  93. workspaceKey: "/workspace",
  94. workspacePath: "/workspace",
  95. parentSessionId: "parent-a",
  96. toolCallId: "tool-wf-1",
  97. runId: "dwfrun-1",
  98. workflowName: "Fan-out review",
  99. };
  100. interface GraphStep {
  101. id: string;
  102. kind: "ask" | "world-read";
  103. label: string;
  104. lane: string;
  105. line?: number;
  106. phase?: string;
  107. }
  108. const STEPS: GraphStep[] = [
  109. {
  110. id: "ask#1",
  111. kind: "ask",
  112. label: "plan",
  113. lane: "actor#1",
  114. // 检视器 SOURCE 区的 `L{n}` 需要一个落点:车道没有行号时退回它第一步的行。
  115. line: 4,
  116. },
  117. // 检视用的另外几张卡:workspace 车道(合成,无会话)与两条匿名车道。
  118. {
  119. id: "world-read#1",
  120. kind: "world-read",
  121. label: "read files",
  122. lane: "workspace",
  123. },
  124. {
  125. id: "ask#2",
  126. kind: "ask",
  127. label: "review",
  128. lane: "actor#2",
  129. },
  130. {
  131. id: "ask#3",
  132. kind: "ask",
  133. label: "audit",
  134. lane: "actor#3",
  135. },
  136. ];
  137. const LANES = [
  138. { id: "actor#1", name: "planner" },
  139. // 两条匿名车道:编号必须出现(Anonymous Subagent 1 / 2),且与图里那份同源。
  140. { id: "actor#2" },
  141. { id: "actor#3" },
  142. { id: "workspace" },
  143. ];
  144. /** 参与者 = 每阶段每车道一张卡,id 按分析器的 `${phase}:${lane}`;无标记脚本归 `unphased`。 */
  145. function participantsOf(steps: readonly GraphStep[]) {
  146. const byId = new Map<string, { id: string; phase: string; lane: string; steps: string[] }>();
  147. for (const step of steps) {
  148. const phase = step.phase ?? "unphased";
  149. const id = `${phase}:${step.lane}`;
  150. const existing = byId.get(id);
  151. if (existing) existing.steps.push(step.id);
  152. else byId.set(id, { id, lane: step.lane, phase, steps: [step.id] });
  153. }
  154. return [...byId.values()];
  155. }
  156. const graphRow = {
  157. kind: "toolCall" as const,
  158. rowId: "row-1",
  159. toolCallId: "tool-wf-1",
  160. toolName: "CreateWorkflow",
  161. status: "success" as const,
  162. inputText: "",
  163. display: {
  164. kind: "create_workflow" as const,
  165. ok: true,
  166. errorCount: 0,
  167. diagnostics: [],
  168. causalityGraph: {
  169. steps: STEPS,
  170. lanes: LANES,
  171. participants: participantsOf(STEPS),
  172. handoffs: [],
  173. },
  174. },
  175. };
  176. /**
  177. * 阶段词汇表在场的变体:单开手风琴与阶段选择需要真的有两个阶段可开。
  178. * 基础图刻意**没有**阶段——绝大多数用例与阶段无关,给它们平白加一层商图只会让
  179. * 「这条用例在验什么」变模糊。
  180. */
  181. const PHASES = [
  182. { id: "phase#a", name: "plan", line: 3 },
  183. { id: "phase#b", name: "review", line: 9 },
  184. ];
  185. const PHASE_OF: Record<string, string> = {
  186. "ask#1": "phase#a",
  187. "ask#2": "phase#b",
  188. "ask#3": "phase#b",
  189. "world-read#1": "phase#a",
  190. };
  191. function run(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  192. return {
  193. runId: "dwfrun-1",
  194. toolCallId: "tool-wf-1",
  195. status: "running",
  196. usage: { spentTokens: 0, nodesUsed: 0 },
  197. actors: [],
  198. nodes: [],
  199. lastEventSequence: 0,
  200. ...overrides,
  201. };
  202. }
  203. function setSnapshot(
  204. options: {
  205. run?: WorkflowRunState;
  206. withGraphRow?: boolean;
  207. /** 换成带 `phase()` 词汇表的图(模块板面);缺省是今天的 step/车道图。 */
  208. phased?: boolean;
  209. } = {},
  210. ) {
  211. const phasedSteps = STEPS.map((step) => ({ ...step, phase: PHASE_OF[step.id]! }));
  212. const causalityGraph =
  213. options.phased === true
  214. ? {
  215. ...graphRow.display.causalityGraph,
  216. participants: participantsOf(phasedSteps),
  217. phases: PHASES,
  218. // 相邻两站之间的边:脊线只在有边的相邻两站之间画轨道段(与卡同一条规则)。
  219. phaseEdges: [{ from: "phase#a", to: "phase#b" }],
  220. steps: phasedSteps,
  221. }
  222. : graphRow.display.causalityGraph;
  223. const row = { ...graphRow, display: { ...graphRow.display, causalityGraph } };
  224. snapshot = {
  225. rows: { window: options.withGraphRow === false ? [] : [row] },
  226. ...(options.run ? { workflowRuns: { revision: 1, runs: [options.run] } } : {}),
  227. };
  228. }
  229. const onOpenWorkflowActorSession = vi.fn();
  230. const onOpenWorkflowArtifact = vi.fn();
  231. const onOpenWorkflowWorkspace = vi.fn();
  232. const onOpenWorkflowRun = vi.fn();
  233. function renderPane(
  234. locale: "en-US" | "zh-CN" = "en-US",
  235. options: {
  236. withActorCallback?: boolean;
  237. withArtifactCallback?: boolean;
  238. withWorkspaceCallback?: boolean;
  239. /** 「已被 run X 替代」的链接要宿主给开 run 的回调;缺省不给(多数用例与 lineage 无关)。 */
  240. withOpenRunCallback?: boolean;
  241. } = {},
  242. ) {
  243. return render(
  244. createElement(
  245. ZCodeIntlProvider,
  246. { initialLocale: locale },
  247. createElement(WorkflowRunSidePane, {
  248. tab,
  249. ...(options.withActorCallback === false ? {} : { onOpenWorkflowActorSession }),
  250. ...(options.withArtifactCallback === false ? {} : { onOpenWorkflowArtifact }),
  251. ...(options.withWorkspaceCallback === false ? {} : { onOpenWorkflowWorkspace }),
  252. ...(options.withOpenRunCallback === true ? { onOpenWorkflowRun } : {}),
  253. }),
  254. ),
  255. );
  256. }
  257. // 待答问题区默认收起,所以任何**条目级**断言都要先点开。这个小助手让「先展开」在用例里
  258. // 只占一行,读者的注意力留给真正被钉的东西。
  259. type Pane = ReturnType<typeof renderPane>;
  260. /**
  261. * 换了投影之后重渲染同一棵树(行是活的,不是打开那一刻的快照)。面板是 memo 组件,投影在
  262. * 真实应用里经由 context 订阅推进;这里的投影是 mock 出来的模块变量,所以给一个新的 tab
  263. * 对象让 memo 放行。
  264. */
  265. function rerenderPane(view: Pane, locale: "en-US" | "zh-CN" = "en-US"): Pane {
  266. view.rerender(
  267. createElement(
  268. ZCodeIntlProvider,
  269. { initialLocale: locale },
  270. createElement(WorkflowRunSidePane, { tab: { ...tab }, onOpenWorkflowActorSession }),
  271. ),
  272. );
  273. return view;
  274. }
  275. beforeEach(() => {
  276. // 本仓 vitest 没开 globals,所以 @testing-library 的自动 cleanup 不会注册;
  277. // 不显式清理,上一条用例的 DOM 会留下来,getByTestId 随即报「找到多个」。
  278. cleanup();
  279. sendCommand.mockClear();
  280. workflowRunsQuery.mockClear();
  281. workflowRunsQuery.mockImplementation(async () => ({ runs: [] }));
  282. workflowRunArtifactsQuery.mockClear();
  283. workflowRunArtifactsQuery.mockImplementation(async () => ({ artifacts: [] }));
  284. workflowRunArtifactDataQuery.mockClear();
  285. workflowRunArtifactDataQuery.mockImplementation(async () => ({ items: [], hasMore: false }));
  286. onOpenWorkflowActorSession.mockClear();
  287. onOpenWorkflowArtifact.mockClear();
  288. onOpenWorkflowWorkspace.mockClear();
  289. setDynamicWorkflowEnabled(true);
  290. setSnapshot({ run: run() });
  291. });
  292. describe("WorkflowRunSidePane 状态头与阶段清单", () => {
  293. it("阶段清单按声明序一节一阶段,正在运行的阶段自己展开", () => {
  294. // docs/dynamic-workflow/presentation.md「The spine」:时间线读作一份纵向清单。
  295. setSnapshot({
  296. run: run({ nodes: [{ siteId: "ask#2", ordinal: 1, phase: "executing" }] }),
  297. phased: true,
  298. });
  299. const view = renderPane();
  300. const phases = view.getAllByTestId("workflow-run-phase");
  301. expect(phases.map((phase) => phase.getAttribute("data-phase-id"))).toEqual([
  302. "phase#a",
  303. "phase#b",
  304. ]);
  305. expect(phases.map((phase) => phase.textContent)).toEqual([
  306. expect.stringContaining("plan"),
  307. expect.stringContaining("review"),
  308. ]);
  309. expect(phases[1]!.getAttribute("data-phase-status")).toBe("running");
  310. expect(phases[1]!.getAttribute("data-phase-open")).toBe("true");
  311. expect(phases[0]!.getAttribute("data-phase-status")).toBe("pending");
  312. expect(phases[0]!.getAttribute("data-phase-open")).toBe("false");
  313. });
  314. it("运行阶段变化时把新的那一节打开,已展开的不动", () => {
  315. setSnapshot({
  316. run: run({ nodes: [{ siteId: "ask#1", ordinal: 1, phase: "executing" }] }),
  317. phased: true,
  318. });
  319. const view = renderPane();
  320. expect(view.getAllByTestId("workflow-run-phase")[0]!.getAttribute("data-phase-open")).toBe(
  321. "true",
  322. );
  323. setSnapshot({
  324. run: run({
  325. nodes: [
  326. { siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" },
  327. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok" },
  328. { siteId: "ask#2", ordinal: 1, phase: "executing" },
  329. ],
  330. }),
  331. phased: true,
  332. });
  333. rerenderPane(view);
  334. const phases = view.getAllByTestId("workflow-run-phase");
  335. expect(phases.map((phase) => phase.getAttribute("data-phase-open"))).toEqual(["true", "true"]);
  336. expect(phases[0]!.getAttribute("data-phase-status")).toBe("done");
  337. });
  338. it("脊线:轨道段按模型的墨迹分两截画在相邻两站上,灯带状态,行进段在进入运行站的那一段", () => {
  339. // docs/dynamic-workflow/presentation.md「The spine」。plan 已结算、review 在跑:
  340. // a→b 那段轨道是行进;plan 的灯绿、review 的灯琥珀带搏动。
  341. setSnapshot({
  342. run: run({
  343. nodes: [
  344. { siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" },
  345. { siteId: "world-read#1", ordinal: 1, phase: "settled", outcome: "ok" },
  346. { siteId: "ask#2", ordinal: 1, phase: "executing" },
  347. ],
  348. }),
  349. phased: true,
  350. });
  351. const view = renderPane();
  352. const rails = view.getAllByTestId("workflow-run-spine-rail");
  353. // 两截都得带着 `data-rail-position`:样式表按它选行进段的渐变(下半截淡入、上半截涨到满)。
  354. expect(rails.map((rail) => rail.getAttribute("data-rail-position"))).toEqual([
  355. "below",
  356. "above",
  357. ]);
  358. expect(rails.map((rail) => rail.getAttribute("data-rail-ink"))).toEqual(["march", "march"]);
  359. expect(rails[0]!.className).toContain("wf-spine-march");
  360. const lamps = view.getAllByTestId("workflow-run-phase-lamp");
  361. expect(lamps.map((lamp) => lamp.getAttribute("data-lamp"))).toEqual(["done", "running"]);
  362. expect(lamps[1]!.className).toContain("wf-lamp-running");
  363. // 灯在节头按钮里:悬停节头时既有的 `.wf-station-open:hover .wf-lamp` 光环规则接得上。
  364. expect(lamps[0]!.closest('[data-testid="workflow-run-phase-toggle"]')).toBeTruthy();
  365. });
  366. it("脊线:折起的阶段在节头带头像串,展开后头像串让位给药丸", () => {
  367. setSnapshot({
  368. run: run({ nodes: [{ siteId: "ask#2", ordinal: 1, phase: "executing" }] }),
  369. phased: true,
  370. });
  371. const view = renderPane();
  372. // plan 折着:头像串在场(planner + workspace = 2 枚,无 +n);review 展开:没有头像串。
  373. const [plan, review] = view.getAllByTestId("workflow-run-phase");
  374. const cluster = within(plan!).getByTestId("workflow-run-phase-cluster");
  375. expect(cluster.querySelectorAll("[title]")).toHaveLength(2);
  376. expect(cluster.textContent).not.toContain("+");
  377. expect(within(review!).queryByTestId("workflow-run-phase-cluster")).toBeNull();
  378. // 展开 plan 后头像串消失,药丸出现。
  379. fireEvent.click(within(plan!).getByTestId("workflow-run-phase-toggle"));
  380. expect(within(plan!).queryByTestId("workflow-run-phase-cluster")).toBeNull();
  381. expect(within(plan!).getAllByTestId("workflow-agent-pill").length).toBeGreaterThan(0);
  382. });
  383. it("脊线:无边的图没有轨道段;轮次写成 ⟳ n 而不是灯串", () => {
  384. setSnapshot({
  385. run: run({ nodes: [{ siteId: "ask#2", ordinal: 1, phase: "executing" }] }),
  386. phased: true,
  387. });
  388. // 把边拿掉:轨道段整个缺席(相邻无边留空,与卡同一条规则)。
  389. snapshot = {
  390. ...(snapshot as { rows: { window: { display: { causalityGraph: object } }[] } }),
  391. rows: {
  392. window: (
  393. snapshot as { rows: { window: { display: { causalityGraph: object } }[] } }
  394. ).rows.window.map((row) => ({
  395. ...row,
  396. display: {
  397. ...row.display,
  398. causalityGraph: { ...row.display.causalityGraph, phaseEdges: [] },
  399. },
  400. })),
  401. },
  402. };
  403. const view = renderPane();
  404. expect(view.queryAllByTestId("workflow-run-spine-rail")).toHaveLength(0);
  405. expect(view.queryByTestId("workflow-run-phase-rounds")).toBeNull();
  406. });
  407. it("渲染 run 状态词(灯旁永远有词)", () => {
  408. setSnapshot({ run: run({ status: "completed" }) });
  409. const view = renderPane();
  410. expect(view.getByTestId("workflow-run-status").textContent).toBe("Completed");
  411. });
  412. it("直接启动(无工具行)时从启动轮元数据取图(docs/dynamic-workflow/launch.md)", () => {
  413. const launchRow = {
  414. kind: "userInput" as const,
  415. rowId: "row-launch",
  416. text: "Started the saved workflow",
  417. origin: "workflowLaunch" as const,
  418. workflowLaunch: {
  419. runId: "dwfrun-1",
  420. toolCallId: "tool-wf-1",
  421. name: "Fan-out review",
  422. scope: "project" as const,
  423. path: "/workspace/.zcode/workflows/fan-out-review.dwf.ts",
  424. display: graphRow.display,
  425. script: "export default async function main() {}",
  426. },
  427. };
  428. snapshot = {
  429. rows: { window: [launchRow] },
  430. workflowRuns: { revision: 1, runs: [run()] },
  431. };
  432. const view = renderPane();
  433. expect(view.getByTestId("workflow-run-phases")).toBeTruthy();
  434. expect(view.queryByTestId("workflow-run-graph-unavailable")).toBeNull();
  435. });
  436. // 直接启动的来龙去脉(docs/dynamic-workflow/launch.md「The launch turn」):作用域、说明、实参与「由你从
  437. // 工作流中枢启动 · 时刻」只在这里说——聊天区的 run 卡与工具路径发起的一模一样。
  438. it("直接启动的 run:状态头下有来龙去脉节——脚注、作用域徽标、说明、实参表", () => {
  439. const workflowLaunch = {
  440. runId: "dwfrun-1",
  441. toolCallId: "tool-wf-1",
  442. name: "Fan-out review",
  443. scope: "global" as const,
  444. path: "/home/u/.zcode/workflows/fan-out-review.dwf.ts",
  445. description: "Review a change from several angles.",
  446. args: { topic: "adaptive concurrency", depth: 3 },
  447. display: graphRow.display,
  448. };
  449. snapshot = {
  450. rows: {
  451. window: [
  452. {
  453. kind: "turnHeader" as const,
  454. rowId: "row-header",
  455. origin: "workflowLaunch" as const,
  456. executionKind: "controlOnly" as const,
  457. state: "completedSuccess" as const,
  458. startedAt: Date.UTC(2026, 8, 14, 13, 34),
  459. workflowLaunch,
  460. },
  461. {
  462. kind: "userInput" as const,
  463. rowId: "row-launch",
  464. text: "Started the saved workflow",
  465. origin: "workflowLaunch" as const,
  466. workflowLaunch,
  467. },
  468. ],
  469. },
  470. workflowRuns: { revision: 1, runs: [run()] },
  471. };
  472. const view = renderPane();
  473. const provenance = view.getByTestId("workflow-run-provenance");
  474. expect(provenance.getAttribute("data-workflow-launch-scope")).toBe("global");
  475. expect(provenance.textContent).toContain("Started by you from the workflows hub");
  476. expect(provenance.textContent).toContain(" · ");
  477. expect(view.getByTestId("workflow-run-provenance-scope").textContent).toBe("Global");
  478. expect(provenance.textContent).toContain("Review a change from several angles.");
  479. const args = view.getByTestId("workflow-run-provenance-args").textContent ?? "";
  480. expect(args).toContain("topic");
  481. expect(args).toContain("adaptive concurrency");
  482. expect(args).toContain("depth");
  483. expect(args).toContain("3");
  484. // 来龙去脉排在状态头之后、结果区 / 脊线之前。
  485. const header = view.getByTestId("workflow-run-status").closest("div.border-b")!;
  486. expect(
  487. header.compareDocumentPosition(provenance) & Node.DOCUMENT_POSITION_FOLLOWING,
  488. ).toBeTruthy();
  489. expect(view.getByTestId("workflow-run-phases")).toBeTruthy();
  490. });
  491. it("工具路径发起的 run 没有来龙去脉节", () => {
  492. setSnapshot({ run: run() });
  493. const view = renderPane();
  494. expect(view.queryByTestId("workflow-run-provenance")).toBeNull();
  495. });
  496. it("行窗口里翻不到那条工具调用时给出「没有图」而不是空清单", () => {
  497. setSnapshot({ run: run(), withGraphRow: false });
  498. const view = renderPane();
  499. expect(view.queryByTestId("workflow-run-phases")).toBeNull();
  500. expect(view.getByTestId("workflow-run-graph-unavailable").textContent).toContain(
  501. "not in this conversation's visible history",
  502. );
  503. });
  504. });
  505. // ── 子代理模型(docs/dynamic-workflow/presentation.md「The run pane」)──
  506. // 用户在启动时把这次 run 的子代理定在了另一个模型上;主代理仍是会话模型,所以只说子代理。
  507. // 状态头第一行**不再**摆模型芯片(它放不下,截断后剩下的正是 provider id):模型名成了摘要行的
  508. // 第一段——这一行本来就是「这条 run 的几个数」。规范串与强度退进 tooltip。
  509. // 没指定过模型的 run 整段缺席——跟随会话模型是常态,没有可说的。
  510. describe("WorkflowRunSidePane 子代理模型", () => {
  511. // 团队套餐的 provider id 是一串十六进制:这次改动要挡的就是它。
  512. const TEAM_PLAN_MODEL = "4fc7f541-2382-4c32-be11-f021b8d7ed1d/GLM-5.3-Flash$high";
  513. it("模型名是摘要行的第一段,不再是状态头上的芯片", () => {
  514. setSnapshot({ run: run({ subagentModel: "zhipu/glm-5.3-flash" }) });
  515. const view = renderPane();
  516. const segment = view.getByTestId("workflow-run-subagent-model");
  517. expect(segment.textContent).toBe("Subagents glm-5.3-flash");
  518. // 它住在摘要行里,不在状态头那一行(与并发芯片、Stop 钮同排的那一行)。
  519. expect(segment.closest('[data-testid="workflow-run-usage"]')).not.toBeNull();
  520. const summary = view.getByTestId("workflow-run-usage").textContent ?? "";
  521. expect(summary.indexOf("Subagents glm-5.3-flash")).toBe(0);
  522. });
  523. it("屏幕上绝不出现 provider id,哪怕它是团队套餐的 UUID;规范串退进 tooltip", () => {
  524. setSnapshot({ run: run({ subagentModel: TEAM_PLAN_MODEL }) });
  525. const view = renderPane();
  526. const segment = view.getByTestId("workflow-run-subagent-model");
  527. expect(segment.textContent).toBe("Subagents GLM-5.3-Flash");
  528. expect(document.body.textContent).not.toContain("4fc7f541");
  529. expect(segment.getAttribute("title")).toContain(TEAM_PLAN_MODEL);
  530. // 强度不上屏,它跟规范串一起住在 tooltip 里。
  531. expect(segment.getAttribute("title")).toContain("thinking High");
  532. });
  533. it("zh-CN 下同一段说中文,模型名原样不译", () => {
  534. setSnapshot({ run: run({ subagentModel: TEAM_PLAN_MODEL }) });
  535. const view = renderPane("zh-CN");
  536. expect(view.getByTestId("workflow-run-subagent-model").textContent).toBe(
  537. "子代理 GLM-5.3-Flash",
  538. );
  539. });
  540. it("图不可得(建不出时间线)退回用量行时,模型仍在行首:它与有没有图无关", () => {
  541. setSnapshot({
  542. run: run({ subagentModel: TEAM_PLAN_MODEL, usage: { spentTokens: 12_345, nodesUsed: 3 } }),
  543. withGraphRow: false,
  544. });
  545. const view = renderPane();
  546. const segment = view.getByTestId("workflow-run-subagent-model");
  547. expect(segment.textContent).toBe("Subagents GLM-5.3-Flash");
  548. expect(document.body.textContent).not.toContain("4fc7f541");
  549. expect(segment.getAttribute("title")).toContain(TEAM_PLAN_MODEL);
  550. // 同一行里,模型在前,用量标签与读数照旧跟在后面。
  551. const usage = view.getByTestId("workflow-run-usage").textContent ?? "";
  552. expect(usage.indexOf("Subagents GLM-5.3-Flash")).toBe(0);
  553. expect(usage).toContain("Usage");
  554. expect(usage).toContain("12,345 tokens · 3 steps");
  555. });
  556. it("没指定过模型的 run 里整段缺席(子代理跟随会话模型)", () => {
  557. setSnapshot({ run: run() });
  558. const view = renderPane();
  559. expect(view.queryByTestId("workflow-run-subagent-model")).toBeNull();
  560. expect(document.body.textContent).not.toContain("Subagents ");
  561. });
  562. it("run 不在投影里(被淘汰 / 冷启动)时也没有这一段", () => {
  563. setSnapshot({});
  564. const view = renderPane();
  565. expect(view.queryByTestId("workflow-run-subagent-model")).toBeNull();
  566. });
  567. });
  568. describe("WorkflowRunSidePane 摘要行", () => {
  569. it("与聊天卡页脚同文案:工作中的子代理数、步数、token,没有上限、没有进度轨", () => {
  570. setSnapshot({
  571. run: run({
  572. usage: { spentTokens: 12_345, nodesUsed: 3 },
  573. actors: [{ siteId: "actor#1", ordinal: 1, status: "running" }],
  574. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "executing" }],
  575. }),
  576. });
  577. const view = renderPane();
  578. const usage = view.getByTestId("workflow-run-usage").textContent ?? "";
  579. expect(usage).toContain("1 agent working");
  580. expect(usage).toContain("0/1 steps");
  581. expect(usage).toContain("12,345 tokens");
  582. expect(usage).not.toContain("%");
  583. expect(view.container.querySelector("progress")).toBeNull();
  584. });
  585. it("图不可得(建不出时间线)时退回用量行", () => {
  586. setSnapshot({
  587. run: run({ usage: { spentTokens: 12_345, nodesUsed: 3 } }),
  588. withGraphRow: false,
  589. });
  590. const view = renderPane();
  591. const usage = view.getByTestId("workflow-run-usage").textContent ?? "";
  592. expect(usage).toContain("Usage");
  593. expect(usage).toContain("12,345 tokens · 3 steps");
  594. });
  595. // 实例表撞界(docs/dynamic-workflow/presentation.md「The run pane」):摘要行里的步数已经把
  596. // 表外的实例算进来了,脊柱却只列得出表内那些——这一句说的正是这个差额。
  597. it("撞界的 run 在摘要行下多一句「仅展示 n/m 步的详情」,计数仍是真实步数", () => {
  598. setSnapshot({
  599. run: run({
  600. usage: {
  601. spentTokens: 1,
  602. nodesUsed: 1_100,
  603. nodesUnlisted: 2_000,
  604. nodesUnlistedSettled: 1_500,
  605. },
  606. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "settled", outcome: "ok" }],
  607. truncated: true,
  608. }),
  609. });
  610. const view = renderPane();
  611. expect(view.getByTestId("workflow-run-truncated").textContent).toBe(
  612. "Details shown for 1 of 2001 steps",
  613. );
  614. expect(view.getByTestId("workflow-run-usage").textContent ?? "").toContain("1501/2001 steps");
  615. });
  616. it("没撞界、以及只有小表撞界(步数一个不少)的 run 都没有这一句", () => {
  617. setSnapshot({ run: run({ nodes: [{ siteId: "ask#1", ordinal: 1, phase: "settled" }] }) });
  618. expect(renderPane().queryByTestId("workflow-run-truncated")).toBeNull();
  619. cleanup();
  620. // `truncated` 也会被 reports / artifacts / phases 触界置位;那时再念「仅展示 1/1 步」是句废话。
  621. setSnapshot({
  622. run: run({ nodes: [{ siteId: "ask#1", ordinal: 1, phase: "settled" }], truncated: true }),
  623. });
  624. expect(renderPane().queryByTestId("workflow-run-truncated")).toBeNull();
  625. });
  626. it("zh-CN 念「仅展示 1/2,001 步的详情」", () => {
  627. setSnapshot({
  628. run: run({
  629. usage: { spentTokens: 1, nodesUsed: 1, nodesUnlisted: 2_000 },
  630. nodes: [{ siteId: "ask#1", ordinal: 1, phase: "queued" }],
  631. truncated: true,
  632. }),
  633. });
  634. expect(renderPane("zh-CN").getByTestId("workflow-run-truncated").textContent).toBe(
  635. "仅展示 1/2001 步的详情",
  636. );
  637. });
  638. });
  639. describe("WorkflowRunSidePane Stop", () => {
  640. it("running 时可点,并且走既有的 cancelBackgroundWork {workId ≡ runId}", () => {
  641. setSnapshot({ run: run({ status: "running" }) });
  642. const view = renderPane();
  643. const button = view.getByTestId<HTMLButtonElement>("workflow-run-cancel");
  644. expect(button.disabled).toBe(false);
  645. fireEvent.click(button);
  646. expect(sendCommand).toHaveBeenCalledTimes(1);
  647. const envelope = sendCommand.mock.calls[0]![0] as unknown as {
  648. type: string;
  649. sessionId: string;
  650. payload: { workId: string };
  651. };
  652. expect(envelope.type).toBe("cancelBackgroundWork");
  653. expect(envelope.payload).toEqual({ workId: "dwfrun-1" });
  654. expect(envelope.sessionId).toBe("parent-a");
  655. });
  656. it.each(["pending", "completed", "errored", "stopped"] as const)("%s 时按钮禁用", (status) => {
  657. setSnapshot({ run: run({ status }) });
  658. const view = renderPane();
  659. expect(view.getByTestId<HTMLButtonElement>("workflow-run-cancel").disabled).toBe(true);
  660. });
  661. it("run 不在投影里时按钮禁用(对它的在飞状态一无所知)", () => {
  662. setSnapshot({});
  663. const view = renderPane();
  664. expect(view.getByTestId<HTMLButtonElement>("workflow-run-cancel").disabled).toBe(true);
  665. });
  666. it("停止按钮提供 Stop run 无障碍名与可见文案", () => {
  667. setSnapshot({ run: run({ status: "running" }) });
  668. const view = renderPane();
  669. const button = view.getByTestId("workflow-run-cancel");
  670. expect(button.getAttribute("aria-label")).toBe("Stop run");
  671. expect(button.textContent).toContain("Stop run");
  672. });
  673. it("可点时提示带第二行「停下的运行可以恢复」;禁用时只剩为什么不可用", () => {
  674. setSnapshot({ run: run({ status: "running" }) });
  675. renderPane();
  676. expect(tooltips.calls.find((call) => call.title === "Stop run")?.description).toBe(
  677. "You can resume later; finished steps are kept.",
  678. );
  679. cleanup();
  680. tooltips.calls.length = 0;
  681. setSnapshot({ run: run({ status: "completed" }) });
  682. renderPane();
  683. const disabled = tooltips.calls.find(
  684. (call) => call.title === "Only a running workflow can be stopped.",
  685. );
  686. expect(disabled).toBeTruthy();
  687. expect(disabled?.description).toBeUndefined();
  688. });
  689. });
  690. // 修复原因(2026-09-15,桌面实测):老 run 被误留在 running 时 Cancel 点了没反应;Resume 撞上
  691. // 不再编译的老脚本同样只在控制台留 warn。被拒的 ACK 现在按词表变成状态头下的一句话。
  692. describe("WorkflowRunSidePane 被拒提示", () => {
  693. it("cancel 被拒(not_found)→ 状态头下出现一句话;run 状态一变即收起", async () => {
  694. setSnapshot({ run: run({ status: "running" }) });
  695. sendCommand.mockResolvedValueOnce({
  696. status: "failed",
  697. reasonCode: "fault.command.backgroundWorkCancelRejected.not_found",
  698. } as never);
  699. const view = renderPane();
  700. fireEvent.click(view.getByTestId("workflow-run-cancel"));
  701. const hint = await view.findByTestId("workflow-run-rejection");
  702. expect(hint.textContent).toContain("not running in this agent");
  703. // 按钮不被锁死:提示只是解释,不改变可点性。
  704. expect(view.getByTestId<HTMLButtonElement>("workflow-run-cancel").disabled).toBe(false);
  705. setSnapshot({ run: run({ status: "stopped", stopReason: "user" }) });
  706. rerenderPane(view);
  707. expect(view.queryByTestId("workflow-run-rejection")).toBeNull();
  708. });
  709. it("resume 被拒(compile_failed)→ 一句话指向调整工作流 + ACK 的诊断在等宽块里", async () => {
  710. setSnapshot({ run: run({ status: "stopped", resumable: true }) });
  711. sendCommand.mockResolvedValueOnce({
  712. status: "failed",
  713. reasonCode: "fault.command.workflowRunResumeRejected.compile_failed",
  714. message: "L3:C1 Property 'askWithOldFacade' does not exist",
  715. } as never);
  716. const view = renderPane();
  717. fireEvent.click(await view.findByTestId("workflow-run-resume"));
  718. const hint = await view.findByTestId("workflow-run-rejection");
  719. expect(hint.textContent).toContain("no longer compiles");
  720. expect(hint.textContent).toContain("amend the workflow");
  721. expect(hint.querySelector("pre")?.textContent).toContain("askWithOldFacade");
  722. });
  723. it("词表外的 reasonCode → 通用文案带 code;accepted 不出提示", async () => {
  724. setSnapshot({ run: run({ status: "running" }) });
  725. sendCommand.mockResolvedValueOnce({
  726. status: "failed",
  727. reasonCode: "fault.command.executionFailed",
  728. } as never);
  729. const view = renderPane();
  730. fireEvent.click(view.getByTestId("workflow-run-cancel"));
  731. const hint = await view.findByTestId("workflow-run-rejection");
  732. expect(hint.textContent).toContain("fault.command.executionFailed");
  733. setSnapshot({ run: run({ status: "stopped" }) });
  734. rerenderPane(view);
  735. setSnapshot({ run: run({ status: "running" }) });
  736. rerenderPane(view);
  737. fireEvent.click(view.getByTestId("workflow-run-cancel"));
  738. await Promise.resolve();
  739. await Promise.resolve();
  740. expect(view.queryByTestId("workflow-run-rejection")).toBeNull();
  741. });
  742. it("zh-CN 文案", async () => {
  743. setSnapshot({ run: run({ status: "running" }) });
  744. sendCommand.mockResolvedValueOnce({
  745. status: "failed",
  746. reasonCode: "fault.command.backgroundWorkCancelRejected.not_running",
  747. } as never);
  748. const view = renderPane("zh-CN");
  749. fireEvent.click(view.getByTestId("workflow-run-cancel"));
  750. expect((await view.findByTestId("workflow-run-rejection")).textContent).toContain("已经结束");
  751. });
  752. });
  753. describe("WorkflowRunSidePane 结果与失败面板", () => {
  754. it("completed 且无 resultPreview 时指向会话里的后台结果消息,不编造结果", () => {
  755. setSnapshot({ run: run({ status: "completed" }) });
  756. const view = renderPane();
  757. expect(view.getByTestId("workflow-run-result").textContent).toContain(
  758. "delivered to the conversation as a background result message",
  759. );
  760. });
  761. it("errored 时原样呈现投影给出的错误原文", () => {
  762. setSnapshot({ run: run({ status: "errored", error: "节点数超过上限 100" }) });
  763. const view = renderPane();
  764. const panel = view.getByTestId("workflow-run-error");
  765. expect(panel.textContent).toContain("Run errored");
  766. expect(panel.textContent).toContain("节点数超过上限 100");
  767. });
  768. it("stopped 且没有错误详情时说明没有,而不是留一片空白", () => {
  769. setSnapshot({ run: run({ status: "stopped" }) });
  770. const view = renderPane();
  771. const panel = view.getByTestId("workflow-run-error");
  772. expect(panel.textContent).toContain("Run stopped");
  773. expect(panel.textContent).toContain("No error detail was recorded.");
  774. });
  775. it("stopped 带原因:标题与状态头都跟原因词(决策 15)", () => {
  776. setSnapshot({
  777. run: run({ status: "stopped", stopReason: "provider", error: "Sign-in expired." } as never),
  778. });
  779. const view = renderPane();
  780. expect(view.getByTestId("workflow-run-stop-reason").textContent).toContain("model error");
  781. expect(view.getByTestId("workflow-run-status-reason").textContent).toContain("model error");
  782. expect(view.getByTestId("workflow-run-error").textContent).toContain("Sign-in expired.");
  783. });
  784. // 「停止」这个动词说不出后果,所以后果回到状态行:可恢复是投影带来的状态位,不从 status 推。
  785. it("状态行第三个词:run 带 resumable 时说「resumable」,不带就没有那个词", () => {
  786. setSnapshot({ run: run({ status: "stopped", stopReason: "user", resumable: true }) });
  787. const withBit = renderPane();
  788. expect(withBit.getByTestId("workflow-run-status-resumable").textContent).toContain("resumable");
  789. expect(withBit.getByTestId("workflow-run-status-reason").textContent).toContain("by you");
  790. cleanup();
  791. setSnapshot({ run: run({ status: "stopped", stopReason: "user" }) });
  792. const without = renderPane();
  793. expect(without.queryByTestId("workflow-run-status-resumable")).toBeNull();
  794. cleanup();
  795. setSnapshot({ run: run({ status: "stopped", stopReason: "user", resumable: true }) });
  796. const zh = renderPane("zh-CN");
  797. expect(zh.getByTestId("workflow-run-status-resumable").textContent).toContain("可恢复");
  798. });
  799. it("running 时既没有结果面板也没有失败面板", () => {
  800. setSnapshot({ run: run({ status: "running" }) });
  801. const view = renderPane();
  802. expect(view.queryByTestId("workflow-run-result")).toBeNull();
  803. expect(view.queryByTestId("workflow-run-error")).toBeNull();
  804. });
  805. });
  806. describe("WorkflowRunSidePane 升级问题", () => {
  807. const NOW = 1_756_000_000_000;
  808. const MINUTE = 60_000;
  809. const questions = [
  810. {
  811. qid: "dwfq-dwfrun1-1",
  812. actorSiteId: "actor#1",
  813. actorOrdinal: 1,
  814. actorName: "poet",
  815. question: "评分上限是 95,但通过门槛是 96,这个门是不是坏了?",
  816. context: "已经试过 4 轮,最高分 95。",
  817. askedAt: NOW - 42 * MINUTE,
  818. },
  819. {
  820. qid: "dwfq-dwfrun1-2",
  821. actorSiteId: "actor#2",
  822. actorOrdinal: 3,
  823. question: "用哪版风格指南?",
  824. askedAt: NOW - 90 * MINUTE,
  825. },
  826. ];
  827. const askers = () =>
  828. run({
  829. actors: [
  830. { siteId: "actor#1", ordinal: 1, name: "poet", sessionId: "s-1", status: "waiting" },
  831. { siteId: "actor#2", ordinal: 3, sessionId: "s-2", status: "waiting" },
  832. ],
  833. nodes: [
  834. {
  835. siteId: "ask#1",
  836. ordinal: 1,
  837. phase: "executing",
  838. actorSiteId: "actor#1",
  839. actorOrdinal: 1,
  840. },
  841. { siteId: "ask#2", ordinal: 3, phase: "waiting", actorSiteId: "actor#2", actorOrdinal: 3 },
  842. ],
  843. pendingQuestions: questions,
  844. });
  845. it("挂在提问者那一行下面:问题紧跟匹配 site@ordinal 的子代理药丸", () => {
  846. setSnapshot({ run: askers() });
  847. const view = renderPane();
  848. const rows = view.getAllByTestId("workflow-run-question");
  849. expect(rows).toHaveLength(2);
  850. expect(rows[0]!.getAttribute("data-qid")).toBe("dwfq-dwfrun1-1");
  851. const pill = rows[0]!.previousElementSibling as HTMLElement;
  852. expect(pill.getAttribute("data-testid")).toBe("workflow-agent-pill");
  853. expect(pill.textContent).toContain("poet");
  854. expect(rows[0]!.textContent).toContain("这个门是不是坏了?");
  855. expect(rows[0]!.textContent).toContain("已经试过 4 轮,最高分 95。");
  856. // qid 是主代理作答要用的 token;用户答不了,但能指着它让主代理去答。
  857. expect(rows[0]!.textContent).toContain("dwfq-dwfrun1-1");
  858. // 挂在行下的问题不重复提问者的名字。
  859. expect(rows[0]!.textContent).not.toContain("poet");
  860. expect(view.queryByTestId("workflow-run-orphan-questions")).toBeNull();
  861. });
  862. it("每条带等待时长(读者的第一个问题恒是「这个已经等了多久」)", () => {
  863. vi.useFakeTimers();
  864. vi.setSystemTime(NOW);
  865. try {
  866. setSnapshot({ run: askers() });
  867. const view = renderPane();
  868. const waited = view.getAllByTestId("workflow-run-question-waited");
  869. expect(waited[0]!.textContent).toBe("42m ago");
  870. expect(waited[1]!.textContent).toBe("1h ago");
  871. } finally {
  872. vi.useRealTimers();
  873. }
  874. });
  875. it("等待时长自己走时钟:run 在等答案时不发事件,靠投影更新会一直显示「刚刚」", () => {
  876. vi.useFakeTimers();
  877. vi.setSystemTime(NOW);
  878. try {
  879. setSnapshot({ run: askers() });
  880. const view = renderPane();
  881. const before = view.getAllByTestId("workflow-run-question-waited")[0]!.textContent;
  882. act(() => {
  883. vi.advanceTimersByTime(20 * MINUTE);
  884. });
  885. const after = view.getAllByTestId("workflow-run-question-waited")[0]!.textContent;
  886. expect(after).not.toBe(before);
  887. } finally {
  888. vi.useRealTimers();
  889. }
  890. });
  891. it("askedAt 缺席(老 journal 重放)时不渲染时长,绝不编一个「刚刚」", () => {
  892. const { askedAt: _dropped, ...withoutAskedAt } = questions[0]!;
  893. setSnapshot({ run: { ...askers(), pendingQuestions: [withoutAskedAt] } });
  894. const view = renderPane();
  895. expect(view.getAllByTestId("workflow-run-question")).toHaveLength(1);
  896. expect(view.queryByTestId("workflow-run-question-waited")).toBeNull();
  897. });
  898. it("匹配不上提问者的问题挂在清单末尾,并自报名字(站点实例标签 / 匿名兜底)", () => {
  899. setSnapshot({
  900. run: run({
  901. pendingQuestions: [
  902. { qid: "q-a", actorSiteId: "actor#9", actorOrdinal: 2, question: "谁来审?" },
  903. { qid: "q-b", question: "没有主语的问题" },
  904. ],
  905. }),
  906. });
  907. const view = renderPane();
  908. const block = view.getByTestId("workflow-run-orphan-questions");
  909. expect(block.textContent).toContain("Waiting on an answer");
  910. const rows = view.getAllByTestId("workflow-run-question");
  911. expect(rows[0]!.textContent).toContain("actor#9@2");
  912. expect(rows[1]!.textContent).toContain("Anonymous Subagent");
  913. });
  914. it("v1 只读:清单里没有任何输入控件或应答按钮", () => {
  915. setSnapshot({ run: askers() });
  916. const view = renderPane();
  917. const list = view.getByTestId("workflow-run-phases");
  918. expect(list.querySelectorAll("input, textarea").length).toBe(0);
  919. expect(list.textContent).not.toContain("Answer");
  920. });
  921. it("零条时没有问题行,也没有末尾的孤儿块(键缺席与空数组两种形态都一样)", () => {
  922. setSnapshot({ run: run({ pendingQuestions: [] }) });
  923. let view = renderPane();
  924. expect(view.queryAllByTestId("workflow-run-question")).toHaveLength(0);
  925. expect(view.queryByTestId("workflow-run-orphan-questions")).toBeNull();
  926. cleanup();
  927. setSnapshot({ run: run() });
  928. view = renderPane();
  929. expect(view.queryAllByTestId("workflow-run-question")).toHaveLength(0);
  930. });
  931. it("zh-CN 下等待时长与孤儿块标题都本地化,且没有英文兜底漏出来", () => {
  932. vi.useFakeTimers();
  933. vi.setSystemTime(NOW);
  934. try {
  935. setSnapshot({
  936. run: run({
  937. pendingQuestions: [
  938. { qid: "q-b", question: "没有主语的问题", askedAt: NOW - 42 * MINUTE },
  939. ],
  940. }),
  941. });
  942. const view = renderPane("zh-CN");
  943. const text = view.getByTestId("workflow-run-orphan-questions").textContent ?? "";
  944. expect(text).toContain("待答问题");
  945. expect(text).toContain("42 分钟前");
  946. expect(text).toContain("未命名子代理");
  947. expect(text).not.toContain("Waiting on an answer");
  948. expect(text).not.toContain("ago");
  949. } finally {
  950. vi.useRealTimers();
  951. }
  952. });
  953. });
  954. describe("WorkflowRunSidePane 淘汰 / 冷启动空态", () => {
  955. it("run 不在 workflowRuns 里时 tab 仍然打开,措辞只说实时状态没了", () => {
  956. setSnapshot({});
  957. const view = renderPane();
  958. const panel = view.getByTestId("workflow-run-untracked");
  959. expect(panel.textContent).toContain("No longer tracked live");
  960. // 关键:不能读成「这次运行不存在了」——journal 里的记录仍然完整,那正是留着这个
  961. // tab 的理由(产物仍列得出来,见产物区那条用例)。
  962. expect(panel.textContent).toContain("record is still complete");
  963. });
  964. });
  965. describe("WorkflowRunSidePane 国际化", () => {
  966. it("状态头、用量、Stop 与结果在 zh-CN 下全部本地化", () => {
  967. setSnapshot({
  968. run: run({
  969. status: "completed",
  970. usage: { spentTokens: 1_000, nodesUsed: 3 },
  971. }),
  972. });
  973. const view = renderPane("zh-CN");
  974. const text = view.container.textContent ?? "";
  975. expect(view.getByTestId("workflow-run-status").textContent).toBe("已完成");
  976. expect(text).toContain("停止运行");
  977. // 摘要行与聊天卡页脚同文案:三条子代理车道 + 步数 + token。
  978. expect(view.getByTestId("workflow-run-usage").textContent).toContain("3 个子代理");
  979. expect(view.getByTestId("workflow-run-usage").textContent).toContain("1,000 tokens");
  980. expect(text).toContain("结果");
  981. // 没有英文兜底漏出来。
  982. expect(text).not.toContain("Stop run");
  983. // 旧动词彻底退场。
  984. expect(text).not.toContain("取消运行");
  985. });
  986. });
  987. // ── 阶段清单的子代理行(docs/dynamic-workflow/presentation.md「The spine」)──
  988. // 与卡上同一枚药丸,加「正在做什么」(当前步的 label)、计数、状态标记与打开 transcript 的箭头。
  989. describe("WorkflowRunSidePane 子代理行", () => {
  990. function actor(overrides: Record<string, unknown> = {}) {
  991. return {
  992. siteId: "actor#1",
  993. ordinal: 1,
  994. sessionId: "dwf-dwfrun-1-actor_1@1",
  995. status: "waiting" as const,
  996. ...overrides,
  997. };
  998. }
  999. const executing = (actorOrdinal = 1) => ({
  1000. siteId: "ask#1",
  1001. ordinal: actorOrdinal,
  1002. phase: "executing" as const,
  1003. actorSiteId: "actor#1",
  1004. actorOrdinal,
  1005. });
  1006. it("行带运行时名、计数与可读的状态标记;不写当前步的 label(站点名对读者没有信息量)", () => {
  1007. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1008. const view = renderPane();
  1009. const pill = view
  1010. .getAllByTestId("workflow-agent-pill")
  1011. .find((candidate) => candidate.textContent?.includes("planner"))!;
  1012. expect(pill.getAttribute("data-agent-status")).toBe("running");
  1013. expect(pill.querySelector('[data-testid="workflow-run-agent-activity"]')).toBeNull();
  1014. expect(pill.textContent).toContain("1 tasks");
  1015. // 状态不只靠颜色或图形:标记带可读文字。
  1016. const mark = pill.querySelector('[data-testid="workflow-pill-status"]');
  1017. expect(mark?.getAttribute("aria-label")).toBe("running");
  1018. });
  1019. /** 行尾的 ↗:一行一枚(活的 run 里每枚子代理药丸都可开),按行里的名字取。 */
  1020. const openOf = (view: ReturnType<typeof renderPane>, name: string) =>
  1021. view
  1022. .getAllByTestId("workflow-agent-pill")
  1023. .find((candidate) => candidate.textContent?.includes(name))!
  1024. .querySelector('[data-testid="workflow-run-agent-open"]')!;
  1025. it("点行尾箭头开 transcript tab,并带上 tab 自己的 workspace scope", () => {
  1026. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1027. const view = renderPane();
  1028. fireEvent.click(openOf(view, "planner"));
  1029. expect(onOpenWorkflowActorSession).toHaveBeenCalledWith({
  1030. workspacePath: "/workspace",
  1031. parentSessionId: "parent-a",
  1032. runId: "dwfrun-1",
  1033. actorSessionId: "dwf-dwfrun-1-actor_1@1",
  1034. siteId: "actor#1",
  1035. ordinal: 1,
  1036. actorName: "planner",
  1037. });
  1038. });
  1039. it("整行就是按钮:点药丸本身即打开,↗ 只是可打开的可见证据", () => {
  1040. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1041. const view = renderPane();
  1042. const pill = view
  1043. .getAllByTestId("workflow-agent-pill")
  1044. .find((candidate) => candidate.textContent?.includes("planner"))!;
  1045. expect(pill.tagName).toBe("BUTTON");
  1046. expect(pill.getAttribute("aria-label")).toBe("Open the transcript of planner");
  1047. expect(pill.querySelector('[data-testid="workflow-run-agent-open"]')).toBeTruthy();
  1048. fireEvent.click(pill);
  1049. expect(onOpenWorkflowActorSession).toHaveBeenCalledTimes(1);
  1050. expect(onOpenWorkflowActorSession).toHaveBeenCalledWith(
  1051. expect.objectContaining({ actorSessionId: "dwf-dwfrun-1-actor_1@1", actorName: "planner" }),
  1052. );
  1053. });
  1054. it("会话未落库的实例仍然成行,也可开:请求带槽位、不带会话 id(tab 里是占位,自愈)", () => {
  1055. // docs/dynamic-workflow/presentation.md「The pill」。
  1056. const { sessionId: _absent, ...pending } = actor({ name: "planner" });
  1057. setSnapshot({ run: run({ actors: [pending], nodes: [executing()] }) });
  1058. const view = renderPane();
  1059. const pill = view
  1060. .getAllByTestId("workflow-agent-pill")
  1061. .find((candidate) => candidate.textContent?.includes("planner"))!;
  1062. expect(pill.tagName).toBe("BUTTON");
  1063. fireEvent.click(pill);
  1064. expect(onOpenWorkflowActorSession).toHaveBeenCalledWith(
  1065. expect.objectContaining({
  1066. runId: "dwfrun-1",
  1067. siteId: "actor#1",
  1068. ordinal: 1,
  1069. actorName: "planner",
  1070. }),
  1071. );
  1072. expect(onOpenWorkflowActorSession.mock.calls[0]![0]).not.toHaveProperty("actorSessionId");
  1073. });
  1074. it("还没出现的子代理(静态车道)在活的 run 里同样可开:期望序号 1", () => {
  1075. // 脚本还没走到它的 agent():投影里没有这个 actor,药丸交出车道 + 将来的序号。
  1076. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1077. const view = renderPane();
  1078. const opens = view.getAllByTestId("workflow-run-agent-open");
  1079. const absent = opens.find((open) => open.getAttribute("data-agent-session-id") === "")!;
  1080. fireEvent.click(absent);
  1081. const request = onOpenWorkflowActorSession.mock.calls[0]![0] as Record<string, unknown>;
  1082. expect(request).toMatchObject({ runId: "dwfrun-1", ordinal: 1 });
  1083. expect(request.siteId).not.toBe("actor#1");
  1084. expect(request).not.toHaveProperty("actorSessionId");
  1085. });
  1086. it("宿主没有下钻回调时没有任何箭头(回调的存在本身就是门控)", () => {
  1087. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1088. const view = renderPane("en-US", { withActorCallback: false });
  1089. expect(view.queryByTestId("workflow-run-agent-open")).toBeNull();
  1090. });
  1091. it("同一车道两个实例时拆成两行,各开各的 transcript", () => {
  1092. setSnapshot({
  1093. run: run({
  1094. actors: [
  1095. actor({ ordinal: 1, name: "worker-1", sessionId: "s-1" }),
  1096. actor({ ordinal: 2, name: "worker-2", sessionId: "s-2" }),
  1097. ],
  1098. nodes: [executing(1), executing(2)],
  1099. }),
  1100. });
  1101. const view = renderPane();
  1102. const opens = view.getAllByTestId("workflow-run-agent-open");
  1103. const withSession = opens.filter((open) => open.getAttribute("data-agent-session-id") !== "");
  1104. expect(withSession.map((button) => button.getAttribute("data-agent-session-id"))).toEqual([
  1105. "s-1",
  1106. "s-2",
  1107. ]);
  1108. fireEvent.click(withSession[1]!);
  1109. expect(onOpenWorkflowActorSession).toHaveBeenCalledWith(
  1110. expect.objectContaining({ actorSessionId: "s-2", ordinal: 2, actorName: "worker-2" }),
  1111. );
  1112. });
  1113. it("脚本行走自己的那条路(docs/dynamic-workflow/transcript-and-notifications.md):不开 actor transcript,开整个 run 的脚本 transcript,落到这一站", () => {
  1114. setSnapshot({
  1115. run: run({ nodes: [{ siteId: "world-read#1", ordinal: 1, phase: "executing" }] }),
  1116. });
  1117. const view = renderPane();
  1118. const pill = view
  1119. .getAllByTestId("workflow-agent-pill")
  1120. .find((candidate) => candidate.textContent?.includes("Script"))!;
  1121. expect(pill.querySelector('[data-testid="workflow-run-agent-open"]')).toBeNull();
  1122. expect(pill.textContent).toContain("1 reads");
  1123. expect(pill.tagName).toBe("BUTTON");
  1124. const open = pill.querySelector('[data-testid="workflow-run-workspace-open"]')!;
  1125. // 无标记脚本:隐式站的 id 是 "workflow",落点就落它。
  1126. expect(open.getAttribute("data-phase-id")).toBe("workflow");
  1127. fireEvent.click(pill);
  1128. expect(onOpenWorkflowActorSession).not.toHaveBeenCalled();
  1129. expect(onOpenWorkflowWorkspace).toHaveBeenCalledWith({
  1130. workspacePath: "/workspace",
  1131. parentSessionId: "parent-a",
  1132. toolCallId: "tool-wf-1",
  1133. runId: "dwfrun-1",
  1134. workflowName: "Fan-out review",
  1135. phaseId: "workflow",
  1136. });
  1137. });
  1138. it("带阶段的图:脚本行交出所在站的阶段 id;宿主没给回调时它是 span", () => {
  1139. setSnapshot({
  1140. phased: true,
  1141. run: run({ nodes: [{ siteId: "world-read#1", ordinal: 1, phase: "executing" }] }),
  1142. });
  1143. const view = renderPane();
  1144. const pill = view
  1145. .getAllByTestId("workflow-agent-pill")
  1146. .find((candidate) => candidate.textContent?.includes("Script"))!;
  1147. expect(pill.getAttribute("aria-label")).toBe("Open the script's steps at plan");
  1148. fireEvent.click(pill);
  1149. expect(onOpenWorkflowWorkspace).toHaveBeenCalledWith(
  1150. expect.objectContaining({ phaseId: "phase#a" }),
  1151. );
  1152. cleanup();
  1153. const bare = renderPane("en-US", { withWorkspaceCallback: false });
  1154. const span = bare
  1155. .getAllByTestId("workflow-agent-pill")
  1156. .find((candidate) => candidate.textContent?.includes("Script"))!;
  1157. expect(span.tagName).toBe("SPAN");
  1158. expect(bare.queryByTestId("workflow-run-workspace-open")).toBeNull();
  1159. });
  1160. it("新实例出现即入列:行是活的,不是打开那一刻的快照", () => {
  1161. const withSession = (view: ReturnType<typeof renderPane>) =>
  1162. view
  1163. .getAllByTestId("workflow-run-agent-open")
  1164. .filter((open) => open.getAttribute("data-agent-session-id") !== "");
  1165. setSnapshot({ run: run({ actors: [actor({ name: "worker-1" })], nodes: [executing()] }) });
  1166. const view = renderPane();
  1167. expect(withSession(view)).toHaveLength(1);
  1168. setSnapshot({
  1169. run: run({
  1170. actors: [
  1171. actor({ name: "worker-1" }),
  1172. actor({ ordinal: 2, name: "worker-2", sessionId: "s-2" }),
  1173. ],
  1174. nodes: [executing(1), executing(2)],
  1175. }),
  1176. });
  1177. rerenderPane(view);
  1178. expect(withSession(view)).toHaveLength(2);
  1179. });
  1180. it("点节头折叠再展开", () => {
  1181. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1182. const view = renderPane();
  1183. const phase = view.getByTestId("workflow-run-phase");
  1184. expect(phase.getAttribute("data-phase-open")).toBe("true");
  1185. fireEvent.click(view.getByTestId("workflow-run-phase-toggle"));
  1186. expect(phase.getAttribute("data-phase-open")).toBe("false");
  1187. expect(view.queryByTestId("workflow-run-agent-open")).toBeNull();
  1188. fireEvent.click(view.getByTestId("workflow-run-phase-toggle"));
  1189. expect(phase.getAttribute("data-phase-open")).toBe("true");
  1190. });
  1191. it("zh-CN 下隐式阶段名、计数与状态标记都本地化", () => {
  1192. setSnapshot({ run: run({ actors: [actor({ name: "planner" })], nodes: [executing()] }) });
  1193. const view = renderPane("zh-CN");
  1194. const list = view.getByTestId("workflow-run-phases");
  1195. expect(list.textContent).toContain("工作流");
  1196. expect(list.textContent).toContain("1 个任务");
  1197. expect(
  1198. list.querySelector('[data-testid="workflow-pill-status"]')?.getAttribute("aria-label"),
  1199. ).toBe("运行中");
  1200. expect(list.textContent).not.toContain("asks");
  1201. });
  1202. });
  1203. describe("WorkflowRunSidePane Resume", () => {
  1204. it("stopped 且带 resumable 状态位 → 渲染 Resume,点击发 resumeWorkflowRun {workId ≡ runId, name}", async () => {
  1205. setSnapshot({ run: run({ status: "stopped", resumable: true }) });
  1206. const view = renderPane();
  1207. const button = await view.findByTestId<HTMLButtonElement>("workflow-run-resume");
  1208. fireEvent.click(button);
  1209. const resumeCall = sendCommand.mock.calls.find(
  1210. (call) => (call[0] as { type: string }).type === "resumeWorkflowRun",
  1211. );
  1212. expect(resumeCall).toBeDefined();
  1213. const envelope = resumeCall![0] as unknown as {
  1214. type: string;
  1215. sessionId: string;
  1216. payload: { workId: string; name?: string };
  1217. };
  1218. // name 喂恢复后完成通知的主题(重启后原工具 input 不可得,tab 上的展示名是仅存来源)。
  1219. expect(envelope.payload).toEqual({ workId: "dwfrun-1", name: "Fan-out review" });
  1220. expect(envelope.sessionId).toBe("parent-a");
  1221. });
  1222. it.each(["pending", "running", "completed"] as const)("%s 不渲染 Resume", async (status) => {
  1223. setSnapshot({ run: run({ status }) });
  1224. const view = renderPane();
  1225. await Promise.resolve();
  1226. expect(view.queryByTestId("workflow-run-resume")).toBeNull();
  1227. });
  1228. it("stopped(interrupted) 且投影带 resumable 状态位(冷回放折叠了行的谓词)→ 渲染 Resume", async () => {
  1229. setSnapshot({
  1230. run: run({
  1231. status: "stopped",
  1232. stopReason: "interrupted",
  1233. error: "owning process exited",
  1234. resumable: true,
  1235. } as never),
  1236. });
  1237. const view = renderPane();
  1238. expect(await view.findByTestId("workflow-run-resume")).toBeDefined();
  1239. });
  1240. it("errored(脚本真失败)→ 不渲染", async () => {
  1241. setSnapshot({ run: run({ status: "errored" }) });
  1242. const view = renderPane();
  1243. await Promise.resolve();
  1244. expect(view.queryByTestId("workflow-run-resume")).toBeNull();
  1245. });
  1246. it("stopped 但无状态位(旧 CLI)→ 不渲染死按钮;不再另查 journal 摘要", async () => {
  1247. setSnapshot({ run: run({ status: "stopped" }) });
  1248. const view = renderPane();
  1249. await Promise.resolve();
  1250. await Promise.resolve();
  1251. expect(view.queryByTestId("workflow-run-resume")).toBeNull();
  1252. expect(workflowRunsQuery).not.toHaveBeenCalled();
  1253. });
  1254. // 灰度(docs/dynamic-workflow/launch.md「Gray release」DWG-07):Resume 会真的起一台引擎,
  1255. // 是这块面板上唯一被收走的动作;面板其余部分照旧渲染。
  1256. it("灰度关 → resumable 的 run 也不渲染 Resume,但状态头与阶段清单照旧", async () => {
  1257. setDynamicWorkflowEnabled(false);
  1258. setSnapshot({ run: run({ status: "stopped", resumable: true }) });
  1259. const view = renderPane();
  1260. await Promise.resolve();
  1261. expect(view.queryByTestId("workflow-run-resume")).toBeNull();
  1262. // 「只收 Resume」:Stop 那枚钮与阶段清单仍在,run 本身没有被藏起来。
  1263. expect(view.queryByTestId("workflow-run-cancel")).not.toBeNull();
  1264. expect(view.queryByTestId("workflow-run-phases")).not.toBeNull();
  1265. });
  1266. it("灰度快照未就绪(loading)→ 先不给 Resume;就绪且命中后再长出来", async () => {
  1267. useDynamicWorkflowAvailabilityStore.setState({
  1268. status: "loading",
  1269. enabled: false,
  1270. config: null,
  1271. });
  1272. setSnapshot({ run: run({ status: "stopped", resumable: true }) });
  1273. const view = renderPane();
  1274. await Promise.resolve();
  1275. expect(view.queryByTestId("workflow-run-resume")).toBeNull();
  1276. act(() => {
  1277. setDynamicWorkflowEnabled(true);
  1278. });
  1279. expect(await view.findByTestId("workflow-run-resume")).toBeDefined();
  1280. });
  1281. });
  1282. // ── 产物区(docs/dynamic-workflow/authoring.md「How the user sees them」)──
  1283. // 区自己的形态(默认展开、卡片字段、点击回调)在 workflowRunArtifactsSection.test.ts 里穷举;
  1284. // 这里只钉「它在这块面板上的位置与在场条件」——那两件事只有在完整面板里才成立。
  1285. //
  1286. // ⚠ 术语:产物 = 脚本经 `artifact.*` 交付给用户的产出,与「结果」(顶层返回值)是两件事,
  1287. // spec 的不变式要求两者同屏可区分。(`report` 条目那一节已于 2026-09-04 按用户指令撤走。)
  1288. describe("WorkflowRunSidePane 产物区", () => {
  1289. const summary = (overrides: Record<string, unknown> = {}) => ({
  1290. id: "book",
  1291. kind: "file",
  1292. title: "审计报告",
  1293. version: 1,
  1294. contentType: "application/pdf",
  1295. bytes: 4096,
  1296. ...overrides,
  1297. });
  1298. it("排在阶段清单之后,是面板的最后一节(Results / 事件日志 / Script 三节已撤走)", async () => {
  1299. setSnapshot({
  1300. run: run({
  1301. artifacts: [summary()],
  1302. pendingQuestions: [
  1303. { qid: "q-1", siteId: "ask#1", ordinal: 1, question: "哪个 registry?" },
  1304. ],
  1305. } as never),
  1306. });
  1307. const view = renderPane();
  1308. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACTS_SECTION)).toBeTruthy());
  1309. const artifacts = view.getByTestId(TID_WORKFLOW_ARTIFACTS_SECTION);
  1310. const phases = view.getByTestId("workflow-run-phases");
  1311. // Node.DOCUMENT_POSITION_FOLLOWING === 4:a 在 b 之前。升级问题挂在清单里的提问者下面
  1312. // (不再是独立一节),所以产物区紧跟阶段清单。
  1313. expect(phases.compareDocumentPosition(artifacts) & 4).toBeTruthy();
  1314. // 面板到此为止:产物区之后没有兄弟节点。
  1315. expect(artifacts.nextElementSibling).toBeNull();
  1316. });
  1317. it("零件时整区缺席(不给不发布产物的 run 留一节空壳)", async () => {
  1318. setSnapshot({ run: run() });
  1319. const view = renderPane();
  1320. await act(async () => {});
  1321. expect(view.queryByTestId(TID_WORKFLOW_ARTIFACTS_SECTION)).toBeNull();
  1322. });
  1323. it.each(["errored", "stopped"] as const)("%s 的 run 一样渲染产物区", async (status) => {
  1324. // 一个死在第 12 步的 run 仍然可能已经发布了一份 pdf;只报一句「失败」等于把它扔了。
  1325. setSnapshot({ run: run({ status, artifacts: [summary()] } as never) });
  1326. const view = renderPane();
  1327. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACTS_SECTION)).toBeTruthy());
  1328. expect(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD)).toBeTruthy();
  1329. });
  1330. it("点卡片 → 打开产物 tab 的请求带上这块面板的 workspace scope 与产物 id,且不带版本号", async () => {
  1331. setSnapshot({ run: run({ artifacts: [summary()] } as never) });
  1332. const view = renderPane();
  1333. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD)).toBeTruthy());
  1334. fireEvent.click(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD));
  1335. expect(onOpenWorkflowArtifact).toHaveBeenCalledWith({
  1336. workspacePath: "/workspace",
  1337. parentSessionId: "parent-a",
  1338. runId: "dwfrun-1",
  1339. artifactId: "book",
  1340. title: "审计报告",
  1341. // 宿主据 contentType 分流(html 直接开浏览器 tab),所以这块面板手上的那份合并视图
  1342. // 带得到就交出去。
  1343. contentType: "application/pdf",
  1344. });
  1345. });
  1346. it("合并视图里有 sourcePath 时一并交出去——宿主不必再为「在工作区显示」查一次 journal", async () => {
  1347. // 出处只在 journal 里(活投影那份摘要刻意不带它),所以这里让 journal 答上同一个 id。
  1348. workflowRunArtifactsQuery.mockImplementation(async () => ({
  1349. artifacts: [
  1350. {
  1351. id: "book",
  1352. kind: "file",
  1353. title: "审计报告",
  1354. version: 1,
  1355. contentType: "text/html",
  1356. sourcePath: "reports/audit.html",
  1357. versions: [{ version: 1, publishedAt: 1, bytes: 4096 }],
  1358. itemCount: 0,
  1359. },
  1360. ],
  1361. }));
  1362. setSnapshot({ run: run({ artifacts: [summary({ contentType: "text/html" })] } as never) });
  1363. const view = renderPane();
  1364. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD)).toBeTruthy());
  1365. fireEvent.click(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD));
  1366. expect(onOpenWorkflowArtifact).toHaveBeenCalledWith({
  1367. workspacePath: "/workspace",
  1368. parentSessionId: "parent-a",
  1369. runId: "dwfrun-1",
  1370. artifactId: "book",
  1371. title: "审计报告",
  1372. contentType: "text/html",
  1373. sourcePath: "reports/audit.html",
  1374. });
  1375. });
  1376. it("宿主没注入打开能力时卡片不可点(回调的存在本身就是门控)", async () => {
  1377. setSnapshot({ run: run({ artifacts: [summary()] } as never) });
  1378. const view = renderPane("en-US", { withArtifactCallback: false });
  1379. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD)).toBeTruthy());
  1380. fireEvent.click(view.getByTestId(TID_WORKFLOW_ARTIFACT_CARD));
  1381. expect(onOpenWorkflowArtifact).not.toHaveBeenCalled();
  1382. });
  1383. it("run 已被活投影淘汰时,产物仍从 journal 列得出来", async () => {
  1384. workflowRunArtifactsQuery.mockImplementation(async () => ({
  1385. artifacts: [
  1386. {
  1387. id: "notes",
  1388. kind: "markdown",
  1389. title: "综述",
  1390. version: 1,
  1391. versions: [{ version: 1, publishedAt: 1, bytes: 12 }],
  1392. itemCount: 0,
  1393. },
  1394. ],
  1395. }));
  1396. setSnapshot({});
  1397. const view = renderPane();
  1398. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACTS_SECTION)).toBeTruthy());
  1399. expect(view.getByText("综述")).toBeTruthy();
  1400. });
  1401. it("zh-CN 下区名念「产物」——与顶部「结果」措辞不重叠", async () => {
  1402. setSnapshot({ run: run({ artifacts: [summary()] } as never) });
  1403. const view = renderPane("zh-CN");
  1404. await waitFor(() => expect(view.getByTestId(TID_WORKFLOW_ARTIFACTS_SECTION)).toBeTruthy());
  1405. expect(view.getByTestId(TID_WORKFLOW_ARTIFACTS_SECTION).textContent).toContain("产物");
  1406. });
  1407. });
  1408. // ── 阶段名册(docs/dynamic-workflow/presentation.md「Past six participants」)──
  1409. // 过了六个参与者的站:钉 5 枚(asking → running → failed → 补位)、问题挂在钉住的提问者下面、
  1410. // 其余每人一格、「列出全部」展开两列密排(展开时格子收起,追记「五枚药丸与一扇门」);折叠节头上
  1411. // 头像串换成迷你量条。
  1412. describe("WorkflowRunSidePane 阶段名册", () => {
  1413. type FanStatus = "done" | "running" | "failed" | "pending";
  1414. function fanoutSnapshot(
  1415. n: number,
  1416. statusOf: (index: number) => FanStatus,
  1417. pendingQuestions: WorkflowRunState["pendingQuestions"] = [],
  1418. unlistedByPhase?: WorkflowRunState["unlistedByPhase"],
  1419. ) {
  1420. // 一条车道跑出 N 个实例:静态图是一张 `many` 卡,run 一来按实例拆成 N 枚药丸。
  1421. const steps: GraphStep[] = [
  1422. { id: "ask#1", kind: "ask", label: "review", lane: "actor#1", phase: "phase#a" },
  1423. ];
  1424. const lanes = [{ id: "actor#1" }];
  1425. const actors: WorkflowRunState["actors"] = [];
  1426. const nodes: WorkflowRunState["nodes"] = [];
  1427. for (let i = 1; i <= n; i += 1) {
  1428. const status = statusOf(i);
  1429. actors.push({
  1430. siteId: "actor#1",
  1431. ordinal: i,
  1432. name: `reviewer-${i}`,
  1433. sessionId: `dwf-dwfrun-1-actor_1@${i}`,
  1434. status: status === "running" ? "running" : status === "pending" ? "waiting" : "completed",
  1435. });
  1436. if (status === "pending") continue;
  1437. nodes.push({
  1438. siteId: "ask#1",
  1439. ordinal: i,
  1440. actorSiteId: "actor#1",
  1441. actorOrdinal: i,
  1442. ...(status === "running"
  1443. ? { phase: "executing" }
  1444. : { phase: "settled", outcome: status === "failed" ? "failed" : "ok" }),
  1445. } as WorkflowRunState["nodes"][number]);
  1446. }
  1447. snapshot = {
  1448. rows: {
  1449. window: [
  1450. {
  1451. ...graphRow,
  1452. display: {
  1453. ...graphRow.display,
  1454. causalityGraph: {
  1455. steps,
  1456. lanes,
  1457. participants: participantsOf(steps).map((participant) => ({
  1458. ...participant,
  1459. many: true,
  1460. })),
  1461. handoffs: [],
  1462. phases: [{ id: "phase#a", name: "review", line: 1 }],
  1463. phaseEdges: [],
  1464. },
  1465. },
  1466. },
  1467. ],
  1468. },
  1469. workflowRuns: {
  1470. revision: 1,
  1471. runs: [
  1472. run({
  1473. actors,
  1474. nodes,
  1475. pendingQuestions,
  1476. ...(unlistedByPhase === undefined ? {} : { truncated: true, unlistedByPhase }),
  1477. }),
  1478. ],
  1479. },
  1480. };
  1481. }
  1482. const mid = (i: number): FanStatus =>
  1483. i === 4 ? "failed" : i === 2 || i === 6 || i === 8 ? "running" : "done";
  1484. const question = {
  1485. qid: "q-6",
  1486. actorSiteId: "actor#1",
  1487. actorOrdinal: 6,
  1488. question: "Treat the failing assertion as a bug or as drift?",
  1489. };
  1490. it("钉 5 枚:asking → running → failed → 补位;问题挂在钉住的提问者下面;第六枚是门,门关着", () => {
  1491. fanoutSnapshot(9, mid, [question]);
  1492. const view = renderPane();
  1493. const section = view.getByTestId("workflow-run-phase");
  1494. expect(section.getAttribute("data-phase-open")).toBe("true");
  1495. const pins = within(section).getByTestId("workflow-roster-pins");
  1496. const pills = within(pins).getAllByTestId("workflow-agent-pill");
  1497. // asking 的 6 领头,再是 running 的 2、8,然后 failed 的 4,最后补位的 1。
  1498. expect(pills.map((pill) => pill.textContent)).toEqual([
  1499. "reviewer-61 tasks",
  1500. "reviewer-21 tasks",
  1501. "reviewer-81 tasks",
  1502. "reviewer-41 tasks",
  1503. "reviewer-11 tasks",
  1504. ]);
  1505. // 问题紧跟 reviewer-6 那一行(同一个纵向 flex 容器里)。
  1506. const row = within(pins).getByTestId("workflow-run-question");
  1507. expect(row.getAttribute("data-qid")).toBe("q-6");
  1508. expect(row.parentElement).toBe(pills[0]!.parentElement);
  1509. // 门:其余四个(3 5 7 9,全 done)——两张脸、「4 more」、计数只数其余、下箭头。
  1510. const door = within(section).getByTestId("workflow-roster-more-row");
  1511. expect(door.tagName).toBe("BUTTON");
  1512. expect(door.getAttribute("data-door")).toBe("closed");
  1513. expect(door.getAttribute("data-more-count")).toBe("4");
  1514. expect(door.getAttribute("title")).toBe("4 more subagents · list them here");
  1515. const tally = within(door).getByTestId("workflow-roster-tally");
  1516. expect(
  1517. [...tally.querySelectorAll("[data-roster-count]")].map(
  1518. (item) => `${item.getAttribute("data-roster-count")}:${item.textContent}`,
  1519. ),
  1520. ).toEqual(["done:4"]);
  1521. expect(within(door).getByTestId("workflow-more-chevron")).toBeTruthy();
  1522. expect(within(door).queryByTestId("workflow-more-open")).toBeNull();
  1523. // 门关着:没有名单;正文里也没有格子、量条、头像串。
  1524. expect(within(section).queryByTestId("workflow-roster-roll")).toBeNull();
  1525. expect(within(section).queryByTestId("workflow-agent-cell")).toBeNull();
  1526. expect(within(section).queryByTestId("workflow-roster-meter")).toBeNull();
  1527. expect(within(section).queryByTestId("workflow-roster-meter-mini")).toBeNull();
  1528. expect(within(section).queryByTestId("workflow-run-phase-cluster")).toBeNull();
  1529. });
  1530. it("门后是名单:只有其余的人、按状态分组、组头是计数;再点门收起;名单里的行开 transcript 带 workspace scope", () => {
  1531. // 60 人:1、7 running,6 failed,其余 done。
  1532. fanoutSnapshot(60, (i) => (i === 1 || i === 7 ? "running" : i === 6 ? "failed" : "done"));
  1533. const view = renderPane();
  1534. const section = view.getByTestId("workflow-run-phase");
  1535. const door = within(section).getByTestId("workflow-roster-more-row");
  1536. // running 先钉:钉位 = 1、7、6、2、3;其余 55 = 4 5 8…60。
  1537. expect(door.getAttribute("data-more-count")).toBe("55");
  1538. expect(door.getAttribute("aria-expanded")).toBe("false");
  1539. fireEvent.click(door);
  1540. expect(door.getAttribute("aria-expanded")).toBe("true");
  1541. expect(door.getAttribute("data-door")).toBe("open");
  1542. expect(within(door).queryByTestId("workflow-roster-tally")).toBeNull();
  1543. const roll = within(section).getByTestId("workflow-roster-roll");
  1544. const headings = within(roll).getAllByTestId("workflow-roll-heading");
  1545. expect(headings.map((heading) => heading.textContent)).toEqual(["55done"]);
  1546. const rows = within(roll).getAllByTestId("workflow-agent-pill");
  1547. expect(rows).toHaveLength(55);
  1548. expect(rows.every((entry) => entry.getAttribute("data-pill-size") === "row")).toBe(true);
  1549. // 钉住的五个不在名单里。
  1550. const names = rows.map((entry) => entry.getAttribute("title"));
  1551. for (const pinned of ["reviewer-6", "reviewer-1", "reviewer-7", "reviewer-2", "reviewer-3"]) {
  1552. expect(names).not.toContain(pinned);
  1553. }
  1554. expect(names.slice(0, 3)).toEqual(["reviewer-4", "reviewer-5", "reviewer-8"]);
  1555. // 名单里的行是按钮,开 transcript 带 tab 自己的 workspace scope。
  1556. const target = rows.find((entry) => entry.getAttribute("title") === "reviewer-5")!;
  1557. expect(target.tagName).toBe("BUTTON");
  1558. fireEvent.click(target);
  1559. expect(onOpenWorkflowActorSession).toHaveBeenCalledWith({
  1560. workspacePath: "/workspace",
  1561. parentSessionId: "parent-a",
  1562. runId: "dwfrun-1",
  1563. actorSessionId: "dwf-dwfrun-1-actor_1@5",
  1564. siteId: "actor#1",
  1565. ordinal: 5,
  1566. actorName: "reviewer-5",
  1567. });
  1568. // 再点门:名单收起,计数行回来。
  1569. fireEvent.click(door);
  1570. expect(within(section).queryByTestId("workflow-roster-roll")).toBeNull();
  1571. expect(within(door).getByTestId("workflow-roster-tally")).toBeTruthy();
  1572. });
  1573. it("名单按注意力序分组:running、pending 在 done 前面;第六个提问者落在名单里带 ?", () => {
  1574. // 九人:1 2 3 4 5 6 都在提问(钉五个,第六个落进名单);7 running、8 pending、9 done。
  1575. const asks = [1, 2, 3, 4, 5, 6].map((i) => ({
  1576. qid: `q-${i}`,
  1577. actorSiteId: "actor#1",
  1578. actorOrdinal: i,
  1579. question: `q ${i}`,
  1580. }));
  1581. fanoutSnapshot(9, (i) => (i === 7 ? "running" : i === 8 ? "pending" : "done"), asks);
  1582. const view = renderPane();
  1583. const section = view.getByTestId("workflow-run-phase");
  1584. fireEvent.click(within(section).getByTestId("workflow-roster-more-row"));
  1585. const roll = within(section).getByTestId("workflow-roster-roll");
  1586. expect(
  1587. within(roll)
  1588. .getAllByTestId("workflow-roll-heading")
  1589. .map((heading) => heading.getAttribute("data-roll-group")),
  1590. ).toEqual(["running", "pending", "done"]);
  1591. const rows = within(roll).getAllByTestId("workflow-agent-pill");
  1592. expect(rows.map((entry) => entry.getAttribute("title"))).toEqual([
  1593. "reviewer-7",
  1594. "reviewer-8",
  1595. "reviewer-6",
  1596. "reviewer-9",
  1597. ]);
  1598. // 第六个提问者 reviewer-6:行上一枚 ?;问题本身不在名单里重复(孤儿块也不收它——它有提问者)。
  1599. expect(within(rows[2]!).getByTestId("workflow-roll-asking")).toBeTruthy();
  1600. expect(within(roll).queryByTestId("workflow-run-question")).toBeNull();
  1601. });
  1602. it("折起的名册站在节头带迷你量条而不是头像串", () => {
  1603. fanoutSnapshot(9, mid);
  1604. const view = renderPane();
  1605. const section = view.getByTestId("workflow-run-phase");
  1606. fireEvent.click(within(section).getByTestId("workflow-run-phase-toggle"));
  1607. expect(section.getAttribute("data-phase-open")).toBe("false");
  1608. expect(within(section).getByTestId("workflow-roster-meter-mini")).toBeTruthy();
  1609. expect(within(section).queryByTestId("workflow-run-phase-cluster")).toBeNull();
  1610. // 六个及以下仍是头像串。
  1611. fanoutSnapshot(6, mid);
  1612. const few = rerenderPane(view);
  1613. const small = few.getByTestId("workflow-run-phase");
  1614. fireEvent.click(within(small).getByTestId("workflow-run-phase-toggle"));
  1615. expect(within(small).queryByTestId("workflow-roster-meter-mini")).toBeNull();
  1616. });
  1617. // 表外的那些(docs/dynamic-workflow/presentation.md「Past six participants」「The spine」):
  1618. // 被归约淘汰的子代理没有药丸也没有行,但门、计数行、量条与 settled/observed 都得算上它们。
  1619. it("被淘汰的子代理进门的人数、计数行、迷你量条与 settled/observed,名单末尾一行淡字交代差额", () => {
  1620. fanoutSnapshot(
  1621. 8,
  1622. (i) => (i === 1 ? "running" : "done"),
  1623. [],
  1624. [{ phaseName: "review", actors: 300, actorsSettled: 300, actorsFailed: 2, settled: 300 }],
  1625. );
  1626. const view = renderPane();
  1627. const section = view.getByTestId("workflow-run-phase");
  1628. // 门:表内其余三个 + 表外三百个。
  1629. const door = within(section).getByTestId("workflow-roster-more-row");
  1630. expect(door.getAttribute("data-more-count")).toBe("303");
  1631. expect(door.getAttribute("title")).toBe("303 more subagents · list them here");
  1632. expect(
  1633. [
  1634. ...within(door)
  1635. .getByTestId("workflow-roster-tally")
  1636. .querySelectorAll("[data-roster-count]"),
  1637. ].map((item) => `${item.getAttribute("data-roster-count")}:${item.textContent}`),
  1638. ).toEqual(["done:301", "failed:2"]);
  1639. // 步数:表内 8 个里结算了 7 个,表外 300 个分子分母一起抬。
  1640. expect(within(section).getByTestId("workflow-run-phase-fraction").textContent).toBe("307/308");
  1641. // 名单只列得出表内的三个,末尾一行说清剩下的三百个。
  1642. fireEvent.click(door);
  1643. const roll = within(section).getByTestId("workflow-roster-roll");
  1644. expect(within(roll).getAllByTestId("workflow-agent-pill")).toHaveLength(3);
  1645. expect(
  1646. within(roll)
  1647. .getAllByTestId("workflow-roll-heading")
  1648. .map((h) => h.textContent),
  1649. ).toEqual(["3done"]);
  1650. expect(within(roll).getByTestId("workflow-roll-unlisted").textContent).toBe(
  1651. "300 more agents not listed",
  1652. );
  1653. // 折起:节头是迷你量条(名册的判定同样算上表外的)。
  1654. fireEvent.click(within(section).getByTestId("workflow-run-phase-toggle"));
  1655. expect(within(section).getByTestId("workflow-roster-meter-mini")).toBeTruthy();
  1656. });
  1657. it("四枚药丸加三百个还没跑的被拒子代理也是名册:门在,量条在,头像串不在,计数行全是 pending", () => {
  1658. fanoutSnapshot(4, () => "running", [], [{ phaseName: "review", actors: 300, settled: 0 }]);
  1659. const view = renderPane();
  1660. const section = view.getByTestId("workflow-run-phase");
  1661. expect(within(section).getAllByTestId("workflow-agent-pill")).toHaveLength(4);
  1662. const door = within(section).getByTestId("workflow-roster-more-row");
  1663. expect(door.getAttribute("data-more-count")).toBe("300");
  1664. // `actorsSettled` 缺席:三百个一个都没跑完,计数行不能把它们说成 done。
  1665. expect(
  1666. [
  1667. ...within(door)
  1668. .getByTestId("workflow-roster-tally")
  1669. .querySelectorAll("[data-roster-count]"),
  1670. ].map((item) => `${item.getAttribute("data-roster-count")}:${item.textContent}`),
  1671. ).toEqual(["pending:300"]);
  1672. fireEvent.click(within(section).getByTestId("workflow-run-phase-toggle"));
  1673. expect(within(section).getByTestId("workflow-roster-meter-mini")).toBeTruthy();
  1674. expect(within(section).queryByTestId("workflow-run-phase-cluster")).toBeNull();
  1675. });
  1676. it("zh-CN:门的两种文案与组头", () => {
  1677. fanoutSnapshot(9, mid);
  1678. const view = renderPane("zh-CN");
  1679. const door = view.getByTestId("workflow-roster-more-row");
  1680. expect(door.textContent).toContain("还有 4 个");
  1681. expect(door.getAttribute("title")).toBe("还有 4 个子代理 · 在这里列出");
  1682. fireEvent.click(door);
  1683. expect(door.getAttribute("title")).toBe("还有 4 个子代理 · 收起");
  1684. expect(view.getByTestId("workflow-roll-heading").textContent).toBe("4个已完成");
  1685. });
  1686. // ── 落点(追记「五枚药丸与一扇门」):卡上「还有 n 个」那一行 / 站头把站 id 交给宿主,tab 带着
  1687. // focusPhaseId 到这里——展开、开门、节头滚到顶、亮一下;同一站换 openedAt 再落一次。
  1688. const landedTree = (overrides: Partial<WorkflowRunSidePaneTab>) =>
  1689. createElement(
  1690. ZCodeIntlProvider,
  1691. { initialLocale: "en-US" },
  1692. createElement(WorkflowRunSidePane, {
  1693. tab: { ...tab, ...overrides },
  1694. onOpenWorkflowActorSession,
  1695. }),
  1696. );
  1697. it("tab 带 focusPhaseId:那一站展开、门开着、节头滚到顶并亮一下;换 openedAt 再落;不带就不落", () => {
  1698. const scrollIntoView = vi.fn();
  1699. // jsdom 没有 scrollIntoView。
  1700. Element.prototype.scrollIntoView = scrollIntoView;
  1701. // 没有在跑的站:默认全部折起,展开只能来自落点。
  1702. fanoutSnapshot(9, () => "done");
  1703. const view = render(landedTree({ focusPhaseId: "phase#a", openedAt: 1 }));
  1704. const section = view.getByTestId("workflow-run-phase");
  1705. expect(section.getAttribute("data-phase-open")).toBe("true");
  1706. expect(section.getAttribute("data-phase-landed")).toBe("true");
  1707. const head = within(section).getByTestId("workflow-run-phase-toggle");
  1708. expect(head.className).toContain("wf-landed");
  1709. expect(
  1710. within(section).getByTestId("workflow-roster-more-row").getAttribute("aria-expanded"),
  1711. ).toBe("true");
  1712. expect(within(section).getByTestId("workflow-roster-roll")).toBeTruthy();
  1713. expect(scrollIntoView).toHaveBeenCalledTimes(1);
  1714. expect(scrollIntoView).toHaveBeenCalledWith(expect.objectContaining({ block: "start" }));
  1715. expect(scrollIntoView.mock.instances[0]).toBe(head);
  1716. // 同一站再点一次(openedAt 刷新):再落。
  1717. view.rerender(landedTree({ focusPhaseId: "phase#a", openedAt: 2 }));
  1718. expect(scrollIntoView).toHaveBeenCalledTimes(2);
  1719. // 不带落点重开(表头的 ⤢):不滚、不收。
  1720. view.rerender(landedTree({ openedAt: 3 }));
  1721. expect(scrollIntoView).toHaveBeenCalledTimes(2);
  1722. expect(view.getByTestId("workflow-run-phase").getAttribute("data-phase-open")).toBe("true");
  1723. });
  1724. it("亮一下是一次性的:1.2 s 后落点标记退场,展开与名单留着", () => {
  1725. vi.useFakeTimers();
  1726. try {
  1727. fanoutSnapshot(9, () => "done");
  1728. const view = render(landedTree({ focusPhaseId: "phase#a", openedAt: 1 }));
  1729. expect(view.getByTestId("workflow-run-phase").getAttribute("data-phase-landed")).toBe("true");
  1730. act(() => {
  1731. vi.advanceTimersByTime(1200);
  1732. });
  1733. const section = view.getByTestId("workflow-run-phase");
  1734. expect(section.getAttribute("data-phase-landed")).toBeNull();
  1735. expect(section.getAttribute("data-phase-open")).toBe("true");
  1736. expect(within(section).getByTestId("workflow-roster-roll")).toBeTruthy();
  1737. } finally {
  1738. vi.useRealTimers();
  1739. }
  1740. });
  1741. });
  1742. // ── 状态头下的 lineage 行(docs/dynamic-workflow/presentation.md「The run pane」)──
  1743. describe("WorkflowRunSidePane lineage", () => {
  1744. it.each([
  1745. ["en-US", "Amends run"],
  1746. ["zh-CN", "调整自 run"],
  1747. ] as const)("修订出来的 run:状态头下一行「调整自 run X」:%s", (locale, label) => {
  1748. setSnapshot({ run: run({ resumedFrom: "dwfrun-prev" }) });
  1749. const view = renderPane(locale);
  1750. const line = view.getByTestId("workflow-run-amends");
  1751. expect(line.textContent).toContain(label);
  1752. expect(line.textContent).toContain("dwfrun-prev");
  1753. expect(view.queryByTestId("workflow-run-superseded-by")).toBeNull();
  1754. });
  1755. it("被替代的 run:状态词带原因,链接开后继的详情、带后继自己的发起行 id", () => {
  1756. const successor = run({
  1757. runId: "dwfrun-next",
  1758. toolCallId: "tool-wf-2",
  1759. resumedFrom: "dwfrun-1",
  1760. });
  1761. const predecessor = run({
  1762. status: "stopped",
  1763. stopReason: "superseded",
  1764. supersededBy: "dwfrun-next",
  1765. } as never);
  1766. snapshot = {
  1767. rows: { window: [graphRow] },
  1768. workflowRuns: { revision: 1, runs: [predecessor, successor] },
  1769. };
  1770. const view = renderPane("en-US", { withOpenRunCallback: true });
  1771. expect(view.getByTestId("workflow-run-status").textContent).toBe("Stopped");
  1772. expect(view.getByTestId("workflow-run-status-reason").textContent).toContain("superseded");
  1773. // 被替代的 run 没有 resumable 位:没有 Resume。
  1774. expect(view.queryByTestId("workflow-run-resume")).toBeNull();
  1775. const link = view.getByTestId("workflow-run-superseded-by");
  1776. expect(link.tagName).toBe("BUTTON");
  1777. expect(link.textContent).toContain("Superseded by run");
  1778. expect(link.textContent).toContain("dwfrun-next");
  1779. fireEvent.click(link);
  1780. expect(onOpenWorkflowRun).toHaveBeenCalledTimes(1);
  1781. expect(onOpenWorkflowRun).toHaveBeenCalledWith(
  1782. expect.objectContaining({
  1783. parentSessionId: "parent-a",
  1784. runId: "dwfrun-next",
  1785. toolCallId: "tool-wf-2",
  1786. workspacePath: "/workspace",
  1787. }),
  1788. );
  1789. });
  1790. it("后继不在投影里时那一行是静态文字", () => {
  1791. setSnapshot({
  1792. run: run({
  1793. status: "stopped",
  1794. stopReason: "superseded",
  1795. supersededBy: "dwfrun-gone",
  1796. } as never),
  1797. });
  1798. const view = renderPane("zh-CN", { withOpenRunCallback: true });
  1799. const line = view.getByTestId("workflow-run-superseded-by");
  1800. expect(line.tagName).toBe("DIV");
  1801. expect(line.textContent).toContain("已被替代,后继 run");
  1802. expect(line.textContent).toContain("dwfrun-gone");
  1803. });
  1804. it("普通 run 没有 lineage 行", () => {
  1805. setSnapshot({ run: run() });
  1806. const view = renderPane();
  1807. expect(view.queryByTestId("workflow-run-amends")).toBeNull();
  1808. expect(view.queryByTestId("workflow-run-superseded-by")).toBeNull();
  1809. });
  1810. });
  1811. // ── 「配置」(docs/dynamic-workflow/presentation.md「The run pane」「The settings popover」)──
  1812. // 状态头两行:名字 + Configure / Resume / Stop,其下是灯与状态词 + 并发芯片。Configure 与 Resume 同一道
  1813. // 灰度门;能配置的 run 上,摘要行的模型段也是一个入口。Apply 被接受后面板原地换成新 run 的 tab。
  1814. describe("WorkflowRunSidePane 配置", () => {
  1815. beforeEach(() => {
  1816. setDynamicWorkflowEnabled(true);
  1817. globalThis.ResizeObserver ??= class {
  1818. observe() {}
  1819. unobserve() {}
  1820. disconnect() {}
  1821. } as unknown as typeof ResizeObserver;
  1822. onOpenWorkflowRun.mockClear();
  1823. });
  1824. it("状态头两行:第一行名字与 Configure → Resume → Stop,第二行灯与状态词和并发芯片", () => {
  1825. setSnapshot({
  1826. run: run({
  1827. status: "stopped",
  1828. stopReason: "user",
  1829. resumable: true,
  1830. concurrencyCeiling: 13,
  1831. concurrency: { cap: 13, ceiling: 13, limit: 4 },
  1832. }),
  1833. });
  1834. const view = renderPane();
  1835. const configure = view.getByTestId("workflow-run-configure");
  1836. const resume = view.getByTestId("workflow-run-resume");
  1837. const cancel = view.getByTestId("workflow-run-cancel");
  1838. expect(configure.textContent).toBe("Configure");
  1839. expect(
  1840. configure.compareDocumentPosition(resume) & Node.DOCUMENT_POSITION_FOLLOWING,
  1841. ).toBeTruthy();
  1842. expect(resume.compareDocumentPosition(cancel) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  1843. const statusRow = view.getByTestId("workflow-run-status-row");
  1844. expect(statusRow.contains(view.getByTestId("workflow-run-status"))).toBe(true);
  1845. expect(statusRow.contains(view.getByTestId("workflow-run-concurrency"))).toBe(true);
  1846. expect(view.getByTestId("workflow-run-concurrency").textContent).toBe("Max concurrency 4");
  1847. expect(statusRow.contains(configure)).toBe(false);
  1848. });
  1849. // 芯片与 Configure 同进同退(docs/dynamic-workflow/concurrency.md「What the user sees」):
  1850. // 完成或被替代的 run 上,界已经没有东西在它下面跑、也没有控件能改它,留下的数只会被读成实时读数。
  1851. it.each([
  1852. ["completed", run({ status: "completed" })],
  1853. ["superseded", run({ status: "stopped", stopReason: "superseded", supersededBy: "run-next" })],
  1854. ])("%s 的 run 不画并发芯片,即便界仍在天花板之下", (_case, state) => {
  1855. setSnapshot({
  1856. run: { ...state, concurrencyCeiling: 13, concurrency: { cap: 13, ceiling: 13, limit: 4 } },
  1857. });
  1858. const view = renderPane();
  1859. expect(view.queryByTestId("workflow-run-concurrency")).toBeNull();
  1860. expect(view.queryByTestId("workflow-run-configure")).toBeNull();
  1861. });
  1862. it.each([
  1863. ["completed", run({ status: "completed" })],
  1864. ["superseded", run({ status: "stopped", stopReason: "superseded", supersededBy: "run-next" })],
  1865. ])("%s 的 run 没有 Configure,模型段只是字", (_case, state) => {
  1866. setSnapshot({ run: { ...state, subagentModel: "zhipu/glm-5.3" } });
  1867. const view = renderPane();
  1868. expect(view.queryByTestId("workflow-run-configure")).toBeNull();
  1869. expect(view.getByTestId("workflow-run-subagent-model").tagName).toBe("SPAN");
  1870. });
  1871. it("灰度关:没有 Configure", () => {
  1872. setDynamicWorkflowEnabled(false);
  1873. setSnapshot({ run: run() });
  1874. expect(renderPane().queryByTestId("workflow-run-configure")).toBeNull();
  1875. });
  1876. it("zh-CN 念「配置」;能配置时模型段是按钮,点它与点 Configure 开的是同一个弹层", () => {
  1877. setSnapshot({ run: run({ subagentModel: "zhipu/glm-5.3" }) });
  1878. const view = renderPane("zh-CN");
  1879. expect(view.getByTestId("workflow-run-configure").textContent).toBe("配置");
  1880. const segment = view.getByTestId("workflow-run-subagent-model");
  1881. expect(segment.tagName).toBe("BUTTON");
  1882. fireEvent.click(segment);
  1883. expect(segment.getAttribute("aria-expanded")).toBe("true");
  1884. expect(document.querySelector('[data-testid="workflow-run-settings-popover"]')).not.toBeNull();
  1885. });
  1886. it("Apply 发 amendWorkflowRunSettings {workId ≡ runId, 改过的设置};新 run 进投影后 tab 原地换成它", async () => {
  1887. sendCommand.mockImplementationOnce(
  1888. async () =>
  1889. ({
  1890. status: "accepted",
  1891. result: {
  1892. type: "amendWorkflowRunSettings",
  1893. runId: "dwfrun-2",
  1894. toolCallId: "settings-1",
  1895. supersededRunId: "dwfrun-1",
  1896. },
  1897. }) as never,
  1898. );
  1899. const current = run({
  1900. concurrencyCeiling: 13,
  1901. concurrency: { cap: 13, ceiling: 13, limit: 4 },
  1902. });
  1903. setSnapshot({ run: current });
  1904. const view = renderPane("en-US", { withOpenRunCallback: true });
  1905. fireEvent.click(view.getByTestId("workflow-run-configure"));
  1906. fireEvent.click(
  1907. document.querySelector('[data-testid="workflow-run-settings-bound-decrease"]')!,
  1908. );
  1909. await act(async () => {
  1910. fireEvent.click(document.querySelector('[data-testid="workflow-run-settings-apply"]')!);
  1911. });
  1912. expect(sendCommand).toHaveBeenCalledWith(
  1913. expect.objectContaining({
  1914. type: "amendWorkflowRunSettings",
  1915. payload: { workId: "dwfrun-1", maxConcurrency: 3 },
  1916. sessionId: "parent-a",
  1917. }),
  1918. );
  1919. // 被接受的那一刻新 run 还没进投影:先不动。
  1920. expect(onOpenWorkflowRun).not.toHaveBeenCalled();
  1921. snapshot = {
  1922. ...(snapshot as object),
  1923. workflowRuns: {
  1924. revision: 2,
  1925. runs: [
  1926. { ...current, status: "stopped", stopReason: "superseded", supersededBy: "dwfrun-2" },
  1927. run({ runId: "dwfrun-2", toolCallId: "settings-1", resumedFrom: "dwfrun-1" }),
  1928. ],
  1929. },
  1930. };
  1931. view.rerender(
  1932. createElement(
  1933. ZCodeIntlProvider,
  1934. { initialLocale: "en-US" },
  1935. createElement(WorkflowRunSidePane, { tab: { ...tab }, onOpenWorkflowRun }),
  1936. ),
  1937. );
  1938. await waitFor(() => expect(onOpenWorkflowRun).toHaveBeenCalledTimes(1));
  1939. expect(onOpenWorkflowRun).toHaveBeenCalledWith({
  1940. workspacePath: "/workspace",
  1941. parentSessionId: "parent-a",
  1942. toolCallId: "settings-1",
  1943. runId: "dwfrun-2",
  1944. workflowName: "Fan-out review",
  1945. replaceRunId: "dwfrun-1",
  1946. });
  1947. });
  1948. // 只改并发上限、run 又在飞:就地生效,结果里的 runId 就是这个 run 自己、没有 supersededRunId
  1949. // (docs/dynamic-workflow/concurrency.md)。没有后继可跟——这个 tab 已经是它了。
  1950. it("就地生效的结果(runId 是自己、无 supersededRunId):不请求换 tab", async () => {
  1951. sendCommand.mockImplementationOnce(
  1952. async () =>
  1953. ({
  1954. status: "accepted",
  1955. result: {
  1956. type: "amendWorkflowRunSettings",
  1957. runId: "dwfrun-1",
  1958. toolCallId: "settings-1",
  1959. },
  1960. }) as never,
  1961. );
  1962. const current = run({
  1963. concurrencyCeiling: 13,
  1964. concurrency: { cap: 13, ceiling: 13, limit: 4 },
  1965. });
  1966. setSnapshot({ run: current });
  1967. const view = renderPane("en-US", { withOpenRunCallback: true });
  1968. fireEvent.click(view.getByTestId("workflow-run-configure"));
  1969. // 就地生效的后果句:不再念「将停止当前运行」。
  1970. fireEvent.click(
  1971. document.querySelector('[data-testid="workflow-run-settings-bound-decrease"]')!,
  1972. );
  1973. expect(
  1974. document.querySelector('[data-testid="workflow-run-settings-consequence"]')?.textContent,
  1975. ).toBe("Applies to this run right away; no new run is started.");
  1976. await act(async () => {
  1977. fireEvent.click(document.querySelector('[data-testid="workflow-run-settings-apply"]')!);
  1978. });
  1979. expect(sendCommand).toHaveBeenCalledWith(
  1980. expect.objectContaining({ payload: { workId: "dwfrun-1", maxConcurrency: 3 } }),
  1981. );
  1982. // 这个 run 一直在投影里:跟随逻辑若不认得「后继就是自己」,这里会立刻请求把 tab 换掉。
  1983. await act(async () => {});
  1984. expect(onOpenWorkflowRun).not.toHaveBeenCalled();
  1985. });
  1986. it("「配置」出来的 run 在设置轮落地之前借前驱的图;设置轮落地后来龙去脉说「由你调整设置」", () => {
  1987. const settingsTab = { ...tab, toolCallId: "settings-1", runId: "dwfrun-2" };
  1988. const predecessor = run({
  1989. status: "stopped",
  1990. stopReason: "superseded",
  1991. supersededBy: "dwfrun-2",
  1992. });
  1993. const successor = run({ runId: "dwfrun-2", toolCallId: "settings-1", resumedFrom: "dwfrun-1" });
  1994. snapshot = {
  1995. rows: { window: [graphRow] },
  1996. workflowRuns: { revision: 1, runs: [predecessor, successor] },
  1997. };
  1998. const borrowed = render(
  1999. createElement(
  2000. ZCodeIntlProvider,
  2001. { initialLocale: "zh-CN" },
  2002. createElement(WorkflowRunSidePane, { tab: settingsTab }),
  2003. ),
  2004. );
  2005. expect(borrowed.getByTestId("workflow-run-phases")).toBeTruthy();
  2006. expect(borrowed.queryByTestId("workflow-run-provenance")).toBeNull();
  2007. cleanup();
  2008. const workflowLaunch = {
  2009. runId: "dwfrun-2",
  2010. toolCallId: "settings-1",
  2011. name: "Fan-out review",
  2012. display: graphRow.display,
  2013. amend: {
  2014. predecessorRunId: "dwfrun-1",
  2015. subagentModel: { to: "zhipu/glm-5.3-flash" },
  2016. maxConcurrency: { from: 13, to: 4 },
  2017. ceiling: 13,
  2018. },
  2019. };
  2020. snapshot = {
  2021. rows: {
  2022. window: [
  2023. graphRow,
  2024. {
  2025. kind: "turnHeader" as const,
  2026. rowId: "row-header",
  2027. origin: "workflowLaunch" as const,
  2028. executionKind: "controlOnly" as const,
  2029. state: "completedSuccess" as const,
  2030. startedAt: Date.UTC(2026, 8, 18, 4, 51),
  2031. workflowLaunch,
  2032. },
  2033. ],
  2034. },
  2035. workflowRuns: { revision: 2, runs: [predecessor, successor] },
  2036. };
  2037. const landed = render(
  2038. createElement(
  2039. ZCodeIntlProvider,
  2040. { initialLocale: "zh-CN" },
  2041. createElement(WorkflowRunSidePane, { tab: settingsTab }),
  2042. ),
  2043. );
  2044. const provenance = landed.getByTestId("workflow-run-provenance");
  2045. expect(provenance.getAttribute("data-workflow-launch-kind")).toBe("settings");
  2046. expect(provenance.textContent).toContain("由你调整设置");
  2047. expect(landed.queryByTestId("workflow-run-provenance-scope")).toBeNull();
  2048. const rows = landed.getByTestId("workflow-run-provenance-settings").textContent ?? "";
  2049. expect(rows).toContain("子代理模型");
  2050. expect(rows).toContain("会话模型 → glm-5.3-flash");
  2051. expect(rows).toContain("最大并发数");
  2052. expect(rows).toContain("默认 13 → 4");
  2053. });
  2054. // 就地生效的设置轮(docs/dynamic-workflow/concurrency.md):`amend` 不带 predecessorRunId。
  2055. // 来龙去脉块按 toolCallId 认轮次,所以只有当用户开的正是那一轮的 tab 时才会读到它——
  2056. // 这一块从不读 predecessorRunId,缺了它照常把改了什么念出来,不炸。
  2057. it("就地生效的设置轮落在来龙去脉块上:没有前驱也照常念「由你调整设置」与上限那一行", () => {
  2058. const retuned = run({ runId: "dwfrun-1", toolCallId: "tool-1" });
  2059. const retuneTab = { ...tab, toolCallId: "settings-9", runId: "dwfrun-1" };
  2060. snapshot = {
  2061. rows: {
  2062. window: [
  2063. graphRow,
  2064. {
  2065. kind: "turnHeader" as const,
  2066. rowId: "row-retune",
  2067. origin: "workflowLaunch" as const,
  2068. executionKind: "controlOnly" as const,
  2069. state: "completedSuccess" as const,
  2070. startedAt: Date.UTC(2026, 8, 18, 4, 51),
  2071. workflowLaunch: {
  2072. runId: "dwfrun-1",
  2073. toolCallId: "settings-9",
  2074. name: "Fan-out review",
  2075. amend: { maxConcurrency: { from: 13, to: 4 }, ceiling: 13 },
  2076. },
  2077. },
  2078. ],
  2079. },
  2080. workflowRuns: { revision: 1, runs: [retuned] },
  2081. };
  2082. const view = render(
  2083. createElement(
  2084. ZCodeIntlProvider,
  2085. { initialLocale: "zh-CN" },
  2086. createElement(WorkflowRunSidePane, { tab: retuneTab }),
  2087. ),
  2088. );
  2089. const provenance = view.getByTestId("workflow-run-provenance");
  2090. expect(provenance.getAttribute("data-workflow-launch-kind")).toBe("settings");
  2091. expect(provenance.textContent).toContain("由你调整设置");
  2092. const rows = view.getByTestId("workflow-run-provenance-settings").textContent ?? "";
  2093. expect(rows).toContain("最大并发数");
  2094. expect(rows).toContain("默认 13 → 4");
  2095. expect(rows).not.toContain("子代理模型");
  2096. });
  2097. });