{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "agent-fanout",
  "type": "registry:ui",
  "title": "Agent Fanout",
  "description": "A live tree of the agents a run started and what each is doing.",
  "categories": [
    "ai-&-chat"
  ],
  "dependencies": [
    "@hugeicons/core-free-icons@4.4.0",
    "@hugeicons/react@1.1.10"
  ],
  "registryDependencies": [
    "https://sprout.tulipfarm.ai/r/sprout-base.json",
    "https://sprout.tulipfarm.ai/r/badge.json",
    "https://sprout.tulipfarm.ai/r/brand-icon.json",
    "https://sprout.tulipfarm.ai/r/button.json",
    "https://sprout.tulipfarm.ai/r/popover.json"
  ],
  "files": [
    {
      "path": "registry/sprout/components/ui/agent-fanout.tsx",
      "type": "registry:ui",
      "target": "components/ui/agent-fanout.tsx",
      "content": "'use client';\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState, type CSSProperties, type ReactNode } from 'react';\nimport { CheckIcon } from '@/lib/sprout/icons/check-icon';\nimport { ChevronDownIcon } from '@/lib/sprout/icons/chevron-down-icon';\nimport { ClockIcon } from '@/lib/sprout/icons/clock-icon';\nimport { DangerIcon } from '@/lib/sprout/icons/danger-icon';\nimport { HourglassIcon } from '@/lib/sprout/icons/hourglass-icon';\nimport { SparkleIcon } from '@/lib/sprout/icons/sparkle-icon';\nimport { StopCircleIcon } from '@/lib/sprout/icons/stop-circle-icon';\nimport { cn } from '@/lib/sprout/classes';\nimport { Badge, type BadgeVariant } from '@/components/ui/badge';\nimport { BrandIcon, BrandStack, BrandTile, brandNames, type Brand } from '@/components/ui/brand-icon';\nimport { Button } from '@/components/ui/button';\nimport { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';\n\nexport const agentFanoutStatusNames = ['queued', 'running', 'needs-you', 'done', 'failed', 'stopped'] as const;\n\nexport const agentFanoutLayoutNames = ['auto', 'tree', 'list'] as const;\n\nexport type AgentFanoutStatus = (typeof agentFanoutStatusNames)[number];\nexport type AgentFanoutLayout = (typeof agentFanoutLayoutNames)[number];\n\nexport interface AgentFanoutAgent {\n  id: string;\n  name: string;\n  model?: string | undefined;\n  brand?: Brand | undefined;\n  icon?: ReactNode;\n  task: string;\n  tools?: readonly Brand[] | undefined;\n  status: AgentFanoutStatus;\n  elapsed?: number | undefined;\n  reason?: string | undefined;\n  agents?: readonly AgentFanoutAgent[] | undefined;\n}\n\nexport interface AgentFanoutProps {\n  agent: AgentFanoutAgent;\n  title?: ReactNode;\n  layout?: AgentFanoutLayout | undefined;\n  defaultCollapsed?: readonly string[] | undefined;\n  onRetry?: ((agent: AgentFanoutAgent) => void) | undefined;\n  onDismiss?: ((agent: AgentFanoutAgent) => void) | undefined;\n  onOpen?: ((agent: AgentFanoutAgent) => void) | undefined;\n  className?: string | undefined;\n}\n\nconst statusText: Record<AgentFanoutStatus, string> = {\n  queued: 'Queued',\n  running: 'Running',\n  'needs-you': 'Needs you',\n  done: 'Done',\n  failed: 'Failed',\n  stopped: 'Stopped',\n};\n\nconst statusVariant: Record<AgentFanoutStatus, BadgeVariant> = {\n  queued: 'outline',\n  running: 'info',\n  'needs-you': 'warning',\n  done: 'success',\n  failed: 'destructive',\n  stopped: 'secondary',\n};\n\nconst maxTools = 4;\n\nconst pad = (value: number) => String(value).padStart(2, '0');\n\nfunction formatElapsed(ms: number) {\n  const seconds = Math.max(0, Math.floor(ms / 1000));\n  if (seconds < 60) return `${seconds}s`;\n  const minutes = Math.floor(seconds / 60);\n  if (minutes < 60) return `${minutes}m ${pad(seconds % 60)}s`;\n  return `${Math.floor(minutes / 60)}h ${pad(minutes % 60)}m`;\n}\n\nfunction flatten(agent: AgentFanoutAgent): AgentFanoutAgent[] {\n  return [agent, ...(agent.agents ?? []).flatMap(flatten)];\n}\n\nfunction levels(agent: AgentFanoutAgent): number {\n  return 1 + Math.max(0, ...(agent.agents ?? []).map(levels));\n}\n\nconst plural = (count: number, one: string, many: string) => `${count} ${count === 1 ? one : many}`;\n\nconst busy = (agent: AgentFanoutAgent): boolean => agent.status === 'running' || (agent.agents ?? []).some(busy);\n\nfunction Arc() {\n  return (\n    <svg viewBox=\"0 0 12 12\" aria-hidden=\"true\" data-icon=\"inline-start\" className=\"sprout-agent-fanout-arc\">\n      <circle cx=\"6\" cy=\"6\" r=\"4.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nfunction StatusIcon({ status }: { status: AgentFanoutStatus }) {\n  const props = { 'aria-hidden': true, 'data-icon': 'inline-start' } as const;\n  switch (status) {\n    case 'running':\n      return <Arc />;\n    case 'needs-you':\n      return <ClockIcon {...props} />;\n    case 'done':\n      return <CheckIcon {...props} />;\n    case 'failed':\n      return <DangerIcon {...props} />;\n    case 'stopped':\n      return <StopCircleIcon {...props} />;\n    default:\n      return <HourglassIcon {...props} />;\n  }\n}\n\nfunction Count({ value }: { value: number }) {\n  return (\n    <span key={value} className=\"sprout-agent-fanout-count\">\n      {value}\n    </span>\n  );\n}\n\nfunction Mark({ agent }: { agent: AgentFanoutAgent }) {\n  if (agent.icon === undefined && agent.brand)\n    return (\n      <BrandIcon brand={agent.brand} size=\"md\" data-slot=\"agent-fanout-mark\" className=\"sprout-agent-fanout-mark\" />\n    );\n  return (\n    <BrandTile size=\"md\" data-slot=\"agent-fanout-mark\" className=\"sprout-agent-fanout-mark\">\n      <span aria-hidden=\"true\" className=\"sprout-agent-fanout-mark-icon\">\n        {agent.icon ?? <SparkleIcon size=\"md\" />}\n      </span>\n    </BrandTile>\n  );\n}\n\nfunction Tools({ tools }: { tools: readonly Brand[] }) {\n  const shown = tools.length > maxTools ? tools.slice(0, maxTools - 1) : tools;\n  return (\n    <span className=\"sprout-agent-fanout-tools\">\n      <BrandStack\n        brands={shown.map(brand => ({ brand, name: brandNames[brand] }))}\n        label={`Uses ${tools.map(brand => brandNames[brand]).join(', ')}`}\n      />\n      {shown.length < tools.length && (\n        <span aria-hidden=\"true\" className=\"sprout-agent-fanout-tools-more\">\n          +{tools.length - shown.length}\n        </span>\n      )}\n    </span>\n  );\n}\n\ninterface BranchProps {\n  agent: AgentFanoutAgent;\n  depth: number;\n  row: boolean;\n  collapsed: ReadonlySet<string>;\n  onToggle: (id: string) => void;\n}\n\nfunction Branch({ agent, depth, row, collapsed, onToggle }: BranchProps) {\n  const listId = useId();\n  const kids = agent.agents ?? [];\n  const open = !collapsed.has(agent.id);\n  const count = kids.length;\n  const model = agent.model ?? (agent.brand && brandNames[agent.brand]);\n  return (\n    <li data-slot=\"agent-fanout-branch\" className=\"sprout-agent-fanout-branch\">\n      <div\n        data-slot=\"agent-fanout-card\"\n        data-agent={agent.id}\n        data-status={agent.status}\n        data-depth={depth}\n        className=\"sprout-agent-fanout-card\"\n      >\n        <div className=\"sprout-agent-fanout-head\">\n          <Mark agent={agent} />\n          <div className=\"sprout-agent-fanout-who\">\n            <span className=\"sprout-agent-fanout-name\">{agent.name}</span>\n            {model && <span className=\"sprout-agent-fanout-model\">{model}</span>}\n          </div>\n          <Badge\n            key={agent.status}\n            variant={statusVariant[agent.status]}\n            data-slot=\"agent-fanout-status\"\n            className=\"sprout-agent-fanout-status\"\n          >\n            <StatusIcon status={agent.status} />\n            <span className=\"sprout-agent-fanout-status-text\">{statusText[agent.status]}</span>\n          </Badge>\n        </div>\n        <p className=\"sprout-agent-fanout-task\">\n          {agent.tools && agent.tools.length > 0 && <Tools tools={agent.tools} />}\n          <span className=\"sprout-agent-fanout-task-text\">{agent.task}</span>\n        </p>\n        <div className=\"sprout-agent-fanout-foot\">\n          {agent.elapsed !== undefined && (\n            <time dateTime={`PT${Math.max(0, Math.floor(agent.elapsed / 1000))}S`} className=\"sprout-agent-fanout-time\">\n              {formatElapsed(agent.elapsed)}\n            </time>\n          )}\n          {count > 0 && (\n            <button\n              type=\"button\"\n              aria-expanded={open}\n              aria-controls={listId}\n              aria-label={`${open ? 'Hide' : 'Show'} ${plural(count, 'agent', 'agents')} started by ${agent.name}`}\n              data-slot=\"agent-fanout-toggle\"\n              className=\"sprout-agent-fanout-toggle\"\n              onClick={() => onToggle(agent.id)}\n            >\n              {open ? count : `+${count}`}\n              <ChevronDownIcon size=\"sm\" aria-hidden=\"true\" data-icon=\"inline-end\" />\n            </button>\n          )}\n        </div>\n      </div>\n      {count > 0 && (\n        <ul\n          id={listId}\n          hidden={!open}\n          aria-label={`Started by ${agent.name}`}\n          data-layout={row ? 'row' : 'stack'}\n          className=\"sprout-agent-fanout-children\"\n        >\n          {kids.map(kid => (\n            <Branch key={kid.id} agent={kid} depth={depth + 1} row={false} collapsed={collapsed} onToggle={onToggle} />\n          ))}\n        </ul>\n      )}\n    </li>\n  );\n}\n\nfunction Issues({\n  kind,\n  agents,\n  onRetry,\n  onDismiss,\n  onOpen,\n}: {\n  kind: 'needs-you' | 'failed';\n  agents: AgentFanoutAgent[];\n  onRetry: AgentFanoutProps['onRetry'];\n  onDismiss: AgentFanoutProps['onDismiss'];\n  onOpen: AgentFanoutProps['onOpen'];\n}) {\n  const label = kind === 'failed' ? 'failed' : 'needs you';\n  return (\n    <Popover>\n      <PopoverTrigger data-slot=\"agent-fanout-issues\" data-kind={kind} className=\"sprout-agent-fanout-chip\">\n        <Count value={agents.length} />\n        {` ${label}`}\n        <ChevronDownIcon size=\"sm\" aria-hidden=\"true\" data-icon=\"inline-end\" />\n      </PopoverTrigger>\n      <PopoverContent\n        align=\"end\"\n        sideOffset={8}\n        aria-label={kind === 'failed' ? 'Agents that failed' : 'Agents that need you'}\n        className=\"sprout-agent-fanout-issues\"\n      >\n        <ul className=\"sprout-agent-fanout-issue-list\">\n          {agents.map(agent => (\n            <li key={agent.id} data-kind={kind} className=\"sprout-agent-fanout-issue\">\n              <span aria-hidden=\"true\" className=\"sprout-agent-fanout-issue-mark\">\n                {kind === 'failed' ? <DangerIcon size=\"md\" /> : <ClockIcon size=\"md\" />}\n              </span>\n              <div className=\"sprout-agent-fanout-issue-body\">\n                <p className=\"sprout-agent-fanout-issue-title\">\n                  <span className=\"sprout-agent-fanout-issue-name\">{agent.name}</span>\n                  <span className=\"sprout-agent-fanout-issue-task\">{agent.task}</span>\n                </p>\n                {agent.reason && <p className=\"sprout-agent-fanout-issue-reason\">{agent.reason}</p>}\n                {kind === 'failed' && (onDismiss || onRetry) && (\n                  <div className=\"sprout-agent-fanout-issue-actions\">\n                    {onDismiss && (\n                      <Button variant=\"outline\" size=\"sm\" onClick={() => onDismiss(agent)}>\n                        Dismiss\n                      </Button>\n                    )}\n                    {onRetry && (\n                      <Button size=\"sm\" onClick={() => onRetry(agent)}>\n                        Retry\n                      </Button>\n                    )}\n                  </div>\n                )}\n                {kind === 'needs-you' && onOpen && (\n                  <div className=\"sprout-agent-fanout-issue-actions\">\n                    <Button size=\"sm\" aria-label={`Open ${agent.name}`} onClick={() => onOpen(agent)}>\n                      Open\n                    </Button>\n                  </div>\n                )}\n              </div>\n            </li>\n          ))}\n        </ul>\n      </PopoverContent>\n    </Popover>\n  );\n}\n\ntype Box = { x: number; y: number; w: number; h: number };\ntype Wire = { id: string; d: string; active: boolean };\ntype Dot = { id: string; x: number; y: number; active: boolean };\ntype Geometry = { wires: Wire[]; dots: Dot[]; width: number; height: number };\n\nconst emptyGeometry: Geometry = { wires: [], dots: [], width: 0, height: 0 };\n\ninterface Fit {\n  fits: boolean;\n  card?: number;\n  gap?: number;\n}\n\nconst fullFit: Fit = { fits: true };\n\nfunction boxIn(element: HTMLElement, root: HTMLElement): Box | null {\n  if (element.offsetParent === null) return null;\n  let x = 0;\n  let y = 0;\n  let node: HTMLElement | null = element;\n  while (node && node !== root) {\n    x += node.offsetLeft;\n    y += node.offsetTop;\n    node = node.offsetParent as HTMLElement | null;\n    if (node && node !== root) {\n      x += node.clientLeft;\n      y += node.clientTop;\n    }\n  }\n  return node ? { x, y, w: element.offsetWidth, h: element.offsetHeight } : null;\n}\n\nconst round = (value: number) => Math.round(value * 2) / 2;\n\nfunction busWire(sx: number, sy: number, child: Box) {\n  const cx = round(child.x + child.w / 2);\n  const bus = round(sy + (child.y - sy) / 2);\n  const sign = Math.sign(cx - sx);\n  const r = Math.min(10, Math.abs(cx - sx) / 2, (child.y - sy) / 2);\n  return `M${sx} ${sy} V${bus - r} Q${sx} ${bus} ${sx + sign * r} ${bus} H${cx - sign * r} Q${cx} ${bus} ${cx} ${bus + r} V${child.y}`;\n}\n\nfunction railWire(sx: number, sy: number, child: Box, hook: number) {\n  const y = round(child.y + hook);\n  const r = Math.min(8, child.x - sx, y - sy);\n  return `M${sx} ${sy} V${y - r} Q${sx} ${y} ${sx + r} ${y} H${child.x}`;\n}\n\nfunction measure(root: AgentFanoutAgent, tree: HTMLElement, collapsed: ReadonlySet<string>) {\n  const cards = new Map<string, HTMLElement>();\n  for (const card of tree.querySelectorAll<HTMLElement>('[data-slot=\"agent-fanout-card\"]'))\n    cards.set(card.dataset.agent!, card);\n  const boxes = new Map<string, Box>();\n  for (const [id, card] of cards) {\n    const box = boxIn(card, tree);\n    if (box) boxes.set(id, box);\n  }\n  const wires: Wire[] = [];\n  const dots: Dot[] = [];\n  const walk = (agent: AgentFanoutAgent) => {\n    const kids = agent.agents ?? [];\n    const parent = boxes.get(agent.id);\n    if (!parent || kids.length === 0 || collapsed.has(agent.id)) return;\n    const card = cards.get(agent.id)!;\n    const row = card.nextElementSibling?.getAttribute('data-layout') === 'row';\n    const mark = card.querySelector<HTMLElement>('[data-slot=\"agent-fanout-mark\"]');\n    const markBox = mark && boxIn(mark, card);\n    const sx = round(\n      row || !markBox ? parent.x + parent.w / 2 : parent.x + card.clientLeft + markBox.x + markBox.w / 2,\n    );\n    const sy = round(parent.y + parent.h);\n    const hook = markBox ? card.clientTop + markBox.y + markBox.h / 2 : 24;\n    let drawn = false;\n    let active = false;\n    for (const kid of kids) {\n      const child = boxes.get(kid.id);\n      if (!child) continue;\n      drawn = true;\n      const lit = busy(kid);\n      active ||= lit;\n      wires.push({\n        id: `${agent.id}\\u0000${kid.id}`,\n        d: row ? busWire(sx, sy, child) : railWire(sx, sy, child, hook),\n        active: lit,\n      });\n      walk(kid);\n    }\n    if (drawn) dots.push({ id: agent.id, x: sx, y: sy, active });\n  };\n  walk(root);\n  let width = 0;\n  let height = 0;\n  for (const box of boxes.values()) {\n    width = Math.max(width, Math.ceil(box.x + box.w));\n    height = Math.max(height, Math.ceil(box.y + box.h));\n  }\n  return { cards, boxes, geometry: { wires, dots, width, height } };\n}\n\nconst sameGeometry = (a: Geometry, b: Geometry) =>\n  a.width === b.width &&\n  a.height === b.height &&\n  a.wires.length === b.wires.length &&\n  a.dots.length === b.dots.length &&\n  a.wires.every((wire, index) => {\n    const other = b.wires[index]!;\n    return wire.id === other.id && wire.d === other.d && wire.active === other.active;\n  }) &&\n  a.dots.every((dot, index) => {\n    const other = b.dots[index]!;\n    return dot.x === other.x && dot.y === other.y && dot.active === other.active;\n  });\n\nconst svgNs = 'http://www.w3.org/2000/svg';\nconst easeOut = 'cubic-bezier(0.2, 0.8, 0.2, 1)';\n\nfunction svgNode<K extends keyof SVGElementTagNameMap>(tag: K, attributes: Record<string, string | number>) {\n  const node = document.createElementNS(svgNs, tag);\n  for (const [name, value] of Object.entries(attributes)) node.setAttribute(name, String(value));\n  return node;\n}\n\nfunction leave(\n  layer: HTMLElement,\n  cards: ReadonlyMap<string, HTMLElement>,\n  before: ReadonlyMap<string, Box>,\n  after: ReadonlyMap<string, Box>,\n  from: Geometry,\n  to: Geometry,\n  still: boolean,\n) {\n  const timing: KeyframeAnimationOptions = { duration: still ? 120 : 160, easing: easeOut, fill: 'forwards' };\n  const fade = (node: Element, keyframes: Keyframe[] | PropertyIndexedKeyframes) =>\n    node.animate(keyframes, timing).finished.then(\n      () => node.remove(),\n      () => node.remove(),\n    );\n  let left = false;\n  for (const [id, box] of before) {\n    const card = cards.get(id);\n    if (after.has(id) || !card) continue;\n    const ghost = card.cloneNode(true) as HTMLElement;\n    for (const node of [ghost, ...ghost.querySelectorAll('[data-slot], [id], [aria-controls]')]) {\n      for (const name of ['data-slot', 'data-agent', 'id', 'aria-controls']) node.removeAttribute(name);\n    }\n    ghost.classList.add('sprout-agent-fanout-ghost');\n    ghost.style.cssText = `left:${box.x}px;top:${box.y}px;width:${box.w}px;height:${box.h}px`;\n    layer.append(ghost);\n    fade(ghost, still ? { opacity: [1, 0] } : { opacity: [1, 0], translate: ['0 0', '0 -0.375rem'] });\n    left = true;\n  }\n  const wires = new Set(to.wires.map(wire => wire.id));\n  const dots = new Set(to.dots.map(dot => dot.id));\n  const goneWires = from.wires.filter(wire => !wires.has(wire.id));\n  const goneDots = from.dots.filter(dot => !dots.has(dot.id));\n  if (goneWires.length + goneDots.length > 0) {\n    const svg = svgNode('svg', {\n      class: 'sprout-agent-fanout-wires',\n      width: from.width,\n      height: from.height,\n      viewBox: `0 0 ${from.width} ${from.height}`,\n    });\n    const runs: Promise<Animation>[] = [];\n    for (const wire of goneWires) {\n      const path = svgNode('path', { d: wire.d, pathLength: 1, class: 'sprout-agent-fanout-wire' });\n      if (wire.active) path.dataset.active = '';\n      svg.append(path);\n      runs.push(path.animate(still ? { opacity: [1, 0] } : { strokeDashoffset: [0, 1] }, timing).finished);\n    }\n    for (const dot of goneDots) {\n      const circle = svgNode('circle', { cx: dot.x, cy: dot.y, r: 3.5, class: 'sprout-agent-fanout-dot' });\n      if (dot.active) circle.dataset.active = '';\n      svg.append(circle);\n      runs.push(circle.animate({ opacity: [1, 0] }, timing).finished);\n    }\n    layer.prepend(svg);\n    Promise.allSettled(runs).then(() => svg.remove());\n  }\n  return left;\n}\n\nconst reducedMotion = () => typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nexport function AgentFanout({\n  agent,\n  title = 'Agents',\n  layout = 'auto',\n  defaultCollapsed,\n  onRetry,\n  onDismiss,\n  onOpen,\n  className,\n}: AgentFanoutProps) {\n  const titleId = useId();\n  const treeRef = useRef<HTMLDivElement>(null);\n  const probeRef = useRef<HTMLDivElement>(null);\n  const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(() => new Set(defaultCollapsed));\n  const [fit, setFit] = useState<Fit>(fullFit);\n  const [geometry, setGeometry] = useState<Geometry>(emptyGeometry);\n  const [live, setLive] = useState(false);\n  const places = useRef(new Map<string, Box>());\n  const seen = useRef<ReadonlyMap<string, HTMLElement>>(new Map());\n  const drawn = useRef<Geometry>(emptyGeometry);\n  const lastHeight = useRef(0);\n  const ghostRef = useRef<HTMLDivElement>(null);\n  const latest = useRef({ agent, collapsed, layout });\n  latest.current = { agent, collapsed, layout };\n\n  const all = flatten(agent);\n  const running = all.filter(item => item.status === 'running').length;\n  const needsYou = all.filter(item => item.status === 'needs-you');\n  const failed = all.filter(item => item.status === 'failed');\n  const nest = Math.max(0, levels(agent) - 2);\n  const row = layout === 'tree' || (layout === 'auto' && fit.fits);\n\n  const toggle = (id: string) =>\n    setCollapsed(current => {\n      const next = new Set(current);\n      if (!next.delete(id)) next.add(id);\n      return next;\n    });\n\n  const decide = () => {\n    const { agent, layout } = latest.current;\n    const tree = treeRef.current;\n    const probe = probeRef.current;\n    if (layout === 'list' || !tree || !probe) return;\n    const style = getComputedStyle(probe);\n    const card = parseFloat(style.maxWidth) || probe.offsetWidth;\n    const cardMin = Math.min(card, parseFloat(style.maxHeight) || card);\n    const gap = parseFloat(style.marginRight) || 0;\n    const gapMin = Math.min(gap, parseFloat(style.marginBottom) || gap);\n    const indent = parseFloat(style.paddingLeft) || 0;\n    const overhang = indent * Math.max(0, levels(agent) - 2);\n    const count = agent.agents?.length ?? 0;\n    const gaps = Math.max(0, count - 1);\n    const box = getComputedStyle(tree);\n    const inner = tree.clientWidth - (parseFloat(box.paddingLeft) || 0) - (parseFloat(box.paddingRight) || 0);\n    const room = inner - overhang;\n    let rowGap = Math.max(gap, overhang + 16);\n    let rowCard = card;\n    if (count * rowCard + gaps * rowGap > room) {\n      const tight = Math.max(gapMin, overhang + 16);\n      rowGap = gaps ? Math.max(tight, Math.min(rowGap, (room - count * rowCard) / gaps)) : rowGap;\n      rowCard = Math.min(card, (room - gaps * rowGap) / Math.max(1, count));\n    }\n    const next: Fit = {\n      fits: count === 0 || rowCard >= cardMin,\n      card: Math.floor(Math.max(cardMin, rowCard)),\n      gap: Math.floor(rowGap),\n    };\n    setFit(current =>\n      current.fits === next.fits && current.card === next.card && current.gap === next.gap ? current : next,\n    );\n  };\n\n  const draw = (animate: boolean) => {\n    const tree = treeRef.current;\n    if (!tree) return;\n    const { cards, boxes, geometry: next } = measure(latest.current.agent, tree, latest.current.collapsed);\n    const height = tree.offsetHeight;\n    const still = reducedMotion();\n    if (animate && ghostRef.current) {\n      const left = leave(ghostRef.current, seen.current, places.current, boxes, drawn.current, next, still);\n      if (left && !still && height < lastHeight.current)\n        tree.animate({ height: [`${lastHeight.current}px`, `${height}px`] }, { duration: 160, easing: easeOut });\n    }\n    if (animate && !still) {\n      for (const [id, box] of boxes) {\n        const before = places.current.get(id);\n        if (!before) continue;\n        const dx = before.x - box.x;\n        const dy = before.y - box.y;\n        if (Math.abs(dx) < 0.5 && Math.abs(dy) < 0.5) continue;\n        tree\n          .querySelector<HTMLElement>(`[data-slot=\"agent-fanout-card\"][data-agent=\"${CSS.escape(id)}\"]`)\n          ?.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }], {\n            duration: 280,\n            easing: 'cubic-bezier(0.4, 0, 0.2, 1)',\n          });\n      }\n    }\n    places.current = boxes;\n    seen.current = cards;\n    drawn.current = next;\n    lastHeight.current = height;\n    setGeometry(current => (sameGeometry(current, next) ? current : next));\n  };\n\n  useLayoutEffect(() => {\n    decide();\n    draw(live);\n  });\n\n  useEffect(() => {\n    const tree = treeRef.current;\n    if (!tree || typeof ResizeObserver !== 'function') return;\n    const observer = new ResizeObserver(() => {\n      decide();\n      draw(false);\n    });\n    observer.observe(tree);\n    for (const card of tree.querySelectorAll('[data-slot=\"agent-fanout-card\"]')) observer.observe(card);\n    return () => observer.disconnect();\n  });\n\n  useEffect(() => {\n    if (live || geometry === emptyGeometry) return;\n    const frame = requestAnimationFrame(() => setLive(true));\n    return () => cancelAnimationFrame(frame);\n  }, [geometry, live]);\n\n  const summary = [\n    plural(all.length, 'agent', 'agents'),\n    running > 0 && `${running} running`,\n    needsYou.length > 0 && `${needsYou.length} ${needsYou.length === 1 ? 'needs' : 'need'} you`,\n    failed.length > 0 && `${failed.length} failed`,\n  ]\n    .filter(Boolean)\n    .join(', ');\n\n  return (\n    <section\n      data-slot=\"agent-fanout\"\n      data-layout={row ? 'tree' : 'list'}\n      data-live={live || undefined}\n      aria-labelledby={titleId}\n      className={cn('sprout-agent-fanout', className)}\n    >\n      <header className=\"sprout-agent-fanout-header\">\n        <h2 id={titleId} className=\"sprout-agent-fanout-title\">\n          <SparkleIcon size=\"md\" aria-hidden=\"true\" className=\"sprout-agent-fanout-title-icon\" />\n          {title}\n        </h2>\n        <div className=\"sprout-agent-fanout-summary\">\n          <span aria-hidden=\"true\" className=\"sprout-agent-fanout-stat\">\n            <Count value={all.length} /> {all.length === 1 ? 'agent' : 'agents'}\n          </span>\n          {running > 0 && (\n            <span aria-hidden=\"true\" data-tone=\"info\" className=\"sprout-agent-fanout-stat\">\n              <Count value={running} /> running\n            </span>\n          )}\n          {needsYou.length > 0 && (\n            <Issues kind=\"needs-you\" agents={needsYou} onRetry={onRetry} onDismiss={onDismiss} onOpen={onOpen} />\n          )}\n          {failed.length > 0 && (\n            <Issues kind=\"failed\" agents={failed} onRetry={onRetry} onDismiss={onDismiss} onOpen={onOpen} />\n          )}\n          <span role=\"status\" className=\"sprout-agent-fanout-sr-only\">\n            {summary}\n          </span>\n        </div>\n      </header>\n      <div\n        ref={treeRef}\n        data-slot=\"agent-fanout-tree\"\n        className=\"sprout-agent-fanout-tree\"\n        style={\n          {\n            '--sprout-agent-fanout-nest': nest,\n            '--sprout-agent-fanout-fit-card': fit.card ? `${fit.card}px` : undefined,\n            '--sprout-agent-fanout-fit-gap': fit.gap ? `${fit.gap}px` : undefined,\n          } as CSSProperties\n        }\n      >\n        <div ref={probeRef} aria-hidden=\"true\" className=\"sprout-agent-fanout-probe\" />\n        <ul aria-label=\"Agent tree\" className=\"sprout-agent-fanout-root\">\n          <Branch agent={agent} depth={0} row={row} collapsed={collapsed} onToggle={toggle} />\n        </ul>\n        {geometry.width > 0 && (\n          <svg\n            aria-hidden=\"true\"\n            data-slot=\"agent-fanout-wires\"\n            className=\"sprout-agent-fanout-wires\"\n            width={geometry.width}\n            height={geometry.height}\n            viewBox={`0 0 ${geometry.width} ${geometry.height}`}\n          >\n            {geometry.wires.map(wire => (\n              <path\n                key={wire.id}\n                d={wire.d}\n                pathLength={1}\n                data-active={wire.active || undefined}\n                className=\"sprout-agent-fanout-wire\"\n              />\n            ))}\n            {geometry.dots.map(dot => (\n              <circle\n                key={dot.id}\n                cx={dot.x}\n                cy={dot.y}\n                r={3.5}\n                data-active={dot.active || undefined}\n                className=\"sprout-agent-fanout-dot\"\n              />\n            ))}\n          </svg>\n        )}\n        <div ref={ghostRef} aria-hidden=\"true\" inert className=\"sprout-agent-fanout-ghosts\" />\n      </div>\n    </section>\n  );\n}\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/check-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/check-icon.tsx",
      "content": "import { Tick02Icon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const CheckIcon = /* @__PURE__ */ createIcon(glyph, 'CheckIcon');\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/chevron-down-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/chevron-down-icon.tsx",
      "content": "import { ArrowDown01Icon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const ChevronDownIcon = /* @__PURE__ */ createIcon(glyph, 'ChevronDownIcon');\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/clock-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/clock-icon.tsx",
      "content": "import { Clock01Icon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const ClockIcon = /* @__PURE__ */ createIcon(glyph, 'ClockIcon');\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/create-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/create-icon.tsx",
      "content": "import { HugeiconsIcon, type IconSvgElement } from '@hugeicons/react';\nimport type { ReactElement, Ref, SVGProps } from 'react';\n\nexport const iconSizes = {\n  xs: 12,\n  sm: 14,\n  md: 16,\n  lg: 18,\n  xl: 20,\n  '2xl': 24,\n} as const;\n\nexport type IconSize = keyof typeof iconSizes;\n\nexport const iconStrokeWidth = 1.5;\n\nexport type IconProps = Omit<SVGProps<SVGSVGElement>, 'ref'> & {\n  size?: IconSize | number;\n  ref?: Ref<SVGSVGElement>;\n};\n\nexport type IconComponent = (props: IconProps) => ReactElement;\n\nexport function createIcon(glyph: IconSvgElement, name: string): IconComponent {\n  const Icon = ({ size = '2xl', strokeWidth = iconStrokeWidth, ...props }: IconProps) => (\n    <HugeiconsIcon\n      icon={glyph}\n      size={typeof size === 'number' ? size : iconSizes[size]}\n      strokeWidth={Number(strokeWidth)}\n      {...props}\n    />\n  );\n  Icon.displayName = name;\n  return Icon;\n}\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/danger-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/danger-icon.tsx",
      "content": "import { Alert01Icon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const DangerIcon = /* @__PURE__ */ createIcon(glyph, 'DangerIcon');\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/hourglass-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/hourglass-icon.tsx",
      "content": "import { HourglassIcon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const HourglassIcon = /* @__PURE__ */ createIcon(glyph, 'HourglassIcon');\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/sparkle-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/sparkle-icon.tsx",
      "content": "import { SparkleIcon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const SparkleIcon = /* @__PURE__ */ createIcon(glyph, 'SparkleIcon');\n"
    },
    {
      "path": "registry/sprout/lib/sprout/icons/stop-circle-icon.tsx",
      "type": "registry:lib",
      "target": "lib/sprout/icons/stop-circle-icon.tsx",
      "content": "import { StopCircleIcon as glyph } from '@hugeicons/core-free-icons';\nimport { createIcon } from '@/lib/sprout/icons/create-icon';\n\nexport const StopCircleIcon = /* @__PURE__ */ createIcon(glyph, 'StopCircleIcon');\n"
    }
  ],
  "docs": "Docs and examples: https://sprout.tulipfarm.ai/components/agent-fanout/",
  "meta": {
    "source": "packages/sprout/src/components/agent-fanout.tsx"
  }
}
