@jive-sh/workflow-platform 1.4.0 → 1.4.2

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,7 +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
+ | `@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; 1.4.1 fits each diagram to its width at a readable scale) |
26
26
 
27
27
  Write `.js` in the import: TypeScript and Convex's bundler both resolve it to the shipped `.ts`. Convex's codegen
28
28
  writes `@jive-sh/workflow-platform/component/_generated/component.js` into an app installing the component, for the
@@ -4,7 +4,9 @@ A browser view of one workflow, read live from the workforce's queries:
4
4
 
5
5
  - **The diagram:** the workflow's BPMN, laid out top to bottom when the view opens and drawn like a UML activity
6
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.
7
+ beside it and the end-state names on its lines; a merge is a plain diamond. It fills the width of the canvas's
8
+ parent, never smaller than a scale its names and badges can be read at (0.85), nor larger than 1.25; the canvas
9
+ takes the height that needs, and a diagram too wide at 0.85 is wider than its parent, for the parent to scroll.
8
10
  - **A metric on every box and queue,** picked in a dropdown:
9
11
  - **Tasks** (the default): the tasks in each step, queued in front of it, and ended at each end state.
10
12
  - **Time:** each step's median time per task, and how long each queue's tasks have waited (median and longest).
@@ -39,7 +41,7 @@ const view = await mountWorkflowView({
39
41
  queries: api.workforce, // the workforce functions the app exports
40
42
  workflow: "matchAFunction",
41
43
  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
44
+ elements: { canvas, panel, picker, pie }, // the diagram's element (the view sizes it), a panel, a <select>, a pie box
43
45
  dark: true,
44
46
  taskName: (fields) => (typeof fields["address"] === "string" ? fields["address"] : undefined),
45
47
  fileHref: (file) => `/files/${file.ref}`, // where the page can open a stored file, such as a transcript
package/dashboard/live.ts CHANGED
@@ -54,6 +54,10 @@ export interface WorkforceQueries {
54
54
 
55
55
  /** Where the view goes on the page. */
56
56
  export interface ViewElements {
57
+ /**
58
+ * The diagram's element. The view sets its width and height: the diagram fills its parent's width, at no less than
59
+ * a scale its names and badges can be read at, so give the parent the width to fill and let it scroll sideways.
60
+ */
57
61
  readonly canvas: HTMLElement
58
62
  readonly panel: HTMLElement
59
63
  /** The metric dropdown; filled by the view. */
package/dashboard/view.ts CHANGED
@@ -23,9 +23,15 @@ interface DiagramElement {
23
23
 
24
24
  const jiveAttribute = (element: DiagramElement, name: string): string | undefined => element.businessObject?.$attrs?.[`jive:${name}`]
25
25
 
26
- /** Room around the fitted diagram, in diagram units. */
26
+ /** Room around the diagram, in diagram units. */
27
27
  const VIEW_MARGIN = 40
28
28
 
29
+ /** The smallest scale a diagram is drawn at: smaller, its names and badges can't be read without zooming. */
30
+ const MIN_SCALE = 0.85
31
+
32
+ /** The largest: a small diagram is drawn at a little over its own size, not blown up to fill a wide window. */
33
+ const MAX_SCALE = 1.25
34
+
29
35
  /** The overlay type of the badges, so a new set replaces the old. */
30
36
  const BADGE_OVERLAY = "jive-badge"
31
37
 
@@ -118,13 +124,37 @@ export const drawWorkflow = async (input: {
118
124
  const canvas = viewer.get("canvas") as {
119
125
  addMarker: (id: string, marker: string) => void
120
126
  removeMarker: (id: string, marker: string) => void
121
- zoom: (level: "fit-viewport") => void
122
- viewbox: (box?: { x: number; y: number; width: number; height: number }) => { readonly x: number; readonly y: number; readonly width: number; readonly height: number }
127
+ resized: () => void
128
+ viewbox: (box?: { x: number; y: number; width: number; height: number }) => {
129
+ readonly x: number
130
+ readonly y: number
131
+ readonly width: number
132
+ readonly height: number
133
+ /** The bounds of everything drawn. */
134
+ readonly inner: { readonly x: number; readonly y: number; readonly width: number; readonly height: number }
135
+ }
136
+ }
137
+ // The diagram fills the width of the canvas's parent, at a scale between MIN_SCALE and MAX_SCALE, and the canvas takes
138
+ // the height that needs, so the page scrolls instead of the diagram shrinking until its names and badges can't be read.
139
+ // A diagram too wide for its parent at MIN_SCALE is wider than it, for the parent to scroll sideways.
140
+ const diagram = canvas.viewbox().inner
141
+ // A margin keeps the outermost start and end circles and their badges whole.
142
+ const box = { x: diagram.x - VIEW_MARGIN, y: diagram.y - VIEW_MARGIN, width: diagram.width + 2 * VIEW_MARGIN, height: diagram.height + 2 * VIEW_MARGIN }
143
+ let fittedTo = -1
144
+ const fitToWidth = () => {
145
+ const available = (input.canvas.parentElement ?? input.canvas).clientWidth
146
+ // Sizing the canvas can resize its parent (a scrollbar comes or goes); refit only when the width changed.
147
+ if (available === fittedTo) return
148
+ fittedTo = available
149
+ const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, available / box.width))
150
+ input.canvas.style.width = `${Math.floor(box.width * scale)}px`
151
+ input.canvas.style.height = `${Math.ceil(box.height * scale)}px`
152
+ canvas.resized()
153
+ canvas.viewbox(box)
123
154
  }
124
- canvas.zoom("fit-viewport")
125
- // Fitting puts the outermost shapes on the box's edge; a margin keeps the start and end circles and their badges whole.
126
- const fitted = canvas.viewbox()
127
- canvas.viewbox({ x: fitted.x - VIEW_MARGIN, y: fitted.y - VIEW_MARGIN, width: fitted.width + 2 * VIEW_MARGIN, height: fitted.height + 2 * VIEW_MARGIN })
155
+ fitToWidth()
156
+ const parentResized = new ResizeObserver(() => fitToWidth())
157
+ if (input.canvas.parentElement !== null) parentResized.observe(input.canvas.parentElement)
128
158
 
129
159
  let selected: DiagramElement | null = null
130
160
  const close = () => {
@@ -185,6 +215,7 @@ export const drawWorkflow = async (input: {
185
215
  if (selected !== null) void show(selected)
186
216
  },
187
217
  destroy: () => {
218
+ parentResized.disconnect()
188
219
  input.canvas.removeEventListener("click", onBadge)
189
220
  viewer.destroy()
190
221
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jive-sh/workflow-platform",
3
- "version": "1.4.0",
3
+ "version": "1.4.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Durable workflows in Convex: one workflow primitive with a task schema, queues on every line, workflow budgets, named end states, events and sub-workflows; worker processes run the steps.",
package/worker/index.ts CHANGED
@@ -7,6 +7,7 @@ export {
7
7
  type ReportedOtherWrite,
8
8
  type TakenStep,
9
9
  type WorkerFunctions,
10
+ type WorkflowBudgets,
10
11
  WorkflowPlatformClient,
11
12
  } from "./platform-client"
12
13
  export { type ServicesOfWorkflows, WorkerLacksService, type WorkerOptions, type WorkerServices, type WorkResult, workForever, workOnce, workUntilIdle } from "./worker"
@@ -1,6 +1,6 @@
1
1
  import type { ConvexHttpClient } from "convex/browser"
2
2
  import type { FunctionReference } from "convex/server"
3
- import { Context, Data, Effect, Schema } from "effect"
3
+ import { Context, Data, Effect, Option, Schema } from "effect"
4
4
  import type { FoundTask, TasksAt } from "../src/definition/tasks"
5
5
  import type { StepMeasurements, TaskFile } from "../src/graph"
6
6
 
@@ -65,8 +65,23 @@ export interface CompleteInput {
65
65
  readonly others?: ReadonlyArray<ReportedOtherWrite>
66
66
  }
67
67
 
68
+ const WorkflowBudgets = Schema.Array(
69
+ Schema.Struct({ workflow: Schema.String, budgets: Schema.NullOr(Schema.Struct({ agents: Schema.Number, cpu: Schema.Number })) }),
70
+ )
71
+ /** Each workflow's budget limits as registered, or null for one not registered. */
72
+ export type WorkflowBudgets = typeof WorkflowBudgets.Type
73
+ const decodeBudgets = Schema.decodeUnknownEffect(WorkflowBudgets)
74
+
68
75
  /** What a worker asks of the workflow platform in Convex: take a task, report on it, and read other tasks for its run. */
69
76
  export interface IWorkflowPlatformClient {
77
+ /**
78
+ * Each workflow's budget limits, so a worker asks `take` only for steps a budget can admit. Every component call in
79
+ * `take` costs tens of milliseconds, and `take` makes one per workflow it is given, so asking for all 30 of a
80
+ * workforce's workflows held each take near a second while nothing could run (2026-11-29). The workforce's `budgets`
81
+ * query reads only the workflow rows, which change only when a workflow registers or its budgets are set, so Convex
82
+ * answers it from its cache. None when the workforce has no `budgets` function: the worker then asks for every step.
83
+ */
84
+ budgets(): Effect.fn.Return<Option.Option<WorkflowBudgets>, PlatformCallFailed>
70
85
  take(input: { readonly worker: string; readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>; readonly leaseMs: number }): Effect.fn.Return<TakenStep | null, PlatformCallFailed>
71
86
  complete(input: CompleteInput): Effect.fn.Return<void, PlatformCallFailed>
72
87
  fail(input: { readonly workflow: string; readonly run: string; readonly error: string; readonly measurements: StepMeasurements }): Effect.fn.Return<void, PlatformCallFailed>
@@ -91,6 +106,8 @@ export interface WorkerFunctions {
91
106
  readonly fail: FunctionReference<"mutation">
92
107
  readonly heartbeat: FunctionReference<"mutation">
93
108
  readonly findTasks: FunctionReference<"query">
109
+ /** Each workflow's budget limits (`IWorkflowPlatformClient.budgets`); a workforce without it is asked for every step. */
110
+ readonly budgets?: FunctionReference<"query">
94
111
  }
95
112
 
96
113
  export class ConvexWorkflowPlatformClient implements IWorkflowPlatformClient {
@@ -99,13 +116,23 @@ export class ConvexWorkflowPlatformClient implements IWorkflowPlatformClient {
99
116
  private readonly functions: WorkerFunctions,
100
117
  ) {}
101
118
 
102
- private call(name: Exclude<keyof WorkerFunctions, "findTasks">, args: Record<string, unknown>) {
119
+ private call(name: Exclude<keyof WorkerFunctions, "findTasks" | "budgets">, args: Record<string, unknown>) {
103
120
  return Effect.tryPromise({
104
121
  try: (): Promise<unknown> => this.client.mutation(this.functions[name], args),
105
122
  catch: (cause) => new PlatformCallFailed({ call: name, cause }),
106
123
  })
107
124
  }
108
125
 
126
+ *budgets() {
127
+ const maybeBudgets = Option.fromUndefinedOr(this.functions.budgets)
128
+ if (Option.isNone(maybeBudgets)) return Option.none<WorkflowBudgets>()
129
+ const read = yield* Effect.tryPromise({
130
+ try: (): Promise<unknown> => this.client.query(maybeBudgets.value, {}),
131
+ catch: (cause) => new PlatformCallFailed({ call: "budgets", cause }),
132
+ })
133
+ return Option.some(yield* Effect.mapError(decodeBudgets(read), (cause) => new PlatformCallFailed({ call: "budgets", cause })))
134
+ }
135
+
109
136
  *take(input: { readonly worker: string; readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>; readonly leaseMs: number }) {
110
137
  const taken = yield* this.call("take", { ...input, steps: [...input.steps] })
111
138
  return yield* Effect.mapError(decodeTaken(taken), (cause) => new PlatformCallFailed({ call: "take", cause }))
@@ -1,12 +1,12 @@
1
1
  import { describe, expect, test } from "bun:test"
2
- import { Effect, pipe, Schema } from "effect"
2
+ import { Effect, Option, pipe, Schema } from "effect"
3
3
  import { AgentRunFailed, AgentRunner } from "../src/definition/agent-runner"
4
4
  import { FileStore, FileStoreError } from "../src/definition/file-store"
5
5
  import * as TaskSchema from "../src/definition/task-schema"
6
6
  import * as Workflow from "../src/definition/workflow"
7
7
  import { problemsOf, type StepMeasurements, type TaskFile } from "../src/graph"
8
- import { type IWorkflowPlatformClient, PlatformCallFailed, type TakenStep, WorkflowPlatformClient } from "./platform-client"
9
- import { workOnce } from "./worker"
8
+ import { type IWorkflowPlatformClient, PlatformCallFailed, type TakenStep, type WorkflowBudgets, WorkflowPlatformClient } from "./platform-client"
9
+ import { admittedSteps, workOnce } from "./worker"
10
10
 
11
11
  const counted = Workflow.make({
12
12
  name: "counted",
@@ -36,8 +36,17 @@ const timedOut = (call: string) => new PlatformCallFailed({ call, cause: "Functi
36
36
  class FakePlatform implements IWorkflowPlatformClient {
37
37
  readonly calls: Array<string> = []
38
38
  readonly failures: Array<string> = []
39
- constructor(private readonly answers: { readonly complete: boolean; readonly fail: boolean }) {}
40
- *take() {
39
+ readonly takes: Array<ReadonlyArray<{ readonly workflow: string; readonly step: string }>> = []
40
+ constructor(
41
+ private readonly answers: { readonly complete: boolean; readonly fail: boolean },
42
+ private readonly budgetsRead: Option.Option<WorkflowBudgets> | "fails" = Option.none(),
43
+ ) {}
44
+ *budgets() {
45
+ if (this.budgetsRead === "fails") return yield* Effect.fail(timedOut("budgets"))
46
+ return this.budgetsRead
47
+ }
48
+ *take(input: { readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }> }) {
49
+ this.takes.push(input.steps)
41
50
  return taken
42
51
  }
43
52
  *complete() {
@@ -90,6 +99,35 @@ describe("a worker reporting to a platform that times out", () => {
90
99
  })
91
100
  })
92
101
 
102
+ describe("asking take only where a budget can admit", () => {
103
+ const budgetsOf = (cpu: number) => Option.some([{ workflow: "counted", budgets: { agents: 0, cpu } }])
104
+
105
+ test("a workflow held at 0 is not asked about: the worker is idle without a take", async () => {
106
+ const platform = new FakePlatform({ complete: true, fail: true }, budgetsOf(0))
107
+ expect(await workWith(platform)).toEqual({ _tag: "Idle" })
108
+ expect(platform.takes).toEqual([])
109
+ })
110
+
111
+ test("a workflow whose budget admits its step is asked about", async () => {
112
+ const platform = new FakePlatform({ complete: true, fail: true }, budgetsOf(1))
113
+ expect((await workWith(platform))._tag).toBe("Ran")
114
+ expect(platform.takes).toEqual([[{ workflow: "counted", step: "count" }]])
115
+ })
116
+
117
+ test("with no budgets function, or a failed read, every step is asked about", async () => {
118
+ for (const read of [Option.none<WorkflowBudgets>(), "fails" as const]) {
119
+ const platform = new FakePlatform({ complete: true, fail: true }, read)
120
+ expect((await workWith(platform))._tag).toBe("Ran")
121
+ expect(platform.takes).toEqual([[{ workflow: "counted", step: "count" }]])
122
+ }
123
+ })
124
+
125
+ test("an agent step is kept by the agents' budget, and an unregistered workflow keeps its steps", () => {
126
+ const steps = [{ workflow: "counted", step: "count" }, { workflow: "other", step: "think" }]
127
+ expect(admittedSteps({ steps, workflows: [counted], budgets: Option.some([{ workflow: "counted", budgets: { agents: 1, cpu: 0 } }, { workflow: "other", budgets: null }]) })).toEqual([{ workflow: "other", step: "think" }])
128
+ })
129
+ })
130
+
93
131
  describe("what a step may use", () => {
94
132
  /** A step that asks for the agent runner; whether it declared it decides whether it compiles and whether it gets it. */
95
133
  const asksForAgents = function* () {
package/worker/worker.ts CHANGED
@@ -4,8 +4,8 @@ import { FileStore } from "../src/definition/file-store"
4
4
  import { ProgramBuild } from "../src/definition/program-build"
5
5
  import { Tasks } from "../src/definition/tasks"
6
6
  import type { WorkflowDefinition } from "../src/definition/workflow"
7
- import { nothingUsed, noSpend, type StepMeasurements, type TaskFile } from "../src/graph"
8
- import { type PlatformCallFailed, type ReportedOtherWrite, type TakenStep, WorkflowPlatformClient } from "./platform-client"
7
+ import { budgetOfStepKind, nothingUsed, noSpend, type StepMeasurements, type TaskFile } from "../src/graph"
8
+ import { type PlatformCallFailed, type ReportedOtherWrite, type TakenStep, type WorkflowBudgets, WorkflowPlatformClient } from "./platform-client"
9
9
  import { StepMeter } from "./step-meter"
10
10
  import { RunTasks } from "./worker-tasks"
11
11
 
@@ -51,6 +51,27 @@ const checkServices = function* (input: { readonly workflows: ReadonlyArray<Work
51
51
  }
52
52
  }
53
53
 
54
+ /**
55
+ * Of `steps`, those whose workflow's budget for the step's kind is above 0, so `take` is asked only where it can give
56
+ * a task: each workflow it is asked about costs it a component call. A workflow with no budgets on record (not
57
+ * registered) keeps its steps, so `take` says why; with no budgets read at all, every step is kept. Pure.
58
+ */
59
+ export const admittedSteps = (input: {
60
+ readonly steps: ReadonlyArray<{ readonly workflow: string; readonly step: string }>
61
+ readonly workflows: ReadonlyArray<WorkflowDefinition<any, any, any>>
62
+ readonly budgets: Option.Option<WorkflowBudgets>
63
+ }): ReadonlyArray<{ readonly workflow: string; readonly step: string }> => {
64
+ if (Option.isNone(input.budgets)) return input.steps
65
+ const limits = new Map(input.budgets.value.map((row) => [row.workflow, row.budgets]))
66
+ return input.steps.filter(({ workflow, step }) => {
67
+ const budgets = limits.get(workflow)
68
+ if (budgets === undefined || budgets === null) return true
69
+ const kind = input.workflows.find((w) => w.name === workflow)?.graph.steps.find((s) => s.id === step)?.kind
70
+ const budget = kind === undefined ? "none" : budgetOfStepKind(kind)
71
+ return budget !== "none" && budgets[budget] > 0
72
+ })
73
+ }
74
+
54
75
  /**
55
76
  * Takes one task from Convex, runs its step with only the services the step declares, and reports the end state with
56
77
  * the task's changed fields and files and the step's writes to other tasks. A step that fails or dies is reported as
@@ -70,7 +91,12 @@ const runOnce = function* <Services>(input: {
70
91
  }): Effect.fn.Return<WorkResult, unknown, WorkerServices<Services>> {
71
92
  const options = input.options
72
93
  const client = yield* WorkflowPlatformClient
73
- const steps = options.workflows.flatMap((workflow) => Object.keys(workflow.runnableSteps).map((step) => ({ workflow: workflow.name, step })))
94
+ const all = options.workflows.flatMap((workflow) => Object.keys(workflow.runnableSteps).map((step) => ({ workflow: workflow.name, step })))
95
+ // A budgets read that fails costs only the saving: every step is asked for, as before it existed.
96
+ const read = yield* Effect.result(Effect.gen(() => client.budgets()))
97
+ if (Result.isFailure(read)) yield* Effect.logWarning(`worker ${options.worker} could not read the budgets, so it asks for every step: ${read.failure.message}`)
98
+ const steps = admittedSteps({ steps: all, workflows: options.workflows, budgets: Result.isSuccess(read) ? read.success : Option.none() })
99
+ if (steps.length === 0) return { _tag: "Idle" }
74
100
  // Workers racing for one queue head can exhaust Convex's own retries; the loser asks again after a jittered wait,
75
101
  // for about 5 seconds in all, since a loaded machine can take a second over each take.
76
102
  const taken = yield* pipe(