@jive-sh/workflow-platform 0.1.0 → 0.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.
Files changed (40) hide show
  1. package/README.md +41 -15
  2. package/dist/cpu-limit/limiter.js +54 -11
  3. package/dist/cpu-limit/limiter.js.map +1 -1
  4. package/dist/index.js +44 -39
  5. package/dist/index.js.map +1 -1
  6. package/dist/keep-running.js +5 -5
  7. package/dist/keep-running.js.map +1 -1
  8. package/dist/pick-wakes.js +7 -1
  9. package/dist/pick-wakes.js.map +1 -1
  10. package/dist/queue-counts.js +47 -0
  11. package/dist/queue-counts.js.map +1 -0
  12. package/dist/steps.js +75 -18
  13. package/dist/steps.js.map +1 -1
  14. package/dist/storage/budgets.js +14 -0
  15. package/dist/storage/budgets.js.map +1 -1
  16. package/dist/storage/sqlite-store.js +68 -15
  17. package/dist/storage/sqlite-store.js.map +1 -1
  18. package/dist/views/workflow-flows.js +53 -0
  19. package/dist/views/workflow-flows.js.map +1 -0
  20. package/dist/views/workflows-view.js +81 -55
  21. package/dist/views/workflows-view.js.map +1 -1
  22. package/package.json +1 -1
  23. package/src/cpu-limit/limiter.ts +61 -11
  24. package/src/dashboard/dashboard.css +78 -0
  25. package/src/dashboard/index.tsx +3 -0
  26. package/src/dashboard/queue-chart.tsx +137 -0
  27. package/src/dashboard/step-graph.tsx +98 -0
  28. package/src/dashboard/workflow-dag.tsx +256 -0
  29. package/src/dashboard/workflows-dashboard.tsx +313 -0
  30. package/src/index.ts +46 -39
  31. package/src/keep-running.ts +5 -7
  32. package/src/pick-wakes.ts +9 -2
  33. package/src/queue-counts.ts +61 -0
  34. package/src/steps.ts +83 -26
  35. package/src/storage/budgets.ts +13 -0
  36. package/src/storage/sqlite-store.ts +82 -18
  37. package/src/storage/step-records.ts +6 -5
  38. package/src/storage/task-store.ts +32 -0
  39. package/src/views/workflow-flows.ts +97 -0
  40. package/src/views/workflows-view.ts +148 -82
@@ -182,8 +182,26 @@ const SHORTEST_WINDOW_SECONDS = 2;
182
182
  const LONGEST_WINDOW_SECONDS = 120;
183
183
  /** How old a reading of project work may be for the line to go by it. */
184
184
  const READ_USE_EVERY_SECONDS = 5;
185
+ /** How long one reading may take (`readLight`'s cap): a process waits this long before it starts one beside another's. */
186
+ const READING_TAKES_AT_MOST_SECONDS = 30;
185
187
  const PS_USE = ['ps', '-Ao', 'pid=,pgid=,%cpu=,time=,command='];
186
188
 
