@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,204 +1,322 @@
1
1
  'use client';
2
2
 
3
3
  /**
4
- * THE PROJECT'S WORKFLOWS AS A DAG, laid out by ELK's layered algorithm (`elkjs`, which the host page brings, as it brings
5
- * React): each workflow one node, in layers in topological order of the forward edges, so every forward arrow points down;
6
- * each stage's layers kept together (ELK's partitions, one per stage in the project's order) and shown as a band named in
7
- * a gutter on the left that no edge enters. Edges are routed orthogonally around the nodes, each with its label beside its
8
- * own line and its arrowhead at its target. A send-back, the only edge against the flow, is routed apart by ELK as a feedback
9
- * edge, dashed and labelled "sends back". A box's name opens that workflow's own level. Workflows no work flows to or from are not drawn: the list of steps under the map has them.
4
+ * ONE WORKFLOW'S STEPS AS A DAG, the one drawing of a workflow at every depth, the top included: each step a box with its
5
+ * name as its heading, the run's start and end small boxes of their own, laid out by ELK's layered algorithm (`elkjs`, which
6
+ * the host page brings, as it brings React) so every forward arrow points down. Edges are routed orthogonally around the
7
+ * boxes, each with its condition and the window's runs beside its own line and its arrowhead at its target; an edge back to
8
+ * an earlier step is routed apart by ELK as a feedback edge, dashed. What a box shows under its heading is the page's
9
+ * (`WorkflowsDashboard`): a step that is a workflow, that workflow's tasks, runs and limits; any other, its own calls.
10
10
  *
11
- * Chosen over dagre (`@dagrejs/dagre`): ELK routes edges around nodes and places labels beside their own edges, lays out
12
- * partitions in order and routes feedback edges apart; dagre does none of those, and its edges and labels cross nodes.
11
+ * The graph is the workflow's declared one, or for a workflow that declares none its steps in their declared order
12
+ * (`views/step-graph.ts` `inOrder`), so every workflow has one.
13
+ *
14
+ * Steps that feed no other step and that no step feeds, two or more whose lines from the run's start and to its end read
15
+ * the same, are drawn in a grid under the graph with those lines said once in words (`standAloneSteps`): Upkeep's 26 such
16
+ * steps drew 52 lines that all said "on its own trigger" and "what it finishes leaves here", in a row 6,146 px wide.
17
+ *
18
+ * Chosen over dagre (`@dagrejs/dagre`): ELK routes edges around nodes and places labels beside their own edges, and routes
19
+ * feedback edges apart; dagre does none of those, and its edges and labels cross nodes.
13
20
  */
14
21
  import ELK, { type ElkNode } from 'elkjs/lib/elk.bundled.js';
15
22
  import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';
16
- import type { WorkflowFlow } from '../views/workflow-flows';
17
- import type { WorkflowView, WorkflowsView } from '../views/workflows-view';
18
- import { QueueBar } from './queue-bar';
23
+ import { A_STEP_FAILS, RUN_ENDS, RUN_STARTS } from '../graph';
24
+ import type { GraphEdge, WorkflowGraph } from '../views/step-graph';
19
25
 
20
- /** An edge's label: what it is, and along a wait how many wait. */
21
- const flowLabel = (f: WorkflowFlow): string => (f.kind === 'waits on' ? `${f.waiting.toLocaleString('en-US')} wait on it` : f.kind);
22
- /** An edge's line: solid feeds, dashed sends back, dotted gives input, dash-dot waits on. */
23
- const DASH: Readonly<Record<WorkflowFlow['kind'], string | undefined>> = { feeds: undefined, 'sends back': '7 4', 'gives input': '1.5 3.5', 'waits on': '7 3 1.5 3' };
24
-
25
- /** The node's width; its height is measured from what it shows. */
26
+ /** A step box's width; an end's; each box's height is measured from what it shows. */
26
27
  const NODE_WIDTH = 250;
