@jive-sh/workflow-platform 0.6.2 → 0.7.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 (89) hide show
  1. package/README.md +189 -42
  2. package/dist/budget-states.js +1 -1
  3. package/dist/budget-states.js.map +1 -1
  4. package/dist/dashboard/dashboard.css +42 -28
  5. package/dist/dashboard/drilldown.js +35 -4
  6. package/dist/dashboard/drilldown.js.map +1 -1
  7. package/dist/dashboard/run-doing-words.js +29 -0
  8. package/dist/dashboard/run-doing-words.js.map +1 -0
  9. package/dist/dashboard/setting-words.js +18 -0
  10. package/dist/dashboard/setting-words.js.map +1 -0
  11. package/dist/dashboard/spending-words.js +2 -10
  12. package/dist/dashboard/spending-words.js.map +1 -1
  13. package/dist/index.js +76 -13
  14. package/dist/index.js.map +1 -1
  15. package/dist/keep-running.js +4 -2
  16. package/dist/keep-running.js.map +1 -1
  17. package/dist/pick-wakes.js +2 -2
  18. package/dist/retention.js +59 -0
  19. package/dist/retention.js.map +1 -0
  20. package/dist/settings.js +88 -0
  21. package/dist/settings.js.map +1 -0
  22. package/dist/spending-limit.js +15 -21
  23. package/dist/spending-limit.js.map +1 -1
  24. package/dist/step-times.js +114 -0
  25. package/dist/step-times.js.map +1 -0
  26. package/dist/steps.js +399 -114
  27. package/dist/steps.js.map +1 -1
  28. package/dist/storage/agent-claims.js +3 -0
  29. package/dist/storage/agent-claims.js.map +1 -0
  30. package/dist/storage/budgets.js +40 -4
  31. package/dist/storage/budgets.js.map +1 -1
  32. package/dist/storage/engine-records.js +26 -10
  33. package/dist/storage/engine-records.js.map +1 -1
  34. package/dist/storage/sqlite-store.js +198 -20
  35. package/dist/storage/sqlite-store.js.map +1 -1
  36. package/dist/storage/task-store.js +11 -5
  37. package/dist/storage/task-store.js.map +1 -1
  38. package/dist/system-workflows.js +54 -0
  39. package/dist/system-workflows.js.map +1 -0
  40. package/dist/tasks.js +72 -29
  41. package/dist/tasks.js.map +1 -1
  42. package/dist/views/runs-now.js +80 -38
  43. package/dist/views/runs-now.js.map +1 -1
  44. package/dist/views/step-graph.js +6 -1
  45. package/dist/views/step-graph.js.map +1 -1
  46. package/dist/views/workflows-view.js +29 -23
  47. package/dist/views/workflows-view.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/budget-states.ts +2 -3
  50. package/src/dashboard/dashboard.css +42 -28
  51. package/src/dashboard/drilldown.ts +32 -5
  52. package/src/dashboard/index.tsx +1 -1
  53. package/src/dashboard/limits-and-runs.tsx +191 -0
  54. package/src/dashboard/queue-bar.tsx +30 -11
  55. package/src/dashboard/queue-chart.tsx +1 -2
  56. package/src/dashboard/run-doing-words.ts +41 -0
  57. package/src/dashboard/setting-words.ts +30 -0
  58. package/src/dashboard/spending-limit-control.tsx +5 -8
  59. package/src/dashboard/spending-words.ts +5 -23
  60. package/src/dashboard/time-distribution.tsx +61 -0
  61. package/src/dashboard/workflow-dag.tsx +247 -129
  62. package/src/dashboard/workflow-drilldown.tsx +13 -71
  63. package/src/dashboard/workflows-dashboard.tsx +345 -227
  64. package/src/index.ts +86 -16
  65. package/src/keep-running.ts +6 -4
  66. package/src/pick-wakes.ts +2 -2
  67. package/src/project.ts +12 -0
  68. package/src/retention.ts +90 -0
  69. package/src/settings.ts +171 -0
  70. package/src/spending-limit.ts +25 -42
  71. package/src/step-times.ts +151 -0
  72. package/src/steps.ts +512 -135
  73. package/src/storage/agent-claims.ts +63 -0
  74. package/src/storage/budgets.ts +43 -4
  75. package/src/storage/engine-records.ts +28 -11
  76. package/src/storage/sqlite-store.ts +225 -32
  77. package/src/storage/step-records.ts +59 -7
  78. package/src/storage/task-store.ts +29 -29
  79. package/src/system-workflows.ts +70 -0
  80. package/src/tasks.ts +69 -30
  81. package/src/views/runs-now.ts +119 -51
  82. package/src/views/step-graph.ts +11 -2
  83. package/src/views/workflows-view.ts +80 -39
  84. package/src/workflow-dag.test.tsx +89 -0
  85. package/src/workflow-page.test.tsx +170 -0
  86. package/dist/views/workflow-flows.js +0 -53
  87. package/dist/views/workflow-flows.js.map +0 -1
  88. package/src/dashboard/step-graph.tsx +0 -106
  89. package/src/views/workflow-flows.ts +0 -97
