@jive-sh/workflow-platform 1.1.0 → 1.3.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.
package/README.md CHANGED
@@ -22,6 +22,7 @@ It ships its source, and three entry points:
22
22
  | `@jive-sh/workflow-platform` | Defining workflows (`Workflow.make`, `TaskSchema.make`), the step services (`AgentRunner`, `FileStore`, `ProgramBuild`, `Tasks`) and the graph types |
23
23
  | `@jive-sh/workflow-platform/component/convex.config.js` | The Convex component a workforce installs once per workflow (`app.use(workflowPlatform, { name })`) |
24
24
  | `@jive-sh/workflow-platform/worker/index.js` | The worker loop (`workOnce`, `workUntilIdle`, `workForever`) and its Convex client |
25
+ | `@jive-sh/workflow-platform/dashboard/index.js` | The workflow views: a workflow's diagram with tasks, time, tokens or cost on every step and queue, a pie of it by step, and a panel of each step's tasks, access, stats and runs with their transcripts ([dashboard/README.md](dashboard/README.md); 1.2.0) |
25
26
 
26
27
  Write `.js` in the import: TypeScript and Convex's bundler both resolve it to the shipped `.ts`. Convex's codegen
27
28
  writes `@jive-sh/workflow-platform/component/_generated/component.js` into an app installing the component, for the
@@ -70,6 +71,12 @@ worker gives a run only what its step lists.
70
71
  (`step.inputsChanged`), retries with a delay and a give-up end state, notes on a task that later steps read, and
71
72
  writes to other tasks (`StepOutcome.others`) in the same transaction as the step's own result. A note written that
72
73
  way carries its writer as `by: { workflow, step, task }` (1.1.0; 1.0.0 put the writer in the note's words).
74
+ - **Sub-workflows (1.3.0):** a child at an end state one of its change events resumes is parked, not done. Its
75
+ parent's step waits on, at no budget cost, and that end is no end of the step, so a parent line out of it is refused.
76
+ `tasksAt` says where each parked child waits, in words (`inside`). `step.workflow({ workflow, returns })` copies
77
+ the named child fields onto the parent as the step ends. To redo a child after its final end, send the parent back
78
+ into its step, from another workflow's step with `others: [{ workflow, taskId, requeue: { event }, note }]`; a child
79
+ re-opened after its parent moved on is kept on the parent as a note.
73
80
  - **Agents:** `AgentRunner` with no tools, a reading mode or a working mode with write scopes, a cached input, and a
74
81
  turn limit; the organization implements it.
75
82
  - **Queues:** requeue with a note, move tasks to the front, an in-progress limit per workflow or per field value (a
@@ -80,6 +87,7 @@ worker gives a run only what its step lists.
80
87
 
81
88
  ## Developing it
82
89
 
83
- `bun run typecheck` checks `src`, `component` and `worker` (`tsconfig.check.json`); `tsconfig.json` is the library
84
- abstract's one line, which its build uses for `src`. `bun test src worker` runs the unit tests. The end-to-end tests
85
- run in an organization package against a local anonymous Convex deployment.
90
+ `bun run typecheck` checks `src`, `component` and `worker` (`tsconfig.check.json`), and `dashboard` with the DOM
91
+ (`tsconfig.dashboard.json`); `tsconfig.json` is the library abstract's one line, which its build uses for `src`.
92
+ `bun run test` runs the unit tests of `src`, `worker` and `dashboard`. The end-to-end tests run in an organization
93
+ package against a local anonymous Convex deployment.
@@ -328,7 +328,14 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
328
328
  subWorkflowTaskEnded: FunctionReference<
329
329
  "mutation",
330
330
  "internal",
331
- { endState: string; entryIndex: number; fields: any; flow: string },
331
+ {
332
+ endState: string;
333
+ entryIndex: number;
334
+ fields: any;
335
+ flow: string;
336
+ task: string;
337
+ workflow: string;
338
+ },
332
339
  null,
333
340
  Name
334
341
  >;
@@ -352,6 +359,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
352
359
  fields?: any;
353
360
  files?: Array<{ name: string; ref: string }>;
354
361
  note: string;
362
+ requeue?: { event: string };
355
363
  task: string;
356
364
  },
357
365
  null | string,
@@ -546,6 +554,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
546
554
  collect?: { endState: string; into: string };
547
555
  each?: string;
548
556
  name: string;
557
+ returns?: Array<string>;
549
558
  };
550
559
  }>;
551
560
  };
@@ -600,6 +609,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
600
609
  collect?: { endState: string; into: string };
601
610
  each?: string;
602
611
  name: string;
612
+ returns?: Array<string>;
603
613
  };
604
614
  }>;
605
615
  };
