{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "diagram",
  "type": "registry:ui",
  "title": "Diagram",
  "description": "Read and edit explicit hierarchies with multiple roots and shared children.",
  "dependencies": [
    "@dagrejs/dagre@3.1.3",
    "lucide-react@0.561.0"
  ],
  "registryDependencies": [
    "https://ghost-ui.com/r/ghost-tokens.json",
    "https://ghost-ui.com/r/foundation.json",
    "https://ghost-ui.com/r/card.json",
    "https://ghost-ui.com/r/empty-state.json",
    "https://ghost-ui.com/r/button.json",
    "https://ghost-ui.com/r/dropdown-menu.json",
    "https://ghost-ui.com/r/tooltip.json",
    "https://ghost-ui.com/r/popover.json",
    "https://ghost-ui.com/r/input.json",
    "https://ghost-ui.com/r/field.json",
    "https://ghost-ui.com/r/select.json",
    "https://ghost-ui.com/r/utils.json",
    "https://ghost-ui.com/r/alert-dialog.json",
    "https://ghost-ui.com/r/button-group.json",
    "https://ghost-ui.com/r/avatar.json",
    "https://ghost-ui.com/r/layer-card.json",
    "https://ghost-ui.com/r/drawer.json",
    "https://ghost-ui.com/r/node-port.json",
    "https://ghost-ui.com/r/number-field.json"
  ],
  "files": [
    {
      "path": "src/components/ui/graph-types.ts",
      "type": "registry:component",
      "target": "@ui/graph-types.ts",
      "content": "import type { GraphNodeAnchors } from \"./graph-anchors\";\nexport type { GraphAnchor, GraphAnchorSide, GraphNodeAnchors } from \"./graph-anchors\";\n\n/** Neutral graph facts. Geometry, selection and disclosure are separate view state. */\nexport interface GraphPoint { x: number; y: number }\nexport interface GraphSize { width: number; height: number }\nexport type GraphPositions = Readonly<Record<string, GraphPoint>>;\nexport type GraphSizes = Readonly<Record<string, GraphSize>>;\nexport interface GraphPort {\n  id: string;\n  label: string;\n  direction: \"input\" | \"output\";\n  type?: string;\n  accepts?: readonly string[];\n  maxConnections?: number;\n}\nexport interface GraphNode<Data = unknown> {\n  id: string;\n  label: string;\n  data?: Data;\n  ports?: readonly GraphPort[];\n}\nexport interface GraphEdge<Data = unknown> {\n  id: string;\n  source: string;\n  target: string;\n  role: string;\n  label?: string;\n  sourcePort?: string;\n  targetPort?: string;\n  line?: \"solid\" | \"dashed\" | \"dotted\";\n  status?: \"idle\" | \"running\" | \"success\" | \"error\";\n  data?: Data;\n}\nexport interface GraphValue<NodeData = unknown, EdgeData = unknown> {\n  nodes: readonly GraphNode<NodeData>[];\n  edges: readonly GraphEdge<EdgeData>[];\n}\nexport interface GraphOptions {\n  /** null means no ancestry, useful for a free workflow canvas. Default: reporting. */\n  hierarchyRole?: string | null;\n  /** Defaults to hierarchyRole; other roles may form cycles. */\n  acyclicRoles?: readonly string[];\n}\nexport type GraphPermission = { allowed: true } | { allowed: false; reason: string };\nexport type GraphChange<NodeData = unknown, EdgeData = unknown> =\n  | { type: \"insert\"; node: GraphNode<NodeData>; edge?: GraphEdge<EdgeData>; position?: GraphPoint; beforeNodeId?: string | null; beforeEdgeId?: string | null }\n  | { type: \"rename\"; nodeId: string; label: string }\n  | { type: \"update-node\"; nodeId: string; label?: string; data?: NodeData }\n  | { type: \"connect\"; edge: GraphEdge<EdgeData> }\n  | { type: \"reconnect\"; edgeId: string; endpoint: \"source\" | \"target\"; nodeId: string; portId?: string }\n  | { type: \"move\"; edgeId: string; parentId: string }\n  | { type: \"reorder\"; edgeId: string; beforeEdgeId: string | null }\n  | { type: \"reorder-root\"; nodeId: string; beforeNodeId: string | null }\n  | { type: \"update-edge\"; edgeId: string; label?: string; role?: string; line?: \"solid\" | \"dashed\" | \"dotted\" }\n  | { type: \"disconnect\"; edgeId: string }\n  | { type: \"remove\"; nodeId: string }\n  | { type: \"position\"; moves: readonly { nodeId: string; position: GraphPoint; from?: GraphPoint }[] };\nexport interface GraphProjectionOptions extends GraphOptions {\n  collapsedIds?: ReadonlySet<string>;\n  rootIds?: readonly string[];\n}\nexport interface GraphProjection<NodeData = unknown, EdgeData = unknown> extends GraphValue<NodeData, EdgeData> {\n  rootIds: readonly string[];\n  visibleIds: ReadonlySet<string>;\n}\nexport interface GraphConnection {\n  source: string;\n  target: string;\n  role: string;\n  sourcePort?: string;\n  targetPort?: string;\n}\nexport interface GraphCreateContext {\n  id: string;\n  label: string;\n  /** The parent of the created node, when it is added below a parent. */\n  parentId?: string;\n  /** The existing node involved in a child, parent or sibling insertion. */\n  relatedNodeId?: string;\n  siblingId?: string;\n  /** Existing output port when the new node is connected downstream. */\n  sourcePort?: GraphPort;\n  /** Existing input port when the new node is connected upstream. */\n  targetPort?: GraphPort;\n  formData?: FormData;\n  relation?: \"child\" | \"parent\" | \"sibling\";\n}\nexport interface GraphNodeTemplate<NodeData = unknown> {\n  id: string;\n  label: string;\n  /** A missing type constraint is an untyped template, not an inferred capability. */\n  accepts?: readonly string[];\n  create: (context: GraphCreateContext) => GraphNode<NodeData>;\n}\nexport interface GraphLayoutOptions { direction?: \"down\" | \"right\"; align?: \"center\" | \"start\"; nodeGap?: number; levelGap?: number }\nexport interface GraphLayout {\n  positions: GraphPositions;\n  paths?: Readonly<Record<string, readonly GraphPoint[]>>;\n  anchors?: Readonly<Record<string, GraphNodeAnchors>>;\n}\nexport type GraphLayoutFunction<NodeData = unknown, EdgeData = unknown> = (\n  value: GraphValue<NodeData, EdgeData>, sizes: GraphSizes, options: GraphOptions & GraphLayoutOptions,\n) => GraphLayout;\n"
    },
    {
      "path": "src/components/ui/graph-model.ts",
      "type": "registry:component",
      "target": "@ui/graph-model.ts",
      "content": "import type { GraphChange, GraphEdge, GraphNode, GraphOptions, GraphPoint, GraphPositions, GraphProjection, GraphProjectionOptions, GraphValue } from \"./graph-types\";\nexport type * from \"./graph-types\";\n\nconst fail = (message: string): never => { throw new Error(message); };\nconst text = (v: unknown): v is string => typeof v === \"string\" && v.trim().length > 0;\nconst point = (p: GraphPoint): boolean => !!p && Number.isFinite(p.x) && Number.isFinite(p.y);\nconst own = (o: object, key: string) => Object.prototype.hasOwnProperty.call(o, key);\nconst hierarchy = (options: GraphOptions = {}) => options.hierarchyRole === undefined ? \"reporting\" : options.hierarchyRole;\nconst same = (a: readonly unknown[], b: readonly unknown[]) => a.length === b.length && a.every((item, i) => item === b[i]);\n\nfunction adjacency<N,E>(value: GraphValue<N,E>, role: string | null) {\n  const next = new Map<string, string[]>();\n  for (const edge of value.edges) if (edge.role === role) {\n    const children = next.get(edge.source);\n    if (children) children.push(edge.target); else next.set(edge.source, [edge.target]);\n  }\n  return next;\n}\n\nexport function assertGraphValue<N,E>(value: GraphValue<N,E>, options: GraphOptions = {}): void {\n  if (!value || !Array.isArray(value.nodes) || !Array.isArray(value.edges)) fail(\"Graph must contain node and edge arrays\");\n  const nodes = new Map<string, GraphNode<N>>();\n  for (const node of value.nodes) {\n    if (!node || !text(node.id) || !text(node.label)) fail(\"Nodes need nonempty IDs and labels\");\n    if (nodes.has(node.id)) fail(`Duplicate node ID: ${node.id}`);\n    nodes.set(node.id, node);\n    if (node.ports !== undefined && !Array.isArray(node.ports)) fail(`Invalid ports on ${node.id}`);\n    const ports = new Set<string>();\n    for (const port of node.ports ?? []) {\n      if (!port || !text(port.id) || !text(port.label) || ![\"input\", \"output\"].includes(port.direction) || ports.has(port.id)\n        || port.type !== undefined && !text(port.type)\n        || port.accepts !== undefined && (!Array.isArray(port.accepts) || !port.accepts.every(text))\n        || port.maxConnections !== undefined && (!Number.isInteger(port.maxConnections) || port.maxConnections < 0)) fail(`Invalid port on ${node.id}`);\n      ports.add(port.id);\n    }\n  }\n  const identities = new Set<string>(), relations = new Set<string>(), counts = new Map<string, number>();\n  for (const edge of value.edges) {\n    if (!edge || !text(edge.id) || !text(edge.role) || identities.has(edge.id)) fail(\"Edges need unique IDs and nonempty roles\");\n    identities.add(edge.id);\n    const source = nodes.get(edge.source), target = nodes.get(edge.target);\n    if (!source || !target) fail(`Edge ${edge.id} has a missing endpoint`);\n    if (edge.source === edge.target) fail(`Edge ${edge.id} is a self link`);\n    if (edge.label !== undefined && typeof edge.label !== \"string\") fail(`Invalid label on ${edge.id}`);\n    if (edge.line !== undefined && ![\"solid\", \"dashed\", \"dotted\"].includes(edge.line)) fail(`Invalid line on ${edge.id}`);\n    const output = source!.ports?.find(p => p.id === edge.sourcePort), input = target!.ports?.find(p => p.id === edge.targetPort);\n    if (edge.sourcePort !== undefined && (!output || output.direction !== \"output\") || edge.targetPort !== undefined && (!input || input.direction !== \"input\")) fail(`Invalid port on ${edge.id}`);\n    if (input?.accepts && (!output?.type || !input.accepts.includes(output.type))) fail(\"The selected input does not accept this output.\");\n    const relation = JSON.stringify([edge.role, edge.source, edge.target, edge.sourcePort ?? null, edge.targetPort ?? null]);\n    if (relations.has(relation)) fail(`Duplicate relationship on ${edge.id}`);\n    relations.add(relation);\n    for (const [node, port] of [[source, output], [target, input]] as const) if (port) {\n      const key = JSON.stringify([node!.id, port.id]), count = (counts.get(key) ?? 0) + 1;\n      counts.set(key, count);\n      if (port.maxConnections !== undefined && count > port.maxConnections) fail(`Port ${port.id} exceeds capacity`);\n    }\n  }\n  const role = hierarchy(options), acyclic = options.acyclicRoles ?? (role === null ? [] : [role]);\n  for (const role of acyclic) {\n    const next = adjacency(value, role), indegree = new Map(value.nodes.map(n => [n.id, 0]));\n    for (const children of next.values()) for (const id of children) indegree.set(id, indegree.get(id)! + 1);\n    const queue = [...indegree].filter(([, degree]) => degree === 0).map(([id]) => id);\n    for (let i = 0; i < queue.length; i++) for (const child of next.get(queue[i]) ?? []) {\n      const degree = indegree.get(child)! - 1; indegree.set(child, degree); if (degree === 0) queue.push(child);\n    }\n    if (queue.length !== value.nodes.length) fail(`Cycle in role ${role}`);\n  }\n}\n\n// One reducer owns proposals and committed changes; validation cannot drift from application.\nfunction reduce<N,E>(value: GraphValue<N,E>, change: GraphChange<N,E>, options: GraphOptions): GraphValue<N,E> {\n  if (!change || typeof change !== \"object\") fail(\"Malformed graph change\");\n  const nodes = value.nodes, edges = value.edges;\n  const nodeAt = (id: string) => { const index = nodes.findIndex(n => n.id === id); return index < 0 ? fail(\"Stale node\") : index; };\n  const edgeAt = (id: string) => { const index = edges.findIndex(e => e.id === id); return index < 0 ? fail(\"Stale edge\") : index; };\n  const replaceEdge = (index: number, edge: GraphEdge<E>) => {\n    const previous = edges[index];\n    if ((Object.keys(edge) as (keyof GraphEdge<E>)[]).every(key => edge[key] === previous[key])) return value;\n    const result = [...edges]; result[index] = edge; return { ...value, edges: result };\n  };\n  switch (change.type) {\n    case \"insert\": {\n      if (!change.node || nodes.some(n => n.id === change.node.id)) fail(\"Invalid or duplicate inserted node\");\n      if (change.position !== undefined && !point(change.position)) fail(\"Invalid position\");\n      const index = change.beforeNodeId == null ? nodes.length : nodeAt(change.beforeNodeId), result = [...nodes];\n      if (change.edge && change.edge.source !== change.node.id && change.edge.target !== change.node.id) fail(\"Inserted edge must connect the new node\");\n      result.splice(index, 0, change.node);\n      if (!change.edge) { if (change.beforeEdgeId != null) fail(\"An edge insertion anchor needs an edge\"); return { nodes: result, edges }; }\n      const edgeIndex = change.beforeEdgeId == null ? edges.length : edges.findIndex(edge => edge.id === change.beforeEdgeId);\n      if (edgeIndex < 0) fail(\"Stale edge anchor\");\n      if (change.beforeEdgeId != null) { const anchor = edges[edgeIndex]; if (anchor.source !== change.edge.source || anchor.role !== change.edge.role) fail(\"Invalid edge insertion anchor\"); }\n      const nextEdges = [...edges]; nextEdges.splice(edgeIndex, 0, change.edge); return { nodes: result, edges: nextEdges };\n    }\n    case \"rename\": { const index = nodeAt(change.nodeId); if (!text(change.label)) fail(\"Label must not be empty\"); if (nodes[index].label === change.label) return value; const result = [...nodes]; result[index] = { ...nodes[index], label: change.label }; return { ...value, nodes: result }; }\n    case \"update-node\": { const index = nodeAt(change.nodeId), previous = nodes[index]; if (change.label !== undefined && !text(change.label)) fail(\"Label must not be empty\"); if (change.label === previous.label && (!own(change, \"data\") || change.data === previous.data)) return value; const result = [...nodes]; result[index] = { ...previous, ...(change.label !== undefined ? { label: change.label } : {}), ...(own(change, \"data\") ? { data: change.data } : {}) }; return { ...value, nodes: result }; }\n    case \"connect\": return { ...value, edges: [...edges, change.edge] };\n    case \"reconnect\": {\n      if (![\"source\", \"target\"].includes(change.endpoint)) fail(\"Invalid endpoint\");\n      nodeAt(change.nodeId); const index = edgeAt(change.edgeId);\n      return replaceEdge(index, { ...edges[index], [change.endpoint]: change.nodeId, [change.endpoint === \"source\" ? \"sourcePort\" : \"targetPort\"]: change.portId });\n    }\n    case \"move\": { nodeAt(change.parentId); const index = edgeAt(change.edgeId); if (edges[index].role !== hierarchy(options)) fail(\"Only hierarchy edges can move branches\"); if (edges[index].source === change.parentId) return value; return replaceEdge(index, { ...edges[index], source: change.parentId, sourcePort: undefined }); }\n    case \"update-edge\": {\n      const index = edgeAt(change.edgeId), edge = { ...edges[index] };\n      for (const key of [\"label\", \"role\", \"line\"] as const) if (own(change, key)) Object.assign(edge, { [key]: change[key] });\n      return replaceEdge(index, edge);\n    }\n    case \"reorder\": {\n      const index = edgeAt(change.edgeId), edge = edges[index]; if (change.beforeEdgeId === edge.id) return value;\n      if (change.beforeEdgeId !== null) { const anchor = edges[edgeAt(change.beforeEdgeId)]; if (anchor.source !== edge.source || anchor.role !== edge.role) fail(\"Invalid sibling anchor\"); }\n      const result = edges.filter(e => e !== edge), before = change.beforeEdgeId === null ? result.map(e => e.source === edge.source && e.role === edge.role).lastIndexOf(true) + 1 : result.findIndex(e => e.id === change.beforeEdgeId);\n      result.splice(before, 0, edge); return same(result, edges) ? value : { ...value, edges: result };\n    }\n    case \"reorder-root\": {\n      nodeAt(change.nodeId); const incoming = new Set(edges.filter(e => e.role === hierarchy(options)).map(e => e.target));\n      const roots = nodes.filter(n => !incoming.has(n.id)); if (incoming.has(change.nodeId)) fail(\"Node is not a root\");\n      if (change.beforeNodeId === change.nodeId) return value;\n      if (change.beforeNodeId !== null && !roots.some(n => n.id === change.beforeNodeId)) fail(\"Invalid root anchor\");\n      const reordered = roots.filter(n => n.id !== change.nodeId), node = nodes.find(n => n.id === change.nodeId)!;\n      reordered.splice(change.beforeNodeId === null ? reordered.length : reordered.findIndex(n => n.id === change.beforeNodeId), 0, node);\n      let i = 0; const result = nodes.map(n => incoming.has(n.id) ? n : reordered[i++]); return same(result, nodes) ? value : { ...value, nodes: result };\n    }\n    case \"disconnect\": { edgeAt(change.edgeId); return { ...value, edges: edges.filter(e => e.id !== change.edgeId) }; }\n    case \"remove\": { nodeAt(change.nodeId); return { nodes: nodes.filter(n => n.id !== change.nodeId), edges: edges.filter(e => e.source !== change.nodeId && e.target !== change.nodeId) }; }\n    case \"position\": {\n      if (!Array.isArray(change.moves)) fail(\"Malformed position batch\"); const seen = new Set<string>();\n      for (const move of change.moves) { if (!move) fail(\"Malformed position\"); nodeAt(move.nodeId); if (seen.has(move.nodeId) || !point(move.position) || move.from !== undefined && !point(move.from)) fail(\"Invalid position batch\"); seen.add(move.nodeId); }\n      return value;\n    }\n    default: return fail(\"Unknown graph change\");\n  }\n}\n\nexport function getGraphChangeError<N,E>(value: GraphValue<N,E>, change: GraphChange<N,E>, options: GraphOptions = {}): string | null {\n  assertGraphValue(value, options);\n  try { const next = reduce(value, change, options); assertGraphValue(next, options); return null; }\n  catch (error) { return error instanceof Error ? error.message : \"Malformed graph change\"; }\n}\nexport function applyGraphChange<N,E>(value: GraphValue<N,E>, change: GraphChange<N,E>, options: GraphOptions = {}): GraphValue<N,E> {\n  assertGraphValue(value, options);\n  try { const next = reduce(value, change, options); if (next !== value) assertGraphValue(next, options); return next; } catch { return value; }\n}\nexport function getGraphProjection<N,E>(value: GraphValue<N,E>, options: GraphProjectionOptions = {}): GraphProjection<N,E> {\n  assertGraphValue(value, options);\n  const role = hierarchy(options), incoming = new Set(value.edges.filter(e => e.role === role).map(e => e.target));\n  const known = new Set(value.nodes.map(n => n.id));\n  const roots = [...new Set(options.rootIds ?? value.nodes.filter(n => !incoming.has(n.id)).map(n => n.id))];\n  if (roots.some(id => !known.has(id))) fail(\"Unknown projection root\");\n  const next = adjacency(value, role), visible = new Set<string>(), stack = [...roots];\n  while (stack.length) { const id = stack.pop()!; if (visible.has(id)) continue; visible.add(id); if (!options.collapsedIds?.has(id)) for (const child of next.get(id) ?? []) stack.push(child); }\n  return { nodes: value.nodes.filter(n => visible.has(n.id)), edges: value.edges.filter(e => visible.has(e.source) && visible.has(e.target) && !(options.collapsedIds?.has(e.source) && e.role === role)), rootIds: roots, visibleIds: visible };\n}\nexport function getGraphDescendants<N,E>(value: GraphValue<N,E>, nodeId: string, hierarchyRole: string | null = \"reporting\"): ReadonlySet<string> {\n  const next = adjacency(value, hierarchyRole), seen = new Set<string>([nodeId]), stack = [nodeId];\n  while (stack.length) for (const child of next.get(stack.pop()!) ?? []) if (!seen.has(child)) { seen.add(child); stack.push(child); }\n  seen.delete(nodeId); return seen;\n}\nexport function applyGraphPositions<N,E>(positions: GraphPositions, change: GraphChange<N,E>): GraphPositions {\n  if (change.type === \"remove\") { if (!own(positions, change.nodeId)) return positions; const result = { ...positions }; delete (result as Record<string, GraphPoint>)[change.nodeId]; return result; }\n  const moves = change.type === \"position\" ? change.moves : change.type === \"insert\" && change.position !== undefined ? [{ nodeId: change.node.id, position: change.position }] : [];\n  if (!Array.isArray(moves)) return positions;\n  const seen = new Set<string>();\n  for (const move of moves) {\n    if (!move || !text(move.nodeId) || seen.has(move.nodeId) || !point(move.position) || move.from !== undefined && (!point(move.from) || !own(positions, move.nodeId) || positions[move.nodeId].x !== move.from.x || positions[move.nodeId].y !== move.from.y)) return positions;\n    seen.add(move.nodeId);\n  }\n  if (moves.every(m => own(positions, m.nodeId) && positions[m.nodeId].x === m.position.x && positions[m.nodeId].y === m.position.y)) return positions;\n  const result = { ...positions };\n  for (const move of moves) Object.defineProperty(result, move.nodeId, { value: { ...move.position }, enumerable: true, configurable: true, writable: true });\n  return result;\n}\n"
    },
    {
      "path": "src/components/ui/graph-id.ts",
      "type": "registry:component",
      "target": "@ui/graph-id.ts",
      "content": "/** Private transport IDs keep opaque caller IDs out of engine keys and CSS selectors. */\nexport function graphEngineId(id: string): string {\n  let encoded = \"g_\";\n  for (let i = 0; i < id.length; i++) encoded += id.charCodeAt(i).toString(16).padStart(4, \"0\");\n  return encoded;\n}\nexport function graphPublicId(id: string): string | undefined {\n  if (!/^g_(?:[0-9a-f]{4})+$/.test(id)) return undefined;\n  let decoded = \"\";\n  for (let i = 2; i < id.length; i += 4) decoded += String.fromCharCode(parseInt(id.slice(i, i + 4), 16));\n  return decoded;\n}\n"
    },
    {
      "path": "src/components/ui/node-card.tsx",
      "type": "registry:component",
      "target": "@ui/node-card.tsx",
      "content": "import * as React from \"react\";\nimport { Card, type CardRootProps } from \"./card\";\nimport \"./node-card.css\";\nimport { styled } from \"./base-styled\";\n\nexport interface NodeCardRootProps extends Omit<CardRootProps, \"ref\"> {\n  selected?: boolean;\n  interactive?: boolean;\n  stagedParent?: boolean;\n  disabled?: boolean;\n  dragging?: boolean;\n  status?: \"idle\" | \"running\" | \"success\" | \"error\";\n}\nconst Root = React.forwardRef<HTMLDivElement, NodeCardRootProps>(function Root(\n  {\n    selected,\n    interactive,\n    stagedParent,\n    disabled = false,\n    dragging = false,\n    status = \"idle\",\n    className,\n    density = \"compact\",\n    ...props\n  },\n  ref,\n) {\n  return (\n    <Card.Root\n      {...props}\n      ref={ref}\n      className={[\"ui-graph-node\", className].filter(Boolean).join(\" \")}\n      data-selected={selected || undefined}\n      data-interactive={interactive || undefined}\n      data-staged-parent={stagedParent || undefined}\n      data-disabled={disabled || undefined}\n      data-dragging={dragging || undefined}\n      data-status={status !== \"idle\" ? status : undefined}\n      density={density}\n    />\n  );\n});\nRoot.displayName = \"NodeCard.Root\";\n\nexport const NodeCard = {\n  Root,\n  Header: styled(Card.Header, \"ui-graph-node__header\"),\n  Title: styled(Card.Title, \"ui-graph-node__title\"),\n  Description: styled(Card.Description, \"ui-graph-node__description\"),\n  Content: styled(Card.Content, \"ui-graph-node__content\"),\n  Footer: styled(Card.Footer, \"ui-graph-node__footer\"),\n  Actions: styled(Card.Action, \"ui-graph-node__actions\"),\n};\n\nexport namespace NodeCard {\n  export type RootProps = React.ComponentProps<typeof Root>;\n}\n\nexport default NodeCard;\n"
    },
    {
      "path": "src/components/ui/graph-surface-internal.tsx",
      "type": "registry:component",
      "target": "@ui/graph-surface-internal.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport type {\n  GraphViewNode as FlowNode,\n  GraphViewEdge as FlowEdge,\n  GraphNodeViewData as FlowNodeData,\n  GraphEdgeViewData as FlowEdgeData,\n  GraphNodeAction as NodeAction,\n  GraphHandleView,\n  GraphViewNodeChange,\n  GraphViewportHandle,\n  GraphViewportProps,\n} from \"./graph-view-types\";\nimport { getGraphConnectorPath, type GraphConnector } from \"./graph-connectors\";\nimport {\n  ArrowDown,\n  ArrowUp,\n  CornerDownRight,\n  Ellipsis,\n  Link2,\n  ListPlus,\n  Move,\n  MoveRight,\n  Pencil,\n  Plus,\n  Search,\n  Trash2,\n  Workflow,\n  Type,\n  Image as ImageIcon,\n  Video,\n  AudioLines,\n  X,\n} from \"lucide-react\";\nimport { Button, IconButton } from \"./button\";\nimport { ButtonGroup } from \"./button-group\";\nimport { DropdownMenu } from \"./dropdown-menu\";\nimport { AlertDialog } from \"./alert-dialog\";\nimport { Field } from \"./field\";\nimport { NumberField } from \"./number-field\";\nimport { Input } from \"./input\";\nimport { Popover } from \"./popover\";\nimport { Drawer } from \"./drawer\";\nimport { Select } from \"./select\";\nimport { TooltipHint } from \"./tooltip\";\nimport { NodeCard } from \"./node-card\";\nimport { NodePort } from \"./node-port\";\nimport { EdgePath } from \"./edge-path\";\nimport { normalizeGraphAnchors, resolveGraphAnchor } from \"./graph-anchors\";\nimport { Avatar } from \"./avatar\";\nimport { LayerCard } from \"./layer-card\";\nimport { EmptyState } from \"./empty-state\";\nimport { graphEngineId, graphPublicId } from \"./graph-id\";\nimport {\n  applyGraphPositions,\n  assertGraphValue,\n  getGraphChangeError,\n  getGraphDescendants,\n  getGraphProjection,\n} from \"./graph-model\";\nimport type {\n  GraphChange,\n  GraphConnection,\n  GraphEdge,\n  GraphLayout,\n  GraphLayoutFunction,\n  GraphNode,\n  GraphNodeTemplate,\n  GraphOptions,\n  GraphPoint,\n  GraphPort,\n  GraphPositions,\n  GraphSize,\n  GraphValue,\n} from \"./graph-types\";\nimport \"./graph.css\";\n\nexport interface GraphSurfaceProps<N = unknown, E = unknown> {\n  mode: \"diagram\" | \"canvas\";\n  align?: \"center\" | \"start\";\n  fit?: \"width\" | \"none\";\n  collapsible?: boolean;\n  /** Injected canvas renderer. The base graph ships no canvas engine. */\n  viewport?: React.ComponentType<GraphViewportProps>;\n  connector?: GraphConnector;\n  routes?: Readonly<Record<string, readonly GraphPoint[]>>;\n  value: GraphValue<N, E>;\n  editable?: boolean;\n  onChange?: (change: GraphChange<N, E>) => void | Promise<void>;\n  getChangePermission?: (\n    change: GraphChange<N, E>,\n  ) => { allowed: true } | { allowed: false; reason: string };\n  renderNode?: (\n    node: GraphNode<N>,\n    state: { selected: boolean },\n  ) => React.ReactNode;\n  nodeWidth?: number | ((node: GraphNode<N>) => number);\n  createNode?: (context: {\n    id: string;\n    label: string;\n    parentId?: string;\n    relatedNodeId?: string;\n    siblingId?: string;\n    sourcePort?: GraphPort;\n    targetPort?: GraphPort;\n    formData?: FormData;\n    relation?: \"child\" | \"parent\" | \"sibling\";\n  }) => GraphNode<N>;\n  createEdge?: (connection: GraphConnection & { id: string }) => GraphEdge<E>;\n  nodeTemplates?: readonly GraphNodeTemplate<N>[];\n  relationshipTypes?: readonly { value: string; label: string }[];\n  connectionRole?: string;\n  selectedNodeId?: string | null;\n  onSelectedNodeIdChange?: (id: string | undefined) => void;\n  onEditNode?: (node: GraphNode<N>) => void;\n  renderNodeFooter?: (node: GraphNode<N>) => React.ReactNode;\n  hierarchyRole?: string;\n  collapsedIds?: readonly string[];\n  defaultCollapsedIds?: readonly string[];\n  onCollapsedIdsChange?: (ids: readonly string[]) => void;\n  search?: string;\n  onSearchChange?: (search: string) => void;\n  direction?: \"down\" | \"right\";\n  layout?: GraphLayoutFunction<N, E>;\n  nodeGap?: number;\n  levelGap?: number;\n  positions?: GraphPositions;\n  defaultPositions?: GraphPositions;\n  acyclicRoles?: readonly string[];\n  nativeProps?: React.HTMLAttributes<HTMLDivElement>;\n  rootRef?: React.Ref<HTMLDivElement>;\n}\n\nexport type GraphSurfaceFlowNode = FlowNode;\nexport type GraphSurfaceFlowEdge = FlowEdge;\nexport type { GraphViewportHandle } from \"./graph-view-types\";\nconst ownValue = <T,>(\n  record: Readonly<Record<string, T>>,\n  id: string,\n): T | undefined => (Object.hasOwn(record, id) ? record[id] : undefined);\nconst newId = () => crypto.randomUUID();\n\nfunction GraphTypeGlyph({ type }: { type?: string }) {\n  const normalized = type?.toLowerCase() ?? \"\";\n  if (normalized.includes(\"image\")) return <ImageIcon aria-hidden=\"true\" />;\n  if (normalized.includes(\"video\")) return <Video aria-hidden=\"true\" />;\n  if (normalized.includes(\"audio\")) return <AudioLines aria-hidden=\"true\" />;\n  return <Type aria-hidden=\"true\" />;\n}\n\nfunction NodePorts({\n  node,\n  connectedPortIds = [],\n  renderHandle,\n  onPortHover,\n  onAction,\n  canMutate,\n  pending,\n}: {\n  node: GraphNode;\n  connectedPortIds: readonly string[];\n  renderHandle?: (props: GraphHandleView) => React.ReactNode;\n  onPortHover?: (nodeId: string, portId?: string) => void;\n  onAction: (node: GraphNode<any>, action: NodeAction, sourcePortId?: string, anchor?: Element | null) => void;\n  canMutate: boolean;\n  pending: boolean;\n}) {\n  const inputs = node.ports?.filter((port) => port.direction === \"input\") ?? [];\n  const outputs =\n    node.ports?.filter((port) => port.direction === \"output\") ?? [];\n  if (!inputs.length && !outputs.length)\n    return (\n      <>\n        {renderHandle?.({ direction: \"input\", side: \"left\", offset: 0.5, label: \"Input\", disabled: pending })}\n        {renderHandle?.({\n          direction: \"output\",\n          side: \"right\",\n          offset: 0.5,\n          label: \"Output\",\n          disabled: pending,\n        })}\n      </>\n    );\n  return (\n    <div className=\"ui-graph-node__ports\">\n      {Array.from(\n        { length: Math.max(inputs.length, outputs.length) },\n        (_, index) => (\n          <div className=\"ui-graph-node__port-row\" key={index}>\n            {[inputs[index], outputs[index]].map((port, column) => {\n              if (!port) return <div key={column} />;\n              return <NodePort\n                key={port.id}\n                className={`ui-graph-node__port ui-graph-node__port--${column ? \"output\" : \"input\"}`}\n                label={port.label}\n                direction={port.direction}\n                dataType={port?.type}\n                connected={connectedPortIds.includes(port.id)}\n                disabled={pending}\n                handle={renderHandle?.({\n                  portId: port.id,\n                  direction: port.direction,\n                  side: column ? \"right\" : \"left\",\n                  offset: 0.5,\n                  label: port.label,\n                  disabled: pending,\n                })}\n                onPointerEnter={() => onPortHover?.(node.id, port.id)}\n                onPointerLeave={() => onPortHover?.(node.id)}\n                onFocusCapture={() => onPortHover?.(node.id, port.id)}\n                onBlurCapture={(event) => {\n                  if (!event.currentTarget.contains(event.relatedTarget as Node | null))\n                    onPortHover?.(node.id);\n                }}\n              >\n                {canMutate && <ButtonGroup className=\"ui-graph-node__port-actions\" aria-label={`Actions for ${port.label} port`}><TooltipHint content=\"Add connected node\"><IconButton icon={<Plus />} size=\"icon-xs\" variant=\"subtle\" aria-label={`Add node at ${port.label}`} disabled={pending} onClick={(event) => onAction(node, port.direction === \"input\" ? \"parent\" : \"canvas\", port.id, event.currentTarget)} /></TooltipHint><TooltipHint content=\"Connect existing node\"><IconButton icon={<Link2 />} size=\"icon-xs\" variant=\"subtle\" aria-label={`Connect existing node at ${port.label}`} disabled={pending} onClick={(event) => onAction(node, \"relationship\", port.id, event.currentTarget)} /></TooltipHint></ButtonGroup>}\n              </NodePort>;\n            })}\n          </div>\n        ),\n      )}\n    </div>\n  );\n}\nexport const NodeView = React.memo(function NodeView({\n  data,\n  selected = false,\n  renderHandle,\n}: {\n  data: FlowNodeData;\n  selected?: boolean;\n  renderHandle?: (props: GraphHandleView) => React.ReactNode;\n}) {\n  const node = data.graphNode;\n  const footerContent = data.mode === \"diagram\" ? data.renderNodeFooter?.(node) : null;\n  const hasFooterContent = React.Children.toArray(footerContent).length > 0;\n  const cardRef = React.useRef<HTMLDivElement>(null),\n    [hoveredAction, setHoveredAction] = React.useState<\"top\" | \"right\" | \"bottom\" | \"left\">();\n  const openAction = (action: NodeAction) =>\n    data.onAction(node, action, undefined, cardRef.current);\n  return (\n    <NodeCard.Root\n      ref={cardRef}\n      onPointerMove={(event) => {\n        if (event.buttons !== 0 || !event.currentTarget.ownerDocument.defaultView?.matchMedia(\"(hover: hover) and (pointer: fine)\").matches) return;\n        if (\n          (event.target as HTMLElement).closest(\".ui-graph-node__action-zone\")\n        )\n          return;\n        const bounds = event.currentTarget.getBoundingClientRect(),\n          nearBottom =\n            event.clientY >= bounds.bottom - 18 &&\n            event.clientX >= bounds.left + 32 &&\n            event.clientX <= bounds.right - 32,\n          nearRight =\n            event.clientX >= bounds.right - 18 &&\n            event.clientY >= bounds.top + 32 &&\n            event.clientY <= bounds.bottom - 32,\n          nearTop = event.clientY <= bounds.top + 18 && event.clientX >= bounds.left + 32 && event.clientX <= bounds.right - 32,\n          nearLeft = event.clientX <= bounds.left + 18 && event.clientY >= bounds.top + 32 && event.clientY <= bounds.bottom - 32;\n        setHoveredAction(nearTop ? \"top\" : nearRight ? \"right\" : nearBottom ? \"bottom\" : nearLeft ? \"left\" : undefined);\n      }}\n      onPointerLeave={(event) => {\n        if (\n          event.relatedTarget instanceof Node &&\n          event.currentTarget.contains(event.relatedTarget)\n        )\n          return;\n        setHoveredAction(undefined);\n      }}\n      role=\"group\"\n      selected={selected}\n      interactive={data.canMutate}\n      stagedParent={data.stagedParent}\n      variant={data.mode === \"canvas\" ? \"ghost\" : \"outline\"}\n      aria-label={node.label}\n      data-custom={Boolean(data.renderNode)}\n      data-editable={data.canMutate || undefined}\n      data-port-highlighted={data.portHighlighted || undefined}\n      data-node-mode={data.mode}\n    >\n      {data.mode === \"canvas\" ? (\n        <LayerCard variant=\"compact\" className=\"ui-graph-node__canvas-card\" aria-label={node.label}>\n          <LayerCard.Secondary className=\"ui-graph-node__canvas-heading\">\n            <span><GraphTypeGlyph type={node.ports?.find((port) => port.direction === \"output\")?.type ?? node.ports?.find((port) => port.direction === \"input\")?.accepts?.[0]} />{node.label}</span>\n            {data.canMutate && <NodeMenu node={node} data={data} openAction={openAction} cardRef={cardRef} />}\n          </LayerCard.Secondary>\n          <LayerCard.Primary density=\"compact\">\n            {data.renderNode ? data.renderNode(node, { selected }) : node.label}\n            <NodePorts\n              node={node}\n              connectedPortIds={data.connectedPortIds}\n              renderHandle={renderHandle}\n              onPortHover={data.onPortHover}\n              onAction={data.onAction}\n              canMutate={data.canMutate}\n              pending={data.pending}\n            />\n          </LayerCard.Primary>\n        </LayerCard>\n      ) : data.renderNode ? (\n        <NodeCard.Content>\n          {data.renderNode(node, { selected })}\n        </NodeCard.Content>\n      ) : (\n        <NodeCard.Header>\n          <NodeCard.Title>{node.label}</NodeCard.Title>\n        </NodeCard.Header>\n      )}\n      {data.mode === \"diagram\" && data.canMutate && (\n        <NodeMenu node={node} data={data} openAction={openAction} cardRef={cardRef} />\n      )}\n      {data.mode === \"diagram\" && (data.childCount > 0 || hasFooterContent) && (\n        <NodeCard.Footer>\n          {hasFooterContent && <div className=\"ui-graph-node__footer-content\">{footerContent}</div>}\n          <div className=\"ui-graph-node__actions nodrag nopan\">\n            {data.childCount > 0 && (\n              <TooltipHint content={<span className=\"ui-graph-disclosure-tooltip\"><span>Direct children: {data.childCount}</span><span>Total descendants: {data.descendantCount ?? data.childCount}</span></span>}>\n                <Button className=\"ui-graph-node__disclosure\" size=\"xs\" variant=\"ghost\" aria-label={`${data.collapsed ? \"Expand\" : \"Collapse\"} ${node.label}; ${data.descendantCount ?? data.childCount} descendants`} aria-expanded={!data.collapsed} disabled={!data.canToggle} onClick={() => data.onToggle(node.id)}>\n                  <span aria-hidden=\"true\">{data.descendantCount ?? data.childCount}</span>\n                  {data.collapsed ? <ArrowDown aria-hidden=\"true\" /> : <ArrowUp aria-hidden=\"true\" />}\n                </Button>\n              </TooltipHint>\n            )}\n          </div>\n        </NodeCard.Footer>\n      )}\n      {data.mode === \"diagram\" && renderHandle && (\n        <>\n          {renderHandle({\n            direction: \"output\",\n            side: data.anchors.output.side,\n            offset: data.anchors.output.offset,\n            label: `Connect from ${node.label}`,\n            disabled: data.pending,\n          })}\n          {renderHandle({\n            direction: \"input\",\n            side: data.anchors.input.side,\n            offset: data.anchors.input.offset,\n            label: `Connect to ${node.label}`,\n            disabled: data.pending,\n          })}\n        </>\n      )}\n      {data.mode === \"diagram\" && data.canMutate && ([\"top\", \"right\", \"bottom\", \"left\"] as const).map((side) => <div key={side} className={`ui-graph-node__action-zone ui-graph-node__action-zone--${side} nodrag nopan`} data-active={hoveredAction === side || undefined} onFocusCapture={() => setHoveredAction(side)} onBlurCapture={(event) => { if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setHoveredAction(undefined); }}>\n        <IconButton className=\"ui-graph-node__port-trigger\" icon={<span className=\"ui-graph-node__action-dot\" aria-hidden=\"true\" />} size=\"icon-xs\" variant=\"ghost\" style={{ background: \"transparent\" }} aria-label={`Show actions ${side} of ${node.label}`} disabled={data.pending} onClick={event => event.currentTarget.parentElement?.querySelector<HTMLButtonElement>(\".ui-graph-node__action-group button:not(:disabled)\")?.focus()} />\n        <ButtonGroup orientation={side === \"left\" || side === \"right\" ? \"vertical\" : \"horizontal\"} className=\"ui-graph-node__action-group\" aria-label={`Actions ${side} of ${node.label}`}>\n          <TooltipHint content={side === \"top\" ? \"Add parent\" : side === \"bottom\" ? \"Add child\" : \"Add sibling\"}><IconButton className=\"ui-graph-node__action-button\" icon={<Plus />} size=\"icon\" variant=\"outline\" aria-label={`Add ${side === \"top\" ? \"parent\" : side === \"bottom\" ? \"child\" : \"sibling\"} of ${node.label}`} disabled={data.pending} onClick={(event) => data.onAction(node, side === \"top\" ? \"parent\" : side === \"bottom\" ? \"child\" : \"sibling\", undefined, event.currentTarget)} /></TooltipHint>\n          <TooltipHint content=\"Connect existing node\"><IconButton className=\"ui-graph-node__action-button\" icon={<Link2 />} size=\"icon\" variant=\"outline\" aria-label={`Connect a node to ${node.label}`} disabled={data.pending} onClick={(event) => data.onAction(node, \"relationship\", undefined, event.currentTarget)} /></TooltipHint>\n        </ButtonGroup>\n      </div>)}\n    </NodeCard.Root>\n  );\n});\n\nfunction NodeMenu({\n  node,\n  data,\n  openAction,\n  cardRef,\n}: {\n  node: GraphNode;\n  data: FlowNodeData;\n  openAction: (action: NodeAction) => void;\n  cardRef: React.RefObject<HTMLDivElement | null>;\n}) {\n  return (\n    <div className=\"ui-graph-node__menu nodrag nopan\">\n          <DropdownMenu.Root\n            open={data.actionsOpen}\n            onOpenChange={(open) =>\n              data.onActionsOpenChange(open ? node.id : undefined)\n            }\n          >\n            <DropdownMenu.Trigger\n              disabled={data.pending}\n              render={\n                <IconButton\n                  icon={<Ellipsis />}\n                  aria-label={`Actions for ${node.label}`}\n                  size=\"icon-xs\"\n                  variant=\"ghost\"\n                />\n              }\n            />\n            <DropdownMenu.Portal>\n              <DropdownMenu.Positioner side=\"bottom\" align=\"end\">\n                <DropdownMenu.Popup>\n                  <DropdownMenu.Item\n                    disabled={data.pending}\n                    onClick={() => openAction(\"rename\")}\n                  >\n                    <Pencil aria-hidden=\"true\" />\n                    Edit details\n                  </DropdownMenu.Item>\n                  <DropdownMenu.Separator />\n                  {data.mode === \"diagram\" ? (\n                    <>\n                      <DropdownMenu.Item\n                        disabled={data.pending}\n                        onClick={() => openAction(\"child\")}\n                      >\n                        <CornerDownRight aria-hidden=\"true\" />\n                        Add child\n                      </DropdownMenu.Item>\n                      <DropdownMenu.Item\n                        disabled={data.pending}\n                        onClick={() => openAction(\"sibling\")}\n                      >\n                        <ListPlus aria-hidden=\"true\" />\n                        Add sibling\n                      </DropdownMenu.Item>\n                      <DropdownMenu.Separator />\n                      <DropdownMenu.Item\n                        disabled={data.pending || !data.canReorder.up}\n                        onClick={() =>\n                          data.onReorder(node, \"up\", cardRef.current)\n                        }\n                      >\n                        <ArrowUp aria-hidden=\"true\" />\n                        {data.canReorder.up ? `Put before ${data.orderTarget?.before ?? \"previous position\"}` : \"Put before…\"}\n                      </DropdownMenu.Item>\n                      <DropdownMenu.Item\n                        disabled={data.pending || !data.canReorder.down}\n                        onClick={() =>\n                          data.onReorder(node, \"down\", cardRef.current)\n                        }\n                      >\n                        <ArrowDown aria-hidden=\"true\" />\n                        {data.canReorder.down ? `Put after ${data.orderTarget?.after ?? \"next position\"}` : \"Put after…\"}\n                      </DropdownMenu.Item>\n                      <DropdownMenu.Separator />\n                      <DropdownMenu.Item disabled={data.pending} onClick={() => openAction(\"move\")}>\n                        <MoveRight aria-hidden=\"true\" />\n                        Change parent…\n                      </DropdownMenu.Item>\n                    </>\n                  ) : (\n                    <>\n                      <DropdownMenu.Item\n                        disabled={data.pending}\n                        onClick={() => openAction(\"canvas\")}\n                      >\n                        <Workflow aria-hidden=\"true\" />\n                        Add connected node…\n                      </DropdownMenu.Item>\n                      <DropdownMenu.Item\n                        disabled={data.pending}\n                        onClick={() => openAction(\"position\")}\n                      >\n                        <Move aria-hidden=\"true\" />\n                        Set position…\n                      </DropdownMenu.Item>\n                    </>\n                  )}\n                  <DropdownMenu.Item\n                    disabled={data.pending}\n                    onClick={() => openAction(\"relationship\")}\n                  >\n                    <Link2 aria-hidden=\"true\" />\n                    Add connection…\n                  </DropdownMenu.Item>\n                  <DropdownMenu.Separator />\n                  <DropdownMenu.Item\n                    disabled={data.pending}\n                    onClick={() => data.onAction(node, \"remove\")}\n                  >\n                    <Trash2 aria-hidden=\"true\" />\n                    Remove node…\n                  </DropdownMenu.Item>\n                </DropdownMenu.Popup>\n              </DropdownMenu.Positioner>\n            </DropdownMenu.Portal>\n          </DropdownMenu.Root>\n    </div>\n  );\n}\n\nfunction GraphFormSelect({\n  name,\n  label,\n  options,\n  defaultValue = \"\",\n  value: controlled,\n  onValueChange,\n  disabled,\n  autoFocus,\n}: {\n  name?: string;\n  label: string;\n  options: readonly { value: string; label: string; disabled?: boolean; leading?: React.ReactNode }[];\n  defaultValue?: string;\n  value?: string;\n  onValueChange?: (value: string) => void;\n  disabled?: boolean;\n  autoFocus?: boolean;\n}) {\n  const [local, setLocal] = React.useState(defaultValue),\n    value = controlled ?? local;\n  return (\n    <Field.Root>\n      <Field.Label>{label}</Field.Label>\n      <Select.Root\n        value={value || null}\n        onValueChange={(next) => {\n          const value = next == null ? \"\" : String(next);\n          setLocal(value);\n          onValueChange?.(value);\n        }}\n        disabled={disabled}\n      >\n        <Select.Trigger aria-label={label} autoFocus={autoFocus}>\n          <Select.Value placeholder=\"Choose…\">\n            {(selected) =>\n              (() => { const option = options.find((item) => item.value === String(selected ?? \"\")); return option ? <span className=\"ui-graph-select-value\">{option.leading}{option.label}</span> : \"Choose…\"; })()\n            }\n          </Select.Value>\n          <Select.Icon />\n        </Select.Trigger>\n        <Select.Portal>\n          <Select.Positioner>\n            <Select.Popup>\n              <Select.List>\n                {options.map((option) => (\n                  <Select.Item\n                    key={option.value}\n                    value={option.value}\n                    disabled={option.disabled}\n                  >\n                    {option.leading}\n                    <Select.ItemText>{option.label}</Select.ItemText>\n                  </Select.Item>\n                ))}\n              </Select.List>\n            </Select.Popup>\n          </Select.Positioner>\n        </Select.Portal>\n      </Select.Root>\n      {name && <input type=\"hidden\" name={name} value={value} />}\n    </Field.Root>\n  );\n}\nfunction PortSelect({\n  node,\n  direction,\n  name,\n  pending,\n  portId,\n}: {\n  node?: GraphNode;\n  direction: \"input\" | \"output\";\n  name: string;\n  pending: boolean;\n  portId?: string;\n}) {\n  const ports =\n    node?.ports?.filter((port) => port.direction === direction) ?? [];\n  return ports.length ? (\n    <GraphFormSelect\n      key={node?.id}\n      name={name}\n      label={direction === \"input\" ? \"Input port\" : \"Output port\"}\n      options={ports.map((port) => ({ value: port.id, label: port.label }))}\n      defaultValue={\n        ports.some((port) => port.id === portId) ? portId : ports[0].id\n      }\n      disabled={pending}\n    />\n  ) : null;\n}\nfunction ConnectionForm({\n  value,\n  sourceId,\n  sourcePortId,\n  targetId,\n  targetPortId,\n  edge,\n  endpoint,\n  role,\n  roles,\n  pending,\n  onSubmit,\n  onCancel,\n}: {\n  value: GraphValue<any, any>;\n  sourceId?: string;\n  sourcePortId?: string;\n  targetId?: string;\n  targetPortId?: string;\n  edge?: GraphEdge<any>;\n  endpoint?: \"source\" | \"target\";\n  role: string;\n  roles: readonly { value: string; label: string }[];\n  pending: boolean;\n  onSubmit: (change: GraphChange<any, any>) => void;\n  onCancel?: () => void;\n}) {\n  const [source, setSource] = React.useState(sourceId ?? edge?.source ?? \"\"),\n    [target, setTarget] = React.useState(targetId ?? edge?.target ?? \"\");\n  const sourceNode = value.nodes.find((node) => node.id === source),\n    targetNode = value.nodes.find((node) => node.id === target);\n  return (\n    <form\n      className=\"ui-graph-form\"\n      onSubmit={(event) => {\n        event.preventDefault();\n        const form = new FormData(event.currentTarget);\n        if (endpoint && edge)\n          onSubmit({\n            type: \"reconnect\",\n            edgeId: edge.id,\n            endpoint,\n            nodeId: endpoint === \"source\" ? source : target,\n            portId:\n              String(\n                form.get(endpoint === \"source\" ? \"sourcePort\" : \"targetPort\") ??\n                  \"\",\n              ) || undefined,\n          });\n        else\n          onSubmit({\n            type: \"connect\",\n            edge: {\n              id: newId(),\n              source,\n              target,\n              role: String(form.get(\"role\") ?? role),\n              sourcePort: String(form.get(\"sourcePort\") ?? sourcePortId ?? \"\") || undefined,\n              targetPort: String(form.get(\"targetPort\") ?? targetPortId ?? \"\") || undefined,\n            },\n          });\n      }}\n    >\n      {sourceId && !endpoint ? (\n        <Field.Root><Field.Label>Connect from</Field.Label><div className=\"ui-graph-readonly-value\"><Avatar name={sourceNode?.label ?? \"Unavailable node\"} seed={sourceNode?.id} size=\"sm\" aria-hidden=\"true\" /><span>{sourceNode?.label ?? \"Unavailable node\"}</span></div><input type=\"hidden\" name=\"source\" value={source} /></Field.Root>\n      ) : endpoint !== \"target\" && (\n        <>\n          <GraphFormSelect\n            label=\"Connect from\"\n            value={source}\n            autoFocus={!endpoint || endpoint === \"source\"}\n            onValueChange={(next) => {\n              setSource(next);\n              if (next === target) setTarget(\"\");\n            }}\n            options={value.nodes\n              .filter((node) => endpoint !== \"source\" || node.id !== target)\n              .map((node) => ({ value: node.id, label: node.label, leading: <Avatar name={node.label} seed={node.id} size=\"sm\" aria-hidden=\"true\" /> }))}\n            disabled={pending}\n          />\n          <PortSelect\n            node={sourceNode}\n            direction=\"output\"\n            name=\"sourcePort\"\n            pending={pending}\n            portId={source === edge?.source ? edge.sourcePort : sourcePortId}\n          />\n        </>\n      )}\n      {targetId && !endpoint ? (\n        <Field.Root><Field.Label>Connect to</Field.Label><div className=\"ui-graph-readonly-value\"><Avatar name={targetNode?.label ?? \"Unavailable node\"} seed={targetNode?.id} size=\"sm\" aria-hidden=\"true\" /><span>{targetNode?.label ?? \"Unavailable node\"}</span></div><input type=\"hidden\" name=\"target\" value={target} /><PortSelect node={targetNode} direction=\"input\" name=\"targetPort\" pending={pending} portId={targetPortId} /></Field.Root>\n      ) : endpoint !== \"source\" && (\n        <>\n          <GraphFormSelect\n            label=\"Connect to\"\n            value={target}\n            autoFocus={endpoint === \"target\"}\n            onValueChange={setTarget}\n            options={value.nodes\n              .filter((node) => node.id !== source)\n              .map((node) => ({ value: node.id, label: node.label, leading: <Avatar name={node.label} seed={node.id} size=\"sm\" aria-hidden=\"true\" /> }))}\n            disabled={pending}\n          />\n          <PortSelect\n            node={targetNode}\n            direction=\"input\"\n            name=\"targetPort\"\n            pending={pending}\n            portId={target === edge?.target ? edge.targetPort : targetPortId}\n          />\n        </>\n      )}\n      {!endpoint && (\n        <GraphFormSelect\n          name=\"role\"\n          label=\"Relationship type\"\n          options={roles}\n          defaultValue={role}\n          disabled={pending}\n        />\n      )}\n      <div className=\"ui-graph-form-actions\">\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          variant=\"ghost\"\n          disabled={pending}\n          onClick={onCancel}\n        >\n          Cancel\n        </Button>\n        <Button type=\"submit\" size=\"sm\" disabled={pending}>\n          {endpoint ? \"Reconnect\" : \"Connect\"}\n        </Button>\n      </div>\n    </form>\n  );\n}\nfunction GraphEditor({ open, onOpenChange, anchor, title, side = \"bottom\", pending = false, className = \"ui-graph-popup\", children }: {\n  open: boolean; onOpenChange: (open: boolean) => void; anchor: Element | null; title: string;\n  side?: \"top\" | \"right\" | \"bottom\"; pending?: boolean; className?: string; children: React.ReactNode;\n}) {\n  const [mobile, setMobile] = React.useState(() => typeof window !== \"undefined\" && window.matchMedia?.(\"(max-width: 639px)\").matches === true);\n  React.useEffect(() => {\n    const query = window.matchMedia?.(\"(max-width: 639px)\");\n    if (!query) return;\n    const update = () => { if (!open) setMobile(query.matches); };\n    update(); query.addEventListener(\"change\", update);\n    return () => query.removeEventListener(\"change\", update);\n  }, [open]);\n  const change = (next: boolean) => { if (!pending) onOpenChange(next); };\n  const restoreFocus = () => anchor instanceof HTMLElement && anchor.isConnected ? anchor : undefined;\n  if (mobile) return <Drawer.Root open={open} onOpenChange={change} swipeDirection=\"down\"><Drawer.Portal><Drawer.Viewport><Drawer.Backdrop /><Drawer.Popup grip className={className} aria-label={title} finalFocus={restoreFocus}><Drawer.Content><Drawer.Header><Drawer.Title>{title}</Drawer.Title><Drawer.Close disabled={pending} render={<IconButton icon={<X />} size=\"icon-xs\" variant=\"ghost\" aria-label=\"Close editor\" />} /></Drawer.Header><Drawer.Core>{children}</Drawer.Core></Drawer.Content></Drawer.Popup></Drawer.Viewport></Drawer.Portal></Drawer.Root>;\n  return <Popover.Root open={open} onOpenChange={change}><Popover.Portal><Popover.Positioner anchor={anchor} side={side} align=\"start\" sideOffset={10}><Popover.Popup className={className} aria-label={title} finalFocus={restoreFocus}><Popover.Arrow /><Popover.Header><Popover.Title className=\"ui-graph-editor-title\">{title}</Popover.Title><Popover.Close aria-label=\"Close editor\" disabled={pending} /></Popover.Header><Popover.Core>{children}</Popover.Core></Popover.Popup></Popover.Positioner></Popover.Portal></Popover.Root>;\n}\n\nexport function GraphEdgeLabel({\n  data,\n  label,\n}: {\n  data: FlowEdgeData;\n  selected?: boolean;\n  label: GraphPoint;\n}) {\n  const [open, setOpen] = React.useState(false), [menuOpen, setMenuOpen] = React.useState(false);\n  const labelRef = React.useRef<HTMLDivElement>(null);\n  const edge = data.graphEdge;\n  if (!edge.label && !data.canMutate) return null;\n  return (\n    <div\n      ref={labelRef}\n      className={`ui-graph-edge-label nodrag nopan${!edge.label ? \" ui-graph-edge-label--quiet\" : \"\"}`}\n      data-hovered={data.hovered || undefined}\n      style={{\n        transform: `translate(-50%,-50%) translate(${label.x}px,${label.y}px)`,\n      }}\n    >\n      {edge.label && <span className=\"ui-graph-edge-label__text\">{edge.label}</span>}\n      {data.canMutate && (\n        <DropdownMenu.Root open={menuOpen} onOpenChange={setMenuOpen}>\n          <DropdownMenu.Trigger render={<IconButton className=\"ui-edge-action-button\" size=\"icon-xs\" variant=\"subtle\" icon={<Ellipsis />} aria-label={`Actions for connection from ${data.sourceNode?.label ?? \"node\"} to ${data.targetNode?.label ?? \"node\"}`} />} />\n          <DropdownMenu.Portal><DropdownMenu.Positioner side=\"top\"><DropdownMenu.Popup>\n            <DropdownMenu.Item onClick={() => { setMenuOpen(false); setOpen(true); }}><Pencil aria-hidden=\"true\" />Edit connection</DropdownMenu.Item>\n            <DropdownMenu.Item onClick={() => { setMenuOpen(false); data.onReconnect(edge, \"source\", labelRef.current); }}><ArrowUp aria-hidden=\"true\" />Change start node</DropdownMenu.Item>\n            <DropdownMenu.Item onClick={() => { setMenuOpen(false); data.onReconnect(edge, \"target\", labelRef.current); }}><ArrowDown aria-hidden=\"true\" />Change end node</DropdownMenu.Item>\n            <DropdownMenu.Separator />\n            <DropdownMenu.Item onClick={() => void data.onChange({ type: \"disconnect\", edgeId: edge.id })}><Link2 aria-hidden=\"true\" />Disconnect</DropdownMenu.Item>\n          </DropdownMenu.Popup></DropdownMenu.Positioner></DropdownMenu.Portal>\n        </DropdownMenu.Root>\n      )}\n      {data.canMutate && (\n        <GraphEditor open={open} onOpenChange={setOpen} anchor={labelRef.current} title=\"Edit relationship\" side=\"top\" pending={data.pending} className=\"ui-graph-edge-popup\">\n                  <div className=\"ui-graph-edge-context\" aria-label=\"Connection endpoints\">\n                    {[data.sourceNode, data.targetNode].map((node, index) => <React.Fragment key={index}>{index === 1 && <span className=\"ui-graph-edge-context__arrow\" aria-hidden=\"true\">→</span>}<span className=\"ui-graph-edge-context__node\"><Avatar name={node?.label ?? \"Unavailable node\"} seed={node?.id} size=\"sm\" aria-hidden=\"true\" /><span className=\"ui-graph-edge-context__identity\"><span>{node?.label ?? \"Unavailable node\"}</span>{node?.data && typeof node.data === \"object\" && \"role\" in node.data && <small>{String(node.data.role ?? \"\")}</small>}</span></span></React.Fragment>)}\n                  </div>\n                  <form\n                    key={edge.id}\n                    className=\"ui-graph-form\"\n                    onSubmit={(event) => {\n                      event.preventDefault();\n                      const form = new FormData(event.currentTarget);\n                      void data\n                        .onChange({\n                          type: \"update-edge\",\n                          edgeId: edge.id,\n                          label: String(form.get(\"label\") ?? \"\"),\n                          role: String(form.get(\"role\") ?? edge.role),\n                          line: String(\n                            form.get(\"line\") ?? \"solid\",\n                          ) as GraphEdge[\"line\"],\n                        })\n                        .then((ok) => {\n                          if (ok) setOpen(false);\n                        });\n                    }}\n                  >\n                    <Field.Root>\n                      <Field.Label>Relationship label</Field.Label>\n                      <Field.Control\n                        aria-label=\"Relationship label\"\n                        name=\"label\"\n                        defaultValue={edge.label ?? \"\"}\n                        disabled={data.pending}\n                      />\n                    </Field.Root>\n                    <GraphFormSelect\n                      name=\"role\"\n                      label=\"Relationship role\"\n                      options={data.roles}\n                      defaultValue={edge.role}\n                      disabled={data.pending}\n                    />\n                    <GraphFormSelect\n                      name=\"line\"\n                      label=\"Line style\"\n                      options={[\n                        { value: \"solid\", label: \"Solid\" },\n                        { value: \"dashed\", label: \"Dashed\" },\n                        { value: \"dotted\", label: \"Dotted\" },\n                      ]}\n                      defaultValue={edge.line ?? \"solid\"}\n                      disabled={data.pending}\n                    />\n                    <Button type=\"submit\" size=\"sm\" disabled={data.pending}>\n                      Apply\n                    </Button>\n                  </form>\n        </GraphEditor>\n      )}\n    </div>\n  );\n}\n\ntype Draft<N, E> = {\n  node?: GraphNode<N>;\n  sourcePortId?: string;\n  anchor?: Element | null;\n  mode:\n    | \"root\"\n    | \"child\"\n    | \"parent\"\n    | \"sibling\"\n    | \"rename\"\n    | \"move\"\n    | \"relationship\"\n    | \"canvas\"\n    | \"position\"\n    | \"reorder\"\n    | \"remove\"\n    | \"reconnect\";\n  direction?: \"up\" | \"down\";\n  parentId?: string;\n  edge?: GraphEdge<E>;\n  endpoint?: \"source\" | \"target\";\n  targetId?: string;\n  targetPortId?: string;\n};\nfunction SurfaceInner<N, E>(\n  props: GraphSurfaceProps<N, E>,\n  ref: React.Ref<GraphViewportHandle | null>,\n) {\n  const positionFieldId = React.useId();\n  const {\n    mode,\n    align = \"center\",\n    fit = \"width\",\n    collapsible = true,\n    viewport = false,\n    connector = \"elbow\",\n    routes,\n    value,\n    editable = false,\n    onChange,\n    getChangePermission,\n    renderNode,\n    nodeWidth = 224,\n    createNode,\n    createEdge,\n    nodeTemplates,\n    relationshipTypes,\n    connectionRole,\n    selectedNodeId,\n    onSelectedNodeIdChange,\n    onEditNode,\n    renderNodeFooter,\n    hierarchyRole = \"reporting\",\n    collapsedIds,\n    defaultCollapsedIds,\n    onCollapsedIdsChange,\n    search,\n    onSearchChange,\n    direction = \"down\",\n    layout,\n    nodeGap = align === \"start\" ? 32 : 56,\n    levelGap = align === \"start\" ? 24 : 64,\n    positions,\n    defaultPositions,\n    acyclicRoles,\n    nativeProps,\n    rootRef,\n  } = props;\n  const Renderer = viewport;\n  if (mode === \"canvas\" && !Renderer)\n    throw Error(\"Canvas mode needs a viewport renderer\");\n  const canvas = mode === \"canvas\" || Boolean(Renderer);\n  const canMutate = Boolean(editable && onChange),\n    role = connectionRole ?? (mode === \"diagram\" ? hierarchyRole : \"data\");\n  const options = React.useMemo<GraphOptions>(\n    () => ({\n      hierarchyRole: mode === \"diagram\" ? hierarchyRole : null,\n      acyclicRoles: acyclicRoles ?? (mode === \"canvas\" ? [] : undefined),\n    }),\n    [mode, hierarchyRole, acyclicRoles],\n  );\n  React.useMemo(() => assertGraphValue(value, options), [value, options]);\n  const element = React.useRef<HTMLDivElement>(null),\n    pendingRef = React.useRef(false);\n  const [hostWidth, setHostWidth] = React.useState(0);\n  React.useLayoutEffect(() => {\n    if (canvas || !element.current) return;\n    const host = element.current;\n    const update = (width: number) => setHostWidth((current) => current === width ? current : width);\n    update(host.clientWidth);\n    if (typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(([entry]) => update(entry.contentRect.width));\n    observer.observe(host);\n    return () => observer.disconnect();\n  }, [canvas]);\n  const [pending, setPending] = React.useState(false),\n    [error, setError] = React.useState(\"\");\n  const [localCollapsed, setLocalCollapsed] = React.useState<readonly string[]>(\n    defaultCollapsedIds ?? [],\n  );\n  const collapsed = React.useMemo(\n    () => new Set(collapsible ? collapsedIds ?? localCollapsed : []),\n    [collapsible, collapsedIds, localCollapsed],\n  );\n  const latestCollapsed = React.useRef(collapsed);\n  latestCollapsed.current = collapsed;\n  const [localSearch, setLocalSearch] = React.useState(\"\"),\n    query = search ?? localSearch;\n  const [localSelected, setLocalSelected] = React.useState<string>(),\n    selected = selectedNodeId === undefined ? localSelected : selectedNodeId;\n  const [selectedEdge, setSelectedEdge] = React.useState<string>();\n  const [hoveredEdge, setHoveredEdge] = React.useState<string>();\n  const [hoveredPort, setHoveredPort] = React.useState<{ nodeId: string; portId: string }>();\n  const [draft, setDraft] = React.useState<Draft<N, E>>(),\n    [actionsOpen, setActionsOpen] = React.useState<string>();\n  const [localPositions, setLocalPositions] = React.useState<GraphPositions>(\n      defaultPositions ?? {},\n    ),\n    [sizes, setSizes] = React.useState<Record<string, GraphSize>>({});\n  const [nodes, setNodes] = React.useState<FlowNode[]>([]);\n  const [rf, setRf] = React.useState<GraphViewportHandle | null>(null);\n  React.useImperativeHandle(ref, () => rf!, [rf]);\n  const nodeById = React.useMemo(\n    () => new Map(value.nodes.map((node) => [node.id, node])),\n    [value.nodes],\n  );\n  const incoming = React.useCallback(\n    (id: string) =>\n      value.edges.filter(\n        (edge) => edge.role === hierarchyRole && edge.target === id,\n      ),\n    [value.edges, hierarchyRole],\n  );\n  const roles = React.useMemo(() => {\n    const names = new Map(\n      (\n        relationshipTypes ?? [\n          {\n            value: role,\n            label: mode === \"diagram\" ? \"Reporting line\" : \"Data\",\n          },\n        ]\n      ).map((item) => [item.value, item.label]),\n    );\n    for (const edge of value.edges)\n      if (!names.has(edge.role)) names.set(edge.role, edge.role);\n    return [...names].map(([value, label]) => ({ value, label }));\n  }, [relationshipTypes, role, value.edges, mode]);\n  const widthFor = React.useCallback(\n    (node: GraphNode<N>) => {\n      const width = typeof nodeWidth === \"number\" ? nodeWidth : nodeWidth(node);\n      if (!Number.isFinite(width) || width <= 0)\n        throw Error(`Node ${node.id} needs a positive finite width`);\n      return width;\n    },\n    [nodeWidth],\n  );\n  const visible = React.useMemo(() => {\n    const queryText = query.trim().toLocaleLowerCase();\n    if (!queryText)\n      return getGraphProjection(value, { ...options, collapsedIds: collapsed });\n    const needed = new Set(\n      value.nodes\n        .filter((node) => node.label.toLocaleLowerCase().includes(queryText))\n        .map((node) => node.id),\n    );\n    const parents = new Map<string, string[]>();\n    for (const edge of value.edges)\n      if (edge.role === options.hierarchyRole) {\n        const list = parents.get(edge.target) ?? [];\n        list.push(edge.source);\n        parents.set(edge.target, list);\n      }\n    const queue = [...needed];\n    for (let i = 0; i < queue.length; i++)\n      for (const id of parents.get(queue[i]) ?? [])\n        if (!needed.has(id)) {\n          needed.add(id);\n          queue.push(id);\n        }\n    return {\n      nodes: value.nodes.filter((node) => needed.has(node.id)),\n      edges: value.edges.filter(\n        (edge) => needed.has(edge.source) && needed.has(edge.target),\n      ),\n    };\n  }, [value, query, options, collapsed]);\n  const geometry = React.useMemo<GraphLayout>(() => {\n    if (mode === \"diagram\") {\n      if (!layout) throw Error(\"Diagram requires a layout function\");\n      return layout(\n        visible,\n        Object.fromEntries(\n          visible.nodes.map((node) => [\n            node.id,\n            ownValue(sizes, node.id) ?? { width: widthFor(node), height: 104 },\n          ]),\n        ),\n        { ...options, direction, align, nodeGap, levelGap },\n      );\n    }\n    const source = positions ?? localPositions;\n    return {\n      positions: Object.fromEntries(\n        value.nodes.map((node, index) => {\n          const position = ownValue(source, node.id) ?? {\n            x: 48 + (index % 3) * 300,\n            y: 48 + Math.floor(index / 3) * 240,\n          };\n          if (!Number.isFinite(position.x) || !Number.isFinite(position.y))\n            throw Error(`Invalid position for ${node.id}`);\n          return [node.id, position];\n        }),\n      ),\n    };\n  }, [\n    mode,\n    layout,\n    visible,\n    sizes,\n    widthFor,\n    options,\n    direction,\n    align,\n    nodeGap,\n    levelGap,\n    positions,\n    localPositions,\n    value.nodes,\n  ]);\n  const nodeAnchors = React.useMemo(\n    () => normalizeGraphAnchors(visible.nodes.map((node) => node.id), geometry.anchors, direction),\n    [visible.nodes, geometry.anchors, direction],\n  );\n  const latestGeometry = React.useRef(geometry.positions);\n  latestGeometry.current = geometry.positions;\n  const send = React.useCallback(\n    async (change: GraphChange<N, E>): Promise<boolean> => {\n      if (!canMutate || pendingRef.current || !onChange) return false;\n      try {\n        const invalid = getGraphChangeError(value, change, options);\n        if (invalid) throw Error(invalid);\n        const permission = getChangePermission?.(change);\n        if (permission && !permission.allowed) throw Error(permission.reason);\n        pendingRef.current = true;\n        setPending(true);\n        setError(\"\");\n        await onChange(change);\n        if (mode === \"canvas\" && positions === undefined)\n          setLocalPositions((current) =>\n            applyGraphPositions(\n              { ...latestGeometry.current, ...current },\n              change,\n            ),\n          );\n        return true;\n      } catch (cause) {\n        setError(\n          cause instanceof Error\n            ? cause.message\n            : \"The change could not be saved.\",\n        );\n        return false;\n      } finally {\n        pendingRef.current = false;\n        setPending(false);\n      }\n    },\n    [canMutate, onChange, value, options, getChangePermission, mode, positions],\n  );\n  const closeDraft = () => {\n    setDraft(undefined);\n    setError(\"\");\n  };\n  const submit = async (change: GraphChange<N, E>) => {\n    try {\n      const proposal =\n        change.type === \"connect\" && createEdge\n          ? { ...change, edge: createEdge(change.edge) }\n          : change;\n      if (await send(proposal)) setDraft(undefined);\n    } catch (cause) {\n      setError(\n        cause instanceof Error\n          ? cause.message\n          : \"Could not create this relationship.\",\n      );\n    }\n  };\n  const toggle = (id: string) => {\n    const next = new Set(latestCollapsed.current);\n    next.has(id) ? next.delete(id) : next.add(id);\n    if (collapsedIds === undefined) setLocalCollapsed([...next]);\n    onCollapsedIdsChange?.([...next]);\n  };\n  const select = (id: string | undefined) => {\n    setLocalSelected(id);\n    onSelectedNodeIdChange?.(id);\n    if (id) setSelectedEdge(undefined);\n  };\n  const action = (\n    node: GraphNode<N>,\n    action: NodeAction,\n    sourcePortId?: string,\n    anchor?: Element | null,\n  ) => {\n    if (!canMutate || pendingRef.current) return;\n    setError(\"\");\n    const context = { node, anchor: anchor ?? element.current };\n    if (action === \"rename\") {\n      if (onEditNode) onEditNode(node);\n      else setDraft({ ...context, mode: \"rename\" });\n    } else if (action === \"relationship\" && sourcePortId && node.ports?.some((port) => port.id === sourcePortId && port.direction === \"input\")) {\n      setDraft({ ...context, mode: \"relationship\", targetId: node.id, targetPortId: sourcePortId });\n    } else if (action === \"child\" || action === \"parent\" || action === \"sibling\") {\n      setDraft({ ...context, mode: action, sourcePortId });\n    } else setDraft({ ...context, mode: action, sourcePortId });\n  };\n  const roots = React.useMemo(() => {\n    const targets = new Set(\n      value.edges\n        .filter((edge) => edge.role === hierarchyRole)\n        .map((edge) => edge.target),\n    );\n    return value.nodes.filter((node) => !targets.has(node.id));\n  }, [value, hierarchyRole]);\n  React.useEffect(() => {\n    if (\n      draft?.node &&\n      !value.nodes.some((node) => node.id === draft.node?.id)\n    ) {\n      setDraft(undefined);\n      setError(\"\");\n      return;\n    }\n    if (\n      draft?.edge &&\n      !value.edges.some((edge) => edge.id === draft.edge?.id)\n    ) {\n      setDraft(undefined);\n      setError(\"\");\n    }\n  }, [draft, value.nodes, value.edges]);\n  const reorderChange = (\n    nodeId: string,\n    way: \"up\" | \"down\",\n    edgeId?: string,\n  ): GraphChange<N, E> | undefined => {\n    if (edgeId) {\n      const edge = value.edges.find((item) => item.id === edgeId);\n      if (!edge) return;\n      const siblings = value.edges.filter(\n          (item) => item.role === edge.role && item.source === edge.source,\n        ),\n        index = siblings.findIndex((item) => item.id === edgeId);\n      if (way === \"up\" ? index <= 0 : index >= siblings.length - 1) return;\n      return {\n        type: \"reorder\",\n        edgeId,\n        beforeEdgeId:\n          way === \"up\"\n            ? siblings[index - 1].id\n            : (siblings[index + 2]?.id ?? null),\n      };\n    }\n    const index = roots.findIndex((node) => node.id === nodeId);\n    if (index < 0 || (way === \"up\" ? index === 0 : index === roots.length - 1))\n      return;\n    return {\n      type: \"reorder-root\",\n      nodeId,\n      beforeNodeId:\n        way === \"up\" ? roots[index - 1].id : (roots[index + 2]?.id ?? null),\n    };\n  };\n  const reorder = (\n    node: GraphNode<N>,\n    way: \"up\" | \"down\",\n    anchor?: Element | null,\n  ) => {\n    const parents = incoming(node.id);\n    if (parents.length > 1) {\n      setError(\"\");\n      setDraft({\n        node,\n        mode: \"reorder\",\n        direction: way,\n        anchor: anchor ?? element.current,\n      });\n      return;\n    }\n    const change = reorderChange(node.id, way, parents[0]?.id);\n    if (change) void send(change);\n  };\n  const create = (\n    label: string,\n    parentId?: string,\n    sourcePortId?: string,\n    templateId?: string,\n    siblingId?: string,\n    formData?: FormData,\n    relation: \"child\" | \"parent\" | \"sibling\" = \"child\",\n  ) => {\n    try {\n      const parent = parentId ? nodeById.get(parentId) : undefined;\n      if (parentId && !parent)\n        throw Error(\"The parent is no longer available.\");\n      const sourcePort =\n        mode === \"canvas\"\n          ? parent?.ports?.find(\n              (port) => port.direction === (relation === \"parent\" ? \"input\" : \"output\") && port.id === sourcePortId,\n            )\n          : undefined;\n      if (mode === \"canvas\" && parent?.ports?.length && !sourcePort)\n        throw Error(\"Choose an output port.\");\n      const template = nodeTemplates?.find(\n        (template) => template.id === templateId,\n      );\n      if (nodeTemplates?.length && !template)\n        throw Error(\"Choose a node type.\");\n      if (\n        parent &&\n        template?.accepts &&\n        (!sourcePort?.type || !template.accepts.includes(sourcePort.type))\n      )\n        throw Error(\"This node type does not accept the selected output.\");\n      const context = {\n        id: newId(),\n        label: label.trim(),\n        parentId: relation === \"parent\" ? undefined : parentId,\n        relatedNodeId: parentId,\n        siblingId,\n        sourcePort: relation === \"parent\" ? undefined : sourcePort,\n        targetPort: relation === \"parent\" ? sourcePort : undefined,\n        formData,\n        relation,\n      };\n      if (!context.label) throw Error(\"Name this node before creating it.\");\n      const node = template?.create(context) ??\n        createNode?.(context) ?? { id: context.id, label: context.label };\n      const inputs =\n          node.ports?.filter((port) => port.direction === \"input\") ?? [],\n        outputs = node.ports?.filter((port) => port.direction === \"output\") ?? [],\n        targetPort = inputs.find(\n          (port) =>\n            port.maxConnections !== 0 &&\n            (!port.accepts ||\n              Boolean(\n                sourcePort?.type && port.accepts.includes(sourcePort.type),\n              )),\n        );\n      const upstreamPort = outputs.find((port) => port.maxConnections !== 0 && (!sourcePort?.accepts || Boolean(port.type && sourcePort.accepts.includes(port.type))));\n      if (mode === \"canvas\" && relation !== \"parent\" && parent && inputs.length && !targetPort)\n        throw Error(\"The new node has no compatible input port.\");\n      if (mode === \"canvas\" && relation === \"parent\" && parent && !upstreamPort)\n        throw Error(\"The new node has no output compatible with this input.\");\n      const connection = parent\n        ? {\n            id: newId(),\n            source: relation === \"parent\" ? node.id : parent.id,\n            target: relation === \"parent\" ? parent.id : node.id,\n            role,\n            sourcePort: relation === \"parent\" && mode === \"canvas\" ? upstreamPort?.id : relation === \"parent\" ? undefined : sourcePort?.id,\n            targetPort: mode === \"canvas\" ? relation === \"parent\" ? sourcePort?.id : targetPort?.id : undefined,\n          }\n        : undefined;\n      const edge = connection\n        ? (createEdge?.(connection) ?? connection)\n        : undefined;\n      let position: GraphPoint | undefined;\n      if (mode === \"canvas\") {\n        const origin = parent ? geometry.positions[parent.id] : undefined,\n          host = element.current?.getBoundingClientRect();\n        position = origin\n          ? { x: origin.x + (relation === \"parent\" ? -widthFor(node) - 120 : widthFor(parent!) + 120), y: origin.y }\n          : rf && host\n            ? rf.screenToFlowPosition({\n                x: host.left + host.width / 2,\n                y: host.top + host.height / 2,\n              })\n            : { x: 48, y: 48 };\n        const width = widthFor(node),\n          height = 160;\n        for (let count = 0; count <= nodes.length; count++) {\n          const overlap = nodes.find(\n            (item) =>\n              item.position.x < position!.x + width + 24 &&\n              item.position.x +\n                (item.measured?.width ?? item.width ?? 224) +\n                24 >\n                position!.x &&\n              item.position.y < position!.y + height + 24 &&\n              item.position.y + (item.measured?.height ?? 104) + 24 >\n                position!.y,\n          );\n          if (!overlap) break;\n          position = {\n            ...position,\n            y: overlap.position.y + (overlap.measured?.height ?? 104) + 40,\n          };\n        }\n      }\n      const siblingEdge = siblingId ? incoming(siblingId)[0] : undefined;\n      const siblings = siblingEdge ? value.edges.filter((candidate) => candidate.source === siblingEdge.source && candidate.role === siblingEdge.role) : [];\n      const siblingIndex = siblingEdge ? siblings.findIndex((candidate) => candidate.id === siblingEdge.id) : -1;\n      void send({ type: \"insert\", node, edge, position, beforeNodeId: relation === \"sibling\" ? siblingId : undefined, beforeEdgeId: relation === \"sibling\" ? siblings[siblingIndex + 1]?.id ?? null : undefined }).then((ok) => {\n        if (ok) {\n          setDraft(undefined);\n          if (\n            mode === \"diagram\" &&\n            parentId &&\n            latestCollapsed.current.has(parentId)\n          )\n            toggle(parentId);\n          if (mode === \"canvas\" && position)\n            void rf?.setCenter(\n              position.x + widthFor(node) / 2,\n              position.y + 80,\n              {\n                zoom: Math.min(rf.getZoom(), 1),\n              },\n            );\n        }\n      });\n    } catch (cause) {\n      setError(\n        cause instanceof Error ? cause.message : \"Could not create this node.\",\n      );\n    }\n  };\n  const computedNodes = React.useMemo<FlowNode[]>(\n    () =>\n      visible.nodes.map((node): FlowNode => {\n        const parents = incoming(node.id),\n          canReorder = { up: false, down: false };\n        for (const way of [\"up\", \"down\"] as const)\n          canReorder[way] = parents.length\n            ? parents.some((edge) =>\n                Boolean(reorderChange(node.id, way, edge.id)),\n              )\n            : Boolean(reorderChange(node.id, way));\n        const position = ownValue(geometry.positions, node.id);\n        const parentEdge = parents[0], siblings = parentEdge ? value.edges.filter((edge) => edge.source === parentEdge.source && edge.role === parentEdge.role) : [];\n        const siblingIndex = parentEdge ? siblings.findIndex((edge) => edge.id === parentEdge.id) : roots.findIndex((root) => root.id === node.id);\n        const beforeNode = siblingIndex > 0 ? nodeById.get(parentEdge ? siblings[siblingIndex - 1].target : roots[siblingIndex - 1].id)?.label : undefined;\n        const afterNode = parentEdge ? nodeById.get(siblings[siblingIndex + 1]?.target ?? \"\")?.label : nodeById.get(roots[siblingIndex + 1]?.id ?? \"\")?.label;\n        if (\n          !position ||\n          !Number.isFinite(position.x) ||\n          !Number.isFinite(position.y)\n        )\n          throw Error(`Layout omitted a finite position for ${node.id}`);\n        return {\n          id: graphEngineId(node.id),\n          type: \"graphNode\",\n          position,\n          width: widthFor(node),\n          measured: ownValue(sizes, node.id),\n          selected: selected === node.id,\n          ariaLabel: node.label + (selected === node.id ? \", selected\" : \"\"),\n          data: {\n            graphNode: node,\n            mode,\n            direction,\n            anchors: nodeAnchors[node.id],\n            collapsed: !query.trim() && collapsed.has(node.id),\n            canToggle:\n              collapsible &&\n              !query.trim() &&\n              (collapsedIds === undefined || Boolean(onCollapsedIdsChange)),\n            childNoun: hierarchyRole === \"reporting\" ? \"report\" : \"child\",\n            childCount: collapsible ? new Set(\n              value.edges\n                .filter(\n                  (edge) =>\n                    edge.role === hierarchyRole && edge.source === node.id,\n                )\n                .map((edge) => edge.target),\n            ).size : 0,\n            descendantCount: collapsible ? getGraphDescendants(value, node.id, hierarchyRole).size : 0,\n            orderTarget: { before: beforeNode, after: afterNode },\n            renderNodeFooter: renderNodeFooter as FlowNodeData[\"renderNodeFooter\"],\n            portHighlighted: hoveredPort?.nodeId === node.id,\n            connectedPortIds: value.edges.flatMap((edge) => [\n              ...(edge.source === node.id && edge.sourcePort ? [edge.sourcePort] : []),\n              ...(edge.target === node.id && edge.targetPort ? [edge.targetPort] : []),\n            ]),\n            onPortHover: (nodeId, portId) => setHoveredPort(portId ? { nodeId, portId } : undefined),\n            renderNode: renderNode as FlowNodeData[\"renderNode\"],\n            onToggle: toggle,\n            onAction: action,\n            onReorder: reorder,\n            canReorder,\n            actionsOpen: actionsOpen === node.id,\n            onActionsOpenChange: setActionsOpen,\n            canMutate,\n            pending,\n            stagedParent: false,\n          },\n        };\n      }),\n    [\n      visible.nodes,\n      incoming,\n      roots,\n      geometry,\n      nodeAnchors,\n      widthFor,\n      sizes,\n      selected,\n      mode,\n      direction,\n      query,\n      collapsed,\n      value.edges,\n      hierarchyRole,\n      collapsible,\n      renderNodeFooter,\n      hoveredPort,\n      renderNode,\n      actionsOpen,\n      canMutate,\n      pending,\n      send,\n      createNode,\n      createEdge,\n      nodeTemplates,\n      onEditNode,\n      onCollapsedIdsChange,\n    ],\n  );\n  React.useEffect(() => setNodes(computedNodes), [computedNodes]);\n  const edges = React.useMemo<FlowEdge[]>(\n    () =>\n      visible.edges.map((edge) => ({\n        id: graphEngineId(edge.id),\n        source: graphEngineId(edge.source),\n        target: graphEngineId(edge.target),\n        sourceHandle:\n          edge.sourcePort === undefined\n            ? undefined\n            : graphEngineId(edge.sourcePort),\n        targetHandle:\n          edge.targetPort === undefined\n            ? undefined\n            : graphEngineId(edge.targetPort),\n        type: \"graphEdge\" as const,\n        interactionWidth: 24,\n        selected: selectedEdge === edge.id,\n        zIndex: hoveredEdge === edge.id ? 2 : selectedEdge === edge.id ? 1 : 0,\n        focusable: canMutate,\n        ariaLabel: `${nodeById.get(edge.source)?.label} to ${nodeById.get(edge.target)?.label}${edge.label ? `: ${edge.label}` : \"\"}`,\n        data: {\n          graphEdge: edge,\n          sourceNode: nodeById.get(edge.source),\n          targetNode: nodeById.get(edge.target),\n          hovered: hoveredEdge === edge.id,\n          portHighlighted: Boolean(hoveredPort && ((hoveredPort.nodeId === edge.source && hoveredPort.portId === edge.sourcePort) || (hoveredPort.nodeId === edge.target && hoveredPort.portId === edge.targetPort))),\n          onHover: (active) => setHoveredEdge(active ? edge.id : undefined),\n          onChange: send as FlowEdgeData[\"onChange\"],\n          onReconnect: (edge, endpoint, anchor) =>\n            setDraft({\n              mode: \"reconnect\",\n              edge,\n              endpoint,\n              anchor: anchor ?? element.current,\n            }),\n          canMutate,\n          pending,\n          roles,\n          connector,\n          direction: mode === \"canvas\" ? \"right\" : direction,\n          onSelect: () => {\n            select(undefined);\n            setSelectedEdge(edge.id);\n          },\n          layoutPath:\n            ownValue(routes ?? {}, edge.id) ??\n            ownValue(geometry.paths ?? {}, edge.id)?.slice(1, -1),\n        },\n        style: {\n          strokeDasharray:\n            edge.line === \"dashed\"\n              ? \"5 4\"\n              : edge.line === \"dotted\"\n                ? \"2 4\"\n                : undefined,\n        },\n      })),\n    [\n      visible.edges,\n      selectedEdge,\n      hoveredEdge,\n      hoveredPort,\n      nodeById,\n      send,\n      canMutate,\n      pending,\n      roles,\n      geometry.paths,\n      connector,\n      direction,\n      mode,\n      routes,\n    ],\n  );\n  const onNodesChange = (changes: GraphViewNodeChange[]) => {\n    setNodes((current) =>\n      current.map((node) => {\n        let result = node;\n        for (const change of changes)\n          if (change.id === node.id) {\n            if (change.type === \"position\" && change.position)\n              result = { ...result, position: change.position };\n            if (change.type === \"select\")\n              result = { ...result, selected: change.selected };\n            if (change.type === \"dimensions\" && change.dimensions)\n              result = { ...result, measured: change.dimensions };\n          }\n        return result;\n      }),\n    );\n    const dimensions = changes.filter(\n      (change) => change.type === \"dimensions\" && change.dimensions,\n    );\n    if (dimensions.length)\n      setSizes((current) => {\n        const next = { ...current };\n        let changed = false;\n        for (const change of dimensions)\n          if (change.type === \"dimensions\" && change.dimensions) {\n            const id = graphPublicId(change.id),\n              size = change.dimensions;\n            if (\n              id &&\n              size.width > 0 &&\n              size.height > 0 &&\n              (ownValue(current, id)?.width !== size.width ||\n                ownValue(current, id)?.height !== size.height)\n            ) {\n              Object.defineProperty(next, id, {\n                value: { width: size.width, height: size.height },\n                enumerable: true,\n                configurable: true,\n                writable: true,\n              });\n              changed = true;\n            }\n          }\n        return changed ? next : current;\n      });\n    for (const change of changes)\n      if (change.type === \"select\" && change.selected) {\n        const id = graphPublicId(change.id);\n        if (id) select(id);\n      }\n    const moves = changes.flatMap((change) => {\n      if (\n        change.type !== \"position\" ||\n        change.dragging !== false ||\n        !change.position\n      )\n        return [];\n      const nodeId = graphPublicId(change.id);\n      if (!nodeId) return [];\n      const from = ownValue(geometry.positions, nodeId);\n      return from &&\n        (from.x !== change.position.x || from.y !== change.position.y)\n        ? [{ nodeId, position: change.position, from }]\n        : [];\n    });\n    if (mode === \"canvas\" && moves.length)\n      void send({ type: \"position\", moves }).then((ok) => {\n        if (!ok) setNodes(computedNodes);\n      });\n    if (\n      mode === \"diagram\" &&\n      changes.some((change) => change.type === \"position\" && !change.dragging)\n    )\n      setNodes(computedNodes);\n  };\n  const parentTarget = (moved: FlowNode) =>\n    nodes.find(\n      (candidate) =>\n        candidate.id !== moved.id &&\n        candidate.position.x <\n          moved.position.x + (moved.measured?.width ?? moved.width ?? 224) &&\n        candidate.position.x +\n          (candidate.measured?.width ?? candidate.width ?? 224) >\n          moved.position.x &&\n        candidate.position.y <\n          moved.position.y + (moved.measured?.height ?? 104) &&\n        candidate.position.y + (candidate.measured?.height ?? 104) >\n          moved.position.y,\n    );\n  const drag = (moved: FlowNode) => {\n    if (mode !== \"diagram\") return;\n    const target = parentTarget(moved);\n    setNodes((current) =>\n      current.map((node) =>\n        node.data.stagedParent === (node.id === target?.id)\n          ? node\n          : {\n              ...node,\n              data: { ...node.data, stagedParent: node.id === target?.id },\n            },\n      ),\n    );\n  };\n  const dragStop = (moved: FlowNode) => {\n    if (mode !== \"diagram\") return;\n    const target = parentTarget(moved),\n      nodeId = graphPublicId(moved.id),\n      parentId = target?.data.graphNode.id;\n    setNodes(computedNodes);\n    if (!nodeId || !parentId) return;\n    const node = nodeById.get(nodeId),\n      parents = incoming(nodeId);\n    if (!node || parents.some((edge) => edge.source === parentId)) return;\n    if (parents.length > 1)\n      setDraft({\n        node,\n        mode: \"move\",\n        parentId,\n        anchor: element.current?.querySelector(\n          `[data-id=\"${moved.id}\"] .ui-graph-node`,\n        ),\n      });\n    else if (parents[0])\n      void send({ type: \"move\", edgeId: parents[0].id, parentId });\n    else\n      void submit({\n        type: \"connect\",\n        edge: {\n          id: newId(),\n          source: parentId,\n          target: nodeId,\n          role: hierarchyRole,\n        },\n      });\n  };\n  const connect = (\n    connection: Parameters<GraphViewportProps[\"onConnect\"]>[0],\n  ) => {\n    const source = graphPublicId(connection.source),\n      target = graphPublicId(connection.target);\n    if (source && target)\n      void submit({\n        type: \"connect\",\n        edge: {\n          id: newId(),\n          source,\n          target,\n          role,\n          sourcePort: connection.sourceHandle\n            ? graphPublicId(connection.sourceHandle)\n            : undefined,\n          targetPort: connection.targetHandle\n            ? graphPublicId(connection.targetHandle)\n            : undefined,\n        },\n      });\n  };\n  const reconnect = (\n    edge: FlowEdge,\n    connection: Parameters<GraphViewportProps[\"onConnect\"]>[0],\n  ) => {\n    const edgeId = graphPublicId(edge.id),\n      endpoint =\n        connection.source !== edge.source ||\n        connection.sourceHandle !== (edge.sourceHandle ?? null)\n          ? \"source\"\n          : \"target\",\n      nodeId = graphPublicId(\n        endpoint === \"source\" ? connection.source : connection.target,\n      ),\n      port =\n        endpoint === \"source\"\n          ? connection.sourceHandle\n          : connection.targetHandle;\n    if (edgeId && nodeId)\n      void submit({\n        type: \"reconnect\",\n        edgeId,\n        endpoint,\n        nodeId,\n        portId: port ? graphPublicId(port) : undefined,\n      });\n  };\n  const submitDraft = (event: React.FormEvent<HTMLFormElement>) => {\n    event.preventDefault();\n    if (!draft) return;\n    const form = new FormData(event.currentTarget),\n      node = draft.node;\n    if (draft.mode === \"rename\" && node) {\n      const currentParents = incoming(node.id), currentParentEdge = currentParents.find((edge) => edge.id === String(form.get(\"parentEdgeId\") ?? \"\")) ?? currentParents[0], newParentId = String(form.get(\"newParent\") ?? \"\");\n      const data = node.data && typeof node.data === \"object\" && !Array.isArray(node.data) ? node.data as Record<string, unknown> : undefined;\n      const update: GraphChange<N, E> = data ? { type: \"update-node\", nodeId: node.id, label: String(form.get(\"label\") ?? \"\"), data: { ...data, role: String(form.get(\"role\") ?? data.role ?? \"\"), avatarSeed: String(form.get(\"avatarSeed\") ?? data.avatarSeed ?? node.id) } as N } : { type: \"update-node\", nodeId: node.id, label: String(form.get(\"label\") ?? \"\") };\n      void send(update).then(async (saved) => {\n        if (!saved) return;\n        if (newParentId && newParentId !== currentParents[0]?.source) {\n          const moved = currentParentEdge\n            ? await send({ type: \"move\", edgeId: currentParentEdge.id, parentId: newParentId })\n            : await send({ type: \"connect\", edge: { id: newId(), source: newParentId, target: node.id, role: hierarchyRole } });\n          if (!moved) { setError(\"Details were saved. The parent did not change.\"); return; }\n        }\n        setDraft(undefined);\n      });\n    } else if (draft.mode === \"move\" && node) {\n      const parentId = String(form.get(\"parent\") ?? \"\"),\n        edgeId = String(form.get(\"edgeId\") ?? \"\");\n      void submit(\n        edgeId\n          ? { type: \"move\", edgeId, parentId }\n          : {\n              type: \"connect\",\n              edge: {\n                id: newId(),\n                source: parentId,\n                target: node.id,\n                role: hierarchyRole,\n              },\n            },\n      );\n    } else if (draft.mode === \"reorder\" && node && draft.direction) {\n      const change = reorderChange(\n        node.id,\n        draft.direction,\n        String(form.get(\"edgeId\") ?? \"\"),\n      );\n      if (change) void submit(change);\n      else\n        setError(\n          `This node is already ${draft.direction === \"up\" ? \"first\" : \"last\"} under that parent.`,\n        );\n    } else if (draft.mode === \"position\" && node) {\n      const x = String(form.get(\"x\") ?? \"\"),\n        y = String(form.get(\"y\") ?? \"\");\n      if (!x.trim() || !y.trim()) {\n        setError(\"Enter both coordinates.\");\n        return;\n      }\n      void submit({\n        type: \"position\",\n        moves: [\n          {\n            nodeId: node.id,\n            position: { x: Number(x), y: Number(y) },\n            from: ownValue(geometry.positions, node.id),\n          },\n        ],\n      });\n    }\n  };\n  const titles: Record<Draft<N, E>[\"mode\"], string> = {\n    root: mode === \"diagram\" ? \"Add root\" : \"Add node\",\n    child: \"Add child\",\n    parent: \"Add parent\",\n    sibling: \"Add sibling\",\n    rename: \"Edit details\",\n    move: \"Change parent\",\n    relationship: \"Add connection\",\n    canvas: \"Add connected node\",\n    position: \"Set position\",\n    reorder: `Move ${draft?.direction ?? \"\"}`,\n    remove: \"Remove node\",\n    reconnect: `Reconnect ${draft?.endpoint ?? \"\"}`,\n  };\n  const editor = draft && draft.mode !== \"remove\" && (\n    <GraphEditor open onOpenChange={(open) => { if (!open && !pending) closeDraft(); }} title={titles[draft.mode]} pending={pending} anchor={\n            (!draft.node ||\n              visible.nodes.some((node) => node.id === draft.node?.id)) &&\n            (!draft.edge ||\n              visible.edges.some((edge) => edge.id === draft.edge?.id)) &&\n            draft.anchor?.isConnected\n              ? draft.anchor\n              : element.current\n          }\n          side={\n            draft.mode === \"child\" || draft.mode === \"parent\" ||\n            draft.mode === \"root\" ||\n            draft.mode === \"sibling\"\n              ? \"bottom\"\n              : \"right\"\n          }\n          className=\"ui-graph-popup nodrag nopan\"\n        >\n              {error && (\n                <p className=\"ui-graph-error\" role=\"alert\">\n                  {error}\n                </p>\n              )}\n              {draft.mode === \"relationship\" || draft.mode === \"reconnect\" ? (\n                <ConnectionForm\n                  key={`${draft.mode}-${draft.node?.id ?? draft.edge?.id}-${draft.endpoint}`}\n                  value={value}\n                  sourceId={draft.targetId ? undefined : draft.node?.id}\n                  sourcePortId={draft.sourcePortId}\n                  targetId={draft.targetId}\n                  targetPortId={draft.targetPortId}\n                  edge={draft.edge}\n                  endpoint={draft.endpoint}\n                  role={role}\n                  roles={roles}\n                  pending={pending}\n                  onSubmit={submit}\n                  onCancel={closeDraft}\n                />\n              ) : draft.mode === \"root\" ||\n                draft.mode === \"child\" ||\n                draft.mode === \"parent\" ||\n                draft.mode === \"canvas\" ||\n                draft.mode === \"sibling\" ? (\n                <CreationForm\n                  key={`${draft.mode}-${draft.node?.id}`}\n                  draft={draft}\n                  value={value}\n                  mode={mode}\n                  hierarchyRole={hierarchyRole}\n                  templates={nodeTemplates}\n                  pending={pending}\n                  onCreate={create}\n                  onCancel={closeDraft}\n                />\n              ) : (\n                <form className=\"ui-graph-form\" onSubmit={submitDraft}>\n                  {draft.mode === \"rename\" && draft.node && (\n                    <>\n                      <Field.Root><Field.Label>Name</Field.Label><Field.Control autoFocus required name=\"label\" defaultValue={draft.node.label} disabled={pending} /></Field.Root>\n                      {draft.node.data && typeof draft.node.data === \"object\" && !Array.isArray(draft.node.data) && <>\n                        <Field.Root><Field.Label>Role / label</Field.Label><Field.Control name=\"role\" defaultValue={String((draft.node.data as Record<string, unknown>).role ?? \"\")} disabled={pending} /></Field.Root>\n                        <Field.Root><Field.Label>Avatar seed</Field.Label><div className=\"ui-graph-avatar-field\"><Avatar name={draft.node.label} kind={(draft.node.data as Record<string, unknown>).agent ? \"agent\" : \"human\"} seed={String((draft.node.data as Record<string, unknown>).avatarSeed ?? draft.node.id)} aria-hidden=\"true\" /><Field.Control name=\"avatarSeed\" defaultValue={String((draft.node.data as Record<string, unknown>).avatarSeed ?? draft.node.id)} disabled={pending} /></div></Field.Root>\n                      </>}\n                      <Field.Root><Field.Label>Current parent</Field.Label><div className=\"ui-graph-readonly-value\">{incoming(draft.node.id).length ? incoming(draft.node.id).map((edge) => <span key={edge.id}><Avatar name={nodeById.get(edge.source)?.label ?? \"Unavailable parent\"} seed={edge.source} size=\"sm\" aria-hidden=\"true\" />{nodeById.get(edge.source)?.label ?? \"Unavailable parent\"}</span>) : <span>No parent</span>}</div></Field.Root>\n                      {incoming(draft.node.id).length > 1 && <GraphFormSelect name=\"parentEdgeId\" label=\"Relationship to change\" options={incoming(draft.node.id).map((edge) => ({value:edge.id,label:nodeById.get(edge.source)?.label ?? \"Unavailable parent\",leading:<Avatar name={nodeById.get(edge.source)?.label ?? \"Unavailable parent\"} seed={edge.source} size=\"sm\" aria-hidden=\"true\" />}))} defaultValue={incoming(draft.node.id)[0].id} disabled={pending} />}\n                      <GraphFormSelect name=\"newParent\" label=\"New parent\" options={value.nodes.filter((candidate) => candidate.id !== draft.node!.id && !getGraphDescendants(value, draft.node!.id, hierarchyRole).has(candidate.id) && !incoming(draft.node!.id).some((edge) => edge.source === candidate.id)).map((candidate) => ({value:candidate.id,label:candidate.label,leading:<Avatar name={candidate.label} seed={candidate.id} size=\"sm\" aria-hidden=\"true\" />}))} disabled={pending} />\n                    </>\n                  )}\n                  {(draft.mode === \"move\" || draft.mode === \"reorder\") &&\n                    draft.node &&\n                    incoming(draft.node.id).length > 0 && (\n                      draft.mode === \"move\" ? <>\n                        <Field.Root><Field.Label>Current parent</Field.Label><div className=\"ui-graph-readonly-value\">{incoming(draft.node.id).map((edge) => <span key={edge.id}><Avatar name={nodeById.get(edge.source)?.label ?? \"Unavailable parent\"} seed={edge.source} size=\"sm\" aria-hidden=\"true\" />{nodeById.get(edge.source)?.label ?? \"Unavailable parent\"}</span>)}</div></Field.Root>\n                        {incoming(draft.node.id).length > 1 ? <GraphFormSelect name=\"edgeId\" label=\"Relationship to change\" options={incoming(draft.node.id).map((edge) => ({ value: edge.id, label: nodeById.get(edge.source)?.label ?? \"Unavailable parent\", leading: <Avatar name={nodeById.get(edge.source)?.label ?? \"Unavailable parent\"} seed={edge.source} size=\"sm\" aria-hidden=\"true\" /> }))} defaultValue={incoming(draft.node.id)[0].id} disabled={pending} /> : <input type=\"hidden\" name=\"edgeId\" value={incoming(draft.node.id)[0].id} />}\n                      </> : incoming(draft.node.id).length > 1 ? <GraphFormSelect name=\"edgeId\" autoFocus label=\"Order under which parent?\" options={incoming(draft.node.id).map((edge) => ({ value: edge.id, label: nodeById.get(edge.source)?.label ?? \"Unavailable parent\", leading: <Avatar name={nodeById.get(edge.source)?.label ?? \"Unavailable parent\"} seed={edge.source} size=\"sm\" aria-hidden=\"true\" /> }))} defaultValue={incoming(draft.node.id)[0].id} disabled={pending} /> : <input type=\"hidden\" name=\"edgeId\" value={incoming(draft.node.id)[0].id} />\n                    )}\n                  {draft.mode === \"move\" && (\n                    <GraphFormSelect\n                      name=\"parent\"\n                      label=\"New parent\"\n                      options={value.nodes\n                        .filter((node) => node.id !== draft.node?.id && !getGraphDescendants(value, draft.node!.id, hierarchyRole).has(node.id) && !incoming(draft.node!.id).some((edge) => edge.source === node.id))\n                        .map((node) => ({ value: node.id, label: node.label, leading: <Avatar name={node.label} seed={node.id} size=\"sm\" aria-hidden=\"true\" /> }))}\n                      defaultValue={draft.parentId}\n                      disabled={pending}\n                    />\n                  )}\n                  {draft.mode === \"position\" && draft.node && (\n                    <>\n                      <Field.Root>\n                        <Field.Label htmlFor={`${positionFieldId}-x`}>Horizontal position</Field.Label>\n                        <NumberField.Root\n                          name=\"x\"\n                          required\n                          step=\"any\"\n                          format={{ useGrouping: false, maximumSignificantDigits: 21 }}\n                          defaultValue={geometry.positions[draft.node.id]?.x ?? 0}\n                          disabled={pending}\n                        >\n                          <NumberField.Group>\n                            <NumberField.Input id={`${positionFieldId}-x`} />\n                          </NumberField.Group>\n                        </NumberField.Root>\n                      </Field.Root>\n                      <Field.Root>\n                        <Field.Label htmlFor={`${positionFieldId}-y`}>Vertical position</Field.Label>\n                        <NumberField.Root\n                          name=\"y\"\n                          required\n                          step=\"any\"\n                          format={{ useGrouping: false, maximumSignificantDigits: 21 }}\n                          defaultValue={geometry.positions[draft.node.id]?.y ?? 0}\n                          disabled={pending}\n                        >\n                          <NumberField.Group>\n                            <NumberField.Input id={`${positionFieldId}-y`} />\n                          </NumberField.Group>\n                        </NumberField.Root>\n                      </Field.Root>\n                    </>\n                  )}\n                  <div className={`ui-graph-form-actions${draft.mode === \"move\" ? \" ui-graph-form-actions--equal\" : \"\"}`}>\n                    <Button\n                      type=\"button\"\n                      size=\"sm\"\n                      variant=\"ghost\"\n                      disabled={pending}\n                      onClick={closeDraft}\n                    >\n                      Cancel\n                    </Button>\n                    <Button type=\"submit\" disabled={pending}>\n                      {draft.mode === \"rename\"\n                        ? \"Save\"\n                        : draft.mode === \"position\"\n                          ? \"Set position\"\n                          : \"Move\"}\n                    </Button>\n                  </div>\n                </form>\n              )}\n    </GraphEditor>\n  );\n  const remove = draft?.mode === \"remove\" && draft.node && (\n    <AlertDialog.Root\n      open\n      onOpenChange={(open) => {\n        if (!open && !pending) closeDraft();\n      }}\n    >\n      <AlertDialog.Portal>\n        <AlertDialog.Backdrop />\n        <AlertDialog.Popup>\n          <AlertDialog.Header>\n            <AlertDialog.Title>Remove {draft.node.label}?</AlertDialog.Title>\n            <AlertDialog.Description>\n              Remove this node and its incident relationships. Its descendants\n              will remain.\n            </AlertDialog.Description>\n          </AlertDialog.Header>\n          {error && (\n            <p className=\"ui-graph-error\" role=\"alert\">\n              {error}\n            </p>\n          )}\n          <AlertDialog.Footer>\n            <AlertDialog.Close\n              disabled={pending}\n              render={<Button variant=\"ghost\" />}\n            >\n              Cancel\n            </AlertDialog.Close>\n            <Button\n              disabled={pending}\n              onClick={() =>\n                void submit({ type: \"remove\", nodeId: draft.node!.id })\n              }\n            >\n              Remove node\n            </Button>\n          </AlertDialog.Footer>\n        </AlertDialog.Popup>\n      </AlertDialog.Portal>\n    </AlertDialog.Root>\n  );\n  return (\n    <div\n      {...nativeProps}\n      ref={(node) => {\n        element.current = node;\n        if (typeof rootRef === \"function\") rootRef(node);\n        else if (rootRef) rootRef.current = node;\n      }}\n      className={[\n        \"ui-graph-surface\",\n        `ui-graph-surface--${mode}`,\n        canvas ? \"ui-graph-surface--viewport\" : \"ui-graph-surface--document\",\n        nativeProps?.className,\n      ]\n        .filter(Boolean)\n        .join(\" \")}\n      data-mode={mode}\n      aria-busy={pending || undefined}\n      onKeyDownCapture={(event) => {\n        nativeProps?.onKeyDownCapture?.(event);\n        if (\n          event.defaultPrevented ||\n          mode !== \"diagram\" ||\n          !(event.target as HTMLElement).matches(\".ui-graph-focus-node\") ||\n          ![\"ArrowUp\", \"ArrowDown\", \"ArrowLeft\", \"ArrowRight\"].includes(\n            event.key,\n          )\n        )\n          return;\n        event.preventDefault();\n        event.stopPropagation();\n        const current = nodes.find(\n          (node) => node.id === (event.target as HTMLElement).dataset.id,\n        );\n        if (!current) return;\n        const horizontal =\n            event.key === \"ArrowLeft\" || event.key === \"ArrowRight\",\n          sign = event.key === \"ArrowLeft\" || event.key === \"ArrowUp\" ? -1 : 1;\n        const center = (node: FlowNode) => ({\n            x:\n              node.position.x + (node.measured?.width ?? node.width ?? 224) / 2,\n            y: node.position.y + (node.measured?.height ?? 104) / 2,\n          }),\n          origin = center(current);\n        const next = nodes\n          .filter((node) => node.id !== current.id)\n          .map((node) => {\n            const point = center(node),\n              along =\n                sign * (horizontal ? point.x - origin.x : point.y - origin.y),\n              across = Math.abs(\n                horizontal ? point.y - origin.y : point.x - origin.x,\n              );\n            return { node, along, distance: along + across * 2 };\n          })\n          .filter((item) => item.along > 1)\n          .sort((a, b) => a.distance - b.distance)[0]?.node;\n        if (next) {\n          select(graphPublicId(next.id));\n          element.current\n            ?.querySelector<HTMLElement>(`[data-id=\"${next.id}\"]`)\n            ?.focus();\n        }\n      }}\n      onKeyDown={(event) => {\n        nativeProps?.onKeyDown?.(event);\n        if (event.defaultPrevented) return;\n        if (event.key === \"Escape\" && !pending) {\n          closeDraft();\n          setError(\"\");\n          setActionsOpen(undefined);\n          setSelectedEdge(undefined);\n        }\n        if (\n          (event.target as HTMLElement).closest(\n            'input,textarea,select,[contenteditable=\"true\"],[role=\"menu\"]',\n          )\n        )\n          return;\n        const focused = (event.target as HTMLElement).closest<HTMLElement>(\n            \".ui-graph-focus-node[data-id]\",\n          ),\n          nodeId = focused\n            ? graphPublicId(focused.dataset.id!)\n            : (selected ?? undefined);\n        if (event.key === \"F2\" && nodeId && canMutate && !pending) {\n          event.preventDefault();\n          const node = nodeById.get(nodeId);\n          if (node)\n            action(\n              node,\n              \"rename\",\n              undefined,\n              focused?.querySelector(\".ui-graph-node\"),\n            );\n        }\n        if (\n          event.shiftKey &&\n          event.key === \"F10\" &&\n          nodeId &&\n          canMutate &&\n          !pending\n        ) {\n          event.preventDefault();\n          setActionsOpen(nodeId);\n        }\n      }}\n    >\n      {canvas && (\n        <div className=\"ui-graph-toolbar nodrag nopan\">\n          <label>\n            <Search size={14} aria-hidden=\"true\" />\n            <Input\n              type=\"search\"\n              variant=\"ghost\"\n              controlSize=\"sm\"\n              aria-label=\"Search nodes\"\n              placeholder=\"Search nodes\"\n              validationTooltip={false}\n              value={query}\n              readOnly={search !== undefined && !onSearchChange}\n              onChange={(event) => {\n                setLocalSearch(event.currentTarget.value);\n                onSearchChange?.(event.currentTarget.value);\n              }}\n            />\n          </label>\n          {canMutate && (\n            <TooltipHint content={mode === \"diagram\" ? \"Add root\" : \"Add node\"}>\n              <IconButton\n                icon={<Plus />}\n                variant=\"ghost\"\n                size=\"icon-sm\"\n                aria-label={mode === \"diagram\" ? \"Add root\" : \"Add node\"}\n                disabled={pending}\n                onClick={(event) => {\n                  setError(\"\");\n                  setDraft({ mode: \"root\", anchor: event.currentTarget });\n                }}\n              />\n            </TooltipHint>\n          )}\n        </div>\n      )}\n      {visible.nodes.length > 0 &&\n        (Renderer ? (\n          <React.Suspense\n            fallback={<span role=\"status\">Loading viewport…</span>}\n          >\n            <Renderer\n              connector={connector}\n              nodes={nodes}\n              edges={edges}\n              mode={mode}\n              editable={canMutate}\n              pending={pending}\n              label={\n                nativeProps?.[\"aria-label\"] ??\n                (mode === \"diagram\" ? \"Diagram\" : \"Node canvas\")\n              }\n              onReady={setRf}\n              onNodesChange={onNodesChange}\n              onSelectEdge={(id) => {\n                select(undefined);\n                setSelectedEdge(graphPublicId(id));\n              }}\n              onPaneClick={() => {\n                select(undefined);\n                setSelectedEdge(undefined);\n              }}\n              onDrag={drag}\n              onDragStop={dragStop}\n              onConnect={connect}\n              onReconnect={reconnect}\n              anchorId={\n                roots.find((root) =>\n                  visible.nodes.some((node) => node.id === root.id),\n                )?.id\n              }\n              fitKey={\n                mode === \"diagram\"\n                  ? JSON.stringify(geometry.positions)\n                  : \"canvas\"\n              }\n            />\n          </React.Suspense>\n        ) : (\n          <DocumentGraph\n            nodes={computedNodes}\n            edges={edges}\n            onMeasure={setSizes}\n            onSelect={select}\n            hostWidth={hostWidth}\n            fit={fit}\n            align={align}\n            editable={canMutate}\n          />\n        ))}\n      {!visible.nodes.length && (\n        <div className=\"ui-graph-empty\">\n          {value.nodes.length ? (\n            <EmptyState\n              title=\"No matching nodes\"\n              description=\"Try a different search.\"\n              align=\"center\"\n              size=\"sm\"\n            />\n          ) : (\n            <EmptyState\n              title={\n                mode === \"diagram\" ? \"No organization yet\" : \"No nodes yet\"\n              }\n              description={\n                mode === \"diagram\"\n                  ? \"Create a first position to start the reporting structure.\"\n                  : \"Add a node to start connecting ideas.\"\n              }\n              align=\"center\"\n              size=\"base\"\n              action={\n                canMutate ? (\n                  <Button\n                    size=\"sm\"\n                    variant=\"outline\"\n                    onClick={(event) =>\n                      setDraft({ mode: \"root\", anchor: event.currentTarget })\n                    }\n                  >\n                    {mode === \"diagram\"\n                      ? \"Create first position\"\n                      : \"Create first node\"}\n                  </Button>\n                ) : undefined\n              }\n            />\n          )}\n        </div>\n      )}\n      {(pending || (error && !draft)) && (\n        <div className=\"ui-graph-feedback\">\n          {error && !draft && (\n            <span className=\"ui-graph-error\" role=\"alert\">\n              {error}\n            </span>\n          )}\n          {pending && <span role=\"status\">Saving change…</span>}\n        </div>\n      )}\n      {editor}\n      {remove}\n    </div>\n  );\n}\nfunction CreationForm<N, E>({\n  draft,\n  value,\n  mode,\n  hierarchyRole,\n  templates,\n  pending,\n  onCreate,\n  onCancel,\n}: {\n  draft: Draft<N, E>;\n  value: GraphValue<N, E>;\n  mode: \"diagram\" | \"canvas\";\n  hierarchyRole: string;\n  templates?: readonly GraphNodeTemplate<N>[];\n  pending: boolean;\n  onCancel?: () => void;\n  onCreate: (\n    label: string,\n    parentId?: string,\n    sourcePortId?: string,\n    templateId?: string,\n    siblingId?: string,\n    formData?: FormData,\n    relation?: \"child\" | \"parent\" | \"sibling\",\n  ) => void;\n}) {\n  const [relation, setRelation] = React.useState<\"child\" | \"parent\" | \"sibling\">(\n    draft.mode === \"parent\" || draft.mode === \"sibling\" ? draft.mode : \"child\",\n  );\n  const [label, setLabel] = React.useState(\"\");\n  const [avatarSeed, setAvatarSeed] = React.useState<string>(() => crypto.randomUUID());\n  const parents =\n    relation === \"sibling\" && draft.node\n      ? value.edges\n          .filter(\n            (edge) =>\n              edge.role === hierarchyRole && edge.target === draft.node!.id,\n          )\n          .map((edge) => edge.source)\n      : [];\n  const parentId =\n    draft.mode === \"canvas\" || draft.mode === \"child\" || draft.mode === \"parent\"\n      ? draft.node?.id\n      : undefined;\n  const parent = value.nodes.find((node) => node.id === parentId),\n    outputs =\n      mode === \"canvas\"\n        ? (parent?.ports?.filter((port) => port.direction === (relation === \"parent\" ? \"input\" : \"output\")) ?? [])\n        : [];\n  const [sourcePort, setSourcePort] = React.useState(\n    draft.sourcePortId ?? outputs[0]?.id ?? \"\",\n  );\n  const type = outputs.find((port) => port.id === sourcePort)?.type;\n  const compatible =\n      templates?.filter(\n      (template) =>\n          relation === \"parent\" ||\n        !parent ||\n        !template.accepts ||\n        Boolean(type && template.accepts.includes(type)),\n    ) ?? [];\n  return (\n    <form\n      className=\"ui-graph-form\"\n      onSubmit={(event) => {\n        event.preventDefault();\n        const form = new FormData(event.currentTarget);\n        onCreate(\n          String(form.get(\"label\") ?? \"\"),\n          relation === \"sibling\"\n            ? String(form.get(\"parent\") ?? \"\") || undefined\n            : parentId,\n          sourcePort || undefined,\n          String(form.get(\"template\") ?? \"\") || undefined,\n          relation === \"sibling\" ? draft.node?.id : undefined,\n          form,\n          relation,\n        );\n      }}\n    >\n      {mode === \"diagram\" && draft.node && (\n        <GraphFormSelect label=\"Relationship\" value={relation} onValueChange={(next) => { if (next === \"child\" || next === \"parent\" || next === \"sibling\") setRelation(next); }} options={[{value:\"child\",label:\"Child\"},{value:\"parent\",label:\"Parent\"},{value:\"sibling\",label:\"Sibling\"}]} disabled={pending} />\n      )}\n      <Field.Root>\n        <Field.Label>Node name</Field.Label>\n        <Field.Control\n          autoFocus\n          required\n          name=\"label\"\n          placeholder={mode === \"diagram\" ? \"Name this role\" : \"Name this node\"}\n          value={label}\n          onChange={(event) => setLabel(event.currentTarget.value)}\n          disabled={pending}\n        />\n      </Field.Root>\n      {mode === \"diagram\" && <>\n        <Field.Root><Field.Label>Role / label</Field.Label><Field.Control name=\"role\" placeholder=\"Role or label\" disabled={pending} /></Field.Root>\n        <Field.Root><Field.Label>Avatar seed</Field.Label><div className=\"ui-graph-avatar-field\"><Avatar name={label || \"New position\"} kind=\"human\" seed={avatarSeed} aria-hidden=\"true\" /><Field.Control name=\"avatarSeed\" value={avatarSeed} onChange={(event) => setAvatarSeed(event.currentTarget.value)} disabled={pending} /></div></Field.Root>\n      </>}\n      {relation === \"sibling\" && parents.length > 0 && (\n        <GraphFormSelect\n          name=\"parent\"\n          label=\"Place under\"\n          options={parents.map((id) => ({\n            value: id,\n            label:\n              value.nodes.find((node) => node.id === id)?.label ??\n              \"Unavailable parent\",\n            leading: <Avatar name={value.nodes.find((node) => node.id === id)?.label ?? \"Unavailable parent\"} seed={id} size=\"sm\" aria-hidden=\"true\" />,\n          }))}\n          defaultValue={parents[0]}\n          disabled={pending}\n        />\n      )}\n      {outputs.length > 0 && (\n        <GraphFormSelect\n          label={relation === \"parent\" ? \"Input port\" : \"Output port\"}\n          value={sourcePort}\n          onValueChange={setSourcePort}\n          options={outputs.map((port) => ({\n            value: port.id,\n            label: port.label,\n          }))}\n          disabled={pending}\n        />\n      )}\n      {templates?.length ? (\n        compatible.length > 0 ? (\n          <GraphFormSelect\n            key={sourcePort}\n            name=\"template\"\n            label=\"Node type\"\n            options={compatible.map((template) => ({\n              value: template.id,\n              label: template.label,\n            }))}\n            defaultValue={compatible[0].id}\n            disabled={pending}\n          />\n        ) : (\n          <p className=\"ui-graph-error\">No node type accepts this output.</p>\n        )\n      ) : null}\n      <div className=\"ui-graph-form-actions ui-graph-form-actions--equal\">\n        <Button\n          type=\"button\"\n          size=\"sm\"\n          variant=\"ghost\"\n          disabled={pending}\n          onClick={onCancel}\n        >\n          Cancel\n        </Button>\n        <Button\n          type=\"submit\"\n          disabled={pending || Boolean(templates?.length && !compatible.length)}\n        >\n          Create\n        </Button>\n      </div>\n    </form>\n  );\n}\nexport const GraphSurface = React.forwardRef(SurfaceInner) as <\n  N = unknown,\n  E = unknown,\n>(\n  props: GraphSurfaceProps<N, E> & {\n    ref?: React.Ref<GraphViewportHandle | null>;\n  },\n) => React.ReactElement;\n\nfunction DocumentGraph({\n  nodes,\n  edges,\n  onMeasure,\n  onSelect,\n  hostWidth,\n  fit,\n  align,\n  editable,\n}: {\n  nodes: FlowNode[];\n  edges: FlowEdge[];\n  onMeasure: React.Dispatch<React.SetStateAction<Record<string, GraphSize>>>;\n  onSelect: (id: string | undefined) => void;\n  hostWidth: number;\n  fit: \"width\" | \"none\";\n  align: \"center\" | \"start\";\n  editable: boolean;\n}) {\n  const root = React.useRef<HTMLDivElement>(null),\n    [hoveredEdgeId, setHoveredEdgeId] = React.useState<string>();\n  React.useLayoutEffect(() => {\n    const measure = (elements: Element[]) => {\n      const updates = elements\n        .map((element) => {\n          const box = element as HTMLElement,\n            id = graphPublicId((element as HTMLElement).dataset.id ?? \"\");\n          return { id, width: box.offsetWidth, height: box.offsetHeight };\n        })\n        .filter((item) => item.id && item.width > 0 && item.height > 0);\n      onMeasure((current) => {\n        let next = current;\n        for (const item of updates)\n          if (\n            item.id &&\n            (ownValue(current, item.id)?.width !== item.width ||\n              ownValue(current, item.id)?.height !== item.height)\n          ) {\n            if (next === current) next = { ...current };\n            Object.defineProperty(next, item.id, {\n              value: { width: item.width, height: item.height },\n              enumerable: true,\n              configurable: true,\n              writable: true,\n            });\n          }\n        return next;\n      });\n    };\n    const elements = [\n      ...(root.current?.querySelectorAll(\".ui-graph-document-node\") ?? []),\n    ];\n    measure(elements);\n    if (typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver((entries) =>\n      measure(entries.map((entry) => entry.target)),\n    );\n    elements.forEach((element) => observer.observe(element));\n    return () => observer.disconnect();\n  }, [nodes.map((node) => node.id).join(\"|\"), onMeasure]);\n  // Leave room for the port actions, their gap from the node, and their touch targets.\n  const gutter = editable ? 44 : 24;\n  const minX = Math.min(0, ...nodes.map((node) => node.position.x - gutter)),\n    minY = Math.min(0, ...nodes.map((node) => node.position.y - gutter));\n  const width =\n      Math.max(0, ...nodes.map((node) => node.position.x + node.width + gutter)) -\n      minX,\n    height =\n      Math.max(\n        0,\n        ...nodes.map(\n          (node) => node.position.y + (node.measured?.height ?? 104) + gutter,\n        ),\n      ) - minY;\n  const byId = new Map(nodes.map((node) => [node.id, node]));\n  const paths = [...edges].sort((a, b) => (a.id === hoveredEdgeId ? 2 : Number(a.selected)) - (b.id === hoveredEdgeId ? 2 : Number(b.selected))).flatMap((edge) => {\n    const source = byId.get(edge.source),\n      target = byId.get(edge.target);\n    if (!source || !target) return [];\n    const sourceAnchors = source.data.anchors,\n      targetAnchors = target.data.anchors;\n    const start = resolveGraphAnchor(source.position, {\n        width: source.width,\n        height: source.measured?.height ?? 104,\n      }, sourceAnchors.output),\n      end = resolveGraphAnchor(target.position, {\n        width: target.width,\n        height: target.measured?.height ?? 104,\n      }, targetAnchors.input);\n    return [\n      {\n        edge,\n        geometry: getGraphConnectorPath({\n          source: start,\n          target: end,\n          direction: edge.data.direction,\n          connector: edge.data.connector,\n          points: edge.data.layoutPath,\n        }),\n      },\n    ];\n  });\n  const scale = fit === \"width\" && hostWidth > 0 ? Math.max(0.65, Math.min(1, hostWidth / Math.max(width, 1))) : 1;\n  const scaledWidth = width * scale, scaledHeight = height * scale;\n  return (\n    <div className=\"ui-graph-document-frame\" style={{ width: scaledWidth, height: scaledHeight, marginInline: align === \"center\" && scaledWidth <= hostWidth ? \"auto\" : 0 }}>\n    <div ref={root} className=\"ui-graph-document\" style={{ width, height, transform: `scale(${scale})`, transformOrigin: \"top left\" }}>\n      <svg\n        width={width}\n        height={height}\n        viewBox={`${minX} ${minY} ${width} ${height}`}\n        className=\"ui-graph-document-edges\"\n      >\n        {paths.map(({ edge, geometry }) => (\n          <g\n            key={edge.id}\n            className=\"ui-graph-document-edge\"\n            data-selected={edge.selected || undefined}\n            data-hovered={hoveredEdgeId === edge.id || undefined}\n            onMouseEnter={() => setHoveredEdgeId(edge.id)}\n            onMouseLeave={() => setHoveredEdgeId(undefined)}\n          >\n            <EdgePath\n              d={geometry.path}\n              line={edge.data.graphEdge.line}\n              status={edge.data.graphEdge.status}\n              selected={edge.selected}\n              style={edge.style}\n              aria-hidden=\"true\"\n            />\n            {edge.data.canMutate && (\n              <path\n                className=\"ui-graph-edge-hit\"\n                d={geometry.path}\n                fill=\"none\"\n                stroke=\"transparent\"\n                strokeWidth={24}\n                pointerEvents=\"stroke\"\n                role=\"button\"\n                tabIndex={0}\n                aria-label={edge.ariaLabel}\n                onClick={edge.data.onSelect}\n                onFocus={() => {\n                  setHoveredEdgeId(edge.id);\n                }}\n                onBlur={() => setHoveredEdgeId(undefined)}\n                onKeyDown={(event) => {\n                  if (event.key === \"Enter\" || event.key === \" \") {\n                    event.preventDefault();\n                    edge.data.onSelect();\n                  }\n                }}\n              />\n            )}\n          </g>\n        ))}\n      </svg>\n      <div\n        className=\"ui-graph-document-labels\"\n        style={{ left: -minX, top: -minY }}\n      >\n        {paths.map(({ edge, geometry }) => (\n          <GraphEdgeLabel\n            key={edge.id}\n            data={{ ...edge.data, hovered: hoveredEdgeId === edge.id }}\n            selected={edge.selected}\n            label={geometry.label}\n          />\n        ))}\n      </div>\n      {nodes.map((node) => (\n        <div\n          key={node.id}\n          className=\"ui-graph-document-node ui-graph-focus-node\"\n          data-id={node.id}\n          tabIndex={0}\n          role=\"group\"\n          aria-label={node.ariaLabel}\n          onKeyDown={(event) => {\n            if (\n              event.target === event.currentTarget &&\n              (event.key === \"Enter\" || event.key === \" \")\n            ) {\n              event.preventDefault();\n              onSelect(graphPublicId(node.id));\n            }\n          }}\n          style={{\n            position: \"absolute\",\n            left: node.position.x - minX,\n            top: node.position.y - minY,\n            width: node.width,\n          }}\n          onClick={(event) => {\n            if (\n              !(event.target as HTMLElement).closest(\n                'button,input,select,a,[role=\"button\"]',\n              )\n            )\n              onSelect(graphPublicId(node.id));\n          }}\n        >\n          <NodeView data={node.data} selected={node.selected} />\n        </div>\n      ))}\n    </div>\n    </div>\n  );\n}\n"
    },
    {
      "path": "src/components/ui/graph.css",
      "type": "registry:file",
      "target": "@ui/graph.css",
      "content": "@import \"./node-card.css\";\n@import \"./node-port.css\";\n@import \"./edge-path.css\";\n.ui-graph-surface{position:relative;isolation:isolate;box-sizing:border-box;max-inline-size:100%;min-inline-size:0;color:var(--foreground);font-family:var(--font-sans);font-size:14px;font-weight:var(--font-weight-regular,400);--graph-edge-surface:var(--background)}\n.ui-graph-surface--document{overflow:auto;overscroll-behavior:contain}\n.ui-graph-document-frame{position:relative;flex:none}\n.ui-graph-document{position:relative;min-height:160px}\n.ui-graph-document-edges{position:absolute;inset:0;overflow:visible}\n.ui-graph-document-labels{position:absolute;inset:0;pointer-events:none}\n.ui-graph-document-node{outline:none}\n.ui-graph-document-node:focus-visible>.ui-graph-node{border-color:var(--muted-foreground)}\n.ui-graph-surface--document .ui-graph-empty{position:relative;inset:auto;min-height:180px}\n.ui-graph-surface--document .ui-graph-feedback{position:sticky;bottom:8px;margin:8px;width:fit-content}\n\n.ui-graph-toolbar{position:absolute;z-index:5;top:12px;right:12px;display:flex;max-width:calc(100% - 24px);align-items:center;gap:4px;padding:4px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius-md)}\n.ui-graph-toolbar label{display:flex;min-width:0;align-items:center;gap:8px;padding-inline:8px;color:var(--muted-foreground)}\n.ui-graph-toolbar svg.lucide{width:var(--icon-size);height:var(--icon-size);stroke-width:var(--icon-stroke)}\n.ui-graph-toolbar .ui-input{width:160px;min-width:0}\n.ui-graph-node__menu{position:absolute;right:6px;top:6px;opacity:0}\n.ui-graph-node:focus-within .ui-graph-node__menu,.ui-graph-node[data-selected] .ui-graph-node__menu{opacity:1}\n@media(hover:hover) and (pointer:fine){.ui-graph-node:hover .ui-graph-node__menu{opacity:1}}\n.ui-graph-node__ports{position:absolute;inset:0;overflow:visible;pointer-events:none;display:flex;flex-direction:column;gap:8px;margin-block:4px}\n.ui-graph-node__port-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:12px;min-height:24px}\n.ui-graph-node__port-actions{position:absolute;z-index:4;top:50%;transform:translateY(-50%);opacity:0;pointer-events:none;gap:2px;background:var(--background);border:1px solid var(--border);border-radius:var(--radius-md);padding:3px;box-shadow:var(--shadow-sm, none)}\n.ui-graph-node__port--input .ui-graph-node__port-actions{right:calc(100% + 8px)}\n.ui-graph-node__port--output .ui-graph-node__port-actions{left:calc(100% + 8px)}\n.ui-graph-node__port:focus-within .ui-graph-node__port-actions{opacity:1;pointer-events:auto}\n@media(hover:hover) and (pointer:fine){.ui-graph-node__port:hover .ui-graph-node__port-actions{opacity:1;pointer-events:auto}}\n.ui-graph-node__action-zone{position:absolute;z-index:3;display:flex;flex:0 0 auto;align-items:center;justify-content:center;width:44px;height:44px;opacity:0}\n.ui-graph-node:focus-within .ui-graph-node__action-zone,.ui-graph-node__action-zone:focus-within{opacity:1}\n@media(hover:hover) and (pointer:fine){.ui-graph-node:hover .ui-graph-node__action-zone{opacity:1}}\n.ui-graph-node__action-zone--top{left:50%;top:-22px;transform:translateX(-50%)}\n.ui-graph-node__action-zone--bottom{left:50%;bottom:-22px;transform:translateX(-50%)}\n.ui-graph-node__action-zone--right{top:50%;right:-22px;transform:translateY(-50%)}\n.ui-graph-node__action-zone--left{top:50%;left:-22px;transform:translateY(-50%)}\n.ui-graph-node__action-dot{display:block;flex:none;box-sizing:border-box;width:8px;height:8px;aspect-ratio:1;border:1px solid var(--muted-foreground);border-radius:50%;background:var(--background)}\n.ui-graph-node__action-zone>.ui-button-group.ui-graph-node__action-group{position:absolute;max-width:none}\n/* Reveal the surface at full opacity so connectors never show through it. */\n.ui-graph-node__action-group{--ui-button-icon-size:var(--icon-size-sm);z-index:1;left:50%;background:var(--background);opacity:0;pointer-events:none;transform:translateX(-50%)}\n.ui-graph-node__action-zone--top>.ui-graph-node__action-group{bottom:calc(50% + 4px)}\n.ui-graph-node__action-zone--bottom>.ui-graph-node__action-group{top:calc(50% + 4px)}\n.ui-graph-node__action-zone--right>.ui-graph-node__action-group{top:50%;left:calc(50% + 4px);transform:translateY(-50%)}\n.ui-graph-node__action-zone--left>.ui-graph-node__action-group{top:50%;left:auto;right:calc(50% + 4px);transform:translateY(-50%)}\n.ui-graph-node__action-group>.ui-graph-node__action-button{touch-action:manipulation}\n@media(pointer:coarse){\n  /* Extend each 32px button outward to a 44px hit area. */\n  .ui-graph-node__action-group>.ui-graph-node__action-button{overflow:visible}\n  .ui-graph-node__action-group>.ui-graph-node__action-button::after{content:\"\";position:absolute;inset:-6px 0}\n  .ui-graph-node__action-group[data-orientation=\"horizontal\"]>.ui-graph-node__action-button:first-of-type::after{inset-inline-start:-12px}\n  .ui-graph-node__action-group[data-orientation=\"horizontal\"]>.ui-graph-node__action-button:last-of-type::after{inset-inline-end:-12px}\n  .ui-graph-node__action-group[data-orientation=\"vertical\"]>.ui-graph-node__action-button::after{inset:0 -6px}\n  .ui-graph-node__action-group[data-orientation=\"vertical\"]>.ui-graph-node__action-button:first-of-type::after{inset-block-start:-12px}\n  .ui-graph-node__action-group[data-orientation=\"vertical\"]>.ui-graph-node__action-button:last-of-type::after{inset-block-end:-12px}\n}\n.ui-graph-node__action-zone:focus-within .ui-graph-node__action-group{opacity:1;pointer-events:auto}\n@media(hover:hover) and (pointer:fine){.ui-graph-node__action-zone:hover .ui-graph-node__action-group{opacity:1;pointer-events:auto}}\n.ui-graph-node__action-zone:focus-within .ui-graph-node__action-dot{opacity:0}\n@media(hover:hover) and (pointer:fine){.ui-graph-node__action-zone:hover .ui-graph-node__action-dot{opacity:0}}\n.ui-graph-edge-label{position:absolute;display:flex;align-items:center;gap:4px;pointer-events:all;font-size:12px;background:var(--background);color:var(--muted-foreground);border-radius:var(--radius-sm)}\n.ui-graph-edge-label>span{display:block;padding:2px 6px}\n.ui-graph-document-edge:is(:focus-within,[data-selected=\"true\"])>.ui-graph-edge-path{stroke:color-mix(in srgb,var(--graph-edge-color),var(--foreground) 40%)}\n@media(hover:hover) and (pointer:fine){.ui-graph-document-edge:hover>.ui-graph-edge-path{stroke:color-mix(in srgb,var(--graph-edge-color),var(--foreground) 40%)}}\n.ui-graph-document-edge:has(.ui-graph-edge-hit:focus-visible)>.ui-graph-edge-path{stroke:color-mix(in srgb,var(--graph-edge-color),var(--foreground) 40%)}\n.ui-graph-edge-hit{fill:none;stroke:transparent;stroke-width:24;vector-effect:non-scaling-stroke;pointer-events:stroke;touch-action:manipulation;outline:none}\n.ui-graph-surface .ui-graph-edge-path--port-active{stroke:var(--muted-foreground)}\n.ui-graph-node[data-port-highlighted=true] .ui-layer-card--compact{border-color:var(--muted-foreground)}\n.ui-graph-edge-popup{width:260px;max-height:70dvh}\n.ui-graph-edge-context{display:grid;grid-template-columns:minmax(0,1fr) auto minmax(0,1fr);align-items:center;gap:8px;min-width:0;margin-block-end:12px;color:var(--muted-foreground);font-size:12px}\n.ui-graph-edge-context__node{display:flex;min-width:0;align-items:center;gap:6px;overflow-wrap:anywhere}\n.ui-graph-edge-context__identity{display:grid;min-width:0;gap:2px;line-height:16px}\n.ui-graph-edge-context__identity small{color:var(--muted-foreground);font-size:11px}\n.ui-graph-edge-context__arrow{justify-self:center}\n.ui-graph-node__canvas-card{width:100%;min-width:0;overflow:visible}\n.ui-graph-node__canvas-card.ui-layer-card--compact.ui-radius-container>.ui-graph-node__canvas-heading{min-height:48px;padding:6px var(--space-4);border-start-start-radius:var(--ui-radius-outer);border-start-end-radius:var(--ui-radius-outer)}\n.ui-graph-node__canvas-heading>span{display:flex;flex:1;min-width:0;align-items:center;gap:8px;color:var(--foreground);overflow-wrap:anywhere}\n.ui-graph-node__canvas-heading svg{width:var(--icon-size-sm);height:var(--icon-size-sm);flex:none;stroke-width:var(--icon-stroke)}\n.ui-graph-node__canvas-card .ui-layer-card__primary{display:grid;grid-template-columns:minmax(0,1fr);gap:0;overflow:visible}\n.ui-graph-node__canvas-card .ui-layer-card__primary>*{grid-area:1/1}\n.ui-graph-node__canvas-card .ui-layer-card__secondary{border-radius:0}\n.ui-graph-node__canvas-card .ui-graph-node__port-row{position:relative}\n.ui-graph-node__canvas-card .ui-graph-node__ports,.ui-graph-node__canvas-card .ui-graph-node__port{pointer-events:none}\n.ui-graph-node__canvas-card :is(.ui-graph-node__port-actions,.ui-graph-node__connect){pointer-events:auto}\n.ui-graph-node[data-node-mode=canvas].ui-card{min-height:0;padding:0;border-color:transparent;background:transparent}\n.ui-graph-node[data-node-mode=canvas] .ui-graph-node__menu{position:static;flex:none}\n.ui-graph-node__footer-content{flex:1;min-width:0}\n.ui-graph-node__footer:has(> .ui-graph-node__actions:only-child){justify-content:center}\n.ui-graph-node__disclosure{color:var(--muted-foreground)}\n.ui-graph-node__disclosure svg{width:var(--icon-size-sm);height:var(--icon-size-sm);stroke-width:var(--icon-stroke)}\n.ui-graph-disclosure-tooltip{display:grid;gap:2px;text-align:start;white-space:nowrap}\n.ui-graph-select-value{display:inline-flex;align-items:center;gap:8px}\n.ui-graph-avatar-field{display:flex;align-items:center;gap:8px}\n.ui-graph-avatar-field .ui-avatar{width:32px;height:32px;flex:none}\n.ui-graph-form{display:grid;gap:12px}\n.ui-graph-popup{width:min(360px,calc(100vw - 32px));max-height:min(80dvh,660px);pointer-events:auto}\n.ui-graph-popup .ui-graph-editor-title{margin:0;color:var(--foreground);font-size:14px;font-weight:var(--font-weight-regular,400);line-height:20px}\n.ui-graph-form-actions{display:flex;align-items:center;justify-content:flex-end;gap:8px;margin-block-start:4px}\n.ui-graph-form-actions--equal>*{flex:1}\n.ui-graph-readonly-value{display:flex;align-items:center;gap:8px;min-height:40px;color:var(--muted-foreground)}\n.ui-graph-readonly-value>span{display:inline-flex;align-items:center;gap:6px}\n.ui-graph-node__footer-content .ui-progress-root{display:grid;grid-template-columns:auto auto;align-items:center;gap:4px 8px}\n.ui-graph-node__footer-content .ui-progress-track{grid-column:1/-1}\n.ui-graph-popup .ui-graph-error{margin:0}\n.ui-graph-error{color:var(--destructive);font-size:12px;line-height:18px;overflow-wrap:anywhere}\n.ui-graph-feedback{position:absolute;z-index:6;bottom:12px;right:12px;max-width:calc(100% - 156px);display:grid;gap:4px;border:1px solid var(--border);border-radius:var(--radius-md);background:var(--background);padding:8px 12px;font-size:12px}\n.ui-graph-empty{position:absolute;z-index:2;inset:0;display:grid;place-items:center;min-height:240px;padding:24px;pointer-events:none;color:var(--muted-foreground)}\n.ui-graph-surface--document .ui-graph-empty{position:relative;inset:auto}\n.ui-graph-empty .ui-empty-state{pointer-events:none}\n.ui-graph-empty .ui-empty-state-actions,.ui-graph-empty .ui-button{pointer-events:auto}\n@media(pointer:coarse){.ui-graph-node__menu,.ui-graph-node__action-zone{opacity:1;pointer-events:auto}}\n@media(max-width:520px){.ui-graph-toolbar{top:12px;right:8px}.ui-graph-toolbar .ui-input{width:94px}.ui-graph-toolbar label{gap:4px;padding-inline:4px}.ui-graph-feedback{max-width:calc(100% - 24px);bottom:52px}}\n\n.ui-graph-edge-label--quiet{opacity:0}\n.ui-graph-edge-label--quiet:focus-within{opacity:1}\n@media(hover:hover) and (pointer:fine){.ui-graph-edge-label--quiet:hover{opacity:1}}\n.ui-graph-edge-label--quiet[data-hovered=true]{opacity:1}\n@media(pointer:coarse){.ui-graph-edge-label--quiet{opacity:1}}\n\n.ui-graph-node .ui-graph-node__port-trigger.ui-button{position:absolute;inset:0;width:100%;height:100%;padding:0;touch-action:manipulation;-webkit-user-select:none;user-select:none}\n.ui-graph-node__port-trigger:not(:disabled):active .ui-graph-node__action-dot{border-color:var(--foreground)}\n.ui-graph-node__menu>.ui-button{min-width:44px;min-height:44px}\n.ui-graph-node .ui-graph-node__header{padding-inline-end:44px}\n@media(pointer:coarse){.ui-graph-edge-hit{stroke-width:44}.ui-graph-popup :is(input,textarea,select){font-size:16px}}\n"
    },
    {
      "path": "src/components/ui/diagram.tsx",
      "type": "registry:component",
      "target": "@ui/diagram.tsx",
      "content": "\"use client\";\n\nimport * as React from \"react\";\nimport { GraphSurface } from \"./graph-surface-internal\";\nimport { NodeCard } from \"./node-card\";\nimport { layoutDiagram } from \"./diagram-layout\";\nimport type { GraphLayoutFunction } from \"./graph-types\";\nimport type { GraphSurfaceProps } from \"./graph-surface-internal\";\n\nexport { layoutDiagram, NodeCard };\nexport { getGraphConnectorPath } from \"./graph-connectors\";\nexport type { GraphConnector, GraphConnectorOptions, GraphConnectorPath } from \"./graph-connectors\";\nexport * from \"./graph-types\";\nexport {\n  assertGraphValue,\n  getGraphChangeError,\n  applyGraphChange,\n  getGraphProjection,\n  getGraphDescendants,\n  applyGraphPositions,\n} from \"./graph-model\";\n\nexport type DiagramProps<N = unknown, E = unknown> = Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> &\n  Omit<\n    GraphSurfaceProps<N, E>,\n    \"mode\" | \"nativeProps\" | \"rootRef\" | \"positions\" | \"defaultPositions\" | \"acyclicRoles\"\n  > & {\n    align?: \"center\" | \"start\";\n    fit?: \"width\" | \"none\";\n    collapsible?: boolean;\n    layout?: GraphLayoutFunction<N, E>;\n  };\n\nfunction DiagramInner<N, E>(props: DiagramProps<N, E>, ref: React.ForwardedRef<HTMLDivElement>) {\n  const {\n    value,\n    editable,\n    onChange,\n    getChangePermission,\n    renderNode,\n    nodeWidth,\n    createNode,\n    createEdge,\n    nodeTemplates,\n    relationshipTypes,\n    connectionRole,\n    selectedNodeId,\n    onSelectedNodeIdChange,\n    onEditNode,\n    renderNodeFooter,\n    hierarchyRole,\n    collapsedIds,\n    defaultCollapsedIds,\n    onCollapsedIdsChange,\n    search,\n    onSearchChange,\n    direction,\n    layout,\n    nodeGap,\n    levelGap,\n    viewport,\n    connector,\n    align,\n    fit,\n    collapsible,\n    routes,\n    children: _children,\n    ...nativeProps\n  } = props;\n  return (\n    <GraphSurface\n      value={value}\n      editable={editable}\n      onChange={onChange}\n      getChangePermission={getChangePermission}\n      renderNode={renderNode}\n      nodeWidth={nodeWidth}\n      createNode={createNode}\n      createEdge={createEdge}\n      nodeTemplates={nodeTemplates}\n      relationshipTypes={relationshipTypes}\n      connectionRole={connectionRole}\n      selectedNodeId={selectedNodeId}\n      onSelectedNodeIdChange={onSelectedNodeIdChange}\n      onEditNode={onEditNode}\n      renderNodeFooter={renderNodeFooter}\n      hierarchyRole={hierarchyRole}\n      collapsedIds={collapsedIds}\n      defaultCollapsedIds={defaultCollapsedIds}\n      onCollapsedIdsChange={onCollapsedIdsChange}\n      search={search}\n      onSearchChange={onSearchChange}\n      direction={direction}\n      layout={layout ?? layoutDiagram}\n      nodeGap={nodeGap}\n      levelGap={levelGap}\n      mode=\"diagram\"\n      viewport={viewport}\n      connector={connector}\n      align={align}\n      fit={fit}\n      collapsible={collapsible}\n      routes={routes}\n      nativeProps={nativeProps}\n      rootRef={ref}\n    />\n  );\n}\n\nexport const Diagram = React.forwardRef(DiagramInner) as <N = unknown, E = unknown>(\n  props: DiagramProps<N, E> & React.RefAttributes<HTMLDivElement>,\n) => React.ReactElement;\nexport default Diagram;\n"
    },
    {
      "path": "src/components/ui/diagram-layout.ts",
      "type": "registry:component",
      "target": "@ui/diagram-layout.ts",
      "content": "import { Graph, layout } from \"@dagrejs/dagre\";\nimport { graphEngineId } from \"./graph-id\";\nimport type { GraphLayout, GraphLayoutFunction, GraphPoint, GraphSize } from \"./graph-types\";\n\nfunction isPoint(value: unknown): value is GraphPoint {\n  return !!value && typeof value === \"object\" && \"x\" in value && \"y\" in value\n    && typeof value.x === \"number\" && Number.isFinite(value.x) && typeof value.y === \"number\" && Number.isFinite(value.y);\n}\n\n/** Measured DAG layout. Caller IDs and model order never become engine keys or policy. */\nexport const layoutDiagram: GraphLayoutFunction = (value, sizes, options): GraphLayout => {\n  const role = options.hierarchyRole === undefined ? \"reporting\" : options.hierarchyRole;\n  const nodeGap = options.nodeGap ?? 56, levelGap = options.levelGap ?? 64;\n  if (![nodeGap, levelGap].every(n => Number.isFinite(n) && n >= 0)) throw new Error(\"Diagram layout gaps must be finite, nonnegative numbers.\");\n  const structural = value.edges.filter(edge => edge.role === role);\n  const byId = new Map(value.nodes.map(node => [node.id, node]));\n  if (byId.size !== value.nodes.length) throw new Error(\"Diagram layout needs unique node IDs.\");\n  const children = new Map<string, string[]>(), incoming = new Set<string>();\n  for (const edge of structural) {\n    if (!byId.has(edge.source) || !byId.has(edge.target)) throw new Error(\"Diagram layout received an unknown endpoint.\");\n    const list = children.get(edge.source) ?? [];\n    if (!list.includes(edge.target)) list.push(edge.target);\n    children.set(edge.source, list); incoming.add(edge.target);\n  }\n  const roots = value.nodes.filter(node => !incoming.has(node.id)).map(node => node.id);\n  const ordered: string[] = [], seen = new Set<string>(), depths = new Map<string, number>();\n  for (const start of [...roots, ...byId.keys()]) {\n    const stack = [{ id: start, depth: 0 }];\n    while (stack.length) {\n      const { id, depth } = stack.pop()!;\n      if (seen.has(id)) continue;\n      seen.add(id); ordered.push(id); depths.set(id, depth);\n      const next = children.get(id) ?? [];\n      for (let i = next.length - 1; i >= 0; i--) stack.push({ id: next[i], depth: depth + 1 });\n    }\n  }\n  const dimensions = new Map<string, GraphSize>();\n  for (const id of ordered) {\n    const size = Object.hasOwn(sizes, id) ? sizes[id] : { width: 224, height: 104 };\n    if (!size || ![size.width, size.height].every(n => Number.isFinite(n) && n > 0)) throw new Error(`Diagram node ${id} needs positive, finite dimensions.`);\n    dimensions.set(id, size);\n  }\n  if (options.align === \"start\") {\n    const indent = options.nodeGap ?? 32, rowGap = options.levelGap ?? 24;\n    let y = 24;\n    const positions = Object.fromEntries(ordered.map(id => {\n      const position = { x: 24 + depths.get(id)! * indent, y };\n      y += dimensions.get(id)!.height + rowGap;\n      return [id, position];\n    }));\n    const anchors: NonNullable<GraphLayout[\"anchors\"]> = Object.fromEntries(ordered.map(id => [id, {\n      input: { side: \"left\", offset: 0.5 },\n      output: { side: \"bottom\", offset: Math.min(indent / 2, dimensions.get(id)!.width / 2) / dimensions.get(id)!.width },\n    }]));\n    const paths = Object.fromEntries(structural.map(edge => {\n      const source = positions[edge.source], target = positions[edge.target];\n      const start = { x: source.x + Math.min(indent / 2, dimensions.get(edge.source)!.width / 2), y: source.y + dimensions.get(edge.source)!.height };\n      const end = { x: target.x, y: target.y + dimensions.get(edge.target)!.height / 2 };\n      return [edge.id, [start, { x: start.x, y: end.y }, end]];\n    }));\n    return { positions, anchors, paths };\n  }\n  const graph = new Graph({ directed: true, multigraph: true });\n  graph.setGraph({ rankdir: options.direction === \"right\" ? \"LR\" : \"TB\", nodesep: nodeGap, ranksep: levelGap, marginx: 24, marginy: 24 });\n  graph.setDefaultEdgeLabel(() => ({}));\n  for (const [id, size] of dimensions) graph.setNode(graphEngineId(id), { ...size });\n  // Multiple named edges retain identity; they must never overwrite each other.\n  for (const edge of structural) graph.setEdge(graphEngineId(edge.source), graphEngineId(edge.target), {}, graphEngineId(edge.id));\n  // Crossing optimization can reverse explicit sibling order; retain input traversal order.\n  layout(graph, { disableOptimalOrderHeuristic: true });\n  const positions = Object.fromEntries(ordered.map(id => {\n    const node = graph.node(graphEngineId(id)), size = dimensions.get(id)!;\n    if (!node || !Number.isFinite(node.x) || !Number.isFinite(node.y)) throw new Error(`Diagram layout failed for ${id}.`);\n    return [id, { x: node.x - size.width / 2, y: node.y - size.height / 2 }];\n  }));\n  const paths = Object.fromEntries(structural.map(edge => {\n    const data = graph.edge({ v: graphEngineId(edge.source), w: graphEngineId(edge.target), name: graphEngineId(edge.id) });\n    const points: unknown = data?.points;\n    if (!Array.isArray(points) || !points.every(isPoint)) throw new Error(`Diagram routing failed for ${edge.id}.`);\n    return [edge.id, points.map(point => ({ x: point.x, y: point.y }))];\n  }));\n  return { positions, paths };\n};\n"
    },
    {
      "path": "src/components/ui/node-card.css",
      "type": "registry:file",
      "target": "@ui/node-card.css",
      "content": ".ui-graph-node.ui-card{position:relative;overflow:visible;border-radius:var(--radius-surface);box-shadow:none;transition:border-color 120ms ease}\n.ui-graph-node[data-interactive]{cursor:pointer}\n.ui-graph-node[data-interactive]:active{border-color:var(--muted-foreground)}\n@media(hover:hover) and (pointer:fine){.ui-graph-node:hover{border-color:var(--muted-foreground)}}\n.ui-graph-node[data-selected],.ui-graph-node[data-staged-parent]{border-color:var(--muted-foreground)}\n.ui-graph-node[data-dragging]{border-color:var(--muted-foreground);cursor:grabbing;transition:none}\n.ui-graph-node[data-disabled]{color:var(--muted-foreground)}\n.ui-graph-node[data-status=running]{border-color:var(--muted-foreground);animation:ui-graph-node-running 1800ms ease-in-out infinite}\n@keyframes ui-graph-node-running{0%,100%{border-color:var(--muted-foreground)}50%{border-color:var(--foreground)}}\n.ui-graph-node[data-status=success]{border-color:var(--color-success)}\n.ui-graph-node[data-status=error]{border-color:var(--destructive)}\n.ui-graph-node:focus-within{border-color:var(--muted-foreground)}\n.ui-graph-node:focus-visible{border-color:var(--muted-foreground);outline:none;box-shadow:none}\n.ui-graph-node__header{display:flex;align-items:flex-start;min-width:0;padding-inline-end:24px}\n.ui-graph-node__title{margin:0;font-size:14px;font-weight:var(--font-weight-regular,400);line-height:20px;overflow-wrap:anywhere}\n.ui-graph-node__content{min-width:0}\n.ui-graph-node__footer{display:flex;min-height:24px;align-items:center;justify-content:space-between;gap:8px;color:var(--muted-foreground);font-size:12px}\n.ui-graph-node__actions{display:flex;align-items:center;gap:4px}\n@media(prefers-reduced-motion:reduce){.ui-graph-node.ui-card{transition:none}.ui-graph-node[data-status=running]{animation:none}}\n@media print{.ui-graph-node[data-status=running]{animation:none}}\n"
    },
    {
      "path": "src/components/ui/graph-connectors.ts",
      "type": "registry:component",
      "target": "@ui/graph-connectors.ts",
      "content": "import type { GraphPoint } from \"./graph-types\";\n\nexport type GraphConnector = \"elbow\" | \"bezier\" | \"straight\";\nexport interface GraphConnectorOptions {\n  source: GraphPoint;\n  target: GraphPoint;\n  connector?: GraphConnector;\n  direction?: \"down\" | \"right\";\n  /** Caller-owned interior waypoints, independent of graph relationships. */\n  points?: readonly GraphPoint[];\n}\nexport interface GraphConnectorPath {\n  path: string;\n  label: GraphPoint;\n}\nconst finite = (point: GraphPoint) =>\n  point && Number.isFinite(point.x) && Number.isFinite(point.y);\n\n/** SVG geometry without a canvas engine or application state. */\nexport function getGraphConnectorPath({\n  source,\n  target,\n  connector = \"elbow\",\n  direction = \"down\",\n  points,\n}: GraphConnectorOptions): GraphConnectorPath {\n  if (![source, target, ...(points ?? [])].every(finite))\n    throw new Error(\"Connector coordinates must be finite\");\n  const center = { x: (source.x + target.x) / 2, y: (source.y + target.y) / 2 };\n  if (connector === \"straight\")\n    return {\n      path: `M ${source.x} ${source.y} L ${target.x} ${target.y}`,\n      label: center,\n    };\n  const horizontal = direction === \"right\";\n  if (connector === \"bezier\") {\n    const offset = Math.max(\n      40,\n      Math.abs(horizontal ? target.x - source.x : target.y - source.y) / 2,\n    );\n    const first = {\n      x: source.x + (horizontal ? offset : 0),\n      y: source.y + (horizontal ? 0 : offset),\n    };\n    const last = {\n      x: target.x - (horizontal ? offset : 0),\n      y: target.y - (horizontal ? 0 : offset),\n    };\n    return {\n      path: `M ${source.x} ${source.y} C ${first.x} ${first.y} ${last.x} ${last.y} ${target.x} ${target.y}`,\n      label: {\n        x: (source.x + first.x * 3 + last.x * 3 + target.x) / 8,\n        y: (source.y + first.y * 3 + last.y * 3 + target.y) / 8,\n      },\n    };\n  }\n  if (connector !== \"elbow\") throw new Error(`Unknown connector: ${connector}`);\n  const route: GraphPoint[] = [source];\n  const append = (point: GraphPoint) => {\n    const previous = route.at(-1)!;\n    if (point.x !== previous.x || point.y !== previous.y) route.push(point);\n  };\n  // shortcut: elbows do not avoid unrelated obstacles; supply routes for dense cross-links.\n  const stops = points?.length\n    ? points\n    : horizontal\n      ? [\n          { x: center.x, y: source.y },\n          { x: center.x, y: target.y },\n        ]\n      : [\n          { x: source.x, y: center.y },\n          { x: target.x, y: center.y },\n        ];\n  for (const [index, next] of [...stops, target].entries()) {\n    const previous = route.at(-1)!;\n    if (previous.x !== next.x && previous.y !== next.y)\n      append(\n        index === stops.length\n          ? horizontal\n            ? { x: previous.x, y: next.y }\n            : { x: next.x, y: previous.y }\n          : horizontal\n            ? { x: next.x, y: previous.y }\n            : { x: previous.x, y: next.y },\n      );\n    append(next);\n  }\n  const labelRoute: GraphPoint[] = [];\n  for (const point of route) {\n    const previous = labelRoute.at(-1),\n      before = labelRoute.at(-2);\n    if (\n      before &&\n      previous &&\n      ((before.x === previous.x &&\n        previous.x === point.x &&\n        (previous.y - before.y) * (point.y - previous.y) > 0) ||\n        (before.y === previous.y &&\n          previous.y === point.y &&\n          (previous.x - before.x) * (point.x - previous.x) > 0))\n    )\n      labelRoute.pop();\n    labelRoute.push(point);\n  }\n  const segments = labelRoute.slice(1).map((end, index) => {\n    const start = labelRoute[index];\n    return {\n      start,\n      end,\n      length: Math.abs(end.x - start.x) + Math.abs(end.y - start.y),\n    };\n  });\n  let remaining = segments.reduce((total, segment) => total + segment.length, 0) / 2;\n  let label = center;\n  for (const segment of segments) {\n    if (remaining <= segment.length && segment.length > 0) {\n      const fraction = remaining / segment.length;\n      label = { x: segment.start.x + (segment.end.x - segment.start.x) * fraction, y: segment.start.y + (segment.end.y - segment.start.y) * fraction };\n      break;\n    }\n    remaining -= segment.length;\n  }\n  return {\n    path: `M ${route.map((point) => `${point.x} ${point.y}`).join(\" L \")}`,\n    label,\n  };\n}\n"
    },
    {
      "path": "src/components/ui/graph-view-types.ts",
      "type": "registry:component",
      "target": "@ui/graph-view-types.ts",
      "content": "import type * as React from \"react\";\nimport type { GraphChange, GraphEdge, GraphNode, GraphPoint, GraphSize } from \"./graph-types\";\nimport type { GraphConnector } from \"./graph-connectors\";\nimport type { GraphNodeAnchors } from \"./graph-anchors\";\n\nexport type GraphNodeAction =\n  \"rename\" | \"child\" | \"parent\" | \"sibling\" | \"move\" | \"relationship\" | \"canvas\" | \"position\" | \"remove\";\nexport interface GraphHandleView {\n  portId?: string;\n  direction: \"input\" | \"output\";\n  side: \"left\" | \"right\" | \"top\" | \"bottom\";\n  offset: number;\n  label: string;\n  disabled?: boolean;\n}\nexport interface GraphNodeViewData extends Record<string, unknown> {\n  graphNode: GraphNode<any>;\n  mode: \"diagram\" | \"canvas\";\n  direction: \"down\" | \"right\";\n  anchors: Required<GraphNodeAnchors>;\n  collapsed: boolean;\n  canToggle: boolean;\n  childCount: number;\n  orderTarget?: { before?: string; after?: string };\n  renderNodeFooter?: (node: GraphNode<any>) => React.ReactNode;\n  descendantCount?: number;\n  childNoun: string;\n  portHighlighted: boolean;\n  connectedPortIds: readonly string[];\n  onPortHover?: (nodeId: string, portId?: string) => void;\n  renderNode?: (node: GraphNode<any>, state: { selected: boolean }) => React.ReactNode;\n  onToggle: (id: string) => void;\n  onAction: (node: GraphNode<any>, action: GraphNodeAction, sourcePortId?: string, anchor?: Element | null) => void;\n  onReorder: (node: GraphNode<any>, direction: \"up\" | \"down\", anchor?: Element | null) => void;\n  canReorder: { up: boolean; down: boolean };\n  actionsOpen: boolean;\n  onActionsOpenChange: (nodeId: string | undefined) => void;\n  canMutate: boolean;\n  pending: boolean;\n  stagedParent: boolean;\n}\nexport interface GraphViewNode {\n  id: string;\n  type: \"graphNode\";\n  position: GraphPoint;\n  width: number;\n  measured?: GraphSize;\n  selected: boolean;\n  ariaLabel?: string;\n  data: GraphNodeViewData;\n}\nexport interface GraphEdgeViewData extends Record<string, unknown> {\n  graphEdge: GraphEdge<any>;\n  onChange: (change: GraphChange<any, any>) => Promise<boolean>;\n  onReconnect: (edge: GraphEdge<any>, endpoint: \"source\" | \"target\", anchor?: Element | null) => void;\n  onSelect: () => void;\n  canMutate: boolean;\n  pending: boolean;\n  roles: readonly { value: string; label: string }[];\n  sourceNode?: GraphNode<any>;\n  targetNode?: GraphNode<any>;\n  portHighlighted?: boolean;\n  onHover?: (hovered: boolean) => void;\n  connector: GraphConnector;\n  direction: \"down\" | \"right\";\n  layoutPath?: readonly GraphPoint[];\n}\nexport interface GraphViewEdge {\n  id: string;\n  source: string;\n  target: string;\n  sourceHandle?: string;\n  targetHandle?: string;\n  type: \"graphEdge\";\n  interactionWidth?: number;\n  selected: boolean;\n  zIndex?: number;\n  focusable?: boolean;\n  ariaLabel: string;\n  data: GraphEdgeViewData;\n  style: React.CSSProperties;\n}\nexport type GraphViewNodeChange =\n  | { type: \"select\"; id: string; selected: boolean }\n  | { type: \"dimensions\"; id: string; dimensions?: GraphSize }\n  | { type: \"position\"; id: string; position?: GraphPoint; dragging?: boolean };\nexport interface GraphViewportHandle {\n  fitView: () => Promise<boolean>;\n  zoomIn: () => void;\n  zoomOut: () => void;\n  setCenter: (x: number, y: number, options?: { zoom?: number; duration?: number }) => Promise<boolean>;\n  screenToFlowPosition: (point: GraphPoint) => GraphPoint;\n  getZoom: () => number;\n}\nexport interface GraphViewportProps {\n  connector: GraphConnector;\n  nodes: GraphViewNode[];\n  edges: GraphViewEdge[];\n  mode: \"diagram\" | \"canvas\";\n  editable: boolean;\n  pending: boolean;\n  label: string;\n  fitKey: string;\n  anchorId?: string;\n  onReady: (handle: GraphViewportHandle) => void;\n  onNodesChange: (changes: GraphViewNodeChange[]) => void;\n  onSelectEdge: (edgeId: string) => void;\n  onPaneClick: () => void;\n  onDrag: (node: GraphViewNode) => void;\n  onDragStop: (node: GraphViewNode) => void;\n  onConnect: (connection: {\n    source: string;\n    target: string;\n    sourceHandle: string | null;\n    targetHandle: string | null;\n  }) => void;\n  onReconnect: (\n    edge: GraphViewEdge,\n    connection: { source: string; target: string; sourceHandle: string | null; targetHandle: string | null },\n  ) => void;\n}\n"
    },
    {
      "path": "src/components/ui/graph-anchors.ts",
      "type": "registry:component",
      "target": "@ui/graph-anchors.ts",
      "content": "import type { GraphPoint, GraphSize } from \"./graph-types\";\n\nexport type GraphAnchorSide = \"top\" | \"right\" | \"bottom\" | \"left\";\nexport interface GraphAnchor {\n  side: GraphAnchorSide;\n  /** Fraction along the selected side, from its top or left edge. */\n  offset: number;\n}\nexport interface GraphNodeAnchors {\n  input?: GraphAnchor;\n  output?: GraphAnchor;\n}\nexport type GraphAnchors = Readonly<Record<string, GraphNodeAnchors>>;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nexport function validateGraphAnchor(anchor: GraphAnchor): GraphAnchor {\n  if (!anchor || typeof anchor !== \"object\" || ![\"top\", \"right\", \"bottom\", \"left\"].includes(anchor.side))\n    throw new Error(\"Graph anchor side must be top, right, bottom, or left.\");\n  if (!Number.isFinite(anchor.offset) || anchor.offset < 0 || anchor.offset > 1)\n    throw new Error(\"Graph anchor offset must be a finite fraction from 0 to 1.\");\n  return anchor;\n}\n\nexport function normalizeGraphAnchors(\n  ids: readonly string[],\n  anchors: GraphAnchors | undefined,\n  direction: \"down\" | \"right\",\n): Readonly<Record<string, Required<GraphNodeAnchors>>> {\n  if (anchors !== undefined && !isRecord(anchors))\n    throw new Error(\"Graph anchors must be an object keyed by node ID.\");\n  return Object.fromEntries(ids.map((id) => {\n    const value = anchors && Object.hasOwn(anchors, id) ? anchors[id] : undefined;\n    if (anchors && Object.hasOwn(anchors, id) && !isRecord(value))\n      throw new Error(`Graph anchors for ${id} must be an object.`);\n    return [id, {\n      input: validateGraphAnchor(value?.input === undefined ? { side: direction === \"right\" ? \"left\" : \"top\", offset: 0.5 } : value.input),\n      output: validateGraphAnchor(value?.output === undefined ? { side: direction === \"right\" ? \"right\" : \"bottom\", offset: 0.5 } : value.output),\n    }];\n  }));\n}\n\nexport function resolveGraphAnchor(position: GraphPoint, size: GraphSize, anchor: GraphAnchor): GraphPoint {\n  validateGraphAnchor(anchor);\n  if (![position?.x, position?.y].every(Number.isFinite))\n    throw new Error(\"Graph anchor position must be finite.\");\n  if (![size?.width, size?.height].every((value) => Number.isFinite(value) && value > 0))\n    throw new Error(\"Graph anchor box needs positive finite dimensions.\");\n  switch (anchor.side) {\n    case \"top\": return { x: position.x + size.width * anchor.offset, y: position.y };\n    case \"right\": return { x: position.x + size.width, y: position.y + size.height * anchor.offset };\n    case \"bottom\": return { x: position.x + size.width * anchor.offset, y: position.y + size.height };\n    case \"left\": return { x: position.x, y: position.y + size.height * anchor.offset };\n  }\n}\n\nexport function graphAnchorHandleStyle(anchor: GraphAnchor): { left?: string; top?: string } {\n  validateGraphAnchor(anchor);\n  return anchor.side === \"top\" || anchor.side === \"bottom\"\n    ? { left: `${anchor.offset * 100}%` }\n    : { top: `${anchor.offset * 100}%` };\n}\n"
    },
    {
      "path": "src/components/ui/node-port.tsx",
      "type": "registry:component",
      "target": "@ui/node-port.tsx",
      "content": "import \"./foundation.css\";\nimport * as React from \"react\";\nimport { ArrowBigDown, ArrowBigLeft, ArrowBigRight, ArrowBigUp, ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Cpu, EllipsisVertical, Image, Music, Type, Video } from \"lucide-react\";\nimport { Badge } from \"./badge\";\nimport \"./node-port.css\";\n\nexport function getNodePortOffsets(count: number, gap = 24): number[] {\n  if (!Number.isInteger(count) || count < 0) throw new Error(\"Node port count must be a nonnegative integer.\");\n  if (!Number.isFinite(gap) || gap < 0) throw new Error(\"Node port gap must be a finite nonnegative number.\");\n  return Array.from({ length: count }, (_, index) => (index - (count - 1) / 2) * gap);\n}\n\ntype NodePortSide = \"left\" | \"right\" | \"top\" | \"bottom\";\ntype NodePortElement = React.ReactElement<NodePortProps>;\n\nexport interface NodePortGroupProps extends React.HTMLAttributes<HTMLDivElement> {\n  side: NodePortSide;\n  gap?: number;\n  children?: React.ReactNode;\n}\n\nexport function NodePortGroup({ side, gap, className, style, children, ...props }: NodePortGroupProps) {\n  const ports = React.Children.toArray(children).filter((child): child is NodePortElement => React.isValidElement(child) && child.type === NodePort);\n  const offsets = getNodePortOffsets(ports.length, gap ?? (side === \"left\" || side === \"right\" ? 44 : 64));\n  let index = 0;\n  return <div {...props} role={props.role ?? \"group\"} aria-label={props[\"aria-label\"] ?? `${side} ports`} className={[\"ui-node-port-group\", `ui-node-port-group--${side}`, className].filter(Boolean).join(\" \")} style={style}>\n    {React.Children.map(children, child => {\n      if (!React.isValidElement<NodePortProps>(child) || child.type !== NodePort) return child;\n      const portIndex = index++;\n      return React.cloneElement(child, { placement: side, offset: child.props.offset ?? offsets[portIndex] });\n    })}\n  </div>;\n}\n\nexport interface NodePortProps extends React.HTMLAttributes<HTMLDivElement> {\n  label: string;\n  direction: \"input\" | \"output\";\n  dataType?: string;\n  connected?: boolean;\n  invalid?: boolean;\n  disabled?: boolean;\n  variant?: \"core\" | \"icon\";\n  showLabel?: boolean;\n  size?: \"sm\" | \"md\" | \"lg\" | \"xl\";\n  icon?: React.ReactNode;\n  connectedIcon?: React.ReactNode;\n  placement?: NodePortSide;\n  offset?: number;\n  error?: string;\n  handle?: React.ReactNode;\n  indicatorRef?: React.Ref<HTMLSpanElement>;\n  onActivate?: () => void;\n  /** Caller state for a controlled menu. Keeps the badge's menu mark visible while the menu is open. */\n  menuOpen?: boolean;\n}\n\nfunction defaultIcon(dataType: string | undefined, side: NodePortSide, outward: boolean) {\n  const t = dataType?.toLowerCase() ?? \"\";\n  if (t.includes(\"text\")) return <Type />;\n  if (t.includes(\"image\")) return <Image />;\n  if (t.includes(\"model\")) return <Cpu />;\n  if (t.includes(\"audio\") || t.includes(\"music\")) return <Music />;\n  if (t.includes(\"video\")) return <Video />;\n  const Arrow = side === \"top\" ? outward ? ArrowUp : ArrowDown\n    : side === \"bottom\" ? outward ? ArrowDown : ArrowUp\n    : side === \"left\" ? outward ? ArrowLeft : ArrowRight\n    : outward ? ArrowRight : ArrowLeft;\n  return <Arrow />;\n}\n\nfunction connectedDefaultIcon(dataType: string | undefined, side: NodePortSide, outward: boolean) {\n  const t = dataType?.toLowerCase() ?? \"\";\n  if (t.includes(\"text\")) return <Type />;\n  if (t.includes(\"image\")) return <Image />;\n  if (t.includes(\"model\")) return <Cpu />;\n  if (t.includes(\"audio\") || t.includes(\"music\")) return <Music />;\n  if (t.includes(\"video\")) return <Video />;\n  const Arrow = side === \"top\" ? outward ? ArrowBigUp : ArrowBigDown\n    : side === \"bottom\" ? outward ? ArrowBigDown : ArrowBigUp\n    : side === \"left\" ? outward ? ArrowBigLeft : ArrowBigRight\n    : outward ? ArrowBigRight : ArrowBigLeft;\n  return <Arrow fill=\"currentColor\" />;\n}\n\nexport const NodePort = React.forwardRef<HTMLDivElement, NodePortProps>(function NodePort(\n  { label, direction, dataType, connected = false, invalid: invalidProp = false, disabled = false, variant = \"core\", showLabel, size, icon, connectedIcon, placement, offset = 0, error, handle, indicatorRef, onActivate, menuOpen = false, children, className, style, \"aria-label\": ariaLabel, \"aria-describedby\": describedBy, ...props },\n  ref,\n) {\n  const invalid = invalidProp || Boolean(error);\n  const effectiveSize = size ?? (variant === \"icon\" ? \"lg\" : \"md\");\n  const labelsVisible = showLabel ?? (variant === \"core\" && direction === \"input\");\n  if (placement && ![\"left\", \"right\", \"top\", \"bottom\"].includes(placement)) throw new Error(\"Node port placement must be a side.\");\n  if (placement && !Number.isFinite(offset)) throw new Error(\"Placed node port offset must be finite pixels.\");\n  const invalidDescription = React.useId();\n  const directionDescription = React.useId();\n  const connectionDescription = React.useId();\n  const side = placement ?? (direction === \"output\" ? \"right\" : \"left\");\n  const outward = direction === \"output\";\n  const glyph = connected ? connectedIcon ?? (icon ? icon : connectedDefaultIcon(dataType, side, outward)) : icon ?? defaultIcon(dataType, side, outward);\n  const handleProps = React.isValidElement(handle) ? handle.props as { \"aria-label\"?: string; \"aria-describedby\"?: string; \"aria-invalid\"?: boolean; \"aria-disabled\"?: boolean } : undefined;\n  const handleNode = React.isValidElement(handle) ? React.cloneElement(handle as React.ReactElement<{ \"aria-label\"?: string; \"aria-describedby\"?: string; \"aria-invalid\"?: boolean; \"aria-disabled\"?: boolean }>, {\n    \"aria-label\": handleProps?.[\"aria-label\"] ?? [label, direction, dataType, connected && \"connected\", invalid && \"invalid\", disabled && \"disabled\"].filter(Boolean).join(\", \"),\n    \"aria-describedby\": [handleProps?.[\"aria-describedby\"], directionDescription, !connected && connectionDescription, invalid && invalidDescription].filter(Boolean).join(\" \"),\n    \"aria-invalid\": invalid || handleProps?.[\"aria-invalid\"],\n    \"aria-disabled\": disabled || handleProps?.[\"aria-disabled\"],\n  }) : handle;\n  const visual = <span className=\"ui-node-port__visual\" aria-hidden=\"true\">{connected && <span className=\"ui-node-port__bullet\" />}{variant === \"icon\" && <span className=\"ui-node-port__glyph\">{glyph}</span>}</span>;\n  // The badge opens the same actions, so a separate trigger would be redundant:\n  // the menu mark lives inside the label pill and the badge stays the single control.\n  const menuMark = onActivate && children ? <EllipsisVertical aria-hidden=\"true\" /> : undefined;\n  const indicator = <span ref={indicatorRef} className=\"ui-node-port__indicator\" aria-hidden={handleNode || onActivate ? undefined : true}>\n    {onActivate && !handleNode ? <button type=\"button\" className=\"ui-node-port__point-action\" aria-label={`${label} connection actions`} disabled={disabled}>{visual}</button> : visual}\n    {handleNode}\n  </span>;\n  const rootStyle = { ...style, ...(placement ? { \"--ui-node-port-offset\": `${offset}px` } : {}) } as React.CSSProperties;\n  return <div\n    {...props}\n    ref={ref}\n    onClick={event => {\n      props.onClick?.(event);\n      if (!event.defaultPrevented && !disabled && event.target instanceof Element && event.target.closest(\".ui-node-port__indicator, .ui-node-port__label\")) onActivate?.();\n    }}\n    role={props.role ?? \"group\"}\n    className={[\"ui-node-port\", `ui-node-port--${direction}`, `ui-node-port--${variant}`, `ui-node-port--${effectiveSize}`, placement && `ui-node-port--${placement}`, className].filter(Boolean).join(\" \")}\n    style={rootStyle}\n    data-connected={connected || undefined}\n    data-type={dataType}\n    data-invalid={invalid || undefined}\n    data-disabled={disabled || undefined}\n    data-menu-open={menuOpen || undefined}\n    aria-label={ariaLabel ?? [label, direction, dataType, connected && \"connected\", invalid && \"invalid\", disabled && \"disabled\"].filter(Boolean).join(\", \")}\n    aria-invalid={invalid || undefined}\n    aria-disabled={disabled || undefined}\n    aria-describedby={[describedBy, directionDescription, !connected && connectionDescription, invalid && invalidDescription].filter(Boolean).join(\" \")}\n  >\n    {indicator}\n    <span className=\"ui-node-port__details\">\n      {labelsVisible && <Badge render={onActivate ? <button type=\"button\" disabled={disabled} aria-expanded={menuOpen || undefined} /> : undefined} className=\"ui-node-port__label\" size=\"lg\" variant=\"ghost\" trailing={menuMark}>{label}</Badge>}\n      {children && <span className=\"ui-node-port__actions\">{children}</span>}\n      {invalid && error && <span id={invalidDescription} className=\"ui-node-port__error\" role=\"alert\">{error}</span>}\n    </span>\n    <span id={directionDescription} className=\"ui-sr-only ui-node-port__sr-only\">{direction === \"input\" ? \"Input port. Connect data to this node.\" : \"Output port. Send data from this node.\"}</span>\n    {!connected && <span id={connectionDescription} className=\"ui-sr-only ui-node-port__sr-only\">Not connected</span>}\n    {invalid && !error && <span id={invalidDescription} className=\"ui-sr-only ui-node-port__sr-only\">Invalid connection</span>}\n  </div>;\n});\n\nNodePort.displayName = \"NodePort\";\nexport default NodePort;\n"
    },
    {
      "path": "src/components/ui/node-port.css",
      "type": "registry:file",
      "target": "@ui/node-port.css",
      "content": ".ui-node-port{position:relative;display:flex;min-width:0;min-height:44px;align-items:center;gap:8px;color:var(--foreground);font-size:12px;line-height:18px}\n.ui-node-port[data-disabled]{opacity:.65}\n.ui-node-port--output{flex-direction:row-reverse;text-align:end}\n.ui-node-port-group{position:absolute;z-index:2;width:0;height:0;overflow:visible;pointer-events:none}\n.ui-node-port-group--left{top:50%;left:0}\n.ui-node-port-group--right{top:50%;right:0}\n.ui-node-port-group--top{top:0;left:50%}\n.ui-node-port-group--bottom{bottom:0;left:50%}\n.ui-node-port--left,.ui-node-port--right,.ui-node-port--top,.ui-node-port--bottom{position:absolute;display:block;width:0;height:0;min-height:0;transform:translate(-50%,-50%);pointer-events:auto}\n.ui-node-port--left{left:0;top:var(--ui-node-port-offset,0px)}\n.ui-node-port--right{right:0;top:var(--ui-node-port-offset,0px)}\n.ui-node-port--top{top:0;left:var(--ui-node-port-offset,0px)}\n.ui-node-port--bottom{bottom:0;left:var(--ui-node-port-offset,0px)}\n.ui-node-port__indicator{position:relative;display:inline-flex;flex:none;width:44px;height:44px;align-items:center;justify-content:center}\n.ui-node-port--left .ui-node-port__indicator,.ui-node-port--right .ui-node-port__indicator,.ui-node-port--top .ui-node-port__indicator,.ui-node-port--bottom .ui-node-port__indicator{position:absolute;z-index:1;top:50%;left:50%;transform:translate(-50%,-50%)}\n.ui-node-port__visual{position:relative;z-index:1;display:grid;flex:none;width:var(--ui-node-port-diameter,12px);height:var(--ui-node-port-diameter,12px);place-items:center;box-sizing:border-box;border:1px solid var(--ui-node-port-color,var(--muted-foreground));border-radius:50%;background:var(--background);color:var(--ui-node-port-color,var(--muted-foreground))}\n.ui-node-port--sm{--ui-node-port-core-size:10px;--ui-node-port-icon-size:20px;--ui-node-port-glyph-size:8px}\n.ui-node-port--md{--ui-node-port-core-size:12px;--ui-node-port-icon-size:24px;--ui-node-port-glyph-size:10px}\n.ui-node-port--lg{--ui-node-port-core-size:16px;--ui-node-port-icon-size:28px;--ui-node-port-glyph-size:12px}\n.ui-node-port--xl{--ui-node-port-core-size:20px;--ui-node-port-icon-size:32px;--ui-node-port-glyph-size:14px}\n.ui-node-port--core{--ui-node-port-diameter:var(--ui-node-port-core-size,12px)}\n.ui-node-port--icon{--ui-node-port-diameter:var(--ui-node-port-icon-size,24px)}\n.ui-node-port[data-type=\"text\"]{--ui-node-port-color:light-dark(var(--color-data-indigo-strong),var(--color-data-indigo))}\n.ui-node-port[data-type=\"image\"]{--ui-node-port-color:light-dark(var(--color-data-emerald-strong),var(--color-data-emerald))}\n.ui-node-port[data-type=\"model\"]{--ui-node-port-color:light-dark(var(--color-data-sky-strong),var(--color-data-sky))}\n.ui-node-port[data-type=\"audio\"],.ui-node-port[data-type=\"music\"]{--ui-node-port-color:light-dark(var(--color-data-amber-strong),var(--color-data-amber))}\n.ui-node-port[data-type=\"video\"]{--ui-node-port-color:light-dark(var(--color-data-rose-strong),var(--color-data-rose))}\n.ui-node-port--output:not([data-connected]){--ui-node-port-color:var(--muted-foreground)}\n.ui-node-port[data-type][data-invalid],.ui-node-port[data-invalid]{--ui-node-port-color:var(--destructive)}\n.ui-node-port__bullet{width:calc(var(--ui-node-port-diameter,12px)*.42);height:calc(var(--ui-node-port-diameter,12px)*.42);border-radius:50%;background:var(--ui-node-port-color,var(--muted-foreground))}\n.ui-node-port--icon[data-connected] .ui-node-port__visual{border-color:var(--ui-node-port-color,var(--muted-foreground));background:var(--background);color:var(--ui-node-port-color,var(--muted-foreground))}\n.ui-node-port--icon[data-connected] .ui-node-port__bullet{position:absolute;top:50%;left:50%;width:62%;height:62%;transform:translate(-50%,-50%);background:var(--ui-node-port-color,var(--muted-foreground))}\n.ui-node-port--icon[data-connected] .ui-node-port__glyph{position:relative;z-index:1;width:40%;height:40%;color:var(--background)}\n.ui-node-port__glyph{display:grid;width:var(--ui-node-port-glyph-size,14px);height:var(--ui-node-port-glyph-size,14px);place-items:center;color:var(--ui-node-port-color,var(--muted-foreground))}\n.ui-node-port__glyph>svg{display:block;width:100%;height:100%;stroke-width:var(--icon-stroke)}\n.ui-node-port__glyph>svg:not([class*=\"lucide\"]){overflow:visible}\n.ui-node-port__details{position:relative;z-index:2;display:flex;min-width:0;max-width:100%;align-items:center;flex-wrap:wrap;gap:4px 6px;color:var(--foreground);overflow-wrap:anywhere}\n.ui-node-port--left .ui-node-port__details,.ui-node-port--right .ui-node-port__details,.ui-node-port--top .ui-node-port__details,.ui-node-port--bottom .ui-node-port__details{position:absolute;top:auto;bottom:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px);left:50%;width:max-content;max-width:220px;flex-wrap:nowrap}\n.ui-node-port--left .ui-node-port__details{left:auto;right:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px)}\n.ui-node-port--right .ui-node-port__details{left:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px)}\n.ui-node-port--top .ui-node-port__details{top:auto;bottom:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px);left:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px)}\n.ui-node-port--bottom .ui-node-port__details{top:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px);bottom:auto;left:calc(50% + var(--ui-node-port-diameter,12px)/2 + 4px)}\n.ui-node-port__label.ui-badge{--badge-ink:var(--ui-node-port-color,var(--muted-foreground));flex:none;max-width:220px;white-space:nowrap}\n.ui-node-port__label .ui-badge__trailing{display:none}\n@media(hover:hover) and (pointer:fine){\n.ui-node-port:hover .ui-node-port__label .ui-badge__trailing,.ui-node-port:focus-within .ui-node-port__label .ui-badge__trailing{display:inline-flex}\n}\n@media(pointer:coarse){.ui-node-port__label .ui-badge__trailing{display:inline-flex}}\n.ui-node-port[data-menu-open] .ui-node-port__label .ui-badge__trailing{display:inline-flex}\n.ui-node-port__actions{display:inline-flex;flex:0 0 auto;align-items:center;gap:2px;opacity:0;pointer-events:none;transition:opacity 120ms ease-out}\n.ui-node-port:focus-within .ui-node-port__actions,.ui-node-port__actions:focus-within{opacity:1;pointer-events:auto}\n@media(hover:hover) and (pointer:fine){.ui-node-port:hover .ui-node-port__actions{opacity:1;pointer-events:auto}}\n@media(pointer:coarse){.ui-node-port__actions{opacity:1;pointer-events:auto}}\n@media(prefers-reduced-motion:reduce){.ui-node-port__actions{transition:none}}\n.ui-node-port__error{flex-basis:100%;margin:0;padding:0;padding-inline-start:calc(var(--space-1)*1.5 + 1px);color:var(--destructive);font-size:var(--font-size-2xs);line-height:var(--leading-copy);text-align:start}\n.ui-node-port__indicator>:is(button,[role=button]){min-width:44px;min-height:44px}\n.ui-node-port__point-action{position:relative;z-index:2;display:grid;place-items:center;min-width:44px;min-height:44px;padding:0;border:0;border-radius:50%;background:transparent;color:inherit;cursor:pointer}\n.ui-node-port__point-action:disabled{cursor:default}\n.ui-node-port__point-action:focus-visible{outline:2px solid var(--ring);outline-offset:-2px}\n.ui-node-port__error{position:relative;z-index:3}\n.ui-node-port__details:has(.ui-node-port__error){flex-wrap:wrap;align-items:flex-start}\n\n.ui-node-port__point-action,.ui-node-port__label:is(button,[role=\"button\"]){-webkit-tap-highlight-color:transparent;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;touch-action:manipulation}\n.ui-node-port__point-action:not(:disabled):active .ui-node-port__visual{border-color:var(--foreground)}\n.ui-node-port__label:is(button,[role=\"button\"]){position:relative}\n.ui-node-port__label:is(button,[role=\"button\"])::before{content:\"\";position:absolute;top:50%;left:50%;width:max(100%,44px);height:44px;transform:translate(-50%,-50%)}\n.ui-node-port__label:not(:disabled):active{background:var(--quiet-active)}\n"
    },
    {
      "path": "src/components/ui/edge-path.tsx",
      "type": "registry:component",
      "target": "@ui/edge-path.tsx",
      "content": "export { NodePath as EdgePath, NodePath as default } from \"./node-path\";\nexport type { NodePathProps as EdgePathProps } from \"./node-path\";\n"
    },
    {
      "path": "src/components/ui/node-path.tsx",
      "type": "registry:component",
      "target": "@ui/node-path.tsx",
      "content": "import \"./foundation.css\";\nimport * as React from \"react\";\nimport \"./edge-path.css\";\n\nexport interface NodePathProps extends React.SVGProps<SVGPathElement> {\n  d: string;\n  line?: \"solid\" | \"dashed\" | \"dotted\";\n  status?: \"idle\" | \"running\" | \"success\" | \"error\";\n  selected?: boolean;\n  casing?: boolean;\n  flow?: \"dash\" | \"pulse\";\n  flowColor?: string;\n  /** Content type that colors the edge to match its endpoint ports. Omit for a neutral edge. */\n  dataType?: string;\n  /** Optional caller-owned control at half the SVG path length. Omit for a quiet canvas. */\n  action?: React.ReactNode;\n}\n\nexport const NodePath = React.forwardRef<SVGPathElement, NodePathProps>(function NodePath(\n  { d, line = \"solid\", status = \"idle\", selected = false, casing = true, flow = \"dash\", flowColor, dataType, action, className, ...props },\n  ref,\n) {\n  const pathRef = React.useRef<SVGPathElement>(null);\n  React.useImperativeHandle(ref, () => pathRef.current!, []);\n  const [midpoint, setMidpoint] = React.useState<{ x: number; y: number; scaleX: number; scaleY: number } | null>(null);\n  const hasAction = action != null && action !== false;\n  React.useLayoutEffect(() => {\n    if (!hasAction) return;\n    const path = pathRef.current;\n    if (!path || typeof path.getTotalLength !== \"function\") return;\n    const measure = () => {\n      try {\n        const length = path.getTotalLength();\n        const point = length > 0 && Number.isFinite(length) ? path.getPointAtLength(length / 2) : null;\n        const matrix = path.getScreenCTM?.();\n        const scaleX = matrix ? Math.hypot(matrix.a, matrix.b) : 1;\n        const scaleY = matrix ? Math.hypot(matrix.c, matrix.d) : 1;\n        setMidpoint(point && Number.isFinite(point.x) && Number.isFinite(point.y) && scaleX > 0 && scaleY > 0 ? { x: point.x, y: point.y, scaleX, scaleY } : null);\n      } catch {\n        setMidpoint(null);\n      }\n    };\n    measure();\n    // Keep the control and touch target legible in a stretched SVG viewport.\n    const observer = typeof ResizeObserver === \"undefined\" ? null : new ResizeObserver(measure);\n    if (path.ownerSVGElement) observer?.observe(path.ownerSVGElement);\n    return () => observer?.disconnect();\n  }, [d, hasAction]);\n  const pulseFilterId = `ui-graph-edge-pulse-${React.useId().replace(/:/g, \"\")}`;\n  return (\n    <>\n    {casing && <path d={d} fill=\"none\" stroke=\"var(--graph-edge-surface,var(--background))\" strokeWidth={5} strokeLinecap=\"round\" vectorEffect=\"non-scaling-stroke\" pointerEvents=\"none\" aria-hidden=\"true\" />}\n    <path\n      {...props}\n      ref={pathRef}\n      d={d}\n      fill={props.fill ?? \"none\"}\n      vectorEffect=\"non-scaling-stroke\"\n      className={[\"ui-graph-edge-path\", className].filter(Boolean).join(\" \")}\n      data-line={line}\n      data-status={status}\n      data-flow={flow}\n      data-type={dataType}\n      data-selected={selected || undefined}\n    />\n    {status === \"running\" && flow === \"pulse\" && <>\n      <defs><filter id={pulseFilterId} x=\"-50%\" y=\"-50%\" width=\"200%\" height=\"200%\"><feGaussianBlur stdDeviation=\"2\" /></filter></defs>\n      <path d={d} pathLength={100} fill=\"none\" stroke={flowColor ?? \"var(--foreground)\"} strokeWidth={4} strokeDasharray=\"24 76\" filter={`url(#${pulseFilterId})`} vectorEffect=\"non-scaling-stroke\" className=\"ui-graph-edge-path__pulse-glow\" pointerEvents=\"none\" aria-hidden=\"true\" />\n      <path d={d} pathLength={100} fill=\"none\" stroke={flowColor ?? \"var(--foreground)\"} strokeWidth={1.5} strokeDasharray=\"24 76\" vectorEffect=\"non-scaling-stroke\" className=\"ui-graph-edge-path__pulse\" pointerEvents=\"none\" aria-hidden=\"true\" />\n    </>}\n    {hasAction && midpoint && <foreignObject x={midpoint.x - 22 / midpoint.scaleX} y={midpoint.y - 22 / midpoint.scaleY} width={44 / midpoint.scaleX} height={44 / midpoint.scaleY} className=\"ui-node-path-action-host\">\n      <div className=\"ui-node-path-action\" style={{ transform: `scale(${1 / midpoint.scaleX}, ${1 / midpoint.scaleY})`, transformOrigin: \"top left\" }}>{action}</div>\n    </foreignObject>}\n    </>\n  );\n});\n\nNodePath.displayName = \"NodePath\";\nexport default NodePath;\n"
    },
    {
      "path": "src/components/ui/edge-path.css",
      "type": "registry:file",
      "target": "@ui/edge-path.css",
      "content": ".ui-graph-edge-path{--graph-edge-color:var(--border);stroke:var(--graph-edge-color);stroke-width:1.5;stroke-linecap:round;vector-effect:non-scaling-stroke}\n.ui-graph-edge-path[data-line=\"dashed\"]{stroke-dasharray:5 4}\n.ui-graph-edge-path[data-line=\"dotted\"]{stroke-dasharray:2 4}\n.ui-graph-edge-path[data-type=\"text\"]{--graph-edge-color:light-dark(var(--color-data-indigo-strong),var(--color-data-indigo))}\n.ui-graph-edge-path[data-type=\"image\"]{--graph-edge-color:light-dark(var(--color-data-emerald-strong),var(--color-data-emerald))}\n.ui-graph-edge-path[data-type=\"model\"]{--graph-edge-color:light-dark(var(--color-data-sky-strong),var(--color-data-sky))}\n.ui-graph-edge-path[data-type=\"audio\"],.ui-graph-edge-path[data-type=\"music\"]{--graph-edge-color:light-dark(var(--color-data-amber-strong),var(--color-data-amber))}\n.ui-graph-edge-path[data-type=\"video\"]{--graph-edge-color:light-dark(var(--color-data-rose-strong),var(--color-data-rose))}\n.ui-graph-edge-path[data-status=\"success\"]{--graph-edge-color:var(--color-success)}\n.ui-graph-edge-path[data-status=\"error\"]{--graph-edge-color:var(--destructive)}\n.ui-graph-edge-path[data-selected]{stroke:color-mix(in srgb,var(--graph-edge-color),var(--foreground) 40%)}\n@media(hover:hover) and (pointer:fine){.ui-graph-edge-path:hover{stroke:color-mix(in srgb,var(--graph-edge-color),var(--foreground) 40%)}}\n.ui-graph-edge-path[data-status=\"running\"][data-flow=\"dash\"]{stroke:var(--foreground);stroke-dasharray:8 8;animation:ui-graph-edge-flow 1200ms linear infinite}\n@keyframes ui-graph-edge-flow{to{stroke-dashoffset:-16}}\n.ui-graph-edge-path__pulse,.ui-graph-edge-path__pulse-glow{stroke-dashoffset:0;stroke-linecap:round;vector-effect:non-scaling-stroke;animation:ui-graph-edge-travel 1800ms linear infinite}\n.ui-graph-edge-path__pulse{opacity:1}\n.ui-graph-edge-path__pulse-glow{opacity:.4}\n@keyframes ui-graph-edge-travel{to{stroke-dashoffset:-100}}\n@media(prefers-reduced-motion:reduce){.ui-graph-edge-path[data-status=\"running\"],.ui-graph-edge-path__pulse,.ui-graph-edge-path__pulse-glow{animation:none}}\n@media print{.ui-graph-edge-path[data-status=\"running\"],.ui-graph-edge-path__pulse,.ui-graph-edge-path__pulse-glow{animation:none}}\n\n.ui-node-path-action-host{overflow:visible;pointer-events:none}\n.ui-node-path-action{display:flex;align-items:center;justify-content:center;width:44px;height:44px;pointer-events:none}\n.ui-node-path-action>.ui-button.ui-button{align-self:center;touch-action:manipulation;-webkit-user-select:none;user-select:none;pointer-events:auto}\n\n.ui-button.ui-edge-action-button,.ui-node-path-action>.ui-button.ui-button{position:relative;width:24px;height:16px;min-height:16px;padding:0;overflow:visible}\n.ui-button.ui-edge-action-button::before,.ui-node-path-action>.ui-button::before{content:\"\";position:absolute;inset:-14px -10px}\n"
    }
  ]
}