@@ -1,26 +1,45 @@
1
1
  'use client';
2
2
 
3
3
  /**
4
- * A WORKFLOW'S TASKS AS A BAR, with the addition under it (`queue-table.ts`): queued + in progress + blocked + done, a
5
- * rule, the total. The bar's segments differ in lightness, and every count is also in words.
4
+ * COUNTS AS A BAR, with the addition under it (`queue-table.ts`): a workflow's tasks (queued + in progress + blocked + done)
5
+ * or a step's calls (in progress + failed + done), a rule, the total. The bar's segments differ in lightness, and every
6
+ * count is also in words.
6
7
  */
7
- import type { WorkflowView } from '../views/workflows-view';
8
8
  import { addendLabel, queueSum } from './queue-table';
9
9
 
10
- export function QueueBar({ queue, queuedNeedingAnAgent }: { readonly queue: NonNullable<WorkflowView['queue']>; readonly queuedNeedingAnAgent: WorkflowView['queuedNeedingAnAgent'] }) {
10
+ /** Each count's segment, in the order the bar draws them; a count named nowhere here is drawn last, as the dimmest. */
11
+ const SEGMENTS: ReadonlyArray<{ readonly key: string; readonly cls: string }> = [
12
+ { key: 'done', cls: 'wp-seg-done' },
13
+ { key: 'in progress', cls: 'wp-seg-running' },
14
+ { key: 'queued', cls: 'wp-seg-queued' },
15
+ { key: 'blocked', cls: 'wp-seg-rest' },
16
+ { key: 'failed', cls: 'wp-seg-rest' },
17
+ ];
18
+
19
+ export function QueueBar({ queue, queuedNeedingAnAgent, counts = 'tasks', totalLabel = 'total' }: {
20
+ /** Counts by category, in the order the addition lists them. */
21
+ readonly queue: Readonly<Record<string, number>>;
22
+ /** How many queued tasks need an agent; none where no task can be marked (`WorkflowView`). */
23
+ readonly queuedNeedingAnAgent: number | null;
24
+ /** What it counts, written on its table (`data-counts`) for whatever reads the page: a workflow's tasks, or a step's calls. */
25
+ readonly counts?: 'tasks' | 'calls';
26
+ /** What the total counts: "total" for tasks, "calls, 24 h" for a step's calls. */
27
+ readonly totalLabel?: string;
28
+ }) {
11
29
  const sum = queueSum(queue, queuedNeedingAnAgent);
12
30
  const segments = [
13
- { n: queue.done, cls: 'wp-seg-done' },
14
- { n: queue['in progress'], cls: 'wp-seg-running' },
15
- { n: queue.queued, cls: 'wp-seg-queued' },
16
- { n: queue.blocked, cls: 'wp-seg-rest' },
31
+ ...SEGMENTS.filter((s) => s.key in queue),
32
+ ...Object.keys(queue).filter((k) => !SEGMENTS.some((s) => s.key === k)).map((key) => ({ key, cls: 'wp-seg-rest' })),
17
33
  ];
18
34
  return (
19
35
  <div className="wp-queue">
20
36
  <div className="wp-bar" role="img" aria-label={sum.addends.map((a) => `${a.text} ${addendLabel(a)}`).join(', ')}>
21
- {segments.map((s) => (s.n === 0 ? null : <span key={s.cls} className={s.cls} style={{ width: `${(100 * s.n) / Math.max(1, sum.total)}%` }} />))}
37
+ {segments.map((s) => {
38
+ const n = queue[s.key] ?? 0;
39
+ return n === 0 ? null : <span key={s.key} className={s.cls} style={{ width: `${(100 * n) / Math.max(1, sum.total)}%` }} />;
40
+ })}
22
41
  </div>
23
- <table className="wp-sum">
42
+ <table className="wp-sum" data-counts={counts}>
24
43
  <tbody>
25
44
  {sum.addends.map((a, i) => (
26
45
  <tr key={a.category}>
@@ -34,7 +53,7 @@ export function QueueBar({ queue, queuedNeedingAnAgent }: { readonly queue: NonN
34
53
  <tr className="wp-sum-total">
35
54
  <td className="wp-sum-plus" />
36
55
  <td className="wp-sum-n">{sum.totalText}</td>
37
- <td className="wp-sum-label">total</td>
56
+ <td className="wp-sum-label">{totalLabel}</td>
38
57
  </tr>
39
58
  </tfoot>
40
59
  </table>
@@ -67,7 +67,7 @@ export function QueueChart({ view, workflows, level, rowWord }: QueueChartProps)
67
67
  return () => watch.disconnect();
68
68
  }, []);
69
69
 
70
- if (rows.length === 0) return null;
70
+ if (rows.length === 0) return <p className="wp-line wp-mut">Neither it nor any workflow under it, at any depth, records tasks.</p>;
71
71
  const statuses = rows[0]!.lines.map((l) => l.status);
72
72
  const H = 130;
73
73
  const P = { t: 8, r: 18, b: 18, l: 40 };
@@ -82,7 +82,6 @@ export function QueueChart({ view, workflows, level, rowWord }: QueueChartProps)
82
82
  return (
83
83
  <section className="wp-chart" aria-label="Tasks over time, as a percent of each workflow's tasks">
84
84
  <div className="wp-chart-head">
85
- <span>Tasks over time</span>
86
85
  <span className="wp-mut">{recordedSince === null ? 'recorded from now on, each time a count moves' : `recorded since ${localTime(recordedSince)}`}</span>
87
86
  </div>
88
87
  <div ref={box} className="wp-chart-box">
@@ -0,0 +1,41 @@
1
+ /**
2
+ * A WORKFLOW'S GOING RUNS IN WORDS, EACH BY WHAT IT IS DOING (`views/runs-now.ts` `RunDoing`): "3 runs going: 1 holding
3
+ * an agent, 2 in Repair names". The counts add up to the runs going. Pure, with no React and no
4
+ * JSX, so a test reads it without a page.
5
+ */
6
+ import type { RunDoing, RunsDoing } from '../views/runs-now';
7
+
8
+ const runsWord = (n: number) => `${n} run${n === 1 ? '' : 's'}`;
9
+
10
+ /** One count's words; runs holding an agent name the agents' limit they hold them under, where the workflow has one. */
11
+ const countWords = (c: RunsDoing, agentsLimit: number | null): string => `${c.runs} ${doingWords(c.doing, agentsLimit)}`;
12
+
13
+ const doingWords = (d: RunDoing, agentsLimit: number | null): string =>
14
+ d.kind === 'holding an agent' ? `holding an agent${agentsLimit === null ? '' : ` (limit ${agentsLimit})`}`
15
+ : d.kind === 'in a step' ? `in ${d.step}`
16
+ : d.kind === 'waiting at a step' ? `waiting at ${d.step}`
17
+ : d.kind;
18
+
19
+ /** Its counts, with one of runs holding an agent, none included, where it uses agents: its agent count is never missing. Pure. */
20
+ const withAgentCount = (r: { readonly doing: ReadonlyArray<RunsDoing>; readonly usesAgents: boolean }): ReadonlyArray<RunsDoing> =>
21
+ r.usesAgents && !r.doing.some((c) => c.doing.kind === 'holding an agent') ? [{ doing: { kind: 'holding an agent' }, runs: 0 }, ...r.doing] : r.doing;
22
+
23
+ /**
24
+ * A workflow's going runs and what each is doing. One that uses agents always says how many hold one, none included, so its
25
+ * agent count is never missing; its agents' limit is the one its runs' claims count against.
26
+ */
27
+ export const runsGoingWords = (r: { readonly runs: number; readonly doing: ReadonlyArray<RunsDoing>; readonly usesAgents: boolean; readonly agentsLimit: number | null }): string => {
28
+ if (r.runs === 0) return 'no run going';
29
+ const counts = withAgentCount(r);
30
+ return `${runsWord(r.runs)} going: ${counts.map((c) => countWords(c, r.agentsLimit)).join(', ')}`;
31
+ };
32
+
33
+ /**
34
+ * A WORKFLOW'S GOING RUNS AS LINES, one a state, each its count and its words, as the page's Runs section adds them up to
35
+ * the runs going; its agents' limit is on the Limits section. One that uses agents always has its line of runs holding an
36
+ * agent, none included. Pure.
37
+ */
38
+ export const runsDoingLines = (r: { readonly doing: ReadonlyArray<RunsDoing>; readonly usesAgents: boolean }): ReadonlyArray<{ readonly runs: number; readonly words: string }> => {
39
+ const counts = withAgentCount(r);
40
+ return counts.map((c) => ({ runs: c.runs, words: doingWords(c.doing, null) }));
41
+ };
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A STEP'S INHERITED SETTINGS IN THE WORDS ITS BOX SHOWS (`settings.ts`): the value, and where it is set, so nothing about
3
+ * either is told by colour or by position alone. "keeps 7 days, at least 10,000 runs (set on the app)", "keeps 30 days (set on
4
+ * this step), at least 10,000 runs (set on the app)", "model claude-opus-5-5 (set on this step)". Pure, with no React, so a
5
+ * test reads it without a page.
6
+ */
7
+ import type { Effective, SetOn } from '../settings';
8
+
9
+ /** Where a setting is set, in words, as the box of step `here.step` on `here.workflow`'s page says it. Pure. */
10
+ export const setOnWords = (setOn: SetOn, here: { readonly workflow: string; readonly step: string | null }): string =>
11
+ setOn.kind === 'platform default' ? "the platform's default"
12
+ : setOn.kind === 'app' ? 'set on the app'
13
+ : setOn.kind === 'workflow' ? (here.step === null && setOn.workflow === here.workflow ? 'set on this workflow' : `set on ${setOn.workflow}`)
14
+ : setOn.workflow === here.workflow && setOn.step === here.step ? 'set on this step'
15
+ : `set on its step ${setOn.step} in ${setOn.workflow}`;
16
+
17
+ const plural = (n: number, one: string, many: string) => `${n.toLocaleString('en-US')} ${n === 1 ? one : many}`;
18
+
19
+ /** How long a step's records are kept and the fewest of its runs kept however old, and where each is set: once where both are set in one place. Pure. */
20
+ export const retentionWords = (kept: { readonly days: Effective<number>; readonly atLeastRuns: Effective<number> }, here: { readonly workflow: string; readonly step: string | null }): string => {
21
+ const days = `keeps ${plural(kept.days.value, 'day', 'days')}`;
22
+ const runs = `at least ${plural(kept.atLeastRuns.value, 'run', 'runs')}`;
23
+ const daysOn = setOnWords(kept.days.setOn, here);
24
+ const runsOn = setOnWords(kept.atLeastRuns.setOn, here);
25
+ return daysOn === runsOn ? `${days}, ${runs} (${daysOn})` : `${days} (${daysOn}), ${runs} (${runsOn})`;
26
+ };
27
+
28
+ /** The model a step's agents run on, and where that is set; none set says so, since such a step fails before its agent. Pure. */
29
+ export const modelWords = (model: Effective<string | null>, here: { readonly workflow: string; readonly step: string | null }): string =>
30
+ model.value === null ? `no model set (${setOnWords(model.setOn, here)}): its agent steps fail until one is` : `model ${model.value} (${setOnWords(model.setOn, here)})`;
@@ -2,24 +2,23 @@
2
2
 
3
3
  /**
4
4
  * THE SPENDING LIMIT ON THE PAGE (`spending-limit.ts`): what it is set to with − and +, the week's reading against it, whether
5
- * it holds every agent step, whether the reading is stale, and which agent steps wait on it, each in words
6
- * (`spending-words.ts`). A click shows at once, as asked, until the page's next reading says the same; a failed one says why.
5
+ * it withholds every agent, and whether the reading is stale, each in words (`spending-words.ts`). A click shows at once, as
6
+ * asked, until the page's next reading says the same; a failed one says why.
7
7
  */
8
8
  import { useEffect, useState } from 'react';
9
9
  import type { SpendingLimitState } from '../spending-limit';
10
- import { heldStepsWords, spendingSettingWords, spendingStaleWords, spendingVerdictWords, type HeldStep } from './spending-words';
10
+ import { spendingSettingWords, spendingStaleWords, spendingVerdictWords } from './spending-words';
11
11
 
12
12
  export interface SpendingLimitControlProps {
13
13
  readonly spending: SpendingLimitState;
14
- readonly held: ReadonlyArray<HeldStep>;
15
14
  readonly now: number;
16
15
  /** Stores a new limit, a whole percent from 0 to 100; with none the limit shows without buttons. */
17
16
  readonly setSpendingLimit?: (weekPercent: number) => Promise<void>;
18
17
  }
19
18
 
20
- const WHY = 'While the newest good reading of the week is at or past this percent, every agent step of every workflow waits before its agent call. A failed or late reading never lifts it.';
19
+ const WHY = 'While the newest good reading of the week is at or past this percent, no run of any workflow is given an agent, and a run holding one ends before its next agent call, its task back in its queue. A failed or late reading never lifts it.';
21
20
 
22
- export function SpendingLimitControl({ spending, held, now, setSpendingLimit }: SpendingLimitControlProps) {
21
+ export function SpendingLimitControl({ spending, now, setSpendingLimit }: SpendingLimitControlProps) {
23
22
  const [asked, setAsked] = useState<number | null>(null);
24
23
  const [failed, setFailed] = useState<string | null>(null);
25
24
  useEffect(() => {
@@ -33,7 +32,6 @@ export function SpendingLimitControl({ spending, held, now, setSpendingLimit }:
33
32
  setSpendingLimit(to).catch((e: unknown) => { setAsked(null); setFailed(e instanceof Error ? e.message : String(e)); });
34
33
  };
35
34
  const stale = spendingStaleWords(spending, now);
36
- const waiting = heldStepsWords(spending, held);
37
35
  return (
38
36
  <div className="wp-spending">
39
37
  <span className="wp-limit" title={WHY}>
@@ -44,7 +42,6 @@ export function SpendingLimitControl({ spending, held, now, setSpendingLimit }:
44
42
  </span>
45
43
  <p className={spending.holds ? 'wp-line wp-bad' : 'wp-line'}>{spendingVerdictWords(spending, now)}</p>
46
44
  {stale === null ? null : <p className="wp-line wp-bad">{stale}</p>}
47
- {waiting === null ? null : <p className={held.length > 0 ? 'wp-line wp-bad' : 'wp-line wp-mut'}>{waiting}</p>}
48
45
  </div>
49
46
  );
50
47
  }
@@ -1,28 +1,16 @@
1
1
  /**
2
- * THE SPENDING LIMIT IN WORDS (`spending-limit.ts`): what it is set to, the week's reading against it, whether it holds, and
3
- * which agent steps wait on it. Each state is said in words, first in its line; a colour on the page only repeats it. Pure,
4
- * with no React and no JSX, so a test reads it without a page.
2
+ * THE SPENDING LIMIT IN WORDS (`spending-limit.ts`): what it is set to, the week's reading against it, and whether it holds.
3
+ * Each state is said in words, first in its line; a colour on the page only repeats it. Pure, with no React and no JSX, so a
4
+ * test reads it without a page.
5
5
  */
6
6
  import type { SpendingLimitState } from '../spending-limit';
7
- import type { PhaseRunsNow } from '../views/runs-now';
8
7
  import { percentCut, whenAgo } from '../views/format';
9
8
 
10
- /** One agent step the limit holds runs at, and how many. */
11
- export interface HeldStep {
12
- readonly workflow: string;
13
- readonly step: string;
14
- readonly runs: number;
15
- }
16
-
17
- /** Every agent step the limit holds a run at now, from where runs are now. */
18
- export const heldSteps = (runsNow: ReadonlyArray<PhaseRunsNow>): ReadonlyArray<HeldStep> =>
19
- runsNow.flatMap((p) => p.workflows.flatMap((w) => w.steps.filter((s) => s.heldBySpendingLimit > 0).map((s) => ({ workflow: w.workflow, step: s.step, runs: s.heldBySpendingLimit }))));
20
-
21
9
  /** What the limit is set to: "agents stop at 95% of the week (the default)". */
22
10
  export const spendingSettingWords = (s: Pick<SpendingLimitState, 'limitPercent' | 'setAt'>): string =>
23
11
  `Spending limit: agents stop at ${s.limitPercent}% of the week${s.setAt === null ? ' (the default)' : ''}`;
24
12
 
25
- /** The week's reading against the limit, and whether it holds every agent step. */
13
+ /** The week's reading against the limit, and whether it withholds every agent. */
26
14
  export const spendingVerdictWords = (s: SpendingLimitState, now: number): string => {
27
15
  if (s.reading === null) {
28
16
  return s.failedSince === null
@@ -31,7 +19,7 @@ export const spendingVerdictWords = (s: SpendingLimitState, now: number): string
31
19
  }
32
20
  const reading = `the week's use is ${percentCut(s.reading.usedPercent)}, read ${whenAgo(s.reading.readAt, now)}`;
33
21
  return s.holds
34
- ? `Holding every agent step: ${reading}, at or past the limit. Each waits before its agent call until a reading is below ${s.limitPercent}%.`
22
+ ? `Withholding every agent: ${reading}, at or past the limit. No run is given one, and a run holding one ends before its next agent call, its task back in its queue, until a reading is below ${s.limitPercent}%.`
35
23
  : `Holds nothing: ${reading}, below the limit.`;
36
24
  };
37
25
 
@@ -42,9 +30,3 @@ export const spendingStaleWords = (s: SpendingLimitState, now: number): string |
42
30
  ? "The reading is stale: none came since. The limit keeps that reading's verdict until a new one."
43
31
  : `The reading is stale: the newest read failed at ${whenAgo(s.failedSince.at, now)} (${s.failedSince.error}). The limit keeps the last good reading's verdict until a read succeeds.`;
44
32
  };
45
-
46
- /** Which agent steps wait on it; none to say while it holds nothing and nothing waits. */
47
- export const heldStepsWords = (s: Pick<SpendingLimitState, 'holds'>, held: ReadonlyArray<HeldStep>): string | null => {
48
- if (held.length === 0) return s.holds ? 'No agent step has reached it yet.' : null;
49
- return `Waiting on it: ${held.map((h) => `${h.workflow}, step ${h.step} (${h.runs} run${h.runs === 1 ? '' : 's'})`).join('; ')}.`;
50
- };
@@ -0,0 +1,61 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * ONE STEP'S TIME DISTRIBUTION, AS A CONTINUOUS BAR GRAPH (`step-times.ts`). Alex, 2026-11-21: "one point is (time taken,
5
+ * number of tasks with that time taken). a distribution is a continuous bar graph"; the axis "linear".
6
+ *
7
+ * x is time taken, linear from 0 to the slowest task's time; y is how many tasks took that time. One bar per pixel column of
8
+ * the chart, edge to edge: the finest the screen can show, so nothing visible is lost; no smoothing and no fitted curve. n,
9
+ * the median and the 90th percentile are said in words, computed from every value, and the median and the 90th percentile
10
+ * are marked on the x axis by shapes the words name (▲ and ◆), never by colour.
11
+ */
12
+ import { duration } from '../views/format';
13
+
14
+ /** The chart's width in px: a step box's inner width (`dashboard.css` `.wp-node`), one bar per pixel column of it. */
15
+ export const CHART_WIDTH = 230;
16
+ const BARS_HEIGHT = 44;
17
+
18
+ /** A time in words, to a tenth of a second under 10 s: "0.4 s", "42 s", "3 min 5 s". */
19
+ export const timeWords = (seconds: number): string => (seconds < 10 ? `${(Math.round(seconds * 10) / 10).toFixed(1)} s` : duration(seconds));
20
+
21
+ /** The value at fraction `q` of sorted `values` (the nearest rank: no value is invented between two). Pure. */
22
+ export const quantile = (sorted: ReadonlyArray<number>, q: number): number =>
23
+ sorted.length === 0 ? 0 : sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(q * sorted.length) - 1))]!;
24
+
25
+ /**
26
+ * THE BARS: how many values fall in each of `columns` equal slices of 0 to the largest value, the slowest in the last. Every
27
+ * value is counted in exactly one. Pure.
28
+ */
29
+ export const barCounts = (values: ReadonlyArray<number>, columns: number): ReadonlyArray<number> => {
30
+ const counts = new Array<number>(columns).fill(0);
31
+ const slowest = values.reduce((m, v) => Math.max(m, v), 0);
32
+ for (const v of values) counts[slowest === 0 ? 0 : Math.min(columns - 1, Math.floor((v / slowest) * columns))]! += 1;
33
+ return counts;
34
+ };
35
+
36
+ export function TimeDistribution({ values }: { readonly values: ReadonlyArray<number> }) {
37
+ const sorted = [...values].sort((a, b) => a - b);
38
+ const slowest = sorted[sorted.length - 1] ?? 0;
39
+ const counts = barCounts(sorted, CHART_WIDTH);
40
+ const most = Math.max(1, ...counts);
41
+ const median = quantile(sorted, 0.5);
42
+ const p90 = quantile(sorted, 0.9);
43
+ const x = (v: number) => (slowest === 0 ? 0 : Math.min(CHART_WIDTH - 1, Math.floor((v / slowest) * CHART_WIDTH)) + 0.5);
44
+ const said = `${sorted.length.toLocaleString('en-US')} tasks, median ${timeWords(median)}, 90th percentile ${timeWords(p90)}, slowest ${timeWords(slowest)}`;
45
+ return (
46
+ <figure className="wp-times" aria-label={`Time taken: ${said}`}>
47
+ <p className="wp-times-words">n {sorted.length.toLocaleString('en-US')} · ▲ median {timeWords(median)}</p>
48
+ <p className="wp-times-words">◆ p90 {timeWords(p90)}</p>
49
+ <svg width={CHART_WIDTH} height={BARS_HEIGHT + 26} role="img" aria-hidden="true">
50
+ {counts.map((n, i) => (n === 0 ? null : <rect key={i} x={i} y={BARS_HEIGHT - (n / most) * BARS_HEIGHT} width={1} height={(n / most) * BARS_HEIGHT} fill="var(--wp-fg)" />))}
51
+ <line x1={0} x2={CHART_WIDTH} y1={BARS_HEIGHT + 0.5} y2={BARS_HEIGHT + 0.5} stroke="var(--wp-dim)" strokeWidth="1" />
52
+ <path d={`M${x(median)},${BARS_HEIGHT + 2} l4,7 h-8 z`} fill="var(--wp-fg)" />
53
+ <path d={`M${x(p90)},${BARS_HEIGHT + 2} l4,4 l-4,4 l-4,-4 z`} fill="none" stroke="var(--wp-fg)" strokeWidth="1.2" />
54
+ <text x={0} y={BARS_HEIGHT + 22} fontSize="9.5" fill="var(--wp-dim)">0</text>
55
+ <text x={CHART_WIDTH / 2} y={BARS_HEIGHT + 22} fontSize="9.5" fill="var(--wp-dim)" textAnchor="middle">{timeWords(slowest / 2)}</text>
56
+ <text x={CHART_WIDTH} y={BARS_HEIGHT + 22} fontSize="9.5" fill="var(--wp-dim)" textAnchor="end">{timeWords(slowest)}</text>
57
+ </svg>
58
+ <figcaption className="wp-times-axis">across: time taken · up: tasks</figcaption>
59
+ </figure>
60
+ );
61
+ }