@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,66 +1,119 @@
1
- import React, { useState } from "react";
1
+ import {
2
+ usePluginSend,
3
+ useSessionData,
4
+ useT,
5
+ useUiPrimitive,
6
+ } from "@blackbelt-technology/dashboard-plugin-runtime";
7
+ import { usePluginConfig } from "@blackbelt-technology/dashboard-plugin-runtime/context";
8
+ import type { UiSelectOption as SelectOption } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
9
+ import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
10
+ import type {
11
+ CommandInfo,
12
+ DashboardSession,
13
+ FlowInfo,
14
+ FlowState,
15
+ } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
+ import { mdiPencil, mdiPlay } from "@mdi/js";
2
17
  import { Icon } from "@mdi/react";
3
- import { mdiPlay, mdiPlus } from "@mdi/js";
4
- import type { FlowInfo } from "@blackbelt-technology/pi-dashboard-shared/types.js";
18
+ import React, { useEffect, useRef, useState } from "react";
19
+ import { FlowActivityBadge } from "./FlowActivityBadge.js";
20
+ import { FlowAuthorPromptDialog } from "./FlowAuthorPromptDialog.js";
5
21
  import { FlowLaunchDialog } from "./FlowLaunchDialog.js";
6
- import { ConfirmDialog } from "../../../client/src/components/ConfirmDialog.js";
7
- import { SearchableSelectDialog, type SelectOption } from "../../../client/src/components/SearchableSelectDialog.js";
22
+ import { useFlowsSessionState } from "./FlowsSessionStateContext.js";
23
+ import type { FlowsPluginConfig } from "./FlowsSettings.js";
8
24
 
9
25
  export function SessionFlowActions({
10
26
  flows,
11
- hasFlowsNew,
12
- hasFlowsEdit,
27
+ editMode,
13
28
  hasFlowsDelete,
14
29
  onFlowAction,
30
+ onEditFlow,
31
+ flowState,
32
+ onAbortFlow,
15
33
  }: {
16
34
  flows: FlowInfo[];
17
- hasFlowsNew: boolean;
18
- hasFlowsEdit?: boolean;
35
+ /** Edit-mode on → show the New / Edit launcher (authoring via the skill). */
36
+ editMode: boolean;
19
37
  hasFlowsDelete?: boolean;
20
38
  onFlowAction: (action: string, opts?: { flowName?: string; task?: string; description?: string }) => void;
39
+ /**
40
+ * Launch the manage-flows skill for an existing flow (name) or a new flow
41
+ * (undefined), carrying the user's stated intent (description for new, change
42
+ * instruction for edit; empty string when none given).
43
+ */
44
+ onEditFlow: (flowName: string | undefined, instruction: string) => void;
45
+ /** Current flow state for this session. Drives the status pill rendered above the action buttons. */
46
+ flowState?: FlowState | null;
47
+ /** Dispatch flow_control abort. Called by the running-flow pill's Abort button. */
48
+ onAbortFlow?: () => void;
21
49
  }) {
50
+ const t = useT();
51
+ const ConfirmDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.confirmDialog);
52
+ const SearchableSelectDialog = useUiPrimitive(UI_PRIMITIVE_KEYS.searchableSelectDialog);
22
53
  const [pickerOpen, setPickerOpen] = useState(false);
23
54
  const [editPickerOpen, setEditPickerOpen] = useState(false);
24
- const [editFlowName, setEditFlowName] = useState<string | null>(null);
55
+ // After picking from the edit launcher, capture intent before launching the skill.
56
+ const [authorTarget, setAuthorTarget] = useState<{ mode: "new" | "edit"; flowName?: string } | null>(null);
25
57
  const [deletePickerOpen, setDeletePickerOpen] = useState(false);
26
58
  const [deleteFlowName, setDeleteFlowName] = useState<string | null>(null);
27
59
  const [selectedFlow, setSelectedFlow] = useState<FlowInfo | null>(null);
28
- const [newFlowOpen, setNewFlowOpen] = useState(false);
29
60
 
