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