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 ? `${parts[0]![0]}${parts[1]![0]}` : (parts[0] ?? name).slice(0, 2);
262 let hash = 0;
263 for (const char of name) hash = (hash * 31 + char.codePointAt(0)!) % 9973;
264 return { letters: letters.toUpperCase(), tone: hash % CHIP_TONES };
265}
266
267export type WorkflowRunTone = "input" | "failed" | "working" | "quiet" | "done";
268
269/** A run's state as the one word the thread list would use for it. */
270export function workflowRunState(
271 node: WorkflowRunNode,
272 resolve: MFunctionType = mFallback,
273): {
274 readonly word: string;
275 readonly tone: WorkflowRunTone;
276} {
277 const { run } = node;
278 const input = {
279 word: resolve(msg("Needs you", { $context: "workflow run status: it waits on a person" })),
280 tone: "input",
281 } as const;
282 const working = {
283 word: resolve(msg("Working", { $context: "workflow run status" })),
284 tone: "working",
285 } as const;
286 if (node.questions.length > 0) return input;
287 switch (run.status) {
288 case "paused":
289 return {
290 word: resolve(msg("Paused", { $context: "workflow run status" })),
291 tone: "failed",
292 };
293 case "running":
294 return working;
295 case "waiting": {
296 const detail = run.detail ?? "";
297 if (detail.startsWith("agent ")) return working;
298 if (detail.startsWith("sleep ")) {
299 return {
300 word: resolve(msg("Sleeping", { $context: "workflow run status" })),
301 tone: "quiet",
302 };
303 }
304 // Something below it holds it up; say that, not that it idles.
305 if (node.children.some(needsPerson)) return input;
306 return { word: resolve(msg("Waiting", { $context: "workflow run status" })), tone: "quiet" };
307 }
308 case "completed":
309 return { word: resolve(msg("Done", { $context: "workflow run status" })), tone: "done" };
310 case "stopped":
311 return { word: resolve(msg("Stopped", { $context: "workflow run status" })), tone: "quiet" };
312 case "skipped":
313 return { word: resolve(msg("Skipped", { $context: "workflow run status" })), tone: "quiet" };
314 case "cancelled":
315 return {
316 word: resolve(msg("Cancelled", { $context: "workflow run status" })),
317 tone: "quiet",
318 };
319 }
320}
321
322const firstLine = (text: string) => text.trim().split("\n", 1)[0]!.trim();
323
324/** What a run is at right now, as the line under its title. */
325export function workflowRunNow(node: WorkflowRunNode, resolve: MFunctionType = mFallback): string {
326 const { run } = node;
327 const detail = run.detail?.trim() ?? "";
328 const asked = node.questions[0];
329 if (asked !== undefined) {
330 const more = node.questions.length - 1;
331 const question = readWorkflowQuestion(asked).title;
332 return more > 0
333 ? resolve(msg("Asks: {question} and {more} more", { question, more }))
334 : resolve(msg("Asks: {question}", { question }));
335 }
336 const below = flattenWorkflowRunNodes(node.children);
337 const holding = below.find(
338 (child) => child.questions.length > 0 || child.run.status === "paused",
339 );
340 switch (run.status) {
341 case "paused":
342 return detail === "" ? resolve(msg("A step failed")) : firstLine(detail);
343 case "running":
344 return resolve(msg("Running its own steps"));
345 case "waiting":
346 if (holding !== undefined) {
347 return `${holding.run.title}: ${workflowRunNow(holding, resolve)}`;
348 }
349 if (detail.startsWith("agent ")) {
350 return resolve(msg("{step} is working", { step: detail.slice(6) }));
351 }
352 if (detail.startsWith("sleep ")) {
353 return resolve(msg("Sleeping at {step}", { step: detail.slice(6) }));
354 }
355 if (below.some((child) => child.run.endedAt === null)) {
356 const open = below.filter((child) => child.run.endedAt === null);
357 return open.length === 1
358 ? resolve(msg("Runs {run}", { run: open[0]!.run.title }))
359 : resolve(msg("{count} runs under way", { count: open.length }));
360 }
361 return detail === ""
362 ? resolve(msg("Waiting", { $context: "what a workflow run is doing now" }))
363 : resolve(msg("Waiting for {step}", { step: detail }));
364 case "completed": {
365 const line = workflowResultLines(run.result)[0];
366 if (line === undefined) {
367 return resolve(msg("Finished", { $context: "what a workflow run is doing now" }));
368 }
369 return firstLine(line.label === null ? line.value : `${line.label}: ${line.value}`);
370 }
371 case "stopped":
372 case "skipped":
373 case "cancelled":
374 return detail === "" ? resolve(msg("Ended early")) : firstLine(detail);
375 }
376}
377
378/** A run's result as lines a person can read: a sentence, or the fields of an object. */
379export function workflowResultLines(
380 result: WorkflowRun["result"],
381): ReadonlyArray<{ readonly label: string | null; readonly value: string }> {
382 if (result === null) return [];
383 if (typeof result !== "object") return [{ label: null, value: String(result) }];
384 if (Array.isArray(result)) return [{ label: null, value: JSON.stringify(result) }];
385 return Object.entries(result).map(([label, value]) => ({
386 label,
387 value: typeof value === "string" ? value : JSON.stringify(value),
388 }));
389}
390
391// A step this short is bookkeeping between the parts of a run that take time.
392const QUICK_STEP_MS = 1_000;
393
394export interface WorkflowBeat {
395 readonly kind: WorkflowStep["kind"] | "run";
396 readonly name: string;
397 readonly status: WorkflowStep["status"];
398 readonly attempts: number;
399 /** A failure's reason, or when a sleep wakes. */
400 readonly detail: string | null;
401 /** What it produced: a value, an agent's data or reply, the answer to a question. */
402 readonly result: WorkflowStep["result"];
403 /** What an agent said in closing, when its result is data. */
404 readonly said: string | null;
405 readonly startMs: number;
406 /** When it ended, or `nowMs` while it is under way. */
407 readonly endMs: number;
408 readonly thread: { readonly threadId: string; readonly environmentId: string | null } | null;
409 /** The run this step invoked and waited for. */
410 readonly childRun: WorkflowRun | null;
411 /** Another beat was under way at the same time. */
412 readonly parallel: boolean;
413}
414
415export interface WorkflowQuickSteps {
416 readonly kind: "quick";
417 readonly steps: ReadonlyArray<WorkflowStep>;
418 readonly startMs: number;
419 readonly endMs: number;
420}
421
422export type WorkflowTimelineRow = WorkflowBeat | WorkflowQuickSteps;
423
424export interface WorkflowTimeline {
425 readonly rows: ReadonlyArray<WorkflowTimelineRow>;
426 readonly startMs: number;
427 readonly endMs: number;
428}
429
430/**
431 * A run's steps as the story of the run: what took time or involved someone is a beat, and the
432 * quick steps between two beats fold into one row, since a journal of them hides where the run
433 * is. An invoked run takes the place of the two steps that started and awaited it.
434 */
435export function buildWorkflowTimeline(input: {
436 readonly run: Pick<WorkflowRun, "runId" | "startedAt" | "endedAt">;
437 readonly steps: ReadonlyArray<WorkflowStep>;
438 readonly children: ReadonlyArray<WorkflowRun>;
439 readonly nowMs: number;
440}): WorkflowTimeline {
441 const childByStep = new Map(
442 input.children
443 .filter((child) => child.parentRunId === input.run.runId && child.parentStep !== null)
444 .map((child) => [child.parentStep, child] as const),
445 );
446 const startMs = Date.parse(input.run.startedAt);
447 // A caller's clock can be a minute old. Now is never before anything the run has done.
448 const nowMs = Math.max(
449 input.nowMs,
450 startMs,
451 ...input.steps.map((step) => Date.parse(step.endedAt ?? step.startedAt)),
452 );
453 const endMs = input.run.endedAt === null ? nowMs : Date.parse(input.run.endedAt);
454 const rows: WorkflowTimelineRow[] = [];
455 const beats: WorkflowBeat[] = [];
456 let quick: WorkflowStep[] = [];
457 const flush = () => {
458 if (quick.length === 0) return;
459 rows.push({
460 kind: "quick",
461 steps: quick,
462 startMs: Date.parse(quick[0]!.startedAt),
463 endMs: Date.parse(quick.at(-1)!.endedAt ?? quick.at(-1)!.startedAt),
464 });
465 quick = [];
466 };
467 for (const step of input.steps) {
468 // The step that started an invoked run is told by the wait that follows it.
469 if (step.kind === "step" && step.name.endsWith("/start")) {
470 if (childByStep.has(step.name.slice(0, -"/start".length))) continue;
471 }
472 const stepStart = Date.parse(step.startedAt);
473 const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt);
474 const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null;
475 const isBeat =
476 step.kind !== "step" ||
477 step.status !== "completed" ||
478 step.attempts > 1 ||
479 stepEnd - stepStart >= QUICK_STEP_MS;
480 if (!isBeat) {
481 quick.push(step);
482 continue;
483 }
484 flush();
485 const beat: WorkflowBeat = {
486 kind: childRun === null ? step.kind : "run",
487 name: step.name,
488 status: step.status,
489 attempts: step.attempts,
490 detail: step.detail,
491 result: step.result,
492 said: step.said,
493 startMs: stepStart,
494 endMs: Math.max(stepStart, stepEnd),
495 thread:
496 step.threadId === null
497 ? null
498 : { threadId: step.threadId, environmentId: step.environmentId },
499 childRun,
500 parallel: false,
501 };
502 beats.push(beat);
503 rows.push(beat);
504 }
505 flush();
506 const overlaps = (left: WorkflowBeat, right: WorkflowBeat) =>
507 left !== right && left.startMs < openEnd(right) && right.startMs < openEnd(left);
508 return {
509 rows: rows.map((row) =>
510 row.kind === "quick"
511 ? row
512 : { ...row, parallel: beats.some((other) => overlaps(row, other)) },
513 ),
514 startMs,
515 endMs: Math.max(endMs, ...beats.map((beat) => beat.endMs), startMs + 1),
516 };
517}
518
519/** When a beat stops overlapping what starts after it: one still under way never does. */
520const openEnd = (beat: WorkflowBeat) =>
521 beat.status === "running" ? Number.POSITIVE_INFINITY : beat.endMs;
522
523/** What a person answered a question with, when a step's result is such an answer. */
524export function workflowAnswer(
525 result: WorkflowStep["result"],
526): { readonly choice: string; readonly reason: string | null } | null {
527 const choice = field(result, "choice");
528 const reason = field(result, "reason");
529 return typeof choice === "string"
530 ? { choice, reason: typeof reason === "string" && reason.trim() !== "" ? reason : null }
531 : null;
532}
533
534/** Steps that were under way at the same time, shown side by side. */
535export interface WorkflowTogether {
536 readonly kind: "together";
537 readonly beats: ReadonlyArray<WorkflowBeat>;
538}
539
540export type WorkflowFeedRow = WorkflowTimelineRow | WorkflowTogether;
541
542/**
543 * The timeline as it is read: beats that overlapped become one row, so two reviewers at once look
544 * like two reviewers at once and not like one after the other.
545 */
546export function buildWorkflowFeed(timeline: WorkflowTimeline): ReadonlyArray<WorkflowFeedRow> {
547 const rows: WorkflowFeedRow[] = [];
548 let together: WorkflowBeat[] = [];
549 let until = 0;
550 const flush = () => {
551 if (together.length === 1) rows.push(together[0]!);
552 else if (together.length > 1) rows.push({ kind: "together", beats: together });
553 together = [];
554 };
555 for (const row of timeline.rows) {
556 if (row.kind === "quick") {
557 flush();
558 rows.push(row);
559 continue;
560 }
561 if (together.length > 0 && row.parallel && row.startMs < until) {
562 together.push(row);
563 until = Math.max(until, openEnd(row));
564 continue;
565 }
566 flush();
567 together = [row];
568 until = openEnd(row);
569 }
570 flush();
571 return rows;
572}
573
574/** The steps of a feed that take a place in the run's flow: every beat, in order. */
575const beatsOf = (rows: ReadonlyArray<WorkflowFeedRow>) =>
576 rows.flatMap((row) => (row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row]));
577
578/**
579 * The step a paused run stopped at: the last that failed, unless the run went on after it, since
580 * then the workflow caught that failure. Null when the run is not paused at a step.
581 */
582export function workflowPausedBeat(
583 rows: ReadonlyArray<WorkflowFeedRow>,
584 status: WorkflowRun["status"],
585): WorkflowBeat | null {
586 if (status !== "paused") return null;
587 const failed = beatsOf(rows).findLast((beat) => beat.status === "failed");
588 if (failed === undefined) return null;
589 const wentOn = rows.some((row) =>
590 row.kind === "together"
591 ? row.beats.some((beat) => beat !== failed && beat.startMs >= failed.endMs)
592 : row !== failed && row.startMs >= failed.endMs,
593 );
594 return wentOn ? null : failed;
595}
596
597/**
598 * Which part of a run's flow to open on: what waits on a person, then where it failed, then how
599 * it ended, then what is under way. Keys are `step:<name>`, `question:<name>`, `pause` and `end`.
600 */
601export function workflowFlowFocus(input: {
602 readonly rows: ReadonlyArray<WorkflowFeedRow>;
603 readonly status: WorkflowRun["status"];
604 readonly ended: boolean;
605 /** The names of the questions that wait on a person. */
606 readonly questions: ReadonlyArray<string>;
607}): string | null {
608 const beats = beatsOf(input.rows);
609 const asked = input.questions[0];
610 if (asked !== undefined) {
611 const at = beats.find(
612 (beat) =>
613 beat.kind === "ask" && beat.status === "running" && input.questions.includes(beat.name),
614 );
615 return at === undefined ? `question:${asked}` : `step:${at.name}`;
616 }
617 if (input.status === "paused") {
618 const failed = workflowPausedBeat(input.rows, input.status);
619 return failed === null ? "pause" : `step:${failed.name}`;
620 }
621 if (input.ended) return "end";
622 const last = beats.findLast((beat) => beat.status === "running") ?? beats.at(-1);
623 return last === undefined ? null : `step:${last.name}`;
624}
625
626const FACT_LENGTH = 48;
627const FACTS_SHOWN = 6;
628// A string this long is the agent talking, not a fact about its work.
629const PROSE_LENGTH = 80;
630
631const words = (key: string) =>
632 key
633 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
634 .replace(/[_-]+/g, " ")
635 .toLowerCase();
636
637function factValue(value: unknown): string | null {
638 if (typeof value === "boolean") return value ? "yes" : "no";
639 if (typeof value === "number") return String(value);
640 if (typeof value === "string") {
641 const text = value.trim();
642 return text !== "" && text.length <= FACT_LENGTH && !text.includes("\n") ? text : null;
643 }
644 if (Array.isArray(value) && value.length > 0 && value.length <= 4) {
645 const parts = value.map(factValue);
646 const joined = parts.join(", ");
647 return parts.every((part) => part !== null) && joined.length <= FACT_LENGTH ? joined : null;
648 }
649 return null;
650}
651
652/**
653 * What an agent step has to say for itself: its words, and the short facts of its result. With no
654 * closing words kept, the longest piece of prose in the result stands in for them.
655 */
656export function workflowAgentSummary(beat: Pick<WorkflowBeat, "result" | "said">): {
657 readonly said: string | null;
658 readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>;
659} {
660 const { result } = beat;
661 const kept = beat.said?.trim() ?? "";
662 if (typeof result === "string") {
663 return { said: kept !== "" ? kept : result.trim() === "" ? null : result.trim(), facts: [] };
664 }
665 if (result === null || typeof result !== "object" || Array.isArray(result)) {
666 return { said: kept === "" ? null : kept, facts: [] };
667 }
668 const entries = Object.entries(result);
669 const prose =
670 kept !== ""
671 ? null
672 : (entries
673 .filter(
674 (entry): entry is [string, string] =>
675 typeof entry[1] === "string" && entry[1].trim().length >= PROSE_LENGTH,
676 )
677 .slice()
678 .sort((left, right) => right[1].length - left[1].length)[0] ?? null);
679 return {
680 said: kept !== "" ? kept : (prose?.[1].trim() ?? null),
681 facts: entries
682 .flatMap(([key, value]) => {
683 const text = factValue(value);
684 return text === null ? [] : [{ label: words(key), value: text }];
685 })
686 .slice(0, FACTS_SHOWN),
687 };
688}
689
690/**
691 * The start of what an agent said, cut where a paragraph ends so no markup is left half open.
692 * Null when all of it fits.
693 */
694export function workflowSaidStart(said: string, limit: number): string | null {
695 if (said.length <= limit) return null;
696 const paragraphs = said.split(/\n{2,}/);
697 let kept = paragraphs[0]!;
698 for (const paragraph of paragraphs.slice(1)) {
699 if (kept.length + paragraph.length + 2 > limit) break;
700 kept = `${kept}\n\n${paragraph}`;
701 }
702 // One paragraph that runs on is cut at a word, which can still split markup but not a word.
703 // Text with no space before the limit, such as Chinese, is cut at the limit, never inside a
704 // surrogate pair.
705 if (kept.length > limit * 2) {
706 const space = kept.lastIndexOf(" ", limit);
707 const before = kept.charCodeAt(limit - 1);
708 const highSurrogateLast = before >= 0xd800 && before <= 0xdbff;
709 const end = space > 0 ? space : highSurrogateLast ? limit - 1 : limit;
710 kept = `${kept.slice(0, end)}…`;
711 }
712 return kept === said ? null : kept;
713}
714
715const decodeIssueAddress = Schema.decodeUnknownOption(WorkflowIssueAddress);
716const decodePullRequestAddress = Schema.decodeUnknownOption(WorkflowPullRequestAddress);
717
718/** A reference's issue, when it is one and its address reads as one. */
719export function workflowReferenceIssue(reference: WorkflowRunReference): IssueRef | null {
720 return reference.kind === WorkflowReferenceKind.issue
721 ? Option.getOrNull(decodeIssueAddress(reference.address))
722 : null;
723}
724
725/** A reference's pull request, when it is one and its address reads as one. */
726export function workflowReferencePullRequest(
727 reference: WorkflowRunReference,
728): PullRequestRef | null {
729 return reference.kind === WorkflowReferenceKind.pullRequest
730 ? Option.getOrNull(decodePullRequestAddress(reference.address))
731 : null;
732}
733
734/**
735 * What a reference is called in a chip: `#412` for an issue or pull request on a git host, a
736 * tracker's own key such as `ENG-12`, and the title for a kind this client does not know.
737 */
738export function workflowReferenceLabel(reference: WorkflowRunReference): string {
739 const pullRequest = workflowReferencePullRequest(reference);
740 if (pullRequest !== null) return `#${pullRequest.number}`;
741 const issue = workflowReferenceIssue(reference);
742 if (issue !== null) return /^\d+$/.test(issue.key) ? `#${issue.key}` : issue.key;
743 return reference.title === "" ? reference.kind : reference.title;
744}
745
746/** The references a step touched, in the order the run first touched them. */
747export function workflowStepReferences(
748 references: ReadonlyArray<WorkflowRunReference>,
749 step: string,
750): ReadonlyArray<WorkflowRunReference> {
751 return references.filter((reference) => reference.steps.includes(step));
752}
753
754/** A step's time in one shape down a column: 0.3s, 9.7s, 12s, then minutes. */
755export function workflowStepTime(ms: number): string {
756 if (ms < 10_000 && ms % 1000 !== 0) return `${(Math.max(ms, 100) / 1000).toFixed(1)}s`;
757 if (ms < 60_000) return `${Math.round(ms / 1000)}s`;
758 return formatDuration(ms);
759}
760
761/**
762 * The first sentence of a reply, as one line of plain text: a heading, list mark, inline code,
763 * emphasis or link reads as its words.
764 */
765export function workflowOneLine(text: string): string {
766 const line =
767 text
768 .split("\n")
769 .map((candidate) => candidate.trim())
770 .find((candidate) => candidate !== "" && !/^(#|```|\|)/.test(candidate))
771 ?.replace(/^([-*>]|\d+\.)\s+/, "") ?? "";
772 const plain = line
773 .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
774 .replace(/`([^`]*)`/g, "$1")
775 .replace(/(\*\*|__|\*|_)(\S(?:.*?\S)?)\1/g, "$2");
776 const end = plain.search(/[.!?](\s|$)/);
777 return end === -1 ? plain : plain.slice(0, end + 1);
778}