30
- if (flows.length === 0 && !hasFlowsNew) return null;
61
+ // Compute running-flow badge inputs from flowState (when present).
62
+ // See change: fix-flows-plugin-polish (A5 + A6).
63
+ const badgeProps = flowState
64
+ ? (() => {
65
+ const agents = flowState.agents;
66
+ const total = agents.size;
67
+ const done = Array.from(agents.values()).filter(
68
+ (a) => a.status === "complete" || a.status === "error" || a.status === "blocked",
69
+ ).length;
70
+ return {
71
+ flowName: flowState.flowName,
72
+ agentsDone: done,
73
+ agentsTotal: total,
74
+ status: flowState.status,
75
+ };
76
+ })()
77
+ : null;
78
+
79
+ if (flows.length === 0 && !editMode && !badgeProps) return null;
31
80
 
32
81
  const flowOptions: SelectOption[] = flows.map((f) => ({
33
82
  value: f.name,
34
83
  label: f.name,
35
84
  description: f.description,
36
85
  }));
86
+ // Edit launcher options: existing flows + a "new flow" sentinel.
87
+ const editOptions: SelectOption[] = [
88
+ { value: "__new__", label: t("newFlowOption", undefined, "+ New flow"), description: t("newFlowOptionDesc", undefined, "Author a new flow with the edit-flow skill") },
89
+ ...flowOptions,
90
+ ];
37
91
 
