@blackbelt-technology/pi-dashboard-flows-plugin 0.7.0 → 0.9.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 (54) hide show
  1. package/package.json +18 -7
  2. package/src/bridge/flow-files-reporter.ts +113 -0
  3. package/src/bridge/index.ts +5 -1
  4. package/src/client/FlowAgentCard.tsx +82 -213
  5. package/src/client/FlowAgentDetail.tsx +1 -1
  6. package/src/client/FlowDashboard.tsx +428 -66
  7. package/src/client/FlowInputWiring.tsx +2 -2
  8. package/src/client/FlowSummary.tsx +22 -16
  9. package/src/client/FlowYamlPopoverButton.tsx +27 -92
  10. package/src/client/FlowsCommandRoutes.tsx +13 -5
  11. package/src/client/FlowsSessionStateContext.tsx +40 -4
  12. package/src/client/FlowsSettings.tsx +4 -4
  13. package/src/client/SessionFlowActions.tsx +80 -6
  14. package/src/client/flow-attach-store.ts +140 -0
  15. package/src/client/flow-card-grid.ts +36 -0
  16. package/src/client/flow-files.ts +152 -0
  17. package/src/client/flow-idle-state.ts +230 -0
  18. package/src/client/format-cost.ts +21 -0
  19. package/src/client/send-safe.ts +19 -0
  20. package/src/flow-files-contract.ts +21 -0
  21. package/src/flow-reducer.ts +4 -0
  22. package/src/i18n.ts +28 -0
  23. package/src/server/automation-actions.ts +3 -0
  24. package/src/server/flow-files.ts +264 -0
  25. package/src/server/index.ts +15 -0
  26. package/src/AGENTS.md +0 -8
  27. package/src/__tests__/FlowGraph.test.ts +0 -305
  28. package/src/__tests__/FlowInputWiring.test.tsx +0 -97
  29. package/src/__tests__/FlowSummary.test.tsx +0 -331
  30. package/src/__tests__/FlowYamlPreview.test.tsx +0 -75
  31. package/src/__tests__/FlowsSessionStateContext.test.tsx +0 -223
  32. package/src/__tests__/FlowsUiStateContext.test.tsx +0 -140
  33. package/src/__tests__/authoring-renderers.test.tsx +0 -190
  34. package/src/__tests__/automation-actions.test.ts +0 -117
  35. package/src/__tests__/flow-agent-card-code-source.test.tsx +0 -190
  36. package/src/__tests__/flow-agent-cost.test.tsx +0 -160
  37. package/src/__tests__/flow-agent-error.test.ts +0 -60
  38. package/src/__tests__/flow-collapse-storage.test.ts +0 -90
  39. package/src/__tests__/flow-edges.test.ts +0 -195
  40. package/src/__tests__/flow-inputs.test.ts +0 -69
  41. package/src/__tests__/flow-reducer-bridge-contract.test.ts +0 -108
  42. package/src/__tests__/flow-reducer-seed-on-start.test.ts +0 -61
  43. package/src/__tests__/flow-yaml-parse.test.ts +0 -124
  44. package/src/__tests__/flows-for-cwd.test.ts +0 -51
  45. package/src/__tests__/flowsAvailability.test.ts +0 -79
  46. package/src/__tests__/manifest-discoverability.test.ts +0 -97
  47. package/src/__tests__/node-kind-reducer.test.ts +0 -135
  48. package/src/__tests__/plugin-action-handler.test.ts +0 -54
  49. package/src/__tests__/reducer-parity.test.ts +0 -106
  50. package/src/__tests__/render-actions.test.ts +0 -63
  51. package/src/__tests__/session-flow-actions-edit.test.tsx +0 -98
  52. package/src/bridge/AGENTS.md +0 -8
  53. package/src/client/AGENTS.md +0 -32
  54. package/src/server/AGENTS.md +0 -10
@@ -46,6 +46,8 @@ export interface ActionContributionLike {
46
46
  * `agent_end`) without knowing anything action-specific.
47
47
  * See change: finalize-event-dispatched-automation-runs.
48
48
  */
49
+ /** Event types `buildEvent` may emit (required by the automation registry). */
50
+ emits?: string[];
49
51
  buildEvent?: (args: { payload: Record<string, unknown>; automation: unknown }) =>
