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

workflows.ts

974 lines36.9 KB

1import { mFallback, msg } from "gt-i18n";
2import type { MFunctionType } from "gt-i18n/types";
3import {
4 type IssueRef,
5 type PullRequestRef,
6 WorkflowIssueAddress,
7 WorkflowPullRequestAddress,
8 WorkflowReferenceKind,
9 type WorkflowQuestion,
10 type WorkflowRun,
11 type WorkflowRunReference,
12 type WorkflowRunsSnapshot,
13 type WorkflowRunSubject,
14 type WorkflowStep,
15 type WorkflowSummary,
16} from "@t3tools/contracts";
17import * as Option from "effect/Option";
18import * as Schema from "effect/Schema";
19import { formatDuration } from "@t3tools/shared/orchestrationTiming";
20​
21export interface WorkflowQuestionChoice {
22 readonly value: string;
23 /** What picking it does. */
24 readonly description: string | null;
25 /** The server refuses it without a reason. */
26 readonly requireReason: boolean;
28​
29export interface WorkflowQuestionLink {
30 readonly label: string;
31 readonly url: string;
33​
34export interface WorkflowQuestionView {
35 readonly title: string;
36 readonly choices: ReadonlyArray<WorkflowQuestionChoice>;
37 readonly body: string | null;
38 readonly links: ReadonlyArray<WorkflowQuestionLink>;
40​
41function field(value: unknown, key: string): unknown {
42 return typeof value === "object" && value !== null && !Array.isArray(value)
43 ? (value as Readonly<Record<string, unknown>>)[key]
44 : undefined;
46​
47const text = (value: unknown): string | null =>
48 typeof value === "string" && value.trim() !== "" ? value : null;
49​
50const isWebUrl = (url: string) => {
51 const protocol = URL.parse(url)?.protocol;
52 return protocol === "https:" || protocol === "http:";
53};
54​
55/**
56 * What a question shows. `request` is whatever the workflow handed `ask`, so a part that is
57 * missing or of another shape is left out instead of failing the whole list.
58 */
59export function readWorkflowQuestion(question: WorkflowQuestion): WorkflowQuestionView {
60 const choices = field(question.request, "choices");
61 const details = field(question.request, "choiceDetails");
62 const links = field(question.request, "links");
63 const detailOf = (value: string) =>
64 Array.isArray(details) ? details.find((detail) => field(detail, "value") === value) : undefined;
65 return {
66 title: text(field(question.request, "title")) ?? question.name,
67 choices: Array.isArray(choices)
68 ? choices
69 .filter((choice): choice is string => typeof choice === "string")
70 .map((value) => {
71 const detail = detailOf(value);
72 return {
73 value,
74 description: text(field(detail, "description")),
75 requireReason: field(detail, "requireReason") === true,
76 };
77 })
78 : [],
79 body: text(field(field(question.request, "data"), "body")),
80 links: Array.isArray(links)
81 ? links.flatMap((link) => {
82 const label = text(field(link, "label"));
83 const url = field(link, "url");
84 return label !== null && typeof url === "string" && isWebUrl(url) ? [{ label, url }] : [];
85 })
86 : [],
87 };
89​
90/**
91 * What a run's detail is read again on, out of the live list: the run's last change once it has
92 * ended. Steps do not move a run's `updatedAt`, so one under way is read again on any change.
93 */
94export function workflowRunRefreshKey(
95 snapshot: WorkflowRunsSnapshot | undefined,
96 runId: string,
97): unknown {
98 const run = snapshot?.runs.find((candidate) => candidate.runId === runId);
99 return run === undefined || run.endedAt === null ? snapshot : run.updatedAt;
101​
102export interface WorkflowRunNode {
103 readonly run: WorkflowRun;
104 /** The runs it invoked, in the order they started. */
105 readonly children: ReadonlyArray<WorkflowRunNode>;
106 /** Questions open on this run. */
107 readonly questions: ReadonlyArray<WorkflowQuestion>;
109​
110/** One workflow and the runs of it that nobody has to act on. */
111export interface WorkflowSection {
112 readonly name: string;
113 /** What starts it, in words. Null for a workflow this server no longer has registered. */
114 readonly triggers: ReadonlyArray<string> | null;
115 readonly active: ReadonlyArray<WorkflowRunNode>;
116 readonly finished: ReadonlyArray<WorkflowRunNode>;
117 /** It has runs, and every one was invoked by a run of another workflow. */
118 readonly invokedOnly: boolean;
119 /** It has never run here, as far as the list goes back. */
120 readonly neverRan: boolean;
122​
123export interface WorkflowRunGroups {
124 /** Runs a person has to act on: one has a question open or is paused, itself or below it. */
125 readonly needsYou: ReadonlyArray<WorkflowRunNode>;
126 /** Every workflow there is, busiest first, each with its other runs. */
127 readonly workflows: ReadonlyArray<WorkflowSection>;
129​
130const needsPerson = (node: WorkflowRunNode): boolean =>
131 node.questions.length > 0 || node.run.status === "paused" || node.children.some(needsPerson);
132​
133/**
134 * The list a person reads: what waits on them first, then each workflow with its runs. A run
135 * that another invoked sits under that one, so a piece of work is one entry, and a workflow that
136 * has not run yet is still listed, since the list is also how one learns what exists. `runs` is
137 * newest first and that order is kept.
138 */
139/**
140 * The runs a list shows: without those a workflow skipped as not its to do, unless asked for
141 * them. A skipped run that another run invoked stays, as a step of that one.
142 */
143export function listedWorkflowRuns(
144 runs: ReadonlyArray<WorkflowRun>,
145 showSkipped: boolean,
146): { readonly runs: ReadonlyArray<WorkflowRun>; readonly skipped: number } {
147 const hidden = (run: WorkflowRun) => run.status === "skipped" && run.parentRunId === null;
148 const skipped = runs.filter(hidden).length;
149 return { runs: showSkipped ? runs : runs.filter((run) => !hidden(run)), skipped };
151​
152export function groupWorkflowRuns(
153 workflows: ReadonlyArray<WorkflowSummary>,
154 runs: ReadonlyArray<WorkflowRun>,
155 questions: ReadonlyArray<WorkflowQuestion>,
156): WorkflowRunGroups {
157 const listed = new Set(runs.map((run) => run.runId));
158 const childrenOf = new Map<string, WorkflowRun[]>();
159 const roots: WorkflowRun[] = [];
160 for (const run of runs) {
161 if (run.parentRunId === null || !listed.has(run.parentRunId)) {
162 roots.push(run);
163 continue;
164 }
165 const siblings = childrenOf.get(run.parentRunId);
166 if (siblings) siblings.push(run);
167 else childrenOf.set(run.parentRunId, [run]);
168 }
169 const node = (run: WorkflowRun): WorkflowRunNode => ({
170 run,
171 questions: questions.filter((question) => question.runId === run.runId),
172 children: (childrenOf.get(run.runId) ?? [])
173 .slice()
174 .sort((left, right) => left.startedAt.localeCompare(right.startedAt))
175 .map(node),
176 });
177 const needsYou: WorkflowRunNode[] = [];
178 const sections = new Map<string, { active: WorkflowRunNode[]; finished: WorkflowRunNode[] }>();
179 const sectionOf = (name: string) => {
180 const known = sections.get(name);
181 if (known) return known;
182 const made = { active: [], finished: [] };
183 sections.set(name, made);
184 return made;
185 };
186 for (const root of roots.map(node)) {
187 if (needsPerson(root)) needsYou.push(root);
188 else if (root.run.endedAt === null) sectionOf(root.run.workflow).active.push(root);
189 else sectionOf(root.run.workflow).finished.push(root);
190 }
191 const registered = new Map(workflows.map((workflow) => [workflow.name, workflow] as const));
192 const hasRuns = new Set(runs.map((run) => run.workflow));
193 const hasRootRuns = new Set(roots.map((run) => run.workflow));
194 const names = [...new Set([...sections.keys(), ...registered.keys(), ...hasRuns])];
195 const rank = (name: string) => {
196 const section = sections.get(name);
197 if (section !== undefined && section.active.length > 0) return 0;
198 return section !== undefined && section.finished.length > 0 ? 1 : 2;
199 };
200 return {
201 needsYou,
202 workflows: names
203 .map((name) => ({
204 name,
205 triggers: registered.get(name)?.triggers ?? null,
206 active: sections.get(name)?.active ?? [],
207 finished: sections.get(name)?.finished ?? [],
208 invokedOnly: hasRuns.has(name) && !hasRootRuns.has(name),
209 neverRan: !hasRuns.has(name),
210 }))
211 .slice()
212 .sort(
213 (left, right) => rank(left.name) - rank(right.name) || left.name.localeCompare(right.name),
214 ),
215 };
217​
218/** Every run of these, parents before the runs they invoked. */
219function flattenWorkflowRunNodes(
220 nodes: ReadonlyArray<WorkflowRunNode>,
221): ReadonlyArray<WorkflowRunNode> {
222 return nodes.flatMap((node) => [node, ...flattenWorkflowRunNodes(node.children)]);
224​
225/** Every run in the list, in the order it is listed. */
226export function allWorkflowRunNodes(groups: WorkflowRunGroups): ReadonlyArray<WorkflowRunNode> {
227 return flattenWorkflowRunNodes([
228 ...groups.needsYou,
229 ...groups.workflows.flatMap((section) => [...section.active, ...section.finished]),
230 ]);
232​
233/** The run to show when none was picked: the first that waits on a person, else one under way. */
234export function defaultWorkflowRunId(groups: WorkflowRunGroups): string | null {
235 const waiting = flattenWorkflowRunNodes(groups.needsYou).find(
236 (node) => node.questions.length > 0 || node.run.status === "paused",
237 );
238 const rest = groups.workflows;
239 return (
240 waiting?.run.runId ??
241 rest.find((section) => section.active.length > 0)?.active[0]?.run.runId ??
242 rest
243 .flatMap((section) => section.finished)
244 .slice()
245 .sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt))[0]?.run.runId ??
246 null
247 );
249​
250/** What starts a workflow, in words. */
251export function workflowTriggerLine(
252 section: WorkflowSection,
253 resolve: MFunctionType = mFallback,
254): string {
255 if (section.triggers === null) return resolve(msg("No longer registered on this server"));
256 if (section.invokedOnly) return resolve(msg("Runs as part of other workflows"));
257 return section.triggers.length === 0
258 ? resolve(msg("Started by hand"))
259 : resolve(msg("Starts on {triggers}", { triggers: section.triggers.join(", ") }));
261​
262export type WorkflowListTab = "needs-you" | "running" | "all";
263​
264/**
265 * The three lists a person switches between. Each is whole pieces of work, newest change first: a
266 * run that another invoked is reached through that one.
267 */
268export function workflowRunLists(
269 groups: WorkflowRunGroups,
270): Readonly<Record<WorkflowListTab, ReadonlyArray<WorkflowRunNode>>> {
271 const byChange = (nodes: ReadonlyArray<WorkflowRunNode>) =>
272 [...nodes].sort((left, right) => right.run.updatedAt.localeCompare(left.run.updatedAt));
273 const running = groups.workflows.flatMap((section) => section.active);
274 const finished = groups.workflows.flatMap((section) => section.finished);
275 return {
276 "needs-you": byChange(groups.needsYou),
277 running: byChange(running),
278 all: [...byChange(groups.needsYou), ...byChange(running), ...byChange(finished)],
279 };
281​
282/** Whether a run is of this workflow or invoked one, so a workflow that only runs inside others is found. */
283export function workflowRunInvolves(node: WorkflowRunNode, workflow: string): boolean {
284 return (
285 node.run.workflow === workflow ||
286 node.children.some((child) => workflowRunInvolves(child, workflow))
287 );
289​
290/**
291 * The filter value for the questions listed as Other: asked with no kind, or with one their
292 * workflow does not declare. A workflow cannot declare a blank kind.
293 */
294export const WORKFLOW_OTHER_KIND = "";
295​
296export interface WorkflowQuestionKind {
297 /** The kind as its workflow declares it, or `WORKFLOW_OTHER_KIND`. */
298 readonly kind: string;
299 /** What its workflow calls it. Null for Other, which the caller words. */
300 readonly label: string | null;
301 /** How many open questions in these runs are listed under it. */
302 readonly count: number;
304​
305/**
306 * The kind a question of this run is listed under: its own when the run's workflow declares it,
307 * else `WORKFLOW_OTHER_KIND`. The question keeps the kind it was asked with either way.
308 */
309function workflowListedKind(
310 workflows: ReadonlyArray<WorkflowSummary>,
311 node: WorkflowRunNode,
312 question: WorkflowQuestion,
313): string {
314 const declared = workflows.find((workflow) => workflow.name === node.run.workflow)?.asks ?? [];
315 return question.kind !== undefined && declared.some(({ kind }) => kind === question.kind)
316 ? question.kind
317 : WORKFLOW_OTHER_KIND;
319​
320/** The first run among these, or the runs they invoked, that itself asks a question listed under this kind. */
321export function workflowRunAskingKind(
322 workflows: ReadonlyArray<WorkflowSummary>,
323 nodes: ReadonlyArray<WorkflowRunNode>,
324 kind: string,
325): WorkflowRunNode | null {
326 return (
327 flattenWorkflowRunNodes(nodes).find((node) =>
328 node.questions.some((question) => workflowListedKind(workflows, node, question) === kind),
329 ) ?? null
330 );
332​
333/**
334 * The declared kinds of the open questions, in declared order, then Other. `sources` is one per
335 * environment, counted together. `picked` stays listed at zero, so a filter with nothing left
336 * can be undone. Empty when no question is of a declared kind and none is picked.
337 */
338export function workflowQuestionKinds(
339 sources: ReadonlyArray<{
340 readonly workflows: ReadonlyArray<WorkflowSummary>;
341 readonly nodes: ReadonlyArray<WorkflowRunNode>;
342 }>,
343 picked: string | null = null,
344): ReadonlyArray<WorkflowQuestionKind> {
345 const counts = new Map<string, number>();
346 const labels = new Map<string, string>();
347 for (const { workflows, nodes } of sources) {
348 for (const node of flattenWorkflowRunNodes(nodes)) {
349 for (const question of node.questions) {
350 const kind = workflowListedKind(workflows, node, question);
351 counts.set(kind, (counts.get(kind) ?? 0) + 1);
352 }
353 }
354 for (const workflow of workflows) {
355 for (const { kind, label } of workflow.asks ?? []) {
356 if (!labels.has(kind)) labels.set(kind, label);
357 }
358 }
359 }
360 if (picked !== null && !counts.has(picked)) counts.set(picked, 0);
361 const other = counts.get(WORKFLOW_OTHER_KIND);
362 counts.delete(WORKFLOW_OTHER_KIND);
363 if (counts.size === 0 && picked === null) return [];
364 const order = [...new Set([...labels.keys(), ...counts.keys()])];
365 return [
366 ...order.flatMap((kind) => {
367 const count = counts.get(kind);
368 return count === undefined ? [] : [{ kind, label: labels.get(kind) ?? kind, count }];
369 }),
370 ...(other === undefined ? [] : [{ kind: WORKFLOW_OTHER_KIND, label: null, count: other }]),
371 ];
373​
374/** Whether a run, or one it invoked, has an open question listed under this kind. */
375export function workflowRunAsksKind(
376 workflows: ReadonlyArray<WorkflowSummary>,
377 node: WorkflowRunNode,
378 kind: string,
379): boolean {
380 return workflowRunAskingKind(workflows, [node], kind) !== null;
382​
383/** The list to open on: what waits on a person, else what is under way, else everything. */
384export function defaultWorkflowListTab(groups: WorkflowRunGroups): WorkflowListTab {
385 if (groups.needsYou.length > 0) return "needs-you";
386 return groups.workflows.some((section) => section.active.length > 0) ? "running" : "all";
388​
389const CHIP_TONES = 5;
390​
391/** A workflow's mark in the list: two letters and one of a few colours, the same every time. */
392export function workflowChip(name: string): { readonly letters: string; readonly tone: number } {
393 const parts = name.split(/[^\p{L}\p{N}]+/u).filter((part) => part !== "");
394 const letters =
395 parts.length > 1
396 ? `${[...parts[0]!][0]}${[...parts[1]!][0]}`
397 : [...(parts[0] ?? name)].slice(0, 2).join("");
398 let hash = 0;
399 for (const char of name) hash = (hash * 31 + char.codePointAt(0)!) % 9973;
400 return { letters: letters.toUpperCase(), tone: hash % CHIP_TONES };
402​
403export type WorkflowRunTone = "input" | "failed" | "working" | "quiet" | "done";
404​
405/** A run's state as the one word the thread list would use for it. */
406export function workflowRunState(
407 node: WorkflowRunNode,
408 resolve: MFunctionType = mFallback,
409): {
410 readonly word: string;
411 readonly tone: WorkflowRunTone;
412} {
413 const { run } = node;
414 const input = {
415 word: resolve(msg("Needs you", { $context: "workflow run status: it waits on a person" })),
416 tone: "input",
417 } as const;
418 const working = {
419 word: resolve(msg("Working", { $context: "workflow run status" })),
420 tone: "working",
421 } as const;
422 if (node.questions.length > 0) return input;
423 switch (run.status) {
424 case "paused":
425 return {
426 word: resolve(msg("Paused", { $context: "workflow run status" })),
427 tone: "failed",
428 };
429 case "running":
430 return working;
431 case "waiting": {
432 const detail = run.detail ?? "";
433 if (detail.startsWith("agent ")) return working;
434 if (detail.startsWith("sleep ")) {
435 return {
436 word: resolve(msg("Sleeping", { $context: "workflow run status" })),
437 tone: "quiet",
438 };
439 }
440 if (detail.startsWith("queue ")) {
441 return {
442 word: resolve(
443 msg("Queued", { $context: "workflow run status: it waits for a free place" }),
444 ),
445 tone: "quiet",
446 };
447 }
448 // Something below it holds it up; say that, not that it idles.
449 if (node.children.some(needsPerson)) return input;
450 return { word: resolve(msg("Waiting", { $context: "workflow run status" })), tone: "quiet" };
451 }
452 case "completed":
453 return { word: resolve(msg("Done", { $context: "workflow run status" })), tone: "done" };
454 case "stopped":
455 return { word: resolve(msg("Stopped", { $context: "workflow run status" })), tone: "quiet" };
456 case "skipped":
457 return { word: resolve(msg("Skipped", { $context: "workflow run status" })), tone: "quiet" };
458 case "cancelled":
459 return {
460 word: resolve(msg("Cancelled", { $context: "workflow run status" })),
461 tone: "quiet",
462 };
463 }
465​
466const firstLine = (text: string) => text.trim().split("\n", 1)[0]!.trim();
467​
468/** What a run is at right now, as the line under its title. */
469export function workflowRunNow(node: WorkflowRunNode, resolve: MFunctionType = mFallback): string {
470 const { run } = node;
471 const detail = run.detail?.trim() ?? "";
472 const asked = node.questions[0];
473 if (asked !== undefined) {
474 const more = node.questions.length - 1;
475 const question = readWorkflowQuestion(asked).title;
476 return more > 0
477 ? resolve(msg("Asks: {question} and {more} more", { question, more }))
478 : resolve(msg("Asks: {question}", { question }));
479 }
480 const below = flattenWorkflowRunNodes(node.children);
481 const holding = below.find(
482 (child) => child.questions.length > 0 || child.run.status === "paused",
483 );
484 switch (run.status) {
485 case "paused":
486 return detail === "" ? resolve(msg("A step failed")) : firstLine(detail);
487 case "running":
488 return resolve(msg("Running its own steps"));
489 case "waiting":
490 if (holding !== undefined) {
491 return `${holding.run.title}: ${workflowRunNow(holding, resolve)}`;
492 }
493 if (detail.startsWith("agent ")) {
494 return resolve(msg("{step} is working", { step: detail.slice(6) }));
495 }
496 if (detail.startsWith("sleep ")) {
497 return resolve(msg("Sleeping at {step}", { step: detail.slice(6) }));
498 }
499 if (detail.startsWith("queue ")) {
500 return resolve(msg("Queued for {pool}", { pool: detail.slice(6) }));
501 }
502 if (below.some((child) => child.run.endedAt === null)) {
503 const open = below.filter((child) => child.run.endedAt === null);
504 return open.length === 1
505 ? resolve(msg("Runs {run}", { run: open[0]!.run.title }))
506 : resolve(msg("{count} runs under way", { count: open.length }));
507 }
508 return detail === ""
509 ? resolve(msg("Waiting", { $context: "what a workflow run is doing now" }))
510 : resolve(msg("Waiting for {step}", { step: detail }));
511 case "completed": {
512 const line = workflowResultLines(run.result)[0];
513 if (line === undefined) {
514 return resolve(msg("Finished", { $context: "what a workflow run is doing now" }));
515 }
516 return firstLine(line.label === null ? line.value : `${line.label}: ${line.value}`);
517 }
518 case "stopped":
519 case "skipped":
520 case "cancelled":
521 return detail === "" ? resolve(msg("Ended early")) : firstLine(detail);
522 }
524​
525/** A run's result as lines a person can read: a sentence, or the fields of an object. */
526export function workflowResultLines(
527 result: WorkflowRun["result"],
528): ReadonlyArray<{ readonly label: string | null; readonly value: string }> {
529 if (result === null) return [];
530 if (typeof result !== "object") return [{ label: null, value: String(result) }];
531 if (Array.isArray(result)) return [{ label: null, value: JSON.stringify(result) }];
532 return Object.entries(result).map(([label, value]) => ({
533 label,
534 value: typeof value === "string" ? value : JSON.stringify(value),
535 }));
537​
538// A step this short is bookkeeping between the parts of a run that take time.
539const QUICK_STEP_MS = 1_000;
540​
541export interface WorkflowBeat {
542 readonly kind: WorkflowStep["kind"] | "run";
543 readonly name: string;
544 readonly status: WorkflowStep["status"];
545 readonly attempts: number;
546 /** A failure's reason, or when a sleep wakes. */
547 readonly detail: string | null;
548 /** What it produced: a value, an agent's data or reply, the answer to a question. */
549 readonly result: WorkflowStep["result"];
550 /** What an agent said in closing, when its result is data. */
551 readonly said: string | null;
552 /** For a step queued for a place in a pool, how many are ahead of it. */
553 readonly ahead: number | undefined;
554 readonly startMs: number;
555 /** When it ended, or `nowMs` while it is under way. */
556 readonly endMs: number;
557 readonly thread: { readonly threadId: string; readonly environmentId: string | null } | null;
558 /** The run this step invoked and waited for. */
559 readonly childRun: WorkflowRun | null;
560 /** Another beat was under way at the same time. */
561 readonly parallel: boolean;
563​
564export interface WorkflowQuickSteps {
565 readonly kind: "quick";
566 readonly steps: ReadonlyArray<WorkflowStep>;
567 readonly startMs: number;
568 readonly endMs: number;
570​
571export type WorkflowTimelineRow = WorkflowBeat | WorkflowQuickSteps;
572​
573export interface WorkflowTimeline {
574 readonly rows: ReadonlyArray<WorkflowTimelineRow>;
575 readonly startMs: number;
576 readonly endMs: number;
578​
579/**
580 * A run's steps as the story of the run: what took time or involved someone is a beat, and the
581 * quick steps between two beats fold into one row, since a journal of them hides where the run
582 * is. An invoked run takes the place of the two steps that started and awaited it.
583 */
584export function buildWorkflowTimeline(input: {
585 readonly run: Pick<WorkflowRun, "runId" | "startedAt" | "endedAt">;
586 readonly steps: ReadonlyArray<WorkflowStep>;
587 readonly children: ReadonlyArray<WorkflowRun>;
588 readonly nowMs: number;
589}): WorkflowTimeline {
590 const childByStep = new Map(
591 input.children
592 .filter((child) => child.parentRunId === input.run.runId && child.parentStep !== null)
593 .map((child) => [child.parentStep, child] as const),
594 );
595 const startMs = Date.parse(input.run.startedAt);
596 // A caller's clock can be a minute old. Now is never before anything the run has done.
597 const nowMs = Math.max(
598 input.nowMs,
599 startMs,
600 ...input.steps.map((step) => Date.parse(step.endedAt ?? step.startedAt)),
601 );
602 const endMs = input.run.endedAt === null ? nowMs : Date.parse(input.run.endedAt);
603 const rows: WorkflowTimelineRow[] = [];
604 const beats: WorkflowBeat[] = [];
605 let quick: WorkflowStep[] = [];
606 const flush = () => {
607 if (quick.length === 0) return;
608 rows.push({
609 kind: "quick",
610 steps: quick,
611 startMs: Date.parse(quick[0]!.startedAt),
612 endMs: Date.parse(quick.at(-1)!.endedAt ?? quick.at(-1)!.startedAt),
613 });
614 quick = [];
615 };
616 for (const step of input.steps) {
617 // The step that started an invoked run is told by the wait that follows it.
618 if (step.kind === "step" && step.name.endsWith("/start")) {
619 if (childByStep.has(step.name.slice(0, -"/start".length))) continue;
620 }
621 const stepStart = Date.parse(step.startedAt);
622 const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt);
623 const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null;
624 // A place given at once is bookkeeping too; a wait for one is a beat.
625 const isBeat =
626 (step.kind !== "step" && step.kind !== "queue") ||
627 step.status !== "completed" ||
628 step.attempts > 1 ||
629 stepEnd - stepStart >= QUICK_STEP_MS;
630 if (!isBeat) {
631 quick.push(step);
632 continue;
633 }
634 flush();
635 const beat: WorkflowBeat = {
636 kind: childRun === null ? step.kind : "run",
637 name: step.name,
638 status: step.status,
639 attempts: step.attempts,
640 detail: step.detail,
641 result: step.result,
642 said: step.said,
643 ahead: step.ahead,
644 startMs: stepStart,
645 endMs: Math.max(stepStart, stepEnd),
646 thread:
647 step.threadId === null
648 ? null
649 : { threadId: step.threadId, environmentId: step.environmentId },
650 childRun,
651 parallel: false,
652 };
653 beats.push(beat);
654 rows.push(beat);
655 }
656 flush();
657 const overlaps = (left: WorkflowBeat, right: WorkflowBeat) =>
658 left !== right && left.startMs < openEnd(right) && right.startMs < openEnd(left);
659 return {
660 rows: rows.map((row) =>
661 row.kind === "quick"
662 ? row
663 : { ...row, parallel: beats.some((other) => overlaps(row, other)) },
664 ),
665 startMs,
666 endMs: Math.max(endMs, ...beats.map((beat) => beat.endMs), startMs + 1),
667 };
669​
670/** When a beat stops overlapping what starts after it: one still under way never does. */
671const openEnd = (beat: WorkflowBeat) =>
672 beat.status === "running" ? Number.POSITIVE_INFINITY : beat.endMs;
673​
674/** What a person answered a question with, when a step's result is such an answer. */
675export function workflowAnswer(result: WorkflowStep["result"]): {
676 readonly choice: string;
677 readonly reason: string | null;
678 /** The client, tool or agent thread that answered, by name; null on an answer kept before this. */
679 readonly answeredBy: string | null;
680 /** The client session that answered; null for a tool, an agent, or an answer kept before this. */
681 readonly answeredBySession: string | null;
682 readonly answeredAt: string | null;
683} | null {
684 const choice = field(result, "choice");
685 return typeof choice === "string"
686 ? {
687 choice,
688 reason: text(field(result, "reason")),
689 answeredBy: text(field(result, "answeredBy")),
690 answeredBySession: text(field(result, "answeredBySession")),
691 answeredAt: text(field(result, "answeredAt")),
692 }
693 : null;
695​
696/** Who withdrew a question unanswered, and why, when a step's result says so. */
697export function workflowWithdrawal(
698 result: WorkflowStep["result"],
699): { readonly by: string; readonly reason: string | null } | null {
700 const withdrawn = field(result, "withdrawn");
701 const by = field(withdrawn, "by");
702 const reason = field(withdrawn, "reason");
703 return typeof by === "string"
704 ? { by, reason: typeof reason === "string" && reason.trim() !== "" ? reason : null }
705 : null;
707​
708/**
709 * Whether the client whose session on the run's environment is `sessionId` gave `answer`. Decided
710 * by session, never by name: two browsers share "Chrome on Linux" and every phone its app's name.
711 */
712export const isOwnWorkflowAnswer = (
713 answer: { readonly answeredBySession: string | null },
714 sessionId: string | null | undefined,
715): boolean => answer.answeredBySession !== null && answer.answeredBySession === sessionId;
716​
717/** Steps that were under way at the same time, shown side by side. */
718export interface WorkflowTogether {
719 readonly kind: "together";
720 readonly beats: ReadonlyArray<WorkflowBeat>;
722​
723export type WorkflowFeedRow = WorkflowTimelineRow | WorkflowTogether;
724​
725/**
726 * The timeline as it is read: beats that overlapped become one row, so two reviewers at once look
727 * like two reviewers at once and not like one after the other.
728 */
729export function buildWorkflowFeed(timeline: WorkflowTimeline): ReadonlyArray<WorkflowFeedRow> {
730 const rows: WorkflowFeedRow[] = [];
731 let together: WorkflowBeat[] = [];
732 let until = 0;
733 const flush = () => {
734 if (together.length === 1) rows.push(together[0]!);
735 else if (together.length > 1) rows.push({ kind: "together", beats: together });
736 together = [];
737 };
738 for (const row of timeline.rows) {
739 if (row.kind === "quick") {
740 flush();
741 rows.push(row);
742 continue;
743 }
744 if (together.length > 0 && row.parallel && row.startMs < until) {
745 together.push(row);
746 until = Math.max(until, openEnd(row));
747 continue;
748 }
749 flush();
750 together = [row];
751 until = openEnd(row);
752 }
753 flush();
754 return rows;
756​
757/** The steps of a feed that take a place in the run's flow: every beat, in order. */
758const beatsOf = (rows: ReadonlyArray<WorkflowFeedRow>) =>
759 rows.flatMap((row) => (row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row]));
760​
761/**
762 * The step a paused run stopped at: the last that failed, unless the run went on after it, since
763 * then the workflow caught that failure. Null when the run is not paused at a step.
764 */
765export function workflowPausedBeat(
766 rows: ReadonlyArray<WorkflowFeedRow>,
767 status: WorkflowRun["status"],
768): WorkflowBeat | null {
769 if (status !== "paused") return null;
770 const failed = beatsOf(rows).findLast((beat) => beat.status === "failed");
771 if (failed === undefined) return null;
772 const wentOn = rows.some((row) =>
773 row.kind === "together"
774 ? row.beats.some((beat) => beat !== failed && beat.startMs >= failed.endMs)
775 : row !== failed && row.startMs >= failed.endMs,
776 );
777 return wentOn ? null : failed;
779​
780/**
781 * Which part of a run's flow to open on: what waits on a person, then where it failed, then how
782 * it ended, then what is under way. Keys are `step:<name>`, `question:<name>`, `pause` and `end`.
783 */
784export function workflowFlowFocus(input: {
785 readonly rows: ReadonlyArray<WorkflowFeedRow>;
786 readonly status: WorkflowRun["status"];
787 readonly ended: boolean;
788 /** The names of the questions that wait on a person. */
789 readonly questions: ReadonlyArray<string>;
790}): string | null {
791 const beats = beatsOf(input.rows);
792 const asked = input.questions[0];
793 if (asked !== undefined) {
794 const at = beats.find(
795 (beat) =>
796 beat.kind === "ask" && beat.status === "running" && input.questions.includes(beat.name),
797 );
798 return at === undefined ? `question:${asked}` : `step:${at.name}`;
799 }
800 if (input.status === "paused") {
801 const failed = workflowPausedBeat(input.rows, input.status);
802 return failed === null ? "pause" : `step:${failed.name}`;
803 }
804 if (input.ended) return "end";
805 const last = beats.findLast((beat) => beat.status === "running") ?? beats.at(-1);
806 return last === undefined ? null : `step:${last.name}`;
808​
809const FACT_LENGTH = 48;
810const FACTS_SHOWN = 6;
811// A string this long is the agent talking, not a fact about its work.
812const PROSE_LENGTH = 80;
813​
814const words = (key: string) =>
815 key
816 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
817 .replace(/[_-]+/g, " ")
818 .toLowerCase();
819​
820function factValue(value: unknown): string | null {
821 if (typeof value === "boolean") return value ? "yes" : "no";
822 if (typeof value === "number") return String(value);
823 if (typeof value === "string") {
824 const text = value.trim();
825 return text !== "" && text.length <= FACT_LENGTH && !text.includes("\n") ? text : null;
826 }
827 if (Array.isArray(value) && value.length > 0 && value.length <= 4) {
828 const parts = value.map(factValue);
829 const joined = parts.join(", ");
830 return parts.every((part) => part !== null) && joined.length <= FACT_LENGTH ? joined : null;
831 }
832 return null;
834​
835/**
836 * What an agent step has to say for itself: its words, and the short facts of its result. With no
837 * closing words kept, the longest piece of prose in the result stands in for them.
838 */
839export function workflowAgentSummary(beat: Pick<WorkflowBeat, "result" | "said">): {
840 readonly said: string | null;
841 readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>;
842} {
843 const { result } = beat;
844 const kept = beat.said?.trim() ?? "";
845 if (typeof result === "string") {
846 return { said: kept !== "" ? kept : result.trim() === "" ? null : result.trim(), facts: [] };
847 }
848 if (result === null || typeof result !== "object" || Array.isArray(result)) {
849 return { said: kept === "" ? null : kept, facts: [] };
850 }
851 const entries = Object.entries(result);
852 const prose =
853 kept !== ""
854 ? null
855 : (entries
856 .filter(
857 (entry): entry is [string, string] =>
858 typeof entry[1] === "string" && entry[1].trim().length >= PROSE_LENGTH,
859 )
860 .slice()
861 .sort((left, right) => right[1].length - left[1].length)[0] ?? null);
862 return {
863 said: kept !== "" ? kept : (prose?.[1].trim() ?? null),
864 facts: entries
865 .flatMap(([key, value]) => {
866 const text = factValue(value);
867 return text === null ? [] : [{ label: words(key), value: text }];
868 })
869 .slice(0, FACTS_SHOWN),
870 };
872​
873/**
874 * The start of what an agent said, cut where a paragraph ends so no markup is left half open.
875 * Null when all of it fits.
876 */
877export function workflowSaidStart(said: string, limit: number): string | null {
878 if (said.length <= limit) return null;
879 const paragraphs = said.split(/\n{2,}/);
880 let kept = paragraphs[0]!;
881 for (const paragraph of paragraphs.slice(1)) {
882 if (kept.length + paragraph.length + 2 > limit) break;
883 kept = `${kept}\n\n${paragraph}`;
884 }
885 // One paragraph that runs on is cut at a word, which can still split markup but not a word.
886 // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a
887 // surrogate pair.
888 if (kept.length > limit * 2) {
889 const space = kept.lastIndexOf(" ", limit);
890 const before = kept.charCodeAt(limit - 1);
891 const highSurrogateLast = before >= 0xd800 && before <= 0xdbff;
892 const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit;
893 kept = `${kept.slice(0, end)}…`;
894 }
895 return kept === said ? null : kept;
897​
898const decodeIssueAddress = Schema.decodeUnknownOption(WorkflowIssueAddress);
899const decodePullRequestAddress = Schema.decodeUnknownOption(WorkflowPullRequestAddress);
900​
901/** A reference's issue, when it is one and its address reads as one. */
902export function workflowReferenceIssue(reference: WorkflowRunSubject): IssueRef | null {
903 return reference.kind === WorkflowReferenceKind.issue
904 ? Option.getOrNull(decodeIssueAddress(reference.address))
905 : null;
907​
908/** A reference's pull request, when it is one and its address reads as one. */
909export function workflowReferencePullRequest(reference: WorkflowRunSubject): PullRequestRef | null {
910 return reference.kind === WorkflowReferenceKind.pullRequest
911 ? Option.getOrNull(decodePullRequestAddress(reference.address))
912 : null;
914​
915/** A reference's thread, when it is one, in the run's own environment. */
916export function workflowReferenceThreadId(reference: WorkflowRunSubject): string | null {
917 const threadId = field(reference.address, "threadId");
918 return reference.kind === WorkflowReferenceKind.thread && typeof threadId === "string"
919 ? threadId
920 : null;
922​
923/**
924 * What a reference is called in a chip: `#412` for an issue or pull request on a git host, a
925 * tracker's own key such as `ENG-12`, and otherwise the title, or the host of its web address.
926 */
927export function workflowReferenceLabel(reference: WorkflowRunSubject): string {
928 const pullRequest = workflowReferencePullRequest(reference);
929 if (pullRequest !== null) return `#${pullRequest.number}`;
930 const issue = workflowReferenceIssue(reference);
931 if (issue !== null) return /^\d+$/.test(issue.key) ? `#${issue.key}` : issue.key;
932 if (reference.title !== "") return reference.title;
933 if (reference.url !== null && URL.canParse(reference.url)) return new URL(reference.url).host;
934 return reference.kind;
936​
937/** The references a step touched, in the order the run first touched them. */
938export function workflowStepReferences(
939 references: ReadonlyArray<WorkflowRunReference>,
940 step: string,
941): ReadonlyArray<WorkflowRunReference> {
942 return references.filter((reference) => reference.steps.includes(step));
944​
945/** A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. */
946export function workflowStepTime(ms: number): string {
947 if (ms < 9_950 && ms % 1000 !== 0) return `${(Math.max(ms, 100) / 1000).toFixed(1)}s`;
948 const seconds = Math.round(ms / 1000);
949 if (seconds < 60) return `${seconds}s`;
950 return formatDuration(ms);
952​
953/**
954 * The first sentence of a reply, as one line of plain text: a heading, list mark, inline code,
955 * emphasis or link reads as its words. Code keeps its text, and an underscore inside a word, as in
956 * snake_case, is not emphasis.
957 */
958export function workflowOneLine(text: string): string {
959 const line =
960 text
961 .split("\n")
962 .map((candidate) => candidate.trim())
963 .find((candidate) => candidate !== "" && !/^(#|```|\|)/.test(candidate))
964 ?.replace(/^([-*>]|\d+\.)\s+/, "") ?? "";
965 const code: string[] = [];
966 const plain = line
967 .replace(/(`+)(.+?)\1(?!`)/g, (_, _ticks, inner: string) => `\0${code.push(inner) - 1}\0`)
968 .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
969 .replace(/(?<![\p{L}\p{M}\p{N}_/])(__|_)(\S(?:.*?\S)?)\1(?![\p{L}\p{M}\p{N}_/])/gu, "$2")
970 .replace(/(\*\*|\*)(\S(?:.*?\S)?)\1/g, "$2")
971 .replace(/\0(\d+)\0/g, (match, index: string) => code[Number(index)] ?? match);
972 const end = plain.search(/[.!?](\s|$)/);
973 return end === -1 ? plain : plain.slice(0, end + 1);