@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.
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
@@ -55,6 +56,9 @@ export const review = Workflow.make({
55
56
  })
56
57
  ```
57
58
 
59
+ A package that builds its steps as values of their own, to export them (as a compiled diagram binds its elements to
60
+ them), gets the same builder outside a workflow from `Workflow.stepsOf(taskSchema)` (1.1.0).
61
+
58
62
  A step's `access` lists what its code may use: services (the platform's or an organization's) and the workflows whose
59
63
  tasks it may read and write. Nothing listed grants nothing, a `run` that uses anything else fails to compile, and the
60
64
  worker gives a run only what its step lists.
@@ -65,7 +69,8 @@ worker gives a run only what its step lists.
65
69
  turn task is what the schema decodes from `{}`), and a declared item list kept in step by `step.syncList`.
66
70
  - **Steps:** code, an agent, a sub-workflow (`step.workflow`, or `step.each` with `collect`), an inputs gate
67
71
  (`step.inputsChanged`), retries with a delay and a give-up end state, notes on a task that later steps read, and
68
- writes to other tasks (`StepOutcome.others`) in the same transaction as the step's own result.
72
+ writes to other tasks (`StepOutcome.others`) in the same transaction as the step's own result. A note written that
73
+ way carries its writer as `by: { workflow, step, task }` (1.1.0; 1.0.0 put the writer in the note's words).
69
74
  - **Agents:** `AgentRunner` with no tools, a reading mode or a working mode with write scopes, a cached input, and a
70
75
  turn limit; the organization implements it.
71
76
  - **Queues:** requeue with a note, move tasks to the front, an in-progress limit per workflow or per field value (a
@@ -76,6 +81,7 @@ worker gives a run only what its step lists.
76
81
 
77
82
  ## Developing it
78
83
 
79
- `bun run typecheck` checks `src`, `component` and `worker` (`tsconfig.check.json`); `tsconfig.json` is the library
80
- abstract's one line, which its build uses for `src`. `bun test src worker` runs the unit tests. The end-to-end tests
81
- run in an organization package against a local anonymous Convex deployment.
84
+ `bun run typecheck` checks `src`, `component` and `worker` (`tsconfig.check.json`), and `dashboard` with the DOM
85
+ (`tsconfig.dashboard.json`); `tsconfig.json` is the library abstract's one line, which its build uses for `src`.
86
+ `bun run test` runs the unit tests of `src`, `worker` and `dashboard`. The end-to-end tests run in an organization
87
+ package against a local anonymous Convex deployment.
@@ -215,6 +215,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
215
215
  files: Array<{ name: string; ref: string }>;
216
216
  notes: Array<{
217
217
  at: number;
218
+ by?: { step: string; task: string; workflow: string };
218
219
  note: string;
219
220
  step?: string;
220
221
  workflow: string;
@@ -290,7 +291,13 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
290
291
  "query",
291
292
  "internal",
292
293
  { task: string },
293
- Array<{ at: number; note: string; step?: string; workflow: string }>,
294
+ Array<{
295
+ at: number;
296
+ by?: { step: string; task: string; workflow: string };
297
+ note: string;
298
+ step?: string;
299
+ workflow: string;
300
+ }>,
294
301
  Name
295
302
  >;
296
303
  recordSubWorkflowTask: FunctionReference<
@@ -341,7 +348,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
341
348
  "mutation",
342
349
  "internal",
343
350
  {
344
- by: string;
351
+ by: { step: string; task: string; workflow: string };
345
352
  fields?: any;
346
353
  files?: Array<{ name: string; ref: string }>;
347
354
  note: string;
@@ -463,6 +470,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
463
470
  id: string;
464
471
  notes: Array<{
465
472
  at: number;
473
+ by?: { step: string; task: string; workflow: string };
466
474
  note: string;
467
475
  step?: string;
468
476
  workflow: string;
@@ -10,6 +10,7 @@ import {
10
10
  inputPlacesOf,
11
11
  lineFrom,
12
12
  type LineStart,
13
+ type NoteWriter,
13
14
  placeAtEndOf,
14
15
  problemsOf,
15
16
  stepOfPlace,
@@ -611,7 +612,7 @@ export const complete = function* (input: {
611
612
 
612
613
  /**
613
614
  * Another task's run writes to this task (`StepOutcome.others`), in the transaction that completes that run: the note,
614
- * saying whose run wrote it, then the fields and files, which start this task's change events as any change does. A task
615
+ * with whose run wrote it as its `by`, then the fields and files, which start this task's change events as any change does. A task
615
616
  * in a step now is left alone, so no step's run is overtaken; the reason is returned for the writing run to record.
616
617
  */
617
618
  export const writeOther = function* (input: {
@@ -619,15 +620,15 @@ export const writeOther = function* (input: {
619
620
  readonly fields: Option.Option<Record<string, unknown>>
620
621
  readonly files: Option.Option<ReadonlyArray<TaskFile>>
621
622
  readonly note: string
622
- /** The run that wrote it, in words: its step, its workflow and its task. */
623
- readonly by: string
623
+ /** The run that wrote it: its workflow, step and task, kept on the note. */
624
+ readonly by: NoteWriter
624
625
  }): Run<Option.Option<string>> {
625
626
  const store = yield* WorkflowStore
626
627
  const task = yield* taskWithId(input.task)
627
628
  const workflow = yield* workflowNamed(task.workflow)
628
629
  const inStep = (yield* store.flowsOfTask(task._id)).find((flow) => Option.isSome(stepOfPlace(flow.place)))
629
630
  if (inStep !== undefined) return Option.some(`it was in step ${Option.getOrElse(stepOfPlace(inStep.place), () => "")} when the run ended`)
630
- yield* store.insertTaskNote({ task: task._id, note: `${input.note} (written by ${input.by})` })
631
+ yield* store.insertTaskNote({ task: task._id, note: input.note, by: input.by })
631
632
  if (Option.isSome(input.fields) || Option.isSome(input.files)) {
632
633
  yield* changeTask({
633
634
  workflow,
@@ -9,5 +9,11 @@ export const notesOf = (input: {
9
9
  }): Array<TaskNote> =>
10
10
  [
11
11
  ...input.runs.flatMap((run) => (run.note === undefined ? [] : [{ workflow: input.task.workflow, step: run.step, note: run.note, at: run.endedAt ?? run.startedAt }])),
12
- ...input.left.map((row) => ({ workflow: input.task.workflow, ...(row.step !== undefined ? { step: row.step } : {}), note: row.note, at: row.at })),
12
+ ...input.left.map((row) => ({
13
+ workflow: input.task.workflow,
14
+ ...(row.step !== undefined ? { step: row.step } : {}),
15
+ note: row.note,
16
+ at: row.at,
17
+ ...(row.by !== undefined ? { by: row.by } : {}),
18
+ })),
13
19
  ].sort((a, b) => a.at - b.at)
@@ -7,6 +7,7 @@ import {
7
7
  stepSpendValidator,
8
8
  stepUsedValidator,
9
9
  skippedOtherValidator,
10
+ noteWriterValidator,
10
11
  taskFileValidator,
11
12
  workforceHooksValidator,
12
13
  } from "../src/graph"
@@ -116,6 +117,8 @@ export default defineSchema({
116
117
  at: v.number(),
117
118
  /** The step whose run said it, for a run's note kept here once retention deleted the run. */
118
119
  step: v.optional(v.string()),
120
+ /** The run that wrote it through `others`, on behalf of another task. */
121
+ by: v.optional(noteWriterValidator),
119
122
  }).index("by_task", ["task"]),
120
123
 
121
124
  /**
@@ -5,6 +5,7 @@ import {
5
5
  errorKept,
6
6
  nothingUsed,
7
7
  noSpend,
8
+ type NoteWriter,
8
9
  type ParentRef,
9
10
  type SkippedOther,
10
11
  type StepMeasurements,
@@ -110,7 +111,7 @@ export interface IWorkflowStore {
110
111
  scheduleLeaseCheck(input: { readonly run: Id<"stepRuns">; readonly at: number }): Effect.fn.Return<void>
111
112
  stepRunsOfTask(task: Id<"tasks">): Effect.fn.Return<ReadonlyArray<StepRunRow>>
112
113
  /** Keeps a note about a task that no step wrote, such as why a call sent it back. */
113
- insertTaskNote(input: { readonly task: Id<"tasks">; readonly note: string }): Effect.fn.Return<void>
114
+ insertTaskNote(input: { readonly task: Id<"tasks">; readonly note: string; readonly by?: NoteWriter }): Effect.fn.Return<void>
114
115
  /** Everything said about a task, oldest first: its step runs' notes and the notes calls left. */
115
116
  notesOfTask(task: TaskRow): Effect.fn.Return<ReadonlyArray<TaskNote>>
116
117
  /**
@@ -464,8 +465,8 @@ export class ConvexWorkflowStore implements IWorkflowStore {
464
465
  return yield* Effect.promise(() => this.ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", task)).collect())
465
466
  }
466
467
 
467
- *insertTaskNote(input: { readonly task: Id<"tasks">; readonly note: string }) {
468
- yield* Effect.promise(() => this.ctx.db.insert("taskNotes", { task: input.task, note: input.note, at: this.now }))
468
+ *insertTaskNote(input: { readonly task: Id<"tasks">; readonly note: string; readonly by?: NoteWriter }) {
469
+ yield* Effect.promise(() => this.ctx.db.insert("taskNotes", { task: input.task, note: input.note, at: this.now, ...(input.by !== undefined ? { by: { ...input.by } } : {}) }))
469
470
  }
470
471
 
471
472
  *lastFingerprintOf(input: { readonly workflow: string; readonly step: string; readonly settledBy: ReadonlyArray<string> }) {
@@ -2,6 +2,7 @@ import { v } from "convex/values"
2
2
  import { Option } from "effect"
3
3
  import {
4
4
  createsTasks,
5
+ noteWriterValidator,
5
6
  inputPlacesOf,
6
7
  parentRefValidator,
7
8
  placeAtStartOf,
@@ -261,7 +262,7 @@ export const find = query({
261
262
  * why the write was skipped, or null once it is applied (`Engine.writeOther`). Fields are already encoded and checked.
262
263
  */
263
264
  export const writeOther = mutation({
264
- args: { task: v.string(), fields: v.optional(v.any()), files: v.optional(v.array(taskFileValidator)), note: v.string(), by: v.string() },
265
+ args: { task: v.string(), fields: v.optional(v.any()), files: v.optional(v.array(taskFileValidator)), note: v.string(), by: noteWriterValidator },
265
266
  returns: v.union(v.null(), v.string()),
266
267
  handler: async (ctx, args) => {
267
268
  const task = ctx.db.normalizeId("tasks", args.task)
@@ -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
+ }
@@ -0,0 +1,14 @@
1
+ // The workflow views: a workflow's diagram in the activity-diagram look, with the selected metric (tasks, time, tokens or
2
+ // cost) on every step, queue and end state, a pie of that metric across its steps, and a panel for the clicked step or
3
+ // line with its tasks, access, stats and latest runs. Read live from the workforce's queries.
4
+ //
5
+ // In a browser app: `mountWorkflowView({ client, queries: api.workforce, workflow, bpmn, elements, dark })`, with
6
+ // bpmn-js's diagram-js.css and bpmn-js.css, and this folder's dashboard.css, loaded.
7
+ export { mountWorkflowView, type StepRunRow, type TaskRow, type ViewElements, type WorkflowView, type WorkflowViewOptions, type WorkforceQueries } from "./live"
8
+ export { figuresOf, METRICS, type Badges, type FiguresInput, type Metric, type StepStatsResult, type Waits, type WorkflowCounts } from "./figures"
9
+ export { layOutBpmn, type LaidOut } from "./layout"
10
+ export { linePanel, stepPanel, type PlaceTasks, type StepRun, type StepRuns, type StepStats } from "./panel"
11
+ export { pieHtml, topSlices, type PieSlice } from "./pie"
12
+ export { platformLinesByFlow, type DiagramShape, type PlatformLine } from "./places"
13
+ export { drawWorkflow, type DrawnWorkflow, type PanelSource } from "./view"
14
+ export { accessWords, dollars, duration, PLATFORM_SERVICE_WORDS, tokenWords, workflowWords } from "./words"