Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(graph): add selected custom nodes and readable connection routing

Rahmanb8bb331dd215
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 8a67ebb3..8678dc7d 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mso",
- "version": "0.2.20",
+ "version": "0.2.21",
"description": "Operate MSO projects, workflows, VPS resources, integrations, deployments, and MCP capabilities through reusable safety-first skills.",
"author": {
"name": "MSO"
diff --git a/components/shared/graph-custom-card.tsx b/components/shared/graph-custom-card.tsx
new file mode 100644
index 00000000..c22c3eea
--- /dev/null
+++ b/components/shared/graph-custom-card.tsx
@@ -0,0 +1,14 @@
+"use client";
+import { Handle, Position, type NodeProps } from "@xyflow/react";
+import { Boxes } from "lucide-react";
+import { cn } from "@/lib/utils";
+import type { CustomCanvasNode } from "./graph-custom-projection";
+
+export function GraphCustomCard({ data, selected }: NodeProps<CustomCanvasNode>) {
+ const inputs = data.ports.filter((port) => port.side === "in"), outputs = data.ports.filter((port) => port.side === "out");
+ return <div className={cn("relative w-60 rounded-xl border-2 border-primary/50 bg-card p-3 shadow-sm", selected && "ring-2 ring-ring")} style={{ minHeight: Math.max(104, 48 + Math.max(inputs.length, outputs.length) * 18) }}>
+ <div className="flex items-start gap-2"><Boxes className="size-4 shrink-0 text-primary"/><div className="min-w-0"><div className="line-clamp-2 break-words text-sm font-semibold">{data.group.name}</div><div className="mt-2 text-xs text-muted-foreground">Custom node · {data.group.nodeIds.length} members</div><div className="mt-1 text-[10px] text-muted-foreground">Double-click to expand</div></div></div>
+ {inputs.map((port, index) => <Handle key={port.id} id={port.id} type="target" position={Position.Left} isConnectable={false} title={port.label} style={{ top: 42 + index * 18 }} className="!size-2.5 !bg-primary"/>)}
+ {outputs.map((port, index) => <Handle key={port.id} id={port.id} type="source" position={Position.Right} isConnectable={false} title={port.label} style={{ top: 42 + index * 18 }} className="!size-2.5 !bg-primary"/>)}
+ </div>;
+}
diff --git a/components/shared/graph-custom-controls.tsx b/components/shared/graph-custom-controls.tsx
new file mode 100644
index 00000000..89da10bc
--- /dev/null
+++ b/components/shared/graph-custom-controls.tsx
@@ -0,0 +1,23 @@
+"use client";
+import { useState } from "react";
+import { Boxes, ChevronDown, ChevronUp, Ungroup } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { ResponsiveDialog } from "@/features/appshell";
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
+
+type Props = { groups: GraphCustomNode[]; selectedIds: string[]; nodeIds: string[]; onChange: (groups: GraphCustomNode[]) => void; disabled?: boolean };
+/** Shared selection action; grouping is presentation metadata, never an execution rewrite. */
+export function GraphCustomControls({ groups, selectedIds, nodeIds, onChange, disabled }: Props) {
+ const [open, setOpen] = useState(false), [name, setName] = useState(""), [managedId, setManagedId] = useState("");
+ const members = selectedIds.filter((id) => nodeIds.includes(id));
+ const occupied = members.some((id) => groups.some((group) => group.nodeIds.includes(id)));
+ const selectedGroup = groups.find((group) => selectedIds.includes(group.id)) ?? groups.find((group) => group.id === managedId);
+ const create = () => { if (!members.length || occupied || !name.trim()) return; onChange([...groups, { id: `custom-${crypto.randomUUID()}`, name: name.trim(), nodeIds: members, collapsed: true }]); setOpen(false); setName(""); };
+ return <div data-slot="graph-custom-controls" className="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-2">
+ <span className="text-xs text-muted-foreground" aria-live="polite">{selectedIds.length} selected</span>
+ <Button size="sm" variant="outline" disabled={disabled || !members.length || occupied} title={occupied ? "Ungroup existing members before creating another custom node" : "Select one or more nodes, then create a named custom node"} onClick={() => setOpen(true)}><Boxes className="mr-1 size-3.5"/>Create custom node</Button>
+ {groups.length ? <><select aria-label="Custom node" className="h-8 min-w-0 max-w-48 rounded-md border bg-background px-2 text-xs" value={selectedGroup?.id ?? ""} onChange={(event) => setManagedId(event.target.value)}><option value="">Manage custom node…</option>{groups.map((group) => <option key={group.id} value={group.id}>{group.name} ({group.nodeIds.length})</option>)}</select>{selectedGroup ? <><Button size="sm" variant="outline" disabled={disabled} onClick={() => onChange(groups.map((group) => group.id === selectedGroup.id ? { ...group, collapsed: !group.collapsed } : group))}>{selectedGroup.collapsed ? <ChevronDown className="mr-1 size-3.5"/> : <ChevronUp className="mr-1 size-3.5"/>}{selectedGroup.collapsed ? "Expand" : "Collapse"}</Button><Button size="sm" variant="ghost" disabled={disabled} onClick={() => { onChange(groups.filter((group) => group.id !== selectedGroup.id)); setManagedId(""); }}><Ungroup className="mr-1 size-3.5"/>Ungroup</Button></> : null}</> : null}
+ <ResponsiveDialog open={open} onOpenChange={setOpen} size="md" mobileVariant="drawer-bottom"><ResponsiveDialog.Header><ResponsiveDialog.Title>Create custom node</ResponsiveDialog.Title><ResponsiveDialog.Description>Group {members.length} selected node(s). Original nodes, ports, configuration and execution remain unchanged. Expand to edit or connect individual members.</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body><label className="grid gap-2 text-sm">Custom node name<Input autoFocus maxLength={120} value={name} onChange={(event) => setName(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter") create(); }}/></label></ResponsiveDialog.Body><ResponsiveDialog.Footer><Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button><Button disabled={disabled || !members.length || occupied || !name.trim()} onClick={create}>Create</Button></ResponsiveDialog.Footer></ResponsiveDialog>
+ </div>;
+}
diff --git a/components/shared/graph-custom-projection.ts b/components/shared/graph-custom-projection.ts
new file mode 100644
index 00000000..df9efa8b
--- /dev/null
+++ b/components/shared/graph-custom-projection.ts
@@ -0,0 +1,33 @@
+import type { Edge, Node } from "@xyflow/react";
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
+
+export type CustomNodeData = Record<string, unknown> & { group: GraphCustomNode; ports: { id: string; label: string; side: "in" | "out" }[] };
+export type CustomCanvasNode = Node<CustomNodeData, "customGroup">;
+
+/** Render proxies only. Stored nodes, handles, edges and configuration are never rewritten. */
+export function projectCustomNodes<N extends Node, E extends Edge>(nodes: N[], edges: E[], groups: GraphCustomNode[], selected: string[]) {
+ const collapsed = groups.filter((group) => group.collapsed && group.nodeIds.some((id) => nodes.some((node) => node.id === id)));
+ const owner = new Map(collapsed.flatMap((group) => group.nodeIds.map((id) => [id, group.id] as const)));
+ const nodeById = new Map(nodes.map((node) => [node.id, node]));
+ const proxies: CustomCanvasNode[] = collapsed.map((group) => {
+ const members = group.nodeIds.map((id) => nodeById.get(id)).filter((node): node is N => !!node);
+ const ports = edges.flatMap<CustomNodeData["ports"][number]>((edge) => {
+ if (owner.get(edge.source) === group.id && owner.get(edge.target) !== group.id) return [{ id: `out-${edge.id}`, label: String(edge.sourceHandle ?? edge.source), side: "out" as const }];
+ if (owner.get(edge.target) === group.id && owner.get(edge.source) !== group.id) return [{ id: `in-${edge.id}`, label: String(edge.targetHandle ?? edge.target), side: "in" as const }];
+ return [];
+ });
+ return { id: group.id, type: "customGroup", position: { x: Math.min(...members.map((node) => node.position.x)), y: Math.min(...members.map((node) => node.position.y)) }, width: 240, height: Math.max(104, 48 + Math.max(ports.filter((port) => port.side === "in").length, ports.filter((port) => port.side === "out").length) * 18), selected: selected.includes(group.id), data: { group, ports }, connectable: false, deletable: false };
+ });
+ const projectedEdges = edges.filter((edge) => !owner.has(edge.source) || owner.get(edge.source) !== owner.get(edge.target)).map((edge) => ({
+ ...edge, source: owner.get(edge.source) ?? edge.source, target: owner.get(edge.target) ?? edge.target,
+ ...(owner.has(edge.source) ? { sourceHandle: `out-${edge.id}` } : {}), ...(owner.has(edge.target) ? { targetHandle: `in-${edge.id}` } : {}),
+ }));
+ return { nodes: [...nodes.filter((node) => !owner.has(node.id)).map((node) => ({ ...node, selected: selected.includes(node.id) })), ...proxies] as (N | CustomCanvasNode)[], edges: projectedEdges };
+}
+
+export function moveCustomNode<T extends { id: string; position: { x: number; y: number } }>(nodes: T[], group: GraphCustomNode, position: { x: number; y: number }): T[] {
+ const members = nodes.filter((node) => group.nodeIds.includes(node.id));
+ if (!members.length) return nodes;
+ const dx = position.x - Math.min(...members.map((node) => node.position.x)), dy = position.y - Math.min(...members.map((node) => node.position.y));
+ return nodes.map((node) => group.nodeIds.includes(node.id) ? { ...node, position: { x: node.position.x + dx, y: node.position.y + dy } } : node);
+}
diff --git a/components/shared/graph-route.ts b/components/shared/graph-route.ts
new file mode 100644
index 00000000..fe956980
--- /dev/null
+++ b/components/shared/graph-route.ts
@@ -0,0 +1,76 @@
+/** Bounded orthogonal routing against measured node rectangles; no graph mutation. */
+export type RoutePoint = { x: number; y: number };
+export type RouteRect = RoutePoint & { width: number; height: number };
+const EPS = 0.01;
+export const distance = (a: RoutePoint, b: RoutePoint) => Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
+export function segmentBlocked(a: RoutePoint, b: RoutePoint, rects: RouteRect[]): boolean {
+ return rects.some((r) => Math.abs(a.x - b.x) < EPS
+ ? a.x > r.x + EPS && a.x < r.x + r.width - EPS && Math.max(a.y, b.y) > r.y + EPS && Math.min(a.y, b.y) < r.y + r.height - EPS
+ : Math.abs(a.y - b.y) < EPS
+ ? a.y > r.y + EPS && a.y < r.y + r.height - EPS && Math.max(a.x, b.x) > r.x + EPS && Math.min(a.x, b.x) < r.x + r.width - EPS
+ : true);
+}
+export function simplifyRoute(points: RoutePoint[]): RoutePoint[] {
+ const out: RoutePoint[] = [];
+ for (const point of points) {
+ if (out.length && distance(out[out.length - 1], point) < EPS) continue;
+ while (out.length > 1) {
+ const a = out[out.length - 2], b = out[out.length - 1];
+ if ((a.x === b.x && b.x === point.x || a.y === b.y && b.y === point.y) && distance(a, point) >= distance(a, b)) out.pop(); else break;
+ }
+ out.push(point);
+ }
+ return out;
+}
+const clear = (points: RoutePoint[], rects: RouteRect[]) => points.slice(1).every((point, i) => !segmentBlocked(points[i], point, rects));
+const length = (points: RoutePoint[]) => points.slice(1).reduce((total, p, i) => total + distance(points[i], p), 0);
+type Search = { key: number; cost: number; score: number };
+class Heap {
+ items: Search[] = [];
+ push(item: Search) { const a = this.items; a.push(item); let i = a.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (a[p].score <= item.score) break; a[i] = a[p]; i = p; } a[i] = item; }
+ pop() { const a = this.items, head = a[0], last = a.pop()!; if (a.length) { let i = 0; while (i * 2 + 1 < a.length) { let c = i * 2 + 1; if (c + 1 < a.length && a[c + 1].score < a[c].score) c++; if (a[c].score >= last.score) break; a[i] = a[c]; i = c; } a[i] = last; } return head; }
+}
+/** Fast channel candidates first; bounded A* handles multiple staggered obstacles. */
+export function orthogonalRoute(start: RoutePoint, end: RoutePoint, obstacles: RouteRect[], lane = 0): RoutePoint[] | null {
+ if (![start.x, start.y, end.x, end.y].every(Number.isFinite) || obstacles.length > 400) return null;
+ if (obstacles.some((r) => [start, end].some((p) => p.x > r.x && p.x < r.x + r.width && p.y > r.y && p.y < r.y + r.height))) return null;
+ const gap = 6 + Math.abs(lane) * 6;
+ const xs = [...new Set([start.x, end.x, (start.x + end.x) / 2 + lane * 18, ...obstacles.flatMap((r) => [r.x - gap, r.x + r.width + gap])])].sort((a, b) => a - b);
+ const ys = [...new Set([start.y, end.y, (start.y + end.y) / 2 + lane * 18, ...obstacles.flatMap((r) => [r.y - gap, r.y + r.height + gap])])].sort((a, b) => a - b);
+ const candidates = [
+ ...xs.map((x) => [start, { x, y: start.y }, { x, y: end.y }, end]),
+ ...ys.map((y) => [start, { x: start.x, y }, { x: end.x, y }, end]),
+ ].map(simplifyRoute);
+ const horizontal = Math.abs(end.x - start.x) >= Math.abs(end.y - start.y);
+ const preferred = (horizontal ? (start.x + end.x) / 2 : (start.y + end.y) / 2) + lane * 18;
+ const score = (points: RoutePoint[]) => length(points) + points.length * 12 + (points.length > 2 ? Math.abs((horizontal ? points[1].x : points[1].y) - preferred) * 0.08 : 0);
+ candidates.sort((a, b) => score(a) - score(b));
+ for (const candidate of candidates) if (clear(candidate, obstacles)) return candidate;
+ const width = xs.length, point = (id: number): RoutePoint => ({ x: xs[id % width], y: ys[Math.floor(id / width)] });
+ const first = ys.indexOf(start.y) * width + xs.indexOf(start.x), last = ys.indexOf(end.y) * width + xs.indexOf(end.x);
+ const heap = new Heap(), costs = new Map<number, number>([[first * 3, 0]]), parents = new Map<number, number>();
+ heap.push({ key: first * 3, cost: 0, score: distance(start, end) });
+ let visits = 0;
+ while (heap.items.length && visits++ < 12000) {
+ const current = heap.pop(); if (current.cost !== costs.get(current.key)) continue;
+ const cell = Math.floor(current.key / 3), direction = current.key % 3, here = point(cell);
+ if (cell === last) { const points = [here]; let key = current.key; while (parents.has(key)) { key = parents.get(key)!; points.push(point(Math.floor(key / 3))); } return simplifyRoute(points.reverse()); }
+ const x = cell % width, y = Math.floor(cell / width);
+ const neighbors: [number, number][] = [];
+ if (x > 0) neighbors.push([cell - 1, 1]); if (x + 1 < width) neighbors.push([cell + 1, 1]);
+ if (y > 0) neighbors.push([cell - width, 2]); if (y + 1 < ys.length) neighbors.push([cell + width, 2]);
+ for (const [next, dir] of neighbors) {
+ const target = point(next); if (segmentBlocked(here, target, obstacles)) continue;
+ const cost = current.cost + distance(here, target) + (direction && direction !== dir ? 18 : 0), key = next * 3 + dir;
+ if (cost >= (costs.get(key) ?? Infinity)) continue;
+ costs.set(key, cost); parents.set(key, current.key); heap.push({ key, cost, score: cost + distance(target, end) });
+ }
+ }
+ return null;
+}
+export function routePath(points: RoutePoint[]): string { return points.map((p, i) => `${i ? "L" : "M"}${p.x},${p.y}`).join(" "); }
+export function routeLabel(points: RoutePoint[]): RoutePoint {
+ let best = 0, label = points[0];
+ for (let i = 1; i < points.length; i++) { const size = distance(points[i - 1], points[i]); if (size > best) { best = size; label = { x: (points[i - 1].x + points[i].x) / 2, y: (points[i - 1].y + points[i].y) / 2 }; } }
+ return label;
+}
diff --git a/components/shared/graph-routed-edge.tsx b/components/shared/graph-routed-edge.tsx
new file mode 100644
index 00000000..e9a44e48
--- /dev/null
+++ b/components/shared/graph-routed-edge.tsx
@@ -0,0 +1,32 @@
+"use client";
+import { useMemo } from "react";
+import { BaseEdge, Position, getSmoothStepPath, useNodes, useEdges, type EdgeProps } from "@xyflow/react";
+import { orthogonalRoute, routeLabel, routePath, segmentBlocked, type RoutePoint } from "./graph-route";
+const direction = (position: Position) => position === Position.Left ? { x: -1, y: 0 } : position === Position.Right ? { x: 1, y: 0 } : position === Position.Top ? { x: 0, y: -1 } : { x: 0, y: 1 };
+
+/** Use actual measured cards, including collapsed groups. Only presentation changes. */
+export function GraphRoutedEdge(props: EdgeProps) {
+ const nodes = useNodes(), edges = useEdges();
+ const { id, source, target, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition } = props;
+ const siblings = edges.filter((edge) => edge.source === source || edge.target === target).map((edge) => edge.id).sort();
+ const lane = Math.max(0, siblings.indexOf(id));
+ const geometry = useMemo(() => {
+ const a = { x: sourceX, y: sourceY }, b = { x: targetX, y: targetY }, sd = direction(sourcePosition), td = direction(targetPosition), escape = 26 + (lane % 5) * 4;
+ const start = { x: a.x + sd.x * escape, y: a.y + sd.y * escape }, end = { x: b.x + td.x * escape, y: b.y + td.y * escape };
+ const obstacles = nodes.filter((node) => !node.hidden).map((node) => ({ x: node.position.x - 10, y: node.position.y - 10, width: (node.measured?.width ?? node.width ?? 240) + 20, height: (node.measured?.height ?? node.height ?? 120) + 20 }));
+ const ownSource = nodes.findIndex((node) => node.id === source), ownTarget = nodes.findIndex((node) => node.id === target);
+ const escapes = !segmentBlocked(a, start, obstacles.filter((_, i) => i !== ownSource)) && !segmentBlocked(end, b, obstacles.filter((_, i) => i !== ownTarget));
+ const middle = escapes ? orthogonalRoute(start, end, obstacles, lane % 7) : null;
+ if (!middle) { const [path, x, y] = getSmoothStepPath({ sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, offset: escape }); return { path, label: { x, y }, blocked: true }; }
+ const points: RoutePoint[] = [a, ...middle, b];
+ return { path: routePath(points), label: routeLabel(middle), blocked: false };
+ }, [nodes, source, target, sourceX, sourceY, targetX, targetY, sourcePosition, targetPosition, lane]);
+ const anySelected = nodes.some((node) => node.selected), adjacent = nodes.some((node) => node.selected && (node.id === source || node.id === target));
+ const style = { ...props.style, strokeWidth: adjacent || props.selected ? 3 : 2, opacity: anySelected && !adjacent && !props.selected ? 0.25 : props.style?.opacity ?? 1, ...(geometry.blocked ? { strokeDasharray: "3 5" } : {}), vectorEffect: "non-scaling-stroke" as const };
+ return <g data-routing-state={geometry.blocked ? "overlap" : "clear"}>
+ <title>{geometry.blocked ? "No clear route: move overlapping nodes apart" : `${source} → ${target}`}</title>
+ <path d={geometry.path} fill="none" stroke="var(--background)" strokeWidth={7} opacity={style.opacity} vectorEffect="non-scaling-stroke" pointerEvents="none"/>
+ <BaseEdge id={id} path={geometry.path} markerStart={props.markerStart} markerEnd={props.markerEnd} style={style} interactionWidth={22} label={props.label} labelX={geometry.label.x} labelY={geometry.label.y} labelStyle={{ fill: "var(--foreground)", fontSize: 11, ...props.labelStyle }} labelShowBg labelBgPadding={[5, 3]} labelBgBorderRadius={3} labelBgStyle={{ fill: "var(--background)" }}/>
+ </g>;
+}
+export const graphRoutedEdgeTypes = { routed: GraphRoutedEdge };
diff --git a/components/shared/use-graph-projection.ts b/components/shared/use-graph-projection.ts
new file mode 100644
index 00000000..13ce0a87
--- /dev/null
+++ b/components/shared/use-graph-projection.ts
@@ -0,0 +1,29 @@
+"use client";
+import { useCallback, useMemo, useState } from "react";
+import { applyEdgeChanges, applyNodeChanges, type Edge, type EdgeChange, type Node, type NodeChange } from "@xyflow/react";
+export type GraphProjection<N extends Node, E extends Edge> = { nodes: N[]; edges: E[] };
+type Snapshot<N extends Node, E extends Edge> = GraphProjection<N, E> & { source: GraphProjection<N, E> };
+
+/** One owner for transient selection/measurement/drag state. No effect-to-selection feedback. */
+export function reconcileGraphProjection<N extends Node, E extends Edge>(source: GraphProjection<N, E>, previous: Snapshot<N, E>): Snapshot<N, E> {
+ if (source === previous.source) return previous;
+ const oldNodes = new Map(previous.nodes.map((node) => [node.id, node]));
+ const addedSelection = source.nodes.some((node) => node.selected && !oldNodes.has(node.id));
+ const oldEdges = new Map(previous.edges.map((edge) => [edge.id, edge]));
+ return { source,
+ nodes: source.nodes.map((node) => ({ ...node, measured: oldNodes.get(node.id)?.measured ?? node.measured, selected: addedSelection ? Boolean(node.selected) : oldNodes.get(node.id)?.selected ?? node.selected })),
+ edges: source.edges.map((edge) => ({ ...edge, selected: oldEdges.get(edge.id)?.selected ?? edge.selected })),
+ };
+}
+export function useGraphProjection<N extends Node, E extends Edge>(source: GraphProjection<N, E>) {
+ const [snapshot, setSnapshot] = useState<Snapshot<N, E>>(() => ({ ...source, source }));
+ const current = useMemo(() => reconcileGraphProjection(source, snapshot), [source, snapshot]);
+ const onNodesChange = useCallback((changes: NodeChange<N>[]) => setSnapshot((previous) => {
+ const next = reconcileGraphProjection(source, previous); return { ...next, nodes: applyNodeChanges(changes, next.nodes) };
+ }), [source]);
+ const onEdgesChange = useCallback((changes: EdgeChange<E>[]) => setSnapshot((previous) => {
+ const next = reconcileGraphProjection(source, previous); return { ...next, edges: applyEdgeChanges(changes, next.edges) };
+ }), [source]);
+ const reset = useCallback(() => setSnapshot({ ...source, source }), [source]);
+ return { ...current, onNodesChange, onEdgesChange, reset };
+}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 0d0af9e8..2faa018f 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `graph` add selected custom nodes and readable connection routing
- `organization` add internal project flows with callable CRUD
## 2026-09-17
diff --git a/docs/ORGANIZATION.md b/docs/ORGANIZATION.md
index b1295ec7..07116cfe 100644
--- a/docs/ORGANIZATION.md
+++ b/docs/ORGANIZATION.md
@@ -169,3 +169,26 @@ notes; 2 MiB HTTP body and total private store. Over-limit notes are rejected, n
No flow operation executes a command, fetches a source reference, assigns an agent,
or promotes unconfirmed facts. Existing OAuth scope, device role and audit guards remain.
Public names are unchanged; rescan clients to see the expanded action enum/descriptions.
+
+
+### Custom nodes from canvas selection
+
+Select one node, Ctrl/Cmd-click additional nodes, or drag a selection rectangle in
+Select mode, then choose **Create custom node**. A named collapsed card keeps original
+member ids, notes and directed connections intact. Double-click or choose **Expand**
+to edit individual members; **Collapse** restores the compact view and **Ungroup**
+removes only the presentation wrapper. Nested/overlapping groups are rejected.
+Grouping and member positions persist in the same owner-private store; changes remain
+revision-checked, including one atomic write for a group/multi-node drag.
+
+`organization_manage` adds `flow_custom_nodes` with `data.unitId` and
+`data.customNodes: [{id,name,nodeIds,collapsed}]`, plus `flow_nodes_move` with
+`data.unitId` and `data.positions: [{id,position:{x,y}}]`. An explicit empty group array
+ungroups all; omitting it is an error. The CLI exposes the equivalent hyphenated actions.
+Deleting a member trims its group without deleting other members.
+
+Connectors now route against measured cards, use directional markers and crossing
+halos, and highlight adjacent routes on selection. A bounded router marks an impossible
+route with a dotted line and an overlap warning rather than claiming clearance; separate
+overlapping cards when their ports have no exit. Group boundary ports retain the original
+edge identity. Expand a custom node before creating new member connections.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 861292ac..fba176f5 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,10 @@
+## 2026-09-18 — Selected custom nodes and visible connector routing
+
+- Complete selection-based named grouping in Workflow and Organization project canvases. Collapse/expand/ungroup retain original executable nodes, ports and edges; grouping is bounded, validated metadata in the existing private stores.
+- Preserve multi-selection and atomic group/multi-node movement; prune group membership only on explicit member deletion. Extend existing function-calling and CLI actions rather than inventing another store.
+- Replace unconditional smoothstep connectors with shared bounded orthogonal routing against measured cards, directional markers, crossing halos and selected-route emphasis. Impossible overlapping-card paths are visibly marked rather than silently claimed safe.
+- Verification is performed against synthetic stores and the real production build; private operator graph content is never embedded in source.
+
## 2026-09-18 — Organization-scoped project flow
- The organization overview previously rendered long context notes directly inside unit cards. Keep overview descriptions clamped and put projects, activities, relationships and long notes inside the selected unit instead.
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index a2255117..734d8d0d 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -184,3 +184,23 @@ MSO targets **core self-hosted workflow parity**, not n8n's SaaS business surfac
## Organization seat routing
Organization is not owned by Workflow Graph. An `agent` node may set `orgSeatId`; at execution time MSO resolves that seat from the private Organization registry and routes to its current Project Agent, Local Agent, or A2A target. This indirection lets a workflow say “send to the CTO seat” without duplicating which concrete agent currently fills that seat. Direct project-bound Agent nodes remain backward compatible. See [`ORGANIZATION.md`](./ORGANIZATION.md).
+
+
+## Selected custom nodes and connector routing
+
+One or multiple selected nodes can become a named, collapsible custom node directly
+on the automation canvas. Ctrl/Cmd-click or box-select, then **Create custom node**.
+The selection survives rerenders. Double-click the compact card to expand it;
+**Ungroup** removes only the wrapper. Save persists the change as ordinary graph data.
+`metadata.customNodes` stores `{id,name,nodeIds,collapsed}` arrays, validated against
+the same graph. Members cannot belong to overlapping/nested groups.
+
+This is a presentation abstraction, not an executable new node type: stored node ids,
+configurations, boundary handles, input references, edge topology and run receipts stay
+unchanged. Original members execute in the original graph. Clone/export/import carry
+the grouping metadata. The existing `workflow_graph` get/update actions provide function
+calling with the current revision; no new transport or permission bypass is introduced.
+
+The shared connector renderer avoids measured node cards where a route exists, uses
+arrowheads and crossing halos, and highlights a selected node's incident routes.
+Overlapping cards without a viable port exit receive a visible routing warning.
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 0cdcf467..863ff77e 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,13 +4,13 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.15.1 version=2026.09.18.1 tools=111 read=54 write=35 exec=22 -->
+<!-- mcp-toolset: server=1.15.1 version=2026.09.18.2 tools=111 read=54 write=35 exec=22 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.15.1` |
-| Toolset | `2026.09.18.1` |
-| Toolset changed at | `2026-09-18T07:18:00+07:00` |
+| Toolset | `2026.09.18.2` |
+| Toolset changed at | `2026-09-18T10:20:00+07:00` |
| Transport tools | **113** |
| Model/operator tools | **111** |
| Read | **54** |
@@ -145,7 +145,7 @@
## ChatGPT model profile
-<!-- mcp-chatgpt-profile: server=1.15.1 version=2026.09.18.1 tools=111 read=54 write=35 exec=22 app-only=2 total=113 -->
+<!-- mcp-chatgpt-profile: server=1.15.1 version=2026.09.18.2 tools=111 read=54 write=35 exec=22 app-only=2 total=113 -->
The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.
diff --git a/frontend/slices/organization/components/organization-canvas.tsx b/frontend/slices/organization/components/organization-canvas.tsx
index 2c5f549b..1a5a4671 100644
--- a/frontend/slices/organization/components/organization-canvas.tsx
+++ b/frontend/slices/organization/components/organization-canvas.tsx
@@ -5,6 +5,7 @@ import { Building2 } from "lucide-react";
import { Handle, MarkerType, Position, type Edge, type Node, type NodeProps } from "@xyflow/react";
import type { OrganizationChart, OrganizationSeat, OrganizationSeatRuntime, OrganizationUnit } from "@/lib/contracts/organization";
import { Badge } from "@/components/ui/badge";
+import { graphRoutedEdgeTypes } from "@/components/shared/graph-routed-edge";
import { GraphCanvas } from "@/components/shared/graph-canvas";
import { useContainer } from "@/features/appshell";
import { cn } from "@/lib/utils";
@@ -58,10 +59,10 @@ export function OrganizationCanvas({ chart, runtime, unitId, selectedSeatId, onU
}, [chart, layoutOptions, runtimeById, selectedSeatId, unitById, unitId]);
const visible = useMemo(() => new Set(nodes.map((node) => node.id)), [nodes]);
const edges = useMemo<Edge[]>(() => {
- if (!unitId) return chart.units.filter((unit) => unit.parentUnitId && visible.has(unit.parentUnitId)).map((unit) => ({ id: `unit-${unit.parentUnitId}-${unit.id}`, source: unit.parentUnitId!, target: unit.id, type: "smoothstep", markerEnd: { type: MarkerType.ArrowClosed, width: 18, height: 18, color: "var(--sep-strong)" }, style: { stroke: "var(--sep-strong)", strokeWidth: 1.6 } }));
+ if (!unitId) return chart.units.filter((unit) => unit.parentUnitId && visible.has(unit.parentUnitId)).map((unit) => ({ id: `unit-${unit.parentUnitId}-${unit.id}`, source: unit.parentUnitId!, target: unit.id, type: "routed", markerEnd: { type: MarkerType.ArrowClosed, width: 18, height: 18, color: "var(--muted-foreground)" }, style: { stroke: "var(--muted-foreground)", strokeWidth: 1.6 } }));
return chart.seats.filter((seat) => visible.has(seat.id) && seat.reportsToSeatId && visible.has(seat.reportsToSeatId)).map((seat) => {
- const parent = chart.seats.find((row) => row.id === seat.reportsToSeatId), crossUnit = Boolean(parent && parent.unitId !== seat.unitId), busy = runtimeById.get(seat.id)?.status === "busy" || runtimeById.get(seat.reportsToSeatId!)?.status === "busy", stroke = busy ? "var(--warning)" : "var(--sep-strong)";
- return { id: `seat-${seat.reportsToSeatId}-${seat.id}`, source: seat.reportsToSeatId!, target: seat.id, type: "smoothstep", animated: busy, markerEnd: { type: MarkerType.ArrowClosed, width: 18, height: 18, color: stroke }, style: { stroke, strokeWidth: busy ? 2.4 : 1.6, strokeDasharray: crossUnit ? "7 5" : undefined } };
+ const parent = chart.seats.find((row) => row.id === seat.reportsToSeatId), crossUnit = Boolean(parent && parent.unitId !== seat.unitId), busy = runtimeById.get(seat.id)?.status === "busy" || runtimeById.get(seat.reportsToSeatId!)?.status === "busy", stroke = busy ? "var(--warning)" : "var(--muted-foreground)";
+ return { id: `seat-${seat.reportsToSeatId}-${seat.id}`, source: seat.reportsToSeatId!, target: seat.id, type: "routed", animated: busy, markerEnd: { type: MarkerType.ArrowClosed, width: 18, height: 18, color: stroke }, style: { stroke, strokeWidth: busy ? 2.4 : 1.6, strokeDasharray: crossUnit ? "7 5" : undefined } };
});
}, [chart.seats, chart.units, runtimeById, unitId, visible]);
@@ -72,7 +73,7 @@ export function OrganizationCanvas({ chart, runtime, unitId, selectedSeatId, onU
ariaLabel={unitId ? "Organization seats canvas" : "Organization units canvas"}
nodes={nodes}
edges={edges}
- nodeTypes={nodeTypes}
+ nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}
nodesDraggable={false}
nodesConnectable={false}
edgesFocusable={false}
diff --git a/frontend/slices/organization/components/project-flow.tsx b/frontend/slices/organization/components/project-flow.tsx
index 26515829..55039652 100644
--- a/frontend/slices/organization/components/project-flow.tsx
+++ b/frontend/slices/organization/components/project-flow.tsx
@@ -1,7 +1,8 @@
"use client";
import { useMemo, useRef, useState } from "react";
import { FileText, FolderKanban, Link2, Pencil, Plus, X } from "lucide-react";
-import { Handle, MarkerType, Position, type Edge, type NodeProps, type NodeChange } from "@xyflow/react";
+import { Handle, MarkerType, Position, type Edge, type NodeProps } from "@xyflow/react";
+import { useGraphProjection } from "@/components/shared/use-graph-projection";
import { GraphCanvas } from "@/components/shared/graph-canvas";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -9,7 +10,12 @@ import { Input } from "@/components/ui/input";
import { cn } from "@/lib/utils";
import { emptyOrganizationFlow, type OrganizationFlowAction } from "@/lib/contracts/organization-flow";
import type { OrganizationUnit } from "@/lib/contracts/organization";
-import { projectCanvasNodes, updateFlowProjection, type FlowProjection, type ProjectCanvasNode as FlowNode } from "../lib/flow-projection";
+import { type ProjectCanvasNode as FlowNode } from "../lib/flow-projection";
+import { projectCustomNodes, moveCustomNode, type CustomCanvasNode } from "@/components/shared/graph-custom-projection";
+import { GraphCustomControls } from "@/components/shared/graph-custom-controls";
+import { GraphCustomCard } from "@/components/shared/graph-custom-card";
+import { graphRoutedEdgeTypes } from "@/components/shared/graph-routed-edge";
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
import { ProjectFlowEditor, type FlowDraft } from "./project-flow-editor";
function ProjectCard({ data, selected }: NodeProps<FlowNode>) {
@@ -21,24 +27,32 @@ function ProjectCard({ data, selected }: NodeProps<FlowNode>) {
<Handle type="source" position={Position.Bottom} className="!size-3 !bg-muted-foreground"/>
</div>;
}
-const nodeTypes = { project: ProjectCard };
+const nodeTypes = { project: ProjectCard, customGroup: GraphCustomCard };
+type CanvasNode = FlowNode | CustomCanvasNode;
type Props = { unit: OrganizationUnit; onSave: (action: OrganizationFlowAction, data: Record<string, unknown>) => Promise<void> };
export function ProjectFlow({ unit, onSave }: Props) {
const flow = useMemo(() => unit.projectFlow ?? emptyOrganizationFlow(), [unit.projectFlow]);
const [query, setQuery] = useState(""), [selectedId, setSelectedId] = useState<string | null>(null), [focus, setFocus] = useState(false);
const [draft, setDraft] = useState<FlowDraft | null>(null), [error, setError] = useState(""), [busy, setBusy] = useState(false);
- const [projection, setProjection] = useState<FlowProjection>({ nodes: [] });
+ const groups = useMemo(() => flow.customNodes ?? [], [flow.customNodes]);
const pending = useRef(false);
- const selected = flow.nodes.find((node) => node.id === selectedId);
const visible = useMemo(() => {
const match = new Set(flow.nodes.filter((node) => focus && selectedId ? node.id === selectedId : `${node.title} ${node.summary} ${node.kind}`.toLowerCase().includes(query.toLowerCase())).map((node) => node.id));
const ids = new Set(match);
if (query || (focus && selectedId)) for (const edge of flow.edges) if (match.has(edge.source) || match.has(edge.target)) { ids.add(edge.source); ids.add(edge.target); }
return ids;
}, [flow, query, focus, selectedId]);
- const nodes = useMemo<FlowNode[]>(() => projectCanvasNodes(flow.nodes, projection).filter((node) => visible.has(node.id)).map((node) => ({ ...node, selected: node.id === selectedId })), [flow.nodes, projection, selectedId, visible]);
- const edges = useMemo<Edge[]>(() => flow.edges.filter((edge) => visible.has(edge.source) && visible.has(edge.target)).map((edge) => ({ ...edge, type: "smoothstep", markerEnd: { type: MarkerType.ArrowClosed, color: "var(--muted-foreground)" }, style: { stroke: "var(--muted-foreground)" }, labelStyle: { fill: "var(--foreground)", fontSize: 11 }, labelBgStyle: { fill: "var(--background)" } })), [flow.edges, visible]);
+ const mapped = useMemo(() => {
+ const base: FlowNode[] = flow.nodes.map((item) => ({ id: item.id, type: "project", position: item.position, data: { item } }));
+ const lines: Edge[] = flow.edges.map((edge) => ({ ...edge, type: "routed", markerEnd: { type: MarkerType.ArrowClosed, width: 20, height: 20, color: "var(--muted-foreground)" }, style: { stroke: "var(--muted-foreground)" } }));
+ const result = projectCustomNodes(base, lines, groups, []);
+ const ids = new Set(result.nodes.filter((node) => node.type === "customGroup" ? node.data.group.nodeIds.some((id) => visible.has(id)) : visible.has(node.id)).map((node) => node.id));
+ return { nodes: result.nodes.filter((node) => ids.has(node.id)), edges: result.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target)) };
+ }, [flow.nodes, flow.edges, groups, visible]);
+ const { nodes, edges, onNodesChange, onEdgesChange, reset } = useGraphProjection<CanvasNode, Edge>(mapped);
+ const selectedIds = nodes.filter((node) => node.selected).map((node) => node.id);
+ const selected = selectedIds.length <= 1 ? flow.nodes.find((node) => node.id === selectedId) : undefined;
const save = async (action: OrganizationFlowAction, data: Record<string, unknown>) => {
if (pending.current) throw new Error("A change is still saving. Try again after it completes.");
pending.current = true; setBusy(true); setError("");
@@ -46,8 +60,14 @@ export function ProjectFlow({ unit, onSave }: Props) {
catch (cause) { const message = cause instanceof Error ? cause.message : "Save failed"; setError(message); throw cause; }
finally { pending.current = false; setBusy(false); }
};
- const changes = (updates: NodeChange<FlowNode>[]) => setProjection((prev) => updateFlowProjection(flow.nodes, prev, updates));
- const quickSave = (action: OrganizationFlowAction, data: Record<string, unknown>) => { void save(action, data).catch(() => setProjection({ nodes: [] })); };
+ const quickSave = (action: OrganizationFlowAction, data: Record<string, unknown>) => { if (pending.current) return; void save(action, data).catch(() => reset()); };
+ const changeGroups = (customNodes: GraphCustomNode[]) => { quickSave("flow_custom_nodes", { customNodes }); setSelectedId(null); };
+ const move = (items: CanvasNode[]) => {
+ let moved = flow.nodes;
+ for (const item of items) { const group = groups.find((row) => row.id === item.id); moved = group ? moveCustomNode(moved, group, item.position) : moved.map((node) => node.id === item.id ? { ...node, position: item.position } : node); }
+ const positions = moved.filter((node, i) => node.position !== flow.nodes[i].position).map(({ id, position }) => ({ id, position }));
+ if (positions.length) quickSave("flow_nodes_move", { positions });
+ };
return <div data-slot="organization-project-flow" className="flex h-full min-h-0 flex-col">
<div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-2">
<div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{flow.title}</div><p className="text-[10px] text-muted-foreground">{flow.nodes.length} nodes · {flow.edges.length} connections · {busy ? "Saving…" : "Stored in this organization"}</p></div>
@@ -56,15 +76,16 @@ export function ProjectFlow({ unit, onSave }: Props) {
<Button size="sm" disabled={busy} onClick={() => setDraft({ kind: "node" })}><Plus className="mr-1 size-3.5"/>Node</Button>
<div className="flex w-full items-center gap-2"><Input aria-label="Search project flow" className="h-8 min-w-0 flex-1" placeholder="Search projects, activities, or notes…" value={query} onChange={(e) => setQuery(e.target.value)}/><Button size="sm" variant={focus ? "secondary" : "outline"} disabled={!selected} onClick={() => setFocus(!focus)}>Focus</Button></div>
</div>
+ <GraphCustomControls groups={groups} selectedIds={selectedIds} nodeIds={flow.nodes.map((node) => node.id)} onChange={changeGroups} disabled={busy}/>
{error ? <div role="alert" className="shrink-0 border-b px-3 py-2 text-xs text-destructive">{error} Refresh the organization before retrying a conflicting change.</div> : null}
<div className="relative min-h-0 flex-1">
- {flow.nodes.length ? <GraphCanvas<FlowNode, Edge>
- ariaLabel="Organization project flow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes}
- nodesDraggable={!busy} nodesConnectable={!busy} deleteKeyCode={null} onNodesChange={changes}
- onNodeClick={(_, node) => setSelectedId(node.id)} onNodeDoubleClick={(_, node) => setDraft({ kind: "node", node: node.data.item })}
+ {flow.nodes.length ? <GraphCanvas<CanvasNode, Edge>
+ ariaLabel="Organization project flow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}
+ nodesDraggable={!busy} nodesConnectable={!busy} deleteKeyCode={null} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange}
+ onNodeClick={(event, node) => { if (!event.ctrlKey && !event.metaKey) setSelectedId(node.type === "customGroup" ? null : node.id); }} onNodeDoubleClick={(_, node) => { if (node.type === "customGroup") changeGroups(groups.map((group) => group.id === node.id ? { ...group, collapsed: false } : group)); else setDraft({ kind: "node", node: (node as FlowNode).data.item }); }}
onPaneClick={() => { setSelectedId(null); setFocus(false); }}
- onNodeDragStop={(_, node) => quickSave("flow_node_upsert", { node: { id: node.id, position: node.position } })}
- onConnect={(connection) => quickSave("flow_edge_upsert", { edge: { source: connection.source, target: connection.target, label: "" } })}
+ onNodeDragStop={(_, node, items) => move(items.length ? items : [node])} onSelectionDragStop={(_, items) => move(items)}
+ onConnect={(connection) => { if (flow.nodes.some((n) => n.id === connection.source) && flow.nodes.some((n) => n.id === connection.target)) quickSave("flow_edge_upsert", { edge: { source: connection.source, target: connection.target, label: "" } }); }}
onEdgeClick={(_, edge) => setDraft({ kind: "edge", edge: flow.edges.find((item) => item.id === edge.id) })}
compactFitNodeIds={selected ? [selected.id] : nodes.slice(0, 2).map((node) => node.id)}
/> : <div className="grid h-full place-items-center p-6"><div className="max-w-sm text-center"><FolderKanban className="mx-auto mb-3 size-7 text-muted-foreground"/><h3 className="font-medium">Project flow inside {unit.name}</h3><p className="mt-2 text-sm text-muted-foreground">Add projects, activities, notes and connections here. The organization overview stays compact.</p><Button className="mt-4" onClick={() => setDraft({ kind: "node" })}>Add first node</Button></div></div>}
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index 1fa0e605..aad96ff1 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -1,4 +1,5 @@
"use client";
+import { pruneGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";
import { useEffect, useMemo, useState } from "react";
import { Activity, Copy, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
@@ -69,7 +70,7 @@ export default function WorkflowsApp(props: AppProps) {
const remove = () => graph && wrap(async () => { await deleteGraph(graph); setSelected(null); setRun(null); const list = await listGraphs(); setGraphs(list); setGraph(list[0] ? await getGraph(list[0].id) : null); setDirty(false); });
const execute = () => graph && wrap(async () => { const saved = await saveCurrent(); setRun(await runGraph(saved.id)); setPanel("run"); if (overlayPane) setDetailsOpen(true); });
const updateNode = (next: WorkflowGraphNode) => graph && mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === next.id ? next : item) });
- const deleteNodes = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, nodes: graph.nodes.filter((item) => !removed.has(item.id)), edges: graph.edges.filter((edge) => !removed.has(edge.source) && !removed.has(edge.target)) }); if (selected && removed.has(selected)) setSelected(null); };
+ const deleteNodes = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, nodes: graph.nodes.filter((item) => !removed.has(item.id)), edges: graph.edges.filter((edge) => !removed.has(edge.source) && !removed.has(edge.target)), metadata: { ...graph.metadata, ...(graph.metadata.customNodes ? { customNodes: pruneGraphCustomNodes(graph.metadata.customNodes, new Set(graph.nodes.filter((n) => !removed.has(n.id)).map((n) => n.id))) } : {}) } }); if (selected && removed.has(selected)) setSelected(null); };
const deleteEdges = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, edges: graph.edges.filter((edge) => !removed.has(edge.id)) }); };
const addNode = (type: WorkflowGraphNodeType, defaults: Record<string, unknown>) => { if (!graph) return; const id = `${type}-${crypto.randomUUID().slice(0, 8)}`; const next: WorkflowGraphNode = { id, name: type.replaceAll("_", " ").replace(/\b\w/g, (char) => char.toUpperCase()), type, position: { x: 220 + graph.nodes.length * 36, y: 240 + (graph.nodes.length % 4) * 110 }, config: structuredClone(defaults) }; mutate({ ...graph, nodes: [...graph.nodes, next] }); chooseNode(id); };
const connect = (source: string, target: string, sourceHandle?: string) => { if (!graph || graph.edges.some((edge) => edge.source === source && edge.target === target && edge.sourceHandle === sourceHandle)) return; mutate({ ...graph, edges: [...graph.edges, { id: `edge-${crypto.randomUUID().slice(0, 8)}`, source, target, ...(sourceHandle ? { sourceHandle } : {}) }] }); };
@@ -109,7 +110,7 @@ export default function WorkflowsApp(props: AppProps) {
<div className={`grid h-full min-h-0 min-w-0 ${showLibraryPanel ? "grid-cols-[300px_minmax(0,1fr)] @min-[1200px]:grid-cols-[340px_minmax(0,1fr)]" : "grid-cols-1"}`}>
{showLibraryPanel ? <aside className="min-h-0 min-w-0 border-r">{library}</aside> : null}
<main className="flex min-h-0 min-w-0 overflow-hidden">
- {libraryMode === "automations" ? graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 min-w-0 shrink-0 flex-wrap items-center gap-1.5 border-b px-2 py-1 @min-[520px]:flex-nowrap @min-[520px]:gap-2"><label className="flex shrink-0 items-center gap-1.5 text-[10px] font-medium"><Switch checked={graph.status === "active"} disabled={graph.status === "archived"} onCheckedChange={(checked) => mutate({ ...graph, status: checked ? "active" : "draft" })}/><span>Active</span></label><select aria-label="Workflow lifecycle" className="h-7 min-w-0 max-w-24 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="hidden min-w-0 truncate text-[10px] text-muted-foreground @min-[900px]:inline">Drag output → input. V Select · H Pan · +/- Zoom · F Fit · Space temporary pan.</span>{message ? <span className="w-full min-w-0 truncate text-[11px] text-muted-foreground @min-[520px]:ml-auto @min-[520px]:w-auto @min-[520px]:max-w-72">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} nodeStates={runStates} edgeStates={runEdgeStates} onOpen={(id) => void openNode(id)} onConnect={connect} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Create or select an automation.</div>
+ {libraryMode === "automations" ? graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 min-w-0 shrink-0 flex-wrap items-center gap-1.5 border-b px-2 py-1 @min-[520px]:flex-nowrap @min-[520px]:gap-2"><label className="flex shrink-0 items-center gap-1.5 text-[10px] font-medium"><Switch checked={graph.status === "active"} disabled={graph.status === "archived"} onCheckedChange={(checked) => mutate({ ...graph, status: checked ? "active" : "draft" })}/><span>Active</span></label><select aria-label="Workflow lifecycle" className="h-7 min-w-0 max-w-24 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="hidden min-w-0 truncate text-[10px] text-muted-foreground @min-[900px]:inline">Drag output → input. V Select · H Pan · +/- Zoom · F Fit · Space temporary pan.</span>{message ? <span className="w-full min-w-0 truncate text-[11px] text-muted-foreground @min-[520px]:ml-auto @min-[520px]:w-auto @min-[520px]:max-w-72">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} onCustomNodes={(customNodes) => mutate({ ...graph, metadata: { ...graph.metadata, customNodes } })} onMoveMany={(nodes) => mutate({ ...graph, nodes })} nodeStates={runStates} edgeStates={runEdgeStates} onOpen={(id) => void openNode(id)} onConnect={connect} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Create or select an automation.</div>
: sessionView ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 shrink-0 items-center gap-2 border-b px-3 text-[11px] text-muted-foreground [@media(max-height:520px)]:hidden"><span className="font-medium text-foreground">{sessionView.session.label}</span><span>read-only</span><span>·</span><span>{sessionView.steps.length} steps</span><span>·</span><span>{sessionView.shownEvents}/{sessionView.totalEvents} actions</span>{message ? <span className="ml-auto truncate">{message}</span> : null}</div><div className="min-h-0 min-w-0 flex-1 overflow-hidden"><WorkflowCanvas key={sessionView.graph.revision} graph={sessionView.graph} selectedId={sessionSelected} onSelect={chooseSessionNode} onConnect={() => undefined} onMove={() => undefined} readOnly/></div></div> : <div className="flex h-full min-w-0 flex-1 items-center justify-center px-4 text-center text-sm text-muted-foreground">Select a session to inspect its semantic execution flow.</div>}
{showDetailsPanel ? <aside className="w-[320px] shrink-0 border-l @min-[1200px]:w-[360px]">{details}</aside> : null}
</main>
diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsx
index d06beeae..5998a644 100644
--- a/frontend/slices/workflows/components/workflow-canvas.tsx
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -1,11 +1,17 @@
"use client";
-import { useEffect, useMemo } from "react";
+import { useMemo } from "react";
import {
- Handle, MarkerType, Position, useEdgesState, useNodesState,
+ Handle, MarkerType, Position,
type Connection, type Edge, type Node, type NodeProps,
} from "@xyflow/react";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeState, WorkflowGraphRunEdgeState } from "@/lib/contracts/workflow-graph";
+import { useGraphProjection } from "@/components/shared/use-graph-projection";
import { GraphCanvas } from "@/components/shared/graph-canvas";
+import { GraphCustomControls } from "@/components/shared/graph-custom-controls";
+import { GraphCustomCard } from "@/components/shared/graph-custom-card";
+import { projectCustomNodes, moveCustomNode, type CustomCanvasNode } from "@/components/shared/graph-custom-projection";
+import { graphRoutedEdgeTypes } from "@/components/shared/graph-routed-edge";
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
import { cn } from "@/lib/utils";
interface WorkflowNodeData extends Record<string, unknown> { node: WorkflowGraphNode; state?: WorkflowGraphNodeState }
@@ -36,22 +42,40 @@ function WorkflowNodeCard({data,selected}:NodeProps<FlowNode>){
{canError(node)?<Handle type="source" position={Position.Bottom} id="error" className="!size-3 !border-2 !border-background !bg-destructive"/>:null}
</div>;
}
-const nodeTypes={workflow:WorkflowNodeCard};
+const nodeTypes={workflow:WorkflowNodeCard, customGroup:GraphCustomCard};
+type CanvasNode = FlowNode | CustomCanvasNode;
function toNodes(graph:WorkflowGraph,selectedId:string|null,nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>):FlowNode[]{return graph.nodes.map((node)=>{const metrics=nodeMetrics(node);return{id:node.id,type:"workflow",position:node.position,width:metrics.width,height:metrics.height,selected:node.id===selectedId,data:{node,state:nodeStates?.get(node.id)}};});}
function edgeVisual(edge:WorkflowGraph["edges"][number],state:WorkflowGraphRunEdgeState|undefined,nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>){
const running=nodeStates?.get(edge.source)==="running"||nodeStates?.get(edge.target)==="running",error=edge.sourceHandle==="error",branch=Boolean(edge.sourceHandle&&edge.sourceHandle!=="output"),disabled=edge.disabled||state==="disabled";
- const stroke=error?"var(--destructive)":running?"var(--accent)":state==="enabled"?"var(--success)":"var(--sep-strong)";
+ const stroke=error?"var(--destructive)":running?"var(--accent)":state==="enabled"?"var(--success)":"var(--muted-foreground)";
const strokeDasharray=disabled?"2 6":edge.style==="dashed"?"7 5":edge.style==="solid"?undefined:branch?"7 5":undefined;
const opacity = disabled ? 0.24 : state === "pending" ? 0.55 : 1;
return {animated:running&&!disabled,style:{stroke,strokeWidth:running?2.5:state==="enabled"?2:1.5,opacity,strokeDasharray},markerEnd:{type:MarkerType.ArrowClosed,width:18,height:18,color:stroke}};
}
-function toEdges(graph:WorkflowGraph,nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>,edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>):FlowEdge[]{return graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,sourceHandle:edge.sourceHandle??"output",targetHandle:"input",type:"smoothstep",...edgeVisual(edge,edgeStates?.get(edge.id),nodeStates)}));}
+function toEdges(graph:WorkflowGraph,nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>,edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>):FlowEdge[]{return graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,sourceHandle:edge.sourceHandle??"output",targetHandle:edge.targetHandle??"input",type:"routed",...edgeVisual(edge,edgeStates?.get(edge.id),nodeStates)}));}
function minimapColor(node:FlowNode){const state=node.data.state;if(state==="running")return"var(--accent)";if(state==="failed")return"var(--destructive)";if(state==="completed")return"var(--success)";if(state==="skipped"||state==="blocked")return"var(--text-dim)";return"var(--info)";}
-export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onConnect,nodeStates,edgeStates,onOpen,onDeleteNodes,onDeleteEdges,onTidy,readOnly=false}:{graph:WorkflowGraph;selectedId:string|null;onSelect:(id:string|null)=>void;onMove:(id:string,position:{x:number;y:number})=>void;onConnect:(source:string,target:string,sourceHandle?:string)=>void;nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>;edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>;onOpen?:(id:string)=>void;onDeleteNodes?:(ids:string[])=>void;onDeleteEdges?:(ids:string[])=>void;onTidy?:()=>void;readOnly?:boolean;}){
- const mappedNodes=useMemo(()=>toNodes(graph,selectedId,nodeStates),[graph,nodeStates,selectedId]),mappedEdges=useMemo(()=>toEdges(graph,nodeStates,edgeStates),[edgeStates,graph,nodeStates]);
- const compactFitNodeIds=useMemo(()=>{if(readOnly)return graph.nodes.slice(0,9).map((node)=>node.id);const triggers=graph.nodes.filter((node)=>["manual","schedule","webhook"].includes(node.type)).map((node)=>node.id);return (triggers.length?triggers:[graph.nodes[0]?.id]).filter((id):id is string=>Boolean(id)).slice(0,2);},[graph.nodes,readOnly]);
- const[nodes,setNodes,onNodesChange]=useNodesState<FlowNode>(mappedNodes),[edges,setEdges,onEdgesChange]=useEdgesState<FlowEdge>(mappedEdges);useEffect(()=>setNodes(mappedNodes),[mappedNodes,setNodes]);useEffect(()=>setEdges(mappedEdges),[mappedEdges,setEdges]);
- const connect=(connection:Connection)=>{if(!connection.source||!connection.target||connection.source===connection.target)return;const handle=connection.sourceHandle&&connection.sourceHandle!=="output"?connection.sourceHandle:undefined;onConnect(connection.source,connection.target,handle);};
- return <GraphCanvas<FlowNode,FlowEdge> ariaLabel="Workflow canvas" showMinimap={!readOnly} nodes={nodes} edges={edges} nodeTypes={nodeTypes} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={readOnly?undefined:connect} onPaneClick={()=>onSelect(null)} onNodeClick={(_,item)=>onSelect(item.id)} onEdgeClick={readOnly?undefined:(_,edge)=>onSelect(edge.source)} onNodeDoubleClick={(_,item)=>{const node=item.data.node;if((readOnly||node.type==="project"||node.type==="folder")&&onOpen)onOpen(node.id);}} onNodeDragStop={(_,item)=>onMove(item.id,item.position)} onNodesDelete={readOnly?undefined:(items)=>onDeleteNodes?.(items.map((item)=>item.id))} onEdgesDelete={readOnly?undefined:(items)=>onDeleteEdges?.(items.map((item)=>item.id))} isValidConnection={(connection)=>Boolean(connection.source&&connection.target&&connection.source!==connection.target&&!graph.edges.some((edge)=>edge.source===connection.source&&edge.target===connection.target&&(edge.sourceHandle??undefined)===(connection.sourceHandle==="output"?undefined:connection.sourceHandle??undefined)))} nodesDraggable={!readOnly} nodesConnectable={!readOnly} edgesReconnectable={false} deleteKeyCode={readOnly?null:["Backspace","Delete"]} onTidy={onTidy} snapToGrid snapGrid={[12,12]} defaultEdgeOptions={{type:"smoothstep",markerEnd:{type:MarkerType.ArrowClosed}}} miniMapNodeColor={(node)=>minimapColor(node as FlowNode)} miniMapNodeStrokeColor={(node)=>node.selected?"var(--accent)":"var(--border)"} compactFitNodeIds={compactFitNodeIds} compactFitMaxZoom={readOnly?0.72:0.9}/>
+export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onMoveMany,onCustomNodes,onConnect,nodeStates,edgeStates,onOpen,onDeleteNodes,onDeleteEdges,onTidy,readOnly=false}:{graph:WorkflowGraph;selectedId:string|null;onSelect:(id:string|null)=>void;onMove:(id:string,position:{x:number;y:number})=>void;onMoveMany?:(nodes:WorkflowGraphNode[])=>void;onCustomNodes?:(groups:GraphCustomNode[])=>void;onConnect:(source:string,target:string,sourceHandle?:string)=>void;nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>;edgeStates?:ReadonlyMap<string,WorkflowGraphRunEdgeState>;onOpen?:(id:string)=>void;onDeleteNodes?:(ids:string[])=>void;onDeleteEdges?:(ids:string[])=>void;onTidy?:()=>void;readOnly?:boolean;}){
+ const groups=useMemo(()=>graph.metadata.customNodes??[],[graph.metadata.customNodes]);
+ const mapped=useMemo(()=>projectCustomNodes(toNodes(graph,null,nodeStates),toEdges(graph,nodeStates,edgeStates),groups,selectedId?[selectedId]:[]),[graph,nodeStates,edgeStates,groups,selectedId]);
+ const {nodes,edges,onNodesChange,onEdgesChange}=useGraphProjection<CanvasNode,FlowEdge>(mapped);
+ const selectedIds=nodes.filter((node)=>node.selected).map((node)=>node.id);
+ const changeGroups=(next:GraphCustomNode[])=>{onCustomNodes?.(next);onSelect(null);};
+ const move=(items:CanvasNode[])=>{let next=graph.nodes;for(const item of items){const group=groups.find((g)=>g.id===item.id);next=group?moveCustomNode(next,group,item.position):next.map((n)=>n.id===item.id?{...n,position:item.position}:n);}if(onMoveMany)onMoveMany(next);else for(const item of items)onMove(item.id,item.position);};
+ const connect=(connection:Connection)=>{if(!graph.nodes.some((n)=>n.id===connection.source)||!graph.nodes.some((n)=>n.id===connection.target)||connection.source===connection.target)return;const handle=connection.sourceHandle&&connection.sourceHandle!=="output"?connection.sourceHandle:undefined;onConnect(connection.source!,connection.target!,handle);};
+ const compactIds=readOnly?nodes.slice(0,9).map((n)=>n.id):nodes.slice(0,2).map((n)=>n.id);
+ return <div className="flex h-full min-h-0 flex-col">
+ {!readOnly&&onCustomNodes?<GraphCustomControls groups={groups} selectedIds={selectedIds} nodeIds={graph.nodes.map((n)=>n.id)} onChange={changeGroups}/>:null}
+ <div className="min-h-0 flex-1"><GraphCanvas<CanvasNode,FlowEdge> ariaLabel="Workflow canvas" showMinimap={!readOnly} nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}
+ onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={readOnly?undefined:connect}
+ onPaneClick={()=>{onSelect(null);}}
+ onNodeClick={(event,item)=>{if(event.ctrlKey||event.metaKey)return;onSelect(item.type==="customGroup"?null:item.id);}}
+ onEdgeClick={readOnly?undefined:(_,edge)=>{if(graph.nodes.some((n)=>n.id===edge.source))onSelect(edge.source);}}
+ onNodeDoubleClick={(_,item)=>{if(item.type==="customGroup"){if(!readOnly)changeGroups(groups.map((g)=>g.id===item.id?{...g,collapsed:false}:g));return;}const node=(item as FlowNode).data.node;if((readOnly||node.type==="project"||node.type==="folder")&&onOpen)onOpen(node.id);}}
+ onNodeDragStop={(_,item,items)=>move(items.length?items:[item])} onSelectionDragStop={(_,items)=>move(items)}
+ onNodesDelete={readOnly?undefined:(items)=>onDeleteNodes?.(items.filter((n)=>n.type!=="customGroup").map((n)=>n.id))}
+ onEdgesDelete={readOnly?undefined:(items)=>onDeleteEdges?.(items.map((item)=>item.id))}
+ nodesDraggable={!readOnly} nodesConnectable={!readOnly} edgesReconnectable={false} deleteKeyCode={readOnly?null:["Backspace","Delete"]} onTidy={onTidy} snapToGrid snapGrid={[12,12]}
+ miniMapNodeColor={(node)=>node.type==="customGroup"?"var(--primary)":minimapColor(node as FlowNode)} compactFitNodeIds={compactIds} compactFitMaxZoom={readOnly?0.72:0.9}/></div>
+ </div>;
}
diff --git a/lib/agent/organization-flow-mutations.ts b/lib/agent/organization-flow-mutations.ts
index 49ac03d3..3d956629 100644
--- a/lib/agent/organization-flow-mutations.ts
+++ b/lib/agent/organization-flow-mutations.ts
@@ -1,3 +1,4 @@
+import { pruneGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";
import { randomUUID } from "node:crypto";
import { emptyOrganizationFlow, type OrganizationFlowAction, type OrganizationProjectFlow } from "@/lib/contracts/organization-flow";
import { flowId, flowRecord, parseFlowEdge, parseFlowNode, parseOrganizationFlow } from "./organization-flow-schema";
@@ -6,6 +7,17 @@ import { flowId, flowRecord, parseFlowEdge, parseFlowNode, parseOrganizationFlow
export function changeOrganizationFlow(current: OrganizationProjectFlow | undefined, action: OrganizationFlowAction, data: Record<string, unknown>): OrganizationProjectFlow {
const flow = structuredClone(current ?? emptyOrganizationFlow());
switch (action) {
+ case "flow_custom_nodes": { if (!Array.isArray(data.customNodes)) throw new Error("customNodes array is required"); return parseOrganizationFlow({ ...flow, customNodes: data.customNodes }); }
+ case "flow_nodes_move": {
+ if (!Array.isArray(data.positions) || data.positions.length < 1 || data.positions.length > 200) throw new Error("positions requires 1-200 nodes");
+ const moved = new Set<string>();
+ for (const value of data.positions) {
+ const row = flowRecord(value), id = flowId(row.id), index = flow.nodes.findIndex((node) => node.id === id);
+ if (index < 0 || moved.has(id)) throw new Error("move node missing or duplicated");
+ moved.add(id); flow.nodes[index] = parseFlowNode({ ...flow.nodes[index], position: row.position });
+ }
+ break;
+ }
case "flow_replace": return parseOrganizationFlow(data.flow);
case "flow_update": return parseOrganizationFlow({ ...flow, ...("title" in data ? { title: data.title } : {}), ...("notes" in data ? { notes: data.notes } : {}) });
case "flow_node_upsert": {
@@ -20,6 +32,7 @@ export function changeOrganizationFlow(current: OrganizationProjectFlow | undefi
const id = flowId(data.id);
if (!flow.nodes.some((node) => node.id === id)) throw new Error("flow node not found in this unit");
flow.nodes = flow.nodes.filter((node) => node.id !== id);
+ if (flow.customNodes) flow.customNodes = pruneGraphCustomNodes(flow.customNodes, new Set(flow.nodes.map((node) => node.id)));
flow.edges = flow.edges.filter((edge) => edge.source !== id && edge.target !== id);
break;
}
diff --git a/lib/agent/organization-flow-schema.ts b/lib/agent/organization-flow-schema.ts
index 41e2521a..99622803 100644
--- a/lib/agent/organization-flow-schema.ts
+++ b/lib/agent/organization-flow-schema.ts
@@ -1,3 +1,4 @@
+import { parseGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";
import { ORGANIZATION_FLOW_KINDS, ORGANIZATION_FLOW_STATUSES, type OrganizationFlowNode, type OrganizationFlowEdge, type OrganizationProjectFlow } from "@/lib/contracts/organization-flow";
export function flowRecord(value: unknown): Record<string, unknown> {
@@ -44,5 +45,5 @@ export function parseOrganizationFlow(value: unknown): OrganizationProjectFlow {
const ids = new Set(nodes.map((node) => node.id));
if (ids.size !== nodes.length || new Set(edges.map((edge) => edge.id)).size !== edges.length) throw new Error("project flow ids must be unique");
if (edges.some((edge) => !ids.has(edge.source) || !ids.has(edge.target))) throw new Error("flow edge endpoint not found in this unit");
- return { version: 1, title: text(row.title, "flow title", 160, true).trim(), notes: text(row.notes, "flow notes", 64000), nodes, edges };
+ return { version: 1, title: text(row.title, "flow title", 160, true).trim(), notes: text(row.notes, "flow notes", 64000), nodes, edges, ...(row.customNodes !== undefined ? { customNodes: parseGraphCustomNodes(row.customNodes, ids) } : {}) };
}
diff --git a/lib/agent/organization-flow.test.ts b/lib/agent/organization-flow.test.ts
index 473c3e63..c87be1a3 100644
--- a/lib/agent/organization-flow.test.ts
+++ b/lib/agent/organization-flow.test.ts
@@ -69,7 +69,7 @@ describe("organization project flow persistence", () => {
expect(output.chart.units[0].projectFlow?.nodes[0].id).toBe("via-mcp");
const reread = await read.run({ runtime: false }, { principal: "test" } as never) as { chart: typeof chart };
expect(reread.chart.revision).toBe(output.chart.revision);
- expect(ORGANIZATION_FLOW_ACTIONS).toHaveLength(6);
+ expect(ORGANIZATION_FLOW_ACTIONS).toEqual(expect.arrayContaining(["flow_custom_nodes", "flow_nodes_move", "flow_update", "flow_node_upsert", "flow_node_delete", "flow_edge_upsert", "flow_edge_delete", "flow_replace"]));
});
});
diff --git a/lib/contracts/graph-custom-nodes.ts b/lib/contracts/graph-custom-nodes.ts
new file mode 100644
index 00000000..e54d48c0
--- /dev/null
+++ b/lib/contracts/graph-custom-nodes.ts
@@ -0,0 +1,26 @@
+/** Presentation-only custom nodes. Members retain their original execution identity. */
+export type GraphCustomNode = { id: string; name: string; nodeIds: string[]; collapsed: boolean };
+
+export function parseGraphCustomNodes(value: unknown, nodeIds: ReadonlySet<string>): GraphCustomNode[] {
+ if (value === undefined) return [];
+ if (!Array.isArray(value) || value.length > 100) throw new Error("custom nodes must be an array of at most 100 groups");
+ const groupIds = new Set<string>(), assigned = new Set<string>();
+ return value.map((raw) => {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("invalid custom node");
+ const row = raw as Record<string, unknown>;
+ if (typeof row.id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/.test(row.id) || groupIds.has(row.id) || nodeIds.has(row.id)) throw new Error("custom node id is invalid or duplicated");
+ if (typeof row.name !== "string" || !row.name.trim() || row.name.length > 120) throw new Error("custom node name is required (120 characters maximum)");
+ if (typeof row.collapsed !== "boolean" || !Array.isArray(row.nodeIds) || !row.nodeIds.length || row.nodeIds.length > 200) throw new Error("custom node requires members and a collapsed flag");
+ groupIds.add(row.id);
+ const members = row.nodeIds.map((id) => {
+ if (typeof id !== "string" || !nodeIds.has(id) || assigned.has(id)) throw new Error("custom node members must exist, be unique and belong to only one group");
+ assigned.add(id); return id;
+ });
+ return { id: row.id, name: row.name.trim(), nodeIds: members, collapsed: row.collapsed };
+ });
+}
+
+/** Explicit node deletion trims membership; it never deletes surviving members. */
+export function pruneGraphCustomNodes(groups: GraphCustomNode[] | undefined, ids: ReadonlySet<string>): GraphCustomNode[] {
+ return (groups ?? []).map((group) => ({ ...group, nodeIds: group.nodeIds.filter((id) => ids.has(id)) })).filter((group) => group.nodeIds.length > 0);
+}
diff --git a/lib/contracts/organization-flow.ts b/lib/contracts/organization-flow.ts
index cc7ebab0..a9fee1e8 100644
--- a/lib/contracts/organization-flow.ts
+++ b/lib/contracts/organization-flow.ts
@@ -1,7 +1,8 @@
+import type { GraphCustomNode } from "./graph-custom-nodes";
/** Organization context graph, not an executable automation workflow. */
export const ORGANIZATION_FLOW_KINDS = ["project", "activity", "group", "note"] as const;
export const ORGANIZATION_FLOW_STATUSES = ["unconfirmed", "planned", "active", "blocked", "done"] as const;
-export const ORGANIZATION_FLOW_ACTIONS = ["flow_update", "flow_replace", "flow_node_upsert", "flow_node_delete", "flow_edge_upsert", "flow_edge_delete"] as const;
+export const ORGANIZATION_FLOW_ACTIONS = ["flow_custom_nodes", "flow_nodes_move", "flow_update", "flow_replace", "flow_node_upsert", "flow_node_delete", "flow_edge_upsert", "flow_edge_delete"] as const;
export type OrganizationFlowAction = typeof ORGANIZATION_FLOW_ACTIONS[number];
export type OrganizationFlowNode = {
id: string;
@@ -16,6 +17,7 @@ export type OrganizationFlowNode = {
};
export type OrganizationFlowEdge = { id: string; source: string; target: string; label: string };
export type OrganizationProjectFlow = {
+ customNodes?: GraphCustomNode[];
version: 1;
title: string;
notes: string;
diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.ts
index d677d37d..3cd718ca 100644
--- a/lib/contracts/workflow-graph.ts
+++ b/lib/contracts/workflow-graph.ts
@@ -1,3 +1,4 @@
+import type { GraphCustomNode } from "./graph-custom-nodes";
export const WORKFLOW_GRAPH_NODE_TYPES = [
"manual", "schedule", "webhook", "tool", "project_function", "project_mcp", "integration", "script", "agent", "subflow",
"condition", "switch", "merge", "batch", "loop", "wait", "cache", "memory", "session", "directory", "project", "folder", "skill", "knowledge", "output",
@@ -27,6 +28,7 @@ export type WorkflowGraphEdge = {
};
export type WorkflowGraphMetadata = {
+ customNodes?: GraphCustomNode[];
intent?: string;
normalizedIntent?: string;
project?: string;
diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.ts
index 46532977..5e33c9f4 100644
--- a/lib/mcp/tools-flows.ts
+++ b/lib/mcp/tools-flows.ts
@@ -61,7 +61,7 @@ export const FLOW_TOOLS: McpTool[] = [
return manageProjectFlow(catalog.project.path, { action: a.action, id, flow: a.definition, revision: str(a, "revision") });
} },
{ name: "workflow_graph", title: "Workflow Graph", scope: "exec", limit: { key: "workflow.graph", max: 20, windowMs: 60_000 },
- description: "Private workflow graph CRUD/run plus history, versions, templates, catalog and variable references. Definitions reject embedded secrets.",
+ description: "Private workflow graph CRUD/run plus history, versions, templates, catalog and variable references. Definitions reject embedded secrets. metadata.customNodes supports named collapsible groups [{id,name,nodeIds,collapsed}]; original nodes/edges and execution stay unchanged. Update with the current revision.",
chatgptDescription: "CRUD/run workflows; read node logs.",
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, audit: { action: "exec.run", targetArg: "id" },
inputSchema: S({ action: { type: "string", minLength: 1, maxLength: 32 }, id: { type: "string", maxLength: 96 }, data: { type: "object", additionalProperties: true }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["action"]),
diff --git a/lib/mcp/tools-organization.ts b/lib/mcp/tools-organization.ts
index d1d3537b..a10d9657 100644
--- a/lib/mcp/tools-organization.ts
+++ b/lib/mcp/tools-organization.ts
@@ -18,10 +18,10 @@ export const ORGANIZATION_TOOLS: McpTool[] = [
},
{
name: "organization_manage", title: "Manage Organization", scope: "write",
- description: "Create/update/delete organization units and seats with optimistic revision checks. Seat targets reference existing project agents, local sessions, or A2A peers; no credentials or hidden context are copied. Internal project flow actions: flow_update (data.unitId,title?,notes?), flow_replace (data.unitId,flow), flow_node_upsert (data.unitId,node), flow_node_delete (data.unitId,id), flow_edge_upsert (data.unitId,edge), flow_edge_delete (data.unitId,id). Node fields: id?,title,kind=project|activity|group|note,status=unconfirmed|planned|active|blocked|done,summary,notes,position={x,y},projectRef?. Edge fields: id?,source,target,label. Node deletion removes its incident edges. No action executes graph content.",
+ description: "Create/update/delete organization units and seats with optimistic revision checks. Seat targets reference existing project agents, local sessions, or A2A peers; no credentials or hidden context are copied. Custom grouping: flow_custom_nodes (data.unitId,customNodes=[{id,name,nodeIds,collapsed}]); flow_nodes_move (data.unitId,positions=[{id,position:{x,y}}]). Members and execution identities are preserved. Internal project flow actions: flow_update (data.unitId,title?,notes?), flow_replace (data.unitId,flow), flow_node_upsert (data.unitId,node), flow_node_delete (data.unitId,id), flow_edge_upsert (data.unitId,edge), flow_edge_delete (data.unitId,id). Node fields: id?,title,kind=project|activity|group|note,status=unconfirmed|planned|active|blocked|done,summary,notes,position={x,y},projectRef?. Edge fields: id?,source,target,label. Node deletion removes its incident edges. No action executes graph content.",
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }, audit: { action: "agent.organization", targetArg: "action" }, limit: { key: "organization.write", max: 30, windowMs: 60_000 },
chatgptDescription: "Edit units/seats or internal project flows. flow_* actions require data.unitId and current revision.",
- inputSchema: S({ action: { type: "string", enum: ["unit_upsert", "seat_upsert", "unit_delete", "seat_delete", "replace", ...ORGANIZATION_FLOW_ACTIONS] }, expected_revision: { type: "string" }, id: { type: "string" }, data: { type: "object", description: "For flow_* actions: unitId is required; flow_update uses title/notes; flow_replace uses flow={version:1,title,notes,nodes,edges}; flow_node_upsert uses node={id?,title,kind?,status?,summary?,notes?,position?:{x,y},projectRef?}; flow_edge_upsert uses edge={id?,source,target,label?}; deletes use id. Existing node/edge id permits partial update." } }, ["action", "expected_revision"]),
+ inputSchema: S({ action: { type: "string", enum: ["unit_upsert", "seat_upsert", "unit_delete", "seat_delete", "replace", ...ORGANIZATION_FLOW_ACTIONS] }, expected_revision: { type: "string" }, id: { type: "string" }, data: { type: "object", description: "For flow_* actions: unitId is required; flow_custom_nodes uses customNodes=[{id,name,nodeIds,collapsed}], flow_nodes_move uses positions=[{id,position:{x,y}}]; flow_update uses title/notes; flow_replace uses flow={version:1,title,notes,nodes,edges}; flow_node_upsert uses node={id?,title,kind?,status?,summary?,notes?,position?:{x,y},projectRef?}; flow_edge_upsert uses edge={id?,source,target,label?}; deletes use id. Existing node/edge id permits partial update." } }, ["action", "expected_revision"]),
run: async (a) => {
const action = str(a, "action"), revision = str(a, "expected_revision"), data = a.data && typeof a.data === "object" && !Array.isArray(a.data) ? a.data as Record<string, unknown> : {};
if (action === "unit_upsert") return { chart: await upsertOrganizationUnit(revision, data) };
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 739be7e7..f4d6d8d8 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -4,8 +4,8 @@ import type { McpTool } from "./tool-kit";
import { toolDescriptor, type McpToolProfile } from "./tool-contract";
export const MCP_SERVER_VERSION = "1.15.1";
-export const MCP_TOOLSET_VERSION = "2026.09.18.1";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-18T07:18:00+07:00";
+export const MCP_TOOLSET_VERSION = "2026.09.18.2";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-18T10:20:00+07:00";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/workflow/graph-schema.ts b/lib/workflow/graph-schema.ts
index 3c0486ca..e23fffb5 100644
--- a/lib/workflow/graph-schema.ts
+++ b/lib/workflow/graph-schema.ts
@@ -1,3 +1,4 @@
+import { parseGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";
import { WORKFLOW_GRAPH_NODE_TYPES, type WorkflowGraphEdge, type WorkflowGraphMetadata, type WorkflowGraphNode, type WorkflowGraphStatus } from "@/lib/contracts/workflow-graph";
const ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/;
@@ -80,11 +81,12 @@ function assertAcyclic(nodes: WorkflowGraphNode[], edges: WorkflowGraphEdge[]):
if (visited !== nodes.length) throw new Error("workflow graph contains a cycle; use the loop node with a subflow/body binding instead of cyclic edges");
}
-function parseMetadata(value: unknown): WorkflowGraphMetadata {
+function parseMetadata(value: unknown, nodeIds: ReadonlySet<string>): WorkflowGraphMetadata {
if (value === undefined) return {};
if (!graphObject(value)) throw new Error("workflow metadata must be an object");
assertWorkflowMetadataOnly(value);
const out: WorkflowGraphMetadata = {};
+ if (value.customNodes !== undefined) out.customNodes = parseGraphCustomNodes(value.customNodes, nodeIds);
for (const key of ["intent", "normalizedIntent", "project", "fingerprint", "folder", "errorWorkflowId", "timezone"] as const) if (typeof value[key] === "string" && value[key]) out[key] = String(value[key]).slice(0, 1000);
if (["user", "learned-from-session", "clone", "import", "template", "ai-assisted"].includes(String(value.provenance))) out.provenance = value.provenance as WorkflowGraphMetadata["provenance"];
if (Array.isArray(value.sourceDigests)) out.sourceDigests = value.sourceDigests.filter((item): item is string => typeof item === "string").slice(0, 32).map((item) => item.slice(0, 128));
@@ -109,7 +111,7 @@ export function parseWorkflowGraphDefinition(raw: unknown): WorkflowGraphDefinit
const triggerIds = new Set(nodes.filter((node) => ["manual", "schedule", "webhook"].includes(node.type)).map((node) => node.id));
if (activeEdges.some((edge) => triggerIds.has(edge.target))) throw new Error("trigger nodes must be workflow roots");
assertAcyclic(nodes, activeEdges);
- return { ...(typeof raw.id === "string" ? { id: raw.id } : {}), name: raw.name.trim(), description: raw.description, status: raw.status as WorkflowGraphStatus, inputs: structuredClone(raw.inputs), nodes, edges, metadata: parseMetadata(raw.metadata) };
+ return { ...(typeof raw.id === "string" ? { id: raw.id } : {}), name: raw.name.trim(), description: raw.description, status: raw.status as WorkflowGraphStatus, inputs: structuredClone(raw.inputs), nodes, edges, metadata: parseMetadata(raw.metadata, nodeIds) };
}
export function normalizeWorkflowIntent(value: string): string {
diff --git a/package.json b/package.json
index 3e810aab..7968189b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "mso",
- "version": "0.2.20",
+ "version": "0.2.21",
"private": true,
"engines": {
"node": ">=20.9",
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 3c827cf8..b64ab04c 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -42,7 +42,7 @@ U_cockpit="cockpit [project] | cockpit show [project] | cockpit search <query…
U_threads="threads list|show <id>|save <json>|rm <id>"
U_agent_sessions="agent-sessions list [limit]|show <id>|create [title]"
U_agents="agents list [current-session-id]|send <source-session-id> <target> <message> [message|task]|inbox <session-id> [--all]"
-U_org="org flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete <revision> <JSON with unitId|@file>|show|unit-upsert <revision> <JSON|@file>|seat-upsert <revision> <JSON|@file>|unit-delete <revision> <id>|seat-delete <revision> <id>|replace <revision> <JSON|@file>"
+U_org="org flow-custom-nodes|flow-nodes-move|flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete <revision> <JSON with unitId|@file>|show|unit-upsert <revision> <JSON|@file>|seat-upsert <revision> <JSON|@file>|unit-delete <revision> <id>|seat-delete <revision> <id>|replace <revision> <JSON|@file>"
U_a2a="a2a list|state|sessions|spawn <source-session> <objective> [title]|inbox <session>|discover <url>|add <url> [alias]|rm <target>|send <target> <message> [--wait]|stream <target> <message>|task <target> <taskId> [history]|cancel <target> <taskId>|handoff <target> <objective> [context] [--wait]|local sessions|local handoff <session> <objective>|local spawn <sourceSession> <objective> [title]|local inbox <session>|auth list [target]|auth add <target> [label] [bearer|api-key|oauth2]|auth use <target> <credentialId|none>|auth rm <credentialId>|inbound list|inbound create [label] [read|write|exec]|inbound rm <tokenId>"
U_memory="memory list|add <text>|rm <id>"
U_config="config show|set <json>|key <provider>|style <off|caveman|ponytail>|rm <provider>"
diff --git a/scripts/cli/organization.sh b/scripts/cli/organization.sh
index c6b19874..341cb2c7 100644
--- a/scripts/cli/organization.sh
+++ b/scripts/cli/organization.sh
@@ -14,7 +14,7 @@ run_org() {
show|list)
jget "/api/v1/organization"
;;
- flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete)
+ flow-custom-nodes|flow-nodes-move|flow-update|flow-replace|flow-node-upsert|flow-node-delete|flow-edge-upsert|flow-edge-delete)
revision="${1:?revision}"; input="${2:?JSON containing unitId or @file}"; if [ "${input:0:1}" = "@" ]; then input=$(cat -- "${input:1}"); fi
action="${sub//-/_}"
jpost "/api/v1/organization" "$(jq -n --arg action "$action" --arg revision "$revision" --argjson data "$input" '{action:$action,expected_revision:$revision,data:$data}')" ;;
diff --git a/scripts/e2e/graph-custom.mjs b/scripts/e2e/graph-custom.mjs
new file mode 100644
index 00000000..43379abb
--- /dev/null
+++ b/scripts/e2e/graph-custom.mjs
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+// Selection, persisted grouping and routed edges against a real build with private synthetic stores.
+import { chromium, expect } from "@playwright/test";
+import { mkdir } from "node:fs/promises";
+import path from "node:path";
+import { releaseFixture } from "./release-fixture.mjs";
+const fixture = await releaseFixture({ live: true });
+let browser;
+try {
+ browser = await chromium.launch({ headless: true });
+ const context = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
+ await context.addInitScript((device) => { localStorage.setItem("mso.device.id", device); localStorage.setItem("mso:onboarding:v1", "done"); }, fixture.device);
+ const response = await fetch(fixture.base + "/api/auth/login", { method: "POST", headers: { "content-type": "application/json", origin: fixture.base }, body: JSON.stringify({ password: fixture.password, deviceId: fixture.device }) });
+ expect(response.ok).toBe(true);
+ const cookie = /(?:^|,\s*)session=([^;]+)/.exec(response.headers.get("set-cookie") ?? "")?.[1];
+ if (!cookie) throw new Error("Synthetic session missing");
+ await context.addCookies([{ name: "session", value: cookie, url: fixture.base, httpOnly: true, sameSite: "Lax" }]);
+ const page = await context.newPage(), errors = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.goto(fixture.base + "/organization");
+ const api = (route, body) => page.evaluate(async ([route, body]) => { const r = await fetch(route, body ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : {}); return { status: r.status, body: await r.json() }; }, [route, body]);
+ let chart = (await api("/api/v1/organization")).body.chart;
+ const orgNodes = ["a", "b", "c"].map((id, i) => ({ id, title: `Project ${id.toUpperCase()}`, kind: "project", status: "unconfirmed", summary: "Synthetic context", notes: "Preserve source notes", position: { x: i * 330, y: i === 1 ? 210 : 0 } }));
+ const orgEdges = [{ id: "a-b", source: "a", target: "b", label: "supports" }, { id: "b-c", source: "b", target: "c", label: "continues" }];
+ const created = await api("/api/v1/organization", { action: "unit_upsert", expected_revision: chart.revision, unit: { id: "custom-test", key: "custom-test", name: "Custom Test", kind: "team", projectFlow: { version: 1, title: "Context", notes: "Source", nodes: orgNodes, edges: orgEdges } } });
+ expect(created.status).toBe(200);
+ const openOrg = async () => { await page.goto(fixture.base + "/organization"); await page.getByRole("application", { name: "Organization units canvas", exact: true }).locator('[data-id="custom-test"]').click(); await expect(page.locator('[data-slot="organization-project-flow"]')).toBeVisible(); };
+ await openOrg();
+ const orgCanvas = page.getByRole("application", { name: "Organization project flow canvas", exact: true });
+ const select = async (canvas, ids) => { for (const id of ids) await canvas.locator(`[data-id="${id}"]`).click({ modifiers: ["Control"] }); await expect(page.locator('[data-slot="graph-custom-controls"]')).toContainText(`${ids.length} selected`); };
+ const createGroup = async (name) => { await page.getByRole("button", { name: "Create custom node", exact: true }).click(); await page.getByLabel("Custom node name").fill(name); await page.getByRole("button", { name: "Create", exact: true }).click(); await expect(page.getByRole("heading", { name: "Create custom node", exact: true })).toBeHidden(); };
+ await select(orgCanvas, ["a", "b"]); await createGroup("Delivery custom");
+ await expect(orgCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);
+ chart = (await api("/api/v1/organization")).body.chart;
+ let saved = chart.units.find((u) => u.id === "custom-test").projectFlow;
+ expect(saved.nodes).toEqual(orgNodes); expect(saved.edges).toEqual(orgEdges); expect(saved.customNodes[0].nodeIds.sort()).toEqual(["a", "b"]);
+ await openOrg(); await expect(orgCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);
+ await expect(orgCanvas.locator(".react-flow__edge")).toHaveCount(1);
+ const customCard = orgCanvas.locator(".react-flow__node-customGroup");
+ await page.waitForTimeout(350);
+ const box = await customCard.boundingBox();
+ await page.mouse.move(box.x + box.width / 2, box.y + 24); await page.mouse.down();
+ await page.mouse.move(box.x + box.width / 2 + 55, box.y + 65, { steps: 8 }); await page.mouse.up();
+ await expect.poll(async () => (await api("/api/v1/organization")).body.chart.units.find((u) => u.id === "custom-test").projectFlow.nodes[0].position.x).not.toBe(0);
+ const moved = (await api("/api/v1/organization")).body.chart.units.find((u) => u.id === "custom-test").projectFlow;
+ expect(moved.nodes[1].position.x - moved.nodes[0].position.x).toBe(330);
+ expect(moved.nodes[1].position.y - moved.nodes[0].position.y).toBe(210);
+ expect(moved.nodes[2]).toEqual(orgNodes[2]);
+ await orgCanvas.locator(".react-flow__node-customGroup").dblclick();
+ await expect(orgCanvas.locator(".react-flow__node-project")).toHaveCount(3);
+ await page.getByLabel("Custom node", { exact: true }).selectOption(saved.customNodes[0].id);
+ await page.getByRole("button", { name: "Ungroup", exact: true }).click();
+ await expect.poll(async () => (await api("/api/v1/organization")).body.chart.units.find((u) => u.id === "custom-test").projectFlow.customNodes).toEqual([]);
+ await openOrg(); await select(orgCanvas, ["a"]); await createGroup("Single custom");
+ await expect(orgCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);
+ await orgCanvas.locator(".react-flow__node-customGroup").dblclick();
+ await expect(orgCanvas.locator(".react-flow__node-project")).toHaveCount(3);
+ await expect(orgCanvas.locator('[data-routing-state="clear"]')).toHaveCount(2);
+ const workflowNodes = [
+ { id: "start", name: "Manual", type: "manual", position: { x: 0, y: 100 }, config: {} },
+ { id: "a", name: "First step", type: "batch", position: { x: 330, y: 100 }, config: { items: [1, 2, 3], size: 2 } },
+ { id: "b", name: "Second step", type: "batch", position: { x: 660, y: 100 }, config: { items: [4, 5], size: 1 } },
+ { id: "out", name: "Output", type: "output", position: { x: 990, y: 100 }, config: {} },
+ ];
+ const workflowEdges = workflowNodes.slice(1).map((n, i) => ({ id: `e${i}`, source: workflowNodes[i].id, target: n.id }));
+ const result = await api("/api/v1/workflows", { action: "create", graph: { name: "Custom Workflow", description: "Fixture", status: "draft", inputs: {}, metadata: {}, nodes: workflowNodes, edges: workflowEdges } });
+ expect(result.status).toBe(200); const graphId = result.body.graph.id;
+ await page.goto(fixture.base + "/workflows");
+ const wfCanvas = page.getByRole("application", { name: "Workflow canvas", exact: true });
+ await expect(wfCanvas).toBeVisible(); await wfCanvas.getByRole("button", { name: "Fit view", exact: true }).click();
+ await select(wfCanvas, ["a", "b"]); await createGroup("Two-step custom");
+ await expect(wfCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);
+ const save = page.getByRole("button", { name: "Save", exact: true });
+ if (await save.isVisible()) await save.click(); else { await page.getByRole("button", { name: "More actions", exact: true }).click(); await page.getByRole("menuitem", { name: "Save", exact: true }).click(); }
+ await expect.poll(async () => (await api(`/api/v1/workflows?graph_id=${graphId}`)).body.graph.metadata.customNodes?.length).toBe(1);
+ const graph = (await api(`/api/v1/workflows?graph_id=${graphId}`)).body.graph;
+ expect(graph.nodes).toEqual(workflowNodes); expect(graph.edges).toEqual(workflowEdges);
+ await page.reload(); await expect(wfCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);
+ await expect(wfCanvas.locator(".react-flow__edge")).toHaveCount(2);
+ await expect(wfCanvas.locator('[data-routing-state="clear"]')).toHaveCount(2);
+ const run = await api("/api/v1/workflows", { action: "run", graph_id: graphId, input: {}, idempotency_key: "custom-execution-fixture" });
+ expect(run.status).toBe(200);
+ await expect.poll(async () => (await api(`/api/v1/workflows?run_id=${run.body.id}&wait_ms=500`)).body.state, { timeout: 20000 }).toBe("completed");
+ const receipt = (await api(`/api/v1/workflows?run_id=${run.body.id}`)).body;
+ expect(receipt.nodes.map((n) => n.id)).toEqual(workflowNodes.map((n) => n.id));
+ for (const viewport of [{ width: 1600, height: 1000 }, { width: 390, height: 844 }]) {
+ await page.setViewportSize(viewport); await page.reload();
+ await expect(wfCanvas.locator(".react-flow__node-customGroup")).toBeVisible();
+ expect(await page.locator('[data-slot="workflows-feature"]').evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);
+ if (process.env.MSO_SCREENSHOT_DIR) { await mkdir(process.env.MSO_SCREENSHOT_DIR, { recursive: true }); await page.screenshot({ path: path.join(process.env.MSO_SCREENSHOT_DIR, `custom-workflow-${viewport.width}.png`) }); }
+ }
+ expect(errors).toEqual([]);
+ console.log("PASS: one/multi selection, custom node create/expand/ungroup/reload in organization; workflow grouping preserves branch ports/topology and executes original steps; directional obstacle-aware edges; desktop/mobile reflow.");
+} finally { await browser?.close(); await fixture.close(); }
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 6643df82..0a46e990 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -12,6 +12,7 @@ import { releaseFixture } from "./release-fixture.mjs";
execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });
execFileSync(process.execPath, ["scripts/e2e/organization-flow.mjs"], { stdio: "inherit" });
+execFileSync(process.execPath, ["scripts/e2e/graph-custom.mjs"], { stdio: "inherit" });
const fixture = await releaseFixture();
let browser;
try {
diff --git a/scripts/graph-custom-routing.test.ts b/scripts/graph-custom-routing.test.ts
new file mode 100644
index 00000000..79ddf56c
--- /dev/null
+++ b/scripts/graph-custom-routing.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import { parseGraphCustomNodes, pruneGraphCustomNodes } from "../lib/contracts/graph-custom-nodes";
+import { projectCustomNodes, moveCustomNode } from "../components/shared/graph-custom-projection";
+import { orthogonalRoute, segmentBlocked, routePath } from "../components/shared/graph-route";
+import { parseWorkflowGraphDefinition } from "../lib/workflow/graph-schema";
+import { changeOrganizationFlow } from "../lib/agent/organization-flow-mutations";
+
+const members = new Set(["a", "b", "c"]);
+const group = { id: "custom-one", name: "My custom node", nodeIds: ["a", "b"], collapsed: true };
+const nodes = ["a", "b", "c"].map((id, i) => ({ id, position: { x: i * 300, y: i * 60 }, data: {} }));
+const edges = [{ id: "internal", source: "a", target: "b", sourceHandle: "true" }, { id: "boundary", source: "b", target: "c", sourceHandle: "error" }];
+describe("custom node contract", () => {
+ it("accepts one or several members, rejects invalid or overlapping membership", () => {
+ expect(parseGraphCustomNodes([group], members)).toEqual([group]);
+ expect(parseGraphCustomNodes([{ ...group, nodeIds: ["a"] }], members)[0].nodeIds).toHaveLength(1);
+ for (const value of [[{ ...group, nodeIds: [] }], [{ ...group, nodeIds: ["missing"] }], [{ ...group, nodeIds: ["a", "a"] }], [group, { ...group, id: "another" }], [{ ...group, id: "a" }], [{ ...group, name: " " }]]) expect(() => parseGraphCustomNodes(value, members)).toThrow();
+ });
+ it("renders proxies without rewriting original nodes, ports, configs or edges", () => {
+ const before = JSON.stringify({ nodes, edges });
+ const projected = projectCustomNodes(nodes, edges, [group], [group.id]);
+ expect(projected.nodes.map((n) => n.id)).toEqual(["c", group.id]);
+ expect(projected.edges).toHaveLength(1);
+ expect(projected.edges[0]).toMatchObject({ id: "boundary", source: group.id, target: "c", sourceHandle: "out-boundary" });
+ expect(projected.nodes.at(-1)).toMatchObject({ data: { ports: [{ id: "out-boundary", label: "error", side: "out" }] } });
+ expect(JSON.stringify({ nodes, edges })).toBe(before);
+ expect(projectCustomNodes(nodes, edges, [{ ...group, collapsed: false }], []).edges).toEqual(edges);
+ });
+ it("handles two collapsed groups and keeps each boundary port separate", () => {
+ const second = { ...group, id: "custom-two", nodeIds: ["c"] };
+ const result = projectCustomNodes(nodes, edges, [group, second], []);
+ expect(result.edges[0]).toMatchObject({ source: group.id, target: second.id, sourceHandle: "out-boundary", targetHandle: "in-boundary" });
+ expect(projectCustomNodes([], [], [group], []).nodes).toEqual([]);
+ });
+ it("moves members together and only removes grouping on ungroup", () => {
+ const moved = moveCustomNode(nodes, group, { x: 100, y: 200 });
+ expect(moved[0].position).toEqual({ x: 100, y: 200 }); expect(moved[1].position).toEqual({ x: 400, y: 260 }); expect(moved[2]).toBe(nodes[2]);
+ expect(pruneGraphCustomNodes([group], new Set(["b", "c"]))[0].nodeIds).toEqual(["b"]);
+ expect(pruneGraphCustomNodes([group], new Set(["c"]))).toEqual([]);
+ });
+ it("roundtrips workflow grouping without changing executable topology", () => {
+ const base = { name: "Test", description: "", status: "draft", inputs: {}, nodes: nodes.map((n) => ({ ...n, name: n.id, type: "output", config: {} })), edges };
+ const parsed = parseWorkflowGraphDefinition({ ...base, metadata: { customNodes: [group] } });
+ expect(parsed.metadata.customNodes).toEqual([group]); expect(parsed.edges).toEqual(edges);
+ expect(() => parseWorkflowGraphDefinition({ ...base, metadata: { customNodes: [{ ...group, nodeIds: ["foreign"] }] } })).toThrow();
+ });
+ it("supports native organization grouping, atomic moves and safe member deletion", () => {
+ let flow = changeOrganizationFlow(undefined, "flow_node_upsert", { node: { id: "a", title: "A" } });
+ flow = changeOrganizationFlow(flow, "flow_node_upsert", { node: { id: "b", title: "B" } });
+ flow = changeOrganizationFlow(flow, "flow_custom_nodes", { customNodes: [group] });
+ const before = JSON.stringify(flow);
+ expect(() => changeOrganizationFlow(flow, "flow_nodes_move", { positions: [{ id: "a", position: { x: 1, y: 2 } }, { id: "foreign", position: { x: 0, y: 0 } }] })).toThrow();
+ expect(JSON.stringify(flow)).toBe(before);
+ flow = changeOrganizationFlow(flow, "flow_nodes_move", { positions: [{ id: "a", position: { x: 250, y: 120 } }] });
+ expect(flow.nodes[0].position).toEqual({ x: 250, y: 120 });
+ flow = changeOrganizationFlow(flow, "flow_node_delete", { id: "a" });
+ expect(flow.customNodes?.[0].nodeIds).toEqual(["b"]);
+ });
+});
+describe("obstacle-aware connectors", () => {
+ it("routes forward and reverse paths around intervening node cards", () => {
+ const obstacles = [{ x: 100, y: -50, width: 160, height: 180 }, { x: 310, y: -130, width: 100, height: 180 }];
+ for (const [a, b] of [[{ x: 0, y: 0 }, { x: 500, y: 0 }], [{ x: 500, y: 0 }, { x: 0, y: 0 }], [{ x: 0, y: 200 }, { x: 500, y: -180 }]]) {
+ const points = orthogonalRoute(a, b, obstacles)!; expect(points).not.toBeNull(); expect(points[0]).toEqual(a); expect(points.at(-1)).toEqual(b);
+ for (let i = 1; i < points.length; i++) expect(segmentBlocked(points[i - 1], points[i], obstacles)).toBe(false);
+ expect(routePath(points)).not.toMatch(/NaN|Infinity/);
+ }
+ });
+ it("uses bounded routing and reports impossible overlaps instead of claiming clearance", () => {
+ expect(orthogonalRoute({ x: 5, y: 5 }, { x: 200, y: 200 }, [{ x: 0, y: 0, width: 20, height: 20 }])).toBeNull();
+ expect(orthogonalRoute({ x: NaN, y: 0 }, { x: 0, y: 0 }, [])).toBeNull();
+ expect(orthogonalRoute({ x: 0, y: 0 }, { x: 100, y: 0 }, [])).toEqual([{ x: 0, y: 0 }, { x: 100, y: 0 }]);
+ });
+});