189
+ /** Whether `folder` is `root` or below it. Pure. */
190
+ const runsUnder = (folder: string, root: string): boolean => folder === root || folder.startsWith(`${root}/`);
191
+
192
+ /**
193
+ * Which of `pids` have their working directory in `root` or below it, from the link Linux serves for each (`<proc>/<pid>/cwd`).
194
+ * A process that ended since it was listed, or another user's, has no link this process can read, and is not counted.
195
+ */
196
+ export const pidsRunningUnder = (pids: ReadonlyArray<number>, root: string, proc = '/proc'): ReadonlySet<number> =>
197
+ new Set(pids.filter((pid) => {
198
+ try {
199
+ return runsUnder(fs.readlinkSync(path.join(proc, String(pid), 'cwd')), root);
200
+ } catch {
201
+ return false;
202
+ }
203
+ }));
204
+
187
205
  const alive = (pid: number): boolean => {
188
206
  try {
189
207
  process.kill(pid, 0);
@@ -414,7 +432,7 @@ export const makeCpuLimiter = (facts: CpuLimiterFacts) => {
414
432
  let pid = 0;
415
433
  for (const line of lsof.split('\n')) {
416
434
  if (line.startsWith('p')) pid = Number(line.slice(1));
417
- if (line.startsWith('n') && (line.slice(1) === facts.projectRoot || line.startsWith(`n${facts.projectRoot}/`))) found.add(pid);
435
+ if (line.startsWith('n') && runsUnder(line.slice(1), facts.projectRoot)) found.add(pid);
418
436
  }
419
437
  return found;
420
438
  };
@@ -465,24 +483,56 @@ export const makeCpuLimiter = (facts: CpuLimiterFacts) => {
465
483
  return { ps: measured.lines, busy };
466
484
  };
467
485
 
486
+ /**
487
+ * WHICH OF THE BUSY PIDS RUN IN THE PROJECT'S FOLDERS, by how this system tells where a process runs. Linux serves each
488
+ * process's working directory as a link, read in this process with nothing started (`pidsRunningUnder`). macOS has no such
489
+ * link, so `lsof` is asked there. Asking `lsof` on Linux was the machine's whole load at 16:24-16:27 UTC on 2026-11-17:
490
+ * 0.35 s for one pid on a quiet machine and 10 to 20 s on a busy one, 14 going at once (one per process waiting for a
491
+ * slot), each a busy pid the next reading asked about; load 12.4 on 4 threads, 65-72% of it in the kernel.
492
+ */
493
+ const projectPids: {
494
+ readonly now: (busy: ReadonlyArray<number>) => ReadonlySet<number>;
495
+ readonly later: (busy: ReadonlyArray<number>) => Promise<ReadonlySet<number>>;
496
+ } = process.platform === 'linux'
497
+ ? { now: (busy) => pidsRunningUnder(busy, facts.projectRoot), later: async (busy) => pidsRunningUnder(busy, facts.projectRoot) }
498
+ : {
499
+ now: (busy) => (busy.length === 0 ? new Set<number>() : inProjectFrom(runLightNow(cwdOf(busy)).stdout)),
500
+ later: async (busy) => (busy.length === 0 ? new Set<number>() : inProjectFrom(await readLight(cwdOf(busy)))),
501
+ };
502
+
468
503
  /** What the machine, the service's group and project work are using now: over the time since this process last read it. */
469
504
  const useNow = (serviceGroup: number): ProjectUse => {
470
505
  const { ps, busy } = measure(runLightNow(PS_USE).stdout);
471
- const inProject = busy.length === 0 ? new Set<number>() : inProjectFrom(runLightNow(cwdOf(busy)).stdout);
506
+ const inProject = projectPids.now(busy);
472
507
  return readUse(ps, serviceGroup, (pid) => inProject.has(pid), facts.kinds);
473
508
  };
474
509
 
475
510
  /** `useNow`, read without holding this thread (`readLight`). */
476
511
  const useLater = async (serviceGroup: number): Promise<ProjectUse> => {
477
512
  const { ps, busy } = measure(await readLight(PS_USE));
478
- const inProject = busy.length === 0 ? new Set<number>() : inProjectFrom(await readLight(cwdOf(busy)));
513
+ const inProject = await projectPids.later(busy);
479
514
  return readUse(ps, serviceGroup, (pid) => inProject.has(pid), facts.kinds);
480
515
  };
481
516
 
482
517
  /**
483
- * What project work uses now, in threads, for the line: read at most every 5 seconds, by whichever process is waiting, and
484
- * shared through the pool. The service's group is the one its newest stored reading named. Only the live pool reads the
485
- * system: a test's pool goes by what its test stored, or by the count alone. None when it cannot be read.
518
+ * Reads what project work uses and stores it for the line, without holding this thread (`useLater`): one reading at a
519
+ * time across every process of the pool, claimed in the pool before it starts.
520
+ */
521
+ const storeProjectUse = async (serviceGroup: number): Promise<ProjectUse> => {
522
+ setSetting('project_use_reading', String(Date.now() / 1000));
523
+ const use = await useLater(serviceGroup);
524
+ setSetting('project_use', JSON.stringify({ at: Date.now() / 1000, cores: use.project }));
525
+ return use;
526
+ };
527
+
528
+ /**
529
+ * What project work uses, in threads, for the line: THE STORED READING, NEVER A READ OF THE SYSTEM HERE. The line's look
530
+ * runs on the thread of whichever process waits, the one answering requests included, and `ps` plus `lsof` on a busy
531
+ * machine take 10 s and more: read here, they held the API worker 10 to 14 s at a time whenever anything waited
532
+ * (2026-11-17). The service stores a reading every tick (`holdToTheLimit`); with that one older than 5 seconds a waiting
533
+ * process starts one of its own off the thread, unless another process started one in the last 30 seconds, and goes by
534
+ * the last reading meanwhile. Only the live pool reads the system: a test's pool goes by what its test stored, or by the
535
+ * count alone. None when there is none yet.
486
536
  */
487
537
  const projectUseNow = (): { readonly at: number; readonly cores: number } | null => {
488
538
  try {
@@ -490,9 +540,10 @@ export const makeCpuLimiter = (facts: CpuLimiterFacts) => {
490
540
  const last = stored === null ? null : (JSON.parse(stored) as { at: number; cores: number });
491
541
  const now = Date.now() / 1000;
492
542
  if (facts.poolFile() !== facts.livePool || (last !== null && now - last.at < READ_USE_EVERY_SECONDS)) return last;
493
- const reading = { at: now, cores: useNow(Number(setting('service_group') ?? -1)).project };
494
- setSetting('project_use', JSON.stringify(reading));
495
- return reading;
543
+ if (now - Number(setting('project_use_reading') ?? 0) >= READING_TAKES_AT_MOST_SECONDS) {
544
+ void storeProjectUse(Number(setting('service_group') ?? -1)).catch((e) => console.error(`[cpu slots] could not read project work's use: ${e instanceof Error ? e.message : String(e)}`));
545
+ }
546
+ return last;
496
547
  } catch (e) {
497
548
  console.error(`[cpu slots] could not read project work's use: ${e instanceof Error ? e.message : String(e)}`);
498
549
  return null;
@@ -822,8 +873,7 @@ export const makeCpuLimiter = (facts: CpuLimiterFacts) => {
822
873
  async function tick(): Promise<void> {
823
874
  try {
824
875
  if (facts.stopped()) return resumeAll();
825
- const using = (await useLater(serviceGroup)).project;
826
- setSetting('project_use', JSON.stringify({ at: Date.now() / 1000, cores: using }));
876
+ const using = (await storeProjectUse(serviceGroup)).project;
827
877
  // Each slot's own use, from the CPU time its processes used since the tick before.
828
878
  const ps = await readLight(['ps', '-Ao', 'pid=,ppid=,time=']);
829
879
  const db = pool();
@@ -0,0 +1,78 @@
1
+ /* The workflow platform's dashboard. Colours come from the host page's variables, with these where it has none. */
2
+ /*
3
+ * The host page's colours, light or dark as it is, with these where it has none. Muted text, edges and node borders are mixed
4
+ * from its foreground toward its background, so they keep strong contrast in either theme.
5
+ */
6
+ .wp-page {
7
+ --wp-fg: var(--fg, #e9edf5); --wp-bg: var(--bg, #0f1218); --wp-node: var(--panel, #151a23);
8
+ --wp-dim: color-mix(in srgb, var(--wp-fg) 74%, var(--wp-bg)); --wp-line: color-mix(in srgb, var(--wp-fg) 18%, var(--wp-bg));
9
+ --wp-edge: color-mix(in srgb, var(--wp-fg) 78%, var(--wp-bg)); --wp-node-line: color-mix(in srgb, var(--wp-fg) 40%, var(--wp-bg));
10
+ --wp-warn: var(--warn, #e2574c); --wp-ok: var(--ok, #49c57f);
11
+ --wp-band: color-mix(in srgb, var(--wp-fg) 5%, var(--wp-bg));
12
+ }
13
+ .wp-line { margin: 6px 0; }
14
+ .wp-mut { color: var(--wp-dim); }
15
+ .wp-bad { color: var(--wp-warn); }
16
+ .wp-r { text-align: right; white-space: nowrap; }
17
+ .wp-phase { margin-top: 28px; }
18
+ .wp-h2 { font-size: 11px; text-transform: uppercase; letter-spacing: 0.08em; border-bottom: 1px solid var(--wp-line); padding-bottom: 4px; margin: 0 0 6px; }
19
+ .wp-h4 { font-size: 11px; color: var(--wp-dim); margin: 12px 0 2px; font-weight: normal; }
20
+ .wp-workflow { border-bottom: 1px solid var(--wp-line); padding: 4px 0; }
21
+ .wp-workflow > summary { cursor: pointer; display: flex; flex-wrap: wrap; gap: 4px 14px; align-items: baseline; }
22
+ .wp-workflow > summary a { color: var(--wp-fg); }
23
+ .wp-count { color: var(--wp-ok); }
24
+ .wp-tablewrap { overflow-x: auto; }
25
+ .wp-table { border-collapse: collapse; width: 100%; margin: 4px 0; }
26
+ .wp-table th { color: var(--wp-dim); font-weight: normal; text-align: left; padding: 2px 8px 2px 0; border-bottom: 1px solid var(--wp-line); }
27
+ .wp-table td { padding: 2px 8px 2px 0; vertical-align: top; }
28
+ .wp-total td { border-top: 1px solid var(--wp-line); }
29
+ .wp-limit { display: inline-flex; gap: 4px; align-items: baseline; }
30
+ .wp-limit button { background: none; color: var(--wp-fg); border: 1px solid var(--wp-line); border-radius: 3px; padding: 0 6px; cursor: pointer; font: inherit; }
31
+ .wp-limit button:disabled { color: var(--wp-dim); cursor: default; }
32
+
33
+ .wp-h3 { font-size: 13px; margin: 4px 0; }
34
+ /* The queues' chart: small type, thin lines. */
35
+ .wp-chart { margin: 14px 0 6px; }
36
+ .wp-chart-head { display: flex; flex-wrap: wrap; gap: 4px 12px; align-items: baseline; font-size: 12px; }
37
+ .wp-chart-choose summary { cursor: pointer; color: var(--wp-dim); }
38
+ .wp-chart-options { display: flex; flex-wrap: wrap; gap: 6px 18px; padding: 6px 0; font-size: 12px; }
39
+ .wp-chart-options > div { display: flex; flex-wrap: wrap; gap: 2px 8px; align-items: baseline; }
40
+ .wp-chart-options > div > span { color: var(--wp-fg); }
41
+ .wp-chart-options label { color: var(--wp-dim); white-space: nowrap; }
42
+ .wp-chart-box { width: 100%; overflow: hidden; }
43
+ /* The DAG: one node per workflow, rows by stage, edges drawn under the nodes. */
44
+ /* The map: laid out by ELK, its nodes placed where it says, scrolled sideways where it is wider than the page. */
45
+ .wp-dag-scroll { overflow-x: auto; overflow-y: hidden; }
46
+ .wp-dag { position: relative; min-height: 40px; }
47
+ .wp-band-name { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--wp-fg); line-height: 1.35; }
48
+ .wp-dag-edges { position: absolute; left: 0; top: 0; pointer-events: none; z-index: 0; }
49
+ .wp-stage { position: relative; margin-top: 18px; }
50
+ .wp-nodes { display: flex; flex-wrap: wrap; gap: 26px 22px; padding: 6px 0 30px; }
51
+ .wp-node { position: relative; z-index: 1; background: var(--wp-node); border: 1px solid var(--wp-node-line); border-radius: 6px; padding: 7px 9px; width: 250px; font-size: 12px; color: var(--wp-fg); }
52
+ .wp-node-open { border-color: var(--wp-fg); }
53
+ .wp-node-head { display: flex; justify-content: space-between; align-items: baseline; gap: 6px; }
54
+ .wp-node-name { background: none; border: none; color: var(--wp-fg); font: inherit; font-size: 13px; font-weight: 600; padding: 0; cursor: pointer; text-align: left; }
55
+ /* What it does in two lines and what starts it in one; the whole of each in its hover. */
56
+ .wp-node-what { margin: 3px 0; line-height: 1.3; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
57
+ .wp-node-starts { font-size: 11px; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
58
+ .wp-node-flows { font-size: 11px; line-height: 1.3; }
59
+ .wp-node-flows { display: flex; flex-direction: column; }
60
+ .wp-node-status { display: flex; flex-wrap: wrap; gap: 2px 10px; align-items: baseline; margin-top: 4px; font-size: 11px; }
61
+ .wp-node-detail { position: relative; z-index: 1; background: var(--wp-bg); border: 1px solid var(--wp-node-line); border-radius: 6px; padding: 8px 10px; margin: 0 0 24px; }
62
+ /* A queue's bar: segments told apart by lightness, and every count also in words below it. */
63
+ .wp-queue { margin-top: 5px; }
64
+ .wp-bar { display: flex; height: 7px; border-radius: 2px; overflow: hidden; background: var(--wp-line); }
65
+ .wp-seg-done { background: var(--wp-ok); }
66
+ .wp-seg-running { background: var(--wp-fg); }
67
+ .wp-seg-queued { background: color-mix(in srgb, var(--wp-fg) 50%, var(--wp-bg)); }
68
+ .wp-seg-rest { background: color-mix(in srgb, var(--wp-fg) 28%, var(--wp-bg)); }
69
+ .wp-queue-words { font-size: 11px; margin-top: 2px; }
70
+
71
+ /* One workflow's step graph, small: rows of steps, numbered arrows, the numbers' conditions below. */
72
+ .wp-steps-box { position: relative; display: inline-block; min-width: 260px; padding: 4px 0; margin-right: 240px; }
73
+ .wp-steps-edges { position: absolute; left: 0; top: 0; pointer-events: none; overflow: visible; }
74
+ .wp-steps-row { position: relative; display: flex; flex-wrap: wrap; gap: 8px 14px; margin: 0 0 14px; }
75
+ .wp-step { position: relative; z-index: 1; background: var(--wp-node); border: 1px solid var(--wp-node-line); border-radius: 4px; padding: 2px 7px; font-size: 11px; color: var(--wp-fg); }
76
+ .wp-step em { font-style: normal; color: var(--wp-ok); }
77
+ .wp-step-end { border-style: dashed; color: var(--wp-dim); }
78
+ .wp-steps-when { margin: 0 0 6px 18px; padding: 0; font-size: 11px; color: var(--wp-dim); }
@@ -0,0 +1,3 @@
1
+ /** The workflow platform's dashboard: React components for any project's workflows, and how they write figures. */
2
+ export { usePolledJson, WorkflowsDashboard, type LimitName, type SetLimit, type WorkflowsDashboardProps, type WorkflowsPageData } from './workflows-dashboard';
3
+ export { clockTime, compact, duration, localTime, whenAgo } from '../views/format';
@@ -0,0 +1,137 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * EACH QUEUE OVER TIME, small: the tasks of a workflow in one bucket (queued, done, …) as a thin line, every line named in
5
+ * words at its end and in the key, and told apart by its dash as well as its shade, never by colour alone. Which lines show
6
+ * is the reader's choice, kept in this browser. Reads only the platform's view: its `queueHistory`, a row where a count moved,
7
+ * and each workflow's queue now.
8
+ */
9
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
10
+ import type { QueueCount } from '../storage/task-store';
11
+ import type { WorkflowsView } from '../views/workflows-view';
12
+ import { localTime } from '../views/format';
13
+
14
+ /** A line: one workflow's tasks in one bucket. */
15
+ interface Series {
16
+ readonly key: string;
17
+ readonly workflow: string;
18
+ readonly bucket: string;
19
+ readonly points: ReadonlyArray<{ readonly at: number; readonly tasks: number }>;
20
+ readonly now: number;
21
+ }
22
+
23
+ const STORED_CHOICE = 'workflow-platform.queue-chart.lines';
24
+ /** Lines shown before the reader chooses: the queues that finished most. */
25
+ const SHOWN_AT_FIRST = 3;
26
+ const DASHES = ['', '5 3', '1.5 2.5', '7 2 1.5 2', '3 3'];
27
+ /** The host page's colours, so a line keeps its contrast in a light theme and a dark one alike. */
28
+ const SHADES = ['var(--wp-fg)', 'var(--wp-ok)', 'var(--accent, #5aa9e6)', 'var(--near, #dfa33c)', 'var(--wp-dim)'];
29
+
30
+ const keyOf = (workflow: string, bucket: string) => `${workflow} · ${bucket}`;
31
+
32
+ /** Every queue and bucket as a line: its recorded changes, then its count now. Pure. */
33
+ export const queueSeries = (view: WorkflowsView): ReadonlyArray<Series> =>
34
+ view.groups.flatMap((g) => g.workflows).flatMap((w) => (w.queue === null ? [] : Object.entries(w.queue).map(([bucket, now]) => ({
35
+ key: keyOf(w.name, bucket), workflow: w.name, bucket, now,
36
+ points: [...view.queueHistory.filter((r: QueueCount) => r.workflow === w.name && r.bucket === bucket).map((r) => ({ at: r.at, tasks: r.tasks })), { at: view.at, tasks: now }],
37
+ }))));
38
+
39
+ const readChoice = (): ReadonlyArray<string> | null => {
40
+ try {
41
+ const stored = window.localStorage.getItem(STORED_CHOICE);
42
+ return stored === null ? null : (JSON.parse(stored) as ReadonlyArray<string>);
43
+ } catch {
44
+ return null;
45
+ }
46
+ };
47
+
48
+ export function QueueChart({ view }: { readonly view: WorkflowsView }) {
49
+ const all = queueSeries(view);
50
+ const [chosen, setChosen] = useState<ReadonlyArray<string> | null>(null);
51
+ useEffect(() => setChosen(readChoice()), []);
52
+ const shownAtFirst = [...all].filter((s) => s.bucket === 'done' && s.now > 0).sort((a, b) => b.now - a.now).slice(0, SHOWN_AT_FIRST).map((s) => s.key);
53
+ const shownKeys = chosen ?? shownAtFirst;
54
+ const shown = all.filter((s) => shownKeys.includes(s.key));
55
+ const choose = (key: string, on: boolean) => {
56
+ const next = on ? [...shownKeys, key] : shownKeys.filter((k) => k !== key);
57
+ setChosen(next);
58
+ try { window.localStorage.setItem(STORED_CHOICE, JSON.stringify(next)); } catch { /* A browser that keeps nothing shows the first lines again. */ }
59
+ };
60
+
61
+ // Drawn at the width it is given, so its type stays small and sharp on a phone and a desktop alike.
62
+ const box = useRef<HTMLDivElement>(null);
63
+ const [width, setWidth] = useState(600);
64
+ useLayoutEffect(() => {
65
+ const el = box.current;
66
+ if (el === null) return;
67
+ const measure = () => setWidth(Math.max(280, el.clientWidth));
68
+ measure();
69
+ const watch = new ResizeObserver(measure);
70
+ watch.observe(el);
71
+ return () => watch.disconnect();
72
+ }, []);
73
+
74
+ const H = 120;
75
+ const P = { t: 8, r: 200, b: 18, l: 40 };
76
+ const from = Math.min(view.at - 3600, ...shown.flatMap((s) => s.points.map((p) => p.at)));
77
+ const max = Math.max(1, ...shown.flatMap((s) => s.points.map((p) => p.tasks)));
78
+ const X = (t: number) => P.l + ((t - from) / Math.max(1, view.at - from)) * (width - P.l - P.r);
79
+ const Y = (v: number) => H - P.b - (v / max) * (H - P.t - P.b);
80
+ // Each line's name at its end, moved apart so no two overlap.
81
+ const ends = shown.map((s, i) => ({ s, i, y: Y(s.now) })).sort((a, b) => a.y - b.y);
82
+ for (let k = 1; k < ends.length; k += 1) ends[k]!.y = Math.max(ends[k]!.y, ends[k - 1]!.y + 11);
83
+ const recordedSince = view.queueHistory.length === 0 ? null : view.queueHistory[0]!.at;
84
+
85
+ return (
86
+ <section className="wp-chart" aria-label="Each queue over time">
87
+ <div className="wp-chart-head">
88
+ <span>Queues over time</span>
89
+ <span className="wp-mut">{recordedSince === null ? 'recorded from now on, each time the figures are built' : `recorded since ${localTime(recordedSince)}`}</span>
90
+ <details className="wp-chart-choose">
91
+ <summary>choose lines ({shown.length} of {all.length})</summary>
92
+ <div className="wp-chart-options">
93
+ {[...new Set(all.map((s) => s.workflow))].map((workflow) => (
94
+ <div key={workflow}>
95
+ <span>{workflow}</span>
96
+ {all.filter((s) => s.workflow === workflow).map((s) => (
97
+ <label key={s.key}>
98
+ <input type="checkbox" checked={shownKeys.includes(s.key)} onChange={(e) => choose(s.key, e.target.checked)} />
99
+ {s.bucket} {s.now.toLocaleString('en-US')}
100
+ </label>
101
+ ))}
102
+ </div>
103
+ ))}
104
+ </div>
105
+ </details>
106
+ </div>
107
+ <div ref={box} className="wp-chart-box">
108
+ {shown.length === 0 ? <p className="wp-line wp-mut">No line chosen: choose one above.</p> : (
109
+ <svg width={width} height={H} role="img" aria-label={`Queues over time: ${shown.map((s) => `${s.key} ${s.now}`).join(', ')}`}>
110
+ {[0, 0.5, 1].map((f) => (
111
+ <g key={f}>
112
+ <line x1={P.l} x2={width - P.r} y1={Y(max * f)} y2={Y(max * f)} stroke="var(--wp-line)" strokeWidth="1" />
113
+ <text x={P.l - 4} y={Y(max * f) + 3} textAnchor="end" fontSize="9" fill="var(--wp-dim)">{Math.round(max * f).toLocaleString('en-US')}</text>
114
+ </g>
115
+ ))}
116
+ <text x={P.l} y={H - 4} fontSize="9" fill="var(--wp-dim)">{localTime(from)}</text>
117
+ <text x={width - P.r} y={H - 4} fontSize="9" fill="var(--wp-dim)" textAnchor="end">now</text>
118
+ {shown.map((s, i) => (
119
+ <path
120
+ key={s.key}
121
+ d={s.points.map((p, k) => (k === 0 ? `M${X(p.at)},${Y(p.tasks)}` : `H${X(p.at)}V${Y(p.tasks)}`)).join('')}
122
+ fill="none" stroke={SHADES[i % SHADES.length]} strokeWidth="1.25" strokeDasharray={DASHES[i % DASHES.length]}
123
+ />
124
+ ))}
125
+ {shown.map((s, i) => <circle key={`now:${s.key}`} cx={X(view.at)} cy={Y(s.now)} r="2.2" fill={SHADES[i % SHADES.length]} />)}
126
+ {ends.map(({ s, i, y }) => (
127
+ <g key={s.key}>
128
+ <line x1={width - P.r + 4} x2={width - P.r + 18} y1={y} y2={y} stroke={SHADES[i % SHADES.length]} strokeWidth="1.25" strokeDasharray={DASHES[i % DASHES.length]} />
129
+ <text x={width - P.r + 22} y={y + 3} fontSize="9.5" fill="var(--wp-fg)">{s.workflow} {s.bucket} {s.now.toLocaleString('en-US')}</text>
130
+ </g>
131
+ ))}
132
+ </svg>
133
+ )}
134
+ </div>
135
+ </section>
136
+ );
137
+ }
@@ -0,0 +1,98 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * ONE WORKFLOW'S DECLARED STEP GRAPH, DRAWN SMALL: its steps one under another in the order a run takes them, an agent step
5
+ * marked "agent" in words, and every edge an arrow with a number. The numbers' list below says each edge's condition and
6
+ * how many runs took it in the window. An edge to the next row goes straight down; any other runs in a lane of its own on
7
+ * the right, so it crosses no step.
8
+ */
9
+ import { useLayoutEffect, useRef, useState } from 'react';
10
+ import { A_STEP_FAILS, RUN_ENDS, RUN_STARTS } from '../graph';
11
+ import type { WorkflowGraph } from '../views/step-graph';
12
+
13
+ /**
14
+ * Each step's row, in the order the workflow declares its steps, which is the order a run takes them: the run's start (and
15
+ * "a step fails", where an edge leaves it) first, then each step on a row of its own, then the run's end. Pure.
16
+ */
17
+ export const stepRows = (graph: WorkflowGraph): ReadonlyArray<ReadonlyArray<string>> => [
18
+ [RUN_STARTS, ...(graph.edges.some((e) => e.from === A_STEP_FAILS) ? [A_STEP_FAILS] : [])],
19
+ ...graph.steps.map((s) => [s.name]),
20
+ [RUN_ENDS],
21
+ ];
22
+
23
+ export function StepGraph({ graph }: { readonly graph: WorkflowGraph }) {
24
+ const box = useRef<HTMLDivElement>(null);
25
+ const [paths, setPaths] = useState<ReadonlyArray<{ readonly key: string; readonly n: number; readonly d: string; readonly at: { readonly x: number; readonly y: number } }>>([]);
26
+ const [size, setSize] = useState({ w: 0, h: 0 });
27
+ const rows = stepRows(graph);
28
+ const agent = new Set(graph.steps.filter((s) => s.agent).map((s) => s.name));
29
+ useLayoutEffect(() => {
30
+ const el = box.current;
31
+ if (el === null) return;
32
+ const draw = () => {
33
+ const at = el.getBoundingClientRect();
34
+ const rect = (name: string) => el.querySelector(`[data-step="${CSS.escape(name)}"]`)?.getBoundingClientRect() ?? null;
35
+ const right = Math.max(0, ...[...el.querySelectorAll('[data-step]')].map((s) => s.getBoundingClientRect().right - at.left));
36
+ let lanes = 0;
37
+ setSize({ w: el.scrollWidth, h: el.scrollHeight });
38
+ setPaths(graph.edges.flatMap((e, i) => {
39
+ const a = rect(e.from), b = rect(e.to);
40
+ if (a === null || b === null) return [];
41
+ const ax = a.left + a.width / 2 - at.left, bx = b.left + b.width / 2 - at.left;
42
+ const nextRow = b.top >= a.bottom - 1 && b.top - a.bottom < 40;
43
+ if (nextRow) {
44
+ const y1 = a.bottom - at.top, y2 = b.top - at.top;
45
+ return [{ key: `${e.from}>${e.to}`, n: i + 1, d: `M${ax},${y1} C${ax},${(y1 + y2) / 2} ${bx},${(y1 + y2) / 2} ${bx},${y2 - 5}`, at: { x: (ax + bx) / 2, y: (y1 + y2) / 2 } }];
46
+ }
47
+ // Back up, along its own row, or past a row: in a lane on the right.
48
+ const lane = right + 12 + 10 * lanes++;
49
+ const ay = a.top + a.height / 2 - at.top, by = b.top + b.height / 2 - at.top;
50
+ return [{ key: `${e.from}>${e.to}`, n: i + 1, d: `M${a.right - at.left},${ay} H${lane} V${by} H${b.right - at.left + 5}`, at: { x: lane, y: (ay + by) / 2 } }];
51
+ }));
52
+ };
53
+ draw();
54
+ const watch = new ResizeObserver(draw);
55
+ watch.observe(el);
56
+ return () => watch.disconnect();
57
+ }, [graph]);
58
+
59
+ if (!graph.declared) return <p className="wp-line wp-bad">No step graph declared yet.</p>;
60
+ return (
61
+ <div className="wp-steps">
62
+ <div ref={box} className="wp-steps-box">
63
+ <svg className="wp-steps-edges" width={size.w} height={size.h} aria-hidden="true">
64
+ <defs>
65
+ <marker id="wp-step-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
66
+ <path d="M0,0 L8,4 L0,8 z" fill="var(--wp-edge)" />
67
+ </marker>
68
+ </defs>
69
+ {paths.map((p) => <path key={p.key} d={p.d} fill="none" stroke="var(--wp-edge)" strokeWidth="1.1" markerEnd="url(#wp-step-arrow)" />)}
70
+ {paths.map((p) => (
71
+ <g key={`n:${p.key}`}>
72
+ <circle cx={p.at.x} cy={p.at.y} r="7" fill="var(--wp-bg)" stroke="var(--wp-edge)" strokeWidth="0.8" />
73
+ <text x={p.at.x} y={p.at.y + 3} fontSize="8.5" textAnchor="middle" fill="var(--wp-fg)">{p.n}</text>
74
+ </g>
75
+ ))}
76
+ </svg>
77
+ {rows.map((row) => (
78
+ <div key={row.join('|')} className="wp-steps-row">
79
+ {row.map((name) => (
80
+ <span key={name} data-step={name} className={name === RUN_STARTS || name === RUN_ENDS || name === A_STEP_FAILS ? 'wp-step wp-step-end' : 'wp-step'}
81
+ title={graph.steps.find((s) => s.name === name)?.description ?? name}>
82
+ {name}{agent.has(name) ? <em> · agent</em> : null}
83
+ </span>
84
+ ))}
85
+ </div>
86
+ ))}
87
+ </div>
88
+ <ol className="wp-steps-when">
89
+ {graph.edges.map((e) => (
90
+ <li key={`${e.from}>${e.to}`}>{e.from} → {e.to}: {e.when}{e.runs === 0 ? '' : ` (${e.runs.toLocaleString('en-US')} run${e.runs === 1 ? '' : 's'})`}</li>
91
+ ))}
92
+ </ol>
93
+ {graph.undeclared.length === 0 ? null : (
94
+ <p className="wp-line wp-bad">Taken but not declared: {graph.undeclared.map((e) => `${e.from} → ${e.to} (${e.runs})`).join('; ')}</p>
95
+ )}
96
+ </div>
97
+ );
98
+ }