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): split n8n and improve org automation ux
Rahman4374948ddd47
diff --git a/app/api/v1/workflows/route.ts b/app/api/v1/workflows/route.tsindex 836231f7..57bf713b 100644--- a/app/api/v1/workflows/route.ts+++ b/app/api/v1/workflows/route.ts@@ -11,8 +11,8 @@ 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";+import { requestWorkflowGraphStop, startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";+import { deleteWorkflowGraphRun, listWorkflowGraphRuns, readWorkflowGraphRun } from "@/lib/workflow/graph-run-store";import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workflow/graph-version-store";import { resolveWorkflowGraphNodeTarget } from "@/lib/workflow/graph-target";import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } from "@/lib/workflow/variables";@@ -23,11 +23,12 @@ import { workflowMatchesQuery } from "@/lib/workflow/search";import { resolveProjectHint } from "@/lib/host/projects-api";import { listAutomationScripts, readAutomationScript } from "@/lib/orchestration/repo-memory-artifacts";import { listLearnedRecipes, recipeMaturity } from "@/lib/workflow";+import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";export const runtime="nodejs";export const dynamic="force-dynamic";const headers={"Cache-Control":"no-store, private"};const fail=(error:unknown,status=400)=>NextResponse.json({error:error instanceof Error?error.message.slice(0,500):String(error).slice(0,500)||"workflow request failed"},{status,headers});async 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{+export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,minimum=(q.has("variables")||q.has("data_tables")||q.has("data_table"))?"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);const operator=roleAtLeast(session.context.role,"operator");@@ -41,6 +42,8 @@ export async function GET(req:NextRequest){const q=req.nextUrl.searchParams,miniif(q.get("catalog")==="1")return NextResponse.json({nodes:workflowNodeCatalog(q.get("q")??"")},{headers});if(q.get("templates")==="1")return NextResponse.json({templates:workflowTemplates()},{headers});if(q.get("variables")==="1")return NextResponse.json({variables:await listWorkflowVariables(session.principal)},{headers});+ if(q.get("data_tables")==="1")return NextResponse.json({tables:await listWorkflowDataTables(session.principal)},{headers});+ if(q.has("data_table"))return NextResponse.json({table:await getWorkflowDataTable(session.principal,q.get("data_table"))},{headers});if(q.get("runs")==="1")return NextResponse.json(await listWorkflowGraphRuns(workflowGraphOwner(session.principal),{graphId:q.get("graph_id")||undefined,state:(q.get("state")||undefined) as never,limit:Number(q.get("limit"))||30,offset:Number(q.get("offset"))||0}),{headers});if(q.has("versions")){const graphId=q.get("versions")!;return NextResponse.json({versions:await listWorkflowGraphVersions(workflowGraphOwner(session.principal),graphId)},{headers});}if(q.has("run_id"))return NextResponse.json(await workflowGraphRunStatus(session.principal,q.get("run_id")!,Number(q.get("wait_ms"))||0),{headers});@@ -57,5 +60,12 @@ export async function POST(req:NextRequest){const session=await auth("operator")if(action==="restore_version"){const id=String(body.graph_id??""),snapshot=await readWorkflowGraphVersion(workflowGraphOwner(session.principal),id,String(body.revision??""));if(!snapshot)throw new Error("workflow version not found");return NextResponse.json({graph:await updateWorkflowGraph(session.principal,id,String(body.expected_revision??""),definition(snapshot.graph),"restore",{remember:true})},{headers});}if(action==="variable_set"||action==="variable_delete"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json(action==="variable_set"?await setWorkflowVariable(session.principal,String(body.key??""),body.value,body.secret===true):await deleteWorkflowVariable(session.principal,String(body.key??"")),{headers});}if(action==="ai_suggest"){if(!roleAtLeast(session.context.role,"owner"))return fail("owner_required",403);return NextResponse.json({definition:await suggestWorkflowGraph(String(body.prompt??""))},{headers});}+ if(action==="data_table_create")return NextResponse.json({table:await createWorkflowDataTable(session.principal,body.name,body.columns)},{headers});+ if(action==="data_table_delete")return NextResponse.json(await deleteWorkflowDataTable(session.principal,body.table_id),{headers});+ if(action==="data_table_row_upsert")return NextResponse.json({row:await upsertWorkflowDataTableRow(session.principal,body.table_id,body.row_id,body.values)},{headers});+ if(action==="data_table_row_delete")return NextResponse.json(await deleteWorkflowDataTableRow(session.principal,body.table_id,body.row_id),{headers});+ if(action==="run_stop")return NextResponse.json(await requestWorkflowGraphStop(session.principal,String(body.run_id??"")),{headers});+ if(action==="run_delete")return NextResponse.json(await deleteWorkflowGraphRun(workflowGraphOwner(session.principal),String(body.run_id??"")),{headers});+ if(action==="run_retry"){const prior=await readWorkflowGraphRun(workflowGraphOwner(session.principal),String(body.run_id??""));if(!prior)throw new Error("workflow execution not found");if(prior.state==="running")throw new Error("running execution must be stopped before retry");if(!prior.runtimeInput)throw new Error("execution predates retry input retention; run the workflow again instead");const graph=await getWorkflowGraph(session.principal,prior.graphId);if(!graph)throw new Error("workflow graph not found");if(graph.revision!==prior.graphRevision)throw new Error("workflow changed since this execution; run the current workflow instead of retrying stale input");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow retry: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;return NextResponse.json(await startWorkflowGraph(graph,prior.runtimeInput,String(body.idempotency_key??`retry:${prior.id}:${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}if(action==="run"){const graph=await getWorkflowGraph(session.principal,String(body.graph_id??""));if(!graph)throw new Error("workflow graph not found");const agentSession=await createAgentSession(session.principal,"cli",{title:`Workflow: ${graph.name}`,titleSource:"auto"}),context={principal:session.principal,actor:session.principal,sessionId:agentSession.id,scope:maxScope(),capabilities:msoCapabilityRuntime} as const;return NextResponse.json(await startWorkflowGraph(graph,body.input??{},String(body.idempotency_key??`${Date.now()}`),context,(name)=>TOOLS_BY_NAME.get(name)),{headers});}throw new Error("unknown workflow action");}catch(error){return fail(error);}}diff --git a/components/shared/graph-canvas.tsx b/components/shared/graph-canvas.tsxindex edcdaa28..73e01839 100644--- a/components/shared/graph-canvas.tsx+++ b/components/shared/graph-canvas.tsx@@ -42,6 +42,9 @@ type GraphCanvasProps<NodeType extends Node = Node, EdgeType extends Edge = Edge/** On compact panes, keep these nodes readable instead of shrinking an entire wide graph. */compactFitNodeIds?: string[];compactFitMaxZoom?: number;+ /** On roomy panes, auto-fit this representative cluster instead of shrinking a very large graph. Manual F still fits the complete graph. */+ initialFitNodeIds?: string[];+ initialFitMaxZoom?: number;};export function GraphCanvas<NodeType extends Node = Node, EdgeType extends Edge = Edge>(props: GraphCanvasProps<NodeType, EdgeType>) {@@ -51,6 +54,7 @@ export function GraphCanvas<NodeType extends Node = Node, EdgeType extends Edgefunction GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge = Edge>({ariaLabel, initialMode = "select", showMinimap = true, onTidy, fitPadding = 0.22,miniMapNodeColor, miniMapNodeStrokeColor, compactFitNodeIds, compactFitMaxZoom = 0.9,+ initialFitNodeIds, initialFitMaxZoom = 1,className, children, fitViewOptions, onKeyDown, ...props}: GraphCanvasProps<NodeType, EdgeType>) {const [mode, setMode] = useState<GraphCanvasMode>(initialMode);@@ -67,12 +71,21 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =// Node selection/movement may recreate the array without changing the focus set.const focusKey = JSON.stringify(compactFitNodeIds ?? []);const focusNodes = useMemo(() => (JSON.parse(focusKey) as string[]).map((id) => ({ id })), [focusKey]);+ const initialKey = JSON.stringify(initialFitNodeIds ?? []);+ const initialNodes = useMemo(() => (JSON.parse(initialKey) as string[]).map((id) => ({ id })), [initialKey]);const { fitView, zoomIn, zoomOut } = useReactFlow<NodeType, EdgeType>();const fit = useCallback(() => void fitView({ padding: fitPadding, duration: 220, ...fitViewOptions }), [fitPadding, fitView, fitViewOptions]);const fitResponsive = useCallback((duration: number) => {- const nodes = compact && focusNodes.length ? focusNodes : undefined;- void fitView({ padding: compact ? Math.min(fitPadding, 0.14) : fitPadding, duration, ...fitViewOptions, ...(nodes ? { nodes, maxZoom: compactFitMaxZoom } : {}) });- }, [compact, compactFitMaxZoom, focusNodes, fitPadding, fitView, fitViewOptions]);+ const preferredNodes = compact ? focusNodes : initialNodes;+ const nodes = preferredNodes.length ? preferredNodes : undefined;+ const maxZoom = compact ? compactFitMaxZoom : initialFitMaxZoom;+ void fitView({+ padding: compact ? Math.min(fitPadding, 0.14) : fitPadding,+ duration,+ ...fitViewOptions,+ ...(nodes ? { nodes, maxZoom } : {}),+ });+ }, [compact, compactFitMaxZoom, fitPadding, fitView, fitViewOptions, focusNodes, initialFitMaxZoom, initialNodes]);useEffect(() => {if (!initialized || width <= 0 || height <= 0) return;// A single owner fits only after lazy CSS and node measurement are ready.@@ -114,7 +127,7 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =<ControlButton aria-label="Pan mode" title="Pan (H or hold Space)" onClick={() => setMode("pan")} className={mode === "pan" ? "is-active" : undefined}><Hand aria-hidden/></ControlButton><ControlButton aria-label="Zoom in" title="Zoom in (+)" onClick={() => void zoomIn({ duration: 160 })}><ZoomIn aria-hidden/></ControlButton><ControlButton aria-label="Zoom out" title="Zoom out (-)" onClick={() => void zoomOut({ duration: 160 })}><ZoomOut aria-hidden/></ControlButton>- <ControlButton aria-label="Fit view" title="Fit view (F)" onClick={fit}><Maximize2 aria-hidden/></ControlButton>+ <ControlButton aria-label="Fit view" title="Fit complete graph (F)" onClick={fit}><Maximize2 aria-hidden/></ControlButton>{onTidy ? <ControlButton aria-label="Tidy up" title="Tidy up" onClick={tidy} className="mso-graph-secondary-control"><LayoutGrid aria-hidden/></ControlButton> : null}</Controls>{showMinimap ? <MiniMapdiff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex cc038627..c69628e8 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.## 2026-09-22+**Added**++- `workflows` split n8n and improve org automation ux+**Fixed**- `mcp` normalize widget resource discoverydiff --git a/docs/N8N-PARITY.md b/docs/N8N-PARITY.mdnew file mode 100644index 00000000..6fe9d4a6--- /dev/null+++ b/docs/N8N-PARITY.md@@ -0,0 +1,80 @@+# n8n capability map — native MSO Workflows + Organization++MSO treats n8n as a separate external automation workspace. Native **Workflows** and+**Organization** stay authoritative for MSO-native automation, people/roles, projects,+execution routing, integrations, and server context. This avoids making an embedded n8n+page the source of truth for MSO.++This document maps the core self-hosted n8n capability areas to their MSO-native+counterparts. The goal is capability coverage, not pixel-for-pixel or API-for-API cloning.++| n8n capability area | Native MSO surface | MSO implementation |+|---|---|---|+| Workflow list/search | Workflows | Searchable workflow library with status, project, folder, node and tag filters |+| Create/update/delete/duplicate | Workflows | Workflow Graph create/update/delete/clone |+| Activate/deactivate | Workflows | Draft / active / archived lifecycle and Active switch |+| Tags/folders | Workflows | Graph metadata tags and folders; clickable tag filters |+| Manual trigger | Workflows | Manual trigger node + Run |+| Schedule trigger | Workflows | Schedule node with cron/interval and timezone |+| Webhook trigger | Workflows | Webhook node with bounded response modes |+| Conditions/switch/merge | Workflows | condition, switch and merge nodes |+| Batch/loop/wait | Workflows | batch, bounded loop, repeat-until and wait nodes |+| Sub-workflows | Workflows | subflow node, including saved Workflow Graphs |+| Error handling/retry | Workflows | bounded retry policy, error handles, continue-on-error and error workflows |+| Execution history | Workflows → Executions | Persisted run receipts with graph revision, node states, attempts, durations and logs; running executions can be stopped, stopped/failed/completed executions can be retried with their owner-private retained input when the graph revision is unchanged, and finished receipts can be deleted |+| Current execution | Workflows → Current run | Live polling and node/edge execution state |+| Versions/rollback | Workflows → Versions | Private graph snapshots and revision-checked restore |+| Variables/secrets | Workflows → Variables | Owner-private workflow variables; secrets are redacted and never returned in list responses |+| Credentials/connections | Integrations | Credential authority lives in Integrations; workflow graphs store connection references only |+| Integration actions | Workflows | integration nodes invoke reviewed MSO connections |+| Custom/code-like automation | Workflows | bounded project functions, project MCP, tested RASMIC scripts, tools and agents |+| Templates | Workflows | Built-in templates and AI-assisted draft creation |+| AI-assisted workflow creation | Workflows | Isolated workflow-design prompt; output is schema-validated and starts as draft |+| Persistent workflow data | Workflows → Data | Owner-private persistent data tables with bounded schemas/rows plus a native `data_table` workflow node for list/read/insert/update/delete; TTL cache and memory nodes remain available for other state patterns |+| Project context | Organization + project registry | Organization project flows reference canonical MSO projects without granting authority |+| Projects/groups | Organization | Units model holding/company/division/team/client boundaries |+| Users/members/roles | Organization | Seats model roles, titles, state, reporting lines and execution binding |+| Execution delegation | Organization + Workflows | Workflow Agent node can resolve an Organization seat at run time |+| Remote agents | Organization | Seats may bind to Project Agent, Local Agent or A2A targets |+| Instance/system status | System Monitor + Integrations | Runtime health and connection verification remain separate operational surfaces |+| Source control | Project/Git surfaces | Canonical project Git state stays with the project rather than inside workflow definitions |+| Import/export/backup | Workflows + MSO transfer surfaces | Workflows import/export portable `.mso-workflow.json` packages; credentials and runtime configuration continue to use guarded transfer paths |+| Audit/auth boundaries | MSO auth + audit | Device role, capability scope, audit and rate limits remain authoritative |++## Dedicated n8n app++The built-in `/n8n` route is the only first-class external n8n workspace. Native+`/workflows` no longer mounts provider tabs. The n8n surface uses the reviewed+surface registry and keeps its own authentication/cookies. MSO blocks a reviewed+destination when it would receive the cockpit session cookie.++Recommended registry placement:++```json+{+ "id": "n8n",+ "title": "n8n",+ "origin": "https://automation.example.test",+ "startPath": "/home/workflows",+ "renderer": "iframe",+ "presentation": "inline",+ "environment": "production",+ "placements": ["n8n"]+}+```++For migration, an existing n8n entry using `"placements": ["workflows"]` remains+readable by the compatibility API. New configurations should use `"n8n"`.++## Domain boundaries++- **Workflows** owns automation topology, execution, history, versions and variables.+- **Organization** owns units, seats, project/context mapping and execution routing references.+- **Integrations** owns credentials and provider connections.+- **n8n** is a separate external editor/runtime and does not inherit MSO authority.+- Organization project-flow nodes are context objects, not executable Workflow Graph nodes.+- A seat or project reference never grants capability by itself.++This split is deliberate: it gives the native product the automation and organization+capabilities expected from a self-hosted workflow platform without copying n8n SaaS+billing, marketplace or team-administration products into the wrong authority domain.diff --git a/docs/ORGANIZATION.md b/docs/ORGANIZATION.mdindex 07116cfe..45ec04dd 100644--- a/docs/ORGANIZATION.md+++ b/docs/ORGANIZATION.md@@ -102,9 +102,11 @@ This is a private runtime store. MSO source ships **no operator-specific organizOpen the first-class **Organization** app from the dock, launcher, Start menu, App Library, Spotlight, or `/organization`. **Alfa → Organization** remains a secondary deep-link to the same view and SSOT.-The default `All organization` view renders the complete reporting hierarchy across units. Selecting a unit filters the view while keeping the same SSOT. Seat cards show role, unit, seat mode, execution binding, and current runtime state.+The default `All organization` view is now **directory-first** so large organizations stay readable instead of shrinking dozens of cards into one tiny fit-to-screen graph. The overview shows searchable unit cards and operational counts; **Map** remains available when relationship topology matters.-Editing uses the shell-responsive dialog/drawer primitive so desktop and mobile use the same contract.+Opening a unit keeps **Projects** and **Seats** as explicit sub-surfaces. Projects uses the internal project-flow canvas; Seats defaults to a searchable directory and can switch to the reporting map. Large canvases initially focus a representative readable cluster, while `F` still fits the complete graph on demand. Seat cards show role, unit, seat mode, execution binding, and current runtime state.++Editing uses the shell-responsive dialog/drawer primitive so desktop and mobile use the same contract. The n8n capability split and the boundary between Organization, Workflows and Integrations are documented in [`N8N-PARITY.md`](./N8N-PARITY.md).## CLIdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 92154748..3f551375 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -14,6 +14,16 @@ MSO now advertises the UI extension with `text/html;profile=mcp-app` in both proThis release fixes the MSO-owned negotiation gap; it does not redefine visual acceptance. A generic Code Mode/function wrapper can still unwrap the inner tool result and cannot prove host mounting. Final ChatGPT acceptance remains a direct registered-app invocation after the refreshed server descriptor is active, with success defined by a visibly host-mounted `MSO NATIVE UI WORKS` component and then a real List → Page interaction round-trip.+## 2026-09-22 — Split n8n from Workflows and make Organization/Workflow usable at scale++The Organization project map had become visually unreadable on dense units because the initial canvas fit tried to show the entire graph at once. Organization is now directory-first: the owner sees searchable unit cards and operational counts, opens a unit into explicit Projects/Seats surfaces, and can switch to relationship maps only when topology matters. Seat browsing follows the same directory-first rule. Shared graph fitting now supports a representative readable initial cluster while preserving `F` as full-graph fit, and the Organization sidebar exposes direct Workflows, Integrations and System links without changing capability authority.++External n8n is no longer a provider tab inside native Workflows. It is a first-class `/n8n` app/route with its own reviewed surface placement, cookie-isolated authentication boundary, responsive embed/fallback, and direct links back to native Workflows, Organization and Integrations. Legacy reviewed `workflows` placement remains readable during migration, while new registrations use `n8n`. Role-filtered or unavailable apps now show a neutral unavailable-state instead of the misleading `Unknown app` message.++Native Workflows gained the missing core management pieces needed for practical n8n-style self-hosted parity: persistent owner-private data tables plus a `data_table` node; execution stop/retry/delete controls; portable `.mso-workflow.json` import/export; clearer Builder/Current run/Executions/Versions/Variables/Data/Directory panels; a denser workflow library; and toolbar overflow behavior that keeps wide action sets from pushing the canvas beyond its pane. Execution retry retains runtime input only in the private receipt, strips it from public receipts, requires the current graph revision to match, and stop remains cooperative at bounded node boundaries. Credentials remain owned by Integrations, Organization remains units/seats/projects/routing context, and Workflow remains automation topology/execution. `docs/N8N-PARITY.md` records the domain map rather than claiming pixel/API parity or copying n8n billing/marketplace administration.++Verification on the isolated candidate: TypeScript, ESLint, architecture/docs/contrast/skills/instance-literal checks, the full coverage gate, production build, and the complete release E2E all pass, including dedicated n8n, Organization flow, custom graph, desktop/mobile/landscape reflow, data-table/portability/execution-control regressions, and no browser errors.+## 2026-09-21 — Add bounded Repeat Until for reusable Session workflowsWorkflow 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/README.md b/docs/README.mdindex f0eda6d2..c2e5b631 100644--- a/docs/README.md+++ b/docs/README.md@@ -39,6 +39,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs || [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits || [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2 with n8n-core triggers/flow control, versions/history, variables, integrations, visual execution and automatic learning |+| [`N8N-PARITY.md`](./N8N-PARITY.md) | Core n8n capability map across native Workflows, Organization, Integrations and the dedicated external n8n workspace || [`ORGANIZATION.md`](./ORGANIZATION.md) | Owner-private organization units, seats, reporting lines, live agent bindings, and workflow routing references || [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting || [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model |diff --git a/docs/SLICE-CATALOG.md b/docs/SLICE-CATALOG.mdindex 389cc9d7..90470b6e 100644--- a/docs/SLICE-CATALOG.md+++ b/docs/SLICE-CATALOG.md@@ -3,12 +3,12 @@> **Current reference.** Counts are checked against the directory tree by> `scripts/check-docs.mjs`; the directory remains the final authority.-<!-- slice-catalog: slices=26 appshell-features=10 -->+<!-- slice-catalog: slices=27 appshell-features=10 -->Every application is a vertical slice under `frontend/slices/`. Host-facing slices use theshared API/host seam rather than reaching arbitrary Node host APIs from client code.-## Slices (26)+## Slices (27)| Slug | Purpose ||---|---|@@ -27,6 +27,7 @@ shared API/host seam rather than reaching arbitrary Node host APIs from client c| `infrastructure` | Dokploy/Cloudflare provider configuration and live inventory apps || `integrations` | Native connection manager shell window using the existing Integrations service || `managed-apps` | Hermes/OpenClaw install/lifecycle/update/backup/proxy |+| `n8n` | Dedicated reviewed n8n workspace, isolated from native Workflows and MSO credentials || `media-studio` | Image/media studio surface || `media-viewer` | Preview/Quick Look-style media viewer || `os-settings` | MSO Settings |diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex 555d8e32..d767e2bc 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -58,6 +58,7 @@ Graph edges stay acyclic. Item fan-out uses `loop`; conditional loop-back uses `- `folder`- `skill`- `knowledge`+- `data_table` — list/read a persistent owner-private data table or insert/update/delete one bounded rowProject/folder nodes resolve the live canonical server path when the graph runs and can open that real directory in MSO Files/Finder.@@ -131,7 +132,7 @@ Private run receipts retain up to 1000 recent executions and expose:- compact logs- failed node id/name-The Workflows canvas reflects live node state and pulses edges while related nodes run. The History panel filters one graph's persisted executions and can reopen a complete receipt.+The Workflows canvas reflects live node state and pulses edges while related nodes run. The Executions panel filters one graph's persisted executions and can reopen a complete receipt. A running local execution can be stopped after its current bounded action. Finished/stopped executions can be retried with their owner-private retained input only while the graph revision still matches, and finished receipts can be deleted.## Versions and rollback@@ -164,46 +165,22 @@ AI assistance has an isolated workflow-design system prompt, receives no implici- execution log + persisted history- graph version restore- private variable/secret manager+- persistent workflow data-table manager and `data_table` nodes+- portable workflow JSON import/export+- execution stop/retry/delete controls- template and AI-assisted creationRun 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.-## Reviewed external workflow tabs+## Dedicated n8n workspace-The Workflows workspace keeps the native MSO automation/session editor and can add-external editors such as n8n as sibling tabs. External tabs are **off by default**.-The owner-reviewed Page registry is shared through `lib/surfaces/config.ts`; add-`"placements": ["workflows"]` to an approved external app in the existing-`~/.mso/surface-apps.json` (or its configured override). Preserve existing entries.-Workflow-only placements do not appear in the MCP Page catalog or grant ChatGPT a-nested-frame origin. Legacy entries without placements retain their Page behavior;-explicit `"mcp-page"` is a separate reviewed placement.-For example, a private installation could add:+n8n is a separate first-class MSO app at `/n8n`; it is no longer mounted as a sibling tab inside native Workflows. `/workflows` now always opens the native Workflow Graph editor, so external editor loading, authentication, or frame policy cannot shrink or replace the native canvas.-```json-{- "id": "n8n", "title": "n8n", "description": "External workflow editor",- "origin": "https://automation.example.test", "startPath": "/home/workflows",- "renderer": "iframe", "presentation": "inline", "environment": "production",- "externalAuthPath": "/signin", "placements": ["workflows"],- "sandbox": "allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox"-}-```+Reviewed n8n presentation metadata still uses the owner-private surface registry in `lib/surfaces/config.ts`. New n8n registrations should use `"placements": ["n8n"]`. The compatibility reader also accepts an existing n8n registration using the legacy `"workflows"` placement so operators can migrate without losing access. The registry contains presentation metadata only; Integration credentials are never returned through this surface.++The dedicated n8n app keeps the same cookie-isolation rule: a reviewed external destination is blocked when it would receive the MSO cockpit session cookie. n8n retains its own login and cookies; MSO does not proxy credentials or remove upstream frame/security headers. If embedding is unavailable, the app exposes the reviewed top-level destination instead.-`GET /api/v1/workflow-embeds` and `mso workflow embeds` return only reviewed-presentation metadata to an approved Owner device. They never return Integration-credentials. The Owner-only POST and `mso workflow embed-save` accept `{app, expectedRevision, confirm:true}`; they validate metadata, preserve unrelated entries and reject stale revisions or environment-managed configuration. No raw file or credential access is exposed.-The registry is refreshed when the window regains focus, without a-rebuild. External frames load on first selection; switching tabs preserves both-the native editor's unsaved state and the external editor's frame. Keyboard tab-navigation and narrow viewport layouts use the same workspace wrapper.--MCP authorization does not sign the browser into n8n. Use the visible **Sign in**-link to authenticate directly with the external service, then reload its frame.-**Open** remains available if its frame policy or browser cookie policy prevents-embedding. MSO does not strip upstream security headers, proxy credentials, or-claim that an iframe load proves authentication. Own-cockpit origins and-remote-only registry entries never become embedded frames.+Native feature ownership is documented in [`N8N-PARITY.md`](./N8N-PARITY.md): Workflows owns automation topology/execution/history/versions/variables, Organization owns units/seats/projects/routing context, and Integrations owns credentials/connections.## CLI@@ -236,7 +213,7 @@ MSO deliberately keeps this capability behind one compact MCP tool to preserve tActions:-`list`, `search`, `get`, `create`, `update`, `delete`, `clone`, `run`, `status`, `runs`, `versions`, `restore`, `catalog`, `scripts`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`. `list` and `search` accept the same workflow query/filter semantics used by the UI; `scripts` returns safe RASMIC manifest summaries for an exact project without exposing raw script files or credentials.+`list`, `search`, `get`, `create`, `update`, `delete`, `clone`, `run`, `status`, `runs`, `stop`, `retry`, `run_delete`, `versions`, `restore`, `catalog`, `scripts`, `templates`, `create_from_template`, `variables`, `variable_set`, `variable_delete`, `data_tables`, `data_table_get`, `data_table_create`, `data_table_delete`, `data_table_row_upsert`, `data_table_row_delete`. `list` and `search` accept the same workflow query/filter semantics used by the UI; `scripts` returns safe RASMIC manifest summaries for an exact project without exposing raw script files or credentials.The linear `flow_catalog`, `flow_manage`, `flow_run` and `flow_status` tools remain compatible for small deterministic project-owned sequences.diff --git a/frontend/slices/appshell/components/window-content.tsx b/frontend/slices/appshell/components/window-content.tsxindex 0dea20b3..cb2f47f9 100644--- a/frontend/slices/appshell/components/window-content.tsx+++ b/frontend/slices/appshell/components/window-content.tsx@@ -46,8 +46,12 @@ export function WindowContent({ app, payload, winId }: { app: string; payload?:if (!descriptor) {return (- <div className="grid h-full place-items-center text-sm text-muted-foreground">- Unknown app: {app}+ <div className="grid h-full place-items-center p-6 text-center text-sm text-muted-foreground">+ <div>+ <p className="font-medium text-foreground">App unavailable</p>+ <p className="mt-1 max-w-sm">This app is not installed or is not available for the current session role.</p>+ <p className="mt-2 text-[10px] opacity-70">{app}</p>+ </div></div>);}diff --git a/frontend/slices/n8n/app.tsx b/frontend/slices/n8n/app.tsxnew file mode 100644index 00000000..dff3fa93--- /dev/null+++ b/frontend/slices/n8n/app.tsx@@ -0,0 +1,91 @@+"use client";++import { useCallback, useEffect, useMemo, useState } from "react";+import { Boxes, Building2, Cable, RefreshCw, Workflow } from "lucide-react";+import type { AppProps } from "@/features/appshell";+import { AppFrame, openWindow } from "@/features/appshell";+import type { WorkflowEmbed } from "@/lib/contracts/surface-app";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { N8nEmbedPanel } from "./components/n8n-embed-panel";++type EmbedResponse = { apps?: WorkflowEmbed[] };++export default function N8nApp(_: AppProps) {+ const [apps, setApps] = useState<WorkflowEmbed[]>([]);+ const [loading, setLoading] = useState(true);+ const [message, setMessage] = useState("");++ const load = useCallback(async () => {+ try {+ const response = await fetch("/api/v1/workflow-embeds", { cache: "no-store" });+ if (!response.ok) {+ setApps([]);+ setMessage(response.status === 403 ? "Owner access is required to view the reviewed n8n surface." : "Could not load the n8n surface.");+ return;+ }+ const data = await response.json() as EmbedResponse;+ setApps(Array.isArray(data.apps) ? data.apps : []);+ setMessage("");+ } catch (error) {+ setMessage(error instanceof Error ? error.message : "Could not load the n8n surface.");+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ const frame = requestAnimationFrame(() => { void load(); });+ window.addEventListener("focus", load);+ return () => {+ cancelAnimationFrame(frame);+ window.removeEventListener("focus", load);+ };+ }, [load]);++ const n8n = useMemo(() => apps.find((app) => app.id === "n8n" || app.title.trim().toLowerCase() === "n8n") ?? null, [apps]);++ const toolbar = <div className="flex h-11 min-w-0 items-center gap-2 px-3">+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold">n8n</span>+ <Badge variant={n8n ? "secondary" : "outline"} className={n8n?.blocked ? "text-[9px] text-destructive" : "text-[9px]"}>+ {n8n?.blocked ? "Blocked" : n8n ? "Reviewed" : loading ? "Loading" : "Not configured"}+ </Badge>+ </div>+ </div>+ <Button size="sm" variant="ghost" onClick={() => openWindow("workflows", "Workflows")}><Workflow className="size-4"/><span className="hidden @min-[640px]:inline">Workflows</span></Button>+ <Button size="sm" variant="ghost" onClick={() => openWindow("organization", "Organization")}><Building2 className="size-4"/><span className="hidden @min-[760px]:inline">Organization</span></Button>+ <Button size="sm" variant="ghost" onClick={() => openWindow("integrations", "Integrations")}><Cable className="size-4"/><span className="hidden @min-[900px]:inline">Integrations</span></Button>+ <Button size="icon" variant="ghost" onClick={() => { setLoading(true); void load(); }} aria-label="Refresh n8n surface"><RefreshCw className="size-4"/></Button>+ </div>;++ return <div data-slot="n8n-feature" className="@container h-full min-h-0 min-w-0">+ <AppFrame safeArea={false} className="h-full min-w-0" toolbar={toolbar}>+ {n8n ? <N8nEmbedPanel app={n8n}/> : <div className="grid h-full min-h-0 place-items-center overflow-y-auto p-6">+ <div className="w-full max-w-2xl rounded-2xl border bg-card p-5 shadow-sm">+ <div className="flex items-start gap-3">+ <div className="grid size-10 shrink-0 place-items-center rounded-xl border bg-muted/40"><Boxes className="size-5 text-muted-foreground"/></div>+ <div className="min-w-0 flex-1">+ <h2 className="text-base font-semibold">n8n is now a separate workspace</h2>+ <p className="mt-1 text-sm leading-5 text-muted-foreground">Connect a reviewed n8n surface here. Native MSO Workflows continues to own automation graphs and executions; Organization owns units, seats, projects, members, and execution routing context.</p>+ </div>+ </div>+ <div className="mt-5 grid gap-2 @min-[620px]:grid-cols-3">+ <QuickLink title="Native Workflows" detail="Build, run, inspect, version, and manage automation." onClick={() => openWindow("workflows", "Workflows")}/>+ <QuickLink title="Organization" detail="Manage units, seats, projects, members, and routing context." onClick={() => openWindow("organization", "Organization")}/>+ <QuickLink title="Integrations" detail="Keep provider connections and credentials outside workflow definitions." onClick={() => openWindow("integrations", "Integrations")}/>+ </div>+ <p className="mt-4 text-xs text-muted-foreground">{message || "No reviewed n8n surface is configured for this owner yet."}</p>+ </div>+ </div>}+ </AppFrame>+ </div>;+}++function QuickLink({ title, detail, onClick }: { title: string; detail: string; onClick: () => void }) {+ return <button type="button" onClick={onClick} className="rounded-xl border bg-background p-3 text-left transition hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div className="text-xs font-semibold">{title}</div>+ <div className="mt-1 text-[11px] leading-4 text-muted-foreground">{detail}</div>+ </button>;+}diff --git a/frontend/slices/workflows/components/workflow-embed-panel.test.tsx b/frontend/slices/n8n/components/n8n-embed-panel.test.tsxsimilarity index 74%rename from frontend/slices/workflows/components/workflow-embed-panel.test.tsxrename to frontend/slices/n8n/components/n8n-embed-panel.test.tsxindex 2e7f419f..23b652c6 100644--- a/frontend/slices/workflows/components/workflow-embed-panel.test.tsx+++ b/frontend/slices/n8n/components/n8n-embed-panel.test.tsx@@ -1,22 +1,22 @@import { readFileSync } from "node:fs";import { describe, expect, it } from "vitest";import { renderToStaticMarkup } from "react-dom/server";-import { WorkflowEmbedPanel } from "./workflow-embed-panel";+import { N8nEmbedPanel } from "./n8n-embed-panel";import type { WorkflowEmbed } from "@/lib/contracts/surface-app";const app: WorkflowEmbed = { id: "editor", title: "Editor", origin: "https://editor.example.test", description: "", renderer: "iframe", sandbox: "allow-scripts", url: "https://editor.example.test/", loginUrl: "https://editor.example.test/login" };describe("blocked external editor rendering", () => {it("never renders an iframe, navigation or login URL for a blocked destination", () => {- const html = renderToStaticMarkup(<WorkflowEmbedPanel app={{ ...app, blocked: true, reason: "Blocked session cookie scope" }} />);+ const html = renderToStaticMarkup(<N8nEmbedPanel app={{ ...app, blocked: true, reason: "Blocked session cookie scope" }} />);expect(html).toContain("Blocked session cookie scope");expect(html).not.toContain("<iframe"); expect(html).not.toContain('href='); expect(html).not.toContain(app.origin);});it("remounts the iframe whenever the reviewed sandbox policy changes", () => {- const source = readFileSync(new URL("./workflow-embed-panel.tsx", import.meta.url), "utf8");+ const source = readFileSync(new URL("./n8n-embed-panel.tsx", import.meta.url), "utf8");expect(source).toContain('key={`${revision}:${app.sandbox}`}');});it("fails closed if a destination is missing even without the blocked flag", () => {- const html = renderToStaticMarkup(<WorkflowEmbedPanel app={{ ...app, url: undefined }} />);+ const html = renderToStaticMarkup(<N8nEmbedPanel app={{ ...app, url: undefined }} />);expect(html).not.toContain("<iframe"); expect(html).not.toContain('href=');});});diff --git a/frontend/slices/workflows/components/workflow-embed-panel.tsx b/frontend/slices/n8n/components/n8n-embed-panel.tsxsimilarity index 87%rename from frontend/slices/workflows/components/workflow-embed-panel.tsxrename to frontend/slices/n8n/components/n8n-embed-panel.tsxindex 176e5c3b..f0e6842e 100644--- a/frontend/slices/workflows/components/workflow-embed-panel.tsx+++ b/frontend/slices/n8n/components/n8n-embed-panel.tsx@@ -5,7 +5,7 @@ import { ExternalLink, LogIn, RefreshCw } from "lucide-react";import type { WorkflowEmbed } from "@/lib/contracts/surface-app";import { Button } from "@/components/ui/button";-export function WorkflowEmbedPanel({ app }: { app: WorkflowEmbed }) {+export function N8nEmbedPanel({ app }: { app: WorkflowEmbed }) {const [revision, setRevision] = useState(0);const [loading, setLoading] = useState(true);const [slow, setSlow] = useState(false);@@ -13,12 +13,12 @@ export function WorkflowEmbedPanel({ app }: { app: WorkflowEmbed }) {const timer = setTimeout(() => setSlow(true), 15000);return () => clearTimeout(timer);}, [revision]);- if (app.blocked || !app.url) return <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-sm" data-slot="workflow-embed-panel" role="alert">+ if (app.blocked || !app.url) return <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-2 p-6 text-center text-sm" data-slot="n8n-embed-panel" role="alert"><p>{app.reason || "This editor destination is unavailable."}</p><p className="text-xs text-muted-foreground">No editor or login link is opened. Configure a separate cookie-isolated origin before connecting.</p></div>;const reload = () => { setLoading(true); setSlow(false); setRevision((value) => value + 1); };- return <div className="flex h-full min-h-0 min-w-0 flex-col" data-slot="workflow-embed-panel">+ return <div className="flex h-full min-h-0 min-w-0 flex-col" data-slot="n8n-embed-panel"><div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1.5"><span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>{app.origin}</span>{app.loginUrl ? <Button asChild variant="ghost" size="sm"><a href={app.loginUrl} target="_blank" rel="noopener noreferrer"><LogIn className="size-4"/><span>Sign in</span></a></Button> : null}@@ -27,7 +27,7 @@ export function WorkflowEmbedPanel({ app }: { app: WorkflowEmbed }) {</div>{app.renderer === "iframe" ? <div className="relative min-h-0 min-w-0 flex-1">{loading ? <div className="absolute inset-x-0 top-0 z-10 border-b bg-background px-3 py-2 text-xs text-muted-foreground" role="status">{slow ? `Taking longer than expected. Open ${app.title} in a new tab if its login or frame policy blocks embedding.` : `Loading ${app.title}…`}</div> : null}- <iframe key={`${revision}:${app.sandbox}`} src={app.url} title={`${app.title} workflow editor`} sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/>+ <iframe key={`${revision}:${app.sandbox}`} src={app.url} title="n8n automation editor" sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/></div> : <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{app.reason || `${app.title} opens in a separate tab. Embedded access is not enabled for this provider.`}</div>}<p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.title} keeps its own login. Sign in in a new tab, then reload here. If embedding is blocked, use Open {app.title}.</p></div>;diff --git a/frontend/slices/n8n/index.ts b/frontend/slices/n8n/index.tsnew file mode 100644index 00000000..474cbd1d--- /dev/null+++ b/frontend/slices/n8n/index.ts@@ -0,0 +1,12 @@+import { Waypoints } from "lucide-react";+import type { AppDescriptor } from "@/features/appshell";++export const n8nApp: AppDescriptor = {+ id: "n8n",+ title: "n8n",+ icon: Waypoints,+ gradient: "var(--primary)",+ prefetch: "never",+ load: () => import("./app"),+ defaultSize: { w: 1180, h: 760 },+};diff --git a/frontend/slices/organization/components/organization-canvas.tsx b/frontend/slices/organization/components/organization-canvas.tsxindex 1a5a4671..b57788ec 100644--- a/frontend/slices/organization/components/organization-canvas.tsx+++ b/frontend/slices/organization/components/organization-canvas.tsx@@ -82,6 +82,8 @@ export function OrganizationCanvas({ chart, runtime, unitId, selectedSeatId, onUonNodeClick={(_, node) => node.type === "unit" ? onUnitSelect(node.id) : onSeatSelect((node as SeatNode).data.seat)}onNodeDoubleClick={(_, node) => { if (node.type === "seat") onSeatOpen((node as SeatNode).data.seat); }}fitPadding={pane === "xs" || pane === "sm" ? 0.12 : pane === "md" ? 0.18 : 0.26}+ initialFitNodeIds={nodes.slice(0, 6).map((node) => node.id)}+ initialFitMaxZoom={0.96}miniMapNodeColor={(node) => node.type === "unit" ? "var(--info)" : (() => {const status = (node as SeatNode).data.runtime?.status ?? "vacant";return status === "busy" ? "var(--warning)" : status === "ready" ? "var(--success)" : status === "unresolved" ? "var(--destructive)" : "var(--text-dim)";diff --git a/frontend/slices/organization/components/organization-directory.tsx b/frontend/slices/organization/components/organization-directory.tsxnew file mode 100644index 00000000..37c0fae6--- /dev/null+++ b/frontend/slices/organization/components/organization-directory.tsx@@ -0,0 +1,146 @@+"use client";++import { useMemo, useState } from "react";+import { BriefcaseBusiness, Building2, Search, UserRound, Users } from "lucide-react";+import type { OrganizationChart, OrganizationSeat, OrganizationSeatRuntime } from "@/lib/contracts/organization";+import { Badge } from "@/components/ui/badge";+import { Input } from "@/components/ui/input";+import { cn } from "@/lib/utils";++const runtimeDot: Record<OrganizationSeatRuntime["status"], string> = {+ ready: "bg-success",+ busy: "bg-warning",+ offline: "bg-muted-foreground",+ unresolved: "bg-destructive",+ unbound: "bg-info",+ vacant: "bg-border",+};++export function OrganizationUnitDirectory({+ chart,+ runtime,+ onUnitSelect,+}: {+ chart: OrganizationChart;+ runtime: OrganizationSeatRuntime[];+ onUnitSelect: (id: string) => void;+}) {+ const [query, setQuery] = useState("");+ const runtimeBySeat = useMemo(() => new Map(runtime.map((row) => [row.seatId, row])), [runtime]);+ const units = useMemo(() => {+ const q = query.trim().toLowerCase();+ return chart.units+ .slice()+ .sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name))+ .filter((unit) => !q || `${unit.name} ${unit.description} ${unit.kind}`.toLowerCase().includes(q));+ }, [chart.units, query]);++ return <div data-slot="organization-unit-directory" className="flex h-full min-h-0 flex-col bg-background/40">+ <div className="grid shrink-0 gap-3 border-b p-3 @min-[760px]:grid-cols-[minmax(0,1fr)_auto] @min-[760px]:items-center">+ <div>+ <h3 className="text-sm font-semibold">Organization overview</h3>+ <p className="mt-0.5 text-xs text-muted-foreground">Scan units first. Open a unit for projects, seats, reporting lines, and execution bindings.</p>+ </div>+ <div className="grid grid-cols-3 gap-2 text-center">+ <Metric value={chart.units.length} label="Units" icon={<Building2 className="size-3.5"/>}/>+ <Metric value={chart.seats.length} label="Seats" icon={<Users className="size-3.5"/>}/>+ <Metric value={runtime.filter((row) => row.status === "ready" || row.status === "busy").length} label="Online" icon={<UserRound className="size-3.5"/>}/>+ </div>+ </div>+ <div className="shrink-0 border-b p-3">+ <div className="relative max-w-xl">+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"/>+ <Input aria-label="Search organization units" className="h-9 pl-9" placeholder="Search units, companies, teams, or clients…" value={query} onChange={(event) => setQuery(event.target.value)}/>+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-3">+ {units.length ? <div className="grid gap-3 @min-[620px]:grid-cols-2 @min-[1100px]:grid-cols-3">+ {units.map((unit) => {+ const seats = chart.seats.filter((seat) => seat.unitId === unit.id);+ const active = seats.filter((seat) => {+ const status = runtimeBySeat.get(seat.id)?.status;+ return status === "ready" || status === "busy";+ }).length;+ const projects = unit.projectFlow?.nodes.filter((node) => node.kind === "project").length ?? 0;+ const activities = unit.projectFlow?.nodes.length ?? 0;+ return <button key={unit.id} type="button" onClick={() => onUnitSelect(unit.id)} className="group min-w-0 rounded-xl border bg-card p-4 text-left shadow-sm transition hover:border-foreground/20 hover:bg-accent/35 hover:shadow-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div className="flex items-start gap-3">+ <div className="grid size-9 shrink-0 place-items-center rounded-lg border bg-muted/50"><Building2 className="size-4 text-muted-foreground"/></div>+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2"><h4 className="truncate text-sm font-semibold">{unit.name}</h4><Badge variant="secondary" className="shrink-0 text-[9px]">{unit.kind}</Badge></div>+ <p className="mt-1 line-clamp-2 min-h-8 text-xs leading-4 text-muted-foreground">{unit.description || "No description yet."}</p>+ </div>+ </div>+ <div className="mt-4 grid grid-cols-3 gap-2">+ <MiniMetric value={seats.length} label="seats"/>+ <MiniMetric value={active} label="online"/>+ <MiniMetric value={projects || activities} label={projects ? "projects" : "nodes"}/>+ </div>+ </button>;+ })}+ </div> : <div className="grid h-52 place-items-center rounded-xl border border-dashed text-center text-sm text-muted-foreground">No units match this search.</div>}+ </div>+ </div>;+}++export function OrganizationSeatDirectory({+ chart,+ runtime,+ unitId,+ onSeatSelect,+ onSeatOpen,+}: {+ chart: OrganizationChart;+ runtime: OrganizationSeatRuntime[];+ unitId: string;+ onSeatSelect: (seat: OrganizationSeat | null) => void;+ onSeatOpen: (seat: OrganizationSeat) => void;+}) {+ const [query, setQuery] = useState("");+ const runtimeBySeat = useMemo(() => new Map(runtime.map((row) => [row.seatId, row])), [runtime]);+ const seats = useMemo(() => {+ const q = query.trim().toLowerCase();+ return chart.seats+ .filter((seat) => seat.unitId === unitId)+ .sort((a, b) => a.title.localeCompare(b.title) || a.name.localeCompare(b.name))+ .filter((seat) => !q || `${seat.title} ${seat.name} ${seat.role} ${seat.description}`.toLowerCase().includes(q));+ }, [chart.seats, query, unitId]);++ return <div data-slot="organization-seat-directory" className="flex h-full min-h-0 flex-col">+ <div className="shrink-0 border-b p-3">+ <div className="relative max-w-xl">+ <Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"/>+ <Input aria-label="Search organization seats" className="h-9 pl-9" placeholder="Search seats, roles, or people…" value={query} onChange={(event) => setQuery(event.target.value)}/>+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-3">+ {seats.length ? <div className="grid gap-2 @min-[720px]:grid-cols-2 @min-[1180px]:grid-cols-3">+ {seats.map((seat) => {+ const runtimeRow = runtimeBySeat.get(seat.id);+ const status = runtimeRow?.status ?? "vacant";+ return <button key={seat.id} type="button" onClick={() => onSeatSelect(seat)} onDoubleClick={() => onSeatOpen(seat)} className="min-w-0 rounded-xl border bg-card p-3 text-left shadow-sm transition hover:bg-accent/35 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <div className="flex items-start gap-2.5">+ <span className={cn("mt-1.5 size-2.5 shrink-0 rounded-full", runtimeDot[status])}/>+ <div className="min-w-0 flex-1">+ <div className="truncate text-sm font-semibold">{seat.title}</div>+ <div className="mt-0.5 truncate text-xs text-muted-foreground">{seat.name}</div>+ </div>+ <Badge variant="outline" className="shrink-0 text-[9px]">{status}</Badge>+ </div>+ <div className="mt-3 flex flex-wrap gap-1"><Badge variant="secondary" className="text-[9px]">{seat.role}</Badge><Badge variant="outline" className="text-[9px]">{seat.seatMode}</Badge><Badge variant="outline" className="text-[9px]">{seat.state}</Badge></div>+ {seat.description ? <p className="mt-2 line-clamp-2 text-[11px] leading-4 text-muted-foreground">{seat.description}</p> : null}+ <div className="mt-3 flex items-center gap-1.5 text-[10px] text-muted-foreground"><BriefcaseBusiness className="size-3"/><span className="truncate">{runtimeRow?.label || "No execution target bound"}</span></div>+ </button>;+ })}+ </div> : <div className="grid h-48 place-items-center rounded-xl border border-dashed text-center text-sm text-muted-foreground">No seats match this search.</div>}+ </div>+ </div>;+}++function Metric({ value, label, icon }: { value: number; label: string; icon: React.ReactNode }) {+ return <div className="min-w-16 rounded-lg border bg-card px-2.5 py-2"><div className="flex items-center justify-center gap-1 text-sm font-semibold">{icon}{value}</div><div className="mt-0.5 text-[9px] uppercase tracking-wide text-muted-foreground">{label}</div></div>;+}++function MiniMetric({ value, label }: { value: number; label: string }) {+ return <div className="rounded-lg bg-muted/45 px-2 py-2 text-center"><div className="text-sm font-semibold">{value}</div><div className="text-[9px] uppercase tracking-wide text-muted-foreground">{label}</div></div>;+}diff --git a/frontend/slices/organization/components/organization-view.tsx b/frontend/slices/organization/components/organization-view.tsxindex 02c194ac..7c57610b 100644--- a/frontend/slices/organization/components/organization-view.tsx+++ b/frontend/slices/organization/components/organization-view.tsx@@ -1,22 +1,27 @@"use client";import { useCallback, useEffect, useMemo, useState } from "react";-import { ArrowLeft, Building2, Pencil, Plus, RefreshCw, Users, X } from "lucide-react";+import { Activity, ArrowLeft, Building2, Cable, LayoutGrid, Network, Pencil, Plus, RefreshCw, Users, Workflow, X } from "lucide-react";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import type { OrganizationSeat, OrganizationUnit } from "@/lib/contracts/organization";import { getOrganization, mutateOrganization, type OrganizationPayload } from "../lib/organization-api";import { OrganizationCanvas } from "./organization-canvas";import { OrganizationEditor } from "./organization-editor";+import { OrganizationSeatDirectory, OrganizationUnitDirectory } from "./organization-directory";import { ProjectFlow } from "./project-flow";import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";+import { openWindow } from "@/features/appshell";type Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat; unitId?: string } | null;+type CanvasMode = "directory" | "map";export function OrganizationView() {const [data, setData] = useState<OrganizationPayload | null>(null);const [selectedUnit, setSelectedUnit] = useState("__all__");const [tab, setTab] = useState("projects");+ const [overviewMode, setOverviewMode] = useState<CanvasMode>("directory");+ const [seatMode, setSeatMode] = useState<CanvasMode>("directory");const [selectedSeatId, setSelectedSeatId] = useState<string | null>(null);const [draft, setDraft] = useState<Draft>(null);const [error, setError] = useState("");@@ -64,20 +69,25 @@ export function OrganizationView() {if (kind === "unit" && id === selectedUnit) setSelectedUnit("__all__");if (kind === "seat" && id === selectedSeatId) setSelectedSeatId(null);};- const chooseUnit = (id: string) => { setSelectedUnit(id); setSelectedSeatId(null); setTab("projects"); };+ const chooseUnit = (id: string) => {+ setSelectedUnit(id);+ setSelectedSeatId(null);+ setTab("projects");+ setSeatMode("directory");+ };if (!data) return <div className="grid h-full place-items-center p-6 text-sm text-muted-foreground">{error || "Loading organization…"}</div>;return (- <div data-slot="organization-feature" className="@container grid h-full min-h-0 min-w-0 grid-rows-[auto_minmax(0,1fr)] overflow-hidden @min-[700px]:grid-cols-[220px_minmax(0,1fr)] @min-[700px]:grid-rows-1">- <aside className="min-w-0 border-b bg-card/20 @min-[700px]:flex @min-[700px]:min-h-0 @min-[700px]:flex-col @min-[700px]:border-b-0 @min-[700px]:border-r">- <div className="flex min-w-0 items-center gap-2 px-3 py-2.5 @min-[700px]:py-3">+ <div data-slot="organization-feature" className="@container grid h-full min-h-0 min-w-0 grid-rows-[auto_minmax(0,1fr)] overflow-hidden @min-[760px]:grid-cols-[236px_minmax(0,1fr)] @min-[760px]:grid-rows-1">+ <aside className="min-w-0 border-b bg-card/25 @min-[760px]:flex @min-[760px]:min-h-0 @min-[760px]:flex-col @min-[760px]:border-b-0 @min-[760px]:border-r">+ <div className="flex min-w-0 items-center gap-2 border-b/0 px-3 py-2.5 @min-[760px]:py-3"><div className="min-w-0 flex-1"><div className="truncate font-semibold">Organization</div><div className="text-[11px] text-muted-foreground">{data.chart.units.length} units · {data.chart.seats.length} seats</div></div><Button size="icon" variant="ghost" className="size-8 shrink-0" onClick={() => void load()} aria-label="Refresh organization"><RefreshCw className="size-3.5"/></Button><Button size="icon" className="size-8 shrink-0" onClick={() => setDraft({ kind: "unit" })} aria-label="New organization unit"><Plus className="size-3.5"/></Button></div>- <div className="px-3 pb-2.5 @min-[700px]:hidden">+ <div className="px-3 pb-2.5 @min-[760px]:hidden"><label className="sr-only" htmlFor="organization-unit-picker">Organization unit</label><select id="organization-unit-picker" aria-label="Organization unit" className="h-10 w-full min-w-0 rounded-lg border bg-background px-3 text-sm" value={selectedUnit} onChange={(event) => chooseUnit(event.target.value)}><option value="__all__">All organization · {data.chart.seats.length}</option>@@ -85,40 +95,69 @@ export function OrganizationView() {</select></div>- <nav aria-label="Organization units" className="hidden min-h-0 flex-1 space-y-1 overflow-y-auto px-2 pb-2 @min-[700px]:block">+ <nav aria-label="Organization units" className="hidden min-h-0 flex-1 space-y-1 overflow-y-auto px-2 pb-2 @min-[760px]:block"><UnitButton active={selectedUnit === "__all__"} icon={<Users className="size-4"/>} label="All organization" count={data.chart.seats.length} onClick={() => chooseUnit("__all__")}/>- {units.map((unit) => <UnitButton key={unit.id} active={selectedUnit === unit.id} icon={<Building2 className="size-4"/>} label={unit.name} count={data.chart.seats.filter((seat) => seat.unitId === unit.id).length} onClick={() => chooseUnit(unit.id)}/>) }+ {units.map((unit) => <UnitButton key={unit.id} active={selectedUnit === unit.id} icon={<Building2 className="size-4"/>} label={unit.name} count={data.chart.seats.filter((seat) => seat.unitId === unit.id).length} onClick={() => chooseUnit(unit.id)}/>)}</nav>+ <div className="hidden shrink-0 border-t p-2 @min-[760px]:grid @min-[760px]:grid-cols-3 @min-[920px]:grid-cols-1 @min-[920px]:gap-1">+ <OrgLink icon={<Workflow className="size-3.5"/>} label="Workflows" onClick={() => openWindow("workflows", "Workflows")}/>+ <OrgLink icon={<Cable className="size-3.5"/>} label="Integrations" onClick={() => openWindow("integrations", "Integrations")}/>+ <OrgLink icon={<Activity className="size-3.5"/>} label="System" onClick={() => openWindow("system-monitor", "System Monitor")}/>+ </div></aside><section className="flex min-h-0 min-w-0 flex-col overflow-hidden">- <div className="grid min-h-12 shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 border-b px-3 py-2">+ <div className="grid min-h-14 shrink-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-2 border-b px-3 py-2"><div className="flex min-w-0 items-start gap-1.5">{currentUnit ? <Button size="icon" variant="ghost" className="size-8 shrink-0" onClick={() => chooseUnit("__all__")} aria-label="Back to organization overview"><ArrowLeft className="size-4"/></Button> : null}<div className="min-w-0 flex-1"><div className="flex min-w-0 items-center gap-2"><h2 className="truncate text-sm font-semibold">{currentUnit?.name ?? data.chart.name}</h2>{currentUnit ? <Badge variant="secondary" className="shrink-0">{currentUnit.kind}</Badge> : <Badge variant="outline" className="shrink-0">overview</Badge>}</div>- <p className="mt-0.5 hidden max-w-2xl text-[11px] leading-snug text-muted-foreground @min-[520px]:line-clamp-2">{currentUnit?.description || "Open a unit to inspect its reporting graph. Pan, zoom, fit, and use the minimap like a workflow canvas."}</p>+ <p className="mt-0.5 hidden max-w-3xl text-[11px] leading-snug text-muted-foreground @min-[520px]:line-clamp-2">{currentUnit?.description || "Directory first for fast scanning. The map remains available when you need reporting or relationship topology."}</p></div></div>- <div className="flex shrink-0 gap-1">{currentUnit ? <Button size="sm" variant="outline" className="h-8 px-2" onClick={() => setDraft({ kind: "unit", item: currentUnit })}><Pencil className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Unit</span></Button> : null}{currentUnit ? <Button size="sm" className="h-8 px-2" onClick={() => setDraft({ kind: "seat", unitId: currentUnit.id })}><Users className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Seat</span></Button> : null}</div>+ <div className="flex shrink-0 gap-1">+ {currentUnit ? <Button size="sm" variant="outline" className="h-8 px-2" onClick={() => setDraft({ kind: "unit", item: currentUnit })}><Pencil className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Unit</span></Button> : null}+ {currentUnit ? <Button size="sm" className="h-8 px-2" onClick={() => setDraft({ kind: "seat", unitId: currentUnit.id })}><Users className="size-3 @min-[480px]:mr-1"/><span className="hidden @min-[480px]:inline">Seat</span></Button> : null}+ </div></div>+{error ? <div className="shrink-0 border-b bg-destructive/10 px-4 py-2 text-xs text-destructive">{error}</div> : null}+{currentUnit ? <Tabs key={currentUnit.id} className="flex min-h-0 flex-1 flex-col gap-0">- <TabsList className="mx-3 my-2 w-fit shrink-0"><TabsTrigger active={tab === "projects"} onClick={() => setTab("projects")}>Projects</TabsTrigger><TabsTrigger active={tab === "seats"} onClick={() => setTab("seats")}>Seats</TabsTrigger></TabsList>+ <div className="flex min-w-0 shrink-0 items-center justify-between gap-2 border-b px-3 py-2">+ <TabsList className="w-fit shrink-0"><TabsTrigger active={tab === "projects"} onClick={() => setTab("projects")}>Projects</TabsTrigger><TabsTrigger active={tab === "seats"} onClick={() => setTab("seats")}>Seats</TabsTrigger></TabsList>+ {tab === "seats" ? <ModeSwitch value={seatMode} onChange={setSeatMode}/> : <span className="hidden text-[10px] text-muted-foreground @min-[720px]:inline">Project map starts at a readable cluster; press F to fit everything.</span>}+ </div>{tab === "projects" ? <div className="relative min-h-0 flex-1 overflow-hidden"><ProjectFlow unit={currentUnit} onSave={async (action, record) => { const next = await mutateOrganization({ action, expected_revision: data.chart.revision, data: record }); setData(next); }}/></div> : <div className="relative min-h-0 flex-1 overflow-hidden">- <OrganizationCanvas chart={data.chart} runtime={data.runtime} unitId={currentUnit?.id ?? ""} selectedSeatId={selectedSeatId} onUnitSelect={chooseUnit} onSeatSelect={(seat) => setSelectedSeatId(seat?.id ?? null)} onSeatOpen={(seat) => setDraft({ kind: "seat", item: seat })}/>- {selectedSeat ? <SeatInspector seat={selectedSeat} runtimeLabel={selectedRuntime?.label} runtimeStatus={selectedRuntime?.status} onClose={() => setSelectedSeatId(null)} onEdit={() => setDraft({ kind: "seat", item: selectedSeat })}/> : null}+ {seatMode === "directory" ? <OrganizationSeatDirectory chart={data.chart} runtime={data.runtime} unitId={currentUnit.id} onSeatSelect={(seat) => setSelectedSeatId(seat?.id ?? null)} onSeatOpen={(seat) => setDraft({ kind: "seat", item: seat })}/> : <OrganizationCanvas chart={data.chart} runtime={data.runtime} unitId={currentUnit.id} selectedSeatId={selectedSeatId} onUnitSelect={chooseUnit} onSeatSelect={(seat) => setSelectedSeatId(seat?.id ?? null)} onSeatOpen={(seat) => setDraft({ kind: "seat", item: seat })}/>}+ {selectedSeat ? <SeatInspector seat={selectedSeat} runtimeLabel={selectedRuntime?.label} runtimeStatus={selectedRuntime?.status} onClose={() => setSelectedSeatId(null)} onEdit={() => setDraft({ kind: "seat", item: selectedSeat })}/> : null}</div>}- </Tabs> : <div className="relative min-h-0 min-w-0 flex-1 overflow-hidden">- <OrganizationCanvas chart={data.chart} runtime={data.runtime} unitId="" selectedSeatId={null} onUnitSelect={chooseUnit} onSeatSelect={() => {}} onSeatOpen={() => {}}/>+ </Tabs> : <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">+ <div className="flex shrink-0 items-center justify-between gap-3 border-b px-3 py-2">+ <div className="min-w-0 text-xs text-muted-foreground">Browse the organization as cards, or switch to the relationship map when topology matters.</div>+ <ModeSwitch value={overviewMode} onChange={setOverviewMode}/>+ </div>+ <div className="relative min-h-0 min-w-0 flex-1 overflow-hidden">+ {overviewMode === "directory" ? <OrganizationUnitDirectory chart={data.chart} runtime={data.runtime} onUnitSelect={chooseUnit}/> : <OrganizationCanvas chart={data.chart} runtime={data.runtime} unitId="" selectedSeatId={null} onUnitSelect={chooseUnit} onSeatSelect={() => {}} onSeatOpen={() => {}}/>}+ </div></div>}- <div className="hidden shrink-0 border-t px-3 py-1.5 text-[10px] leading-snug text-muted-foreground @min-[700px]:block">V select · H pan · Space temporary pan · F fit · wheel/pinch zoom. Seat execution status remains capability-safe and does not grant authority.</div></section><OrganizationEditor draft={draft} chart={data.chart} onClose={() => setDraft(null)} onSave={save} onDelete={remove}/></div>);}+function OrgLink({ icon, label, onClick }: { icon: React.ReactNode; label: string; onClick: () => void }) {+ return <button type="button" onClick={onClick} className="flex min-w-0 items-center justify-center gap-1.5 rounded-md px-2 py-1.5 text-[10px] text-muted-foreground hover:bg-accent/60 hover:text-foreground @min-[920px]:justify-start">{icon}<span className="hidden truncate @min-[920px]:inline">{label}</span></button>;+}++function ModeSwitch({ value, onChange }: { value: CanvasMode; onChange: (value: CanvasMode) => void }) {+ return <div className="flex shrink-0 rounded-lg border bg-muted/30 p-0.5" role="group" aria-label="Organization view">+ <button type="button" aria-pressed={value === "directory"} className={`flex h-7 items-center gap-1.5 rounded-md px-2 text-[11px] ${value === "directory" ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground"}`} onClick={() => onChange("directory")}><LayoutGrid className="size-3.5"/>Directory</button>+ <button type="button" aria-pressed={value === "map"} className={`flex h-7 items-center gap-1.5 rounded-md px-2 text-[11px] ${value === "map" ? "bg-background font-medium shadow-sm" : "text-muted-foreground hover:text-foreground"}`} onClick={() => onChange("map")}><Network className="size-3.5"/>Map</button>+ </div>;+}+function UnitButton({ active, icon, label, count, onClick }: { active: boolean; icon: React.ReactNode; label: string; count: number; onClick: () => void }) {return <button type="button" onClick={onClick} className={`flex w-full min-w-0 items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm ${active ? "bg-accent font-medium" : "hover:bg-accent/60"}`}>{icon}<span className="min-w-0 flex-1 truncate">{label}</span><Badge variant="outline" className="shrink-0 text-[9px]">{count}</Badge></button>;}diff --git a/frontend/slices/organization/components/project-flow.tsx b/frontend/slices/organization/components/project-flow.tsxindex 55039652..a60664d4 100644--- a/frontend/slices/organization/components/project-flow.tsx+++ b/frontend/slices/organization/components/project-flow.tsx@@ -88,6 +88,8 @@ export function ProjectFlow({ unit, onSave }: Props) {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)}+ initialFitNodeIds={nodes.slice(0, 6).map((node) => node.id)}+ initialFitMaxZoom={0.96}/> : <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>}{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>diff --git a/frontend/slices/os-shell/n8n-app.test.ts b/frontend/slices/os-shell/n8n-app.test.tsnew file mode 100644index 00000000..0efdc419--- /dev/null+++ b/frontend/slices/os-shell/n8n-app.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";+import { BUILTIN_APPS } from "./shell.manifest";++describe("n8n app registration", () => {+ it("exposes n8n as a first-class built-in route separate from Workflows", () => {+ const n8n = BUILTIN_APPS.find((item) => item.id === "n8n");+ const workflows = BUILTIN_APPS.find((item) => item.id === "workflows");+ expect(n8n).toBeDefined();+ expect(n8n?.title).toBe("n8n");+ expect(n8n?.slug).toBe("n8n");+ expect(n8n?.pinned).toBe(true);+ expect(workflows?.slug).toBe("workflows");+ expect(n8n?.id).not.toBe(workflows?.id);+ });+});diff --git a/frontend/slices/os-shell/shell.manifest.ts b/frontend/slices/os-shell/shell.manifest.tsindex c485bee6..91786b6a 100644--- a/frontend/slices/os-shell/shell.manifest.ts+++ b/frontend/slices/os-shell/shell.manifest.ts@@ -22,6 +22,7 @@ import { quicklinksApp } from "@/features/quicklinks";import { docsApp } from "@/features/docs";import { integrationsApp } from "@/features/integrations";import { workflowsApp } from "@/features/workflows";+import { n8nApp } from "@/features/n8n";import { organizationApp } from "@/features/organization";import { cloudflareApp, dokployApp } from "@/features/infrastructure";import { themeQuickPickerFeature } from "./theme-quick-picker";@@ -70,6 +71,7 @@ export const BUILTIN_APPS: AppDescriptor[] = [withSlug(withArtwork(nineRouterApp), "9router"),pin(withSlug(integrationsApp, "connections")),pin(withSlug(withArtwork(workflowsApp), "workflows")),+ pin(withSlug(withArtwork(n8nApp), "n8n")),withSlug(withArtwork(organizationApp), "organization"),withSlug(withArtwork(dokployApp), "dokploy"),withSlug(withArtwork(cloudflareApp), "cloudflare"),diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsxindex aad96ff1..f5d8d3dc 100644--- a/frontend/slices/workflows/app.tsx+++ b/frontend/slices/workflows/app.tsx@@ -2,11 +2,11 @@import { pruneGraphCustomNodes } from "@/lib/contracts/graph-custom-nodes";import { useEffect, useMemo, useState } from "react";-import { Activity, Copy, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";+import { Activity, Building2, Cable, Copy, Download, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";import type { AppProps, ToolbarItem } from "@/features/appshell";import type { SessionGraphView } from "@/lib/contracts/session-monitor";import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";-import { AppFrame, ResponsiveDialog, ResponsiveToolbar, openWindow, useContainer, useResponsive } from "@/features/appshell";+import { AppFrame, ResponsiveDialog, ResponsiveToolbar, openWindow, saveAs, useContainer, useResponsive } from "@/features/appshell";import { Badge } from "@/components/ui/badge";import { Switch } from "@/components/ui/switch";import { Input } from "@/components/ui/input";@@ -18,11 +18,11 @@ import { WorkflowNodePalette } from "./components/workflow-node-palette";import { WorkflowSessionDetails } from "./components/workflow-session-details";import { WorkflowSessionLibrary } from "./components/workflow-session-library";import { tidyWorkflowNodes } from "./lib/canvas-layout";+import { buildWorkflowPackage, workflowPackageFilename, type WorkflowDefinition } from "./lib/portability";import { cloneGraph, createFromTemplate, createGraph, deleteGraph, getGraph, getSessionGraph, listGraphs, listWorkflowLearning, resolveNode, runGraph, runStatus, saveSessionWorkflowDraft, updateGraph, type WorkflowLearningRecipeSummary } from "./lib/api";-type Definition = Omit<WorkflowGraph, "version" | "id" | "revision" | "createdAt" | "updatedAt">;type LibraryMode = "automations" | "sessions";-function starterGraph(): Definition { return { name: "New Workflow", description: "Private workflow graph.", status: "draft", inputs: {}, metadata: { provenance: "user" }, nodes: [{ id: "manual", name: "Manual Trigger", type: "manual", position: { x: 80, y: 160 }, config: {} }, { id: "output", name: "Output", type: "output", position: { x: 420, y: 160 }, config: {} }], edges: [{ id: "edge-start", source: "manual", target: "output" }] }; }+function starterGraph(): WorkflowDefinition { return { name: "New Workflow", description: "Private workflow graph.", status: "draft", inputs: {}, metadata: { provenance: "user" }, nodes: [{ id: "manual", name: "Manual Trigger", type: "manual", position: { x: 80, y: 160 }, config: {} }, { id: "output", name: "Output", type: "output", position: { x: 420, y: 160 }, config: {} }], edges: [{ id: "edge-start", source: "manual", target: "output" }] }; }function payloadSessionId(payload: unknown): string | undefined { if (!payload || typeof payload !== "object") return undefined; const row = payload as { view?: unknown; sessionId?: unknown }; return row.view === "sessions" && typeof row.sessionId === "string" ? row.sessionId : undefined; }export default function WorkflowsApp(props: AppProps) {@@ -63,10 +63,12 @@ export default function WorkflowsApp(props: AppProps) {const refreshSession = async () => { if (!sessionView) return; const [next, recipes] = await Promise.all([getSessionGraph(sessionView.session.id), listWorkflowLearning(true).catch(() => [])]); setSessionView(next); setLearning(recipes); if (sessionSelected && !next.graph.nodes.some((item) => item.id === sessionSelected)) setSessionSelected("session-root"); };const createBlank = () => wrap(async () => { const next = await createGraph(starterGraph()); setLibraryMode("automations"); await load(next.id); setSelected("manual"); setLibraryOpen(false); });const createTemplate = (id: string) => wrap(async () => { const next = await createFromTemplate(id); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });- const createAI = (definition: Definition) => wrap(async () => { const next = await createGraph(definition); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });+ const createAI = (definition: WorkflowDefinition) => wrap(async () => { const next = await createGraph(definition); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });+ const createImported = (definition: WorkflowDefinition) => wrap(async () => { const next = await createGraph({ ...definition, metadata: { ...definition.metadata, provenance: "import" } }); setLibraryMode("automations"); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });const saveCurrent = async () => { if (!graph) throw new Error("No workflow selected"); if (!dirty) return graph; const next = await updateGraph(graph); setGraph(next); setDirty(false); setGraphs(await listGraphs()); return next; };const save = () => graph && wrap(async () => { await saveCurrent(); setMessage("Saved"); });const duplicate = () => graph && wrap(async () => { const next = await cloneGraph(graph.id); await load(next.id); });+ const exportCurrent = () => { if (!graph) return; const blob = new Blob([JSON.stringify(buildWorkflowPackage(graph), null, 2)], { type: "application/json" }); saveAs(URL.createObjectURL(blob), workflowPackageFilename(graph.name)); setMessage("Exported portable workflow package"); };const remove = () => graph && wrap(async () => { await deleteGraph(graph); setSelected(null); setRun(null); const list = await listGraphs(); setGraphs(list); setGraph(list[0] ? await getGraph(list[0].id) : null); setDirty(false); });const execute = () => graph && wrap(async () => { const saved = await saveCurrent(); setRun(await runGraph(saved.id)); setPanel("run"); if (overlayPane) setDetailsOpen(true); });const updateNode = (next: WorkflowGraphNode) => graph && mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === next.id ? next : item) });@@ -87,26 +89,30 @@ export default function WorkflowsApp(props: AppProps) {const toggleLibrary = () => overlayPane ? setLibraryOpen(true) : setShowLibrary((value) => !value);const toggleDetails = () => overlayPane ? setDetailsOpen(true) : setShowDetails((value) => !value);- const automationLibrary = <WorkflowLibrary graphs={graphs} activeId={graph?.id} search={search} onSearch={setSearch} onSelect={(id) => void wrap(() => selectGraph(id))} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/>;+ const automationLibrary = <WorkflowLibrary graphs={graphs} activeId={graph?.id} search={search} onSearch={setSearch} onSelect={(id) => void wrap(() => selectGraph(id))} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }} onImport={async (definition) => { await createImported(definition); }}/>;const library = <div className="flex h-full min-h-0 flex-col"><div className="grid grid-cols-2 gap-1 border-b p-2">{(["automations", "sessions"] as const).map((mode) => <button key={mode} type="button" className={`rounded-md px-2 py-1.5 text-xs capitalize ${libraryMode === mode ? "bg-accent font-semibold" : "text-muted-foreground hover:bg-accent/60"}`} onClick={() => setLibraryMode(mode)}>{mode}</button>)}</div><div className="min-h-0 flex-1">{libraryMode === "automations" ? automationLibrary : <WorkflowSessionLibrary activeId={sessionView?.session.id} onSelect={(id) => void wrap(() => selectSession(id))}/>}</div></div>;const details = libraryMode === "sessions" && sessionView ? <WorkflowSessionDetails view={sessionView} node={sessionNode} onOpenTerminal={openSessionTerminal} onOpenCode={openSessionCode} onSaveDraft={saveSessionDraft} savingDraft={busy} learning={learning}/> : graph ? <WorkflowDetails graph={graph} graphs={graphs} node={node} run={run} panel={panel} onPanel={setPanel} onNode={updateNode} onDeleteNode={(id) => deleteNodes([id])} onGraph={mutate} onRunSelect={(selectedRun) => { setRun(selectedRun); setPanel("run"); }} onRestored={(next) => { setGraph(next); setDirty(false); void listGraphs().then(setGraphs); }}/> : null;const toolbarItems: ToolbarItem[] = [{ id: "library", label: "Workflow library", icon: PanelLeft, onClick: toggleLibrary, primary: true },+ { id: "organization", label: "Organization", icon: Building2, onClick: () => openWindow("organization", "Organization") },+ { id: "connections", label: "Integrations", icon: Cable, onClick: () => openWindow("integrations", "Integrations") },{ id: "refresh", label: "Refresh", icon: RefreshCw, onClick: () => void wrap(async () => { if (libraryMode === "sessions") await refreshSession(); else await load(undefined, true); }), disabled: busy },...(libraryMode === "automations" && graph ? [{ id: "duplicate", label: "Duplicate", icon: Copy, onClick: () => void duplicate(), disabled: busy },- { id: "save", label: "Save", icon: Save, onClick: () => void save(), disabled: busy || !dirty },+ { id: "export", label: "Export", icon: Download, onClick: exportCurrent, disabled: busy },+ { id: "save", label: "Save", icon: Save, onClick: () => void save(), disabled: busy || !dirty, primary: true },{ id: "run", label: "Run", icon: Play, onClick: () => void execute(), disabled: busy, primary: true },{ id: "details", label: "Details", icon: PanelRight, onClick: toggleDetails },{ id: "delete", label: "Delete", icon: Trash2, onClick: () => void remove(), disabled: busy },] satisfies ToolbarItem[] : libraryMode === "sessions" && sessionView ? [{ id: "details", label: "Session details", icon: PanelRight, onClick: toggleDetails }] satisfies ToolbarItem[] : []),];+ const toolbarCompact = overlayPane || toolbarItems.length > 7;const showLibraryPanel = !overlayPane && showLibrary;const showDetailsPanel = !overlayPane && showDetails && Boolean(libraryMode === "sessions" ? sessionView : graph);const headerTitle = libraryMode === "sessions" ? sessionView?.session.label : graph?.name;return <div ref={appRef} data-slot="workflows-feature" className="@container h-full min-h-0 min-w-0">- <AppFrame safeArea={false} className="h-full min-w-0" toolbar={<div className="flex h-11 min-w-0 items-center gap-1 px-2 @min-[700px]:gap-2 @min-[700px]:px-3"><Workflow className="hidden size-4 shrink-0 @min-[700px]:block"/><span className="hidden shrink-0 text-sm font-semibold @min-[700px]:inline">Workflows</span>{libraryMode === "sessions" ? <Badge variant="outline" className="shrink-0"><Activity className="mr-1 size-3"/>Session</Badge> : dirty ? <Badge variant="outline" className="hidden shrink-0 @min-[520px]:inline-flex">Unsaved</Badge> : null}{libraryMode === "automations" && graph ? <Input aria-label="Workflow name" className="h-8 min-w-[7rem] max-w-56 flex-1 @max-[600px]:max-w-none" value={graph.name} onChange={(event) => mutate({ ...graph, name: event.target.value })}/> : <div className="min-w-0 flex-1 truncate text-sm font-medium">{headerTitle || (libraryMode === "sessions" ? "Sessions" : "Workflows")}</div>}{libraryMode === "automations" ? <WorkflowCreateDialog compact={overlayPane} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/> : null}<ResponsiveToolbar items={toolbarItems} compact={overlayPane} className="ml-auto shrink-0"/></div>}>+ <AppFrame safeArea={false} className="h-full min-w-0" toolbar={<div className="flex h-11 min-w-0 items-center gap-1 px-2 @min-[700px]:gap-2 @min-[700px]:px-3"><Workflow className="hidden size-4 shrink-0 @min-[700px]:block"/><span className="hidden shrink-0 text-sm font-semibold @min-[700px]:inline">Workflows</span>{libraryMode === "sessions" ? <Badge variant="outline" className="shrink-0"><Activity className="mr-1 size-3"/>Session</Badge> : dirty ? <Badge variant="outline" className="hidden shrink-0 @min-[520px]:inline-flex">Unsaved</Badge> : null}{libraryMode === "automations" && graph ? <Input aria-label="Workflow name" className="h-8 min-w-[7rem] max-w-56 flex-1 @max-[600px]:max-w-none" value={graph.name} onChange={(event) => mutate({ ...graph, name: event.target.value })}/> : <div className="min-w-0 flex-1 truncate text-sm font-medium">{headerTitle || (libraryMode === "sessions" ? "Sessions" : "Workflows")}</div>}{libraryMode === "automations" ? <WorkflowCreateDialog compact={overlayPane} onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }} onImport={async (definition) => { await createImported(definition); }}/> : null}<ResponsiveToolbar items={toolbarItems} compact={toolbarCompact} className="ml-auto shrink-0"/></div>}><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">diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsxindex e1a260ac..99d3f84f 100644--- a/frontend/slices/workflows/components/workflow-canvas.tsx+++ b/frontend/slices/workflows/components/workflow-canvas.tsx@@ -80,6 +80,6 @@ export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onMoveMany,onCuonNodesDelete={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>+ miniMapNodeColor={(node)=>node.type==="customGroup"?"var(--primary)":minimapColor(node as FlowNode)} compactFitNodeIds={compactIds} compactFitMaxZoom={readOnly?0.72:0.9} initialFitNodeIds={compactIds} initialFitMaxZoom={readOnly?0.78:0.94}/></div></div>;}diff --git a/frontend/slices/workflows/components/workflow-create-dialog.tsx b/frontend/slices/workflows/components/workflow-create-dialog.tsxindex 9cd0c0d7..a9f201d9 100644--- a/frontend/slices/workflows/components/workflow-create-dialog.tsx+++ b/frontend/slices/workflows/components/workflow-create-dialog.tsx@@ -1,17 +1,84 @@"use client";+import { useEffect, useState } from "react";-import { Plus, Sparkles } from "lucide-react";-import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";+import { Plus, Sparkles, Upload } from "lucide-react";import { Button } from "@/components/ui/button";import { FormDrawer } from "@/features/appshell";import { ScrollArea } from "@/components/ui/scroll-area";import { Textarea } from "@/components/ui/textarea";import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import { aiSuggest, listTemplates } from "../lib/api";-type Definition=Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">;-export function WorkflowCreateDialog({onBlank,onTemplate,onAI,compact=false}:{onBlank:()=>Promise<void>;onTemplate:(id:string)=>Promise<void>;onAI:(definition:Definition)=>Promise<void>;compact?:boolean}){- const[open,setOpen]=useState(false),[tab,setTab]=useState<"blank"|"templates"|"ai">("templates"),[templates,setTemplates]=useState<Array<{id:string;title:string;description:string;tags:string[];nodeCount:number}>>([]),[prompt,setPrompt]=useState(""),[busy,setBusy]=useState(false),[error,setError]=useState("");- useEffect(()=>{if(!open)return;let cancelled=false;void listTemplates().then((rows)=>{if(!cancelled)setTemplates(rows);}).catch(()=>undefined);return()=>{cancelled=true;};},[open]);- const run=async(fn:()=>Promise<void>)=>{setBusy(true);setError("");try{await fn();setOpen(false);}catch(e){setError(e instanceof Error?e.message:"Action failed");}finally{setBusy(false);}};- return <><Button size={compact?"icon":"sm"} variant="outline" className={compact?"size-9 shrink-0":""} onClick={()=>setOpen(true)} aria-label={compact?"New workflow":undefined}>{compact?<Plus className="size-4"/>:"New"}</Button><FormDrawer open={open} onOpenChange={setOpen} size="lg"><FormDrawer.Header><FormDrawer.Title>Create workflow</FormDrawer.Title><FormDrawer.Description>Blank graph, reusable template, or AI-assisted draft. Secrets stay outside definitions.</FormDrawer.Description></FormDrawer.Header><FormDrawer.Body className="space-y-3"><Tabs><TabsList>{(["templates","blank","ai"] as const).map((value)=><TabsTrigger key={value} active={tab===value} onClick={()=>setTab(value)}>{value}</TabsTrigger>)}</TabsList></Tabs>{tab==="blank"&&<div className="rounded-lg border p-4"><p className="mb-3 text-sm text-muted-foreground">Start with Manual Trigger → Output.</p><Button disabled={busy} onClick={()=>void run(onBlank)}>Create blank</Button></div>}{tab==="templates"&&<ScrollArea className="h-72"><div className="grid gap-2 sm:grid-cols-2">{templates.map((item)=><button key={item.id} type="button" disabled={busy} onClick={()=>void run(()=>onTemplate(item.id))} className="rounded-lg border p-3 text-left hover:bg-accent"><div className="text-sm font-semibold">{item.title}</div><p className="mt-1 text-xs text-muted-foreground">{item.description}</p><div className="mt-2 text-[10px] text-muted-foreground">{item.nodeCount} nodes · {item.tags.join(" · ")}</div></button>)}</div></ScrollArea>}{tab==="ai"&&<div className="space-y-3"><Textarea className="min-h-32" placeholder="Describe the workflow, triggers, branches, project/integration actions, and expected output…" value={prompt} onChange={(e)=>setPrompt(e.target.value)}/><Button disabled={busy||!prompt.trim()} onClick={()=>void run(async()=>onAI(await aiSuggest(prompt)))}><Sparkles className="mr-2 size-4"/>Generate draft</Button></div>}{error&&<p className="text-xs text-destructive">{error}</p>}</FormDrawer.Body></FormDrawer></>;+import { parseWorkflowPackage, type WorkflowDefinition } from "../lib/portability";++export function WorkflowCreateDialog({+ onBlank,+ onTemplate,+ onAI,+ onImport,+ compact = false,+}: {+ onBlank: () => Promise<void>;+ onTemplate: (id: string) => Promise<void>;+ onAI: (definition: WorkflowDefinition) => Promise<void>;+ onImport: (definition: WorkflowDefinition) => Promise<void>;+ compact?: boolean;+}) {+ const [open, setOpen] = useState(false);+ const [tab, setTab] = useState<"blank" | "templates" | "ai" | "import">("templates");+ const [templates, setTemplates] = useState<Array<{ id: string; title: string; description: string; tags: string[]; nodeCount: number }>>([]);+ const [prompt, setPrompt] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ useEffect(() => {+ if (!open) return;+ let cancelled = false;+ void listTemplates().then((rows) => { if (!cancelled) setTemplates(rows); }).catch(() => undefined);+ return () => { cancelled = true; };+ }, [open]);++ const run = async (fn: () => Promise<void>) => {+ setBusy(true);+ setError("");+ try { await fn(); setOpen(false); }+ catch (cause) { setError(cause instanceof Error ? cause.message : "Action failed"); }+ finally { setBusy(false); }+ };++ const importFile = async (file: File) => {+ if (file.size > 2 * 1024 * 1024) throw new Error("Workflow package exceeds 2 MiB");+ await onImport(parseWorkflowPackage(await file.text()));+ };++ return <>+ <Button size={compact ? "icon" : "sm"} variant="outline" className={compact ? "size-9 shrink-0" : ""} onClick={() => setOpen(true)} aria-label={compact ? "New workflow" : undefined}>+ {compact ? <Plus className="size-4"/> : "New"}+ </Button>+ <FormDrawer open={open} onOpenChange={setOpen} size="lg">+ <FormDrawer.Header>+ <FormDrawer.Title>Create workflow</FormDrawer.Title>+ <FormDrawer.Description>Blank graph, template, portable package, or AI-assisted draft. Secrets stay outside definitions.</FormDrawer.Description>+ </FormDrawer.Header>+ <FormDrawer.Body className="space-y-3">+ <Tabs><TabsList>{(["templates", "blank", "import", "ai"] as const).map((value) => <TabsTrigger key={value} active={tab === value} onClick={() => setTab(value)}>{value}</TabsTrigger>)}</TabsList></Tabs>+ {tab === "blank" ? <div className="rounded-lg border p-4"><p className="mb-3 text-sm text-muted-foreground">Start with Manual Trigger → Output.</p><Button disabled={busy} onClick={() => void run(onBlank)}>Create blank</Button></div> : null}+ {tab === "templates" ? <ScrollArea className="h-72"><div className="grid gap-2 sm:grid-cols-2">{templates.map((item) => <button key={item.id} type="button" disabled={busy} onClick={() => void run(() => onTemplate(item.id))} className="rounded-lg border p-3 text-left hover:bg-accent"><div className="text-sm font-semibold">{item.title}</div><p className="mt-1 text-xs text-muted-foreground">{item.description}</p><div className="mt-2 text-[10px] text-muted-foreground">{item.nodeCount} nodes · {item.tags.join(" · ")}</div></button>)}</div></ScrollArea> : null}+ {tab === "import" ? <div className="rounded-lg border border-dashed p-5 text-center">+ <Upload className="mx-auto size-6 text-muted-foreground"/>+ <p className="mt-2 text-sm font-medium">Import portable workflow JSON</p>+ <p className="mt-1 text-xs text-muted-foreground">Accepts MSO workflow packages or a compatible graph definition up to 2 MiB. Server validation still applies.</p>+ <label className="mt-4 inline-flex h-9 cursor-pointer items-center rounded-md border bg-background px-3 text-sm font-medium hover:bg-accent">+ Choose file+ <input type="file" className="sr-only" accept=".json,application/json" disabled={busy} onChange={(event) => {+ const file = event.target.files?.[0];+ event.currentTarget.value = "";+ if (file) void run(() => importFile(file));+ }}/>+ </label>+ </div> : null}+ {tab === "ai" ? <div className="space-y-3"><Textarea className="min-h-32" placeholder="Describe the workflow, triggers, branches, project/integration actions, and expected output…" value={prompt} onChange={(event) => setPrompt(event.target.value)}/><Button disabled={busy || !prompt.trim()} onClick={() => void run(async () => onAI(await aiSuggest(prompt)))}><Sparkles className="mr-2 size-4"/>Generate draft</Button></div> : null}+ {error ? <p className="text-xs text-destructive">{error}</p> : null}+ </FormDrawer.Body>+ </FormDrawer>+ </>;}diff --git a/frontend/slices/workflows/components/workflow-data-table-panel.tsx b/frontend/slices/workflows/components/workflow-data-table-panel.tsxnew file mode 100644index 00000000..efdfffb2--- /dev/null+++ b/frontend/slices/workflows/components/workflow-data-table-panel.tsx@@ -0,0 +1,103 @@+"use client";++import { useEffect, useMemo, useState } from "react";+import { Database, Plus, RefreshCw, Save, Trash2 } from "lucide-react";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { ScrollArea } from "@/components/ui/scroll-area";+import {+ createDataTable,+ deleteDataTable,+ deleteDataTableRow,+ getDataTable,+ listDataTables,+ upsertDataTableRow,+ type WorkflowDataTable,+ type WorkflowDataTableSummary,+} from "../lib/api";++export function WorkflowDataTablePanel() {+ const [tables, setTables] = useState<WorkflowDataTableSummary[]>([]);+ const [table, setTable] = useState<WorkflowDataTable | null>(null);+ const [name, setName] = useState("");+ const [columns, setColumns] = useState("");+ const [rowId, setRowId] = useState("");+ const [values, setValues] = useState<Record<string, string>>({});+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ const load = async (selectId?: string) => {+ setError("");+ const next = await listDataTables();+ setTables(next);+ const id = selectId ?? table?.id ?? next[0]?.id;+ setTable(id ? await getDataTable(id) : null);+ };+ useEffect(() => {+ let alive = true;+ void listDataTables().then(async (next) => {+ if (!alive) return;+ setTables(next);+ if (next[0]) setTable(await getDataTable(next[0].id));+ }).catch((cause: unknown) => { if (alive) setError(cause instanceof Error ? cause.message : "Data tables unavailable"); });+ return () => { alive = false; };+ }, []);++ const rowDraft = useMemo(() => Object.fromEntries((table?.columns ?? []).map((column) => [column, values[column] ?? ""])), [table?.columns, values]);+ const act = async (fn: () => Promise<void>) => {+ setBusy(true); setError("");+ try { await fn(); } catch (cause) { setError(cause instanceof Error ? cause.message : "Data-table action failed"); }+ finally { setBusy(false); }+ };+ const create = () => void act(async () => {+ const nextColumns = columns.split(",").map((value) => value.trim()).filter(Boolean);+ const created = await createDataTable(name, nextColumns);+ setName(""); setColumns(""); await load(created.id);+ });+ const saveRow = () => table && void act(async () => {+ await upsertDataTableRow(table.id, rowDraft, rowId || undefined);+ setRowId(""); setValues({}); await load(table.id);+ });+ const editRow = (id: string, row: Record<string, unknown>) => {+ setRowId(id);+ setValues(Object.fromEntries((table?.columns ?? []).map((column) => [column, row[column] == null ? "" : typeof row[column] === "string" ? row[column] as string : JSON.stringify(row[column])])));+ };++ return <div className="flex h-full min-h-0 flex-col">+ <div className="space-y-2 border-b p-3">+ <div className="flex items-center justify-between gap-2"><div><div className="text-xs font-semibold">Data tables</div><div className="text-[10px] text-muted-foreground">Owner-private persistent workflow data. Credentials stay in Integrations.</div></div><Button size="icon" variant="ghost" className="size-7" disabled={busy} onClick={() => void act(() => load())} aria-label="Refresh data tables"><RefreshCw className="size-3.5"/></Button></div>+ <div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] gap-1.5">+ <Input className="h-8 text-xs" placeholder="Table name" value={name} onChange={(event) => setName(event.target.value)}/>+ <Input className="h-8 text-xs" placeholder="columns, comma, separated" value={columns} onChange={(event) => setColumns(event.target.value)}/>+ <Button size="icon" className="size-8" disabled={busy || !name.trim() || !columns.trim()} onClick={create} aria-label="Create data table"><Plus className="size-3.5"/></Button>+ </div>+ {tables.length ? <select aria-label="Workflow data table" className="h-8 w-full rounded-md border bg-background px-2 text-xs" value={table?.id ?? ""} onChange={(event) => void act(async () => setTable(await getDataTable(event.target.value)))}>+ {tables.map((item) => <option key={item.id} value={item.id}>{item.name} · {item.rowCount} rows</option>)}+ </select> : null}+ {error ? <p role="alert" className="text-xs text-destructive">{error}</p> : null}+ </div>++ {table ? <>+ <div className="space-y-2 border-b p-3">+ <div className="flex items-center gap-2"><Database className="size-3.5 text-muted-foreground"/><span className="min-w-0 flex-1 truncate text-xs font-semibold">{table.name}</span><span className="text-[10px] text-muted-foreground">{table.rows.length} rows · {table.columns.length} cols</span><Button size="icon" variant="ghost" className="size-7 text-muted-foreground" disabled={busy} onClick={() => void act(async () => { await deleteDataTable(table.id); setTable(null); await load(); })} aria-label="Delete data table"><Trash2 className="size-3.5"/></Button></div>+ <div className="grid gap-1.5">{table.columns.map((column) => <label key={column} className="grid grid-cols-[88px_minmax(0,1fr)] items-center gap-2 text-[10px] text-muted-foreground"><span className="truncate">{column}</span><Input className="h-7 text-xs" value={values[column] ?? ""} onChange={(event) => setValues((current) => ({ ...current, [column]: event.target.value }))}/></label>)}</div>+ <div className="flex gap-1.5"><Button size="sm" className="h-7 text-[10px]" disabled={busy} onClick={saveRow}><Save className="mr-1 size-3"/>{rowId ? "Update row" : "Add row"}</Button>{rowId ? <Button size="sm" variant="ghost" className="h-7 text-[10px]" onClick={() => { setRowId(""); setValues({}); }}>Cancel edit</Button> : null}</div>+ </div>+ <ScrollArea className="min-h-0 flex-1"><div className="space-y-1.5 p-2">+ {table.rows.length === 0 ? <p className="p-3 text-xs text-muted-foreground">No rows yet.</p> : null}+ {table.rows.map((row) => <div key={row.id} className="rounded-lg border bg-card p-2">+ <button type="button" className="w-full text-left" onClick={() => editRow(row.id, row.values)}>+ <div className="grid gap-1">{table.columns.map((column) => <div key={column} className="grid grid-cols-[78px_minmax(0,1fr)] gap-2 text-[10px]"><span className="truncate text-muted-foreground">{column}</span><span className="truncate">{formatCell(row.values[column])}</span></div>)}</div>+ </button>+ <div className="mt-1.5 flex justify-end"><Button size="icon" variant="ghost" className="size-6 text-muted-foreground" disabled={busy} onClick={() => void act(async () => { await deleteDataTableRow(table.id, row.id); await load(table.id); })} aria-label="Delete data-table row"><Trash2 className="size-3"/></Button></div>+ </div>)}+ </div></ScrollArea>+ </> : <div className="grid min-h-0 flex-1 place-items-center p-6 text-center text-xs text-muted-foreground">Create a data table for persistent workflow rows.</div>}+ </div>;+}++function formatCell(value: unknown) {+ if (value == null) return "—";+ if (typeof value === "string") return value;+ try { return JSON.stringify(value); } catch { return String(value); }+}diff --git a/frontend/slices/workflows/components/workflow-details.tsx b/frontend/slices/workflows/components/workflow-details.tsxindex 656345e6..919b740d 100644--- a/frontend/slices/workflows/components/workflow-details.tsx+++ b/frontend/slices/workflows/components/workflow-details.tsx@@ -1,5 +1,6 @@"use client";+import { Activity, BookOpen, Braces, Clock3, Database, History, SlidersHorizontal } from "lucide-react";import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";import { ScrollArea } from "@/components/ui/scroll-area";import { WorkflowInspector } from "./workflow-inspector";@@ -8,10 +9,19 @@ import { WorkflowRunPanel } from "./workflow-run-panel";import { WorkflowVariablePanel } from "./workflow-variable-panel";import { WorkflowVersionPanel } from "./workflow-version-panel";import { WorkflowDirectoryPanel } from "./workflow-directory-panel";+import { WorkflowDataTablePanel } from "./workflow-data-table-panel";-export type WorkflowPanel = "inspector" | "run" | "history" | "versions" | "variables" | "directory";+export type WorkflowPanel = "inspector" | "run" | "history" | "versions" | "variables" | "data" | "directory";-const LABELS: Array<[WorkflowPanel, string]> = [["inspector", "Inspector"], ["run", "Run"], ["history", "History"], ["versions", "Versions"], ["variables", "Vars"], ["directory", "Directory"]];+const PANELS = [+ ["inspector", "Builder", SlidersHorizontal],+ ["run", "Current run", Activity],+ ["history", "Executions", History],+ ["versions", "Versions", Clock3],+ ["variables", "Variables", Braces],+ ["data", "Data", Database],+ ["directory", "Directory", BookOpen],+] as const satisfies ReadonlyArray<readonly [WorkflowPanel, string, typeof SlidersHorizontal]>;export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNode, onDeleteNode, onGraph, onRunSelect, onRestored }: {graph: WorkflowGraph;@@ -27,7 +37,25 @@ export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNoonRestored: (graph: WorkflowGraph) => void;}) {return <div className="flex h-full min-h-0 flex-col bg-card/20">- <div className="flex h-10 shrink-0 overflow-x-auto border-b">{LABELS.map(([value, label]) => <button key={value} type="button" className={`min-w-14 flex-1 px-1 text-[10px] ${panel === value ? "font-semibold text-foreground" : "text-muted-foreground hover:text-foreground"}`} onClick={() => onPanel(value)}>{label}</button>)}</div>- <div className="min-h-0 flex-1">{panel === "inspector" ? <ScrollArea className="h-full"><WorkflowInspector key={node?.id ?? `graph-${graph.id}`} graph={graph} graphs={graphs} node={node} onNode={onNode} onDeleteNode={onDeleteNode} onGraph={onGraph}/></ScrollArea> : null}{panel === "run" ? <WorkflowRunPanel run={run}/> : null}{panel === "history" ? <WorkflowRunHistory graph={graph} onSelect={onRunSelect}/> : null}{panel === "versions" ? <WorkflowVersionPanel graph={graph} onRestored={onRestored}/> : null}{panel === "variables" ? <WorkflowVariablePanel/> : null}{panel === "directory" ? <WorkflowDirectoryPanel/> : null}</div>+ <div className="shrink-0 overflow-x-auto border-b">+ <div className="flex min-w-max gap-1 p-1.5">+ {PANELS.map(([value, label, Icon]) => <button+ key={value}+ type="button"+ aria-pressed={panel === value}+ className={`flex h-8 items-center gap-1.5 rounded-md px-2.5 text-[11px] transition ${panel === value ? "bg-accent font-semibold text-foreground" : "text-muted-foreground hover:bg-accent/50 hover:text-foreground"}`}+ onClick={() => onPanel(value)}+ ><Icon className="size-3.5"/><span>{label}</span></button>)}+ </div>+ </div>+ <div className="min-h-0 flex-1">+ {panel === "inspector" ? <ScrollArea className="h-full"><WorkflowInspector key={node?.id ?? `graph-${graph.id}`} graph={graph} graphs={graphs} node={node} onNode={onNode} onDeleteNode={onDeleteNode} onGraph={onGraph}/></ScrollArea> : null}+ {panel === "run" ? <WorkflowRunPanel run={run}/> : null}+ {panel === "history" ? <WorkflowRunHistory graph={graph} onSelect={onRunSelect}/> : null}+ {panel === "versions" ? <WorkflowVersionPanel graph={graph} onRestored={onRestored}/> : null}+ {panel === "variables" ? <WorkflowVariablePanel/> : null}+ {panel === "data" ? <WorkflowDataTablePanel/> : null}+ {panel === "directory" ? <WorkflowDirectoryPanel/> : null}+ </div></div>;}diff --git a/frontend/slices/workflows/components/workflow-inspector.tsx b/frontend/slices/workflows/components/workflow-inspector.tsxindex 2f9e9581..bfa945bb 100644--- a/frontend/slices/workflows/components/workflow-inspector.tsx+++ b/frontend/slices/workflows/components/workflow-inspector.tsx@@ -29,7 +29,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraphconst 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}`);- const actionNode=["tool","project_function","project_mcp","integration","script","agent","subflow","loop","repeat"].includes(node.type);+ const actionNode=["tool","project_function","project_mcp","integration","script","agent","subflow","loop","repeat","data_table"].includes(node.type);return <div className="space-y-4 p-3 text-xs"><Field label="Name"><Input value={node.name} onChange={(e)=>patch({name:e.target.value})}/></Field><Field label="Type"><select className={selectClass} value={node.type} onChange={(e)=>patch({type:e.target.value as WorkflowGraphNodeType})}>{WORKFLOW_GRAPH_NODE_TYPES.map((type)=><option key={type} value={type}>{type}</option>)}</select></Field>@@ -46,6 +46,7 @@ export function WorkflowInspector({graph,graphs,node,onNode,onDeleteNode,onGraph{node.type==="repeat"&&<><Field label="Workflow to repeat"><select className={selectClass} value={String(node.config.workflowId??"")} onChange={(e)=>e.target.value?setConfig("workflowId",e.target.value):removeConfig("workflowId")}><option value="">Select saved workflow</option>{graphs.filter((item)=>item.id!==graph.id).map((item)=><option key={item.id} value={item.id}>{item.name}</option>)}</select></Field><JsonField label="Input JSON / bindings" value={node.config.input??{}} onChange={(value)=>setConfig("input",value)}/><Field label="Condition path"><Input value={String(node.config.path??"result.output")} placeholder="result.output.ok" onChange={(e)=>setConfig("path",e.target.value)}/></Field><label className="flex items-center justify-between"><span>Compare exact value</span><Switch checked={Object.hasOwn(node.config,"equals")} onCheckedChange={(checked)=>checked?setConfig("equals",true):removeConfig("equals")}/></label>{Object.hasOwn(node.config,"equals")&&<JsonField label="Expected JSON" value={node.config.equals} onChange={(value)=>setConfig("equals",value)}/>}<Field label="Max iterations"><Input type="number" min={1} max={50} value={number(node.config.maxIterations,5)} onChange={(e)=>setConfig("maxIterations",Number(e.target.value))}/></Field><Field label="Delay between iterations ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field><Field label="Max repeat duration ms"><Input type="number" min={1000} max={840000} value={number(node.config.maxDurationMs,600000)} onChange={(e)=>setConfig("maxDurationMs",Number(e.target.value))}/></Field><p className="text-[10px] text-muted-foreground">Each child run receives <code>input.repeat.iteration</code> and the previous iteration output. Route <code>done</code> when the condition matches or <code>exhausted</code> when limits are reached.</p></>}{node.type==="wait"&&<Field label="Delay ms"><Input type="number" min={0} max={600000} value={number(node.config.delayMs,1000)} onChange={(e)=>setConfig("delayMs",Number(e.target.value))}/></Field>}{node.type==="cache"&&<><Field label="Cache mode"><select className={selectClass} value={String(node.config.mode??"get_or_set")} onChange={(e)=>setConfig("mode",e.target.value)}>{["get_or_set","get","set","delete"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field><Field label="Cache key"><Input value={String(node.config.key??"")} onChange={(e)=>setConfig("key",e.target.value)}/></Field>{["get_or_set","set"].includes(String(node.config.mode??"get_or_set"))&&<><Field label="TTL seconds"><Input type="number" min={0} max={2592000} value={number(node.config.ttlSeconds,300)} onChange={(e)=>setConfig("ttlSeconds",Number(e.target.value))}/></Field><JsonField label="Value JSON / binding" value={node.config.value??{"$ref":"input"}} onChange={(value)=>setConfig("value",value)}/></>}</>}+ {node.type==="data_table"&&<><Field label="Data-table mode"><select className={selectClass} value={String(node.config.mode??"list")} onChange={(e)=>setConfig("mode",e.target.value)}>{["list","get","insert","update","delete"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{String(node.config.mode??"list")!=="list"&&<Field label="Table ID"><Input value={String(node.config.tableId??"")} placeholder="Persistent table id" onChange={(e)=>setConfig("tableId",e.target.value)}/></Field>}{["update","delete"].includes(String(node.config.mode))&&<Field label="Row ID"><Input value={String(node.config.rowId??"")} onChange={(e)=>setConfig("rowId",e.target.value)}/></Field>}{["insert","update"].includes(String(node.config.mode))&&<JsonField label="Row values JSON / bindings" value={node.config.values??{"$ref":"input"}} onChange={(value)=>setConfig("values",value)}/>}</>}{node.type==="memory"&&<><Field label="Memory scope"><select className={selectClass} value={String(node.config.scope??"agent")} onChange={(e)=>setConfig("scope",e.target.value)}><option value="agent">Agent memory</option><option value="project">Project memory</option></select></Field><Field label="Memory mode"><select className={selectClass} value={String(node.config.mode??"search")} onChange={(e)=>setConfig("mode",e.target.value)}>{(node.config.scope==="project"?["search","remember"]:["read","search","remember","forget"]).map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{String(node.config.mode??"search")==="search"&&<Field label="Query"><Input value={String(node.config.query??"")} onChange={(e)=>setConfig("query",e.target.value)}/></Field>}{node.config.scope!=="project"&&<Field label="Document"><select className={selectClass} value={String(node.config.document??"MEMORY.md")} onChange={(e)=>setConfig("document",e.target.value)}><option value="MEMORY.md">MEMORY.md</option><option value="USER.md">USER.md</option></select></Field>}{["remember","forget"].includes(String(node.config.mode))&&<Field label="Memory key"><Input value={String(node.config.key??"")} onChange={(e)=>setConfig("key",e.target.value)}/></Field>}{String(node.config.mode)==="remember"&&<Field label={node.config.scope==="project"?"Summary":"Value"}><Textarea value={String(node.config.value??node.config.summary??"")} onChange={(e)=>setConfig(node.config.scope==="project"?"summary":"value",e.target.value)}/></Field>}</>}{node.type==="session"&&<><Field label="Session mode"><select className={selectClass} value={String(node.config.mode??"current")} onChange={(e)=>setConfig("mode",e.target.value)}>{["current","list","resume","note"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field>{node.config.mode==="resume"&&<Field label="Session label"><Input placeholder="agent-context-session" value={String(node.config.sessionRef??"")} onChange={(e)=>setConfig("sessionRef",e.target.value)}/></Field>}{node.config.mode==="note"&&<Field label="Note"><Textarea value={String(node.config.note??"")} onChange={(e)=>setConfig("note",e.target.value)}/></Field>}</>}{node.type==="directory"&&<><Field label="Directory source"><select className={selectClass} value={String(node.config.source??"tools")} onChange={(e)=>setConfig("source",e.target.value)}>{["tools","workflows","sessions","projects","skills"].map((x)=><option key={x} value={x}>{x}</option>)}</select></Field><Field label="Query"><Input value={String(node.config.query??"")} onChange={(e)=>setConfig("query",e.target.value)}/></Field><Field label="Limit"><Input type="number" min={1} max={100} value={number(node.config.limit,30)} onChange={(e)=>setConfig("limit",Number(e.target.value))}/></Field></>}diff --git a/frontend/slices/workflows/components/workflow-library.tsx b/frontend/slices/workflows/components/workflow-library.tsxindex 2ede94b3..9a91a133 100644--- a/frontend/slices/workflows/components/workflow-library.tsx+++ b/frontend/slices/workflows/components/workflow-library.tsx@@ -1,16 +1,16 @@"use client";-import { FolderOpen } from "lucide-react";+import { CircleDot, FolderOpen, Search, Workflow } from "lucide-react";import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";+import type { WorkflowDefinition } from "../lib/portability";import { workflowMatchesQuery, workflowTagQuery } from "@/lib/workflow/search";import { Input } from "@/components/ui/input";import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";import { ScrollArea } from "@/components/ui/scroll-area";import { WorkflowCreateDialog } from "./workflow-create-dialog";-type Definition = Omit<WorkflowGraph, "version" | "id" | "revision" | "createdAt" | "updatedAt">;--export function WorkflowLibrary({ graphs, activeId, search, onSearch, onSelect, onBlank, onTemplate, onAI }: {+export function WorkflowLibrary({ graphs, activeId, search, onSearch, onSelect, onBlank, onTemplate, onAI, onImport }: {graphs: WorkflowGraph[];activeId?: string;search: string;@@ -18,20 +18,40 @@ export function WorkflowLibrary({ graphs, activeId, search, onSearch, onSelect,onSelect: (id: string) => void;onBlank: () => Promise<void>;onTemplate: (id: string) => Promise<void>;- onAI: (definition: Definition) => Promise<void>;+ onAI: (definition: WorkflowDefinition) => Promise<void>;+ onImport: (definition: WorkflowDefinition) => Promise<void>;}) {const filtered = graphs.filter((graph) => workflowMatchesQuery(graph, search));+ const activeCount = graphs.filter((graph) => graph.status === "active").length;return <div className="flex h-full min-h-0 flex-col bg-card/20">- <div className="space-y-2 border-b p-2"><Input className="h-8" aria-label="Search workflows" placeholder="deploy tag:qa status:active" value={search} onChange={(event) => onSearch(event.target.value)}/><WorkflowCreateDialog onBlank={onBlank} onTemplate={onTemplate} onAI={onAI}/></div>- <ScrollArea className="min-h-0 flex-1"><div className="space-y-1 p-2">- {filtered.length === 0 ? <div className="p-3 text-xs text-muted-foreground">No matching private workflows.</div> : null}- {filtered.map((graph) => <div key={graph.id} className={`rounded-lg border text-xs ${activeId === graph.id ? "bg-accent" : "bg-card"}`}>- <button type="button" onClick={() => onSelect(graph.id)} className="w-full rounded-lg p-2 text-left transition-colors hover:bg-accent/60" aria-pressed={activeId === graph.id}>- <div className="flex items-center gap-2"><FolderOpen className="size-3.5 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1 truncate font-medium">{graph.name}</div></div>- {graph.description ? <p className="mt-1 line-clamp-2 break-words text-muted-foreground">{graph.description}</p> : null}- <div className="mt-1 flex flex-wrap gap-1 break-all text-[10px] text-muted-foreground"><span>{graph.status} · {graph.nodes.length} nodes</span>{graph.metadata.folder ? <span>· {graph.metadata.folder}</span> : null}{graph.metadata.project ? <span>· {graph.metadata.project}</span> : null}</div>+ <div className="space-y-2.5 border-b p-3">+ <div className="flex items-center gap-2">+ <div className="min-w-0 flex-1"><div className="text-xs font-semibold">Automation library</div><div className="mt-0.5 text-[10px] text-muted-foreground">{graphs.length} workflows · {activeCount} active</div></div>+ <WorkflowCreateDialog onBlank={onBlank} onTemplate={onTemplate} onAI={onAI} onImport={onImport}/>+ </div>+ <div className="relative">+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground"/>+ <Input className="h-8 pl-8 text-xs" aria-label="Search workflows" placeholder="Search or use tag:, status:, project:…" value={search} onChange={(event) => onSearch(event.target.value)}/>+ </div>+ </div>+ <ScrollArea className="min-h-0 flex-1"><div className="space-y-2 p-2.5">+ {filtered.length === 0 ? <div className="grid min-h-32 place-items-center rounded-xl border border-dashed p-4 text-center text-xs text-muted-foreground">No workflows match this filter.</div> : null}+ {filtered.map((graph) => <div key={graph.id} className={`overflow-hidden rounded-xl border text-xs shadow-sm transition ${activeId === graph.id ? "border-foreground/20 bg-accent/75" : "bg-card hover:bg-accent/35"}`}>+ <button type="button" onClick={() => onSelect(graph.id)} className="w-full p-3 text-left" aria-pressed={activeId === graph.id}>+ <div className="flex items-start gap-2.5">+ <div className="grid size-8 shrink-0 place-items-center rounded-lg border bg-muted/40"><Workflow className="size-3.5 text-muted-foreground"/></div>+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-1.5"><div className="min-w-0 flex-1 truncate font-semibold">{graph.name}</div><Badge variant={graph.status === "active" ? "secondary" : "outline"} className="shrink-0 text-[9px]">{graph.status}</Badge></div>+ {graph.description ? <p className="mt-1 line-clamp-2 break-words text-[11px] leading-4 text-muted-foreground">{graph.description}</p> : null}+ </div>+ </div>+ <div className="mt-2.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[10px] text-muted-foreground">+ <span className="inline-flex items-center gap-1"><CircleDot className="size-3"/>{graph.nodes.length} nodes</span>+ {graph.metadata.folder ? <span className="inline-flex min-w-0 items-center gap-1"><FolderOpen className="size-3"/><span className="max-w-28 truncate">{graph.metadata.folder}</span></span> : null}+ {graph.metadata.project ? <span className="max-w-28 truncate">project: {graph.metadata.project}</span> : null}+ </div></button>- {graph.metadata.tags?.length ? <div className="flex flex-wrap gap-1 px-2 pb-2">{graph.metadata.tags.map((tag, index) => <Button key={`${tag}-${index}`} type="button" variant="secondary" size="sm" className="h-auto max-w-full whitespace-normal break-all px-2 py-1 text-[10px]" aria-label={`Filter workflows by tag ${tag}`} onClick={() => onSearch(workflowTagQuery(tag))}>{tag}</Button>)}</div> : null}+ {graph.metadata.tags?.length ? <div className="flex flex-wrap gap-1 border-t px-3 py-2">{graph.metadata.tags.map((tag, index) => <Button key={`${tag}-${index}`} type="button" variant="ghost" size="sm" className="h-6 max-w-full rounded-md px-1.5 text-[9px]" aria-label={`Filter workflows by tag ${tag}`} onClick={() => onSearch(workflowTagQuery(tag))}>#{tag}</Button>)}</div> : null}</div>)}</div></ScrollArea></div>;diff --git a/frontend/slices/workflows/components/workflow-run-history.tsx b/frontend/slices/workflows/components/workflow-run-history.tsxindex 2b621471..7e580561 100644--- a/frontend/slices/workflows/components/workflow-run-history.tsx+++ b/frontend/slices/workflows/components/workflow-run-history.tsx@@ -1,13 +1,30 @@"use client";import { useEffect, useState } from "react";+import { RotateCcw, Square, Trash2 } from "lucide-react";import type { WorkflowGraph, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { ScrollArea } from "@/components/ui/scroll-area";-import { listRuns, runStatus } from "../lib/api";+import { deleteRun, listRuns, retryRun, runStatus, stopRun } from "../lib/api";+export function WorkflowRunHistory({graph,onSelect}:{graph:WorkflowGraph;onSelect:(run:WorkflowGraphRun)=>void}){- const[rows,setRows]=useState<Awaited<ReturnType<typeof listRuns>>["runs"]>([]),[loading,setLoading]=useState(false);- const load=async()=>{setLoading(true);try{setRows((await listRuns(graph.id)).runs);}finally{setLoading(false);}};- useEffect(()=>{let cancelled=false;void Promise.resolve().then(()=>listRuns(graph.id)).then((value)=>{if(!cancelled)setRows(value.runs);}).finally(()=>{if(!cancelled)setLoading(false);});return()=>{cancelled=true;};},[graph.id]);- return <ScrollArea className="h-full"><div className="space-y-2 p-3"><div className="flex items-center justify-between"><span className="text-xs font-semibold">Execution history</span><Button size="sm" variant="ghost" disabled={loading} onClick={()=>void load()}>Refresh</Button></div>{rows.length===0&&<p className="text-xs text-muted-foreground">No executions yet.</p>}{rows.map((row)=><button key={row.id} type="button" className="w-full rounded-lg border p-2 text-left" onClick={()=>void runStatus(row.id).then(onSelect)}><div className="flex items-center justify-between gap-2"><span className="truncate text-xs font-medium">{new Date(row.startedAt).toLocaleString()}</span><Badge variant="outline">{row.state}</Badge></div><div className="mt-1 text-[10px] text-muted-foreground">{row.trigger?.type??"manual"}{row.failedNodeName?` · ${row.failedNodeName}`:""}</div></button>)}</div></ScrollArea>;+ const[rows,setRows]=useState<Awaited<ReturnType<typeof listRuns>>["runs"]>([]),[loading,setLoading]=useState(false),[busyId,setBusyId]=useState(""),[error,setError]=useState("");+ const load=async()=>{setLoading(true);setError("");try{setRows((await listRuns(graph.id)).runs);}catch(cause){setError(cause instanceof Error?cause.message:"Could not load executions");}finally{setLoading(false);}};+ useEffect(()=>{let cancelled=false;void Promise.resolve().then(()=>listRuns(graph.id)).then((value)=>{if(!cancelled)setRows(value.runs);}).catch((cause:unknown)=>{if(!cancelled)setError(cause instanceof Error?cause.message:"Could not load executions");}).finally(()=>{if(!cancelled)setLoading(false);});return()=>{cancelled=true;};},[graph.id]);+ const action=async(id:string,fn:()=>Promise<unknown>)=>{setBusyId(id);setError("");try{await fn();await load();}catch(cause){setError(cause instanceof Error?cause.message:"Execution action failed");}finally{setBusyId("");}};+ return <ScrollArea className="h-full"><div className="space-y-2 p-3">+ <div className="flex items-center justify-between"><div><div className="text-xs font-semibold">Executions</div><div className="text-[10px] text-muted-foreground">Inspect, stop, retry, or remove persisted run receipts.</div></div><Button size="sm" variant="ghost" disabled={loading} onClick={()=>void load()}>Refresh</Button></div>+ {error?<p role="alert" className="rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{error}</p>:null}+ {rows.length===0&&!loading?<p className="text-xs text-muted-foreground">No executions yet.</p>:null}+ {rows.map((row)=><div key={row.id} className="rounded-xl border bg-card p-2.5">+ <button type="button" className="w-full text-left" onClick={()=>void runStatus(row.id).then(onSelect)}>+ <div className="flex items-center justify-between gap-2"><span className="truncate text-xs font-medium">{new Date(row.startedAt).toLocaleString()}</span><Badge variant="outline">{row.state}</Badge></div>+ <div className="mt-1 text-[10px] text-muted-foreground">{row.trigger?.type??"manual"}{row.failedNodeName?` · ${row.failedNodeName}`:""}</div>+ </button>+ <div className="mt-2 flex flex-wrap gap-1 border-t pt-2">+ {row.state==="running"?<Button size="sm" variant="outline" className="h-7 px-2 text-[10px]" disabled={busyId===row.id} onClick={()=>void action(row.id,()=>stopRun(row.id))}><Square className="mr-1 size-3"/>Stop</Button>:<Button size="sm" variant="outline" className="h-7 px-2 text-[10px]" disabled={busyId===row.id} onClick={()=>void action(row.id,async()=>{const next=await retryRun(row.id);onSelect(next);return next;})}><RotateCcw className="mr-1 size-3"/>Retry</Button>}+ {row.state!=="running"?<Button size="sm" variant="ghost" className="h-7 px-2 text-[10px] text-muted-foreground" disabled={busyId===row.id} onClick={()=>void action(row.id,()=>deleteRun(row.id))}><Trash2 className="mr-1 size-3"/>Delete receipt</Button>:null}+ </div>+ </div>)}+ </div></ScrollArea>;}diff --git a/frontend/slices/workflows/index.ts b/frontend/slices/workflows/index.tsindex 380c1e4c..d9dc05bb 100644--- a/frontend/slices/workflows/index.ts+++ b/frontend/slices/workflows/index.ts@@ -7,6 +7,6 @@ export const workflowsApp: AppDescriptor = {icon: Workflow,gradient: "var(--primary)",prefetch: "never",- load: () => import("./workspace"),+ load: () => import("./app"),defaultSize: { w: 1180, h: 760 },};diff --git a/frontend/slices/workflows/lib/api.ts b/frontend/slices/workflows/lib/api.tsindex 09c95447..b66ce785 100644--- a/frontend/slices/workflows/lib/api.ts+++ b/frontend/slices/workflows/lib/api.ts@@ -12,6 +12,9 @@ export async function deleteGraph(graph:WorkflowGraph){await post({action:"deletexport async function cloneGraph(id:string){const next=(await post<{graph:WorkflowGraph}>({action:"clone",graph_id:id})).graph;invalidateWorkflowResources("graphs");seedWorkflowResource(`graph:${next.id}`,next,8000);return next;}export async function runGraph(id:string,input:Record<string,unknown>={}){return post<WorkflowGraphRun&{pollAfterMs?:number}>({action:"run",graph_id:id,input,idempotency_key:`ui-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});}export async function runStatus(id:string){return json<WorkflowGraphRun&{pollAfterMs?:number}>(`/api/v1/workflows?run_id=${encodeURIComponent(id)}&wait_ms=1500`);}+export async function stopRun(id:string){return post<WorkflowGraphRun&{stopRequested?:boolean}>({action:"run_stop",run_id:id});}+export async function retryRun(id:string){return post<WorkflowGraphRun&{pollAfterMs?:number}>({action:"run_retry",run_id:id,idempotency_key:`ui-retry-${Date.now()}-${Math.random().toString(36).slice(2,8)}`});}+export async function deleteRun(id:string){return post<{id:string;deleted:boolean}>({action:"run_delete",run_id:id});}export async function listRuns(graphId?:string,state?:WorkflowGraphStatus|string,offset=0){const q=new URLSearchParams({runs:"1",limit:"30",offset:String(offset)});if(graphId)q.set("graph_id",graphId);if(state)q.set("state",state);return json<{total:number;runs:Array<Pick<WorkflowGraphRun,"id"|"graphId"|"graphRevision"|"graphName"|"state"|"startedAt"|"updatedAt"|"finishedAt"|"failedNodeId"|"failedNodeName"|"trigger">>;nextOffset?:number}>(`/api/v1/workflows?${q}`);}export async function listVersions(graphId:string){return(await json<{versions:Array<{revision:string;savedAt:string;reason:string;name:string;nodeCount:number}>}>(`/api/v1/workflows?versions=${encodeURIComponent(graphId)}`)).versions;}export async function restoreVersion(graph:WorkflowGraph,revision:string){return(await post<{graph:WorkflowGraph}>({action:"restore_version",graph_id:graph.id,expected_revision:graph.revision,revision})).graph;}@@ -21,6 +24,15 @@ export async function createFromTemplate(id:string){return(await post<{graph:Worexport async function listVariables(){return(await json<{variables:Array<{key:string;secret:boolean;updatedAt:string;value?:unknown}>}>("/api/v1/workflows?variables=1")).variables;}export async function setVariable(key:string,value:unknown,secret=false){return post({action:"variable_set",key,value,secret});}export async function deleteVariable(key:string){return post({action:"variable_delete",key});}+export type WorkflowDataTableSummary={id:string;name:string;columns:string[];rowCount:number;createdAt:string;updatedAt:string};+export type WorkflowDataTableRow={id:string;values:Record<string,unknown>;createdAt:string;updatedAt:string};+export type WorkflowDataTable={id:string;name:string;columns:string[];rows:WorkflowDataTableRow[];createdAt:string;updatedAt:string};+export async function listDataTables(){return(await json<{tables:WorkflowDataTableSummary[]}>("/api/v1/workflows?data_tables=1")).tables;}+export async function getDataTable(id:string){return(await json<{table:WorkflowDataTable}>(`/api/v1/workflows?data_table=${encodeURIComponent(id)}`)).table;}+export async function createDataTable(name:string,columns:string[]){return(await post<{table:WorkflowDataTable}>({action:"data_table_create",name,columns})).table;}+export async function deleteDataTable(id:string){return post<{id:string;deleted:boolean}>({action:"data_table_delete",table_id:id});}+export async function upsertDataTableRow(tableId:string,values:Record<string,unknown>,rowId?:string){return(await post<{row:WorkflowDataTableRow}>({action:"data_table_row_upsert",table_id:tableId,...(rowId?{row_id:rowId}:{}),values})).row;}+export async function deleteDataTableRow(tableId:string,rowId:string){return post<{tableId:string;rowId:string;deleted:boolean}>({action:"data_table_row_delete",table_id:tableId,row_id:rowId});}export async function aiSuggest(prompt:string){return(await post<{definition:Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">}>({action:"ai_suggest",prompt})).definition;}export async function resolveNode(graphId:string,nodeId:string){return json<{project:string;name:string;path:string;relativePath:string}>(`/api/v1/workflows?graph_id=${encodeURIComponent(graphId)}&node_id=${encodeURIComponent(nodeId)}&resolve=target`);}diff --git a/frontend/slices/workflows/lib/portability.test.ts b/frontend/slices/workflows/lib/portability.test.tsnew file mode 100644index 00000000..87b9f9e4--- /dev/null+++ b/frontend/slices/workflows/lib/portability.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";+import { buildWorkflowPackage, parseWorkflowPackage, workflowPackageFilename } from "./portability";++const graph: WorkflowGraph = {+ version: 2,+ id: "graph-id",+ revision: "revision",+ createdAt: "2026-09-22T00:00:00.000Z",+ updatedAt: "2026-09-22T00:00:00.000Z",+ name: "Deploy & Verify",+ description: "portable",+ status: "draft",+ inputs: {},+ metadata: { provenance: "user", tags: ["qa"] },+ nodes: [{ id: "manual", name: "Manual", type: "manual", position: { x: 0, y: 0 }, config: {} }],+ edges: [],+};++describe("workflow portability", () => {+ it("exports a runtime-id-free package and imports the definition", () => {+ const pkg = buildWorkflowPackage(graph);+ expect(pkg.graph).not.toHaveProperty("id");+ expect(pkg.graph).not.toHaveProperty("revision");+ expect(parseWorkflowPackage(JSON.stringify(pkg))).toMatchObject({ name: graph.name, nodes: graph.nodes, metadata: graph.metadata });+ });++ it("accepts a full graph export but drops runtime identity fields", () => {+ const imported = parseWorkflowPackage(JSON.stringify(graph));+ expect(imported.name).toBe(graph.name);+ expect(imported).not.toHaveProperty("id");+ expect(imported).not.toHaveProperty("createdAt");+ });++ it("creates a bounded portable filename and rejects invalid payloads", () => {+ expect(workflowPackageFilename(graph.name)).toBe("deploy-verify.mso-workflow.json");+ expect(() => parseWorkflowPackage("{}")).toThrow("required graph fields");+ expect(() => parseWorkflowPackage("{")).toThrow("valid JSON");+ });+});diff --git a/frontend/slices/workflows/lib/portability.ts b/frontend/slices/workflows/lib/portability.tsnew file mode 100644index 00000000..4865d0fa--- /dev/null+++ b/frontend/slices/workflows/lib/portability.ts@@ -0,0 +1,36 @@+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";++export type WorkflowDefinition = Omit<WorkflowGraph, "version" | "id" | "revision" | "createdAt" | "updatedAt">;+export type WorkflowPackage = { format: "mso-workflow"; version: 1; exportedAt: string; graph: WorkflowDefinition };++function object(value: unknown): value is Record<string, unknown> {+ return Boolean(value && typeof value === "object" && !Array.isArray(value));+}++export function workflowDefinition(graph: WorkflowGraph): WorkflowDefinition {+ const { version: _version, id: _id, revision: _revision, createdAt: _createdAt, updatedAt: _updatedAt, ...definition } = graph;+ return structuredClone(definition);+}++export function buildWorkflowPackage(graph: WorkflowGraph): WorkflowPackage {+ return { format: "mso-workflow", version: 1, exportedAt: new Date().toISOString(), graph: workflowDefinition(graph) };+}++export function workflowPackageFilename(name: string): string {+ const slug = name.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 80) || "workflow";+ return `${slug}.mso-workflow.json`;+}++export function parseWorkflowPackage(text: string): WorkflowDefinition {+ if (text.length > 2 * 1024 * 1024) throw new Error("Workflow package exceeds 2 MiB");+ let raw: unknown;+ try { raw = JSON.parse(text); } catch { throw new Error("Workflow package is not valid JSON"); }+ if (!object(raw)) throw new Error("Workflow package must be an object");+ const candidate = raw.format === "mso-workflow" && raw.version === 1 ? raw.graph : raw;+ if (!object(candidate)) throw new Error("Workflow package does not contain a graph");+ const { version: _version, id: _id, revision: _revision, createdAt: _createdAt, updatedAt: _updatedAt, ...definition } = candidate;+ if (typeof definition.name !== "string" || !Array.isArray(definition.nodes) || !Array.isArray(definition.edges) || !object(definition.metadata)) {+ throw new Error("Workflow package is missing required graph fields");+ }+ return definition as WorkflowDefinition;+}diff --git a/frontend/slices/workflows/workspace.tsx b/frontend/slices/workflows/workspace.tsxdeleted file mode 100644index b1810b44..00000000--- a/frontend/slices/workflows/workspace.tsx+++ /dev/null@@ -1,51 +0,0 @@-"use client";--import { useEffect, useId, useState } from "react";-import type { AppProps } from "@/features/appshell";-import type { WorkflowEmbed } from "@/lib/contracts/surface-app";-import { Button } from "@/components/ui/button";-import { cn } from "@/lib/utils";-import NativeWorkflowsApp from "./app";-import { WorkflowEmbedPanel } from "./components/workflow-embed-panel";--export default function WorkflowsWorkspace(props: AppProps) {- const [apps, setApps] = useState<WorkflowEmbed[]>([]);- const [selected, setSelected] = useState("__native");- const [visited, setVisited] = useState<string[]>([]);- const prefix = useId();- useEffect(() => {- const controller = new AbortController();- const load = async () => {- try {- const response = await fetch("/api/v1/workflow-embeds", { cache: "no-store", signal: controller.signal });- if (!response.ok) { if ([401, 403].includes(response.status)) setApps([]); return; }- const data = await response.json() as { apps: WorkflowEmbed[] };- setApps(data.apps);- } catch { /* Keep mounted editors on transient network failures; authorization failures clear them above. */ }- };- void load(); window.addEventListener("focus", load);- return () => { controller.abort(); window.removeEventListener("focus", load); };- }, []);- useEffect(() => {- if (!props.payload || typeof props.payload !== "object" || !("view" in props.payload) || props.payload.view !== "sessions") return;- const frame = requestAnimationFrame(() => setSelected("__native"));- return () => cancelAnimationFrame(frame);- }, [props.payload]);- const active = apps.some((app) => app.id === selected) ? selected : "__native";- const choices = [{ id: "__native", title: "MSO" }, ...apps];- const select = (id: string) => { setSelected(id); setVisited((ids) => ids.includes(id) ? ids : [...ids, id]); };- return <div className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden" data-slot="workflows-workspace">- {apps.length ? <div role="tablist" aria-label="Workflow providers" className="flex shrink-0 gap-1 overflow-x-auto border-b px-2 py-1">- {choices.map((choice, index) => <Button key={choice.id} id={`${prefix}-tab-${choice.id}`} role="tab" aria-selected={active === choice.id} aria-controls={`${prefix}-panel-${choice.id}`} tabIndex={active === choice.id ? 0 : -1} variant={active === choice.id ? "secondary" : "ghost"} size="sm" className="shrink-0" onClick={() => select(choice.id)} onKeyDown={(event) => {- const offset = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;- const next = event.key === "Home" ? 0 : event.key === "End" ? choices.length - 1 : offset ? (index + offset + choices.length) % choices.length : -1;- if (next < 0) return;- event.preventDefault(); select(choices[next].id); document.getElementById(`${prefix}-tab-${choices[next].id}`)?.focus();- }}>{choice.title}</Button>)}- </div> : null}- <section id={`${prefix}-panel-__native`} role={apps.length ? "tabpanel" : undefined} aria-labelledby={apps.length ? `${prefix}-tab-__native` : undefined} hidden={active !== "__native"} className={cn("min-h-0 min-w-0 flex-1 overflow-hidden", active !== "__native" && "hidden")}>- <NativeWorkflowsApp {...props}/>- </section>- {apps.map((app) => <section key={app.id + app.origin + String(app.blocked)} id={`${prefix}-panel-${app.id}`} role="tabpanel" aria-labelledby={`${prefix}-tab-${app.id}`} hidden={active !== app.id} className={cn("min-h-0 min-w-0 flex-1 overflow-hidden", active !== app.id && "hidden")}>{visited.includes(app.id) ? <WorkflowEmbedPanel app={app}/> : null}</section>)}- </div>;-}diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsindex 9b6587e3..d70ba0f7 100644--- a/lib/config/env-example.test.ts+++ b/lib/config/env-example.test.ts@@ -44,9 +44,6 @@ const NOT_A_KNOB: Record<string, string> = {WATCHDOG_USEC: "systemd's",// Test + tooling only, never part of a deployment.E2E_BASE_URL: "test harness",- E2E_EVIDENCE_DIR: "workflow embed browser harness only: screenshot/report output directory, never runtime configuration",- E2E_WORKFLOW_EMBED_PARENT_ORIGIN: "workflow embed browser harness only: explicitly approved synthetic parent origin for live policy checks",- E2E_WORKFLOW_EMBED_ORIGIN: "workflow embed browser harness only: explicit signed-out live provider smoke target, never production configuration",MSO_SCREENSHOT_DIR: "injected per-session artifact staging path for browser tooling; never persistent app configuration",E2E_DEMO: "desktop browser harness only: preview has no authentication; never production configuration",E2E_CAPTURE_ONLY: "desktop browser harness only: capture baseline before native behavior assertions",diff --git a/lib/contracts/surface-app.ts b/lib/contracts/surface-app.tsindex b37a3eed..13ec45a9 100644--- a/lib/contracts/surface-app.ts+++ b/lib/contracts/surface-app.ts@@ -1,6 +1,7 @@export type SurfaceRenderer = "iframe" | "remote";export type SurfacePresentation = "inline" | "fullscreen" | "pip";export type SurfaceEnvironment = "development" | "preview" | "production" | "other";+export type SurfacePlacement = "workflows" | "n8n" | "mcp-page";export type SurfaceApp = {id: string;@@ -15,10 +16,9 @@ export type SurfaceApp = {externalAuthPath?: string;reason?: string;project?: string;- placements?: Array<"workflows" | "mcp-page">;+ placements?: SurfacePlacement[];};-export type WorkflowEmbed = {id: string; title: string; description: string; origin: string; url?: string; blocked?: boolean;loginUrl?: string; renderer: SurfaceRenderer; sandbox: string; reason?: string;diff --git a/lib/contracts/workflow-graph.ts b/lib/contracts/workflow-graph.tsindex f9934442..9cd875ff 100644--- a/lib/contracts/workflow-graph.ts+++ b/lib/contracts/workflow-graph.ts@@ -1,7 +1,7 @@import type { GraphCustomNode } from "./graph-custom-nodes";export const WORKFLOW_GRAPH_NODE_TYPES = ["manual", "schedule", "webhook", "tool", "project_function", "project_mcp", "integration", "script", "agent", "subflow",- "condition", "switch", "merge", "batch", "loop", "repeat", "wait", "cache", "memory", "session", "directory", "project", "folder", "skill", "knowledge", "output",+ "condition", "switch", "merge", "batch", "loop", "repeat", "wait", "cache", "data_table", "memory", "session", "directory", "project", "folder", "skill", "knowledge", "output",] as const;export type WorkflowGraphNodeType = (typeof WORKFLOW_GRAPH_NODE_TYPES)[number];export type WorkflowGraphStatus = "draft" | "active" | "archived";@@ -101,4 +101,6 @@ export type WorkflowGraphRun = {edges?: WorkflowGraphRunEdge[];trigger?: { type: "manual" | "schedule" | "webhook" | "system"; nodeId?: string; receivedAt: string };ancestry?: string[];+ /** Owner-private runtime input retained only so an execution can be retried safely. Public receipts strip this field. */+ runtimeInput?: Record<string, unknown>;};diff --git a/lib/host/workflow-embed-cookie.test.ts b/lib/host/workflow-embed-cookie.test.tsindex 94466957..43158935 100644--- a/lib/host/workflow-embed-cookie.test.ts+++ b/lib/host/workflow-embed-cookie.test.ts@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import { workflowEmbeds, listWorkflowEmbeds, workflowEmbedSettings } from "./workflow-embeds-api";const cockpit = "https://mso.example.com";-const app = { id: "editor", title: "Editor", description: "Reviewed external editor", origin: "https://n8n.mso.example.com", startPath: "/editor", externalAuthPath: "/signin", renderer: "iframe" as const, presentation: "inline" as const, environment: "production" as const, placements: ["workflows", "mcp-page"] as Array<"workflows" | "mcp-page"> };+const app = { id: "editor", title: "Editor", description: "Reviewed external editor", origin: "https://n8n.mso.example.com", startPath: "/editor", externalAuthPath: "/signin", renderer: "iframe" as const, presentation: "inline" as const, environment: "production" as const, placements: ["n8n", "mcp-page"] as Array<"n8n" | "mcp-page"> };afterEach(() => vi.unstubAllEnvs());describe("external editor session-cookie isolation", () => {it.each(["mso.example.com", ".MSO.EXAMPLE.COM", " example.com "])("blocks frames AND navigation under cookie domain %s", domain => {diff --git a/lib/host/workflow-embeds-api.test.ts b/lib/host/workflow-embeds-api.test.tsindex 88eb1ad3..4ac07e41 100644--- a/lib/host/workflow-embeds-api.test.ts+++ b/lib/host/workflow-embeds-api.test.ts@@ -7,6 +7,7 @@ describe("reviewed Workflows embed registry", () => {it("is disabled by default and requires explicit placement", () => {expect(workflowEmbeds([app], [])).toEqual([]);expect(workflowEmbeds([{ ...app, placements: ["workflows"] }], [])).toHaveLength(1);+ expect(workflowEmbeds([{ ...app, id: "n8n", title: "n8n", placements: ["n8n"] }], [])).toHaveLength(1);});it("shares the Page registry and only returns approved non-secret presentation metadata", async () => {vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, placements: ["workflows"], externalAuthPath: "/signin", accessToken: "must-not-leak" }]));diff --git a/lib/host/workflow-embeds-api.ts b/lib/host/workflow-embeds-api.tsindex 6e3e07e8..daab41b3 100644--- a/lib/host/workflow-embeds-api.ts+++ b/lib/host/workflow-embeds-api.ts@@ -5,7 +5,7 @@ import { surfaceRegistrySnapshot } from "@/lib/surfaces/manage";/** Presentation metadata only. An embed never inherits the cockpit's credentials. */export function workflowEmbeds(apps: SurfaceApp[], cockpitOrigins: string[]): WorkflowEmbed[] {- return apps.filter((app) => app.placements?.includes("workflows")).map((app) => {+ return apps.filter((app) => app.placements?.includes("workflows") || app.placements?.includes("n8n")).map((app) => {if (externalSurfaceSharesSession(app.origin, cockpitOrigins)) return {id: app.id, title: app.title, description: app.description, origin: app.origin,renderer: "remote" as const, sandbox: app.sandbox ?? "allow-scripts allow-same-origin allow-forms", blocked: true,diff --git a/lib/mcp/tools-flows.ts b/lib/mcp/tools-flows.tsindex 51ec37bb..00a0d102 100644--- a/lib/mcp/tools-flows.ts+++ b/lib/mcp/tools-flows.ts@@ -4,8 +4,8 @@ import { BUILTIN_FLOWS } from "@/lib/workflow/automation-builtins";import { manageProjectFlow } from "@/lib/host/project-flow-manifest";import { type McpTool, S, str } from "./tool-kit";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";+import { requestWorkflowGraphStop, startWorkflowGraph, workflowGraphRunStatus } from "@/lib/workflow/graph-engine";+import { deleteWorkflowGraphRun, listWorkflowGraphRuns, readWorkflowGraphRun } from "@/lib/workflow/graph-run-store";import { listWorkflowGraphVersions, readWorkflowGraphVersion } from "@/lib/workflow/graph-version-store";import { workflowNodeCatalog } from "@/lib/workflow/node-catalog";import { workflowTemplate, workflowTemplates } from "@/lib/workflow/templates";@@ -13,6 +13,7 @@ import { deleteWorkflowVariable, listWorkflowVariables, setWorkflowVariable } frimport { workflowMatchesQuery } from "@/lib/workflow/search";import { resolveProjectHint } from "@/lib/host/projects-api";import { listAutomationScripts } from "@/lib/orchestration/repo-memory-artifacts";+import { createWorkflowDataTable, deleteWorkflowDataTable, deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "@/lib/workflow/data-table-store";const project = { type: "string", maxLength: 4096 };const flow = { type: "string", maxLength: 64 };@@ -61,7 +62,7 @@ export const FLOW_TOOLS: McpTool[] = [return manageProjectFlow(catalog.project.path, { action: a.action, id, flow: a.definition, revision: str(a, "revision") });} },{ name: "workflow_graph", title: "Workflow Graph", scope: "exec", limit: { key: "workflow.graph", max: 20, windowMs: 60_000 },- description: "Private workflow graph CRUD/run plus history, versions, templates, catalog and variable references. Definitions reject embedded secrets. metadata.customNodes supports named collapsible groups [{id,name,nodeIds,collapsed}]; original nodes/edges and execution stay unchanged. Update with the current revision.",+ description: "Private workflow graph CRUD/run plus execution controls, history, versions, templates, catalog, variables and data tables. Definitions reject embedded secrets. metadata.customNodes supports named collapsible groups [{id,name,nodeIds,collapsed}]; original nodes/edges and execution stay unchanged. Update with the current revision.",chatgptDescription: "CRUD/run workflows; read node logs.",annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, audit: { action: "exec.run", targetArg: "id" },inputSchema: S({ action: { type: "string", minLength: 1, maxLength: 32 }, id: { type: "string", maxLength: 96 }, data: { type: "object", additionalProperties: true }, wait_ms: { type: "integer", minimum: 0, maximum: 25_000 } }, ["action"]),@@ -71,12 +72,21 @@ export const FLOW_TOOLS: McpTool[] = [if (action === "list" || action === "search") { const graphs = await listWorkflowGraphs(principal), query = typeof data.query === "string" ? data.query : "", filters = { tag: typeof data.tag === "string" ? data.tag : undefined, status: typeof data.status === "string" ? data.status : undefined, project: typeof data.project === "string" ? data.project : undefined, folder: typeof data.folder === "string" ? data.folder : undefined, node: typeof data.node === "string" ? data.node : undefined }; return { graphs: graphs.filter((graph) => workflowMatchesQuery(graph, query, filters)).map(graph => ({ id: graph.id, name: graph.name, description: graph.description, status: graph.status, revision: graph.revision, nodeCount: graph.nodes.length, updatedAt: graph.updatedAt, provenance: graph.metadata.provenance, project: graph.metadata.project, folder: graph.metadata.folder, tags: graph.metadata.tags ?? [] })) }; }if (action === "status") return workflowGraphRunStatus(principal, str(a, "id"), Number(a.wait_ms) || 0);if (action === "runs") return listWorkflowGraphRuns(workflowGraphOwner(principal), { graphId: typeof data.graph_id === "string" ? data.graph_id : undefined, limit: Number(data.limit) || 30, offset: Number(data.offset) || 0 });+ if (action === "stop") return requestWorkflowGraphStop(principal, str(a, "id"));+ if (action === "run_delete") return deleteWorkflowGraphRun(workflowGraphOwner(principal), str(a, "id"));+ if (action === "retry") { const prior = await readWorkflowGraphRun(workflowGraphOwner(principal), str(a, "id")); if (!prior) throw new Error("workflow execution not found"); if (prior.state === "running") throw new Error("running execution must be stopped before retry"); if (!prior.runtimeInput) throw new Error("execution predates retry input retention; run the workflow again instead"); const graph = await getWorkflowGraph(principal, prior.graphId); if (!graph) throw new Error("workflow graph not found"); if (graph.revision !== prior.graphRevision) throw new Error("workflow changed since this execution; run current graph instead"); const key = typeof data.key === "string" ? data.key : ""; if (!key) throw new Error("data.key is required for retry idempotency"); const { TOOLS_BY_NAME } = await import("./tools"); return startWorkflowGraph(graph, prior.runtimeInput, key, context, name => TOOLS_BY_NAME.get(name), principal); }if (action === "scripts") { const hint = typeof data.project === "string" ? data.project : ""; 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 = typeof data.query === "string" ? data.query.toLowerCase().trim() : ""; const 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 { project: project.id, scripts }; }if (action === "catalog") return { nodes: workflowNodeCatalog(typeof data.query === "string" ? data.query : "") };if (action === "templates") return { templates: workflowTemplates() };if (action === "variables") return { variables: await listWorkflowVariables(principal) };if (action === "variable_set") return setWorkflowVariable(principal, String(data.key ?? ""), data.value, data.secret === true);if (action === "variable_delete") return deleteWorkflowVariable(principal, String(data.key ?? ""));+ if (action === "data_tables") return { tables: await listWorkflowDataTables(principal) };+ if (action === "data_table_get") return { table: await getWorkflowDataTable(principal, data.table_id) };+ if (action === "data_table_create") return { table: await createWorkflowDataTable(principal, data.name, data.columns) };+ if (action === "data_table_delete") return deleteWorkflowDataTable(principal, data.table_id);+ if (action === "data_table_row_upsert") return { row: await upsertWorkflowDataTableRow(principal, data.table_id, data.row_id, data.values) };+ if (action === "data_table_row_delete") return deleteWorkflowDataTableRow(principal, data.table_id, data.row_id);if (action === "create_from_template") { const row = workflowTemplate(String(data.template_id ?? "")); if (!row) throw new Error("workflow template not found"); return { graph: await createWorkflowGraph(principal, row.definition, "template", { remember: true }) }; }if (action === "create") return { graph: await createWorkflowGraph(principal, data.definition ?? data, "create", { remember: true }) };const id = str(a, "id");diff --git a/lib/surfaces/config.ts b/lib/surfaces/config.tsindex 5d87f12c..fe8025e1 100644--- a/lib/surfaces/config.ts+++ b/lib/surfaces/config.ts@@ -2,7 +2,7 @@ import { promises as fs } from "node:fs";import { homedir } from "node:os";import { resolve } from "node:path";-import type { SurfaceApp, SurfacePresentation, SurfaceEnvironment } from "@/lib/contracts/surface-app";+import type { SurfaceApp, SurfacePlacement, SurfacePresentation, SurfaceEnvironment } from "@/lib/contracts/surface-app";export type { SurfaceApp, SurfaceRenderer, SurfacePresentation, SurfaceEnvironment } from "@/lib/contracts/surface-app";const MAX_APPS = 16;@@ -71,8 +71,8 @@ function parseApp(entry: unknown, seen: Set<string>): SurfaceApp | null {if (row.externalAuthPath !== undefined && !externalAuthPath) return null;const project = boundedText(row.project, true);if (row.project !== undefined && !project) return null;- if (row.placements !== undefined && (!Array.isArray(row.placements) || row.placements.some((value) => value !== "workflows" && value !== "mcp-page"))) return null;- const placements = row.placements === undefined ? undefined : [...new Set(row.placements)] as Array<"workflows" | "mcp-page">;+ if (row.placements !== undefined && (!Array.isArray(row.placements) || row.placements.some((value) => value !== "workflows" && value !== "n8n" && value !== "mcp-page"))) return null;+ const placements = row.placements === undefined ? undefined : [...new Set(row.placements)] as SurfacePlacement[];seen.add(id);const reason = boundedText(row.reason);return {diff --git a/lib/surfaces/manage.test.ts b/lib/surfaces/manage.test.tsindex 59e1799b..13154d69 100644--- a/lib/surfaces/manage.test.ts+++ b/lib/surfaces/manage.test.ts@@ -55,6 +55,11 @@ describe("owner-reviewed workflow surface configuration", () => {expect((await surfaceRegistrySnapshot()).apps[0].placements).toEqual(["workflows"]);await expect(save({ ...app, placements: ["workflows", "mcp-page"] })).rejects.toThrow("invalid_workflow_placement");});+ it("persists n8n as a dedicated reviewed placement without adding Page approval", async () => {+ await save({ ...app, id: "n8n", title: "n8n", placements: ["n8n"] });+ const saved = (await surfaceRegistrySnapshot()).apps[0];+ expect(saved).toMatchObject({ id: "n8n", title: "n8n", placements: ["n8n"] });+ });it("rejects stale updates and concurrent lost writes", async () => {const revision = (await surfaceRegistrySnapshot()).revision;await save();diff --git a/lib/surfaces/manage.ts b/lib/surfaces/manage.tsindex 0d2ece9a..5caf7949 100644--- a/lib/surfaces/manage.ts+++ b/lib/surfaces/manage.ts@@ -33,8 +33,10 @@ export async function saveWorkflowSurface(input: Record<string, unknown>) {const app = input.app;if (!app || typeof app !== "object" || Array.isArray(app) || Object.keys(app).some((key) => !APP_FIELDS.has(key))) throw new SurfaceConfigError("invalid_surface_metadata");const row = app as Record<string, unknown>;- if (row.placements !== undefined && JSON.stringify(row.placements) !== JSON.stringify(["workflows"])) throw new SurfaceConfigError("invalid_workflow_placement");- const normalized = await configuredSurfaceApps(JSON.stringify([{ ...row, placements: ["workflows"] }]));+ const placement = Array.isArray(row.placements) && row.placements.length === 1 && (row.placements[0] === "workflows" || row.placements[0] === "n8n") ? row.placements[0] : undefined;+ if (row.placements !== undefined && !placement) throw new SurfaceConfigError("invalid_workflow_placement");+ const selectedPlacement = placement ?? "workflows";+ const normalized = await configuredSurfaceApps(JSON.stringify([{ ...row, placements: [selectedPlacement] }]));if (normalized.length !== 1) throw new SurfaceConfigError("invalid_surface_metadata");const selected = normalized[0];return withSecurityStoreLock(surfaceRegistryPath(), async () => {@@ -58,7 +60,7 @@ export async function saveWorkflowSurface(input: Record<string, unknown>) {throw new SurfaceConfigError("workflow_login_path_must_not_contain_query");}if (sharesPage) {- replacement.placements = ["workflows", "mcp-page"];+ replacement.placements = [selectedPlacement, "mcp-page"];if (existingNormalized?.externalAuthPath !== undefined) replacement.externalAuthPath = existingNormalized.externalAuthPath;else delete replacement.externalAuthPath;}diff --git a/lib/workflow/data-table-store.test.ts b/lib/workflow/data-table-store.test.tsnew file mode 100644index 00000000..e2a79a32--- /dev/null+++ b/lib/workflow/data-table-store.test.ts@@ -0,0 +1,30 @@+import { afterAll, describe, expect, it } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";++const dir = await mkdtemp(path.join(os.tmpdir(), "mso-workflow-data-table-"));+process.env.OS_AGENT_SESSIONS_DIR = dir;+const api = await import("./data-table-store");+afterAll(async () => { delete process.env.OS_AGENT_SESSIONS_DIR; await rm(dir, { recursive: true, force: true }); });++describe("workflow data tables", () => {+ it("creates an owner-private table and CRUDs bounded rows", async () => {+ const table = await api.createWorkflowDataTable("owner-a", "Contacts", ["name", "email"]);+ expect((await api.listWorkflowDataTables("owner-a"))[0]).toMatchObject({ id: table.id, rowCount: 0, columns: ["name", "email"] });+ expect(await api.listWorkflowDataTables("owner-b")).toEqual([]);++ const row = await api.upsertWorkflowDataTableRow("owner-a", table.id, undefined, { name: "Ada", email: "[email protected]" });+ expect((await api.getWorkflowDataTable("owner-a", table.id)).rows[0]).toMatchObject({ id: row.id, values: { name: "Ada" } });+ await api.upsertWorkflowDataTableRow("owner-a", table.id, row.id, { name: "Ada Lovelace", email: "[email protected]" });+ expect((await api.getWorkflowDataTable("owner-a", table.id)).rows[0]?.values.name).toBe("Ada Lovelace");+ expect((await api.deleteWorkflowDataTableRow("owner-a", table.id, row.id)).deleted).toBe(true);+ expect((await api.deleteWorkflowDataTable("owner-a", table.id)).deleted).toBe(true);+ });++ it("rejects unknown columns and invalid definitions", async () => {+ await expect(api.createWorkflowDataTable("owner-a", "", ["name"])).rejects.toThrow("name");+ const table = await api.createWorkflowDataTable("owner-a", "Safe", ["name"]);+ await expect(api.upsertWorkflowDataTableRow("owner-a", table.id, undefined, { token: "nope" })).rejects.toThrow("unknown column");+ });+});diff --git a/lib/workflow/data-table-store.ts b/lib/workflow/data-table-store.tsnew file mode 100644index 00000000..e14f1a6f--- /dev/null+++ b/lib/workflow/data-table-store.ts@@ -0,0 +1,113 @@+import { randomUUID } from "node:crypto";+import path from "node:path";+import { agentSessionsDir } from "@/lib/agent/session-paths";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import { workflowGraphOwner } from "./graph-store";+import { readWorkflowJson, writeWorkflowFile } from "./private-file";++export type WorkflowDataTableRow = { id: string; values: Record<string, unknown>; createdAt: string; updatedAt: string };+export type WorkflowDataTable = { id: string; name: string; columns: string[]; rows: WorkflowDataTableRow[]; createdAt: string; updatedAt: string };+type Store = { version: 1; owner: string; tables: Record<string, WorkflowDataTable> };++const MAX_STORE_BYTES = 8 * 1024 * 1024;+const MAX_TABLES = 64;+const MAX_ROWS = 2000;+const MAX_COLUMNS = 32;+const MAX_ROW_BYTES = 32 * 1024;+const ID = /^[a-zA-Z0-9_-]{1,80}$/;++function file(owner: string) {+ if (!/^[a-f0-9]{64}$/.test(owner)) throw new Error("invalid workflow data-table owner");+ return path.join(agentSessionsDir(), ".workflow-data-tables", owner, "tables.json");+}+async function read(owner: string): Promise<Store> {+ try {+ const row = await readWorkflowJson(file(owner), MAX_STORE_BYTES, "workflow data-table store") as Store;+ if (row.version !== 1 || row.owner !== owner || !row.tables || typeof row.tables !== "object") throw new Error("invalid workflow data-table store");+ return row;+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { version: 1, owner, tables: {} };+ throw error;+ }+}+async function write(store: Store) {+ const body = JSON.stringify(store);+ if (Buffer.byteLength(body) > MAX_STORE_BYTES) throw new Error("workflow data-table store exceeds 8 MiB");+ await writeWorkflowFile(file(store.owner), body);+}+function tableName(value: unknown) {+ const name = typeof value === "string" ? value.trim() : "";+ if (!name || name.length > 80) throw new Error("data-table name must be 1-80 characters");+ return name;+}+function columns(value: unknown) {+ if (!Array.isArray(value) || value.length < 1 || value.length > MAX_COLUMNS) throw new Error("data-table requires 1-32 columns");+ const result = [...new Set(value.map((item) => typeof item === "string" ? item.trim() : ""))];+ if (result.length !== value.length || result.some((item) => !item || item.length > 64 || !/^[A-Za-z][A-Za-z0-9_. -]{0,63}$/.test(item))) throw new Error("data-table columns must be unique simple names");+ return result;+}+function rowValues(value: unknown, allowed: string[]) {+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("data-table row values must be an object");+ const row = value as Record<string, unknown>;+ if (Object.keys(row).some((key) => !allowed.includes(key))) throw new Error("data-table row contains an unknown column");+ const encoded = JSON.stringify(row);+ if (!encoded || Buffer.byteLength(encoded) > MAX_ROW_BYTES) throw new Error("data-table row exceeds 32 KiB");+ return structuredClone(row);+}+function tableId(value: unknown) {+ const id = typeof value === "string" ? value : "";+ if (!ID.test(id)) throw new Error("invalid data-table id");+ return id;+}++export async function listWorkflowDataTables(principal: string) {+ const owner = workflowGraphOwner(principal), store = await read(owner);+ return Object.values(store.tables).sort((a, b) => a.name.localeCompare(b.name)).map(({ rows, ...table }) => ({ ...table, rowCount: rows.length }));+}+export async function getWorkflowDataTable(principal: string, rawId: unknown) {+ const owner = workflowGraphOwner(principal), id = tableId(rawId), table = (await read(owner)).tables[id];+ if (!table) throw new Error("workflow data-table not found");+ return structuredClone(table);+}+export async function createWorkflowDataTable(principal: string, rawName: unknown, rawColumns: unknown) {+ const owner = workflowGraphOwner(principal), name = tableName(rawName), nextColumns = columns(rawColumns);+ return withSecurityStoreLock(file(owner), async () => {+ const store = await read(owner);+ if (Object.keys(store.tables).length >= MAX_TABLES) throw new Error("workflow data-table limit reached");+ const now = new Date().toISOString(), id = randomUUID();+ const table: WorkflowDataTable = { id, name, columns: nextColumns, rows: [], createdAt: now, updatedAt: now };+ store.tables[id] = table; await write(store); return structuredClone(table);+ });+}+export async function deleteWorkflowDataTable(principal: string, rawId: unknown) {+ const owner = workflowGraphOwner(principal), id = tableId(rawId);+ return withSecurityStoreLock(file(owner), async () => {+ const store = await read(owner), deleted = delete store.tables[id];+ if (deleted) await write(store);+ return { id, deleted };+ });+}+export async function upsertWorkflowDataTableRow(principal: string, rawTableId: unknown, rawRowId: unknown, rawValues: unknown) {+ const owner = workflowGraphOwner(principal), tableIdValue = tableId(rawTableId);+ return withSecurityStoreLock(file(owner), async () => {+ const store = await read(owner), table = store.tables[tableIdValue];+ if (!table) throw new Error("workflow data-table not found");+ const values = rowValues(rawValues, table.columns), rowId = rawRowId ? tableId(rawRowId) : randomUUID();+ const index = table.rows.findIndex((row) => row.id === rowId), now = new Date().toISOString();+ if (index < 0 && table.rows.length >= MAX_ROWS) throw new Error("workflow data-table row limit reached");+ const row: WorkflowDataTableRow = index >= 0 ? { ...table.rows[index]!, values, updatedAt: now } : { id: rowId, values, createdAt: now, updatedAt: now };+ if (index >= 0) table.rows[index] = row; else table.rows.push(row);+ table.updatedAt = now; await write(store); return structuredClone(row);+ });+}+export async function deleteWorkflowDataTableRow(principal: string, rawTableId: unknown, rawRowId: unknown) {+ const owner = workflowGraphOwner(principal), tableIdValue = tableId(rawTableId), rowId = tableId(rawRowId);+ return withSecurityStoreLock(file(owner), async () => {+ const store = await read(owner), table = store.tables[tableIdValue];+ if (!table) throw new Error("workflow data-table not found");+ const before = table.rows.length; table.rows = table.rows.filter((row) => row.id !== rowId);+ const deleted = table.rows.length !== before;+ if (deleted) { table.updatedAt = new Date().toISOString(); await write(store); }+ return { tableId: tableIdValue, rowId, deleted };+ });+}diff --git a/lib/workflow/graph-engine-controls.test.ts b/lib/workflow/graph-engine-controls.test.tsnew file mode 100644index 00000000..70237c01--- /dev/null+++ b/lib/workflow/graph-engine-controls.test.ts@@ -0,0 +1,55 @@+import { afterAll, describe, expect, it, vi } from "vitest";+import { mkdtemp, rm } from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import type { CapabilityTool } from "@/lib/capabilities/tool";++vi.mock("@/lib/capabilities/execute", () => ({ executeCapabilityCall: async ({ tool, args, context }: { tool: CapabilityTool; args: Record<string, unknown>; context: never }) => {+ try { return { kind: "success", result: await tool.run(args, context) }; }+ catch (error) { return { kind: "error", message: error instanceof Error ? error.message : String(error) }; }+} }));++const dir = await mkdtemp(path.join(os.tmpdir(), "mso-graph-controls-"));+process.env.OS_AGENT_SESSIONS_DIR = dir;+const { createWorkflowGraph } = await import("./graph-store");+const { requestWorkflowGraphStop, startWorkflowGraph, workflowGraphRunStatus } = await import("./graph-engine");+const tables = await import("./data-table-store");+const context = { principal: "controls-owner", sessionId: "session", scope: "exec" as const, actor: "controls-owner" };+afterAll(async () => { delete process.env.OS_AGENT_SESSIONS_DIR; await rm(dir, { recursive: true, force: true }); });++describe("workflow execution controls and data tables", () => {+ it("stops after the current bounded action and skips remaining nodes", async () => {+ let enter!: () => void, release!: () => void;+ const entered = new Promise<void>((resolve) => { enter = resolve; });+ const blocked = new Promise<void>((resolve) => { release = resolve; });+ const graph = await createWorkflowGraph("controls-owner", { name: "Stop run", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [+ { id: "start", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },+ { id: "tool", name: "Long tool", type: "tool", position: { x: 100, y: 0 }, config: { tool: "fixture_block", arguments: {} } },+ { id: "out", name: "After stop", type: "output", position: { x: 200, y: 0 }, config: { value: "should-not-run" } },+ ], edges: [{ id: "e1", source: "start", target: "tool" }, { id: "e2", source: "tool", target: "out" }] });+ const tool: CapabilityTool = { name: "fixture_block", description: "fixture", scope: "exec", inputSchema: { type: "object", properties: {} }, run: async () => { enter(); await blocked; return { ok: true }; } };+ const started = await startWorkflowGraph(graph, { token: "private-input" }, "stop-run-once", context, (name) => name === tool.name ? tool : undefined);+ await entered;+ expect(await requestWorkflowGraphStop("controls-owner", started.id)).toMatchObject({ state: "running", stopRequested: true });+ release();+ const done = await workflowGraphRunStatus("controls-owner", started.id, 5000);+ expect(done.state).toBe("interrupted");+ expect(done.nodes.find((node) => node.id === "out")?.state).toBe("skipped");+ expect(JSON.stringify(done)).not.toContain("private-input");+ });++ it("mutates and reads persistent data tables through data_table nodes", async () => {+ const table = await tables.createWorkflowDataTable("controls-owner", "People", ["name"]);+ const graph = await createWorkflowGraph("controls-owner", { name: "Data table", description: "", status: "draft", inputs: {}, metadata: {}, nodes: [+ { id: "start-dt", name: "Start", type: "manual", position: { x: 0, y: 0 }, config: {} },+ { id: "insert", name: "Insert", type: "data_table", position: { x: 120, y: 0 }, config: { mode: "insert", tableId: table.id, values: { name: "Ada" } } },+ { id: "read", name: "Read", type: "data_table", position: { x: 240, y: 0 }, config: { mode: "get", tableId: table.id } },+ { id: "out-dt", name: "Out", type: "output", position: { x: 360, y: 0 }, config: { value: { "$ref": "nodes.read.output.rows" } } },+ ], edges: [{ id: "d1", source: "start-dt", target: "insert" }, { id: "d2", source: "insert", target: "read" }, { id: "d3", source: "read", target: "out-dt" }] });+ const started = await startWorkflowGraph(graph, {}, "data-table-node", context, () => undefined);+ const done = await workflowGraphRunStatus("controls-owner", started.id, 5000);+ expect(done.state).toBe("completed");+ expect((await tables.getWorkflowDataTable("controls-owner", table.id)).rows[0]?.values.name).toBe("Ada");+ expect(done.nodes.find((node) => node.id === "read")?.output).toMatchObject({ name: "People" });+ });+});diff --git a/lib/workflow/graph-engine.ts b/lib/workflow/graph-engine.tsindex 72143d1c..d1d3915e 100644--- a/lib/workflow/graph-engine.ts+++ b/lib/workflow/graph-engine.ts@@ -9,9 +9,10 @@ import { compact, executeNode } from "./graph-runtime";import { lockWorkflowGraphRun, pruneWorkflowGraphRuns, publicWorkflowGraphRun, readWorkflowGraphRun, writeWorkflowGraphRun } from "./graph-run-store";import { workflowSecretValues } from "./variables";-const state = globalThis as typeof globalThis & { msoGraphInstance?: string; msoGraphPending?: Map<string, Promise<void>> };+const state = globalThis as typeof globalThis & { msoGraphInstance?: string; msoGraphPending?: Map<string, Promise<void>>; msoGraphCancelled?: Set<string> };const INSTANCE = state.msoGraphInstance ??= randomUUID();const pending = state.msoGraphPending ??= new Map<string, Promise<void>>();+const cancelled = state.msoGraphCancelled ??= new Set<string>();type Resolver = (name: string) => CapabilityTool | undefined;export type WorkflowRunTrigger = WorkflowGraphRun["trigger"];function hash(value: string): string { return createHash("sha256").update(value).digest("hex"); }@@ -46,9 +47,11 @@ async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Recortry {const remaining=new Set(graph.nodes.map((node)=>node.id));while(remaining.size){+ if(cancelled.has(run.id)){run.state="interrupted";run.error="Stopped by user.";for(const pendingId of remaining){const queued=rows.get(pendingId);if(queued?.state==="queued"){queued.state="skipped";queued.logs.push("Skipped because the execution was stopped.");}}throw new Error(run.error);}if(Date.now()-Date.parse(run.startedAt)>15*60_000)throw new Error("workflow graph exceeded 15 minutes; remaining nodes were not started");let progressed=false;for(const node of graph.nodes){+ if(cancelled.has(run.id)){run.state="interrupted";run.error="Stopped by user.";for(const pendingId of remaining){const queued=rows.get(pendingId);if(queued?.state==="queued"){queued.state="skipped";queued.logs.push("Skipped because the execution was stopped.");}}throw new Error(run.error);}if(!remaining.has(node.id))continue; const deps=incoming.get(node.id)??[]; if(deps.some((edge)=>edgeState.get(edge.id)==="pending"))continue; const row=rows.get(node.id)!;const triggerNode=["manual","schedule","webhook"].includes(node.type),triggerMismatch=Boolean(triggerNode&&run.trigger?.nodeId&&run.trigger.nodeId!==node.id);if(node.disabled||triggerMismatch||(deps.length>0&&deps.every((edge)=>edgeState.get(edge.id)==="disabled"))){row.state="skipped";row.finishedAt=new Date().toISOString();row.logs.push(node.disabled?"Node disabled by workflow definition.":triggerMismatch?"Skipped because another trigger started this run.":"Skipped because no incoming branch was selected.");disableOutgoing(node.id);remaining.delete(node.id);progressed=true;run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);continue;}row.state="running";row.startedAt=new Date().toISOString();row.logs.push("Node started.");run.updatedAt=row.startedAt;await writeWorkflowGraphRun(run);await sessionEvent("running",`${node.name} · ${node.type}`); const started=Date.now(),policy=retryPolicy(node); let failure:unknown;@@ -59,7 +62,7 @@ async function execute(run: WorkflowGraphRun, graph: WorkflowGraph, input: Recorif(!progressed&&remaining.size)throw new Error("workflow graph could not make progress; inspect dependencies/branches");}run.state=handledErrors?"completed_with_errors":"completed";- } catch(error){if(run.state!=="failed"){run.state="failed";run.error=secretText(redactText(error instanceof Error?error.message:"workflow graph failed",800),secrets);}}+ } catch(error){if(run.state!=="failed"&&run.state!=="interrupted"){run.state="failed";run.error=secretText(redactText(error instanceof Error?error.message:"workflow graph failed",800),secrets);}}run.finishedAt=run.updatedAt=new Date().toISOString();await writeWorkflowGraphRun(run);await sessionEvent(run.state,graph.name);}@@ -72,6 +75,8 @@ 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: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);});+ 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],runtimeInput:structuredClone(input)};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);cancelled.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);}++export async function requestWorkflowGraphStop(principal:string,id:string){const owner=workflowGraphOwner(principal),run=await readWorkflowGraphRun(owner,id);if(!run)throw new Error("workflow graph run not found for this principal");if(run.state!=="running")return{...publicWorkflowGraphRun(run),stopRequested:false};if(run.instance!==INSTANCE||!pending.has(id))throw new Error("workflow execution is owned by another runtime; refresh its status before retrying stop");cancelled.add(id);return{...publicWorkflowGraphRun(run),stopRequested:true};}diff --git a/lib/workflow/graph-run-store.ts b/lib/workflow/graph-run-store.tsindex 9f727dd9..5da19d25 100644--- a/lib/workflow/graph-run-store.ts+++ b/lib/workflow/graph-run-store.ts@@ -48,10 +48,18 @@ export async function pruneWorkflowGraphRuns(owner: string): Promise<void> {}export function publicWorkflowGraphRun(run: WorkflowGraphRun) {- const { owner: _owner, pid: _pid, instance: _instance, sessionId: _sessionId, fingerprint: _fingerprint, ancestry: _ancestry, ...safe } = run;+ const { owner: _owner, pid: _pid, instance: _instance, sessionId: _sessionId, fingerprint: _fingerprint, ancestry: _ancestry, runtimeInput: _runtimeInput, ...safe } = run;return { ...safe, pollAfterMs: run.state === "running" ? 1500 : 0 };}+export async function deleteWorkflowGraphRun(owner: string, id: string) {+ const existing = await readWorkflowGraphRun(owner, id);+ if (!existing) return { id, deleted: false as const };+ if (existing.state === "running") throw new Error("running workflow execution must be stopped before deletion");+ await removeWorkflowFile(file(owner, id));+ return { id, deleted: true as const };+}+export type WorkflowGraphRunFilter = { graphId?: string; state?: WorkflowGraphRun["state"]; limit?: number; offset?: number };export async function listWorkflowGraphRuns(owner: string, filter: WorkflowGraphRunFilter = {}) {const dir = path.dirname(file(owner, "0".repeat(32))), names = (await listWorkflowFiles(dir)).filter((name) => /^[a-f0-9]{32}\.json$/.test(name));diff --git a/lib/workflow/graph-runtime.ts b/lib/workflow/graph-runtime.tsindex 3c50e2c6..51691620 100644--- a/lib/workflow/graph-runtime.ts+++ b/lib/workflow/graph-runtime.ts@@ -12,6 +12,7 @@ import { executeFlowNode, workflowItems, type FlowNodeResult } from "./graph-floimport { workflowVariableValues } from "./variables";import { organizationLocalAgentPrincipal, resolveOrganizationSeat } from "@/lib/agent/organization-runtime";import { workflowCacheDelete, workflowCacheGet, workflowCacheSet } from "./cache-store";+import { deleteWorkflowDataTableRow, getWorkflowDataTable, listWorkflowDataTables, upsertWorkflowDataTableRow } from "./data-table-store";import { repeatWorkflow, runWorkflowGraphChild } from "./graph-repeat";type Resolver = (name: string) => CapabilityTool | undefined;@@ -71,6 +72,24 @@ async function executeNode(node: WorkflowGraphNode, run: WorkflowGraphRun, graphif (typeof config.query === "string" && config.query) return { output: await callTool("project_memory_search", { project, query: config.query, limit: Number(config.limit) || 8, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project memory queried." };return { output: await callTool("project_knowledge_get", { project, ...(context.workflowId ? { workflow_id: context.workflowId } : {}) }, context, resolve), log: "Project knowledge resolved." };}+ if (node.type === "data_table") {+ const mode = typeof config.mode === "string" ? config.mode : "list";+ if (mode === "list") return { output: { tables: await listWorkflowDataTables(principal) }, log: "Workflow data tables listed." };+ const tableId = typeof config.tableId === "string" ? config.tableId : "";+ if (!tableId) throw new Error("data_table node requires config.tableId");+ if (mode === "get") return { output: await getWorkflowDataTable(principal, tableId), log: "Workflow data table read." };+ if (mode === "insert" || mode === "update") {+ const values = graphObject(config.values) ? config.values : graphInput;+ const rowId = mode === "update" ? String(config.rowId ?? "") : undefined;+ if (mode === "update" && !rowId) throw new Error("data_table update requires config.rowId");+ return { output: await upsertWorkflowDataTableRow(principal, tableId, rowId, values), log: `Workflow data-table row ${mode === "insert" ? "inserted" : "updated"}.` };+ }+ if (mode === "delete") {+ const rowId = String(config.rowId ?? ""); if (!rowId) throw new Error("data_table delete requires config.rowId");+ return { output: await deleteWorkflowDataTableRow(principal, tableId, rowId), log: "Workflow data-table row deleted." };+ }+ throw new Error("data_table node mode must be list, get, insert, update, or delete");+ }if (node.type === "cache") {const key = typeof config.key === "string" ? config.key : `${graph.id}:${node.id}`;const mode = typeof config.mode === "string" ? config.mode : "get";diff --git a/lib/workflow/node-catalog.ts b/lib/workflow/node-catalog.tsindex 1e6e6bca..d58bfde3 100644--- a/lib/workflow/node-catalog.ts+++ b/lib/workflow/node-catalog.ts@@ -12,6 +12,7 @@ export const WORKFLOW_NODE_CATALOG:WorkflowNodeCatalogItem[]=[{type:"repeat",title:"Repeat Until",category:"Flow",description:"Run a saved workflow repeatedly until its output matches a condition or a hard iteration/time limit is reached.",handles:["done","exhausted"],defaults:{input:{},path:"result.output",equals:true,maxIterations:5,delayMs:1000,maxDurationMs:600000}},{type:"wait",title:"Wait",category:"Flow",description:"Delay execution or wait until a timestamp within run timeout.",defaults:{delayMs:1000}},{type:"cache",title:"Cache",category:"Context",description:"Read/write/delete a private principal-scoped TTL cache for reusable workflow data.",defaults:{mode:"get_or_set",ttlSeconds:300,key:"workflow-cache"}},+ {type:"data_table",title:"Data Table",category:"Context",description:"List/read persistent workflow tables or insert/update/delete table rows.",defaults:{mode:"list",tableId:""}},{type:"memory",title:"Memory",category:"Context",description:"Read/search/remember MSO agent memory or repo-local project memory.",defaults:{scope:"agent",mode:"search",query:""}},{type:"session",title:"Session",category:"Context",description:"Read current durable session, list/resume sessions, or attach a durable note.",defaults:{mode:"current"}},{type:"directory",title:"Directory",category:"Context",description:"Discover MSO tools, workflows, sessions, projects or skills at runtime.",defaults:{source:"tools",query:"",limit:30}},diff --git a/scripts/e2e/graph-custom.mjs b/scripts/e2e/graph-custom.mjsindex 43379abb..9e41dc61 100644--- a/scripts/e2e/graph-custom.mjs+++ b/scripts/e2e/graph-custom.mjs@@ -24,7 +24,7 @@ try {const orgEdges = [{ id: "a-b", source: "a", target: "b", label: "supports" }, { id: "b-c", source: "b", target: "c", label: "continues" }];const created = await api("/api/v1/organization", { action: "unit_upsert", expected_revision: chart.revision, unit: { id: "custom-test", key: "custom-test", name: "Custom Test", kind: "team", projectFlow: { version: 1, title: "Context", notes: "Source", nodes: orgNodes, edges: orgEdges } } });expect(created.status).toBe(200);- const openOrg = async () => { await page.goto(fixture.base + "/organization"); await page.getByRole("application", { name: "Organization units canvas", exact: true }).locator('[data-id="custom-test"]').click(); await expect(page.locator('[data-slot="organization-project-flow"]')).toBeVisible(); };+ const openOrg = async () => { await page.goto(fixture.base + "/organization"); const directory = page.locator('[data-slot="organization-unit-directory"]'); await expect(directory).toBeVisible(); await directory.getByRole("button", { name: /Custom Test/ }).click(); await expect(page.locator('[data-slot="organization-project-flow"]')).toBeVisible(); };await openOrg();const orgCanvas = page.getByRole("application", { name: "Organization project flow canvas", exact: true });const select = async (canvas, ids) => { for (const id of ids) await canvas.locator(`[data-id="${id}"]`).click({ modifiers: ["Control"] }); await expect(page.locator('[data-slot="graph-custom-controls"]')).toContainText(`${ids.length} selected`); };@@ -86,7 +86,12 @@ try {for (const viewport of [{ width: 1600, height: 1000 }, { width: 390, height: 844 }]) {await page.setViewportSize(viewport); await page.reload();await expect(wfCanvas.locator(".react-flow__node-customGroup")).toBeVisible();- expect(await page.locator('[data-slot="workflows-feature"]').evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);+ const overflow = await page.locator('[data-slot="workflows-feature"]').evaluate((el) => {+ const root = el.getBoundingClientRect();+ const offenders = [...el.querySelectorAll('*')].map((node) => ({ node, rect: node.getBoundingClientRect() })).filter(({ rect }) => rect.right > root.right + 1 || rect.left < root.left - 1).slice(0, 12).map(({ node, rect }) => ({ tag: node.tagName, slot: node.getAttribute('data-slot'), cls: node.className?.toString?.().slice(0, 160), text: node.textContent?.trim().slice(0, 80), left: Math.round(rect.left), right: Math.round(rect.right), width: Math.round(rect.width) }));+ return { ok: el.scrollWidth <= el.clientWidth + 1, clientWidth: el.clientWidth, scrollWidth: el.scrollWidth, offenders };+ });+ expect(overflow, JSON.stringify(overflow, null, 2)).toMatchObject({ ok: true });if (process.env.MSO_SCREENSHOT_DIR) { await mkdir(process.env.MSO_SCREENSHOT_DIR, { recursive: true }); await page.screenshot({ path: path.join(process.env.MSO_SCREENSHOT_DIR, `custom-workflow-${viewport.width}.png`) }); }}expect(errors).toEqual([]);diff --git a/scripts/e2e/organization-flow.mjs b/scripts/e2e/organization-flow.mjsindex 8b50db9b..de41481f 100644--- a/scripts/e2e/organization-flow.mjs+++ b/scripts/e2e/organization-flow.mjs@@ -30,9 +30,11 @@ try {}const open = async () => {await page.goto(fixture.base + "/organization");- const card = page.getByRole("application", { name: "Organization units canvas", exact: true }).locator('[data-id="flow-workspace"]');+ const directory = page.locator('[data-slot="organization-unit-directory"]');+ await expect(directory).toBeVisible();+ const card = directory.getByRole("button", { name: /Flow Workspace/ });await expect(card).toBeVisible();- expect(await card.evaluate((el) => el.offsetHeight)).toBeLessThan(170);+ expect(await card.evaluate((el) => el.offsetHeight)).toBeLessThan(220);await card.click();await expect(page.locator('[data-slot="organization-project-flow"]')).toBeVisible();};diff --git a/scripts/e2e/organization.mjs b/scripts/e2e/organization.mjsindex 9805fb6a..946f2e31 100644--- a/scripts/e2e/organization.mjs+++ b/scripts/e2e/organization.mjs@@ -35,14 +35,17 @@ export async function organizationJourney(page, fixture) {expect(response.status).toBe(200);await page.goto(fixture.base + "/organization");+ const unitDirectory = page.locator('[data-slot="organization-unit-directory"]');+ await expect(unitDirectory).toBeVisible();+ await expect(unitDirectory.getByRole("button", { name: /E2E Holding/ })).toBeVisible();+ await expect(unitDirectory.getByRole("button", { name: /E2E Product/ })).toBeVisible();+ await page.getByRole("button", { name: "Map", exact: true }).click();const unitCanvas = page.getByRole("application", { name: "Organization units canvas" });await expect(unitCanvas).toBeVisible();for (const name of ["Select mode", "Pan mode", "Zoom in", "Zoom out", "Fit view"]) await expect(unitCanvas.getByRole("button", { name })).toBeVisible();const unitMinimap = unitCanvas.getByLabel("Organization units canvas minimap");await expect(unitMinimap).toBeVisible();await expect(unitMinimap.locator(".react-flow__minimap-node")).toHaveCount(2);- await expect(page.getByText("E2E Holding", { exact: true }).first()).toBeVisible();- await expect(page.getByText("E2E Product", { exact: true }).first()).toBeVisible();expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);// Responsive contract: compact panes use one native unit picker, hide desktop-only@@ -56,18 +59,18 @@ export async function organizationJourney(page, fixture) {if (viewport.width < 700) {await expect(page.getByLabel("Organization unit", { exact: true })).toBeVisible();await expect(page.getByRole("navigation", { name: "Organization units" })).toBeHidden();- const rootNode = unitCanvas.locator('.react-flow__node').first();- const box = await rootNode.boundingBox();- expect(box?.width ?? 0).toBeGreaterThan(140);} else {await expect(page.getByRole("navigation", { name: "Organization units" })).toBeVisible();}+ await expect(page.locator('[data-slot="organization-unit-directory"]')).toBeVisible();}await page.setViewportSize({ width: 1280, height: 900 });await page.goto(fixture.base + "/organization");- await page.getByRole("button", { name: /E2E Product/ }).click();+ await page.locator('[data-slot="organization-unit-directory"]').getByRole("button", { name: /E2E Product/ }).click();await page.getByRole("button", { name: "Seats", exact: true }).click();+ await expect(page.locator('[data-slot="organization-seat-directory"]')).toBeVisible();+ await page.getByRole("button", { name: "Map", exact: true }).click();const seatCanvas = page.getByRole("application", { name: "Organization seats canvas" });await expect(seatCanvas).toBeVisible();await expect(seatCanvas.locator(".react-flow__node", { hasText: "Chief Executive Officer" })).toBeVisible();diff --git a/scripts/e2e/workflow-canvas.mjs b/scripts/e2e/workflow-canvas.mjsindex 30fac443..0c310e5e 100644--- a/scripts/e2e/workflow-canvas.mjs+++ b/scripts/e2e/workflow-canvas.mjs@@ -99,7 +99,7 @@ export async function workflowCanvasJourney(page, fixture) {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();+ await page.getByRole("button", { name: "Builder", exact: true }).click();// Connection controls are persisted graph metadata, not temporary React Flow styling.await page.locator(".react-flow__node", { hasText: "Manual Trigger" }).click();diff --git a/scripts/e2e/workflow-embeds.mjs b/scripts/e2e/workflow-embeds.mjsindex 32124fb5..60bdf59b 100644--- a/scripts/e2e/workflow-embeds.mjs+++ b/scripts/e2e/workflow-embeds.mjs@@ -1,158 +1,126 @@#!/usr/bin/env nodeimport { chromium, expect } from '@playwright/test';-import sharp from 'sharp';-import { mkdir, writeFile } from 'node:fs/promises';+import { writeFile } from 'node:fs/promises';import path from 'node:path';import { releaseFixture } from './release-fixture.mjs';-const app = { id: 'automation', title: 'n8n', description: 'Reviewed test provider', origin: 'https://automation.example.test', startPath: '/editor', externalAuthPath: '/signin', renderer: 'iframe', presentation: 'inline', environment: 'production', placements: ['workflows'], sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads' };-const liveOrigin = process.env.E2E_WORKFLOW_EMBED_ORIGIN;-const parentOrigin = process.env.E2E_WORKFLOW_EMBED_PARENT_ORIGIN;-if (liveOrigin && (!parentOrigin || !parentOrigin.startsWith('https://') || new URL(parentOrigin).origin !== parentOrigin)) throw new Error('Exact approved HTTPS E2E_WORKFLOW_EMBED_PARENT_ORIGIN required for live policy verification');-if (liveOrigin && (new URL(liveOrigin).origin !== liveOrigin || !liveOrigin.startsWith('https://'))) throw new Error('Exact HTTPS E2E_WORKFLOW_EMBED_ORIGIN required');+const app = {+ id: 'n8n',+ title: 'n8n',+ description: 'Reviewed test provider',+ origin: 'https://automation.example.test',+ startPath: '/editor',+ externalAuthPath: '/signin',+ renderer: 'iframe',+ presentation: 'inline',+ environment: 'production',+ placements: ['n8n'],+ sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads',+};+const fixture = await releaseFixture({ surfaceApps: [app] });let browser;-const evidence = [];try {browser = await chromium.launch({ headless: true });const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });- await context.addInitScript(device => { if (window !== window.top) return; localStorage.setItem('mso.device.id', device); localStorage.setItem('mso:onboarding:v1', 'done'); }, fixture.device);+ await context.addInitScript(device => {+ if (window !== window.top) return;+ localStorage.setItem('mso.device.id', device);+ localStorage.setItem('mso:onboarding:v1', 'done');+ }, fixture.device);+let frameRequests = 0;await context.route('https://automation.example.test/**', async route => {frameRequests++;- await route.fulfill({ contentType: 'text/html', body: '<!doctype html><html><head><title>Fixture editor</title></head><body><h1>Fixture editor</h1><label>External draft <input aria-label="External draft"></label></body></html>' });+ await route.fulfill({+ contentType: 'text/html',+ body: '<!doctype html><html><head><title>Fixture editor</title></head><body><h1>Fixture editor</h1><label>External draft <input aria-label="External draft"></label></body></html>',+ });});+const page = await context.newPage();page.setDefaultTimeout(15000);- page.setDefaultNavigationTimeout(30000);- const frameNetwork = [];- page.on("requestfailed", request => { if (liveOrigin && request.url().startsWith(liveOrigin)) frameNetwork.push({ path: new URL(request.url()).pathname, error: request.failure()?.errorText }); });- page.on("response", response => { if (liveOrigin && response.url().startsWith(liveOrigin) && response.status() >= 400) frameNetwork.push({ path: new URL(response.url()).pathname, status: response.status() }); });const errors = [];page.on('pageerror', error => errors.push(error.message));- await page.goto(fixture.base + '/login?returnTo=%2Fworkflows');++ await page.goto(fixture.base + '/login?returnTo=%2Fn8n');await page.locator('input[type="password"]').fill(fixture.password);await page.getByRole('button', { name: 'Unlock', exact: true }).click();- await expect(page).toHaveURL(fixture.base + '/workflows');- await expect(page.getByRole('tab', { name: 'n8n', exact: true })).toBeVisible();- expect(frameRequests).toBe(0);+ await expect(page).toHaveURL(fixture.base + '/n8n');+ await expect(page.getByText('n8n', { exact: true }).first()).toBeVisible();+ await expect(page.locator('iframe[title="n8n automation editor"]')).toBeVisible();+ await expect(page.frameLocator('iframe[title="n8n automation editor"]').getByRole('heading', { name: 'Fixture editor' })).toBeVisible();+const saved = await page.evaluate(async app => {const state = await (await fetch('/api/v1/workflow-embeds')).json();const input = { app, expectedRevision: state.revision, confirm: true };- const write = () => fetch('/api/v1/workflow-embeds', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) });+ const write = () => fetch('/api/v1/workflow-embeds', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(input),+ });const response = await write();return { status: response.status, updated: await response.json(), staleStatus: (await write()).status };}, app);- expect(saved.status).toBe(200); expect(saved.updated.id).toBe(app.id); expect(saved.staleStatus).toBe(409);- evidence.push({ ownerReviewedConfiguration: true, staleRevisionRejected: true });- console.log('PASS owner metadata save and stale-revision refusal');- const result = await page.evaluate(async () => {- const res = await fetch('/api/v1/workflows', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'create', graph: { name: 'Native fixture', description: 'Private fixture', status: 'draft', inputs: {}, metadata: { provenance: 'user' }, nodes: [{ id: 'manual', name: 'Manual', type: 'manual', position: { x: 80, y: 160 }, config: {} }, { id: 'output', name: 'Output', type: 'output', position: { x: 420, y: 160 }, config: {} }], edges: [{ id: 'start', source: 'manual', target: 'output' }] } }) });- return res.status;- });- expect(result).toBe(200);+ expect(saved.status).toBe(200);+ expect(saved.updated.id).toBe('n8n');+ expect(saved.staleStatus).toBe(409);++ // n8n is a separate first-class feature. Native Workflows must not mount an external provider tab/frame.+ await page.goto(fixture.base + '/workflows');+ await expect(page.locator('[data-slot="workflows-feature"]')).toBeVisible();+ await expect(page.locator('[data-slot="workflows-workspace"]')).toHaveCount(0);+ await expect(page.locator('iframe[title="n8n automation editor"]')).toHaveCount(0);+for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {await page.setViewportSize(viewport);- await page.reload();- await expect(page.getByLabel('Workflow name')).toHaveValue('Native fixture');- await page.getByLabel('Workflow name').fill('Unsaved fixture');- await page.getByRole('tab', { name: 'n8n', exact: true }).click();- const frame = page.frameLocator('iframe[title="n8n workflow editor"]');+ await page.goto(fixture.base + '/n8n');+ const frame = page.frameLocator('iframe[title="n8n automation editor"]');await expect(frame.getByRole('heading', { name: 'Fixture editor' })).toBeVisible();await frame.getByLabel('External draft').fill('External unsaved draft');- const requestsBeforeSwitch = frameRequests;- await page.getByRole('tab', { name: 'MSO', exact: true }).click();- await expect(page.getByLabel('Workflow name')).toHaveValue('Unsaved fixture');- await page.getByRole('tab', { name: 'MSO', exact: true }).press('ArrowRight');- await expect(page.getByRole('tab', { name: 'n8n', exact: true })).toBeFocused();await expect(frame.getByLabel('External draft')).toHaveValue('External unsaved draft');- expect(frameRequests).toBe(requestsBeforeSwitch);- expect(await page.locator('[data-slot="workflows-workspace"]').evaluate(el => el.scrollWidth <= el.clientWidth + 1)).toBe(true);- const iframeBox = await page.locator('iframe[title="n8n workflow editor"]').boundingBox();- if (iframeBox.height <= 120 && process.env.E2E_EVIDENCE_DIR) {- await mkdir(process.env.E2E_EVIDENCE_DIR, { recursive: true });- await page.screenshot({ path: path.join(process.env.E2E_EVIDENCE_DIR, 'embed-height-diagnostic.png'), fullPage: true });- console.log(JSON.stringify({ viewport, iframeBox, layout: await page.locator('[data-slot="workflows-workspace"]').evaluate(el => ({ workspace: el.getBoundingClientRect().toJSON(), children: [...el.children].map(x => ({ tag: x.tagName, hidden: x.hidden, rect: x.getBoundingClientRect().toJSON() })) })) }));- }+ const iframeBox = await page.locator('iframe[title="n8n automation editor"]').boundingBox();expect(iframeBox.height).toBeGreaterThan(120);await expect(page.getByRole('link', { name: 'Sign in', exact: true })).toHaveAttribute('href', app.origin + '/signin');await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toHaveAttribute('target', '_blank');+ const before = frameRequests;await page.getByRole('button', { name: 'Reload n8n', exact: true }).click();await expect(frame.getByLabel('External draft')).toHaveValue('');- evidence.push({ viewport, nativeDraftPreserved: true, externalDraftPreserved: true, reload: true, keyboard: true, reflow: true, frameHeight: iframeBox.height });+ expect(frameRequests).toBeGreaterThan(before);+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);}- console.log('PASS provider tabs, native/external draft preservation and all three viewport sizes');+await fixture.setRole('viewer');expect(await page.evaluate(async () => (await fetch('/api/v1/workflow-embeds')).status)).toBe(403);await page.evaluate(() => window.dispatchEvent(new Event('focus')));- await expect(page.getByRole('tab', { name: 'n8n', exact: true })).toHaveCount(0);- await expect(page.locator('iframe[title="n8n workflow editor"]')).toHaveCount(0);- console.log('PASS demotion response and removed frame');+ await expect(page.locator('iframe[title="n8n automation editor"]')).toHaveCount(0);+ await expect(page.getByText('App unavailable', { exact: true })).toBeVisible();+await fixture.setRole('owner');await writeFile(path.join(fixture.dir, 'surface-apps.json'), JSON.stringify([{ ...app, renderer: 'remote', reason: 'Fixture provider requires top-level access' }]));await page.evaluate(() => window.dispatchEvent(new Event('focus')));- await page.getByRole('tab', { name: 'n8n', exact: true }).click();await expect(page.getByText('Fixture provider requires top-level access')).toBeVisible();- await expect(page.locator('iframe[title="n8n workflow editor"]')).toHaveCount(0);- evidence.push({ ownerDemotion: '403 and frame removed', remoteOnly: 'no iframe' });- console.log('PASS remote-only fallback');- // Cookies have no port isolation: prove a reviewed same-host HTTPS editor is- // visibly blocked before any frame/login/navigation can send the fixture session.- const unsafe = new URL(fixture.base); unsafe.protocol = 'https:'; unsafe.port = '4443';+ await expect(page.locator('iframe[title="n8n automation editor"]')).toHaveCount(0);++ const unsafe = new URL(fixture.base);+ unsafe.protocol = 'https:';+ unsafe.port = '4443';let unsafeRequests = 0;const watchUnsafe = request => { if (request.url().startsWith(unsafe.origin)) unsafeRequests++; };page.on('request', watchUnsafe);await writeFile(path.join(fixture.dir, 'surface-apps.json'), JSON.stringify([{ ...app, origin: unsafe.origin }]));await page.evaluate(() => window.dispatchEvent(new Event('focus')));- await page.getByRole('tab', { name: 'n8n', exact: true }).click();await expect(page.getByRole('alert').filter({ hasText: 'this editor would receive the MSO session cookie' })).toBeVisible();- await expect(page.locator('iframe[title="n8n workflow editor"]')).toHaveCount(0);+ await expect(page.locator('iframe[title="n8n automation editor"]')).toHaveCount(0);await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toHaveCount(0);await expect(page.getByRole('link', { name: 'Sign in', exact: true })).toHaveCount(0);expect(unsafeRequests).toBe(0);page.off('request', watchUnsafe);- evidence.push({ cookieCollision: 'blocked frame, login and navigation', unsafeRequests });- console.log('PASS cookie-isolated external editors: no unsafe frame, link or request');- if (liveOrigin) {- await writeFile(path.join(fixture.dir, 'surface-apps.json'), JSON.stringify([{ ...app, id: 'live-n8n', origin: liveOrigin, startPath: '/home/workflows' }]));- await page.setViewportSize({ width: 1280, height: 900 });- await page.evaluate(() => window.dispatchEvent(new Event('focus')));- await page.locator('[role="tab"][id$="-tab-live-n8n"]').click();- await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toHaveAttribute('href', liveOrigin + '/home/workflows');- await expect.poll(() => frameNetwork.some(row => row.error === 'net::ERR_BLOCKED_BY_RESPONSE'), {timeout:20000}).toBe(true);- await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toBeVisible();- evidence.push({ unapprovedLocalParentBlocked: true, fallbackVisible: true });- const probe = await browser.newContext({ viewport: { width: 1280, height: 900 } });- const probePage = await probe.newPage();- probePage.setDefaultTimeout(15000);- const probeUrl = parentOrigin + '/__workflow_embed_policy_probe__';- // Synthetic parent document at the explicitly approved origin; the child is- // live n8n. No owner session, response-header rewrite or browser-security flag.- await probe.route(probeUrl, route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><html><head><title>n8n frame policy verification</title></head><body style="margin:0"><iframe title="Live n8n" style="display:block;width:100vw;height:100vh;border:0" referrerpolicy="no-referrer" sandbox="' + app.sandbox + '" src="' + liveOrigin + '/home/workflows"></iframe></body></html>' }));- await probePage.goto(probeUrl);- await probePage.bringToFront();- await expect(probePage.frameLocator('iframe').locator('input[type="password"]')).toBeVisible({ timeout:30000 });- const capturePaint = async filename => {- let image;- await expect.poll(async () => {- image = await probePage.screenshot({ fullPage: false, animations: 'disabled' });- return (await sharp(image).stats()).entropy;- }, { timeout:10000, intervals:[100,250,500] }).toBeGreaterThan(0.1);- if (process.env.E2E_EVIDENCE_DIR) {- await mkdir(process.env.E2E_EVIDENCE_DIR, { recursive: true });- await writeFile(path.join(process.env.E2E_EVIDENCE_DIR, filename), image);- }- };- await capturePaint('n8n-approved-parent-desktop.png');- await probePage.setViewportSize({ width:390, height:844 });- await expect(probePage.frameLocator('iframe').locator('input[type="password"]')).toBeVisible();- await capturePaint('n8n-approved-parent-mobile.png');- evidence.push({ liveProvider: liveOrigin, approvedParentOrigin: parentOrigin, parentDocumentIsSynthetic: true, signedOutLoginRendered: true, paintVerified: true, authenticatedEditorTested: false });- await probe.close();- }expect(errors).toEqual([]);- if (process.env.E2E_EVIDENCE_DIR) await writeFile(path.join(process.env.E2E_EVIDENCE_DIR, 'workflow-embed-browser.json'), JSON.stringify({ passed: true, evidence }, null, 2));- console.log(JSON.stringify({ passed: true, evidence }, null, 2));+ console.log('PASS dedicated n8n feature, native Workflows separation, responsive embed, demotion and cookie isolation');await context.close();-} finally { await browser?.close(); await fixture.close(); }+} finally {+ await browser?.close();+ await fixture.close();+}