Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
refactor(graph): establish shared flow foundation
Rahman7dfa058524ff
diff --git a/components/shared/graph-canvas.tsx b/components/shared/graph-canvas.tsxindex 73e01839..85597ffc 100644--- a/components/shared/graph-canvas.tsx+++ b/components/shared/graph-canvas.tsx@@ -21,7 +21,7 @@ import {type Node,type ReactFlowProps,} from "@xyflow/react";-import { Hand, LayoutGrid, Maximize2, MousePointer2, ZoomIn, ZoomOut } from "lucide-react";+import { Hand, LayoutGrid, LocateFixed, Maximize2, MousePointer2, ZoomIn, ZoomOut } from "lucide-react";import { cn } from "@/lib/utils";import { compactGraphViewport } from "./graph-fit";import { GraphRoutingProvider } from "./graph-routed-edge";@@ -74,7 +74,15 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =const initialKey = JSON.stringify(initialFitNodeIds ?? []);const initialNodes = useMemo(() => (JSON.parse(initialKey) as string[]).map((id) => ({ id })), [initialKey]);const { fitView, zoomIn, zoomOut } = useReactFlow<NodeType, EdgeType>();+ const routingNodes = props.nodes ?? props.defaultNodes ?? [];+ const routingEdges = props.edges ?? props.defaultEdges ?? [];+ const selectionKey = JSON.stringify(routingNodes.filter((node) => node.selected).map((node) => node.id).sort());+ const selectedNodes = useMemo(() => (JSON.parse(selectionKey) as string[]).map((id) => ({ id })), [selectionKey]);const fit = useCallback(() => void fitView({ padding: fitPadding, duration: 220, ...fitViewOptions }), [fitPadding, fitView, fitViewOptions]);+ const focusSelection = useCallback(() => {+ if (!selectedNodes.length) return;+ void fitView({ nodes: selectedNodes, padding: Math.min(fitPadding, 0.16), duration: 220, maxZoom: 1.2, ...fitViewOptions });+ }, [fitPadding, fitView, fitViewOptions, selectedNodes]);const fitResponsive = useCallback((duration: number) => {const preferredNodes = compact ? focusNodes : initialNodes;const nodes = preferredNodes.length ? preferredNodes : undefined;@@ -103,12 +111,10 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =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(); }+ if (key === "f") { event.preventDefault(); if (event.shiftKey && selectedNodes.length) focusSelection(); else fit(); }if (key === "+" || key === "=") { event.preventDefault(); void zoomIn({ duration: 160 }); }if (key === "-") { event.preventDefault(); void zoomOut({ duration: 160 }); }};- const routingNodes = props.nodes ?? props.defaultNodes ?? [];- const routingEdges = props.edges ?? props.defaultEdges ?? [];return <GraphRoutingProvider nodes={routingNodes} edges={routingEdges}><div className="h-full min-h-0 w-full min-w-0 outline-none" tabIndex={0} onKeyDown={keyboard}><ReactFlow<NodeType, EdgeType>{...props}@@ -127,6 +133,7 @@ function GraphCanvasInner<NodeType extends Node = Node, EdgeType extends Edge =<ControlButton aria-label="Pan mode" title="Pan (H or hold Space)" onClick={() => setMode("pan")} className={mode === "pan" ? "is-active" : undefined}><Hand aria-hidden/></ControlButton><ControlButton aria-label="Zoom in" title="Zoom in (+)" onClick={() => void zoomIn({ duration: 160 })}><ZoomIn aria-hidden/></ControlButton><ControlButton aria-label="Zoom out" title="Zoom out (-)" onClick={() => void zoomOut({ duration: 160 })}><ZoomOut aria-hidden/></ControlButton>+ <ControlButton aria-label="Focus selection" title="Focus selection (Shift+F)" disabled={!selectedNodes.length} onClick={focusSelection}><LocateFixed aria-hidden/></ControlButton><ControlButton aria-label="Fit view" title="Fit complete graph (F)" onClick={fit}><Maximize2 aria-hidden/></ControlButton>{onTidy ? <ControlButton aria-label="Tidy up" title="Tidy up" onClick={tidy} className="mso-graph-secondary-control"><LayoutGrid aria-hidden/></ControlButton> : null}</Controls>diff --git a/components/shared/graph-custom-card.tsx b/components/shared/graph-custom-card.tsxindex c22c3eea..25c6e68a 100644--- a/components/shared/graph-custom-card.tsx+++ b/components/shared/graph-custom-card.tsx@@ -1,14 +1,15 @@"use client";import { Handle, Position, type NodeProps } from "@xyflow/react";-import { Boxes } from "lucide-react";-import { cn } from "@/lib/utils";import type { CustomCanvasNode } from "./graph-custom-projection";+import { GraphNodeShell } from "./graph-node-shell";export function GraphCustomCard({ data, selected }: NodeProps<CustomCanvasNode>) {- const inputs = data.ports.filter((port) => port.side === "in"), outputs = data.ports.filter((port) => port.side === "out");- return <div className={cn("relative w-60 rounded-xl border-2 border-primary/50 bg-card p-3 shadow-sm", selected && "ring-2 ring-ring")} style={{ minHeight: Math.max(104, 48 + Math.max(inputs.length, outputs.length) * 18) }}>- <div className="flex items-start gap-2"><Boxes className="size-4 shrink-0 text-primary"/><div className="min-w-0"><div className="line-clamp-2 break-words text-sm font-semibold">{data.group.name}</div><div className="mt-2 text-xs text-muted-foreground">Custom node · {data.group.nodeIds.length} members</div><div className="mt-1 text-[10px] text-muted-foreground">Double-click to expand</div></div></div>- {inputs.map((port, index) => <Handle key={port.id} id={port.id} type="target" position={Position.Left} isConnectable={false} title={port.label} style={{ top: 42 + index * 18 }} className="!size-2.5 !bg-primary"/>)}- {outputs.map((port, index) => <Handle key={port.id} id={port.id} type="source" position={Position.Right} isConnectable={false} title={port.label} style={{ top: 42 + index * 18 }} className="!size-2.5 !bg-primary"/>)}- </div>;+ const { group, ports } = data;+ const inputs = ports.filter((port) => port.side === "in"), outputs = ports.filter((port) => port.side === "out");+ return <GraphNodeShell selected={selected} className="w-60 border-2 border-primary/50" style={{ minHeight: Math.max(104, 48 + Math.max(inputs.length, outputs.length) * 18) }}>+ <div className="truncate text-xs font-semibold">{group.name}</div>+ <div className="mt-1 text-[10px] text-muted-foreground">{group.nodeIds.length} nodes · collapsed</div>+ {inputs.map((port, index) => <Handle key={port.id} type="target" position={Position.Left} id={port.id} className="!size-3 !bg-muted-foreground" style={{ top: 48 + index * 18 }} />)}+ {outputs.map((port, index) => <Handle key={port.id} type="source" position={Position.Right} id={port.id} className="!size-3 !bg-muted-foreground" style={{ top: 48 + index * 18 }} />)}+ </GraphNodeShell>;}diff --git a/components/shared/graph-custom-projection.ts b/components/shared/graph-custom-projection.tsindex df9efa8b..f056f997 100644--- a/components/shared/graph-custom-projection.ts+++ b/components/shared/graph-custom-projection.ts@@ -31,3 +31,19 @@ export function moveCustomNode<T extends { id: string; position: { x: number; y:const dx = position.x - Math.min(...members.map((node) => node.position.x)), dy = position.y - Math.min(...members.map((node) => node.position.y));return nodes.map((node) => group.nodeIds.includes(node.id) ? { ...node, position: { x: node.position.x + dx, y: node.position.y + dy } } : node);}+++export function moveGraphNodesWithCustomGroups<T extends { id: string; position: { x: number; y: number } }>(+ nodes: T[],+ groups: GraphCustomNode[],+ movedItems: Array<{ id: string; position: { x: number; y: number } }>,+): T[] {+ let next = nodes;+ for (const item of movedItems) {+ const group = groups.find((candidate) => candidate.id === item.id);+ next = group+ ? moveCustomNode(next, group, item.position)+ : next.map((node) => node.id === item.id ? { ...node, position: item.position } : node);+ }+ return next;+}diff --git a/components/shared/graph-focus.ts b/components/shared/graph-focus.tsnew file mode 100644index 00000000..e8feaf7c--- /dev/null+++ b/components/shared/graph-focus.ts@@ -0,0 +1,54 @@+export type GraphFocusEdge = { source: string; target: string };++type GraphFocusOptions = {+ depth?: number;+ maxNodes?: number;+ fallbackLimit?: number;+};++export function graphEntryNodeIds(nodeIds: string[], edges: GraphFocusEdge[], limit = 1): string[] {+ const visible = new Set(nodeIds);+ const incoming = new Set(+ edges+ .filter((edge) => visible.has(edge.source) && visible.has(edge.target))+ .map((edge) => edge.target),+ );+ const roots = nodeIds.filter((id) => !incoming.has(id));+ return (roots.length ? roots : nodeIds).slice(0, Math.max(1, limit));+}++/** Return a deterministic, bounded focus cluster around seeds using direct relationships in either direction. */+export function graphFocusClusterIds(+ nodeIds: string[],+ edges: GraphFocusEdge[],+ seedIds: string[] = [],+ options: GraphFocusOptions = {},+): string[] {+ if (!nodeIds.length) return [];+ const depth = Math.max(0, Math.floor(options.depth ?? 1));+ const maxNodes = Math.max(1, Math.floor(options.maxNodes ?? 12));+ const fallbackLimit = Math.max(1, Math.floor(options.fallbackLimit ?? 1));+ const visible = new Set(nodeIds);+ const seeds = [...new Set(seedIds)].filter((id) => visible.has(id));+ const initial = seeds.length ? seeds : graphEntryNodeIds(nodeIds, edges, fallbackLimit);+ const result: string[] = [];+ const seen = new Set<string>();+ let frontier = initial;++ for (let level = 0; level <= depth && frontier.length && result.length < maxNodes; level += 1) {+ const next: string[] = [];+ for (const id of frontier) {+ if (!visible.has(id) || seen.has(id)) continue;+ seen.add(id);+ result.push(id);+ if (result.length >= maxNodes) break;+ for (const edge of edges) {+ const neighbor = edge.source === id ? edge.target : edge.target === id ? edge.source : null;+ if (neighbor && visible.has(neighbor) && !seen.has(neighbor) && !next.includes(neighbor)) next.push(neighbor);+ }+ }+ frontier = next;+ }++ return result;+}diff --git a/components/shared/graph-node-shell.tsx b/components/shared/graph-node-shell.tsxnew file mode 100644index 00000000..ec11b630--- /dev/null+++ b/components/shared/graph-node-shell.tsx@@ -0,0 +1,22 @@+"use client";++import type { ComponentProps } from "react";+import { cn } from "@/lib/utils";++type GraphNodeShellProps = ComponentProps<"div"> & {+ selected?: boolean;+};++/** Domain-independent graph node chrome. Feature slices own handles, content and domain state. */+export function GraphNodeShell({ selected = false, className, ...props }: GraphNodeShellProps) {+ return (+ <div+ {...props}+ className={cn(+ "relative rounded-xl border bg-card p-3 shadow-sm transition-[box-shadow,border-color,opacity]",+ selected && "ring-2 ring-ring shadow-md",+ className,+ )}+ />+ );+}diff --git a/docs/README.md b/docs/README.mdindex c2e5b631..d6eaddda 100644--- a/docs/README.md+++ b/docs/README.md@@ -39,6 +39,7 @@ evidence and review freshness. The repository quality gate runs both automatical| [`PROJECT-MCP-CONNECTIONS.md`](./PROJECT-MCP-CONNECTIONS.md) | Named private connections, endpoint binding and identity for modular project MCPs || [`AUTOMATION-FLOWS.md`](./AUTOMATION-FLOWS.md) | Versioned project API/MCP flows, CLI, sessions, Add MCP, assets and limits || [`WORKFLOW-GRAPH.md`](./WORKFLOW-GRAPH.md) | Private server-native Workflow Graph v2 with n8n-core triggers/flow control, versions/history, variables, integrations, visual execution and automatic learning |+| [`SHARED-GRAPH-FOUNDATION.md`](./SHARED-GRAPH-FOUNDATION.md) | Canonical shared graph mechanics, feature adapters, ownership matrix and dense-graph Focus/Map interaction boundary || [`N8N-PARITY.md`](./N8N-PARITY.md) | Core n8n capability map across native Workflows, Organization, Integrations and the dedicated external n8n workspace || [`ORGANIZATION.md`](./ORGANIZATION.md) | Owner-private organization units, seats, reporting lines, live agent bindings, and workflow routing references || [`MCP-HOW-TO.md`](./MCP-HOW-TO.md) | Bahasa Indonesia onboarding: client connection, prompts, workflow, project MCP and troubleshooting |diff --git a/docs/SHARED-GRAPH-FOUNDATION.md b/docs/SHARED-GRAPH-FOUNDATION.mdnew file mode 100644index 00000000..a6c989ca--- /dev/null+++ b/docs/SHARED-GRAPH-FOUNDATION.md@@ -0,0 +1,46 @@+# Shared Graph Foundation++This document records the current ownership boundary for first-party MSO graph UI. It is an architecture map, not a universal graph domain model.++## Ownership matrix++| Capability | Canonical owner | Organization | Workflow | Session | Classification |+| --- | --- | --- | --- | --- | --- |+| Canvas / ReactFlow provider | `components/shared/graph-canvas.tsx` | consumer | consumer | via WorkflowCanvas | A shared |+| Pan / zoom / full fit / measured initial fit | `components/shared/graph-canvas.tsx` | consumer | consumer | consumer | A shared |+| Minimap | `components/shared/graph-canvas.tsx` | consumer | consumer | consumer when useful | A shared |+| Selection projection / box selection preservation | `components/shared/use-graph-projection.ts` | ProjectFlow | WorkflowCanvas | via WorkflowCanvas | A shared |+| Multi-select mechanics | `components/shared/graph-canvas.tsx` + projection hook | supported where feature allows | supported | selection-only | A shared + feature capability |+| Generic focus / direct-neighbor cluster | `components/shared/graph-focus.ts` | ProjectFlow adapter | Workflow seed adapter | Workflow seed adapter | A shared |+| Generic routed edge | `components/shared/graph-routed-edge.tsx`, `graph-route*.ts` | consumer | consumer | consumer | A shared |+| Generic node chrome | `components/shared/graph-node-shell.tsx` | Unit/Seat/Project content | Workflow content | Workflow semantic content | A shared |+| Collapsed custom/group projection | `components/shared/graph-custom-*.{ts,tsx}` | consumer | consumer | read-only projection if present | A shared |+| Organization graph layout | `frontend/slices/organization/lib/canvas-layout.ts` | owner | — | — | B feature-owned |+| Workflow entry seed semantics | `frontend/slices/workflows/lib/compact-focus.ts` | — | owner | session-root adapter | B feature-owned |+| Domain node rendering / handles | feature slice components | owner | owner | Workflow semantic adapter | B feature-owned |+| Inspector layout and fields | feature slice components | owner | owner | `workflow-session-details.tsx` | B feature-owned |+| Organization persistence | Organization API/actions | owner | — | — | B feature-owned |+| Workflow persistence / execution / run state | Workflow API/runtime | — | owner | read-only history input | B feature-owned |+| Session artifacts / terminal / save-as-workflow | `workflow-session-details.tsx` + session APIs | — | — | owner | B feature-owned |+| n8n iframe/auth/origin/sandbox | `frontend/slices/n8n/**` | — | — | — | C provider-specific |+| Legacy Organization projection helper | removed; superseded by shared projection | — | — | — | D obsolete |++## Adapter rule++Shared code owns graph mechanics only. Each feature transforms its domain data into the shared presentation contract and keeps persistence, execution, permissions, inspector fields and provider behavior in its own slice.++Session is intentionally not a separate graph implementation:++`SessionGraphView -> WorkflowCanvas(readOnly) -> GraphCanvas -> WorkflowSessionDetails`.++Read-only changes capabilities, not viewport, focus, selection or routing mechanics.++## Dense graph UX++Organization Project Flow defaults to Focus. The initial cluster is root-based when nothing is selected, then selected-node + direct relationships when a node is selected. Expand neighbors increases the bounded cluster. Map is the explicit full-topology mode.++Physical layout and viewport policy are separate concerns: layout provides coordinates; shared GraphCanvas decides what viewport cluster is readable and keeps full-fit available explicitly.++## Extraction rule++Move code into shared only when at least two real first-party consumers have the same semantic responsibility. Prefer a small shared primitive plus a feature adapter. Do not add Organization/Workflow/Session conditionals to shared code, and never move n8n provider-specific iframe/auth behavior into this foundation.diff --git a/frontend/slices/organization/components/organization-canvas.tsx b/frontend/slices/organization/components/organization-canvas.tsxindex b57788ec..3754bad1 100644--- a/frontend/slices/organization/components/organization-canvas.tsx+++ b/frontend/slices/organization/components/organization-canvas.tsx@@ -7,6 +7,7 @@ import type { OrganizationChart, OrganizationSeat, OrganizationSeatRuntime, Orgaimport { Badge } from "@/components/ui/badge";import { graphRoutedEdgeTypes } from "@/components/shared/graph-routed-edge";import { GraphCanvas } from "@/components/shared/graph-canvas";+import { GraphNodeShell } from "@/components/shared/graph-node-shell";import { useContainer } from "@/features/appshell";import { cn } from "@/lib/utils";import { organizationSeatLayout, organizationUnitLayout } from "../lib/canvas-layout";@@ -22,17 +23,17 @@ const statusClass: Record<OrganizationSeatRuntime["status"], string> = {};function UnitCard({ data, selected }: NodeProps<UnitNode>) {- return <div className={cn("relative w-[230px] rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring")}><Handle type="target" position={Position.Top} id="input" className="!size-2 !border-0 !bg-muted-foreground/50"/><Handle type="source" position={Position.Bottom} id="output" className="!size-2 !border-0 !bg-muted-foreground/50"/>+ return <GraphNodeShell selected={selected} className="w-[230px]"><Handle type="target" position={Position.Top} id="input" className="!size-2 !border-0 !bg-muted-foreground/50"/><Handle type="source" position={Position.Bottom} id="output" className="!size-2 !border-0 !bg-muted-foreground/50"/><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 line-clamp-2 break-words 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>{data.unit.projectFlow?.nodes.length ? <Badge variant="outline" className="text-[9px]">{data.unit.projectFlow.nodes.length} nodes</Badge> : null}</div>- </div>;+ </GraphNodeShell>;}function SeatCard({ data, selected }: NodeProps<SeatNode>) {const status = data.runtime?.status ?? "vacant";- return <div className={cn("relative w-[238px] rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring", data.external && "opacity-75")}><Handle type="target" position={Position.Top} id="input" className="!size-2 !border-0 !bg-muted-foreground/50"/><Handle type="source" position={Position.Bottom} id="output" className="!size-2 !border-0 !bg-muted-foreground/50"/>+ return <GraphNodeShell selected={selected} className={cn("w-[238px]", data.external && "opacity-75")}><Handle type="target" position={Position.Top} id="input" className="!size-2 !border-0 !bg-muted-foreground/50"/><Handle type="source" position={Position.Bottom} id="output" className="!size-2 !border-0 !bg-muted-foreground/50"/><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>;+ </GraphNodeShell>;}const nodeTypes = { unit: UnitCard, seat: SeatCard };@@ -82,7 +83,8 @@ export function OrganizationCanvas({ chart, runtime, unitId, selectedSeatId, onUonNodeClick={(_, node) => node.type === "unit" ? onUnitSelect(node.id) : onSeatSelect((node as SeatNode).data.seat)}onNodeDoubleClick={(_, node) => { if (node.type === "seat") onSeatOpen((node as SeatNode).data.seat); }}fitPadding={pane === "xs" || pane === "sm" ? 0.12 : pane === "md" ? 0.18 : 0.26}- initialFitNodeIds={nodes.slice(0, 6).map((node) => node.id)}+ compactFitNodeIds={selectedSeatId ? [selectedSeatId] : nodes.slice(0, 4).map((node) => node.id)}+ initialFitNodeIds={selectedSeatId ? [selectedSeatId] : nodes.slice(0, 6).map((node) => node.id)}initialFitMaxZoom={0.96}miniMapNodeColor={(node) => node.type === "unit" ? "var(--info)" : (() => {const status = (node as SeatNode).data.runtime?.status ?? "vacant";diff --git a/frontend/slices/organization/components/organization-view.tsx b/frontend/slices/organization/components/organization-view.tsxindex 67df8087..f6f048bb 100644--- a/frontend/slices/organization/components/organization-view.tsx+++ b/frontend/slices/organization/components/organization-view.tsx@@ -106,7 +106,7 @@ export function OrganizationView() {{currentUnit ? <Button size="icon" variant="ghost" className="size-8 shrink-0" onClick={() => chooseUnit("__all__")} aria-label="Back to organization overview"><ArrowLeft className="size-4"/></Button> : null}<div className="min-w-0 flex-1"><div className="flex min-w-0 items-center gap-2"><h2 className="truncate text-sm font-semibold">{currentUnit?.name ?? data.chart.name}</h2>{currentUnit ? <Badge variant="secondary" className="shrink-0">{currentUnit.kind}</Badge> : null}</div>- <p className="mt-0.5 hidden max-w-3xl text-[11px] leading-snug text-muted-foreground @min-[520px]:line-clamp-2">{currentUnit?.description || "Directory first for fast scanning. The map remains available when you need reporting or relationship topology."}</p>+ <p className="mt-0.5 hidden max-w-3xl text-[11px] leading-snug text-muted-foreground @min-[520px]:line-clamp-2 [@media(max-height:520px)]:!hidden">{currentUnit?.description || "Directory first for fast scanning. The map remains available when you need reporting or relationship topology."}</p></div></div><div className="flex shrink-0 gap-1">diff --git a/frontend/slices/organization/components/project-flow.tsx b/frontend/slices/organization/components/project-flow.tsxindex a60664d4..4344c452 100644--- a/frontend/slices/organization/components/project-flow.tsx+++ b/frontend/slices/organization/components/project-flow.tsx@@ -1,58 +1,76 @@"use client";import { useMemo, useRef, useState } from "react";-import { FileText, FolderKanban, Link2, Pencil, Plus, X } from "lucide-react";-import { Handle, MarkerType, Position, type Edge, type NodeProps } from "@xyflow/react";+import { FileText, FolderKanban, Link2, LocateFixed, Network, Pencil, Plus, X } from "lucide-react";+import { Handle, MarkerType, Position, type Edge, type Node, type NodeProps } from "@xyflow/react";import { useGraphProjection } from "@/components/shared/use-graph-projection";import { GraphCanvas } from "@/components/shared/graph-canvas";+import { GraphNodeShell } from "@/components/shared/graph-node-shell";+import { graphFocusClusterIds } from "@/components/shared/graph-focus";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";import { cn } from "@/lib/utils";-import { emptyOrganizationFlow, type OrganizationFlowAction } from "@/lib/contracts/organization-flow";+import { emptyOrganizationFlow, type OrganizationFlowAction, type OrganizationFlowNode } from "@/lib/contracts/organization-flow";import type { OrganizationUnit } from "@/lib/contracts/organization";-import { type ProjectCanvasNode as FlowNode } from "../lib/flow-projection";-import { projectCustomNodes, moveCustomNode, type CustomCanvasNode } from "@/components/shared/graph-custom-projection";+import { projectCustomNodes, moveGraphNodesWithCustomGroups, type CustomCanvasNode } from "@/components/shared/graph-custom-projection";import { GraphCustomControls } from "@/components/shared/graph-custom-controls";import { GraphCustomCard } from "@/components/shared/graph-custom-card";import { graphRoutedEdgeTypes } from "@/components/shared/graph-routed-edge";import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";import { ProjectFlowEditor, type FlowDraft } from "./project-flow-editor";+type FlowNode = Node<{ item: OrganizationFlowNode }, "project">;+type CanvasNode = FlowNode | CustomCanvasNode;+type ViewMode = "focus" | "map";+function ProjectCard({ data, selected }: NodeProps<FlowNode>) {const item = data.item;- return <div className={cn("w-60 rounded-xl border bg-card p-3 shadow-sm", selected && "ring-2 ring-ring", item.kind === "group" && "border-primary/50", item.kind === "note" && "border-dashed")}>+ return <GraphNodeShell selected={selected} className={cn("w-60", item.kind === "group" && "border-primary/50", item.kind === "note" && "border-dashed")}><Handle type="target" position={Position.Top} className="!size-3 !bg-muted-foreground"/><div className="flex items-start gap-2"><FolderKanban className="mt-0.5 size-4 shrink-0 text-muted-foreground"/><div className="min-w-0 flex-1"><div className="break-words text-sm font-semibold">{item.title}</div><p className="mt-1 line-clamp-2 break-words text-xs text-muted-foreground">{item.summary || "Open for details"}</p></div></div><div className="mt-2 flex gap-1"><Badge variant="secondary" className="text-[10px]">{item.kind}</Badge><Badge variant="outline" className="text-[10px]">{item.status}</Badge></div><Handle type="source" position={Position.Bottom} className="!size-3 !bg-muted-foreground"/>- </div>;+ </GraphNodeShell>;}const nodeTypes = { project: ProjectCard, customGroup: GraphCustomCard };-type CanvasNode = FlowNode | CustomCanvasNode;type Props = { unit: OrganizationUnit; onSave: (action: OrganizationFlowAction, data: Record<string, unknown>) => Promise<void> };export function ProjectFlow({ unit, onSave }: Props) {const flow = useMemo(() => unit.projectFlow ?? emptyOrganizationFlow(), [unit.projectFlow]);- const [query, setQuery] = useState(""), [selectedId, setSelectedId] = useState<string | null>(null), [focus, setFocus] = useState(false);+ const [query, setQuery] = useState(""), [selectedId, setSelectedId] = useState<string | null>(null);+ const [viewMode, setViewMode] = useState<ViewMode>("focus"), [focusDepth, setFocusDepth] = useState(1);const [draft, setDraft] = useState<FlowDraft | null>(null), [error, setError] = useState(""), [busy, setBusy] = useState(false);const groups = useMemo(() => flow.customNodes ?? [], [flow.customNodes]);const pending = useRef(false);+ const nodeIds = useMemo(() => flow.nodes.map((node) => node.id), [flow.nodes]);const visible = useMemo(() => {- const match = new Set(flow.nodes.filter((node) => focus && selectedId ? node.id === selectedId : `${node.title} ${node.summary} ${node.kind}`.toLowerCase().includes(query.toLowerCase())).map((node) => node.id));- const ids = new Set(match);- if (query || (focus && selectedId)) for (const edge of flow.edges) if (match.has(edge.source) || match.has(edge.target)) { ids.add(edge.source); ids.add(edge.target); }- return ids;- }, [flow, query, focus, selectedId]);+ const search = query.trim().toLowerCase();+ if (search) {+ const matches = flow.nodes+ .filter((node) => `${node.title} ${node.summary} ${node.kind}`.toLowerCase().includes(search))+ .map((node) => node.id);+ if (!matches.length) return new Set<string>();+ return new Set(graphFocusClusterIds(nodeIds, flow.edges, matches, { depth: 1, maxNodes: 36, fallbackLimit: 1 }));+ }+ if (viewMode === "map") return new Set(nodeIds);+ return new Set(graphFocusClusterIds(nodeIds, flow.edges, selectedId ? [selectedId] : [], {+ depth: focusDepth,+ maxNodes: focusDepth > 1 ? 24 : 12,+ fallbackLimit: 1,+ }));+ }, [flow.edges, flow.nodes, focusDepth, nodeIds, query, selectedId, viewMode]);const mapped = useMemo(() => {const base: FlowNode[] = flow.nodes.map((item) => ({ id: item.id, type: "project", position: item.position, data: { item } }));const lines: Edge[] = flow.edges.map((edge) => ({ ...edge, type: "routed", markerEnd: { type: MarkerType.ArrowClosed, width: 20, height: 20, color: "var(--muted-foreground)" }, style: { stroke: "var(--muted-foreground)" } }));- const result = projectCustomNodes(base, lines, groups, []);+ const result = projectCustomNodes(base, lines, groups, selectedId ? [selectedId] : []);const ids = new Set(result.nodes.filter((node) => node.type === "customGroup" ? node.data.group.nodeIds.some((id) => visible.has(id)) : visible.has(node.id)).map((node) => node.id));return { nodes: result.nodes.filter((node) => ids.has(node.id)), edges: result.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target)) };- }, [flow.nodes, flow.edges, groups, visible]);+ }, [flow.edges, flow.nodes, groups, selectedId, visible]);const { nodes, edges, onNodesChange, onEdgesChange, reset } = useGraphProjection<CanvasNode, Edge>(mapped);const selectedIds = nodes.filter((node) => node.selected).map((node) => node.id);- const selected = selectedIds.length <= 1 ? flow.nodes.find((node) => node.id === selectedId) : undefined;+ const selected = selectedIds.length <= 1 && selectedId && visible.has(selectedId) ? flow.nodes.find((node) => node.id === selectedId) : undefined;+ const viewportIds = nodes.map((node) => node.id).slice(0, viewMode === "map" && !query ? 0 : 12);+const save = async (action: OrganizationFlowAction, data: Record<string, unknown>) => {if (pending.current) throw new Error("A change is still saving. Try again after it completes.");pending.current = true; setBusy(true); setError("");@@ -63,42 +81,53 @@ export function ProjectFlow({ unit, onSave }: Props) {const quickSave = (action: OrganizationFlowAction, data: Record<string, unknown>) => { if (pending.current) return; void save(action, data).catch(() => reset()); };const changeGroups = (customNodes: GraphCustomNode[]) => { quickSave("flow_custom_nodes", { customNodes }); setSelectedId(null); };const move = (items: CanvasNode[]) => {- let moved = flow.nodes;- for (const item of items) { const group = groups.find((row) => row.id === item.id); moved = group ? moveCustomNode(moved, group, item.position) : moved.map((node) => node.id === item.id ? { ...node, position: item.position } : node); }+ const moved = moveGraphNodesWithCustomGroups(flow.nodes, groups, items);const positions = moved.filter((node, i) => node.position !== flow.nodes[i].position).map(({ id, position }) => ({ id, position }));if (positions.length) quickSave("flow_nodes_move", { positions });};- return <div data-slot="organization-project-flow" className="flex h-full min-h-0 flex-col">- <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-2">- <div className="min-w-0 flex-1"><div className="truncate text-sm font-medium">{flow.title}</div><p className="text-[10px] text-muted-foreground">{flow.nodes.length} nodes · {flow.edges.length} connections · {busy ? "Saving…" : "Stored in this organization"}</p></div>- <Button variant="outline" size="sm" onClick={() => setDraft({ kind: "notes" })}><FileText className="mr-1 size-3.5"/>Notes</Button>- <Button variant="outline" size="sm" disabled={flow.nodes.length < 2 || busy} onClick={() => setDraft({ kind: "edge" })}><Link2 className="mr-1 size-3.5"/>Connect</Button>- <Button size="sm" disabled={busy} onClick={() => setDraft({ kind: "node" })}><Plus className="mr-1 size-3.5"/>Node</Button>- <div className="flex w-full items-center gap-2"><Input aria-label="Search project flow" className="h-8 min-w-0 flex-1" placeholder="Search projects, activities, or notes…" value={query} onChange={(e) => setQuery(e.target.value)}/><Button size="sm" variant={focus ? "secondary" : "outline"} disabled={!selected} onClick={() => setFocus(!focus)}>Focus</Button></div>+ const selectNode = (id: string | null) => { setSelectedId(id); if (id && viewMode === "focus") setFocusDepth(1); };++ return <div data-slot="organization-project-flow" className="@container flex h-full min-h-0 flex-col">+ <div className="flex shrink-0 flex-wrap items-center gap-2 border-b px-3 py-2 [@media(max-height:520px)]:flex-nowrap [@media(max-height:520px)]:py-1">+ <div className="min-w-0 flex-1 [@media(max-height:520px)]:hidden"><div className="truncate text-sm font-medium">{flow.title}</div><p className="text-[10px] text-muted-foreground">{flow.nodes.length} nodes · {flow.edges.length} connections · {visible.size} visible · {busy ? "Saving…" : "Stored in this organization"}</p></div>+ <Button variant="outline" size="sm" className="[@media(max-height:520px)]:size-8 [@media(max-height:520px)]:px-0" onClick={() => setDraft({ kind: "notes" })}><FileText className="mr-1 size-3.5 [@media(max-height:520px)]:mr-0"/><span className="[@media(max-height:520px)]:sr-only">Notes</span></Button>+ <Button variant="outline" size="sm" className="[@media(max-height:520px)]:size-8 [@media(max-height:520px)]:px-0" disabled={flow.nodes.length < 2 || busy} onClick={() => setDraft({ kind: "edge" })}><Link2 className="mr-1 size-3.5 [@media(max-height:520px)]:mr-0"/><span className="[@media(max-height:520px)]:sr-only">Connect</span></Button>+ <Button size="sm" className="[@media(max-height:520px)]:size-8 [@media(max-height:520px)]:px-0" disabled={busy} onClick={() => setDraft({ kind: "node" })}><Plus className="mr-1 size-3.5 [@media(max-height:520px)]:mr-0"/><span className="[@media(max-height:520px)]:sr-only">Node</span></Button>+ <div className="flex w-full min-w-0 flex-wrap items-center gap-2 [@media(max-height:520px)]:w-auto [@media(max-height:520px)]:flex-1 [@media(max-height:520px)]:flex-nowrap">+ <Input aria-label="Search project flow" className="h-8 min-w-40 flex-1 [@media(max-height:520px)]:min-w-24" placeholder="Search projects, activities, or notes…" value={query} onChange={(event) => setQuery(event.target.value)}/>+ <div className="flex shrink-0 items-center rounded-lg border p-0.5">+ <Button size="sm" variant={viewMode === "focus" ? "secondary" : "ghost"} className="h-7" onClick={() => setViewMode("focus")}><LocateFixed className="mr-1 size-3.5"/>Focus</Button>+ <Button size="sm" variant={viewMode === "map" ? "secondary" : "ghost"} className="h-7" onClick={() => setViewMode("map")}><Network className="mr-1 size-3.5"/>Map</Button>+ </div>+ {viewMode === "focus" && !query ? <Button size="sm" variant="outline" className="h-8" onClick={() => setFocusDepth((depth) => depth === 1 ? 2 : 1)}>{focusDepth === 1 ? "Expand neighbors" : "Collapse cluster"}</Button> : null}+ </div></div>- <GraphCustomControls groups={groups} selectedIds={selectedIds} nodeIds={flow.nodes.map((node) => node.id)} onChange={changeGroups} disabled={busy}/>+ {groups.length || selectedIds.length ? <GraphCustomControls groups={groups} selectedIds={selectedIds} nodeIds={flow.nodes.map((node) => node.id)} onChange={changeGroups} disabled={busy}/> : null}{error ? <div role="alert" className="shrink-0 border-b px-3 py-2 text-xs text-destructive">{error} Refresh the organization before retrying a conflicting change.</div> : null}- <div className="relative min-h-0 flex-1">- {flow.nodes.length ? <GraphCanvas<CanvasNode, Edge>- ariaLabel="Organization project flow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}- nodesDraggable={!busy} nodesConnectable={!busy} deleteKeyCode={null} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange}- onNodeClick={(event, node) => { if (!event.ctrlKey && !event.metaKey) setSelectedId(node.type === "customGroup" ? null : node.id); }} onNodeDoubleClick={(_, node) => { if (node.type === "customGroup") changeGroups(groups.map((group) => group.id === node.id ? { ...group, collapsed: false } : group)); else setDraft({ kind: "node", node: (node as FlowNode).data.item }); }}- onPaneClick={() => { setSelectedId(null); setFocus(false); }}- onNodeDragStop={(_, node, items) => move(items.length ? items : [node])} onSelectionDragStop={(_, items) => move(items)}- onConnect={(connection) => { if (flow.nodes.some((n) => n.id === connection.source) && flow.nodes.some((n) => n.id === connection.target)) quickSave("flow_edge_upsert", { edge: { source: connection.source, target: connection.target, label: "" } }); }}- onEdgeClick={(_, edge) => setDraft({ kind: "edge", edge: flow.edges.find((item) => item.id === edge.id) })}- compactFitNodeIds={selected ? [selected.id] : nodes.slice(0, 2).map((node) => node.id)}- initialFitNodeIds={nodes.slice(0, 6).map((node) => node.id)}- initialFitMaxZoom={0.96}- /> : <div className="grid h-full place-items-center p-6"><div className="max-w-sm text-center"><FolderKanban className="mx-auto mb-3 size-7 text-muted-foreground"/><h3 className="font-medium">Project flow inside {unit.name}</h3><p className="mt-2 text-sm text-muted-foreground">Add projects, activities, notes and connections here. The organization overview stays compact.</p><Button className="mt-4" onClick={() => setDraft({ kind: "node" })}>Add first node</Button></div></div>}- {selected ? <div className="absolute inset-x-2 top-2 z-10 max-h-[calc(100%-1rem)] overflow-y-auto rounded-xl border bg-popover p-3 shadow-lg @min-[700px]:left-auto @min-[700px]:right-3 @min-[700px]:w-80">- <div className="flex items-start gap-2"><h3 className="min-w-0 flex-1 break-words text-sm font-semibold">{selected.title}</h3><Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Close node details" onClick={() => setSelectedId(null)}><X className="size-4"/></Button></div>+ <div className={cn("relative grid min-h-0 flex-1 grid-cols-1", selected && "@min-[920px]:grid-cols-[minmax(0,1fr)_320px]")}>+ <div className="relative min-h-0 min-w-0">+ {flow.nodes.length ? nodes.length ? <GraphCanvas<CanvasNode, Edge>+ ariaLabel="Organization project flow canvas" nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}+ nodesDraggable={!busy} nodesConnectable={!busy} deleteKeyCode={null} onNodesChange={onNodesChange} onEdgesChange={onEdgesChange}+ onNodeClick={(event, node) => { if (!event.ctrlKey && !event.metaKey) selectNode(node.type === "customGroup" ? null : node.id); }} onNodeDoubleClick={(_, node) => { if (node.type === "customGroup") changeGroups(groups.map((group) => group.id === node.id ? { ...group, collapsed: false } : group)); else setDraft({ kind: "node", node: (node as FlowNode).data.item }); }}+ onPaneClick={() => selectNode(null)}+ onNodeDragStop={(_, node, items) => move(items.length ? items : [node])} onSelectionDragStop={(_, items) => move(items)}+ onConnect={(connection) => { if (flow.nodes.some((node) => node.id === connection.source) && flow.nodes.some((node) => node.id === connection.target)) quickSave("flow_edge_upsert", { edge: { source: connection.source, target: connection.target, label: "" } }); }}+ onEdgeClick={(_, edge) => setDraft({ kind: "edge", edge: flow.edges.find((item) => item.id === edge.id) })}+ compactFitNodeIds={selected ? [selected.id] : nodes.slice(0, 4).map((node) => node.id)}+ initialFitNodeIds={viewportIds}+ initialFitMaxZoom={0.96}+ /> : <div className="grid h-full place-items-center p-6 text-center text-sm text-muted-foreground">No nodes match this search.</div>+ : <div className="grid h-full place-items-center p-6"><div className="max-w-sm text-center"><FolderKanban className="mx-auto mb-3 size-7 text-muted-foreground"/><h3 className="font-medium">Project flow inside {unit.name}</h3><p className="mt-2 text-sm text-muted-foreground">Add projects, activities, notes and connections here. The organization overview stays compact.</p><Button className="mt-4" onClick={() => setDraft({ kind: "node" })}>Add first node</Button></div></div>}+ </div>+ {selected ? <aside className="absolute inset-x-2 top-2 z-10 max-h-[calc(100%-1rem)] overflow-y-auto rounded-xl border bg-popover p-3 shadow-lg @min-[920px]:static @min-[920px]:inset-auto @min-[920px]:max-h-none @min-[920px]:rounded-none @min-[920px]:border-y-0 @min-[920px]:border-r-0 @min-[920px]:border-l @min-[920px]:bg-card/60 @min-[920px]:shadow-none">+ <div className="flex items-start gap-2"><h3 className="min-w-0 flex-1 break-words text-sm font-semibold">{selected.title}</h3><Button size="icon" variant="ghost" className="size-7 shrink-0" aria-label="Close node details" onClick={() => selectNode(null)}><X className="size-4"/></Button></div><div className="mt-2 flex gap-1"><Badge variant="secondary">{selected.kind}</Badge><Badge variant="outline">{selected.status}</Badge></div>{selected.summary ? <p className="mt-3 whitespace-pre-wrap break-words text-sm">{selected.summary}</p> : null}{selected.notes ? <div className="mt-3 whitespace-pre-wrap break-words text-xs leading-relaxed text-muted-foreground">{selected.notes}</div> : null}{selected.projectRef ? <p className="mt-3 break-all text-xs">Project reference: {selected.projectRef}</p> : null}<Button className="mt-3 w-full" size="sm" onClick={() => setDraft({ kind: "node", node: selected })}><Pencil className="mr-2 size-3"/>Edit node</Button>- </div> : null}+ </aside> : null}</div><ProjectFlowEditor draft={draft} flow={flow} onClose={() => setDraft(null)} onSave={save}/></div>;diff --git a/frontend/slices/organization/lib/flow-projection.test.ts b/frontend/slices/organization/lib/flow-projection.test.tsdeleted file mode 100644index d05aef80..00000000--- a/frontend/slices/organization/lib/flow-projection.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { describe, expect, it } from "vitest";-import type { OrganizationFlowNode } from "@/lib/contracts/organization-flow";-import { projectCanvasNodes, updateFlowProjection, type FlowProjection } from "./flow-projection";--const source = (): OrganizationFlowNode[] => [{ id: "one", title: "Project", kind: "project", status: "unconfirmed", summary: "", notes: "", position: { x: 0, y: 0 } }];--describe("organization flow canvas projection", () => {- it("retains measured dimensions required for edges, not only drag positions", () => {- const items = source();- const state = updateFlowProjection(items, { nodes: [] }, [{ type: "dimensions", id: "one", dimensions: { width: 240, height: 95 } }]);- expect(projectCanvasNodes(items, state)[0].measured).toEqual({ width: 240, height: 95 });- const dragged = updateFlowProjection(items, state, [{ type: "position", id: "one", position: { x: 90, y: 40 } }]);- expect(dragged.nodes[0].position).toEqual({ x: 90, y: 40 });- expect(dragged.nodes[0].measured).toEqual({ width: 240, height: 95 });- });-- it("uses refreshed backend positions rather than replaying a stale drag", () => {- const items = source();- const state = updateFlowProjection(items, { nodes: [] }, [{ type: "position", id: "one", position: { x: 90, y: 40 } }]);- const refreshed = source(); refreshed[0].title = "Server edit";- expect(projectCanvasNodes(refreshed, state)[0]).toMatchObject({ position: { x: 0, y: 0 }, data: { item: { title: "Server edit" } } });- });-- it("does not copy canvas-only measurements to persisted source data", () => {- const items = source();- const state: FlowProjection = updateFlowProjection(items, { nodes: [] }, [{ type: "dimensions", id: "one", dimensions: { width: 240, height: 95 } }]);- expect(items).toEqual(source());- expect(projectCanvasNodes([], state)).toEqual([]);- expect(projectCanvasNodes(source(), state)[0].measured).toEqual({ width: 240, height: 95 });- });-});diff --git a/frontend/slices/organization/lib/flow-projection.ts b/frontend/slices/organization/lib/flow-projection.tsdeleted file mode 100644index dc8a4801..00000000--- a/frontend/slices/organization/lib/flow-projection.ts+++ /dev/null@@ -1,20 +0,0 @@-import { applyNodeChanges, type Node, type NodeChange } from "@xyflow/react";-import type { OrganizationFlowNode } from "@/lib/contracts/organization-flow";--export type ProjectCanvasNode = Node<{ item: OrganizationFlowNode }, "project">;-export type FlowProjection = { source?: OrganizationFlowNode[]; nodes: ProjectCanvasNode[] };--/** API positions are authoritative; measured dimensions belong only to the canvas. */-export function projectCanvasNodes(source: OrganizationFlowNode[], projection: FlowProjection): ProjectCanvasNode[] {- if (projection.source === source) return projection.nodes;- const previous = new Map(projection.nodes.map((node) => [node.id, node]));- return source.map((item) => ({- id: item.id, type: "project", position: item.position, data: { item },- measured: previous.get(item.id)?.measured,- }));-}--/** Retain dimension changes as well as drags, so React Flow can resolve edge handles. */-export function updateFlowProjection(source: OrganizationFlowNode[], previous: FlowProjection, changes: NodeChange<ProjectCanvasNode>[]): FlowProjection {- return { source, nodes: applyNodeChanges(changes, projectCanvasNodes(source, previous)) };-}diff --git a/frontend/slices/organization/project-flow-ui.test.ts b/frontend/slices/organization/project-flow-ui.test.tsnew file mode 100644index 00000000..1af9012d--- /dev/null+++ b/frontend/slices/organization/project-flow-ui.test.ts@@ -0,0 +1,21 @@+import { readFileSync } from "node:fs";+import { describe, expect, it } from "vitest";++const source = readFileSync(new URL("./components/project-flow.tsx", import.meta.url), "utf8");++describe("Organization project-flow UX contract", () => {+ it("starts dense project flows in bounded Focus mode and keeps Map explicit", () => {+ expect(source).toContain('useState<ViewMode>("focus")');+ expect(source).toContain('viewMode === "map"');+ expect(source).toContain('maxNodes: focusDepth > 1 ? 24 : 12');+ expect(source).toContain("fallbackLimit: 1");+ expect(source).toContain(">Map</Button>");+ expect(source).toContain("Expand neighbors");+ expect(source).toContain("Collapse cluster");+ });++ it("moves selected details into a static side inspector on roomy panes", () => {+ expect(source).toContain('@min-[920px]:grid-cols-[minmax(0,1fr)_320px]');+ expect(source).toContain("@min-[920px]:static");+ });+});diff --git a/frontend/slices/workflows/components/workflow-canvas.tsx b/frontend/slices/workflows/components/workflow-canvas.tsxindex 99d3f84f..8f77ab4b 100644--- a/frontend/slices/workflows/components/workflow-canvas.tsx+++ b/frontend/slices/workflows/components/workflow-canvas.tsx@@ -9,8 +9,10 @@ import { useGraphProjection } from "@/components/shared/use-graph-projection";import { GraphCanvas } from "@/components/shared/graph-canvas";import { GraphCustomControls } from "@/components/shared/graph-custom-controls";import { GraphCustomCard } from "@/components/shared/graph-custom-card";-import { projectCustomNodes, moveCustomNode, type CustomCanvasNode } from "@/components/shared/graph-custom-projection";+import { projectCustomNodes, moveGraphNodesWithCustomGroups, type CustomCanvasNode } from "@/components/shared/graph-custom-projection";import { graphRoutedEdgeTypes } from "@/components/shared/graph-routed-edge";+import { graphFocusClusterIds } from "@/components/shared/graph-focus";+import { GraphNodeShell } from "@/components/shared/graph-node-shell";import type { GraphCustomNode } from "@/lib/contracts/graph-custom-nodes";import { compactWorkflowFocusIds } from "../lib/compact-focus";import { cn } from "@/lib/utils";@@ -35,14 +37,14 @@ function nodeMetrics(node:WorkflowGraphNode){function WorkflowNodeCard({data,selected}:NodeProps<FlowNode>){const{node,state}=data,handles=sourceHandles(node),metrics=nodeMetrics(node),semantic=node.config.sessionStep===true||node.config.sessionRoot===true;const actionCount=typeof node.config.actionCount==="number"?node.config.actionCount:undefined,summary=typeof node.config.summary==="string"?node.config.summary:undefined;- return <div className={cn("relative rounded-xl border bg-card px-3 py-3 shadow-sm transition-shadow",semantic?"w-[250px]":"w-[200px]",selected&&"ring-2 ring-ring shadow-md",state==="failed"&&"border-destructive ring-1 ring-destructive",state==="running"&&"border-primary ring-1 ring-primary",["skipped","blocked"].includes(state??"")&&"opacity-55",node.disabled&&"opacity-50")} style={{minHeight:metrics.height}}>+ return <GraphNodeShell selected={selected} className={cn(semantic?"w-[250px]":"w-[200px]",state==="failed"&&"border-destructive ring-1 ring-destructive",state==="running"&&"border-primary ring-1 ring-primary",["skipped","blocked"].includes(state??"")&&"opacity-55",node.disabled&&"opacity-50")} style={{minHeight:metrics.height}}>{canInput(node)?<Handle type="target" position={Position.Left} id="input" className="!size-3.5 !border-2 !border-background !bg-muted-foreground"/>:null}<div className={cn("text-xs font-semibold",semantic?"line-clamp-2 leading-4":"truncate")}>{node.name}</div><div className="mt-1 flex items-center gap-1.5 text-[10px] uppercase tracking-wide text-muted-foreground"><span>{node.type.replaceAll("_"," ")}{state?` · ${state}`:""}</span>{actionCount!==undefined?<span className="rounded bg-muted px-1.5 py-0.5 normal-case tracking-normal">{actionCount} actions</span>:null}</div>{summary?<p className="mt-1.5 line-clamp-2 text-[10px] leading-4 text-muted-foreground">{summary}</p>:null}{canOutput(node)?handles.map((handle,index)=><div key={handle??"output"} className="absolute right-0 flex translate-x-1/2 items-center" style={{top:38+index*20}}>{handle?<span className="pointer-events-none absolute right-4 whitespace-nowrap pr-1 text-[8px] text-muted-foreground">{handle}</span>:null}<Handle type="source" position={Position.Right} id={handle??"output"} className="!relative !right-auto !top-auto !size-3.5 !translate-x-0 !translate-y-0 !border-2 !border-background !bg-muted-foreground"/></div>):null}{canError(node)?<Handle type="source" position={Position.Bottom} id="error" className="!size-3 !border-2 !border-background !bg-destructive"/>:null}- </div>;+ </GraphNodeShell>;}const nodeTypes={workflow:WorkflowNodeCard, customGroup:GraphCustomCard};type CanvasNode = FlowNode | CustomCanvasNode;@@ -63,14 +65,14 @@ export function WorkflowCanvas({graph,selectedId,onSelect,onMove,onMoveMany,onCuconst {nodes,edges,onNodesChange,onEdgesChange}=useGraphProjection<CanvasNode,FlowEdge>(mapped);const selectedIds=nodes.filter((node)=>node.selected).map((node)=>node.id);const changeGroups=(next:GraphCustomNode[])=>{onCustomNodes?.(next);onSelect(null);};- const move=(items:CanvasNode[])=>{let next=graph.nodes;for(const item of items){const group=groups.find((g)=>g.id===item.id);next=group?moveCustomNode(next,group,item.position):next.map((n)=>n.id===item.id?{...n,position:item.position}:n);}if(onMoveMany)onMoveMany(next);else for(const item of items)onMove(item.id,item.position);};+ const move=(items:CanvasNode[])=>{const next=moveGraphNodesWithCustomGroups(graph.nodes,groups,items);if(onMoveMany)onMoveMany(next);else for(const item of items)onMove(item.id,item.position);};const connect=(connection:Connection)=>{if(!graph.nodes.some((n)=>n.id===connection.source)||!graph.nodes.some((n)=>n.id===connection.target)||connection.source===connection.target)return;const handle=connection.sourceHandle&&connection.sourceHandle!=="output"?connection.sourceHandle:undefined;onConnect(connection.source!,connection.target!,handle);};const visibleIds=useMemo(()=>new Set(nodes.map((node)=>node.id)),[nodes]);- const rootFocusIds=useMemo(()=>compactWorkflowFocusIds(graph.nodes,groups,visibleIds,readOnly?9:2),[graph.nodes,groups,readOnly,visibleIds]);- const compactIds=rootFocusIds.length?rootFocusIds:(readOnly?nodes.slice(0,9):nodes.slice(0,2)).map((node)=>node.id);+ const rootFocusIds=useMemo(()=>compactWorkflowFocusIds(graph.nodes,groups,visibleIds,readOnly?2:1),[graph.nodes,groups,readOnly,visibleIds]);+ const compactIds=graphFocusClusterIds(nodes.map((node)=>node.id),edges,selectedId?[selectedId]:rootFocusIds,{depth:1,maxNodes:readOnly?12:8,fallbackLimit:readOnly?2:1});return <div className="flex h-full min-h-0 flex-col">{!readOnly&&onCustomNodes?<GraphCustomControls groups={groups} selectedIds={selectedIds} nodeIds={graph.nodes.map((n)=>n.id)} onChange={changeGroups}/>:null}- <div className="min-h-0 flex-1"><GraphCanvas<CanvasNode,FlowEdge> ariaLabel="Workflow canvas" showMinimap={!readOnly} nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}+ <div className="min-h-0 flex-1"><GraphCanvas<CanvasNode,FlowEdge> ariaLabel="Workflow canvas" showMinimap={nodes.length > 3} nodes={nodes} edges={edges} nodeTypes={nodeTypes} edgeTypes={graphRoutedEdgeTypes}onNodesChange={onNodesChange} onEdgesChange={onEdgesChange} onConnect={readOnly?undefined:connect}onPaneClick={()=>{onSelect(null);}}onNodeClick={(event,item)=>{if(event.ctrlKey||event.metaKey)return;onSelect(item.type==="customGroup"?null:item.id);}}diff --git a/frontend/slices/workflows/session-graph-ui.test.ts b/frontend/slices/workflows/session-graph-ui.test.tsindex 82bcbe0b..dae1ed51 100644--- a/frontend/slices/workflows/session-graph-ui.test.ts+++ b/frontend/slices/workflows/session-graph-ui.test.ts@@ -45,7 +45,8 @@ describe("Workflow session graph UI contract", () => {expect(sessionDetails).toContain("Self-improve");expect(workflowApp).toContain("saveSessionWorkflowDraft");expect(workflowApp).toContain("listWorkflowLearning");- expect(workflowCanvas).toContain('showMinimap={!readOnly}');+ expect(workflowCanvas).toContain('showMinimap={nodes.length > 3}');+ expect(workflowCanvas).not.toContain('showMinimap={!readOnly}');});it("gives the desktop session library enough width and lets labels wrap instead of clipping", () => {diff --git a/scripts/e2e/graph-custom.mjs b/scripts/e2e/graph-custom.mjsindex 9e41dc61..a2eb244f 100644--- a/scripts/e2e/graph-custom.mjs+++ b/scripts/e2e/graph-custom.mjs@@ -35,6 +35,7 @@ try {let saved = chart.units.find((u) => u.id === "custom-test").projectFlow;expect(saved.nodes).toEqual(orgNodes); expect(saved.edges).toEqual(orgEdges); expect(saved.customNodes[0].nodeIds.sort()).toEqual(["a", "b"]);await openOrg(); await expect(orgCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);+ await page.getByRole("button", { name: "Map", exact: true }).click();await expect(orgCanvas.locator(".react-flow__edge")).toHaveCount(1);const customCard = orgCanvas.locator(".react-flow__node-customGroup");await page.waitForTimeout(350);@@ -53,6 +54,7 @@ try {await expect.poll(async () => (await api("/api/v1/organization")).body.chart.units.find((u) => u.id === "custom-test").projectFlow.customNodes).toEqual([]);await openOrg(); await select(orgCanvas, ["a"]); await createGroup("Single custom");await expect(orgCanvas.locator(".react-flow__node-customGroup")).toHaveCount(1);+ await page.getByRole("button", { name: "Map", exact: true }).click();await orgCanvas.locator(".react-flow__node-customGroup").dblclick();await expect(orgCanvas.locator(".react-flow__node-project")).toHaveCount(3);await expect(orgCanvas.locator('[data-routing-state="clear"]')).toHaveCount(2);diff --git a/scripts/e2e/organization-flow.mjs b/scripts/e2e/organization-flow.mjsindex de41481f..7437c5ec 100644--- a/scripts/e2e/organization-flow.mjs+++ b/scripts/e2e/organization-flow.mjs@@ -58,6 +58,7 @@ try {await page.getByLabel("Relationship", { exact: true }).fill("supports");await page.getByRole("button", { name: "Save", exact: true }).click();await expect(page.getByRole("heading", { name: "New edge", exact: true })).toBeHidden();+ await expect(page.locator('[data-slot="dialog-overlay"]')).toHaveCount(0);const canvas = page.getByRole("application", { name: "Organization project flow canvas", exact: true });await expect(canvas.locator(".react-flow__edge")).toHaveCount(1);await expect(canvas.locator(".react-flow__edge-path")).toHaveAttribute("marker-end", /url/);@@ -119,6 +120,61 @@ try {const deleted = await call({ action: "flow_node_delete", expected_revision: chart.revision, data: { unitId: "flow-workspace", id: first } });expect(deleted.status).toBe(200);expect(deleted.body.chart.units.find((u) => u.id === "flow-workspace").projectFlow.edges).toEqual([]);++ // Dense acceptance: Focus is the default task view; Map is an explicit full-topology action.+ chart = deleted.body.chart;+ const denseNodes = Array.from({ length: 36 }, (_, index) => {+ const cluster = Math.floor(index / 12);+ const local = index % 12;+ return {+ id: `dense-${index + 1}`,+ title: `Dense ${String.fromCharCode(65 + cluster)}${local + 1}`,+ kind: local === 0 ? "group" : "project",+ status: "active",+ summary: `Cluster ${cluster + 1} relationship node`,+ position: { x: cluster * 2500 + (local % 4) * 320, y: Math.floor(local / 4) * 210 },+ };+ });+ const denseEdges = [];+ for (let cluster = 0; cluster < 3; cluster += 1) {+ const start = cluster * 12;+ for (let local = 1; local < 12; local += 1) {+ denseEdges.push({ id: `dense-edge-${cluster}-${local}`, source: `dense-${start + local}`, target: `dense-${start + local + 1}`, label: "depends on" });+ }+ }+ const dense = await call({+ action: "flow_replace",+ expected_revision: chart.revision,+ data: { unitId: "flow-workspace", flow: { version: 1, title: "Dense Organization Flow", notes: "36-node visual acceptance fixture", nodes: denseNodes, edges: denseEdges } },+ });+ expect(dense.status).toBe(200);+ chart = dense.body.chart;++ for (const viewport of [{ width: 1363, height: 936 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {+ await page.setViewportSize(viewport);+ await open();+ const denseCanvas = page.getByRole("application", { name: "Organization project flow canvas", exact: true });+ await expect(denseCanvas).toBeVisible();+ const feature = page.locator('[data-slot="organization-feature"]');+ expect(await feature.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true);++ const focusedNodes = denseCanvas.locator(".react-flow__node");+ await expect.poll(async () => focusedNodes.count()).toBeGreaterThan(0);+ expect(await focusedNodes.count()).toBeLessThan(36);+ const focusedBox = await focusedNodes.first().boundingBox();+ expect(focusedBox?.width ?? 0).toBeGreaterThan(viewport.width < 700 ? 120 : 145);++ if (process.env.MSO_SCREENSHOT_DIR) {+ await mkdir(process.env.MSO_SCREENSHOT_DIR, { recursive: true });+ await page.screenshot({ path: path.join(process.env.MSO_SCREENSHOT_DIR, `dense-organization-flow-${viewport.width}x${viewport.height}.png`), fullPage: false });+ }++ await page.getByRole("button", { name: "Map", exact: true }).click();+ await expect(denseCanvas.locator(".react-flow__node")).toHaveCount(36);+ await page.getByRole("button", { name: "Focus", exact: true }).click();+ await expect.poll(async () => denseCanvas.locator(".react-flow__node").count()).toBeLessThan(36);+ }+expect(errors).toEqual([]);- console.log("PASS: compact overview; internal node create/edit/connect/drag; visible directional edges after reload; multiline notes >16 KiB; reload persistence; real MCP mutation; stale revision/cross-unit/viewer/read-scope refusal; 3 responsive viewports; cascade delete; no browser errors.");+ console.log("PASS: compact overview; internal node create/edit/connect/drag; visible directional edges after reload; multiline notes >16 KiB; reload persistence; real MCP mutation; stale revision/cross-unit/viewer/read-scope refusal; cascade delete; dense 36-node Focus/Map acceptance at desktop/portrait/landscape; no browser errors.");} finally { await browser?.close(); await fixture.close(); }diff --git a/scripts/graph-custom-routing.test.ts b/scripts/graph-custom-routing.test.tsindex 79ddf56c..4c7e0a79 100644--- a/scripts/graph-custom-routing.test.ts+++ b/scripts/graph-custom-routing.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";import { parseGraphCustomNodes, pruneGraphCustomNodes } from "../lib/contracts/graph-custom-nodes";-import { projectCustomNodes, moveCustomNode } from "../components/shared/graph-custom-projection";+import { projectCustomNodes, moveCustomNode, moveGraphNodesWithCustomGroups } from "../components/shared/graph-custom-projection";import { orthogonalRoute, segmentBlocked, routePath } from "../components/shared/graph-route";import { parseWorkflowGraphDefinition } from "../lib/workflow/graph-schema";import { changeOrganizationFlow } from "../lib/agent/organization-flow-mutations";@@ -31,6 +31,15 @@ describe("custom node contract", () => {expect(result.edges[0]).toMatchObject({ source: group.id, target: second.id, sourceHandle: "out-boundary", targetHandle: "in-boundary" });expect(projectCustomNodes([], [], [group], []).nodes).toEqual([]);});+ it("applies mixed normal/group canvas moves through one shared helper", () => {+ const moved = moveGraphNodesWithCustomGroups(nodes, [group], [+ { id: group.id, position: { x: 100, y: 200 } },+ { id: "c", position: { x: 900, y: 300 } },+ ]);+ expect(moved[0].position).toEqual({ x: 100, y: 200 });+ expect(moved[1].position).toEqual({ x: 400, y: 260 });+ expect(moved[2].position).toEqual({ x: 900, y: 300 });+ });it("moves members together and only removes grouping on ungroup", () => {const moved = moveCustomNode(nodes, group, { x: 100, y: 200 });expect(moved[0].position).toEqual({ x: 100, y: 200 }); expect(moved[1].position).toEqual({ x: 400, y: 260 }); expect(moved[2]).toBe(nodes[2]);diff --git a/scripts/graph-fit.test.ts b/scripts/graph-fit.test.tsindex 305115f6..37bfcbc5 100644--- a/scripts/graph-fit.test.ts+++ b/scripts/graph-fit.test.ts@@ -15,6 +15,12 @@ describe("readable measured graph viewport", () => {expect(compactGraphViewport(0, 0)).toBe(false);expect(compactGraphViewport(826, 0)).toBe(false);});+ it("focuses selected nodes explicitly without changing full-fit semantics", () => {+ const source = readFileSync("components/shared/graph-canvas.tsx", "utf8");+ expect(source).toContain('aria-label="Focus selection"');+ expect(source).toContain('event.shiftKey && selectedNodes.length');+ expect(source).toContain('title="Fit complete graph (F)"');+ });it("waits for node measurements and avoids competing initial fit controllers", () => {const source = readFileSync("components/shared/graph-canvas.tsx", "utf8");expect(source).toContain("useNodesInitialized()");diff --git a/scripts/graph-focus.test.ts b/scripts/graph-focus.test.tsnew file mode 100644index 00000000..ed336d37--- /dev/null+++ b/scripts/graph-focus.test.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";+import { graphEntryNodeIds, graphFocusClusterIds } from "../components/shared/graph-focus";++describe("shared graph focus", () => {+ it("uses graph roots as the deterministic fallback focus", () => {+ const nodes = ["root", "a", "b"];+ const edges = [{ source: "root", target: "a" }, { source: "a", target: "b" }];+ expect(graphEntryNodeIds(nodes, edges, 2)).toEqual(["root"]);+ expect(graphFocusClusterIds(nodes, edges)).toEqual(["root", "a"]);+ });++ it("includes direct relationships in both directions and respects depth", () => {+ const nodes = ["a", "b", "c", "d"];+ const edges = [{ source: "a", target: "b" }, { source: "b", target: "c" }, { source: "d", target: "b" }];+ expect(graphFocusClusterIds(nodes, edges, ["b"], { depth: 1, maxNodes: 10 })).toEqual(["b", "a", "c", "d"]);+ expect(graphFocusClusterIds(nodes, edges, ["a"], { depth: 2, maxNodes: 10 })).toEqual(["a", "b", "c", "d"]);+ });++ it("stays bounded for large graphs", () => {+ const nodes = Array.from({ length: 120 }, (_, index) => "n-" + index);+ const edges = nodes.slice(1).map((id, index) => ({ source: "n-" + index, target: id }));+ const focused = graphFocusClusterIds(nodes, edges, ["n-60"], { depth: 50, maxNodes: 12 });+ expect(focused).toHaveLength(12);+ expect(new Set(focused).size).toBe(12);+ });++ it("falls back safely for cycles without roots", () => {+ const nodes = ["a", "b", "c"];+ const edges = [{ source: "a", target: "b" }, { source: "b", target: "c" }, { source: "c", target: "a" }];+ expect(graphEntryNodeIds(nodes, edges)).toEqual(["a"]);+ expect(graphFocusClusterIds(nodes, edges, [], { depth: 1, maxNodes: 3 })).toEqual(["a", "b", "c"]);+ });+});