@jive-sh/workflow-platform 0.3.3 → 0.4.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 (54) hide show
  1. package/README.md +64 -21
  2. package/dist/dashboard/agent-usage.js +25 -0
  3. package/dist/dashboard/agent-usage.js.map +1 -0
  4. package/dist/dashboard/drilldown.js +16 -0
  5. package/dist/dashboard/drilldown.js.map +1 -0
  6. package/dist/dashboard/queue-lines.js +44 -0
  7. package/dist/dashboard/queue-lines.js.map +1 -0
  8. package/dist/index.js +8 -7
  9. package/dist/index.js.map +1 -1
  10. package/dist/keep-running.js +1 -1
  11. package/dist/keep-running.js.map +1 -1
  12. package/dist/pick-wakes.js +4 -4
  13. package/dist/pick-wakes.js.map +1 -1
  14. package/dist/queue-counts.js +7 -9
  15. package/dist/queue-counts.js.map +1 -1
  16. package/dist/steps.js +133 -30
  17. package/dist/steps.js.map +1 -1
  18. package/dist/storage/sqlite-store.js +115 -40
  19. package/dist/storage/sqlite-store.js.map +1 -1
  20. package/dist/storage/task-store.js +14 -1
  21. package/dist/storage/task-store.js.map +1 -1
  22. package/dist/tasks.js +215 -267
  23. package/dist/tasks.js.map +1 -1
  24. package/dist/views/runs-now.js +2 -1
  25. package/dist/views/runs-now.js.map +1 -1
  26. package/dist/views/workflows-view.js +74 -15
  27. package/dist/views/workflows-view.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/dashboard/agent-usage-line.tsx +28 -0
  30. package/src/dashboard/agent-usage.ts +48 -0
  31. package/src/dashboard/dashboard.css +57 -28
  32. package/src/dashboard/drilldown.ts +44 -0
  33. package/src/dashboard/index.tsx +1 -0
  34. package/src/dashboard/machine-controls.tsx +53 -0
  35. package/src/dashboard/queue-bar.tsx +43 -0
  36. package/src/dashboard/queue-chart.tsx +89 -76
  37. package/src/dashboard/queue-lines.ts +87 -0
  38. package/src/dashboard/workflow-drilldown.tsx +89 -0
  39. package/src/dashboard/workflows-dashboard.tsx +103 -37
  40. package/src/index.ts +11 -10
  41. package/src/keep-running.ts +3 -3
  42. package/src/pick-wakes.ts +14 -9
  43. package/src/queue-counts.ts +10 -14
  44. package/src/steps.ts +179 -42
  45. package/src/storage/sqlite-store.ts +123 -46
  46. package/src/storage/step-records.ts +14 -3
  47. package/src/storage/task-store.ts +88 -36
  48. package/src/tasks.ts +235 -301
  49. package/src/views/runs-now.ts +3 -2
  50. package/src/views/workflows-view.ts +102 -32
  51. package/dist/views/workflow-flows.js +0 -53
  52. package/dist/views/workflow-flows.js.map +0 -1
  53. package/src/dashboard/workflow-dag.tsx +0 -276
  54. package/src/views/workflow-flows.ts +0 -97
@@ -1,3 +1,4 @@
1
1
  /** The workflow platform's dashboard: React components for any project's workflows, and how they write figures. */
2
2
  export { usePolledJson, WorkflowsDashboard, type LimitName, type SetLimit, type WorkflowsDashboardProps, type WorkflowsPageData } from './workflows-dashboard';
3
+ export type { AgentUsage, UsageLimit } from './agent-usage';
3
4
  export { clockTime, compact, duration, localTime, whenAgo } from '../views/format';