@@ -206,9 +206,23 @@ export const subWorkflowTaskEnded = function* (input: {
206
206
  readonly entryIndex: number
207
207
  readonly endState: string
208
208
  readonly fields: unknown
209
+ /** The sub-workflow task that ended, and its workflow. */
210
+ readonly task: string
211
+ readonly workflow: string
209
212
  }): Run<void> {
210
213
  const store = yield* WorkflowStore
211
- const parentFlow = yield* flowWithId(input.flow)
214
+ const maybeParentFlow = yield* store.getFlow(input.flow)
215
+ // A child re-opened after its parent's step took its end, such as one requeued after it matched, is no longer that
216
+ // step's: its parent has moved on (a send-back requeues the parent instead), so its end is kept on the parent as a note.
217
+ const entry = Option.isNone(maybeParentFlow) ? undefined : (yield* store.subWorkflowTasksOf(maybeParentFlow.value._id)).find((row) => row.entryIndex === input.entryIndex)
218
+ if (Option.isNone(maybeParentFlow) || entry === undefined || entry.task !== input.task) {
219
+ const parentTask = Option.isNone(maybeParentFlow) ? Option.none() : yield* store.getTask(maybeParentFlow.value.task)
220
+ if (Option.isSome(parentTask)) {
221
+ yield* store.insertTaskNote({ task: parentTask.value._id, note: `${input.workflow} task ${input.task} ended again, "${input.endState}", after this task had moved on` })
222
+ }
223
+ return
224
+ }
225
+ const parentFlow = maybeParentFlow.value
212
226
  const parentWorkflow = yield* workflowNamed(parentFlow.workflow)
213
227
  const maybeStep = stepOfPlace(parentFlow.place)
214
228
  if (Option.isNone(maybeStep)) return yield* Effect.die(new Error(`flow ${parentFlow._id} waits on sub-workflow tasks but is at ${parentFlow.place}`))
@@ -231,6 +245,14 @@ export const subWorkflowTaskEnded = function* (input: {
231
245
 
232
246
  const subWorkflowTasks = yield* store.subWorkflowTasksOf(parentFlow._id)
233
247
  if (subWorkflowTasks.some((subWorkflowTask) => subWorkflowTask.endedAs === undefined)) return
248
+ // The child's fields its parent asked for come back onto the parent as the step ends, starting its change events.
249
+ const returned = subWorkflow.returns ?? []
250
+ if (subWorkflow.each === undefined && returned.length > 0 && typeof input.fields === "object" && input.fields !== null) {
251
+ const childFields = input.fields as Record<string, unknown>
252
+ const parentTask = yield* taskWithId(parentFlow.task)
253
+ const fields = { ...parentTask.fields, ...Object.fromEntries(returned.filter((field) => field in childFields).map((field) => [field, childFields[field]])) }
254
+ yield* changeTask({ workflow: parentWorkflow, task: parentTask, fields, files: parentTask.files })
255
+ }
234
256
  const endState = subWorkflow.each !== undefined ? everySubWorkflowTaskEnded : input.endState
235
257
  yield* leaveStep({ workflow: parentWorkflow, flow: parentFlow, step, endState, measurements: Option.none(), note: Option.none() })
236
258
  yield* advance(parentWorkflow.name)
@@ -428,18 +450,26 @@ export const requeue = function* (input: {
428
450
  if (inStep !== undefined) return yield* Effect.fail(new TaskInProgress({ task: task._id, step: Option.getOrElse(stepOfPlace(inStep.place), () => "") }))
429
451
  yield* store.insertTaskNote({ task: task._id, note: input.note })
430
452
  if (Option.isSome(input.fields)) yield* changeTask({ workflow, task, fields: input.fields.value, files: task.files })
431
- const ended = (yield* store.flowsOfTask(task._id)).filter(
432
- (flow) => arrivals.some((arrival) => arrival._id === flow._id) && Option.isSome(endStateOfPlace(flow.place)),
453
+ yield* sendBack({ workflow, task: task._id, event: event.id, arrivals })
454
+ yield* advance(workflow.name)
455
+ }
456
+
457
+ /**
458
+ * Moves a task's arrival flows that ended at an end state onto `event`'s line, so the task is taken again from there;
459
+ * one still waiting on a line keeps its place. The caller has checked that no flow of it is in a step.
460
+ */
461
+ const sendBack = function* (input: { readonly workflow: WorkflowRow; readonly task: Id<"tasks">; readonly event: string; readonly arrivals: ReadonlyArray<FlowRow> }): Run<void> {
462
+ const store = yield* WorkflowStore
463
+ const ended = (yield* store.flowsOfTask(input.task)).filter(
464
+ (flow) => input.arrivals.some((arrival) => arrival._id === flow._id) && Option.isSome(endStateOfPlace(flow.place)),
433
465
  )
434
- if (ended.length > 0) {
435
- const line = yield* lineOutOf({ workflow, start: { event: event.id } })
436
- yield* store.markTaskResumed(task._id)
437
- for (const flow of ended) {
438
- const moved = yield* store.moveFlow({ flow: flow._id, place: placeAtEndOf(line), enteredAt: store.now })
439
- yield* afterArriving({ workflow, flow: moved })
440
- }
466
+ if (ended.length === 0) return
467
+ const line = yield* lineOutOf({ workflow: input.workflow, start: { event: input.event } })
468
+ yield* store.markTaskResumed(input.task)
469
+ for (const flow of ended) {
470
+ const moved = yield* store.moveFlow({ flow: flow._id, place: placeAtEndOf(line), enteredAt: store.now })
471
+ yield* afterArriving({ workflow: input.workflow, flow: moved })
441
472
  }
442
- yield* advance(workflow.name)
443
473
  }
444
474
 
445
475
  /**
@@ -622,12 +652,18 @@ export const writeOther = function* (input: {
622
652
  readonly note: string
623
653
  /** The run that wrote it: its workflow, step and task, kept on the note. */
624
654
  readonly by: NoteWriter
655
+ /** A task or request event of the task's workflow to send it back through once written, as `requeue` does. */
656
+ readonly requeue: Option.Option<string>
625
657
  }): Run<Option.Option<string>> {
626
658
  const store = yield* WorkflowStore
627
659
  const task = yield* taskWithId(input.task)
628
660
  const workflow = yield* workflowNamed(task.workflow)
629
661
  const inStep = (yield* store.flowsOfTask(task._id)).find((flow) => Option.isSome(stepOfPlace(flow.place)))
630
662
  if (inStep !== undefined) return Option.some(`it was in step ${Option.getOrElse(stepOfPlace(inStep.place), () => "")} when the run ended`)
663
+ const requeueEvent = Option.getOrUndefined(input.requeue)
664
+ const event = requeueEvent === undefined ? undefined : workflow.graph.events.find((candidate) => candidate.id === requeueEvent && createsTasks(candidate))
665
+ if (requeueEvent !== undefined && event === undefined) return Option.some(`${workflow.name} has no task or request event ${requeueEvent} to send it back through`)
666
+ const arrivals = (yield* store.flowsOfTask(task._id)).filter((flow) => workflow.graph.events.some((candidate) => candidate.id === flow.startedBy && createsTasks(candidate)))
631
667
  yield* store.insertTaskNote({ task: task._id, note: input.note, by: input.by })
632
668
  if (Option.isSome(input.fields) || Option.isSome(input.files)) {
633
669
  yield* changeTask({
@@ -637,6 +673,7 @@ export const writeOther = function* (input: {
637
673
  files: Option.getOrElse(input.files, () => task.files),
638
674
  })
639
675
  }
676
+ if (event !== undefined) yield* sendBack({ workflow, task: task._id, event: event.id, arrivals })
640
677
  yield* advance(workflow.name)
641
678
  return Option.none()
642
679
  }
@@ -156,7 +156,7 @@ export const recordSubWorkflowTask = mutation({
156
156
 
157
157
  /** The workforce relays that a sub-workflow task of a flow waiting here ended, with that task's fields. */
158
158
  export const subWorkflowTaskEnded = mutation({
159
- args: { flow: v.id("flows"), entryIndex: v.number(), endState: v.string(), fields: v.any() },
159
+ args: { flow: v.id("flows"), entryIndex: v.number(), endState: v.string(), fields: v.any(), task: v.string(), workflow: v.string() },
160
160
  returns: v.null(),
161
161
  handler: async (ctx, args) => {
162
162
  await runEngine(ctx, Engine.subWorkflowTaskEnded(args))
@@ -262,14 +262,21 @@ export const find = query({
262
262
  * why the write was skipped, or null once it is applied (`Engine.writeOther`). Fields are already encoded and checked.
263
263
  */
264
264
  export const writeOther = mutation({
265
- args: { task: v.string(), fields: v.optional(v.any()), files: v.optional(v.array(taskFileValidator)), note: v.string(), by: noteWriterValidator },
265
+ args: {
266
+ task: v.string(),
267
+ fields: v.optional(v.any()),
268
+ files: v.optional(v.array(taskFileValidator)),
269
+ note: v.string(),
270
+ by: noteWriterValidator,
271
+ requeue: v.optional(v.object({ event: v.string() })),
272
+ },
266
273
  returns: v.union(v.null(), v.string()),
267
274
  handler: async (ctx, args) => {
268
275
  const task = ctx.db.normalizeId("tasks", args.task)
269
276
  if (task === null) return "there is no such task"
270
277
  const skipped = await runEngine(
271
278
  ctx,
272
- Engine.writeOther({ task, fields: Option.fromNullishOr(args.fields), files: Option.fromNullishOr(args.files), note: args.note, by: args.by }),
279
+ Engine.writeOther({ task, fields: Option.fromNullishOr(args.fields), files: Option.fromNullishOr(args.files), note: args.note, by: args.by, requeue: Option.fromNullishOr(args.requeue?.event) }),
273
280
  )
274
281
  return Option.getOrNull(skipped)
275
282
  },
@@ -0,0 +1,57 @@
1
+ # The workflow views
2
+
3
+ A browser view of one workflow, read live from the workforce's queries:
4
+
5
+ - **The diagram:** the workflow's BPMN, laid out top to bottom when the view opens and drawn like a UML activity
6
+ diagram. Steps are rounded boxes, and an agent step has a robot. A decision is a plain diamond with its question
7
+ beside it and the end-state names on its lines; a merge is a plain diamond.
8
+ - **A metric on every box and queue,** picked in a dropdown:
9
+ - **Tasks** (the default): the tasks in each step, queued in front of it, and ended at each end state.
10
+ - **Time:** each step's median time per task, and how long each queue's tasks have waited (median and longest).
11
+ - **Tokens** and **Cost:** each step's totals, on agent steps and on sub-workflow steps whose workflow has agent
12
+ steps. Code steps and queues get no badge.
13
+ - **A pie** splitting the metric across the steps: at most six slices plus "other steps". Each slice is named with
14
+ its value in words, and every slice is listed with its share. Clicking a slice opens its step's panel.
15
+ - **A panel** for the clicked step, line or badge:
16
+ - **Step:** its tasks (oldest first, with each task's latest note), what it can access, its stats, and its latest
17
+ finished runs. Each run has its end state, agent, tokens, cost and a link to each transcript. A sub-workflow step
18
+ lists the runs of the agent steps inside its workflow.
19
+ - **Line:** its queue, in the order the step takes it, and which of the workflow's lines it carries.
20
+
21
+ Every figure is in words with its unit, so nothing is told apart by colour alone.
22
+
23
+ ## Using it
24
+
25
+ ```sh
26
+ bun add bpmn-js bpmn-moddle diagram-js elkjs tiny-svg
27
+ ```
28
+
29
+ These are optional peer dependencies of `@jive-sh/workflow-platform`; an app that only runs workflows doesn't need
30
+ them. Load bpmn-js's `dist/assets/diagram-js.css` and `dist/assets/bpmn-js.css`, and this folder's `dashboard.css`.
31
+
32
+ ```ts
33
+ import { ConvexClient } from "convex/browser"
34
+ import { mountWorkflowView } from "@jive-sh/workflow-platform/dashboard/index.js"
35
+ import { api } from "../convex/_generated/api"
36
+
37
+ const view = await mountWorkflowView({
38
+ client: new ConvexClient(convexUrl),
39
+ queries: api.workforce, // the workforce functions the app exports
40
+ workflow: "matchAFunction",
41
+ bpmn: matchAFunctionBpmn, // the workflow package's .bpmn
42
+ elements: { canvas, panel, picker, pie }, // a sized element for the diagram, a panel, a <select>, a pie box
43
+ dark: true,
44
+ taskName: (fields) => (typeof fields["address"] === "string" ? fields["address"] : undefined),
45
+ fileHref: (file) => `/files/${file.ref}`, // where the page can open a stored file, such as a transcript
46
+ serviceWords: { DecompRecords: "decomp-service records" }, // the organization's own services, in words
47
+ })
48
+ ```
49
+
50
+ `view.summary` says what was drawn, including any workflow line the diagram has no path for. `view.destroy()` stops
51
+ following the workflow's counts and removes the diagram.
52
+
53
+ The BPMN must carry the compiler's `jive:` attributes (`jive:export` on steps, `jive:kind`, `jive:end` on end
54
+ states, `jive:ends` on decisions). A workflow compiled by `jive-abstract-agentic-workflow` has them.
55
+
56
+ The pure parts are exported too: `layOutBpmn`, `figuresOf`, `platformLinesByFlow`, `stepPanel`, `linePanel`,
57
+ `pieHtml` and the words helpers.
@@ -0,0 +1,93 @@
1
+ // Draws BPMN elements the way a UML activity diagram does, on top of bpmn-js's own renderer: a decision is a plain
2
+ // diamond with no X and its question as a label beside it, a merge is a plain diamond with no label, a step is a thin rounded box that keeps BPMN's
3
+ // own markers (gear, boxed plus, three bars), and an agent step gets a robot.
4
+ import BaseRenderer from 'diagram-js/lib/draw/BaseRenderer';
5
+ import type EventBus from 'diagram-js/lib/core/EventBus';
6
+ import type { ShapeLike } from 'diagram-js/lib/core/Types';
7
+ import { getStrokeColor, getFillColor } from 'bpmn-js/lib/draw/BpmnRenderUtil';
8
+ import { append as svgAppend, attr as svgAttr, create as svgCreate } from 'tiny-svg';
9
+ import { isMerge } from './shapes';
10
+
11
+ /** A drawn element as diagram-js types it: its own fields (type, labelTarget, businessObject) are untyped there. */
12
+ type LookElement = ShapeLike;
13
+
14
+ interface RendererConfig {
15
+ readonly defaultStrokeColor?: string;
16
+ readonly defaultFillColor?: string;
17
+ readonly defaultLabelColor?: string;
18
+ }
19
+
20
+ const STEP_TYPES = new Set(['bpmn:Task', 'bpmn:ServiceTask', 'bpmn:CallActivity', 'bpmn:UserTask', 'bpmn:ScriptTask']);
21
+
22
+ const isGateway = (element: LookElement): boolean => element['type'] === 'bpmn:ExclusiveGateway';
23
+
24
+ /** A decision and a merge are both a plain diamond. */
25
+ const polygon = (element: LookElement): string => {
26
+ const { width: w, height: h } = element;
27
+ return `M ${w / 2} 0 L ${w} ${h / 2} L ${w / 2} ${h} L 0 ${h / 2} Z`;
28
+ };
29
+
30
+ /** A robot head in a step's upper-left corner, where BPMN puts a task type's marker. */
31
+ export const drawRobot = (parent: SVGElement, stroke: string) => {
32
+ const robot = svgCreate('g');
33
+ svgAttr(robot, { transform: 'translate(7, 6)', fill: 'none', stroke, 'stroke-width': 1.5 });
34
+ const parts: ReadonlyArray<{ readonly tag: string; readonly attrs: Readonly<Record<string, string | number>> }> = [
35
+ { tag: 'rect', attrs: { x: 1, y: 5, width: 14, height: 10, rx: 3 } },
36
+ { tag: 'line', attrs: { x1: 8, y1: 5, x2: 8, y2: 2 } },
37
+ { tag: 'circle', attrs: { cx: 8, cy: 1.5, r: 1.2 } },
38
+ { tag: 'circle', attrs: { cx: 5, cy: 10, r: 1.3, fill: stroke } },
39
+ { tag: 'circle', attrs: { cx: 11, cy: 10, r: 1.3, fill: stroke } },
40
+ ];
41
+ for (const part of parts) {
42
+ const node = svgCreate(part.tag);
43
+ svgAttr(node, part.attrs);
44
+ svgAppend(robot, node);
45
+ }
46
+ svgAppend(parent, robot);
47
+ };
48
+
49
+ class ActivityLookRenderer extends BaseRenderer {
50
+ static $inject = ['eventBus', 'bpmnRenderer', 'config.bpmnRenderer'];
51
+
52
+ private readonly bpmnRenderer: BaseRenderer;
53
+ private readonly config: RendererConfig;
54
+
55
+ constructor(eventBus: EventBus, bpmnRenderer: BaseRenderer, config: RendererConfig | undefined) {
56
+ super(eventBus, 1500);
57
+ this.bpmnRenderer = bpmnRenderer;
58
+ this.config = config ?? {};
59
+ }
60
+
61
+ override canRender(element: LookElement): boolean {
62
+ // A merge asks no question, so its BPMN label draws nothing; a decision's label is bpmn-js's own, beside it.
63
+ if (element['labelTarget'] !== undefined) return isGateway(element['labelTarget']) && isMerge(element['labelTarget'].businessObject);
64
+ return isGateway(element) || STEP_TYPES.has(element['type']);
65
+ }
66
+
67
+ override drawShape(parent: SVGElement, element: LookElement): SVGElement {
68
+ if (element['labelTarget'] !== undefined) {
69
+ const nothing = svgCreate('g');
70
+ svgAppend(parent, nothing);
71
+ return nothing;
72
+ }
73
+ const stroke = getStrokeColor(element, this.config.defaultStrokeColor ?? '#181818');
74
+ const fill = getFillColor(element, this.config.defaultFillColor ?? '#f1f1f1');
75
+ if (isGateway(element)) {
76
+ const shape = svgCreate('path');
77
+ svgAttr(shape, { d: polygon(element), fill, stroke, 'stroke-width': 1.5, 'stroke-linejoin': 'round' });
78
+ svgAppend(parent, shape);
79
+ return shape;
80
+ }
81
+ const shape = this.bpmnRenderer.drawShape(parent, element) as SVGElement;
82
+ svgAttr(shape, { rx: 12, ry: 12, 'stroke-width': 1.5 });
83
+ if (element.businessObject.$attrs?.['jive:kind'] === 'agent') drawRobot(parent, stroke);
84
+ return shape;
85
+ }
86
+
87
+ override getShapePath(element: LookElement): string {
88
+ if (!isGateway(element)) return this.bpmnRenderer.getShapePath(element);
89
+ return polygon(element).replace(/(-?\d+(?:\.\d+)?) (-?\d+(?:\.\d+)?)/g, (_, x: string, y: string) => `${Number(x) + element.x} ${Number(y) + element.y}`);
90
+ }
91
+ }
92
+
93
+ export const activityLookModule = { __init__: ['activityLookRenderer'], activityLookRenderer: ['type', ActivityLookRenderer] };
@@ -0,0 +1,9 @@
1
+ // bpmn-moddle ships no types. These are the calls the layout makes: read a BPMN document, create diagram elements, write
2
+ // the document back.
3
+ declare module "bpmn-moddle" {
4
+ export class BpmnModdle {
5
+ fromXML(xml: string): Promise<{ readonly rootElement: unknown; readonly warnings: ReadonlyArray<unknown> }>
6
+ toXML(element: unknown, options?: { readonly format?: boolean }): Promise<{ readonly xml: string }>
7
+ create(type: string, attributes?: Readonly<Record<string, unknown>>): unknown
8
+ }
9
+ }
@@ -0,0 +1,31 @@
1
+ /* The workflow view's own styles. Load beside bpmn-js's diagram-js.css and bpmn-js.css. Every badge, slice and panel
2
+ line carries its meaning in words, so no style here is the only way something is told apart. */
3
+ .jive-badge { background: #5fd38d; color: #0d1410; font: bold 12px Arial, sans-serif; padding: 2px 8px; border-radius: 10px; white-space: nowrap; cursor: pointer; }
4
+ .jive-on-line { transform: translate(-50%, 30%); }
5
+ .jive-beside-line { transform: translate(8px, -50%); }
6
+ .jive-selected .djs-visual > :first-child { stroke-width: 5px !important; stroke-dasharray: 8 4 !important; }
7
+
8
+ .jive-panel { padding: 14px 16px; border: 1px solid #c8cfca; border-radius: 8px; background: #ffffff; color: #16201a; font: 13px/1.4 Arial, sans-serif; }
9
+ .jive-panel.jive-dark { background: #22262a; color: #e3e7e4; border-color: #4a524c; }
10
+ .jive-panel h2 { margin: 0 0 4px; font-size: 16px; }
11
+ .jive-panel h3 { margin: 14px 0 6px; font-size: 13px; }
12
+ .jive-panel .jive-sub, .jive-panel .jive-more, .jive-panel .jive-empty { margin: 4px 0; opacity: 0.85; }
13
+ .jive-panel .jive-close { float: right; font: 12px Arial, sans-serif; }
14
+ .jive-panel a { color: inherit; text-decoration: underline; }
15
+ .jive-tasks, .jive-runs { margin: 0; padding: 0; list-style: none; }
16
+ .jive-tasks li, .jive-runs li { padding: 5px 0; border-top: 1px solid rgba(128, 128, 128, 0.35); }
17
+ .jive-runs li { font-size: 12px; }
18
+ .jive-task-head { display: flex; justify-content: space-between; gap: 8px; font-weight: bold; }
19
+ .jive-task-age { font-weight: normal; white-space: nowrap; }
20
+ .jive-task-note { font-size: 12px; opacity: 0.85; }
21
+ .jive-stats { display: grid; grid-template-columns: max-content 1fr; gap: 4px 12px; margin: 0; }
22
+ .jive-stats dt { font-weight: bold; }
23
+ .jive-stats dd { margin: 0; }
24
+ .jive-ends { margin: 0; padding-left: 16px; }
25
+
26
+ .jive-pie-box h3 { margin: 0 0 6px; font: bold 13px Arial, sans-serif; }
27
+ .jive-slices { margin: 4px 0 0; padding: 0; list-style: none; font: 12px Arial, sans-serif; }
28
+ .jive-slices li { display: flex; align-items: center; gap: 6px; padding: 2px 0; }
29
+ .jive-slices .jive-slice-value { margin-left: auto; white-space: nowrap; }
30
+ .jive-swatch { width: 10px; height: 10px; border-radius: 2px; flex: none; }
31
+ .jive-slice { cursor: pointer; }
@@ -0,0 +1,120 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import type { WorkflowGraph } from "../src/graph"
3
+ import { figuresOf, type FiguresInput, type StepStatsResult, waitsOf } from "./figures"
4
+
5
+ /** A workflow shaped like Match a function: a sub-workflow step with an agent inside, an agent step and a code step. */
6
+ const graph: WorkflowGraph = {
7
+ name: "matchAFunction",
8
+ endStates: ["behaves", "no progress"],
9
+ budgets: { agents: 4, cpu: 8 },
10
+ events: [{ id: "task", kind: "task" }],
11
+ steps: [
12
+ { id: "decompile", kind: "workflow", endStates: ["matched", "no progress"], workflow: { name: "decompile" } },
13
+ { id: "learnFromBlocked", kind: "agent", endStates: ["found something new", "nothing new"], access: { services: ["AgentRunner"] } },
14
+ { id: "build", kind: "workflow", endStates: ["built"], workflow: { name: "build" } },
15
+ ],
16
+ lines: [
17
+ { id: "event.task>step.decompile", from: { event: "task" }, to: { step: "decompile" } },
18
+ { id: "learn>decompile", from: { step: "learnFromBlocked", endState: "found something new" }, to: { step: "decompile" } },
19
+ { id: "decompile>learn", from: { step: "decompile", endState: "no progress" }, to: { step: "learnFromBlocked" } },
20
+ { id: "decompile>build", from: { step: "decompile", endState: "matched" }, to: { step: "build" } },
21
+ { id: "build>end", from: { step: "build", endState: "built" }, to: { end: "behaves" } },
22
+ { id: "learn>end", from: { step: "learnFromBlocked", endState: "nothing new" }, to: { end: "no progress" } },
23
+ ],
24
+ }
25
+ const innerGraph = (name: string, kind: "agent" | "code"): WorkflowGraph => ({
26
+ name,
27
+ endStates: ["done"],
28
+ budgets: { agents: 1, cpu: 1 },
29
+ events: [{ id: "task", kind: "task" }],
30
+ steps: [{ id: name, kind, endStates: ["done"] }],
31
+ lines: [],
32
+ })
33
+ const innerGraphs = new Map([
34
+ ["decompile", innerGraph("decompile", "agent")],
35
+ ["build", innerGraph("build", "code")],
36
+ ])
37
+ const names: Readonly<Record<string, string>> = { decompile: "Decompile", learnFromBlocked: "Learn from blocked", build: "Build" }
38
+
39
+ const stats = (input: { readonly tokens: number; readonly costUsd: number; readonly wallSeconds: number; readonly median: number; readonly calls?: number; readonly running?: number }): StepStatsResult => ({
40
+ calls: input.calls ?? 10,
41
+ running: input.running ?? 0,
42
+ endStates: [],
43
+ spend: { fresh: input.tokens - 100, cacheWrite: 0, cacheRead: 0, output: 100, costUsd: input.costUsd },
44
+ wallSeconds: input.wallSeconds,
45
+ perTask: { wallSeconds: { median: input.median, p90: input.median * 2 } },
46
+ })
47
+
48
+ const base: FiguresInput = {
49
+ metric: "tasks",
50
+ graph,
51
+ innerGraphs,
52
+ counts: {
53
+ lines: [
54
+ { line: "event.task>step.decompile", tasks: 5 },
55
+ { line: "learn>decompile", tasks: 2 },
56
+ { line: "decompile>learn", tasks: 1 },
57
+ ],
58
+ steps: [
59
+ { step: "decompile", tasks: 40 },
60
+ { step: "build", tasks: 3 },
61
+ ],
62
+ ends: [{ end: "behaves", tasks: 12 }],
63
+ },
64
+ stats: new Map([
65
+ ["decompile", stats({ tokens: 1_600_000, costUsd: 2.5, wallSeconds: 3600, median: 120 })],
66
+ ["learnFromBlocked", stats({ tokens: 300_000, costUsd: 0.4, wallSeconds: 60, median: 8 })],
67
+ ["build", stats({ tokens: 0, costUsd: 0, wallSeconds: 300, median: 20 })],
68
+ ]),
69
+ waits: new Map([["decompile", { median: 7_000, longest: 34_000 }]]),
70
+ stepName: (step) => names[step] ?? step,
71
+ dark: true,
72
+ }
73
+
74
+ describe("the figures of each metric", () => {
75
+ test("tasks: each step's tasks, each queue's tasks over all the lines into it, and each end state's", () => {
76
+ const { badges, pie } = figuresOf(base)
77
+ expect(badges.steps).toEqual({ decompile: "40 in it", learnFromBlocked: "0 in it", build: "3 in it" })
78
+ // Decompile's queue is both lines into it: 5 arriving and 2 sent back.
79
+ expect(badges.queues).toEqual({ decompile: "7 queued", learnFromBlocked: "1 queued", build: "0 queued" })
80
+ expect(badges.ends).toEqual({ behaves: "12 ended here" })
81
+ expect(pie).toContain("Tasks in each step now")
82
+ expect(pie).toContain("Decompile")
83
+ })
84
+
85
+ test("time: the median per task on each step that finished a run, and how long its queue has waited", () => {
86
+ const { badges, pie } = figuresOf({ ...base, metric: "time" })
87
+ expect(badges.steps["decompile"]).toBe("median 2 min")
88
+ expect(badges.steps["learnFromBlocked"]).toBe("median 8 s")
89
+ expect(badges.queues).toEqual({ decompile: "waited median 7 s, longest 34 s" })
90
+ expect(pie).toContain("Time spent in each step")
91
+ })
92
+
93
+ test("time: a step whose every run is still going has no median yet", () => {
94
+ const running = new Map(base.stats)
95
+ running.set("build", stats({ tokens: 0, costUsd: 0, wallSeconds: 0, median: 0, calls: 2, running: 2 }))
96
+ expect(figuresOf({ ...base, metric: "time", stats: running }).badges.steps["build"]).toBeUndefined()
97
+ })
98
+
99
+ test("tokens and cost: only agent steps and sub-workflows with agents inside, and never a queue", () => {
100
+ const tokens = figuresOf({ ...base, metric: "tokens" })
101
+ expect(tokens.badges.steps).toEqual({ decompile: "1.6 M tokens", learnFromBlocked: "300 k tokens" })
102
+ expect(tokens.badges.queues).toEqual({})
103
+ expect(tokens.pie).toContain("Tokens by step")
104
+ const cost = figuresOf({ ...base, metric: "cost" })
105
+ expect(cost.badges.steps).toEqual({ decompile: "$2.50", learnFromBlocked: "$0.40" })
106
+ expect(cost.pie).toContain("Cost by step")
107
+ })
108
+
109
+ test("the pie says so when nothing has been spent yet", () => {
110
+ const idle = new Map([...base.stats].map(([step]) => [step, stats({ tokens: 0, costUsd: 0, wallSeconds: 0, median: 0 })]))
111
+ expect(figuresOf({ ...base, metric: "tokens", stats: idle }).pie).toContain("No agent step has spent tokens yet.")
112
+ })
113
+ })
114
+
115
+ describe("how long a queue has waited", () => {
116
+ test("the median and the longest wait, or nothing for an empty queue", () => {
117
+ expect(waitsOf([1_000, 4_000, 9_000], 10_000)).toEqual({ median: 6_000, longest: 9_000 })
118
+ expect(waitsOf([], 10_000)).toBeUndefined()
119
+ })
120
+ })
@@ -0,0 +1,125 @@
1
+ // The figures a workflow view shows for its selected metric: the badge on each step, on each step's queue and on each end
2
+ // state, and the pie splitting the metric across steps. Worked out from query results already read, so it is the same
3
+ // for a live view and a test.
4
+ import type { GraphStep, WorkflowGraph } from "../src/graph"
5
+ import { pieHtml, type PieSlice, topSlices } from "./pie"
6
+ import { dollars, duration, tokenWords } from "./words"
7
+
8
+ /** What every box and queue badge shows, picked in the view's dropdown. */
9
+ export type Metric = "tasks" | "time" | "tokens" | "cost"
10
+ export const METRICS: ReadonlyArray<{ readonly metric: Metric; readonly label: string }> = [
11
+ { metric: "tasks", label: "Tasks" },
12
+ { metric: "time", label: "Time" },
13
+ { metric: "tokens", label: "Tokens" },
14
+ { metric: "cost", label: "Cost" },
15
+ ]
16
+
17
+ /** The workforce's `counts`: the tasks on every line, in every step and at every end state. */
18
+ export interface WorkflowCounts {
19
+ readonly lines: ReadonlyArray<{ readonly line: string; readonly tasks: number }>
20
+ readonly steps: ReadonlyArray<{ readonly step: string; readonly tasks: number }>
21
+ readonly ends: ReadonlyArray<{ readonly end: string; readonly tasks: number }>
22
+ }
23
+
24
+ /** The parts of the workforce's `stepStats` the figures read. */
25
+ export interface StepStatsResult {
26
+ readonly calls: number
27
+ readonly running: number
28
+ readonly endStates: ReadonlyArray<{ readonly endState: string; readonly runs: number }>
29
+ readonly spend: { readonly fresh: number; readonly cacheWrite: number; readonly cacheRead: number; readonly output: number; readonly costUsd: number }
30
+ readonly wallSeconds: number
31
+ readonly perTask: { readonly wallSeconds: { readonly median: number; readonly p90: number } }
32
+ }
33
+
34
+ /** How long the tasks in front of a step have waited, in milliseconds. */
35
+ export interface Waits {
36
+ readonly median: number
37
+ readonly longest: number
38
+ }
39
+
40
+ /**
41
+ * The words on the diagram's badges, keyed by the step's id (its BPMN jive:export) and the end state's name (jive:end):
42
+ * on each step, on the line into each step (its queue), and on each end state. An element with no words gets no badge.
43
+ */
44
+ export interface Badges {
45
+ readonly steps: Readonly<Record<string, string>>
46
+ readonly queues: Readonly<Record<string, string>>
47
+ readonly ends: Readonly<Record<string, string>>
48
+ }
49
+
50
+ export const tokensOf = (spend: StepStatsResult["spend"]): number => spend.fresh + spend.cacheWrite + spend.cacheRead + spend.output
51
+
52
+ /** Tokens and cost apply to agent steps, and to sub-workflow steps whose inner workflow has agent steps. */
53
+ export const spendsTokens = (step: GraphStep, innerGraphs: ReadonlyMap<string, WorkflowGraph>): boolean =>
54
+ step.kind === "agent" || (step.workflow !== undefined && innerGraphs.get(step.workflow.name)?.steps.some((each) => each.kind === "agent") === true)
55
+
56
+ /** Every line into `step`: its whole queue. */
57
+ export const linesInto = (graph: WorkflowGraph, step: string) => graph.lines.filter((line) => "step" in line.to && line.to.step === step)
58
+
59
+ export const tasksOnLine = (counts: WorkflowCounts, line: string): number => counts.lines.find((each) => each.line === line)?.tasks ?? 0
60
+
61
+ /** The median and longest of how long tasks have waited, given when each entered its queue. */
62
+ export const waitsOf = (entered: ReadonlyArray<number>, now: number): Waits | undefined => {
63
+ const waits = entered.map((at) => now - at).sort((a, b) => a - b)
64
+ return waits.length === 0 ? undefined : { median: waits[Math.ceil(waits.length / 2) - 1]!, longest: waits[waits.length - 1]! }
65
+ }
66
+
67
+ /** What the figures are worked out from. `stats` and `waits` are needed only for the metrics that read them. */
68
+ export interface FiguresInput {
69
+ readonly metric: Metric
70
+ readonly graph: WorkflowGraph
71
+ readonly innerGraphs: ReadonlyMap<string, WorkflowGraph>
72
+ readonly counts: WorkflowCounts
73
+ readonly stats: ReadonlyMap<string, StepStatsResult>
74
+ readonly waits: ReadonlyMap<string, Waits>
75
+ readonly stepName: (step: string) => string
76
+ readonly dark: boolean
77
+ }
78
+
79
+ /** The badges and the pie of the selected metric. */
80
+ export const figuresOf = (input: FiguresInput): { readonly badges: Badges; readonly pie: string } => {
81
+ const steps: Record<string, string> = {}
82
+ const queues: Record<string, string> = {}
83
+ const ends: Record<string, string> = {}
84
+ const slices: Array<PieSlice> = []
85
+ const pieOf = (title: string, wordsOf: (value: number) => string, empty: string) =>
86
+ pieHtml({ title, slices: topSlices({ slices, wordsOf }), dark: input.dark, empty })
87
+ const done = (pie: string) => ({ badges: { steps, queues, ends }, pie })
88
+
89
+ if (input.metric === "tasks") {
90
+ for (const step of input.graph.steps) {
91
+ const inIt = input.counts.steps.find((each) => each.step === step.id)?.tasks ?? 0
92
+ steps[step.id] = `${inIt} in it`
93
+ queues[step.id] = `${linesInto(input.graph, step.id).reduce((total, line) => total + tasksOnLine(input.counts, line.id), 0)} queued`
94
+ slices.push({ step: step.id, label: input.stepName(step.id), value: inIt, words: `${inIt} ${inIt === 1 ? "task" : "tasks"}` })
95
+ }
96
+ for (const end of input.counts.ends) ends[end.end] = `${end.tasks} ended here`
97
+ return done(pieOf("Tasks in each step now", (n) => `${n} tasks`, "No task is in a step now."))
98
+ }
99
+
100
+ if (input.metric === "time") {
101
+ for (const step of input.graph.steps) {
102
+ const own = input.stats.get(step.id)
103
+ if (own !== undefined && own.calls - own.running > 0) {
104
+ steps[step.id] = `median ${duration(own.perTask.wallSeconds.median * 1000)}`
105
+ slices.push({ step: step.id, label: input.stepName(step.id), value: own.wallSeconds, words: duration(own.wallSeconds * 1000) })
106
+ }
107
+ const waits = input.waits.get(step.id)
108
+ if (waits !== undefined) queues[step.id] = `waited median ${duration(waits.median)}, longest ${duration(waits.longest)}`
109
+ }
110
+ return done(pieOf("Time spent in each step", (seconds) => duration(seconds * 1000), "No step has finished a run yet."))
111
+ }
112
+
113
+ // Tokens and cost: only steps that spend them get a badge, and a queue gets none.
114
+ for (const step of input.graph.steps) {
115
+ const own = input.stats.get(step.id)
116
+ if (own === undefined || !spendsTokens(step, input.innerGraphs)) continue
117
+ const value = input.metric === "tokens" ? tokensOf(own.spend) : own.spend.costUsd
118
+ const words = input.metric === "tokens" ? tokenWords(value) : dollars(value)
119
+ steps[step.id] = words
120
+ slices.push({ step: step.id, label: input.stepName(step.id), value, words })
121
+ }
122
+ return input.metric === "tokens"
123
+ ? done(pieOf("Tokens by step", tokenWords, "No agent step has spent tokens yet."))
124
+ : done(pieOf("Cost by step", dollars, "No agent step has spent anything yet."))
125
+ }