Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

workflows.test.ts

521 lines18.6 KB

1import type {
2 WorkflowQuestion,
3 WorkflowRun,
4 WorkflowRunReference,
5 WorkflowStep,
6} from "@t3tools/contracts";
7import { describe, expect, it } from "vite-plus/test";
8​
9import {
10 allWorkflowRunNodes,
11 buildWorkflowFeed,
12 buildWorkflowTimeline,
13 defaultWorkflowListTab,
14 defaultWorkflowRunId,
15 groupWorkflowRuns,
16 listedWorkflowRuns,
17 readWorkflowQuestion,
18 workflowAgentSummary,
19 workflowAnswer,
20 workflowChip,
21 workflowFlowFocus,
22 workflowPausedBeat,
23 workflowResultLines,
24 workflowRunInvolves,
25 workflowRunLists,
26 workflowRunNow,
27 workflowRunRefreshKey,
28 workflowReferenceIssue,
29 workflowReferenceLabel,
30 workflowReferencePullRequest,
31 workflowRunState,
32 workflowSaidStart,
33 workflowStepReferences,
34 workflowStepTime,
35 workflowOneLine,
36 workflowTriggerLine,
37} from "./workflows.ts";
38​
39const two = (value: number) => String(value).padStart(2, "0");
40const at = (minute: number, second = 0) => `2026-11-01T00:${two(minute)}:${two(second)}.000Z`;
41​
42const run = (runId: string, fields: Partial<WorkflowRun> = {}): WorkflowRun => ({
43 runId,
44 workflow: "release",
45 version: 1,
46 title: runId,
47 status: "running",
48 detail: null,
49 result: null,
50 pauses: 0,
51 retired: false,
52 resumesAt: null,
53 parentRunId: null,
54 parentStep: null,
55 startedAt: at(0),
56 updatedAt: at(0),
57 endedAt: null,
58 ...fields,
59});
60const step = (
61 name: string,
62 kind: WorkflowStep["kind"],
63 from: string,
64 to: string | null,
65 fields: Partial<WorkflowStep> = {},
66): WorkflowStep => ({
67 name,
68 kind,
69 status: to === null ? "running" : "completed",
70 attempts: 1,
71 detail: null,
72 threadId: null,
73 environmentId: null,
74 result: null,
75 said: null,
76 startedAt: from,
77 endedAt: to,
78 ...fields,
79});
80const question = (runId: string, request: unknown = { title: "Ship?" }): WorkflowQuestion => ({
81 runId,
82 name: "approve",
83 request: request as never,
84 askedAt: at(1),
85 thread: null,
86});
87​
88describe("groupWorkflowRuns", () => {
89 const registered = [
90 { name: "release", version: 1, triggers: ["webhook tags"] },
91 { name: "check", version: 1, triggers: [] },
92 { name: "report", version: 2, triggers: ["daily at 09:00"] },
93 ];
94​
95 it("puts what waits on a person first, then each workflow with its own runs", () => {
96 const groups = groupWorkflowRuns(
97 registered,
98 [
99 run("done", { status: "completed", endedAt: at(9) }),
100 run("busy"),
101 run("parent", { status: "waiting", detail: "check" }),
102 // The child is what is paused, so its parent is the entry that needs someone.
103 run("child", {
104 workflow: "check",
105 status: "paused",
106 parentRunId: "parent",
107 parentStep: "check",
108 }),
109 run("asks", { workflow: "old", status: "waiting", detail: "approve" }),
110 run("orphan", { workflow: "old", status: "completed", endedAt: at(8), parentRunId: "x" }),
111 ],
112 [question("asks")],
113 );
114 expect(groups.needsYou.map((node) => node.run.runId)).toEqual(["parent", "asks"]);
115 expect(groups.needsYou[0]?.children.map((node) => node.run.runId)).toEqual(["child"]);
116 expect(
117 groups.workflows.map((section) => [
118 section.name,
119 workflowTriggerLine(section),
120 [...section.active, ...section.finished].map((node) => node.run.runId),
121 ]),
122 ).toEqual([
123 // What is under way comes first, then what has run, then what only exists.
124 ["release", "Starts on webhook tags", ["busy", "done"]],
125 ["old", "No longer registered on this server", ["orphan"]],
126 ["check", "Runs as part of other workflows", []],
127 ["report", "Starts on daily at 09:00", []],
128 ]);
129 expect(allWorkflowRunNodes(groups).map((node) => node.run.runId)).toEqual([
130 "parent",
131 "child",
132 "asks",
133 "busy",
134 "done",
135 "orphan",
136 ]);
137 // Opening the page lands on the first thing to act on, not on its untroubled parent.
138 expect(defaultWorkflowRunId(groups)).toBe("child");
139 });
140​
141 it("opens a run that is under way when nothing waits on anyone, else the newest", () => {
142 const quiet = groupWorkflowRuns(
143 registered,
144 [run("old", { endedAt: at(2), updatedAt: at(2) }), run("live", { workflow: "report" })],
145 [],
146 );
147 expect(defaultWorkflowRunId(quiet)).toBe("live");
148 const over = groupWorkflowRuns(
149 registered,
150 [
151 run("first", { endedAt: at(2), updatedAt: at(2) }),
152 run("last", { workflow: "report", endedAt: at(5), updatedAt: at(5) }),
153 ],
154 [],
155 );
156 expect(defaultWorkflowRunId(over)).toBe("last");
157 expect(defaultWorkflowRunId(groupWorkflowRuns(registered, [], []))).toBeNull();
158 });
159});
160​
161describe("the list of runs", () => {
162 const only = (fields: Partial<WorkflowRun>, questions: ReadonlyArray<WorkflowQuestion> = []) =>
163 allWorkflowRunNodes(groupWorkflowRuns([], [run("a", fields)], questions))[0]!;
164​
165 it("gives a run the word the thread list would, and says what it is at", () => {
166 const told = (fields: Partial<WorkflowRun>, questions?: ReadonlyArray<WorkflowQuestion>) => {
167 const node = only(fields, questions);
168 return `${workflowRunState(node).word}: ${workflowRunNow(node)}`;
169 };
170 expect(told({ status: "waiting", detail: "agent review" })).toBe("Working: review is working");
171 expect(told({ status: "waiting", detail: "sleep night" })).toBe("Sleeping: Sleeping at night");
172 expect(told({ status: "waiting", detail: "ci" })).toBe("Waiting: Waiting for ci");
173 expect(told({ status: "waiting", detail: "approve" }, [question("a")])).toBe(
174 "Needs you: Asks: Ship?",
175 );
176 expect(told({ status: "paused", detail: "build: exit 1\n at build.ts" })).toBe(
177 "Paused: build: exit 1",
178 );
179 expect(told({ status: "completed", endedAt: at(1), result: { merged: "ba6ac73" } })).toBe(
180 "Done: merged: ba6ac73",
181 );
182 expect(told({ status: "cancelled", endedAt: at(1), detail: "superseded" })).toBe(
183 "Cancelled: superseded",
184 );
185 });
186​
187 it("says of a run that waits on one it invoked what that one waits on", () => {
188 const groups = groupWorkflowRuns(
189 [],
190 [
191 run("child", { parentRunId: "parent", status: "waiting", title: "Check web" }),
192 run("parent", { status: "waiting", detail: "check" }),
193 ],
194 [question("child")],
195 );
196 const parent = allWorkflowRunNodes(groups)[0]!;
197 expect(workflowRunState(parent).word).toBe("Needs you");
198 expect(workflowRunNow(parent)).toBe("Check web: Asks: Ship?");
199 });
200​
201 it("sorts runs into what waits on a person, what is under way, and everything", () => {
202 const groups = groupWorkflowRuns(
203 [],
204 [
205 run("old", { status: "completed", endedAt: at(1), updatedAt: at(1) }),
206 run("busy", { updatedAt: at(2) }),
207 run("stuck", { status: "paused", updatedAt: at(3) }),
208 run("new", { status: "completed", endedAt: at(4), updatedAt: at(4) }),
209 ],
210 [],
211 );
212 const lists = workflowRunLists(groups);
213 const ids = (nodes: ReadonlyArray<{ readonly run: WorkflowRun }>) =>
214 nodes.map((node) => node.run.runId);
215 expect(ids(lists["needs-you"])).toEqual(["stuck"]);
216 expect(ids(lists.running)).toEqual(["busy"]);
217 expect(ids(lists.all)).toEqual(["stuck", "busy", "new", "old"]);
218 expect(defaultWorkflowListTab(groups)).toBe("needs-you");
219 expect(defaultWorkflowListTab(groupWorkflowRuns([], [run("busy")], []))).toBe("running");
220 expect(
221 defaultWorkflowListTab(
222 groupWorkflowRuns([], [run("old", { status: "completed", endedAt: at(1) })], []),
223 ),
224 ).toBe("all");
225 const invoked = workflowRunLists(
226 groupWorkflowRuns(
227 [],
228 [run("parent"), run("child", { workflow: "check", parentRunId: "parent" }), run("other")],
229 [],
230 ),
231 ).all;
232 expect(ids(invoked.filter((node) => workflowRunInvolves(node, "check")))).toEqual(["parent"]);
233 });
234​
235 it("leaves out what a workflow skipped, but not a skipped step of another run", () => {
236 const runs = [
237 run("ignored", { status: "skipped", endedAt: at(1) }),
238 run("parent"),
239 run("child", { status: "skipped", endedAt: at(1), parentRunId: "parent" }),
240 ];
241 expect(listedWorkflowRuns(runs, false)).toEqual({ runs: [runs[1], runs[2]], skipped: 1 });
242 expect(listedWorkflowRuns(runs, true)).toEqual({ runs, skipped: 1 });
243 });
244​
245 it("marks a workflow with the same letters and colour every time", () => {
246 expect(workflowChip("nightly-report").letters).toBe("NR");
247 expect(workflowChip("issue").letters).toBe("IS");
248 expect(workflowChip("issue")).toEqual(workflowChip("issue"));
249 });
250});
251​
252describe("workflowRunRefreshKey", () => {
253 it("reads an ended run again only when it changes, and one under way on any change", () => {
254 const snapshot = (runs: ReadonlyArray<WorkflowRun>) => ({ workflows: [], runs, questions: [] });
255 const ended = run("old", { endedAt: at(5), updatedAt: at(5) });
256 const before = snapshot([ended, run("busy", { updatedAt: at(6) })]);
257 const after = snapshot([ended, run("busy", { updatedAt: at(7) })]);
258 expect(workflowRunRefreshKey(before, "old")).toBe(workflowRunRefreshKey(after, "old"));
259 expect(workflowRunRefreshKey(before, "busy")).not.toBe(workflowRunRefreshKey(after, "busy"));
260 });
261});
262​
263describe("workflowAgentSummary", () => {
264 it("tells an agent's words apart from the facts of its result", () => {
265 expect(workflowAgentSummary({ result: "Fixed in one line.", said: null })).toEqual({
266 said: "Fixed in one line.",
267 facts: [],
268 });
269 expect(
270 workflowAgentSummary({
271 said: "Reproduced on main.",
272 result: { kind: "bug", reproduced: true, surfaces: ["web", "desktop"], prUrl: null },
273 }),
274 ).toEqual({
275 said: "Reproduced on main.",
276 facts: [
277 { label: "kind", value: "bug" },
278 { label: "reproduced", value: "yes" },
279 { label: "surfaces", value: "web, desktop" },
280 ],
281 });
282 });
283​
284 it("lets the longest prose of a result speak when no closing words were kept", () => {
285 const summary =
286 "The draft is stored per thread id, and a reload before the thread exists drops it for good.";
287 expect(workflowAgentSummary({ said: null, result: { verdict: "merge", summary } })).toEqual({
288 said: summary,
289 facts: [{ label: "verdict", value: "merge" }],
290 });
291 });
292});
293​
294describe("workflowSaidStart", () => {
295 it("cuts a long reply where a paragraph ends", () => {
296 const said =
297 "It is a real bug.\n\n**Where:** line 5.\n\n**Reproduced:** yes, with 3660 seconds.";
298 expect(workflowSaidStart(said, 200)).toBeNull();
299 expect(workflowSaidStart(said, 40)).toBe("It is a real bug.\n\n**Where:** line 5.");
300 expect(workflowSaidStart(said, 10)).toBe("It is a real bug.");
301 });
302});
303​
304describe("buildWorkflowTimeline", () => {
305 it("keeps the beats of a run and folds the bookkeeping between them", () => {
306 const parent = run("r", { startedAt: at(0), endedAt: at(10) });
307 const child = run("c", { parentRunId: "r", parentStep: "check", title: "Check web" });
308 const timeline = buildWorkflowTimeline({
309 run: parent,
310 children: [child],
311 nowMs: Date.parse(at(10)),
312 steps: [
313 step("load", "step", at(0), at(0)),
314 step("switch", "step", at(0), at(0)),
315 step("triage", "agent", at(0), at(3), { threadId: "t1" }),
316 // Two reviews at once.
317 step("review-a", "agent", at(3), at(5)),
318 step("review-b", "agent", at(3), at(6)),
319 step("record", "step", at(6), at(6)),
320 step("check/start", "step", at(6), at(6)),
321 step("check", "wait", at(6), at(8)),
322 step("build", "step", at(8), at(9)),
323 step("publish", "step", at(9), at(9), { status: "failed", detail: "503" }),
324 ],
325 });
326 expect(
327 timeline.rows.map((row) =>
328 row.kind === "quick"
329 ? `quick:${row.steps.map((quick) => quick.name).join(",")}`
330 : `${row.kind}:${row.name}${row.parallel ? ":parallel" : ""}`,
331 ),
332 ).toEqual([
333 "quick:load,switch",
334 "agent:triage",
335 "agent:review-a:parallel",
336 "agent:review-b:parallel",
337 "quick:record",
338 // The step that started the invoked run is told by the wait for it.
339 "run:check",
340 // A plain step that took a minute is a beat; so is one that failed in no time.
341 "step:build",
342 "step:publish",
343 ]);
344 const invoked = timeline.rows.find((row) => row.kind === "run");
345 expect(invoked?.kind === "run" ? invoked.childRun?.title : null).toBe("Check web");
346 // Read as a feed, the two reviews are one row, and the path has a stop per row that matters.
347 const feed = buildWorkflowFeed(timeline);
348 expect(
349 feed.map((row) =>
350 row.kind === "together"
351 ? row.beats.map((beat) => beat.name).join("+")
352 : row.kind === "quick"
353 ? "quick"
354 : row.name,
355 ),
356 ).toEqual(["quick", "triage", "review-a+review-b", "quick", "check", "build", "publish"]);
357 // The flow opens where the run needs someone, then where it failed, then on how it ended.
358 const focus = (status: WorkflowRun["status"], questions: ReadonlyArray<string> = []) =>
359 workflowFlowFocus({ rows: feed, status, ended: status === "completed", questions });
360 expect(focus("waiting", ["approve"])).toBe("question:approve");
361 expect(focus("paused")).toBe("step:publish");
362 expect(focus("completed")).toBe("end");
363 expect(focus("running")).toBe("step:publish");
364 expect(workflowPausedBeat(feed, "paused")?.name).toBe("publish");
365 // A failure the workflow caught, with the run going on after it, is not where it paused.
366 const caught = buildWorkflowFeed(
367 buildWorkflowTimeline({
368 run: run("r", { startedAt: at(0) }),
369 children: [],
370 nowMs: Date.parse(at(10)),
371 steps: [
372 step("lint", "agent", at(0), at(2), { status: "failed", detail: "timed out" }),
373 step("build", "agent", at(2), at(4)),
374 ],
375 }),
376 );
377 expect(workflowPausedBeat(caught, "paused")).toBeNull();
378 expect(workflowFlowFocus({ rows: caught, status: "paused", ended: false, questions: [] })).toBe(
379 "pause",
380 );
381 });
382​
383 it("measures a step that is under way up to now", () => {
384 const timeline = buildWorkflowTimeline({
385 run: run("r", { startedAt: at(0) }),
386 children: [],
387 nowMs: Date.parse(at(4)),
388 steps: [step("fix", "agent", at(1), null)],
389 });
390 const [fix] = timeline.rows;
391 expect(fix?.kind === "agent" ? [fix.endMs - fix.startMs, timeline.endMs] : null).toEqual([
392 180_000,
393 Date.parse(at(4)),
394 ]);
395 // Six started at once and a clock a minute behind: still one row, and no time runs backwards.
396 const wide = buildWorkflowTimeline({
397 run: run("r", { startedAt: at(1) }),
398 children: [],
399 nowMs: Date.parse(at(0)),
400 steps: [
401 step("a", "sleep", at(1), at(2)),
402 ...["b", "c", "d", "e", "f"].map((name) => step(name, "sleep", at(1), null)),
403 ],
404 });
405 expect(
406 buildWorkflowFeed(wide).map((row) => (row.kind === "together" ? row.beats.length : 1)),
407 ).toEqual([6]);
408 expect(wide.rows.every((row) => row.endMs >= row.startMs)).toBe(true);
409 });
410});
411​
412describe("workflowResultLines", () => {
413 it("reads a result as a sentence or as its fields", () => {
414 expect(workflowResultLines("merged as ba6ac7")).toEqual([
415 { label: null, value: "merged as ba6ac7" },
416 ]);
417 expect(workflowResultLines({ sent: true, to: "everyone" })).toEqual([
418 { label: "sent", value: "true" },
419 { label: "to", value: "everyone" },
420 ]);
421 expect(workflowResultLines(null)).toEqual([]);
422 });
423});
424​
425describe("readWorkflowQuestion", () => {
426 it("reads the title, the choices and the body, and drops parts of another shape", () => {
427 expect(
428 readWorkflowQuestion(
429 question("r", { title: "Ship it?", choices: ["yes", 2], data: { body: "Diff is small." } }),
430 ),
431 ).toEqual({ title: "Ship it?", choices: ["yes"], body: "Diff is small." });
432 expect(readWorkflowQuestion(question("r", null))).toEqual({
433 title: "approve",
434 choices: [],
435 body: null,
436 });
437 });
438});
439​
440describe("workflowAnswer", () => {
441 it("reads a person's answer off a question's result", () => {
442 expect(workflowAnswer({ choice: "Ship", reason: " " })).toEqual({
443 choice: "Ship",
444 reason: null,
445 });
446 expect(workflowAnswer({ choice: "Hold", reason: "Too risky" })).toEqual({
447 choice: "Hold",
448 reason: "Too risky",
449 });
450 expect(workflowAnswer("done")).toBeNull();
451 expect(workflowAnswer(null)).toBeNull();
452 });
453});
454​
455describe("workflow references", () => {
456 const reference = (fields: Partial<WorkflowRunReference>): WorkflowRunReference => ({
457 kind: "issue",
458 key: "k",
459 address: {},
460 title: "",
461 url: null,
462 state: null,
463 steps: [],
464 origin: "step",
465 ...fields,
466 });
467 const issue = (key: string) =>
468 reference({
469 key,
470 address: { projectId: "p1", tracker: "github", scope: "me/app", key },
471 steps: ["triage"],
472 });
473 const pullRequest = reference({
474 kind: "pullRequest",
475 key: "pr",
476 address: { projectId: "p1", host: "github.com", repository: "me/app", number: 418 },
477 steps: ["fix", "checks"],
478 });
479 const machine = reference({ kind: "machine", address: { id: 1 }, title: "box-1" });
480​
481 it("names each by what its kind calls it, and a kind it does not know by its title", () => {
482 expect(
483 [issue("412"), issue("ENG-12"), pullRequest, machine].map(workflowReferenceLabel),
484 ).toEqual(["#412", "ENG-12", "#418", "box-1"]);
485 expect(workflowReferenceLabel(reference({ kind: "machine" }))).toBe("machine");
486 });
487​
488 it("opens an issue or pull request only when its address reads as one", () => {
489 expect(workflowReferencePullRequest(pullRequest)?.number).toBe(418);
490 expect(workflowReferenceIssue(pullRequest)).toBeNull();
491 expect(workflowReferenceIssue(reference({ address: { key: 1 } }))).toBeNull();
492 expect(workflowReferenceIssue(machine)).toBeNull();
493 });
494​
495 it("gives a step the things it touched", () => {
496 const all = [issue("412"), pullRequest, machine];
497 expect(workflowStepReferences(all, "checks")).toEqual([pullRequest]);
498 expect(workflowStepReferences(all, "merge")).toEqual([]);
499 });
500});
501​
502describe("workflowStepTime", () => {
503 it("keeps one shape down the column", () => {
504 expect(workflowStepTime(9)).toBe("0.1s");
505 expect(workflowStepTime(342)).toBe("0.3s");
506 expect(workflowStepTime(9_700)).toBe("9.7s");
507 expect(workflowStepTime(4_000)).toBe("4s");
508 expect(workflowStepTime(12_400)).toBe("12s");
509 });
510});
511​
512describe("workflowOneLine", () => {
513 it("reads a reply's first sentence as plain words", () => {
514 expect(workflowOneLine("## Done\n\nI added `clamp` next to **sum**. Tests pass.")).toBe(
515 "I added clamp next to sum.",
516 );
517 expect(workflowOneLine("- See [the issue](https://x.test/2) first")).toBe(
518 "See the issue first",
519 );
520 });
521});