workflowArtifactPresets.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. applyArtifactItems,
  4. formatArtifactValue,
  5. readArtifactField,
  6. type ArtifactItem,
  7. type ChartModel,
  8. } from "@/app-shell/workflow-artifacts/presets/apply.js";
  9. import {
  10. artifactPresetFieldPaths,
  11. chartSeriesFields,
  12. parseArtifactPresetSpec,
  13. type ArtifactPresetKind,
  14. type BoardSpec,
  15. type ChartSpec,
  16. type MetricsSpec,
  17. type TableSpec,
  18. } from "@/app-shell/workflow-artifacts/presets/spec.js";
  19. /**
  20. * 预置产物的纯折叠函数与 spec 解析(docs/dynamic-workflow/authoring.md「Declaring a dashboard」
  21. * 「预置纯函数 `applyArtifactItems`」一行)。
  22. *
  23. * 看板不存数据,它是 journal 上带 `artifact_id` 的 report 条目的投影,因此这些断言就是
  24. * 「同一批条目必须折出同一张图」这条重放健全性要求本身。
  25. */
  26. function items(...raw: unknown[]): ArtifactItem[] {
  27. return raw.map((item, index) => ({
  28. sequence: index + 1,
  29. siteId: "report#1",
  30. ordinal: index + 1,
  31. item,
  32. }));
  33. }
  34. function parsedChart(spec: unknown): ChartSpec {
  35. const parsed = parseArtifactPresetSpec("chart", spec);
  36. expect(parsed).toBeDefined();
  37. return parsed as ChartSpec;
  38. }
  39. function seriesValues(model: ChartModel, seriesIndex: number): (number | string | null)[] {
  40. const key = model.series[seriesIndex]!.key;
  41. return model.points.map((point) => point[key] ?? null);
  42. }
  43. describe("readArtifactField / formatArtifactValue", () => {
  44. it("walks dot paths through objects and array indices", () => {
  45. const item = { timing: { after: 12 }, rounds: [{ ms: 3 }, { ms: 5 }] };
  46. expect(readArtifactField(item, "timing.after")).toBe(12);
  47. expect(readArtifactField(item, "rounds.1.ms")).toBe(5);
  48. expect(readArtifactField(item, "rounds.9.ms")).toBeUndefined();
  49. expect(readArtifactField(item, "timing.missing")).toBeUndefined();
  50. expect(readArtifactField(item, "timing.after.deeper")).toBeUndefined();
  51. expect(readArtifactField(null, "a.b")).toBeUndefined();
  52. });
  53. it("renders objects as compact JSON instead of [object Object]", () => {
  54. expect(formatArtifactValue({ a: 1 })).toBe('{"a":1}');
  55. expect(formatArtifactValue(undefined)).toBe("");
  56. expect(formatArtifactValue(null)).toBe("");
  57. expect(formatArtifactValue(false)).toBe("false");
  58. expect(formatArtifactValue("done")).toBe("done");
  59. });
  60. });
  61. describe("parseArtifactPresetSpec", () => {
  62. it("normalizes a single y field into an array and fills type/scale defaults", () => {
  63. const spec = parsedChart({ x: { field: "round" }, y: { field: "ms", unit: "ms" } });
  64. expect(spec.type).toBe("line");
  65. expect(spec.scale).toBe("linear");
  66. expect(chartSeriesFields(spec)).toEqual([{ field: "ms", unit: "ms" }]);
  67. });
  68. it("keeps declared chart type, scale and baseline", () => {
  69. const spec = parsedChart({
  70. type: "bar",
  71. scale: "log",
  72. x: { field: "round" },
  73. y: [{ field: "a" }, { field: "b", label: "B" }],
  74. baseline: { field: "budget", label: "预算" },
  75. title: "perf",
  76. description: "d",
  77. });
  78. expect(spec.type).toBe("bar");
  79. expect(spec.scale).toBe("log");
  80. expect(spec.baseline).toEqual({ field: "budget", label: "预算" });
  81. expect(spec.title).toBe("perf");
  82. expect(chartSeriesFields(spec)).toHaveLength(2);
  83. });
  84. it("falls back to defaults for unknown type/scale rather than refusing to render", () => {
  85. const spec = parsedChart({ x: { field: "r" }, y: { field: "v" }, type: "pie", scale: "sqrt" });
  86. expect(spec.type).toBe("line");
  87. expect(spec.scale).toBe("linear");
  88. });
  89. it("drops malformed optional pieces but keeps the spec renderable", () => {
  90. const spec = parsedChart({
  91. x: { field: "r" },
  92. y: [{ field: "a" }, { field: "" }, 7, { label: "no field" }],
  93. baseline: { label: "no field" },
  94. title: " ",
  95. });
  96. expect(chartSeriesFields(spec)).toEqual([{ field: "a" }]);
  97. expect(spec.baseline).toBeUndefined();
  98. expect(spec.title).toBeUndefined();
  99. });
  100. it("accepts a bare string as a field shorthand", () => {
  101. const spec = parsedChart({ x: "round", y: "ms" });
  102. expect(spec.x).toEqual({ field: "round" });
  103. expect(chartSeriesFields(spec)).toEqual([{ field: "ms" }]);
  104. });
  105. it("rejects malformed chart specs", () => {
  106. expect(parseArtifactPresetSpec("chart", undefined)).toBeUndefined();
  107. expect(parseArtifactPresetSpec("chart", null)).toBeUndefined();
  108. expect(parseArtifactPresetSpec("chart", "chart")).toBeUndefined();
  109. expect(parseArtifactPresetSpec("chart", [])).toBeUndefined();
  110. expect(parseArtifactPresetSpec("chart", {})).toBeUndefined();
  111. expect(parseArtifactPresetSpec("chart", { x: { field: "r" } })).toBeUndefined();
  112. expect(parseArtifactPresetSpec("chart", { y: { field: "v" } })).toBeUndefined();
  113. expect(parseArtifactPresetSpec("chart", { x: { field: "" }, y: "v" })).toBeUndefined();
  114. expect(parseArtifactPresetSpec("chart", { x: "r", y: [] })).toBeUndefined();
  115. });
  116. it("rejects malformed table / metrics / board specs", () => {
  117. expect(parseArtifactPresetSpec("table", {})).toBeUndefined();
  118. expect(parseArtifactPresetSpec("table", { columns: [] })).toBeUndefined();
  119. expect(parseArtifactPresetSpec("table", { columns: {} })).toBeUndefined();
  120. expect(parseArtifactPresetSpec("metrics", { metrics: [{ label: "x" }] })).toBeUndefined();
  121. expect(parseArtifactPresetSpec("board", { status: "s", columns: ["a"] })).toBeUndefined();
  122. expect(parseArtifactPresetSpec("board", { key: "k", columns: ["a"] })).toBeUndefined();
  123. expect(parseArtifactPresetSpec("board", { key: "k", status: "s" })).toBeUndefined();
  124. expect(
  125. parseArtifactPresetSpec("board", { key: "k", status: "s", columns: [] }),
  126. ).toBeUndefined();
  127. expect(
  128. parseArtifactPresetSpec("board", { key: "k", status: "s", columns: [1, ""] }),
  129. ).toBeUndefined();
  130. });
  131. it("keeps valid table / metrics / board specs and drops blank optionals", () => {
  132. const table = parseArtifactPresetSpec("table", {
  133. columns: ["name", { field: "ms", unit: "ms" }],
  134. key: " ",
  135. }) as TableSpec;
  136. expect(table.columns).toEqual([{ field: "name" }, { field: "ms", unit: "ms" }]);
  137. expect(table.key).toBeUndefined();
  138. const metrics = parseArtifactPresetSpec("metrics", {
  139. metrics: [{ field: "p99", label: "P99", unit: "ms" }],
  140. }) as MetricsSpec;
  141. expect(metrics.metrics).toEqual([{ field: "p99", label: "P99", unit: "ms" }]);
  142. const board = parseArtifactPresetSpec("board", {
  143. key: "id",
  144. status: "state",
  145. columns: ["todo", "done"],
  146. cardTitle: "title",
  147. detail: [{ field: "owner" }],
  148. }) as BoardSpec;
  149. expect(board.columns).toEqual(["todo", "done"]);
  150. expect(board.cardTitle).toBe("title");
  151. expect(board.detail).toEqual([{ field: "owner" }]);
  152. });
  153. });
  154. describe("applyArtifactItems — chart", () => {
  155. const spec = parsedChart({
  156. x: { field: "round", label: "轮次" },
  157. y: [
  158. { field: "queryMs", label: "查询", unit: "ms" },
  159. { field: "writeMs", label: "写入", unit: "ms" },
  160. ],
  161. baseline: { field: "budgetMs", label: "预算", unit: "ms" },
  162. });
  163. it("builds one series per y field and keeps the arriving sequence on every point", () => {
  164. const model = applyArtifactItems(
  165. "chart",
  166. spec,
  167. items(
  168. { round: 1, queryMs: 10, writeMs: 4 },
  169. { round: 2, queryMs: 8, writeMs: 5 },
  170. { round: 3, queryMs: 6 },
  171. ),
  172. );
  173. expect(model.series.map((series) => series.label)).toEqual(["查询", "写入"]);
  174. expect(model.series.map((series) => series.colorIndex)).toEqual([0, 1]);
  175. expect(model.points.map((point) => point.sequence)).toEqual([1, 2, 3]);
  176. expect(seriesValues(model, 0)).toEqual([10, 8, 6]);
  177. // 缺席的一维是 null(图上留缺口),不是 0——0 会凭空画出一次「性能归零」。
  178. expect(seriesValues(model, 1)).toEqual([4, 5, null]);
  179. expect(model.domain).toEqual({ xMin: 1, xMax: 3, yMin: 4, yMax: 10 });
  180. });
  181. it("sorts numeric x ascending regardless of arrival order", () => {
  182. const model = applyArtifactItems(
  183. "chart",
  184. spec,
  185. items({ round: 3, queryMs: 6 }, { round: 1, queryMs: 10 }, { round: 2, queryMs: 8 }),
  186. );
  187. expect(model.points.map((point) => point.x)).toEqual([1, 2, 3]);
  188. expect(model.points.map((point) => point.sequence)).toEqual([2, 3, 1]);
  189. expect(model.x.numeric).toBe(true);
  190. });
  191. it("keeps non-numeric x in arrival order and indexes it", () => {
  192. const model = applyArtifactItems(
  193. "chart",
  194. parsedChart({ x: "stage", y: "ms" }),
  195. items({ stage: "build", ms: 3 }, { stage: "test", ms: 9 }, { stage: "ship", ms: 1 }),
  196. );
  197. expect(model.x.numeric).toBe(false);
  198. expect(model.points.map((point) => point.x)).toEqual([0, 1, 2]);
  199. expect(model.points.map((point) => point.xLabel)).toEqual(["build", "test", "ship"]);
  200. });
  201. it("takes the baseline from the first item that has the field", () => {
  202. const model = applyArtifactItems(
  203. "chart",
  204. spec,
  205. items(
  206. { round: 1, queryMs: 10 },
  207. { round: 2, queryMs: 8, budgetMs: 7 },
  208. { round: 3, queryMs: 6, budgetMs: 99 },
  209. ),
  210. );
  211. expect(model.baseline).toEqual({ value: 7, label: "预算", unit: "ms" });
  212. });
  213. it("drops non-positive y values under a log scale", () => {
  214. const logSpec = parsedChart({ scale: "log", x: "round", y: "ms", baseline: "floor" });
  215. const model = applyArtifactItems(
  216. "chart",
  217. logSpec,
  218. items(
  219. { round: 1, ms: 10, floor: 0 },
  220. { round: 2, ms: 0 },
  221. { round: 3, ms: -4 },
  222. { round: 4, ms: 2, floor: 1 },
  223. ),
  224. );
  225. expect(seriesValues(model, 0)).toEqual([10, null, null, 2]);
  226. // 参考线同理:log 轴上 0 没有位置,于是跳到下一条带该字段的条目。
  227. expect(model.baseline).toEqual({ value: 1, label: "floor" });
  228. expect(model.domain).toEqual({ xMin: 1, xMax: 4, yMin: 2, yMax: 10 });
  229. });
  230. it("keeps non-positive y values under a linear scale", () => {
  231. const model = applyArtifactItems(
  232. "chart",
  233. parsedChart({ x: "round", y: "delta" }),
  234. items({ round: 1, delta: -3 }, { round: 2, delta: 0 }),
  235. );
  236. expect(seriesValues(model, 0)).toEqual([-3, 0]);
  237. });
  238. it("skips items without an x value and survives an empty stream", () => {
  239. const model = applyArtifactItems(
  240. "chart",
  241. spec,
  242. items({ queryMs: 10 }, { round: 2, queryMs: 8 }),
  243. );
  244. expect(model.points).toHaveLength(1);
  245. const empty = applyArtifactItems("chart", spec, []);
  246. expect(empty.points).toEqual([]);
  247. expect(empty.domain).toBeUndefined();
  248. });
  249. it("parses numeric strings so shell-scraped values still plot", () => {
  250. const model = applyArtifactItems(
  251. "chart",
  252. parsedChart({ x: "round", y: "ms" }),
  253. items({ round: "2", ms: "8.5" }, { round: "1", ms: "3" }),
  254. );
  255. expect(model.x.numeric).toBe(true);
  256. expect(model.points.map((point) => point.x)).toEqual([1, 2]);
  257. expect(seriesValues(model, 0)).toEqual([3, 8.5]);
  258. });
  259. });
  260. describe("applyArtifactItems — table", () => {
  261. const columns = [{ field: "name" }, { field: "state" }, { field: "timing.ms", label: "耗时" }];
  262. it("appends one row per item when no key is declared", () => {
  263. const spec = parseArtifactPresetSpec("table", { columns }) as TableSpec;
  264. const model = applyArtifactItems(
  265. "table",
  266. spec,
  267. items(
  268. { name: "a", state: "run", timing: { ms: 1 } },
  269. { name: "a", state: "done", timing: { ms: 2 } },
  270. ),
  271. );
  272. expect(model.rows).toHaveLength(2);
  273. expect(model.rows.map((row) => row.cells)).toEqual([
  274. ["a", "run", "1"],
  275. ["a", "done", "2"],
  276. ]);
  277. expect(model.columns.map((column) => column.label)).toEqual(["name", "state", "耗时"]);
  278. });
  279. it("upserts by key and keeps the row at its first-seen position", () => {
  280. const spec = parseArtifactPresetSpec("table", { columns, key: "name" }) as TableSpec;
  281. const model = applyArtifactItems(
  282. "table",
  283. spec,
  284. items(
  285. { name: "a", state: "run" },
  286. { name: "b", state: "run" },
  287. { name: "a", state: "done", timing: { ms: 9 } },
  288. ),
  289. );
  290. expect(model.rows.map((row) => row.id)).toEqual(["a", "b"]);
  291. expect(model.rows[0]!.cells).toEqual(["a", "done", "9"]);
  292. // 替换是整行替换,所以行的 sequence 跟到最后一次写入。
  293. expect(model.rows[0]!.sequence).toBe(3);
  294. });
  295. it("leaves a cell empty when the path does not resolve", () => {
  296. const spec = parseArtifactPresetSpec("table", { columns }) as TableSpec;
  297. const model = applyArtifactItems("table", spec, items({ name: "a" }));
  298. expect(model.rows[0]!.cells).toEqual(["a", "", ""]);
  299. });
  300. it("falls back to the journal identity when a keyed item carries no key", () => {
  301. const spec = parseArtifactPresetSpec("table", { columns, key: "name" }) as TableSpec;
  302. const model = applyArtifactItems("table", spec, items({ state: "run" }, { state: "done" }));
  303. expect(model.rows.map((row) => row.id)).toEqual(["report#1@1", "report#1@2"]);
  304. });
  305. });
  306. describe("applyArtifactItems — metrics", () => {
  307. const spec = parseArtifactPresetSpec("metrics", {
  308. metrics: [{ field: "p99", label: "P99", unit: "ms" }, { field: "errors" }, { field: "never" }],
  309. }) as MetricsSpec;
  310. it("takes each tile from the last item that has that field", () => {
  311. const model = applyArtifactItems(
  312. "metrics",
  313. spec,
  314. items({ p99: 10, errors: 2 }, { p99: 8 }, { stage: "idle" }),
  315. );
  316. expect(model.metrics[0]).toMatchObject({ label: "P99", unit: "ms", value: "8", sequence: 2 });
  317. // 只报 stage 的心跳条目不该把上一轮的 errors 抹掉。
  318. expect(model.metrics[1]).toMatchObject({ value: "2", sequence: 1 });
  319. expect(model.metrics[2]!.value).toBeUndefined();
  320. expect(model.metrics[2]!.sequence).toBeUndefined();
  321. });
  322. it("treats an explicit null as absent", () => {
  323. const model = applyArtifactItems("metrics", spec, items({ p99: 5 }, { p99: null }));
  324. expect(model.metrics[0]!.value).toBe("5");
  325. });
  326. it("keeps every tile present when the stream is empty", () => {
  327. const model = applyArtifactItems("metrics", spec, []);
  328. expect(model.metrics).toHaveLength(3);
  329. expect(model.metrics.every((tile) => tile.value === undefined)).toBe(true);
  330. });
  331. });
  332. describe("applyArtifactItems — board", () => {
  333. const spec = parseArtifactPresetSpec("board", {
  334. key: "id",
  335. status: "state",
  336. columns: ["todo", "doing", "done"],
  337. cardTitle: "title",
  338. detail: [{ field: "owner", label: "负责人" }],
  339. }) as BoardSpec;
  340. it("upserts cards by key and groups them into the declared column order", () => {
  341. const model = applyArtifactItems(
  342. "board",
  343. spec,
  344. items(
  345. { id: "1", state: "todo", title: "解析器", owner: "a" },
  346. { id: "2", state: "doing", title: "渲染器" },
  347. { id: "1", state: "done", title: "解析器", owner: "b" },
  348. ),
  349. );
  350. expect(model.columns.map((column) => column.id)).toEqual(["todo", "doing", "done"]);
  351. expect(model.columns[0]!.cards).toEqual([]);
  352. expect(model.columns[1]!.cards.map((card) => card.id)).toEqual(["2"]);
  353. expect(model.columns[2]!.cards.map((card) => card.id)).toEqual(["1"]);
  354. expect(model.columns[2]!.cards[0]!.details).toEqual([{ label: "负责人", value: "b" }]);
  355. expect(model.cardCount).toBe(2);
  356. });
  357. it("sends an unlisted status to a trailing other column", () => {
  358. const model = applyArtifactItems(
  359. "board",
  360. spec,
  361. items({ id: "1", state: "blocked" }, { id: "2", state: "todo" }),
  362. );
  363. expect(model.columns).toHaveLength(4);
  364. expect(model.columns.at(-1)!.other).toBe(true);
  365. expect(model.columns.at(-1)!.cards.map((card) => card.id)).toEqual(["1"]);
  366. });
  367. it("omits the other column when every status is listed", () => {
  368. const model = applyArtifactItems("board", spec, items({ id: "1", state: "todo" }));
  369. expect(model.columns.some((column) => column.other)).toBe(false);
  370. });
  371. it("falls back to the key for a missing card title and skips keyless items", () => {
  372. const model = applyArtifactItems(
  373. "board",
  374. spec,
  375. items({ id: "7", state: "todo" }, { state: "todo", title: "无主" }),
  376. );
  377. expect(model.cardCount).toBe(1);
  378. expect(model.columns[0]!.cards[0]!.title).toBe("7");
  379. });
  380. });
  381. describe("field-only entries (the CLI extracts the fields a dashboard reads)", () => {
  382. /**
  383. * CLI 只取 spec 点名的字段时,渲染器拿到的是 `fields` 表而不是整条 item。这里模拟 CLI:用同一条
  384. * 路径规则从整条 item 里取出 `artifactPresetFieldPaths` 列出的字段。两种条目必须折出同一张图——
  385. * 路径表漏一个,那一列 / 那条序列就会变空,断言就会红。
  386. */
  387. function asFieldEntries(entries: ArtifactItem[], paths: readonly string[]): ArtifactItem[] {
  388. return entries.map(({ item, ...rest }) => {
  389. const fields: Record<string, unknown> = {};
  390. for (const path of paths) {
  391. const value = readArtifactField(item, path);
  392. if (value !== undefined) fields[path] = value;
  393. }
  394. return { ...rest, fields };
  395. });
  396. }
  397. const stream = items(
  398. { round: 1, timing: { ms: 120, base: 100 }, name: "a", state: "todo", rows: [{ v: 3 }] },
  399. { round: 2, timing: { ms: 90 }, name: "b", state: "done", rows: [{ v: 4 }] },
  400. { round: 3, timing: { ms: 80 }, name: "a", state: "done", note: "late", rows: [] },
  401. );
  402. const specs: Array<[ArtifactPresetKind, unknown]> = [
  403. ["chart", { x: "round", y: ["timing.ms", "rows.0.v"], baseline: { field: "timing.base" } }],
  404. ["table", { key: "name", columns: [{ field: "round" }, { field: "timing.ms", unit: "ms" }] }],
  405. ["metrics", { metrics: [{ field: "timing.ms" }, { field: "note" }] }],
  406. [
  407. "board",
  408. {
  409. key: "name",
  410. status: "state",
  411. columns: ["todo", "done"],
  412. cardTitle: "note",
  413. detail: [{ field: "round" }],
  414. },
  415. ],
  416. ];
  417. for (const [kind, rawSpec] of specs) {
  418. it(`folds a ${kind} identically from whole items and from its field list`, () => {
  419. const paths = artifactPresetFieldPaths(kind, rawSpec);
  420. expect(paths).toBeDefined();
  421. const spec = parseArtifactPresetSpec(kind, rawSpec)!;
  422. expect(applyArtifactItems(kind, spec, asFieldEntries(stream, paths!))).toEqual(
  423. applyArtifactItems(kind, spec, stream),
  424. );
  425. });
  426. }
  427. it("lists each path once, in spec order, and nothing for a spec it cannot render", () => {
  428. expect(
  429. artifactPresetFieldPaths("chart", { x: "round", y: ["ms", "round"], baseline: "ms" }),
  430. ).toEqual(["round", "ms"]);
  431. expect(artifactPresetFieldPaths("board", { key: "id", status: "id", columns: ["a"] })).toEqual([
  432. "id",
  433. ]);
  434. expect(artifactPresetFieldPaths("table", { columns: [] })).toBeUndefined();
  435. });
  436. });