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(workflows): refine builder and organization focus UX

Rahman5d2617486aa9
diff --git a/docs/A2A.md b/docs/A2A.md
index d36d9242..520454e0 100644
--- a/docs/A2A.md
+++ b/docs/A2A.md
@@ -86,6 +86,18 @@ mso a2a inbound rm <tokenId>
The Settings → **A2A** panel exposes the same flow, shows the one-time token once, lists/revokes inbound profiles, and surfaces bounded task/audit activity.
+## Relationship to Workflow and Organization
+
+A2A is a **transport boundary**, not MSO's visual orchestration graph and not its organization chart.
+
+- **Workflow Graph** owns repeatable automation topology: triggers, If/Switch, Merge, Loop Over Items, bounded Repeat Until, Execute Workflow/subflow, retry/error routing, and run receipts.
+- **Organization** owns stable unit/seat identity, reporting lines, and the pointer from a seat to its current Project Agent, Local Agent, or remote A2A executor.
+- **A2A** owns discovery, authentication, message/task lifecycle, streaming, cancellation, and the remote trust boundary.
+
+A Workflow `agent` node may target an `orgSeatId`. If that seat currently maps to an A2A peer, runtime resolution reaches the existing `a2a_handoff` path; changing the concrete peer later does not rewrite the workflow. Likewise, a saved Session workflow can be called through Execute Workflow or bounded Repeat Until without turning A2A itself into a loop engine. This separation keeps transport credentials and remote task state out of portable workflow definitions and organization metadata.
+
+See [Workflow Graph](./WORKFLOW-GRAPH.md) and [Organization](./ORGANIZATION.md).
+
## Same-host sessions are native Local Agents, not remote A2A
MSO 1.9 separates live same-host session communication from this remote interoperability protocol. `/agents`, `/message`, local `/delegate`, local inbox delivery, and the `local_agent_*` MCP tools use a private **presence lease + durable mailbox + SSE/event-bus** layer. They require no Agent Card, URL, registration, credential, refresh, or restart when another session appears or is renamed.
diff --git a/docs/AUTOMATION-FLOWS.md b/docs/AUTOMATION-FLOWS.md
index 4f46a1bc..1dfd0ceb 100644
--- a/docs/AUTOMATION-FLOWS.md
+++ b/docs/AUTOMATION-FLOWS.md
@@ -142,4 +142,4 @@ workflow-store model; a multi-writer database is not introduced.
## Workflow Graph v2
-For visual, branching, mixed-node workflows, see [WORKFLOW-GRAPH.md](./WORKFLOW-GRAPH.md). Graph v2 is private per authenticated principal and now covers server schedule/webhook triggers, switch/merge/batch/loop/wait/sub-workflow control, retry/error routing, version/history rollback, private variables, integration references and per-node receipts while resolving project/folder locations dynamically. It coexists with the linear flow format documented above. `workflow_start` checks matching private graphs before learned recipes; successful `workflow_finish` seeds private draft graphs automatically.
+For visual, branching, mixed-node workflows, see [WORKFLOW-GRAPH.md](./WORKFLOW-GRAPH.md). Graph v2 is private per authenticated principal and now covers server schedule/webhook triggers, switch/merge/batch/loop/bounded-repeat/wait/Execute-Workflow control, retry/error routing, version/history rollback, private variables, integration references and per-node receipts while resolving project/folder locations dynamically. It coexists with the linear flow format documented above. `workflow_start` checks matching private graphs before learned recipes; successful `workflow_finish` seeds private draft graphs automatically.
diff --git a/docs/ORGANIZATION.md b/docs/ORGANIZATION.md
index 07116cfe..d571054a 100644
--- a/docs/ORGANIZATION.md
+++ b/docs/ORGANIZATION.md
@@ -139,8 +139,11 @@ Node kinds are `project`, `activity`, `group`, and `note`; status defaults to
`unconfirmed`, with explicit `planned`, `active`, `blocked`, and `done` alternatives.
`projectRef` is a reference only and grants no authority. Clicking a node opens its
details; editing, dragging positions, connecting and deleting persist through the API.
-Search and focus limit the visible context without changing stored data. Long source
-notes live inside the unit's Notes editor, not on the overview card.
+Search and focus limit the visible context without changing stored data. Search also
+matches named presentation groups. Selecting an individual node can focus that node plus
+its immediate incoming/outgoing context; selecting a collapsed custom group can focus all
+members plus their one-hop boundary context. Long source notes live inside the unit's
+Notes editor, not on the overview card.
The existing `organization_chart` read tool returns each unit's `projectFlow`.
The existing `organization_manage` write tool supports the following actions; all
@@ -181,6 +184,14 @@ 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.
+A collapsed group is also a **focus boundary**. Click the group to open its member summary,
+jump directly to an individual member, toggle **Focus group**, expand/collapse it, or ungroup
+the presentation wrapper. Group focus keeps the group's one-hop external dependencies visible
+so the user sees the surrounding operating context rather than an isolated box. This adopts
+the useful Paperclip-style control-plane principle of understanding a team/work area at a
+glance while keeping MSO's Organization store, routing model and execution authorities unchanged.
+Paperclip is a UX reference only; MSO does not depend on Paperclip or import its company data model.
+
`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
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index ac3f4250..38c42cec 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,13 @@
+## 2026-09-21 — Tighten Workflow builder UX and Organization group focus
+
+The bounded Repeat Until release completed the missing control-flow primitive, but the visual construction path still required more ceremony than mature workflow editors: node creation was a flat popover, adding a next step meant creating then wiring it manually, and collapsed Organization project groups could not become an explicit focus context. This pass improves those interaction gaps without changing Workflow execution authority or Organization persistence.
+
+Workflows now uses a categorized node creator across Triggers, Actions, AI, Flow and Context, with search, keyboard-first first-result insertion, clearer node-family cards, and a contextual **+** on every executable output. Quick-add opens an after-node picker that intentionally excludes triggers, positions the new node to the right with sibling spacing, preserves the exact branch handle, creates the edge in the same editor mutation and opens the new node in Inspector. The reusable subflow node is presented as **Execute Workflow** while retaining the existing `subflow` contract. Canvas cards now distinguish node families and surface live run state more clearly. Collapsed Workflow groups can be selected and managed directly instead of behaving like inert proxies.
+
+Organization project-flow groups now act as Paperclip-style focus boundaries without changing the Organization data model. Selecting a collapsed group opens a member summary, permits direct member navigation, focus/exit-focus, expand/collapse and presentation-only ungrouping. Group focus keeps all members plus their one-hop external dependencies visible; search also resolves group names. The implementation remains presentation/context metadata only: reporting lines, seat routing, Workflow topology and agent/A2A execution authorities stay in their existing stores.
+
+Documentation was reconciled across Workflow Graph, Organization, A2A and Automation Flows. The n8n-parity section now distinguishes practical interaction parity from visual cloning and explicitly records remaining gaps such as n8n's richer drag/drop data mapper and community-node ecosystem. A2A now states that it is the remote transport boundary, while Workflow owns repeatable topology and Organization owns stable seat/routing identity. Targeted regression, typecheck, lint and full `bun run verify` pass on the candidate working tree; the committed candidate must still pass the official isolated build/browser release gate before shipping.
+
## 2026-09-21 — Add bounded Repeat Until for reusable Session workflows
Workflow Graph could already save successful/reviewable Session action history as a private workflow draft and invoke saved workflows through Subflow, but its graph schema deliberately rejected cyclic edges and the existing `loop` node only iterated arrays. That left ordinary automation patterns such as “run this saved task, inspect its result, and try again until ready” without a native bounded control-flow primitive.
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 555d8e32..cdbbb278 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -41,7 +41,7 @@ Webhook endpoint:
- `loop` — execute one bounded tool for each item with concurrency 1–4
- `repeat` — execute one saved Workflow Graph repeatedly until a result condition matches, with explicit `done` / `exhausted` branches, `maxIterations` 1–50, optional inter-iteration delay, and a hard node duration cap
- `wait` — delay/until, bounded to ten minutes inside a run
-- `subflow` — execute another private Workflow Graph, or a legacy project flow
+- `subflow` / **Execute Workflow** — execute another private Workflow Graph, or a legacy project flow
- `output` — explicit result collection
Graph edges stay acyclic. Item fan-out uses `loop`; conditional loop-back uses `repeat`, which reruns a referenced saved Workflow Graph internally instead of creating an unrestricted graph cycle. `repeat` always has hard iteration/time bounds and emits `done` or `exhausted`. Cross-workflow recursion is rejected with an ancestry guard.
@@ -153,8 +153,9 @@ AI assistance has an isolated workflow-design system prompt, receives no implici
- private searchable workflow library with description/project/folder/tag metadata, clickable tag chips, and shared query syntax (`tag:`, `status:`, `project:`, `folder:`, `node:` plus free-text AND terms)
- draft / active / archived lifecycle
-- searchable node palette
-- draggable canvas
+- category-aware node creator with search across Triggers, Actions, AI, Flow and Context
+- contextual **+** quick-add from every executable output/branch; the chosen node is positioned and connected automatically, while trigger-only nodes stay out of after-node suggestions
+- draggable canvas with node-family iconography, live execution state, multi-select and collapsible presentation groups
- click-to-connect input/output ports
- persistent per-edge `Auto/Solid/Dashed` presentation, execution `Active` toggle, directional arrows and bounded reverse-direction control
- true/false, switch and error handles
@@ -168,6 +169,19 @@ AI assistance has an isolated workflow-design system prompt, receives no implici
Run automatically saves a dirty graph before execution, so execution always uses the revision visible in the editor. Disabled connections remain visible in the graph and receipts but are excluded from runtime traversal, cycle checks and tidy layout; a target reachable only through disabled connections is skipped rather than silently promoted to a new root.
+### Canvas construction UX
+
+The native editor follows the same construction rhythm users expect from tools such as n8n without copying n8n code or branding:
+
+1. **Add node** opens a searchable category browser rather than a flat technical type list.
+2. Hover any executable output and use **+** to choose the next node in context. Trigger nodes are omitted because a connected trigger would violate the graph contract.
+3. The new node is placed to the right of its source, connected through the exact branch handle (`true`, `false`, switch case, `done`, `exhausted`, or ordinary output), and opened in Inspector immediately.
+4. Node cards separate Trigger / Action / AI / Flow / Context families visually and surface running/completed/failed state without changing the stored definition.
+5. Multi-select grouping remains presentation-only. Selecting a collapsed group makes it manageable directly on the canvas; expanding restores its original executable members and ports.
+
+The result is a fast visual-builder path while the saved Workflow Graph remains the execution SSOT. There is no hidden browser-local automation state.
+
+
## Reviewed external workflow tabs
The Workflows workspace keeps the native MSO automation/session editor and can add
@@ -246,7 +260,9 @@ The linear `flow_catalog`, `flow_manage`, `flow_run` and `flow_status` tools rem
## Scope of n8n parity
-MSO targets **core self-hosted workflow parity**, not n8n's SaaS business surface. MSO intentionally uses its own server-native project, filesystem, Skill, agent and integration nodes instead of reproducing n8n's marketplace or cloud billing/team-administration products. Free cyclic graph topology is also intentionally replaced by bounded loop/subflow constructs for safer unattended server execution.
+MSO targets **core self-hosted workflow parity**, not visual cloning or n8n's SaaS business surface. The native editor intentionally matches the high-value interaction model: searchable categorized node creation, contextual insert-and-connect, explicit branch handles, drag/connect/tidy/minimap canvas controls, run-state overlays, execution history, retry/error routing, reusable **Execute Workflow**, Loop Over Items, Split In Batches, Merge, If/Switch, Wait, schedules/webhooks, variables, and previous-node data references.
+
+MSO intentionally uses its own server-native Project, Folder, Skill, Agent, Organization-seat, RASMIC and Integration nodes instead of reproducing n8n's marketplace or cloud billing/team-administration products. n8n's richer drag-and-drop input/output data mapper and full community-node ecosystem are not claimed as native parity today. Free cyclic graph topology is also intentionally replaced by bounded Loop/Repeat/Execute-Workflow constructs for safer unattended server execution. A reviewed external n8n editor can still be mounted as a sibling Workflows tab when an owner wants the original n8n surface.
## Organization seat routing
diff --git a/frontend/slices/organization/components/project-flow.tsx b/frontend/slices/organization/components/project-flow.tsx
index 55039652..91a0745a 100644
--- a/frontend/slices/organization/components/project-flow.tsx
+++ b/frontend/slices/organization/components/project-flow.tsx
@@ -11,6 +11,7 @@ import { cn } from "@/lib/utils";
import { emptyOrganizationFlow, type OrganizationFlowAction } from "@/lib/contracts/organization-flow";
import type { OrganizationUnit } from "@/lib/contracts/organization";
import { type ProjectCanvasNode as FlowNode } from "../lib/flow-projection";
+import { organizationProjectFlowVisibleIds } from "../lib/project-flow-focus";
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";
@@ -33,26 +34,30 @@ 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 [query, setQuery] = useState(""), [selectedId, setSelectedId] = useState<string | null>(null), [selectedGroupId, setSelectedGroupId] = useState<string | null>(null), [focus, setFocus] = useState(false);
const [draft, setDraft] = useState<FlowDraft | null>(null), [error, setError] = useState(""), [busy, setBusy] = useState(false);
const groups = useMemo(() => flow.customNodes ?? [], [flow.customNodes]);
const pending = useRef(false);
- 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 visible = useMemo(() => organizationProjectFlowVisibleIds({
+ nodes: flow.nodes,
+ edges: flow.edges,
+ groups,
+ query,
+ focusNodeId: focus ? selectedId : null,
+ focusGroupId: focus ? selectedGroupId : null,
+ }), [flow.nodes, flow.edges, groups, query, focus, selectedId, selectedGroupId]);
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 result = projectCustomNodes(base, lines, groups, selectedGroupId ? [selectedGroupId] : selectedId ? [selectedId] : []);
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]);
+ }, [flow.nodes, flow.edges, groups, selectedGroupId, selectedId, 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 selectedGroup = selectedGroupId ? groups.find((group) => group.id === selectedGroupId) : undefined;
+ const selectedGroupMembers = selectedGroup ? selectedGroup.nodeIds.map((id) => flow.nodes.find((node) => node.id === id)).filter((node): node is NonNullable<typeof node> => Boolean(node)) : [];
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("");
@@ -61,7 +66,11 @@ export function ProjectFlow({ unit, onSave }: Props) {
finally { pending.current = false; setBusy(false); }
};
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 changeGroups = (customNodes: GraphCustomNode[]) => {
+ quickSave("flow_custom_nodes", { customNodes });
+ setSelectedId(null);
+ if (selectedGroupId && !customNodes.some((group) => group.id === selectedGroupId)) { setSelectedGroupId(null); setFocus(false); }
+ };
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); }
@@ -74,7 +83,7 @@ export function ProjectFlow({ unit, onSave }: Props) {
<Button variant="outline" size="sm" onClick={() => setDraft({ kind: "notes" })}><FileText className="mr-1 size-3.5"/>Notes</Button>
<Button variant="outline" size="sm" disabled={flow.nodes.length < 2 || busy} onClick={() => setDraft({ kind: "edge" })}><Link2 className="mr-1 size-3.5"/>Connect</Button>
<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 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, groups, or notes…" value={query} onChange={(e) => setQuery(e.target.value)}/><Button size="sm" variant={focus ? "secondary" : "outline"} disabled={!selected && !selectedGroup} onClick={() => setFocus(!focus)}>{focus ? "Exit focus" : selectedGroup ? "Focus group" : "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}
@@ -82,13 +91,23 @@ export function ProjectFlow({ unit, onSave }: Props) {
{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); }}
+ onNodeClick={(event, node) => {
+ if (event.ctrlKey || event.metaKey) return;
+ if (node.type === "customGroup") { setSelectedGroupId(node.id); setSelectedId(null); return; }
+ setSelectedGroupId(null); setSelectedId(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); setSelectedGroupId(null); setFocus(false); }}
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)}
+ compactFitNodeIds={selectedGroup && selectedGroup.collapsed ? [selectedGroup.id] : 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>}
+ {selectedGroup ? <div data-slot="organization-group-focus" className="absolute inset-x-2 top-2 z-10 max-h-[calc(100%-1rem)] overflow-y-auto rounded-xl border bg-popover p-3 shadow-lg @min-[700px]:left-auto @min-[700px]:right-3 @min-[700px]:w-80">
+ <div className="flex items-start gap-2"><div className="min-w-0 flex-1"><div className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">Group focus</div><h3 className="mt-1 break-words text-sm font-semibold">{selectedGroup.name}</h3><p className="mt-1 text-xs text-muted-foreground">{selectedGroupMembers.length} mapped members · {selectedGroup.collapsed ? "collapsed" : "expanded"}</p></div><Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Close group details" onClick={() => { setSelectedGroupId(null); setFocus(false); }}><X className="size-4"/></Button></div>
+ <div className="mt-3 space-y-1.5">{selectedGroupMembers.map((member) => <button type="button" key={member.id} className="flex w-full items-center justify-between gap-2 rounded-md border px-2.5 py-2 text-left hover:bg-accent/60" onClick={() => { setSelectedGroupId(null); setSelectedId(member.id); }}><span className="min-w-0 truncate text-xs font-medium">{member.title}</span><Badge variant="outline" className="shrink-0 text-[9px]">{member.status}</Badge></button>)}</div>
+ <div className="mt-3 grid grid-cols-2 gap-2"><Button size="sm" variant={focus ? "secondary" : "outline"} onClick={() => setFocus(!focus)}>{focus ? "Exit focus" : "Focus group"}</Button><Button size="sm" variant="outline" onClick={() => changeGroups(groups.map((group) => group.id === selectedGroup.id ? { ...group, collapsed: !group.collapsed } : group))}>{selectedGroup.collapsed ? "Expand" : "Collapse"}</Button></div>
+ <Button className="mt-2 w-full" size="sm" variant="ghost" onClick={() => changeGroups(groups.filter((group) => group.id !== selectedGroup.id))}>Ungroup presentation only</Button>
+ </div> : null}
{selected ? <div className="absolute inset-x-2 top-2 z-10 max-h-[calc(100%-1rem)] overflow-y-auto rounded-xl border bg-popover p-3 shadow-lg @min-[700px]:left-auto @min-[700px]:right-3 @min-[700px]:w-80">
<div className="flex items-start gap-2"><h3 className="min-w-0 flex-1 break-words text-sm font-semibold">{selected.title}</h3><Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Close node details" onClick={() => setSelectedId(null)}><X className="size-4"/></Button></div>
<div className="mt-2 flex gap-1"><Badge variant="secondary">{selected.kind}</Badge><Badge variant="outline">{selected.status}</Badge></div>
diff --git a/frontend/slices/organization/lib/project-flow-focus.test.ts b/frontend/slices/organization/lib/project-flow-focus.test.ts
new file mode 100644
index 00000000..5f6fc054
--- /dev/null
+++ b/frontend/slices/organization/lib/project-flow-focus.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
+import type { OrganizationFlowEdge, OrganizationFlowNode } from "@/lib/contracts/organization-flow";
+import { organizationProjectFlowVisibleIds } from "./project-flow-focus";
+
+const nodes: OrganizationFlowNode[] = [
+ { id: "a", title: "Research", kind: "activity", status: "active", summary: "Discover", notes: "", position: { x: 0, y: 0 } },
+ { id: "b", title: "Draft", kind: "activity", status: "planned", summary: "Write", notes: "", position: { x: 200, y: 0 } },
+ { id: "c", title: "Review", kind: "activity", status: "planned", summary: "Check", notes: "", position: { x: 400, y: 0 } },
+ { id: "d", title: "Publish", kind: "activity", status: "planned", summary: "Ship", notes: "", position: { x: 600, y: 0 } },
+];
+const edges: OrganizationFlowEdge[] = [
+ { id: "ab", source: "a", target: "b", label: "" },
+ { id: "bc", source: "b", target: "c", label: "" },
+ { id: "cd", source: "c", target: "d", label: "" },
+];
+const groups: GraphCustomNode[] = [{ id: "editorial", name: "Editorial", nodeIds: ["b", "c"], collapsed: true }];
+
+describe("organization project-flow focus", () => {
+ it("shows the whole map without search or focus", () => {
+ expect([...organizationProjectFlowVisibleIds({ nodes, edges, groups, query: "" })]).toEqual(["a", "b", "c", "d"]);
+ });
+ it("focuses a group plus its one-hop boundary context", () => {
+ expect([...organizationProjectFlowVisibleIds({ nodes, edges, groups, query: "", focusGroupId: "editorial" })].sort()).toEqual(["a", "b", "c", "d"]);
+ });
+ it("focuses one node plus immediate neighbors", () => {
+ expect([...organizationProjectFlowVisibleIds({ nodes, edges, groups, query: "", focusNodeId: "b" })].sort()).toEqual(["a", "b", "c"]);
+ });
+ it("lets search find a custom group by its group name", () => {
+ expect([...organizationProjectFlowVisibleIds({ nodes, edges, groups, query: "editorial" })].sort()).toEqual(["a", "b", "c", "d"]);
+ });
+});
diff --git a/frontend/slices/organization/lib/project-flow-focus.ts b/frontend/slices/organization/lib/project-flow-focus.ts
new file mode 100644
index 00000000..22c14710
--- /dev/null
+++ b/frontend/slices/organization/lib/project-flow-focus.ts
@@ -0,0 +1,37 @@
+import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
+import type { OrganizationFlowEdge, OrganizationFlowNode } from "@/lib/contracts/organization-flow";
+
+export function organizationProjectFlowVisibleIds({
+ nodes, edges, groups, query, focusNodeId, focusGroupId,
+}: {
+ nodes: OrganizationFlowNode[];
+ edges: OrganizationFlowEdge[];
+ groups: GraphCustomNode[];
+ query: string;
+ focusNodeId?: string | null;
+ focusGroupId?: string | null;
+}): Set<string> {
+ const text = query.trim().toLowerCase();
+ const focusedGroup = focusGroupId ? groups.find((group) => group.id === focusGroupId) : undefined;
+ const focusSeeds = focusedGroup?.nodeIds.length ? focusedGroup.nodeIds : focusNodeId ? [focusNodeId] : [];
+ if (!text && !focusSeeds.length) return new Set(nodes.map((node) => node.id));
+
+ const seeds = new Set<string>(focusSeeds);
+ if (text) {
+ for (const node of nodes) {
+ if (`${node.title} ${node.summary} ${node.kind} ${node.status}`.toLowerCase().includes(text)) seeds.add(node.id);
+ }
+ for (const group of groups) {
+ if (group.name.toLowerCase().includes(text)) for (const id of group.nodeIds) seeds.add(id);
+ }
+ }
+
+ const visible = new Set(seeds);
+ for (const edge of edges) {
+ if (seeds.has(edge.source) || seeds.has(edge.target)) {
+ visible.add(edge.source);
+ visible.add(edge.target);
+ }
+ }
+ return visible;
+}
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index aad96ff1..aecab078 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -31,6 +31,7 @@ export default function WorkflowsApp(props: AppProps) {
const overlayPane = isMobile || pane !== "lg";
const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useState<WorkflowGraph | null>(null), [selected, setSelected] = useState<string | null>(null), [run, setRun] = useState<WorkflowGraphRun | null>(null);
const [busy, setBusy] = useState(false), [dirty, setDirty] = useState(false), [message, setMessage] = useState(""), [panel, setPanel] = useState<WorkflowPanel>("inspector"), [search, setSearch] = useState("");
+ const [nodeCreator, setNodeCreator] = useState<{ open: boolean; sourceId?: string; sourceHandle?: string }>({ open: false });
const [libraryOpen, setLibraryOpen] = useState(false), [detailsOpen, setDetailsOpen] = useState(false), [showLibrary, setShowLibrary] = useState(true), [showDetails, setShowDetails] = useState(true);
const [libraryMode, setLibraryMode] = useState<LibraryMode>(() => payloadSessionId(props.payload) ? "sessions" : "automations");
const [sessionView, setSessionView] = useState<SessionGraphView | null>(null), [sessionSelected, setSessionSelected] = useState<string | null>(null);
@@ -72,7 +73,17 @@ export default function WorkflowsApp(props: AppProps) {
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)), 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 addNode = (type: WorkflowGraphNodeType, defaults: Record<string, unknown>) => {
+ if (!graph) return;
+ const id = `${type}-${crypto.randomUUID().slice(0, 8)}`, source = nodeCreator.sourceId ? graph.nodes.find((item) => item.id === nodeCreator.sourceId) : undefined;
+ const siblingCount = source ? graph.edges.filter((edge) => edge.source === source.id).length : 0;
+ const position = source ? { x: source.position.x + 290, y: source.position.y + siblingCount * 110 } : { x: 220 + graph.nodes.length * 36, y: 240 + (graph.nodes.length % 4) * 110 };
+ const next: WorkflowGraphNode = { id, name: type.replaceAll("_", " ").replace(/\b\w/g, (char) => char.toUpperCase()), type, position, config: structuredClone(defaults) };
+ const edge = source ? { id: `edge-${crypto.randomUUID().slice(0, 8)}`, source: source.id, target: id, ...(nodeCreator.sourceHandle ? { sourceHandle: nodeCreator.sourceHandle } : {}) } : undefined;
+ mutate({ ...graph, nodes: [...graph.nodes, next], edges: edge ? [...graph.edges, edge] : graph.edges });
+ setNodeCreator({ open: false });
+ 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 } : {}) }] }); };
const openNode = async (id: string) => { if (!graph) return; const resolved = await resolveNode(graph.id, id); openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true }); };
const openSessionTerminal = () => { if (!sessionView) return; setDetailsOpen(false); openWindow("os-terminal", "Terminal", undefined, { initialCwd: sessionView.session.cwd || "~" }, { multi: true }); };
@@ -110,7 +121,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} 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>
+ {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} open={nodeCreator.open} context={nodeCreator.sourceId ? "after-node" : "all"} onOpenChange={(open) => setNodeCreator(open ? { open: true } : { open: false })}/><span className="hidden min-w-0 truncate text-[10px] text-muted-foreground @min-[900px]:inline">Drag output → input or use + to insert. V Select · H Pan · +/- Zoom · F Fit · Space 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} onQuickAdd={(sourceId, sourceHandle) => setNodeCreator({ open: true, sourceId, ...(sourceHandle ? { sourceHandle } : {}) })} 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 e1a260ac..401f6420 100644
--- a/frontend/slices/workflows/components/workflow-canvas.tsx
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -1,5 +1,6 @@
"use client";
-import { useMemo } from "react";
+import { useMemo, useState } from "react";
+import { Bot, Braces, GitBranch, Plus, Wrench, Zap } from "lucide-react";
import {
Handle, MarkerType, Position,
type Connection, type Edge, type Node, type NodeProps,
@@ -15,71 +16,156 @@ import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";
import { compactWorkflowFocusIds } from "../lib/compact-focus";
import { cn } from "@/lib/utils";
-interface WorkflowNodeData extends Record<string, unknown> { node: WorkflowGraphNode; state?: WorkflowGraphNodeState }
+interface WorkflowNodeData extends Record<string, unknown> {
+ node: WorkflowGraphNode;
+ state?: WorkflowGraphNodeState;
+ quickAdd?: (sourceId: string, sourceHandle?: string) => void;
+}
type FlowNode = Node<WorkflowNodeData, "workflow">;
type FlowEdge = Edge;
+const flowTypes = new Set(["condition", "switch", "merge", "batch", "loop", "repeat", "wait", "subflow", "output"]);
+const contextTypes = new Set(["cache", "memory", "session", "directory", "project", "folder", "skill", "knowledge"]);
+function nodeFamily(node: WorkflowGraphNode) {
+ if (["manual", "schedule", "webhook"].includes(node.type)) return { label: "Trigger", Icon: Zap };
+ if (node.type === "agent") return { label: "AI", Icon: Bot };
+ if (flowTypes.has(node.type)) return { label: "Flow", Icon: GitBranch };
+ if (contextTypes.has(node.type)) return { label: "Context", Icon: Braces };
+ return { label: "Action", Icon: Wrench };
+}
function sourceHandles(node: WorkflowGraphNode): Array<string | undefined> {
if (node.type === "condition") return ["true", "false"];
if (node.type === "repeat") return ["done", "exhausted"];
- if (node.type === "switch") { const cases = Array.isArray(node.config.cases) ? node.config.cases : []; return [...cases.map((row,index)=>row&&typeof row==="object"&&typeof (row as {handle?:unknown}).handle==="string"?String((row as {handle:string}).handle):`case-${index+1}`),"default"]; }
+ if (node.type === "switch") {
+ const cases = Array.isArray(node.config.cases) ? node.config.cases : [];
+ return [...cases.map((row, index) => row && typeof row === "object" && typeof (row as {handle?: unknown}).handle === "string" ? String((row as {handle: string}).handle) : `case-${index + 1}`), "default"];
+ }
return [undefined];
}
-const canError=(node:WorkflowGraphNode)=>!["manual","schedule","webhook","output"].includes(node.type);
-const canInput=(node:WorkflowGraphNode)=>!["manual","schedule","webhook"].includes(node.type);
-const canOutput=(node:WorkflowGraphNode)=>node.type!=="output";
-function nodeMetrics(node:WorkflowGraphNode){
- const semantic=node.config.sessionStep===true||node.config.sessionRoot===true,handles=sourceHandles(node);
- return {width:semantic?250:200,height:semantic?104:Math.max(78,48+Math.max(handles.length,canError(node)?2:1)*20)};
+const canError = (node: WorkflowGraphNode) => !["manual", "schedule", "webhook", "output"].includes(node.type);
+const canInput = (node: WorkflowGraphNode) => !["manual", "schedule", "webhook"].includes(node.type);
+const canOutput = (node: WorkflowGraphNode) => node.type !== "output";
+function nodeMetrics(node: WorkflowGraphNode) {
+ const semantic = node.config.sessionStep === true || node.config.sessionRoot === true, handles = sourceHandles(node);
+ return { width: semantic ? 250 : 210, height: semantic ? 104 : Math.max(84, 54 + Math.max(handles.length, canError(node) ? 2 : 1) * 20) };
}
-function WorkflowNodeCard({data,selected}:NodeProps<FlowNode>){
- const{node,state}=data,handles=sourceHandles(node),metrics=nodeMetrics(node),semantic=node.config.sessionStep===true||node.config.sessionRoot===true;
- const actionCount=typeof node.config.actionCount==="number"?node.config.actionCount:undefined,summary=typeof node.config.summary==="string"?node.config.summary:undefined;
- return <div className={cn("relative rounded-xl border bg-card px-3 py-3 shadow-sm transition-shadow",semantic?"w-[250px]":"w-[200px]",selected&&"ring-2 ring-ring shadow-md",state==="failed"&&"border-destructive ring-1 ring-destructive",state==="running"&&"border-primary ring-1 ring-primary",["skipped","blocked"].includes(state??"")&&"opacity-55",node.disabled&&"opacity-50")} style={{minHeight:metrics.height}}>
- {canInput(node)?<Handle type="target" position={Position.Left} id="input" className="!size-3.5 !border-2 !border-background !bg-muted-foreground"/>:null}
- <div className={cn("text-xs font-semibold",semantic?"line-clamp-2 leading-4":"truncate")}>{node.name}</div>
- <div className="mt-1 flex items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground"><span>{node.type.replaceAll("_"," ")}{state?` · ${state}`:""}</span>{actionCount!==undefined?<span className="rounded bg-muted px-1.5 py-0.5 normal-case tracking-normal">{actionCount} actions</span>:null}</div>
- {summary?<p className="mt-1.5 line-clamp-2 text-[10px] leading-4 text-muted-foreground">{summary}</p>:null}
- {canOutput(node)?handles.map((handle,index)=><div key={handle??"output"} className="absolute right-0 flex translate-x-1/2 items-center" style={{top:38+index*20}}>{handle?<span className="pointer-events-none absolute right-4 whitespace-nowrap pr-1 text-[8px] text-muted-foreground">{handle}</span>:null}<Handle type="source" position={Position.Right} id={handle??"output"} className="!relative !right-auto !top-auto !size-3.5 !translate-x-0 !translate-y-0 !border-2 !border-background !bg-muted-foreground"/></div>):null}
- {canError(node)?<Handle type="source" position={Position.Bottom} id="error" className="!size-3 !border-2 !border-background !bg-destructive"/>:null}
+function WorkflowNodeCard({ data, selected }: NodeProps<FlowNode>) {
+ const { node, state, quickAdd } = data, handles = sourceHandles(node), metrics = nodeMetrics(node), semantic = node.config.sessionStep === true || node.config.sessionRoot === true;
+ const actionCount = typeof node.config.actionCount === "number" ? node.config.actionCount : undefined, summary = typeof node.config.summary === "string" ? node.config.summary : undefined;
+ const { label, Icon } = nodeFamily(node);
+ return <div className={cn("relative rounded-xl border bg-card px-3 py-3 shadow-sm transition-shadow", semantic ? "w-[250px]" : "w-[210px]", selected && "ring-2 ring-ring shadow-md", state === "failed" && "border-destructive ring-1 ring-destructive", state === "running" && "border-primary ring-1 ring-primary", ["skipped", "blocked"].includes(state ?? "") && "opacity-55", node.disabled && "opacity-50")} style={{ minHeight: metrics.height }}>
+ {canInput(node) ? <Handle type="target" position={Position.Left} id="input" className="!size-3.5 !border-2 !border-background !bg-muted-foreground"/> : null}
+ <div className="flex items-start gap-2">
+ <span className="grid size-7 shrink-0 place-items-center rounded-lg border bg-background"><Icon className="size-3.5 text-muted-foreground"/></span>
+ <div className="min-w-0 flex-1">
+ <div className={cn("text-xs font-semibold", semantic ? "line-clamp-2 leading-4" : "truncate")}>{node.name}</div>
+ <div className="mt-1 flex flex-wrap items-center gap-1.5 text-[9px] uppercase tracking-wide text-muted-foreground">
+ <span>{label}</span><span>·</span><span>{node.type.replaceAll("_", " ")}</span>
+ {state ? <><span>·</span><span className={cn(state === "failed" && "text-destructive", state === "completed" && "text-success", state === "running" && "text-primary")}>{state}</span></> : null}
+ </div>
+ </div>
+ </div>
+ {actionCount !== undefined ? <span className="mt-2 inline-flex rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">{actionCount} actions</span> : null}
+ {summary ? <p className="mt-1.5 line-clamp-2 text-[10px] leading-4 text-muted-foreground">{summary}</p> : null}
+ {canOutput(node) ? handles.map((handle, index) => <div key={handle ?? "output"} className="absolute right-0 flex translate-x-1/2 items-center" style={{ top: 42 + index * 20 }}>
+ {handle ? <span className="pointer-events-none absolute right-4 whitespace-nowrap pr-1 text-[8px] text-muted-foreground">{handle}</span> : null}
+ <Handle type="source" position={Position.Right} id={handle ?? "output"} className="!relative !right-auto !top-auto !size-3.5 !translate-x-0 !translate-y-0 !border-2 !border-background !bg-muted-foreground"/>
+ {quickAdd ? <button type="button" aria-label={`Add after ${node.name}${handle ? ` (${handle})` : ""}`} title="Add and connect next node" className="nodrag nopan absolute left-5 grid size-5 place-items-center rounded-full border bg-background text-muted-foreground opacity-0 shadow-sm transition-opacity hover:text-foreground focus-visible:opacity-100 [.react-flow__node:hover_&]:opacity-100" onPointerDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); quickAdd(node.id, handle); }}><Plus className="size-3"/></button> : null}
+ </div>) : null}
+ {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, customGroup:GraphCustomCard};
+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(--muted-foreground)";
- const strokeDasharray=disabled?"2 6":edge.style==="dashed"?"7 5":edge.style==="solid"?undefined:branch?"7 5":undefined;
+function toNodes(graph: WorkflowGraph, selectedId: string | null, nodeStates?: ReadonlyMap<string, WorkflowGraphNodeState>, quickAdd?: (sourceId: string, sourceHandle?: string) => void): 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), quickAdd } };
+ });
+}
+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(--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}};
+ 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: 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)";
}
-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,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 visibleIds=useMemo(()=>new Set(nodes.map((node)=>node.id)),[nodes]);
- const rootFocusIds=useMemo(()=>compactWorkflowFocusIds(graph.nodes,groups,visibleIds,readOnly?9:2),[graph.nodes,groups,readOnly,visibleIds]);
- const compactIds=rootFocusIds.length?rootFocusIds:(readOnly?nodes.slice(0,9):nodes.slice(0,2)).map((node)=>node.id);
+export function WorkflowCanvas({ graph, selectedId, onSelect, onMove, onMoveMany, onCustomNodes, onConnect, onQuickAdd, 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;
+ onQuickAdd?: (sourceId: 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 [activeGroupId, setActiveGroupId] = useState<string | null>(null);
+ const groups = useMemo(() => graph.metadata.customNodes ?? [], [graph.metadata.customNodes]);
+ const selection = useMemo(() => activeGroupId ? [activeGroupId] : selectedId ? [selectedId] : [], [activeGroupId, selectedId]);
+ const mapped = useMemo(() => projectCustomNodes(toNodes(graph, null, nodeStates, readOnly ? undefined : onQuickAdd), toEdges(graph, nodeStates, edgeStates), groups, selection), [edgeStates, graph, groups, nodeStates, onQuickAdd, readOnly, selection]);
+ 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);
+ if (activeGroupId && !next.some((group) => group.id === activeGroupId)) setActiveGroupId(null);
+ 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 visibleIds = useMemo(() => new Set(nodes.map((node) => node.id)), [nodes]);
+ const rootFocusIds = useMemo(() => compactWorkflowFocusIds(graph.nodes, groups, visibleIds, readOnly ? 9 : 2), [graph.nodes, groups, readOnly, visibleIds]);
+ const compactIds = rootFocusIds.length ? rootFocusIds : (readOnly ? nodes.slice(0, 9) : nodes.slice(0, 2)).map((node) => node.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>
+ {!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={() => { setActiveGroupId(null); onSelect(null); }}
+ onNodeClick={(event, item) => {
+ if (event.ctrlKey || event.metaKey) return;
+ if (item.type === "customGroup") { setActiveGroupId(item.id); onSelect(null); return; }
+ setActiveGroupId(null); onSelect(item.id);
+ }}
+ onEdgeClick={readOnly ? undefined : (_, edge) => { if (graph.nodes.some((n) => n.id === edge.source)) { setActiveGroupId(null); 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/frontend/slices/workflows/components/workflow-node-palette.tsx b/frontend/slices/workflows/components/workflow-node-palette.tsx
index 34ccb196..f9d40202 100644
--- a/frontend/slices/workflows/components/workflow-node-palette.tsx
+++ b/frontend/slices/workflows/components/workflow-node-palette.tsx
@@ -1,16 +1,83 @@
"use client";
import { useEffect, useMemo, useState } from "react";
-import { Plus, Search } from "lucide-react";
+import { Bot, Braces, GitBranch, Plus, Search, Sparkles, Wrench, Zap } from "lucide-react";
import type { WorkflowGraphNodeType } from "@/lib/contracts/workflow-graph";
import type { WorkflowNodeCatalogItem } from "@/lib/workflow/node-catalog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { cn } from "@/lib/utils";
import { listNodeCatalog } from "../lib/api";
-export function WorkflowNodePalette({onAdd}:{onAdd:(type:WorkflowGraphNodeType,defaults:Record<string,unknown>)=>void}){
- const[open,setOpen]=useState(false),[query,setQuery]=useState(""),[items,setItems]=useState<WorkflowNodeCatalogItem[]>([]);
- useEffect(()=>{let cancelled=false;void listNodeCatalog().then((rows)=>{if(!cancelled)setItems(rows);}).catch(()=>undefined);return()=>{cancelled=true;};},[]);
- const filtered=useMemo(()=>{const q=query.toLowerCase().trim();return items.filter((item)=>!q||`${item.title} ${item.type} ${item.category} ${item.description}`.toLowerCase().includes(q));},[items,query]);
- return <Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><Button size="sm" variant="outline"><Plus className="mr-1 size-3"/>Node</Button></PopoverTrigger><PopoverContent align="start" className="w-80 p-2"><div className="relative mb-2"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="pl-7" placeholder="Search nodes…" value={query} onChange={(e)=>setQuery(e.target.value)}/></div><ScrollArea className="h-80"><div className="space-y-1">{filtered.map((item)=><button key={item.type} type="button" className="w-full rounded-md border p-2 text-left hover:bg-accent" onClick={()=>{onAdd(item.type,item.defaults);setOpen(false);setQuery("");}}><div className="flex items-center justify-between gap-2"><span className="text-xs font-semibold">{item.title}</span><span className="text-[10px] text-muted-foreground">{item.category}</span></div><p className="mt-1 text-[11px] text-muted-foreground">{item.description}</p></button>)}</div></ScrollArea></PopoverContent></Popover>;
+
+type Context = "all" | "after-node";
+type Props = {
+ onAdd: (type: WorkflowGraphNodeType, defaults: Record<string, unknown>) => void;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ context?: Context;
+};
+
+const categoryOrder = ["Triggers", "Actions", "AI", "Flow", "Context"] as const;
+function categoryIcon(category: string) {
+ if (category === "Triggers") return Zap;
+ if (category === "Actions") return Wrench;
+ if (category === "AI") return Bot;
+ if (category === "Flow") return GitBranch;
+ if (category === "Context") return Braces;
+ return Sparkles;
+}
+
+export function WorkflowNodePalette({ onAdd, open: openProp, onOpenChange, context = "all" }: Props) {
+ const [internalOpen, setInternalOpen] = useState(false), [query, setQuery] = useState(""), [category, setCategory] = useState("All");
+ const [items, setItems] = useState<WorkflowNodeCatalogItem[]>([]);
+ const open = openProp ?? internalOpen;
+ const setOpen = (next: boolean) => {
+ if (openProp === undefined) setInternalOpen(next);
+ onOpenChange?.(next);
+ if (!next) { setQuery(""); setCategory("All"); }
+ };
+ useEffect(() => {
+ let cancelled = false;
+ void listNodeCatalog().then((rows) => { if (!cancelled) setItems(rows); }).catch(() => undefined);
+ return () => { cancelled = true; };
+ }, []);
+ const available = useMemo(() => items.filter((item) => context !== "after-node" || item.category !== "Triggers"), [context, items]);
+ const categories = useMemo(() => ["All", ...categoryOrder.filter((name) => available.some((item) => item.category === name))], [available]);
+ const filtered = useMemo(() => {
+ const q = query.toLowerCase().trim();
+ return available.filter((item) => (category === "All" || item.category === category) && (!q || `${item.title} ${item.type} ${item.category} ${item.description}`.toLowerCase().includes(q)));
+ }, [available, category, query]);
+ const add = (item: WorkflowNodeCatalogItem) => {
+ onAdd(item.type, item.defaults);
+ setOpen(false);
+ };
+ return <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild><Button size="sm" variant="outline"><Plus className="mr-1 size-3"/>Add node</Button></PopoverTrigger>
+ <PopoverContent align="start" className="w-[min(92vw,34rem)] p-0">
+ <div className="border-b p-3">
+ <div className="mb-2"><div className="text-sm font-semibold">{context === "after-node" ? "What happens next?" : "Add a node"}</div><p className="mt-0.5 text-[11px] text-muted-foreground">{context === "after-node" ? "Choose the next action or flow step. It will be connected automatically." : "Search MSO triggers, actions, AI, flow-control and context nodes."}</p></div>
+ <div className="relative"><Search className="absolute left-2.5 top-2.5 size-3.5 text-muted-foreground"/><Input autoFocus className="pl-8" placeholder="Search nodes…" value={query} onChange={(event) => setQuery(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && filtered[0]) add(filtered[0]); }}/></div>
+ </div>
+ <div className="grid min-h-72 grid-cols-[8.5rem_minmax(0,1fr)]">
+ <div className="border-r p-2">
+ {categories.map((name) => {
+ const Icon = name === "All" ? Sparkles : categoryIcon(name);
+ return <button key={name} type="button" className={cn("flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-xs", category === name ? "bg-accent font-medium" : "text-muted-foreground hover:bg-accent/60 hover:text-foreground")} onClick={() => setCategory(name)}><Icon className="size-3.5 shrink-0"/><span className="truncate">{name}</span></button>;
+ })}
+ </div>
+ <ScrollArea className="h-80"><div className="space-y-1 p-2">
+ {filtered.map((item) => {
+ const Icon = categoryIcon(item.category);
+ return <button key={item.type} type="button" className="group flex w-full items-start gap-3 rounded-lg border border-transparent p-2.5 text-left hover:border-border hover:bg-accent/60" onClick={() => add(item)}>
+ <span className="grid size-8 shrink-0 place-items-center rounded-lg border bg-background"><Icon className="size-4 text-muted-foreground group-hover:text-foreground"/></span>
+ <span className="min-w-0 flex-1"><span className="flex items-center justify-between gap-2"><span className="text-xs font-semibold">{item.title}</span><span className="text-[9px] uppercase tracking-wide text-muted-foreground">{item.category}</span></span><span className="mt-1 block text-[11px] leading-4 text-muted-foreground">{item.description}</span></span>
+ </button>;
+ })}
+ {!filtered.length ? <div className="px-3 py-8 text-center text-xs text-muted-foreground">No nodes match this search.</div> : null}
+ </div></ScrollArea>
+ </div>
+ <div className="border-t px-3 py-2 text-[10px] text-muted-foreground">Tip: press Enter to add the first result. Use the + buttons on node outputs to insert and connect in one step.</div>
+ </PopoverContent>
+ </Popover>;
}
diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.ts
index 1e6e6bca..0babcad0 100644
--- a/lib/workflow/node-catalog.ts
+++ b/lib/workflow/node-catalog.ts
@@ -21,7 +21,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[
{type:"integration",title:"Integration",category:"Actions",description:"Execute through an existing MSO integration connection; credentials stay outside the graph.",defaults:{}},
{type:"script",title:"Script",category:"Actions",description:"Run a saved validated RASMIC script by project and script id.",defaults:{}},
{type:"agent",title:"Agent",category:"AI",description:"Run an organization seat or focused project agent action.",defaults:{wait:true,max_scope:"write"}},
- {type:"subflow",title:"Subflow",category:"Flow",description:"Run an existing project flow.",defaults:{}},
+ {type:"subflow",title:"Execute Workflow",category:"Flow",description:"Run a saved Workflow Graph or a legacy project flow as a reusable sub-workflow.",defaults:{}},
{type:"project",title:"Project",category:"Context",description:"Resolve canonical project identity/path at runtime.",defaults:{}},
{type:"folder",title:"Folder",category:"Context",description:"Resolve a real folder inside a canonical project.",defaults:{path:"."}},
{type:"skill",title:"Skill",category:"Context",description:"Search trusted skill catalog with provenance.",defaults:{}},
diff --git a/scripts/e2e/graph-custom.mjs b/scripts/e2e/graph-custom.mjs
index 43379abb..7fc5980d 100644
--- a/scripts/e2e/graph-custom.mjs
+++ b/scripts/e2e/graph-custom.mjs
@@ -37,6 +37,14 @@ try {
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 customCard.click();
+ const groupFocus = page.locator('[data-slot="organization-group-focus"]');
+ await expect(groupFocus).toContainText("Delivery custom");
+ await expect(groupFocus).toContainText("2 mapped members");
+ await groupFocus.getByRole("button", { name: "Focus group", exact: true }).click();
+ await expect(groupFocus.getByRole("button", { name: "Exit focus", exact: true })).toBeVisible();
+ await expect(orgCanvas.locator('[data-id="c"]')).toBeVisible();
+ await groupFocus.getByRole("button", { name: "Exit focus", exact: true }).click();
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();
@@ -90,5 +98,5 @@ try {
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.");
+ console.log("PASS: one/multi selection, Paperclip-like organization group focus, custom node create/expand/ungroup/reload; 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/workflow-canvas.mjs b/scripts/e2e/workflow-canvas.mjs
index 30fac443..d56a67a3 100644
--- a/scripts/e2e/workflow-canvas.mjs
+++ b/scripts/e2e/workflow-canvas.mjs
@@ -47,7 +47,25 @@ export async function workflowCanvasJourney(page, fixture) {
const minimap = canvas.getByLabel("Workflow canvas minimap");
await expect(minimap).toBeVisible();
await expect(minimap.locator(".react-flow__minimap-node")).toHaveCount(8);
- await expect(canvas.locator(".react-flow__node", { hasText: "Manual Trigger" })).toBeVisible();
+ const manualNode = canvas.locator(".react-flow__node", { hasText: "Manual Trigger" });
+ await expect(manualNode).toBeVisible();
+
+ // n8n-style fast construction: a node output exposes +, opens the contextual
+ // node creator without trigger types, and inserts+connects the chosen next step.
+ await manualNode.hover();
+ await canvas.getByRole("button", { name: "Add after Manual Trigger", exact: true }).click();
+ await expect(page.getByText("What happens next?", { exact: true })).toBeVisible();
+ await expect(page.getByPlaceholder("Search nodes…")).toBeFocused();
+ await expect(page.getByRole("button", { name: "Flow", exact: true })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Triggers", exact: true })).toHaveCount(0);
+ await page.getByPlaceholder("Search nodes…").fill("Wait");
+ await page.getByText("Wait", { exact: true }).click();
+ const insertedWait = canvas.locator(".react-flow__node", { hasText: "Wait" });
+ await expect(insertedWait).toBeVisible();
+ await expect(canvas.locator(".react-flow__edge")).toHaveCount(8);
+ await page.getByRole("button", { name: "Delete node", exact: true }).click();
+ await expect(insertedWait).toHaveCount(0);
+ await expect(canvas.locator(".react-flow__edge")).toHaveCount(7);
// Responsive contract: on a phone-sized pane the wide graph starts focused on
// the trigger at a readable zoom, side panels become drawers, and the toolbar
@@ -150,5 +168,5 @@ export async function workflowCanvasJourney(page, fixture) {
// Delete using the last persisted revision; the local tidy is intentionally unsaved.
response = await call(page, { action: "delete", graph_id: graph.id, expected_revision: graph.revision });
expect(response.status).toBe(200);
- console.log("PASS Workflow responsive toolbar/drawers, readable compact trigger focus, 5/5 canvas controls, minimap, persistent edge style/active/reverse controls, project/skill directory, active mode, cache/memory/session/directory runtime and cleanup");
+ console.log("PASS Workflow n8n-like contextual node creator/quick-add, responsive toolbar/drawers, readable compact trigger focus, 5/5 canvas controls, minimap, persistent edge style/active/reverse controls, project/skill directory, active mode, cache/memory/session/directory runtime and cleanup");
}