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