Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(canvas): unify organization and workflow navigation

Rahman795cacc49b91
diff --git a/app/globals.css b/app/globals.css
index 7145c6e8..82f0ac1c 100644
--- a/app/globals.css
+++ b/app/globals.css
@@ -1,5 +1,6 @@
@import "tailwindcss";
@import "tw-animate-css";
+@import "@xyflow/react/dist/style.css";
/* Dark is driven by [data-theme=dark] (os-rr convention), so shadcn `dark:`
utilities key off the same attribute. */
@@ -704,3 +705,47 @@ body {
}
[data-shell="ios"] [data-slot="widget-card"] { border-radius: 22px; }
[data-slot="mobile-widgets"], [data-slot="quicklinks-widget-grid"] { max-width: 100%; }
+
+/* Shared node-canvas chrome (Organization + Workflows). */
+.mso-graph-flow {
+ --xy-background-color: transparent;
+ --xy-node-border: 1px solid var(--border);
+ --xy-handle-background-color: var(--background);
+ --xy-handle-border-color: var(--sep-strong);
+ --xy-edge-stroke: var(--sep-strong);
+ --xy-edge-stroke-selected: var(--accent);
+ background: color-mix(in srgb, var(--surface) 78%, transparent);
+}
+.mso-graph-flow .react-flow__controls {
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: calc(var(--radius) + 0.125rem);
+ background: var(--glass-panel);
+ box-shadow: var(--shadow-pop);
+ backdrop-filter: blur(var(--blur));
+}
+.mso-graph-flow .react-flow__controls-button {
+ width: 2rem;
+ height: 2rem;
+ border: 0;
+ border-bottom: 1px solid var(--border);
+ background: transparent;
+ color: var(--text);
+}
+.mso-graph-flow .react-flow__controls-button:last-child { border-bottom: 0; }
+.mso-graph-flow .react-flow__controls-button:hover,
+.mso-graph-flow .react-flow__controls-button.is-active { background: var(--hover-strong); }
+.mso-graph-flow .react-flow__controls-button svg { max-width: 0.9rem; max-height: 0.9rem; fill: none; }
+.mso-graph-flow .react-flow__minimap {
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: calc(var(--radius) + 0.125rem);
+ background: var(--glass-panel);
+ box-shadow: var(--shadow-pop);
+ backdrop-filter: blur(var(--blur));
+}
+.mso-graph-flow .react-flow__minimap-mask { fill: color-mix(in srgb, var(--surface) 60%, transparent); }
+.mso-graph-flow .react-flow__minimap-node { fill: var(--text-dim); stroke: none; }
+.mso-graph-flow .react-flow__selection,
+.mso-graph-flow .react-flow__nodesselection-rect { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 10%, transparent); }
+.mso-graph-flow .react-flow__edge.selected .react-flow__edge-path { stroke: var(--accent); }
diff --git a/bun.lock b/bun.lock
index deea0fd4..b625aa9d 100644
--- a/bun.lock
+++ b/bun.lock
@@ -20,6 +20,7 @@
"@radix-ui/react-tooltip": "^1.2.9",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+ "@xyflow/react": "12.11.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"geist": "^1.7.2",
@@ -416,6 +417,18 @@
"@types/chai": ["@types/[email protected]", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="],
+ "@types/d3-color": ["@types/[email protected]", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
+
+ "@types/d3-drag": ["@types/[email protected]", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-HE3jVKlzU9AaMazNufooRJ5ZpWmLIoc90A37WU2JMmeq28w1FQqCZswHZ3xR+SuxYftzHq6WU6KJHvqxKzTxxQ=="],
+
+ "@types/d3-interpolate": ["@types/[email protected]", "", { "dependencies": { "@types/d3-color": "*" } }, "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA=="],
+
+ "@types/d3-selection": ["@types/[email protected]", "", {}, "sha512-Qe/KWYhEiIIxGs7HrAAjMfShxKldx19SJtr5zu53f3afPsdZNz7HHtdTLXo/kqeiWNXVycI24kSnfzBYkTzpgw=="],
+
+ "@types/d3-transition": ["@types/[email protected]", "", { "dependencies": { "@types/d3-selection": "*" } }, "sha512-uZS5shfxzO3rGlu0cC3bjmMFKsXv+SmZZcgp0KD22ts4uGXp5EVYGzu/0YdwZeKmddhcAccYtREJKkPfXkZuCg=="],
+
+ "@types/d3-zoom": ["@types/[email protected]", "", { "dependencies": { "@types/d3-interpolate": "*", "@types/d3-selection": "*" } }, "sha512-iqMC4/YlFCSlO8+2Ii1GGGliCAY4XdeG748w5vQUbevlbDu0zSjH/+jojorQVBK/se0j6DUFNPBGSqD3YWYnDw=="],
+
"@types/deep-eql": ["@types/[email protected]", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="],
"@types/estree": ["@types/[email protected]", "", {}, "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="],
@@ -516,6 +529,10 @@
"@xterm/xterm": ["@xterm/[email protected]", "", {}, "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg=="],
+ "@xyflow/react": ["@xyflow/[email protected]", "", { "dependencies": { "@xyflow/system": "0.0.82", "classcat": "^5.0.3", "zustand": "^4.4.0" }, "peerDependencies": { "@types/react": ">=17", "@types/react-dom": ">=17", "react": ">=17", "react-dom": ">=17" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-9XsEJNHjatKYndszKTF/bsU7FOP9dJ6V/EQwzy3oMdtqgBuUq7BjKSwkEo+C7s4qHstHQfwwoHA3E8QfpPxZZQ=="],
+
+ "@xyflow/system": ["@xyflow/[email protected]", "", { "dependencies": { "@types/d3-drag": "^3.0.7", "@types/d3-interpolate": "^3.0.4", "@types/d3-selection": "^3.0.10", "@types/d3-transition": "^3.0.8", "@types/d3-zoom": "^3.0.8", "d3-drag": "^3.0.0", "d3-interpolate": "^3.0.1", "d3-selection": "^3.0.0", "d3-zoom": "^3.0.0" } }, "sha512-4DKnL3CGtCGLRSmgDqaajRVgeksMXq/Yw4wPfdMfm7JvdIiWHGzVYOfFUztiATwdBXZqUU6HhehwUdbV9G23PQ=="],
+
"acorn": ["[email protected]", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="],
"acorn-jsx": ["[email protected]", "", { "peerDependencies": { "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ=="],
@@ -586,6 +603,8 @@
"class-variance-authority": ["[email protected]", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="],
+ "classcat": ["[email protected]", "", {}, "sha512-JhZUT7JFcQy/EzW605k/ktHtncoo9vnyW/2GspNYwFlN1C/WmjuV/xtS04e9SOkL2sTdw0VAZ2UGCcQ9lR6p6w=="],
+
"client-only": ["[email protected]", "", {}, "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA=="],
"clsx": ["[email protected]", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
@@ -602,6 +621,24 @@
"csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+ "d3-color": ["[email protected]", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
+
+ "d3-dispatch": ["[email protected]", "", {}, "sha512-rzUyPU/S7rwUflMyLc1ETDeBj0NRuHKKAcvukozwhshr6g6c5d8zh4c2gQjY2bZ0dXeGLWc1PF174P2tVvKhfg=="],
+
+ "d3-drag": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-selection": "3" } }, "sha512-pWbUJLdETVA8lQNJecMxoXfH6x+mO2UQo8rSmZ+QqxcbyA3hfeprFgIT//HW2nlHChWeIIMwS2Fq+gEARkhTkg=="],
+
+ "d3-ease": ["[email protected]", "", {}, "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w=="],
+
+ "d3-interpolate": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
+
+ "d3-selection": ["[email protected]", "", {}, "sha512-fmTRWbNMmsmWq6xJV8D19U/gw/bwrHfNXxrIN+HfZgnzqTHp9jOmKMhsTUjXOJnZOdZY9Q28y4yebKzqDKlxlQ=="],
+
+ "d3-timer": ["[email protected]", "", {}, "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA=="],
+
+ "d3-transition": ["[email protected]", "", { "dependencies": { "d3-color": "1 - 3", "d3-dispatch": "1 - 3", "d3-ease": "1 - 3", "d3-interpolate": "1 - 3", "d3-timer": "1 - 3" }, "peerDependencies": { "d3-selection": "2 - 3" } }, "sha512-ApKvfjsSR6tg06xrL434C0WydLr7JewBB3V+/39RMHsaXTOG0zmt/OAXeng5M5LBm0ojmxJrpomQVZ1aPvBL4w=="],
+
+ "d3-zoom": ["[email protected]", "", { "dependencies": { "d3-dispatch": "1 - 3", "d3-drag": "2 - 3", "d3-interpolate": "1 - 3", "d3-selection": "2 - 3", "d3-transition": "2 - 3" } }, "sha512-b8AmV3kfQaqWAuacbPuNbL6vahnOJflOhexLzMMNLga62+/nh0JzvJ0aO/5a5MVgUFGS7Hu1P9P03o3fJkDCyw=="],
+
"damerau-levenshtein": ["[email protected]", "", {}, "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA=="],
"data-view-buffer": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", "is-data-view": "^1.0.2" } }, "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ=="],
@@ -1188,6 +1225,8 @@
"use-sidecar": ["[email protected]", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
+ "use-sync-external-store": ["[email protected]", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A=="],
+
"vaul": ["[email protected]", "", { "dependencies": { "@radix-ui/react-dialog": "^1.1.1" }, "peerDependencies": { "react": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-ZFkClGpWyI2WUQjdLJ/BaGuV6AVQiJ3uELGk3OYtP+B6yCO7Cmn9vPFXVJkRaGkOJu3m8bQMgtyzNHixULceQA=="],
"vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.5", "postcss": "^8.5.23", "rolldown": "~1.2.0", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.4.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-pn+CFpM0lwDeKwmOq1ZaBK/9sjorZcgqxki6MbY/jPEVd9vichIlmlD4HmQ5wdP5EgqQCFRaACBxMC7uEGc6lQ=="],
@@ -1218,6 +1257,8 @@
"zod-validation-error": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" } }, "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ=="],
+ "zustand": ["[email protected]", "", { "dependencies": { "use-sync-external-store": "^1.2.2" }, "peerDependencies": { "@types/react": ">=16.8", "immer": ">=9.0.6", "react": ">=16.8" }, "optionalPeers": ["@types/react", "immer", "react"] }, "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw=="],
+
"@babel/code-frame/js-tokens": ["[email protected]", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
"@babel/core/json5": ["[email protected]", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="],
diff --git a/components/shared/graph-canvas.tsx b/components/shared/graph-canvas.tsx
new file mode 100644
index 00000000..037b8985
--- /dev/null
+++ b/components/shared/graph-canvas.tsx
@@ -0,0 +1,103 @@
+"use client";
+
+import { useCallback, useState } from "react";
+import {
+ Background,
+ BackgroundVariant,
+ ControlButton,
+ Controls,
+ MiniMap,
+ ReactFlow,
+ ReactFlowProvider,
+ SelectionMode,
+ useReactFlow,
+ type Edge,
+ type Node,
+ type ReactFlowProps,
+} from "@xyflow/react";
+import { Hand, LayoutGrid, MousePointer2 } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+export type GraphCanvasMode = "select" | "pan";
+
+type GraphCanvasProps<NodeType extends Node = Node, EdgeType extends Edge = Edge> =
+ Omit<ReactFlowProps<NodeType, EdgeType>, "panOnDrag" | "panOnScroll" | "selectionOnDrag" | "selectionMode"> & {
+ ariaLabel: string;
+ initialMode?: GraphCanvasMode;
+ showMinimap?: boolean;
+ onTidy?: () => void;
+ fitPadding?: number;
+ };
+
+export function GraphCanvas<NodeType extends Node = Node, EdgeType extends Edge = Edge>(props: GraphCanvasProps<NodeType, EdgeType>) {
+ return <ReactFlowProvider><GraphCanvasInner {...props} /></ReactFlowProvider>;
+}
+
+function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge = Edge>({
+ ariaLabel,
+ initialMode = "select",
+ showMinimap = true,
+ onTidy,
+ fitPadding = 0.22,
+ className,
+ children,
+ fitViewOptions,
+ onKeyDown,
+ ...props
+}: GraphCanvasProps<NodeType, EdgeType>) {
+ const [mode, setMode] = useState<GraphCanvasMode>(initialMode);
+ const { fitView } = useReactFlow<NodeType, EdgeType>();
+ const fit = useCallback(() => void fitView({ padding: fitPadding, duration: 220, ...fitViewOptions }), [fitPadding, fitView, fitViewOptions]);
+ const tidy = useCallback(() => {
+ onTidy?.();
+ requestAnimationFrame(() => requestAnimationFrame(fit));
+ }, [fit, onTidy]);
+
+ const keyboard = (event: React.KeyboardEvent<HTMLDivElement>) => {
+ onKeyDown?.(event);
+ if (event.defaultPrevented) return;
+ const target = event.target as HTMLElement;
+ if (target.closest("input,textarea,select,[contenteditable='true']")) return;
+ const key = event.key.toLowerCase();
+ if (key === "v") { event.preventDefault(); setMode("select"); }
+ if (key === "h") { event.preventDefault(); setMode("pan"); }
+ if (key === "f") { event.preventDefault(); fit(); }
+ };
+
+ return (
+ <div className="h-full w-full outline-none" tabIndex={0} onKeyDown={keyboard}>
+ <ReactFlow<NodeType, EdgeType>
+ {...props}
+ aria-label={ariaLabel}
+ className={cn("mso-graph-flow h-full w-full", className)}
+ fitView
+ fitViewOptions={{ padding: fitPadding, duration: 220, ...fitViewOptions }}
+ minZoom={props.minZoom ?? 0.18}
+ maxZoom={props.maxZoom ?? 2.5}
+ selectionMode={SelectionMode.Partial}
+ selectionOnDrag={mode === "select"}
+ panOnDrag={mode === "pan" ? true : [1, 2]}
+ panOnScroll={mode === "select"}
+ zoomOnScroll={mode === "pan"}
+ zoomOnPinch
+ zoomActivationKeyCode={["Meta", "Control"]}
+ panActivationKeyCode="Space"
+ multiSelectionKeyCode={["Meta", "Control"]}
+ preventScrolling
+ >
+ <Background variant={BackgroundVariant.Dots} gap={20} size={1.25} color="var(--sep-strong)" />
+ <Controls position="bottom-left" showInteractive={false} fitViewOptions={{ padding: fitPadding, duration: 220 }}>
+ <ControlButton aria-label="Select mode" title="Select (V)" onClick={() => setMode("select")} className={mode === "select" ? "is-active" : undefined}>
+ <MousePointer2 aria-hidden />
+ </ControlButton>
+ <ControlButton aria-label="Pan mode" title="Pan (H or hold Space)" onClick={() => setMode("pan")} className={mode === "pan" ? "is-active" : undefined}>
+ <Hand aria-hidden />
+ </ControlButton>
+ {onTidy ? <ControlButton aria-label="Tidy up" title="Tidy up" onClick={tidy}><LayoutGrid aria-hidden /></ControlButton> : null}
+ </Controls>
+ {showMinimap ? <MiniMap pannable zoomable position="bottom-right" ariaLabel={`${ariaLabel} minimap`} /> : null}
+ {children}
+ </ReactFlow>
+ </div>
+ );
+}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index f0c17494..0369a165 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `canvas` unify organization and workflow navigation
- `organization` surface as first-class app
- `organization` add agent org chart and routing
- `workflows` complete server-native automation parity
diff --git a/frontend/slices/organization/components/organization-canvas.tsx b/frontend/slices/organization/components/organization-canvas.tsx
new file mode 100644
index 00000000..261366ee
--- /dev/null
+++ b/frontend/slices/organization/components/organization-canvas.tsx
@@ -0,0 +1,73 @@
+"use client";
+
+import { useMemo } from "react";
+import { Building2 } from "lucide-react";
+import type { Edge, Node, NodeProps } from "@xyflow/react";
+import type { OrganizationChart, OrganizationSeat, OrganizationSeatRuntime, OrganizationUnit } from "@/lib/contracts/organization";
+import { Badge } from "@/components/ui/badge";
+import { GraphCanvas } from "@/components/shared/graph-canvas";
+import { cn } from "@/lib/utils";
+import { organizationSeatLayout, organizationUnitLayout } from "../lib/canvas-layout";
+
+interface UnitData extends Record<string, unknown> { unit: OrganizationUnit; seatCount: number }
+interface SeatData extends Record<string, unknown> { seat: OrganizationSeat; runtime?: OrganizationSeatRuntime; unitName: string; external: boolean }
+type UnitNode = Node<UnitData, "unit">;
+type SeatNode = Node<SeatData, "seat">;
+type OrganizationNode = UnitNode | SeatNode;
+
+const statusClass: Record<OrganizationSeatRuntime["status"], string> = {
+ ready: "bg-success", busy: "bg-warning", offline: "bg-muted-foreground", unresolved: "bg-destructive", unbound: "bg-info", vacant: "bg-border",
+};
+
+function UnitCard({ data, selected }: NodeProps<UnitNode>) {
+ return <div className={cn("w-[230px] rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring")}>
+ <div className="flex items-start gap-2"><Building2 className="mt-0.5 size-4 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1"><div className="truncate text-sm font-semibold">{data.unit.name}</div><div className="mt-0.5 text-[10px] text-muted-foreground">{data.unit.description || data.unit.kind}</div></div></div>
+ <div className="mt-2 flex gap-1"><Badge variant="secondary" className="text-[9px]">{data.unit.kind}</Badge><Badge variant="outline" className="text-[9px]">{data.seatCount} seats</Badge></div>
+ </div>;
+}
+function SeatCard({ data, selected }: NodeProps<SeatNode>) {
+ const status = data.runtime?.status ?? "vacant";
+ return <div className={cn("w-[238px] rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring", data.external && "opacity-75")}>
+ <div className="flex items-start gap-2"><span className={cn("mt-1 size-2.5 shrink-0 rounded-full", statusClass[status])}/><div className="min-w-0 flex-1"><div className="text-xs font-semibold leading-tight">{data.seat.title}</div><div className="mt-0.5 truncate text-[10px] text-muted-foreground">{data.seat.name}</div></div></div>
+ <div className="mt-2 flex flex-wrap gap-1"><Badge variant="secondary" className="text-[9px]">{data.seat.role}</Badge><Badge variant="outline" className="max-w-[140px] truncate text-[9px]">{data.unitName}</Badge>{data.external?<Badge variant="outline" className="text-[9px]">reporting parent</Badge>:null}</div>
+ </div>;
+}
+const nodeTypes = { unit: UnitCard, seat: SeatCard };
+
+export function OrganizationCanvas({ chart, runtime, unitId, selectedSeatId, onUnitSelect, onSeatSelect, onSeatOpen }: {
+ chart: OrganizationChart;
+ runtime: OrganizationSeatRuntime[];
+ unitId: string;
+ selectedSeatId: string | null;
+ onUnitSelect: (id: string) => void;
+ onSeatSelect: (seat: OrganizationSeat | null) => void;
+ onSeatOpen: (seat: OrganizationSeat) => void;
+}) {
+ const runtimeById = useMemo(() => new Map(runtime.map((row) => [row.seatId, row])), [runtime]);
+ const unitById = useMemo(() => new Map(chart.units.map((unit) => [unit.id, unit])), [chart.units]);
+ const nodes = useMemo<OrganizationNode[]>(() => {
+ if (!unitId) return organizationUnitLayout(chart).map(({ item, position }) => ({ id: item.id, type: "unit", position, data: { unit: item, seatCount: chart.seats.filter((seat) => seat.unitId === item.id).length } }));
+ return organizationSeatLayout(chart, unitId).map(({ item, position, external }) => ({ id: item.id, type: "seat", position, selected: item.id === selectedSeatId, data: { seat: item, runtime: runtimeById.get(item.id), unitName: unitById.get(item.unitId)?.name ?? item.unitId, external } }));
+ }, [chart, runtimeById, selectedSeatId, unitById, unitId]);
+ const visible = useMemo(() => new Set(nodes.map((node) => node.id)), [nodes]);
+ const edges = useMemo<Edge[]>(() => {
+ if (!unitId) return chart.units.filter((unit) => unit.parentUnitId && visible.has(unit.parentUnitId)).map((unit) => ({ id: `unit-${unit.parentUnitId}-${unit.id}`, source: unit.parentUnitId!, target: unit.id, type: "smoothstep" }));
+ return chart.seats.filter((seat) => visible.has(seat.id) && seat.reportsToSeatId && visible.has(seat.reportsToSeatId)).map((seat) => ({ id: `seat-${seat.reportsToSeatId}-${seat.id}`, source: seat.reportsToSeatId!, target: seat.id, type: "smoothstep" }));
+ }, [chart.seats, chart.units, unitId, visible]);
+
+ return <GraphCanvas<OrganizationNode, Edge>
+ key={unitId || "unit-overview"}
+ ariaLabel={unitId ? "Organization seats canvas" : "Organization units canvas"}
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ edgesFocusable={false}
+ deleteKeyCode={null}
+ onPaneClick={() => onSeatSelect(null)}
+ onNodeClick={(_, 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={0.28}
+ />;
+}
diff --git a/frontend/slices/organization/components/organization-tree.tsx b/frontend/slices/organization/components/organization-tree.tsx
deleted file mode 100644
index 1943853b..00000000
--- a/frontend/slices/organization/components/organization-tree.tsx
+++ /dev/null
@@ -1,27 +0,0 @@
-"use client";
-import { Badge } from "@/components/ui/badge";
-import { Button } from "@/components/ui/button";
-import { cn } from "@/lib/utils";
-import type { OrganizationChart, OrganizationSeat, OrganizationSeatRuntime } from "@/lib/contracts/organization";
-
-type Props = { chart: OrganizationChart; runtime: OrganizationSeatRuntime[]; unitId: string; onEdit: (seat: OrganizationSeat) => void };
-const statusClass: Record<OrganizationSeatRuntime["status"], string> = { ready: "bg-emerald-500", busy: "bg-amber-500", offline: "bg-muted-foreground", unresolved: "bg-destructive", unbound: "bg-sky-500", vacant: "bg-border" };
-export function OrganizationTree({ chart, runtime, unitId, onEdit }: Props) {
- const seats = chart.seats.filter((seat) => !unitId || seat.unitId === unitId).sort((a, b) => a.sortOrder - b.sortOrder || a.title.localeCompare(b.title));
- const ids = new Set(seats.map((seat) => seat.id)), roots = seats.filter((seat) => !seat.reportsToSeatId || !ids.has(seat.reportsToSeatId));
- const byParent = new Map<string, OrganizationSeat[]>(); for (const seat of seats) if (seat.reportsToSeatId && ids.has(seat.reportsToSeatId)) byParent.set(seat.reportsToSeatId, [...(byParent.get(seat.reportsToSeatId) ?? []), seat]);
- const runtimeById = new Map(runtime.map((row) => [row.seatId, row])), unitById = new Map(chart.units.map((row) => [row.id, row]));
- if (!seats.length) return <div className="grid min-h-64 place-items-center rounded-xl border border-dashed text-sm text-muted-foreground">No seats in this unit yet.</div>;
- return <div className="min-w-max p-4"><div className="flex items-start justify-center gap-8">{roots.map((seat) => <Branch key={seat.id} seat={seat} childrenByParent={byParent} runtimeById={runtimeById} unitById={unitById} onEdit={onEdit} />)}</div></div>;
-}
-function Branch({ seat, childrenByParent, runtimeById, unitById, onEdit }: { seat: OrganizationSeat; childrenByParent: Map<string, OrganizationSeat[]>; runtimeById: Map<string, OrganizationSeatRuntime>; unitById: Map<string, { name: string }>; onEdit: (seat: OrganizationSeat) => void }) {
- const children = (childrenByParent.get(seat.id) ?? []).sort((a, b) => a.sortOrder - b.sortOrder || a.title.localeCompare(b.title)), state = runtimeById.get(seat.id);
- return <div className="flex min-w-[220px] flex-col items-center">
- <Button variant="ghost" className="h-auto w-[220px] whitespace-normal rounded-xl border bg-card p-0 text-left shadow-sm hover:bg-accent" onClick={() => onEdit(seat)}>
- <div className="w-full p-3"><div className="flex items-start gap-2"><span className={cn("mt-1 size-2.5 shrink-0 rounded-full", statusClass[state?.status ?? "vacant"])} /><div className="min-w-0 flex-1"><div className="font-semibold leading-tight">{seat.title}</div><div className="mt-0.5 text-[11px] text-muted-foreground">{seat.name}</div></div></div>
- <div className="mt-2 flex flex-wrap gap-1"><Badge variant="secondary" className="text-[9px]">{seat.role}</Badge><Badge variant="outline" className="text-[9px]">{unitById.get(seat.unitId)?.name ?? seat.unitId}</Badge><Badge variant="outline" className="text-[9px]">{seat.seatMode}</Badge>{seat.target.kind !== "none" ? <Badge variant="outline" className="max-w-[180px] truncate text-[9px]">{state?.label ?? seat.target.kind}</Badge> : null}</div>
- </div>
- </Button>
- {children.length ? <><div className="h-5 w-px bg-border"/><div className="relative flex items-start gap-4 pt-5 before:absolute before:left-[calc(50%-((100%-220px)/2))] before:right-[calc(50%-((100%-220px)/2))] before:top-0 before:h-px before:bg-border">{children.map((child) => <div key={child.id} className="relative before:absolute before:left-1/2 before:top-[-20px] before:h-5 before:w-px before:bg-border"><Branch seat={child} childrenByParent={childrenByParent} runtimeById={runtimeById} unitById={unitById} onEdit={onEdit}/></div>)}</div></> : null}
- </div>;
-}
diff --git a/frontend/slices/organization/components/organization-view.tsx b/frontend/slices/organization/components/organization-view.tsx
index 081c6c20..bb363d9d 100644
--- a/frontend/slices/organization/components/organization-view.tsx
+++ b/frontend/slices/organization/components/organization-view.tsx
@@ -1,34 +1,106 @@
"use client";
-import { useCallback, useEffect, useState } from "react";
-import { Building2, Plus, RefreshCw, Users } from "lucide-react";
+
+import { useCallback, useEffect, useMemo, useState } from "react";
+import { ArrowLeft, Building2, Pencil, Plus, RefreshCw, Users, X } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
-import { ScrollArea } from "@/components/ui/scroll-area";
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 { OrganizationTree } from "./organization-tree";
type Draft = { kind: "unit"; item?: OrganizationUnit } | { kind: "seat"; item?: OrganizationSeat } | null;
+
export function OrganizationView() {
- const [data, setData] = useState<OrganizationPayload | null>(null), [selected, setSelected] = useState("__all__"), [draft, setDraft] = useState<Draft>(null), [error, setError] = useState("");
- const load = useCallback(async () => { try { const next = await getOrganization(); setData(next); setSelected((current) => current === "__all__" || next.chart.units.some((u)=>u.id===current) ? current : "__all__"); setError(""); } catch (e) { setError(e instanceof Error ? e.message : "Organization unavailable"); } }, []);
+ const [data, setData] = useState<OrganizationPayload | null>(null);
+ const [selectedUnit, setSelectedUnit] = useState("__all__");
+ const [selectedSeatId, setSelectedSeatId] = useState<string | null>(null);
+ const [draft, setDraft] = useState<Draft>(null);
+ const [error, setError] = useState("");
+
+ const load = useCallback(async () => {
+ try {
+ const next = await getOrganization();
+ setData(next);
+ setSelectedUnit((current) => current === "__all__" || next.chart.units.some((unit) => unit.id === current) ? current : "__all__");
+ setSelectedSeatId((current) => current && next.chart.seats.some((seat) => seat.id === current) ? current : null);
+ setError("");
+ } catch (cause) {
+ setError(cause instanceof Error ? cause.message : "Organization unavailable");
+ }
+ }, []);
+
useEffect(() => {
let alive = true;
void getOrganization().then((next) => {
if (!alive) return;
- setData(next); setSelected((current) => current === "__all__" || next.chart.units.some((u) => u.id === current) ? current : "__all__"); setError("");
- }).catch((e: unknown) => { if (alive) setError(e instanceof Error ? e.message : "Organization unavailable"); });
+ setData(next);
+ setSelectedUnit((current) => current === "__all__" || next.chart.units.some((unit) => unit.id === current) ? current : "__all__");
+ setSelectedSeatId((current) => current && next.chart.seats.some((seat) => seat.id === current) ? current : null);
+ setError("");
+ }).catch((cause: unknown) => { if (alive) setError(cause instanceof Error ? cause.message : "Organization unavailable"); });
return () => { alive = false; };
}, []);
- const current = data?.chart.units.find((u) => u.id === selected);
- const mutate = async (action: string, record: Record<string, unknown>) => { if (!data) return; const key = action.startsWith("unit_") ? "unit" : "seat", next = await mutateOrganization({ action, expected_revision: data.chart.revision, [key]: record }); setData(next); };
- const remove = async (kind: "unit"|"seat", id: string) => { if (!data) return; const next = await mutateOrganization({ action: `${kind}_delete`, expected_revision: data.chart.revision, id }); setData(next); setDraft(null); if (kind === "unit" && id === selected) setSelected("__all__"); };
+
+ const currentUnit = data?.chart.units.find((unit) => unit.id === selectedUnit);
+ const selectedSeat = data?.chart.seats.find((seat) => seat.id === selectedSeatId) ?? null;
+ const selectedRuntime = data?.runtime.find((row) => row.seatId === selectedSeatId);
+ const units = useMemo(() => data?.chart.units.slice().sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name)) ?? [], [data]);
+
+ const save = async (action: string, record: Record<string, unknown>) => {
+ if (!data) return;
+ const key = action.startsWith("unit_") ? "unit" : "seat";
+ const next = await mutateOrganization({ action, expected_revision: data.chart.revision, [key]: record });
+ setData(next);
+ if (key === "seat" && typeof record.id === "string") setSelectedSeatId(record.id);
+ };
+ const remove = async (kind: "unit" | "seat", id: string) => {
+ if (!data) return;
+ const next = await mutateOrganization({ action: `${kind}_delete`, expected_revision: data.chart.revision, id });
+ setData(next); setDraft(null);
+ if (kind === "unit" && id === selectedUnit) setSelectedUnit("__all__");
+ if (kind === "seat" && id === selectedSeatId) setSelectedSeatId(null);
+ };
+ const chooseUnit = (id: string) => { setSelectedUnit(id); setSelectedSeatId(null); };
+
if (!data) return <div className="grid h-full place-items-center p-6 text-sm text-muted-foreground">{error || "Loading organization…"}</div>;
- return <div className="grid h-full min-h-0 grid-cols-1 overflow-hidden lg:grid-cols-[240px_minmax(0,1fr)]">
- <aside className="flex min-h-0 flex-col border-b bg-card/20 lg:border-b-0 lg:border-r"><div className="flex items-center gap-2 p-3"><div><div className="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="ml-auto" onClick={()=>void load()}><RefreshCw className="size-3.5"/></Button><Button size="icon" onClick={()=>setDraft({kind:"unit"})}><Plus className="size-3.5"/></Button></div><ScrollArea className="max-h-40 flex-1 lg:max-h-none"><div className="space-y-1 p-2"><button className={`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm ${selected==="__all__"?"bg-accent font-medium":"hover:bg-accent/60"}`} onClick={()=>setSelected("__all__")}><Users className="size-4 shrink-0"/><span className="min-w-0 flex-1 truncate">All organization</span><Badge variant="outline" className="text-[9px]">{data.chart.seats.length}</Badge></button>{data.chart.units.slice().sort((a,b)=>a.sortOrder-b.sortOrder||a.name.localeCompare(b.name)).map((unit)=><button key={unit.id} className={`flex w-full items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm ${unit.id===selected?"bg-accent font-medium":"hover:bg-accent/60"}`} onClick={()=>setSelected(unit.id)}><Building2 className="size-4 shrink-0"/><span className="min-w-0 flex-1 truncate">{unit.name}</span><Badge variant="outline" className="text-[9px]">{data.chart.seats.filter((s)=>s.unitId===unit.id).length}</Badge></button>)}</div></ScrollArea></aside>
- <section className="flex min-h-0 min-w-0 flex-col"><div className="flex flex-wrap items-center gap-2 border-b px-4 py-3"><div className="min-w-0"><div className="flex items-center gap-2"><h2 className="truncate font-semibold">{current?.name ?? data.chart.name}</h2>{current?<Badge variant="secondary">{current.kind}</Badge>:null}</div><p className="text-xs text-muted-foreground">{current?.description || (selected==="__all__"?"Complete reporting hierarchy across every organization unit.":"Choose or create an organization unit.")}</p></div><div className="ml-auto flex gap-2">{current?<Button size="sm" variant="outline" onClick={()=>setDraft({kind:"unit",item:current})}>Edit unit</Button>:null}{current?<Button size="sm" onClick={()=>setDraft({kind:"seat"})}><Users className="mr-1 size-3.5"/>Add seat</Button>:null}</div></div>
- {error?<div className="border-b bg-destructive/10 px-4 py-2 text-xs text-destructive">{error}</div>:null}<ScrollArea className="flex-1"><div className="min-h-full min-w-full overflow-auto">{selected==="__all__"||current?<OrganizationTree chart={data.chart} runtime={data.runtime} unitId={current?.id??""} onEdit={(seat)=>setDraft({kind:"seat",item:seat})}/>:<div className="grid min-h-64 place-items-center text-sm text-muted-foreground">Create the first organization unit.</div>}</div></ScrollArea><div className="border-t px-4 py-2 text-[10px] text-muted-foreground">Seat status resolves existing project agents, durable local sessions, or registered A2A peers. Org metadata grants no extra capability.</div>
- </section><OrganizationEditor draft={draft} chart={data.chart} onClose={()=>setDraft(null)} onSave={mutate} onDelete={remove}/>
- </div>;
+
+ return (
+ <div className="grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] overflow-hidden lg:grid-cols-[220px_minmax(0,1fr)] lg:grid-rows-1">
+ <aside className="border-b bg-card/20 lg:flex lg:min-h-0 lg:flex-col lg:border-b-0 lg:border-r">
+ <div className="flex items-center gap-2 p-3">
+ <div className="min-w-0"><div className="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="ml-auto" onClick={() => void load()} aria-label="Refresh organization"><RefreshCw className="size-3.5"/></Button>
+ <Button size="icon" onClick={() => setDraft({ kind: "unit" })} aria-label="New organization unit"><Plus className="size-3.5"/></Button>
+ </div>
+ <div className="flex gap-1 overflow-x-auto px-2 pb-2 lg:block lg:flex-1 lg:space-y-1 lg:overflow-y-auto">
+ <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)}/>) }
+ </div>
+ </aside>
+
+ <section className="flex min-h-0 min-w-0 flex-col">
+ <div className="flex min-h-12 flex-wrap items-center gap-2 border-b px-3 py-2">
+ {currentUnit ? <Button size="icon" variant="ghost" onClick={() => chooseUnit("__all__")} aria-label="Back to organization overview"><ArrowLeft className="size-4"/></Button> : null}
+ <div className="min-w-0"><div className="flex items-center gap-2"><h2 className="truncate text-sm font-semibold">{currentUnit?.name ?? data.chart.name}</h2>{currentUnit ? <Badge variant="secondary">{currentUnit.kind}</Badge> : <Badge variant="outline">overview</Badge>}</div><p className="max-w-2xl truncate text-[11px] text-muted-foreground">{currentUnit?.description || "Open a unit to inspect its reporting graph. Pan, zoom, fit, and use the minimap like a workflow canvas."}</p></div>
+ <div className="ml-auto flex gap-1">{currentUnit ? <Button size="sm" variant="outline" onClick={() => setDraft({ kind: "unit", item: currentUnit })}><Pencil className="mr-1 size-3"/>Unit</Button> : null}{currentUnit ? <Button size="sm" onClick={() => setDraft({ kind: "seat" })}><Users className="mr-1 size-3"/>Seat</Button> : null}</div>
+ </div>
+ {error ? <div className="border-b bg-destructive/10 px-4 py-2 text-xs text-destructive">{error}</div> : null}
+ <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}
+ </div>
+ <div className="border-t px-3 py-1.5 text-[10px] text-muted-foreground">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 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 shrink-0 items-center gap-2 rounded-lg px-2.5 py-2 text-left text-sm lg:w-full ${active ? "bg-accent font-medium" : "hover:bg-accent/60"}`}>{icon}<span className="max-w-40 truncate lg:min-w-0 lg:flex-1">{label}</span><Badge variant="outline" className="text-[9px]">{count}</Badge></button>;
+}
+
+function SeatInspector({ seat, runtimeLabel, runtimeStatus, onClose, onEdit }: { seat: OrganizationSeat; runtimeLabel?: string; runtimeStatus?: string; onClose: () => void; onEdit: () => void }) {
+ return <div className="absolute right-3 top-3 z-10 w-[min(19rem,calc(100%-1.5rem))] rounded-xl border bg-popover/95 p-3 shadow-lg backdrop-blur"><div className="flex items-start gap-2"><div className="min-w-0 flex-1"><div className="text-xs font-semibold">{seat.title}</div><div className="mt-0.5 truncate text-[11px] text-muted-foreground">{seat.name}</div></div><Button size="icon" variant="ghost" className="size-7" onClick={onClose} aria-label="Close seat details"><X className="size-3.5"/></Button></div><div className="mt-2 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]">{runtimeStatus ?? seat.state}</Badge></div>{seat.description ? <p className="mt-2 text-[11px] text-muted-foreground">{seat.description}</p> : null}{runtimeLabel ? <p className="mt-2 truncate text-[10px] text-muted-foreground">Target: {runtimeLabel}</p> : null}<Button size="sm" className="mt-3 w-full" onClick={onEdit}><Pencil className="mr-1 size-3"/>Edit seat</Button></div>;
}
diff --git a/frontend/slices/organization/lib/canvas-layout.test.ts b/frontend/slices/organization/lib/canvas-layout.test.ts
new file mode 100644
index 00000000..0cfd4445
--- /dev/null
+++ b/frontend/slices/organization/lib/canvas-layout.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import type { OrganizationChart, OrganizationSeat, OrganizationUnit } from "@/lib/contracts/organization";
+import { organizationSeatLayout, organizationUnitLayout } from "./canvas-layout";
+
+const stamp = "2026-01-01T00:00:00Z";
+const unit = (id: string, parentUnitId?: string): OrganizationUnit => ({ id, key: id, name: id, kind: parentUnitId ? "company" : "holding", status: "active", parentUnitId, sortOrder: 0, createdAt: stamp, updatedAt: stamp });
+const seat = (id: string, unitId: string, reportsToSeatId?: string): OrganizationSeat => ({ id, unitId, name: id, title: id, role: "ceo", state: "active", seatMode: "permanent", reportsToSeatId, responsibilities: [], target: { kind: "none" }, sortOrder: 0, createdAt: stamp, updatedAt: stamp });
+const chart = (units: OrganizationUnit[], seats: OrganizationSeat[]): OrganizationChart => ({ version: 1, name: "Org", revision: "r", updatedAt: stamp, units, seats });
+
+describe("organization canvas layout", () => {
+ it("places child organization units below their parent", () => {
+ const rows = organizationUnitLayout(chart([unit("holding"), unit("business", "holding")], []));
+ const byId = new Map(rows.map((row) => [row.item.id, row.position]));
+ expect(byId.get("business")!.y).toBeGreaterThan(byId.get("holding")!.y);
+ });
+
+ it("includes an external reporting parent when a subsidiary seat reports outside its unit", () => {
+ const rows = organizationSeatLayout(chart([unit("holding"), unit("subsidiary", "holding")], [seat("holding-ceo", "holding"), seat("subsidiary-ceo", "subsidiary", "holding-ceo")]), "subsidiary");
+ expect(rows.map((row) => [row.item.id, row.external])).toEqual(expect.arrayContaining([["holding-ceo", true], ["subsidiary-ceo", false]]));
+ const byId = new Map(rows.map((row) => [row.item.id, row.position]));
+ expect(byId.get("subsidiary-ceo")!.y).toBeGreaterThan(byId.get("holding-ceo")!.y);
+ });
+});
diff --git a/frontend/slices/organization/lib/canvas-layout.ts b/frontend/slices/organization/lib/canvas-layout.ts
new file mode 100644
index 00000000..4a4d0316
--- /dev/null
+++ b/frontend/slices/organization/lib/canvas-layout.ts
@@ -0,0 +1,47 @@
+import type { OrganizationChart, OrganizationSeat, OrganizationUnit } from "@/lib/contracts/organization";
+
+type Positioned<T> = { item: T; position: { x: number; y: number } };
+const X_GAP = 270;
+const Y_GAP = 176;
+
+function layered<T extends { id: string }>(items: T[], parentId: (item: T) => string | undefined): Positioned<T>[] {
+ const ids = new Set(items.map((item) => item.id));
+ const depth = new Map<string, number>();
+ const resolve = (item: T, trail = new Set<string>()): number => {
+ if (depth.has(item.id)) return depth.get(item.id)!;
+ if (trail.has(item.id)) return 0;
+ const parent = parentId(item);
+ if (!parent || !ids.has(parent)) { depth.set(item.id, 0); return 0; }
+ const nextTrail = new Set(trail).add(item.id);
+ const parentItem = items.find((row) => row.id === parent);
+ const value = parentItem ? resolve(parentItem, nextTrail) + 1 : 0;
+ depth.set(item.id, value);
+ return value;
+ };
+ for (const item of items) resolve(item);
+ const rows = new Map<number, T[]>();
+ for (const item of items) rows.set(depth.get(item.id)!, [...(rows.get(depth.get(item.id)!) ?? []), item]);
+ for (const row of rows.values()) row.sort((a, b) => a.id.localeCompare(b.id));
+ const widest = Math.max(1, ...[...rows.values()].map((row) => row.length));
+ return items.map((item) => {
+ const level = depth.get(item.id)!;
+ const row = rows.get(level)!;
+ const index = row.findIndex((entry) => entry.id === item.id);
+ const span = (row.length - 1) * X_GAP;
+ const globalSpan = (widest - 1) * X_GAP;
+ return { item, position: { x: (globalSpan - span) / 2 + index * X_GAP + 80, y: 70 + level * Y_GAP } };
+ });
+}
+
+export function organizationUnitLayout(chart: OrganizationChart): Positioned<OrganizationUnit>[] {
+ return layered(chart.units.slice().sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name)), (unit) => unit.parentUnitId);
+}
+
+export function organizationSeatLayout(chart: OrganizationChart, unitId: string): Array<Positioned<OrganizationSeat> & { external: boolean }> {
+ const local = chart.seats.filter((seat) => seat.unitId === unitId);
+ const localIds = new Set(local.map((seat) => seat.id));
+ const outsideParentIds = new Set(local.map((seat) => seat.reportsToSeatId).filter((id): id is string => Boolean(id && !localIds.has(id))));
+ const external = chart.seats.filter((seat) => outsideParentIds.has(seat.id));
+ const items = [...external, ...local].sort((a, b) => a.sortOrder - b.sortOrder || a.title.localeCompare(b.title));
+ return layered(items, (seat) => seat.reportsToSeatId).map((entry) => ({ ...entry, external: !localIds.has(entry.item.id) }));
+}
diff --git a/frontend/slices/workflows/app.tsx b/frontend/slices/workflows/app.tsx
index 89f583d6..ceb7b2c0 100644
--- a/frontend/slices/workflows/app.tsx
+++ b/frontend/slices/workflows/app.tsx
@@ -1,54 +1,63 @@
"use client";
+
import { useEffect, useMemo, useState } from "react";
-import { Copy, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
+import { Copy, PanelLeft, PanelRight, Play, RefreshCw, Save, Trash2, Workflow } from "lucide-react";
import type { AppProps } from "@/features/appshell";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeType, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
-import { AppFrame, openWindow } from "@/features/appshell";
+import { AppFrame, ResponsiveDialog, openWindow, useResponsive } from "@/features/appshell";
+import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
-import { ScrollArea } from "@/components/ui/scroll-area";
-import { Badge } from "@/components/ui/badge";
import { WorkflowCanvas } from "./components/workflow-canvas";
import { WorkflowCreateDialog } from "./components/workflow-create-dialog";
-import { WorkflowInspector } from "./components/workflow-inspector";
+import { WorkflowDetails, type WorkflowPanel } from "./components/workflow-details";
+import { WorkflowLibrary } from "./components/workflow-library";
import { WorkflowNodePalette } from "./components/workflow-node-palette";
-import { WorkflowRunHistory } from "./components/workflow-run-history";
-import { WorkflowRunPanel } from "./components/workflow-run-panel";
-import { WorkflowVariablePanel } from "./components/workflow-variable-panel";
-import { WorkflowVersionPanel } from "./components/workflow-version-panel";
+import { tidyWorkflowNodes } from "./lib/canvas-layout";
import { cloneGraph, createFromTemplate, createGraph, deleteGraph, getGraph, listGraphs, resolveNode, runGraph, runStatus, updateGraph } from "./lib/api";
-type Definition=Omit<WorkflowGraph,"version"|"id"|"revision"|"createdAt"|"updatedAt">;
-type Panel="inspector"|"run"|"history"|"versions"|"variables";
-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"}]};}
-export default function WorkflowsApp(_props:AppProps){
- const[graphs,setGraphs]=useState<WorkflowGraph[]>([]),[graph,setGraph]=useState<WorkflowGraph|null>(null),[selected,setSelected]=useState<string|null>(null),[run,setRun]=useState<WorkflowGraphRun|null>(null),[busy,setBusy]=useState(false),[dirty,setDirty]=useState(false),[message,setMessage]=useState(""),[panel,setPanel]=useState<Panel>("inspector"),[search,setSearch]=useState("");
- const node=useMemo(()=>graph?.nodes.find((item)=>item.id===selected)??null,[graph,selected]),runStates=useMemo(()=>new Map(run?.nodes.map((item)=>[item.id,item.state])??[]),[run]),filtered=useMemo(()=>{const q=search.toLowerCase().trim();return graphs.filter((item)=>!q||`${item.name} ${item.metadata.folder??""} ${(item.metadata.tags??[]).join(" ")}`.toLowerCase().includes(q));},[graphs,search]);
- const load=async(selectId?:string)=>{const list=await listGraphs();setGraphs(list);const id=selectId??graph?.id??list[0]?.id;if(id){setGraph(await getGraph(id));setDirty(false);}else{setGraph(null);setDirty(false);}};
- useEffect(()=>{let cancelled=false;void listGraphs().then(async(list)=>{if(cancelled)return;setGraphs(list);if(list[0]){const first=await getGraph(list[0].id);if(!cancelled)setGraph(first);}}).catch((error:unknown)=>{if(!cancelled)setMessage(error instanceof Error?error.message:"Could not load workflows");});return()=>{cancelled=true;};},[]);
- useEffect(()=>{if(!run||run.state!=="running")return;const timer=setInterval(()=>{void runStatus(run.id).then(setRun).catch(()=>undefined);},1600);return()=>clearInterval(timer);},[run]);
- const wrap=async(fn:()=>Promise<void>)=>{setBusy(true);setMessage("");try{await fn();}catch(error){setMessage(error instanceof Error?error.message:"Action failed");}finally{setBusy(false);}};
- const mutate=(next:WorkflowGraph)=>{setGraph(next);setDirty(true);};
- const selectGraph=async(id:string)=>{setGraph(await getGraph(id));setSelected(null);setRun(null);setDirty(false);setPanel("inspector");};
- const createBlank=()=>wrap(async()=>{const next=await createGraph(starterGraph());await load(next.id);setSelected("manual");});
- const createTemplate=(id:string)=>wrap(async()=>{const next=await createFromTemplate(id);await load(next.id);setSelected(next.nodes[0]?.id??null);});
- const createAI=(definition:Definition)=>wrap(async()=>{const next=await createGraph(definition);await load(next.id);setSelected(next.nodes[0]?.id??null);});
- 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 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(),receipt=await runGraph(saved.id);setRun(receipt);setPanel("run");});
- const updateNode=(next:WorkflowGraphNode)=>graph&&mutate({...graph,nodes:graph.nodes.map((item)=>item.id===next.id?next:item)});
- const deleteNode=(id:string)=>{if(!graph)return;mutate({...graph,nodes:graph.nodes.filter((item)=>item.id!==id),edges:graph.edges.filter((edge)=>edge.source!==id&&edge.target!==id)});setSelected(null);};
- const addNode=(type:WorkflowGraphNodeType,defaults:Record<string,unknown>)=>{if(!graph)return;const id=`${type}-${crypto.randomUUID().slice(0,8)}`,next:WorkflowGraphNode={id,name:type.replaceAll("_"," ").replace(/\b\w/g,(c)=>c.toUpperCase()),type,position:{x:220+graph.nodes.length*36,y:240+(graph.nodes.length%4)*110},config:structuredClone(defaults)};mutate({...graph,nodes:[...graph.nodes,next]});setSelected(id);setPanel("inspector");};
- const connect=(source:string,target:string,sourceHandle?:string)=>{if(!graph||graph.edges.some((edge)=>edge.source===source&&edge.target===target&&edge.sourceHandle===sourceHandle))return;mutate({...graph,edges:[...graph.edges,{id:`edge-${crypto.randomUUID().slice(0,8)}`,source,target,...(sourceHandle?{sourceHandle}:{})}]});};
- const openNode=async(id:string)=>{if(!graph)return;const resolved=await resolveNode(graph.id,id);openWindow("files-manager",resolved.name,undefined,{path:resolved.path},{multi:true});};
- const panelButton=(value:Panel,label:string)=><button type="button" className={`min-w-0 flex-1 px-1 text-[10px] ${panel===value?"font-semibold text-foreground":"text-muted-foreground"}`} onClick={()=>setPanel(value)}>{label}</button>;
- return <AppFrame safeArea={false} className="h-full" toolbar={<div className="flex h-11 items-center gap-2 border-b px-3"><Workflow className="size-4"/><span className="text-sm font-semibold">Workflows</span>{dirty&&<Badge variant="outline">Unsaved</Badge>}{graph&&<Input className="h-8 max-w-56" value={graph.name} onChange={(e)=>mutate({...graph,name:e.target.value})}/>}<div className="ml-auto flex items-center gap-1"><Button size="sm" variant="ghost" onClick={()=>void load()} disabled={busy}><RefreshCw className="size-3"/></Button><WorkflowCreateDialog onBlank={async()=>{await createBlank();}} onTemplate={async(id)=>{await createTemplate(id);}} onAI={async(definition)=>{await createAI(definition);}}/>{graph&&<><Button size="sm" variant="outline" onClick={()=>void duplicate()} disabled={busy}><Copy className="size-3"/></Button><Button size="sm" variant="outline" onClick={()=>void save()} disabled={busy||!dirty}><Save className="mr-1 size-3"/>Save</Button><Button size="sm" onClick={()=>void execute()} disabled={busy}><Play className="mr-1 size-3"/>Run</Button><Button size="sm" variant="ghost" onClick={()=>void remove()} disabled={busy}><Trash2 className="size-3"/></Button></>}</div></div>}>
- <div className="grid h-full min-h-0 grid-cols-[240px_minmax(0,1fr)_340px]">
- <aside className="min-h-0 border-r bg-muted/10"><div className="space-y-2 border-b p-2"><Input className="h-8" placeholder="Search workflows…" value={search} onChange={(e)=>setSearch(e.target.value)}/><WorkflowCreateDialog onBlank={async()=>{await createBlank();}} onTemplate={async(id)=>{await createTemplate(id);}} onAI={async(definition)=>{await createAI(definition);}}/></div><ScrollArea className="h-[calc(100%-86px)]"><div className="space-y-1 p-2">{filtered.length===0&&<div className="p-3 text-xs text-muted-foreground">No matching private workflows.</div>}{filtered.map((item)=><button key={item.id} type="button" onClick={()=>void wrap(()=>selectGraph(item.id))} className={`w-full rounded-lg border p-2 text-left text-xs ${graph?.id===item.id?"bg-accent":"bg-card"}`}><div className="truncate font-medium">{item.name}</div><div className="mt-1 flex flex-wrap gap-1 text-[10px] text-muted-foreground"><span>{item.status} · {item.nodes.length} nodes</span>{item.metadata.folder&&<span>· {item.metadata.folder}</span>}</div></button>)}</div></ScrollArea></aside>
- <main className="min-h-0 min-w-0 overflow-hidden">{graph?<div className="flex h-full flex-col"><div className="flex h-10 items-center gap-2 border-b px-2"><select className="h-7 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(e)=>mutate({...graph,status:e.target.value as WorkflowGraph["status"]})}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="text-[10px] text-muted-foreground">Click output port → input port to connect. Red port = error.</span>{message&&<span className="ml-auto max-w-72 truncate text-[11px] text-muted-foreground">{message}</span>}</div><div className="min-h-0 flex-1 overflow-auto"><WorkflowCanvas graph={graph} selectedId={selected} onSelect={(id)=>{setSelected(id);if(id)setPanel("inspector");}} nodeStates={runStates} onOpen={(id)=>void openNode(id)} onConnect={connect} onMove={(id,position)=>mutate({...graph,nodes:graph.nodes.map((item)=>item.id===id?{...item,position}:item)})}/></div></div>:<div className="flex h-full items-center justify-center text-sm text-muted-foreground">Create or select a workflow.</div>}</main>
- <aside className="min-h-0 border-l"><div className="flex h-10 border-b">{panelButton("inspector","Inspector")}{panelButton("run","Run")}{panelButton("history","History")}{panelButton("versions","Versions")}{panelButton("variables","Vars")}</div><div className="h-[calc(100%-40px)]">{graph&&panel==="inspector"&&<ScrollArea className="h-full"><WorkflowInspector key={node?.id??`graph-${graph.id}`} graph={graph} graphs={graphs} node={node} onNode={updateNode} onDeleteNode={deleteNode} onGraph={mutate}/></ScrollArea>}{panel==="run"&&<WorkflowRunPanel run={run}/>} {graph&&panel==="history"&&<WorkflowRunHistory graph={graph} onSelect={(selectedRun)=>{setRun(selectedRun);setPanel("run");}}/>}{graph&&panel==="versions"&&<WorkflowVersionPanel graph={graph} onRestored={(next)=>{setGraph(next);setDirty(false);void listGraphs().then(setGraphs);}}/>}{panel==="variables"&&<WorkflowVariablePanel/>}</div></aside>
- </div>
- </AppFrame>;
+type Definition = Omit<WorkflowGraph, "version" | "id" | "revision" | "createdAt" | "updatedAt">;
+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" }] }; }
+
+export default function WorkflowsApp(_props: AppProps) {
+ const { isMobile } = useResponsive();
+ const [graphs, setGraphs] = useState<WorkflowGraph[]>([]), [graph, setGraph] = useState<WorkflowGraph | null>(null), [selected, setSelected] = useState<string | null>(null), [run, setRun] = useState<WorkflowGraphRun | null>(null);
+ const [busy, setBusy] = useState(false), [dirty, setDirty] = useState(false), [message, setMessage] = useState(""), [panel, setPanel] = useState<WorkflowPanel>("inspector"), [search, setSearch] = useState("");
+ const [libraryOpen, setLibraryOpen] = useState(false), [detailsOpen, setDetailsOpen] = useState(false), [showLibrary, setShowLibrary] = useState(true), [showDetails, setShowDetails] = useState(true);
+ const node = useMemo(() => graph?.nodes.find((item) => item.id === selected) ?? null, [graph, selected]);
+ const runStates = useMemo(() => new Map(run?.nodes.map((item) => [item.id, item.state]) ?? []), [run]);
+
+ const load = async (selectId?: string) => { const list = await listGraphs(); setGraphs(list); const id = selectId ?? graph?.id ?? list[0]?.id; if (id) { setGraph(await getGraph(id)); setDirty(false); } else { setGraph(null); setDirty(false); } };
+ useEffect(() => { let cancelled = false; void listGraphs().then(async (list) => { if (cancelled) return; setGraphs(list); if (list[0]) { const first = await getGraph(list[0].id); if (!cancelled) setGraph(first); } }).catch((error: unknown) => { if (!cancelled) setMessage(error instanceof Error ? error.message : "Could not load workflows"); }); return () => { cancelled = true; }; }, []);
+ useEffect(() => { if (!run || run.state !== "running") return; const timer = setInterval(() => { void runStatus(run.id).then(setRun).catch(() => undefined); }, 1600); return () => clearInterval(timer); }, [run]);
+ const wrap = async (fn: () => Promise<void>) => { setBusy(true); setMessage(""); try { await fn(); } catch (error) { setMessage(error instanceof Error ? error.message : "Action failed"); } finally { setBusy(false); } };
+ const mutate = (next: WorkflowGraph) => { setGraph(next); setDirty(true); };
+ const selectGraph = async (id: string) => { setGraph(await getGraph(id)); setSelected(null); setRun(null); setDirty(false); setPanel("inspector"); setLibraryOpen(false); };
+ const createBlank = () => wrap(async () => { const next = await createGraph(starterGraph()); await load(next.id); setSelected("manual"); setLibraryOpen(false); });
+ const createTemplate = (id: string) => wrap(async () => { const next = await createFromTemplate(id); await load(next.id); setSelected(next.nodes[0]?.id ?? null); setLibraryOpen(false); });
+ const createAI = (definition: Definition) => wrap(async () => { const next = await createGraph(definition); 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 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 (isMobile) setDetailsOpen(true); });
+ const updateNode = (next: WorkflowGraphNode) => graph && mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === next.id ? next : item) });
+ const deleteNodes = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, nodes: graph.nodes.filter((item) => !removed.has(item.id)), edges: graph.edges.filter((edge) => !removed.has(edge.source) && !removed.has(edge.target)) }); if (selected && removed.has(selected)) setSelected(null); };
+ const deleteEdges = (ids: string[]) => { if (!graph || !ids.length) return; const removed = new Set(ids); mutate({ ...graph, edges: graph.edges.filter((edge) => !removed.has(edge.id)) }); };
+ const addNode = (type: WorkflowGraphNodeType, defaults: Record<string, unknown>) => { if (!graph) return; const id = `${type}-${crypto.randomUUID().slice(0, 8)}`; const next: WorkflowGraphNode = { id, name: type.replaceAll("_", " ").replace(/\b\w/g, (char) => char.toUpperCase()), type, position: { x: 220 + graph.nodes.length * 36, y: 240 + (graph.nodes.length % 4) * 110 }, config: structuredClone(defaults) }; mutate({ ...graph, nodes: [...graph.nodes, next] }); chooseNode(id); };
+ const connect = (source: string, target: string, sourceHandle?: string) => { if (!graph || graph.edges.some((edge) => edge.source === source && edge.target === target && edge.sourceHandle === sourceHandle)) return; mutate({ ...graph, edges: [...graph.edges, { id: `edge-${crypto.randomUUID().slice(0, 8)}`, source, target, ...(sourceHandle ? { sourceHandle } : {}) }] }); };
+ const openNode = async (id: string) => { if (!graph) return; const resolved = await resolveNode(graph.id, id); openWindow("files-manager", resolved.name, undefined, { path: resolved.path }, { multi: true }); };
+ const chooseNode = (id: string | null) => { setSelected(id); if (!id) return; setPanel("inspector"); if (isMobile) setDetailsOpen(true); };
+ const tidy = () => graph && mutate({ ...graph, nodes: tidyWorkflowNodes(graph) });
+
+ const library = <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 details = 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;
+
+ return <AppFrame safeArea={false} className="h-full" toolbar={<div className="flex h-11 items-center gap-1 border-b px-2 sm:gap-2 sm:px-3"><Workflow className="size-4 shrink-0"/><span className="hidden text-sm font-semibold sm:inline">Workflows</span>{dirty ? <Badge variant="outline">Unsaved</Badge> : null}{graph ? <Input className="h-8 min-w-0 max-w-56 flex-1 sm:flex-none" value={graph.name} onChange={(event) => mutate({ ...graph, name: event.target.value })}/> : null}<div className="ml-auto flex items-center gap-1"><Button size="icon" variant="ghost" onClick={() => isMobile ? setLibraryOpen(true) : setShowLibrary((value) => !value)} aria-label="Toggle workflow library"><PanelLeft className="size-3.5"/></Button><Button size="icon" variant="ghost" onClick={() => void load()} disabled={busy} aria-label="Refresh workflows"><RefreshCw className="size-3.5"/></Button><WorkflowCreateDialog onBlank={async () => { await createBlank(); }} onTemplate={async (id) => { await createTemplate(id); }} onAI={async (definition) => { await createAI(definition); }}/>{graph ? <><Button size="icon" variant="ghost" onClick={() => void duplicate()} disabled={busy} aria-label="Duplicate workflow"><Copy className="size-3.5"/></Button><Button size="sm" variant="outline" className="hidden sm:inline-flex" onClick={() => void save()} disabled={busy || !dirty}><Save className="mr-1 size-3"/>Save</Button><Button size="sm" onClick={() => void execute()} disabled={busy}><Play className="mr-1 size-3"/>Run</Button><Button size="icon" variant="ghost" onClick={() => isMobile ? setDetailsOpen(true) : setShowDetails((value) => !value)} aria-label="Toggle workflow details"><PanelRight className="size-3.5"/></Button><Button size="icon" variant="ghost" className="hidden sm:inline-flex" onClick={() => void remove()} disabled={busy} aria-label="Delete workflow"><Trash2 className="size-3.5"/></Button></> : null}</div></div>}>
+ <div className={`grid h-full min-h-0 ${!isMobile && showLibrary ? "lg:grid-cols-[220px_minmax(0,1fr)]" : "grid-cols-1"}`}>
+ {!isMobile && showLibrary ? <aside className="min-h-0 border-r">{library}</aside> : null}
+ <main className="flex min-h-0 min-w-0 overflow-hidden">{graph ? <div className="flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-10 shrink-0 items-center gap-2 border-b px-2"><select className="h-7 rounded border bg-background px-2 text-xs" value={graph.status} onChange={(event) => mutate({ ...graph, status: event.target.value as WorkflowGraph["status"] })}><option value="draft">Draft</option><option value="active">Active</option><option value="archived">Archived</option></select><WorkflowNodePalette onAdd={addNode}/><span className="hidden text-[10px] text-muted-foreground xl:inline">Drag output → input. V select · H pan · Space pan · F fit.</span>{message ? <span className="ml-auto max-w-72 truncate text-[11px] text-muted-foreground">{message}</span> : null}</div><div className="min-h-0 flex-1 overflow-hidden"><WorkflowCanvas key={graph.id} graph={graph} selectedId={selected} onSelect={chooseNode} nodeStates={runStates} onOpen={(id) => void openNode(id)} onConnect={connect} onMove={(id, position) => mutate({ ...graph, nodes: graph.nodes.map((item) => item.id === id ? { ...item, position } : item) })} onDeleteNodes={deleteNodes} onDeleteEdges={deleteEdges} onTidy={tidy}/></div></div> : <div className="flex h-full flex-1 items-center justify-center text-sm text-muted-foreground">Create or select a workflow.</div>}{!isMobile && showDetails && graph ? <aside className="w-[320px] shrink-0 border-l xl:w-[360px]">{details}</aside> : null}</main>
+ </div>
+ {isMobile ? <><ResponsiveDialog open={libraryOpen} onOpenChange={setLibraryOpen} variant="panel" size="lg" mobileVariant="drawer-right" sheetSide="left"><ResponsiveDialog.Header><ResponsiveDialog.Title>Workflows</ResponsiveDialog.Title><ResponsiveDialog.Description>Select or create a workflow without leaving the canvas.</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body className="p-0">{library}</ResponsiveDialog.Body></ResponsiveDialog><ResponsiveDialog open={detailsOpen && Boolean(graph)} onOpenChange={setDetailsOpen} variant="panel" size="lg" mobileVariant="drawer-right" sheetSide="right"><ResponsiveDialog.Header><ResponsiveDialog.Title>{node?.name ?? graph?.name ?? "Workflow details"}</ResponsiveDialog.Title><ResponsiveDialog.Description>Inspect configuration, runs, versions, and variables while preserving canvas context.</ResponsiveDialog.Description></ResponsiveDialog.Header><ResponsiveDialog.Body className="p-0">{details}</ResponsiveDialog.Body></ResponsiveDialog></> : null}
+ </AppFrame>;
}
diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsx
index 5477f442..8b732b54 100644
--- a/frontend/slices/workflows/components/workflow-canvas.tsx
+++ b/frontend/slices/workflows/components/workflow-canvas.tsx
@@ -1,25 +1,131 @@
"use client";
-import { useMemo, useRef, useState } from "react";
+
+import { useEffect, useMemo } from "react";
+import {
+ Handle,
+ Position,
+ useEdgesState,
+ useNodesState,
+ type Connection,
+ type Edge,
+ type Node,
+ type NodeProps,
+} from "@xyflow/react";
import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphNodeState } from "@/lib/contracts/workflow-graph";
+import { GraphCanvas } from "@/components/shared/graph-canvas";
import { cn } from "@/lib/utils";
-const W=184,H=76;
-type Source={id:string;handle?:string}|null;
-function handles(node:WorkflowGraphNode){if(node.type==="condition")return["true","false"];if(node.type==="switch"){const cases=Array.isArray(node.config.cases)?node.config.cases:[];return[...cases.map((row,i)=>row&&typeof row==="object"&&typeof (row as {handle?:unknown}).handle==="string"?String((row as {handle:string}).handle):`case-${i+1}`),"default"];}return[undefined];}
-function canError(node:WorkflowGraphNode){return!["manual","schedule","webhook","output"].includes(node.type);}
-export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onConnect,nodeStates,onOpen}:{graph:WorkflowGraph;selectedId:string|null;onSelect:(id:string|null)=>void;onMove:(id:string,position:{x:number;y:number})=>void;onConnect:(source:string,target:string,sourceHandle?:string)=>void;nodeStates?:ReadonlyMap<string,WorkflowGraphNodeState>;onOpen?:(id:string)=>void;}){
- const drag=useRef<{id:string;dx:number;dy:number}|null>(null),[source,setSource]=useState<Source>(null),nodes=useMemo(()=>new Map(graph.nodes.map((node)=>[node.id,node])),[graph.nodes]);
- const down=(event:React.PointerEvent,node:WorkflowGraphNode)=>{const box=event.currentTarget.getBoundingClientRect();drag.current={id:node.id,dx:event.clientX-box.left,dy:event.clientY-box.top};event.currentTarget.setPointerCapture(event.pointerId);onSelect(node.id);};
- const move=(event:React.PointerEvent)=>{if(!drag.current)return;const canvas=event.currentTarget.getBoundingClientRect();onMove(drag.current.id,{x:Math.max(12,event.clientX-canvas.left-drag.current.dx),y:Math.max(12,event.clientY-canvas.top-drag.current.dy)});};
- const connect=(target:string)=>{if(source&&source.id!==target)onConnect(source.id,target,source.handle);setSource(null);};
- return <div className="relative h-full min-h-[520px] min-w-[880px] overflow-auto bg-muted/20" onPointerMove={move} onPointerUp={()=>{drag.current=null;}} onClick={(event)=>{if(event.target===event.currentTarget){onSelect(null);setSource(null);}}}>
- <svg className="absolute inset-0 h-[1400px] w-[2200px]" aria-hidden>{graph.edges.map((edge)=>{const a=nodes.get(edge.source),b=nodes.get(edge.target);if(!a||!b)return null;const x1=a.position.x+W,y1=a.position.y+H/2,x2=b.position.x,y2=b.position.y+H/2,c=Math.max(60,Math.abs(x2-x1)/2),live=nodeStates?.get(edge.source)==="running"||nodeStates?.get(edge.target)==="running";return <path key={edge.id} d={`M ${x1} ${y1} C ${x1+c} ${y1}, ${x2-c} ${y2}, ${x2} ${y2}`} fill="none" stroke="currentColor" strokeWidth="1.5" className={cn("pointer-events-none text-border",live&&"animate-pulse text-primary")}/>;})}</svg>
- <div className="relative h-[1400px] w-[2200px]">{graph.nodes.map((node)=><div key={node.id} className="absolute" style={{transform:`translate(${node.position.x}px, ${node.position.y}px)`}}>
- <button type="button" onPointerDown={(event)=>down(event,node)} onClick={(event)=>{event.stopPropagation();onSelect(node.id);}} onDoubleClick={()=>{if((node.type==="project"||node.type==="folder")&&onOpen)onOpen(node.id);}} className={cn("flex h-[76px] w-[184px] cursor-grab flex-col items-start justify-center rounded-xl border bg-card px-3 text-left shadow-sm active:cursor-grabbing",selectedId===node.id&&"ring-2 ring-ring",nodeStates?.get(node.id)==="failed"&&"border-destructive ring-1 ring-destructive",nodeStates?.get(node.id)==="running"&&"border-primary ring-1 ring-primary",["skipped","blocked"].includes(nodeStates?.get(node.id)??"")&&"opacity-55",node.disabled&&"opacity-50")}>
- <span className="w-full truncate text-xs font-semibold">{node.name}</span><span className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">{node.type.replaceAll("_"," ")}{nodeStates?.get(node.id)?` · ${nodeStates.get(node.id)}`:""}</span>{node.type==="condition"&&<span className="mt-1 text-[10px] text-muted-foreground">true / false</span>}
- </button>
- {!["manual","schedule","webhook"].includes(node.type)&&<button type="button" aria-label={`Connect into ${node.name}`} onPointerDown={(e)=>e.stopPropagation()} onClick={(e)=>{e.stopPropagation();connect(node.id);}} className={cn("absolute -left-2 top-1/2 size-4 -translate-y-1/2 rounded-full border bg-background",source&&"ring-1 ring-ring")}/>}
- {node.type!=="output"&&handles(node).map((handle,index)=><button key={handle??"default"} type="button" title={handle??"output"} aria-label={`Connect ${node.name} ${handle??"output"}`} onPointerDown={(e)=>e.stopPropagation()} onClick={(e)=>{e.stopPropagation();setSource({id:node.id,...(handle?{handle}:{})});}} className={cn("absolute -right-2 size-4 rounded-full border bg-background",source?.id===node.id&&source.handle===handle&&"ring-2 ring-ring")} style={{top:`${22+index*22}px`}}/>)}
- {canError(node)&&<button type="button" title="error" aria-label={`Connect ${node.name} error`} onPointerDown={(e)=>e.stopPropagation()} onClick={(e)=>{e.stopPropagation();setSource({id:node.id,handle:"error"});}} className={cn("absolute -right-2 bottom-1 size-3 rounded-full border border-destructive bg-background",source?.id===node.id&&source.handle==="error"&&"ring-2 ring-destructive")}/>}
- </div>)}</div>
- </div>;
+
+interface WorkflowNodeData extends Record<string, unknown> { node: WorkflowGraphNode; state?: WorkflowGraphNodeState }
+type FlowNode = Node<WorkflowNodeData, "workflow">;
+type FlowEdge = Edge;
+
+function sourceHandles(node: WorkflowGraphNode): Array<string | undefined> {
+ if (node.type === "condition") return ["true", "false"];
+ if (node.type === "switch") {
+ const cases = Array.isArray(node.config.cases) ? node.config.cases : [];
+ return [...cases.map((row, index) => row && typeof row === "object" && typeof (row as { handle?: unknown }).handle === "string" ? String((row as { handle: string }).handle) : `case-${index + 1}`), "default"];
+ }
+ return [undefined];
+}
+function canError(node: WorkflowGraphNode) { return !["manual", "schedule", "webhook", "output"].includes(node.type); }
+function canInput(node: WorkflowGraphNode) { return !["manual", "schedule", "webhook"].includes(node.type); }
+function canOutput(node: WorkflowGraphNode) { return node.type !== "output"; }
+
+function WorkflowNodeCard({ data, selected }: NodeProps<FlowNode>) {
+ const { node, state } = data;
+ const handles = sourceHandles(node);
+ const height = Math.max(78, 48 + Math.max(handles.length, canError(node) ? 2 : 1) * 20);
+ return (
+ <div
+ className={cn(
+ "relative w-[200px] rounded-xl border bg-card px-3 py-3 shadow-sm transition-shadow",
+ selected && "ring-2 ring-ring shadow-md",
+ state === "failed" && "border-destructive ring-1 ring-destructive",
+ state === "running" && "border-primary ring-1 ring-primary",
+ ["skipped", "blocked"].includes(state ?? "") && "opacity-55",
+ node.disabled && "opacity-50",
+ )}
+ style={{ minHeight: height }}
+ >
+ {canInput(node) ? <Handle type="target" position={Position.Left} id="input" className="!size-3.5 !border-2 !border-background !bg-muted-foreground" /> : null}
+ <div className="truncate text-xs font-semibold">{node.name}</div>
+ <div className="mt-1 text-[10px] uppercase tracking-wide text-muted-foreground">{node.type.replaceAll("_", " ")}{state ? ` · ${state}` : ""}</div>
+ {canOutput(node) ? handles.map((handle, index) => (
+ <div key={handle ?? "output"} className="absolute right-0 flex translate-x-1/2 items-center" style={{ top: 38 + index * 20 }}>
+ {handle ? <span className="pointer-events-none absolute right-4 whitespace-nowrap pr-1 text-[8px] text-muted-foreground">{handle}</span> : null}
+ <Handle type="source" position={Position.Right} id={handle ?? "output"} className="!relative !right-auto !top-auto !size-3.5 !translate-x-0 !translate-y-0 !border-2 !border-background !bg-muted-foreground" />
+ </div>
+ )) : null}
+ {canError(node) ? <Handle type="source" position={Position.Bottom} id="error" className="!size-3 !border-2 !border-background !bg-destructive" /> : null}
+ </div>
+ );
+}
+const nodeTypes = { workflow: WorkflowNodeCard };
+
+function toNodes(graph: WorkflowGraph, selectedId: string | null, nodeStates?: ReadonlyMap<string, WorkflowGraphNodeState>): FlowNode[] {
+ return graph.nodes.map((node) => ({ id: node.id, type: "workflow", position: node.position, selected: node.id === selectedId, data: { node, state: nodeStates?.get(node.id) } }));
+}
+function toEdges(graph: WorkflowGraph, nodeStates?: ReadonlyMap<string, WorkflowGraphNodeState>): FlowEdge[] {
+ return graph.edges.map((edge) => ({
+ id: edge.id,
+ source: edge.source,
+ target: edge.target,
+ sourceHandle: edge.sourceHandle ?? "output",
+ targetHandle: "input",
+ type: "smoothstep",
+ animated: nodeStates?.get(edge.source) === "running" || nodeStates?.get(edge.target) === "running",
+ }));
+}
+
+export function WorkflowCanvas({ graph, selectedId, onSelect, onMove, onConnect, nodeStates, onOpen, onDeleteNodes, onDeleteEdges, onTidy }: {
+ graph: WorkflowGraph;
+ selectedId: string | null;
+ onSelect: (id: string | null) => void;
+ onMove: (id: string, position: { x: number; y: number }) => void;
+ onConnect: (source: string, target: string, sourceHandle?: string) => void;
+ nodeStates?: ReadonlyMap<string, WorkflowGraphNodeState>;
+ onOpen?: (id: string) => void;
+ onDeleteNodes?: (ids: string[]) => void;
+ onDeleteEdges?: (ids: string[]) => void;
+ onTidy?: () => void;
+}) {
+ const mappedNodes = useMemo(() => toNodes(graph, selectedId, nodeStates), [graph, nodeStates, selectedId]);
+ const mappedEdges = useMemo(() => toEdges(graph, nodeStates), [graph, nodeStates]);
+ const [nodes, setNodes, onNodesChange] = useNodesState<FlowNode>(mappedNodes);
+ const [edges, setEdges, onEdgesChange] = useEdgesState<FlowEdge>(mappedEdges);
+ useEffect(() => setNodes(mappedNodes), [mappedNodes, setNodes]);
+ useEffect(() => setEdges(mappedEdges), [mappedEdges, setEdges]);
+
+ const connect = (connection: Connection) => {
+ if (!connection.source || !connection.target || connection.source === connection.target) return;
+ const handle = connection.sourceHandle && connection.sourceHandle !== "output" ? connection.sourceHandle : undefined;
+ onConnect(connection.source, connection.target, handle);
+ };
+
+ return (
+ <GraphCanvas<FlowNode, FlowEdge>
+ ariaLabel="Workflow canvas"
+ nodes={nodes}
+ edges={edges}
+ nodeTypes={nodeTypes}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ onConnect={connect}
+ onPaneClick={() => onSelect(null)}
+ onNodeClick={(_, item) => onSelect(item.id)}
+ onNodeDoubleClick={(_, item) => { const node = item.data.node; if ((node.type === "project" || node.type === "folder") && onOpen) onOpen(node.id); }}
+ onNodeDragStop={(_, item) => onMove(item.id, item.position)}
+ onNodesDelete={(items) => onDeleteNodes?.(items.map((item) => item.id))}
+ onEdgesDelete={(items) => onDeleteEdges?.(items.map((item) => item.id))}
+ isValidConnection={(connection) => Boolean(connection.source && connection.target && connection.source !== connection.target && !graph.edges.some((edge) => edge.source === connection.source && edge.target === connection.target && (edge.sourceHandle ?? undefined) === (connection.sourceHandle === "output" ? undefined : connection.sourceHandle ?? undefined)))}
+ nodesDraggable
+ nodesConnectable
+ edgesReconnectable={false}
+ deleteKeyCode={["Backspace", "Delete"]}
+ onTidy={onTidy}
+ snapToGrid
+ snapGrid={[12, 12]}
+ defaultEdgeOptions={{ type: "smoothstep" }}
+ />
+ );
}
diff --git a/frontend/slices/workflows/components/workflow-details.tsx b/frontend/slices/workflows/components/workflow-details.tsx
new file mode 100644
index 00000000..5b93ed85
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-details.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import type { WorkflowGraph, WorkflowGraphNode, WorkflowGraphRun } from "@/lib/contracts/workflow-graph";
+import { ScrollArea } from "@/components/ui/scroll-area";
+import { WorkflowInspector } from "./workflow-inspector";
+import { WorkflowRunHistory } from "./workflow-run-history";
+import { WorkflowRunPanel } from "./workflow-run-panel";
+import { WorkflowVariablePanel } from "./workflow-variable-panel";
+import { WorkflowVersionPanel } from "./workflow-version-panel";
+
+export type WorkflowPanel = "inspector" | "run" | "history" | "versions" | "variables";
+
+const LABELS: Array<[WorkflowPanel, string]> = [["inspector", "Inspector"], ["run", "Run"], ["history", "History"], ["versions", "Versions"], ["variables", "Vars"]];
+
+export function WorkflowDetails({ graph, graphs, node, run, panel, onPanel, onNode, onDeleteNode, onGraph, onRunSelect, onRestored }: {
+ graph: WorkflowGraph;
+ graphs: WorkflowGraph[];
+ node: WorkflowGraphNode | null;
+ run: WorkflowGraphRun | null;
+ panel: WorkflowPanel;
+ onPanel: (panel: WorkflowPanel) => void;
+ onNode: (node: WorkflowGraphNode) => void;
+ onDeleteNode: (id: string) => void;
+ onGraph: (graph: WorkflowGraph) => void;
+ onRunSelect: (run: WorkflowGraphRun) => void;
+ onRestored: (graph: WorkflowGraph) => void;
+}) {
+ return <div className="flex h-full min-h-0 flex-col bg-card/20">
+ <div className="flex h-10 shrink-0 border-b">{LABELS.map(([value, label]) => <button key={value} type="button" className={`min-w-0 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}</div>
+ </div>;
+}
diff --git a/frontend/slices/workflows/components/workflow-library.tsx b/frontend/slices/workflows/components/workflow-library.tsx
new file mode 100644
index 00000000..d9fcaa92
--- /dev/null
+++ b/frontend/slices/workflows/components/workflow-library.tsx
@@ -0,0 +1,27 @@
+"use client";
+
+import { FolderOpen } from "lucide-react";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { Input } from "@/components/ui/input";
+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 }: {
+ graphs: WorkflowGraph[];
+ activeId?: string;
+ search: string;
+ onSearch: (value: string) => void;
+ onSelect: (id: string) => void;
+ onBlank: () => Promise<void>;
+ onTemplate: (id: string) => Promise<void>;
+ onAI: (definition: Definition) => Promise<void>;
+}) {
+ const query = search.toLowerCase().trim();
+ const filtered = graphs.filter((graph) => !query || `${graph.name} ${graph.metadata.folder ?? ""} ${(graph.metadata.tags ?? []).join(" ")}`.toLowerCase().includes(query));
+ 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" placeholder="Search workflows…" 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) => <button key={graph.id} type="button" onClick={() => onSelect(graph.id)} className={`w-full rounded-lg border p-2 text-left text-xs transition-colors ${activeId === graph.id ? "bg-accent" : "bg-card hover:bg-accent/60"}`}><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><div className="mt-1 flex flex-wrap gap-1 pl-5 text-[10px] text-muted-foreground"><span>{graph.status} · {graph.nodes.length} nodes</span>{graph.metadata.folder ? <span>· {graph.metadata.folder}</span> : null}</div></button>)}</div></ScrollArea>
+ </div>;
+}
diff --git a/frontend/slices/workflows/lib/canvas-layout.test.ts b/frontend/slices/workflows/lib/canvas-layout.test.ts
new file mode 100644
index 00000000..f2d6dbf6
--- /dev/null
+++ b/frontend/slices/workflows/lib/canvas-layout.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from "vitest";
+import type { WorkflowGraph } from "@/lib/contracts/workflow-graph";
+import { tidyWorkflowNodes } from "./canvas-layout";
+
+const graph = (nodes: WorkflowGraph["nodes"], edges: WorkflowGraph["edges"]): WorkflowGraph => ({
+ version: 2, id: "g", name: "Graph", description: "", status: "draft", inputs: {}, metadata: {},
+ createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", revision: "r", nodes, edges,
+});
+const node = (id: string): WorkflowGraph["nodes"][number] => ({ id, name: id, type: id === "manual" ? "manual" : id === "output" ? "output" : "tool", position: { x: 0, y: 0 }, config: {} });
+
+describe("workflow canvas tidy layout", () => {
+ it("lays dependencies left to right and branches without overlap", () => {
+ const rows = tidyWorkflowNodes(graph([node("manual"), node("alpha"), node("beta"), node("output")], [
+ { id: "a", source: "manual", target: "alpha" }, { id: "b", source: "manual", target: "beta" },
+ { id: "c", source: "alpha", target: "output" }, { id: "d", source: "beta", target: "output" },
+ ]));
+ const byId = new Map(rows.map((row) => [row.id, row.position]));
+ expect(byId.get("manual")!.x).toBeLessThan(byId.get("alpha")!.x);
+ expect(byId.get("alpha")!.x).toBeLessThan(byId.get("output")!.x);
+ expect(byId.get("alpha")!.y).not.toBe(byId.get("beta")!.y);
+ });
+
+ it("keeps invalid cyclic drafts finite instead of exploding layout", () => {
+ const rows = tidyWorkflowNodes(graph([node("alpha"), node("beta")], [{ id: "a", source: "alpha", target: "beta" }, { id: "b", source: "beta", target: "alpha" }]));
+ expect(rows).toHaveLength(2);
+ for (const row of rows) expect(Number.isFinite(row.position.x) && Number.isFinite(row.position.y)).toBe(true);
+ });
+});
diff --git a/frontend/slices/workflows/lib/canvas-layout.ts b/frontend/slices/workflows/lib/canvas-layout.ts
new file mode 100644
index 00000000..10b47525
--- /dev/null
+++ b/frontend/slices/workflows/lib/canvas-layout.ts
@@ -0,0 +1,40 @@
+import type { WorkflowGraph, WorkflowGraphNode } from "@/lib/contracts/workflow-graph";
+
+const X_GAP = 270;
+const Y_GAP = 128;
+const START_X = 72;
+const START_Y = 72;
+
+export function tidyWorkflowNodes(graph: WorkflowGraph): WorkflowGraphNode[] {
+ const byId = new Map(graph.nodes.map((node) => [node.id, node]));
+ const incoming = new Map(graph.nodes.map((node) => [node.id, graph.edges.filter((edge) => edge.target === node.id && byId.has(edge.source))]));
+ const indegree = new Map(graph.nodes.map((node) => [node.id, incoming.get(node.id)?.length ?? 0]));
+ const layer = new Map<string, number>();
+ const queue = graph.nodes.filter((node) => (indegree.get(node.id) ?? 0) === 0).sort((a, b) => a.position.y - b.position.y || a.name.localeCompare(b.name));
+
+ for (const node of queue) layer.set(node.id, 0);
+ for (let index = 0; index < queue.length; index += 1) {
+ const current = queue[index]!;
+ const currentLayer = layer.get(current.id) ?? 0;
+ for (const edge of graph.edges.filter((row) => row.source === current.id && byId.has(row.target))) {
+ layer.set(edge.target, Math.max(layer.get(edge.target) ?? 0, currentLayer + 1));
+ const next = (indegree.get(edge.target) ?? 1) - 1;
+ indegree.set(edge.target, next);
+ if (next === 0) queue.push(byId.get(edge.target)!);
+ }
+ }
+
+ const fallbackLayer = Math.max(0, ...layer.values()) + 1;
+ for (const node of graph.nodes) if (!layer.has(node.id)) layer.set(node.id, fallbackLayer);
+ const rows = new Map<number, WorkflowGraphNode[]>();
+ for (const node of graph.nodes) rows.set(layer.get(node.id)!, [...(rows.get(layer.get(node.id)!) ?? []), node]);
+ for (const group of rows.values()) group.sort((a, b) => a.position.y - b.position.y || a.name.localeCompare(b.name));
+
+ return graph.nodes.map((node) => {
+ const depth = layer.get(node.id)!;
+ const row = rows.get(depth)!;
+ const index = row.findIndex((item) => item.id === node.id);
+ const yOffset = ((row.length - 1) * Y_GAP) / 2;
+ return { ...node, position: { x: START_X + depth * X_GAP, y: Math.max(32, START_Y + index * Y_GAP - yOffset + 180) } };
+ });
+}
diff --git a/package.json b/package.json
index 75a68642..1be4ffd6 100644
--- a/package.json
+++ b/package.json
@@ -62,6 +62,7 @@
"@radix-ui/react-tooltip": "^1.2.9",
"@xterm/addon-fit": "^0.11.0",
"@xterm/xterm": "^6.0.0",
+ "@xyflow/react": "12.11.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"geist": "^1.7.2",
diff --git a/scripts/e2e/organization.mjs b/scripts/e2e/organization.mjs
index dad704e7..d252fdd3 100644
--- a/scripts/e2e/organization.mjs
+++ b/scripts/e2e/organization.mjs
@@ -34,21 +34,28 @@ export async function organizationJourney(page, fixture) {
});
expect(response.status).toBe(200);
- await page.goto(fixture.base + "/assistant/organization");
- await expect(page.getByRole("button", { name: "Organization", exact: true })).toBeVisible();
- await expect(page.getByText("All organization", { exact: true })).toBeVisible();
- await expect(page.getByText("Chief Executive Officer", { exact: true })).toBeVisible();
- await expect(page.getByText("Chief Technology Officer", { exact: true })).toBeVisible();
+ await page.goto(fixture.base + "/organization");
+ await expect(page.getByRole("application", { name: "Organization units canvas" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Select mode" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Pan mode" })).toBeVisible();
+ await expect(page.getByLabel("Organization units canvas minimap")).toBeVisible();
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);
- await page.getByRole("button", { name: /Chief Technology Officer/ }).click();
+ await page.getByRole("button", { name: /E2E Product/ }).click();
+ await expect(page.getByRole("application", { name: "Organization seats canvas" })).toBeVisible();
+ await expect(page.locator(".react-flow__node", { hasText: "Chief Executive Officer" })).toBeVisible();
+ const cto = page.locator(".react-flow__node", { hasText: "Chief Technology Officer" });
+ await expect(cto).toBeVisible();
+ await cto.click();
+ await expect(page.getByRole("button", { name: "Edit seat" })).toBeVisible();
+ await page.getByRole("button", { name: "Edit seat" }).click();
await expect(page.getByRole("heading", { name: "Edit seat" })).toBeVisible();
await page.getByLabel("Execution target").selectOption("project-agent");
await page.getByRole("textbox", { name: "Project", exact: true }).fill("fixture-project");
await page.getByRole("button", { name: "Save", exact: true }).click();
- await expect(page.getByText("fixture-project", { exact: true })).toBeVisible();
+ await expect(page.getByRole("heading", { name: "Edit seat" })).toBeHidden();
response = await call(page, "/api/v1/organization");
expect(response.status).toBe(200); revision = response.body.chart.revision;
diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjs
index 6a15ac91..9d32a462 100644
--- a/scripts/e2e/release.mjs
+++ b/scripts/e2e/release.mjs
@@ -6,6 +6,7 @@ import AxeBuilder from "@axe-core/playwright";
import { mcpOwnerJourneys, mcpPublicJourney, settingsAccessibilityJourney } from "./mcp-settings.mjs";
import { automationJourney } from "./automation.mjs";
import { organizationJourney } from "./organization.mjs";
+import { workflowCanvasJourney } from "./workflow-canvas.mjs";
import { releaseFixture } from "./release-fixture.mjs";
execFileSync(process.execPath, ["scripts/e2e/mcp-page.mjs"], { stdio: "inherit" });
@@ -118,6 +119,7 @@ try {
await mcpOwnerJourneys(page, fixture);
await automationJourney(page, fixture);
await organizationJourney(page, fixture);
+ await workflowCanvasJourney(page, fixture);
await fixture.setRole("viewer");
expect((await call("/api/v1/agent-sessions?view=monitor")).status).toBe(403);
expect((await call("/api/v1/integrations")).status).toBe(403);
diff --git a/scripts/e2e/shell.mjs b/scripts/e2e/shell.mjs
index 1f24132b..e53a4a0f 100644
--- a/scripts/e2e/shell.mjs
+++ b/scripts/e2e/shell.mjs
@@ -67,7 +67,7 @@ const check = (cond, m) => (cond ? pass(m) : fail(m));
const TITLES = {
files: "Files", browser: "Camoufox", code: "Code", terminal: "Terminal", claude: "Claude Code",
studio: "Image Editor", reel: "Video Editor", viewer: "Preview", store: "App Store", create: "Create App",
- monitor: "System Monitor", assistant: "Alfa", links: "Quicklinks", docs: "Docs", settings: "Settings",
+ monitor: "System Monitor", assistant: "Alfa", organization: "Organization", workflows: "Workflows", links: "Quicklinks", docs: "Docs", settings: "Settings",
hermes: "Hermes", openclaw: "OpenClaw", "9router": "9Router", dokploy: "Dokploy", cloudflare: "Cloudflare",
};
@@ -188,7 +188,7 @@ async function session(browser, { width, height, label, touch = width < 768, exp
// this app render", and conflating them made both unreliable.
const nativeSlugs = [
"files", "browser", "code", "terminal", "claude", "studio", "reel", "viewer",
- "store", "create", "monitor", "assistant", "links", "docs", "settings", "dokploy", "cloudflare",
+ "store", "create", "monitor", "assistant", "organization", "workflows", "links", "docs", "settings", "dokploy", "cloudflare",
];
for (const slug of nativeSlugs) {
await page.goto(`${BASE}/${slug}`, { waitUntil: "domcontentloaded" });
diff --git a/scripts/e2e/workflow-canvas.mjs b/scripts/e2e/workflow-canvas.mjs
new file mode 100644
index 00000000..6cef57ef
--- /dev/null
+++ b/scripts/e2e/workflow-canvas.mjs
@@ -0,0 +1,47 @@
+import { expect } from "@playwright/test";
+
+async function call(page, body) {
+ return page.evaluate(async (body) => {
+ const response = await fetch("/api/v1/workflows", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+ return { status: response.status, body: await response.json() };
+ }, body);
+}
+
+export async function workflowCanvasJourney(page, fixture) {
+ let response = await call(page, {
+ action: "create",
+ graph: {
+ name: "E2E Canvas Workflow", description: "Canvas navigation fixture", status: "draft", inputs: {}, metadata: { provenance: "user" },
+ nodes: [
+ { id: "manual", name: "Manual Trigger", type: "manual", position: { x: 620, y: 420 }, config: {} },
+ { id: "action", name: "Fixture Action", type: "wait", position: { x: 120, y: 720 }, config: { delayMs: 0 } },
+ { id: "output", name: "Output", type: "output", position: { x: 880, y: 80 }, config: {} },
+ ],
+ edges: [{ id: "edge-a", source: "manual", target: "action" }, { id: "edge-b", source: "action", target: "output" }],
+ },
+ });
+ expect(response.status).toBe(200);
+ const graph = response.body.graph;
+
+ await page.goto(fixture.base + "/workflows");
+ await expect(page.getByRole("application", { name: "Workflow canvas" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Select mode" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Pan mode" })).toBeVisible();
+ await expect(page.getByRole("button", { name: "Tidy up" })).toBeVisible();
+ await expect(page.getByLabel("Workflow canvas minimap")).toBeVisible();
+ await expect(page.locator(".react-flow__node", { hasText: "Manual Trigger" })).toBeVisible();
+
+ await page.locator(".react-flow__node", { hasText: "Fixture Action" }).click();
+ await expect(page.getByText("Delay ms", { exact: true })).toBeVisible();
+ await page.getByRole("button", { name: "Pan mode" }).click();
+ await expect(page.getByRole("button", { name: "Pan mode" })).toHaveClass(/is-active/);
+ await page.getByRole("button", { name: "Select mode" }).click();
+ await expect(page.getByRole("button", { name: "Select mode" })).toHaveClass(/is-active/);
+ await page.getByRole("button", { name: "Tidy up" }).click();
+ await expect(page.getByText("Unsaved", { exact: true })).toBeVisible();
+ expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1)).toBe(true);
+
+ response = await call(page, { action: "delete", graph_id: graph.id, expected_revision: graph.revision });
+ expect(response.status).toBe(200);
+ console.log("PASS Workflow n8n-style canvas controls, selection/inspector, tidy-up and cleanup");
+}