@@ -0,0 +1,53 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * THE PROJECT'S TWO MACHINE CONTROLS, where it gives them: its one CPU limit with − and +, and the stop of everything it
5
+ * runs, with the resume that undoes it. Generic to any project on the platform: the platform holds the CPU limit
6
+ * (`cpu-limit/limiter.ts`), and a run limit of 0 on every workflow is how everything stops. Each control says what it does
7
+ * in words, and a click that failed says why.
8
+ */
9
+ import { useState } from 'react';
10
+ import { localTime } from '../views/format';
11
+
12
+ export interface MachineControlsProps {
13
+ /** The CPU limit now, and how many threads the machine has: the most it can be set to. */
14
+ readonly cpu: { readonly limit: number; readonly threads?: number };
15
+ /** When everything was stopped, unix seconds; none while the project runs. */
16
+ readonly stopped: { readonly at: number } | null;
17
+ readonly now: number;
18
+ /** Stores a new CPU limit; with none the limit shows without buttons. */
19
+ readonly setCpuLimit?: (limit: number) => Promise<void>;
20
+ /** Stops everything the project runs, and resumes it; with neither, no button shows. */
21
+ readonly stopEverything?: () => Promise<void>;
22
+ readonly resume?: () => Promise<void>;
23
+ }
24
+
25
+ export function MachineControls({ cpu, stopped, now, setCpuLimit, stopEverything, resume }: MachineControlsProps) {
26
+ const [asked, setAsked] = useState<number | null>(null);
27
+ const [failed, setFailed] = useState<string | null>(null);
28
+ const doing = (what: Promise<void>) => { setFailed(null); what.catch((e: unknown) => { setAsked(null); setFailed(e instanceof Error ? e.message : String(e)); }); };
29
+ const limit = asked !== null && asked !== cpu.limit ? asked : cpu.limit;
30
+ const change = (to: number) => {
31
+ if (setCpuLimit === undefined) return;
32
+ setAsked(to);
33
+ doing(setCpuLimit(to));
34
+ };
35
+ const why = 'How many CPU-heavy processes run at once. Takes effect on new work at once; running work finishes.';
36
+ if (setCpuLimit === undefined && stopEverything === undefined && resume === undefined) return null;
37
+ return (
38
+ <div className="wp-machine">
39
+ {setCpuLimit === undefined ? null : (
40
+ <span className="wp-limit" title={why}>
41
+ <button type="button" aria-label="Lower the CPU limit" disabled={limit <= 1} onClick={() => change(limit - 1)}>−</button>
42
+ <span>CPU limit: {limit}{cpu.threads === undefined ? '' : ` of ${cpu.threads}`}</span>
43
+ <button type="button" aria-label="Raise the CPU limit" disabled={cpu.threads !== undefined && limit >= cpu.threads} onClick={() => change(limit + 1)}>+</button>
44
+ </span>
45
+ )}
46
+ {stopped === null
47
+ ? (stopEverything === undefined ? null : <button type="button" className="wp-stop" title="Stops every process of the project and sets every limit aside until you resume." onClick={() => doing(stopEverything())}>Stop everything</button>)
48
+ : (resume === undefined ? null : <button type="button" className="wp-stop" title="Puts the limits back and starts the work again." onClick={() => doing(resume())}>Resume</button>)}
49
+ {stopped === null ? null : <span className="wp-bad">Everything stopped at {localTime(stopped.at, now)}; the limits are set aside.</span>}
50
+ {failed === null ? null : <span className="wp-bad">not done: {failed}</span>}
51
+ </div>
52
+ );
53
+ }
@@ -0,0 +1,43 @@
1
+ 'use client';
2
+
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.
6
+ */
7
+ import type { WorkflowView } from '../views/workflows-view';
8
+ import { queueSum } from './queue-table';
9
+
10
+ export function QueueBar({ queue }: { readonly queue: NonNullable<WorkflowView['queue']> }) {
11
+ const sum = queueSum(queue);
12
+ 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' },
17
+ ];
18
+ return (
19
+ <div className="wp-queue">
20
+ <div className="wp-bar" role="img" aria-label={sum.addends.map((a) => `${a.text} ${a.category}`).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)}%` }} />))}
22
+ </div>
23
+ <table className="wp-sum">
24
+ <tbody>
25
+ {sum.addends.map((a, i) => (
26
+ <tr key={a.category}>
27
+ <td className="wp-sum-plus">{i === sum.addends.length - 1 ? '+' : ''}</td>
28
+ <td className="wp-sum-n">{a.text}</td>
29
+ <td className="wp-sum-label">{a.category}</td>
30
+ </tr>
31
+ ))}
32
+ </tbody>
33
+ <tfoot>
34
+ <tr className="wp-sum-total">
35
+ <td className="wp-sum-plus" />
36
+ <td className="wp-sum-n">{sum.totalText}</td>
37
+ <td className="wp-sum-label">total</td>
38
+ </tr>
39
+ </tfoot>
40
+ </table>
41
+ </div>
42
+ );
43
+ }
@@ -1,61 +1,57 @@
1
1
  'use client';
2
2
 
3
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.
4
+ * TASKS OVER TIME, small: one status of one workflow as a thin line, always as a percent of that workflow's tasks
5
+ * (`queue-lines.ts`). Each line carries a number at its end and in the key under the chart, where its label reads its
6
+ * tasks over its workflow's total with the percent, so no line is told apart by colour alone. Which lines show is the
7
+ * reader's choice, made in a table (a row per workflow, a column per status) and kept in this browser for each level of
8
+ * the drill-down.
8
9
  */
9
10
  import { useEffect, useLayoutEffect, useRef, useState } from 'react';
10
- import type { QueueCount } from '../storage/task-store';
11
- import type { WorkflowsView } from '../views/workflows-view';
11
+ import type { WorkflowsView, WorkflowView } from '../views/workflows-view';
12
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
- }
13
+ import { lineLabel, percentOf, queueRows } from './queue-lines';
22
14
 
23
15
  const STORED_CHOICE = 'workflow-platform.queue-chart.lines';
24
- /** Lines shown before the reader chooses: the queues that finished most. */
16
+ /** Lines shown before the reader chooses: the rows that finished most. */
25
17
  const SHOWN_AT_FIRST = 3;
26
18
  const DASHES = ['', '5 3', '1.5 2.5', '7 2 1.5 2', '3 3'];
27
19
  /** The host page's colours, so a line keeps its contrast in a light theme and a dark one alike. */
28
20
  const SHADES = ['var(--wp-fg)', 'var(--wp-ok)', 'var(--accent, #5aa9e6)', 'var(--near, #dfa33c)', 'var(--wp-dim)'];
21
+ /** The status a workflow's finished tasks stand in. */
22
+ const DONE = 'done';
29
23
 
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 => {
24
+ const readChoice = (level: string): ReadonlyArray<string> | null => {
40
25
  try {
41
- const stored = window.localStorage.getItem(STORED_CHOICE);
26
+ const stored = window.localStorage.getItem(`${STORED_CHOICE}:${level}`);
42
27
  return stored === null ? null : (JSON.parse(stored) as ReadonlyArray<string>);
43
28
  } catch {
44
29
  return null;
45
30
  }
46
31
  };
47
32
 
48
- export function QueueChart({ view }: { readonly view: WorkflowsView }) {
49
- const all = queueSeries(view);
33
+ export interface QueueChartProps {
34
+ readonly view: Pick<WorkflowsView, 'at' | 'queueHistory'>;
35
+ /** The table's rows: the workflows of the level being looked at, in its order. */
36
+ readonly workflows: ReadonlyArray<WorkflowView>;
37
+ /** The level, for the reader's choice of lines there. */
38
+ readonly level: string;
39
+ /** What the first column holds: a step of the level, or the workflow itself. */
40
+ readonly rowWord: string;
41
+ }
42
+
43
+ export function QueueChart({ view, workflows, level, rowWord }: QueueChartProps) {
44
+ const rows = queueRows({ workflows, history: view.queueHistory, at: view.at });
45
+ const all = rows.flatMap((r) => r.lines);
50
46
  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);
47
+ useEffect(() => setChosen(readChoice(level)), [level]);
48
+ const shownAtFirst = all.filter((l) => l.status === DONE && l.now.tasks > 0).sort((a, b) => b.now.tasks - a.now.tasks).slice(0, SHOWN_AT_FIRST).map((l) => l.key);
53
49
  const shownKeys = chosen ?? shownAtFirst;
54
- const shown = all.filter((s) => shownKeys.includes(s.key));
50
+ const shown = all.filter((l) => shownKeys.includes(l.key));
55
51
  const choose = (key: string, on: boolean) => {
56
52
  const next = on ? [...shownKeys, key] : shownKeys.filter((k) => k !== key);
57
53
  setChosen(next);
58
- try { window.localStorage.setItem(STORED_CHOICE, JSON.stringify(next)); } catch { /* A browser that keeps nothing shows the first lines again. */ }
54
+ try { window.localStorage.setItem(`${STORED_CHOICE}:${level}`, JSON.stringify(next)); } catch { /* A browser that keeps nothing shows the first lines again. */ }
59
55
  };
60
56
 
61
57
  // Drawn at the width it is given, so its type stays small and sharp on a phone and a desktop alike.
@@ -71,67 +67,84 @@ export function QueueChart({ view }: { readonly view: WorkflowsView }) {
71
67
  return () => watch.disconnect();
72
68
  }, []);
73
69
 
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)));
70
+ if (rows.length === 0) return null;
71
+ const statuses = rows[0]!.lines.map((l) => l.status);
72
+ const H = 130;
73
+ const P = { t: 8, r: 18, b: 18, l: 40 };
74
+ const from = Math.min(view.at - 3600, ...shown.flatMap((l) => l.points.map((p) => p.at)));
78
75
  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);
76
+ const Y = (percent: number) => H - P.b - (percent / 100) * (H - P.t - P.b);
77
+ // Each line's number at its end, moved apart so no two overlap.
78
+ const ends = shown.map((l, i) => ({ l, i, y: Y(percentOf(l.now)) })).sort((a, b) => a.y - b.y);
79
+ for (let k = 1; k < ends.length; k += 1) ends[k]!.y = Math.max(ends[k]!.y, ends[k - 1]!.y + 10);
83
80
  const recordedSince = view.queueHistory.length === 0 ? null : view.queueHistory[0]!.at;
84
81
 
85
82
  return (
86
- <section className="wp-chart" aria-label="Each queue over time">
83
+ <section className="wp-chart" aria-label="Tasks over time, as a percent of each workflow's tasks">
87
84
  <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>
85
+ <span>Tasks over time</span>
86
+ <span className="wp-mut">{recordedSince === null ? 'recorded from now on, each time a count moves' : `recorded since ${localTime(recordedSince)}`}</span>
106
87
  </div>
107
88
  <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>
89
+ {shown.length === 0 ? <p className="wp-line wp-mut">No line chosen: tick a count in the table below.</p> : (
90
+ <svg width={width} height={H} role="img" aria-label={`Tasks over time, each line a percent of its workflow's tasks: ${shown.map((l) => lineLabel(l, l.now)).join(', ')}`}>
91
+ {[0, 50, 100].map((percent) => (
92
+ <g key={percent}>
93
+ <line x1={P.l} x2={width - P.r} y1={Y(percent)} y2={Y(percent)} stroke="var(--wp-line)" strokeWidth="1" />
94
+ <text x={P.l - 4} y={Y(percent) + 3} textAnchor="end" fontSize="9" fill="var(--wp-dim)">{percent}%</text>
114
95
  </g>
115
96
  ))}
