workflowTimelineStreams.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // @vitest-environment jsdom
  2. // 阶段流(docs/dynamic-workflow/presentation.md「Streams」「Bands and tracks」「Station status」
  3. // 「Stream rails」「The spine」):channel 串起来的 future 阶段是一条线上的几站,不是一条带里互不相干
  4. // 的几条 strand。触发它的是 testfield 的「2077 未来职业流水线」:五个阶段两两 alongside、phaseEdges
  5. // 为空,旧画法是五条分支、第四站没跑就是绿灯、第五站替 run 背了停止的红灯。
  6. import { createElement } from "react";
  7. import { cleanup, render, within } from "@testing-library/react";
  8. import { afterEach, describe, expect, it } from "vitest";
  9. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  10. import type { WorkflowCausalityGraphData } from "@/components/workflow-graph/types.js";
  11. import { foldPhaseBands, foldPhaseEdges } from "@/components/workflow-timeline/timeline-bands.js";
  12. import { buildWorkflowTimeline } from "@/components/workflow-timeline/timeline-model.js";
  13. import { WorkflowTimeline } from "@/components/workflow-timeline/WorkflowTimeline.js";
  14. import { spineLayout } from "@/app-shell/workflowRunSpine.js";
  15. import { WorkflowRunPhaseList } from "@/app-shell/WorkflowRunPhaseList.js";
  16. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  17. interface Spec {
  18. names: readonly string[];
  19. /** 站下标 → 与它并行的站下标。 */
  20. alongside?: Record<number, readonly number[]>;
  21. edges?: readonly (readonly [number, number])[];
  22. streams?: readonly (readonly [number, number])[];
  23. /** 没有成员 step 的站(只有标记)。 */
  24. markerOnly?: readonly number[];
  25. }
  26. function graphOf({
  27. alongside = {},
  28. edges = [],
  29. markerOnly = [],
  30. names,
  31. streams = [],
  32. }: Spec): WorkflowCausalityGraphData {
  33. const members = names.flatMap((_, i) => (markerOnly.includes(i) ? [] : [i]));
  34. return {
  35. steps: members.map((i) => ({
  36. id: `ask#${i + 1}`,
  37. kind: "ask" as const,
  38. label: names[i]!,
  39. lane: `actor#${i + 1}`,
  40. phase: `phase#${i + 1}`,
  41. })),
  42. lanes: members.map((i) => ({ id: `actor#${i + 1}`, name: `agent ${i + 1}` })),
  43. participants: members.map((i) => ({
  44. id: `phase#${i + 1}:actor#${i + 1}`,
  45. phase: `phase#${i + 1}`,
  46. lane: `actor#${i + 1}`,
  47. steps: [`ask#${i + 1}`],
  48. })),
  49. handoffs: [],
  50. phases: names.map((name, i) => ({
  51. id: `phase#${i + 1}`,
  52. name,
  53. ...(alongside[i] === undefined
  54. ? {}
  55. : { alongside: alongside[i]!.map((j) => `phase#${j + 1}`) }),
  56. })),
  57. phaseEdges: edges.map(([from, to]) => ({ from: `phase#${from + 1}`, to: `phase#${to + 1}` })),
  58. ...(streams.length === 0
  59. ? {}
  60. : {
  61. phaseStreams: streams.map(([from, to]) => ({
  62. from: `phase#${from + 1}`,
  63. to: `phase#${to + 1}`,
  64. })),
  65. }),
  66. exits: [`phase#${names.length}`],
  67. };
  68. }
  69. /** 五站两两并行(每站报出它之前的所有站),流 0 → 1 → 2 → 3 → 4,没有控制边。 */
  70. const PIPELINE: Spec = {
  71. alongside: { 1: [0], 2: [0, 1], 3: [0, 1, 2], 4: [0, 1, 2, 3] },
  72. names: ["Invent", "Post", "Tell", "Roast", "Bind"],
  73. streams: [
  74. [0, 1],
  75. [1, 2],
  76. [2, 3],
  77. [3, 4],
  78. ],
  79. };
  80. type Node = WorkflowRunState["nodes"][number];
  81. type Status = "done" | "running" | "queued" | "failed";
  82. const node = (station: number, ordinal: number, status: Status): Node =>
  83. ({
  84. siteId: `ask#${station + 1}`,
  85. ordinal,
  86. actorSiteId: `actor#${station + 1}`,
  87. actorOrdinal: ordinal,
  88. phaseName: PIPELINE.names[station],
  89. ...(status === "done"
  90. ? { phase: "settled", outcome: "ok" }
  91. : status === "failed"
  92. ? { phase: "settled", outcome: "cancelled" }
  93. : status === "running"
  94. ? { phase: "executing" }
  95. : { phase: "queued" }),
  96. }) as Node;
  97. /** 每站的节点状态列表 → run;五个标记都已进入,currentPhase 是最后进入的那个(第五站)。 */
  98. function runOf(
  99. stages: readonly (readonly Status[])[],
  100. status: WorkflowRunState["status"] = "running",
  101. ): WorkflowRunState {
  102. return {
  103. runId: "dwfrun-1",
  104. toolCallId: "tool-wf-1",
  105. status,
  106. usage: { spentTokens: 0, nodesUsed: 0 },
  107. actors: [],
  108. nodes: stages.flatMap((list, station) => list.map((s, k) => node(station, k + 1, s))),
  109. phases: PIPELINE.names.map((name) => ({ name, rounds: 1 })),
  110. currentPhase: PIPELINE.names[4],
  111. lastEventSequence: 0,
  112. };
  113. }
  114. const lamps = (model: ReturnType<typeof buildWorkflowTimeline>) =>
  115. model.stations.map((station) => station.status);
  116. const streamInks = (model: ReturnType<typeof buildWorkflowTimeline>) =>
  117. model.rails.filter((rail) => rail.kind === "stream").map((rail) => rail.ink);
  118. afterEach(cleanup);
  119. describe("foldPhaseBands · 流把 strand 从带里拿出来", () => {
  120. it("流水线的五站落在同一条轨道上,带整个解散", () => {
  121. const near = [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]];
  122. const streams = PIPELINE.streams!.map(([from, to]) => ({ from, to }));
  123. expect(foldPhaseBands(5, near, streams)).toEqual([]);
  124. // 侧栏的迷你运行线不传流:仍是 alongside 的带。
  125. expect(foldPhaseBands(5, near)).toEqual([
  126. { from: 0, to: 4, tracks: [[0], [1], [2], [3], [4]] },
  127. ]);
  128. });
  129. it("流够不着的 strand(旁路 future)仍占自己的轨道,带还是带", () => {
  130. const near = [[], [0], [0, 1], [0, 1, 2]];
  131. expect(
  132. foldPhaseBands(4, near, [
  133. { from: 0, to: 1 },
  134. { from: 1, to: 2 },
  135. ]),
  136. ).toEqual([{ from: 0, to: 3, tracks: [[0, 1, 2], [3]] }]);
  137. });
  138. it("汇入:两个互不可达的生产者,消费者跟着先声明的那个", () => {
  139. // A ∥ B ∥ C,A → C、B → C:A 与 B 谁也够不着谁,C 被两者都够得着。
  140. expect(
  141. foldPhaseBands(
  142. 3,
  143. [[], [0], [0, 1]],
  144. [
  145. { from: 0, to: 2 },
  146. { from: 1, to: 2 },
  147. ],
  148. ),
  149. ).toEqual([{ from: 0, to: 2, tracks: [[0, 2], [1]] }]);
  150. });
  151. });
  152. describe("foldPhaseEdges · 流轨与流弧", () => {
  153. it("解散的带:相邻两站之间是流轨,没有分叉、汇合与双线段", () => {
  154. const streams = PIPELINE.streams!.map(([from, to]) => ({ from, to }));
  155. const fold = foldPhaseEdges(5, [], [], streams);
  156. expect(fold.bands).toEqual([]);
  157. expect(fold.rails).toEqual([
  158. { from: 0, kind: "stream", to: 1 },
  159. { from: 1, kind: "stream", to: 2 },
  160. { from: 2, kind: "stream", to: 3 },
  161. { from: 3, kind: "stream", to: 4 },
  162. ]);
  163. expect(fold.arcs).toEqual([]);
  164. });
  165. it("流轨顶替同一对站的普通轨道段;带内同轨道相邻的一对也是流轨", () => {
  166. const bands = foldPhaseBands(
  167. 5,
  168. [[], [0], [0, 1], [0, 1, 2], []],
  169. [
  170. { from: 0, to: 1 },
  171. { from: 1, to: 2 },
  172. ],
  173. );
  174. const fold = foldPhaseEdges(
  175. 5,
  176. bands,
  177. [
  178. [0, 1],
  179. [2, 4],
  180. [3, 4],
  181. ].map(([from, to]) => ({ from: from!, to: to! })),
  182. [
  183. { from: 0, to: 1 },
  184. { from: 1, to: 2 },
  185. ],
  186. );
  187. expect(fold.rails.filter((rail) => rail.from === 0 && rail.to === 1)).toEqual([
  188. { from: 0, kind: "stream", to: 1 },
  189. ]);
  190. expect(fold.rails).toContainEqual({ from: 1, kind: "stream", to: 2 });
  191. });
  192. it("不相邻的流是一条流弧:同轨道的在那条轨道的空里,它不是回环", () => {
  193. const fold = foldPhaseEdges(3, [], [{ from: 0, to: 1 }], [{ from: 0, to: 2 }]);
  194. expect(fold.arcs).toEqual([{ air: 0, from: 0, stream: true, to: 2 }]);
  195. });
  196. });
  197. describe("buildWorkflowTimeline · 流水线", () => {
  198. it("五站一条线:没有带,四段流轨,全在主线上", () => {
  199. const model = buildWorkflowTimeline(graphOf(PIPELINE), undefined);
  200. expect(model.bands).toEqual([]);
  201. expect(model.stations.map((station) => station.track)).toEqual([0, 0, 0, 0, 0]);
  202. expect(model.rails.map((rail) => [rail.from, rail.to, rail.kind])).toEqual([
  203. [0, 1, "stream"],
  204. [1, 2, "stream"],
  205. [2, 3, "stream"],
  206. [3, 4, "stream"],
  207. ]);
  208. expect(streamInks(model)).toEqual(["faint", "faint", "faint", "faint"]);
  209. });
  210. it("t≈10s:还没收到活的站是 pending,不因为标记进入过就绿,也不替 currentPhase 背灯", () => {
  211. const model = buildWorkflowTimeline(
  212. graphOf(PIPELINE),
  213. runOf([
  214. ["done", "done", "running", "queued"],
  215. ["done", "running", "queued"],
  216. ["running"],
  217. [],
  218. [],
  219. ]),
  220. );
  221. expect(lamps(model)).toEqual(["running", "running", "running", "pending", "pending"]);
  222. // 两端都在跑的流轨正在流;第三站往后什么都还没过去。
  223. expect(streamInks(model)).toEqual(["march", "march", "faint", "faint"]);
  224. });
  225. it("t≈40s:上游跑完的流轨是 strong;全在排队的站是 pending,它的入口流轨也 strong", () => {
  226. const model = buildWorkflowTimeline(
  227. graphOf(PIPELINE),
  228. runOf([
  229. ["done", "done", "done"],
  230. ["done", "running", "queued"],
  231. ["done", "running"],
  232. ["running"],
  233. ["queued"],
  234. ]),
  235. );
  236. expect(lamps(model)).toEqual(["done", "running", "running", "running", "pending"]);
  237. expect(streamInks(model)).toEqual(["strong", "march", "march", "strong"]);
  238. });
  239. it("自己的节点都结算了、上游还开着的站仍是 running:还会有活进来", () => {
  240. const model = buildWorkflowTimeline(
  241. graphOf(PIPELINE),
  242. runOf([["done", "running"], ["done"], ["done"], [], []]),
  243. );
  244. expect(lamps(model)).toEqual(["running", "running", "running", "pending", "pending"]);
  245. });
  246. it("停止的 run:从没收到活的站是 pending,不是 done 也不是 failed", () => {
  247. const model = buildWorkflowTimeline(
  248. graphOf(PIPELINE),
  249. runOf([["done", "done"], ["done", "done"], ["failed", "failed"], [], []], "stopped"),
  250. );
  251. expect(lamps(model)).toEqual(["done", "done", "failed", "pending", "pending"]);
  252. expect(streamInks(model)).toEqual(["strong", "strong", "faint", "faint"]);
  253. });
  254. it("完成的 run:进入过却一件活都没收到的站是 done", () => {
  255. const model = buildWorkflowTimeline(
  256. graphOf(PIPELINE),
  257. runOf([["done"], ["done"], ["done"], ["done"], []], "completed"),
  258. );
  259. expect(lamps(model)).toEqual(["done", "done", "done", "done", "done"]);
  260. });
  261. it("流轨与流弧都不行进:它们的墨说的是有没有东西在过,不是控制从哪来", () => {
  262. const model = buildWorkflowTimeline(
  263. graphOf(PIPELINE),
  264. runOf([["done"], ["running"], [], [], []]),
  265. );
  266. expect(model.rails.every((rail) => rail.kind === "stream")).toBe(true);
  267. expect(model.rails[0]!.ink).toBe("strong");
  268. expect(model.stations.every((station) => !station.onLoop)).toBe(true);
  269. });
  270. });
  271. describe("buildWorkflowTimeline · 并行但没有流的站", () => {
  272. it("两个互不相干的 future:没开始的那条是 pending,不是 done", () => {
  273. // A ∥ B → C。旧规则下 A 进入过、不是 currentPhase、没有节点 → done(绿灯)。
  274. const spec: Spec = { alongside: { 1: [0] }, edges: [[1, 2]], names: ["A", "B", "C"] };
  275. const state = {
  276. ...runOf([[], ["running"], []]),
  277. phases: [
  278. { name: "A", rounds: 1 },
  279. { name: "B", rounds: 1 },
  280. ],
  281. currentPhase: "B",
  282. nodes: [{ siteId: "ask#2", ordinal: 1, phase: "executing" } as Node],
  283. };
  284. const model = buildWorkflowTimeline(graphOf(spec), state);
  285. expect(lamps(model)).toEqual(["pending", "running", "pending"]);
  286. expect(model.bands).toHaveLength(1);
  287. });
  288. it("只有标记、没有成员 step 的阶段照旧按进入记录点灯", () => {
  289. const spec: Spec = { ...PIPELINE, markerOnly: [3] };
  290. const model = buildWorkflowTimeline(
  291. graphOf(spec),
  292. runOf([["done"], ["done"], ["running"], [], []]),
  293. );
  294. expect(model.stations[3]!.status).toBe("done");
  295. });
  296. });
  297. function renderCard(spec: Spec, state?: WorkflowRunState) {
  298. const model = buildWorkflowTimeline(graphOf(spec), state);
  299. return render(
  300. createElement(
  301. ZCodeIntlProvider,
  302. { initialLocale: "en-US" },
  303. createElement(WorkflowTimeline, { model }),
  304. ),
  305. );
  306. }
  307. describe("WorkflowTimeline · 流轨", () => {
  308. it("流水线画在站头行上:轨道段带三枚 chevron,墨与模型一致", () => {
  309. const view = renderCard(PIPELINE, runOf([["done", "running"], ["running"], [], [], []]));
  310. expect(view.queryAllByTestId("workflow-timeline-leader")).toHaveLength(0);
  311. const rails = view.getAllByTestId("workflow-timeline-rail");
  312. expect(rails.map((rail) => rail.getAttribute("data-rail-kind"))).toEqual([
  313. "stream",
  314. "stream",
  315. "stream",
  316. "stream",
  317. ]);
  318. expect(rails[0]!.className).toContain("wf-rail-stream");
  319. const chevrons = rails.map((rail) => within(rail).getByTestId("workflow-stream-chevrons"));
  320. expect(chevrons.map((group) => group.getAttribute("data-stream-ink"))).toEqual([
  321. "march",
  322. "faint",
  323. "faint",
  324. "faint",
  325. ]);
  326. expect(chevrons[0]!.querySelectorAll("path")).toHaveLength(3);
  327. });
  328. it("带内同轨道相邻的流也画 chevron:SVG 里轨道段断开一截,chevron 站在缺口里", () => {
  329. const view = renderCard({
  330. alongside: { 1: [0], 2: [0, 1], 3: [0, 1, 2] },
  331. names: ["Crawl", "Clean", "Index", "Monitor"],
  332. streams: [
  333. [0, 1],
  334. [1, 2],
  335. ],
  336. });
  337. const stream = view
  338. .getAllByTestId("workflow-timeline-rail")
  339. .filter((rail) => rail.getAttribute("data-rail-kind") === "stream");
  340. expect(stream.map((rail) => rail.getAttribute("data-rail-from"))).toEqual(["0", "1"]);
  341. for (const rail of stream) {
  342. expect(within(rail as HTMLElement).getByTestId("workflow-stream-chevrons")).toBeDefined();
  343. // 一条路径两笔:M…H… M…H…
  344. expect(rail.querySelector("path")!.getAttribute("d")!.match(/M/g)).toHaveLength(2);
  345. }
  346. });
  347. });
  348. describe("脊线 · 流轨", () => {
  349. it("解散的带没有接头行;流轨的两截在节边界让出缺口,两枚 chevron 朝下站在里面", () => {
  350. const graph = graphOf(PIPELINE);
  351. const state = runOf([["done", "running"], ["running"], [], [], []]);
  352. const model = buildWorkflowTimeline(graph, state);
  353. const layout = spineLayout(model);
  354. expect(layout.gutter).toBe(0);
  355. expect(layout.sections.every((section) => !section.fork && !section.merge)).toBe(true);
  356. expect(layout.sections[0]!.rails).toEqual([
  357. { ink: "march", position: "below", stream: true, track: 0 },
  358. ]);
  359. const view = render(
  360. createElement(
  361. ZCodeIntlProvider,
  362. { initialLocale: "en-US" },
  363. createElement(WorkflowRunPhaseList, { graph, model, pendingQuestions: [], run: state }),
  364. ),
  365. );
  366. expect(view.queryAllByTestId("workflow-run-spine-joint")).toHaveLength(0);
  367. const groups = view.getAllByTestId("workflow-stream-chevrons");
  368. expect(groups.map((group) => group.getAttribute("data-stream-ink"))).toEqual([
  369. "march",
  370. "faint",
  371. "faint",
  372. "faint",
  373. ]);
  374. expect(groups[0]!.querySelectorAll("path")).toHaveLength(2);
  375. });
  376. });