@blackbelt-technology/pi-dashboard-flows-plugin 0.5.4 → 0.6.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 (66) hide show
  1. package/package.json +25 -16
  2. package/src/AGENTS.md +8 -0
  3. package/src/__tests__/FlowGraph.test.ts +151 -5
  4. package/src/__tests__/FlowInputWiring.test.tsx +97 -0
  5. package/src/__tests__/FlowSummary.test.tsx +331 -0
  6. package/src/__tests__/FlowYamlPreview.test.tsx +75 -0
  7. package/src/__tests__/FlowsSessionStateContext.test.tsx +2 -39
  8. package/src/__tests__/authoring-renderers.test.tsx +190 -0
  9. package/src/__tests__/automation-actions.test.ts +117 -0
  10. package/src/__tests__/flow-agent-card-code-source.test.tsx +154 -0
  11. package/src/__tests__/flow-agent-cost.test.tsx +160 -0
  12. package/src/__tests__/flow-agent-error.test.ts +60 -0
  13. package/src/__tests__/flow-collapse-storage.test.ts +90 -0
  14. package/src/__tests__/flow-edges.test.ts +195 -0
  15. package/src/__tests__/flow-inputs.test.ts +69 -0
  16. package/src/__tests__/flow-reducer-bridge-contract.test.ts +108 -0
  17. package/src/__tests__/flow-reducer-seed-on-start.test.ts +61 -0
  18. package/src/__tests__/flow-yaml-parse.test.ts +124 -0
  19. package/src/__tests__/flows-for-cwd.test.ts +51 -0
  20. package/src/__tests__/flowsAvailability.test.ts +51 -64
  21. package/src/__tests__/node-kind-reducer.test.ts +135 -0
  22. package/src/__tests__/plugin-action-handler.test.ts +54 -0
  23. package/src/__tests__/session-flow-actions-edit.test.tsx +98 -0
  24. package/src/bridge/AGENTS.md +8 -0
  25. package/src/client/AGENTS.md +32 -0
  26. package/src/client/FlowActivityBadge.tsx +8 -5
  27. package/src/client/FlowAgentCard.tsx +231 -110
  28. package/src/client/FlowAgentDetail.tsx +20 -12
  29. package/src/client/FlowAgentsToolRenderer.tsx +228 -0
  30. package/src/client/FlowAuthorPromptDialog.tsx +92 -0
  31. package/src/client/FlowDashboard.tsx +88 -23
  32. package/src/client/FlowGraph.tsx +420 -275
  33. package/src/client/FlowInputWiring.tsx +243 -0
  34. package/src/client/FlowLaunchDialog.tsx +48 -54
  35. package/src/client/FlowQuestionCard.tsx +6 -3
  36. package/src/client/FlowSummary.tsx +252 -69
  37. package/src/client/FlowWriteToolRenderer.tsx +127 -0
  38. package/src/client/FlowYamlPopoverButton.tsx +26 -25
  39. package/src/client/FlowYamlPreview.tsx +9 -7
  40. package/src/client/FlowsSessionStateContext.tsx +14 -33
  41. package/src/client/FlowsSettings.tsx +68 -0
  42. package/src/client/SessionFlowActions.tsx +92 -76
  43. package/src/client/flow-collapse-storage.ts +79 -0
  44. package/src/client/flow-edges.ts +173 -0
  45. package/src/client/flow-yaml-parse.ts +140 -0
  46. package/src/client/flowsAvailability.ts +28 -87
  47. package/src/client/index.tsx +27 -32
  48. package/src/client/shouldRender.ts +24 -12
  49. package/src/configSchema.json +14 -0
  50. package/src/flow-reducer.ts +94 -13
  51. package/src/i18n.ts +90 -0
  52. package/src/reducer.ts +5 -5
  53. package/src/server/AGENTS.md +10 -0
  54. package/src/server/automation-actions.ts +162 -0
  55. package/src/server/flow-inputs.ts +58 -0
  56. package/src/server/index.ts +93 -9
  57. package/src/server/state-store.ts +3 -14
  58. package/src/__tests__/ArchitectInputPrompt.test.tsx +0 -81
  59. package/src/__tests__/architect-reducer.test.ts +0 -307
  60. package/src/architect-reducer.ts +0 -386
  61. package/src/client/FlowAgentPopoutClaim.tsx +0 -66
  62. package/src/client/FlowAgentPopoutPage.tsx +0 -177
  63. package/src/client/FlowArchitect.tsx +0 -699
  64. package/src/client/FlowArchitectPopoutClaim.tsx +0 -52
  65. package/src/client/FlowArchitectPopoutPage.tsx +0 -133
  66. package/src/client/popout-url.ts +0 -59