116
97
  <text x={P.l} y={H - 4} fontSize="9" fill="var(--wp-dim)">{localTime(from)}</text>
117
98
  <text x={width - P.r} y={H - 4} fontSize="9" fill="var(--wp-dim)" textAnchor="end">now</text>
118
- {shown.map((s, i) => (
99
+ {shown.map((l, i) => (
119
100
  <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('')}
101
+ key={l.key}
102
+ d={l.points.map((p, k) => (k === 0 ? `M${X(p.at)},${Y(percentOf(p))}` : `H${X(p.at)}V${Y(percentOf(p))}`)).join('')}
122
103
  fill="none" stroke={SHADES[i % SHADES.length]} strokeWidth="1.25" strokeDasharray={DASHES[i % DASHES.length]}
123
104
  />
124
105
  ))}
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
- ))}
106
+ {shown.map((l, i) => <circle key={`now:${l.key}`} cx={X(view.at)} cy={Y(percentOf(l.now))} r="2.2" fill={SHADES[i % SHADES.length]} />)}
107
+ {ends.map(({ l, i, y }) => <text key={l.key} x={width - P.r + 5} y={y + 3} fontSize="9.5" fill="var(--wp-fg)">{i + 1}</text>)}
132
108
  </svg>
133
109
  )}
134
110
  </div>
