@blackbelt-technology/pi-dashboard-flows-plugin 0.5.3 → 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 (70) hide show
  1. package/package.json +48 -4
  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 +223 -0
  8. package/src/__tests__/FlowsUiStateContext.test.tsx +140 -0
  9. package/src/__tests__/authoring-renderers.test.tsx +190 -0
  10. package/src/__tests__/automation-actions.test.ts +117 -0
  11. package/src/__tests__/flow-agent-card-code-source.test.tsx +154 -0
  12. package/src/__tests__/flow-agent-cost.test.tsx +160 -0
  13. package/src/__tests__/flow-agent-error.test.ts +60 -0
  14. package/src/__tests__/flow-collapse-storage.test.ts +90 -0
  15. package/src/__tests__/flow-edges.test.ts +195 -0
  16. package/src/__tests__/flow-inputs.test.ts +69 -0
  17. package/src/__tests__/flow-reducer-bridge-contract.test.ts +108 -0
  18. package/src/__tests__/flow-reducer-seed-on-start.test.ts +61 -0
  19. package/src/__tests__/flow-yaml-parse.test.ts +124 -0
  20. package/src/__tests__/flows-for-cwd.test.ts +51 -0
  21. package/src/__tests__/flowsAvailability.test.ts +79 -0
  22. package/src/__tests__/manifest-discoverability.test.ts +97 -0
  23. package/src/__tests__/node-kind-reducer.test.ts +135 -0
  24. package/src/__tests__/plugin-action-handler.test.ts +54 -0
  25. package/src/__tests__/render-actions.test.ts +63 -0
  26. package/src/__tests__/session-flow-actions-edit.test.tsx +98 -0
  27. package/src/bridge/AGENTS.md +8 -0
  28. package/src/bridge/flow-question-adapter.ts +93 -0
  29. package/src/bridge/index.ts +30 -0
  30. package/src/client/AGENTS.md +32 -0
  31. package/src/client/FlowActivityBadge.tsx +41 -11
  32. package/src/client/FlowAgentCard.tsx +321 -61
  33. package/src/client/FlowAgentDetail.tsx +103 -154
  34. package/src/client/FlowAgentsToolRenderer.tsx +228 -0
  35. package/src/client/FlowAuthorPromptDialog.tsx +92 -0
  36. package/src/client/FlowDashboard.tsx +271 -43
  37. package/src/client/FlowGraph.tsx +425 -276
  38. package/src/client/FlowInputWiring.tsx +243 -0
  39. package/src/client/FlowLaunchDialog.tsx +52 -52
  40. package/src/client/FlowQuestionCard.tsx +216 -0
  41. package/src/client/FlowQuestionTranscriptPill.tsx +58 -0
  42. package/src/client/FlowSummary.tsx +285 -80
  43. package/src/client/FlowWriteToolRenderer.tsx +127 -0
  44. package/src/client/FlowYamlPopoverButton.tsx +110 -0
  45. package/src/client/FlowYamlPreview.tsx +67 -0
  46. package/src/client/FlowsCommandRoutes.tsx +237 -0
  47. package/src/client/FlowsSessionStateContext.tsx +142 -0
  48. package/src/client/FlowsSettings.tsx +68 -0
  49. package/src/client/FlowsUiStateContext.tsx +169 -0
  50. package/src/client/SessionFlowActions.tsx +172 -65
  51. package/src/client/flow-collapse-storage.ts +79 -0
  52. package/src/client/flow-edges.ts +173 -0
  53. package/src/client/flow-yaml-parse.ts +140 -0
  54. package/src/client/flowsAvailability.ts +44 -0
  55. package/src/client/index.tsx +95 -13
  56. package/src/client/shouldRender.ts +38 -0
  57. package/src/configSchema.json +14 -0
  58. package/src/flow-reducer.ts +94 -13
  59. package/src/i18n.ts +90 -0
  60. package/src/reducer.ts +5 -5
  61. package/src/server/AGENTS.md +10 -0
  62. package/src/server/automation-actions.ts +162 -0
  63. package/src/server/flow-inputs.ts +58 -0
  64. package/src/server/index.ts +171 -0
  65. package/src/server/render-actions.ts +88 -0
  66. package/src/server/state-store.ts +74 -0
  67. package/src/__tests__/ArchitectInputPrompt.test.tsx +0 -81
  68. package/src/__tests__/architect-reducer.test.ts +0 -307
  69. package/src/architect-reducer.ts +0 -386
  70. package/src/client/FlowArchitect.tsx +0 -622