@@ -1,31 +1,44 @@
1
- import React, { useMemo, useRef, useState, useEffect } from "react";
1
+ import { useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
2
2
  // useZoomPan is a HOOK — it cannot go through the registry (Rules of Hooks).
3
3
  // Stays as a direct import. See add-plugin-ui-primitive-registry Decision 4.
4
4
  import { useZoomPan } from "@blackbelt-technology/pi-dashboard-client-utils/useZoomPan";
5
5
  import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
6
- import { useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
6
+ import type { FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
7
+ import { mdiCallSplit, mdiCodeTags, mdiRobotOutline, mdiSourceBranch } from "@mdi/js";
7
8
  import { graphlib } from "dagre-d3-es";
8
9
  import { layout as dagreLayout } from "dagre-d3-es/src/dagre/index.js";
9
- import type { FlowState, ArchitectDagStep } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
+ import { useEffect, useMemo, useRef, useState } from "react";
11
+ import { FLOW_SHOW_ERROR_ROUTES_KEY, usePersistedToggle } from "./flow-collapse-storage.js";
12
+ import { deriveFlowEdges, type FlowEdge, type FlowEdgeKind, type FlowEdgeStep } from "./flow-edges.js";
13
+
14
+ /** Per-kind visual identity for graph nodes, mirroring the FlowAgentCard badges:
15
+ * code/code-decision = cyan, fork/agent-decision = amber, agent = green/status.
16
+ * `accent` drives the left stripe + icon tint; `icon` is an mdi 24-unit path.
17
+ * See change: improve-flow-ui. */
18
+ const KIND_VISUAL: Record<string, { icon: string; accent?: string }> = {
19
+ code: { icon: mdiCodeTags, accent: "#22d3ee" }, // cyan-400
20
+ "code-decision": { icon: mdiCallSplit, accent: "#22d3ee" },
21
+ fork: { icon: mdiSourceBranch, accent: "#fbbf24" }, // amber-400 (also agent-decision)
22
+ agent: { icon: mdiRobotOutline }, // no accent — tinted by status
23
+ };
10
24
 
11
25
  // ── Types ───────────────────────────────────────────────────────────
12
26
 
13
- /** Step type determines visual rendering:
14
- * - "agent" (default): solid rounded rect
15
- * - "fork": diamond-shaped (rotated rect) for decision points
16
- * - "loop": rounded rect with loop icon/double border
17
- * - "flow-ref": dashed border for subflows
18
- */
19
- export type FlowStepType = "agent" | "fork" | "loop" | "conditional" | "flow-ref";
27
+ /** Step type drives the node's mdi icon + kind accent (see KIND_VISUAL):
28
+ * agent = robot/green, code+code-decision = cyan, fork+agent-decision = amber.
29
+ * Border/fill stay status-driven. */
30
+ export type FlowStepType = "agent" | "fork" | "code" | "code-decision";
20
31
 
21
- /** Map flow engine stepType string to graph visual type */
32
+ /** Map flow engine stepType/nodeKind string to graph visual type.
33
+ * Canonical node set: agent, agent-decision, code, code-decision, fork. Dead
34
+ * types removed (conditional, agent-loop-decision, and the former subflow node).
35
+ * See change: improve-flow-ui. */
22
36
  export function mapStepType(stepType: string | undefined): FlowStepType | undefined {
23
37
  switch (stepType) {
24
38
  case "fork":
25
- case "conditional":
26
39
  case "agent-decision": return "fork";
27
- case "agent-loop-decision": return "loop";
28
- case "flow-ref": return "flow-ref";
40
+ case "code": return "code";
41
+ case "code-decision": return "code-decision";
29
42
  default: return undefined; // "agent" → default styling
30
43
  }
31
44
  }
@@ -36,56 +49,21 @@ export interface FlowGraphStep {
36
49
  status: "pending" | "running" | "complete" | "error" | "blocked";
37
50
  blockedBy: string[];
38
51
  type?: FlowStepType;
39
- /** For loop steps: the step ID to loop back to (rendered as a backward arrow) */
40
- loopTarget?: string;
41
- }
42
-
43
- /** Step types that act as segment separators (non-agent control flow) */
44
- const SEPARATOR_STEP_TYPES = new Set(["fork", "conditional", "agent-decision", "agent-loop-decision", "flow-ref"]);
45
-
46
- /** Synthesize implicit sequential edges that aren't expressed in blockedBy.
47
- * - Steps after a separator with no blockedBy get an edge from the preceding separator.
48
- * - Loop exit_target steps get an edge from the loop step. */
49
- export function synthesizeImplicitEdges(
50
- steps: FlowGraphStep[],
51
- dagSteps: Array<{ id: string; stepType?: string; exitTarget?: string }>,
52
- ): void {
53
- const allStepIds = new Set(steps.map(s => s.id));
54
- const stepById = new Map(steps.map(s => [s.id, s]));
55
-
56
- // 1. Exit target edges: loop-decision → exit_target
57
- for (const ds of dagSteps) {
58
- if (ds.exitTarget && allStepIds.has(ds.exitTarget)) {
59
- const target = stepById.get(ds.exitTarget);
60
- if (target && !target.blockedBy.includes(ds.id)) {
61
- target.blockedBy = [...target.blockedBy, ds.id];
62
- }
63
- }
64
- }
65
-
66
- // 2. Implicit segment edges: steps with no blockedBy after a separator
67
- for (let i = 1; i < dagSteps.length; i++) {
68
- const curr = stepById.get(dagSteps[i].id);
69
- if (!curr || curr.blockedBy.length > 0) continue;
70
-
71
- for (let j = i - 1; j >= 0; j--) {
72
- const prev = dagSteps[j];
73
- if (prev.stepType && SEPARATOR_STEP_TYPES.has(prev.stepType) && allStepIds.has(prev.id)) {
74
- curr.blockedBy = [prev.id];
75
- break;
76
- }
77
- if ((!prev.stepType || prev.stepType === "agent") && allStepIds.has(prev.id)) {
78
- curr.blockedBy = [prev.id];
79
- break;
80
- }
81
- }
82
- }
52
+ /** Decision branch label → target step id (fork / agent-decision / code-decision). */
53
+ branches?: Record<string, string>;
54
+ /** Success route target (`on_complete`). Present on the static preview path and,
55
+ * once pi-flows emits it on `flow:flow-started`, the live path (see §8). */
56
+ onComplete?: string;
57
+ /** Error route target (`on_error`). Drives returning-loop vs terminal-sink rendering. */
58
+ onError?: string;
83
59
  }
84
60
 
85
61
  // ── Data converters ────────────────────────────────────────────────
86
62
 
87
63
  /** Convert FlowState (running/completed flow) to FlowGraphStep array.
88
- * Uses dagSteps when available, falls back to agents map for backward compat. */
64
+ * Uses dagSteps when available, falls back to agents map for backward compat.
65
+ * Implicit-segment + branch edges are derived later by `deriveFlowEdges` in
66
+ * computeLayout; here we only carry `blockedBy` + `branches`. */
89
67
  export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
90
68
  if (flowState.dagSteps && flowState.dagSteps.length > 0) {
91
69
  const stepStatus = new Map<string, FlowGraphStep["status"]>();
@@ -96,30 +74,19 @@ export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
96
74
  }
97
75
 
98
76
  const allStepIds = new Set(flowState.dagSteps.map(s => s.id));
99
- const steps: FlowGraphStep[] = flowState.dagSteps.map(step => ({
77
+ return flowState.dagSteps.map(step => ({
100
78
  id: step.id,
101
79
  label: step.id,
102
80
  status: stepStatus.get(step.id) || stepStatus.get(step.agent || "") || "pending",
103
81
  blockedBy: step.blockedBy.filter(dep => allStepIds.has(dep)),
104
82
  type: mapStepType(step.stepType),
105
- loopTarget: step.loopTarget && allStepIds.has(step.loopTarget) ? step.loopTarget : undefined,
83
+ branches: step.branches,
84
+ // Forward/error routing (present once pi-flows emits it on flow:flow-started)
85
+ // so on_complete-wired flows draw `route` edges live. See change:
86
+ // fix-flow-ui-graph-zoom-summary.
87
+ onComplete: step.onComplete,
88
+ onError: step.onError,
106
89
  }));
107
-
108
- // Add flow-ref steps not in dagSteps
109
- for (const ref of flowState.flowRefSteps || []) {
110
- if (!allStepIds.has(ref.id)) {
111
- steps.push({
112
- id: ref.id,
113
- label: ref.label,
114
- status: "pending",
115
- blockedBy: ref.blockedBy.filter(dep => allStepIds.has(dep)),
116
- type: "flow-ref",
117
- });
118
- }
119
- }
120
-
121
- synthesizeImplicitEdges(steps, flowState.dagSteps);
122
- return steps;
123
90
  }
124
91
 
125
92
  // Fallback: build from agents map (backward compat for old events without dagSteps)
@@ -127,38 +94,14 @@ export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
127
94
  for (const agent of flowState.agents.values()) {
128
95
  if (agent.stepId) stepToAgent.set(agent.stepId, agent.agentName);
129
96
  }
130
- const agentSteps: FlowGraphStep[] = Array.from(flowState.agents.values()).map(agent => ({
97
+ return Array.from(flowState.agents.values()).map(agent => ({
131
98
  id: agent.agentName,
132
99
  label: agent.label || agent.agentName,
133
100
  status: agent.status,
134
101
  blockedBy: agent.blockedBy
135
102
  .map(depId => stepToAgent.get(depId) || depId)
136
- .filter(name => flowState.agents.has(name) || flowState.flowRefSteps?.some(r => r.id === name)),
103
+ .filter(name => flowState.agents.has(name)),
137
104
  }));
138
- const flowRefSteps: FlowGraphStep[] = (flowState.flowRefSteps || []).map(ref => ({
139
- id: ref.id,
140
- label: ref.label,
141
- status: "pending" as const,
142
- blockedBy: ref.blockedBy.map(depId => stepToAgent.get(depId) || depId),
143
- type: "flow-ref" as const,
144
- }));
145
- return [...agentSteps, ...flowRefSteps];
146
- }
147
-
148
- /** Convert ArchitectState dagSteps (design-time, all pending) to FlowGraphStep array. */
149
- export function architectStepsToGraphSteps(dagSteps: ArchitectDagStep[]): FlowGraphStep[] {
150
- const allStepIds = new Set(dagSteps.map(s => s.id));
151
- const steps: FlowGraphStep[] = dagSteps.map((step) => ({
152
- id: step.id,
153
- label: step.agentName || step.id,
154
- status: "pending" as const,
155
- blockedBy: [...step.blockedBy],
156
- type: mapStepType(step.stepType),
157
- loopTarget: step.loopTarget && allStepIds.has(step.loopTarget) ? step.loopTarget : undefined,
158
- }));
159
-
160
- synthesizeImplicitEdges(steps, dagSteps);
161
- return steps;
162
105
  }
163
106
 
164
107
  interface PositionedNode {
@@ -178,20 +121,32 @@ interface PositionedEdge {
178
121
  points: Array<{ x: number; y: number }>;
179
122
  sourceStatus: FlowGraphStep["status"];
180
123
  targetStatus: FlowGraphStep["status"];
124
+ label?: string;
125
+ /** Edge class for styling (sequential/branch/route/implicit). */
126
+ kind?: FlowEdgeKind;
127
+ /** on_error route edge. */
128
+ isError?: boolean;
129
+ /** Returning on_error (rejoins the flow) vs terminal (routed to the sink). */
130
+ isReturning?: boolean;
131
+ /** Backward target (loop): declared at/before the source. */
132
+ isLoop?: boolean;
181
133
  }
182
134
 
183
- interface LoopBackEdge {
184
- source: string;
185
- target: string;
186
- sourceStatus: FlowGraphStep["status"];
187
- targetStatus: FlowGraphStep["status"];
188
- path: string;
135
+ /** Collapsed tail node pooling all terminal on_error handlers (`⚠ N exits`). */
136
+ interface ErrorSink {
137
+ x: number;
138
+ y: number;
139
+ width: number;
140
+ height: number;
141
+ /** Handler step ids pooled into this sink (expandable). */
142
+ handlers: string[];
189
143
  }
190
144
 
191
145
  interface LayoutResult {
192
146
  nodes: PositionedNode[];
193
147
  edges: PositionedEdge[];
194
- loopEdges: LoopBackEdge[];
148
+ /** Collapsed terminal-handler sink (only when error routes are shown). */
149
+ errorSink?: ErrorSink;
195
150
  width: number;
196
151
  height: number;
197
152
  }
@@ -228,33 +183,105 @@ const NODE_WIDTH = 120;
228
183
  const NODE_HEIGHT = 32;
229
184
  const FONT_SIZE = 11;
230
185
  const ARROW_SIZE = 6;
186
+ /** Inline (bounded) graph height. The whole graph is scaled to fit this box
187
+ * via preserveAspectRatio; expand to a Dialog for pan/zoom. */
188
+ const FIT_HEIGHT = 240;
231
189
 
232
- export function computeLayout(steps: FlowGraphStep[]): LayoutResult {
190
+ export function computeLayout(
191
+ steps: FlowGraphStep[],
192
+ opts: { showErrorRoutes?: boolean } = {},
193
+ ): LayoutResult {
233
194
  if (steps.length === 0) {
234
- return { nodes: [], edges: [], loopEdges: [], width: 0, height: 0 };
195
+ return { nodes: [], edges: [], width: 0, height: 0 };
235
196
  }
236
197
 
237
- const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
238
- g.setGraph({ rankdir: "LR", nodesep: 15, ranksep: 40, marginx: 16, marginy: 16 });
198
+ const showErrorRoutes = opts.showErrorRoutes ?? true;
199
+
200
+ // Single edge derivation (shared with the static Mermaid snapshot). Route
201
+ // edges (on_complete/on_error) appear whenever the caller passes them: the
202
+ // static path parses YAML, the live path now receives them on
203
+ // flow:flow-started. See change: fix-flow-ui-graph-zoom-summary.
204
+ const flowEdges = deriveFlowEdges(
205
+ steps.map((s): FlowEdgeStep => ({
206
+ id: s.id,
207
+ type: s.type ?? "agent",
208
+ blockedBy: s.blockedBy,
209
+ branches: s.branches,
210
+ onComplete: s.onComplete,
211
+ onError: s.onError,
212
+ })),
213
+ );
239
214
 
240
- const statusMap = new Map<string, FlowGraphStep["status"]>();
241
- for (const step of steps) {
242
- g.setNode(step.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
243
- statusMap.set(step.id, step.status);
215
+ const isOnError = (e: FlowEdge) => e.kind === "route" && e.label === "on_error";
216
+ const onErrorEdges = flowEdges.filter(isOnError);
217
+ const terminalHandlerIds = new Set(
218
+ onErrorEdges.filter(e => e.routeTopology === "terminal").map(e => e.to),
219
+ );
220
+
221
+ // A node reached ONLY via on_error routes is an error-only handler (returning
222
+ // or terminal). Roots (no incoming edge at all) are NOT error-only.
223
+ const incoming = new Map<string, FlowEdge[]>();
224
+ for (const e of flowEdges) {
225
+ const list = incoming.get(e.to);
226
+ if (list) list.push(e); else incoming.set(e.to, [e]);
244
227
  }
228
+ const isErrorOnly = (id: string) => {
229
+ const inc = incoming.get(id) ?? [];
230
+ return inc.length > 0 && inc.every(isOnError);
231
+ };
245
232
 
246
- for (const step of steps) {
247
- for (const dep of step.blockedBy) {
248
- if (statusMap.has(dep)) {
249
- g.setEdge(dep, step.id);
250
- }
251
- }
233
+ // Terminal handlers collapse into ONE sink (excluded as real nodes). When the
234
+ // error layer is hidden, every error-only node leaves too — graph height then
235
+ // matches a flow with no on_error declared (zero footprint).
236
+ const excluded = new Set<string>(terminalHandlerIds);
237
+ if (!showErrorRoutes) {
238
+ for (const s of steps) if (isErrorOnly(s.id)) excluded.add(s.id);
239
+ }
240
+ const laidOutSteps = steps.filter(s => !excluded.has(s.id));
241
+ const laidOutIds = new Set(laidOutSteps.map(s => s.id));
242
+
243
+ const SINK_ID = "__errorSink__";
244
+ const SINK_W = 96;
245
+ const haveSink = showErrorRoutes && terminalHandlerIds.size > 0;
246
+
247
+ const statusMap = new Map<string, FlowGraphStep["status"]>();
248
+ for (const step of steps) statusMap.set(step.id, step.status);
249
+
250
+ // Feed EVERY edge to dagre with an acyclicer, so loops/back-edges are ranked
251
+ // AND routed by dagre itself. dagre threads edges through routing channels
252
+ // (dummy nodes) so a polyline goes AROUND nodes instead of through them — this
253
+ // is what eliminates the old hand-routed legs that sliced across node boxes.
254
+ // Terminal on_error edges are redirected to the collapsed sink node.
255
+ const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
256
+ // Flatter layout: tighter vertical node gap + small edgesep packs the graph
257
+ // (edges may overlap slightly — acceptable) so it reads more horizontal.
258
+ g.setGraph({ rankdir: "LR", nodesep: 12, edgesep: 8, ranksep: 46, marginx: 16, marginy: 16, acyclicer: "greedy" });
259
+
260
+ for (const step of laidOutSteps) g.setNode(step.id, { width: NODE_WIDTH, height: NODE_HEIGHT });
261
+ if (haveSink) g.setNode(SINK_ID, { width: SINK_W, height: NODE_HEIGHT });
262
+
263
+ interface EdgeSpec {
264
+ from: string; to: string; dTo: string; label?: string;
265
+ kind: FlowEdgeKind; isError: boolean; isReturning: boolean; isLoop: boolean;
266
+ }
267
+ const specs: EdgeSpec[] = [];
268
+ for (const e of flowEdges) {
269
+ const err = isOnError(e);
270
+ if (err && !showErrorRoutes) continue;
271
+ const terminal = err && e.routeTopology === "terminal";
272
+ const dTo = terminal ? SINK_ID : e.to;
273
+ if (!laidOutIds.has(e.from)) continue;
274
+ if (dTo !== SINK_ID && !laidOutIds.has(dTo)) continue;
275
+ g.setEdge(e.from, dTo, e.label ? { width: e.label.length * 6 + 6, height: 12 } : {});
276
+ specs.push({
277
+ from: e.from, to: e.to, dTo, label: e.label, kind: e.kind,
278
+ isError: err, isReturning: err && e.routeTopology === "returning", isLoop: !!e.backward,
279
+ });
252
280
  }
253
281
 
254
282
  dagreLayout(g, {});
255
283
 
256
- const graphMeta = g.graph();
257
- const nodes: PositionedNode[] = steps.map((step) => {
284
+ const nodes: PositionedNode[] = laidOutSteps.map((step) => {
258
285
  const n = g.node(step.id);
259
286
  return {
260
287
  id: step.id,
@@ -268,101 +295,39 @@ export function computeLayout(steps: FlowGraphStep[]): LayoutResult {
268
295
  };
269
296
  });
270
297
 
298
+ // Every edge rendered from dagre's routed waypoints (multi-segment, node-aware).
271
299
  const edges: PositionedEdge[] = [];
272
- for (const step of steps) {
273
- for (const dep of step.blockedBy) {
274
- if (statusMap.has(dep)) {
275
- const edgeData = g.edge(dep, step.id);
276
- if (edgeData) {
277
- edges.push({
278
- source: dep,
279
- target: step.id,
280
- points: edgeData.points,
281
- sourceStatus: statusMap.get(dep) || "pending",
282
- targetStatus: step.status,
283
- });
284
- }
285
- }
286
- }
287
- }
288
-
289
- // Compute loop-back edges (backward arrows that skip dagre to avoid cycles)
290
- const loopEdges: LoopBackEdge[] = [];
291
- const nodeById = new Map(nodes.map(n => [n.id, n]));
292
- const LOOP_MARGIN = 24; // vertical space above the graph for loop arcs
293
-
294
- // Find the topmost node edge to route arcs above everything
295
- let minY = Infinity;
296
- for (const n of nodes) {
297
- if (n.y < minY) minY = n.y;
300
+ for (const s of specs) {
301
+ const ed = g.edge(s.from, s.dTo);
302
+ if (!ed?.points) continue;
303
+ edges.push({
304
+ source: s.from,
305
+ target: s.to,
306
+ points: ed.points,
307
+ sourceStatus: statusMap.get(s.from) || "pending",
308
+ targetStatus: statusMap.get(s.to) || "pending",
309
+ label: s.label,
310
+ kind: s.kind,
311
+ isError: s.isError,
312
+ isReturning: s.isReturning,
313
+ isLoop: s.isLoop,
314
+ });
298
315
  }
299
316
 
300
- for (const step of steps) {
301
- if (step.loopTarget && nodeById.has(step.loopTarget)) {
302
- const src = nodeById.get(step.id)!;
303
- const tgt = nodeById.get(step.loopTarget)!;
304
- // Arc above the entire graph so it doesn't overlap any nodes
305
- const srcCx = src.x + src.width / 2;
306
- const srcTop = src.y;
307
- const tgtCx = tgt.x + tgt.width / 2;
308
- const tgtTop = tgt.y;
309
- const arcY = minY - LOOP_MARGIN;
310
- const path = `M${srcCx},${srcTop} C${srcCx},${arcY} ${tgtCx},${arcY} ${tgtCx},${tgtTop}`;
311
- loopEdges.push({
312
- source: step.id,
313
- target: step.loopTarget,
314
- sourceStatus: step.status,
315
- targetStatus: statusMap.get(step.loopTarget) || "pending",
316
- path,
317
- });
318
- }
319
- }
320
-
321
- // Compute bounding box including loop arcs
322
- const graphWidth = graphMeta.width || 200;
323
- const graphHeight = graphMeta.height || 50;
324
- const loopArcTop = loopEdges.length > 0 ? minY - LOOP_MARGIN - ARROW_SIZE : 0;
325
- const yOffset = loopArcTop < 0 ? -loopArcTop : 0;
326
-
327
- // Shift all geometry down to make room for arcs above
328
- if (yOffset > 0) {
329
- for (const n of nodes) n.y += yOffset;
330
- for (const e of edges) {
331
- for (const p of e.points) p.y += yOffset;
332
- }
333
- for (const le of loopEdges) {
334
- // Recompute path with shifted coordinates
335
- const src = nodeById.get(le.source)!;
336
- const tgt = nodeById.get(le.target)!;
337
- const srcCx = src.x + src.width / 2;
338
- const srcTop = src.y;
339
- const tgtCx = tgt.x + tgt.width / 2;
340
- const tgtTop = tgt.y;
341
- const arcY = ARROW_SIZE; // top of SVG with small padding
342
- le.path = `M${srcCx},${srcTop} C${srcCx},${arcY} ${tgtCx},${arcY} ${tgtCx},${tgtTop}`;
343
- }
317
+ let errorSink: ErrorSink | undefined;
318
+ if (haveSink) {
319
+ const sn = g.node(SINK_ID);
320
+ errorSink = {
321
+ x: sn.x - SINK_W / 2,
322
+ y: sn.y - NODE_HEIGHT / 2,
323
+ width: SINK_W,
324
+ height: NODE_HEIGHT,
325
+ handlers: Array.from(terminalHandlerIds),
326
+ };
344
327
  }
345
328
 
346
- // Compute actual bounding box from positioned nodes (dagre's reported
347
- // dimensions may not account for yOffset shift or full node extents)
348
- let maxRight = 0;
349
- let maxBottom = 0;
350
- for (const n of nodes) {
351
- const right = n.x + n.width;
352
- const bottom = n.y + n.height;
353
- if (right > maxRight) maxRight = right;
354
- if (bottom > maxBottom) maxBottom = bottom;
355
- }
356
- const actualWidth = Math.max(graphWidth, maxRight + 16);
357
- const actualHeight = Math.max(graphHeight + yOffset, maxBottom + 16);
358
-
359
- return {
360
- nodes,
361
- edges,
362
- loopEdges,
363
- width: actualWidth,
364
- height: actualHeight,
365
- };
329
+ const meta = g.graph();
330
+ return { nodes, edges, errorSink, width: meta.width || 200, height: meta.height || 50 };
366
331
  }
367
332
 
368
333
  // ── SVG edge path (cubic bezier through waypoints) ──────────────────
@@ -390,17 +355,39 @@ function buildEdgePath(points: Array<{ x: number; y: number }>): string {
390
355
 
391
356
  // ── Component ───────────────────────────────────────────────────────
392
357
 
393
- export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
358
+ export function FlowGraph({ steps, fit = false, onExpand, selectedStepId, onSelectStep }: {
359
+ steps: FlowGraphStep[];
360
+ /** Bounded, static, whole-graph-fits-the-window (no pan/zoom). Default false. */
361
+ fit?: boolean;
362
+ /** When set (and `fit`), shows a ⤢ expand button that opens the graph bigger. */
363
+ onExpand?: () => void;
364
+ /** Currently-selected step id — renders a ring on the matching node.
365
+ * See change: improve-flow-graph-dialog-and-card-interaction. */
366
+ selectedStepId?: string | null;
367
+ /** Node click handler (toggle selection). When set, nodes are clickable. */
368
+ onSelectStep?: (stepId: string) => void;
369
+ }) {
370
+ // Error-route layer toggle. Default ON: returning routes show as red loop
371
+ // arcs, terminal handlers collapse to one sink. OFF removes them from the
372
+ // dagre input entirely (zero footprint). Only relevant when on_error exists.
373
+ const hasErrorRoutes = useMemo(() => steps.some(s => s.onError), [steps]);
374
+ // Error routes are an exception layer — hidden by default to keep the happy
375
+ // path legible; the ⚠ toggle reveals them. Visibility persists globally (a
376
+ // viewing preference across all graphs). See change: fix-flow-ui-graph-zoom-summary.
377
+ const [showErrorRoutes, toggleShowErrorRoutes] = usePersistedToggle(FLOW_SHOW_ERROR_ROUTES_KEY, false);
378
+ const [sinkExpanded, setSinkExpanded] = useState(false);
379
+
394
380
  const layout = useMemo(() => {
395
381
  if (steps.length === 0) return null;
396
382
  try {
397
- return computeLayout(steps);
383
+ return computeLayout(steps, { showErrorRoutes });
398
384
  } catch (err) {
399
385
  console.error("[FlowGraph] computeLayout failed:", err, "steps:", steps);
400
386
  return null;
401
387
  }
402
- }, [steps]);
388
+ }, [steps, showErrorRoutes]);
403
389
 
390
+ const t = useT();
404
391
  const ZoomControls = useUiPrimitive(UI_PRIMITIVE_KEYS.zoomControls);
405
392
  const { state: zoom, handlers, zoomIn, zoomOut, reset } = useZoomPan();
406
393
  const [hovered, setHovered] = useState(false);
@@ -429,38 +416,74 @@ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
429
416
  const svgWidth = Math.max(layout.width, 150);
430
417
  const svgHeight = Math.max(layout.height, 50);
431
418
 
419
+ // Pan/zoom is enabled in BOTH the in-socket (fit) and dialog (non-fit) views.
420
+ // In fit mode the container clips (overflow:hidden) so panning never spills
421
+ // over sibling cards; the graph still defaults to whole-graph-fits via
422
+ // preserveAspectRatio, with zoom/pan layered on top.
423
+ const panHandlers = {
424
+ onPointerDown: handlers.onPointerDown,
425
+ onPointerMove: handlers.onPointerMove,
426
+ onPointerUp: handlers.onPointerUp,
427
+ onDoubleClick: handlers.onDoubleClick,
428
+ onTouchMove: handlers.onTouchMove,
429
+ onTouchEnd: handlers.onTouchEnd,
430
+ };
431
+
432
432
  return (
433
433
  <div
434
434
  ref={containerRef}
435
- className="flow-dag-graph-container relative"
436
- style={{ overflow: "visible" }}
437
- onPointerDown={handlers.onPointerDown}
438
- onPointerMove={handlers.onPointerMove}
439
- onPointerUp={handlers.onPointerUp}
440
- onDoubleClick={handlers.onDoubleClick}
441
- onTouchMove={handlers.onTouchMove}
442
- onTouchEnd={handlers.onTouchEnd}
435
+ className="flow-dag-graph-container relative flex items-center justify-center"
436
+ style={fit ? { height: FIT_HEIGHT, overflow: "hidden" } : { width: "100%", height: "100%", overflow: "visible" }}
443
437
  onMouseEnter={() => setHovered(true)}
444
438
  onMouseLeave={() => setHovered(false)}
439
+ {...panHandlers}
445
440
  >
441
+ {/* No onPointerDown stopPropagation needed: useZoomPan defers pointer
442
+ capture until movement exceeds the drag threshold, so a click on these
443
+ controls stays a click. ZoomControls still self-guards its own drag. */}
444
+ {fit && onExpand && (
445
+ <button
446
+ type="button"
447
+ onClick={onExpand}
448
+ title={t("expandGraph", undefined, "Expand graph")}
449
+ className="absolute bottom-1 right-1 z-10 text-[11px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] bg-[var(--bg-secondary)]/80 text-[var(--text-tertiary)] hover:text-[var(--text-primary)]"
450
+ >
451
+ ⤢ Expand
452
+ </button>
453
+ )}
454
+ {hasErrorRoutes && (
455
+ <button
456
+ type="button"
457
+ onClick={toggleShowErrorRoutes}
458
+ title={showErrorRoutes ? "Hide error routes" : "Show error routes"}
459
+ aria-pressed={showErrorRoutes}
460
+ className={`absolute top-1 left-1 z-10 text-[11px] px-1.5 py-0.5 rounded border ${showErrorRoutes ? "border-[#ef4444]/60 text-[#ef4444]" : "border-[var(--border-subtle)] text-[var(--text-tertiary)]"} bg-[var(--bg-secondary)]/80 hover:text-[var(--text-primary)]`}
461
+ >
462
+ ⚠ error routes
463
+ </button>
464
+ )}
446
465
  {hovered && (
447
- <ZoomControls
448
- onZoomIn={zoomIn}
449
- onZoomOut={zoomOut}
450
- onReset={reset}
451
- scale={zoom.scale}
452
- />
466
+ <div>
467
+ <ZoomControls
468
+ onZoomIn={zoomIn}
469
+ onZoomOut={zoomOut}
470
+ onReset={reset}
471
+ scale={zoom.scale}
472
+ />
473
+ </div>
453
474
  )}
454
475
  <div
455
476
  style={{
477
+ ...(fit ? { width: "100%", height: "100%" } : {}),
456
478
  transform: `translate(${zoom.translateX}px, ${zoom.translateY}px) scale(${zoom.scale})`,
457
479
  transformOrigin: "0 0",
458
480
  }}
459
481
  >
460
482
  <svg
461
- width={svgWidth}
462
- height={svgHeight}
483
+ width={fit ? "100%" : svgWidth}
484
+ height={fit ? "100%" : svgHeight}
463
485
  viewBox={`0 0 ${svgWidth} ${svgHeight}`}
486
+ preserveAspectRatio={fit ? "xMidYMid meet" : undefined}
464
487
  className="flow-dag-graph"
465
488
  style={{ display: "block", overflow: "visible" }}
466
489
  >
@@ -481,60 +504,164 @@ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
481
504
  ))}
482
505
  </defs>
483
506
 
484
- {/* Edges */}
507
+ {/* Edges — every edge routed by dagre (waypoints thread around nodes,
508
+ never through them). Styled by class: red on_error (↺ returning /
509
+ ⊗ terminal), purple loop, status-grey otherwise. */}
485
510
  {layout.edges.map((edge, i) => {
486
- const { stroke, animated, dashed } = getEdgeColor(edge.sourceStatus, edge.targetStatus);
511
+ let stroke: string;
512
+ let dash: string;
513
+ let animated = false;
514
+ if (edge.isError) {
515
+ stroke = "#ef4444";
516
+ dash = "5 4";
517
+ } else if (edge.isLoop) {
518
+ stroke = "#a855f7";
519
+ dash = "5 3";
520
+ } else {
521
+ const c = getEdgeColor(edge.sourceStatus, edge.targetStatus);
522
+ stroke = c.stroke;
523
+ dash = c.dashed ? "4 3" : c.animated ? "6 3" : "none";
524
+ animated = c.animated;
525
+ }
526
+ const mid = edge.points[Math.floor(edge.points.length / 2)];
527
+ // `on_complete` is the happy-path default — render unlabeled to avoid
528
+ // labelling every arrow on an on_complete-wired flow. Keep branch +
529
+ // on_error labels. See change: fix-flow-ui-graph-zoom-summary.
530
+ const label = edge.isError
531
+ ? `on_error ${edge.isReturning ? "↺" : "⊗"}`
532
+ : edge.label === "on_complete" ? undefined : edge.label;
533
+ const labelColor = edge.isError ? "#ef4444" : edge.isLoop ? "#a855f7" : "#888";
487
534
  return (
488
- <path
489
- key={`edge-${i}`}
490
- d={buildEdgePath(edge.points)}
491
- fill="none"
492
- stroke={stroke}
493
- strokeWidth={1.5}
494
- strokeDasharray={dashed ? "4 3" : animated ? "6 3" : "none"}
495
- markerEnd={`url(#arrow-${stroke.replace("#", "")})`}
496
- className={animated ? "flow-edge-animated" : ""}
497
- />
535
+ <g key={`edge-${i}`}>
536
+ <path
537
+ d={buildEdgePath(edge.points)}
538
+ fill="none"
539
+ stroke={stroke}
540
+ strokeWidth={1.5}
541
+ strokeDasharray={dash}
542
+ markerEnd={`url(#arrow-${stroke.replace("#", "")})`}
543
+ className={animated ? "flow-edge-animated" : ""}
544
+ opacity={edge.isError || edge.isLoop ? 0.8 : 1}
545
+ />
546
+ {label && mid && (
547
+ <text
548
+ x={mid.x}
549
+ y={mid.y - 3}
550
+ fontSize={8}
551
+ fill={labelColor}
552
+ textAnchor="middle"
553
+ fontFamily="system-ui, -apple-system, sans-serif"
554
+ >
555
+ {label}
556
+ </text>
557
+ )}
558
+ </g>
498
559
  );
499
560
  })}
500
561
 
501
- {/* Loop-back edges (backward arrows below the graph) */}
502
- {layout.loopEdges.map((edge, i) => (
503
- <path
504
- key={`loop-${i}`}
505
- d={edge.path}
506
- fill="none"
507
- stroke="#a855f7"
508
- strokeWidth={1.5}
509
- strokeDasharray="5 3"
510
- markerEnd="url(#arrow-a855f7)"
511
- opacity={0.7}
512
- />
513
- ))}
562
+ {/* Collapsed terminal-handler sink (`⚠ N exits`), click to expand. */}
563
+ {layout.errorSink && (
564
+ <g
565
+ data-error-sink=""
566
+ style={{ cursor: "pointer" }}
567
+ onClick={() => setSinkExpanded(v => !v)}
568
+ >
569
+ <rect
570
+ x={layout.errorSink.x}
571
+ y={layout.errorSink.y}
572
+ width={layout.errorSink.width}
573
+ height={layout.errorSink.height}
574
+ rx={5}
575
+ ry={5}
576
+ fill="#2a1416"
577
+ stroke="#ef4444"
578
+ strokeWidth={1.5}
579
+ />
580
+ <text
581
+ x={layout.errorSink.x + layout.errorSink.width / 2}
582
+ y={layout.errorSink.y + layout.errorSink.height / 2 + 1}
583
+ fontSize={10}
584
+ fill="#ef4444"
585
+ dominantBaseline="middle"
586
+ textAnchor="middle"
587
+ fontFamily="system-ui, -apple-system, sans-serif"
588
+ >
589
+ {`⚠ ${layout.errorSink.handlers.length} exit${layout.errorSink.handlers.length === 1 ? "" : "s"}`}
590
+ </text>
591
+ {/* Expanded handler list stacks below the sink. */}
592
+ {sinkExpanded && layout.errorSink.handlers.map((h, hi) => (
593
+ <g key={`sink-h-${h}`}>
594
+ <rect
595
+ x={layout.errorSink!.x}
596
+ y={layout.errorSink!.y + layout.errorSink!.height + 6 + hi * (NODE_HEIGHT + 6)}
597
+ width={layout.errorSink!.width}
598
+ height={NODE_HEIGHT}
599
+ rx={5}
600
+ ry={5}
601
+ fill="#2a1416"
602
+ stroke="#ef4444"
603
+ strokeWidth={1}
604
+ opacity={0.85}
605
+ />
606
+ <text
607
+ x={layout.errorSink!.x + layout.errorSink!.width / 2}
608
+ y={layout.errorSink!.y + layout.errorSink!.height + 6 + hi * (NODE_HEIGHT + 6) + NODE_HEIGHT / 2 + 1}
609
+ fontSize={10}
610
+ fill="#ef4444"
611
+ dominantBaseline="middle"
612
+ textAnchor="middle"
613
+ fontFamily="system-ui, -apple-system, sans-serif"
614
+ >
615
+ {h}
616
+ </text>
617
+ </g>
618
+ ))}
619
+ </g>
620
+ )}
514
621
 
515
622
  {/* Nodes */}
516
623
  {layout.nodes.map((node) => {
517
624
  const style = STATUS_COLORS[node.status] || STATUS_COLORS.pending;
518
625
  const isRunning = node.status === "running";
519
- // Add type prefix icon to label
520
- const typePrefix = node.type === "fork" ? "◇ "
521
- : node.type === "loop" ? "↻ "
522
- : node.type === "conditional" ? "? "
523
- : "";
524
- const displayLabel = typePrefix + node.label;
525
- const availW = node.width - 16;
526
- const naturalW = displayLabel.length * FONT_SIZE * 0.6;
626
+ // Per-kind visual: mdi icon + accent matching the cards (code=cyan,
627
+ // fork=amber, agent=green/status). Border/fill stay status-driven.
628
+ const visual = KIND_VISUAL[node.type ?? "agent"] ?? KIND_VISUAL.agent;
629
+ const accent = visual.accent;
630
+ const ICON_SIZE = 13;
631
+ const iconX = node.x + 7;
632
+ const iconY = node.y + (node.height - ICON_SIZE) / 2;
633
+ const iconScale = ICON_SIZE / 24;
634
+ const labelX = node.x + 7 + ICON_SIZE + 4;
635
+ const availW = node.x + node.width - labelX - 8;
636
+ const naturalW = node.label.length * FONT_SIZE * 0.6;
527
637
  const labelFontSize = naturalW > availW
528
638
  ? Math.max(7, FONT_SIZE * (availW / naturalW))
529
639
  : FONT_SIZE;
530
640
 
641
+ const isSelected = node.id === selectedStepId;
531
642
  return (
532
643
  <g
533
644
  key={node.id}
534
645
  data-node={node.id}
535
- style={{ cursor: "default" }}
536
- className={isRunning ? "flow-node-running" : ""}
646
+ style={{ cursor: onSelectStep ? "pointer" : "default" }}
647
+ className={`${isRunning ? "flow-node-running" : ""}${isSelected ? " flow-node-selected" : ""}`.trim()}
648
+ onClick={onSelectStep ? () => onSelectStep(node.id) : undefined}
537
649
  >
650
+ {/* Selection ring (accent glow). See change:
651
+ improve-flow-graph-dialog-and-card-interaction. */}
652
+ {isSelected && (
653
+ <rect
654
+ x={node.x - 3}
655
+ y={node.y - 3}
656
+ width={node.width + 6}
657
+ height={node.height + 6}
658
+ rx={7}
659
+ ry={7}
660
+ fill="none"
661
+ stroke="#60a5fa"
662
+ strokeWidth={2}
663
+ />
664
+ )}
538
665
  <rect
539
666
  x={node.x}
540
667
  y={node.y}
@@ -543,19 +670,37 @@ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
543
670
  rx={5}
544
671
  ry={5}
545
672
  fill={style.fill}
546
- stroke={style.border}
547
- strokeWidth={1.5}
673
+ stroke={isSelected ? "#60a5fa" : style.border}
674
+ strokeWidth={isSelected ? 2.5 : 1.5}
675
+ />
676
+ {/* Kind accent stripe (code=cyan, fork=amber); agent has none. */}
677
+ {accent && (
678
+ <rect
679
+ x={node.x}
680
+ y={node.y}
681
+ width={4}
682
+ height={node.height}
683
+ rx={2}
684
+ ry={2}
685
+ fill={accent}
686
+ />
687
+ )}
688
+ {/* mdi kind icon (24-unit path scaled), tinted by accent or status. */}
689
+ <path
690
+ d={visual.icon}
691
+ transform={`translate(${iconX}, ${iconY}) scale(${iconScale})`}
692
+ fill={accent ?? style.text}
548
693
  />
549
694
  <text
550
- x={node.x + node.width / 2}
695
+ x={labelX}
551
696
  y={node.y + node.height / 2 + 1}
552
697
  fontSize={labelFontSize}
553
698
  fill={style.text}
554
699
  dominantBaseline="middle"
555
- textAnchor="middle"
700
+ textAnchor="start"
556
701
  fontFamily="system-ui, -apple-system, sans-serif"
557
702
  >
558
- {displayLabel}
703
+ {node.label}
559
704
  </text>
560
705
  </g>
561
706
  );