111
+ <p className="wp-chart-axis wp-mut">Each line: one status, as a percent of all the tasks of its workflow.</p>
112
+ {shown.length === 0 ? null : (
113
+ <ol className="wp-chart-key">
114
+ {shown.map((l, i) => (
115
+ <li key={l.key}>
116
+ <svg width="26" height="8" aria-hidden="true"><line x1="0" x2="26" y1="4" y2="4" stroke={SHADES[i % SHADES.length]} strokeWidth="1.5" strokeDasharray={DASHES[i % DASHES.length]} /></svg>
117
+ {lineLabel(l, l.now)}
118
+ </li>
119
+ ))}
120
+ </ol>
121
+ )}
122
+ <details className="wp-chart-choose">
123
+ <summary>choose lines ({shown.length} of {all.length})</summary>
124
+ <div className="wp-tablewrap">
125
+ <table className="wp-choose">
126
+ <thead>
127
+ <tr><th scope="col">{rowWord}</th>{statuses.map((s) => <th key={s} scope="col" className="wp-r">{s}</th>)}<th scope="col" className="wp-r">total</th></tr>
128
+ </thead>
129
+ <tbody>
130
+ {rows.map((r) => (
131
+ <tr key={r.workflow}>
132
+ <th scope="row">{r.workflow}</th>
133
+ {r.lines.map((l) => (
134
+ <td key={l.key} className="wp-r">
135
+ <label>
136
+ <input type="checkbox" aria-label={`Show ${l.workflow} ${l.status}`} checked={shownKeys.includes(l.key)} onChange={(e) => choose(l.key, e.target.checked)} />
137
+ {l.now.tasks.toLocaleString('en-US')}
138
+ </label>
139
+ </td>
140
+ ))}
141
+ <td className="wp-r">{r.total.toLocaleString('en-US')}</td>
142
+ </tr>
143
+ ))}
144
+ </tbody>
145
+ </table>
146
+ </div>
147
+ </details>
135
148
  </section>
