Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 2 additions & 20 deletions packages/app/src/features/projects/graph-flow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
import "@xyflow/react/dist/style.css";
import { RunStatusLabel } from "../../shared/ui";
import { routeAroundNodes, roundedPath, type GraphRect, type GraphSide } from "./graph-geometry";
import { positionProjectGraph } from "./graph-layout.mjs";

export type GraphNode = { id: string; type: string; label: string; provider?: string; jobKind?: string; enabled?: boolean; runningCount?: number; concurrencyLimit?: number };
export type GraphConnection = { id: string; source: string; target: string; label: string; details?: string; kind: string; enabled: boolean };
Expand All @@ -16,27 +17,8 @@ type FlowEdge = Edge<GraphEdgeData, "routed">;
export type ProjectFlowInstance = ReactFlowInstance<FlowNode, FlowEdge>;
const width = (node: GraphNode) => node.type === "webhook" ? 145 : 220;
const height = (node: GraphNode) => node.type === "webhook" ? 70 : 112;
const positionFor = (nodes: GraphNode[], edges: GraphConnection[]) => {
const jobs = nodes.filter(node => node.type === "job");
const indegree = new Map(jobs.map(node => [node.id, 0]));
for (const edge of edges) if (indegree.has(edge.source) && indegree.has(edge.target) && edge.kind !== "manual") indegree.set(edge.target, indegree.get(edge.target)! + 1);
const level = new Map<string, number>(), queue = jobs.filter(node => indegree.get(node.id) === 0).map(node => node.id);
queue.forEach(id => level.set(id, 0));
for (let i = 0; i < queue.length; i++) for (const edge of edges) if (edge.source === queue[i] && indegree.has(edge.target) && edge.kind !== "manual") {
level.set(edge.target, Math.max(level.get(edge.target) ?? 0, (level.get(queue[i]) ?? 0) + 1));
indegree.set(edge.target, indegree.get(edge.target)! - 1); if (indegree.get(edge.target) === 0) queue.push(edge.target);
}
let maxLevel = Math.max(0, ...level.values());
for (const node of jobs) if (!level.has(node.id)) level.set(node.id, ++maxLevel);
const columns = new Map<number, GraphNode[]>();
for (const node of jobs) { const col = level.get(node.id)!; columns.set(col, [...(columns.get(col) ?? []), node]); }
const positions = new Map<string, { x: number; y: number }>();
for (const [col, column] of columns) column.forEach((node, row) => positions.set(node.id, { x: 300 + col * 340, y: 110 + row * 200 }));
nodes.filter(node => node.type === "webhook").forEach((node, row) => positions.set(node.id, { x: 35, y: 110 + row * 190 }));
return positions;
};
function makeLayout(nodes: GraphNode[], edges: GraphConnection[], onOpen: (id: string) => void, onSelect: (edge: GraphConnection) => void, onGroup: (edges: GraphConnection[], trigger: HTMLButtonElement) => void) {
const positions = positionFor(nodes, edges);
const positions = positionProjectGraph(nodes, edges);
const rects: GraphRect[] = nodes.map(node => ({ id: node.id, ...positions.get(node.id)!, width: width(node), height: height(node) }));
const grouped = new Map<string, GraphConnection[]>();
for (const edge of edges) { const pair = JSON.stringify([edge.source, edge.target].sort()); grouped.set(pair, [...(grouped.get(pair) ?? []), edge]); }
Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/features/projects/graph-layout.d.mts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export type LayoutNode = { id: string; type: string; label: string };
export type LayoutEdge = { source: string; target: string; enabled: boolean };
export function positionProjectGraph(nodes: LayoutNode[], edges: LayoutEdge[]): Map<string, { x: number; y: number }>;
124 changes: 124 additions & 0 deletions packages/app/src/features/projects/graph-layout.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
const JOB_GAP_X = 130;
const JOB_GAP_Y = 38;
const LEFT = 300;
const TOP = 40;
const WEBHOOK_LEFT = 35;
const WEBHOOK_GAP = 30;

const jobWidth = 220;
const jobHeight = 112;
const webhookWidth = 145;
const webhookHeight = 70;

const byId = (a, b) => a.id.localeCompare(b.id);

function stronglyConnectedComponents(ids, edges) {
const adjacency = new Map(ids.map(id => [id, []]));
for (const edge of edges) if (adjacency.has(edge.source) && adjacency.has(edge.target)) adjacency.get(edge.source).push(edge.target);
for (const targets of adjacency.values()) targets.sort();
let nextIndex = 0;
const indices = new Map(), low = new Map(), stack = [], onStack = new Set(), components = [];
function visit(id) {
indices.set(id, nextIndex); low.set(id, nextIndex++); stack.push(id); onStack.add(id);
for (const target of adjacency.get(id)) {
if (!indices.has(target)) { visit(target); low.set(id, Math.min(low.get(id), low.get(target))); }
else if (onStack.has(target)) low.set(id, Math.min(low.get(id), indices.get(target)));
}
if (low.get(id) === indices.get(id)) {
const component = [];
let member;
do { member = stack.pop(); onStack.delete(member); component.push(member); } while (member !== id);
component.sort(); components.push(component);
}
}
for (const id of [...ids].sort()) if (!indices.has(id)) visit(id);
return components;
}

/**
* Deterministic layered layout. Enabled automatic and manual job connections define ranks;
* disabled connections stay visible but do not pull jobs into misleading positions.
* @param {{id:string,type:string,label:string}[]} nodes
* @param {{source:string,target:string,enabled:boolean}[]} edges
* @returns {Map<string,{x:number,y:number}>}
*/
export function positionProjectGraph(nodes, edges) {
const jobs = nodes.filter(node => node.type === "job").sort(byId);
const jobIds = new Set(jobs.map(node => node.id));
const activeEdges = edges.filter(edge => edge.enabled && jobIds.has(edge.source) && jobIds.has(edge.target));
const components = stronglyConnectedComponents(jobs.map(node => node.id), activeEdges);
const componentOf = new Map();
components.forEach((component, index) => component.forEach(id => componentOf.set(id, index)));
const outgoing = components.map(() => new Set()), indegree = components.map(() => 0);
for (const edge of activeEdges) {
const from = componentOf.get(edge.source), to = componentOf.get(edge.target);
if (from !== to && !outgoing[from].has(to)) { outgoing[from].add(to); indegree[to]++; }
}
const componentKey = components.map(component => component[0]);
const ready = components.map((_, index) => index).filter(index => indegree[index] === 0).sort((a, b) => componentKey[a].localeCompare(componentKey[b]));
const rank = components.map(() => 0), topological = [];
while (ready.length) {
const current = ready.shift(); topological.push(current);
for (const next of [...outgoing[current]].sort((a, b) => componentKey[a].localeCompare(componentKey[b]))) {
rank[next] = Math.max(rank[next], rank[current] + 1);
if (--indegree[next] === 0) { ready.push(next); ready.sort((a, b) => componentKey[a].localeCompare(componentKey[b])); }
}
}
// The condensation graph is acyclic. This fallback keeps malformed/empty input safe.
for (const index of components.map((_, i) => i)) if (!topological.includes(index)) topological.push(index);
const layers = new Map();
for (const node of jobs) {
const value = rank[componentOf.get(node.id)];
layers.set(value, [...(layers.get(value) ?? []), node]);
}
for (const layer of layers.values()) layer.sort(byId);
const rankKeys = [...layers.keys()].sort((a, b) => a - b);
let order = new Map(rankKeys.map(key => [key, new Map(layers.get(key).map((node, index) => [node.id, index]))]));
const neighbors = new Map(jobs.map(node => [node.id, { incoming: [], outgoing: [] }]));
for (const edge of activeEdges) {
neighbors.get(edge.source).outgoing.push(edge.target);
neighbors.get(edge.target).incoming.push(edge.source);
}
const reorder = (key, direction) => {
const layer = layers.get(key), previous = order.get(key);
const updated = [...layer].sort((a, b) => {
const positions = node => neighbors.get(node.id)[direction]
.map(id => order.get(rank[componentOf.get(id)])?.get(id))
.filter(value => value !== undefined);
const pa = positions(a), pb = positions(b);
const ba = pa.length ? pa.reduce((sum, value) => sum + value, 0) / pa.length : previous.get(a.id);
const bb = pb.length ? pb.reduce((sum, value) => sum + value, 0) / pb.length : previous.get(b.id);
return ba - bb || previous.get(a.id) - previous.get(b.id) || a.id.localeCompare(b.id);
});
layers.set(key, updated);
order.set(key, new Map(updated.map((node, index) => [node.id, index])));
};
// Alternating barycentric sweeps reduce crossings while stable ties preserve permutation invariance.
for (let sweep = 0; sweep < 4; sweep++) {
for (const key of rankKeys.slice(1)) reorder(key, "incoming");
for (const key of rankKeys.slice(0, -1).reverse()) reorder(key, "outgoing");
}

const positions = new Map();
const centers = new Map();
for (const key of rankKeys) layers.get(key).forEach((node, row) => {
const y = TOP + row * (jobHeight + JOB_GAP_Y);
positions.set(node.id, { x: LEFT + key * (jobWidth + JOB_GAP_X), y });
centers.set(node.id, y + jobHeight / 2);
});

const webhooks = nodes.filter(node => node.type === "webhook").sort((a, b) => {
const targets = node => edges.filter(edge => edge.enabled && edge.source === node.id && centers.has(edge.target)).map(edge => centers.get(edge.target));
const average = values => values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : Infinity;
return average(targets(a)) - average(targets(b)) || a.id.localeCompare(b.id);
});
let lastWebhookY = TOP - WEBHOOK_GAP - webhookHeight;
for (const node of webhooks) {
const targets = edges.filter(edge => edge.enabled && edge.source === node.id && centers.has(edge.target)).map(edge => centers.get(edge.target));
const desired = targets.length ? targets.reduce((sum, value) => sum + value, 0) / targets.length - webhookHeight / 2 : TOP;
const y = Math.max(desired, lastWebhookY + webhookHeight + WEBHOOK_GAP);
positions.set(node.id, { x: WEBHOOK_LEFT, y });
lastWebhookY = y;
}
return positions;
}
48 changes: 48 additions & 0 deletions packages/app/test/graph-layout.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import assert from "node:assert/strict";
import test from "node:test";
import { positionProjectGraph } from "../src/features/projects/graph-layout.mjs";

const job = id => ({ id, type: "job", label: id });
const edge = (source, target, enabled = true) => ({ source, target, enabled });
const coord = (positions, id) => positions.get(id);

test("manual links affect ranks, disabled links do not, and input permutations are stable", () => {
const nodes = [job("c"), job("a"), job("d"), job("b")];
const edges = [edge("a", "b", false), edge("c", "d"), edge("a", "c", true), edge("b", "d", true), edge("d", "a", false)];
const expected = [...positionProjectGraph(nodes, edges)].sort(([a], [b]) => a.localeCompare(b));
for (const n of [nodes.toReversed(), [nodes[1], nodes[3], nodes[0], nodes[2]]]) {
for (const e of [edges.toReversed(), [...edges].sort((a, b) => `${a.source}:${a.target}`.localeCompare(`${b.source}:${b.target}`))]) {
assert.deepEqual([...positionProjectGraph(n, e)].sort(([a], [b]) => a.localeCompare(b)), expected);
}
}
const positions = new Map(expected);
assert.equal(coord(positions, "c").x, coord(positions, "a").x + 350);
assert.equal(coord(positions, "b").x, coord(positions, "a").x);
});

test("cycles share a meaningful layer and feedback edges do not create runaway columns", () => {
const nodes = [job("a"), job("b"), job("c"), job("d")];
const positions = positionProjectGraph(nodes, [edge("a", "b"), edge("b", "c"), edge("c", "b"), edge("c", "d")]);
assert.equal(positions.get("b").x, positions.get("c").x);
assert.equal(positions.get("d").x, positions.get("b").x + 350);
assert.equal(positions.get("a").x, positions.get("b").x - 350);
assert.notEqual(positions.get("b").y, positions.get("c").y);
});

test("branch and merge ordering follows connected neighbors to avoid a crossing", () => {
const nodes = [job("a"), job("b"), job("c"), job("d"), job("merge")];
const edges = [edge("a", "d"), edge("b", "c"), edge("c", "merge"), edge("d", "merge")];
const positions = positionProjectGraph(nodes, edges);
assert.ok(positions.get("a").y < positions.get("b").y);
assert.ok(positions.get("d").y < positions.get("c").y);
assert.ok(positions.get("merge").x > positions.get("d").x);
assert.notEqual(positions.get("c").y, positions.get("d").y);
});

test("webhook sources follow their enabled targets and remain separated", () => {
const nodes = [job("a"), job("b"), { id: "hook-2", type: "webhook", label: "Hook 2" }, { id: "hook-1", type: "webhook", label: "Hook 1" }];
const positions = positionProjectGraph(nodes, [edge("a", "b"), edge("hook-1", "a"), edge("hook-2", "b")]);
assert.ok(positions.get("hook-1").y < positions.get("hook-2").y);
assert.ok(positions.get("hook-2").y > positions.get("hook-1").y + 70);
assert.equal(positions.get("hook-1").x, positions.get("hook-2").x);
});
Loading