@jive-sh/workflow-platform 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,82 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { BpmnModdle } from "bpmn-moddle"
3
+ import { enterShape, layOutBpmn, leaveShape } from "./layout"
4
+
5
+ /** A small workflow in the compiler's BPMN format, with no positions: a merge, a step, a decision and two end states. */
6
+ const bpmn = `<?xml version="1.0" encoding="UTF-8"?>
7
+ <bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:jive="https://jive.sh/schema/workflow/1" id="defs" targetNamespace="https://jive.sh/workflows">
8
+ <bpmn:process id="checkIt" name="Check it" isExecutable="true">
9
+ <bpmn:startEvent id="arrives" name="an item arrives" jive:kind="task"><bpmn:outgoing>toBackInLine</bpmn:outgoing></bpmn:startEvent>
10
+ <bpmn:exclusiveGateway id="backInLine" name="back in line"><bpmn:incoming>toBackInLine</bpmn:incoming><bpmn:incoming>again</bpmn:incoming><bpmn:outgoing>toCheck</bpmn:outgoing></bpmn:exclusiveGateway>
11
+ <bpmn:serviceTask id="check" name="Check" jive:kind="agent" jive:export="check"><bpmn:incoming>toCheck</bpmn:incoming><bpmn:outgoing>toChecked</bpmn:outgoing></bpmn:serviceTask>
12
+ <bpmn:exclusiveGateway id="checked" name="Check ended" jive:ends="check"><bpmn:incoming>toChecked</bpmn:incoming><bpmn:outgoing>passed</bpmn:outgoing><bpmn:outgoing>again</bpmn:outgoing><bpmn:outgoing>failed</bpmn:outgoing></bpmn:exclusiveGateway>
13
+ <bpmn:endEvent id="endPassed" name="passed" jive:end="passed"><bpmn:incoming>passed</bpmn:incoming></bpmn:endEvent>
14
+ <bpmn:endEvent id="endFailed" name="failed" jive:end="failed"><bpmn:incoming>failed</bpmn:incoming></bpmn:endEvent>
15
+ <bpmn:sequenceFlow id="toBackInLine" sourceRef="arrives" targetRef="backInLine" />
16
+ <bpmn:sequenceFlow id="toCheck" sourceRef="backInLine" targetRef="check" />
17
+ <bpmn:sequenceFlow id="toChecked" sourceRef="check" targetRef="checked" />
18
+ <bpmn:sequenceFlow id="passed" name="passed" sourceRef="checked" targetRef="endPassed" />
19
+ <bpmn:sequenceFlow id="again" name="try again" sourceRef="checked" targetRef="backInLine" />
20
+ <bpmn:sequenceFlow id="failed" name="failed" sourceRef="checked" targetRef="endFailed" />
21
+ </bpmn:process>
22
+ </bpmn:definitions>`
23
+
24
+ interface Di {
25
+ readonly bpmnElement: { readonly id: string }
26
+ readonly bounds?: { readonly x: number; readonly y: number; readonly width: number; readonly height: number }
27
+ readonly waypoint?: ReadonlyArray<{ readonly x: number; readonly y: number }>
28
+ readonly label?: { readonly bounds: { readonly x: number; readonly y: number } }
29
+ }
30
+
31
+ const diagramOf = async (xml: string): Promise<ReadonlyMap<string, Di>> => {
32
+ const parsed = await new BpmnModdle().fromXML(xml)
33
+ const definitions = parsed.rootElement as unknown as { diagrams: ReadonlyArray<{ plane: { planeElement: ReadonlyArray<Di> } }> }
34
+ return new Map(definitions.diagrams[0]!.plane.planeElement.map((di) => [di.bpmnElement.id, di]))
35
+ }
36
+
37
+ describe("laying out a workflow's BPMN", () => {
38
+ test("gives every element a shape and every line a route, top to bottom", async () => {
39
+ const laid = await layOutBpmn(bpmn)
40
+ expect(laid).toMatchObject({ shapes: 6, lines: 6 })
41
+ const di = await diagramOf(laid.xml)
42
+ for (const id of ["arrives", "backInLine", "check", "checked", "endPassed", "endFailed"]) expect(di.get(id)?.bounds).toBeDefined()
43
+ for (const id of ["toBackInLine", "toCheck", "toChecked", "passed", "again", "failed"]) expect(di.get(id)?.waypoint?.length).toBeGreaterThanOrEqual(2)
44
+ expect(di.get("check")!.bounds!.y).toBeGreaterThan(di.get("arrives")!.bounds!.y)
45
+ })
46
+
47
+ test("draws a decision and a merge as small diamonds, and puts the decision's question above it", async () => {
48
+ const di = await diagramOf((await layOutBpmn(bpmn)).xml)
49
+ expect(di.get("checked")!.bounds).toMatchObject({ width: 34, height: 34 })
50
+ expect(di.get("backInLine")!.bounds).toMatchObject({ width: 26, height: 26 })
51
+ expect(di.get("checked")!.label!.bounds.y).toBeLessThan(di.get("checked")!.bounds!.y)
52
+ expect(di.get("backInLine")!.label).toBeUndefined()
53
+ })
54
+
55
+ test("refuses a document with no process", async () => {
56
+ const empty = `<?xml version="1.0" encoding="UTF-8"?><bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL" id="d" targetNamespace="x"></bpmn:definitions>`
57
+ await expect(layOutBpmn(empty)).rejects.toThrow("no process")
58
+ })
59
+ })
60
+
61
+ describe("re-attaching a line to the drawn shape inside its wider box", () => {
62
+ const shape = { centreX: 100, centreY: 50, halfWidth: 17, top: 33, bottom: 67 }
63
+
64
+ test("a line leaving well off to one side leaves from that side's corner", () => {
65
+ expect(leaveShape([{ x: 160, y: 67 }, { x: 160, y: 120 }], shape)).toEqual([{ x: 117, y: 50 }, { x: 160, y: 50 }, { x: 160, y: 120 }])
66
+ })
67
+
68
+ test("a line leaving a little off the middle leaves from the bottom middle and bends back", () => {
69
+ expect(leaveShape([{ x: 108, y: 67 }, { x: 108, y: 120 }], shape)).toEqual([
70
+ { x: 100, y: 67 },
71
+ { x: 100, y: 93.5 },
72
+ { x: 108, y: 93.5 },
73
+ { x: 108, y: 120 },
74
+ ])
75
+ })
76
+
77
+ test("a line already at the middle is left alone, and a line's end enters the top middle the same way", () => {
78
+ const straight = [{ x: 100, y: 67 }, { x: 100, y: 120 }]
79
+ expect(leaveShape(straight, shape)).toBe(straight)
80
+ expect(enterShape([{ x: 108, y: 0 }, { x: 108, y: 33 }], shape).at(-1)).toEqual({ x: 100, y: 33 })
81
+ })
82
+ })
@@ -0,0 +1,168 @@
1
+ /// <reference path="./bpmn-moddle.d.ts" />
2
+ // Lays a BPMN workflow out top to bottom with ELK's layered algorithm and orthogonal lines, like a UML activity diagram,
3
+ // and writes the result into the document's BPMN DI (shape bounds, line waypoints, label bounds). It runs in the browser
4
+ // when a view opens, so a workflow's .bpmn needs no layout of its own.
5
+ import { BpmnModdle } from "bpmn-moddle"
6
+ import ELK, { type ElkExtendedEdge, type ElkNode } from "elkjs/lib/elk.bundled.js"
7
+ import { nodeShape, textWidth, type NodeShape } from "./shapes"
8
+
9
+ interface BpmnElement {
10
+ readonly $type: string
11
+ readonly id: string
12
+ readonly name?: string
13
+ readonly incoming?: ReadonlyArray<BpmnElement>
14
+ readonly outgoing?: ReadonlyArray<BpmnElement>
15
+ readonly sourceRef?: BpmnElement
16
+ readonly targetRef?: BpmnElement
17
+ readonly loopCharacteristics?: unknown
18
+ readonly flowElements?: ReadonlyArray<BpmnElement>
19
+ }
20
+
21
+ const LABEL_HEIGHT = 16
22
+
23
+ const layoutOptions: Record<string, string> = {
24
+ "elk.algorithm": "layered",
25
+ "elk.direction": "DOWN",
26
+ "elk.edgeRouting": "ORTHOGONAL",
27
+ "elk.layered.feedbackEdges": "true",
28
+ // The file's order decides which line goes against the flow, such as a loop back to an earlier step.
29
+ "elk.layered.cycleBreaking.strategy": "MODEL_ORDER",
30
+ "elk.layered.considerModelOrder.strategy": "NODES_AND_EDGES",
31
+ "elk.layered.nodePlacement.strategy": "NETWORK_SIMPLEX",
32
+ "elk.layered.spacing.nodeNodeBetweenLayers": "44",
33
+ // Room beside each box for its badge, which ELK doesn't know about.
34
+ "elk.spacing.nodeNode": "96",
35
+ "elk.spacing.edgeNode": "20",
36
+ "elk.spacing.edgeEdge": "14",
37
+ "elk.spacing.edgeLabel": "4",
38
+ "elk.spacing.componentComponent": "70",
39
+ "elk.layered.edgeLabels.sideSelection": "SMART_DOWN",
40
+ "elk.padding": "[top=20,left=20,bottom=20,right=20]",
41
+ }
42
+
43
+ /** The ELK box of one element: one with its name beside it is wide enough for the name on both sides, so the shape stays at the box's centre, where ELK attaches lines. */
44
+ const elkBox = (shape: NodeShape): { readonly width: number; readonly height: number } =>
45
+ shape.labelBeside === null ? { width: shape.width, height: shape.height } : { width: shape.width + 2 * (8 + shape.labelBeside), height: shape.height }
46
+
47
+ export type Point = { readonly x: number; readonly y: number }
48
+ /** Where a drawn shape sits inside its ELK box: its middle, and its top and bottom. */
49
+ export interface Placed {
50
+ readonly centreX: number
51
+ readonly centreY: number
52
+ readonly halfWidth: number
53
+ readonly top: number
54
+ readonly bottom: number
55
+ }
56
+
57
+ /**
58
+ * ELK attaches lines anywhere along a box, and the box of an element with its name beside it is wider than its shape.
59
+ * So a line that leaves such a box away from its middle is moved to leave the shape itself: from its bottom middle, or
60
+ * its side when it leaves sideways at mid-height, with one bend to rejoin ELK's route.
61
+ */
62
+ export const leaveShape = (points: ReadonlyArray<Point>, shape: Placed): ReadonlyArray<Point> => {
63
+ const [first, second] = points
64
+ if (first === undefined || second === undefined || Math.abs(first.x - shape.centreX) < 1) return points
65
+ const leavesSideways = Math.abs(first.y - shape.centreY) < 1
66
+ if (leavesSideways) return [{ x: shape.centreX + Math.sign(first.x - shape.centreX) * shape.halfWidth, y: first.y }, ...points.slice(1)]
67
+ // A branch heading off to one side leaves from that side's corner, as a UML decision's branches do, so two branches
68
+ // never share the bottom point and each keeps clear of the other's label.
69
+ if (Math.abs(first.x - shape.centreX) > shape.halfWidth) {
70
+ const corner = { x: shape.centreX + Math.sign(first.x - shape.centreX) * shape.halfWidth, y: shape.centreY }
71
+ return [corner, { x: first.x, y: shape.centreY }, ...points.slice(1)]
72
+ }
73
+ if (points.length === 2) {
74
+ const middle = (first.y + second.y) / 2
75
+ return [{ x: shape.centreX, y: shape.bottom }, { x: shape.centreX, y: middle }, { x: second.x, y: middle }, second]
76
+ }
77
+ return [{ x: shape.centreX, y: shape.bottom }, { x: shape.centreX, y: second.y }, ...points.slice(2)]
78
+ }
79
+
80
+ /** The same at the line's end: into the shape's top middle, or its side. */
81
+ export const enterShape = (points: ReadonlyArray<Point>, shape: Placed): ReadonlyArray<Point> =>
82
+ [...leaveShape([...points].reverse(), { ...shape, bottom: shape.top })].reverse()
83
+
84
+ /** A workflow's BPMN, laid out: the document with its diagram (DI) replaced, and how many shapes and lines it drew. */
85
+ export interface LaidOut {
86
+ readonly xml: string
87
+ readonly shapes: number
88
+ readonly lines: number
89
+ }
90
+
91
+ /** Lays out the first process of `xml` and returns the document with that layout as its only diagram. */
92
+ export const layOutBpmn = async (xml: string): Promise<LaidOut> => {
93
+ const moddle = new BpmnModdle()
94
+ const parsed = await moddle.fromXML(xml)
95
+ const definitions = parsed.rootElement as unknown as { rootElements?: ReadonlyArray<BpmnElement>; diagrams: Array<unknown> }
96
+ const process = (definitions.rootElements ?? []).find((element) => element.$type === "bpmn:Process")
97
+ if (process === undefined) throw new Error("the BPMN document has no process")
98
+ const elements = process.flowElements ?? []
99
+ const nodes = elements.filter((element) => element.$type !== "bpmn:SequenceFlow")
100
+ const flows = elements.filter((element) => element.$type === "bpmn:SequenceFlow")
101
+ const shapes = new Map(nodes.map((node) => [node.id, nodeShape(node)]))
102
+
103
+ const graph: ElkNode = {
104
+ id: process.id,
105
+ layoutOptions,
106
+ children: nodes.map((node) => ({ id: node.id, ...elkBox(shapes.get(node.id)!) })),
107
+ edges: flows.map(
108
+ (flow): ElkExtendedEdge => ({
109
+ id: flow.id,
110
+ sources: [flow.sourceRef!.id],
111
+ targets: [flow.targetRef!.id],
112
+ labels: flow.name === undefined ? [] : [{ id: `${flow.id}_label`, text: flow.name, width: textWidth(flow.name, 11) + 6, height: LABEL_HEIGHT }],
113
+ }),
114
+ ),
115
+ }
116
+ const laid = await new ELK().layout(graph)
117
+
118
+ const bounds = (x: number, y: number, width: number, height: number) =>
119
+ moddle.create("dc:Bounds", { x: Math.round(x), y: Math.round(y), width: Math.round(width), height: Math.round(height) })
120
+ const byId = new Map(elements.map((element) => [element.id, element]))
121
+ const planeElements: Array<unknown> = []
122
+ const placed = new Map<string, Placed>()
123
+ for (const child of laid.children ?? []) {
124
+ const shape = shapes.get(child.id)!
125
+ const shapeX = (child.x ?? 0) + ((child.width ?? 0) - shape.width) / 2
126
+ const y = child.y ?? 0
127
+ placed.set(child.id, { centreX: shapeX + shape.width / 2, centreY: y + shape.height / 2, halfWidth: shape.width / 2, top: y, bottom: y + shape.height })
128
+ // An event's name sits level with it; a decision's question sits above its right corner, clear of the branch leaving that corner.
129
+ const label =
130
+ shape.labelBeside === null
131
+ ? undefined
132
+ : shape.kind === "decision"
133
+ ? bounds(shapeX + shape.width * 0.75, y - LABEL_HEIGHT, shape.labelBeside, LABEL_HEIGHT)
134
+ : bounds(shapeX + shape.width + 8, y + (shape.height - LABEL_HEIGHT) / 2, shape.labelBeside, LABEL_HEIGHT)
135
+ planeElements.push(
136
+ moddle.create("bpmndi:BPMNShape", {
137
+ id: `${child.id}_di`,
138
+ bpmnElement: byId.get(child.id),
139
+ bounds: bounds(shapeX, y, shape.width, shape.height),
140
+ ...(label === undefined ? {} : { label: moddle.create("bpmndi:BPMNLabel", { bounds: label }) }),
141
+ }),
142
+ )
143
+ }
144
+ for (const edge of (laid.edges ?? []) as ReadonlyArray<ElkExtendedEdge>) {
145
+ const section = edge.sections?.[0]
146
+ if (section === undefined) continue
147
+ const routed = [section.startPoint, ...(section.bendPoints ?? []), section.endPoint]
148
+ const from = placed.get(edge.sources[0] ?? "")
149
+ const to = placed.get(edge.targets[0] ?? "")
150
+ const leaving = from === undefined ? routed : leaveShape(routed, from)
151
+ const points = to === undefined ? leaving : enterShape(leaving, to)
152
+ const label = edge.labels?.[0]
153
+ planeElements.push(
154
+ moddle.create("bpmndi:BPMNEdge", {
155
+ id: `${edge.id}_di`,
156
+ bpmnElement: byId.get(edge.id),
157
+ waypoint: points.map((point) => moddle.create("dc:Point", { x: Math.round(point.x), y: Math.round(point.y) })),
158
+ ...(label === undefined || label.x === undefined || label.y === undefined
159
+ ? {}
160
+ : { label: moddle.create("bpmndi:BPMNLabel", { bounds: bounds(label.x, label.y, label.width ?? 0, label.height ?? 0) }) }),
161
+ }),
162
+ )
163
+ }
164
+ const plane = moddle.create("bpmndi:BPMNPlane", { id: `${process.id}_plane`, bpmnElement: process, planeElement: planeElements })
165
+ definitions.diagrams = [moddle.create("bpmndi:BPMNDiagram", { id: `${process.id}_diagram`, plane })]
166
+ const written = await moddle.toXML(definitions as never, { format: true })
167
+ return { xml: written.xml, shapes: laid.children?.length ?? 0, lines: laid.edges?.length ?? 0 }
168
+ }
@@ -0,0 +1,334 @@
1
+ // A live view of one workflow: its diagram with the selected metric on every step, queue and end state, a pie of that
2
+ // metric across its steps, and a panel for the clicked step or line. Everything shown is read from the workforce's
3
+ // queries, and the view follows the workflow's counts as they change.
4
+ import type { ConvexClient } from "convex/browser"
5
+ import type { DefaultFunctionArgs, FunctionArgs, FunctionReference, FunctionReturnType } from "convex/server"
6
+ import type { TaskFile, WorkflowGraph } from "../src/graph"
7
+ import { figuresOf, linesInto, METRICS, type Metric, spendsTokens, type StepStatsResult, tasksOnLine, tokensOf, type Waits, waitsOf, type WorkflowCounts } from "./figures"
8
+ import { layOutBpmn } from "./layout"
9
+ import { escape, linePanel, type PlaceTasks, type StepRun, type StepRuns, stepPanel } from "./panel"
10
+ import { type DiagramShape, platformLinesByFlow, type PlatformLine } from "./places"
11
+ import { drawWorkflow, type PanelSource } from "./view"
12
+ import { accessWords, dollars, workflowWords } from "./words"
13
+
14
+ type Query<Args extends DefaultFunctionArgs, Result> = FunctionReference<"query", "public", Args, Result>
15
+
16
+ type Place = { readonly line: string } | { readonly step: string } | { readonly inFrontOf: string } | { readonly end: string }
17
+
18
+ /** A task at a place, as the workforce's `tasksAt` returns it. */
19
+ export interface TaskRow {
20
+ readonly task: string
21
+ readonly fields: Readonly<Record<string, unknown>>
22
+ readonly enteredAt: number
23
+ readonly note?: string
24
+ readonly run?: { readonly worker?: string; readonly call: number }
25
+ }
26
+
27
+ interface Page<Row> {
28
+ readonly page: ReadonlyArray<Row>
29
+ readonly isDone: boolean
30
+ readonly continueCursor: string
31
+ }
32
+
33
+ /** One run from the workforce's `stepRuns`, newest started first. */
34
+ export interface StepRunRow {
35
+ readonly task: string
36
+ readonly call: number
37
+ readonly endedAt?: number
38
+ readonly endState?: string
39
+ readonly error?: string
40
+ readonly agent?: string
41
+ readonly spend: StepStatsResult["spend"]
42
+ readonly transcripts: ReadonlyArray<TaskFile>
43
+ }
44
+
45
+ /** The workforce's public queries the view reads, as the app exports them (`api.workforce` in a Convex app). */
46
+ export interface WorkforceQueries {
47
+ readonly workflow: Query<{ workflow: string }, { readonly graph: WorkflowGraph; readonly version: string } | null>
48
+ readonly counts: Query<{ workflow: string }, WorkflowCounts>
49
+ readonly tasksAt: Query<{ workflow: string; place: Place; paginationOpts: { numItems: number; cursor: string | null } }, Page<TaskRow>>
50
+ readonly stepStats: Query<{ workflow: string; step: string; since: number }, StepStatsResult>
51
+ readonly stepRuns: Query<{ workflow: string; step: string; paginationOpts: { numItems: number; cursor: string | null } }, Page<StepRunRow>>
52
+ readonly task: Query<{ workflow: string; task: string }, { readonly fields: Readonly<Record<string, unknown>> } | null>
53
+ }
54
+
55
+ /** Where the view goes on the page. */
56
+ export interface ViewElements {
57
+ readonly canvas: HTMLElement
58
+ readonly panel: HTMLElement
59
+ /** The metric dropdown; filled by the view. */
60
+ readonly picker: HTMLSelectElement
61
+ readonly pie: HTMLElement
62
+ }
63
+
64
+ export interface WorkflowViewOptions {
65
+ readonly client: ConvexClient
66
+ readonly queries: WorkforceQueries
67
+ /** The workflow's registered name. */
68
+ readonly workflow: string
69
+ /** The workflow's BPMN, with the compiler's jive: attributes; it is laid out when the view opens. */
70
+ readonly bpmn: string
71
+ readonly elements: ViewElements
72
+ readonly dark: boolean
73
+ /** A task's name in the panel, from its fields; its id when absent or when this gives nothing. */
74
+ readonly taskName?: (fields: Readonly<Record<string, unknown>>) => string | undefined
75
+ /** Where a transcript can be opened from this page; null when it can't. */
76
+ readonly fileHref?: (file: TaskFile) => string | null
77
+ /** The organization's own worker services in words, beside the platform's. */
78
+ readonly serviceWords?: Readonly<Record<string, string>>
79
+ }
80
+
81
+ /** How many tasks of a place the panel lists; the rest are counted. */
82
+ const PAGE = 20
83
+ /** How many finished runs a step's panel lists. */
84
+ const RUNS = 6
85
+ /** How many times the view tries a query that failed, such as one a busy backend timed out. A query changes nothing, so trying again is safe. */
86
+ const QUERY_TRIES = 4
87
+
88
+ export interface WorkflowView {
89
+ /** What the view drew, in words: import warnings, and any workflow line the diagram has no path for. */
90
+ readonly summary: string
91
+ readonly selectMetric: (metric: Metric) => void
92
+ readonly openStep: (step: string) => void
93
+ readonly destroy: () => void
94
+ }
95
+
96
+ export const mountWorkflowView = async (options: WorkflowViewOptions): Promise<WorkflowView> => {
97
+ const { client, queries, workflow } = options
98
+ const query = async <Ref extends FunctionReference<"query">>(ref: Ref, args: FunctionArgs<Ref>): Promise<FunctionReturnType<Ref>> => {
99
+ for (let attempt = 1; ; attempt++) {
100
+ try {
101
+ return await client.query(ref, args)
102
+ } catch (cause) {
103
+ if (attempt >= QUERY_TRIES) throw cause
104
+ await new Promise((resolve) => setTimeout(resolve, 400 * attempt))
105
+ }
106
+ }
107
+ }
108
+ const graphOf = async (name: string) => {
109
+ const registered = await query(queries.workflow, { workflow: name })
110
+ if (registered === null) throw new Error(`the workflow ${name} is not registered`)
111
+ return registered
112
+ }
113
+ const pageAt = (name: string, place: Place, cursor: string | null, numItems: number) =>
114
+ query(queries.tasksAt, { workflow: name, place, paginationOpts: { numItems, cursor } })
115
+ const nameOf = (fields: Readonly<Record<string, unknown>>, id: string) => options.taskName?.(fields) ?? id
116
+ const hrefOf = options.fileHref ?? (() => null)
117
+
118
+ const running = await graphOf(workflow)
119
+ const graph = running.graph
120
+ const innerGraphs = new Map<string, WorkflowGraph>()
121
+ for (const step of graph.steps) if (step.workflow !== undefined) innerGraphs.set(step.workflow.name, (await graphOf(step.workflow.name)).graph)
122
+ let latest: WorkflowCounts = await query(queries.counts, { workflow })
123
+
124
+ const laidOut = await layOutBpmn(options.bpmn)
125
+ let shapes: ReadonlyArray<DiagramShape> = []
126
+ let linesByFlow: ReadonlyMap<string, ReadonlyArray<PlatformLine>> = new Map()
127
+ const stepName = (step: string) =>
128
+ shapes.find((shape) => shape.businessObject.$attrs?.["jive:export"] === step && shape.type !== "bpmn:Process")?.businessObject.name ?? workflowWords(step)
129
+ const lineWords = (line: PlatformLine): string => {
130
+ const from = line.from
131
+ const start =
132
+ "event" in from
133
+ ? `the event ${graph.events.find((event) => event.id === from.event)?.kind ?? from.event}`
134
+ : "step" in from
135
+ ? `${stepName(from.step)} ending "${from.endState}"`
136
+ : `the end state "${from.end}"`
137
+ return `from ${start} to ${"step" in line.to ? stepName(line.to.step) : `the end state "${line.to.end}"`}`
138
+ }
139
+
140
+ const placeTasks = (total: number, rows: ReadonlyArray<TaskRow>): PlaceTasks => ({
141
+ total,
142
+ tasks: rows.map((row) => ({
143
+ name: nameOf(row.fields, row.task),
144
+ enteredAt: row.enteredAt,
145
+ lastNote: row.note ?? null,
146
+ ...(row.run !== undefined ? { detail: `${row.run.worker === undefined ? "run by the workforce" : `run by ${row.run.worker}`}, try ${row.run.call}` } : {}),
147
+ })),
148
+ })
149
+
150
+ /** The latest finished runs of `step`, newest first. A sub-workflow step's agent runs are its inner workflow's. */
151
+ const runsOf = async (name: string, stepGraph: WorkflowGraph, step: string): Promise<StepRuns> => {
152
+ const graphStep = stepGraph.steps.find((each) => each.id === step)
153
+ if (graphStep?.workflow !== undefined) {
154
+ const innerName = graphStep.workflow.name
155
+ const inner = innerGraphs.get(innerName)
156
+ if (inner === undefined) return { runs: [], from: `The ${workflowWords(innerName)} workflow is not registered.` }
157
+ const each = await Promise.all(inner.steps.filter((one) => one.kind === "agent").map((agentStep) => runsOf(innerName, inner, agentStep.id)))
158
+ return {
159
+ runs: each.flatMap((one) => one.runs).sort((a, b) => b.endedAt - a.endedAt).slice(0, RUNS),
160
+ from: `The runs of the agent steps inside the ${workflowWords(innerName)} workflow, which this step hands its tasks to.`,
161
+ }
162
+ }
163
+ // Newest started first; a run still going has no end yet, so a page a little larger than the list is read.
164
+ const page = await query(queries.stepRuns, { workflow: name, step, paginationOpts: { numItems: RUNS * 3, cursor: null } })
165
+ const finished = page.page.filter((run) => run.endedAt !== undefined).slice(0, RUNS)
166
+ const spends = graphStep?.kind === "agent"
167
+ const runs: Array<StepRun> = []
168
+ for (const run of finished) {
169
+ // Only the task's id comes with a run; its record gives the name.
170
+ const record = await query(queries.task, { workflow: name, task: run.task })
171
+ runs.push({
172
+ taskName: record === null ? run.task : nameOf(record.fields, run.task),
173
+ call: run.call,
174
+ endedAt: run.endedAt!,
175
+ endState: run.endState ?? null,
176
+ error: run.error ?? null,
177
+ agent: run.agent ?? null,
178
+ tokens: spends ? tokensOf(run.spend) : null,
179
+ costUsd: spends ? run.spend.costUsd : null,
180
+ transcripts: run.transcripts.map((file) => ({ name: file.name, href: hrefOf(file) })),
181
+ })
182
+ }
183
+ return { runs, from: "The step's latest runs that have finished, newest first." }
184
+ }
185
+
186
+ /** How long the tasks in front of `step` have waited, over every page of its queue. */
187
+ const waitsInFrontOf = async (step: string): Promise<Waits | undefined> => {
188
+ const entered: Array<number> = []
189
+ let cursor: string | null = null
190
+ for (;;) {
191
+ const page: Page<TaskRow> = await pageAt(workflow, { inFrontOf: step }, cursor, 100)
192
+ entered.push(...page.page.map((row) => row.enteredAt))
193
+ if (page.isDone) break
194
+ cursor = page.continueCursor
195
+ }
196
+ return waitsOf(entered, Date.now())
197
+ }
198
+ const statsOf = (step: string) => query(queries.stepStats, { workflow, step, since: 0 })
199
+
200
+ const source: PanelSource = {
201
+ step: async ({ step, name }) => {
202
+ const graphStep = graph.steps.find((each) => each.id === step)
203
+ const [page, stats] = await Promise.all([pageAt(workflow, { step }, null, PAGE), statsOf(step)])
204
+ const total = latest.steps.find((each) => each.step === step)?.tasks ?? page.page.length
205
+ const extra: Array<string> = graphStep === undefined ? [] : [...accessWords(graphStep, options.serviceWords)]
206
+ const notes: Array<string> = []
207
+ if (graphStep?.workflow !== undefined) {
208
+ // A sub-workflow step's tasks wait and are worked on inside the sub-workflow.
209
+ const inner = await query(queries.counts, { workflow: graphStep.workflow.name })
210
+ const waiting = inner.lines.reduce((sum, line) => sum + line.tasks, 0)
211
+ const working = inner.steps.reduce((sum, each) => sum + each.tasks, 0)
212
+ extra.push(`Inside the ${name} workflow: ${waiting} waiting on its lines, ${working} being worked on in its steps.`)
213
+ notes.push(`Spend is the ${name} workflow's, for the tasks this step started there.`)
214
+ }
215
+ const spends = graphStep !== undefined && spendsTokens(graphStep, innerGraphs)
216
+ const spend = stats.spend
217
+ const runs = await runsOf(workflow, graph, step).catch((cause): StepRuns => ({ runs: [], from: `Could not read the runs: ${String(cause)}` }))
218
+ return stepPanel({
219
+ name,
220
+ place: placeTasks(total, page.page),
221
+ stats: {
222
+ calls: stats.calls,
223
+ tokens: spends ? { input: spend.fresh + spend.cacheWrite + spend.cacheRead, output: spend.output } : null,
224
+ timePerTaskMs: { median: stats.perTask.wallSeconds.median * 1000, p90: stats.perTask.wallSeconds.p90 * 1000 },
225
+ endStates: stats.endStates.map((end) => ({ end: end.endState, runs: end.runs })),
226
+ over: "all runs so far",
227
+ notes: [...notes, ...(spends ? [`Cost: ${dollars(spend.costUsd)}.`] : []), "Time per task counts the tasks whose runs here have all finished."],
228
+ },
229
+ now: Date.now(),
230
+ extra,
231
+ runs,
232
+ })
233
+ },
234
+ line: async ({ flowId, into, from }) => {
235
+ const carried = linesByFlow.get(flowId) ?? []
236
+ const queues = carried.filter((line) => "step" in line.to)
237
+ const target = queues[0]?.to
238
+ // A drawn line carrying a step's whole queue is paged as that queue, in the order the step takes it.
239
+ const wholeQueue =
240
+ target !== undefined &&
241
+ "step" in target &&
242
+ queues.every((line) => "step" in line.to && line.to.step === target.step) &&
243
+ queues.length === linesInto(graph, target.step).length
244
+ const rows = wholeQueue
245
+ ? (await pageAt(workflow, { inFrontOf: target.step }, null, PAGE)).page
246
+ : (await Promise.all(queues.map((line) => pageAt(workflow, { line: line.id }, null, PAGE))))
247
+ .flatMap((page) => page.page)
248
+ .sort((a, b) => a.enteredAt - b.enteredAt)
249
+ .slice(0, PAGE)
250
+ const total = queues.reduce((sum, line) => sum + tasksOnLine(latest, line.id), 0)
251
+ const extra =
252
+ carried.length > 1
253
+ ? [`This line carries ${carried.length} of the workflow's lines: ${carried.map((line) => `${lineWords(line)} (${tasksOnLine(latest, line.id)} waiting)`).join("; ")}.`]
254
+ : []
255
+ return linePanel({ into, from, place: placeTasks(total, rows), now: Date.now(), extra })
256
+ },
257
+ }
258
+
259
+ const drawn = await drawWorkflow({ xml: laidOut.xml, canvas: options.elements.canvas, panel: options.elements.panel, dark: options.dark, source })
260
+ shapes = drawn.elements() as ReadonlyArray<DiagramShape>
261
+ const places = platformLinesByFlow({ shapes, graph })
262
+ linesByFlow = places.byFlow
263
+
264
+ const { picker, pie } = options.elements
265
+ pie.classList.add("jive-pie-box")
266
+ let metric: Metric = "tasks"
267
+ let reading = false
268
+ let again = false
269
+ /** Reads the selected metric again; a change that lands while it reads is read once more after. */
270
+ const refresh = async (): Promise<void> => {
271
+ if (reading) {
272
+ again = true
273
+ return
274
+ }
275
+ reading = true
276
+ try {
277
+ const needsStats = metric !== "tasks"
278
+ const stats = new Map(needsStats ? await Promise.all(graph.steps.map(async (step) => [step.id, await statsOf(step.id)] as const)) : [])
279
+ const waits = new Map<string, Waits>()
280
+ if (metric === "time")
281
+ for (const step of graph.steps) {
282
+ const found = await waitsInFrontOf(step.id)
283
+ if (found !== undefined) waits.set(step.id, found)
284
+ }
285
+ const figures = figuresOf({ metric, graph, innerGraphs, counts: latest, stats, waits, stepName, dark: options.dark })
286
+ drawn.setBadges(figures.badges)
287
+ pie.innerHTML = figures.pie
288
+ } catch (cause) {
289
+ // The badges keep their last figures; the pie says the read failed rather than showing old numbers as new.
290
+ pie.innerHTML = `<h3>Could not read ${metric} from the workflow platform</h3><p class="jive-empty">${escape(String(cause))}</p>`
291
+ } finally {
292
+ reading = false
293
+ }
294
+ if (again) {
295
+ again = false
296
+ await refresh()
297
+ }
298
+ }
299
+ picker.innerHTML = METRICS.map((each) => `<option value="${each.metric}">${each.label}</option>`).join("")
300
+ const onPick = () => {
301
+ metric = METRICS.find((each) => each.metric === picker.value)?.metric ?? "tasks"
302
+ void refresh()
303
+ }
304
+ picker.addEventListener("change", onPick)
305
+ const onSlice = (event: Event) => {
306
+ const step = (event.target as Element | null)?.closest("[data-step]")?.getAttribute("data-step")
307
+ if (step !== null && step !== undefined) drawn.openStep(step)
308
+ }
309
+ pie.addEventListener("click", onSlice)
310
+ await refresh()
311
+ const unsubscribe = client.onUpdate(queries.counts, { workflow }, (counts) => {
312
+ latest = counts
313
+ void refresh()
314
+ drawn.refreshPanel()
315
+ })
316
+
317
+ const warnings = drawn.importWarnings.length === 0 ? "no import warnings" : `import warnings: ${drawn.importWarnings.join(" | ")}`
318
+ const undrawn = places.undrawn.length === 0 ? "every workflow line is drawn" : `workflow lines with no drawn path: ${places.undrawn.join(", ")}`
319
+ return {
320
+ summary: `${laidOut.shapes} shapes, ${laidOut.lines} lines; ${warnings}; ${undrawn}; version ${running.version}`,
321
+ selectMetric: (next) => {
322
+ picker.value = next
323
+ onPick()
324
+ },
325
+ openStep: drawn.openStep,
326
+ destroy: () => {
327
+ unsubscribe()
328
+ picker.removeEventListener("change", onPick)
329
+ pie.removeEventListener("click", onSlice)
330
+ drawn.destroy()
331
+ },
332
+ }
333
+ }
334
+
@@ -0,0 +1,72 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { linePanel, stepPanel, type StepRun } from "./panel"
3
+
4
+ const now = Date.UTC(2026, 10, 28, 23, 0)
5
+ const run = (input: Partial<StepRun>): StepRun => ({
6
+ taskName: "FUN_0045C350",
7
+ call: 1,
8
+ endedAt: now - 90_000,
9
+ endState: "found something new",
10
+ error: null,
11
+ agent: "claude-opus",
12
+ tokens: 55_064,
13
+ costUsd: 0.07,
14
+ transcripts: [{ name: "transcript.jsonl", href: "/files/abc/transcript.jsonl" }],
15
+ ...input,
16
+ })
17
+
18
+ describe("a step's panel", () => {
19
+ const panel = (runs: ReadonlyArray<StepRun>) =>
20
+ stepPanel({
21
+ name: "Learn from blocked",
22
+ place: { total: 3, tasks: [{ name: "FUN_1", enteredAt: now - 13_000, lastNote: null, detail: "run by worker-5, try 1" }] },
23
+ stats: { calls: 10, tokens: { input: 435_072, output: 17_671 }, timePerTaskMs: { median: 10_000, p90: 11_000 }, endStates: [{ end: "nothing new", runs: 5 }], over: "all runs so far" },
24
+ now,
25
+ extra: ["Can use: agents."],
26
+ runs: { runs, from: "The step's latest runs that have finished, newest first." },
27
+ })
28
+
29
+ test("lists its tasks, the rest counted, with its access and stats", () => {
30
+ const html = panel([])
31
+ expect(html).toContain("3 tasks in this step")
32
+ expect(html).toContain("in it 13 s")
33
+ expect(html).toContain("and 2 more, in queue order")
34
+ expect(html).toContain("Can use: agents.")
35
+ expect(html).toContain("452,743 tokens (435,072 in, 17,671 out)")
36
+ expect(html).toContain("nothing new: 5 runs")
37
+ expect(html).toContain("No finished run yet.")
38
+ })
39
+
40
+ test("lists each finished run with its end state, agent, tokens, cost and a link to its transcript", () => {
41
+ const html = panel([run({})])
42
+ expect(html).toContain("FUN_0045C350, try 1")
43
+ expect(html).toContain("1 min 30 s ago")
44
+ expect(html).toContain('ended "found something new"; agent: claude-opus; 55,064 tokens, $0.07')
45
+ expect(html).toContain('<a href="/files/abc/transcript.jsonl" target="_blank" rel="noopener">Open transcript (transcript.jsonl)</a>')
46
+ })
47
+
48
+ test("says why a run failed, when a code step spends nothing, and when a transcript can't be opened from the page", () => {
49
+ const html = panel([run({ error: "lease expired", endState: null, agent: null, tokens: null, costUsd: null, transcripts: [{ name: "transcript.jsonl", href: null }] })])
50
+ expect(html).toContain("failed: lease expired; agent: not recorded; no agent, so no tokens or cost")
51
+ expect(html).toContain("Transcript (transcript.jsonl): not reachable from this page")
52
+ expect(html).not.toContain("<a ")
53
+ })
54
+
55
+ test("escapes what tasks and notes say", () => {
56
+ const html = stepPanel({ name: "<Step>", place: { total: 1, tasks: [{ name: "a", enteredAt: now, lastNote: "<script>" }] }, stats: undefined, now })
57
+ expect(html).toContain("Step: &lt;Step&gt;")
58
+ expect(html).toContain("Last note: &lt;script&gt;")
59
+ expect(html).not.toContain("<script>")
60
+ })
61
+ })
62
+
63
+ describe("a line's panel", () => {
64
+ test("lists the queue oldest first with each task's place in it", () => {
65
+ const html = linePanel({ into: "Decompile", from: "the merge", place: { total: 1, tasks: [{ name: "FUN_2", enteredAt: now - 7_000, lastNote: "came back" }] }, now })
66
+ expect(html).toContain("Queue into Decompile")
67
+ expect(html).toContain("1 task waiting, oldest first")
68
+ expect(html).toContain("1. FUN_2")
69
+ expect(html).toContain("waiting 7 s")
70
+ expect(html).toContain("Last note: came back")
71
+ })
72
+ })