136
149
  );
137
150
  }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * A WORKFLOW'S TASKS OVER TIME, AS SHARES OF ITS TOTAL: one row per workflow, one line per status, each point that status's
3
+ * tasks over every task the workflow had at that moment. Alex, 2026-11-19: "this should really be a table where row is
4
+ * workflow step and column is status. the y axis should always be a percent of the total tasks assigned to the workflow",
5
+ * and of a line's label: "the line label gets the numerator and denominator with percent in parens".
6
+ *
7
+ * Read from the view's history of counts (a row where a count moved, `queue-counts.ts`) and each queue's count now. Pure,
8
+ * with no React and no JSX, so a test reads it without a page.
9
+ */
10
+ import type { QueueCount } from '../storage/task-store';
11
+
12
+ /** One status of one workflow at one moment: its tasks, and every task the workflow had then. */
13
+ export interface QueuePoint {
14
+ /** Unix seconds. */
15
+ readonly at: number;
16
+ readonly tasks: number;
17
+ readonly total: number;
18
+ }
19
+
20
+ /** A line: one status of one workflow over time, its last point the count now. */
21
+ export interface QueueLine {
22
+ readonly key: string;
23
+ readonly workflow: string;
24
+ readonly status: string;
25
+ readonly points: ReadonlyArray<QueuePoint>;
26
+ readonly now: QueuePoint;
27
+ }
28
+
29
+ /** A row of the table: a workflow, its total now, and its line for each status, in the platform's order of statuses. */
30
+ export interface QueueRow {
31
+ readonly workflow: string;
32
+ readonly total: number;
33
+ readonly lines: ReadonlyArray<QueueLine>;
34
+ }
35
+
36
+ /** A point's share of its workflow's tasks, 0 to 100; 0 for a workflow with no task. */
37
+ export const percentOf = (p: Pick<QueuePoint, 'tasks' | 'total'>): number => (p.total === 0 ? 0 : (100 * p.tasks) / p.total);
38
+
39
+ /** A share as a label writes it: a whole percent, and "under 1%" for a share that is not zero and rounds to it. */
40
+ export const percentText = (p: Pick<QueuePoint, 'tasks' | 'total'>): string => {
41
+ const percent = percentOf(p);
42
+ return percent > 0 && percent < 0.5 ? 'under 1%' : `${Math.round(percent)}%`;
43
+ };
44
+
45
+ const written = (n: number): string => n.toLocaleString('en-US');
46
+
47
+ /** A line's label: its status's tasks over its workflow's total, then the percent: `Decompile done 2,510 / 7,273 (35%)`. */
48
+ export const lineLabel = (line: Pick<QueueLine, 'workflow' | 'status'>, at: Pick<QueuePoint, 'tasks' | 'total'>): string =>
49
+ `${line.workflow} ${line.status} ${written(at.tasks)} / ${written(at.total)} (${percentText(at)})`;
50
+
51
+ const keyOf = (workflow: string, status: string) => `${workflow} · ${status}`;
52
+
53
+ /**
54
+ * Each workflow's row. A point is made at each moment a count of the workflow was recorded, from the first at which every
55
+ * status the history holds has a count: before it the total would leave tasks out.
56
+ */
57
+ export const queueRows = (input: {
58
+ /** Each with its tasks by status now, in the platform's order of statuses; none for a workflow with no tasks. */
59
+ readonly workflows: ReadonlyArray<{ readonly name: string; readonly queue: Readonly<Record<string, number>> | null }>;
60
+ /** Oldest first. */
61
+ readonly history: ReadonlyArray<QueueCount>;
62
+ /** When the counts now were read, unix seconds. */
63
+ readonly at: number;
64
+ }): ReadonlyArray<QueueRow> => input.workflows.flatMap((w) => {
65
+ if (w.queue === null) return [];
66
+ const queue = w.queue;
67
+ const statuses = Object.keys(queue);
68
+ const recorded = input.history.filter((r) => r.workflow === w.name && statuses.includes(r.bucket));
69
+ const firstSeen = new Map<string, number>();
70
+ for (const r of recorded) if (!firstSeen.has(r.bucket)) firstSeen.set(r.bucket, r.at);
71
+ const complete = Math.max(-Infinity, ...firstSeen.values());
72
+ const counts = new Map<string, number>(statuses.map((s) => [s, 0]));
73
+ const moments: Array<{ readonly at: number; readonly counts: ReadonlyMap<string, number>; readonly total: number }> = [];
74
+ recorded.forEach((r, i) => {
75
+ counts.set(r.bucket, r.tasks);
76
+ const last = i === recorded.length - 1 || recorded[i + 1]!.at !== r.at;
77
+ if (last && r.at >= complete) moments.push({ at: r.at, counts: new Map(counts), total: [...counts.values()].reduce((a, b) => a + b, 0) });
78
+ });
79
+ const total = statuses.reduce((sum, s) => sum + queue[s]!, 0);
80
+ return [{
81
+ workflow: w.name, total,
82
+ lines: statuses.map((status) => {
83
+ const now = { at: input.at, tasks: queue[status]!, total };
84
+ return { key: keyOf(w.name, status), workflow: w.name, status, now, points: [...moments.map((m) => ({ at: m.at, tasks: m.counts.get(status)!, total: m.total })), now] };
85
+ }),
86
+ }];
87
+ });
@@ -0,0 +1,89 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * THE DRILL-DOWN'S TWO PARTS: the breadcrumb of the workflows opened, each a link back up, and one workflow's own steps,
5
+ * each with its kind in words, a sub-workflow step a link that opens that workflow's view (`drilldown.ts`).
6
+ */
7
+ import { Fragment, type ReactNode } from 'react';
8
+ import type { StepRunsNow, WorkflowRunsNow } from '../views/runs-now';
9
+ import type { StepSummary, WorkflowView } from '../views/workflows-view';
10
+ import { kindWords, type Crumb } from './drilldown';
11
+ import { queueSum } from './queue-table';
12
+
13
+ /** The path opened, top first: every part but the last a link to its level, the last the page's title; `after` follows it. */
14
+ export function Breadcrumb({ crumbs, hrefOf, after }: { readonly crumbs: ReadonlyArray<Crumb>; readonly hrefOf: (path: ReadonlyArray<string>) => string; readonly after?: ReactNode }) {
15
+ return (
16
+ <nav className="wp-crumbs" aria-label="Workflows opened, top first">
17
+ {crumbs.map((c, i) => (
18
+ <Fragment key={c.path.join('/')}>
19
+ {i === 0 ? null : <span className="wp-crumb-sep" aria-hidden="true">›</span>}
20
+ {i === crumbs.length - 1 ? <span className="wp-crumb-here" aria-current="page">{c.name}</span> : <a href={hrefOf(c.path)}>{c.name}</a>}
21
+ </Fragment>
22
+ ))}
23
+ {after}
24
+ </nav>
25
+ );
26
+ }
27
+
28
+ /** A sub-workflow's tasks on one line, as an addition: every category, then their total. */
29
+ const tasksLine = (queue: NonNullable<WorkflowView['queue']>): string => {
30
+ const sum = queueSum(queue);
31
+ return `${sum.addends.map((a) => `${a.text} ${a.category}`).join(' + ')} = ${sum.totalText}`;
32
+ };
33
+
34
+ /** A sub-workflow's runs now against its run limit, in words. */
35
+ const runsLine = (w: WorkflowView, runs: WorkflowRunsNow | undefined): string => {
36
+ const going = runs?.runs ?? 0;
37
+ const limit = w.limits === null ? '' : w.limits.runs === null ? ', no run limit' : `, run limit ${w.limits.runs}`;
38
+ return `${going === 0 ? 'no run going' : `${going} run${going === 1 ? '' : 's'} going`}${limit}`;
39
+ };
40
+
41
+ /** Where runs are in a step now, in words; nothing with none. */
42
+ const inStepLine = (s: StepRunsNow | undefined): string | null => {
43
+ if (s === undefined || (s.inStep === 0 && s.waitingAfter === 0)) return null;
44
+ return [...(s.inStep > 0 ? [`${s.inStep} run${s.inStep === 1 ? '' : 's'} in it now`] : []), ...(s.waitingAfter > 0 ? [`${s.waitingAfter} just past it`] : [])].join(', ');
45
+ };
46
+
47
+ export interface StepListProps {
48
+ readonly steps: ReadonlyArray<StepSummary>;
49
+ /** The path of the level these steps belong to. */
50
+ readonly path: ReadonlyArray<string>;
51
+ readonly hrefOf: (path: ReadonlyArray<string>) => string;
52
+ /** A sub-workflow step's workflow, for its tasks and runs. */
53
+ readonly workflowOf: (name: string) => WorkflowView | undefined;
54
+ readonly runsOf: (workflow: string) => WorkflowRunsNow | undefined;
55
+ /** This level's own runs, by step; none at the top. */
56
+ readonly runs: WorkflowRunsNow | undefined;
57
+ /** A heading the steps under it share (a stage of the project); none where the level has none. */
58
+ readonly groupOf?: (step: StepSummary) => ReactNode | null;
59
+ readonly groupKey?: (step: StepSummary) => string | null;
60
+ }
61
+
62
+ export function StepList({ steps, path, hrefOf, workflowOf, runsOf, runs, groupOf, groupKey }: StepListProps) {
63
+ if (steps.length === 0) return <p className="wp-line wp-mut">It declares no steps.</p>;
64
+ return (
65
+ <ol className="wp-drill-steps">
66
+ {steps.map((s, i) => {
67
+ const sub = s.workflow === null ? undefined : workflowOf(s.workflow);
68
+ const group = groupKey?.(s) ?? null;
69
+ const newGroup = group !== null && (i === 0 || groupKey?.(steps[i - 1]!) !== group);
70
+ const inStep = inStepLine(runs?.steps.find((r) => r.step === s.name));
71
+ return (
72
+ <Fragment key={s.name}>
73
+ {newGroup ? <li className="wp-drill-group">{groupOf?.(s)}</li> : null}
74
+ <li className="wp-drill-step">
75
+ <div className="wp-drill-head">
76
+ {sub === undefined ? <span className="wp-drill-name">{s.name}</span> : <a className="wp-drill-name" href={hrefOf([...path, s.name])}>{s.name} ›</a>}
77
+ <span className="wp-kind">{kindWords(s)}</span>
78
+ </div>
79
+ <div className="wp-drill-what wp-mut">{s.description}</div>
80
+ {sub === undefined || sub.queue === null ? null : <div className="wp-drill-figures">{tasksLine(sub.queue)}</div>}
81
+ {sub === undefined ? null : <div className="wp-drill-figures wp-mut">{runsLine(sub, runsOf(sub.name))}</div>}
82
+ {inStep === null ? null : <div className="wp-drill-figures">{inStep}</div>}
83
+ </li>
84
+ </Fragment>
85
+ );
86
+ })}
87
+ </ol>
88
+ );
89
+ }