@@ -1,28 +1,44 @@
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";
1
+ import { useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
2
+ // useZoomPan is a HOOK — it cannot go through the registry (Rules of Hooks).
3
+ // Stays as a direct import. See add-plugin-ui-primitive-registry Decision 4.
4
+ import { useZoomPan } from "@blackbelt-technology/pi-dashboard-client-utils/useZoomPan";
5
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
6
+ import type { FlowState } from "@blackbelt-technology/pi-dashboard-shared/types.js";
7
+ import { mdiCallSplit, mdiCodeTags, mdiRobotOutline, mdiSourceBranch } from "@mdi/js";
4
8
  import { graphlib } from "dagre-d3-es";
5
9
  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";
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
+ };
7
24
 
8
25
  // ── Types ───────────────────────────────────────────────────────────
9
26
 
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";
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";
17
31
 
18
- /** 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. */
19
36
  export function mapStepType(stepType: string | undefined): FlowStepType | undefined {
20
37
  switch (stepType) {
21
38
  case "fork":
22
- case "conditional":
23
39
  case "agent-decision": return "fork";
24
- case "agent-loop-decision": return "loop";
25
- case "flow-ref": return "flow-ref";
40
+ case "code": return "code";
41
+ case "code-decision": return "code-decision";
26
42
  default: return undefined; // "agent" → default styling
27
43
  }
28
44
  }
@@ -33,56 +49,21 @@ export interface FlowGraphStep {
33
49
  status: "pending" | "running" | "complete" | "error" | "blocked";
34
50
  blockedBy: string[];
35
51
  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
- }
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;
80
59
  }
81
60
 
82
61
  // ── Data converters ────────────────────────────────────────────────
83
62
 
84
63
  /** Convert FlowState (running/completed flow) to FlowGraphStep array.
85
- * 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`. */
86
67
  export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
87
68
  if (flowState.dagSteps && flowState.dagSteps.length > 0) {
88
69
  const stepStatus = new Map<string, FlowGraphStep["status"]>();
@@ -93,30 +74,19 @@ export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
93
74
  }
94
75
 
95
76
  const allStepIds = new Set(flowState.dagSteps.map(s => s.id));