50
52
  | {
51
53
  eventType: string;
@@ -130,6 +132,7 @@ export function flowsActionContributions(flowsForCwd: FlowsForCwd): ActionContri
130
132
  // which pi-flows consumes as `flowInput` → `${{flow.input.<name>}}`.
131
133
  // `task` stays optional and may coexist with `inputs`.
132
134
  // See change: finalize-event-dispatched-automation-runs, wire-flow-inputs-in-automation.
135
+ emits: ["flow:run"],
133
136
  buildEvent: ({ payload }) => {
134
137
  const flow = String(payload.flow ?? "").trim();
135
138
  if (!FLOW_ID_RE.test(flow)) return null;
@@ -0,0 +1,264 @@
1
+ /**
2
+ * Per-session registry of the flow files a live session's pi-flows engine
3
+ * actually uses, reported by this plugin's own bridge (`flow:list-flows` +
4
+ * `flow:get-agents`) over the private plugin request lane. Lets the flows UI
5
+ * open a flow's YAML, its agent `.md` files and its code-node handlers even
6
+ * when they live in runtime-registered dirs (`flow:register-flows-dir` /
7
+ * `flow:register-agents-dir`, e.g. InvoiceBot / RackInspect) outside the host's
8
+ * `/api/pi-resource-file` allow-list — without any host-core change.
9
+ *
10
+ * Allowed = EXACT files only (realpath-canonicalized):
11
+ * - each reported flow `source` (`.yaml`/`.yml`)
12
+ * - each reported agent `source` (`.md`)
13
+ * - each code / code-decision handler the engine would run for a reported
14
+ * flow: `target:` → `resolve(sessionCwd, target)`, else
15
+ * `<dirname(flow.source)>/<step id>.ts` (pi-flows 0.5.0 execute-code-step)
16
+ * No sibling, parent dir, or helper file becomes readable.
17
+ * See change: attach-flow-before-run.
18
+ */
19
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
20
+ import rateLimit from "@fastify/rate-limit";
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import { parse as parseYaml } from "yaml";
24
+ import { FLOW_FILES_REPORT, FLOW_FILES_REQUEST_EVENT, type FlowFilesReport, type ReportedFile } from "../flow-files-contract.js";
25
+
26
+ interface SessionFiles {
27
+ allowed: Map<string, string>;
28
+ /** agent name → absolute agent file. */
29
+ agents: Record<string, string>;
30
+ /** flow name → step id → absolute handler file. */
31
+ handlers: Record<string, Record<string, string>>;
32
+ }
33
+
34
+ const YAML = /\.ya?ml$/i;
35
+ const MARKDOWN = /\.md$/i;
36
+ const HANDLER = /\.[cm]?[jt]s$/i;
37
+ /** Largest file served / parsed (flow files are small text). */
38
+ const MAX_FILE_BYTES = 1024 * 1024;
39
+ /** Largest number of flows / agents accepted per report. */
40
+ const MAX_REPORT_ITEMS = 2000;
41
+ /** Minimum gap between asks to one session's bridge to (re)report. */
42
+ const REPORT_REQUEST_COOLDOWN_MS = 2_000;
43
+
44
+ /** A regular file no larger than {@link MAX_FILE_BYTES}. */
45
+ function isSmallFile(p: string): boolean {
46
+ try {
47
+ const st = fs.statSync(p);
48
+ return st.isFile() && st.size <= MAX_FILE_BYTES;
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ function canonical(p: string): string {
55
+ try {
56
+ return fs.realpathSync(p);
57
+ } catch {
58
+ return path.resolve(p);
59
+ }
60
+ }
61
+
62
+ function sanitize(list: unknown, ext: RegExp): ReportedFile[] {
63
+ if (!Array.isArray(list)) return [];
64
+ const out: ReportedFile[] = [];
65
+ for (const item of list.slice(0, MAX_REPORT_ITEMS)) {
66
+ const name = (item as ReportedFile | null)?.name;
67
+ const source = (item as ReportedFile | null)?.source;
68
+ if (typeof name !== "string" || typeof source !== "string") continue;
69
+ if (!path.isAbsolute(source) || !ext.test(source)) continue;
70
+ out.push({ name, source });
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** Handler files pi-flows would run for one flow.yaml (read from disk). */
76
+ export function codeHandlerPaths(flowSource: string, cwd: string | undefined): Record<string, string> {
77
+ const out: Record<string, string> = Object.create(null);
78
+ if (!isSmallFile(flowSource)) return out;
79
+ let doc: unknown;
80
+ try {
81
+ doc = parseYaml(fs.readFileSync(flowSource, "utf8"));
82
+ } catch {
83
+ return out;
84
+ }
85
+ const steps = (doc as { steps?: unknown } | null)?.steps;
86
+ if (!Array.isArray(steps)) return out;
87
+ for (const raw of steps) {
88
+ const s = raw as { id?: unknown; type?: unknown; target?: unknown } | null;
89
+ if (!s || typeof s.id !== "string" || s.id === "__proto__") continue;
90
+ if (s.type !== "code" && s.type !== "code-decision") continue;
91
+ let file: string | undefined;
92
+ if (s.target !== undefined && s.target !== null && s.target !== "") {
93
+ if (cwd) file = path.resolve(cwd, String(s.target));
94
+ } else {
95
+ file = path.join(path.dirname(flowSource), `${s.id}.ts`);
96
+ }
97
+ if (file && HANDLER.test(file)) out[s.id] = file;
98
+ }
99
+ return out;
100
+ }
101
+
102
+ export class FlowFileRegistry {
103
+ private readonly bySession = new Map<string, SessionFiles>();
104
+
105
+ /** Replace a session's report. `cwd` resolves explicit code `target:`s. */
106
+ report(sessionId: string, report: FlowFilesReport | null | undefined, cwd?: string): void {
107
+ const flows = sanitize(report?.flows, YAML);
108
+ const agents = sanitize(report?.agents, MARKDOWN);
109
+ // lookup key (as reported / resolved, and its realpath) → canonical file.
110
+ const allowed = new Map<string, string>();
111
+ const allow = (file: string) => {
112
+ const real = canonical(file);
113
+ allowed.set(path.resolve(file), real);
114
+ allowed.set(real, real);
115
+ };
116
+ const agentMap: Record<string, string> = Object.create(null);
117
+ const handlers: Record<string, Record<string, string>> = Object.create(null);
118
+ for (const f of flows) {
119
+ allow(f.source);
120
+ const h = codeHandlerPaths(f.source, cwd);
121
+ handlers[f.name] = h;
122
+ for (const file of Object.values(h)) allow(file);
123
+ }
124
+ for (const a of agents) {
125
+ agentMap[a.name] = a.source;
126
+ allow(a.source);
127
+ }
128
+ this.bySession.set(sessionId, { allowed, agents: agentMap, handlers });
129
+ }
130
+
131
+ has(sessionId: string): boolean {
132
+ return this.bySession.has(sessionId);
133
+ }
134
+
135
+ remove(sessionId: string): void {
136
+ this.bySession.delete(sessionId);
137
+ }
138
+
139
+ /**
140
+ * The stored canonical path when `filePath` is exactly one of the session's
141
+ * reported files, else null. Pure string lookup — the request path never
142
+ * touches the filesystem; callers read only the returned stored path.
143
+ */
144
+ resolveAllowed(sessionId: string, filePath: string): string | null {
145
+ if (!path.isAbsolute(filePath)) return null;
146
+ return this.bySession.get(sessionId)?.allowed.get(path.resolve(filePath)) ?? null;
147
+ }
148
+
149
+ /** True when `filePath` is exactly one of the session's reported files. */
150
+ isAllowed(sessionId: string, filePath: string): boolean {
151
+ return this.resolveAllowed(sessionId, filePath) !== null;
152
+ }
153
+
154
+ /** Agent sources + per-flow code handler paths for one session. */
155
+ files(sessionId: string): { agents: Record<string, string>; handlers: Record<string, Record<string, string>> } | null {
156
+ const s = this.bySession.get(sessionId);
157
+ return s ? { agents: { ...s.agents }, handlers: { ...s.handlers } } : null;
158
+ }
159
+
160
+ /** Drop sessions no longer live. */
161
+ retainOnly(liveIds: ReadonlySet<string>): void {
162
+ for (const id of this.bySession.keys()) if (!liveIds.has(id)) this.bySession.delete(id);
163
+ }
164
+ }
165
+
166
+
167
+ const flowFileRegistry = new FlowFileRegistry();
168
+
169
+ interface RouteDeps {
170
+ fastify: ServerPluginContext["fastify"];
171
+ networkGuard: ServerPluginContext["networkGuard"];
172
+ registerPiRequestHandler?: (type: string, h: (payload: unknown, meta: { sessionId: string }) => unknown) => void;
173
+ sessionManager: { listActive(): unknown[]; getSession(id: string): unknown };
174
+ emitEventToSession: (sessionId: string, eventType: string, data: Record<string, unknown>) => boolean;
175
+ registry?: FlowFileRegistry;
176
+ }
177
+
178
+ function liveIds(sm: RouteDeps["sessionManager"]): Set<string> {
179
+ const ids = new Set<string>();
180
+ for (const s of sm.listActive()) {
181
+ const r = s as { id?: unknown; status?: unknown } | null;
182
+ if (r && typeof r.id === "string" && r.status !== "ended") ids.add(r.id);
183
+ }
184
+ return ids;
185
+ }
186
+
187
+ /**
188
+ * Wire the report lane + `GET /api/plugins/flows/files?sessionId` (agent
189
+ * sources + code handler paths) and `GET /api/plugins/flows/file?sessionId&path`
190
+ * (content of an exact reported file). Both behind the host `networkGuard`.
191
+ * A lookup for a live session with no report yet asks its bridge to report
192
+ * and answers `reported: false` (the client retries).
193
+ */
194
+ export async function registerFlowFileRoutes(deps: RouteDeps): Promise<void> {
195
+ const registry = deps.registry ?? flowFileRegistry;
196
+ const lastAsk = new Map<string, number>();
197
+ const requestReport = (sessionId: string) => {
198
+ const now = Date.now();
199
+ if (now - (lastAsk.get(sessionId) ?? 0) < REPORT_REQUEST_COOLDOWN_MS) return;
200
+ lastAsk.set(sessionId, now);
201
+ try {
202
+ deps.emitEventToSession(sessionId, FLOW_FILES_REQUEST_EVENT, {});
203
+ } catch {
204
+ /* best-effort */
205
+ }
206
+ };
207
+ const liveSession = (q: unknown): string | null => {
208
+ const id = (q as { sessionId?: unknown } | null)?.sessionId;
209
+ if (typeof id !== "string" || !id) return null;
210
+ const live = liveIds(deps.sessionManager);
211
+ registry.retainOnly(live);
212
+ for (const sid of lastAsk.keys()) if (!live.has(sid)) lastAsk.delete(sid);
213
+ return live.has(id) ? id : null;
214
+ };
215
+
216
+ deps.registerPiRequestHandler?.(FLOW_FILES_REPORT, (payload, meta) => {
217
+ const session = deps.sessionManager.getSession(meta.sessionId) as { cwd?: unknown } | undefined;
218
+ const cwd = typeof session?.cwd === "string" ? session.cwd : undefined;
219
+ registry.report(meta.sessionId, payload as FlowFilesReport, cwd);
220
+ return { ok: true };
221
+ });
222
+
223
+ // Routes live in an encapsulated scope carrying a request rate limit
224
+ // (recognized by CodeQL js/missing-rate-limiting; same pattern as
225
+ // system-one / gmail). Loopback is allow-listed.
226
+ await deps.fastify.register(async (scope) => {
227
+ await scope.register(rateLimit, { global: true, max: 600, timeWindow: "1 minute", allowList: ["127.0.0.1", "::1"] });
228
+
229
+ scope.get("/api/plugins/flows/files", { preHandler: deps.networkGuard }, async (req, reply) => {
230
+ const sessionId = liveSession(req.query);
231
+ if (!sessionId) return reply.code(404).send({ success: false, error: "session not found" });
232
+ const files = registry.files(sessionId);
233
+ if (!files) {
234
+ requestReport(sessionId);
235
+ return { success: true, data: { reported: false, agents: {}, handlers: {} } };
236
+ }
237
+ return { success: true, data: { reported: true, ...files } };
238
+ });
239
+
240
+ scope.get("/api/plugins/flows/file", { preHandler: deps.networkGuard }, async (req, reply) => {
241
+ const sessionId = liveSession(req.query);
242
+ const filePath = (req.query as { path?: unknown } | null)?.path;
243
+ if (!sessionId) return reply.code(404).send({ success: false, error: "session not found" });
244
+ if (typeof filePath !== "string" || !filePath) {
245
+ return reply.code(400).send({ success: false, error: "path parameter required" });
246
+ }
247
+ if (!registry.has(sessionId)) {
248
+ requestReport(sessionId);
249
+ return reply.code(409).send({ success: false, error: "not reported yet", retry: true });
250
+ }
251
+ const target = registry.resolveAllowed(sessionId, filePath);
252
+ if (!target) {
253
+ return reply.code(403).send({ success: false, error: "not a flow file of this session" });
254
+ }
255
+ if (!isSmallFile(target)) return reply.code(404).send({ success: false, error: "not found" });
256
+ try {
257
+ const content = await fs.promises.readFile(target, "utf8");
258
+ return { success: true, data: { type: "file", content } };
259
+ } catch {
260
+ return reply.code(404).send({ success: false, error: "not found" });
261
+ }
262
+ });
263
+ });
264
+ }
@@ -10,6 +10,7 @@
10
10
  import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
11
  import { provideFlowsActions } from "./automation-actions.js";
12
12
  import { readFlowInputs } from "./flow-inputs.js";
13
+ import { registerFlowFileRoutes } from "./flow-files.js";
13
14
  import { renderSessionFlowActions } from "./render-actions.js";
14
15
  import { stateStore } from "./state-store.js";
15
16
 
@@ -67,6 +68,20 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
67
68
  return { inputs: flow ? readFlowInputs(cwd, flow) : [] };
68
69
  });
69
70
 
71
+ // Flow YAML / agent / code-handler files reported by this plugin's bridge,
72
+ // so the UI can open files in runtime-registered flow dirs. Plugin-owned
73
+ // (no host allow-list change). Mounted in an encapsulated scope carrying a
74
+ // request rate limit (recognized by CodeQL js/missing-rate-limiting; same
75
+ // pattern as system-one / gmail). Loopback is allow-listed.
76
+ // See change: attach-flow-before-run.
77
+ await registerFlowFileRoutes({
78
+ fastify: ctx.fastify,
79
+ networkGuard: ctx.networkGuard,
80
+ registerPiRequestHandler: ctx.registerPiRequestHandler,
81
+ sessionManager: ctx.sessionManager,
82
+ emitEventToSession,
83
+ });
84
+
70
85
  /**
71
86
  * Broadcast the current intent tree for one session's slot.
72
87
  * Called from action handlers AND in response to event-store changes
package/src/AGENTS.md DELETED
@@ -1,8 +0,0 @@
1
- # DOX — packages/flows-plugin/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
6
- |------|---------|
7
- | `flow-reducer.ts` | Flow event fold. Reads `nodeKind` at `flow_agent_started` (decided once; agent-card fallback), `typedOutputs`/`branch`/`outcome` at complete, code target from `data.target`, `cost` from `result.cost` (verbatim, undefined when absent; see change surface-flow-agent-cost). Pre-lists code/code-decision steps as pending cards. `flow_complete` non-success downgrades in-flight cards to error/hard. See change: rework-flows-plugin-for-new-pi-flows. |
8
- | `reducer.ts` | Re-export barrel for `isFlowEvent`, `reduceFlowEvent`. Architect reducer exports REMOVED (flow-architect deleted upstream). See change: rework-flows-plugin-for-new-pi-flows. L1/L2 reducer coverage: `__tests__/flow-reducer-seed-on-start.test.ts` (missing-start -> null; start-then-progression advances status + agents to terminal) and `__tests__/flow-reducer-bridge-contract.test.ts` (CONTRACT-PINNED: event types read from the bridge `FLOW_EVENT_MAP` values, never hand-typed; core lifecycle reduces to terminal, reducer never throws on any mapped `flow_*`, passthrough leaves state unchanged). See change: add-flow-plugin-e2e-tests. |
@@ -1,305 +0,0 @@
1
- import {
2
- createUiPrimitiveRegistry,
3
- registerUiPrimitive,
4
- UiPrimitiveProvider,
5
- } from "@blackbelt-technology/dashboard-plugin-runtime";
6
- import { UI_PRIMITIVE_KEYS } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/ui-primitives.js";
7
- import { cleanup, render } from "@testing-library/react";
8
- import { createElement } from "react";
9
- import { afterEach, describe, expect, it } from "vitest";
10
- import { computeLayout, FlowGraph, type FlowGraphStep, mapStepType } from "../client/FlowGraph.js";
11
-
12
- const registry = createUiPrimitiveRegistry();
13
- registerUiPrimitive(registry, UI_PRIMITIVE_KEYS.zoomControls, ((() => null) as never));
14
-
15
- afterEach(() => cleanup());
16
-
17
- describe("FlowGraph render: on_complete label suppression", () => {
18
- it("renders branch labels but never the on_complete label", () => {
19
- // See change: fix-flow-ui-graph-zoom-summary — on_complete is the happy-path
20
- // default and renders as a plain arrow; branch labels stay visible.
21
- const steps: FlowGraphStep[] = [
22
- { id: "load", label: "load", status: "complete", blockedBy: [], type: "code", onComplete: "gate" },
23
- { id: "gate", label: "gate", status: "complete", blockedBy: [], type: "code-decision", branches: { go: "done" } },
24
- { id: "done", label: "done", status: "pending", blockedBy: [] },
25
- ];
26
- const { container } = render(
27
- createElement(UiPrimitiveProvider, {
28
- value: registry,
29
- children: createElement(FlowGraph, { steps }),
30
- }),
31
- );
32
- const text = container.textContent ?? "";
33
- expect(text).toContain("go"); // branch label rendered
34
- expect(text).not.toContain("on_complete"); // route happy-path label suppressed
35
- });
36
- });
37
-
38
- describe("mapStepType (canonical node set)", () => {
39
- it("maps the new code node kinds", () => {
40
- expect(mapStepType("code")).toBe("code");
41
- expect(mapStepType("code-decision")).toBe("code-decision");
42
- });
43
- it("maps fork + agent-decision to fork shape", () => {
44
- expect(mapStepType("fork")).toBe("fork");
45
- expect(mapStepType("agent-decision")).toBe("fork");
46
- });
47
- it("agent and removed legacy types (incl. flow-ref) map to default (undefined)", () => {
48
- expect(mapStepType("agent")).toBeUndefined();
49
- expect(mapStepType("conditional")).toBeUndefined();
50
- expect(mapStepType("agent-loop-decision")).toBeUndefined();
51
- expect(mapStepType("flow-ref")).toBeUndefined();
52
- });
53
- });
54
-
55
- describe("computeLayout", () => {
56
- it("lays out a linear flow A→B→C left-to-right", () => {
57
- const steps: FlowGraphStep[] = [
58
- { id: "a", label: "step-a", status: "complete", blockedBy: [] },
59
- { id: "b", label: "step-b", status: "running", blockedBy: ["a"] },
60
- { id: "c", label: "step-c", status: "pending", blockedBy: ["b"] },
61
- ];
62
-
63
- const result = computeLayout(steps);
64
-
65
- expect(result.nodes).toHaveLength(3);
66
- expect(result.edges).toHaveLength(2);
67
-
68
- // Nodes should be left-to-right: a.x < b.x < c.x
69
- const nodeA = result.nodes.find(n => n.id === "a")!;
70
- const nodeB = result.nodes.find(n => n.id === "b")!;
71
- const nodeC = result.nodes.find(n => n.id === "c")!;
72
- expect(nodeA.x).toBeLessThan(nodeB.x);
73
- expect(nodeB.x).toBeLessThan(nodeC.x);
74
-
75
- // All nodes at same y (linear flow, same rank)
76
- expect(nodeA.y).toBe(nodeB.y);
77
- expect(nodeB.y).toBe(nodeC.y);
78
-
79
- // Edges should have points
80
- for (const edge of result.edges) {
81
- expect(edge.points.length).toBeGreaterThanOrEqual(2);
82
- }
83
-
84
- // Width and height should be positive
85
- expect(result.width).toBeGreaterThan(0);
86
- expect(result.height).toBeGreaterThan(0);
87
- });
88
-
89
- it("lays out a branching flow A→B, A→C, B→D, C→D with vertical stacking", () => {
90
- const steps: FlowGraphStep[] = [
91
- { id: "a", label: "start", status: "complete", blockedBy: [] },
92
- { id: "b", label: "branch-1", status: "running", blockedBy: ["a"] },
93
- { id: "c", label: "branch-2", status: "running", blockedBy: ["a"] },
94
- { id: "d", label: "merge", status: "pending", blockedBy: ["b", "c"] },
95
- ];
96
-
97
- const result = computeLayout(steps);
98
-
99
- expect(result.nodes).toHaveLength(4);
100
- expect(result.edges).toHaveLength(4); // a→b, a→c, b→d, c→d
101
-
102
- const nodeA = result.nodes.find(n => n.id === "a")!;
103
- const nodeB = result.nodes.find(n => n.id === "b")!;
104
- const nodeC = result.nodes.find(n => n.id === "c")!;
105
- const nodeD = result.nodes.find(n => n.id === "d")!;
106
-
107
- // A and D should be at different x positions (different ranks)
108
- expect(nodeA.x).toBeLessThan(nodeB.x);
109
- expect(nodeB.x).toBeLessThan(nodeD.x);
110
-
111
- // B and C should be at the same x (same rank) but different y (stacked)
112
- expect(nodeB.x).toBe(nodeC.x);
113
- expect(nodeB.y).not.toBe(nodeC.y);
114
- });
115
-
116
- it("places no-blockedBy parallel roots in the same rank (no false serialization)", () => {
117
- // Two roots, no blockedBy, no separator between them. The engine runs both
118
- // in wave 1 (parallel); the layout must NOT synthesize an impl→docs edge that
119
- // pushes them into consecutive ranks (would read as sequential).
120
- const steps: FlowGraphStep[] = [
121
- { id: "impl", label: "impl", status: "running", blockedBy: [] },
122
- { id: "docs", label: "docs", status: "running", blockedBy: [] },
123
- ];
124
- const result = computeLayout(steps);
125
- expect(result.edges).toHaveLength(0);
126
- const impl = result.nodes.find(n => n.id === "impl")!;
127
- const docs = result.nodes.find(n => n.id === "docs")!;
128
- expect(impl.x).toBe(docs.x); // same rank
129
- expect(impl.y).not.toBe(docs.y); // stacked vertically = parallel
130
- });
131
-
132
- it("handles single-step flow", () => {
133
- const steps: FlowGraphStep[] = [
134
- { id: "solo", label: "solo-step", status: "running", blockedBy: [] },
135
- ];
136
-
137
- const result = computeLayout(steps);
138
- expect(result.nodes).toHaveLength(1);
139
- expect(result.edges).toHaveLength(0);
140
- expect(result.width).toBeGreaterThan(0);
141
- });
142
-
143
- it("marks a returning on_error route as a red loop-styled edge (isError + isReturning)", () => {
144
- const steps: FlowGraphStep[] = [
145
- { id: "validate", label: "validate", status: "complete", blockedBy: [], type: "code-decision", onError: "fixup" },
146
- { id: "transform", label: "transform", status: "running", blockedBy: ["validate"] },
147
- { id: "fixup", label: "fixup", status: "pending", blockedBy: [], onComplete: "validate" },
148
- ];
149
- const result = computeLayout(steps);
150
- const e = result.edges.find(ed => ed.source === "validate" && ed.target === "fixup");
151
- expect(e).toBeTruthy();
152
- expect(e!.isError).toBe(true);
153
- expect(e!.isReturning).toBe(true);
154
- // dagre-routed: multi-segment polyline (does not cross the band naively)
155
- expect(e!.points.length).toBeGreaterThanOrEqual(2);
156
- });
157
-
158
- it("collapses terminal on_error handlers into a single sink node", () => {
159
- const steps: FlowGraphStep[] = [
160
- { id: "a", label: "a", status: "complete", blockedBy: [], onError: "notify" },
161
- { id: "b", label: "b", status: "running", blockedBy: ["a"], onError: "notify" },
162
- { id: "notify", label: "notify", status: "pending", blockedBy: [] },
163
- ];
164
- const result = computeLayout(steps);
165
- expect(result.errorSink).toBeTruthy();
166
- expect(result.errorSink!.handlers).toEqual(["notify"]);
167
- // the terminal handler is NOT laid out as a normal node
168
- expect(result.nodes.some(n => n.id === "notify")).toBe(false);
169
- // both terminal routes are present as error edges (routed to the sink)
170
- expect(result.edges.filter(e => e.isError).map(e => e.source).sort()).toEqual(["a", "b"]);
171
- });
172
-
173
- it("removes error routes from layout when showErrorRoutes is false (zero footprint)", () => {
174
- const withErr: FlowGraphStep[] = [
175
- { id: "a", label: "a", status: "complete", blockedBy: [], onError: "notify" },
176
- { id: "b", label: "b", status: "running", blockedBy: ["a"] },
177
- { id: "notify", label: "notify", status: "pending", blockedBy: [] },
178
- ];
179
- const baseline: FlowGraphStep[] = [
180
- { id: "a", label: "a", status: "complete", blockedBy: [] },
181
- { id: "b", label: "b", status: "running", blockedBy: ["a"] },
182
- ];
183
- const off = computeLayout(withErr, { showErrorRoutes: false });
184
- const base = computeLayout(baseline);
185
- expect(off.errorSink).toBeUndefined();
186
- expect(off.edges.some(e => e.isError)).toBe(false);
187
- expect(off.nodes.some(n => n.id === "notify")).toBe(false);
188
- expect(off.height).toBe(base.height);
189
- });
190
-
191
- it("handles empty steps array", () => {
192
- const result = computeLayout([]);
193
- // Should return empty layout without throwing
194
- expect(result.nodes).toHaveLength(0);
195
- expect(result.edges).toHaveLength(0);
196
- });
197
-
198
- it("uses consistent node dimensions", () => {
199
- const steps: FlowGraphStep[] = [
200
- { id: "a", label: "step-a", status: "pending", blockedBy: [] },
201
- { id: "b", label: "step-b", status: "pending", blockedBy: ["a"] },
202
- ];
203
-
204
- const result = computeLayout(steps);
205
- // All nodes should have same width and height
206
- expect(result.nodes[0].width).toBe(result.nodes[1].width);
207
- expect(result.nodes[0].height).toBe(result.nodes[1].height);
208
- expect(result.nodes[0].width).toBeGreaterThan(0);
209
- expect(result.nodes[0].height).toBeGreaterThan(0);
210
- });
211
-
212
- it("preserves status on positioned nodes", () => {
213
- const steps: FlowGraphStep[] = [
214
- { id: "a", label: "step-a", status: "complete", blockedBy: [] },
215
- { id: "b", label: "step-b", status: "error", blockedBy: ["a"] },
216
- ];
217
-
218
- const result = computeLayout(steps);
219
- expect(result.nodes.find(n => n.id === "a")!.status).toBe("complete");
220
- expect(result.nodes.find(n => n.id === "b")!.status).toBe("error");
221
- });
222
-
223
- it("edges carry source/target status for styling", () => {
224
- const steps: FlowGraphStep[] = [
225
- { id: "a", label: "step-a", status: "complete", blockedBy: [] },
226
- { id: "b", label: "step-b", status: "running", blockedBy: ["a"] },
227
- ];
228
-
229
- const result = computeLayout(steps);
230
- expect(result.edges).toHaveLength(1);
231
- expect(result.edges[0].sourceStatus).toBe("complete");
232
- expect(result.edges[0].targetStatus).toBe("running");
233
- });
234
-
235
- it("layout dimensions are consistent regardless of step count", () => {
236
- // Single node
237
- const single = computeLayout([
238
- { id: "a", label: "step-a", status: "pending", blockedBy: [] },
239
- ]);
240
- // Many nodes
241
- const many = computeLayout([
242
- { id: "a", label: "step-a", status: "pending", blockedBy: [] },
243
- { id: "b", label: "step-b", status: "pending", blockedBy: ["a"] },
244
- { id: "c", label: "step-c", status: "pending", blockedBy: ["b"] },
245
- { id: "d", label: "step-d", status: "pending", blockedBy: ["c"] },
246
- ]);
247
- // Nodes should have identical dimensions in both layouts (fixed-scale)
248
- expect(single.nodes[0].width).toBe(many.nodes[0].width);
249
- expect(single.nodes[0].height).toBe(many.nodes[0].height);
250
- // Multi-node layout should be wider
251
- expect(many.width).toBeGreaterThan(single.width);
252
- });
253
-
254
- it("ignores blockedBy references to non-existent steps", () => {
255
- const steps: FlowGraphStep[] = [
256
- { id: "a", label: "step-a", status: "pending", blockedBy: ["nonexistent"] },
257
- ];
258
-
259
- const result = computeLayout(steps);
260
- expect(result.nodes).toHaveLength(1);
261
- expect(result.edges).toHaveLength(0); // no edge for missing dep
262
- });
263
-
264
- it("preserves type field on positioned nodes", () => {
265
- const steps: FlowGraphStep[] = [
266
- { id: "a", label: "agent-step", status: "pending", blockedBy: [], type: "agent" },
267
- { id: "b", label: "decision-step", status: "pending", blockedBy: ["a"], type: "code-decision" },
268
- ];
269
-
270
- const result = computeLayout(steps);
271
- expect(result.nodes.find(n => n.id === "a")!.type).toBe("agent");
272
- expect(result.nodes.find(n => n.id === "b")!.type).toBe("code-decision");
273
- });
274
-
275
- it("renders forward decision-branch edges with labels while running", () => {
276
- const steps: FlowGraphStep[] = [
277
- { id: "choose", label: "choose", status: "running", blockedBy: [], type: "fork", branches: { PathA: "a", PathB: "b" } },
278
- { id: "a", label: "a", status: "pending", blockedBy: [] },
279
- { id: "b", label: "b", status: "pending", blockedBy: [] },
280
- ];
281
- const result = computeLayout(steps);
282
- const labels = result.edges.map(e => e.label).sort();
283
- expect(result.edges).toHaveLength(2);
284
- expect(labels).toEqual(["PathA", "PathB"]);
285
- });
286
-
287
- it("marks a backward branch as a loop edge, routed by dagre (not a hand-arc)", () => {
288
- const steps: FlowGraphStep[] = [
289
- { id: "work", label: "work", status: "complete", blockedBy: [] },
290
- { id: "gate", label: "gate", status: "running", blockedBy: ["work"], type: "code-decision", branches: { again: "work", go: "done" } },
291
- { id: "done", label: "done", status: "pending", blockedBy: [] },
292
- ];
293
- const result = computeLayout(steps);
294
- // Backward branch gate->work is a loop-styled edge (isLoop), routed by dagre.
295
- const loop = result.edges.find(e => e.source === "gate" && e.target === "work");
296
- expect(loop).toBeTruthy();
297
- expect(loop!.isLoop).toBe(true);
298
- expect(loop!.label).toBe("again");
299
- expect(loop!.points.length).toBeGreaterThanOrEqual(2);
300
- // forward branch gate->done carries its label and is not a loop.
301
- const fwd = result.edges.find(e => e.source === "gate" && e.target === "done");
302
- expect(fwd?.label).toBe("go");
303
- expect(fwd?.isLoop).toBeFalsy();
304
- });
305
- });