workflowRunSidePane.test.ts 96 KB

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