96
- const steps: FlowGraphStep[] = flowState.dagSteps.map(step => ({
77
+ return flowState.dagSteps.map(step => ({
97
78
  id: step.id,
98
79
  label: step.id,
99
80
  status: stepStatus.get(step.id) || stepStatus.get(step.agent || "") || "pending",
100
81
  blockedBy: step.blockedBy.filter(dep => allStepIds.has(dep)),
101
82
  type: mapStepType(step.stepType),
102
- 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,
103
89
  }));
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
90
  }
121
91
 
122
92
  // Fallback: build from agents map (backward compat for old events without dagSteps)
@@ -124,38 +94,14 @@ export function flowStateToGraphSteps(flowState: FlowState): FlowGraphStep[] {
124
94
  for (const agent of flowState.agents.values()) {
125
95
  if (agent.stepId) stepToAgent.set(agent.stepId, agent.agentName);
126
96
  }
127
- const agentSteps: FlowGraphStep[] = Array.from(flowState.agents.values()).map(agent => ({
97
+ return Array.from(flowState.agents.values()).map(agent => ({
128
98
  id: agent.agentName,
129
99
  label: agent.label || agent.agentName,
130
100
  status: agent.status,
131
101
  blockedBy: agent.blockedBy
132
102
  .map(depId => stepToAgent.get(depId) || depId)
133
- .filter(name => flowState.agents.has(name) || flowState.flowRefSteps?.some(r => r.id === name)),
103
+ .filter(name => flowState.agents.has(name)),
134
104
  }));
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
105
  }
160
106
 
161
107
  interface PositionedNode {
@@ -175,20 +121,32 @@ interface PositionedEdge {
175
121
  points: Array<{ x: number; y: number }>;
176
122
  sourceStatus: FlowGraphStep["status"];
177
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;
178
133
  }
179
134
 
180
- interface LoopBackEdge {
181
- source: string;
182
- target: string;
183
- sourceStatus: FlowGraphStep["status"];
184
- targetStatus: FlowGraphStep["status"];
185
- 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[];
186
143
  }
187
144
 
188
145
  interface LayoutResult {
189
146
  nodes: PositionedNode[];
190
147
  edges: PositionedEdge[];
191
- loopEdges: LoopBackEdge[];
148
+ /** Collapsed terminal-handler sink (only when error routes are shown). */
149
+ errorSink?: ErrorSink;
192
150
  width: number;
193
151
  height: number;
194
152
  }
@@ -225,33 +183,105 @@ const NODE_WIDTH = 120;
225
183
  const NODE_HEIGHT = 32;
226
184
  const FONT_SIZE = 11;
227
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;
228
189
 
229
- export function computeLayout(steps: FlowGraphStep[]): LayoutResult {
190
+ export function computeLayout(
191
+ steps: FlowGraphStep[],
192
+ opts: { showErrorRoutes?: boolean } = {},
193
+ ): LayoutResult {
230
194
  if (steps.length === 0) {
231
- return { nodes: [], edges: [], loopEdges: [], width: 0, height: 0 };
195
+ return { nodes: [], edges: [], width: 0, height: 0 };
232
196
  }
233
197
 
234
- const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
235
- 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
+ );
236
214
 
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);
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]);
241
227
  }
228
+ const isErrorOnly = (id: string) => {
229
+ const inc = incoming.get(id) ?? [];
230
+ return inc.length > 0 && inc.every(isOnError);
231
+ };
242
232
 
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
- }
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
+ });
249
280
  }
250
281
 
251
282
  dagreLayout(g, {});
252
283
 
253
- const graphMeta = g.graph();
254
- const nodes: PositionedNode[] = steps.map((step) => {
284
+ const nodes: PositionedNode[] = laidOutSteps.map((step) => {
255
285
  const n = g.node(step.id);
256
286
  return {
257
287
  id: step.id,
@@ -265,101 +295,39 @@ export function computeLayout(steps: FlowGraphStep[]): LayoutResult {
265
295
  };
266
296
  });
267
297
 
298
+ // Every edge rendered from dagre's routed waypoints (multi-segment, node-aware).
268
299
  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;
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
+ });
295
315
  }
296
316
 
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
- }
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
+ };
341
327
  }
342
328
 
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
- };
329
+ const meta = g.graph();
330
+ return { nodes, edges, errorSink, width: meta.width || 200, height: meta.height || 50 };
363
331
  }
364
332
 
365
333
  // ── SVG edge path (cubic bezier through waypoints) ──────────────────
@@ -387,17 +355,40 @@ function buildEdgePath(points: Array<{ x: number; y: number }>): string {
387
355
 
388
356
  // ── Component ───────────────────────────────────────────────────────
389
357
 
390
- 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
+
391
380
  const layout = useMemo(() => {
392
381
  if (steps.length === 0) return null;
393
382
  try {
394
- return computeLayout(steps);
383
+ return computeLayout(steps, { showErrorRoutes });
395
384
  } catch (err) {
396
385
  console.error("[FlowGraph] computeLayout failed:", err, "steps:", steps);
397
386
  return null;
398
387
  }
399
- }, [steps]);
388
+ }, [steps, showErrorRoutes]);
400
389
 
