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

workflows.ts

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