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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(workflows): finish edge controls and directory
rahmanef63b32ec1dea949
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.tsindex 32e2f3ac..4a30ef12 100644--- a/app/api/v1/workflows/route.ts+++ b/app/api/v1/workflows/route.ts@@ -8,6 +8,8 @@ import { rateLimited } from "@/lib/host/limits-api";import { maxScope } from "@/lib/mcp/scope";import { TOOLS_BY_NAME } from "@/lib/mcp/tools";import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";+import { listProjects } from "@/lib/host/projects-api";+import { catalogSkillsDetailed } from "@/lib/skills/catalog";import { cloneWorkflowGraph, createWorkflowGraph, deleteWorkflowGraph, getWorkflowGraph, listWorkflowGraphs, updateWorkflowGraph, workflowGraphOwner } from "@/lib/workflow/graph-store";import { startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";import { listWorkflowGraphRuns } from "@/lib/workflow/graph-run-store";@@ -26,7 +28,14 @@ const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceofasync function auth(minimum:"viewer"|"operator"|"owner"="viewer"){const context=await getSessionContext();if(!context?.session.device_id||!roleAtLeast(context.role,minimum))return null;return{context,principal:`web:${context.session.device_id}`};}function definition(graph:NonNullable<Awaited<ReturnType<typeof getWorkflowGraph>>>){const{revision:_r,createdAt:_c,updatedAt:_u,version:_v,...rest}=graph;return rest;}export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,minimum=q.has("variables")?"operator":"viewer",session=await auth(minimum);if(!session)return fail("unauthorized",401);try{- if(q.get("directory")==="1"){const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(maxScope()).filter((tool)=>!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0,150),graphs=await listWorkflowGraphs(session.principal),sessions=await listAgentSessions(session.principal,50);return NextResponse.json({tools,workflows:graphs.filter((graph)=>!query||`${graph.name} ${graph.description} ${(graph.metadata.tags??[]).join(" ")}`.toLowerCase().includes(query)).map((graph)=>({id:graph.id,name:graph.name,status:graph.status,nodeCount:graph.nodes.length,updatedAt:graph.updatedAt})),sessions:sessions.filter((row)=>!query||`${agentSessionLabel(row.name,row.title,row.cwd)} ${row.title} ${row.name} ${row.cwd??""}`.toLowerCase().includes(query)).map((row)=>({...row,label:agentSessionLabel(row.name,row.title,row.cwd)}))},{headers});}+ if(q.get("directory")==="1"){+ const query=(q.get("q")??"").toLowerCase().trim(),tools=msoCapabilityRuntime.list(maxScope()).filter((tool)=>!query||`${tool.name} ${tool.description} ${tool.scope}`.toLowerCase().includes(query)).slice(0,150);+ const operator=roleAtLeast(session.context.role,"operator");+ const [graphs,sessions,projectResult,skillResult]=await Promise.all([listWorkflowGraphs(session.principal),listAgentSessions(session.principal,50),operator?listProjects({query:query||undefined,limit:100}):Promise.resolve(null),operator?catalogSkillsDetailed():Promise.resolve(null)]);+ const projects=projectResult?.projects.map((row)=>({id:row.id,name:row.name,...(row.packageName?{packageName:row.packageName}:{}),...(row.packageVersion?{packageVersion:row.packageVersion}:{}),...(row.git?.branch?{branch:row.git.branch}:{}),...(row.git?.head?{head:row.git.head}:{})}))??[];+ const skills=skillResult?.skills.filter((row)=>!query||`${row.id} ${row.name} ${row.description} ${row.source} ${row.trust} ${row.project?.name??""}`.toLowerCase().includes(query)).slice(0,150).map((row)=>({id:row.id,name:row.name,description:row.description,source:row.source,trust:row.trust,...(row.project?{project:row.project.name}:{})}))??[];+ return NextResponse.json({tools,workflows:graphs.filter((graph)=>!query||`${graph.name} ${graph.description} ${(graph.metadata.tags??[]).join(" ")}`.toLowerCase().includes(query)).map((graph)=>({id:graph.id,name:graph.name,status:graph.status,nodeCount:graph.nodes.length,updatedAt:graph.updatedAt})),sessions:sessions.filter((row)=>!query||`${agentSessionLabel(row.name,row.title,row.cwd)} ${row.title} ${row.name} ${row.cwd??""}`.toLowerCase().includes(query)).map((row)=>({...row,label:agentSessionLabel(row.name,row.title,row.cwd)})),projects,skills},{headers});+ }if(q.get("scripts")==="1"){const hint=q.get("project")?.trim();if(!hint)throw new Error("project is required");const project=await resolveProjectHint(hint);if(!project||project.matchedBy==="fuzzy")throw new Error("exact project not found");const query=(q.get("q")??"").toLowerCase().trim(),scripts=(await listAutomationScripts(project.path)).filter((script)=>!query||`${script.id} ${script.intent} ${script.status} ${script.steps.map((step)=>step.tool).join(" ")}`.toLowerCase().includes(query)).map((script)=>({id:script.id,intent:script.intent,status:script.status,stepCount:script.steps.length,updatedAt:script.updatedAt,project:script.project,tools:script.steps.map((step)=>step.tool)}));return NextResponse.json({project:project.id,scripts},{headers});}if(q.get("learning")==="1"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);const recipes=(await listLearnedRecipes({ownerView:true})).slice(0,100);const rows=await Promise.all(recipes.map(async(recipe)=>{const maturity=recipeMaturity(recipe),sources=[...new Map(recipe.bestSteps.map((step)=>step.provenance).filter(Boolean).map((source)=>[source!.sessionLabel,source!])).values()];let scriptStatus:"candidate"|"tested"|undefined;if(recipe.project){const project=await resolveProjectHint(recipe.project).catch(()=>null);if(project&&project.matchedBy!=="fuzzy")scriptStatus=(await readAutomationScript(project.path,`script_${recipe.id}`).catch(()=>null))?.status;}return{id:recipe.id,intent:recipe.intent,project:recipe.project,maturity:maturity.maturity,stage:scriptStatus==="tested"?"tested":maturity.maturity,scriptStatus,attempts:recipe.attempts,successes:recipe.successes,failures:recipe.failures,successRate:Math.round(maturity.successRate*1000)/10,fastestDurationMs:recipe.fastestDurationMs,updatedAt:recipe.updatedAt,sourceSessions:sources.map((source)=>({label:source.sessionLabel,actionRef:source.actionRef,eventRef:source.eventRef,artifactRefs:source.artifactRefs??[]})),forge:{eligible:recipe.qualityVersion===1&&recipe.successes>=2&&recipe.attempts>0&&recipe.successes/recipe.attempts>=0.9&&recipe.bestSteps.length>0&&recipe.bestSteps.every((step)=>step.state==="completed"),promotion:"explicit" as const}};}));return NextResponse.json({recipes:rows},{headers});}if(q.get("catalog")==="1")return NextResponse.json({nodes:workflowNodeCatalog(q.get("q")??"")},{headers});diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 799e1f35..bbd07487 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -76,6 +76,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `workflows` finish edge controls and directory- `workflows` complete canvas runtime- `canvas` unify organization and workflow navigation- `organization` surface as first-class appdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 725b531a..195a6880 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -53,6 +53,11 @@ Added `render_mso_list` + `ui://mso/list-v1.html` as the lightweight collection- WHY: make routing, target, source-of-truth, validation, confirmation, concurrency, and OpenAI presentation machine-readable without replacing MSO's stronger trust/provenance, bounded scopes, CAS/revision guards, workflow isolation, evidence receipts, dynamic project MCP boundaries, explicit confirmations, or shell escape hatch.- Kept all 112 ChatGPT actions and the 97,350-byte compact action profile; per-tool action contracts stay on the full MCP descriptor while OpenAI receives the structured workflow policy through skill resources, preserving the scanner budget without hiding capabilities.- Re-reviewed the refreshed Shopify reference implementation: adopted its offline/local schema-validation and per-skill OpenAI descriptor ideas, but did not copy external prompt/code telemetry. The live OAuth `/mcp` app remains a separate connection from the skill-only Codex/OpenAI plugin package.+## 2026-09-15 — Workflow edges and Directory close the remaining n8n-style interaction gaps++Workflow Graph v2 already had the real server-native pieces—schedule/webhook triggers, cache, memory, sessions, capability tools, project functions/MCP, organization-seat agent routing, run history, versions and variables—but two editor gaps still made the surface feel incomplete. Connections now persist an explicit **Auto / Solid / Dashed** presentation, an **Active** execution toggle, directional arrows and a guarded reverse-direction action. A disabled connection stays visible for documentation/debugging and is recorded as disabled in run receipts, but it cannot be re-enabled by source execution, affect cycle/tidy topology, or accidentally promote its target into a new executable root.++The Workflow Directory now exposes the five runtime registries users actually work with: **Tools, Workflows, Sessions, Projects and Skills**. Project/skill metadata is added only for Operator/Owner sessions so the existing Viewer boundary is not widened. The web UI and Directory nodes continue to reuse MSO's project/Skill SSOTs rather than introducing another catalog. Release E2E covers the 5/5 graph controls, responsive canvas/drawers, minimap content, project/skill directory, edge style/active/reverse controls, real cache/memory/session/directory execution and Organization responsiveness.## 2026-09-15 — Shell-native server status + CI security fixesdiff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex 42433ca4..a2255117 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -129,15 +129,17 @@ AI assistance has an isolated workflow-design system prompt, receives no implici- searchable node palette- draggable canvas- 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- structured trigger/action/retry inspectors plus advanced JSON- real project/folder navigation+- one live Directory for Tools, Workflows, Sessions, Projects and Skills (the same registries used by runtime nodes)- execution log + persisted history- graph version restore- private variable/secret manager- template and AI-assisted creation-Run automatically saves a dirty graph before execution, so execution always uses the revision visible in the editor.+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.## CLIdiff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsxindex ad085a10..d06beeae 100644--- a/frontend/slices/workflows/components/workflow-canvas.tsx+++ b/frontend/slices/workflows/components/workflow-canvas.tsx@@ -39,9 +39,11 @@ function WorkflowNodeCard({data,selected}:NodeProps<FlowNode>){const nodeTypes={workflow:WorkflowNodeCard};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=state==="disabled";+ 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)";- return {animated:running&&!disabled,style:{stroke,strokeWidth:running?2.5:state==="enabled"?2:1.5,opacity:disabled?.24:state==="pending"?.55:1,strokeDasharray:disabled?"2 6":branch?"7 5":undefined},markerEnd:{type:MarkerType.ArrowClosed,width:18,height:18,color:stroke}};+ 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 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)";}@@ -51,5 +53,5 @@ export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onConnect,nodeSconst 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)} 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}/>+ 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}/>}diff --git a/frontend/slices/workflows/components/workflow-directory-panel.tsx b/frontend/slices/workflows/components/workflow-directory-panel.tsxindex 4f60eb20..c433769a 100644--- a/frontend/slices/workflows/components/workflow-directory-panel.tsx+++ b/frontend/slices/workflows/components/workflow-directory-panel.tsx@@ -1,23 +1,60 @@"use client";+import { useEffect, useMemo, useState } from "react";-import { Database, Search, Workflow, Wrench } from "lucide-react";+import { Database, FolderKanban, Search, Sparkles, Workflow, Wrench } from "lucide-react";import { Input } from "@/components/ui/input";import { ScrollArea } from "@/components/ui/scroll-area";import { listWorkflowDirectory, type WorkflowDirectory } from "../lib/api";-type View = "tools" | "workflows" | "sessions";-type DirectoryRow = WorkflowDirectory["tools"][number] | WorkflowDirectory["workflows"][number] | WorkflowDirectory["sessions"][number];+type View = keyof WorkflowDirectory;+type DirectoryRow = WorkflowDirectory[View][number];+const VIEWS = ["tools", "workflows", "sessions", "projects", "skills"] as const;+const ICONS = { tools: Wrench, workflows: Workflow, sessions: Database, projects: FolderKanban, skills: Sparkles };function rowTitle(row: DirectoryRow): string {- if ("source" in row) return row.label || `${row.name}-${row.title}`;- return row.name;+ return "title" in row ? row.label || `${row.name}-${row.title}` : row.name;}function rowKey(row: DirectoryRow): string { return "id" in row ? row.id : row.name; }+function searchText(row: DirectoryRow): string {+ return [rowTitle(row), "description" in row ? row.description : "", "scope" in row ? row.scope : "",+ "status" in row ? row.status : "", "source" in row ? row.source : "", "trust" in row ? row.trust : "",+ "packageName" in row ? row.packageName : "", "branch" in row ? row.branch : "",+ "cwd" in row ? row.cwd : ""].join(" ").toLowerCase();+}export function WorkflowDirectoryPanel() {- const [view, setView] = useState<View>("tools"), [query, setQuery] = useState(""), [data, setData] = useState<WorkflowDirectory | null>(null), [error, setError] = useState("");- useEffect(() => { let alive = true; void listWorkflowDirectory().then((value)=>{if(alive)setData(value);}).catch((e)=>{if(alive)setError(e instanceof Error?e.message:"Directory unavailable");}); return()=>{alive=false;}; }, []);- const q=query.toLowerCase().trim();- const rows = useMemo<DirectoryRow[]>(()=> view==="tools"?(data?.tools??[]).filter((r)=>!q||`${r.name} ${r.description} ${r.scope}`.toLowerCase().includes(q)):view==="workflows"?(data?.workflows??[]).filter((r)=>!q||`${r.name} ${r.status}`.toLowerCase().includes(q)):(data?.sessions??[]).filter((r)=>!q||`${r.label??""} ${r.title} ${r.name} ${r.cwd??""}`.toLowerCase().includes(q)),[data,q,view]);- const icons={tools:Wrench,workflows:Workflow,sessions:Database}, Icon=icons[view];- return <div className="flex h-full min-h-0 flex-col"><div className="space-y-2 border-b p-2"><div className="grid grid-cols-3 gap-1">{(["tools","workflows","sessions"] as const).map((item)=><button key={item} type="button" className={`rounded-md px-2 py-1.5 text-[10px] capitalize ${view===item?"bg-accent font-semibold":"text-muted-foreground hover:bg-accent/60"}`} onClick={()=>setView(item)}>{item}</button>)}</div><div className="relative"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/><Input className="h-8 pl-7" placeholder={`Search ${view}…`} value={query} onChange={(e)=>setQuery(e.target.value)}/></div></div><ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">{error?<p className="p-2 text-xs text-destructive">{error}</p>:null}{rows.map((row)=><div key={rowKey(row)} className="rounded-lg border p-2"><div className="flex items-center gap-2"><Icon className="size-3.5 text-muted-foreground"/><div className="min-w-0 flex-1 truncate text-xs font-semibold">{rowTitle(row)}</div>{"inputSchema" in row?<span className="text-[9px] uppercase text-muted-foreground">{row.scope}</span>:null}</div>{"inputSchema" in row?<p className="mt-1 line-clamp-2 text-[10px] text-muted-foreground">{row.description}</p>:null}{"nodeCount" in row?<p className="mt-1 text-[10px] text-muted-foreground">{row.status} · {row.nodeCount} nodes</p>:null}{"source" in row?<p className="mt-1 truncate text-[10px] text-muted-foreground">{row.source} · {row.title}</p>:null}</div>)}{rows.length===0&&!error?<p className="p-3 text-xs text-muted-foreground">No matching {view}.</p>:null}</div></ScrollArea></div>;+ const [view, setView] = useState<View>("tools");+ const [query, setQuery] = useState("");+ const [data, setData] = useState<WorkflowDirectory | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ let alive = true;+ void listWorkflowDirectory().then(value => { if (alive) setData(value); })+ .catch((e: unknown) => { if (alive) setError(e instanceof Error ? e.message : "Directory unavailable"); });+ return () => { alive = false; };+ }, []);+ const q = query.toLowerCase().trim();+ const rows = useMemo<DirectoryRow[]>(() => (data?.[view] ?? []).filter(row => !q || searchText(row).includes(q)), [data, q, view]);+ const Icon = ICONS[view];+ return <div className="flex h-full min-h-0 flex-col">+ <div className="space-y-2 border-b p-2">+ <div className="grid grid-cols-5 gap-1">{VIEWS.map(item => <button key={item} type="button"+ className={`rounded-md px-2 py-1.5 text-[10px] capitalize ${view === item ? "bg-accent font-semibold" : "text-muted-foreground hover:bg-accent/60"}`}+ onClick={() => setView(item)}>{item}</button>)}</div>+ <div className="relative"><Search className="absolute left-2 top-2.5 size-3 text-muted-foreground"/>+ <Input className="h-8 pl-7" placeholder={`Search ${view}…`} value={query} onChange={e => setQuery(e.target.value)}/></div>+ </div>+ <ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">+ {error ? <p className="p-2 text-xs text-destructive">{error}</p> : null}+ {rows.map(row => <div key={rowKey(row)} className="rounded-lg border p-2">+ <div className="flex items-center gap-2"><Icon className="size-3.5 text-muted-foreground"/>+ <div className="min-w-0 flex-1 truncate text-xs font-semibold">{rowTitle(row)}</div>+ {"scope" in row ? <span className="text-[9px] uppercase text-muted-foreground">{row.scope}</span> : null}</div>+ {"description" in row ? <p className="mt-1 line-clamp-2 text-[10px] text-muted-foreground">{row.description}</p> : null}+ {"nodeCount" in row ? <p className="mt-1 text-[10px] text-muted-foreground">{row.status} · {row.nodeCount} nodes</p> : null}+ {"source" in row ? <p className="mt-1 truncate text-[10px] text-muted-foreground">{row.source} · {"trust" in row ? row.trust : row.title}</p> : null}+ {"branch" in row ? <p className="mt-1 truncate text-[10px] text-muted-foreground">{row.branch ?? "no git"}{row.packageName ? ` · ${row.packageName}` : ""}</p> : null}+ </div>)}+ {rows.length === 0 && !error ? <p className="p-3 text-xs text-muted-foreground">No matching {view}.</p> : null}+ </div></ScrollArea>+ </div>;}diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsxindex dbdcfec3..3fee5e0c 100644--- a/frontend/slices/workflows/components/workflow-inspector.tsx+++ b/frontend/slices/workflows/components/workflow-inspector.tsx@@ -1,6 +1,6 @@"use client";import { useMemo, useState } from "react";-import { Copy, FolderOpen, Trash2 } from "lucide-react";+import { ArrowLeftRight, Copy, FolderOpen, Trash2 } from "lucide-react";import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType } from "@/lib/contracts/workflow-graph";import { WORKFLOW_GRAPH_NODE_TYPES } from "@/lib/contracts/workflow-graph";import { Button } from "@/components/ui/button";@@ -24,6 +24,8 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraphif(!node){const tags=graph.metadata.tags?.join(", ")??"";return <div className="space-y-4 p-3 text-xs"><div className="font-semibold">Workflow settings</div><Field label="Description"><Textarea value={graph.description} onChange={(e)=>onGraph({...graph,description:e.target.value})}/></Field><Field label="Folder"><Input value={graph.metadata.folder??""} placeholder="Automation / Operations" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,folder:e.target.value||undefined}})}/></Field><Field label="Tags"><Input value={tags} placeholder="deploy, qa, daily" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,tags:e.target.value.split(",").map((v)=>v.trim()).filter(Boolean).slice(0,32)}})}/></Field><Field label="Timezone"><Input value={graph.metadata.timezone??"UTC"} placeholder="UTC" onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,timezone:e.target.value||undefined}})}/></Field><Field label="Error workflow"><select className={selectClass} value={graph.metadata.errorWorkflowId??""} onChange={(e)=>onGraph({...graph,metadata:{...graph.metadata,errorWorkflowId:e.target.value||undefined}})}><option value="">None</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><p className="text-[10px] text-muted-foreground">Active schedule/webhook triggers execute server-side. Workflow data, versions, runs and variables stay private to the authenticated principal.</p></div>;}const projectValue=String(node.config.project??graph.metadata.project??"");const patch=(next:Partial<WorkflowGraphNode>)=>onNode({...node,...next}),setConfig=(key:string,value:unknown)=>patch({config:{...node.config,[key]:value}}),removeConfig=(key:string)=>{const next={...node.config};delete next[key];patch({config:next});};+ const patchEdge=(id:string,patch:Partial<WorkflowGraph["edges"][number]>)=>onGraph({...graph,edges:graph.edges.map((edge)=>edge.id===id?{...edge,...patch}:edge)});+ const reverseEdge=(id:string)=>onGraph({...graph,edges:graph.edges.map((edge)=>edge.id===id?{...edge,source:edge.target,target:edge.source,sourceHandle:undefined,targetHandle:undefined}:edge)});const applyAdvanced=(text:string)=>{try{const value=JSON.parse(text);if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("Config must be an object");patch({config:value as Record<string,unknown>});setAdvancedError("");}catch(e){setAdvancedError(e instanceof Error?e.message:"Invalid JSON");}};const openTarget=async()=>{const resolved=await resolveNode(graph.id,node.id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};const copyWebhook=()=>void navigator.clipboard?.writeText(`${window.location.origin}/api/v1/workflows/webhook/${graph.id}/${node.id}`);@@ -52,7 +54,10 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph{actionNode&&<div className="space-y-3 rounded-lg border p-3"><div className="font-medium">Failure policy</div><Field label="Attempts"><Input type="number" min={1} max={5} value={number((node.config.retry as Record<string,unknown>|undefined)?.maxAttempts,1)} onChange={(e)=>setConfig("retry",{...((node.config.retry as Record<string,unknown>|undefined)??{}),maxAttempts:Number(e.target.value)})}/></Field><Field label="Backoff ms"><Input type="number" min={0} max={30000} value={number((node.config.retry as Record<string,unknown>|undefined)?.backoffMs,0)} onChange={(e)=>setConfig("retry",{...((node.config.retry as Record<string,unknown>|undefined)??{}),backoffMs:Number(e.target.value)})}/></Field><label className="flex items-center justify-between"><span>Continue on error</span><Switch checked={node.config.onError==="continue"} onCheckedChange={(checked)=>checked?setConfig("onError","continue"):removeConfig("onError")}/></label><p className="text-[10px] text-muted-foreground">Connect the red error port for an explicit error branch.</p></div>}{(node.type==="project"||node.type==="folder")&&<Button variant="secondary" size="sm" className="w-full" onClick={()=>void openTarget()}><FolderOpen className="mr-2 size-3"/>Open real folder</Button>}<details><summary className="cursor-pointer font-medium">Advanced config JSON</summary><div className="mt-2 space-y-2"><AdvancedConfig key={JSON.stringify(node.config)} value={node.config} onApply={applyAdvanced}/>{advancedError&&<p className="text-destructive">{advancedError}</p>}</div></details>- <div className="space-y-2"><div className="font-medium">Connections</div>{outgoing.map((edge)=><div key={edge.id} className="flex items-center justify-between rounded border p-2"><span className="truncate">{edge.sourceHandle?`${edge.sourceHandle} → `:"→ "}{graph.nodes.find((item)=>item.id===edge.target)?.name??edge.target}</span><Button size="icon" variant="ghost" onClick={()=>onGraph({...graph,edges:graph.edges.filter((item)=>item.id!==edge.id)})}><Trash2 className="size-3"/></Button></div>)}<p className="text-[10px] text-muted-foreground">Connect nodes directly from canvas ports.</p></div>+ <div className="space-y-2"><div className="font-medium">Connections</div>{outgoing.map((edge)=>{+ const target=graph.nodes.find((item)=>item.id===edge.target),reverseBlocked=["manual","schedule","webhook"].includes(node.type)||target?.type==="output";+ return <div key={edge.id} className="space-y-2 rounded border p-2"><div className="flex items-center gap-2"><span className="min-w-0 flex-1 truncate">{edge.sourceHandle?`${edge.sourceHandle} → `:"→ "}{target?.name??edge.target}</span><Button size="icon" variant="ghost" title="Reverse direction" aria-label={`Reverse ${node.name} to ${target?.name??edge.target}`} disabled={reverseBlocked} onClick={()=>reverseEdge(edge.id)}><ArrowLeftRight className="size-3"/></Button><Button size="icon" variant="ghost" aria-label={`Delete connection to ${target?.name??edge.target}`} onClick={()=>onGraph({...graph,edges:graph.edges.filter((item)=>item.id!==edge.id)})}><Trash2 className="size-3"/></Button></div><div className="grid grid-cols-[minmax(0,1fr)_auto] items-end gap-2"><Field label="Line style"><select className={selectClass} value={edge.style??"auto"} onChange={(e)=>patchEdge(edge.id,{style:e.target.value==="auto"?undefined:e.target.value as "solid"|"dashed"})}><option value="auto">Auto</option><option value="solid">Solid</option><option value="dashed">Dashed</option></select></Field><label className="flex h-9 items-center gap-2"><Switch checked={!edge.disabled} onCheckedChange={(checked)=>patchEdge(edge.id,{disabled:checked?undefined:true})}/><span>Active</span></label></div>{reverseBlocked?<p className="text-[9px] text-muted-foreground">Reverse is blocked when it would target a trigger or make Output a source.</p>:null}</div>;+ })}<p className="text-[10px] text-muted-foreground">Click an edge to focus its source node. Style is visual; Active controls execution/topology. Reverse swaps execution direction and is validated on save.</p></div><Button variant="destructive" size="sm" className="w-full" onClick={()=>onDeleteNode(node.id)}><Trash2 className="mr-2 size-3"/>Delete node</Button></div>;}diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.tsindex 5cf23aa6..09c95447 100644--- a/frontend/slices/workflows/lib/api.ts+++ b/frontend/slices/workflows/lib/api.ts@@ -36,7 +36,13 @@ export type SessionArtifactHistoryView = {export type SessionArtifactHistoryResponse = {artifact:{ref:string;revisionRef:string;path:string;relativePath:string;label:string;kind:"file"|"script";language?:string};history:SessionArtifactHistoryView};export async function getSessionArtifactHistory(id:string,actionRef:string){const q=new URLSearchParams({view:"artifact",id,action_ref:actionRef});return json<SessionArtifactHistoryResponse>(`/api/v1/agent-sessions?${q}`);}-export type WorkflowDirectory = {tools:Array<{name:string;description:string;scope:string;inputSchema:Record<string,unknown>}>;workflows:Array<{id:string;name:string;status:string;nodeCount:number;updatedAt:string}>;sessions:Array<{id:string;label?:string;title:string;name:string;updatedAt:string;cwd?:string;source:string}>};+export type WorkflowDirectory = {+ tools:Array<{name:string;description:string;scope:string;inputSchema:Record<string,unknown>}>;+ workflows:Array<{id:string;name:string;status:string;nodeCount:number;updatedAt:string}>;+ sessions:Array<{id:string;label?:string;title:string;name:string;updatedAt:string;cwd?:string;source:string}>;+ projects:Array<{id:string;name:string;packageName?:string;packageVersion?:string;branch?:string;head?:string}>;+ skills:Array<{id:string;name:string;description:string;source:string;trust:string;project?:string}>;+};export async function listWorkflowDirectory(query=""){return cachedWorkflowResource(`directory:${query}`,15000,()=>json<WorkflowDirectory>(`/api/v1/workflows?directory=1&q=${encodeURIComponent(query)}`));}export type WorkflowScriptSummary = { id:string; intent:string; status:"candidate"|"tested"; stepCount:number; updatedAt:string; project?:string; tools:string[] };diff --git a/frontend/slices/workflows/lib/canvas-layout.ts b/frontend/slices/workflows/lib/canvas-layout.tsindex 10b47525..b5ebf2f6 100644--- a/frontend/slices/workflows/lib/canvas-layout.ts+++ b/frontend/slices/workflows/lib/canvas-layout.ts@@ -7,7 +7,7 @@ const START_Y = 72;export function tidyWorkflowNodes(graph: WorkflowGraph): WorkflowGraphNode[] {const byId = new Map(graph.nodes.map((node) => [node.id, node]));- const incoming = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => edge.target === node.id && byId.has(edge.source))]));+ const incoming = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => !edge.disabled && edge.target === node.id && byId.has(edge.source))]));const indegree = new Map(graph.nodes.map((node) => [node.id, incoming.get(node.id)?.length ?? 0]));const layer = new Map<string, number>();const queue = graph.nodes.filter((node) => (indegree.get(node.id) ?? 0) === 0).sort((a, b) => a.position.y - b.position.y || a.name.localeCompare(b.name));@@ -16,7 +16,7 @@ export function tidyWorkflowNodes(graph: WorkflowGraph): WorkflowGraphNode[] {for (let index = 0; index < queue.length; index += 1) {const current = queue[index]!;const currentLayer = layer.get(current.id) ?? 0;- for (const edge of graph.edges.filter((row) => row.source === current.id && byId.has(row.target))) {+ for (const edge of graph.edges.filter((row) => !row.disabled && row.source === current.id && byId.has(row.target))) {layer.set(edge.target, Math.max(layer.get(edge.target) ?? 0, currentLayer + 1));const next = (indegree.get(edge.target) ?? 1) - 1;indegree.set(edge.target, next);diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.tsindex f4cce601..d677d37d 100644--- a/lib/contracts/workflow-graph.ts+++ b/lib/contracts/workflow-graph.ts@@ -20,6 +20,10 @@ export type WorkflowGraphEdge = {target: string;sourceHandle?: string;targetHandle?: string;+ /** Optional visual override. Branch/error semantics may still color the edge. */+ style?: "solid" | "dashed";+ /** Disabled edges stay visible in the editor but are excluded from execution/topology. */+ disabled?: boolean;};export type WorkflowGraphMetadata = {diff --git a/lib/workflow/ai-assist.ts b/lib/workflow/ai-assist.tsindex 0ba9a12b..54ca0b91 100644--- a/lib/workflow/ai-assist.ts+++ b/lib/workflow/ai-assist.ts@@ -4,7 +4,7 @@ import { parseWorkflowGraphDefinition } from "./graph-schema";export async function suggestWorkflowGraph(prompt:string){const request=prompt.trim();if(!request||request.length>4000)throw new Error("workflow AI prompt must be 1-4000 characters");const prepared=await prepareSelectedModel(),abort=new AbortController(),timer=setTimeout(()=>abort.abort(new Error("workflow AI suggestion timed out")),45_000);let text="";- const system=["Design one MSO workflow graph as strict JSON only. No markdown.",`Allowed node types: ${WORKFLOW_GRAPH_NODE_TYPES.join(", ")}.`,`Return keys: name, description, status, inputs, metadata, nodes, edges. Status must be draft.`,"Every node needs id,name,type,position{x,y},config. Every edge needs id,source,target and optional sourceHandle.","Never output credentials, tokens, passwords, cookies, authorization headers, or secret values. Use {$var:\"NAME\"} for runtime private variables and integration nodes for credential-backed provider actions.","Use schedule/webhook nodes only as roots. Use true/false handles for condition, named handles/default for switch, error handle for failure branches. Prefer DRY subflows and explicit output nodes."].join(" ");+ const system=["Design one MSO workflow graph as strict JSON only. No markdown.",`Allowed node types: ${WORKFLOW_GRAPH_NODE_TYPES.join(", ")}.`,`Return keys: name, description, status, inputs, metadata, nodes, edges. Status must be draft.`,"Every node needs id,name,type,position{x,y},config. Every edge needs id,source,target and optional sourceHandle, style (solid|dashed), disabled (boolean).","Never output credentials, tokens, passwords, cookies, authorization headers, or secret values. Use {$var:\"NAME\"} for runtime private variables and integration nodes for credential-backed provider actions.","Use schedule/webhook nodes only as roots. Use true/false handles for condition, named handles/default for switch, error handle for failure branches. Prefer DRY subflows and explicit output nodes."].join(" ");try{await streamPreparedSelectedModel({prepared,messages:[{role:"user",text:request}],system,signal:abort.signal,emit:(event,data)=>{if(event==="delta"&&typeof data==="string"&&text.length<256*1024)text+=data;}});}finally{clearTimeout(timer);}const clean=text.replace(/^```(?:json)?\s*/i,"").replace(/\s*```$/,""),start=clean.indexOf("{"),end=clean.lastIndexOf("}");if(start<0||end<=start)throw new Error("workflow AI did not return JSON");let raw:unknown;try{raw=JSON.parse(clean.slice(start,end+1));}catch{throw new Error("workflow AI returned invalid JSON");}diff --git a/lib/workflow/graph-engine.test.ts b/lib/workflow/graph-engine.test.tsindex 3f7ab530..da0e00bc 100644--- a/lib/workflow/graph-engine.test.ts+++ b/lib/workflow/graph-engine.test.ts@@ -32,6 +32,24 @@ describe("workflow graph engine", () => {expect(done.edges?.find((edge) => edge.id === "b")?.state).toBe("enabled");expect(done.edges?.find((edge) => edge.id === "c")?.state).toBe("disabled");});++ it("keeps disabled connections visible in receipts but excludes them from execution", async () => {+ const graph = await createWorkflowGraph("graph-owner", { name: "Disabled edge", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [+ { id: "start-disabled", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },+ { id: "live", name: "Live", type: "output", position: { x: 140, y: 0 }, config: { value: "live" } },+ { id: "offline", name: "Offline", type: "output", position: { x: 140, y: 120 }, config: { value: "offline" } },+ ], edges: [+ { id: "live-edge", source: "start-disabled", target: "live" },+ { id: "disabled-edge", source: "start-disabled", target: "offline", style: "dashed", disabled: true },+ ] });+ const started = await startWorkflowGraph(graph, {}, "disabled-edge-once", context, () => undefined);+ const done = await workflowGraphRunStatus("graph-owner", started.id, 5000);+ expect(done.state).toBe("completed");+ expect(done.nodes.find((node) => node.id === "live")?.state).toBe("completed");+ expect(done.nodes.find((node) => node.id === "offline")?.state).toBe("skipped");+ expect(done.edges?.find((edge) => edge.id === "disabled-edge")?.state).toBe("disabled");+ });+it("pinpoints the failed node and blocks downstream nodes", async () => {const graph = await createWorkflowGraph("graph-owner", { name: "Failure", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [{ id: "start2", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.tsindex f3a40468..72143d1c 100644--- a/lib/workflow/graph-engine.ts+++ b/lib/workflow/graph-engine.ts@@ -34,8 +34,10 @@ function secretValue(value:unknown,secrets:string[],depth=0):unknown{if(depth>14async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Record<string, unknown>, context: CapabilityRunContext, resolve: Resolver): Promise<void> {const rows = new Map(run.nodes.map((row) => [row.id, row])), outputs: Record<string, unknown> = {}, secrets = await workflowSecretValues(context.principal ?? context.actor ?? "");- const edgeState = new Map(graph.edges.map((edge) => [edge.id, run.edges?.find((row) => row.id === edge.id)?.state ?? "pending" as WorkflowGraphRunEdgeState]));- const incoming = new Map(graph.nodes.map((node)=>[node.id,graph.edges.filter((edge)=>edge.target===node.id)])), outgoing = new Map(graph.nodes.map((node)=>[node.id,graph.edges.filter((edge)=>edge.source===node.id)]));+ const activeEdges = graph.edges.filter((edge) => !edge.disabled);+ const edgeState = new Map(graph.edges.map((edge) => [edge.id, edge.disabled ? "disabled" as WorkflowGraphRunEdgeState : run.edges?.find((row) => row.id === edge.id)?.state ?? "pending" as WorkflowGraphRunEdgeState]));+ // Keep disabled incoming edges as disabled dependencies so a node whose only route is inactive is skipped, not promoted to a new root. Outgoing resolution touches active edges only.+ const incoming = new Map(graph.nodes.map((node)=>[node.id,graph.edges.filter((edge)=>edge.target===node.id)])), outgoing = new Map(graph.nodes.map((node)=>[node.id,activeEdges.filter((edge)=>edge.source===node.id)]));const setEdge=(id:string,state:WorkflowGraphRunEdgeState)=>{edgeState.set(id,state);const row=run.edges?.find((item)=>item.id===id);if(row)row.state=state;};const disableOutgoing=(id:string)=>{for(const edge of outgoing.get(id)??[])if(edgeState.get(edge.id)==="pending")setEdge(edge.id,"disabled");};const resolveOutgoing=(id:string,handles?:string[])=>{for(const edge of outgoing.get(id)??[]){const enabled=handles?Boolean(edge.sourceHandle&&handles.includes(edge.sourceHandle)):!edge.sourceHandle;setEdge(edge.id,enabled?"enabled":"disabled");}};@@ -70,6 +72,6 @@ export function workflowGraphRunId(owner:string,key:string){return hash(`${ownerexport async function startWorkflowGraph(graph: WorkflowGraph, rawInput: unknown, idempotencyKey: string, context: CapabilityRunContext, resolve: Resolver, storagePrincipal?: string, trigger?: WorkflowRunTrigger, ancestry: string[] = []) {const principal=storagePrincipal??context.principal;if(!principal||!context.sessionId)throw new Error("workflow graph requires an authenticated principal/session");if(ancestry.includes(graph.id)||ancestry.length>=16)throw new Error("recursive workflow subflow detected");if(graph.status==="archived")throw new Error("archived workflow graph cannot run");if(!/^[A-Za-z0-9_.:-]{1,128}$/.test(idempotencyKey))throw new Error("idempotency_key must be 1-128 simple characters");const owner=workflowGraphOwner(principal),input=inputObject(rawInput),fingerprint=hash(canonical({graphId:graph.id,revision:graph.revision,input})),id=workflowGraphRunId(owner,idempotencyKey);- return lockWorkflowGraphRun(owner,id,async()=>{const existing=await readWorkflowGraphRun(owner,id);if(existing){if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id]};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>pending.delete(id));pending.set(id,work);return publicWorkflowGraphRun(run);});+ return lockWorkflowGraphRun(owner,id,async()=>{const existing=await readWorkflowGraphRun(owner,id);if(existing){if(existing.fingerprint!==fingerprint)throw new Error("idempotency_key already identifies a different graph/input/revision");return publicWorkflowGraphRun(existing);}await pruneWorkflowGraphRuns(owner);const run:WorkflowGraphRun={version:1,id,owner,sessionId:context.sessionId!,graphId:graph.id,graphRevision:graph.revision,graphName:graph.name,idempotencyKey,fingerprint,state:"running",startedAt:new Date().toISOString(),updatedAt:new Date().toISOString(),pid:process.pid,instance:INSTANCE,nodes:graph.nodes.map((node)=>({id:node.id,name:node.name,type:node.type,state:"queued",logs:[]})),edges:graph.edges.map((edge)=>({id:edge.id,source:edge.source,target:edge.target,...(edge.sourceHandle?{sourceHandle:edge.sourceHandle}:{}),state:edge.disabled?"disabled":"pending"})),trigger:trigger??{type:"manual",nodeId:graph.nodes.find((node)=>node.type==="manual")?.id??graph.nodes.find((node)=>["schedule","webhook"].includes(node.type))?.id,receivedAt:new Date().toISOString()},ancestry:[...ancestry,graph.id]};await writeWorkflowGraphRun(run);await appendAgentSessionEvent(principal,run.sessionId,{kind:"workflow",tool:"workflow_graph",state:"started",workflowId:graph.id,detail:graph.name}).catch(()=>undefined);const work=execute(run,graph,input,context,resolve).then(()=>maybeRunErrorWorkflow(run,graph,context,resolve,principal)).catch(()=>undefined).finally(()=>pending.delete(id));pending.set(id,work);return publicWorkflowGraphRun(run);});}export async function workflowGraphRunStatus(principal:string,id:string,waitMs=0){if(!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>25_000)throw new Error("wait_ms must be 0-25000");const owner=workflowGraphOwner(principal);let run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");if(run.state==="running"&&pending.has(id)&&waitMs>0){let timer:ReturnType<typeof setTimeout>|undefined;await Promise.race([pending.get(id),new Promise((resolve)=>{timer=setTimeout(resolve,waitMs);})]);clearTimeout(timer);run=await readWorkflowGraphRun(owner,id)??run;}if(run.state==="running"&&run.instance!==INSTANCE){let gone=false;try{process.kill(run.pid,0);}catch(error){gone=(error as NodeJS.ErrnoException).code==="ESRCH";}if(gone){run.state="interrupted";run.updatedAt=run.finishedAt=new Date().toISOString();await writeWorkflowGraphRun(run);}}return publicWorkflowGraphRun(run);}diff --git a/lib/workflow/graph-flow-nodes.ts b/lib/workflow/graph-flow-nodes.tsindex 536069e8..bf8e8a5e 100644--- a/lib/workflow/graph-flow-nodes.ts+++ b/lib/workflow/graph-flow-nodes.ts@@ -6,7 +6,7 @@ function items(config:Record<string,unknown>,runtime:unknown){const raw=Array.isexport async function executeFlowNode(node:WorkflowGraphNode,config:Record<string,unknown>,graph:WorkflowGraph,outputs:Record<string,unknown>,runtime:unknown):Promise<FlowNodeResult|null>{if(node.type==="condition"){const ref=typeof config.path==="string"?config.path:"input",value=workflowPath(runtime,ref),branch=Object.hasOwn(config,"equals")?JSON.stringify(value)===JSON.stringify(config.equals):Boolean(value);return{output:{value,branch},handles:[String(branch)],log:`Condition evaluated to ${branch}.`};}if(node.type==="switch"){const ref=typeof config.path==="string"?config.path:"input",value=workflowPath(runtime,ref),cases=Array.isArray(config.cases)?config.cases:[],handles:string[]=[];for(let i=0;i<Math.min(32,cases.length);i++){const row=cases[i];if(!graphObject(row))continue;const handle=typeof row.handle==="string"&&row.handle?row.handle:`case-${i+1}`;if(Object.hasOwn(row,"equals")&&JSON.stringify(value)===JSON.stringify(row.equals))handles.push(handle);}if(!handles.length)handles.push("default");return{output:{value,handles},handles,log:`Switch selected ${handles.join(", ")}.`};}- if(node.type==="merge"){const incoming=graph.edges.filter((edge)=>edge.target===node.id).map((edge)=>({source:edge.source,value:outputs[edge.source]}));const mode=String(config.mode??"combine");let output:unknown;if(mode==="append")output=incoming.flatMap((row)=>Array.isArray(row.value)?row.value:[row.value]);else if(mode==="passThrough")output=incoming.at(-1)?.value??null;else output=Object.fromEntries(incoming.map((row)=>[row.source,row.value]));return{output,log:`Merged ${incoming.length} incoming branch(es) using ${mode}.`};}+ if(node.type==="merge"){const incoming=graph.edges.filter((edge)=>!edge.disabled&&edge.target===node.id).map((edge)=>({source:edge.source,value:outputs[edge.source]}));const mode=String(config.mode??"combine");let output:unknown;if(mode==="append")output=incoming.flatMap((row)=>Array.isArray(row.value)?row.value:[row.value]);else if(mode==="passThrough")output=incoming.at(-1)?.value??null;else output=Object.fromEntries(incoming.map((row)=>[row.source,row.value]));return{output,log:`Merged ${incoming.length} incoming branch(es) using ${mode}.`};}if(node.type==="batch"){const all=items(config,runtime),size=Math.max(1,Math.min(1000,Math.trunc(Number(config.size)||10))),batches=[];for(let i=0;i<all.length;i+=size)batches.push(all.slice(i,i+size));return{output:{items:all,batches,count:batches.length,size},log:`Split ${all.length} item(s) into ${batches.length} batch(es).`};}if(node.type==="wait"){const until=typeof config.until==="string"?Date.parse(config.until):NaN,delay=Number.isFinite(until)?until-Date.now():Number(config.delayMs??0),ms=Math.max(0,Math.min(10*60_000,Math.trunc(delay)||0));if(delay>10*60_000)throw new Error("wait node maximum is 10 minutes per run");if(ms)await new Promise((resolve)=>setTimeout(resolve,ms));return{output:{waitedMs:ms,resumedAt:new Date().toISOString()},log:`Waited ${ms}ms.`};}return null;diff --git a/lib/workflow/graph-schema.test.ts b/lib/workflow/graph-schema.test.tsindex 93cf0b16..8a09db73 100644--- a/lib/workflow/graph-schema.test.ts+++ b/lib/workflow/graph-schema.test.ts@@ -13,6 +13,22 @@ describe("workflow graph schema", () => {it("accepts a bounded acyclic metadata-only graph", () => expect(parseWorkflowGraphDefinition(base()).nodes).toHaveLength(2));it("rejects cycles", () => expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "a", name: "A", type: "tool", position: { x: 0, y: 0 }, config: { tool: "x" } }, { id: "b", name: "B", type: "output", position: { x: 200, y: 0 }, config: {} }], edges: [{ id: "e1", source: "a", target: "b" }, { id: "e2", source: "b", target: "a" }] })).toThrow("cycle"));it("rejects secret-like config fields recursively", () => expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Start", type: "tool", position: { x: 0, y: 0 }, config: { nested: { accessToken: "x" } } }, base().nodes[1]] })).toThrow("secret_input_forbidden"));++ it("persists edge style/active state and ignores disabled edges for topology", () => {+ const parsed = parseWorkflowGraphDefinition({+ ...base(),+ edges: [+ { id: "e1", source: "start", target: "done", style: "dashed", disabled: true },+ { id: "e2", source: "done", target: "start", style: "solid", disabled: true },+ ],+ });+ expect(parsed.edges).toEqual([+ { id: "e1", source: "start", target: "done", style: "dashed", disabled: true },+ { id: "e2", source: "done", target: "start", style: "solid", disabled: true },+ ]);+ expect(() => parseWorkflowGraphDefinition({ ...base(), edges: [{ id: "bad", source: "start", target: "done", style: "dots" }] })).toThrow("edge style");+ });+it("accepts parity node types but keeps triggers root-only", () => {expect(parseWorkflowGraphDefinition({ ...base(), nodes: [{ id: "start", name: "Schedule", type: "schedule", position: { x: 0, y: 0 }, config: { mode: "interval", everyMinutes: 5 } }, { id: "wait", name: "Wait", type: "wait", position: { x: 100, y: 0 }, config: { delayMs: 0 } }, base().nodes[1]], edges: [{ id: "a", source: "start", target: "wait" }, { id: "b", source: "wait", target: "done" }] }).nodes.map((node) => node.type)).toEqual(["schedule", "wait", "output"]);expect(() => parseWorkflowGraphDefinition({ ...base(), nodes: [base().nodes[0], { id: "hook", name: "Hook", type: "webhook", position: { x: 100, y: 0 }, config: {} }], edges: [{ id: "bad", source: "start", target: "hook" }] })).toThrow("root");diff --git a/lib/workflow/graph-schema.ts b/lib/workflow/graph-schema.tsindex ec804b77..3c0486ca 100644--- a/lib/workflow/graph-schema.ts+++ b/lib/workflow/graph-schema.ts@@ -56,7 +56,15 @@ function parseEdge(value: unknown, nodeIds: Set<string>): WorkflowGraphEdge {if (!graphObject(value) || !text(value.id, 96) || !ID.test(value.id) || !text(value.source, 96) || !text(value.target, 96)) throw new Error("invalid workflow edge");if (!nodeIds.has(value.source) || !nodeIds.has(value.target) || value.source === value.target) throw new Error("workflow edge references invalid node");const handle = (key: "sourceHandle" | "targetHandle") => value[key] === undefined ? undefined : (text(value[key], 64) && ID.test(value[key] as string) ? String(value[key]) : (() => { throw new Error("invalid workflow edge handle"); })());- return { id: value.id, source: value.source, target: value.target, ...(handle("sourceHandle") ? { sourceHandle: handle("sourceHandle") } : {}), ...(handle("targetHandle") ? { targetHandle: handle("targetHandle") } : {}) };+ if (value.style !== undefined && !["solid", "dashed"].includes(String(value.style))) throw new Error("invalid workflow edge style");+ if (value.disabled !== undefined && typeof value.disabled !== "boolean") throw new Error("invalid workflow edge disabled flag");+ return {+ id: value.id, source: value.source, target: value.target,+ ...(handle("sourceHandle") ? { sourceHandle: handle("sourceHandle") } : {}),+ ...(handle("targetHandle") ? { targetHandle: handle("targetHandle") } : {}),+ ...(value.style === "dashed" ? { style: "dashed" as const } : value.style === "solid" ? { style: "solid" as const } : {}),+ ...(value.disabled === true ? { disabled: true } : {}),+ };}function assertAcyclic(nodes: WorkflowGraphNode[], edges: WorkflowGraphEdge[]): void {@@ -97,9 +105,10 @@ export function parseWorkflowGraphDefinition(raw: unknown): WorkflowGraphDefinitif (!Array.isArray(raw.edges) || raw.edges.length > 400) throw new Error("workflow graph supports up to 400 edges");const edges = raw.edges.map((edge) => parseEdge(edge, nodeIds));if (new Set(edges.map((edge) => edge.id)).size !== edges.length) throw new Error("duplicate workflow edge id");+ const activeEdges = edges.filter((edge) => !edge.disabled);const triggerIds = new Set(nodes.filter((node) => ["manual", "schedule", "webhook"].includes(node.type)).map((node) => node.id));- if (edges.some((edge) => triggerIds.has(edge.target))) throw new Error("trigger nodes must be workflow roots");- assertAcyclic(nodes, edges);+ 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) };}diff --git a/scripts/cli/organization.sh b/scripts/cli/organization.shindex 1cf36156..058080a8 100644--- a/scripts/cli/organization.sh+++ b/scripts/cli/organization.sh@@ -1,19 +1,56 @@#!/usr/bin/env bash# Owner-private Organization CLI. Same API as Alfa → Organization and MCP.run_org() {- local sub="${1:-show}" revision input action key body id+ local sub="${1:-show}"+ local revision=""+ local input=""+ local action=""+ local key=""+ local body=""+ local id=""shift || true+case "$sub" in- show|list) jget "/api/v1/organization" ;;+ show|list)+ jget "/api/v1/organization"+ ;;unit-upsert|seat-upsert|replace)- revision="${1:?revision}"; input="${2:?JSON or @file}"; case "$input" in @*) input=$(cat -- "${input#@}") ;; esac- action="${sub//-/_}"; key="${sub%%-*}"- if [ "$sub" = replace ]; then body=$(jq -n --arg action "$action" --arg revision "$revision" --argjson chart "$input" '{action:$action,expected_revision:$revision,chart:$chart}')- else body=$(jq -n --arg action "$action" --arg revision "$revision" --arg key "$key" --argjson data "$input" '{action:$action,expected_revision:$revision} + {($key):$data}'); fi- jpost "/api/v1/organization" "$body" ;;+ revision="${1:?revision}"+ input="${2:?JSON or @file}"+ if [[ "$input" == @* ]]; then+ input=$(cat -- "${input#@}")+ fi+ action="${sub//-/_}"+ key="${sub%%-*}"+ if [ "$sub" = "replace" ]; then+ body=$(jq -n \+ --arg action "$action" \+ --arg revision "$revision" \+ --argjson chart "$input" \+ '{action:$action,expected_revision:$revision,chart:$chart}')+ else+ body=$(jq -n \+ --arg action "$action" \+ --arg revision "$revision" \+ --arg key "$key" \+ --argjson data "$input" \+ '{action:$action,expected_revision:$revision} + {($key):$data}')+ fi+ jpost "/api/v1/organization" "$body"+ ;;unit-delete|seat-delete)- revision="${1:?revision}"; id="${2:?id}"; action="${sub//-/_}"- jpost "/api/v1/organization" "$(jq -n --arg action "$action" --arg revision "$revision" --arg id "$id" '{action:$action,expected_revision:$revision,id:$id}')" ;;- *) die "usage: mso $U_org" ;;+ revision="${1:?revision}"+ id="${2:?id}"+ action="${sub//-/_}"+ body=$(jq -n \+ --arg action "$action" \+ --arg revision "$revision" \+ --arg id "$id" \+ '{action:$action,expected_revision:$revision,id:$id}')+ jpost "/api/v1/organization" "$body"+ ;;+ *)+ die "usage: mso ${U_org:-org}"+ ;;esac}diff --git a/scripts/cli/workflows.sh b/scripts/cli/workflows.shindex 052500f6..a617f9c7 100644--- a/scripts/cli/workflows.sh+++ b/scripts/cli/workflows.sh@@ -19,7 +19,9 @@ run_workflow() {*) die "unknown workflow option: $1" ;;esacdone- case "$input" in @*) input=$(cat -- "${input#@}") ;; esac+ if [[ "$input" == @* ]]; then+ input=$(cat -- "${input#@}")+ ficase "$sub" inlist) jget "/api/v1/workflows"; return ;;show) jget "/api/v1/workflows?graph_id=$(enc "$id")"; return ;;@@ -41,6 +43,13 @@ run_workflow() {run) [ -n "$key" ] || die "workflow run requires --key <unique-operation-id>"; body=$(jq -n --arg id "$id" --arg key "$key" --argjson input "$input" '{action:"run",graph_id:$id,input:$input,idempotency_key:$key}'); result=$(jpost "/api/v1/workflows" "$body"); id=$(jq -er .id <<<"$result") ;;*) die "usage: mso ${U_workflow:-workflow}" ;;esac- while [ "$wait" -eq 1 ] && [ "$(jq -r .state <<<"$result")" = running ]; do result=$(jget "/api/v1/workflows?run_id=$(enc "$id")&wait_ms=1500"); done- printf '%s\n' "$result"; case "$(jq -r .state <<<"$result")" in failed|interrupted) return 1 ;; esac+ while [ "$wait" -eq 1 ] && [ "$(jq -r .state <<<"$result")" = "running" ]; do+ result=$(jget "/api/v1/workflows?run_id=$(enc "$id")&wait_ms=1500")+ done+ printf '%s\n' "$result"+ case "$(jq -r .state <<<"$result")" in+ failed|interrupted)+ return 1+ ;;+ esac}diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjsindex d8539029..fc8740e5 100644--- a/scripts/e2e/release-fixture.mjs+++ b/scripts/e2e/release-fixture.mjs@@ -1,5 +1,5 @@import { seedSessionMonitor } from "./session-fixture.mjs";-import { mkdtemp, writeFile, rm, readFile } from "node:fs/promises";+import { mkdir, mkdtemp, writeFile, rm, readFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { createServer } from "node:http";@@ -23,6 +23,10 @@ export async function releaseFixture({ live = false } = {}) {await setRole("owner");if (live) await writeFile(path.join(dir, "prefs.json"), JSON.stringify({ tweaks: { server: { mode: "live", activeTargetId: "vps", url: "" } } }), { mode: 0o600 });await writeFile(path.join(dir, "fixture.txt"), "MSO release fixture");+ // One real project makes Workflow Directory → Projects verifiable without borrowing the host owner's projects.+ const fixtureProject = path.join(dir, "projects", "fixture-project");+ await mkdir(fixtureProject, { recursive: true });+ await writeFile(path.join(fixtureProject, "package.json"), JSON.stringify({ name: "fixture-project", version: "1.0.0", private: true }), { mode: 0o600 });await writeFile(path.join(dir, "infra.json"), JSON.stringify({version: 2, instanceId: randomUUID(), defaultUser: "fixture", bindings: [],users: { fixture: { id: "fixture", uid: randomUUID(), label: "Release fixture", defaults: { convex: "local" },diff --git a/scripts/e2e/workflow-canvas.mjs b/scripts/e2e/workflow-canvas.mjsindex 6b22750e..30fac443 100644--- a/scripts/e2e/workflow-canvas.mjs+++ b/scripts/e2e/workflow-canvas.mjs@@ -95,8 +95,33 @@ export async function workflowCanvasJourney(page, fixture) {await page.getByRole("button", { name: "Directory", exact: true }).click();await expect(page.getByPlaceholder("Search tools…")).toBeVisible();await expect(page.getByText("agent_memory_search", { exact: true })).toBeVisible();+ await page.getByRole("button", { name: "projects", exact: true }).click();+ await expect(page.getByText("fixture-project", { exact: true })).toBeVisible();+ await page.getByRole("button", { name: "skills", exact: true }).click();+ await expect(page.getByText("No matching skills.", { exact: true })).toBeHidden();+ await page.getByRole("button", { name: "Inspector", exact: true }).click();- const active = page.getByRole("switch", { name: "Active" });+ // Connection controls are persisted graph metadata, not temporary React Flow styling.+ await page.locator(".react-flow__node", { hasText: "Manual Trigger" }).click();+ const connectionPanel = page.getByText("Connections", { exact: true }).locator("..");+ const lineStyle = connectionPanel.getByLabel("Line style").first();+ await expect(lineStyle).toHaveValue("auto");+ await lineStyle.selectOption("dashed");+ const connectionActive = connectionPanel.getByRole("switch", { name: "Active" }).first();+ await expect(connectionActive).toBeChecked();+ await connectionActive.click();+ await expect(connectionActive).not.toBeChecked();+ await connectionActive.click();+ await lineStyle.selectOption("solid");++ // Reverse is available for ordinary action edges, then reversible back before execution.+ await page.locator(".react-flow__node", { hasText: "Cache Context" }).click();+ await page.getByRole("button", { name: "Reverse Cache Context to Memory Search" }).click();+ await page.locator(".react-flow__node", { hasText: "Memory Search" }).click();+ await expect(page.getByText(/→ Cache Context/)).toBeVisible();+ await page.getByRole("button", { name: "Reverse Memory Search to Cache Context" }).click();++ const active = page.getByRole("switch", { name: "Active" }).first();await expect(active).not.toBeChecked();await active.click();await expect(active).toBeChecked();@@ -125,5 +150,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, edge semantics, active mode, cache/memory/session/directory runtime and cleanup");+ 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");}