390
+ const t = useT();
391
+ const ZoomControls = useUiPrimitive(UI_PRIMITIVE_KEYS.zoomControls);
401
392
  const { state: zoom, handlers, zoomIn, zoomOut, reset } = useZoomPan();
402
393
  const [hovered, setHovered] = useState(false);
403
394
  const containerRef = useRef<HTMLDivElement>(null);
@@ -425,38 +416,74 @@ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
425
416
  const svgWidth = Math.max(layout.width, 150);
426
417
  const svgHeight = Math.max(layout.height, 50);
427
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
+
428
432
  return (
429
433
  <div
430
434
  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}
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" }}
439
437
  onMouseEnter={() => setHovered(true)}
440
438
  onMouseLeave={() => setHovered(false)}
439
+ {...panHandlers}
441
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
+ )}
442
465
  {hovered && (
443
- <ZoomControls
444
- onZoomIn={zoomIn}
445
- onZoomOut={zoomOut}
446
- onReset={reset}
447
- scale={zoom.scale}
448
- />
466
+ <div>
467
+ <ZoomControls
468
+ onZoomIn={zoomIn}
469
+ onZoomOut={zoomOut}
470
+ onReset={reset}
471
+ scale={zoom.scale}
472
+ />
473
+ </div>
449
474
  )}
450
475
  <div
451
476
  style={{
477
+ ...(fit ? { width: "100%", height: "100%" } : {}),
452
478
  transform: `translate(${zoom.translateX}px, ${zoom.translateY}px) scale(${zoom.scale})`,
453
479
  transformOrigin: "0 0",
454
480
  }}
455
481
  >
456
482
  <svg
457
- width={svgWidth}
458
- height={svgHeight}
483
+ width={fit ? "100%" : svgWidth}
484
+ height={fit ? "100%" : svgHeight}
459
485
  viewBox={`0 0 ${svgWidth} ${svgHeight}`}
486
+ preserveAspectRatio={fit ? "xMidYMid meet" : undefined}
460
487
  className="flow-dag-graph"
461
488
  style={{ display: "block", overflow: "visible" }}
462
489
  >
@@ -477,60 +504,164 @@ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
477
504
  ))}
478
505
  </defs>
479
506
 
480
- {/* 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. */}
481
510
  {layout.edges.map((edge, i) => {
482
- 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";
483
534
  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
- />
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>
494
559
  );
495
560
  })}
496
561
 
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
- ))}
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
+ )}
510
621
 
511
622
  {/* Nodes */}
512
623
  {layout.nodes.map((node) => {
513
624
  const style = STATUS_COLORS[node.status] || STATUS_COLORS.pending;
514
625
  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;
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;
523
637
  const labelFontSize = naturalW > availW
524
638
  ? Math.max(7, FONT_SIZE * (availW / naturalW))
525
639
  : FONT_SIZE;
526
640
 
641
+ const isSelected = node.id === selectedStepId;
527
642
  return (
528
643
  <g
529
644
  key={node.id}
530
645
  data-node={node.id}
531
- style={{ cursor: "default" }}
532
- 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}
533
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
+ )}
534
665
  <rect
535
666
  x={node.x}
536
667
  y={node.y}
@@ -539,19 +670,37 @@ export function FlowGraph({ steps }: { steps: FlowGraphStep[] }) {
539
670
  rx={5}
540
671
  ry={5}
541
672
  fill={style.fill}
542
- stroke={style.border}
543
- 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}
544
693
  />
545
694
  <text
546
- x={node.x + node.width / 2}
695
+ x={labelX}
547
696
  y={node.y + node.height / 2 + 1}
548
697
  fontSize={labelFontSize}
549
698
  fill={style.text}
550
699
  dominantBaseline="middle"
551
- textAnchor="middle"
700
+ textAnchor="start"
552
701
  fontFamily="system-ui, -apple-system, sans-serif"
553
702
  >
554
- {displayLabel}
703
+ {node.label}
555
704
  </text>
556
705
  </g>
557
706
  );