27
- /** The left gutter the stages are named in. */
28
- const GUTTER = 104;
29
- const LABEL_HEIGHT = 15;
30
- const labelWidth = (text: string) => Math.ceil(text.length * 6.3) + 10;
31
-
32
- interface Laid {
33
- readonly nodes: ReadonlyMap<string, { readonly x: number; readonly y: number; readonly h: number }>;
34
- readonly edges: ReadonlyArray<{ readonly flow: WorkflowFlow; readonly points: ReadonlyArray<{ readonly x: number; readonly y: number }>; readonly label: { readonly x: number; readonly y: number; readonly w: number } | null }>;
35
- readonly width: number;
36
- readonly height: number;
28
+ const END_WIDTH = 96;
29
+ const LABEL_LINE = 13;
30
+ /** An edge label's lines are wrapped at this many characters, so a long condition stays beside its own line. */
31
+ const LABEL_CHARS = 22;
32
+ const charWidth = 6.1;
33
+
34
+ const isEnd = (name: string) => name === RUN_STARTS || name === RUN_ENDS || name === A_STEP_FAILS;
35
+
36
+ /** An edge's label: its condition and how many runs took it in the window, wrapped into lines; none with neither. Pure. */
37
+ export const edgeLabelLines = (e: Pick<GraphEdge, 'when' | 'runs'>): ReadonlyArray<string> => {
38
+ const text = [e.when, e.runs === 0 ? '' : `${e.runs.toLocaleString('en-US')} run${e.runs === 1 ? '' : 's'}`].filter((t) => t !== '').join(' · ');
39
+ const lines: string[] = [];
40
+ for (const word of text.split(' ').filter((w) => w !== '')) {
41
+ const last = lines[lines.length - 1];
42
+ if (last !== undefined && last.length + 1 + word.length <= LABEL_CHARS) lines[lines.length - 1] = `${last} ${word}`;
43
+ else lines.push(word);
44
+ }
45
+ return lines;
46
+ };
47
+
48
+ /**
49
+ * The boxes a graph draws, in the order ELK is given them, which decides which edges go against the flow: the run's start,
50
+ * then each step by how few edges reach it from the start (ties, and steps no edge reaches, in their declared order), then
51
+ * the ends. In declared order alone, Decompile's Pick, declared before the claim step every run takes first, was drawn above
52
+ * the run's start. Pure.
53
+ */
54
+ export const graphBoxes = (graph: Pick<WorkflowGraph, 'steps' | 'edges'>): ReadonlyArray<string> => {
55
+ const names = graph.steps.map((s) => s.name);
56
+ const depth = new Map<string, number>([[RUN_STARTS, 0]]);
57
+ for (let frontier = [RUN_STARTS], d = 1; frontier.length > 0; d += 1) {
58
+ frontier = graph.edges.filter((e) => frontier.includes(e.from) && !depth.has(e.to)).map((e) => e.to);
59
+ for (const to of frontier) depth.set(to, d);
60
+ }
61
+ const byFlow = [...names].sort((a, b) => (depth.get(a) ?? Infinity) - (depth.get(b) ?? Infinity) || names.indexOf(a) - names.indexOf(b));
62
+ return [RUN_STARTS, ...(graph.edges.some((e) => e.from === A_STEP_FAILS) ? [A_STEP_FAILS] : []), ...byFlow, RUN_ENDS];
63
+ };
64
+
65
+ /** Steps drawn in a grid without lines: each one's only lines are one from the run's start and one to its end, labelled as given. */
66
+ export interface StandAloneSteps {
67
+ readonly steps: ReadonlyArray<string>;
68
+ readonly into: ReadonlyArray<string>;
69
+ readonly outOf: ReadonlyArray<string>;
37
70
  }
38
71
 
39
- const elk = new ELK();
72
+ /**
73
+ * A graph's steps that feed no other step and that no step feeds, grouped by the labels of their two lines, each group of
74
+ * two or more to be drawn in a grid; and the graph left to lay out, without them. A step on its own keeps its lines, and so
75
+ * does one whose lines read differently from every other's (Repair names' two steps, each with its own condition). Pure.
76
+ */
77
+ export const standAloneSteps = (graph: Pick<WorkflowGraph, 'steps' | 'edges'>): { readonly grids: ReadonlyArray<StandAloneSteps>; readonly drawn: Pick<WorkflowGraph, 'steps' | 'edges'> } => {
78
+ const groups = new Map<string, { readonly steps: string[]; readonly into: ReadonlyArray<string>; readonly outOf: ReadonlyArray<string> }>();
79
+ for (const { name } of graph.steps) {
80
+ const touching = graph.edges.filter((e) => e.from === name || e.to === name);
81
+ const into = touching.find((e) => e.from === RUN_STARTS);
82
+ const outOf = touching.find((e) => e.to === RUN_ENDS);
83
+ if (touching.length !== 2 || into === undefined || outOf === undefined) continue;
84
+ const labels = { into: edgeLabelLines(into), outOf: edgeLabelLines(outOf) };
85
+ const key = JSON.stringify(labels);
86
+ const group = groups.get(key);
87
+ if (group === undefined) groups.set(key, { steps: [name], ...labels });
88
+ else group.steps.push(name);
89
+ }
90
+ const grids = [...groups.values()].filter((g) => g.steps.length >= 2);
91
+ const apart = new Set(grids.flatMap((g) => g.steps));
92
+ return {
93
+ grids,
94
+ drawn: { steps: graph.steps.filter((s) => !apart.has(s.name)), edges: graph.edges.filter((e) => !apart.has(e.from) && !apart.has(e.to)) },
95
+ };
96
+ };
40
97
 
41
- /** The layout of the linked workflows, given each node's height. */
42
- const layOut = async (input: {
43
- /** In pipeline order: by stage, then by depth through forward edges within it. */
44
- readonly workflows: ReadonlyArray<{ readonly name: string; readonly stage: number; readonly height: number }>;
45
- readonly flows: ReadonlyArray<WorkflowFlow>;
46
- }): Promise<Laid> => {
47
- const asked: ElkNode = {
48
- id: 'workflows',
98
+ /** What a grid of steps says in place of their lines: "These 26 steps feed no other step… Into each: on its own trigger." Pure. */
99
+ export const standAloneWords = (grid: StandAloneSteps): string => {
100
+ const into = grid.into.join(' ');
101
+ const outOf = grid.outOf.join(' ');
102
+ return [
103
+ `These ${grid.steps.length} steps feed no other step and no step feeds them, so they are drawn without lines.`,
104
+ ...(into === '' ? [] : [`Into each from the run's start: ${into}.`]),
105
+ ...(outOf === '' ? [] : [`Out of each to the run's end: ${outOf}.`]),
106
+ ].join(' ');
107
+ };
108
+
109
+ /** The edges drawn: those whose two ends are boxes. Pure. */
110
+ export const graphEdges = (graph: Pick<WorkflowGraph, 'steps' | 'edges'>): ReadonlyArray<GraphEdge> => {
111
+ const boxes = new Set(graphBoxes(graph));
112
+ return graph.edges.filter((e) => boxes.has(e.from) && boxes.has(e.to));
113
+ };
114
+
115
+ /** What ELK is asked to lay out, given each box's measured height. Pure, so a test lays a graph out without a page. */
116
+ export const layoutRequest = (input: { readonly graph: Pick<WorkflowGraph, 'steps' | 'edges'>; readonly heightOf: (box: string) => number }): ElkNode => {
117
+ const edges = graphEdges(input.graph);
118
+ return {
119
+ id: 'steps',
49
120
  layoutOptions: {
50
121
  'elk.algorithm': 'layered',
51
122
  'elk.direction': 'DOWN',
52
123
  'elk.edgeRouting': 'ORTHOGONAL',
53
- 'elk.partitioning.activate': 'true',
54
- // One layering for all, so every stage's layers come before the next stage's; laid out apart, unconnected groups sat side by side.
55
- 'elk.separateConnectedComponents': 'false',
56
124
  'elk.layered.feedbackEdges': 'true',
57
- // The platform's pipeline order decides which edges go against the flow: only one to a workflow earlier in it, a
58
- // send-back. Left to itself, ELK kept Retry near-misses' send-back as forward and drew Decompile's feed going up.
125
+ // The declared order decides which edges go against the flow: only one to an earlier step.
59
126
  'elk.layered.cycleBreaking.strategy': 'MODEL_ORDER',
60
127
  'elk.layered.considerModelOrder.strategy': 'NODES_AND_EDGES',
61
- 'elk.layered.spacing.nodeNodeBetweenLayers': '64',
62
- 'elk.spacing.nodeNode': '36',
63
- 'elk.spacing.edgeNode': '18',
64
- 'elk.spacing.edgeEdge': '12',
128
+ // Placed to keep edges short and straight: half the width of the default placement on Decompile's 37 edges (2026-11-21).
129
+ 'elk.layered.nodePlacement.strategy': 'NETWORK_SIMPLEX',
130
+ 'elk.layered.spacing.nodeNodeBetweenLayers': '56',
131
+ 'elk.spacing.nodeNode': '30',
132
+ 'elk.spacing.edgeNode': '16',
133
+ 'elk.spacing.edgeEdge': '10',
65
134
  'elk.spacing.edgeLabel': '4',
66
135
  'elk.layered.edgeLabels.sideSelection': 'SMART_DOWN',
67
- 'elk.padding': `[top=34,left=${GUTTER},bottom=16,right=16]`,
136
+ 'elk.padding': '[top=12,left=12,bottom=12,right=12]',
68
137
  },
69
- children: input.workflows.map((w) => ({ id: w.name, width: NODE_WIDTH, height: w.height, layoutOptions: { 'elk.partitioning.partition': String(w.stage) } })),
70
- edges: input.flows.map((f, i) => ({ id: `edge-${i}`, sources: [f.from], targets: [f.to], labels: [{ id: `label-${i}`, text: flowLabel(f), width: labelWidth(flowLabel(f)), height: LABEL_HEIGHT }] })),
138
+ children: graphBoxes(input.graph).map((name) => ({ id: name, width: isEnd(name) ? END_WIDTH : NODE_WIDTH, height: input.heightOf(name) })),
139
+ edges: edges.map((e, i) => {
140
+ const lines = edgeLabelLines(e);
141
+ return {
142
+ id: `edge-${i}`, sources: [e.from], targets: [e.to],
143
+ labels: lines.length === 0 ? [] : [{ id: `label-${i}`, text: lines.join('\n'), width: Math.ceil(Math.max(...lines.map((l) => l.length)) * charWidth) + 10, height: lines.length * LABEL_LINE + 4 }],
144
+ };
145
+ }),
71
146
  };
72
- const graph = await elk.layout(asked);
73
- const nodes = new Map((graph.children ?? []).map((c) => [c.id, { x: c.x ?? 0, y: c.y ?? 0, h: c.height ?? 0 }]));
74
- const edges = (graph.edges ?? []).map((e, i) => {
147
+ };
148
+
149
+ export interface Laid {
150
+ readonly boxes: ReadonlyMap<string, { readonly x: number; readonly y: number; readonly h: number }>;
151
+ readonly edges: ReadonlyArray<{ readonly edge: GraphEdge; readonly back: boolean; readonly points: ReadonlyArray<{ readonly x: number; readonly y: number }>; readonly label: { readonly x: number; readonly y: number; readonly w: number; readonly lines: ReadonlyArray<string> } | null }>;
152
+ readonly width: number;
153
+ readonly height: number;
154
+ }
155
+
156
+ const elk = new ELK();
157
+
158
+ /** The layout of a graph's boxes and edges, given each box's height. */
159
+ export const layOut = async (input: { readonly graph: Pick<WorkflowGraph, 'steps' | 'edges'>; readonly heightOf: (box: string) => number }): Promise<Laid> => {
160
+ const drawn = graphEdges(input.graph);
161
+ const laid = await elk.layout(layoutRequest(input));
162
+ const boxes = new Map((laid.children ?? []).map((c) => [c.id, { x: c.x ?? 0, y: c.y ?? 0, h: c.height ?? 0 }]));
163
+ const edges = (laid.edges ?? []).map((e, i) => {
75
164
  const s = e.sections?.[0];
76
165
  const label = e.labels?.[0];
166
+ const points = s === undefined ? [] : [s.startPoint, ...(s.bendPoints ?? []), s.endPoint];
167
+ const from = boxes.get(drawn[i]!.from), to = boxes.get(drawn[i]!.to);
77
168
  return {
78
- flow: input.flows[i]!,
79
- points: s === undefined ? [] : [s.startPoint, ...(s.bendPoints ?? []), s.endPoint],
80
- label: label === undefined || label.x === undefined || label.y === undefined ? null : { x: label.x, y: label.y, w: label.width ?? 0 },
169
+ edge: drawn[i]!,
170
+ back: from !== undefined && to !== undefined && to.y < from.y,
171
+ points,
172
+ label: label === undefined || label.x === undefined || label.y === undefined ? null : { x: label.x, y: label.y, w: label.width ?? 0, lines: edgeLabelLines(drawn[i]!) },
81
173
  };
82
174
  });
83
- return { nodes, edges, width: graph.width ?? 0, height: graph.height ?? 0 };
175
+ return { boxes, edges, width: laid.width ?? 0, height: laid.height ?? 0 };
84
176
  };
85
177
 
178
+ /** What one step's box shows: where its heading links (none for a step that is no workflow) and what is under it. */
179
+ export interface StepBox {
180
+ readonly href: string | null;
181
+ readonly title: string;
182
+ readonly body: ReactNode;
183
+ }
184
+
86
185
  export interface WorkflowDagProps {
87
- readonly view: WorkflowsView;
88
- readonly phaseLabel: (phase: string) => string;
89
- /** A box's runs and agents now, with its limit controls. */
90
- readonly nodeStatus: (w: WorkflowView) => ReactNode;
91
- /** The address of a workflow's own level, which its box's name opens. */
92
- readonly hrefOfWorkflow: (workflow: string) => string;
186
+ readonly graph: WorkflowGraph;
187
+ /** A step's box, by the step's name. */
188
+ readonly box: (step: string) => StepBox;
93
189
  }
94
190
 
95
- function Node({ w, nodeStatus, href, style }: { readonly w: WorkflowView; readonly nodeStatus: (w: WorkflowView) => ReactNode; readonly href: string; readonly style?: CSSProperties }) {
191
+ /** A step's box: its name, a link to its workflow where it is one, and what the page shows under it. */
192
+ function StepBoxView({ name, box, style }: { readonly name: string; readonly box: StepBox; readonly style?: CSSProperties }) {
96
193
  return (
97
- <div data-workflow={w.name} className="wp-node" style={style}>
98
- <a className="wp-node-name" href={href} title={`Open ${w.name}: ${w.description}`}>{w.name} ›</a>
99
- {w.queue === null ? null : <QueueBar queue={w.queue} queuedNeedingAnAgent={w.queuedNeedingAnAgent} />}
100
- <div className="wp-node-status">{nodeStatus(w)}</div>
194
+ <div data-step={name} className="wp-node" style={style}>
195
+ {box.href === null ? <span className="wp-node-name" title={box.title}>{name}</span> : <a className="wp-node-name" href={box.href} title={box.title}>{name} ›</a>}
196
+ {box.body}
101
197
  </div>
102
198
  );
103
199
  }
104
200
 
105
- export function WorkflowDag({ view, phaseLabel, nodeStatus, hrefOfWorkflow }: WorkflowDagProps) {
106
- const all = view.groups.flatMap((g) => g.workflows);
107
- const linkedNames = new Set(view.flows.flatMap((f) => [f.from, f.to]));
108
- const linked = all.filter((w) => linkedNames.has(w.name));
109
- const stageOf = new Map(view.groups.map((g, i) => [g.phase, i]));
110
-
111
- // Each box's height, measured as drawn, then the layout from them; laid out again whenever a height or the flows change.
201
+ export function WorkflowDag({ graph: whole, box }: WorkflowDagProps) {
202
+ const { grids, drawn: graph } = standAloneSteps(whole);
203
+ const boxes = graphBoxes(graph);
204
+ // Each box's height, measured as drawn, then the layout from them; laid out again whenever a height or the edges change.
112
205
  const map = useRef<HTMLDivElement>(null);
113
206
  const [heights, setHeights] = useState<string>('');
114
207
  const [laid, setLaid] = useState<Laid | null>(null);
115
208
  const [failed, setFailed] = useState<string | null>(null);
116
- // Opened at its first box: on a phone the box shows one box across, and a map opened at its left edge showed none.
117
- const scrollBox = useRef<HTMLDivElement>(null);
118
- const opened = useRef(false);
119
- useEffect(() => {
120
- if (laid === null || opened.current || scrollBox.current === null) return;
121
- const first = [...laid.nodes.values()].sort((a, b) => a.y - b.y || a.x - b.x)[0];
122
- if (first === undefined) return;
123
- opened.current = true;
124
- if (scrollBox.current.clientWidth < laid.width) scrollBox.current.scrollLeft = Math.max(0, first.x - 12);
125
- }, [laid]);
126
209
  useLayoutEffect(() => {
127
210
  const el = map.current;
128
211
  if (el === null) return;
129
- const measure = () => setHeights(JSON.stringify([...el.querySelectorAll('[data-workflow]')].map((n) => [n.getAttribute('data-workflow'), Math.ceil(n.getBoundingClientRect().height)])));
212
+ const measure = () => setHeights(JSON.stringify([...el.querySelectorAll('[data-step]')].map((n) => [n.getAttribute('data-step'), Math.ceil(n.getBoundingClientRect().height)])));
130
213
  measure();
131
214
  const watch = new ResizeObserver(measure);
132
- for (const n of el.querySelectorAll('[data-workflow]')) watch.observe(n);
215
+ for (const n of el.querySelectorAll('[data-step]')) watch.observe(n);
133
216
  return () => watch.disconnect();
134
- }, [view.at, linked.length]);
135
- const flowsKey = JSON.stringify(view.flows.map((f) => [f.from, f.to, f.kind, flowLabel(f)]));
217
+ }, [boxes.join('\u0000')]);
218
+ const edgesKey = JSON.stringify(graph.edges.map((e) => [e.from, e.to, e.when, e.runs]));
136
219
  useEffect(() => {
137
220
  if (heights === '') return;
138
221
  const h = new Map(JSON.parse(heights) as Array<[string, number]>);
139
222
  let current = true;
140
- const inOrder = [...linked].sort((a, b) => a.place.stage - b.place.stage || a.place.depth - b.place.depth || a.name.localeCompare(b.name));
141
- layOut({ workflows: inOrder.map((w) => ({ name: w.name, stage: stageOf.get(w.phase) ?? 0, height: h.get(w.name) ?? 120 })), flows: view.flows })
223
+ layOut({ graph, heightOf: (name) => h.get(name) ?? 60 })
142
224
  .then((l) => { if (current) { setLaid(l); setFailed(null); } })
143
225
  .catch((e: unknown) => { if (current) setFailed(e instanceof Error ? e.message : String(e)); });
144
226
  return () => { current = false; };
145
- // eslint-disable-next-line react-hooks/exhaustive-deps -- `linked` and `stageOf` follow `heights` and `flowsKey`.
146
- }, [heights, flowsKey]);
147
-
148
- // Each stage's band: from the top of its first box to the bottom of its last.
149
- const bands = laid === null ? [] : view.groups.flatMap((g) => {
150
- const ys = linked.filter((w) => w.phase === g.phase).flatMap((w) => { const n = laid.nodes.get(w.name); return n === undefined ? [] : [{ top: n.y, bottom: n.y + n.h }]; });
151
- return ys.length === 0 ? [] : [{ phase: g.phase, top: Math.min(...ys.map((y) => y.top)) - 24, bottom: Math.max(...ys.map((y) => y.bottom)) + 14 }];
152
- });
153
- if (linked.length === 0) return null;
154
- const others = all.length - linked.length;
227
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- `graph` is read through `edgesKey` and `heights`.
228
+ }, [heights, edgesKey]);
229
+ // Opened at the run's start, once: a graph wider than its box opened at its left edge showed nothing on a phone.
230
+ const scrollBox = useRef<HTMLDivElement>(null);
231
+ const opened = useRef(false);
232
+ useEffect(() => {
233
+ const el = scrollBox.current;
234
+ const start = laid?.boxes.get(RUN_STARTS);
235
+ if (laid === null || opened.current || el === null || start === undefined) return;
236
+ opened.current = true;
237
+ if (el.clientWidth < laid.width) el.scrollLeft = Math.max(0, start.x + END_WIDTH / 2 - el.clientWidth / 2);
238
+ }, [laid]);
239
+ // The frame's width, so a graph wider than it says so in words: Upkeep's 28 steps were 6,146 px wide in a 1,026 px frame.
240
+ // A graph whose every step is in a grid has no frame.
241
+ const framed = graph.steps.length > 0;
242
+ const [frameWidth, setFrameWidth] = useState<number | null>(null);
243
+ useLayoutEffect(() => {
244
+ const el = scrollBox.current;
245
+ if (el === null) return;
246
+ const measure = () => setFrameWidth(el.clientWidth);
247
+ measure();
248
+ const watch = new ResizeObserver(measure);
249
+ watch.observe(el);
250
+ return () => watch.disconnect();
251
+ }, [framed]);
252
+ const wider = laid !== null && frameWidth !== null && frameWidth < laid.width;
253
+ /**
254
+ * EVERY BOX REACHABLE WITH ANY POINTER: the frame scrolls sideways inside itself, but a mouse wheel scrolls only down and
255
+ * an overlay scrollbar is hidden until one scrolls, so a mouse drag on its background (not on a box, whose text can be
256
+ * selected) scrolls it too. A touch scrolls it natively.
257
+ */
258
+ const drag = useRef<{ readonly pointer: number; readonly x: number; readonly scrollLeft: number } | null>(null);
259
+ const onBackground = (target: EventTarget | null): boolean => target instanceof Element && target.closest('.wp-node') === null;
155
260
 
156
261
  return (
157
262
  <div className="wp-dag-wrap">
158
- <p className="wp-line wp-mut">
159
- Each box is one workflow; its name opens it. Arrows point the way work goes, down the page: a solid arrow feeds the next
160
- workflow&apos;s tasks; dashed, &ldquo;sends back&rdquo;, returns work to an earlier one. Each stage is a band, named on the left.
161
- {others === 0 ? null : ` The ${others.toLocaleString('en-US')} workflow${others === 1 ? '' : 's'} no work flows to or from ${others === 1 ? 'is' : 'are'} in the list of steps below.`}
162
- </p>
163
- {failed === null ? null : <p className="wp-line wp-bad">The map could not be laid out: {failed}</p>}
164
- <div ref={scrollBox} className="wp-dag-scroll">
263
+ {failed === null ? null : <p className="wp-line wp-bad">The steps could not be laid out: {failed}</p>}
264
+ {wider ? <p className="wp-line wp-mut">Wider than this frame: scroll it sideways, drag its background, or click it and use the arrow keys.</p> : null}
265
+ {!framed ? null : <div ref={scrollBox} className="wp-dag-scroll" tabIndex={0} role="region" aria-label="The workflow's steps"
266
+ onPointerDown={(e) => {
267
+ if (e.pointerType !== 'mouse' || e.button !== 0 || !onBackground(e.target)) return;
268
+ drag.current = { pointer: e.pointerId, x: e.clientX, scrollLeft: e.currentTarget.scrollLeft };
269
+ e.currentTarget.setPointerCapture(e.pointerId);
270
+ e.preventDefault();
271
+ }}
272
+ onPointerMove={(e) => {
273
+ const d = drag.current;
274
+ if (d !== null && d.pointer === e.pointerId) e.currentTarget.scrollLeft = d.scrollLeft - (e.clientX - d.x);
275
+ }}
276
+ onPointerUp={(e) => { if (drag.current?.pointer === e.pointerId) drag.current = null; }}
277
+ onPointerCancel={() => { drag.current = null; }}>
165
278
  <div ref={map} className="wp-dag" style={{ width: laid === null ? undefined : laid.width, height: laid === null ? undefined : laid.height }}>
166
279
  {laid === null ? null : (
167
280
  <svg className="wp-dag-edges" width={laid.width} height={laid.height} aria-hidden="true">
168
281
  <defs>
169
- <marker id="wp-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="11" markerHeight="11" markerUnits="userSpaceOnUse" orient="auto">
282
+ <marker id="wp-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="10" markerHeight="10" markerUnits="userSpaceOnUse" orient="auto">
170
283
  <path d="M0,0 L10,5 L0,10 z" fill="var(--wp-edge)" />
171
284
  </marker>
172
285
  </defs>
173
- {bands.map((b, i) => (
174
- <g key={b.phase}>
175
- <rect x={0} y={b.top} width={laid.width} height={b.bottom - b.top} fill={i % 2 === 0 ? 'var(--wp-band)' : 'transparent'} />
176
- <foreignObject x={6} y={b.top + 6} width={GUTTER - 16} height={Math.max(40, b.bottom - b.top - 12)}>
177
- <div className="wp-band-name">{phaseLabel(b.phase)}</div>
178
- </foreignObject>
179
- </g>
180
- ))}
181
- {laid.edges.map(({ flow, points }) => (
182
- <polyline key={`${flow.from}>${flow.to}>${flow.kind}`} points={points.map((p) => `${p.x},${p.y}`).join(' ')} fill="none" stroke="var(--wp-edge)"
183
- strokeWidth={flow.kind === 'feeds' ? 1.8 : 1.5} strokeDasharray={DASH[flow.kind]} markerEnd="url(#wp-arrow)" />
286
+ {laid.edges.map(({ edge, back, points }) => (
287
+ <polyline key={`${edge.from}>${edge.to}`} points={points.map((p) => `${p.x},${p.y}`).join(' ')} fill="none" stroke="var(--wp-edge)"
288
+ strokeWidth={edge.runs === 0 ? 1.1 : 1.6} strokeDasharray={back ? '7 4' : undefined} markerEnd="url(#wp-arrow)" />
184
289
  ))}
185
- {laid.edges.map(({ flow, label }) => (label === null ? null : (
186
- <g key={`label:${flow.from}>${flow.to}>${flow.kind}`}>
187
- <rect x={label.x} y={label.y} width={label.w} height={LABEL_HEIGHT} rx={3} fill="var(--wp-bg)" stroke="var(--wp-edge)" strokeWidth="0.7" />
188
- <text x={label.x + 5} y={label.y + 11} fontSize="10.5" fill="var(--wp-fg)">{flowLabel(flow)}{flow.why === null ? null : <title>{flow.why}</title>}</text>
290
+ {laid.edges.map(({ edge, label }) => (label === null ? null : (
291
+ <g key={`label:${edge.from}>${edge.to}`}>
292
+ <rect x={label.x} y={label.y} width={label.w} height={label.lines.length * LABEL_LINE + 4} rx={3} fill="var(--wp-bg)" stroke="var(--wp-edge)" strokeWidth="0.6" />
293
+ <text x={label.x + 5} y={label.y + 12} fontSize="10.5" fill="var(--wp-fg)">
294
+ {label.lines.map((line, i) => <tspan key={i} x={label.x + 5} dy={i === 0 ? 0 : LABEL_LINE}>{line}</tspan>)}
295
+ <title>{`${edge.from} → ${edge.to}`}</title>
296
+ </text>
189
297
  </g>
190
298
  )))}
191
299
  </svg>
192
300
  )}
193
- {linked.map((w) => {
194
- const at = laid?.nodes.get(w.name);
195
- return (
196
- <Node key={w.name} w={w} nodeStatus={nodeStatus} href={hrefOfWorkflow(w.name)}
197
- style={at === undefined ? { position: 'absolute', left: 0, top: 0, visibility: 'hidden' } : { position: 'absolute', left: at.x, top: at.y }} />
198
- );
301
+ {boxes.map((name) => {
302
+ const at = laid?.boxes.get(name);
303
+ const style = at === undefined ? { position: 'absolute' as const, left: 0, top: 0, visibility: 'hidden' as const } : { position: 'absolute' as const, left: at.x, top: at.y };
304
+ if (isEnd(name)) return <div key={name} data-step={name} className="wp-node wp-node-end" style={style}>{name}</div>;
305
+ return <StepBoxView key={name} name={name} box={box(name)} style={style} />;
199
306
  })}
200
307
  </div>
201
- </div>
308
+ </div>}
309
+ {grids.map((grid) => (
310
+ <div key={grid.steps.join('\u0000')} data-stand-alone-steps>
311
+ <p className="wp-line wp-mut">{standAloneWords(grid)}</p>
312
+ <div className="wp-dag-grid" role="list" aria-label="Steps that feed no other step">
313
+ {grid.steps.map((name) => <div key={name} role="listitem"><StepBoxView name={name} box={box(name)} /></div>)}
314
+ </div>
315
+ </div>
316
+ ))}
317
+ {whole.undeclared.length === 0 ? null : (
318
+ <p className="wp-line wp-bad">Taken but not declared: {whole.undeclared.map((e) => `${e.from} → ${e.to} (${e.runs})`).join('; ')}</p>
319
+ )}
202
320
  </div>
203
321
  );
204
322
  }
@@ -1,89 +1,31 @@
1
1
  'use client';
2
2
 
3
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`).
4
+ * WHERE A PAGE IS, AND WHAT IT SHOWS (`drilldown.ts`). Alex, 2026-11-21: "i need to know what workflow I'm looking at and see
5
+ * a breadcrumb back to the top level workflow". Two elements, the same at every depth: the path from the top-level workflow
6
+ * down to this one, every part but the last a link, labelled as the path; and below it the page's title, the workflow
7
+ * opened, by name. A workflow's own steps are its graph's boxes (`workflow-dag.tsx`), each step that is a workflow a link
8
+ * one level down.
6
9
  */
7
10
  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 { addendLabel, queueSum } from './queue-table';
11
+ import type { Crumb } from './drilldown';
12
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 }) {
13
+ /** The path opened, top first: every part but the last a link to its level, the last this page, said and not linked. */
14
+ export function Breadcrumb({ crumbs, hrefOf }: { readonly crumbs: ReadonlyArray<Crumb>; readonly hrefOf: (path: ReadonlyArray<string>) => string }) {
15
15
  return (
16
- <nav className="wp-crumbs" aria-label="Workflows opened, top first">
16
+ <nav className="wp-crumbs" aria-label="Path from the top-level workflow">
17
+ <span className="wp-crumbs-label">Path:</span>
17
18
  {crumbs.map((c, i) => (
18
19
  <Fragment key={c.path.join('/')}>
19
20
  {i === 0 ? null : <span className="wp-crumb-sep" aria-hidden="true">›</span>}
20
21
  {i === crumbs.length - 1 ? <span className="wp-crumb-here" aria-current="page">{c.name}</span> : <a href={hrefOf(c.path)}>{c.name}</a>}
21
22
  </Fragment>
22
23
  ))}
23
- {after}
24
24
  </nav>
25
25
  );
26
26
  }
27
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']>, queuedNeedingAnAgent: WorkflowView['queuedNeedingAnAgent']): string => {
30
- const sum = queueSum(queue, queuedNeedingAnAgent);
31
- return `${sum.addends.map((a) => `${a.text} ${addendLabel(a)}`).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, sub.queuedNeedingAnAgent)}</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
- );
28
+ /** The page's title: the workflow it shows, by name; `after` follows it (its source's link). */
29
+ export function WorkflowTitle({ name, after }: { readonly name: string; readonly after?: ReactNode }) {
30
+ return <h2 className="wp-title">Workflow: {name}{after}</h2>;
89
31
  }