get-workflow-run-summary.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. // GetWorkflowRun 的摘要拼装与「多久以前」这把尺(docs/dynamic-workflow/launch.md「`GetWorkflowRun`」)。
  2. //
  3. // 这两件东西被单独钉住,是因为模型面上每一句话都建立在它们之上:摘要是确定性的(同一份
  4. // 快照永远同一句话),年龄是对 `generatedAt` 算的(一次输出一把尺)。任何一处飘了,
  5. // 整段情势报告就开始说一些它并不知道的事。
  6. import { describe, expect, it } from "vitest";
  7. import type { GetWorkflowRunOutput } from "@zcode/contracts";
  8. import { buildWorkflowRunSummary } from "../src/tool/handlers/get-workflow-run-summary.js";
  9. import {
  10. formatRelativeAge,
  11. formatWorkflowRunCount,
  12. formatWorkflowRunDuration,
  13. formatWorkflowRunInstant,
  14. } from "../src/tool/handlers/workflow-run-introspection.js";
  15. const NOW = Date.UTC(2026, 7, 21, 9, 5, 40);
  16. /** 一个最小但完整的输出:五个必填字段齐备,其余由各用例按需覆盖。 */
  17. const BASE: Omit<GetWorkflowRunOutput, "summary"> = {
  18. runId: "dwfrun-1",
  19. label: "nightly triage",
  20. labelSource: "name",
  21. status: "running",
  22. ownedByThisSession: true,
  23. createdAt: Date.UTC(2026, 7, 21, 9, 0, 0),
  24. updatedAt: Date.UTC(2026, 7, 21, 9, 5, 0),
  25. generatedAt: NOW,
  26. usage: { spentTokens: 0, nodesObserved: 0, nodesRunning: 0, nodesCompleted: 0, nodesFailed: 0 },
  27. actors: [],
  28. logTail: [],
  29. subagents: [],
  30. health: { consecutiveFailures: 0, cachedSteps: 0, pendingQuestionsKnown: true },
  31. };
  32. function summaryOf(patch: Partial<Omit<GetWorkflowRunOutput, "summary">>): string {
  33. return buildWorkflowRunSummary({ ...BASE, ...patch });
  34. }
  35. describe("workflow run duration and age", () => {
  36. // 四级阶梯:秒、分秒、时分、日时。分与秒补零(`1m 5s` 与 `1m 50s` 一眼难分)。
  37. it("writes two units at most, padding the 60-base ones", () => {
  38. expect(formatWorkflowRunDuration(40_000)).toBe("40s");
  39. expect(formatWorkflowRunDuration(310_000)).toBe("5m 10s");
  40. expect(formatWorkflowRunDuration(65_000)).toBe("1m 05s");
  41. expect(formatWorkflowRunDuration(8_100_000)).toBe("2h 15m");
  42. expect(formatWorkflowRunDuration(266_400_000)).toBe("3d 2h");
  43. });
  44. // 时钟回拨或坏值不该让一条时间戳把整个工具结果变成 NaN。
  45. it("folds a negative or non-finite span to zero", () => {
  46. expect(formatWorkflowRunDuration(-5_000)).toBe("0s");
  47. expect(formatWorkflowRunDuration(Number.NaN)).toBe("0s");
  48. });
  49. // 缺席读作「不知道」:老 journal 没有时间列,那样的行就没有年龄,而不是「0s ago」。
  50. it("returns nothing when the instant is unknown", () => {
  51. expect(formatRelativeAge(NOW, undefined)).toBeUndefined();
  52. expect(formatRelativeAge(NOW, Number.NaN)).toBeUndefined();
  53. expect(formatRelativeAge(NOW, NOW - 40_000)).toBe("40s ago");
  54. });
  55. it("writes an instant as ISO plus its age", () => {
  56. expect(formatWorkflowRunInstant(NOW, NOW - 40_000)).toBe("2026-08-21T09:05:00.000Z (40s ago)");
  57. });
  58. // 千分位自己插逗号:`toLocaleString` 的结果取决于宿主 ICU,而模型面要能逐字钉住。
  59. it("groups thousands without leaning on the host locale", () => {
  60. expect(formatWorkflowRunCount(6_210)).toBe("6,210");
  61. expect(formatWorkflowRunCount(41_200)).toBe("41,200");
  62. expect(formatWorkflowRunCount(999)).toBe("999");
  63. expect(formatWorkflowRunCount(1_000_000)).toBe("1,000,000");
  64. });
  65. });
  66. describe("workflow run summary — the live shapes", () => {
  67. it("says how long it has been running and how far the steps got", () => {
  68. expect(
  69. summaryOf({
  70. // 计数与花名册对齐:活相位的子代理各占一条还在跑的 ask 行,observed 是三态之和。
  71. usage: {
  72. spentTokens: 10,
  73. nodesObserved: 7,
  74. nodesRunning: 2,
  75. nodesCompleted: 5,
  76. nodesFailed: 0,
  77. },
  78. subagents: [
  79. {
  80. siteId: "a",
  81. ordinal: 1,
  82. state: "executing",
  83. stepsSettled: 0,
  84. stepsFailed: 0,
  85. tokens: 0,
  86. },
  87. { siteId: "b", ordinal: 1, state: "waiting", stepsSettled: 0, stepsFailed: 0, tokens: 0 },
  88. ],
  89. }),
  90. ).toBe(
  91. "Running for 5m 40s. 5 of 7 dispatched steps settled, 2 running (1 executing, 1 waiting).",
  92. );
  93. });
  94. // 花名册读不出来时(只有计数、没有 actor 行)宁可不给括号,也不拿计数去编一个细分。
  95. it("omits the breakdown instead of inventing one when the roster is empty", () => {
  96. const summary = summaryOf({
  97. usage: {
  98. spentTokens: 10,
  99. nodesObserved: 7,
  100. nodesRunning: 2,
  101. nodesCompleted: 5,
  102. nodesFailed: 0,
  103. },
  104. });
  105. expect(summary).toContain("2 running.");
  106. expect(summary).not.toContain("(");
  107. });
  108. // 在飞那几步分别在干什么,从花名册的相位数出来——「2 running」本身不回答「卡住了没」。
  109. it("breaks the running steps down by what the roster says they are doing", () => {
  110. const summary = summaryOf({
  111. usage: {
  112. spentTokens: 10,
  113. nodesObserved: 7,
  114. nodesRunning: 3,
  115. nodesCompleted: 4,
  116. nodesFailed: 0,
  117. },
  118. subagents: [
  119. { siteId: "a", ordinal: 1, state: "executing", stepsSettled: 0, stepsFailed: 0, tokens: 0 },
  120. { siteId: "b", ordinal: 1, state: "waiting", stepsSettled: 0, stepsFailed: 0, tokens: 0 },
  121. { siteId: "c", ordinal: 1, state: "parked", stepsSettled: 0, stepsFailed: 0, tokens: 0 },
  122. ],
  123. });
  124. expect(summary).toContain("3 running (1 executing, 1 waiting, 1 parked)");
  125. });
  126. it("points at the current phase while one is current", () => {
  127. expect(
  128. summaryOf({
  129. phases: [
  130. { name: "collect", state: "done", rounds: 1, nodesSettled: 2, nodesRunning: 0 },
  131. { name: "judge", state: "current", rounds: 1, nodesSettled: 0, nodesRunning: 1 },
  132. { name: "verify", state: "ahead", rounds: 0, nodesSettled: 0, nodesRunning: 0 },
  133. ],
  134. }),
  135. ).toContain("in phase 2 of 3 (judge)");
  136. });
  137. // 脚本没有阶段就不提阶段:一句「across 0 phases」是在回答一个没人问的问题。
  138. it("says nothing about phases when the run has none", () => {
  139. expect(summaryOf({})).not.toContain("phase");
  140. });
  141. it("counts the questions that are waiting, and stays silent when none are", () => {
  142. expect(
  143. summaryOf({
  144. pendingQuestions: [
  145. { qid: "q1", actor: "a@1", question: "?", askedAt: NOW },
  146. { qid: "q2", actor: "b@1", question: "?", askedAt: NOW },
  147. ],
  148. }),
  149. ).toContain("2 questions awaiting your answer.");
  150. expect(summaryOf({})).not.toContain("awaiting your answer");
  151. });
  152. // 「没有人在等」与「查不到」是两个不同的事实,而沉默会把后者读成前者。
  153. it("says outright that pending questions are unknown when they are", () => {
  154. expect(summaryOf({ health: { ...BASE.health, pendingQuestionsKnown: false } })).toContain(
  155. "Pending questions are unknown from this session.",
  156. );
  157. });
  158. it("reports the last progress and names a stall", () => {
  159. expect(summaryOf({ health: { ...BASE.health, lastProgressAt: NOW - 40_000 } })).toContain(
  160. "Last progress 40s ago.",
  161. );
  162. expect(
  163. summaryOf({
  164. health: { ...BASE.health, lastProgressAt: NOW - 40_000, stalledSince: NOW - 30_000 },
  165. }),
  166. ).toContain("Stalled, last progress 40s ago.");
  167. });
  168. it("marks a run this session does not own", () => {
  169. expect(summaryOf({ ownedByThisSession: false })).toContain("Owned by another session.");
  170. expect(summaryOf({})).not.toContain("Owned by another session.");
  171. });
  172. });
  173. describe("workflow run summary — the terminal shapes", () => {
  174. it("totals the settled steps and tokens for a completed run", () => {
  175. expect(
  176. summaryOf({
  177. status: "completed",
  178. usage: {
  179. spentTokens: 41_200,
  180. nodesObserved: 12,
  181. nodesRunning: 0,
  182. nodesCompleted: 12,
  183. nodesFailed: 0,
  184. },
  185. }),
  186. ).toBe("Completed in 5m 00s. 12 steps settled, 41,200 tokens.");
  187. });
  188. it("names the failure code so the model can tell a dead process from a bad script", () => {
  189. expect(
  190. summaryOf({ status: "errored", error: { code: "DriverError", message: "the script threw" } }),
  191. ).toContain("Failure: DriverError.");
  192. // 普通的 user 取消没有失败可报。
  193. expect(summaryOf({ status: "stopped", stopReason: "user" })).not.toContain("Failure:");
  194. });
  195. // 终态 run 里标着 running 的那些行是进程死在它们下面的残留,恢复会重派它们。
  196. it("explains the leftovers of an exited process instead of counting them as running", () => {
  197. expect(
  198. summaryOf({
  199. status: "stopped",
  200. stopReason: "interrupted",
  201. usage: {
  202. spentTokens: 10,
  203. nodesObserved: 7,
  204. nodesRunning: 2,
  205. nodesCompleted: 5,
  206. nodesFailed: 0,
  207. },
  208. health: { ...BASE.health, leftoverRunning: 2 },
  209. }),
  210. ).toContain(
  211. "2 were still running when the owning process exited and will be re-dispatched on resume",
  212. );
  213. });
  214. it("counts the phases instead of pointing at one once they are all behind it", () => {
  215. expect(
  216. summaryOf({
  217. status: "completed",
  218. phases: [
  219. { name: "collect", state: "done", rounds: 1, nodesSettled: 2, nodesRunning: 0 },
  220. { name: "judge", state: "done", rounds: 1, nodesSettled: 6, nodesRunning: 0 },
  221. ],
  222. }),
  223. ).toContain("across 2 phases");
  224. });
  225. it("points the reader at the deliverable of a completed run", () => {
  226. expect(
  227. summaryOf({
  228. status: "completed",
  229. artifacts: [
  230. { id: "notes", kind: "markdown", version: 1, itemCount: 0 },
  231. {
  232. id: "report",
  233. kind: "markdown",
  234. title: "Nightly triage report",
  235. version: 1,
  236. itemCount: 0,
  237. primary: true,
  238. },
  239. ],
  240. }),
  241. ).toContain("Deliverable: Nightly triage report (markdown, primary).");
  242. // 没有 primary 的 run 不去挑一件充数。
  243. expect(
  244. summaryOf({
  245. status: "completed",
  246. artifacts: [{ id: "notes", kind: "markdown", version: 1, itemCount: 0 }],
  247. }),
  248. ).not.toContain("Deliverable");
  249. });
  250. });
  251. describe("workflow run summary — the budget", () => {
  252. // 上界是整句整句地丢尾巴,而不是从中间切断一句话;头两句(处境 + 步数)任何预算下都在。
  253. it("drops whole trailing sentences to stay inside 400 characters", () => {
  254. const longTitle = "R".repeat(360);
  255. const summary = summaryOf({
  256. status: "completed",
  257. ownedByThisSession: false,
  258. usage: {
  259. spentTokens: 41_200,
  260. nodesObserved: 12,
  261. nodesRunning: 0,
  262. nodesCompleted: 12,
  263. nodesFailed: 0,
  264. },
  265. artifacts: [
  266. {
  267. id: "report",
  268. kind: "markdown",
  269. title: longTitle,
  270. version: 1,
  271. itemCount: 0,
  272. primary: true,
  273. },
  274. ],
  275. });
  276. expect(summary.length).toBeLessThanOrEqual(400);
  277. expect(summary).toContain("Completed in 5m 00s.");
  278. expect(summary).toContain("12 steps settled");
  279. expect(summary).not.toContain(longTitle);
  280. });
  281. });