38
92
  return (
39
93
  <>
40
- <div>
94
+ <div className="flex flex-col gap-1.5">
95
+ {badgeProps && (
96
+ <FlowActivityBadge
97
+ {...badgeProps}
98
+ onAbort={badgeProps.status === "running" ? onAbortFlow : undefined}
99
+ />
100
+ )}
41
101
  <div className="flex items-center gap-1.5 flex-wrap">
42
102
  {flows.length > 0 && (
43
103
  <button
44
104
  onClick={(e) => { e.stopPropagation(); setPickerOpen(true); }}
45
105
  className="text-[10px] px-1.5 py-0.5 rounded border border-blue-500/30 text-blue-400 hover:bg-blue-500/10"
46
106
  >
47
- <Icon path={mdiPlay} size={0.4} className="inline mr-0.5" />Run Flow...
48
- </button>
49
- )}
50
- {hasFlowsNew && (
51
- <button
52
- onClick={(e) => { e.stopPropagation(); setNewFlowOpen(true); }}
53
- className="text-[10px] px-1.5 py-0.5 rounded border border-purple-500/30 text-purple-400 hover:bg-purple-500/10"
54
- >
55
- <Icon path={mdiPlus} size={0.4} className="inline mr-0.5" />New Flow
107
+ <Icon path={mdiPlay} size={0.4} className="inline mr-0.5" />{t("runFlowButton", undefined, "Run Flow...")}
56
108
  </button>
57
109
  )}
58
- {hasFlowsEdit && flows.length > 0 && (
110
+ {editMode && (
59
111
  <button
60
112
  onClick={(e) => { e.stopPropagation(); setEditPickerOpen(true); }}
61
- className="text-[10px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-hover)]"
113
+ className="text-[10px] px-1.5 py-0.5 rounded border border-purple-500/30 text-purple-400 hover:bg-purple-500/10"
114
+ data-testid="flows-new-edit-button"
62
115
  >
63
- &#x270E;&#xFE0E; Edit
116
+ <Icon path={mdiPencil} size={0.4} className="inline mr-0.5" />{t("newEditButton", undefined, "New / Edit…")}
64
117
  </button>
65
118
  )}
66
119
  {hasFlowsDelete && flows.length > 0 && (
@@ -68,7 +121,7 @@ export function SessionFlowActions({
68
121
  onClick={(e) => { e.stopPropagation(); setDeletePickerOpen(true); }}
69
122
  className="text-[10px] px-1.5 py-0.5 rounded border border-[var(--border-subtle)] text-[var(--text-tertiary)] hover:text-[var(--text-primary)] hover:bg-[var(--bg-hover)]"
70
123
  >
71
- &#215; Delete
124
+ &#215; {t("delete", undefined, "Delete")}
72
125
  </button>
73
126
  )}
74
127
  </div>
@@ -77,10 +130,10 @@ export function SessionFlowActions({
77
130
  {/* Run: pick flow → task dialog */}
78
131
  {pickerOpen && (
79
132
  <SearchableSelectDialog
80
- title="Run Flow"
133
+ title={t("runFlowDialogTitle", undefined, "Run Flow")}
81
134
  options={flowOptions}
82
- placeholder="Search flows..."
83
- emptyMessage="No flows available"
135
+ placeholder={t("searchFlows", undefined, "Search flows...")}
136
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
84
137
  onSelect={(value) => {
85
138
  const flow = flows.find(f => f.name === value);
86
139
  if (flow) setSelectedFlow(flow);
@@ -102,42 +155,43 @@ export function SessionFlowActions({
102
155
  />
103
156
  )}
104
157
 
105
- {/* Edit: pick flow → modification input dialog */}
158
+ {/* New / Edit: pick an existing flow or "new" → launch the edit-flow skill */}
106
159
  {editPickerOpen && (
107
160
  <SearchableSelectDialog
108
- title="Edit Flow"
109
- options={flowOptions}
110
- placeholder="Search flows..."
111
- emptyMessage="No flows available"
161
+ title={t("newEditFlowTitle", undefined, "New / Edit flow")}
162
+ options={editOptions}
163
+ placeholder={t("pickFlowToEdit", undefined, "Pick a flow to edit, or + New flow…")}
164
+ emptyMessage={t("noFlowsYet", undefined, "No flows yet — pick + New flow")}
112
165
  onSelect={(value) => {
113
- setEditFlowName(value);
166
+ setAuthorTarget(
167
+ value === "__new__" ? { mode: "new" } : { mode: "edit", flowName: value },
168
+ );
114
169
  setEditPickerOpen(false);
115
170
  }}
116
171
  onCancel={() => setEditPickerOpen(false)}
117
172
  />
118
173
  )}
119
174
 
120
- {editFlowName && (
121
- <FlowLaunchDialog
122
- flowName={editFlowName}
123
- description="Describe how this flow should be updated"
124
- onSubmit={(desc) => {
125
- if (desc.trim()) {
126
- onFlowAction("edit", { flowName: editFlowName, description: desc.trim() });
127
- }
128
- setEditFlowName(null);
175
+ {/* New / Edit: capture intent → launch the manage-flows skill */}
176
+ {authorTarget && (
177
+ <FlowAuthorPromptDialog
178
+ mode={authorTarget.mode}
179
+ flowName={authorTarget.flowName}
180
+ onSubmit={(instruction) => {
181
+ onEditFlow(authorTarget.flowName, instruction);
182
+ setAuthorTarget(null);
129
183
  }}
130
- onCancel={() => setEditFlowName(null)}
184
+ onCancel={() => setAuthorTarget(null)}
131
185
  />
132
186
  )}
133
187
 
134
188
  {/* Delete: pick flow → confirm dialog */}
135
189
  {deletePickerOpen && (
136
190
  <SearchableSelectDialog
137
- title="Delete Flow"
191
+ title={t("deleteFlowTitle", undefined, "Delete Flow")}
138
192
  options={flowOptions}
139
- placeholder="Search flows..."
140
- emptyMessage="No flows available"
193
+ placeholder={t("searchFlows", undefined, "Search flows...")}
194
+ emptyMessage={t("noFlowsAvailable", undefined, "No flows available")}
141
195
  onSelect={(value) => {
142
196
  setDeleteFlowName(value);
143
197
  setDeletePickerOpen(false);
@@ -148,8 +202,8 @@ export function SessionFlowActions({
148
202
 
149
203
  {deleteFlowName && (
150
204
  <ConfirmDialog
151
- message={`Delete flow "${deleteFlowName}"? This will remove the flow file and any associated agents.`}
152
- confirmLabel="Delete"
205
+ message={t("deleteFlowConfirm", { name: deleteFlowName }, `Delete flow "${deleteFlowName}"? This will remove the flow file and any associated agents.`)}
206
+ confirmLabel={t("delete", undefined, "Delete")}
153
207
  onConfirm={() => {
154
208
  onFlowAction("delete", { flowName: deleteFlowName });
155
209
  setDeleteFlowName(null);
@@ -157,21 +211,74 @@ export function SessionFlowActions({
157
211
  onCancel={() => setDeleteFlowName(null)}
158
212
  />
159
213
  )}
160
-
161
- {/* New: description dialog */}
162
- {newFlowOpen && (
163
- <FlowLaunchDialog
164
- flowName="flows:new"
165
- description="Design a new flow with the Flow Architect"
166
- onSubmit={(task) => {
167
- if (task.trim()) {
168
- onFlowAction("new", { description: task.trim() });
169
- }
170
- setNewFlowOpen(false);
171
- }}
172
- onCancel={() => setNewFlowOpen(false)}
173
- />
174
- )}
175
214
  </>
176
215
  );
177
216
  }
217
+
218
+ /**
219
+ * Slot-consumer wrapper for the `session-card-action-bar` claim.
220
+ * Reads per-session `flows_list` and `commands_list` from the plugin-
221
+ * runtime per-session-data store (mirrored by the shell on every
222
+ * `flows_list` / `commands_list` browser-protocol message). Dispatches
223
+ * via pluginContext.send. See change: pluginize-flows-via-registry.
224
+ *
225
+ * Returns null when the session has no flows AND no `flows:new`
226
+ * command — this matches the shell's previous gate at
227
+ * SessionCard.tsx:651 (`flows && onFlowAction && ...`).
228
+ */
229
+ export function SessionFlowActionsClaim({ session }: { session: DashboardSession }) {
230
+ const flows = useSessionData<FlowInfo[]>(session.id, "flowsList") ?? [];
231
+ const commands = useSessionData<CommandInfo[]>(session.id, "commandsList") ?? [];
232
+ const { flowState } = useFlowsSessionState(session.id);
233
+ const send = usePluginSend();
234
+ const config = usePluginConfig<FlowsPluginConfig>();
235
+ const editMode = config.editFlow ?? false;
236
+
237
+ const hasFlowsDelete = commands.some((c) => c.name === "flows:delete");
238
+
239
+ // Reconcile the GLOBAL edit-mode default down to this session once its flows
240
+ // plugin is available (flowsList observed). pi-flows persists it to the
241
+ // project .pi/settings.json. Idempotent — re-emits only when the default
242
+ // changes. See change: rework-flows-plugin-for-new-pi-flows (D4).
243
+ const reconciledRef = useRef<boolean | null>(null);
244
+ useEffect(() => {
245
+ if (flows.length === 0) return; // wait until flows-plugin is available
246
+ if (reconciledRef.current === editMode) return;
247
+ reconciledRef.current = editMode;
248
+ send({ type: "flow_management", sessionId: session.id, action: "set-edit-mode", enabled: editMode });
249
+ }, [flows.length, editMode, session.id, send]);
250
+
251
+ // Render when there's a flow active OR action buttons are available.
252
+ if (flows.length === 0 && !editMode && !flowState) return null;
253
+
254
+ return (
255
+ <SessionFlowActions
256
+ flows={flows}
257
+ editMode={editMode}
258
+ hasFlowsDelete={hasFlowsDelete}
259
+ flowState={flowState}
260
+ onAbortFlow={() => send({ type: "flow_control", sessionId: session.id, action: "abort" })}
261
+ onEditFlow={(flowName, instruction) => {
262
+ const intent = instruction.trim();
263
+ // New flow: instruction describes what to build. Edit: flow name is
264
+ // token-1 (the skill reads that file), instruction follows on a new line.
265
+ const text = flowName
266
+ ? intent
267
+ ? `/skill:manage-flows ${flowName}\n\n${intent}`
268
+ : `/skill:manage-flows ${flowName}`
269
+ : `/skill:manage-flows ${intent}`;
270
+ send({ type: "send_prompt", sessionId: session.id, text });
271
+ }}
272
+ onFlowAction={(action, opts) =>
273
+ send({
274
+ type: "flow_management",
275
+ sessionId: session.id,
276
+ action,
277
+ flowName: opts?.flowName,
278
+ task: opts?.task,
279
+ description: opts?.description,
280
+ })
281
+ }
282
+ />
283
+ );
284
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Per-session persistence for the flow socket's collapse state. The whole-panel
3
+ * (`FlowSummary`) and live-dashboard (`FlowDashboard`) collapses are stored in
4
+ * localStorage keyed by session id, so collapsing a session's flow panel sticks
5
+ * across remounts/reloads instead of re-opening every time. Mirrors the
6
+ * try/catch-swallow pattern of `useSidebarState.ts`; a localStorage failure
7
+ * (quota / disabled / private mode) degrades to in-memory state and never throws.
8
+ *
9
+ * Default is expanded (false) for any session never collapsed.
10
+ *
11
+ * See change: fix-flow-ui-graph-zoom-summary.
12
+ */
13
+ import { useCallback, useEffect, useState } from "react";
14
+
15
+ export type FlowCollapseKind = "summary" | "dashboard";
16
+
17
+ /** localStorage key for a (kind, session) pair. */
18
+ export function flowCollapseKey(kind: FlowCollapseKind, sessionId: string): string {
19
+ return `dashboard:flow-${kind}-collapsed:${sessionId}`;
20
+ }
21
+
22
+ function readBoolean(key: string, fallback: boolean): boolean {
23
+ try {
24
+ const raw = localStorage.getItem(key);
25
+ if (raw === null) return fallback;
26
+ return raw === "true";
27
+ } catch {
28
+ return fallback;
29
+ }
30
+ }
31
+
32
+ function writeBoolean(key: string, value: boolean): void {
33
+ try {
34
+ localStorage.setItem(key, String(value));
35
+ } catch {
36
+ /* noop — degrade to in-memory */
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Generic localStorage-backed boolean toggle. Returns `[value, toggle]`.
42
+ * `key === null` → purely in-memory (no persistence). Re-syncs on key change
43
+ * (so a component reused under a new key reads the right value) without
44
+ * clobbering a same-key toggle. localStorage failures degrade to in-memory.
45
+ */
46
+ export function usePersistedToggle(
47
+ key: string | null,
48
+ fallback: boolean,
49
+ ): [boolean, () => void] {
50
+ const [value, setValue] = useState<boolean>(() => (key ? readBoolean(key, fallback) : fallback));
51
+
52
+ useEffect(() => {
53
+ setValue(key ? readBoolean(key, fallback) : fallback);
54
+ }, [key, fallback]);
55
+
56
+ const toggle = useCallback(() => {
57
+ setValue((prev) => {
58
+ const next = !prev;
59
+ if (key) writeBoolean(key, next);
60
+ return next;
61
+ });
62
+ }, [key]);
63
+
64
+ return [value, toggle];
65
+ }
66
+
67
+ /** localStorage key for the global error-route visibility toggle (not session-scoped). */
68
+ export const FLOW_SHOW_ERROR_ROUTES_KEY = "dashboard:flow-show-error-routes";
69
+
70
+ /**
71
+ * Persisted collapse state for one flow panel. Returns `[collapsed, toggle]`.
72
+ * When `sessionId` is undefined the state is purely in-memory (no key to scope by).
73
+ */
74
+ export function useFlowCollapsePersisted(
75
+ sessionId: string | undefined,
76
+ kind: FlowCollapseKind,
77
+ ): [boolean, () => void] {
78
+ return usePersistedToggle(sessionId ? flowCollapseKey(kind, sessionId) : null, false);
79
+ }
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Shared flow-edge derivation. ONE rule, consumed by both the live `FlowGraph`
3
+ * (running runs, from `dagSteps`) and the static `flow_write` Mermaid snapshot
4
+ * (from parsed YAML), so the two views never drift on what an edge is.
5
+ *
6
+ * Edge classes:
7
+ * - `sequential` — `blockedBy` dependency
8
+ * - `branch` — decision `branches` (fork / agent-decision / code-decision)
9
+ * - `route` — `on_complete` / `on_error` cross-segment routing
10
+ * - `implicit` — a step after a separator with no `blockedBy` (segment fall-through)
11
+ *
12
+ * The function derives only the classes its input carries: the live caller
13
+ * passes `branches` but not `onComplete`/`onError` (pi-flows omits those from
14
+ * `flow:flow-started`), so `route` edges appear only in the static caller.
15
+ *
16
+ * See change: improve-flow-ui.
17
+ */
18
+
19
+ export type FlowEdgeKind = "sequential" | "branch" | "route" | "implicit";
20
+
21
+ export interface FlowEdgeStep {
22
+ id: string;
23
+ /** Node kind (`agent` | `fork` | `agent-decision` | `code` | `code-decision`). */
24
+ type: string;
25
+ blockedBy: string[];
26
+ /** Decision branch label → target step id. */
27
+ branches?: Record<string, string>;
28
+ onComplete?: string;
29
+ onError?: string;
30
+ }
31
+
32
+ export interface FlowEdge {
33
+ from: string;
34
+ to: string;
35
+ label?: string;
36
+ kind: FlowEdgeKind;
37
+ /** Target declared at or before the source → render as backward/loop edge. */
38
+ backward: boolean;
39
+ /** Set only on `route` edges labeled `on_error`. `returning` = the handler's
40
+ * forward closure rejoins the main flow (live control flow → render as a loop
41
+ * arc); `terminal` = the handler is a sink that never rejoins (→ collapse into
42
+ * a tail sink node). Mirrors the engine, which keeps running every step
43
+ * reachable from an on_error target after routing to it. */
44
+ routeTopology?: "returning" | "terminal";
45
+ }
46
+
47
+ /** Derive the canonical edge set for a flow. Pure; order-sensitive (array index
48
+ * defines forward/backward). Skips edges whose endpoints are not in `steps`,
49
+ * and collapses duplicate `{from,to}` pairs (labeled branch/route wins). */
50
+ /** Separator node types that close a DAG segment and open the next. A
51
+ * no-blockedBy step falling through from one of these is the only `implicit`
52
+ * edge the engine actually serializes. (`flow-ref` is NOT a separator.) The
53
+ * set covers both raw stepTypes (static YAML preview) and the live graph's
54
+ * mapped types, where `agent-decision` collapses to `fork`. */
55
+ const SEPARATOR_TYPES = new Set(["fork", "agent-decision", "code-decision"]);
56
+
57
+ export function deriveFlowEdges(steps: FlowEdgeStep[]): FlowEdge[] {
58
+ const order = new Map(steps.map((s, i) => [s.id, i]));
59
+ const has = (id: string) => order.has(id);
60
+ const edges: FlowEdge[] = [];
61
+
62
+ const add = (from: string, to: string, kind: FlowEdgeKind, label?: string): void => {
63
+ if (!has(from) || !has(to)) return;
64
+ const backward = (order.get(to) ?? 0) <= (order.get(from) ?? 0);
65
+ const existing = edges.find((e) => e.from === from && e.to === to);
66
+ if (existing) {
67
+ // De-dup: prefer the labeled branch/route classification over a plain
68
+ // sequential/implicit edge for the same pair.
69
+ const labeled = kind === "branch" || kind === "route";
70
+ const existingLabeled = existing.kind === "branch" || existing.kind === "route";
71
+ if (labeled && !existingLabeled) {
72
+ existing.kind = kind;
73
+ existing.label = label;
74
+ existing.backward = backward;
75
+ }
76
+ return;
77
+ }
78
+ edges.push({ from, to, kind, label, backward });
79
+ };
80
+
81
+ // 1. Sequential edges (blockedBy).
82
+ for (const s of steps) {
83
+ for (const dep of s.blockedBy) add(dep, s.id, "sequential");
84
+ }
85
+
86
+ // 2. Decision-branch edges.
87
+ for (const s of steps) {
88
+ if (!s.branches) continue;
89
+ for (const [label, target] of Object.entries(s.branches)) {
90
+ add(s.id, target, "branch", label);
91
+ }
92
+ }
93
+
94
+ // 3. Routing edges (on_complete / on_error).
95
+ for (const s of steps) {
96
+ if (s.onComplete) add(s.id, s.onComplete, "route", "on_complete");
97
+ if (s.onError) add(s.id, s.onError, "route", "on_error");
98
+ }
99
+
100
+ // 4. Implicit-segment edges. The engine wave scheduler runs EVERY step whose
101
+ // blockedBy is satisfied at once — a step with no blockedBy is a root that
102
+ // fires in wave 1, in parallel with its siblings. Inter-segment ordering is
103
+ // enforced only by SEPARATOR steps (fork / agent-decision / code-decision),
104
+ // which close one segment and open the next. So a no-blockedBy step with no
105
+ // incoming edge falls through ONLY from the most recent separator (placing it
106
+ // after that boundary); two such roots after the same separator are parallel
107
+ // siblings and both fan out from it (never chained to each other). Roots
108
+ // before any separator stay un-parented → same rank → parallel.
109
+ const incoming = new Set(edges.map((e) => e.to));
110
+ let lastSeparator: string | undefined;
111
+ for (const curr of steps) {
112
+ const fallsThrough = curr.blockedBy.length === 0 && !incoming.has(curr.id);
113
+ if (fallsThrough && lastSeparator && lastSeparator !== curr.id) {
114
+ add(lastSeparator, curr.id, "implicit");
115
+ incoming.add(curr.id);
116
+ }
117
+ if (SEPARATOR_TYPES.has(curr.type)) lastSeparator = curr.id;
118
+ }
119
+
120
+ // 5. on_error route topology. The engine keeps running everything reachable
121
+ // from an on_error target. A handler is `returning` when its forward
122
+ // closure rejoins the source or the source's success continuation
123
+ // (live control flow → loop arc); `terminal` otherwise (a sink).
124
+ classifyRouteTopology(edges);
125
+
126
+ return edges;
127
+ }
128
+
129
+ /** Tag each `on_error` route edge with `routeTopology`. Pure: reachability over
130
+ * the flow edges EXCLUDING on_error routes (those are what we classify). A
131
+ * handler is `returning` when its forward closure reaches the route source or
132
+ * any node on the source's success continuation; else `terminal`. */
133
+ function classifyRouteTopology(edges: FlowEdge[]): void {
134
+ const errorRoutes = edges.filter((e) => e.kind === "route" && e.label === "on_error");
135
+ if (errorRoutes.length === 0) return;
136
+
137
+ const adj = new Map<string, string[]>();
138
+ for (const e of edges) {
139
+ if (e.kind === "route" && e.label === "on_error") continue; // exclude the edges under test
140
+ const list = adj.get(e.from);
141
+ if (list) list.push(e.to);
142
+ else adj.set(e.from, [e.to]);
143
+ }
144
+
145
+ const cache = new Map<string, Set<string>>();
146
+ const reach = (start: string): Set<string> => {
147
+ const cached = cache.get(start);
148
+ if (cached) return cached;
149
+ const seen = new Set<string>();
150
+ const stack = [start];
151
+ while (stack.length) {
152
+ const n = stack.pop() as string;
153
+ if (seen.has(n)) continue;
154
+ seen.add(n);
155
+ for (const m of adj.get(n) ?? []) stack.push(m);
156
+ }
157
+ cache.set(start, seen);
158
+ return seen;
159
+ };
160
+
161
+ for (const e of errorRoutes) {
162
+ const fromClosure = reach(e.from); // source + its success continuation
163
+ const handlerClosure = reach(e.to); // handler + its forward closure
164
+ let returning = false;
165
+ for (const n of handlerClosure) {
166
+ if (n !== e.to && (n === e.from || fromClosure.has(n))) {
167
+ returning = true;
168
+ break;
169
+ }
170
+ }
171
+ e.routeTopology = returning ? "returning" : "terminal";
172
+ }
173
+ }