@blackbelt-technology/pi-dashboard-flows-plugin 0.0.1

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.
@@ -0,0 +1,563 @@
1
+ import React, { useMemo, useRef, useState, useEffect } from "react";
2
+ import { useZoomPan } from "../../../client/src/hooks/useZoomPan.js";
3
+ import { ZoomControls } from "../../../client/src/components/ZoomControls.js";
4
+ import { graphlib } from "dagre-d3-es";
5
+ import { layout as dagreLayout } from "dagre-d3-es/src/dagre/index.js";
6
+ import type { FlowState, ArchitectDagStep } from "@blackbelt-technology/pi-dashboard-shared/types.js";
7
+
8
+ // ── Types ───────────────────────────────────────────────────────────
9
+
10
+ /** Step type determines visual rendering:
11
+ * - "agent" (default): solid rounded rect
12
+ * - "fork": diamond-shaped (rotated rect) for decision points
13
+ * - "loop": rounded rect with loop icon/double border
14
+ * - "flow-ref": dashed border for subflows
15
+ */
16
+ export type FlowStepType = "agent" | "fork" | "loop" | "conditional" | "flow-ref";
17
+
18
+ /** Map flow engine stepType string to graph visual type */
19
+ export function mapStepType(stepType: string | undefined): FlowStepType | undefined {
20
+ switch (stepType) {
21
+ case "fork":
22
+ case "conditional":
23
+ case "agent-decision": return "fork";
24
+ case "agent-loop-decision": return "loop";
25
+ case "flow-ref": return "flow-ref";
26
+ default: return undefined; // "agent" → default styling
27
+ }
28
+ }
29
+
30
+ export interface FlowGraphStep {
31
+ id: string;
32
+ label: string;
33
+ status: "pending" | "running" | "complete" | "error" | "blocked";
34
+ blockedBy: string[];
35
+ type?: FlowStepType;
36
+ /** For loop steps: the step ID to loop back to (rendered as a backward arrow) */
37
+ loopTarget?: string;
38
+ }
39
+
40
+ /** Step types that act as segment separators (non-agent control flow) */
41
+ const SEPARATOR_STEP_TYPES = new Set(["fork", "conditional", "agent-decision", "agent-loop-decision", "flow-ref"]);
42
+
43
+ /** Synthesize implicit sequential edges that aren't expressed in blockedBy.
44
+ * - Steps after a separator with no blockedBy get an edge from the preceding separator.
45
+ * - Loop exit_target steps get an edge from the loop step. */
46
+ export function synthesizeImplicitEdges(
47
+ steps: FlowGraphStep[],
48
+ dagSteps: Array<{ id: string; stepType?: string; exitTarget?: string }>,
49
+ ): void {
50
+ const allStepIds = new Set(steps.map(s => s.id));
51
+ const stepById = new Map(steps.map(s => [s.id, s]));
52
+
53
+ // 1. Exit target edges: loop-decision → exit_target
54
+ for (const ds of dagSteps) {
55
+ if (ds.exitTarget && allStepIds.has(ds.exitTarget)) {
56
+ const target = stepById.get(ds.exitTarget);
57
+ if (target && !target.blockedBy.includes(ds.id)) {
58
+ target.blockedBy = [...target.blockedBy, ds.id];
59
+ }
60
+ }
61
+ }
62
+
63
+ // 2. Implicit segment edges: steps with no blockedBy after a separator
64
+ for (let i = 1; i < dagSteps.length; i++) {
65
+ const curr = stepById.get(dagSteps[i].id);
66
+ if (!curr || curr.blockedBy.length > 0) continue;
67
+
68
+ for (let j = i - 1; j >= 0; j--) {
69
+ const prev = dagSteps[j];
70
+ if (prev.stepType && SEPARATOR_STEP_TYPES.has(prev.stepType) && allStepIds.has(prev.id)) {
71
+ curr.blockedBy = [prev.id];
72
+ break;
73
+ }
74
+ if ((!prev.stepType || prev.stepType === "agent") && allStepIds.has(prev.id)) {
75
+ curr.blockedBy = [prev.id];
76
+ break;
77
+ }
78
+ }
79
+ }
80
+ }
81
+
82
+ // ── Data converters ────────────────────────────────────────────────
83
+
84
+ /** Convert FlowState (running/completed flow) to FlowGraphStep array.
85
+ * Uses dagSteps when available, falls back to agents map for backward compat. */
86
+ export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
87
+ if (flowState.dagSteps && flowState.dagSteps.length > 0) {
88
+ const stepStatus = new Map<string, FlowGraphStep["status"]>();
89
+ for (const [key, agent] of flowState.agents) {
90
+ stepStatus.set(key, agent.status);
91
+ if (agent.stepId) stepStatus.set(agent.stepId, agent.status);
92
+ stepStatus.set(agent.agentName, agent.status);
93
+ }
94
+
95
+ const allStepIds = new Set(flowState.dagSteps.map(s => s.id));
96
+ const steps: FlowGraphStep[] = flowState.dagSteps.map(step => ({
97
+ id: step.id,
98
+ label: step.id,
99
+ status: stepStatus.get(step.id) || stepStatus.get(step.agent || "") || "pending",
100
+ blockedBy: step.blockedBy.filter(dep => allStepIds.has(dep)),
101
+ type: mapStepType(step.stepType),
102
+ loopTarget: step.loopTarget && allStepIds.has(step.loopTarget) ? step.loopTarget : undefined,
103
+ }));
104
+
105
+ // Add flow-ref steps not in dagSteps
106
+ for (const ref of flowState.flowRefSteps || []) {
107
+ if (!allStepIds.has(ref.id)) {
108
+ steps.push({
109
+ id: ref.id,
110
+ label: ref.label,
111
+ status: "pending",
112
+ blockedBy: ref.blockedBy.filter(dep => allStepIds.has(dep)),
113
+ type: "flow-ref",
114
+ });
115
+ }
116
+ }
117
+
118
+ synthesizeImplicitEdges(steps, flowState.dagSteps);
119
+ return steps;
120
+ }
121
+
122
+ // Fallback: build from agents map (backward compat for old events without dagSteps)
123
+ const stepToAgent = new Map<string, string>();
124
+ for (const agent of flowState.agents.values()) {
125
+ if (agent.stepId) stepToAgent.set(agent.stepId, agent.agentName);
126
+ }
127
+ const agentSteps: FlowGraphStep[] = Array.from(flowState.agents.values()).map(agent => ({
128
+ id: agent.agentName,
129
+ label: agent.label || agent.agentName,
130
+ status: agent.status,
131
+ blockedBy: agent.blockedBy
132
+ .map(depId => stepToAgent.get(depId) || depId)
133
+ .filter(name => flowState.agents.has(name) || flowState.flowRefSteps?.some(r => r.id === name)),
134
+ }));
135
+ const flowRefSteps: FlowGraphStep[] = (flowState.flowRefSteps || []).map(ref => ({
136
+ id: ref.id,
137
+ label: ref.label,
138
+ status: "pending" as const,
139
+ blockedBy: ref.blockedBy.map(depId => stepToAgent.get(depId) || depId),
140
+ type: "flow-ref" as const,
141
+ }));
142
+ return [...agentSteps, ...flowRefSteps];
143
+ }
144
+
145
+ /** Convert ArchitectState dagSteps (design-time, all pending) to FlowGraphStep array. */
146
+ export function architectStepsToGraphSteps(dagSteps: ArchitectDagStep[]): FlowGraphStep[] {
147
+ const allStepIds = new Set(dagSteps.map(s => s.id));
148
+ const steps: FlowGraphStep[] = dagSteps.map((step) => ({
149
+ id: step.id,
150
+ label: step.agentName || step.id,
151
+ status: "pending" as const,
152
+ blockedBy: [...step.blockedBy],
153
+ type: mapStepType(step.stepType),
154
+ loopTarget: step.loopTarget && allStepIds.has(step.loopTarget) ? step.loopTarget : undefined,
155
+ }));
156
+
157
+ synthesizeImplicitEdges(steps, dagSteps);
158
+ return steps;
159
+ }
160
+
161
+ interface PositionedNode {
162
+ id: string;
163
+ label: string;
164
+ status: FlowGraphStep["status"];
165
+ type?: FlowStepType;
166
+ x: number;
167
+ y: number;
168
+ width: number;
169
+ height: number;
170
+ }
171
+
172
+ interface PositionedEdge {
173
+ source: string;
174
+ target: string;
175
+ points: Array<{ x: number; y: number }>;
176
+ sourceStatus: FlowGraphStep["status"];
177
+ targetStatus: FlowGraphStep["status"];
178
+ }
179
+
180
+ interface LoopBackEdge {
181
+ source: string;
182
+ target: string;
183
+ sourceStatus: FlowGraphStep["status"];
184
+ targetStatus: FlowGraphStep["status"];
185
+ path: string;
186
+ }
187
+
188
+ interface LayoutResult {
189
+ nodes: PositionedNode[];
190
+ edges: PositionedEdge[];
191
+ loopEdges: LoopBackEdge[];
192
+ width: number;
193
+ height: number;
194
+ }
195
+
196
+ // ── Status styling ──────────────────────────────────────────────────
197
+
198
+ const STATUS_COLORS: Record<string, { border: string; fill: string; text: string }> = {
199
+ pending: { border: "#555", fill: "#2a2a2a", text: "#888" },
200
+ running: { border: "#eab308", fill: "#2a2800", text: "#eab308" },
201
+ complete: { border: "#22c55e", fill: "#0a2a10", text: "#22c55e" },
202
+ error: { border: "#ef4444", fill: "#2a0a0a", text: "#ef4444" },
203
+ blocked: { border: "#f97316", fill: "#2a1a00", text: "#f97316" },
204
+ };
205
+
206
+ function getEdgeColor(sourceStatus: string, targetStatus: string): { stroke: string; animated: boolean; dashed: boolean } {
207
+ if (sourceStatus === "complete" && targetStatus === "running") {
208
+ return { stroke: "#eab308", animated: true, dashed: false };
209
+ }
210
+ if (sourceStatus === "complete" && targetStatus === "complete") {
211
+ return { stroke: "#22c55e", animated: false, dashed: false };
212
+ }
213
+ if (sourceStatus === "complete") {
214
+ return { stroke: "#666", animated: false, dashed: false };
215
+ }
216
+ if (targetStatus === "error") {
217
+ return { stroke: "#ef4444", animated: false, dashed: false };
218
+ }
219
+ return { stroke: "#444", animated: false, dashed: true };
220
+ }
221
+
222
+ // ── Dagre layout ────────────────────────────────────────────────────
223
+
224
+ const NODE_WIDTH = 120;
225
+ const NODE_HEIGHT = 32;
226
+ const FONT_SIZE = 11;
227
+ const ARROW_SIZE = 6;
228
+
229
+ export function computeLayout(steps: FlowGraphStep[]): LayoutResult {
230
+ if (steps.length === 0) {
231
+ return { nodes: [], edges: [], loopEdges: [], width: 0, height: 0 };
232
+ }
233
+
234
+ const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
235
+ g.setGraph({ rankdir: "LR", nodesep: 15, ranksep: 40, marginx: 16, marginy: 16 });
236
+
237
+ const statusMap = new Map<string, FlowGraphStep["status"]>();
238
+ for (const step of steps) {
239
+ g.setNode(step.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
240
+ statusMap.set(step.id, step.status);
241
+ }
242
+
243
+ for (const step of steps) {
244
+ for (const dep of step.blockedBy) {
245
+ if (statusMap.has(dep)) {
246
+ g.setEdge(dep, step.id);
247
+ }
248
+ }
249
+ }
250
+
251
+ dagreLayout(g, {});
252
+
253
+ const graphMeta = g.graph();
254
+ const nodes: PositionedNode[] = steps.map((step) => {
255
+ const n = g.node(step.id);
256
+ return {
257
+ id: step.id,
258
+ label: step.label,
259
+ status: step.status,
260
+ type: step.type,
261
+ x: n.x - NODE_WIDTH / 2,
262
+ y: n.y - NODE_HEIGHT / 2,
263
+ width: NODE_WIDTH,
264
+ height: NODE_HEIGHT,
265
+ };
266
+ });
267
+
268
+ const edges: PositionedEdge[] = [];
269
+ for (const step of steps) {
270
+ for (const dep of step.blockedBy) {
271
+ if (statusMap.has(dep)) {
272
+ const edgeData = g.edge(dep, step.id);
273
+ if (edgeData) {
274
+ edges.push({
275
+ source: dep,
276
+ target: step.id,
277
+ points: edgeData.points,
278
+ sourceStatus: statusMap.get(dep) || "pending",
279
+ targetStatus: step.status,
280
+ });
281
+ }
282
+ }
283
+ }
284
+ }
285
+
286
+ // Compute loop-back edges (backward arrows that skip dagre to avoid cycles)
287
+ const loopEdges: LoopBackEdge[] = [];
288
+ const nodeById = new Map(nodes.map(n => [n.id, n]));
289
+ const LOOP_MARGIN = 24; // vertical space above the graph for loop arcs
290
+
291
+ // Find the topmost node edge to route arcs above everything
292
+ let minY = Infinity;
293
+ for (const n of nodes) {
294
+ if (n.y < minY) minY = n.y;
295
+ }
296
+
297
+ for (const step of steps) {
298
+ if (step.loopTarget && nodeById.has(step.loopTarget)) {
299
+ const src = nodeById.get(step.id)!;
300
+ const tgt = nodeById.get(step.loopTarget)!;
301
+ // Arc above the entire graph so it doesn't overlap any nodes
302
+ const srcCx = src.x + src.width / 2;
303
+ const srcTop = src.y;
304
+ const tgtCx = tgt.x + tgt.width / 2;
305
+ const tgtTop = tgt.y;
306
+ const arcY = minY - LOOP_MARGIN;
307
+ const path = `M${srcCx},${srcTop} C${srcCx},${arcY} ${tgtCx},${arcY} ${tgtCx},${tgtTop}`;
308
+ loopEdges.push({
309
+ source: step.id,
310
+ target: step.loopTarget,
311
+ sourceStatus: step.status,
312
+ targetStatus: statusMap.get(step.loopTarget) || "pending",
313
+ path,
314
+ });
315
+ }
316
+ }
317
+
318
+ // Compute bounding box including loop arcs
319
+ const graphWidth = graphMeta.width || 200;
320
+ const graphHeight = graphMeta.height || 50;
321
+ const loopArcTop = loopEdges.length > 0 ? minY - LOOP_MARGIN - ARROW_SIZE : 0;
322
+ const yOffset = loopArcTop < 0 ? -loopArcTop : 0;
323
+
324
+ // Shift all geometry down to make room for arcs above
325
+ if (yOffset > 0) {
326
+ for (const n of nodes) n.y += yOffset;
327
+ for (const e of edges) {
328
+ for (const p of e.points) p.y += yOffset;
329
+ }
330
+ for (const le of loopEdges) {
331
+ // Recompute path with shifted coordinates
332
+ const src = nodeById.get(le.source)!;
333
+ const tgt = nodeById.get(le.target)!;
334
+ const srcCx = src.x + src.width / 2;
335
+ const srcTop = src.y;
336
+ const tgtCx = tgt.x + tgt.width / 2;
337
+ const tgtTop = tgt.y;
338
+ const arcY = ARROW_SIZE; // top of SVG with small padding
339
+ le.path = `M${srcCx},${srcTop} C${srcCx},${arcY} ${tgtCx},${arcY} ${tgtCx},${tgtTop}`;
340
+ }
341
+ }
342
+
343
+ // Compute actual bounding box from positioned nodes (dagre's reported
344
+ // dimensions may not account for yOffset shift or full node extents)
345
+ let maxRight = 0;
346
+ let maxBottom = 0;
347
+ for (const n of nodes) {
348
+ const right = n.x + n.width;
349
+ const bottom = n.y + n.height;
350
+ if (right > maxRight) maxRight = right;
351
+ if (bottom > maxBottom) maxBottom = bottom;
352
+ }
353
+ const actualWidth = Math.max(graphWidth, maxRight + 16);
354
+ const actualHeight = Math.max(graphHeight + yOffset, maxBottom + 16);
355
+
356
+ return {
357
+ nodes,
358
+ edges,
359
+ loopEdges,
360
+ width: actualWidth,
361
+ height: actualHeight,
362
+ };
363
+ }
364
+
365
+ // ── SVG edge path (cubic bezier through waypoints) ──────────────────
366
+
367
+ function buildEdgePath(points: Array<{ x: number; y: number }>): string {
368
+ if (points.length < 2) return "";
369
+ const [first, ...rest] = points;
370
+ if (rest.length === 1) {
371
+ return `M${first.x},${first.y} L${rest[0].x},${rest[0].y}`;
372
+ }
373
+ let d = `M${first.x},${first.y}`;
374
+ for (let i = 0; i < rest.length; i++) {
375
+ if (i === 0) {
376
+ const cp1x = first.x + (rest[0].x - first.x) * 0.5;
377
+ d += ` C${cp1x},${first.y} ${cp1x},${rest[0].y} ${rest[0].x},${rest[0].y}`;
378
+ } else {
379
+ const prev = rest[i - 1];
380
+ const curr = rest[i];
381
+ const cpx = prev.x + (curr.x - prev.x) * 0.5;
382
+ d += ` C${cpx},${prev.y} ${cpx},${curr.y} ${curr.x},${curr.y}`;
383
+ }
384
+ }
385
+ return d;
386
+ }
387
+
388
+ // ── Component ───────────────────────────────────────────────────────
389
+
390
+ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
391
+ const layout = useMemo(() => {
392
+ if (steps.length === 0) return null;
393
+ try {
394
+ return computeLayout(steps);
395
+ } catch (err) {
396
+ console.error("[FlowGraph] computeLayout failed:", err, "steps:", steps);
397
+ return null;
398
+ }
399
+ }, [steps]);
400
+
401
+ const { state: zoom, handlers, zoomIn, zoomOut, reset } = useZoomPan();
402
+ const [hovered, setHovered] = useState(false);
403
+ const containerRef = useRef<HTMLDivElement>(null);
404
+
405
+ // Reset zoom/pan when the graph layout changes (new steps, different dimensions)
406
+ const prevStepCount = useRef(steps.length);
407
+ useEffect(() => {
408
+ if (steps.length !== prevStepCount.current) {
409
+ prevStepCount.current = steps.length;
410
+ reset();
411
+ }
412
+ }, [steps.length, reset]);
413
+
414
+ // Attach non-passive wheel listener (React onWheel is passive and can't preventDefault)
415
+ useEffect(() => {
416
+ const el = containerRef.current;
417
+ if (!el) return;
418
+ const wheelHandler = handlers.onWheel as EventListener;
419
+ el.addEventListener("wheel", wheelHandler, { passive: false });
420
+ return () => el.removeEventListener("wheel", wheelHandler);
421
+ }, [handlers.onWheel]);
422
+
423
+ if (!layout || layout.nodes.length === 0) return null;
424
+
425
+ const svgWidth = Math.max(layout.width, 150);
426
+ const svgHeight = Math.max(layout.height, 50);
427
+
428
+ return (
429
+ <div
430
+ ref={containerRef}
431
+ className="flow-dag-graph-container relative"
432
+ style={{ overflow: "visible" }}
433
+ onPointerDown={handlers.onPointerDown}
434
+ onPointerMove={handlers.onPointerMove}
435
+ onPointerUp={handlers.onPointerUp}
436
+ onDoubleClick={handlers.onDoubleClick}
437
+ onTouchMove={handlers.onTouchMove}
438
+ onTouchEnd={handlers.onTouchEnd}
439
+ onMouseEnter={() => setHovered(true)}
440
+ onMouseLeave={() => setHovered(false)}
441
+ >
442
+ {hovered && (
443
+ <ZoomControls
444
+ onZoomIn={zoomIn}
445
+ onZoomOut={zoomOut}
446
+ onReset={reset}
447
+ scale={zoom.scale}
448
+ />
449
+ )}
450
+ <div
451
+ style={{
452
+ transform: `translate(${zoom.translateX}px, ${zoom.translateY}px) scale(${zoom.scale})`,
453
+ transformOrigin: "0 0",
454
+ }}
455
+ >
456
+ <svg
457
+ width={svgWidth}
458
+ height={svgHeight}
459
+ viewBox={`0 0 ${svgWidth} ${svgHeight}`}
460
+ className="flow-dag-graph"
461
+ style={{ display: "block", overflow: "visible" }}
462
+ >
463
+ <defs>
464
+ {["#444", "#666", "#22c55e", "#eab308", "#ef4444", "#a855f7"].map((color) => (
465
+ <marker
466
+ key={color}
467
+ id={`arrow-${color.replace("#", "")}`}
468
+ viewBox={`0 0 ${ARROW_SIZE * 2} ${ARROW_SIZE * 2}`}
469
+ refX={ARROW_SIZE * 2 - 1}
470
+ refY={ARROW_SIZE}
471
+ markerWidth={ARROW_SIZE}
472
+ markerHeight={ARROW_SIZE}
473
+ orient="auto-start-reverse"
474
+ >
475
+ <path d={`M0,0 L${ARROW_SIZE * 2},${ARROW_SIZE} L0,${ARROW_SIZE * 2} Z`} fill={color} />
476
+ </marker>
477
+ ))}
478
+ </defs>
479
+
480
+ {/* Edges */}
481
+ {layout.edges.map((edge, i) => {
482
+ const { stroke, animated, dashed } = getEdgeColor(edge.sourceStatus, edge.targetStatus);
483
+ return (
484
+ <path
485
+ key={`edge-${i}`}
486
+ d={buildEdgePath(edge.points)}
487
+ fill="none"
488
+ stroke={stroke}
489
+ strokeWidth={1.5}
490
+ strokeDasharray={dashed ? "4 3" : animated ? "6 3" : "none"}
491
+ markerEnd={`url(#arrow-${stroke.replace("#", "")})`}
492
+ className={animated ? "flow-edge-animated" : ""}
493
+ />
494
+ );
495
+ })}
496
+
497
+ {/* Loop-back edges (backward arrows below the graph) */}
498
+ {layout.loopEdges.map((edge, i) => (
499
+ <path
500
+ key={`loop-${i}`}
501
+ d={edge.path}
502
+ fill="none"
503
+ stroke="#a855f7"
504
+ strokeWidth={1.5}
505
+ strokeDasharray="5 3"
506
+ markerEnd="url(#arrow-a855f7)"
507
+ opacity={0.7}
508
+ />
509
+ ))}
510
+
511
+ {/* Nodes */}
512
+ {layout.nodes.map((node) => {
513
+ const style = STATUS_COLORS[node.status] || STATUS_COLORS.pending;
514
+ const isRunning = node.status === "running";
515
+ // Add type prefix icon to label
516
+ const typePrefix = node.type === "fork" ? "◇ "
517
+ : node.type === "loop" ? "↻ "
518
+ : node.type === "conditional" ? "? "
519
+ : "";
520
+ const displayLabel = typePrefix + node.label;
521
+ const availW = node.width - 16;
522
+ const naturalW = displayLabel.length * FONT_SIZE * 0.6;
523
+ const labelFontSize = naturalW > availW
524
+ ? Math.max(7, FONT_SIZE * (availW / naturalW))
525
+ : FONT_SIZE;
526
+
527
+ return (
528
+ <g
529
+ key={node.id}
530
+ data-node={node.id}
531
+ style={{ cursor: "default" }}
532
+ className={isRunning ? "flow-node-running" : ""}
533
+ >
534
+ <rect
535
+ x={node.x}
536
+ y={node.y}
537
+ width={node.width}
538
+ height={node.height}
539
+ rx={5}
540
+ ry={5}
541
+ fill={style.fill}
542
+ stroke={style.border}
543
+ strokeWidth={1.5}
544
+ />
545
+ <text
546
+ x={node.x + node.width / 2}
547
+ y={node.y + node.height / 2 + 1}
548
+ fontSize={labelFontSize}
549
+ fill={style.text}
550
+ dominantBaseline="middle"
551
+ textAnchor="middle"
552
+ fontFamily="system-ui, -apple-system, sans-serif"
553
+ >
554
+ {displayLabel}
555
+ </text>
556
+ </g>
557
+ );
558
+ })}
559
+ </svg>
560
+ </div>
561
+ </div>
562
+ );
563
+ }
@@ -0,0 +1,87 @@
1
+ import React, { useState, useRef, useEffect } from "react";
2
+ import { Icon } from "@mdi/react";
3
+ import { mdiPlay } from "@mdi/js";
4
+ import { DialogPortal } from "../../../client/src/components/DialogPortal.js";
5
+ import { GateSlot, aggregateGateState } from "../../../client/src/components/extension-ui/GateSlot.js";
6
+ import type { DashboardSession } from "@blackbelt-technology/pi-dashboard-shared/types.js";
7
+
8
+ export function FlowLaunchDialog({
9
+ flowName,
10
+ description,
11
+ onSubmit,
12
+ onCancel,
13
+ session,
14
+ }: {
15
+ flowName: string;
16
+ description?: string;
17
+ onSubmit: (task: string) => void;
18
+ onCancel: () => void;
19
+ /** Phase-2 decorator host — used to gate the Run button when an extension declares the flow unavailable. */
20
+ session?: Pick<DashboardSession, "uiDecorators">;
21
+ }) {
22
+ // Phase-2 (`add-extension-ui-decorations`): aggregate any `gate` decorators
23
+ // targeting this flowId. Most-restrictive-wins: any `available: false`
24
+ // disables the Run button and renders the reason inline.
25
+ const gateState = aggregateGateState(session?.uiDecorators, flowName);
26
+ const [task, setTask] = useState("");
27
+ const inputRef = useRef<HTMLInputElement>(null);
28
+
29
+ useEffect(() => {
30
+ inputRef.current?.focus();
31
+ }, []);
32
+
33
+ const handleSubmit = (e: React.FormEvent) => {
34
+ e.preventDefault();
35
+ onSubmit(task.trim());
36
+ };
37
+
38
+ return (
39
+ <DialogPortal>
40
+ <div className="fixed inset-0 z-[60] flex items-center justify-center">
41
+ <div className="absolute inset-0 bg-[var(--bg-overlay)]" onClick={onCancel} />
42
+ <div className="relative bg-[var(--bg-secondary)] rounded-xl border border-[var(--border-subtle)] shadow-2xl p-4 w-[90vw] max-w-md">
43
+ <h3 className="text-sm font-medium text-[var(--text-primary)] mb-1">
44
+ Run Flow: {flowName}
45
+ </h3>
46
+ {description && (
47
+ <p className="text-[11px] text-[var(--text-tertiary)] mb-3">{description}</p>
48
+ )}
49
+ {/* Phase-2 gate decorator slot. See change: add-extension-ui-decorations. */}
50
+ <GateSlot session={session} flowId={flowName} />
51
+ <form onSubmit={handleSubmit}>
52
+ <input
53
+ ref={inputRef}
54
+ type="text"
55
+ value={task}
56
+ onChange={(e) => setTask(e.target.value)}
57
+ placeholder="Describe the task (optional)..."
58
+ className="w-full px-3 py-2 text-sm bg-[var(--bg-tertiary)] border border-[var(--border-subtle)] rounded-lg text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:outline-none focus:border-blue-500/50"
59
+ />
60
+ <div className="flex justify-end gap-2 mt-3">
61
+ <button
62
+ type="button"
63
+ onClick={onCancel}
64
+ className="text-xs px-3 py-1.5 rounded-lg border border-[var(--border-subtle)] text-[var(--text-tertiary)] hover:text-[var(--text-primary)]"
65
+ >
66
+ Cancel
67
+ </button>
68
+ <button
69
+ type="submit"
70
+ disabled={!gateState.available}
71
+ title={gateState.available ? undefined : gateState.reason}
72
+ className={`text-xs px-3 py-1.5 rounded-lg ${
73
+ gateState.available
74
+ ? "bg-blue-600 text-white hover:bg-blue-500"
75
+ : "bg-[var(--bg-tertiary)] text-[var(--text-muted)] cursor-not-allowed"
76
+ }`}
77
+ data-testid="flow-launch-run"
78
+ >
79
+ <Icon path={mdiPlay} size={0.45} className="inline mr-0.5" />Run
80
+ </button>
81
+ </div>
82
+ </form>
83
+ </div>
84
+ </div>
85
+ </DialogPortal>
86
+ );
87
+ }