workflowTimelineModel.test.ts 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. // 时间线模型(docs/dynamic-workflow/presentation.md「The timeline model」):一个纯函数把有界
  2. // display 与 workflowRuns 投影折成站 / 轨道段 / 弧。聊天卡、确认窗与侧栏清单都从这里出发,
  3. // 所以派生规则钉在这里而不是各自的渲染测试里。
  4. import { describe, expect, it } from "vitest";
  5. import type { WorkflowRunState } from "@zcode/shared/zcode-protocol-v4";
  6. import type { WorkflowCausalityGraphData } from "@/components/workflow-graph/types.js";
  7. import {
  8. arcLaneCount,
  9. assignArcLanes,
  10. buildWorkflowTimeline,
  11. } from "@/components/workflow-timeline/timeline-model.js";
  12. import { pillActivity } from "@/components/workflow-timeline/timeline-pill-activity.js";
  13. // plan → draft → verify,verify 回到 plan(循环),plan 直跳 verify(跳段)。
  14. const STEPS: WorkflowCausalityGraphData["steps"] = [
  15. { id: "ask#1", kind: "ask", label: "plan", lane: "actor#1", phase: "phase#a" },
  16. {
  17. id: "world-read#1",
  18. kind: "world-read",
  19. label: "read files",
  20. lane: "workspace",
  21. phase: "phase#a",
  22. },
  23. { id: "ask#2", kind: "ask", label: "draft", lane: "actor#2", phase: "phase#b" },
  24. { id: "ask#3", kind: "ask", label: "verify", lane: "actor#3", phase: "phase#c" },
  25. { id: "ask#4", kind: "ask", label: "polish", lane: "actor#2", phase: "phase#c" },
  26. ];
  27. function participantsOf(steps: readonly WorkflowCausalityGraphData["steps"][number][]) {
  28. const byId = new Map<string, { id: string; phase: string; lane: string; steps: string[] }>();
  29. for (const step of steps) {
  30. const phase = step.phase ?? "unphased";
  31. const id = `${phase}:${step.lane}`;
  32. const existing = byId.get(id);
  33. if (existing) existing.steps.push(step.id);
  34. else byId.set(id, { id, lane: step.lane, phase, steps: [step.id] });
  35. }
  36. return [...byId.values()];
  37. }
  38. const GRAPH: WorkflowCausalityGraphData = {
  39. steps: STEPS,
  40. lanes: [
  41. { id: "actor#1", name: "planner" },
  42. { id: "actor#2", name: "writer" },
  43. { id: "actor#3" },
  44. { id: "workspace" },
  45. ],
  46. participants: participantsOf(STEPS),
  47. handoffs: [],
  48. phases: [
  49. { id: "phase#a", name: "plan" },
  50. { id: "phase#b", name: "draft" },
  51. { id: "phase#c", name: "verify" },
  52. ],
  53. // 分析器把再入的 phase("plan") 标成前向边(不带 back):画面上它仍然向左。
  54. phaseEdges: [
  55. { from: "phase#a", to: "phase#b" },
  56. { from: "phase#b", to: "phase#c" },
  57. { from: "phase#c", to: "phase#a" },
  58. { from: "phase#a", to: "phase#c" },
  59. ],
  60. exits: ["phase#c"],
  61. };
  62. function run(overrides: Partial<WorkflowRunState> = {}): WorkflowRunState {
  63. return {
  64. runId: "dwfrun-1",
  65. toolCallId: "tool-wf-1",
  66. status: "running",
  67. usage: { spentTokens: 0, nodesUsed: 0 },
  68. actors: [],
  69. nodes: [],
  70. lastEventSequence: 0,
  71. ...overrides,
  72. };
  73. }
  74. type Node = WorkflowRunState["nodes"][number];
  75. function settled(siteId: string, ordinal = 1, extra: Partial<Node> = {}): Node {
  76. return { siteId, ordinal, phase: "settled", outcome: "ok", ...extra } as Node;
  77. }
  78. function executing(siteId: string, ordinal = 1, extra: Partial<Node> = {}): Node {
  79. return { siteId, ordinal, phase: "executing", ...extra } as Node;
  80. }
  81. describe("buildWorkflowTimeline · 站与边", () => {
  82. it("站按声明序(phases[] 顺序)一阶段一站,不再分秩", () => {
  83. const model = buildWorkflowTimeline(GRAPH, undefined);
  84. expect(model.stations.map((station) => station.id)).toEqual(["phase#a", "phase#b", "phase#c"]);
  85. expect(model.stations.map((station) => station.naming.name)).toEqual([
  86. "plan",
  87. "draft",
  88. "verify",
  89. ]);
  90. });
  91. it("无标记脚本合成一个隐式站,所有参与者都在它下面", () => {
  92. const flat: WorkflowCausalityGraphData = {
  93. steps: STEPS.map(({ phase: _phase, ...step }) => step),
  94. lanes: GRAPH.lanes,
  95. participants: participantsOf(STEPS.map(({ phase: _phase, ...step }) => step)),
  96. handoffs: [],
  97. };
  98. const model = buildWorkflowTimeline(flat, undefined);
  99. expect(model.stations).toHaveLength(1);
  100. expect(model.stations[0]!.naming.name).toBeUndefined();
  101. expect(model.stations[0]!.pills.map((pill) => pill.lane.id)).toEqual([
  102. "actor#1",
  103. "workspace",
  104. "actor#2",
  105. "actor#3",
  106. ]);
  107. expect(model.rails).toEqual([]);
  108. expect(model.arcs).toEqual([]);
  109. });
  110. it("相邻且有边的两站之间是轨道段;非相邻的边是弧,按方向分回边与跳段", () => {
  111. const model = buildWorkflowTimeline(GRAPH, undefined);
  112. expect(model.rails).toEqual([
  113. { from: 0, ink: "faint", to: 1 },
  114. { from: 1, ink: "faint", to: 2 },
  115. ]);
  116. // 两条弧在 x 上相交,所以分道:按跨度先落的贴近轨道;两条跨度相同时保持载荷序。
  117. expect(model.arcs).toEqual([
  118. { air: 0, from: 2, ink: "faint", lane: 0, to: 0 },
  119. { air: 0, from: 0, ink: "faint", lane: 1, to: 2 },
  120. ]);
  121. });
  122. it("弧的分道是区间着色:互不相干的同高,嵌套的里矮外高,共用端点的也分开", () => {
  123. // 两条各在一头的回边(3→1、5→4):不相交,同一道——高度不同只会让人去找并不存在的理由。
  124. expect(
  125. assignArcLanes([
  126. { from: 3, to: 1 },
  127. { from: 5, to: 4 },
  128. ]).map((arc) => arc.lane),
  129. ).toEqual([0, 0]);
  130. // 嵌套:短的先落在 0 道,长的包在外面只能往上。
  131. expect(
  132. assignArcLanes([
  133. { from: 3, to: 2 },
  134. { from: 5, to: 0 },
  135. ]).map((arc) => arc.lane),
  136. ).toEqual([0, 1]);
  137. // 共用一个端点(3→1 与 5→3):两条弧在站 3 的竖段会连成一线,也分道。
  138. expect(
  139. assignArcLanes([
  140. { from: 3, to: 1 },
  141. { from: 5, to: 3 },
  142. ]).map((arc) => arc.lane),
  143. ).toEqual([0, 1]);
  144. // 三条:两条无关的同在 0 道,第三条跨过两者才上 1 道;道数是 2 不是 3。
  145. const lanes = assignArcLanes([
  146. { from: 1, to: 0 },
  147. { from: 4, to: 3 },
  148. { from: 4, to: 0 },
  149. ]);
  150. expect(lanes.map((arc) => arc.lane)).toEqual([0, 0, 1]);
  151. expect(arcLaneCount(lanes)).toBe(2);
  152. expect(arcLaneCount([])).toBe(0);
  153. });
  154. it("只有回边(向左的弧)的两端才是 onLoop:跳段两端不显示轮次", () => {
  155. const skipOnly: WorkflowCausalityGraphData = {
  156. ...GRAPH,
  157. phaseEdges: [
  158. { from: "phase#a", to: "phase#b" },
  159. { from: "phase#a", to: "phase#c" },
  160. ],
  161. };
  162. expect(buildWorkflowTimeline(GRAPH, undefined).stations.map((s) => s.onLoop)).toEqual([
  163. true,
  164. false,
  165. true,
  166. ]);
  167. expect(buildWorkflowTimeline(skipOnly, undefined).stations.map((s) => s.onLoop)).toEqual([
  168. false,
  169. false,
  170. false,
  171. ]);
  172. });
  173. it("没有相邻边的两站之间没有轨道段(画面上留空,不是淡墨)", () => {
  174. const gapped: WorkflowCausalityGraphData = {
  175. ...GRAPH,
  176. phaseEdges: [{ from: "phase#a", to: "phase#c" }],
  177. };
  178. expect(buildWorkflowTimeline(gapped, undefined).rails).toEqual([]);
  179. });
  180. it("自环与指向未列出阶段的边在这一粒度上被忽略;重复边只算一次", () => {
  181. const noisy: WorkflowCausalityGraphData = {
  182. ...GRAPH,
  183. phaseEdges: [
  184. { from: "phase#a", to: "phase#a" },
  185. { from: "phase#a", to: "phase#zz" },
  186. { from: "phase#a", to: "phase#b" },
  187. { from: "phase#a", to: "phase#b", back: true },
  188. ],
  189. };
  190. const model = buildWorkflowTimeline(noisy, undefined);
  191. expect(model.rails).toEqual([{ from: 0, ink: "faint", to: 1 }]);
  192. expect(model.arcs).toEqual([]);
  193. });
  194. it("无 run:站与药丸状态 undefined、墨迹全淡、没有运行站、live=false", () => {
  195. const model = buildWorkflowTimeline(GRAPH, undefined);
  196. expect(model.live).toBe(false);
  197. expect(model.runningIndex).toBeUndefined();
  198. for (const station of model.stations) {
  199. expect(station.status).toBeUndefined();
  200. expect(station.visited).toBe(false);
  201. expect(station.rounds).toBe(0);
  202. expect(station.fraction).toBeUndefined();
  203. for (const pill of station.pills) expect(pill.status).toBeUndefined();
  204. // 没有 run 就没有可开的工作区:抓手与槽位一样缺席。
  205. for (const pill of station.pills) expect(pill.workspace).toBeUndefined();
  206. }
  207. });
  208. });
  209. describe("buildWorkflowTimeline · 投影叠加", () => {
  210. it("visited / rounds / fraction 从落在该站站点上的节点派生", () => {
  211. const model = buildWorkflowTimeline(
  212. GRAPH,
  213. run({
  214. nodes: [settled("ask#1"), settled("world-read#1"), settled("ask#1", 2), executing("ask#2")],
  215. }),
  216. );
  217. const [plan, draft, verify] = model.stations;
  218. expect(plan).toMatchObject({ visited: true, rounds: 2, fraction: { observed: 3, settled: 3 } });
  219. expect(draft).toMatchObject({
  220. visited: true,
  221. rounds: 1,
  222. fraction: { observed: 1, settled: 0 },
  223. status: "running",
  224. });
  225. expect(verify).toMatchObject({ visited: false, rounds: 0 });
  226. expect(verify!.fraction).toBeUndefined();
  227. expect(model.live).toBe(true);
  228. });
  229. it("may-set 拷贝按 source 关联:拷贝站上报的是站点 id,漏掉 source 会让它永远「未到」", () => {
  230. const copied: WorkflowCausalityGraphData = {
  231. ...GRAPH,
  232. steps: [
  233. ...STEPS,
  234. {
  235. id: "ask#2~copy",
  236. kind: "ask",
  237. label: "draft",
  238. lane: "actor#3",
  239. phase: "phase#b",
  240. source: "ask#2",
  241. },
  242. ],
  243. participants: participantsOf([
  244. ...STEPS,
  245. {
  246. id: "ask#2~copy",
  247. kind: "ask",
  248. label: "draft",
  249. lane: "actor#3",
  250. phase: "phase#b",
  251. source: "ask#2",
  252. },
  253. ]),
  254. };
  255. const model = buildWorkflowTimeline(copied, run({ nodes: [settled("ask#2")] }));
  256. expect(model.stations[1]).toMatchObject({ visited: true, rounds: 1 });
  257. });
  258. it("运行站取最右边的 running 站", () => {
  259. const model = buildWorkflowTimeline(
  260. GRAPH,
  261. run({ nodes: [executing("ask#1"), executing("ask#3")] }),
  262. );
  263. expect(model.runningIndex).toBe(2);
  264. });
  265. it("轨道段:两端都到过才是浓墨", () => {
  266. const model = buildWorkflowTimeline(
  267. GRAPH,
  268. run({ nodes: [settled("ask#1"), settled("ask#2")] }),
  269. );
  270. expect(model.rails.map((rail) => rail.ink)).toEqual(["strong", "faint"]);
  271. });
  272. it("回边:源到过且目标 rounds ≥ 2 才是浓墨——走过一遍还没回头时仍是淡墨", () => {
  273. const once = buildWorkflowTimeline(
  274. GRAPH,
  275. run({ nodes: [settled("ask#1"), settled("ask#2"), settled("ask#3")] }),
  276. );
  277. expect(once.arcs.find((arc) => arc.to === 0)?.ink).toBe("faint");
  278. const twice = buildWorkflowTimeline(
  279. GRAPH,
  280. run({ nodes: [settled("ask#1"), settled("ask#2"), settled("ask#3"), settled("ask#1", 2)] }),
  281. );
  282. expect(twice.arcs.find((arc) => arc.to === 0)?.ink).toBe("strong");
  283. });
  284. it("跳段:两端都到过才是浓墨", () => {
  285. const model = buildWorkflowTimeline(
  286. GRAPH,
  287. run({ nodes: [settled("ask#1"), settled("ask#3")] }),
  288. );
  289. expect(model.arcs.find((arc) => arc.from === 0 && arc.to === 2)?.ink).toBe("strong");
  290. expect(model.arcs.find((arc) => arc.to === 0)?.ink).toBe("faint");
  291. });
  292. it("行进边:进入运行站的相邻轨道段", () => {
  293. const model = buildWorkflowTimeline(
  294. GRAPH,
  295. run({ nodes: [settled("ask#1"), executing("ask#2")] }),
  296. );
  297. expect(model.rails.map((rail) => rail.ink)).toEqual(["march", "faint"]);
  298. expect(model.arcs.every((arc) => arc.ink !== "march")).toBe(true);
  299. });
  300. it("行进边:再入的回边优先于轨道段——第二轮的 plan 正在跑时,脉冲走回边而不是凭空从左边来", () => {
  301. const model = buildWorkflowTimeline(
  302. GRAPH,
  303. run({
  304. nodes: [settled("ask#1"), settled("ask#2"), settled("ask#3"), executing("ask#1", 2)],
  305. }),
  306. );
  307. expect(model.runningIndex).toBe(0);
  308. expect(model.arcs.find((arc) => arc.to === 0)?.ink).toBe("march");
  309. expect(model.rails.every((rail) => rail.ink !== "march")).toBe(true);
  310. });
  311. it("行进边:没有轨道段时落在任一到过源的弧上(跳段直达)", () => {
  312. const gapped: WorkflowCausalityGraphData = {
  313. ...GRAPH,
  314. phaseEdges: [
  315. { from: "phase#a", to: "phase#b" },
  316. { from: "phase#a", to: "phase#c" },
  317. ],
  318. };
  319. const model = buildWorkflowTimeline(
  320. gapped,
  321. run({ nodes: [settled("ask#1"), executing("ask#3")] }),
  322. );
  323. expect(model.arcs.find((arc) => arc.from === 0 && arc.to === 2)?.ink).toBe("march");
  324. });
  325. it("第一站正在跑而没有任何进入它的边时没有行进边", () => {
  326. const model = buildWorkflowTimeline(GRAPH, run({ nodes: [executing("ask#1")] }));
  327. expect(model.rails.every((rail) => rail.ink === "faint")).toBe(true);
  328. expect(model.arcs.every((arc) => arc.ink === "faint")).toBe(true);
  329. });
  330. });
  331. describe("buildWorkflowTimeline · 药丸", () => {
  332. it("药丸是该站的参与者:车道引用、运行时名、实例与会话、折叠后的状态", () => {
  333. const model = buildWorkflowTimeline(
  334. GRAPH,
  335. run({
  336. actors: [
  337. {
  338. siteId: "actor#1",
  339. ordinal: 1,
  340. name: "Ada the planner",
  341. sessionId: "s-1",
  342. status: "running",
  343. },
  344. { siteId: "actor#2", ordinal: 1, status: "waiting" },
  345. ],
  346. nodes: [executing("ask#1", 1, { actorSiteId: "actor#1", actorOrdinal: 1 })],
  347. }),
  348. );
  349. const [plan] = model.stations;
  350. const planner = plan!.pills.find((pill) => pill.lane.id === "actor#1")!;
  351. expect(planner).toMatchObject({
  352. laneClass: "agent",
  353. runtimeName: "Ada the planner",
  354. status: "running",
  355. instance: { siteId: "actor#1", ordinal: 1, sessionId: "s-1" },
  356. slot: { siteId: "actor#1", ordinal: 1 },
  357. stepIds: ["ask#1"],
  358. });
  359. // 合成车道没有实例,也没有槽位。
  360. const workspace = plan!.pills.find((pill) => pill.lane.id === "workspace")!;
  361. expect(workspace.laneClass).toBe("workspace");
  362. expect(workspace.instance).toBeUndefined();
  363. expect(workspace.slot).toBeUndefined();
  364. // 但它有自己的抓手(docs/dynamic-workflow/transcript-and-notifications.md):活的 run 里点它开工作区
  365. // transcript、落到这一站。
  366. expect(workspace.workspace).toEqual({ phaseId: "phase#a" });
  367. expect(planner.workspace).toBeUndefined();
  368. // 会话还没落库的实例:instance 在,sessionId 缺席;槽位仍是实例的序号。
  369. const writer = model.stations[1]!.pills[0]!;
  370. expect(writer.instance).toEqual({ siteId: "actor#2", ordinal: 1 });
  371. expect(writer.slot).toEqual({ siteId: "actor#2", ordinal: 1 });
  372. expect(writer.runtimeName).toBeUndefined();
  373. expect(writer.status).toBe("pending");
  374. // 还没出现的子代理(actor#3 没有实例):槽位是它将来的序号 1。
  375. const verifier = model.stations[2]!.pills.find((pill) => pill.lane.id === "actor#3")!;
  376. expect(verifier.instance).toBeUndefined();
  377. expect(verifier.slot).toEqual({ siteId: "actor#3", ordinal: 1 });
  378. });
  379. it("槽位(追记「点击语法修订」):无 run 没有槽位;成员卡的期望序号是 member.index + 1", () => {
  380. const cold = buildWorkflowTimeline(GRAPH, undefined);
  381. expect(
  382. cold.stations.flatMap((station) => station.pills).every((pill) => pill.slot === undefined),
  383. ).toBe(true);
  384. // 字面量基数展开的成员卡:第 i 个成员对应该车道上的第 i 个实例,出现之前就知道它的序号。
  385. const members: WorkflowCausalityGraphData = {
  386. ...GRAPH,
  387. participants: GRAPH.participants.flatMap((participant) =>
  388. participant.lane === "actor#2" && participant.phase === "phase#b"
  389. ? [0, 1, 2].map((index) => ({
  390. ...participant,
  391. id: `${participant.id}#${index}`,
  392. member: { index, of: 3 },
  393. }))
  394. : [participant],
  395. ),
  396. };
  397. const model = buildWorkflowTimeline(
  398. members,
  399. run({ actors: [{ siteId: "actor#2", ordinal: 1, sessionId: "s-2", status: "waiting" }] }),
  400. );
  401. const draft = model.stations[1]!;
  402. expect(draft.pills.map((pill) => pill.slot)).toEqual([
  403. { siteId: "actor#2", ordinal: 1 },
  404. { siteId: "actor#2", ordinal: 2 },
  405. { siteId: "actor#2", ordinal: 3 },
  406. ]);
  407. // 第一个成员已绑定实例(带会话),其余两个还没出现。
  408. expect(draft.pills[0]!.instance).toEqual({ siteId: "actor#2", ordinal: 1, sessionId: "s-2" });
  409. expect(draft.pills[1]!.instance).toBeUndefined();
  410. });
  411. it("同一车道在两个站各有一枚药丸:verify 站的 writer 与 draft 站的 writer 不是同一枚", () => {
  412. const model = buildWorkflowTimeline(GRAPH, undefined);
  413. const keys = model.stations.flatMap((station) => station.pills.map((pill) => pill.key));
  414. expect(new Set(keys).size).toBe(keys.length);
  415. expect(model.stations[2]!.pills.map((pill) => pill.lane.id)).toEqual(["actor#3", "actor#2"]);
  416. });
  417. });
  418. describe("pillActivity", () => {
  419. const model = (state: WorkflowRunState | undefined) => buildWorkflowTimeline(GRAPH, state);
  420. it("正在跑的 step 的 label 优先,其次最后一个已结算的,再次第一个", () => {
  421. const verifyStation = (state: WorkflowRunState | undefined) =>
  422. model(state).stations[2]!.pills.find((pill) => pill.lane.id === "actor#2")!;
  423. const graph = GRAPH;
  424. expect(pillActivity(graph, undefined, verifyStation(undefined)).label).toBe("polish");
  425. const running = run({ nodes: [executing("ask#4")] });
  426. expect(pillActivity(graph, running, verifyStation(running)).label).toBe("polish");
  427. const planStation = (state: WorkflowRunState) =>
  428. model(state).stations[0]!.pills.find((pill) => pill.lane.id === "actor#1")!;
  429. const done = run({ nodes: [settled("ask#1")] });
  430. expect(pillActivity(graph, done, planStation(done)).label).toBe("plan");
  431. });
  432. it("asks / reads 按 step 种类计数", () => {
  433. const state = run({ nodes: [settled("ask#1"), settled("world-read#1")] });
  434. const [plan] = model(state).stations;
  435. const planner = plan!.pills.find((pill) => pill.lane.id === "actor#1")!;
  436. const workspace = plan!.pills.find((pill) => pill.lane.id === "workspace")!;
  437. expect(pillActivity(GRAPH, state, planner)).toEqual({ asks: 1, label: "plan", reads: 0 });
  438. expect(pillActivity(GRAPH, state, workspace)).toEqual({
  439. asks: 0,
  440. label: "read files",
  441. reads: 1,
  442. });
  443. });
  444. });
  445. // 进入记录(docs/dynamic-workflow/presentation.md):一站按名字关联
  446. // run.phases,currentPhase 是控制流所在的站。零成员站只有它能点灯。
  447. describe("buildWorkflowTimeline · 进入记录", () => {
  448. const EMPTY_TAIL: WorkflowCausalityGraphData = {
  449. ...GRAPH,
  450. phases: [...GRAPH.phases!, { id: "phase#d", name: "wrap up" }],
  451. phaseEdges: [...GRAPH.phaseEdges!, { from: "phase#c", to: "phase#d" }],
  452. exits: ["phase#d"],
  453. };
  454. const byName = (model: ReturnType<typeof buildWorkflowTimeline>, name: string) =>
  455. model.stations.find((station) => station.naming.name === name)!;
  456. it("零成员站:进入即 running,下一站进入后 done,run 完成后 done,失败给 failed", () => {
  457. const entered = buildWorkflowTimeline(
  458. EMPTY_TAIL,
  459. run({
  460. nodes: [settled("ask#1"), settled("ask#2"), settled("ask#3")],
  461. phases: [
  462. { name: "plan", rounds: 1 },
  463. { name: "draft", rounds: 1 },
  464. { name: "verify", rounds: 1 },
  465. { name: "wrap up", rounds: 1 },
  466. ],
  467. currentPhase: "wrap up",
  468. }),
  469. );
  470. expect(byName(entered, "wrap up").status).toBe("running");
  471. expect(byName(entered, "wrap up").visited).toBe(true);
  472. expect(entered.runningIndex).toBe(3);
  473. // 行进边落在进入这一站的轨道段上。
  474. expect(entered.rails.find((rail) => rail.to === 3)?.ink).toBe("march");
  475. const completed = buildWorkflowTimeline(
  476. EMPTY_TAIL,
  477. run({
  478. status: "completed",
  479. nodes: [settled("ask#1"), settled("ask#2"), settled("ask#3")],
  480. phases: [
  481. { name: "plan", rounds: 1 },
  482. { name: "draft", rounds: 1 },
  483. { name: "verify", rounds: 1 },
  484. { name: "wrap up", rounds: 1 },
  485. ],
  486. currentPhase: "wrap up",
  487. }),
  488. );
  489. expect(byName(completed, "wrap up").status).toBe("done");
  490. const failed = buildWorkflowTimeline(
  491. EMPTY_TAIL,
  492. run({
  493. status: "failed",
  494. phases: [{ name: "plan", rounds: 1 }],
  495. currentPhase: "plan",
  496. }),
  497. );
  498. // plan 有成员但一个节点都没派发:失败发生在它的脚本逻辑里,灯给 failed。
  499. expect(byName(failed, "plan").status).toBe("failed");
  500. expect(byName(failed, "wrap up").status).toBe("pending");
  501. // 一个零成员的头站:控制流已经越过它(后面的站是 current),它就是 done。
  502. const passed = buildWorkflowTimeline(
  503. {
  504. ...EMPTY_TAIL,
  505. phases: [{ id: "phase#0", name: "setup" }, ...EMPTY_TAIL.phases!],
  506. phaseEdges: [{ from: "phase#0", to: "phase#a" }, ...EMPTY_TAIL.phaseEdges!],
  507. },
  508. run({
  509. nodes: [executing("ask#1")],
  510. phases: [
  511. { name: "setup", rounds: 1 },
  512. { name: "plan", rounds: 1 },
  513. ],
  514. currentPhase: "plan",
  515. }),
  516. );
  517. expect(byName(passed, "setup").status).toBe("done");
  518. expect(byName(passed, "plan").status).toBe("running");
  519. expect(passed.rails[0]?.ink).toBe("march");
  520. });
  521. it("有成员的站在第一个 ask 派发之前就 running;节点一 running / failed 就按节点说", () => {
  522. const beforeDispatch = buildWorkflowTimeline(
  523. GRAPH,
  524. run({ phases: [{ name: "plan", rounds: 1 }], currentPhase: "plan" }),
  525. );
  526. expect(byName(beforeDispatch, "plan").status).toBe("running");
  527. expect(byName(beforeDispatch, "plan").visited).toBe(true);
  528. expect(byName(beforeDispatch, "draft").status).toBe("pending");
  529. // 当前站的节点都结算了、下一个标记还没到:控制流仍在这一站。
  530. const between = buildWorkflowTimeline(
  531. GRAPH,
  532. run({
  533. nodes: [settled("ask#1"), settled("world-read#1")],
  534. phases: [{ name: "plan", rounds: 1 }],
  535. currentPhase: "plan",
  536. }),
  537. );
  538. expect(byName(between, "plan").status).toBe("running");
  539. const failedNode = buildWorkflowTimeline(
  540. GRAPH,
  541. run({
  542. nodes: [settled("ask#1", 1, { outcome: "failed" })],
  543. phases: [{ name: "plan", rounds: 1 }],
  544. currentPhase: "plan",
  545. }),
  546. );
  547. expect(byName(failedNode, "plan").status).toBe("failed");
  548. });
  549. it("rounds 取进入次数与节点 ordinal 之大;display 名被截断时按前缀关联", () => {
  550. const model = buildWorkflowTimeline(
  551. GRAPH,
  552. run({
  553. nodes: [settled("ask#1", 1), settled("ask#1", 2)],
  554. phases: [
  555. { name: "plan", rounds: 3 },
  556. { name: "draft", rounds: 1 },
  557. ],
  558. currentPhase: "plan",
  559. }),
  560. );
  561. expect(byName(model, "plan").rounds).toBe(3);
  562. expect(byName(model, "draft").rounds).toBe(1);
  563. expect(byName(model, "draft").visited).toBe(true);
  564. const long = "x".repeat(128);
  565. const truncated = buildWorkflowTimeline(
  566. { ...GRAPH, phases: [{ id: "phase#a", name: long }, ...GRAPH.phases!.slice(1)] },
  567. run({ phases: [{ name: `${long}yyy`, rounds: 2 }], currentPhase: `${long}yyy` }),
  568. );
  569. expect(byName(truncated, long).rounds).toBe(2);
  570. expect(byName(truncated, long).status).toBe("running");
  571. // 没被截断的短名不做前缀匹配:「plan」不认「plan the fix」。
  572. const short = buildWorkflowTimeline(
  573. GRAPH,
  574. run({ phases: [{ name: "plan the fix", rounds: 1 }], currentPhase: "plan the fix" }),
  575. );
  576. expect(byName(short, "plan").visited).toBe(false);
  577. expect(byName(short, "plan").status).toBe("pending");
  578. });
  579. it("无标记脚本(隐式站)不读进入记录:仍按节点点灯", () => {
  580. const model = buildWorkflowTimeline(
  581. { ...GRAPH, phases: undefined, phaseEdges: undefined, exits: undefined },
  582. run({ phases: [{ name: "plan", rounds: 1 }], currentPhase: "plan" }),
  583. );
  584. expect(model.stations).toHaveLength(1);
  585. expect(model.stations[0]?.status).toBe("pending");
  586. });
  587. });
  588. describe("buildWorkflowTimeline · 分支站(追记「缺席不是状态」)", () => {
  589. // 一个参与者两个站点:`round === 1 ? poet.ask(…) : poet.ask(…)` 每轮只走一支。
  590. const BRANCH_STEPS: WorkflowCausalityGraphData["steps"] = [
  591. { id: "ask#1", kind: "ask", label: "poet", lane: "actor#1", phase: "phase#a" },
  592. { id: "ask#2", kind: "ask", label: "poet", lane: "actor#1", phase: "phase#a" },
  593. { id: "ask#3", kind: "ask", label: "critic", lane: "actor#2", phase: "phase#b" },
  594. ];
  595. const BRANCH: WorkflowCausalityGraphData = {
  596. steps: BRANCH_STEPS,
  597. lanes: [
  598. { id: "actor#1", name: "poet" },
  599. { id: "actor#2", name: "critic" },
  600. ],
  601. participants: participantsOf(BRANCH_STEPS),
  602. handoffs: [],
  603. phases: [
  604. { id: "phase#a", name: "draft" },
  605. { id: "phase#b", name: "review" },
  606. ],
  607. phaseEdges: [
  608. { from: "phase#a", to: "phase#b" },
  609. { from: "phase#b", to: "phase#a" },
  610. ],
  611. exits: ["phase#b"],
  612. };
  613. const actors: WorkflowRunState["actors"] = [
  614. { siteId: "actor#1", ordinal: 1, name: "poet", sessionId: "s-1", status: "waiting" },
  615. { siteId: "actor#2", ordinal: 1, name: "critic", sessionId: "s-2", status: "running" },
  616. ];
  617. const draftOf = (model: ReturnType<typeof buildWorkflowTimeline>) => model.stations[0]!;
  618. it("只观察到一支且已结算、控制流在下一站:站 done、药丸 done——没走的那支不把它们拖成 pending", () => {
  619. const model = buildWorkflowTimeline(
  620. BRANCH,
  621. run({
  622. actors,
  623. nodes: [
  624. settled("ask#1", 1, { actorSiteId: "actor#1", actorOrdinal: 1 }),
  625. executing("ask#3", 1, { actorSiteId: "actor#2", actorOrdinal: 1 }),
  626. ],
  627. phases: [
  628. { name: "draft", rounds: 1 },
  629. { name: "review", rounds: 1 },
  630. ],
  631. currentPhase: "review",
  632. }),
  633. );
  634. expect(draftOf(model).status).toBe("done");
  635. expect(draftOf(model).pills[0]!.status).toBe("done");
  636. expect(model.stations[1]!.status).toBe("running");
  637. expect(model.runningIndex).toBe(1);
  638. });
  639. it("评审第一轮就通过、revision 那支永远不跑:run 完成后站与药丸仍是 done", () => {
  640. const model = buildWorkflowTimeline(
  641. BRANCH,
  642. run({
  643. status: "completed",
  644. actors,
  645. nodes: [
  646. settled("ask#1", 1, { actorSiteId: "actor#1", actorOrdinal: 1 }),
  647. settled("ask#3", 1, { actorSiteId: "actor#2", actorOrdinal: 1 }),
  648. ],
  649. phases: [
  650. { name: "draft", rounds: 1 },
  651. { name: "review", rounds: 1 },
  652. ],
  653. currentPhase: "review",
  654. }),
  655. );
  656. expect(draftOf(model).status).toBe("done");
  657. expect(draftOf(model).pills[0]!.status).toBe("done");
  658. expect(model.stations[1]!.status).toBe("done");
  659. });
  660. it("观察到的那支正在跑:站与药丸 running;另一支的缺席不改变任何东西", () => {
  661. const model = buildWorkflowTimeline(
  662. BRANCH,
  663. run({
  664. actors,
  665. nodes: [executing("ask#2", 1, { actorSiteId: "actor#1", actorOrdinal: 1 })],
  666. phases: [{ name: "draft", rounds: 2 }],
  667. currentPhase: "draft",
  668. }),
  669. );
  670. expect(draftOf(model).status).toBe("running");
  671. expect(draftOf(model).pills[0]!.status).toBe("running");
  672. });
  673. it("一支失败:站与药丸 failed", () => {
  674. const model = buildWorkflowTimeline(
  675. BRANCH,
  676. run({
  677. status: "failed",
  678. actors,
  679. nodes: [
  680. settled("ask#1", 1, { actorSiteId: "actor#1", actorOrdinal: 1, outcome: "failed" }),
  681. ],
  682. phases: [{ name: "draft", rounds: 1 }],
  683. currentPhase: "draft",
  684. }),
  685. );
  686. expect(draftOf(model).status).toBe("failed");
  687. expect(draftOf(model).pills[0]!.status).toBe("failed");
  688. });
  689. it("一个节点都没观察到的站仍按控制流点灯:进入过 → done,没进入过 → pending;药丸 pending", () => {
  690. const model = buildWorkflowTimeline(
  691. BRANCH,
  692. run({
  693. actors,
  694. nodes: [executing("ask#3", 1, { actorSiteId: "actor#2", actorOrdinal: 1 })],
  695. phases: [
  696. { name: "draft", rounds: 1 },
  697. { name: "review", rounds: 1 },
  698. ],
  699. currentPhase: "review",
  700. }),
  701. );
  702. expect(draftOf(model).status).toBe("done");
  703. expect(draftOf(model).pills[0]!.status).toBe("pending");
  704. const untouched = buildWorkflowTimeline(BRANCH, run({ actors, nodes: [] }));
  705. expect(draftOf(untouched).status).toBe("pending");
  706. expect(draftOf(untouched).pills[0]!.status).toBe("pending");
  707. });
  708. });
  709. describe("buildWorkflowTimeline · asking", () => {
  710. it("run.pendingQuestions 里有该实例的问题时药丸带 asking(名册钉位规则读它)", () => {
  711. const model = buildWorkflowTimeline(
  712. GRAPH,
  713. run({
  714. actors: [
  715. { siteId: "actor#1", ordinal: 1, name: "Ada", sessionId: "s-1", status: "waiting" },
  716. { siteId: "actor#2", ordinal: 1, name: "Bob", sessionId: "s-2", status: "running" },
  717. ],
  718. nodes: [
  719. {
  720. siteId: "ask#1",
  721. ordinal: 1,
  722. phase: "executing",
  723. actorSiteId: "actor#1",
  724. actorOrdinal: 1,
  725. },
  726. {
  727. siteId: "ask#2",
  728. ordinal: 1,
  729. phase: "executing",
  730. actorSiteId: "actor#2",
  731. actorOrdinal: 1,
  732. },
  733. ] as WorkflowRunState["nodes"],
  734. pendingQuestions: [
  735. { qid: "q-1", actorSiteId: "actor#1", actorOrdinal: 1, question: "Which branch?" },
  736. // 没有提问者的问题不落在任何药丸上。
  737. { qid: "q-2", question: "orphan" },
  738. ],
  739. }),
  740. );
  741. const [plan, draft] = model.stations;
  742. expect(plan!.pills.find((pill) => pill.lane.id === "actor#1")!.asking).toBe(true);
  743. expect(draft!.pills.find((pill) => pill.lane.id === "actor#2")!.asking).toBeUndefined();
  744. });
  745. });
  746. /**
  747. * 实例的阶段坐标(docs/dynamic-workflow/presentation.md)。本 bug 的形状:
  748. * 一个 `runBatch(p)` 从 5 个阶段各调一次、每次并行派 20 个子代理——一条车道、一个 ask 站点,
  749. * 静态是 5 份拷贝 + 5 张 `many` 卡,运行时是 100 个实例。按车道绑定时每站都认领全部 100 个。
  750. */
  751. describe("buildWorkflowTimeline · 实例按出生阶段划分", () => {
  752. const NAMES = ["调研", "起草", "校对", "复核", "收尾"];
  753. const FAN_OUT: WorkflowCausalityGraphData = {
  754. exits: ["phase#5"],
  755. handoffs: [],
  756. lanes: [{ id: "actor#1", name: "worker" }],
  757. participants: NAMES.map((_, i) => ({
  758. id: `phase#${i + 1}:actor#1`,
  759. lane: "actor#1",
  760. many: true,
  761. phase: `phase#${i + 1}`,
  762. steps: [`ask#1~phase#${i + 1}`],
  763. })),
  764. phaseEdges: NAMES.slice(1).map((_, i) => ({ from: `phase#${i + 1}`, to: `phase#${i + 2}` })),
  765. phases: NAMES.map((name, i) => ({ id: `phase#${i + 1}`, name })),
  766. steps: NAMES.map((_, i) => ({
  767. id: `ask#1~phase#${i + 1}`,
  768. kind: "ask" as const,
  769. label: "review",
  770. lane: "actor#1",
  771. phase: `phase#${i + 1}`,
  772. source: "ask#1",
  773. })),
  774. };
  775. function fanOutRun(stamped: boolean): WorkflowRunState {
  776. const stamp = (name: string) => (stamped ? { phaseName: name } : {});
  777. return run({
  778. actors: NAMES.flatMap((name, i) =>
  779. Array.from({ length: 20 }, (_, k) => ({
  780. ordinal: i * 20 + k + 1,
  781. siteId: "actor#1",
  782. status: "waiting" as const,
  783. ...stamp(name),
  784. })),
  785. ),
  786. nodes: NAMES.flatMap((name, i) =>
  787. Array.from({ length: 20 }, (_, k) =>
  788. settled("ask#1", i * 20 + k + 1, {
  789. actorOrdinal: i * 20 + k + 1,
  790. actorSiteId: "actor#1",
  791. ...stamp(name),
  792. }),
  793. ),
  794. ),
  795. });
  796. }
  797. it("每站只数自己阶段的实例:药丸 20/20/20/20/20、fraction 20/20,而不是 100", () => {
  798. const model = buildWorkflowTimeline(FAN_OUT, fanOutRun(true));
  799. expect(model.stations.map((station) => station.pills.length)).toEqual([20, 20, 20, 20, 20]);
  800. expect(model.stations.map((station) => station.fraction)).toEqual(
  801. NAMES.map(() => ({ observed: 20, settled: 20 })),
  802. );
  803. // 药丸就是该阶段的那 20 个实例(第 3 站是 41…60)。
  804. expect(model.stations[2]!.pills.map((pill) => pill.instance?.ordinal)).toEqual(
  805. Array.from({ length: 20 }, (_, k) => 41 + k),
  806. );
  807. });
  808. it("无戳的 run 退回按车道绑定:每站 100 个——bug 的画面,旧 run 保持不变", () => {
  809. const model = buildWorkflowTimeline(FAN_OUT, fanOutRun(false));
  810. expect(model.stations.map((station) => station.pills.length)).toEqual([
  811. 100, 100, 100, 100, 100,
  812. ]);
  813. expect(model.stations[0]!.fraction).toEqual({ observed: 100, settled: 100 });
  814. });
  815. // ——— 追记 2026-09-10「叠加视图也按出生阶段收窄」:灯也只信自己阶段的节点 ———
  816. /** 第 p 阶段(1 起)在跑、之前的阶段全部结算:节点、进入记录与 currentPhase 一致。 */
  817. function midRun(p: number, stamped = true): WorkflowRunState {
  818. const stamp = (name: string) => (stamped ? { phaseName: name } : {});
  819. return run({
  820. currentPhase: NAMES[p - 1],
  821. nodes: NAMES.slice(0, p).flatMap((name, i) =>
  822. Array.from({ length: 20 }, (_, k) =>
  823. (i + 1 < p ? settled : executing)("ask#1", i * 20 + k + 1, {
  824. actorOrdinal: i * 20 + k + 1,
  825. actorSiteId: "actor#1",
  826. ...stamp(name),
  827. }),
  828. ),
  829. ),
  830. phases: NAMES.slice(0, p).map((name) => ({ name, rounds: 1 })),
  831. });
  832. }
  833. it("灯只信自己阶段的节点:第 1 阶段在跑时 running/pending×4,第 2 阶段在跑时 done/running/pending×3", () => {
  834. expect(buildWorkflowTimeline(FAN_OUT, midRun(1)).stations.map((s) => s.status)).toEqual([
  835. "running",
  836. "pending",
  837. "pending",
  838. "pending",
  839. "pending",
  840. ]);
  841. const second = buildWorkflowTimeline(FAN_OUT, midRun(2));
  842. expect(second.stations.map((s) => s.status)).toEqual([
  843. "done",
  844. "running",
  845. "pending",
  846. "pending",
  847. "pending",
  848. ]);
  849. expect(second.runningIndex).toBe(1);
  850. // 第 2 站的药丸是它自己的 20 个,且都在跑;第 3 站的药丸还没出生,pending。
  851. expect(second.stations[1]!.pills.every((pill) => pill.status === "running")).toBe(true);
  852. expect(second.stations[2]!.pills.every((pill) => pill.status === "pending")).toBe(true);
  853. });
  854. it("无戳的 run 保持五灯齐亮的旧画面:叠加退回按站点广播", () => {
  855. expect(buildWorkflowTimeline(FAN_OUT, midRun(1, false)).stations.map((s) => s.status)).toEqual([
  856. "running",
  857. "running",
  858. "running",
  859. "running",
  860. "running",
  861. ]);
  862. });
  863. });
  864. // 表外条目(docs/dynamic-workflow/presentation.md「Past six participants」):归约淘汰掉的子代理
  865. // 没有药丸,它们的账记在 `unlistedByPhase` 的出生阶段那一格上,由站带给卡与侧板。
  866. describe("buildWorkflowTimeline · 表外条目", () => {
  867. function truncated(
  868. unlistedByPhase: NonNullable<WorkflowRunState["unlistedByPhase"]>,
  869. nodes: WorkflowRunState["nodes"] = [],
  870. ): WorkflowRunState {
  871. return run({
  872. actors: [{ siteId: "actor#1", ordinal: 1, status: "completed", phaseName: "plan" }],
  873. nodes,
  874. truncated: true,
  875. unlistedByPhase,
  876. usage: { spentTokens: 0, nodesUsed: 0, nodesUnlisted: 300, nodesUnlistedSettled: 300 },
  877. });
  878. }
  879. it("按出生阶段的戳归位;fraction 的分子与分母一起抬,一条都没少的站不带这一格", () => {
  880. const model = buildWorkflowTimeline(
  881. GRAPH,
  882. truncated(
  883. [
  884. { phaseName: "plan", actors: 300, actorsSettled: 100, actorsFailed: 2, settled: 300 },
  885. { phaseName: "draft", actors: 1, settled: 0 },
  886. ],
  887. [settled("ask#1", 1, { phaseName: "plan" })],
  888. ),
  889. );
  890. const [plan, draft, verify] = model.stations;
  891. // 子代理的三个数与节点的那个数分开:`settled` 是 `actorsSettled`,`nodesSettled` 是节点的。
  892. expect(plan!.unlisted).toEqual({ actors: 300, failed: 2, nodesSettled: 300, settled: 100 });
  893. // 表内一个已结算 + 表外三百个节点:301/301,而不是 1/1。
  894. expect(plan!.fraction).toEqual({ observed: 301, settled: 301 });
  895. // 只少了子代理、没少节点的站:数字在,fraction 仍然缺席(一个节点都没观察到)。
  896. // `actorsSettled` 缺席即归零——那一个还没跑。
  897. expect(draft!.unlisted).toEqual({ actors: 1, failed: 0, nodesSettled: 0, settled: 0 });
  898. expect(draft!.fraction).toBeUndefined();
  899. expect(verify!.unlisted).toBeUndefined();
  900. // 灯不受影响:表外的只是数字,不是状态。
  901. expect(model.stations.map((station) => station.status)).toEqual(["done", "pending", "pending"]);
  902. });
  903. it("无阶段那一格落在无名的站上——与无戳实例同一条绑定规则", () => {
  904. const mixed: WorkflowCausalityGraphData = {
  905. steps: [
  906. { id: "ask#0", kind: "ask", label: "warm up", lane: "actor#1", phase: "unphased" },
  907. { id: "ask#1", kind: "ask", label: "plan", lane: "actor#1", phase: "phase#a" },
  908. ],
  909. lanes: [{ id: "actor#1" }],
  910. participants: [
  911. { id: "unphased:actor#1", phase: "unphased", lane: "actor#1", steps: ["ask#0"] },
  912. { id: "phase#a:actor#1", phase: "phase#a", lane: "actor#1", steps: ["ask#1"] },
  913. ],
  914. handoffs: [],
  915. phases: [{ id: "unphased" }, { id: "phase#a", name: "plan" }],
  916. phaseEdges: [{ from: "unphased", to: "phase#a" }],
  917. };
  918. const model = buildWorkflowTimeline(
  919. mixed,
  920. truncated([
  921. { actors: 4, actorsSettled: 4, settled: 7 },
  922. { phaseName: "plan", actors: 2, actorsSettled: 1, actorsFailed: 1, settled: 0 },
  923. ]),
  924. );
  925. expect(model.stations.map((station) => station.unlisted)).toEqual([
  926. { actors: 4, failed: 0, nodesSettled: 7, settled: 4 },
  927. { actors: 2, failed: 1, nodesSettled: 0, settled: 1 },
  928. ]);
  929. expect(model.stations[0]!.fraction).toEqual({ observed: 7, settled: 7 });
  930. });
  931. });
  932. // 并行阶段(docs/dynamic-workflow/presentation.md「The timeline model」的带):`alongside` 把
  933. // 声明序上连续的几站折成一条带,带内分轨道,带之前分叉、之后汇合;弧把整条带当一个节点。
  934. describe("buildWorkflowTimeline · 带", () => {
  935. /** 一站一个 ask 成员的骨架图:`near[i]` 是第 i 站的 `alongside`,边按下标给。 */
  936. function bandGraph(
  937. near: (number[] | undefined)[],
  938. edges: [number, number][],
  939. ): WorkflowCausalityGraphData {
  940. const steps: WorkflowCausalityGraphData["steps"] = near.map((_, i) => ({
  941. id: `ask#${i}`,
  942. kind: "ask",
  943. label: `step ${i}`,
  944. lane: `actor#${i}`,
  945. phase: `phase#${i}`,
  946. }));
  947. return {
  948. steps,
  949. lanes: near.map((_, i) => ({ id: `actor#${i}` })),
  950. participants: participantsOf(steps),
  951. handoffs: [],
  952. phases: near.map((alongside, i) => ({
  953. id: `phase#${i}`,
  954. name: `P${i}`,
  955. ...(alongside === undefined ? {} : { alongside: alongside.map((j) => `phase#${j}`) }),
  956. })),
  957. phaseEdges: edges.map(([from, to]) => ({ from: `phase#${from}`, to: `phase#${to}` })),
  958. exits: [`phase#${near.length - 1}`],
  959. };
  960. }
  961. // A ∥ B → C(strand-fanout-two-phases-join)。有界层报的是约简后的边:A → B、B → C,
  962. // A → C 被传递约简掉了。
  963. const TESTFIELD = bandGraph(
  964. [undefined, [0], undefined],
  965. [
  966. [0, 1],
  967. [1, 2],
  968. ],
  969. );
  970. it("没有 alongside 时没有带:站都在主线上,弧都在最下面那层空里", () => {
  971. const model = buildWorkflowTimeline(GRAPH, undefined);
  972. expect(model.bands).toEqual([]);
  973. expect(model.stations.map((station) => station.track)).toEqual([0, 0, 0]);
  974. expect(model.arcs.every((arc) => arc.air === 0)).toBe(true);
  975. expect(model.rails.every((rail) => rail.kind === undefined)).toBe(true);
  976. });
  977. it("A ∥ B → C:一条带两条轨道,没有前驱、汇合到 C", () => {
  978. const model = buildWorkflowTimeline(TESTFIELD, undefined);
  979. expect(model.stations.map((station) => station.track)).toEqual([0, 1, 0]);
  980. expect(model.bands).toEqual([
  981. {
  982. from: 0,
  983. join: 2,
  984. to: 1,
  985. tracks: [
  986. { entry: "faint", exit: "faint", stations: [0] },
  987. { entry: "faint", exit: "faint", stations: [1] },
  988. ],
  989. },
  990. ]);
  991. });
  992. it("带内跨轨道的前向边被丢掉(分叉已经说过控制经过了两边),相邻两站改画双线段", () => {
  993. const model = buildWorkflowTimeline(TESTFIELD, undefined);
  994. expect(model.rails).toEqual([
  995. { from: 0, ink: "faint", kind: "twin", to: 1 },
  996. { from: 0, ink: "faint", to: 2 },
  997. { from: 1, ink: "faint", kind: "merge", to: 2 },
  998. ]);
  999. expect(model.arcs).toEqual([]);
  1000. });
  1001. it("轨道的进出墨:没有前驱时按首站到没到过,汇合段的墨就是那条轨道的出墨", () => {
  1002. const model = buildWorkflowTimeline(
  1003. TESTFIELD,
  1004. run({ nodes: [settled("ask#0"), settled("ask#1"), settled("ask#2")] }),
  1005. );
  1006. expect(model.bands[0]!.tracks.map((track) => [track.entry, track.exit])).toEqual([
  1007. ["strong", "strong"],
  1008. ["strong", "strong"],
  1009. ]);
  1010. const half = buildWorkflowTimeline(TESTFIELD, run({ nodes: [settled("ask#0")] }));
  1011. expect(half.bands[0]!.tracks.map((track) => [track.entry, track.exit])).toEqual([
  1012. ["strong", "faint"],
  1013. ["faint", "faint"],
  1014. ]);
  1015. });
  1016. it("行进边:汇合站在跑时,主线那一段与每一条汇合段都行进", () => {
  1017. const model = buildWorkflowTimeline(
  1018. TESTFIELD,
  1019. run({ nodes: [settled("ask#0"), settled("ask#1"), executing("ask#2")] }),
  1020. );
  1021. expect(model.runningIndex).toBe(2);
  1022. expect(model.rails.filter((rail) => rail.ink === "march")).toEqual([
  1023. { from: 0, ink: "march", to: 2 },
  1024. { from: 1, ink: "march", kind: "merge", to: 2 },
  1025. ]);
  1026. expect(model.bands[0]!.tracks.map((track) => track.exit)).toEqual(["march", "march"]);
  1027. });
  1028. it("行进边:带的两条轨道同时在跑而没有前驱时什么都不行进——双线段不是控制流走的路", () => {
  1029. const model = buildWorkflowTimeline(
  1030. TESTFIELD,
  1031. run({ nodes: [executing("ask#0"), executing("ask#1")] }),
  1032. );
  1033. expect(model.runningIndex).toBe(1);
  1034. expect(model.rails.every((rail) => rail.ink !== "march")).toBe(true);
  1035. expect(model.arcs).toEqual([]);
  1036. });
  1037. it("有前驱时分叉出去:主线一条平轨、每条分支一条分叉段,同时在跑就一起行进", () => {
  1038. const withPred = bandGraph(
  1039. [undefined, undefined, [1], undefined],
  1040. [
  1041. [0, 1],
  1042. [1, 2],
  1043. [2, 3],
  1044. ],
  1045. );
  1046. const model = buildWorkflowTimeline(withPred, undefined);
  1047. expect(model.bands[0]).toMatchObject({ from: 1, join: 3, pred: 0, to: 2 });
  1048. expect(model.rails).toEqual([
  1049. { from: 0, ink: "faint", to: 1 },
  1050. { from: 0, ink: "faint", kind: "fork", to: 2 },
  1051. { from: 1, ink: "faint", kind: "twin", to: 2 },
  1052. { from: 1, ink: "faint", to: 3 },
  1053. { from: 2, ink: "faint", kind: "merge", to: 3 },
  1054. ]);
  1055. const live = buildWorkflowTimeline(
  1056. withPred,
  1057. run({ nodes: [settled("ask#0"), executing("ask#1"), executing("ask#2")] }),
  1058. );
  1059. expect(live.rails.filter((rail) => rail.ink === "march")).toEqual([
  1060. { from: 0, ink: "march", to: 1 },
  1061. { from: 0, ink: "march", kind: "fork", to: 2 },
  1062. ]);
  1063. expect(live.bands[0]!.tracks.map((track) => track.entry)).toEqual(["march", "march"]);
  1064. });
  1065. it("重叠链:A 与 C 在主线上前后相接,即使它们之间的边已经被约简掉", () => {
  1066. const chain = bandGraph(
  1067. [undefined, [0], [1], undefined],
  1068. [
  1069. [0, 1],
  1070. [1, 2],
  1071. [2, 3],
  1072. ],
  1073. );
  1074. const model = buildWorkflowTimeline(chain, undefined);
  1075. expect(model.stations.map((station) => station.track)).toEqual([0, 1, 0, 0]);
  1076. expect(model.bands[0]!.tracks.map((track) => track.stations)).toEqual([[0, 2], [1]]);
  1077. expect(model.rails).toEqual([
  1078. { from: 0, ink: "faint", kind: "twin", to: 1 },
  1079. { from: 0, ink: "faint", to: 2 },
  1080. { from: 1, ink: "faint", kind: "twin", to: 2 },
  1081. { from: 1, ink: "faint", kind: "merge", to: 3 },
  1082. { from: 2, ink: "faint", to: 3 },
  1083. ]);
  1084. });
  1085. it("绕整条带的循环落在带的左端:整条带都上环", () => {
  1086. // 规则 1a:回边 C → A 画到分叉点上,说的是「整条带再入一次」。
  1087. const loop = bandGraph(
  1088. [undefined, [0], undefined],
  1089. [
  1090. [0, 2],
  1091. [1, 2],
  1092. [2, 0],
  1093. ],
  1094. );
  1095. const model = buildWorkflowTimeline(loop, undefined);
  1096. expect(model.arcs).toEqual([{ air: 1, from: 2, ink: "faint", lane: 0, to: 0 }]);
  1097. expect(model.stations.map((station) => station.onLoop)).toEqual([true, true, true]);
  1098. });
  1099. it("带内闭合的循环从带的右端出发(没有汇合站的带也有一个汇合点)", () => {
  1100. // 规则 1b:回边 B → plan 画到合流点上,说的是「两条 strand 都结算之后回到 plan」。
  1101. const loop = bandGraph(
  1102. [undefined, undefined, [1]],
  1103. [
  1104. [0, 1],
  1105. [0, 2],
  1106. [2, 0],
  1107. ],
  1108. );
  1109. const model = buildWorkflowTimeline(loop, undefined);
  1110. expect(model.bands[0]).toMatchObject({ from: 1, pred: 0, to: 2 });
  1111. expect(model.bands[0]!.join).toBeUndefined();
  1112. expect(model.arcs).toEqual([{ air: 1, from: 2, ink: "faint", lane: 0, to: 0 }]);
  1113. expect(model.rails).toEqual([
  1114. { from: 0, ink: "faint", to: 1 },
  1115. { from: 0, ink: "faint", kind: "fork", to: 2 },
  1116. { from: 1, ink: "faint", kind: "twin", to: 2 },
  1117. ]);
  1118. });
  1119. it("一条轨道内部的循环用那条轨道自己的空", () => {
  1120. // 规则 2:评审 → 起草 是同一条分支轨道上的两站,弧画在那条轨道的上方。
  1121. const inside = bandGraph(
  1122. [undefined, undefined, [1], [1], undefined],
  1123. [
  1124. [0, 1],
  1125. [0, 2],
  1126. [2, 3],
  1127. [3, 2],
  1128. [1, 4],
  1129. [3, 4],
  1130. ],
  1131. );
  1132. const model = buildWorkflowTimeline(inside, undefined);
  1133. expect(model.bands[0]!.tracks.map((track) => track.stations)).toEqual([[1], [2, 3]]);
  1134. expect(model.arcs).toEqual([{ air: 1, from: 3, ink: "faint", lane: 0, to: 2 }]);
  1135. // 同轨道相邻的 2 → 3 已经是轨道段,不再画一遍。
  1136. expect(model.rails).toEqual([
  1137. { from: 0, ink: "faint", to: 1 },
  1138. { from: 0, ink: "faint", kind: "fork", to: 2 },
  1139. { from: 1, ink: "faint", kind: "twin", to: 2 },
  1140. { from: 1, ink: "faint", to: 4 },
  1141. { from: 2, ink: "faint", to: 3 },
  1142. { from: 3, ink: "faint", kind: "merge", to: 4 },
  1143. ]);
  1144. expect(model.stations.map((station) => station.onLoop)).toEqual([
  1145. false,
  1146. true,
  1147. true,
  1148. true,
  1149. false,
  1150. ]);
  1151. });
  1152. it("分道按空各算各的:两条轨道各有一个循环时,两条弧都贴着自己的轨道", () => {
  1153. const twoLoops = bandGraph(
  1154. [undefined, undefined, [1], [2], [3], undefined],
  1155. [
  1156. [0, 1],
  1157. [3, 1],
  1158. [4, 2],
  1159. [3, 5],
  1160. [4, 5],
  1161. ],
  1162. );
  1163. const model = buildWorkflowTimeline(twoLoops, undefined);
  1164. expect(model.bands[0]!.tracks.map((track) => track.stations)).toEqual([
  1165. [1, 3],
  1166. [2, 4],
  1167. ]);
  1168. // 两条弧在 x 上相交([1,3] 与 [2,4]),但它们在不同的空里,各自都是最低的一道。
  1169. expect(model.arcs).toEqual([
  1170. { air: 0, from: 3, ink: "faint", lane: 0, to: 1 },
  1171. { air: 1, from: 4, ink: "faint", lane: 0, to: 2 },
  1172. ]);
  1173. expect(arcLaneCount(model.arcs.filter((arc) => arc.air === 0))).toBe(1);
  1174. expect(arcLaneCount(model.arcs.filter((arc) => arc.air === 1))).toBe(1);
  1175. });
  1176. });